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