zat.dev/zds
atproto pds · mirror of https://tangled.org/zat.dev/zds
zds 0.25.1 Latest 2 packages, all images
0
0
# permissioned data
Permissioned data support is experimental and operator gated. Treat the current
ZDS surface as an alpha implementation that can change incompatibly, not as a
claim of complete parity with the evolving upstream proposal. ZDS documents the
`com.atproto.space.*` routes as experimental, and only enables the handlers when
explicitly configured:
```sh
ZDS_PERMISSIONED_DATA=true
```
When the flag is off, permissioned-data routes return a structured
`MethodNotImplemented` response and do not create or mutate permissioned-space
rows. The API reference marks the space routes with
`x-zds-experimental: true` so clients can treat the namespace as experimental
even when an operator has not enabled it.
The OAuth server follows the same flag. When it is off, a PAR or token request
that asks for a `space:` scope, or for an `include:` permission set that expands
to one, is rejected with `invalid_scope`. Clients can therefore treat the
presence of a `space:` grant on an issued token as proof that the PDS serves the
space routes: ZDS never hands out a grant it will answer with
`MethodNotImplemented`.
`describeServer` also reports `spacesAlpha: true` while the flag is on.
## references
- Announcement: <https://atproto.com/blog/atproto-spaces-alpha> (lists ZDS among
the spaces-compatible PDS implementations)
- Bulletin, the alpha's example app: <https://github.com/bluesky-social/bulletin>
(creates one `my.bulletin.board` space per user; the smallest real
client of this surface)
- Proposal: <https://github.com/bluesky-social/proposals/tree/main/0016-permissioned-data>
- Diary 7, signed commits and sync:
<https://dholms.leaflet.pub/3mqtqvjidqs2p>
- Current discussion: <https://discourse.atmosphere.community/t/permissioned-data-proposal-discussion/946>
- Earlier lexicon discussion: <https://discourse.atmosphere.community/t/permissioned-data-pds-lexicons/879>
- Member-list direction:
<https://discourse.atmosphere.community/t/removing-the-member-list/895>
- App-layer roles and cross-space relations (Habitat's proposal to standardize
reader/writer/manager/owner relationships):
<https://discourse.atmosphere.community/t/spaces-interoperable-fine-grained-permissioning/1161>
- Habitat, "road to release 06: commenting" (one `network.habitat.docs` space
per document plus a `network.habitat.docs.comments` space, with viewer,
commenter, and editor roles derived by relations between the two):
<https://habitat.leaflet.pub/3mvb55bjhbk2n>
- Branch: <https://github.com/bluesky-social/atproto/tree/permissioned-data>
- Lexicons:
<https://github.com/bluesky-social/atproto/tree/permissioned-data/lexicons/com/atproto/space>
- Reference implementation path:
`packages/pds/src/actor-store/space` on the permissioned-data branch
- Bluesky proposal PR:
<https://github.com/bluesky-social/proposals/pull/94>
- How ZDS followed earlier alphas, with the interop evidence of the time:
[history](https://tangled.org/zat.dev/zds/tree/main/docs/history)
ZDS targets the November 12, 2026 Spaces alpha: the `permissioned-data`
branch at atproto commit `d4def6e9f`, published as
`@atproto/space@0.0.0-spaces-alpha-20261112204144`. Use that revision's
Lexicons and handlers for wire contracts; the moving branch can contain later
changes. Upstream is still settling the design, and ZDS follows each alpha as a
hard cut, without aliases for earlier names. For space URI syntax, ZDS follows
the [upstream URI change](https://github.com/bluesky-social/atproto/pull/6010).
The interop suite pins the November 12 SDK with that change's validator backported
from [the reference commit](https://github.com/bluesky-social/atproto/commit/6d08d367133949e4461aa8225536a6023703ac1a).
Clients using SDK versions that require the old URI need an updated validator
to read new-format STAR metadata.
Feedback should respect the research behind the sketch and avoid overfitting to
ZDS or plyr.fm. Name concrete implementation pressure, but frame it as input for
the broader protocol shape.
The current local motivation is private data storage on a resident's PDS. That
is narrower than proving every group/community use case. Recent proposal
discussion reinforces the same posture: groups are the hard case that may
justify the primitive, but ZDS should not bake group semantics into the PDS just
to get private records and blobs working early.
## current prototype surface
ZDS splits protocol data routes from baseline PDS management routes:
- `com.atproto.space.*`: the lifecycle methods `createSpace`, `getSpace`,
`updateSpace`, and `deleteSpace`; the account-migration methods
`exportSpaceMeta`, `importSpaceMeta`, and `importRepo`; `listSpaces`, `listWriters`, `removeWriter`,
`getDelegationToken`, `authorizeSpaceSync`, records, `clearRecords`, blobs,
MAC'd commits, full and incremental repo sync, blob enumeration, notification
registration through `authorizeSpaceSync`, write notifications from repo
hosts (`notifyRepoUpdate`), and credential revocation. As a space host ZDS
calls a registered syncer's `confirmRegistration` and `notifySpaceUpdate`; it
does not serve them.
- `com.atproto.memberspace.*`: `putMembers`, `removeMembers`, and `listMembers`
- `com.atproto.managedspace.checkAccess`: the managing-app hook
ZDS uses the proposal names for the credential and sync-read surface:
`getDelegationToken` and `listRepoOps`.
`createSpace` anchors the space on the authenticated DID and takes
`{spaceType, skey?, policy}`. The policy is an open union discriminated by
`$type`:
- `com.atproto.personalspace.policy`: only the authority reads or writes.
- `com.atproto.memberspace.policy`: `publicRead`, `publicWrite`, optional
`allowedApps`, `publishPolicy`, and `publishMembers`, all booleans default
false. Otherwise members' `read` and `write` flags decide.
- `com.atproto.managedspace.policy`: `managingApp` (a `did#serviceId`
reference on a did:plc or a pathless did:web) decides every read and write;
optional `publishPolicy`.
ZDS stores the policy with defaults filled and unknown fields dropped, and
answers any other `$type` with `UnsupportedPolicy`. `getSpace` returns
`{space, policy}` to the owner only, over OAuth with `read_self` or a session.
`updateSpace` replaces the policy wholesale; a new `$type` deletes the previous
policy's state, so a member list does not survive a round trip through another
policy. The member methods answer `PolicyMismatch` outside a memberspace.
With `publishPolicy`, the authority's own repo in the space holds
`com.atproto.space.policy/self` `{policy}`; with `publishMembers`, it holds one
`com.atproto.memberspace.member/<did>` `{read, write}` per member. They are
written in the same transaction as the configuration change, advance the repo,
and send `notifyRepoUpdate`; clearing a flag deletes them. A did:web member's
percent-encoded port is keyed unencoded (`did:web:localhost%3A2583` becomes
`did:web:localhost:2583`). Direct `createRecord`, `putRecord`, `deleteRecord`,
and `applyWrites` to either collection are refused with 400 in any repo.
`removeWriter` removes an account from the writer set at the next `spaceRev`,
sends registered syncers a `repoRemoved`, and
keeps listing it as removed until its next authorized write. `removeMembers`
and `putMembers` with `write: false` do the same; under `publicWrite`, a member
whose `write` is false is not a writer. `exportSpaceMeta` leaves removed
writers out. `updateSpace` does not re-evaluate the writer set.
`clearRecords` deletes every record in the caller's repo in one transaction and
advances it to a new rev with an empty oplog; the empty repo's digest is
`e5a00aa9…b183ad`. The authority's repo keeps its published records. Under
OAuth the caller needs a `delete` grant for each other collection it holds;
clearing an empty repo changes nothing.
`listRepoOps` pages with an opaque `rev/idx` cursor: a full page (`limit`,
default 100, max 1000) carries `cursor`, and every page carries the repo's
current `commit`, which a syncer checks against its running set hash once it
has applied the last page, the one without a cursor. A repo with no writes is
`RepoNotFound`. `listWriters` uses the
same default and maximum, but orders latest writer states by `spaceRev`.
Each entry names its `$type`: a `com.atproto.space.defs#repoWrite`
`{repo, repoRev, data, spaceRev}`, or a `#repoRemoved` `{repo, spaceRev}`.
Neither carries `prevSpaceRev` here. Every nonempty
page returns its last `spaceRev` as `cursor`; an empty page omits it. Cursors
are opaque strings and exclusive checkpoints. A writer can reappear during
pagination when it advances; consumers must process it idempotently.
ZDS does not serve names from earlier drafts and alphas:
- `getMembers`, `getMemberState`, `getMemberOplog`, and `notifyMembership`
- `com.atproto.space.updateSpaceConfig`
- every `com.atproto.simplespace.*` method
- `getSpaceCredential`, `listRepos`, `notifyWrite`, `putMember`,
`checkUserAccess`, `registerNotify`, `unregisterNotify`, and
`notifySpaceStatus`
`getSpace` and `listSpaces` do not return `members` or `isMember`. A space
credential does not reach `getSpace`; syncers read a published policy record.
## access model
ZDS treats permissioned data as a space credential and writer-repo substrate,
not as a universal group-membership system.
Applications own rich reader/group semantics: label rosters, supporter access,
personal private libraries, community roles, follower-only access, and similar
policy all belong above the low-level PDS substrate. If an application needs
portable access state, it should model that state as application records in a
permissioned space rather than relying on a universal PDS-wide member list.
Cross-space role inheritance is the same kind of application policy. Habitat's
Chalk editor (September 2026) puts a document and its comments in two spaces
and derives comment access from document access inside its own space host,
then asks the community to standardize those relations. Nothing in that shape
needs a PDS primitive: a managing app answers `checkAccess` for the comments
space by consulting the document relation itself. The one substrate limit to
keep in mind is that `checkAccess` answers only `read` and `write`, so a
viewer/commenter/editor split cannot be enforced by a ZDS-hosted space alone; an app that needs tiered write access hosts the
space itself or splits tiers across spaces, as Habitat does.
The member list is stored only as memberspace policy state. It is not
exposed as a protocol sync surface except through records the policy chooses to
publish. ZDS checks a member's read flag for credentials and write flag for
writer authorization. A resident may store records in their own repo even when
the authority denies write access; the authority then excludes that update from
writer registration and notification forwarding. For `managedspace`, the
authority calls the managing app's `com.atproto.managedspace.checkAccess`
with `space`, optional `repo` and `clientId`, and service auth (`lxm` is the
same NSID); the app answers `{read, write}` and the authority uses the one it
needs. Write checks omit `clientId`. The generic PDS implementation of that
method answers both false; policy services replace it with their own decision.
Under every policy the authority itself is authorized without asking anyone.
A managing app that cannot be resolved, fails, answers anything but a 200 with
boolean `read` and `write`, or takes more than 10 seconds is an upstream
failure, not a denial: `authorizeSpaceSync` answers 502
`UpstreamFailure` and leaves the syncer's registration in place, and
`notifyRepoUpdate` answers 502 `UpstreamFailure`, so the repo host retries.
An app's `false` reaches the client as `SpaceNotFound`. The server log has the
cause:
- `space managing app unresolved … err=…`: the app's DID or service fragment
did not resolve to an endpoint.
- `space managing app check failed … err=…` or `… status=…`: the request
failed in transport, or the app answered with an error status or a malformed
body. `401` means it rejected the service-auth token, which an app that logs
only inside its handler will report as never having received the request.
- `space managing app denied …`: the app answered false.
The service-auth token's `aud` is the `managingApp` value exactly as
configured, service fragment included (`did:web:app.example#svc`), as in the
reference PDS. An app that compares `aud` with its bare DID rejects every
check before its handler runs. With `verifyJwt` from `@atproto/xrpc-server`
0.13.4, a zds `checkAccess` token verifies when the app passes its full
service id as `ownDid` and fails with `BadJwtAudience` when it passes the bare
DID.
Delegation tokens identify the user, not the app. For `allowedApps`, ZDS
verifies the separately supplied `clientAttestation` against the client's
published metadata and JWKS before using its `client_id`. `authorizeSpaceSync`
takes everything in its JSON body: `space`, a P-256 `did:key` as
`credentialKey`, and optionally `delegationToken` and `clientAttestation`. The
request carries no authorization header or signature. It answers
`{credential, spaceRev?}`, where `spaceRev` is the space's current revision,
omitted before its first update. A deleted space answers `SpaceDeleted` before
anything else in the request is checked. The user is checked
before the app: a user the policy refuses gets `SpaceNotFound` (400), and only
then can `allowedApps` answer `AppNotAuthorized` (400). Without a delegation
token, a memberspace with `publicRead` issues a credential and a managed space
asks its app about an anonymous reader, both still subject to `allowedApps`;
every other space answers `SpaceNotFound`. The credential binds the key in
`cnf.kid` and, when attested, records `client_id`. Credential uses send
`Authorization: Atproto-Space-Credential ...` and sign `authorization` plus
`atproto-space-audience` under the `atproto-space-credential` label with
`tag="atproto-space-credential"`; `keyid` is optional and must match.
The audience is the repo owner's DID for repo reads and the authority's bare
DID for space-host operations. Signatures are reusable for the same credential
and audience; OAuth DPoP and single-use delegation tokens are unchanged.
Delegation tokens and client attestations name the authority as
`<did>#atproto_pds`, and space credentials are signed only with its `#atproto`
key.
Credentials default to 600 seconds and may last at most 3600 seconds, with
five seconds of clock skew. `notifyCredentialsRevoked` accepts 1–100 credential
JWT IDs, authenticated by the exact authority and addressed to a local repo
DID. Revocations persist for 3610 seconds from receipt and are enforced on
credential use. Removing a member prevents new issuance; it does not currently
send revocations automatically.
Writer notifications are keyed by writer repo. `notifyRepoUpdate` verifies service
auth from the writer repo to the authority's `#atproto_pds` audience
(the bare authority DID is also accepted). A token whose issuer is not the
writer repo, whose audience is not the authority, or whose writer the policy
refuses answers 403 `Forbidden`; a service token whose `lxm` is not the called
method answers 401 `BadJwtLexiconMethod`. Its input is `{space, repo,
repoRev, data}`, with nothing of the space's sequence: only the space host
sequences updates and removes writers. It records `repoRev` and `data`, the
SHA-256 digest of the writer's LtHash state, atomically assigning a
strictly increasing space-wide `spaceRev`. Duplicate/older repo revisions are ignored, and revisions
more than five minutes in the future are rejected. `listWriters` is space-credential-only and
returns this authority-maintained writer set; it never exposes the raw LtHash
state or a reader/member list.
A syncer registers for notifications by passing `notify: {endpoint, token}`
to `authorizeSpaceSync`. `endpoint` is a URL whose origin ZDS calls XRPC
methods on; `token` is the syncer's opaque secret for the space, at most 512
bytes. A registration is the triple (space, endpoint, token): another token is
another registration. Before storing a new one, ZDS calls
`confirmRegistration` on the endpoint with `{space, token, challenge}` and
requires the same `challenge` back; otherwise it answers
`RegistrationNotConfirmed` and issues nothing. A renewal is not confirmed
again. Each authorization renews the registration's expiry to its credential's
(600 seconds). A refusal (`SpaceNotFound`, `AppNotAuthorized`) withdraws the
registration the request carries; an authority that is taken down or
deactivated does not. Registrations are stored in
`permissioned_space_notify_registrations`; the token is never logged.
ZDS sends `notifySpaceUpdate` `{space, token, update}` with no service auth,
fetching endpoints as untrusted URLs (HTTPS, public addresses, no redirects,
10 seconds; `ZDS_ALLOW_PRIVATE_FETCH` lifts the address checks for the smoke
suite). Each sequenced write or removal goes to every active registration as a
`com.atproto.space.defs#repoWrite` or `#repoRemoved` with `spaceRev` and,
after the space's first update, `prevSpaceRev`. That fan-out is best effort:
syncers recover gaps through `listWriters` from their last safely processed
checkpoint. A registration that has lapsed is sent
`notifySpaceUpdate#registrationExpired {spaceRev}` in place of the next update,
and nothing more until it reauthorizes. Deleting a space sends every
registration, lapsed or not, `#spaceDeleted`. Those two notices go through
`permissioned_space_syncer_outbox` and are retried after 1 minute, 10 minutes,
an hour, 6 hours, then every 12 hours, for at least 72 hours; a deletion
notice replaces a pending expiry notice. A notice waits while the authority is
taken down or deactivated, and is dropped once it no longer applies (the
syncer renewed, or the space was recreated). A syncer that answers an expiry
notice with a status other than 408, 425, 429, 500, 502, 503, 504, 522 or 524,
or that cannot be reached within the window, is unregistered.
Repo writes save pending repo-host notifications in the same SQLite
transaction as the records and commit state. The delivery worker coalesces
newer state per writer/space, uses expiring leases, and retries transient
failures with backoff for up to 24 hours per new revision. Permanent errors
stop delivery.
The space host is the authority's PDS. ZDS resolves the authority's
`#atproto_pds` service when notifying a remote authority; there is no dedicated
space-host service or space signing key.
## account status
A taken down, suspended, or deactivated authority answers `authorizeSpaceSync`
and `listWriters` with `RepoTakendown`, `RepoSuspended`, or `RepoDeactivated`,
while credentials it already issued stay valid until they expire. Space writes
and management need an active account. A taken down account keeps a limited
`allowTakendown` session for `listSpaces`, `exportSpaceMeta`, and its own
repo's `getRepo`, `listBlobs`, and `getBlob` (see the takedown runbook). As in
the reference, space reads check the caller's token before the repo's status,
so the limited session gets `InvalidToken` outside its grant, and an admin
token reads any repo that is not deleted.
## moderation
A space blob is the same `(did, cid)` blob as a public one, so
`com.atproto.admin.updateSubjectStatus` with a `repoBlobRef` stops
`space.getBlob` and `sync.getBlob` together (see the takedown runbook). Label
records (`com.atproto.label.record`) are ordinary space records written by the
labeler or the space authority; ZDS stores any collection in a space, and
deciding which labels to honor is an app's job.
## capability discovery
`scopes_supported` in the OAuth metadata lists only `atproto` and the
`transition:` scopes; `space:` scopes are dynamic and cannot be enumerated.
Clients must not infer capability from it; the grant on an issued token is the
portable signal. `listMembers` answers only the owner, over OAuth with a
covering `read_self` grant; other implementations have differed here, so a
client should treat it as owner-only.
## storage shape
ZDS stores many actor repos in one SQLite database, so permissioned data uses
explicit space-scoped tables instead of the public repo tables:
- `permissioned_spaces`: canonical space rows keyed by space URI, with the
normalized `policy_json` on spaces this host is the authority for
- `permissioned_space_actor_state`: actor-local authority/deleted state keyed by
`(space, actor_did)`
- `memberspace_members`: memberspace member-list state keyed by
`(space, member_did)`
- `permissioned_space_records`: current records keyed by
`(space, repo_did, collection, rkey)` with CID, AT JSON value, repo revision,
and indexed timestamp; canonical DAG-CBOR is reconstructed and CID-checked
for full-state export
- `permissioned_space_record_blobs`: which blob CIDs each record in a space
references, so blob reads and collection are scoped to the exact space
- `permissioned_space_repos`: repo-host state, including the full LtHash state
needed to update that writer's local permissioned repo and its commit digest
- `permissioned_space_writers`: authority-host writer registry, containing only
each known writer's latest repo revision, space revision, and 32-byte commit digest
- `permissioned_space_record_oplog`: incremental record changes by
`(space, repo_did, rev, idx)`
- `permissioned_space_notify_registrations`: syncer webhook registrations,
keyed by `(space, endpoint, token)`, with their expiry
- `permissioned_space_syncer_outbox`: pending `#registrationExpired` and
`#spaceDeleted` notices and their retry state
- `permissioned_space_sequence`: persistent last revision for each authority space
- `permissioned_space_notify_outbox`: durable, coalesced repo-host notifications
- `permissioned_space_revocations`: expiring `(space, jti)` revocations
- `permissioned_space_used_delegations`: consumed one-use delegation-token IDs
- `permissioned_space_used_client_attestations`: consumed one-use client
attestation IDs
Space roots use the canonical proposal URI:
```text
at:space/{authorityDid}/{spaceType}/{skey}
```
Permissioned record URIs append `{authorDid}/{collection}/{rkey}`. ZDS migrates the earlier experimental space URI formats in storage. The HTTP API
accepts the canonical `at:space/` form. Previously issued space credentials and
delegation tokens carry an older URI in their signed subject and need to be
replaced after the upgrade.
`listSpaces` enumerates actor-local space rows: spaces the resident owns or has
materialized a permissioned writer repo in. Being named in a memberspace member
list does not make a space appear there.
OAuth space grants use `authority=`, repeated `action=` record operations, and
separate repeated `manage=` space-management operations. A missing authority
or `authority=self` is resolved to the granting account's DID when the token is
issued; a stored grant without an authority matches nothing. The space type is
`*` or one exact NSID, named positionally (`space:<nsid>`) or with `spaceType`
(`space?spaceType=<nsid>`), not both.
When a grant omits `collection`, ZDS preserves that omission and resolves the
space type's declared collections when authorizing a record write, import or
clear. Declaration updates therefore apply to existing grants after the
five-minute lexicon cache expires, including after token refresh. An explicit
collection list stays fixed. Declaration lookup failures return `UpstreamFailure`
without applying the write. Reads and management do not depend on these defaults.
Grants issued before this behavior stored a materialized collection list, losing
the distinction between explicit and default collections. They remain fixed;
reauthorize the app to obtain a declaration-based grant. Permission-set expansion
still happens at issuance; its resulting bare space grants follow declaration
updates in the same way as directly requested ones.
OAuth reads are limited to the authenticated account's own permissioned repo;
another account's repo answers `RepoNotFound`, as an absent one does.
Whole-space writer enumeration and cross-repo reads require a space credential.
Delegation tokens and client attestations are short-lived and consumed together
in one transaction when the authority mints that credential. A missing
or invalid issuance signature does not consume either token. Reusing a consumed
delegation token still fails even with a valid signature.
Permissioned records and blobs are not public repo records. They must not be
squeezed into `records`, `repo_blocks`, `commits`, or `seq_events`.
## host roles and blob ownership
The proposal separates three roles that are often served by one PDS:
- the PDS authenticates its resident and accepts writes
- the repo host stores and serves that resident's permissioned repo and blobs
- the space host describes the space, decides whether to mint space
credentials, lists known writers, and routes notifications
The roles may be implemented by different services, but that does not imply
centralizing every writer's records at the space host. In the proposal's normal
topology, each writer's permissioned repo and referenced blobs remain on that
writer's repo host. A syncer obtains a space credential from the space host,
discovers writers there, and then pulls records and blobs from each writer's
repo host.
ZDS currently serves all three roles for its resident-owned spaces. In
the plyr.fm path, `com.atproto.repo.uploadBlob` places bytes in the resident's
blobstore and a subsequent permissioned record write associates the CID with
that exact space. Public `com.atproto.sync.getBlob` remains unavailable unless
a public repo record also references the blob. Permissioned
`com.atproto.space.getBlob` requires both valid read authority and an exact
`(space, repo, CID)` record reference; a credential for one space cannot be
used to retrieve a blob referenced only by another.
A separate space host may choose to store permissioned records itself as a
compatibility layer for PDSes that do not implement permissioned repos. That is
a valid experimental deployment shape, but it is not equivalent to the
proposal topology: the writer's PDS cannot infer the remote private record's
blob reference, so retention and garbage collection require an additional
contract. ZDS should not invent that contract locally before interoperability
testing establishes the shared requirement.
These invariants must hold, and are worth checking independently before
cross-implementation testing:
- a previously uploaded blob becomes reachable only after a record in the
requested space references it
- the same CID remains unavailable through another space
- public blob reads remain unavailable for private-only references
- record update and deletion update the space-scoped blob reference index
The draft proposal and its reference branch remain works in progress. Treat
their stated topology and wire contracts as the interoperability target while
testing security-sensitive behavior rather than inheriting implementation gaps.
`com.atproto.space.listRecords` returns current record values by default, in
line with the permissioned-data proposal. Consumers that only need the
collection, rkey, and CID listing can pass `excludeValues=true` to avoid
materializing record JSON.
`com.atproto.space.listRepoOps` follows the same value rule. Create and update
operations inline a value only while that operation's CID is still the current
record CID; deletes and superseded operations remain metadata-only.
`com.atproto.space.getRepo` is the full-state recovery path. It returns a
STAR v1 archive (`application/vnd.dasl.star`): magic `2a 6c 01 00`, DRISL
metadata holding `$type: "atproto-space-repo"` and the commit, then one record
path / record DRISL pair per record in strict bytewise path order. Space
records are limited to 1 MiB of DRISL. Blobs are deliberately excluded;
`listBlobs` enumerates referenced CIDs and `getBlob` serves the authorized
bytes. Pairs carry the `0x01` control byte and the archive ends with `0x00`,
as required by the published STAR framing. Legacy STAR-lite archives are rejected.
`exportSpaceMeta` answers with the same content type, and `importRepo` and
`importSpaceMeta` refuse a body sent as anything else with `InvalidRequest`.
## commit MACs
A commit (`com.atproto.space.defs#commit`) is `{ver, repo, space, rev, data}`,
where `data` is the SHA-256 digest of the repo's LtHash state. It carries no
signature. The repo host authenticates it to each syncer with a MAC keyed by a
per-request shared secret:
- every account has a P-256 `#atproto_kem` key in its DID document, generated
at account creation and published in the PLC genesis operation
- the syncer asks with an `Accept-Signature` member, under any label, tagged
with the profile and keyed by a fresh ephemeral P-256 key share per request:
`mac=("atproto-space-commit";sf);keyid="did:key:...";tag="atproto-space-commit"`
- the host derives the shared secret as HPKE's secret export (RFC 9180 §6.2:
DHKEM(P-256, HKDF-SHA256), HKDF-SHA256, export-only, info `atproto-mac`, empty
exporter context) and answers with an `Atproto-Space-Commit` header,
`ver=1, repo="...", space="...", rev="...", data=:<base64>:`, plus
`Signature-Input` and `Signature` under the requested label: an RFC 9421
`hmac-sha256` signature covering that header as a structured field, with the
requested parameters
- `getRecord` uses the `atproto-space-record` tag and header,
`uri="...", cid="..."`
`getLatestCommit`, `listRepoOps`, `getRepo`, and `getRecord` require a MAC
request when called with a space credential and answer `400 InvalidSpaceMac`
when none carries the profile's tag, or the one that does covers anything but
the profile's header with `sf`, carries a parameter other than `keyid`, `tag`
and `alg`, names an alg other than `hmac-sha256`, or keys by something other
than a P-256 `did:key`. An account reading its own repo over OAuth may omit
it. These responses send `Vary: accept-signature` and expose the covered,
`signature-input` and `signature` headers to browsers. Every `listRepoOps`
page is MAC'd over its commit. `listRecords`, `getBlob`, and
`listBlobs` carry no MAC. The wire primitives are `zat.space.mac` and
`zat.space.kem`.
The MAC shows the host vouched for the commit to whoever holds the shared
secret, and to nobody else: the syncer could compute the same MAC, so a leaked
response proves nothing to a third party. Anyone holding a shared secret can
substitute records and MAC the forgery. `verifyRepoStarFull` checks the MAC
and archive consistency; content provenance still comes from the authenticated
fetch from the author's resolved repo host.
Accounts created before KEM keys existed get one from a background backfill
that runs with `ZDS_PERMISSIONED_DATA=true`, as do accounts created with a
caller-built PLC operation, which cannot carry a key the caller has never seen.
It rescans every ten minutes. For each account without a key,
it publishes `atproto_kem` through a PLC operation signed by the PDS rotation
key, stores the key, and emits an identity event. An account whose document
this PDS cannot update (did:web, a DID not on the directory, a rotation key the
PDS does not hold, or an account served elsewhere) still gets a key, logged so
its owner can publish it. Failures, such as an unreachable directory, are
retried after a minute, backing off to an hour. Until then, MAC'd reads
for that account fail with `InternalServerError`.
`getRecommendedDidCredentials` includes `atproto_kem`, and
`submitPlcOperation` rejects an operation that drops or changes it.
LtHash also does not provide a compact record inclusion proof: subtracting an
arbitrary record's contribution and adding it back works even when the record
was never in the set. `getRecord` returns a URI, CID, and value, not an inclusion
proof. A secondary service serving selected records therefore needs its own
trust relationship with consumers or independent verification against the
source; it cannot use the repo commit as transferable proof of those records.
## moving spaces with an account
After the usual account migration steps, a migration tool:
1. Lists the account's spaces on the old host with `com.atproto.space.listSpaces`,
following `cursor`. The spaces the account is the authority of are those
whose `space` URI names the account's DID.
2. For each owned space, downloads `com.atproto.space.exportSpaceMeta?space=…`
and POSTs the bytes to `com.atproto.space.importSpaceMeta` on the new host with
`Content-Type: application/vnd.dasl.star`. This must come before importing the
account's own repo in that space, which otherwise answers `SpaceNotFound`.
3. For each space the account holds a repo in, downloads `com.atproto.space.getRepo`
for its own repo and POSTs it to `com.atproto.space.importRepo`, then copies the
repo's blobs with `com.atproto.space.listBlobs` and `getBlob` on the old host and
`com.atproto.repo.uploadBlob` on the new one. A blob an imported record
references is kept.
Imports replace what the new host holds, so a failed step can be retried. They
take the account's own session or OAuth (`manage=create` and `manage=update` for
importSpaceMeta, `create` for each collection in the archive for importRepo), not
an app password, and accept archives up to 128 MiB. Writer entries keep their
`spaceRev`, so syncers' `listWriters` cursors stay valid; the imported repo gets a
new rev with unchanged data. Notification registrations, credential revocations,
and deleted-space tombstones are not carried over. Space metadata archives name
the writer field `repoRev`.
## differences from the reference PDS
- `checkAccess` on ZDS is the generic PDS answer, denying both `read` and
`write`.
- ZDS answers `RepoNotFound` with HTTP 404 where the reference PDS (checked at
`3a0b8c6`) threw `InvalidRequestError` (400). The error name is the same.
`com.atproto.repo.getRecord` answers 400 like the reference, because Germ's
sign-in read the 404 as a failure.
- `clearRecords` applies no separate write rate limit; ZDS has none for space
writes.
- The space imports accept up to 128 MiB, as `com.atproto.repo.importRepo` does,
and have no "accepting imports" switch. `com.atproto.repo.importRepo` itself
still accepts app-password sessions; the space imports do not.
- ZDS reads only a space type declaration's `collections`, not its `title`, so
its consent screen shows the NSID.
- Garbage collection of empty repos and removed writers after 72 hours is
optional upstream, and ZDS does not collect.
- ZDS never revokes credentials as a space host, so no registration is dropped
for a revoked credential; it honours `notifyCredentialsRevoked` as a repo
host.
## Zat
`zat.space` owns the Spaces wire primitives: space URIs, LtHash, STAR archives,
delegation-token and credential JWTs, RFC 9421 credential signatures, and the
KEM and MACs. ZDS uses them and does not keep its own copies; a primitive ZDS
needs that Zat lacks belongs in Zat. Do not edit or patch the sibling `zat`
repo from ZDS without stopping and making the proposed Zat change explicit.
## code boundaries
Permissioned data is experimental code and should stay segmented:
- HTTP dispatch and XRPC semantics live in `src/atproto/space.zig`.
- Space policies (normalization, member checks, published records) live in
`src/internal/space_policy.zig`.
- The resident private-record browser lives in the `/account/spaces` section
rendered by `src/internal/account.zig`.
- OAuth scope parsing for `space:` scopes lives in `src/internal/scopes.zig`.
- Persistent state lives in permissioned-data tables in
`src/storage/store.zig`.
- API-reference surfacing is marked experimental through the `space` router
group and `x-zds-experimental`.
Normal repo writes, sync events, account auth, and appview proxy behavior should
not learn permissioned-data special cases unless the protocol requires a shared
primitive. Prefer a permissioned-data helper over scattering conditionals into
stable PDS code.
## SDK interop lane
The SDK interop lane runs the permissioned suite with the Bluesky
`@atproto/space` SDK checking ZDS's signatures, MACs, and STAR archives.
`tools/space-sdk` pins the November 12 alpha from npm, with a pnpm lockfile.
Its packages depend on each other with caret ranges, which also match
unrelated `0.0.0` releases, so `pnpm-workspace.yaml` overrides every
`@atproto` package in the tree to the alpha. `just smoke-space-sdk` installs it
and runs the lane, and CI runs it on every push. To try another snapshot, point
`ZDS_SPACE_SDK_DIR` at a project with `node_modules/@atproto/space` and run
`just smoke-permissioned`.
## checks
Run both smoke lanes when touching this area:
```sh
just test
just smoke
just smoke-permissioned
git diff --check
zig zen
```