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