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