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