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