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