╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
2377 const trimmed = std.mem.trim(u8, pair, " \t"); 2378 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2379 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2380 return trimmed[eq + 1 ..]; 2381 } 2382 } 2383 } 2384 return null; 2385 } 2386 2387 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2388 var iter = std.mem.splitScalar(u8, body, '&'); 2389 while (iter.next()) |pair| { 2390 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2391 if (std.mem.eql(u8, pair[0..eq], key)) { 2392 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2393 } 2394 } 2395 return null; 2396 } 2397 2398 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2399 var buffer: [256]u8 = undefined; 2400 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2401 } 2402 2403 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2404 var out: std.ArrayList(u8) = .empty; 2405 errdefer out.deinit(allocator); 2406 var i: usize = 0; 2407 while (i < encoded.len) : (i += 1) { 2408 switch (encoded[i]) { 2409 '+' => try out.append(allocator, ' '), 2410 '%' => { 2411 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2412 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2413 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2414 try out.append(allocator, hi * 16 + lo); 2415 i += 2; 2416 }, 2417 else => try out.append(allocator, encoded[i]), 2418 } 2419 } 2420 return try out.toOwnedSlice(allocator); 2421 } 2422 2423 // disk-backed web session store. each login mints a random, opaque token 2424 // (not the user's id) that is stored as a file named by the token hex, whose 2425 // contents are the raw user_id bytes. authenticating a request is a lookup of 2426 // the cookie's token; logout deletes the file, revoking the session. there is 2427 // deliberately no expiry — a session lives until logout. form failures use 2428 // files in the flash subdirectory that the redirected GET consumes. the 2429 // directory is cleared whenever the server starts. 2430 pub const SessionStore = struct { 2431 io: std.Io, 2432 dir: std.Io.Dir, 2433 flash_dir: std.Io.Dir, 2434 auto_login: ?[token_hex_len]u8, 2435 2436 pub const token_hex_len = evt.event_id_size * 2; 2437 2438 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2439 try data_dir.createDirPath(io, "sessions"); 2440 const dir = try data_dir.openDir(io, "sessions", .{}); 2441 errdefer dir.close(io); 2442 try dir.deleteTree(io, "flash"); 2443 try dir.createDirPath(io, "flash"); 2444 const flash_dir = try dir.openDir(io, "flash", .{}); 2445 errdefer flash_dir.close(io); 2446 const auto_login = blk: { 2447 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2448 defer file.close(io); 2449 var token: [token_hex_len]u8 = undefined; 2450 var storage: [token_hex_len]u8 = undefined; 2451 var reader = file.reader(io, &storage); 2452 reader.interface.readSliceAll(&token) catch break :blk null; 2453 break :blk token; 2454 }; 2455 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 2456 } 2457 2458 pub fn deinit(self: SessionStore) void { 2459 self.flash_dir.close(self.io); 2460 self.dir.close(self.io); 2461 } 2462 2463 // mint a new session for user_id, returning the token hex to set as the 2464 // cookie value. 2465 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2466 var token: [evt.event_id_size]u8 = undefined; 2467 self.io.random(&token); 2468 const token_hex = std.fmt.bytesToHex(token, .lower); 2469 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2470 defer file.close(self.io); 2471 try file.writeStreamingAll(self.io, user_id); 2472 return token_hex; 2473 } 2474 2475 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 2476 var token: [evt.event_id_size]u8 = undefined; 2477 self.io.random(&token); 2478 const token_hex = std.fmt.bytesToHex(token, .lower); 2479 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 2480 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 2481 defer file.close(self.io); 2482 2483 var json: std.Io.Writer.Allocating = .init(allocator); 2484 defer json.deinit(); 2485 try std.json.Stringify.value(value, .{}, &json.writer); 2486 try file.writeStreamingAll(self.io, json.written()); 2487 return token_hex; 2488 } 2489 2490 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 2491 if (!isToken(token_hex)) return null; 2492 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 2493 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 2494 defer file.close(self.io); 2495 2496 var storage: [4096]u8 = undefined; 2497 var reader = file.reader(self.io, &storage); 2498 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 2499 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 2500 } 2501 2502 // resolve a cookie's token to its user_id. returns false (logged out) for a 2503 // missing, malformed, or unknown token. 2504 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2505 if (!isToken(token_hex)) return false; 2506 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2507 defer file.close(self.io); 2508 var storage: [evt.event_id_size]u8 = undefined; 2509 var file_reader = file.reader(self.io, &storage); 2510 file_reader.interface.readSliceAll(out) catch return false; 2511 return true; 2512 } 2513 2514 // revoke a session. a no-op for a missing or malformed token. 2515 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2516 if (!isToken(token_hex)) return; 2517 self.dir.deleteFile(self.io, token_hex) catch {}; 2518 } 2519 2520 // leave `token_hex`'s session for visitors arriving without one. only the 2521 // `try` fixture writes one. the name can't collide with a session token. 2522 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2523 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2524 defer file.close(self.io); 2525 try file.writeStreamingAll(self.io, token_hex); 2526 } 2527 2528 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2529 out.* = self.auto_login orelse return false; 2530 return true; 2531 } 2532 2533 const auto_login_name = "auto-login"; 2534 2535 // a token is exactly token_hex_len hex chars. validating before using the 2536 // value as a path keeps attacker-supplied cookies from escaping the 2537 // sessions dir (e.g. via "/" or ".." bytes). 2538 fn isToken(token_hex: []const u8) bool { 2539 if (token_hex.len != token_hex_len) return false; 2540 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2541 return true; 2542 } 2543 }; 2544