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