╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
761 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 762 try out.appendSlice(allocator, template[cursor..idx]); 763 try out.appendSlice(allocator, sub.replacement); 764 cursor = idx + sub.needle.len; 765 } 766 try out.appendSlice(allocator, template[cursor..]); 767 } 768 return try out.toOwnedSlice(allocator); 769 } 770 771 fn findEmbed(request_path: []const u8) ?Embed { 772 const path = if (std.mem.eql(u8, request_path, "/")) 773 "index.html" 774 else if (request_path.len > 1 and request_path[0] == '/') 775 request_path[1..] 776 else 777 return null; 778 779 for (embeds) |embed| { 780 if (std.mem.eql(u8, path, embed.path)) return embed; 781 } 782 return null; 783 } 784 785 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 786 // own absolutely-positioned, natively-scrollable <div> holding its full content, 787 // rendered recursively so nested scrolls work. 788 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 789 const grid = root.getGrid() orelse return error.MissingGrid; 790 791 var out: std.ArrayList(u8) = .empty; 792 errdefer out.deinit(allocator); 793 794 try renderPanel(allocator, &out, root.getFocus(), grid); 795 return try out.toOwnedSlice(allocator); 796 } 797 798 // render one panel — a focus subtree and its content grid — as HTML, recursing 799 // once per web-native Scroll inside it. the root panel is the whole page; each 800 // Scroll becomes a nested, natively-scrollable div holding its full content. 801 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 802 // then the child scroll divs over those holes. 803 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 804 // `direct` is this panel's scroll children, each drawn as an overlaid div. 805 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 806 // plus their descendants, which the focus tree flattens into this panel's 807 // children): the cell hit-test below skips them so this panel doesn't claim 808 // cells that are really rendered inside a child scroll's own panel. 809 // (scrolls aren't nested in practice, so every scroll child is direct here.) 810 var direct: std.ArrayList(usize) = .empty; 811 defer direct.deinit(allocator); 812 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 813 defer excluded.deinit(allocator); 814 { 815 var it = focus.children.iterator(); 816 while (it.next()) |e| { 817 if (e.value_ptr.focus.scroll == null) continue; 818 try direct.append(allocator, e.key_ptr.*); 819 try excluded.put(allocator, e.key_ptr.*, {}); 820 var mit = e.value_ptr.focus.children.iterator(); 821 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 822 } 823 } 824 825 // the HTML element a run of cells is wrapped in, chosen from the cell's 826 // focusable kind 827 const CellTag = union(enum) { 828 span, // clickable focusable cell 829 a: []const u8, // clickable focusable link 830 plain, // non-focusable, colored 831 832 const a_prefix = "a:"; 833 // an "in-page" anchor: rendered as a real <a href> so it works with js 834 // disabled, but crossPageLink ignores it, so with wasm the click just 835 // moves focus rather than navigating. 836 const inpage_prefix = "ai:"; 837 838 fn init(str: []const u8) @This() { 839 if (std.mem.startsWith(u8, str, inpage_prefix)) { 840 return .{ .a = str[inpage_prefix.len..] }; 841 } 842 if (std.mem.startsWith(u8, str, a_prefix)) { 843 return .{ .a = str[a_prefix.len..] }; 844 } 845 return .span; 846 } 847 848 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 849 var id_buf: [32]u8 = undefined; 850 switch (self) { 851 .span => { 852 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 853 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 854 try out.appendSlice(alloc, "\""); 855 try out.appendSlice(alloc, style_attr); 856 try out.appendSlice(alloc, ">"); 857 }, 858 .a => |href| { 859 // tabindex=-1 keeps these out of the browser's tab order 860 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 861 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 862 try out.appendSlice(alloc, "\" href=\""); 863 try appendEscapedHtml(alloc, out, href); 864 try out.appendSlice(alloc, "\""); 865 try out.appendSlice(alloc, style_attr); 866 try out.appendSlice(alloc, ">"); 867 }, 868 .plain => { 869 try out.appendSlice(alloc, "<span"); 870 try out.appendSlice(alloc, style_attr); 871 try out.appendSlice(alloc, ">"); 872 }, 873 } 874 } 875 876 fn closeTag(self: @This()) []const u8 { 877 return switch (self) { 878 .span, .plain => "</span>", 879 .a => "</a>", 880 }; 881 } 882 }; 883 884 // emit this panel's grid as rows of text, coalescing adjacent cells that 885 // share a focus id and colors into one tag (a clickable span, a link, or a 886 // plain colored span). cells under a child scroll keep only their background. 887 for (0..grid.size.height) |y| { 888 var cur_id: ?usize = null; 889 var cur_fg: ?Grid.Color = null; 890 var cur_bg: ?Grid.Color = null; 891 var open_tag: ?CellTag = null; 892 var first = true; 893 for (0..grid.size.width) |x| { 894 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 895 // a cell covered by a child scroll's viewport is drawn by that scroll's 896 // own div, so blank its glyph and make it non-clickable here — but keep 897 // its background, so the backdrop still shows through the scroll's 898 // transparent div instead of a bare hole. 899 const covered_by_scroll = blk: { 900 for (direct.items) |id| { 901 const r = (focus.children.get(id) orelse continue).rect; 902 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; 903 } 904 break :blk false; 905 }; 906 // the focusable cell at (x, y) among this panel's own focusables (skipping 907 // any that belong to a child scroll, whose cells are drawn in their own 908 // panel); none for a covered cell. 909 const cell_id = if (covered_by_scroll) null else blk: { 910 var iter = focus.children.iterator(); 911 while (iter.next()) |entry| { 912 const child = entry.value_ptr.*; 913 if (!child.focus.focusable) continue; 914 if (excluded.contains(entry.key_ptr.*)) continue; 915 const r = child.rect; 916 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 917 break :blk entry.key_ptr.*; 918 } 919 } 920 break :blk null; 921 }; 922 const fg = if (covered_by_scroll) null else cell.style.fg; 923 const bg = cell.style.bg; 924 925 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 926 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 927 928 var new_tag: ?CellTag = null; 929 if (cell_id) |id| { 930 if (focus.children.get(id)) |child| { 931 new_tag = switch (child.focus.kind) { 932 .custom => |custom| CellTag.init(custom), 933 else => .span, 934 }; 935 } 936 } 937 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 938 939 if (new_tag) |t| { 940 var style_buf: [64]u8 = undefined; 941 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 942 } 943 944 open_tag = new_tag; 945 cur_id = cell_id; 946 cur_fg = fg; 947 cur_bg = bg; 948 first = false; 949 } 950 951 if (covered_by_scroll) { 952 try appendEscapedHtml(allocator, output, " "); 953 } else if (cell.continuation) { 954 // the wide rune to the left was emitted 2ch wide, covering this column 955 } else if (cell.rune) |rune| { 956 // a double-width rune is pinned inside a 2ch span so the 957 // fallback glyph's advance width can't shift the rest of the row 958 const wide = x + 1 < grid.size.width and grid.cells.items[try grid.cells.at(.{ y, x + 1 })].continuation; 959 if (wide) { 960 try output.appendSlice(allocator, "<span class=\"w2\">"); 961 try appendEscapedHtml(allocator, output, rune); 962 try output.appendSlice(allocator, "</span>"); 963 } else { 964 try appendEscapedHtml(allocator, output, rune); 965 } 966 } else { 967 try appendEscapedHtml(allocator, output, " "); 968 } 969 } 970 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 971 try output.append(allocator, '\n'); 972 } 973 974 // each child scroll becomes a natively-scrollable div positioned over its 975 // viewport, holding its full content rendered recursively. 976 for (direct.items) |id| { 977 const child = focus.children.get(id) orelse continue; 978 const info = child.focus.scroll orelse continue; 979 const r = child.rect; 980 // overflow only on the axes the widget scrolls; `auto` shows a bar only 981 // when that axis actually overflows. the other axis is clipped (hidden), 982 // matching how the terminal Scroll handles its non-scrolling axis. 983 const overflow = switch (info.direction) { 984 .vert => "overflow-x:hidden;overflow-y:auto", 985 .horiz => "overflow-x:auto;overflow-y:hidden", 986 .both => "overflow:auto", 987 }; 988 // the id carries a content version so JS preserves the native scroll 989 // position across re-renders of the same content but resets it when the 990 // content is replaced — e.g. selecting a different commit. the widget's 991 // scroll offset (in cells) rides along so JS can apply it when it has no 992 // preserved position, letting a wasm-side scrollToRect (the files list 993 // scrolling to its selected row on page load) reach the browser. 994 var buf: [224]u8 = undefined; 995 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 })); 996 try renderPanel(allocator, output, child.focus, info.content); 997 try output.appendSlice(allocator, "</div>"); 998 } 999 } 1000 1001 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 1002 // widget tree, each wrapping the text inputs and submit button inside it, 1003 // positioned absolutely over the matching grid cells. 1004 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1005 const root_focus = root.getFocus(); 1006 1007 var out: std.ArrayList(u8) = .empty; 1008 errdefer out.deinit(allocator); 1009 1010 const form_prefix = "form:"; 1011 1012 // Focus.children is an AutoArrayHashMap that preserves insertion order, 1013 // which matches the order widgets were added in code 1014 var iter = root_focus.children.iterator(); 1015 while (iter.next()) |entry| { 1016 const child = entry.value_ptr.*; 1017 const action_url = switch (child.focus.kind) { 1018 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 1019 custom[form_prefix.len..] 1020 else 1021 continue, 1022 else => continue, 1023 }; 1024 1025 try out.appendSlice(allocator, "<form action=\""); 1026 try appendEscapedHtml(allocator, &out, action_url); 1027 try out.appendSlice(allocator, "\" method=\"post\""); 1028 // an empty action must not POST — block it and send the input to the TUI instead 1029 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 1030 try out.appendSlice(allocator, ">"); 1031 1032 // form.focus.children was populated by addChild, which flattens the 1033 // whole subtree into one map — so descendants (inputs + the submit 1034 // button) all appear here. positions on form.focus are relative to 1035 // the form, so we look up absolute rects via root_focus for layout. 1036 var inner_iter = child.focus.children.iterator(); 1037 while (inner_iter.next()) |inner_entry| { 1038 const inner_id = inner_entry.key_ptr.*; 1039 const root_child = root_focus.children.get(inner_id) orelse continue; 1040 const r = root_child.rect; 1041 switch (root_child.focus.kind) { 1042 .text_input, .text_input_password => { 1043 const ti = session.text_inputs.get(inner_id) orelse continue; 1044 const inner_left = r.x + 1; 1045 const inner_top = r.y + 1; 1046 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1047 1048 try out.appendSlice(allocator, "<input type=\""); 1049 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 1050 try out.appendSlice(allocator, "\" data-focus-id=\""); 1051 var id_buf: [32]u8 = undefined; 1052 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1053 if (ti.options.name.len > 0) { 1054 try out.appendSlice(allocator, "\" name=\""); 1055 try appendEscapedHtml(allocator, &out, ti.options.name); 1056 } 1057 // never the live content as the `value`: the browser tracks user 1058 // input natively, and including the wasm-side value here would make 1059 // the overlay HTML differ on every keystroke — that would trip the 1060 // diff in _setOverlay and rebuild the <input>, eating the user's 1061 // caret. a page-constant initial value is safe. 1062 if (session.input_values.get(inner_id)) |value| { 1063 try out.appendSlice(allocator, "\" value=\""); 1064 try appendEscapedHtml(allocator, &out, value); 1065 } 1066 try out.appendSlice(allocator, "\" style=\"left:"); 1067 var pos_buf: [64]u8 = undefined; 1068 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 })); 1069 try out.appendSlice(allocator, "\">"); 1070 }, 1071 .text_area => { 1072 const ti = session.text_inputs.get(inner_id) orelse continue; 1073 const inner_left = r.x + 1; 1074 const inner_top = r.y + 1; 1075 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1076 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 1077 1078 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 1079 var id_buf: [32]u8 = undefined; 1080 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1081 if (ti.options.name.len > 0) { 1082 try out.appendSlice(allocator, "\" name=\""); 1083 try appendEscapedHtml(allocator, &out, ti.options.name); 1084 } 1085 // like the input above, only a page-constant initial value 1086 // inside: the browser tracks the live value and the 1087 // overlay diff must stay stable across keystrokes 1088 try out.appendSlice(allocator, "\" style=\"left:"); 1089 var pos_buf: [128]u8 = undefined; 1090 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 })); 1091 try out.appendSlice(allocator, "\">"); 1092 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1093 try out.appendSlice(allocator, "</textarea>"); 1094 }, 1095 .custom => |custom| { 1096 if (std.mem.eql(u8, "submit", custom)) { 1097 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1098 var id_buf: [32]u8 = undefined; 1099 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1100 try out.appendSlice(allocator, "\" style=\"left:"); 1101 var pos_buf: [128]u8 = undefined; 1102 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 })); 1103 try out.appendSlice(allocator, "\"></button>"); 1104 } 1105 }, 1106 else => {}, 1107 } 1108 } 1109 1110 try out.appendSlice(allocator, "</form>"); 1111 } 1112 1113 return try out.toOwnedSlice(allocator); 1114 } 1115 1116 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1117 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1118 return b == null; 1119 } 1120 1121 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1122 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1123 // empty slice when neither is set. 1124 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1125 if (fg == null and bg == null) return buf[0..0]; 1126 const prefix = " style=\""; 1127 @memcpy(buf[0..prefix.len], prefix); 1128 var i: usize = prefix.len; 1129 if (fg) |c| { 1130 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]; 1131 i += s.len; 1132 } 1133 if (bg) |c| { 1134 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]; 1135 i += s.len; 1136 } 1137 buf[i] = '"'; 1138 i += 1; 1139 return buf[0..i]; 1140 } 1141 1142 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1143 for (input) |ch| { 1144 switch (ch) { 1145 '&' => try out.appendSlice(allocator, "&amp;"), 1146 '<' => try out.appendSlice(allocator, "&lt;"), 1147 '>' => try out.appendSlice(allocator, "&gt;"), 1148 '"' => try out.appendSlice(allocator, "&quot;"), 1149 '\'' => try out.appendSlice(allocator, "&#39;"), 1150 else => try out.append(allocator, ch), 1151 } 1152 } 1153 } 1154 1155 // --- helpers -------------------------------------------------------------- 1156 1157 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1158 var iter = request.iterateHeaders(); 1159 while (iter.next()) |header| { 1160 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1161 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1162 while (pairs.next()) |pair| { 1163 const trimmed = std.mem.trim(u8, pair, " \t"); 1164 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1165 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1166 return trimmed[eq + 1 ..]; 1167 } 1168 } 1169 } 1170 return null; 1171 } 1172 1173 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1174 var iter = std.mem.splitScalar(u8, body, '&'); 1175 while (iter.next()) |pair| { 1176 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1177 if (std.mem.eql(u8, pair[0..eq], key)) { 1178 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1179 } 1180 } 1181 return null; 1182 } 1183 1184 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1185 var out: std.ArrayList(u8) = .empty; 1186 errdefer out.deinit(allocator); 1187 var i: usize = 0; 1188 while (i < encoded.len) : (i += 1) { 1189 switch (encoded[i]) { 1190 '+' => try out.append(allocator, ' '), 1191 '%' => { 1192 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1193 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1194 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1195 try out.append(allocator, hi * 16 + lo); 1196 i += 2; 1197 }, 1198 else => try out.append(allocator, encoded[i]), 1199 } 1200 } 1201 return try out.toOwnedSlice(allocator); 1202 } 1203 1204 // disk-backed web session store. each login mints a random, opaque token 1205 // (not the user's id) that is stored as a file named by the token hex, whose 1206 // contents are the raw user_id bytes. authenticating a request is a lookup of 1207 // the cookie's token; logout deletes the file, revoking the session. there is 1208 // deliberately no expiry — a session lives until logout. 1209 pub const SessionStore = struct { 1210 io: std.Io, 1211 dir: std.Io.Dir, 1212 1213 pub const token_hex_len = evt.event_id_size * 2; 1214 1215 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1216 try data_dir.createDirPath(io, "sessions"); 1217 const dir = try data_dir.openDir(io, "sessions", .{}); 1218 return .{ .io = io, .dir = dir }; 1219 } 1220 1221 pub fn deinit(self: SessionStore) void { 1222 self.dir.close(self.io); 1223 } 1224 1225 // mint a new session for user_id, returning the token hex to set as the 1226 // cookie value. 1227 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1228 var token: [evt.event_id_size]u8 = undefined; 1229 self.io.random(&token); 1230 const token_hex = std.fmt.bytesToHex(token, .lower); 1231 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1232 defer file.close(self.io); 1233 try file.writeStreamingAll(self.io, user_id); 1234 return token_hex; 1235 } 1236 1237 // resolve a cookie's token to its user_id. returns false (logged out) for a 1238 // missing, malformed, or unknown token. 1239 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1240 if (!isToken(token_hex)) return false; 1241 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1242 defer file.close(self.io); 1243 var storage: [evt.event_id_size]u8 = undefined; 1244 var file_reader = file.reader(self.io, &storage); 1245 file_reader.interface.readSliceAll(out) catch return false; 1246 return true; 1247 } 1248 1249 // revoke a session. a no-op for a missing or malformed token. 1250 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1251 if (!isToken(token_hex)) return; 1252 self.dir.deleteFile(self.io, token_hex) catch {}; 1253 } 1254 1255 // leave `token_hex`'s session for the next visitor arriving without one. 1256 // only the `try` fixture writes one, and only a debug build honors it. the 1257 // name isn't token-shaped, so it can't collide with a session file. 1258 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 1259 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 1260 defer file.close(self.io); 1261 try file.writeStreamingAll(self.io, token_hex); 1262 } 1263 1264 // claim the offered session, if one is there. the delete picks the winner 1265 // of a race, so the offer is only ever taken once. a release build never 1266 // looks, because that would be an extra syscall for every GET request. 1267 pub fn claimAutoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 1268 if (builtin.mode != .Debug) return false; 1269 { 1270 const file = self.dir.openFile(self.io, auto_login_name, .{ .mode = .read_only }) catch return false; 1271 defer file.close(self.io); 1272 var storage: [token_hex_len]u8 = undefined; 1273 var file_reader = file.reader(self.io, &storage); 1274 file_reader.interface.readSliceAll(out) catch return false; 1275 } 1276 self.dir.deleteFile(self.io, auto_login_name) catch return false; 1277 return true; 1278 } 1279 1280 const auto_login_name = "auto-login"; 1281 1282 // a token is exactly token_hex_len hex chars. validating before using the 1283 // value as a path keeps attacker-supplied cookies from escaping the 1284 // sessions dir (e.g. via "/" or ".." bytes). 1285 fn isToken(token_hex: []const u8) bool { 1286 if (token_hex.len != token_hex_len) return false; 1287 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1288 return true; 1289 } 1290 }; 1291