╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1718 const route = (switch (host) { 1719 .local => ui.RoutablePage.fromUrlLocal(base), 1720 .server => ui.RoutablePage.fromUrl(base), 1721 }) orelse return respondRepoNotFound(request); 1722 if (route != .repo_undo) return respondRepoNotFound(request); 1723 const target = route.repo_undo; 1724 var arena = std.heap.ArenaAllocator.init(allocator); 1725 defer arena.deinit(); 1726 const repo_base = if (target.name.len == 0) "" else try std.fmt.allocPrint(arena.allocator(), "/repo/{s}", .{target.name.slice()}); 1727 _ = (try authorizeWrite(io, allocator, &arena, request, host, repo_base, .owner)) orelse return; 1728 const resolved = (try requestRepoSource(io, allocator, host, repo_base)) orelse return respondRepoNotFound(request); 1729 defer resolved.deinit(allocator); 1730 (switch (action) { 1731 .undo => ui.Repo.Undo.execute(io, allocator, resolved.source, target.index orelse return respondRepoNotFound(request)), 1732 .clear => ui.Repo.Undo.clearHistory(io, allocator, resolved.source), 1733 }) catch |err| switch (err) { 1734 error.NotFound, error.InvalidHistoryIndex, error.TransactionNotFound => return respondRepoNotFound(request), 1735 else => return err, 1736 }; 1737 const location = try (ui.RoutablePage.repoUndoRoute(target.name.slice(), null) orelse return error.RouteTooLong).toUrl(&arena); 1738 try request.respond("", .{ .status = .see_other, .keep_alive = false, .extra_headers = &.{.{ .name = "location", .value = location }} }); 1739 } 1740 1741 fn handleSync( 1742 io: std.Io, 1743 request: *std.http.Server.Request, 1744 allocator: std.mem.Allocator, 1745 base: []const u8, 1746 source: ui.RepoSource, 1747 ) !void { 1748 if (base.len != 0) { 1749 try request.respond("not found", .{ 1750 .status = .not_found, 1751 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1752 }); 1753 return; 1754 } 1755 1756 var owned_failure: ?[]u8 = null; 1757 defer if (owned_failure) |message| allocator.free(message); 1758 const failure: ?[]const u8 = blk: { 1759 owned_failure = ui.Repo.Events.sync(io, allocator, source) catch |err| break :blk @errorName(err); 1760 break :blk owned_failure; 1761 }; 1762 if (failure) |message| { 1763 var encoded: std.Io.Writer.Allocating = .init(allocator); 1764 defer encoded.deinit(); 1765 try std.Uri.Component.percentEncode(&encoded.writer, message, struct { 1766 fn isUnreserved(c: u8) bool { 1767 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 1768 } 1769 }.isUnreserved); 1770 const cookie = try std.fmt.allocPrint( 1771 allocator, 1772 local_flash_cookie ++ "=" ++ local_sync_failure_prefix ++ "{s}; Path=/; HttpOnly; SameSite=Strict", 1773 .{encoded.written()}, 1774 ); 1775 defer allocator.free(cookie); 1776 try request.respond("", .{ 1777 .status = .see_other, 1778 .extra_headers = &.{ 1779 .{ .name = "location", .value = "/events" }, 1780 .{ .name = "set-cookie", .value = cookie }, 1781 }, 1782 }); 1783 return; 1784 } 1785 1786 try request.respond("", .{ 1787 .status = .see_other, 1788 .extra_headers = &.{ 1789 .{ .name = "location", .value = "/events" }, 1790 .{ .name = "set-cookie", .value = local_flash_cookie ++ "=; Path=/; Max-Age=0" }, 1791 }, 1792 }); 1793 } 1794 1795 fn renderIndexHtml( 1796 io: std.Io, 1797 allocator: std.mem.Allocator, 1798 host: Host, 1799 session_token: ?[]const u8, 1800 session_data: ui.Session.Data, 1801 ) ![]const u8 { 1802 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 1803 1804 var page_arena = std.heap.ArenaAllocator.init(allocator); 1805 defer page_arena.deinit(); 1806 1807 // the server admin repo must outlive the page build, since the session's 1808 // moment reads from it. 1809 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 1810 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 1811 1812 var session = switch (host) { 1813 .server => |server| blk: { 1814 // open the admin repo to read live user/repo data. 1815 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 1816 const repo = if (repo_maybe) |*repo| repo else unreachable; 1817 var session = try ui.Session.init(&page_arena, repo, session_data); 1818 // the session dropped a user whose account was removed, so revoke 1819 // the token that named them 1820 if (session_token) |token| { 1821 if (session.data.user_id == null) server.session_store.remove(token); 1822 } 1823 // give the page builders filesystem access to the on-disk repos (a 1824 // sibling "repos" dir next to the admin repo) so the Repo page can 1825 // read its files. 1826 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(server.admin_repo_path) orelse ".", "repos" }); 1827 break :blk session; 1828 }, 1829 .local => |local| ui.Session{ 1830 .data = session_data, 1831 .arena = &page_arena, 1832 .page_arena = &page_arena, 1833 .local = local, 1834 }, 1835 }; 1836 session.io = io; 1837 1838 var page = try ui.Page.init(session.page_arena, &session, session.data.current_page); 1839 var root = try ui.initRoot(allocator, &page, &session); 1840 defer root.deinit(allocator); 1841 1842 const snapshot: ui.Snapshot = .{ .page = page, .session = session.data }; 1843 1844 const content = try generateHtml(allocator, &root, &session); 1845 defer allocator.free(content); 1846 1847 // serialize the snapshot so the wasm side can parse it back without making 1848 // a second request. it's embedded raw in a <script type="application/json"> 1849 // block, whose content is raw text terminated only by "</script". in json, 1850 // '<' appears solely inside string values, so escaping every '<' (and '>' 1851 // for good measure) to its \uXXXX form yields equivalent json that can't 1852 // break out of the tag. 1853 var json: std.Io.Writer.Allocating = .init(allocator); 1854 defer json.deinit(); 1855 try std.json.Stringify.value(snapshot, .{}, &json.writer); 1856 1857 var json_escaped: std.ArrayList(u8) = .empty; 1858 defer json_escaped.deinit(allocator); 1859 for (json.written()) |c| switch (c) { 1860 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 1861 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 1862 else => try json_escaped.append(allocator, c), 1863 }; 1864 1865 var out: std.ArrayList(u8) = .empty; 1866 errdefer out.deinit(allocator); 1867 { 1868 var cursor: usize = 0; 1869 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 1870 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 1871 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 1872 }) |sub| { 1873 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 1874 try out.appendSlice(allocator, template[cursor..idx]); 1875 try out.appendSlice(allocator, sub.replacement); 1876 cursor = idx + sub.needle.len; 1877 } 1878 try out.appendSlice(allocator, template[cursor..]); 1879 } 1880 return try out.toOwnedSlice(allocator); 1881 } 1882 1883 fn findEmbed(request_path: []const u8) ?Embed { 1884 const path = if (std.mem.eql(u8, request_path, "/")) 1885 "index.html" 1886 else if (request_path.len > 1 and request_path[0] == '/') 1887 request_path[1..] 1888 else 1889 return null; 1890 1891 for (embeds) |embed| { 1892 if (std.mem.eql(u8, path, embed.path)) return embed; 1893 } 1894 return null; 1895 } 1896 1897 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 1898 // own absolutely-positioned, natively-scrollable <div> holding its full content, 1899 // rendered recursively so nested scrolls work. 1900 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1901 const grid = root.getGrid() orelse return error.MissingGrid; 1902 const root_focus = root.getFocus(); 1903 1904 var out: std.ArrayList(u8) = .empty; 1905 errdefer out.deinit(allocator); 1906 1907 switch (root.*) { 1908 .background => |*background| { 1909 if (background.art.getGrid()) |art| { 1910 var position_buf: [64]u8 = undefined; 1911 try out.appendSlice(allocator, try std.fmt.bufPrint(&position_buf, "<div class=\"ansi-art\" aria-hidden=\"true\" style=\"left:{d}ch\">", .{grid.size.width -| art.size.width})); 1912 try renderPanel(allocator, &out, background.art.getFocus(), art, session, root_focus); 1913 try out.appendSlice(allocator, "</div>"); 1914 } 1915 }, 1916 else => {}, 1917 } 1918 try out.appendSlice(allocator, "<div class=\"grid-content\" data-key=\"panel:root\">"); 1919 try renderPanel(allocator, &out, root_focus, grid, session, root_focus); 1920 try out.appendSlice(allocator, "</div>"); 1921 try renderForms(allocator, &out, root_focus); 1922 return try out.toOwnedSlice(allocator); 1923 } 1924 1925 // render one panel — a focus subtree and its content grid — as HTML, recursing 1926 // once per web-native Scroll inside it. the root panel is the whole page; each 1927 // Scroll becomes a nested, natively-scrollable div holding its full content. 1928 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 1929 // then the child scroll divs over those holes. 1930 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid, session: *ui.Session, root_focus: *Focus) !void { 1931 // `direct` is this panel's scroll children, each drawn as an overlaid div. 1932 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 1933 // plus their descendants, which the focus tree flattens into this panel's 1934 // children): the cell hit-test below skips them so this panel doesn't claim 1935 // cells that are really rendered inside a child scroll's own panel. 1936 // (scrolls aren't nested in practice, so every scroll child is direct here.) 1937 var direct: std.ArrayList(usize) = .empty; 1938 defer direct.deinit(allocator); 1939 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 1940 defer excluded.deinit(allocator); 1941 { 1942 var it = focus.children.iterator(); 1943 while (it.next()) |e| { 1944 if (e.value_ptr.focus.scroll == null) continue; 1945 try direct.append(allocator, e.key_ptr.*); 1946 try excluded.put(allocator, e.key_ptr.*, {}); 1947 var mit = e.value_ptr.focus.children.iterator(); 1948 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 1949 } 1950 } 1951 1952 // the HTML element a run of cells is wrapped in, chosen from the cell's 1953 // focusable kind 1954 const CellTag = union(enum) { 1955 span, // clickable focusable cell 1956 a: []const u8, // clickable focusable link 1957 plain, // non-focusable, colored 1958 1959 const a_prefix = "a:"; 1960 // an "in-page" anchor: rendered as a real <a href> so it works with js 1961 // disabled, but wasm handles it without navigating. 1962 fn init(str: []const u8) @This() { 1963 if (std.mem.startsWith(u8, str, ui.raw_link_prefix)) { 1964 return .{ .a = str[ui.raw_link_prefix.len..] }; 1965 } 1966 if (std.mem.startsWith(u8, str, ui.in_page_link_prefix)) { 1967 return .{ .a = str[ui.in_page_link_prefix.len..] }; 1968 } 1969 if (std.mem.startsWith(u8, str, a_prefix)) { 1970 return .{ .a = str[a_prefix.len..] }; 1971 } 1972 return .span; 1973 } 1974 1975 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 1976 var id_buf: [32]u8 = undefined; 1977 switch (self) { 1978 .span => { 1979 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 1980 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1981 try out.appendSlice(alloc, "\""); 1982 try out.appendSlice(alloc, style_attr); 1983 try out.appendSlice(alloc, ">"); 1984 }, 1985 .a => |href| { 1986 // tabindex=-1 keeps these out of the browser's tab order 1987 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 1988 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1989 try out.appendSlice(alloc, "\" href=\""); 1990 try appendEscapedHtml(alloc, out, href); 1991 try out.appendSlice(alloc, "\""); 1992 try out.appendSlice(alloc, style_attr); 1993 try out.appendSlice(alloc, ">"); 1994 }, 1995 .plain => { 1996 try out.appendSlice(alloc, "<span"); 1997 try out.appendSlice(alloc, style_attr); 1998 try out.appendSlice(alloc, ">"); 1999 }, 2000 } 2001 } 2002 2003 fn closeTag(self: @This()) []const u8 { 2004 return switch (self) { 2005 .span, .plain => "</span>", 2006 .a => "</a>", 2007 }; 2008 } 2009 }; 2010 2011 // the focusable owning each cell, among this panel's own (skipping any 2012 // that belong to a child scroll, whose cells are drawn in their own panel). 2013 // claimed in focus order, so the first focusable over a cell keeps it. 2014 // looking every focusable up for every cell is quadratic in a long list. 2015 const owners = try allocator.alloc(?usize, grid.size.width * grid.size.height); 2016 defer allocator.free(owners); 2017 @memset(owners, null); 2018 { 2019 var it = focus.children.iterator(); 2020 while (it.next()) |entry| { 2021 const child = entry.value_ptr.*; 2022 if (child.focus.mode != .all) continue; 2023 if (excluded.contains(entry.key_ptr.*)) continue; 2024 const r = child.rect; 2025 for (@min(r.y, grid.size.height)..@min(r.y + r.size.height, grid.size.height)) |y| { 2026 for (@min(r.x, grid.size.width)..@min(r.x + r.size.width, grid.size.width)) |x| { 2027 const owner = &owners[y * grid.size.width + x]; 2028 if (owner.* == null) owner.* = entry.key_ptr.*; 2029 } 2030 } 2031 } 2032 } 2033 2034 // the cells are the volatile part of a panel. js replaces this one subtree 2035 // wholesale while retaining the panel's native controls and scroll shells. 2036 try output.appendSlice(allocator, "<div class=\"grid-cells\">"); 2037 2038 // emit this panel's grid as rows of text, coalescing adjacent cells that 2039 // share a focus id and colors into one tag (a clickable span, a link, or a 2040 // plain colored span). cells under a child scroll keep only their background. 2041 for (0..grid.size.height) |y| { 2042 var cur_id: ?usize = null; 2043 var cur_fg: ?Grid.Color = null; 2044 var cur_bg: ?Grid.Color = null; 2045 var cur_inverted = false; 2046 var open_tag: ?CellTag = null; 2047 var first = true; 2048 for (0..grid.size.width) |x| { 2049 const cell = (try grid.cell(x, y)).*; 2050 // a cell covered by a child scroll's viewport is drawn by that scroll's 2051 // own div, so blank its glyph and make it non-clickable here — but keep 2052 // its background, so the backdrop still shows through the scroll's 2053 // transparent div instead of a bare hole. 2054 const covered_by_scroll = blk: { 2055 for (direct.items) |id| { 2056 const r = (focus.children.get(id) orelse continue).rect; 2057 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; 2058 } 2059 break :blk false; 2060 }; 2061 // the focusable owning the cell at (x, y); none for a covered cell. 2062 const cell_id = if (covered_by_scroll) null else owners[y * grid.size.width + x]; 2063 const fg = if (covered_by_scroll) null else cell.style.fg; 2064 const bg = cell.style.bg; 2065 const inverted = !covered_by_scroll and cell.style.inverted; 2066 2067 if (first or cell_id != cur_id or !std.meta.eql(fg, cur_fg) or !std.meta.eql(bg, cur_bg) or inverted != cur_inverted) { 2068 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2069 2070 var new_tag: ?CellTag = null; 2071 if (cell_id) |id| { 2072 if (focus.children.get(id)) |child| { 2073 new_tag = switch (child.focus.kind) { 2074 .custom => |custom| CellTag.init(custom), 2075 else => .span, 2076 }; 2077 } 2078 } 2079 if (new_tag == null and (fg != null or bg != null or inverted)) new_tag = .plain; 2080 2081 if (new_tag) |t| { 2082 var style_buf: [64]u8 = undefined; 2083 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg, inverted)); 2084 } 2085 2086 open_tag = new_tag; 2087 cur_id = cell_id; 2088 cur_fg = fg; 2089 cur_bg = bg; 2090 cur_inverted = inverted; 2091 first = false; 2092 } 2093 2094 if (covered_by_scroll) { 2095 try appendEscapedHtml(allocator, output, " "); 2096 } else if (cell.continuation) { 2097 // the wide rune to the left was emitted 2ch wide, covering this column 2098 } else if (cell.rune) |rune| { 2099 var encoded: [4]u8 = undefined; 2100 const encoded_len = try std.unicode.utf8Encode(rune, &encoded); 2101 const rune_text = encoded[0..encoded_len]; 2102 // a double-width rune is pinned inside a 2ch span so the 2103 // fallback glyph's advance width can't shift the rest of the row 2104 const wide = x + 1 < grid.size.width and (try grid.cell(x + 1, y)).continuation; 2105 if (wide) { 2106 try output.appendSlice(allocator, "<span class=\"w2\">"); 2107 try appendEscapedHtml(allocator, output, rune_text); 2108 try output.appendSlice(allocator, "</span>"); 2109 } else { 2110 try appendEscapedHtml(allocator, output, rune_text); 2111 } 2112 } else { 2113 try appendEscapedHtml(allocator, output, " "); 2114 } 2115 } 2116 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2117 try output.append(allocator, '\n'); 2118 } 2119 try output.appendSlice(allocator, "</div>"); 2120 2121 // native controls live in their panel, beside the replaceable cells. their 2122 // stable keys let JS update layout without recreating their DOM nodes, and 2123 // being actual descendants of a scroll gives them native movement/clipping. 2124 try renderPanelControls(allocator, output, focus, session, root_focus, &excluded); 2125 2126 // each child scroll becomes a natively-scrollable div positioned over its 2127 // viewport, holding its full content rendered recursively. 2128 for (direct.items) |id| { 2129 const child = focus.children.get(id) orelse continue; 2130 const info = child.focus.scroll orelse continue; 2131 const r = child.rect; 2132 // overflow only on the axes the widget scrolls; `auto` shows a bar only 2133 // when that axis actually overflows. the other axis is clipped (hidden), 2134 // matching how the terminal Scroll handles its non-scrolling axis. 2135 const overflow = switch (info.direction) { 2136 .vert => "overflow-x:hidden;overflow-y:auto", 2137 .horiz => "overflow-x:auto;overflow-y:hidden", 2138 .both => "overflow:auto", 2139 }; 2140 // the id carries a content version so JS preserves the native scroll 2141 // position across re-renders of the same content but resets it when the 2142 // content is replaced — e.g. selecting a different commit. the widget's 2143 // scroll offset (in cells) rides along so JS can apply it when it has no 2144 // preserved position, letting a wasm-side scrollToRect (the files list 2145 // scrolling to its selected row on page load) reach the browser. 2146 var buf: [256]u8 = undefined; 2147 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, "<div class=\"scroll\" data-key=\"scroll:{d}\" data-scroll-id=\"{d}-{d}\" data-scroll-direction=\"{s}\" data-scroll-x=\"{d}\" data-scroll-y=\"{d}\" style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em;{s}\">", .{ id, id, child.focus.version, @tagName(info.direction), info.offset_x, info.offset_y, r.x, r.y, r.size.width, r.size.height, overflow })); 2148 try renderPanel(allocator, output, child.focus, info.content, session, root_focus); 2149 try output.appendSlice(allocator, "</div>"); 2150 } 2151 } 2152 2153 const form_prefix = "form:"; 2154 const form_id_prefix = "haxy-form-"; 2155 2156 fn formAction(focus: *const Focus) ?[]const u8 { 2157 return switch (focus.kind) { 2158 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) custom[form_prefix.len..] else null, 2159 else => null, 2160 }; 2161 } 2162 2163 // find the form ancestor of a flattened focus-tree child. html's `form` 2164 // attribute then associates the control with that form without requiring the 2165 // form and control to share a DOM parent. 2166 fn formOwner(root_focus: *Focus, focus_id: usize) ?usize { 2167 var id = focus_id; 2168 while (root_focus.children.get(id)) |child| { 2169 const parent_id = child.parent_id; 2170 if (parent_id == root_focus.id) return if (formAction(root_focus) != null) root_focus.id else null; 2171 const parent = root_focus.children.get(parent_id) orelse return null; 2172 if (formAction(parent.focus) != null) return parent_id; 2173 id = parent_id; 2174 } 2175 return null; 2176 } 2177 2178 fn appendFormAttribute(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus, focus_id: usize) !void { 2179 const form_id = formOwner(root_focus, focus_id) orelse return; 2180 var buf: [64]u8 = undefined; 2181 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, " form=\"" ++ form_id_prefix ++ "{d}\"", .{form_id})); 2182 } 2183 2184 fn renderPanelControls( 2185 allocator: std.mem.Allocator, 2186 output: *std.ArrayList(u8), 2187 focus: *Focus, 2188 session: *ui.Session, 2189 root_focus: *Focus, 2190 excluded: *const std.AutoHashMapUnmanaged(usize, void), 2191 ) !void { 2192 var iter = focus.children.iterator(); 2193 while (iter.next()) |entry| { 2194 const id = entry.key_ptr.*; 2195 if (excluded.contains(id)) continue; 2196 const child = entry.value_ptr.*; 2197 const r = child.rect; 2198 2199 if (r.size.width == 0 or r.size.height == 0) continue; // not laid out, rather than merely off-screen 2200 2201 switch (child.focus.kind) { 2202 .text_input, .text_input_password, .text_area => { 2203 const ti = session.text_inputs.get(id) orelse continue; 2204 2205 const inner_left = r.x + 1; 2206 const inner_top = r.y + 1; 2207 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 2208 const preserve = !ti.options.read_only; 2209 2210 if (child.focus.kind == .text_area) { 2211 const value = try ti.text(allocator); 2212 defer allocator.free(value); 2213 var id_buf: [128]u8 = undefined; 2214 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<textarea data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2215 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2216 try appendFormAttribute(allocator, output, root_focus, id); 2217 if (ti.options.name.len > 0) { 2218 try output.appendSlice(allocator, " name=\""); 2219 try appendEscapedHtml(allocator, output, ti.options.name); 2220 try output.append(allocator, '"'); 2221 } 2222 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 2223 var pos_buf: [128]u8 = undefined; 2224 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">\n", .{ inner_left, inner_top, inner_width, inner_height })); 2225 try appendEscapedHtml(allocator, output, value); 2226 try output.appendSlice(allocator, "</textarea>"); 2227 continue; 2228 } 2229 2230 var id_buf: [160]u8 = undefined; 2231 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<input type=\"{s}\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ if (child.focus.kind == .text_input_password) "password" else "text", id, id })); 2232 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2233 try appendFormAttribute(allocator, output, root_focus, id); 2234 if (ti.options.name.len > 0) { 2235 try output.appendSlice(allocator, " name=\""); 2236 try appendEscapedHtml(allocator, output, ti.options.name); 2237 try output.append(allocator, '"'); 2238 } 2239 if (child.focus.kind != .text_input_password) { 2240 const value = try ti.text(allocator); 2241 defer allocator.free(value); 2242 try output.appendSlice(allocator, " value=\""); 2243 try appendEscapedHtml(allocator, output, value); 2244 try output.append(allocator, '"'); 2245 } 2246 var pos_buf: [96]u8 = undefined; 2247 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:1em\">", .{ inner_left, inner_top, inner_width })); 2248 }, 2249 .custom => |custom| { 2250 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2251 if (formOwner(root_focus, id) == null) continue; 2252 var id_buf: [128]u8 = undefined; 2253 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2254 try appendFormAttribute(allocator, output, root_focus, id); 2255 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2256 try output.appendSlice(allocator, " formaction=\""); 2257 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 2258 try output.append(allocator, '"'); 2259 } 2260 var pos_buf: [128]u8 = undefined; 2261 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\"></button>", .{ r.x, r.y, r.size.width, r.size.height })); 2262 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 2263 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 2264 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 2265 var id_buf: [128]u8 = undefined; 2266 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "\" data-key=\"control:{d}\" data-focus-id=\"{d}\" style=\"opacity:0;left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">", .{ id, id, r.x, r.y, r.size.width, r.size.height })); 2267 } 2268 }, 2269 else => {}, 2270 } 2271 } 2272 } 2273 2274 // emit hidden form owners beside the rendered panels. their controls point 2275 // back here with the standard HTML `form` attribute. 2276 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 2277 // the focus child map preserves insertion order, which matches the order 2278 // widgets were added in code 2279 var iter = root_focus.children.iterator(); 2280 while (iter.next()) |entry| { 2281 const child = entry.value_ptr.*; 2282 const action_url = formAction(child.focus) orelse continue; 2283 2284 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 2285 var id_buf: [96]u8 = undefined; 2286 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 2287 try appendEscapedHtml(allocator, output, action_url); 2288 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 2289 } 2290 } 2291 2292 // the 16 ansi colors as the browser shows them (xterm's defaults) 2293 const ansi_palette = [16]Grid.Color.Rgb{ 2294 .{ .r = 0x00, .g = 0x00, .b = 0x00 }, .{ .r = 0xcd, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xcd, .b = 0x00 }, .{ .r = 0xcd, .g = 0xcd, .b = 0x00 }, 2295 .{ .r = 0x00, .g = 0x00, .b = 0xee }, .{ .r = 0xcd, .g = 0x00, .b = 0xcd }, .{ .r = 0x00, .g = 0xcd, .b = 0xcd }, .{ .r = 0xe5, .g = 0xe5, .b = 0xe5 }, 2296 .{ .r = 0x7f, .g = 0x7f, .b = 0x7f }, .{ .r = 0xff, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xff, .b = 0x00 }, .{ .r = 0xff, .g = 0xff, .b = 0x00 }, 2297 .{ .r = 0x5c, .g = 0x5c, .b = 0xff }, .{ .r = 0xff, .g = 0x00, .b = 0xff }, .{ .r = 0x00, .g = 0xff, .b = 0xff }, .{ .r = 0xff, .g = 0xff, .b = 0xff }, 2298 }; 2299 2300 // resolve any color to rgb: palette colors through the ansi table and the 2301 // xterm 256-color layout (16 ansi, a 6x6x6 cube, then 24 grays) 2302 fn colorRgb(color: Grid.Color) Grid.Color.Rgb { 2303 return switch (color) { 2304 .rgb => |c| c, 2305 .ansi => |a| ansi_palette[@intFromEnum(a)], 2306 .indexed => |n| if (n < 16) 2307 ansi_palette[n] 2308 else if (n < 232) blk: { 2309 const levels = [6]u8{ 0, 0x5f, 0x87, 0xaf, 0xd7, 0xff }; 2310 const i = n - 16; 2311 break :blk .{ .r = levels[i / 36], .g = levels[(i / 6) % 6], .b = levels[i % 6] }; 2312 } else blk: { 2313 const v: u8 = 8 + (n - 232) * 10; 2314 break :blk .{ .r = v, .g = v, .b = v }; 2315 }, 2316 }; 2317 } 2318 2319 // builds an HTML ` style="color:…;background-color:…"` attribute from a 2320 // cell's fg/bg into `buf`, omitting whichever color is unset. an inverted 2321 // cell swaps the two, falling back to the page's --fg/--bg variables for 2322 // whichever side is unset. returns an empty slice when nothing is set. 2323 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color, inverted: bool) []const u8 { 2324 if (fg == null and bg == null and !inverted) return buf[0..0]; 2325 const prefix = " style=\""; 2326 @memcpy(buf[0..prefix.len], prefix); 2327 var i: usize = prefix.len; 2328 i = cssColor(buf, i, "color", if (inverted) bg else fg, if (inverted) "var(--bg)" else null) orelse return buf[0..0]; 2329 i = cssColor(buf, i, "background-color", if (inverted) fg else bg, if (inverted) "var(--fg)" else null) orelse return buf[0..0]; 2330 buf[i] = '"'; 2331 return buf[0 .. i + 1]; 2332 } 2333 2334 // append `prop:value;` at buf[i..] for the color, or for the fallback when 2335 // the color is unset (nothing when both are). returns the new end, or null 2336 // when it doesn't fit. 2337 fn cssColor(buf: []u8, i: usize, prop: []const u8, color: ?Grid.Color, fallback: ?[]const u8) ?usize { 2338 const s = if (color) |c| blk: { 2339 const v = colorRgb(c); 2340 break :blk std.fmt.bufPrint(buf[i..], "{s}:#{x:0>2}{x:0>2}{x:0>2};", .{ prop, v.r, v.g, v.b }) catch return null; 2341 } else if (fallback) |f| 2342 std.fmt.bufPrint(buf[i..], "{s}:{s};", .{ prop, f }) catch return null 2343 else 2344 return i; 2345 return i + s.len; 2346 } 2347 2348 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2349 for (input) |ch| { 2350 switch (ch) { 2351 '&' => try out.appendSlice(allocator, "&amp;"), 2352 '<' => try out.appendSlice(allocator, "&lt;"), 2353 '>' => try out.appendSlice(allocator, "&gt;"), 2354 '"' => try out.appendSlice(allocator, "&quot;"), 2355 '\'' => try out.appendSlice(allocator, "&#39;"), 2356 else => try out.append(allocator, ch), 2357 } 2358 } 2359 } 2360 2361 // --- helpers -------------------------------------------------------------- 2362 2363 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 2364 var iter = request.iterateHeaders(); 2365 while (iter.next()) |header| { 2366 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2367 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2368 while (pairs.next()) |pair| { 2369 const trimmed = std.mem.trim(u8, pair, " \t"); 2370 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2371 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2372 return trimmed[eq + 1 ..]; 2373 } 2374 } 2375 } 2376 return null; 2377 } 2378 2379 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2380 var iter = std.mem.splitScalar(u8, body, '&'); 2381 while (iter.next()) |pair| { 2382 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2383 if (std.mem.eql(u8, pair[0..eq], key)) { 2384 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2385 } 2386 } 2387 return null; 2388 } 2389 2390 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2391 var buffer: [256]u8 = undefined; 2392 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2393 } 2394 2395 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2396 var out: std.ArrayList(u8) = .empty; 2397 errdefer out.deinit(allocator); 2398 var i: usize = 0; 2399 while (i < encoded.len) : (i += 1) { 2400 switch (encoded[i]) { 2401 '+' => try out.append(allocator, ' '), 2402 '%' => { 2403 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2404 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2405 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2406 try out.append(allocator, hi * 16 + lo); 2407 i += 2; 2408 }, 2409 else => try out.append(allocator, encoded[i]), 2410 } 2411 } 2412 return try out.toOwnedSlice(allocator); 2413 } 2414 2415 // disk-backed web session store. each login mints a random, opaque token 2416 // (not the user's id) that is stored as a file named by the token hex, whose 2417 // contents are the raw user_id bytes. authenticating a request is a lookup of 2418 // the cookie's token; logout deletes the file, revoking the session. there is 2419 // deliberately no expiry — a session lives until logout. form failures use 2420 // files in the flash subdirectory that the redirected GET consumes. the 2421 // directory is cleared whenever the server starts. 2422 pub const SessionStore = struct { 2423 io: std.Io, 2424 dir: std.Io.Dir, 2425 flash_dir: std.Io.Dir, 2426 auto_login: ?[token_hex_len]u8, 2427 2428 pub const token_hex_len = evt.event_id_size * 2; 2429 2430 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2431 try data_dir.createDirPath(io, "sessions"); 2432 const dir = try data_dir.openDir(io, "sessions", .{}); 2433 errdefer dir.close(io); 2434 try dir.deleteTree(io, "flash"); 2435 try dir.createDirPath(io, "flash"); 2436 const flash_dir = try dir.openDir(io, "flash", .{}); 2437 errdefer flash_dir.close(io); 2438 const auto_login = blk: { 2439 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2440 defer file.close(io); 2441 var token: [token_hex_len]u8 = undefined; 2442 var storage: [token_hex_len]u8 = undefined; 2443 var reader = file.reader(io, &storage); 2444 reader.interface.readSliceAll(&token) catch break :blk null; 2445 break :blk token; 2446 }; 2447 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 2448 } 2449 2450 pub fn deinit(self: SessionStore) void { 2451 self.flash_dir.close(self.io); 2452 self.dir.close(self.io); 2453 } 2454 2455 // mint a new session for user_id, returning the token hex to set as the 2456 // cookie value. 2457 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2458 var token: [evt.event_id_size]u8 = undefined; 2459 self.io.random(&token); 2460 const token_hex = std.fmt.bytesToHex(token, .lower); 2461 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2462 defer file.close(self.io); 2463 try file.writeStreamingAll(self.io, user_id); 2464 return token_hex; 2465 } 2466 2467 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 2468 var token: [evt.event_id_size]u8 = undefined; 2469 self.io.random(&token); 2470 const token_hex = std.fmt.bytesToHex(token, .lower); 2471 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 2472 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 2473 defer file.close(self.io); 2474 2475 var json: std.Io.Writer.Allocating = .init(allocator); 2476 defer json.deinit(); 2477 try std.json.Stringify.value(value, .{}, &json.writer); 2478 try file.writeStreamingAll(self.io, json.written()); 2479 return token_hex; 2480 } 2481 2482 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 2483 if (!isToken(token_hex)) return null; 2484 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 2485 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 2486 defer file.close(self.io); 2487 2488 var storage: [4096]u8 = undefined; 2489 var reader = file.reader(self.io, &storage); 2490 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 2491 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 2492 } 2493 2494 // resolve a cookie's token to its user_id. returns false (logged out) for a 2495 // missing, malformed, or unknown token. 2496 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2497 if (!isToken(token_hex)) return false; 2498 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2499 defer file.close(self.io); 2500 var storage: [evt.event_id_size]u8 = undefined; 2501 var file_reader = file.reader(self.io, &storage); 2502 file_reader.interface.readSliceAll(out) catch return false; 2503 return true; 2504 } 2505 2506 // revoke a session. a no-op for a missing or malformed token. 2507 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2508 if (!isToken(token_hex)) return; 2509 self.dir.deleteFile(self.io, token_hex) catch {}; 2510 } 2511 2512 // leave `token_hex`'s session for visitors arriving without one. only the 2513 // `try` fixture writes one. the name can't collide with a session token. 2514 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2515 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2516 defer file.close(self.io); 2517 try file.writeStreamingAll(self.io, token_hex); 2518 } 2519 2520 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2521 out.* = self.auto_login orelse return false; 2522 return true; 2523 } 2524 2525 const auto_login_name = "auto-login"; 2526 2527 // a token is exactly token_hex_len hex chars. validating before using the 2528 // value as a path keeps attacker-supplied cookies from escaping the 2529 // sessions dir (e.g. via "/" or ".." bytes). 2530 fn isToken(token_hex: []const u8) bool { 2531 if (token_hex.len != token_hex_len) return false; 2532 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2533 return true; 2534 } 2535 }; 2536