╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const evt = @import("./event.zig"); 5 const serve_common = @import("./serve_common.zig"); 6 const ui = @import("./ui.zig"); 7 const xitui = xit.xitui; 8 const wgt = xitui.widget; 9 const Focus = xitui.focus.Focus; 10 const Grid = xitui.grid.Grid; 11 12 const cookie_name = "haxy_session"; 13 // flash cookie for surfacing the outcome of the most recent /login POST. 14 // set on the failure redirect, read and immediately expired on the next 15 // GET / so refreshing the page doesn't keep showing the error. 16 const login_failure_cookie = "haxy_login_failure"; 17 18 const Embed = struct { 19 path: []const u8, 20 content_type: []const u8, 21 body: []const u8, 22 }; 23 24 const embeds = [_]Embed{ 25 .{ .path = "index.html", .content_type = "text/html; charset=utf-8", .body = @embedFile("embed/index.html") }, 26 .{ .path = "script.js", .content_type = "text/javascript; charset=utf-8", .body = @embedFile("embed/script.js") }, 27 .{ .path = "term.ttf", .content_type = "font/ttf", .body = @embedFile("embed/term.ttf") }, 28 .{ .path = "haxy.wasm", .content_type = "application/wasm", .body = @embedFile("haxy.wasm") }, 29 }; 30 31 // what a web request is served from: the multi-user server (admin repo + 32 // login sessions) or a single local repo. 33 pub const Host = union(enum) { 34 remote: struct { 35 admin_repo_path: []const u8, 36 session_store: SessionStore, 37 }, 38 local: ui.RepoSource, 39 }; 40 41 pub fn handleConnection( 42 io: std.Io, 43 allocator: std.mem.Allocator, 44 stream: std.Io.net.Stream, 45 host: Host, 46 err: *std.Io.Writer, 47 ) !void { 48 var send_buffer = [_]u8{0} ** 4096; 49 var recv_buffer = [_]u8{0} ** 4096; 50 var conn_br = stream.reader(io, &recv_buffer); 51 var conn_bw = stream.writer(io, &send_buffer); 52 var http_server = std.http.Server.init(&conn_br.interface, &conn_bw.interface); 53 54 // serve multiple requests on a single connection so HTTP/1.1 keep-alive 55 // works — important for browser-native form POST: after the 303 the 56 // browser issues GET / on the same socket, and forcibly closing here 57 // would race the follow-up request into a "site can't be reached". 58 while (http_server.reader.state == .ready) { 59 var request = http_server.receiveHead() catch |receive_err| switch (receive_err) { 60 error.HttpConnectionClosing => break, 61 error.ReadFailed => break, 62 else => |e| return e, 63 }; 64 65 handleRequest(io, &request, allocator, host) catch |request_err| { 66 try err.print("web ui request failed: {s}\n", .{@errorName(request_err)}); 67 try err.flush(); 68 // best-effort 500. if handleRequest already started writing a 69 // response before throwing, this respond may fail too, but at 70 // that point the connection is unrecoverable anyway. 71 request.respond(@errorName(request_err), .{ 72 .status = .internal_server_error, 73 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 74 }) catch {}; 75 }; 76 } 77 } 78 79 fn handleRequest( 80 io: std.Io, 81 request: *std.http.Server.Request, 82 allocator: std.mem.Allocator, 83 host: Host, 84 ) !void { 85 const method = request.head.method; 86 const uri = try std.Uri.parseAfterScheme("", request.head.target); 87 const path = uri.path.percent_encoded; 88 89 // POST routes can be scoped by any page, so they can redirect using 90 // the base of the URL. this allows logging in to keep you on the page 91 // you were on. local mode has no accounts, so no POST routes. 92 if (method == .POST) { 93 switch (host) { 94 .remote => |remote| { 95 const PostRoute = enum { login, logout, ansi, issue }; 96 inline for (@typeInfo(PostRoute).@"enum".fields) |field| { 97 const suffix = "/" ++ field.name; 98 if (std.mem.endsWith(u8, path, suffix)) { 99 const base = path[0 .. path.len - suffix.len]; 100 return switch (@field(PostRoute, field.name)) { 101 .login => handleLogin(io, request, allocator, base, remote.admin_repo_path, remote.session_store), 102 .logout => handleLogout(request, base, remote.session_store), 103 .ansi => handleAnsi(io, request, allocator, base, remote.admin_repo_path, remote.session_store), 104 .issue => handleIssue(io, request, allocator, base, remote.admin_repo_path), 105 }; 106 } 107 } 108 }, 109 .local => {}, 110 } 111 } 112 113 const get_or_head = method == .GET or method == .HEAD; 114 if (!get_or_head) { 115 try request.respond("method not allowed", .{ 116 .status = .method_not_allowed, 117 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 118 }); 119 return; 120 } 121 122 if (std.mem.eql(u8, path, "/favicon.ico")) { 123 try request.respond("", .{ 124 .status = .no_content, 125 .extra_headers = &.{.{ .name = "content-type", .value = "image/x-icon" }}, 126 }); 127 return; 128 } 129 130 const current_page_maybe = switch (host) { 131 .remote => ui.RoutablePage.fromUrl(path), 132 .local => ui.RoutablePage.fromUrlLocal(path), 133 }; 134 if (current_page_maybe) |current_page| { 135 // resolve the haxy_session cookie's token to a user_id via the 136 // store. user_id_buf lives on the stack for the rest of handleRequest, 137 // which is plenty for renderIndexHtml to consume. local mode has no 138 // accounts, so it is always logged out. 139 var user_id_buf: [evt.event_id_size]u8 = undefined; 140 var user_id: ?[]const u8 = null; 141 var login_failure: ?ui.Home.Auth.Login.Failure = null; 142 switch (host) { 143 .remote => |remote| { 144 user_id = blk: { 145 const token = getCookieValue(request, cookie_name) orelse break :blk null; 146 if (!remote.session_store.lookup(token, &user_id_buf)) break :blk null; 147 break :blk user_id_buf[0..evt.event_id_size]; 148 }; 149 login_failure = if (getCookieValue(request, login_failure_cookie)) |raw| 150 if (std.mem.eql(u8, raw, "unknown_user")) 151 .unknown_user 152 else if (std.mem.eql(u8, raw, "wrong_password")) 153 .wrong_password 154 else 155 null 156 else 157 null; 158 }, 159 .local => {}, 160 } 161 162 const html = renderIndexHtml(io, allocator, host, .{ 163 .user_id = user_id, 164 .login_failure = login_failure, 165 .current_page = current_page, 166 .is_local = host == .local, 167 }) catch |err| switch (err) { 168 error.NotFound => { 169 try request.respond("not found", .{ 170 .status = .not_found, 171 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 172 }); 173 return; 174 }, 175 else => |e| return e, 176 }; 177 defer allocator.free(html); 178 179 // expire the flash cookie on the way out so a refresh doesn't keep 180 // showing the failure label. 181 var headers: [2]std.http.Header = undefined; 182 headers[0] = .{ .name = "content-type", .value = "text/html; charset=utf-8" }; 183 var headers_slice: []const std.http.Header = headers[0..1]; 184 if (login_failure != null) { 185 headers[1] = .{ .name = "set-cookie", .value = login_failure_cookie ++ "=; Path=/; Max-Age=0" }; 186 headers_slice = headers[0..2]; 187 } 188 try request.respond(html, .{ .extra_headers = headers_slice }); 189 return; 190 } 191 192 const embed = findEmbed(path) orelse { 193 try request.respond("not found", .{ 194 .status = .not_found, 195 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 196 }); 197 return; 198 }; 199 200 // the embeds change with every build, so the browser must revalidate 201 // rather than heuristically cache them across server restarts 202 try request.respond(embed.body, .{ 203 .extra_headers = &.{ 204 .{ .name = "content-type", .value = embed.content_type }, 205 .{ .name = "cache-control", .value = "no-cache" }, 206 }, 207 }); 208 } 209 210 fn handleLogin( 211 io: std.Io, 212 request: *std.http.Server.Request, 213 allocator: std.mem.Allocator, 214 base: []const u8, 215 admin_repo_path: []const u8, 216 session_store: SessionStore, 217 ) !void { 218 var body_buf: [256]u8 = undefined; 219 const reader = request.readerExpectNone(&body_buf); 220 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 221 defer allocator.free(body); 222 223 const username = (try parseFormField(allocator, body, "username")) orelse try allocator.dupe(u8, ""); 224 defer allocator.free(username); 225 const password = (try parseFormField(allocator, body, "password")) orelse try allocator.dupe(u8, ""); 226 defer allocator.free(password); 227 228 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 229 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 230 defer repo.deinit(io, allocator); 231 232 var arena = std.heap.ArenaAllocator.init(allocator); 233 defer arena.deinit(); 234 235 const haxy_moment = try evt.currentMoment(evt.admin_repo_opts, &repo); 236 const result = try evt.User.verifyCredentials(evt.AdminDB, evt.admin_repo_opts.hash, haxy_moment, &arena, username, password); 237 238 // on success, return to the page the login came from (base, or "/" at the 239 // root); on failure, stay on its auth tab to surface the error. 240 const success_location: []const u8 = if (base.len == 0) "/" else base; 241 const failure_location = try std.fmt.allocPrint(arena.allocator(), "{s}/auth", .{base}); 242 243 switch (result) { 244 .success => |user_id| { 245 const token = try session_store.create(&user_id); 246 var cookie_buf: [256]u8 = undefined; 247 const cookie = try std.fmt.bufPrint(&cookie_buf, cookie_name ++ "={s}; Path=/; HttpOnly; SameSite=Strict", .{token}); 248 try request.respond("", .{ 249 .status = .see_other, 250 .extra_headers = &.{ 251 .{ .name = "location", .value = success_location }, 252 .{ .name = "set-cookie", .value = cookie }, 253 }, 254 }); 255 }, 256 .unknown_user => { 257 try request.respond("", .{ 258 .status = .see_other, 259 .extra_headers = &.{ 260 .{ .name = "location", .value = failure_location }, 261 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=unknown_user; Path=/; HttpOnly; SameSite=Strict" }, 262 }, 263 }); 264 }, 265 .wrong_password => { 266 try request.respond("", .{ 267 .status = .see_other, 268 .extra_headers = &.{ 269 .{ .name = "location", .value = failure_location }, 270 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=wrong_password; Path=/; HttpOnly; SameSite=Strict" }, 271 }, 272 }); 273 }, 274 } 275 } 276 277 fn handleLogout(request: *std.http.Server.Request, base: []const u8, session_store: SessionStore) !void { 278 // revoke the session server-side so the cookie is dead for anyone holding 279 // a copy, not just this browser. 280 if (getCookieValue(request, cookie_name)) |token| session_store.remove(token); 281 // return to the page the logout came from (base, or "/" at the root). 282 const location: []const u8 = if (base.len == 0) "/" else base; 283 // close the connection instead of keeping it alive: we don't read the 284 // request body, and respond()'s keep-alive path would otherwise try to 285 // discard it — which asserts on a bodyless POST that carries no 286 // content-length, and would block on one with no framing at all. a logout 287 // is just a redirect, so the browser reconnects for the follow-up GET. 288 try request.respond("", .{ 289 .status = .see_other, 290 .keep_alive = false, 291 .extra_headers = &.{ 292 .{ .name = "location", .value = location }, 293 .{ .name = "set-cookie", .value = cookie_name ++ "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0" }, 294 }, 295 }); 296 } 297 298 fn handleAnsi( 299 io: std.Io, 300 request: *std.http.Server.Request, 301 allocator: std.mem.Allocator, 302 base: []const u8, 303 admin_repo_path: []const u8, 304 session_store: SessionStore, 305 ) !void { 306 var user_id: [evt.event_id_size]u8 = undefined; 307 if (getCookieValue(request, cookie_name)) |token| { 308 if (session_store.lookup(token, &user_id)) { 309 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 310 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 311 defer repo.deinit(io, allocator); 312 313 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, &repo, &user_id); 314 } 315 } 316 317 // return to the settings tab the toggle came from so the change is visible. 318 const location = try std.fmt.allocPrint(allocator, "{s}/settings", .{base}); 319 defer allocator.free(location); 320 321 // like logout, this is a bodyless POST, so close the connection rather than 322 // letting the keep-alive path try to discard a body that isn't framed. 323 try request.respond("", .{ 324 .status = .see_other, 325 .keep_alive = false, 326 .extra_headers = &.{ 327 .{ .name = "location", .value = location }, 328 }, 329 }); 330 } 331 332 // create an issue in the repo the form's page names (base is 333 // "/repo/<owner>/<name>") and redirect to it 334 fn handleIssue( 335 io: std.Io, 336 request: *std.http.Server.Request, 337 allocator: std.mem.Allocator, 338 base: []const u8, 339 admin_repo_path: []const u8, 340 ) !void { 341 var body_buf: [256]u8 = undefined; 342 const reader = request.readerExpectNone(&body_buf); 343 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 344 defer allocator.free(body); 345 346 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 347 defer allocator.free(title); 348 const tags = (try parseFormField(allocator, body, "tags")) orelse try allocator.dupe(u8, ""); 349 defer allocator.free(tags); 350 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 351 defer allocator.free(description_crlf); 352 // form submission normalizes textarea line breaks to CRLF; store plain 353 // newlines so the text renders the same on every host 354 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 355 defer allocator.free(description); 356 357 // a title is required, and a too-long tag would fail consumption after 358 // the event is already committed; both send the user back to the form 359 const valid = blk: { 360 if (title.len == 0) break :blk false; 361 var tag_iter = evt.Issue.tagIterator(tags); 362 while (tag_iter.next()) |tag| { 363 if (tag.len > evt.Issue.tag_max_len) break :blk false; 364 } 365 break :blk true; 366 }; 367 if (!valid) { 368 const form_location = try std.fmt.allocPrint(allocator, "{s}/issues/new", .{base}); 369 defer allocator.free(form_location); 370 try request.respond("", .{ 371 .status = .see_other, 372 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 373 }); 374 return; 375 } 376 377 const not_found = "repo not found"; 378 const repo_prefix = "/repo/"; 379 if (!std.mem.startsWith(u8, base, repo_prefix)) { 380 try request.respond(not_found, .{ 381 .status = .not_found, 382 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 383 }); 384 return; 385 } 386 387 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(admin_repo_path) orelse ".", "repos" }); 388 defer allocator.free(repos_dir); 389 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, repos_dir, admin_repo_path, base[repo_prefix.len..], false)) { 390 .ok => |p| p, 391 .invalid, .not_found => { 392 try request.respond(not_found, .{ 393 .status = .not_found, 394 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 395 }); 396 return; 397 }, 398 }; 399 defer allocator.free(repo_path); 400 401 var repo = try rp.Repo(.xit, .{}).open(io, allocator, .{ .path = repo_path }); 402 defer repo.deinit(io, allocator); 403 404 var id_bytes: [evt.event_id_size]u8 = undefined; 405 io.random(&id_bytes); 406 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 407 408 try evt.commitAndConsume(.xit, .{}, io, allocator, &repo, evt.events_ref, &[_]evt.EventWithId{.{ 409 .id = event_id_hex, 410 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 411 .event = .{ .issue = .{ 412 .title = title, 413 .description = description, 414 .tags = tags, 415 } }, 416 }}, false); 417 418 const location = try std.fmt.allocPrint(allocator, "{s}/issues/{s}", .{ base, &event_id_hex }); 419 defer allocator.free(location); 420 try request.respond("", .{ 421 .status = .see_other, 422 .extra_headers = &.{.{ .name = "location", .value = location }}, 423 }); 424 } 425 426 fn renderIndexHtml( 427 io: std.Io, 428 allocator: std.mem.Allocator, 429 host: Host, 430 session_data: ui.Session.Data, 431 ) ![]const u8 { 432 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 433 434 var page_arena = std.heap.ArenaAllocator.init(allocator); 435 defer page_arena.deinit(); 436 437 // the remote admin repo must outlive the page build, since the session's 438 // moment reads from it. 439 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 440 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 441 442 var session = switch (host) { 443 .remote => |remote| blk: { 444 // open the admin repo to read live user/repo data. 445 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 446 const repo = if (repo_maybe) |*repo| repo else unreachable; 447 var session = try ui.Session.init(&page_arena, repo, session_data); 448 // give the page builders filesystem access to the on-disk repos (a 449 // sibling "repos" dir next to the admin repo) so the Repo page can 450 // read its files. 451 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 452 break :blk session; 453 }, 454 .local => |local| ui.Session{ 455 .data = session_data, 456 .arena = &page_arena, 457 .page_arena = &page_arena, 458 .local = local, 459 }, 460 }; 461 session.io = io; 462 463 const snapshot: ui.Snapshot = .{ 464 .page = try ui.Page.init(session.page_arena, &session, session.data.current_page), 465 .session = session.data, 466 }; 467 var root = try ui.initRoot(allocator, &snapshot.page, &session); 468 defer root.deinit(allocator); 469 470 const content = try generateHtml(allocator, &root); 471 defer allocator.free(content); 472 const overlay = try generateOverlay(allocator, &root, &session); 473 defer allocator.free(overlay); 474 475 // serialize the snapshot so the wasm side can parse it back without making 476 // a second request. it's embedded raw in a <script type="application/json"> 477 // block, whose content is raw text terminated only by "</script". in json, 478 // '<' appears solely inside string values, so escaping every '<' (and '>' 479 // for good measure) to its \uXXXX form yields equivalent json that can't 480 // break out of the tag. 481 var json: std.Io.Writer.Allocating = .init(allocator); 482 defer json.deinit(); 483 try std.json.Stringify.value(snapshot, .{}, &json.writer); 484 485 var json_escaped: std.ArrayList(u8) = .empty; 486 defer json_escaped.deinit(allocator); 487 for (json.written()) |c| switch (c) { 488 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 489 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 490 else => try json_escaped.append(allocator, c), 491 }; 492 493 var out: std.ArrayList(u8) = .empty; 494 errdefer out.deinit(allocator); 495 { 496 var cursor: usize = 0; 497 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 498 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 499 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 500 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 501 }) |sub| { 502 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 503 try out.appendSlice(allocator, template[cursor..idx]); 504 try out.appendSlice(allocator, sub.replacement); 505 cursor = idx + sub.needle.len; 506 } 507 try out.appendSlice(allocator, template[cursor..]); 508 } 509 return try out.toOwnedSlice(allocator); 510 } 511 512 fn findEmbed(request_path: []const u8) ?Embed { 513 const path = if (std.mem.eql(u8, request_path, "/")) 514 "index.html" 515 else if (request_path.len > 1 and request_path[0] == '/') 516 request_path[1..] 517 else 518 return null; 519 520 for (embeds) |embed| { 521 if (std.mem.eql(u8, path, embed.path)) return embed; 522 } 523 return null; 524 } 525 526 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 527 // own absolutely-positioned, natively-scrollable <div> holding its full content, 528 // rendered recursively so nested scrolls work. 529 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 530 const grid = root.getGrid() orelse return error.MissingGrid; 531 532 var out: std.ArrayList(u8) = .empty; 533 errdefer out.deinit(allocator); 534 535 try renderPanel(allocator, &out, root.getFocus(), grid); 536 return try out.toOwnedSlice(allocator); 537 } 538 539 // render one panel — a focus subtree and its content grid — as HTML, recursing 540 // once per web-native Scroll inside it. the root panel is the whole page; each 541 // Scroll becomes a nested, natively-scrollable div holding its full content. 542 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 543 // then the child scroll divs over those holes. 544 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 545 // `direct` is this panel's scroll children, each drawn as an overlaid div. 546 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 547 // plus their descendants, which the focus tree flattens into this panel's 548 // children): the cell hit-test below skips them so this panel doesn't claim 549 // cells that are really rendered inside a child scroll's own panel. 550 // (scrolls aren't nested in practice, so every scroll child is direct here.) 551 var direct: std.ArrayList(usize) = .empty; 552 defer direct.deinit(allocator); 553 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 554 defer excluded.deinit(allocator); 555 { 556 var it = focus.children.iterator(); 557 while (it.next()) |e| { 558 if (e.value_ptr.focus.scroll == null) continue; 559 try direct.append(allocator, e.key_ptr.*); 560 try excluded.put(allocator, e.key_ptr.*, {}); 561 var mit = e.value_ptr.focus.children.iterator(); 562 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 563 } 564 } 565 566 // the HTML element a run of cells is wrapped in, chosen from the cell's 567 // focusable kind 568 const CellTag = union(enum) { 569 span, // clickable focusable cell 570 a: []const u8, // clickable focusable link 571 plain, // non-focusable, colored 572 573 const a_prefix = "a:"; 574 // an "in-page" anchor: rendered as a real <a href> so it works with js 575 // disabled, but crossPageLink ignores it, so with wasm the click just 576 // moves focus rather than navigating. 577 const inpage_prefix = "ai:"; 578 579 fn init(str: []const u8) @This() { 580 if (std.mem.startsWith(u8, str, inpage_prefix)) { 581 return .{ .a = str[inpage_prefix.len..] }; 582 } 583 if (std.mem.startsWith(u8, str, a_prefix)) { 584 return .{ .a = str[a_prefix.len..] }; 585 } 586 return .span; 587 } 588 589 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 590 var id_buf: [32]u8 = undefined; 591 switch (self) { 592 .span => { 593 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 594 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 595 try out.appendSlice(alloc, "\""); 596 try out.appendSlice(alloc, style_attr); 597 try out.appendSlice(alloc, ">"); 598 }, 599 .a => |href| { 600 // tabindex=-1 keeps these out of the browser's tab order 601 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 602 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 603 try out.appendSlice(alloc, "\" href=\""); 604 try appendEscapedHtml(alloc, out, href); 605 try out.appendSlice(alloc, "\""); 606 try out.appendSlice(alloc, style_attr); 607 try out.appendSlice(alloc, ">"); 608 }, 609 .plain => { 610 try out.appendSlice(alloc, "<span"); 611 try out.appendSlice(alloc, style_attr); 612 try out.appendSlice(alloc, ">"); 613 }, 614 } 615 } 616 617 fn closeTag(self: @This()) []const u8 { 618 return switch (self) { 619 .span, .plain => "</span>", 620 .a => "</a>", 621 }; 622 } 623 }; 624 625 // emit this panel's grid as rows of text, coalescing adjacent cells that 626 // share a focus id and colors into one tag (a clickable span, a link, or a 627 // plain colored span). cells under a child scroll keep only their background. 628 for (0..grid.size.height) |y| { 629 var cur_id: ?usize = null; 630 var cur_fg: ?Grid.Color = null; 631 var cur_bg: ?Grid.Color = null; 632 var open_tag: ?CellTag = null; 633 var first = true; 634 for (0..grid.size.width) |x| { 635 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 636 // a cell covered by a child scroll's viewport is drawn by that scroll's 637 // own div, so blank its glyph and make it non-clickable here — but keep 638 // its background, so the backdrop still shows through the scroll's 639 // transparent div instead of a bare hole. 640 const covered_by_scroll = blk: { 641 for (direct.items) |id| { 642 const r = (focus.children.get(id) orelse continue).rect; 643 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) break :blk true; 644 } 645 break :blk false; 646 }; 647 // the focusable cell at (x, y) among this panel's own focusables (skipping 648 // any that belong to a child scroll, whose cells are drawn in their own 649 // panel); none for a covered cell. 650 const cell_id = if (covered_by_scroll) null else blk: { 651 var iter = focus.children.iterator(); 652 while (iter.next()) |entry| { 653 const child = entry.value_ptr.*; 654 if (!child.focus.focusable) continue; 655 if (excluded.contains(entry.key_ptr.*)) continue; 656 const r = child.rect; 657 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 658 break :blk entry.key_ptr.*; 659 } 660 } 661 break :blk null; 662 }; 663 const fg = if (covered_by_scroll) null else cell.style.fg; 664 const bg = cell.style.bg; 665 666 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 667 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 668 669 var new_tag: ?CellTag = null; 670 if (cell_id) |id| { 671 if (focus.children.get(id)) |child| { 672 new_tag = switch (child.focus.kind) { 673 .custom => |custom| CellTag.init(custom), 674 else => .span, 675 }; 676 } 677 } 678 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 679 680 if (new_tag) |t| { 681 var style_buf: [64]u8 = undefined; 682 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 683 } 684 685 open_tag = new_tag; 686 cur_id = cell_id; 687 cur_fg = fg; 688 cur_bg = bg; 689 first = false; 690 } 691 692 try appendEscapedHtml(allocator, output, if (covered_by_scroll) " " else (cell.rune orelse " ")); 693 } 694 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 695 try output.append(allocator, '\n'); 696 } 697 698 // each child scroll becomes a natively-scrollable div positioned over its 699 // viewport, holding its full content rendered recursively. 700 for (direct.items) |id| { 701 const child = focus.children.get(id) orelse continue; 702 const info = child.focus.scroll orelse continue; 703 const r = child.rect; 704 // overflow only on the axes the widget scrolls; `auto` shows a bar only 705 // when that axis actually overflows. the other axis is clipped (hidden), 706 // matching how the terminal Scroll handles its non-scrolling axis. 707 const overflow = switch (info.direction) { 708 .vert => "overflow-x:hidden;overflow-y:auto", 709 .horiz => "overflow-x:auto;overflow-y:hidden", 710 .both => "overflow:auto", 711 }; 712 // the id carries a content version so JS preserves the native scroll 713 // position across re-renders of the same content but resets it when the 714 // content is replaced — e.g. selecting a different commit. the widget's 715 // scroll offset (in cells) rides along so JS can apply it when it has no 716 // preserved position, letting a wasm-side scrollToRect (the files list 717 // scrolling to its selected row on page load) reach the browser. 718 var buf: [224]u8 = undefined; 719 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, "<div class=\"scroll\" data-scroll-id=\"{d}-{d}\" data-scroll-x=\"{d}\" data-scroll-y=\"{d}\" style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em;{s}\">", .{ id, child.focus.version, info.offset_x, info.offset_y, r.x, r.y, r.size.width, r.size.height, overflow })); 720 try renderPanel(allocator, output, child.focus, info.content); 721 try output.appendSlice(allocator, "</div>"); 722 } 723 } 724 725 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 726 // widget tree, each wrapping the text inputs and submit button inside it, 727 // positioned absolutely over the matching grid cells. 728 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 729 const root_focus = root.getFocus(); 730 731 var out: std.ArrayList(u8) = .empty; 732 errdefer out.deinit(allocator); 733 734 const form_prefix = "form:"; 735 736 // Focus.children is an AutoArrayHashMap that preserves insertion order, 737 // which matches the order widgets were added in code 738 var iter = root_focus.children.iterator(); 739 while (iter.next()) |entry| { 740 const child = entry.value_ptr.*; 741 const action_url = switch (child.focus.kind) { 742 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 743 custom[form_prefix.len..] 744 else 745 continue, 746 else => continue, 747 }; 748 749 try out.appendSlice(allocator, "<form action=\""); 750 try appendEscapedHtml(allocator, &out, action_url); 751 try out.appendSlice(allocator, "\" method=\"post\""); 752 // an empty action must not POST — block it and send the input to the TUI instead 753 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 754 try out.appendSlice(allocator, ">"); 755 756 // form.focus.children was populated by addChild, which flattens the 757 // whole subtree into one map — so descendants (inputs + the submit 758 // button) all appear here. positions on form.focus are relative to 759 // the form, so we look up absolute rects via root_focus for layout. 760 var inner_iter = child.focus.children.iterator(); 761 while (inner_iter.next()) |inner_entry| { 762 const inner_id = inner_entry.key_ptr.*; 763 const root_child = root_focus.children.get(inner_id) orelse continue; 764 const r = root_child.rect; 765 switch (root_child.focus.kind) { 766 .text_input, .text_input_password => { 767 const ti = session.text_inputs.get(inner_id) orelse continue; 768 const inner_left = r.x + 1; 769 const inner_top = r.y + 1; 770 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 771 772 try out.appendSlice(allocator, "<input type=\""); 773 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 774 try out.appendSlice(allocator, "\" data-focus-id=\""); 775 var id_buf: [32]u8 = undefined; 776 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 777 if (ti.options.name.len > 0) { 778 try out.appendSlice(allocator, "\" name=\""); 779 try appendEscapedHtml(allocator, &out, ti.options.name); 780 } 781 // intentionally no `value` attribute: the browser tracks user input 782 // natively, and including the wasm-side value here would make the 783 // overlay HTML differ on every keystroke — that would trip the diff 784 // in _setOverlay and rebuild the <input>, eating the user's caret. 785 try out.appendSlice(allocator, "\" style=\"left:"); 786 var pos_buf: [64]u8 = undefined; 787 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:1em", .{ inner_left, inner_top, inner_width })); 788 try out.appendSlice(allocator, "\">"); 789 }, 790 .text_area => { 791 const ti = session.text_inputs.get(inner_id) orelse continue; 792 const inner_left = r.x + 1; 793 const inner_top = r.y + 1; 794 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 795 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 796 797 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 798 var id_buf: [32]u8 = undefined; 799 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 800 if (ti.options.name.len > 0) { 801 try out.appendSlice(allocator, "\" name=\""); 802 try appendEscapedHtml(allocator, &out, ti.options.name); 803 } 804 // like the input above, no content inside: the browser 805 // tracks the value and the overlay diff must stay stable 806 // across keystrokes 807 try out.appendSlice(allocator, "\" style=\"left:"); 808 var pos_buf: [128]u8 = undefined; 809 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ inner_left, inner_top, inner_width, inner_height })); 810 try out.appendSlice(allocator, "\"></textarea>"); 811 }, 812 .custom => |custom| { 813 if (std.mem.eql(u8, "submit", custom)) { 814 // inside the dashed border the TUI cells draw around the button. 815 const inner_left = r.x + 1; 816 const inner_top = r.y + 1; 817 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 818 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 819 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 820 var id_buf: [32]u8 = undefined; 821 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 822 try out.appendSlice(allocator, "\" style=\"left:"); 823 var pos_buf: [128]u8 = undefined; 824 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ inner_left, inner_top, inner_width, inner_height })); 825 try out.appendSlice(allocator, "\"></button>"); 826 } 827 }, 828 else => {}, 829 } 830 } 831 832 try out.appendSlice(allocator, "</form>"); 833 } 834 835 return try out.toOwnedSlice(allocator); 836 } 837 838 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 839 if (a) |av| return if (b) |bv| av.eql(bv) else false; 840 return b == null; 841 } 842 843 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 844 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 845 // empty slice when neither is set. 846 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 847 if (fg == null and bg == null) return buf[0..0]; 848 const prefix = " style=\""; 849 @memcpy(buf[0..prefix.len], prefix); 850 var i: usize = prefix.len; 851 if (fg) |c| { 852 const s = std.fmt.bufPrint(buf[i..], "color:#{x:0>2}{x:0>2}{x:0>2};", .{ c.r, c.g, c.b }) catch return buf[0..0]; 853 i += s.len; 854 } 855 if (bg) |c| { 856 const s = std.fmt.bufPrint(buf[i..], "background-color:#{x:0>2}{x:0>2}{x:0>2};", .{ c.r, c.g, c.b }) catch return buf[0..0]; 857 i += s.len; 858 } 859 buf[i] = '"'; 860 i += 1; 861 return buf[0..i]; 862 } 863 864 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 865 for (input) |ch| { 866 switch (ch) { 867 '&' => try out.appendSlice(allocator, "&amp;"), 868 '<' => try out.appendSlice(allocator, "&lt;"), 869 '>' => try out.appendSlice(allocator, "&gt;"), 870 '"' => try out.appendSlice(allocator, "&quot;"), 871 '\'' => try out.appendSlice(allocator, "&#39;"), 872 else => try out.append(allocator, ch), 873 } 874 } 875 } 876 877 // --- helpers -------------------------------------------------------------- 878 879 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 880 var iter = request.iterateHeaders(); 881 while (iter.next()) |header| { 882 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 883 var pairs = std.mem.splitScalar(u8, header.value, ';'); 884 while (pairs.next()) |pair| { 885 const trimmed = std.mem.trim(u8, pair, " \t"); 886 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 887 if (std.mem.eql(u8, trimmed[0..eq], name)) { 888 return trimmed[eq + 1 ..]; 889 } 890 } 891 } 892 return null; 893 } 894 895 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 896 var iter = std.mem.splitScalar(u8, body, '&'); 897 while (iter.next()) |pair| { 898 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 899 if (std.mem.eql(u8, pair[0..eq], key)) { 900 return try decodeFormValue(allocator, pair[eq + 1 ..]); 901 } 902 } 903 return null; 904 } 905 906 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 907 var out: std.ArrayList(u8) = .empty; 908 errdefer out.deinit(allocator); 909 var i: usize = 0; 910 while (i < encoded.len) : (i += 1) { 911 switch (encoded[i]) { 912 '+' => try out.append(allocator, ' '), 913 '%' => { 914 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 915 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 916 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 917 try out.append(allocator, hi * 16 + lo); 918 i += 2; 919 }, 920 else => try out.append(allocator, encoded[i]), 921 } 922 } 923 return try out.toOwnedSlice(allocator); 924 } 925 926 // disk-backed web session store. each login mints a random, opaque token 927 // (not the user's id) that is stored as a file named by the token hex, whose 928 // contents are the raw user_id bytes. authenticating a request is a lookup of 929 // the cookie's token; logout deletes the file, revoking the session. there is 930 // deliberately no expiry — a session lives until logout. 931 pub const SessionStore = struct { 932 io: std.Io, 933 dir: std.Io.Dir, 934 935 pub const token_hex_len = evt.event_id_size * 2; 936 937 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 938 try data_dir.createDirPath(io, "sessions"); 939 const dir = try data_dir.openDir(io, "sessions", .{}); 940 return .{ .io = io, .dir = dir }; 941 } 942 943 pub fn deinit(self: SessionStore) void { 944 self.dir.close(self.io); 945 } 946 947 // mint a new session for user_id, returning the token hex to set as the 948 // cookie value. 949 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 950 var token: [evt.event_id_size]u8 = undefined; 951 self.io.random(&token); 952 const token_hex = std.fmt.bytesToHex(token, .lower); 953 const file = try self.dir.createFile(self.io, &token_hex, .{}); 954 defer file.close(self.io); 955 try file.writeStreamingAll(self.io, user_id); 956 return token_hex; 957 } 958 959 // resolve a cookie's token to its user_id. returns false (logged out) for a 960 // missing, malformed, or unknown token. 961 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 962 if (!isToken(token_hex)) return false; 963 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 964 defer file.close(self.io); 965 var storage: [evt.event_id_size]u8 = undefined; 966 var file_reader = file.reader(self.io, &storage); 967 file_reader.interface.readSliceAll(out) catch return false; 968 return true; 969 } 970 971 // revoke a session. a no-op for a missing or malformed token. 972 pub fn remove(self: SessionStore, token_hex: []const u8) void { 973 if (!isToken(token_hex)) return; 974 self.dir.deleteFile(self.io, token_hex) catch {}; 975 } 976 977 // a token is exactly token_hex_len hex chars. validating before using the 978 // value as a path keeps attacker-supplied cookies from escaping the 979 // sessions dir (e.g. via "/" or ".." bytes). 980 fn isToken(token_hex: []const u8) bool { 981 if (token_hex.len != token_hex_len) return false; 982 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 983 return true; 984 } 985 }; 986