╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
214 var cookie_buf: [256]u8 = undefined; 215 const cookie = try std.fmt.bufPrint(&cookie_buf, cookie_name ++ "={s}; Path=/; HttpOnly; SameSite=Strict", .{token}); 216 try request.respond("", .{ 217 .status = .see_other, 218 .extra_headers = &.{ 219 .{ .name = "location", .value = success_location }, 220 .{ .name = "set-cookie", .value = cookie }, 221 }, 222 }); 223 }, 224 .unknown_user => { 225 try request.respond("", .{ 226 .status = .see_other, 227 .extra_headers = &.{ 228 .{ .name = "location", .value = failure_location }, 229 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=unknown_user; Path=/; HttpOnly; SameSite=Strict" }, 230 }, 231 }); 232 }, 233 .wrong_password => { 234 try request.respond("", .{ 235 .status = .see_other, 236 .extra_headers = &.{ 237 .{ .name = "location", .value = failure_location }, 238 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=wrong_password; Path=/; HttpOnly; SameSite=Strict" }, 239 }, 240 }); 241 }, 242 } 243 } 244 245 fn handleLogout(request: *std.http.Server.Request, base: []const u8, session_store: SessionStore) !void { 246 // revoke the session server-side so the cookie is dead for anyone holding 247 // a copy, not just this browser. 248 if (getCookieValue(request, cookie_name)) |token| session_store.remove(token); 249 // return to the page the logout came from (base, or "/" at the root). 250 const location: []const u8 = if (base.len == 0) "/" else base; 251 // close the connection instead of keeping it alive: we don't read the 252 // request body, and respond()'s keep-alive path would otherwise try to 253 // discard it — which asserts on a bodyless POST that carries no 254 // content-length, and would block on one with no framing at all. a logout 255 // is just a redirect, so the browser reconnects for the follow-up GET. 256 try request.respond("", .{ 257 .status = .see_other, 258 .keep_alive = false, 259 .extra_headers = &.{ 260 .{ .name = "location", .value = location }, 261 .{ .name = "set-cookie", .value = cookie_name ++ "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0" }, 262 }, 263 }); 264 } 265 266 fn handleAnsi( 267 io: std.Io, 268 request: *std.http.Server.Request, 269 allocator: std.mem.Allocator, 270 base: []const u8, 271 admin_repo_path: []const u8, 272 session_store: SessionStore, 273 ) !void { 274 var user_id: [evt.event_id_size]u8 = undefined; 275 if (getCookieValue(request, cookie_name)) |token| { 276 if (session_store.lookup(token, &user_id)) { 277 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 278 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 279 defer repo.deinit(io, allocator); 280 281 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, &repo, &user_id); 282 } 283 } 284 285 // return to the settings tab the toggle came from so the change is visible. 286 const location = try std.fmt.allocPrint(allocator, "{s}/settings", .{base}); 287 defer allocator.free(location); 288 289 // like logout, this is a bodyless POST, so close the connection rather than 290 // letting the keep-alive path try to discard a body that isn't framed. 291 try request.respond("", .{ 292 .status = .see_other, 293 .keep_alive = false, 294 .extra_headers = &.{ 295 .{ .name = "location", .value = location }, 296 }, 297 }); 298 } 299 300 fn renderIndexHtml( 301 io: std.Io, 302 allocator: std.mem.Allocator, 303 admin_repo_path: []const u8, 304 session_data: ui.Session.Data, 305 ) ![]const u8 { 306 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 307 308 // open the admin repo to read live user/repo data. 309 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 310 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 311 defer repo.deinit(io, allocator); 312 var page_arena = std.heap.ArenaAllocator.init(allocator); 313 defer page_arena.deinit(); 314 315 var session = try ui.Session.init(&page_arena, &repo, session_data); 316 // give the page builders filesystem access to the on-disk repos (a sibling 317 // "repos" dir next to the admin repo) so the Repo page can read its files. 318 session.io = io; 319 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(admin_repo_path) orelse ".", "repos" }); 320 321 const snapshot: ui.Snapshot = .{ 322 .page = try ui.Page.init(session.page_arena, &session, session.data.current_page), 323 .session = session.data, 324 }; 325 var root = try ui.initRoot(allocator, &snapshot.page, &session); 326 defer root.deinit(allocator); 327 328 const content = try generateHtml(allocator, &root); 329 defer allocator.free(content); 330 const overlay = try generateOverlay(allocator, &root, &session); 331 defer allocator.free(overlay); 332 333 // serialize the snapshot so the wasm side can parse it back without making 334 // a second request. it's embedded raw in a <script type="application/json"> 335 // block, whose content is raw text terminated only by "</script". in json, 336 // '<' appears solely inside string values, so escaping every '<' (and '>' 337 // for good measure) to its \uXXXX form yields equivalent json that can't 338 // break out of the tag. 339 var json: std.Io.Writer.Allocating = .init(allocator); 340 defer json.deinit(); 341 try std.json.Stringify.value(snapshot, .{}, &json.writer); 342 343 var json_escaped: std.ArrayList(u8) = .empty; 344 defer json_escaped.deinit(allocator); 345 for (json.written()) |c| switch (c) { 346 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 347 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 348 else => try json_escaped.append(allocator, c), 349 }; 350 351 var out: std.ArrayList(u8) = .empty; 352 errdefer out.deinit(allocator); 353 { 354 var cursor: usize = 0; 355 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 356 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 357 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 358 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 359 }) |sub| { 360 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 361 try out.appendSlice(allocator, template[cursor..idx]); 362 try out.appendSlice(allocator, sub.replacement); 363 cursor = idx + sub.needle.len; 364 } 365 try out.appendSlice(allocator, template[cursor..]); 366 } 367 return try out.toOwnedSlice(allocator); 368 } 369 370 fn findEmbed(request_path: []const u8) ?Embed { 371 const path = if (std.mem.eql(u8, request_path, "/")) 372 "index.html" 373 else if (request_path.len > 1 and request_path[0] == '/') 374 request_path[1..] 375 else 376 return null; 377 378 for (embeds) |embed| { 379 if (std.mem.eql(u8, path, embed.path)) return embed; 380 } 381 return null; 382 } 383 384 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 385 // own absolutely-positioned, natively-scrollable <div> holding its full content, 386 // rendered recursively so nested scrolls work. 387 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 388 const grid = root.getGrid() orelse return error.MissingGrid; 389 390 var out: std.ArrayList(u8) = .empty; 391 errdefer out.deinit(allocator); 392 393 try renderPanel(allocator, &out, root.getFocus(), grid); 394 return try out.toOwnedSlice(allocator); 395 } 396 397 // render one panel — a focus subtree and its content grid — as HTML, recursing 398 // once per web-native Scroll inside it. the root panel is the whole page; each 399 // Scroll becomes a nested, natively-scrollable div holding its full content. 400 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 401 // then the child scroll divs over those holes. 402 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 403 // `direct` is this panel's scroll children, each drawn as an overlaid div. 404 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 405 // plus their descendants, which the focus tree flattens into this panel's 406 // children): the cell hit-test below skips them so this panel doesn't claim 407 // cells that are really rendered inside a child scroll's own panel. 408 // (scrolls aren't nested in practice, so every scroll child is direct here.) 409 var direct: std.ArrayList(usize) = .empty; 410 defer direct.deinit(allocator); 411 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 412 defer excluded.deinit(allocator); 413 { 414 var it = focus.children.iterator(); 415 while (it.next()) |e| { 416 if (e.value_ptr.focus.scroll == null) continue; 417 try direct.append(allocator, e.key_ptr.*); 418 try excluded.put(allocator, e.key_ptr.*, {}); 419 var mit = e.value_ptr.focus.children.iterator(); 420 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 421 } 422 } 423 424 // the HTML element a run of cells is wrapped in, chosen from the cell's 425 // focusable kind 426 const CellTag = union(enum) { 427 span, // clickable focusable cell 428 a: []const u8, // clickable focusable link 429 plain, // non-focusable, colored 430 431 const a_prefix = "a:"; 432 // an "in-page" anchor: rendered as a real <a href> so it works with js 433 // disabled, but crossPageLink ignores it, so with wasm the click just 434 // moves focus rather than navigating. 435 const inpage_prefix = "ai:"; 436 437 fn init(str: []const u8) @This() { 438 if (std.mem.startsWith(u8, str, inpage_prefix)) { 439 return .{ .a = str[inpage_prefix.len..] }; 440 } 441 if (std.mem.startsWith(u8, str, a_prefix)) { 442 return .{ .a = str[a_prefix.len..] }; 443 } 444 return .span; 445 } 446 447 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 448 var id_buf: [32]u8 = undefined; 449 switch (self) { 450 .span => { 451 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 452 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 453 try out.appendSlice(alloc, "\""); 454 try out.appendSlice(alloc, style_attr); 455 try out.appendSlice(alloc, ">"); 456 }, 457 .a => |href| { 458 // tabindex=-1 keeps these out of the browser's tab order 459 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 460 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 461 try out.appendSlice(alloc, "\" href=\""); 462 try appendEscapedHtml(alloc, out, href); 463 try out.appendSlice(alloc, "\""); 464 try out.appendSlice(alloc, style_attr); 465 try out.appendSlice(alloc, ">"); 466 }, 467 .plain => { 468 try out.appendSlice(alloc, "<span"); 469 try out.appendSlice(alloc, style_attr); 470 try out.appendSlice(alloc, ">"); 471 }, 472 } 473 } 474 475 fn closeTag(self: @This()) []const u8 { 476 return switch (self) { 477 .span, .plain => "</span>", 478 .a => "</a>", 479 }; 480 } 481 }; 482 483 // emit this panel's grid as rows of text, coalescing adjacent cells that 484 // share a focus id and colors into one tag (a clickable span, a link, or a 485 // plain colored span). cells under a child scroll keep only their background. 486 for (0..grid.size.height) |y| { 487 var cur_id: ?usize = null; 488 var cur_fg: ?Grid.Color = null; 489 var cur_bg: ?Grid.Color = null; 490 var open_tag: ?CellTag = null; 491 var first = true; 492 for (0..grid.size.width) |x| { 493 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 494 // a cell covered by a child scroll's viewport is drawn by that scroll's 495 // own div, so blank its glyph and make it non-clickable here — but keep 496 // its background, so the backdrop still shows through the scroll's 497 // transparent div instead of a bare hole. 498 const covered_by_scroll = blk: { 499 for (direct.items) |id| { 500 const r = (focus.children.get(id) orelse continue).rect; 501 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; 502 } 503 break :blk false; 504 }; 505 // the focusable cell at (x, y) among this panel's own focusables (skipping 506 // any that belong to a child scroll, whose cells are drawn in their own 507 // panel); none for a covered cell. 508 const cell_id = if (covered_by_scroll) null else blk: { 509 var iter = focus.children.iterator(); 510 while (iter.next()) |entry| { 511 const child = entry.value_ptr.*; 512 if (!child.focus.focusable) continue; 513 if (excluded.contains(entry.key_ptr.*)) continue; 514 const r = child.rect; 515 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 516 break :blk entry.key_ptr.*; 517 } 518 } 519 break :blk null; 520 }; 521 const fg = if (covered_by_scroll) null else cell.style.fg; 522 const bg = cell.style.bg; 523 524 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 525 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 526 527 var new_tag: ?CellTag = null; 528 if (cell_id) |id| { 529 if (focus.children.get(id)) |child| { 530 new_tag = switch (child.focus.kind) { 531 .custom => |custom| CellTag.init(custom), 532 else => .span, 533 }; 534 } 535 } 536 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 537 538 if (new_tag) |t| { 539 var style_buf: [64]u8 = undefined; 540 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 541 } 542 543 open_tag = new_tag; 544 cur_id = cell_id; 545 cur_fg = fg; 546 cur_bg = bg; 547 first = false; 548 } 549 550 try appendEscapedHtml(allocator, output, if (covered_by_scroll) " " else (cell.rune orelse " ")); 551 } 552 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 553 try output.append(allocator, '\n'); 554 } 555 556 // each child scroll becomes a natively-scrollable div positioned over its 557 // viewport, holding its full content rendered recursively. 558 for (direct.items) |id| { 559 const child = focus.children.get(id) orelse continue; 560 const info = child.focus.scroll orelse continue; 561 const r = child.rect; 562 // overflow only on the axes the widget scrolls; `auto` shows a bar only 563 // when that axis actually overflows. the other axis is clipped (hidden), 564 // matching how the terminal Scroll handles its non-scrolling axis. 565 const overflow = switch (info.direction) { 566 .vert => "overflow-x:hidden;overflow-y:auto", 567 .horiz => "overflow-x:auto;overflow-y:hidden", 568 .both => "overflow:auto", 569 }; 570 // the id carries a content version so JS preserves the native scroll 571 // position across re-renders of the same content but resets it (to the 572 // top) when the content is replaced — e.g. selecting a different commit. 573 var buf: [160]u8 = undefined; 574 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, "<div class=\"scroll\" data-scroll-id=\"{d}-{d}\" style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em;{s}\">", .{ id, child.focus.version, r.x, r.y, r.size.width, r.size.height, overflow })); 575 try renderPanel(allocator, output, child.focus, info.content); 576 try output.appendSlice(allocator, "</div>"); 577 } 578 } 579 580 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 581 // widget tree, each wrapping the text inputs and submit button inside it, 582 // positioned absolutely over the matching grid cells. 583 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 584 const root_focus = root.getFocus(); 585 586 var out: std.ArrayList(u8) = .empty; 587 errdefer out.deinit(allocator); 588 589 const form_prefix = "form:"; 590 591 // Focus.children is an AutoArrayHashMap that preserves insertion order, 592 // which matches the order widgets were added in code 593 var iter = root_focus.children.iterator(); 594 while (iter.next()) |entry| { 595 const child = entry.value_ptr.*; 596 const action_url = switch (child.focus.kind) { 597 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 598 custom[form_prefix.len..] 599 else 600 continue, 601 else => continue, 602 }; 603 604 try out.appendSlice(allocator, "<form action=\""); 605 try appendEscapedHtml(allocator, &out, action_url); 606 try out.appendSlice(allocator, "\" method=\"post\""); 607 // an empty action must not POST — block it and send the input to the TUI instead 608 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 609 try out.appendSlice(allocator, ">"); 610 611 // form.focus.children was populated by addChild, which flattens the 612 // whole subtree into one map — so descendants (inputs + the submit 613 // button) all appear here. positions on form.focus are relative to 614 // the form, so we look up absolute rects via root_focus for layout. 615 var inner_iter = child.focus.children.iterator(); 616 while (inner_iter.next()) |inner_entry| { 617 const inner_id = inner_entry.key_ptr.*; 618 const root_child = root_focus.children.get(inner_id) orelse continue; 619 const r = root_child.rect; 620 switch (root_child.focus.kind) { 621 .text_input, .text_input_password => { 622 const ti = session.text_inputs.get(inner_id) orelse continue; 623 const inner_left = r.x + 1; 624 const inner_top = r.y + 1; 625 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 626 627 try out.appendSlice(allocator, "<input type=\""); 628 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 629 try out.appendSlice(allocator, "\" data-focus-id=\""); 630 var id_buf: [32]u8 = undefined; 631 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 632 if (ti.options.name.len > 0) { 633 try out.appendSlice(allocator, "\" name=\""); 634 try appendEscapedHtml(allocator, &out, ti.options.name); 635 } 636 // intentionally no `value` attribute: the browser tracks user input 637 // natively, and including the wasm-side value here would make the 638 // overlay HTML differ on every keystroke — that would trip the diff 639 // in _setOverlay and rebuild the <input>, eating the user's caret. 640 try out.appendSlice(allocator, "\" style=\"left:"); 641 var pos_buf: [64]u8 = undefined; 642 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 })); 643 try out.appendSlice(allocator, "\">"); 644 }, 645 .custom => |custom| { 646 if (std.mem.eql(u8, "submit", custom)) { 647 // inside the dashed border the TUI cells draw around the button. 648 const inner_left = r.x + 1; 649 const inner_top = r.y + 1; 650 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 651 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 652 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 653 var id_buf: [32]u8 = undefined; 654 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 655 try out.appendSlice(allocator, "\" style=\"left:"); 656 var pos_buf: [128]u8 = undefined; 657 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 })); 658 try out.appendSlice(allocator, "\"></button>"); 659 } 660 }, 661 else => {}, 662 } 663 } 664 665 try out.appendSlice(allocator, "</form>"); 666 } 667 668 return try out.toOwnedSlice(allocator); 669 } 670 671 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 672 if (a) |av| return if (b) |bv| av.eql(bv) else false; 673 return b == null; 674 } 675 676 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 677 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 678 // empty slice when neither is set. 679 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 680 if (fg == null and bg == null) return buf[0..0]; 681 const prefix = " style=\""; 682 @memcpy(buf[0..prefix.len], prefix); 683 var i: usize = prefix.len; 684 if (fg) |c| { 685 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]; 686 i += s.len; 687 } 688 if (bg) |c| { 689 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]; 690 i += s.len; 691 } 692 buf[i] = '"'; 693 i += 1; 694 return buf[0..i]; 695 } 696 697 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 698 for (input) |ch| { 699 switch (ch) { 700 '&' => try out.appendSlice(allocator, "&amp;"), 701 '<' => try out.appendSlice(allocator, "&lt;"), 702 '>' => try out.appendSlice(allocator, "&gt;"), 703 '"' => try out.appendSlice(allocator, "&quot;"), 704 '\'' => try out.appendSlice(allocator, "&#39;"), 705 else => try out.append(allocator, ch), 706 } 707 } 708 } 709 710 // --- helpers -------------------------------------------------------------- 711 712 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 713 var iter = request.iterateHeaders(); 714 while (iter.next()) |header| { 715 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 716 var pairs = std.mem.splitScalar(u8, header.value, ';'); 717 while (pairs.next()) |pair| { 718 const trimmed = std.mem.trim(u8, pair, " \t"); 719 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 720 if (std.mem.eql(u8, trimmed[0..eq], name)) { 721 return trimmed[eq + 1 ..]; 722 } 723 } 724 } 725 return null; 726 } 727 728 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 729 var iter = std.mem.splitScalar(u8, body, '&'); 730 while (iter.next()) |pair| { 731 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 732 if (std.mem.eql(u8, pair[0..eq], key)) { 733 return try decodeFormValue(allocator, pair[eq + 1 ..]); 734 } 735 } 736 return null; 737 } 738 739 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 740 var out: std.ArrayList(u8) = .empty; 741 errdefer out.deinit(allocator); 742 var i: usize = 0; 743 while (i < encoded.len) : (i += 1) { 744 switch (encoded[i]) { 745 '+' => try out.append(allocator, ' '), 746 '%' => { 747 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 748 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 749 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 750 try out.append(allocator, hi * 16 + lo); 751 i += 2; 752 }, 753 else => try out.append(allocator, encoded[i]), 754 } 755 } 756 return try out.toOwnedSlice(allocator); 757 } 758 759 // disk-backed web session store. each login mints a random, opaque token 760 // (not the user's id) that is stored as a file named by the token hex, whose 761 // contents are the raw user_id bytes. authenticating a request is a lookup of 762 // the cookie's token; logout deletes the file, revoking the session. there is 763 // deliberately no expiry — a session lives until logout. 764 pub const SessionStore = struct { 765 io: std.Io, 766 dir: std.Io.Dir, 767 768 pub const token_hex_len = evt.event_id_size * 2; 769 770 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 771 try data_dir.createDirPath(io, "sessions"); 772 const dir = try data_dir.openDir(io, "sessions", .{}); 773 return .{ .io = io, .dir = dir }; 774 } 775 776 pub fn deinit(self: SessionStore) void { 777 self.dir.close(self.io); 778 } 779 780 // mint a new session for user_id, returning the token hex to set as the 781 // cookie value. 782 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 783 var token: [evt.event_id_size]u8 = undefined; 784 self.io.random(&token); 785 const token_hex = std.fmt.bytesToHex(token, .lower); 786 const file = try self.dir.createFile(self.io, &token_hex, .{}); 787 defer file.close(self.io); 788 try file.writeStreamingAll(self.io, user_id); 789 return token_hex; 790 } 791 792 // resolve a cookie's token to its user_id. returns false (logged out) for a 793 // missing, malformed, or unknown token. 794 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 795 if (!isToken(token_hex)) return false; 796 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 797 defer file.close(self.io); 798 var storage: [evt.event_id_size]u8 = undefined; 799 var file_reader = file.reader(self.io, &storage); 800 file_reader.interface.readSliceAll(out) catch return false; 801 return true; 802 } 803 804 // revoke a session. a no-op for a missing or malformed token. 805 pub fn remove(self: SessionStore, token_hex: []const u8) void { 806 if (!isToken(token_hex)) return; 807 self.dir.deleteFile(self.io, token_hex) catch {}; 808 } 809 810 // a token is exactly token_hex_len hex chars. validating before using the 811 // value as a path keeps attacker-supplied cookies from escaping the 812 // sessions dir (e.g. via "/" or ".." bytes). 813 fn isToken(token_hex: []const u8) bool { 814 if (token_hex.len != token_hex_len) return false; 815 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 816 return true; 817 } 818 }; 819