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