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