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