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