╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
981 const types = [_]struct { ext: []const u8, value: []const u8 }{ 982 .{ .ext = ".png", .value = "image/png" }, 983 .{ .ext = ".jpg", .value = "image/jpeg" }, 984 .{ .ext = ".jpeg", .value = "image/jpeg" }, 985 .{ .ext = ".gif", .value = "image/gif" }, 986 .{ .ext = ".webp", .value = "image/webp" }, 987 }; 988 for (types) |entry| { 989 if (name.len > entry.ext.len and std.ascii.eqlIgnoreCase(name[name.len - entry.ext.len ..], entry.ext)) return entry.value; 990 } 991 return null; 992 } 993 994 fn respondAttachmentNotFound(request: *std.http.Server.Request) !void { 995 try request.respond("attachment not found", .{ 996 .status = .not_found, 997 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 998 }); 999 } 1000 1001 fn respondAttachmentParentNotFound(request: *std.http.Server.Request) !void { 1002 try request.respond("attachment parent not found", .{ 1003 .status = .not_found, 1004 .keep_alive = false, 1005 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1006 }); 1007 } 1008 1009 // the upload declares its file's name here, since the body is the file itself 1010 const attachment_name_header = "x-attachment-name"; 1011 1012 const AttachParentParts = struct { 1013 repo_base: []const u8, 1014 id_bytes: [evt.event_id_size]u8, 1015 }; 1016 1017 // what an attachment hangs off: the `<kind>:<id>` segment the form's page ends 1018 // with, whatever kind that is 1019 fn attachParentParts(base: []const u8) ?AttachParentParts { 1020 const segment_at = std.mem.lastIndexOfScalar(u8, base, '/') orelse return null; 1021 const segment = base[segment_at + 1 ..]; 1022 const colon_at = std.mem.lastIndexOfScalar(u8, segment, ':') orelse return null; 1023 const id_bytes = evt.parseEventId(segment[colon_at + 1 ..]) catch return null; 1024 return .{ .repo_base = base[0..segment_at], .id_bytes = id_bytes }; 1025 } 1026 1027 // attach the uploaded file to the event the url names, then reload. the file is 1028 // the whole request body, so it streams from the socket into the object store 1029 // without being buffered. 1030 fn handleAttach( 1031 io: std.Io, 1032 request: *std.http.Server.Request, 1033 allocator: std.mem.Allocator, 1034 base: []const u8, 1035 host: Host, 1036 ) !void { 1037 const parts = attachParentParts(base) orelse return respondAttachmentParentNotFound(request); 1038 1039 var author_arena = std.heap.ArenaAllocator.init(allocator); 1040 defer author_arena.deinit(); 1041 const author = ((try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request)).author; 1042 1043 const name = (try attachmentName(allocator, request)) orelse return respondUploadError(request, .bad_request, "attachment needs a name"); 1044 defer allocator.free(name); 1045 if (!evt.Attachment.nameValid(name)) return respondUploadError(request, .bad_request, "invalid attachment name"); 1046 1047 const size = request.head.content_length orelse return respondUploadError(request, .length_required, "attachments must declare a content length"); 1048 if (size == 0) return respondUploadError(request, .bad_request, "attachment is empty"); 1049 if (size > evt.Attachment.max_size) return respondUploadError(request, .payload_too_large, "attachment is too large"); 1050 1051 const parent_id_hex = std.fmt.bytesToHex(parts.id_bytes, .lower); 1052 1053 var body_buf: [4096]u8 = undefined; 1054 const blob: evt.Blob = .{ .name = name, .size = size, .reader = try request.readerExpectContinue(&body_buf) }; 1055 1056 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondAttachmentParentNotFound(request); 1057 defer request_repo.deinit(allocator); 1058 const source = request_repo.source; 1059 switch (source.repo_kind) { 1060 inline else => |repo_kind| { 1061 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1062 defer any_repo.deinit(io, allocator); 1063 switch (any_repo) { 1064 inline else => |*repo| _ = evt.Attachment.create(std.meta.activeTag(host), repo_kind, repo.self_repo_opts, io, allocator, repo, &parent_id_hex, blob, author) catch |err| switch (err) { 1065 error.ParentNotFound => return respondAttachmentParentNotFound(request), 1066 else => return err, 1067 }, 1068 } 1069 }, 1070 } 1071 1072 // the client reloads the page itself 1073 try request.respond("", .{ .status = .no_content, .keep_alive = false }); 1074 } 1075 1076 // the name the upload declares for its file, percent-encoded so it survives a 1077 // header 1078 fn attachmentName(allocator: std.mem.Allocator, request: *std.http.Server.Request) !?[]u8 { 1079 var iter = request.iterateHeaders(); 1080 while (iter.next()) |header| { 1081 if (!std.ascii.eqlIgnoreCase(header.name, attachment_name_header)) continue; 1082 return try decodeFormValue(allocator, header.value); 1083 } 1084 return null; 1085 } 1086 1087 // an upload that failed leaves the body partly read, so the connection closes 1088 fn respondUploadError(request: *std.http.Server.Request, status: std.http.Status, message: []const u8) !void { 1089 try request.respond(message, .{ 1090 .status = status, 1091 .keep_alive = false, 1092 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1093 }); 1094 } 1095 1096 // re-emit the comment `parts` names with a new body, in the repo the host 1097 // resolves the base to. 1098 fn updateComment( 1099 io: std.Io, 1100 allocator: std.mem.Allocator, 1101 host: Host, 1102 parts: CommentBaseParts, 1103 body: []const u8, 1104 author: evt.CommitAuthor, 1105 ) !void { 1106 const comment_id = parts.comment_id orelse return error.NotFound; 1107 const thread_id = std.fmt.bytesToHex(parts.thread_id, .lower); 1108 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return error.NotFound; 1109 defer request_repo.deinit(allocator); 1110 const source = request_repo.source; 1111 switch (source.repo_kind) { 1112 inline else => |repo_kind| { 1113 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1114 defer any_repo.deinit(io, allocator); 1115 switch (any_repo) { 1116 inline else => |*repo| try evt.Comment.update(std.meta.activeTag(host), repo_kind, repo.self_repo_opts, io, allocator, repo, &thread_id, &comment_id, body, author), 1117 } 1118 }, 1119 } 1120 } 1121 1122 // edit actions share a suffix; the base identifies the event being edited. 1123 fn handleEdit( 1124 io: std.Io, 1125 request: *std.http.Server.Request, 1126 allocator: std.mem.Allocator, 1127 base: []const u8, 1128 host: Host, 1129 ) !void { 1130 const parts = commentBaseParts(base) orelse return respondRemoveNotFound(request); 1131 if (parts.comment_id != null) return handleCommentEdit(io, request, allocator, base, host, parts); 1132 return handleThreadEdit(io, request, allocator, base, host, parts); 1133 } 1134 1135 // replace the body of the comment the url names, then redirect to its 1136 // permalink. 1137 fn handleCommentEdit( 1138 io: std.Io, 1139 request: *std.http.Server.Request, 1140 allocator: std.mem.Allocator, 1141 base: []const u8, 1142 host: Host, 1143 parts: CommentBaseParts, 1144 ) !void { 1145 var author_arena = std.heap.ArenaAllocator.init(allocator); 1146 defer author_arena.deinit(); 1147 const author = ((try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request)).author; 1148 1149 const form_body = try readFormBody(request, allocator); 1150 defer allocator.free(form_body); 1151 const body_crlf = (try parseFormField(allocator, form_body, "body")) orelse try allocator.dupe(u8, ""); 1152 defer allocator.free(body_crlf); 1153 const body = try std.mem.replaceOwned(u8, allocator, body_crlf, "\r\n", "\n"); 1154 defer allocator.free(body); 1155 1156 if (!evt.Comment.fieldsValid(body)) { 1157 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1158 defer allocator.free(form_location); 1159 try request.respond("", .{ 1160 .status = .see_other, 1161 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1162 }); 1163 return; 1164 } 1165 1166 const not_found = "comment not found"; 1167 updateComment(io, allocator, host, parts, body, author) catch |err| switch (err) { 1168 error.NotFound => { 1169 try request.respond(not_found, .{ 1170 .status = .not_found, 1171 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1172 }); 1173 return; 1174 }, 1175 else => |e| return e, 1176 }; 1177 1178 try request.respond("", .{ 1179 .status = .see_other, 1180 .extra_headers = &.{.{ .name = "location", .value = base }}, 1181 }); 1182 } 1183 1184 fn updateThread( 1185 comptime Event: type, 1186 io: std.Io, 1187 allocator: std.mem.Allocator, 1188 host: Host, 1189 repo_base: []const u8, 1190 id: *const [evt.event_id_size]u8, 1191 update: Event.Update, 1192 author: evt.CommitAuthor, 1193 ) !void { 1194 const request_repo = (try requestRepoSource(io, allocator, host, repo_base)) orelse return error.NotFound; 1195 defer request_repo.deinit(allocator); 1196 const source = request_repo.source; 1197 switch (source.repo_kind) { 1198 inline else => |repo_kind| { 1199 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1200 defer any_repo.deinit(io, allocator); 1201 switch (any_repo) { 1202 inline else => |*repo| try Event.update(std.meta.activeTag(host), repo_kind, repo.self_repo_opts, io, allocator, repo, id, update, author), 1203 } 1204 }, 1205 } 1206 } 1207 1208 const RemoveParts = struct { 1209 repo_base: []const u8, 1210 kind: evt.EventKind, 1211 id: [evt.event_id_size]u8, 1212 }; 1213 1214 // split a remove url into the repo and event it names 1215 fn removeParts(base: []const u8) ?RemoveParts { 1216 if (attachmentRequest(base)) |attachment| { 1217 const parent = attachParentParts(attachment.repo_base) orelse return null; 1218 return .{ 1219 .repo_base = parent.repo_base, 1220 .kind = .attach, 1221 .id = attachment.id, 1222 }; 1223 } 1224 if (commentBaseParts(base)) |thread| return .{ 1225 .repo_base = thread.repo_base, 1226 .kind = if (thread.comment_id != null) .comment else thread.thread_kind, 1227 .id = thread.comment_id orelse thread.thread_id, 1228 }; 1229 return null; 1230 } 1231 1232 // remove the event named by the form's url 1233 fn handleRemove( 1234 io: std.Io, 1235 request: *std.http.Server.Request, 1236 allocator: std.mem.Allocator, 1237 base: []const u8, 1238 host: Host, 1239 ) !void { 1240 const parts = removeParts(base) orelse return respondRemoveNotFound(request); 1241 1242 var author_arena = std.heap.ArenaAllocator.init(allocator); 1243 defer author_arena.deinit(); 1244 const request_author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 1245 const author = request_author.author; 1246 1247 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1248 defer request_repo.deinit(allocator); 1249 const source = request_repo.source; 1250 1251 if (parts.kind == .patch) switch (host) { 1252 .server => |server| { 1253 const user_id = request_author.user_id orelse return respondLoginRequired(request); 1254 1255 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 1256 defer admin_repo.deinit(io, allocator); 1257 const moment = try evt.currentMoment(evt.admin_repo_opts, &admin_repo); 1258 const record = try evt.Fork.readById(evt.AdminDB, evt.admin_repo_opts.hash, moment, &author_arena, &parts.id); 1259 if (record) |fork_record| { 1260 const repo_id = evt.parseEventId(std.fs.path.basename(source.path)) catch return respondRemoveNotFound(request); 1261 if (!fork_record.removed and fork_record.event.stage == .draft and std.mem.eql(u8, fork_record.event.repo_id, &repo_id)) { 1262 const id = std.fmt.bytesToHex(parts.id, .lower); 1263 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(server.admin_repo_path) orelse ".", "repos" }); 1264 defer allocator.free(repos_dir); 1265 try fork.remove(io, allocator, repos_dir, &admin_repo, &id, &user_id, author); 1266 1267 const location = try std.fmt.allocPrint(allocator, "{s}/patches/drafts", .{parts.repo_base}); 1268 defer allocator.free(location); 1269 try request.respond("", .{ 1270 .status = .see_other, 1271 .keep_alive = false, 1272 .extra_headers = &.{.{ .name = "location", .value = location }}, 1273 }); 1274 return; 1275 } 1276 } 1277 }, 1278 .local => {}, 1279 }; 1280 1281 switch (source.repo_kind) { 1282 inline else => |repo_kind| { 1283 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1284 defer any_repo.deinit(io, allocator); 1285 switch (any_repo) { 1286 inline else => |*repo| evt.remove(std.meta.activeTag(host), .repo, repo_kind, repo.self_repo_opts, io, allocator, repo, &parts.id, parts.kind, author) catch |err| switch (err) { 1287 error.EventNotFound => return respondRemoveNotFound(request), 1288 else => |e| return e, 1289 }, 1290 } 1291 }, 1292 } 1293 1294 const id = std.fmt.bytesToHex(parts.id, .lower); 1295 const location = try std.fmt.allocPrint(allocator, "{s}/event:{s}/kind:{s}", .{ parts.repo_base, &id, @tagName(parts.kind) }); 1296 defer allocator.free(location); 1297 try request.respond("", .{ 1298 .status = .see_other, 1299 .keep_alive = false, 1300 .extra_headers = &.{.{ .name = "location", .value = location }}, 1301 }); 1302 } 1303 1304 fn respondRemoveNotFound(request: *std.http.Server.Request) !void { 1305 try request.respond("event not found", .{ 1306 .status = .not_found, 1307 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1308 }); 1309 } 1310 1311 fn updateDiscussion( 1312 io: std.Io, 1313 allocator: std.mem.Allocator, 1314 host: Host, 1315 repo_base: []const u8, 1316 id: *const [evt.event_id_size]u8, 1317 title: []const u8, 1318 tags: []const u8, 1319 description: []const u8, 1320 author: evt.CommitAuthor, 1321 ) !void { 1322 const request_repo = (try requestRepoSource(io, allocator, host, repo_base)) orelse return error.NotFound; 1323 defer request_repo.deinit(allocator); 1324 const source = request_repo.source; 1325 switch (source.repo_kind) { 1326 inline else => |repo_kind| { 1327 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1328 defer any_repo.deinit(io, allocator); 1329 switch (any_repo) { 1330 inline else => |*repo| try evt.Discussion.update(std.meta.activeTag(host), repo_kind, repo.self_repo_opts, io, allocator, repo, id, title, tags, description, author), 1331 } 1332 }, 1333 } 1334 } 1335 1336 // set the status of the issue the url names (base is 1337 // "/repo/<owner>/<name>/issue:<id>", identity elided in local mode) by 1338 // re-emitting its event, then redirect back to it 1339 fn handleThreadStatus( 1340 io: std.Io, 1341 request: *std.http.Server.Request, 1342 allocator: std.mem.Allocator, 1343 base: []const u8, 1344 host: Host, 1345 open: bool, 1346 ) !void { 1347 const not_found = "thread not found"; 1348 const parts = commentBaseParts(base) orelse { 1349 try request.respond(not_found, .{ 1350 .status = .not_found, 1351 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1352 }); 1353 return; 1354 }; 1355 1356 var author_arena = std.heap.ArenaAllocator.init(allocator); 1357 defer author_arena.deinit(); 1358 const author = ((try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request)).author; 1359 1360 (switch (parts.thread_kind) { 1361 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .status = if (open) .open else .closed }, author), 1362 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .status = if (open) .open else .closed }, author), 1363 else => return respondRemoveNotFound(request), 1364 }) catch |err| switch (err) { 1365 error.NotFound => { 1366 try request.respond(not_found, .{ 1367 .status = .not_found, 1368 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1369 }); 1370 return; 1371 }, 1372 else => |e| return e, 1373 }; 1374 1375 // like logout, this is a bodyless POST, so close the connection rather than 1376 // letting the keep-alive path try to discard a body that isn't framed. 1377 try request.respond("", .{ 1378 .status = .see_other, 1379 .keep_alive = false, 1380 .extra_headers = &.{.{ .name = "location", .value = base }}, 1381 }); 1382 } 1383 1384 // replace a thread's editable fields. 1385 fn handleThreadEdit( 1386 io: std.Io, 1387 request: *std.http.Server.Request, 1388 allocator: std.mem.Allocator, 1389 base: []const u8, 1390 host: Host, 1391 parts: CommentBaseParts, 1392 ) !void { 1393 var author_arena = std.heap.ArenaAllocator.init(allocator); 1394 defer author_arena.deinit(); 1395 const request_author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 1396 const author = request_author.author; 1397 1398 const body = try readFormBody(request, allocator); 1399 defer allocator.free(body); 1400 1401 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 1402 defer allocator.free(title); 1403 const tags = (try parseFormField(allocator, body, "tags")) orelse try allocator.dupe(u8, ""); 1404 defer allocator.free(tags); 1405 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 1406 defer allocator.free(description_crlf); 1407 // form submission normalizes textarea line breaks to CRLF; store plain 1408 // newlines so the text renders the same on every host 1409 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 1410 defer allocator.free(description); 1411 const target_branch = (try parseFormField(allocator, body, "target_branch")) orelse try allocator.dupe(u8, ""); 1412 defer allocator.free(target_branch); 1413 1414 // invalid fields send the user back to the edit form 1415 const valid = switch (parts.thread_kind) { 1416 .issue => evt.Issue.fieldsValid(title, tags), 1417 .patch => evt.Patch.fieldsValid(title, tags), 1418 .discuss => evt.Discussion.fieldsValid(title, tags), 1419 else => unreachable, 1420 }; 1421 if (!valid) { 1422 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1423 defer allocator.free(form_location); 1424 if (!evt.titleValid(title)) { 1425 return respondThreadFormFailure(request, allocator, host, form_location, requiredTitleFeedback(parts.thread_kind, title, tags, description, target_branch)); 1426 } 1427 try request.respond("", .{ 1428 .status = .see_other, 1429 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1430 }); 1431 return; 1432 } 1433 1434 const draft_user_id = if (parts.thread_kind == .patch) request_author.user_id else null; 1435 if (draft_user_id) |user_id| { 1436 const server = switch (host) { 1437 .server => |server| server, 1438 .local => unreachable, 1439 }; 1440 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1441 defer request_repo.deinit(allocator); 1442 if (!try request_repo.source.hasBranch(io, allocator, target_branch)) { 1443 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1444 defer allocator.free(form_location); 1445 return respondThreadFormFailure(request, allocator, host, form_location, invalidTargetBranchFeedback(title, tags, description, target_branch)); 1446 } 1447 const repo_id = evt.parseEventId(std.fs.path.basename(request_repo.source.path)) catch return respondRemoveNotFound(request); 1448 var admin_repo = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 1449 defer admin_repo.deinit(io, allocator); 1450 const id = std.fmt.bytesToHex(parts.thread_id, .lower); 1451 const repos_dir = try std.fs.path.join(allocator, &.{ std.fs.path.dirname(server.admin_repo_path) orelse ".", "repos" }); 1452 defer allocator.free(repos_dir); 1453 const fork_path = try fork.forkPath(allocator, repos_dir, &id); 1454 defer allocator.free(fork_path); 1455 if (try pch.editDraft(.{}, io, allocator, &admin_repo, fork_path, .{ 1456 .id = id, 1457 .user_id = user_id, 1458 .repo_id = repo_id, 1459 .title = title, 1460 .tags = tags, 1461 .description = description, 1462 .target_branch = target_branch, 1463 .author = author, 1464 .timestamp = @intCast(std.Io.Timestamp.now(io, .real).toSeconds()), 1465 })) { 1466 try request.respond("", .{ 1467 .status = .see_other, 1468 .extra_headers = &.{.{ .name = "location", .value = base }}, 1469 }); 1470 return; 1471 } 1472 } 1473 1474 const not_found = switch (parts.thread_kind) { 1475 .issue => "issue not found", 1476 .patch => "patch not found", 1477 .discuss => "discussion not found", 1478 else => unreachable, 1479 }; 1480 (switch (parts.thread_kind) { 1481 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 1482 .title = title, 1483 .tags = tags, 1484 .description = description, 1485 } }, author), 1486 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .fields = .{ 1487 .title = title, 1488 .tags = tags, 1489 .description = description, 1490 .target_branch = target_branch, 1491 } }, author), 1492 .discuss => updateDiscussion(io, allocator, host, parts.repo_base, &parts.thread_id, title, tags, description, author), 1493 else => unreachable, 1494 }) catch |err| switch (err) { 1495 error.NotFound => { 1496 try request.respond(not_found, .{ 1497 .status = .not_found, 1498 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1499 }); 1500 return; 1501 }, 1502 else => |e| return e, 1503 }; 1504 1505 try request.respond("", .{ 1506 .status = .see_other, 1507 .extra_headers = &.{.{ .name = "location", .value = base }}, 1508 }); 1509 } 1510 1511 // resolve every conflicted field of the thread the url names 1512 fn handleThreadResolve( 1513 io: std.Io, 1514 request: *std.http.Server.Request, 1515 allocator: std.mem.Allocator, 1516 base: []const u8, 1517 host: Host, 1518 ) !void { 1519 var author_arena = std.heap.ArenaAllocator.init(allocator); 1520 defer author_arena.deinit(); 1521 const author = ((try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request)).author; 1522 1523 const body = try readFormBody(request, allocator); 1524 defer allocator.free(body); 1525 1526 var field_arena = std.heap.ArenaAllocator.init(allocator); 1527 defer field_arena.deinit(); 1528 const aa = field_arena.allocator(); 1529 const title = try parseFormField(aa, body, "title"); 1530 const tags = try parseFormField(aa, body, "tags"); 1531 1532 // the hunk inputs are submitted as d0, d1, ...; form submission normalizes their 1533 // textarea line breaks to CRLF 1534 var hunks: std.ArrayList([]const u8) = .empty; 1535 var hunk_index: usize = 0; 1536 while (true) : (hunk_index += 1) { 1537 const name = try std.fmt.allocPrint(aa, "d{d}", .{hunk_index}); 1538 const submitted = (try parseFormField(aa, body, name)) orelse break; 1539 try hunks.append(aa, try std.mem.replaceOwned(u8, aa, submitted, "\r\n", "\n")); 1540 } 1541 1542 const parts = commentBaseParts(base) orelse { 1543 try request.respond("thread not found", .{ 1544 .status = .not_found, 1545 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1546 }); 1547 return; 1548 }; 1549 if (parts.comment_id != null or (parts.thread_kind != .issue and parts.thread_kind != .patch)) { 1550 try request.respond("thread not found", .{ 1551 .status = .not_found, 1552 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1553 }); 1554 return; 1555 } 1556 const route = ui.RoutablePage.fromUrl(base) orelse ui.RoutablePage.fromUrlLocal(base) orelse { 1557 try request.respond("thread not found", .{ 1558 .status = .not_found, 1559 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1560 }); 1561 return; 1562 }; 1563 const theirs: []const u8 = switch (route) { 1564 .repo_patches => |*patch| patch.theirs.slice(), 1565 .repo_issues => "", 1566 else => unreachable, 1567 }; 1568 const not_found = if (parts.thread_kind == .patch) "patch not found" else "issue not found"; 1569 1570 (switch (parts.thread_kind) { 1571 .issue => updateThread(evt.Issue, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 1572 .title = title, 1573 .tags = tags, 1574 .hunks = hunks.items, 1575 } }, author), 1576 .patch => updateThread(evt.Patch, io, allocator, host, parts.repo_base, &parts.thread_id, .{ .resolve = .{ 1577 .title = title, 1578 .tags = tags, 1579 .hunks = hunks.items, 1580 .theirs = theirs, 1581 } }, author), 1582 else => unreachable, 1583 }) catch |err| switch (err) { 1584 error.NotFound => { 1585 try request.respond(not_found, .{ 1586 .status = .not_found, 1587 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1588 }); 1589 return; 1590 }, 1591 // invalid fields send the user back to the resolve form 1592 error.InvalidFields => { 1593 const form_location = try std.fmt.allocPrint(allocator, "{s}/resolve", .{base}); 1594 defer allocator.free(form_location); 1595 try request.respond("", .{ 1596 .status = .see_other, 1597 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1598 }); 1599 return; 1600 }, 1601 else => |e| return e, 1602 }; 1603 1604 try request.respond("", .{ 1605 .status = .see_other, 1606 .extra_headers = &.{.{ .name = "location", .value = base }}, 1607 }); 1608 } 1609 1610 fn handleSync( 1611 io: std.Io, 1612 request: *std.http.Server.Request, 1613 allocator: std.mem.Allocator, 1614 base: []const u8, 1615 source: ui.RepoSource, 1616 ) !void { 1617 if (base.len != 0) { 1618 try request.respond("not found", .{ 1619 .status = .not_found, 1620 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1621 }); 1622 return; 1623 } 1624 1625 var owned_failure: ?[]u8 = null; 1626 defer if (owned_failure) |message| allocator.free(message); 1627 const failure: ?[]const u8 = blk: { 1628 owned_failure = ui.Repo.Events.sync(io, allocator, source) catch |err| break :blk @errorName(err); 1629 break :blk owned_failure; 1630 }; 1631 if (failure) |message| { 1632 var encoded: std.Io.Writer.Allocating = .init(allocator); 1633 defer encoded.deinit(); 1634 try std.Uri.Component.percentEncode(&encoded.writer, message, struct { 1635 fn isUnreserved(c: u8) bool { 1636 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 1637 } 1638 }.isUnreserved); 1639 const cookie = try std.fmt.allocPrint( 1640 allocator, 1641 local_flash_cookie ++ "=" ++ local_sync_failure_prefix ++ "{s}; Path=/; HttpOnly; SameSite=Strict", 1642 .{encoded.written()}, 1643 ); 1644 defer allocator.free(cookie); 1645 try request.respond("", .{ 1646 .status = .see_other, 1647 .extra_headers = &.{ 1648 .{ .name = "location", .value = "/events" }, 1649 .{ .name = "set-cookie", .value = cookie }, 1650 }, 1651 }); 1652 return; 1653 } 1654 1655 try request.respond("", .{ 1656 .status = .see_other, 1657 .extra_headers = &.{ 1658 .{ .name = "location", .value = "/events" }, 1659 .{ .name = "set-cookie", .value = local_flash_cookie ++ "=; Path=/; Max-Age=0" }, 1660 }, 1661 }); 1662 } 1663 1664 fn renderIndexHtml( 1665 io: std.Io, 1666 allocator: std.mem.Allocator, 1667 host: Host, 1668 session_data: ui.Session.Data, 1669 ) ![]const u8 { 1670 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 1671 1672 var page_arena = std.heap.ArenaAllocator.init(allocator); 1673 defer page_arena.deinit(); 1674 1675 // the server admin repo must outlive the page build, since the session's 1676 // moment reads from it. 1677 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 1678 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 1679 1680 var session = switch (host) { 1681 .server => |server| blk: { 1682 // open the admin repo to read live user/repo data. 1683 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = server.admin_repo_path }); 1684 const repo = if (repo_maybe) |*repo| repo else unreachable; 1685 var session = try ui.Session.init(&page_arena, repo, session_data); 1686 // give the page builders filesystem access to the on-disk repos (a 1687 // sibling "repos" dir next to the admin repo) so the Repo page can 1688 // read its files. 1689 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(server.admin_repo_path) orelse ".", "repos" }); 1690 break :blk session; 1691 }, 1692 .local => |local| ui.Session{ 1693 .data = session_data, 1694 .arena = &page_arena, 1695 .page_arena = &page_arena, 1696 .local = local, 1697 }, 1698 }; 1699 session.io = io; 1700 1701 var page = try ui.Page.init(session.page_arena, &session, session.data.current_page); 1702 var root = try ui.initRoot(allocator, &page, &session); 1703 defer root.deinit(allocator); 1704 1705 const snapshot: ui.Snapshot = .{ .page = page, .session = session.data }; 1706 1707 const content = try generateHtml(allocator, &root, &session); 1708 defer allocator.free(content); 1709 1710 // serialize the snapshot so the wasm side can parse it back without making 1711 // a second request. it's embedded raw in a <script type="application/json"> 1712 // block, whose content is raw text terminated only by "</script". in json, 1713 // '<' appears solely inside string values, so escaping every '<' (and '>' 1714 // for good measure) to its \uXXXX form yields equivalent json that can't 1715 // break out of the tag. 1716 var json: std.Io.Writer.Allocating = .init(allocator); 1717 defer json.deinit(); 1718 try std.json.Stringify.value(snapshot, .{}, &json.writer); 1719 1720 var json_escaped: std.ArrayList(u8) = .empty; 1721 defer json_escaped.deinit(allocator); 1722 for (json.written()) |c| switch (c) { 1723 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 1724 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 1725 else => try json_escaped.append(allocator, c), 1726 }; 1727 1728 var out: std.ArrayList(u8) = .empty; 1729 errdefer out.deinit(allocator); 1730 { 1731 var cursor: usize = 0; 1732 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 1733 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 1734 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 1735 }) |sub| { 1736 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 1737 try out.appendSlice(allocator, template[cursor..idx]); 1738 try out.appendSlice(allocator, sub.replacement); 1739 cursor = idx + sub.needle.len; 1740 } 1741 try out.appendSlice(allocator, template[cursor..]); 1742 } 1743 return try out.toOwnedSlice(allocator); 1744 } 1745 1746 fn findEmbed(request_path: []const u8) ?Embed { 1747 const path = if (std.mem.eql(u8, request_path, "/")) 1748 "index.html" 1749 else if (request_path.len > 1 and request_path[0] == '/') 1750 request_path[1..] 1751 else 1752 return null; 1753 1754 for (embeds) |embed| { 1755 if (std.mem.eql(u8, path, embed.path)) return embed; 1756 } 1757 return null; 1758 } 1759 1760 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 1761 // own absolutely-positioned, natively-scrollable <div> holding its full content, 1762 // rendered recursively so nested scrolls work. 1763 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1764 const grid = root.getGrid() orelse return error.MissingGrid; 1765 const root_focus = root.getFocus(); 1766 1767 var out: std.ArrayList(u8) = .empty; 1768 errdefer out.deinit(allocator); 1769 1770 switch (root.*) { 1771 .background => |*background| { 1772 if (background.art.getGrid()) |art| { 1773 var position_buf: [64]u8 = undefined; 1774 try out.appendSlice(allocator, try std.fmt.bufPrint(&position_buf, "<div class=\"ansi-art\" aria-hidden=\"true\" style=\"left:{d}ch\">", .{grid.size.width -| art.size.width})); 1775 try renderPanel(allocator, &out, background.art.getFocus(), art, session, root_focus); 1776 try out.appendSlice(allocator, "</div>"); 1777 } 1778 }, 1779 else => {}, 1780 } 1781 try out.appendSlice(allocator, "<div class=\"grid-content\" data-key=\"panel:root\">"); 1782 try renderPanel(allocator, &out, root_focus, grid, session, root_focus); 1783 try out.appendSlice(allocator, "</div>"); 1784 try renderForms(allocator, &out, root_focus); 1785 return try out.toOwnedSlice(allocator); 1786 } 1787 1788 // render one panel — a focus subtree and its content grid — as HTML, recursing 1789 // once per web-native Scroll inside it. the root panel is the whole page; each 1790 // Scroll becomes a nested, natively-scrollable div holding its full content. 1791 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 1792 // then the child scroll divs over those holes. 1793 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid, session: *ui.Session, root_focus: *Focus) !void { 1794 // `direct` is this panel's scroll children, each drawn as an overlaid div. 1795 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 1796 // plus their descendants, which the focus tree flattens into this panel's 1797 // children): the cell hit-test below skips them so this panel doesn't claim 1798 // cells that are really rendered inside a child scroll's own panel. 1799 // (scrolls aren't nested in practice, so every scroll child is direct here.) 1800 var direct: std.ArrayList(usize) = .empty; 1801 defer direct.deinit(allocator); 1802 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 1803 defer excluded.deinit(allocator); 1804 { 1805 var it = focus.children.iterator(); 1806 while (it.next()) |e| { 1807 if (e.value_ptr.focus.scroll == null) continue; 1808 try direct.append(allocator, e.key_ptr.*); 1809 try excluded.put(allocator, e.key_ptr.*, {}); 1810 var mit = e.value_ptr.focus.children.iterator(); 1811 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 1812 } 1813 } 1814 1815 // the HTML element a run of cells is wrapped in, chosen from the cell's 1816 // focusable kind 1817 const CellTag = union(enum) { 1818 span, // clickable focusable cell 1819 a: []const u8, // clickable focusable link 1820 plain, // non-focusable, colored 1821 1822 const a_prefix = "a:"; 1823 // an "in-page" anchor: rendered as a real <a href> so it works with js 1824 // disabled, but wasm handles it without navigating. 1825 fn init(str: []const u8) @This() { 1826 if (std.mem.startsWith(u8, str, ui.raw_link_prefix)) { 1827 return .{ .a = str[ui.raw_link_prefix.len..] }; 1828 } 1829 if (std.mem.startsWith(u8, str, ui.in_page_link_prefix)) { 1830 return .{ .a = str[ui.in_page_link_prefix.len..] }; 1831 } 1832 if (std.mem.startsWith(u8, str, a_prefix)) { 1833 return .{ .a = str[a_prefix.len..] }; 1834 } 1835 return .span; 1836 } 1837 1838 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 1839 var id_buf: [32]u8 = undefined; 1840 switch (self) { 1841 .span => { 1842 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 1843 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1844 try out.appendSlice(alloc, "\""); 1845 try out.appendSlice(alloc, style_attr); 1846 try out.appendSlice(alloc, ">"); 1847 }, 1848 .a => |href| { 1849 // tabindex=-1 keeps these out of the browser's tab order 1850 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 1851 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1852 try out.appendSlice(alloc, "\" href=\""); 1853 try appendEscapedHtml(alloc, out, href); 1854 try out.appendSlice(alloc, "\""); 1855 try out.appendSlice(alloc, style_attr); 1856 try out.appendSlice(alloc, ">"); 1857 }, 1858 .plain => { 1859 try out.appendSlice(alloc, "<span"); 1860 try out.appendSlice(alloc, style_attr); 1861 try out.appendSlice(alloc, ">"); 1862 }, 1863 } 1864 } 1865 1866 fn closeTag(self: @This()) []const u8 { 1867 return switch (self) { 1868 .span, .plain => "</span>", 1869 .a => "</a>", 1870 }; 1871 } 1872 }; 1873 1874 // the cells are the volatile part of a panel. js replaces this one subtree 1875 // wholesale while retaining the panel's native controls and scroll shells. 1876 try output.appendSlice(allocator, "<div class=\"grid-cells\">"); 1877 1878 // emit this panel's grid as rows of text, coalescing adjacent cells that 1879 // share a focus id and colors into one tag (a clickable span, a link, or a 1880 // plain colored span). cells under a child scroll keep only their background. 1881 for (0..grid.size.height) |y| { 1882 var cur_id: ?usize = null; 1883 var cur_fg: ?Grid.Color = null; 1884 var cur_bg: ?Grid.Color = null; 1885 var open_tag: ?CellTag = null; 1886 var first = true; 1887 for (0..grid.size.width) |x| { 1888 const cell = (try grid.cell(x, y)).*; 1889 // a cell covered by a child scroll's viewport is drawn by that scroll's 1890 // own div, so blank its glyph and make it non-clickable here — but keep 1891 // its background, so the backdrop still shows through the scroll's 1892 // transparent div instead of a bare hole. 1893 const covered_by_scroll = blk: { 1894 for (direct.items) |id| { 1895 const r = (focus.children.get(id) orelse continue).rect; 1896 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; 1897 } 1898 break :blk false; 1899 }; 1900 // the focusable cell at (x, y) among this panel's own focusables (skipping 1901 // any that belong to a child scroll, whose cells are drawn in their own 1902 // panel); none for a covered cell. 1903 const cell_id = if (covered_by_scroll) null else blk: { 1904 var iter = focus.children.iterator(); 1905 while (iter.next()) |entry| { 1906 const child = entry.value_ptr.*; 1907 if (child.focus.mode != .all) continue; 1908 if (excluded.contains(entry.key_ptr.*)) continue; 1909 const r = child.rect; 1910 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 1911 break :blk entry.key_ptr.*; 1912 } 1913 } 1914 break :blk null; 1915 }; 1916 const fg = if (covered_by_scroll) null else cell.style.fg; 1917 const bg = cell.style.bg; 1918 1919 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 1920 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1921 1922 var new_tag: ?CellTag = null; 1923 if (cell_id) |id| { 1924 if (focus.children.get(id)) |child| { 1925 new_tag = switch (child.focus.kind) { 1926 .custom => |custom| CellTag.init(custom), 1927 else => .span, 1928 }; 1929 } 1930 } 1931 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 1932 1933 if (new_tag) |t| { 1934 var style_buf: [64]u8 = undefined; 1935 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 1936 } 1937 1938 open_tag = new_tag; 1939 cur_id = cell_id; 1940 cur_fg = fg; 1941 cur_bg = bg; 1942 first = false; 1943 } 1944 1945 if (covered_by_scroll) { 1946 try appendEscapedHtml(allocator, output, " "); 1947 } else if (cell.continuation) { 1948 // the wide rune to the left was emitted 2ch wide, covering this column 1949 } else if (cell.rune) |rune| { 1950 var encoded: [4]u8 = undefined; 1951 const encoded_len = try std.unicode.utf8Encode(rune, &encoded); 1952 const rune_text = encoded[0..encoded_len]; 1953 // a double-width rune is pinned inside a 2ch span so the 1954 // fallback glyph's advance width can't shift the rest of the row 1955 const wide = x + 1 < grid.size.width and (try grid.cell(x + 1, y)).continuation; 1956 if (wide) { 1957 try output.appendSlice(allocator, "<span class=\"w2\">"); 1958 try appendEscapedHtml(allocator, output, rune_text); 1959 try output.appendSlice(allocator, "</span>"); 1960 } else { 1961 try appendEscapedHtml(allocator, output, rune_text); 1962 } 1963 } else { 1964 try appendEscapedHtml(allocator, output, " "); 1965 } 1966 } 1967 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1968 try output.append(allocator, '\n'); 1969 } 1970 try output.appendSlice(allocator, "</div>"); 1971 1972 // native controls live in their panel, beside the replaceable cells. their 1973 // stable keys let JS update layout without recreating their DOM nodes, and 1974 // being actual descendants of a scroll gives them native movement/clipping. 1975 try renderPanelControls(allocator, output, focus, session, root_focus, &excluded); 1976 1977 // each child scroll becomes a natively-scrollable div positioned over its 1978 // viewport, holding its full content rendered recursively. 1979 for (direct.items) |id| { 1980 const child = focus.children.get(id) orelse continue; 1981 const info = child.focus.scroll orelse continue; 1982 const r = child.rect; 1983 // overflow only on the axes the widget scrolls; `auto` shows a bar only 1984 // when that axis actually overflows. the other axis is clipped (hidden), 1985 // matching how the terminal Scroll handles its non-scrolling axis. 1986 const overflow = switch (info.direction) { 1987 .vert => "overflow-x:hidden;overflow-y:auto", 1988 .horiz => "overflow-x:auto;overflow-y:hidden", 1989 .both => "overflow:auto", 1990 }; 1991 // the id carries a content version so JS preserves the native scroll 1992 // position across re-renders of the same content but resets it when the 1993 // content is replaced — e.g. selecting a different commit. the widget's 1994 // scroll offset (in cells) rides along so JS can apply it when it has no 1995 // preserved position, letting a wasm-side scrollToRect (the files list 1996 // scrolling to its selected row on page load) reach the browser. 1997 var buf: [256]u8 = undefined; 1998 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 })); 1999 try renderPanel(allocator, output, child.focus, info.content, session, root_focus); 2000 try output.appendSlice(allocator, "</div>"); 2001 } 2002 } 2003 2004 const form_prefix = "form:"; 2005 const form_id_prefix = "haxy-form-"; 2006 2007 fn formAction(focus: *const Focus) ?[]const u8 { 2008 return switch (focus.kind) { 2009 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) custom[form_prefix.len..] else null, 2010 else => null, 2011 }; 2012 } 2013 2014 // find the form ancestor of a flattened focus-tree child. html's `form` 2015 // attribute then associates the control with that form without requiring the 2016 // form and control to share a DOM parent. 2017 fn formOwner(root_focus: *Focus, focus_id: usize) ?usize { 2018 var id = focus_id; 2019 while (root_focus.children.get(id)) |child| { 2020 const parent_id = child.parent_id; 2021 if (parent_id == root_focus.id) return if (formAction(root_focus) != null) root_focus.id else null; 2022 const parent = root_focus.children.get(parent_id) orelse return null; 2023 if (formAction(parent.focus) != null) return parent_id; 2024 id = parent_id; 2025 } 2026 return null; 2027 } 2028 2029 fn appendFormAttribute(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus, focus_id: usize) !void { 2030 const form_id = formOwner(root_focus, focus_id) orelse return; 2031 var buf: [64]u8 = undefined; 2032 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, " form=\"" ++ form_id_prefix ++ "{d}\"", .{form_id})); 2033 } 2034 2035 fn renderPanelControls( 2036 allocator: std.mem.Allocator, 2037 output: *std.ArrayList(u8), 2038 focus: *Focus, 2039 session: *ui.Session, 2040 root_focus: *Focus, 2041 excluded: *const std.AutoHashMapUnmanaged(usize, void), 2042 ) !void { 2043 var iter = focus.children.iterator(); 2044 while (iter.next()) |entry| { 2045 const id = entry.key_ptr.*; 2046 if (excluded.contains(id)) continue; 2047 const child = entry.value_ptr.*; 2048 const r = child.rect; 2049 2050 switch (child.focus.kind) { 2051 .text_input, .text_input_password, .text_area => { 2052 const ti = session.text_inputs.get(id) orelse continue; 2053 2054 const inner_left = r.x + 1; 2055 const inner_top = r.y + 1; 2056 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 2057 const preserve = !ti.options.read_only; 2058 2059 if (child.focus.kind == .text_area) { 2060 const value = try ti.text(allocator); 2061 defer allocator.free(value); 2062 var id_buf: [128]u8 = undefined; 2063 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<textarea data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2064 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2065 try appendFormAttribute(allocator, output, root_focus, id); 2066 if (ti.options.name.len > 0) { 2067 try output.appendSlice(allocator, " name=\""); 2068 try appendEscapedHtml(allocator, output, ti.options.name); 2069 try output.append(allocator, '"'); 2070 } 2071 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 2072 var pos_buf: [128]u8 = undefined; 2073 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 })); 2074 try appendEscapedHtml(allocator, output, value); 2075 try output.appendSlice(allocator, "</textarea>"); 2076 continue; 2077 } 2078 2079 var id_buf: [160]u8 = undefined; 2080 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 })); 2081 if (preserve) try output.appendSlice(allocator, " data-preserve-value") else try output.appendSlice(allocator, " readonly"); 2082 try appendFormAttribute(allocator, output, root_focus, id); 2083 if (ti.options.name.len > 0) { 2084 try output.appendSlice(allocator, " name=\""); 2085 try appendEscapedHtml(allocator, output, ti.options.name); 2086 try output.append(allocator, '"'); 2087 } 2088 if (child.focus.kind != .text_input_password) { 2089 const value = try ti.text(allocator); 2090 defer allocator.free(value); 2091 try output.appendSlice(allocator, " value=\""); 2092 try appendEscapedHtml(allocator, output, value); 2093 try output.append(allocator, '"'); 2094 } 2095 var pos_buf: [96]u8 = undefined; 2096 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 })); 2097 }, 2098 .custom => |custom| { 2099 if (std.mem.eql(u8, custom, "submit") or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2100 if (formOwner(root_focus, id) == null) continue; 2101 var id_buf: [128]u8 = undefined; 2102 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "<button type=\"submit\" data-key=\"control:{d}\" data-focus-id=\"{d}\"", .{ id, id })); 2103 try appendFormAttribute(allocator, output, root_focus, id); 2104 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 2105 try output.appendSlice(allocator, " formaction=\""); 2106 try appendEscapedHtml(allocator, output, custom[ui.submit_action_prefix.len..]); 2107 try output.append(allocator, '"'); 2108 } 2109 var pos_buf: [128]u8 = undefined; 2110 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 })); 2111 } else if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) { 2112 try output.appendSlice(allocator, "<input type=\"file\" data-preserve-value data-action=\""); 2113 try appendEscapedHtml(allocator, output, custom[ui.file_input_prefix.len..]); 2114 var id_buf: [128]u8 = undefined; 2115 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 })); 2116 } 2117 }, 2118 else => {}, 2119 } 2120 } 2121 } 2122 2123 // emit hidden form owners beside the rendered panels. their controls point 2124 // back here with the standard HTML `form` attribute. 2125 fn renderForms(allocator: std.mem.Allocator, output: *std.ArrayList(u8), root_focus: *Focus) !void { 2126 // the focus child map preserves insertion order, which matches the order 2127 // widgets were added in code 2128 var iter = root_focus.children.iterator(); 2129 while (iter.next()) |entry| { 2130 const child = entry.value_ptr.*; 2131 const action_url = formAction(child.focus) orelse continue; 2132 2133 try output.appendSlice(allocator, "<form hidden data-key=\"form:"); 2134 var id_buf: [96]u8 = undefined; 2135 try output.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}\" id=\"" ++ form_id_prefix ++ "{d}\" action=\"", .{ entry.key_ptr.*, entry.key_ptr.* })); 2136 try appendEscapedHtml(allocator, output, action_url); 2137 try output.appendSlice(allocator, "\" method=\"post\"></form>"); 2138 } 2139 } 2140 2141 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 2142 if (a) |av| return if (b) |bv| av.eql(bv) else false; 2143 return b == null; 2144 } 2145 2146 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 2147 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 2148 // empty slice when neither is set. 2149 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 2150 if (fg == null and bg == null) return buf[0..0]; 2151 const prefix = " style=\""; 2152 @memcpy(buf[0..prefix.len], prefix); 2153 var i: usize = prefix.len; 2154 if (fg) |c| { 2155 const s = std.fmt.bufPrint(buf[i..], "color:#{x:0>2}{x:0>2}{x:0>2};", .{ c.r, c.g, c.b }) catch return buf[0..0]; 2156 i += s.len; 2157 } 2158 if (bg) |c| { 2159 const s = std.fmt.bufPrint(buf[i..], "background-color:#{x:0>2}{x:0>2}{x:0>2};", .{ c.r, c.g, c.b }) catch return buf[0..0]; 2160 i += s.len; 2161 } 2162 buf[i] = '"'; 2163 i += 1; 2164 return buf[0..i]; 2165 } 2166 2167 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 2168 for (input) |ch| { 2169 switch (ch) { 2170 '&' => try out.appendSlice(allocator, "&amp;"), 2171 '<' => try out.appendSlice(allocator, "&lt;"), 2172 '>' => try out.appendSlice(allocator, "&gt;"), 2173 '"' => try out.appendSlice(allocator, "&quot;"), 2174 '\'' => try out.appendSlice(allocator, "&#39;"), 2175 else => try out.append(allocator, ch), 2176 } 2177 } 2178 } 2179 2180 // --- helpers -------------------------------------------------------------- 2181 2182 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 2183 var iter = request.iterateHeaders(); 2184 while (iter.next()) |header| { 2185 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 2186 var pairs = std.mem.splitScalar(u8, header.value, ';'); 2187 while (pairs.next()) |pair| { 2188 const trimmed = std.mem.trim(u8, pair, " \t"); 2189 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 2190 if (std.mem.eql(u8, trimmed[0..eq], name)) { 2191 return trimmed[eq + 1 ..]; 2192 } 2193 } 2194 } 2195 return null; 2196 } 2197 2198 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 2199 var iter = std.mem.splitScalar(u8, body, '&'); 2200 while (iter.next()) |pair| { 2201 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 2202 if (std.mem.eql(u8, pair[0..eq], key)) { 2203 return try decodeFormValue(allocator, pair[eq + 1 ..]); 2204 } 2205 } 2206 return null; 2207 } 2208 2209 fn readFormBody(request: *std.http.Server.Request, allocator: std.mem.Allocator) ![]u8 { 2210 var buffer: [256]u8 = undefined; 2211 return request.readerExpectNone(&buffer).allocRemaining(allocator, .limited(65536)); 2212 } 2213 2214 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 2215 var out: std.ArrayList(u8) = .empty; 2216 errdefer out.deinit(allocator); 2217 var i: usize = 0; 2218 while (i < encoded.len) : (i += 1) { 2219 switch (encoded[i]) { 2220 '+' => try out.append(allocator, ' '), 2221 '%' => { 2222 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 2223 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 2224 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 2225 try out.append(allocator, hi * 16 + lo); 2226 i += 2; 2227 }, 2228 else => try out.append(allocator, encoded[i]), 2229 } 2230 } 2231 return try out.toOwnedSlice(allocator); 2232 } 2233 2234 // disk-backed web session store. each login mints a random, opaque token 2235 // (not the user's id) that is stored as a file named by the token hex, whose 2236 // contents are the raw user_id bytes. authenticating a request is a lookup of 2237 // the cookie's token; logout deletes the file, revoking the session. there is 2238 // deliberately no expiry — a session lives until logout. form failures use 2239 // files in the flash subdirectory that the redirected GET consumes. the 2240 // directory is cleared whenever the server starts. 2241 pub const SessionStore = struct { 2242 io: std.Io, 2243 dir: std.Io.Dir, 2244 flash_dir: std.Io.Dir, 2245 auto_login: ?[token_hex_len]u8, 2246 2247 pub const token_hex_len = evt.event_id_size * 2; 2248 2249 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 2250 try data_dir.createDirPath(io, "sessions"); 2251 const dir = try data_dir.openDir(io, "sessions", .{}); 2252 errdefer dir.close(io); 2253 try dir.deleteTree(io, "flash"); 2254 try dir.createDirPath(io, "flash"); 2255 const flash_dir = try dir.openDir(io, "flash", .{}); 2256 errdefer flash_dir.close(io); 2257 const auto_login = blk: { 2258 const file = dir.openFile(io, auto_login_name, .{ .mode = .read_only }) catch break :blk null; 2259 defer file.close(io); 2260 var token: [token_hex_len]u8 = undefined; 2261 var storage: [token_hex_len]u8 = undefined; 2262 var reader = file.reader(io, &storage); 2263 reader.interface.readSliceAll(&token) catch break :blk null; 2264 break :blk token; 2265 }; 2266 return .{ .io = io, .dir = dir, .flash_dir = flash_dir, .auto_login = auto_login }; 2267 } 2268 2269 pub fn deinit(self: SessionStore) void { 2270 self.flash_dir.close(self.io); 2271 self.dir.close(self.io); 2272 } 2273 2274 // mint a new session for user_id, returning the token hex to set as the 2275 // cookie value. 2276 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 2277 var token: [evt.event_id_size]u8 = undefined; 2278 self.io.random(&token); 2279 const token_hex = std.fmt.bytesToHex(token, .lower); 2280 const file = try self.dir.createFile(self.io, &token_hex, .{}); 2281 defer file.close(self.io); 2282 try file.writeStreamingAll(self.io, user_id); 2283 return token_hex; 2284 } 2285 2286 fn createFlash(self: SessionStore, allocator: std.mem.Allocator, value: ui.Session.FormFeedback) ![token_hex_len]u8 { 2287 var token: [evt.event_id_size]u8 = undefined; 2288 self.io.random(&token); 2289 const token_hex = std.fmt.bytesToHex(token, .lower); 2290 const file = try self.flash_dir.createFile(self.io, &token_hex, .{}); 2291 errdefer self.flash_dir.deleteFile(self.io, &token_hex) catch {}; 2292 defer file.close(self.io); 2293 2294 var json: std.Io.Writer.Allocating = .init(allocator); 2295 defer json.deinit(); 2296 try std.json.Stringify.value(value, .{}, &json.writer); 2297 try file.writeStreamingAll(self.io, json.written()); 2298 return token_hex; 2299 } 2300 2301 fn takeFlash(self: SessionStore, allocator: std.mem.Allocator, token_hex: []const u8) ?ui.Session.FormFeedback { 2302 if (!isToken(token_hex)) return null; 2303 const file = self.flash_dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return null; 2304 defer self.flash_dir.deleteFile(self.io, token_hex) catch {}; 2305 defer file.close(self.io); 2306 2307 var storage: [4096]u8 = undefined; 2308 var reader = file.reader(self.io, &storage); 2309 const bytes = reader.interface.allocRemaining(allocator, .limited(512 * 1024)) catch return null; 2310 return std.json.parseFromSliceLeaky(ui.Session.FormFeedback, allocator, bytes, .{}) catch null; 2311 } 2312 2313 // resolve a cookie's token to its user_id. returns false (logged out) for a 2314 // missing, malformed, or unknown token. 2315 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 2316 if (!isToken(token_hex)) return false; 2317 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 2318 defer file.close(self.io); 2319 var storage: [evt.event_id_size]u8 = undefined; 2320 var file_reader = file.reader(self.io, &storage); 2321 file_reader.interface.readSliceAll(out) catch return false; 2322 return true; 2323 } 2324 2325 // revoke a session. a no-op for a missing or malformed token. 2326 pub fn remove(self: SessionStore, token_hex: []const u8) void { 2327 if (!isToken(token_hex)) return; 2328 self.dir.deleteFile(self.io, token_hex) catch {}; 2329 } 2330 2331 // leave `token_hex`'s session for visitors arriving without one. only the 2332 // `try` fixture writes one. the name can't collide with a session token. 2333 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 2334 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 2335 defer file.close(self.io); 2336 try file.writeStreamingAll(self.io, token_hex); 2337 } 2338 2339 pub fn autoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 2340 out.* = self.auto_login orelse return false; 2341 return true; 2342 } 2343 2344 const auto_login_name = "auto-login"; 2345 2346 // a token is exactly token_hex_len hex chars. validating before using the 2347 // value as a path keeps attacker-supplied cookies from escaping the 2348 // sessions dir (e.g. via "/" or ".." bytes). 2349 fn isToken(token_hex: []const u8) bool { 2350 if (token_hex.len != token_hex_len) return false; 2351 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 2352 return true; 2353 } 2354 }; 2355