╭ 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("haxy.wasm") }, 28 }; 29 30 // what a web request is served from: the multi-user server (admin repo + 31 // login sessions) or a single local repo. 32 pub const Host = union(enum) { 33 remote: struct { 34 admin_repo_path: []const u8, 35 session_store: SessionStore, 36 }, 37 local: ui.RepoSource, 38 }; 39 40 pub fn handleConnection( 41 io: std.Io, 42 allocator: std.mem.Allocator, 43 stream: std.Io.net.Stream, 44 host: Host, 45 err: *std.Io.Writer, 46 ) !void { 47 var send_buffer = [_]u8{0} ** 4096; 48 var recv_buffer = [_]u8{0} ** 4096; 49 var conn_br = stream.reader(io, &recv_buffer); 50 var conn_bw = stream.writer(io, &send_buffer); 51 var http_server = std.http.Server.init(&conn_br.interface, &conn_bw.interface); 52 53 // serve multiple requests on a single connection so HTTP/1.1 keep-alive 54 // works — important for browser-native form POST: after the 303 the 55 // browser issues GET / on the same socket, and forcibly closing here 56 // would race the follow-up request into a "site can't be reached". 57 while (http_server.reader.state == .ready) { 58 var request = http_server.receiveHead() catch |receive_err| switch (receive_err) { 59 error.HttpConnectionClosing => break, 60 error.ReadFailed => break, 61 else => |e| return e, 62 }; 63 64 handleRequest(io, &request, allocator, host) catch |request_err| { 65 try err.print("web ui request failed: {s}\n", .{@errorName(request_err)}); 66 try err.flush(); 67 // best-effort 500. if handleRequest already started writing a 68 // response before throwing, this respond may fail too, but at 69 // that point the connection is unrecoverable anyway. 70 request.respond(@errorName(request_err), .{ 71 .status = .internal_server_error, 72 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 73 }) catch {}; 74 }; 75 } 76 } 77 78 fn handleRequest( 79 io: std.Io, 80 request: *std.http.Server.Request, 81 allocator: std.mem.Allocator, 82 host: Host, 83 ) !void { 84 const method = request.head.method; 85 const uri = try std.Uri.parseAfterScheme("", request.head.target); 86 const path = uri.path.percent_encoded; 87 88 // POST routes can be scoped by any page, so they can redirect using 89 // the base of the URL. this allows logging in to keep you on the page 90 // you were on. local mode has no accounts, so no POST routes. 91 if (method == .POST) { 92 switch (host) { 93 .remote => |remote| { 94 const PostRoute = enum { login, logout, ansi }; 95 inline for (@typeInfo(PostRoute).@"enum".fields) |field| { 96 const suffix = "/" ++ field.name; 97 if (std.mem.endsWith(u8, path, suffix)) { 98 const base = path[0 .. path.len - suffix.len]; 99 return switch (@field(PostRoute, field.name)) { 100 .login => handleLogin(io, request, allocator, base, remote.admin_repo_path, remote.session_store), 101 .logout => handleLogout(request, base, remote.session_store), 102 .ansi => handleAnsi(io, request, allocator, base, remote.admin_repo_path, remote.session_store), 103 }; 104 } 105 } 106 }, 107 .local => {}, 108 } 109 } 110 111 const get_or_head = method == .GET or method == .HEAD; 112 if (!get_or_head) { 113 try request.respond("method not allowed", .{ 114 .status = .method_not_allowed, 115 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 116 }); 117 return; 118 } 119 120 if (std.mem.eql(u8, path, "/favicon.ico")) { 121 try request.respond("", .{ 122 .status = .no_content, 123 .extra_headers = &.{.{ .name = "content-type", .value = "image/x-icon" }}, 124 }); 125 return; 126 } 127 128 const current_page_maybe = switch (host) { 129 .remote => ui.RoutablePage.fromUrl(path), 130 .local => ui.RoutablePage.fromUrlLocal(path), 131 }; 132 if (current_page_maybe) |current_page| { 133 // resolve the haxy_session cookie's token to a user_id via the 134 // store. user_id_buf lives on the stack for the rest of handleRequest, 135 // which is plenty for renderIndexHtml to consume. local mode has no 136 // accounts, so it is always logged out. 137 var user_id_buf: [evt.event_id_size]u8 = undefined; 138 var user_id: ?[]const u8 = null; 139 var login_failure: ?ui.Home.Auth.Login.Failure = null; 140 switch (host) { 141 .remote => |remote| { 142 user_id = blk: { 143 const token = getCookieValue(request, cookie_name) orelse break :blk null; 144 if (!remote.session_store.lookup(token, &user_id_buf)) break :blk null; 145 break :blk user_id_buf[0..evt.event_id_size]; 146 }; 147 login_failure = if (getCookieValue(request, login_failure_cookie)) |raw| 148 if (std.mem.eql(u8, raw, "unknown_user")) 149 .unknown_user 150 else if (std.mem.eql(u8, raw, "wrong_password")) 151 .wrong_password 152 else 153 null 154 else 155 null; 156 }, 157 .local => {}, 158 } 159 160 const html = renderIndexHtml(io, allocator, host, .{ 161 .user_id = user_id, 162 .login_failure = login_failure, 163 .current_page = current_page, 164 .is_local = host == .local, 165 }) catch |err| switch (err) { 166 error.NotFound => { 167 try request.respond("not found", .{ 168 .status = .not_found, 169 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 170 }); 171 return; 172 }, 173 else => |e| return e, 174 }; 175 defer allocator.free(html); 176 177 // expire the flash cookie on the way out so a refresh doesn't keep 178 // showing the failure label. 179 var headers: [2]std.http.Header = undefined; 180 headers[0] = .{ .name = "content-type", .value = "text/html; charset=utf-8" }; 181 var headers_slice: []const std.http.Header = headers[0..1]; 182 if (login_failure != null) { 183 headers[1] = .{ .name = "set-cookie", .value = login_failure_cookie ++ "=; Path=/; Max-Age=0" }; 184 headers_slice = headers[0..2]; 185 } 186 try request.respond(html, .{ .extra_headers = headers_slice }); 187 return; 188 } 189 190 const embed = findEmbed(path) orelse { 191 try request.respond("not found", .{ 192 .status = .not_found, 193 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 194 }); 195 return; 196 }; 197 198 try request.respond(embed.body, .{ 199 .extra_headers = &.{.{ .name = "content-type", .value = embed.content_type }}, 200 }); 201 } 202 203 fn handleLogin( 204 io: std.Io, 205 request: *std.http.Server.Request, 206 allocator: std.mem.Allocator, 207 base: []const u8, 208 admin_repo_path: []const u8, 209 session_store: SessionStore, 210 ) !void { 211 var body_buf: [256]u8 = undefined; 212 const reader = request.readerExpectNone(&body_buf); 213 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 214 defer allocator.free(body); 215 216 const username = (try parseFormField(allocator, body, "username")) orelse try allocator.dupe(u8, ""); 217 defer allocator.free(username); 218 const password = (try parseFormField(allocator, body, "password")) orelse try allocator.dupe(u8, ""); 219 defer allocator.free(password); 220 221 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 222 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 223 defer repo.deinit(io, allocator); 224 225 var arena = std.heap.ArenaAllocator.init(allocator); 226 defer arena.deinit(); 227 228 const haxy_moment = try evt.currentMoment(evt.admin_repo_opts, &repo); 229 const result = try evt.User.verifyCredentials(evt.AdminDB, evt.admin_repo_opts.hash, haxy_moment, &arena, username, password); 230 231 // on success, return to the page the login came from (base, or "/" at the 232 // root); on failure, stay on its auth tab to surface the error. 233 const success_location: []const u8 = if (base.len == 0) "/" else base; 234 const failure_location = try std.fmt.allocPrint(arena.allocator(), "{s}/auth", .{base}); 235 236 switch (result) { 237 .success => |user_id| { 238 const token = try session_store.create(&user_id); 239 var cookie_buf: [256]u8 = undefined; 240 const cookie = try std.fmt.bufPrint(&cookie_buf, cookie_name ++ "={s}; Path=/; HttpOnly; SameSite=Strict", .{token}); 241 try request.respond("", .{ 242 .status = .see_other, 243 .extra_headers = &.{ 244 .{ .name = "location", .value = success_location }, 245 .{ .name = "set-cookie", .value = cookie }, 246 }, 247 }); 248 }, 249 .unknown_user => { 250 try request.respond("", .{ 251 .status = .see_other, 252 .extra_headers = &.{ 253 .{ .name = "location", .value = failure_location }, 254 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=unknown_user; Path=/; HttpOnly; SameSite=Strict" }, 255 }, 256 }); 257 }, 258 .wrong_password => { 259 try request.respond("", .{ 260 .status = .see_other, 261 .extra_headers = &.{ 262 .{ .name = "location", .value = failure_location }, 263 .{ .name = "set-cookie", .value = login_failure_cookie ++ "=wrong_password; Path=/; HttpOnly; SameSite=Strict" }, 264 }, 265 }); 266 }, 267 } 268 } 269 270 fn handleLogout(request: *std.http.Server.Request, base: []const u8, session_store: SessionStore) !void { 271 // revoke the session server-side so the cookie is dead for anyone holding 272 // a copy, not just this browser. 273 if (getCookieValue(request, cookie_name)) |token| session_store.remove(token); 274 // return to the page the logout came from (base, or "/" at the root). 275 const location: []const u8 = if (base.len == 0) "/" else base; 276 // close the connection instead of keeping it alive: we don't read the 277 // request body, and respond()'s keep-alive path would otherwise try to 278 // discard it — which asserts on a bodyless POST that carries no 279 // content-length, and would block on one with no framing at all. a logout 280 // is just a redirect, so the browser reconnects for the follow-up GET. 281 try request.respond("", .{ 282 .status = .see_other, 283 .keep_alive = false, 284 .extra_headers = &.{ 285 .{ .name = "location", .value = location }, 286 .{ .name = "set-cookie", .value = cookie_name ++ "=; Path=/; HttpOnly; SameSite=Strict; Max-Age=0" }, 287 }, 288 }); 289 } 290 291 fn handleAnsi( 292 io: std.Io, 293 request: *std.http.Server.Request, 294 allocator: std.mem.Allocator, 295 base: []const u8, 296 admin_repo_path: []const u8, 297 session_store: SessionStore, 298 ) !void { 299 var user_id: [evt.event_id_size]u8 = undefined; 300 if (getCookieValue(request, cookie_name)) |token| { 301 if (session_store.lookup(token, &user_id)) { 302 const Repo = rp.Repo(.xit, evt.admin_repo_opts); 303 var repo = try Repo.open(io, allocator, .{ .path = admin_repo_path }); 304 defer repo.deinit(io, allocator); 305 306 try evt.User.toggleAnsi(evt.admin_repo_opts, io, allocator, &repo, &user_id); 307 } 308 } 309 310 // return to the settings tab the toggle came from so the change is visible. 311 const location = try std.fmt.allocPrint(allocator, "{s}/settings", .{base}); 312 defer allocator.free(location); 313 314 // like logout, this is a bodyless POST, so close the connection rather than 315 // letting the keep-alive path try to discard a body that isn't framed. 316 try request.respond("", .{ 317 .status = .see_other, 318 .keep_alive = false, 319 .extra_headers = &.{ 320 .{ .name = "location", .value = location }, 321 }, 322 }); 323 } 324 325 fn renderIndexHtml( 326 io: std.Io, 327 allocator: std.mem.Allocator, 328 host: Host, 329 session_data: ui.Session.Data, 330 ) ![]const u8 { 331 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 332 333 var page_arena = std.heap.ArenaAllocator.init(allocator); 334 defer page_arena.deinit(); 335 336 // the remote admin repo must outlive the page build, since the session's 337 // moment reads from it. 338 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 339 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 340 341 var session = switch (host) { 342 .remote => |remote| blk: { 343 // open the admin repo to read live user/repo data. 344 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 345 const repo = if (repo_maybe) |*repo| repo else unreachable; 346 var session = try ui.Session.init(&page_arena, repo, session_data); 347 // give the page builders filesystem access to the on-disk repos (a 348 // sibling "repos" dir next to the admin repo) so the Repo page can 349 // read its files. 350 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 351 break :blk session; 352 }, 353 .local => |local| ui.Session{ 354 .data = session_data, 355 .arena = &page_arena, 356 .page_arena = &page_arena, 357 .local = local, 358 }, 359 }; 360 session.io = io; 361 362 const snapshot: ui.Snapshot = .{ 363 .page = try ui.Page.init(session.page_arena, &session, session.data.current_page), 364 .session = session.data, 365 }; 366 var root = try ui.initRoot(allocator, &snapshot.page, &session); 367 defer root.deinit(allocator); 368 369 const content = try generateHtml(allocator, &root); 370 defer allocator.free(content); 371 const overlay = try generateOverlay(allocator, &root, &session); 372 defer allocator.free(overlay); 373 374 // serialize the snapshot so the wasm side can parse it back without making 375 // a second request. it's embedded raw in a <script type="application/json"> 376 // block, whose content is raw text terminated only by "</script". in json, 377 // '<' appears solely inside string values, so escaping every '<' (and '>' 378 // for good measure) to its \uXXXX form yields equivalent json that can't 379 // break out of the tag. 380 var json: std.Io.Writer.Allocating = .init(allocator); 381 defer json.deinit(); 382 try std.json.Stringify.value(snapshot, .{}, &json.writer); 383 384 var json_escaped: std.ArrayList(u8) = .empty; 385 defer json_escaped.deinit(allocator); 386 for (json.written()) |c| switch (c) { 387 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 388 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 389 else => try json_escaped.append(allocator, c), 390 }; 391 392 var out: std.ArrayList(u8) = .empty; 393 errdefer out.deinit(allocator); 394 { 395 var cursor: usize = 0; 396 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 397 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 398 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 399 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 400 }) |sub| { 401 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 402 try out.appendSlice(allocator, template[cursor..idx]); 403 try out.appendSlice(allocator, sub.replacement); 404 cursor = idx + sub.needle.len; 405 } 406 try out.appendSlice(allocator, template[cursor..]); 407 } 408 return try out.toOwnedSlice(allocator); 409 } 410 411 fn findEmbed(request_path: []const u8) ?Embed { 412 const path = if (std.mem.eql(u8, request_path, "/")) 413 "index.html" 414 else if (request_path.len > 1 and request_path[0] == '/') 415 request_path[1..] 416 else 417 return null; 418 419 for (embeds) |embed| { 420 if (std.mem.eql(u8, path, embed.path)) return embed; 421 } 422 return null; 423 } 424 425 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 426 // own absolutely-positioned, natively-scrollable <div> holding its full content, 427 // rendered recursively so nested scrolls work. 428 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 429 const grid = root.getGrid() orelse return error.MissingGrid; 430 431 var out: std.ArrayList(u8) = .empty; 432 errdefer out.deinit(allocator); 433 434 try renderPanel(allocator, &out, root.getFocus(), grid); 435 return try out.toOwnedSlice(allocator); 436 } 437 438 // render one panel — a focus subtree and its content grid — as HTML, recursing 439 // once per web-native Scroll inside it. the root panel is the whole page; each 440 // Scroll becomes a nested, natively-scrollable div holding its full content. 441 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 442 // then the child scroll divs over those holes. 443 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 444 // `direct` is this panel's scroll children, each drawn as an overlaid div. 445 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 446 // plus their descendants, which the focus tree flattens into this panel's 447 // children): the cell hit-test below skips them so this panel doesn't claim 448 // cells that are really rendered inside a child scroll's own panel. 449 // (scrolls aren't nested in practice, so every scroll child is direct here.) 450 var direct: std.ArrayList(usize) = .empty; 451 defer direct.deinit(allocator); 452 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 453 defer excluded.deinit(allocator); 454 { 455 var it = focus.children.iterator(); 456 while (it.next()) |e| { 457 if (e.value_ptr.focus.scroll == null) continue; 458 try direct.append(allocator, e.key_ptr.*); 459 try excluded.put(allocator, e.key_ptr.*, {}); 460 var mit = e.value_ptr.focus.children.iterator(); 461 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 462 } 463 } 464 465 // the HTML element a run of cells is wrapped in, chosen from the cell's 466 // focusable kind 467 const CellTag = union(enum) { 468 span, // clickable focusable cell 469 a: []const u8, // clickable focusable link 470 plain, // non-focusable, colored 471 472 const a_prefix = "a:"; 473 // an "in-page" anchor: rendered as a real <a href> so it works with js 474 // disabled, but crossPageLink ignores it, so with wasm the click just 475 // moves focus rather than navigating. 476 const inpage_prefix = "ai:"; 477 478 fn init(str: []const u8) @This() { 479 if (std.mem.startsWith(u8, str, inpage_prefix)) { 480 return .{ .a = str[inpage_prefix.len..] }; 481 } 482 if (std.mem.startsWith(u8, str, a_prefix)) { 483 return .{ .a = str[a_prefix.len..] }; 484 } 485 return .span; 486 } 487 488 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 489 var id_buf: [32]u8 = undefined; 490 switch (self) { 491 .span => { 492 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 493 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 494 try out.appendSlice(alloc, "\""); 495 try out.appendSlice(alloc, style_attr); 496 try out.appendSlice(alloc, ">"); 497 }, 498 .a => |href| { 499 // tabindex=-1 keeps these out of the browser's tab order 500 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 501 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 502 try out.appendSlice(alloc, "\" href=\""); 503 try appendEscapedHtml(alloc, out, href); 504 try out.appendSlice(alloc, "\""); 505 try out.appendSlice(alloc, style_attr); 506 try out.appendSlice(alloc, ">"); 507 }, 508 .plain => { 509 try out.appendSlice(alloc, "<span"); 510 try out.appendSlice(alloc, style_attr); 511 try out.appendSlice(alloc, ">"); 512 }, 513 } 514 } 515 516 fn closeTag(self: @This()) []const u8 { 517 return switch (self) { 518 .span, .plain => "</span>", 519 .a => "</a>", 520 }; 521 } 522 }; 523 524 // emit this panel's grid as rows of text, coalescing adjacent cells that 525 // share a focus id and colors into one tag (a clickable span, a link, or a 526 // plain colored span). cells under a child scroll keep only their background. 527 for (0..grid.size.height) |y| { 528 var cur_id: ?usize = null; 529 var cur_fg: ?Grid.Color = null; 530 var cur_bg: ?Grid.Color = null; 531 var open_tag: ?CellTag = null; 532 var first = true; 533 for (0..grid.size.width) |x| { 534 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 535 // a cell covered by a child scroll's viewport is drawn by that scroll's 536 // own div, so blank its glyph and make it non-clickable here — but keep 537 // its background, so the backdrop still shows through the scroll's 538 // transparent div instead of a bare hole. 539 const covered_by_scroll = blk: { 540 for (direct.items) |id| { 541 const r = (focus.children.get(id) orelse continue).rect; 542 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; 543 } 544 break :blk false; 545 }; 546 // the focusable cell at (x, y) among this panel's own focusables (skipping 547 // any that belong to a child scroll, whose cells are drawn in their own 548 // panel); none for a covered cell. 549 const cell_id = if (covered_by_scroll) null else blk: { 550 var iter = focus.children.iterator(); 551 while (iter.next()) |entry| { 552 const child = entry.value_ptr.*; 553 if (!child.focus.focusable) continue; 554 if (excluded.contains(entry.key_ptr.*)) continue; 555 const r = child.rect; 556 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 557 break :blk entry.key_ptr.*; 558 } 559 } 560 break :blk null; 561 }; 562 const fg = if (covered_by_scroll) null else cell.style.fg; 563 const bg = cell.style.bg; 564 565 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 566 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 567 568 var new_tag: ?CellTag = null; 569 if (cell_id) |id| { 570 if (focus.children.get(id)) |child| { 571 new_tag = switch (child.focus.kind) { 572 .custom => |custom| CellTag.init(custom), 573 else => .span, 574 }; 575 } 576 } 577 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 578 579 if (new_tag) |t| { 580 var style_buf: [64]u8 = undefined; 581 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 582 } 583 584 open_tag = new_tag; 585 cur_id = cell_id; 586 cur_fg = fg; 587 cur_bg = bg; 588 first = false; 589 } 590 591 try appendEscapedHtml(allocator, output, if (covered_by_scroll) " " else (cell.rune orelse " ")); 592 } 593 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 594 try output.append(allocator, '\n'); 595 } 596 597 // each child scroll becomes a natively-scrollable div positioned over its 598 // viewport, holding its full content rendered recursively. 599 for (direct.items) |id| { 600 const child = focus.children.get(id) orelse continue; 601 const info = child.focus.scroll orelse continue; 602 const r = child.rect; 603 // overflow only on the axes the widget scrolls; `auto` shows a bar only 604 // when that axis actually overflows. the other axis is clipped (hidden), 605 // matching how the terminal Scroll handles its non-scrolling axis. 606 const overflow = switch (info.direction) { 607 .vert => "overflow-x:hidden;overflow-y:auto", 608 .horiz => "overflow-x:auto;overflow-y:hidden", 609 .both => "overflow:auto", 610 }; 611 // the id carries a content version so JS preserves the native scroll 612 // position across re-renders of the same content but resets it (to the 613 // top) when the content is replaced — e.g. selecting a different commit. 614 var buf: [160]u8 = undefined; 615 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 })); 616 try renderPanel(allocator, output, child.focus, info.content); 617 try output.appendSlice(allocator, "</div>"); 618 } 619 } 620 621 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 622 // widget tree, each wrapping the text inputs and submit button inside it, 623 // positioned absolutely over the matching grid cells. 624 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 625 const root_focus = root.getFocus(); 626 627 var out: std.ArrayList(u8) = .empty; 628 errdefer out.deinit(allocator); 629 630 const form_prefix = "form:"; 631 632 // Focus.children is an AutoArrayHashMap that preserves insertion order, 633 // which matches the order widgets were added in code 634 var iter = root_focus.children.iterator(); 635 while (iter.next()) |entry| { 636 const child = entry.value_ptr.*; 637 const action_url = switch (child.focus.kind) { 638 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 639 custom[form_prefix.len..] 640 else 641 continue, 642 else => continue, 643 }; 644 645 try out.appendSlice(allocator, "<form action=\""); 646 try appendEscapedHtml(allocator, &out, action_url); 647 try out.appendSlice(allocator, "\" method=\"post\""); 648 // an empty action must not POST — block it and send the input to the TUI instead 649 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 650 try out.appendSlice(allocator, ">"); 651 652 // form.focus.children was populated by addChild, which flattens the 653 // whole subtree into one map — so descendants (inputs + the submit 654 // button) all appear here. positions on form.focus are relative to 655 // the form, so we look up absolute rects via root_focus for layout. 656 var inner_iter = child.focus.children.iterator(); 657 while (inner_iter.next()) |inner_entry| { 658 const inner_id = inner_entry.key_ptr.*; 659 const root_child = root_focus.children.get(inner_id) orelse continue; 660 const r = root_child.rect; 661 switch (root_child.focus.kind) { 662 .text_input, .text_input_password => { 663 const ti = session.text_inputs.get(inner_id) orelse continue; 664 const inner_left = r.x + 1; 665 const inner_top = r.y + 1; 666 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 667 668 try out.appendSlice(allocator, "<input type=\""); 669 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 670 try out.appendSlice(allocator, "\" data-focus-id=\""); 671 var id_buf: [32]u8 = undefined; 672 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 673 if (ti.options.name.len > 0) { 674 try out.appendSlice(allocator, "\" name=\""); 675 try appendEscapedHtml(allocator, &out, ti.options.name); 676 } 677 // intentionally no `value` attribute: the browser tracks user input 678 // natively, and including the wasm-side value here would make the 679 // overlay HTML differ on every keystroke — that would trip the diff 680 // in _setOverlay and rebuild the <input>, eating the user's caret. 681 try out.appendSlice(allocator, "\" style=\"left:"); 682 var pos_buf: [64]u8 = undefined; 683 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 })); 684 try out.appendSlice(allocator, "\">"); 685 }, 686 .custom => |custom| { 687 if (std.mem.eql(u8, "submit", custom)) { 688 // inside the dashed border the TUI cells draw around the button. 689 const inner_left = r.x + 1; 690 const inner_top = r.y + 1; 691 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 692 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 693 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 694 var id_buf: [32]u8 = undefined; 695 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 696 try out.appendSlice(allocator, "\" style=\"left:"); 697 var pos_buf: [128]u8 = undefined; 698 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 })); 699 try out.appendSlice(allocator, "\"></button>"); 700 } 701 }, 702 else => {}, 703 } 704 } 705 706 try out.appendSlice(allocator, "</form>"); 707 } 708 709 return try out.toOwnedSlice(allocator); 710 } 711 712 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 713 if (a) |av| return if (b) |bv| av.eql(bv) else false; 714 return b == null; 715 } 716 717 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 718 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 719 // empty slice when neither is set. 720 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 721 if (fg == null and bg == null) return buf[0..0]; 722 const prefix = " style=\""; 723 @memcpy(buf[0..prefix.len], prefix); 724 var i: usize = prefix.len; 725 if (fg) |c| { 726 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]; 727 i += s.len; 728 } 729 if (bg) |c| { 730 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]; 731 i += s.len; 732 } 733 buf[i] = '"'; 734 i += 1; 735 return buf[0..i]; 736 } 737 738 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 739 for (input) |ch| { 740 switch (ch) { 741 '&' => try out.appendSlice(allocator, "&amp;"), 742 '<' => try out.appendSlice(allocator, "&lt;"), 743 '>' => try out.appendSlice(allocator, "&gt;"), 744 '"' => try out.appendSlice(allocator, "&quot;"), 745 '\'' => try out.appendSlice(allocator, "&#39;"), 746 else => try out.append(allocator, ch), 747 } 748 } 749 } 750 751 // --- helpers -------------------------------------------------------------- 752 753 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 754 var iter = request.iterateHeaders(); 755 while (iter.next()) |header| { 756 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 757 var pairs = std.mem.splitScalar(u8, header.value, ';'); 758 while (pairs.next()) |pair| { 759 const trimmed = std.mem.trim(u8, pair, " \t"); 760 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 761 if (std.mem.eql(u8, trimmed[0..eq], name)) { 762 return trimmed[eq + 1 ..]; 763 } 764 } 765 } 766 return null; 767 } 768 769 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 770 var iter = std.mem.splitScalar(u8, body, '&'); 771 while (iter.next()) |pair| { 772 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 773 if (std.mem.eql(u8, pair[0..eq], key)) { 774 return try decodeFormValue(allocator, pair[eq + 1 ..]); 775 } 776 } 777 return null; 778 } 779 780 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 781 var out: std.ArrayList(u8) = .empty; 782 errdefer out.deinit(allocator); 783 var i: usize = 0; 784 while (i < encoded.len) : (i += 1) { 785 switch (encoded[i]) { 786 '+' => try out.append(allocator, ' '), 787 '%' => { 788 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 789 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 790 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 791 try out.append(allocator, hi * 16 + lo); 792 i += 2; 793 }, 794 else => try out.append(allocator, encoded[i]), 795 } 796 } 797 return try out.toOwnedSlice(allocator); 798 } 799 800 // disk-backed web session store. each login mints a random, opaque token 801 // (not the user's id) that is stored as a file named by the token hex, whose 802 // contents are the raw user_id bytes. authenticating a request is a lookup of 803 // the cookie's token; logout deletes the file, revoking the session. there is 804 // deliberately no expiry — a session lives until logout. 805 pub const SessionStore = struct { 806 io: std.Io, 807 dir: std.Io.Dir, 808 809 pub const token_hex_len = evt.event_id_size * 2; 810 811 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 812 try data_dir.createDirPath(io, "sessions"); 813 const dir = try data_dir.openDir(io, "sessions", .{}); 814 return .{ .io = io, .dir = dir }; 815 } 816 817 pub fn deinit(self: SessionStore) void { 818 self.dir.close(self.io); 819 } 820 821 // mint a new session for user_id, returning the token hex to set as the 822 // cookie value. 823 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 824 var token: [evt.event_id_size]u8 = undefined; 825 self.io.random(&token); 826 const token_hex = std.fmt.bytesToHex(token, .lower); 827 const file = try self.dir.createFile(self.io, &token_hex, .{}); 828 defer file.close(self.io); 829 try file.writeStreamingAll(self.io, user_id); 830 return token_hex; 831 } 832 833 // resolve a cookie's token to its user_id. returns false (logged out) for a 834 // missing, malformed, or unknown token. 835 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 836 if (!isToken(token_hex)) return false; 837 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 838 defer file.close(self.io); 839 var storage: [evt.event_id_size]u8 = undefined; 840 var file_reader = file.reader(self.io, &storage); 841 file_reader.interface.readSliceAll(out) catch return false; 842 return true; 843 } 844 845 // revoke a session. a no-op for a missing or malformed token. 846 pub fn remove(self: SessionStore, token_hex: []const u8) void { 847 if (!isToken(token_hex)) return; 848 self.dir.deleteFile(self.io, token_hex) catch {}; 849 } 850 851 // a token is exactly token_hex_len hex chars. validating before using the 852 // value as a path keeps attacker-supplied cookies from escaping the 853 // sessions dir (e.g. via "/" or ".." bytes). 854 fn isToken(token_hex: []const u8) bool { 855 if (token_hex.len != token_hex_len) return false; 856 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 857 return true; 858 } 859 }; 860