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