╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
363 }, 364 } 365 } 366 367 fn handleLogout(request: *std.http.Server.Request, base: []const u8, session_store: SessionStore) !void { 368 // revoke the session server-side so the cookie is dead for anyone holding 369 // a copy, not just this browser. 370 if (getCookieValue(request, cookie_name)) |token| session_store.remove(token); 371 // return to the page the logout came from (base, or "/" at the root). 372 const location: []const u8 = if (base.len == 0) "/" else base; 373 // close the connection instead of keeping it alive: we don't read the 374 // request body, and respond()'s keep-alive path would otherwise try to 375 // discard it — which asserts on a bodyless POST that carries no 376 // content-length, and would block on one with no framing at all. a logout 377 // is just a redirect, so the browser reconnects for the follow-up GET. 378 try request.respond("", .{ 379 .status = .see_other, 380 .keep_alive = false, 381 .extra_headers = &.{ 382 .{ .name = "location", .value = location }, 383 .{ .name = "set-cookie", .value = cookie_name ++ "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0" }, 384 }, 385 }); 386 } 387 388 fn handleAnsi( 389 io: std.Io, 390 request: *std.http.Server.Request, 391 allocator: std.mem.Allocator, 392 base: []const u8, 393 admin_repo_path: []const u8, 394 session_store: SessionStore, 395 ) !void { 396 // the toggle re-emits the user's own event, so it takes a logged-in user 397 var user_id: [evt.event_id_size]u8 = undefined; 398 const token = getCookieValue(request, cookie_name) orelse return respondLoginRequired(request); 399 if (!session_store.lookup(token, &user_id)) return respondLoginRequired(request); 400 401 { 402 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 403 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 404 defer repo.deinit(io, allocator); 405 406 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, &repo, &user_id); 407 } 408 409 // return to the settings tab the toggle came from so the change is visible. 410 const location = try std.fmt.allocPrint(allocator, "{s}/settings", .{base}); 411 defer allocator.free(location); 412 413 // like logout, this is a bodyless POST, so close the connection rather than 414 // letting the keep-alive path try to discard a body that isn't framed. 415 try request.respond("", .{ 416 .status = .see_other, 417 .keep_alive = false, 418 .extra_headers = &.{ 419 .{ .name = "location", .value = location }, 420 }, 421 }); 422 } 423 424 // the author for an event created by this request, or null when the request 425 // may not create one. local mode has no accounts, so it authors anonymously. 426 fn eventAuthor( 427 io: std.Io, 428 allocator: std.mem.Allocator, 429 arena: *std.heap.ArenaAllocator, 430 request: *std.http.Server.Request, 431 host: Host, 432 ) !?evt.CommitAuthor { 433 const remote = switch (host) { 434 .remote => |remote| remote, 435 .local => |src| return try ui.localAuthor(src, io, allocator, arena), 436 }; 437 const token = getCookieValue(request, cookie_name) orelse return null; 438 var user_id: [evt.event_id_size]u8 = undefined; 439 if (!remote.session_store.lookup(token, &user_id)) return null; 440 441 var repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 442 defer repo.deinit(io, allocator); 443 const moment = try evt.currentMoment(evt.admin_repo_opts, &repo); 444 const user = (try evt.User.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, arena, &user_id)) orelse return null; 445 return .{ .name = user.event.name, .email = user.event.email }; 446 } 447 448 // refuse a write from a request with no logged-in user. the body goes unread, 449 // so the connection closes. 450 fn respondLoginRequired(request: *std.http.Server.Request) !void { 451 try request.respond("log in to make changes", .{ 452 .status = .forbidden, 453 .keep_alive = false, 454 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 455 }); 456 } 457 458 // new actions share a suffix; the base identifies whether the form creates an 459 // issue or comment. 460 fn handleNew( 461 io: std.Io, 462 request: *std.http.Server.Request, 463 allocator: std.mem.Allocator, 464 base: []const u8, 465 host: Host, 466 ) !void { 467 if (commentBaseParts(base) != null) return handleCommentNew(io, request, allocator, base, host); 468 469 const issues_suffix = "/issues"; 470 if (std.mem.endsWith(u8, base, issues_suffix)) 471 return handleTopicNew(io, request, allocator, base[0 .. base.len - issues_suffix.len], host, .issue); 472 const discussions_suffix = "/discussions"; 473 if (std.mem.endsWith(u8, base, discussions_suffix)) 474 return handleTopicNew(io, request, allocator, base[0 .. base.len - discussions_suffix.len], host, .discussion); 475 476 try request.respond("new event target not found", .{ 477 .status = .not_found, 478 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 479 }); 480 } 481 482 // create an issue or discussion in the repo the form's page names and redirect to it. 483 fn handleTopicNew( 484 io: std.Io, 485 request: *std.http.Server.Request, 486 allocator: std.mem.Allocator, 487 base: []const u8, 488 host: Host, 489 kind: evt.EventKind, 490 ) !void { 491 var author_arena = std.heap.ArenaAllocator.init(allocator); 492 defer author_arena.deinit(); 493 const author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 494 495 var body_buf: [256]u8 = undefined; 496 const reader = request.readerExpectNone(&body_buf); 497 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 498 defer allocator.free(body); 499 500 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 501 defer allocator.free(title); 502 const tags = (try parseFormField(allocator, body, "tags")) orelse try allocator.dupe(u8, ""); 503 defer allocator.free(tags); 504 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 505 defer allocator.free(description_crlf); 506 // form submission normalizes textarea line breaks to CRLF; store plain 507 // newlines so the text renders the same on every host 508 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 509 defer allocator.free(description); 510 511 const valid = switch (kind) { 512 .issue => evt.Issue.fieldsValid(title, tags), 513 .discussion => evt.Discussion.fieldsValid(title, tags), 514 else => unreachable, 515 }; 516 if (!valid) { 517 const form_location = try std.fmt.allocPrint(allocator, "{s}/{s}s/new", .{ base, @tagName(kind) }); 518 defer allocator.free(form_location); 519 try request.respond("", .{ 520 .status = .see_other, 521 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 522 }); 523 return; 524 } 525 526 var id_bytes: [evt.event_id_size]u8 = undefined; 527 io.random(&id_bytes); 528 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 529 530 const event = evt.EventWithId{ 531 .id = event_id_hex, 532 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 533 .author = author, 534 .event = switch (kind) { 535 .issue => .{ .issue = .{ .title = title, .description = description, .tags = tags } }, 536 .discussion => .{ .discussion = .{ .title = title, .description = description, .tags = tags } }, 537 else => unreachable, 538 }, 539 }; 540 541 const not_found = "repo not found"; 542 const request_repo = (try requestRepoSource(io, allocator, host, base)) orelse { 543 try request.respond(not_found, .{ 544 .status = .not_found, 545 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 546 }); 547 return; 548 }; 549 defer request_repo.deinit(allocator); 550 const source = request_repo.source; 551 switch (source.repo_kind) { 552 inline else => |repo_kind| { 553 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 554 defer any_repo.deinit(io, allocator); 555 switch (any_repo) { 556 inline else => |*repo| try evt.consume(repo_kind, repo.self_repo_opts, io, allocator, repo, evt.events_ref, &[_]evt.EventWithId{event}), 557 } 558 }, 559 } 560 561 const location = try std.fmt.allocPrint(allocator, "{s}/{s}:{s}", .{ base, @tagName(kind), &event_id_hex }); 562 defer allocator.free(location); 563 try request.respond("", .{ 564 .status = .see_other, 565 .extra_headers = &.{.{ .name = "location", .value = location }}, 566 }); 567 } 568 569 const CommentBaseParts = struct { 570 repo_base: []const u8, 571 thread_kind: evt.EventKind, 572 thread_id: [evt.event_id_size]u8, 573 comment_id: ?[evt.event_id_size]u8, 574 }; 575 576 fn commentBaseParts(base: []const u8) ?CommentBaseParts { 577 const route = ui.RoutablePage.fromUrl(base) orelse ui.RoutablePage.fromUrlLocal(base) orelse return null; 578 const identity, const thread_kind, const thread_hex, const comment_hex = switch (route) { 579 .repo_issues => |*issue| .{ issue.name.slice(), evt.EventKind.issue, issue.selected.slice(), issue.comment.slice() }, 580 .repo_discussions => |*discussion| .{ discussion.name.slice(), evt.EventKind.discussion, discussion.selected.slice(), discussion.comment.slice() }, 581 else => return null, 582 }; 583 var thread_id: [evt.event_id_size]u8 = undefined; 584 _ = std.fmt.hexToBytes(&thread_id, thread_hex) catch return null; 585 const comment_id = if (comment_hex.len == 0) null else blk: { 586 var id: [evt.event_id_size]u8 = undefined; 587 _ = std.fmt.hexToBytes(&id, comment_hex) catch return null; 588 break :blk id; 589 }; 590 const repo_base_len = if (identity.len == 0) 0 else "/repo/".len + identity.len; 591 return .{ .repo_base = base[0..repo_base_len], .thread_kind = thread_kind, .thread_id = thread_id, .comment_id = comment_id }; 592 } 593 594 // create a reply and redirect to its permalink. 595 fn handleCommentNew( 596 io: std.Io, 597 request: *std.http.Server.Request, 598 allocator: std.mem.Allocator, 599 base: []const u8, 600 host: Host, 601 ) !void { 602 const not_found = "comment parent not found"; 603 const parts = commentBaseParts(base) orelse { 604 try request.respond(not_found, .{ 605 .status = .not_found, 606 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 607 }); 608 return; 609 }; 610 611 var author_arena = std.heap.ArenaAllocator.init(allocator); 612 defer author_arena.deinit(); 613 const author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 614 615 var body_buf: [256]u8 = undefined; 616 const reader = request.readerExpectNone(&body_buf); 617 const posted = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 618 defer allocator.free(posted); 619 const body_crlf = (try parseFormField(allocator, posted, "body")) orelse try allocator.dupe(u8, ""); 620 defer allocator.free(body_crlf); 621 const body = try std.mem.replaceOwned(u8, allocator, body_crlf, "\r\n", "\n"); 622 defer allocator.free(body); 623 624 if (!evt.Comment.fieldsValid(body)) { 625 const form_location = try std.fmt.allocPrint(allocator, "{s}/new", .{base}); 626 defer allocator.free(form_location); 627 try request.respond("", .{ 628 .status = .see_other, 629 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 630 }); 631 return; 632 } 633 634 const thread_id_hex = std.fmt.bytesToHex(parts.thread_id, .lower); 635 const parent_id_hex = std.fmt.bytesToHex(parts.comment_id orelse parts.thread_id, .lower); 636 637 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse { 638 try request.respond(not_found, .{ 639 .status = .not_found, 640 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 641 }); 642 return; 643 }; 644 defer request_repo.deinit(allocator); 645 const source = request_repo.source; 646 var event_id_hex: [evt.event_id_size * 2]u8 = undefined; 647 switch (source.repo_kind) { 648 inline else => |repo_kind| { 649 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 650 defer any_repo.deinit(io, allocator); 651 switch (any_repo) { 652 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), 653 } 654 }, 655 } 656 657 const location = try std.fmt.allocPrint(allocator, "{s}/{s}:{s}/comment:{s}", .{ parts.repo_base, @tagName(parts.thread_kind), &thread_id_hex, &event_id_hex }); 658 defer allocator.free(location); 659 try request.respond("", .{ 660 .status = .see_other, 661 .extra_headers = &.{.{ .name = "location", .value = location }}, 662 }); 663 } 664 665 const AttachmentRequest = struct { 666 repo_base: []const u8, 667 id: [evt.event_id_size]u8, 668 }; 669 670 // an attachment url is its repo's base and the attachment's event id 671 fn attachmentRequest(path: []const u8) ?AttachmentRequest { 672 const infix = "/attachment:"; 673 const id_len = evt.event_id_size * 2; 674 const at = std.mem.lastIndexOf(u8, path, infix) orelse return null; 675 const tail = path[at + infix.len ..]; 676 if (tail.len != id_len) return null; 677 var id: [evt.event_id_size]u8 = undefined; 678 _ = std.fmt.hexToBytes(&id, tail) catch return null; 679 return .{ .repo_base = path[0..at], .id = id }; 680 } 681 682 // serve an attachment's bytes from the repo its url names 683 fn serveAttachment( 684 io: std.Io, 685 request: *std.http.Server.Request, 686 allocator: std.mem.Allocator, 687 attachment: AttachmentRequest, 688 host: Host, 689 ) !void { 690 const request_repo = (try requestRepoSource(io, allocator, host, attachment.repo_base)) orelse return respondAttachmentNotFound(request); 691 defer request_repo.deinit(allocator); 692 const source = request_repo.source; 693 switch (source.repo_kind) { 694 inline else => |repo_kind| { 695 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 696 defer any_repo.deinit(io, allocator); 697 switch (any_repo) { 698 inline else => |*repo| try sendAttachment(repo_kind, repo.self_repo_opts, io, request, allocator, repo, &attachment.id), 699 } 700 }, 701 } 702 } 703 704 fn sendAttachment( 705 comptime repo_kind: rp.RepoKind, 706 comptime repo_opts: rp.RepoOpts(repo_kind), 707 io: std.Io, 708 request: *std.http.Server.Request, 709 allocator: std.mem.Allocator, 710 repo: *rp.Repo(repo_kind, repo_opts), 711 id: *const [evt.event_id_size]u8, 712 ) !void { 713 var arena = std.heap.ArenaAllocator.init(allocator); 714 defer arena.deinit(); 715 716 const DB = evt.EventDB(repo_opts.hash); 717 var event_db_maybe: ?evt.LocalEventDB(repo_opts.hash) = if (repo_kind == .git) try evt.LocalEventDB(repo_opts.hash).openReadOnly(io, allocator, repo.core.repo_dir) else null; 718 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 719 const haxy_moment = (if (event_db_maybe) |*event_db| 720 evt.currentMomentFromDb(repo_opts.hash, event_db.db) 721 else if (repo_kind == .git) 722 return respondAttachmentNotFound(request) 723 else 724 evt.currentMoment(repo_opts, repo)) catch return respondAttachmentNotFound(request); 725 726 const record = (try evt.Attachment.readById(DB, repo_opts.hash, haxy_moment, &arena, id)) orelse return respondAttachmentNotFound(request); 727 if (record.removed) return respondAttachmentNotFound(request); 728 if (record.blob_oid.len != hash.hexLen(repo_opts.hash)) return respondAttachmentNotFound(request); 729 const blob_oid: *const [hash.hexLen(repo_opts.hash)]u8 = @ptrCast(record.blob_oid.ptr); 730 731 var moment = repo.core.latestMoment() catch return respondAttachmentNotFound(request); 732 const state = rp.Repo(repo_kind, repo_opts).State(.read_only){ .core = &repo.core, .extra = .{ .moment = &moment } }; 733 var object_reader = obj.ObjectReader(repo_kind, repo_opts).init(state, io, allocator, blob_oid) catch return respondAttachmentNotFound(request); 734 defer object_reader.deinit(); 735 if (object_reader.header().kind != .blob) return respondAttachmentNotFound(request); 736 737 const content_type = attachmentContentType(record.name); 738 const encoded_name = try ui.urlEncodeRef(allocator, record.name); 739 defer allocator.free(encoded_name); 740 const disposition = try std.fmt.allocPrint(allocator, "{s}; filename*=UTF-8''{s}", .{ if (content_type == null) "attachment" else "inline", encoded_name }); 741 defer allocator.free(disposition); 742 743 var send_buf: [8192]u8 = undefined; 744 var body = try request.respondStreaming(&send_buf, .{ 745 .content_length = object_reader.header().size, 746 .respond_options = .{ 747 .extra_headers = &.{ 748 .{ .name = "content-type", .value = content_type orelse "application/octet-stream" }, 749 .{ .name = "content-disposition", .value = disposition }, 750 // uploaded bytes are never sniffed into a type that could run 751 // as script on this origin 752 .{ .name = "x-content-type-options", .value = "nosniff" }, 753 }, 754 }, 755 }); 756 _ = try object_reader.interface.streamRemaining(&body.writer); 757 try body.end(); 758 } 759 760 // the images a browser renders safely inline. anything else downloads as 761 // opaque bytes, so an uploaded page can't run on this origin. 762 fn attachmentContentType(name: []const u8) ?[]const u8 { 763 const types = [_]struct { ext: []const u8, value: []const u8 }{ 764 .{ .ext = ".png", .value = "image/png" }, 765 .{ .ext = ".jpg", .value = "image/jpeg" }, 766 .{ .ext = ".jpeg", .value = "image/jpeg" }, 767 .{ .ext = ".gif", .value = "image/gif" }, 768 .{ .ext = ".webp", .value = "image/webp" }, 769 }; 770 for (types) |entry| { 771 if (name.len > entry.ext.len and std.ascii.eqlIgnoreCase(name[name.len - entry.ext.len ..], entry.ext)) return entry.value; 772 } 773 return null; 774 } 775 776 fn respondAttachmentNotFound(request: *std.http.Server.Request) !void { 777 try request.respond("attachment not found", .{ 778 .status = .not_found, 779 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 780 }); 781 } 782 783 fn respondAttachmentParentNotFound(request: *std.http.Server.Request) !void { 784 try request.respond("attachment parent not found", .{ 785 .status = .not_found, 786 .keep_alive = false, 787 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 788 }); 789 } 790 791 // the upload declares its file's name here, since the body is the file itself 792 const attachment_name_header = "x-attachment-name"; 793 794 const AttachParentParts = struct { 795 repo_base: []const u8, 796 id_bytes: [evt.event_id_size]u8, 797 }; 798 799 // what an attachment hangs off: the `<kind>:<id>` segment the form's page ends 800 // with, whatever kind that is 801 fn attachParentParts(base: []const u8) ?AttachParentParts { 802 const id_len = evt.event_id_size * 2; 803 if (base.len < id_len + 1) return null; 804 const head = base[0 .. base.len - id_len]; 805 if (head[head.len - 1] != ':') return null; 806 var id_bytes: [evt.event_id_size]u8 = undefined; 807 _ = std.fmt.hexToBytes(&id_bytes, base[base.len - id_len ..]) catch return null; 808 const segment_at = std.mem.lastIndexOfScalar(u8, head, '/') orelse return null; 809 return .{ .repo_base = head[0..segment_at], .id_bytes = id_bytes }; 810 } 811 812 // attach the posted file to the event the url names, then reload. the file is 813 // the whole request body, so it streams from the socket into the object store 814 // without being buffered. 815 fn handleAttach( 816 io: std.Io, 817 request: *std.http.Server.Request, 818 allocator: std.mem.Allocator, 819 base: []const u8, 820 host: Host, 821 ) !void { 822 // reading the body invalidates the request head's memory, and the url is 823 // still needed to resolve the repo afterward 824 const base_copy = try allocator.dupe(u8, base); 825 defer allocator.free(base_copy); 826 827 const parts = attachParentParts(base_copy) orelse return respondAttachmentParentNotFound(request); 828 829 var author_arena = std.heap.ArenaAllocator.init(allocator); 830 defer author_arena.deinit(); 831 const author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 832 833 const name = (try attachmentName(allocator, request)) orelse return respondUploadError(request, .bad_request, "attachment needs a name"); 834 defer allocator.free(name); 835 if (!evt.Attachment.nameValid(name)) return respondUploadError(request, .bad_request, "invalid attachment name"); 836 837 const size = request.head.content_length orelse return respondUploadError(request, .length_required, "attachments must declare a content length"); 838 if (size == 0) return respondUploadError(request, .bad_request, "attachment is empty"); 839 if (size > evt.Attachment.max_size) return respondUploadError(request, .payload_too_large, "attachment is too large"); 840 841 const parent_id_hex = std.fmt.bytesToHex(parts.id_bytes, .lower); 842 843 var body_buf: [4096]u8 = undefined; 844 const blob: evt.Blob = .{ .name = name, .size = size, .reader = try request.readerExpectContinue(&body_buf) }; 845 846 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondAttachmentParentNotFound(request); 847 defer request_repo.deinit(allocator); 848 const source = request_repo.source; 849 switch (source.repo_kind) { 850 inline else => |repo_kind| { 851 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 852 defer any_repo.deinit(io, allocator); 853 switch (any_repo) { 854 inline else => |*repo| _ = evt.Attachment.create(repo_kind, repo.self_repo_opts, io, allocator, repo, &parent_id_hex, blob, author) catch |err| switch (err) { 855 error.ParentNotFound => return respondAttachmentParentNotFound(request), 856 else => return err, 857 }, 858 } 859 }, 860 } 861 862 // the client reloads the page itself 863 try request.respond("", .{ .status = .no_content, .keep_alive = false }); 864 } 865 866 // the name the upload declares for its file, percent-encoded so it survives a 867 // header 868 fn attachmentName(allocator: std.mem.Allocator, request: *std.http.Server.Request) !?[]u8 { 869 var iter = request.iterateHeaders(); 870 while (iter.next()) |header| { 871 if (!std.ascii.eqlIgnoreCase(header.name, attachment_name_header)) continue; 872 return try decodeFormValue(allocator, header.value); 873 } 874 return null; 875 } 876 877 // an upload that failed leaves the body partly read, so the connection closes 878 fn respondUploadError(request: *std.http.Server.Request, status: std.http.Status, message: []const u8) !void { 879 try request.respond(message, .{ 880 .status = status, 881 .keep_alive = false, 882 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 883 }); 884 } 885 886 // re-emit the comment `parts` names with a new body, in the repo the host 887 // resolves the base to. 888 fn updateComment( 889 io: std.Io, 890 allocator: std.mem.Allocator, 891 host: Host, 892 parts: CommentBaseParts, 893 body: []const u8, 894 author: evt.CommitAuthor, 895 ) !void { 896 const comment_id = parts.comment_id orelse return error.NotFound; 897 const thread_id = std.fmt.bytesToHex(parts.thread_id, .lower); 898 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return error.NotFound; 899 defer request_repo.deinit(allocator); 900 const source = request_repo.source; 901 switch (source.repo_kind) { 902 inline else => |repo_kind| { 903 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 904 defer any_repo.deinit(io, allocator); 905 switch (any_repo) { 906 inline else => |*repo| try evt.Comment.update(repo_kind, repo.self_repo_opts, io, allocator, repo, &thread_id, &comment_id, body, author), 907 } 908 }, 909 } 910 } 911 912 // edit actions share a suffix; the base identifies the event being edited. 913 fn handleEdit( 914 io: std.Io, 915 request: *std.http.Server.Request, 916 allocator: std.mem.Allocator, 917 base: []const u8, 918 host: Host, 919 ) !void { 920 const parts = commentBaseParts(base) orelse return respondRemoveNotFound(request); 921 if (parts.comment_id != null) return handleCommentEdit(io, request, allocator, base, host, parts); 922 return handleTopicEdit(io, request, allocator, base, host, parts); 923 } 924 925 // replace the body of the comment the url names, then redirect to its 926 // permalink. 927 fn handleCommentEdit( 928 io: std.Io, 929 request: *std.http.Server.Request, 930 allocator: std.mem.Allocator, 931 base: []const u8, 932 host: Host, 933 parts: CommentBaseParts, 934 ) !void { 935 var author_arena = std.heap.ArenaAllocator.init(allocator); 936 defer author_arena.deinit(); 937 const author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 938 939 var body_buf: [256]u8 = undefined; 940 const reader = request.readerExpectNone(&body_buf); 941 const posted = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 942 defer allocator.free(posted); 943 const body_crlf = (try parseFormField(allocator, posted, "body")) orelse try allocator.dupe(u8, ""); 944 defer allocator.free(body_crlf); 945 const body = try std.mem.replaceOwned(u8, allocator, body_crlf, "\r\n", "\n"); 946 defer allocator.free(body); 947 948 if (!evt.Comment.fieldsValid(body)) { 949 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 950 defer allocator.free(form_location); 951 try request.respond("", .{ 952 .status = .see_other, 953 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 954 }); 955 return; 956 } 957 958 const not_found = "comment not found"; 959 updateComment(io, allocator, host, parts, body, author) catch |err| switch (err) { 960 error.NotFound => { 961 try request.respond(not_found, .{ 962 .status = .not_found, 963 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 964 }); 965 return; 966 }, 967 else => |e| return e, 968 }; 969 970 try request.respond("", .{ 971 .status = .see_other, 972 .extra_headers = &.{.{ .name = "location", .value = base }}, 973 }); 974 } 975 976 const IssueBaseParts = struct { repo_base: []const u8, id_bytes: [evt.event_id_size]u8 }; 977 fn issueBaseParts(base: []const u8) ?IssueBaseParts { 978 const parts = commentBaseParts(base) orelse return null; 979 if (parts.thread_kind != .issue or parts.comment_id != null) return null; 980 return .{ .repo_base = parts.repo_base, .id_bytes = parts.thread_id }; 981 } 982 983 const RemoveParts = struct { 984 repo_base: []const u8, 985 kind: evt.EventKind, 986 id: [evt.event_id_size]u8, 987 }; 988 989 // split a remove url into the repo and event it names 990 fn removeParts(base: []const u8) ?RemoveParts { 991 if (attachmentRequest(base)) |attachment| { 992 const parent = attachParentParts(attachment.repo_base) orelse return null; 993 return .{ 994 .repo_base = parent.repo_base, 995 .kind = .attach, 996 .id = attachment.id, 997 }; 998 } 999 if (commentBaseParts(base)) |thread| return .{ 1000 .repo_base = thread.repo_base, 1001 .kind = if (thread.comment_id != null) .comment else thread.thread_kind, 1002 .id = thread.comment_id orelse thread.thread_id, 1003 }; 1004 return null; 1005 } 1006 1007 // remove the event named by the form's url 1008 fn handleRemove( 1009 io: std.Io, 1010 request: *std.http.Server.Request, 1011 allocator: std.mem.Allocator, 1012 base: []const u8, 1013 host: Host, 1014 ) !void { 1015 const parts = removeParts(base) orelse return respondRemoveNotFound(request); 1016 1017 var author_arena = std.heap.ArenaAllocator.init(allocator); 1018 defer author_arena.deinit(); 1019 const author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 1020 1021 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1022 defer request_repo.deinit(allocator); 1023 const source = request_repo.source; 1024 switch (source.repo_kind) { 1025 inline else => |repo_kind| { 1026 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1027 defer any_repo.deinit(io, allocator); 1028 switch (any_repo) { 1029 inline else => |*repo| evt.remove(repo_kind, repo.self_repo_opts, io, allocator, repo, &parts.id, parts.kind, author) catch |err| switch (err) { 1030 error.EventNotFound => return respondRemoveNotFound(request), 1031 else => |e| return e, 1032 }, 1033 } 1034 }, 1035 } 1036 1037 const id = std.fmt.bytesToHex(parts.id, .lower); 1038 const location = try std.fmt.allocPrint(allocator, "{s}/event:{s}/kind:{s}", .{ parts.repo_base, &id, @tagName(parts.kind) }); 1039 defer allocator.free(location); 1040 try request.respond("", .{ 1041 .status = .see_other, 1042 .keep_alive = false, 1043 .extra_headers = &.{.{ .name = "location", .value = location }}, 1044 }); 1045 } 1046 1047 fn respondRemoveNotFound(request: *std.http.Server.Request) !void { 1048 try request.respond("event not found", .{ 1049 .status = .not_found, 1050 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1051 }); 1052 } 1053 1054 // re-emit the issue `parts` names with `update` applied, in the repo the 1055 // host resolves the base to. error.NotFound when the base names no repo or 1056 // the id no issue. 1057 fn updateIssue( 1058 io: std.Io, 1059 allocator: std.mem.Allocator, 1060 host: Host, 1061 parts: IssueBaseParts, 1062 update: evt.Issue.Update, 1063 author: evt.CommitAuthor, 1064 ) !void { 1065 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return error.NotFound; 1066 defer request_repo.deinit(allocator); 1067 const source = request_repo.source; 1068 switch (source.repo_kind) { 1069 inline else => |repo_kind| { 1070 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1071 defer any_repo.deinit(io, allocator); 1072 switch (any_repo) { 1073 inline else => |*repo| try evt.Issue.update(repo_kind, repo.self_repo_opts, io, allocator, repo, &parts.id_bytes, update, author), 1074 } 1075 }, 1076 } 1077 } 1078 1079 fn updateDiscussion( 1080 io: std.Io, 1081 allocator: std.mem.Allocator, 1082 host: Host, 1083 repo_base: []const u8, 1084 id: *const [evt.event_id_size]u8, 1085 title: []const u8, 1086 tags: []const u8, 1087 description: []const u8, 1088 author: evt.CommitAuthor, 1089 ) !void { 1090 const request_repo = (try requestRepoSource(io, allocator, host, repo_base)) orelse return error.NotFound; 1091 defer request_repo.deinit(allocator); 1092 const source = request_repo.source; 1093 switch (source.repo_kind) { 1094 inline else => |repo_kind| { 1095 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1096 defer any_repo.deinit(io, allocator); 1097 switch (any_repo) { 1098 inline else => |*repo| try evt.Discussion.update(repo_kind, repo.self_repo_opts, io, allocator, repo, id, title, tags, description, author), 1099 } 1100 }, 1101 } 1102 } 1103 1104 // set the status of the issue the url names (base is 1105 // "/repo/<owner>/<name>/issue:<id>", identity elided in local mode) by 1106 // re-emitting its event, then redirect back to it 1107 fn handleIssueStatus( 1108 io: std.Io, 1109 request: *std.http.Server.Request, 1110 allocator: std.mem.Allocator, 1111 base: []const u8, 1112 host: Host, 1113 status: evt.Issue.Status, 1114 ) !void { 1115 const not_found = "issue not found"; 1116 const parts = issueBaseParts(base) orelse { 1117 try request.respond(not_found, .{ 1118 .status = .not_found, 1119 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1120 }); 1121 return; 1122 }; 1123 1124 var author_arena = std.heap.ArenaAllocator.init(allocator); 1125 defer author_arena.deinit(); 1126 const author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 1127 1128 updateIssue(io, allocator, host, parts, .{ .status = status }, author) catch |err| switch (err) { 1129 error.NotFound => { 1130 try request.respond(not_found, .{ 1131 .status = .not_found, 1132 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1133 }); 1134 return; 1135 }, 1136 else => |e| return e, 1137 }; 1138 1139 // like logout, this is a bodyless POST, so close the connection rather than 1140 // letting the keep-alive path try to discard a body that isn't framed. 1141 try request.respond("", .{ 1142 .status = .see_other, 1143 .keep_alive = false, 1144 .extra_headers = &.{.{ .name = "location", .value = base }}, 1145 }); 1146 } 1147 1148 // replace the title, tags and description of an issue or discussion. 1149 fn handleTopicEdit( 1150 io: std.Io, 1151 request: *std.http.Server.Request, 1152 allocator: std.mem.Allocator, 1153 base: []const u8, 1154 host: Host, 1155 parts: CommentBaseParts, 1156 ) !void { 1157 var author_arena = std.heap.ArenaAllocator.init(allocator); 1158 defer author_arena.deinit(); 1159 const author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 1160 1161 var body_buf: [256]u8 = undefined; 1162 const reader = request.readerExpectNone(&body_buf); 1163 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 1164 defer allocator.free(body); 1165 1166 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 1167 defer allocator.free(title); 1168 const tags = (try parseFormField(allocator, body, "tags")) orelse try allocator.dupe(u8, ""); 1169 defer allocator.free(tags); 1170 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 1171 defer allocator.free(description_crlf); 1172 // form submission normalizes textarea line breaks to CRLF; store plain 1173 // newlines so the text renders the same on every host 1174 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 1175 defer allocator.free(description); 1176 1177 // invalid fields send the user back to the edit form 1178 const valid = switch (parts.thread_kind) { 1179 .issue => evt.Issue.fieldsValid(title, tags), 1180 .discussion => evt.Discussion.fieldsValid(title, tags), 1181 else => unreachable, 1182 }; 1183 if (!valid) { 1184 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1185 defer allocator.free(form_location); 1186 try request.respond("", .{ 1187 .status = .see_other, 1188 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1189 }); 1190 return; 1191 } 1192 1193 const not_found = switch (parts.thread_kind) { 1194 .issue => "issue not found", 1195 .discussion => "discussion not found", 1196 else => unreachable, 1197 }; 1198 (switch (parts.thread_kind) { 1199 .issue => updateIssue(io, allocator, host, .{ .repo_base = parts.repo_base, .id_bytes = parts.thread_id }, .{ .fields = .{ 1200 .title = title, 1201 .tags = tags, 1202 .description = description, 1203 } }, author), 1204 .discussion => updateDiscussion(io, allocator, host, parts.repo_base, &parts.thread_id, title, tags, description, author), 1205 else => unreachable, 1206 }) catch |err| switch (err) { 1207 error.NotFound => { 1208 try request.respond(not_found, .{ 1209 .status = .not_found, 1210 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1211 }); 1212 return; 1213 }, 1214 else => |e| return e, 1215 }; 1216 1217 try request.respond("", .{ 1218 .status = .see_other, 1219 .extra_headers = &.{.{ .name = "location", .value = base }}, 1220 }); 1221 } 1222 1223 // resolve the conflict of the issue the url names (base is 1224 // "/repo/<owner>/<name>/issue:<id>", identity elided in local mode; the 1225 // form posts to "<base>/resolve") 1226 fn handleIssueResolve( 1227 io: std.Io, 1228 request: *std.http.Server.Request, 1229 allocator: std.mem.Allocator, 1230 base: []const u8, 1231 host: Host, 1232 ) !void { 1233 var author_arena = std.heap.ArenaAllocator.init(allocator); 1234 defer author_arena.deinit(); 1235 const author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 1236 1237 var body_buf: [256]u8 = undefined; 1238 const reader = request.readerExpectNone(&body_buf); 1239 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 1240 defer allocator.free(body); 1241 1242 var field_arena = std.heap.ArenaAllocator.init(allocator); 1243 defer field_arena.deinit(); 1244 const aa = field_arena.allocator(); 1245 const title = try parseFormField(aa, body, "title"); 1246 const tags = try parseFormField(aa, body, "tags"); 1247 1248 // the hunk inputs post as d0, d1, ...; form submission normalizes their 1249 // textarea line breaks to CRLF 1250 var hunks: std.ArrayList([]const u8) = .empty; 1251 var hunk_index: usize = 0; 1252 while (true) : (hunk_index += 1) { 1253 const name = try std.fmt.allocPrint(aa, "d{d}", .{hunk_index}); 1254 const posted = (try parseFormField(aa, body, name)) orelse break; 1255 try hunks.append(aa, try std.mem.replaceOwned(u8, aa, posted, "\r\n", "\n")); 1256 } 1257 1258 const not_found = "issue not found"; 1259 const parts = issueBaseParts(base) orelse { 1260 try request.respond(not_found, .{ 1261 .status = .not_found, 1262 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1263 }); 1264 return; 1265 }; 1266 1267 updateIssue(io, allocator, host, parts, .{ .resolve = .{ 1268 .title = title, 1269 .tags = tags, 1270 .hunks = hunks.items, 1271 } }, author) catch |err| switch (err) { 1272 error.NotFound => { 1273 try request.respond(not_found, .{ 1274 .status = .not_found, 1275 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1276 }); 1277 return; 1278 }, 1279 // invalid fields send the user back to the resolve form 1280 error.InvalidFields => { 1281 const form_location = try std.fmt.allocPrint(allocator, "{s}/resolve", .{base}); 1282 defer allocator.free(form_location); 1283 try request.respond("", .{ 1284 .status = .see_other, 1285 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1286 }); 1287 return; 1288 }, 1289 else => |e| return e, 1290 }; 1291 1292 try request.respond("", .{ 1293 .status = .see_other, 1294 .extra_headers = &.{.{ .name = "location", .value = base }}, 1295 }); 1296 } 1297 1298 fn handleSync( 1299 io: std.Io, 1300 request: *std.http.Server.Request, 1301 allocator: std.mem.Allocator, 1302 base: []const u8, 1303 source: ui.RepoSource, 1304 ) !void { 1305 if (base.len != 0) { 1306 try request.respond("not found", .{ 1307 .status = .not_found, 1308 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1309 }); 1310 return; 1311 } 1312 1313 var owned_failure: ?[]u8 = null; 1314 defer if (owned_failure) |message| allocator.free(message); 1315 const failure: ?[]const u8 = blk: { 1316 owned_failure = ui.Repo.Events.sync(io, allocator, source) catch |err| break :blk @errorName(err); 1317 break :blk owned_failure; 1318 }; 1319 if (failure) |message| { 1320 var encoded: std.Io.Writer.Allocating = .init(allocator); 1321 defer encoded.deinit(); 1322 try std.Uri.Component.percentEncode(&encoded.writer, message, struct { 1323 fn isUnreserved(c: u8) bool { 1324 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 1325 } 1326 }.isUnreserved); 1327 const cookie = try std.fmt.allocPrint( 1328 allocator, 1329 sync_failure_cookie ++ "={s}; Path=/; HttpOnly; SameSite=Strict", 1330 .{encoded.written()}, 1331 ); 1332 defer allocator.free(cookie); 1333 try request.respond("", .{ 1334 .status = .see_other, 1335 .extra_headers = &.{ 1336 .{ .name = "location", .value = "/events" }, 1337 .{ .name = "set-cookie", .value = cookie }, 1338 }, 1339 }); 1340 return; 1341 } 1342 1343 try request.respond("", .{ 1344 .status = .see_other, 1345 .extra_headers = &.{ 1346 .{ .name = "location", .value = "/events" }, 1347 .{ .name = "set-cookie", .value = sync_failure_cookie ++ "=; Path=/; Max-Age=0" }, 1348 }, 1349 }); 1350 } 1351 1352 fn renderIndexHtml( 1353 io: std.Io, 1354 allocator: std.mem.Allocator, 1355 host: Host, 1356 session_data: ui.Session.Data, 1357 ) ![]const u8 { 1358 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 1359 1360 var page_arena = std.heap.ArenaAllocator.init(allocator); 1361 defer page_arena.deinit(); 1362 1363 // the remote admin repo must outlive the page build, since the session's 1364 // moment reads from it. 1365 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 1366 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 1367 1368 var session = switch (host) { 1369 .remote => |remote| blk: { 1370 // open the admin repo to read live user/repo data. 1371 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 1372 const repo = if (repo_maybe) |*repo| repo else unreachable; 1373 var session = try ui.Session.init(&page_arena, repo, session_data); 1374 // give the page builders filesystem access to the on-disk repos (a 1375 // sibling "repos" dir next to the admin repo) so the Repo page can 1376 // read its files. 1377 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 1378 break :blk session; 1379 }, 1380 .local => |local| ui.Session{ 1381 .data = session_data, 1382 .arena = &page_arena, 1383 .page_arena = &page_arena, 1384 .local = local, 1385 }, 1386 }; 1387 session.io = io; 1388 1389 const snapshot: ui.Snapshot = .{ 1390 .page = try ui.Page.init(session.page_arena, &session, session.data.current_page), 1391 .session = session.data, 1392 }; 1393 var root = try ui.initRoot(allocator, &snapshot.page, &session); 1394 defer root.deinit(allocator); 1395 1396 const content = try generateHtml(allocator, &root); 1397 defer allocator.free(content); 1398 const overlay = try generateOverlay(allocator, &root, &session); 1399 defer allocator.free(overlay); 1400 1401 // serialize the snapshot so the wasm side can parse it back without making 1402 // a second request. it's embedded raw in a <script type="application/json"> 1403 // block, whose content is raw text terminated only by "</script". in json, 1404 // '<' appears solely inside string values, so escaping every '<' (and '>' 1405 // for good measure) to its \uXXXX form yields equivalent json that can't 1406 // break out of the tag. 1407 var json: std.Io.Writer.Allocating = .init(allocator); 1408 defer json.deinit(); 1409 try std.json.Stringify.value(snapshot, .{}, &json.writer); 1410 1411 var json_escaped: std.ArrayList(u8) = .empty; 1412 defer json_escaped.deinit(allocator); 1413 for (json.written()) |c| switch (c) { 1414 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 1415 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 1416 else => try json_escaped.append(allocator, c), 1417 }; 1418 1419 var out: std.ArrayList(u8) = .empty; 1420 errdefer out.deinit(allocator); 1421 { 1422 var cursor: usize = 0; 1423 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 1424 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 1425 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 1426 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 1427 }) |sub| { 1428 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 1429 try out.appendSlice(allocator, template[cursor..idx]); 1430 try out.appendSlice(allocator, sub.replacement); 1431 cursor = idx + sub.needle.len; 1432 } 1433 try out.appendSlice(allocator, template[cursor..]); 1434 } 1435 return try out.toOwnedSlice(allocator); 1436 } 1437 1438 fn findEmbed(request_path: []const u8) ?Embed { 1439 const path = if (std.mem.eql(u8, request_path, "/")) 1440 "index.html" 1441 else if (request_path.len > 1 and request_path[0] == '/') 1442 request_path[1..] 1443 else 1444 return null; 1445 1446 for (embeds) |embed| { 1447 if (std.mem.eql(u8, path, embed.path)) return embed; 1448 } 1449 return null; 1450 } 1451 1452 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 1453 // own absolutely-positioned, natively-scrollable <div> holding its full content, 1454 // rendered recursively so nested scrolls work. 1455 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 1456 const grid = root.getGrid() orelse return error.MissingGrid; 1457 1458 var out: std.ArrayList(u8) = .empty; 1459 errdefer out.deinit(allocator); 1460 1461 try renderPanel(allocator, &out, root.getFocus(), grid); 1462 return try out.toOwnedSlice(allocator); 1463 } 1464 1465 // render one panel — a focus subtree and its content grid — as HTML, recursing 1466 // once per web-native Scroll inside it. the root panel is the whole page; each 1467 // Scroll becomes a nested, natively-scrollable div holding its full content. 1468 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 1469 // then the child scroll divs over those holes. 1470 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 1471 // `direct` is this panel's scroll children, each drawn as an overlaid div. 1472 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 1473 // plus their descendants, which the focus tree flattens into this panel's 1474 // children): the cell hit-test below skips them so this panel doesn't claim 1475 // cells that are really rendered inside a child scroll's own panel. 1476 // (scrolls aren't nested in practice, so every scroll child is direct here.) 1477 var direct: std.ArrayList(usize) = .empty; 1478 defer direct.deinit(allocator); 1479 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 1480 defer excluded.deinit(allocator); 1481 { 1482 var it = focus.children.iterator(); 1483 while (it.next()) |e| { 1484 if (e.value_ptr.focus.scroll == null) continue; 1485 try direct.append(allocator, e.key_ptr.*); 1486 try excluded.put(allocator, e.key_ptr.*, {}); 1487 var mit = e.value_ptr.focus.children.iterator(); 1488 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 1489 } 1490 } 1491 1492 // the HTML element a run of cells is wrapped in, chosen from the cell's 1493 // focusable kind 1494 const CellTag = union(enum) { 1495 span, // clickable focusable cell 1496 a: []const u8, // clickable focusable link 1497 plain, // non-focusable, colored 1498 1499 const a_prefix = "a:"; 1500 // an "in-page" anchor: rendered as a real <a href> so it works with js 1501 // disabled, but crossPageLink ignores it, so with wasm the click just 1502 // moves focus rather than navigating. 1503 const inpage_prefix = "ai:"; 1504 1505 fn init(str: []const u8) @This() { 1506 if (std.mem.startsWith(u8, str, ui.raw_link_prefix)) { 1507 return .{ .a = str[ui.raw_link_prefix.len..] }; 1508 } 1509 if (std.mem.startsWith(u8, str, inpage_prefix)) { 1510 return .{ .a = str[inpage_prefix.len..] }; 1511 } 1512 if (std.mem.startsWith(u8, str, a_prefix)) { 1513 return .{ .a = str[a_prefix.len..] }; 1514 } 1515 return .span; 1516 } 1517 1518 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 1519 var id_buf: [32]u8 = undefined; 1520 switch (self) { 1521 .span => { 1522 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 1523 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1524 try out.appendSlice(alloc, "\""); 1525 try out.appendSlice(alloc, style_attr); 1526 try out.appendSlice(alloc, ">"); 1527 }, 1528 .a => |href| { 1529 // tabindex=-1 keeps these out of the browser's tab order 1530 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 1531 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1532 try out.appendSlice(alloc, "\" href=\""); 1533 try appendEscapedHtml(alloc, out, href); 1534 try out.appendSlice(alloc, "\""); 1535 try out.appendSlice(alloc, style_attr); 1536 try out.appendSlice(alloc, ">"); 1537 }, 1538 .plain => { 1539 try out.appendSlice(alloc, "<span"); 1540 try out.appendSlice(alloc, style_attr); 1541 try out.appendSlice(alloc, ">"); 1542 }, 1543 } 1544 } 1545 1546 fn closeTag(self: @This()) []const u8 { 1547 return switch (self) { 1548 .span, .plain => "</span>", 1549 .a => "</a>", 1550 }; 1551 } 1552 }; 1553 1554 // emit this panel's grid as rows of text, coalescing adjacent cells that 1555 // share a focus id and colors into one tag (a clickable span, a link, or a 1556 // plain colored span). cells under a child scroll keep only their background. 1557 for (0..grid.size.height) |y| { 1558 var cur_id: ?usize = null; 1559 var cur_fg: ?Grid.Color = null; 1560 var cur_bg: ?Grid.Color = null; 1561 var open_tag: ?CellTag = null; 1562 var first = true; 1563 for (0..grid.size.width) |x| { 1564 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 1565 // a cell covered by a child scroll's viewport is drawn by that scroll's 1566 // own div, so blank its glyph and make it non-clickable here — but keep 1567 // its background, so the backdrop still shows through the scroll's 1568 // transparent div instead of a bare hole. 1569 const covered_by_scroll = blk: { 1570 for (direct.items) |id| { 1571 const r = (focus.children.get(id) orelse continue).rect; 1572 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; 1573 } 1574 break :blk false; 1575 }; 1576 // the focusable cell at (x, y) among this panel's own focusables (skipping 1577 // any that belong to a child scroll, whose cells are drawn in their own 1578 // panel); none for a covered cell. 1579 const cell_id = if (covered_by_scroll) null else blk: { 1580 var iter = focus.children.iterator(); 1581 while (iter.next()) |entry| { 1582 const child = entry.value_ptr.*; 1583 if (!child.focus.focusable) continue; 1584 if (excluded.contains(entry.key_ptr.*)) continue; 1585 const r = child.rect; 1586 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 1587 break :blk entry.key_ptr.*; 1588 } 1589 } 1590 break :blk null; 1591 }; 1592 const fg = if (covered_by_scroll) null else cell.style.fg; 1593 const bg = cell.style.bg; 1594 1595 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 1596 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1597 1598 var new_tag: ?CellTag = null; 1599 if (cell_id) |id| { 1600 if (focus.children.get(id)) |child| { 1601 new_tag = switch (child.focus.kind) { 1602 .custom => |custom| CellTag.init(custom), 1603 else => .span, 1604 }; 1605 } 1606 } 1607 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 1608 1609 if (new_tag) |t| { 1610 var style_buf: [64]u8 = undefined; 1611 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 1612 } 1613 1614 open_tag = new_tag; 1615 cur_id = cell_id; 1616 cur_fg = fg; 1617 cur_bg = bg; 1618 first = false; 1619 } 1620 1621 if (covered_by_scroll) { 1622 try appendEscapedHtml(allocator, output, " "); 1623 } else if (cell.continuation) { 1624 // the wide rune to the left was emitted 2ch wide, covering this column 1625 } else if (cell.rune) |rune| { 1626 // a double-width rune is pinned inside a 2ch span so the 1627 // fallback glyph's advance width can't shift the rest of the row 1628 const wide = x + 1 < grid.size.width and grid.cells.items[try grid.cells.at(.{ y, x + 1 })].continuation; 1629 if (wide) { 1630 try output.appendSlice(allocator, "<span class=\"w2\">"); 1631 try appendEscapedHtml(allocator, output, rune); 1632 try output.appendSlice(allocator, "</span>"); 1633 } else { 1634 try appendEscapedHtml(allocator, output, rune); 1635 } 1636 } else { 1637 try appendEscapedHtml(allocator, output, " "); 1638 } 1639 } 1640 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1641 try output.append(allocator, '\n'); 1642 } 1643 1644 // each child scroll becomes a natively-scrollable div positioned over its 1645 // viewport, holding its full content rendered recursively. 1646 for (direct.items) |id| { 1647 const child = focus.children.get(id) orelse continue; 1648 const info = child.focus.scroll orelse continue; 1649 const r = child.rect; 1650 // overflow only on the axes the widget scrolls; `auto` shows a bar only 1651 // when that axis actually overflows. the other axis is clipped (hidden), 1652 // matching how the terminal Scroll handles its non-scrolling axis. 1653 const overflow = switch (info.direction) { 1654 .vert => "overflow-x:hidden;overflow-y:auto", 1655 .horiz => "overflow-x:auto;overflow-y:hidden", 1656 .both => "overflow:auto", 1657 }; 1658 // the id carries a content version so JS preserves the native scroll 1659 // position across re-renders of the same content but resets it when the 1660 // content is replaced — e.g. selecting a different commit. the widget's 1661 // scroll offset (in cells) rides along so JS can apply it when it has no 1662 // preserved position, letting a wasm-side scrollToRect (the files list 1663 // scrolling to its selected row on page load) reach the browser. 1664 var buf: [224]u8 = undefined; 1665 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 })); 1666 try renderPanel(allocator, output, child.focus, info.content); 1667 try output.appendSlice(allocator, "</div>"); 1668 } 1669 } 1670 1671 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 1672 // widget tree, each wrapping the text inputs and submit button inside it, 1673 // positioned absolutely over the matching grid cells. 1674 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1675 const root_focus = root.getFocus(); 1676 1677 var out: std.ArrayList(u8) = .empty; 1678 errdefer out.deinit(allocator); 1679 1680 const form_prefix = "form:"; 1681 1682 // Focus.children is an AutoArrayHashMap that preserves insertion order, 1683 // which matches the order widgets were added in code 1684 var iter = root_focus.children.iterator(); 1685 while (iter.next()) |entry| { 1686 const child = entry.value_ptr.*; 1687 const action_url = switch (child.focus.kind) { 1688 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 1689 custom[form_prefix.len..] 1690 else 1691 continue, 1692 else => continue, 1693 }; 1694 1695 try out.appendSlice(allocator, "<form action=\""); 1696 try appendEscapedHtml(allocator, &out, action_url); 1697 try out.appendSlice(allocator, "\" method=\"post\""); 1698 // an empty action must not POST — block it and send the input to the TUI instead 1699 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 1700 try out.appendSlice(allocator, ">"); 1701 1702 // form.focus.children was populated by addChild, which flattens the 1703 // whole subtree into one map — so descendants (inputs + the submit 1704 // button) all appear here. positions on form.focus are relative to 1705 // the form, so we look up absolute rects via root_focus for layout. 1706 var inner_iter = child.focus.children.iterator(); 1707 while (inner_iter.next()) |inner_entry| { 1708 const inner_id = inner_entry.key_ptr.*; 1709 const root_child = root_focus.children.get(inner_id) orelse continue; 1710 const r = root_child.rect; 1711 switch (root_child.focus.kind) { 1712 .text_input, .text_input_password => { 1713 const ti = session.text_inputs.get(inner_id) orelse continue; 1714 const inner_left = r.x + 1; 1715 const inner_top = r.y + 1; 1716 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1717 1718 try out.appendSlice(allocator, "<input type=\""); 1719 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 1720 try out.appendSlice(allocator, if (action_url.len == 0) "\" readonly data-focus-id=\"" else "\" data-focus-id=\""); 1721 var id_buf: [32]u8 = undefined; 1722 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1723 if (ti.options.name.len > 0) { 1724 try out.appendSlice(allocator, "\" name=\""); 1725 try appendEscapedHtml(allocator, &out, ti.options.name); 1726 } 1727 // never the live content as the `value`: the browser tracks user 1728 // input natively, and including the wasm-side value here would make 1729 // the overlay HTML differ on every keystroke — that would trip the 1730 // diff in _setOverlay and rebuild the <input>, eating the user's 1731 // caret. a page-constant initial value is safe. 1732 if (session.input_values.get(inner_id)) |value| { 1733 try out.appendSlice(allocator, "\" value=\""); 1734 try appendEscapedHtml(allocator, &out, value); 1735 } 1736 try out.appendSlice(allocator, "\" style=\"left:"); 1737 var pos_buf: [64]u8 = undefined; 1738 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 })); 1739 try out.appendSlice(allocator, "\">"); 1740 }, 1741 .text_area => { 1742 const ti = session.text_inputs.get(inner_id) orelse continue; 1743 const inner_left = r.x + 1; 1744 const inner_top = r.y + 1; 1745 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1746 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 1747 1748 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 1749 var id_buf: [32]u8 = undefined; 1750 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1751 if (ti.options.name.len > 0) { 1752 try out.appendSlice(allocator, "\" name=\""); 1753 try appendEscapedHtml(allocator, &out, ti.options.name); 1754 } 1755 // like the input above, only a page-constant initial value 1756 // inside: the browser tracks the live value and the 1757 // overlay diff must stay stable across keystrokes 1758 try out.appendSlice(allocator, "\" style=\"left:"); 1759 var pos_buf: [128]u8 = undefined; 1760 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 })); 1761 // textarea discards the first newline immediately following 1762 // its start tag, so add one of our own so text that begins 1763 // with a newline doesn't lose it 1764 try out.appendSlice(allocator, "\">\n"); 1765 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1766 try out.appendSlice(allocator, "</textarea>"); 1767 }, 1768 .custom => |custom| { 1769 if (std.mem.eql(u8, "submit", custom) or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 1770 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1771 var id_buf: [32]u8 = undefined; 1772 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1773 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 1774 try out.appendSlice(allocator, "\" formaction=\""); 1775 try appendEscapedHtml(allocator, &out, custom[ui.submit_action_prefix.len..]); 1776 } 1777 try out.appendSlice(allocator, "\" style=\"left:"); 1778 var pos_buf: [128]u8 = undefined; 1779 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 })); 1780 try out.appendSlice(allocator, "\"></button>"); 1781 } 1782 }, 1783 else => {}, 1784 } 1785 } 1786 1787 try out.appendSlice(allocator, "</form>"); 1788 } 1789 1790 // a file picker isn't part of a form: it posts its file straight to the url 1791 // in its marker. it sits transparent over the button the tui drew, so 1792 // clicking that button opens the browser's own dialog. 1793 var file_iter = root_focus.children.iterator(); 1794 while (file_iter.next()) |entry| { 1795 const child = entry.value_ptr.*; 1796 const action_url = switch (child.focus.kind) { 1797 .custom => |custom| if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) 1798 custom[ui.file_input_prefix.len..] 1799 else 1800 continue, 1801 else => continue, 1802 }; 1803 const r = child.rect; 1804 1805 try out.appendSlice(allocator, "<input type=\"file\" data-action=\""); 1806 try appendEscapedHtml(allocator, &out, action_url); 1807 try out.appendSlice(allocator, "\" data-focus-id=\""); 1808 var id_buf: [32]u8 = undefined; 1809 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{entry.key_ptr.*})); 1810 try out.appendSlice(allocator, "\" style=\"opacity:0;left:"); 1811 var pos_buf: [128]u8 = undefined; 1812 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 })); 1813 try out.appendSlice(allocator, "\">"); 1814 } 1815 1816 return try out.toOwnedSlice(allocator); 1817 } 1818 1819 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1820 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1821 return b == null; 1822 } 1823 1824 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1825 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1826 // empty slice when neither is set. 1827 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1828 if (fg == null and bg == null) return buf[0..0]; 1829 const prefix = " style=\""; 1830 @memcpy(buf[0..prefix.len], prefix); 1831 var i: usize = prefix.len; 1832 if (fg) |c| { 1833 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]; 1834 i += s.len; 1835 } 1836 if (bg) |c| { 1837 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]; 1838 i += s.len; 1839 } 1840 buf[i] = '"'; 1841 i += 1; 1842 return buf[0..i]; 1843 } 1844 1845 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1846 for (input) |ch| { 1847 switch (ch) { 1848 '&' => try out.appendSlice(allocator, "&amp;"), 1849 '<' => try out.appendSlice(allocator, "&lt;"), 1850 '>' => try out.appendSlice(allocator, "&gt;"), 1851 '"' => try out.appendSlice(allocator, "&quot;"), 1852 '\'' => try out.appendSlice(allocator, "&#39;"), 1853 else => try out.append(allocator, ch), 1854 } 1855 } 1856 } 1857 1858 // --- helpers -------------------------------------------------------------- 1859 1860 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1861 var iter = request.iterateHeaders(); 1862 while (iter.next()) |header| { 1863 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1864 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1865 while (pairs.next()) |pair| { 1866 const trimmed = std.mem.trim(u8, pair, " \t"); 1867 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1868 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1869 return trimmed[eq + 1 ..]; 1870 } 1871 } 1872 } 1873 return null; 1874 } 1875 1876 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1877 var iter = std.mem.splitScalar(u8, body, '&'); 1878 while (iter.next()) |pair| { 1879 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1880 if (std.mem.eql(u8, pair[0..eq], key)) { 1881 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1882 } 1883 } 1884 return null; 1885 } 1886 1887 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1888 var out: std.ArrayList(u8) = .empty; 1889 errdefer out.deinit(allocator); 1890 var i: usize = 0; 1891 while (i < encoded.len) : (i += 1) { 1892 switch (encoded[i]) { 1893 '+' => try out.append(allocator, ' '), 1894 '%' => { 1895 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1896 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1897 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1898 try out.append(allocator, hi * 16 + lo); 1899 i += 2; 1900 }, 1901 else => try out.append(allocator, encoded[i]), 1902 } 1903 } 1904 return try out.toOwnedSlice(allocator); 1905 } 1906 1907 // disk-backed web session store. each login mints a random, opaque token 1908 // (not the user's id) that is stored as a file named by the token hex, whose 1909 // contents are the raw user_id bytes. authenticating a request is a lookup of 1910 // the cookie's token; logout deletes the file, revoking the session. there is 1911 // deliberately no expiry — a session lives until logout. 1912 pub const SessionStore = struct { 1913 io: std.Io, 1914 dir: std.Io.Dir, 1915 1916 pub const token_hex_len = evt.event_id_size * 2; 1917 1918 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1919 try data_dir.createDirPath(io, "sessions"); 1920 const dir = try data_dir.openDir(io, "sessions", .{}); 1921 return .{ .io = io, .dir = dir }; 1922 } 1923 1924 pub fn deinit(self: SessionStore) void { 1925 self.dir.close(self.io); 1926 } 1927 1928 // mint a new session for user_id, returning the token hex to set as the 1929 // cookie value. 1930 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1931 var token: [evt.event_id_size]u8 = undefined; 1932 self.io.random(&token); 1933 const token_hex = std.fmt.bytesToHex(token, .lower); 1934 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1935 defer file.close(self.io); 1936 try file.writeStreamingAll(self.io, user_id); 1937 return token_hex; 1938 } 1939 1940 // resolve a cookie's token to its user_id. returns false (logged out) for a 1941 // missing, malformed, or unknown token. 1942 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1943 if (!isToken(token_hex)) return false; 1944 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1945 defer file.close(self.io); 1946 var storage: [evt.event_id_size]u8 = undefined; 1947 var file_reader = file.reader(self.io, &storage); 1948 file_reader.interface.readSliceAll(out) catch return false; 1949 return true; 1950 } 1951 1952 // revoke a session. a no-op for a missing or malformed token. 1953 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1954 if (!isToken(token_hex)) return; 1955 self.dir.deleteFile(self.io, token_hex) catch {}; 1956 } 1957 1958 // leave `token_hex`'s session for the next visitor arriving without one. 1959 // only the `try` fixture writes one, and only a debug build honors it. the 1960 // name isn't token-shaped, so it can't collide with a session file. 1961 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 1962 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 1963 defer file.close(self.io); 1964 try file.writeStreamingAll(self.io, token_hex); 1965 } 1966 1967 // claim the offered session, if one is there. the delete picks the winner 1968 // of a race, so the offer is only ever taken once. a release build never 1969 // looks, because that would be an extra syscall for every GET request. 1970 pub fn claimAutoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 1971 if (builtin.mode != .Debug) return false; 1972 { 1973 const file = self.dir.openFile(self.io, auto_login_name, .{ .mode = .read_only }) catch return false; 1974 defer file.close(self.io); 1975 var storage: [token_hex_len]u8 = undefined; 1976 var file_reader = file.reader(self.io, &storage); 1977 file_reader.interface.readSliceAll(out) catch return false; 1978 } 1979 self.dir.deleteFile(self.io, auto_login_name) catch return false; 1980 return true; 1981 } 1982 1983 const auto_login_name = "auto-login"; 1984 1985 // a token is exactly token_hex_len hex chars. validating before using the 1986 // value as a path keeps attacker-supplied cookies from escaping the 1987 // sessions dir (e.g. via "/" or ".." bytes). 1988 fn isToken(token_hex: []const u8) bool { 1989 if (token_hex.len != token_hex_len) return false; 1990 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1991 return true; 1992 } 1993 }; 1994