╭ 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 11 const cookie_name = "haxy_user"; 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 err: *std.Io.Writer, 37 ) void { 38 const Listener = struct { 39 io: std.Io, 40 allocator: std.mem.Allocator, 41 net_server: *std.Io.net.Server, 42 tasks: *std.Io.Group, 43 admin_repo_path: []const u8, 44 err: *std.Io.Writer, 45 46 fn run(ctx: @This()) void { 47 while (true) { 48 const stream = ctx.net_server.accept(ctx.io) catch |accept_err| { 49 if (accept_err == error.Canceled) return; 50 logError(ctx.err, "web ui accept failed: {s}\n", .{@errorName(accept_err)}); 51 continue; 52 }; 53 54 const Connection = struct { 55 io: std.Io, 56 allocator: std.mem.Allocator, 57 stream: std.Io.net.Stream, 58 admin_repo_path: []const u8, 59 err: *std.Io.Writer, 60 61 fn run(conn: @This()) void { 62 defer conn.stream.close(conn.io); 63 handleConnection(conn.io, conn.allocator, conn.stream, conn.admin_repo_path, conn.err) catch |request_err| { 64 logError(conn.err, "web ui request failed: {s}\n", .{@errorName(request_err)}); 65 }; 66 } 67 }; 68 69 ctx.tasks.async(ctx.io, Connection.run, .{Connection{ 70 .io = ctx.io, 71 .allocator = ctx.allocator, 72 .stream = stream, 73 .admin_repo_path = ctx.admin_repo_path, 74 .err = ctx.err, 75 }}); 76 } 77 } 78 }; 79 80 tasks.async(io, Listener.run, .{Listener{ 81 .io = io, 82 .allocator = allocator, 83 .net_server = net_server, 84 .tasks = tasks, 85 .admin_repo_path = admin_repo_path, 86 .err = err, 87 }}); 88 } 89 90 fn handleConnection( 91 io: std.Io, 92 allocator: std.mem.Allocator, 93 stream: std.Io.net.Stream, 94 admin_repo_path: []const u8, 95 err: *std.Io.Writer, 96 ) !void { 97 var send_buffer = [_]u8{0} ** 4096; 98 var recv_buffer = [_]u8{0} ** 4096; 99 var conn_br = stream.reader(io, &recv_buffer); 100 var conn_bw = stream.writer(io, &send_buffer); 101 var http_server = std.http.Server.init(&conn_br.interface, &conn_bw.interface); 102 103 // serve multiple requests on a single connection so HTTP/1.1 keep-alive 104 // works — important for browser-native form POST: after the 303 the 105 // browser issues GET / on the same socket, and forcibly closing here 106 // would race the follow-up request into a "site can't be reached". 107 while (http_server.reader.state == .ready) { 108 var request = http_server.receiveHead() catch |receive_err| switch (receive_err) { 109 error.HttpConnectionClosing => break, 110 error.ReadFailed => break, 111 else => |e| return e, 112 }; 113 114 handleRequest(io, &request, allocator, admin_repo_path) catch |request_err| { 115 try err.print("web ui request failed: {s}\n", .{@errorName(request_err)}); 116 try err.flush(); 117 // best-effort 500. if handleRequest already started writing a 118 // response before throwing, this respond may fail too, but at 119 // that point the connection is unrecoverable anyway. 120 request.respond(@errorName(request_err), .{ 121 .status = .internal_server_error, 122 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 123 }) catch {}; 124 }; 125 } 126 } 127 128 fn handleRequest( 129 io: std.Io, 130 request: *std.http.Server.Request, 131 allocator: std.mem.Allocator, 132 admin_repo_path: []const u8, 133 ) !void { 134 const method = request.head.method; 135 const uri = try std.Uri.parseAfterScheme("", request.head.target); 136 const path = uri.path.percent_encoded; 137 138 if (method == .POST and std.mem.eql(u8, path, "/login")) { 139 return handleLogin(io, request, allocator, admin_repo_path); 140 } 141 if (method == .POST and std.mem.eql(u8, path, "/logout")) { 142 return handleLogout(request); 143 } 144 145 const get_or_head = method == .GET or method == .HEAD; 146 if (!get_or_head) { 147 try request.respond("method not allowed", .{ 148 .status = .method_not_allowed, 149 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 150 }); 151 return; 152 } 153 154 if (std.mem.eql(u8, path, "/favicon.ico")) { 155 try request.respond("", .{ 156 .status = .no_content, 157 .extra_headers = &.{.{ .name = "content-type", .value = "image/x-icon" }}, 158 }); 159 return; 160 } 161 162 if (ui.RoutablePage.fromUrl(path)) |current_page| { 163 // decode the haxy_user cookie into raw bytes on the stack; the 164 // slice lives for the rest of handleRequest, which is plenty for 165 // renderIndexHtml to consume. 166 var user_id_buf: [evt.event_id_size]u8 = undefined; 167 const user_id: ?[]const u8 = blk: { 168 const hex = getCookieValue(request, cookie_name) orelse break :blk null; 169 if (hex.len != evt.event_id_size * 2) break :blk null; 170 _ = std.fmt.hexToBytes(&user_id_buf, hex) catch break :blk null; 171 break :blk user_id_buf[0..evt.event_id_size]; 172 }; 173 const login_failure: ?ui.Home.Auth.Login.Failure = 174 if (getCookieValue(request, login_failure_cookie)) |raw| 175 if (std.mem.eql(u8, raw, "unknown_user")) 176 .unknown_user 177 else if (std.mem.eql(u8, raw, "wrong_password")) 178 .wrong_password 179 else 180 null 181 else 182 null; 183 const html = try renderIndexHtml(io, allocator, admin_repo_path, .{ 184 .user_id = user_id, 185 .login_failure = login_failure, 186 .current_page = current_page, 187 }); 188 defer allocator.free(html); 189 // expire the flash cookie on the way out so a refresh doesn't keep 190 // showing the failure label. 191 var headers: [2]std.http.Header = undefined; 192 headers[0] = .{ .name = "content-type", .value = "text/html; charset=utf-8" }; 193 var headers_slice: []const std.http.Header = headers[0..1]; 194 if (login_failure != null) { 195 headers[1] = .{ .name = "set-cookie", .value = login_failure_cookie ++ "=; Path=/; Max-Age=0" }; 196 headers_slice = headers[0..2]; 197 } 198 try request.respond(html, .{ .extra_headers = headers_slice }); 199 return; 200 } 201 202 const embed = findEmbed(path) orelse { 203 try request.respond("not found", .{ 204 .status = .not_found, 205 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 206 }); 207 return; 208 }; 209 210 try request.respond(embed.body, .{ 211 .extra_headers = &.{.{ .name = "content-type", .value = embed.content_type }}, 212 }); 213 } 214 215 fn handleLogin( 216 io: std.Io, 217 request: *std.http.Server.Request, 218 allocator: std.mem.Allocator, 219 admin_repo_path: []const u8, 220 ) !void { 221 var body_buf: [256]u8 = undefined; 222 const reader = request.readerExpectNone(&body_buf); 223 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 224 defer allocator.free(body); 225 226 const username = (try parseFormField(allocator, body, "username")) orelse try allocator.dupe(u8, ""); 227 defer allocator.free(username); 228 const password = (try parseFormField(allocator, body, "password")) orelse try allocator.dupe(u8, ""); 229 defer allocator.free(password); 230 231 const repo_opts: rp.RepoOpts(.xit) = .{}; 232 const Repo = rp.Repo(.xit, repo_opts); 233 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 234 defer repo.deinit(io, allocator); 235 236 var arena = std.heap.ArenaAllocator.init(allocator); 237 defer arena.deinit(); 238 239 const haxy_moment = try openHaxyMoment(repo_opts, &repo); 240 const result = try evt.User.verifyCredentials(Repo.DB, repo_opts.hash, haxy_moment, &arena, username, password); 241 242 switch (result) { 243 .success => |user_id| { 244 const hex = std.fmt.bytesToHex(user_id, .lower); 245 var cookie_buf: [256]u8 = undefined; 246 const cookie = try std.fmt.bufPrint(&cookie_buf, cookie_name ++ "={s}; Path=/; HttpOnly; SameSite=Strict", .{hex}); 247 try request.respond("", .{ 248 .status = .see_other, 249 .extra_headers = &.{ 250 .{ .name = "location", .value = ui.RoutablePage.url(.default) }, 251 .{ .name = "set-cookie", .value = cookie }, 252 }, 253 }); 254 }, 255 .unknown_user => { 256 try request.respond("", .{ 257 .status = .see_other, 258 .extra_headers = &.{ 259 .{ .name = "location", .value = ui.RoutablePage.url(.home_auth) }, 260 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=unknown_user; Path=/; HttpOnly; SameSite=Strict" }, 261 }, 262 }); 263 }, 264 .wrong_password => { 265 try request.respond("", .{ 266 .status = .see_other, 267 .extra_headers = &.{ 268 .{ .name = "location", .value = ui.RoutablePage.url(.home_auth) }, 269 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=wrong_password; Path=/; HttpOnly; SameSite=Strict" }, 270 }, 271 }); 272 }, 273 } 274 } 275 276 fn handleLogout(request: *std.http.Server.Request) !void { 277 // request.respond's discardBody reads any unused body for us and lands 278 // the connection back in the .ready state for the next request on the 279 // same connection (keep_alive defaults to true). 280 try request.respond("", .{ 281 .status = .see_other, 282 .extra_headers = &.{ 283 .{ .name = "location", .value = ui.RoutablePage.url(.home_auth) }, 284 .{ .name = "set-cookie", .value = cookie_name ++ "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0" }, 285 }, 286 }); 287 } 288 289 fn renderIndexHtml( 290 io: std.Io, 291 allocator: std.mem.Allocator, 292 admin_repo_path: []const u8, 293 session_data: ui.Session.Data, 294 ) ![]const u8 { 295 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 296 297 // open the admin repo to read live user/repo data. 298 const repo_opts: rp.RepoOpts(.xit) = .{}; 299 const Repo = rp.Repo(.xit, repo_opts); 300 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 301 defer repo.deinit(io, allocator); 302 var page_arena = std.heap.ArenaAllocator.init(allocator); 303 defer page_arena.deinit(); 304 305 var session = try ui.Session.init(repo_opts, &page_arena, &repo, session_data); 306 307 const snapshot: ui.Snapshot = .{ 308 .page = .{ .home = try .init(repo_opts, session.arena, session.haxy_moment orelse unreachable) }, 309 .session = session.data, 310 }; 311 var root = try ui.initRoot(allocator, &snapshot.page, &session); 312 defer root.deinit(allocator); 313 314 const content = try generateHtml(allocator, &root, &session); 315 defer allocator.free(content); 316 const overlay = try generateOverlay(allocator, &root, &session); 317 defer allocator.free(overlay); 318 319 // serialize the snapshot so the wasm side can parse it back without 320 // making a second request. base64-encoded so the json can be embedded 321 // safely inside the host html. 322 var json: std.Io.Writer.Allocating = .init(allocator); 323 defer json.deinit(); 324 try std.json.Stringify.value(snapshot, .{}, &json.writer); 325 326 const b64 = std.base64.standard.Encoder; 327 const json_b64 = try allocator.alloc(u8, b64.calcSize(json.written().len)); 328 defer allocator.free(json_b64); 329 _ = b64.encode(json_b64, json.written()); 330 331 var out: std.ArrayList(u8) = .empty; 332 errdefer out.deinit(allocator); 333 { 334 var cursor: usize = 0; 335 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 336 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 337 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 338 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_b64 }, 339 }) |sub| { 340 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 341 try out.appendSlice(allocator, template[cursor..idx]); 342 try out.appendSlice(allocator, sub.replacement); 343 cursor = idx + sub.needle.len; 344 } 345 try out.appendSlice(allocator, template[cursor..]); 346 } 347 return try out.toOwnedSlice(allocator); 348 } 349 350 fn findEmbed(request_path: []const u8) ?Embed { 351 const path = if (std.mem.eql(u8, request_path, "/")) 352 "index.html" 353 else if (request_path.len > 1 and request_path[0] == '/') 354 request_path[1..] 355 else 356 return null; 357 358 for (embeds) |embed| { 359 if (std.mem.eql(u8, path, embed.path)) return embed; 360 } 361 return null; 362 } 363 364 fn logError(err: *std.Io.Writer, comptime fmt: []const u8, args: anytype) void { 365 err.print(fmt, args) catch return; 366 err.flush() catch {}; 367 } 368 369 // emits the TUI grid cells (one <span> run per focusable widget) 370 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget, session: *const ui.Session) ![]const u8 { 371 _ = session; 372 const grid = root.getGrid() orelse return error.MissingGrid; 373 const root_focus = root.getFocus(); 374 375 var out: std.ArrayList(u8) = .empty; 376 errdefer out.deinit(allocator); 377 378 for (0..grid.size.height) |y| { 379 var current_id: ?usize = null; 380 for (0..grid.size.width) |x| { 381 const cell_id = cellFocusId(root_focus, x, y); 382 if (cell_id != current_id) { 383 if (current_id != null) try out.appendSlice(allocator, "</span>"); 384 if (cell_id) |id| { 385 var buf: [128]u8 = undefined; 386 const tag = try std.fmt.bufPrint(&buf, "<span class=\"clickable\" data-focus-id=\"{d}\">", .{id}); 387 try out.appendSlice(allocator, tag); 388 } 389 current_id = cell_id; 390 } 391 const rune = grid.cells.items[try grid.cells.at(.{ y, x })].rune orelse " "; 392 try appendEscapedHtml(allocator, &out, rune); 393 } 394 if (current_id != null) try out.appendSlice(allocator, "</span>"); 395 try out.append(allocator, '\n'); 396 } 397 398 return try out.toOwnedSlice(allocator); 399 } 400 401 // emits the form overlay — a <form> wrapping the text inputs and submit 402 // button, positioned absolutely over the matching grid cells 403 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *const ui.Session) ![]const u8 { 404 const root_focus = root.getFocus(); 405 406 var out: std.ArrayList(u8) = .empty; 407 errdefer out.deinit(allocator); 408 409 const InputEntry = struct { 410 focus_id: usize, 411 x: usize, 412 y: usize, 413 width: usize, 414 is_password: bool, 415 ti: *wgt.TextInput(ui.Widget), 416 }; 417 const SubmitButton = struct { 418 focus_id: usize, 419 x: usize, 420 y: usize, 421 width: usize, 422 height: usize, 423 }; 424 var inputs: std.ArrayList(InputEntry) = .empty; 425 defer inputs.deinit(allocator); 426 var submit: ?SubmitButton = null; 427 428 var iter = root_focus.children.iterator(); 429 while (iter.next()) |entry| { 430 const child = entry.value_ptr.*; 431 switch (child.focus.kind) { 432 .text_input, .text_input_password => { 433 try inputs.append(allocator, .{ 434 .focus_id = entry.key_ptr.*, 435 .x = child.rect.x, 436 .y = child.rect.y, 437 .width = child.rect.size.width, 438 .is_password = child.focus.kind == .text_input_password, 439 .ti = @fieldParentPtr("focus", child.focus), 440 }); 441 }, 442 .submit_button => { 443 submit = .{ 444 .focus_id = entry.key_ptr.*, 445 .x = child.rect.x, 446 .y = child.rect.y, 447 .width = child.rect.size.width, 448 .height = child.rect.size.height, 449 }; 450 }, 451 else => {}, 452 } 453 } 454 455 if (submit == null and inputs.items.len == 0) return try out.toOwnedSlice(allocator); 456 457 // top-to-bottom, left-to-right order so the natural tab cycle matches 458 // visual layout (username -> password -> submit button). 459 std.mem.sort(InputEntry, inputs.items, {}, struct { 460 fn lt(_: void, a: InputEntry, b: InputEntry) bool { 461 if (a.y != b.y) return a.y < b.y; 462 return a.x < b.x; 463 } 464 }.lt); 465 466 // only the auth page hosts a form right now; on any other page we 467 // emit nothing. on auth, the URL depends on whether there's already 468 // an active session. 469 const action_url: []const u8 = switch (session.data.current_page) { 470 .home_auth => if (session.data.user_id != null) "/logout" else "/login", 471 .home_users, .home_repos => return try out.toOwnedSlice(allocator), 472 }; 473 474 try out.appendSlice(allocator, "<form action=\""); 475 try out.appendSlice(allocator, action_url); 476 try out.appendSlice(allocator, "\" method=\"post\">"); 477 478 for (inputs.items) |entry| { 479 const inner_left = entry.x + 1; 480 const inner_top = entry.y + 1; 481 const inner_width = if (entry.width > 2) entry.width - 2 else 0; 482 483 try out.appendSlice(allocator, "<input type=\""); 484 try out.appendSlice(allocator, if (entry.is_password) "password" else "text"); 485 try out.appendSlice(allocator, "\" data-focus-id=\""); 486 var id_buf: [32]u8 = undefined; 487 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{entry.focus_id})); 488 if (entry.ti.options.name.len > 0) { 489 try out.appendSlice(allocator, "\" name=\""); 490 try appendEscapedHtml(allocator, &out, entry.ti.options.name); 491 } 492 // intentionally no `value` attribute: the browser tracks user input 493 // natively, and including the wasm-side value here would make the 494 // overlay HTML differ on every keystroke — that would trip the diff 495 // in _setOverlay and rebuild the <input>, eating the user's caret. 496 try out.appendSlice(allocator, "\" style=\"left:"); 497 var pos_buf: [64]u8 = undefined; 498 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 })); 499 try out.appendSlice(allocator, "\">"); 500 } 501 502 if (submit) |btn| { 503 // inside the dashed border the TUI cells draw around the button. 504 const inner_left = btn.x + 1; 505 const inner_top = btn.y + 1; 506 const inner_width = if (btn.width > 2) btn.width - 2 else 0; 507 const inner_height = if (btn.height > 2) btn.height - 2 else 0; 508 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 509 var id_buf: [32]u8 = undefined; 510 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{btn.focus_id})); 511 try out.appendSlice(allocator, "\" style=\"left:"); 512 var pos_buf: [128]u8 = undefined; 513 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 })); 514 try out.appendSlice(allocator, "\"></button>"); 515 } 516 517 try out.appendSlice(allocator, "</form>"); 518 519 return try out.toOwnedSlice(allocator); 520 } 521 522 fn cellFocusId(focus: *Focus, x: usize, y: usize) ?usize { 523 var iter = focus.children.iterator(); 524 while (iter.next()) |entry| { 525 const child = entry.value_ptr.*; 526 if (!child.focus.focusable) continue; 527 const r = child.rect; 528 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 529 return entry.key_ptr.*; 530 } 531 } 532 return null; 533 } 534 535 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 536 for (input) |ch| { 537 switch (ch) { 538 '&' => try out.appendSlice(allocator, "&amp;"), 539 '<' => try out.appendSlice(allocator, "&lt;"), 540 '>' => try out.appendSlice(allocator, "&gt;"), 541 '"' => try out.appendSlice(allocator, "&quot;"), 542 '\'' => try out.appendSlice(allocator, "&#39;"), 543 else => try out.append(allocator, ch), 544 } 545 } 546 } 547 548 // --- helpers -------------------------------------------------------------- 549 550 fn openHaxyMoment( 551 comptime repo_opts: rp.RepoOpts(.xit), 552 repo: *rp.Repo(.xit, repo_opts), 553 ) !rp.Repo(.xit, repo_opts).DB.HashMap(.read_only) { 554 const DB = rp.Repo(.xit, repo_opts).DB; 555 const history = try DB.ArrayList(.read_only).init(repo.core.db.rootCursor().readOnly()); 556 const moment_cursor = try history.getCursor(-1) orelse return error.NotFound; 557 const moment = try DB.HashMap(.read_only).init(moment_cursor); 558 const last_object_id_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy-last-object-id")) orelse return error.NotFound; 559 var last_object_id: [hash.byteLen(repo_opts.hash)]u8 = undefined; 560 _ = try last_object_id_cursor.readBytes(&last_object_id); 561 const haxy_cursor = try moment.getCursor(hash.hashInt(repo_opts.hash, "haxy")) orelse return error.NotFound; 562 const haxy = try DB.ArrayList(.read_only).init(haxy_cursor); 563 const haxy_moments_cursor = try haxy.getCursor(-1) orelse return error.NotFound; 564 const haxy_moments = try DB.HashMap(.read_only).init(haxy_moments_cursor); 565 const haxy_moment_cursor = try haxy_moments.getCursor(hash.bytesToInt(repo_opts.hash, &last_object_id)) orelse return error.NotFound; 566 return try DB.HashMap(.read_only).init(haxy_moment_cursor); 567 } 568 569 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 570 var iter = request.iterateHeaders(); 571 while (iter.next()) |header| { 572 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 573 var pairs = std.mem.splitScalar(u8, header.value, ';'); 574 while (pairs.next()) |pair| { 575 const trimmed = std.mem.trim(u8, pair, " \t"); 576 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 577 if (std.mem.eql(u8, trimmed[0..eq], name)) { 578 return trimmed[eq + 1 ..]; 579 } 580 } 581 } 582 return null; 583 } 584 585 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 586 var iter = std.mem.splitScalar(u8, body, '&'); 587 while (iter.next()) |pair| { 588 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 589 if (std.mem.eql(u8, pair[0..eq], key)) { 590 return try decodeFormValue(allocator, pair[eq + 1 ..]); 591 } 592 } 593 return null; 594 } 595 596 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 597 var out: std.ArrayList(u8) = .empty; 598 errdefer out.deinit(allocator); 599 var i: usize = 0; 600 while (i < encoded.len) : (i += 1) { 601 switch (encoded[i]) { 602 '+' => try out.append(allocator, ' '), 603 '%' => { 604 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 605 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 606 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 607 try out.append(allocator, hi * 16 + lo); 608 i += 2; 609 }, 610 else => try out.append(allocator, encoded[i]), 611 } 612 } 613 return try out.toOwnedSlice(allocator); 614 } 615