╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─╯
1979 }); 1980 return; 1981 }, 1982 else => |e| return e, 1983 }; 1984 1985 // like logout, this is a bodyless POST, so close the connection rather than 1986 // letting the keep-alive path try to discard a body that isn't framed. 1987 try request.respond("", .{ 1988 .status = .see_other, 1989 .keep_alive = false, 1990 .extra_headers = &.{.{ .name = "location", .value = base }}, 1991 }); 1992 } 1993 1994 // replace a thread's editable fields. 1995 fn handleThreadEdit( 1996 io: std.Io, 1997 request: *std.http.Server.Request, 1998 allocator: std.mem.Allocator, 1999 base: []const u8, 2000 host: Host, 2001 parts: CommentBaseParts, 2002 ) !void { 2003 var author_arena = std.heap.ArenaAllocator.init(allocator); 2004 defer author_arena.deinit(); 2005 const actor = (try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .read, parts.thread_kind)) orelse return; 2006 const author = actor.author; 2007 2008 const body = try readFormBody(request, allocator); 2009 defer allocator.free(body); 2010 2011 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 2012 defer allocator.free(title); 2013 const labels = (try parseFormField(allocator, body, "labels")) orelse try allocator.dupe(u8, ""); 2014 defer allocator.free(labels); 2015 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 2016 defer allocator.free(description_crlf); 2017 // form submission normalizes textarea line breaks to CRLF; store plain 2018 // newlines so the text renders the same on every host 2019 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 2020 defer allocator.free(description); 2021 const target_branch = (try parseFormField(allocator, body, "target_branch")) orelse try allocator.dupe(u8, ""); 2022 defer allocator.free(target_branch); 2023 2024 // invalid fields send the user back to the edit form 2025 const valid = switch (parts.thread_kind) { 2026 .issue => evt.Issue.fieldsValid(title, labels), 2027 .patch => evt.Patch.fieldsValid(title, labels), 2028 .discuss => evt.Discussion.fieldsValid(title, labels), 2029 else => unreachable, 2030 }; 2031 if (!valid) { 2032 const form_location = try allocator.print("{s}/edit", .{base}); 2033 defer allocator.free(form_location); 2034 if (!evt.titleValid(title)) { 2035 return respondThreadFormFailure(request, allocator, host, form_location, requiredTitleFeedback(parts.thread_kind, title, labels, description, target_branch, null)); 2036 } 2037 try request.respond("", .{ 2038 .status = .see_other, 2039 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 2040 }); 2041 return; 2042 } 2043 2044 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 2045 defer request_repo.deinit(allocator); 2046 2047 const draft_user_id = if (parts.thread_kind == .patch) actor.user_id else null; 2048 if (draft_user_id) |user_id| { 2049 const server = switch (host) { 2050 .server => |server| server, 2051 .local => unreachable, 2052 }; 2053 if (!evt.Patch.branchValid(target_branch) or !try request_repo.source.hasBranch(io, allocator, target_branch)) { 2054 const form_location = try allocator.print("{s}/edit", .{base}); 2055 defer allocator.free(form_location); 2056 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(.invalid_target_branch, title, labels, description, target_branch, null)); 2057 } 2058 const repo_id = evt.parseEventId(std.Io.Dir.path.basename(request_repo.source.path)) catch return respondRemoveNotFound(request); 2059 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 2060 defer admin_repo.deinit(io, allocator); 2061 const id = std.fmt.bytesToHex(parts.thread_id, .lower); 2062 if (try pch.editDraft(.{}, io, allocator, server.users_dir, &admin_repo, .{ 2063 .id = id, 2064 .user_id = user_id, 2065 .repo_id = repo_id, 2066 .title = title, 2067 .labels = labels, 2068 .description = description, 2069 .target_branch = target_branch, 2070 .author = author, 2071 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 2072 })) { 2073 try request.respond("", .{ 2074 .status = .see_other, 2075 .extra_headers = &.{.{ .name = "location", .value = base }}, 2076 }); 2077 return; 2078 } 2079 } 2080 2081 // a draft is its author's alone, which its edit above checks 2082 if (!try request_repo.source.canModify(io, allocator, actor, parts.thread_kind, &parts.thread_id)) return respondForbidden(request); 2083 2084 const not_found = switch (parts.thread_kind) { 2085 .issue => "issue not found", 2086 .patch => "patch not found", 2087 .discuss => "discussion not found", 2088 else => unreachable, 2089 }; 2090 (switch (parts.thread_kind) { 2091 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 2092 .title = title, 2093 .labels = labels, 2094 .description = description, 2095 } }, author), 2096 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 2097 .title = title, 2098 .labels = labels, 2099 .description = description, 2100 .target_branch = target_branch, 2101 } }, author), 2102 .discuss => updateDiscussion(io, allocator, host, parts.repo_base, &parts.thread_id, title, labels, description, author), 2103 else => unreachable, 2104 }) catch |err| switch (err) { 2105 error.NotFound => { 2106 try request.respond(not_found, .{ 2107 .status = .not_found, 2108 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2109 }); 2110 return; 2111 }, 2112 else => { 2113 if (parts.thread_kind != .patch) return err; 2114 const failure = ui.Session.FormFeedback.PatchFailure.fromError(err) orelse return err; 2115 const form_location = try allocator.print("{s}/edit", .{base}); 2116 defer allocator.free(form_location); 2117 return respondThreadFormFailure(request, allocator, host, form_location, patchFeedback(failure, title, labels, description, target_branch, null)); 2118 }, 2119 }; 2120 2121 try request.respond("", .{ 2122 .status = .see_other, 2123 .extra_headers = &.{.{ .name = "location", .value = base }}, 2124 }); 2125 } 2126 2127 // resolve every conflicted field of the thread the url names 2128 fn handleThreadResolve( 2129 io: std.Io, 2130 request: *std.http.Server.Request, 2131 allocator: std.mem.Allocator, 2132 base: []const u8, 2133 host: Host, 2134 ) !void { 2135 const parts = commentBaseParts(host, base) orelse { 2136 try request.respond("thread not found", .{ 2137 .status = .not_found, 2138 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2139 }); 2140 return; 2141 }; 2142 2143 var author_arena = std.heap.ArenaAllocator.init(allocator); 2144 defer author_arena.deinit(); 2145 const author = ((try authorizeWrite(io, allocator, &author_arena, request, host, parts.repo_base, .write, parts.thread_kind)) orelse return).author; 2146 2147 const body = try readFormBody(request, allocator); 2148 defer allocator.free(body); 2149 2150 var field_arena = std.heap.ArenaAllocator.init(allocator); 2151 defer field_arena.deinit(); 2152 const aa = field_arena.allocator(); 2153 const title = try parseFormField(aa, body, "title"); 2154 const labels = try parseFormField(aa, body, "labels"); 2155 2156 // the hunk inputs are submitted as d0, d1, ...; form submission normalizes their 2157 // textarea line breaks to CRLF 2158 var hunks: std.ArrayList([]const u8) = .empty; 2159 var hunk_index: usize = 0; 2160 while (true) : (hunk_index += 1) { 2161 const name = try aa.print("d{d}", .{hunk_index}); 2162 const submitted = (try parseFormField(aa, body, name)) orelse break; 2163 try hunks.append(aa, try std.mem.replaceOwned(u8, aa, submitted, "\r\n", "\n")); 2164 } 2165 2166 if (parts.comment_id != null or (parts.thread_kind != .issue and parts.thread_kind != .patch)) { 2167 try request.respond("thread not found", .{ 2168 .status = .not_found, 2169 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2170 }); 2171 return; 2172 } 2173 const route = routeFromUrl(host, base) orelse { 2174 try request.respond("thread not found", .{ 2175 .status = .not_found, 2176 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2177 }); 2178 return; 2179 }; 2180 const theirs: []const u8 = switch (route) { 2181 .repo_patches => |*patch| patch.theirs.slice(), 2182 .repo_issues => "", 2183 else => unreachable, 2184 }; 2185 const not_found = if (parts.thread_kind == .patch) "patch not found" else "issue not found"; 2186 2187 (switch (parts.thread_kind) { 2188 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 2189 .title = title, 2190 .labels = labels, 2191 .hunks = hunks.items, 2192 } }, author), 2193 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 2194 .title = title, 2195 .labels = labels, 2196 .hunks = hunks.items, 2197 .theirs = theirs, 2198 } }, author), 2199 else => unreachable, 2200 }) catch |err| switch (err) { 2201 error.NotFound => { 2202 try request.respond(not_found, .{ 2203 .status = .not_found, 2204 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2205 }); 2206 return; 2207 }, 2208 // invalid fields send the user back to the resolve form 2209 error.InvalidFields => { 2210 const form_location = try allocator.print("{s}/resolve", .{base}); 2211 defer allocator.free(form_location); 2212 try request.respond("", .{ 2213 .status = .see_other, 2214 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 2215 }); 2216 return; 2217 }, 2218 else => |e| return e, 2219 }; 2220 2221 try request.respond("", .{ 2222 .status = .see_other, 2223 .extra_headers = &.{.{ .name = "location", .value = base }}, 2224 }); 2225 } 2226 2227 // the posted path drops the action's own segment, so the route it parses is 2228 // the undo page the action applies to 2229 fn handleUndo(io: std.Io, request: *std.http.Server.Request, allocator: std.mem.Allocator, base: []const u8, host: Host) !void { 2230 const route = routeFromUrl(host, base) orelse return respondRepoNotFound(request); 2231 if (route != .repo_undo) return respondRepoNotFound(request); 2232 const target = route.repo_undo; 2233 var arena = std.heap.ArenaAllocator.init(allocator); 2234 defer arena.deinit(); 2235 const repo_base = if (target.name.len == 0) "" else try arena.allocator().print("/{s}", .{target.name.slice()}); 2236 _ = (try authorizeWrite(io, allocator, &arena, request, host, repo_base, .owner, null)) orelse return; 2237 const resolved = (try requestRepoSource(io, allocator, host, repo_base)) orelse return respondRepoNotFound(request); 2238 defer resolved.deinit(allocator); 2239 ui.Repo.Undo.execute(io, allocator, resolved.source, target.index orelse return respondRepoNotFound(request)) catch |err| switch (err) { 2240 error.NotFound, error.InvalidHistoryIndex, error.TransactionNotFound => return respondRepoNotFound(request), 2241 else => return err, 2242 }; 2243 const location = try (ui.RoutablePage.repoUndoRoute(target.name.slice(), null) orelse return error.RouteTooLong).toUrl(&arena); 2244 try request.respond("", .{ .status = .see_other, .keep_alive = false, .extra_headers = &.{.{ .name = "location", .value = location }} }); 2245 } 2246 2247 fn handleSync( 2248 io: std.Io, 2249 request: *std.http.Server.Request, 2250 allocator: std.mem.Allocator, 2251 base: []const u8, 2252 source: ui.RepoSource, 2253 ) !void { 2254 if (base.len != 0) { 2255 try request.respond("not found", .{ 2256 .status = .not_found, 2257 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 2258 }); 2259 return; 2260 } 2261 2262 var owned_failure: ?[]u8 = null; 2263 defer if (owned_failure) |message| allocator.free(message); 2264 const failure: ?[]const u8 = blk: { 2265 owned_failure = ui.Repo.Events.sync(io, allocator, source) catch |err| break :blk @errorName(err); 2266 break :blk owned_failure; 2267 }; 2268 if (failure) |message| { 2269 var encoded: std.Io.Writer.Allocating = .init(allocator); 2270 defer encoded.deinit(); 2271 try std.Uri.Component.percentEncode(&encoded.writer, message, struct { 2272 fn isUnreserved(c: u8) bool { 2273 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 2274 } 2275 }.isUnreserved); 2276 const cookie = try allocator.print( 2277 local_flash_cookie ++ "=" ++ local_sync_failure_prefix ++ "{s}; Path=/; HttpOnly; SameSite=Strict", 2278 .{encoded.written()}, 2279 ); 2280 defer allocator.free(cookie); 2281 try request.respond("", .{ 2282 .status = .see_other, 2283 .extra_headers = &.{ 2284 .{ .name = "location", .value = "/events" }, 2285 .{ .name = "set-cookie", .value = cookie }, 2286 }, 2287 }); 2288 return; 2289 } 2290 2291 try request.respond("", .{ 2292 .status = .see_other, 2293 .extra_headers = &.{ 2294 .{ .name = "location", .value = "/events" }, 2295 .{ .name = "set-cookie", .value = local_flash_cookie ++ "=; Path=/; Max-Age=0" }, 2296 }, 2297 }); 2298 } 2299 2300 fn renderIndexHtml( 2301 io: std.Io, 2302 allocator: std.mem.Allocator, 2303 host: Host, 2304 session_token: ?[]const u8, 2305 session_data: ui.Session.Data, 2306 ) ![]const u8 { 2307 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 2308 2309 var page_arena = std.heap.ArenaAllocator.init(allocator); 2310 defer page_arena.deinit(); 2311 2312 // the server admin repo must outlive the page build, since the session's 2313 // moment reads from it. 2314 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 2315 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 2316 2317 var session = switch (host) { 2318 .server => |server| blk: { 2319 // open the admin repo to read live user/repo data. 2320 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 2321 const repo = if (repo_maybe) |*repo| repo else unreachable; 2322 var session = try ui.Session.init(&page_arena, repo, session_data); 2323 // the session dropped a user whose account was removed, so revoke 2324 // the token that named them 2325 if (session_token) |token| { 2326 if (session.data.user_id == null) server.session_store.remove(token); 2327 } 2328 // give the page builders filesystem access to the on-disk repos (a 2329 // sibling "users" dir next to the admin repo) so the Repo page can 2330 // read its files. 2331 session.users_dir = server.users_dir; 2332 break :blk session; 2333 }, 2334 .local => |local| ui.Session{ 2335 .data = session_data, 2336 .arena = &page_arena, 2337 .page_arena = &page_arena, 2338 .local = local, 2339 }, 2340 }; 2341 session.io = io; 2342 session.data.now = std.math.cast(i64, std.Io.Timestamp.now(io, .real).toSeconds()) orelse return error.TimestampOutOfRange; 2343 2344 var page = try ui.Page.init(session.page_arena, &session, session.data.current_page); 2345 var root = try ui.initRoot(allocator, &page, &session); 2346 defer root.deinit(allocator); 2347 2348 const snapshot: ui.Snapshot = .{ .page = page, .session = session.data }; 2349 2350 const content = try generateHtml(allocator, &root, &session); 2351 defer allocator.free(content); 2352 2353 // serialize the snapshot so the wasm side can parse it back without making 2354 // a second request. it's embedded raw in a <script type="application/json"> 2355 // block, whose content is raw text terminated only by "</script". in json, 2356 // '<' appears solely inside string values, so escaping every '<' (and '>' 2357 // for good measure) to its \uXXXX form yields equivalent json that can't 2358 // break out of the tag. 2359 var json: std.Io.Writer.Allocating = .init(allocator); 2360 defer json.deinit(); 2361 try std.json.Stringify.value(snapshot, .{}, &json.writer); 2362 2363 var json_escaped: std.ArrayList(u8) = .empty; 2364 defer json_escaped.deinit(allocator); 2365 for (json.written()) |c| switch (c) { 2366 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 2367 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 2368 else => try json_escaped.append(allocator, c), 2369 }; 2370 2371 var out: std.ArrayList(u8) = .empty; 2372 errdefer out.deinit(allocator); 2373 { 2374 var cursor: usize = 0; 2375 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 2376 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 2377 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 2378 }) |sub| { 2379 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 2380 try out.appendSlice(allocator, template[cursor..idx]); 2381 try out.appendSlice(allocator, sub.replacement); 2382 cursor = idx + sub.needle.len; 2383 } 2384 try out.appendSlice(allocator, template[cursor..]); 2385 } 2386 return try out.toOwnedSlice(allocator); 2387 } 2388 2389 fn findEmbed(request_path: []const u8) ?Embed { 2390 // embeds are matched before pages, so a dot keeps them from claiming a username or tab 2391 comptime for (embeds) |embed| { 2392 if (std.mem.indexOfScalar(u8, embed.path, '.') == null) @compileError("embed path needs a '.' so it can't shadow a page: " ++ embed.path); 2393 }; 2394 if (request_path.len < 2 or request_path[0] != '/') return null; 2395 const path = request_path[1..]; 2396 2397 for (embeds) |embed| { 2398 if (std.mem.eql(u8, path, embed.path)) return embed; 2399 } 2400 return null; 2401 } 2402 2403 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 2404 // own absolutely-positioned, natively-scrollable <div> holding its full content, 2405 // rendered recursively so nested scrolls work. 2406 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 2407 const grid = root.getGrid() orelse return error.MissingGrid; 2408 const root_focus = root.getFocus(); 2409 2410 var out: std.ArrayList(u8) = .empty; 2411 errdefer out.deinit(allocator); 2412 2413 switch (root.*) { 2414 .background => |*background| { 2415 if (background.art.getGrid()) |art| { 2416 try out.print(allocator, "<div class=\"ansi-art\" aria-hidden=\"true\" style=\"left:{d}ch;opacity:{d}%\">", .{ grid.size.width -| art.size.width, ui.widget.AnsiBackground.art_opacity }); 2417 try renderPanel(allocator, &out, background.art.getFocus(), art, session, root_focus); 2418 try out.appendSlice(allocator, "</div>"); 2419 } 2420 }, 2421 else => {}, 2422 } 2423 try out.appendSlice(allocator, "<div class=\"grid-content\" data-key=\"panel:root\">"); 2424 try renderPanel(allocator, &out, root_focus, grid, session, root_focus); 2425 try out.appendSlice(allocator, "</div>"); 2426 try renderForms(allocator, &out, root_focus); 2427 return try out.toOwnedSlice(allocator); 2428 } 2429 2430 // render one panel — a focus subtree and its content grid — as HTML, recursing 2431 // once per web-native Scroll inside it. the root panel is the whole page; each 2432 // Scroll becomes a nested, natively-scrollable div holding its full content. 2433 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 2434 // then the child scroll divs over those holes. 2435 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid, session: *ui.Session, root_focus: *Focus) !void { 2436 // `direct` is this panel's scroll children, each drawn as an overlaid div. 2437 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 2438 // plus their descendants, which the focus tree flattens into this panel's 2439 // children): the cell hit-test below skips them so this panel doesn't claim 2440 // cells that are really rendered inside a child scroll's own panel. 2441 // (scrolls aren't nested in practice, so every scroll child is direct here.) 2442 var direct: std.ArrayList(usize) = .empty; 2443 defer direct.deinit(allocator); 2444 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 2445 defer excluded.deinit(allocator); 2446 { 2447 var it = focus.children.iterator(); 2448 while (it.next()) |e| { 2449 if (e.value_ptr.focus.scroll == null) continue; 2450 try direct.append(allocator, e.key_ptr.*); 2451 try excluded.put(allocator, e.key_ptr.*, {}); 2452 var mit = e.value_ptr.focus.children.iterator(); 2453 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 2454 } 2455 } 2456 2457 // the HTML element a run of cells is wrapped in, chosen from the cell's 2458 // focusable kind 2459 const CellTag = union(enum) { 2460 span, // clickable focusable cell 2461 a: []const u8, // clickable focusable link 2462 plain, // non-focusable, colored 2463 2464 const a_prefix = "a:"; 2465 // an "in-page" anchor: rendered as a real <a href> so it works with js 2466 // disabled, but wasm handles it without navigating. 2467 fn init(str: []const u8) @This() { 2468 if (std.mem.startsWith(u8, str, ui.raw_link_prefix)) { 2469 return .{ .a = str[ui.raw_link_prefix.len..] }; 2470 } 2471 if (std.mem.startsWith(u8, str, ui.in_page_link_prefix)) { 2472 return .{ .a = str[ui.in_page_link_prefix.len..] }; 2473 } 2474 if (std.mem.startsWith(u8, str, a_prefix)) { 2475 return .{ .a = str[a_prefix.len..] }; 2476 } 2477 return .span; 2478 } 2479 2480 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 2481 var id_buf: [32]u8 = undefined; 2482 switch (self) { 2483 .span => { 2484 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 2485 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 2486 try out.appendSlice(alloc, "\""); 2487 try out.appendSlice(alloc, style_attr); 2488 try out.appendSlice(alloc, ">"); 2489 }, 2490 .a => |href| { 2491 // tabindex=-1 keeps these out of the browser's tab order 2492 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 2493 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 2494 try out.appendSlice(alloc, "\" href=\""); 2495 try appendEscapedHtml(alloc, out, href); 2496 try out.appendSlice(alloc, "\""); 2497 try out.appendSlice(alloc, style_attr); 2498 try out.appendSlice(alloc, ">"); 2499 }, 2500 .plain => { 2501 try out.appendSlice(alloc, "<span"); 2502 try out.appendSlice(alloc, style_attr); 2503 try out.appendSlice(alloc, ">"); 2504 }, 2505 } 2506 } 2507 2508 fn closeTag(self: @This()) []const u8 { 2509 return switch (self) { 2510 .span, .plain => "</span>", 2511 .a => "</a>", 2512 }; 2513 } 2514 }; 2515 2516 // the focusable owning each cell, among this panel's own (skipping any 2517 // that belong to a child scroll, whose cells are drawn in their own panel). 2518 // claimed in focus order, so the first focusable over a cell keeps it. 2519 // looking every focusable up for every cell is quadratic in a long list. 2520 const owners = try allocator.alloc(?usize, grid.size.width * grid.size.height); 2521 defer allocator.free(owners); 2522 @memset(owners, null); 2523 { 2524 var it = focus.children.iterator(); 2525 while (it.next()) |entry| { 2526 const child = entry.value_ptr.*; 2527 if (child.focus.mode != .all) continue; 2528 if (excluded.contains(entry.key_ptr.*)) continue; 2529 const r = child.rect; 2530 for (@min(r.y, grid.size.height)..@min(r.y + r.size.height, grid.size.height)) |y| { 2531 for (@min(r.x, grid.size.width)..@min(r.x + r.size.width, grid.size.width)) |x| { 2532 const owner = &owners[y * grid.size.width + x]; 2533 if (owner.* == null) owner.* = entry.key_ptr.*; 2534 } 2535 } 2536 } 2537 } 2538 2539 // the cells are the volatile part of a panel. js replaces this one subtree 2540 // wholesale while retaining the panel's native controls and scroll shells. 2541 try output.appendSlice(allocator, "<div class=\"grid-cells\">"); 2542 2543 // emit this panel's grid as rows of text, coalescing adjacent cells that 2544 // share a focus id and style into one tag (a clickable span, a link, or a 2545 // plain styled span). cells under a child scroll keep only their background. 2546 // a cell's own link is an anchor nested in that tag. 2547 for (0..grid.size.height) |y| { 2548 var cur_id: ?usize = null; 2549 var cur_style: Grid.Style = .{}; 2550 var open_tag: ?CellTag = null; 2551 var open_link: ?[]const u8 = null; 2552 var first = true; 2553 for (0..grid.size.width) |x| { 2554 const cell = (try grid.cell(x, y)).*; 2555 // a cell covered by a child scroll's viewport is drawn by that scroll's 2556 // own div, so blank its glyph and make it non-clickable here — but keep 2557 // its background, so the backdrop still shows through the scroll's 2558 // transparent div instead of a bare hole. 2559 const covered_by_scroll = blk: { 2560 for (direct.items) |id| { 2561 const r = (focus.children.get(id) orelse continue).rect; 2562 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; 2563 } 2564 break :blk false; 2565 }; 2566 // the focusable owning the cell at (x, y); none for a covered cell. 2567 const cell_id = if (covered_by_scroll) null else owners[y * grid.size.width + x]; 2568 const style: Grid.Style = if (covered_by_scroll) .{ .bg = cell.style.bg } else cell.style; 2569 2570 if (first or cell_id != cur_id or !style.eql(cur_style)) { 2571 if (open_link != null) try output.appendSlice(allocator, "</a>"); 2572 open_link = null; 2573 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2574 2575 var new_tag: ?CellTag = null; 2576 if (cell_id) |id| { 2577 if (focus.children.get(id)) |child| { 2578 new_tag = switch (child.focus.kind) { 2579 .custom => |custom| CellTag.init(custom), 2580 else => .span, 2581 }; 2582 } 2583 } 2584 if (new_tag == null and !style.eql(.{})) new_tag = .plain; 2585 2586 if (new_tag) |t| { 2587 var style_buf: [192]u8 = undefined; 2588 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, style)); 2589 } 2590 2591 open_tag = new_tag; 2592 cur_id = cell_id; 2593 cur_style = style; 2594 first = false; 2595 } 2596 2597 // an anchor can't nest in another, so a link tag's cells skip theirs 2598 const in_anchor = if (open_tag) |t| t == .a else false; 2599 const link = if (covered_by_scroll or in_anchor) null else webLink(cell.link); 2600 if (!sameLink(link, open_link)) { 2601 if (open_link != null) try output.appendSlice(allocator, "</a>"); 2602 if (link) |url| { 2603 // a page path opens in this tab, any other url in a new one 2604 try output.appendSlice(allocator, if (url[0] == '/') 2605 "<a class=\"cell-link\" tabindex=\"-1\" href=\"" 2606 else 2607 "<a class=\"cell-link\" tabindex=\"-1\" target=\"_blank\" rel=\"noopener noreferrer\" href=\""); 2608 try appendEscapedHtml(allocator, output, url); 2609 try output.appendSlice(allocator, "\">"); 2610 } 2611 open_link = link; 2612 } 2613 2614 if (covered_by_scroll) { 2615 try appendEscapedHtml(allocator, output, " "); 2616 } else if (cell.continuation) { 2617 // the wide rune to the left was emitted 2ch wide, covering this column 2618 } else if (cell.rune) |rune| { 2619 var encoded: [4]u8 = undefined; 2620 const encoded_len = try std.unicode.utf8Encode(rune, &encoded); 2621 const rune_text = encoded[0..encoded_len]; 2622 // a double-width rune is pinned inside a 2ch span so the 2623 // fallback glyph's advance width can't shift the rest of the row 2624 const wide = x + 1 < grid.size.width and (try grid.cell(x + 1, y)).continuation; 2625 if (wide) { 2626 try output.appendSlice(allocator, "<span class=\"w2\">"); 2627 try appendEscapedHtml(allocator, output, rune_text); 2628 try output.appendSlice(allocator, "</span>"); 2629 } else { 2630 try appendEscapedHtml(allocator, output, rune_text); 2631 } 2632 } else { 2633 try appendEscapedHtml(allocator, output, " "); 2634 } 2635 } 2636 if (open_link != null) try output.appendSlice(allocator, "</a>"); 2637 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 2638 try output.append(allocator, '\n'); 2639 } 2640 try output.appendSlice(allocator, "</div>"); 2641 2642 // native controls live in their panel, beside the replaceable cells. their 2643 // stable keys let JS update layout without recreating their DOM nodes, and 2644 // being actual descendants of a scroll gives them native movement/clipping. 2645 try renderPanelControls(allocator, output, focus, session, root_focus, &excluded); 2646 2647 // each child scroll becomes a natively-scrollable div positioned over its 2648 // viewport, holding its full content rendered recursively. 2649 for (direct.items) |id| { 2650 const child = focus.children.get(id) orelse continue; 2651 const info = child.focus.scroll orelse continue; 2652 const r = child.rect; 2653 // overflow only on the axes the widget scrolls; `auto` shows a bar only 2654 // when that axis actually overflows. the other axis is clipped (hidden), 2655 // matching how the terminal Scroll handles its non-scrolling axis. 2656 const overflow = switch (info.direction) { 2657 .vert => "overflow-x:hidden;overflow-y:auto", 2658 .horiz => "overflow-x:auto;overflow-y:hidden", 2659 .both => "overflow:auto", 2660 }; 2661 // the id carries a content version so JS preserves the native scroll 2662 // position across re-renders of the same content but resets it when the 2663 // content is replaced — e.g. selecting a different commit. the widget's 2664 // scroll offset (in cells) rides along so JS can apply it when it has no 2665 // preserved position, letting a wasm-side scrollToRect (the files list 2666 // scrolling to its selected row on page load) reach the browser. 2667 var buf: [256]u8 = undefined; 2668 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, "<div class=\"scroll\" data-key=\"scroll:{d}\" data-scroll-id=\"{d}-{d}\" data-scroll-direction=\"{s}\" data-scroll-x=\"{d}\" data-scroll-y=\"{d}\" style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em;{s}\">", .{ id, id, child.focus.version, @tagName(info.direction), info.offset_x, info.offset_y, r.x, r.y, r.size.width, r.size.height, overflow })); 2669 try renderPanel(allocator, output, child.focus, info.content, session, root_focus); 2670 try output.appendSlice(allocator, "</div>"); 2671 } 2672 } 2673 2674 const form_prefix = "form:"; 2675 const form_id_prefix = "haxy-form-"; 2676 2677 fn formAction(focus: *const Focus) ?[]const u8 { 2678 return switch (focus.kind) { 2679 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) custom[form_prefix.len..] else null, 2680 else => null, 2681 }; 2682 } 2683 2684 // find the form ancestor of a flattened focus-tree child. html's `form` 2685 // attribute then associates the control with that form without requiring the 2686 // form and control to share a DOM parent. 2687 fn formOwner(root_focus: *Focus, focus_id: usize) ?usize { 2688 var id = focus_id; 2689 while (root_focus.children.get(id)) |child| { 2690 const parent_id = child.parent_id; 2691 if (parent_id == root_focus.id) return if (formAction(root_focus) != null) root_focus.id else null; 2692 const parent = root_focus.children.get(parent_id) orelse return null; 2693 if (formAction(parent.focus) != null) return parent_id; 2694 id = parent_id; 2695 } 2696 return null; 2697 } 2698 2699 fn appendFormAttribute(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus, focus_id: usize) !void { 2700 const form_id = formOwner(root_focus, focus_id) orelse return; 2701 var buf: [64]u8 = undefined; 2702 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, " form=\"" ++ form_id_prefix ++ "{d}\"", .{form_id})); 2703 } 2704 2705 fn renderPanelControls( 2706 allocator: std.mem.Allocator, 2707 output: *std.ArrayList(u8), 2708 focus: *Focus, 2709 session: *ui.Session, 2710 root_focus: *Focus, 2711 excluded: *const std.AutoHashMapUnmanaged(usize, void), 2712 ) !void { 2713 var iter = focus.children.iterator(); 2714 while (iter.next()) |entry| { 2715 const id = entry.key_ptr.*; 2716 if (excluded.contains(id)) continue; 2717 const child = entry.value_ptr.*; 2718 const r = child.rect; 2719 2720 if (r.size.width == 0 or r.size.height == 0) continue; // not laid out, rather than merely off-screen 2721 2722 switch (child.focus.kind) { 2723 .text_input, .text_input_password, .text_area => { 2724 const ti = session.text_inputs.get(id) orelse continue; 2725 2726 const inner_left = r.x + 1; 2727 const inner_top = r.y + 1; 2728 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 2729 const preserve = !ti.options.read_only; 2730 2731 if (child.focus.kind == .text_area) { 2732 const value = try ti.text(allocator); 2733 defer allocator.free(value); 2734 var id_buf: [128]u8 = undefined; 2735 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<textarea data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2736 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2737 try appendFormAttribute(allocator, output, root_focus, id); 2738 if (ti.options.name.len > 0) { 2739 try output.appendSlice(allocator, " name=\""); 2740 try appendEscapedHtml(allocator, output, ti.options.name); 2741 try output.append(allocator, '"'); 2742 } 2743 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 2744 var pos_buf: [128]u8 = undefined; 2745 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">\n", .{ inner_left, inner_top, inner_width, inner_height })); 2746 try appendEscapedHtml(allocator, output, value); 2747 try output.appendSlice(allocator, "</textarea>"); 2748 continue; 2749 } 2750 2751 var id_buf: [160]u8 = undefined; 2752 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<input type=\"{s}\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ if (child.focus.kind == .text_input_password) "password" else "text", id, id })); 2753 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2754 try appendFormAttribute(allocator, output, root_focus, id); 2755 if (ti.options.name.len > 0) { 2756 try output.appendSlice(allocator, " name=\""); 2757 try appendEscapedHtml(allocator, output, ti.options.name); 2758 try output.append(allocator, '"'); 2759 } 2760 if (child.focus.kind != .text_input_password) { 2761 const value = try ti.text(allocator); 2762 defer allocator.free(value); 2763 try output.appendSlice(allocator, " value=\""); 2764 try appendEscapedHtml(allocator, output, value); 2765 try output.append(allocator, '"'); 2766 } 2767 var pos_buf: [96]u8 = undefined; 2768 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:1em\">", .{ inner_left, inner_top, inner_width })); 2769 }, 2770 .custom => |custom| { 2771 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2772 if (formOwner(root_focus, id) == null) continue; 2773 var id_buf: [128]u8 = undefined; 2774 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2775 try appendFormAttribute(allocator, output, root_focus, id); 2776 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2777 try output.appendSlice(allocator, " formaction=\""); 2778 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 2779 try output.append(allocator, '"'); 2780 } 2781 var pos_buf: [128]u8 = undefined; 2782 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\"></button>", .{ r.x, r.y, r.size.width, r.size.height })); 2783 } else if (std.mem.startsWith(u8, custom, ui.radio_prefix)) { 2784 // an invisible native radio over the option, checked when the option is its row's selection 2785 const field = custom[ui.radio_prefix.len..]; 2786 const separator = std.mem.indexOfScalar(u8, field, '=') orelse continue; 2787 const row = root_focus.children.get(child.parent_id) orelse continue; 2788 var id_buf: [128]u8 = undefined; 2789 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<input type=\"radio\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2790 try appendFormAttribute(allocator, output, root_focus, id); 2791 try output.appendSlice(allocator, " name=\""); 2792 try appendEscapedHtml(allocator, output, field[0..separator]); 2793 try output.appendSlice(allocator, "\" value=\""); 2794 try appendEscapedHtml(allocator, output, field[separator + 1 ..]); 2795 try output.append(allocator, '"'); 2796 if (row.focus.child_id == id) try output.appendSlice(allocator, " checked"); 2797 var pos_buf: [128]u8 = undefined; 2798 try output.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, " style=\"opacity:0;left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">", .{ r.x, r.y, r.size.width, r.size.height })); 2799 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 2800 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 2801 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 2802 var id_buf: [128]u8 = undefined; 2803 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "\" data-key=\"control:{d}\" data-focus-id=\"{d}\" style=\"opacity:0;left:{d}ch;top:{d}em;width:{d}ch;height:{d}em\">", .{ id, id, r.x, r.y, r.size.width, r.size.height })); 2804 } 2805 }, 2806 else => {}, 2807 } 2808 } 2809 } 2810 2811 // emit hidden form owners beside the rendered panels. their controls point 2812 // back here with the standard HTML `form` attribute. 2813 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 2814 // the focus child map preserves insertion order, which matches the order 2815 // widgets were added in code 2816 var iter = root_focus.children.iterator(); 2817 while (iter.next()) |entry| { 2818 const child = entry.value_ptr.*; 2819 const action_url = formAction(child.focus) orelse continue; 2820 2821 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 2822 var id_buf: [96]u8 = undefined; 2823 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 2824 try appendEscapedHtml(allocator, output, action_url); 2825 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 2826 } 2827 } 2828 2829 // the 16 ansi colors as the browser shows them (xterm's defaults) 2830 const ansi_palette = [16]Grid.Color.Rgb{ 2831 .{ .r = 0x00, .g = 0x00, .b = 0x00 }, .{ .r = 0xcd, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xcd, .b = 0x00 }, .{ .r = 0xcd, .g = 0xcd, .b = 0x00 }, 2832 .{ .r = 0x00, .g = 0x00, .b = 0xee }, .{ .r = 0xcd, .g = 0x00, .b = 0xcd }, .{ .r = 0x00, .g = 0xcd, .b = 0xcd }, .{ .r = 0xe5, .g = 0xe5, .b = 0xe5 }, 2833 .{ .r = 0x7f, .g = 0x7f, .b = 0x7f }, .{ .r = 0xff, .g = 0x00, .b = 0x00 }, .{ .r = 0x00, .g = 0xff, .b = 0x00 }, .{ .r = 0xff, .g = 0xff, .b = 0x00 }, 2834 .{ .r = 0x5c, .g = 0x5c, .b = 0xff }, .{ .r = 0xff, .g = 0x00, .b = 0xff }, .{ .r = 0x00, .g = 0xff, .b = 0xff }, .{ .r = 0xff, .g = 0xff, .b = 0xff }, 2835 }; 2836 2837 // resolve any color to rgb: palette colors through the ansi table and the 2838 // xterm 256-color layout (16 ansi, a 6x6x6 cube, then 24 grays) 2839 fn colorRgb(color: Grid.Color) Grid.Color.Rgb { 2840 return switch (color) { 2841 .rgb => |c| c, 2842 .ansi => |a| ansi_palette[@backingInt(a)], 2843 .indexed => |n| if (n < 16) 2844 ansi_palette[n] 2845 else if (n < 232) blk: { 2846 const levels = [6]u8{ 0, 0x5f, 0x87, 0xaf, 0xd7, 0xff }; 2847 const i = n - 16; 2848 break :blk .{ .r = levels[i / 36], .g = levels[(i / 6) % 6], .b = levels[i % 6] }; 2849 } else blk: { 2850 const v: u8 = 8 + (n - 232) * 10; 2851 break :blk .{ .r = v, .g = v, .b = v }; 2852 }, 2853 }; 2854 } 2855 2856 // builds an HTML ` style="color:…;background-color:…"` attribute from a 2857 // cell's style into `buf`, omitting whichever color is unset. an inverted 2858 // cell swaps the two, falling back to the page's --fg/--bg variables for 2859 // whichever side is unset. text attributes follow the colors. returns an 2860 // empty slice when nothing is set. 2861 fn styleAttr(buf: []u8, style: Grid.Style) []const u8 { 2862 if (style.eql(.{})) return buf[0..0]; 2863 const prefix = " style=\""; 2864 @memcpy(buf[0..prefix.len], prefix); 2865 var i: usize = prefix.len; 2866 const inverted = style.inverted; 2867 i = cssColor(buf, i, "color", if (inverted) style.bg else style.fg, if (inverted) "var(--bg)" else null) orelse return buf[0..0]; 2868 i = cssColor(buf, i, "background-color", if (inverted) style.fg else style.bg, if (inverted) "var(--fg)" else null) orelse return buf[0..0]; 2869 const decoration: []const u8 = if (style.underline and style.strikethrough) 2870 "text-decoration:underline line-through;" 2871 else if (style.underline) 2872 "text-decoration:underline;" 2873 else if (style.strikethrough) 2874 "text-decoration:line-through;" 2875 else 2876 ""; 2877 const attributes = std.fmt.bufPrint(buf[i..], "{s}{s}{s}{s}", .{ 2878 if (style.bold) "font-weight:bold;" else "", 2879 if (style.italic) "font-style:italic;" else "", 2880 decoration, 2881 if (style.dim) "opacity:.6;" else "", 2882 }) catch return buf[0..0]; 2883 i += attributes.len; 2884 if (i >= buf.len) return buf[0..0]; 2885 buf[i] = '"'; 2886 return buf[0 .. i + 1]; 2887 } 2888 2889 // append `prop:value;` at buf[i..] for the color, or for the fallback when 2890 // the color is unset (nothing when both are). returns the new end, or null 2891 // when it doesn't fit. 2892 fn cssColor(buf: []u8, i: usize, prop: []const u8, color: ?Grid.Color, fallback: ?[]const u8) ?usize { 2893 const s = if (color) |c| blk: { 2894 const v = colorRgb(c); 2895 break :blk std.fmt.bufPrint(buf[i..], "{s}:#{x:0>2}{x:0>2}{x:0>2};", .{ prop, v.r, v.g, v.b }) catch return null; 2896 } else if (fallback) |f| 2897 std.fmt.bufPrint(buf[i..], "{s}:{s};", .{ prop, f }) catch return null 2898 else 2899 return i; 2900 return i + s.len; 2901 } 2902 2903 // a cell's link as an href, when it's a page path or a web or mail url 2904 fn webLink(link: ?[]const u8) ?[]const u8 { 2905 const url = link orelse return null; 2906 // a page path, not a protocol-relative url 2907 if (url.len > 1 and url[0] == '/' and url[1] != '/') return url; 2908 for ([_][]const u8{ "http://", "https://", "mailto:" }) |scheme| { 2909 if (std.ascii.startsWithIgnoreCase(url, scheme)) return url; 2910 } 2911 return null; 2912 } 2913 2914 fn sameLink(a: ?[]const u8, b: ?[]const u8) bool { 2915 if (a) |x| return if (b) |y| std.mem.eql(u8, x, y) else false; 2916 return b == null; 2917 } 2918 2919 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2920 for (input) |ch| { 2921 switch (ch) { 2922 '&' => try out.appendSlice(allocator, "&amp;"), 2923 '<' => try out.appendSlice(allocator, "&lt;"), 2924 '>' => try out.appendSlice(allocator, "&gt;"), 2925 '"' => try out.appendSlice(allocator, "&quot;"), 2926 '\'' => try out.appendSlice(allocator, "&#39;"), 2927 else => try out.append(allocator, ch), 2928 } 2929 } 2930 } 2931 2932 // --- helpers -------------------------------------------------------------- 2933 2934 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 2935 var iter = request.iterateHeaders(); 2936 while (iter.next()) |header| { 2937 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2938 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2939 while (pairs.next()) |pair| { 2940 const trimmed = std.mem.trim(u8, pair, " \t"); 2941 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2942 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2943 return trimmed[eq + 1 ..]; 2944 } 2945 } 2946 } 2947 return null; 2948 } 2949 2950 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2951 var iter = std.mem.splitScalar(u8, body, '&'); 2952 while (iter.next()) |pair| { 2953 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2954 if (std.mem.eql(u8, pair[0..eq], key)) { 2955 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2956 } 2957 } 2958 return null; 2959 } 2960 2961 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2962 var buffer: [256]u8 = undefined; 2963 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2964 } 2965 2966 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2967 var out: std.ArrayList(u8) = .empty; 2968 errdefer out.deinit(allocator); 2969 var i: usize = 0; 2970 while (i < encoded.len) : (i += 1) { 2971 switch (encoded[i]) { 2972 '+' => try out.append(allocator, ' '), 2973 '%' => { 2974 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2975 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2976 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2977 try out.append(allocator, hi * 16 + lo); 2978 i += 2; 2979 }, 2980 else => try out.append(allocator, encoded[i]), 2981 } 2982 } 2983 return try out.toOwnedSlice(allocator); 2984 } 2985 2986 // disk-backed web session store. each login mints a random, opaque token 2987 // (not the user's id) that is stored as a file named by the token hex, whose 2988 // contents are the raw user_id bytes. authenticating a request is a lookup of 2989 // the cookie's token; logout deletes the file, revoking the session. there is 2990 // deliberately no expiry — a session lives until logout. form failures use 2991 // files in the flash subdirectory that the redirected GET consumes. the 2992 // directory is cleared whenever the server starts. 2993 pub const SessionStore = struct { 2994 io: std.Io, 2995 dir: std.Io.Dir, 2996 flash_dir: std.Io.Dir, 2997 auto_login: ?[token_hex_len]u8, 2998 2999 pub const token_hex_len = evt.event_id_size * 2; 3000 3001 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 3002 try data_dir.createDirPath(io, "sessions"); 3003 const dir = try data_dir.openDir(io, "sessions", .{}); 3004 errdefer dir.close(io); 3005 try dir.deleteTree(io, "flash"); 3006 try dir.createDirPath(io, "flash"); 3007 const flash_dir = try dir.openDir(io, "flash", .{}); 3008 errdefer flash_dir.close(io); 3009 const auto_login = blk: { 3010 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 3011 defer file.close(io); 3012 var token: [token_hex_len]u8 = undefined; 3013 var storage: [token_hex_len]u8 = undefined; 3014 var reader = file.reader(io, &storage); 3015 reader.interface.readSliceAll(&token) catch break :blk null; 3016 break :blk token; 3017 }; 3018 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 3019 } 3020 3021 pub fn deinit(self: SessionStore) void { 3022 self.flash_dir.close(self.io); 3023 self.dir.close(self.io); 3024 } 3025 3026 // mint a new session for user_id, returning the token hex to set as the 3027 // cookie value. 3028 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 3029 var token: [evt.event_id_size]u8 = undefined; 3030 self.io.random(&token); 3031 const token_hex = std.fmt.bytesToHex(token, .lower); 3032 const file = try self.dir.createFile(self.io, &token_hex, .{}); 3033 defer file.close(self.io); 3034 try file.writeStreamingAll(self.io, user_id); 3035 return token_hex; 3036 } 3037 3038 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 3039 var token: [evt.event_id_size]u8 = undefined; 3040 self.io.random(&token); 3041 const token_hex = std.fmt.bytesToHex(token, .lower); 3042 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 3043 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 3044 defer file.close(self.io); 3045 3046 var json: std.Io.Writer.Allocating = .init(allocator); 3047 defer json.deinit(); 3048 try std.json.Stringify.value(value, .{}, &json.writer); 3049 try file.writeStreamingAll(self.io, json.written()); 3050 return token_hex; 3051 } 3052 3053 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 3054 if (!isToken(token_hex)) return null; 3055 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 3056 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 3057 defer file.close(self.io); 3058 3059 var storage: [4096]u8 = undefined; 3060 var reader = file.reader(self.io, &storage); 3061 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 3062 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 3063 } 3064 3065 // resolve a cookie's token to its user_id. returns false (logged out) for a 3066 // missing, malformed, or unknown token. 3067 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 3068 if (!isToken(token_hex)) return false; 3069 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 3070 defer file.close(self.io); 3071 var storage: [evt.event_id_size]u8 = undefined; 3072 var file_reader = file.reader(self.io, &storage); 3073 file_reader.interface.readSliceAll(out) catch return false; 3074 return true; 3075 } 3076 3077 // revoke a session. a no-op for a missing or malformed token. 3078 pub fn remove(self: SessionStore, token_hex: []const u8) void { 3079 if (!isToken(token_hex)) return; 3080 self.dir.deleteFile(self.io, token_hex) catch {}; 3081 } 3082 3083 // leave `token_hex`'s session for visitors arriving without one. only the 3084 // `try` fixture writes one. the name can't collide with a session token. 3085 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 3086 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 3087 defer file.close(self.io); 3088 try file.writeStreamingAll(self.io, token_hex); 3089 } 3090 3091 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 3092 out.* = self.auto_login orelse return false; 3093 return true; 3094 } 3095 3096 const auto_login_name = "auto-login"; 3097 3098 // a token is exactly token_hex_len hex chars. validating before using the 3099 // value as a path keeps attacker-supplied cookies from escaping the 3100 // sessions dir (e.g. via "/" or ".." bytes). 3101 fn isToken(token_hex: []const u8) bool { 3102 if (token_hex.len != token_hex_len) return false; 3103 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 3104 return true; 3105 } 3106 }; 3107