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