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