╭ 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. each web-native Scroll becomes its 449 // own absolutely-positioned, natively-scrollable <div> holding its full content, 450 // rendered recursively so nested scrolls work. 451 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 452 const grid = root.getGrid() orelse return error.MissingGrid; 453 454 var out: std.ArrayList(u8) = .empty; 455 errdefer out.deinit(allocator); 456 457 try renderPanel(allocator, &out, root.getFocus(), grid); 458 return try out.toOwnedSlice(allocator); 459 } 460 461 // render one panel — a focus subtree and its content grid — as HTML, recursing 462 // once per web-native Scroll inside it. the root panel is the whole page; each 463 // Scroll becomes a nested, natively-scrollable div holding its full content. 464 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 465 // then the child scroll divs over those holes. 466 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 467 // `direct` is this panel's scroll children, each drawn as an overlaid div. 468 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 469 // plus their descendants, which the focus tree flattens into this panel's 470 // children): the cell hit-test below skips them so this panel doesn't claim 471 // cells that are really rendered inside a child scroll's own panel. 472 // (scrolls aren't nested in practice, so every scroll child is direct here.) 473 var direct: std.ArrayList(usize) = .empty; 474 defer direct.deinit(allocator); 475 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 476 defer excluded.deinit(allocator); 477 { 478 var it = focus.children.iterator(); 479 while (it.next()) |e| { 480 if (e.value_ptr.focus.scroll == null) continue; 481 try direct.append(allocator, e.key_ptr.*); 482 try excluded.put(allocator, e.key_ptr.*, {}); 483 var mit = e.value_ptr.focus.children.iterator(); 484 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 485 } 486 } 487 488 // the HTML element a run of cells is wrapped in, chosen from the cell's 489 // focusable kind 490 const CellTag = union(enum) { 491 span, // clickable focusable cell 492 a: []const u8, // clickable focusable link 493 plain, // non-focusable, colored 494 495 const a_prefix = "a:"; 496 // an "in-page" anchor: rendered as a real <a href> so it works with js 497 // disabled, but crossPageLink ignores it, so with wasm the click just 498 // moves focus rather than navigating. 499 const inpage_prefix = "ai:"; 500 501 fn init(str: []const u8) @This() { 502 if (std.mem.startsWith(u8, str, inpage_prefix)) { 503 return .{ .a = str[inpage_prefix.len..] }; 504 } 505 if (std.mem.startsWith(u8, str, a_prefix)) { 506 return .{ .a = str[a_prefix.len..] }; 507 } 508 return .span; 509 } 510 511 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 512 var id_buf: [32]u8 = undefined; 513 switch (self) { 514 .span => { 515 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 516 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 517 try out.appendSlice(alloc, "\""); 518 try out.appendSlice(alloc, style_attr); 519 try out.appendSlice(alloc, ">"); 520 }, 521 .a => |href| { 522 // tabindex=-1 keeps these out of the browser's tab order 523 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 524 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 525 try out.appendSlice(alloc, "\" href=\""); 526 try appendEscapedHtml(alloc, out, href); 527 try out.appendSlice(alloc, "\""); 528 try out.appendSlice(alloc, style_attr); 529 try out.appendSlice(alloc, ">"); 530 }, 531 .plain => { 532 try out.appendSlice(alloc, "<span"); 533 try out.appendSlice(alloc, style_attr); 534 try out.appendSlice(alloc, ">"); 535 }, 536 } 537 } 538 539 fn closeTag(self: @This()) []const u8 { 540 return switch (self) { 541 .span, .plain => "</span>", 542 .a => "</a>", 543 }; 544 } 545 }; 546 547 // emit this panel's grid as rows of text, coalescing adjacent cells that 548 // share a focus id and colors into one tag (a clickable span, a link, or a 549 // plain colored span). cells under a child scroll keep only their background. 550 for (0..grid.size.height) |y| { 551 var cur_id: ?usize = null; 552 var cur_fg: ?Grid.Color = null; 553 var cur_bg: ?Grid.Color = null; 554 var open_tag: ?CellTag = null; 555 var first = true; 556 for (0..grid.size.width) |x| { 557 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 558 // a cell covered by a child scroll's viewport is drawn by that scroll's 559 // own div, so blank its glyph and make it non-clickable here — but keep 560 // its background, so the backdrop still shows through the scroll's 561 // transparent div instead of a bare hole. 562 const covered_by_scroll = blk: { 563 for (direct.items) |id| { 564 const r = (focus.children.get(id) orelse continue).rect; 565 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) break :blk true; 566 } 567 break :blk false; 568 }; 569 // the focusable cell at (x, y) among this panel's own focusables (skipping 570 // any that belong to a child scroll, whose cells are drawn in their own 571 // panel); none for a covered cell. 572 const cell_id = if (covered_by_scroll) null else blk: { 573 var iter = focus.children.iterator(); 574 while (iter.next()) |entry| { 575 const child = entry.value_ptr.*; 576 if (!child.focus.focusable) continue; 577 if (excluded.contains(entry.key_ptr.*)) continue; 578 const r = child.rect; 579 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 580 break :blk entry.key_ptr.*; 581 } 582 } 583 break :blk null; 584 }; 585 const fg = if (covered_by_scroll) null else cell.style.fg; 586 const bg = cell.style.bg; 587 588 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 589 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 590 591 var new_tag: ?CellTag = null; 592 if (cell_id) |id| { 593 if (focus.children.get(id)) |child| { 594 new_tag = switch (child.focus.kind) { 595 .custom => |custom| CellTag.init(custom), 596 else => .span, 597 }; 598 } 599 } 600 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 601 602 if (new_tag) |t| { 603 var style_buf: [64]u8 = undefined; 604 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 605 } 606 607 open_tag = new_tag; 608 cur_id = cell_id; 609 cur_fg = fg; 610 cur_bg = bg; 611 first = false; 612 } 613 614 try appendEscapedHtml(allocator, output, if (covered_by_scroll) " " else (cell.rune orelse " ")); 615 } 616 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 617 try output.append(allocator, '\n'); 618 } 619 620 // each child scroll becomes a natively-scrollable div positioned over its 621 // viewport, holding its full content rendered recursively. 622 for (direct.items) |id| { 623 const child = focus.children.get(id) orelse continue; 624 const info = child.focus.scroll orelse continue; 625 const r = child.rect; 626 // overflow only on the axes the widget scrolls; `auto` shows a bar only 627 // when that axis actually overflows. the other axis is clipped (hidden), 628 // matching how the terminal Scroll handles its non-scrolling axis. 629 const overflow = switch (info.direction) { 630 .vert => "overflow-x:hidden;overflow-y:auto", 631 .horiz => "overflow-x:auto;overflow-y:hidden", 632 .both => "overflow:auto", 633 }; 634 // the id carries a content version so JS preserves the native scroll 635 // position across re-renders of the same content but resets it (to the 636 // top) when the content is replaced — e.g. selecting a different commit. 637 var buf: [160]u8 = undefined; 638 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, "<div class=\"scroll\" data-scroll-id=\"{d}-{d}\" style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em;{s}\">", .{ id, child.focus.version, r.x, r.y, r.size.width, r.size.height, overflow })); 639 try renderPanel(allocator, output, child.focus, info.content); 640 try output.appendSlice(allocator, "</div>"); 641 } 642 } 643 644 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 645 // widget tree, each wrapping the text inputs and submit button inside it, 646 // positioned absolutely over the matching grid cells. 647 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 648 const root_focus = root.getFocus(); 649 650 var out: std.ArrayList(u8) = .empty; 651 errdefer out.deinit(allocator); 652 653 const form_prefix = "form:"; 654 655 // Focus.children is an AutoArrayHashMap that preserves insertion order, 656 // which matches the order widgets were added in code 657 var iter = root_focus.children.iterator(); 658 while (iter.next()) |entry| { 659 const child = entry.value_ptr.*; 660 const action_url = switch (child.focus.kind) { 661 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 662 custom[form_prefix.len..] 663 else 664 continue, 665 else => continue, 666 }; 667 668 try out.appendSlice(allocator, "<form action=\""); 669 try appendEscapedHtml(allocator, &out, action_url); 670 try out.appendSlice(allocator, "\" method=\"post\""); 671 // an empty action must not POST — block it and send the input to the TUI instead 672 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 673 try out.appendSlice(allocator, ">"); 674 675 // form.focus.children was populated by addChild, which flattens the 676 // whole subtree into one map — so descendants (inputs + the submit 677 // button) all appear here. positions on form.focus are relative to 678 // the form, so we look up absolute rects via root_focus for layout. 679 var inner_iter = child.focus.children.iterator(); 680 while (inner_iter.next()) |inner_entry| { 681 const inner_id = inner_entry.key_ptr.*; 682 const root_child = root_focus.children.get(inner_id) orelse continue; 683 const r = root_child.rect; 684 switch (root_child.focus.kind) { 685 .text_input, .text_input_password => { 686 const ti = session.text_inputs.get(inner_id) orelse continue; 687 const inner_left = r.x + 1; 688 const inner_top = r.y + 1; 689 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 690 691 try out.appendSlice(allocator, "<input type=\""); 692 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 693 try out.appendSlice(allocator, "\" data-focus-id=\""); 694 var id_buf: [32]u8 = undefined; 695 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 696 if (ti.options.name.len > 0) { 697 try out.appendSlice(allocator, "\" name=\""); 698 try appendEscapedHtml(allocator, &out, ti.options.name); 699 } 700 // intentionally no `value` attribute: the browser tracks user input 701 // natively, and including the wasm-side value here would make the 702 // overlay HTML differ on every keystroke — that would trip the diff 703 // in _setOverlay and rebuild the <input>, eating the user's caret. 704 try out.appendSlice(allocator, "\" style=\"left:"); 705 var pos_buf: [64]u8 = undefined; 706 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 })); 707 try out.appendSlice(allocator, "\">"); 708 }, 709 .custom => |custom| { 710 if (std.mem.eql(u8, "submit", custom)) { 711 // inside the dashed border the TUI cells draw around the button. 712 const inner_left = r.x + 1; 713 const inner_top = r.y + 1; 714 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 715 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 716 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 717 var id_buf: [32]u8 = undefined; 718 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 719 try out.appendSlice(allocator, "\" style=\"left:"); 720 var pos_buf: [128]u8 = undefined; 721 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 })); 722 try out.appendSlice(allocator, "\"></button>"); 723 } 724 }, 725 else => {}, 726 } 727 } 728 729 try out.appendSlice(allocator, "</form>"); 730 } 731 732 return try out.toOwnedSlice(allocator); 733 } 734 735 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 736 if (a) |av| return if (b) |bv| av.eql(bv) else false; 737 return b == null; 738 } 739 740 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 741 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 742 // empty slice when neither is set. 743 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 744 if (fg == null and bg == null) return buf[0..0]; 745 const prefix = " style=\""; 746 @memcpy(buf[0..prefix.len], prefix); 747 var i: usize = prefix.len; 748 if (fg) |c| { 749 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]; 750 i += s.len; 751 } 752 if (bg) |c| { 753 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]; 754 i += s.len; 755 } 756 buf[i] = '"'; 757 i += 1; 758 return buf[0..i]; 759 } 760 761 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 762 for (input) |ch| { 763 switch (ch) { 764 '&' => try out.appendSlice(allocator, "&amp;"), 765 '<' => try out.appendSlice(allocator, "&lt;"), 766 '>' => try out.appendSlice(allocator, "&gt;"), 767 '"' => try out.appendSlice(allocator, "&quot;"), 768 '\'' => try out.appendSlice(allocator, "&#39;"), 769 else => try out.append(allocator, ch), 770 } 771 } 772 } 773 774 // --- helpers -------------------------------------------------------------- 775 776 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 777 var iter = request.iterateHeaders(); 778 while (iter.next()) |header| { 779 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 780 var pairs = std.mem.splitScalar(u8, header.value, ';'); 781 while (pairs.next()) |pair| { 782 const trimmed = std.mem.trim(u8, pair, " \t"); 783 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 784 if (std.mem.eql(u8, trimmed[0..eq], name)) { 785 return trimmed[eq + 1 ..]; 786 } 787 } 788 } 789 return null; 790 } 791 792 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 793 var iter = std.mem.splitScalar(u8, body, '&'); 794 while (iter.next()) |pair| { 795 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 796 if (std.mem.eql(u8, pair[0..eq], key)) { 797 return try decodeFormValue(allocator, pair[eq + 1 ..]); 798 } 799 } 800 return null; 801 } 802 803 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 804 var out: std.ArrayList(u8) = .empty; 805 errdefer out.deinit(allocator); 806 var i: usize = 0; 807 while (i < encoded.len) : (i += 1) { 808 switch (encoded[i]) { 809 '+' => try out.append(allocator, ' '), 810 '%' => { 811 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 812 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 813 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 814 try out.append(allocator, hi * 16 + lo); 815 i += 2; 816 }, 817 else => try out.append(allocator, encoded[i]), 818 } 819 } 820 return try out.toOwnedSlice(allocator); 821 } 822 823 // disk-backed web session store. each login mints a random, opaque token 824 // (not the user's id) that is stored as a file named by the token hex, whose 825 // contents are the raw user_id bytes. authenticating a request is a lookup of 826 // the cookie's token; logout deletes the file, revoking the session. there is 827 // deliberately no expiry — a session lives until logout. 828 pub const SessionStore = struct { 829 io: std.Io, 830 dir: std.Io.Dir, 831 832 pub const token_hex_len = evt.event_id_size * 2; 833 834 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 835 try data_dir.createDirPath(io, "sessions"); 836 const dir = try data_dir.openDir(io, "sessions", .{}); 837 return .{ .io = io, .dir = dir }; 838 } 839 840 pub fn deinit(self: SessionStore) void { 841 self.dir.close(self.io); 842 } 843 844 // mint a new session for user_id, returning the token hex to set as the 845 // cookie value. 846 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 847 var token: [evt.event_id_size]u8 = undefined; 848 self.io.random(&token); 849 const token_hex = std.fmt.bytesToHex(token, .lower); 850 const file = try self.dir.createFile(self.io, &token_hex, .{}); 851 defer file.close(self.io); 852 try file.writeStreamingAll(self.io, user_id); 853 return token_hex; 854 } 855 856 // resolve a cookie's token to its user_id. returns false (logged out) for a 857 // missing, malformed, or unknown token. 858 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 859 if (!isToken(token_hex)) return false; 860 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 861 defer file.close(self.io); 862 var storage: [evt.event_id_size]u8 = undefined; 863 var file_reader = file.reader(self.io, &storage); 864 file_reader.interface.readSliceAll(out) catch return false; 865 return true; 866 } 867 868 // revoke a session. a no-op for a missing or malformed token. 869 pub fn remove(self: SessionStore, token_hex: []const u8) void { 870 if (!isToken(token_hex)) return; 871 self.dir.deleteFile(self.io, token_hex) catch {}; 872 } 873 874 // a token is exactly token_hex_len hex chars. validating before using the 875 // value as a path keeps attacker-supplied cookies from escaping the 876 // sessions dir (e.g. via "/" or ".." bytes). 877 fn isToken(token_hex: []const u8) bool { 878 if (token_hex.len != token_hex_len) return false; 879 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 880 return true; 881 } 882 }; 883