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