╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
557 558 const snapshot: ui.Snapshot = .{ 559 .page = try ui.Page.init(session.page_arena, &session, session.data.current_page), 560 .session = session.data, 561 }; 562 var root = try ui.initRoot(allocator, &snapshot.page, &session); 563 defer root.deinit(allocator); 564 565 const content = try generateHtml(allocator, &root); 566 defer allocator.free(content); 567 const overlay = try generateOverlay(allocator, &root, &session); 568 defer allocator.free(overlay); 569 570 // serialize the snapshot so the wasm side can parse it back without making 571 // a second request. it's embedded raw in a <script type="application/json"> 572 // block, whose content is raw text terminated only by "</script". in json, 573 // '<' appears solely inside string values, so escaping every '<' (and '>' 574 // for good measure) to its \uXXXX form yields equivalent json that can't 575 // break out of the tag. 576 var json: std.Io.Writer.Allocating = .init(allocator); 577 defer json.deinit(); 578 try std.json.Stringify.value(snapshot, .{}, &json.writer); 579 580 var json_escaped: std.ArrayList(u8) = .empty; 581 defer json_escaped.deinit(allocator); 582 for (json.written()) |c| switch (c) { 583 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 584 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 585 else => try json_escaped.append(allocator, c), 586 }; 587 588 var out: std.ArrayList(u8) = .empty; 589 errdefer out.deinit(allocator); 590 { 591 var cursor: usize = 0; 592 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 593 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 594 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 595 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 596 }) |sub| { 597 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 598 try out.appendSlice(allocator, template[cursor..idx]); 599 try out.appendSlice(allocator, sub.replacement); 600 cursor = idx + sub.needle.len; 601 } 602 try out.appendSlice(allocator, template[cursor..]); 603 } 604 return try out.toOwnedSlice(allocator); 605 } 606 607 fn findEmbed(request_path: []const u8) ?Embed { 608 const path = if (std.mem.eql(u8, request_path, "/")) 609 "index.html" 610 else if (request_path.len > 1 and request_path[0] == '/') 611 request_path[1..] 612 else 613 return null; 614 615 for (embeds) |embed| { 616 if (std.mem.eql(u8, path, embed.path)) return embed; 617 } 618 return null; 619 } 620 621 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 622 // own absolutely-positioned, natively-scrollable <div> holding its full content, 623 // rendered recursively so nested scrolls work. 624 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 625 const grid = root.getGrid() orelse return error.MissingGrid; 626 627 var out: std.ArrayList(u8) = .empty; 628 errdefer out.deinit(allocator); 629 630 try renderPanel(allocator, &out, root.getFocus(), grid); 631 return try out.toOwnedSlice(allocator); 632 } 633 634 // render one panel — a focus subtree and its content grid — as HTML, recursing 635 // once per web-native Scroll inside it. the root panel is the whole page; each 636 // Scroll becomes a nested, natively-scrollable div holding its full content. 637 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 638 // then the child scroll divs over those holes. 639 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 640 // `direct` is this panel's scroll children, each drawn as an overlaid div. 641 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 642 // plus their descendants, which the focus tree flattens into this panel's 643 // children): the cell hit-test below skips them so this panel doesn't claim 644 // cells that are really rendered inside a child scroll's own panel. 645 // (scrolls aren't nested in practice, so every scroll child is direct here.) 646 var direct: std.ArrayList(usize) = .empty; 647 defer direct.deinit(allocator); 648 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 649 defer excluded.deinit(allocator); 650 { 651 var it = focus.children.iterator(); 652 while (it.next()) |e| { 653 if (e.value_ptr.focus.scroll == null) continue; 654 try direct.append(allocator, e.key_ptr.*); 655 try excluded.put(allocator, e.key_ptr.*, {}); 656 var mit = e.value_ptr.focus.children.iterator(); 657 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 658 } 659 } 660 661 // the HTML element a run of cells is wrapped in, chosen from the cell's 662 // focusable kind 663 const CellTag = union(enum) { 664 span, // clickable focusable cell 665 a: []const u8, // clickable focusable link 666 plain, // non-focusable, colored 667 668 const a_prefix = "a:"; 669 // an "in-page" anchor: rendered as a real <a href> so it works with js 670 // disabled, but crossPageLink ignores it, so with wasm the click just 671 // moves focus rather than navigating. 672 const inpage_prefix = "ai:"; 673 674 fn init(str: []const u8) @This() { 675 if (std.mem.startsWith(u8, str, inpage_prefix)) { 676 return .{ .a = str[inpage_prefix.len..] }; 677 } 678 if (std.mem.startsWith(u8, str, a_prefix)) { 679 return .{ .a = str[a_prefix.len..] }; 680 } 681 return .span; 682 } 683 684 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 685 var id_buf: [32]u8 = undefined; 686 switch (self) { 687 .span => { 688 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 689 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 690 try out.appendSlice(alloc, "\""); 691 try out.appendSlice(alloc, style_attr); 692 try out.appendSlice(alloc, ">"); 693 }, 694 .a => |href| { 695 // tabindex=-1 keeps these out of the browser's tab order 696 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 697 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 698 try out.appendSlice(alloc, "\" href=\""); 699 try appendEscapedHtml(alloc, out, href); 700 try out.appendSlice(alloc, "\""); 701 try out.appendSlice(alloc, style_attr); 702 try out.appendSlice(alloc, ">"); 703 }, 704 .plain => { 705 try out.appendSlice(alloc, "<span"); 706 try out.appendSlice(alloc, style_attr); 707 try out.appendSlice(alloc, ">"); 708 }, 709 } 710 } 711 712 fn closeTag(self: @This()) []const u8 { 713 return switch (self) { 714 .span, .plain => "</span>", 715 .a => "</a>", 716 }; 717 } 718 }; 719 720 // emit this panel's grid as rows of text, coalescing adjacent cells that 721 // share a focus id and colors into one tag (a clickable span, a link, or a 722 // plain colored span). cells under a child scroll keep only their background. 723 for (0..grid.size.height) |y| { 724 var cur_id: ?usize = null; 725 var cur_fg: ?Grid.Color = null; 726 var cur_bg: ?Grid.Color = null; 727 var open_tag: ?CellTag = null; 728 var first = true; 729 for (0..grid.size.width) |x| { 730 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 731 // a cell covered by a child scroll's viewport is drawn by that scroll's 732 // own div, so blank its glyph and make it non-clickable here — but keep 733 // its background, so the backdrop still shows through the scroll's 734 // transparent div instead of a bare hole. 735 const covered_by_scroll = blk: { 736 for (direct.items) |id| { 737 const r = (focus.children.get(id) orelse continue).rect; 738 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; 739 } 740 break :blk false; 741 }; 742 // the focusable cell at (x, y) among this panel's own focusables (skipping 743 // any that belong to a child scroll, whose cells are drawn in their own 744 // panel); none for a covered cell. 745 const cell_id = if (covered_by_scroll) null else blk: { 746 var iter = focus.children.iterator(); 747 while (iter.next()) |entry| { 748 const child = entry.value_ptr.*; 749 if (!child.focus.focusable) continue; 750 if (excluded.contains(entry.key_ptr.*)) continue; 751 const r = child.rect; 752 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 753 break :blk entry.key_ptr.*; 754 } 755 } 756 break :blk null; 757 }; 758 const fg = if (covered_by_scroll) null else cell.style.fg; 759 const bg = cell.style.bg; 760 761 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 762 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 763 764 var new_tag: ?CellTag = null; 765 if (cell_id) |id| { 766 if (focus.children.get(id)) |child| { 767 new_tag = switch (child.focus.kind) { 768 .custom => |custom| CellTag.init(custom), 769 else => .span, 770 }; 771 } 772 } 773 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 774 775 if (new_tag) |t| { 776 var style_buf: [64]u8 = undefined; 777 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 778 } 779 780 open_tag = new_tag; 781 cur_id = cell_id; 782 cur_fg = fg; 783 cur_bg = bg; 784 first = false; 785 } 786 787 try appendEscapedHtml(allocator, output, if (covered_by_scroll) " " else (cell.rune orelse " ")); 788 } 789 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 790 try output.append(allocator, '\n'); 791 } 792 793 // each child scroll becomes a natively-scrollable div positioned over its 794 // viewport, holding its full content rendered recursively. 795 for (direct.items) |id| { 796 const child = focus.children.get(id) orelse continue; 797 const info = child.focus.scroll orelse continue; 798 const r = child.rect; 799 // overflow only on the axes the widget scrolls; `auto` shows a bar only 800 // when that axis actually overflows. the other axis is clipped (hidden), 801 // matching how the terminal Scroll handles its non-scrolling axis. 802 const overflow = switch (info.direction) { 803 .vert => "overflow-x:hidden;overflow-y:auto", 804 .horiz => "overflow-x:auto;overflow-y:hidden", 805 .both => "overflow:auto", 806 }; 807 // the id carries a content version so JS preserves the native scroll 808 // position across re-renders of the same content but resets it when the 809 // content is replaced — e.g. selecting a different commit. the widget's 810 // scroll offset (in cells) rides along so JS can apply it when it has no 811 // preserved position, letting a wasm-side scrollToRect (the files list 812 // scrolling to its selected row on page load) reach the browser. 813 var buf: [224]u8 = undefined; 814 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, "<div class=\"scroll\" data-scroll-id=\"{d}-{d}\" 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, info.offset_x, info.offset_y, r.x, r.y, r.size.width, r.size.height, overflow })); 815 try renderPanel(allocator, output, child.focus, info.content); 816 try output.appendSlice(allocator, "</div>"); 817 } 818 } 819 820 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 821 // widget tree, each wrapping the text inputs and submit button inside it, 822 // positioned absolutely over the matching grid cells. 823 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 824 const root_focus = root.getFocus(); 825 826 var out: std.ArrayList(u8) = .empty; 827 errdefer out.deinit(allocator); 828 829 const form_prefix = "form:"; 830 831 // Focus.children is an AutoArrayHashMap that preserves insertion order, 832 // which matches the order widgets were added in code 833 var iter = root_focus.children.iterator(); 834 while (iter.next()) |entry| { 835 const child = entry.value_ptr.*; 836 const action_url = switch (child.focus.kind) { 837 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 838 custom[form_prefix.len..] 839 else 840 continue, 841 else => continue, 842 }; 843 844 try out.appendSlice(allocator, "<form action=\""); 845 try appendEscapedHtml(allocator, &out, action_url); 846 try out.appendSlice(allocator, "\" method=\"post\""); 847 // an empty action must not POST — block it and send the input to the TUI instead 848 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 849 try out.appendSlice(allocator, ">"); 850 851 // form.focus.children was populated by addChild, which flattens the 852 // whole subtree into one map — so descendants (inputs + the submit 853 // button) all appear here. positions on form.focus are relative to 854 // the form, so we look up absolute rects via root_focus for layout. 855 var inner_iter = child.focus.children.iterator(); 856 while (inner_iter.next()) |inner_entry| { 857 const inner_id = inner_entry.key_ptr.*; 858 const root_child = root_focus.children.get(inner_id) orelse continue; 859 const r = root_child.rect; 860 switch (root_child.focus.kind) { 861 .text_input, .text_input_password => { 862 const ti = session.text_inputs.get(inner_id) orelse continue; 863 const inner_left = r.x + 1; 864 const inner_top = r.y + 1; 865 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 866 867 try out.appendSlice(allocator, "<input type=\""); 868 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 869 try out.appendSlice(allocator, "\" data-focus-id=\""); 870 var id_buf: [32]u8 = undefined; 871 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 872 if (ti.options.name.len > 0) { 873 try out.appendSlice(allocator, "\" name=\""); 874 try appendEscapedHtml(allocator, &out, ti.options.name); 875 } 876 // intentionally no `value` attribute: the browser tracks user input 877 // natively, and including the wasm-side value here would make the 878 // overlay HTML differ on every keystroke — that would trip the diff 879 // in _setOverlay and rebuild the <input>, eating the user's caret. 880 try out.appendSlice(allocator, "\" style=\"left:"); 881 var pos_buf: [64]u8 = undefined; 882 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 })); 883 try out.appendSlice(allocator, "\">"); 884 }, 885 .text_area => { 886 const ti = session.text_inputs.get(inner_id) orelse continue; 887 const inner_left = r.x + 1; 888 const inner_top = r.y + 1; 889 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 890 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 891 892 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 893 var id_buf: [32]u8 = undefined; 894 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 895 if (ti.options.name.len > 0) { 896 try out.appendSlice(allocator, "\" name=\""); 897 try appendEscapedHtml(allocator, &out, ti.options.name); 898 } 899 // like the input above, no content inside: the browser 900 // tracks the value and the overlay diff must stay stable 901 // across keystrokes 902 try out.appendSlice(allocator, "\" style=\"left:"); 903 var pos_buf: [128]u8 = undefined; 904 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 })); 905 try out.appendSlice(allocator, "\"></textarea>"); 906 }, 907 .custom => |custom| { 908 if (std.mem.eql(u8, "submit", custom)) { 909 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 910 var id_buf: [32]u8 = undefined; 911 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 912 try out.appendSlice(allocator, "\" style=\"left:"); 913 var pos_buf: [128]u8 = undefined; 914 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 })); 915 try out.appendSlice(allocator, "\"></button>"); 916 } 917 }, 918 else => {}, 919 } 920 } 921 922 try out.appendSlice(allocator, "</form>"); 923 } 924 925 return try out.toOwnedSlice(allocator); 926 } 927 928 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 929 if (a) |av| return if (b) |bv| av.eql(bv) else false; 930 return b == null; 931 } 932 933 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 934 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 935 // empty slice when neither is set. 936 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 937 if (fg == null and bg == null) return buf[0..0]; 938 const prefix = " style=\""; 939 @memcpy(buf[0..prefix.len], prefix); 940 var i: usize = prefix.len; 941 if (fg) |c| { 942 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]; 943 i += s.len; 944 } 945 if (bg) |c| { 946 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]; 947 i += s.len; 948 } 949 buf[i] = '"'; 950 i += 1; 951 return buf[0..i]; 952 } 953 954 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 955 for (input) |ch| { 956 switch (ch) { 957 '&' => try out.appendSlice(allocator, "&amp;"), 958 '<' => try out.appendSlice(allocator, "&lt;"), 959 '>' => try out.appendSlice(allocator, "&gt;"), 960 '"' => try out.appendSlice(allocator, "&quot;"), 961 '\'' => try out.appendSlice(allocator, "&#39;"), 962 else => try out.append(allocator, ch), 963 } 964 } 965 } 966 967 // --- helpers -------------------------------------------------------------- 968 969 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 970 var iter = request.iterateHeaders(); 971 while (iter.next()) |header| { 972 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 973 var pairs = std.mem.splitScalar(u8, header.value, ';'); 974 while (pairs.next()) |pair| { 975 const trimmed = std.mem.trim(u8, pair, " \t"); 976 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 977 if (std.mem.eql(u8, trimmed[0..eq], name)) { 978 return trimmed[eq + 1 ..]; 979 } 980 } 981 } 982 return null; 983 } 984 985 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 986 var iter = std.mem.splitScalar(u8, body, '&'); 987 while (iter.next()) |pair| { 988 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 989 if (std.mem.eql(u8, pair[0..eq], key)) { 990 return try decodeFormValue(allocator, pair[eq + 1 ..]); 991 } 992 } 993 return null; 994 } 995 996 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 997 var out: std.ArrayList(u8) = .empty; 998 errdefer out.deinit(allocator); 999 var i: usize = 0; 1000 while (i < encoded.len) : (i += 1) { 1001 switch (encoded[i]) { 1002 '+' => try out.append(allocator, ' '), 1003 '%' => { 1004 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1005 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1006 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1007 try out.append(allocator, hi * 16 + lo); 1008 i += 2; 1009 }, 1010 else => try out.append(allocator, encoded[i]), 1011 } 1012 } 1013 return try out.toOwnedSlice(allocator); 1014 } 1015 1016 // disk-backed web session store. each login mints a random, opaque token 1017 // (not the user's id) that is stored as a file named by the token hex, whose 1018 // contents are the raw user_id bytes. authenticating a request is a lookup of 1019 // the cookie's token; logout deletes the file, revoking the session. there is 1020 // deliberately no expiry — a session lives until logout. 1021 pub const SessionStore = struct { 1022 io: std.Io, 1023 dir: std.Io.Dir, 1024 1025 pub const token_hex_len = evt.event_id_size * 2; 1026 1027 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1028 try data_dir.createDirPath(io, "sessions"); 1029 const dir = try data_dir.openDir(io, "sessions", .{}); 1030 return .{ .io = io, .dir = dir }; 1031 } 1032 1033 pub fn deinit(self: SessionStore) void { 1034 self.dir.close(self.io); 1035 } 1036 1037 // mint a new session for user_id, returning the token hex to set as the 1038 // cookie value. 1039 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1040 var token: [evt.event_id_size]u8 = undefined; 1041 self.io.random(&token); 1042 const token_hex = std.fmt.bytesToHex(token, .lower); 1043 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1044 defer file.close(self.io); 1045 try file.writeStreamingAll(self.io, user_id); 1046 return token_hex; 1047 } 1048 1049 // resolve a cookie's token to its user_id. returns false (logged out) for a 1050 // missing, malformed, or unknown token. 1051 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1052 if (!isToken(token_hex)) return false; 1053 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1054 defer file.close(self.io); 1055 var storage: [evt.event_id_size]u8 = undefined; 1056 var file_reader = file.reader(self.io, &storage); 1057 file_reader.interface.readSliceAll(out) catch return false; 1058 return true; 1059 } 1060 1061 // revoke a session. a no-op for a missing or malformed token. 1062 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1063 if (!isToken(token_hex)) return; 1064 self.dir.deleteFile(self.io, token_hex) catch {}; 1065 } 1066 1067 // a token is exactly token_hex_len hex chars. validating before using the 1068 // value as a path keeps attacker-supplied cookies from escaping the 1069 // sessions dir (e.g. via "/" or ".." bytes). 1070 fn isToken(token_hex: []const u8) bool { 1071 if (token_hex.len != token_hex_len) return false; 1072 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1073 return true; 1074 } 1075 }; 1076