╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
627 fn respondRepoNotFound(request: *std.http.Server.Request) !void { 628 try request.respond("repo not found", .{ 629 .status = .not_found, 630 .keep_alive = false, 631 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 632 }); 633 } 634 635 // new actions share a suffix; the base identifies whether the form creates a 636 // thread or comment. 637 fn handleNew( 638 io: std.Io, 639 request: *std.http.Server.Request, 640 allocator: std.mem.Allocator, 641 base: []const u8, 642 host: Host, 643 ) !void { 644 if (commentBaseParts(host, base) != null) return handleCommentNew(io, request, allocator, base, host); 645 646 const issues_suffix = "/issues"; 647 if (std.mem.endsWith(u8, base, issues_suffix)) 648 return handleThreadNew(io, request, allocator, base[0 .. base.len - issues_suffix.len], host, .issue); 649 const discussions_suffix = "/discussions"; 650 if (std.mem.endsWith(u8, base, discussions_suffix)) 651 return handleThreadNew(io, request, allocator, base[0 .. base.len - discussions_suffix.len], host, .discuss); 652 const patches_suffix = "/patches"; 653 if (std.mem.endsWith(u8, base, patches_suffix)) 654 return handleThreadNew(io, request, allocator, base[0 .. base.len - patches_suffix.len], host, .patch); 655 656 try request.respond("new event target not found", .{ 657 .status = .not_found, 658 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 659 }); 660 } 661 662 // create a repo for the logged-in user and redirect to it. a failure goes 663 // back to the new-repo page that posted the form. 664 fn handleRepoNew( 665 io: std.Io, 666 request: *std.http.Server.Request, 667 allocator: std.mem.Allocator, 668 form_location: []const u8, 669 admin_repo_path: []const u8, 670 users_dir: []const u8, 671 session_store: SessionStore, 672 ) !void { 673 const user_id = requestUserId(request, session_store) orelse return respondLoginRequired(request); 674 var arena = std.heap.ArenaAllocator.init(allocator); 675 defer arena.deinit(); 676 const user = blk: { 677 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }); 678 defer admin_repo.deinit(io, allocator); 679 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin_repo); 680 break :blk (try ui.activeUser(moment, &arena, user_id)) orelse return respondLoginRequired(request); 681 }; 682 683 const body = try readFormBody(request, allocator); 684 defer allocator.free(body); 685 const name = (try parseFormField(allocator, body, "name")) orelse try allocator.dupe(u8, ""); 686 defer allocator.free(name); 687 const description = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 688 defer allocator.free(description); 689 const hash_value = (try parseFormField(allocator, body, "hash")) orelse try allocator.dupe(u8, ""); 690 defer allocator.free(hash_value); 691 const access_value = (try parseFormField(allocator, body, "access")) orelse try allocator.dupe(u8, ""); 692 defer allocator.free(access_value); 693 const bad_request: std.http.Server.Request.RespondOptions = .{ .status = .bad_request, .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }} }; 694 const hash_kind = std.meta.stringToEnum(hash.HashKind, hash_value) orelse return request.respond("invalid hash", bad_request); 695 const access = std.meta.stringToEnum(evt.Repo.Access, access_value) orelse return request.respond("invalid access", bad_request); 696 697 _ = evt.createRepo(io, allocator, users_dir, &user_id, .{ .name = user.event.name, .email = user.event.email }, name, description, access, hash_kind) catch |err| { 698 const failure = ui.Session.FormFeedback.RepoFailure.fromError(err) orelse return err; 699 return respondFormFailure(request, allocator, session_store, form_location, .{ .repo = .{ .failure = failure, .fields = .{ 700 .name = name, 701 .description = description, 702 .hash = hash_kind, 703 .access = access, 704 } } }); 705 }; 706 707 const location = try allocator.print("/{s}:{s}", .{ user.event.name, name }); 708 defer allocator.free(location); 709 try request.respond("", .{ 710 .status = .see_other, 711 .extra_headers = &.{.{ .name = "location", .value = location }}, 712 }); 713 } 714 715 // change the repo the settings url `form_location` names as its owner, then 716 // redirect to its settings under its new name. a failure goes back to the 717 // settings page. 718 fn handleRepoSettings( 719 io: std.Io, 720 request: *std.http.Server.Request, 721 allocator: std.mem.Allocator, 722 form_location: []const u8, 723 host: Host, 724 ) !void { 725 const server = switch (host) { 726 .server => |server| server, 727 .local => return respondRepoNotFound(request), 728 }; 729 const route = routeFromUrl(host, form_location) orelse return respondRepoNotFound(request); 730 if (route != .repo_settings) return respondRepoNotFound(request); 731 var arena = std.heap.ArenaAllocator.init(allocator); 732 defer arena.deinit(); 733 const repo_base = try arena.allocator().print("/{s}", .{route.repo_settings.slice()}); 734 const actor = (try authorizeWrite(io, allocator, &arena, request, host, repo_base, .owner, null)) orelse return; 735 736 const body = try readFormBody(request, allocator); 737 defer allocator.free(body); 738 const name = (try parseFormField(allocator, body, "name")) orelse try allocator.dupe(u8, ""); 739 defer allocator.free(name); 740 const description = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 741 defer allocator.free(description); 742 const access_value = (try parseFormField(allocator, body, "access")) orelse try allocator.dupe(u8, ""); 743 defer allocator.free(access_value); 744 const access = std.meta.stringToEnum(evt.Repo.Access, access_value) orelse return request.respond("invalid access", .{ .status = .bad_request, .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }} }); 745 var roles: [3]?evt.Repo.Role = undefined; 746 for (&roles, [_][]const u8{ "discuss_role", "issue_role", "patch_role" }) |*role, field| { 747 const role_value = (try parseFormField(allocator, body, field)) orelse try allocator.dupe(u8, ""); 748 defer allocator.free(role_value); 749 role.* = ui.Repo.Settings.labelRole(role_value) catch return request.respond("invalid role", .{ .status = .bad_request, .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }} }); 750 } 751 const discuss_role, const issue_role, const patch_role = roles; 752 753 const updated = ui.Repo.Settings.update(io, allocator, server.users_dir, actor, route.repo_settings.slice(), name, description, access, discuss_role, issue_role, patch_role) catch |err| switch (err) { 754 error.NotFound => return respondRepoNotFound(request), 755 else => { 756 const failure = ui.Session.FormFeedback.RepoFailure.fromError(err) orelse return err; 757 return respondFormFailure(request, allocator, server.session_store, form_location, .{ .repo_settings = .{ .failure = failure, .fields = .{ 758 .name = name, 759 .description = description, 760 .access = access, 761 .discuss_role = discuss_role, 762 .issue_role = issue_role, 763 .patch_role = patch_role, 764 } } }); 765 }, 766 }; 767 768 try request.respond("", .{ 769 .status = .see_other, 770 .extra_headers = &.{.{ .name = "location", .value = try updated.toUrl(&arena) }}, 771 }); 772 } 773 774 // act on a user's role in the repo the members url `base` names, as one of its 775 // owners, then redirect back to the list. the add form names the user in its 776 // body and the row forms in the url. 777 fn handleMembers(io: std.Io, request: *std.http.Server.Request, allocator: std.mem.Allocator, base: []const u8, host: Host, action: ui.Repo.Members.Action) !void { 778 const server = switch (host) { 779 .server => |server| server, 780 .local => return respondRepoNotFound(request), 781 }; 782 const route = routeFromUrl(host, base) orelse return respondRepoNotFound(request); 783 if (route != .repo_members) return respondRepoNotFound(request); 784 const target = route.repo_members; 785 var arena = std.heap.ArenaAllocator.init(allocator); 786 defer arena.deinit(); 787 const identity = target.name.slice(); 788 const actor = (try authorizeWrite(io, allocator, &arena, request, host, try arena.allocator().print("/{s}", .{identity}), .owner, null)) orelse return; 789 790 const name = switch (action) { 791 .grant => blk: { 792 const body = try readFormBody(request, allocator); 793 defer allocator.free(body); 794 break :blk (try parseFormField(arena.allocator(), body, "name")) orelse ""; 795 }, 796 .revoke, .promote, .demote => if (target.user.len != 0) target.user.slice() else return respondRepoNotFound(request), 797 }; 798 799 const failure = blk: { 800 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 801 defer admin_repo.deinit(io, allocator); 802 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin_repo); 803 break :blk ui.Repo.Members.perform(io, allocator, moment, server.users_dir, actor, identity, action, name) catch |err| switch (err) { 804 error.NotFound, error.EventNotFound => return respondRepoNotFound(request), 805 else => return err, 806 }; 807 }; 808 if (failure) |value| { 809 const location = try (ui.RoutablePage.repoMembersRoute(identity, target.start) orelse return error.RouteTooLong).toUrl(&arena); 810 return respondFormFailure(request, allocator, server.session_store, location, .{ .repo_members = .{ .failure = value, .name = name } }); 811 } 812 const location = try (ui.Repo.Members.landingRoute(identity, target.start, actor, action, name) orelse return error.RouteTooLong).toUrl(&arena); 813 try request.respond("", .{ .status = .see_other, .keep_alive = false, .extra_headers = &.{.{ .name = "location", .value = location }} }); 814 } 815 816 // protect or unprotect a branch of the repo the branches url `base` names, as 817 // one of its owners, then redirect back to the list. the add form names the 818 // branch in its body and the row forms in the url. 819 fn handleBranches(io: std.Io, request: *std.http.Server.Request, allocator: std.mem.Allocator, base: []const u8, host: Host, action: ui.Repo.Branches.Action) !void { 820 const server = switch (host) { 821 .server => |server| server, 822 .local => return respondRepoNotFound(request), 823 }; 824 const route = routeFromUrl(host, base) orelse return respondRepoNotFound(request); 825 if (route != .repo_branches) return respondRepoNotFound(request); 826 const target = route.repo_branches; 827 var arena = std.heap.ArenaAllocator.init(allocator); 828 defer arena.deinit(); 829 const identity = target.name.slice(); 830 const actor = (try authorizeWrite(io, allocator, &arena, request, host, try arena.allocator().print("/{s}", .{identity}), .owner, null)) orelse return; 831 832 const branch = switch (action) { 833 .protect => blk: { 834 const body = try readFormBody(request, allocator); 835 defer allocator.free(body); 836 break :blk (try parseFormField(arena.allocator(), body, "name")) orelse ""; 837 }, 838 .unprotect => if (target.branch.len != 0) std.Uri.percentDecodeInPlace(try arena.allocator().dupe(u8, target.branch.slice())) else return respondRepoNotFound(request), 839 }; 840 841 const failure = ui.Repo.Branches.perform(io, allocator, server.users_dir, actor, identity, action, branch) catch |err| switch (err) { 842 error.NotFound => return respondRepoNotFound(request), 843 else => return err, 844 }; 845 const location = try (ui.RoutablePage.repoBranchesRoute(identity) orelse return error.RouteTooLong).toUrl(&arena); 846 if (failure) |value| return respondFormFailure(request, allocator, server.session_store, location, .{ .repo_branches = .{ .failure = value, .name = branch } }); 847 try request.respond("", .{ .status = .see_other, .keep_alive = false, .extra_headers = &.{.{ .name = "location", .value = location }} }); 848 } 849 850 // create a user, log them in, and redirect to their page. a failure goes 851 // back to the new-user page that posted the form. 852 fn handleUserNew( 853 io: std.Io, 854 request: *std.http.Server.Request, 855 allocator: std.mem.Allocator, 856 form_location: []const u8, 857 admin_repo_path: []const u8, 858 users_dir: []const u8, 859 session_store: SessionStore, 860 ) !void { 861 if (requestUserId(request, session_store) != null) { 862 return request.respond("log out to create a user", .{ 863 .status = .forbidden, 864 .keep_alive = false, 865 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 866 }); 867 } 868 869 const body = try readFormBody(request, allocator); 870 defer allocator.free(body); 871 const name = (try parseFormField(allocator, body, "name")) orelse try allocator.dupe(u8, ""); 872 defer allocator.free(name); 873 const email = (try parseFormField(allocator, body, "email")) orelse try allocator.dupe(u8, ""); 874 defer allocator.free(email); 875 const password = (try parseFormField(allocator, body, "password")) orelse try allocator.dupe(u8, ""); 876 defer allocator.free(password); 877 const password_again = (try parseFormField(allocator, body, "password_again")) orelse try allocator.dupe(u8, ""); 878 defer allocator.free(password_again); 879 880 const user_id = blk: { 881 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }); 882 defer admin_repo.deinit(io, allocator); 883 break :blk evt.createUser(io, allocator, users_dir, &admin_repo, name, email, password, password_again) catch |err| { 884 const failure = ui.Session.FormFeedback.UserFailure.fromError(err) orelse return err; 885 return respondFormFailure(request, allocator, session_store, form_location, .{ .user = .{ .failure = failure, .fields = .{ .name = name, .email = email } } }); 886 }; 887 }; 888 889 const token = try session_store.create(&user_id); 890 var cookie_buf: [256]u8 = undefined; 891 const cookie = try std.fmt.bufPrint(&cookie_buf, session_cookie_fmt, .{token}); 892 const location = try allocator.print("/{s}", .{name}); 893 defer allocator.free(location); 894 try request.respond("", .{ 895 .status = .see_other, 896 .extra_headers = &.{ 897 .{ .name = "location", .value = location }, 898 .{ .name = "set-cookie", .value = cookie }, 899 }, 900 }); 901 } 902 903 // change the logged-in user's settings, then return to the settings tab that 904 // posted the form, which a failure also goes back to. 905 fn handleUserSettings( 906 io: std.Io, 907 request: *std.http.Server.Request, 908 allocator: std.mem.Allocator, 909 form_location: []const u8, 910 admin_repo_path: []const u8, 911 users_dir: []const u8, 912 session_store: SessionStore, 913 ) !void { 914 const user_id = requestUserId(request, session_store) orelse return respondLoginRequired(request); 915 916 const body = try readFormBody(request, allocator); 917 defer allocator.free(body); 918 const email = (try parseFormField(allocator, body, "email")) orelse try allocator.dupe(u8, ""); 919 defer allocator.free(email); 920 const current_password = (try parseFormField(allocator, body, "current_password")) orelse try allocator.dupe(u8, ""); 921 defer allocator.free(current_password); 922 const new_password = (try parseFormField(allocator, body, "new_password")) orelse try allocator.dupe(u8, ""); 923 defer allocator.free(new_password); 924 const new_password_again = (try parseFormField(allocator, body, "new_password_again")) orelse try allocator.dupe(u8, ""); 925 defer allocator.free(new_password_again); 926 927 { 928 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }); 929 defer admin_repo.deinit(io, allocator); 930 evt.updateUser(io, allocator, users_dir, &admin_repo, &user_id, email, current_password, new_password, new_password_again) catch |err| switch (err) { 931 error.NotFound => return respondLoginRequired(request), 932 else => { 933 const failure = ui.Session.FormFeedback.UserFailure.fromError(err) orelse return err; 934 return respondFormFailure(request, allocator, session_store, form_location, .{ .user_settings = .{ .failure = failure, .fields = .{ .email = email } } }); 935 }, 936 }; 937 } 938 939 try request.respond("", .{ 940 .status = .see_other, 941 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 942 }); 943 } 944 945 // add one of the logged-in user's ssh keys, then return to the ssh keys tab 946 // that posted the form, which a failure also goes back to. 947 fn handleUserKeyAdd( 948 io: std.Io, 949 request: *std.http.Server.Request, 950 allocator: std.mem.Allocator, 951 form_location: []const u8, 952 admin_repo_path: []const u8, 953 users_dir: []const u8, 954 session_store: SessionStore, 955 ) !void { 956 const user_id = requestUserId(request, session_store) orelse return respondLoginRequired(request); 957 958 const body = try readFormBody(request, allocator); 959 defer allocator.free(body); 960 const key = (try parseFormField(allocator, body, "key")) orelse try allocator.dupe(u8, ""); 961 defer allocator.free(key); 962 963 { 964 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }); 965 defer admin_repo.deinit(io, allocator); 966 evt.addUserKey(io, allocator, users_dir, &admin_repo, &user_id, key) catch |err| switch (err) { 967 error.NotFound => return respondLoginRequired(request), 968 else => { 969 const failure = ui.Session.FormFeedback.KeyFailure.fromError(err) orelse return err; 970 return respondFormFailure(request, allocator, session_store, form_location, .{ .user_keys = .{ .failure = failure, .key = key } }); 971 }, 972 }; 973 } 974 975 try request.respond("", .{ 976 .status = .see_other, 977 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 978 }); 979 } 980 981 // remove the logged-in user's ssh key the confirmation url names, then return 982 // to the ssh keys tab 983 fn handleUserKeyRemove( 984 io: std.Io, 985 request: *std.http.Server.Request, 986 allocator: std.mem.Allocator, 987 base: []const u8, 988 admin_repo_path: []const u8, 989 users_dir: []const u8, 990 session_store: SessionStore, 991 ) !void { 992 const user_id = requestUserId(request, session_store) orelse return respondLoginRequired(request); 993 const route = ui.RoutablePage.fromUrl(base) orelse return respondKeyNotFound(request); 994 const tab = route.userTab(); 995 if (tab.view != .keys or tab.key.len != evt.User.fingerprint_len) return respondKeyNotFound(request); 996 997 { 998 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = admin_repo_path }); 999 defer admin_repo.deinit(io, allocator); 1000 evt.removeUserKey(io, allocator, users_dir, &admin_repo, &user_id, &tab.key.bytes) catch |err| switch (err) { 1001 error.NotFound => return respondLoginRequired(request), 1002 else => return err, 1003 }; 1004 } 1005 1006 var arena = std.heap.ArenaAllocator.init(allocator); 1007 defer arena.deinit(); 1008 const location = try route.withUserTab(.{ .view = .keys }).toUrl(&arena); 1009 try request.respond("", .{ 1010 .status = .see_other, 1011 .extra_headers = &.{.{ .name = "location", .value = location }}, 1012 }); 1013 } 1014 1015 // delete the repo, fork or user the delete tab url `base` names, as its main 1016 // owner. a failure goes back to the tab. 1017 fn handleDelete(io: std.Io, request: *std.http.Server.Request, allocator: std.mem.Allocator, base: []const u8, server: @FieldType(Host, "server")) !void { 1018 const user_id = requestUserId(request, server.session_store) orelse return respondLoginRequired(request); 1019 var arena = std.heap.ArenaAllocator.init(allocator); 1020 defer arena.deinit(); 1021 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 1022 defer admin_repo.deinit(io, allocator); 1023 const user = (try ui.activeUser(try evt.currentMoment(evt.admin_repo_opts, &admin_repo), &arena, user_id)) orelse return respondLoginRequired(request); 1024 1025 const route = ui.RoutablePage.fromUrl(base) orelse return respondDeleteNotFound(request); 1026 const target: ui.Delete.Target = switch (route) { 1027 .repo_delete => |*name| .{ .repo = name.slice() }, 1028 .fork_delete => |*f| .{ .fork = .{ .identity = f.name.slice(), .id = f.id.bytes } }, 1029 else => if (route.userTab().view == .delete) .{ .user = user.event.name } else return respondDeleteNotFound(request), 1030 }; 1031 1032 const body = try readFormBody(request, allocator); 1033 defer allocator.free(body); 1034 const confirm = (try parseFormField(arena.allocator(), body, "confirm")) orelse ""; 1035 const password = (try parseFormField(arena.allocator(), body, "password")) orelse ""; 1036 1037 const failure = ui.Delete.perform(io, allocator, server.users_dir, &admin_repo, user_id, target, confirm, password) catch |err| switch (err) { 1038 error.NotFound => return respondDeleteNotFound(request), 1039 else => return err, 1040 }; 1041 if (failure) |value| return respondFormFailure(request, allocator, server.session_store, base, .{ .delete = .{ .failure = value, .target = std.meta.activeTag(target), .confirm = confirm } }); 1042 1043 switch (target) { 1044 .repo, .fork => { 1045 const location = try arena.allocator().print("/{s}", .{user.event.name}); 1046 try request.respond("", .{ .status = .see_other, .keep_alive = false, .extra_headers = &.{.{ .name = "location", .value = location }} }); 1047 }, 1048 // log the deleted user out, as a logout does 1049 .user => { 1050 if (getCookieValue(request, cookie_name)) |token| server.session_store.remove(token); 1051 try request.respond("", .{ 1052 .status = .see_other, 1053 .keep_alive = false, 1054 .extra_headers = &.{ 1055 .{ .name = "location", .value = "/" }, 1056 .{ .name = "set-cookie", .value = cookie_name ++ "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0" }, 1057 }, 1058 }); 1059 }, 1060 } 1061 } 1062 1063 fn respondDeleteNotFound(request: *std.http.Server.Request) !void { 1064 try request.respond("nothing to delete", .{ 1065 .status = .not_found, 1066 .keep_alive = false, 1067 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1068 }); 1069 } 1070 1071 fn respondKeyNotFound(request: *std.http.Server.Request) !void { 1072 try request.respond("ssh key not found", .{ 1073 .status = .not_found, 1074 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1075 }); 1076 } 1077 1078 // create a thread in the repo the form's page names and redirect to it. 1079 fn handleThreadNew( 1080 io: std.Io, 1081 request: *std.http.Server.Request, 1082 allocator: std.mem.Allocator, 1083 base: []const u8, 1084 host: Host, 1085 kind: evt.EventKind, 1086 ) !void { 1087 var author_arena = std.heap.ArenaAllocator.init(allocator); 1088 defer author_arena.deinit(); 1089 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, base, .read, kind)) orelse return; 1090 const author = actor.author; 1091 const body = try readFormBody(request, allocator); 1092 defer allocator.free(body); 1093 1094 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 1095 defer allocator.free(title); 1096 const labels = (try parseFormField(allocator, body, "labels")) orelse try allocator.dupe(u8, ""); 1097 defer allocator.free(labels); 1098 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 1099 defer allocator.free(description_crlf); 1100 // form submission normalizes textarea line breaks to CRLF; store plain 1101 // newlines so the text renders the same on every host 1102 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 1103 defer allocator.free(description); 1104 const target_branch = (try parseFormField(allocator, body, "target_branch")) orelse try allocator.dupe(u8, ""); 1105 defer allocator.free(target_branch); 1106 1107 const source_branch = if (kind == .patch) try parseFormField(allocator, body, "source_branch") else null; 1108 defer if (source_branch) |branch| allocator.free(branch); 1109 1110 const valid = switch (kind) { 1111 .issue => evt.Issue.fieldsValid(title, labels), 1112 .patch => evt.Patch.fieldsValid(title, labels), 1113 .discuss => evt.Discussion.fieldsValid(title, labels), 1114 else => unreachable, 1115 }; 1116 if (!valid) { 1117 const form_location = try allocator.print("{s}/{s}/new", .{ base, threadListName(kind) }); 1118 defer allocator.free(form_location); 1119 if (!evt.titleValid(title)) { 1120 return respondThreadFormFailure(request, allocator, host, form_location, requiredTitleFeedback(kind, title, labels, description, target_branch, source_branch)); 1121 } 1122 try request.respond("", .{ 1123 .status = .see_other, 1124 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1125 }); 1126 return; 1127 } 1128 1129 var id_bytes: [evt.event_id_size]u8 = undefined; 1130 io.random(&id_bytes); 1131 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 1132 1133 const not_found = "repo not found"; 1134 const request_repo = (try requestRepoSource(io, allocator, host, base)) orelse { 1135 try request.respond(not_found, .{ 1136 .status = .not_found, 1137 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1138 }); 1139 return; 1140 }; 1141 defer request_repo.deinit(allocator); 1142 const source = request_repo.source; 1143 if (kind == .patch and source_branch == null) { 1144 const server = switch (host) { 1145 .server => |server| server, 1146 .local => return respondRemoveNotFound(request), 1147 }; 1148 const user_id = actor.user_id orelse return respondLoginRequired(request); 1149 if (!evt.Patch.branchValid(target_branch) or !try request_repo.source.hasBranch(io, allocator, target_branch)) { 1150 const form_location = try allocator.print("{s}/patches/new", .{base}); 1151 defer allocator.free(form_location); 1152 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(.invalid_target_branch, title, labels, description, target_branch, null)); 1153 } 1154 const repo_id = evt.parseEventId(std.Io.Dir.path.basename(request_repo.source.path)) catch return respondRemoveNotFound(request); 1155 const repo_user_id = actor.repo_user_id orelse unreachable; 1156 const identity = ui.RoutablePage.RepoIdentity.parse(repoBaseIdentity(base) orelse return respondRemoveNotFound(request)) orelse return respondRemoveNotFound(request); 1157 const fork_path = try fork.create(.{}, io, allocator, server.users_dir, .{ 1158 .id = event_id_hex, 1159 .user_id = user_id, 1160 .repo_id = repo_id, 1161 .repo_user_id = repo_user_id, 1162 .repo_name = identity.name, 1163 .title = title, 1164 .description = description, 1165 .labels = labels, 1166 .target_branch = target_branch, 1167 .author = author, 1168 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1169 }); 1170 defer allocator.free(fork_path); 1171 } else { 1172 const event = evt.EventWithId{ 1173 .id = event_id_hex, 1174 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1175 .author = author, 1176 .event = switch (kind) { 1177 .issue => .{ .issue = .{ .title = title, .description = description, .labels = labels } }, 1178 .patch => .{ .patch = .{ .title = title, .description = description, .labels = labels, .target_branch = target_branch, .source_branch = source_branch } }, 1179 .discuss => .{ .discuss = .{ .title = title, .description = description, .labels = labels } }, 1180 else => unreachable, 1181 }, 1182 }; 1183 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| { 1190 const result = if (kind == .patch) 1191 pch.writeBranchPatch(host.event(), repo_kind, repo.self_repo_opts, io, allocator, repo, event_id_hex, event.event.patch orelse unreachable, null, author) 1192 else 1193 evt.consume(host.event(), .repo, repo_kind, repo.self_repo_opts, io, allocator, repo, evt.events_ref, &.{event}); 1194 result catch |err| { 1195 if (kind != .patch) return err; 1196 const failure = ui.Session.FormFeedback.PatchFailure.fromError(err) orelse return err; 1197 const form_location = try allocator.print("{s}/patches/new", .{base}); 1198 defer allocator.free(form_location); 1199 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(failure, title, labels, description, target_branch, source_branch)); 1200 }; 1201 }, 1202 } 1203 }, 1204 } 1205 } 1206 1207 const location = try allocator.print("{s}/{s}:{s}", .{ base, @tagName(kind), &event_id_hex }); 1208 defer allocator.free(location); 1209 try request.respond("", .{ 1210 .status = .see_other, 1211 .extra_headers = &.{.{ .name = "location", .value = location }}, 1212 }); 1213 } 1214 1215 const CommentBaseParts = struct { 1216 repo_base: []const u8, 1217 thread_kind: evt.EventKind, 1218 thread_id: [evt.event_id_size]u8, 1219 comment_id: ?[evt.event_id_size]u8, 1220 }; 1221 1222 fn commentBaseParts(host: Host, base: []const u8) ?CommentBaseParts { 1223 const route = routeFromUrl(host, base) orelse return null; 1224 const identity, const thread_kind, const thread_hex, const comment_hex = switch (route) { 1225 .repo_issues => |*issue| .{ issue.name.slice(), evt.EventKind.issue, issue.selected.slice(), issue.comment.slice() }, 1226 .repo_patches => |*patch| .{ patch.name.slice(), evt.EventKind.patch, patch.selected.slice(), patch.comment.slice() }, 1227 .repo_discussions => |*discussion| .{ discussion.name.slice(), evt.EventKind.discuss, discussion.selected.slice(), discussion.comment.slice() }, 1228 else => return null, 1229 }; 1230 const thread_id = evt.parseEventId(thread_hex) catch return null; 1231 const comment_id = if (comment_hex.len == 0) null else evt.parseEventId(comment_hex) catch return null; 1232 const repo_base_len = if (identity.len == 0) 0 else "/".len + identity.len; 1233 return .{ .repo_base = base[0..repo_base_len], .thread_kind = thread_kind, .thread_id = thread_id, .comment_id = comment_id }; 1234 } 1235 1236 fn handlePatchPublish( 1237 io: std.Io, 1238 request: *std.http.Server.Request, 1239 allocator: std.mem.Allocator, 1240 base: []const u8, 1241 host: Host, 1242 ) !void { 1243 const parts = commentBaseParts(host, base) orelse return respondRemoveNotFound(request); 1244 if (parts.thread_kind != .patch or parts.comment_id != null) return respondRemoveNotFound(request); 1245 const server = switch (host) { 1246 .server => |server| server, 1247 .local => return respondRemoveNotFound(request), 1248 }; 1249 var author_arena = std.heap.ArenaAllocator.init(allocator); 1250 defer author_arena.deinit(); 1251 // only the draft's author may publish it, which publish checks 1252 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read, .patch)) orelse return; 1253 const user_id = actor.user_id orelse return respondLoginRequired(request); 1254 const author = actor.author; 1255 1256 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1257 defer request_repo.deinit(allocator); 1258 const repo_id = evt.parseEventId(std.Io.Dir.path.basename(request_repo.source.path)) catch return respondRemoveNotFound(request); 1259 var target_repo = try rp.AnyRepo(.xit, .{}).open(io, allocator, request_repo.source.localInitOpts()); 1260 defer target_repo.deinit(io, allocator); 1261 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 1262 defer admin_repo.deinit(io, allocator); 1263 const id = std.fmt.bytesToHex(parts.thread_id, .lower); 1264 switch (target_repo) { 1265 inline else => |*repo| try pch.publish(repo.self_repo_opts, io, allocator, host.event().server, &admin_repo, repo, .{ 1266 .id = id, 1267 .user_id = user_id, 1268 .repo_id = repo_id, 1269 .author = author, 1270 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1271 }), 1272 } 1273 try request.respond("", .{ 1274 .status = .see_other, 1275 .extra_headers = &.{.{ .name = "location", .value = base }}, 1276 }); 1277 } 1278 1279 fn handlePatchMerge( 1280 io: std.Io, 1281 request: *std.http.Server.Request, 1282 allocator: std.mem.Allocator, 1283 base: []const u8, 1284 host: Host, 1285 revision: evt.Patch.MergeRevision, 1286 ) !void { 1287 const parts = commentBaseParts(host, base) orelse return respondRemoveNotFound(request); 1288 if (parts.thread_kind != .patch or parts.comment_id != null) return respondRemoveNotFound(request); 1289 const server = switch (host.event()) { 1290 .server => |server| server, 1291 .local => return respondRemoveNotFound(request), 1292 }; 1293 var author_arena = std.heap.ArenaAllocator.init(allocator); 1294 defer author_arena.deinit(); 1295 const author = ((try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .write, .patch)) orelse return).author; 1296 1297 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1298 defer request_repo.deinit(allocator); 1299 var target_repo = try rp.AnyRepo(.xit, .{}).open(io, allocator, request_repo.source.localInitOpts()); 1300 defer target_repo.deinit(io, allocator); 1301 1302 const id = std.fmt.bytesToHex(parts.thread_id, .lower); 1303 const merged = switch (target_repo) { 1304 inline else => |*repo| pch.mergeAndRemoveFork(repo.self_repo_opts, io, allocator, server, repo, .{ 1305 .id = id, 1306 .revision = revision, 1307 .author = author, 1308 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1309 }), 1310 }; 1311 merged catch |err| switch (err) { 1312 error.MergeConflict => return request.respond("merge conflict", .{ 1313 .status = .conflict, 1314 .keep_alive = false, 1315 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1316 }), 1317 error.MergeCheckUnavailable, error.PatchOutOfDate, error.PatchDataUnavailable => {}, 1318 else => return err, 1319 }; 1320 1321 const location = try allocator.print("{s}/patch:{s}", .{ parts.repo_base, &id }); 1322 defer allocator.free(location); 1323 try request.respond("", .{ 1324 .status = .see_other, 1325 .keep_alive = false, 1326 .extra_headers = &.{.{ .name = "location", .value = location }}, 1327 }); 1328 } 1329 1330 // create a reply and redirect to its permalink. 1331 fn handleCommentNew( 1332 io: std.Io, 1333 request: *std.http.Server.Request, 1334 allocator: std.mem.Allocator, 1335 base: []const u8, 1336 host: Host, 1337 ) !void { 1338 const not_found = "comment parent not found"; 1339 const parts = commentBaseParts(host, base) orelse { 1340 try request.respond(not_found, .{ 1341 .status = .not_found, 1342 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1343 }); 1344 return; 1345 }; 1346 1347 var author_arena = std.heap.ArenaAllocator.init(allocator); 1348 defer author_arena.deinit(); 1349 const author = ((try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read, parts.thread_kind)) orelse return).author; 1350 1351 const form_body = try readFormBody(request, allocator); 1352 defer allocator.free(form_body); 1353 const body_crlf = (try parseFormField(allocator, form_body, "body")) orelse try allocator.dupe(u8, ""); 1354 defer allocator.free(body_crlf); 1355 const body = try std.mem.replaceOwned(u8, allocator, body_crlf, "\r\n", "\n"); 1356 defer allocator.free(body); 1357 1358 if (!evt.Comment.fieldsValid(body)) { 1359 const form_location = try allocator.print("{s}/new", .{base}); 1360 defer allocator.free(form_location); 1361 try request.respond("", .{ 1362 .status = .see_other, 1363 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1364 }); 1365 return; 1366 } 1367 1368 const thread_id_hex = std.fmt.bytesToHex(parts.thread_id, .lower); 1369 const parent_id_hex = std.fmt.bytesToHex(parts.comment_id orelse parts.thread_id, .lower); 1370 1371 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse { 1372 try request.respond(not_found, .{ 1373 .status = .not_found, 1374 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1375 }); 1376 return; 1377 }; 1378 defer request_repo.deinit(allocator); 1379 const source = request_repo.source; 1380 var event_id_hex: [evt.event_id_size * 2]u8 = undefined; 1381 switch (source.repo_kind) { 1382 inline else => |repo_kind| { 1383 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1384 defer any_repo.deinit(io, allocator); 1385 switch (any_repo) { 1386 inline else => |*repo| event_id_hex = evt.Comment.create(host.event(), repo_kind, repo.self_repo_opts, io, allocator, repo, parts.thread_kind, &thread_id_hex, &parent_id_hex, body, author) catch |err| switch (err) { 1387 // the url's thread or parent comment isn't what it claims 1388 error.NotFound => return request.respond(not_found, .{ 1389 .status = .not_found, 1390 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1391 }), 1392 else => |e| return e, 1393 }, 1394 } 1395 }, 1396 } 1397 1398 const location = try allocator.print("{s}/{s}:{s}/comment:{s}", .{ parts.repo_base, @tagName(parts.thread_kind), &thread_id_hex, &event_id_hex }); 1399 defer allocator.free(location); 1400 try request.respond("", .{ 1401 .status = .see_other, 1402 .extra_headers = &.{.{ .name = "location", .value = location }}, 1403 }); 1404 } 1405 1406 const AttachmentRequest = struct { 1407 repo_base: []const u8, 1408 id: [evt.event_id_size]u8, 1409 }; 1410 1411 // an attachment url is its repo's base and the attachment's event id 1412 fn attachmentRequest(path: []const u8) ?AttachmentRequest { 1413 const infix = "/attachment:"; 1414 const at = std.mem.lastIndexOf(u8, path, infix) orelse return null; 1415 const tail = path[at + infix.len ..]; 1416 const id = evt.parseEventId(tail) catch return null; 1417 return .{ .repo_base = path[0..at], .id = id }; 1418 } 1419 1420 // serve an attachment's bytes from the repo its url names 1421 fn serveAttachment( 1422 io: std.Io, 1423 request: *std.http.Server.Request, 1424 allocator: std.mem.Allocator, 1425 attachment: AttachmentRequest, 1426 host: Host, 1427 ) !void { 1428 if (!try mayRead(io, allocator, request, host, attachment.repo_base)) return respondAttachmentNotFound(request); 1429 const request_repo = (try requestRepoSource(io, allocator, host, attachment.repo_base)) orelse return respondAttachmentNotFound(request); 1430 defer request_repo.deinit(allocator); 1431 const source = request_repo.source; 1432 switch (source.repo_kind) { 1433 inline else => |repo_kind| { 1434 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1435 defer any_repo.deinit(io, allocator); 1436 switch (any_repo) { 1437 inline else => |*repo| try sendAttachment(repo_kind, repo.self_repo_opts, io, request, allocator, repo, &attachment.id), 1438 } 1439 }, 1440 } 1441 } 1442 1443 fn sendAttachment( 1444 comptime repo_kind: rp.RepoKind, 1445 comptime repo_opts: rp.RepoOpts(repo_kind), 1446 io: std.Io, 1447 request: *std.http.Server.Request, 1448 allocator: std.mem.Allocator, 1449 repo: *rp.Repo(repo_kind, repo_opts), 1450 id: *const [evt.event_id_size]u8, 1451 ) !void { 1452 var arena = std.heap.ArenaAllocator.init(allocator); 1453 defer arena.deinit(); 1454 1455 const DB = evt.EventDB(repo_opts.hash); 1456 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; 1457 defer if (event_db_maybe) |*event_db| event_db.deinit(io, allocator); 1458 const haxy_moment = (if (event_db_maybe) |*event_db| 1459 evt.currentMomentFromDb(repo_opts.hash, event_db.db) 1460 else if (repo_kind == .git) 1461 return respondAttachmentNotFound(request) 1462 else 1463 evt.currentMoment(repo_opts, repo)) catch return respondAttachmentNotFound(request); 1464 1465 const record = (try evt.Attachment.readById(DB, repo_opts.hash, haxy_moment, &arena, id)) orelse return respondAttachmentNotFound(request); 1466 if (record.removed) return respondAttachmentNotFound(request); 1467 if (record.blob_oid.len != hash.hexLen(repo_opts.hash)) return respondAttachmentNotFound(request); 1468 const blob_oid: *const [hash.hexLen(repo_opts.hash)]u8 = @ptrCast(record.blob_oid.ptr); 1469 1470 var moment = repo.core.latestMoment() catch return respondAttachmentNotFound(request); 1471 const state = rp.Repo(repo_kind, repo_opts).State(.read_only){ .core = &repo.core, .extra = .{ .moment = &moment } }; 1472 var object_reader = obj.ObjectReader(repo_kind, repo_opts).init(state, io, allocator, blob_oid) catch return respondAttachmentNotFound(request); 1473 defer object_reader.deinit(); 1474 if (object_reader.header().kind != .blob) return respondAttachmentNotFound(request); 1475 1476 const content_type = attachmentContentType(record.name); 1477 const encoded_name = try ui.urlEncodeRef(allocator, record.name); 1478 defer allocator.free(encoded_name); 1479 const disposition = try allocator.print("{s}; filename*=UTF-8''{s}", .{ if (content_type == null) "attachment" else "inline", encoded_name }); 1480 defer allocator.free(disposition); 1481 1482 var send_buf: [8192]u8 = undefined; 1483 var body = try request.respondStreaming(&send_buf, .{ 1484 .content_length = object_reader.header().size, 1485 .respond_options = .{ 1486 .extra_headers = &.{ 1487 .{ .name = "content-type", .value = content_type orelse "application/octet-stream" }, 1488 .{ .name = "content-disposition", .value = disposition }, 1489 // uploaded bytes are never sniffed into a type that could run 1490 // as script on this origin 1491 .{ .name = "x-content-type-options", .value = "nosniff" }, 1492 }, 1493 }, 1494 }); 1495 _ = try object_reader.interface.streamRemaining(&body.writer); 1496 try body.end(); 1497 } 1498 1499 // the images a browser renders safely inline. anything else downloads as 1500 // opaque bytes, so an uploaded page can't run on this origin. 1501 fn attachmentContentType(name: []const u8) ?[]const u8 { 1502 const types = [_]struct { ext: []const u8, value: []const u8 }{ 1503 .{ .ext = ".png", .value = "image/png" }, 1504 .{ .ext = ".jpg", .value = "image/jpeg" }, 1505 .{ .ext = ".jpeg", .value = "image/jpeg" }, 1506 .{ .ext = ".gif", .value = "image/gif" }, 1507 .{ .ext = ".webp", .value = "image/webp" }, 1508 }; 1509 for (types) |entry| { 1510 if (name.len > entry.ext.len and std.ascii.eqlIgnoreCase(name[name.len - entry.ext.len ..], entry.ext)) return entry.value; 1511 } 1512 return null; 1513 } 1514 1515 fn respondAttachmentNotFound(request: *std.http.Server.Request) !void { 1516 try request.respond("attachment not found", .{ 1517 .status = .not_found, 1518 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1519 }); 1520 } 1521 1522 fn respondAttachmentTargetNotFound(request: *std.http.Server.Request) !void { 1523 try request.respond("attachment target not found", .{ 1524 .status = .not_found, 1525 .keep_alive = false, 1526 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1527 }); 1528 } 1529 1530 // the upload declares its file's name here, since the body is the file itself 1531 const attachment_name_header = "x-attachment-name"; 1532 1533 const AttachTargetParts = struct { 1534 repo_base: []const u8, 1535 kind: evt.EventKind, 1536 id_bytes: [evt.event_id_size]u8, 1537 }; 1538 1539 // what an attachment hangs off: the `<kind>:<id>` segment the form's page ends 1540 // with, whatever kind that is 1541 fn attachTargetParts(base: []const u8) ?AttachTargetParts { 1542 const segment_at = std.mem.lastIndexOfScalar(u8, base, '/') orelse return null; 1543 const segment = base[segment_at + 1 ..]; 1544 const colon_at = std.mem.lastIndexOfScalar(u8, segment, ':') orelse return null; 1545 const kind = std.meta.stringToEnum(evt.EventKind, segment[0..colon_at]) orelse return null; 1546 const id_bytes = evt.parseEventId(segment[colon_at + 1 ..]) catch return null; 1547 return .{ .repo_base = base[0..segment_at], .kind = kind, .id_bytes = id_bytes }; 1548 } 1549 1550 // attach the uploaded file to the event the url names, then reload. the file is 1551 // the whole request body, so it streams from the socket into the object store 1552 // without being buffered. 1553 fn handleAttach( 1554 io: std.Io, 1555 request: *std.http.Server.Request, 1556 allocator: std.mem.Allocator, 1557 base: []const u8, 1558 host: Host, 1559 ) !void { 1560 const parts = attachTargetParts(base) orelse return respondAttachmentTargetNotFound(request); 1561 1562 var author_arena = std.heap.ArenaAllocator.init(allocator); 1563 defer author_arena.deinit(); 1564 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read, parts.kind)) orelse return; 1565 const author = actor.author; 1566 // an attachment changes the event it hangs off 1567 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondAttachmentTargetNotFound(request); 1568 defer request_repo.deinit(allocator); 1569 const source = request_repo.source; 1570 if (!try source.canModify(io, allocator, actor, parts.kind, &parts.id_bytes)) return respondForbidden(request); 1571 1572 const name = (try attachmentName(allocator, request)) orelse return respondUploadError(request, .bad_request, "attachment needs a name"); 1573 defer allocator.free(name); 1574 if (!evt.Attachment.nameValid(name)) return respondUploadError(request, .bad_request, "invalid attachment name"); 1575 1576 const size = request.head.content_length orelse return respondUploadError(request, .length_required, "attachments must declare a content length"); 1577 if (size == 0) return respondUploadError(request, .bad_request, "attachment is empty"); 1578 if (size > evt.Attachment.max_size) return respondUploadError(request, .payload_too_large, "attachment is too large"); 1579 1580 const target_id_hex = std.fmt.bytesToHex(parts.id_bytes, .lower); 1581 1582 var body_buf: [4096]u8 = undefined; 1583 const blob: evt.Blob = .{ .name = name, .size = size, .reader = try request.readerExpectContinue(&body_buf) }; 1584 1585 switch (source.repo_kind) { 1586 inline else => |repo_kind| { 1587 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1588 defer any_repo.deinit(io, allocator); 1589 switch (any_repo) { 1590 inline else => |*repo| _ = evt.Attachment.create(host.event(), repo_kind, repo.self_repo_opts, io, allocator, repo, parts.kind, &target_id_hex, blob, author) catch |err| switch (err) { 1591 error.TargetNotFound => return respondAttachmentTargetNotFound(request), 1592 else => return err, 1593 }, 1594 } 1595 }, 1596 } 1597 1598 // the client reloads the page itself 1599 try request.respond("", .{ .status = .no_content, .keep_alive = false }); 1600 } 1601 1602 // assign the posted email, or the email of the user it names, to the thread the 1603 // url names, then reload it 1604 fn handleAssign( 1605 io: std.Io, 1606 request: *std.http.Server.Request, 1607 allocator: std.mem.Allocator, 1608 base: []const u8, 1609 host: Host, 1610 ) !void { 1611 const parts = commentBaseParts(host, base) orelse return respondRemoveNotFound(request); 1612 if (parts.comment_id != null) return respondRemoveNotFound(request); 1613 1614 var arena = std.heap.ArenaAllocator.init(allocator); 1615 defer arena.deinit(); 1616 const actor = (try authorizeWrite(io, allocator, &arena, request, host, parts.repo_base, .read, parts.thread_kind)) orelse return; 1617 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1618 defer request_repo.deinit(allocator); 1619 const source = request_repo.source; 1620 if (!try source.canModify(io, allocator, actor, parts.thread_kind, &parts.thread_id)) return respondForbidden(request); 1621 1622 const text = blk: { 1623 const body = try readFormBody(request, allocator); 1624 defer allocator.free(body); 1625 break :blk (try parseFormField(arena.allocator(), body, "assignee")) orelse ""; 1626 }; 1627 const failure: ?ui.Session.FormFeedback.AssignmentFailure = blk: { 1628 const lookup = switch (host) { 1629 .local => try ui.assigneeEmail(null, &arena, text), 1630 .server => |server| server: { 1631 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 1632 defer admin_repo.deinit(io, allocator); 1633 break :server try ui.assigneeEmail(try evt.currentMoment(evt.admin_repo_opts, &admin_repo), &arena, text); 1634 }, 1635 }; 1636 const email = switch (lookup) { 1637 .email => |email| email, 1638 .failure => |value| break :blk value, 1639 }; 1640 const thread_id_hex = std.fmt.bytesToHex(parts.thread_id, .lower); 1641 switch (source.repo_kind) { 1642 inline else => |repo_kind| { 1643 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1644 defer any_repo.deinit(io, allocator); 1645 switch (any_repo) { 1646 inline else => |*repo| _ = evt.Assignment.create(host.event(), repo_kind, repo.self_repo_opts, io, allocator, repo, parts.thread_kind, &thread_id_hex, email, actor.author) catch |err| switch (err) { 1647 error.AlreadyAssigned => break :blk .already_assigned, 1648 error.InvalidFields => break :blk .not_an_email, 1649 error.NotFound => return respondRemoveNotFound(request), 1650 else => |e| return e, 1651 }, 1652 } 1653 }, 1654 } 1655 break :blk null; 1656 }; 1657 if (failure) |value| return respondThreadFormFailure(request, allocator, host, base, .{ .assignment = .{ .failure = value, .text = text } }); 1658 try request.respond("", .{ .status = .see_other, .keep_alive = false, .extra_headers = &.{.{ .name = "location", .value = base }} }); 1659 } 1660 1661 // unassign the email the url's last segment carries from the thread before it, 1662 // then reload the thread 1663 fn handleUnassign( 1664 io: std.Io, 1665 request: *std.http.Server.Request, 1666 allocator: std.mem.Allocator, 1667 base: []const u8, 1668 host: Host, 1669 ) !void { 1670 const infix = "/assignee:"; 1671 const at = std.mem.lastIndexOf(u8, base, infix) orelse return respondRemoveNotFound(request); 1672 const thread_url = base[0..at]; 1673 const parts = commentBaseParts(host, thread_url) orelse return respondRemoveNotFound(request); 1674 if (parts.comment_id != null) return respondRemoveNotFound(request); 1675 1676 var arena = std.heap.ArenaAllocator.init(allocator); 1677 defer arena.deinit(); 1678 const email = std.Uri.percentDecodeInPlace(try arena.allocator().dupe(u8, base[at + infix.len ..])); 1679 const actor = (try authorizeWrite(io, allocator, &arena, request, host, parts.repo_base, .read, parts.thread_kind)) orelse return; 1680 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1681 defer request_repo.deinit(allocator); 1682 const source = request_repo.source; 1683 if (!try source.canModify(io, allocator, actor, parts.thread_kind, &parts.thread_id)) return respondForbidden(request); 1684 1685 switch (source.repo_kind) { 1686 inline else => |repo_kind| { 1687 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1688 defer any_repo.deinit(io, allocator); 1689 switch (any_repo) { 1690 inline else => |*repo| evt.removeInThread(host.event(), repo_kind, repo.self_repo_opts, io, allocator, repo, parts.thread_kind, &parts.thread_id, .assign, &evt.Assignment.idOf(&parts.thread_id, email), actor.author) catch |err| switch (err) { 1691 error.EventNotFound => return respondRemoveNotFound(request), 1692 else => |e| return e, 1693 }, 1694 } 1695 }, 1696 } 1697 try request.respond("", .{ .status = .see_other, .keep_alive = false, .extra_headers = &.{.{ .name = "location", .value = thread_url }} }); 1698 } 1699 1700 // subscribe the logged-in user to the thread the url names, or mute it, then reload it 1701 fn handleNotify( 1702 io: std.Io, 1703 request: *std.http.Server.Request, 1704 allocator: std.mem.Allocator, 1705 base: []const u8, 1706 host: Host, 1707 users_dir: []const u8, 1708 mode: ui.NotifyAction, 1709 ) !void { 1710 const parts = commentBaseParts(host, base) orelse return respondRemoveNotFound(request); 1711 if (parts.comment_id != null) return respondRemoveNotFound(request); 1712 1713 var arena = std.heap.ArenaAllocator.init(allocator); 1714 defer arena.deinit(); 1715 const actor = (try authorizeWrite(io, allocator, &arena, request, host, parts.repo_base, .read, null)) orelse return; 1716 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1717 defer request_repo.deinit(allocator); 1718 // a server actor always has both ids 1719 const user_id = actor.user_id orelse unreachable; 1720 const location: evt.RepoLocation = .{ 1721 .owner_id = actor.repo_user_id orelse unreachable, 1722 .repo_id = evt.parseEventId(std.Io.Dir.path.basename(request_repo.source.path)) catch return respondRemoveNotFound(request), 1723 }; 1724 1725 switch (mode) { 1726 .subscribe => try notify.subscribe(io, allocator, users_dir, &user_id, location, &parts.thread_id, actor.author), 1727 .mute => try notify.mute(io, allocator, users_dir, &user_id, location, &parts.thread_id, actor.author), 1728 } 1729 try request.respond("", .{ .status = .see_other, .keep_alive = false, .extra_headers = &.{.{ .name = "location", .value = base }} }); 1730 } 1731 1732 // the name the upload declares for its file, percent-encoded so it survives a 1733 // header 1734 fn attachmentName(allocator: std.mem.Allocator, request: *std.http.Server.Request) !?[]u8 { 1735 var iter = request.iterateHeaders(); 1736 while (iter.next()) |header| { 1737 if (!std.ascii.eqlIgnoreCase(header.name, attachment_name_header)) continue; 1738 return try decodeFormValue(allocator, header.value); 1739 } 1740 return null; 1741 } 1742 1743 // an upload that failed leaves the body partly read, so the connection closes 1744 fn respondUploadError(request: *std.http.Server.Request, status: std.http.Status, message: []const u8) !void { 1745 try request.respond(message, .{ 1746 .status = status, 1747 .keep_alive = false, 1748 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1749 }); 1750 } 1751 1752 // re-emit the comment `parts` names with a new body, in the repo the host 1753 // resolves the base to. 1754 fn updateComment( 1755 io: std.Io, 1756 allocator: std.mem.Allocator, 1757 host: Host, 1758 parts: CommentBaseParts, 1759 body: []const u8, 1760 author: evt.CommitAuthor, 1761 ) !void { 1762 const comment_id = parts.comment_id orelse return error.NotFound; 1763 const thread_id = std.fmt.bytesToHex(parts.thread_id, .lower); 1764 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return error.NotFound; 1765 defer request_repo.deinit(allocator); 1766 const source = request_repo.source; 1767 switch (source.repo_kind) { 1768 inline else => |repo_kind| { 1769 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1770 defer any_repo.deinit(io, allocator); 1771 switch (any_repo) { 1772 inline else => |*repo| try evt.Comment.update(host.event(), repo_kind, repo.self_repo_opts, io, allocator, repo, parts.thread_kind, &thread_id, &comment_id, body, author), 1773 } 1774 }, 1775 } 1776 } 1777 1778 // edit actions share a suffix; the base identifies the event being edited. 1779 fn handleEdit( 1780 io: std.Io, 1781 request: *std.http.Server.Request, 1782 allocator: std.mem.Allocator, 1783 base: []const u8, 1784 host: Host, 1785 ) !void { 1786 const parts = commentBaseParts(host, base) orelse return respondRemoveNotFound(request); 1787 if (parts.comment_id != null) return handleCommentEdit(io, request, allocator, base, host, parts); 1788 return handleThreadEdit(io, request, allocator, base, host, parts); 1789 } 1790 1791 // replace the body of the comment the url names, then redirect to its 1792 // permalink. 1793 fn handleCommentEdit( 1794 io: std.Io, 1795 request: *std.http.Server.Request, 1796 allocator: std.mem.Allocator, 1797 base: []const u8, 1798 host: Host, 1799 parts: CommentBaseParts, 1800 ) !void { 1801 var author_arena = std.heap.ArenaAllocator.init(allocator); 1802 defer author_arena.deinit(); 1803 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read, parts.thread_kind)) orelse return; 1804 const author = actor.author; 1805 // edits only reach here for a comment 1806 const comment_id = parts.comment_id orelse unreachable; 1807 { 1808 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1809 defer request_repo.deinit(allocator); 1810 if (!try request_repo.source.canModify(io, allocator, actor, .comment, &comment_id)) return respondForbidden(request); 1811 } 1812 1813 const form_body = try readFormBody(request, allocator); 1814 defer allocator.free(form_body); 1815 const body_crlf = (try parseFormField(allocator, form_body, "body")) orelse try allocator.dupe(u8, ""); 1816 defer allocator.free(body_crlf); 1817 const body = try std.mem.replaceOwned(u8, allocator, body_crlf, "\r\n", "\n"); 1818 defer allocator.free(body); 1819 1820 if (!evt.Comment.fieldsValid(body)) { 1821 const form_location = try allocator.print("{s}/edit", .{base}); 1822 defer allocator.free(form_location); 1823 try request.respond("", .{ 1824 .status = .see_other, 1825 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1826 }); 1827 return; 1828 } 1829 1830 const not_found = "comment not found"; 1831 updateComment(io, allocator, host, parts, body, author) catch |err| switch (err) { 1832 error.NotFound => { 1833 try request.respond(not_found, .{ 1834 .status = .not_found, 1835 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1836 }); 1837 return; 1838 }, 1839 else => |e| return e, 1840 }; 1841 1842 try request.respond("", .{ 1843 .status = .see_other, 1844 .extra_headers = &.{.{ .name = "location", .value = base }}, 1845 }); 1846 } 1847 1848 fn updateThread( 1849 comptime Event: type, 1850 io: std.Io, 1851 allocator: std.mem.Allocator, 1852 host: Host, 1853 repo_base: []const u8, 1854 id: *const [evt.event_id_size]u8, 1855 update: Event.Update, 1856 author: evt.CommitAuthor, 1857 ) !void { 1858 const request_repo = (try requestRepoSource(io, allocator, host, repo_base)) orelse return error.NotFound; 1859 defer request_repo.deinit(allocator); 1860 const source = request_repo.source; 1861 switch (source.repo_kind) { 1862 inline else => |repo_kind| { 1863 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1864 defer any_repo.deinit(io, allocator); 1865 switch (any_repo) { 1866 inline else => |*repo| try Event.update(host.event(), repo_kind, repo.self_repo_opts, io, allocator, repo, id, update, author), 1867 } 1868 }, 1869 } 1870 } 1871 1872 const RemoveParts = struct { 1873 repo_base: []const u8, 1874 kind: evt.EventKind, 1875 // the thread the removed event is, or belongs to 1876 thread_kind: evt.EventKind, 1877 thread_id: [evt.event_id_size]u8, 1878 id: [evt.event_id_size]u8, 1879 }; 1880 1881 // split a remove url into the repo and event it names 1882 fn removeParts(host: Host, base: []const u8) ?RemoveParts { 1883 if (attachmentRequest(base)) |attachment| { 1884 const target = attachTargetParts(attachment.repo_base) orelse return null; 1885 return .{ 1886 .repo_base = target.repo_base, 1887 .kind = .attach, 1888 .thread_kind = target.kind, 1889 .thread_id = target.id_bytes, 1890 .id = attachment.id, 1891 }; 1892 } 1893 if (commentBaseParts(host, base)) |thread| return .{ 1894 .repo_base = thread.repo_base, 1895 .kind = if (thread.comment_id != null) .comment else thread.thread_kind, 1896 .thread_kind = thread.thread_kind, 1897 .thread_id = thread.thread_id, 1898 .id = thread.comment_id orelse thread.thread_id, 1899 }; 1900 return null; 1901 } 1902 1903 // remove the event named by the form's url 1904 fn handleRemove( 1905 io: std.Io, 1906 request: *std.http.Server.Request, 1907 allocator: std.mem.Allocator, 1908 base: []const u8, 1909 host: Host, 1910 ) !void { 1911 const parts = removeParts(host, base) orelse return respondRemoveNotFound(request); 1912 1913 var author_arena = std.heap.ArenaAllocator.init(allocator); 1914 defer author_arena.deinit(); 1915 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read, parts.thread_kind)) orelse return; 1916 const author = actor.author; 1917 1918 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1919 defer request_repo.deinit(allocator); 1920 const source = request_repo.source; 1921 1922 if (parts.kind == .patch) switch (host) { 1923 .server => |server| { 1924 const user_id = actor.user_id orelse return respondLoginRequired(request); 1925 1926 // a draft lives in its author's user repo 1927 if (try evt.readForkById(io, allocator, &author_arena, server.users_dir, &user_id, &parts.id)) |fork_record| { 1928 const repo_id = evt.parseEventId(std.Io.Dir.path.basename(source.path)) catch return respondRemoveNotFound(request); 1929 if (!fork_record.removed and fork_record.event.stage == .draft and std.mem.eql(u8, &fork_record.event.repo_id, &std.fmt.bytesToHex(repo_id, .lower))) { 1930 const id = std.fmt.bytesToHex(parts.id, .lower); 1931 try fork.remove(io, allocator, server.users_dir, &user_id, &id, author); 1932 1933 const location = try allocator.print("{s}/patches/drafts", .{parts.repo_base}); 1934 defer allocator.free(location); 1935 try request.respond("", .{ 1936 .status = .see_other, 1937 .keep_alive = false, 1938 .extra_headers = &.{.{ .name = "location", .value = location }}, 1939 }); 1940 return; 1941 } 1942 } 1943 }, 1944 .local => {}, 1945 }; 1946 1947 // a draft is its author's alone, which its removal above checks 1948 if (!try source.canModify(io, allocator, actor, parts.kind, &parts.id)) return respondForbidden(request); 1949 1950 switch (source.repo_kind) { 1951 inline else => |repo_kind| { 1952 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1953 defer any_repo.deinit(io, allocator); 1954 switch (any_repo) { 1955 inline else => |*repo| evt.removeInThread(host.event(), repo_kind, repo.self_repo_opts, io, allocator, repo, parts.thread_kind, &parts.thread_id, parts.kind, &parts.id, author) catch |err| switch (err) { 1956 error.EventNotFound => return respondRemoveNotFound(request), 1957 else => |e| return e, 1958 }, 1959 } 1960 }, 1961 } 1962 1963 // back to the thread a comment or attachment was on, or to the list a thread left 1964 const location = if (parts.kind == parts.thread_kind) 1965 try allocator.print("{s}/{s}", .{ parts.repo_base, threadListName(parts.thread_kind) }) 1966 else 1967 try allocator.print("{s}/{s}:{s}", .{ parts.repo_base, @tagName(parts.thread_kind), &std.fmt.bytesToHex(parts.thread_id, .lower) }); 1968 defer allocator.free(location); 1969 try request.respond("", .{ 1970 .status = .see_other, 1971 .keep_alive = false, 1972 .extra_headers = &.{.{ .name = "location", .value = location }}, 1973 }); 1974 } 1975 1976 // the tab listing threads of `kind` 1977 fn threadListName(kind: evt.EventKind) []const u8 { 1978 return switch (kind) { 1979 .issue => "issues", 1980 .patch => "patches", 1981 .discuss => "discussions", 1982 else => unreachable, 1983 }; 1984 } 1985 1986 fn respondRemoveNotFound(request: *std.http.Server.Request) !void { 1987 try request.respond("event not found", .{ 1988 .status = .not_found, 1989 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1990 }); 1991 } 1992 1993 fn updateDiscussion( 1994 io: std.Io, 1995 allocator: std.mem.Allocator, 1996 host: Host, 1997 repo_base: []const u8, 1998 id: *const [evt.event_id_size]u8, 1999 title: []const u8, 2000 labels: []const u8, 2001 description: []const u8, 2002 author: evt.CommitAuthor, 2003 ) !void { 2004 const request_repo = (try requestRepoSource(io, allocator, host, repo_base)) orelse return error.NotFound; 2005 defer request_repo.deinit(allocator); 2006 const source = request_repo.source; 2007 switch (source.repo_kind) { 2008 inline else => |repo_kind| { 2009 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 2010 defer any_repo.deinit(io, allocator); 2011 switch (any_repo) { 2012 inline else => |*repo| try evt.Discussion.update(host.event(), repo_kind, repo.self_repo_opts, io, allocator, repo, id, title, labels, description, author), 2013 } 2014 }, 2015 } 2016 } 2017 2018 // set the status of the issue the url names (base is 2019 // "/<owner>:<name>/issue:<id>", identity elided in local mode) by 2020 // re-emitting its event, then redirect back to it 2021 fn handleThreadStatus( 2022 io: std.Io, 2023 request: *std.http.Server.Request, 2024 allocator: std.mem.Allocator, 2025 base: []const u8, 2026 host: Host, 2027 open: bool, 2028 ) !void { 2029 const not_found = "thread not found"; 2030 const parts = commentBaseParts(host, base) orelse { 2031 try request.respond(not_found, .{ 2032 .status = .not_found, 2033 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2034 }); 2035 return; 2036 }; 2037 2038 var author_arena = std.heap.ArenaAllocator.init(allocator); 2039 defer author_arena.deinit(); 2040 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read, parts.thread_kind)) orelse return; 2041 const author = actor.author; 2042 { 2043 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 2044 defer request_repo.deinit(allocator); 2045 if (!try request_repo.source.canModify(io, allocator, actor, parts.thread_kind, &parts.thread_id)) return respondForbidden(request); 2046 } 2047 2048 (switch (parts.thread_kind) { 2049 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .status = if (open) .open else .closed }, author), 2050 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .status = if (open) .open else .closed }, author), 2051 else => return respondRemoveNotFound(request), 2052 }) catch |err| switch (err) { 2053 error.NotFound => { 2054 try request.respond(not_found, .{ 2055 .status = .not_found, 2056 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2057 }); 2058 return; 2059 }, 2060 else => |e| return e, 2061 }; 2062 2063 // like logout, this is a bodyless POST, so close the connection rather than 2064 // letting the keep-alive path try to discard a body that isn't framed. 2065 try request.respond("", .{ 2066 .status = .see_other, 2067 .keep_alive = false, 2068 .extra_headers = &.{.{ .name = "location", .value = base }}, 2069 }); 2070 } 2071 2072 // replace a thread's editable fields. 2073 fn handleThreadEdit( 2074 io: std.Io, 2075 request: *std.http.Server.Request, 2076 allocator: std.mem.Allocator, 2077 base: []const u8, 2078 host: Host, 2079 parts: CommentBaseParts, 2080 ) !void { 2081 var author_arena = std.heap.ArenaAllocator.init(allocator); 2082 defer author_arena.deinit(); 2083 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read, parts.thread_kind)) orelse return; 2084 const author = actor.author; 2085 2086 const body = try readFormBody(request, allocator); 2087 defer allocator.free(body); 2088 2089 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 2090 defer allocator.free(title); 2091 const labels = (try parseFormField(allocator, body, "labels")) orelse try allocator.dupe(u8, ""); 2092 defer allocator.free(labels); 2093 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 2094 defer allocator.free(description_crlf); 2095 // form submission normalizes textarea line breaks to CRLF; store plain 2096 // newlines so the text renders the same on every host 2097 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 2098 defer allocator.free(description); 2099 const target_branch = (try parseFormField(allocator, body, "target_branch")) orelse try allocator.dupe(u8, ""); 2100 defer allocator.free(target_branch); 2101 2102 // invalid fields send the user back to the edit form 2103 const valid = switch (parts.thread_kind) { 2104 .issue => evt.Issue.fieldsValid(title, labels), 2105 .patch => evt.Patch.fieldsValid(title, labels), 2106 .discuss => evt.Discussion.fieldsValid(title, labels), 2107 else => unreachable, 2108 }; 2109 if (!valid) { 2110 const form_location = try allocator.print("{s}/edit", .{base}); 2111 defer allocator.free(form_location); 2112 if (!evt.titleValid(title)) { 2113 return respondThreadFormFailure(request, allocator, host, form_location, requiredTitleFeedback(parts.thread_kind, title, labels, description, target_branch, null)); 2114 } 2115 try request.respond("", .{ 2116 .status = .see_other, 2117 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 2118 }); 2119 return; 2120 } 2121 2122 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 2123 defer request_repo.deinit(allocator); 2124 2125 const draft_user_id = if (parts.thread_kind == .patch) actor.user_id else null; 2126 if (draft_user_id) |user_id| { 2127 const server = switch (host) { 2128 .server => |server| server, 2129 .local => unreachable, 2130 }; 2131 if (!evt.Patch.branchValid(target_branch) or !try request_repo.source.hasBranch(io, allocator, target_branch)) { 2132 const form_location = try allocator.print("{s}/edit", .{base}); 2133 defer allocator.free(form_location); 2134 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(.invalid_target_branch, title, labels, description, target_branch, null)); 2135 } 2136 const repo_id = evt.parseEventId(std.Io.Dir.path.basename(request_repo.source.path)) catch return respondRemoveNotFound(request); 2137 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 2138 defer admin_repo.deinit(io, allocator); 2139 const id = std.fmt.bytesToHex(parts.thread_id, .lower); 2140 if (try pch.editDraft(.{}, io, allocator, server.users_dir, &admin_repo, .{ 2141 .id = id, 2142 .user_id = user_id, 2143 .repo_id = repo_id, 2144 .title = title, 2145 .labels = labels, 2146 .description = description, 2147 .target_branch = target_branch, 2148 .author = author, 2149 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2150 })) { 2151 try request.respond("", .{ 2152 .status = .see_other, 2153 .extra_headers = &.{.{ .name = "location", .value = base }}, 2154 }); 2155 return; 2156 } 2157 } 2158 2159 // a draft is its author's alone, which its edit above checks 2160 if (!try request_repo.source.canModify(io, allocator, actor, parts.thread_kind, &parts.thread_id)) return respondForbidden(request); 2161 2162 const not_found = switch (parts.thread_kind) { 2163 .issue => "issue not found", 2164 .patch => "patch not found", 2165 .discuss => "discussion not found", 2166 else => unreachable, 2167 }; 2168 (switch (parts.thread_kind) { 2169 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 2170 .title = title, 2171 .labels = labels, 2172 .description = description, 2173 } }, author), 2174 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 2175 .title = title, 2176 .labels = labels, 2177 .description = description, 2178 .target_branch = target_branch, 2179 } }, author), 2180 .discuss => updateDiscussion(io, allocator, host, parts.repo_base, &parts.thread_id, title, labels, description, author), 2181 else => unreachable, 2182 }) catch |err| switch (err) { 2183 error.NotFound => { 2184 try request.respond(not_found, .{ 2185 .status = .not_found, 2186 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2187 }); 2188 return; 2189 }, 2190 else => { 2191 if (parts.thread_kind != .patch) return err; 2192 const failure = ui.Session.FormFeedback.PatchFailure.fromError(err) orelse return err; 2193 const form_location = try allocator.print("{s}/edit", .{base}); 2194 defer allocator.free(form_location); 2195 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(failure, title, labels, description, target_branch, null)); 2196 }, 2197 }; 2198 2199 try request.respond("", .{ 2200 .status = .see_other, 2201 .extra_headers = &.{.{ .name = "location", .value = base }}, 2202 }); 2203 } 2204 2205 // resolve every conflicted field of the thread the url names 2206 fn handleThreadResolve( 2207 io: std.Io, 2208 request: *std.http.Server.Request, 2209 allocator: std.mem.Allocator, 2210 base: []const u8, 2211 host: Host, 2212 ) !void { 2213 const parts = commentBaseParts(host, base) orelse { 2214 try request.respond("thread not found", .{ 2215 .status = .not_found, 2216 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2217 }); 2218 return; 2219 }; 2220 2221 var author_arena = std.heap.ArenaAllocator.init(allocator); 2222 defer author_arena.deinit(); 2223 const author = ((try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .write, parts.thread_kind)) orelse return).author; 2224 2225 const body = try readFormBody(request, allocator); 2226 defer allocator.free(body); 2227 2228 var field_arena = std.heap.ArenaAllocator.init(allocator); 2229 defer field_arena.deinit(); 2230 const aa = field_arena.allocator(); 2231 const title = try parseFormField(aa, body, "title"); 2232 const labels = try parseFormField(aa, body, "labels"); 2233 2234 // the hunk inputs are submitted as d0, d1, ...; form submission normalizes their 2235 // textarea line breaks to CRLF 2236 var hunks: std.ArrayList([]const u8) = .empty; 2237 var hunk_index: usize = 0; 2238 while (true) : (hunk_index += 1) { 2239 const name = try aa.print("d{d}", .{hunk_index}); 2240 const submitted = (try parseFormField(aa, body, name)) orelse break; 2241 try hunks.append(aa, try std.mem.replaceOwned(u8, aa, submitted, "\r\n", "\n")); 2242 } 2243 2244 if (parts.comment_id != null or (parts.thread_kind != .issue and parts.thread_kind != .patch)) { 2245 try request.respond("thread not found", .{ 2246 .status = .not_found, 2247 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2248 }); 2249 return; 2250 } 2251 const route = routeFromUrl(host, base) orelse { 2252 try request.respond("thread not found", .{ 2253 .status = .not_found, 2254 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2255 }); 2256 return; 2257 }; 2258 const theirs: []const u8 = switch (route) { 2259 .repo_patches => |*patch| patch.theirs.slice(), 2260 .repo_issues => "", 2261 else => unreachable, 2262 }; 2263 const not_found = if (parts.thread_kind == .patch) "patch not found" else "issue not found"; 2264 2265 (switch (parts.thread_kind) { 2266 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 2267 .title = title, 2268 .labels = labels, 2269 .hunks = hunks.items, 2270 } }, author), 2271 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 2272 .title = title, 2273 .labels = labels, 2274 .hunks = hunks.items, 2275 .theirs = theirs, 2276 } }, author), 2277 else => unreachable, 2278 }) catch |err| switch (err) { 2279 error.NotFound => { 2280 try request.respond(not_found, .{ 2281 .status = .not_found, 2282 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2283 }); 2284 return; 2285 }, 2286 // invalid fields send the user back to the resolve form 2287 error.InvalidFields => { 2288 const form_location = try allocator.print("{s}/resolve", .{base}); 2289 defer allocator.free(form_location); 2290 try request.respond("", .{ 2291 .status = .see_other, 2292 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 2293 }); 2294 return; 2295 }, 2296 else => |e| return e, 2297 }; 2298 2299 try request.respond("", .{ 2300 .status = .see_other, 2301 .extra_headers = &.{.{ .name = "location", .value = base }}, 2302 }); 2303 } 2304 2305 // the posted path drops the action's own segment, so the route it parses is 2306 // the undo page the action applies to 2307 fn handleUndo(io: std.Io, request: *std.http.Server.Request, allocator: std.mem.Allocator, base: []const u8, host: Host) !void { 2308 const route = routeFromUrl(host, base) orelse return respondRepoNotFound(request); 2309 if (route != .repo_undo) return respondRepoNotFound(request); 2310 const target = route.repo_undo; 2311 var arena = std.heap.ArenaAllocator.init(allocator); 2312 defer arena.deinit(); 2313 const repo_base = if (target.name.len == 0) "" else try arena.allocator().print("/{s}", .{target.name.slice()}); 2314 _ = (try authorizeWrite(io, allocator, &arena, request, host, repo_base, .owner, null)) orelse return; 2315 const resolved = (try requestRepoSource(io, allocator, host, repo_base)) orelse return respondRepoNotFound(request); 2316 defer resolved.deinit(allocator); 2317 ui.Repo.Undo.execute(io, allocator, resolved.source, target.index orelse return respondRepoNotFound(request)) catch |err| switch (err) { 2318 error.NotFound, error.InvalidHistoryIndex, error.TransactionNotFound => return respondRepoNotFound(request), 2319 else => return err, 2320 }; 2321 const location = try (ui.RoutablePage.repoUndoRoute(target.name.slice(), null) orelse return error.RouteTooLong).toUrl(&arena); 2322 try request.respond("", .{ .status = .see_other, .keep_alive = false, .extra_headers = &.{.{ .name = "location", .value = location }} }); 2323 } 2324 2325 fn handleSync( 2326 io: std.Io, 2327 request: *std.http.Server.Request, 2328 allocator: std.mem.Allocator, 2329 base: []const u8, 2330 source: ui.RepoSource, 2331 ) !void { 2332 if (base.len != 0) { 2333 try request.respond("not found", .{ 2334 .status = .not_found, 2335 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2336 }); 2337 return; 2338 } 2339 2340 var owned_failure: ?[]u8 = null; 2341 defer if (owned_failure) |message| allocator.free(message); 2342 const failure: ?[]const u8 = blk: { 2343 owned_failure = ui.Repo.Events.sync(io, allocator, source) catch |err| break :blk @errorName(err); 2344 break :blk owned_failure; 2345 }; 2346 if (failure) |message| { 2347 var encoded: std.Io.Writer.Allocating = .init(allocator); 2348 defer encoded.deinit(); 2349 try std.Uri.Component.percentEncode(&encoded.writer, message, struct { 2350 fn isUnreserved(c: u8) bool { 2351 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 2352 } 2353 }.isUnreserved); 2354 const cookie = try allocator.print( 2355 local_flash_cookie ++ "=" ++ local_sync_failure_prefix ++ "{s}; Path=/; HttpOnly; SameSite=Strict", 2356 .{encoded.written()}, 2357 ); 2358 defer allocator.free(cookie); 2359 try request.respond("", .{ 2360 .status = .see_other, 2361 .extra_headers = &.{ 2362 .{ .name = "location", .value = "/events" }, 2363 .{ .name = "set-cookie", .value = cookie }, 2364 }, 2365 }); 2366 return; 2367 } 2368 2369 try request.respond("", .{ 2370 .status = .see_other, 2371 .extra_headers = &.{ 2372 .{ .name = "location", .value = "/events" }, 2373 .{ .name = "set-cookie", .value = local_flash_cookie ++ "=; Path=/; Max-Age=0" }, 2374 }, 2375 }); 2376 } 2377 2378 fn renderIndexHtml( 2379 io: std.Io, 2380 allocator: std.mem.Allocator, 2381 host: Host, 2382 session_token: ?[]const u8, 2383 session_data: ui.Session.Data, 2384 ) ![]const u8 { 2385 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 2386 2387 var page_arena = std.heap.ArenaAllocator.init(allocator); 2388 defer page_arena.deinit(); 2389 2390 // the server admin repo must outlive the page build, since the session's 2391 // moment reads from it. 2392 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 2393 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 2394 2395 var session = switch (host) { 2396 .server => |server| blk: { 2397 // open the admin repo to read live user/repo data. 2398 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 2399 const repo = if (repo_maybe) |*repo| repo else unreachable; 2400 var session = try ui.Session.init(&page_arena, repo, session_data); 2401 // the session dropped a user whose account was removed, so revoke 2402 // the token that named them 2403 if (session_token) |token| { 2404 if (session.data.user_id == null) server.session_store.remove(token); 2405 } 2406 // give the page builders filesystem access to the on-disk repos (a 2407 // sibling "users" dir next to the admin repo) so the Repo page can 2408 // read its files. 2409 session.users_dir = server.users_dir; 2410 break :blk session; 2411 }, 2412 .local => |local| ui.Session{ 2413 .data = session_data, 2414 .arena = &page_arena, 2415 .page_arena = &page_arena, 2416 .local = local, 2417 }, 2418 }; 2419 session.io = io; 2420 session.data.now = std.math.cast(i64, std.Io.Timestamp.now(io, .real).toSeconds()) orelse return error.TimestampOutOfRange; 2421 2422 var page = try ui.Page.init(session.page_arena, &session, session.data.current_page); 2423 var root = try ui.initRoot(allocator, &page, &session); 2424 defer root.deinit(allocator); 2425 2426 const snapshot: ui.Snapshot = .{ .page = page, .session = session.data }; 2427 2428 const content = try generateHtml(allocator, &root, &session); 2429 defer allocator.free(content); 2430 2431 // serialize the snapshot so the wasm side can parse it back without making 2432 // a second request. it's embedded raw in a <script type="application/json"> 2433 // block, whose content is raw text terminated only by "</script". in json, 2434 // '<' appears solely inside string values, so escaping every '<' (and '>' 2435 // for good measure) to its \uXXXX form yields equivalent json that can't 2436 // break out of the tag. 2437 var json: std.Io.Writer.Allocating = .init(allocator); 2438 defer json.deinit(); 2439 try std.json.Stringify.value(snapshot, .{}, &json.writer); 2440 2441 var json_escaped: std.ArrayList(u8) = .empty; 2442 defer json_escaped.deinit(allocator); 2443 for (json.written()) |c| switch (c) { 2444 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 2445 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 2446 else => try json_escaped.append(allocator, c), 2447 }; 2448 2449 var out: std.ArrayList(u8) = .empty; 2450 errdefer out.deinit(allocator); 2451 { 2452 var cursor: usize = 0; 2453 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 2454 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 2455 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 2456 }) |sub| { 2457 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 2458 try out.appendSlice(allocator, template[cursor..idx]); 2459 try out.appendSlice(allocator, sub.replacement); 2460 cursor = idx + sub.needle.len; 2461 } 2462 try out.appendSlice(allocator, template[cursor..]); 2463 } 2464 return try out.toOwnedSlice(allocator); 2465 } 2466 2467 fn findEmbed(request_path: []const u8) ?Embed { 2468 // embeds are matched before pages, so a dot keeps them from claiming a username or tab 2469 comptime for (embeds) |embed| { 2470 if (std.mem.indexOfScalar(u8, embed.path, '.') == null) @compileError("embed path needs a '.' so it can't shadow a page: " ++ embed.path); 2471 }; 2472 if (request_path.len < 2 or request_path[0] != '/') return null; 2473 const path = request_path[1..]; 2474 2475 for (embeds) |embed| { 2476 if (std.mem.eql(u8, path, embed.path)) return embed; 2477 } 2478 return null; 2479 } 2480 2481 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 2482 // own absolutely-positioned, natively-scrollable <div> holding its full content, 2483 // rendered recursively so nested scrolls work. 2484 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 2485 const grid = root.getGrid() orelse return error.MissingGrid; 2486 const root_focus = root.getFocus(); 2487 2488 var out: std.ArrayList(u8) = .empty; 2489 errdefer out.deinit(allocator); 2490 2491 switch (root.*) { 2492 .background => |*background| { 2493 if (background.art.getGrid()) |art| { 2494 try out.print(allocator, "<div class=\"ansi-art\" aria-hidden=\"true\" style=\"left:{d}ch;opacity:{d}%\">", .{ grid.size.width -| art.size.width, ui.widget.AnsiBackground.art_opacity }); 2495 try renderPanel(allocator, &out, background.art.getFocus(), art, session, root_focus); 2496 try out.appendSlice(allocator, "</div>"); 2497 } 2498 }, 2499 else => {}, 2500 } 2501 try out.appendSlice(allocator, "<div class=\"grid-content\" data-key=\"panel:root\">"); 2502 try renderPanel(allocator, &out, root_focus, grid, session, root_focus); 2503 try out.appendSlice(allocator, "</div>"); 2504 try renderForms(allocator, &out, root_focus); 2505 return try out.toOwnedSlice(allocator); 2506 } 2507 2508 // render one panel — a focus subtree and its content grid — as HTML, recursing 2509 // once per web-native Scroll inside it. the root panel is the whole page; each 2510 // Scroll becomes a nested, natively-scrollable div holding its full content. 2511 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 2512 // then the child scroll divs over those holes. 2513 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid, session: *ui.Session, root_focus: *Focus) !void { 2514 // `direct` is this panel's scroll children, each drawn as an overlaid div. 2515 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 2516 // plus their descendants, which the focus tree flattens into this panel's 2517 // children): the cell hit-test below skips them so this panel doesn't claim 2518 // cells that are really rendered inside a child scroll's own panel. 2519 // (scrolls aren't nested in practice, so every scroll child is direct here.) 2520 var direct: std.ArrayList(usize) = .empty; 2521 defer direct.deinit(allocator); 2522 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 2523 defer excluded.deinit(allocator); 2524 { 2525 var it = focus.children.iterator(); 2526 while (it.next()) |e| { 2527 if (e.value_ptr.focus.scroll == null) continue; 2528 try direct.append(allocator, e.key_ptr.*); 2529 try excluded.put(allocator, e.key_ptr.*, {}); 2530 var mit = e.value_ptr.focus.children.iterator(); 2531 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 2532 } 2533 } 2534 2535 // the HTML element a run of cells is wrapped in, chosen from the cell's 2536 // focusable kind 2537 const CellTag = union(enum) { 2538 span, // clickable focusable cell 2539 a: []const u8, // clickable focusable link 2540 plain, // non-focusable, colored 2541 2542 const a_prefix = "a:"; 2543 // an "in-page" anchor: rendered as a real <a href> so it works with js 2544 // disabled, but wasm handles it without navigating. 2545 fn init(str: []const u8) @This() { 2546 if (std.mem.startsWith(u8, str, ui.raw_link_prefix)) { 2547 return .{ .a = str[ui.raw_link_prefix.len..] }; 2548 } 2549 if (std.mem.startsWith(u8, str, ui.in_page_link_prefix)) { 2550 return .{ .a = str[ui.in_page_link_prefix.len..] }; 2551 } 2552 if (std.mem.startsWith(u8, str, a_prefix)) { 2553 return .{ .a = str[a_prefix.len..] }; 2554 } 2555 return .span; 2556 } 2557 2558 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 2559 var id_buf: [32]u8 = undefined; 2560 switch (self) { 2561 .span => { 2562 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 2563 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 2564 try out.appendSlice(alloc, "\""); 2565 try out.appendSlice(alloc, style_attr); 2566 try out.appendSlice(alloc, ">"); 2567 }, 2568 .a => |href| { 2569 // tabindex=-1 keeps these out of the browser's tab order 2570 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 2571 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 2572 try out.appendSlice(alloc, "\" href=\""); 2573 try appendEscapedHtml(alloc, out, href); 2574 try out.appendSlice(alloc, "\""); 2575 try out.appendSlice(alloc, style_attr); 2576 try out.appendSlice(alloc, ">"); 2577 }, 2578 .plain => { 2579 try out.appendSlice(alloc, "<span"); 2580 try out.appendSlice(alloc, style_attr); 2581 try out.appendSlice(alloc, ">"); 2582 }, 2583 } 2584 } 2585 2586 fn closeTag(self: @This()) []const u8 { 2587 return switch (self) { 2588 .span, .plain => "</span>", 2589 .a => "</a>", 2590 }; 2591 } 2592 }; 2593 2594 // the focusable owning each cell, among this panel's own (skipping any 2595 // that belong to a child scroll, whose cells are drawn in their own panel). 2596 // claimed in focus order, so the first focusable over a cell keeps it. 2597 // looking every focusable up for every cell is quadratic in a long list. 2598 const owners = try allocator.alloc(?usize, grid.size.width * grid.size.height); 2599 defer allocator.free(owners); 2600 @memset(owners, null); 2601 { 2602 var it = focus.children.iterator(); 2603 while (it.next()) |entry| { 2604 const child = entry.value_ptr.*; 2605 if (child.focus.mode != .all) continue; 2606 if (excluded.contains(entry.key_ptr.*)) continue; 2607 const r = child.rect; 2608 for (@min(r.y, grid.size.height)..@min(r.y + r.size.height, grid.size.height)) |y| { 2609 for (@min(r.x, grid.size.width)..@min(r.x + r.size.width, grid.size.width)) |x| { 2610 const owner = &owners[y * grid.size.width + x]; 2611 if (owner.* == null) owner.* = entry.key_ptr.*; 2612 } 2613 } 2614 } 2615 } 2616 2617 // the cells are the volatile part of a panel. js replaces this one subtree 2618 // wholesale while retaining the panel's native controls and scroll shells. 2619 try output.appendSlice(allocator, "<div class=\"grid-cells\">"); 2620 2621 // emit this panel's grid as rows of text, coalescing adjacent cells that 2622 // share a focus id and style into one tag (a clickable span, a link, or a 2623 // plain styled span). cells under a child scroll keep only their background. 2624 // a cell's own link is an anchor nested in that tag. 2625 for (0..grid.size.height) |y| { 2626 var cur_id: ?usize = null; 2627 var cur_style: Grid.Style = .{}; 2628 var open_tag: ?CellTag = null; 2629 var open_link: ?[]const u8 = null; 2630 var first = true; 2631 for (0..grid.size.width) |x| { 2632 const cell = (try grid.cell(x, y)).*; 2633 // a cell covered by a child scroll's viewport is drawn by that scroll's 2634 // own div, so blank its glyph and make it non-clickable here — but keep 2635 // its background, so the backdrop still shows through the scroll's 2636 // transparent div instead of a bare hole. 2637 const covered_by_scroll = blk: { 2638 for (direct.items) |id| { 2639 const r = (focus.children.get(id) orelse continue).rect; 2640 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; 2641 } 2642 break :blk false; 2643 }; 2644 // the focusable owning the cell at (x, y); none for a covered cell. 2645 const cell_id = if (covered_by_scroll) null else owners[y * grid.size.width + x]; 2646 const style: Grid.Style = if (covered_by_scroll) .{ .bg = cell.style.bg } else cell.style; 2647 2648 if (first or cell_id != cur_id or !style.eql(cur_style)) { 2649 if (open_link != null) try output.appendSlice(allocator, "</a>"); 2650 open_link = null; 2651 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2652 2653 var new_tag: ?CellTag = null; 2654 if (cell_id) |id| { 2655 if (focus.children.get(id)) |child| { 2656 new_tag = switch (child.focus.kind) { 2657 .custom => |custom| CellTag.init(custom), 2658 else => .span, 2659 }; 2660 } 2661 } 2662 if (new_tag == null and !style.eql(.{})) new_tag = .plain; 2663 2664 if (new_tag) |t| { 2665 var style_buf: [192]u8 = undefined; 2666 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, style)); 2667 } 2668 2669 open_tag = new_tag; 2670 cur_id = cell_id; 2671 cur_style = style; 2672 first = false; 2673 } 2674 2675 // an anchor can't nest in another, so a link tag's cells skip theirs 2676 const in_anchor = if (open_tag) |t| t == .a else false; 2677 const link = if (covered_by_scroll or in_anchor) null else webLink(cell.link); 2678 if (!sameLink(link, open_link)) { 2679 if (open_link != null) try output.appendSlice(allocator, "</a>"); 2680 if (link) |url| { 2681 // a page path opens in this tab, any other url in a new one 2682 try output.appendSlice(allocator, if (url[0] == '/') 2683 "<a class=\"cell-link\" tabindex=\"-1\" href=\"" 2684 else 2685 "<a class=\"cell-link\" tabindex=\"-1\" target=\"_blank\" rel=\"noopener noreferrer\" href=\""); 2686 try appendEscapedHtml(allocator, output, url); 2687 try output.appendSlice(allocator, "\">"); 2688 } 2689 open_link = link; 2690 } 2691 2692 if (covered_by_scroll) { 2693 try appendEscapedHtml(allocator, output, " "); 2694 } else if (cell.continuation) { 2695 // the wide rune to the left was emitted 2ch wide, covering this column 2696 } else if (cell.rune) |rune| { 2697 var encoded: [4]u8 = undefined; 2698 const encoded_len = try std.unicode.utf8Encode(rune, &encoded); 2699 const rune_text = encoded[0..encoded_len]; 2700 // a double-width rune is pinned inside a 2ch span so the 2701 // fallback glyph's advance width can't shift the rest of the row 2702 const wide = x + 1 < grid.size.width and (try grid.cell(x + 1, y)).continuation; 2703 if (wide) { 2704 try output.appendSlice(allocator, "<span class=\"w2\">"); 2705 try appendEscapedHtml(allocator, output, rune_text); 2706 try output.appendSlice(allocator, "</span>"); 2707 } else { 2708 try appendEscapedHtml(allocator, output, rune_text); 2709 } 2710 } else { 2711 try appendEscapedHtml(allocator, output, " "); 2712 } 2713 } 2714 if (open_link != null) try output.appendSlice(allocator, "</a>"); 2715 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2716 try output.append(allocator, '\n'); 2717 } 2718 try output.appendSlice(allocator, "</div>"); 2719 2720 // native controls live in their panel, beside the replaceable cells. their 2721 // stable keys let JS update layout without recreating their DOM nodes, and 2722 // being actual descendants of a scroll gives them native movement/clipping. 2723 try renderPanelControls(allocator, output, focus, session, root_focus, &excluded); 2724 2725 // each child scroll becomes a natively-scrollable div positioned over its 2726 // viewport, holding its full content rendered recursively. 2727 for (direct.items) |id| { 2728 const child = focus.children.get(id) orelse continue; 2729 const info = child.focus.scroll orelse continue; 2730 const r = child.rect; 2731 // overflow only on the axes the widget scrolls; `auto` shows a bar only 2732 // when that axis actually overflows. the other axis is clipped (hidden), 2733 // matching how the terminal Scroll handles its non-scrolling axis. 2734 const overflow = switch (info.direction) { 2735 .vert => "overflow-x:hidden;overflow-y:auto", 2736 .horiz => "overflow-x:auto;overflow-y:hidden", 2737 .both => "overflow:auto", 2738 }; 2739 // the id carries a content version so JS preserves the native scroll 2740 // position across re-renders of the same content but resets it when the 2741 // content is replaced — e.g. selecting a different commit. the widget's 2742 // scroll offset (in cells) rides along so JS can apply it when it has no 2743 // preserved position, letting a wasm-side scrollToRect (the files list 2744 // scrolling to its selected row on page load) reach the browser. 2745 var buf: [256]u8 = undefined; 2746 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 })); 2747 try renderPanel(allocator, output, child.focus, info.content, session, root_focus); 2748 try output.appendSlice(allocator, "</div>"); 2749 } 2750 } 2751 2752 const form_prefix = "form:"; 2753 const form_id_prefix = "haxy-form-"; 2754 2755 fn formAction(focus: *const Focus) ?[]const u8 { 2756 return switch (focus.kind) { 2757 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) custom[form_prefix.len..] else null, 2758 else => null, 2759 }; 2760 } 2761 2762 // find the form ancestor of a flattened focus-tree child. html's `form` 2763 // attribute then associates the control with that form without requiring the 2764 // form and control to share a DOM parent. 2765 fn formOwner(root_focus: *Focus, focus_id: usize) ?usize { 2766 var id = focus_id; 2767 while (root_focus.children.get(id)) |child| { 2768 const parent_id = child.parent_id; 2769 if (parent_id == root_focus.id) return if (formAction(root_focus) != null) root_focus.id else null; 2770 const parent = root_focus.children.get(parent_id) orelse return null; 2771 if (formAction(parent.focus) != null) return parent_id; 2772 id = parent_id; 2773 } 2774 return null; 2775 } 2776 2777 fn appendFormAttribute(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus, focus_id: usize) !void { 2778 const form_id = formOwner(root_focus, focus_id) orelse return; 2779 var buf: [64]u8 = undefined; 2780 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, " form=\"" ++ form_id_prefix ++ "{d}\"", .{form_id})); 2781 } 2782 2783 fn renderPanelControls( 2784 allocator: std.mem.Allocator, 2785 output: *std.ArrayList(u8), 2786 focus: *Focus, 2787 session: *ui.Session, 2788 root_focus: *Focus, 2789 excluded: *const std.AutoHashMapUnmanaged(usize, void), 2790 ) !void { 2791 var iter = focus.children.iterator(); 2792 while (iter.next()) |entry| { 2793 const id = entry.key_ptr.*; 2794 if (excluded.contains(id)) continue; 2795 const child = entry.value_ptr.*; 2796 const r = child.rect; 2797 2798 if (r.size.width == 0 or r.size.height == 0) continue; // not laid out, rather than merely off-screen 2799 2800 switch (child.focus.kind) { 2801 .text_input, .text_input_password, .text_area => { 2802 const ti = session.text_inputs.get(id) orelse continue; 2803 2804 const inner_left = r.x + 1; 2805 const inner_top = r.y + 1; 2806 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 2807 const preserve = !ti.options.read_only; 2808 2809 if (child.focus.kind == .text_area) { 2810 const value = try ti.text(allocator); 2811 defer allocator.free(value); 2812 var id_buf: [128]u8 = undefined; 2813 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<textarea data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2814 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2815 try appendFormAttribute(allocator, output, root_focus, id); 2816 if (ti.options.name.len > 0) { 2817 try output.appendSlice(allocator, " name=\""); 2818 try appendEscapedHtml(allocator, output, ti.options.name); 2819 try output.append(allocator, '"'); 2820 } 2821 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 2822 var pos_buf: [128]u8 = undefined; 2823 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 })); 2824 try appendEscapedHtml(allocator, output, value); 2825 try output.appendSlice(allocator, "</textarea>"); 2826 continue; 2827 } 2828 2829 var id_buf: [160]u8 = undefined; 2830 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 })); 2831 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2832 try appendFormAttribute(allocator, output, root_focus, id); 2833 if (ti.options.name.len > 0) { 2834 try output.appendSlice(allocator, " name=\""); 2835 try appendEscapedHtml(allocator, output, ti.options.name); 2836 try output.append(allocator, '"'); 2837 } 2838 if (child.focus.kind != .text_input_password) { 2839 const value = try ti.text(allocator); 2840 defer allocator.free(value); 2841 try output.appendSlice(allocator, " value=\""); 2842 try appendEscapedHtml(allocator, output, value); 2843 try output.append(allocator, '"'); 2844 } 2845 var pos_buf: [96]u8 = undefined; 2846 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 })); 2847 }, 2848 .custom => |custom| { 2849 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2850 if (formOwner(root_focus, id) == null) continue; 2851 var id_buf: [128]u8 = undefined; 2852 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2853 try appendFormAttribute(allocator, output, root_focus, id); 2854 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2855 try output.appendSlice(allocator, " formaction=\""); 2856 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 2857 try output.append(allocator, '"'); 2858 } 2859 var pos_buf: [128]u8 = undefined; 2860 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 })); 2861 } else if (std.mem.startsWith(u8, custom, ui.radio_prefix)) { 2862 // an invisible native radio over the option, checked when the option is its row's selection 2863 const field = custom[ui.radio_prefix.len..]; 2864 const separator = std.mem.indexOfScalar(u8, field, '=') orelse continue; 2865 const row = root_focus.children.get(child.parent_id) orelse continue; 2866 var id_buf: [128]u8 = undefined; 2867 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<input type=\"radio\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2868 try appendFormAttribute(allocator, output, root_focus, id); 2869 try output.appendSlice(allocator, " name=\""); 2870 try appendEscapedHtml(allocator, output, field[0..separator]); 2871 try output.appendSlice(allocator, "\" value=\""); 2872 try appendEscapedHtml(allocator, output, field[separator + 1 ..]); 2873 try output.append(allocator, '"'); 2874 if (row.focus.child_id == id) try output.appendSlice(allocator, " checked"); 2875 var pos_buf: [128]u8 = undefined; 2876 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"opacity:0;left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">", .{ r.x, r.y, r.size.width, r.size.height })); 2877 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 2878 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 2879 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 2880 var id_buf: [128]u8 = undefined; 2881 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 })); 2882 } 2883 }, 2884 else => {}, 2885 } 2886 } 2887 } 2888 2889 // emit hidden form owners beside the rendered panels. their controls point 2890 // back here with the standard HTML `form` attribute. 2891 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 2892 // the focus child map preserves insertion order, which matches the order 2893 // widgets were added in code 2894 var iter = root_focus.children.iterator(); 2895 while (iter.next()) |entry| { 2896 const child = entry.value_ptr.*; 2897 const action_url = formAction(child.focus) orelse continue; 2898 2899 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 2900 var id_buf: [96]u8 = undefined; 2901 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 2902 try appendEscapedHtml(allocator, output, action_url); 2903 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 2904 } 2905 } 2906 2907 // the 16 ansi colors as the browser shows them (xterm's defaults) 2908 const ansi_palette = [16]Grid.Color.Rgb{ 2909 .{ .r = 0x00, .g = 0x00, .b = 0x00 }, .{ .r = 0xcd, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xcd, .b = 0x00 }, .{ .r = 0xcd, .g = 0xcd, .b = 0x00 }, 2910 .{ .r = 0x00, .g = 0x00, .b = 0xee }, .{ .r = 0xcd, .g = 0x00, .b = 0xcd }, .{ .r = 0x00, .g = 0xcd, .b = 0xcd }, .{ .r = 0xe5, .g = 0xe5, .b = 0xe5 }, 2911 .{ .r = 0x7f, .g = 0x7f, .b = 0x7f }, .{ .r = 0xff, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xff, .b = 0x00 }, .{ .r = 0xff, .g = 0xff, .b = 0x00 }, 2912 .{ .r = 0x5c, .g = 0x5c, .b = 0xff }, .{ .r = 0xff, .g = 0x00, .b = 0xff }, .{ .r = 0x00, .g = 0xff, .b = 0xff }, .{ .r = 0xff, .g = 0xff, .b = 0xff }, 2913 }; 2914 2915 // resolve any color to rgb: palette colors through the ansi table and the 2916 // xterm 256-color layout (16 ansi, a 6x6x6 cube, then 24 grays) 2917 fn colorRgb(color: Grid.Color) Grid.Color.Rgb { 2918 return switch (color) { 2919 .rgb => |c| c, 2920 .ansi => |a| ansi_palette[@backingInt(a)], 2921 .indexed => |n| if (n < 16) 2922 ansi_palette[n] 2923 else if (n < 232) blk: { 2924 const levels = [6]u8{ 0, 0x5f, 0x87, 0xaf, 0xd7, 0xff }; 2925 const i = n - 16; 2926 break :blk .{ .r = levels[i / 36], .g = levels[(i / 6) % 6], .b = levels[i % 6] }; 2927 } else blk: { 2928 const v: u8 = 8 + (n - 232) * 10; 2929 break :blk .{ .r = v, .g = v, .b = v }; 2930 }, 2931 }; 2932 } 2933 2934 // builds an HTML ` style="color:…;background-color:…"` attribute from a 2935 // cell's style into `buf`, omitting whichever color is unset. an inverted 2936 // cell swaps the two, falling back to the page's --fg/--bg variables for 2937 // whichever side is unset. text attributes follow the colors. returns an 2938 // empty slice when nothing is set. 2939 fn styleAttr(buf: []u8, style: Grid.Style) []const u8 { 2940 if (style.eql(.{})) return buf[0..0]; 2941 const prefix = " style=\""; 2942 @memcpy(buf[0..prefix.len], prefix); 2943 var i: usize = prefix.len; 2944 const inverted = style.inverted; 2945 i = cssColor(buf, i, "color", if (inverted) style.bg else style.fg, if (inverted) "var(--bg)" else null) orelse return buf[0..0]; 2946 i = cssColor(buf, i, "background-color", if (inverted) style.fg else style.bg, if (inverted) "var(--fg)" else null) orelse return buf[0..0]; 2947 const decoration: []const u8 = if (style.underline and style.strikethrough) 2948 "text-decoration:underline line-through;" 2949 else if (style.underline) 2950 "text-decoration:underline;" 2951 else if (style.strikethrough) 2952 "text-decoration:line-through;" 2953 else 2954 ""; 2955 const attributes = std.fmt.bufPrint(buf[i..], "{s}{s}{s}{s}", .{ 2956 if (style.bold) "font-weight:bold;" else "", 2957 if (style.italic) "font-style:italic;" else "", 2958 decoration, 2959 if (style.dim) "opacity:.6;" else "", 2960 }) catch return buf[0..0]; 2961 i += attributes.len; 2962 if (i >= buf.len) return buf[0..0]; 2963 buf[i] = '"'; 2964 return buf[0 .. i + 1]; 2965 } 2966 2967 // append `prop:value;` at buf[i..] for the color, or for the fallback when 2968 // the color is unset (nothing when both are). returns the new end, or null 2969 // when it doesn't fit. 2970 fn cssColor(buf: []u8, i: usize, prop: []const u8, color: ?Grid.Color, fallback: ?[]const u8) ?usize { 2971 const s = if (color) |c| blk: { 2972 const v = colorRgb(c); 2973 break :blk std.fmt.bufPrint(buf[i..], "{s}:#{x:0>2}{x:0>2}{x:0>2};", .{ prop, v.r, v.g, v.b }) catch return null; 2974 } else if (fallback) |f| 2975 std.fmt.bufPrint(buf[i..], "{s}:{s};", .{ prop, f }) catch return null 2976 else 2977 return i; 2978 return i + s.len; 2979 } 2980 2981 // a cell's link as an href, when it's a page path or a web or mail url 2982 fn webLink(link: ?[]const u8) ?[]const u8 { 2983 const url = link orelse return null; 2984 // a page path, not a protocol-relative url 2985 if (url.len > 1 and url[0] == '/' and url[1] != '/') return url; 2986 for ([_][]const u8{ "http://", "https://", "mailto:" }) |scheme| { 2987 if (std.ascii.startsWithIgnoreCase(url, scheme)) return url; 2988 } 2989 return null; 2990 } 2991 2992 fn sameLink(a: ?[]const u8, b: ?[]const u8) bool { 2993 if (a) |x| return if (b) |y| std.mem.eql(u8, x, y) else false; 2994 return b == null; 2995 } 2996 2997 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2998 for (input) |ch| { 2999 switch (ch) { 3000 '&' => try out.appendSlice(allocator, "&amp;"), 3001 '<' => try out.appendSlice(allocator, "&lt;"), 3002 '>' => try out.appendSlice(allocator, "&gt;"), 3003 '"' => try out.appendSlice(allocator, "&quot;"), 3004 '\'' => try out.appendSlice(allocator, "&#39;"), 3005 else => try out.append(allocator, ch), 3006 } 3007 } 3008 } 3009 3010 // --- helpers -------------------------------------------------------------- 3011 3012 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 3013 var iter = request.iterateHeaders(); 3014 while (iter.next()) |header| { 3015 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 3016 var pairs = std.mem.splitScalar(u8, header.value, ';'); 3017 while (pairs.next()) |pair| { 3018 const trimmed = std.mem.trim(u8, pair, " \t"); 3019 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 3020 if (std.mem.eql(u8, trimmed[0..eq], name)) { 3021 return trimmed[eq + 1 ..]; 3022 } 3023 } 3024 } 3025 return null; 3026 } 3027 3028 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 3029 var iter = std.mem.splitScalar(u8, body, '&'); 3030 while (iter.next()) |pair| { 3031 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 3032 if (std.mem.eql(u8, pair[0..eq], key)) { 3033 return try decodeFormValue(allocator, pair[eq + 1 ..]); 3034 } 3035 } 3036 return null; 3037 } 3038 3039 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 3040 var buffer: [256]u8 = undefined; 3041 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 3042 } 3043 3044 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 3045 var out: std.ArrayList(u8) = .empty; 3046 errdefer out.deinit(allocator); 3047 var i: usize = 0; 3048 while (i < encoded.len) : (i += 1) { 3049 switch (encoded[i]) { 3050 '+' => try out.append(allocator, ' '), 3051 '%' => { 3052 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 3053 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 3054 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 3055 try out.append(allocator, hi * 16 + lo); 3056 i += 2; 3057 }, 3058 else => try out.append(allocator, encoded[i]), 3059 } 3060 } 3061 return try out.toOwnedSlice(allocator); 3062 } 3063 3064 // disk-backed web session store. each login mints a random, opaque token 3065 // (not the user's id) that is stored as a file named by the token hex, whose 3066 // contents are the raw user_id bytes. authenticating a request is a lookup of 3067 // the cookie's token; logout deletes the file, revoking the session. there is 3068 // deliberately no expiry — a session lives until logout. form failures use 3069 // files in the flash subdirectory that the redirected GET consumes. the 3070 // directory is cleared whenever the server starts. 3071 pub const SessionStore = struct { 3072 io: std.Io, 3073 dir: std.Io.Dir, 3074 flash_dir: std.Io.Dir, 3075 auto_login: ?[token_hex_len]u8, 3076 3077 pub const token_hex_len = evt.event_id_size * 2; 3078 3079 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 3080 try data_dir.createDirPath(io, "sessions"); 3081 const dir = try data_dir.openDir(io, "sessions", .{}); 3082 errdefer dir.close(io); 3083 try dir.deleteTree(io, "flash"); 3084 try dir.createDirPath(io, "flash"); 3085 const flash_dir = try dir.openDir(io, "flash", .{}); 3086 errdefer flash_dir.close(io); 3087 const auto_login = blk: { 3088 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 3089 defer file.close(io); 3090 var token: [token_hex_len]u8 = undefined; 3091 var storage: [token_hex_len]u8 = undefined; 3092 var reader = file.reader(io, &storage); 3093 reader.interface.readSliceAll(&token) catch break :blk null; 3094 break :blk token; 3095 }; 3096 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 3097 } 3098 3099 pub fn deinit(self: SessionStore) void { 3100 self.flash_dir.close(self.io); 3101 self.dir.close(self.io); 3102 } 3103 3104 // mint a new session for user_id, returning the token hex to set as the 3105 // cookie value. 3106 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 3107 var token: [evt.event_id_size]u8 = undefined; 3108 self.io.random(&token); 3109 const token_hex = std.fmt.bytesToHex(token, .lower); 3110 const file = try self.dir.createFile(self.io, &token_hex, .{}); 3111 defer file.close(self.io); 3112 try file.writeStreamingAll(self.io, user_id); 3113 return token_hex; 3114 } 3115 3116 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 3117 var token: [evt.event_id_size]u8 = undefined; 3118 self.io.random(&token); 3119 const token_hex = std.fmt.bytesToHex(token, .lower); 3120 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 3121 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 3122 defer file.close(self.io); 3123 3124 var json: std.Io.Writer.Allocating = .init(allocator); 3125 defer json.deinit(); 3126 try std.json.Stringify.value(value, .{}, &json.writer); 3127 try file.writeStreamingAll(self.io, json.written()); 3128 return token_hex; 3129 } 3130 3131 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 3132 if (!isToken(token_hex)) return null; 3133 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 3134 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 3135 defer file.close(self.io); 3136 3137 var storage: [4096]u8 = undefined; 3138 var reader = file.reader(self.io, &storage); 3139 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 3140 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 3141 } 3142 3143 // resolve a cookie's token to its user_id. returns false (logged out) for a 3144 // missing, malformed, or unknown token. 3145 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 3146 if (!isToken(token_hex)) return false; 3147 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 3148 defer file.close(self.io); 3149 var storage: [evt.event_id_size]u8 = undefined; 3150 var file_reader = file.reader(self.io, &storage); 3151 file_reader.interface.readSliceAll(out) catch return false; 3152 return true; 3153 } 3154 3155 // revoke a session. a no-op for a missing or malformed token. 3156 pub fn remove(self: SessionStore, token_hex: []const u8) void { 3157 if (!isToken(token_hex)) return; 3158 self.dir.deleteFile(self.io, token_hex) catch {}; 3159 } 3160 3161 // leave `token_hex`'s session for visitors arriving without one. only the 3162 // `try` fixture writes one. the name can't collide with a session token. 3163 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 3164 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 3165 defer file.close(self.io); 3166 try file.writeStreamingAll(self.io, token_hex); 3167 } 3168 3169 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 3170 out.* = self.auto_login orelse return false; 3171 return true; 3172 } 3173 3174 const auto_login_name = "auto-login"; 3175 3176 // a token is exactly token_hex_len hex chars. validating before using the 3177 // value as a path keeps attacker-supplied cookies from escaping the 3178 // sessions dir (e.g. via "/" or ".." bytes). 3179 fn isToken(token_hex: []const u8) bool { 3180 if (token_hex.len != token_hex_len) return false; 3181 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 3182 return true; 3183 } 3184 }; 3185