~ knotless Search/
↑↓ move↵ open⇧↵ all results

zat.dev/zds

atproto pds · mirror of https://tangled.org/zat.dev/zds

0
0
2414 lines · 132.9 KB Raw History
//! Experimental permissioned-data XRPC handlers.
//!
//! This module is intentionally feature-flagged at dispatch and should remain
//! the only HTTP entry point for `com.atproto.space.*`,
//! `com.atproto.memberspace.*`, and `com.atproto.managedspace.*` behavior
//! while the upstream protocol is still experimental.

const std = @import("std");
const clock = @import("../core/clock.zig");
const auth = @import("../auth/tokens.zig");
const config = @import("../core/config.zig");
const http_api = @import("../http/api.zig");
const log = @import("../core/log.zig");
const client_attestation = @import("../internal/client_attestation.zig");
const service_auth = @import("../internal/service_auth.zig");
const space_policy = @import("../internal/space_policy.zig");
const outbound = @import("../internal/outbound.zig");
const scopes = @import("../internal/scopes.zig");
const store = @import("../storage/store.zig");
const zat = @import("zat");

const http = std.http;

const check_access_method = "com.atproto.managedspace.checkAccess";
const star_content_type = "application/vnd.dasl.star";
const notify_credentials_revoked_method = "com.atproto.space.notifyCredentialsRevoked";
const notify_repo_update_method = "com.atproto.space.notifyRepoUpdate";
const notify_space_update_method = "com.atproto.space.notifySpaceUpdate";
const confirm_registration_method = "com.atproto.space.confirmRegistration";

pub fn dispatch(request: *http_api.Request) !void {
    if (!config.permissionedData()) {
        return http_api.xrpcError(
            request,
            .not_implemented,
            "MethodNotImplemented",
            "Permissioned data is experimental and disabled on this PDS",
        );
    }

    const method = xrpcMethod(request.url.raw) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid XRPC path");
    };

    if (std.mem.eql(u8, method, "com.atproto.space.createSpace")) return createSpace(request);
    if (std.mem.eql(u8, method, "com.atproto.space.updateSpace")) return updateSpace(request);
    if (std.mem.eql(u8, method, "com.atproto.space.getSpace")) return getSpace(request);
    if (std.mem.eql(u8, method, "com.atproto.space.deleteSpace")) return deleteSpace(request);
    if (std.mem.eql(u8, method, "com.atproto.space.removeWriter")) return removeWriter(request);
    if (std.mem.eql(u8, method, "com.atproto.space.clearRecords")) return clearRecords(request);
    if (std.mem.eql(u8, method, "com.atproto.space.exportSpaceMeta")) return exportSpaceMeta(request);
    if (std.mem.eql(u8, method, "com.atproto.space.importSpaceMeta")) return importSpaceMeta(request);
    if (std.mem.eql(u8, method, "com.atproto.space.importRepo")) return importSpaceRepo(request);
    if (std.mem.eql(u8, method, "com.atproto.space.listSpaces")) return listSpaces(request);
    if (std.mem.eql(u8, method, "com.atproto.space.listWriters")) return listWriters(request);
    if (std.mem.eql(u8, method, "com.atproto.space.getDelegationToken")) return getDelegationToken(request);
    if (std.mem.eql(u8, method, "com.atproto.space.createRecord")) return createRecord(request);
    if (std.mem.eql(u8, method, "com.atproto.space.putRecord")) return putRecord(request);
    if (std.mem.eql(u8, method, "com.atproto.space.deleteRecord")) return deleteRecord(request);
    if (std.mem.eql(u8, method, "com.atproto.space.applyWrites")) return applyWrites(request);
    if (std.mem.eql(u8, method, "com.atproto.space.getRecord")) return getRecord(request);
    if (std.mem.eql(u8, method, "com.atproto.space.listRecords")) return listRecords(request);
    if (std.mem.eql(u8, method, "com.atproto.space.getBlob")) return getBlob(request);
    if (std.mem.eql(u8, method, "com.atproto.space.listBlobs")) return listBlobs(request);
    if (std.mem.eql(u8, method, "com.atproto.space.getLatestCommit")) return getLatestCommit(request);
    if (std.mem.eql(u8, method, "com.atproto.space.getRepo")) return getRepo(request);
    if (std.mem.eql(u8, method, "com.atproto.space.listRepoOps")) return listRepoOps(request);
    if (std.mem.eql(u8, method, "com.atproto.space.authorizeSpaceSync")) return authorizeSpaceSync(request);
    if (std.mem.eql(u8, method, notify_credentials_revoked_method)) return notifyCredentialsRevoked(request);
    if (std.mem.eql(u8, method, notify_repo_update_method)) return notifyRepoUpdate(request);
    if (std.mem.eql(u8, method, "com.atproto.memberspace.putMembers")) return changeMembers(request, .put);
    if (std.mem.eql(u8, method, "com.atproto.memberspace.removeMembers")) return changeMembers(request, .remove);
    if (std.mem.eql(u8, method, "com.atproto.memberspace.listMembers")) return listMembers(request);
    if (std.mem.eql(u8, method, check_access_method)) return checkAccess(request);

    return http_api.xrpcError(
        request,
        .not_implemented,
        "MethodNotImplemented",
        "Permissioned data is enabled but this method is not implemented yet",
    );
}

fn createSpace(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const auth_ctx = requireActiveAccount(request, allocator) catch return;
    const parsed = parseBody(request, allocator, 64 * 1024) catch |err| switch (err) {
        error.HandledResponse => return,
        else => return err,
    };
    const input = parsed.value;
    const authority = auth_ctx.account.did;
    const space_type = zat.json.getString(input, "spaceType") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing spaceType");
    };
    const skey = zat.json.getString(input, "skey") orelse try store.generateRkey(allocator);
    try requireSpaceScope(request, auth_ctx.oauth_scope, space_type, authority, skey, .manage_create, null);
    const policy_value = jsonField(input, "policy") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing policy");
    const policy = space_policy.fromInput(allocator, policy_value) catch |err| return rejectPolicy(request, err);

    const space = store.createSpace(allocator, .{
        .actor_did = authority,
        .authority_did = authority,
        .space_type = space_type,
        .skey = skey,
        .is_authority = true,
        .policy = policy,
    }) catch |err| switch (err) {
        error.InvalidRepoPath => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid authority"),
        error.InvalidCollection => return http_api.xrpcError(request, .bad_request, "InvalidType", "Invalid space type"),
        error.InvalidRecordKey => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid skey"),
        error.InvalidRefreshSession => return http_api.xrpcError(request, .bad_request, "SpaceAlreadyExists", "Space already exists"),
        else => return err,
    };
    if (space_policy.isPolicyPublished(policy)) notifyAuthorityWrite(allocator, auth_ctx.account, space.uri);

    const body = try std.fmt.allocPrint(allocator, "{{\"space\":{f}}}", .{std.json.fmt(space.uri, .{})});
    return http_api.json(request, .ok, body);
}

/// Owner-only: the policy is the authority's own state, so a space credential
/// does not reach it. A policy can publish itself to readers instead.
fn getSpace(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const auth_ctx = requireAccount(request, allocator) catch return;
    var space_buf: [1024]u8 = undefined;
    const space = http_api.queryParam(request.url.raw, "space", &space_buf) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    };
    const policy = try requireSpaceOwner(request, allocator, auth_ctx, space, .read_self);
    return http_api.json(request, .ok, try std.fmt.allocPrint(allocator, "{{\"space\":{f},\"policy\":{s}}}", .{
        std.json.fmt(space, .{}),
        try space_policy.toJson(allocator, policy),
    }));
}

fn listSpaces(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const auth_ctx = requireExportAccount(request, allocator) catch return;
    var did_buf: [256]u8 = undefined;
    const maybe_did = http_api.queryParam(request.url.raw, "spaceDid", &did_buf);
    if (maybe_did) |did| {
        if (zat.Did.parse(did) == null) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid spaceDid");
    }
    var type_buf: [320]u8 = undefined;
    const maybe_type = http_api.queryParam(request.url.raw, "spaceType", &type_buf);
    if (maybe_type) |space_type| {
        if (zat.Nsid.parse(space_type) == null) return http_api.xrpcError(request, .bad_request, "InvalidType", "Invalid space type");
    }
    if (auth_ctx.oauth_scope) |scope_text| {
        if (!scopes.spaceAllows(scope_text, .read, maybe_type orelse "*", maybe_did orelse "*", "*", null)) {
            return http_api.xrpcError(request, .forbidden, "InsufficientScope", "OAuth token does not grant the requested space operation");
        }
    }
    var cursor_buf: [1024]u8 = undefined;
    const maybe_cursor = http_api.queryParam(request.url.raw, "cursor", &cursor_buf);
    if (maybe_cursor) |cursor| if (parseSpaceUri(cursor) == null) return invalidCursor(request);
    const spaces = try store.listSpaces(allocator, auth_ctx.account.did, maybe_did, maybe_type, maybe_cursor, http_api.queryLimit(request.url.raw, 50));

    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try out.writer.writeAll("{\"spaces\":[");
    for (spaces, 0..) |space, idx| {
        if (idx != 0) try out.writer.writeByte(',');
        try out.writer.print("{{\"space\":{f}", .{std.json.fmt(space.uri, .{})});
        const state = try store.getSpaceRepoState(allocator, space.uri, auth_ctx.account.did);
        if (state.rev) |rev| if (state.set_hash) |set_hash| {
            const digest = (try zat.space.LtHash.fromBytes(set_hash)).digest();
            try out.writer.print(",\"repoRev\":{f},\"data\":", .{std.json.fmt(rev, .{})});
            try zat.cbor.toJson(&out.writer, .{ .bytes = &digest });
        };
        if (space.is_authority) {
            if (try store.latestSpaceRev(allocator, space.uri)) |space_rev| try out.writer.print(",\"spaceRev\":{f}", .{std.json.fmt(space_rev, .{})});
        }
        try out.writer.writeByte('}');
    }
    try out.writer.writeByte(']');
    if (spaces.len > 0) {
        try out.writer.print(",\"cursor\":{f}", .{std.json.fmt(spaces[spaces.len - 1].uri, .{})});
    }
    try out.writer.writeByte('}');
    return http_api.json(request, .ok, out.written());
}

fn listWriters(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    var space_buf: [1024]u8 = undefined;
    const space = http_api.queryParam(request.url.raw, "space", &space_buf) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    };
    const parsed = parseSpaceUri(space) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid space URI");
    requireActiveAuthority(request, parsed.space_did) catch return;
    _ = requireSpaceCredential(request, allocator, space, null) catch return;
    var cursor_buf: [256]u8 = undefined;
    const maybe_cursor = http_api.queryParam(request.url.raw, "cursor", &cursor_buf);
    const limit = pageLimit(request.url.raw, 100, 1000);
    const repos = store.listSpaceWriters(allocator, space, maybe_cursor, limit) catch |err| switch (err) {
        error.RepoNotFound => return http_api.xrpcError(request, .bad_request, "SpaceNotFound", "Space not found"),
        else => return err,
    };
    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try out.writer.writeAll("{\"repos\":[");
    for (repos, 0..) |repo, idx| {
        if (idx != 0) try out.writer.writeByte(',');
        const change: WriterChange = if (repo.removed) .removed else .{ .write = .{ .rev = repo.rev, .hash = repo.hash } };
        try out.writer.writeAll(try writerUpdateJson(allocator, repo.repo_did, change, .{ .space_rev = repo.space_rev, .prev_space_rev = null }));
    }
    try out.writer.writeByte(']');
    if (repos.len > 0) try out.writer.print(",\"cursor\":{f}", .{std.json.fmt(repos[repos.len - 1].space_rev, .{})});
    try out.writer.writeByte('}');
    return http_api.json(request, .ok, out.written());
}

const MemberMutation = enum { put, remove };

const max_member_changes = 100;

/// putMembers and removeMembers: up to 100 members (or DIDs) in one commit.
fn changeMembers(request: *http_api.Request, mutation: MemberMutation) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireActiveAccount(request, allocator) catch return;
    const parsed_body = parseBody(request, allocator, 64 * 1024) catch |err| switch (err) {
        error.HandledResponse => return,
        else => return err,
    };
    const input = parsed_body.value;
    const space = zat.json.getString(input, "space") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    const field = switch (mutation) {
        .put => "members",
        .remove => "dids",
    };
    const items = switch (jsonField(input, field) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing members")) {
        .array => |array| array.items,
        else => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Expected an array"),
    };
    if (items.len > max_member_changes) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "At most 100 entries");
    var changes: std.ArrayList(store.MemberChange) = .empty;
    for (items) |item| {
        try changes.append(allocator, switch (mutation) {
            .put => .{
                .did = zat.json.getString(item, "did") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Each member needs a did"),
                .access = .{
                    .read = requiredBool(item, "read") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "read must be a boolean"),
                    .write = requiredBool(item, "write") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "write must be a boolean"),
                },
            },
            .remove => .{
                .did = switch (item) {
                    .string => |did| did,
                    else => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "dids must be strings"),
                },
                .access = null,
            },
        });
    }
    _ = try requireSpaceOwner(request, allocator, auth_ctx, space, .manage_update);
    const result = store.changeSpaceMembers(allocator, space, changes.items) catch |err| switch (err) {
        error.InvalidRepoPath => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid DID"),
        error.RepoNotFound => return spaceNotFound(request),
        error.PolicyMismatch => return policyMismatch(request),
        else => return err,
    };
    if (result.changed) notifyAuthorityWrite(allocator, auth_ctx.account, space);
    for (result.removed_writers) |removed| forwardSpaceUpdate(allocator, space, removed.repo_did, .removed, removed.update);
    return http_api.json(request, .ok, "{}");
}

fn listMembers(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireAccount(request, allocator) catch return;
    var space_buf: [1024]u8 = undefined;
    const space = http_api.queryParam(request.url.raw, "space", &space_buf) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    _ = try requireSpaceOwner(request, allocator, auth_ctx, space, .read_self);
    var cursor_buf: [256]u8 = undefined;
    const maybe_cursor = http_api.queryParam(request.url.raw, "cursor", &cursor_buf);
    if (maybe_cursor) |cursor| if (zat.Did.parse(cursor) == null) return invalidCursor(request);
    const members = store.listSpaceMembers(allocator, space, maybe_cursor, pageLimit(request.url.raw, 100, 1000)) catch |err| switch (err) {
        error.RepoNotFound => return spaceNotFound(request),
        error.PolicyMismatch => return policyMismatch(request),
        else => return err,
    };
    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try out.writer.writeAll("{\"members\":[");
    for (members, 0..) |entry, idx| {
        if (idx != 0) try out.writer.writeByte(',');
        try out.writer.print("{{\"did\":{f},\"read\":{},\"write\":{}}}", .{ std.json.fmt(entry.did, .{}), entry.read, entry.write });
    }
    try out.writer.writeByte(']');
    if (members.len > 0) try out.writer.print(",\"cursor\":{f}", .{std.json.fmt(members[members.len - 1].did, .{})});
    try out.writer.writeByte('}');
    return http_api.json(request, .ok, out.written());
}

/// `repo` is optional and the answer covers read and write. This PDS is not a
/// managing app, so it refuses both.
fn checkAccess(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    var space_buf: [1024]u8 = undefined;
    const space = http_api.queryParam(request.url.raw, "space", &space_buf) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    const parsed = parseSpaceUri(space) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid space URI");
    var repo_buf: [256]u8 = undefined;
    if (http_api.queryParam(request.url.raw, "repo", &repo_buf)) |repo| {
        if (zat.Did.parse(repo) == null) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid repo DID");
    }
    const service = requireServiceAuth(request, allocator, check_access_method) catch return;
    if (!std.mem.eql(u8, service.issuer_did, parsed.space_did)) {
        return http_api.xrpcError(request, .unauthorized, "InvalidToken", "JWT issuer must be the space authority DID");
    }
    if (!serviceAudienceMatchesPds(service.audience)) {
        return http_api.xrpcError(request, .unauthorized, "BadJwtAudience", "JWT audience does not identify this service");
    }
    return http_api.json(request, .ok, "{\"read\":false,\"write\":false}");
}

fn updateSpace(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireActiveAccount(request, allocator) catch return;
    const parsed_body = parseBody(request, allocator, 64 * 1024) catch |err| switch (err) {
        error.HandledResponse => return,
        else => return err,
    };
    const input = parsed_body.value;
    const space = zat.json.getString(input, "space") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    const policy_value = jsonField(input, "policy") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing policy");
    _ = try requireSpaceOwner(request, allocator, auth_ctx, space, .manage_update);
    const policy = space_policy.fromInput(allocator, policy_value) catch |err| return rejectPolicy(request, err);
    const changed = store.updateSpacePolicy(allocator, space, policy) catch |err| switch (err) {
        error.RepoNotFound => return spaceNotFound(request),
        else => return err,
    };
    if (changed) notifyAuthorityWrite(allocator, auth_ctx.account, space);
    return http_api.json(request, .ok, "{}");
}

fn deleteSpace(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireActiveAccount(request, allocator) catch return;
    const parsed_body = parseBody(request, allocator, 16 * 1024) catch |err| switch (err) {
        error.HandledResponse => return,
        else => return err,
    };
    const space = zat.json.getString(parsed_body.value, "space") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    const parsed = parseSpaceUri(space) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid space URI");
    if (!std.mem.eql(u8, parsed.space_did, auth_ctx.account.did)) return notSpaceOwner(request);
    try requireSpaceScope(request, auth_ctx.oauth_scope, parsed.space_type, parsed.space_did, parsed.skey, .manage_delete, null);
    const existing = try store.getSpace(allocator, auth_ctx.account.did, space);
    if (existing == null) return spaceNotFound(request);
    if (!existing.?.is_authority) return notSpaceOwner(request);
    if (existing.?.deleted_at != null) return http_api.json(request, .ok, "{}");
    try store.markSpaceDeleted(auth_ctx.account.did, space);
    try store.purgeAuthoritySpaceData(space, auth_ctx.account.did);
    return http_api.json(request, .ok, "{}");
}

/// Drops an account from the writer set at the next space revision. Syncers are
/// told, it is listed as removed, and its next authorized write adds it back.
fn removeWriter(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireActiveAccount(request, allocator) catch return;
    const parsed_body = parseBody(request, allocator, 16 * 1024) catch |err| switch (err) {
        error.HandledResponse => return,
        else => return err,
    };
    const input = parsed_body.value;
    const space = zat.json.getString(input, "space") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    const writer = zat.json.getString(input, "repo") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing repo");
    if (zat.Did.parse(writer) == null) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid DID");
    _ = try requireSpaceOwner(request, allocator, auth_ctx, space, .manage_update);
    const removed = store.removeSpaceWriter(allocator, space, writer) catch |err| switch (err) {
        error.RepoNotFound => return spaceNotFound(request),
        else => return err,
    };
    if (removed) |update| forwardSpaceUpdate(allocator, space, writer, .removed, update);
    return http_api.json(request, .ok, "{}");
}

const ClearScope = struct {
    scope: []const u8,
    space: zat.space.SpaceUri,

    fn allows(context: *const anyopaque, collection: []const u8) bool {
        const self: *const ClearScope = @ptrCast(@alignCast(context));
        return scopes.spaceAllows(self.scope, .delete, self.space.space_type, self.space.space_did, self.space.skey, collection);
    }
};

/// Deletes every record in the caller's repo in the space. Under OAuth the
/// caller needs a delete grant for each collection it holds records in, apart
/// from the published configuration the authority's repo keeps.
fn clearRecords(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireActiveAccount(request, allocator) catch return;
    const parsed_body = parseBody(request, allocator, 16 * 1024) catch |err| switch (err) {
        error.HandledResponse => return,
        else => return err,
    };
    const input = parsed_body.value;
    const space = zat.json.getString(input, "space") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    const repo = zat.json.getString(input, "repo") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing repo");
    if (!std.mem.eql(u8, repo, auth_ctx.account.did)) return http_api.xrpcError(request, .forbidden, "InvalidRepo", "repo must match authenticated user");
    const parsed = parseSpaceUri(space) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid space URI");
    const clear_scope: ?ClearScope = if (auth_ctx.oauth_scope) |scope| .{ .scope = try resolveWriteScopes(request, allocator, scope, parsed.space_type), .space = parsed } else null;
    const check: ?store.CollectionCheck = if (clear_scope) |*held| .{ .context = held, .allows = ClearScope.allows } else null;
    const cleared = store.clearSpaceRecords(allocator, space, repo, check) catch |err| switch (err) {
        error.InsufficientScope => return http_api.xrpcError(request, .forbidden, "InsufficientScope", "OAuth token does not grant delete for every collection in the repo"),
        error.RepoNotFound => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid space URI"),
        else => return err,
    };
    if (cleared) {
        const state = try store.getSpaceRepoState(allocator, space, repo);
        fireNotifyRepoUpdateForState(allocator, auth_ctx.account, space, repo, state) catch {};
    }
    return http_api.json(request, .ok, "{}");
}

fn notifyAuthorityWrite(allocator: std.mem.Allocator, account: auth.Account, space: []const u8) void {
    const state = store.getSpaceRepoState(allocator, space, account.did) catch return;
    fireNotifyRepoUpdateForState(allocator, account, space, account.did, state) catch {};
}

const max_import_bytes = 128 * 1024 * 1024;

/// Owner-only, as for getSpace: the archive is the authority's own state.
fn exportSpaceMeta(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireExportAccount(request, allocator) catch return;
    var space_buf: [1024]u8 = undefined;
    const space = http_api.queryParam(request.url.raw, "space", &space_buf) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    _ = try requireSpaceOwner(request, allocator, auth_ctx, space, .read_self);
    const meta = store.exportSpaceMeta(allocator, space) catch |err| switch (err) {
        error.RepoNotFound => return spaceNotFound(request),
        else => return err,
    };
    const policy_value = try std.json.parseFromSliceLeaky(std.json.Value, allocator, try space_policy.toJson(allocator, meta.policy), .{});
    var state: std.ArrayList(zat.space.archive.SpaceMetaEntry) = .empty;
    for (meta.members) |member| {
        try state.append(allocator, .{
            .key = try std.fmt.allocPrint(allocator, space_policy.member_collection ++ "/{s}", .{try space_policy.didToRecordKey(allocator, member.did)}),
            .value = .{ .map = try allocator.dupe(zat.cbor.Value.MapEntry, &.{
                .{ .key = "$type", .value = .{ .text = space_policy.member_collection } },
                .{ .key = "read", .value = .{ .boolean = member.read } },
                .{ .key = "write", .value = .{ .boolean = member.write } },
            }) },
        });
    }
    var writers: std.ArrayList(zat.space.archive.SpaceMetaWriter) = .empty;
    for (meta.writers) |writer| {
        if (writer.hash.len != zat.space.lthash.digest_bytes) continue;
        try writers.append(allocator, .{ .did = writer.repo_did, .repo_rev = writer.rev, .data = writer.hash[0..zat.space.lthash.digest_bytes].*, .space_rev = writer.space_rev });
    }
    const body = try zat.space.archive.writeSpaceMetaStar(allocator, space, try store.recordValueFromJson(allocator, policy_value), state.items, writers.items);
    const headers = [_]http.Header{
        .{ .name = "content-type", .value = star_content_type },
        .{ .name = "access-control-allow-origin", .value = "*" },
    };
    return http_api.respond(request, .ok, body, &headers);
}

/// Imports replace a whole space or repo, so they take the account's own
/// session or OAuth, never an app password, and an account the host still serves.
fn requireImportAccount(request: *http_api.Request, allocator: std.mem.Allocator) !http_api.BearerAccount {
    const auth_ctx = try requireAccount(request, allocator);
    if (auth_ctx.app_password) {
        try http_api.xrpcError(request, .unauthorized, "InvalidToken", "Imports need the account's own session, not an app password");
        return error.HandledResponse;
    }
    try http_api.requireActiveAccount(request, auth_ctx.account.did, .takedown);
    return auth_ctx;
}

/// Archives arrive as `application/vnd.dasl.star`, as the import lexicons
/// declare; any other encoding is refused before the body is read.
fn readImportBody(request: *http_api.Request, allocator: std.mem.Allocator) ![]const u8 {
    if (!isStarContentType(http_api.headerValue(request, "content-type"))) {
        try http_api.xrpcError(request, .bad_request, "InvalidRequest", "Wrong request encoding (Content-Type): expected " ++ star_content_type);
        return error.HandledResponse;
    }
    return http_api.readBodyAlloc(request, allocator, max_import_bytes) catch |err| switch (err) {
        error.BodyTooLarge => {
            try http_api.xrpcError(request, .payload_too_large, "InvalidRequest", "Archive is too large");
            return error.HandledResponse;
        },
        else => return err,
    };
}

fn isStarContentType(maybe_value: ?[]const u8) bool {
    const value = maybe_value orelse return false;
    const mime = std.mem.trim(u8, value[0 .. std.mem.indexOfScalar(u8, value, ';') orelse value.len], " \t");
    return std.ascii.eqlIgnoreCase(mime, star_content_type);
}

fn invalidArchive(request: *http_api.Request, error_name: []const u8, err: anyerror) !void {
    var buf: [160]u8 = undefined;
    const message = std.fmt.bufPrint(&buf, "Invalid STAR: {s}", .{@errorName(err)}) catch "Invalid STAR";
    return http_api.xrpcError(request, .bad_request, error_name, message);
}

/// Import a space exported by its authority's previous host, replacing what
/// this host held for it. Must come before the authority's own importRepo.
fn importSpaceMeta(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireImportAccount(request, allocator) catch return;
    const body = readImportBody(request, allocator) catch return;
    var archive = zat.space.archive.readSpaceMetaStar(allocator, body) catch |err| return invalidArchive(request, "InvalidSpaceMeta", err);
    defer archive.deinit();
    const parsed = parseSpaceUri(archive.space) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid space URI");
    try requireSpaceScope(request, auth_ctx.oauth_scope, parsed.space_type, parsed.space_did, parsed.skey, .manage_create, null);
    try requireSpaceScope(request, auth_ctx.oauth_scope, parsed.space_type, parsed.space_did, parsed.skey, .manage_update, null);
    if (!std.mem.eql(u8, parsed.space_did, auth_ctx.account.did)) return notSpaceOwner(request);

    const policy_value = try std.json.parseFromSliceLeaky(std.json.Value, allocator, try zat.cbor.toJsonAlloc(allocator, archive.policy), .{});
    const policy = space_policy.fromInput(allocator, policy_value) catch |err| return rejectPolicy(request, err);
    var members: std.ArrayList(store.ImportedSpaceMember) = .empty;
    for (archive.policy_state) |entry| {
        const member = memberFromState(allocator, policy, entry) catch {
            var buf: [400]u8 = undefined;
            return http_api.xrpcError(request, .bad_request, "InvalidSpaceMeta", std.fmt.bufPrint(&buf, "Unrecognized policy state: {s}", .{entry.key}) catch "Unrecognized policy state");
        };
        try members.append(allocator, member);
    }
    var writers: std.ArrayList(store.SpaceWriterState) = .empty;
    for (archive.writers) |writer| {
        try writers.append(allocator, .{ .repo_did = writer.did, .hash = try allocator.dupe(u8, &writer.data), .rev = writer.repo_rev, .space_rev = writer.space_rev });
    }
    store.importSpaceMeta(allocator, archive.space, policy, members.items, writers.items) catch |err| switch (err) {
        error.PolicyMismatch, error.InvalidRepoPath => return http_api.xrpcError(request, .bad_request, "InvalidSpaceMeta", "Unrecognized policy state"),
        else => return err,
    };
    return http_api.json(request, .ok, "{}");
}

fn memberFromState(allocator: std.mem.Allocator, policy: space_policy.Policy, entry: zat.space.archive.SpaceMetaEntry) !store.ImportedSpaceMember {
    if (policy != .member) return error.UnrecognizedPolicyState;
    const prefix = space_policy.member_collection ++ "/";
    if (!std.mem.startsWith(u8, entry.key, prefix)) return error.UnrecognizedPolicyState;
    const did = try space_policy.recordKeyToDid(allocator, entry.key[prefix.len..]);
    if (zat.Did.parse(did) == null) return error.UnrecognizedPolicyState;
    if (entry.value.getString("$type")) |kind| if (!std.mem.eql(u8, kind, space_policy.member_collection)) return error.UnrecognizedPolicyState;
    const read = entry.value.get("read") orelse return error.UnrecognizedPolicyState;
    const write = entry.value.get("write") orelse return error.UnrecognizedPolicyState;
    if (read != .boolean or write != .boolean) return error.UnrecognizedPolicyState;
    return .{ .did = did, .access = .{ .read = read.boolean, .write = write.boolean } };
}

/// Import the authenticated account's repo in a space from its previous repo
/// host. Records are taken as they are, including published policy and member
/// records, and the repo gets a new rev with the same data.
fn importSpaceRepo(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireImportAccount(request, allocator) catch return;
    const body = readImportBody(request, allocator) catch return;
    var repo = zat.space.archive.readRepoStar(allocator, body) catch |err| return invalidArchive(request, "InvalidRepoFile", err);
    defer repo.deinit();
    if (!std.mem.eql(u8, repo.commit.repo, auth_ctx.account.did)) {
        return http_api.xrpcError(request, .bad_request, "RepoMismatch", "Repo does not match the authenticated account");
    }
    const parsed = parseSpaceUri(repo.commit.space) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid space URI");
    var records: std.ArrayList(store.ImportedSpaceRecord) = .empty;
    for (repo.records) |block| {
        const slash = std.mem.indexOfScalar(u8, block.path, '/').?;
        const collection = block.path[0..slash];
        const rkey = block.path[slash + 1 ..];
        try requireSpaceScope(request, auth_ctx.oauth_scope, parsed.space_type, parsed.space_did, parsed.skey, .create, collection);
        const value_json = try zat.cbor.toJsonAlloc(allocator, try zat.cbor.decodeAll(allocator, block.data));
        const value = try std.json.parseFromSliceLeaky(std.json.Value, allocator, value_json, .{});
        const prepared = prepareSpaceRecord(request, allocator, collection, rkey, value) catch |err| switch (err) {
            error.HandledResponse => return,
            else => return err,
        };
        if (!std.mem.eql(u8, prepared.cid, try block.cid.toString(allocator))) {
            var buf: [400]u8 = undefined;
            return http_api.xrpcError(request, .bad_request, "InvalidRepoFile", std.fmt.bufPrint(&buf, "Invalid STAR: record is not canonical DRISL at {s}", .{block.path}) catch "Invalid STAR");
        }
        try records.append(allocator, .{ .collection = collection, .rkey = rkey, .prepared = prepared });
    }
    store.importSpaceRepo(allocator, repo.commit.space, repo.commit.repo, records.items, repo.commit.data) catch |err| switch (err) {
        error.RepoNotFound => return spaceNotFound(request),
        error.InvalidRepoIndex => return http_api.xrpcError(request, .bad_request, "InvalidRepoFile", "Invalid STAR: records do not fold to the commit data"),
        else => return err,
    };
    return http_api.json(request, .ok, "{}");
}

fn getDelegationToken(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireActiveAccount(request, allocator) catch return;
    var space_buf: [1024]u8 = undefined;
    const space = http_api.queryParam(request.url.raw, "space", &space_buf) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    const parsed = parseSpaceUri(space) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid space URI");
    try requireSpaceScope(request, auth_ctx.oauth_scope, parsed.space_type, parsed.space_did, parsed.skey, .read, null);
    var keypair = store.signingKeypair(auth_ctx.account.did) catch return http_api.xrpcError(request, .not_found, "RepoNotFound", "Signing key not found");
    const token = try zat.space.token.create(allocator, store.currentIo(), .delegation, &keypair, .{
        .iss = auth_ctx.account.did,
        .sub = space,
        .aud = try zat.space.spaceHostAud(allocator, parsed.space_did),
        .iat = clock.nowSeconds(),
    });
    return http_api.json(request, .ok, try std.fmt.allocPrint(allocator, "{{\"token\":{f}}}", .{std.json.fmt(token, .{})}));
}

fn createRecord(request: *http_api.Request) !void {
    return writeSpaceRecord(request, .create);
}

fn putRecord(request: *http_api.Request) !void {
    return writeSpaceRecord(request, .put);
}

const WriteMode = enum { create, put };

fn deleteRecord(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireActiveAccount(request, allocator) catch return;
    const parsed_body = parseBody(request, allocator, 64 * 1024) catch |err| switch (err) {
        error.HandledResponse => return,
        else => return err,
    };
    const input = parsed_body.value;
    const space = zat.json.getString(input, "space") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    const repo = zat.json.getString(input, "repo") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing repo");
    if (!std.mem.eql(u8, repo, auth_ctx.account.did)) return http_api.xrpcError(request, .forbidden, "InvalidRepo", "repo must match authenticated user");
    const collection = zat.json.getString(input, "collection") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing collection");
    const rkey = zat.json.getString(input, "rkey") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing rkey");
    if (space_policy.isPublishedCollection(collection)) return rejectPublishedCollection(request, collection);
    requireSpaceAccess(request, allocator, auth_ctx, space, .delete, collection) catch return;
    store.deleteSpaceRecord(allocator, space, repo, collection, rkey) catch |err| switch (err) {
        error.RepoNotFound => return http_api.xrpcError(request, .bad_request, "SpaceNotFound", "Space not found"),
        error.MissingRecord => {},
        error.InvalidRefreshSession => return http_api.xrpcError(request, .bad_request, "RecordAlreadyExists", "Record already exists"),
        else => return err,
    };
    const state = try store.getSpaceRepoState(allocator, space, repo);
    fireNotifyRepoUpdateForState(allocator, auth_ctx.account, space, repo, state) catch {};
    return http_api.json(request, .ok, "{}");
}

fn applyWrites(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const auth_ctx = requireActiveAccount(request, allocator) catch return;
    const parsed_body = parseBody(request, allocator, 8 * 1024 * 1024) catch |err| switch (err) {
        error.HandledResponse => return,
        else => return err,
    };
    const input = parsed_body.value;
    const space = zat.json.getString(input, "space") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    const repo = zat.json.getString(input, "repo") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing repo");
    if (!std.mem.eql(u8, repo, auth_ctx.account.did)) return http_api.xrpcError(request, .forbidden, "InvalidRepo", "repo must match authenticated user");
    const writes_value = switch (input) {
        .object => |object| object.get("writes") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing writes"),
        else => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid body"),
    };
    if (writes_value != .array) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "writes must be an array");
    var ops: std.ArrayList(store.SpaceWriteOp) = .empty;
    for (writes_value.array.items) |write| {
        const write_type = zat.json.getString(write, "$type") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "write missing $type");
        const collection = zat.json.getString(write, "collection") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "write missing collection");
        if (space_policy.isPublishedCollection(collection)) return rejectPublishedCollection(request, collection);
        if (std.mem.endsWith(u8, write_type, "#create")) {
            requireSpaceAccess(request, allocator, auth_ctx, space, .create, collection) catch return;
            const rkey = zat.json.getString(write, "rkey") orelse try store.generateRkey(allocator);
            const value = switch (write) {
                .object => |object| object.get("value") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "create missing value"),
                else => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid write"),
            };
            const prepared = try prepareSpaceRecord(request, allocator, collection, rkey, value);
            try ops.append(allocator, .{ .create = .{ .collection = collection, .rkey = rkey, .prepared = prepared } });
        } else if (std.mem.endsWith(u8, write_type, "#update")) {
            requireSpaceAccess(request, allocator, auth_ctx, space, .update, collection) catch return;
            const rkey = zat.json.getString(write, "rkey") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "update missing rkey");
            const value = switch (write) {
                .object => |object| object.get("value") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "update missing value"),
                else => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid write"),
            };
            const prepared = try prepareSpaceRecord(request, allocator, collection, rkey, value);
            try ops.append(allocator, .{ .update = .{ .collection = collection, .rkey = rkey, .prepared = prepared } });
        } else if (std.mem.endsWith(u8, write_type, "#delete")) {
            requireSpaceAccess(request, allocator, auth_ctx, space, .delete, collection) catch return;
            const rkey = zat.json.getString(write, "rkey") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "delete missing rkey");
            try ops.append(allocator, .{ .delete = .{ .collection = collection, .rkey = rkey } });
        } else {
            return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Unknown write type");
        }
    }
    const results = store.applySpaceWrites(allocator, space, repo, ops.items) catch |err| switch (err) {
        error.RepoNotFound => return http_api.xrpcError(request, .bad_request, "SpaceNotFound", "Space not found"),
        error.MissingRecord => return http_api.xrpcError(request, .not_found, "RecordNotFound", "Record not found"),
        error.InvalidRefreshSession => return http_api.xrpcError(request, .bad_request, "RecordAlreadyExists", "Record already exists"),
        else => return err,
    };
    const state = try store.getSpaceRepoState(allocator, space, repo);
    fireNotifyRepoUpdateForState(allocator, auth_ctx.account, space, repo, state) catch {};
    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try out.writer.writeAll("{\"results\":[");
    for (results, 0..) |result, idx| {
        if (idx != 0) try out.writer.writeByte(',');
        switch (result) {
            .create => |record| try out.writer.print("{{\"$type\":\"com.atproto.space.applyWrites#createResult\",\"uri\":{f},\"cid\":{f}}}", .{ std.json.fmt(try record.uri(allocator), .{}), std.json.fmt(record.cid, .{}) }),
            .update => |record| try out.writer.print("{{\"$type\":\"com.atproto.space.applyWrites#updateResult\",\"uri\":{f},\"cid\":{f}}}", .{ std.json.fmt(try record.uri(allocator), .{}), std.json.fmt(record.cid, .{}) }),
            .delete => try out.writer.writeAll("{\"$type\":\"com.atproto.space.applyWrites#deleteResult\"}"),
        }
    }
    try out.writer.writeAll("]}");
    return http_api.json(request, .ok, out.written());
}

fn writeSpaceRecord(request: *http_api.Request, mode: WriteMode) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const auth_ctx = requireActiveAccount(request, allocator) catch return;
    const parsed = parseBody(request, allocator, 4 * 1024 * 1024) catch |err| switch (err) {
        error.HandledResponse => return,
        else => return err,
    };
    const input = parsed.value;
    const space = zat.json.getString(input, "space") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    };
    const repo = zat.json.getString(input, "repo") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing repo");
    };
    if (!std.mem.eql(u8, repo, auth_ctx.account.did)) {
        return http_api.xrpcError(request, .forbidden, "InvalidRepo", "repo must match authenticated user");
    }
    const collection = zat.json.getString(input, "collection") orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing collection");
    };
    if (space_policy.isPublishedCollection(collection)) return rejectPublishedCollection(request, collection);
    switch (mode) {
        .create => requireSpaceAccess(request, allocator, auth_ctx, space, .create, collection) catch return,
        .put => {
            requireSpaceAccess(request, allocator, auth_ctx, space, .create, collection) catch return;
            requireSpaceAccess(request, allocator, auth_ctx, space, .update, collection) catch return;
        },
    }
    const rkey = zat.json.getString(input, "rkey") orelse switch (mode) {
        .create => try store.generateRkey(allocator),
        .put => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing rkey"),
    };
    const record = recordBodyValue(input) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing record");
    };
    const prepared = store.prepareRecordValue(allocator, collection, rkey, record) catch |err| switch (err) {
        error.InvalidCollection => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid collection"),
        error.InvalidRecordKey => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid rkey"),
        error.InvalidRecordType => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid record type"),
        error.InvalidDagCbor => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "record is outside the atproto data model"),
        error.RecordTooLarge => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "record exceeds 1048576 encoded bytes"),
        else => return err,
    };
    const stored = switch (mode) {
        .create => store.createSpaceRecord(allocator, space, repo, collection, rkey, prepared),
        .put => store.putSpaceRecord(allocator, space, repo, collection, rkey, prepared),
    } catch |err| switch (err) {
        error.RepoNotFound => return http_api.xrpcError(request, .bad_request, "SpaceNotFound", "Space not found"),
        error.InvalidRefreshSession => return http_api.xrpcError(request, .bad_request, "RecordAlreadyExists", "Record already exists"),
        error.MissingRecord => return http_api.xrpcError(request, .bad_request, "RecordNotFound", "Record not found"),
        else => return err,
    };
    const state = try store.getSpaceRepoState(allocator, space, repo);
    fireNotifyRepoUpdateForState(allocator, auth_ctx.account, space, repo, state) catch {};
    const uri = try stored.uri(allocator);
    const body = try std.fmt.allocPrint(
        allocator,
        "{{\"uri\":{f},\"cid\":{f}}}",
        .{ std.json.fmt(uri, .{}), std.json.fmt(stored.cid, .{}) },
    );
    return http_api.json(request, .ok, body);
}

fn getRecord(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    const params = recordParams(request, allocator) catch |err| switch (err) {
        error.HandledResponse => return,
        else => return err,
    };
    const read_auth = requireReadAccess(request, allocator, params.space, params.repo, params.collection, false) catch return;
    const mac = requireSpaceMac(request, allocator, read_auth, params.repo, .record) catch return;
    const record = (try store.getSpaceRecord(allocator, params.space, params.repo, params.collection, params.rkey)) orelse {
        return http_api.xrpcError(request, .not_found, "RecordNotFound", "Record not found");
    };
    const uri = try record.uri(allocator);
    const body = try std.fmt.allocPrint(
        allocator,
        "{{\"uri\":{f},\"cid\":{f},\"value\":{s}}}",
        .{ std.json.fmt(uri, .{}), std.json.fmt(record.cid, .{}), record.value_json },
    );
    try http_api.json(request, .ok, body);
    if (mac) |owed| try setSpaceMacHeaders(try zat.space.mac.createRecordMacHeaders(allocator, uri, record.cid, owed.request, &owed.secret));
}

fn listRecords(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    var space_buf: [1024]u8 = undefined;
    const space = http_api.queryParam(request.url.raw, "space", &space_buf) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    };
    var repo_buf: [256]u8 = undefined;
    const repo = http_api.queryParam(request.url.raw, "repo", &repo_buf) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing repo");
    };
    var collection_buf: [320]u8 = undefined;
    const maybe_collection = http_api.queryParam(request.url.raw, "collection", &collection_buf);
    _ = requireReadAccess(request, allocator, space, repo, maybe_collection, false) catch return;
    var cursor_buf: [1024]u8 = undefined;
    const maybe_cursor = http_api.queryParam(request.url.raw, "cursor", &cursor_buf);
    if (maybe_cursor) |cursor| if (!validRecordCursor(cursor)) return invalidCursor(request);
    var exclude_values_buf: [8]u8 = undefined;
    const exclude_values = if (http_api.queryParam(request.url.raw, "excludeValues", &exclude_values_buf)) |value|
        std.mem.eql(u8, value, "true")
    else
        false;

    const records = try store.listSpaceRecords(
        allocator,
        space,
        repo,
        maybe_collection,
        maybe_cursor,
        http_api.queryLimit(request.url.raw, 50),
        !exclude_values,
    );
    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try out.writer.writeAll("{\"records\":[");
    for (records, 0..) |record, idx| {
        if (idx != 0) try out.writer.writeByte(',');
        try out.writer.print(
            "{{\"collection\":{f},\"rkey\":{f},\"cid\":{f}",
            .{ std.json.fmt(record.collection, .{}), std.json.fmt(record.rkey, .{}), std.json.fmt(record.cid, .{}) },
        );
        if (record.value_json) |value_json| {
            try out.writer.print(",\"value\":{s}", .{value_json});
        }
        try out.writer.writeByte('}');
    }
    try out.writer.writeByte(']');
    if (records.len > 0) {
        const last = records[records.len - 1];
        try out.writer.print(",\"cursor\":{f}", .{std.json.fmt(try std.fmt.allocPrint(allocator, "{s}/{s}", .{ last.collection, last.rkey }), .{})});
    }
    try out.writer.writeByte('}');
    return http_api.json(request, .ok, out.written());
}

fn getBlob(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    var space_buf: [1024]u8 = undefined;
    const space = http_api.queryParam(request.url.raw, "space", &space_buf) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    };
    var repo_buf: [256]u8 = undefined;
    const repo = http_api.queryParam(request.url.raw, "repo", &repo_buf) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing repo");
    };
    var cid_buf: [256]u8 = undefined;
    const cid = http_api.queryParam(request.url.raw, "cid", &cid_buf) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing cid");
    };
    _ = requireReadAccess(request, allocator, space, repo, null, true) catch return;
    if (!try store.permissionedBlobReferenced(space, repo, cid)) {
        return http_api.xrpcError(request, .not_found, "BlobNotFound", "Blob not found");
    }
    const blob = store.getBlob(allocator, repo, cid) orelse {
        return http_api.xrpcError(request, .not_found, "BlobNotFound", "Blob not found");
    };
    return writeBlobResponse(request, allocator, cid, blob);
}

fn listBlobs(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();

    var space_buf: [1024]u8 = undefined;
    const space = http_api.queryParam(request.url.raw, "space", &space_buf) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    };
    var repo_buf: [256]u8 = undefined;
    const repo = http_api.queryParam(request.url.raw, "repo", &repo_buf) orelse {
        return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing repo");
    };
    _ = requireReadAccess(request, allocator, space, repo, null, true) catch return;

    var cursor_buf: [256]u8 = undefined;
    const cursor = http_api.queryParam(request.url.raw, "cursor", &cursor_buf);
    const limit = listBlobsLimit(request) catch return;
    const cids = try store.listPermissionedBlobs(allocator, space, repo, cursor, limit);

    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try out.writer.writeAll("{\"cids\":[");
    for (cids, 0..) |cid, idx| {
        if (idx != 0) try out.writer.writeByte(',');
        try out.writer.print("{f}", .{std.json.fmt(cid, .{})});
    }
    try out.writer.writeByte(']');
    if (cids.len == limit and cids.len > 0) {
        try out.writer.print(",\"cursor\":{f}", .{std.json.fmt(cids[cids.len - 1], .{})});
    }
    try out.writer.writeByte('}');
    return http_api.json(request, .ok, out.written());
}

fn getLatestCommit(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    var space_buf: [1024]u8 = undefined;
    const space = http_api.queryParam(request.url.raw, "space", &space_buf) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    var repo_buf: [256]u8 = undefined;
    const repo = http_api.queryParam(request.url.raw, "repo", &repo_buf) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing repo");
    const read_auth = requireReadAccess(request, allocator, space, repo, null, false) catch return;
    const mac = requireSpaceMac(request, allocator, read_auth, repo, .commit) catch return;
    const state = try store.getSpaceRepoState(allocator, space, repo);
    const commit = (try spaceCommit(space, repo, state)) orelse {
        return http_api.xrpcError(request, .not_found, "RepoNotFound", "Permissioned repo not found");
    };
    try http_api.json(request, .ok, try std.fmt.allocPrint(allocator, "{{\"commit\":{s}}}", .{try zat.space.archive.commitJson(allocator, commit)}));
    if (mac) |owed| try setCommitMac(allocator, owed, commit);
}

fn getRepo(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    var space_buf: [1024]u8 = undefined;
    const space = http_api.queryParam(request.url.raw, "space", &space_buf) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    var repo_buf: [256]u8 = undefined;
    const repo = http_api.queryParam(request.url.raw, "repo", &repo_buf) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing repo");
    const read_auth = requireReadAccess(request, allocator, space, repo, null, true) catch return;
    const mac = requireSpaceMac(request, allocator, read_auth, repo, .commit) catch return;

    if ((try store.findAccount(allocator, repo)) == null) {
        return http_api.xrpcError(request, .not_found, "RepoNotFound", "Repo not found");
    }
    const state = try store.getSpaceRepoState(allocator, space, repo);
    const commit = (try spaceCommit(space, repo, state)) orelse {
        return http_api.xrpcError(request, .not_found, "RepoNotFound", "Permissioned repo not found");
    };
    const records = try store.loadSpaceRepoBlocks(allocator, space, repo);
    const body = try zat.space.archive.writeRepoStar(allocator, commit, records);
    const headers = [_]http.Header{
        .{ .name = "content-type", .value = star_content_type },
        .{ .name = "access-control-allow-origin", .value = "*" },
        .{ .name = "access-control-allow-private-network", .value = "true" },
        .{ .name = "connection", .value = "close" },
    };
    try http_api.respond(request, .ok, body, &headers);
    if (mac) |owed| try setCommitMac(allocator, owed, commit);
}

fn listRepoOps(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    var space_buf: [1024]u8 = undefined;
    const space = http_api.queryParam(request.url.raw, "space", &space_buf) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    var repo_buf: [256]u8 = undefined;
    const repo = http_api.queryParam(request.url.raw, "repo", &repo_buf) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing repo");
    const read_auth = requireReadAccess(request, allocator, space, repo, null, false) catch return;
    const mac = requireSpaceMac(request, allocator, read_auth, repo, .commit) catch return;
    var since_buf: [128]u8 = undefined;
    const since = http_api.queryParam(request.url.raw, "since", &since_buf);
    if (since) |rev| if (zat.Tid.parse(rev) == null) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "since must be a TID");
    var exclude_values_buf: [8]u8 = undefined;
    const exclude_values = if (http_api.queryParam(request.url.raw, "excludeValues", &exclude_values_buf)) |value|
        std.mem.eql(u8, value, "true")
    else
        false;
    var cursor_buf: [160]u8 = undefined;
    const cursor: ?store.OplogCursor = if (http_api.queryParam(request.url.raw, "cursor", &cursor_buf)) |raw|
        parseOplogCursor(raw) orelse return invalidCursor(request)
    else
        null;
    const limit = pageLimit(request.url.raw, 100, 1000);
    const ops = try store.listSpaceRecordOplog(allocator, space, repo, since, cursor, limit, !exclude_values);
    const state = try store.getSpaceRepoState(allocator, space, repo);
    // Every page carries the repo's current commit; a syncer checks it against
    // its running set hash once it has applied the last page.
    const head = (try spaceCommit(space, repo, state)) orelse {
        return http_api.xrpcError(request, .not_found, "RepoNotFound", "Permissioned repo not found");
    };
    var out: std.Io.Writer.Allocating = .init(allocator);
    defer out.deinit();
    try out.writer.writeAll("{\"ops\":[");
    for (ops, 0..) |op, idx| {
        if (idx != 0) try out.writer.writeByte(',');
        try out.writer.print(
            "{{\"rev\":{f},\"collection\":{f},\"rkey\":{f},\"cid\":",
            .{ std.json.fmt(op.rev, .{}), std.json.fmt(op.collection, .{}), std.json.fmt(op.rkey, .{}) },
        );
        if (op.cid) |cid_value| try out.writer.print("{f}", .{std.json.fmt(cid_value, .{})}) else try out.writer.writeAll("null");
        try out.writer.writeAll(",\"prev\":");
        if (op.prev) |prev_value| try out.writer.print("{f}", .{std.json.fmt(prev_value, .{})}) else try out.writer.writeAll("null");
        if (op.value_json) |value_json| try out.writer.print(",\"value\":{s}", .{value_json});
        try out.writer.writeByte('}');
    }
    try out.writer.writeByte(']');
    // A full page may not be the last; one that ends exactly on the last op
    // costs the syncer one more request.
    if (ops.len == limit) {
        const last = ops[ops.len - 1];
        try out.writer.print(",\"cursor\":\"{s}/{d}\"", .{ last.rev, last.idx });
    }
    try out.writer.print(",\"commit\":{s}}}", .{try zat.space.archive.commitJson(allocator, head)});
    try http_api.json(request, .ok, out.written());
    if (mac) |owed| try setCommitMac(allocator, owed, head);
}

/// Issues a space credential, and reports the space's current revision so a
/// syncer can tell whether it missed an update.
fn authorizeSpaceSync(request: *http_api.Request) !void {
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const parsed_body = parseBody(request, allocator, 32 * 1024) catch |err| switch (err) {
        error.HandledResponse => return,
        else => return err,
    };
    const input = parsed_body.value;
    const space = zat.json.getString(input, "space") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    const credential_kid = zat.json.getString(input, "credentialKey") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing credentialKey");
    if (!isP256DidKey(allocator, credential_kid)) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "credentialKey must be a P-256 did:key");
    const parsed = parseSpaceUri(space) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid space URI");
    const notify = parseNotify(request, input) catch return;
    requireActiveAuthority(request, parsed.space_did) catch return;
    // Answered before the request's authorization is checked: a public space's
    // syncer may hold no delegation token, and this is how a syncer that missed
    // the deletion notice learns of it.
    if (try store.spaceDeleted(parsed.space_did, space)) {
        return http_api.xrpcError(request, .bad_request, "SpaceDeleted", "Space has been deleted");
    }
    const delegation: ?zat.space.token.Claims = if (zat.json.getString(input, "delegationToken")) |token| blk: {
        const unverified = zat.space.token.parse(allocator, .delegation, token) catch {
            return http_api.xrpcError(request, .bad_request, "InvalidDelegationToken", "Invalid delegation token");
        };
        const public_key = service_auth.signingKey(allocator, unverified.claims.iss, "#atproto") catch {
            return http_api.xrpcError(request, .bad_gateway, "DidResolutionFailed", "could not resolve delegation token issuer did");
        };
        const verified = zat.space.token.verify(allocator, .delegation, token, .{
            .signing_key = try didKey(allocator, public_key),
            .now = clock.nowSeconds(),
        }) catch {
            return http_api.xrpcError(request, .bad_request, "InvalidDelegationToken", "Invalid delegation token");
        };
        if (!std.mem.eql(u8, verified.claims.sub, space)) return http_api.xrpcError(request, .bad_request, "InvalidDelegationToken", "Delegation token subject does not match requested space");
        const audience_did = zat.space.token.spaceDidFromAud(verified.claims.aud.?) orelse "";
        if (!std.mem.eql(u8, audience_did, parsed.space_did)) return http_api.xrpcError(request, .bad_request, "InvalidDelegationToken", "Delegation token audience does not match the space authority");
        break :blk verified.claims;
    } else null;
    const config_row = (try store.getSpace(allocator, parsed.space_did, space)) orelse return spaceNotFound(request);
    const policy = (if (config_row.is_authority) try config_row.policy(allocator) else null) orelse return spaceNotFound(request);
    const attestation_claims: ?client_attestation.Claims = if (zat.json.getString(input, "clientAttestation")) |attestation| blk: {
        const audience = try zat.space.spaceHostAud(allocator, parsed.space_did);
        break :blk client_attestation.verify(allocator, store.currentIo(), attestation, audience) catch {
            return http_api.xrpcError(request, .unauthorized, "InvalidClientAttestation", "Client attestation verification failed");
        };
    } else null;
    const attested_client_id = if (attestation_claims) |claims| claims.client_id else null;
    // The user goes first, and a refused user is answered as though the space
    // does not exist, so a refusal discloses nothing about it. Without a
    // delegation token only a public-read memberspace issues.
    const decided = if (delegation) |verified|
        spacePolicyAllowsRequester(allocator, config_row, policy, verified.iss, .read, attested_client_id)
    else switch (policy) {
        // The lexicon review has a managed space ask its app even without a
        // delegation token, with no repo; the app decides on anonymous reads.
        .managed => |managed| managingAppAllowsRequester(allocator, config_row, managed.managing_app, null, .read, attested_client_id),
        else => space_policy.isPublicRead(policy),
    };
    // Not a refusal: no credential, and the registration stays.
    const user_authorized = decided catch |err| switch (err) {
        error.UpstreamFailure => return upstreamFailure(request),
        else => return err,
    };
    // A refusal withdraws the registration the request carries, so a syncer that
    // lost access stops hearing about the space. Failures that are not a
    // refusal, such as the authority's takedown, leave it be.
    if (!user_authorized) {
        if (notify) |registration| try store.removeNotifyRegistration(space, registration);
        return spaceNotFound(request);
    }
    if (!space_policy.isAppAuthorized(policy, attested_client_id)) {
        if (notify) |registration| try store.removeNotifyRegistration(space, registration);
        return http_api.xrpcError(request, .bad_request, "AppNotAuthorized", "Application not authorized for this space");
    }
    // Confirmed before the one-use tokens are spent, so an unconfirmed
    // registration does not cost the syncer its delegation.
    if (notify) |registration| if (!try store.notifyRegistrationExists(space, registration)) {
        confirmRegistration(allocator, space, registration) catch {
            return http_api.xrpcError(request, .bad_request, "RegistrationNotConfirmed", "Notify endpoint did not confirm the registration");
        };
    };
    const delegation_replay: ?store.SpaceReplayToken = if (delegation) |verified| .{ .jti = verified.jti, .expires_at = verified.exp } else null;
    const attestation_replay: ?store.SpaceReplayToken = if (attestation_claims) |claims| .{ .jti = claims.jti, .expires_at = claims.exp } else null;
    if (!try store.consumeSpaceCredentialExchange(delegation_replay, attestation_replay)) {
        return http_api.xrpcError(request, .bad_request, "InvalidDelegationToken", "Credential exchange token has already been used");
    }
    var keypair = store.signingKeypair(parsed.space_did) catch return http_api.xrpcError(request, .not_found, "RepoNotFound", "Authority signing key not found");
    const issued_at = clock.nowSeconds();
    const credential = try zat.space.token.create(allocator, store.currentIo(), .credential, &keypair, .{
        .iss = parsed.space_did,
        .sub = space,
        .cnf_kid = credential_kid,
        .iat = issued_at,
    });
    // Each authorization renews the registration to its credential's expiry,
    // so a syncer that keeps reauthorizing stays registered.
    if (notify) |registration| store.putNotifyRegistration(space, registration, issued_at + zat.space.token.Type.credential.lifetime()) catch |err| switch (err) {
        error.RepoNotFound => return http_api.xrpcError(request, .bad_request, "SpaceDeleted", "Space has been deleted"),
        else => return err,
    };
    // Read after registering, so every update past this revision is notified.
    var out: std.Io.Writer.Allocating = .init(allocator);
    try out.writer.print("{{\"credential\":{f}", .{std.json.fmt(credential, .{})});
    // Omitted before the space's first update.
    if (try store.latestSpaceRev(allocator, space)) |space_rev| try out.writer.print(",\"spaceRev\":{f}", .{std.json.fmt(space_rev, .{})});
    try out.writer.writeByte('}');
    return http_api.json(request, .ok, out.written());
}

/// The optional `notify` of authorizeSpaceSync: an endpoint to call
/// notifySpaceUpdate on, and the opaque token that identifies the
/// registration with it.
fn parseNotify(request: *http_api.Request, input: std.json.Value) !?store.NotifyRegistration {
    const notify = jsonField(input, "notify") orelse return null;
    const invalid = struct {
        fn reply(req: *http_api.Request, message: []const u8) !?store.NotifyRegistration {
            try http_api.xrpcError(req, .bad_request, "InvalidRequest", message);
            return error.HandledResponse;
        }
    }.reply;
    if (notify != .object) return invalid(request, "notify must be an object");
    const endpoint = zat.json.getString(notify, "endpoint") orelse return invalid(request, "notify.endpoint must be a string");
    const token = zat.json.getString(notify, "token") orelse return invalid(request, "notify.token must be a string");
    if (token.len > max_notify_token_bytes) return invalid(request, "notify.token is longer than 512 characters");
    if (endpoint.len > max_notify_endpoint_bytes) return invalid(request, "notify.endpoint is too long");
    const uri = std.Uri.parse(endpoint) catch return invalid(request, "notify.endpoint must be a URI");
    if (uri.host == null) return invalid(request, "notify.endpoint must name a host");
    return .{ .endpoint = endpoint, .token = token };
}

const max_notify_token_bytes = 512;
const max_notify_endpoint_bytes = 8 * 1024;

/// Before registering a new endpoint, check that it asked to be: it must
/// recognize the token as one it issued for this space and echo back a fresh
/// challenge.
fn confirmRegistration(allocator: std.mem.Allocator, space: []const u8, registration: store.NotifyRegistration) !void {
    const challenge = try store.randomToken(allocator, "", 16);
    const body = try std.fmt.allocPrint(allocator, "{{\"space\":{f},\"token\":{f},\"challenge\":{f}}}", .{
        std.json.fmt(space, .{}),
        std.json.fmt(registration.token, .{}),
        std.json.fmt(challenge, .{}),
    });
    var result = postToSyncer(allocator, registration.endpoint, confirm_registration_method, body) catch |err| {
        log.info("registration not confirmed space={s} endpoint={s} err={s}\n", .{ space, registration.endpoint, @errorName(err) });
        return error.RegistrationNotConfirmed;
    };
    defer result.deinit(allocator);
    const answer = std.json.parseFromSliceLeaky(std.json.Value, allocator, result.body, .{}) catch return error.RegistrationNotConfirmed;
    const echoed = zat.json.getString(answer, "challenge") orelse return error.RegistrationNotConfirmed;
    if (!std.mem.eql(u8, echoed, challenge)) {
        log.info("registration not confirmed space={s} endpoint={s} err=ChallengeMismatch\n", .{ space, registration.endpoint });
        return error.RegistrationNotConfirmed;
    }
}

/// A `publicKeyMultibase` as the did:key that zat.space verifies against.
fn didKey(allocator: std.mem.Allocator, public_key_multibase: []const u8) ![]const u8 {
    return std.fmt.allocPrint(allocator, "did:key:{s}", .{public_key_multibase});
}

fn isP256DidKey(allocator: std.mem.Allocator, kid: []const u8) bool {
    const key = zat.multicodec.parseDidKey(allocator, kid) catch return false;
    return key.key_type == .p256;
}

fn notifyCredentialsRevoked(request: *http_api.Request) !void {
    const method = notify_credentials_revoked_method;
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const service = requireServiceAuth(request, allocator, method) catch return;
    const issuer = service.issuer_did;
    const body = parseBody(request, allocator, 32 * 1024) catch return;
    const space = zat.json.getString(body.value, "space") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    const parsed = parseSpaceUri(space) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid space");
    if (!std.mem.eql(u8, issuer, parsed.space_did)) return http_api.xrpcError(request, .forbidden, "Forbidden", "Revocation issuer is not the space authority");
    if (try store.findAccount(allocator, service.audience) == null) return http_api.xrpcError(request, .forbidden, "Forbidden", "Revocation audience does not match a repo hosted here");
    const credentials = zat.json.getPath(body.value, "credentials") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing credentials");
    if (credentials != .array or credentials.array.items.len == 0 or credentials.array.items.len > 100) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Expected 1 to 100 credential IDs");
    var ids: [100][]const u8 = undefined;
    for (credentials.array.items, 0..) |value, i| {
        if (value != .string or value.string.len == 0) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid credential ID");
        ids[i] = value.string;
    }
    try store.revokeSpaceCredentials(space, ids[0..credentials.array.items.len]);
    return http_api.json(request, .ok, "{}");
}

/// From a repo host to the space host: the writer repo advanced to `repoRev`,
/// whose LtHash digest is `data`. Only the space host sequences the update and
/// removes writers, so the call carries nothing of the space's sequence.
fn notifyRepoUpdate(request: *http_api.Request) !void {
    const method = notify_repo_update_method;
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const parsed_body = parseBody(request, allocator, 16 * 1024) catch |err| switch (err) {
        error.HandledResponse => return,
        else => return err,
    };
    const input = parsed_body.value;
    const space = zat.json.getString(input, "space") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing space");
    const repo = zat.json.getString(input, "repo") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing repo");
    const rev = zat.json.getString(input, "repoRev") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing repoRev");
    const hash = parseAtJsonBytes(allocator, zat.json.getPath(input, "data") orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Missing data")) catch return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid data");
    if (hash.len != zat.space.lthash.digest_bytes) return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid data");
    const parsed = parseSpaceUri(space) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid space URI");
    const service = requireServiceAuth(request, allocator, method) catch return;
    if (!std.mem.eql(u8, service.issuer_did, repo)) return http_api.xrpcError(request, .forbidden, "Forbidden", "Notification iss does not match the repo");
    const audience = try zat.space.spaceHostAud(allocator, parsed.space_did);
    if (!std.mem.eql(u8, service.audience, parsed.space_did) and !std.mem.eql(u8, service.audience, audience)) return http_api.xrpcError(request, .forbidden, "Forbidden", "Notification aud does not match the space authority");
    processSpaceNotification(allocator, space, repo, rev, hash) catch |err| switch (err) {
        error.RepoNotFound => return http_api.xrpcError(request, .bad_request, "SpaceNotFound", "Space not found"),
        error.WriterNotAuthorized => return http_api.xrpcError(request, .forbidden, "Forbidden", "Repo is not authorized to write to the space"),
        error.FutureRev => return http_api.xrpcError(request, .bad_request, "FutureRev", "Repo revision is too far in the future"),
        // The repo host retries.
        error.UpstreamFailure => return upstreamFailure(request),
        error.InvalidRecordType => return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid repo revision"),
        else => return err,
    };
    return http_api.json(request, .ok, "{}");
}

const RecordParams = struct {
    space: []const u8,
    repo: []const u8,
    collection: []const u8,
    rkey: []const u8,
};

fn recordParams(request: *http_api.Request, allocator: std.mem.Allocator) !RecordParams {
    var space_buf: [1024]u8 = undefined;
    var repo_buf: [256]u8 = undefined;
    var collection_buf: [320]u8 = undefined;
    var rkey_buf: [512]u8 = undefined;
    return .{
        .space = try requiredQueryParam(request, allocator, "space", &space_buf, "Missing space"),
        .repo = try requiredQueryParam(request, allocator, "repo", &repo_buf, "Missing repo"),
        .collection = try requiredQueryParam(request, allocator, "collection", &collection_buf, "Missing collection"),
        .rkey = try requiredQueryParam(request, allocator, "rkey", &rkey_buf, "Missing rkey"),
    };
}

fn requiredQueryParam(
    request: *http_api.Request,
    allocator: std.mem.Allocator,
    name: []const u8,
    buf: []u8,
    message: []const u8,
) ![]const u8 {
    const value = http_api.queryParam(request.url.raw, name, buf) orelse {
        try http_api.xrpcError(request, .bad_request, "InvalidRequest", message);
        return error.HandledResponse;
    };
    return allocator.dupe(u8, value);
}

fn writeBlobResponse(request: *http_api.Request, allocator: std.mem.Allocator, cid: []const u8, blob: store.BlobRecord) !void {
    const range = http_api.headerValue(request, "range");
    const selected = parseRange(range, blob.data.len) catch {
        const headers = [_]http.Header{
            .{ .name = "content-range", .value = try std.fmt.allocPrint(allocator, "bytes */{d}", .{blob.data.len}) },
            .{ .name = "accept-ranges", .value = "bytes" },
            .{ .name = "access-control-allow-origin", .value = "*" },
        };
        return http_api.respond(request, .range_not_satisfiable, "", &headers);
    };
    const start = selected.start;
    const end_inclusive = selected.end_inclusive;
    const body = blob.data[start .. end_inclusive + 1];
    const status: http.Status = if (range == null) .ok else .partial_content;
    const content_range = try std.fmt.allocPrint(allocator, "bytes {d}-{d}/{d}", .{ start, end_inclusive, blob.data.len });
    const disposition = try std.fmt.allocPrint(allocator, "attachment; filename=\"{s}\"", .{cid});
    const headers = [_]http.Header{
        .{ .name = "content-type", .value = if (blob.mime_type.len > 0) blob.mime_type else "application/octet-stream" },
        .{ .name = "accept-ranges", .value = "bytes" },
        .{ .name = "content-range", .value = content_range },
        .{ .name = "x-content-type-options", .value = "nosniff" },
        .{ .name = "content-disposition", .value = disposition },
        .{ .name = "content-security-policy", .value = "default-src 'none'; sandbox" },
        .{ .name = "access-control-allow-origin", .value = "*" },
        .{ .name = "access-control-allow-private-network", .value = "true" },
    };
    return http_api.respond(request, status, if (request.method == .HEAD) "" else body, &headers);
}

fn parseRange(maybe_range: ?[]const u8, size: usize) !struct { start: usize, end_inclusive: usize } {
    if (size == 0) return error.InvalidRange;
    const raw = maybe_range orelse return .{ .start = 0, .end_inclusive = size - 1 };
    if (!std.mem.startsWith(u8, raw, "bytes=")) return error.InvalidRange;
    const spec = raw["bytes=".len..];
    const dash = std.mem.indexOfScalar(u8, spec, '-') orelse return error.InvalidRange;
    if (dash == 0) {
        const suffix = try std.fmt.parseInt(usize, spec[1..], 10);
        if (suffix == 0) return error.InvalidRange;
        const start = if (suffix >= size) 0 else size - suffix;
        return .{ .start = start, .end_inclusive = size - 1 };
    }
    const start = try std.fmt.parseInt(usize, spec[0..dash], 10);
    const end = if (dash + 1 < spec.len) try std.fmt.parseInt(usize, spec[dash + 1 ..], 10) else size - 1;
    if (start >= size or end < start) return error.InvalidRange;
    return .{ .start = start, .end_inclusive = @min(end, size - 1) };
}

fn bearerToken(request: *http_api.Request) ?[]const u8 {
    const raw_header = http_api.headerValue(request, "authorization") orelse return null;
    if (!std.ascii.startsWithIgnoreCase(raw_header, "bearer ")) return null;
    return std.mem.trim(u8, raw_header["bearer ".len..], " \t");
}

fn spaceToken(request: *http_api.Request) ?[]const u8 {
    const raw_header = http_api.headerValue(request, "authorization") orelse return null;
    if (!std.ascii.startsWithIgnoreCase(raw_header, "atproto-space-credential ")) return null;
    return std.mem.trim(u8, raw_header["atproto-space-credential ".len..], " \t");
}

const ServiceAuth = struct {
    issuer_did: []const u8,
    audience: []const u8,
};

fn requireServiceAuth(request: *http_api.Request, allocator: std.mem.Allocator, method: []const u8) !ServiceAuth {
    const token = bearerToken(request) orelse {
        try http_api.xrpcError(request, .unauthorized, "AuthenticationRequired", "Authentication required");
        return error.HandledResponse;
    };
    var arena = std.heap.ArenaAllocator.init(allocator);
    defer arena.deinit();
    const verified = zat.service_auth.verify(arena.allocator(), token, .{
        .now = clock.nowSeconds(),
        .audiences = null,
        .lxm = method,
    }, service_auth.KeyResolver{}) catch |err| {
        switch (err) {
            error.OutOfMemory => return err,
            error.BadJwtLexiconMethod => try http_api.xrpcError(request, .unauthorized, "BadJwtLexiconMethod", "JWT lxm must name the called method"),
            error.BadJwt, error.BadJwtType, error.JwtExpired, error.BadJwtAudience, error.BadJwtIss, error.BadJwtSignature => try http_api.xrpcError(request, .unauthorized, "InvalidToken", "Invalid token"),
            else => try http_api.xrpcError(request, .bad_gateway, "DidResolutionFailed", "could not resolve jwt issuer did"),
        }
        return error.HandledResponse;
    };
    return .{
        .issuer_did = try allocator.dupe(u8, verified.issuer_did),
        .audience = try allocator.dupe(u8, verified.aud),
    };
}

fn serviceAudienceMatchesPds(aud: []const u8) bool {
    if (std.mem.eql(u8, aud, config.serverDid())) return true;
    if (!std.mem.startsWith(u8, aud, config.serverDid())) return false;
    return std.mem.eql(u8, aud[config.serverDid().len..], "#atproto_pds");
}

fn spaceHostEndpointForDid(allocator: std.mem.Allocator, did: []const u8) ![]const u8 {
    const parsed = zat.Did.parse(did) orelse return error.InvalidDid;
    var resolver = service_auth.didResolver(allocator);
    defer resolver.deinit();
    var doc = try resolver.resolve(parsed);
    defer doc.deinit();
    return allocator.dupe(u8, doc.pdsEndpoint() orelse return error.MissingSpaceHostEndpoint);
}

fn serviceEndpointForId(allocator: std.mem.Allocator, service_id: []const u8) ![]const u8 {
    const fragment_index = std.mem.indexOfScalar(u8, service_id, '#') orelse return error.InvalidServiceId;
    const did = zat.Did.parse(service_id[0..fragment_index]) orelse return error.InvalidServiceId;
    var resolver = service_auth.didResolver(allocator);
    defer resolver.deinit();
    var doc = try resolver.resolve(did);
    defer doc.deinit();
    const endpoint = doc.serviceEndpoint(service_id) orelse return error.MissingServiceEndpoint;
    return allocator.dupe(u8, endpoint);
}

fn managingAppCheckAccessUrl(
    allocator: std.mem.Allocator,
    endpoint: []const u8,
    space: []const u8,
    requester_did: ?[]const u8,
    client_id: ?[]const u8,
) ![]const u8 {
    var out: std.Io.Writer.Allocating = .init(allocator);
    try out.writer.print("{s}/xrpc/" ++ check_access_method ++ "?space={s}", .{ endpoint, try zat.oauth.percentEncodeAlloc(allocator, space) });
    if (requester_did) |did| try out.writer.print("&repo={s}", .{try zat.oauth.percentEncodeAlloc(allocator, did)});
    if (client_id) |id| try out.writer.print("&clientId={s}", .{try zat.oauth.percentEncodeAlloc(allocator, id)});
    return out.toOwnedSlice();
}

/// Asks the managing app about reads and writes alike. When it can't be
/// resolved, errors, answers malformed, or takes more than 10 seconds, this is
/// `error.UpstreamFailure` rather than a denial: failing open would hand out
/// credentials for the spaces that asked for the strictest gate, and denying
/// would withdraw syncers' registrations and drop repo hosts' notifications.
fn managingAppAllowsRequester(
    allocator: std.mem.Allocator,
    space: store.SpaceConfig,
    managing_app: []const u8,
    requester_did: ?[]const u8,
    access: store.SpaceAccess,
    client_id: ?[]const u8,
) !bool {
    const endpoint = serviceEndpointForId(allocator, managing_app) catch |err| {
        log.err("space managing app unresolved space={s} managing_app={s} err={s}\n", .{ space.uri, managing_app, @errorName(err) });
        return error.UpstreamFailure;
    };
    const parsed = parseSpaceUri(space.uri) orelse return error.UpstreamFailure;
    const authority = (try store.findAccount(allocator, parsed.space_did)) orelse {
        log.err("space managing app check has no local authority space={s}\n", .{space.uri});
        return error.UpstreamFailure;
    };
    const check_url = try managingAppCheckAccessUrl(allocator, endpoint, space.uri, requester_did, client_id);
    const answer = try askManagingApp(allocator, authority, managing_app, check_url);
    const authorized = switch (access) {
        .read => answer.read,
        .write => answer.write,
    };
    return logManagingAppAnswer(space, managing_app, endpoint, requester_did, access, authorized);
}

fn logManagingAppAnswer(space: store.SpaceConfig, managing_app: []const u8, endpoint: []const u8, requester_did: ?[]const u8, access: store.SpaceAccess, authorized: bool) bool {
    if (!authorized) {
        log.info("space managing app denied space={s} managing_app={s} endpoint={s} user={s} access={s}\n", .{ space.uri, managing_app, endpoint, requester_did orelse "-", @tagName(access) });
    }
    return authorized;
}

const ManagedAccess = struct { read: bool, write: bool };

fn askManagingApp(
    allocator: std.mem.Allocator,
    authority: auth.Account,
    managing_app: []const u8,
    url: []const u8,
) !ManagedAccess {
    const method = check_access_method;
    var keypair = try store.signingKeypair(authority.did);
    const token = try zat.service_auth.create(allocator, store.currentIo(), &keypair, .{ .iss = authority.did, .sub = authority.did, .aud = managing_app, .lxm = method });
    const authorization = try std.fmt.allocPrint(allocator, "Bearer {s}", .{token});
    var transport = zat.HttpTransport.init(store.currentIo(), allocator);
    defer transport.deinit();
    var result = outbound.fetch(allocator, store.currentIo(), &transport, .{
        .url = url,
        .authorization = authorization,
        .accept = "application/json",
        .max_response_size = 16 * 1024,
        .deadline_ns = 10 * std.time.ns_per_s,
    }) catch |err| {
        log.err("space managing app check failed managing_app={s} method={s} err={s}\n", .{ managing_app, method, @errorName(err) });
        return error.UpstreamFailure;
    };
    defer result.deinit(allocator);
    if (result.status != .ok) {
        log.err("space managing app check failed managing_app={s} method={s} status={d}\n", .{ managing_app, method, @backingInt(result.status) });
        return error.UpstreamFailure;
    }
    return managedAccess(allocator, result.body) catch {
        log.err("space managing app check failed managing_app={s} method={s} err=InvalidResponse\n", .{ managing_app, method });
        return error.UpstreamFailure;
    };
}

/// checkAccess answers `{read, write}`, both booleans.
fn managedAccess(allocator: std.mem.Allocator, body: []const u8) !ManagedAccess {
    const response = try std.json.parseFromSlice(std.json.Value, allocator, body, .{});
    defer response.deinit();
    const read = requiredBool(response.value, "read") orelse return error.InvalidResponse;
    const write = requiredBool(response.value, "write") orelse return error.InvalidResponse;
    return .{ .read = read, .write = write };
}

fn postSignedXrpc(
    allocator: std.mem.Allocator,
    account: auth.Account,
    endpoint: []const u8,
    audience: []const u8,
    method: []const u8,
    body: []const u8,
) !void {
    var keypair = try store.signingKeypair(account.did);
    const token = try zat.service_auth.create(allocator, store.currentIo(), &keypair, .{ .iss = account.did, .sub = account.did, .aud = audience, .lxm = method });
    const authorization = try std.fmt.allocPrint(allocator, "Bearer {s}", .{token});
    const url = try std.fmt.allocPrint(allocator, "{s}/xrpc/{s}", .{ endpoint, method });
    var transport = zat.HttpTransport.init(store.currentIo(), allocator);
    defer transport.deinit();
    const result = outbound.fetch(allocator, store.currentIo(), &transport, .{
        .url = url,
        .method = .POST,
        .payload = body,
        .content_type = "application/json",
        .authorization = authorization,
        .max_response_size = 64 * 1024,
    }) catch |err| switch (err) {
        error.ForbiddenScheme, error.ForbiddenAddress, error.MissingHost => return error.RemotePermanentError,
        else => return err,
    };
    defer allocator.free(result.body);
    if (@backingInt(result.status) >= 500 or result.status == .too_many_requests or result.status == .request_timeout) return error.RemoteServerError;
    if (@backingInt(result.status) < 200 or @backingInt(result.status) >= 300) return error.RemotePermanentError;
}

fn processSpaceNotification(allocator: std.mem.Allocator, space: []const u8, repo: []const u8, rev: []const u8, hash: []const u8) !void {
    const parsed = parseSpaceUri(space) orelse return error.InvalidSpaceUri;
    if (try store.findAccount(allocator, parsed.space_did) == null) return error.RepoNotFound;
    const row = (try store.getSpace(allocator, parsed.space_did, space)) orelse return error.RepoNotFound;
    if (!row.is_authority or row.deleted_at != null) return error.RepoNotFound;
    const policy = (try row.policy(allocator)) orelse return error.RepoNotFound;
    if (!try spacePolicyAllowsRequester(allocator, row, policy, repo, .write, null)) return error.WriterNotAuthorized;
    const update = (try store.recordSpaceWriter(allocator, space, repo, rev, hash)) orelse return;
    forwardSpaceUpdate(allocator, space, repo, .{ .write = .{ .rev = rev, .hash = hash } }, update);
}

const repo_write_type = "com.atproto.space.defs#repoWrite";
const repo_removed_type = "com.atproto.space.defs#repoRemoved";

/// How a repo's place in the writer set changed.
const WriterChange = union(enum) {
    /// It advanced to `rev`, whose LtHash digest is `hash`.
    write: struct { rev: []const u8, hash: []const u8 },
    removed,
};

/// A sequenced change to the writer set, as `com.atproto.space.defs#repoWrite`
/// or `#repoRemoved`. listWriters leaves `prevSpaceRev` out.
fn writerUpdateJson(allocator: std.mem.Allocator, repo: []const u8, change: WriterChange, update: store.SpaceUpdate) ![]const u8 {
    var out: std.Io.Writer.Allocating = .init(allocator);
    switch (change) {
        .write => |write| try out.writer.print("{{\"$type\":\"" ++ repo_write_type ++ "\",\"repo\":{f},\"repoRev\":{f},\"data\":{s}", .{
            std.json.fmt(repo, .{}),
            std.json.fmt(write.rev, .{}),
            try zat.cbor.toJsonAlloc(allocator, .{ .bytes = write.hash }),
        }),
        .removed => try out.writer.print("{{\"$type\":\"" ++ repo_removed_type ++ "\",\"repo\":{f}", .{std.json.fmt(repo, .{})}),
    }
    try out.writer.print(",\"spaceRev\":{f}", .{std.json.fmt(update.space_rev, .{})});
    if (update.prev_space_rev) |prev| try out.writer.print(",\"prevSpaceRev\":{f}", .{std.json.fmt(prev, .{})});
    try out.writer.writeByte('}');
    return out.toOwnedSlice();
}

/// Tell the syncers registered for a space that its writer set changed at
/// `update`. Delivery is best effort: a syncer reconciles with listWriters. A
/// registration that lapsed since the last update is owed an expiry notice in
/// place of this one, which the notification worker delivers reliably.
fn forwardSpaceUpdate(allocator: std.mem.Allocator, space: []const u8, repo: []const u8, change: WriterChange, update: store.SpaceUpdate) void {
    forwardSpaceUpdateOrFail(allocator, space, repo, change, update) catch |err| log.err("notifySpaceUpdate fan-out failed space={s} repo={s}: {s}\n", .{ space, repo, @errorName(err) });
}

fn forwardSpaceUpdateOrFail(allocator: std.mem.Allocator, space: []const u8, repo: []const u8, change: WriterChange, update: store.SpaceUpdate) !void {
    const update_json = try writerUpdateJson(allocator, repo, change, update);
    for (try store.activeNotifyRegistrations(allocator, space)) |registration| {
        notifySyncer(allocator, space, registration, update_json) catch |err| {
            log.info("notifySpaceUpdate not delivered space={s} endpoint={s} err={s}\n", .{ space, registration.endpoint, @errorName(err) });
        };
    }
    try store.queueExpiryNotices(space, update.space_rev);
}

/// `com.atproto.space.notifySpaceUpdate` to a registered endpoint. It carries no
/// service auth: the registration's token, in the body, authenticates it.
fn notifySyncer(allocator: std.mem.Allocator, space: []const u8, registration: store.NotifyRegistration, update_json: []const u8) !void {
    const body = try std.fmt.allocPrint(allocator, "{{\"space\":{f},\"token\":{f},\"update\":{s}}}", .{
        std.json.fmt(space, .{}),
        std.json.fmt(registration.token, .{}),
        update_json,
    });
    var result = try postToSyncer(allocator, registration.endpoint, notify_space_update_method, body);
    result.deinit(allocator);
}

/// A notice the worker delivers reliably, as a notifySpaceUpdate `update`.
fn syncerNoticeJson(allocator: std.mem.Allocator, pending: store.PendingSyncerNotice) ![]const u8 {
    return switch (pending.notice) {
        .deleted => "{\"$type\":\"" ++ notify_space_update_method ++ "#spaceDeleted\"}",
        .expired => std.fmt.allocPrint(allocator, "{{\"$type\":\"" ++ notify_space_update_method ++ "#registrationExpired\",\"spaceRev\":{f}}}", .{std.json.fmt(pending.space_rev orelse "", .{})}),
    };
}

/// The retryable statuses, as the reference client counts them.
fn retryableStatus(status: http.Status) bool {
    return switch (@backingInt(status)) {
        408, 425, 429, 500, 502, 503, 504, 522, 524 => true,
        else => false,
    };
}

/// POSTs an XRPC call to a syncer's endpoint. The endpoint came from whoever
/// asked to be registered, so it is fetched as an untrusted URL, and like the
/// reference client only its origin is used. A refused address or a
/// non-retryable status is `RemotePermanentError`; a retryable status is
/// `RemoteServerError`; transport failures pass through.
fn postToSyncer(allocator: std.mem.Allocator, endpoint: []const u8, method: []const u8, body: []const u8) !zat.HttpTransport.FetchResult {
    const url = try xrpcUrl(allocator, endpoint, method);
    var transport = zat.HttpTransport.init(store.currentIo(), allocator);
    defer transport.deinit();
    var result = outbound.fetch(allocator, store.currentIo(), &transport, .{
        .url = url,
        .method = .POST,
        .payload = body,
        .content_type = "application/json",
        .accept = "application/json",
        .max_response_size = 64 * 1024,
        .deadline_ns = 10 * std.time.ns_per_s,
    }) catch |err| switch (err) {
        error.ForbiddenScheme, error.ForbiddenAddress, error.MissingHost, error.NoPublicAddress => return error.RemotePermanentError,
        else => return err,
    };
    const code = @backingInt(result.status);
    if (code >= 200 and code < 300) return result;
    result.deinit(allocator);
    return if (retryableStatus(result.status)) error.RemoteServerError else error.RemotePermanentError;
}

/// `{origin}/xrpc/{method}`: the reference client resolves the method path
/// against the endpoint, which drops any path it has.
fn xrpcUrl(allocator: std.mem.Allocator, endpoint: []const u8, method: []const u8) ![]const u8 {
    const uri = std.Uri.parse(endpoint) catch return error.RemotePermanentError;
    const host = switch (uri.host orelse return error.RemotePermanentError) {
        .raw, .percent_encoded => |text| text,
    };
    if (uri.port) |port| return std.fmt.allocPrint(allocator, "{s}://{s}:{d}/xrpc/{s}", .{ uri.scheme, host, port, method });
    return std.fmt.allocPrint(allocator, "{s}://{s}/xrpc/{s}", .{ uri.scheme, host, method });
}

fn deliverSpaceNotification(allocator: std.mem.Allocator, account: auth.Account, space: []const u8, repo: []const u8, rev: []const u8, hash: []const u8) !void {
    const parsed = parseSpaceUri(space) orelse return error.InvalidSpaceUri;
    if (try store.findAccount(allocator, parsed.space_did) != null) {
        return processSpaceNotification(allocator, space, repo, rev, hash);
    }
    const endpoint = try spaceHostEndpointForDid(allocator, parsed.space_did);
    const audience = try zat.space.spaceHostAud(allocator, parsed.space_did);
    const body = try std.fmt.allocPrint(allocator, "{{\"space\":{f},\"repo\":{f},\"repoRev\":{f},\"data\":{s}}}", .{
        std.json.fmt(space, .{}),
        std.json.fmt(repo, .{}),
        std.json.fmt(rev, .{}),
        try zat.cbor.toJsonAlloc(allocator, .{ .bytes = hash }),
    });
    try postSignedXrpc(allocator, account, endpoint, audience, notify_repo_update_method, body);
}

fn permanentNotificationError(err: anyerror) bool {
    return err == error.RemotePermanentError or err == error.WriterNotAuthorized or err == error.RepoNotFound or err == error.InvalidRecordType or err == error.FutureRev;
}

fn fireNotifyRepoUpdateForState(allocator: std.mem.Allocator, account: auth.Account, space: []const u8, repo: []const u8, state: store.SpaceState) !void {
    const rev = state.rev orelse return;
    const set_hash = try zat.space.LtHash.fromBytes(state.set_hash orelse return);
    deliverSpaceNotification(allocator, account, space, repo, rev, &set_hash.digest()) catch |err| {
        if (!permanentNotificationError(err)) {
            store.releaseSpaceNotification(space, repo, rev) catch {};
            return err;
        }
    };
    try store.finishSpaceNotification(space, repo, rev);
}

pub fn startNotificationWorker() !void {
    const thread = try std.Thread.spawn(.{}, notificationWorker, .{});
    thread.detach();
}

fn notificationWorker() void {
    while (true) {
        var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
        const a = arena.allocator();
        const pending = store.claimSpaceNotification(a) catch null;
        if (pending) |item| {
            deliverPendingNotification(a, item) catch {};
        }
        const notice = store.claimSyncerNotice(a) catch null;
        if (notice) |item| {
            deliverSyncerNotice(a, item) catch |err| log.err("syncer notice failed space={s} endpoint={s} err={s}\n", .{ item.space, item.registration.endpoint, @errorName(err) });
        }
        arena.deinit();
        if (pending == null and notice == null) store.currentIo().sleep(std.Io.Duration.fromSeconds(1), .awake) catch {};
    }
}

fn deliverPendingNotification(allocator: std.mem.Allocator, item: store.PendingSpaceNotification) !void {
    const account = (try store.findAccount(allocator, item.repo)) orelse {
        return store.finishSpaceNotification(item.space, item.repo, item.rev);
    };
    deliverSpaceNotification(allocator, account, item.space, item.repo, item.rev, item.hash) catch |err| {
        if (!permanentNotificationError(err)) return store.retrySpaceNotification(item);
    };
    try store.finishSpaceNotification(item.space, item.repo, item.rev);
}

/// Deletion and expiry notices are retried until accepted, for at least 72
/// hours. A notice waits while the authority is taken down or deactivated,
/// and one that no longer applies is dropped. A syncer that rejects an expiry
/// notice, or stays unreachable, is unregistered.
fn deliverSyncerNotice(allocator: std.mem.Allocator, item: store.PendingSyncerNotice) !void {
    const parsed = parseSpaceUri(item.space) orelse return store.finishSyncerNotice(item);
    const status = store.accountStatus(parsed.space_did) catch |err| switch (err) {
        error.RepoNotFound => return store.finishSyncerNotice(item),
        else => return err,
    };
    switch (status) {
        .active => {},
        .deleted => return store.finishSyncerNotice(item),
        .takendown, .suspended, .deactivated => return rescheduleSyncerNotice(item),
    }
    if (!try store.syncerNoticeOwed(item)) return store.finishSyncerNotice(item);
    notifySyncer(allocator, item.space, item.registration, try syncerNoticeJson(allocator, item)) catch |err| {
        if (err == error.RemotePermanentError) return store.abandonSyncerNotice(item);
        return rescheduleSyncerNotice(item);
    };
    try store.finishSyncerNotice(item);
}

fn rescheduleSyncerNotice(item: store.PendingSyncerNotice) !void {
    // The last retry lands after the window closes; once it fails too, give up.
    if (item.expires_at <= unixNow()) return store.abandonSyncerNotice(item);
    return store.retrySyncerNotice(item);
}

fn unixNow() i64 {
    return clock.nowSeconds();
}

fn requireAccount(request: *http_api.Request, allocator: std.mem.Allocator) !http_api.BearerAccount {
    return http_api.requireBearerAccess(request, allocator) catch |err| {
        try http_api.bearerErrorResponse(request, err);
        return error.HandledResponse;
    };
}

/// The space exports a taken-down account needs to move away (listSpaces,
/// exportSpaceMeta) take its limited session as well.
fn requireExportAccount(request: *http_api.Request, allocator: std.mem.Allocator) !http_api.BearerAccount {
    return http_api.requireBearerAccessOrTakendown(request, allocator) catch |err| {
        try http_api.bearerErrorResponse(request, err);
        return error.HandledResponse;
    };
}

/// Space writes and management need an active account, as repo writes do; a
/// deactivated account keeps its session but can only read its own data.
fn requireActiveAccount(request: *http_api.Request, allocator: std.mem.Allocator) !http_api.BearerAccount {
    const auth_ctx = try requireAccount(request, allocator);
    try http_api.requireActiveAccount(request, auth_ctx.account.did, .takedown_and_deactivation);
    return auth_ctx;
}

/// A space authority that is taken down or deactivated issues no credentials and
/// serves no writer list. One not hosted here is answered by the caller's lookup.
fn requireActiveAuthority(request: *http_api.Request, authority_did: []const u8) !void {
    const status = store.accountStatus(authority_did) catch |err| switch (err) {
        error.RepoNotFound => return,
        else => return err,
    };
    if (status.isActive()) return;
    try accountUnavailable(request, status);
    return error.HandledResponse;
}

fn accountUnavailable(request: *http_api.Request, status: store.AccountStatus) !void {
    return switch (status) {
        .active => {},
        .takendown => http_api.xrpcError(request, .bad_request, "RepoTakendown", "Repo has been taken down"),
        .suspended => http_api.xrpcError(request, .bad_request, "RepoSuspended", "Repo is suspended"),
        .deactivated => http_api.xrpcError(request, .bad_request, "RepoDeactivated", "Repo is deactivated"),
        .deleted => http_api.xrpcError(request, .not_found, "RepoNotFound", "Repo not found"),
    };
}

fn requireSpaceScope(
    request: *http_api.Request,
    maybe_scope: ?[]const u8,
    space_type: []const u8,
    did: []const u8,
    skey: []const u8,
    action: scopes.SpaceAction,
    collection: ?[]const u8,
) !void {
    if (maybe_scope == null) return;
    const scope = switch (action) {
        .create, .update, .delete => try resolveWriteScopes(request, request.arena, maybe_scope.?, space_type),
        else => maybe_scope.?,
    };
    if (scopes.spaceAllows(scope, action, space_type, did, skey, collection)) return;
    return http_api.xrpcError(request, .forbidden, "InsufficientScope", "OAuth token does not grant the requested space operation");
}

fn resolveWriteScopes(request: *http_api.Request, allocator: std.mem.Allocator, scope: []const u8, space_type: []const u8) ![]const u8 {
    return @import("oauth/permission_sets.zig").resolveSpaceWriteScopes(allocator, scope, space_type) catch |err| {
        log.err("space scope resolution failed type={s} err={s}\n", .{ space_type, @errorName(err) });
        try http_api.xrpcError(request, .bad_gateway, "UpstreamFailure", "Could not resolve space type declaration");
        return error.HandledResponse;
    };
}

fn requireSpaceAccess(
    request: *http_api.Request,
    allocator: std.mem.Allocator,
    auth_ctx: http_api.BearerAccount,
    space: []const u8,
    action: scopes.SpaceAction,
    collection: ?[]const u8,
) !void {
    const parsed = parseSpaceUri(space) orelse return http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid space URI");
    try requireSpaceScope(request, auth_ctx.oauth_scope, parsed.space_type, parsed.space_did, parsed.skey, action, collection);
    if (try store.getSpace(allocator, auth_ctx.account.did, space)) |visible| {
        if (visible.deleted_at == null and (visible.is_authority or !std.mem.eql(u8, parsed.space_did, auth_ctx.account.did))) return;
        try http_api.xrpcError(request, .bad_request, "SpaceNotFound", "Space not found");
        return error.HandledResponse;
    }
    // The authority's own spaces exist only through createSpace: a write must
    // neither conjure an ungoverned space nor revive a deleted one.
    if (std.mem.eql(u8, parsed.space_did, auth_ctx.account.did)) {
        try http_api.xrpcError(request, .bad_request, "SpaceNotFound", "Space not found");
        return error.HandledResponse;
    }
    // A writer's PDS needs no prior knowledge of a space: it keeps the writer's
    // own repo, and the authority decides who counts as a writer when
    // notifyRepoUpdate arrives. First write materializes the local repo.
    _ = store.createSpace(allocator, .{
        .actor_did = auth_ctx.account.did,
        .authority_did = parsed.space_did,
        .space_type = parsed.space_type,
        .skey = parsed.skey,
        .is_authority = false,
    }) catch {
        try http_api.xrpcError(request, .forbidden, "NotPermitted", "Not permitted to write in this space");
        return error.HandledResponse;
    };
}

/// The space is anchored on its creator's DID, so ownership is a comparison
/// against the space URI. Returns the space's policy.
fn requireSpaceOwner(
    request: *http_api.Request,
    allocator: std.mem.Allocator,
    auth_ctx: http_api.BearerAccount,
    space: []const u8,
    action: scopes.SpaceAction,
) !space_policy.Policy {
    const parsed = parseSpaceUri(space) orelse {
        try http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid space URI");
        return error.HandledResponse;
    };
    try requireSpaceScope(request, auth_ctx.oauth_scope, parsed.space_type, parsed.space_did, parsed.skey, action, null);
    if (!std.mem.eql(u8, parsed.space_did, auth_ctx.account.did)) {
        try notSpaceOwner(request);
        return error.HandledResponse;
    }
    const existing = (try store.getSpace(allocator, auth_ctx.account.did, space)) orelse {
        try spaceNotFound(request);
        return error.HandledResponse;
    };
    const policy = (if (existing.is_authority) try existing.policy(allocator) else null) orelse {
        try spaceNotFound(request);
        return error.HandledResponse;
    };
    return policy;
}

fn upstreamFailure(request: *http_api.Request) !void {
    return http_api.xrpcError(request, .bad_gateway, "UpstreamFailure", "Managing app did not answer");
}

fn spaceNotFound(request: *http_api.Request) !void {
    return http_api.xrpcError(request, .bad_request, "SpaceNotFound", "Space not found");
}

fn notSpaceOwner(request: *http_api.Request) !void {
    return http_api.xrpcError(request, .bad_request, "NotAuthorized", "Not the space authority");
}

fn policyMismatch(request: *http_api.Request) !void {
    return http_api.xrpcError(request, .bad_request, "PolicyMismatch", "Space is not governed by the memberspace policy");
}

fn rejectPublishedCollection(request: *http_api.Request, collection: []const u8) !void {
    var buf: [400]u8 = undefined;
    const message = std.fmt.bufPrint(&buf, "{s} records are published by the PDS from a space's configuration and cannot be written directly", .{collection}) catch "Published configuration records cannot be written directly";
    return http_api.xrpcError(request, .bad_request, "InvalidRequest", message);
}

fn readBearer(request: *http_api.Request, allocator: std.mem.Allocator, export_session: bool) http_api.BearerError!http_api.BearerAccount {
    return if (export_session) http_api.requireBearerAccessOrTakendown(request, allocator) else http_api.requireBearerAccess(request, allocator);
}

const ReadAuth = union(enum) {
    bearer: http_api.BearerAccount,
    space_credential: zat.space.token.Claims,
    /// The admin token, which reads any repo as it does through sync.*.
    admin,
};

/// Authenticates first and then checks the repo is available, as the reference
/// PDS does. The account itself reads its own deactivated repo; `export_session`
/// marks the reads a taken-down account needs to move its spaces (getRepo,
/// getBlob, listBlobs), which take its limited session and its taken-down repo.
fn requireReadAccess(request: *http_api.Request, allocator: std.mem.Allocator, space: []const u8, repo: []const u8, collection: ?[]const u8, export_session: bool) !ReadAuth {
    if (zat.Did.parse(repo) == null) {
        try http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid repo DID");
        return error.HandledResponse;
    }
    const repo_status = store.accountStatus(repo) catch |err| switch (err) {
        error.RepoNotFound => {
            try http_api.xrpcError(request, .not_found, "RepoNotFound", "Repo not found");
            return error.HandledResponse;
        },
        else => return err,
    };
    const parsed = parseSpaceUri(space) orelse {
        try http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid space URI");
        return error.HandledResponse;
    };
    const read_auth: ReadAuth = if (http_api.hasAdminToken(request))
        .admin
    else if (readBearer(request, allocator, export_session)) |auth_ctx| blk: {
        // As for an absent repo: whether another account holds a repo in this
        // space is not the caller's business.
        if (!std.mem.eql(u8, repo, auth_ctx.account.did)) {
            try http_api.xrpcError(request, .not_found, "RepoNotFound", "Repo not found");
            return error.HandledResponse;
        }
        try requireSpaceScope(request, auth_ctx.oauth_scope, parsed.space_type, parsed.space_did, parsed.skey, .read_self, collection);
        break :blk .{ .bearer = auth_ctx };
    } else |err| if (err == error.ExpiredToken or spaceToken(request) == null) {
        try http_api.bearerErrorResponse(request, err);
        return error.HandledResponse;
    } else .{ .space_credential = try requireSpaceCredential(request, allocator, space, repo) };

    if (repo_status.isActive()) return read_auth;
    const readable = switch (read_auth) {
        .admin => repo_status != .deleted,
        .bearer => repo_status == .deactivated or (repo_status == .takendown and export_session),
        .space_credential => false,
    };
    if (!readable) {
        try accountUnavailable(request, repo_status);
        return error.HandledResponse;
    }
    return read_auth;
}

fn listBlobsLimit(request: *http_api.Request) !usize {
    var buf: [16]u8 = undefined;
    const raw = http_api.queryParam(request.url.raw, "limit", &buf) orelse return 500;
    const limit = std.fmt.parseInt(usize, raw, 10) catch {
        try http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid limit");
        return error.HandledResponse;
    };
    if (limit < 1 or limit > 1000) {
        try http_api.xrpcError(request, .bad_request, "InvalidRequest", "limit must be between 1 and 1000");
        return error.HandledResponse;
    }
    return limit;
}

fn requireSpaceCredential(request: *http_api.Request, allocator: std.mem.Allocator, space: []const u8, repo: ?[]const u8) !zat.space.token.Claims {
    const parsed = parseSpaceUri(space) orelse {
        try http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid space URI");
        return error.HandledResponse;
    };
    const token = spaceToken(request) orelse {
        try http_api.xrpcError(request, .unauthorized, "AuthenticationRequired", "Authentication required");
        return error.HandledResponse;
    };
    const unverified = zat.space.token.parse(allocator, .credential, token) catch {
        try http_api.xrpcError(request, .unauthorized, "InvalidToken", "Invalid token");
        return error.HandledResponse;
    };
    const issuer = unverified.claims.iss;
    if (!std.mem.eql(u8, issuer, parsed.space_did)) {
        try http_api.xrpcError(request, .unauthorized, "InvalidToken", "Space credential issuer must be the space authority");
        return error.HandledResponse;
    }
    const kid = unverified.kid.?;
    const public_key = service_auth.signingKey(allocator, issuer, kid) catch {
        try http_api.xrpcError(request, .bad_gateway, "DidResolutionFailed", "could not resolve credential issuer did");
        return error.HandledResponse;
    };
    const verified = zat.space.token.verify(allocator, .credential, token, .{
        .signing_key = try didKey(allocator, public_key),
        .now = clock.nowSeconds(),
    }) catch {
        try http_api.xrpcError(request, .unauthorized, "InvalidToken", "Invalid space credential");
        return error.HandledResponse;
    };
    const credential = verified.claims;
    if (!std.mem.eql(u8, credential.sub, space)) {
        try http_api.xrpcError(request, .bad_request, "InvalidRequest", "Credential space mismatch");
        return error.HandledResponse;
    }
    if (try store.spaceCredentialRevoked(space, credential.jti)) {
        try http_api.xrpcError(request, .unauthorized, "CredentialRevoked", "Space credential has been revoked");
        return error.HandledResponse;
    }
    verifyCredentialUse(allocator, request, credential.cnf_kid.?, repo orelse parsed.space_did) catch |err| {
        try http_api.xrpcError(request, .unauthorized, if (err == error.BadSpaceAudience) "BadSpaceAudience" else "BadSpaceSignature", "Invalid space credential signature or audience");
        return error.HandledResponse;
    };
    return credential;
}

/// The holder's HTTP signature over this use of its credential, addressed to
/// `audience`. Each covered header must appear once.
fn verifyCredentialUse(allocator: std.mem.Allocator, request: *const http_api.Request, holder_key: []const u8, audience: []const u8) !void {
    const authorization = try singleHeader(request, "authorization") orelse return error.BadSpaceSignature;
    const actual = singleHeader(request, "atproto-space-audience") catch return error.BadSpaceAudience;
    if (!std.mem.eql(u8, audience, actual orelse return error.BadSpaceAudience)) return error.BadSpaceAudience;
    return zat.space.verifyCredentialUse(allocator, authorization, audience, try singleHeader(request, "signature-input"), try singleHeader(request, "signature"), holder_key);
}

fn singleHeader(request: *const http_api.Request, name: []const u8) error{BadSpaceSignature}!?[]const u8 {
    var value: ?[]const u8 = null;
    for (request.headers.keys[0..request.headers.len], request.headers.values[0..request.headers.len]) |key, item| {
        if (!std.ascii.eqlIgnoreCase(key, name)) continue;
        if (value != null) return error.BadSpaceSignature;
        value = item;
    }
    return value;
}

fn prepareSpaceRecord(
    request: *http_api.Request,
    allocator: std.mem.Allocator,
    collection: []const u8,
    rkey: []const u8,
    value: std.json.Value,
) !store.PreparedRecord {
    return store.prepareRecordValue(allocator, collection, rkey, value) catch |err| switch (err) {
        error.InvalidCollection => {
            try http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid collection");
            return error.HandledResponse;
        },
        error.InvalidRecordKey => {
            try http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid rkey");
            return error.HandledResponse;
        },
        error.InvalidRecordType => {
            try http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid record type");
            return error.HandledResponse;
        },
        error.InvalidDagCbor => {
            try http_api.xrpcError(request, .bad_request, "InvalidRequest", "record is outside the atproto data model");
            return error.HandledResponse;
        },
        error.RecordTooLarge => {
            try http_api.xrpcError(request, .bad_request, "InvalidRequest", "record exceeds 1048576 encoded bytes");
            return error.HandledResponse;
        },
        else => return err,
    };
}

fn spaceCommit(space: []const u8, repo: []const u8, state: store.SpaceState) !?zat.space.Commit {
    const set_hash = state.set_hash orelse return null;
    const rev = state.rev orelse return null;
    _ = parseSpaceUri(space) orelse return error.InvalidSpaceUri;
    return try zat.space.archive.commitForState(set_hash, .{ .space = space, .repo = repo, .rev = rev });
}

const space_mac_expose_headers = "dpop-nonce, www-authenticate, signature-input, signature, atproto-space-commit, atproto-space-record";

/// A MAC the response owes: what the syncer asked for in `Accept-Signature`,
/// and the secret shared with it.
const SpaceMac = struct {
    request: zat.space.mac.MacRequest,
    secret: [32]u8,
};

/// Reads that return a commit or record must carry a MAC when called with a
/// space credential, requested with `Accept-Signature`. An account reading its
/// own repo may ask for one. Returns null when no MAC is owed.
fn requireSpaceMac(
    request: *http_api.Request,
    allocator: std.mem.Allocator,
    read_auth: ReadAuth,
    repo: []const u8,
    profile: zat.space.mac.Profile,
) !?SpaceMac {
    try http_api.addResponseHeader("vary", zat.space.mac.request_header);
    const header = http_api.headerValue(request, zat.space.mac.request_header);
    const mac_request = zat.space.mac.parseMacRequest(allocator, header, profile) catch |err| switch (err) {
        error.OutOfMemory => return error.OutOfMemory,
        error.InvalidSpaceMac => return rejectSpaceMac(request, profile),
    } orelse {
        if (read_auth == .space_credential) return rejectSpaceMac(request, profile);
        return null;
    };
    const kem_secret = (try store.kemSecretKey(repo)) orelse {
        log.err("space mac requested for account without a KEM key did={s}\n", .{repo});
        try http_api.xrpcError(request, .internal_server_error, "InternalServerError", "Account has no KEM key");
        return error.HandledResponse;
    };
    const secret = zat.space.decapsulate(kem_secret, mac_request.key_share) catch |err| switch (err) {
        error.OutOfMemory => return error.OutOfMemory,
        error.InvalidKemKey => return rejectSpaceMac(request, profile),
    };
    return .{ .request = mac_request, .secret = secret };
}

fn rejectSpaceMac(request: *http_api.Request, profile: zat.space.mac.Profile) error{ HandledResponse, OutOfMemory } {
    var buf: [128]u8 = undefined;
    const message = std.fmt.bufPrint(&buf, "Accept-Signature must request one {s} MAC keyed by a P-256 key share", .{profile.tag()}) catch unreachable;
    http_api.xrpcError(request, .bad_request, "InvalidSpaceMac", message) catch |write_err| switch (write_err) {
        error.HandledResponse => {},
        else => return error.OutOfMemory,
    };
    http_api.addResponseHeader("access-control-expose-headers", space_mac_expose_headers) catch return error.OutOfMemory;
    return error.HandledResponse;
}

fn setSpaceMacHeaders(headers: zat.space.mac.MacHeaders) !void {
    try http_api.addResponseHeader(headers.covered_name, headers.covered);
    try http_api.addResponseHeader("signature-input", headers.signature_input);
    try http_api.addResponseHeader("signature", headers.signature);
    try http_api.addResponseHeader("access-control-expose-headers", space_mac_expose_headers);
}

fn setCommitMac(allocator: std.mem.Allocator, mac: SpaceMac, commit: zat.space.Commit) !void {
    try setSpaceMacHeaders(try zat.space.mac.createCommitMacHeaders(allocator, commit, mac.request, &mac.secret));
}

fn parseBody(request: *http_api.Request, allocator: std.mem.Allocator, max_len: usize) !std.json.Parsed(std.json.Value) {
    const body = http_api.readBodyAlloc(request, allocator, max_len) catch |err| switch (err) {
        error.BodyTooLarge => {
            try http_api.xrpcError(request, .payload_too_large, "InvalidRequest", "Request body too large");
            return error.HandledResponse;
        },
        else => return err,
    };
    return http_api.parseJsonBody(request, allocator, body);
}

fn recordBodyValue(value: std.json.Value) ?std.json.Value {
    return switch (value) {
        .object => |object| object.get("record"),
        else => null,
    };
}

fn spacePolicyAllowsRequester(
    allocator: std.mem.Allocator,
    space: store.SpaceConfig,
    policy: space_policy.Policy,
    requester_did: []const u8,
    access: store.SpaceAccess,
    client_id: ?[]const u8,
) !bool {
    // The authority is the only party that can reconfigure the space, so it must
    // never be able to lock itself out — and reaching its own data must not
    // depend on a managing app being reachable.
    if (std.mem.eql(u8, requester_did, space.authority_did)) return true;
    return switch (policy) {
        .personal => false,
        // A member without write access stays out even under publicWrite.
        .member => |member| switch (access) {
            .read => member.public_read or try store.spaceMemberAllows(space.uri, requester_did, .read),
            .write => try store.spaceMemberAccess(space.uri, requester_did, .write) orelse member.public_write,
        },
        .managed => |managed| managingAppAllowsRequester(allocator, space, managed.managing_app, requester_did, access, client_id),
    };
}

fn parseAtJsonBytes(allocator: std.mem.Allocator, value: std.json.Value) ![]const u8 {
    return switch (try zat.cbor.fromJson(allocator, value)) {
        .bytes => |bytes| bytes,
        else => error.InvalidBytes,
    };
}

fn requiredBool(value: std.json.Value, key: []const u8) ?bool {
    const field = jsonField(value, key) orelse return null;
    return if (field == .bool) field.bool else null;
}

fn jsonField(value: std.json.Value, key: []const u8) ?std.json.Value {
    return switch (value) {
        .object => |object| object.get(key),
        else => null,
    };
}

fn pageLimit(target: []const u8, default: usize, max: usize) usize {
    const requested = http_api.queryLimit(target, default);
    return @min(if (requested == 0) default else requested, max);
}

fn rejectPolicy(request: *http_api.Request, err: space_policy.Error) !void {
    return switch (err) {
        error.UnsupportedPolicy => http_api.xrpcError(request, .bad_request, "UnsupportedPolicy", "The requested policy is not one this host implements"),
        error.InvalidPolicy => http_api.xrpcError(request, .bad_request, "InvalidRequest", "Invalid policy"),
        error.OutOfMemory => error.OutOfMemory,
    };
}

fn invalidCursor(request: *http_api.Request) !void {
    return http_api.xrpcError(request, .bad_request, "InvalidCursor", "Malformed cursor");
}

/// listRecords pages by `collection/rkey`.
fn validRecordCursor(cursor: []const u8) bool {
    const slash = std.mem.indexOfScalar(u8, cursor, '/') orelse return false;
    return zat.Nsid.parse(cursor[0..slash]) != null and zat.Rkey.parse(cursor[slash + 1 ..]) != null;
}

fn parseOplogCursor(raw: []const u8) ?store.OplogCursor {
    const slash = std.mem.indexOfScalar(u8, raw, '/') orelse return null;
    const rev = raw[0..slash];
    if (rev.len == 0) return null;
    const idx = std.fmt.parseInt(i64, raw[slash + 1 ..], 10) catch return null;
    return .{ .rev = rev, .idx = idx };
}

const parseSpaceUri = zat.space.SpaceUri.parse;

fn xrpcMethod(target: []const u8) ?[]const u8 {
    const prefix = "/xrpc/";
    if (!std.mem.startsWith(u8, target, prefix)) return null;
    const rest = target[prefix.len..];
    const end = std.mem.indexOfScalar(u8, rest, '?') orelse rest.len;
    return rest[0..end];
}

test "parses permissioned space uris" {
    const parsed = parseSpaceUri("at:space/did:plc:abc/fm.plyr.privateMedia/self").?;
    try std.testing.expectEqualStrings("did:plc:abc", parsed.space_did);
    try std.testing.expectEqualStrings("fm.plyr.privateMedia", parsed.space_type);
    try std.testing.expectEqualStrings("self", parsed.skey);
}

test "AT JSON bytes decode with and without padding" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const expected = [_]u8{ 1, 2, 3, 4 };
    for ([_][]const u8{ "{\"$bytes\":\"AQIDBA==\"}", "{\"$bytes\":\"AQIDBA\"}" }) |text| {
        const parsed = try std.json.parseFromSlice(std.json.Value, allocator, text, .{});
        defer parsed.deinit();
        try std.testing.expectEqualSlices(u8, &expected, try parseAtJsonBytes(allocator, parsed.value));
    }
}

test "permissioned wire hashes use AT JSON bytes" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const allocator = arena.allocator();
    const expected = [_]u8{ 0, 1, 2, 253, 254 };
    const encoded = try zat.cbor.toJsonAlloc(allocator, .{ .bytes = &expected });
    try std.testing.expectEqualStrings("{\"$bytes\":\"AAEC/f4\"}", encoded);
    const parsed = try std.json.parseFromSlice(std.json.Value, allocator, encoded, .{});
    defer parsed.deinit();
    const actual = try parseAtJsonBytes(allocator, parsed.value);
    try std.testing.expectEqualSlices(u8, &expected, actual);
}

test "the space authority is always authorized for its own space" {
    const space: store.SpaceConfig = .{
        .uri = "at:space/did:plc:auth/my.bulletin.board/self",
        .authority_did = "did:plc:auth",
        .space_type = "my.bulletin.board",
        .skey = "self",
        .policy_json = null,
        .is_authority = true,
        .deleted_at = null,
    };
    // Returns before the managing-app branch would try to resolve the (here
    // deliberately unreachable) service, so no allocator or store is touched.
    const policies = [_]space_policy.Policy{ .personal, .{ .member = .{} }, .{ .managed = .{ .managing_app = "did:web:unreachable.invalid#bulletin" } } };
    for (policies) |policy| {
        try std.testing.expect(try spacePolicyAllowsRequester(std.testing.allocator, space, policy, "did:plc:auth", .read, null));
        try std.testing.expect(try spacePolicyAllowsRequester(std.testing.allocator, space, policy, "did:plc:auth", .write, null));
    }
    try std.testing.expect(!try spacePolicyAllowsRequester(std.testing.allocator, space, .personal, "did:plc:other", .read, null));
    try std.testing.expect(!try spacePolicyAllowsRequester(std.testing.allocator, space, .personal, "did:plc:other", .write, null));
}

test "imports take only the STAR content type" {
    try std.testing.expect(isStarContentType("application/vnd.dasl.star"));
    try std.testing.expect(isStarContentType("Application/VND.dasl.star; foo=bar"));
    try std.testing.expect(!isStarContentType("application/octet-stream"));
    try std.testing.expect(!isStarContentType("application/vnd.dasl.star+json"));
    try std.testing.expect(!isStarContentType(null));
}

test "listRecords cursors are collection/rkey" {
    try std.testing.expect(validRecordCursor("fm.plyr.track/track-one"));
    try std.testing.expect(!validRecordCursor("fm.plyr.track"));
    try std.testing.expect(!validRecordCursor("/track-one"));
    try std.testing.expect(!validRecordCursor("fm.plyr.track/"));
    try std.testing.expect(!validRecordCursor("not a collection/x"));
}

test "listRepoOps cursors are rev/idx" {
    const cursor = parseOplogCursor("3lx7abcdefg22/4").?;
    try std.testing.expectEqualStrings("3lx7abcdefg22", cursor.rev);
    try std.testing.expectEqual(@as(i64, 4), cursor.idx);
    try std.testing.expect(parseOplogCursor("3lx7abcdefg22") == null);
    try std.testing.expect(parseOplogCursor("/4") == null);
    try std.testing.expect(parseOplogCursor("3lx7abcdefg22/x") == null);
}

test "memberspace access combines public flags with the member list" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    try store.init(std.Options.debug_io, ":memory:");
    defer store.close();
    const owner = try store.createAccount(a, "access.test", "access@test.com", "password", "did:plc:access", true);
    const space = try store.createSpace(a, .{
        .actor_did = owner.did,
        .authority_did = owner.did,
        .space_type = "test.access.space",
        .skey = "self",
        .is_authority = true,
        .policy = .{ .member = .{} },
    });
    const public_read: space_policy.Policy = .{ .member = .{ .public_read = true } };
    const public_write: space_policy.Policy = .{ .member = .{ .public_write = true } };
    const members: space_policy.Policy = .{ .member = .{} };
    try std.testing.expect(try spacePolicyAllowsRequester(a, space, public_read, "did:plc:member", .read, null));
    try std.testing.expect(!try spacePolicyAllowsRequester(a, space, public_read, "did:plc:member", .write, null));
    try std.testing.expect(!try spacePolicyAllowsRequester(a, space, public_write, "did:plc:member", .read, null));
    try std.testing.expect(try spacePolicyAllowsRequester(a, space, public_write, "did:plc:member", .write, null));
    _ = try store.changeSpaceMembers(a, space.uri, &.{.{ .did = "did:plc:member", .access = .{ .read = false, .write = true } }});
    try std.testing.expect(!try spacePolicyAllowsRequester(a, space, members, "did:plc:member", .read, null));
    try std.testing.expect(try spacePolicyAllowsRequester(a, space, members, "did:plc:member", .write, null));
    try std.testing.expect(!try spacePolicyAllowsRequester(a, space, members, "did:plc:stranger", .write, null));
    try std.testing.expect(try spacePolicyAllowsRequester(a, space, members, owner.did, .read, null));
    try std.testing.expect(try spacePolicyAllowsRequester(a, space, members, owner.did, .write, null));
    // A member denied write stays out even when anyone may write.
    _ = try store.changeSpaceMembers(a, space.uri, &.{.{ .did = "did:plc:reader", .access = .{ .read = true, .write = false } }});
    try std.testing.expect(!try spacePolicyAllowsRequester(a, space, public_write, "did:plc:reader", .write, null));
    try std.testing.expect(try spacePolicyAllowsRequester(a, space, public_write, "did:plc:stranger", .write, null));
}

test "a managing app answer needs both read and write as booleans" {
    const a = std.testing.allocator;
    try std.testing.expectError(error.InvalidResponse, managedAccess(a, "{\"read\":\"true\",\"write\":false}"));
    try std.testing.expectError(error.InvalidResponse, managedAccess(a, "{}"));
    try std.testing.expectError(error.InvalidResponse, managedAccess(a, "[true]"));
    try std.testing.expectError(error.InvalidResponse, managedAccess(a, "{\"read\":true}"));
    try std.testing.expect(std.meta.isError(managedAccess(a, "not json")));
    try std.testing.expectEqual(ManagedAccess{ .read = true, .write = false }, try managedAccess(a, "{\"read\":true,\"write\":false}"));
}

test "managing app checks include access and omit client identity for writes" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const check = "https://manager.test/xrpc/com.atproto.managedspace.checkAccess?space=at%3Aspace%2Fdid%3Aplc%3Aa%2Ft.s%2Fself";
    try std.testing.expectEqualStrings(check, try managingAppCheckAccessUrl(a, "https://manager.test", "at:space/did:plc:a/t.s/self", null, null));
    try std.testing.expectEqualStrings(check ++ "&repo=did%3Aplc%3Ab&clientId=https%3A%2F%2Fclient.test", try managingAppCheckAccessUrl(a, "https://manager.test", "at:space/did:plc:a/t.s/self", "did:plc:b", "https://client.test"));
}