╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1156 description: []const u8, 1157 author: evt.CommitAuthor, 1158 ) !void { 1159 const request_repo = (try requestRepoSource(io, allocator, host, repo_base)) orelse return error.NotFound; 1160 defer request_repo.deinit(allocator); 1161 const source = request_repo.source; 1162 switch (source.repo_kind) { 1163 inline else => |repo_kind| { 1164 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1165 defer any_repo.deinit(io, allocator); 1166 switch (any_repo) { 1167 inline else => |*repo| try evt.Discussion.update(repo_kind, repo.self_repo_opts, io, allocator, repo, id, title, tags, description, author), 1168 } 1169 }, 1170 } 1171 } 1172 1173 // set the status of the issue the url names (base is 1174 // "/repo/<owner>/<name>/issue:<id>", identity elided in local mode) by 1175 // re-emitting its event, then redirect back to it 1176 fn handleThreadStatus( 1177 io: std.Io, 1178 request: *std.http.Server.Request, 1179 allocator: std.mem.Allocator, 1180 base: []const u8, 1181 host: Host, 1182 open: bool, 1183 ) !void { 1184 const not_found = "thread not found"; 1185 const parts = commentBaseParts(base) orelse { 1186 try request.respond(not_found, .{ 1187 .status = .not_found, 1188 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1189 }); 1190 return; 1191 }; 1192 1193 var author_arena = std.heap.ArenaAllocator.init(allocator); 1194 defer author_arena.deinit(); 1195 const author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 1196 1197 (switch (parts.thread_kind) { 1198 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .status = if (open) .open else .closed }, author), 1199 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .status = if (open) .open else .closed }, author), 1200 else => return respondRemoveNotFound(request), 1201 }) catch |err| switch (err) { 1202 error.NotFound => { 1203 try request.respond(not_found, .{ 1204 .status = .not_found, 1205 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1206 }); 1207 return; 1208 }, 1209 else => |e| return e, 1210 }; 1211 1212 // like logout, this is a bodyless POST, so close the connection rather than 1213 // letting the keep-alive path try to discard a body that isn't framed. 1214 try request.respond("", .{ 1215 .status = .see_other, 1216 .keep_alive = false, 1217 .extra_headers = &.{.{ .name = "location", .value = base }}, 1218 }); 1219 } 1220 1221 // replace the title, tags and description of an issue or discussion. 1222 fn handleTopicEdit( 1223 io: std.Io, 1224 request: *std.http.Server.Request, 1225 allocator: std.mem.Allocator, 1226 base: []const u8, 1227 host: Host, 1228 parts: CommentBaseParts, 1229 ) !void { 1230 var author_arena = std.heap.ArenaAllocator.init(allocator); 1231 defer author_arena.deinit(); 1232 const author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 1233 1234 const body = try readFormBody(request, allocator); 1235 defer allocator.free(body); 1236 1237 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 1238 defer allocator.free(title); 1239 const tags = (try parseFormField(allocator, body, "tags")) orelse try allocator.dupe(u8, ""); 1240 defer allocator.free(tags); 1241 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 1242 defer allocator.free(description_crlf); 1243 // form submission normalizes textarea line breaks to CRLF; store plain 1244 // newlines so the text renders the same on every host 1245 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 1246 defer allocator.free(description); 1247 1248 // invalid fields send the user back to the edit form 1249 const valid = switch (parts.thread_kind) { 1250 .issue => evt.Issue.fieldsValid(title, tags), 1251 .patch => evt.Patch.fieldsValid(title, tags), 1252 .discuss => evt.Discussion.fieldsValid(title, tags), 1253 else => unreachable, 1254 }; 1255 if (!valid) { 1256 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1257 defer allocator.free(form_location); 1258 try request.respond("", .{ 1259 .status = .see_other, 1260 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1261 }); 1262 return; 1263 } 1264 1265 const not_found = switch (parts.thread_kind) { 1266 .issue => "issue not found", 1267 .patch => "patch not found", 1268 .discuss => "discussion not found", 1269 else => unreachable, 1270 }; 1271 (switch (parts.thread_kind) { 1272 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 1273 .title = title, 1274 .tags = tags, 1275 .description = description, 1276 } }, author), 1277 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 1278 .title = title, 1279 .tags = tags, 1280 .description = description, 1281 } }, author), 1282 .discuss => updateDiscussion(io, allocator, host, parts.repo_base, &parts.thread_id, title, tags, description, author), 1283 else => unreachable, 1284 }) catch |err| switch (err) { 1285 error.NotFound => { 1286 try request.respond(not_found, .{ 1287 .status = .not_found, 1288 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1289 }); 1290 return; 1291 }, 1292 else => |e| return e, 1293 }; 1294 1295 try request.respond("", .{ 1296 .status = .see_other, 1297 .extra_headers = &.{.{ .name = "location", .value = base }}, 1298 }); 1299 } 1300 1301 // resolve every conflicted field of the thread the url names 1302 fn handleThreadResolve( 1303 io: std.Io, 1304 request: *std.http.Server.Request, 1305 allocator: std.mem.Allocator, 1306 base: []const u8, 1307 host: Host, 1308 ) !void { 1309 var author_arena = std.heap.ArenaAllocator.init(allocator); 1310 defer author_arena.deinit(); 1311 const author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 1312 1313 const body = try readFormBody(request, allocator); 1314 defer allocator.free(body); 1315 1316 var field_arena = std.heap.ArenaAllocator.init(allocator); 1317 defer field_arena.deinit(); 1318 const aa = field_arena.allocator(); 1319 const title = try parseFormField(aa, body, "title"); 1320 const tags = try parseFormField(aa, body, "tags"); 1321 1322 // the hunk inputs post as d0, d1, ...; form submission normalizes their 1323 // textarea line breaks to CRLF 1324 var hunks: std.ArrayList([]const u8) = .empty; 1325 var hunk_index: usize = 0; 1326 while (true) : (hunk_index += 1) { 1327 const name = try std.fmt.allocPrint(aa, "d{d}", .{hunk_index}); 1328 const posted = (try parseFormField(aa, body, name)) orelse break; 1329 try hunks.append(aa, try std.mem.replaceOwned(u8, aa, posted, "\r\n", "\n")); 1330 } 1331 1332 const parts = commentBaseParts(base) orelse { 1333 try request.respond("thread not found", .{ 1334 .status = .not_found, 1335 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1336 }); 1337 return; 1338 }; 1339 if (parts.comment_id != null or (parts.thread_kind != .issue and parts.thread_kind != .patch)) { 1340 try request.respond("thread not found", .{ 1341 .status = .not_found, 1342 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1343 }); 1344 return; 1345 } 1346 const route = ui.RoutablePage.fromUrl(base) orelse ui.RoutablePage.fromUrlLocal(base) orelse { 1347 try request.respond("thread not found", .{ 1348 .status = .not_found, 1349 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1350 }); 1351 return; 1352 }; 1353 const theirs: []const u8 = switch (route) { 1354 .repo_patches => |*patch| patch.theirs.slice(), 1355 .repo_issues => "", 1356 else => unreachable, 1357 }; 1358 const not_found = if (parts.thread_kind == .patch) "patch not found" else "issue not found"; 1359 1360 (switch (parts.thread_kind) { 1361 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 1362 .title = title, 1363 .tags = tags, 1364 .hunks = hunks.items, 1365 } }, author), 1366 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 1367 .title = title, 1368 .tags = tags, 1369 .hunks = hunks.items, 1370 .theirs = theirs, 1371 } }, author), 1372 else => unreachable, 1373 }) catch |err| switch (err) { 1374 error.NotFound => { 1375 try request.respond(not_found, .{ 1376 .status = .not_found, 1377 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1378 }); 1379 return; 1380 }, 1381 // invalid fields send the user back to the resolve form 1382 error.InvalidFields => { 1383 const form_location = try std.fmt.allocPrint(allocator, "{s}/resolve", .{base}); 1384 defer allocator.free(form_location); 1385 try request.respond("", .{ 1386 .status = .see_other, 1387 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1388 }); 1389 return; 1390 }, 1391 else => |e| return e, 1392 }; 1393 1394 try request.respond("", .{ 1395 .status = .see_other, 1396 .extra_headers = &.{.{ .name = "location", .value = base }}, 1397 }); 1398 } 1399 1400 fn handleSync( 1401 io: std.Io, 1402 request: *std.http.Server.Request, 1403 allocator: std.mem.Allocator, 1404 base: []const u8, 1405 source: ui.RepoSource, 1406 ) !void { 1407 if (base.len != 0) { 1408 try request.respond("not found", .{ 1409 .status = .not_found, 1410 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1411 }); 1412 return; 1413 } 1414 1415 var owned_failure: ?[]u8 = null; 1416 defer if (owned_failure) |message| allocator.free(message); 1417 const failure: ?[]const u8 = blk: { 1418 owned_failure = ui.Repo.Events.sync(io, allocator, source) catch |err| break :blk @errorName(err); 1419 break :blk owned_failure; 1420 }; 1421 if (failure) |message| { 1422 var encoded: std.Io.Writer.Allocating = .init(allocator); 1423 defer encoded.deinit(); 1424 try std.Uri.Component.percentEncode(&encoded.writer, message, struct { 1425 fn isUnreserved(c: u8) bool { 1426 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 1427 } 1428 }.isUnreserved); 1429 const cookie = try std.fmt.allocPrint( 1430 allocator, 1431 sync_failure_cookie ++ "={s}; Path=/; HttpOnly; SameSite=Strict", 1432 .{encoded.written()}, 1433 ); 1434 defer allocator.free(cookie); 1435 try request.respond("", .{ 1436 .status = .see_other, 1437 .extra_headers = &.{ 1438 .{ .name = "location", .value = "/events" }, 1439 .{ .name = "set-cookie", .value = cookie }, 1440 }, 1441 }); 1442 return; 1443 } 1444 1445 try request.respond("", .{ 1446 .status = .see_other, 1447 .extra_headers = &.{ 1448 .{ .name = "location", .value = "/events" }, 1449 .{ .name = "set-cookie", .value = sync_failure_cookie ++ "=; Path=/; Max-Age=0" }, 1450 }, 1451 }); 1452 } 1453 1454 fn renderIndexHtml( 1455 io: std.Io, 1456 allocator: std.mem.Allocator, 1457 host: Host, 1458 session_data: ui.Session.Data, 1459 ) ![]const u8 { 1460 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 1461 1462 var page_arena = std.heap.ArenaAllocator.init(allocator); 1463 defer page_arena.deinit(); 1464 1465 // the remote admin repo must outlive the page build, since the session's 1466 // moment reads from it. 1467 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 1468 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 1469 1470 var session = switch (host) { 1471 .remote => |remote| blk: { 1472 // open the admin repo to read live user/repo data. 1473 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 1474 const repo = if (repo_maybe) |*repo| repo else unreachable; 1475 var session = try ui.Session.init(&page_arena, repo, session_data); 1476 // give the page builders filesystem access to the on-disk repos (a 1477 // sibling "repos" dir next to the admin repo) so the Repo page can 1478 // read its files. 1479 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 1480 break :blk session; 1481 }, 1482 .local => |local| ui.Session{ 1483 .data = session_data, 1484 .arena = &page_arena, 1485 .page_arena = &page_arena, 1486 .local = local, 1487 }, 1488 }; 1489 session.io = io; 1490 1491 var page = try ui.Page.init(session.page_arena, &session, session.data.current_page); 1492 var root = try ui.initRoot(allocator, &page, &session); 1493 defer root.deinit(allocator); 1494 1495 const snapshot: ui.Snapshot = .{ .page = page, .session = session.data }; 1496 1497 const content = try generateHtml(allocator, &root); 1498 defer allocator.free(content); 1499 const overlay = try generateOverlay(allocator, &root, &session); 1500 defer allocator.free(overlay); 1501 1502 // serialize the snapshot so the wasm side can parse it back without making 1503 // a second request. it's embedded raw in a <script type="application/json"> 1504 // block, whose content is raw text terminated only by "</script". in json, 1505 // '<' appears solely inside string values, so escaping every '<' (and '>' 1506 // for good measure) to its \uXXXX form yields equivalent json that can't 1507 // break out of the tag. 1508 var json: std.Io.Writer.Allocating = .init(allocator); 1509 defer json.deinit(); 1510 try std.json.Stringify.value(snapshot, .{}, &json.writer); 1511 1512 var json_escaped: std.ArrayList(u8) = .empty; 1513 defer json_escaped.deinit(allocator); 1514 for (json.written()) |c| switch (c) { 1515 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 1516 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 1517 else => try json_escaped.append(allocator, c), 1518 }; 1519 1520 var out: std.ArrayList(u8) = .empty; 1521 errdefer out.deinit(allocator); 1522 { 1523 var cursor: usize = 0; 1524 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 1525 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 1526 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 1527 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 1528 }) |sub| { 1529 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 1530 try out.appendSlice(allocator, template[cursor..idx]); 1531 try out.appendSlice(allocator, sub.replacement); 1532 cursor = idx + sub.needle.len; 1533 } 1534 try out.appendSlice(allocator, template[cursor..]); 1535 } 1536 return try out.toOwnedSlice(allocator); 1537 } 1538 1539 fn findEmbed(request_path: []const u8) ?Embed { 1540 const path = if (std.mem.eql(u8, request_path, "/")) 1541 "index.html" 1542 else if (request_path.len > 1 and request_path[0] == '/') 1543 request_path[1..] 1544 else 1545 return null; 1546 1547 for (embeds) |embed| { 1548 if (std.mem.eql(u8, path, embed.path)) return embed; 1549 } 1550 return null; 1551 } 1552 1553 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 1554 // own absolutely-positioned, natively-scrollable <div> holding its full content, 1555 // rendered recursively so nested scrolls work. 1556 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 1557 const grid = root.getGrid() orelse return error.MissingGrid; 1558 1559 var out: std.ArrayList(u8) = .empty; 1560 errdefer out.deinit(allocator); 1561 1562 try renderPanel(allocator, &out, root.getFocus(), grid); 1563 return try out.toOwnedSlice(allocator); 1564 } 1565 1566 // render one panel — a focus subtree and its content grid — as HTML, recursing 1567 // once per web-native Scroll inside it. the root panel is the whole page; each 1568 // Scroll becomes a nested, natively-scrollable div holding its full content. 1569 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 1570 // then the child scroll divs over those holes. 1571 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 1572 // `direct` is this panel's scroll children, each drawn as an overlaid div. 1573 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 1574 // plus their descendants, which the focus tree flattens into this panel's 1575 // children): the cell hit-test below skips them so this panel doesn't claim 1576 // cells that are really rendered inside a child scroll's own panel. 1577 // (scrolls aren't nested in practice, so every scroll child is direct here.) 1578 var direct: std.ArrayList(usize) = .empty; 1579 defer direct.deinit(allocator); 1580 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 1581 defer excluded.deinit(allocator); 1582 { 1583 var it = focus.children.iterator(); 1584 while (it.next()) |e| { 1585 if (e.value_ptr.focus.scroll == null) continue; 1586 try direct.append(allocator, e.key_ptr.*); 1587 try excluded.put(allocator, e.key_ptr.*, {}); 1588 var mit = e.value_ptr.focus.children.iterator(); 1589 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 1590 } 1591 } 1592 1593 // the HTML element a run of cells is wrapped in, chosen from the cell's 1594 // focusable kind 1595 const CellTag = union(enum) { 1596 span, // clickable focusable cell 1597 a: []const u8, // clickable focusable link 1598 plain, // non-focusable, colored 1599 1600 const a_prefix = "a:"; 1601 // an "in-page" anchor: rendered as a real <a href> so it works with js 1602 // disabled, but wasm handles it without navigating. 1603 fn init(str: []const u8) @This() { 1604 if (std.mem.startsWith(u8, str, ui.raw_link_prefix)) { 1605 return .{ .a = str[ui.raw_link_prefix.len..] }; 1606 } 1607 if (std.mem.startsWith(u8, str, ui.in_page_link_prefix)) { 1608 return .{ .a = str[ui.in_page_link_prefix.len..] }; 1609 } 1610 if (std.mem.startsWith(u8, str, a_prefix)) { 1611 return .{ .a = str[a_prefix.len..] }; 1612 } 1613 return .span; 1614 } 1615 1616 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 1617 var id_buf: [32]u8 = undefined; 1618 switch (self) { 1619 .span => { 1620 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 1621 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1622 try out.appendSlice(alloc, "\""); 1623 try out.appendSlice(alloc, style_attr); 1624 try out.appendSlice(alloc, ">"); 1625 }, 1626 .a => |href| { 1627 // tabindex=-1 keeps these out of the browser's tab order 1628 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 1629 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1630 try out.appendSlice(alloc, "\" href=\""); 1631 try appendEscapedHtml(alloc, out, href); 1632 try out.appendSlice(alloc, "\""); 1633 try out.appendSlice(alloc, style_attr); 1634 try out.appendSlice(alloc, ">"); 1635 }, 1636 .plain => { 1637 try out.appendSlice(alloc, "<span"); 1638 try out.appendSlice(alloc, style_attr); 1639 try out.appendSlice(alloc, ">"); 1640 }, 1641 } 1642 } 1643 1644 fn closeTag(self: @This()) []const u8 { 1645 return switch (self) { 1646 .span, .plain => "</span>", 1647 .a => "</a>", 1648 }; 1649 } 1650 }; 1651 1652 // emit this panel's grid as rows of text, coalescing adjacent cells that 1653 // share a focus id and colors into one tag (a clickable span, a link, or a 1654 // plain colored span). cells under a child scroll keep only their background. 1655 for (0..grid.size.height) |y| { 1656 var cur_id: ?usize = null; 1657 var cur_fg: ?Grid.Color = null; 1658 var cur_bg: ?Grid.Color = null; 1659 var open_tag: ?CellTag = null; 1660 var first = true; 1661 for (0..grid.size.width) |x| { 1662 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 1663 // a cell covered by a child scroll's viewport is drawn by that scroll's 1664 // own div, so blank its glyph and make it non-clickable here — but keep 1665 // its background, so the backdrop still shows through the scroll's 1666 // transparent div instead of a bare hole. 1667 const covered_by_scroll = blk: { 1668 for (direct.items) |id| { 1669 const r = (focus.children.get(id) orelse continue).rect; 1670 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; 1671 } 1672 break :blk false; 1673 }; 1674 // the focusable cell at (x, y) among this panel's own focusables (skipping 1675 // any that belong to a child scroll, whose cells are drawn in their own 1676 // panel); none for a covered cell. 1677 const cell_id = if (covered_by_scroll) null else blk: { 1678 var iter = focus.children.iterator(); 1679 while (iter.next()) |entry| { 1680 const child = entry.value_ptr.*; 1681 if (!child.focus.focusable) continue; 1682 if (excluded.contains(entry.key_ptr.*)) continue; 1683 const r = child.rect; 1684 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 1685 break :blk entry.key_ptr.*; 1686 } 1687 } 1688 break :blk null; 1689 }; 1690 const fg = if (covered_by_scroll) null else cell.style.fg; 1691 const bg = cell.style.bg; 1692 1693 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 1694 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1695 1696 var new_tag: ?CellTag = null; 1697 if (cell_id) |id| { 1698 if (focus.children.get(id)) |child| { 1699 new_tag = switch (child.focus.kind) { 1700 .custom => |custom| CellTag.init(custom), 1701 else => .span, 1702 }; 1703 } 1704 } 1705 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 1706 1707 if (new_tag) |t| { 1708 var style_buf: [64]u8 = undefined; 1709 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 1710 } 1711 1712 open_tag = new_tag; 1713 cur_id = cell_id; 1714 cur_fg = fg; 1715 cur_bg = bg; 1716 first = false; 1717 } 1718 1719 if (covered_by_scroll) { 1720 try appendEscapedHtml(allocator, output, " "); 1721 } else if (cell.continuation) { 1722 // the wide rune to the left was emitted 2ch wide, covering this column 1723 } else if (cell.rune) |rune| { 1724 // a double-width rune is pinned inside a 2ch span so the 1725 // fallback glyph's advance width can't shift the rest of the row 1726 const wide = x + 1 < grid.size.width and grid.cells.items[try grid.cells.at(.{ y, x + 1 })].continuation; 1727 if (wide) { 1728 try output.appendSlice(allocator, "<span class=\"w2\">"); 1729 try appendEscapedHtml(allocator, output, rune); 1730 try output.appendSlice(allocator, "</span>"); 1731 } else { 1732 try appendEscapedHtml(allocator, output, rune); 1733 } 1734 } else { 1735 try appendEscapedHtml(allocator, output, " "); 1736 } 1737 } 1738 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1739 try output.append(allocator, '\n'); 1740 } 1741 1742 // each child scroll becomes a natively-scrollable div positioned over its 1743 // viewport, holding its full content rendered recursively. 1744 for (direct.items) |id| { 1745 const child = focus.children.get(id) orelse continue; 1746 const info = child.focus.scroll orelse continue; 1747 const r = child.rect; 1748 // overflow only on the axes the widget scrolls; `auto` shows a bar only 1749 // when that axis actually overflows. the other axis is clipped (hidden), 1750 // matching how the terminal Scroll handles its non-scrolling axis. 1751 const overflow = switch (info.direction) { 1752 .vert => "overflow-x:hidden;overflow-y:auto", 1753 .horiz => "overflow-x:auto;overflow-y:hidden", 1754 .both => "overflow:auto", 1755 }; 1756 // the id carries a content version so JS preserves the native scroll 1757 // position across re-renders of the same content but resets it when the 1758 // content is replaced — e.g. selecting a different commit. the widget's 1759 // scroll offset (in cells) rides along so JS can apply it when it has no 1760 // preserved position, letting a wasm-side scrollToRect (the files list 1761 // scrolling to its selected row on page load) reach the browser. 1762 var buf: [256]u8 = undefined; 1763 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, "<div class=\"scroll\" 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, child.focus.version, @tagName(info.direction), info.offset_x, info.offset_y, r.x, r.y, r.size.width, r.size.height, overflow })); 1764 try renderPanel(allocator, output, child.focus, info.content); 1765 try output.appendSlice(allocator, "</div>"); 1766 } 1767 } 1768 1769 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 1770 // widget tree, each wrapping the text inputs and submit button inside it, 1771 // positioned absolutely over the matching grid cells. 1772 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1773 const root_focus = root.getFocus(); 1774 1775 var out: std.ArrayList(u8) = .empty; 1776 errdefer out.deinit(allocator); 1777 1778 const form_prefix = "form:"; 1779 1780 // Focus.children is an AutoArrayHashMap that preserves insertion order, 1781 // which matches the order widgets were added in code 1782 var iter = root_focus.children.iterator(); 1783 while (iter.next()) |entry| { 1784 const child = entry.value_ptr.*; 1785 const action_url = switch (child.focus.kind) { 1786 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 1787 custom[form_prefix.len..] 1788 else 1789 continue, 1790 else => continue, 1791 }; 1792 1793 try out.appendSlice(allocator, "<form action=\""); 1794 try appendEscapedHtml(allocator, &out, action_url); 1795 try out.appendSlice(allocator, "\" method=\"post\""); 1796 // an empty action must not POST — block it and send the input to the TUI instead 1797 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 1798 try out.appendSlice(allocator, ">"); 1799 1800 // form.focus.children was populated by addChild, which flattens the 1801 // whole subtree into one map — so descendants (inputs + the submit 1802 // button) all appear here. positions on form.focus are relative to 1803 // the form, so we look up absolute rects via root_focus for layout. 1804 var inner_iter = child.focus.children.iterator(); 1805 while (inner_iter.next()) |inner_entry| { 1806 const inner_id = inner_entry.key_ptr.*; 1807 const root_child = root_focus.children.get(inner_id) orelse continue; 1808 const r = root_child.rect; 1809 switch (root_child.focus.kind) { 1810 .text_input, .text_input_password => { 1811 const ti = session.text_inputs.get(inner_id) orelse continue; 1812 const inner_left = r.x + 1; 1813 const inner_top = r.y + 1; 1814 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1815 1816 try out.appendSlice(allocator, "<input type=\""); 1817 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 1818 try out.appendSlice(allocator, if (action_url.len == 0) "\" readonly data-focus-id=\"" else "\" data-focus-id=\""); 1819 var id_buf: [32]u8 = undefined; 1820 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1821 if (ti.options.name.len > 0) { 1822 try out.appendSlice(allocator, "\" name=\""); 1823 try appendEscapedHtml(allocator, &out, ti.options.name); 1824 } 1825 // never the live content as the `value`: the browser tracks user 1826 // input natively, and including the wasm-side value here would make 1827 // the overlay HTML differ on every keystroke — that would trip the 1828 // diff in _setOverlay and rebuild the <input>, eating the user's 1829 // caret. a page-constant initial value is safe. 1830 if (session.input_values.get(inner_id)) |value| { 1831 try out.appendSlice(allocator, "\" value=\""); 1832 try appendEscapedHtml(allocator, &out, value); 1833 } 1834 try out.appendSlice(allocator, "\" style=\"left:"); 1835 var pos_buf: [64]u8 = undefined; 1836 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:1em", .{ inner_left, inner_top, inner_width })); 1837 try out.appendSlice(allocator, "\">"); 1838 }, 1839 .text_area => { 1840 const ti = session.text_inputs.get(inner_id) orelse continue; 1841 const inner_left = r.x + 1; 1842 const inner_top = r.y + 1; 1843 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1844 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 1845 1846 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 1847 var id_buf: [32]u8 = undefined; 1848 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1849 if (ti.options.name.len > 0) { 1850 try out.appendSlice(allocator, "\" name=\""); 1851 try appendEscapedHtml(allocator, &out, ti.options.name); 1852 } 1853 // like the input above, only a page-constant initial value 1854 // inside: the browser tracks the live value and the 1855 // overlay diff must stay stable across keystrokes 1856 try out.appendSlice(allocator, "\" style=\"left:"); 1857 var pos_buf: [128]u8 = undefined; 1858 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ inner_left, inner_top, inner_width, inner_height })); 1859 // textarea discards the first newline immediately following 1860 // its start tag, so add one of our own so text that begins 1861 // with a newline doesn't lose it 1862 try out.appendSlice(allocator, "\">\n"); 1863 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1864 try out.appendSlice(allocator, "</textarea>"); 1865 }, 1866 .custom => |custom| { 1867 if (std.mem.eql(u8, "submit", custom) or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 1868 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1869 var id_buf: [32]u8 = undefined; 1870 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1871 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 1872 try out.appendSlice(allocator, "\" formaction=\""); 1873 try appendEscapedHtml(allocator, &out, custom[ui.submit_action_prefix.len..]); 1874 } 1875 try out.appendSlice(allocator, "\" style=\"left:"); 1876 var pos_buf: [128]u8 = undefined; 1877 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ r.x, r.y, r.size.width, r.size.height })); 1878 try out.appendSlice(allocator, "\"></button>"); 1879 } 1880 }, 1881 else => {}, 1882 } 1883 } 1884 1885 try out.appendSlice(allocator, "</form>"); 1886 } 1887 1888 // a file picker isn't part of a form: it posts its file straight to the url 1889 // in its marker. it sits transparent over the button the tui drew, so 1890 // clicking that button opens the browser's own dialog. 1891 var file_iter = root_focus.children.iterator(); 1892 while (file_iter.next()) |entry| { 1893 const child = entry.value_ptr.*; 1894 const action_url = switch (child.focus.kind) { 1895 .custom => |custom| if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) 1896 custom[ui.file_input_prefix.len..] 1897 else 1898 continue, 1899 else => continue, 1900 }; 1901 const r = child.rect; 1902 1903 try out.appendSlice(allocator, "<input type=\"file\" data-action=\""); 1904 try appendEscapedHtml(allocator, &out, action_url); 1905 try out.appendSlice(allocator, "\" data-focus-id=\""); 1906 var id_buf: [32]u8 = undefined; 1907 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{entry.key_ptr.*})); 1908 try out.appendSlice(allocator, "\" style=\"opacity:0;left:"); 1909 var pos_buf: [128]u8 = undefined; 1910 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ r.x, r.y, r.size.width, r.size.height })); 1911 try out.appendSlice(allocator, "\">"); 1912 } 1913 1914 return try out.toOwnedSlice(allocator); 1915 } 1916 1917 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1918 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1919 return b == null; 1920 } 1921 1922 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1923 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1924 // empty slice when neither is set. 1925 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1926 if (fg == null and bg == null) return buf[0..0]; 1927 const prefix = " style=\""; 1928 @memcpy(buf[0..prefix.len], prefix); 1929 var i: usize = prefix.len; 1930 if (fg) |c| { 1931 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]; 1932 i += s.len; 1933 } 1934 if (bg) |c| { 1935 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]; 1936 i += s.len; 1937 } 1938 buf[i] = '"'; 1939 i += 1; 1940 return buf[0..i]; 1941 } 1942 1943 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1944 for (input) |ch| { 1945 switch (ch) { 1946 '&' => try out.appendSlice(allocator, "&amp;"), 1947 '<' => try out.appendSlice(allocator, "&lt;"), 1948 '>' => try out.appendSlice(allocator, "&gt;"), 1949 '"' => try out.appendSlice(allocator, "&quot;"), 1950 '\'' => try out.appendSlice(allocator, "&#39;"), 1951 else => try out.append(allocator, ch), 1952 } 1953 } 1954 } 1955 1956 // --- helpers -------------------------------------------------------------- 1957 1958 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1959 var iter = request.iterateHeaders(); 1960 while (iter.next()) |header| { 1961 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1962 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1963 while (pairs.next()) |pair| { 1964 const trimmed = std.mem.trim(u8, pair, " \t"); 1965 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1966 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1967 return trimmed[eq + 1 ..]; 1968 } 1969 } 1970 } 1971 return null; 1972 } 1973 1974 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1975 var iter = std.mem.splitScalar(u8, body, '&'); 1976 while (iter.next()) |pair| { 1977 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1978 if (std.mem.eql(u8, pair[0..eq], key)) { 1979 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1980 } 1981 } 1982 return null; 1983 } 1984 1985 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 1986 var buffer: [256]u8 = undefined; 1987 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 1988 } 1989 1990 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1991 var out: std.ArrayList(u8) = .empty; 1992 errdefer out.deinit(allocator); 1993 var i: usize = 0; 1994 while (i < encoded.len) : (i += 1) { 1995 switch (encoded[i]) { 1996 '+' => try out.append(allocator, ' '), 1997 '%' => { 1998 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1999 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2000 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2001 try out.append(allocator, hi * 16 + lo); 2002 i += 2; 2003 }, 2004 else => try out.append(allocator, encoded[i]), 2005 } 2006 } 2007 return try out.toOwnedSlice(allocator); 2008 } 2009 2010 // disk-backed web session store. each login mints a random, opaque token 2011 // (not the user's id) that is stored as a file named by the token hex, whose 2012 // contents are the raw user_id bytes. authenticating a request is a lookup of 2013 // the cookie's token; logout deletes the file, revoking the session. there is 2014 // deliberately no expiry — a session lives until logout. 2015 pub const SessionStore = struct { 2016 io: std.Io, 2017 dir: std.Io.Dir, 2018 auto_login: ?[token_hex_len]u8, 2019 2020 pub const token_hex_len = evt.event_id_size * 2; 2021 2022 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2023 try data_dir.createDirPath(io, "sessions"); 2024 const dir = try data_dir.openDir(io, "sessions", .{}); 2025 const auto_login = blk: { 2026 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2027 defer file.close(io); 2028 var token: [token_hex_len]u8 = undefined; 2029 var storage: [token_hex_len]u8 = undefined; 2030 var reader = file.reader(io, &storage); 2031 reader.interface.readSliceAll(&token) catch break :blk null; 2032 break :blk token; 2033 }; 2034 return .{ .io = io, .dir = dir, .auto_login = auto_login }; 2035 } 2036 2037 pub fn deinit(self: SessionStore) void { 2038 self.dir.close(self.io); 2039 } 2040 2041 // mint a new session for user_id, returning the token hex to set as the 2042 // cookie value. 2043 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2044 var token: [evt.event_id_size]u8 = undefined; 2045 self.io.random(&token); 2046 const token_hex = std.fmt.bytesToHex(token, .lower); 2047 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2048 defer file.close(self.io); 2049 try file.writeStreamingAll(self.io, user_id); 2050 return token_hex; 2051 } 2052 2053 // resolve a cookie's token to its user_id. returns false (logged out) for a 2054 // missing, malformed, or unknown token. 2055 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2056 if (!isToken(token_hex)) return false; 2057 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2058 defer file.close(self.io); 2059 var storage: [evt.event_id_size]u8 = undefined; 2060 var file_reader = file.reader(self.io, &storage); 2061 file_reader.interface.readSliceAll(out) catch return false; 2062 return true; 2063 } 2064 2065 // revoke a session. a no-op for a missing or malformed token. 2066 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2067 if (!isToken(token_hex)) return; 2068 self.dir.deleteFile(self.io, token_hex) catch {}; 2069 } 2070 2071 // leave `token_hex`'s session for visitors arriving without one. only the 2072 // `try` fixture writes one. the name can't collide with a session token. 2073 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2074 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2075 defer file.close(self.io); 2076 try file.writeStreamingAll(self.io, token_hex); 2077 } 2078 2079 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2080 out.* = self.auto_login orelse return false; 2081 return true; 2082 } 2083 2084 const auto_login_name = "auto-login"; 2085 2086 // a token is exactly token_hex_len hex chars. validating before using the 2087 // value as a path keeps attacker-supplied cookies from escaping the 2088 // sessions dir (e.g. via "/" or ".." bytes). 2089 fn isToken(token_hex: []const u8) bool { 2090 if (token_hex.len != token_hex_len) return false; 2091 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2092 return true; 2093 } 2094 }; 2095