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