╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const obj = xit.object; 5 const hash = xit.hash; 6 const evt = @import("./event.zig"); 7 const serve_common = @import("./serve_common.zig"); 8 const ui = @import("./ui.zig"); 9 const fork = @import("./fork.zig"); 10 const pch = @import("./patch.zig"); 11 const xitui = xit.xitui; 12 const wgt = xitui.widget; 13 const Focus = xitui.focus.Focus; 14 const Grid = xitui.grid.Grid; 15 16 const cookie_name = "haxy_session"; 17 // the session cookie a login or a claimed auto-login sets; both must scope 18 // it the same way. 19 const session_cookie_fmt = cookie_name ++ "={s}; Path=/; HttpOnly; SameSite=Strict"; 20 const form_flash_cookie = "haxy_form_flash"; 21 const local_flash_cookie = "haxy_local_flash"; 22 const local_required_title_prefix = "required_title:"; 23 const local_sync_failure_prefix = "sync:"; 24 25 const Embed = struct { 26 path: []const u8, 27 content_type: []const u8, 28 body: []const u8, 29 }; 30 31 const embeds = [_]Embed{ 32 .{ .path = "index.html", .content_type = "text/html; charset=utf-8", .body = @embedFile("embed/index.html") }, 33 .{ .path = "script.js", .content_type = "text/javascript; charset=utf-8", .body = @embedFile("embed/script.js") }, 34 .{ .path = "term.ttf", .content_type = "font/ttf", .body = @embedFile("embed/term.ttf") }, 35 .{ .path = "haxy.wasm", .content_type = "application/wasm", .body = @embedFile("haxy.wasm") }, 36 }; 37 38 // what a web request is served from: the multi-user server (admin repo + 39 // login sessions) or a single local repo. 40 pub const Host = union(evt.HostKind) { 41 local: ui.RepoSource, 42 server: struct { 43 admin_repo_path: []const u8, 44 users_dir: []const u8, 45 session_store: SessionStore, 46 git_http_port: ?u16, 47 git_ssh_port: ?u16, 48 git_ssh_prefix: []const u8, 49 }, 50 }; 51 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.users_dir, 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.users_dir, 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.users_dir, 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 const fork_path = try fork.create(.{}, io, allocator, server.users_dir, .{ 712 .id = event_id_hex, 713 .user_id = user_id, 714 .repo_id = repo_id, 715 .repo_user_id = repo_user_id, 716 .title = title, 717 .description = description, 718 .labels = labels, 719 .target_branch = target_branch, 720 .author = author, 721 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 722 }); 723 defer allocator.free(fork_path); 724 } else { 725 const event = evt.EventWithId{ 726 .id = event_id_hex, 727 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 728 .author = author, 729 .event = switch (kind) { 730 .issue => .{ .issue = .{ .title = title, .description = description, .labels = labels } }, 731 .patch => .{ .patch = .{ .title = title, .description = description, .labels = labels, .target_branch = target_branch, .source_branch = source_branch } }, 732 .discuss => .{ .discuss = .{ .title = title, .description = description, .labels = labels } }, 733 else => unreachable, 734 }, 735 }; 736 737 switch (source.repo_kind) { 738 inline else => |repo_kind| { 739 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 740 defer any_repo.deinit(io, allocator); 741 switch (any_repo) { 742 inline else => |*repo| { 743 const result = if (kind == .patch) 744 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) 745 else 746 evt.consume(std.meta.activeTag(host), .repo, repo_kind, repo.self_repo_opts, io, allocator, repo, evt.events_ref, &.{event}); 747 result catch |err| { 748 if (kind != .patch) return err; 749 const failure = ui.Session.FormFeedback.PatchFailure.fromError(err) orelse return err; 750 const form_location = try std.fmt.allocPrint(allocator, "{s}/patches/new", .{base}); 751 defer allocator.free(form_location); 752 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(failure, title, labels, description, target_branch, source_branch)); 753 }; 754 }, 755 } 756 }, 757 } 758 } 759 760 const location = try std.fmt.allocPrint(allocator, "{s}/{s}:{s}", .{ base, @tagName(kind), &event_id_hex }); 761 defer allocator.free(location); 762 try request.respond("", .{ 763 .status = .see_other, 764 .extra_headers = &.{.{ .name = "location", .value = location }}, 765 }); 766 } 767 768 const CommentBaseParts = struct { 769 repo_base: []const u8, 770 thread_kind: evt.EventKind, 771 thread_id: [evt.event_id_size]u8, 772 comment_id: ?[evt.event_id_size]u8, 773 }; 774 775 fn commentBaseParts(base: []const u8) ?CommentBaseParts { 776 const route = ui.RoutablePage.fromUrl(base) orelse ui.RoutablePage.fromUrlLocal(base) orelse return null; 777 const identity, const thread_kind, const thread_hex, const comment_hex = switch (route) { 778 .repo_issues => |*issue| .{ issue.name.slice(), evt.EventKind.issue, issue.selected.slice(), issue.comment.slice() }, 779 .repo_patches => |*patch| .{ patch.name.slice(), evt.EventKind.patch, patch.selected.slice(), patch.comment.slice() }, 780 .repo_discussions => |*discussion| .{ discussion.name.slice(), evt.EventKind.discuss, discussion.selected.slice(), discussion.comment.slice() }, 781 else => return null, 782 }; 783 const thread_id = evt.parseEventId(thread_hex) catch return null; 784 const comment_id = if (comment_hex.len == 0) null else evt.parseEventId(comment_hex) catch return null; 785 const repo_base_len = if (identity.len == 0) 0 else "/repo/".len + identity.len; 786 return .{ .repo_base = base[0..repo_base_len], .thread_kind = thread_kind, .thread_id = thread_id, .comment_id = comment_id }; 787 } 788 789 fn handlePatchPublish( 790 io: std.Io, 791 request: *std.http.Server.Request, 792 allocator: std.mem.Allocator, 793 base: []const u8, 794 host: Host, 795 ) !void { 796 const parts = commentBaseParts(base) orelse return respondRemoveNotFound(request); 797 if (parts.thread_kind != .patch or parts.comment_id != null) return respondRemoveNotFound(request); 798 const server = switch (host) { 799 .server => |server| server, 800 .local => return respondRemoveNotFound(request), 801 }; 802 var author_arena = std.heap.ArenaAllocator.init(allocator); 803 defer author_arena.deinit(); 804 // only the draft's author may publish it, which publish checks 805 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return; 806 const user_id = actor.user_id orelse return respondLoginRequired(request); 807 const author = actor.author; 808 809 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 810 defer request_repo.deinit(allocator); 811 const repo_id = evt.parseEventId(std.fs.path.basename(request_repo.source.path)) catch return respondRemoveNotFound(request); 812 var target_repo = try rp.Repo(.xit, .{}).open(io, allocator, request_repo.source.localInitOpts()); 813 defer target_repo.deinit(io, allocator); 814 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 815 defer admin_repo.deinit(io, allocator); 816 const id = std.fmt.bytesToHex(parts.thread_id, .lower); 817 try pch.publish(.{}, io, allocator, server.users_dir, &admin_repo, &target_repo, .{ 818 .id = id, 819 .user_id = user_id, 820 .repo_id = repo_id, 821 .author = author, 822 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 823 }); 824 try request.respond("", .{ 825 .status = .see_other, 826 .extra_headers = &.{.{ .name = "location", .value = base }}, 827 }); 828 } 829 830 fn handlePatchMerge( 831 io: std.Io, 832 request: *std.http.Server.Request, 833 allocator: std.mem.Allocator, 834 base: []const u8, 835 host: Host, 836 revision: evt.Patch.MergeRevision, 837 ) !void { 838 const parts = commentBaseParts(base) orelse return respondRemoveNotFound(request); 839 if (parts.thread_kind != .patch or parts.comment_id != null) return respondRemoveNotFound(request); 840 const server = switch (host) { 841 .server => |server| server, 842 .local => return respondRemoveNotFound(request), 843 }; 844 var author_arena = std.heap.ArenaAllocator.init(allocator); 845 defer author_arena.deinit(); 846 const author = ((try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .write)) orelse return).author; 847 848 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 849 defer request_repo.deinit(allocator); 850 var target_repo = try rp.Repo(.xit, .{}).open(io, allocator, request_repo.source.localInitOpts()); 851 defer target_repo.deinit(io, allocator); 852 853 const id = std.fmt.bytesToHex(parts.thread_id, .lower); 854 pch.mergeAndRemoveFork(.{}, io, allocator, server.users_dir, &target_repo, .{ 855 .id = id, 856 .revision = revision, 857 .author = author, 858 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 859 }) catch |err| switch (err) { 860 error.MergeConflict => return request.respond("merge conflict", .{ 861 .status = .conflict, 862 .keep_alive = false, 863 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 864 }), 865 error.MergeCheckUnavailable, error.PatchOutOfDate, error.PatchDataUnavailable => {}, 866 else => return err, 867 }; 868 869 const location = try std.fmt.allocPrint(allocator, "{s}/patch:{s}", .{ parts.repo_base, &id }); 870 defer allocator.free(location); 871 try request.respond("", .{ 872 .status = .see_other, 873 .keep_alive = false, 874 .extra_headers = &.{.{ .name = "location", .value = location }}, 875 }); 876 } 877 878 // create a reply and redirect to its permalink. 879 fn handleCommentNew( 880 io: std.Io, 881 request: *std.http.Server.Request, 882 allocator: std.mem.Allocator, 883 base: []const u8, 884 host: Host, 885 ) !void { 886 const not_found = "comment parent not found"; 887 const parts = commentBaseParts(base) orelse { 888 try request.respond(not_found, .{ 889 .status = .not_found, 890 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 891 }); 892 return; 893 }; 894 895 var author_arena = std.heap.ArenaAllocator.init(allocator); 896 defer author_arena.deinit(); 897 const author = ((try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return).author; 898 899 const form_body = try readFormBody(request, allocator); 900 defer allocator.free(form_body); 901 const body_crlf = (try parseFormField(allocator, form_body, "body")) orelse try allocator.dupe(u8, ""); 902 defer allocator.free(body_crlf); 903 const body = try std.mem.replaceOwned(u8, allocator, body_crlf, "\r\n", "\n"); 904 defer allocator.free(body); 905 906 if (!evt.Comment.fieldsValid(body)) { 907 const form_location = try std.fmt.allocPrint(allocator, "{s}/new", .{base}); 908 defer allocator.free(form_location); 909 try request.respond("", .{ 910 .status = .see_other, 911 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 912 }); 913 return; 914 } 915 916 const thread_id_hex = std.fmt.bytesToHex(parts.thread_id, .lower); 917 const parent_id_hex = std.fmt.bytesToHex(parts.comment_id orelse parts.thread_id, .lower); 918 919 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse { 920 try request.respond(not_found, .{ 921 .status = .not_found, 922 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 923 }); 924 return; 925 }; 926 defer request_repo.deinit(allocator); 927 const source = request_repo.source; 928 var event_id_hex: [evt.event_id_size * 2]u8 = undefined; 929 switch (source.repo_kind) { 930 inline else => |repo_kind| { 931 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 932 defer any_repo.deinit(io, allocator); 933 switch (any_repo) { 934 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), 935 } 936 }, 937 } 938 939 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 }); 940 defer allocator.free(location); 941 try request.respond("", .{ 942 .status = .see_other, 943 .extra_headers = &.{.{ .name = "location", .value = location }}, 944 }); 945 } 946 947 const AttachmentRequest = struct { 948 repo_base: []const u8, 949 id: [evt.event_id_size]u8, 950 }; 951 952 // an attachment url is its repo's base and the attachment's event id 953 fn attachmentRequest(path: []const u8) ?AttachmentRequest { 954 const infix = "/attachment:"; 955 const at = std.mem.lastIndexOf(u8, path, infix) orelse return null; 956 const tail = path[at + infix.len ..]; 957 const id = evt.parseEventId(tail) catch return null; 958 return .{ .repo_base = path[0..at], .id = id }; 959 } 960 961 // serve an attachment's bytes from the repo its url names 962 fn serveAttachment( 963 io: std.Io, 964 request: *std.http.Server.Request, 965 allocator: std.mem.Allocator, 966 attachment: AttachmentRequest, 967 host: Host, 968 ) !void { 969 if (!try mayRead(io, allocator, request, host, attachment.repo_base)) return respondAttachmentNotFound(request); 970 const request_repo = (try requestRepoSource(io, allocator, host, attachment.repo_base)) orelse return respondAttachmentNotFound(request); 971 defer request_repo.deinit(allocator); 972 const source = request_repo.source; 973 switch (source.repo_kind) { 974 inline else => |repo_kind| { 975 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 976 defer any_repo.deinit(io, allocator); 977 switch (any_repo) { 978 inline else => |*repo| try sendAttachment(repo_kind, repo.self_repo_opts, io, request, allocator, repo, &attachment.id), 979 } 980 }, 981 } 982 } 983 984 fn sendAttachment( 985 comptime repo_kind: rp.RepoKind, 986 comptime repo_opts: rp.RepoOpts(repo_kind), 987 io: std.Io, 988 request: *std.http.Server.Request, 989 allocator: std.mem.Allocator, 990 repo: *rp.Repo(repo_kind, repo_opts), 991 id: *const [evt.event_id_size]u8, 992 ) !void { 993 var arena = std.heap.ArenaAllocator.init(allocator); 994 defer arena.deinit(); 995 996 const DB = evt.EventDB(repo_opts.hash); 997 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; 998 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 999 const haxy_moment = (if (event_db_maybe) |*event_db| 1000 evt.currentMomentFromDb(repo_opts.hash, event_db.db) 1001 else if (repo_kind == .git) 1002 return respondAttachmentNotFound(request) 1003 else 1004 evt.currentMoment(repo_opts, repo)) catch return respondAttachmentNotFound(request); 1005 1006 const record = (try evt.Attachment.readById(DB, repo_opts.hash, haxy_moment, &arena, id)) orelse return respondAttachmentNotFound(request); 1007 if (record.removed) return respondAttachmentNotFound(request); 1008 if (record.blob_oid.len != hash.hexLen(repo_opts.hash)) return respondAttachmentNotFound(request); 1009 const blob_oid: *const [hash.hexLen(repo_opts.hash)]u8 = @ptrCast(record.blob_oid.ptr); 1010 1011 var moment = repo.core.latestMoment() catch return respondAttachmentNotFound(request); 1012 const state = rp.Repo(repo_kind, repo_opts).State(.read_only){ .core = &repo.core, .extra = .{ .moment = &moment } }; 1013 var object_reader = obj.ObjectReader(repo_kind, repo_opts).init(state, io, allocator, blob_oid) catch return respondAttachmentNotFound(request); 1014 defer object_reader.deinit(); 1015 if (object_reader.header().kind != .blob) return respondAttachmentNotFound(request); 1016 1017 const content_type = attachmentContentType(record.name); 1018 const encoded_name = try ui.urlEncodeRef(allocator, record.name); 1019 defer allocator.free(encoded_name); 1020 const disposition = try std.fmt.allocPrint(allocator, "{s}; filename*=UTF-8''{s}", .{ if (content_type == null) "attachment" else "inline", encoded_name }); 1021 defer allocator.free(disposition); 1022 1023 var send_buf: [8192]u8 = undefined; 1024 var body = try request.respondStreaming(&send_buf, .{ 1025 .content_length = object_reader.header().size, 1026 .respond_options = .{ 1027 .extra_headers = &.{ 1028 .{ .name = "content-type", .value = content_type orelse "application/octet-stream" }, 1029 .{ .name = "content-disposition", .value = disposition }, 1030 // uploaded bytes are never sniffed into a type that could run 1031 // as script on this origin 1032 .{ .name = "x-content-type-options", .value = "nosniff" }, 1033 }, 1034 }, 1035 }); 1036 _ = try object_reader.interface.streamRemaining(&body.writer); 1037 try body.end(); 1038 } 1039 1040 // the images a browser renders safely inline. anything else downloads as 1041 // opaque bytes, so an uploaded page can't run on this origin. 1042 fn attachmentContentType(name: []const u8) ?[]const u8 { 1043 const types = [_]struct { ext: []const u8, value: []const u8 }{ 1044 .{ .ext = ".png", .value = "image/png" }, 1045 .{ .ext = ".jpg", .value = "image/jpeg" }, 1046 .{ .ext = ".jpeg", .value = "image/jpeg" }, 1047 .{ .ext = ".gif", .value = "image/gif" }, 1048 .{ .ext = ".webp", .value = "image/webp" }, 1049 }; 1050 for (types) |entry| { 1051 if (name.len > entry.ext.len and std.ascii.eqlIgnoreCase(name[name.len - entry.ext.len ..], entry.ext)) return entry.value; 1052 } 1053 return null; 1054 } 1055 1056 fn respondAttachmentNotFound(request: *std.http.Server.Request) !void { 1057 try request.respond("attachment not found", .{ 1058 .status = .not_found, 1059 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1060 }); 1061 } 1062 1063 fn respondAttachmentParentNotFound(request: *std.http.Server.Request) !void { 1064 try request.respond("attachment parent not found", .{ 1065 .status = .not_found, 1066 .keep_alive = false, 1067 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1068 }); 1069 } 1070 1071 // the upload declares its file's name here, since the body is the file itself 1072 const attachment_name_header = "x-attachment-name"; 1073 1074 const AttachParentParts = struct { 1075 repo_base: []const u8, 1076 kind: evt.EventKind, 1077 id_bytes: [evt.event_id_size]u8, 1078 }; 1079 1080 // what an attachment hangs off: the `<kind>:<id>` segment the form's page ends 1081 // with, whatever kind that is 1082 fn attachParentParts(base: []const u8) ?AttachParentParts { 1083 const segment_at = std.mem.lastIndexOfScalar(u8, base, '/') orelse return null; 1084 const segment = base[segment_at + 1 ..]; 1085 const colon_at = std.mem.lastIndexOfScalar(u8, segment, ':') orelse return null; 1086 const kind = std.meta.stringToEnum(evt.EventKind, segment[0..colon_at]) orelse return null; 1087 const id_bytes = evt.parseEventId(segment[colon_at + 1 ..]) catch return null; 1088 return .{ .repo_base = base[0..segment_at], .kind = kind, .id_bytes = id_bytes }; 1089 } 1090 1091 // attach the uploaded file to the event the url names, then reload. the file is 1092 // the whole request body, so it streams from the socket into the object store 1093 // without being buffered. 1094 fn handleAttach( 1095 io: std.Io, 1096 request: *std.http.Server.Request, 1097 allocator: std.mem.Allocator, 1098 base: []const u8, 1099 host: Host, 1100 ) !void { 1101 const parts = attachParentParts(base) orelse return respondAttachmentParentNotFound(request); 1102 1103 var author_arena = std.heap.ArenaAllocator.init(allocator); 1104 defer author_arena.deinit(); 1105 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return; 1106 const author = actor.author; 1107 // an attachment changes the event it hangs off 1108 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondAttachmentParentNotFound(request); 1109 defer request_repo.deinit(allocator); 1110 const source = request_repo.source; 1111 if (!try source.canModify(io, allocator, actor, parts.kind, &parts.id_bytes)) return respondForbidden(request); 1112 1113 const name = (try attachmentName(allocator, request)) orelse return respondUploadError(request, .bad_request, "attachment needs a name"); 1114 defer allocator.free(name); 1115 if (!evt.Attachment.nameValid(name)) return respondUploadError(request, .bad_request, "invalid attachment name"); 1116 1117 const size = request.head.content_length orelse return respondUploadError(request, .length_required, "attachments must declare a content length"); 1118 if (size == 0) return respondUploadError(request, .bad_request, "attachment is empty"); 1119 if (size > evt.Attachment.max_size) return respondUploadError(request, .payload_too_large, "attachment is too large"); 1120 1121 const parent_id_hex = std.fmt.bytesToHex(parts.id_bytes, .lower); 1122 1123 var body_buf: [4096]u8 = undefined; 1124 const blob: evt.Blob = .{ .name = name, .size = size, .reader = try request.readerExpectContinue(&body_buf) }; 1125 1126 switch (source.repo_kind) { 1127 inline else => |repo_kind| { 1128 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1129 defer any_repo.deinit(io, allocator); 1130 switch (any_repo) { 1131 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) { 1132 error.ParentNotFound => return respondAttachmentParentNotFound(request), 1133 else => return err, 1134 }, 1135 } 1136 }, 1137 } 1138 1139 // the client reloads the page itself 1140 try request.respond("", .{ .status = .no_content, .keep_alive = false }); 1141 } 1142 1143 // the name the upload declares for its file, percent-encoded so it survives a 1144 // header 1145 fn attachmentName(allocator: std.mem.Allocator, request: *std.http.Server.Request) !?[]u8 { 1146 var iter = request.iterateHeaders(); 1147 while (iter.next()) |header| { 1148 if (!std.ascii.eqlIgnoreCase(header.name, attachment_name_header)) continue; 1149 return try decodeFormValue(allocator, header.value); 1150 } 1151 return null; 1152 } 1153 1154 // an upload that failed leaves the body partly read, so the connection closes 1155 fn respondUploadError(request: *std.http.Server.Request, status: std.http.Status, message: []const u8) !void { 1156 try request.respond(message, .{ 1157 .status = status, 1158 .keep_alive = false, 1159 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1160 }); 1161 } 1162 1163 // re-emit the comment `parts` names with a new body, in the repo the host 1164 // resolves the base to. 1165 fn updateComment( 1166 io: std.Io, 1167 allocator: std.mem.Allocator, 1168 host: Host, 1169 parts: CommentBaseParts, 1170 body: []const u8, 1171 author: evt.CommitAuthor, 1172 ) !void { 1173 const comment_id = parts.comment_id orelse return error.NotFound; 1174 const thread_id = std.fmt.bytesToHex(parts.thread_id, .lower); 1175 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return error.NotFound; 1176 defer request_repo.deinit(allocator); 1177 const source = request_repo.source; 1178 switch (source.repo_kind) { 1179 inline else => |repo_kind| { 1180 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1181 defer any_repo.deinit(io, allocator); 1182 switch (any_repo) { 1183 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), 1184 } 1185 }, 1186 } 1187 } 1188 1189 // edit actions share a suffix; the base identifies the event being edited. 1190 fn handleEdit( 1191 io: std.Io, 1192 request: *std.http.Server.Request, 1193 allocator: std.mem.Allocator, 1194 base: []const u8, 1195 host: Host, 1196 ) !void { 1197 const parts = commentBaseParts(base) orelse return respondRemoveNotFound(request); 1198 if (parts.comment_id != null) return handleCommentEdit(io, request, allocator, base, host, parts); 1199 return handleThreadEdit(io, request, allocator, base, host, parts); 1200 } 1201 1202 // replace the body of the comment the url names, then redirect to its 1203 // permalink. 1204 fn handleCommentEdit( 1205 io: std.Io, 1206 request: *std.http.Server.Request, 1207 allocator: std.mem.Allocator, 1208 base: []const u8, 1209 host: Host, 1210 parts: CommentBaseParts, 1211 ) !void { 1212 var author_arena = std.heap.ArenaAllocator.init(allocator); 1213 defer author_arena.deinit(); 1214 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return; 1215 const author = actor.author; 1216 // edits only reach here for a comment 1217 const comment_id = parts.comment_id orelse unreachable; 1218 { 1219 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1220 defer request_repo.deinit(allocator); 1221 if (!try request_repo.source.canModify(io, allocator, actor, .comment, &comment_id)) return respondForbidden(request); 1222 } 1223 1224 const form_body = try readFormBody(request, allocator); 1225 defer allocator.free(form_body); 1226 const body_crlf = (try parseFormField(allocator, form_body, "body")) orelse try allocator.dupe(u8, ""); 1227 defer allocator.free(body_crlf); 1228 const body = try std.mem.replaceOwned(u8, allocator, body_crlf, "\r\n", "\n"); 1229 defer allocator.free(body); 1230 1231 if (!evt.Comment.fieldsValid(body)) { 1232 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1233 defer allocator.free(form_location); 1234 try request.respond("", .{ 1235 .status = .see_other, 1236 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1237 }); 1238 return; 1239 } 1240 1241 const not_found = "comment not found"; 1242 updateComment(io, allocator, host, parts, body, author) catch |err| switch (err) { 1243 error.NotFound => { 1244 try request.respond(not_found, .{ 1245 .status = .not_found, 1246 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1247 }); 1248 return; 1249 }, 1250 else => |e| return e, 1251 }; 1252 1253 try request.respond("", .{ 1254 .status = .see_other, 1255 .extra_headers = &.{.{ .name = "location", .value = base }}, 1256 }); 1257 } 1258 1259 fn updateThread( 1260 comptime Event: type, 1261 io: std.Io, 1262 allocator: std.mem.Allocator, 1263 host: Host, 1264 repo_base: []const u8, 1265 id: *const [evt.event_id_size]u8, 1266 update: Event.Update, 1267 author: evt.CommitAuthor, 1268 ) !void { 1269 const request_repo = (try requestRepoSource(io, allocator, host, repo_base)) orelse return error.NotFound; 1270 defer request_repo.deinit(allocator); 1271 const source = request_repo.source; 1272 switch (source.repo_kind) { 1273 inline else => |repo_kind| { 1274 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1275 defer any_repo.deinit(io, allocator); 1276 switch (any_repo) { 1277 inline else => |*repo| try Event.update(std.meta.activeTag(host), repo_kind, repo.self_repo_opts, io, allocator, repo, id, update, author), 1278 } 1279 }, 1280 } 1281 } 1282 1283 const RemoveParts = struct { 1284 repo_base: []const u8, 1285 kind: evt.EventKind, 1286 id: [evt.event_id_size]u8, 1287 }; 1288 1289 // split a remove url into the repo and event it names 1290 fn removeParts(base: []const u8) ?RemoveParts { 1291 if (attachmentRequest(base)) |attachment| { 1292 const parent = attachParentParts(attachment.repo_base) orelse return null; 1293 return .{ 1294 .repo_base = parent.repo_base, 1295 .kind = .attach, 1296 .id = attachment.id, 1297 }; 1298 } 1299 if (commentBaseParts(base)) |thread| return .{ 1300 .repo_base = thread.repo_base, 1301 .kind = if (thread.comment_id != null) .comment else thread.thread_kind, 1302 .id = thread.comment_id orelse thread.thread_id, 1303 }; 1304 return null; 1305 } 1306 1307 // remove the event named by the form's url 1308 fn handleRemove( 1309 io: std.Io, 1310 request: *std.http.Server.Request, 1311 allocator: std.mem.Allocator, 1312 base: []const u8, 1313 host: Host, 1314 ) !void { 1315 const parts = removeParts(base) orelse return respondRemoveNotFound(request); 1316 1317 var author_arena = std.heap.ArenaAllocator.init(allocator); 1318 defer author_arena.deinit(); 1319 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return; 1320 const author = actor.author; 1321 1322 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1323 defer request_repo.deinit(allocator); 1324 const source = request_repo.source; 1325 1326 if (parts.kind == .patch) switch (host) { 1327 .server => |server| { 1328 const user_id = actor.user_id orelse return respondLoginRequired(request); 1329 1330 // a draft lives in its author's user repo 1331 if (try evt.readForkById(io, allocator, &author_arena, server.users_dir, &user_id, &parts.id)) |fork_record| { 1332 const repo_id = evt.parseEventId(std.fs.path.basename(source.path)) catch return respondRemoveNotFound(request); 1333 if (!fork_record.removed and fork_record.event.stage == .draft and std.mem.eql(u8, fork_record.event.repo_id, &repo_id)) { 1334 const id = std.fmt.bytesToHex(parts.id, .lower); 1335 try fork.remove(io, allocator, server.users_dir, &user_id, &id, author); 1336 1337 const location = try std.fmt.allocPrint(allocator, "{s}/patches/drafts", .{parts.repo_base}); 1338 defer allocator.free(location); 1339 try request.respond("", .{ 1340 .status = .see_other, 1341 .keep_alive = false, 1342 .extra_headers = &.{.{ .name = "location", .value = location }}, 1343 }); 1344 return; 1345 } 1346 } 1347 }, 1348 .local => {}, 1349 }; 1350 1351 // a draft is its author's alone, which its removal above checks 1352 if (!try source.canModify(io, allocator, actor, parts.kind, &parts.id)) return respondForbidden(request); 1353 1354 switch (source.repo_kind) { 1355 inline else => |repo_kind| { 1356 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1357 defer any_repo.deinit(io, allocator); 1358 switch (any_repo) { 1359 inline else => |*repo| 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) { 1360 error.EventNotFound => return respondRemoveNotFound(request), 1361 else => |e| return e, 1362 }, 1363 } 1364 }, 1365 } 1366 1367 const id = std.fmt.bytesToHex(parts.id, .lower); 1368 const location = try std.fmt.allocPrint(allocator, "{s}/event:{s}/kind:{s}", .{ parts.repo_base, &id, @tagName(parts.kind) }); 1369 defer allocator.free(location); 1370 try request.respond("", .{ 1371 .status = .see_other, 1372 .keep_alive = false, 1373 .extra_headers = &.{.{ .name = "location", .value = location }}, 1374 }); 1375 } 1376 1377 fn respondRemoveNotFound(request: *std.http.Server.Request) !void { 1378 try request.respond("event not found", .{ 1379 .status = .not_found, 1380 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1381 }); 1382 } 1383 1384 fn updateDiscussion( 1385 io: std.Io, 1386 allocator: std.mem.Allocator, 1387 host: Host, 1388 repo_base: []const u8, 1389 id: *const [evt.event_id_size]u8, 1390 title: []const u8, 1391 labels: []const u8, 1392 description: []const u8, 1393 author: evt.CommitAuthor, 1394 ) !void { 1395 const request_repo = (try requestRepoSource(io, allocator, host, repo_base)) orelse return error.NotFound; 1396 defer request_repo.deinit(allocator); 1397 const source = request_repo.source; 1398 switch (source.repo_kind) { 1399 inline else => |repo_kind| { 1400 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1401 defer any_repo.deinit(io, allocator); 1402 switch (any_repo) { 1403 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), 1404 } 1405 }, 1406 } 1407 } 1408 1409 // set the status of the issue the url names (base is 1410 // "/repo/<owner>/<name>/issue:<id>", identity elided in local mode) by 1411 // re-emitting its event, then redirect back to it 1412 fn handleThreadStatus( 1413 io: std.Io, 1414 request: *std.http.Server.Request, 1415 allocator: std.mem.Allocator, 1416 base: []const u8, 1417 host: Host, 1418 open: bool, 1419 ) !void { 1420 const not_found = "thread not found"; 1421 const parts = commentBaseParts(base) orelse { 1422 try request.respond(not_found, .{ 1423 .status = .not_found, 1424 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1425 }); 1426 return; 1427 }; 1428 1429 var author_arena = std.heap.ArenaAllocator.init(allocator); 1430 defer author_arena.deinit(); 1431 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return; 1432 const author = actor.author; 1433 { 1434 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1435 defer request_repo.deinit(allocator); 1436 if (!try request_repo.source.canModify(io, allocator, actor, parts.thread_kind, &parts.thread_id)) return respondForbidden(request); 1437 } 1438 1439 (switch (parts.thread_kind) { 1440 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .status = if (open) .open else .closed }, author), 1441 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .status = if (open) .open else .closed }, author), 1442 else => return respondRemoveNotFound(request), 1443 }) catch |err| switch (err) { 1444 error.NotFound => { 1445 try request.respond(not_found, .{ 1446 .status = .not_found, 1447 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1448 }); 1449 return; 1450 }, 1451 else => |e| return e, 1452 }; 1453 1454 // like logout, this is a bodyless POST, so close the connection rather than 1455 // letting the keep-alive path try to discard a body that isn't framed. 1456 try request.respond("", .{ 1457 .status = .see_other, 1458 .keep_alive = false, 1459 .extra_headers = &.{.{ .name = "location", .value = base }}, 1460 }); 1461 } 1462 1463 // replace a thread's editable fields. 1464 fn handleThreadEdit( 1465 io: std.Io, 1466 request: *std.http.Server.Request, 1467 allocator: std.mem.Allocator, 1468 base: []const u8, 1469 host: Host, 1470 parts: CommentBaseParts, 1471 ) !void { 1472 var author_arena = std.heap.ArenaAllocator.init(allocator); 1473 defer author_arena.deinit(); 1474 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read)) orelse return; 1475 const author = actor.author; 1476 1477 const body = try readFormBody(request, allocator); 1478 defer allocator.free(body); 1479 1480 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 1481 defer allocator.free(title); 1482 const labels = (try parseFormField(allocator, body, "labels")) orelse try allocator.dupe(u8, ""); 1483 defer allocator.free(labels); 1484 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 1485 defer allocator.free(description_crlf); 1486 // form submission normalizes textarea line breaks to CRLF; store plain 1487 // newlines so the text renders the same on every host 1488 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 1489 defer allocator.free(description); 1490 const target_branch = (try parseFormField(allocator, body, "target_branch")) orelse try allocator.dupe(u8, ""); 1491 defer allocator.free(target_branch); 1492 1493 // invalid fields send the user back to the edit form 1494 const valid = switch (parts.thread_kind) { 1495 .issue => evt.Issue.fieldsValid(title, labels), 1496 .patch => evt.Patch.fieldsValid(title, labels), 1497 .discuss => evt.Discussion.fieldsValid(title, labels), 1498 else => unreachable, 1499 }; 1500 if (!valid) { 1501 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1502 defer allocator.free(form_location); 1503 if (!evt.titleValid(title)) { 1504 return respondThreadFormFailure(request, allocator, host, form_location, requiredTitleFeedback(parts.thread_kind, title, labels, description, target_branch, null)); 1505 } 1506 try request.respond("", .{ 1507 .status = .see_other, 1508 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1509 }); 1510 return; 1511 } 1512 1513 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1514 defer request_repo.deinit(allocator); 1515 1516 const draft_user_id = if (parts.thread_kind == .patch) actor.user_id else null; 1517 if (draft_user_id) |user_id| { 1518 const server = switch (host) { 1519 .server => |server| server, 1520 .local => unreachable, 1521 }; 1522 if (!evt.Patch.branchValid(target_branch) or !try request_repo.source.hasBranch(io, allocator, target_branch)) { 1523 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1524 defer allocator.free(form_location); 1525 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(.invalid_target_branch, title, labels, description, target_branch, null)); 1526 } 1527 const repo_id = evt.parseEventId(std.fs.path.basename(request_repo.source.path)) catch return respondRemoveNotFound(request); 1528 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 1529 defer admin_repo.deinit(io, allocator); 1530 const id = std.fmt.bytesToHex(parts.thread_id, .lower); 1531 if (try pch.editDraft(.{}, io, allocator, server.users_dir, &admin_repo, .{ 1532 .id = id, 1533 .user_id = user_id, 1534 .repo_id = repo_id, 1535 .title = title, 1536 .labels = labels, 1537 .description = description, 1538 .target_branch = target_branch, 1539 .author = author, 1540 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1541 })) { 1542 try request.respond("", .{ 1543 .status = .see_other, 1544 .extra_headers = &.{.{ .name = "location", .value = base }}, 1545 }); 1546 return; 1547 } 1548 } 1549 1550 // a draft is its author's alone, which its edit above checks 1551 if (!try request_repo.source.canModify(io, allocator, actor, parts.thread_kind, &parts.thread_id)) return respondForbidden(request); 1552 1553 const not_found = switch (parts.thread_kind) { 1554 .issue => "issue not found", 1555 .patch => "patch not found", 1556 .discuss => "discussion not found", 1557 else => unreachable, 1558 }; 1559 (switch (parts.thread_kind) { 1560 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 1561 .title = title, 1562 .labels = labels, 1563 .description = description, 1564 } }, author), 1565 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 1566 .title = title, 1567 .labels = labels, 1568 .description = description, 1569 .target_branch = target_branch, 1570 } }, author), 1571 .discuss => updateDiscussion(io, allocator, host, parts.repo_base, &parts.thread_id, title, labels, description, author), 1572 else => unreachable, 1573 }) catch |err| switch (err) { 1574 error.NotFound => { 1575 try request.respond(not_found, .{ 1576 .status = .not_found, 1577 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1578 }); 1579 return; 1580 }, 1581 else => { 1582 if (parts.thread_kind != .patch) return err; 1583 const failure = ui.Session.FormFeedback.PatchFailure.fromError(err) orelse return err; 1584 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1585 defer allocator.free(form_location); 1586 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(failure, title, labels, description, target_branch, null)); 1587 }, 1588 }; 1589 1590 try request.respond("", .{ 1591 .status = .see_other, 1592 .extra_headers = &.{.{ .name = "location", .value = base }}, 1593 }); 1594 } 1595 1596 // resolve every conflicted field of the thread the url names 1597 fn handleThreadResolve( 1598 io: std.Io, 1599 request: *std.http.Server.Request, 1600 allocator: std.mem.Allocator, 1601 base: []const u8, 1602 host: Host, 1603 ) !void { 1604 const parts = commentBaseParts(base) orelse { 1605 try request.respond("thread not found", .{ 1606 .status = .not_found, 1607 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1608 }); 1609 return; 1610 }; 1611 1612 var author_arena = std.heap.ArenaAllocator.init(allocator); 1613 defer author_arena.deinit(); 1614 const author = ((try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .write)) orelse return).author; 1615 1616 const body = try readFormBody(request, allocator); 1617 defer allocator.free(body); 1618 1619 var field_arena = std.heap.ArenaAllocator.init(allocator); 1620 defer field_arena.deinit(); 1621 const aa = field_arena.allocator(); 1622 const title = try parseFormField(aa, body, "title"); 1623 const labels = try parseFormField(aa, body, "labels"); 1624 1625 // the hunk inputs are submitted as d0, d1, ...; form submission normalizes their 1626 // textarea line breaks to CRLF 1627 var hunks: std.ArrayList([]const u8) = .empty; 1628 var hunk_index: usize = 0; 1629 while (true) : (hunk_index += 1) { 1630 const name = try std.fmt.allocPrint(aa, "d{d}", .{hunk_index}); 1631 const submitted = (try parseFormField(aa, body, name)) orelse break; 1632 try hunks.append(aa, try std.mem.replaceOwned(u8, aa, submitted, "\r\n", "\n")); 1633 } 1634 1635 if (parts.comment_id != null or (parts.thread_kind != .issue and parts.thread_kind != .patch)) { 1636 try request.respond("thread not found", .{ 1637 .status = .not_found, 1638 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1639 }); 1640 return; 1641 } 1642 const route = ui.RoutablePage.fromUrl(base) orelse ui.RoutablePage.fromUrlLocal(base) orelse { 1643 try request.respond("thread not found", .{ 1644 .status = .not_found, 1645 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1646 }); 1647 return; 1648 }; 1649 const theirs: []const u8 = switch (route) { 1650 .repo_patches => |*patch| patch.theirs.slice(), 1651 .repo_issues => "", 1652 else => unreachable, 1653 }; 1654 const not_found = if (parts.thread_kind == .patch) "patch not found" else "issue not found"; 1655 1656 (switch (parts.thread_kind) { 1657 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 1658 .title = title, 1659 .labels = labels, 1660 .hunks = hunks.items, 1661 } }, author), 1662 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 1663 .title = title, 1664 .labels = labels, 1665 .hunks = hunks.items, 1666 .theirs = theirs, 1667 } }, author), 1668 else => unreachable, 1669 }) catch |err| switch (err) { 1670 error.NotFound => { 1671 try request.respond(not_found, .{ 1672 .status = .not_found, 1673 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1674 }); 1675 return; 1676 }, 1677 // invalid fields send the user back to the resolve form 1678 error.InvalidFields => { 1679 const form_location = try std.fmt.allocPrint(allocator, "{s}/resolve", .{base}); 1680 defer allocator.free(form_location); 1681 try request.respond("", .{ 1682 .status = .see_other, 1683 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1684 }); 1685 return; 1686 }, 1687 else => |e| return e, 1688 }; 1689 1690 try request.respond("", .{ 1691 .status = .see_other, 1692 .extra_headers = &.{.{ .name = "location", .value = base }}, 1693 }); 1694 } 1695 1696 // the posted path drops the action's own segment, so the route it parses is 1697 // the undo page the action applies to, never the confirmation page itself 1698 fn handleUndo(io: std.Io, request: *std.http.Server.Request, allocator: std.mem.Allocator, base: []const u8, host: Host, action: enum { undo, clear }) !void { 1699 const route = (switch (host) { 1700 .local => ui.RoutablePage.fromUrlLocal(base), 1701 .server => ui.RoutablePage.fromUrl(base), 1702 }) orelse return respondRepoNotFound(request); 1703 if (route != .repo_undo) return respondRepoNotFound(request); 1704 const target = route.repo_undo; 1705 var arena = std.heap.ArenaAllocator.init(allocator); 1706 defer arena.deinit(); 1707 const repo_base = if (target.name.len == 0) "" else try std.fmt.allocPrint(arena.allocator(), "/repo/{s}", .{target.name.slice()}); 1708 _ = (try authorizeWrite(io, allocator, &arena, request, host, repo_base, .owner)) orelse return; 1709 const resolved = (try requestRepoSource(io, allocator, host, repo_base)) orelse return respondRepoNotFound(request); 1710 defer resolved.deinit(allocator); 1711 (switch (action) { 1712 .undo => ui.Repo.Undo.execute(io, allocator, resolved.source, target.index orelse return respondRepoNotFound(request)), 1713 .clear => ui.Repo.Undo.clearHistory(io, allocator, resolved.source), 1714 }) catch |err| switch (err) { 1715 error.NotFound, error.InvalidHistoryIndex, error.TransactionNotFound => return respondRepoNotFound(request), 1716 else => return err, 1717 }; 1718 const location = try (ui.RoutablePage.repoUndoRoute(target.name.slice(), null) orelse return error.RouteTooLong).toUrl(&arena); 1719 try request.respond("", .{ .status = .see_other, .keep_alive = false, .extra_headers = &.{.{ .name = "location", .value = location }} }); 1720 } 1721 1722 fn handleSync( 1723 io: std.Io, 1724 request: *std.http.Server.Request, 1725 allocator: std.mem.Allocator, 1726 base: []const u8, 1727 source: ui.RepoSource, 1728 ) !void { 1729 if (base.len != 0) { 1730 try request.respond("not found", .{ 1731 .status = .not_found, 1732 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1733 }); 1734 return; 1735 } 1736 1737 var owned_failure: ?[]u8 = null; 1738 defer if (owned_failure) |message| allocator.free(message); 1739 const failure: ?[]const u8 = blk: { 1740 owned_failure = ui.Repo.Events.sync(io, allocator, source) catch |err| break :blk @errorName(err); 1741 break :blk owned_failure; 1742 }; 1743 if (failure) |message| { 1744 var encoded: std.Io.Writer.Allocating = .init(allocator); 1745 defer encoded.deinit(); 1746 try std.Uri.Component.percentEncode(&encoded.writer, message, struct { 1747 fn isUnreserved(c: u8) bool { 1748 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 1749 } 1750 }.isUnreserved); 1751 const cookie = try std.fmt.allocPrint( 1752 allocator, 1753 local_flash_cookie ++ "=" ++ local_sync_failure_prefix ++ "{s}; Path=/; HttpOnly; SameSite=Strict", 1754 .{encoded.written()}, 1755 ); 1756 defer allocator.free(cookie); 1757 try request.respond("", .{ 1758 .status = .see_other, 1759 .extra_headers = &.{ 1760 .{ .name = "location", .value = "/events" }, 1761 .{ .name = "set-cookie", .value = cookie }, 1762 }, 1763 }); 1764 return; 1765 } 1766 1767 try request.respond("", .{ 1768 .status = .see_other, 1769 .extra_headers = &.{ 1770 .{ .name = "location", .value = "/events" }, 1771 .{ .name = "set-cookie", .value = local_flash_cookie ++ "=; Path=/; Max-Age=0" }, 1772 }, 1773 }); 1774 } 1775 1776 fn renderIndexHtml( 1777 io: std.Io, 1778 allocator: std.mem.Allocator, 1779 host: Host, 1780 session_token: ?[]const u8, 1781 session_data: ui.Session.Data, 1782 ) ![]const u8 { 1783 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 1784 1785 var page_arena = std.heap.ArenaAllocator.init(allocator); 1786 defer page_arena.deinit(); 1787 1788 // the server admin repo must outlive the page build, since the session's 1789 // moment reads from it. 1790 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 1791 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 1792 1793 var session = switch (host) { 1794 .server => |server| blk: { 1795 // open the admin repo to read live user/repo data. 1796 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 1797 const repo = if (repo_maybe) |*repo| repo else unreachable; 1798 var session = try ui.Session.init(&page_arena, repo, session_data); 1799 // the session dropped a user whose account was removed, so revoke 1800 // the token that named them 1801 if (session_token) |token| { 1802 if (session.data.user_id == null) server.session_store.remove(token); 1803 } 1804 // give the page builders filesystem access to the on-disk repos (a 1805 // sibling "users" dir next to the admin repo) so the Repo page can 1806 // read its files. 1807 session.users_dir = server.users_dir; 1808 break :blk session; 1809 }, 1810 .local => |local| ui.Session{ 1811 .data = session_data, 1812 .arena = &page_arena, 1813 .page_arena = &page_arena, 1814 .local = local, 1815 }, 1816 }; 1817 session.io = io; 1818 1819 var page = try ui.Page.init(session.page_arena, &session, session.data.current_page); 1820 var root = try ui.initRoot(allocator, &page, &session); 1821 defer root.deinit(allocator); 1822 1823 const snapshot: ui.Snapshot = .{ .page = page, .session = session.data }; 1824 1825 const content = try generateHtml(allocator, &root, &session); 1826 defer allocator.free(content); 1827 1828 // serialize the snapshot so the wasm side can parse it back without making 1829 // a second request. it's embedded raw in a <script type="application/json"> 1830 // block, whose content is raw text terminated only by "</script". in json, 1831 // '<' appears solely inside string values, so escaping every '<' (and '>' 1832 // for good measure) to its \uXXXX form yields equivalent json that can't 1833 // break out of the tag. 1834 var json: std.Io.Writer.Allocating = .init(allocator); 1835 defer json.deinit(); 1836 try std.json.Stringify.value(snapshot, .{}, &json.writer); 1837 1838 var json_escaped: std.ArrayList(u8) = .empty; 1839 defer json_escaped.deinit(allocator); 1840 for (json.written()) |c| switch (c) { 1841 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 1842 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 1843 else => try json_escaped.append(allocator, c), 1844 }; 1845 1846 var out: std.ArrayList(u8) = .empty; 1847 errdefer out.deinit(allocator); 1848 { 1849 var cursor: usize = 0; 1850 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 1851 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 1852 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 1853 }) |sub| { 1854 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 1855 try out.appendSlice(allocator, template[cursor..idx]); 1856 try out.appendSlice(allocator, sub.replacement); 1857 cursor = idx + sub.needle.len; 1858 } 1859 try out.appendSlice(allocator, template[cursor..]); 1860 } 1861 return try out.toOwnedSlice(allocator); 1862 } 1863 1864 fn findEmbed(request_path: []const u8) ?Embed { 1865 const path = if (std.mem.eql(u8, request_path, "/")) 1866 "index.html" 1867 else if (request_path.len > 1 and request_path[0] == '/') 1868 request_path[1..] 1869 else 1870 return null; 1871 1872 for (embeds) |embed| { 1873 if (std.mem.eql(u8, path, embed.path)) return embed; 1874 } 1875 return null; 1876 } 1877 1878 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 1879 // own absolutely-positioned, natively-scrollable <div> holding its full content, 1880 // rendered recursively so nested scrolls work. 1881 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1882 const grid = root.getGrid() orelse return error.MissingGrid; 1883 const root_focus = root.getFocus(); 1884 1885 var out: std.ArrayList(u8) = .empty; 1886 errdefer out.deinit(allocator); 1887 1888 switch (root.*) { 1889 .background => |*background| { 1890 if (background.art.getGrid()) |art| { 1891 var position_buf: [64]u8 = undefined; 1892 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})); 1893 try renderPanel(allocator, &out, background.art.getFocus(), art, session, root_focus); 1894 try out.appendSlice(allocator, "</div>"); 1895 } 1896 }, 1897 else => {}, 1898 } 1899 try out.appendSlice(allocator, "<div class=\"grid-content\" data-key=\"panel:root\">"); 1900 try renderPanel(allocator, &out, root_focus, grid, session, root_focus); 1901 try out.appendSlice(allocator, "</div>"); 1902 try renderForms(allocator, &out, root_focus); 1903 return try out.toOwnedSlice(allocator); 1904 } 1905 1906 // render one panel — a focus subtree and its content grid — as HTML, recursing 1907 // once per web-native Scroll inside it. the root panel is the whole page; each 1908 // Scroll becomes a nested, natively-scrollable div holding its full content. 1909 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 1910 // then the child scroll divs over those holes. 1911 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid, session: *ui.Session, root_focus: *Focus) !void { 1912 // `direct` is this panel's scroll children, each drawn as an overlaid div. 1913 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 1914 // plus their descendants, which the focus tree flattens into this panel's 1915 // children): the cell hit-test below skips them so this panel doesn't claim 1916 // cells that are really rendered inside a child scroll's own panel. 1917 // (scrolls aren't nested in practice, so every scroll child is direct here.) 1918 var direct: std.ArrayList(usize) = .empty; 1919 defer direct.deinit(allocator); 1920 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 1921 defer excluded.deinit(allocator); 1922 { 1923 var it = focus.children.iterator(); 1924 while (it.next()) |e| { 1925 if (e.value_ptr.focus.scroll == null) continue; 1926 try direct.append(allocator, e.key_ptr.*); 1927 try excluded.put(allocator, e.key_ptr.*, {}); 1928 var mit = e.value_ptr.focus.children.iterator(); 1929 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 1930 } 1931 } 1932 1933 // the HTML element a run of cells is wrapped in, chosen from the cell's 1934 // focusable kind 1935 const CellTag = union(enum) { 1936 span, // clickable focusable cell 1937 a: []const u8, // clickable focusable link 1938 plain, // non-focusable, colored 1939 1940 const a_prefix = "a:"; 1941 // an "in-page" anchor: rendered as a real <a href> so it works with js 1942 // disabled, but wasm handles it without navigating. 1943 fn init(str: []const u8) @This() { 1944 if (std.mem.startsWith(u8, str, ui.raw_link_prefix)) { 1945 return .{ .a = str[ui.raw_link_prefix.len..] }; 1946 } 1947 if (std.mem.startsWith(u8, str, ui.in_page_link_prefix)) { 1948 return .{ .a = str[ui.in_page_link_prefix.len..] }; 1949 } 1950 if (std.mem.startsWith(u8, str, a_prefix)) { 1951 return .{ .a = str[a_prefix.len..] }; 1952 } 1953 return .span; 1954 } 1955 1956 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 1957 var id_buf: [32]u8 = undefined; 1958 switch (self) { 1959 .span => { 1960 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 1961 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1962 try out.appendSlice(alloc, "\""); 1963 try out.appendSlice(alloc, style_attr); 1964 try out.appendSlice(alloc, ">"); 1965 }, 1966 .a => |href| { 1967 // tabindex=-1 keeps these out of the browser's tab order 1968 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 1969 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1970 try out.appendSlice(alloc, "\" href=\""); 1971 try appendEscapedHtml(alloc, out, href); 1972 try out.appendSlice(alloc, "\""); 1973 try out.appendSlice(alloc, style_attr); 1974 try out.appendSlice(alloc, ">"); 1975 }, 1976 .plain => { 1977 try out.appendSlice(alloc, "<span"); 1978 try out.appendSlice(alloc, style_attr); 1979 try out.appendSlice(alloc, ">"); 1980 }, 1981 } 1982 } 1983 1984 fn closeTag(self: @This()) []const u8 { 1985 return switch (self) { 1986 .span, .plain => "</span>", 1987 .a => "</a>", 1988 }; 1989 } 1990 }; 1991 1992 // the focusable owning each cell, among this panel's own (skipping any 1993 // that belong to a child scroll, whose cells are drawn in their own panel). 1994 // claimed in focus order, so the first focusable over a cell keeps it. 1995 // looking every focusable up for every cell is quadratic in a long list. 1996 const owners = try allocator.alloc(?usize, grid.size.width * grid.size.height); 1997 defer allocator.free(owners); 1998 @memset(owners, null); 1999 { 2000 var it = focus.children.iterator(); 2001 while (it.next()) |entry| { 2002 const child = entry.value_ptr.*; 2003 if (child.focus.mode != .all) continue; 2004 if (excluded.contains(entry.key_ptr.*)) continue; 2005 const r = child.rect; 2006 for (@min(r.y, grid.size.height)..@min(r.y + r.size.height, grid.size.height)) |y| { 2007 for (@min(r.x, grid.size.width)..@min(r.x + r.size.width, grid.size.width)) |x| { 2008 const owner = &owners[y * grid.size.width + x]; 2009 if (owner.* == null) owner.* = entry.key_ptr.*; 2010 } 2011 } 2012 } 2013 } 2014 2015 // the cells are the volatile part of a panel. js replaces this one subtree 2016 // wholesale while retaining the panel's native controls and scroll shells. 2017 try output.appendSlice(allocator, "<div class=\"grid-cells\">"); 2018 2019 // emit this panel's grid as rows of text, coalescing adjacent cells that 2020 // share a focus id and style into one tag (a clickable span, a link, or a 2021 // plain styled span). cells under a child scroll keep only their background. 2022 // a cell's own link is an anchor nested in that tag. 2023 for (0..grid.size.height) |y| { 2024 var cur_id: ?usize = null; 2025 var cur_style: Grid.Style = .{}; 2026 var open_tag: ?CellTag = null; 2027 var open_link: ?[]const u8 = null; 2028 var first = true; 2029 for (0..grid.size.width) |x| { 2030 const cell = (try grid.cell(x, y)).*; 2031 // a cell covered by a child scroll's viewport is drawn by that scroll's 2032 // own div, so blank its glyph and make it non-clickable here — but keep 2033 // its background, so the backdrop still shows through the scroll's 2034 // transparent div instead of a bare hole. 2035 const covered_by_scroll = blk: { 2036 for (direct.items) |id| { 2037 const r = (focus.children.get(id) orelse continue).rect; 2038 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; 2039 } 2040 break :blk false; 2041 }; 2042 // the focusable owning the cell at (x, y); none for a covered cell. 2043 const cell_id = if (covered_by_scroll) null else owners[y * grid.size.width + x]; 2044 const style: Grid.Style = if (covered_by_scroll) .{ .bg = cell.style.bg } else cell.style; 2045 2046 if (first or cell_id != cur_id or !style.eql(cur_style)) { 2047 if (open_link != null) try output.appendSlice(allocator, "</a>"); 2048 open_link = null; 2049 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2050 2051 var new_tag: ?CellTag = null; 2052 if (cell_id) |id| { 2053 if (focus.children.get(id)) |child| { 2054 new_tag = switch (child.focus.kind) { 2055 .custom => |custom| CellTag.init(custom), 2056 else => .span, 2057 }; 2058 } 2059 } 2060 if (new_tag == null and !style.eql(.{})) new_tag = .plain; 2061 2062 if (new_tag) |t| { 2063 var style_buf: [192]u8 = undefined; 2064 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, style)); 2065 } 2066 2067 open_tag = new_tag; 2068 cur_id = cell_id; 2069 cur_style = style; 2070 first = false; 2071 } 2072 2073 // an anchor can't nest in another, so a link tag's cells skip theirs 2074 const in_anchor = if (open_tag) |t| t == .a else false; 2075 const link = if (covered_by_scroll or in_anchor) null else webLink(cell.link); 2076 if (!sameLink(link, open_link)) { 2077 if (open_link != null) try output.appendSlice(allocator, "</a>"); 2078 if (link) |url| { 2079 try output.appendSlice(allocator, "<a class=\"cell-link\" tabindex=\"-1\" target=\"_blank\" rel=\"noopener noreferrer\" href=\""); 2080 try appendEscapedHtml(allocator, output, url); 2081 try output.appendSlice(allocator, "\">"); 2082 } 2083 open_link = link; 2084 } 2085 2086 if (covered_by_scroll) { 2087 try appendEscapedHtml(allocator, output, " "); 2088 } else if (cell.continuation) { 2089 // the wide rune to the left was emitted 2ch wide, covering this column 2090 } else if (cell.rune) |rune| { 2091 var encoded: [4]u8 = undefined; 2092 const encoded_len = try std.unicode.utf8Encode(rune, &encoded); 2093 const rune_text = encoded[0..encoded_len]; 2094 // a double-width rune is pinned inside a 2ch span so the 2095 // fallback glyph's advance width can't shift the rest of the row 2096 const wide = x + 1 < grid.size.width and (try grid.cell(x + 1, y)).continuation; 2097 if (wide) { 2098 try output.appendSlice(allocator, "<span class=\"w2\">"); 2099 try appendEscapedHtml(allocator, output, rune_text); 2100 try output.appendSlice(allocator, "</span>"); 2101 } else { 2102 try appendEscapedHtml(allocator, output, rune_text); 2103 } 2104 } else { 2105 try appendEscapedHtml(allocator, output, " "); 2106 } 2107 } 2108 if (open_link != null) try output.appendSlice(allocator, "</a>"); 2109 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2110 try output.append(allocator, '\n'); 2111 } 2112 try output.appendSlice(allocator, "</div>"); 2113 2114 // native controls live in their panel, beside the replaceable cells. their 2115 // stable keys let JS update layout without recreating their DOM nodes, and 2116 // being actual descendants of a scroll gives them native movement/clipping. 2117 try renderPanelControls(allocator, output, focus, session, root_focus, &excluded); 2118 2119 // each child scroll becomes a natively-scrollable div positioned over its 2120 // viewport, holding its full content rendered recursively. 2121 for (direct.items) |id| { 2122 const child = focus.children.get(id) orelse continue; 2123 const info = child.focus.scroll orelse continue; 2124 const r = child.rect; 2125 // overflow only on the axes the widget scrolls; `auto` shows a bar only 2126 // when that axis actually overflows. the other axis is clipped (hidden), 2127 // matching how the terminal Scroll handles its non-scrolling axis. 2128 const overflow = switch (info.direction) { 2129 .vert => "overflow-x:hidden;overflow-y:auto", 2130 .horiz => "overflow-x:auto;overflow-y:hidden", 2131 .both => "overflow:auto", 2132 }; 2133 // the id carries a content version so JS preserves the native scroll 2134 // position across re-renders of the same content but resets it when the 2135 // content is replaced — e.g. selecting a different commit. the widget's 2136 // scroll offset (in cells) rides along so JS can apply it when it has no 2137 // preserved position, letting a wasm-side scrollToRect (the files list 2138 // scrolling to its selected row on page load) reach the browser. 2139 var buf: [256]u8 = undefined; 2140 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 })); 2141 try renderPanel(allocator, output, child.focus, info.content, session, root_focus); 2142 try output.appendSlice(allocator, "</div>"); 2143 } 2144 } 2145 2146 const form_prefix = "form:"; 2147 const form_id_prefix = "haxy-form-"; 2148 2149 fn formAction(focus: *const Focus) ?[]const u8 { 2150 return switch (focus.kind) { 2151 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) custom[form_prefix.len..] else null, 2152 else => null, 2153 }; 2154 } 2155 2156 // find the form ancestor of a flattened focus-tree child. html's `form` 2157 // attribute then associates the control with that form without requiring the 2158 // form and control to share a DOM parent. 2159 fn formOwner(root_focus: *Focus, focus_id: usize) ?usize { 2160 var id = focus_id; 2161 while (root_focus.children.get(id)) |child| { 2162 const parent_id = child.parent_id; 2163 if (parent_id == root_focus.id) return if (formAction(root_focus) != null) root_focus.id else null; 2164 const parent = root_focus.children.get(parent_id) orelse return null; 2165 if (formAction(parent.focus) != null) return parent_id; 2166 id = parent_id; 2167 } 2168 return null; 2169 } 2170 2171 fn appendFormAttribute(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus, focus_id: usize) !void { 2172 const form_id = formOwner(root_focus, focus_id) orelse return; 2173 var buf: [64]u8 = undefined; 2174 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, " form=\"" ++ form_id_prefix ++ "{d}\"", .{form_id})); 2175 } 2176 2177 fn renderPanelControls( 2178 allocator: std.mem.Allocator, 2179 output: *std.ArrayList(u8), 2180 focus: *Focus, 2181 session: *ui.Session, 2182 root_focus: *Focus, 2183 excluded: *const std.AutoHashMapUnmanaged(usize, void), 2184 ) !void { 2185 var iter = focus.children.iterator(); 2186 while (iter.next()) |entry| { 2187 const id = entry.key_ptr.*; 2188 if (excluded.contains(id)) continue; 2189 const child = entry.value_ptr.*; 2190 const r = child.rect; 2191 2192 if (r.size.width == 0 or r.size.height == 0) continue; // not laid out, rather than merely off-screen 2193 2194 switch (child.focus.kind) { 2195 .text_input, .text_input_password, .text_area => { 2196 const ti = session.text_inputs.get(id) orelse continue; 2197 2198 const inner_left = r.x + 1; 2199 const inner_top = r.y + 1; 2200 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 2201 const preserve = !ti.options.read_only; 2202 2203 if (child.focus.kind == .text_area) { 2204 const value = try ti.text(allocator); 2205 defer allocator.free(value); 2206 var id_buf: [128]u8 = undefined; 2207 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<textarea data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2208 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2209 try appendFormAttribute(allocator, output, root_focus, id); 2210 if (ti.options.name.len > 0) { 2211 try output.appendSlice(allocator, " name=\""); 2212 try appendEscapedHtml(allocator, output, ti.options.name); 2213 try output.append(allocator, '"'); 2214 } 2215 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 2216 var pos_buf: [128]u8 = undefined; 2217 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 })); 2218 try appendEscapedHtml(allocator, output, value); 2219 try output.appendSlice(allocator, "</textarea>"); 2220 continue; 2221 } 2222 2223 var id_buf: [160]u8 = undefined; 2224 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 })); 2225 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2226 try appendFormAttribute(allocator, output, root_focus, id); 2227 if (ti.options.name.len > 0) { 2228 try output.appendSlice(allocator, " name=\""); 2229 try appendEscapedHtml(allocator, output, ti.options.name); 2230 try output.append(allocator, '"'); 2231 } 2232 if (child.focus.kind != .text_input_password) { 2233 const value = try ti.text(allocator); 2234 defer allocator.free(value); 2235 try output.appendSlice(allocator, " value=\""); 2236 try appendEscapedHtml(allocator, output, value); 2237 try output.append(allocator, '"'); 2238 } 2239 var pos_buf: [96]u8 = undefined; 2240 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 })); 2241 }, 2242 .custom => |custom| { 2243 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2244 if (formOwner(root_focus, id) == null) continue; 2245 var id_buf: [128]u8 = undefined; 2246 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2247 try appendFormAttribute(allocator, output, root_focus, id); 2248 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2249 try output.appendSlice(allocator, " formaction=\""); 2250 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 2251 try output.append(allocator, '"'); 2252 } 2253 var pos_buf: [128]u8 = undefined; 2254 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 })); 2255 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 2256 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 2257 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 2258 var id_buf: [128]u8 = undefined; 2259 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 })); 2260 } 2261 }, 2262 else => {}, 2263 } 2264 } 2265 } 2266 2267 // emit hidden form owners beside the rendered panels. their controls point 2268 // back here with the standard HTML `form` attribute. 2269 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 2270 // the focus child map preserves insertion order, which matches the order 2271 // widgets were added in code 2272 var iter = root_focus.children.iterator(); 2273 while (iter.next()) |entry| { 2274 const child = entry.value_ptr.*; 2275 const action_url = formAction(child.focus) orelse continue; 2276 2277 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 2278 var id_buf: [96]u8 = undefined; 2279 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 2280 try appendEscapedHtml(allocator, output, action_url); 2281 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 2282 } 2283 } 2284 2285 // the 16 ansi colors as the browser shows them (xterm's defaults) 2286 const ansi_palette = [16]Grid.Color.Rgb{ 2287 .{ .r = 0x00, .g = 0x00, .b = 0x00 }, .{ .r = 0xcd, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xcd, .b = 0x00 }, .{ .r = 0xcd, .g = 0xcd, .b = 0x00 }, 2288 .{ .r = 0x00, .g = 0x00, .b = 0xee }, .{ .r = 0xcd, .g = 0x00, .b = 0xcd }, .{ .r = 0x00, .g = 0xcd, .b = 0xcd }, .{ .r = 0xe5, .g = 0xe5, .b = 0xe5 }, 2289 .{ .r = 0x7f, .g = 0x7f, .b = 0x7f }, .{ .r = 0xff, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xff, .b = 0x00 }, .{ .r = 0xff, .g = 0xff, .b = 0x00 }, 2290 .{ .r = 0x5c, .g = 0x5c, .b = 0xff }, .{ .r = 0xff, .g = 0x00, .b = 0xff }, .{ .r = 0x00, .g = 0xff, .b = 0xff }, .{ .r = 0xff, .g = 0xff, .b = 0xff }, 2291 }; 2292 2293 // resolve any color to rgb: palette colors through the ansi table and the 2294 // xterm 256-color layout (16 ansi, a 6x6x6 cube, then 24 grays) 2295 fn colorRgb(color: Grid.Color) Grid.Color.Rgb { 2296 return switch (color) { 2297 .rgb => |c| c, 2298 .ansi => |a| ansi_palette[@intFromEnum(a)], 2299 .indexed => |n| if (n < 16) 2300 ansi_palette[n] 2301 else if (n < 232) blk: { 2302 const levels = [6]u8{ 0, 0x5f, 0x87, 0xaf, 0xd7, 0xff }; 2303 const i = n - 16; 2304 break :blk .{ .r = levels[i / 36], .g = levels[(i / 6) % 6], .b = levels[i % 6] }; 2305 } else blk: { 2306 const v: u8 = 8 + (n - 232) * 10; 2307 break :blk .{ .r = v, .g = v, .b = v }; 2308 }, 2309 }; 2310 } 2311 2312 // builds an HTML ` style="color:…;background-color:…"` attribute from a 2313 // cell's style into `buf`, omitting whichever color is unset. an inverted 2314 // cell swaps the two, falling back to the page's --fg/--bg variables for 2315 // whichever side is unset. text attributes follow the colors. returns an 2316 // empty slice when nothing is set. 2317 fn styleAttr(buf: []u8, style: Grid.Style) []const u8 { 2318 if (style.eql(.{})) return buf[0..0]; 2319 const prefix = " style=\""; 2320 @memcpy(buf[0..prefix.len], prefix); 2321 var i: usize = prefix.len; 2322 const inverted = style.inverted; 2323 i = cssColor(buf, i, "color", if (inverted) style.bg else style.fg, if (inverted) "var(--bg)" else null) orelse return buf[0..0]; 2324 i = cssColor(buf, i, "background-color", if (inverted) style.fg else style.bg, if (inverted) "var(--fg)" else null) orelse return buf[0..0]; 2325 const decoration: []const u8 = if (style.underline and style.strikethrough) 2326 "text-decoration:underline line-through;" 2327 else if (style.underline) 2328 "text-decoration:underline;" 2329 else if (style.strikethrough) 2330 "text-decoration:line-through;" 2331 else 2332 ""; 2333 const attributes = std.fmt.bufPrint(buf[i..], "{s}{s}{s}{s}", .{ 2334 if (style.bold) "font-weight:bold;" else "", 2335 if (style.italic) "font-style:italic;" else "", 2336 decoration, 2337 if (style.dim) "opacity:.6;" else "", 2338 }) catch return buf[0..0]; 2339 i += attributes.len; 2340 if (i >= buf.len) return buf[0..0]; 2341 buf[i] = '"'; 2342 return buf[0 .. i + 1]; 2343 } 2344 2345 // append `prop:value;` at buf[i..] for the color, or for the fallback when 2346 // the color is unset (nothing when both are). returns the new end, or null 2347 // when it doesn't fit. 2348 fn cssColor(buf: []u8, i: usize, prop: []const u8, color: ?Grid.Color, fallback: ?[]const u8) ?usize { 2349 const s = if (color) |c| blk: { 2350 const v = colorRgb(c); 2351 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; 2352 } else if (fallback) |f| 2353 std.fmt.bufPrint(buf[i..], "{s}:{s};", .{ prop, f }) catch return null 2354 else 2355 return i; 2356 return i + s.len; 2357 } 2358 2359 // a cell's link as an href, when it's a web or mail url 2360 fn webLink(link: ?[]const u8) ?[]const u8 { 2361 const url = link orelse return null; 2362 for ([_][]const u8{ "http://", "https://", "mailto:" }) |scheme| { 2363 if (std.ascii.startsWithIgnoreCase(url, scheme)) return url; 2364 } 2365 return null; 2366 } 2367 2368 fn sameLink(a: ?[]const u8, b: ?[]const u8) bool { 2369 if (a) |x| return if (b) |y| std.mem.eql(u8, x, y) else false; 2370 return b == null; 2371 } 2372 2373 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2374 for (input) |ch| { 2375 switch (ch) { 2376 '&' => try out.appendSlice(allocator, "&amp;"), 2377 '<' => try out.appendSlice(allocator, "&lt;"), 2378 '>' => try out.appendSlice(allocator, "&gt;"), 2379 '"' => try out.appendSlice(allocator, "&quot;"), 2380 '\'' => try out.appendSlice(allocator, "&#39;"), 2381 else => try out.append(allocator, ch), 2382 } 2383 } 2384 } 2385 2386 // --- helpers -------------------------------------------------------------- 2387 2388 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 2389 var iter = request.iterateHeaders(); 2390 while (iter.next()) |header| { 2391 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2392 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2393 while (pairs.next()) |pair| { 2394 const trimmed = std.mem.trim(u8, pair, " \t"); 2395 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2396 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2397 return trimmed[eq + 1 ..]; 2398 } 2399 } 2400 } 2401 return null; 2402 } 2403 2404 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2405 var iter = std.mem.splitScalar(u8, body, '&'); 2406 while (iter.next()) |pair| { 2407 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2408 if (std.mem.eql(u8, pair[0..eq], key)) { 2409 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2410 } 2411 } 2412 return null; 2413 } 2414 2415 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2416 var buffer: [256]u8 = undefined; 2417 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2418 } 2419 2420 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2421 var out: std.ArrayList(u8) = .empty; 2422 errdefer out.deinit(allocator); 2423 var i: usize = 0; 2424 while (i < encoded.len) : (i += 1) { 2425 switch (encoded[i]) { 2426 '+' => try out.append(allocator, ' '), 2427 '%' => { 2428 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2429 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2430 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2431 try out.append(allocator, hi * 16 + lo); 2432 i += 2; 2433 }, 2434 else => try out.append(allocator, encoded[i]), 2435 } 2436 } 2437 return try out.toOwnedSlice(allocator); 2438 } 2439 2440 // disk-backed web session store. each login mints a random, opaque token 2441 // (not the user's id) that is stored as a file named by the token hex, whose 2442 // contents are the raw user_id bytes. authenticating a request is a lookup of 2443 // the cookie's token; logout deletes the file, revoking the session. there is 2444 // deliberately no expiry — a session lives until logout. form failures use 2445 // files in the flash subdirectory that the redirected GET consumes. the 2446 // directory is cleared whenever the server starts. 2447 pub const SessionStore = struct { 2448 io: std.Io, 2449 dir: std.Io.Dir, 2450 flash_dir: std.Io.Dir, 2451 auto_login: ?[token_hex_len]u8, 2452 2453 pub const token_hex_len = evt.event_id_size * 2; 2454 2455 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2456 try data_dir.createDirPath(io, "sessions"); 2457 const dir = try data_dir.openDir(io, "sessions", .{}); 2458 errdefer dir.close(io); 2459 try dir.deleteTree(io, "flash"); 2460 try dir.createDirPath(io, "flash"); 2461 const flash_dir = try dir.openDir(io, "flash", .{}); 2462 errdefer flash_dir.close(io); 2463 const auto_login = blk: { 2464 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2465 defer file.close(io); 2466 var token: [token_hex_len]u8 = undefined; 2467 var storage: [token_hex_len]u8 = undefined; 2468 var reader = file.reader(io, &storage); 2469 reader.interface.readSliceAll(&token) catch break :blk null; 2470 break :blk token; 2471 }; 2472 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 2473 } 2474 2475 pub fn deinit(self: SessionStore) void { 2476 self.flash_dir.close(self.io); 2477 self.dir.close(self.io); 2478 } 2479 2480 // mint a new session for user_id, returning the token hex to set as the 2481 // cookie value. 2482 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2483 var token: [evt.event_id_size]u8 = undefined; 2484 self.io.random(&token); 2485 const token_hex = std.fmt.bytesToHex(token, .lower); 2486 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2487 defer file.close(self.io); 2488 try file.writeStreamingAll(self.io, user_id); 2489 return token_hex; 2490 } 2491 2492 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 2493 var token: [evt.event_id_size]u8 = undefined; 2494 self.io.random(&token); 2495 const token_hex = std.fmt.bytesToHex(token, .lower); 2496 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 2497 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 2498 defer file.close(self.io); 2499 2500 var json: std.Io.Writer.Allocating = .init(allocator); 2501 defer json.deinit(); 2502 try std.json.Stringify.value(value, .{}, &json.writer); 2503 try file.writeStreamingAll(self.io, json.written()); 2504 return token_hex; 2505 } 2506 2507 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 2508 if (!isToken(token_hex)) return null; 2509 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 2510 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 2511 defer file.close(self.io); 2512 2513 var storage: [4096]u8 = undefined; 2514 var reader = file.reader(self.io, &storage); 2515 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 2516 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 2517 } 2518 2519 // resolve a cookie's token to its user_id. returns false (logged out) for a 2520 // missing, malformed, or unknown token. 2521 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2522 if (!isToken(token_hex)) return false; 2523 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2524 defer file.close(self.io); 2525 var storage: [evt.event_id_size]u8 = undefined; 2526 var file_reader = file.reader(self.io, &storage); 2527 file_reader.interface.readSliceAll(out) catch return false; 2528 return true; 2529 } 2530 2531 // revoke a session. a no-op for a missing or malformed token. 2532 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2533 if (!isToken(token_hex)) return; 2534 self.dir.deleteFile(self.io, token_hex) catch {}; 2535 } 2536 2537 // leave `token_hex`'s session for visitors arriving without one. only the 2538 // `try` fixture writes one. the name can't collide with a session token. 2539 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2540 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2541 defer file.close(self.io); 2542 try file.writeStreamingAll(self.io, token_hex); 2543 } 2544 2545 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2546 out.* = self.auto_login orelse return false; 2547 return true; 2548 } 2549 2550 const auto_login_name = "auto-login"; 2551 2552 // a token is exactly token_hex_len hex chars. validating before using the 2553 // value as a path keeps attacker-supplied cookies from escaping the 2554 // sessions dir (e.g. via "/" or ".." bytes). 2555 fn isToken(token_hex: []const u8) bool { 2556 if (token_hex.len != token_hex_len) return false; 2557 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2558 return true; 2559 } 2560 }; 2561