╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1376 } 1377 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1378 try output.append(allocator, '\n'); 1379 } 1380 1381 // each child scroll becomes a natively-scrollable div positioned over its 1382 // viewport, holding its full content rendered recursively. 1383 for (direct.items) |id| { 1384 const child = focus.children.get(id) orelse continue; 1385 const info = child.focus.scroll orelse continue; 1386 const r = child.rect; 1387 // overflow only on the axes the widget scrolls; `auto` shows a bar only 1388 // when that axis actually overflows. the other axis is clipped (hidden), 1389 // matching how the terminal Scroll handles its non-scrolling axis. 1390 const overflow = switch (info.direction) { 1391 .vert => "overflow-x:hidden;overflow-y:auto", 1392 .horiz => "overflow-x:auto;overflow-y:hidden", 1393 .both => "overflow:auto", 1394 }; 1395 // the id carries a content version so JS preserves the native scroll 1396 // position across re-renders of the same content but resets it when the 1397 // content is replaced — e.g. selecting a different commit. the widget's 1398 // scroll offset (in cells) rides along so JS can apply it when it has no 1399 // preserved position, letting a wasm-side scrollToRect (the files list 1400 // scrolling to its selected row on page load) reach the browser. 1401 var buf: [224]u8 = undefined; 1402 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 })); 1403 try renderPanel(allocator, output, child.focus, info.content); 1404 try output.appendSlice(allocator, "</div>"); 1405 } 1406 } 1407 1408 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 1409 // widget tree, each wrapping the text inputs and submit button inside it, 1410 // positioned absolutely over the matching grid cells. 1411 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1412 const root_focus = root.getFocus(); 1413 1414 var out: std.ArrayList(u8) = .empty; 1415 errdefer out.deinit(allocator); 1416 1417 const form_prefix = "form:"; 1418 1419 // Focus.children is an AutoArrayHashMap that preserves insertion order, 1420 // which matches the order widgets were added in code 1421 var iter = root_focus.children.iterator(); 1422 while (iter.next()) |entry| { 1423 const child = entry.value_ptr.*; 1424 const action_url = switch (child.focus.kind) { 1425 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 1426 custom[form_prefix.len..] 1427 else 1428 continue, 1429 else => continue, 1430 }; 1431 1432 try out.appendSlice(allocator, "<form action=\""); 1433 try appendEscapedHtml(allocator, &out, action_url); 1434 try out.appendSlice(allocator, "\" method=\"post\""); 1435 // an empty action must not POST — block it and send the input to the TUI instead 1436 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 1437 try out.appendSlice(allocator, ">"); 1438 1439 // form.focus.children was populated by addChild, which flattens the 1440 // whole subtree into one map — so descendants (inputs + the submit 1441 // button) all appear here. positions on form.focus are relative to 1442 // the form, so we look up absolute rects via root_focus for layout. 1443 var inner_iter = child.focus.children.iterator(); 1444 while (inner_iter.next()) |inner_entry| { 1445 const inner_id = inner_entry.key_ptr.*; 1446 const root_child = root_focus.children.get(inner_id) orelse continue; 1447 const r = root_child.rect; 1448 switch (root_child.focus.kind) { 1449 .text_input, .text_input_password => { 1450 const ti = session.text_inputs.get(inner_id) orelse continue; 1451 const inner_left = r.x + 1; 1452 const inner_top = r.y + 1; 1453 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1454 1455 try out.appendSlice(allocator, "<input type=\""); 1456 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 1457 try out.appendSlice(allocator, if (action_url.len == 0) "\" readonly data-focus-id=\"" else "\" data-focus-id=\""); 1458 var id_buf: [32]u8 = undefined; 1459 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1460 if (ti.options.name.len > 0) { 1461 try out.appendSlice(allocator, "\" name=\""); 1462 try appendEscapedHtml(allocator, &out, ti.options.name); 1463 } 1464 // never the live content as the `value`: the browser tracks user 1465 // input natively, and including the wasm-side value here would make 1466 // the overlay HTML differ on every keystroke — that would trip the 1467 // diff in _setOverlay and rebuild the <input>, eating the user's 1468 // caret. a page-constant initial value is safe. 1469 if (session.input_values.get(inner_id)) |value| { 1470 try out.appendSlice(allocator, "\" value=\""); 1471 try appendEscapedHtml(allocator, &out, value); 1472 } 1473 try out.appendSlice(allocator, "\" style=\"left:"); 1474 var pos_buf: [64]u8 = undefined; 1475 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 })); 1476 try out.appendSlice(allocator, "\">"); 1477 }, 1478 .text_area => { 1479 const ti = session.text_inputs.get(inner_id) orelse continue; 1480 const inner_left = r.x + 1; 1481 const inner_top = r.y + 1; 1482 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1483 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 1484 1485 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 1486 var id_buf: [32]u8 = undefined; 1487 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1488 if (ti.options.name.len > 0) { 1489 try out.appendSlice(allocator, "\" name=\""); 1490 try appendEscapedHtml(allocator, &out, ti.options.name); 1491 } 1492 // like the input above, only a page-constant initial value 1493 // inside: the browser tracks the live value and the 1494 // overlay diff must stay stable across keystrokes 1495 try out.appendSlice(allocator, "\" style=\"left:"); 1496 var pos_buf: [128]u8 = undefined; 1497 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 })); 1498 // textarea discards the first newline immediately following 1499 // its start tag, so add one of our own so text that begins 1500 // with a newline doesn't lose it 1501 try out.appendSlice(allocator, "\">\n"); 1502 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1503 try out.appendSlice(allocator, "</textarea>"); 1504 }, 1505 .custom => |custom| { 1506 if (std.mem.eql(u8, "submit", custom)) { 1507 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1508 var id_buf: [32]u8 = undefined; 1509 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1510 try out.appendSlice(allocator, "\" style=\"left:"); 1511 var pos_buf: [128]u8 = undefined; 1512 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 })); 1513 try out.appendSlice(allocator, "\"></button>"); 1514 } 1515 }, 1516 else => {}, 1517 } 1518 } 1519 1520 try out.appendSlice(allocator, "</form>"); 1521 } 1522 1523 return try out.toOwnedSlice(allocator); 1524 } 1525 1526 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1527 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1528 return b == null; 1529 } 1530 1531 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1532 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1533 // empty slice when neither is set. 1534 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1535 if (fg == null and bg == null) return buf[0..0]; 1536 const prefix = " style=\""; 1537 @memcpy(buf[0..prefix.len], prefix); 1538 var i: usize = prefix.len; 1539 if (fg) |c| { 1540 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]; 1541 i += s.len; 1542 } 1543 if (bg) |c| { 1544 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]; 1545 i += s.len; 1546 } 1547 buf[i] = '"'; 1548 i += 1; 1549 return buf[0..i]; 1550 } 1551 1552 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1553 for (input) |ch| { 1554 switch (ch) { 1555 '&' => try out.appendSlice(allocator, "&amp;"), 1556 '<' => try out.appendSlice(allocator, "&lt;"), 1557 '>' => try out.appendSlice(allocator, "&gt;"), 1558 '"' => try out.appendSlice(allocator, "&quot;"), 1559 '\'' => try out.appendSlice(allocator, "&#39;"), 1560 else => try out.append(allocator, ch), 1561 } 1562 } 1563 } 1564 1565 // --- helpers -------------------------------------------------------------- 1566 1567 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1568 var iter = request.iterateHeaders(); 1569 while (iter.next()) |header| { 1570 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1571 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1572 while (pairs.next()) |pair| { 1573 const trimmed = std.mem.trim(u8, pair, " \t"); 1574 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1575 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1576 return trimmed[eq + 1 ..]; 1577 } 1578 } 1579 } 1580 return null; 1581 } 1582 1583 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1584 var iter = std.mem.splitScalar(u8, body, '&'); 1585 while (iter.next()) |pair| { 1586 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1587 if (std.mem.eql(u8, pair[0..eq], key)) { 1588 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1589 } 1590 } 1591 return null; 1592 } 1593 1594 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1595 var out: std.ArrayList(u8) = .empty; 1596 errdefer out.deinit(allocator); 1597 var i: usize = 0; 1598 while (i < encoded.len) : (i += 1) { 1599 switch (encoded[i]) { 1600 '+' => try out.append(allocator, ' '), 1601 '%' => { 1602 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1603 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1604 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1605 try out.append(allocator, hi * 16 + lo); 1606 i += 2; 1607 }, 1608 else => try out.append(allocator, encoded[i]), 1609 } 1610 } 1611 return try out.toOwnedSlice(allocator); 1612 } 1613 1614 // disk-backed web session store. each login mints a random, opaque token 1615 // (not the user's id) that is stored as a file named by the token hex, whose 1616 // contents are the raw user_id bytes. authenticating a request is a lookup of 1617 // the cookie's token; logout deletes the file, revoking the session. there is 1618 // deliberately no expiry — a session lives until logout. 1619 pub const SessionStore = struct { 1620 io: std.Io, 1621 dir: std.Io.Dir, 1622 1623 pub const token_hex_len = evt.event_id_size * 2; 1624 1625 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1626 try data_dir.createDirPath(io, "sessions"); 1627 const dir = try data_dir.openDir(io, "sessions", .{}); 1628 return .{ .io = io, .dir = dir }; 1629 } 1630 1631 pub fn deinit(self: SessionStore) void { 1632 self.dir.close(self.io); 1633 } 1634 1635 // mint a new session for user_id, returning the token hex to set as the 1636 // cookie value. 1637 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1638 var token: [evt.event_id_size]u8 = undefined; 1639 self.io.random(&token); 1640 const token_hex = std.fmt.bytesToHex(token, .lower); 1641 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1642 defer file.close(self.io); 1643 try file.writeStreamingAll(self.io, user_id); 1644 return token_hex; 1645 } 1646 1647 // resolve a cookie's token to its user_id. returns false (logged out) for a 1648 // missing, malformed, or unknown token. 1649 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1650 if (!isToken(token_hex)) return false; 1651 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1652 defer file.close(self.io); 1653 var storage: [evt.event_id_size]u8 = undefined; 1654 var file_reader = file.reader(self.io, &storage); 1655 file_reader.interface.readSliceAll(out) catch return false; 1656 return true; 1657 } 1658 1659 // revoke a session. a no-op for a missing or malformed token. 1660 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1661 if (!isToken(token_hex)) return; 1662 self.dir.deleteFile(self.io, token_hex) catch {}; 1663 } 1664 1665 // leave `token_hex`'s session for the next visitor arriving without one. 1666 // only the `try` fixture writes one, and only a debug build honors it. the 1667 // name isn't token-shaped, so it can't collide with a session file. 1668 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 1669 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 1670 defer file.close(self.io); 1671 try file.writeStreamingAll(self.io, token_hex); 1672 } 1673 1674 // claim the offered session, if one is there. the delete picks the winner 1675 // of a race, so the offer is only ever taken once. a release build never 1676 // looks, because that would be an extra syscall for every GET request. 1677 pub fn claimAutoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 1678 if (builtin.mode != .Debug) return false; 1679 { 1680 const file = self.dir.openFile(self.io, auto_login_name, .{ .mode = .read_only }) catch return false; 1681 defer file.close(self.io); 1682 var storage: [token_hex_len]u8 = undefined; 1683 var file_reader = file.reader(self.io, &storage); 1684 file_reader.interface.readSliceAll(out) catch return false; 1685 } 1686 self.dir.deleteFile(self.io, auto_login_name) catch return false; 1687 return true; 1688 } 1689 1690 const auto_login_name = "auto-login"; 1691 1692 // a token is exactly token_hex_len hex chars. validating before using the 1693 // value as a path keeps attacker-supplied cookies from escaping the 1694 // sessions dir (e.g. via "/" or ".." bytes). 1695 fn isToken(token_hex: []const u8) bool { 1696 if (token_hex.len != token_hex_len) return false; 1697 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1698 return true; 1699 } 1700 }; 1701