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