╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
603 allocator: std.mem.Allocator, 604 base: []const u8, 605 host: Host, 606 ) !void { 607 if (commentBaseParts(base) != null) return handleCommentNew(io, request, allocator, base, host); 608 609 const issues_suffix = "/issues"; 610 if (std.mem.endsWith(u8, base, issues_suffix)) 611 return handleThreadNew(io, request, allocator, base[0 .. base.len - issues_suffix.len], host, .issue); 612 const discussions_suffix = "/discussions"; 613 if (std.mem.endsWith(u8, base, discussions_suffix)) 614 return handleThreadNew(io, request, allocator, base[0 .. base.len - discussions_suffix.len], host, .discuss); 615 const patches_suffix = "/patches"; 616 if (std.mem.endsWith(u8, base, patches_suffix)) 617 return handleThreadNew(io, request, allocator, base[0 .. base.len - patches_suffix.len], host, .patch); 618 619 try request.respond("new event target not found", .{ 620 .status = .not_found, 621 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 622 }); 623 } 624 625 // create a thread in the repo the form's page names and redirect to it. 626 fn handleThreadNew( 627 io: std.Io, 628 request: *std.http.Server.Request, 629 allocator: std.mem.Allocator, 630 base: []const u8, 631 host: Host, 632 kind: evt.EventKind, 633 ) !void { 634 var author_arena = std.heap.ArenaAllocator.init(allocator); 635 defer author_arena.deinit(); 636 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, base, .read)) orelse return; 637 const author = actor.author; 638 const body = try readFormBody(request, allocator); 639 defer allocator.free(body); 640 641 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 642 defer allocator.free(title); 643 const tags = (try parseFormField(allocator, body, "tags")) orelse try allocator.dupe(u8, ""); 644 defer allocator.free(tags); 645 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 646 defer allocator.free(description_crlf); 647 // form submission normalizes textarea line breaks to CRLF; store plain 648 // newlines so the text renders the same on every host 649 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 650 defer allocator.free(description); 651 const target_branch = (try parseFormField(allocator, body, "target_branch")) orelse try allocator.dupe(u8, ""); 652 defer allocator.free(target_branch); 653 654 const source_branch = if (kind == .patch) try parseFormField(allocator, body, "source_branch") else null; 655 defer if (source_branch) |branch| allocator.free(branch); 656 657 const valid = switch (kind) { 658 .issue => evt.Issue.fieldsValid(title, tags), 659 .patch => evt.Patch.fieldsValid(title, tags), 660 .discuss => evt.Discussion.fieldsValid(title, tags), 661 else => unreachable, 662 }; 663 if (!valid) { 664 const list_name: []const u8 = switch (kind) { 665 .issue => "issues", 666 .patch => "patches", 667 .discuss => "discussions", 668 else => unreachable, 669 }; 670 const form_location = try std.fmt.allocPrint(allocator, "{s}/{s}/new", .{ base, list_name }); 671 defer allocator.free(form_location); 672 if (!evt.titleValid(title)) { 673 return respondThreadFormFailure(request, allocator, host, form_location, requiredTitleFeedback(kind, title, tags, description, target_branch, source_branch)); 674 } 675 try request.respond("", .{ 676 .status = .see_other, 677 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 678 }); 679 return; 680 } 681 682 var id_bytes: [evt.event_id_size]u8 = undefined; 683 io.random(&id_bytes); 684 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 685 686 const not_found = "repo not found"; 687 const request_repo = (try requestRepoSource(io, allocator, host, base)) orelse { 688 try request.respond(not_found, .{ 689 .status = .not_found, 690 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 691 }); 692 return; 693 }; 694 defer request_repo.deinit(allocator); 695 const source = request_repo.source; 696 if (kind == .patch and source_branch == null) { 697 const server = switch (host) { 698 .server => |server| server, 699 .local => return respondRemoveNotFound(request), 700 }; 701 const user_id = actor.user_id orelse return respondLoginRequired(request); 702 if (!evt.Patch.branchValid(target_branch) or !try request_repo.source.hasBranch(io, allocator, target_branch)) { 703 const form_location = try std.fmt.allocPrint(allocator, "{s}/patches/new", .{base}); 704 defer allocator.free(form_location); 705 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(.invalid_target_branch, title, tags, description, target_branch, null)); 706 } 707 const repo_id = evt.parseEventId(std.fs.path.basename(request_repo.source.path)) catch return respondRemoveNotFound(request); 708 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 709 defer admin_repo.deinit(io, allocator); 710 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(server.admin_repo_path) orelse ".", "repos" }); 711 defer allocator.free(repos_dir); 712 const fork_path = try fork.create(.{}, io, allocator, repos_dir, &admin_repo, .{ 713 .id = event_id_hex, 714 .user_id = user_id, 715 .repo_id = repo_id, 716 .title = title, 717 .description = description, 718 .tags = tags, 719 .target_branch = target_branch, 720 .author = author, 721 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 722 }); 723 defer allocator.free(fork_path); 724 } else { 725 const event = evt.EventWithId{ 726 .id = event_id_hex, 727 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 728 .author = author, 729 .event = switch (kind) { 730 .issue => .{ .issue = .{ .title = title, .description = description, .tags = tags } }, 731 .patch => .{ .patch = .{ .title = title, .description = description, .tags = tags, .target_branch = target_branch, .source_branch = source_branch } }, 732 .discuss => .{ .discuss = .{ .title = title, .description = description, .tags = tags } }, 733 else => unreachable, 734 }, 735 }; 736 737 switch (source.repo_kind) { 738 inline else => |repo_kind| { 739 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 740 defer any_repo.deinit(io, allocator); 741 switch (any_repo) { 742 inline else => |*repo| { 743 const result = if (kind == .patch) 744 pch.writeBranchPatch(std.meta.activeTag(host), repo_kind, repo.self_repo_opts, io, allocator, repo, event_id_hex, event.event.patch orelse unreachable, null, author) 745 else 746 evt.consume(std.meta.activeTag(host), .repo, repo_kind, repo.self_repo_opts, io, allocator, repo, evt.events_ref, &.{event}); 747 result catch |err| { 748 if (kind != .patch) return err; 749 const failure = ui.Session.FormFeedback.PatchFailure.fromError(err) orelse return err; 750 const form_location = try std.fmt.allocPrint(allocator, "{s}/patches/new", .{base}); 751 defer allocator.free(form_location); 752 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(failure, title, tags, description, target_branch, source_branch)); 753 }; 754 }, 755 } 756 }, 757 } 758 } 759 760 const location = try std.fmt.allocPrint(allocator, "{s}/{s}:{s}", .{ base, @tagName(kind), &event_id_hex }); 761 defer allocator.free(location); 762 try request.respond("", .{ 763 .status = .see_other, 764 .extra_headers = &.{.{ .name = "location", .value = location }}, 765 }); 766 } 767 768 const CommentBaseParts = struct { 769 repo_base: []const u8, 770 thread_kind: evt.EventKind, 771 thread_id: [evt.event_id_size]u8, 772 comment_id: ?[evt.event_id_size]u8, 773 }; 774 775 fn commentBaseParts(base: []const u8) ?CommentBaseParts { 776 const route = ui.RoutablePage.fromUrl(base) orelse ui.RoutablePage.fromUrlLocal(base) orelse return null; 777 const identity, const thread_kind, const thread_hex, const comment_hex = switch (route) { 778 .repo_issues => |*issue| .{ issue.name.slice(), evt.EventKind.issue, issue.selected.slice(), issue.comment.slice() }, 779 .repo_patches => |*patch| .{ patch.name.slice(), evt.EventKind.patch, patch.selected.slice(), patch.comment.slice() }, 780 .repo_discussions => |*discussion| .{ discussion.name.slice(), evt.EventKind.discuss, discussion.selected.slice(), discussion.comment.slice() }, 781 else => return null, 782 }; 783 const thread_id = evt.parseEventId(thread_hex) catch return null; 784 const comment_id = if (comment_hex.len == 0) null else evt.parseEventId(comment_hex) catch return null; 785 const repo_base_len = if (identity.len == 0) 0 else "/repo/".len + identity.len; 786 return .{ .repo_base = base[0..repo_base_len], .thread_kind = thread_kind, .thread_id = thread_id, .comment_id = comment_id }; 787 } 788 789 fn handlePatchPublish( 790 io: std.Io, 791 request: *std.http.Server.Request, 792 allocator: std.mem.Allocator, 793 base: []const u8, 794 host: Host, 795 ) !void { 796 const parts = commentBaseParts(base) orelse return respondRemoveNotFound(request); 797 if (parts.thread_kind != .patch or parts.comment_id != null) return respondRemoveNotFound(request); 798 const server = switch (host) { 799 .server => |server| server, 800 .local => return respondRemoveNotFound(request), 801 }; 802 var author_arena = std.heap.ArenaAllocator.init(allocator); 803 defer author_arena.deinit(); 804 // only the draft's author may publish it, which publish checks 805 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return; 806 const user_id = actor.user_id orelse return respondLoginRequired(request); 807 const author = actor.author; 808 809 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 810 defer request_repo.deinit(allocator); 811 const repo_id = evt.parseEventId(std.fs.path.basename(request_repo.source.path)) catch return respondRemoveNotFound(request); 812 var target_repo = try rp.Repo(.xit, .{}).open(io, allocator, request_repo.source.localInitOpts()); 813 defer target_repo.deinit(io, allocator); 814 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 815 defer admin_repo.deinit(io, allocator); 816 const id = std.fmt.bytesToHex(parts.thread_id, .lower); 817 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(server.admin_repo_path) orelse ".", "repos" }); 818 defer allocator.free(repos_dir); 819 const fork_path = try fork.forkPath(allocator, repos_dir, &id); 820 defer allocator.free(fork_path); 821 try pch.publish(.{}, io, allocator, &admin_repo, &target_repo, fork_path, .{ 822 .id = id, 823 .user_id = user_id, 824 .repo_id = repo_id, 825 .author = author, 826 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 827 }); 828 try request.respond("", .{ 829 .status = .see_other, 830 .extra_headers = &.{.{ .name = "location", .value = base }}, 831 }); 832 } 833 834 fn handlePatchMerge( 835 io: std.Io, 836 request: *std.http.Server.Request, 837 allocator: std.mem.Allocator, 838 base: []const u8, 839 host: Host, 840 revision: evt.Patch.MergeRevision, 841 ) !void { 842 const parts = commentBaseParts(base) orelse return respondRemoveNotFound(request); 843 if (parts.thread_kind != .patch or parts.comment_id != null) return respondRemoveNotFound(request); 844 const server = switch (host) { 845 .server => |server| server, 846 .local => return respondRemoveNotFound(request), 847 }; 848 var author_arena = std.heap.ArenaAllocator.init(allocator); 849 defer author_arena.deinit(); 850 const author = ((try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .write)) orelse return).author; 851 852 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 853 defer request_repo.deinit(allocator); 854 var target_repo = try rp.Repo(.xit, .{}).open(io, allocator, request_repo.source.localInitOpts()); 855 defer target_repo.deinit(io, allocator); 856 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 857 defer admin_repo.deinit(io, allocator); 858 859 const id = std.fmt.bytesToHex(parts.thread_id, .lower); 860 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(server.admin_repo_path) orelse ".", "repos" }); 861 defer allocator.free(repos_dir); 862 pch.mergeAndRemoveFork(.{}, io, allocator, repos_dir, &admin_repo, &target_repo, .{ 863 .id = id, 864 .revision = revision, 865 .author = author, 866 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 867 }) catch |err| switch (err) { 868 error.MergeConflict => return request.respond("merge conflict", .{ 869 .status = .conflict, 870 .keep_alive = false, 871 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 872 }), 873 error.MergeCheckUnavailable, error.PatchOutOfDate, error.PatchDataUnavailable => {}, 874 else => return err, 875 }; 876 877 const location = try std.fmt.allocPrint(allocator, "{s}/patch:{s}", .{ parts.repo_base, &id }); 878 defer allocator.free(location); 879 try request.respond("", .{ 880 .status = .see_other, 881 .keep_alive = false, 882 .extra_headers = &.{.{ .name = "location", .value = location }}, 883 }); 884 } 885 886 // create a reply and redirect to its permalink. 887 fn handleCommentNew( 888 io: std.Io, 889 request: *std.http.Server.Request, 890 allocator: std.mem.Allocator, 891 base: []const u8, 892 host: Host, 893 ) !void { 894 const not_found = "comment parent not found"; 895 const parts = commentBaseParts(base) orelse { 896 try request.respond(not_found, .{ 897 .status = .not_found, 898 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 899 }); 900 return; 901 }; 902 903 var author_arena = std.heap.ArenaAllocator.init(allocator); 904 defer author_arena.deinit(); 905 const author = ((try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return).author; 906 907 const form_body = try readFormBody(request, allocator); 908 defer allocator.free(form_body); 909 const body_crlf = (try parseFormField(allocator, form_body, "body")) orelse try allocator.dupe(u8, ""); 910 defer allocator.free(body_crlf); 911 const body = try std.mem.replaceOwned(u8, allocator, body_crlf, "\r\n", "\n"); 912 defer allocator.free(body); 913 914 if (!evt.Comment.fieldsValid(body)) { 915 const form_location = try std.fmt.allocPrint(allocator, "{s}/new", .{base}); 916 defer allocator.free(form_location); 917 try request.respond("", .{ 918 .status = .see_other, 919 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 920 }); 921 return; 922 } 923 924 const thread_id_hex = std.fmt.bytesToHex(parts.thread_id, .lower); 925 const parent_id_hex = std.fmt.bytesToHex(parts.comment_id orelse parts.thread_id, .lower); 926 927 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse { 928 try request.respond(not_found, .{ 929 .status = .not_found, 930 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 931 }); 932 return; 933 }; 934 defer request_repo.deinit(allocator); 935 const source = request_repo.source; 936 var event_id_hex: [evt.event_id_size * 2]u8 = undefined; 937 switch (source.repo_kind) { 938 inline else => |repo_kind| { 939 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 940 defer any_repo.deinit(io, allocator); 941 switch (any_repo) { 942 inline else => |*repo| event_id_hex = try evt.Comment.create(std.meta.activeTag(host), repo_kind, repo.self_repo_opts, io, allocator, repo, &thread_id_hex, &parent_id_hex, body, author), 943 } 944 }, 945 } 946 947 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 }); 948 defer allocator.free(location); 949 try request.respond("", .{ 950 .status = .see_other, 951 .extra_headers = &.{.{ .name = "location", .value = location }}, 952 }); 953 } 954 955 const AttachmentRequest = struct { 956 repo_base: []const u8, 957 id: [evt.event_id_size]u8, 958 }; 959 960 // an attachment url is its repo's base and the attachment's event id 961 fn attachmentRequest(path: []const u8) ?AttachmentRequest { 962 const infix = "/attachment:"; 963 const at = std.mem.lastIndexOf(u8, path, infix) orelse return null; 964 const tail = path[at + infix.len ..]; 965 const id = evt.parseEventId(tail) catch return null; 966 return .{ .repo_base = path[0..at], .id = id }; 967 } 968 969 // serve an attachment's bytes from the repo its url names 970 fn serveAttachment( 971 io: std.Io, 972 request: *std.http.Server.Request, 973 allocator: std.mem.Allocator, 974 attachment: AttachmentRequest, 975 host: Host, 976 ) !void { 977 if (!try mayRead(io, allocator, request, host, attachment.repo_base)) return respondAttachmentNotFound(request); 978 const request_repo = (try requestRepoSource(io, allocator, host, attachment.repo_base)) orelse return respondAttachmentNotFound(request); 979 defer request_repo.deinit(allocator); 980 const source = request_repo.source; 981 switch (source.repo_kind) { 982 inline else => |repo_kind| { 983 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 984 defer any_repo.deinit(io, allocator); 985 switch (any_repo) { 986 inline else => |*repo| try sendAttachment(repo_kind, repo.self_repo_opts, io, request, allocator, repo, &attachment.id), 987 } 988 }, 989 } 990 } 991 992 fn sendAttachment( 993 comptime repo_kind: rp.RepoKind, 994 comptime repo_opts: rp.RepoOpts(repo_kind), 995 io: std.Io, 996 request: *std.http.Server.Request, 997 allocator: std.mem.Allocator, 998 repo: *rp.Repo(repo_kind, repo_opts), 999 id: *const [evt.event_id_size]u8, 1000 ) !void { 1001 var arena = std.heap.ArenaAllocator.init(allocator); 1002 defer arena.deinit(); 1003 1004 const DB = evt.EventDB(repo_opts.hash); 1005 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; 1006 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1007 const haxy_moment = (if (event_db_maybe) |*event_db| 1008 evt.currentMomentFromDb(repo_opts.hash, event_db.db) 1009 else if (repo_kind == .git) 1010 return respondAttachmentNotFound(request) 1011 else 1012 evt.currentMoment(repo_opts, repo)) catch return respondAttachmentNotFound(request); 1013 1014 const record = (try evt.Attachment.readById(DB, repo_opts.hash, haxy_moment, &arena, id)) orelse return respondAttachmentNotFound(request); 1015 if (record.removed) return respondAttachmentNotFound(request); 1016 if (record.blob_oid.len != hash.hexLen(repo_opts.hash)) return respondAttachmentNotFound(request); 1017 const blob_oid: *const [hash.hexLen(repo_opts.hash)]u8 = @ptrCast(record.blob_oid.ptr); 1018 1019 var moment = repo.core.latestMoment() catch return respondAttachmentNotFound(request); 1020 const state = rp.Repo(repo_kind, repo_opts).State(.read_only){ .core = &repo.core, .extra = .{ .moment = &moment } }; 1021 var object_reader = obj.ObjectReader(repo_kind, repo_opts).init(state, io, allocator, blob_oid) catch return respondAttachmentNotFound(request); 1022 defer object_reader.deinit(); 1023 if (object_reader.header().kind != .blob) return respondAttachmentNotFound(request); 1024 1025 const content_type = attachmentContentType(record.name); 1026 const encoded_name = try ui.urlEncodeRef(allocator, record.name); 1027 defer allocator.free(encoded_name); 1028 const disposition = try std.fmt.allocPrint(allocator, "{s}; filename*=UTF-8''{s}", .{ if (content_type == null) "attachment" else "inline", encoded_name }); 1029 defer allocator.free(disposition); 1030 1031 var send_buf: [8192]u8 = undefined; 1032 var body = try request.respondStreaming(&send_buf, .{ 1033 .content_length = object_reader.header().size, 1034 .respond_options = .{ 1035 .extra_headers = &.{ 1036 .{ .name = "content-type", .value = content_type orelse "application/octet-stream" }, 1037 .{ .name = "content-disposition", .value = disposition }, 1038 // uploaded bytes are never sniffed into a type that could run 1039 // as script on this origin 1040 .{ .name = "x-content-type-options", .value = "nosniff" }, 1041 }, 1042 }, 1043 }); 1044 _ = try object_reader.interface.streamRemaining(&body.writer); 1045 try body.end(); 1046 } 1047 1048 // the images a browser renders safely inline. anything else downloads as 1049 // opaque bytes, so an uploaded page can't run on this origin. 1050 fn attachmentContentType(name: []const u8) ?[]const u8 { 1051 const types = [_]struct { ext: []const u8, value: []const u8 }{ 1052 .{ .ext = ".png", .value = "image/png" }, 1053 .{ .ext = ".jpg", .value = "image/jpeg" }, 1054 .{ .ext = ".jpeg", .value = "image/jpeg" }, 1055 .{ .ext = ".gif", .value = "image/gif" }, 1056 .{ .ext = ".webp", .value = "image/webp" }, 1057 }; 1058 for (types) |entry| { 1059 if (name.len > entry.ext.len and std.ascii.eqlIgnoreCase(name[name.len - entry.ext.len ..], entry.ext)) return entry.value; 1060 } 1061 return null; 1062 } 1063 1064 fn respondAttachmentNotFound(request: *std.http.Server.Request) !void { 1065 try request.respond("attachment not found", .{ 1066 .status = .not_found, 1067 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1068 }); 1069 } 1070 1071 fn respondAttachmentParentNotFound(request: *std.http.Server.Request) !void { 1072 try request.respond("attachment parent not found", .{ 1073 .status = .not_found, 1074 .keep_alive = false, 1075 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1076 }); 1077 } 1078 1079 // the upload declares its file's name here, since the body is the file itself 1080 const attachment_name_header = "x-attachment-name"; 1081 1082 const AttachParentParts = struct { 1083 repo_base: []const u8, 1084 kind: evt.EventKind, 1085 id_bytes: [evt.event_id_size]u8, 1086 }; 1087 1088 // what an attachment hangs off: the `<kind>:<id>` segment the form's page ends 1089 // with, whatever kind that is 1090 fn attachParentParts(base: []const u8) ?AttachParentParts { 1091 const segment_at = std.mem.lastIndexOfScalar(u8, base, '/') orelse return null; 1092 const segment = base[segment_at + 1 ..]; 1093 const colon_at = std.mem.lastIndexOfScalar(u8, segment, ':') orelse return null; 1094 const kind = std.meta.stringToEnum(evt.EventKind, segment[0..colon_at]) orelse return null; 1095 const id_bytes = evt.parseEventId(segment[colon_at + 1 ..]) catch return null; 1096 return .{ .repo_base = base[0..segment_at], .kind = kind, .id_bytes = id_bytes }; 1097 } 1098 1099 // attach the uploaded file to the event the url names, then reload. the file is 1100 // the whole request body, so it streams from the socket into the object store 1101 // without being buffered. 1102 fn handleAttach( 1103 io: std.Io, 1104 request: *std.http.Server.Request, 1105 allocator: std.mem.Allocator, 1106 base: []const u8, 1107 host: Host, 1108 ) !void { 1109 const parts = attachParentParts(base) orelse return respondAttachmentParentNotFound(request); 1110 1111 var author_arena = std.heap.ArenaAllocator.init(allocator); 1112 defer author_arena.deinit(); 1113 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return; 1114 const author = actor.author; 1115 // an attachment changes the event it hangs off 1116 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondAttachmentParentNotFound(request); 1117 defer request_repo.deinit(allocator); 1118 const source = request_repo.source; 1119 if (!try source.canModify(io, allocator, actor, parts.kind, &parts.id_bytes)) return respondForbidden(request); 1120 1121 const name = (try attachmentName(allocator, request)) orelse return respondUploadError(request, .bad_request, "attachment needs a name"); 1122 defer allocator.free(name); 1123 if (!evt.Attachment.nameValid(name)) return respondUploadError(request, .bad_request, "invalid attachment name"); 1124 1125 const size = request.head.content_length orelse return respondUploadError(request, .length_required, "attachments must declare a content length"); 1126 if (size == 0) return respondUploadError(request, .bad_request, "attachment is empty"); 1127 if (size > evt.Attachment.max_size) return respondUploadError(request, .payload_too_large, "attachment is too large"); 1128 1129 const parent_id_hex = std.fmt.bytesToHex(parts.id_bytes, .lower); 1130 1131 var body_buf: [4096]u8 = undefined; 1132 const blob: evt.Blob = .{ .name = name, .size = size, .reader = try request.readerExpectContinue(&body_buf) }; 1133 1134 switch (source.repo_kind) { 1135 inline else => |repo_kind| { 1136 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1137 defer any_repo.deinit(io, allocator); 1138 switch (any_repo) { 1139 inline else => |*repo| _ = evt.Attachment.create(std.meta.activeTag(host), repo_kind, repo.self_repo_opts, io, allocator, repo, &parent_id_hex, blob, author) catch |err| switch (err) { 1140 error.ParentNotFound => return respondAttachmentParentNotFound(request), 1141 else => return err, 1142 }, 1143 } 1144 }, 1145 } 1146 1147 // the client reloads the page itself 1148 try request.respond("", .{ .status = .no_content, .keep_alive = false }); 1149 } 1150 1151 // the name the upload declares for its file, percent-encoded so it survives a 1152 // header 1153 fn attachmentName(allocator: std.mem.Allocator, request: *std.http.Server.Request) !?[]u8 { 1154 var iter = request.iterateHeaders(); 1155 while (iter.next()) |header| { 1156 if (!std.ascii.eqlIgnoreCase(header.name, attachment_name_header)) continue; 1157 return try decodeFormValue(allocator, header.value); 1158 } 1159 return null; 1160 } 1161 1162 // an upload that failed leaves the body partly read, so the connection closes 1163 fn respondUploadError(request: *std.http.Server.Request, status: std.http.Status, message: []const u8) !void { 1164 try request.respond(message, .{ 1165 .status = status, 1166 .keep_alive = false, 1167 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1168 }); 1169 } 1170 1171 // re-emit the comment `parts` names with a new body, in the repo the host 1172 // resolves the base to. 1173 fn updateComment( 1174 io: std.Io, 1175 allocator: std.mem.Allocator, 1176 host: Host, 1177 parts: CommentBaseParts, 1178 body: []const u8, 1179 author: evt.CommitAuthor, 1180 ) !void { 1181 const comment_id = parts.comment_id orelse return error.NotFound; 1182 const thread_id = std.fmt.bytesToHex(parts.thread_id, .lower); 1183 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return error.NotFound; 1184 defer request_repo.deinit(allocator); 1185 const source = request_repo.source; 1186 switch (source.repo_kind) { 1187 inline else => |repo_kind| { 1188 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1189 defer any_repo.deinit(io, allocator); 1190 switch (any_repo) { 1191 inline else => |*repo| try evt.Comment.update(std.meta.activeTag(host), repo_kind, repo.self_repo_opts, io, allocator, repo, &thread_id, &comment_id, body, author), 1192 } 1193 }, 1194 } 1195 } 1196 1197 // edit actions share a suffix; the base identifies the event being edited. 1198 fn handleEdit( 1199 io: std.Io, 1200 request: *std.http.Server.Request, 1201 allocator: std.mem.Allocator, 1202 base: []const u8, 1203 host: Host, 1204 ) !void { 1205 const parts = commentBaseParts(base) orelse return respondRemoveNotFound(request); 1206 if (parts.comment_id != null) return handleCommentEdit(io, request, allocator, base, host, parts); 1207 return handleThreadEdit(io, request, allocator, base, host, parts); 1208 } 1209 1210 // replace the body of the comment the url names, then redirect to its 1211 // permalink. 1212 fn handleCommentEdit( 1213 io: std.Io, 1214 request: *std.http.Server.Request, 1215 allocator: std.mem.Allocator, 1216 base: []const u8, 1217 host: Host, 1218 parts: CommentBaseParts, 1219 ) !void { 1220 var author_arena = std.heap.ArenaAllocator.init(allocator); 1221 defer author_arena.deinit(); 1222 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return; 1223 const author = actor.author; 1224 // edits only reach here for a comment 1225 const comment_id = parts.comment_id orelse unreachable; 1226 { 1227 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1228 defer request_repo.deinit(allocator); 1229 if (!try request_repo.source.canModify(io, allocator, actor, .comment, &comment_id)) return respondForbidden(request); 1230 } 1231 1232 const form_body = try readFormBody(request, allocator); 1233 defer allocator.free(form_body); 1234 const body_crlf = (try parseFormField(allocator, form_body, "body")) orelse try allocator.dupe(u8, ""); 1235 defer allocator.free(body_crlf); 1236 const body = try std.mem.replaceOwned(u8, allocator, body_crlf, "\r\n", "\n"); 1237 defer allocator.free(body); 1238 1239 if (!evt.Comment.fieldsValid(body)) { 1240 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1241 defer allocator.free(form_location); 1242 try request.respond("", .{ 1243 .status = .see_other, 1244 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1245 }); 1246 return; 1247 } 1248 1249 const not_found = "comment not found"; 1250 updateComment(io, allocator, host, parts, body, author) catch |err| switch (err) { 1251 error.NotFound => { 1252 try request.respond(not_found, .{ 1253 .status = .not_found, 1254 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1255 }); 1256 return; 1257 }, 1258 else => |e| return e, 1259 }; 1260 1261 try request.respond("", .{ 1262 .status = .see_other, 1263 .extra_headers = &.{.{ .name = "location", .value = base }}, 1264 }); 1265 } 1266 1267 fn updateThread( 1268 comptime Event: type, 1269 io: std.Io, 1270 allocator: std.mem.Allocator, 1271 host: Host, 1272 repo_base: []const u8, 1273 id: *const [evt.event_id_size]u8, 1274 update: Event.Update, 1275 author: evt.CommitAuthor, 1276 ) !void { 1277 const request_repo = (try requestRepoSource(io, allocator, host, repo_base)) orelse return error.NotFound; 1278 defer request_repo.deinit(allocator); 1279 const source = request_repo.source; 1280 switch (source.repo_kind) { 1281 inline else => |repo_kind| { 1282 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1283 defer any_repo.deinit(io, allocator); 1284 switch (any_repo) { 1285 inline else => |*repo| try Event.update(std.meta.activeTag(host), repo_kind, repo.self_repo_opts, io, allocator, repo, id, update, author), 1286 } 1287 }, 1288 } 1289 } 1290 1291 const RemoveParts = struct { 1292 repo_base: []const u8, 1293 kind: evt.EventKind, 1294 id: [evt.event_id_size]u8, 1295 }; 1296 1297 // split a remove url into the repo and event it names 1298 fn removeParts(base: []const u8) ?RemoveParts { 1299 if (attachmentRequest(base)) |attachment| { 1300 const parent = attachParentParts(attachment.repo_base) orelse return null; 1301 return .{ 1302 .repo_base = parent.repo_base, 1303 .kind = .attach, 1304 .id = attachment.id, 1305 }; 1306 } 1307 if (commentBaseParts(base)) |thread| return .{ 1308 .repo_base = thread.repo_base, 1309 .kind = if (thread.comment_id != null) .comment else thread.thread_kind, 1310 .id = thread.comment_id orelse thread.thread_id, 1311 }; 1312 return null; 1313 } 1314 1315 // remove the event named by the form's url 1316 fn handleRemove( 1317 io: std.Io, 1318 request: *std.http.Server.Request, 1319 allocator: std.mem.Allocator, 1320 base: []const u8, 1321 host: Host, 1322 ) !void { 1323 const parts = removeParts(base) orelse return respondRemoveNotFound(request); 1324 1325 var author_arena = std.heap.ArenaAllocator.init(allocator); 1326 defer author_arena.deinit(); 1327 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return; 1328 const author = actor.author; 1329 1330 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1331 defer request_repo.deinit(allocator); 1332 const source = request_repo.source; 1333 1334 if (parts.kind == .patch) switch (host) { 1335 .server => |server| { 1336 const user_id = actor.user_id orelse return respondLoginRequired(request); 1337 1338 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 1339 defer admin_repo.deinit(io, allocator); 1340 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin_repo); 1341 const record = try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, &author_arena, &parts.id); 1342 if (record) |fork_record| { 1343 const repo_id = evt.parseEventId(std.fs.path.basename(source.path)) catch return respondRemoveNotFound(request); 1344 if (!fork_record.removed and fork_record.event.stage == .draft and std.mem.eql(u8, fork_record.event.repo_id, &repo_id)) { 1345 const id = std.fmt.bytesToHex(parts.id, .lower); 1346 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(server.admin_repo_path) orelse ".", "repos" }); 1347 defer allocator.free(repos_dir); 1348 try fork.remove(io, allocator, repos_dir, &admin_repo, &id, &user_id, author); 1349 1350 const location = try std.fmt.allocPrint(allocator, "{s}/patches/drafts", .{parts.repo_base}); 1351 defer allocator.free(location); 1352 try request.respond("", .{ 1353 .status = .see_other, 1354 .keep_alive = false, 1355 .extra_headers = &.{.{ .name = "location", .value = location }}, 1356 }); 1357 return; 1358 } 1359 } 1360 }, 1361 .local => {}, 1362 }; 1363 1364 // a draft is its author's alone, which its removal above checks 1365 if (!try source.canModify(io, allocator, actor, parts.kind, &parts.id)) return respondForbidden(request); 1366 1367 switch (source.repo_kind) { 1368 inline else => |repo_kind| { 1369 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1370 defer any_repo.deinit(io, allocator); 1371 switch (any_repo) { 1372 inline else => |*repo| evt.remove(std.meta.activeTag(host), .repo, repo_kind, repo.self_repo_opts, io, allocator, repo, &parts.id, parts.kind, author) catch |err| switch (err) { 1373 error.EventNotFound => return respondRemoveNotFound(request), 1374 else => |e| return e, 1375 }, 1376 } 1377 }, 1378 } 1379 1380 const id = std.fmt.bytesToHex(parts.id, .lower); 1381 const location = try std.fmt.allocPrint(allocator, "{s}/event:{s}/kind:{s}", .{ parts.repo_base, &id, @tagName(parts.kind) }); 1382 defer allocator.free(location); 1383 try request.respond("", .{ 1384 .status = .see_other, 1385 .keep_alive = false, 1386 .extra_headers = &.{.{ .name = "location", .value = location }}, 1387 }); 1388 } 1389 1390 fn respondRemoveNotFound(request: *std.http.Server.Request) !void { 1391 try request.respond("event not found", .{ 1392 .status = .not_found, 1393 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1394 }); 1395 } 1396 1397 fn updateDiscussion( 1398 io: std.Io, 1399 allocator: std.mem.Allocator, 1400 host: Host, 1401 repo_base: []const u8, 1402 id: *const [evt.event_id_size]u8, 1403 title: []const u8, 1404 tags: []const u8, 1405 description: []const u8, 1406 author: evt.CommitAuthor, 1407 ) !void { 1408 const request_repo = (try requestRepoSource(io, allocator, host, repo_base)) orelse return error.NotFound; 1409 defer request_repo.deinit(allocator); 1410 const source = request_repo.source; 1411 switch (source.repo_kind) { 1412 inline else => |repo_kind| { 1413 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1414 defer any_repo.deinit(io, allocator); 1415 switch (any_repo) { 1416 inline else => |*repo| try evt.Discussion.update(std.meta.activeTag(host), repo_kind, repo.self_repo_opts, io, allocator, repo, id, title, tags, description, author), 1417 } 1418 }, 1419 } 1420 } 1421 1422 // set the status of the issue the url names (base is 1423 // "/repo/<owner>/<name>/issue:<id>", identity elided in local mode) by 1424 // re-emitting its event, then redirect back to it 1425 fn handleThreadStatus( 1426 io: std.Io, 1427 request: *std.http.Server.Request, 1428 allocator: std.mem.Allocator, 1429 base: []const u8, 1430 host: Host, 1431 open: bool, 1432 ) !void { 1433 const not_found = "thread not found"; 1434 const parts = commentBaseParts(base) orelse { 1435 try request.respond(not_found, .{ 1436 .status = .not_found, 1437 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1438 }); 1439 return; 1440 }; 1441 1442 var author_arena = std.heap.ArenaAllocator.init(allocator); 1443 defer author_arena.deinit(); 1444 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return; 1445 const author = actor.author; 1446 { 1447 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1448 defer request_repo.deinit(allocator); 1449 if (!try request_repo.source.canModify(io, allocator, actor, parts.thread_kind, &parts.thread_id)) return respondForbidden(request); 1450 } 1451 1452 (switch (parts.thread_kind) { 1453 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .status = if (open) .open else .closed }, author), 1454 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .status = if (open) .open else .closed }, author), 1455 else => return respondRemoveNotFound(request), 1456 }) catch |err| switch (err) { 1457 error.NotFound => { 1458 try request.respond(not_found, .{ 1459 .status = .not_found, 1460 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1461 }); 1462 return; 1463 }, 1464 else => |e| return e, 1465 }; 1466 1467 // like logout, this is a bodyless POST, so close the connection rather than 1468 // letting the keep-alive path try to discard a body that isn't framed. 1469 try request.respond("", .{ 1470 .status = .see_other, 1471 .keep_alive = false, 1472 .extra_headers = &.{.{ .name = "location", .value = base }}, 1473 }); 1474 } 1475 1476 // replace a thread's editable fields. 1477 fn handleThreadEdit( 1478 io: std.Io, 1479 request: *std.http.Server.Request, 1480 allocator: std.mem.Allocator, 1481 base: []const u8, 1482 host: Host, 1483 parts: CommentBaseParts, 1484 ) !void { 1485 var author_arena = std.heap.ArenaAllocator.init(allocator); 1486 defer author_arena.deinit(); 1487 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return; 1488 const author = actor.author; 1489 1490 const body = try readFormBody(request, allocator); 1491 defer allocator.free(body); 1492 1493 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 1494 defer allocator.free(title); 1495 const tags = (try parseFormField(allocator, body, "tags")) orelse try allocator.dupe(u8, ""); 1496 defer allocator.free(tags); 1497 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 1498 defer allocator.free(description_crlf); 1499 // form submission normalizes textarea line breaks to CRLF; store plain 1500 // newlines so the text renders the same on every host 1501 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 1502 defer allocator.free(description); 1503 const target_branch = (try parseFormField(allocator, body, "target_branch")) orelse try allocator.dupe(u8, ""); 1504 defer allocator.free(target_branch); 1505 1506 // invalid fields send the user back to the edit form 1507 const valid = switch (parts.thread_kind) { 1508 .issue => evt.Issue.fieldsValid(title, tags), 1509 .patch => evt.Patch.fieldsValid(title, tags), 1510 .discuss => evt.Discussion.fieldsValid(title, tags), 1511 else => unreachable, 1512 }; 1513 if (!valid) { 1514 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1515 defer allocator.free(form_location); 1516 if (!evt.titleValid(title)) { 1517 return respondThreadFormFailure(request, allocator, host, form_location, requiredTitleFeedback(parts.thread_kind, title, tags, description, target_branch, null)); 1518 } 1519 try request.respond("", .{ 1520 .status = .see_other, 1521 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1522 }); 1523 return; 1524 } 1525 1526 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1527 defer request_repo.deinit(allocator); 1528 1529 const draft_user_id = if (parts.thread_kind == .patch) actor.user_id else null; 1530 if (draft_user_id) |user_id| { 1531 const server = switch (host) { 1532 .server => |server| server, 1533 .local => unreachable, 1534 }; 1535 if (!evt.Patch.branchValid(target_branch) or !try request_repo.source.hasBranch(io, allocator, target_branch)) { 1536 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1537 defer allocator.free(form_location); 1538 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(.invalid_target_branch, title, tags, description, target_branch, null)); 1539 } 1540 const repo_id = evt.parseEventId(std.fs.path.basename(request_repo.source.path)) catch return respondRemoveNotFound(request); 1541 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 1542 defer admin_repo.deinit(io, allocator); 1543 const id = std.fmt.bytesToHex(parts.thread_id, .lower); 1544 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(server.admin_repo_path) orelse ".", "repos" }); 1545 defer allocator.free(repos_dir); 1546 const fork_path = try fork.forkPath(allocator, repos_dir, &id); 1547 defer allocator.free(fork_path); 1548 if (try pch.editDraft(.{}, io, allocator, &admin_repo, fork_path, .{ 1549 .id = id, 1550 .user_id = user_id, 1551 .repo_id = repo_id, 1552 .title = title, 1553 .tags = tags, 1554 .description = description, 1555 .target_branch = target_branch, 1556 .author = author, 1557 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1558 })) { 1559 try request.respond("", .{ 1560 .status = .see_other, 1561 .extra_headers = &.{.{ .name = "location", .value = base }}, 1562 }); 1563 return; 1564 } 1565 } 1566 1567 // a draft is its author's alone, which its edit above checks 1568 if (!try request_repo.source.canModify(io, allocator, actor, parts.thread_kind, &parts.thread_id)) return respondForbidden(request); 1569 1570 const not_found = switch (parts.thread_kind) { 1571 .issue => "issue not found", 1572 .patch => "patch not found", 1573 .discuss => "discussion not found", 1574 else => unreachable, 1575 }; 1576 (switch (parts.thread_kind) { 1577 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 1578 .title = title, 1579 .tags = tags, 1580 .description = description, 1581 } }, author), 1582 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 1583 .title = title, 1584 .tags = tags, 1585 .description = description, 1586 .target_branch = target_branch, 1587 } }, author), 1588 .discuss => updateDiscussion(io, allocator, host, parts.repo_base, &parts.thread_id, title, tags, description, author), 1589 else => unreachable, 1590 }) catch |err| switch (err) { 1591 error.NotFound => { 1592 try request.respond(not_found, .{ 1593 .status = .not_found, 1594 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1595 }); 1596 return; 1597 }, 1598 else => { 1599 if (parts.thread_kind != .patch) return err; 1600 const failure = ui.Session.FormFeedback.PatchFailure.fromError(err) orelse return err; 1601 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1602 defer allocator.free(form_location); 1603 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(failure, title, tags, description, target_branch, null)); 1604 }, 1605 }; 1606 1607 try request.respond("", .{ 1608 .status = .see_other, 1609 .extra_headers = &.{.{ .name = "location", .value = base }}, 1610 }); 1611 } 1612 1613 // resolve every conflicted field of the thread the url names 1614 fn handleThreadResolve( 1615 io: std.Io, 1616 request: *std.http.Server.Request, 1617 allocator: std.mem.Allocator, 1618 base: []const u8, 1619 host: Host, 1620 ) !void { 1621 const parts = commentBaseParts(base) orelse { 1622 try request.respond("thread not found", .{ 1623 .status = .not_found, 1624 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1625 }); 1626 return; 1627 }; 1628 1629 var author_arena = std.heap.ArenaAllocator.init(allocator); 1630 defer author_arena.deinit(); 1631 const author = ((try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .write)) orelse return).author; 1632 1633 const body = try readFormBody(request, allocator); 1634 defer allocator.free(body); 1635 1636 var field_arena = std.heap.ArenaAllocator.init(allocator); 1637 defer field_arena.deinit(); 1638 const aa = field_arena.allocator(); 1639 const title = try parseFormField(aa, body, "title"); 1640 const tags = try parseFormField(aa, body, "tags"); 1641 1642 // the hunk inputs are submitted as d0, d1, ...; form submission normalizes their 1643 // textarea line breaks to CRLF 1644 var hunks: std.ArrayList([]const u8) = .empty; 1645 var hunk_index: usize = 0; 1646 while (true) : (hunk_index += 1) { 1647 const name = try std.fmt.allocPrint(aa, "d{d}", .{hunk_index}); 1648 const submitted = (try parseFormField(aa, body, name)) orelse break; 1649 try hunks.append(aa, try std.mem.replaceOwned(u8, aa, submitted, "\r\n", "\n")); 1650 } 1651 1652 if (parts.comment_id != null or (parts.thread_kind != .issue and parts.thread_kind != .patch)) { 1653 try request.respond("thread not found", .{ 1654 .status = .not_found, 1655 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1656 }); 1657 return; 1658 } 1659 const route = ui.RoutablePage.fromUrl(base) orelse ui.RoutablePage.fromUrlLocal(base) orelse { 1660 try request.respond("thread not found", .{ 1661 .status = .not_found, 1662 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1663 }); 1664 return; 1665 }; 1666 const theirs: []const u8 = switch (route) { 1667 .repo_patches => |*patch| patch.theirs.slice(), 1668 .repo_issues => "", 1669 else => unreachable, 1670 }; 1671 const not_found = if (parts.thread_kind == .patch) "patch not found" else "issue not found"; 1672 1673 (switch (parts.thread_kind) { 1674 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 1675 .title = title, 1676 .tags = tags, 1677 .hunks = hunks.items, 1678 } }, author), 1679 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 1680 .title = title, 1681 .tags = tags, 1682 .hunks = hunks.items, 1683 .theirs = theirs, 1684 } }, author), 1685 else => unreachable, 1686 }) catch |err| switch (err) { 1687 error.NotFound => { 1688 try request.respond(not_found, .{ 1689 .status = .not_found, 1690 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1691 }); 1692 return; 1693 }, 1694 // invalid fields send the user back to the resolve form 1695 error.InvalidFields => { 1696 const form_location = try std.fmt.allocPrint(allocator, "{s}/resolve", .{base}); 1697 defer allocator.free(form_location); 1698 try request.respond("", .{ 1699 .status = .see_other, 1700 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1701 }); 1702 return; 1703 }, 1704 else => |e| return e, 1705 }; 1706 1707 try request.respond("", .{ 1708 .status = .see_other, 1709 .extra_headers = &.{.{ .name = "location", .value = base }}, 1710 }); 1711 } 1712 1713 fn handleUndo(io: std.Io, request: *std.http.Server.Request, allocator: std.mem.Allocator, base: []const u8, host: Host) !void { 1714 const route = (switch (host) { 1715 .local => ui.RoutablePage.fromUrlLocal(base), 1716 .server => ui.RoutablePage.fromUrl(base), 1717 }) orelse return respondRepoNotFound(request); 1718 if (route != .repo_undo) return respondRepoNotFound(request); 1719 const target = route.repo_undo; 1720 const index = target.index orelse return respondRepoNotFound(request); 1721 var arena = std.heap.ArenaAllocator.init(allocator); 1722 defer arena.deinit(); 1723 const repo_base = if (target.name.len == 0) "" else try std.fmt.allocPrint(arena.allocator(), "/repo/{s}", .{target.name.slice()}); 1724 _ = (try authorizeWrite(io, allocator, &arena, request, host, repo_base, .owner)) orelse return; 1725 const resolved = (try requestRepoSource(io, allocator, host, repo_base)) orelse return respondRepoNotFound(request); 1726 defer resolved.deinit(allocator); 1727 ui.Repo.Undo.execute(io, allocator, resolved.source, index) catch |err| switch (err) { 1728 error.NotFound, error.InvalidHistoryIndex, error.TransactionNotFound => return respondRepoNotFound(request), 1729 else => return err, 1730 }; 1731 const location = try (ui.RoutablePage.repoUndoRoute(target.name.slice(), null) orelse return error.RouteTooLong).toUrl(&arena); 1732 try request.respond("", .{ .status = .see_other, .keep_alive = false, .extra_headers = &.{.{ .name = "location", .value = location }} }); 1733 } 1734 1735 fn handleSync( 1736 io: std.Io, 1737 request: *std.http.Server.Request, 1738 allocator: std.mem.Allocator, 1739 base: []const u8, 1740 source: ui.RepoSource, 1741 ) !void { 1742 if (base.len != 0) { 1743 try request.respond("not found", .{ 1744 .status = .not_found, 1745 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1746 }); 1747 return; 1748 } 1749 1750 var owned_failure: ?[]u8 = null; 1751 defer if (owned_failure) |message| allocator.free(message); 1752 const failure: ?[]const u8 = blk: { 1753 owned_failure = ui.Repo.Events.sync(io, allocator, source) catch |err| break :blk @errorName(err); 1754 break :blk owned_failure; 1755 }; 1756 if (failure) |message| { 1757 var encoded: std.Io.Writer.Allocating = .init(allocator); 1758 defer encoded.deinit(); 1759 try std.Uri.Component.percentEncode(&encoded.writer, message, struct { 1760 fn isUnreserved(c: u8) bool { 1761 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 1762 } 1763 }.isUnreserved); 1764 const cookie = try std.fmt.allocPrint( 1765 allocator, 1766 local_flash_cookie ++ "=" ++ local_sync_failure_prefix ++ "{s}; Path=/; HttpOnly; SameSite=Strict", 1767 .{encoded.written()}, 1768 ); 1769 defer allocator.free(cookie); 1770 try request.respond("", .{ 1771 .status = .see_other, 1772 .extra_headers = &.{ 1773 .{ .name = "location", .value = "/events" }, 1774 .{ .name = "set-cookie", .value = cookie }, 1775 }, 1776 }); 1777 return; 1778 } 1779 1780 try request.respond("", .{ 1781 .status = .see_other, 1782 .extra_headers = &.{ 1783 .{ .name = "location", .value = "/events" }, 1784 .{ .name = "set-cookie", .value = local_flash_cookie ++ "=; Path=/; Max-Age=0" }, 1785 }, 1786 }); 1787 } 1788 1789 fn renderIndexHtml( 1790 io: std.Io, 1791 allocator: std.mem.Allocator, 1792 host: Host, 1793 session_token: ?[]const u8, 1794 session_data: ui.Session.Data, 1795 ) ![]const u8 { 1796 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 1797 1798 var page_arena = std.heap.ArenaAllocator.init(allocator); 1799 defer page_arena.deinit(); 1800 1801 // the server admin repo must outlive the page build, since the session's 1802 // moment reads from it. 1803 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 1804 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 1805 1806 var session = switch (host) { 1807 .server => |server| blk: { 1808 // open the admin repo to read live user/repo data. 1809 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 1810 const repo = if (repo_maybe) |*repo| repo else unreachable; 1811 var session = try ui.Session.init(&page_arena, repo, session_data); 1812 // the session dropped a user whose account was removed, so revoke 1813 // the token that named them 1814 if (session_token) |token| { 1815 if (session.data.user_id == null) server.session_store.remove(token); 1816 } 1817 // give the page builders filesystem access to the on-disk repos (a 1818 // sibling "repos" dir next to the admin repo) so the Repo page can 1819 // read its files. 1820 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(server.admin_repo_path) orelse ".", "repos" }); 1821 break :blk session; 1822 }, 1823 .local => |local| ui.Session{ 1824 .data = session_data, 1825 .arena = &page_arena, 1826 .page_arena = &page_arena, 1827 .local = local, 1828 }, 1829 }; 1830 session.io = io; 1831 1832 var page = try ui.Page.init(session.page_arena, &session, session.data.current_page); 1833 var root = try ui.initRoot(allocator, &page, &session); 1834 defer root.deinit(allocator); 1835 1836 const snapshot: ui.Snapshot = .{ .page = page, .session = session.data }; 1837 1838 const content = try generateHtml(allocator, &root, &session); 1839 defer allocator.free(content); 1840 1841 // serialize the snapshot so the wasm side can parse it back without making 1842 // a second request. it's embedded raw in a <script type="application/json"> 1843 // block, whose content is raw text terminated only by "</script". in json, 1844 // '<' appears solely inside string values, so escaping every '<' (and '>' 1845 // for good measure) to its \uXXXX form yields equivalent json that can't 1846 // break out of the tag. 1847 var json: std.Io.Writer.Allocating = .init(allocator); 1848 defer json.deinit(); 1849 try std.json.Stringify.value(snapshot, .{}, &json.writer); 1850 1851 var json_escaped: std.ArrayList(u8) = .empty; 1852 defer json_escaped.deinit(allocator); 1853 for (json.written()) |c| switch (c) { 1854 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 1855 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 1856 else => try json_escaped.append(allocator, c), 1857 }; 1858 1859 var out: std.ArrayList(u8) = .empty; 1860 errdefer out.deinit(allocator); 1861 { 1862 var cursor: usize = 0; 1863 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 1864 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 1865 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 1866 }) |sub| { 1867 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 1868 try out.appendSlice(allocator, template[cursor..idx]); 1869 try out.appendSlice(allocator, sub.replacement); 1870 cursor = idx + sub.needle.len; 1871 } 1872 try out.appendSlice(allocator, template[cursor..]); 1873 } 1874 return try out.toOwnedSlice(allocator); 1875 } 1876 1877 fn findEmbed(request_path: []const u8) ?Embed { 1878 const path = if (std.mem.eql(u8, request_path, "/")) 1879 "index.html" 1880 else if (request_path.len > 1 and request_path[0] == '/') 1881 request_path[1..] 1882 else 1883 return null; 1884 1885 for (embeds) |embed| { 1886 if (std.mem.eql(u8, path, embed.path)) return embed; 1887 } 1888 return null; 1889 } 1890 1891 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 1892 // own absolutely-positioned, natively-scrollable <div> holding its full content, 1893 // rendered recursively so nested scrolls work. 1894 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1895 const grid = root.getGrid() orelse return error.MissingGrid; 1896 const root_focus = root.getFocus(); 1897 1898 var out: std.ArrayList(u8) = .empty; 1899 errdefer out.deinit(allocator); 1900 1901 switch (root.*) { 1902 .background => |*background| { 1903 if (background.art.getGrid()) |art| { 1904 var position_buf: [64]u8 = undefined; 1905 try out.appendSlice(allocator, try std.fmt.bufPrint(&position_buf, "<div class=\"ansi-art\" aria-hidden=\"true\" style=\"left:{d}ch\">", .{grid.size.width -| art.size.width})); 1906 try renderPanel(allocator, &out, background.art.getFocus(), art, session, root_focus); 1907 try out.appendSlice(allocator, "</div>"); 1908 } 1909 }, 1910 else => {}, 1911 } 1912 try out.appendSlice(allocator, "<div class=\"grid-content\" data-key=\"panel:root\">"); 1913 try renderPanel(allocator, &out, root_focus, grid, session, root_focus); 1914 try out.appendSlice(allocator, "</div>"); 1915 try renderForms(allocator, &out, root_focus); 1916 return try out.toOwnedSlice(allocator); 1917 } 1918 1919 // render one panel — a focus subtree and its content grid — as HTML, recursing 1920 // once per web-native Scroll inside it. the root panel is the whole page; each 1921 // Scroll becomes a nested, natively-scrollable div holding its full content. 1922 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 1923 // then the child scroll divs over those holes. 1924 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid, session: *ui.Session, root_focus: *Focus) !void { 1925 // `direct` is this panel's scroll children, each drawn as an overlaid div. 1926 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 1927 // plus their descendants, which the focus tree flattens into this panel's 1928 // children): the cell hit-test below skips them so this panel doesn't claim 1929 // cells that are really rendered inside a child scroll's own panel. 1930 // (scrolls aren't nested in practice, so every scroll child is direct here.) 1931 var direct: std.ArrayList(usize) = .empty; 1932 defer direct.deinit(allocator); 1933 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 1934 defer excluded.deinit(allocator); 1935 { 1936 var it = focus.children.iterator(); 1937 while (it.next()) |e| { 1938 if (e.value_ptr.focus.scroll == null) continue; 1939 try direct.append(allocator, e.key_ptr.*); 1940 try excluded.put(allocator, e.key_ptr.*, {}); 1941 var mit = e.value_ptr.focus.children.iterator(); 1942 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 1943 } 1944 } 1945 1946 // the HTML element a run of cells is wrapped in, chosen from the cell's 1947 // focusable kind 1948 const CellTag = union(enum) { 1949 span, // clickable focusable cell 1950 a: []const u8, // clickable focusable link 1951 plain, // non-focusable, colored 1952 1953 const a_prefix = "a:"; 1954 // an "in-page" anchor: rendered as a real <a href> so it works with js 1955 // disabled, but wasm handles it without navigating. 1956 fn init(str: []const u8) @This() { 1957 if (std.mem.startsWith(u8, str, ui.raw_link_prefix)) { 1958 return .{ .a = str[ui.raw_link_prefix.len..] }; 1959 } 1960 if (std.mem.startsWith(u8, str, ui.in_page_link_prefix)) { 1961 return .{ .a = str[ui.in_page_link_prefix.len..] }; 1962 } 1963 if (std.mem.startsWith(u8, str, a_prefix)) { 1964 return .{ .a = str[a_prefix.len..] }; 1965 } 1966 return .span; 1967 } 1968 1969 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 1970 var id_buf: [32]u8 = undefined; 1971 switch (self) { 1972 .span => { 1973 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 1974 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1975 try out.appendSlice(alloc, "\""); 1976 try out.appendSlice(alloc, style_attr); 1977 try out.appendSlice(alloc, ">"); 1978 }, 1979 .a => |href| { 1980 // tabindex=-1 keeps these out of the browser's tab order 1981 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 1982 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1983 try out.appendSlice(alloc, "\" href=\""); 1984 try appendEscapedHtml(alloc, out, href); 1985 try out.appendSlice(alloc, "\""); 1986 try out.appendSlice(alloc, style_attr); 1987 try out.appendSlice(alloc, ">"); 1988 }, 1989 .plain => { 1990 try out.appendSlice(alloc, "<span"); 1991 try out.appendSlice(alloc, style_attr); 1992 try out.appendSlice(alloc, ">"); 1993 }, 1994 } 1995 } 1996 1997 fn closeTag(self: @This()) []const u8 { 1998 return switch (self) { 1999 .span, .plain => "</span>", 2000 .a => "</a>", 2001 }; 2002 } 2003 }; 2004 2005 // the focusable owning each cell, among this panel's own (skipping any 2006 // that belong to a child scroll, whose cells are drawn in their own panel). 2007 // claimed in focus order, so the first focusable over a cell keeps it. 2008 // looking every focusable up for every cell is quadratic in a long list. 2009 const owners = try allocator.alloc(?usize, grid.size.width * grid.size.height); 2010 defer allocator.free(owners); 2011 @memset(owners, null); 2012 { 2013 var it = focus.children.iterator(); 2014 while (it.next()) |entry| { 2015 const child = entry.value_ptr.*; 2016 if (child.focus.mode != .all) continue; 2017 if (excluded.contains(entry.key_ptr.*)) continue; 2018 const r = child.rect; 2019 for (@min(r.y, grid.size.height)..@min(r.y + r.size.height, grid.size.height)) |y| { 2020 for (@min(r.x, grid.size.width)..@min(r.x + r.size.width, grid.size.width)) |x| { 2021 const owner = &owners[y * grid.size.width + x]; 2022 if (owner.* == null) owner.* = entry.key_ptr.*; 2023 } 2024 } 2025 } 2026 } 2027 2028 // the cells are the volatile part of a panel. js replaces this one subtree 2029 // wholesale while retaining the panel's native controls and scroll shells. 2030 try output.appendSlice(allocator, "<div class=\"grid-cells\">"); 2031 2032 // emit this panel's grid as rows of text, coalescing adjacent cells that 2033 // share a focus id and colors into one tag (a clickable span, a link, or a 2034 // plain colored span). cells under a child scroll keep only their background. 2035 for (0..grid.size.height) |y| { 2036 var cur_id: ?usize = null; 2037 var cur_fg: ?Grid.Color = null; 2038 var cur_bg: ?Grid.Color = null; 2039 var open_tag: ?CellTag = null; 2040 var first = true; 2041 for (0..grid.size.width) |x| { 2042 const cell = (try grid.cell(x, y)).*; 2043 // a cell covered by a child scroll's viewport is drawn by that scroll's 2044 // own div, so blank its glyph and make it non-clickable here — but keep 2045 // its background, so the backdrop still shows through the scroll's 2046 // transparent div instead of a bare hole. 2047 const covered_by_scroll = blk: { 2048 for (direct.items) |id| { 2049 const r = (focus.children.get(id) orelse continue).rect; 2050 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; 2051 } 2052 break :blk false; 2053 }; 2054 // the focusable owning the cell at (x, y); none for a covered cell. 2055 const cell_id = if (covered_by_scroll) null else owners[y * grid.size.width + x]; 2056 const fg = if (covered_by_scroll) null else cell.style.fg; 2057 const bg = cell.style.bg; 2058 2059 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 2060 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2061 2062 var new_tag: ?CellTag = null; 2063 if (cell_id) |id| { 2064 if (focus.children.get(id)) |child| { 2065 new_tag = switch (child.focus.kind) { 2066 .custom => |custom| CellTag.init(custom), 2067 else => .span, 2068 }; 2069 } 2070 } 2071 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 2072 2073 if (new_tag) |t| { 2074 var style_buf: [64]u8 = undefined; 2075 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 2076 } 2077 2078 open_tag = new_tag; 2079 cur_id = cell_id; 2080 cur_fg = fg; 2081 cur_bg = bg; 2082 first = false; 2083 } 2084 2085 if (covered_by_scroll) { 2086 try appendEscapedHtml(allocator, output, " "); 2087 } else if (cell.continuation) { 2088 // the wide rune to the left was emitted 2ch wide, covering this column 2089 } else if (cell.rune) |rune| { 2090 var encoded: [4]u8 = undefined; 2091 const encoded_len = try std.unicode.utf8Encode(rune, &encoded); 2092 const rune_text = encoded[0..encoded_len]; 2093 // a double-width rune is pinned inside a 2ch span so the 2094 // fallback glyph's advance width can't shift the rest of the row 2095 const wide = x + 1 < grid.size.width and (try grid.cell(x + 1, y)).continuation; 2096 if (wide) { 2097 try output.appendSlice(allocator, "<span class=\"w2\">"); 2098 try appendEscapedHtml(allocator, output, rune_text); 2099 try output.appendSlice(allocator, "</span>"); 2100 } else { 2101 try appendEscapedHtml(allocator, output, rune_text); 2102 } 2103 } else { 2104 try appendEscapedHtml(allocator, output, " "); 2105 } 2106 } 2107 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2108 try output.append(allocator, '\n'); 2109 } 2110 try output.appendSlice(allocator, "</div>"); 2111 2112 // native controls live in their panel, beside the replaceable cells. their 2113 // stable keys let JS update layout without recreating their DOM nodes, and 2114 // being actual descendants of a scroll gives them native movement/clipping. 2115 try renderPanelControls(allocator, output, focus, session, root_focus, &excluded); 2116 2117 // each child scroll becomes a natively-scrollable div positioned over its 2118 // viewport, holding its full content rendered recursively. 2119 for (direct.items) |id| { 2120 const child = focus.children.get(id) orelse continue; 2121 const info = child.focus.scroll orelse continue; 2122 const r = child.rect; 2123 // overflow only on the axes the widget scrolls; `auto` shows a bar only 2124 // when that axis actually overflows. the other axis is clipped (hidden), 2125 // matching how the terminal Scroll handles its non-scrolling axis. 2126 const overflow = switch (info.direction) { 2127 .vert => "overflow-x:hidden;overflow-y:auto", 2128 .horiz => "overflow-x:auto;overflow-y:hidden", 2129 .both => "overflow:auto", 2130 }; 2131 // the id carries a content version so JS preserves the native scroll 2132 // position across re-renders of the same content but resets it when the 2133 // content is replaced — e.g. selecting a different commit. the widget's 2134 // scroll offset (in cells) rides along so JS can apply it when it has no 2135 // preserved position, letting a wasm-side scrollToRect (the files list 2136 // scrolling to its selected row on page load) reach the browser. 2137 var buf: [256]u8 = undefined; 2138 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, "<div class=\"scroll\" data-key=\"scroll:{d}\" data-scroll-id=\"{d}-{d}\" data-scroll-direction=\"{s}\" data-scroll-x=\"{d}\" data-scroll-y=\"{d}\" style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em;{s}\">", .{ id, id, child.focus.version, @tagName(info.direction), info.offset_x, info.offset_y, r.x, r.y, r.size.width, r.size.height, overflow })); 2139 try renderPanel(allocator, output, child.focus, info.content, session, root_focus); 2140 try output.appendSlice(allocator, "</div>"); 2141 } 2142 } 2143 2144 const form_prefix = "form:"; 2145 const form_id_prefix = "haxy-form-"; 2146 2147 fn formAction(focus: *const Focus) ?[]const u8 { 2148 return switch (focus.kind) { 2149 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) custom[form_prefix.len..] else null, 2150 else => null, 2151 }; 2152 } 2153 2154 // find the form ancestor of a flattened focus-tree child. html's `form` 2155 // attribute then associates the control with that form without requiring the 2156 // form and control to share a DOM parent. 2157 fn formOwner(root_focus: *Focus, focus_id: usize) ?usize { 2158 var id = focus_id; 2159 while (root_focus.children.get(id)) |child| { 2160 const parent_id = child.parent_id; 2161 if (parent_id == root_focus.id) return if (formAction(root_focus) != null) root_focus.id else null; 2162 const parent = root_focus.children.get(parent_id) orelse return null; 2163 if (formAction(parent.focus) != null) return parent_id; 2164 id = parent_id; 2165 } 2166 return null; 2167 } 2168 2169 fn appendFormAttribute(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus, focus_id: usize) !void { 2170 const form_id = formOwner(root_focus, focus_id) orelse return; 2171 var buf: [64]u8 = undefined; 2172 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, " form=\"" ++ form_id_prefix ++ "{d}\"", .{form_id})); 2173 } 2174 2175 fn renderPanelControls( 2176 allocator: std.mem.Allocator, 2177 output: *std.ArrayList(u8), 2178 focus: *Focus, 2179 session: *ui.Session, 2180 root_focus: *Focus, 2181 excluded: *const std.AutoHashMapUnmanaged(usize, void), 2182 ) !void { 2183 var iter = focus.children.iterator(); 2184 while (iter.next()) |entry| { 2185 const id = entry.key_ptr.*; 2186 if (excluded.contains(id)) continue; 2187 const child = entry.value_ptr.*; 2188 const r = child.rect; 2189 2190 if (r.size.width == 0 or r.size.height == 0) continue; // not laid out, rather than merely off-screen 2191 2192 switch (child.focus.kind) { 2193 .text_input, .text_input_password, .text_area => { 2194 const ti = session.text_inputs.get(id) orelse continue; 2195 2196 const inner_left = r.x + 1; 2197 const inner_top = r.y + 1; 2198 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 2199 const preserve = !ti.options.read_only; 2200 2201 if (child.focus.kind == .text_area) { 2202 const value = try ti.text(allocator); 2203 defer allocator.free(value); 2204 var id_buf: [128]u8 = undefined; 2205 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<textarea data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2206 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2207 try appendFormAttribute(allocator, output, root_focus, id); 2208 if (ti.options.name.len > 0) { 2209 try output.appendSlice(allocator, " name=\""); 2210 try appendEscapedHtml(allocator, output, ti.options.name); 2211 try output.append(allocator, '"'); 2212 } 2213 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 2214 var pos_buf: [128]u8 = undefined; 2215 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">\n", .{ inner_left, inner_top, inner_width, inner_height })); 2216 try appendEscapedHtml(allocator, output, value); 2217 try output.appendSlice(allocator, "</textarea>"); 2218 continue; 2219 } 2220 2221 var id_buf: [160]u8 = undefined; 2222 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<input type=\"{s}\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ if (child.focus.kind == .text_input_password) "password" else "text", id, id })); 2223 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2224 try appendFormAttribute(allocator, output, root_focus, id); 2225 if (ti.options.name.len > 0) { 2226 try output.appendSlice(allocator, " name=\""); 2227 try appendEscapedHtml(allocator, output, ti.options.name); 2228 try output.append(allocator, '"'); 2229 } 2230 if (child.focus.kind != .text_input_password) { 2231 const value = try ti.text(allocator); 2232 defer allocator.free(value); 2233 try output.appendSlice(allocator, " value=\""); 2234 try appendEscapedHtml(allocator, output, value); 2235 try output.append(allocator, '"'); 2236 } 2237 var pos_buf: [96]u8 = undefined; 2238 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:1em\">", .{ inner_left, inner_top, inner_width })); 2239 }, 2240 .custom => |custom| { 2241 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2242 if (formOwner(root_focus, id) == null) continue; 2243 var id_buf: [128]u8 = undefined; 2244 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2245 try appendFormAttribute(allocator, output, root_focus, id); 2246 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2247 try output.appendSlice(allocator, " formaction=\""); 2248 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 2249 try output.append(allocator, '"'); 2250 } 2251 var pos_buf: [128]u8 = undefined; 2252 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\"></button>", .{ r.x, r.y, r.size.width, r.size.height })); 2253 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 2254 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 2255 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 2256 var id_buf: [128]u8 = undefined; 2257 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "\" data-key=\"control:{d}\" data-focus-id=\"{d}\" style=\"opacity:0;left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">", .{ id, id, r.x, r.y, r.size.width, r.size.height })); 2258 } 2259 }, 2260 else => {}, 2261 } 2262 } 2263 } 2264 2265 // emit hidden form owners beside the rendered panels. their controls point 2266 // back here with the standard HTML `form` attribute. 2267 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 2268 // the focus child map preserves insertion order, which matches the order 2269 // widgets were added in code 2270 var iter = root_focus.children.iterator(); 2271 while (iter.next()) |entry| { 2272 const child = entry.value_ptr.*; 2273 const action_url = formAction(child.focus) orelse continue; 2274 2275 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 2276 var id_buf: [96]u8 = undefined; 2277 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 2278 try appendEscapedHtml(allocator, output, action_url); 2279 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 2280 } 2281 } 2282 2283 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 2284 if (a) |av| return if (b) |bv| av.eql(bv) else false; 2285 return b == null; 2286 } 2287 2288 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 2289 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 2290 // empty slice when neither is set. 2291 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 2292 if (fg == null and bg == null) return buf[0..0]; 2293 const prefix = " style=\""; 2294 @memcpy(buf[0..prefix.len], prefix); 2295 var i: usize = prefix.len; 2296 if (fg) |c| { 2297 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]; 2298 i += s.len; 2299 } 2300 if (bg) |c| { 2301 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]; 2302 i += s.len; 2303 } 2304 buf[i] = '"'; 2305 i += 1; 2306 return buf[0..i]; 2307 } 2308 2309 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2310 for (input) |ch| { 2311 switch (ch) { 2312 '&' => try out.appendSlice(allocator, "&amp;"), 2313 '<' => try out.appendSlice(allocator, "&lt;"), 2314 '>' => try out.appendSlice(allocator, "&gt;"), 2315 '"' => try out.appendSlice(allocator, "&quot;"), 2316 '\'' => try out.appendSlice(allocator, "&#39;"), 2317 else => try out.append(allocator, ch), 2318 } 2319 } 2320 } 2321 2322 // --- helpers -------------------------------------------------------------- 2323 2324 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 2325 var iter = request.iterateHeaders(); 2326 while (iter.next()) |header| { 2327 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2328 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2329 while (pairs.next()) |pair| { 2330 const trimmed = std.mem.trim(u8, pair, " \t"); 2331 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2332 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2333 return trimmed[eq + 1 ..]; 2334 } 2335 } 2336 } 2337 return null; 2338 } 2339 2340 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2341 var iter = std.mem.splitScalar(u8, body, '&'); 2342 while (iter.next()) |pair| { 2343 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2344 if (std.mem.eql(u8, pair[0..eq], key)) { 2345 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2346 } 2347 } 2348 return null; 2349 } 2350 2351 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2352 var buffer: [256]u8 = undefined; 2353 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2354 } 2355 2356 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2357 var out: std.ArrayList(u8) = .empty; 2358 errdefer out.deinit(allocator); 2359 var i: usize = 0; 2360 while (i < encoded.len) : (i += 1) { 2361 switch (encoded[i]) { 2362 '+' => try out.append(allocator, ' '), 2363 '%' => { 2364 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2365 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2366 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2367 try out.append(allocator, hi * 16 + lo); 2368 i += 2; 2369 }, 2370 else => try out.append(allocator, encoded[i]), 2371 } 2372 } 2373 return try out.toOwnedSlice(allocator); 2374 } 2375 2376 // disk-backed web session store. each login mints a random, opaque token 2377 // (not the user's id) that is stored as a file named by the token hex, whose 2378 // contents are the raw user_id bytes. authenticating a request is a lookup of 2379 // the cookie's token; logout deletes the file, revoking the session. there is 2380 // deliberately no expiry — a session lives until logout. form failures use 2381 // files in the flash subdirectory that the redirected GET consumes. the 2382 // directory is cleared whenever the server starts. 2383 pub const SessionStore = struct { 2384 io: std.Io, 2385 dir: std.Io.Dir, 2386 flash_dir: std.Io.Dir, 2387 auto_login: ?[token_hex_len]u8, 2388 2389 pub const token_hex_len = evt.event_id_size * 2; 2390 2391 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2392 try data_dir.createDirPath(io, "sessions"); 2393 const dir = try data_dir.openDir(io, "sessions", .{}); 2394 errdefer dir.close(io); 2395 try dir.deleteTree(io, "flash"); 2396 try dir.createDirPath(io, "flash"); 2397 const flash_dir = try dir.openDir(io, "flash", .{}); 2398 errdefer flash_dir.close(io); 2399 const auto_login = blk: { 2400 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2401 defer file.close(io); 2402 var token: [token_hex_len]u8 = undefined; 2403 var storage: [token_hex_len]u8 = undefined; 2404 var reader = file.reader(io, &storage); 2405 reader.interface.readSliceAll(&token) catch break :blk null; 2406 break :blk token; 2407 }; 2408 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 2409 } 2410 2411 pub fn deinit(self: SessionStore) void { 2412 self.flash_dir.close(self.io); 2413 self.dir.close(self.io); 2414 } 2415 2416 // mint a new session for user_id, returning the token hex to set as the 2417 // cookie value. 2418 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2419 var token: [evt.event_id_size]u8 = undefined; 2420 self.io.random(&token); 2421 const token_hex = std.fmt.bytesToHex(token, .lower); 2422 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2423 defer file.close(self.io); 2424 try file.writeStreamingAll(self.io, user_id); 2425 return token_hex; 2426 } 2427 2428 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 2429 var token: [evt.event_id_size]u8 = undefined; 2430 self.io.random(&token); 2431 const token_hex = std.fmt.bytesToHex(token, .lower); 2432 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 2433 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 2434 defer file.close(self.io); 2435 2436 var json: std.Io.Writer.Allocating = .init(allocator); 2437 defer json.deinit(); 2438 try std.json.Stringify.value(value, .{}, &json.writer); 2439 try file.writeStreamingAll(self.io, json.written()); 2440 return token_hex; 2441 } 2442 2443 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 2444 if (!isToken(token_hex)) return null; 2445 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 2446 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 2447 defer file.close(self.io); 2448 2449 var storage: [4096]u8 = undefined; 2450 var reader = file.reader(self.io, &storage); 2451 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 2452 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 2453 } 2454 2455 // resolve a cookie's token to its user_id. returns false (logged out) for a 2456 // missing, malformed, or unknown token. 2457 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2458 if (!isToken(token_hex)) return false; 2459 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2460 defer file.close(self.io); 2461 var storage: [evt.event_id_size]u8 = undefined; 2462 var file_reader = file.reader(self.io, &storage); 2463 file_reader.interface.readSliceAll(out) catch return false; 2464 return true; 2465 } 2466 2467 // revoke a session. a no-op for a missing or malformed token. 2468 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2469 if (!isToken(token_hex)) return; 2470 self.dir.deleteFile(self.io, token_hex) catch {}; 2471 } 2472 2473 // leave `token_hex`'s session for visitors arriving without one. only the 2474 // `try` fixture writes one. the name can't collide with a session token. 2475 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2476 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2477 defer file.close(self.io); 2478 try file.writeStreamingAll(self.io, token_hex); 2479 } 2480 2481 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2482 out.* = self.auto_login orelse return false; 2483 return true; 2484 } 2485 2486 const auto_login_name = "auto-login"; 2487 2488 // a token is exactly token_hex_len hex chars. validating before using the 2489 // value as a path keeps attacker-supplied cookies from escaping the 2490 // sessions dir (e.g. via "/" or ".." bytes). 2491 fn isToken(token_hex: []const u8) bool { 2492 if (token_hex.len != token_hex_len) return false; 2493 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2494 return true; 2495 } 2496 }; 2497