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