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