╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
374 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 375 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 376 defer repo.deinit(io, allocator); 377 var page_arena = std.heap.ArenaAllocator.init(allocator); 378 defer page_arena.deinit(); 379 380 var session = try ui.Session.init(&page_arena, &repo, session_data); 381 // give the page builders filesystem access to the on-disk repos (a sibling 382 // "repos" dir next to the admin repo) so the Repo page can read its files. 383 session.io = io; 384 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(admin_repo_path) orelse ".", "repos" }); 385 386 const snapshot: ui.Snapshot = .{ 387 .page = try ui.Page.init(session.page_arena, &session, session.data.current_page), 388 .session = session.data, 389 }; 390 var root = try ui.initRoot(allocator, &snapshot.page, &session); 391 defer root.deinit(allocator); 392 393 const content = try generateHtml(allocator, &root); 394 defer allocator.free(content); 395 const overlay = try generateOverlay(allocator, &root, &session); 396 defer allocator.free(overlay); 397 398 // serialize the snapshot so the wasm side can parse it back without making 399 // a second request. it's embedded raw in a <script type="application/json"> 400 // block, whose content is raw text terminated only by "</script". in json, 401 // '<' appears solely inside string values, so escaping every '<' (and '>' 402 // for good measure) to its \uXXXX form yields equivalent json that can't 403 // break out of the tag. 404 var json: std.Io.Writer.Allocating = .init(allocator); 405 defer json.deinit(); 406 try std.json.Stringify.value(snapshot, .{}, &json.writer); 407 408 var json_escaped: std.ArrayList(u8) = .empty; 409 defer json_escaped.deinit(allocator); 410 for (json.written()) |c| switch (c) { 411 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 412 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 413 else => try json_escaped.append(allocator, c), 414 }; 415 416 var out: std.ArrayList(u8) = .empty; 417 errdefer out.deinit(allocator); 418 { 419 var cursor: usize = 0; 420 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 421 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 422 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 423 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 424 }) |sub| { 425 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 426 try out.appendSlice(allocator, template[cursor..idx]); 427 try out.appendSlice(allocator, sub.replacement); 428 cursor = idx + sub.needle.len; 429 } 430 try out.appendSlice(allocator, template[cursor..]); 431 } 432 return try out.toOwnedSlice(allocator); 433 } 434 435 fn findEmbed(request_path: []const u8) ?Embed { 436 const path = if (std.mem.eql(u8, request_path, "/")) 437 "index.html" 438 else if (request_path.len > 1 and request_path[0] == '/') 439 request_path[1..] 440 else 441 return null; 442 443 for (embeds) |embed| { 444 if (std.mem.eql(u8, path, embed.path)) return embed; 445 } 446 return null; 447 } 448 449 fn logError(err: *std.Io.Writer, comptime fmt: []const u8, args: anytype) void { 450 err.print(fmt, args) catch return; 451 err.flush() catch {}; 452 } 453 454 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 455 // own absolutely-positioned, natively-scrollable <div> holding its full content, 456 // rendered recursively so nested scrolls work. 457 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 458 const grid = root.getGrid() orelse return error.MissingGrid; 459 460 var out: std.ArrayList(u8) = .empty; 461 errdefer out.deinit(allocator); 462 463 try renderPanel(allocator, &out, root.getFocus(), grid); 464 return try out.toOwnedSlice(allocator); 465 } 466 467 // render one panel — a focus subtree and its content grid — as HTML, recursing 468 // once per web-native Scroll inside it. the root panel is the whole page; each 469 // Scroll becomes a nested, natively-scrollable div holding its full content. 470 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 471 // then the child scroll divs over those holes. 472 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 473 // `direct` is this panel's scroll children, each drawn as an overlaid div. 474 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 475 // plus their descendants, which the focus tree flattens into this panel's 476 // children): the cell hit-test below skips them so this panel doesn't claim 477 // cells that are really rendered inside a child scroll's own panel. 478 // (scrolls aren't nested in practice, so every scroll child is direct here.) 479 var direct: std.ArrayList(usize) = .empty; 480 defer direct.deinit(allocator); 481 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 482 defer excluded.deinit(allocator); 483 { 484 var it = focus.children.iterator(); 485 while (it.next()) |e| { 486 if (e.value_ptr.focus.scroll == null) continue; 487 try direct.append(allocator, e.key_ptr.*); 488 try excluded.put(allocator, e.key_ptr.*, {}); 489 var mit = e.value_ptr.focus.children.iterator(); 490 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 491 } 492 } 493 494 // the HTML element a run of cells is wrapped in, chosen from the cell's 495 // focusable kind 496 const CellTag = union(enum) { 497 span, // clickable focusable cell 498 a: []const u8, // clickable focusable link 499 plain, // non-focusable, colored 500 501 const a_prefix = "a:"; 502 // an "in-page" anchor: rendered as a real <a href> so it works with js 503 // disabled, but crossPageLink ignores it, so with wasm the click just 504 // moves focus rather than navigating. 505 const inpage_prefix = "ai:"; 506 507 fn init(str: []const u8) @This() { 508 if (std.mem.startsWith(u8, str, inpage_prefix)) { 509 return .{ .a = str[inpage_prefix.len..] }; 510 } 511 if (std.mem.startsWith(u8, str, a_prefix)) { 512 return .{ .a = str[a_prefix.len..] }; 513 } 514 return .span; 515 } 516 517 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 518 var id_buf: [32]u8 = undefined; 519 switch (self) { 520 .span => { 521 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 522 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 523 try out.appendSlice(alloc, "\""); 524 try out.appendSlice(alloc, style_attr); 525 try out.appendSlice(alloc, ">"); 526 }, 527 .a => |href| { 528 // tabindex=-1 keeps these out of the browser's tab order 529 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 530 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 531 try out.appendSlice(alloc, "\" href=\""); 532 try appendEscapedHtml(alloc, out, href); 533 try out.appendSlice(alloc, "\""); 534 try out.appendSlice(alloc, style_attr); 535 try out.appendSlice(alloc, ">"); 536 }, 537 .plain => { 538 try out.appendSlice(alloc, "<span"); 539 try out.appendSlice(alloc, style_attr); 540 try out.appendSlice(alloc, ">"); 541 }, 542 } 543 } 544 545 fn closeTag(self: @This()) []const u8 { 546 return switch (self) { 547 .span, .plain => "</span>", 548 .a => "</a>", 549 }; 550 } 551 }; 552 553 // emit this panel's grid as rows of text, coalescing adjacent cells that 554 // share a focus id and colors into one tag (a clickable span, a link, or a 555 // plain colored span). cells under a child scroll keep only their background. 556 for (0..grid.size.height) |y| { 557 var cur_id: ?usize = null; 558 var cur_fg: ?Grid.Color = null; 559 var cur_bg: ?Grid.Color = null; 560 var open_tag: ?CellTag = null; 561 var first = true; 562 for (0..grid.size.width) |x| { 563 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 564 // a cell covered by a child scroll's viewport is drawn by that scroll's 565 // own div, so blank its glyph and make it non-clickable here — but keep 566 // its background, so the backdrop still shows through the scroll's 567 // transparent div instead of a bare hole. 568 const covered_by_scroll = blk: { 569 for (direct.items) |id| { 570 const r = (focus.children.get(id) orelse continue).rect; 571 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; 572 } 573 break :blk false; 574 }; 575 // the focusable cell at (x, y) among this panel's own focusables (skipping 576 // any that belong to a child scroll, whose cells are drawn in their own 577 // panel); none for a covered cell. 578 const cell_id = if (covered_by_scroll) null else blk: { 579 var iter = focus.children.iterator(); 580 while (iter.next()) |entry| { 581 const child = entry.value_ptr.*; 582 if (!child.focus.focusable) continue; 583 if (excluded.contains(entry.key_ptr.*)) continue; 584 const r = child.rect; 585 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 586 break :blk entry.key_ptr.*; 587 } 588 } 589 break :blk null; 590 }; 591 const fg = if (covered_by_scroll) null else cell.style.fg; 592 const bg = cell.style.bg; 593 594 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 595 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 596 597 var new_tag: ?CellTag = null; 598 if (cell_id) |id| { 599 if (focus.children.get(id)) |child| { 600 new_tag = switch (child.focus.kind) { 601 .custom => |custom| CellTag.init(custom), 602 else => .span, 603 }; 604 } 605 } 606 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 607 608 if (new_tag) |t| { 609 var style_buf: [64]u8 = undefined; 610 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 611 } 612 613 open_tag = new_tag; 614 cur_id = cell_id; 615 cur_fg = fg; 616 cur_bg = bg; 617 first = false; 618 } 619 620 try appendEscapedHtml(allocator, output, if (covered_by_scroll) " " else (cell.rune orelse " ")); 621 } 622 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 623 try output.append(allocator, '\n'); 624 } 625 626 // each child scroll becomes a natively-scrollable div positioned over its 627 // viewport, holding its full content rendered recursively. 628 for (direct.items) |id| { 629 const child = focus.children.get(id) orelse continue; 630 const info = child.focus.scroll orelse continue; 631 const r = child.rect; 632 // overflow only on the axes the widget scrolls; `auto` shows a bar only 633 // when that axis actually overflows. the other axis is clipped (hidden), 634 // matching how the terminal Scroll handles its non-scrolling axis. 635 const overflow = switch (info.direction) { 636 .vert => "overflow-x:hidden;overflow-y:auto", 637 .horiz => "overflow-x:auto;overflow-y:hidden", 638 .both => "overflow:auto", 639 }; 640 // the id carries a content version so JS preserves the native scroll 641 // position across re-renders of the same content but resets it (to the 642 // top) when the content is replaced — e.g. selecting a different commit. 643 var buf: [160]u8 = undefined; 644 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 })); 645 try renderPanel(allocator, output, child.focus, info.content); 646 try output.appendSlice(allocator, "</div>"); 647 } 648 } 649 650 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 651 // widget tree, each wrapping the text inputs and submit button inside it, 652 // positioned absolutely over the matching grid cells. 653 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 654 const root_focus = root.getFocus(); 655 656 var out: std.ArrayList(u8) = .empty; 657 errdefer out.deinit(allocator); 658 659 const form_prefix = "form:"; 660 661 // Focus.children is an AutoArrayHashMap that preserves insertion order, 662 // which matches the order widgets were added in code 663 var iter = root_focus.children.iterator(); 664 while (iter.next()) |entry| { 665 const child = entry.value_ptr.*; 666 const action_url = switch (child.focus.kind) { 667 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 668 custom[form_prefix.len..] 669 else 670 continue, 671 else => continue, 672 }; 673 674 try out.appendSlice(allocator, "<form action=\""); 675 try appendEscapedHtml(allocator, &out, action_url); 676 try out.appendSlice(allocator, "\" method=\"post\""); 677 // an empty action must not POST — block it and send the input to the TUI instead 678 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 679 try out.appendSlice(allocator, ">"); 680 681 // form.focus.children was populated by addChild, which flattens the 682 // whole subtree into one map — so descendants (inputs + the submit 683 // button) all appear here. positions on form.focus are relative to 684 // the form, so we look up absolute rects via root_focus for layout. 685 var inner_iter = child.focus.children.iterator(); 686 while (inner_iter.next()) |inner_entry| { 687 const inner_id = inner_entry.key_ptr.*; 688 const root_child = root_focus.children.get(inner_id) orelse continue; 689 const r = root_child.rect; 690 switch (root_child.focus.kind) { 691 .text_input, .text_input_password => { 692 const ti = session.text_inputs.get(inner_id) orelse continue; 693 const inner_left = r.x + 1; 694 const inner_top = r.y + 1; 695 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 696 697 try out.appendSlice(allocator, "<input type=\""); 698 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 699 try out.appendSlice(allocator, "\" data-focus-id=\""); 700 var id_buf: [32]u8 = undefined; 701 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 702 if (ti.options.name.len > 0) { 703 try out.appendSlice(allocator, "\" name=\""); 704 try appendEscapedHtml(allocator, &out, ti.options.name); 705 } 706 // intentionally no `value` attribute: the browser tracks user input 707 // natively, and including the wasm-side value here would make the 708 // overlay HTML differ on every keystroke — that would trip the diff 709 // in _setOverlay and rebuild the <input>, eating the user's caret. 710 try out.appendSlice(allocator, "\" style=\"left:"); 711 var pos_buf: [64]u8 = undefined; 712 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 })); 713 try out.appendSlice(allocator, "\">"); 714 }, 715 .custom => |custom| { 716 if (std.mem.eql(u8, "submit", custom)) { 717 // inside the dashed border the TUI cells draw around the button. 718 const inner_left = r.x + 1; 719 const inner_top = r.y + 1; 720 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 721 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 722 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 723 var id_buf: [32]u8 = undefined; 724 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 725 try out.appendSlice(allocator, "\" style=\"left:"); 726 var pos_buf: [128]u8 = undefined; 727 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 })); 728 try out.appendSlice(allocator, "\"></button>"); 729 } 730 }, 731 else => {}, 732 } 733 } 734 735 try out.appendSlice(allocator, "</form>"); 736 } 737 738 return try out.toOwnedSlice(allocator); 739 } 740 741 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 742 if (a) |av| return if (b) |bv| av.eql(bv) else false; 743 return b == null; 744 } 745 746 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 747 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 748 // empty slice when neither is set. 749 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 750 if (fg == null and bg == null) return buf[0..0]; 751 const prefix = " style=\""; 752 @memcpy(buf[0..prefix.len], prefix); 753 var i: usize = prefix.len; 754 if (fg) |c| { 755 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]; 756 i += s.len; 757 } 758 if (bg) |c| { 759 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]; 760 i += s.len; 761 } 762 buf[i] = '"'; 763 i += 1; 764 return buf[0..i]; 765 } 766 767 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 768 for (input) |ch| { 769 switch (ch) { 770 '&' => try out.appendSlice(allocator, "&amp;"), 771 '<' => try out.appendSlice(allocator, "&lt;"), 772 '>' => try out.appendSlice(allocator, "&gt;"), 773 '"' => try out.appendSlice(allocator, "&quot;"), 774 '\'' => try out.appendSlice(allocator, "&#39;"), 775 else => try out.append(allocator, ch), 776 } 777 } 778 } 779 780 // --- helpers -------------------------------------------------------------- 781 782 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 783 var iter = request.iterateHeaders(); 784 while (iter.next()) |header| { 785 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 786 var pairs = std.mem.splitScalar(u8, header.value, ';'); 787 while (pairs.next()) |pair| { 788 const trimmed = std.mem.trim(u8, pair, " \t"); 789 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 790 if (std.mem.eql(u8, trimmed[0..eq], name)) { 791 return trimmed[eq + 1 ..]; 792 } 793 } 794 } 795 return null; 796 } 797 798 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 799 var iter = std.mem.splitScalar(u8, body, '&'); 800 while (iter.next()) |pair| { 801 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 802 if (std.mem.eql(u8, pair[0..eq], key)) { 803 return try decodeFormValue(allocator, pair[eq + 1 ..]); 804 } 805 } 806 return null; 807 } 808 809 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 810 var out: std.ArrayList(u8) = .empty; 811 errdefer out.deinit(allocator); 812 var i: usize = 0; 813 while (i < encoded.len) : (i += 1) { 814 switch (encoded[i]) { 815 '+' => try out.append(allocator, ' '), 816 '%' => { 817 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 818 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 819 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 820 try out.append(allocator, hi * 16 + lo); 821 i += 2; 822 }, 823 else => try out.append(allocator, encoded[i]), 824 } 825 } 826 return try out.toOwnedSlice(allocator); 827 } 828 829 // disk-backed web session store. each login mints a random, opaque token 830 // (not the user's id) that is stored as a file named by the token hex, whose 831 // contents are the raw user_id bytes. authenticating a request is a lookup of 832 // the cookie's token; logout deletes the file, revoking the session. there is 833 // deliberately no expiry — a session lives until logout. 834 pub const SessionStore = struct { 835 io: std.Io, 836 dir: std.Io.Dir, 837 838 pub const token_hex_len = evt.event_id_size * 2; 839 840 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 841 try data_dir.createDirPath(io, "sessions"); 842 const dir = try data_dir.openDir(io, "sessions", .{}); 843 return .{ .io = io, .dir = dir }; 844 } 845 846 pub fn deinit(self: SessionStore) void { 847 self.dir.close(self.io); 848 } 849 850 // mint a new session for user_id, returning the token hex to set as the 851 // cookie value. 852 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 853 var token: [evt.event_id_size]u8 = undefined; 854 self.io.random(&token); 855 const token_hex = std.fmt.bytesToHex(token, .lower); 856 const file = try self.dir.createFile(self.io, &token_hex, .{}); 857 defer file.close(self.io); 858 try file.writeStreamingAll(self.io, user_id); 859 return token_hex; 860 } 861 862 // resolve a cookie's token to its user_id. returns false (logged out) for a 863 // missing, malformed, or unknown token. 864 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 865 if (!isToken(token_hex)) return false; 866 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 867 defer file.close(self.io); 868 var storage: [evt.event_id_size]u8 = undefined; 869 var file_reader = file.reader(self.io, &storage); 870 file_reader.interface.readSliceAll(out) catch return false; 871 return true; 872 } 873 874 // revoke a session. a no-op for a missing or malformed token. 875 pub fn remove(self: SessionStore, token_hex: []const u8) void { 876 if (!isToken(token_hex)) return; 877 self.dir.deleteFile(self.io, token_hex) catch {}; 878 } 879 880 // a token is exactly token_hex_len hex chars. validating before using the 881 // value as a path keeps attacker-supplied cookies from escaping the 882 // sessions dir (e.g. via "/" or ".." bytes). 883 fn isToken(token_hex: []const u8) bool { 884 if (token_hex.len != token_hex_len) return false; 885 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 886 return true; 887 } 888 }; 889