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