zat.dev/zds
atproto pds · mirror of https://tangled.org/zat.dev/zds
zds 0.25.1 Latest 2 packages, all images
0
0
# architecture
`zds` is a Zig implementation of an AT Protocol Personal Data Server.
The server owns account state, repo state, sessions, OAuth authorization,
service auth, blobs, sync output, and identity operations. It does not implement
an appview. Appview requests are forwarded through the generic `atproto-proxy`
path: to the service the proxy header names, or to the configured appview for
`app.bsky.*` methods sent without one.
The proxy forwards the request headers the reference PDS does
(`accept-language`, `atproto-accept-labelers`, `x-bsky-topics`, every
`x-atproto-*`) plus `if-none-match`, and signs its own service-auth token;
the caller's authorization and DPoP proof stay here. The answer keeps the
service's status and content type, and these response headers:
`content-type`, `content-language`, `atproto-repo-rev`,
`atproto-content-labelers`, `retry-after`, and, as Tranquil adds, `vary` and
`etag`. A `304 Not Modified` passes through without a body.
## compatibility
Start with the AT Protocol specifications and cross-check the reference PDS.
Document intentional differences. Experimental Spaces APIs track the upstream
alpha behind `ZDS_PERMISSIONED_DATA` and can change incompatibly.
Routing, `/api`, and `/api/openapi.json` use the same comptime endpoint inventory.
## boundaries
- `zat` owns AT Protocol primitives: syntax, TIDs, DID/handle resolution, JWT
helpers, DAG-CBOR, CAR, MST, repo verification, OAuth helpers, streaming
clients, and the Spaces wire primitives (`zat.space`: space URIs, LtHash,
STAR archives, space tokens, credential signatures, the KEM and MACs).
- `httpz` owns the HTTP/1.1 server mechanics: request parsing, response
serialization, connection handling, upgrades, and server-side websocket
plumbing. ZDS adapts AT Protocol handlers onto that server boundary.
- `zds` owns PDS policy and persistence: accounts, repo writes, sessions,
app passwords, passkeys, storage, server routes, sync production, account
migration, and the local login/security surface.
- Dependency fixes should happen at the owning layer. Since this project also
maintains `zat`, ZDS depends on a released `zat` version rather than vendoring
or patching a private copy.
- Space policy, `space:` scope matching, and space storage are ZDS's; the wire
formats and cryptography they use come from `zat.space`.
- SQLite stores account, repo, commit, token, OAuth, blob metadata, and identity
state, plus Spaces revocations, authority sequencing, and pending notifications.
- One writer connection, serialized by the store's database lock, takes every
write and every read-modify-write. Request-path reads that only read (record,
repo and sync lookups, account and token lookups, firehose backfill, the
public pages) use a small pool of read-only WAL connections
(`ZDS_DB_READERS`, default 4), so they do not wait behind a write or a blob
GC pass. Each statement on a reader sees the latest committed state, and a
write commits before it returns, so a read after a write sees it; a reader
never sees a write still inside its transaction. Full `getRepo` exports open
their own connection (see [sync](#sync)).
- Password sessions are durable rows keyed by access and refresh JWT IDs. Refresh
rotates the stored token family instead of trusting self-contained JWTs alone.
- Account-plane audit events store subject, actor, and optional controller DID
fields. That mirrors Tranquil's delegation-ready model without exposing user
delegation before the surrounding account controls exist.
- Invite codes follow the official PDS split between code metadata and recorded
uses; account creation consumes a code while holding the store lock.
- Blob bytes live in the disk blobstore rooted at `ZDS_BLOBSTORE_PATH`.
- Uploads sniff at most 4,100 bytes for common image, video, audio and archive
formats before enforcing MIME-based OAuth permissions. Detected types take
precedence over the request Content-Type; unrecognized formats use that header
(or `application/octet-stream` if absent). The remaining body streams to disk.
- Passkey storage follows Tranquil's core shape: credential ID, public key,
signature counter, friendly name, and timestamps. Passkeys are outside the
official PDS surface ZDS tracks for compatibility.
## repo write invariants
Repo writes must match reference PDS behavior:
- `$type` must match the collection being written.
- omitted rkeys are generated as TIDs.
- known `key: "tid"` records reject explicit non-TID rkeys.
- known `literal:self` records require rkey `self`.
- known records return `validationStatus: "valid"`.
- unknown lexicons return `validationStatus: "unknown"` unless a known schema is
available and validation succeeds.
- a created or updated record may name only blobs this account uploaded and
that are not taken down; anything else answers `400 BlobNotFound` "Could
not find blob: <cid>" and nothing is written. importRepo is exempt, since a
migrating repo's blobs arrive after it (`listMissingBlobs`).
- writes update the MST, write a signed commit block, emit sync events, and
request relay crawls.
These rules are grounded in `bluesky-social/atproto/packages/pds` record
preparation and Tranquil's validation/conformance model.
## sync
`subscribeRepos` and sync read endpoints expose the local repo state. Relay
visibility depends on valid repo commits, coherent event frames, and crawl
requests. `ZDS_CRAWLERS` should include both `https://bsky.network` and
`https://vsky.network` for current deployment coverage.
A full `com.atproto.sync.getRepo` export contains only the blocks reachable from
the current commit (`zat.mst.collectReachableBlocks`), so deleted and replaced
records do not leak. File-backed exports read from their own read-only SQLite
transaction, so writes and account reads do not wait behind a large export, and
at most `ZDS_MAX_CONCURRENT_REPO_EXPORTS` full exports (default 4) run at once.
`since` exports filter blocks by repo revision.
`getRepo`, `getRecord` and `getLatestCommit` answer with a weak `ETag` naming
the repo's current commit CID and `Cache-Control: no-cache` (`private` when
the request carries credentials); `getBlob` tags a blob with its CID. A
request whose `If-None-Match` names the current tag gets `304 Not Modified`
after the same availability checks, without building the export.
## auth and login
OAuth follows the ATProto OAuth profile: PAR is required, redirect URIs are
validated against client metadata, permission-set includes must resolve, tokens
enforce granular repo/blob/rpc/account/identity/space scopes, DPoP-bound OAuth access
tokens must present matching proof headers on resource requests, and revocation
affects resource-server checks. A resource request whose DPoP proof lacks a
nonce gets the reference's challenge: `401`, `WWW-Authenticate: DPoP
error="use_dpop_nonce"`, a `DPoP-Nonce` header and the body error
`use_dpop_nonce` (some clients, such as atproto-oauth's `DpopRetry`, retry only
on the body). Every other token failure on a DPoP request is likewise a `401`
whose challenge and body error name the OAuth code: `invalid_dpop_proof` for a
proof that fails verification, `invalid_token` for the rest. Bearer-scheme
failures keep the XRPC names (`InvalidToken`, `ExpiredToken`), since that
scheme also carries password sessions and service auth. Requested scopes must each match a scope in the client metadata:
a registered scope without parameters (`repo:*`, `blob:*/*`) also covers
narrower forms of its resource, and one with parameters covers only itself.
`rpc` permissions follow the reference grammar: methods are `*` or exact NSIDs,
positionally or as `lxm` parameters but not both, exactly one `aud`, no other
parameters, and not `*` for both; values compare percent-decoded. `repo`
permissions name one or more collections, each `*` or an exact NSID,
positionally or as `collection` parameters but not both, with optional
`action` parameters of create, update or delete; `blob` permissions name one
or more accepted types (`*/*`, `type/*` or `type/subtype`), positionally or
as `accept` parameters but not both. Neither takes other parameters, and
partial wildcards such as `repo:app.bsky.feed.*` are not collections. A scope
outside these grammars is refused at sign-in and grants nothing. Redirect matching is exact, with the RFC 8252
loopback exception the reference provider applies: a client whose metadata says
`application_type: native` and registers `http://127.0.0.1/callback` (or the
`[::1]` form) without a port matches that redirect on whatever port it bound at
request time. A registered port still has to match and `localhost` is not a
loopback host for this redirect exception. Separately, the virtual OAuth client
ID `http://localhost` supports the ATProto localhost development profile, with
loopback-IP redirect URIs and metadata supplied in its query string.
Password sessions and app passwords match the reference PDS account model.
Session JWTs are accepted only when their JTI is present in the active session
table, so revocation and refresh rotation can be enforced by storage. The
answers a client gets for an expired, revoked, or replayed token are in
[account security](https://tangled.org/zat.dev/zds/blob/main/docs/account-security.md#sessions).
App-password sessions are attributed to the app-password name, and revoking the
credential revokes those sessions too. The session schema already carries an
optional `controller_did` column for future delegated-account flows, following
Tranquil's controller-vs-subject split.
Passkeys are an additional OAuth login credential inspired by Tranquil, backed
by the local `webauthn` dependency and stored in SQLite. Discoverable passkey
login is supported so an account can be chosen by the authenticator during the
OAuth flow.
`/account` is the resident management surface. Its security section,
`/account/manage`, manages passkeys and app passwords with account-password
authentication, matching the official PDS boundary that app passwords cannot
mint or revoke other app passwords.
PDS-owned `app.bsky.actor` preferences are handled locally because the official
PDS implements those routes. Appview reads and writes remain behind the generic
`atproto-proxy` path.
### account web surfaces
Follow the reference PDS account manager's categories: Home, Account, Devices,
Apps, About. ZDS currently exposes Home, Account, Apps, About. Credentials
(passkeys and app passwords), email, and account status belong together under
`/account/manage`; `/account/security`, `/security`, and `/passkeys` redirect
there. App access uses `/account/apps`, with `/account/sessions` retained as an
alias. Do not add a separate security/settings dashboard for each feature.
The experimental `/account/spaces` data viewer remains reachable from Home but
is not an account-management navigation section. A future device-management
view should use the reference Devices category instead of introducing another
settings concept.
Reference: `bluesky-social/atproto`,
`packages/oauth/oauth-provider-ui/src/routes/account/u/$accountId/route.tsx`
(inspected 2026-09-05).