╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1125 // (scrolls aren't nested in practice, so every scroll child is direct here.) 1126 var direct: std.ArrayList(usize) = .empty; 1127 defer direct.deinit(allocator); 1128 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 1129 defer excluded.deinit(allocator); 1130 { 1131 var it = focus.children.iterator(); 1132 while (it.next()) |e| { 1133 if (e.value_ptr.focus.scroll == null) continue; 1134 try direct.append(allocator, e.key_ptr.*); 1135 try excluded.put(allocator, e.key_ptr.*, {}); 1136 var mit = e.value_ptr.focus.children.iterator(); 1137 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 1138 } 1139 } 1140 1141 // the HTML element a run of cells is wrapped in, chosen from the cell's 1142 // focusable kind 1143 const CellTag = union(enum) { 1144 span, // clickable focusable cell 1145 a: []const u8, // clickable focusable link 1146 plain, // non-focusable, colored 1147 1148 const a_prefix = "a:"; 1149 // an "in-page" anchor: rendered as a real <a href> so it works with js 1150 // disabled, but crossPageLink ignores it, so with wasm the click just 1151 // moves focus rather than navigating. 1152 const inpage_prefix = "ai:"; 1153 1154 fn init(str: []const u8) @This() { 1155 if (std.mem.startsWith(u8, str, inpage_prefix)) { 1156 return .{ .a = str[inpage_prefix.len..] }; 1157 } 1158 if (std.mem.startsWith(u8, str, a_prefix)) { 1159 return .{ .a = str[a_prefix.len..] }; 1160 } 1161 return .span; 1162 } 1163 1164 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 1165 var id_buf: [32]u8 = undefined; 1166 switch (self) { 1167 .span => { 1168 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 1169 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1170 try out.appendSlice(alloc, "\""); 1171 try out.appendSlice(alloc, style_attr); 1172 try out.appendSlice(alloc, ">"); 1173 }, 1174 .a => |href| { 1175 // tabindex=-1 keeps these out of the browser's tab order 1176 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 1177 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1178 try out.appendSlice(alloc, "\" href=\""); 1179 try appendEscapedHtml(alloc, out, href); 1180 try out.appendSlice(alloc, "\""); 1181 try out.appendSlice(alloc, style_attr); 1182 try out.appendSlice(alloc, ">"); 1183 }, 1184 .plain => { 1185 try out.appendSlice(alloc, "<span"); 1186 try out.appendSlice(alloc, style_attr); 1187 try out.appendSlice(alloc, ">"); 1188 }, 1189 } 1190 } 1191 1192 fn closeTag(self: @This()) []const u8 { 1193 return switch (self) { 1194 .span, .plain => "</span>", 1195 .a => "</a>", 1196 }; 1197 } 1198 }; 1199 1200 // emit this panel's grid as rows of text, coalescing adjacent cells that 1201 // share a focus id and colors into one tag (a clickable span, a link, or a 1202 // plain colored span). cells under a child scroll keep only their background. 1203 for (0..grid.size.height) |y| { 1204 var cur_id: ?usize = null; 1205 var cur_fg: ?Grid.Color = null; 1206 var cur_bg: ?Grid.Color = null; 1207 var open_tag: ?CellTag = null; 1208 var first = true; 1209 for (0..grid.size.width) |x| { 1210 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 1211 // a cell covered by a child scroll's viewport is drawn by that scroll's 1212 // own div, so blank its glyph and make it non-clickable here — but keep 1213 // its background, so the backdrop still shows through the scroll's 1214 // transparent div instead of a bare hole. 1215 const covered_by_scroll = blk: { 1216 for (direct.items) |id| { 1217 const r = (focus.children.get(id) orelse continue).rect; 1218 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; 1219 } 1220 break :blk false; 1221 }; 1222 // the focusable cell at (x, y) among this panel's own focusables (skipping 1223 // any that belong to a child scroll, whose cells are drawn in their own 1224 // panel); none for a covered cell. 1225 const cell_id = if (covered_by_scroll) null else blk: { 1226 var iter = focus.children.iterator(); 1227 while (iter.next()) |entry| { 1228 const child = entry.value_ptr.*; 1229 if (!child.focus.focusable) continue; 1230 if (excluded.contains(entry.key_ptr.*)) continue; 1231 const r = child.rect; 1232 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 1233 break :blk entry.key_ptr.*; 1234 } 1235 } 1236 break :blk null; 1237 }; 1238 const fg = if (covered_by_scroll) null else cell.style.fg; 1239 const bg = cell.style.bg; 1240 1241 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 1242 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1243 1244 var new_tag: ?CellTag = null; 1245 if (cell_id) |id| { 1246 if (focus.children.get(id)) |child| { 1247 new_tag = switch (child.focus.kind) { 1248 .custom => |custom| CellTag.init(custom), 1249 else => .span, 1250 }; 1251 } 1252 } 1253 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 1254 1255 if (new_tag) |t| { 1256 var style_buf: [64]u8 = undefined; 1257 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 1258 } 1259 1260 open_tag = new_tag; 1261 cur_id = cell_id; 1262 cur_fg = fg; 1263 cur_bg = bg; 1264 first = false; 1265 } 1266 1267 if (covered_by_scroll) { 1268 try appendEscapedHtml(allocator, output, " "); 1269 } else if (cell.continuation) { 1270 // the wide rune to the left was emitted 2ch wide, covering this column 1271 } else if (cell.rune) |rune| { 1272 // a double-width rune is pinned inside a 2ch span so the 1273 // fallback glyph's advance width can't shift the rest of the row 1274 const wide = x + 1 < grid.size.width and grid.cells.items[try grid.cells.at(.{ y, x + 1 })].continuation; 1275 if (wide) { 1276 try output.appendSlice(allocator, "<span class=\"w2\">"); 1277 try appendEscapedHtml(allocator, output, rune); 1278 try output.appendSlice(allocator, "</span>"); 1279 } else { 1280 try appendEscapedHtml(allocator, output, rune); 1281 } 1282 } else { 1283 try appendEscapedHtml(allocator, output, " "); 1284 } 1285 } 1286 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1287 try output.append(allocator, '\n'); 1288 } 1289 1290 // each child scroll becomes a natively-scrollable div positioned over its 1291 // viewport, holding its full content rendered recursively. 1292 for (direct.items) |id| { 1293 const child = focus.children.get(id) orelse continue; 1294 const info = child.focus.scroll orelse continue; 1295 const r = child.rect; 1296 // overflow only on the axes the widget scrolls; `auto` shows a bar only 1297 // when that axis actually overflows. the other axis is clipped (hidden), 1298 // matching how the terminal Scroll handles its non-scrolling axis. 1299 const overflow = switch (info.direction) { 1300 .vert => "overflow-x:hidden;overflow-y:auto", 1301 .horiz => "overflow-x:auto;overflow-y:hidden", 1302 .both => "overflow:auto", 1303 }; 1304 // the id carries a content version so JS preserves the native scroll 1305 // position across re-renders of the same content but resets it when the 1306 // content is replaced — e.g. selecting a different commit. the widget's 1307 // scroll offset (in cells) rides along so JS can apply it when it has no 1308 // preserved position, letting a wasm-side scrollToRect (the files list 1309 // scrolling to its selected row on page load) reach the browser. 1310 var buf: [224]u8 = undefined; 1311 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 })); 1312 try renderPanel(allocator, output, child.focus, info.content); 1313 try output.appendSlice(allocator, "</div>"); 1314 } 1315 } 1316 1317 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 1318 // widget tree, each wrapping the text inputs and submit button inside it, 1319 // positioned absolutely over the matching grid cells. 1320 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1321 const root_focus = root.getFocus(); 1322 1323 var out: std.ArrayList(u8) = .empty; 1324 errdefer out.deinit(allocator); 1325 1326 const form_prefix = "form:"; 1327 1328 // Focus.children is an AutoArrayHashMap that preserves insertion order, 1329 // which matches the order widgets were added in code 1330 var iter = root_focus.children.iterator(); 1331 while (iter.next()) |entry| { 1332 const child = entry.value_ptr.*; 1333 const action_url = switch (child.focus.kind) { 1334 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 1335 custom[form_prefix.len..] 1336 else 1337 continue, 1338 else => continue, 1339 }; 1340 1341 try out.appendSlice(allocator, "<form action=\""); 1342 try appendEscapedHtml(allocator, &out, action_url); 1343 try out.appendSlice(allocator, "\" method=\"post\""); 1344 // an empty action must not POST — block it and send the input to the TUI instead 1345 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 1346 try out.appendSlice(allocator, ">"); 1347 1348 // form.focus.children was populated by addChild, which flattens the 1349 // whole subtree into one map — so descendants (inputs + the submit 1350 // button) all appear here. positions on form.focus are relative to 1351 // the form, so we look up absolute rects via root_focus for layout. 1352 var inner_iter = child.focus.children.iterator(); 1353 while (inner_iter.next()) |inner_entry| { 1354 const inner_id = inner_entry.key_ptr.*; 1355 const root_child = root_focus.children.get(inner_id) orelse continue; 1356 const r = root_child.rect; 1357 switch (root_child.focus.kind) { 1358 .text_input, .text_input_password => { 1359 const ti = session.text_inputs.get(inner_id) orelse continue; 1360 const inner_left = r.x + 1; 1361 const inner_top = r.y + 1; 1362 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1363 1364 try out.appendSlice(allocator, "<input type=\""); 1365 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 1366 try out.appendSlice(allocator, "\" data-focus-id=\""); 1367 var id_buf: [32]u8 = undefined; 1368 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1369 if (ti.options.name.len > 0) { 1370 try out.appendSlice(allocator, "\" name=\""); 1371 try appendEscapedHtml(allocator, &out, ti.options.name); 1372 } 1373 // never the live content as the `value`: the browser tracks user 1374 // input natively, and including the wasm-side value here would make 1375 // the overlay HTML differ on every keystroke — that would trip the 1376 // diff in _setOverlay and rebuild the <input>, eating the user's 1377 // caret. a page-constant initial value is safe. 1378 if (session.input_values.get(inner_id)) |value| { 1379 try out.appendSlice(allocator, "\" value=\""); 1380 try appendEscapedHtml(allocator, &out, value); 1381 } 1382 try out.appendSlice(allocator, "\" style=\"left:"); 1383 var pos_buf: [64]u8 = undefined; 1384 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 })); 1385 try out.appendSlice(allocator, "\">"); 1386 }, 1387 .text_area => { 1388 const ti = session.text_inputs.get(inner_id) orelse continue; 1389 const inner_left = r.x + 1; 1390 const inner_top = r.y + 1; 1391 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1392 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 1393 1394 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 1395 var id_buf: [32]u8 = undefined; 1396 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1397 if (ti.options.name.len > 0) { 1398 try out.appendSlice(allocator, "\" name=\""); 1399 try appendEscapedHtml(allocator, &out, ti.options.name); 1400 } 1401 // like the input above, only a page-constant initial value 1402 // inside: the browser tracks the live value and the 1403 // overlay diff must stay stable across keystrokes 1404 try out.appendSlice(allocator, "\" style=\"left:"); 1405 var pos_buf: [128]u8 = undefined; 1406 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 })); 1407 // textarea discards the first newline immediately following 1408 // its start tag, so add one of our own so text that begins 1409 // with a newline doesn't lose it 1410 try out.appendSlice(allocator, "\">\n"); 1411 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1412 try out.appendSlice(allocator, "</textarea>"); 1413 }, 1414 .custom => |custom| { 1415 if (std.mem.eql(u8, "submit", custom)) { 1416 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1417 var id_buf: [32]u8 = undefined; 1418 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1419 try out.appendSlice(allocator, "\" style=\"left:"); 1420 var pos_buf: [128]u8 = undefined; 1421 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 })); 1422 try out.appendSlice(allocator, "\"></button>"); 1423 } 1424 }, 1425 else => {}, 1426 } 1427 } 1428 1429 try out.appendSlice(allocator, "</form>"); 1430 } 1431 1432 return try out.toOwnedSlice(allocator); 1433 } 1434 1435 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1436 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1437 return b == null; 1438 } 1439 1440 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1441 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1442 // empty slice when neither is set. 1443 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1444 if (fg == null and bg == null) return buf[0..0]; 1445 const prefix = " style=\""; 1446 @memcpy(buf[0..prefix.len], prefix); 1447 var i: usize = prefix.len; 1448 if (fg) |c| { 1449 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]; 1450 i += s.len; 1451 } 1452 if (bg) |c| { 1453 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]; 1454 i += s.len; 1455 } 1456 buf[i] = '"'; 1457 i += 1; 1458 return buf[0..i]; 1459 } 1460 1461 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1462 for (input) |ch| { 1463 switch (ch) { 1464 '&' => try out.appendSlice(allocator, "&amp;"), 1465 '<' => try out.appendSlice(allocator, "&lt;"), 1466 '>' => try out.appendSlice(allocator, "&gt;"), 1467 '"' => try out.appendSlice(allocator, "&quot;"), 1468 '\'' => try out.appendSlice(allocator, "&#39;"), 1469 else => try out.append(allocator, ch), 1470 } 1471 } 1472 } 1473 1474 // --- helpers -------------------------------------------------------------- 1475 1476 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1477 var iter = request.iterateHeaders(); 1478 while (iter.next()) |header| { 1479 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1480 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1481 while (pairs.next()) |pair| { 1482 const trimmed = std.mem.trim(u8, pair, " \t"); 1483 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1484 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1485 return trimmed[eq + 1 ..]; 1486 } 1487 } 1488 } 1489 return null; 1490 } 1491 1492 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1493 var iter = std.mem.splitScalar(u8, body, '&'); 1494 while (iter.next()) |pair| { 1495 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1496 if (std.mem.eql(u8, pair[0..eq], key)) { 1497 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1498 } 1499 } 1500 return null; 1501 } 1502 1503 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1504 var out: std.ArrayList(u8) = .empty; 1505 errdefer out.deinit(allocator); 1506 var i: usize = 0; 1507 while (i < encoded.len) : (i += 1) { 1508 switch (encoded[i]) { 1509 '+' => try out.append(allocator, ' '), 1510 '%' => { 1511 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1512 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1513 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1514 try out.append(allocator, hi * 16 + lo); 1515 i += 2; 1516 }, 1517 else => try out.append(allocator, encoded[i]), 1518 } 1519 } 1520 return try out.toOwnedSlice(allocator); 1521 } 1522 1523 // disk-backed web session store. each login mints a random, opaque token 1524 // (not the user's id) that is stored as a file named by the token hex, whose 1525 // contents are the raw user_id bytes. authenticating a request is a lookup of 1526 // the cookie's token; logout deletes the file, revoking the session. there is 1527 // deliberately no expiry — a session lives until logout. 1528 pub const SessionStore = struct { 1529 io: std.Io, 1530 dir: std.Io.Dir, 1531 1532 pub const token_hex_len = evt.event_id_size * 2; 1533 1534 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1535 try data_dir.createDirPath(io, "sessions"); 1536 const dir = try data_dir.openDir(io, "sessions", .{}); 1537 return .{ .io = io, .dir = dir }; 1538 } 1539 1540 pub fn deinit(self: SessionStore) void { 1541 self.dir.close(self.io); 1542 } 1543 1544 // mint a new session for user_id, returning the token hex to set as the 1545 // cookie value. 1546 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1547 var token: [evt.event_id_size]u8 = undefined; 1548 self.io.random(&token); 1549 const token_hex = std.fmt.bytesToHex(token, .lower); 1550 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1551 defer file.close(self.io); 1552 try file.writeStreamingAll(self.io, user_id); 1553 return token_hex; 1554 } 1555 1556 // resolve a cookie's token to its user_id. returns false (logged out) for a 1557 // missing, malformed, or unknown token. 1558 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1559 if (!isToken(token_hex)) return false; 1560 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1561 defer file.close(self.io); 1562 var storage: [evt.event_id_size]u8 = undefined; 1563 var file_reader = file.reader(self.io, &storage); 1564 file_reader.interface.readSliceAll(out) catch return false; 1565 return true; 1566 } 1567 1568 // revoke a session. a no-op for a missing or malformed token. 1569 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1570 if (!isToken(token_hex)) return; 1571 self.dir.deleteFile(self.io, token_hex) catch {}; 1572 } 1573 1574 // leave `token_hex`'s session for the next visitor arriving without one. 1575 // only the `try` fixture writes one, and only a debug build honors it. the 1576 // name isn't token-shaped, so it can't collide with a session file. 1577 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 1578 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 1579 defer file.close(self.io); 1580 try file.writeStreamingAll(self.io, token_hex); 1581 } 1582 1583 // claim the offered session, if one is there. the delete picks the winner 1584 // of a race, so the offer is only ever taken once. a release build never 1585 // looks, because that would be an extra syscall for every GET request. 1586 pub fn claimAutoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 1587 if (builtin.mode != .Debug) return false; 1588 { 1589 const file = self.dir.openFile(self.io, auto_login_name, .{ .mode = .read_only }) catch return false; 1590 defer file.close(self.io); 1591 var storage: [token_hex_len]u8 = undefined; 1592 var file_reader = file.reader(self.io, &storage); 1593 file_reader.interface.readSliceAll(out) catch return false; 1594 } 1595 self.dir.deleteFile(self.io, auto_login_name) catch return false; 1596 return true; 1597 } 1598 1599 const auto_login_name = "auto-login"; 1600 1601 // a token is exactly token_hex_len hex chars. validating before using the 1602 // value as a path keeps attacker-supplied cookies from escaping the 1603 // sessions dir (e.g. via "/" or ".." bytes). 1604 fn isToken(token_hex: []const u8) bool { 1605 if (token_hex.len != token_hex_len) return false; 1606 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1607 return true; 1608 } 1609 }; 1610