╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
2014 const parent = root_focus.children.get(parent_id) orelse return null; 2015 if (formAction(parent.focus) != null) return parent_id; 2016 id = parent_id; 2017 } 2018 return null; 2019 } 2020 2021 fn appendFormAttribute(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus, focus_id: usize) !void { 2022 const form_id = formOwner(root_focus, focus_id) orelse return; 2023 var buf: [64]u8 = undefined; 2024 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, " form=\"" ++ form_id_prefix ++ "{d}\"", .{form_id})); 2025 } 2026 2027 fn renderPanelControls( 2028 allocator: std.mem.Allocator, 2029 output: *std.ArrayList(u8), 2030 focus: *Focus, 2031 session: *ui.Session, 2032 root_focus: *Focus, 2033 excluded: *const std.AutoHashMapUnmanaged(usize, void), 2034 ) !void { 2035 var iter = focus.children.iterator(); 2036 while (iter.next()) |entry| { 2037 const id = entry.key_ptr.*; 2038 if (excluded.contains(id)) continue; 2039 const child = entry.value_ptr.*; 2040 const r = child.rect; 2041 2042 switch (child.focus.kind) { 2043 .text_input, .text_input_password, .text_area => { 2044 const ti = session.text_inputs.get(id) orelse continue; 2045 2046 const inner_left = r.x + 1; 2047 const inner_top = r.y + 1; 2048 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 2049 const preserve = !ti.options.read_only; 2050 2051 if (child.focus.kind == .text_area) { 2052 const value = try ti.text(allocator); 2053 defer allocator.free(value); 2054 var id_buf: [128]u8 = undefined; 2055 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<textarea data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2056 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2057 try appendFormAttribute(allocator, output, root_focus, id); 2058 if (ti.options.name.len > 0) { 2059 try output.appendSlice(allocator, " name=\""); 2060 try appendEscapedHtml(allocator, output, ti.options.name); 2061 try output.append(allocator, '"'); 2062 } 2063 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 2064 var pos_buf: [128]u8 = undefined; 2065 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">\n", .{ inner_left, inner_top, inner_width, inner_height })); 2066 try appendEscapedHtml(allocator, output, value); 2067 try output.appendSlice(allocator, "</textarea>"); 2068 continue; 2069 } 2070 2071 var id_buf: [160]u8 = undefined; 2072 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<input type=\"{s}\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ if (child.focus.kind == .text_input_password) "password" else "text", id, id })); 2073 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2074 try appendFormAttribute(allocator, output, root_focus, id); 2075 if (ti.options.name.len > 0) { 2076 try output.appendSlice(allocator, " name=\""); 2077 try appendEscapedHtml(allocator, output, ti.options.name); 2078 try output.append(allocator, '"'); 2079 } 2080 if (child.focus.kind != .text_input_password) { 2081 const value = try ti.text(allocator); 2082 defer allocator.free(value); 2083 try output.appendSlice(allocator, " value=\""); 2084 try appendEscapedHtml(allocator, output, value); 2085 try output.append(allocator, '"'); 2086 } 2087 var pos_buf: [96]u8 = undefined; 2088 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:1em\">", .{ inner_left, inner_top, inner_width })); 2089 }, 2090 .custom => |custom| { 2091 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2092 if (formOwner(root_focus, id) == null) continue; 2093 var id_buf: [128]u8 = undefined; 2094 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2095 try appendFormAttribute(allocator, output, root_focus, id); 2096 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2097 try output.appendSlice(allocator, " formaction=\""); 2098 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 2099 try output.append(allocator, '"'); 2100 } 2101 var pos_buf: [128]u8 = undefined; 2102 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\"></button>", .{ r.x, r.y, r.size.width, r.size.height })); 2103 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 2104 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 2105 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 2106 var id_buf: [128]u8 = undefined; 2107 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "\" data-key=\"control:{d}\" data-focus-id=\"{d}\" style=\"opacity:0;left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">", .{ id, id, r.x, r.y, r.size.width, r.size.height })); 2108 } 2109 }, 2110 else => {}, 2111 } 2112 } 2113 } 2114 2115 // emit hidden form owners beside the rendered panels. their controls point 2116 // back here with the standard HTML `form` attribute. 2117 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 2118 // the focus child map preserves insertion order, which matches the order 2119 // widgets were added in code 2120 var iter = root_focus.children.iterator(); 2121 while (iter.next()) |entry| { 2122 const child = entry.value_ptr.*; 2123 const action_url = formAction(child.focus) orelse continue; 2124 2125 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 2126 var id_buf: [96]u8 = undefined; 2127 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 2128 try appendEscapedHtml(allocator, output, action_url); 2129 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 2130 } 2131 } 2132 2133 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 2134 if (a) |av| return if (b) |bv| av.eql(bv) else false; 2135 return b == null; 2136 } 2137 2138 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 2139 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 2140 // empty slice when neither is set. 2141 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 2142 if (fg == null and bg == null) return buf[0..0]; 2143 const prefix = " style=\""; 2144 @memcpy(buf[0..prefix.len], prefix); 2145 var i: usize = prefix.len; 2146 if (fg) |c| { 2147 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]; 2148 i += s.len; 2149 } 2150 if (bg) |c| { 2151 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]; 2152 i += s.len; 2153 } 2154 buf[i] = '"'; 2155 i += 1; 2156 return buf[0..i]; 2157 } 2158 2159 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2160 for (input) |ch| { 2161 switch (ch) { 2162 '&' => try out.appendSlice(allocator, "&amp;"), 2163 '<' => try out.appendSlice(allocator, "&lt;"), 2164 '>' => try out.appendSlice(allocator, "&gt;"), 2165 '"' => try out.appendSlice(allocator, "&quot;"), 2166 '\'' => try out.appendSlice(allocator, "&#39;"), 2167 else => try out.append(allocator, ch), 2168 } 2169 } 2170 } 2171 2172 // --- helpers -------------------------------------------------------------- 2173 2174 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 2175 var iter = request.iterateHeaders(); 2176 while (iter.next()) |header| { 2177 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2178 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2179 while (pairs.next()) |pair| { 2180 const trimmed = std.mem.trim(u8, pair, " \t"); 2181 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2182 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2183 return trimmed[eq + 1 ..]; 2184 } 2185 } 2186 } 2187 return null; 2188 } 2189 2190 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2191 var iter = std.mem.splitScalar(u8, body, '&'); 2192 while (iter.next()) |pair| { 2193 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2194 if (std.mem.eql(u8, pair[0..eq], key)) { 2195 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2196 } 2197 } 2198 return null; 2199 } 2200 2201 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2202 var buffer: [256]u8 = undefined; 2203 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2204 } 2205 2206 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2207 var out: std.ArrayList(u8) = .empty; 2208 errdefer out.deinit(allocator); 2209 var i: usize = 0; 2210 while (i < encoded.len) : (i += 1) { 2211 switch (encoded[i]) { 2212 '+' => try out.append(allocator, ' '), 2213 '%' => { 2214 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2215 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2216 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2217 try out.append(allocator, hi * 16 + lo); 2218 i += 2; 2219 }, 2220 else => try out.append(allocator, encoded[i]), 2221 } 2222 } 2223 return try out.toOwnedSlice(allocator); 2224 } 2225 2226 // disk-backed web session store. each login mints a random, opaque token 2227 // (not the user's id) that is stored as a file named by the token hex, whose 2228 // contents are the raw user_id bytes. authenticating a request is a lookup of 2229 // the cookie's token; logout deletes the file, revoking the session. there is 2230 // deliberately no expiry — a session lives until logout. form failures use 2231 // files in the flash subdirectory that the redirected GET consumes. the 2232 // directory is cleared whenever the server starts. 2233 pub const SessionStore = struct { 2234 io: std.Io, 2235 dir: std.Io.Dir, 2236 flash_dir: std.Io.Dir, 2237 auto_login: ?[token_hex_len]u8, 2238 2239 pub const token_hex_len = evt.event_id_size * 2; 2240 2241 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2242 try data_dir.createDirPath(io, "sessions"); 2243 const dir = try data_dir.openDir(io, "sessions", .{}); 2244 errdefer dir.close(io); 2245 try dir.deleteTree(io, "flash"); 2246 try dir.createDirPath(io, "flash"); 2247 const flash_dir = try dir.openDir(io, "flash", .{}); 2248 errdefer flash_dir.close(io); 2249 const auto_login = blk: { 2250 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2251 defer file.close(io); 2252 var token: [token_hex_len]u8 = undefined; 2253 var storage: [token_hex_len]u8 = undefined; 2254 var reader = file.reader(io, &storage); 2255 reader.interface.readSliceAll(&token) catch break :blk null; 2256 break :blk token; 2257 }; 2258 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 2259 } 2260 2261 pub fn deinit(self: SessionStore) void { 2262 self.flash_dir.close(self.io); 2263 self.dir.close(self.io); 2264 } 2265 2266 // mint a new session for user_id, returning the token hex to set as the 2267 // cookie value. 2268 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2269 var token: [evt.event_id_size]u8 = undefined; 2270 self.io.random(&token); 2271 const token_hex = std.fmt.bytesToHex(token, .lower); 2272 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2273 defer file.close(self.io); 2274 try file.writeStreamingAll(self.io, user_id); 2275 return token_hex; 2276 } 2277 2278 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 2279 var token: [evt.event_id_size]u8 = undefined; 2280 self.io.random(&token); 2281 const token_hex = std.fmt.bytesToHex(token, .lower); 2282 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 2283 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 2284 defer file.close(self.io); 2285 2286 var json: std.Io.Writer.Allocating = .init(allocator); 2287 defer json.deinit(); 2288 try std.json.Stringify.value(value, .{}, &json.writer); 2289 try file.writeStreamingAll(self.io, json.written()); 2290 return token_hex; 2291 } 2292 2293 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 2294 if (!isToken(token_hex)) return null; 2295 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 2296 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 2297 defer file.close(self.io); 2298 2299 var storage: [4096]u8 = undefined; 2300 var reader = file.reader(self.io, &storage); 2301 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 2302 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 2303 } 2304 2305 // resolve a cookie's token to its user_id. returns false (logged out) for a 2306 // missing, malformed, or unknown token. 2307 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2308 if (!isToken(token_hex)) return false; 2309 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2310 defer file.close(self.io); 2311 var storage: [evt.event_id_size]u8 = undefined; 2312 var file_reader = file.reader(self.io, &storage); 2313 file_reader.interface.readSliceAll(out) catch return false; 2314 return true; 2315 } 2316 2317 // revoke a session. a no-op for a missing or malformed token. 2318 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2319 if (!isToken(token_hex)) return; 2320 self.dir.deleteFile(self.io, token_hex) catch {}; 2321 } 2322 2323 // leave `token_hex`'s session for visitors arriving without one. only the 2324 // `try` fixture writes one. the name can't collide with a session token. 2325 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2326 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2327 defer file.close(self.io); 2328 try file.writeStreamingAll(self.io, token_hex); 2329 } 2330 2331 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2332 out.* = self.auto_login orelse return false; 2333 return true; 2334 } 2335 2336 const auto_login_name = "auto-login"; 2337 2338 // a token is exactly token_hex_len hex chars. validating before using the 2339 // value as a path keeps attacker-supplied cookies from escaping the 2340 // sessions dir (e.g. via "/" or ".." bytes). 2341 fn isToken(token_hex: []const u8) bool { 2342 if (token_hex.len != token_hex_len) return false; 2343 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2344 return true; 2345 } 2346 }; 2347