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