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