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