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