╭─────────────╮ │scroll to top│ ╰─────────────╯ ╭ web.zig ──────────────────────────────────────────────────────╮ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ │ ╰───────────────────────────────────────────────────────────────╯
╭────╮ ╭ clone ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╮ │http│ ssh │ │ ╰────╯ ╰ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ─ ╯
775 for (types) |entry| { 776 if (name.len > entry.ext.len and std.ascii.eqlIgnoreCase(name[name.len - entry.ext.len ..], entry.ext)) return entry.value; 777 } 778 return null; 779 } 780 781 fn respondAttachmentNotFound(request: *std.http.Server.Request) !void { 782 try request.respond("attachment not found", .{ 783 .status = .not_found, 784 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 785 }); 786 } 787 788 fn respondAttachmentParentNotFound(request: *std.http.Server.Request) !void { 789 try request.respond("attachment parent not found", .{ 790 .status = .not_found, 791 .keep_alive = false, 792 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 793 }); 794 } 795 796 // the upload declares its file's name here, since the body is the file itself 797 const attachment_name_header = "x-attachment-name"; 798 799 const AttachParentParts = struct { 800 repo_base: []const u8, 801 id_bytes: [evt.event_id_size]u8, 802 }; 803 804 // what an attachment hangs off: the `<kind>:<id>` segment the form's page ends 805 // with, whatever kind that is 806 fn attachParentParts(base: []const u8) ?AttachParentParts { 807 const id_len = evt.event_id_size * 2; 808 if (base.len < id_len + 1) return null; 809 const head = base[0 .. base.len - id_len]; 810 if (head[head.len - 1] != ':') return null; 811 var id_bytes: [evt.event_id_size]u8 = undefined; 812 _ = std.fmt.hexToBytes(&id_bytes, base[base.len - id_len ..]) catch return null; 813 const segment_at = std.mem.lastIndexOfScalar(u8, head, '/') orelse return null; 814 return .{ .repo_base = head[0..segment_at], .id_bytes = id_bytes }; 815 } 816 817 // attach the posted file to the event the url names, then reload. the file is 818 // the whole request body, so it streams from the socket into the object store 819 // without being buffered. 820 fn handleAttach( 821 io: std.Io, 822 request: *std.http.Server.Request, 823 allocator: std.mem.Allocator, 824 base: []const u8, 825 host: Host, 826 ) !void { 827 // reading the body invalidates the request head's memory, and the url is 828 // still needed to resolve the repo afterward 829 const base_copy = try allocator.dupe(u8, base); 830 defer allocator.free(base_copy); 831 832 const parts = attachParentParts(base_copy) orelse return respondAttachmentParentNotFound(request); 833 834 var author_arena = std.heap.ArenaAllocator.init(allocator); 835 defer author_arena.deinit(); 836 const author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 837 838 const name = (try attachmentName(allocator, request)) orelse return respondUploadError(request, .bad_request, "attachment needs a name"); 839 defer allocator.free(name); 840 if (!evt.Attachment.nameValid(name)) return respondUploadError(request, .bad_request, "invalid attachment name"); 841 842 const size = request.head.content_length orelse return respondUploadError(request, .length_required, "attachments must declare a content length"); 843 if (size == 0) return respondUploadError(request, .bad_request, "attachment is empty"); 844 if (size > evt.Attachment.max_size) return respondUploadError(request, .payload_too_large, "attachment is too large"); 845 846 const parent_id_hex = std.fmt.bytesToHex(parts.id_bytes, .lower); 847 848 var body_buf: [4096]u8 = undefined; 849 const blob: evt.Blob = .{ .name = name, .size = size, .reader = try request.readerExpectContinue(&body_buf) }; 850 851 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondAttachmentParentNotFound(request); 852 defer request_repo.deinit(allocator); 853 const source = request_repo.source; 854 switch (source.repo_kind) { 855 inline else => |repo_kind| { 856 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 857 defer any_repo.deinit(io, allocator); 858 switch (any_repo) { 859 inline else => |*repo| _ = evt.Attachment.create(repo_kind, repo.self_repo_opts, io, allocator, repo, &parent_id_hex, blob, author) catch |err| switch (err) { 860 error.ParentNotFound => return respondAttachmentParentNotFound(request), 861 else => return err, 862 }, 863 } 864 }, 865 } 866 867 // the client reloads the page itself 868 try request.respond("", .{ .status = .no_content, .keep_alive = false }); 869 } 870 871 // the name the upload declares for its file, percent-encoded so it survives a 872 // header 873 fn attachmentName(allocator: std.mem.Allocator, request: *std.http.Server.Request) !?[]u8 { 874 var iter = request.iterateHeaders(); 875 while (iter.next()) |header| { 876 if (!std.ascii.eqlIgnoreCase(header.name, attachment_name_header)) continue; 877 return try decodeFormValue(allocator, header.value); 878 } 879 return null; 880 } 881 882 // an upload that failed leaves the body partly read, so the connection closes 883 fn respondUploadError(request: *std.http.Server.Request, status: std.http.Status, message: []const u8) !void { 884 try request.respond(message, .{ 885 .status = status, 886 .keep_alive = false, 887 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 888 }); 889 } 890 891 // re-emit the comment `parts` names with a new body, in the repo the host 892 // resolves the base to. 893 fn updateComment( 894 io: std.Io, 895 allocator: std.mem.Allocator, 896 host: Host, 897 parts: CommentBaseParts, 898 body: []const u8, 899 author: evt.CommitAuthor, 900 ) !void { 901 const comment_id = parts.comment_id orelse return error.NotFound; 902 const thread_id = std.fmt.bytesToHex(parts.thread_id, .lower); 903 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return error.NotFound; 904 defer request_repo.deinit(allocator); 905 const source = request_repo.source; 906 switch (source.repo_kind) { 907 inline else => |repo_kind| { 908 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 909 defer any_repo.deinit(io, allocator); 910 switch (any_repo) { 911 inline else => |*repo| try evt.Comment.update(repo_kind, repo.self_repo_opts, io, allocator, repo, &thread_id, &comment_id, body, author), 912 } 913 }, 914 } 915 } 916 917 // edit actions share a suffix; the base identifies the event being edited. 918 fn handleEdit( 919 io: std.Io, 920 request: *std.http.Server.Request, 921 allocator: std.mem.Allocator, 922 base: []const u8, 923 host: Host, 924 ) !void { 925 const parts = commentBaseParts(base) orelse return respondRemoveNotFound(request); 926 if (parts.comment_id != null) return handleCommentEdit(io, request, allocator, base, host, parts); 927 return handleTopicEdit(io, request, allocator, base, host, parts); 928 } 929 930 // replace the body of the comment the url names, then redirect to its 931 // permalink. 932 fn handleCommentEdit( 933 io: std.Io, 934 request: *std.http.Server.Request, 935 allocator: std.mem.Allocator, 936 base: []const u8, 937 host: Host, 938 parts: CommentBaseParts, 939 ) !void { 940 var author_arena = std.heap.ArenaAllocator.init(allocator); 941 defer author_arena.deinit(); 942 const author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 943 944 var body_buf: [256]u8 = undefined; 945 const reader = request.readerExpectNone(&body_buf); 946 const posted = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 947 defer allocator.free(posted); 948 const body_crlf = (try parseFormField(allocator, posted, "body")) orelse try allocator.dupe(u8, ""); 949 defer allocator.free(body_crlf); 950 const body = try std.mem.replaceOwned(u8, allocator, body_crlf, "\r\n", "\n"); 951 defer allocator.free(body); 952 953 if (!evt.Comment.fieldsValid(body)) { 954 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 955 defer allocator.free(form_location); 956 try request.respond("", .{ 957 .status = .see_other, 958 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 959 }); 960 return; 961 } 962 963 const not_found = "comment not found"; 964 updateComment(io, allocator, host, parts, body, author) catch |err| switch (err) { 965 error.NotFound => { 966 try request.respond(not_found, .{ 967 .status = .not_found, 968 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 969 }); 970 return; 971 }, 972 else => |e| return e, 973 }; 974 975 try request.respond("", .{ 976 .status = .see_other, 977 .extra_headers = &.{.{ .name = "location", .value = base }}, 978 }); 979 } 980 981 const IssueBaseParts = struct { repo_base: []const u8, id_bytes: [evt.event_id_size]u8 }; 982 fn issueBaseParts(base: []const u8) ?IssueBaseParts { 983 const parts = commentBaseParts(base) orelse return null; 984 if (parts.thread_kind != .issue or parts.comment_id != null) return null; 985 return .{ .repo_base = parts.repo_base, .id_bytes = parts.thread_id }; 986 } 987 988 const RemoveParts = struct { 989 repo_base: []const u8, 990 kind: evt.EventKind, 991 id: [evt.event_id_size]u8, 992 }; 993 994 // split a remove url into the repo and event it names 995 fn removeParts(base: []const u8) ?RemoveParts { 996 if (attachmentRequest(base)) |attachment| { 997 const parent = attachParentParts(attachment.repo_base) orelse return null; 998 return .{ 999 .repo_base = parent.repo_base, 1000 .kind = .attach, 1001 .id = attachment.id, 1002 }; 1003 } 1004 if (commentBaseParts(base)) |thread| return .{ 1005 .repo_base = thread.repo_base, 1006 .kind = if (thread.comment_id != null) .comment else thread.thread_kind, 1007 .id = thread.comment_id orelse thread.thread_id, 1008 }; 1009 return null; 1010 } 1011 1012 // remove the event named by the form's url 1013 fn handleRemove( 1014 io: std.Io, 1015 request: *std.http.Server.Request, 1016 allocator: std.mem.Allocator, 1017 base: []const u8, 1018 host: Host, 1019 ) !void { 1020 const parts = removeParts(base) orelse return respondRemoveNotFound(request); 1021 1022 var author_arena = std.heap.ArenaAllocator.init(allocator); 1023 defer author_arena.deinit(); 1024 const author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 1025 1026 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return respondRemoveNotFound(request); 1027 defer request_repo.deinit(allocator); 1028 const source = request_repo.source; 1029 switch (source.repo_kind) { 1030 inline else => |repo_kind| { 1031 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1032 defer any_repo.deinit(io, allocator); 1033 switch (any_repo) { 1034 inline else => |*repo| evt.remove(.repo, repo_kind, repo.self_repo_opts, io, allocator, repo, &parts.id, parts.kind, author) catch |err| switch (err) { 1035 error.EventNotFound => return respondRemoveNotFound(request), 1036 else => |e| return e, 1037 }, 1038 } 1039 }, 1040 } 1041 1042 const id = std.fmt.bytesToHex(parts.id, .lower); 1043 const location = try std.fmt.allocPrint(allocator, "{s}/event:{s}/kind:{s}", .{ parts.repo_base, &id, @tagName(parts.kind) }); 1044 defer allocator.free(location); 1045 try request.respond("", .{ 1046 .status = .see_other, 1047 .keep_alive = false, 1048 .extra_headers = &.{.{ .name = "location", .value = location }}, 1049 }); 1050 } 1051 1052 fn respondRemoveNotFound(request: *std.http.Server.Request) !void { 1053 try request.respond("event not found", .{ 1054 .status = .not_found, 1055 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1056 }); 1057 } 1058 1059 // re-emit the issue `parts` names with `update` applied, in the repo the 1060 // host resolves the base to. error.NotFound when the base names no repo or 1061 // the id no issue. 1062 fn updateIssue( 1063 io: std.Io, 1064 allocator: std.mem.Allocator, 1065 host: Host, 1066 parts: IssueBaseParts, 1067 update: evt.Issue.Update, 1068 author: evt.CommitAuthor, 1069 ) !void { 1070 const request_repo = (try requestRepoSource(io, allocator, host, parts.repo_base)) orelse return error.NotFound; 1071 defer request_repo.deinit(allocator); 1072 const source = request_repo.source; 1073 switch (source.repo_kind) { 1074 inline else => |repo_kind| { 1075 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1076 defer any_repo.deinit(io, allocator); 1077 switch (any_repo) { 1078 inline else => |*repo| try evt.Issue.update(repo_kind, repo.self_repo_opts, io, allocator, repo, &parts.id_bytes, update, author), 1079 } 1080 }, 1081 } 1082 } 1083 1084 fn updateDiscussion( 1085 io: std.Io, 1086 allocator: std.mem.Allocator, 1087 host: Host, 1088 repo_base: []const u8, 1089 id: *const [evt.event_id_size]u8, 1090 title: []const u8, 1091 tags: []const u8, 1092 description: []const u8, 1093 author: evt.CommitAuthor, 1094 ) !void { 1095 const request_repo = (try requestRepoSource(io, allocator, host, repo_base)) orelse return error.NotFound; 1096 defer request_repo.deinit(allocator); 1097 const source = request_repo.source; 1098 switch (source.repo_kind) { 1099 inline else => |repo_kind| { 1100 var any_repo = try rp.AnyRepo(repo_kind, .{}).open(io, allocator, source.localInitOpts()); 1101 defer any_repo.deinit(io, allocator); 1102 switch (any_repo) { 1103 inline else => |*repo| try evt.Discussion.update(repo_kind, repo.self_repo_opts, io, allocator, repo, id, title, tags, description, author), 1104 } 1105 }, 1106 } 1107 } 1108 1109 // set the status of the issue the url names (base is 1110 // "/repo/<owner>/<name>/issue:<id>", identity elided in local mode) by 1111 // re-emitting its event, then redirect back to it 1112 fn handleIssueStatus( 1113 io: std.Io, 1114 request: *std.http.Server.Request, 1115 allocator: std.mem.Allocator, 1116 base: []const u8, 1117 host: Host, 1118 status: evt.Issue.Status, 1119 ) !void { 1120 const not_found = "issue not found"; 1121 const parts = issueBaseParts(base) orelse { 1122 try request.respond(not_found, .{ 1123 .status = .not_found, 1124 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1125 }); 1126 return; 1127 }; 1128 1129 var author_arena = std.heap.ArenaAllocator.init(allocator); 1130 defer author_arena.deinit(); 1131 const author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 1132 1133 updateIssue(io, allocator, host, parts, .{ .status = status }, author) catch |err| switch (err) { 1134 error.NotFound => { 1135 try request.respond(not_found, .{ 1136 .status = .not_found, 1137 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1138 }); 1139 return; 1140 }, 1141 else => |e| return e, 1142 }; 1143 1144 // like logout, this is a bodyless POST, so close the connection rather than 1145 // letting the keep-alive path try to discard a body that isn't framed. 1146 try request.respond("", .{ 1147 .status = .see_other, 1148 .keep_alive = false, 1149 .extra_headers = &.{.{ .name = "location", .value = base }}, 1150 }); 1151 } 1152 1153 // replace the title, tags and description of an issue or discussion. 1154 fn handleTopicEdit( 1155 io: std.Io, 1156 request: *std.http.Server.Request, 1157 allocator: std.mem.Allocator, 1158 base: []const u8, 1159 host: Host, 1160 parts: CommentBaseParts, 1161 ) !void { 1162 var author_arena = std.heap.ArenaAllocator.init(allocator); 1163 defer author_arena.deinit(); 1164 const author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 1165 1166 var body_buf: [256]u8 = undefined; 1167 const reader = request.readerExpectNone(&body_buf); 1168 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 1169 defer allocator.free(body); 1170 1171 const title = (try parseFormField(allocator, body, "title")) orelse try allocator.dupe(u8, ""); 1172 defer allocator.free(title); 1173 const tags = (try parseFormField(allocator, body, "tags")) orelse try allocator.dupe(u8, ""); 1174 defer allocator.free(tags); 1175 const description_crlf = (try parseFormField(allocator, body, "description")) orelse try allocator.dupe(u8, ""); 1176 defer allocator.free(description_crlf); 1177 // form submission normalizes textarea line breaks to CRLF; store plain 1178 // newlines so the text renders the same on every host 1179 const description = try std.mem.replaceOwned(u8, allocator, description_crlf, "\r\n", "\n"); 1180 defer allocator.free(description); 1181 1182 // invalid fields send the user back to the edit form 1183 const valid = switch (parts.thread_kind) { 1184 .issue => evt.Issue.fieldsValid(title, tags), 1185 .discuss => evt.Discussion.fieldsValid(title, tags), 1186 else => unreachable, 1187 }; 1188 if (!valid) { 1189 const form_location = try std.fmt.allocPrint(allocator, "{s}/edit", .{base}); 1190 defer allocator.free(form_location); 1191 try request.respond("", .{ 1192 .status = .see_other, 1193 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1194 }); 1195 return; 1196 } 1197 1198 const not_found = switch (parts.thread_kind) { 1199 .issue => "issue not found", 1200 .discuss => "discussion not found", 1201 else => unreachable, 1202 }; 1203 (switch (parts.thread_kind) { 1204 .issue => updateIssue(io, allocator, host, .{ .repo_base = parts.repo_base, .id_bytes = parts.thread_id }, .{ .fields = .{ 1205 .title = title, 1206 .tags = tags, 1207 .description = description, 1208 } }, author), 1209 .discuss => updateDiscussion(io, allocator, host, parts.repo_base, &parts.thread_id, title, tags, description, author), 1210 else => unreachable, 1211 }) catch |err| switch (err) { 1212 error.NotFound => { 1213 try request.respond(not_found, .{ 1214 .status = .not_found, 1215 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1216 }); 1217 return; 1218 }, 1219 else => |e| return e, 1220 }; 1221 1222 try request.respond("", .{ 1223 .status = .see_other, 1224 .extra_headers = &.{.{ .name = "location", .value = base }}, 1225 }); 1226 } 1227 1228 // resolve the conflict of the issue the url names (base is 1229 // "/repo/<owner>/<name>/issue:<id>", identity elided in local mode; the 1230 // form posts to "<base>/resolve") 1231 fn handleIssueResolve( 1232 io: std.Io, 1233 request: *std.http.Server.Request, 1234 allocator: std.mem.Allocator, 1235 base: []const u8, 1236 host: Host, 1237 ) !void { 1238 var author_arena = std.heap.ArenaAllocator.init(allocator); 1239 defer author_arena.deinit(); 1240 const author = (try eventAuthor(io, allocator, &author_arena, request, host)) orelse return respondLoginRequired(request); 1241 1242 var body_buf: [256]u8 = undefined; 1243 const reader = request.readerExpectNone(&body_buf); 1244 const body = reader.allocRemaining(allocator, .limited(65536)) catch &[_]u8{}; 1245 defer allocator.free(body); 1246 1247 var field_arena = std.heap.ArenaAllocator.init(allocator); 1248 defer field_arena.deinit(); 1249 const aa = field_arena.allocator(); 1250 const title = try parseFormField(aa, body, "title"); 1251 const tags = try parseFormField(aa, body, "tags"); 1252 1253 // the hunk inputs post as d0, d1, ...; form submission normalizes their 1254 // textarea line breaks to CRLF 1255 var hunks: std.ArrayList([]const u8) = .empty; 1256 var hunk_index: usize = 0; 1257 while (true) : (hunk_index += 1) { 1258 const name = try std.fmt.allocPrint(aa, "d{d}", .{hunk_index}); 1259 const posted = (try parseFormField(aa, body, name)) orelse break; 1260 try hunks.append(aa, try std.mem.replaceOwned(u8, aa, posted, "\r\n", "\n")); 1261 } 1262 1263 const not_found = "issue not found"; 1264 const parts = issueBaseParts(base) orelse { 1265 try request.respond(not_found, .{ 1266 .status = .not_found, 1267 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1268 }); 1269 return; 1270 }; 1271 1272 updateIssue(io, allocator, host, parts, .{ .resolve = .{ 1273 .title = title, 1274 .tags = tags, 1275 .hunks = hunks.items, 1276 } }, author) catch |err| switch (err) { 1277 error.NotFound => { 1278 try request.respond(not_found, .{ 1279 .status = .not_found, 1280 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1281 }); 1282 return; 1283 }, 1284 // invalid fields send the user back to the resolve form 1285 error.InvalidFields => { 1286 const form_location = try std.fmt.allocPrint(allocator, "{s}/resolve", .{base}); 1287 defer allocator.free(form_location); 1288 try request.respond("", .{ 1289 .status = .see_other, 1290 .extra_headers = &.{.{ .name = "location", .value = form_location }}, 1291 }); 1292 return; 1293 }, 1294 else => |e| return e, 1295 }; 1296 1297 try request.respond("", .{ 1298 .status = .see_other, 1299 .extra_headers = &.{.{ .name = "location", .value = base }}, 1300 }); 1301 } 1302 1303 fn handleSync( 1304 io: std.Io, 1305 request: *std.http.Server.Request, 1306 allocator: std.mem.Allocator, 1307 base: []const u8, 1308 source: ui.RepoSource, 1309 ) !void { 1310 if (base.len != 0) { 1311 try request.respond("not found", .{ 1312 .status = .not_found, 1313 .extra_headers = &.{.{ .name = "content-type", .value = "text/plain" }}, 1314 }); 1315 return; 1316 } 1317 1318 var owned_failure: ?[]u8 = null; 1319 defer if (owned_failure) |message| allocator.free(message); 1320 const failure: ?[]const u8 = blk: { 1321 owned_failure = ui.Repo.Events.sync(io, allocator, source) catch |err| break :blk @errorName(err); 1322 break :blk owned_failure; 1323 }; 1324 if (failure) |message| { 1325 var encoded: std.Io.Writer.Allocating = .init(allocator); 1326 defer encoded.deinit(); 1327 try std.Uri.Component.percentEncode(&encoded.writer, message, struct { 1328 fn isUnreserved(c: u8) bool { 1329 return std.ascii.isAlphanumeric(c) or c == '-' or c == '.' or c == '_' or c == '~'; 1330 } 1331 }.isUnreserved); 1332 const cookie = try std.fmt.allocPrint( 1333 allocator, 1334 sync_failure_cookie ++ "={s}; Path=/; HttpOnly; SameSite=Strict", 1335 .{encoded.written()}, 1336 ); 1337 defer allocator.free(cookie); 1338 try request.respond("", .{ 1339 .status = .see_other, 1340 .extra_headers = &.{ 1341 .{ .name = "location", .value = "/events" }, 1342 .{ .name = "set-cookie", .value = cookie }, 1343 }, 1344 }); 1345 return; 1346 } 1347 1348 try request.respond("", .{ 1349 .status = .see_other, 1350 .extra_headers = &.{ 1351 .{ .name = "location", .value = "/events" }, 1352 .{ .name = "set-cookie", .value = sync_failure_cookie ++ "=; Path=/; Max-Age=0" }, 1353 }, 1354 }); 1355 } 1356 1357 fn renderIndexHtml( 1358 io: std.Io, 1359 allocator: std.mem.Allocator, 1360 host: Host, 1361 session_data: ui.Session.Data, 1362 ) ![]const u8 { 1363 const template = (findEmbed("/index.html") orelse return error.MissingIndexAsset).body; 1364 1365 var page_arena = std.heap.ArenaAllocator.init(allocator); 1366 defer page_arena.deinit(); 1367 1368 // the remote admin repo must outlive the page build, since the session's 1369 // moment reads from it. 1370 var repo_maybe: ?rp.Repo(.xit, evt.admin_repo_opts) = null; 1371 defer if (repo_maybe) |*repo| repo.deinit(io, allocator); 1372 1373 var session = switch (host) { 1374 .remote => |remote| blk: { 1375 // open the admin repo to read live user/repo data. 1376 repo_maybe = try rp.Repo(.xit, evt.admin_repo_opts).open(io, allocator, .{ .path = remote.admin_repo_path }); 1377 const repo = if (repo_maybe) |*repo| repo else unreachable; 1378 var session = try ui.Session.init(&page_arena, repo, session_data); 1379 // give the page builders filesystem access to the on-disk repos (a 1380 // sibling "repos" dir next to the admin repo) so the Repo page can 1381 // read its files. 1382 session.repos_dir = try std.fs.path.join(page_arena.allocator(), &.{ std.fs.path.dirname(remote.admin_repo_path) orelse ".", "repos" }); 1383 break :blk session; 1384 }, 1385 .local => |local| ui.Session{ 1386 .data = session_data, 1387 .arena = &page_arena, 1388 .page_arena = &page_arena, 1389 .local = local, 1390 }, 1391 }; 1392 session.io = io; 1393 1394 const snapshot: ui.Snapshot = .{ 1395 .page = try ui.Page.init(session.page_arena, &session, session.data.current_page), 1396 .session = session.data, 1397 }; 1398 var root = try ui.initRoot(allocator, &snapshot.page, &session); 1399 defer root.deinit(allocator); 1400 1401 const content = try generateHtml(allocator, &root); 1402 defer allocator.free(content); 1403 const overlay = try generateOverlay(allocator, &root, &session); 1404 defer allocator.free(overlay); 1405 1406 // serialize the snapshot so the wasm side can parse it back without making 1407 // a second request. it's embedded raw in a <script type="application/json"> 1408 // block, whose content is raw text terminated only by "</script". in json, 1409 // '<' appears solely inside string values, so escaping every '<' (and '>' 1410 // for good measure) to its \uXXXX form yields equivalent json that can't 1411 // break out of the tag. 1412 var json: std.Io.Writer.Allocating = .init(allocator); 1413 defer json.deinit(); 1414 try std.json.Stringify.value(snapshot, .{}, &json.writer); 1415 1416 var json_escaped: std.ArrayList(u8) = .empty; 1417 defer json_escaped.deinit(allocator); 1418 for (json.written()) |c| switch (c) { 1419 '<' => try json_escaped.appendSlice(allocator, "\\u003c"), 1420 '>' => try json_escaped.appendSlice(allocator, "\\u003e"), 1421 else => try json_escaped.append(allocator, c), 1422 }; 1423 1424 var out: std.ArrayList(u8) = .empty; 1425 errdefer out.deinit(allocator); 1426 { 1427 var cursor: usize = 0; 1428 for (&[_]struct { needle: []const u8, replacement: []const u8 }{ 1429 .{ .needle = "{{{ HAXY_HTML }}}", .replacement = content }, 1430 .{ .needle = "{{{ HAXY_OVERLAY }}}", .replacement = overlay }, 1431 .{ .needle = "{{{ HAXY_JSON }}}", .replacement = json_escaped.items }, 1432 }) |sub| { 1433 const idx = std.mem.indexOfPos(u8, template, cursor, sub.needle) orelse return error.MissingTemplateToken; 1434 try out.appendSlice(allocator, template[cursor..idx]); 1435 try out.appendSlice(allocator, sub.replacement); 1436 cursor = idx + sub.needle.len; 1437 } 1438 try out.appendSlice(allocator, template[cursor..]); 1439 } 1440 return try out.toOwnedSlice(allocator); 1441 } 1442 1443 fn findEmbed(request_path: []const u8) ?Embed { 1444 const path = if (std.mem.eql(u8, request_path, "/")) 1445 "index.html" 1446 else if (request_path.len > 1 and request_path[0] == '/') 1447 request_path[1..] 1448 else 1449 return null; 1450 1451 for (embeds) |embed| { 1452 if (std.mem.eql(u8, path, embed.path)) return embed; 1453 } 1454 return null; 1455 } 1456 1457 // emits the TUI grid cells as static HTML. each web-native Scroll becomes its 1458 // own absolutely-positioned, natively-scrollable <div> holding its full content, 1459 // rendered recursively so nested scrolls work. 1460 pub fn generateHtml(allocator: std.mem.Allocator, root: *ui.Widget) ![]const u8 { 1461 const grid = root.getGrid() orelse return error.MissingGrid; 1462 1463 var out: std.ArrayList(u8) = .empty; 1464 errdefer out.deinit(allocator); 1465 1466 try renderPanel(allocator, &out, root.getFocus(), grid); 1467 return try out.toOwnedSlice(allocator); 1468 } 1469 1470 // render one panel — a focus subtree and its content grid — as HTML, recursing 1471 // once per web-native Scroll inside it. the root panel is the whole page; each 1472 // Scroll becomes a nested, natively-scrollable div holding its full content. 1473 // emits the panel's grid cells as text, leaving holes where child scrolls sit, 1474 // then the child scroll divs over those holes. 1475 fn renderPanel(allocator: std.mem.Allocator, output: *std.ArrayList(u8), focus: *Focus, grid: Grid) !void { 1476 // `direct` is this panel's scroll children, each drawn as an overlaid div. 1477 // `excluded` is every focus id that belongs to a scroll (the scroll nodes 1478 // plus their descendants, which the focus tree flattens into this panel's 1479 // children): the cell hit-test below skips them so this panel doesn't claim 1480 // cells that are really rendered inside a child scroll's own panel. 1481 // (scrolls aren't nested in practice, so every scroll child is direct here.) 1482 var direct: std.ArrayList(usize) = .empty; 1483 defer direct.deinit(allocator); 1484 var excluded: std.AutoHashMapUnmanaged(usize, void) = .empty; 1485 defer excluded.deinit(allocator); 1486 { 1487 var it = focus.children.iterator(); 1488 while (it.next()) |e| { 1489 if (e.value_ptr.focus.scroll == null) continue; 1490 try direct.append(allocator, e.key_ptr.*); 1491 try excluded.put(allocator, e.key_ptr.*, {}); 1492 var mit = e.value_ptr.focus.children.iterator(); 1493 while (mit.next()) |m| try excluded.put(allocator, m.key_ptr.*, {}); 1494 } 1495 } 1496 1497 // the HTML element a run of cells is wrapped in, chosen from the cell's 1498 // focusable kind 1499 const CellTag = union(enum) { 1500 span, // clickable focusable cell 1501 a: []const u8, // clickable focusable link 1502 plain, // non-focusable, colored 1503 1504 const a_prefix = "a:"; 1505 // an "in-page" anchor: rendered as a real <a href> so it works with js 1506 // disabled, but crossPageLink ignores it, so with wasm the click just 1507 // moves focus rather than navigating. 1508 const inpage_prefix = "ai:"; 1509 1510 fn init(str: []const u8) @This() { 1511 if (std.mem.startsWith(u8, str, ui.raw_link_prefix)) { 1512 return .{ .a = str[ui.raw_link_prefix.len..] }; 1513 } 1514 if (std.mem.startsWith(u8, str, inpage_prefix)) { 1515 return .{ .a = str[inpage_prefix.len..] }; 1516 } 1517 if (std.mem.startsWith(u8, str, a_prefix)) { 1518 return .{ .a = str[a_prefix.len..] }; 1519 } 1520 return .span; 1521 } 1522 1523 fn writeOpenTag(self: @This(), alloc: std.mem.Allocator, out: *std.ArrayList(u8), id: usize, style_attr: []const u8) !void { 1524 var id_buf: [32]u8 = undefined; 1525 switch (self) { 1526 .span => { 1527 try out.appendSlice(alloc, "<span class=\"clickable\" data-focus-id=\""); 1528 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1529 try out.appendSlice(alloc, "\""); 1530 try out.appendSlice(alloc, style_attr); 1531 try out.appendSlice(alloc, ">"); 1532 }, 1533 .a => |href| { 1534 // tabindex=-1 keeps these out of the browser's tab order 1535 try out.appendSlice(alloc, "<a class=\"clickable\" tabindex=\"-1\" data-focus-id=\""); 1536 try out.appendSlice(alloc, try std.fmt.bufPrint(&id_buf, "{d}", .{id})); 1537 try out.appendSlice(alloc, "\" href=\""); 1538 try appendEscapedHtml(alloc, out, href); 1539 try out.appendSlice(alloc, "\""); 1540 try out.appendSlice(alloc, style_attr); 1541 try out.appendSlice(alloc, ">"); 1542 }, 1543 .plain => { 1544 try out.appendSlice(alloc, "<span"); 1545 try out.appendSlice(alloc, style_attr); 1546 try out.appendSlice(alloc, ">"); 1547 }, 1548 } 1549 } 1550 1551 fn closeTag(self: @This()) []const u8 { 1552 return switch (self) { 1553 .span, .plain => "</span>", 1554 .a => "</a>", 1555 }; 1556 } 1557 }; 1558 1559 // emit this panel's grid as rows of text, coalescing adjacent cells that 1560 // share a focus id and colors into one tag (a clickable span, a link, or a 1561 // plain colored span). cells under a child scroll keep only their background. 1562 for (0..grid.size.height) |y| { 1563 var cur_id: ?usize = null; 1564 var cur_fg: ?Grid.Color = null; 1565 var cur_bg: ?Grid.Color = null; 1566 var open_tag: ?CellTag = null; 1567 var first = true; 1568 for (0..grid.size.width) |x| { 1569 const cell = grid.cells.items[try grid.cells.at(.{ y, x })]; 1570 // a cell covered by a child scroll's viewport is drawn by that scroll's 1571 // own div, so blank its glyph and make it non-clickable here — but keep 1572 // its background, so the backdrop still shows through the scroll's 1573 // transparent div instead of a bare hole. 1574 const covered_by_scroll = blk: { 1575 for (direct.items) |id| { 1576 const r = (focus.children.get(id) orelse continue).rect; 1577 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; 1578 } 1579 break :blk false; 1580 }; 1581 // the focusable cell at (x, y) among this panel's own focusables (skipping 1582 // any that belong to a child scroll, whose cells are drawn in their own 1583 // panel); none for a covered cell. 1584 const cell_id = if (covered_by_scroll) null else blk: { 1585 var iter = focus.children.iterator(); 1586 while (iter.next()) |entry| { 1587 const child = entry.value_ptr.*; 1588 if (!child.focus.focusable) continue; 1589 if (excluded.contains(entry.key_ptr.*)) continue; 1590 const r = child.rect; 1591 if (x >= r.x and y >= r.y and x < r.x + r.size.width and y < r.y + r.size.height) { 1592 break :blk entry.key_ptr.*; 1593 } 1594 } 1595 break :blk null; 1596 }; 1597 const fg = if (covered_by_scroll) null else cell.style.fg; 1598 const bg = cell.style.bg; 1599 1600 if (first or cell_id != cur_id or !colorEql(fg, cur_fg) or !colorEql(bg, cur_bg)) { 1601 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1602 1603 var new_tag: ?CellTag = null; 1604 if (cell_id) |id| { 1605 if (focus.children.get(id)) |child| { 1606 new_tag = switch (child.focus.kind) { 1607 .custom => |custom| CellTag.init(custom), 1608 else => .span, 1609 }; 1610 } 1611 } 1612 if (new_tag == null and (fg != null or bg != null)) new_tag = .plain; 1613 1614 if (new_tag) |t| { 1615 var style_buf: [64]u8 = undefined; 1616 try t.writeOpenTag(allocator, output, cell_id orelse 0, styleAttr(&style_buf, fg, bg)); 1617 } 1618 1619 open_tag = new_tag; 1620 cur_id = cell_id; 1621 cur_fg = fg; 1622 cur_bg = bg; 1623 first = false; 1624 } 1625 1626 if (covered_by_scroll) { 1627 try appendEscapedHtml(allocator, output, " "); 1628 } else if (cell.continuation) { 1629 // the wide rune to the left was emitted 2ch wide, covering this column 1630 } else if (cell.rune) |rune| { 1631 // a double-width rune is pinned inside a 2ch span so the 1632 // fallback glyph's advance width can't shift the rest of the row 1633 const wide = x + 1 < grid.size.width and grid.cells.items[try grid.cells.at(.{ y, x + 1 })].continuation; 1634 if (wide) { 1635 try output.appendSlice(allocator, "<span class=\"w2\">"); 1636 try appendEscapedHtml(allocator, output, rune); 1637 try output.appendSlice(allocator, "</span>"); 1638 } else { 1639 try appendEscapedHtml(allocator, output, rune); 1640 } 1641 } else { 1642 try appendEscapedHtml(allocator, output, " "); 1643 } 1644 } 1645 if (open_tag) |t| try output.appendSlice(allocator, t.closeTag()); 1646 try output.append(allocator, '\n'); 1647 } 1648 1649 // each child scroll becomes a natively-scrollable div positioned over its 1650 // viewport, holding its full content rendered recursively. 1651 for (direct.items) |id| { 1652 const child = focus.children.get(id) orelse continue; 1653 const info = child.focus.scroll orelse continue; 1654 const r = child.rect; 1655 // overflow only on the axes the widget scrolls; `auto` shows a bar only 1656 // when that axis actually overflows. the other axis is clipped (hidden), 1657 // matching how the terminal Scroll handles its non-scrolling axis. 1658 const overflow = switch (info.direction) { 1659 .vert => "overflow-x:hidden;overflow-y:auto", 1660 .horiz => "overflow-x:auto;overflow-y:hidden", 1661 .both => "overflow:auto", 1662 }; 1663 // the id carries a content version so JS preserves the native scroll 1664 // position across re-renders of the same content but resets it when the 1665 // content is replaced — e.g. selecting a different commit. the widget's 1666 // scroll offset (in cells) rides along so JS can apply it when it has no 1667 // preserved position, letting a wasm-side scrollToRect (the files list 1668 // scrolling to its selected row on page load) reach the browser. 1669 var buf: [256]u8 = undefined; 1670 try output.appendSlice(allocator, try std.fmt.bufPrint(&buf, "<div class=\"scroll\" 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, child.focus.version, @tagName(info.direction), info.offset_x, info.offset_y, r.x, r.y, r.size.width, r.size.height, overflow })); 1671 try renderPanel(allocator, output, child.focus, info.content); 1672 try output.appendSlice(allocator, "</div>"); 1673 } 1674 } 1675 1676 // emits the form overlay — one <form> per "form:<url>" focus subtree in the 1677 // widget tree, each wrapping the text inputs and submit button inside it, 1678 // positioned absolutely over the matching grid cells. 1679 pub fn generateOverlay(allocator: std.mem.Allocator, root: *ui.Widget, session: *ui.Session) ![]const u8 { 1680 const root_focus = root.getFocus(); 1681 1682 var out: std.ArrayList(u8) = .empty; 1683 errdefer out.deinit(allocator); 1684 1685 const form_prefix = "form:"; 1686 1687 // Focus.children is an AutoArrayHashMap that preserves insertion order, 1688 // which matches the order widgets were added in code 1689 var iter = root_focus.children.iterator(); 1690 while (iter.next()) |entry| { 1691 const child = entry.value_ptr.*; 1692 const action_url = switch (child.focus.kind) { 1693 .custom => |custom| if (std.mem.startsWith(u8, custom, form_prefix)) 1694 custom[form_prefix.len..] 1695 else 1696 continue, 1697 else => continue, 1698 }; 1699 1700 try out.appendSlice(allocator, "<form action=\""); 1701 try appendEscapedHtml(allocator, &out, action_url); 1702 try out.appendSlice(allocator, "\" method=\"post\""); 1703 // an empty action must not POST — block it and send the input to the TUI instead 1704 if (action_url.len == 0) try out.appendSlice(allocator, " onsubmit=\"event.preventDefault();sendEnter(this);\""); 1705 try out.appendSlice(allocator, ">"); 1706 1707 // form.focus.children was populated by addChild, which flattens the 1708 // whole subtree into one map — so descendants (inputs + the submit 1709 // button) all appear here. positions on form.focus are relative to 1710 // the form, so we look up absolute rects via root_focus for layout. 1711 var inner_iter = child.focus.children.iterator(); 1712 while (inner_iter.next()) |inner_entry| { 1713 const inner_id = inner_entry.key_ptr.*; 1714 const root_child = root_focus.children.get(inner_id) orelse continue; 1715 const r = root_child.rect; 1716 switch (root_child.focus.kind) { 1717 .text_input, .text_input_password => { 1718 const ti = session.text_inputs.get(inner_id) orelse continue; 1719 const inner_left = r.x + 1; 1720 const inner_top = r.y + 1; 1721 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1722 1723 try out.appendSlice(allocator, "<input type=\""); 1724 try out.appendSlice(allocator, if (root_child.focus.kind == .text_input_password) "password" else "text"); 1725 try out.appendSlice(allocator, if (action_url.len == 0) "\" readonly data-focus-id=\"" else "\" data-focus-id=\""); 1726 var id_buf: [32]u8 = undefined; 1727 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1728 if (ti.options.name.len > 0) { 1729 try out.appendSlice(allocator, "\" name=\""); 1730 try appendEscapedHtml(allocator, &out, ti.options.name); 1731 } 1732 // never the live content as the `value`: the browser tracks user 1733 // input natively, and including the wasm-side value here would make 1734 // the overlay HTML differ on every keystroke — that would trip the 1735 // diff in _setOverlay and rebuild the <input>, eating the user's 1736 // caret. a page-constant initial value is safe. 1737 if (session.input_values.get(inner_id)) |value| { 1738 try out.appendSlice(allocator, "\" value=\""); 1739 try appendEscapedHtml(allocator, &out, value); 1740 } 1741 try out.appendSlice(allocator, "\" style=\"left:"); 1742 var pos_buf: [64]u8 = undefined; 1743 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:1em", .{ inner_left, inner_top, inner_width })); 1744 try out.appendSlice(allocator, "\">"); 1745 }, 1746 .text_area => { 1747 const ti = session.text_inputs.get(inner_id) orelse continue; 1748 const inner_left = r.x + 1; 1749 const inner_top = r.y + 1; 1750 const inner_width = if (r.size.width > 2) r.size.width - 2 else 0; 1751 const inner_height = if (r.size.height > 2) r.size.height - 2 else 0; 1752 1753 try out.appendSlice(allocator, "<textarea data-focus-id=\""); 1754 var id_buf: [32]u8 = undefined; 1755 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1756 if (ti.options.name.len > 0) { 1757 try out.appendSlice(allocator, "\" name=\""); 1758 try appendEscapedHtml(allocator, &out, ti.options.name); 1759 } 1760 // like the input above, only a page-constant initial value 1761 // inside: the browser tracks the live value and the 1762 // overlay diff must stay stable across keystrokes 1763 try out.appendSlice(allocator, "\" style=\"left:"); 1764 var pos_buf: [128]u8 = undefined; 1765 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ inner_left, inner_top, inner_width, inner_height })); 1766 // textarea discards the first newline immediately following 1767 // its start tag, so add one of our own so text that begins 1768 // with a newline doesn't lose it 1769 try out.appendSlice(allocator, "\">\n"); 1770 if (session.input_values.get(inner_id)) |value| try appendEscapedHtml(allocator, &out, value); 1771 try out.appendSlice(allocator, "</textarea>"); 1772 }, 1773 .custom => |custom| { 1774 if (std.mem.eql(u8, "submit", custom) or std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 1775 try out.appendSlice(allocator, "<button type=\"submit\" data-focus-id=\""); 1776 var id_buf: [32]u8 = undefined; 1777 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{inner_id})); 1778 if (std.mem.startsWith(u8, custom, ui.submit_action_prefix)) { 1779 try out.appendSlice(allocator, "\" formaction=\""); 1780 try appendEscapedHtml(allocator, &out, custom[ui.submit_action_prefix.len..]); 1781 } 1782 try out.appendSlice(allocator, "\" style=\"left:"); 1783 var pos_buf: [128]u8 = undefined; 1784 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ r.x, r.y, r.size.width, r.size.height })); 1785 try out.appendSlice(allocator, "\"></button>"); 1786 } 1787 }, 1788 else => {}, 1789 } 1790 } 1791 1792 try out.appendSlice(allocator, "</form>"); 1793 } 1794 1795 // a file picker isn't part of a form: it posts its file straight to the url 1796 // in its marker. it sits transparent over the button the tui drew, so 1797 // clicking that button opens the browser's own dialog. 1798 var file_iter = root_focus.children.iterator(); 1799 while (file_iter.next()) |entry| { 1800 const child = entry.value_ptr.*; 1801 const action_url = switch (child.focus.kind) { 1802 .custom => |custom| if (std.mem.startsWith(u8, custom, ui.file_input_prefix)) 1803 custom[ui.file_input_prefix.len..] 1804 else 1805 continue, 1806 else => continue, 1807 }; 1808 const r = child.rect; 1809 1810 try out.appendSlice(allocator, "<input type=\"file\" data-action=\""); 1811 try appendEscapedHtml(allocator, &out, action_url); 1812 try out.appendSlice(allocator, "\" data-focus-id=\""); 1813 var id_buf: [32]u8 = undefined; 1814 try out.appendSlice(allocator, try std.fmt.bufPrint(&id_buf, "{d}", .{entry.key_ptr.*})); 1815 try out.appendSlice(allocator, "\" style=\"opacity:0;left:"); 1816 var pos_buf: [128]u8 = undefined; 1817 try out.appendSlice(allocator, try std.fmt.bufPrint(&pos_buf, "{d}ch;top:{d}em;width:{d}ch;height:{d}em", .{ r.x, r.y, r.size.width, r.size.height })); 1818 try out.appendSlice(allocator, "\">"); 1819 } 1820 1821 return try out.toOwnedSlice(allocator); 1822 } 1823 1824 fn colorEql(a: ?Grid.Color, b: ?Grid.Color) bool { 1825 if (a) |av| return if (b) |bv| av.eql(bv) else false; 1826 return b == null; 1827 } 1828 1829 // builds an HTML ` style="color:#rrggbb;background-color:#rrggbb"` attribute 1830 // from a cell's fg/bg into `buf`, omitting whichever color is unset. returns an 1831 // empty slice when neither is set. 1832 fn styleAttr(buf: []u8, fg: ?Grid.Color, bg: ?Grid.Color) []const u8 { 1833 if (fg == null and bg == null) return buf[0..0]; 1834 const prefix = " style=\""; 1835 @memcpy(buf[0..prefix.len], prefix); 1836 var i: usize = prefix.len; 1837 if (fg) |c| { 1838 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]; 1839 i += s.len; 1840 } 1841 if (bg) |c| { 1842 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]; 1843 i += s.len; 1844 } 1845 buf[i] = '"'; 1846 i += 1; 1847 return buf[0..i]; 1848 } 1849 1850 fn appendEscapedHtml(allocator: std.mem.Allocator, out: *std.ArrayList(u8), input: []const u8) !void { 1851 for (input) |ch| { 1852 switch (ch) { 1853 '&' => try out.appendSlice(allocator, "&amp;"), 1854 '<' => try out.appendSlice(allocator, "&lt;"), 1855 '>' => try out.appendSlice(allocator, "&gt;"), 1856 '"' => try out.appendSlice(allocator, "&quot;"), 1857 '\'' => try out.appendSlice(allocator, "&#39;"), 1858 else => try out.append(allocator, ch), 1859 } 1860 } 1861 } 1862 1863 // --- helpers -------------------------------------------------------------- 1864 1865 fn getCookieValue(request: *std.http.Server.Request, name: []const u8) ?[]const u8 { 1866 var iter = request.iterateHeaders(); 1867 while (iter.next()) |header| { 1868 if (!std.ascii.eqlIgnoreCase(header.name, "cookie")) continue; 1869 var pairs = std.mem.splitScalar(u8, header.value, ';'); 1870 while (pairs.next()) |pair| { 1871 const trimmed = std.mem.trim(u8, pair, " \t"); 1872 const eq = std.mem.indexOfScalar(u8, trimmed, '=') orelse continue; 1873 if (std.mem.eql(u8, trimmed[0..eq], name)) { 1874 return trimmed[eq + 1 ..]; 1875 } 1876 } 1877 } 1878 return null; 1879 } 1880 1881 fn parseFormField(allocator: std.mem.Allocator, body: []const u8, key: []const u8) !?[]u8 { 1882 var iter = std.mem.splitScalar(u8, body, '&'); 1883 while (iter.next()) |pair| { 1884 const eq = std.mem.indexOfScalar(u8, pair, '=') orelse continue; 1885 if (std.mem.eql(u8, pair[0..eq], key)) { 1886 return try decodeFormValue(allocator, pair[eq + 1 ..]); 1887 } 1888 } 1889 return null; 1890 } 1891 1892 fn decodeFormValue(allocator: std.mem.Allocator, encoded: []const u8) ![]u8 { 1893 var out: std.ArrayList(u8) = .empty; 1894 errdefer out.deinit(allocator); 1895 var i: usize = 0; 1896 while (i < encoded.len) : (i += 1) { 1897 switch (encoded[i]) { 1898 '+' => try out.append(allocator, ' '), 1899 '%' => { 1900 if (i + 2 >= encoded.len) return error.InvalidPercentEncoding; 1901 const hi = std.fmt.charToDigit(encoded[i + 1], 16) catch return error.InvalidPercentEncoding; 1902 const lo = std.fmt.charToDigit(encoded[i + 2], 16) catch return error.InvalidPercentEncoding; 1903 try out.append(allocator, hi * 16 + lo); 1904 i += 2; 1905 }, 1906 else => try out.append(allocator, encoded[i]), 1907 } 1908 } 1909 return try out.toOwnedSlice(allocator); 1910 } 1911 1912 // disk-backed web session store. each login mints a random, opaque token 1913 // (not the user's id) that is stored as a file named by the token hex, whose 1914 // contents are the raw user_id bytes. authenticating a request is a lookup of 1915 // the cookie's token; logout deletes the file, revoking the session. there is 1916 // deliberately no expiry — a session lives until logout. 1917 pub const SessionStore = struct { 1918 io: std.Io, 1919 dir: std.Io.Dir, 1920 1921 pub const token_hex_len = evt.event_id_size * 2; 1922 1923 pub fn init(io: std.Io, data_dir: std.Io.Dir) !SessionStore { 1924 try data_dir.createDirPath(io, "sessions"); 1925 const dir = try data_dir.openDir(io, "sessions", .{}); 1926 return .{ .io = io, .dir = dir }; 1927 } 1928 1929 pub fn deinit(self: SessionStore) void { 1930 self.dir.close(self.io); 1931 } 1932 1933 // mint a new session for user_id, returning the token hex to set as the 1934 // cookie value. 1935 pub fn create(self: SessionStore, user_id: *const [evt.event_id_size]u8) ![token_hex_len]u8 { 1936 var token: [evt.event_id_size]u8 = undefined; 1937 self.io.random(&token); 1938 const token_hex = std.fmt.bytesToHex(token, .lower); 1939 const file = try self.dir.createFile(self.io, &token_hex, .{}); 1940 defer file.close(self.io); 1941 try file.writeStreamingAll(self.io, user_id); 1942 return token_hex; 1943 } 1944 1945 // resolve a cookie's token to its user_id. returns false (logged out) for a 1946 // missing, malformed, or unknown token. 1947 pub fn lookup(self: SessionStore, token_hex: []const u8, out: *[evt.event_id_size]u8) bool { 1948 if (!isToken(token_hex)) return false; 1949 const file = self.dir.openFile(self.io, token_hex, .{ .mode = .read_only }) catch return false; 1950 defer file.close(self.io); 1951 var storage: [evt.event_id_size]u8 = undefined; 1952 var file_reader = file.reader(self.io, &storage); 1953 file_reader.interface.readSliceAll(out) catch return false; 1954 return true; 1955 } 1956 1957 // revoke a session. a no-op for a missing or malformed token. 1958 pub fn remove(self: SessionStore, token_hex: []const u8) void { 1959 if (!isToken(token_hex)) return; 1960 self.dir.deleteFile(self.io, token_hex) catch {}; 1961 } 1962 1963 // leave `token_hex`'s session for the next visitor arriving without one. 1964 // only the `try` fixture writes one, and only a debug build honors it. the 1965 // name isn't token-shaped, so it can't collide with a session file. 1966 pub fn offerAutoLogin(self: SessionStore, token_hex: *const [token_hex_len]u8) !void { 1967 const file = try self.dir.createFile(self.io, auto_login_name, .{}); 1968 defer file.close(self.io); 1969 try file.writeStreamingAll(self.io, token_hex); 1970 } 1971 1972 // claim the offered session, if one is there. the delete picks the winner 1973 // of a race, so the offer is only ever taken once. a release build never 1974 // looks, because that would be an extra syscall for every GET request. 1975 pub fn claimAutoLogin(self: SessionStore, out: *[token_hex_len]u8) bool { 1976 if (builtin.mode != .Debug) return false; 1977 { 1978 const file = self.dir.openFile(self.io, auto_login_name, .{ .mode = .read_only }) catch return false; 1979 defer file.close(self.io); 1980 var storage: [token_hex_len]u8 = undefined; 1981 var file_reader = file.reader(self.io, &storage); 1982 file_reader.interface.readSliceAll(out) catch return false; 1983 } 1984 self.dir.deleteFile(self.io, auto_login_name) catch return false; 1985 return true; 1986 } 1987 1988 const auto_login_name = "auto-login"; 1989 1990 // a token is exactly token_hex_len hex chars. validating before using the 1991 // value as a path keeps attacker-supplied cookies from escaping the 1992 // sessions dir (e.g. via "/" or ".." bytes). 1993 fn isToken(token_hex: []const u8) bool { 1994 if (token_hex.len != token_hex_len) return false; 1995 for (token_hex) |c| if (!std.ascii.isHex(c)) return false; 1996 return true; 1997 } 1998 }; 1999