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