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