╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1890 try out.appendSlice(allocator, "\" name=\""); 1891 try appendEscapedHtml(allocator, &out, ti.options.name); 1892 } 1893 // like the input above, only a page-constant initial value 1894 // inside: the browser tracks the live value and the 1895 // overlay diff must stay stable across keystrokes 1896 try out.appendSlice(allocator, "\" style=\"left:"); 1897 var pos_buf: [128]u8 = undefined; 1898 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 })); 1899 // textarea discards the first newline immediately following 1900 // its start tag, so add one of our own so text that begins 1901 // with a newline doesn't lose it 1902 try out.appendSlice(allocator, "\">\n"); 1903 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1904 try out.appendSlice(allocator, "</textarea>"); 1905 }, 1906 .custom => |custom| { 1907 if (std.mem.eql(u8, "submit", custom) or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 1908 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1909 var id_buf: [32]u8 = undefined; 1910 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1911 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 1912 try out.appendSlice(allocator, "\" formaction=\""); 1913 try appendEscapedHtml(allocator, &out, custom[ui.submit_action_prefix.len..]); 1914 } 1915 try out.appendSlice(allocator, "\" style=\"left:"); 1916 var pos_buf: [128]u8 = undefined; 1917 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 })); 1918 try out.appendSlice(allocator, "\"></button>"); 1919 } 1920 }, 1921 else => {}, 1922 } 1923 } 1924 1925 try out.appendSlice(allocator, "</form>"); 1926 } 1927 1928 // a file picker isn't part of a form: it posts its file straight to the url 1929 // in its marker. it sits transparent over the button the tui drew, so 1930 // clicking that button opens the browser's own dialog. 1931 var file_iter = root_focus.children.iterator(); 1932 while (file_iter.next()) |entry| { 1933 const child = entry.value_ptr.*; 1934 const action_url = switch (child.focus.kind) { 1935 .custom => |custom| if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) 1936 custom[ui.file_input_prefix.len..] 1937 else 1938 continue, 1939 else => continue, 1940 }; 1941 const r = child.rect; 1942 1943 try out.appendSlice(allocator, "<input type=\"file\" data-action=\""); 1944 try appendEscapedHtml(allocator, &out, action_url); 1945 try out.appendSlice(allocator, "\" data-focus-id=\""); 1946 var id_buf: [32]u8 = undefined; 1947 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{entry.key_ptr.*})); 1948 try out.appendSlice(allocator, "\" style=\"opacity:0;left:"); 1949 var pos_buf: [128]u8 = undefined; 1950 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 })); 1951 try out.appendSlice(allocator, "\">"); 1952 } 1953 1954 return try out.toOwnedSlice(allocator); 1955 } 1956 1957 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1958 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1959 return b == null; 1960 } 1961 1962 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1963 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1964 // empty slice when neither is set. 1965 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1966 if (fg == null and bg == null) return buf[0..0]; 1967 const prefix = " style=\""; 1968 @memcpy(buf[0..prefix.len], prefix); 1969 var i: usize = prefix.len; 1970 if (fg) |c| { 1971 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]; 1972 i += s.len; 1973 } 1974 if (bg) |c| { 1975 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]; 1976 i += s.len; 1977 } 1978 buf[i] = '"'; 1979 i += 1; 1980 return buf[0..i]; 1981 } 1982 1983 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1984 for (input) |ch| { 1985 switch (ch) { 1986 '&' => try out.appendSlice(allocator, "&amp;"), 1987 '<' => try out.appendSlice(allocator, "&lt;"), 1988 '>' => try out.appendSlice(allocator, "&gt;"), 1989 '"' => try out.appendSlice(allocator, "&quot;"), 1990 '\'' => try out.appendSlice(allocator, "&#39;"), 1991 else => try out.append(allocator, ch), 1992 } 1993 } 1994 } 1995 1996 // --- helpers -------------------------------------------------------------- 1997 1998 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1999 var iter = request.iterateHeaders(); 2000 while (iter.next()) |header| { 2001 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2002 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2003 while (pairs.next()) |pair| { 2004 const trimmed = std.mem.trim(u8, pair, " \t"); 2005 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2006 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2007 return trimmed[eq + 1 ..]; 2008 } 2009 } 2010 } 2011 return null; 2012 } 2013 2014 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2015 var iter = std.mem.splitScalar(u8, body, '&'); 2016 while (iter.next()) |pair| { 2017 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2018 if (std.mem.eql(u8, pair[0..eq], key)) { 2019 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2020 } 2021 } 2022 return null; 2023 } 2024 2025 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2026 var buffer: [256]u8 = undefined; 2027 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2028 } 2029 2030 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2031 var out: std.ArrayList(u8) = .empty; 2032 errdefer out.deinit(allocator); 2033 var i: usize = 0; 2034 while (i < encoded.len) : (i += 1) { 2035 switch (encoded[i]) { 2036 '+' => try out.append(allocator, ' '), 2037 '%' => { 2038 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2039 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2040 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2041 try out.append(allocator, hi * 16 + lo); 2042 i += 2; 2043 }, 2044 else => try out.append(allocator, encoded[i]), 2045 } 2046 } 2047 return try out.toOwnedSlice(allocator); 2048 } 2049 2050 // disk-backed web session store. each login mints a random, opaque token 2051 // (not the user's id) that is stored as a file named by the token hex, whose 2052 // contents are the raw user_id bytes. authenticating a request is a lookup of 2053 // the cookie's token; logout deletes the file, revoking the session. there is 2054 // deliberately no expiry — a session lives until logout. 2055 pub const SessionStore = struct { 2056 io: std.Io, 2057 dir: std.Io.Dir, 2058 auto_login: ?[token_hex_len]u8, 2059 2060 pub const token_hex_len = evt.event_id_size * 2; 2061 2062 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2063 try data_dir.createDirPath(io, "sessions"); 2064 const dir = try data_dir.openDir(io, "sessions", .{}); 2065 const auto_login = blk: { 2066 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2067 defer file.close(io); 2068 var token: [token_hex_len]u8 = undefined; 2069 var storage: [token_hex_len]u8 = undefined; 2070 var reader = file.reader(io, &storage); 2071 reader.interface.readSliceAll(&token) catch break :blk null; 2072 break :blk token; 2073 }; 2074 return .{ .io = io, .dir = dir, .auto_login = auto_login }; 2075 } 2076 2077 pub fn deinit(self: SessionStore) void { 2078 self.dir.close(self.io); 2079 } 2080 2081 // mint a new session for user_id, returning the token hex to set as the 2082 // cookie value. 2083 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2084 var token: [evt.event_id_size]u8 = undefined; 2085 self.io.random(&token); 2086 const token_hex = std.fmt.bytesToHex(token, .lower); 2087 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2088 defer file.close(self.io); 2089 try file.writeStreamingAll(self.io, user_id); 2090 return token_hex; 2091 } 2092 2093 // resolve a cookie's token to its user_id. returns false (logged out) for a 2094 // missing, malformed, or unknown token. 2095 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2096 if (!isToken(token_hex)) return false; 2097 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2098 defer file.close(self.io); 2099 var storage: [evt.event_id_size]u8 = undefined; 2100 var file_reader = file.reader(self.io, &storage); 2101 file_reader.interface.readSliceAll(out) catch return false; 2102 return true; 2103 } 2104 2105 // revoke a session. a no-op for a missing or malformed token. 2106 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2107 if (!isToken(token_hex)) return; 2108 self.dir.deleteFile(self.io, token_hex) catch {}; 2109 } 2110 2111 // leave `token_hex`'s session for visitors arriving without one. only the 2112 // `try` fixture writes one. the name can't collide with a session token. 2113 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2114 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2115 defer file.close(self.io); 2116 try file.writeStreamingAll(self.io, token_hex); 2117 } 2118 2119 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2120 out.* = self.auto_login orelse return false; 2121 return true; 2122 } 2123 2124 const auto_login_name = "auto-login"; 2125 2126 // a token is exactly token_hex_len hex chars. validating before using the 2127 // value as a path keeps attacker-supplied cookies from escaping the 2128 // sessions dir (e.g. via "/" or ".." bytes). 2129 fn isToken(token_hex: []const u8) bool { 2130 if (token_hex.len != token_hex_len) return false; 2131 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2132 return true; 2133 } 2134 }; 2135