╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1708 // whole subtree into one map — so descendants (inputs + the submit 1709 // button) all appear here. positions on form.focus are relative to 1710 // the form, so we look up absolute rects via root_focus for layout. 1711 var inner_iter = child.focus.children.iterator(); 1712 while (inner_iter.next()) |inner_entry| { 1713 const inner_id = inner_entry.key_ptr.*; 1714 const root_child = root_focus.children.get(inner_id) orelse continue; 1715 const r = root_child.rect; 1716 switch (root_child.focus.kind) { 1717 .text_input, .text_input_password => { 1718 const ti = session.text_inputs.get(inner_id) orelse continue; 1719 const inner_left = r.x + 1; 1720 const inner_top = r.y + 1; 1721 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1722 1723 try out.appendSlice(allocator, "<input type=\""); 1724 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 1725 try out.appendSlice(allocator, if (action_url.len == 0) "\" readonly data-focus-id=\"" else "\" data-focus-id=\""); 1726 var id_buf: [32]u8 = undefined; 1727 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1728 if (ti.options.name.len > 0) { 1729 try out.appendSlice(allocator, "\" name=\""); 1730 try appendEscapedHtml(allocator, &out, ti.options.name); 1731 } 1732 // never the live content as the `value`: the browser tracks user 1733 // input natively, and including the wasm-side value here would make 1734 // the overlay HTML differ on every keystroke — that would trip the 1735 // diff in _setOverlay and rebuild the <input>, eating the user's 1736 // caret. a page-constant initial value is safe. 1737 if (session.input_values.get(inner_id)) |value| { 1738 try out.appendSlice(allocator, "\" value=\""); 1739 try appendEscapedHtml(allocator, &out, value); 1740 } 1741 try out.appendSlice(allocator, "\" style=\"left:"); 1742 var pos_buf: [64]u8 = undefined; 1743 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 })); 1744 try out.appendSlice(allocator, "\">"); 1745 }, 1746 .text_area => { 1747 const ti = session.text_inputs.get(inner_id) orelse continue; 1748 const inner_left = r.x + 1; 1749 const inner_top = r.y + 1; 1750 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1751 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 1752 1753 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 1754 var id_buf: [32]u8 = undefined; 1755 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1756 if (ti.options.name.len > 0) { 1757 try out.appendSlice(allocator, "\" name=\""); 1758 try appendEscapedHtml(allocator, &out, ti.options.name); 1759 } 1760 // like the input above, only a page-constant initial value 1761 // inside: the browser tracks the live value and the 1762 // overlay diff must stay stable across keystrokes 1763 try out.appendSlice(allocator, "\" style=\"left:"); 1764 var pos_buf: [128]u8 = undefined; 1765 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 })); 1766 // textarea discards the first newline immediately following 1767 // its start tag, so add one of our own so text that begins 1768 // with a newline doesn't lose it 1769 try out.appendSlice(allocator, "\">\n"); 1770 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1771 try out.appendSlice(allocator, "</textarea>"); 1772 }, 1773 .custom => |custom| { 1774 if (std.mem.eql(u8, "submit", custom) or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 1775 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1776 var id_buf: [32]u8 = undefined; 1777 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1778 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 1779 try out.appendSlice(allocator, "\" formaction=\""); 1780 try appendEscapedHtml(allocator, &out, custom[ui.submit_action_prefix.len..]); 1781 } 1782 try out.appendSlice(allocator, "\" style=\"left:"); 1783 var pos_buf: [128]u8 = undefined; 1784 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 })); 1785 try out.appendSlice(allocator, "\"></button>"); 1786 } 1787 }, 1788 else => {}, 1789 } 1790 } 1791 1792 try out.appendSlice(allocator, "</form>"); 1793 } 1794 1795 // a file picker isn't part of a form: it posts its file straight to the url 1796 // in its marker. it sits transparent over the button the tui drew, so 1797 // clicking that button opens the browser's own dialog. 1798 var file_iter = root_focus.children.iterator(); 1799 while (file_iter.next()) |entry| { 1800 const child = entry.value_ptr.*; 1801 const action_url = switch (child.focus.kind) { 1802 .custom => |custom| if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) 1803 custom[ui.file_input_prefix.len..] 1804 else 1805 continue, 1806 else => continue, 1807 }; 1808 const r = child.rect; 1809 1810 try out.appendSlice(allocator, "<input type=\"file\" data-action=\""); 1811 try appendEscapedHtml(allocator, &out, action_url); 1812 try out.appendSlice(allocator, "\" data-focus-id=\""); 1813 var id_buf: [32]u8 = undefined; 1814 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{entry.key_ptr.*})); 1815 try out.appendSlice(allocator, "\" style=\"opacity:0;left:"); 1816 var pos_buf: [128]u8 = undefined; 1817 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 })); 1818 try out.appendSlice(allocator, "\">"); 1819 } 1820 1821 return try out.toOwnedSlice(allocator); 1822 } 1823 1824 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1825 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1826 return b == null; 1827 } 1828 1829 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1830 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1831 // empty slice when neither is set. 1832 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1833 if (fg == null and bg == null) return buf[0..0]; 1834 const prefix = " style=\""; 1835 @memcpy(buf[0..prefix.len], prefix); 1836 var i: usize = prefix.len; 1837 if (fg) |c| { 1838 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]; 1839 i += s.len; 1840 } 1841 if (bg) |c| { 1842 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]; 1843 i += s.len; 1844 } 1845 buf[i] = '"'; 1846 i += 1; 1847 return buf[0..i]; 1848 } 1849 1850 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1851 for (input) |ch| { 1852 switch (ch) { 1853 '&' => try out.appendSlice(allocator, "&amp;"), 1854 '<' => try out.appendSlice(allocator, "&lt;"), 1855 '>' => try out.appendSlice(allocator, "&gt;"), 1856 '"' => try out.appendSlice(allocator, "&quot;"), 1857 '\'' => try out.appendSlice(allocator, "&#39;"), 1858 else => try out.append(allocator, ch), 1859 } 1860 } 1861 } 1862 1863 // --- helpers -------------------------------------------------------------- 1864 1865 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1866 var iter = request.iterateHeaders(); 1867 while (iter.next()) |header| { 1868 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1869 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1870 while (pairs.next()) |pair| { 1871 const trimmed = std.mem.trim(u8, pair, " \t"); 1872 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1873 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1874 return trimmed[eq + 1 ..]; 1875 } 1876 } 1877 } 1878 return null; 1879 } 1880 1881 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1882 var iter = std.mem.splitScalar(u8, body, '&'); 1883 while (iter.next()) |pair| { 1884 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1885 if (std.mem.eql(u8, pair[0..eq], key)) { 1886 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1887 } 1888 } 1889 return null; 1890 } 1891 1892 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1893 var out: std.ArrayList(u8) = .empty; 1894 errdefer out.deinit(allocator); 1895 var i: usize = 0; 1896 while (i < encoded.len) : (i += 1) { 1897 switch (encoded[i]) { 1898 '+' => try out.append(allocator, ' '), 1899 '%' => { 1900 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1901 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1902 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1903 try out.append(allocator, hi * 16 + lo); 1904 i += 2; 1905 }, 1906 else => try out.append(allocator, encoded[i]), 1907 } 1908 } 1909 return try out.toOwnedSlice(allocator); 1910 } 1911 1912 // disk-backed web session store. each login mints a random, opaque token 1913 // (not the user's id) that is stored as a file named by the token hex, whose 1914 // contents are the raw user_id bytes. authenticating a request is a lookup of 1915 // the cookie's token; logout deletes the file, revoking the session. there is 1916 // deliberately no expiry — a session lives until logout. 1917 pub const SessionStore = struct { 1918 io: std.Io, 1919 dir: std.Io.Dir, 1920 1921 pub const token_hex_len = evt.event_id_size * 2; 1922 1923 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1924 try data_dir.createDirPath(io, "sessions"); 1925 const dir = try data_dir.openDir(io, "sessions", .{}); 1926 return .{ .io = io, .dir = dir }; 1927 } 1928 1929 pub fn deinit(self: SessionStore) void { 1930 self.dir.close(self.io); 1931 } 1932 1933 // mint a new session for user_id, returning the token hex to set as the 1934 // cookie value. 1935 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1936 var token: [evt.event_id_size]u8 = undefined; 1937 self.io.random(&token); 1938 const token_hex = std.fmt.bytesToHex(token, .lower); 1939 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1940 defer file.close(self.io); 1941 try file.writeStreamingAll(self.io, user_id); 1942 return token_hex; 1943 } 1944 1945 // resolve a cookie's token to its user_id. returns false (logged out) for a 1946 // missing, malformed, or unknown token. 1947 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1948 if (!isToken(token_hex)) return false; 1949 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1950 defer file.close(self.io); 1951 var storage: [evt.event_id_size]u8 = undefined; 1952 var file_reader = file.reader(self.io, &storage); 1953 file_reader.interface.readSliceAll(out) catch return false; 1954 return true; 1955 } 1956 1957 // revoke a session. a no-op for a missing or malformed token. 1958 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1959 if (!isToken(token_hex)) return; 1960 self.dir.deleteFile(self.io, token_hex) catch {}; 1961 } 1962 1963 // leave `token_hex`'s session for the next visitor arriving without one. 1964 // only the `try` fixture writes one, and only a debug build honors it. the 1965 // name isn't token-shaped, so it can't collide with a session file. 1966 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 1967 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 1968 defer file.close(self.io); 1969 try file.writeStreamingAll(self.io, token_hex); 1970 } 1971 1972 // claim the offered session, if one is there. the delete picks the winner 1973 // of a race, so the offer is only ever taken once. a release build never 1974 // looks, because that would be an extra syscall for every GET request. 1975 pub fn claimAutoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 1976 if (builtin.mode != .Debug) return false; 1977 { 1978 const file = self.dir.openFile(self.io, auto_login_name, .{ .mode = .read_only }) catch return false; 1979 defer file.close(self.io); 1980 var storage: [token_hex_len]u8 = undefined; 1981 var file_reader = file.reader(self.io, &storage); 1982 file_reader.interface.readSliceAll(out) catch return false; 1983 } 1984 self.dir.deleteFile(self.io, auto_login_name) catch return false; 1985 return true; 1986 } 1987 1988 const auto_login_name = "auto-login"; 1989 1990 // a token is exactly token_hex_len hex chars. validating before using the 1991 // value as a path keeps attacker-supplied cookies from escaping the 1992 // sessions dir (e.g. via "/" or ".." bytes). 1993 fn isToken(token_hex: []const u8) bool { 1994 if (token_hex.len != token_hex_len) return false; 1995 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1996 return true; 1997 } 1998 }; 1999