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