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