╭ 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 var id_bytes: [evt.event_id_size]u8 = undefined; 581 io.random(&id_bytes); 582 const event_id_hex = std.fmt.bytesToHex(id_bytes, .lower); 583 const thread_id_hex = std.fmt.bytesToHex(parts.thread_id, .lower); 584 const parent_id_hex = std.fmt.bytesToHex(parts.parent_id, .lower); 585 const event = evt.EventWithId{ 586 .id = event_id_hex, 587 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 588 .author_email = author_email, 589 .event = .{ .comment = .{ 590 .thread_id = thread_id_hex, 591 .parent_id = parent_id_hex, 592 .body = body, 593 } }, 594 }; 595 596 switch (host) { 597 .remote => |remote| { 598 const repo_prefix = "/repo/"; 599 if (!std.mem.startsWith(u8, parts.repo_base, repo_prefix)) { 600 try request.respond(not_found, .{ 601 .status = .not_found, 602 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 603 }); 604 return; 605 } 606 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 607 defer allocator.free(repos_dir); 608 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, repos_dir, remote.admin_repo_path, parts.repo_base[repo_prefix.len..], false)) { 609 .ok => |p| p, 610 .invalid, .not_found => { 611 try request.respond(not_found, .{ 612 .status = .not_found, 613 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 614 }); 615 return; 616 }, 617 }; 618 defer allocator.free(repo_path); 619 620 var repo = try rp.Repo(.xit, .{}).open(io, allocator, .{ .path = repo_path }); 621 defer repo.deinit(io, allocator); 622 try evt.consume(.xit, .{}, io, allocator, &repo, evt.events_ref, &.{event}); 623 }, 624 .local => |src| { 625 if (parts.repo_base.len != 0) { 626 try request.respond(not_found, .{ 627 .status = .not_found, 628 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 629 }); 630 return; 631 } 632 switch (src.repo_kind) { 633 inline else => |repo_kind| { 634 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, .{ .path = src.path }); 635 defer any_repo.deinit(io, allocator); 636 switch (any_repo) { 637 inline else => |*repo| try evt.consume(repo_kind, repo.self_repo_opts, io, allocator, repo, evt.events_ref, &.{event}), 638 } 639 }, 640 } 641 }, 642 } 643 644 const location = try std.fmt.allocPrint(allocator, "{s}/issue:{s}/comment:{s}", .{ parts.repo_base, &thread_id_hex, &event_id_hex }); 645 defer allocator.free(location); 646 try request.respond("", .{ 647 .status = .see_other, 648 .extra_headers = &.{.{ .name = "location", .value = location }}, 649 }); 650 } 651 652 // split an issue url ("/repo/<owner>/<name>/issue:<id>", identity elided in 653 // local mode) into what precedes "/issue:" and the decoded id, null when it 654 // isn't one. the repo base is validated per host in updateIssue. 655 const IssueBaseParts = struct { repo_base: []const u8, id_bytes: [evt.event_id_size]u8 }; 656 fn issueBaseParts(base: []const u8) ?IssueBaseParts { 657 const issues_infix = "/issue:"; 658 const id_len = evt.event_id_size * 2; 659 if (base.len < issues_infix.len + id_len) return null; 660 var id_bytes: [evt.event_id_size]u8 = undefined; 661 _ = std.fmt.hexToBytes(&id_bytes, base[base.len - id_len ..]) catch return null; 662 const head = base[0 .. base.len - id_len]; 663 if (!std.mem.endsWith(u8, head, issues_infix)) return null; 664 return .{ .repo_base = head[0 .. head.len - issues_infix.len], .id_bytes = id_bytes }; 665 } 666 667 // re-emit the issue `parts` names with `update` applied, in the repo the 668 // host resolves the base to. error.NotFound when the base names no repo or 669 // the id no issue. 670 fn updateIssue( 671 io: std.Io, 672 allocator: std.mem.Allocator, 673 host: Host, 674 parts: IssueBaseParts, 675 update: evt.Issue.Update, 676 author_email: []const u8, 677 ) !void { 678 switch (host) { 679 .remote => |remote| { 680 const repo_prefix = "/repo/"; 681 if (!std.mem.startsWith(u8, parts.repo_base, repo_prefix)) return error.NotFound; 682 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 683 defer allocator.free(repos_dir); 684 const repo_path = switch (try serve_common.resolveRepoPath(io, allocator, repos_dir, remote.admin_repo_path, parts.repo_base[repo_prefix.len..], false)) { 685 .ok => |p| p, 686 .invalid, .not_found => return error.NotFound, 687 }; 688 defer allocator.free(repo_path); 689 690 var repo = try rp.Repo(.xit, .{}).open(io, allocator, .{ .path = repo_path }); 691 defer repo.deinit(io, allocator); 692 try evt.Issue.update(.xit, .{}, io, allocator, &repo, &parts.id_bytes, update, author_email); 693 }, 694 .local => |src| { 695 // the local forms post to "/issue:<id>/...", so the repo base 696 // is empty 697 if (parts.repo_base.len != 0) return error.NotFound; 698 switch (src.repo_kind) { 699 inline else => |repo_kind| { 700 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, .{ .path = src.path }); 701 defer any_repo.deinit(io, allocator); 702 switch (any_repo) { 703 inline else => |*repo| try evt.Issue.update(repo_kind, repo.self_repo_opts, io, allocator, repo, &parts.id_bytes, update, author_email), 704 } 705 }, 706 } 707 }, 708 } 709 } 710 711 // set the status of the issue the url names (base is 712 // "/repo/<owner>/<name>/issue:<id>", identity elided in local mode) by 713 // re-emitting its event, then redirect back to it 714 fn handleIssueStatus( 715 io: std.Io, 716 request: *std.http.Server.Request, 717 allocator: std.mem.Allocator, 718 base: []const u8, 719 host: Host, 720 status: evt.Issue.Status, 721 ) !void { 722 const not_found = "issue not found"; 723 const parts = issueBaseParts(base) orelse { 724 try request.respond(not_found, .{ 725 .status = .not_found, 726 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 727 }); 728 return; 729 }; 730 731 var author_arena = std.heap.ArenaAllocator.init(allocator); 732 defer author_arena.deinit(); 733 const author_email = (try eventAuthorEmail(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 734 735 updateIssue(io, allocator, host, parts, .{ .status = status }, author_email) catch |err| switch (err) { 736 error.NotFound => { 737 try request.respond(not_found, .{ 738 .status = .not_found, 739 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 740 }); 741 return; 742 }, 743 else => |e| return e, 744 }; 745 746 // like logout, this is a bodyless POST, so close the connection rather than 747 // letting the keep-alive path try to discard a body that isn't framed. 748 try request.respond("", .{ 749 .status = .see_other, 750 .keep_alive = false, 751 .extra_headers = &.{.{ .name = "location", .value = base }}, 752 }); 753 } 754 755 // replace the title/tags/description of the issue the url names (base is 756 // "/repo/<owner>/<name>/issue:<id>", identity elided in local mode; the 757 // form posts to "<base>/edit") by re-emitting its event with its status 758 // preserved, then redirect back to it 759 fn handleIssueEdit( 760 io: std.Io, 761 request: *std.http.Server.Request, 762 allocator: std.mem.Allocator, 763 base: []const u8, 764 host: Host, 765 ) !void { 766 var author_arena = std.heap.ArenaAllocator.init(allocator); 767 defer author_arena.deinit(); 768 const author_email = (try eventAuthorEmail(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 769 770 var body_buf: [256]u8 = undefined; 771 const reader = request.readerExpectNone(&body_buf); 772 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 773 defer allocator.free(body); 774 775 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 776 defer allocator.free(title); 777 const tags = (try parseFormField(allocator, body, "tags")) orelse try allocator.dupe(u8, ""); 778 defer allocator.free(tags); 779 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 780 defer allocator.free(description_crlf); 781 // form submission normalizes textarea line breaks to CRLF; store plain 782 // newlines so the text renders the same on every host 783 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 784 defer allocator.free(description); 785 786 // invalid fields send the user back to the edit form 787 if (!evt.Issue.fieldsValid(title, tags)) { 788 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 789 defer allocator.free(form_location); 790 try request.respond("", .{ 791 .status = .see_other, 792 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 793 }); 794 return; 795 } 796 797 const not_found = "issue not found"; 798 const parts = issueBaseParts(base) orelse { 799 try request.respond(not_found, .{ 800 .status = .not_found, 801 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 802 }); 803 return; 804 }; 805 806 updateIssue(io, allocator, host, parts, .{ .fields = .{ 807 .title = title, 808 .tags = tags, 809 .description = description, 810 } }, author_email) catch |err| switch (err) { 811 error.NotFound => { 812 try request.respond(not_found, .{ 813 .status = .not_found, 814 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 815 }); 816 return; 817 }, 818 else => |e| return e, 819 }; 820 821 try request.respond("", .{ 822 .status = .see_other, 823 .extra_headers = &.{.{ .name = "location", .value = base }}, 824 }); 825 } 826 827 // resolve the conflict of the issue the url names (base is 828 // "/repo/<owner>/<name>/issue:<id>", identity elided in local mode; the 829 // form posts to "<base>/resolve") 830 fn handleIssueResolve( 831 io: std.Io, 832 request: *std.http.Server.Request, 833 allocator: std.mem.Allocator, 834 base: []const u8, 835 host: Host, 836 ) !void { 837 var author_arena = std.heap.ArenaAllocator.init(allocator); 838 defer author_arena.deinit(); 839 const author_email = (try eventAuthorEmail(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 840 841 var body_buf: [256]u8 = undefined; 842 const reader = request.readerExpectNone(&body_buf); 843 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 844 defer allocator.free(body); 845 846 var field_arena = std.heap.ArenaAllocator.init(allocator); 847 defer field_arena.deinit(); 848 const aa = field_arena.allocator(); 849 const title = try parseFormField(aa, body, "title"); 850 const tags = try parseFormField(aa, body, "tags"); 851 852 // the hunk inputs post as d0, d1, ...; form submission normalizes their 853 // textarea line breaks to CRLF 854 var hunks: std.ArrayList([]const u8) = .empty; 855 var hunk_index: usize = 0; 856 while (true) : (hunk_index += 1) { 857 const name = try std.fmt.allocPrint(aa, "d{d}", .{hunk_index}); 858 const posted = (try parseFormField(aa, body, name)) orelse break; 859 try hunks.append(aa, try std.mem.replaceOwned(u8, aa, posted, "\r\n", "\n")); 860 } 861 862 const not_found = "issue not found"; 863 const parts = issueBaseParts(base) orelse { 864 try request.respond(not_found, .{ 865 .status = .not_found, 866 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 867 }); 868 return; 869 }; 870 871 updateIssue(io, allocator, host, parts, .{ .resolve = .{ 872 .title = title, 873 .tags = tags, 874 .hunks = hunks.items, 875 } }, author_email) catch |err| switch (err) { 876 error.NotFound => { 877 try request.respond(not_found, .{ 878 .status = .not_found, 879 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 880 }); 881 return; 882 }, 883 // invalid fields send the user back to the resolve form 884 error.InvalidFields => { 885 const form_location = try std.fmt.allocPrint(allocator, "{s}/resolve", .{base}); 886 defer allocator.free(form_location); 887 try request.respond("", .{ 888 .status = .see_other, 889 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 890 }); 891 return; 892 }, 893 else => |e| return e, 894 }; 895 896 try request.respond("", .{ 897 .status = .see_other, 898 .extra_headers = &.{.{ .name = "location", .value = base }}, 899 }); 900 } 901 902 fn renderIndexHtml( 903 io: std.Io, 904 allocator: std.mem.Allocator, 905 host: Host, 906 session_data: ui.Session.Data, 907 ) ![]const u8 { 908 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 909 910 var page_arena = std.heap.ArenaAllocator.init(allocator); 911 defer page_arena.deinit(); 912 913 // the remote admin repo must outlive the page build, since the session's 914 // moment reads from it. 915 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 916 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 917 918 var session = switch (host) { 919 .remote => |remote| blk: { 920 // open the admin repo to read live user/repo data. 921 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 922 const repo = if (repo_maybe) |*repo| repo else unreachable; 923 var session = try ui.Session.init(&page_arena, repo, session_data); 924 // give the page builders filesystem access to the on-disk repos (a 925 // sibling "repos" dir next to the admin repo) so the Repo page can 926 // read its files. 927 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 928 break :blk session; 929 }, 930 .local => |local| ui.Session{ 931 .data = session_data, 932 .arena = &page_arena, 933 .page_arena = &page_arena, 934 .local = local, 935 }, 936 }; 937 session.io = io; 938 939 const snapshot: ui.Snapshot = .{ 940 .page = try ui.Page.init(session.page_arena, &session, session.data.current_page), 941 .session = session.data, 942 }; 943 var root = try ui.initRoot(allocator, &snapshot.page, &session); 944 defer root.deinit(allocator); 945 946 const content = try generateHtml(allocator, &root); 947 defer allocator.free(content); 948 const overlay = try generateOverlay(allocator, &root, &session); 949 defer allocator.free(overlay); 950 951 // serialize the snapshot so the wasm side can parse it back without making 952 // a second request. it's embedded raw in a <script type="application/json"> 953 // block, whose content is raw text terminated only by "</script". in json, 954 // '<' appears solely inside string values, so escaping every '<' (and '>' 955 // for good measure) to its \uXXXX form yields equivalent json that can't 956 // break out of the tag. 957 var json: std.Io.Writer.Allocating = .init(allocator); 958 defer json.deinit(); 959 try std.json.Stringify.value(snapshot, .{}, &json.writer); 960 961 var json_escaped: std.ArrayList(u8) = .empty; 962 defer json_escaped.deinit(allocator); 963 for (json.written()) |c| switch (c) { 964 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 965 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 966 else => try json_escaped.append(allocator, c), 967 }; 968 969 var out: std.ArrayList(u8) = .empty; 970 errdefer out.deinit(allocator); 971 { 972 var cursor: usize = 0; 973 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 974 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 975 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 976 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 977 }) |sub| { 978 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 979 try out.appendSlice(allocator, template[cursor..idx]); 980 try out.appendSlice(allocator, sub.replacement); 981 cursor = idx + sub.needle.len; 982 } 983 try out.appendSlice(allocator, template[cursor..]); 984 } 985 return try out.toOwnedSlice(allocator); 986 } 987 988 fn findEmbed(request_path: []const u8) ?Embed { 989 const path = if (std.mem.eql(u8, request_path, "/")) 990 "index.html" 991 else if (request_path.len > 1 and request_path[0] == '/') 992 request_path[1..] 993 else 994 return null; 995 996 for (embeds) |embed| { 997 if (std.mem.eql(u8, path, embed.path)) return embed; 998 } 999 return null; 1000 } 1001 1002 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 1003 // own absolutely-positioned, natively-scrollable <div> holding its full content, 1004 // rendered recursively so nested scrolls work. 1005 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 1006 const grid = root.getGrid() orelse return error.MissingGrid; 1007 1008 var out: std.ArrayList(u8) = .empty; 1009 errdefer out.deinit(allocator); 1010 1011 try renderPanel(allocator, &out, root.getFocus(), grid); 1012 return try out.toOwnedSlice(allocator); 1013 } 1014 1015 // render one panel — a focus subtree and its content grid — as HTML, recursing 1016 // once per web-native Scroll inside it. the root panel is the whole page; each 1017 // Scroll becomes a nested, natively-scrollable div holding its full content. 1018 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 1019 // then the child scroll divs over those holes. 1020 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 1021 // `direct` is this panel's scroll children, each drawn as an overlaid div. 1022 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 1023 // plus their descendants, which the focus tree flattens into this panel's 1024 // children): the cell hit-test below skips them so this panel doesn't claim 1025 // cells that are really rendered inside a child scroll's own panel. 1026 // (scrolls aren't nested in practice, so every scroll child is direct here.) 1027 var direct: std.ArrayList(usize) = .empty; 1028 defer direct.deinit(allocator); 1029 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 1030 defer excluded.deinit(allocator); 1031 { 1032 var it = focus.children.iterator(); 1033 while (it.next()) |e| { 1034 if (e.value_ptr.focus.scroll == null) continue; 1035 try direct.append(allocator, e.key_ptr.*); 1036 try excluded.put(allocator, e.key_ptr.*, {}); 1037 var mit = e.value_ptr.focus.children.iterator(); 1038 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 1039 } 1040 } 1041 1042 // the HTML element a run of cells is wrapped in, chosen from the cell's 1043 // focusable kind 1044 const CellTag = union(enum) { 1045 span, // clickable focusable cell 1046 a: []const u8, // clickable focusable link 1047 plain, // non-focusable, colored 1048 1049 const a_prefix = "a:"; 1050 // an "in-page" anchor: rendered as a real <a href> so it works with js 1051 // disabled, but crossPageLink ignores it, so with wasm the click just 1052 // moves focus rather than navigating. 1053 const inpage_prefix = "ai:"; 1054 1055 fn init(str: []const u8) @This() { 1056 if (std.mem.startsWith(u8, str, inpage_prefix)) { 1057 return .{ .a = str[inpage_prefix.len..] }; 1058 } 1059 if (std.mem.startsWith(u8, str, a_prefix)) { 1060 return .{ .a = str[a_prefix.len..] }; 1061 } 1062 return .span; 1063 } 1064 1065 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 1066 var id_buf: [32]u8 = undefined; 1067 switch (self) { 1068 .span => { 1069 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 1070 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1071 try out.appendSlice(alloc, "\""); 1072 try out.appendSlice(alloc, style_attr); 1073 try out.appendSlice(alloc, ">"); 1074 }, 1075 .a => |href| { 1076 // tabindex=-1 keeps these out of the browser's tab order 1077 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 1078 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1079 try out.appendSlice(alloc, "\" href=\""); 1080 try appendEscapedHtml(alloc, out, href); 1081 try out.appendSlice(alloc, "\""); 1082 try out.appendSlice(alloc, style_attr); 1083 try out.appendSlice(alloc, ">"); 1084 }, 1085 .plain => { 1086 try out.appendSlice(alloc, "<span"); 1087 try out.appendSlice(alloc, style_attr); 1088 try out.appendSlice(alloc, ">"); 1089 }, 1090 } 1091 } 1092 1093 fn closeTag(self: @This()) []const u8 { 1094 return switch (self) { 1095 .span, .plain => "</span>", 1096 .a => "</a>", 1097 }; 1098 } 1099 }; 1100 1101 // emit this panel's grid as rows of text, coalescing adjacent cells that 1102 // share a focus id and colors into one tag (a clickable span, a link, or a 1103 // plain colored span). cells under a child scroll keep only their background. 1104 for (0..grid.size.height) |y| { 1105 var cur_id: ?usize = null; 1106 var cur_fg: ?Grid.Color = null; 1107 var cur_bg: ?Grid.Color = null; 1108 var open_tag: ?CellTag = null; 1109 var first = true; 1110 for (0..grid.size.width) |x| { 1111 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 1112 // a cell covered by a child scroll's viewport is drawn by that scroll's 1113 // own div, so blank its glyph and make it non-clickable here — but keep 1114 // its background, so the backdrop still shows through the scroll's 1115 // transparent div instead of a bare hole. 1116 const covered_by_scroll = blk: { 1117 for (direct.items) |id| { 1118 const r = (focus.children.get(id) orelse continue).rect; 1119 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; 1120 } 1121 break :blk false; 1122 }; 1123 // the focusable cell at (x, y) among this panel's own focusables (skipping 1124 // any that belong to a child scroll, whose cells are drawn in their own 1125 // panel); none for a covered cell. 1126 const cell_id = if (covered_by_scroll) null else blk: { 1127 var iter = focus.children.iterator(); 1128 while (iter.next()) |entry| { 1129 const child = entry.value_ptr.*; 1130 if (!child.focus.focusable) continue; 1131 if (excluded.contains(entry.key_ptr.*)) continue; 1132 const r = child.rect; 1133 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 1134 break :blk entry.key_ptr.*; 1135 } 1136 } 1137 break :blk null; 1138 }; 1139 const fg = if (covered_by_scroll) null else cell.style.fg; 1140 const bg = cell.style.bg; 1141 1142 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 1143 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1144 1145 var new_tag: ?CellTag = null; 1146 if (cell_id) |id| { 1147 if (focus.children.get(id)) |child| { 1148 new_tag = switch (child.focus.kind) { 1149 .custom => |custom| CellTag.init(custom), 1150 else => .span, 1151 }; 1152 } 1153 } 1154 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 1155 1156 if (new_tag) |t| { 1157 var style_buf: [64]u8 = undefined; 1158 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 1159 } 1160 1161 open_tag = new_tag; 1162 cur_id = cell_id; 1163 cur_fg = fg; 1164 cur_bg = bg; 1165 first = false; 1166 } 1167 1168 if (covered_by_scroll) { 1169 try appendEscapedHtml(allocator, output, " "); 1170 } else if (cell.continuation) { 1171 // the wide rune to the left was emitted 2ch wide, covering this column 1172 } else if (cell.rune) |rune| { 1173 // a double-width rune is pinned inside a 2ch span so the 1174 // fallback glyph's advance width can't shift the rest of the row 1175 const wide = x + 1 < grid.size.width and grid.cells.items[try grid.cells.at(.{ y, x + 1 })].continuation; 1176 if (wide) { 1177 try output.appendSlice(allocator, "<span class=\"w2\">"); 1178 try appendEscapedHtml(allocator, output, rune); 1179 try output.appendSlice(allocator, "</span>"); 1180 } else { 1181 try appendEscapedHtml(allocator, output, rune); 1182 } 1183 } else { 1184 try appendEscapedHtml(allocator, output, " "); 1185 } 1186 } 1187 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1188 try output.append(allocator, '\n'); 1189 } 1190 1191 // each child scroll becomes a natively-scrollable div positioned over its 1192 // viewport, holding its full content rendered recursively. 1193 for (direct.items) |id| { 1194 const child = focus.children.get(id) orelse continue; 1195 const info = child.focus.scroll orelse continue; 1196 const r = child.rect; 1197 // overflow only on the axes the widget scrolls; `auto` shows a bar only 1198 // when that axis actually overflows. the other axis is clipped (hidden), 1199 // matching how the terminal Scroll handles its non-scrolling axis. 1200 const overflow = switch (info.direction) { 1201 .vert => "overflow-x:hidden;overflow-y:auto", 1202 .horiz => "overflow-x:auto;overflow-y:hidden", 1203 .both => "overflow:auto", 1204 }; 1205 // the id carries a content version so JS preserves the native scroll 1206 // position across re-renders of the same content but resets it when the 1207 // content is replaced — e.g. selecting a different commit. the widget's 1208 // scroll offset (in cells) rides along so JS can apply it when it has no 1209 // preserved position, letting a wasm-side scrollToRect (the files list 1210 // scrolling to its selected row on page load) reach the browser. 1211 var buf: [224]u8 = undefined; 1212 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 })); 1213 try renderPanel(allocator, output, child.focus, info.content); 1214 try output.appendSlice(allocator, "</div>"); 1215 } 1216 } 1217 1218 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 1219 // widget tree, each wrapping the text inputs and submit button inside it, 1220 // positioned absolutely over the matching grid cells. 1221 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1222 const root_focus = root.getFocus(); 1223 1224 var out: std.ArrayList(u8) = .empty; 1225 errdefer out.deinit(allocator); 1226 1227 const form_prefix = "form:"; 1228 1229 // Focus.children is an AutoArrayHashMap that preserves insertion order, 1230 // which matches the order widgets were added in code 1231 var iter = root_focus.children.iterator(); 1232 while (iter.next()) |entry| { 1233 const child = entry.value_ptr.*; 1234 const action_url = switch (child.focus.kind) { 1235 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 1236 custom[form_prefix.len..] 1237 else 1238 continue, 1239 else => continue, 1240 }; 1241 1242 try out.appendSlice(allocator, "<form action=\""); 1243 try appendEscapedHtml(allocator, &out, action_url); 1244 try out.appendSlice(allocator, "\" method=\"post\""); 1245 // an empty action must not POST — block it and send the input to the TUI instead 1246 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 1247 try out.appendSlice(allocator, ">"); 1248 1249 // form.focus.children was populated by addChild, which flattens the 1250 // whole subtree into one map — so descendants (inputs + the submit 1251 // button) all appear here. positions on form.focus are relative to 1252 // the form, so we look up absolute rects via root_focus for layout. 1253 var inner_iter = child.focus.children.iterator(); 1254 while (inner_iter.next()) |inner_entry| { 1255 const inner_id = inner_entry.key_ptr.*; 1256 const root_child = root_focus.children.get(inner_id) orelse continue; 1257 const r = root_child.rect; 1258 switch (root_child.focus.kind) { 1259 .text_input, .text_input_password => { 1260 const ti = session.text_inputs.get(inner_id) orelse continue; 1261 const inner_left = r.x + 1; 1262 const inner_top = r.y + 1; 1263 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1264 1265 try out.appendSlice(allocator, "<input type=\""); 1266 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 1267 try out.appendSlice(allocator, "\" data-focus-id=\""); 1268 var id_buf: [32]u8 = undefined; 1269 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1270 if (ti.options.name.len > 0) { 1271 try out.appendSlice(allocator, "\" name=\""); 1272 try appendEscapedHtml(allocator, &out, ti.options.name); 1273 } 1274 // never the live content as the `value`: the browser tracks user 1275 // input natively, and including the wasm-side value here would make 1276 // the overlay HTML differ on every keystroke — that would trip the 1277 // diff in _setOverlay and rebuild the <input>, eating the user's 1278 // caret. a page-constant initial value is safe. 1279 if (session.input_values.get(inner_id)) |value| { 1280 try out.appendSlice(allocator, "\" value=\""); 1281 try appendEscapedHtml(allocator, &out, value); 1282 } 1283 try out.appendSlice(allocator, "\" style=\"left:"); 1284 var pos_buf: [64]u8 = undefined; 1285 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 })); 1286 try out.appendSlice(allocator, "\">"); 1287 }, 1288 .text_area => { 1289 const ti = session.text_inputs.get(inner_id) orelse continue; 1290 const inner_left = r.x + 1; 1291 const inner_top = r.y + 1; 1292 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1293 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 1294 1295 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 1296 var id_buf: [32]u8 = undefined; 1297 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1298 if (ti.options.name.len > 0) { 1299 try out.appendSlice(allocator, "\" name=\""); 1300 try appendEscapedHtml(allocator, &out, ti.options.name); 1301 } 1302 // like the input above, only a page-constant initial value 1303 // inside: the browser tracks the live value and the 1304 // overlay diff must stay stable across keystrokes 1305 try out.appendSlice(allocator, "\" style=\"left:"); 1306 var pos_buf: [128]u8 = undefined; 1307 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 })); 1308 // textarea discards the first newline immediately following 1309 // its start tag, so add one of our own so text that begins 1310 // with a newline doesn't lose it 1311 try out.appendSlice(allocator, "\">\n"); 1312 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1313 try out.appendSlice(allocator, "</textarea>"); 1314 }, 1315 .custom => |custom| { 1316 if (std.mem.eql(u8, "submit", custom)) { 1317 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1318 var id_buf: [32]u8 = undefined; 1319 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1320 try out.appendSlice(allocator, "\" style=\"left:"); 1321 var pos_buf: [128]u8 = undefined; 1322 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 })); 1323 try out.appendSlice(allocator, "\"></button>"); 1324 } 1325 }, 1326 else => {}, 1327 } 1328 } 1329 1330 try out.appendSlice(allocator, "</form>"); 1331 } 1332 1333 return try out.toOwnedSlice(allocator); 1334 } 1335 1336 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1337 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1338 return b == null; 1339 } 1340 1341 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1342 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1343 // empty slice when neither is set. 1344 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1345 if (fg == null and bg == null) return buf[0..0]; 1346 const prefix = " style=\""; 1347 @memcpy(buf[0..prefix.len], prefix); 1348 var i: usize = prefix.len; 1349 if (fg) |c| { 1350 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]; 1351 i += s.len; 1352 } 1353 if (bg) |c| { 1354 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]; 1355 i += s.len; 1356 } 1357 buf[i] = '"'; 1358 i += 1; 1359 return buf[0..i]; 1360 } 1361 1362 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1363 for (input) |ch| { 1364 switch (ch) { 1365 '&' => try out.appendSlice(allocator, "&amp;"), 1366 '<' => try out.appendSlice(allocator, "&lt;"), 1367 '>' => try out.appendSlice(allocator, "&gt;"), 1368 '"' => try out.appendSlice(allocator, "&quot;"), 1369 '\'' => try out.appendSlice(allocator, "&#39;"), 1370 else => try out.append(allocator, ch), 1371 } 1372 } 1373 } 1374 1375 // --- helpers -------------------------------------------------------------- 1376 1377 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1378 var iter = request.iterateHeaders(); 1379 while (iter.next()) |header| { 1380 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1381 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1382 while (pairs.next()) |pair| { 1383 const trimmed = std.mem.trim(u8, pair, " \t"); 1384 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1385 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1386 return trimmed[eq + 1 ..]; 1387 } 1388 } 1389 } 1390 return null; 1391 } 1392 1393 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1394 var iter = std.mem.splitScalar(u8, body, '&'); 1395 while (iter.next()) |pair| { 1396 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1397 if (std.mem.eql(u8, pair[0..eq], key)) { 1398 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1399 } 1400 } 1401 return null; 1402 } 1403 1404 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1405 var out: std.ArrayList(u8) = .empty; 1406 errdefer out.deinit(allocator); 1407 var i: usize = 0; 1408 while (i < encoded.len) : (i += 1) { 1409 switch (encoded[i]) { 1410 '+' => try out.append(allocator, ' '), 1411 '%' => { 1412 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1413 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1414 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1415 try out.append(allocator, hi * 16 + lo); 1416 i += 2; 1417 }, 1418 else => try out.append(allocator, encoded[i]), 1419 } 1420 } 1421 return try out.toOwnedSlice(allocator); 1422 } 1423 1424 // disk-backed web session store. each login mints a random, opaque token 1425 // (not the user's id) that is stored as a file named by the token hex, whose 1426 // contents are the raw user_id bytes. authenticating a request is a lookup of 1427 // the cookie's token; logout deletes the file, revoking the session. there is 1428 // deliberately no expiry — a session lives until logout. 1429 pub const SessionStore = struct { 1430 io: std.Io, 1431 dir: std.Io.Dir, 1432 1433 pub const token_hex_len = evt.event_id_size * 2; 1434 1435 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1436 try data_dir.createDirPath(io, "sessions"); 1437 const dir = try data_dir.openDir(io, "sessions", .{}); 1438 return .{ .io = io, .dir = dir }; 1439 } 1440 1441 pub fn deinit(self: SessionStore) void { 1442 self.dir.close(self.io); 1443 } 1444 1445 // mint a new session for user_id, returning the token hex to set as the 1446 // cookie value. 1447 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1448 var token: [evt.event_id_size]u8 = undefined; 1449 self.io.random(&token); 1450 const token_hex = std.fmt.bytesToHex(token, .lower); 1451 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1452 defer file.close(self.io); 1453 try file.writeStreamingAll(self.io, user_id); 1454 return token_hex; 1455 } 1456 1457 // resolve a cookie's token to its user_id. returns false (logged out) for a 1458 // missing, malformed, or unknown token. 1459 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1460 if (!isToken(token_hex)) return false; 1461 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1462 defer file.close(self.io); 1463 var storage: [evt.event_id_size]u8 = undefined; 1464 var file_reader = file.reader(self.io, &storage); 1465 file_reader.interface.readSliceAll(out) catch return false; 1466 return true; 1467 } 1468 1469 // revoke a session. a no-op for a missing or malformed token. 1470 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1471 if (!isToken(token_hex)) return; 1472 self.dir.deleteFile(self.io, token_hex) catch {}; 1473 } 1474 1475 // leave `token_hex`'s session for the next visitor arriving without one. 1476 // only the `try` fixture writes one, and only a debug build honors it. the 1477 // name isn't token-shaped, so it can't collide with a session file. 1478 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 1479 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 1480 defer file.close(self.io); 1481 try file.writeStreamingAll(self.io, token_hex); 1482 } 1483 1484 // claim the offered session, if one is there. the delete picks the winner 1485 // of a race, so the offer is only ever taken once. a release build never 1486 // looks, because that would be an extra syscall for every GET request. 1487 pub fn claimAutoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 1488 if (builtin.mode != .Debug) return false; 1489 { 1490 const file = self.dir.openFile(self.io, auto_login_name, .{ .mode = .read_only }) catch return false; 1491 defer file.close(self.io); 1492 var storage: [token_hex_len]u8 = undefined; 1493 var file_reader = file.reader(self.io, &storage); 1494 file_reader.interface.readSliceAll(out) catch return false; 1495 } 1496 self.dir.deleteFile(self.io, auto_login_name) catch return false; 1497 return true; 1498 } 1499 1500 const auto_login_name = "auto-login"; 1501 1502 // a token is exactly token_hex_len hex chars. validating before using the 1503 // value as a path keeps attacker-supplied cookies from escaping the 1504 // sessions dir (e.g. via "/" or ".." bytes). 1505 fn isToken(token_hex: []const u8) bool { 1506 if (token_hex.len != token_hex_len) return false; 1507 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1508 return true; 1509 } 1510 }; 1511