╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1930 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1931 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1932 // empty slice when neither is set. 1933 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1934 if (fg == null and bg == null) return buf[0..0]; 1935 const prefix = " style=\""; 1936 @memcpy(buf[0..prefix.len], prefix); 1937 var i: usize = prefix.len; 1938 if (fg) |c| { 1939 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]; 1940 i += s.len; 1941 } 1942 if (bg) |c| { 1943 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]; 1944 i += s.len; 1945 } 1946 buf[i] = '"'; 1947 i += 1; 1948 return buf[0..i]; 1949 } 1950 1951 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1952 for (input) |ch| { 1953 switch (ch) { 1954 '&' => try out.appendSlice(allocator, "&amp;"), 1955 '<' => try out.appendSlice(allocator, "&lt;"), 1956 '>' => try out.appendSlice(allocator, "&gt;"), 1957 '"' => try out.appendSlice(allocator, "&quot;"), 1958 '\'' => try out.appendSlice(allocator, "&#39;"), 1959 else => try out.append(allocator, ch), 1960 } 1961 } 1962 } 1963 1964 // --- helpers -------------------------------------------------------------- 1965 1966 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1967 var iter = request.iterateHeaders(); 1968 while (iter.next()) |header| { 1969 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1970 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1971 while (pairs.next()) |pair| { 1972 const trimmed = std.mem.trim(u8, pair, " \t"); 1973 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1974 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1975 return trimmed[eq + 1 ..]; 1976 } 1977 } 1978 } 1979 return null; 1980 } 1981 1982 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1983 var iter = std.mem.splitScalar(u8, body, '&'); 1984 while (iter.next()) |pair| { 1985 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1986 if (std.mem.eql(u8, pair[0..eq], key)) { 1987 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1988 } 1989 } 1990 return null; 1991 } 1992 1993 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1994 var out: std.ArrayList(u8) = .empty; 1995 errdefer out.deinit(allocator); 1996 var i: usize = 0; 1997 while (i < encoded.len) : (i += 1) { 1998 switch (encoded[i]) { 1999 '+' => try out.append(allocator, ' '), 2000 '%' => { 2001 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2002 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2003 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2004 try out.append(allocator, hi * 16 + lo); 2005 i += 2; 2006 }, 2007 else => try out.append(allocator, encoded[i]), 2008 } 2009 } 2010 return try out.toOwnedSlice(allocator); 2011 } 2012 2013 // disk-backed web session store. each login mints a random, opaque token 2014 // (not the user's id) that is stored as a file named by the token hex, whose 2015 // contents are the raw user_id bytes. authenticating a request is a lookup of 2016 // the cookie's token; logout deletes the file, revoking the session. there is 2017 // deliberately no expiry — a session lives until logout. 2018 pub const SessionStore = struct { 2019 io: std.Io, 2020 dir: std.Io.Dir, 2021 2022 pub const token_hex_len = evt.event_id_size * 2; 2023 2024 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2025 try data_dir.createDirPath(io, "sessions"); 2026 const dir = try data_dir.openDir(io, "sessions", .{}); 2027 return .{ .io = io, .dir = dir }; 2028 } 2029 2030 pub fn deinit(self: SessionStore) void { 2031 self.dir.close(self.io); 2032 } 2033 2034 // mint a new session for user_id, returning the token hex to set as the 2035 // cookie value. 2036 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2037 var token: [evt.event_id_size]u8 = undefined; 2038 self.io.random(&token); 2039 const token_hex = std.fmt.bytesToHex(token, .lower); 2040 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2041 defer file.close(self.io); 2042 try file.writeStreamingAll(self.io, user_id); 2043 return token_hex; 2044 } 2045 2046 // resolve a cookie's token to its user_id. returns false (logged out) for a 2047 // missing, malformed, or unknown token. 2048 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2049 if (!isToken(token_hex)) return false; 2050 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2051 defer file.close(self.io); 2052 var storage: [evt.event_id_size]u8 = undefined; 2053 var file_reader = file.reader(self.io, &storage); 2054 file_reader.interface.readSliceAll(out) catch return false; 2055 return true; 2056 } 2057 2058 // revoke a session. a no-op for a missing or malformed token. 2059 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2060 if (!isToken(token_hex)) return; 2061 self.dir.deleteFile(self.io, token_hex) catch {}; 2062 } 2063 2064 // leave `token_hex`'s session for the next visitor arriving without one. 2065 // only the `try` fixture writes one, and only a debug build honors it. the 2066 // name isn't token-shaped, so it can't collide with a session file. 2067 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2068 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2069 defer file.close(self.io); 2070 try file.writeStreamingAll(self.io, token_hex); 2071 } 2072 2073 // claim the offered session, if one is there. the delete picks the winner 2074 // of a race, so the offer is only ever taken once. a release build never 2075 // looks, because that would be an extra syscall for every GET request. 2076 pub fn claimAutoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2077 if (builtin.mode != .Debug) return false; 2078 { 2079 const file = self.dir.openFile(self.io, auto_login_name, .{ .mode = .read_only }) catch return false; 2080 defer file.close(self.io); 2081 var storage: [token_hex_len]u8 = undefined; 2082 var file_reader = file.reader(self.io, &storage); 2083 file_reader.interface.readSliceAll(out) catch return false; 2084 } 2085 self.dir.deleteFile(self.io, auto_login_name) catch return false; 2086 return true; 2087 } 2088 2089 const auto_login_name = "auto-login"; 2090 2091 // a token is exactly token_hex_len hex chars. validating before using the 2092 // value as a path keeps attacker-supplied cookies from escaping the 2093 // sessions dir (e.g. via "/" or ".." bytes). 2094 fn isToken(token_hex: []const u8) bool { 2095 if (token_hex.len != token_hex_len) return false; 2096 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2097 return true; 2098 } 2099 }; 2100