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