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