╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
2103 .vert => "overflow-x:hidden;overflow-y:auto", 2104 .horiz => "overflow-x:auto;overflow-y:hidden", 2105 .both => "overflow:auto", 2106 }; 2107 // the id carries a content version so JS preserves the native scroll 2108 // position across re-renders of the same content but resets it when the 2109 // content is replaced — e.g. selecting a different commit. the widget's 2110 // scroll offset (in cells) rides along so JS can apply it when it has no 2111 // preserved position, letting a wasm-side scrollToRect (the files list 2112 // scrolling to its selected row on page load) reach the browser. 2113 var buf: [256]u8 = undefined; 2114 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 })); 2115 try renderPanel(allocator, output, child.focus, info.content, session, root_focus); 2116 try output.appendSlice(allocator, "</div>"); 2117 } 2118 } 2119 2120 const form_prefix = "form:"; 2121 const form_id_prefix = "haxy-form-"; 2122 2123 fn formAction(focus: *const Focus) ?[]const u8 { 2124 return switch (focus.kind) { 2125 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) custom[form_prefix.len..] else null, 2126 else => null, 2127 }; 2128 } 2129 2130 // find the form ancestor of a flattened focus-tree child. html's `form` 2131 // attribute then associates the control with that form without requiring the 2132 // form and control to share a DOM parent. 2133 fn formOwner(root_focus: *Focus, focus_id: usize) ?usize { 2134 var id = focus_id; 2135 while (root_focus.children.get(id)) |child| { 2136 const parent_id = child.parent_id; 2137 if (parent_id == root_focus.id) return if (formAction(root_focus) != null) root_focus.id else null; 2138 const parent = root_focus.children.get(parent_id) orelse return null; 2139 if (formAction(parent.focus) != null) return parent_id; 2140 id = parent_id; 2141 } 2142 return null; 2143 } 2144 2145 fn appendFormAttribute(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus, focus_id: usize) !void { 2146 const form_id = formOwner(root_focus, focus_id) orelse return; 2147 var buf: [64]u8 = undefined; 2148 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, " form=\"" ++ form_id_prefix ++ "{d}\"", .{form_id})); 2149 } 2150 2151 fn renderPanelControls( 2152 allocator: std.mem.Allocator, 2153 output: *std.ArrayList(u8), 2154 focus: *Focus, 2155 session: *ui.Session, 2156 root_focus: *Focus, 2157 excluded: *const std.AutoHashMapUnmanaged(usize, void), 2158 ) !void { 2159 var iter = focus.children.iterator(); 2160 while (iter.next()) |entry| { 2161 const id = entry.key_ptr.*; 2162 if (excluded.contains(id)) continue; 2163 const child = entry.value_ptr.*; 2164 const r = child.rect; 2165 2166 if (r.size.width == 0 or r.size.height == 0) continue; // not laid out, rather than merely off-screen 2167 2168 switch (child.focus.kind) { 2169 .text_input, .text_input_password, .text_area => { 2170 const ti = session.text_inputs.get(id) orelse continue; 2171 2172 const inner_left = r.x + 1; 2173 const inner_top = r.y + 1; 2174 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 2175 const preserve = !ti.options.read_only; 2176 2177 if (child.focus.kind == .text_area) { 2178 const value = try ti.text(allocator); 2179 defer allocator.free(value); 2180 var id_buf: [128]u8 = undefined; 2181 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<textarea data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2182 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2183 try appendFormAttribute(allocator, output, root_focus, id); 2184 if (ti.options.name.len > 0) { 2185 try output.appendSlice(allocator, " name=\""); 2186 try appendEscapedHtml(allocator, output, ti.options.name); 2187 try output.append(allocator, '"'); 2188 } 2189 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 2190 var pos_buf: [128]u8 = undefined; 2191 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 })); 2192 try appendEscapedHtml(allocator, output, value); 2193 try output.appendSlice(allocator, "</textarea>"); 2194 continue; 2195 } 2196 2197 var id_buf: [160]u8 = undefined; 2198 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 })); 2199 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2200 try appendFormAttribute(allocator, output, root_focus, id); 2201 if (ti.options.name.len > 0) { 2202 try output.appendSlice(allocator, " name=\""); 2203 try appendEscapedHtml(allocator, output, ti.options.name); 2204 try output.append(allocator, '"'); 2205 } 2206 if (child.focus.kind != .text_input_password) { 2207 const value = try ti.text(allocator); 2208 defer allocator.free(value); 2209 try output.appendSlice(allocator, " value=\""); 2210 try appendEscapedHtml(allocator, output, value); 2211 try output.append(allocator, '"'); 2212 } 2213 var pos_buf: [96]u8 = undefined; 2214 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 })); 2215 }, 2216 .custom => |custom| { 2217 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2218 if (formOwner(root_focus, id) == null) continue; 2219 var id_buf: [128]u8 = undefined; 2220 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2221 try appendFormAttribute(allocator, output, root_focus, id); 2222 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2223 try output.appendSlice(allocator, " formaction=\""); 2224 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 2225 try output.append(allocator, '"'); 2226 } 2227 var pos_buf: [128]u8 = undefined; 2228 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 })); 2229 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 2230 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 2231 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 2232 var id_buf: [128]u8 = undefined; 2233 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 })); 2234 } 2235 }, 2236 else => {}, 2237 } 2238 } 2239 } 2240 2241 // emit hidden form owners beside the rendered panels. their controls point 2242 // back here with the standard HTML `form` attribute. 2243 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 2244 // the focus child map preserves insertion order, which matches the order 2245 // widgets were added in code 2246 var iter = root_focus.children.iterator(); 2247 while (iter.next()) |entry| { 2248 const child = entry.value_ptr.*; 2249 const action_url = formAction(child.focus) orelse continue; 2250 2251 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 2252 var id_buf: [96]u8 = undefined; 2253 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 2254 try appendEscapedHtml(allocator, output, action_url); 2255 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 2256 } 2257 } 2258 2259 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 2260 if (a) |av| return if (b) |bv| av.eql(bv) else false; 2261 return b == null; 2262 } 2263 2264 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 2265 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 2266 // empty slice when neither is set. 2267 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 2268 if (fg == null and bg == null) return buf[0..0]; 2269 const prefix = " style=\""; 2270 @memcpy(buf[0..prefix.len], prefix); 2271 var i: usize = prefix.len; 2272 if (fg) |c| { 2273 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]; 2274 i += s.len; 2275 } 2276 if (bg) |c| { 2277 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]; 2278 i += s.len; 2279 } 2280 buf[i] = '"'; 2281 i += 1; 2282 return buf[0..i]; 2283 } 2284 2285 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2286 for (input) |ch| { 2287 switch (ch) { 2288 '&' => try out.appendSlice(allocator, "&amp;"), 2289 '<' => try out.appendSlice(allocator, "&lt;"), 2290 '>' => try out.appendSlice(allocator, "&gt;"), 2291 '"' => try out.appendSlice(allocator, "&quot;"), 2292 '\'' => try out.appendSlice(allocator, "&#39;"), 2293 else => try out.append(allocator, ch), 2294 } 2295 } 2296 } 2297 2298 // --- helpers -------------------------------------------------------------- 2299 2300 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 2301 var iter = request.iterateHeaders(); 2302 while (iter.next()) |header| { 2303 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2304 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2305 while (pairs.next()) |pair| { 2306 const trimmed = std.mem.trim(u8, pair, " \t"); 2307 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2308 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2309 return trimmed[eq + 1 ..]; 2310 } 2311 } 2312 } 2313 return null; 2314 } 2315 2316 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2317 var iter = std.mem.splitScalar(u8, body, '&'); 2318 while (iter.next()) |pair| { 2319 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2320 if (std.mem.eql(u8, pair[0..eq], key)) { 2321 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2322 } 2323 } 2324 return null; 2325 } 2326 2327 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2328 var buffer: [256]u8 = undefined; 2329 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2330 } 2331 2332 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2333 var out: std.ArrayList(u8) = .empty; 2334 errdefer out.deinit(allocator); 2335 var i: usize = 0; 2336 while (i < encoded.len) : (i += 1) { 2337 switch (encoded[i]) { 2338 '+' => try out.append(allocator, ' '), 2339 '%' => { 2340 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2341 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2342 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2343 try out.append(allocator, hi * 16 + lo); 2344 i += 2; 2345 }, 2346 else => try out.append(allocator, encoded[i]), 2347 } 2348 } 2349 return try out.toOwnedSlice(allocator); 2350 } 2351 2352 // disk-backed web session store. each login mints a random, opaque token 2353 // (not the user's id) that is stored as a file named by the token hex, whose 2354 // contents are the raw user_id bytes. authenticating a request is a lookup of 2355 // the cookie's token; logout deletes the file, revoking the session. there is 2356 // deliberately no expiry — a session lives until logout. form failures use 2357 // files in the flash subdirectory that the redirected GET consumes. the 2358 // directory is cleared whenever the server starts. 2359 pub const SessionStore = struct { 2360 io: std.Io, 2361 dir: std.Io.Dir, 2362 flash_dir: std.Io.Dir, 2363 auto_login: ?[token_hex_len]u8, 2364 2365 pub const token_hex_len = evt.event_id_size * 2; 2366 2367 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2368 try data_dir.createDirPath(io, "sessions"); 2369 const dir = try data_dir.openDir(io, "sessions", .{}); 2370 errdefer dir.close(io); 2371 try dir.deleteTree(io, "flash"); 2372 try dir.createDirPath(io, "flash"); 2373 const flash_dir = try dir.openDir(io, "flash", .{}); 2374 errdefer flash_dir.close(io); 2375 const auto_login = blk: { 2376 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2377 defer file.close(io); 2378 var token: [token_hex_len]u8 = undefined; 2379 var storage: [token_hex_len]u8 = undefined; 2380 var reader = file.reader(io, &storage); 2381 reader.interface.readSliceAll(&token) catch break :blk null; 2382 break :blk token; 2383 }; 2384 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 2385 } 2386 2387 pub fn deinit(self: SessionStore) void { 2388 self.flash_dir.close(self.io); 2389 self.dir.close(self.io); 2390 } 2391 2392 // mint a new session for user_id, returning the token hex to set as the 2393 // cookie value. 2394 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2395 var token: [evt.event_id_size]u8 = undefined; 2396 self.io.random(&token); 2397 const token_hex = std.fmt.bytesToHex(token, .lower); 2398 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2399 defer file.close(self.io); 2400 try file.writeStreamingAll(self.io, user_id); 2401 return token_hex; 2402 } 2403 2404 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 2405 var token: [evt.event_id_size]u8 = undefined; 2406 self.io.random(&token); 2407 const token_hex = std.fmt.bytesToHex(token, .lower); 2408 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 2409 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 2410 defer file.close(self.io); 2411 2412 var json: std.Io.Writer.Allocating = .init(allocator); 2413 defer json.deinit(); 2414 try std.json.Stringify.value(value, .{}, &json.writer); 2415 try file.writeStreamingAll(self.io, json.written()); 2416 return token_hex; 2417 } 2418 2419 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 2420 if (!isToken(token_hex)) return null; 2421 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 2422 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 2423 defer file.close(self.io); 2424 2425 var storage: [4096]u8 = undefined; 2426 var reader = file.reader(self.io, &storage); 2427 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 2428 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 2429 } 2430 2431 // resolve a cookie's token to its user_id. returns false (logged out) for a 2432 // missing, malformed, or unknown token. 2433 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2434 if (!isToken(token_hex)) return false; 2435 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2436 defer file.close(self.io); 2437 var storage: [evt.event_id_size]u8 = undefined; 2438 var file_reader = file.reader(self.io, &storage); 2439 file_reader.interface.readSliceAll(out) catch return false; 2440 return true; 2441 } 2442 2443 // revoke a session. a no-op for a missing or malformed token. 2444 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2445 if (!isToken(token_hex)) return; 2446 self.dir.deleteFile(self.io, token_hex) catch {}; 2447 } 2448 2449 // leave `token_hex`'s session for visitors arriving without one. only the 2450 // `try` fixture writes one. the name can't collide with a session token. 2451 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2452 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2453 defer file.close(self.io); 2454 try file.writeStreamingAll(self.io, token_hex); 2455 } 2456 2457 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2458 out.* = self.auto_login orelse return false; 2459 return true; 2460 } 2461 2462 const auto_login_name = "auto-login"; 2463 2464 // a token is exactly token_hex_len hex chars. validating before using the 2465 // value as a path keeps attacker-supplied cookies from escaping the 2466 // sessions dir (e.g. via "/" or ".." bytes). 2467 fn isToken(token_hex: []const u8) bool { 2468 if (token_hex.len != token_hex_len) return false; 2469 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2470 return true; 2471 } 2472 }; 2473