╭ 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, if (uri.query) |comp| comp.percent_encoded else null)) |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 // give the page builders filesystem access to the on-disk repos (a sibling 382 // "repos" dir next to the admin repo) so the Repo page can read its files. 383 session.io = io; 384 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(admin_repo_path) orelse ".", "repos" }); 385 386 const snapshot: ui.Snapshot = .{ 387 .page = try ui.Page.init(session.page_arena, &session, session.data.current_page), 388 .session = session.data, 389 }; 390 var root = try ui.initRoot(allocator, &snapshot.page, &session); 391 defer root.deinit(allocator); 392 393 const content = try generateHtml(allocator, &root); 394 defer allocator.free(content); 395 const overlay = try generateOverlay(allocator, &root, &session); 396 defer allocator.free(overlay); 397 398 // serialize the snapshot so the wasm side can parse it back without 399 // making a second request. base64-encoded so the json can be embedded 400 // safely inside the host html. 401 var json: std.Io.Writer.Allocating = .init(allocator); 402 defer json.deinit(); 403 try std.json.Stringify.value(snapshot, .{}, &json.writer); 404 405 const b64 = std.base64.standard.Encoder; 406 const json_b64 = try allocator.alloc(u8, b64.calcSize(json.written().len)); 407 defer allocator.free(json_b64); 408 _ = b64.encode(json_b64, json.written()); 409 410 var out: std.ArrayList(u8) = .empty; 411 errdefer out.deinit(allocator); 412 { 413 var cursor: usize = 0; 414 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 415 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 416 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 417 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_b64 }, 418 }) |sub| { 419 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 420 try out.appendSlice(allocator, template[cursor..idx]); 421 try out.appendSlice(allocator, sub.replacement); 422 cursor = idx + sub.needle.len; 423 } 424 try out.appendSlice(allocator, template[cursor..]); 425 } 426 return try out.toOwnedSlice(allocator); 427 } 428 429 fn findEmbed(request_path: []const u8) ?Embed { 430 const path = if (std.mem.eql(u8, request_path, "/")) 431 "index.html" 432 else if (request_path.len > 1 and request_path[0] == '/') 433 request_path[1..] 434 else 435 return null; 436 437 for (embeds) |embed| { 438 if (std.mem.eql(u8, path, embed.path)) return embed; 439 } 440 return null; 441 } 442 443 fn logError(err: *std.Io.Writer, comptime fmt: []const u8, args: anytype) void { 444 err.print(fmt, args) catch return; 445 err.flush() catch {}; 446 } 447 448 // emits the TUI grid cells as static HTML 449 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 450 const grid = root.getGrid() orelse return error.MissingGrid; 451 const root_focus = root.getFocus(); 452 453 const Tag = union(enum) { 454 span, // clickable focusable cell 455 a: []const u8, // clickable focusable link 456 plain, // non-focusable, colored 457 458 const a_prefix = "a:"; 459 460 fn init(str: []const u8) @This() { 461 if (std.mem.startsWith(u8, str, a_prefix)) { 462 return .{ .a = str[a_prefix.len..] }; 463 } 464 return .span; 465 } 466 467 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 468 var id_buf: [32]u8 = undefined; 469 switch (self) { 470 .span => { 471 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 472 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 473 try out.appendSlice(alloc, "\""); 474 try out.appendSlice(alloc, style_attr); 475 try out.appendSlice(alloc, ">"); 476 }, 477 .a => |href| { 478 // tabindex=-1 keeps these out of the browser's tab order 479 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 480 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 481 try out.appendSlice(alloc, "\" href=\""); 482 try appendEscapedHtml(alloc, out, href); 483 try out.appendSlice(alloc, "\""); 484 try out.appendSlice(alloc, style_attr); 485 try out.appendSlice(alloc, ">"); 486 }, 487 .plain => { 488 try out.appendSlice(alloc, "<span"); 489 try out.appendSlice(alloc, style_attr); 490 try out.appendSlice(alloc, ">"); 491 }, 492 } 493 } 494 495 fn closeTag(self: @This()) []const u8 { 496 return switch (self) { 497 .span, .plain => "</span>", 498 .a => "</a>", 499 }; 500 } 501 }; 502 503 var out: std.ArrayList(u8) = .empty; 504 errdefer out.deinit(allocator); 505 506 for (0..grid.size.height) |y| { 507 var cur_id: ?usize = null; 508 var cur_fg: ?Grid.Color = null; 509 var cur_bg: ?Grid.Color = null; 510 var open_tag: ?Tag = null; 511 var first = true; 512 for (0..grid.size.width) |x| { 513 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 514 const cell_id = cellFocusId(root_focus, x, y); 515 const fg = cell.style.fg; 516 const bg = cell.style.bg; 517 518 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 519 if (open_tag) |t| try out.appendSlice(allocator, t.closeTag()); 520 521 var new_tag: ?Tag = null; 522 if (cell_id) |id| { 523 if (root_focus.children.get(id)) |child| { 524 new_tag = switch (child.focus.kind) { 525 .custom => |custom| Tag.init(custom), 526 else => .span, 527 }; 528 } 529 } 530 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 531 532 if (new_tag) |t| { 533 var style_buf: [64]u8 = undefined; 534 try t.writeOpenTag(allocator, &out, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 535 } 536 537 open_tag = new_tag; 538 cur_id = cell_id; 539 cur_fg = fg; 540 cur_bg = bg; 541 first = false; 542 } 543 544 try appendEscapedHtml(allocator, &out, cell.rune orelse " "); 545 } 546 if (open_tag) |t| try out.appendSlice(allocator, t.closeTag()); 547 try out.append(allocator, '\n'); 548 } 549 550 return try out.toOwnedSlice(allocator); 551 } 552 553 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 554 // widget tree, each wrapping the text inputs and submit button inside it, 555 // positioned absolutely over the matching grid cells. 556 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 557 const root_focus = root.getFocus(); 558 559 var out: std.ArrayList(u8) = .empty; 560 errdefer out.deinit(allocator); 561 562 const form_prefix = "form:"; 563 564 // Focus.children is an AutoArrayHashMap that preserves insertion order, 565 // which matches the order widgets were added in code 566 var iter = root_focus.children.iterator(); 567 while (iter.next()) |entry| { 568 const child = entry.value_ptr.*; 569 const action_url = switch (child.focus.kind) { 570 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 571 custom[form_prefix.len..] 572 else 573 continue, 574 else => continue, 575 }; 576 577 try out.appendSlice(allocator, "<form action=\""); 578 try appendEscapedHtml(allocator, &out, action_url); 579 try out.appendSlice(allocator, "\" method=\"post\""); 580 // an empty action must not POST — block it and send the input to the TUI instead 581 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 582 try out.appendSlice(allocator, ">"); 583 584 // form.focus.children was populated by addChild, which flattens the 585 // whole subtree into one map — so descendants (inputs + the submit 586 // button) all appear here. positions on form.focus are relative to 587 // the form, so we look up absolute rects via root_focus for layout. 588 var inner_iter = child.focus.children.iterator(); 589 while (inner_iter.next()) |inner_entry| { 590 const inner_id = inner_entry.key_ptr.*; 591 const root_child = root_focus.children.get(inner_id) orelse continue; 592 const r = root_child.rect; 593 switch (root_child.focus.kind) { 594 .text_input, .text_input_password => { 595 const ti = session.text_inputs.get(inner_id) orelse continue; 596 const inner_left = r.x + 1; 597 const inner_top = r.y + 1; 598 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 599 600 try out.appendSlice(allocator, "<input type=\""); 601 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 602 try out.appendSlice(allocator, "\" data-focus-id=\""); 603 var id_buf: [32]u8 = undefined; 604 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 605 if (ti.options.name.len > 0) { 606 try out.appendSlice(allocator, "\" name=\""); 607 try appendEscapedHtml(allocator, &out, ti.options.name); 608 } 609 // intentionally no `value` attribute: the browser tracks user input 610 // natively, and including the wasm-side value here would make the 611 // overlay HTML differ on every keystroke — that would trip the diff 612 // in _setOverlay and rebuild the <input>, eating the user's caret. 613 try out.appendSlice(allocator, "\" style=\"left:"); 614 var pos_buf: [64]u8 = undefined; 615 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 })); 616 try out.appendSlice(allocator, "\">"); 617 }, 618 .custom => |custom| { 619 if (std.mem.eql(u8, "submit", custom)) { 620 // inside the dashed border the TUI cells draw around the button. 621 const inner_left = r.x + 1; 622 const inner_top = r.y + 1; 623 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 624 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 625 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 626 var id_buf: [32]u8 = undefined; 627 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 628 try out.appendSlice(allocator, "\" style=\"left:"); 629 var pos_buf: [128]u8 = undefined; 630 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 })); 631 try out.appendSlice(allocator, "\"></button>"); 632 } 633 }, 634 else => {}, 635 } 636 } 637 638 try out.appendSlice(allocator, "</form>"); 639 } 640 641 return try out.toOwnedSlice(allocator); 642 } 643 644 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 645 if (a) |av| return if (b) |bv| av.eql(bv) else false; 646 return b == null; 647 } 648 649 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 650 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 651 // empty slice when neither is set. 652 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 653 if (fg == null and bg == null) return buf[0..0]; 654 const prefix = " style=\""; 655 @memcpy(buf[0..prefix.len], prefix); 656 var i: usize = prefix.len; 657 if (fg) |c| { 658 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]; 659 i += s.len; 660 } 661 if (bg) |c| { 662 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]; 663 i += s.len; 664 } 665 buf[i] = '"'; 666 i += 1; 667 return buf[0..i]; 668 } 669 670 fn cellFocusId(focus: *Focus, x: usize, y: usize) ?usize { 671 var iter = focus.children.iterator(); 672 while (iter.next()) |entry| { 673 const child = entry.value_ptr.*; 674 if (!child.focus.focusable) continue; 675 const r = child.rect; 676 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 677 return entry.key_ptr.*; 678 } 679 } 680 return null; 681 } 682 683 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 684 for (input) |ch| { 685 switch (ch) { 686 '&' => try out.appendSlice(allocator, "&amp;"), 687 '<' => try out.appendSlice(allocator, "&lt;"), 688 '>' => try out.appendSlice(allocator, "&gt;"), 689 '"' => try out.appendSlice(allocator, "&quot;"), 690 '\'' => try out.appendSlice(allocator, "&#39;"), 691 else => try out.append(allocator, ch), 692 } 693 } 694 } 695 696 // --- helpers -------------------------------------------------------------- 697 698 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 699 var iter = request.iterateHeaders(); 700 while (iter.next()) |header| { 701 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 702 var pairs = std.mem.splitScalar(u8, header.value, ';'); 703 while (pairs.next()) |pair| { 704 const trimmed = std.mem.trim(u8, pair, " \t"); 705 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 706 if (std.mem.eql(u8, trimmed[0..eq], name)) { 707 return trimmed[eq + 1 ..]; 708 } 709 } 710 } 711 return null; 712 } 713 714 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 715 var iter = std.mem.splitScalar(u8, body, '&'); 716 while (iter.next()) |pair| { 717 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 718 if (std.mem.eql(u8, pair[0..eq], key)) { 719 return try decodeFormValue(allocator, pair[eq + 1 ..]); 720 } 721 } 722 return null; 723 } 724 725 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 726 var out: std.ArrayList(u8) = .empty; 727 errdefer out.deinit(allocator); 728 var i: usize = 0; 729 while (i < encoded.len) : (i += 1) { 730 switch (encoded[i]) { 731 '+' => try out.append(allocator, ' '), 732 '%' => { 733 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 734 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 735 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 736 try out.append(allocator, hi * 16 + lo); 737 i += 2; 738 }, 739 else => try out.append(allocator, encoded[i]), 740 } 741 } 742 return try out.toOwnedSlice(allocator); 743 } 744 745 // disk-backed web session store. each login mints a random, opaque token 746 // (not the user's id) that is stored as a file named by the token hex, whose 747 // contents are the raw user_id bytes. authenticating a request is a lookup of 748 // the cookie's token; logout deletes the file, revoking the session. there is 749 // deliberately no expiry — a session lives until logout. 750 pub const SessionStore = struct { 751 io: std.Io, 752 dir: std.Io.Dir, 753 754 pub const token_hex_len = evt.event_id_size * 2; 755 756 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 757 try data_dir.createDirPath(io, "sessions"); 758 const dir = try data_dir.openDir(io, "sessions", .{}); 759 return .{ .io = io, .dir = dir }; 760 } 761 762 pub fn deinit(self: SessionStore) void { 763 self.dir.close(self.io); 764 } 765 766 // mint a new session for user_id, returning the token hex to set as the 767 // cookie value. 768 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 769 var token: [evt.event_id_size]u8 = undefined; 770 self.io.random(&token); 771 const token_hex = std.fmt.bytesToHex(token, .lower); 772 const file = try self.dir.createFile(self.io, &token_hex, .{}); 773 defer file.close(self.io); 774 try file.writeStreamingAll(self.io, user_id); 775 return token_hex; 776 } 777 778 // resolve a cookie's token to its user_id. returns false (logged out) for a 779 // missing, malformed, or unknown token. 780 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 781 if (!isToken(token_hex)) return false; 782 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 783 defer file.close(self.io); 784 var storage: [evt.event_id_size]u8 = undefined; 785 var file_reader = file.reader(self.io, &storage); 786 file_reader.interface.readSliceAll(out) catch return false; 787 return true; 788 } 789 790 // revoke a session. a no-op for a missing or malformed token. 791 pub fn remove(self: SessionStore, token_hex: []const u8) void { 792 if (!isToken(token_hex)) return; 793 self.dir.deleteFile(self.io, token_hex) catch {}; 794 } 795 796 // a token is exactly token_hex_len hex chars. validating before using the 797 // value as a path keeps attacker-supplied cookies from escaping the 798 // sessions dir (e.g. via "/" or ".." bytes). 799 fn isToken(token_hex: []const u8) bool { 800 if (token_hex.len != token_hex_len) return false; 801 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 802 return true; 803 } 804 }; 805