╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
2993 '&' => try out.appendSlice(allocator, "&amp;"), 2994 '<' => try out.appendSlice(allocator, "&lt;"), 2995 '>' => try out.appendSlice(allocator, "&gt;"), 2996 '"' => try out.appendSlice(allocator, "&quot;"), 2997 '\'' => try out.appendSlice(allocator, "&#39;"), 2998 else => try out.append(allocator, ch), 2999 } 3000 } 3001 } 3002 3003 // --- helpers -------------------------------------------------------------- 3004 3005 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 3006 var iter = request.iterateHeaders(); 3007 while (iter.next()) |header| { 3008 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 3009 var pairs = std.mem.splitScalar(u8, header.value, ';'); 3010 while (pairs.next()) |pair| { 3011 const trimmed = std.mem.trim(u8, pair, " \t"); 3012 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 3013 if (std.mem.eql(u8, trimmed[0..eq], name)) { 3014 return trimmed[eq + 1 ..]; 3015 } 3016 } 3017 } 3018 return null; 3019 } 3020 3021 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 3022 var iter = std.mem.splitScalar(u8, body, '&'); 3023 while (iter.next()) |pair| { 3024 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 3025 if (std.mem.eql(u8, pair[0..eq], key)) { 3026 return try decodeFormValue(allocator, pair[eq + 1 ..]); 3027 } 3028 } 3029 return null; 3030 } 3031 3032 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 3033 var buffer: [256]u8 = undefined; 3034 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 3035 } 3036 3037 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 3038 var out: std.ArrayList(u8) = .empty; 3039 errdefer out.deinit(allocator); 3040 var i: usize = 0; 3041 while (i < encoded.len) : (i += 1) { 3042 switch (encoded[i]) { 3043 '+' => try out.append(allocator, ' '), 3044 '%' => { 3045 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 3046 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 3047 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 3048 try out.append(allocator, hi * 16 + lo); 3049 i += 2; 3050 }, 3051 else => try out.append(allocator, encoded[i]), 3052 } 3053 } 3054 return try out.toOwnedSlice(allocator); 3055 } 3056 3057 // disk-backed web session store. each login mints a random, opaque token 3058 // (not the user's id) that is stored as a file named by the token hex, whose 3059 // contents are the raw user_id bytes. authenticating a request is a lookup of 3060 // the cookie's token; logout deletes the file, revoking the session. there is 3061 // deliberately no expiry — a session lives until logout. form failures use 3062 // files in the flash subdirectory that the redirected GET consumes. the 3063 // directory is cleared whenever the server starts. 3064 pub const SessionStore = struct { 3065 io: std.Io, 3066 dir: std.Io.Dir, 3067 flash_dir: std.Io.Dir, 3068 auto_login: ?[token_hex_len]u8, 3069 3070 pub const token_hex_len = evt.event_id_size * 2; 3071 3072 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 3073 try data_dir.createDirPath(io, "sessions"); 3074 const dir = try data_dir.openDir(io, "sessions", .{}); 3075 errdefer dir.close(io); 3076 try dir.deleteTree(io, "flash"); 3077 try dir.createDirPath(io, "flash"); 3078 const flash_dir = try dir.openDir(io, "flash", .{}); 3079 errdefer flash_dir.close(io); 3080 const auto_login = blk: { 3081 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 3082 defer file.close(io); 3083 var token: [token_hex_len]u8 = undefined; 3084 var storage: [token_hex_len]u8 = undefined; 3085 var reader = file.reader(io, &storage); 3086 reader.interface.readSliceAll(&token) catch break :blk null; 3087 break :blk token; 3088 }; 3089 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 3090 } 3091 3092 pub fn deinit(self: SessionStore) void { 3093 self.flash_dir.close(self.io); 3094 self.dir.close(self.io); 3095 } 3096 3097 // mint a new session for user_id, returning the token hex to set as the 3098 // cookie value. 3099 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 3100 var token: [evt.event_id_size]u8 = undefined; 3101 self.io.random(&token); 3102 const token_hex = std.fmt.bytesToHex(token, .lower); 3103 const file = try self.dir.createFile(self.io, &token_hex, .{}); 3104 defer file.close(self.io); 3105 try file.writeStreamingAll(self.io, user_id); 3106 return token_hex; 3107 } 3108 3109 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 3110 var token: [evt.event_id_size]u8 = undefined; 3111 self.io.random(&token); 3112 const token_hex = std.fmt.bytesToHex(token, .lower); 3113 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 3114 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 3115 defer file.close(self.io); 3116 3117 var json: std.Io.Writer.Allocating = .init(allocator); 3118 defer json.deinit(); 3119 try std.json.Stringify.value(value, .{}, &json.writer); 3120 try file.writeStreamingAll(self.io, json.written()); 3121 return token_hex; 3122 } 3123 3124 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 3125 if (!isToken(token_hex)) return null; 3126 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 3127 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 3128 defer file.close(self.io); 3129 3130 var storage: [4096]u8 = undefined; 3131 var reader = file.reader(self.io, &storage); 3132 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 3133 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 3134 } 3135 3136 // resolve a cookie's token to its user_id. returns false (logged out) for a 3137 // missing, malformed, or unknown token. 3138 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 3139 if (!isToken(token_hex)) return false; 3140 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 3141 defer file.close(self.io); 3142 var storage: [evt.event_id_size]u8 = undefined; 3143 var file_reader = file.reader(self.io, &storage); 3144 file_reader.interface.readSliceAll(out) catch return false; 3145 return true; 3146 } 3147 3148 // revoke a session. a no-op for a missing or malformed token. 3149 pub fn remove(self: SessionStore, token_hex: []const u8) void { 3150 if (!isToken(token_hex)) return; 3151 self.dir.deleteFile(self.io, token_hex) catch {}; 3152 } 3153 3154 // leave `token_hex`'s session for visitors arriving without one. only the 3155 // `try` fixture writes one. the name can't collide with a session token. 3156 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 3157 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 3158 defer file.close(self.io); 3159 try file.writeStreamingAll(self.io, token_hex); 3160 } 3161 3162 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 3163 out.* = self.auto_login orelse return false; 3164 return true; 3165 } 3166 3167 const auto_login_name = "auto-login"; 3168 3169 // a token is exactly token_hex_len hex chars. validating before using the 3170 // value as a path keeps attacker-supplied cookies from escaping the 3171 // sessions dir (e.g. via "/" or ".." bytes). 3172 fn isToken(token_hex: []const u8) bool { 3173 if (token_hex.len != token_hex_len) return false; 3174 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 3175 return true; 3176 } 3177 }; 3178