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