╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
1 const std = @import("std"); 2 const xit = @import("xit"); 3 const rp = xit.repo; 4 const hash = xit.hash; 5 const evt = @import("./event.zig"); 6 const ui = @import("./ui.zig"); 7 const xitui = xit.xitui; 8 const wgt = xitui.widget; 9 const Focus = xitui.focus.Focus; 10 const Grid = xitui.grid.Grid; 11 12 const cookie_name = "haxy_session"; 13 // flash cookie for surfacing the outcome of the most recent /login POST. 14 // set on the failure redirect, read and immediately expired on the next 15 // GET / so refreshing the page doesn't keep showing the error. 16 const login_failure_cookie = "haxy_login_failure"; 17 18 const Embed = struct { 19 path: []const u8, 20 content_type: []const u8, 21 body: []const u8, 22 }; 23 24 const embeds = [_]Embed{ 25 .{ .path = "index.html", .content_type = "text/html; charset=utf-8", .body = @embedFile("embed/index.html") }, 26 .{ .path = "script.js", .content_type = "text/javascript; charset=utf-8", .body = @embedFile("embed/script.js") }, 27 .{ .path = "term.ttf", .content_type = "font/ttf", .body = @embedFile("embed/term.ttf") }, 28 .{ .path = "haxy.wasm", .content_type = "application/wasm", .body = @embedFile("embed/haxy.wasm") }, 29 }; 30 31 pub fn run( 32 io: std.Io, 33 allocator: std.mem.Allocator, 34 net_server: *std.Io.net.Server, 35 tasks: *std.Io.Group, 36 admin_repo_path: []const u8, 37 session_store: SessionStore, 38 err: *std.Io.Writer, 39 ) void { 40 const Listener = struct { 41 io: std.Io, 42 allocator: std.mem.Allocator, 43 net_server: *std.Io.net.Server, 44 tasks: *std.Io.Group, 45 admin_repo_path: []const u8, 46 session_store: SessionStore, 47 err: *std.Io.Writer, 48 49 fn run(ctx: @This()) void { 50 while (true) { 51 const stream = ctx.net_server.accept(ctx.io) catch |accept_err| { 52 if (accept_err == error.Canceled) return; 53 logError(ctx.err, "web ui accept failed: {s}\n", .{@errorName(accept_err)}); 54 continue; 55 }; 56 57 const Connection = struct { 58 io: std.Io, 59 allocator: std.mem.Allocator, 60 stream: std.Io.net.Stream, 61 admin_repo_path: []const u8, 62 session_store: SessionStore, 63 err: *std.Io.Writer, 64 65 fn run(conn: @This()) void { 66 defer conn.stream.close(conn.io); 67 handleConnection(conn.io, conn.allocator, conn.stream, conn.admin_repo_path, conn.session_store, conn.err) catch |request_err| { 68 logError(conn.err, "web ui request failed: {s}\n", .{@errorName(request_err)}); 69 }; 70 } 71 }; 72 73 ctx.tasks.async(ctx.io, Connection.run, .{Connection{ 74 .io = ctx.io, 75 .allocator = ctx.allocator, 76 .stream = stream, 77 .admin_repo_path = ctx.admin_repo_path, 78 .session_store = ctx.session_store, 79 .err = ctx.err, 80 }}); 81 } 82 } 83 }; 84 85 tasks.async(io, Listener.run, .{Listener{ 86 .io = io, 87 .allocator = allocator, 88 .net_server = net_server, 89 .tasks = tasks, 90 .admin_repo_path = admin_repo_path, 91 .session_store = session_store, 92 .err = err, 93 }}); 94 } 95 96 fn handleConnection( 97 io: std.Io, 98 allocator: std.mem.Allocator, 99 stream: std.Io.net.Stream, 100 admin_repo_path: []const u8, 101 session_store: SessionStore, 102 err: *std.Io.Writer, 103 ) !void { 104 var send_buffer = [_]u8{0} ** 4096; 105 var recv_buffer = [_]u8{0} ** 4096; 106 var conn_br = stream.reader(io, &recv_buffer); 107 var conn_bw = stream.writer(io, &send_buffer); 108 var http_server = std.http.Server.init(&conn_br.interface, &conn_bw.interface); 109 110 // serve multiple requests on a single connection so HTTP/1.1 keep-alive 111 // works — important for browser-native form POST: after the 303 the 112 // browser issues GET / on the same socket, and forcibly closing here 113 // would race the follow-up request into a "site can't be reached". 114 while (http_server.reader.state == .ready) { 115 var request = http_server.receiveHead() catch |receive_err| switch (receive_err) { 116 error.HttpConnectionClosing => break, 117 error.ReadFailed => break, 118 else => |e| return e, 119 }; 120 121 handleRequest(io, &request, allocator, admin_repo_path, session_store) catch |request_err| { 122 try err.print("web ui request failed: {s}\n", .{@errorName(request_err)}); 123 try err.flush(); 124 // best-effort 500. if handleRequest already started writing a 125 // response before throwing, this respond may fail too, but at 126 // that point the connection is unrecoverable anyway. 127 request.respond(@errorName(request_err), .{ 128 .status = .internal_server_error, 129 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 130 }) catch {}; 131 }; 132 } 133 } 134 135 fn handleRequest( 136 io: std.Io, 137 request: *std.http.Server.Request, 138 allocator: std.mem.Allocator, 139 admin_repo_path: []const u8, 140 session_store: SessionStore, 141 ) !void { 142 const method = request.head.method; 143 const uri = try std.Uri.parseAfterScheme("", request.head.target); 144 const path = uri.path.percent_encoded; 145 146 if (method == .POST and std.mem.eql(u8, path, "/login")) { 147 return handleLogin(io, request, allocator, admin_repo_path, session_store); 148 } 149 if (method == .POST and std.mem.eql(u8, path, "/logout")) { 150 return handleLogout(request, session_store); 151 } 152 if (method == .POST and std.mem.eql(u8, path, "/ansi")) { 153 return handleAnsi(request); 154 } 155 156 const get_or_head = method == .GET or method == .HEAD; 157 if (!get_or_head) { 158 try request.respond("method not allowed", .{ 159 .status = .method_not_allowed, 160 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 161 }); 162 return; 163 } 164 165 if (std.mem.eql(u8, path, "/favicon.ico")) { 166 try request.respond("", .{ 167 .status = .no_content, 168 .extra_headers = &.{.{ .name = "content-type", .value = "image/x-icon" }}, 169 }); 170 return; 171 } 172 173 if (ui.RoutablePage.fromUrl(path)) |current_page| { 174 // resolve the haxy_session cookie's token to a user_id via the 175 // store. user_id_buf lives on the stack for the rest of handleRequest, 176 // which is plenty for renderIndexHtml to consume. 177 var user_id_buf: [evt.event_id_size]u8 = undefined; 178 const user_id: ?[]const u8 = blk: { 179 const token = getCookieValue(request, cookie_name) orelse break :blk null; 180 if (!session_store.lookup(token, &user_id_buf)) break :blk null; 181 break :blk user_id_buf[0..evt.event_id_size]; 182 }; 183 const login_failure: ?ui.Home.Auth.Login.Failure = 184 if (getCookieValue(request, login_failure_cookie)) |raw| 185 if (std.mem.eql(u8, raw, "unknown_user")) 186 .unknown_user 187 else if (std.mem.eql(u8, raw, "wrong_password")) 188 .wrong_password 189 else 190 null 191 else 192 null; 193 const html = try renderIndexHtml(io, allocator, admin_repo_path, .{ 194 .user_id = user_id, 195 .login_failure = login_failure, 196 .current_page = current_page, 197 // enable_ansi is intentionally left at its default 198 }); 199 defer allocator.free(html); 200 // expire the flash cookie on the way out so a refresh doesn't keep 201 // showing the failure label. 202 var headers: [2]std.http.Header = undefined; 203 headers[0] = .{ .name = "content-type", .value = "text/html; charset=utf-8" }; 204 var headers_slice: []const std.http.Header = headers[0..1]; 205 if (login_failure != null) { 206 headers[1] = .{ .name = "set-cookie", .value = login_failure_cookie ++ "=; Path=/; Max-Age=0" }; 207 headers_slice = headers[0..2]; 208 } 209 try request.respond(html, .{ .extra_headers = headers_slice }); 210 return; 211 } 212 213 const embed = findEmbed(path) orelse { 214 try request.respond("not found", .{ 215 .status = .not_found, 216 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 217 }); 218 return; 219 }; 220 221 try request.respond(embed.body, .{ 222 .extra_headers = &.{.{ .name = "content-type", .value = embed.content_type }}, 223 }); 224 } 225 226 fn handleLogin( 227 io: std.Io, 228 request: *std.http.Server.Request, 229 allocator: std.mem.Allocator, 230 admin_repo_path: []const u8, 231 session_store: SessionStore, 232 ) !void { 233 var body_buf: [256]u8 = undefined; 234 const reader = request.readerExpectNone(&body_buf); 235 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 236 defer allocator.free(body); 237 238 const username = (try parseFormField(allocator, body, "username")) orelse try allocator.dupe(u8, ""); 239 defer allocator.free(username); 240 const password = (try parseFormField(allocator, body, "password")) orelse try allocator.dupe(u8, ""); 241 defer allocator.free(password); 242 243 const repo_opts: rp.RepoOpts(.xit) = .{}; 244 const Repo = rp.Repo(.xit, repo_opts); 245 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 246 defer repo.deinit(io, allocator); 247 248 var arena = std.heap.ArenaAllocator.init(allocator); 249 defer arena.deinit(); 250 251 const haxy_moment = try openHaxyMoment(repo_opts, &repo); 252 const result = try evt.User.verifyCredentials(Repo.DB, repo_opts.hash, haxy_moment, &arena, username, password); 253 254 switch (result) { 255 .success => |user_id| { 256 const token = try session_store.create(&user_id); 257 var cookie_buf: [256]u8 = undefined; 258 const cookie = try std.fmt.bufPrint(&cookie_buf, cookie_name ++ "={s}; Path=/; HttpOnly; SameSite=Strict", .{token}); 259 try request.respond("", .{ 260 .status = .see_other, 261 .extra_headers = &.{ 262 .{ .name = "location", .value = ui.RoutablePage.url(.default) }, 263 .{ .name = "set-cookie", .value = cookie }, 264 }, 265 }); 266 }, 267 .unknown_user => { 268 try request.respond("", .{ 269 .status = .see_other, 270 .extra_headers = &.{ 271 .{ .name = "location", .value = ui.RoutablePage.url(.home_auth) }, 272 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=unknown_user; Path=/; HttpOnly; SameSite=Strict" }, 273 }, 274 }); 275 }, 276 .wrong_password => { 277 try request.respond("", .{ 278 .status = .see_other, 279 .extra_headers = &.{ 280 .{ .name = "location", .value = ui.RoutablePage.url(.home_auth) }, 281 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=wrong_password; Path=/; HttpOnly; SameSite=Strict" }, 282 }, 283 }); 284 }, 285 } 286 } 287 288 fn handleLogout(request: *std.http.Server.Request, session_store: SessionStore) !void { 289 // revoke the session server-side so the cookie is dead for anyone holding 290 // a copy, not just this browser. 291 if (getCookieValue(request, cookie_name)) |token| session_store.remove(token); 292 // close the connection instead of keeping it alive: we don't read the 293 // request body, and respond()'s keep-alive path would otherwise try to 294 // discard it — which asserts on a bodyless POST that carries no 295 // content-length, and would block on one with no framing at all. a logout 296 // is just a redirect, so the browser reconnects for the follow-up GET. 297 try request.respond("", .{ 298 .status = .see_other, 299 .keep_alive = false, 300 .extra_headers = &.{ 301 .{ .name = "location", .value = ui.RoutablePage.url(.home_auth) }, 302 .{ .name = "set-cookie", .value = cookie_name ++ "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0" }, 303 }, 304 }); 305 } 306 307 fn handleAnsi(request: *std.http.Server.Request) !void { 308 // TODO: persist the flip in the logged-in user's server-side session so it 309 // survives this redirect and subsequent GETs. 310 // 311 // like logout, this is a bodyless POST, so close the connection rather than 312 // letting the keep-alive path try to discard a body that isn't framed. 313 try request.respond("", .{ 314 .status = .see_other, 315 .keep_alive = false, 316 .extra_headers = &.{ 317 .{ .name = "location", .value = ui.RoutablePage.url(.home_ansi) }, 318 }, 319 }); 320 } 321 322 fn renderIndexHtml( 323 io: std.Io, 324 allocator: std.mem.Allocator, 325 admin_repo_path: []const u8, 326 session_data: ui.Session.Data, 327 ) ![]const u8 { 328 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 329 330 // open the admin repo to read live user/repo data. 331 const repo_opts: rp.RepoOpts(.xit) = .{}; 332 const Repo = rp.Repo(.xit, repo_opts); 333 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 334 defer repo.deinit(io, allocator); 335 var page_arena = std.heap.ArenaAllocator.init(allocator); 336 defer page_arena.deinit(); 337 338 var session = try ui.Session.init(repo_opts, &page_arena, &repo, session_data); 339 340 const snapshot: ui.Snapshot = .{ 341 .page = .{ .home = try .init(repo_opts, session.arena, session.haxy_moment orelse unreachable) }, 342 .session = session.data, 343 }; 344 var root = try ui.initRoot(allocator, &snapshot.page, &session); 345 defer root.deinit(allocator); 346 347 const content = try generateHtml(allocator, &root); 348 defer allocator.free(content); 349 const overlay = try generateOverlay(allocator, &root); 350 defer allocator.free(overlay); 351 352 // serialize the snapshot so the wasm side can parse it back without 353 // making a second request. base64-encoded so the json can be embedded 354 // safely inside the host html. 355 var json: std.Io.Writer.Allocating = .init(allocator); 356 defer json.deinit(); 357 try std.json.Stringify.value(snapshot, .{}, &json.writer); 358 359 const b64 = std.base64.standard.Encoder; 360 const json_b64 = try allocator.alloc(u8, b64.calcSize(json.written().len)); 361 defer allocator.free(json_b64); 362 _ = b64.encode(json_b64, json.written()); 363 364 var out: std.ArrayList(u8) = .empty; 365 errdefer out.deinit(allocator); 366 { 367 var cursor: usize = 0; 368 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 369 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 370 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 371 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_b64 }, 372 }) |sub| { 373 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 374 try out.appendSlice(allocator, template[cursor..idx]); 375 try out.appendSlice(allocator, sub.replacement); 376 cursor = idx + sub.needle.len; 377 } 378 try out.appendSlice(allocator, template[cursor..]); 379 } 380 return try out.toOwnedSlice(allocator); 381 } 382 383 fn findEmbed(request_path: []const u8) ?Embed { 384 const path = if (std.mem.eql(u8, request_path, "/")) 385 "index.html" 386 else if (request_path.len > 1 and request_path[0] == '/') 387 request_path[1..] 388 else 389 return null; 390 391 for (embeds) |embed| { 392 if (std.mem.eql(u8, path, embed.path)) return embed; 393 } 394 return null; 395 } 396 397 fn logError(err: *std.Io.Writer, comptime fmt: []const u8, args: anytype) void { 398 err.print(fmt, args) catch return; 399 err.flush() catch {}; 400 } 401 402 // emits the TUI grid cells as static HTML 403 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 404 const grid = root.getGrid() orelse return error.MissingGrid; 405 const root_focus = root.getFocus(); 406 407 const Tag = union(enum) { 408 span, // clickable focusable cell 409 a: []const u8, // clickable focusable link 410 plain, // non-focusable, colored 411 412 const a_prefix = "a:"; 413 414 fn init(str: []const u8) @This() { 415 if (std.mem.startsWith(u8, str, a_prefix)) { 416 return .{ .a = str[a_prefix.len..] }; 417 } 418 return .span; 419 } 420 421 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 422 var id_buf: [32]u8 = undefined; 423 switch (self) { 424 .span => { 425 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 426 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 427 try out.appendSlice(alloc, "\""); 428 try out.appendSlice(alloc, style_attr); 429 try out.appendSlice(alloc, ">"); 430 }, 431 .a => |href| { 432 try out.appendSlice(alloc, "<a class=\"clickable\" data-focus-id=\""); 433 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 434 try out.appendSlice(alloc, "\" href=\""); 435 try appendEscapedHtml(alloc, out, href); 436 try out.appendSlice(alloc, "\""); 437 try out.appendSlice(alloc, style_attr); 438 try out.appendSlice(alloc, ">"); 439 }, 440 .plain => { 441 try out.appendSlice(alloc, "<span"); 442 try out.appendSlice(alloc, style_attr); 443 try out.appendSlice(alloc, ">"); 444 }, 445 } 446 } 447 448 fn closeTag(self: @This()) []const u8 { 449 return switch (self) { 450 .span, .plain => "</span>", 451 .a => "</a>", 452 }; 453 } 454 }; 455 456 var out: std.ArrayList(u8) = .empty; 457 errdefer out.deinit(allocator); 458 459 for (0..grid.size.height) |y| { 460 var cur_id: ?usize = null; 461 var cur_fg: ?Grid.Color = null; 462 var cur_bg: ?Grid.Color = null; 463 var open_tag: ?Tag = null; 464 var first = true; 465 for (0..grid.size.width) |x| { 466 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 467 const cell_id = cellFocusId(root_focus, x, y); 468 const fg = cell.style.fg; 469 const bg = cell.style.bg; 470 471 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 472 if (open_tag) |t| try out.appendSlice(allocator, t.closeTag()); 473 474 var new_tag: ?Tag = null; 475 if (cell_id) |id| { 476 if (root_focus.children.get(id)) |child| { 477 new_tag = switch (child.focus.kind) { 478 .custom => |custom| Tag.init(custom), 479 else => .span, 480 }; 481 } 482 } 483 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 484 485 if (new_tag) |t| { 486 var style_buf: [64]u8 = undefined; 487 try t.writeOpenTag(allocator, &out, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 488 } 489 490 open_tag = new_tag; 491 cur_id = cell_id; 492 cur_fg = fg; 493 cur_bg = bg; 494 first = false; 495 } 496 497 try appendEscapedHtml(allocator, &out, cell.rune orelse " "); 498 } 499 if (open_tag) |t| try out.appendSlice(allocator, t.closeTag()); 500 try out.append(allocator, '\n'); 501 } 502 503 return try out.toOwnedSlice(allocator); 504 } 505 506 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 507 // widget tree, each wrapping the text inputs and submit button inside it, 508 // positioned absolutely over the matching grid cells. 509 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 510 const root_focus = root.getFocus(); 511 512 var out: std.ArrayList(u8) = .empty; 513 errdefer out.deinit(allocator); 514 515 const form_prefix = "form:"; 516 517 // Focus.children is an AutoArrayHashMap that preserves insertion order, 518 // which matches the order widgets were added in code 519 var iter = root_focus.children.iterator(); 520 while (iter.next()) |entry| { 521 const child = entry.value_ptr.*; 522 const action_url = switch (child.focus.kind) { 523 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 524 custom[form_prefix.len..] 525 else 526 continue, 527 else => continue, 528 }; 529 530 try out.appendSlice(allocator, "<form action=\""); 531 try appendEscapedHtml(allocator, &out, action_url); 532 try out.appendSlice(allocator, "\" method=\"post\">"); 533 534 // form.focus.children was populated by addChild, which flattens the 535 // whole subtree into one map — so descendants (inputs + the submit 536 // button) all appear here. positions on form.focus are relative to 537 // the form, so we look up absolute rects via root_focus for layout. 538 var inner_iter = child.focus.children.iterator(); 539 while (inner_iter.next()) |inner_entry| { 540 const inner_id = inner_entry.key_ptr.*; 541 const root_child = root_focus.children.get(inner_id) orelse continue; 542 const r = root_child.rect; 543 switch (root_child.focus.kind) { 544 .text_input, .text_input_password => { 545 const ti: *wgt.TextInput(ui.Widget) = @fieldParentPtr("focus", root_child.focus); 546 const inner_left = r.x + 1; 547 const inner_top = r.y + 1; 548 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 549 550 try out.appendSlice(allocator, "<input type=\""); 551 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 552 try out.appendSlice(allocator, "\" data-focus-id=\""); 553 var id_buf: [32]u8 = undefined; 554 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 555 if (ti.options.name.len > 0) { 556 try out.appendSlice(allocator, "\" name=\""); 557 try appendEscapedHtml(allocator, &out, ti.options.name); 558 } 559 // intentionally no `value` attribute: the browser tracks user input 560 // natively, and including the wasm-side value here would make the 561 // overlay HTML differ on every keystroke — that would trip the diff 562 // in _setOverlay and rebuild the <input>, eating the user's caret. 563 try out.appendSlice(allocator, "\" style=\"left:"); 564 var pos_buf: [64]u8 = undefined; 565 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 })); 566 try out.appendSlice(allocator, "\">"); 567 }, 568 .custom => |custom| { 569 if (std.mem.eql(u8, "submit", custom)) { 570 // inside the dashed border the TUI cells draw around the button. 571 const inner_left = r.x + 1; 572 const inner_top = r.y + 1; 573 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 574 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 575 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 576 var id_buf: [32]u8 = undefined; 577 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 578 try out.appendSlice(allocator, "\" style=\"left:"); 579 var pos_buf: [128]u8 = undefined; 580 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 })); 581 try out.appendSlice(allocator, "\"></button>"); 582 } 583 }, 584 else => {}, 585 } 586 } 587 588 try out.appendSlice(allocator, "</form>"); 589 } 590 591 return try out.toOwnedSlice(allocator); 592 } 593 594 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 595 if (a) |av| return if (b) |bv| av.eql(bv) else false; 596 return b == null; 597 } 598 599 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 600 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 601 // empty slice when neither is set. 602 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 603 if (fg == null and bg == null) return buf[0..0]; 604 const prefix = " style=\""; 605 @memcpy(buf[0..prefix.len], prefix); 606 var i: usize = prefix.len; 607 if (fg) |c| { 608 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]; 609 i += s.len; 610 } 611 if (bg) |c| { 612 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]; 613 i += s.len; 614 } 615 buf[i] = '"'; 616 i += 1; 617 return buf[0..i]; 618 } 619 620 fn cellFocusId(focus: *Focus, x: usize, y: usize) ?usize { 621 var iter = focus.children.iterator(); 622 while (iter.next()) |entry| { 623 const child = entry.value_ptr.*; 624 if (!child.focus.focusable) continue; 625 const r = child.rect; 626 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 627 return entry.key_ptr.*; 628 } 629 } 630 return null; 631 } 632 633 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 634 for (input) |ch| { 635 switch (ch) { 636 '&' => try out.appendSlice(allocator, "&amp;"), 637 '<' => try out.appendSlice(allocator, "&lt;"), 638 '>' => try out.appendSlice(allocator, "&gt;"), 639 '"' => try out.appendSlice(allocator, "&quot;"), 640 '\'' => try out.appendSlice(allocator, "&#39;"), 641 else => try out.append(allocator, ch), 642 } 643 } 644 } 645 646 // --- helpers -------------------------------------------------------------- 647 648 fn openHaxyMoment( 649 comptime repo_opts: rp.RepoOpts(.xit), 650 repo: *rp.Repo(.xit, repo_opts), 651 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 652 const DB = rp.Repo(.xit, repo_opts).DB; 653 const history = try DB.ArrayList(.read_only).init(repo.core.db.rootCursor().readOnly()); 654 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 655 const moment = try DB.HashMap(.read_only).init(moment_cursor); 656 const last_object_id_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy-last-object-id")) orelse return error.NotFound; 657 var last_object_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 658 _ = try last_object_id_cursor.readBytes(&last_object_id); 659 const haxy_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy")) orelse return error.NotFound; 660 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 661 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 662 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 663 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &last_object_id)) orelse return error.NotFound; 664 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 665 } 666 667 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 668 var iter = request.iterateHeaders(); 669 while (iter.next()) |header| { 670 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 671 var pairs = std.mem.splitScalar(u8, header.value, ';'); 672 while (pairs.next()) |pair| { 673 const trimmed = std.mem.trim(u8, pair, " \t"); 674 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 675 if (std.mem.eql(u8, trimmed[0..eq], name)) { 676 return trimmed[eq + 1 ..]; 677 } 678 } 679 } 680 return null; 681 } 682 683 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 684 var iter = std.mem.splitScalar(u8, body, '&'); 685 while (iter.next()) |pair| { 686 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 687 if (std.mem.eql(u8, pair[0..eq], key)) { 688 return try decodeFormValue(allocator, pair[eq + 1 ..]); 689 } 690 } 691 return null; 692 } 693 694 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 695 var out: std.ArrayList(u8) = .empty; 696 errdefer out.deinit(allocator); 697 var i: usize = 0; 698 while (i < encoded.len) : (i += 1) { 699 switch (encoded[i]) { 700 '+' => try out.append(allocator, ' '), 701 '%' => { 702 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 703 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 704 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 705 try out.append(allocator, hi * 16 + lo); 706 i += 2; 707 }, 708 else => try out.append(allocator, encoded[i]), 709 } 710 } 711 return try out.toOwnedSlice(allocator); 712 } 713 714 // disk-backed web session store. each login mints a random, opaque token 715 // (not the user's id) that is stored as a file named by the token hex, whose 716 // contents are the raw user_id bytes. authenticating a request is a lookup of 717 // the cookie's token; logout deletes the file, revoking the session. there is 718 // deliberately no expiry — a session lives until logout. 719 pub const SessionStore = struct { 720 io: std.Io, 721 dir: std.Io.Dir, 722 723 pub const token_hex_len = evt.event_id_size * 2; 724 725 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 726 try data_dir.createDirPath(io, "sessions"); 727 const dir = try data_dir.openDir(io, "sessions", .{}); 728 return .{ .io = io, .dir = dir }; 729 } 730 731 pub fn deinit(self: SessionStore) void { 732 self.dir.close(self.io); 733 } 734 735 // mint a new session for user_id, returning the token hex to set as the 736 // cookie value. 737 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 738 var token: [evt.event_id_size]u8 = undefined; 739 self.io.random(&token); 740 const token_hex = std.fmt.bytesToHex(token, .lower); 741 const file = try self.dir.createFile(self.io, &token_hex, .{}); 742 defer file.close(self.io); 743 try file.writeStreamingAll(self.io, user_id); 744 return token_hex; 745 } 746 747 // resolve a cookie's token to its user_id. returns false (logged out) for a 748 // missing, malformed, or unknown token. 749 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 750 if (!isToken(token_hex)) return false; 751 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 752 defer file.close(self.io); 753 var storage: [evt.event_id_size]u8 = undefined; 754 var file_reader = file.reader(self.io, &storage); 755 file_reader.interface.readSliceAll(out) catch return false; 756 return true; 757 } 758 759 // revoke a session. a no-op for a missing or malformed token. 760 pub fn remove(self: SessionStore, token_hex: []const u8) void { 761 if (!isToken(token_hex)) return; 762 self.dir.deleteFile(self.io, token_hex) catch {}; 763 } 764 765 // a token is exactly token_hex_len hex chars. validating before using the 766 // value as a path keeps attacker-supplied cookies from escaping the 767 // sessions dir (e.g. via "/" or ".." bytes). 768 fn isToken(token_hex: []const u8) bool { 769 if (token_hex.len != token_hex_len) return false; 770 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 771 return true; 772 } 773 }; 774