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