╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
279 var cookie_buf: [256]u8 = undefined; 280 const cookie = try std.fmt.bufPrint(&cookie_buf, session_cookie_fmt, .{token}); 281 try request.respond("", .{ 282 .status = .see_other, 283 .extra_headers = &.{ 284 .{ .name = "location", .value = success_location }, 285 .{ .name = "set-cookie", .value = cookie }, 286 }, 287 }); 288 }, 289 .unknown_user => { 290 try request.respond("", .{ 291 .status = .see_other, 292 .extra_headers = &.{ 293 .{ .name = "location", .value = failure_location }, 294 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=unknown_user; Path=/; HttpOnly; SameSite=Strict" }, 295 }, 296 }); 297 }, 298 .wrong_password => { 299 try request.respond("", .{ 300 .status = .see_other, 301 .extra_headers = &.{ 302 .{ .name = "location", .value = failure_location }, 303 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=wrong_password; Path=/; HttpOnly; SameSite=Strict" }, 304 }, 305 }); 306 }, 307 } 308 } 309 310 fn handleLogout(request: *std.http.Server.Request, base: []const u8, session_store: SessionStore) !void { 311 // revoke the session server-side so the cookie is dead for anyone holding 312 // a copy, not just this browser. 313 if (getCookieValue(request, cookie_name)) |token| session_store.remove(token); 314 // return to the page the logout came from (base, or "/" at the root). 315 const location: []const u8 = if (base.len == 0) "/" else base; 316 // close the connection instead of keeping it alive: we don't read the 317 // request body, and respond()'s keep-alive path would otherwise try to 318 // discard it — which asserts on a bodyless POST that carries no 319 // content-length, and would block on one with no framing at all. a logout 320 // is just a redirect, so the browser reconnects for the follow-up GET. 321 try request.respond("", .{ 322 .status = .see_other, 323 .keep_alive = false, 324 .extra_headers = &.{ 325 .{ .name = "location", .value = location }, 326 .{ .name = "set-cookie", .value = cookie_name ++ "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0" }, 327 }, 328 }); 329 } 330 331 fn handleAnsi( 332 io: std.Io, 333 request: *std.http.Server.Request, 334 allocator: std.mem.Allocator, 335 base: []const u8, 336 admin_repo_path: []const u8, 337 session_store: SessionStore, 338 ) !void { 339 // the toggle re-emits the user's own event, so it takes a logged-in user 340 var user_id: [evt.event_id_size]u8 = undefined; 341 const token = getCookieValue(request, cookie_name) orelse return respondLoginRequired(request); 342 if (!session_store.lookup(token, &user_id)) return respondLoginRequired(request); 343 344 { 345 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 346 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 347 defer repo.deinit(io, allocator); 348 349 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, &repo, &user_id); 350 } 351 352 // return to the settings tab the toggle came from so the change is visible. 353 const location = try std.fmt.allocPrint(allocator, "{s}/settings", .{base}); 354 defer allocator.free(location); 355 356 // like logout, this is a bodyless POST, so close the connection rather than 357 // letting the keep-alive path try to discard a body that isn't framed. 358 try request.respond("", .{ 359 .status = .see_other, 360 .keep_alive = false, 361 .extra_headers = &.{ 362 .{ .name = "location", .value = location }, 363 }, 364 }); 365 } 366 367 // the author for an event created by this request, or null when the request 368 // may not create one. local mode has no accounts, so it authors anonymously. 369 fn eventAuthorEmail( 370 io: std.Io, 371 allocator: std.mem.Allocator, 372 arena: *std.heap.ArenaAllocator, 373 request: *std.http.Server.Request, 374 host: Host, 375 ) !?[]const u8 { 376 const remote = switch (host) { 377 .remote => |remote| remote, 378 .local => return "user@haxy", // TODO: try the repo's git config user.email first 379 }; 380 const token = getCookieValue(request, cookie_name) orelse return null; 381 var user_id: [evt.event_id_size]u8 = undefined; 382 if (!remote.session_store.lookup(token, &user_id)) return null; 383 384 var repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 385 defer repo.deinit(io, allocator); 386 const moment = try evt.currentMoment(evt.admin_repo_opts, &repo); 387 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, &user_id)) orelse return null; 388 return user.event.email; 389 } 390 391 // refuse a write from a request with no logged-in user. the body goes unread, 392 // so the connection closes. 393 fn respondLoginRequired(request: *std.http.Server.Request) !void { 394 try request.respond("log in to make changes", .{ 395 .status = .forbidden, 396 .keep_alive = false, 397 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 398 }); 399 } 400 401 // create an issue in the repo the form's page names (base is 402 // "/repo/<owner>/<name>", or "" in local mode) and redirect to it 403 fn handleIssue( 404 io: std.Io, 405 request: *std.http.Server.Request, 406 allocator: std.mem.Allocator, 407 base: []const u8, 408 host: Host, 409 ) !void { 410 var author_arena = std.heap.ArenaAllocator.init(allocator); 411 defer author_arena.deinit(); 412 const author_email = (try eventAuthorEmail(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 413 414 var body_buf: [256]u8 = undefined; 415 const reader = request.readerExpectNone(&body_buf); 416 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 417 defer allocator.free(body); 418 419 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 420 defer allocator.free(title); 421 const tags = (try parseFormField(allocator, body, "tags")) orelse try allocator.dupe(u8, ""); 422 defer allocator.free(tags); 423 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 424 defer allocator.free(description_crlf); 425 // form submission normalizes textarea line breaks to CRLF; store plain 426 // newlines so the text renders the same on every host 427 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 428 defer allocator.free(description); 429 430 if (!evt.Issue.fieldsValid(title, tags)) { 431 const form_location = try std.fmt.allocPrint(allocator, "{s}/issues/new", .{base}); 432 defer allocator.free(form_location); 433 try request.respond("", .{ 434 .status = .see_other, 435 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 436 }); 437 return; 438 } 439 440 var id_bytes: [evt.event_id_size]u8 = undefined; 441 io.random(&id_bytes); 442 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 443 444 const event = evt.EventWithId{ 445 .id = event_id_hex, 446 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 447 .author_email = author_email, 448 .event = .{ .issue = .{ 449 .title = title, 450 .description = description, 451 .tags = tags, 452 } }, 453 }; 454 455 const not_found = "repo not found"; 456 switch (host) { 457 .remote => |remote| { 458 const repo_prefix = "/repo/"; 459 if (!std.mem.startsWith(u8, base, repo_prefix)) { 460 try request.respond(not_found, .{ 461 .status = .not_found, 462 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 463 }); 464 return; 465 } 466 467 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 468 defer allocator.free(repos_dir); 469 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, repos_dir, remote.admin_repo_path, base[repo_prefix.len..], false)) { 470 .ok => |p| p, 471 .invalid, .not_found => { 472 try request.respond(not_found, .{ 473 .status = .not_found, 474 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 475 }); 476 return; 477 }, 478 }; 479 defer allocator.free(repo_path); 480 481 var repo = try rp.Repo(.xit, .{}).open(io, allocator, .{ .path = repo_path }); 482 defer repo.deinit(io, allocator); 483 try evt.consume(.xit, .{}, io, allocator, &repo, evt.events_ref, &[_]evt.EventWithId{event}); 484 }, 485 .local => |src| { 486 // the local form posts to "/issue", so base is empty 487 if (base.len != 0) { 488 try request.respond(not_found, .{ 489 .status = .not_found, 490 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 491 }); 492 return; 493 } 494 switch (src.repo_kind) { 495 inline else => |repo_kind| { 496 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, .{ .path = src.path }); 497 defer any_repo.deinit(io, allocator); 498 switch (any_repo) { 499 inline else => |*repo| try evt.consume(repo_kind, repo.self_repo_opts, io, allocator, repo, evt.events_ref, &[_]evt.EventWithId{event}), 500 } 501 }, 502 } 503 }, 504 } 505 506 const location = try std.fmt.allocPrint(allocator, "{s}/issue:{s}", .{ base, &event_id_hex }); 507 defer allocator.free(location); 508 try request.respond("", .{ 509 .status = .see_other, 510 .extra_headers = &.{.{ .name = "location", .value = location }}, 511 }); 512 } 513 514 const CommentBaseParts = struct { 515 repo_base: []const u8, 516 thread_id: [evt.event_id_size]u8, 517 comment_id: ?[evt.event_id_size]u8, 518 }; 519 520 fn commentBaseParts(base: []const u8) ?CommentBaseParts { 521 const issue_infix = "/issue:"; 522 const comment_infix = "/comment:"; 523 const id_len = evt.event_id_size * 2; 524 const issue_at = std.mem.lastIndexOf(u8, base, issue_infix) orelse return null; 525 const tail = base[issue_at + issue_infix.len ..]; 526 if (tail.len < id_len) return null; 527 528 var thread_id: [evt.event_id_size]u8 = undefined; 529 _ = std.fmt.hexToBytes(&thread_id, tail[0..id_len]) catch return null; 530 var comment_id: ?[evt.event_id_size]u8 = null; 531 if (tail.len != id_len) { 532 if (tail.len != id_len + comment_infix.len + id_len) return null; 533 if (!std.mem.eql(u8, tail[id_len .. id_len + comment_infix.len], comment_infix)) return null; 534 var id: [evt.event_id_size]u8 = undefined; 535 _ = std.fmt.hexToBytes(&id, tail[id_len + comment_infix.len ..]) catch return null; 536 comment_id = id; 537 } 538 return .{ .repo_base = base[0..issue_at], .thread_id = thread_id, .comment_id = comment_id }; 539 } 540 541 // create a reply from an issue or comment /new form, then redirect to its 542 // permalink. the rest of the url identifies the thread and parent. 543 fn handleComment( 544 io: std.Io, 545 request: *std.http.Server.Request, 546 allocator: std.mem.Allocator, 547 base: []const u8, 548 host: Host, 549 ) !void { 550 const not_found = "comment parent not found"; 551 const parts = commentBaseParts(base) orelse { 552 try request.respond(not_found, .{ 553 .status = .not_found, 554 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 555 }); 556 return; 557 }; 558 559 var author_arena = std.heap.ArenaAllocator.init(allocator); 560 defer author_arena.deinit(); 561 const author_email = (try eventAuthorEmail(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 562 563 var body_buf: [256]u8 = undefined; 564 const reader = request.readerExpectNone(&body_buf); 565 const posted = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 566 defer allocator.free(posted); 567 const body_crlf = (try parseFormField(allocator, posted, "body")) orelse try allocator.dupe(u8, ""); 568 defer allocator.free(body_crlf); 569 const body = try std.mem.replaceOwned(u8, allocator, body_crlf, "\r\n", "\n"); 570 defer allocator.free(body); 571 572 if (!evt.Comment.fieldsValid(body)) { 573 const form_location = try std.fmt.allocPrint(allocator, "{s}/new", .{base}); 574 defer allocator.free(form_location); 575 try request.respond("", .{ 576 .status = .see_other, 577 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 578 }); 579 return; 580 } 581 582 const thread_id_hex = std.fmt.bytesToHex(parts.thread_id, .lower); 583 const parent_id_hex = std.fmt.bytesToHex(parts.comment_id orelse parts.thread_id, .lower); 584 585 var event_id_hex: [evt.event_id_size * 2]u8 = undefined; 586 switch (host) { 587 .remote => |remote| { 588 const repo_prefix = "/repo/"; 589 if (!std.mem.startsWith(u8, parts.repo_base, repo_prefix)) { 590 try request.respond(not_found, .{ 591 .status = .not_found, 592 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 593 }); 594 return; 595 } 596 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 597 defer allocator.free(repos_dir); 598 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, repos_dir, remote.admin_repo_path, parts.repo_base[repo_prefix.len..], false)) { 599 .ok => |p| p, 600 .invalid, .not_found => { 601 try request.respond(not_found, .{ 602 .status = .not_found, 603 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 604 }); 605 return; 606 }, 607 }; 608 defer allocator.free(repo_path); 609 610 var repo = try rp.Repo(.xit, .{}).open(io, allocator, .{ .path = repo_path }); 611 defer repo.deinit(io, allocator); 612 event_id_hex = try evt.Comment.create(.xit, .{}, io, allocator, &repo, &thread_id_hex, &parent_id_hex, body, author_email); 613 }, 614 .local => |src| { 615 if (parts.repo_base.len != 0) { 616 try request.respond(not_found, .{ 617 .status = .not_found, 618 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 619 }); 620 return; 621 } 622 switch (src.repo_kind) { 623 inline else => |repo_kind| { 624 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, .{ .path = src.path }); 625 defer any_repo.deinit(io, allocator); 626 switch (any_repo) { 627 inline else => |*repo| event_id_hex = try evt.Comment.create(repo_kind, repo.self_repo_opts, io, allocator, repo, &thread_id_hex, &parent_id_hex, body, author_email), 628 } 629 }, 630 } 631 }, 632 } 633 634 const location = try std.fmt.allocPrint(allocator, "{s}/issue:{s}/comment:{s}", .{ parts.repo_base, &thread_id_hex, &event_id_hex }); 635 defer allocator.free(location); 636 try request.respond("", .{ 637 .status = .see_other, 638 .extra_headers = &.{.{ .name = "location", .value = location }}, 639 }); 640 } 641 642 // re-emit the comment `parts` names with a new body, in the repo the host 643 // resolves the base to. 644 fn updateComment( 645 io: std.Io, 646 allocator: std.mem.Allocator, 647 host: Host, 648 parts: CommentBaseParts, 649 body: []const u8, 650 author_email: []const u8, 651 ) !void { 652 const comment_id = parts.comment_id orelse return error.NotFound; 653 const thread_id = std.fmt.bytesToHex(parts.thread_id, .lower); 654 switch (host) { 655 .remote => |remote| { 656 const repo_prefix = "/repo/"; 657 if (!std.mem.startsWith(u8, parts.repo_base, repo_prefix)) return error.NotFound; 658 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 659 defer allocator.free(repos_dir); 660 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, repos_dir, remote.admin_repo_path, parts.repo_base[repo_prefix.len..], false)) { 661 .ok => |p| p, 662 .invalid, .not_found => return error.NotFound, 663 }; 664 defer allocator.free(repo_path); 665 666 var repo = try rp.Repo(.xit, .{}).open(io, allocator, .{ .path = repo_path }); 667 defer repo.deinit(io, allocator); 668 try evt.Comment.update(.xit, .{}, io, allocator, &repo, &thread_id, &comment_id, body, author_email); 669 }, 670 .local => |src| { 671 if (parts.repo_base.len != 0) return error.NotFound; 672 switch (src.repo_kind) { 673 inline else => |repo_kind| { 674 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, .{ .path = src.path }); 675 defer any_repo.deinit(io, allocator); 676 switch (any_repo) { 677 inline else => |*repo| try evt.Comment.update(repo_kind, repo.self_repo_opts, io, allocator, repo, &thread_id, &comment_id, body, author_email), 678 } 679 }, 680 } 681 }, 682 } 683 } 684 685 // edit actions share a suffix; the base identifies whether the form names an 686 // issue or comment. 687 fn handleEdit( 688 io: std.Io, 689 request: *std.http.Server.Request, 690 allocator: std.mem.Allocator, 691 base: []const u8, 692 host: Host, 693 ) !void { 694 if (commentBaseParts(base)) |parts| { 695 if (parts.comment_id != null) return handleCommentEdit(io, request, allocator, base, host, parts); 696 } 697 return handleIssueEdit(io, request, allocator, base, host); 698 } 699 700 // replace the body of the comment the url names, then redirect to its 701 // permalink. 702 fn handleCommentEdit( 703 io: std.Io, 704 request: *std.http.Server.Request, 705 allocator: std.mem.Allocator, 706 base: []const u8, 707 host: Host, 708 parts: CommentBaseParts, 709 ) !void { 710 var author_arena = std.heap.ArenaAllocator.init(allocator); 711 defer author_arena.deinit(); 712 const author_email = (try eventAuthorEmail(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 713 714 var body_buf: [256]u8 = undefined; 715 const reader = request.readerExpectNone(&body_buf); 716 const posted = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 717 defer allocator.free(posted); 718 const body_crlf = (try parseFormField(allocator, posted, "body")) orelse try allocator.dupe(u8, ""); 719 defer allocator.free(body_crlf); 720 const body = try std.mem.replaceOwned(u8, allocator, body_crlf, "\r\n", "\n"); 721 defer allocator.free(body); 722 723 if (!evt.Comment.fieldsValid(body)) { 724 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 725 defer allocator.free(form_location); 726 try request.respond("", .{ 727 .status = .see_other, 728 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 729 }); 730 return; 731 } 732 733 const not_found = "comment not found"; 734 updateComment(io, allocator, host, parts, body, author_email) catch |err| switch (err) { 735 error.NotFound => { 736 try request.respond(not_found, .{ 737 .status = .not_found, 738 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 739 }); 740 return; 741 }, 742 else => |e| return e, 743 }; 744 745 try request.respond("", .{ 746 .status = .see_other, 747 .extra_headers = &.{.{ .name = "location", .value = base }}, 748 }); 749 } 750 751 // split an issue url ("/repo/<owner>/<name>/issue:<id>", identity elided in 752 // local mode) into what precedes "/issue:" and the decoded id, null when it 753 // isn't one. the repo base is validated per host in updateIssue. 754 const IssueBaseParts = struct { repo_base: []const u8, id_bytes: [evt.event_id_size]u8 }; 755 fn issueBaseParts(base: []const u8) ?IssueBaseParts { 756 const issues_infix = "/issue:"; 757 const id_len = evt.event_id_size * 2; 758 if (base.len < issues_infix.len + id_len) return null; 759 var id_bytes: [evt.event_id_size]u8 = undefined; 760 _ = std.fmt.hexToBytes(&id_bytes, base[base.len - id_len ..]) catch return null; 761 const head = base[0 .. base.len - id_len]; 762 if (!std.mem.endsWith(u8, head, issues_infix)) return null; 763 return .{ .repo_base = head[0 .. head.len - issues_infix.len], .id_bytes = id_bytes }; 764 } 765 766 // re-emit the issue `parts` names with `update` applied, in the repo the 767 // host resolves the base to. error.NotFound when the base names no repo or 768 // the id no issue. 769 fn updateIssue( 770 io: std.Io, 771 allocator: std.mem.Allocator, 772 host: Host, 773 parts: IssueBaseParts, 774 update: evt.Issue.Update, 775 author_email: []const u8, 776 ) !void { 777 switch (host) { 778 .remote => |remote| { 779 const repo_prefix = "/repo/"; 780 if (!std.mem.startsWith(u8, parts.repo_base, repo_prefix)) return error.NotFound; 781 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 782 defer allocator.free(repos_dir); 783 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, repos_dir, remote.admin_repo_path, parts.repo_base[repo_prefix.len..], false)) { 784 .ok => |p| p, 785 .invalid, .not_found => return error.NotFound, 786 }; 787 defer allocator.free(repo_path); 788 789 var repo = try rp.Repo(.xit, .{}).open(io, allocator, .{ .path = repo_path }); 790 defer repo.deinit(io, allocator); 791 try evt.Issue.update(.xit, .{}, io, allocator, &repo, &parts.id_bytes, update, author_email); 792 }, 793 .local => |src| { 794 // the local forms post to "/issue:<id>/...", so the repo base 795 // is empty 796 if (parts.repo_base.len != 0) return error.NotFound; 797 switch (src.repo_kind) { 798 inline else => |repo_kind| { 799 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, .{ .path = src.path }); 800 defer any_repo.deinit(io, allocator); 801 switch (any_repo) { 802 inline else => |*repo| try evt.Issue.update(repo_kind, repo.self_repo_opts, io, allocator, repo, &parts.id_bytes, update, author_email), 803 } 804 }, 805 } 806 }, 807 } 808 } 809 810 // set the status of the issue the url names (base is 811 // "/repo/<owner>/<name>/issue:<id>", identity elided in local mode) by 812 // re-emitting its event, then redirect back to it 813 fn handleIssueStatus( 814 io: std.Io, 815 request: *std.http.Server.Request, 816 allocator: std.mem.Allocator, 817 base: []const u8, 818 host: Host, 819 status: evt.Issue.Status, 820 ) !void { 821 const not_found = "issue not found"; 822 const parts = issueBaseParts(base) orelse { 823 try request.respond(not_found, .{ 824 .status = .not_found, 825 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 826 }); 827 return; 828 }; 829 830 var author_arena = std.heap.ArenaAllocator.init(allocator); 831 defer author_arena.deinit(); 832 const author_email = (try eventAuthorEmail(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 833 834 updateIssue(io, allocator, host, parts, .{ .status = status }, author_email) catch |err| switch (err) { 835 error.NotFound => { 836 try request.respond(not_found, .{ 837 .status = .not_found, 838 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 839 }); 840 return; 841 }, 842 else => |e| return e, 843 }; 844 845 // like logout, this is a bodyless POST, so close the connection rather than 846 // letting the keep-alive path try to discard a body that isn't framed. 847 try request.respond("", .{ 848 .status = .see_other, 849 .keep_alive = false, 850 .extra_headers = &.{.{ .name = "location", .value = base }}, 851 }); 852 } 853 854 // replace the title/tags/description of the issue the url names (base is 855 // "/repo/<owner>/<name>/issue:<id>", identity elided in local mode; the 856 // form posts to "<base>/edit") by re-emitting its event with its status 857 // preserved, then redirect back to it 858 fn handleIssueEdit( 859 io: std.Io, 860 request: *std.http.Server.Request, 861 allocator: std.mem.Allocator, 862 base: []const u8, 863 host: Host, 864 ) !void { 865 var author_arena = std.heap.ArenaAllocator.init(allocator); 866 defer author_arena.deinit(); 867 const author_email = (try eventAuthorEmail(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 868 869 var body_buf: [256]u8 = undefined; 870 const reader = request.readerExpectNone(&body_buf); 871 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 872 defer allocator.free(body); 873 874 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 875 defer allocator.free(title); 876 const tags = (try parseFormField(allocator, body, "tags")) orelse try allocator.dupe(u8, ""); 877 defer allocator.free(tags); 878 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 879 defer allocator.free(description_crlf); 880 // form submission normalizes textarea line breaks to CRLF; store plain 881 // newlines so the text renders the same on every host 882 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 883 defer allocator.free(description); 884 885 // invalid fields send the user back to the edit form 886 if (!evt.Issue.fieldsValid(title, tags)) { 887 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 888 defer allocator.free(form_location); 889 try request.respond("", .{ 890 .status = .see_other, 891 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 892 }); 893 return; 894 } 895 896 const not_found = "issue not found"; 897 const parts = issueBaseParts(base) orelse { 898 try request.respond(not_found, .{ 899 .status = .not_found, 900 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 901 }); 902 return; 903 }; 904 905 updateIssue(io, allocator, host, parts, .{ .fields = .{ 906 .title = title, 907 .tags = tags, 908 .description = description, 909 } }, author_email) catch |err| switch (err) { 910 error.NotFound => { 911 try request.respond(not_found, .{ 912 .status = .not_found, 913 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 914 }); 915 return; 916 }, 917 else => |e| return e, 918 }; 919 920 try request.respond("", .{ 921 .status = .see_other, 922 .extra_headers = &.{.{ .name = "location", .value = base }}, 923 }); 924 } 925 926 // resolve the conflict of the issue the url names (base is 927 // "/repo/<owner>/<name>/issue:<id>", identity elided in local mode; the 928 // form posts to "<base>/resolve") 929 fn handleIssueResolve( 930 io: std.Io, 931 request: *std.http.Server.Request, 932 allocator: std.mem.Allocator, 933 base: []const u8, 934 host: Host, 935 ) !void { 936 var author_arena = std.heap.ArenaAllocator.init(allocator); 937 defer author_arena.deinit(); 938 const author_email = (try eventAuthorEmail(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 939 940 var body_buf: [256]u8 = undefined; 941 const reader = request.readerExpectNone(&body_buf); 942 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 943 defer allocator.free(body); 944 945 var field_arena = std.heap.ArenaAllocator.init(allocator); 946 defer field_arena.deinit(); 947 const aa = field_arena.allocator(); 948 const title = try parseFormField(aa, body, "title"); 949 const tags = try parseFormField(aa, body, "tags"); 950 951 // the hunk inputs post as d0, d1, ...; form submission normalizes their 952 // textarea line breaks to CRLF 953 var hunks: std.ArrayList([]const u8) = .empty; 954 var hunk_index: usize = 0; 955 while (true) : (hunk_index += 1) { 956 const name = try std.fmt.allocPrint(aa, "d{d}", .{hunk_index}); 957 const posted = (try parseFormField(aa, body, name)) orelse break; 958 try hunks.append(aa, try std.mem.replaceOwned(u8, aa, posted, "\r\n", "\n")); 959 } 960 961 const not_found = "issue not found"; 962 const parts = issueBaseParts(base) orelse { 963 try request.respond(not_found, .{ 964 .status = .not_found, 965 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 966 }); 967 return; 968 }; 969 970 updateIssue(io, allocator, host, parts, .{ .resolve = .{ 971 .title = title, 972 .tags = tags, 973 .hunks = hunks.items, 974 } }, author_email) catch |err| switch (err) { 975 error.NotFound => { 976 try request.respond(not_found, .{ 977 .status = .not_found, 978 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 979 }); 980 return; 981 }, 982 // invalid fields send the user back to the resolve form 983 error.InvalidFields => { 984 const form_location = try std.fmt.allocPrint(allocator, "{s}/resolve", .{base}); 985 defer allocator.free(form_location); 986 try request.respond("", .{ 987 .status = .see_other, 988 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 989 }); 990 return; 991 }, 992 else => |e| return e, 993 }; 994 995 try request.respond("", .{ 996 .status = .see_other, 997 .extra_headers = &.{.{ .name = "location", .value = base }}, 998 }); 999 } 1000 1001 fn renderIndexHtml( 1002 io: std.Io, 1003 allocator: std.mem.Allocator, 1004 host: Host, 1005 session_data: ui.Session.Data, 1006 ) ![]const u8 { 1007 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 1008 1009 var page_arena = std.heap.ArenaAllocator.init(allocator); 1010 defer page_arena.deinit(); 1011 1012 // the remote admin repo must outlive the page build, since the session's 1013 // moment reads from it. 1014 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 1015 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 1016 1017 var session = switch (host) { 1018 .remote => |remote| blk: { 1019 // open the admin repo to read live user/repo data. 1020 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 1021 const repo = if (repo_maybe) |*repo| repo else unreachable; 1022 var session = try ui.Session.init(&page_arena, repo, session_data); 1023 // give the page builders filesystem access to the on-disk repos (a 1024 // sibling "repos" dir next to the admin repo) so the Repo page can 1025 // read its files. 1026 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 1027 break :blk session; 1028 }, 1029 .local => |local| ui.Session{ 1030 .data = session_data, 1031 .arena = &page_arena, 1032 .page_arena = &page_arena, 1033 .local = local, 1034 }, 1035 }; 1036 session.io = io; 1037 1038 const snapshot: ui.Snapshot = .{ 1039 .page = try ui.Page.init(session.page_arena, &session, session.data.current_page), 1040 .session = session.data, 1041 }; 1042 var root = try ui.initRoot(allocator, &snapshot.page, &session); 1043 defer root.deinit(allocator); 1044 1045 const content = try generateHtml(allocator, &root); 1046 defer allocator.free(content); 1047 const overlay = try generateOverlay(allocator, &root, &session); 1048 defer allocator.free(overlay); 1049 1050 // serialize the snapshot so the wasm side can parse it back without making 1051 // a second request. it's embedded raw in a <script type="application/json"> 1052 // block, whose content is raw text terminated only by "</script". in json, 1053 // '<' appears solely inside string values, so escaping every '<' (and '>' 1054 // for good measure) to its \uXXXX form yields equivalent json that can't 1055 // break out of the tag. 1056 var json: std.Io.Writer.Allocating = .init(allocator); 1057 defer json.deinit(); 1058 try std.json.Stringify.value(snapshot, .{}, &json.writer); 1059 1060 var json_escaped: std.ArrayList(u8) = .empty; 1061 defer json_escaped.deinit(allocator); 1062 for (json.written()) |c| switch (c) { 1063 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 1064 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 1065 else => try json_escaped.append(allocator, c), 1066 }; 1067 1068 var out: std.ArrayList(u8) = .empty; 1069 errdefer out.deinit(allocator); 1070 { 1071 var cursor: usize = 0; 1072 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 1073 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 1074 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 1075 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 1076 }) |sub| { 1077 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 1078 try out.appendSlice(allocator, template[cursor..idx]); 1079 try out.appendSlice(allocator, sub.replacement); 1080 cursor = idx + sub.needle.len; 1081 } 1082 try out.appendSlice(allocator, template[cursor..]); 1083 } 1084 return try out.toOwnedSlice(allocator); 1085 } 1086 1087 fn findEmbed(request_path: []const u8) ?Embed { 1088 const path = if (std.mem.eql(u8, request_path, "/")) 1089 "index.html" 1090 else if (request_path.len > 1 and request_path[0] == '/') 1091 request_path[1..] 1092 else 1093 return null; 1094 1095 for (embeds) |embed| { 1096 if (std.mem.eql(u8, path, embed.path)) return embed; 1097 } 1098 return null; 1099 } 1100 1101 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 1102 // own absolutely-positioned, natively-scrollable <div> holding its full content, 1103 // rendered recursively so nested scrolls work. 1104 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 1105 const grid = root.getGrid() orelse return error.MissingGrid; 1106 1107 var out: std.ArrayList(u8) = .empty; 1108 errdefer out.deinit(allocator); 1109 1110 try renderPanel(allocator, &out, root.getFocus(), grid); 1111 return try out.toOwnedSlice(allocator); 1112 } 1113 1114 // render one panel — a focus subtree and its content grid — as HTML, recursing 1115 // once per web-native Scroll inside it. the root panel is the whole page; each 1116 // Scroll becomes a nested, natively-scrollable div holding its full content. 1117 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 1118 // then the child scroll divs over those holes. 1119 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 1120 // `direct` is this panel's scroll children, each drawn as an overlaid div. 1121 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 1122 // plus their descendants, which the focus tree flattens into this panel's 1123 // children): the cell hit-test below skips them so this panel doesn't claim 1124 // cells that are really rendered inside a child scroll's own panel. 1125 // (scrolls aren't nested in practice, so every scroll child is direct here.) 1126 var direct: std.ArrayList(usize) = .empty; 1127 defer direct.deinit(allocator); 1128 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 1129 defer excluded.deinit(allocator); 1130 { 1131 var it = focus.children.iterator(); 1132 while (it.next()) |e| { 1133 if (e.value_ptr.focus.scroll == null) continue; 1134 try direct.append(allocator, e.key_ptr.*); 1135 try excluded.put(allocator, e.key_ptr.*, {}); 1136 var mit = e.value_ptr.focus.children.iterator(); 1137 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 1138 } 1139 } 1140 1141 // the HTML element a run of cells is wrapped in, chosen from the cell's 1142 // focusable kind 1143 const CellTag = union(enum) { 1144 span, // clickable focusable cell 1145 a: []const u8, // clickable focusable link 1146 plain, // non-focusable, colored 1147 1148 const a_prefix = "a:"; 1149 // an "in-page" anchor: rendered as a real <a href> so it works with js 1150 // disabled, but crossPageLink ignores it, so with wasm the click just 1151 // moves focus rather than navigating. 1152 const inpage_prefix = "ai:"; 1153 1154 fn init(str: []const u8) @This() { 1155 if (std.mem.startsWith(u8, str, inpage_prefix)) { 1156 return .{ .a = str[inpage_prefix.len..] }; 1157 } 1158 if (std.mem.startsWith(u8, str, a_prefix)) { 1159 return .{ .a = str[a_prefix.len..] }; 1160 } 1161 return .span; 1162 } 1163 1164 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 1165 var id_buf: [32]u8 = undefined; 1166 switch (self) { 1167 .span => { 1168 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 1169 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1170 try out.appendSlice(alloc, "\""); 1171 try out.appendSlice(alloc, style_attr); 1172 try out.appendSlice(alloc, ">"); 1173 }, 1174 .a => |href| { 1175 // tabindex=-1 keeps these out of the browser's tab order 1176 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 1177 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1178 try out.appendSlice(alloc, "\" href=\""); 1179 try appendEscapedHtml(alloc, out, href); 1180 try out.appendSlice(alloc, "\""); 1181 try out.appendSlice(alloc, style_attr); 1182 try out.appendSlice(alloc, ">"); 1183 }, 1184 .plain => { 1185 try out.appendSlice(alloc, "<span"); 1186 try out.appendSlice(alloc, style_attr); 1187 try out.appendSlice(alloc, ">"); 1188 }, 1189 } 1190 } 1191 1192 fn closeTag(self: @This()) []const u8 { 1193 return switch (self) { 1194 .span, .plain => "</span>", 1195 .a => "</a>", 1196 }; 1197 } 1198 }; 1199 1200 // emit this panel's grid as rows of text, coalescing adjacent cells that 1201 // share a focus id and colors into one tag (a clickable span, a link, or a 1202 // plain colored span). cells under a child scroll keep only their background. 1203 for (0..grid.size.height) |y| { 1204 var cur_id: ?usize = null; 1205 var cur_fg: ?Grid.Color = null; 1206 var cur_bg: ?Grid.Color = null; 1207 var open_tag: ?CellTag = null; 1208 var first = true; 1209 for (0..grid.size.width) |x| { 1210 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 1211 // a cell covered by a child scroll's viewport is drawn by that scroll's 1212 // own div, so blank its glyph and make it non-clickable here — but keep 1213 // its background, so the backdrop still shows through the scroll's 1214 // transparent div instead of a bare hole. 1215 const covered_by_scroll = blk: { 1216 for (direct.items) |id| { 1217 const r = (focus.children.get(id) orelse continue).rect; 1218 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) break :blk true; 1219 } 1220 break :blk false; 1221 }; 1222 // the focusable cell at (x, y) among this panel's own focusables (skipping 1223 // any that belong to a child scroll, whose cells are drawn in their own 1224 // panel); none for a covered cell. 1225 const cell_id = if (covered_by_scroll) null else blk: { 1226 var iter = focus.children.iterator(); 1227 while (iter.next()) |entry| { 1228 const child = entry.value_ptr.*; 1229 if (!child.focus.focusable) continue; 1230 if (excluded.contains(entry.key_ptr.*)) continue; 1231 const r = child.rect; 1232 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 1233 break :blk entry.key_ptr.*; 1234 } 1235 } 1236 break :blk null; 1237 }; 1238 const fg = if (covered_by_scroll) null else cell.style.fg; 1239 const bg = cell.style.bg; 1240 1241 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 1242 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1243 1244 var new_tag: ?CellTag = null; 1245 if (cell_id) |id| { 1246 if (focus.children.get(id)) |child| { 1247 new_tag = switch (child.focus.kind) { 1248 .custom => |custom| CellTag.init(custom), 1249 else => .span, 1250 }; 1251 } 1252 } 1253 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 1254 1255 if (new_tag) |t| { 1256 var style_buf: [64]u8 = undefined; 1257 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 1258 } 1259 1260 open_tag = new_tag; 1261 cur_id = cell_id; 1262 cur_fg = fg; 1263 cur_bg = bg; 1264 first = false; 1265 } 1266 1267 if (covered_by_scroll) { 1268 try appendEscapedHtml(allocator, output, " "); 1269 } else if (cell.continuation) { 1270 // the wide rune to the left was emitted 2ch wide, covering this column 1271 } else if (cell.rune) |rune| { 1272 // a double-width rune is pinned inside a 2ch span so the 1273 // fallback glyph's advance width can't shift the rest of the row 1274 const wide = x + 1 < grid.size.width and grid.cells.items[try grid.cells.at(.{ y, x + 1 })].continuation; 1275 if (wide) { 1276 try output.appendSlice(allocator, "<span class=\"w2\">"); 1277 try appendEscapedHtml(allocator, output, rune); 1278 try output.appendSlice(allocator, "</span>"); 1279 } else { 1280 try appendEscapedHtml(allocator, output, rune); 1281 } 1282 } else { 1283 try appendEscapedHtml(allocator, output, " "); 1284 } 1285 } 1286 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1287 try output.append(allocator, '\n'); 1288 } 1289 1290 // each child scroll becomes a natively-scrollable div positioned over its 1291 // viewport, holding its full content rendered recursively. 1292 for (direct.items) |id| { 1293 const child = focus.children.get(id) orelse continue; 1294 const info = child.focus.scroll orelse continue; 1295 const r = child.rect; 1296 // overflow only on the axes the widget scrolls; `auto` shows a bar only 1297 // when that axis actually overflows. the other axis is clipped (hidden), 1298 // matching how the terminal Scroll handles its non-scrolling axis. 1299 const overflow = switch (info.direction) { 1300 .vert => "overflow-x:hidden;overflow-y:auto", 1301 .horiz => "overflow-x:auto;overflow-y:hidden", 1302 .both => "overflow:auto", 1303 }; 1304 // the id carries a content version so JS preserves the native scroll 1305 // position across re-renders of the same content but resets it when the 1306 // content is replaced — e.g. selecting a different commit. the widget's 1307 // scroll offset (in cells) rides along so JS can apply it when it has no 1308 // preserved position, letting a wasm-side scrollToRect (the files list 1309 // scrolling to its selected row on page load) reach the browser. 1310 var buf: [224]u8 = undefined; 1311 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, "<div class=\"scroll\" data-scroll-id=\"{d}-{d}\" data-scroll-x=\"{d}\" data-scroll-y=\"{d}\" style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em;{s}\">", .{ id, child.focus.version, info.offset_x, info.offset_y, r.x, r.y, r.size.width, r.size.height, overflow })); 1312 try renderPanel(allocator, output, child.focus, info.content); 1313 try output.appendSlice(allocator, "</div>"); 1314 } 1315 } 1316 1317 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 1318 // widget tree, each wrapping the text inputs and submit button inside it, 1319 // positioned absolutely over the matching grid cells. 1320 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1321 const root_focus = root.getFocus(); 1322 1323 var out: std.ArrayList(u8) = .empty; 1324 errdefer out.deinit(allocator); 1325 1326 const form_prefix = "form:"; 1327 1328 // Focus.children is an AutoArrayHashMap that preserves insertion order, 1329 // which matches the order widgets were added in code 1330 var iter = root_focus.children.iterator(); 1331 while (iter.next()) |entry| { 1332 const child = entry.value_ptr.*; 1333 const action_url = switch (child.focus.kind) { 1334 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 1335 custom[form_prefix.len..] 1336 else 1337 continue, 1338 else => continue, 1339 }; 1340 1341 try out.appendSlice(allocator, "<form action=\""); 1342 try appendEscapedHtml(allocator, &out, action_url); 1343 try out.appendSlice(allocator, "\" method=\"post\""); 1344 // an empty action must not POST — block it and send the input to the TUI instead 1345 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 1346 try out.appendSlice(allocator, ">"); 1347 1348 // form.focus.children was populated by addChild, which flattens the 1349 // whole subtree into one map — so descendants (inputs + the submit 1350 // button) all appear here. positions on form.focus are relative to 1351 // the form, so we look up absolute rects via root_focus for layout. 1352 var inner_iter = child.focus.children.iterator(); 1353 while (inner_iter.next()) |inner_entry| { 1354 const inner_id = inner_entry.key_ptr.*; 1355 const root_child = root_focus.children.get(inner_id) orelse continue; 1356 const r = root_child.rect; 1357 switch (root_child.focus.kind) { 1358 .text_input, .text_input_password => { 1359 const ti = session.text_inputs.get(inner_id) orelse continue; 1360 const inner_left = r.x + 1; 1361 const inner_top = r.y + 1; 1362 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1363 1364 try out.appendSlice(allocator, "<input type=\""); 1365 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 1366 try out.appendSlice(allocator, "\" data-focus-id=\""); 1367 var id_buf: [32]u8 = undefined; 1368 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1369 if (ti.options.name.len > 0) { 1370 try out.appendSlice(allocator, "\" name=\""); 1371 try appendEscapedHtml(allocator, &out, ti.options.name); 1372 } 1373 // never the live content as the `value`: the browser tracks user 1374 // input natively, and including the wasm-side value here would make 1375 // the overlay HTML differ on every keystroke — that would trip the 1376 // diff in _setOverlay and rebuild the <input>, eating the user's 1377 // caret. a page-constant initial value is safe. 1378 if (session.input_values.get(inner_id)) |value| { 1379 try out.appendSlice(allocator, "\" value=\""); 1380 try appendEscapedHtml(allocator, &out, value); 1381 } 1382 try out.appendSlice(allocator, "\" style=\"left:"); 1383 var pos_buf: [64]u8 = undefined; 1384 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:1em", .{ inner_left, inner_top, inner_width })); 1385 try out.appendSlice(allocator, "\">"); 1386 }, 1387 .text_area => { 1388 const ti = session.text_inputs.get(inner_id) orelse continue; 1389 const inner_left = r.x + 1; 1390 const inner_top = r.y + 1; 1391 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1392 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 1393 1394 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 1395 var id_buf: [32]u8 = undefined; 1396 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1397 if (ti.options.name.len > 0) { 1398 try out.appendSlice(allocator, "\" name=\""); 1399 try appendEscapedHtml(allocator, &out, ti.options.name); 1400 } 1401 // like the input above, only a page-constant initial value 1402 // inside: the browser tracks the live value and the 1403 // overlay diff must stay stable across keystrokes 1404 try out.appendSlice(allocator, "\" style=\"left:"); 1405 var pos_buf: [128]u8 = undefined; 1406 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ inner_left, inner_top, inner_width, inner_height })); 1407 // textarea discards the first newline immediately following 1408 // its start tag, so add one of our own so text that begins 1409 // with a newline doesn't lose it 1410 try out.appendSlice(allocator, "\">\n"); 1411 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1412 try out.appendSlice(allocator, "</textarea>"); 1413 }, 1414 .custom => |custom| { 1415 if (std.mem.eql(u8, "submit", custom)) { 1416 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1417 var id_buf: [32]u8 = undefined; 1418 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1419 try out.appendSlice(allocator, "\" style=\"left:"); 1420 var pos_buf: [128]u8 = undefined; 1421 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ r.x, r.y, r.size.width, r.size.height })); 1422 try out.appendSlice(allocator, "\"></button>"); 1423 } 1424 }, 1425 else => {}, 1426 } 1427 } 1428 1429 try out.appendSlice(allocator, "</form>"); 1430 } 1431 1432 return try out.toOwnedSlice(allocator); 1433 } 1434 1435 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1436 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1437 return b == null; 1438 } 1439 1440 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1441 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1442 // empty slice when neither is set. 1443 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1444 if (fg == null and bg == null) return buf[0..0]; 1445 const prefix = " style=\""; 1446 @memcpy(buf[0..prefix.len], prefix); 1447 var i: usize = prefix.len; 1448 if (fg) |c| { 1449 const s = std.fmt.bufPrint(buf[i..], "color:#{x:0>2}{x:0>2}{x:0>2};", .{ c.r, c.g, c.b }) catch return buf[0..0]; 1450 i += s.len; 1451 } 1452 if (bg) |c| { 1453 const s = std.fmt.bufPrint(buf[i..], "background-color:#{x:0>2}{x:0>2}{x:0>2};", .{ c.r, c.g, c.b }) catch return buf[0..0]; 1454 i += s.len; 1455 } 1456 buf[i] = '"'; 1457 i += 1; 1458 return buf[0..i]; 1459 } 1460 1461 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1462 for (input) |ch| { 1463 switch (ch) { 1464 '&' => try out.appendSlice(allocator, "&amp;"), 1465 '<' => try out.appendSlice(allocator, "&lt;"), 1466 '>' => try out.appendSlice(allocator, "&gt;"), 1467 '"' => try out.appendSlice(allocator, "&quot;"), 1468 '\'' => try out.appendSlice(allocator, "&#39;"), 1469 else => try out.append(allocator, ch), 1470 } 1471 } 1472 } 1473 1474 // --- helpers -------------------------------------------------------------- 1475 1476 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1477 var iter = request.iterateHeaders(); 1478 while (iter.next()) |header| { 1479 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1480 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1481 while (pairs.next()) |pair| { 1482 const trimmed = std.mem.trim(u8, pair, " \t"); 1483 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1484 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1485 return trimmed[eq + 1 ..]; 1486 } 1487 } 1488 } 1489 return null; 1490 } 1491 1492 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1493 var iter = std.mem.splitScalar(u8, body, '&'); 1494 while (iter.next()) |pair| { 1495 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1496 if (std.mem.eql(u8, pair[0..eq], key)) { 1497 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1498 } 1499 } 1500 return null; 1501 } 1502 1503 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1504 var out: std.ArrayList(u8) = .empty; 1505 errdefer out.deinit(allocator); 1506 var i: usize = 0; 1507 while (i < encoded.len) : (i += 1) { 1508 switch (encoded[i]) { 1509 '+' => try out.append(allocator, ' '), 1510 '%' => { 1511 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1512 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1513 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1514 try out.append(allocator, hi * 16 + lo); 1515 i += 2; 1516 }, 1517 else => try out.append(allocator, encoded[i]), 1518 } 1519 } 1520 return try out.toOwnedSlice(allocator); 1521 } 1522 1523 // disk-backed web session store. each login mints a random, opaque token 1524 // (not the user's id) that is stored as a file named by the token hex, whose 1525 // contents are the raw user_id bytes. authenticating a request is a lookup of 1526 // the cookie's token; logout deletes the file, revoking the session. there is 1527 // deliberately no expiry — a session lives until logout. 1528 pub const SessionStore = struct { 1529 io: std.Io, 1530 dir: std.Io.Dir, 1531 1532 pub const token_hex_len = evt.event_id_size * 2; 1533 1534 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1535 try data_dir.createDirPath(io, "sessions"); 1536 const dir = try data_dir.openDir(io, "sessions", .{}); 1537 return .{ .io = io, .dir = dir }; 1538 } 1539 1540 pub fn deinit(self: SessionStore) void { 1541 self.dir.close(self.io); 1542 } 1543 1544 // mint a new session for user_id, returning the token hex to set as the 1545 // cookie value. 1546 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1547 var token: [evt.event_id_size]u8 = undefined; 1548 self.io.random(&token); 1549 const token_hex = std.fmt.bytesToHex(token, .lower); 1550 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1551 defer file.close(self.io); 1552 try file.writeStreamingAll(self.io, user_id); 1553 return token_hex; 1554 } 1555 1556 // resolve a cookie's token to its user_id. returns false (logged out) for a 1557 // missing, malformed, or unknown token. 1558 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1559 if (!isToken(token_hex)) return false; 1560 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1561 defer file.close(self.io); 1562 var storage: [evt.event_id_size]u8 = undefined; 1563 var file_reader = file.reader(self.io, &storage); 1564 file_reader.interface.readSliceAll(out) catch return false; 1565 return true; 1566 } 1567 1568 // revoke a session. a no-op for a missing or malformed token. 1569 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1570 if (!isToken(token_hex)) return; 1571 self.dir.deleteFile(self.io, token_hex) catch {}; 1572 } 1573 1574 // leave `token_hex`'s session for the next visitor arriving without one. 1575 // only the `try` fixture writes one, and only a debug build honors it. the 1576 // name isn't token-shaped, so it can't collide with a session file. 1577 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 1578 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 1579 defer file.close(self.io); 1580 try file.writeStreamingAll(self.io, token_hex); 1581 } 1582 1583 // claim the offered session, if one is there. the delete picks the winner 1584 // of a race, so the offer is only ever taken once. a release build never 1585 // looks, because that would be an extra syscall for every GET request. 1586 pub fn claimAutoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 1587 if (builtin.mode != .Debug) return false; 1588 { 1589 const file = self.dir.openFile(self.io, auto_login_name, .{ .mode = .read_only }) catch return false; 1590 defer file.close(self.io); 1591 var storage: [token_hex_len]u8 = undefined; 1592 var file_reader = file.reader(self.io, &storage); 1593 file_reader.interface.readSliceAll(out) catch return false; 1594 } 1595 self.dir.deleteFile(self.io, auto_login_name) catch return false; 1596 return true; 1597 } 1598 1599 const auto_login_name = "auto-login"; 1600 1601 // a token is exactly token_hex_len hex chars. validating before using the 1602 // value as a path keeps attacker-supplied cookies from escaping the 1603 // sessions dir (e.g. via "/" or ".." bytes). 1604 fn isToken(token_hex: []const u8) bool { 1605 if (token_hex.len != token_hex_len) return false; 1606 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1607 return true; 1608 } 1609 }; 1610