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