╭ 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 ui = @import("./ui.zig"); 6 const xitui = xit.xitui; 7 const wgt = xitui.widget; 8 const Focus = xitui.focus.Focus; 9 const Grid = xitui.grid.Grid; 10 11 const cookie_name = "haxy_session"; 12 // flash cookie for surfacing the outcome of the most recent /login POST. 13 // set on the failure redirect, read and immediately expired on the next 14 // GET / so refreshing the page doesn't keep showing the error. 15 const login_failure_cookie = "haxy_login_failure"; 16 17 const Embed = struct { 18 path: []const u8, 19 content_type: []const u8, 20 body: []const u8, 21 }; 22 23 const embeds = [_]Embed{ 24 .{ .path = "index.html", .content_type = "text/html; charset=utf-8", .body = @embedFile("embed/index.html") }, 25 .{ .path = "script.js", .content_type = "text/javascript; charset=utf-8", .body = @embedFile("embed/script.js") }, 26 .{ .path = "term.ttf", .content_type = "font/ttf", .body = @embedFile("embed/term.ttf") }, 27 .{ .path = "haxy.wasm", .content_type = "application/wasm", .body = @embedFile("embed/haxy.wasm") }, 28 }; 29 30 pub fn run( 31 io: std.Io, 32 allocator: std.mem.Allocator, 33 net_server: *std.Io.net.Server, 34 tasks: *std.Io.Group, 35 admin_repo_path: []const u8, 36 session_store: SessionStore, 37 err: *std.Io.Writer, 38 ) void { 39 const Listener = struct { 40 io: std.Io, 41 allocator: std.mem.Allocator, 42 net_server: *std.Io.net.Server, 43 tasks: *std.Io.Group, 44 admin_repo_path: []const u8, 45 session_store: SessionStore, 46 err: *std.Io.Writer, 47 48 fn run(ctx: @This()) void { 49 while (true) { 50 const stream = ctx.net_server.accept(ctx.io) catch |accept_err| { 51 if (accept_err == error.Canceled) return; 52 logError(ctx.err, "web ui accept failed: {s}\n", .{@errorName(accept_err)}); 53 continue; 54 }; 55 56 const Connection = struct { 57 io: std.Io, 58 allocator: std.mem.Allocator, 59 stream: std.Io.net.Stream, 60 admin_repo_path: []const u8, 61 session_store: SessionStore, 62 err: *std.Io.Writer, 63 64 fn run(conn: @This()) void { 65 defer conn.stream.close(conn.io); 66 handleConnection(conn.io, conn.allocator, conn.stream, conn.admin_repo_path, conn.session_store, conn.err) catch |request_err| { 67 logError(conn.err, "web ui request failed: {s}\n", .{@errorName(request_err)}); 68 }; 69 } 70 }; 71 72 ctx.tasks.async(ctx.io, Connection.run, .{Connection{ 73 .io = ctx.io, 74 .allocator = ctx.allocator, 75 .stream = stream, 76 .admin_repo_path = ctx.admin_repo_path, 77 .session_store = ctx.session_store, 78 .err = ctx.err, 79 }}); 80 } 81 } 82 }; 83 84 tasks.async(io, Listener.run, .{Listener{ 85 .io = io, 86 .allocator = allocator, 87 .net_server = net_server, 88 .tasks = tasks, 89 .admin_repo_path = admin_repo_path, 90 .session_store = session_store, 91 .err = err, 92 }}); 93 } 94 95 fn handleConnection( 96 io: std.Io, 97 allocator: std.mem.Allocator, 98 stream: std.Io.net.Stream, 99 admin_repo_path: []const u8, 100 session_store: SessionStore, 101 err: *std.Io.Writer, 102 ) !void { 103 var send_buffer = [_]u8{0} ** 4096; 104 var recv_buffer = [_]u8{0} ** 4096; 105 var conn_br = stream.reader(io, &recv_buffer); 106 var conn_bw = stream.writer(io, &send_buffer); 107 var http_server = std.http.Server.init(&conn_br.interface, &conn_bw.interface); 108 109 // serve multiple requests on a single connection so HTTP/1.1 keep-alive 110 // works — important for browser-native form POST: after the 303 the 111 // browser issues GET / on the same socket, and forcibly closing here 112 // would race the follow-up request into a "site can't be reached". 113 while (http_server.reader.state == .ready) { 114 var request = http_server.receiveHead() catch |receive_err| switch (receive_err) { 115 error.HttpConnectionClosing => break, 116 error.ReadFailed => break, 117 else => |e| return e, 118 }; 119 120 handleRequest(io, &request, allocator, admin_repo_path, session_store) catch |request_err| { 121 try err.print("web ui request failed: {s}\n", .{@errorName(request_err)}); 122 try err.flush(); 123 // best-effort 500. if handleRequest already started writing a 124 // response before throwing, this respond may fail too, but at 125 // that point the connection is unrecoverable anyway. 126 request.respond(@errorName(request_err), .{ 127 .status = .internal_server_error, 128 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 129 }) catch {}; 130 }; 131 } 132 } 133 134 fn handleRequest( 135 io: std.Io, 136 request: *std.http.Server.Request, 137 allocator: std.mem.Allocator, 138 admin_repo_path: []const u8, 139 session_store: SessionStore, 140 ) !void { 141 const method = request.head.method; 142 const uri = try std.Uri.parseAfterScheme("", request.head.target); 143 const path = uri.path.percent_encoded; 144 145 // login/logout are page-scoped. the base (the path minus the trailing verb) 146 // is where we redirect afterward, so logging in keeps you on the page you 147 // were on instead of jumping to the home view. 148 if (method == .POST and std.mem.endsWith(u8, path, "/login")) { 149 return handleLogin(io, request, allocator, path[0 .. path.len - "/login".len], admin_repo_path, session_store); 150 } 151 if (method == .POST and std.mem.endsWith(u8, path, "/logout")) { 152 return handleLogout(request, path[0 .. path.len - "/logout".len], session_store); 153 } 154 if (method == .POST and std.mem.endsWith(u8, path, "/ansi")) { 155 return handleAnsi(io, request, allocator, path[0 .. path.len - "/ansi".len], admin_repo_path, session_store); 156 } 157 158 const get_or_head = method == .GET or method == .HEAD; 159 if (!get_or_head) { 160 try request.respond("method not allowed", .{ 161 .status = .method_not_allowed, 162 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 163 }); 164 return; 165 } 166 167 if (std.mem.eql(u8, path, "/favicon.ico")) { 168 try request.respond("", .{ 169 .status = .no_content, 170 .extra_headers = &.{.{ .name = "content-type", .value = "image/x-icon" }}, 171 }); 172 return; 173 } 174 175 if (ui.RoutablePage.fromUrl(path)) |current_page| { 176 // resolve the haxy_session cookie's token to a user_id via the 177 // store. user_id_buf lives on the stack for the rest of handleRequest, 178 // which is plenty for renderIndexHtml to consume. 179 var user_id_buf: [evt.event_id_size]u8 = undefined; 180 const user_id: ?[]const u8 = blk: { 181 const token = getCookieValue(request, cookie_name) orelse break :blk null; 182 if (!session_store.lookup(token, &user_id_buf)) break :blk null; 183 break :blk user_id_buf[0..evt.event_id_size]; 184 }; 185 const login_failure: ?ui.Home.Auth.Login.Failure = 186 if (getCookieValue(request, login_failure_cookie)) |raw| 187 if (std.mem.eql(u8, raw, "unknown_user")) 188 .unknown_user 189 else if (std.mem.eql(u8, raw, "wrong_password")) 190 .wrong_password 191 else 192 null 193 else 194 null; 195 196 const html = renderIndexHtml(io, allocator, admin_repo_path, .{ 197 .user_id = user_id, 198 .login_failure = login_failure, 199 .current_page = current_page, 200 }) catch |err| switch (err) { 201 error.NotFound => { 202 try request.respond("not found", .{ 203 .status = .not_found, 204 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 205 }); 206 return; 207 }, 208 else => |e| return e, 209 }; 210 defer allocator.free(html); 211 212 // expire the flash cookie on the way out so a refresh doesn't keep 213 // showing the failure label. 214 var headers: [2]std.http.Header = undefined; 215 headers[0] = .{ .name = "content-type", .value = "text/html; charset=utf-8" }; 216 var headers_slice: []const std.http.Header = headers[0..1]; 217 if (login_failure != null) { 218 headers[1] = .{ .name = "set-cookie", .value = login_failure_cookie ++ "=; Path=/; Max-Age=0" }; 219 headers_slice = headers[0..2]; 220 } 221 try request.respond(html, .{ .extra_headers = headers_slice }); 222 return; 223 } 224 225 const embed = findEmbed(path) orelse { 226 try request.respond("not found", .{ 227 .status = .not_found, 228 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 229 }); 230 return; 231 }; 232 233 try request.respond(embed.body, .{ 234 .extra_headers = &.{.{ .name = "content-type", .value = embed.content_type }}, 235 }); 236 } 237 238 fn handleLogin( 239 io: std.Io, 240 request: *std.http.Server.Request, 241 allocator: std.mem.Allocator, 242 base: []const u8, 243 admin_repo_path: []const u8, 244 session_store: SessionStore, 245 ) !void { 246 var body_buf: [256]u8 = undefined; 247 const reader = request.readerExpectNone(&body_buf); 248 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 249 defer allocator.free(body); 250 251 const username = (try parseFormField(allocator, body, "username")) orelse try allocator.dupe(u8, ""); 252 defer allocator.free(username); 253 const password = (try parseFormField(allocator, body, "password")) orelse try allocator.dupe(u8, ""); 254 defer allocator.free(password); 255 256 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 257 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 258 defer repo.deinit(io, allocator); 259 260 var arena = std.heap.ArenaAllocator.init(allocator); 261 defer arena.deinit(); 262 263 const haxy_moment = try evt.currentMoment(evt.admin_repo_opts, &repo); 264 const result = try evt.User.verifyCredentials(evt.AdminDB, evt.admin_repo_opts.hash, haxy_moment, &arena, username, password); 265 266 // on success, return to the page the login came from (base, or "/" at the 267 // root); on failure, stay on its auth tab to surface the error. 268 const success_location: []const u8 = if (base.len == 0) "/" else base; 269 const failure_location = try std.fmt.allocPrint(arena.allocator(), "{s}/auth", .{base}); 270 271 switch (result) { 272 .success => |user_id| { 273 const token = try session_store.create(&user_id); 274 var cookie_buf: [256]u8 = undefined; 275 const cookie = try std.fmt.bufPrint(&cookie_buf, cookie_name ++ "={s}; Path=/; HttpOnly; SameSite=Strict", .{token}); 276 try request.respond("", .{ 277 .status = .see_other, 278 .extra_headers = &.{ 279 .{ .name = "location", .value = success_location }, 280 .{ .name = "set-cookie", .value = cookie }, 281 }, 282 }); 283 }, 284 .unknown_user => { 285 try request.respond("", .{ 286 .status = .see_other, 287 .extra_headers = &.{ 288 .{ .name = "location", .value = failure_location }, 289 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=unknown_user; Path=/; HttpOnly; SameSite=Strict" }, 290 }, 291 }); 292 }, 293 .wrong_password => { 294 try request.respond("", .{ 295 .status = .see_other, 296 .extra_headers = &.{ 297 .{ .name = "location", .value = failure_location }, 298 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=wrong_password; Path=/; HttpOnly; SameSite=Strict" }, 299 }, 300 }); 301 }, 302 } 303 } 304 305 fn handleLogout(request: *std.http.Server.Request, base: []const u8, session_store: SessionStore) !void { 306 // revoke the session server-side so the cookie is dead for anyone holding 307 // a copy, not just this browser. 308 if (getCookieValue(request, cookie_name)) |token| session_store.remove(token); 309 // return to the page the logout came from (base, or "/" at the root). 310 const location: []const u8 = if (base.len == 0) "/" else base; 311 // close the connection instead of keeping it alive: we don't read the 312 // request body, and respond()'s keep-alive path would otherwise try to 313 // discard it — which asserts on a bodyless POST that carries no 314 // content-length, and would block on one with no framing at all. a logout 315 // is just a redirect, so the browser reconnects for the follow-up GET. 316 try request.respond("", .{ 317 .status = .see_other, 318 .keep_alive = false, 319 .extra_headers = &.{ 320 .{ .name = "location", .value = location }, 321 .{ .name = "set-cookie", .value = cookie_name ++ "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0" }, 322 }, 323 }); 324 } 325 326 fn handleAnsi( 327 io: std.Io, 328 request: *std.http.Server.Request, 329 allocator: std.mem.Allocator, 330 base: []const u8, 331 admin_repo_path: []const u8, 332 session_store: SessionStore, 333 ) !void { 334 var user_id: [evt.event_id_size]u8 = undefined; 335 if (getCookieValue(request, cookie_name)) |token| { 336 if (session_store.lookup(token, &user_id)) { 337 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 338 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 339 defer repo.deinit(io, allocator); 340 341 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, &repo, &user_id); 342 } 343 } 344 345 // return to the settings tab the toggle came from so the change is visible. 346 const location = try std.fmt.allocPrint(allocator, "{s}/settings", .{base}); 347 defer allocator.free(location); 348 349 // like logout, this is a bodyless POST, so close the connection rather than 350 // letting the keep-alive path try to discard a body that isn't framed. 351 try request.respond("", .{ 352 .status = .see_other, 353 .keep_alive = false, 354 .extra_headers = &.{ 355 .{ .name = "location", .value = location }, 356 }, 357 }); 358 } 359 360 fn renderIndexHtml( 361 io: std.Io, 362 allocator: std.mem.Allocator, 363 admin_repo_path: []const u8, 364 session_data: ui.Session.Data, 365 ) ![]const u8 { 366 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 367 368 // open the admin repo to read live user/repo data. 369 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 370 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 371 defer repo.deinit(io, allocator); 372 var page_arena = std.heap.ArenaAllocator.init(allocator); 373 defer page_arena.deinit(); 374 375 var session = try ui.Session.init(&page_arena, &repo, session_data); 376 377 const snapshot: ui.Snapshot = .{ 378 .page = try ui.Page.init(session.arena, session.haxy_moment orelse unreachable, session.data.current_page), 379 .session = session.data, 380 }; 381 var root = try ui.initRoot(allocator, &snapshot.page, &session); 382 defer root.deinit(allocator); 383 384 const content = try generateHtml(allocator, &root); 385 defer allocator.free(content); 386 const overlay = try generateOverlay(allocator, &root); 387 defer allocator.free(overlay); 388 389 // serialize the snapshot so the wasm side can parse it back without 390 // making a second request. base64-encoded so the json can be embedded 391 // safely inside the host html. 392 var json: std.Io.Writer.Allocating = .init(allocator); 393 defer json.deinit(); 394 try std.json.Stringify.value(snapshot, .{}, &json.writer); 395 396 const b64 = std.base64.standard.Encoder; 397 const json_b64 = try allocator.alloc(u8, b64.calcSize(json.written().len)); 398 defer allocator.free(json_b64); 399 _ = b64.encode(json_b64, json.written()); 400 401 var out: std.ArrayList(u8) = .empty; 402 errdefer out.deinit(allocator); 403 { 404 var cursor: usize = 0; 405 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 406 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 407 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 408 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_b64 }, 409 }) |sub| { 410 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 411 try out.appendSlice(allocator, template[cursor..idx]); 412 try out.appendSlice(allocator, sub.replacement); 413 cursor = idx + sub.needle.len; 414 } 415 try out.appendSlice(allocator, template[cursor..]); 416 } 417 return try out.toOwnedSlice(allocator); 418 } 419 420 fn findEmbed(request_path: []const u8) ?Embed { 421 const path = if (std.mem.eql(u8, request_path, "/")) 422 "index.html" 423 else if (request_path.len > 1 and request_path[0] == '/') 424 request_path[1..] 425 else 426 return null; 427 428 for (embeds) |embed| { 429 if (std.mem.eql(u8, path, embed.path)) return embed; 430 } 431 return null; 432 } 433 434 fn logError(err: *std.Io.Writer, comptime fmt: []const u8, args: anytype) void { 435 err.print(fmt, args) catch return; 436 err.flush() catch {}; 437 } 438 439 // emits the TUI grid cells as static HTML 440 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 441 const grid = root.getGrid() orelse return error.MissingGrid; 442 const root_focus = root.getFocus(); 443 444 const Tag = union(enum) { 445 span, // clickable focusable cell 446 a: []const u8, // clickable focusable link 447 plain, // non-focusable, colored 448 449 const a_prefix = "a:"; 450 451 fn init(str: []const u8) @This() { 452 if (std.mem.startsWith(u8, str, a_prefix)) { 453 return .{ .a = str[a_prefix.len..] }; 454 } 455 return .span; 456 } 457 458 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 459 var id_buf: [32]u8 = undefined; 460 switch (self) { 461 .span => { 462 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 463 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 464 try out.appendSlice(alloc, "\""); 465 try out.appendSlice(alloc, style_attr); 466 try out.appendSlice(alloc, ">"); 467 }, 468 .a => |href| { 469 try out.appendSlice(alloc, "<a class=\"clickable\" data-focus-id=\""); 470 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 471 try out.appendSlice(alloc, "\" href=\""); 472 try appendEscapedHtml(alloc, out, href); 473 try out.appendSlice(alloc, "\""); 474 try out.appendSlice(alloc, style_attr); 475 try out.appendSlice(alloc, ">"); 476 }, 477 .plain => { 478 try out.appendSlice(alloc, "<span"); 479 try out.appendSlice(alloc, style_attr); 480 try out.appendSlice(alloc, ">"); 481 }, 482 } 483 } 484 485 fn closeTag(self: @This()) []const u8 { 486 return switch (self) { 487 .span, .plain => "</span>", 488 .a => "</a>", 489 }; 490 } 491 }; 492 493 var out: std.ArrayList(u8) = .empty; 494 errdefer out.deinit(allocator); 495 496 for (0..grid.size.height) |y| { 497 var cur_id: ?usize = null; 498 var cur_fg: ?Grid.Color = null; 499 var cur_bg: ?Grid.Color = null; 500 var open_tag: ?Tag = null; 501 var first = true; 502 for (0..grid.size.width) |x| { 503 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 504 const cell_id = cellFocusId(root_focus, x, y); 505 const fg = cell.style.fg; 506 const bg = cell.style.bg; 507 508 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 509 if (open_tag) |t| try out.appendSlice(allocator, t.closeTag()); 510 511 var new_tag: ?Tag = null; 512 if (cell_id) |id| { 513 if (root_focus.children.get(id)) |child| { 514 new_tag = switch (child.focus.kind) { 515 .custom => |custom| Tag.init(custom), 516 else => .span, 517 }; 518 } 519 } 520 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 521 522 if (new_tag) |t| { 523 var style_buf: [64]u8 = undefined; 524 try t.writeOpenTag(allocator, &out, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 525 } 526 527 open_tag = new_tag; 528 cur_id = cell_id; 529 cur_fg = fg; 530 cur_bg = bg; 531 first = false; 532 } 533 534 try appendEscapedHtml(allocator, &out, cell.rune orelse " "); 535 } 536 if (open_tag) |t| try out.appendSlice(allocator, t.closeTag()); 537 try out.append(allocator, '\n'); 538 } 539 540 return try out.toOwnedSlice(allocator); 541 } 542 543 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 544 // widget tree, each wrapping the text inputs and submit button inside it, 545 // positioned absolutely over the matching grid cells. 546 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 547 const root_focus = root.getFocus(); 548 549 var out: std.ArrayList(u8) = .empty; 550 errdefer out.deinit(allocator); 551 552 const form_prefix = "form:"; 553 554 // Focus.children is an AutoArrayHashMap that preserves insertion order, 555 // which matches the order widgets were added in code 556 var iter = root_focus.children.iterator(); 557 while (iter.next()) |entry| { 558 const child = entry.value_ptr.*; 559 const action_url = switch (child.focus.kind) { 560 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 561 custom[form_prefix.len..] 562 else 563 continue, 564 else => continue, 565 }; 566 567 try out.appendSlice(allocator, "<form action=\""); 568 try appendEscapedHtml(allocator, &out, action_url); 569 try out.appendSlice(allocator, "\" method=\"post\""); 570 // an empty action must not POST — block it and send the input to the TUI instead 571 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 572 try out.appendSlice(allocator, ">"); 573 574 // form.focus.children was populated by addChild, which flattens the 575 // whole subtree into one map — so descendants (inputs + the submit 576 // button) all appear here. positions on form.focus are relative to 577 // the form, so we look up absolute rects via root_focus for layout. 578 var inner_iter = child.focus.children.iterator(); 579 while (inner_iter.next()) |inner_entry| { 580 const inner_id = inner_entry.key_ptr.*; 581 const root_child = root_focus.children.get(inner_id) orelse continue; 582 const r = root_child.rect; 583 switch (root_child.focus.kind) { 584 .text_input, .text_input_password => { 585 const ti: *wgt.TextInput(ui.Widget) = @fieldParentPtr("focus", root_child.focus); 586 const inner_left = r.x + 1; 587 const inner_top = r.y + 1; 588 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 589 590 try out.appendSlice(allocator, "<input type=\""); 591 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 592 try out.appendSlice(allocator, "\" data-focus-id=\""); 593 var id_buf: [32]u8 = undefined; 594 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 595 if (ti.options.name.len > 0) { 596 try out.appendSlice(allocator, "\" name=\""); 597 try appendEscapedHtml(allocator, &out, ti.options.name); 598 } 599 // intentionally no `value` attribute: the browser tracks user input 600 // natively, and including the wasm-side value here would make the 601 // overlay HTML differ on every keystroke — that would trip the diff 602 // in _setOverlay and rebuild the <input>, eating the user's caret. 603 try out.appendSlice(allocator, "\" style=\"left:"); 604 var pos_buf: [64]u8 = undefined; 605 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 })); 606 try out.appendSlice(allocator, "\">"); 607 }, 608 .custom => |custom| { 609 if (std.mem.eql(u8, "submit", custom)) { 610 // inside the dashed border the TUI cells draw around the button. 611 const inner_left = r.x + 1; 612 const inner_top = r.y + 1; 613 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 614 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 615 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 616 var id_buf: [32]u8 = undefined; 617 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 618 try out.appendSlice(allocator, "\" style=\"left:"); 619 var pos_buf: [128]u8 = undefined; 620 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 })); 621 try out.appendSlice(allocator, "\"></button>"); 622 } 623 }, 624 else => {}, 625 } 626 } 627 628 try out.appendSlice(allocator, "</form>"); 629 } 630 631 return try out.toOwnedSlice(allocator); 632 } 633 634 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 635 if (a) |av| return if (b) |bv| av.eql(bv) else false; 636 return b == null; 637 } 638 639 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 640 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 641 // empty slice when neither is set. 642 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 643 if (fg == null and bg == null) return buf[0..0]; 644 const prefix = " style=\""; 645 @memcpy(buf[0..prefix.len], prefix); 646 var i: usize = prefix.len; 647 if (fg) |c| { 648 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]; 649 i += s.len; 650 } 651 if (bg) |c| { 652 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]; 653 i += s.len; 654 } 655 buf[i] = '"'; 656 i += 1; 657 return buf[0..i]; 658 } 659 660 fn cellFocusId(focus: *Focus, x: usize, y: usize) ?usize { 661 var iter = focus.children.iterator(); 662 while (iter.next()) |entry| { 663 const child = entry.value_ptr.*; 664 if (!child.focus.focusable) continue; 665 const r = child.rect; 666 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 667 return entry.key_ptr.*; 668 } 669 } 670 return null; 671 } 672 673 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 674 for (input) |ch| { 675 switch (ch) { 676 '&' => try out.appendSlice(allocator, "&amp;"), 677 '<' => try out.appendSlice(allocator, "&lt;"), 678 '>' => try out.appendSlice(allocator, "&gt;"), 679 '"' => try out.appendSlice(allocator, "&quot;"), 680 '\'' => try out.appendSlice(allocator, "&#39;"), 681 else => try out.append(allocator, ch), 682 } 683 } 684 } 685 686 // --- helpers -------------------------------------------------------------- 687 688 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 689 var iter = request.iterateHeaders(); 690 while (iter.next()) |header| { 691 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 692 var pairs = std.mem.splitScalar(u8, header.value, ';'); 693 while (pairs.next()) |pair| { 694 const trimmed = std.mem.trim(u8, pair, " \t"); 695 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 696 if (std.mem.eql(u8, trimmed[0..eq], name)) { 697 return trimmed[eq + 1 ..]; 698 } 699 } 700 } 701 return null; 702 } 703 704 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 705 var iter = std.mem.splitScalar(u8, body, '&'); 706 while (iter.next()) |pair| { 707 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 708 if (std.mem.eql(u8, pair[0..eq], key)) { 709 return try decodeFormValue(allocator, pair[eq + 1 ..]); 710 } 711 } 712 return null; 713 } 714 715 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 716 var out: std.ArrayList(u8) = .empty; 717 errdefer out.deinit(allocator); 718 var i: usize = 0; 719 while (i < encoded.len) : (i += 1) { 720 switch (encoded[i]) { 721 '+' => try out.append(allocator, ' '), 722 '%' => { 723 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 724 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 725 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 726 try out.append(allocator, hi * 16 + lo); 727 i += 2; 728 }, 729 else => try out.append(allocator, encoded[i]), 730 } 731 } 732 return try out.toOwnedSlice(allocator); 733 } 734 735 // disk-backed web session store. each login mints a random, opaque token 736 // (not the user's id) that is stored as a file named by the token hex, whose 737 // contents are the raw user_id bytes. authenticating a request is a lookup of 738 // the cookie's token; logout deletes the file, revoking the session. there is 739 // deliberately no expiry — a session lives until logout. 740 pub const SessionStore = struct { 741 io: std.Io, 742 dir: std.Io.Dir, 743 744 pub const token_hex_len = evt.event_id_size * 2; 745 746 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 747 try data_dir.createDirPath(io, "sessions"); 748 const dir = try data_dir.openDir(io, "sessions", .{}); 749 return .{ .io = io, .dir = dir }; 750 } 751 752 pub fn deinit(self: SessionStore) void { 753 self.dir.close(self.io); 754 } 755 756 // mint a new session for user_id, returning the token hex to set as the 757 // cookie value. 758 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 759 var token: [evt.event_id_size]u8 = undefined; 760 self.io.random(&token); 761 const token_hex = std.fmt.bytesToHex(token, .lower); 762 const file = try self.dir.createFile(self.io, &token_hex, .{}); 763 defer file.close(self.io); 764 try file.writeStreamingAll(self.io, user_id); 765 return token_hex; 766 } 767 768 // resolve a cookie's token to its user_id. returns false (logged out) for a 769 // missing, malformed, or unknown token. 770 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 771 if (!isToken(token_hex)) return false; 772 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 773 defer file.close(self.io); 774 var storage: [evt.event_id_size]u8 = undefined; 775 var file_reader = file.reader(self.io, &storage); 776 file_reader.interface.readSliceAll(out) catch return false; 777 return true; 778 } 779 780 // revoke a session. a no-op for a missing or malformed token. 781 pub fn remove(self: SessionStore, token_hex: []const u8) void { 782 if (!isToken(token_hex)) return; 783 self.dir.deleteFile(self.io, token_hex) catch {}; 784 } 785 786 // a token is exactly token_hex_len hex chars. validating before using the 787 // value as a path keeps attacker-supplied cookies from escaping the 788 // sessions dir (e.g. via "/" or ".." bytes). 789 fn isToken(token_hex: []const u8) bool { 790 if (token_hex.len != token_hex_len) return false; 791 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 792 return true; 793 } 794 }; 795