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