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