╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
2194 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2195 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2196 return trimmed[eq + 1 ..]; 2197 } 2198 } 2199 } 2200 return null; 2201 } 2202 2203 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2204 var iter = std.mem.splitScalar(u8, body, '&'); 2205 while (iter.next()) |pair| { 2206 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2207 if (std.mem.eql(u8, pair[0..eq], key)) { 2208 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2209 } 2210 } 2211 return null; 2212 } 2213 2214 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2215 var buffer: [256]u8 = undefined; 2216 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2217 } 2218 2219 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2220 var out: std.ArrayList(u8) = .empty; 2221 errdefer out.deinit(allocator); 2222 var i: usize = 0; 2223 while (i < encoded.len) : (i += 1) { 2224 switch (encoded[i]) { 2225 '+' => try out.append(allocator, ' '), 2226 '%' => { 2227 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2228 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2229 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2230 try out.append(allocator, hi * 16 + lo); 2231 i += 2; 2232 }, 2233 else => try out.append(allocator, encoded[i]), 2234 } 2235 } 2236 return try out.toOwnedSlice(allocator); 2237 } 2238 2239 // disk-backed web session store. each login mints a random, opaque token 2240 // (not the user's id) that is stored as a file named by the token hex, whose 2241 // contents are the raw user_id bytes. authenticating a request is a lookup of 2242 // the cookie's token; logout deletes the file, revoking the session. there is 2243 // deliberately no expiry — a session lives until logout. form failures use 2244 // files in the flash subdirectory that the redirected GET consumes. the 2245 // directory is cleared whenever the server starts. 2246 pub const SessionStore = struct { 2247 io: std.Io, 2248 dir: std.Io.Dir, 2249 flash_dir: std.Io.Dir, 2250 auto_login: ?[token_hex_len]u8, 2251 2252 pub const token_hex_len = evt.event_id_size * 2; 2253 2254 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2255 try data_dir.createDirPath(io, "sessions"); 2256 const dir = try data_dir.openDir(io, "sessions", .{}); 2257 errdefer dir.close(io); 2258 try dir.deleteTree(io, "flash"); 2259 try dir.createDirPath(io, "flash"); 2260 const flash_dir = try dir.openDir(io, "flash", .{}); 2261 errdefer flash_dir.close(io); 2262 const auto_login = blk: { 2263 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2264 defer file.close(io); 2265 var token: [token_hex_len]u8 = undefined; 2266 var storage: [token_hex_len]u8 = undefined; 2267 var reader = file.reader(io, &storage); 2268 reader.interface.readSliceAll(&token) catch break :blk null; 2269 break :blk token; 2270 }; 2271 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 2272 } 2273 2274 pub fn deinit(self: SessionStore) void { 2275 self.flash_dir.close(self.io); 2276 self.dir.close(self.io); 2277 } 2278 2279 // mint a new session for user_id, returning the token hex to set as the 2280 // cookie value. 2281 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2282 var token: [evt.event_id_size]u8 = undefined; 2283 self.io.random(&token); 2284 const token_hex = std.fmt.bytesToHex(token, .lower); 2285 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2286 defer file.close(self.io); 2287 try file.writeStreamingAll(self.io, user_id); 2288 return token_hex; 2289 } 2290 2291 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 2292 var token: [evt.event_id_size]u8 = undefined; 2293 self.io.random(&token); 2294 const token_hex = std.fmt.bytesToHex(token, .lower); 2295 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 2296 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 2297 defer file.close(self.io); 2298 2299 var json: std.Io.Writer.Allocating = .init(allocator); 2300 defer json.deinit(); 2301 try std.json.Stringify.value(value, .{}, &json.writer); 2302 try file.writeStreamingAll(self.io, json.written()); 2303 return token_hex; 2304 } 2305 2306 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 2307 if (!isToken(token_hex)) return null; 2308 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 2309 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 2310 defer file.close(self.io); 2311 2312 var storage: [4096]u8 = undefined; 2313 var reader = file.reader(self.io, &storage); 2314 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 2315 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 2316 } 2317 2318 // resolve a cookie's token to its user_id. returns false (logged out) for a 2319 // missing, malformed, or unknown token. 2320 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2321 if (!isToken(token_hex)) return false; 2322 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2323 defer file.close(self.io); 2324 var storage: [evt.event_id_size]u8 = undefined; 2325 var file_reader = file.reader(self.io, &storage); 2326 file_reader.interface.readSliceAll(out) catch return false; 2327 return true; 2328 } 2329 2330 // revoke a session. a no-op for a missing or malformed token. 2331 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2332 if (!isToken(token_hex)) return; 2333 self.dir.deleteFile(self.io, token_hex) catch {}; 2334 } 2335 2336 // leave `token_hex`'s session for visitors arriving without one. only the 2337 // `try` fixture writes one. the name can't collide with a session token. 2338 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2339 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2340 defer file.close(self.io); 2341 try file.writeStreamingAll(self.io, token_hex); 2342 } 2343 2344 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2345 out.* = self.auto_login orelse return false; 2346 return true; 2347 } 2348 2349 const auto_login_name = "auto-login"; 2350 2351 // a token is exactly token_hex_len hex chars. validating before using the 2352 // value as a path keeps attacker-supplied cookies from escaping the 2353 // sessions dir (e.g. via "/" or ".." bytes). 2354 fn isToken(token_hex: []const u8) bool { 2355 if (token_hex.len != token_hex_len) return false; 2356 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2357 return true; 2358 } 2359 }; 2360