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