╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1271 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 1272 1273 if (new_tag) |t| { 1274 var style_buf: [64]u8 = undefined; 1275 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 1276 } 1277 1278 open_tag = new_tag; 1279 cur_id = cell_id; 1280 cur_fg = fg; 1281 cur_bg = bg; 1282 first = false; 1283 } 1284 1285 if (covered_by_scroll) { 1286 try appendEscapedHtml(allocator, output, " "); 1287 } else if (cell.continuation) { 1288 // the wide rune to the left was emitted 2ch wide, covering this column 1289 } else if (cell.rune) |rune| { 1290 // a double-width rune is pinned inside a 2ch span so the 1291 // fallback glyph's advance width can't shift the rest of the row 1292 const wide = x + 1 < grid.size.width and grid.cells.items[try grid.cells.at(.{ y, x + 1 })].continuation; 1293 if (wide) { 1294 try output.appendSlice(allocator, "<span class=\"w2\">"); 1295 try appendEscapedHtml(allocator, output, rune); 1296 try output.appendSlice(allocator, "</span>"); 1297 } else { 1298 try appendEscapedHtml(allocator, output, rune); 1299 } 1300 } else { 1301 try appendEscapedHtml(allocator, output, " "); 1302 } 1303 } 1304 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1305 try output.append(allocator, '\n'); 1306 } 1307 1308 // each child scroll becomes a natively-scrollable div positioned over its 1309 // viewport, holding its full content rendered recursively. 1310 for (direct.items) |id| { 1311 const child = focus.children.get(id) orelse continue; 1312 const info = child.focus.scroll orelse continue; 1313 const r = child.rect; 1314 // overflow only on the axes the widget scrolls; `auto` shows a bar only 1315 // when that axis actually overflows. the other axis is clipped (hidden), 1316 // matching how the terminal Scroll handles its non-scrolling axis. 1317 const overflow = switch (info.direction) { 1318 .vert => "overflow-x:hidden;overflow-y:auto", 1319 .horiz => "overflow-x:auto;overflow-y:hidden", 1320 .both => "overflow:auto", 1321 }; 1322 // the id carries a content version so JS preserves the native scroll 1323 // position across re-renders of the same content but resets it when the 1324 // content is replaced — e.g. selecting a different commit. the widget's 1325 // scroll offset (in cells) rides along so JS can apply it when it has no 1326 // preserved position, letting a wasm-side scrollToRect (the files list 1327 // scrolling to its selected row on page load) reach the browser. 1328 var buf: [224]u8 = undefined; 1329 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 })); 1330 try renderPanel(allocator, output, child.focus, info.content); 1331 try output.appendSlice(allocator, "</div>"); 1332 } 1333 } 1334 1335 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 1336 // widget tree, each wrapping the text inputs and submit button inside it, 1337 // positioned absolutely over the matching grid cells. 1338 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1339 const root_focus = root.getFocus(); 1340 1341 var out: std.ArrayList(u8) = .empty; 1342 errdefer out.deinit(allocator); 1343 1344 const form_prefix = "form:"; 1345 1346 // Focus.children is an AutoArrayHashMap that preserves insertion order, 1347 // which matches the order widgets were added in code 1348 var iter = root_focus.children.iterator(); 1349 while (iter.next()) |entry| { 1350 const child = entry.value_ptr.*; 1351 const action_url = switch (child.focus.kind) { 1352 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 1353 custom[form_prefix.len..] 1354 else 1355 continue, 1356 else => continue, 1357 }; 1358 1359 try out.appendSlice(allocator, "<form action=\""); 1360 try appendEscapedHtml(allocator, &out, action_url); 1361 try out.appendSlice(allocator, "\" method=\"post\""); 1362 // an empty action must not POST — block it and send the input to the TUI instead 1363 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 1364 try out.appendSlice(allocator, ">"); 1365 1366 // form.focus.children was populated by addChild, which flattens the 1367 // whole subtree into one map — so descendants (inputs + the submit 1368 // button) all appear here. positions on form.focus are relative to 1369 // the form, so we look up absolute rects via root_focus for layout. 1370 var inner_iter = child.focus.children.iterator(); 1371 while (inner_iter.next()) |inner_entry| { 1372 const inner_id = inner_entry.key_ptr.*; 1373 const root_child = root_focus.children.get(inner_id) orelse continue; 1374 const r = root_child.rect; 1375 switch (root_child.focus.kind) { 1376 .text_input, .text_input_password => { 1377 const ti = session.text_inputs.get(inner_id) orelse continue; 1378 const inner_left = r.x + 1; 1379 const inner_top = r.y + 1; 1380 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1381 1382 try out.appendSlice(allocator, "<input type=\""); 1383 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 1384 try out.appendSlice(allocator, "\" data-focus-id=\""); 1385 var id_buf: [32]u8 = undefined; 1386 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1387 if (ti.options.name.len > 0) { 1388 try out.appendSlice(allocator, "\" name=\""); 1389 try appendEscapedHtml(allocator, &out, ti.options.name); 1390 } 1391 // never the live content as the `value`: the browser tracks user 1392 // input natively, and including the wasm-side value here would make 1393 // the overlay HTML differ on every keystroke — that would trip the 1394 // diff in _setOverlay and rebuild the <input>, eating the user's 1395 // caret. a page-constant initial value is safe. 1396 if (session.input_values.get(inner_id)) |value| { 1397 try out.appendSlice(allocator, "\" value=\""); 1398 try appendEscapedHtml(allocator, &out, value); 1399 } 1400 try out.appendSlice(allocator, "\" style=\"left:"); 1401 var pos_buf: [64]u8 = undefined; 1402 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 })); 1403 try out.appendSlice(allocator, "\">"); 1404 }, 1405 .text_area => { 1406 const ti = session.text_inputs.get(inner_id) orelse continue; 1407 const inner_left = r.x + 1; 1408 const inner_top = r.y + 1; 1409 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1410 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 1411 1412 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 1413 var id_buf: [32]u8 = undefined; 1414 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1415 if (ti.options.name.len > 0) { 1416 try out.appendSlice(allocator, "\" name=\""); 1417 try appendEscapedHtml(allocator, &out, ti.options.name); 1418 } 1419 // like the input above, only a page-constant initial value 1420 // inside: the browser tracks the live value and the 1421 // overlay diff must stay stable across keystrokes 1422 try out.appendSlice(allocator, "\" style=\"left:"); 1423 var pos_buf: [128]u8 = undefined; 1424 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 })); 1425 // textarea discards the first newline immediately following 1426 // its start tag, so add one of our own so text that begins 1427 // with a newline doesn't lose it 1428 try out.appendSlice(allocator, "\">\n"); 1429 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1430 try out.appendSlice(allocator, "</textarea>"); 1431 }, 1432 .custom => |custom| { 1433 if (std.mem.eql(u8, "submit", custom)) { 1434 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1435 var id_buf: [32]u8 = undefined; 1436 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1437 try out.appendSlice(allocator, "\" style=\"left:"); 1438 var pos_buf: [128]u8 = undefined; 1439 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 })); 1440 try out.appendSlice(allocator, "\"></button>"); 1441 } 1442 }, 1443 else => {}, 1444 } 1445 } 1446 1447 try out.appendSlice(allocator, "</form>"); 1448 } 1449 1450 return try out.toOwnedSlice(allocator); 1451 } 1452 1453 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1454 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1455 return b == null; 1456 } 1457 1458 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1459 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1460 // empty slice when neither is set. 1461 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1462 if (fg == null and bg == null) return buf[0..0]; 1463 const prefix = " style=\""; 1464 @memcpy(buf[0..prefix.len], prefix); 1465 var i: usize = prefix.len; 1466 if (fg) |c| { 1467 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]; 1468 i += s.len; 1469 } 1470 if (bg) |c| { 1471 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]; 1472 i += s.len; 1473 } 1474 buf[i] = '"'; 1475 i += 1; 1476 return buf[0..i]; 1477 } 1478 1479 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1480 for (input) |ch| { 1481 switch (ch) { 1482 '&' => try out.appendSlice(allocator, "&amp;"), 1483 '<' => try out.appendSlice(allocator, "&lt;"), 1484 '>' => try out.appendSlice(allocator, "&gt;"), 1485 '"' => try out.appendSlice(allocator, "&quot;"), 1486 '\'' => try out.appendSlice(allocator, "&#39;"), 1487 else => try out.append(allocator, ch), 1488 } 1489 } 1490 } 1491 1492 // --- helpers -------------------------------------------------------------- 1493 1494 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1495 var iter = request.iterateHeaders(); 1496 while (iter.next()) |header| { 1497 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1498 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1499 while (pairs.next()) |pair| { 1500 const trimmed = std.mem.trim(u8, pair, " \t"); 1501 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1502 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1503 return trimmed[eq + 1 ..]; 1504 } 1505 } 1506 } 1507 return null; 1508 } 1509 1510 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1511 var iter = std.mem.splitScalar(u8, body, '&'); 1512 while (iter.next()) |pair| { 1513 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1514 if (std.mem.eql(u8, pair[0..eq], key)) { 1515 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1516 } 1517 } 1518 return null; 1519 } 1520 1521 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1522 var out: std.ArrayList(u8) = .empty; 1523 errdefer out.deinit(allocator); 1524 var i: usize = 0; 1525 while (i < encoded.len) : (i += 1) { 1526 switch (encoded[i]) { 1527 '+' => try out.append(allocator, ' '), 1528 '%' => { 1529 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1530 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1531 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1532 try out.append(allocator, hi * 16 + lo); 1533 i += 2; 1534 }, 1535 else => try out.append(allocator, encoded[i]), 1536 } 1537 } 1538 return try out.toOwnedSlice(allocator); 1539 } 1540 1541 // disk-backed web session store. each login mints a random, opaque token 1542 // (not the user's id) that is stored as a file named by the token hex, whose 1543 // contents are the raw user_id bytes. authenticating a request is a lookup of 1544 // the cookie's token; logout deletes the file, revoking the session. there is 1545 // deliberately no expiry — a session lives until logout. 1546 pub const SessionStore = struct { 1547 io: std.Io, 1548 dir: std.Io.Dir, 1549 1550 pub const token_hex_len = evt.event_id_size * 2; 1551 1552 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1553 try data_dir.createDirPath(io, "sessions"); 1554 const dir = try data_dir.openDir(io, "sessions", .{}); 1555 return .{ .io = io, .dir = dir }; 1556 } 1557 1558 pub fn deinit(self: SessionStore) void { 1559 self.dir.close(self.io); 1560 } 1561 1562 // mint a new session for user_id, returning the token hex to set as the 1563 // cookie value. 1564 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1565 var token: [evt.event_id_size]u8 = undefined; 1566 self.io.random(&token); 1567 const token_hex = std.fmt.bytesToHex(token, .lower); 1568 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1569 defer file.close(self.io); 1570 try file.writeStreamingAll(self.io, user_id); 1571 return token_hex; 1572 } 1573 1574 // resolve a cookie's token to its user_id. returns false (logged out) for a 1575 // missing, malformed, or unknown token. 1576 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1577 if (!isToken(token_hex)) return false; 1578 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1579 defer file.close(self.io); 1580 var storage: [evt.event_id_size]u8 = undefined; 1581 var file_reader = file.reader(self.io, &storage); 1582 file_reader.interface.readSliceAll(out) catch return false; 1583 return true; 1584 } 1585 1586 // revoke a session. a no-op for a missing or malformed token. 1587 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1588 if (!isToken(token_hex)) return; 1589 self.dir.deleteFile(self.io, token_hex) catch {}; 1590 } 1591 1592 // leave `token_hex`'s session for the next visitor arriving without one. 1593 // only the `try` fixture writes one, and only a debug build honors it. the 1594 // name isn't token-shaped, so it can't collide with a session file. 1595 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 1596 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 1597 defer file.close(self.io); 1598 try file.writeStreamingAll(self.io, token_hex); 1599 } 1600 1601 // claim the offered session, if one is there. the delete picks the winner 1602 // of a race, so the offer is only ever taken once. a release build never 1603 // looks, because that would be an extra syscall for every GET request. 1604 pub fn claimAutoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 1605 if (builtin.mode != .Debug) return false; 1606 { 1607 const file = self.dir.openFile(self.io, auto_login_name, .{ .mode = .read_only }) catch return false; 1608 defer file.close(self.io); 1609 var storage: [token_hex_len]u8 = undefined; 1610 var file_reader = file.reader(self.io, &storage); 1611 file_reader.interface.readSliceAll(out) catch return false; 1612 } 1613 self.dir.deleteFile(self.io, auto_login_name) catch return false; 1614 return true; 1615 } 1616 1617 const auto_login_name = "auto-login"; 1618 1619 // a token is exactly token_hex_len hex chars. validating before using the 1620 // value as a path keeps attacker-supplied cookies from escaping the 1621 // sessions dir (e.g. via "/" or ".." bytes). 1622 fn isToken(token_hex: []const u8) bool { 1623 if (token_hex.len != token_hex_len) return false; 1624 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1625 return true; 1626 } 1627 }; 1628