╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const obj = xit.object; 5 const hash = xit.hash; 6 const evt = @import("./event.zig"); 7 const serve_common = @import("./serve_common.zig"); 8 const ui = @import("./ui.zig"); 9 const fork = @import("./fork.zig"); 10 const pch = @import("./patch.zig"); 11 const xitui = xit.xitui; 12 const wgt = xitui.widget; 13 const Focus = xitui.focus.Focus; 14 const Grid = xitui.grid.Grid; 15 16 const cookie_name = "haxy_session"; 17 // the session cookie a login or a claimed auto-login sets; both must scope 18 // it the same way. 19 const session_cookie_fmt = cookie_name ++ "={s}; Path=/; HttpOnly; SameSite=Strict"; 20 const form_flash_cookie = "haxy_form_flash"; 21 const local_flash_cookie = "haxy_local_flash"; 22 const local_required_title_prefix = "required_title:"; 23 const local_sync_failure_prefix = "sync:"; 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(evt.HostKind) { 41 local: ui.RepoSource, 42 server: struct { 43 admin_repo_path: []const u8, 44 users_dir: []const u8, 45 session_store: SessionStore, 46 git_http_port: ?u16, 47 git_ssh_port: ?u16, 48 git_ssh_prefix: []const u8, 49 }, 50 51 // where this host's event writes go 52 pub fn event(self: Host) evt.Host { 53 return switch (self) { 54 .local => .local, 55 .server => |server| .{ .server = .{ .users_dir = server.users_dir } }, 56 }; 57 } 58 }; 59 60 // an on-disk repo resolved from a request url. server paths are owned. 61 const RequestRepoSource = struct { 62 source: ui.RepoSource, 63 owned_path: ?[]const u8 = null, 64 65 fn deinit(self: RequestRepoSource, allocator: std.mem.Allocator) void { 66 if (self.owned_path) |path| allocator.free(path); 67 } 68 }; 69 70 fn requestRepoSource(io: std.Io, allocator: std.mem.Allocator, host: Host, repo_base: []const u8) !?RequestRepoSource { 71 return switch (host) { 72 .server => |server| blk: { 73 const repo_prefix = "/repo/"; 74 if (!std.mem.startsWith(u8, repo_base, repo_prefix)) break :blk null; 75 const path = switch (try serve_common.resolveRepoPath(io, allocator, server.users_dir, server.admin_repo_path, repo_base[repo_prefix.len..], false)) { 76 .ok => |value| value, 77 .invalid, .not_found => break :blk null, 78 }; 79 break :blk .{ 80 .source = .{ .path = path, .repo_kind = .xit }, 81 .owned_path = path, 82 }; 83 }, 84 .local => |source| if (repo_base.len == 0) .{ .source = source } else null, 85 }; 86 } 87 88 pub fn handleConnection( 89 io: std.Io, 90 allocator: std.mem.Allocator, 91 stream: std.Io.net.Stream, 92 host: Host, 93 err: *std.Io.Writer, 94 ) !void { 95 var send_buffer = [_]u8{0} ** 4096; 96 var recv_buffer = [_]u8{0} ** 4096; 97 var conn_br = stream.reader(io, &recv_buffer); 98 var conn_bw = stream.writer(io, &send_buffer); 99 var http_server = std.http.Server.init(&conn_br.interface, &conn_bw.interface); 100 101 // serve multiple requests on a single connection so HTTP/1.1 keep-alive 102 // works — important for browser-native form POST: after the 303 the 103 // browser issues GET / on the same socket, and forcibly closing here 104 // would race the follow-up request into a "site can't be reached". 105 while (http_server.reader.state == .ready) { 106 var request = http_server.receiveHead() catch |receive_err| switch (receive_err) { 107 error.HttpConnectionClosing => break, 108 error.ReadFailed => break, 109 else => |e| return e, 110 }; 111 112 handleRequest(io, &request, allocator, host) catch |request_err| { 113 serve_common.logError(io, err, "web ui request failed: {s}\n", .{@errorName(request_err)}); 114 // best-effort 500. if handleRequest already started writing a 115 // response before throwing, this respond may fail too, but at 116 // that point the connection is unrecoverable anyway. 117 request.respond(@errorName(request_err), .{ 118 .status = .internal_server_error, 119 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 120 }) catch {}; 121 }; 122 } 123 } 124 125 fn handleRequest( 126 io: std.Io, 127 request: *std.http.Server.Request, 128 allocator: std.mem.Allocator, 129 host: Host, 130 ) !void { 131 const method = request.head.method; 132 const owned_target = if (method == .POST) try allocator.dupe(u8, request.head.target) else null; 133 defer if (owned_target) |target| allocator.free(target); 134 const uri = try std.Uri.parseAfterScheme("", owned_target orelse request.head.target); 135 const path = uri.path.percent_encoded; 136 137 // POST routes can be scoped by any page, so they can redirect using 138 // the base of the URL. this allows logging in to keep you on the page 139 // you were on. local mode has no accounts, so only the repo routes. 140 if (method == .POST) { 141 switch (host) { 142 .server => |server| { 143 // "repo/new" and "user/new" come before "new", which would claim them 144 const PostRoute = enum { login, logout, @"repo/new", @"user/new", new, edit, remove, open, close, resolve, publish, merge, squash, attach, undo, clear }; 145 inline for (@typeInfo(PostRoute).@"enum".fields) |field| { 146 const suffix = "/" ++ field.name; 147 if (std.mem.endsWith(u8, path, suffix)) { 148 const base = path[0 .. path.len - suffix.len]; 149 return switch (@field(PostRoute, field.name)) { 150 .login => handleLogin(io, request, allocator, base, server.admin_repo_path, server.session_store), 151 .logout => handleLogout(request, base, server.session_store), 152 .@"repo/new" => handleRepoNew(io, request, allocator, path, server.admin_repo_path, server.users_dir, server.session_store), 153 .@"user/new" => handleUserNew(io, request, allocator, path, server.admin_repo_path, server.users_dir, server.session_store), 154 .new => handleNew(io, request, allocator, base, host), 155 .edit => handleEdit(io, request, allocator, base, host), 156 .remove => handleRemove(io, request, allocator, base, host), 157 .open => handleThreadStatus(io, request, allocator, base, host, true), 158 .close => handleThreadStatus(io, request, allocator, base, host, false), 159 .resolve => handleThreadResolve(io, request, allocator, base, host), 160 .publish => handlePatchPublish(io, request, allocator, base, host), 161 .merge => handlePatchMerge(io, request, allocator, base, host, .source), 162 .squash => handlePatchMerge(io, request, allocator, base, host, .squash), 163 .undo => handleUndo(io, request, allocator, base, host, .undo), 164 .clear => handleUndo(io, request, allocator, base, host, .clear), 165 .attach => handleAttach(io, request, allocator, base, host), 166 }; 167 } 168 } 169 }, 170 .local => |local| { 171 const PostRoute = enum { new, edit, remove, open, close, resolve, sync, attach, undo, clear }; 172 inline for (@typeInfo(PostRoute).@"enum".fields) |field| { 173 const suffix = "/" ++ field.name; 174 if (std.mem.endsWith(u8, path, suffix)) { 175 const base = path[0 .. path.len - suffix.len]; 176 return switch (@field(PostRoute, field.name)) { 177 .new => handleNew(io, request, allocator, base, host), 178 .edit => handleEdit(io, request, allocator, base, host), 179 .remove => handleRemove(io, request, allocator, base, host), 180 .open => handleThreadStatus(io, request, allocator, base, host, true), 181 .close => handleThreadStatus(io, request, allocator, base, host, false), 182 .resolve => handleThreadResolve(io, request, allocator, base, host), 183 .sync => handleSync(io, request, allocator, base, local), 184 .undo => handleUndo(io, request, allocator, base, host, .undo), 185 .clear => handleUndo(io, request, allocator, base, host, .clear), 186 .attach => handleAttach(io, request, allocator, base, host), 187 }; 188 } 189 } 190 }, 191 } 192 } 193 194 const get_or_head = method == .GET or method == .HEAD; 195 if (!get_or_head) { 196 try request.respond("method not allowed", .{ 197 .status = .method_not_allowed, 198 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 199 }); 200 return; 201 } 202 203 if (std.mem.eql(u8, path, "/favicon.ico")) { 204 try request.respond("", .{ 205 .status = .no_content, 206 .extra_headers = &.{.{ .name = "content-type", .value = "image/x-icon" }}, 207 }); 208 return; 209 } 210 211 // an attachment serves raw bytes rather than a page, so it is matched 212 // before the routable pages 213 if (attachmentRequest(path)) |attachment| return serveAttachment(io, request, allocator, attachment, host); 214 215 const route_maybe = switch (host) { 216 .server => ui.RoutablePage.fromUrl(path), 217 .local => ui.RoutablePage.fromUrlLocal(path), 218 }; 219 // a path that's neither a page nor an embed gets the not-found page 220 if (route_maybe == null) if (findEmbed(path)) |embed| { 221 // the embeds change with every build, so the browser must revalidate 222 // rather than heuristically cache them across server restarts 223 try request.respond(embed.body, .{ 224 .extra_headers = &.{ 225 .{ .name = "content-type", .value = embed.content_type }, 226 .{ .name = "cache-control", .value = "no-cache" }, 227 }, 228 }); 229 return; 230 }; 231 { 232 const current_page = route_maybe orelse .not_found; 233 // resolve the haxy_session cookie's token to a user_id via the 234 // store. user_id_buf lives on the stack for the rest of handleRequest, 235 // which is plenty for renderIndexHtml to consume. local mode has no 236 // accounts, so it is always logged out. 237 var user_id_buf: [evt.event_id_size]u8 = undefined; 238 var user_id: ?[]const u8 = null; 239 // the session token that named the user, so a stale one can be revoked 240 var token_buf: [SessionStore.token_hex_len]u8 = undefined; 241 var session_token: ?[]const u8 = null; 242 var form_arena = std.heap.ArenaAllocator.init(allocator); 243 defer form_arena.deinit(); 244 var form_feedback: ?ui.Session.FormFeedback = null; 245 var form_cookie_seen = false; 246 var local_flash_seen = false; 247 var sync_failure: ?[]const u8 = null; 248 var sync_failure_allocated: ?[]u8 = null; 249 defer if (sync_failure_allocated) |value| allocator.free(value); 250 // backs the cookie a claimed auto-login sets 251 var cookie_buf: [256]u8 = undefined; 252 var session_cookie: ?[]const u8 = null; 253 switch (host) { 254 .server => |server| { 255 user_id = blk: { 256 const token = getCookieValue(request, cookie_name) orelse break :blk null; 257 if (!server.session_store.lookup(token, &user_id_buf)) break :blk null; 258 session_token = token; 259 break :blk user_id_buf[0..evt.event_id_size]; 260 }; 261 // whoever seeded the store may have left a session to claim 262 if (user_id == null) { 263 if (server.session_store.autoLogin(&token_buf) and server.session_store.lookup(&token_buf, &user_id_buf)) { 264 session_cookie = try std.fmt.bufPrint(&cookie_buf, session_cookie_fmt, .{token_buf}); 265 session_token = &token_buf; 266 user_id = user_id_buf[0..evt.event_id_size]; 267 } 268 } 269 if (getCookieValue(request, form_flash_cookie)) |token| { 270 form_cookie_seen = true; 271 form_feedback = server.session_store.takeFlash(form_arena.allocator(), token); 272 } 273 }, 274 .local => { 275 if (getCookieValue(request, local_flash_cookie)) |raw| { 276 local_flash_seen = true; 277 if (std.mem.startsWith(u8, raw, local_required_title_prefix)) { 278 const tag = std.meta.stringToEnum(std.meta.Tag(ui.Session.FormFeedback), raw[local_required_title_prefix.len..]); 279 form_feedback = if (tag) |feedback_tag| switch (feedback_tag) { 280 .issue => .{ .issue = .{ .failure = .required_title } }, 281 .patch => .{ .patch = .{ .failure = .required_title } }, 282 .discussion => .{ .discussion = .{ .failure = .required_title } }, 283 else => null, 284 } else null; 285 } else if (std.mem.startsWith(u8, raw, local_sync_failure_prefix)) { 286 const value = try allocator.dupe(u8, raw[local_sync_failure_prefix.len..]); 287 sync_failure_allocated = value; 288 sync_failure = std.Uri.percentDecodeInPlace(value); 289 } 290 } 291 }, 292 } 293 294 const git_http_port: ?u16, const git_ssh_port: ?u16, const git_ssh_prefix: []const u8 = switch (host) { 295 .server => |server| .{ server.git_http_port, server.git_ssh_port, server.git_ssh_prefix }, 296 .local => .{ null, null, "" }, 297 }; 298 var session_data: ui.Session.Data = .{ 299 .user_id = user_id, 300 .form_feedback = form_feedback, 301 .sync_failure = sync_failure, 302 .current_page = current_page, 303 .host_kind = std.meta.activeTag(host), 304 .git_http_port = git_http_port, 305 .git_ssh_port = git_ssh_port, 306 .git_ssh_prefix = git_ssh_prefix, 307 }; 308 // a page that can't be built shows the not-found page instead 309 const html = renderIndexHtml(io, allocator, host, session_token, session_data) catch |err| switch (err) { 310 error.NotFound => blk: { 311 session_data.current_page = .not_found; 312 break :blk try renderIndexHtml(io, allocator, host, session_token, session_data); 313 }, 314 else => |e| return e, 315 }; 316 defer allocator.free(html); 317 318 const expired_form_cookie = if (form_cookie_seen) 319 try std.fmt.allocPrint(allocator, form_flash_cookie ++ "=; Path={s}; Max-Age=0", .{path}) 320 else 321 null; 322 defer if (expired_form_cookie) |cookie| allocator.free(cookie); 323 var header_buf: [4]std.http.Header = undefined; 324 var headers: std.ArrayList(std.http.Header) = .initBuffer(&header_buf); 325 headers.appendAssumeCapacity(.{ .name = "content-type", .value = "text/html; charset=utf-8" }); 326 if (expired_form_cookie) |cookie| headers.appendAssumeCapacity(.{ .name = "set-cookie", .value = cookie }); 327 if (local_flash_seen) headers.appendAssumeCapacity(.{ .name = "set-cookie", .value = local_flash_cookie ++ "=; Path=/; Max-Age=0" }); 328 if (session_cookie) |cookie| headers.appendAssumeCapacity(.{ .name = "set-cookie", .value = cookie }); 329 try request.respond(html, .{ 330 .status = if (session_data.current_page == .not_found) .not_found else .ok, 331 .extra_headers = headers.items, 332 }); 333 } 334 } 335 336 fn handleLogin( 337 io: std.Io, 338 request: *std.http.Server.Request, 339 allocator: std.mem.Allocator, 340 base: []const u8, 341 admin_repo_path: []const u8, 342 session_store: SessionStore, 343 ) !void { 344 const body = try readFormBody(request, allocator); 345 defer allocator.free(body); 346 347 const username = (try parseFormField(allocator, body, "username")) orelse try allocator.dupe(u8, ""); 348 defer allocator.free(username); 349 const password = (try parseFormField(allocator, body, "password")) orelse try allocator.dupe(u8, ""); 350 defer allocator.free(password); 351 352 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 353 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 354 defer repo.deinit(io, allocator); 355 356 var arena = std.heap.ArenaAllocator.init(allocator); 357 defer arena.deinit(); 358 359 const haxy_moment = try evt.currentMoment(evt.admin_repo_opts, &repo); 360 const result = try evt.User.verifyCredentials(evt.AdminDB, evt.admin_repo_opts.hash, haxy_moment, &arena, username, password); 361 362 // on success, return to the page the login came from (base, or "/" at the 363 // root); on failure, stay on its user tab to surface the error. 364 const success_location: []const u8 = if (base.len == 0) "/" else base; 365 const failure_location = try std.fmt.allocPrint(arena.allocator(), "{s}/user", .{base}); 366 367 switch (result) { 368 .success => |user_id| { 369 const token = try session_store.create(&user_id); 370 var cookie_buf: [256]u8 = undefined; 371 const cookie = try std.fmt.bufPrint(&cookie_buf, session_cookie_fmt, .{token}); 372 try request.respond("", .{ 373 .status = .see_other, 374 .extra_headers = &.{ 375 .{ .name = "location", .value = success_location }, 376 .{ .name = "set-cookie", .value = cookie }, 377 }, 378 }); 379 }, 380 .unknown_user => try respondFormFailure(request, allocator, session_store, failure_location, .{ .login = .{ .failure = .unknown_user, .username = username } }), 381 .wrong_password => try respondFormFailure(request, allocator, session_store, failure_location, .{ .login = .{ .failure = .wrong_password, .username = username } }), 382 } 383 } 384 385 fn respondFormFailure(request: *std.http.Server.Request, allocator: std.mem.Allocator, session_store: SessionStore, location: []const u8, feedback: ui.Session.FormFeedback) !void { 386 const token = try session_store.createFlash(allocator, feedback); 387 const cookie = try std.fmt.allocPrint(allocator, form_flash_cookie ++ "={s}; Path={s}; HttpOnly; SameSite=Strict", .{ token, location }); 388 defer allocator.free(cookie); 389 try request.respond("", .{ 390 .status = .see_other, 391 .extra_headers = &.{ 392 .{ .name = "location", .value = location }, 393 .{ .name = "set-cookie", .value = cookie }, 394 }, 395 }); 396 } 397 398 fn respondThreadFormFailure(request: *std.http.Server.Request, allocator: std.mem.Allocator, host: Host, location: []const u8, feedback: ui.Session.FormFeedback) !void { 399 return switch (host) { 400 .server => |server| respondFormFailure(request, allocator, server.session_store, location, feedback), 401 .local => { 402 const tag = std.meta.activeTag(feedback); 403 const required_title = switch (feedback) { 404 .issue => |value| value.failure == .required_title, 405 .discussion => |value| value.failure == .required_title, 406 .patch => |value| value.failure == .required_title, 407 else => false, 408 }; 409 if (!required_title) return error.InvalidFormFeedback; 410 const cookie = try std.fmt.allocPrint(allocator, local_flash_cookie ++ "=" ++ local_required_title_prefix ++ "{s}; Path=/; HttpOnly; SameSite=Strict", .{@tagName(tag)}); 411 defer allocator.free(cookie); 412 try request.respond("", .{ 413 .status = .see_other, 414 .extra_headers = &.{ 415 .{ .name = "location", .value = location }, 416 .{ .name = "set-cookie", .value = cookie }, 417 }, 418 }); 419 }, 420 }; 421 } 422 423 fn requiredTitleFeedback(kind: evt.EventKind, title: []const u8, labels: []const u8, description: []const u8, target_branch: []const u8, source_branch: ?[]const u8) ui.Session.FormFeedback { 424 return switch (kind) { 425 .issue => .{ .issue = .{ .failure = .required_title, .fields = .{ 426 .title = title, 427 .labels = labels, 428 .description = description, 429 } } }, 430 .patch => patchFeedback(.required_title, title, labels, description, target_branch, source_branch), 431 .discuss => .{ .discussion = .{ .failure = .required_title, .fields = .{ 432 .title = title, 433 .labels = labels, 434 .description = description, 435 } } }, 436 else => unreachable, 437 }; 438 } 439 440 fn patchFeedback(failure: ui.Session.FormFeedback.PatchFailure, title: []const u8, labels: []const u8, description: []const u8, target_branch: []const u8, source_branch: ?[]const u8) ui.Session.FormFeedback { 441 return .{ .patch = .{ .failure = failure, .fields = .{ 442 .title = title, 443 .labels = labels, 444 .description = description, 445 .target_branch = target_branch, 446 .source_branch = source_branch orelse "", 447 .source_kind = if (source_branch != null) .branch else .fork, 448 } } }; 449 } 450 451 fn handleLogout(request: *std.http.Server.Request, base: []const u8, session_store: SessionStore) !void { 452 // revoke the session server-side so the cookie is dead for anyone holding 453 // a copy, not just this browser. 454 if (getCookieValue(request, cookie_name)) |token| session_store.remove(token); 455 // return to the page the logout came from (base, or "/" at the root). 456 const location: []const u8 = if (base.len == 0) "/" else base; 457 // close the connection instead of keeping it alive: we don't read the 458 // request body, and respond()'s keep-alive path would otherwise try to 459 // discard it — which asserts on a bodyless POST that carries no 460 // content-length, and would block on one with no framing at all. a logout 461 // is just a redirect, so the browser reconnects for the follow-up GET. 462 try request.respond("", .{ 463 .status = .see_other, 464 .keep_alive = false, 465 .extra_headers = &.{ 466 .{ .name = "location", .value = location }, 467 .{ .name = "set-cookie", .value = cookie_name ++ "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0" }, 468 }, 469 }); 470 } 471 472 // the actor for a write to the repo `repo_base` names with at least `min_role`, 473 // or null once the refusal has been sent. local mode always writes. 474 fn authorizeWrite( 475 io: std.Io, 476 allocator: std.mem.Allocator, 477 arena: *std.heap.ArenaAllocator, 478 request: *std.http.Server.Request, 479 host: Host, 480 repo_base: []const u8, 481 min_role: evt.Repo.Role, 482 ) !?ui.Actor { 483 const server = switch (host) { 484 .server => |server| server, 485 .local => |src| return .{ .author = try ui.localAuthor(src, io, allocator, arena), .role = .owner }, 486 }; 487 const authorization: ui.Authorization = blk: { 488 const user_id = requestUserId(request, server.session_store) orelse break :blk .login_required; 489 490 const repo_prefix = "/repo/"; 491 if (!std.mem.startsWith(u8, repo_base, repo_prefix)) break :blk .repo_not_found; 492 493 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 494 defer admin_repo.deinit(io, allocator); 495 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin_repo); 496 break :blk try ui.authorizeUser(io, moment, arena, server.users_dir, user_id, repo_base[repo_prefix.len..], min_role); 497 }; 498 switch (authorization) { 499 .actor => |actor| return actor, 500 .login_required => try respondLoginRequired(request), 501 .repo_not_found => try respondRepoNotFound(request), 502 .forbidden => try respondForbidden(request), 503 } 504 return null; 505 } 506 507 // whether the request may read the repo `repo_base` names. local mode always 508 // may. 509 fn mayRead( 510 io: std.Io, 511 allocator: std.mem.Allocator, 512 request: *std.http.Server.Request, 513 host: Host, 514 repo_base: []const u8, 515 ) !bool { 516 const server = switch (host) { 517 .server => |server| server, 518 .local => return true, 519 }; 520 const repo_prefix = "/repo/"; 521 if (!std.mem.startsWith(u8, repo_base, repo_prefix)) return false; 522 523 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 524 defer admin_repo.deinit(io, allocator); 525 var arena = std.heap.ArenaAllocator.init(allocator); 526 defer arena.deinit(); 527 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin_repo); 528 const user_id = blk: { 529 const id = requestUserId(request, server.session_store) orelse break :blk null; 530 break :blk if (try ui.activeUser(moment, &arena, id) != null) id else null; 531 }; 532 const owner_repo = evt.parseOwnerRepoPath(repo_base[repo_prefix.len..]) orelse return false; 533 const repo = (try evt.readRepoByOwnerAndName(io, allocator, &arena, moment, server.users_dir, owner_repo.owner, owner_repo.name, user_id)) orelse return false; 534 return repo.role != .none; 535 } 536 537 // the logged-in user the request's session cookie names 538 fn requestUserId(request: *std.http.Server.Request, session_store: SessionStore) ?[evt.event_id_size]u8 { 539 const token = getCookieValue(request, cookie_name) orelse return null; 540 var user_id: [evt.event_id_size]u8 = undefined; 541 return if (session_store.lookup(token, &user_id)) user_id else null; 542 } 543 544 // refuse a write from a request with no logged-in user. the body goes unread, 545 // so the connection closes. 546 fn respondLoginRequired(request: *std.http.Server.Request) !void { 547 try request.respond("log in to make changes", .{ 548 .status = .forbidden, 549 .keep_alive = false, 550 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 551 }); 552 } 553 554 // refuse a write the user's role in the repo doesn't allow 555 fn respondForbidden(request: *std.http.Server.Request) !void { 556 try request.respond("you don't have permission to do that", .{ 557 .status = .forbidden, 558 .keep_alive = false, 559 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 560 }); 561 } 562 563 fn respondRepoNotFound(request: *std.http.Server.Request) !void { 564 try request.respond("repo not found", .{ 565 .status = .not_found, 566 .keep_alive = false, 567 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 568 }); 569 } 570 571 // new actions share a suffix; the base identifies whether the form creates a 572 // thread or comment. 573 fn handleNew( 574 io: std.Io, 575 request: *std.http.Server.Request, 576 allocator: std.mem.Allocator, 577 base: []const u8, 578 host: Host, 579 ) !void { 580 if (commentBaseParts(base) != null) return handleCommentNew(io, request, allocator, base, host); 581 582 const issues_suffix = "/issues"; 583 if (std.mem.endsWith(u8, base, issues_suffix)) 584 return handleThreadNew(io, request, allocator, base[0 .. base.len - issues_suffix.len], host, .issue); 585 const discussions_suffix = "/discussions"; 586 if (std.mem.endsWith(u8, base, discussions_suffix)) 587 return handleThreadNew(io, request, allocator, base[0 .. base.len - discussions_suffix.len], host, .discuss); 588 const patches_suffix = "/patches"; 589 if (std.mem.endsWith(u8, base, patches_suffix)) 590 return handleThreadNew(io, request, allocator, base[0 .. base.len - patches_suffix.len], host, .patch); 591 592 try request.respond("new event target not found", .{ 593 .status = .not_found, 594 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 595 }); 596 } 597 598 // create a repo for the logged-in user and redirect to it. a failure goes 599 // back to the new-repo page that posted the form. 600 fn handleRepoNew( 601 io: std.Io, 602 request: *std.http.Server.Request, 603 allocator: std.mem.Allocator, 604 form_location: []const u8, 605 admin_repo_path: []const u8, 606 users_dir: []const u8, 607 session_store: SessionStore, 608 ) !void { 609 const user_id = requestUserId(request, session_store) orelse return respondLoginRequired(request); 610 var arena = std.heap.ArenaAllocator.init(allocator); 611 defer arena.deinit(); 612 const user = blk: { 613 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }); 614 defer admin_repo.deinit(io, allocator); 615 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin_repo); 616 break :blk (try ui.activeUser(moment, &arena, user_id)) orelse return respondLoginRequired(request); 617 }; 618 619 const body = try readFormBody(request, allocator); 620 defer allocator.free(body); 621 const name = (try parseFormField(allocator, body, "name")) orelse try allocator.dupe(u8, ""); 622 defer allocator.free(name); 623 const description = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 624 defer allocator.free(description); 625 const hash_value = (try parseFormField(allocator, body, "hash")) orelse try allocator.dupe(u8, ""); 626 defer allocator.free(hash_value); 627 const access_value = (try parseFormField(allocator, body, "access")) orelse try allocator.dupe(u8, ""); 628 defer allocator.free(access_value); 629 const bad_request: std.http.Server.Request.RespondOptions = .{ .status = .bad_request, .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }} }; 630 const hash_kind = std.meta.stringToEnum(hash.HashKind, hash_value) orelse return request.respond("invalid hash", bad_request); 631 const access = std.meta.stringToEnum(evt.Repo.Access, access_value) orelse return request.respond("invalid access", bad_request); 632 633 _ = evt.createRepo(io, allocator, users_dir, &user_id, .{ .name = user.event.name, .email = user.event.email }, name, description, access, hash_kind) catch |err| { 634 const failure = ui.Session.FormFeedback.RepoFailure.fromError(err) orelse return err; 635 return respondFormFailure(request, allocator, session_store, form_location, .{ .repo = .{ .failure = failure, .fields = .{ 636 .name = name, 637 .description = description, 638 .hash = hash_kind, 639 .access = access, 640 } } }); 641 }; 642 643 const location = try std.fmt.allocPrint(allocator, "/repo/{s}/{s}", .{ user.event.name, name }); 644 defer allocator.free(location); 645 try request.respond("", .{ 646 .status = .see_other, 647 .extra_headers = &.{.{ .name = "location", .value = location }}, 648 }); 649 } 650 651 // create a user, log them in, and redirect to their page. a failure goes 652 // back to the new-user page that posted the form. 653 fn handleUserNew( 654 io: std.Io, 655 request: *std.http.Server.Request, 656 allocator: std.mem.Allocator, 657 form_location: []const u8, 658 admin_repo_path: []const u8, 659 users_dir: []const u8, 660 session_store: SessionStore, 661 ) !void { 662 if (requestUserId(request, session_store) != null) { 663 return request.respond("log out to create a user", .{ 664 .status = .forbidden, 665 .keep_alive = false, 666 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 667 }); 668 } 669 670 const body = try readFormBody(request, allocator); 671 defer allocator.free(body); 672 const name = (try parseFormField(allocator, body, "name")) orelse try allocator.dupe(u8, ""); 673 defer allocator.free(name); 674 const email = (try parseFormField(allocator, body, "email")) orelse try allocator.dupe(u8, ""); 675 defer allocator.free(email); 676 const password = (try parseFormField(allocator, body, "password")) orelse try allocator.dupe(u8, ""); 677 defer allocator.free(password); 678 const password_again = (try parseFormField(allocator, body, "password_again")) orelse try allocator.dupe(u8, ""); 679 defer allocator.free(password_again); 680 681 const user_id = blk: { 682 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }); 683 defer admin_repo.deinit(io, allocator); 684 break :blk evt.createUser(io, allocator, users_dir, &admin_repo, name, email, password, password_again) catch |err| { 685 const failure = ui.Session.FormFeedback.UserFailure.fromError(err) orelse return err; 686 return respondFormFailure(request, allocator, session_store, form_location, .{ .user = .{ .failure = failure, .fields = .{ .name = name, .email = email } } }); 687 }; 688 }; 689 690 const token = try session_store.create(&user_id); 691 var cookie_buf: [256]u8 = undefined; 692 const cookie = try std.fmt.bufPrint(&cookie_buf, session_cookie_fmt, .{token}); 693 const location = try std.fmt.allocPrint(allocator, "/user/{s}", .{name}); 694 defer allocator.free(location); 695 try request.respond("", .{ 696 .status = .see_other, 697 .extra_headers = &.{ 698 .{ .name = "location", .value = location }, 699 .{ .name = "set-cookie", .value = cookie }, 700 }, 701 }); 702 } 703 704 // create a thread in the repo the form's page names and redirect to it. 705 fn handleThreadNew( 706 io: std.Io, 707 request: *std.http.Server.Request, 708 allocator: std.mem.Allocator, 709 base: []const u8, 710 host: Host, 711 kind: evt.EventKind, 712 ) !void { 713 var author_arena = std.heap.ArenaAllocator.init(allocator); 714 defer author_arena.deinit(); 715 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, base, .read)) orelse return; 716 const author = actor.author; 717 const body = try readFormBody(request, allocator); 718 defer allocator.free(body); 719 720 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 721 defer allocator.free(title); 722 const labels = (try parseFormField(allocator, body, "labels")) orelse try allocator.dupe(u8, ""); 723 defer allocator.free(labels); 724 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 725 defer allocator.free(description_crlf); 726 // form submission normalizes textarea line breaks to CRLF; store plain 727 // newlines so the text renders the same on every host 728 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 729 defer allocator.free(description); 730 const target_branch = (try parseFormField(allocator, body, "target_branch")) orelse try allocator.dupe(u8, ""); 731 defer allocator.free(target_branch); 732 733 const source_branch = if (kind == .patch) try parseFormField(allocator, body, "source_branch") else null; 734 defer if (source_branch) |branch| allocator.free(branch); 735 736 const valid = switch (kind) { 737 .issue => evt.Issue.fieldsValid(title, labels), 738 .patch => evt.Patch.fieldsValid(title, labels), 739 .discuss => evt.Discussion.fieldsValid(title, labels), 740 else => unreachable, 741 }; 742 if (!valid) { 743 const list_name: []const u8 = switch (kind) { 744 .issue => "issues", 745 .patch => "patches", 746 .discuss => "discussions", 747 else => unreachable, 748 }; 749 const form_location = try std.fmt.allocPrint(allocator, "{s}/{s}/new", .{ base, list_name }); 750 defer allocator.free(form_location); 751 if (!evt.titleValid(title)) { 752 return respondThreadFormFailure(request, allocator, host, form_location, requiredTitleFeedback(kind, title, labels, description, target_branch, source_branch)); 753 } 754 try request.respond("", .{ 755 .status = .see_other, 756 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 757 }); 758 return; 759 } 760 761 var id_bytes: [evt.event_id_size]u8 = undefined; 762 io.random(&id_bytes); 763 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 764 765 const not_found = "repo not found"; 766 const request_repo = (try requestRepoSource(io, allocator, host, base)) orelse { 767 try request.respond(not_found, .{ 768 .status = .not_found, 769 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 770 }); 771 return; 772 }; 773 defer request_repo.deinit(allocator); 774 const source = request_repo.source; 775 if (kind == .patch and source_branch == null) { 776 const server = switch (host) { 777 .server => |server| server, 778 .local => return respondRemoveNotFound(request), 779 }; 780 const user_id = actor.user_id orelse return respondLoginRequired(request); 781 if (!evt.Patch.branchValid(target_branch) or !try request_repo.source.hasBranch(io, allocator, target_branch)) { 782 const form_location = try std.fmt.allocPrint(allocator, "{s}/patches/new", .{base}); 783 defer allocator.free(form_location); 784 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(.invalid_target_branch, title, labels, description, target_branch, null)); 785 } 786 const repo_id = evt.parseEventId(std.fs.path.basename(request_repo.source.path)) catch return respondRemoveNotFound(request); 787 const repo_user_id = actor.repo_user_id orelse unreachable; 788 const fork_path = try fork.create(.{}, io, allocator, server.users_dir, .{ 789 .id = event_id_hex, 790 .user_id = user_id, 791 .repo_id = repo_id, 792 .repo_user_id = repo_user_id, 793 .title = title, 794 .description = description, 795 .labels = labels, 796 .target_branch = target_branch, 797 .author = author, 798 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 799 }); 800 defer allocator.free(fork_path); 801 } else { 802 const event = evt.EventWithId{ 803 .id = event_id_hex, 804 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 805 .author = author, 806 .event = switch (kind) { 807 .issue => .{ .issue = .{ .title = title, .description = description, .labels = labels } }, 808 .patch => .{ .patch = .{ .title = title, .description = description, .labels = labels, .target_branch = target_branch, .source_branch = source_branch } }, 809 .discuss => .{ .discuss = .{ .title = title, .description = description, .labels = labels } }, 810 else => unreachable, 811 }, 812 }; 813 814 switch (source.repo_kind) { 815 inline else => |repo_kind| { 816 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 817 defer any_repo.deinit(io, allocator); 818 switch (any_repo) { 819 inline else => |*repo| { 820 const result = if (kind == .patch) 821 pch.writeBranchPatch(host.event(), repo_kind, repo.self_repo_opts, io, allocator, repo, event_id_hex, event.event.patch orelse unreachable, null, author) 822 else 823 evt.consume(host.event(), .repo, repo_kind, repo.self_repo_opts, io, allocator, repo, evt.events_ref, &.{event}); 824 result catch |err| { 825 if (kind != .patch) return err; 826 const failure = ui.Session.FormFeedback.PatchFailure.fromError(err) orelse return err; 827 const form_location = try std.fmt.allocPrint(allocator, "{s}/patches/new", .{base}); 828 defer allocator.free(form_location); 829 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(failure, title, labels, description, target_branch, source_branch)); 830 }; 831 }, 832 } 833 }, 834 } 835 } 836 837 const location = try std.fmt.allocPrint(allocator, "{s}/{s}:{s}", .{ base, @tagName(kind), &event_id_hex }); 838 defer allocator.free(location); 839 try request.respond("", .{ 840 .status = .see_other, 841 .extra_headers = &.{.{ .name = "location", .value = location }}, 842 }); 843 } 844 845 const CommentBaseParts = struct { 846 repo_base: []const u8, 847 thread_kind: evt.EventKind, 848 thread_id: [evt.event_id_size]u8, 849 comment_id: ?[evt.event_id_size]u8, 850 }; 851 852 fn commentBaseParts(base: []const u8) ?CommentBaseParts { 853 const route = ui.RoutablePage.fromUrl(base) orelse ui.RoutablePage.fromUrlLocal(base) orelse return null; 854 const identity, const thread_kind, const thread_hex, const comment_hex = switch (route) { 855 .repo_issues => |*issue| .{ issue.name.slice(), evt.EventKind.issue, issue.selected.slice(), issue.comment.slice() }, 856 .repo_patches => |*patch| .{ patch.name.slice(), evt.EventKind.patch, patch.selected.slice(), patch.comment.slice() }, 857 .repo_discussions => |*discussion| .{ discussion.name.slice(), evt.EventKind.discuss, discussion.selected.slice(), discussion.comment.slice() }, 858 else => return null, 859 }; 860 const thread_id = evt.parseEventId(thread_hex) catch return null; 861 const comment_id = if (comment_hex.len == 0) null else evt.parseEventId(comment_hex) catch return null; 862 const repo_base_len = if (identity.len == 0) 0 else "/repo/".len + identity.len; 863 return .{ .repo_base = base[0..repo_base_len], .thread_kind = thread_kind, .thread_id = thread_id, .comment_id = comment_id }; 864 } 865 866 fn handlePatchPublish( 867 io: std.Io, 868 request: *std.http.Server.Request, 869 allocator: std.mem.Allocator, 870 base: []const u8, 871 host: Host, 872 ) !void { 873 const parts = commentBaseParts(base) orelse return respondRemoveNotFound(request); 874 if (parts.thread_kind != .patch or parts.comment_id != null) return respondRemoveNotFound(request); 875 const server = switch (host) { 876 .server => |server| server, 877 .local => return respondRemoveNotFound(request), 878 }; 879 var author_arena = std.heap.ArenaAllocator.init(allocator); 880 defer author_arena.deinit(); 881 // only the draft's author may publish it, which publish checks 882 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return; 883 const user_id = actor.user_id orelse return respondLoginRequired(request); 884 const author = actor.author; 885 886 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 887 defer request_repo.deinit(allocator); 888 const repo_id = evt.parseEventId(std.fs.path.basename(request_repo.source.path)) catch return respondRemoveNotFound(request); 889 var target_repo = try rp.AnyRepo(.xit, .{}).open(io, allocator, request_repo.source.localInitOpts()); 890 defer target_repo.deinit(io, allocator); 891 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 892 defer admin_repo.deinit(io, allocator); 893 const id = std.fmt.bytesToHex(parts.thread_id, .lower); 894 switch (target_repo) { 895 inline else => |*repo| try pch.publish(repo.self_repo_opts, io, allocator, server.users_dir, &admin_repo, repo, .{ 896 .id = id, 897 .user_id = user_id, 898 .repo_id = repo_id, 899 .author = author, 900 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 901 }), 902 } 903 try request.respond("", .{ 904 .status = .see_other, 905 .extra_headers = &.{.{ .name = "location", .value = base }}, 906 }); 907 } 908 909 fn handlePatchMerge( 910 io: std.Io, 911 request: *std.http.Server.Request, 912 allocator: std.mem.Allocator, 913 base: []const u8, 914 host: Host, 915 revision: evt.Patch.MergeRevision, 916 ) !void { 917 const parts = commentBaseParts(base) orelse return respondRemoveNotFound(request); 918 if (parts.thread_kind != .patch or parts.comment_id != null) return respondRemoveNotFound(request); 919 const server = switch (host) { 920 .server => |server| server, 921 .local => return respondRemoveNotFound(request), 922 }; 923 var author_arena = std.heap.ArenaAllocator.init(allocator); 924 defer author_arena.deinit(); 925 const author = ((try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .write)) orelse return).author; 926 927 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 928 defer request_repo.deinit(allocator); 929 var target_repo = try rp.AnyRepo(.xit, .{}).open(io, allocator, request_repo.source.localInitOpts()); 930 defer target_repo.deinit(io, allocator); 931 932 const id = std.fmt.bytesToHex(parts.thread_id, .lower); 933 const merged = switch (target_repo) { 934 inline else => |*repo| pch.mergeAndRemoveFork(repo.self_repo_opts, io, allocator, server.users_dir, repo, .{ 935 .id = id, 936 .revision = revision, 937 .author = author, 938 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 939 }), 940 }; 941 merged catch |err| switch (err) { 942 error.MergeConflict => return request.respond("merge conflict", .{ 943 .status = .conflict, 944 .keep_alive = false, 945 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 946 }), 947 error.MergeCheckUnavailable, error.PatchOutOfDate, error.PatchDataUnavailable => {}, 948 else => return err, 949 }; 950 951 const location = try std.fmt.allocPrint(allocator, "{s}/patch:{s}", .{ parts.repo_base, &id }); 952 defer allocator.free(location); 953 try request.respond("", .{ 954 .status = .see_other, 955 .keep_alive = false, 956 .extra_headers = &.{.{ .name = "location", .value = location }}, 957 }); 958 } 959 960 // create a reply and redirect to its permalink. 961 fn handleCommentNew( 962 io: std.Io, 963 request: *std.http.Server.Request, 964 allocator: std.mem.Allocator, 965 base: []const u8, 966 host: Host, 967 ) !void { 968 const not_found = "comment parent not found"; 969 const parts = commentBaseParts(base) orelse { 970 try request.respond(not_found, .{ 971 .status = .not_found, 972 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 973 }); 974 return; 975 }; 976 977 var author_arena = std.heap.ArenaAllocator.init(allocator); 978 defer author_arena.deinit(); 979 const author = ((try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return).author; 980 981 const form_body = try readFormBody(request, allocator); 982 defer allocator.free(form_body); 983 const body_crlf = (try parseFormField(allocator, form_body, "body")) orelse try allocator.dupe(u8, ""); 984 defer allocator.free(body_crlf); 985 const body = try std.mem.replaceOwned(u8, allocator, body_crlf, "\r\n", "\n"); 986 defer allocator.free(body); 987 988 if (!evt.Comment.fieldsValid(body)) { 989 const form_location = try std.fmt.allocPrint(allocator, "{s}/new", .{base}); 990 defer allocator.free(form_location); 991 try request.respond("", .{ 992 .status = .see_other, 993 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 994 }); 995 return; 996 } 997 998 const thread_id_hex = std.fmt.bytesToHex(parts.thread_id, .lower); 999 const parent_id_hex = std.fmt.bytesToHex(parts.comment_id orelse parts.thread_id, .lower); 1000 1001 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse { 1002 try request.respond(not_found, .{ 1003 .status = .not_found, 1004 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1005 }); 1006 return; 1007 }; 1008 defer request_repo.deinit(allocator); 1009 const source = request_repo.source; 1010 var event_id_hex: [evt.event_id_size * 2]u8 = undefined; 1011 switch (source.repo_kind) { 1012 inline else => |repo_kind| { 1013 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1014 defer any_repo.deinit(io, allocator); 1015 switch (any_repo) { 1016 inline else => |*repo| event_id_hex = try evt.Comment.create(host.event(), repo_kind, repo.self_repo_opts, io, allocator, repo, &thread_id_hex, &parent_id_hex, body, author), 1017 } 1018 }, 1019 } 1020 1021 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 }); 1022 defer allocator.free(location); 1023 try request.respond("", .{ 1024 .status = .see_other, 1025 .extra_headers = &.{.{ .name = "location", .value = location }}, 1026 }); 1027 } 1028 1029 const AttachmentRequest = struct { 1030 repo_base: []const u8, 1031 id: [evt.event_id_size]u8, 1032 }; 1033 1034 // an attachment url is its repo's base and the attachment's event id 1035 fn attachmentRequest(path: []const u8) ?AttachmentRequest { 1036 const infix = "/attachment:"; 1037 const at = std.mem.lastIndexOf(u8, path, infix) orelse return null; 1038 const tail = path[at + infix.len ..]; 1039 const id = evt.parseEventId(tail) catch return null; 1040 return .{ .repo_base = path[0..at], .id = id }; 1041 } 1042 1043 // serve an attachment's bytes from the repo its url names 1044 fn serveAttachment( 1045 io: std.Io, 1046 request: *std.http.Server.Request, 1047 allocator: std.mem.Allocator, 1048 attachment: AttachmentRequest, 1049 host: Host, 1050 ) !void { 1051 if (!try mayRead(io, allocator, request, host, attachment.repo_base)) return respondAttachmentNotFound(request); 1052 const request_repo = (try requestRepoSource(io, allocator, host, attachment.repo_base)) orelse return respondAttachmentNotFound(request); 1053 defer request_repo.deinit(allocator); 1054 const source = request_repo.source; 1055 switch (source.repo_kind) { 1056 inline else => |repo_kind| { 1057 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1058 defer any_repo.deinit(io, allocator); 1059 switch (any_repo) { 1060 inline else => |*repo| try sendAttachment(repo_kind, repo.self_repo_opts, io, request, allocator, repo, &attachment.id), 1061 } 1062 }, 1063 } 1064 } 1065 1066 fn sendAttachment( 1067 comptime repo_kind: rp.RepoKind, 1068 comptime repo_opts: rp.RepoOpts(repo_kind), 1069 io: std.Io, 1070 request: *std.http.Server.Request, 1071 allocator: std.mem.Allocator, 1072 repo: *rp.Repo(repo_kind, repo_opts), 1073 id: *const [evt.event_id_size]u8, 1074 ) !void { 1075 var arena = std.heap.ArenaAllocator.init(allocator); 1076 defer arena.deinit(); 1077 1078 const DB = evt.EventDB(repo_opts.hash); 1079 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; 1080 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1081 const haxy_moment = (if (event_db_maybe) |*event_db| 1082 evt.currentMomentFromDb(repo_opts.hash, event_db.db) 1083 else if (repo_kind == .git) 1084 return respondAttachmentNotFound(request) 1085 else 1086 evt.currentMoment(repo_opts, repo)) catch return respondAttachmentNotFound(request); 1087 1088 const record = (try evt.Attachment.readById(DB, repo_opts.hash, haxy_moment, &arena, id)) orelse return respondAttachmentNotFound(request); 1089 if (record.removed) return respondAttachmentNotFound(request); 1090 if (record.blob_oid.len != hash.hexLen(repo_opts.hash)) return respondAttachmentNotFound(request); 1091 const blob_oid: *const [hash.hexLen(repo_opts.hash)]u8 = @ptrCast(record.blob_oid.ptr); 1092 1093 var moment = repo.core.latestMoment() catch return respondAttachmentNotFound(request); 1094 const state = rp.Repo(repo_kind, repo_opts).State(.read_only){ .core = &repo.core, .extra = .{ .moment = &moment } }; 1095 var object_reader = obj.ObjectReader(repo_kind, repo_opts).init(state, io, allocator, blob_oid) catch return respondAttachmentNotFound(request); 1096 defer object_reader.deinit(); 1097 if (object_reader.header().kind != .blob) return respondAttachmentNotFound(request); 1098 1099 const content_type = attachmentContentType(record.name); 1100 const encoded_name = try ui.urlEncodeRef(allocator, record.name); 1101 defer allocator.free(encoded_name); 1102 const disposition = try std.fmt.allocPrint(allocator, "{s}; filename*=UTF-8''{s}", .{ if (content_type == null) "attachment" else "inline", encoded_name }); 1103 defer allocator.free(disposition); 1104 1105 var send_buf: [8192]u8 = undefined; 1106 var body = try request.respondStreaming(&send_buf, .{ 1107 .content_length = object_reader.header().size, 1108 .respond_options = .{ 1109 .extra_headers = &.{ 1110 .{ .name = "content-type", .value = content_type orelse "application/octet-stream" }, 1111 .{ .name = "content-disposition", .value = disposition }, 1112 // uploaded bytes are never sniffed into a type that could run 1113 // as script on this origin 1114 .{ .name = "x-content-type-options", .value = "nosniff" }, 1115 }, 1116 }, 1117 }); 1118 _ = try object_reader.interface.streamRemaining(&body.writer); 1119 try body.end(); 1120 } 1121 1122 // the images a browser renders safely inline. anything else downloads as 1123 // opaque bytes, so an uploaded page can't run on this origin. 1124 fn attachmentContentType(name: []const u8) ?[]const u8 { 1125 const types = [_]struct { ext: []const u8, value: []const u8 }{ 1126 .{ .ext = ".png", .value = "image/png" }, 1127 .{ .ext = ".jpg", .value = "image/jpeg" }, 1128 .{ .ext = ".jpeg", .value = "image/jpeg" }, 1129 .{ .ext = ".gif", .value = "image/gif" }, 1130 .{ .ext = ".webp", .value = "image/webp" }, 1131 }; 1132 for (types) |entry| { 1133 if (name.len > entry.ext.len and std.ascii.eqlIgnoreCase(name[name.len - entry.ext.len ..], entry.ext)) return entry.value; 1134 } 1135 return null; 1136 } 1137 1138 fn respondAttachmentNotFound(request: *std.http.Server.Request) !void { 1139 try request.respond("attachment not found", .{ 1140 .status = .not_found, 1141 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1142 }); 1143 } 1144 1145 fn respondAttachmentParentNotFound(request: *std.http.Server.Request) !void { 1146 try request.respond("attachment parent not found", .{ 1147 .status = .not_found, 1148 .keep_alive = false, 1149 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1150 }); 1151 } 1152 1153 // the upload declares its file's name here, since the body is the file itself 1154 const attachment_name_header = "x-attachment-name"; 1155 1156 const AttachParentParts = struct { 1157 repo_base: []const u8, 1158 kind: evt.EventKind, 1159 id_bytes: [evt.event_id_size]u8, 1160 }; 1161 1162 // what an attachment hangs off: the `<kind>:<id>` segment the form's page ends 1163 // with, whatever kind that is 1164 fn attachParentParts(base: []const u8) ?AttachParentParts { 1165 const segment_at = std.mem.lastIndexOfScalar(u8, base, '/') orelse return null; 1166 const segment = base[segment_at + 1 ..]; 1167 const colon_at = std.mem.lastIndexOfScalar(u8, segment, ':') orelse return null; 1168 const kind = std.meta.stringToEnum(evt.EventKind, segment[0..colon_at]) orelse return null; 1169 const id_bytes = evt.parseEventId(segment[colon_at + 1 ..]) catch return null; 1170 return .{ .repo_base = base[0..segment_at], .kind = kind, .id_bytes = id_bytes }; 1171 } 1172 1173 // attach the uploaded file to the event the url names, then reload. the file is 1174 // the whole request body, so it streams from the socket into the object store 1175 // without being buffered. 1176 fn handleAttach( 1177 io: std.Io, 1178 request: *std.http.Server.Request, 1179 allocator: std.mem.Allocator, 1180 base: []const u8, 1181 host: Host, 1182 ) !void { 1183 const parts = attachParentParts(base) orelse return respondAttachmentParentNotFound(request); 1184 1185 var author_arena = std.heap.ArenaAllocator.init(allocator); 1186 defer author_arena.deinit(); 1187 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return; 1188 const author = actor.author; 1189 // an attachment changes the event it hangs off 1190 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondAttachmentParentNotFound(request); 1191 defer request_repo.deinit(allocator); 1192 const source = request_repo.source; 1193 if (!try source.canModify(io, allocator, actor, parts.kind, &parts.id_bytes)) return respondForbidden(request); 1194 1195 const name = (try attachmentName(allocator, request)) orelse return respondUploadError(request, .bad_request, "attachment needs a name"); 1196 defer allocator.free(name); 1197 if (!evt.Attachment.nameValid(name)) return respondUploadError(request, .bad_request, "invalid attachment name"); 1198 1199 const size = request.head.content_length orelse return respondUploadError(request, .length_required, "attachments must declare a content length"); 1200 if (size == 0) return respondUploadError(request, .bad_request, "attachment is empty"); 1201 if (size > evt.Attachment.max_size) return respondUploadError(request, .payload_too_large, "attachment is too large"); 1202 1203 const parent_id_hex = std.fmt.bytesToHex(parts.id_bytes, .lower); 1204 1205 var body_buf: [4096]u8 = undefined; 1206 const blob: evt.Blob = .{ .name = name, .size = size, .reader = try request.readerExpectContinue(&body_buf) }; 1207 1208 switch (source.repo_kind) { 1209 inline else => |repo_kind| { 1210 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1211 defer any_repo.deinit(io, allocator); 1212 switch (any_repo) { 1213 inline else => |*repo| _ = evt.Attachment.create(host.event(), repo_kind, repo.self_repo_opts, io, allocator, repo, &parent_id_hex, blob, author) catch |err| switch (err) { 1214 error.ParentNotFound => return respondAttachmentParentNotFound(request), 1215 else => return err, 1216 }, 1217 } 1218 }, 1219 } 1220 1221 // the client reloads the page itself 1222 try request.respond("", .{ .status = .no_content, .keep_alive = false }); 1223 } 1224 1225 // the name the upload declares for its file, percent-encoded so it survives a 1226 // header 1227 fn attachmentName(allocator: std.mem.Allocator, request: *std.http.Server.Request) !?[]u8 { 1228 var iter = request.iterateHeaders(); 1229 while (iter.next()) |header| { 1230 if (!std.ascii.eqlIgnoreCase(header.name, attachment_name_header)) continue; 1231 return try decodeFormValue(allocator, header.value); 1232 } 1233 return null; 1234 } 1235 1236 // an upload that failed leaves the body partly read, so the connection closes 1237 fn respondUploadError(request: *std.http.Server.Request, status: std.http.Status, message: []const u8) !void { 1238 try request.respond(message, .{ 1239 .status = status, 1240 .keep_alive = false, 1241 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1242 }); 1243 } 1244 1245 // re-emit the comment `parts` names with a new body, in the repo the host 1246 // resolves the base to. 1247 fn updateComment( 1248 io: std.Io, 1249 allocator: std.mem.Allocator, 1250 host: Host, 1251 parts: CommentBaseParts, 1252 body: []const u8, 1253 author: evt.CommitAuthor, 1254 ) !void { 1255 const comment_id = parts.comment_id orelse return error.NotFound; 1256 const thread_id = std.fmt.bytesToHex(parts.thread_id, .lower); 1257 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return error.NotFound; 1258 defer request_repo.deinit(allocator); 1259 const source = request_repo.source; 1260 switch (source.repo_kind) { 1261 inline else => |repo_kind| { 1262 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1263 defer any_repo.deinit(io, allocator); 1264 switch (any_repo) { 1265 inline else => |*repo| try evt.Comment.update(host.event(), repo_kind, repo.self_repo_opts, io, allocator, repo, &thread_id, &comment_id, body, author), 1266 } 1267 }, 1268 } 1269 } 1270 1271 // edit actions share a suffix; the base identifies the event being edited. 1272 fn handleEdit( 1273 io: std.Io, 1274 request: *std.http.Server.Request, 1275 allocator: std.mem.Allocator, 1276 base: []const u8, 1277 host: Host, 1278 ) !void { 1279 const parts = commentBaseParts(base) orelse return respondRemoveNotFound(request); 1280 if (parts.comment_id != null) return handleCommentEdit(io, request, allocator, base, host, parts); 1281 return handleThreadEdit(io, request, allocator, base, host, parts); 1282 } 1283 1284 // replace the body of the comment the url names, then redirect to its 1285 // permalink. 1286 fn handleCommentEdit( 1287 io: std.Io, 1288 request: *std.http.Server.Request, 1289 allocator: std.mem.Allocator, 1290 base: []const u8, 1291 host: Host, 1292 parts: CommentBaseParts, 1293 ) !void { 1294 var author_arena = std.heap.ArenaAllocator.init(allocator); 1295 defer author_arena.deinit(); 1296 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return; 1297 const author = actor.author; 1298 // edits only reach here for a comment 1299 const comment_id = parts.comment_id orelse unreachable; 1300 { 1301 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1302 defer request_repo.deinit(allocator); 1303 if (!try request_repo.source.canModify(io, allocator, actor, .comment, &comment_id)) return respondForbidden(request); 1304 } 1305 1306 const form_body = try readFormBody(request, allocator); 1307 defer allocator.free(form_body); 1308 const body_crlf = (try parseFormField(allocator, form_body, "body")) orelse try allocator.dupe(u8, ""); 1309 defer allocator.free(body_crlf); 1310 const body = try std.mem.replaceOwned(u8, allocator, body_crlf, "\r\n", "\n"); 1311 defer allocator.free(body); 1312 1313 if (!evt.Comment.fieldsValid(body)) { 1314 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1315 defer allocator.free(form_location); 1316 try request.respond("", .{ 1317 .status = .see_other, 1318 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1319 }); 1320 return; 1321 } 1322 1323 const not_found = "comment not found"; 1324 updateComment(io, allocator, host, parts, body, author) catch |err| switch (err) { 1325 error.NotFound => { 1326 try request.respond(not_found, .{ 1327 .status = .not_found, 1328 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1329 }); 1330 return; 1331 }, 1332 else => |e| return e, 1333 }; 1334 1335 try request.respond("", .{ 1336 .status = .see_other, 1337 .extra_headers = &.{.{ .name = "location", .value = base }}, 1338 }); 1339 } 1340 1341 fn updateThread( 1342 comptime Event: type, 1343 io: std.Io, 1344 allocator: std.mem.Allocator, 1345 host: Host, 1346 repo_base: []const u8, 1347 id: *const [evt.event_id_size]u8, 1348 update: Event.Update, 1349 author: evt.CommitAuthor, 1350 ) !void { 1351 const request_repo = (try requestRepoSource(io, allocator, host, repo_base)) orelse return error.NotFound; 1352 defer request_repo.deinit(allocator); 1353 const source = request_repo.source; 1354 switch (source.repo_kind) { 1355 inline else => |repo_kind| { 1356 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1357 defer any_repo.deinit(io, allocator); 1358 switch (any_repo) { 1359 inline else => |*repo| try Event.update(host.event(), repo_kind, repo.self_repo_opts, io, allocator, repo, id, update, author), 1360 } 1361 }, 1362 } 1363 } 1364 1365 const RemoveParts = struct { 1366 repo_base: []const u8, 1367 kind: evt.EventKind, 1368 id: [evt.event_id_size]u8, 1369 }; 1370 1371 // split a remove url into the repo and event it names 1372 fn removeParts(base: []const u8) ?RemoveParts { 1373 if (attachmentRequest(base)) |attachment| { 1374 const parent = attachParentParts(attachment.repo_base) orelse return null; 1375 return .{ 1376 .repo_base = parent.repo_base, 1377 .kind = .attach, 1378 .id = attachment.id, 1379 }; 1380 } 1381 if (commentBaseParts(base)) |thread| return .{ 1382 .repo_base = thread.repo_base, 1383 .kind = if (thread.comment_id != null) .comment else thread.thread_kind, 1384 .id = thread.comment_id orelse thread.thread_id, 1385 }; 1386 return null; 1387 } 1388 1389 // remove the event named by the form's url 1390 fn handleRemove( 1391 io: std.Io, 1392 request: *std.http.Server.Request, 1393 allocator: std.mem.Allocator, 1394 base: []const u8, 1395 host: Host, 1396 ) !void { 1397 const parts = removeParts(base) orelse return respondRemoveNotFound(request); 1398 1399 var author_arena = std.heap.ArenaAllocator.init(allocator); 1400 defer author_arena.deinit(); 1401 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return; 1402 const author = actor.author; 1403 1404 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1405 defer request_repo.deinit(allocator); 1406 const source = request_repo.source; 1407 1408 if (parts.kind == .patch) switch (host) { 1409 .server => |server| { 1410 const user_id = actor.user_id orelse return respondLoginRequired(request); 1411 1412 // a draft lives in its author's user repo 1413 if (try evt.readForkById(io, allocator, &author_arena, server.users_dir, &user_id, &parts.id)) |fork_record| { 1414 const repo_id = evt.parseEventId(std.fs.path.basename(source.path)) catch return respondRemoveNotFound(request); 1415 if (!fork_record.removed and fork_record.event.stage == .draft and std.mem.eql(u8, fork_record.event.repo_id, &repo_id)) { 1416 const id = std.fmt.bytesToHex(parts.id, .lower); 1417 try fork.remove(io, allocator, server.users_dir, &user_id, &id, author); 1418 1419 const location = try std.fmt.allocPrint(allocator, "{s}/patches/drafts", .{parts.repo_base}); 1420 defer allocator.free(location); 1421 try request.respond("", .{ 1422 .status = .see_other, 1423 .keep_alive = false, 1424 .extra_headers = &.{.{ .name = "location", .value = location }}, 1425 }); 1426 return; 1427 } 1428 } 1429 }, 1430 .local => {}, 1431 }; 1432 1433 // a draft is its author's alone, which its removal above checks 1434 if (!try source.canModify(io, allocator, actor, parts.kind, &parts.id)) return respondForbidden(request); 1435 1436 switch (source.repo_kind) { 1437 inline else => |repo_kind| { 1438 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1439 defer any_repo.deinit(io, allocator); 1440 switch (any_repo) { 1441 inline else => |*repo| evt.remove(host.event(), .repo, repo_kind, repo.self_repo_opts, io, allocator, repo, &parts.id, parts.kind, author) catch |err| switch (err) { 1442 error.EventNotFound => return respondRemoveNotFound(request), 1443 else => |e| return e, 1444 }, 1445 } 1446 }, 1447 } 1448 1449 const id = std.fmt.bytesToHex(parts.id, .lower); 1450 const location = try std.fmt.allocPrint(allocator, "{s}/event:{s}/kind:{s}", .{ parts.repo_base, &id, @tagName(parts.kind) }); 1451 defer allocator.free(location); 1452 try request.respond("", .{ 1453 .status = .see_other, 1454 .keep_alive = false, 1455 .extra_headers = &.{.{ .name = "location", .value = location }}, 1456 }); 1457 } 1458 1459 fn respondRemoveNotFound(request: *std.http.Server.Request) !void { 1460 try request.respond("event not found", .{ 1461 .status = .not_found, 1462 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1463 }); 1464 } 1465 1466 fn updateDiscussion( 1467 io: std.Io, 1468 allocator: std.mem.Allocator, 1469 host: Host, 1470 repo_base: []const u8, 1471 id: *const [evt.event_id_size]u8, 1472 title: []const u8, 1473 labels: []const u8, 1474 description: []const u8, 1475 author: evt.CommitAuthor, 1476 ) !void { 1477 const request_repo = (try requestRepoSource(io, allocator, host, repo_base)) orelse return error.NotFound; 1478 defer request_repo.deinit(allocator); 1479 const source = request_repo.source; 1480 switch (source.repo_kind) { 1481 inline else => |repo_kind| { 1482 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1483 defer any_repo.deinit(io, allocator); 1484 switch (any_repo) { 1485 inline else => |*repo| try evt.Discussion.update(host.event(), repo_kind, repo.self_repo_opts, io, allocator, repo, id, title, labels, description, author), 1486 } 1487 }, 1488 } 1489 } 1490 1491 // set the status of the issue the url names (base is 1492 // "/repo/<owner>/<name>/issue:<id>", identity elided in local mode) by 1493 // re-emitting its event, then redirect back to it 1494 fn handleThreadStatus( 1495 io: std.Io, 1496 request: *std.http.Server.Request, 1497 allocator: std.mem.Allocator, 1498 base: []const u8, 1499 host: Host, 1500 open: bool, 1501 ) !void { 1502 const not_found = "thread not found"; 1503 const parts = commentBaseParts(base) orelse { 1504 try request.respond(not_found, .{ 1505 .status = .not_found, 1506 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1507 }); 1508 return; 1509 }; 1510 1511 var author_arena = std.heap.ArenaAllocator.init(allocator); 1512 defer author_arena.deinit(); 1513 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return; 1514 const author = actor.author; 1515 { 1516 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1517 defer request_repo.deinit(allocator); 1518 if (!try request_repo.source.canModify(io, allocator, actor, parts.thread_kind, &parts.thread_id)) return respondForbidden(request); 1519 } 1520 1521 (switch (parts.thread_kind) { 1522 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .status = if (open) .open else .closed }, author), 1523 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .status = if (open) .open else .closed }, author), 1524 else => return respondRemoveNotFound(request), 1525 }) catch |err| switch (err) { 1526 error.NotFound => { 1527 try request.respond(not_found, .{ 1528 .status = .not_found, 1529 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1530 }); 1531 return; 1532 }, 1533 else => |e| return e, 1534 }; 1535 1536 // like logout, this is a bodyless POST, so close the connection rather than 1537 // letting the keep-alive path try to discard a body that isn't framed. 1538 try request.respond("", .{ 1539 .status = .see_other, 1540 .keep_alive = false, 1541 .extra_headers = &.{.{ .name = "location", .value = base }}, 1542 }); 1543 } 1544 1545 // replace a thread's editable fields. 1546 fn handleThreadEdit( 1547 io: std.Io, 1548 request: *std.http.Server.Request, 1549 allocator: std.mem.Allocator, 1550 base: []const u8, 1551 host: Host, 1552 parts: CommentBaseParts, 1553 ) !void { 1554 var author_arena = std.heap.ArenaAllocator.init(allocator); 1555 defer author_arena.deinit(); 1556 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return; 1557 const author = actor.author; 1558 1559 const body = try readFormBody(request, allocator); 1560 defer allocator.free(body); 1561 1562 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 1563 defer allocator.free(title); 1564 const labels = (try parseFormField(allocator, body, "labels")) orelse try allocator.dupe(u8, ""); 1565 defer allocator.free(labels); 1566 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 1567 defer allocator.free(description_crlf); 1568 // form submission normalizes textarea line breaks to CRLF; store plain 1569 // newlines so the text renders the same on every host 1570 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 1571 defer allocator.free(description); 1572 const target_branch = (try parseFormField(allocator, body, "target_branch")) orelse try allocator.dupe(u8, ""); 1573 defer allocator.free(target_branch); 1574 1575 // invalid fields send the user back to the edit form 1576 const valid = switch (parts.thread_kind) { 1577 .issue => evt.Issue.fieldsValid(title, labels), 1578 .patch => evt.Patch.fieldsValid(title, labels), 1579 .discuss => evt.Discussion.fieldsValid(title, labels), 1580 else => unreachable, 1581 }; 1582 if (!valid) { 1583 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1584 defer allocator.free(form_location); 1585 if (!evt.titleValid(title)) { 1586 return respondThreadFormFailure(request, allocator, host, form_location, requiredTitleFeedback(parts.thread_kind, title, labels, description, target_branch, null)); 1587 } 1588 try request.respond("", .{ 1589 .status = .see_other, 1590 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1591 }); 1592 return; 1593 } 1594 1595 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1596 defer request_repo.deinit(allocator); 1597 1598 const draft_user_id = if (parts.thread_kind == .patch) actor.user_id else null; 1599 if (draft_user_id) |user_id| { 1600 const server = switch (host) { 1601 .server => |server| server, 1602 .local => unreachable, 1603 }; 1604 if (!evt.Patch.branchValid(target_branch) or !try request_repo.source.hasBranch(io, allocator, target_branch)) { 1605 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1606 defer allocator.free(form_location); 1607 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(.invalid_target_branch, title, labels, description, target_branch, null)); 1608 } 1609 const repo_id = evt.parseEventId(std.fs.path.basename(request_repo.source.path)) catch return respondRemoveNotFound(request); 1610 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 1611 defer admin_repo.deinit(io, allocator); 1612 const id = std.fmt.bytesToHex(parts.thread_id, .lower); 1613 if (try pch.editDraft(.{}, io, allocator, server.users_dir, &admin_repo, .{ 1614 .id = id, 1615 .user_id = user_id, 1616 .repo_id = repo_id, 1617 .title = title, 1618 .labels = labels, 1619 .description = description, 1620 .target_branch = target_branch, 1621 .author = author, 1622 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1623 })) { 1624 try request.respond("", .{ 1625 .status = .see_other, 1626 .extra_headers = &.{.{ .name = "location", .value = base }}, 1627 }); 1628 return; 1629 } 1630 } 1631 1632 // a draft is its author's alone, which its edit above checks 1633 if (!try request_repo.source.canModify(io, allocator, actor, parts.thread_kind, &parts.thread_id)) return respondForbidden(request); 1634 1635 const not_found = switch (parts.thread_kind) { 1636 .issue => "issue not found", 1637 .patch => "patch not found", 1638 .discuss => "discussion not found", 1639 else => unreachable, 1640 }; 1641 (switch (parts.thread_kind) { 1642 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 1643 .title = title, 1644 .labels = labels, 1645 .description = description, 1646 } }, author), 1647 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 1648 .title = title, 1649 .labels = labels, 1650 .description = description, 1651 .target_branch = target_branch, 1652 } }, author), 1653 .discuss => updateDiscussion(io, allocator, host, parts.repo_base, &parts.thread_id, title, labels, description, author), 1654 else => unreachable, 1655 }) catch |err| switch (err) { 1656 error.NotFound => { 1657 try request.respond(not_found, .{ 1658 .status = .not_found, 1659 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1660 }); 1661 return; 1662 }, 1663 else => { 1664 if (parts.thread_kind != .patch) return err; 1665 const failure = ui.Session.FormFeedback.PatchFailure.fromError(err) orelse return err; 1666 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1667 defer allocator.free(form_location); 1668 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(failure, title, labels, description, target_branch, null)); 1669 }, 1670 }; 1671 1672 try request.respond("", .{ 1673 .status = .see_other, 1674 .extra_headers = &.{.{ .name = "location", .value = base }}, 1675 }); 1676 } 1677 1678 // resolve every conflicted field of the thread the url names 1679 fn handleThreadResolve( 1680 io: std.Io, 1681 request: *std.http.Server.Request, 1682 allocator: std.mem.Allocator, 1683 base: []const u8, 1684 host: Host, 1685 ) !void { 1686 const parts = commentBaseParts(base) orelse { 1687 try request.respond("thread not found", .{ 1688 .status = .not_found, 1689 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1690 }); 1691 return; 1692 }; 1693 1694 var author_arena = std.heap.ArenaAllocator.init(allocator); 1695 defer author_arena.deinit(); 1696 const author = ((try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .write)) orelse return).author; 1697 1698 const body = try readFormBody(request, allocator); 1699 defer allocator.free(body); 1700 1701 var field_arena = std.heap.ArenaAllocator.init(allocator); 1702 defer field_arena.deinit(); 1703 const aa = field_arena.allocator(); 1704 const title = try parseFormField(aa, body, "title"); 1705 const labels = try parseFormField(aa, body, "labels"); 1706 1707 // the hunk inputs are submitted as d0, d1, ...; form submission normalizes their 1708 // textarea line breaks to CRLF 1709 var hunks: std.ArrayList([]const u8) = .empty; 1710 var hunk_index: usize = 0; 1711 while (true) : (hunk_index += 1) { 1712 const name = try std.fmt.allocPrint(aa, "d{d}", .{hunk_index}); 1713 const submitted = (try parseFormField(aa, body, name)) orelse break; 1714 try hunks.append(aa, try std.mem.replaceOwned(u8, aa, submitted, "\r\n", "\n")); 1715 } 1716 1717 if (parts.comment_id != null or (parts.thread_kind != .issue and parts.thread_kind != .patch)) { 1718 try request.respond("thread not found", .{ 1719 .status = .not_found, 1720 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1721 }); 1722 return; 1723 } 1724 const route = ui.RoutablePage.fromUrl(base) orelse ui.RoutablePage.fromUrlLocal(base) orelse { 1725 try request.respond("thread not found", .{ 1726 .status = .not_found, 1727 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1728 }); 1729 return; 1730 }; 1731 const theirs: []const u8 = switch (route) { 1732 .repo_patches => |*patch| patch.theirs.slice(), 1733 .repo_issues => "", 1734 else => unreachable, 1735 }; 1736 const not_found = if (parts.thread_kind == .patch) "patch not found" else "issue not found"; 1737 1738 (switch (parts.thread_kind) { 1739 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 1740 .title = title, 1741 .labels = labels, 1742 .hunks = hunks.items, 1743 } }, author), 1744 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 1745 .title = title, 1746 .labels = labels, 1747 .hunks = hunks.items, 1748 .theirs = theirs, 1749 } }, author), 1750 else => unreachable, 1751 }) catch |err| switch (err) { 1752 error.NotFound => { 1753 try request.respond(not_found, .{ 1754 .status = .not_found, 1755 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1756 }); 1757 return; 1758 }, 1759 // invalid fields send the user back to the resolve form 1760 error.InvalidFields => { 1761 const form_location = try std.fmt.allocPrint(allocator, "{s}/resolve", .{base}); 1762 defer allocator.free(form_location); 1763 try request.respond("", .{ 1764 .status = .see_other, 1765 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1766 }); 1767 return; 1768 }, 1769 else => |e| return e, 1770 }; 1771 1772 try request.respond("", .{ 1773 .status = .see_other, 1774 .extra_headers = &.{.{ .name = "location", .value = base }}, 1775 }); 1776 } 1777 1778 // the posted path drops the action's own segment, so the route it parses is 1779 // the undo page the action applies to, never the confirmation page itself 1780 fn handleUndo(io: std.Io, request: *std.http.Server.Request, allocator: std.mem.Allocator, base: []const u8, host: Host, action: enum { undo, clear }) !void { 1781 const route = (switch (host) { 1782 .local => ui.RoutablePage.fromUrlLocal(base), 1783 .server => ui.RoutablePage.fromUrl(base), 1784 }) orelse return respondRepoNotFound(request); 1785 if (route != .repo_undo) return respondRepoNotFound(request); 1786 const target = route.repo_undo; 1787 var arena = std.heap.ArenaAllocator.init(allocator); 1788 defer arena.deinit(); 1789 const repo_base = if (target.name.len == 0) "" else try std.fmt.allocPrint(arena.allocator(), "/repo/{s}", .{target.name.slice()}); 1790 _ = (try authorizeWrite(io, allocator, &arena, request, host, repo_base, .owner)) orelse return; 1791 const resolved = (try requestRepoSource(io, allocator, host, repo_base)) orelse return respondRepoNotFound(request); 1792 defer resolved.deinit(allocator); 1793 (switch (action) { 1794 .undo => ui.Repo.Undo.execute(io, allocator, resolved.source, target.index orelse return respondRepoNotFound(request)), 1795 .clear => ui.Repo.Undo.clearHistory(io, allocator, resolved.source), 1796 }) catch |err| switch (err) { 1797 error.NotFound, error.InvalidHistoryIndex, error.TransactionNotFound => return respondRepoNotFound(request), 1798 else => return err, 1799 }; 1800 const location = try (ui.RoutablePage.repoUndoRoute(target.name.slice(), null) orelse return error.RouteTooLong).toUrl(&arena); 1801 try request.respond("", .{ .status = .see_other, .keep_alive = false, .extra_headers = &.{.{ .name = "location", .value = location }} }); 1802 } 1803 1804 fn handleSync( 1805 io: std.Io, 1806 request: *std.http.Server.Request, 1807 allocator: std.mem.Allocator, 1808 base: []const u8, 1809 source: ui.RepoSource, 1810 ) !void { 1811 if (base.len != 0) { 1812 try request.respond("not found", .{ 1813 .status = .not_found, 1814 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1815 }); 1816 return; 1817 } 1818 1819 var owned_failure: ?[]u8 = null; 1820 defer if (owned_failure) |message| allocator.free(message); 1821 const failure: ?[]const u8 = blk: { 1822 owned_failure = ui.Repo.Events.sync(io, allocator, source) catch |err| break :blk @errorName(err); 1823 break :blk owned_failure; 1824 }; 1825 if (failure) |message| { 1826 var encoded: std.Io.Writer.Allocating = .init(allocator); 1827 defer encoded.deinit(); 1828 try std.Uri.Component.percentEncode(&encoded.writer, message, struct { 1829 fn isUnreserved(c: u8) bool { 1830 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 1831 } 1832 }.isUnreserved); 1833 const cookie = try std.fmt.allocPrint( 1834 allocator, 1835 local_flash_cookie ++ "=" ++ local_sync_failure_prefix ++ "{s}; Path=/; HttpOnly; SameSite=Strict", 1836 .{encoded.written()}, 1837 ); 1838 defer allocator.free(cookie); 1839 try request.respond("", .{ 1840 .status = .see_other, 1841 .extra_headers = &.{ 1842 .{ .name = "location", .value = "/events" }, 1843 .{ .name = "set-cookie", .value = cookie }, 1844 }, 1845 }); 1846 return; 1847 } 1848 1849 try request.respond("", .{ 1850 .status = .see_other, 1851 .extra_headers = &.{ 1852 .{ .name = "location", .value = "/events" }, 1853 .{ .name = "set-cookie", .value = local_flash_cookie ++ "=; Path=/; Max-Age=0" }, 1854 }, 1855 }); 1856 } 1857 1858 fn renderIndexHtml( 1859 io: std.Io, 1860 allocator: std.mem.Allocator, 1861 host: Host, 1862 session_token: ?[]const u8, 1863 session_data: ui.Session.Data, 1864 ) ![]const u8 { 1865 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 1866 1867 var page_arena = std.heap.ArenaAllocator.init(allocator); 1868 defer page_arena.deinit(); 1869 1870 // the server admin repo must outlive the page build, since the session's 1871 // moment reads from it. 1872 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 1873 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 1874 1875 var session = switch (host) { 1876 .server => |server| blk: { 1877 // open the admin repo to read live user/repo data. 1878 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 1879 const repo = if (repo_maybe) |*repo| repo else unreachable; 1880 var session = try ui.Session.init(&page_arena, repo, session_data); 1881 // the session dropped a user whose account was removed, so revoke 1882 // the token that named them 1883 if (session_token) |token| { 1884 if (session.data.user_id == null) server.session_store.remove(token); 1885 } 1886 // give the page builders filesystem access to the on-disk repos (a 1887 // sibling "users" dir next to the admin repo) so the Repo page can 1888 // read its files. 1889 session.users_dir = server.users_dir; 1890 break :blk session; 1891 }, 1892 .local => |local| ui.Session{ 1893 .data = session_data, 1894 .arena = &page_arena, 1895 .page_arena = &page_arena, 1896 .local = local, 1897 }, 1898 }; 1899 session.io = io; 1900 1901 var page = try ui.Page.init(session.page_arena, &session, session.data.current_page); 1902 var root = try ui.initRoot(allocator, &page, &session); 1903 defer root.deinit(allocator); 1904 1905 const snapshot: ui.Snapshot = .{ .page = page, .session = session.data }; 1906 1907 const content = try generateHtml(allocator, &root, &session); 1908 defer allocator.free(content); 1909 1910 // serialize the snapshot so the wasm side can parse it back without making 1911 // a second request. it's embedded raw in a <script type="application/json"> 1912 // block, whose content is raw text terminated only by "</script". in json, 1913 // '<' appears solely inside string values, so escaping every '<' (and '>' 1914 // for good measure) to its \uXXXX form yields equivalent json that can't 1915 // break out of the tag. 1916 var json: std.Io.Writer.Allocating = .init(allocator); 1917 defer json.deinit(); 1918 try std.json.Stringify.value(snapshot, .{}, &json.writer); 1919 1920 var json_escaped: std.ArrayList(u8) = .empty; 1921 defer json_escaped.deinit(allocator); 1922 for (json.written()) |c| switch (c) { 1923 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 1924 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 1925 else => try json_escaped.append(allocator, c), 1926 }; 1927 1928 var out: std.ArrayList(u8) = .empty; 1929 errdefer out.deinit(allocator); 1930 { 1931 var cursor: usize = 0; 1932 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 1933 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 1934 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 1935 }) |sub| { 1936 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 1937 try out.appendSlice(allocator, template[cursor..idx]); 1938 try out.appendSlice(allocator, sub.replacement); 1939 cursor = idx + sub.needle.len; 1940 } 1941 try out.appendSlice(allocator, template[cursor..]); 1942 } 1943 return try out.toOwnedSlice(allocator); 1944 } 1945 1946 fn findEmbed(request_path: []const u8) ?Embed { 1947 const path = if (std.mem.eql(u8, request_path, "/")) 1948 "index.html" 1949 else if (request_path.len > 1 and request_path[0] == '/') 1950 request_path[1..] 1951 else 1952 return null; 1953 1954 for (embeds) |embed| { 1955 if (std.mem.eql(u8, path, embed.path)) return embed; 1956 } 1957 return null; 1958 } 1959 1960 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 1961 // own absolutely-positioned, natively-scrollable <div> holding its full content, 1962 // rendered recursively so nested scrolls work. 1963 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1964 const grid = root.getGrid() orelse return error.MissingGrid; 1965 const root_focus = root.getFocus(); 1966 1967 var out: std.ArrayList(u8) = .empty; 1968 errdefer out.deinit(allocator); 1969 1970 switch (root.*) { 1971 .background => |*background| { 1972 if (background.art.getGrid()) |art| { 1973 try out.print(allocator, "<div class=\"ansi-art\" aria-hidden=\"true\" style=\"left:{d}ch;opacity:{d}%\">", .{ grid.size.width -| art.size.width, ui.widget.AnsiBackground.art_opacity }); 1974 try renderPanel(allocator, &out, background.art.getFocus(), art, session, root_focus); 1975 try out.appendSlice(allocator, "</div>"); 1976 } 1977 }, 1978 else => {}, 1979 } 1980 try out.appendSlice(allocator, "<div class=\"grid-content\" data-key=\"panel:root\">"); 1981 try renderPanel(allocator, &out, root_focus, grid, session, root_focus); 1982 try out.appendSlice(allocator, "</div>"); 1983 try renderForms(allocator, &out, root_focus); 1984 return try out.toOwnedSlice(allocator); 1985 } 1986 1987 // render one panel — a focus subtree and its content grid — as HTML, recursing 1988 // once per web-native Scroll inside it. the root panel is the whole page; each 1989 // Scroll becomes a nested, natively-scrollable div holding its full content. 1990 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 1991 // then the child scroll divs over those holes. 1992 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid, session: *ui.Session, root_focus: *Focus) !void { 1993 // `direct` is this panel's scroll children, each drawn as an overlaid div. 1994 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 1995 // plus their descendants, which the focus tree flattens into this panel's 1996 // children): the cell hit-test below skips them so this panel doesn't claim 1997 // cells that are really rendered inside a child scroll's own panel. 1998 // (scrolls aren't nested in practice, so every scroll child is direct here.) 1999 var direct: std.ArrayList(usize) = .empty; 2000 defer direct.deinit(allocator); 2001 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 2002 defer excluded.deinit(allocator); 2003 { 2004 var it = focus.children.iterator(); 2005 while (it.next()) |e| { 2006 if (e.value_ptr.focus.scroll == null) continue; 2007 try direct.append(allocator, e.key_ptr.*); 2008 try excluded.put(allocator, e.key_ptr.*, {}); 2009 var mit = e.value_ptr.focus.children.iterator(); 2010 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 2011 } 2012 } 2013 2014 // the HTML element a run of cells is wrapped in, chosen from the cell's 2015 // focusable kind 2016 const CellTag = union(enum) { 2017 span, // clickable focusable cell 2018 a: []const u8, // clickable focusable link 2019 plain, // non-focusable, colored 2020 2021 const a_prefix = "a:"; 2022 // an "in-page" anchor: rendered as a real <a href> so it works with js 2023 // disabled, but wasm handles it without navigating. 2024 fn init(str: []const u8) @This() { 2025 if (std.mem.startsWith(u8, str, ui.raw_link_prefix)) { 2026 return .{ .a = str[ui.raw_link_prefix.len..] }; 2027 } 2028 if (std.mem.startsWith(u8, str, ui.in_page_link_prefix)) { 2029 return .{ .a = str[ui.in_page_link_prefix.len..] }; 2030 } 2031 if (std.mem.startsWith(u8, str, a_prefix)) { 2032 return .{ .a = str[a_prefix.len..] }; 2033 } 2034 return .span; 2035 } 2036 2037 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 2038 var id_buf: [32]u8 = undefined; 2039 switch (self) { 2040 .span => { 2041 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 2042 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 2043 try out.appendSlice(alloc, "\""); 2044 try out.appendSlice(alloc, style_attr); 2045 try out.appendSlice(alloc, ">"); 2046 }, 2047 .a => |href| { 2048 // tabindex=-1 keeps these out of the browser's tab order 2049 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 2050 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 2051 try out.appendSlice(alloc, "\" href=\""); 2052 try appendEscapedHtml(alloc, out, href); 2053 try out.appendSlice(alloc, "\""); 2054 try out.appendSlice(alloc, style_attr); 2055 try out.appendSlice(alloc, ">"); 2056 }, 2057 .plain => { 2058 try out.appendSlice(alloc, "<span"); 2059 try out.appendSlice(alloc, style_attr); 2060 try out.appendSlice(alloc, ">"); 2061 }, 2062 } 2063 } 2064 2065 fn closeTag(self: @This()) []const u8 { 2066 return switch (self) { 2067 .span, .plain => "</span>", 2068 .a => "</a>", 2069 }; 2070 } 2071 }; 2072 2073 // the focusable owning each cell, among this panel's own (skipping any 2074 // that belong to a child scroll, whose cells are drawn in their own panel). 2075 // claimed in focus order, so the first focusable over a cell keeps it. 2076 // looking every focusable up for every cell is quadratic in a long list. 2077 const owners = try allocator.alloc(?usize, grid.size.width * grid.size.height); 2078 defer allocator.free(owners); 2079 @memset(owners, null); 2080 { 2081 var it = focus.children.iterator(); 2082 while (it.next()) |entry| { 2083 const child = entry.value_ptr.*; 2084 if (child.focus.mode != .all) continue; 2085 if (excluded.contains(entry.key_ptr.*)) continue; 2086 const r = child.rect; 2087 for (@min(r.y, grid.size.height)..@min(r.y + r.size.height, grid.size.height)) |y| { 2088 for (@min(r.x, grid.size.width)..@min(r.x + r.size.width, grid.size.width)) |x| { 2089 const owner = &owners[y * grid.size.width + x]; 2090 if (owner.* == null) owner.* = entry.key_ptr.*; 2091 } 2092 } 2093 } 2094 } 2095 2096 // the cells are the volatile part of a panel. js replaces this one subtree 2097 // wholesale while retaining the panel's native controls and scroll shells. 2098 try output.appendSlice(allocator, "<div class=\"grid-cells\">"); 2099 2100 // emit this panel's grid as rows of text, coalescing adjacent cells that 2101 // share a focus id and style into one tag (a clickable span, a link, or a 2102 // plain styled span). cells under a child scroll keep only their background. 2103 // a cell's own link is an anchor nested in that tag. 2104 for (0..grid.size.height) |y| { 2105 var cur_id: ?usize = null; 2106 var cur_style: Grid.Style = .{}; 2107 var open_tag: ?CellTag = null; 2108 var open_link: ?[]const u8 = null; 2109 var first = true; 2110 for (0..grid.size.width) |x| { 2111 const cell = (try grid.cell(x, y)).*; 2112 // a cell covered by a child scroll's viewport is drawn by that scroll's 2113 // own div, so blank its glyph and make it non-clickable here — but keep 2114 // its background, so the backdrop still shows through the scroll's 2115 // transparent div instead of a bare hole. 2116 const covered_by_scroll = blk: { 2117 for (direct.items) |id| { 2118 const r = (focus.children.get(id) orelse continue).rect; 2119 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; 2120 } 2121 break :blk false; 2122 }; 2123 // the focusable owning the cell at (x, y); none for a covered cell. 2124 const cell_id = if (covered_by_scroll) null else owners[y * grid.size.width + x]; 2125 const style: Grid.Style = if (covered_by_scroll) .{ .bg = cell.style.bg } else cell.style; 2126 2127 if (first or cell_id != cur_id or !style.eql(cur_style)) { 2128 if (open_link != null) try output.appendSlice(allocator, "</a>"); 2129 open_link = null; 2130 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2131 2132 var new_tag: ?CellTag = null; 2133 if (cell_id) |id| { 2134 if (focus.children.get(id)) |child| { 2135 new_tag = switch (child.focus.kind) { 2136 .custom => |custom| CellTag.init(custom), 2137 else => .span, 2138 }; 2139 } 2140 } 2141 if (new_tag == null and !style.eql(.{})) new_tag = .plain; 2142 2143 if (new_tag) |t| { 2144 var style_buf: [192]u8 = undefined; 2145 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, style)); 2146 } 2147 2148 open_tag = new_tag; 2149 cur_id = cell_id; 2150 cur_style = style; 2151 first = false; 2152 } 2153 2154 // an anchor can't nest in another, so a link tag's cells skip theirs 2155 const in_anchor = if (open_tag) |t| t == .a else false; 2156 const link = if (covered_by_scroll or in_anchor) null else webLink(cell.link); 2157 if (!sameLink(link, open_link)) { 2158 if (open_link != null) try output.appendSlice(allocator, "</a>"); 2159 if (link) |url| { 2160 try output.appendSlice(allocator, "<a class=\"cell-link\" tabindex=\"-1\" target=\"_blank\" rel=\"noopener noreferrer\" href=\""); 2161 try appendEscapedHtml(allocator, output, url); 2162 try output.appendSlice(allocator, "\">"); 2163 } 2164 open_link = link; 2165 } 2166 2167 if (covered_by_scroll) { 2168 try appendEscapedHtml(allocator, output, " "); 2169 } else if (cell.continuation) { 2170 // the wide rune to the left was emitted 2ch wide, covering this column 2171 } else if (cell.rune) |rune| { 2172 var encoded: [4]u8 = undefined; 2173 const encoded_len = try std.unicode.utf8Encode(rune, &encoded); 2174 const rune_text = encoded[0..encoded_len]; 2175 // a double-width rune is pinned inside a 2ch span so the 2176 // fallback glyph's advance width can't shift the rest of the row 2177 const wide = x + 1 < grid.size.width and (try grid.cell(x + 1, y)).continuation; 2178 if (wide) { 2179 try output.appendSlice(allocator, "<span class=\"w2\">"); 2180 try appendEscapedHtml(allocator, output, rune_text); 2181 try output.appendSlice(allocator, "</span>"); 2182 } else { 2183 try appendEscapedHtml(allocator, output, rune_text); 2184 } 2185 } else { 2186 try appendEscapedHtml(allocator, output, " "); 2187 } 2188 } 2189 if (open_link != null) try output.appendSlice(allocator, "</a>"); 2190 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2191 try output.append(allocator, '\n'); 2192 } 2193 try output.appendSlice(allocator, "</div>"); 2194 2195 // native controls live in their panel, beside the replaceable cells. their 2196 // stable keys let JS update layout without recreating their DOM nodes, and 2197 // being actual descendants of a scroll gives them native movement/clipping. 2198 try renderPanelControls(allocator, output, focus, session, root_focus, &excluded); 2199 2200 // each child scroll becomes a natively-scrollable div positioned over its 2201 // viewport, holding its full content rendered recursively. 2202 for (direct.items) |id| { 2203 const child = focus.children.get(id) orelse continue; 2204 const info = child.focus.scroll orelse continue; 2205 const r = child.rect; 2206 // overflow only on the axes the widget scrolls; `auto` shows a bar only 2207 // when that axis actually overflows. the other axis is clipped (hidden), 2208 // matching how the terminal Scroll handles its non-scrolling axis. 2209 const overflow = switch (info.direction) { 2210 .vert => "overflow-x:hidden;overflow-y:auto", 2211 .horiz => "overflow-x:auto;overflow-y:hidden", 2212 .both => "overflow:auto", 2213 }; 2214 // the id carries a content version so JS preserves the native scroll 2215 // position across re-renders of the same content but resets it when the 2216 // content is replaced — e.g. selecting a different commit. the widget's 2217 // scroll offset (in cells) rides along so JS can apply it when it has no 2218 // preserved position, letting a wasm-side scrollToRect (the files list 2219 // scrolling to its selected row on page load) reach the browser. 2220 var buf: [256]u8 = undefined; 2221 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, "<div class=\"scroll\" data-key=\"scroll:{d}\" data-scroll-id=\"{d}-{d}\" data-scroll-direction=\"{s}\" data-scroll-x=\"{d}\" data-scroll-y=\"{d}\" style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em;{s}\">", .{ id, id, child.focus.version, @tagName(info.direction), info.offset_x, info.offset_y, r.x, r.y, r.size.width, r.size.height, overflow })); 2222 try renderPanel(allocator, output, child.focus, info.content, session, root_focus); 2223 try output.appendSlice(allocator, "</div>"); 2224 } 2225 } 2226 2227 const form_prefix = "form:"; 2228 const form_id_prefix = "haxy-form-"; 2229 2230 fn formAction(focus: *const Focus) ?[]const u8 { 2231 return switch (focus.kind) { 2232 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) custom[form_prefix.len..] else null, 2233 else => null, 2234 }; 2235 } 2236 2237 // find the form ancestor of a flattened focus-tree child. html's `form` 2238 // attribute then associates the control with that form without requiring the 2239 // form and control to share a DOM parent. 2240 fn formOwner(root_focus: *Focus, focus_id: usize) ?usize { 2241 var id = focus_id; 2242 while (root_focus.children.get(id)) |child| { 2243 const parent_id = child.parent_id; 2244 if (parent_id == root_focus.id) return if (formAction(root_focus) != null) root_focus.id else null; 2245 const parent = root_focus.children.get(parent_id) orelse return null; 2246 if (formAction(parent.focus) != null) return parent_id; 2247 id = parent_id; 2248 } 2249 return null; 2250 } 2251 2252 fn appendFormAttribute(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus, focus_id: usize) !void { 2253 const form_id = formOwner(root_focus, focus_id) orelse return; 2254 var buf: [64]u8 = undefined; 2255 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, " form=\"" ++ form_id_prefix ++ "{d}\"", .{form_id})); 2256 } 2257 2258 fn renderPanelControls( 2259 allocator: std.mem.Allocator, 2260 output: *std.ArrayList(u8), 2261 focus: *Focus, 2262 session: *ui.Session, 2263 root_focus: *Focus, 2264 excluded: *const std.AutoHashMapUnmanaged(usize, void), 2265 ) !void { 2266 var iter = focus.children.iterator(); 2267 while (iter.next()) |entry| { 2268 const id = entry.key_ptr.*; 2269 if (excluded.contains(id)) continue; 2270 const child = entry.value_ptr.*; 2271 const r = child.rect; 2272 2273 if (r.size.width == 0 or r.size.height == 0) continue; // not laid out, rather than merely off-screen 2274 2275 switch (child.focus.kind) { 2276 .text_input, .text_input_password, .text_area => { 2277 const ti = session.text_inputs.get(id) orelse continue; 2278 2279 const inner_left = r.x + 1; 2280 const inner_top = r.y + 1; 2281 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 2282 const preserve = !ti.options.read_only; 2283 2284 if (child.focus.kind == .text_area) { 2285 const value = try ti.text(allocator); 2286 defer allocator.free(value); 2287 var id_buf: [128]u8 = undefined; 2288 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<textarea data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2289 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2290 try appendFormAttribute(allocator, output, root_focus, id); 2291 if (ti.options.name.len > 0) { 2292 try output.appendSlice(allocator, " name=\""); 2293 try appendEscapedHtml(allocator, output, ti.options.name); 2294 try output.append(allocator, '"'); 2295 } 2296 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 2297 var pos_buf: [128]u8 = undefined; 2298 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">\n", .{ inner_left, inner_top, inner_width, inner_height })); 2299 try appendEscapedHtml(allocator, output, value); 2300 try output.appendSlice(allocator, "</textarea>"); 2301 continue; 2302 } 2303 2304 var id_buf: [160]u8 = undefined; 2305 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<input type=\"{s}\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ if (child.focus.kind == .text_input_password) "password" else "text", id, id })); 2306 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2307 try appendFormAttribute(allocator, output, root_focus, id); 2308 if (ti.options.name.len > 0) { 2309 try output.appendSlice(allocator, " name=\""); 2310 try appendEscapedHtml(allocator, output, ti.options.name); 2311 try output.append(allocator, '"'); 2312 } 2313 if (child.focus.kind != .text_input_password) { 2314 const value = try ti.text(allocator); 2315 defer allocator.free(value); 2316 try output.appendSlice(allocator, " value=\""); 2317 try appendEscapedHtml(allocator, output, value); 2318 try output.append(allocator, '"'); 2319 } 2320 var pos_buf: [96]u8 = undefined; 2321 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:1em\">", .{ inner_left, inner_top, inner_width })); 2322 }, 2323 .custom => |custom| { 2324 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2325 if (formOwner(root_focus, id) == null) continue; 2326 var id_buf: [128]u8 = undefined; 2327 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2328 try appendFormAttribute(allocator, output, root_focus, id); 2329 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2330 try output.appendSlice(allocator, " formaction=\""); 2331 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 2332 try output.append(allocator, '"'); 2333 } 2334 var pos_buf: [128]u8 = undefined; 2335 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\"></button>", .{ r.x, r.y, r.size.width, r.size.height })); 2336 } else if (std.mem.startsWith(u8, custom, ui.radio_prefix)) { 2337 // an invisible native radio over the option, checked when the option is its row's selection 2338 const field = custom[ui.radio_prefix.len..]; 2339 const separator = std.mem.indexOfScalar(u8, field, '=') orelse continue; 2340 const row = root_focus.children.get(child.parent_id) orelse continue; 2341 var id_buf: [128]u8 = undefined; 2342 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<input type=\"radio\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2343 try appendFormAttribute(allocator, output, root_focus, id); 2344 try output.appendSlice(allocator, " name=\""); 2345 try appendEscapedHtml(allocator, output, field[0..separator]); 2346 try output.appendSlice(allocator, "\" value=\""); 2347 try appendEscapedHtml(allocator, output, field[separator + 1 ..]); 2348 try output.append(allocator, '"'); 2349 if (row.focus.child_id == id) try output.appendSlice(allocator, " checked"); 2350 var pos_buf: [128]u8 = undefined; 2351 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"opacity:0;left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">", .{ r.x, r.y, r.size.width, r.size.height })); 2352 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 2353 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 2354 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 2355 var id_buf: [128]u8 = undefined; 2356 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "\" data-key=\"control:{d}\" data-focus-id=\"{d}\" style=\"opacity:0;left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">", .{ id, id, r.x, r.y, r.size.width, r.size.height })); 2357 } 2358 }, 2359 else => {}, 2360 } 2361 } 2362 } 2363 2364 // emit hidden form owners beside the rendered panels. their controls point 2365 // back here with the standard HTML `form` attribute. 2366 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 2367 // the focus child map preserves insertion order, which matches the order 2368 // widgets were added in code 2369 var iter = root_focus.children.iterator(); 2370 while (iter.next()) |entry| { 2371 const child = entry.value_ptr.*; 2372 const action_url = formAction(child.focus) orelse continue; 2373 2374 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 2375 var id_buf: [96]u8 = undefined; 2376 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 2377 try appendEscapedHtml(allocator, output, action_url); 2378 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 2379 } 2380 } 2381 2382 // the 16 ansi colors as the browser shows them (xterm's defaults) 2383 const ansi_palette = [16]Grid.Color.Rgb{ 2384 .{ .r = 0x00, .g = 0x00, .b = 0x00 }, .{ .r = 0xcd, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xcd, .b = 0x00 }, .{ .r = 0xcd, .g = 0xcd, .b = 0x00 }, 2385 .{ .r = 0x00, .g = 0x00, .b = 0xee }, .{ .r = 0xcd, .g = 0x00, .b = 0xcd }, .{ .r = 0x00, .g = 0xcd, .b = 0xcd }, .{ .r = 0xe5, .g = 0xe5, .b = 0xe5 }, 2386 .{ .r = 0x7f, .g = 0x7f, .b = 0x7f }, .{ .r = 0xff, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xff, .b = 0x00 }, .{ .r = 0xff, .g = 0xff, .b = 0x00 }, 2387 .{ .r = 0x5c, .g = 0x5c, .b = 0xff }, .{ .r = 0xff, .g = 0x00, .b = 0xff }, .{ .r = 0x00, .g = 0xff, .b = 0xff }, .{ .r = 0xff, .g = 0xff, .b = 0xff }, 2388 }; 2389 2390 // resolve any color to rgb: palette colors through the ansi table and the 2391 // xterm 256-color layout (16 ansi, a 6x6x6 cube, then 24 grays) 2392 fn colorRgb(color: Grid.Color) Grid.Color.Rgb { 2393 return switch (color) { 2394 .rgb => |c| c, 2395 .ansi => |a| ansi_palette[@intFromEnum(a)], 2396 .indexed => |n| if (n < 16) 2397 ansi_palette[n] 2398 else if (n < 232) blk: { 2399 const levels = [6]u8{ 0, 0x5f, 0x87, 0xaf, 0xd7, 0xff }; 2400 const i = n - 16; 2401 break :blk .{ .r = levels[i / 36], .g = levels[(i / 6) % 6], .b = levels[i % 6] }; 2402 } else blk: { 2403 const v: u8 = 8 + (n - 232) * 10; 2404 break :blk .{ .r = v, .g = v, .b = v }; 2405 }, 2406 }; 2407 } 2408 2409 // builds an HTML ` style="color:…;background-color:…"` attribute from a 2410 // cell's style into `buf`, omitting whichever color is unset. an inverted 2411 // cell swaps the two, falling back to the page's --fg/--bg variables for 2412 // whichever side is unset. text attributes follow the colors. returns an 2413 // empty slice when nothing is set. 2414 fn styleAttr(buf: []u8, style: Grid.Style) []const u8 { 2415 if (style.eql(.{})) return buf[0..0]; 2416 const prefix = " style=\""; 2417 @memcpy(buf[0..prefix.len], prefix); 2418 var i: usize = prefix.len; 2419 const inverted = style.inverted; 2420 i = cssColor(buf, i, "color", if (inverted) style.bg else style.fg, if (inverted) "var(--bg)" else null) orelse return buf[0..0]; 2421 i = cssColor(buf, i, "background-color", if (inverted) style.fg else style.bg, if (inverted) "var(--fg)" else null) orelse return buf[0..0]; 2422 const decoration: []const u8 = if (style.underline and style.strikethrough) 2423 "text-decoration:underline line-through;" 2424 else if (style.underline) 2425 "text-decoration:underline;" 2426 else if (style.strikethrough) 2427 "text-decoration:line-through;" 2428 else 2429 ""; 2430 const attributes = std.fmt.bufPrint(buf[i..], "{s}{s}{s}{s}", .{ 2431 if (style.bold) "font-weight:bold;" else "", 2432 if (style.italic) "font-style:italic;" else "", 2433 decoration, 2434 if (style.dim) "opacity:.6;" else "", 2435 }) catch return buf[0..0]; 2436 i += attributes.len; 2437 if (i >= buf.len) return buf[0..0]; 2438 buf[i] = '"'; 2439 return buf[0 .. i + 1]; 2440 } 2441 2442 // append `prop:value;` at buf[i..] for the color, or for the fallback when 2443 // the color is unset (nothing when both are). returns the new end, or null 2444 // when it doesn't fit. 2445 fn cssColor(buf: []u8, i: usize, prop: []const u8, color: ?Grid.Color, fallback: ?[]const u8) ?usize { 2446 const s = if (color) |c| blk: { 2447 const v = colorRgb(c); 2448 break :blk std.fmt.bufPrint(buf[i..], "{s}:#{x:0>2}{x:0>2}{x:0>2};", .{ prop, v.r, v.g, v.b }) catch return null; 2449 } else if (fallback) |f| 2450 std.fmt.bufPrint(buf[i..], "{s}:{s};", .{ prop, f }) catch return null 2451 else 2452 return i; 2453 return i + s.len; 2454 } 2455 2456 // a cell's link as an href, when it's a web or mail url 2457 fn webLink(link: ?[]const u8) ?[]const u8 { 2458 const url = link orelse return null; 2459 for ([_][]const u8{ "http://", "https://", "mailto:" }) |scheme| { 2460 if (std.ascii.startsWithIgnoreCase(url, scheme)) return url; 2461 } 2462 return null; 2463 } 2464 2465 fn sameLink(a: ?[]const u8, b: ?[]const u8) bool { 2466 if (a) |x| return if (b) |y| std.mem.eql(u8, x, y) else false; 2467 return b == null; 2468 } 2469 2470 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2471 for (input) |ch| { 2472 switch (ch) { 2473 '&' => try out.appendSlice(allocator, "&amp;"), 2474 '<' => try out.appendSlice(allocator, "&lt;"), 2475 '>' => try out.appendSlice(allocator, "&gt;"), 2476 '"' => try out.appendSlice(allocator, "&quot;"), 2477 '\'' => try out.appendSlice(allocator, "&#39;"), 2478 else => try out.append(allocator, ch), 2479 } 2480 } 2481 } 2482 2483 // --- helpers -------------------------------------------------------------- 2484 2485 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 2486 var iter = request.iterateHeaders(); 2487 while (iter.next()) |header| { 2488 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2489 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2490 while (pairs.next()) |pair| { 2491 const trimmed = std.mem.trim(u8, pair, " \t"); 2492 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2493 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2494 return trimmed[eq + 1 ..]; 2495 } 2496 } 2497 } 2498 return null; 2499 } 2500 2501 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2502 var iter = std.mem.splitScalar(u8, body, '&'); 2503 while (iter.next()) |pair| { 2504 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2505 if (std.mem.eql(u8, pair[0..eq], key)) { 2506 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2507 } 2508 } 2509 return null; 2510 } 2511 2512 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2513 var buffer: [256]u8 = undefined; 2514 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2515 } 2516 2517 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2518 var out: std.ArrayList(u8) = .empty; 2519 errdefer out.deinit(allocator); 2520 var i: usize = 0; 2521 while (i < encoded.len) : (i += 1) { 2522 switch (encoded[i]) { 2523 '+' => try out.append(allocator, ' '), 2524 '%' => { 2525 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2526 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2527 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2528 try out.append(allocator, hi * 16 + lo); 2529 i += 2; 2530 }, 2531 else => try out.append(allocator, encoded[i]), 2532 } 2533 } 2534 return try out.toOwnedSlice(allocator); 2535 } 2536 2537 // disk-backed web session store. each login mints a random, opaque token 2538 // (not the user's id) that is stored as a file named by the token hex, whose 2539 // contents are the raw user_id bytes. authenticating a request is a lookup of 2540 // the cookie's token; logout deletes the file, revoking the session. there is 2541 // deliberately no expiry — a session lives until logout. form failures use 2542 // files in the flash subdirectory that the redirected GET consumes. the 2543 // directory is cleared whenever the server starts. 2544 pub const SessionStore = struct { 2545 io: std.Io, 2546 dir: std.Io.Dir, 2547 flash_dir: std.Io.Dir, 2548 auto_login: ?[token_hex_len]u8, 2549 2550 pub const token_hex_len = evt.event_id_size * 2; 2551 2552 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2553 try data_dir.createDirPath(io, "sessions"); 2554 const dir = try data_dir.openDir(io, "sessions", .{}); 2555 errdefer dir.close(io); 2556 try dir.deleteTree(io, "flash"); 2557 try dir.createDirPath(io, "flash"); 2558 const flash_dir = try dir.openDir(io, "flash", .{}); 2559 errdefer flash_dir.close(io); 2560 const auto_login = blk: { 2561 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2562 defer file.close(io); 2563 var token: [token_hex_len]u8 = undefined; 2564 var storage: [token_hex_len]u8 = undefined; 2565 var reader = file.reader(io, &storage); 2566 reader.interface.readSliceAll(&token) catch break :blk null; 2567 break :blk token; 2568 }; 2569 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 2570 } 2571 2572 pub fn deinit(self: SessionStore) void { 2573 self.flash_dir.close(self.io); 2574 self.dir.close(self.io); 2575 } 2576 2577 // mint a new session for user_id, returning the token hex to set as the 2578 // cookie value. 2579 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2580 var token: [evt.event_id_size]u8 = undefined; 2581 self.io.random(&token); 2582 const token_hex = std.fmt.bytesToHex(token, .lower); 2583 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2584 defer file.close(self.io); 2585 try file.writeStreamingAll(self.io, user_id); 2586 return token_hex; 2587 } 2588 2589 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 2590 var token: [evt.event_id_size]u8 = undefined; 2591 self.io.random(&token); 2592 const token_hex = std.fmt.bytesToHex(token, .lower); 2593 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 2594 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 2595 defer file.close(self.io); 2596 2597 var json: std.Io.Writer.Allocating = .init(allocator); 2598 defer json.deinit(); 2599 try std.json.Stringify.value(value, .{}, &json.writer); 2600 try file.writeStreamingAll(self.io, json.written()); 2601 return token_hex; 2602 } 2603 2604 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 2605 if (!isToken(token_hex)) return null; 2606 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 2607 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 2608 defer file.close(self.io); 2609 2610 var storage: [4096]u8 = undefined; 2611 var reader = file.reader(self.io, &storage); 2612 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 2613 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 2614 } 2615 2616 // resolve a cookie's token to its user_id. returns false (logged out) for a 2617 // missing, malformed, or unknown token. 2618 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2619 if (!isToken(token_hex)) return false; 2620 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2621 defer file.close(self.io); 2622 var storage: [evt.event_id_size]u8 = undefined; 2623 var file_reader = file.reader(self.io, &storage); 2624 file_reader.interface.readSliceAll(out) catch return false; 2625 return true; 2626 } 2627 2628 // revoke a session. a no-op for a missing or malformed token. 2629 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2630 if (!isToken(token_hex)) return; 2631 self.dir.deleteFile(self.io, token_hex) catch {}; 2632 } 2633 2634 // leave `token_hex`'s session for visitors arriving without one. only the 2635 // `try` fixture writes one. the name can't collide with a session token. 2636 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2637 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2638 defer file.close(self.io); 2639 try file.writeStreamingAll(self.io, token_hex); 2640 } 2641 2642 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2643 out.* = self.auto_login orelse return false; 2644 return true; 2645 } 2646 2647 const auto_login_name = "auto-login"; 2648 2649 // a token is exactly token_hex_len hex chars. validating before using the 2650 // value as a path keeps attacker-supplied cookies from escaping the 2651 // sessions dir (e.g. via "/" or ".." bytes). 2652 fn isToken(token_hex: []const u8) bool { 2653 if (token_hex.len != token_hex_len) return false; 2654 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2655 return true; 2656 } 2657 }; 2658