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