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