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