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