# brain-pds
Repo layer of the Brain's PDS (Personal Data Server) for atproto, vendored from Cirrus. The module holds the code that stores a signed repo in a Durable Object's SQLite, serves it, and streams its commits.
| | |
|---|---|
| Worker | `brain-x-pds` |
| Durable Objects | `Registry` as `REGISTRY`, one object; `Repo` (`AccountDurableObject`) as `REPO`, one per repo |
| Blob store | `BLOBS` of `pds_bucket`, over the platform cells `blobs` and `rows` |
| Packages | `@atproto/repo`, `@atproto/crypto`, `@atproto/lex-*`, `@atcute/*`, `@ipld/car`: one bundle, the file `atproto.js`, loaded by `pds_bundle` with `library` and read by `pds_libs` (cell "bundle building") |
## Cells
Each vendored cell takes the cells it imports as parameters and returns the names its upstream file exports. A comment on its first line names that file.
| Cell | Upstream file | Holds |
|---|---|---|
| `pds_repo_storage` | `repo/storage.ts` | `SqliteRepoStorage`: blocks, repo state, firehose events and blob tables in `SqlStorage` |
| `pds_repo_engine` | `repo/engine.ts` | `RepoEngine`: MST, signed commits, record writes, `applyWrites`, CAR import |
| `pds_repo_sequencer` | `repo/sequencer.ts` | `Sequencer`: sequence numbers and the `#commit`, `#identity`, `#sync` and `#account` frames |
| `pds_repo_firehose` | `repo/firehose.ts` | `Firehose`: WebSocket broadcast and cursor replay |
| `pds_repo_sync` | `repo/sync.ts` | `getRepoCar`, `getBlocksCar`, `getRecordProofCar` |
| `pds_repo_blobs` | `repo/blobs.ts` | `BlobStore`: staged and public blob keys in R2, `extractJsonBlobCids` |
| `pds_repo_facet` | `repo/facet.ts` | `RepoFacet`: the RPC target the Worker calls |
| `pds_keys` | none | `generateSigningKey`, `seal`, `open`, `hkdf`, `publicKeyOf`: key generation, sealing and HKDF |
| `pds_plc` | none | `genesis`, `didOf`, `signOperation`, `cidOf`, `update`: the operations of a did:plc, their signatures, the DID and the CID of an operation |
| `pds_prove` | none | the proof and `check` of a record of any repo, by its DID document, `sync.getRecord` and `verifyProofs`; `checkHandle`, a handle's DID; `refusedHost` |
| `pds_auth` | none | `issue` and `verify`: the HS256 tokens of an identity, under a key derived from `PDS_WRAP_KEY` |
| `pds_registry` | none | `RESERVED_NAMES`, the default `reservedNames`, and `Registry`: the Durable Object that holds identities, controllers, quotas, the cluster key and the host-wide sequence |
| `pds_settings`, `pds_make_app` | none | the settings read from `config`, and the factory of the Hono app |
| `pds_bucket` | none | R2's `put`, `get`, `head`, `delete` and `list`. A key's bytes are in `blobs`, its size and type in the row `blob/KEY`.
A promote copies no bytes. |
| `pds_account_do` | `account-do.ts` | `AccountDurableObject`, without the person-account store and the OAuth store |
| `pds_xrpc_repo` | `xrpc/repo.ts` | handlers of `com.atproto.repo.*` |
| `pds_xrpc_sync` | `xrpc/sync.ts` | handlers of `com.atproto.sync.*` |
| `pds_relay` | `relay.ts` | `pokeRelaysIfUnheard`: `requestCrawl` to the relays when nobody subscribes |
| `pds_cbor_compat`, `pds_validation`, `pds_format` | `cbor-compat.ts`, `validation.ts`, `format.ts` | DAG-CBOR encoding, record validation, content-type detection |
| `comLopecodeModuleLexicon` | none | the lexicon JSON of the record `com.lopecode.module` |
| `pds_objects` | none | `Registry` and `AccountDurableObject` as the Worker declares them: each reads `PDS_WRAP_KEY` from `secrets` |
| `pds_app`, `pds_service`, `pds_announce` | none | the Hono app, the service and its announcement |
| `pds_lexicons`, `pds_atproto_lexicons` | none | the lexicon of each method: the Worker's own, and atproto's for the `com.atproto` methods |
| `pds_notice` | none | the licence text and upstream commit of the vendored code, as a value |
| `pds_xrpc_scope` | none | `requireScope` and `buildScopeChecker`, which let every caller through |
## Settings and bindings
`AccountDurableObject` and the handlers read these from the Worker's environment.
| Name | Meaning |
|---|---|
| `INITIAL_ACTIVE` | `true` or `1` starts a new repo active. Unset also starts it active. Any other value starts it deactivated. |
| `BLOBS` | The bucket of `pds_bucket`, which `pds_app` sets in the app's env. An env that brings its own `BLOBS` keeps it. |
| `RELAYS` | Comma-separated relay URLs for `requestCrawl`. Unset or empty, the Worker asks no relay. |
| `PDS_HOSTNAME` | Hostname of the PDS. Unset, a `com.atproto` method takes `x-forwarded-host` of the kernel. Another method takes the setting `publicHost`, else `host`. |
| `PDS_WRAP_KEY` | A secret of the core, 32 bytes in base64, read with `secrets`. It seals the signing keys. Unset, a mint answers 503 `WrapKeyMissing`. |
| `REGISTRY` | Durable Object namespace of `Registry`. The Worker names the one object `registry`. Without it the identity methods answer 503 `RegistryUnbound`. |
| `REPO` | Durable Object namespace of `Repo`, which `Registry` calls. Without it `identity.mint` throws `RepoUnbound`. |
The owner stores these settings for the Worker. The Worker reads them from `config` at each call.
| Setting | Meaning |
|---|---|
| `mintQuota` | Identities a member holds at most. Default 5. The owner has no cap. |
| `recoveryDidKey` | The `did:key` of the owner's recovery key. Each genesis operation lists it first. Unset, `identity.mint` answers 503 `RecoveryKeyUnset`. |
| `plcUrl` | Base URL of the PLC directory. Default `https://plc.directory`. |
| `relays` | Comma-separated relay URLs for the registry's `requestCrawl`. Unset or empty asks no relay. An entry that is not a URL makes `identity.mint` throw `InvalidSettings`. |
| `handleDomain` | Domain of the handles. Unset gives no identity a handle. A handle is a name under this domain. |
| `reservedNames` | Comma-separated names that no member takes. Unset or empty gives the default list below. |
| `tokenMinutes` | Lifetime of a mint token and an access token, a whole number of minutes from 1 to 1440. Default 15. |
| `proveMs` | Milliseconds that `proveRecord` spends on its two reads at most. Default 10000. |
| `proveBytes` | Bytes that `proveRecord` reads at most from each of its two reads. Default 1000000. |
| `checkPerCaller` | Calls of `checkRecord` that one caller makes in a UTC day. Default 20. |
| `checkPerHost` | Reads of one host that `checkRecord` makes in a UTC day, for every caller together. Default 500. |
| `dohUrl` | The DNS-over-HTTPS resolver of `checkHandle`, which answers JSON. Default `https://cloudflare-dns.com/dns-query`. |
| `handleMs` | Milliseconds that each read of `checkHandle` takes at most. Default 5000. |
| `handleBytes` | Bytes that `checkHandle` reads at most from each answer. Default 65536. |
| `publicHost` | The host that the `com.lopecode` methods name in DID documents, tokens and crawl requests. Unset, they name `host`. |
| `host` | The Brain's own host, bound by the deployer. |
A `mintQuota`, `handleDomain`, `reservedNames` or `tokenMinutes` of the wrong form fails the call with `InvalidSettings`. An entry of `reservedNames` that is not a name is the wrong form.
The default `reservedNames` holds these names:
```
admin,administrator,support,security,abuse,postmaster,hostmaster,webmaster,noreply,no-reply,official,staff,moderator,owner,system,account,accounts,billing,login,logout,signin,signup,register,settings,status,about,contact,privacy,terms,legal,cloudbrain,lopecode,brain,bluesky,atproto,delve,delvetown,plc-directory,handle,invalid,kernel,deployer,database,browser,canary,container,dashboard,inbox,issues,knowledge,library,proxy,snapshot,static,topic,usage,whatsapp,mail,send,cf-bounce
```
## Identity of a repo
A `Repo` object holds the DID, the handle and the signing key of its repo in its own SQLite table `identity`. No Worker setting carries them. The registry calls `provision` on the object when it mints the identity.
- `provision({ did, handle, signingKey? })`: stores the identity. `did` is a DID and `handle` defaults to `handle.invalid`. The object generates a secp256k1 signing key and derives the public key from it.
- An optional `signingKey` of 64 lowercase hex characters imports that key instead. A call with invalid input throws `InvalidRequest`.
- A second `provision` with the same DID, and the same key when it gives one, changes nothing. A second call with any other DID or key throws `RepoAlreadyProvisioned`.
- `identity()`: answers `{ did, handle, signingKeyPublic }`, or null before `provision`. It never answers the signing key.
- Every other method of an object without an identity throws `RepoNotProvisioned`.
A handler takes the stub of the object that holds the repo. It compares the `repo` or `did` parameter with the DID of that object and answers 404 `RepoNotFound` when they differ. The caller that picks the stub names the object by the DID, as the test rig does.
## Signing keys
The object seals its signing key before it stores it. No method answers the key, and no log line holds it.
- The object makes the key with the runtime's random source. The key never leaves the object.
- `hkdf` derives an AES-256 key from `PDS_WRAP_KEY` with HKDF-SHA256. The salt is a fixed label. The info joins `seal:` to the DID.
- `seal` encrypts the key with AES-GCM under that key, with a random 12-byte IV and the DID as additional data. It answers `v1.` and the base64 of IV and ciphertext.
- The table `identity` holds the sealed text and the public key only.
- The object opens the key when it starts the repo engine, and the engine signs the commits of this repo only.
- `open` throws `KeyUnsealFailed` for another DID, another wrap key or a changed text.
- Another `PDS_WRAP_KEY` cannot open the stored keys; they need a reseal under the new secret.
## The service
The cell `pds_service` declares the Worker `brain-x-pds` and `pds_announce` announces it. The method `com.lopecode.brain.pds.status` answers `{ worker, repoLayer, routed }` to a trusted caller. `routed` is true: the service declares its `com.atproto` methods and the path `/.well-known/atproto-did`, so the core forwards them to the Worker.
The rule of each `com.atproto` method and of the path is `who: "anyone"` with `allow: "true"`. The core lets every caller through, anonymous included. The declared methods are the twenty of "Server methods", "Firehose" and "Repo reads".
- Server: `server.describeServer`, `server.createAccount`, `server.createSession`, `server.refreshSession` and `server.getSession`.
- Identity: `identity.resolveHandle`, `identity.updateHandle` and `identity.getRecommendedDidCredentials`.
- Sync: `sync.subscribeRepos`, `sync.getRepo`, `sync.getRepoStatus`, `sync.getLatestCommit`, `sync.getBlocks`, `sync.getBlob`, `sync.listBlobs`, `sync.getRecord` and `sync.listRepos`.
- Repo: `repo.describeRepo`, `repo.getRecord` and `repo.listRecords`.
## Proving a record
`com.lopecode.brain.pds.proveRecord` takes `uri` and `cid` and proves that the record at `uri` has the CID `cid` in its author's signed repo. The record may sit on any PDS.
1. The `uri` is `at:////`. A handle in place of the DID proves nothing.
2. The Worker reads the DID document: `/` for a `did:plc`, `https:///.well-known/did.json` for a `did:web` of a bare host. The document's `id` is the DID.
3. The document names the key `#atproto`, a Multikey, and the service `#atproto_pds`, an `https` URL.
4. The Worker reads `com.atproto.sync.getRecord` of that PDS, a CAR of the commit, the MST path and the record.
5. `verifyProofs` of `@atproto/repo` checks each block's hash, the commit's DID and signature, and the record's CID in the MST.
The answer is `{ proved: true, did, cid, rev, record }`, `rev` the commit's and `record` the record as JSON. Any failed step answers `{ proved: false, why }` with status 200. `why` names the step, or holds the library's message. The two reads share one bound, `proveMs`; past it the answer is `{ proved: false, why: "timeout" }`. Each read holds at most `proveBytes` bytes. A `content-length` above it, or a body that passes it, answers `{ proved: false, why: "too large" }`. The Worker stops reading that body.
The rule is `caller.id == "worker:brain-x-delve" || caller.id == "owner"`. The method reads public data only, but each call makes two outbound reads.
## Checking a record
`com.lopecode.brain.pds.checkRecord` takes `uri`, and optionally `cid` and `history`. It answers the current CID of a record of any repo. A town post that quotes a record's CID gets its check from this call.
1. The `uri` is `at:////`, of a `did:plc` or a `did:web` of a bare host. Otherwise the call answers 400 `InvalidRequest`. A `cid` that is no CID answers 400 too.
2. The Worker reads the DID document as `proveRecord` does, then `com.atproto.sync.getRecord` of the PDS it names.
3. The CID at the record's key comes from the commit's MST.
4. `verifyProofs` checks each block's hash, the commit's DID and its signature. It checks that CID at the key too, or the key's absence.
The answer is `{ checked: true, uri, did, pds, readAt, rev, found, signed: true, cid, createdAt, matches, note }`.
- `readAt` is the time of the request to the PDS. `rev` is the commit's.
- `cid` and `createdAt` are set when the repo holds the record; `createdAt` only when the record has one.
- `matches` is set when the call gives a `cid`: true when it is the record's current CID.
- `note` is set when `history` is true and the given `cid` does not match. It names the record's current CID, or says the key holds no record. The check reads no earlier version.
- A PDS that answers `RecordNotFound` gives `found: false` and `signed: false`, as no signed proof came with it.
- Any other failure answers 200 `{ checked: false, uri, did, why }`, with `pds` and `readAt` when the read got that far. `why` is `timeout` past `proveMs`, and `too large` past `proveBytes`.
The check reads only hosts of the public internet. `refusedHost` refuses a URL that is not `https` on port 443. It refuses an IP address, a name of one label, and a name under `localhost`, `local`, `internal`, `lan`, `home`, `arpa`, `test`, `invalid` or `example`. A refused host answers `checked: false`, and the Worker reads nothing from it. No read follows a redirect.
The bounds are rows of the Worker, each a statement of `rows.addWithin`, keyed by the UTC day:
- A call takes a place of `checkPerCaller` first. The caller of a call by post is `x-brain-holder`, `post:`; of any other call, the core's `x-brain-caller`. Past it, 429 `RateLimitExceeded` with `bound: caller`.
- Each read takes a place of `checkPerHost` for its host, the directory's and the PDS's. Past it, 429 `RateLimitExceeded` with `bound: host`, and that read does not go out.
- A refusal names `until`, the next UTC midnight. The first check of a UTC day deletes the rows of the days before.
- Without the platform cell `rows` the method answers 503 `RowsUnbound`.
The rule is `caller.holder.startsWith("post:") || caller.trusted || caller.id == "worker:brain-x-delve"`. A stranger calls it by a post, which `brain-x-delve` bounds with its `postMethods` share. The owner, a member, a token and `brain-x-delve` call it over HTTP. A call over HTTP with no account gets 403.
A call by post is two lines and a key, as `brain-x-delve` reads them:
```
@cloudbrain.delve.town pds.checkRecord
uri: at://did:plc:7euawtxp2hu7n7oap2lbstjj/town.delve.feed.post/3mzrnyaz2zd2w
cid: bafyreidx2orvw7sc5lyd7k6l2vzidcwpn3ssk25rptyros5xg6dewstfzi
```
## Checking a handle
`com.lopecode.brain.pds.checkHandle` takes `handle`, and optionally `did`. It answers the DID that a handle points at, as the atproto handle spec resolves it. A town post that names a handle and a declared DID gets its check from this call.
1. The `handle` is an atproto handle by its syntax, in any case. The Worker drops one leading `@`. Otherwise the call answers 400 `InvalidRequest`. A `did` that is no DID answers 400 too.
2. A handle under a local or reserved suffix, as `refusedHost` names them, answers 200 `{ checked: false, handle, why }`. The Worker reads nothing then.
3. DNS: the resolver `dohUrl` answers the TXT records of `_atproto.`. Exactly one record `did=` gives `dns`.
4. HTTPS: the resolver answers the A and AAAA records of the handle first. The Worker skips a name with no address, or with a private, loopback, link-local, shared or multicast address.
5. Otherwise the body of `https:///.well-known/atproto-did`, a DID alone, gives `http`.
6. `did` is `dns`, else `http`. `method` is `both` when the two agree, else the source of `did`.
7. The Worker reads the DID document of `did` as `proveRecord` does. A `did:web` host passes the same address check first. `document` is `{ pds, alsoKnownAs }` of a document whose `id` is `did`.
8. `bidirectional` is true when `alsoKnownAs` holds `at://`.
The answer is `{ checked: true, handle, did, method, dns, http, document, bidirectional, expected, matches, readAt, why }`.
- A handle that resolves to nothing answers 200 with `did: null` and `method: null`.
- `expected` is the `did` given, or null. `matches` is true when `did` is the DID given. The answer has it only with a `did` given.
- `why` names the reason for each of `dns`, `http` and `document` that found nothing. A reason is a status, `timeout`, `too large` or a refused host.
- `readAt` is the time the reads begin.
Each read follows no redirect. Each read takes at most `handleMs` and `handleBytes`. A call makes seven reads at most: five of the resolver, the handle's host and the document. The method keeps no row and calls no model.
The rule is that of `checkRecord`. A stranger calls it by a post. The owner, a member, a token and `brain-x-delve` call it over HTTP. A call by post is a method line and its keys:
```
@cloudbrain.delve.town pds.checkHandle
handle: penny.hailey.at
did: did:plc:m4247k3y7qpbpw5opune7nvf
```
## Lexicons
Each method declares its [atproto lexicon](https://atproto.com/specs/lexicon) beside its rule. The lexicon gives the method's parameters, input, output and errors; the tables below leave them out. Read them at `getSource?worker=brain-x-pds&part=lexicons`.
- `pds_lexicons` holds the documents of the seventeen `com.lopecode.brain.pds` methods.
- `pds_atproto_lexicons` holds the documents of the twenty `com.atproto` methods, unchanged from `https://github.com/bluesky-social/atproto/tree/b7dcaeefbb070b8182dc68b4e6b52114d6786d4e/lexicons/com/atproto`.
- The wrapper of cloudflare-iac checks each call against its lexicon before the app runs. A mismatch answers 400 `InvalidRequest` and names the field, as `params.did: required`.
- The lexicon of `sync.subscribeRepos` is a subscription, and the core routes the method as a query. Its document is in the option `lexicons`, and the wrapper checks no call of it.
- The tests call the app through `pds_t_wrap`, the same wrapper, which also checks each answer against `output` and `errors`.
## Identities
The object `Registry` holds one row for each identity. A row has the DID, a name, the handle, the controller, the minter, the Workers, the status and the latest signed operation of the DID. The methods below take the caller from the headers `x-brain-caller` and `x-brain-member`. A member is a DID with `x-brain-member: 1`. The owner is the caller `owner`.
| Method | Caller |
|---|---|
| `identity.mint` | The owner or a member. |
| `identity.list` | The identities the caller controls, and every identity for the owner. |
| `identity.get` | The owner, the controller or a named Worker. |
| `identity.setWorkers` | The owner or the controller. |
| `identity.token` | The controller only, owner included. |
| `identity.deactivate` | The owner or the controller. |
| `identity.tombstone` | The owner only. |
| `identity.setEndpoint` | The owner only. |
- `name` is 1 to 63 lowercase letters, digits or hyphens. A member's name has 5 characters at least and is not reserved (see Handles). The owner is exempt. `workers` lists 16 Worker names at most, in the same form.
- `controller` is `owner` or a DID. It defaults to the caller. A member names no other controller. The owner names any.
- `handle` is the name under `handleDomain`, or null when the setting or the name is unset. `pdsPublic` is always true.
- `identity.mint` costs 0.01 when it succeeds. The core charges the price of the method when it accepts the call and returns nothing for an error. A call whose origin is anonymous costs nothing.
- The rule of the method lets a trusted caller and any DID through. The Worker then refuses a DID without the member header.
- `status` is `pending` while the directory has not accepted the genesis operation, `active` when it has, and `rejected` when the directory answers with a 4xx.
- `Registry.authorize(caller, did)` answers `{ did, controller }` for the owner, the controller and a Worker the controller named. It throws `Forbidden` for any other caller.
Failure answers: `InvalidRequest`, `InvalidHandle`, `HandleNotAvailable` and `HandleNotFound` are 400. `InvalidToken`, `ExpiredToken` and `AuthenticationRequired` are 401. `Forbidden`, `QuotaExceeded` and `AccountCreationClosed` are 403. `NotFound` and `RepoNotFound` are 404. `IdentityPending`, `IdentityRejected`, `ClusterKeyRemoved` and `UpdateInProgress` are 409. `DirectoryRefused` is 502. `RecoveryKeyUnset`, `HostUnset`, `WrapKeyMissing`, `RepoUnbound` and `RegistryUnbound` are 503. `RepoDeactivated` is 400. `IdentityTombstoned` is 409. Any other failure is 500 `InternalError`.
## Records and blobs
A Worker or a controller reads and writes the repo of an identity through the methods below. The kernel names the caller. The registry lets in the owner, the controller, and the Workers that `identity.setWorkers` named for the identity. It refuses any other caller with 403 `Forbidden`. No method takes or answers a repo key or a password.
The methods are `record.put`, `record.get`, `record.list`, `record.delete` and `blob.put`. Each names the identity in `did`. The body of `blob.put` is the bytes, and `content-type` is the MIME type.
- A record or blob that `record.put` or `blob.put` writes is public: relays and other servers crawl the repo. `record.delete` does not recall a copy already crawled.
- Each method runs the handler of the same name in `com.atproto.repo` on the repo object of the DID. `record.put` writes or replaces, `record.get` and `record.list` read, and `blob.put` stages the bytes as `uploadBlob` does.
- A DID that names no identity answers 404 `NotFound`. An identity that the directory rejected answers 409 `IdentityRejected`, and a tombstoned one answers 409 `IdentityTombstoned`.
- Every method above answers 400 `RepoDeactivated` for a deactivated repo.
- A missing record answers 400 `RecordNotFound`. A blob over 60 MB answers 400 `BlobTooLarge`.
- The repo object runs its writes one at a time. Each write builds on the commit of the write before it. Reads do not wait.
- A commit writes its blocks, its root and its firehose event in one `transactionSync`. A failure there leaves all three unchanged.
## Deactivate and tombstone
- `identity.deactivate` deactivates the repo object. The repo then refuses the record and blob methods, and its firehose sends one `#account` event with `active` false and status `deactivated`. A second call changes nothing. The method refuses a Worker named for the identity.
- A deactivated repo answers 400 `RepoDeactivated` to the public reads of `com.atproto.sync` and `com.atproto.repo`. `sync.getRepoStatus` and `sync.listRepos` answer it with `active` false.
- `identity.tombstone` reads the latest operation from the directory, deactivates the repo, then posts a `plc_tombstone` operation. The operation follows the latest one and carries the signature of the cluster key. The directory then answers 404 for the DID.
- A tombstoned identity keeps its row with the status `tombstoned` and gives up its handle. The firehose route, tokens and sessions refuse it. A new identity can take its name.
- The tombstone needs the status `active`. A pending identity answers 409 `IdentityPending`. A refusal of the read answers 502 `DirectoryRefused` and leaves the repo active. A latest operation without the cluster key answers 409 `ClusterKeyRemoved`; the registry stores it and the repo stays active. A refusal by the directory answers 502 `DirectoryRefused`; the repo stays deactivated and the status stays `active`, so the owner calls the method again.
- Both answers carry `note`: records that relays and other servers already crawled stay public. Neither method recalls them.
## Moving the endpoint
`identity.setEndpoint` takes `did` and points the identity's `atproto_pds` service at `https://` and the host of a mint. Only the owner may call it.
1. The registry reads the latest operation from `GET //log/last` and stores it.
2. An endpoint already on the host answers `{ did, endpoint, unchanged: true }`. The registry sends nothing.
3. The cluster key signs an update after that operation. The update changes `services.atproto_pds.endpoint` and keeps every other field.
4. After the directory's 200 the registry stores the update. The repo emits an `#identity` event, which the host-wide sequence reads.
5. The registry queues a `requestCrawl` of the host to each URL in `relays`. The answer is `{ did, endpoint, unchanged: false }`.
- The identity must be `active`, or the method throws 409 `IdentityPending`. A second change of the identity under way throws 409 `UpdateInProgress`.
- A latest operation without the cluster key throws 409 `ClusterKeyRemoved` and sends nothing.
- A refused read or a refused update throws 502 `DirectoryRefused`. The registry then stores no update and emits no event.
- The `Repo` object keeps its handle and its key. Its records stay where they are.
## Tokens and sessions
An external client signs in to one identity with a token that its controller asks for.
1. The controller calls `identity.token` and receives a mint token.
2. The client calls `com.atproto.server.createSession` with the DID or handle as `identifier` and the mint token as `password`.
3. The answer holds `accessJwt` and `refreshJwt`. The client sends the access token as `Authorization: Bearer`.
4. The client calls `com.atproto.server.refreshSession` with the refresh token as bearer to receive a new pair.
- Every token is an HS256 JWT. The key derives from `PDS_WRAP_KEY` with HKDF. The claim `sub` is the DID and the claim `scp` is `mint`, `access` or `refresh`.
- A mint token and an access token last `tokenMinutes`. A refresh token lasts 24 hours.
- A token serves its own `scp` only. The registry holds no list of tokens, so none ends before its expiry.
- `com.atproto.server.getSession` answers `{ did, handle, active }` for an access token. A missing handle shows as `handle.invalid`.
- `Registry.authenticate(accessJwt, did)` answers `{ did, handle, controller }`. It throws `Forbidden` when the token is for another DID.
- A token for an identity the directory rejected, or for an unknown DID, throws `InvalidToken`. An expired token throws `ExpiredToken`.
- A method answers `InvalidToken` and `ExpiredToken` as 401 under their own names.
## Server methods
The methods of `com.atproto` take no caller headers. The Worker reads the bearer token and answers 401 without a good one.
- `server.describeServer`: the `did` is `did:web:` and the host of the settings table. `availableUserDomains` holds `.handleDomain`. `inviteCodeRequired` is true.
- `server.createAccount`: always 403 `AccountCreationClosed`, for every caller. `identity.mint` is the only way to a new account.
- `server.createSession`, `server.refreshSession`, `server.getSession`: the session of the section above.
- `identity.resolveHandle`: 400 `HandleNotFound` for a handle no identity holds.
- `identity.updateHandle`: the access token names the identity. It answers an empty 200.
- `identity.getRecommendedDidCredentials`: the fields of the latest operation.
The Worker serves no other `com.atproto.server` method.
## Handles
A handle is one name under `handleDomain`, in lower case. Without the setting no identity has a handle.
- `identity.mint` with a `name` sets the handle to the name and the domain. The genesis operation lists it in `alsoKnownAs` as `at://` and the handle.
- A name that another identity holds as a handle throws `HandleNotAvailable`, and the registry sends nothing to the directory.
- A member's name has 5 characters at least. A shorter one throws `InvalidHandle`, on `identity.mint` and on `updateHandle`.
- A member's name in `reservedNames` throws `HandleNotAvailable`. The match ignores case and hyphens, so `a-dmin` matches `admin`.
- The owner is exempt from both rules. On `updateHandle` the exemption holds for an identity whose controller is `owner`. A member's token gets no exemption.
- A handle taken before these rules keeps its name.
- `GET /.well-known/atproto-did` answers the DID in plain text for the handle in `x-forwarded-host`, or 404. Without that header it reads `Host`.
- `updateHandle` accepts a name under `handleDomain` that no other identity holds. Any other handle throws `InvalidHandle` or `HandleNotAvailable`.
- The cluster key signs an update operation. Its `prev` is the CID of the latest operation, read from `GET //log/last`. The identity must be `active`, or `IdentityPending` is thrown.
- The registry stores the operation that read answers. When its `rotationKeys` lack the cluster key, the registry throws 409 `ClusterKeyRemoved` and sends nothing. A recovery key above the cluster key made that change.
- The registry stores the handle after the directory answers 200 to the update. Any other answer throws `DirectoryRefused` and the handle stays.
- A second change to the same identity or handle, while one is under way, throws `UpdateInProgress`.
- The `Repo` object keeps the handle of its `provision` call. The update leaves it unchanged.
## Minting
A mint runs these steps in order.
1. The registry refuses a caller who is neither the owner nor a member, and a member who holds `mintQuota` identities. It sends nothing to the directory.
2. The quota counts the identities the caller minted that the directory has not rejected.
3. The registry makes the cluster rotation key on the first mint. It seals the key under `PDS_WRAP_KEY` and keeps it in the table `cluster`.
4. The registry generates the repo signing key and builds the genesis operation. The key goes to the `Repo` object of the new DID, which seals it. The registry keeps its public half only.
5. The operation has two `rotationKeys`: `recoveryDidKey` first, the cluster key second. Its `verificationMethods.atproto` is the repo key. Its `atproto_pds` service is `https://` and the host: `PDS_HOSTNAME`, else `publicHost`, else `host`.
6. The cluster key signs the DAG-CBOR of the operation without `sig`. The DID is `did:plc:` and the first 24 characters of the base32 of the SHA-256 of the signed operation.
7. The registry stores the row, calls `provision` on the `Repo` object, and POSTs the operation to `plcUrl` at `/`.
A directory that answers 200 makes the identity `active`. A network error or a 5xx leaves it `pending`, and an alarm tries again every 60 seconds. Each retry first asks the directory with a GET whether an earlier POST got through. A 4xx makes the identity `rejected`, and the registry does not retry it.
A settle changes only a `pending` identity. A mint and an alarm may settle one identity at once. The first answer decides, and the later settle answers the stored status.
A mint that fails before step 7 stores nothing. Without `PDS_HOSTNAME`, `publicHost` and `host` it throws `HostUnset`.
## Crawl requests
A relay lists this host after a `requestCrawl` for the host: `PDS_HOSTNAME`, else `publicHost`, else `host`. The registry sends it by alarm, so a mint never waits for a relay.
1. An identity that turns `active` sets an alarm one second ahead.
2. The alarm POSTs `{ "hostname": }` to `/xrpc/com.atproto.sync.requestCrawl` of each URL in `relays`.
3. A relay that does not answer 2xx, or does not answer, makes the alarm run again after 60 seconds. The request goes to every relay again.
4. After 5 tries the registry logs `requestCrawl gave up` and stops. The next identity that turns `active` starts the tries again.
The registry keeps the host and `relays` as the last mint or `identity.setEndpoint` read them. A rejected or `pending` identity sends no request. With `relays` unset or empty, the alarm sends no request.
## Firehose
`GET /xrpc/com.atproto.sync.subscribeRepos` streams events over a WebSocket. The query takes these parameters:
- `did`: the repo to follow. Optional. Without it the stream holds every repo of the host.
- `cursor`: the sequence number after which the stream starts. Optional.
With `did` the `Repo` object of that DID holds the socket, and the numbers are its own. Without `did` the registry holds the socket, and the numbers are the global `seq` of the host-wide sequence.
Without `cursor` the stream sends events from the moment of the connection. With `cursor` it first sends the stored events after that number, 1000 at most, and then the live events. Each event is a frame of two DAG-CBOR values: the header `{ op, t }` and the body. The frame types are `#commit`, `#identity`, `#sync`, `#account` and `#info`.
A cursor above the latest sequence number gets an error frame `FutureCursor` and a close with code 1008. An older cursor than the oldest stored event gets an `#info` frame `OutdatedCursor`, and the stream starts at the oldest event.
The route answers 400 `InvalidRequest` for a call without a WebSocket upgrade. It answers the same for a `cursor` that is not a whole number of 0 or more. It answers 404 `NotFound` for a DID that the registry does not host or the directory rejected. It answers 503 `RepoUnbound` without the binding `REPO`. The stream of one DID is never mixed with another.
The host-wide stream sends the rows of `host_events` in `seq` order. The frame of each row is the frame of its `Repo` object, with the body's `seq` set to the global `seq`. Its types are `#commit`, `#identity`, `#sync` and `#account`. The replay reads pages of 500 rows up to the head. Each new row then reaches every socket of the stream, during the `report` that wrote it. Cursors, `FutureCursor` and `OutdatedCursor` work as in the stream of one repo. The oldest kept row of `host_events` sets the bound of `OutdatedCursor`.
- An event that its `Repo` object pruned has no frame. The stream skips its `seq`.
- A failed read of a repo's frames logs `host stream read of failed`. The stream stops before that row and reads it again at the next report or upgrade.
- One pass of the stream runs at a time. A report during a pass makes the pass read again at its end.
## Host-wide sequence
The registry numbers the events of every `Repo` object in one sequence. A relay that follows the whole host reads it. The table `host_events` holds one row for each event:
| Column | Meaning |
|---|---|
| `seq` | The global sequence number: a whole number, from 1, one more for each row. |
| `did` | The repo of the event. |
| `repo_seq` | The sequence number of the event in the `Repo` object of `did`, its `firehose_events` row. |
| `type` | `commit`, `identity`, `sync` or `account`. |
| `time` | The time the registry wrote the row, in ISO 8601. |
The registry reads the events from the `Repo` object; the object makes no outbound call. The steps of a write are these:
1. `record.put` and `record.delete` call `Registry.authorize` with `write` true. The registry marks the DID and sets an alarm a minute ahead.
2. The write runs on the `Repo` object.
3. The Worker calls `Registry.report(did)`. The registry asks the object `sequencedSince(last, 500)` and writes a row for each new event.
4. The report takes off one mark, the mark of its own write.
5. A report that fails logs a warning, and the write still answers. The mark stays, and the alarm reads the DID's events.
The alarm reads each marked DID. It clears the marks of a DID when the last mark is 60 seconds old. A younger mark stays, and the alarm runs again when it is old. The next alarm reads a write that runs past an alarm's read of its DID.
`identity.deactivate` and `identity.tombstone` mark the DID and read its `#account` event themselves. `identity.setEndpoint` reads its `#identity` event the same way.
The rows of one DID follow the order of its `Repo` object and skip none of its events. Each read starts after the DID's last row. A late event gets a later global `seq` than the events written meanwhile. The global sequence has no holes.
| Method | Caller | Answer |
|---|---|---|
| `Registry.hostEvents(cursor, limit)` | The Worker. | `{ events: [{ seq, did, repoSeq, type, time }], latest, earliest }` |
| `Registry.report(did)` | The Worker, after a write. | `{ did, added, repoSeq }` |
| `Repo.sequencedSince(cursor, limit)` | The registry. | `[{ seq, type }]`, the object's events after `cursor`, without payload |
| `Repo.hostFrames(rows)` | The registry's stream. | `[{ seq, frame }]` for rows `[{ seq, repoSeq }]`: the frame of event `repoSeq`, its body's `seq` set to `seq` |
| `Registry.fetch(request)` | The Worker, for `subscribeRepos` without `did`. | 101 and the WebSocket of the host-wide stream; 405 for another path |
- `hostEvents` answers the rows after `cursor` in order. `cursor` defaults to 0 and `limit` to 500.
- `limit` is at most 1000. `latest` is the last `seq`, or 0. `earliest` is the first `seq` kept, or null.
- The frame of a row is the event `repoSeq` of the `Repo` object of `did`. The stream reads it there.
- The registry keeps the latest 100000 rows and deletes older ones.
- A failed read by the alarm keeps the mark and sets the alarm again 60 seconds ahead.
- After 5 failed reads of one DID the alarm logs `host sequence gave up on ` and stops. The next write of that DID gives the alarm 5 tries again, and its report reads the events.
Failure answers: a `cursor` that is not a whole number of 0 or more answers `InvalidRequest`, and so does a `limit` out of range. `report` throws `NotFound` for a DID the registry holds no identity of. It throws `RepoUnbound` without the binding `REPO`.
## Repo reads
A relay reads these methods after a `requestCrawl`. Each is a query that answers anyone and reads no bearer token.
The methods are `sync.getRepo`, `sync.getRepoStatus`, `sync.getLatestCommit`, `sync.getBlocks`, `sync.getBlob`, `sync.listBlobs`, `sync.getRecord`, `repo.describeRepo`, `repo.getRecord`, `repo.listRecords` and `sync.listRepos`.
- `sync.getRepo` streams the repo as a CAR file, the latest commit as its root. `sync.getBlocks` and `sync.getRecord` answer CAR files too.
- `sync.getBlob` answers the bytes of a blob that a record cites.
- The Worker asks `Registry.hosts` for the DID of the query, then runs the handler of the same name on the repo object of that DID.
- The parameter is `did` for a `sync` method and `repo` for a `repo` method. `did` takes a DID. `repo` takes a DID or a handle.
- The Worker resolves a handle with `Registry.resolveHandle` first. The handler then reads the DID as `repo`.
- `repo.describeRepo` answers the registry's handle in `handle` and `alsoKnownAs`, and `handle.invalid` for an identity with none.
- `sync.listRepos` answers the identities of the registry, not of one object. A rejected or tombstoned identity is not listed.
- `Registry.hostedRepos(limit, cursor)` answers `{ dids, cursor? }` in DID order. The cursor is the last DID of a full page.
- A page of `sync.listRepos` holds 100 repos at most, whatever its `limit`, as each repo costs a subrequest.
- A deactivated repo stays in the list with `active` false and the status `deactivated`.
Failure answers: a call without its `did` or `repo` answers 400 `InvalidRequest`, and so does a `limit` out of its lexicon's range. A DID or handle that the registry does not host answers 404 `RepoNotFound`. A rejected or tombstoned identity answers the same. Without the binding `REPO` the methods answer 503 `RepoUnbound`. Every read but `sync.getRepoStatus` and `sync.listRepos` answers 400 `RepoDeactivated` for a deactivated repo. `sync.getBlob` answers 404 `BlobNotFound` for a blob that no record cites.
## Methods
The handlers take a Hono context `c` and the Durable Object stub. They answer a `Response` with JSON.
- `describeRepo`, `getRecord`, `listRecords`: query methods. `listRecords` answers 50 records by default and 100 at most.
- `createRecord`, `putRecord`, `deleteRecord`, `applyWrites`: write methods. A commit holds 200 operations at most; `applyWrites` answers 400 `InvalidRequest` for more.
- `uploadBlob`: stores the body in R2 under `/staged/` and answers a blob reference. A blob over 60 MB answers 400 `BlobTooLarge`.
- A record write that references a staged blob copies it to `/`, where `getBlob` and `listBlobs` read it.
- `importRepo`: reads a CAR file of 100 MB at most. `listMissingBlobs` answers 500 blobs at most.
- `sync.getRepo`, `getRepoStatus`, `getLatestCommit`, `getBlocks`, `getBlob`, `listRepos`, `listBlobs`, `getRecord`: the sync methods of atproto.
- The object's `fetch` answers `GET /xrpc/com.atproto.sync.subscribeRepos` as a WebSocket and `GET /xrpc/com.atproto.sync.getRepo` as a streamed CAR file. Other paths answer 405.
Failure answers: a write to a deactivated repo answers 403 `AccountDeactivated`. A second create with the same key answers 409 `RecordAlreadyExists`. An invalid record answers 400 `InvalidRecord`. A missing record answers 400 `RecordNotFound`.
## Record validation
`pds_validation` checks a record against the schema of its collection before a write. The table `recordSchemas` holds the schemas as `@atcute/lexicons` validators.
- It knows 18 `app.bsky` and `chat.bsky` collections, `com.atproto.lexicon.schema` and `com.lopecode.module`.
- `validate: true` checks the record and refuses an unknown collection. `validate: false` checks nothing. Unset checks a known collection only.
- A record that breaks its schema answers 400 `InvalidRecord` and names the collection and the field.
### `com.lopecode.module`
A record of `com.lopecode.module` is one version of a lopecode module. The cell `comLopecodeModuleLexicon` holds its lexicon as JSON, the value of a `com.atproto.lexicon.schema` record. A hand-written entry of `recordSchemas` follows that JSON.
- The key is a TID.
- `id` is the module id, `@user/name`, 200 characters at most.
- `source` is a blob of the compiled module text.
- `imports` lists each module the source imports, but the built-ins, as `{ id }`. Which version of it runs is the `modulePins` lockfile's of the service that runs it.
- `attachments` lists the module's files as `{ name, encoding, blob }`. `encoding` is `text` or `base64`.
- `prev` is an optional strongRef to the version this one follows.
- `createdAt` is a datetime, and `by` names the caller that published the version, 512 characters at most.
- The schema does not check the blob's MIME type or size.
`test_pds_module_lexicon_the_validator_accepts_and_refuses_as_the_json_says` reads each field of the JSON. It checks that the validator refuses a missing required field and a value of the wrong type. It also refuses a longer string, a value outside an enum and a malformed datetime. `test_pds_module_lexicon_an_import_is_an_id_and_the_cb4_records_validate` accepts an import of `id` alone, refuses one without `id`, and validates the two records of the cluster repo of cb4.
## Storage
`Registry` keeps the tables `identities`, `cluster`, `crawl`, `host_events` and `host_cursors`. A row of `host_cursors` holds a DID's last `repo_seq` in `host_events`, its marks and its failed reads. A `Repo` object keeps these tables in its SQLite: `identity`, `blocks`, `repo_state`, `firehose_events`, `record_blob`, `imported_blobs` and `collections`. Sequence numbers come from `firehose_events`. A daily alarm schedules cleanup.
## Logs
The code writes warnings with `console.warn`, for example `requestCrawl to failed`. Read them in the Worker's logs. The registry logs `requestCrawl gave up`, `host sequence gave up on ` and `host stream read of failed`. The Worker logs `host sequence report for failed`. A directory failure is in the column `plc_error` of the row, and `identity.get` does not answer it.
## Third-party code
The cells named above, except `pds_xrpc_scope`, are copies of files of Cirrus, with the types stripped and the imports turned into cell parameters.
- Upstream: `https://github.com/ascorbic/cirrus`, `packages/pds/src`, commit `de476f57ba1fb936c6480a8fc278b6c7fc250cab`.
- Licence as the upstream declares it in `README.md` and `package.json`: MIT. © Matt Kane (@ascorbic).
- Changes: `pds_account_do` omits the account store and the OAuth store, and takes its DID, handle and sealed key from the table `identity`, not from settings. It adds the methods `sequencedSince` and `hostFrames`. The handlers read the DID from the object's `identity()`. `pds_xrpc_repo` takes its scope checks from `pds_xrpc_scope`.
- The dependencies of Cirrus keep their own licences and are not copied.
MIT. © Matt Kane (@ascorbic)
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
## Tests
Each `test_…` cell runs under `bun test.ts brain-x-pds`. A cell builds its own world with `pds_rig`: an in-memory SQLite behind a `SqlStorage`, a bucket in memory, and the settings of Cirrus's test configuration. The cells read the packages from `pds_bundle`, the file `atproto.js` of this module, so no `node_modules` is needed. The repo cells need `bun:sqlite`. Where it is missing, as in the deployer's browser, each of them returns `skipped` and passes without running.
## bundle building
`atproto.js` is the packages of `pds_libs` and `pds_test_libs` at the versions of `package.json` below, as one ES module with no import. esbuild bundles them for the browser platform, so a `node:` import fails the build. A Worker without `nodejs_compat` and a browser have no `node:` modules: `node:stream` is the package `readable-stream`, `Buffer` and `process` are the packages `buffer` and `process`, `createHash("sha256")` is `@noble/hashes`, `setImmediate` of `node:timers/promises` is a `setTimeout`, and `node:zlib`, `node:fs` and `node:fs/promises` throw when called. The cell `pds_bundle` loads the file with `library` of `cloudflare-iac`. The file makes an `Intl.Segmenter` and reads `AbortSignal.any` when it loads. The deployer distils the module in QuickJS, which has neither global. There `pds_bundle` sets a stand-in for each, and the stand-in throws when it is used. `test_pds_service_distils_in_the_deployers_sandbox` runs that distil with `distilIn` of `cloudflare-iac`. `pds_app` reaches `pds_bundle` through the record and blob methods, so `pds_service.emit()` gives `worker.js`, `lib/hono.js`, `lib/atproto.js` and `source.js`.
Built with esbuild 0.28.2 under node 26.7.0: 807068 bytes, SHA-256 `bb86c558d3073b19d8b00b7f2cc01d71041db8731846e4c7b45019f06d1a9c78`. esbuild keeps only the `/*!` licence comments, at the end of the file: those of `buffer`, `ieee754`, `safe-buffer` and `@noble/*`. The 41 bundled packages are 25 MIT, 11 0BSD (`@atcute/*`, `tslib`), 1 BSD-3-Clause (`ieee754`), 1 Apache-2.0 (`cborg`), 2 Apache-2.0 AND MIT (`multiformats`, `@ipld/dag-cbor`) and 1 Apache-2.0 OR MIT (`@ipld/car`). The notices of most of them are not in the file.
~~~
npm install --ignore-scripts # in a directory with the files below
node build.mjs deploy/@tomlarkworthy/brain-pds/atproto.js
~~~
`package.json`:
~~~json
{
"name": "pds-bundle",
"private": true,
"type": "module",
"dependencies": {
"@atcute/atproto": "3.1.10",
"@atcute/bluesky": "3.2.17",
"@atcute/cbor": "2.3.3",
"@atcute/cid": "2.4.1",
"@atcute/lexicons": "1.2.7",
"@atcute/tid": "1.1.1",
"@atproto/crypto": "0.4.5",
"@atproto/lex-cbor": "0.0.3",
"@atproto/lex-data": "0.0.3",
"@atproto/lex-json": "0.0.11",
"@atproto/repo": "0.8.12",
"@ipld/car": "5.4.7",
"@noble/hashes": "1.8.0",
"buffer": "6.0.3",
"esbuild": "0.28.2",
"process": "0.11.10",
"readable-stream": "4.8.0"
}
}
~~~
`entry.js`:
~~~js
export * as atproto_repo from "@atproto/repo";
export * as atproto_crypto from "@atproto/crypto";
export * as atproto_lex_data from "@atproto/lex-data";
export * as atproto_lex_json from "@atproto/lex-json";
export * as atproto_lex_cbor from "@atproto/lex-cbor";
export * as atcute_cbor from "@atcute/cbor";
export * as atcute_cid from "@atcute/cid";
export * as atcute_tid from "@atcute/tid";
export * as atcute_lexicons_syntax from "@atcute/lexicons/syntax";
export * as atcute_lexicons_validations from "@atcute/lexicons/validations";
export * as atcute_bluesky from "@atcute/bluesky";
export * as atcute_atproto from "@atcute/atproto";
export * as ipld_car from "@ipld/car";
~~~
`build.mjs`:
~~~js
import { build } from "esbuild";
import { resolve } from "node:path";
const here = import.meta.dirname;
const shims = {
"node:crypto": "shims/crypto.js",
"node:zlib": "shims/absent.js",
"node:fs": "shims/absent.js",
"node:fs/promises": "shims/absent.js",
"node:timers/promises": "shims/timers-promises.js",
};
const nodeShims = {
name: "node-shims",
setup(b) {
b.onResolve({ filter: /^node:/ }, async (args) => {
if (shims[args.path]) return { path: resolve(here, shims[args.path]) };
const bare = args.path.slice(5);
const r = await b.resolve(bare === "stream" ? "readable-stream" : bare, { resolveDir: here, kind: args.kind });
return r.errors.length ? { errors: [{ text: "no shim for " + args.path }] } : { path: r.path };
});
},
};
await build({
entryPoints: [resolve(here, "entry.js")],
bundle: true, format: "esm", minify: true, platform: "browser", target: "es2022",
legalComments: "eof", outfile: process.argv[2] || "out/atproto.js", logLimit: 0,
inject: [resolve(here, "shims/globals.js")],
plugins: [nodeShims],
});
~~~
`shims/globals.js`:
~~~js
// Buffer and process for packages that read them as globals; a Worker without nodejs_compat has neither.
import { Buffer } from "buffer";
import process from "process/browser.js";
export { Buffer, process };
~~~
`shims/crypto.js`:
~~~js
// node:crypto as @atproto/common reads it: createHash("sha256") for VerifyCidTransform.
import { sha256 } from "@noble/hashes/sha256";
export function createHash(alg) {
if (alg !== "sha256") throw new Error("node:crypto shim: only sha256, asked " + alg);
const h = sha256.create();
const self = { update(d) { h.update(typeof d === "string" ? new TextEncoder().encode(d) : d); return self; }, digest() { return h.digest(); } };
return self;
}
export default { createHash };
~~~
`shims/absent.js`:
~~~js
// node:zlib, node:fs, node:fs/promises: not in a Worker without nodejs_compat or a browser. A call throws.
const absent = (name) => () => { throw new Error(name + " is not available in this runtime (pds bundle shim)"); };
export const createGunzip = absent("zlib.createGunzip"), createInflate = absent("zlib.createInflate"), createBrotliDecompress = absent("zlib.createBrotliDecompress");
export const access = absent("fs.access"), rm = absent("fs.rm"), rename = absent("fs.rename"), mkdir = absent("fs.mkdir"), readFile = absent("fs.readFile"), writeFile = absent("fs.writeFile"), stat = absent("fs.stat"), createReadStream = absent("fs.createReadStream"), createWriteStream = absent("fs.createWriteStream");
export const constants = { F_OK: 0 };
const all = { createGunzip, createInflate, createBrotliDecompress, access, rm, rename, mkdir, readFile, writeFile, stat, createReadStream, createWriteStream, constants };
export const promises = all;
export default all;
~~~
`shims/timers-promises.js`:
~~~js
export const setImmediate = (value) => new Promise((resolve) => setTimeout(() => resolve(value), 0));
export default { setImmediate };
~~~