╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
2233 try appendFormAttribute(allocator, output, root_focus, id); 2234 if (ti.options.name.len > 0) { 2235 try output.appendSlice(allocator, " name=\""); 2236 try appendEscapedHtml(allocator, output, ti.options.name); 2237 try output.append(allocator, '"'); 2238 } 2239 if (child.focus.kind != .text_input_password) { 2240 const value = try ti.text(allocator); 2241 defer allocator.free(value); 2242 try output.appendSlice(allocator, " value=\""); 2243 try appendEscapedHtml(allocator, output, value); 2244 try output.append(allocator, '"'); 2245 } 2246 var pos_buf: [96]u8 = undefined; 2247 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 })); 2248 }, 2249 .custom => |custom| { 2250 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2251 if (formOwner(root_focus, id) == null) continue; 2252 var id_buf: [128]u8 = undefined; 2253 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2254 try appendFormAttribute(allocator, output, root_focus, id); 2255 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2256 try output.appendSlice(allocator, " formaction=\""); 2257 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 2258 try output.append(allocator, '"'); 2259 } 2260 var pos_buf: [128]u8 = undefined; 2261 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 })); 2262 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 2263 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 2264 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 2265 var id_buf: [128]u8 = undefined; 2266 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 })); 2267 } 2268 }, 2269 else => {}, 2270 } 2271 } 2272 } 2273 2274 // emit hidden form owners beside the rendered panels. their controls point 2275 // back here with the standard HTML `form` attribute. 2276 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 2277 // the focus child map preserves insertion order, which matches the order 2278 // widgets were added in code 2279 var iter = root_focus.children.iterator(); 2280 while (iter.next()) |entry| { 2281 const child = entry.value_ptr.*; 2282 const action_url = formAction(child.focus) orelse continue; 2283 2284 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 2285 var id_buf: [96]u8 = undefined; 2286 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 2287 try appendEscapedHtml(allocator, output, action_url); 2288 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 2289 } 2290 } 2291 2292 // the 16 ansi colors as the browser shows them (xterm's defaults) 2293 const ansi_palette = [16]Grid.Color.Rgb{ 2294 .{ .r = 0x00, .g = 0x00, .b = 0x00 }, .{ .r = 0xcd, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xcd, .b = 0x00 }, .{ .r = 0xcd, .g = 0xcd, .b = 0x00 }, 2295 .{ .r = 0x00, .g = 0x00, .b = 0xee }, .{ .r = 0xcd, .g = 0x00, .b = 0xcd }, .{ .r = 0x00, .g = 0xcd, .b = 0xcd }, .{ .r = 0xe5, .g = 0xe5, .b = 0xe5 }, 2296 .{ .r = 0x7f, .g = 0x7f, .b = 0x7f }, .{ .r = 0xff, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xff, .b = 0x00 }, .{ .r = 0xff, .g = 0xff, .b = 0x00 }, 2297 .{ .r = 0x5c, .g = 0x5c, .b = 0xff }, .{ .r = 0xff, .g = 0x00, .b = 0xff }, .{ .r = 0x00, .g = 0xff, .b = 0xff }, .{ .r = 0xff, .g = 0xff, .b = 0xff }, 2298 }; 2299 2300 // resolve any color to rgb: palette colors through the ansi table and the 2301 // xterm 256-color layout (16 ansi, a 6x6x6 cube, then 24 grays) 2302 fn colorRgb(color: Grid.Color) Grid.Color.Rgb { 2303 return switch (color) { 2304 .rgb => |c| c, 2305 .ansi => |a| ansi_palette[@intFromEnum(a)], 2306 .indexed => |n| if (n < 16) 2307 ansi_palette[n] 2308 else if (n < 232) blk: { 2309 const levels = [6]u8{ 0, 0x5f, 0x87, 0xaf, 0xd7, 0xff }; 2310 const i = n - 16; 2311 break :blk .{ .r = levels[i / 36], .g = levels[(i / 6) % 6], .b = levels[i % 6] }; 2312 } else blk: { 2313 const v: u8 = 8 + (n - 232) * 10; 2314 break :blk .{ .r = v, .g = v, .b = v }; 2315 }, 2316 }; 2317 } 2318 2319 // builds an HTML ` style="color:…;background-color:…"` attribute from a 2320 // cell's fg/bg into `buf`, omitting whichever color is unset. an inverted 2321 // cell swaps the two, falling back to the page's --fg/--bg variables for 2322 // whichever side is unset. returns an empty slice when nothing is set. 2323 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color, inverted: bool) []const u8 { 2324 if (fg == null and bg == null and !inverted) return buf[0..0]; 2325 const prefix = " style=\""; 2326 @memcpy(buf[0..prefix.len], prefix); 2327 var i: usize = prefix.len; 2328 i = cssColor(buf, i, "color", if (inverted) bg else fg, if (inverted) "var(--bg)" else null) orelse return buf[0..0]; 2329 i = cssColor(buf, i, "background-color", if (inverted) fg else bg, if (inverted) "var(--fg)" else null) orelse return buf[0..0]; 2330 buf[i] = '"'; 2331 return buf[0 .. i + 1]; 2332 } 2333 2334 // append `prop:value;` at buf[i..] for the color, or for the fallback when 2335 // the color is unset (nothing when both are). returns the new end, or null 2336 // when it doesn't fit. 2337 fn cssColor(buf: []u8, i: usize, prop: []const u8, color: ?Grid.Color, fallback: ?[]const u8) ?usize { 2338 const s = if (color) |c| blk: { 2339 const v = colorRgb(c); 2340 break :blk std.fmt.bufPrint(buf[i..], "{s}:#{x:0>2}{x:0>2}{x:0>2};", .{ prop, v.r, v.g, v.b }) catch return null; 2341 } else if (fallback) |f| 2342 std.fmt.bufPrint(buf[i..], "{s}:{s};", .{ prop, f }) catch return null 2343 else 2344 return i; 2345 return i + s.len; 2346 } 2347 2348 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2349 for (input) |ch| { 2350 switch (ch) { 2351 '&' => try out.appendSlice(allocator, "&amp;"), 2352 '<' => try out.appendSlice(allocator, "&lt;"), 2353 '>' => try out.appendSlice(allocator, "&gt;"), 2354 '"' => try out.appendSlice(allocator, "&quot;"), 2355 '\'' => try out.appendSlice(allocator, "&#39;"), 2356 else => try out.append(allocator, ch), 2357 } 2358 } 2359 } 2360 2361 // --- helpers -------------------------------------------------------------- 2362 2363 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 2364 var iter = request.iterateHeaders(); 2365 while (iter.next()) |header| { 2366 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2367 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2368 while (pairs.next()) |pair| { 2369 const trimmed = std.mem.trim(u8, pair, " \t"); 2370 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2371 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2372 return trimmed[eq + 1 ..]; 2373 } 2374 } 2375 } 2376 return null; 2377 } 2378 2379 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2380 var iter = std.mem.splitScalar(u8, body, '&'); 2381 while (iter.next()) |pair| { 2382 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2383 if (std.mem.eql(u8, pair[0..eq], key)) { 2384 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2385 } 2386 } 2387 return null; 2388 } 2389 2390 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2391 var buffer: [256]u8 = undefined; 2392 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2393 } 2394 2395 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2396 var out: std.ArrayList(u8) = .empty; 2397 errdefer out.deinit(allocator); 2398 var i: usize = 0; 2399 while (i < encoded.len) : (i += 1) { 2400 switch (encoded[i]) { 2401 '+' => try out.append(allocator, ' '), 2402 '%' => { 2403 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2404 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2405 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2406 try out.append(allocator, hi * 16 + lo); 2407 i += 2; 2408 }, 2409 else => try out.append(allocator, encoded[i]), 2410 } 2411 } 2412 return try out.toOwnedSlice(allocator); 2413 } 2414 2415 // disk-backed web session store. each login mints a random, opaque token 2416 // (not the user's id) that is stored as a file named by the token hex, whose 2417 // contents are the raw user_id bytes. authenticating a request is a lookup of 2418 // the cookie's token; logout deletes the file, revoking the session. there is 2419 // deliberately no expiry — a session lives until logout. form failures use 2420 // files in the flash subdirectory that the redirected GET consumes. the 2421 // directory is cleared whenever the server starts. 2422 pub const SessionStore = struct { 2423 io: std.Io, 2424 dir: std.Io.Dir, 2425 flash_dir: std.Io.Dir, 2426 auto_login: ?[token_hex_len]u8, 2427 2428 pub const token_hex_len = evt.event_id_size * 2; 2429 2430 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2431 try data_dir.createDirPath(io, "sessions"); 2432 const dir = try data_dir.openDir(io, "sessions", .{}); 2433 errdefer dir.close(io); 2434 try dir.deleteTree(io, "flash"); 2435 try dir.createDirPath(io, "flash"); 2436 const flash_dir = try dir.openDir(io, "flash", .{}); 2437 errdefer flash_dir.close(io); 2438 const auto_login = blk: { 2439 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2440 defer file.close(io); 2441 var token: [token_hex_len]u8 = undefined; 2442 var storage: [token_hex_len]u8 = undefined; 2443 var reader = file.reader(io, &storage); 2444 reader.interface.readSliceAll(&token) catch break :blk null; 2445 break :blk token; 2446 }; 2447 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 2448 } 2449 2450 pub fn deinit(self: SessionStore) void { 2451 self.flash_dir.close(self.io); 2452 self.dir.close(self.io); 2453 } 2454 2455 // mint a new session for user_id, returning the token hex to set as the 2456 // cookie value. 2457 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2458 var token: [evt.event_id_size]u8 = undefined; 2459 self.io.random(&token); 2460 const token_hex = std.fmt.bytesToHex(token, .lower); 2461 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2462 defer file.close(self.io); 2463 try file.writeStreamingAll(self.io, user_id); 2464 return token_hex; 2465 } 2466 2467 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 2468 var token: [evt.event_id_size]u8 = undefined; 2469 self.io.random(&token); 2470 const token_hex = std.fmt.bytesToHex(token, .lower); 2471 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 2472 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 2473 defer file.close(self.io); 2474 2475 var json: std.Io.Writer.Allocating = .init(allocator); 2476 defer json.deinit(); 2477 try std.json.Stringify.value(value, .{}, &json.writer); 2478 try file.writeStreamingAll(self.io, json.written()); 2479 return token_hex; 2480 } 2481 2482 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 2483 if (!isToken(token_hex)) return null; 2484 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 2485 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 2486 defer file.close(self.io); 2487 2488 var storage: [4096]u8 = undefined; 2489 var reader = file.reader(self.io, &storage); 2490 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 2491 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 2492 } 2493 2494 // resolve a cookie's token to its user_id. returns false (logged out) for a 2495 // missing, malformed, or unknown token. 2496 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2497 if (!isToken(token_hex)) return false; 2498 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2499 defer file.close(self.io); 2500 var storage: [evt.event_id_size]u8 = undefined; 2501 var file_reader = file.reader(self.io, &storage); 2502 file_reader.interface.readSliceAll(out) catch return false; 2503 return true; 2504 } 2505 2506 // revoke a session. a no-op for a missing or malformed token. 2507 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2508 if (!isToken(token_hex)) return; 2509 self.dir.deleteFile(self.io, token_hex) catch {}; 2510 } 2511 2512 // leave `token_hex`'s session for visitors arriving without one. only the 2513 // `try` fixture writes one. the name can't collide with a session token. 2514 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2515 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2516 defer file.close(self.io); 2517 try file.writeStreamingAll(self.io, token_hex); 2518 } 2519 2520 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2521 out.* = self.auto_login orelse return false; 2522 return true; 2523 } 2524 2525 const auto_login_name = "auto-login"; 2526 2527 // a token is exactly token_hex_len hex chars. validating before using the 2528 // value as a path keeps attacker-supplied cookies from escaping the 2529 // sessions dir (e.g. via "/" or ".." bytes). 2530 fn isToken(token_hex: []const u8) bool { 2531 if (token_hex.len != token_hex_len) return false; 2532 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2533 return true; 2534 } 2535 }; 2536