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