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