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