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