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