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