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