From 121584fe81ae2ee44539de37d1ffdf8257fd735f Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 08:25:03 +0000 Subject: [PATCH 01/16] chore(spaces): bump spaces alpha to 20261105160032 and re-vendor lexicons Pins @atproto/space, oauth-scopes and dev-env to the 2026-11-05 alpha, cut from permissioned-data-alpha@704b9e2. Re-vendors the space, memberspace, personalspace and managedspace lexicons (simplespace is gone upstream) with a new scripts/vendor-lexicons.mjs, so the weekly sync's vendor step is one command. @atproto/space now depends on the alpha lex-cbor/lex-data/star builds, each of which has an outranking broken release (bare 0.0.0, or star's corrupt 0.0.0-stage). Sibling pins no longer rescue npm installs, so the published spaces and conformance packages keep every alpha @atproto package in devDependencies for tsdown to bundle, and @getcirrus/pds drops its direct @atproto/space dependency and the common pins. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LZ7qcQNQoiA6a23woGC7tB --- packages/oauth-provider/package.json | 2 +- packages/pds/package.json | 7 +- .../space-conformance-matrix/package.json | 2 +- .../space-conformance/lexicons/MANIFEST.json | 6 +- .../checkUserAccess.json | 13 +- .../lexicons/managedspace/policy.json | 22 + .../listMembers.json | 16 +- .../lexicons/memberspace/member.json | 25 + .../lexicons/memberspace/policy.json | 40 + .../lexicons/memberspace/putMember.json | 49 + .../removeMember.json | 8 +- .../lexicons/personalspace/policy.json | 11 + .../lexicons/simplespace/defs.json | 47 - .../lexicons/simplespace/deleteSpace.json | 32 - .../lexicons/simplespace/getSpace.json | 53 - .../lexicons/simplespace/updateSpace.json | 57 - .../lexicons/space/clearRecords.json | 36 + .../{simplespace => space}/createSpace.json | 28 +- .../lexicons/space/defs.json | 36 +- .../lexicons/space/deleteSpace.json | 32 + .../lexicons/space/exportSpaceMeta.json | 32 + .../lexicons/space/getLatestCommit.json | 10 +- .../lexicons/space/getRecord.json | 6 +- .../lexicons/space/getRepo.json | 13 +- .../lexicons/space/getSpace.json | 45 + .../lexicons/space/getSpaceCredential.json | 25 +- .../lexicons/space/importRepo.json | 19 + .../lexicons/space/importSpaceMeta.json | 22 + .../lexicons/space/listRepoOps.json | 10 +- .../lexicons/space/listRepos.json | 36 +- .../lexicons/space/listSpaces.json | 6 +- .../space/notifyCredentialRevoked.json | 31 + .../lexicons/space/notifySpaceDeleted.json | 2 +- .../lexicons/space/notifyWrite.json | 33 +- .../lexicons/space/policy.json | 26 + .../removeWriter.json} | 6 +- .../lexicons/space/updateSpace.json | 45 + packages/space-conformance/package.json | 20 +- .../scripts/vendor-lexicons.mjs | 105 ++ packages/space-conformance/src/lexicons.ts | 62 +- packages/spaces/package.json | 24 +- pnpm-lock.yaml | 1057 +++++++++-------- pnpm-workspace.yaml | 50 +- 43 files changed, 1341 insertions(+), 866 deletions(-) rename packages/space-conformance/lexicons/{simplespace => managedspace}/checkUserAccess.json (66%) create mode 100644 packages/space-conformance/lexicons/managedspace/policy.json rename packages/space-conformance/lexicons/{simplespace => memberspace}/listMembers.json (64%) create mode 100644 packages/space-conformance/lexicons/memberspace/member.json create mode 100644 packages/space-conformance/lexicons/memberspace/policy.json create mode 100644 packages/space-conformance/lexicons/memberspace/putMember.json rename packages/space-conformance/lexicons/{simplespace => memberspace}/removeMember.json (69%) create mode 100644 packages/space-conformance/lexicons/personalspace/policy.json delete mode 100644 packages/space-conformance/lexicons/simplespace/defs.json delete mode 100644 packages/space-conformance/lexicons/simplespace/deleteSpace.json delete mode 100644 packages/space-conformance/lexicons/simplespace/getSpace.json delete mode 100644 packages/space-conformance/lexicons/simplespace/updateSpace.json create mode 100644 packages/space-conformance/lexicons/space/clearRecords.json rename packages/space-conformance/lexicons/{simplespace => space}/createSpace.json (58%) create mode 100644 packages/space-conformance/lexicons/space/deleteSpace.json create mode 100644 packages/space-conformance/lexicons/space/exportSpaceMeta.json create mode 100644 packages/space-conformance/lexicons/space/getSpace.json create mode 100644 packages/space-conformance/lexicons/space/importRepo.json create mode 100644 packages/space-conformance/lexicons/space/importSpaceMeta.json create mode 100644 packages/space-conformance/lexicons/space/notifyCredentialRevoked.json create mode 100644 packages/space-conformance/lexicons/space/policy.json rename packages/space-conformance/lexicons/{simplespace/addMember.json => space/removeWriter.json} (62%) create mode 100644 packages/space-conformance/lexicons/space/updateSpace.json create mode 100644 packages/space-conformance/scripts/vendor-lexicons.mjs diff --git a/packages/oauth-provider/package.json b/packages/oauth-provider/package.json index 6fa0c67..3ad1dec 100644 --- a/packages/oauth-provider/package.json +++ b/packages/oauth-provider/package.json @@ -26,7 +26,7 @@ "@atcute/lexicon-resolver": "^0.1.6", "@atcute/lexicons": "^1.2.6", "@atcute/repo": "^0.1.1", - "@atproto/oauth-scopes": "0.0.0-spaces-alpha-20260818163953", + "@atproto/oauth-scopes": "0.0.0-spaces-alpha-20261105160032", "@atproto/oauth-types": "^0.6.3", "@atproto/syntax": "^0.4.2", "jose": "^6.1.3" diff --git a/packages/pds/package.json b/packages/pds/package.json index 76acc6e..ef0d4f3 100644 --- a/packages/pds/package.json +++ b/packages/pds/package.json @@ -1,7 +1,7 @@ { "name": "@getcirrus/pds", "version": "0.19.0", - "description": "Cirrus \u2013 A single-user AT Protocol PDS on Cloudflare Workers", + "description": "Cirrus – A single-user AT Protocol PDS on Cloudflare Workers", "type": "module", "main": "dist/index.js", "bin": { @@ -31,8 +31,6 @@ "@atcute/identity-resolver": "^1.2.2", "@atcute/lexicons": "^1.2.6", "@atcute/tid": "^1.1.1", - "@atproto/common": "0.0.0-spaces-alpha-20260818163953", - "@atproto/common-web": "0.0.0-spaces-alpha-20260818163953", "@atproto/crypto": "^0.4.5", "@atproto/lex-cbor": "^0.0.3", "@atproto/lex-data": "^0.0.3", @@ -47,8 +45,7 @@ "jose": "^6.1.3", "picocolors": "^1.1.1", "qrcode": "^1.5.4", - "@getcirrus/spaces": "workspace:*", - "@atproto/space": "0.0.0-spaces-alpha-20260818163953" + "@getcirrus/spaces": "workspace:*" }, "devDependencies": { "@arethetypeswrong/cli": "^0.18.2", diff --git a/packages/space-conformance-matrix/package.json b/packages/space-conformance-matrix/package.json index 87cae52..e8b5415 100644 --- a/packages/space-conformance-matrix/package.json +++ b/packages/space-conformance-matrix/package.json @@ -9,7 +9,7 @@ "check": "tsc --noEmit -p tsconfig.json" }, "devDependencies": { - "@atproto/dev-env": "0.0.0-spaces-alpha-20260818163953", + "@atproto/dev-env": "0.0.0-spaces-alpha-20261105160032", "@getcirrus/space-conformance": "workspace:*", "typescript": "^5.9.3", "vitest": "4.1.0-beta.1" diff --git a/packages/space-conformance/lexicons/MANIFEST.json b/packages/space-conformance/lexicons/MANIFEST.json index 27313ec..891a6b5 100644 --- a/packages/space-conformance/lexicons/MANIFEST.json +++ b/packages/space-conformance/lexicons/MANIFEST.json @@ -1,7 +1,7 @@ { "source": "https://github.com/bluesky-social/atproto", "branch": "permissioned-data-alpha", - "commit": "4c33457", - "vendoredAt": "2026-08-28", - "note": "Vendored verbatim from lexicons/com/atproto/{space,simplespace}. Re-vendored by the weekly sync; a diff here identifies affected checks via their citations." + "commit": "704b9e2ac", + "vendoredAt": "2026-11-09", + "note": "Vendored verbatim from lexicons/com/atproto/{space,memberspace,personalspace,managedspace} by scripts/vendor-lexicons.mjs. A diff here identifies affected checks via their citations." } diff --git a/packages/space-conformance/lexicons/simplespace/checkUserAccess.json b/packages/space-conformance/lexicons/managedspace/checkUserAccess.json similarity index 66% rename from packages/space-conformance/lexicons/simplespace/checkUserAccess.json rename to packages/space-conformance/lexicons/managedspace/checkUserAccess.json index 7506084..bf32fa5 100644 --- a/packages/space-conformance/lexicons/simplespace/checkUserAccess.json +++ b/packages/space-conformance/lexicons/managedspace/checkUserAccess.json @@ -1,13 +1,13 @@ { "lexicon": 1, - "id": "com.atproto.simplespace.checkUserAccess", + "id": "com.atproto.managedspace.checkUserAccess", "defs": { "main": { "type": "query", - "description": "Ask a space's managing app whether to authorize a requesting user for a space credential. Served by the managingApp (not the PDS), called by the space authority at mint time when policy is 'managing-app'. Authenticated with service auth from the authority.", + "description": "Ask a space's managing app whether to authorize a user to read or write. Served by the managingApp (not the PDS), called by the authority of a space governed by the managedspace policy. Authenticated with service auth from the authority.", "parameters": { "type": "params", - "required": ["space", "user"], + "required": ["space", "user", "access"], "properties": { "space": { "type": "string", @@ -19,9 +19,14 @@ "format": "did", "description": "The DID of the requesting user." }, + "access": { + "type": "string", + "knownValues": ["read", "write"], + "description": "The kind of access being checked." + }, "clientId": { "type": "string", - "description": "The attested client_id, if a client attestation was presented." + "description": "The attested client_id, if a client attestation was presented. Omitted for write checks." } } }, diff --git a/packages/space-conformance/lexicons/managedspace/policy.json b/packages/space-conformance/lexicons/managedspace/policy.json new file mode 100644 index 0000000..a3fc21c --- /dev/null +++ b/packages/space-conformance/lexicons/managedspace/policy.json @@ -0,0 +1,22 @@ +{ + "lexicon": 1, + "id": "com.atproto.managedspace.policy", + "defs": { + "main": { + "type": "object", + "description": "Space policy that defers each user access decision to an external managing app, which the authority asks via checkUserAccess.", + "required": ["managingApp"], + "properties": { + "managingApp": { + "type": "string", + "description": "Service identifier of the managing app: a DID with an optional service fragment (e.g. 'did:web:example.com#forum')." + }, + "publishPolicy": { + "type": "boolean", + "default": false, + "description": "Publish the policy to readers as a com.atproto.space.policy record in the authority's repo in the space." + } + } + } + } +} diff --git a/packages/space-conformance/lexicons/simplespace/listMembers.json b/packages/space-conformance/lexicons/memberspace/listMembers.json similarity index 64% rename from packages/space-conformance/lexicons/simplespace/listMembers.json rename to packages/space-conformance/lexicons/memberspace/listMembers.json index e79a26e..54d03a5 100644 --- a/packages/space-conformance/lexicons/simplespace/listMembers.json +++ b/packages/space-conformance/lexicons/memberspace/listMembers.json @@ -1,10 +1,10 @@ { "lexicon": 1, - "id": "com.atproto.simplespace.listMembers", + "id": "com.atproto.memberspace.listMembers", "defs": { "main": { "type": "query", - "description": "List the members in a space's host-internal member list. Must be called on the space authority's PDS. Requires OAuth with a covering read grant; a space credential is not sufficient, so members hosted elsewhere cannot enumerate the list. This reflects the simplespace member list, not a protocol-level reader set.", + "description": "List the members of a space governed by the memberspace policy, and their read and write access. Must be called on the space authority's PDS. Requires OAuth with a covering read_self grant; a space credential is not sufficient, so members hosted elsewhere cannot enumerate the list. To make the list visible to readers, set the policy's publishMembers.", "parameters": { "type": "params", "required": ["space"], @@ -48,16 +48,26 @@ "errors": [ { "name": "SpaceNotFound" + }, + { + "name": "PolicyMismatch", + "description": "The space is not governed by the memberspace policy." } ] }, "member": { "type": "object", - "required": ["did"], + "required": ["did", "read", "write"], "properties": { "did": { "type": "string", "format": "did" + }, + "read": { + "type": "boolean" + }, + "write": { + "type": "boolean" } } } diff --git a/packages/space-conformance/lexicons/memberspace/member.json b/packages/space-conformance/lexicons/memberspace/member.json new file mode 100644 index 0000000..6a2932c --- /dev/null +++ b/packages/space-conformance/lexicons/memberspace/member.json @@ -0,0 +1,25 @@ +{ + "lexicon": 1, + "id": "com.atproto.memberspace.member", + "defs": { + "main": { + "type": "record", + "description": "An entry in the member list of a space governed by the memberspace policy, published to readers when the policy's publishMembers is set. Keyed by the member's DID. Written by the space authority's PDS to the authority's own repo in the space, and kept in sync with the member list. Only authoritative in the authority's repo.", + "key": "any", + "record": { + "type": "object", + "required": ["read", "write"], + "properties": { + "read": { + "type": "boolean", + "description": "Whether the member may read when the policy's publicRead is not set." + }, + "write": { + "type": "boolean", + "description": "Whether the member's writes are tracked when the policy's publicWrite is not set." + } + } + } + } + } +} diff --git a/packages/space-conformance/lexicons/memberspace/policy.json b/packages/space-conformance/lexicons/memberspace/policy.json new file mode 100644 index 0000000..77320c9 --- /dev/null +++ b/packages/space-conformance/lexicons/memberspace/policy.json @@ -0,0 +1,40 @@ +{ + "lexicon": 1, + "id": "com.atproto.memberspace.policy", + "defs": { + "main": { + "type": "object", + "description": "Space policy that governs access via a member list maintained by the space host, managed with putMember and removeMember.", + "properties": { + "publicRead": { + "type": "boolean", + "default": false, + "description": "If true, the authority issues a space credential to anyone, with or without a delegation token. Otherwise, only to members whose entry has read set." + }, + "publicWrite": { + "type": "boolean", + "default": false, + "description": "If true, the authority tracks and forwards notifications for any user's writes. Otherwise, only for members whose entry has write set." + }, + "allowedApps": { + "type": "array", + "description": "If set, the authority mints a credential only for these apps, evaluated against the attested client_id. When omitted, any app may read the space and no client attestation is required. Does not apply to writes.", + "items": { + "type": "string", + "description": "An OAuth client ID." + } + }, + "publishPolicy": { + "type": "boolean", + "default": false, + "description": "Publish the policy to readers as a com.atproto.space.policy record in the authority's repo in the space." + }, + "publishMembers": { + "type": "boolean", + "default": false, + "description": "Publish the member list to readers as com.atproto.memberspace.member records in the authority's repo in the space." + } + } + } + } +} diff --git a/packages/space-conformance/lexicons/memberspace/putMember.json b/packages/space-conformance/lexicons/memberspace/putMember.json new file mode 100644 index 0000000..f5befb8 --- /dev/null +++ b/packages/space-conformance/lexicons/memberspace/putMember.json @@ -0,0 +1,49 @@ +{ + "lexicon": 1, + "id": "com.atproto.memberspace.putMember", + "defs": { + "main": { + "type": "procedure", + "description": "Add a member to the member list of a space governed by the memberspace policy, or replace their read and write access. Requires auth as the space owner.", + "input": { + "encoding": "application/json", + "schema": { + "type": "object", + "required": ["space", "did", "read", "write"], + "properties": { + "space": { + "type": "string", + "format": "space-ref", + "description": "Reference to the space." + }, + "did": { + "type": "string", + "format": "did", + "description": "The DID of the member." + }, + "read": { + "type": "boolean", + "description": "Whether the member may read when the policy's publicRead is not set." + }, + "write": { + "type": "boolean", + "description": "Whether the member's writes are tracked when the policy's publicWrite is not set." + } + } + } + }, + "errors": [ + { + "name": "SpaceNotFound" + }, + { + "name": "NotSpaceOwner" + }, + { + "name": "PolicyMismatch", + "description": "The space is not governed by the memberspace policy." + } + ] + } + } +} diff --git a/packages/space-conformance/lexicons/simplespace/removeMember.json b/packages/space-conformance/lexicons/memberspace/removeMember.json similarity index 69% rename from packages/space-conformance/lexicons/simplespace/removeMember.json rename to packages/space-conformance/lexicons/memberspace/removeMember.json index 7377bf0..bb259cc 100644 --- a/packages/space-conformance/lexicons/simplespace/removeMember.json +++ b/packages/space-conformance/lexicons/memberspace/removeMember.json @@ -1,10 +1,10 @@ { "lexicon": 1, - "id": "com.atproto.simplespace.removeMember", + "id": "com.atproto.memberspace.removeMember", "defs": { "main": { "type": "procedure", - "description": "Remove a member from a space's member list. The member list is host-internal state consulted at credential-mint time when the space's policy is 'member-list'. Requires auth as the space owner.", + "description": "Remove a member from the member list of a space governed by the memberspace policy. Requires auth as the space owner.", "input": { "encoding": "application/json", "schema": { @@ -30,6 +30,10 @@ }, { "name": "NotSpaceOwner" + }, + { + "name": "PolicyMismatch", + "description": "The space is not governed by the memberspace policy." } ] } diff --git a/packages/space-conformance/lexicons/personalspace/policy.json b/packages/space-conformance/lexicons/personalspace/policy.json new file mode 100644 index 0000000..689fe16 --- /dev/null +++ b/packages/space-conformance/lexicons/personalspace/policy.json @@ -0,0 +1,11 @@ +{ + "lexicon": 1, + "id": "com.atproto.personalspace.policy", + "defs": { + "main": { + "type": "object", + "description": "Space policy for data that only its owner should see, such as bookmarks, mutes, or drafts. Only the space authority's own account is authorized to read, and the authority tracks no other writers. Has no configuration fields.", + "properties": {} + } + } +} diff --git a/packages/space-conformance/lexicons/simplespace/defs.json b/packages/space-conformance/lexicons/simplespace/defs.json deleted file mode 100644 index b1bf9f8..0000000 --- a/packages/space-conformance/lexicons/simplespace/defs.json +++ /dev/null @@ -1,47 +0,0 @@ -{ - "lexicon": 1, - "id": "com.atproto.simplespace.defs", - "defs": { - "publicPolicy": { - "type": "object", - "description": "User access policy: any user may access the space.", - "properties": {} - }, - "memberListPolicy": { - "type": "object", - "description": "User access policy: only users on the space's member list may access it.", - "properties": {} - }, - "managingAppPolicy": { - "type": "object", - "description": "User access policy: the managing app is asked, via checkUserAccess, whether to authorize each user.", - "required": ["managingApp"], - "properties": { - "managingApp": { - "type": "string", - "description": "Service identifier of the managing app: a DID with an optional service fragment (e.g. 'did:web:example.com#forum')." - } - } - }, - "open": { - "type": "object", - "description": "App access policy: any app may access the space. No client attestation required.", - "properties": {} - }, - "allowList": { - "type": "object", - "description": "App access policy: only the named clients may access the space, evaluated against the attested client_id.", - "required": ["allowed"], - "properties": { - "allowed": { - "type": "array", - "description": "The OAuth client IDs permitted to access the space.", - "items": { - "type": "string", - "description": "An OAuth client ID." - } - } - } - } - } -} diff --git a/packages/space-conformance/lexicons/simplespace/deleteSpace.json b/packages/space-conformance/lexicons/simplespace/deleteSpace.json deleted file mode 100644 index 8c83915..0000000 --- a/packages/space-conformance/lexicons/simplespace/deleteSpace.json +++ /dev/null @@ -1,32 +0,0 @@ -{ - "lexicon": 1, - "id": "com.atproto.simplespace.deleteSpace", - "defs": { - "main": { - "type": "procedure", - "description": "Delete a space. The authenticated user must be the space owner. The authority's own repo in the space is deleted along with it, since the space host and the repo host are the same service here; other members' repos are flagged as belonging to a deleted space rather than erased. After deletion, all reads and writes against the space fail with SpaceNotFound, and getSpaceCredential answers SpaceDeleted so a syncer that missed the notification still learns to drop its copy. Idempotent. Requires auth, implemented by PDS.", - "input": { - "encoding": "application/json", - "schema": { - "type": "object", - "required": ["space"], - "properties": { - "space": { - "type": "string", - "format": "space-ref", - "description": "Reference to the space to delete." - } - } - } - }, - "errors": [ - { - "name": "SpaceNotFound" - }, - { - "name": "NotSpaceOwner" - } - ] - } - } -} diff --git a/packages/space-conformance/lexicons/simplespace/getSpace.json b/packages/space-conformance/lexicons/simplespace/getSpace.json deleted file mode 100644 index 17027aa..0000000 --- a/packages/space-conformance/lexicons/simplespace/getSpace.json +++ /dev/null @@ -1,53 +0,0 @@ -{ - "lexicon": 1, - "id": "com.atproto.simplespace.getSpace", - "defs": { - "main": { - "type": "query", - "description": "Describe a space managed by the simplespace implementation, including its configuration. Served by the space host. Requires either OAuth (for a caller with an account on this host) or a space credential (for a member hosted elsewhere); either way the caller must be authorized for the space.", - "parameters": { - "type": "params", - "required": ["space"], - "properties": { - "space": { - "type": "string", - "format": "space-ref", - "description": "Reference to the space." - } - } - }, - "output": { - "encoding": "application/json", - "schema": { - "type": "object", - "required": ["uri", "policy", "appAccess"], - "properties": { - "uri": { - "type": "string", - "format": "space-ref", - "description": "URI of the space." - }, - "policy": { - "type": "union", - "description": "How the authority decides whether to authorize a requesting user.", - "refs": [ - "com.atproto.simplespace.defs#publicPolicy", - "com.atproto.simplespace.defs#memberListPolicy", - "com.atproto.simplespace.defs#managingAppPolicy" - ] - }, - "appAccess": { - "type": "union", - "description": "How the authority decides whether to authorize a requesting app.", - "refs": [ - "com.atproto.simplespace.defs#open", - "com.atproto.simplespace.defs#allowList" - ] - } - } - } - }, - "errors": [{ "name": "SpaceNotFound" }] - } - } -} diff --git a/packages/space-conformance/lexicons/simplespace/updateSpace.json b/packages/space-conformance/lexicons/simplespace/updateSpace.json deleted file mode 100644 index 4d4e9ef..0000000 --- a/packages/space-conformance/lexicons/simplespace/updateSpace.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "lexicon": 1, - "id": "com.atproto.simplespace.updateSpace", - "defs": { - "main": { - "type": "procedure", - "description": "Update the configuration of a space. The authenticated user must be the space owner. Omitted fields are left unchanged. Requires auth, implemented by PDS.", - "input": { - "encoding": "application/json", - "schema": { - "type": "object", - "required": ["space"], - "properties": { - "space": { - "type": "string", - "format": "space-ref", - "description": "Reference to the space to update." - }, - "policy": { - "type": "union", - "description": "How the authority decides whether to authorize a requesting user. When supplied, replaces the current policy wholesale.", - "refs": [ - "com.atproto.simplespace.defs#publicPolicy", - "com.atproto.simplespace.defs#memberListPolicy", - "com.atproto.simplespace.defs#managingAppPolicy" - ] - }, - "appAccess": { - "type": "union", - "description": "How the authority decides whether to authorize a requesting app. When supplied, replaces the current policy wholesale.", - "refs": [ - "com.atproto.simplespace.defs#open", - "com.atproto.simplespace.defs#allowList" - ] - } - } - } - }, - "errors": [ - { - "name": "SpaceNotFound" - }, - { - "name": "NotSpaceOwner" - }, - { - "name": "UnsupportedPolicy", - "description": "The requested policy is not one the host implements." - }, - { - "name": "UnsupportedAppAccess", - "description": "The requested appAccess variant is not one the host implements. A host will not store an app access policy it cannot enforce." - } - ] - } - } -} diff --git a/packages/space-conformance/lexicons/space/clearRecords.json b/packages/space-conformance/lexicons/space/clearRecords.json new file mode 100644 index 0000000..a6d2cbe --- /dev/null +++ b/packages/space-conformance/lexicons/space/clearRecords.json @@ -0,0 +1,36 @@ +{ + "lexicon": 1, + "id": "com.atproto.space.clearRecords", + "defs": { + "main": { + "type": "procedure", + "description": "Delete every record in the authenticated account's space repo. The repo advances to a new revision with the empty repo's digest, and its oplog is cleared. In the space authority's own repo, the records the host publishes from the space's configuration (com.atproto.space.policy and com.atproto.memberspace.member) are kept, and the digest is that of the records that remain. Succeeds whether or not the repo held any records to delete. Requires auth, implemented by PDS.", + "input": { + "encoding": "application/json", + "schema": { + "type": "object", + "required": ["space", "repo"], + "properties": { + "space": { + "type": "string", + "format": "space-ref", + "description": "Reference to the space." + }, + "repo": { + "type": "string", + "format": "did", + "description": "The DID of the repo to clear (the authenticated member)." + } + } + } + }, + "output": { + "encoding": "application/json", + "schema": { + "type": "object", + "properties": {} + } + } + } + } +} diff --git a/packages/space-conformance/lexicons/simplespace/createSpace.json b/packages/space-conformance/lexicons/space/createSpace.json similarity index 58% rename from packages/space-conformance/lexicons/simplespace/createSpace.json rename to packages/space-conformance/lexicons/space/createSpace.json index caf2ddb..8aab935 100644 --- a/packages/space-conformance/lexicons/simplespace/createSpace.json +++ b/packages/space-conformance/lexicons/space/createSpace.json @@ -1,17 +1,17 @@ { "lexicon": 1, - "id": "com.atproto.simplespace.createSpace", + "id": "com.atproto.space.createSpace", "defs": { "main": { "type": "procedure", - "description": "Create a new space managed by the simplespace implementation. The space is anchored on the authenticated user's DID, who becomes the space owner. Requires auth, implemented by PDS.", + "description": "Create a new space governed by the given policy. The space is anchored on the authenticated user's DID, who becomes the space owner. Requires auth, implemented by PDS.", "input": { "encoding": "application/json", "schema": { "type": "object", - "required": ["type", "policy", "appAccess"], + "required": ["spaceType", "policy"], "properties": { - "type": { + "spaceType": { "type": "string", "format": "nsid", "description": "The NSID of the space type, describing the modality of the space (e.g. app.bsky.group, app.bsky.personal)." @@ -23,19 +23,11 @@ }, "policy": { "type": "union", - "description": "How the authority decides whether to authorize a requesting user.", + "description": "The policy governing the space, including its configuration.", "refs": [ - "com.atproto.simplespace.defs#publicPolicy", - "com.atproto.simplespace.defs#memberListPolicy", - "com.atproto.simplespace.defs#managingAppPolicy" - ] - }, - "appAccess": { - "type": "union", - "description": "How the authority decides whether to authorize a requesting app.", - "refs": [ - "com.atproto.simplespace.defs#open", - "com.atproto.simplespace.defs#allowList" + "com.atproto.personalspace.policy", + "com.atproto.memberspace.policy", + "com.atproto.managedspace.policy" ] } } @@ -63,10 +55,6 @@ { "name": "UnsupportedPolicy", "description": "The requested policy is not one the host implements." - }, - { - "name": "UnsupportedAppAccess", - "description": "The requested appAccess variant is not one the host implements. A host will not store an app access policy it cannot enforce." } ] } diff --git a/packages/space-conformance/lexicons/space/defs.json b/packages/space-conformance/lexicons/space/defs.json index db62653..7cc0ae0 100644 --- a/packages/space-conformance/lexicons/space/defs.json +++ b/packages/space-conformance/lexicons/space/defs.json @@ -2,35 +2,33 @@ "lexicon": 1, "id": "com.atproto.space.defs", "defs": { - "signedCommit": { + "commit": { "type": "object", - "description": "A signed commit over the current state of a permissioned repo.", - "required": ["ver", "hash", "mac", "ikm", "sig", "rev"], + "description": "A commit over the current state of a permissioned repo. Carries no signature: the repo host authenticates it to a syncer with a MAC in the Atproto-Space-Mac response header.", + "required": ["ver", "repo", "space", "rev", "data"], "properties": { "ver": { "type": "integer", - "description": "Commit format version, currently 1. Corresponds to the version in the ctx protocol tag (atproto-space-v1)." + "description": "Commit format version, currently 1." }, - "hash": { - "type": "bytes", - "description": "sha256 digest of the LtHash state (32 bytes)." - }, - "ikm": { - "type": "bytes", - "description": "Per-signature input keying material (32 random bytes)" - }, - "sig": { - "type": "bytes", - "description": "Signature over ctx (space, author DID, rev, ikm) by the user's atproto signing key. Does not cover the repo hash." + "repo": { + "type": "string", + "format": "did", + "description": "The author DID of the repo." }, - "mac": { - "type": "bytes", - "description": "HMAC-SHA256 over hash, keyed by HKDF-SHA256(ikm, info=ctx). Binds the repo hash to this commit's context." + "space": { + "type": "string", + "format": "space-ref", + "description": "Reference to the space." }, "rev": { "type": "string", "format": "tid", - "description": "Commit revision (TID), also bound into ctx." + "description": "Commit revision (TID)." + }, + "data": { + "type": "bytes", + "description": "sha256 digest of the LtHash state (32 bytes)." } } } diff --git a/packages/space-conformance/lexicons/space/deleteSpace.json b/packages/space-conformance/lexicons/space/deleteSpace.json new file mode 100644 index 0000000..5de6875 --- /dev/null +++ b/packages/space-conformance/lexicons/space/deleteSpace.json @@ -0,0 +1,32 @@ +{ + "lexicon": 1, + "id": "com.atproto.space.deleteSpace", + "defs": { + "main": { + "type": "procedure", + "description": "Delete a space. Requires auth as the space owner. Deletes the owner's own repo in the space; other members' repos are left in place. Afterwards, reads and writes fail with SpaceNotFound and getSpaceCredential returns SpaceDeleted. Idempotent. Implemented by PDS.", + "input": { + "encoding": "application/json", + "schema": { + "type": "object", + "required": ["space"], + "properties": { + "space": { + "type": "string", + "format": "space-ref", + "description": "Reference to the space to delete." + } + } + } + }, + "errors": [ + { + "name": "SpaceNotFound" + }, + { + "name": "NotSpaceOwner" + } + ] + } + } +} diff --git a/packages/space-conformance/lexicons/space/exportSpaceMeta.json b/packages/space-conformance/lexicons/space/exportSpaceMeta.json new file mode 100644 index 0000000..11b0453 --- /dev/null +++ b/packages/space-conformance/lexicons/space/exportSpaceMeta.json @@ -0,0 +1,32 @@ +{ + "lexicon": 1, + "id": "com.atproto.space.exportSpaceMeta", + "defs": { + "main": { + "type": "query", + "description": "Download a space's host-side state as a space meta archive, for account migration: a STAR file with the atproto-space-meta profile. The archive's metadata is the space. Its body is the space's policy, then any state the policy keeps (such as a memberspace member list), then the writer set. Served by the space host. Requires OAuth as the space owner with a covering read_self grant.", + "parameters": { + "type": "params", + "required": ["space"], + "properties": { + "space": { + "type": "string", + "format": "space-ref", + "description": "Reference to the space." + } + } + }, + "output": { + "encoding": "application/octet-stream" + }, + "errors": [ + { + "name": "SpaceNotFound" + }, + { + "name": "NotSpaceOwner" + } + ] + } + } +} diff --git a/packages/space-conformance/lexicons/space/getLatestCommit.json b/packages/space-conformance/lexicons/space/getLatestCommit.json index 1cc491f..1151558 100644 --- a/packages/space-conformance/lexicons/space/getLatestCommit.json +++ b/packages/space-conformance/lexicons/space/getLatestCommit.json @@ -4,7 +4,7 @@ "defs": { "main": { "type": "query", - "description": "Get the current signed commit for an account's permissioned repo within a space. Served by a repo host. Throws RepoNotFound when the account holds no repo in the space, including the case of a member that has never written to it. Callable with either OAuth (for the authenticated user's own data) or a space credential (for syncing services).", + "description": "Get the current commit for an account's permissioned repo within a space. Served by a repo host. When called with a space credential, the caller must send an Atproto-Space-Want-Mac header, and the commit's MAC is returned in the Atproto-Space-Mac response header. Throws RepoNotFound when the account holds no repo in the space, including the case of a member that has never written to it. Callable with either OAuth (for the authenticated user's own data) or a space credential (for syncing services).", "parameters": { "type": "params", "required": ["space", "repo"], @@ -28,14 +28,18 @@ "properties": { "commit": { "type": "ref", - "ref": "com.atproto.space.defs#signedCommit", - "description": "The account's current signed commit." + "ref": "com.atproto.space.defs#commit", + "description": "The account's current commit." } }, "required": ["commit"] } }, "errors": [ + { + "name": "BadSpaceMac", + "description": "The Atproto-Space-Want-Mac header is missing or malformed, names an unsupported type or version, or carries an invalid key share." + }, { "name": "SpaceNotFound" }, diff --git a/packages/space-conformance/lexicons/space/getRecord.json b/packages/space-conformance/lexicons/space/getRecord.json index 144ec5b..7ef6f87 100644 --- a/packages/space-conformance/lexicons/space/getRecord.json +++ b/packages/space-conformance/lexicons/space/getRecord.json @@ -4,7 +4,7 @@ "defs": { "main": { "type": "query", - "description": "Get a single record from a permissioned space. Callable with either OAuth (for the authenticated user's own data) or a space credential (for syncing services). Throws RepoNotFound when the account holds no repo in the space; this does not distinguish a member that has never written from a non-member.", + "description": "Get a single record from a permissioned space. Callable with either OAuth (for the authenticated user's own data) or a space credential (for syncing services). When called with a space credential, the caller must send an Atproto-Space-Want-Mac header, and the record's MAC is returned in the Atproto-Space-Mac response header. Throws RepoNotFound when the account holds no repo in the space; this does not distinguish a member that has never written from a non-member.", "parameters": { "type": "params", "required": ["space", "repo", "collection", "rkey"], @@ -52,6 +52,10 @@ } }, "errors": [ + { + "name": "BadSpaceMac", + "description": "The Atproto-Space-Want-Mac header is missing or malformed, names an unsupported type or version, or carries an invalid key share." + }, { "name": "RecordNotFound" }, diff --git a/packages/space-conformance/lexicons/space/getRepo.json b/packages/space-conformance/lexicons/space/getRepo.json index 4ace8bb..f184698 100644 --- a/packages/space-conformance/lexicons/space/getRepo.json +++ b/packages/space-conformance/lexicons/space/getRepo.json @@ -4,7 +4,7 @@ "defs": { "main": { "type": "query", - "description": "Download an account's permissioned repo within a space as a CAR file, for full-state recovery. The CAR declares two roots in order: the signed commit, then a DRISL (DAG-CBOR) index mapping '{collection}/{rkey}' to record CID. Record blocks follow, in the same canonical DAG-CBOR key order as the index (length-first, then bytewise). Blobs are not included and are fetched separately via getBlob. Served by a repo host. Callable with either OAuth (for the authenticated user's own data) or a space credential (for syncing services).", + "description": "Download an account's permissioned repo within a space as a STAR file, for full-state recovery. The archive's metadata is the repo's commit; each key/value pair is a record path ('{collection}/{rkey}') and the record's DRISL encoding, in strict lexicographic order of the path. Blobs are not included and are fetched separately via getBlob. Served by a repo host. Callable with either OAuth (for the authenticated user's own data) or a space credential (for syncing services). When called with a space credential, the caller must send an Atproto-Space-Want-Mac header, and the commit's MAC is returned in the Atproto-Space-Mac response header.", "parameters": { "type": "params", "required": ["space", "repo"], @@ -18,18 +18,17 @@ "type": "string", "format": "did", "description": "The DID of the account whose repo to download." - }, - "excludeValues": { - "type": "boolean", - "default": false, - "description": "If true, omit the record blocks and return only the commit and index roots. The index is still fully authenticated by folding its entries into a set hash and comparing against the commit, so a syncer can diff it against a local copy and fetch just the records it lacks. Note the resulting CAR declares two roots and carries no non-root blocks." } } }, "output": { - "encoding": "application/vnd.ipld.car" + "encoding": "application/octet-stream" }, "errors": [ + { + "name": "BadSpaceMac", + "description": "The Atproto-Space-Want-Mac header is missing or malformed, names an unsupported type or version, or carries an invalid key share." + }, { "name": "SpaceNotFound" }, { "name": "RepoNotFound" }, { "name": "RepoTakendown" }, diff --git a/packages/space-conformance/lexicons/space/getSpace.json b/packages/space-conformance/lexicons/space/getSpace.json new file mode 100644 index 0000000..de0709b --- /dev/null +++ b/packages/space-conformance/lexicons/space/getSpace.json @@ -0,0 +1,45 @@ +{ + "lexicon": 1, + "id": "com.atproto.space.getSpace", + "defs": { + "main": { + "type": "query", + "description": "Describe a space, including the policy that governs it. Served by the space host for every space it hosts, regardless of policy. Requires OAuth as the space owner with a covering read_self grant. A policy may optionally be published in the space, as a com.atproto.space.policy record, so that syncers can view it.", + "parameters": { + "type": "params", + "required": ["space"], + "properties": { + "space": { + "type": "string", + "format": "space-ref", + "description": "Reference to the space." + } + } + }, + "output": { + "encoding": "application/json", + "schema": { + "type": "object", + "required": ["uri", "policy"], + "properties": { + "uri": { + "type": "string", + "format": "space-ref", + "description": "URI of the space." + }, + "policy": { + "type": "union", + "description": "The policy governing the space, including its configuration.", + "refs": [ + "com.atproto.personalspace.policy", + "com.atproto.memberspace.policy", + "com.atproto.managedspace.policy" + ] + } + } + } + }, + "errors": [{ "name": "SpaceNotFound" }] + } + } +} diff --git a/packages/space-conformance/lexicons/space/getSpaceCredential.json b/packages/space-conformance/lexicons/space/getSpaceCredential.json index 3834ab4..12d6b77 100644 --- a/packages/space-conformance/lexicons/space/getSpaceCredential.json +++ b/packages/space-conformance/lexicons/space/getSpaceCredential.json @@ -4,18 +4,26 @@ "defs": { "main": { "type": "procedure", - "description": "Exchange a delegation token for a space credential. Called on the space authority, with the delegation token as the request's authorization token and a DPoP proof signed by the key to bind the credential to. The resulting space credential reads repos across the space. Requires a delegation token and DPoP proof, plus a client attestation when the space gates on app identity.", + "description": "Request a space credential. Called on the space authority. A delegation token is required when the space gates on the user. A client attestation is required when the space gates on app identity. A space that requires neither offers public access. The resulting space credential reads repos across the space.", "input": { "encoding": "application/json", "schema": { "type": "object", - "required": ["space"], + "required": ["space", "credentialKid"], "properties": { "space": { "type": "string", "format": "space-ref", "description": "Reference to the space." }, + "credentialKid": { + "type": "string", + "description": "P-256 did:key to bind the credential to. Each request using the credential is signed by this key." + }, + "delegationToken": { + "type": "string", + "description": "Optional delegation token establishing the user being acted for. Required only when the space gates on the user." + }, "clientAttestation": { "type": "string", "description": "Optional client attestation JWT establishing the app's identity. Required only when the space gates on app identity." @@ -31,14 +39,15 @@ "properties": { "credential": { "type": "string", - "description": "A signed JWT space credential, bound through its cnf.jkt claim to the key that signed the request's DPoP proof." + "description": "A signed JWT space credential." } } } }, "errors": [ { - "name": "SpaceNotFound" + "name": "SpaceNotFound", + "description": "The space does not exist. An authority may also answer this in place of UserNotAuthorized, so that a refusal does not disclose that the space exists to a user who may not read it." }, { "name": "SpaceDeleted" @@ -60,6 +69,14 @@ }, { "name": "InvalidClientAttestation" + }, + { + "name": "RepoTakendown", + "description": "The space authority has been taken down." + }, + { + "name": "RepoDeactivated", + "description": "The space authority has been deactivated." } ] } diff --git a/packages/space-conformance/lexicons/space/importRepo.json b/packages/space-conformance/lexicons/space/importRepo.json new file mode 100644 index 0000000..f6b1713 --- /dev/null +++ b/packages/space-conformance/lexicons/space/importRepo.json @@ -0,0 +1,19 @@ +{ + "lexicon": 1, + "id": "com.atproto.space.importRepo", + "defs": { + "main": { + "type": "procedure", + "description": "Import the authenticated account's repo in a space from a STAR file, as served by getRepo, during account migration, replacing whatever this host holds for that repo. The archive's commit names the space and must name the account as its repo. If the account is the space's authority, the space must first be imported with importSpaceMeta. Blobs are not included and are uploaded separately. Requires OAuth with a create grant for every collection in the archive, implemented by PDS.", + "input": { + "encoding": "application/octet-stream" + }, + "errors": [ + { + "name": "SpaceNotFound", + "description": "The account is the space's authority, and the space has not been imported." + } + ] + } + } +} diff --git a/packages/space-conformance/lexicons/space/importSpaceMeta.json b/packages/space-conformance/lexicons/space/importSpaceMeta.json new file mode 100644 index 0000000..b85126a --- /dev/null +++ b/packages/space-conformance/lexicons/space/importSpaceMeta.json @@ -0,0 +1,22 @@ +{ + "lexicon": 1, + "id": "com.atproto.space.importSpaceMeta", + "defs": { + "main": { + "type": "procedure", + "description": "Import a space from a space meta archive, as served by exportSpaceMeta, during account migration, replacing whatever this host holds for that space. The space must be anchored on the authenticated account's DID. Must come before importing the account's own repo in the space with importRepo. Notification registrations, credential revocations, and deleted space tombstones are not carried over. Requires OAuth with manage=create and manage=update grants for the space, implemented by PDS.", + "input": { + "encoding": "application/octet-stream" + }, + "errors": [ + { + "name": "NotSpaceOwner" + }, + { + "name": "UnsupportedPolicy", + "description": "The archive's policy, or a value within it, is not one the host implements. A host will not store a policy it cannot enforce." + } + ] + } + } +} diff --git a/packages/space-conformance/lexicons/space/listRepoOps.json b/packages/space-conformance/lexicons/space/listRepoOps.json index 886b573..9a96b1a 100644 --- a/packages/space-conformance/lexicons/space/listRepoOps.json +++ b/packages/space-conformance/lexicons/space/listRepoOps.json @@ -4,7 +4,7 @@ "defs": { "main": { "type": "query", - "description": "List the operation log for an account's permissioned repo within a space, returning operations after a given revision. Primary incremental sync mechanism. By default each created or updated operation inlines the record's current value; set excludeValues for metadata-only entries. Note the oplog is a transport optimization with no history guarantee: a host may compact it or drop it, and it does not survive account migration, so omitting `since` returns the retained window rather than the repo's full history. Use getRepo for an initial sync or when a `since` revision is no longer available. Callable with either OAuth (for the authenticated user's own data) or a space credential (for syncing services).", + "description": "List the operation log for an account's permissioned repo within a space, returning operations after a given revision. Primary incremental sync mechanism. By default each created or updated operation inlines the record's current value; set excludeValues for metadata-only entries. Note the oplog is a transport optimization with no history guarantee: a host may compact it or drop it, and it does not survive account migration, so omitting `since` returns the retained window rather than the repo's full history. Use getRepo for an initial sync or when a `since` revision is no longer available. Callable with either OAuth (for the authenticated user's own data) or a space credential (for syncing services). When called with a space credential, the caller must send an Atproto-Space-Want-Mac header, and a response that includes the commit carries its MAC in the Atproto-Space-Mac response header.", "parameters": { "type": "params", "required": ["space", "repo"], @@ -57,8 +57,8 @@ }, "commit": { "type": "ref", - "ref": "com.atproto.space.defs#signedCommit", - "description": "The account's current signed commit. Included when the response reaches the head of the oplog; omitted on backfill responses." + "ref": "com.atproto.space.defs#commit", + "description": "The account's current commit. Included when the response reaches the head of the oplog; omitted on backfill responses." }, "cursor": { "type": "string", @@ -68,6 +68,10 @@ } }, "errors": [ + { + "name": "BadSpaceMac", + "description": "The Atproto-Space-Want-Mac header is missing or malformed, names an unsupported type or version, or carries an invalid key share." + }, { "name": "SpaceNotFound" }, { "name": "RepoNotFound" }, { "name": "RepoTakendown" }, diff --git a/packages/space-conformance/lexicons/space/listRepos.json b/packages/space-conformance/lexicons/space/listRepos.json index 2ee2c35..357e96b 100644 --- a/packages/space-conformance/lexicons/space/listRepos.json +++ b/packages/space-conformance/lexicons/space/listRepos.json @@ -4,7 +4,7 @@ "defs": { "main": { "type": "query", - "description": "List the known repos that hold data in a space (the writer set), with each repo's current rev and commit hash. Served by the space host. This is the sync boundary, not an access-control list: it enumerates only writers, never readers. The set is what the authority claims from write notifications and is not itself authoritative; a repo's host is the source of truth.", + "description": "List the known repos that hold data in a space (the writer set), with each repo's current repoRev and commit data. Served by the space host. This is the sync boundary, not an access-control list: it enumerates only writers, never readers. The set is what the authority claims from write notifications and is not itself authoritative; a repo's host is the source of truth.", "parameters": { "type": "params", "required": ["space"], @@ -22,7 +22,8 @@ "description": "Maximum number of repos to return." }, "cursor": { - "type": "string" + "type": "string", + "description": "Return repos updated after this space revision (exclusive). Use a previous response's cursor or a previously processed spaceRev." } } }, @@ -32,15 +33,17 @@ "type": "object", "required": ["repos"], "properties": { - "cursor": { - "type": "string" - }, "repos": { "type": "array", "items": { "type": "ref", "ref": "#repo" - } + }, + "description": "Returned in ascending spaceRev order. A repo may reappear if updated while paginating." + }, + "cursor": { + "type": "string", + "description": "Pass this cursor on the next request. Omitted when no repos are returned." } } } @@ -48,26 +51,39 @@ "errors": [ { "name": "SpaceNotFound" + }, + { + "name": "RepoTakendown", + "description": "The space authority has been taken down." + }, + { + "name": "RepoDeactivated", + "description": "The space authority has been deactivated." } ] }, "repo": { "type": "object", - "required": ["did", "rev", "hash"], + "required": ["did", "repoRev", "data", "spaceRev"], "properties": { "did": { "type": "string", "format": "did", "description": "The DID of a repo that holds data in the space." }, - "rev": { + "repoRev": { "type": "string", "description": "The repo's current revision (TID), as last reported to the authority. May lag the repo host, which is the source of truth.", "format": "tid" }, - "hash": { + "data": { "type": "bytes", - "description": "The repo's current commit hash (sha256 of the LtHash state), as last reported to the authority." + "description": "The repo's current commit data (sha256 of the LtHash state), as last reported to the authority." + }, + "spaceRev": { + "type": "string", + "format": "tid", + "description": "The space revision at which this repo was last updated." } } } diff --git a/packages/space-conformance/lexicons/space/listSpaces.json b/packages/space-conformance/lexicons/space/listSpaces.json index dfdf9f8..959a80a 100644 --- a/packages/space-conformance/lexicons/space/listSpaces.json +++ b/packages/space-conformance/lexicons/space/listSpaces.json @@ -4,14 +4,14 @@ "defs": { "main": { "type": "query", - "description": "List the spaces the authenticated user holds a repo in (i.e. spaces the user has written data to), optionally filtered by type and/or authority DID. Note this is not 'spaces I'm a member of' — a member's PDS only tracks spaces its user has written to. Requires auth, implemented by PDS.", + "description": "List the spaces the authenticated user holds a repo in (i.e. spaces the user has written data to) or is the authority of, optionally filtered by type and/or authority DID. Note this is not 'spaces I'm a member of' — a member's PDS only tracks spaces its user has written to. Requires auth, implemented by PDS.", "parameters": { "type": "params", "properties": { - "type": { + "spaceType": { "type": "string", "format": "nsid", - "description": "Filter to spaces of this type." + "description": "Filter to spaces of this space type." }, "did": { "type": "string", diff --git a/packages/space-conformance/lexicons/space/notifyCredentialRevoked.json b/packages/space-conformance/lexicons/space/notifyCredentialRevoked.json new file mode 100644 index 0000000..6259d44 --- /dev/null +++ b/packages/space-conformance/lexicons/space/notifyCredentialRevoked.json @@ -0,0 +1,31 @@ +{ + "lexicon": 1, + "id": "com.atproto.space.notifyCredentialRevoked", + "defs": { + "main": { + "type": "procedure", + "description": "Notify a repo host that the space authority has revoked one or more credentials. Authenticated with service auth from the space authority, addressed to the repo DID.", + "input": { + "encoding": "application/json", + "schema": { + "type": "object", + "required": ["space", "credentials"], + "properties": { + "space": { + "type": "string", + "format": "space-ref", + "description": "Reference to the space." + }, + "credentials": { + "type": "array", + "minLength": 1, + "maxLength": 100, + "description": "The jti of the revoked credentials.", + "items": { "type": "string", "minLength": 1 } + } + } + } + } + } + } +} diff --git a/packages/space-conformance/lexicons/space/notifySpaceDeleted.json b/packages/space-conformance/lexicons/space/notifySpaceDeleted.json index cff248d..dc50a9c 100644 --- a/packages/space-conformance/lexicons/space/notifySpaceDeleted.json +++ b/packages/space-conformance/lexicons/space/notifySpaceDeleted.json @@ -4,7 +4,7 @@ "defs": { "main": { "type": "procedure", - "description": "Notify a syncing service that a space has been deleted, and that it should drop every copy of the space's data it holds. Sent by the space authority to the services registered for the space, best-effort. Authenticated with service auth addressed to the receiving service.", + "description": "Notify a syncing service that a space was deleted and its copy should be dropped. Sent by the space authority to registered services, retried until delivered or the registration expires. Requires service auth.", "input": { "encoding": "application/json", "schema": { diff --git a/packages/space-conformance/lexicons/space/notifyWrite.json b/packages/space-conformance/lexicons/space/notifyWrite.json index 2d85875..c93cb57 100644 --- a/packages/space-conformance/lexicons/space/notifyWrite.json +++ b/packages/space-conformance/lexicons/space/notifyWrite.json @@ -4,12 +4,12 @@ "defs": { "main": { "type": "procedure", - "description": "Notify that a repo in a space has advanced to a new revision. Sent by a repo host to the space host, and forwarded to registered syncers. Best-effort. Authenticated with service auth.", + "description": "Notify that a repo in a space has advanced. Repo hosts reliably deliver their latest state to the space host, which sequences updates and forwards them to registered syncers with reasonable-effort delivery. Authenticated with service auth.", "input": { "encoding": "application/json", "schema": { "type": "object", - "required": ["space", "repo", "rev", "hash"], + "required": ["space", "repo", "repoRev", "data"], "properties": { "space": { "type": "string", @@ -21,18 +21,37 @@ "format": "did", "description": "The DID of the account whose repo advanced." }, - "rev": { + "repoRev": { "type": "string", - "description": "The revision of the write.", + "description": "The repo revision after the write.", "format": "tid" }, - "hash": { + "data": { "type": "bytes", - "description": "The repo's current commit hash (sha256 of the LtHash state) after the write. Lets the space host maintain each repo's hash for listRepos." + "description": "The repo's current commit data (sha256 of the LtHash state) after the write. Lets the space host maintain each repo's commit data for listRepos." + }, + "spaceRev": { + "type": "string", + "format": "tid", + "description": "The space revision assigned by the space host. Present only on notifications forwarded to syncers." + }, + "prevSpaceRev": { + "type": "string", + "format": "tid", + "description": "The previous space revision. Omitted on the first update in a space. A gap indicates missed notifications; recover using listRepos with cursor." } } } - } + }, + "errors": [ + { + "name": "SpaceNotFound" + }, + { + "name": "FutureRev", + "description": "The repo revision exceeds the permitted clock skew." + } + ] } } } diff --git a/packages/space-conformance/lexicons/space/policy.json b/packages/space-conformance/lexicons/space/policy.json new file mode 100644 index 0000000..b7fedcd --- /dev/null +++ b/packages/space-conformance/lexicons/space/policy.json @@ -0,0 +1,26 @@ +{ + "lexicon": 1, + "id": "com.atproto.space.policy", + "defs": { + "main": { + "type": "record", + "description": "The policy governing a space, optionally published in the space so that syncers can view a description of the space's policy. Written to the space authority's own repo in the space, and kept in sync with the policy. Only authoritative in the authority's repo.", + "key": "literal:self", + "record": { + "type": "object", + "required": ["policy"], + "properties": { + "policy": { + "type": "union", + "description": "The current policy governing the space, including its configuration.", + "refs": [ + "com.atproto.personalspace.policy", + "com.atproto.memberspace.policy", + "com.atproto.managedspace.policy" + ] + } + } + } + } + } +} diff --git a/packages/space-conformance/lexicons/simplespace/addMember.json b/packages/space-conformance/lexicons/space/removeWriter.json similarity index 62% rename from packages/space-conformance/lexicons/simplespace/addMember.json rename to packages/space-conformance/lexicons/space/removeWriter.json index 1ec2f0b..e3d05c1 100644 --- a/packages/space-conformance/lexicons/simplespace/addMember.json +++ b/packages/space-conformance/lexicons/space/removeWriter.json @@ -1,10 +1,10 @@ { "lexicon": 1, - "id": "com.atproto.simplespace.addMember", + "id": "com.atproto.space.removeWriter", "defs": { "main": { "type": "procedure", - "description": "Add a member to a space's member list. The member list is host-internal state consulted at credential-mint time when the space's policy is 'member-list'. It is not a synced protocol structure and is not enumerated to the network. Requires auth as the space owner.", + "description": "Remove an account from a space's writer set, so that listRepos no longer lists it. The account is tracked again if it later writes while still authorized. Idempotent: succeeds whether or not the account was in the writer set. Requires auth as an account that may manage the space.", "input": { "encoding": "application/json", "schema": { @@ -19,7 +19,7 @@ "did": { "type": "string", "format": "did", - "description": "The DID of the member to add." + "description": "The DID of the writer to remove." } } } diff --git a/packages/space-conformance/lexicons/space/updateSpace.json b/packages/space-conformance/lexicons/space/updateSpace.json new file mode 100644 index 0000000..4ce170a --- /dev/null +++ b/packages/space-conformance/lexicons/space/updateSpace.json @@ -0,0 +1,45 @@ +{ + "lexicon": 1, + "id": "com.atproto.space.updateSpace", + "defs": { + "main": { + "type": "procedure", + "description": "Replace the policy of a space wholesale. A policy with a different $type migrates the space, discarding state held by the previous policy (such as a member list). The authenticated user must be the space owner. Requires auth, implemented by PDS.", + "input": { + "encoding": "application/json", + "schema": { + "type": "object", + "required": ["space", "policy"], + "properties": { + "space": { + "type": "string", + "format": "space-ref", + "description": "Reference to the space to update." + }, + "policy": { + "type": "union", + "description": "The policy governing the space, including its configuration. Replaces the current policy.", + "refs": [ + "com.atproto.personalspace.policy", + "com.atproto.memberspace.policy", + "com.atproto.managedspace.policy" + ] + } + } + } + }, + "errors": [ + { + "name": "SpaceNotFound" + }, + { + "name": "NotSpaceOwner" + }, + { + "name": "UnsupportedPolicy", + "description": "The requested policy is not one the host implements." + } + ] + } + } +} diff --git a/packages/space-conformance/package.json b/packages/space-conformance/package.json index 32d0bb2..20d9de4 100644 --- a/packages/space-conformance/package.json +++ b/packages/space-conformance/package.json @@ -16,22 +16,16 @@ "build": "tsdown", "dev": "tsdown --watch", "test": "vitest run", - "check": "publint && attw --pack --profile esm-only" - }, - "dependencies": { - "@atproto/common": "0.0.0-spaces-alpha-20260818163953", - "@atproto/common-web": "0.0.0-spaces-alpha-20260818163953", - "@atproto/crypto": "^0.4.5", - "@atproto/lex-cbor": "^0.1.6", - "@atproto/lex-data": "^0.1.7", - "@atproto/lexicon": "0.0.0-spaces-alpha-20260818163953", - "@atproto/oauth-client": "0.0.0-spaces-alpha-20260818163953", - "@atproto/oauth-client-node": "0.0.0-spaces-alpha-20260818163953", - "@atproto/space": "0.0.0-spaces-alpha-20260818163953", - "@atproto/xrpc": "0.0.0-spaces-alpha-20260818163953" + "check": "publint && attw --pack --profile esm-only", + "vendor-lexicons": "node scripts/vendor-lexicons.mjs" }, "devDependencies": { "@arethetypeswrong/cli": "^0.18.2", + "@atproto/crypto": "0.0.0-spaces-alpha-20261105160032", + "@atproto/lex-cbor": "0.0.0-spaces-alpha-20261105160032", + "@atproto/lex-data": "0.0.0-spaces-alpha-20261105160032", + "@atproto/oauth-client-node": "0.0.0-spaces-alpha-20261105160032", + "@atproto/space": "0.0.0-spaces-alpha-20261105160032", "publint": "^0.3.16", "tsdown": "^0.18.3", "typescript": "^5.9.3", diff --git a/packages/space-conformance/scripts/vendor-lexicons.mjs b/packages/space-conformance/scripts/vendor-lexicons.mjs new file mode 100644 index 0000000..168aeb6 --- /dev/null +++ b/packages/space-conformance/scripts/vendor-lexicons.mjs @@ -0,0 +1,105 @@ +#!/usr/bin/env node +/** + * Vendor the spaces lexicons from a checkout of bluesky-social/atproto. + * + * node scripts/vendor-lexicons.mjs + * + * Copies every lexicon under `lexicons/com/atproto/{NAMESPACES}` verbatim + * into `lexicons/`, removes namespaces that no longer exist upstream, + * regenerates `src/lexicons.ts` (explicit imports, so bundlers carry the + * documents without filesystem access at runtime) and stamps + * `lexicons/MANIFEST.json` with the source commit. + * + * Check out the commit the pinned alpha build was cut from before running. + * A diff in `lexicons/` then identifies affected checks via their citations, + * and the coverage test names any method or error that has no MUST check. + */ + +import { execFileSync } from "node:child_process"; +import { + cpSync, + existsSync, + mkdirSync, + readdirSync, + rmSync, + writeFileSync, +} from "node:fs"; +import { dirname, join } from "node:path"; +import { fileURLToPath } from "node:url"; + +/** Namespaces under com.atproto that make up the spaces protocol. */ +const NAMESPACES = ["space", "memberspace", "personalspace", "managedspace"]; + +const root = join(dirname(fileURLToPath(import.meta.url)), ".."); +const source = process.argv[2]; +if (!source) { + console.error("usage: vendor-lexicons.mjs "); + process.exit(1); +} + +const git = (...args) => + execFileSync("git", ["-C", source, ...args], { encoding: "utf8" }).trim(); +const commit = git("rev-parse", "--short=9", "HEAD"); +const branch = git("rev-parse", "--abbrev-ref", "HEAD"); + +const target = join(root, "lexicons"); +for (const entry of readdirSync(target, { withFileTypes: true })) { + if (entry.isDirectory()) rmSync(join(target, entry.name), { recursive: true }); +} + +const imports = []; +const names = []; +for (const ns of NAMESPACES) { + const from = join(source, "lexicons", "com", "atproto", ns); + if (!existsSync(from)) { + throw new Error(`Missing upstream namespace: com.atproto.${ns}`); + } + mkdirSync(join(target, ns), { recursive: true }); + for (const file of readdirSync(from).filter((f) => f.endsWith(".json")).sort()) { + cpSync(join(from, file), join(target, ns, file)); + const name = `${ns}_${file.replace(/\.json$/, "")}`; + imports.push( + `import ${name} from "../lexicons/${ns}/${file}" with { type: "json" };`, + ); + names.push(name); + } +} + +writeFileSync( + join(root, "src", "lexicons.ts"), + `/** + * Vendored lexicon access. Generated by scripts/vendor-lexicons.mjs whenever + * lexicons/ is re-vendored — imports are explicit so bundlers carry the + * documents without filesystem access at runtime. + */ + +${imports.join("\n")} + +export interface LexiconDoc { + lexicon: number; + id: string; + defs: Record; +} + +export const lexicons: LexiconDoc[] = [ +${names.map((name) => `\t${name} as LexiconDoc,`).join("\n")} +]; +`, +); + +writeFileSync( + join(target, "MANIFEST.json"), + `${JSON.stringify( + { + source: "https://github.com/bluesky-social/atproto", + branch, + commit, + vendoredAt: new Date().toISOString().slice(0, 10), + note: `Vendored verbatim from lexicons/com/atproto/{${NAMESPACES.join(",")}} by scripts/vendor-lexicons.mjs. A diff here identifies affected checks via their citations.`, + }, + null, + "\t", + )}\n`, +); + +console.log(`Vendored ${names.length} lexicons from ${branch}@${commit}`); diff --git a/packages/space-conformance/src/lexicons.ts b/packages/space-conformance/src/lexicons.ts index fbe96f4..6152e8d 100644 --- a/packages/space-conformance/src/lexicons.ts +++ b/packages/space-conformance/src/lexicons.ts @@ -1,38 +1,48 @@ /** - * Vendored lexicon access. Regenerated by the vendor step of the weekly - * sync whenever lexicons/ changes — imports are explicit so bundlers - * carry the documents without filesystem access at runtime. + * Vendored lexicon access. Generated by scripts/vendor-lexicons.mjs whenever + * lexicons/ is re-vendored — imports are explicit so bundlers carry the + * documents without filesystem access at runtime. */ import space_applyWrites from "../lexicons/space/applyWrites.json" with { type: "json" }; +import space_clearRecords from "../lexicons/space/clearRecords.json" with { type: "json" }; import space_createRecord from "../lexicons/space/createRecord.json" with { type: "json" }; +import space_createSpace from "../lexicons/space/createSpace.json" with { type: "json" }; import space_defs from "../lexicons/space/defs.json" with { type: "json" }; import space_deleteRecord from "../lexicons/space/deleteRecord.json" with { type: "json" }; +import space_deleteSpace from "../lexicons/space/deleteSpace.json" with { type: "json" }; +import space_exportSpaceMeta from "../lexicons/space/exportSpaceMeta.json" with { type: "json" }; import space_getBlob from "../lexicons/space/getBlob.json" with { type: "json" }; import space_getDelegationToken from "../lexicons/space/getDelegationToken.json" with { type: "json" }; import space_getLatestCommit from "../lexicons/space/getLatestCommit.json" with { type: "json" }; import space_getRecord from "../lexicons/space/getRecord.json" with { type: "json" }; import space_getRepo from "../lexicons/space/getRepo.json" with { type: "json" }; +import space_getSpace from "../lexicons/space/getSpace.json" with { type: "json" }; import space_getSpaceCredential from "../lexicons/space/getSpaceCredential.json" with { type: "json" }; +import space_importRepo from "../lexicons/space/importRepo.json" with { type: "json" }; +import space_importSpaceMeta from "../lexicons/space/importSpaceMeta.json" with { type: "json" }; import space_listBlobs from "../lexicons/space/listBlobs.json" with { type: "json" }; import space_listRecords from "../lexicons/space/listRecords.json" with { type: "json" }; import space_listRepoOps from "../lexicons/space/listRepoOps.json" with { type: "json" }; import space_listRepos from "../lexicons/space/listRepos.json" with { type: "json" }; import space_listSpaces from "../lexicons/space/listSpaces.json" with { type: "json" }; +import space_notifyCredentialRevoked from "../lexicons/space/notifyCredentialRevoked.json" with { type: "json" }; import space_notifySpaceDeleted from "../lexicons/space/notifySpaceDeleted.json" with { type: "json" }; import space_notifyWrite from "../lexicons/space/notifyWrite.json" with { type: "json" }; +import space_policy from "../lexicons/space/policy.json" with { type: "json" }; import space_putRecord from "../lexicons/space/putRecord.json" with { type: "json" }; import space_registerNotify from "../lexicons/space/registerNotify.json" with { type: "json" }; +import space_removeWriter from "../lexicons/space/removeWriter.json" with { type: "json" }; import space_unregisterNotify from "../lexicons/space/unregisterNotify.json" with { type: "json" }; -import simplespace_addMember from "../lexicons/simplespace/addMember.json" with { type: "json" }; -import simplespace_checkUserAccess from "../lexicons/simplespace/checkUserAccess.json" with { type: "json" }; -import simplespace_createSpace from "../lexicons/simplespace/createSpace.json" with { type: "json" }; -import simplespace_defs from "../lexicons/simplespace/defs.json" with { type: "json" }; -import simplespace_deleteSpace from "../lexicons/simplespace/deleteSpace.json" with { type: "json" }; -import simplespace_getSpace from "../lexicons/simplespace/getSpace.json" with { type: "json" }; -import simplespace_listMembers from "../lexicons/simplespace/listMembers.json" with { type: "json" }; -import simplespace_removeMember from "../lexicons/simplespace/removeMember.json" with { type: "json" }; -import simplespace_updateSpace from "../lexicons/simplespace/updateSpace.json" with { type: "json" }; +import space_updateSpace from "../lexicons/space/updateSpace.json" with { type: "json" }; +import memberspace_listMembers from "../lexicons/memberspace/listMembers.json" with { type: "json" }; +import memberspace_member from "../lexicons/memberspace/member.json" with { type: "json" }; +import memberspace_policy from "../lexicons/memberspace/policy.json" with { type: "json" }; +import memberspace_putMember from "../lexicons/memberspace/putMember.json" with { type: "json" }; +import memberspace_removeMember from "../lexicons/memberspace/removeMember.json" with { type: "json" }; +import personalspace_policy from "../lexicons/personalspace/policy.json" with { type: "json" }; +import managedspace_checkUserAccess from "../lexicons/managedspace/checkUserAccess.json" with { type: "json" }; +import managedspace_policy from "../lexicons/managedspace/policy.json" with { type: "json" }; export interface LexiconDoc { lexicon: number; @@ -42,32 +52,42 @@ export interface LexiconDoc { export const lexicons: LexiconDoc[] = [ space_applyWrites as LexiconDoc, + space_clearRecords as LexiconDoc, space_createRecord as LexiconDoc, + space_createSpace as LexiconDoc, space_defs as LexiconDoc, space_deleteRecord as LexiconDoc, + space_deleteSpace as LexiconDoc, + space_exportSpaceMeta as LexiconDoc, space_getBlob as LexiconDoc, space_getDelegationToken as LexiconDoc, space_getLatestCommit as LexiconDoc, space_getRecord as LexiconDoc, space_getRepo as LexiconDoc, + space_getSpace as LexiconDoc, space_getSpaceCredential as LexiconDoc, + space_importRepo as LexiconDoc, + space_importSpaceMeta as LexiconDoc, space_listBlobs as LexiconDoc, space_listRecords as LexiconDoc, space_listRepoOps as LexiconDoc, space_listRepos as LexiconDoc, space_listSpaces as LexiconDoc, + space_notifyCredentialRevoked as LexiconDoc, space_notifySpaceDeleted as LexiconDoc, space_notifyWrite as LexiconDoc, + space_policy as LexiconDoc, space_putRecord as LexiconDoc, space_registerNotify as LexiconDoc, + space_removeWriter as LexiconDoc, space_unregisterNotify as LexiconDoc, - simplespace_addMember as LexiconDoc, - simplespace_checkUserAccess as LexiconDoc, - simplespace_createSpace as LexiconDoc, - simplespace_defs as LexiconDoc, - simplespace_deleteSpace as LexiconDoc, - simplespace_getSpace as LexiconDoc, - simplespace_listMembers as LexiconDoc, - simplespace_removeMember as LexiconDoc, - simplespace_updateSpace as LexiconDoc, + space_updateSpace as LexiconDoc, + memberspace_listMembers as LexiconDoc, + memberspace_member as LexiconDoc, + memberspace_policy as LexiconDoc, + memberspace_putMember as LexiconDoc, + memberspace_removeMember as LexiconDoc, + personalspace_policy as LexiconDoc, + managedspace_checkUserAccess as LexiconDoc, + managedspace_policy as LexiconDoc, ]; diff --git a/packages/spaces/package.json b/packages/spaces/package.json index 648f02a..6ba7ec0 100644 --- a/packages/spaces/package.json +++ b/packages/spaces/package.json @@ -1,7 +1,7 @@ { "name": "@getcirrus/spaces", "version": "0.1.0", - "description": "Atproto spaces engine (alpha) for Cloudflare Workers \u2013 permissioned repos, space hosting and credentials", + "description": "Atproto spaces engine (alpha) for Cloudflare Workers – permissioned repos, space hosting and credentials", "type": "module", "main": "dist/index.js", "files": [ @@ -18,29 +18,29 @@ }, "dependencies": { "@atcute/cid": "^2.3.0", - "@atproto/common": "0.0.0-spaces-alpha-20260818163953", - "@atproto/common-web": "0.0.0-spaces-alpha-20260818163953", - "@atproto/crypto": "^0.4.5", - "@atproto/lex-cbor": "^0.1.6", - "@atproto/lex-data": "^0.1.7", - "@atproto/lex-json": "^0.1.6", - "@atproto/space": "0.0.0-spaces-alpha-20260818163953", + "@atcute/lexicons": "^1.2.6", "@atcute/tid": "^1.1.1", "hono": "^4.11.3", - "@atcute/lexicons": "^1.2.6", "jose": "^5.2.0" }, "devDependencies": { "@arethetypeswrong/cli": "^0.18.2", + "@atproto/crypto": "0.0.0-spaces-alpha-20261105160032", + "@atproto/jwk-jose": "^0.2.1", + "@atproto/lex-cbor": "0.0.0-spaces-alpha-20261105160032", + "@atproto/lex-data": "0.0.0-spaces-alpha-20261105160032", + "@atproto/lex-json": "0.0.0-spaces-alpha-20261105160032", + "@atproto/space": "0.0.0-spaces-alpha-20261105160032", + "@atproto/star": "0.0.0-spaces-alpha-20261105160032", + "@atproto/syntax": "0.0.0-spaces-alpha-20261105160032", "@cloudflare/vitest-pool-workers": "^0.16.9", "@cloudflare/workers-types": "^4.20260524.1", - "@atproto/jwk-jose": "^0.2.1", + "@getcirrus/space-conformance": "workspace:*", "publint": "^0.3.16", "tsdown": "^0.18.3", "typescript": "^5.9.3", "vitest": "4.1.0-beta.1", - "wrangler": "^4.93.0", - "@getcirrus/space-conformance": "workspace:*" + "wrangler": "^4.93.0" }, "repository": { "type": "git", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 43baa9f..e8a14f0 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -5,13 +5,17 @@ settings: excludeLinksFromLockfile: false overrides: - '@atproto/lex': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-resolver': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-client': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-schema': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-builder': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-installer': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-document': 0.0.0-spaces-alpha-20260818163953 + '@atproto/lex': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-resolver': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-client': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-builder': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-installer': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-document': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-cbor@^0.0.0-spaces-alpha': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-data@^0.0.0-spaces-alpha': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-json@^0.0.0-spaces-alpha': 0.0.0-spaces-alpha-20261105160032 + '@atproto/star': 0.0.0-spaces-alpha-20261105160032 importers: @@ -183,8 +187,8 @@ importers: specifier: ^0.1.1 version: 0.1.4 '@atproto/oauth-scopes': - specifier: 0.0.0-spaces-alpha-20260818163953 - version: 0.0.0-spaces-alpha-20260818163953 + specifier: 0.0.0-spaces-alpha-20261105160032 + version: 0.0.0-spaces-alpha-20261105160032 '@atproto/oauth-types': specifier: ^0.6.3 version: 0.6.3 @@ -249,12 +253,6 @@ importers: '@atcute/tid': specifier: ^1.1.1 version: 1.1.1 - '@atproto/common': - specifier: 0.0.0-spaces-alpha-20260818163953 - version: 0.0.0-spaces-alpha-20260818163953 - '@atproto/common-web': - specifier: 0.0.0-spaces-alpha-20260818163953 - version: 0.0.0-spaces-alpha-20260818163953 '@atproto/crypto': specifier: ^0.4.5 version: 0.4.5 @@ -270,9 +268,6 @@ importers: '@atproto/repo': specifier: ^0.8.12 version: 0.8.12 - '@atproto/space': - specifier: 0.0.0-spaces-alpha-20260818163953 - version: 0.0.0-spaces-alpha-20260818163953 '@clack/prompts': specifier: ^0.11.0 version: 0.11.0 @@ -357,41 +352,25 @@ importers: version: 8.19.0 packages/space-conformance: - dependencies: - '@atproto/common': - specifier: 0.0.0-spaces-alpha-20260818163953 - version: 0.0.0-spaces-alpha-20260818163953 - '@atproto/common-web': - specifier: 0.0.0-spaces-alpha-20260818163953 - version: 0.0.0-spaces-alpha-20260818163953 + devDependencies: + '@arethetypeswrong/cli': + specifier: ^0.18.2 + version: 0.18.2 '@atproto/crypto': - specifier: ^0.4.5 - version: 0.4.5 + specifier: 0.0.0-spaces-alpha-20261105160032 + version: 0.0.0-spaces-alpha-20261105160032 '@atproto/lex-cbor': - specifier: ^0.1.6 - version: 0.1.6 + specifier: 0.0.0-spaces-alpha-20261105160032 + version: 0.0.0-spaces-alpha-20261105160032 '@atproto/lex-data': - specifier: ^0.1.7 - version: 0.1.7 - '@atproto/lexicon': - specifier: 0.0.0-spaces-alpha-20260818163953 - version: 0.0.0-spaces-alpha-20260818163953 - '@atproto/oauth-client': - specifier: 0.0.0-spaces-alpha-20260818163953 - version: 0.0.0-spaces-alpha-20260818163953 + specifier: 0.0.0-spaces-alpha-20261105160032 + version: 0.0.0-spaces-alpha-20261105160032 '@atproto/oauth-client-node': - specifier: 0.0.0-spaces-alpha-20260818163953 - version: 0.0.0-spaces-alpha-20260818163953 + specifier: 0.0.0-spaces-alpha-20261105160032 + version: 0.0.0-spaces-alpha-20261105160032 '@atproto/space': - specifier: 0.0.0-spaces-alpha-20260818163953 - version: 0.0.0-spaces-alpha-20260818163953 - '@atproto/xrpc': - specifier: 0.0.0-spaces-alpha-20260818163953 - version: 0.0.0-spaces-alpha-20260818163953 - devDependencies: - '@arethetypeswrong/cli': - specifier: ^0.18.2 - version: 0.18.2 + specifier: 0.0.0-spaces-alpha-20261105160032 + version: 0.0.0-spaces-alpha-20261105160032 publint: specifier: ^0.3.16 version: 0.3.17 @@ -408,8 +387,8 @@ importers: packages/space-conformance-matrix: devDependencies: '@atproto/dev-env': - specifier: 0.0.0-spaces-alpha-20260818163953 - version: 0.0.0-spaces-alpha-20260818163953(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) + specifier: 0.0.0-spaces-alpha-20261105160032 + version: 0.0.0-spaces-alpha-20261105160032(@opentelemetry/api@1.9.1)(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) '@getcirrus/space-conformance': specifier: workspace:* version: link:../space-conformance @@ -431,27 +410,6 @@ importers: '@atcute/tid': specifier: ^1.1.1 version: 1.1.1 - '@atproto/common': - specifier: 0.0.0-spaces-alpha-20260818163953 - version: 0.0.0-spaces-alpha-20260818163953 - '@atproto/common-web': - specifier: 0.0.0-spaces-alpha-20260818163953 - version: 0.0.0-spaces-alpha-20260818163953 - '@atproto/crypto': - specifier: ^0.4.5 - version: 0.4.5 - '@atproto/lex-cbor': - specifier: ^0.1.6 - version: 0.1.6 - '@atproto/lex-data': - specifier: ^0.1.7 - version: 0.1.7 - '@atproto/lex-json': - specifier: ^0.1.6 - version: 0.1.6 - '@atproto/space': - specifier: 0.0.0-spaces-alpha-20260818163953 - version: 0.0.0-spaces-alpha-20260818163953 hono: specifier: ^4.11.3 version: 4.11.8 @@ -462,9 +420,30 @@ importers: '@arethetypeswrong/cli': specifier: ^0.18.2 version: 0.18.2 + '@atproto/crypto': + specifier: 0.0.0-spaces-alpha-20261105160032 + version: 0.0.0-spaces-alpha-20261105160032 '@atproto/jwk-jose': specifier: ^0.2.1 version: 0.2.4 + '@atproto/lex-cbor': + specifier: 0.0.0-spaces-alpha-20261105160032 + version: 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-data': + specifier: 0.0.0-spaces-alpha-20261105160032 + version: 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-json': + specifier: 0.0.0-spaces-alpha-20261105160032 + version: 0.0.0-spaces-alpha-20261105160032 + '@atproto/space': + specifier: 0.0.0-spaces-alpha-20261105160032 + version: 0.0.0-spaces-alpha-20261105160032 + '@atproto/star': + specifier: 0.0.0-spaces-alpha-20261105160032 + version: 0.0.0-spaces-alpha-20261105160032 + '@atproto/syntax': + specifier: 0.0.0-spaces-alpha-20261105160032 + version: 0.0.0-spaces-alpha-20261105160032 '@cloudflare/vitest-pool-workers': specifier: ^0.16.9 version: 0.16.9(@cloudflare/workers-types@4.20260524.1)(@vitest/runner@4.1.7)(@vitest/snapshot@4.1.7)(vitest@4.1.0-beta.1(@opentelemetry/api@1.9.1)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0)) @@ -680,28 +659,32 @@ packages: '@atcute/varint@2.0.2': resolution: {integrity: sha512-/+hS1juMgnmf6eL6lICUkTw7wcGTo3I+Q0L1PI521mUz77rGSC6nXAUNKtvm2wYJpuWdEGq+GILGoYkOArn0TQ==} - '@atproto-labs/did-resolver@0.3.7': - resolution: {integrity: sha512-F3M3U5cU1QSAXX3J5auGEc5N2pgDgpirAjvyDFsytXuyWfrjWfTPd/H+DZrrED7gK+noW0cAWtxxjdX7/cTSVQ==} + '@atproto-labs/did-resolver@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-pqiH1Niu/pyMQ0ja7n87VshYeVrzRlv0X2lM3u81CODoKAvU9bCnN9Jhhoh805dPzNonW2o2BeotsDcAM6U9dw==} engines: {node: '>=22'} - '@atproto-labs/fetch-node@0.3.7': - resolution: {integrity: sha512-WZvjXIeEHGeOPmeckyGiSGeoHhkvzwnKtSrRSxgnHakkNqlKNLmPbUIYOIiJgiYgBSOCbse5NpPLRu3Zdw2+gA==} + '@atproto-labs/fetch-node@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-Yjjo+eu0NNU+lFtPd2hekriSSPTdYVpx09rtSsTMWUpWh5wf4GmSpQgEeCG8mc66DKO59qL8xgSEpx/LJnyUqA==} engines: {node: '>=22'} '@atproto-labs/fetch@0.3.5': resolution: {integrity: sha512-iDFZEoNqfL17EVKE+uNzdUD7YF8LWhEhxeBtP6x+PNuAxoXv3ip9vLmB8nNzNxFwVn++FipfDtSiPqmziv1bdA==} engines: {node: '>=22'} - '@atproto-labs/handle-resolver-node@0.2.8': - resolution: {integrity: sha512-S4HR3s15TP85LpBvK2pfmJgXRFEX9rPFpcRfBPeW1Rh2Bj8ixN5VZwOgABz2fHTyMidEZLyFGxc0G5HlVh0aWw==} + '@atproto-labs/handle-resolver-node@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-O4fYwo4NrXEhcihLcvnOjYaltmwe8UeYiamBVTH5daTcvsuvH1fkZAxXbvBEGlxG0TSXfszwT/lyPX97ClNcZg==} engines: {node: '>=22'} - '@atproto-labs/handle-resolver@0.4.8': - resolution: {integrity: sha512-38I+j8Efs+cCgW/NX9RFKKu7qv/AF+FqxlKS8sWjXlNZSHQZqPj5cnKVQhSsJCs4ypPB84iKch8w4/STd33bLg==} + '@atproto-labs/handle-resolver@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-lmLXB3xLPZLx3ljjHp1BySE9NHpSdWotfmZSf/csNRFqR+SouxN7hPIylTyNEe1fGcrSPS7nMXl5qFV+JDWweA==} engines: {node: '>=22'} - '@atproto-labs/identity-resolver@0.4.7': - resolution: {integrity: sha512-lKDaiBHoxrqTOFdSKAAPpplEtbbFrH4djGjnXJtOSMnZ46k7+G7AkCr1xycGGPOBYfyF54zRnTp0Tt8iu86qWg==} + '@atproto-labs/identity-resolver@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-IpY6TbqGlJKikEdmgR27bsXeGFcp6aK6+dVXIQw17lg7Jjv1GrfvwT6CjEiCroBO896JEIknfp/qv4lu+YUerg==} + engines: {node: '>=22'} + + '@atproto-labs/opentelemetry-node@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-jr6sQf5/8PZ7EA6rjf1FIQ3YWoJL1sBYsXaFMQeXWTo7LfFxM6TbnAgyB0CTkfdGpItHbqOKok0VzEK2FOnrzQ==} engines: {node: '>=22'} '@atproto-labs/pipe@0.2.4': @@ -722,30 +705,34 @@ packages: resolution: {integrity: sha512-vfvoDhu6ds6BT3Pqe+d2/LBU1WpDRtt69y6zltlfMCoucPm82m1j50/Wb6xTvv+oZ+2j0JyZVXsmXQ12SWYQJg==} engines: {node: '>=22'} - '@atproto-labs/xrpc-utils@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-Dqx1QY1hZa7UwvXkyw6imuX21GM8DrQ14LNaNOlseLQXtbFLq/XXhYdaOH+BpWRaUiwdHpJ+hlxtIB/7utP9jQ==} + '@atproto-labs/xrpc-utils@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-ETXqS9SJonX0a9gUPz6c45ulrbSiI/ehnlJa19R+a0jffXMJSZ4v03PUxi/OjJtCpJtv5gMcE/+jgqS1R1pxKA==} engines: {node: '>=22'} - '@atproto/api@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-5TZ3rHXTLGRQRxw/H17pwOvcuaAKXZFy24w//LCcfFcSuCdWIBxV9MDvBU47xCxotNOATw2/TENhmkaVWu2QJQ==} + '@atproto/api@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-/QrFn46Mh7w5ht1teDq10SLQ44e+NFoUKyEg1yLG7Aer7iXTAicjC1YcFvua9nORY46N3oljLS55nMcj8LqIcQ==} engines: {node: '>=22'} '@atproto/api@0.18.20': resolution: {integrity: sha512-BZYZkh2VJIFCXEnc/vzKwAwWjAQQTgbNJ8FBxpBK+z+KYh99O0uPCsRYKoCQsRrnkgrhzdU9+g2G+7zanTIGbw==} - '@atproto/aws@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-vPe3y7CuNfxKsBxLoBltaOO8jDNPKMRRzN6VwptWfA5Hzd8fLXumFozcxJAcI1A/3QpL9GfwwkYk64YDwzbXTw==} + '@atproto/aws@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-HyOHMTcbUjHmNENccdpd8E8BiSZ21334rJ86vVySUqQCsYmx/ysVGNPu3FFiDllWn7LnV+homWUPC04UNuEeaA==} engines: {node: '>=22'} - '@atproto/bsky@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-Ay6Ds/o3SbpWw2c+RLiwkwnbe0HKyz1KKNMG7yPgIXFlUZQaoJXQBEjBujedn7SabP3/P+rgrr5Tz07dIV+YDw==} + '@atproto/bsky@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-U5BwLzG6UF/7b9YlsZ1YqlfcpHpwZFlpHYXp4xuJxTtYFi+xsxuHC9s8/C+cF44t8hQ/DNb72vrVV92hTzzijw==} engines: {node: '>=22'} '@atproto/bsync@0.0.0': resolution: {integrity: sha512-gv0dOnKGPhB0xyqLJhu3U3osZAPXLnaZQTRzwZlC5tm/Yc+c8myv2E3nIF+3Ojekh/cbg9SC8qRae4pEL0WHYg==} - '@atproto/common-web@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-9D7IJ5HAsQxFWibfL1+F26envBEoDR24e1q8diXrA8LfzVoRLP3zUlPWDG02zaumxgAPIIO5Yr5yuhzHYusEUg==} + '@atproto/car@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-YDq+BHlfUkDsbOII+BuqQQFtsCSM3+SX6reVgigJbXOJMgn4EgQvb2L5IXLQNvSGMXBHK9Du2ltraOA9X7bBOg==} + engines: {node: '>=22'} + + '@atproto/common-web@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-mYAUpD1QborMVi6GtJwl4zGQOk1ZYbtxZ8rp7OdH2kYWoqVemSdrm0y27vrA3HMoE+KE7XrMtZAtsaV8IQf8OQ==} engines: {node: '>=22'} '@atproto/common-web@0.2.4': @@ -754,8 +741,8 @@ packages: '@atproto/common-web@0.4.16': resolution: {integrity: sha512-Ufvaff5JgxUyUyTAG0/3o7ltpy3lnZ1DvLjyAnvAf+hHfiK7OMQg+8byr+orN+KP9MtIQaRTsCgYPX+PxMKUoA==} - '@atproto/common@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-lzXomMvIHMFbmXPpsnuNUok4yZB4E67FJyNL/D3RVqxzL+OgkyPilsOYPIVzCRLZFzrVdy8Lah7kfLdxaHptgQ==} + '@atproto/common@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-DVkrueYwAJTO+KKu/IkW+krlixWPuUZHGrzggXt8wrJwenChh5IvtSMbsQM8KnbJX9D9v1xOiyyybqmVIyHVCQ==} engines: {node: '>=22'} '@atproto/common@0.1.0': @@ -771,8 +758,8 @@ packages: resolution: {integrity: sha512-WRlT4s+wv80WdQuzkQub9D5vTD82O8dH2p91u4b+x3O17q5IQbmA3Lj+1NICINNSy2voqloqAWdqXEkRfdlAPw==} engines: {node: '>=18.7.0'} - '@atproto/crypto@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-Cjqoa3BKUFaqkdZkiZy+aQJTPxFGFv0yNmbsF21zh+gK3Hvkjdgxg7TjlaFasLIy6RKY1k9weD3SztVKKMoZzw==} + '@atproto/crypto@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-3fKgpldF14VvEn/awMuBUdiJNEqtgu5PIizeMx4puOXTOu6oWZ9p0OqDOdPFqQ7VQOgSGtSZzeCBIMCD+Q4kKQ==} engines: {node: '>=22'} '@atproto/crypto@0.1.0': @@ -782,20 +769,20 @@ packages: resolution: {integrity: sha512-n40aKkMoCatP0u9Yvhrdk6fXyOHFDDbkdm4h4HCyWW+KlKl8iXfD5iV+ECq+w5BM+QH25aIpt3/j6EUNerhLxw==} engines: {node: '>=18.7.0'} - '@atproto/dev-env@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-q6eVHFEFhrXBIDtQGHTF+ymF8WbpIuhTpw/OYl7f75gtONloAE9b23N8muquuk4+2v6p2M+0htG95b/DU75HRA==} + '@atproto/dev-env@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-gWN4edHdJDjXhgilRWte2msMEsFRnk/wgFtqxskHdrcuwj9c/iW6Ym6nvnZBKxcWRiNOYmep8MK5mxeUf+qOrA==} engines: {node: '>=22'} hasBin: true + '@atproto/did@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-aiI8nvHhGVn3c7BY+T/Rpqn8/ydrEsuT8wNSS0tPIimqtEouViZCqEwoTSaM54nif3P6Cs3s/NmsLBFshtRb3Q==} + engines: {node: '>=22'} + '@atproto/did@0.3.0': resolution: {integrity: sha512-raUPzUGegtW/6OxwCmM8bhZvuIMzxG5t9oWsth6Tp91Kb5fTnHV2h/KKNF1C82doeA4BdXCErTyg7ISwLbQkzA==} - '@atproto/did@0.5.4': - resolution: {integrity: sha512-BlnwQ+obL+4ZA71KH/EzZ3TY+cpSxnLiUI85mjBJIQwvDF/oN2sQA18wIj9jpduviIt2b/cMtlJuzHjzBkfXvw==} - engines: {node: '>=22'} - - '@atproto/identity@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-Ozc2nPVAc93AsGMmcfUNuWfeT6pIwptDmftVu1XbZOcoODbemHk0pJfz7n27pHjWgghjMUkCj6KDq6TogAX/jg==} + '@atproto/identity@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-eD0VsntdfWiMZtT/17nb3cDPzko8XipLM1sjSqEifaLQ/WVkLYMNAiq27bQZl0UP6ZPPQfmjkbYoBn4UyAoCFg==} engines: {node: '>=22'} '@atproto/jwk-jose@0.2.4': @@ -813,8 +800,12 @@ packages: resolution: {integrity: sha512-tq7TUDmNfe1yDfpRgdGQMJdl9TUlJmREQNCag9yg5w8Evu+TOiFiLgiOCbo7X4ouRPSgd1DpOzXbUa8UyKKMZA==} engines: {node: '>=22'} - '@atproto/lex-builder@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-yi1sNcGw7eBaupBsMKHhe0mFfBDb4rBNvyCiCK/I+e/RzqPAYoRcD/wmOcOA567YV4UAouLGcY5ZHzUBsRjnuw==} + '@atproto/lex-builder@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-NPiH+H3m6s34Z7FVPsfRPoWcLy0wqoh1y4tDHVb+IDkv80ABA52UgvHqHzkQ9is53igKf4xBc+NsXN2QAZSMng==} + engines: {node: '>=22'} + + '@atproto/lex-cbor@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-dO/dTNO7MBEeNpG8gcEe4nnZEYk6sDm1PR0S2GwCeAseO/9XgzJqYar0FhG92zRtimFxfJio5GAKmdVJzFdAjw==} engines: {node: '>=22'} '@atproto/lex-cbor@0.0.11': @@ -823,12 +814,12 @@ packages: '@atproto/lex-cbor@0.0.3': resolution: {integrity: sha512-N8lCV3kK5ZcjSOWxKLWqzlnaSpK4isjXRZ0EqApl/5y9KB64s78hQ/U3KIE5qnPRlBbW5kSH3YACoU27u9nTOA==} - '@atproto/lex-cbor@0.1.6': - resolution: {integrity: sha512-PxLQy7jzV8u9zTGURNF8ZczLPk+ZH+WNx/2z/z7RacJbu7sWNpx26U2pC7cIkWtt4jyDaruaLhssw3w3atLotA==} + '@atproto/lex-client@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-2vmImywMxhn9n2iDDZiKXdUGYsmKXBbk98s2pq3W3wVJ94R8524cBnEb3eVKqnZry39tR8p26KlgyyuB1GERWQ==} engines: {node: '>=22'} - '@atproto/lex-client@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-OoBXOl1BxGpYJ8BRcCcsp7UI5OrkMpzpzf14T2lhVLHtCtih+jjUCMV5pNdvqU/g/BJbm9Nk/uTsU84BcOP4Og==} + '@atproto/lex-data@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-oPBQ35NDU5re/b0tRvKm7PKlEzn1LcbJ/L8UpbixOSFwbE33/EYj836WmVY8JESshOkXFcSGjPm0p8Ne//Kiog==} engines: {node: '>=22'} '@atproto/lex-data@0.0.11': @@ -837,102 +828,105 @@ packages: '@atproto/lex-data@0.0.3': resolution: {integrity: sha512-ivo1IpY/EX+RIpxPgCf4cPhQo5bfu4nrpa1vJCt8hCm9SfoonJkDFGa0n4SMw4JnXZoUcGcrJ46L+D8bH6GI2g==} - '@atproto/lex-data@0.1.7': - resolution: {integrity: sha512-kW/dPLqo/WgCLV+XESR4JKwV6c1rZWJGOfuPupZGTjEDAKoBbKXdaEzX9/1vKQYbZ9U3j0DS/n7OFFK7wBugyQ==} + '@atproto/lex-document@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-AWei82KuHFAQ/QG/mqUbNFCfqhKt4jMLjGmsKf0huSnkZUP0NeikIR8OH/AZooJ1vpsY13Y5q/7BKMCc3I7+Sw==} engines: {node: '>=22'} - '@atproto/lex-document@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-AnIERSuXVXEGYKQ8GA6TepzgXq8NSDlCibeldZyph6CNS8V5NRJcFf6AJSpr0tZxpSnnp1fGj+Kk8aSaxl0KkQ==} + '@atproto/lex-installer@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-oUGar5m1tLp9GyeXOYLHWHhnrlD9vvwDmWJWDQzJW8rW3i73gV9YlWiQjfVD0ro7zoGWFnEfdPe9C2y8gr3U1Q==} engines: {node: '>=22'} - '@atproto/lex-installer@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-Co2HTaK5C+ZABDb2L6LWznXb0beYNHtWBts2yYJXva9wDFY6I4SteD94PeAmypKnX/y4v4RrBfoKS3GzyskVfA==} + '@atproto/lex-json@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-0wLiDyR1DG9hY55uspAXoe3jqo76WJtG5yae13cTI69lhAeraC7ZPkn5As/L8qIXRBidh4goHBj1RmxqdeRWWg==} engines: {node: '>=22'} '@atproto/lex-json@0.0.11': resolution: {integrity: sha512-2IExAoQ4KsR5fyPa1JjIvtR316PvdgRH/l3BVGLBd3cSxM3m5MftIv1B6qZ9HjNiK60SgkWp0mi9574bTNDhBQ==} - '@atproto/lex-json@0.1.6': - resolution: {integrity: sha512-mvrAd0lbyuecIHjyld8QN6MN6CBf4j0GCxLzegsvLh0SvDf+GbYWklkcQqmITL44yFQOwmA/QNIQj0Uvh7+R/g==} - engines: {node: '>=22'} + '@atproto/lex-password-session@0.0.0': + resolution: {integrity: sha512-7IsFdFyeAldr+l9Jz1EGgBECXKf4LVSvkfxUQFEIPPhfGSSlhQpqqHM3ZVsrc4Hjd63S8ZtOmO7wYQLp9fslVw==} - '@atproto/lex-resolver@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-My+azw9+fTZ2Sxnz3Efzqmd8pVLr2psW7DiitQLBqLWHCq+OcP2lN/yKAQoIOm9uuaAkl0+5a9h7LNLhOyL1zQ==} + '@atproto/lex-resolver@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-HaCrrcZX0ZS1NyVdW0+Jxi7zNLL4XwcDFrgfcjDpFxzUl1KnaAyGAYAyQiaSDTGLKTgxg4F1JBjDWGtdmsoz/g==} engines: {node: '>=22'} - '@atproto/lex-schema@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-mcj2BVAl8QmB9GL8cZTkDgX6VvoIHxHnU9PbG0mMfiI1otNIpG9jX0ZqgYtVx8V5SN+LDLR+UhKrk7S5nvKolQ==} + '@atproto/lex-schema@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-i88pl575dXkJc01l1wJJXMlTdGNyQI0GWVKLaqCqcnF+Q7ZTCWpDw6JHTdpjVxiPEriF3EL9BI98dUOORYEVpw==} engines: {node: '>=22'} - '@atproto/lex@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-HEf4jqeZrnU4bVkKLO/P/vgpJBNgmAyMmIPZJNc+TsmB34jPfeG3o/n4axv0s8zV3yAQrzs/sRGgW6XMYi9L+w==} + '@atproto/lex@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-BAIndja10iJJz5NZBPXOmqGeh2NNhcTesBfVxGyrU6hdBwEZdUEzGf3hoZRybOnHGq8dsq3Bi9NSRn2kV8SLJA==} engines: {node: '>=22'} hasBin: true - '@atproto/lexicon@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-ncg3KVMl4aLj+fEJp1vu3Og6ZkKo/tBzz+5XClsk8zYAwRe6qNsJ+cYW5GrECxPvxuCvUra7ko9wMCwz3VJFmg==} + '@atproto/lexicon@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-6gFzYj8u3c31oxisnbwzthm74z+y41ssniWkqLR5cCYD8K3kG9ggIdZP6c3V4iJQ9NB/vP81oOaDgFDFfBDq3g==} engines: {node: '>=22'} '@atproto/lexicon@0.6.1': resolution: {integrity: sha512-/vI1kVlY50Si+5MXpvOucelnYwb0UJ6Qto5mCp+7Q5C+Jtp+SoSykAPVvjVtTnQUH2vrKOFOwpb3C375vSKzXw==} - '@atproto/oauth-client-node@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-XEJS6GMk5mG136FVcoSzzFynnMKGsJ3J2Z0oVWotwkYdCyawN1UCoxtKalMqzFRSsk6uWyiNKig1OK+XwC+weQ==} + '@atproto/oauth-client-node@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-8TtrUULBv63G15g4YqcvB7TH5Ti1cX2nZAB4x6D79RuWg4FU3StrqhxZFmzlknpqf+iybDNJcv+uBcw0EJrqKQ==} engines: {node: '>=22'} - '@atproto/oauth-client@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-LYCLFJuIkf3hgZxpFdN+tIkOtdRtszshS8aURcv/tEwlDWwIL86nryf/ORh+FCo/AxgJpXEZmr/zkyNBlGmdlw==} + '@atproto/oauth-client@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-yrgioKn0jPYmzDxHUMHXAoM1RaYekIKJPMRs3EpTRhcNNiZj2e/RZquqWAf2IW+1vk5EspDNPvCL5wMs6hfOkw==} engines: {node: '>=22'} - '@atproto/oauth-provider-api@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-yA9z2KQ3sXzQy9yhB8sVnFwimgYZ83F/bm8Tpep0Nzr/cia+9O2mnr330K1xZ1AemclLdLmxL8aYEKn9F0U44Q==} + '@atproto/oauth-provider-api@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-fMfgsM5LVEN/aBeDQE3/zTsQ/Rp7mZB/urzye7uLCR/pATjbJkbm+efXTIgrUOOj4sBeSJ7KlNOTFz2qP+M8lQ==} engines: {node: '>=22'} - '@atproto/oauth-provider-ui@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-V+o2LcV9pRQ8CZu28YR42m/MGJl8aUkJZT40fTtz4v6ufe5kg7+3mCyRJ6o1MZp1FKv5ETKBRlYyZFe+0aNALQ==} + '@atproto/oauth-provider-ui@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-QwM+dHfJnuRj6i6rwHwUyz2ks2OwqpHPxaHMhvYH1sAQrXcjMHwExiZk0A/iACetePpJzbUup+cqL28JKsps0A==} engines: {node: '>=22'} - '@atproto/oauth-provider@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-S7sViep3rVfNpkwjGcljYky4v4S5d0j+Aali934S8HMy643on1KRmmHvaVWui/NBGyhLOhpVFS6vtgOnntsnBw==} + '@atproto/oauth-provider@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-4ZqYQ+qDorAuaypw9MtlFnlKYhQzHaPhhizKg1FCd2B62X8b9QKGofTsBAQ+fx2vtpxB1ZTq/t3sniraz8YZlw==} engines: {node: '>=22'} - '@atproto/oauth-scopes@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-bQz4BwNk/FAPd8bXGO3EyhlIKu/UJzN5XIgmNeiZXtJbhbe30J78A3WnvBuA+SILiGFw7/M9hfgq9FcJKCzjCw==} + '@atproto/oauth-scopes@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-7F7I5mATu78oF3EE/ujjmn3O3z7szGNiFoVm1cX0HOp99phVUoKud/bo4LuaK6fb9WeJ/vwneMDCmxd1BFNOUg==} + engines: {node: '>=22'} + + '@atproto/oauth-types@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-eXF+KRdhVlvkIdnIqzR9QPyI+jakNsp2fsMuTO3NZmV7libBm19BJbhSHEywF98ZMLbRIEU9WgQfa60XtwCCdQ==} engines: {node: '>=22'} '@atproto/oauth-types@0.6.3': resolution: {integrity: sha512-jdKuoPknJuh/WjI+mYk7agSbx9mNVMbS6Dr3k1z2YMY2oRiCQjxYBuo4MLKATbxj05nMQaZRWlHRUazoAu5Cng==} - '@atproto/oauth-types@0.7.5': - resolution: {integrity: sha512-x75O0HsKB1IGfBikAQrrTX6EL8Rt4Q0+wMcwhZQRGPk/N/WqbYbsW3Powj4R8ZJKSfWCpVfaw32Piu1pTi891Q==} - engines: {node: '>=22'} - - '@atproto/ozone@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-xgVJ1ucgJLqIeRh+Wqnxa838Rn40Ghx8dKQoR/UPHqJ4VH/f97MzNmKLnSG8ah4JBYWivp6sLbBQ4aqaesqeBQ==} + '@atproto/ozone@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-vEmjdnqe3oi3YXU8jzdgq+gMQzfvJJfWxwJhLWoBcKBnwQQYVVxtuba81c7sm9+gDDaK6my0O0iOW5cy/1J9kg==} engines: {node: '>=22'} - '@atproto/pds@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-62c2jAW27UjS5WU1TLFsDC+Y9002HfOwShzPSpWU5u3Mnb5JEwJ5tsn2JZto+rCJjQLMogAXo4IlImlGam363A==} + '@atproto/pds@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-DLG6BIPkRIcDjitqmEKmScqqp9aStW/6nJhOkd/b66BKbDRuT7ro2fYhe7pbPSV/pToc2JUL9X5oDXGd1HC3Wg==} engines: {node: '>=22'} - '@atproto/repo@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-KsnmeQMlFgSzzE9zkMGsFGfsdeN5UyR3PThGFjFWLrwbRnLEqnOMVgb/dznG66Sh+BJ9vSKKdOtUAx4ilTEMJw==} + '@atproto/repo@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-nqC7dakknV0dWHoyA6YJuVs1IRHJm7Smfq7Mp/SeFjjNCaGm5CRABzraeUd8ebk6ot+mBbvqhh7TTek+cWwzJA==} engines: {node: '>=22'} '@atproto/repo@0.8.12': resolution: {integrity: sha512-QpVTVulgfz5PUiCTELlDBiRvnsnwrFWi+6CfY88VwXzrRHd9NE8GItK7sfxQ6U65vD/idH8ddCgFrlrsn1REPQ==} engines: {node: '>=18.7.0'} - '@atproto/space@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-0TQwGc7tD+ctccBD7ZD52BJ8RKUKR7hN2MtzDztJbTJSLIY4GYdr6XTnwdlsJBfDBvIqhpFp/9oHdELZLecuyw==} + '@atproto/space@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-+ICI+XXW0pNYRE01aq+xZZurza9j0VrVrE3mG/Gv9F+rBioSv+99miExXF6A/naJW+jIPgFrgc8a753nKWmSzg==} engines: {node: '>=22'} - '@atproto/sync@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-QjW1Hb6DZ4jxK2/CA+e7wcTuij5/nx/AAS6QChtrqbChkfenp+PmNNcqT+YM1rSGrVqFam0wfpWIO6bDgzh8/A==} + '@atproto/star@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-MTeZW52Ym8gPUxcWdDOFqzHi9qgVZy6B7ZbenjRGL84sPWtKwZDKJstUmp0NgH8TykcklZOjmO1X10v0QBximQ==} engines: {node: '>=22'} - '@atproto/syntax@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-Xl2fpD/NcfVOWpHR86HKym2XNDYHmgiqThZXoYMwh9XUo+/LgVZYGVpSecfKRBcQ5tNGiRivE1Fvio5YDfJ3lA==} + '@atproto/sync@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-UDtnHF/WO0geM1V3gIG04GZ/TtRtjhQYFhQCRtrTN0yacg8XS8hZgwwFqMJfI8hfe5w3ANWdNh57xk1cf+STuA==} + engines: {node: '>=22'} + + '@atproto/syntax@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-XW+S/xGd3AbmLLtOIxhTKjZWvq+dI3YoXX2UD7IKt4VJCBW0/LMTV/esh24m1jWzj1wNjnmPgPDpUIr3NWrgPQ==} engines: {node: '>=22'} '@atproto/syntax@0.1.5': @@ -948,12 +942,12 @@ packages: resolution: {integrity: sha512-HCGkqH/Ksxpgg/xCyIvH5hK6o8Lg2PxcEA790GCEV9MspCZB/xIesHZVgJN0cEvklGe+6pNCOZE1B5kj9q1ONA==} engines: {node: '>=22'} - '@atproto/xrpc-server@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-0875PjiWYCV+uwGr91Ri8x3YC1x7oT1+J9GMQKQFlPtDkYOVmO7i9iFPNLNu0BnOx9fo2Lck+qvJDVY1IfP9/g==} + '@atproto/xrpc-server@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-LIv4nyekvtjgiKl59lALlvnlMiDpwJltIFyZu/GH3CbfI5Z0gwTX9xvAW3XnjgSSHqFqk0CriLB6l5duM7E03g==} engines: {node: '>=22'} - '@atproto/xrpc@0.0.0-spaces-alpha-20260818163953': - resolution: {integrity: sha512-AW2zqwpUh8C4pkiDNbmM1FLjmVm5TShaGKDlGAiTMuxf43rfQ+FeBucb9H5w2iaIUQJ594dN3lHXijBATkGNcw==} + '@atproto/xrpc@0.0.0-spaces-alpha-20261105160032': + resolution: {integrity: sha512-uT9Z5hsxdRiO96b2Os1CdmIauDM61zydNmv4C5sga2wFnP3K+Acgn3ETF1bICqrDDdyKXACS1yvZD2/5/ks6dg==} engines: {node: '>=22'} '@atproto/xrpc@0.7.7': @@ -1135,6 +1129,9 @@ packages: resolution: {integrity: sha512-4kdqcjyxo/8RQ8ayjms47HCWZIF5981oE5nIenbfThKDxWXtEHKipAOWlflpPJzZx9y/JWYQkp18Awr7VuepFg==} engines: {node: '>= 18'} + '@borewit/text-codec@0.2.3': + resolution: {integrity: sha512-49CycTz1aAZmvFcwkeFyhud1HUmRIB5Tabf7ALV+VA4Iu85MTfz2cUwzPagMFAdVBvrWdkCxG67I30tUwwpKsw==} + '@braidai/lang@1.1.2': resolution: {integrity: sha512-qBcknbBufNHlui137Hft8xauQMTZDKdophmLFv05r2eNmdIv/MlPuP4TdUknHG68UdWLgVZwgxVe735HzJNIwA==} @@ -1296,6 +1293,7 @@ packages: '@cloudflare/vitest-pool-workers@0.16.9': resolution: {integrity: sha512-qdohrJbLhuB3mq3j/Vg4nHQU+Gw0ZhQErlZ7xr9A2VpP1F4QzCewwwJmWZnXlwU2rMbvGVwwOD91Eb39EvfQmQ==} + deprecated: '@cloudflare/vitest-pool-workers has been renamed to @cloudflare/vitest-plugin. This package will not receive future updates.' peerDependencies: '@vitest/runner': ^4.1.0 '@vitest/snapshot': ^4.1.0 @@ -2175,6 +2173,10 @@ packages: resolution: {integrity: sha512-FFx7YnaYJlIjqWW/AG/yAZ0L/NEY724PipXXXQLdtZPbLwBGbUMTGL1i/esI56TWfTUXxhLfpgrnWJCG8aUJyg==} engines: {node: '>=8.0.0'} + '@opentelemetry/api-logs@0.220.0': + resolution: {integrity: sha512-CmVa4ImJ+ynfrPMNaAXHET6Bhb44SwzmfyVJFq9ni2jgXJR/l7C6gfVFddNmHP+ZOkP9cf4f9DBe68qVLTHc9w==} + engines: {node: '>=8.0.0'} + '@opentelemetry/api@1.9.1': resolution: {integrity: sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==} engines: {node: '>=8.0.0'} @@ -2468,6 +2470,12 @@ packages: peerDependencies: '@opentelemetry/api': ^1.3.0 + '@opentelemetry/instrumentation-pg@0.72.0': + resolution: {integrity: sha512-p9xrFc/6R8t6Y293sTYLZ83LnzZo/qY0bBPA4xabdQt0Qjt8i1SlYFsIeGY2Jmf5WcESNUdjQB3NxWnt5Ox7zw==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + '@opentelemetry/instrumentation-pino@0.65.0': resolution: {integrity: sha512-p6eh+NRmzi1F+/4QG7XDqRk4ICdCNTsM5vdcwUPnpMie2MddgY1/ENmWvCF9r0Kh6QQRA2kkpnhoJFaiRQ5kVw==} engines: {node: ^18.19.0 || >=20.6.0} @@ -2534,6 +2542,12 @@ packages: peerDependencies: '@opentelemetry/api': ^1.3.0 + '@opentelemetry/instrumentation@0.220.0': + resolution: {integrity: sha512-xQx3E2WxP1mDvKzxLxX+CTCtNLa560YJZ3087qYHerl2YmiKpv7AH+dAy7vmx+eVrZ5BwhfWUAVoKOoxCNHcpw==} + engines: {node: ^18.19.0 || >=20.6.0} + peerDependencies: + '@opentelemetry/api': ^1.3.0 + '@opentelemetry/otlp-exporter-base@0.219.0': resolution: {integrity: sha512-zvIxQX/AZUVKDU+hCuYx+7UkiP7GRdnk1ZbFQRYzHvYp47cAWR4j3IhoPhV9KaeXEv2xdGq3IA6PnpzDmLcmSA==} engines: {node: ^18.19.0 || >=20.6.0} @@ -2567,6 +2581,7 @@ packages: '@opentelemetry/propagator-jaeger@2.8.0': resolution: {integrity: sha512-Xnz9zZvvQzUw+9DrOn0MomR7BxFCkA2pcfXBQuHC28ndJpSbjLs7knzYb05kw5SyCjSsEWombkZMgGcJSk8JVg==} engines: {node: ^18.19.0 || >=20.6.0} + deprecated: Package no longer supported. See https://github.com/open-telemetry/opentelemetry-js/pull/7077 peerDependencies: '@opentelemetry/api': '>=1.0.0 <1.10.0' @@ -2637,12 +2652,14 @@ packages: '@opentelemetry/sdk-trace-base@2.8.0': resolution: {integrity: sha512-mhU4jp+vW0mGbFRd+GeXHvmfA4aDqWjBjLC3pE5XMpLs0IE2ryYb019Ts2AQrOq67gaTF25D91+fgvEHDZEnuQ==} engines: {node: ^18.19.0 || >=20.6.0} + deprecated: Use @opentelemetry/sdk-trace package peerDependencies: '@opentelemetry/api': '>=1.3.0 <1.10.0' '@opentelemetry/sdk-trace-node@2.8.0': resolution: {integrity: sha512-nZt9OGufioAc3AfoLTqA9bsAeaMJAictYDdI2VcNQ+PmT+3rfKjAZDZvgPfd8VPX0O5Bw1hdQF6kDK8VSpZiWg==} engines: {node: ^18.19.0 || >=20.6.0} + deprecated: Use @opentelemetry/sdk-trace package peerDependencies: '@opentelemetry/api': '>=1.0.0 <1.10.0' @@ -3368,6 +3385,9 @@ packages: '@smithy/core@3.33.3': resolution: {integrity: sha512-CsOeKq/9kA3y6VJHt+/+VTCtBaxJ4OTFpgrjIUhPpDIKxBci1k2bJaQASF2h/ELWrulGp+t97DZ0mevfAD8idg==} engines: {node: '>=18.0.0'} + deprecated: |- + Deprecated due to a bug in custom logger data redaction. Upgrade to the latest version. If you used a custom logger with this + version, review your logs and rotate any credentials or other secrets. See https://github.com/aws/aws-sdk-js-v3/issues/8393. '@smithy/credential-provider-imds@4.5.2': resolution: {integrity: sha512-A9uSdn72ozbRUSit0eib0TW7nXuNPlaeM0zcGkJ+nE6tFcSDbnmtwoxbTCFBukVQcszDAyvsd7+rTduPTXpygg==} @@ -3497,6 +3517,10 @@ packages: peerDependencies: vite: ^5.2.0 || ^6 || ^7 || ^8 + '@tokenizer/inflate@0.6.0': + resolution: {integrity: sha512-+0RDxhBkyT9xMnGdJAwmats9yxRLR8ypJrQgrnLqOu4Gv/aHlnxYgdGVy2QTwvBl6IF/w2Hr+ZNirH+iMUbVZA==} + engines: {node: '>=18'} + '@tokenizer/token@0.3.0': resolution: {integrity: sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==} @@ -3521,9 +3545,6 @@ packages: '@types/babel__traverse@7.28.0': resolution: {integrity: sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==} - '@types/bn.js@5.2.0': - resolution: {integrity: sha512-DLbJ1BPqxvQhIGbeu8VbUC1DiAiahHtAYvA0ZEAa4P31F7IaArc8z3C3BRQdWX4mtLQuABG4yzp76ZrS02Ui1Q==} - '@types/bun@1.3.8': resolution: {integrity: sha512-3LvWJ2q5GerAXYxO2mffLTqOzEu5qnhEAlh48Vnu8WQfnmSwbgagjGZV6BoHKJztENYEDn6QmVd949W4uESRJA==} @@ -3542,9 +3563,6 @@ packages: '@types/deep-eql@4.0.2': resolution: {integrity: sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==} - '@types/elliptic@6.4.18': - resolution: {integrity: sha512-UseG6H5vjRiNpQvrhy4VF/JXdA3V/Fp5amvveaL+fs28BZ6xIKJBPnUPRlEaZpysD9MbpfaLi8lbl7PGUAkpWw==} - '@types/estree-jsx@1.0.5': resolution: {integrity: sha512-52CcUVNFyfb1A2ALocQw/Dd1BQFNmSdkuC3BkZ6iqhdMfQz7JWOFRuJFloOzjk+6WijU56m9oKXFAXc7o3Towg==} @@ -3730,9 +3748,6 @@ packages: array-iterate@2.0.1: resolution: {integrity: sha512-I1jXZMjAgCMmxT4qxXfPXa6SthSoE8h6gkSI9BGGNv8mP8G/v0blc+qFnZu6K42vTOiuME596QaLO0TP3Lk0xg==} - asn1.js@5.4.1: - resolution: {integrity: sha512-+I//4cYPccV8LdmBLiX8CYvf9Sp3vQsrqu2QNXRcrbiWvcx/UdlFiqUJJzxRQxgsZmvhXhn4cSKeSmoFjVdupA==} - asn1js@3.0.7: resolution: {integrity: sha512-uLvq6KJu04qoQM6gvBfKFjlh6Gl0vOKQuR5cJMDHQkmwfMOQeN3F3SHCv9SNYSL+CRoHvOGFfllDlVz03GQjvQ==} engines: {node: '>=12.0.0'} @@ -3835,6 +3850,9 @@ packages: bindings@1.5.0: resolution: {integrity: sha512-p2q/t/mhvuOj/UeLlV6566GD/guowlr0hHxClI0W9m7MWYkL1F0hLo+0Aexs9HSPCtR1SXQ0TD3MMKrXZajbiQ==} + bintrees@1.0.2: + resolution: {integrity: sha512-VOMgTMwjAaUG580SXn3LacVgjurrbMme7ZZNYGSSV7mmtY6QQRh0Eg3pwIcntQ77DErK1L0NxkbetjcoXzVwKw==} + birpc@4.0.0: resolution: {integrity: sha512-LShSxJP0KTmd101b6DRyGBj57LZxSDYWKitQNW/mi8GRMvZb078Uf9+pveax1DrVL89vm7mWe+TovdI/UDOuPw==} @@ -3844,9 +3862,6 @@ packages: blake3-wasm@2.1.5: resolution: {integrity: sha512-F1+K8EbfOZE49dtoPtmxUQrpXaBIl3ICvasLh+nJta0xkz+9kF/7uet9fLnwKqhDrmj6g+6K3Tw9yQPUg2ka5g==} - bn.js@4.12.5: - resolution: {integrity: sha512-3aRg6/JxfffFD+OlOjOFR3Vo79l39ooBTFucxx+MT3dhCtzn3EmiUPQo+6/OZuI2jbXi3YKgmiTFBgChQMwIRQ==} - body-parser@1.20.6: resolution: {integrity: sha512-p5tAzS57i5MV9fZFDj9LeIiTZEufbSe2eDozP+ElheSUq1m74CRq1jI4mYNDdVs9vQztXFLuk/Gd6BWTdwRJ5g==} engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16} @@ -3868,9 +3883,6 @@ packages: resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} engines: {node: '>=8'} - brorand@1.1.0: - resolution: {integrity: sha512-cKV8tMCEpQs4hK/ik71d6LrPOnpkpGBR0wzxqr68g2m/LB2GxVYQroAjMJZRVM1Y4BCjCKc3vAamxSzOY2RP+w==} - browserslist@4.28.2: resolution: {integrity: sha512-48xSriZYYg+8qXna9kwqjIVzuQxi+KYWp2+5nCYnYKPTr0LvD89Jqk2Or5ogxz0NUMfIjhh2lIUX/LyX9B4oIg==} engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7} @@ -4099,6 +4111,9 @@ packages: core-js@3.49.0: resolution: {integrity: sha512-es1U2+YTtzpwkxVLwAFdSpaIMyQaq0PBgm3YD1W3Qpsn1NAmO3KSgZfu+oGSWVu6NvLHoHCV/aYcsE5wiB7ALg==} + core-js@3.51.0: + resolution: {integrity: sha512-7bDKx/5jm5MxzsXxc93g6Z2+4ZsuT/MddrfRmTDJNAkWsYWHU8EVNEsBiIEWnMAMCHMmRfUEjkuo3jeNBOIHRw==} + cors@2.8.6: resolution: {integrity: sha512-tJtZBBHA6vjIAaF6EnIaq6laBBP9aq/Y3ouVJjEfoHbRBcHBAHYcMh/w8LDrk2PvIMMq8gmopa5D4V8RmbrxGw==} engines: {node: '>= 0.10'} @@ -4270,8 +4285,8 @@ packages: domutils@3.2.2: resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==} - dotenv@16.6.1: - resolution: {integrity: sha512-uBq4egWHTcTt33a72vpSG0z3HnPuIl6NqYcTrKEg2azoEyl2hpW0zqlxysq2pK9HlDIHyHyakeYaYnSAwd8bow==} + dotenv@17.4.2: + resolution: {integrity: sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==} engines: {node: '>=12'} dset@3.1.4: @@ -4300,9 +4315,6 @@ packages: electron-to-chromium@1.5.361: resolution: {integrity: sha512-Q6Hts7N9FnJc5LeGRINFvLhCI9xZmNtTDe5ZbcVezQz7cU4a8Aua3GH1b8J2XY8Al9PF+OCwYqhgsOOheMdvkA==} - elliptic@6.6.1: - resolution: {integrity: sha512-RaddvvMatK2LJHqFJ+YA4WysVN5Ita9E35botqIYspQ4TkRAlCicdzKOjlyv/1Za5RyTNn7di//eEV0uTAfe3g==} - emoji-regex@10.6.0: resolution: {integrity: sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==} @@ -4512,9 +4524,9 @@ packages: fflate@0.8.2: resolution: {integrity: sha512-cPJU47OaAoCbg0pBvzsgpTPhmhqI5eJjh/JIu8tPj5q+T7iLvW/JAYUqmE7KOB4R1ZyEhzBaIQpQpardBF5z8A==} - file-type@16.5.4: - resolution: {integrity: sha512-/yFHK0aGjFEgDJjEKP0pWCplsPFPhwyfwevf/pVxiN0tmE4L9LmwWxWukdJSHdoCli4VgQLehjJtwQBnqmsKcw==} - engines: {node: '>=10'} + file-type@22.3.0: + resolution: {integrity: sha512-PrPedgnnWl5bWz3JHgar0QSzRvzeyFh7dZ9JpYOgcPZu4KALS9zw4MMa6qXRYyjeBsAlpaWB2boLuG991+0HIQ==} + engines: {node: '>=22'} file-uri-to-path@1.0.0: resolution: {integrity: sha512-0Zt+s3L7Vf1biwWZ29aARiVYLx7iMGnEUl9x33fbB/j3jR81u/O2LbqK+Bm1CDSNDKVtJ/YjwY7TUd5SkeLQLw==} @@ -4681,9 +4693,6 @@ packages: resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==} engines: {node: '>= 0.4'} - hash.js@1.1.7: - resolution: {integrity: sha512-taOaskGt4z4SOANNseOviYDvjEJinIkRgmp7LbKP2YTTmVxWBl87s/uzK9r+44BclBSp2X7K1hqeNfz9JbBeXA==} - hasown@2.0.4: resolution: {integrity: sha512-T2UbfbBEF32wiepXIsMlTW9+dDYC6wMh/t/vYA4tuOMKqWz/n3vr1NFSxQiyP+zk2mXsoMA/i/7qV6LKut1t1A==} engines: {node: '>= 0.4'} @@ -4758,9 +4767,6 @@ packages: hls.js@1.6.16: resolution: {integrity: sha512-VSIRpLfRwlAAdGL4wiTucx2ScRipo0ed1FBatWkyt832jC4CReKstga6yIhYVwGu9LOBjuX9wzmRMeQdBJtzEA==} - hmac-drbg@1.0.1: - resolution: {integrity: sha512-Tti3gMqLdZfhOQY1Mzf/AanLiqh1WTiJgEj26ZuYQ9fbkLomzGchCws4FyrSd4VkpBfiNhaE1On+lOz894jvXg==} - hono@4.11.8: resolution: {integrity: sha512-eVkB/CYCCei7K2WElZW9yYQFWssG0DhaDhVvr7wy5jJ22K+ck8fWW0EsLpB0sITUTvPnc97+rrbQqIr5iqiy9Q==} engines: {node: '>=16.9.0'} @@ -4970,9 +4976,6 @@ packages: jsonc-parser@3.3.1: resolution: {integrity: sha512-HUgH65KyejrUFPvHFPbqOY0rsFip3Bo5wb4ngvdi1EpCYWUQDC5V+Y7mZws+DLkr4M//zQJoanu1SP+87Dv1oQ==} - key-encoder@2.0.3: - resolution: {integrity: sha512-fgBtpAGIr/Fy5/+ZLQZIPPhsZEcbSlYu/Wu96tNDFNSjSACw5lEIOFeaVdQ/iwrb8oxjlWi6wmWdH76hV6GZjg==} - kleur@4.1.5: resolution: {integrity: sha512-o+NO+8WrRiQEE4/7nwRJhN1HWpVmJm511pBHUxPLtp0BUISzlBplORYSmTclCnJvQq2tKu/sgl3xVpkc7ZWuQQ==} engines: {node: '>=6'} @@ -5365,12 +5368,6 @@ packages: engines: {node: '>=22.0.0'} hasBin: true - minimalistic-assert@1.0.1: - resolution: {integrity: sha512-UtJcAD4yEaGtjPezWuO9wC4nwUnVH/8/Im3yEHQP4b67cXlD/Qr9hdITCU1xDbSEXg2XKNaP8jsReV7vQd00/A==} - - minimalistic-crypto-utils@1.0.1: - resolution: {integrity: sha512-JIYlbt6g8i5jKfJ3xz7rF0LXmv2TkDxBLUkiBeZ7bAx4GnnNMr8xFpGnOxn6GhTEHx3SjRrZEoU+j04prX1ktg==} - minimatch@10.2.6: resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==} engines: {node: 18 || 20 || >=22} @@ -5662,10 +5659,6 @@ packages: pathe@2.0.3: resolution: {integrity: sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==} - peek-readable@4.1.0: - resolution: {integrity: sha512-ZI3LnwUv5nOGbQzD9c2iDG6toheuXSZP5esSHBjopsXH4dg19soufvpUGA3uohi5anFtGb2lhAVdHzH6R/Evvg==} - engines: {node: '>=8'} - pg-cloudflare@1.4.0: resolution: {integrity: sha512-Vo7z/6rrQYxpNRylp4Tlob2elzbh+N/MOQbxFVWCxS7oEx6jF53GTJFxK2WWpKuBRkmiin4Mt+xofFDjx09R0A==} @@ -5746,6 +5739,7 @@ packages: plyr@3.8.4: resolution: {integrity: sha512-DrzLbK9Wol3zeiuZCleD9aUOl0KAaBHR9H6WVVVYPZ4Ya+LYxUFTgSF1jooHcMQCv96Ws96wCaZzIoP3bES8pQ==} + deprecated: 'Plyr is deprecated and receives security updates only. Use Video.js 10 for new projects. Migration guide: https://videojs.org/docs/framework/html/guides/migrate-from-plyr' pngjs@5.0.0: resolution: {integrity: sha512-40QW5YalBNfQo5yRYmiw7Yz6TKKVr3h6970B2YE+3fQpsWcrbj1PzJgxeJ19DRQjhMbKPIuMY8rFaXc8moolVw==} @@ -5815,6 +5809,11 @@ packages: resolution: {integrity: sha512-cdGef/drWFoydD1JsMzuFf8100nZl+GT+yacc2bEced5f9Rjk4z+WtFUTBu9PhOi9j/jfmBPu0mMEY4wIdAF8A==} engines: {node: '>= 0.6.0'} + prom-client@15.1.3: + resolution: {integrity: sha512-6ZiOBfCywsD4k1BN9IX0uZhF+tJkV8q8llP64G5Hajs4JOeVLPCwpPVcpXy3BwYiUGgyJzsJJQeOIv7+hDSq8g==} + engines: {node: ^16 || ^18 || >=20} + deprecated: prom-client has been replaced by @prometheus-io/client + property-information@7.1.0: resolution: {integrity: sha512-TwEZ+X+yCJmYfL7TPUOcvBZ4QfoT5YenQiJuX//0th53DE6w0xxLEtfK3iyryQFddXuvkIk51EEgrJQ0WJkOmQ==} @@ -5892,10 +5891,6 @@ packages: resolution: {integrity: sha512-oIGGmcpTLwPga8Bn6/Z75SVaH1z5dUut2ibSyAMVhmUggWpmDn2dapB0n7f8nwaSiRtepAsfJyfXIO5DCVAODg==} engines: {node: ^12.22.0 || ^14.17.0 || >=16.0.0} - readable-web-to-node-stream@3.0.4: - resolution: {integrity: sha512-9nX56alTf5bwXQ3ZDipHJhusu9NTQJ/CVPtb/XHAJCXihZeitfJvIRS4GqQ/mfIoOE3IelHMrpayVrosdHBuLw==} - engines: {node: '>=8'} - readdirp@5.0.0: resolution: {integrity: sha512-9u/XQ1pvrQtYyMpZe7DXKv2p5CNvyVwzUB6uhLAnQwHMSgKMBR62lc7AHljaeteeHXn11XTAaLLUVZYVZyuRBQ==} engines: {node: '>= 20.19.0'} @@ -6312,9 +6307,9 @@ packages: resolution: {integrity: sha512-1tB5mhVo7U+ETBKNf92xT4hrQa3pm0MZ0PQvuDnWgAAGHDsfp4lPSpiS6psrSiet87wyGPh9ft6wmhOMQ0hDiw==} engines: {node: '>=14.16'} - strtok3@6.3.0: - resolution: {integrity: sha512-fZtbhtvI9I48xDSywd/somNqgUHl2L2cstmXCCif0itOf96jeW18MBSyrLuNicYQVkvpOxkZtkzujiTJ9LW5Jw==} - engines: {node: '>=10'} + strtok3@10.7.0: + resolution: {integrity: sha512-iAqrCpp7UXD2FZiHWhLXqdJ6CmNeVzRkkHAyyhhKMVtbVm2KtPX3D/bJNonvtcyLTHS4rwqP2pz9fsjK1K4z0Q==} + engines: {node: '>=18'} structured-headers@1.0.1: resolution: {integrity: sha512-QYBxdBtA4Tl5rFPuqmbmdrS9kbtren74RTJTcs0VSQNVV5iRhJD4QlYTLD0+81SBwUQctjEQzjTRI3WG4DzICA==} @@ -6363,6 +6358,9 @@ packages: resolution: {integrity: sha512-ujeqbceABgwMZxEJnk2HDY2DlnUZ+9oEcb1KzTVfYHio0UE6dG71n60d8D2I4qNvleWrrXpmjpt7vZeF1LnMZQ==} engines: {node: '>=6'} + tdigest@0.1.3: + resolution: {integrity: sha512-zbRt+lT+/H4fRItHshczHErVCQnitJk8MfMT24MqFJf3YL7SJJPqGIGeuOdvxXxM/AHFzKBl7WoyaYwqO9s3Kw==} + thenify-all@1.6.0: resolution: {integrity: sha512-RNxQH/qI8/t3thXJDwcstUO4zeqo64+Uy/+sNVRBx4Xn2OX+OZ9oP+iJnNFqplFra2ZUVeKCSa2oVWi3T4uVmA==} engines: {node: '>=0.8'} @@ -6427,9 +6425,9 @@ packages: resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==} engines: {node: '>=0.6'} - token-types@4.2.1: - resolution: {integrity: sha512-6udB24Q737UD/SDsKAHI9FCRP7Bqc9D/MQUV02ORQg5iskjtLJlZJNdN4kKtcdtwCeWIwIHDGaUsTsCCAa8sFQ==} - engines: {node: '>=10'} + token-types@6.2.0: + resolution: {integrity: sha512-s9euYHM//T3loJtbNUYdbAzsMlvKBeRS+XCLFy+UGosMQH19Hwjap5k19i4PPAEJJBsVIpMpVTxl4fIqCuNfUg==} + engines: {node: '>=14.16'} toygrad@2.6.0: resolution: {integrity: sha512-g4zBmlSbvzOE5FOILxYkAybTSxijKLkj1WoNqVGnbMcWDyj4wWQ+eYSr3ik7XOpIgMq/7eBcPRTJX3DM2E0YMg==} @@ -6524,6 +6522,10 @@ packages: engines: {node: '>=0.8.0'} hasBin: true + uint8array-extras@1.6.0: + resolution: {integrity: sha512-8iAasVS4wUx0gPLjH8Xtz2PeDzTSiy8QiLGu2DT3X5GU+egFEQhpnbtkehbAwjvDcxIERmCYcysiODFmE3Ud0Q==} + engines: {node: '>=18'} + uint8arrays@3.0.0: resolution: {integrity: sha512-HRCx0q6O9Bfbp+HHSfQQKD7wU70+lydKVt4EghkdOvlK/NlrF90z+eXV34mUd48rNvVJXwkrMSPpCATkct8fJA==} @@ -7453,16 +7455,16 @@ snapshots: '@atcute/varint@2.0.2': {} - '@atproto-labs/did-resolver@0.3.7': + '@atproto-labs/did-resolver@0.0.0-spaces-alpha-20261105160032': dependencies: '@atproto-labs/fetch': 0.3.5 '@atproto-labs/pipe': 0.2.4 '@atproto-labs/simple-store': 0.5.1 '@atproto-labs/simple-store-memory': 0.2.6 - '@atproto/did': 0.5.4 + '@atproto/did': 0.0.0-spaces-alpha-20261105160032 zod: 3.25.76 - '@atproto-labs/fetch-node@0.3.7': + '@atproto-labs/fetch-node@0.0.0-spaces-alpha-20261105160032': dependencies: '@atproto-labs/fetch': 0.3.5 '@atproto-labs/pipe': 0.2.4 @@ -7475,23 +7477,41 @@ snapshots: dependencies: '@atproto-labs/pipe': 0.2.4 - '@atproto-labs/handle-resolver-node@0.2.8': + '@atproto-labs/handle-resolver-node@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto-labs/fetch-node': 0.3.7 - '@atproto-labs/handle-resolver': 0.4.8 - '@atproto/did': 0.5.4 + '@atproto-labs/fetch-node': 0.0.0-spaces-alpha-20261105160032 + '@atproto-labs/handle-resolver': 0.0.0-spaces-alpha-20261105160032 + '@atproto/did': 0.0.0-spaces-alpha-20261105160032 - '@atproto-labs/handle-resolver@0.4.8': + '@atproto-labs/handle-resolver@0.0.0-spaces-alpha-20261105160032': dependencies: '@atproto-labs/simple-store': 0.5.1 '@atproto-labs/simple-store-memory': 0.2.6 - '@atproto/did': 0.5.4 + '@atproto/did': 0.0.0-spaces-alpha-20261105160032 zod: 3.25.76 - '@atproto-labs/identity-resolver@0.4.7': + '@atproto-labs/identity-resolver@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto-labs/did-resolver': 0.3.7 - '@atproto-labs/handle-resolver': 0.4.8 + '@atproto-labs/did-resolver': 0.0.0-spaces-alpha-20261105160032 + '@atproto-labs/handle-resolver': 0.0.0-spaces-alpha-20261105160032 + + '@atproto-labs/opentelemetry-node@0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/auto-instrumentations-node': 0.77.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.10.0(@opentelemetry/api@1.9.1))(supports-color@10.2.2) + '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-express': 0.67.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-http': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-pino': 0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-runtime-node': 0.32.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-undici': 0.29.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/resource-detector-container': 0.8.12(@opentelemetry/api@1.9.1) + '@opentelemetry/sdk-node': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/semantic-conventions': 1.43.0 + import-in-the-middle: 3.3.3 + transitivePeerDependencies: + - supports-color '@atproto-labs/pipe@0.2.4': {} @@ -7507,21 +7527,21 @@ snapshots: '@atproto-labs/simple-store@0.5.1': {} - '@atproto-labs/xrpc-utils@0.0.0-spaces-alpha-20260818163953(supports-color@10.2.2)': + '@atproto-labs/xrpc-utils@0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2)': dependencies: - '@atproto/xrpc': 0.0.0-spaces-alpha-20260818163953 - '@atproto/xrpc-server': 0.0.0-spaces-alpha-20260818163953(supports-color@10.2.2) + '@atproto/xrpc': 0.0.0-spaces-alpha-20261105160032 + '@atproto/xrpc-server': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) transitivePeerDependencies: - bufferutil - supports-color - utf-8-validate - '@atproto/api@0.0.0-spaces-alpha-20260818163953': + '@atproto/api@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto/common-web': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lexicon': 0.0.0-spaces-alpha-20260818163953 - '@atproto/syntax': 0.0.0-spaces-alpha-20260818163953 - '@atproto/xrpc': 0.0.0-spaces-alpha-20260818163953 + '@atproto/common-web': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lexicon': 0.0.0-spaces-alpha-20261105160032 + '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 + '@atproto/xrpc': 0.0.0-spaces-alpha-20261105160032 await-lock: 3.0.0 multiformats: 13.4.2 tlds: 1.261.0 @@ -7538,35 +7558,35 @@ snapshots: tlds: 1.261.0 zod: 3.25.76 - '@atproto/aws@0.0.0-spaces-alpha-20260818163953': + '@atproto/aws@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto/common': 0.0.0-spaces-alpha-20260818163953 - '@atproto/common-web': 0.0.0-spaces-alpha-20260818163953 - '@atproto/crypto': 0.0.0-spaces-alpha-20260818163953 - '@atproto/repo': 0.0.0-spaces-alpha-20260818163953 + '@atproto/common': 0.0.0-spaces-alpha-20261105160032 + '@atproto/common-web': 0.0.0-spaces-alpha-20261105160032 + '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 + '@atproto/repo': 0.0.0-spaces-alpha-20261105160032 '@aws-sdk/client-cloudfront': 3.1121.0 '@aws-sdk/client-kms': 3.1121.0 '@aws-sdk/client-s3': 3.1121.0 '@aws-sdk/lib-storage': 3.879.0(@aws-sdk/client-s3@3.1121.0) '@noble/curves': 1.9.7 - key-encoder: 2.0.3 multiformats: 13.4.2 uint8arrays: 5.1.1 - '@atproto/bsky@0.0.0-spaces-alpha-20260818163953(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2)': - dependencies: - '@atproto-labs/fetch-node': 0.3.7 - '@atproto-labs/xrpc-utils': 0.0.0-spaces-alpha-20260818163953(supports-color@10.2.2) - '@atproto/api': 0.0.0-spaces-alpha-20260818163953 - '@atproto/common': 0.0.0-spaces-alpha-20260818163953 - '@atproto/crypto': 0.0.0-spaces-alpha-20260818163953 - '@atproto/did': 0.5.4 - '@atproto/identity': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex': 0.0.0-spaces-alpha-20260818163953 - '@atproto/repo': 0.0.0-spaces-alpha-20260818163953 - '@atproto/sync': 0.0.0-spaces-alpha-20260818163953(supports-color@10.2.2) - '@atproto/syntax': 0.0.0-spaces-alpha-20260818163953 - '@atproto/xrpc-server': 0.0.0-spaces-alpha-20260818163953(supports-color@10.2.2) + '@atproto/bsky@0.0.0-spaces-alpha-20261105160032(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2)': + dependencies: + '@atproto-labs/fetch-node': 0.0.0-spaces-alpha-20261105160032 + '@atproto-labs/opentelemetry-node': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) + '@atproto-labs/xrpc-utils': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) + '@atproto/api': 0.0.0-spaces-alpha-20261105160032 + '@atproto/common': 0.0.0-spaces-alpha-20261105160032 + '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 + '@atproto/did': 0.0.0-spaces-alpha-20261105160032 + '@atproto/identity': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex': 0.0.0-spaces-alpha-20261105160032 + '@atproto/repo': 0.0.0-spaces-alpha-20261105160032 + '@atproto/sync': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) + '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 + '@atproto/xrpc-server': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) '@bufbuild/protobuf': 1.10.1 '@connectrpc/connect': 1.7.0(@bufbuild/protobuf@1.10.1) '@connectrpc/connect-express': 1.7.0(@bufbuild/protobuf@1.10.1)(@connectrpc/connect-node@1.7.0(@bufbuild/protobuf@1.10.1)(@connectrpc/connect@1.7.0(@bufbuild/protobuf@1.10.1)))(@connectrpc/connect@1.7.0(@bufbuild/protobuf@1.10.1)) @@ -7574,6 +7594,10 @@ snapshots: '@did-plc/lib': 0.0.1(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) '@growthbook/growthbook': 1.7.0 '@hapi/address': 5.1.1 + '@noble/curves': 1.9.7 + '@opentelemetry/api': 1.9.1 + '@opentelemetry/api-logs': 0.219.0 + '@opentelemetry/semantic-conventions': 1.43.0 '@types/http-errors': 2.0.5 compression: 1.8.1(supports-color@10.2.2) cors: 2.8.6 @@ -7584,7 +7608,6 @@ snapshots: http-terminator: 3.2.0 ioredis: 5.11.1(supports-color@10.2.2) jose: 5.10.0 - key-encoder: 2.0.3 kysely: 0.29.5 leo-profanity: 1.9.0 murmurhash: 2.0.1 @@ -7596,6 +7619,9 @@ snapshots: structured-headers: 1.0.1 uint8arrays: 5.1.1 undici: 8.10.0 + undici_v6: undici@6.28.0 + undici_v7: undici@7.24.8 + undici_v8: undici@8.10.0 zod: 3.23.8 transitivePeerDependencies: - bufferutil @@ -7621,11 +7647,18 @@ snapshots: transitivePeerDependencies: - pg-native - '@atproto/common-web@0.0.0-spaces-alpha-20260818163953': + '@atproto/car@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto/lex-data': 0.1.7 - '@atproto/lex-json': 0.1.6 - '@atproto/syntax': 0.0.0-spaces-alpha-20260818163953 + '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 + tslib: 2.8.1 + varint: 6.0.0 + + '@atproto/common-web@0.0.0-spaces-alpha-20261105160032': + dependencies: + '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-json': 0.0.0-spaces-alpha-20261105160032 + '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 zod: 3.25.76 '@atproto/common-web@0.2.4': @@ -7642,14 +7675,13 @@ snapshots: '@atproto/syntax': 0.4.3 zod: 3.25.76 - '@atproto/common@0.0.0-spaces-alpha-20260818163953': + '@atproto/common@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto/common-web': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-cbor': 0.1.6 - '@atproto/lex-data': 0.1.7 + '@atproto/common-web': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 multiformats: 13.4.2 pino: 10.3.1 - varint: 6.0.0 '@atproto/common@0.1.0': dependencies: @@ -7684,7 +7716,7 @@ snapshots: multiformats: 9.9.0 pino: 8.21.0 - '@atproto/crypto@0.0.0-spaces-alpha-20260818163953': + '@atproto/crypto@0.0.0-spaces-alpha-20261105160032': dependencies: '@noble/curves': 1.9.7 '@noble/hashes': 1.8.0 @@ -7704,24 +7736,24 @@ snapshots: '@noble/hashes': 1.8.0 uint8arrays: 3.0.0 - '@atproto/dev-env@0.0.0-spaces-alpha-20260818163953(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2)': + '@atproto/dev-env@0.0.0-spaces-alpha-20261105160032(@opentelemetry/api@1.9.1)(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@atproto/api': 0.0.0-spaces-alpha-20260818163953 - '@atproto/bsky': 0.0.0-spaces-alpha-20260818163953(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) + '@atproto/api': 0.0.0-spaces-alpha-20261105160032 + '@atproto/bsky': 0.0.0-spaces-alpha-20261105160032(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) '@atproto/bsync': 0.0.0 - '@atproto/common-web': 0.0.0-spaces-alpha-20260818163953 - '@atproto/crypto': 0.0.0-spaces-alpha-20260818163953 - '@atproto/identity': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lexicon': 0.0.0-spaces-alpha-20260818163953 - '@atproto/ozone': 0.0.0-spaces-alpha-20260818163953(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) - '@atproto/pds': 0.0.0-spaces-alpha-20260818163953(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) - '@atproto/sync': 0.0.0-spaces-alpha-20260818163953(supports-color@10.2.2) - '@atproto/syntax': 0.0.0-spaces-alpha-20260818163953 - '@atproto/xrpc-server': 0.0.0-spaces-alpha-20260818163953(supports-color@10.2.2) + '@atproto/common-web': 0.0.0-spaces-alpha-20261105160032 + '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 + '@atproto/identity': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lexicon': 0.0.0-spaces-alpha-20261105160032 + '@atproto/ozone': 0.0.0-spaces-alpha-20261105160032(@opentelemetry/api@1.9.1)(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) + '@atproto/pds': 0.0.0-spaces-alpha-20261105160032(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) + '@atproto/sync': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) + '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 + '@atproto/xrpc-server': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) '@did-plc/lib': 0.0.1(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) '@did-plc/server': 0.0.1(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) - dotenv: 16.6.1 + dotenv: 17.4.2 express: 4.22.2(supports-color@10.2.2) get-port: 5.1.1 http-terminator: 3.2.0 @@ -7729,24 +7761,25 @@ snapshots: uint8arrays: 5.1.1 undici: 8.10.0 transitivePeerDependencies: + - '@opentelemetry/api' - bufferutil - debug - pg-native - supports-color - utf-8-validate - '@atproto/did@0.3.0': + '@atproto/did@0.0.0-spaces-alpha-20261105160032': dependencies: zod: 3.25.76 - '@atproto/did@0.5.4': + '@atproto/did@0.3.0': dependencies: zod: 3.25.76 - '@atproto/identity@0.0.0-spaces-alpha-20260818163953': + '@atproto/identity@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto/common-web': 0.0.0-spaces-alpha-20260818163953 - '@atproto/crypto': 0.0.0-spaces-alpha-20260818163953 + '@atproto/common-web': 0.0.0-spaces-alpha-20261105160032 + '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 '@atproto/jwk-jose@0.2.4': dependencies: @@ -7769,14 +7802,20 @@ snapshots: multiformats: 13.4.2 zod: 3.25.76 - '@atproto/lex-builder@0.0.0-spaces-alpha-20260818163953': + '@atproto/lex-builder@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto/lex-document': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-schema': 0.0.0-spaces-alpha-20260818163953 + '@atproto/lex-document': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261105160032 prettier: 3.9.6 ts-morph: 27.0.2 tslib: 2.8.1 + '@atproto/lex-cbor@0.0.0-spaces-alpha-20261105160032': + dependencies: + '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 + cborg: 4.5.8 + tslib: 2.8.1 + '@atproto/lex-cbor@0.0.11': dependencies: '@atproto/lex-data': 0.0.11 @@ -7788,18 +7827,18 @@ snapshots: multiformats: 9.9.0 tslib: 2.8.1 - '@atproto/lex-cbor@0.1.6': + '@atproto/lex-client@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto/lex-data': 0.1.7 - cborg: 4.5.8 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-json': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261105160032 tslib: 2.8.1 - '@atproto/lex-client@0.0.0-spaces-alpha-20260818163953': + '@atproto/lex-data@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto/lex-data': 0.1.7 - '@atproto/lex-json': 0.1.6 - '@atproto/lex-schema': 0.0.0-spaces-alpha-20260818163953 + multiformats: 13.4.2 tslib: 2.8.1 + unicode-segmenter: 0.14.5 '@atproto/lex-data@0.0.11': dependencies: @@ -7816,27 +7855,26 @@ snapshots: uint8arrays: 3.0.0 unicode-segmenter: 0.14.5 - '@atproto/lex-data@0.1.7': + '@atproto/lex-document@0.0.0-spaces-alpha-20261105160032': dependencies: - multiformats: 13.4.2 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261105160032 + core-js: 3.51.0 tslib: 2.8.1 - unicode-segmenter: 0.14.5 - '@atproto/lex-document@0.0.0-spaces-alpha-20260818163953': + '@atproto/lex-installer@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto/lex-schema': 0.0.0-spaces-alpha-20260818163953 - core-js: 3.49.0 + '@atproto/lex-builder': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-document': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-resolver': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261105160032 + '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 tslib: 2.8.1 - '@atproto/lex-installer@0.0.0-spaces-alpha-20260818163953': + '@atproto/lex-json@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto/lex-builder': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-cbor': 0.1.6 - '@atproto/lex-data': 0.1.7 - '@atproto/lex-document': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-resolver': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-schema': 0.0.0-spaces-alpha-20260818163953 - '@atproto/syntax': 0.0.0-spaces-alpha-20260818163953 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 tslib: 2.8.1 '@atproto/lex-json@0.0.11': @@ -7844,45 +7882,46 @@ snapshots: '@atproto/lex-data': 0.0.11 tslib: 2.8.1 - '@atproto/lex-json@0.1.6': + '@atproto/lex-password-session@0.0.0': dependencies: - '@atproto/lex-data': 0.1.7 + '@atproto/lex-client': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261105160032 tslib: 2.8.1 - '@atproto/lex-resolver@0.0.0-spaces-alpha-20260818163953': + '@atproto/lex-resolver@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto-labs/did-resolver': 0.3.7 - '@atproto/crypto': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-client': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-data': 0.1.7 - '@atproto/lex-document': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-schema': 0.0.0-spaces-alpha-20260818163953 - '@atproto/repo': 0.0.0-spaces-alpha-20260818163953 - '@atproto/syntax': 0.0.0-spaces-alpha-20260818163953 + '@atproto-labs/did-resolver': 0.0.0-spaces-alpha-20261105160032 + '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-client': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-document': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261105160032 + '@atproto/repo': 0.0.0-spaces-alpha-20261105160032 + '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 tslib: 2.8.1 - '@atproto/lex-schema@0.0.0-spaces-alpha-20260818163953': + '@atproto/lex-schema@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto/lex-data': 0.1.7 - '@atproto/syntax': 0.0.0-spaces-alpha-20260818163953 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 + '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 '@standard-schema/spec': 1.1.0 tslib: 2.8.1 - '@atproto/lex@0.0.0-spaces-alpha-20260818163953': + '@atproto/lex@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto/lex-builder': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-client': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-data': 0.1.7 - '@atproto/lex-installer': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-json': 0.1.6 - '@atproto/lex-schema': 0.0.0-spaces-alpha-20260818163953 + '@atproto/lex-builder': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-client': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-installer': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-json': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261105160032 tslib: 2.8.1 yargs: 18.1.0 - '@atproto/lexicon@0.0.0-spaces-alpha-20260818163953': + '@atproto/lexicon@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto/common-web': 0.0.0-spaces-alpha-20260818163953 - '@atproto/syntax': 0.0.0-spaces-alpha-20260818163953 + '@atproto/common-web': 0.0.0-spaces-alpha-20261105160032 + '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 multiformats: 13.4.2 zod: 3.25.76 @@ -7894,62 +7933,63 @@ snapshots: multiformats: 9.9.0 zod: 3.25.76 - '@atproto/oauth-client-node@0.0.0-spaces-alpha-20260818163953': + '@atproto/oauth-client-node@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto-labs/did-resolver': 0.3.7 - '@atproto-labs/handle-resolver-node': 0.2.8 + '@atproto-labs/did-resolver': 0.0.0-spaces-alpha-20261105160032 + '@atproto-labs/handle-resolver-node': 0.0.0-spaces-alpha-20261105160032 '@atproto-labs/simple-store': 0.5.1 - '@atproto/did': 0.5.4 + '@atproto/did': 0.0.0-spaces-alpha-20261105160032 '@atproto/jwk': 0.7.4 '@atproto/jwk-jose': 0.2.4 '@atproto/jwk-webcrypto': 0.3.4 - '@atproto/oauth-client': 0.0.0-spaces-alpha-20260818163953 - '@atproto/oauth-types': 0.7.5 + '@atproto/oauth-client': 0.0.0-spaces-alpha-20261105160032 + '@atproto/oauth-types': 0.0.0-spaces-alpha-20261105160032 - '@atproto/oauth-client@0.0.0-spaces-alpha-20260818163953': + '@atproto/oauth-client@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto-labs/did-resolver': 0.3.7 + '@atproto-labs/did-resolver': 0.0.0-spaces-alpha-20261105160032 '@atproto-labs/fetch': 0.3.5 - '@atproto-labs/handle-resolver': 0.4.8 - '@atproto-labs/identity-resolver': 0.4.7 + '@atproto-labs/handle-resolver': 0.0.0-spaces-alpha-20261105160032 + '@atproto-labs/identity-resolver': 0.0.0-spaces-alpha-20261105160032 '@atproto-labs/simple-store': 0.5.1 '@atproto-labs/simple-store-memory': 0.2.6 - '@atproto/did': 0.5.4 + '@atproto/did': 0.0.0-spaces-alpha-20261105160032 '@atproto/jwk': 0.7.4 - '@atproto/oauth-types': 0.7.5 - '@atproto/xrpc': 0.0.0-spaces-alpha-20260818163953 - core-js: 3.49.0 + '@atproto/oauth-types': 0.0.0-spaces-alpha-20261105160032 + '@atproto/xrpc': 0.0.0-spaces-alpha-20261105160032 + core-js: 3.51.0 multiformats: 13.4.2 zod: 3.25.76 - '@atproto/oauth-provider-api@0.0.0-spaces-alpha-20260818163953': + '@atproto/oauth-provider-api@0.0.0-spaces-alpha-20261105160032': dependencies: '@atproto/jwk': 0.7.4 - '@atproto/oauth-types': 0.7.5 - '@atproto/syntax': 0.0.0-spaces-alpha-20260818163953 + '@atproto/oauth-types': 0.0.0-spaces-alpha-20261105160032 + '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 - '@atproto/oauth-provider-ui@0.0.0-spaces-alpha-20260818163953': + '@atproto/oauth-provider-ui@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto/oauth-provider-api': 0.0.0-spaces-alpha-20260818163953 + '@atproto/oauth-provider-api': 0.0.0-spaces-alpha-20261105160032 - '@atproto/oauth-provider@0.0.0-spaces-alpha-20260818163953(supports-color@10.2.2)': + '@atproto/oauth-provider@0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2)': dependencies: - '@atproto-labs/fetch-node': 0.3.7 + '@atproto-labs/did-resolver': 0.0.0-spaces-alpha-20261105160032 + '@atproto-labs/fetch-node': 0.0.0-spaces-alpha-20261105160032 + '@atproto-labs/handle-resolver-node': 0.0.0-spaces-alpha-20261105160032 '@atproto-labs/pipe': 0.2.4 '@atproto-labs/simple-store': 0.5.1 '@atproto-labs/simple-store-memory': 0.2.6 - '@atproto/common': 0.0.0-spaces-alpha-20260818163953 - '@atproto/did': 0.5.4 - '@atproto/identity': 0.0.0-spaces-alpha-20260818163953 + '@atproto/common': 0.0.0-spaces-alpha-20261105160032 + '@atproto/did': 0.0.0-spaces-alpha-20261105160032 '@atproto/jwk': 0.7.4 '@atproto/jwk-jose': 0.2.4 - '@atproto/lex-document': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-resolver': 0.0.0-spaces-alpha-20260818163953 - '@atproto/oauth-provider-api': 0.0.0-spaces-alpha-20260818163953 - '@atproto/oauth-provider-ui': 0.0.0-spaces-alpha-20260818163953 - '@atproto/oauth-scopes': 0.0.0-spaces-alpha-20260818163953 - '@atproto/oauth-types': 0.7.5 - '@atproto/syntax': 0.0.0-spaces-alpha-20260818163953 + '@atproto/lex-document': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-resolver': 0.0.0-spaces-alpha-20261105160032 + '@atproto/oauth-provider-api': 0.0.0-spaces-alpha-20261105160032 + '@atproto/oauth-provider-ui': 0.0.0-spaces-alpha-20261105160032 + '@atproto/oauth-scopes': 0.0.0-spaces-alpha-20261105160032 + '@atproto/oauth-types': 0.0.0-spaces-alpha-20261105160032 + '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 '@hapi/accept': 6.0.3 '@hapi/address': 5.1.1 '@hapi/bourne': 3.0.0 @@ -7964,37 +8004,40 @@ snapshots: transitivePeerDependencies: - supports-color - '@atproto/oauth-scopes@0.0.0-spaces-alpha-20260818163953': + '@atproto/oauth-scopes@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto/did': 0.5.4 - '@atproto/syntax': 0.0.0-spaces-alpha-20260818163953 + '@atproto/did': 0.0.0-spaces-alpha-20261105160032 + '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 - '@atproto/oauth-types@0.6.3': + '@atproto/oauth-types@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto/did': 0.3.0 - '@atproto/jwk': 0.6.0 + '@atproto/did': 0.0.0-spaces-alpha-20261105160032 + '@atproto/jwk': 0.7.4 zod: 3.25.76 - '@atproto/oauth-types@0.7.5': + '@atproto/oauth-types@0.6.3': dependencies: - '@atproto/did': 0.5.4 - '@atproto/jwk': 0.7.4 + '@atproto/did': 0.3.0 + '@atproto/jwk': 0.6.0 zod: 3.25.76 - '@atproto/ozone@0.0.0-spaces-alpha-20260818163953(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2)': + '@atproto/ozone@0.0.0-spaces-alpha-20261105160032(@opentelemetry/api@1.9.1)(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@atproto/api': 0.0.0-spaces-alpha-20260818163953 - '@atproto/common': 0.0.0-spaces-alpha-20260818163953 - '@atproto/crypto': 0.0.0-spaces-alpha-20260818163953 - '@atproto/identity': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lexicon': 0.0.0-spaces-alpha-20260818163953 - '@atproto/syntax': 0.0.0-spaces-alpha-20260818163953 + '@atproto-labs/fetch-node': 0.0.0-spaces-alpha-20261105160032 + '@atproto-labs/opentelemetry-node': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) + '@atproto/common': 0.0.0-spaces-alpha-20261105160032 + '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 + '@atproto/identity': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-password-session': 0.0.0 + '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 '@atproto/ws-client': 0.2.1 - '@atproto/xrpc': 0.0.0-spaces-alpha-20260818163953 - '@atproto/xrpc-server': 0.0.0-spaces-alpha-20260818163953(supports-color@10.2.2) + '@atproto/xrpc-server': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) '@did-plc/lib': 0.0.1(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) + '@opentelemetry/instrumentation-pg': 0.72.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) compression: 1.8.1(supports-color@10.2.2) cors: 2.8.6 + dotenv: 17.4.2 express: 4.22.2(supports-color@10.2.2) http-terminator: 3.2.0 kysely: 0.29.5 @@ -8003,71 +8046,64 @@ snapshots: p-queue: 8.1.1 pg: 8.23.0 pino-http: 11.0.0 + prom-client: 15.1.3 structured-headers: 1.0.1 uint8arrays: 5.1.1 undici: 8.10.0 ws: 8.20.1 transitivePeerDependencies: + - '@opentelemetry/api' - bufferutil - debug - pg-native - supports-color - utf-8-validate - '@atproto/pds@0.0.0-spaces-alpha-20260818163953(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2)': + '@atproto/pds@0.0.0-spaces-alpha-20261105160032(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: '@atproto-labs/fetch': 0.3.5 - '@atproto-labs/fetch-node': 0.3.7 + '@atproto-labs/fetch-node': 0.0.0-spaces-alpha-20261105160032 + '@atproto-labs/opentelemetry-node': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) '@atproto-labs/simple-store': 0.5.1 '@atproto-labs/simple-store-memory': 0.2.6 '@atproto-labs/simple-store-redis': 0.1.6(ioredis@5.11.1(supports-color@10.2.2)) - '@atproto-labs/xrpc-utils': 0.0.0-spaces-alpha-20260818163953(supports-color@10.2.2) - '@atproto/aws': 0.0.0-spaces-alpha-20260818163953 - '@atproto/common': 0.0.0-spaces-alpha-20260818163953 - '@atproto/crypto': 0.0.0-spaces-alpha-20260818163953 - '@atproto/did': 0.5.4 - '@atproto/identity': 0.0.0-spaces-alpha-20260818163953 + '@atproto-labs/xrpc-utils': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) + '@atproto/aws': 0.0.0-spaces-alpha-20261105160032 + '@atproto/common': 0.0.0-spaces-alpha-20261105160032 + '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 + '@atproto/did': 0.0.0-spaces-alpha-20261105160032 + '@atproto/identity': 0.0.0-spaces-alpha-20261105160032 '@atproto/jwk': 0.7.4 - '@atproto/lex': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-cbor': 0.1.6 - '@atproto/lex-data': 0.1.7 - '@atproto/lex-json': 0.1.6 - '@atproto/oauth-provider': 0.0.0-spaces-alpha-20260818163953(supports-color@10.2.2) - '@atproto/oauth-scopes': 0.0.0-spaces-alpha-20260818163953 - '@atproto/oauth-types': 0.7.5 - '@atproto/repo': 0.0.0-spaces-alpha-20260818163953 - '@atproto/space': 0.0.0-spaces-alpha-20260818163953 - '@atproto/syntax': 0.0.0-spaces-alpha-20260818163953 - '@atproto/xrpc-server': 0.0.0-spaces-alpha-20260818163953(supports-color@10.2.2) + '@atproto/lex': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-json': 0.0.0-spaces-alpha-20261105160032 + '@atproto/oauth-provider': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) + '@atproto/oauth-scopes': 0.0.0-spaces-alpha-20261105160032 + '@atproto/oauth-types': 0.0.0-spaces-alpha-20261105160032 + '@atproto/repo': 0.0.0-spaces-alpha-20261105160032 + '@atproto/space': 0.0.0-spaces-alpha-20261105160032 + '@atproto/star': 0.0.0-spaces-alpha-20261105160032 + '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 + '@atproto/xrpc-server': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) '@did-plc/lib': 0.0.4(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) '@hapi/address': 5.1.1 + '@noble/curves': 1.9.7 '@opentelemetry/api': 1.9.1 '@opentelemetry/api-logs': 0.219.0 - '@opentelemetry/auto-instrumentations-node': 0.77.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.10.0(@opentelemetry/api@1.9.1))(supports-color@10.2.2) - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/instrumentation-aws-sdk': 0.74.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-express': 0.67.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-http': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) '@opentelemetry/instrumentation-ioredis': 0.67.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-pino': 0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-runtime-node': 0.32.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-undici': 0.29.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/resource-detector-container': 0.8.12(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-node': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/semantic-conventions': 1.43.0 better-sqlite3: 12.11.1 compression: 1.8.1(supports-color@10.2.2) cors: 2.8.6 disposable-email-domains-js: 1.25.0 express: 4.22.2(supports-color@10.2.2) express-async-errors: 3.1.1(express@4.22.2(supports-color@10.2.2)) - file-type: 16.5.4 + file-type: 22.3.0(supports-color@10.2.2) handlebars: 4.7.9 http-terminator: 3.2.0 ioredis: 5.11.1(supports-color@10.2.2) jose: 5.10.0 - key-encoder: 2.0.3 kysely: 0.29.5 nodemailer: 6.10.1 nodemailer-html-to-text: 3.2.0 @@ -8075,6 +8111,7 @@ snapshots: p-queue: 8.1.1 pino: 10.3.1 pino-http: 11.0.0 + strtok3: 10.7.0 uint8arrays: 5.1.1 undici: 8.10.0 zod: 3.25.76 @@ -8084,14 +8121,15 @@ snapshots: - supports-color - utf-8-validate - '@atproto/repo@0.0.0-spaces-alpha-20260818163953': + '@atproto/repo@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto/common': 0.0.0-spaces-alpha-20260818163953 - '@atproto/common-web': 0.0.0-spaces-alpha-20260818163953 - '@atproto/crypto': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-cbor': 0.1.6 - '@atproto/lex-data': 0.1.7 - '@atproto/syntax': 0.0.0-spaces-alpha-20260818163953 + '@atproto/car': 0.0.0-spaces-alpha-20261105160032 + '@atproto/common': 0.0.0-spaces-alpha-20261105160032 + '@atproto/common-web': 0.0.0-spaces-alpha-20261105160032 + '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 + '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 zod: 3.25.76 '@atproto/repo@0.8.12': @@ -8106,25 +8144,30 @@ snapshots: varint: 6.0.0 zod: 3.25.76 - '@atproto/space@0.0.0-spaces-alpha-20260818163953': + '@atproto/space@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto/common': 0.0.0-spaces-alpha-20260818163953 - '@atproto/crypto': 0.0.0-spaces-alpha-20260818163953 - '@atproto/jwk': 0.7.4 - '@atproto/lex-cbor': 0.1.6 - '@atproto/lex-data': 0.1.7 + '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 + '@atproto/star': 0.0.0-spaces-alpha-20261105160032 + '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 '@noble/hashes': 1.8.0 - jose: 5.10.0 + structured-headers: 1.0.1 zod: 3.25.76 - '@atproto/sync@0.0.0-spaces-alpha-20260818163953(supports-color@10.2.2)': + '@atproto/star@0.0.0-spaces-alpha-20261105160032': + dependencies: + '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 + + '@atproto/sync@0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2)': dependencies: - '@atproto/common': 0.0.0-spaces-alpha-20260818163953 - '@atproto/identity': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex': 0.0.0-spaces-alpha-20260818163953 - '@atproto/repo': 0.0.0-spaces-alpha-20260818163953 - '@atproto/syntax': 0.0.0-spaces-alpha-20260818163953 - '@atproto/xrpc-server': 0.0.0-spaces-alpha-20260818163953(supports-color@10.2.2) + '@atproto/common': 0.0.0-spaces-alpha-20261105160032 + '@atproto/identity': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex': 0.0.0-spaces-alpha-20261105160032 + '@atproto/repo': 0.0.0-spaces-alpha-20261105160032 + '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 + '@atproto/xrpc-server': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) p-queue: 8.1.1 ws: 8.20.1 transitivePeerDependencies: @@ -8132,7 +8175,7 @@ snapshots: - supports-color - utf-8-validate - '@atproto/syntax@0.0.0-spaces-alpha-20260818163953': + '@atproto/syntax@0.0.0-spaces-alpha-20261105160032': dependencies: iso-datestring-validator: 2.2.2 tslib: 2.8.1 @@ -8154,18 +8197,18 @@ snapshots: - bufferutil - utf-8-validate - '@atproto/xrpc-server@0.0.0-spaces-alpha-20260818163953(supports-color@10.2.2)': + '@atproto/xrpc-server@0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2)': dependencies: - '@atproto/common': 0.0.0-spaces-alpha-20260818163953 - '@atproto/crypto': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-cbor': 0.1.6 - '@atproto/lex-client': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lex-data': 0.1.7 - '@atproto/lex-json': 0.1.6 - '@atproto/lex-schema': 0.0.0-spaces-alpha-20260818163953 - '@atproto/lexicon': 0.0.0-spaces-alpha-20260818163953 + '@atproto/common': 0.0.0-spaces-alpha-20261105160032 + '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-client': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-json': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lexicon': 0.0.0-spaces-alpha-20261105160032 '@atproto/ws-client': 0.2.1 - '@atproto/xrpc': 0.0.0-spaces-alpha-20260818163953 + '@atproto/xrpc': 0.0.0-spaces-alpha-20261105160032 express: 4.22.2(supports-color@10.2.2) http-errors: 2.0.1 mime-types: 3.0.2 @@ -8176,9 +8219,9 @@ snapshots: - supports-color - utf-8-validate - '@atproto/xrpc@0.0.0-spaces-alpha-20260818163953': + '@atproto/xrpc@0.0.0-spaces-alpha-20261105160032': dependencies: - '@atproto/lexicon': 0.0.0-spaces-alpha-20260818163953 + '@atproto/lexicon': 0.0.0-spaces-alpha-20261105160032 zod: 3.25.76 '@atproto/xrpc@0.7.7': @@ -8501,6 +8544,8 @@ snapshots: '@badrap/valita@0.4.6': {} + '@borewit/text-codec@0.2.3': {} + '@braidai/lang@1.1.2': {} '@bufbuild/protobuf@1.10.1': {} @@ -8806,7 +8851,7 @@ snapshots: dependencies: '@atproto/common': 0.1.0 '@atproto/crypto': 0.1.0 - '@did-plc/lib': 0.0.1(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) + '@did-plc/lib': 0.0.4(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) axios: 1.20.0(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) cors: 2.8.6 express: 4.22.2(supports-color@10.2.2) @@ -9415,6 +9460,10 @@ snapshots: dependencies: '@opentelemetry/api': 1.9.1 + '@opentelemetry/api-logs@0.220.0': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/api@1.9.1': {} '@opentelemetry/auto-instrumentations-node@0.77.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.10.0(@opentelemetry/api@1.9.1))(supports-color@10.2.2)': @@ -9873,6 +9922,18 @@ snapshots: transitivePeerDependencies: - supports-color + '@opentelemetry/instrumentation-pg@0.72.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) + '@opentelemetry/instrumentation': 0.220.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/semantic-conventions': 1.43.0 + '@opentelemetry/sql-common': 0.42.0(@opentelemetry/api@1.9.1) + '@types/pg': 8.15.6 + '@types/pg-pool': 2.0.7 + transitivePeerDependencies: + - supports-color + '@opentelemetry/instrumentation-pino@0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': dependencies: '@opentelemetry/api': 1.9.1 @@ -9968,6 +10029,15 @@ snapshots: transitivePeerDependencies: - supports-color + '@opentelemetry/instrumentation@0.220.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + dependencies: + '@opentelemetry/api': 1.9.1 + '@opentelemetry/api-logs': 0.220.0 + import-in-the-middle: 3.3.3 + require-in-the-middle: 8.0.1(supports-color@10.2.2) + transitivePeerDependencies: + - supports-color + '@opentelemetry/otlp-exporter-base@0.219.0(@opentelemetry/api@1.9.1)': dependencies: '@opentelemetry/api': 1.9.1 @@ -10755,6 +10825,14 @@ snapshots: tailwindcss: 4.3.0 vite: 8.0.14(@types/node@24.10.11)(esbuild@0.27.3)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0) + '@tokenizer/inflate@0.6.0(supports-color@10.2.2)': + dependencies: + debug: 4.4.3(supports-color@10.2.2) + strtok3: 10.7.0 + token-types: 6.2.0 + transitivePeerDependencies: + - supports-color + '@tokenizer/token@0.3.0': {} '@ts-morph/common@0.28.1': @@ -10791,10 +10869,6 @@ snapshots: dependencies: '@babel/types': 7.29.0 - '@types/bn.js@5.2.0': - dependencies: - '@types/node': 24.10.11 - '@types/bun@1.3.8': dependencies: bun-types: 1.3.8 @@ -10818,10 +10892,6 @@ snapshots: '@types/deep-eql@4.0.2': {} - '@types/elliptic@6.4.18': - dependencies: - '@types/bn.js': 5.2.0 - '@types/estree-jsx@1.0.5': dependencies: '@types/estree': 1.0.8 @@ -11017,13 +11087,6 @@ snapshots: array-iterate@2.0.1: {} - asn1.js@5.4.1: - dependencies: - bn.js: 4.12.5 - inherits: 2.0.4 - minimalistic-assert: 1.0.1 - safer-buffer: 2.1.2 - asn1js@3.0.7: dependencies: pvtsutils: 1.3.6 @@ -11206,6 +11269,8 @@ snapshots: dependencies: file-uri-to-path: 1.0.0 + bintrees@1.0.2: {} + birpc@4.0.0: {} bl@4.1.0: @@ -11216,8 +11281,6 @@ snapshots: blake3-wasm@2.1.5: {} - bn.js@4.12.5: {} - body-parser@1.20.6(supports-color@10.2.2): dependencies: bytes: 3.1.2 @@ -11251,8 +11314,6 @@ snapshots: dependencies: fill-range: 7.1.1 - brorand@1.1.0: {} - browserslist@4.28.2: dependencies: baseline-browser-mapping: 2.10.32 @@ -11472,6 +11533,8 @@ snapshots: core-js@3.49.0: {} + core-js@3.51.0: {} + cors@2.8.6: dependencies: object-assign: 4.1.1 @@ -11619,7 +11682,7 @@ snapshots: domelementtype: 2.3.0 domhandler: 5.0.3 - dotenv@16.6.1: {} + dotenv@17.4.2: {} dset@3.1.4: {} @@ -11639,16 +11702,6 @@ snapshots: electron-to-chromium@1.5.361: {} - elliptic@6.6.1: - dependencies: - bn.js: 4.12.5 - brorand: 1.1.0 - hash.js: 1.1.7 - hmac-drbg: 1.0.1 - inherits: 2.0.4 - minimalistic-assert: 1.0.1 - minimalistic-crypto-utils: 1.0.1 - emoji-regex@10.6.0: {} emoji-regex@8.0.0: {} @@ -11929,11 +11982,14 @@ snapshots: fflate@0.8.2: {} - file-type@16.5.4: + file-type@22.3.0(supports-color@10.2.2): dependencies: - readable-web-to-node-stream: 3.0.4 - strtok3: 6.3.0 - token-types: 4.2.1 + '@tokenizer/inflate': 0.6.0(supports-color@10.2.2) + strtok3: 10.7.0 + token-types: 6.2.0 + uint8array-extras: 1.6.0 + transitivePeerDependencies: + - supports-color file-uri-to-path@1.0.0: {} @@ -12114,11 +12170,6 @@ snapshots: dependencies: has-symbols: 1.1.0 - hash.js@1.1.7: - dependencies: - inherits: 2.0.4 - minimalistic-assert: 1.0.1 - hasown@2.0.4: dependencies: function-bind: 1.1.2 @@ -12318,12 +12369,6 @@ snapshots: hls.js@1.6.16: {} - hmac-drbg@1.0.1: - dependencies: - hash.js: 1.1.7 - minimalistic-assert: 1.0.1 - minimalistic-crypto-utils: 1.0.1 - hono@4.11.8: {} hookable@6.0.1: {} @@ -12509,13 +12554,6 @@ snapshots: jsonc-parser@3.3.1: {} - key-encoder@2.0.3: - dependencies: - '@types/elliptic': 6.4.18 - asn1.js: 5.4.1 - bn.js: 4.12.5 - elliptic: 6.6.1 - kleur@4.1.5: {} klona@2.0.6: {} @@ -13176,10 +13214,6 @@ snapshots: - bufferutil - utf-8-validate - minimalistic-assert@1.0.1: {} - - minimalistic-crypto-utils@1.0.1: {} - minimatch@10.2.6: dependencies: brace-expansion: 5.0.9 @@ -13460,8 +13494,6 @@ snapshots: pathe@2.0.3: {} - peek-readable@4.1.0: {} - pg-cloudflare@1.4.0: optional: true @@ -13631,6 +13663,11 @@ snapshots: process@0.11.10: {} + prom-client@15.1.3: + dependencies: + '@opentelemetry/api': 1.9.1 + tdigest: 0.1.3 + property-information@7.1.0: {} protobufjs@7.6.6: @@ -13725,10 +13762,6 @@ snapshots: process: 0.11.10 string_decoder: 1.3.0 - readable-web-to-node-stream@3.0.4: - dependencies: - readable-stream: 4.7.0 - readdirp@5.0.0: {} real-require@0.2.0: {} @@ -14348,10 +14381,9 @@ snapshots: strip-json-comments@5.0.3: {} - strtok3@6.3.0: + strtok3@10.7.0: dependencies: '@tokenizer/token': 0.3.0 - peek-readable: 4.1.0 structured-headers@1.0.1: {} @@ -14405,6 +14437,10 @@ snapshots: inherits: 2.0.4 readable-stream: 3.6.2 + tdigest@0.1.3: + dependencies: + bintrees: 1.0.2 + thenify-all@1.6.0: dependencies: thenify: 3.3.1 @@ -14455,8 +14491,9 @@ snapshots: toidentifier@1.0.1: {} - token-types@4.2.1: + token-types@6.2.0: dependencies: + '@borewit/text-codec': 0.2.3 '@tokenizer/token': 0.3.0 ieee754: 1.2.1 @@ -14543,6 +14580,8 @@ snapshots: uglify-js@3.19.3: optional: true + uint8array-extras@1.6.0: {} + uint8arrays@3.0.0: dependencies: multiformats: 9.9.0 diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 6b173db..8415e87 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -17,29 +17,35 @@ allowBuilds: sharp: false workerd: false -# @atproto/dev-env (the reference PDS harness the conformance matrix runs -# against) transitively pulls the @atproto/lex* family. Each of those was -# published twice in the spaces alpha: once as a broken bare `0.0.0` whose -# manifest still carries unresolved `workspace:*` sibling specifiers (so it -# cannot install outside the atproto monorepo), and once as a clean -# `0.0.0-spaces-alpha-*` build. The dependency ranges are `^0.0.0-spaces-alpha-*`, -# and by semver a bare `0.0.0` release outranks any `-prerelease`, so pnpm picks -# the broken one. Pin the whole family to the clean timestamp build. Nothing -# else in this repo uses these packages, so a global override is safe. +# The spaces alpha published the @atproto/lex* family twice: once as a broken +# bare `0.0.0` whose manifest still carries unresolved `workspace:*` sibling +# specifiers (so it cannot install outside the atproto monorepo), and once as a +# clean `0.0.0-spaces-alpha-*` build. @atproto/star likewise has a corrupt +# `0.0.0-stage` tarball. Alpha dependency ranges are `^0.0.0-spaces-alpha-*`, +# and by semver both a bare `0.0.0` and `0.0.0-stage` outrank that prerelease, +# so pnpm picks the broken build. @atproto/space and @atproto/dev-env (the +# reference PDS harness the conformance matrix runs against) both reach these. # -# Overrides don't reach consumers of the published packages, so @getcirrus/pds, -# @getcirrus/spaces and @getcirrus/space-conformance instead list the -# intermediate alpha packages (@atproto/common, common-web, and for the -# conformance suite oauth-client, xrpc, lexicon) as exact dependencies, which -# package managers reuse when resolving @atproto/space's caret ranges. Bump -# those pins in lockstep with @atproto/space. +# Pin the family to the clean timestamp build. lex-cbor, lex-data and lex-json +# are also stable dependencies of @getcirrus/pds (^0.0.x for @atproto/repo +# interop), so those overrides only apply to edges asking for the alpha range. +# +# Overrides don't reach consumers of the published packages, so +# @getcirrus/spaces and @getcirrus/space-conformance keep every alpha +# @atproto package in devDependencies, where tsdown bundles it into dist. +# Consumers never resolve an alpha range. Bump these in lockstep with +# @atproto/space. overrides: - "@atproto/lex": "0.0.0-spaces-alpha-20260818163953" - "@atproto/lex-resolver": "0.0.0-spaces-alpha-20260818163953" - "@atproto/lex-client": "0.0.0-spaces-alpha-20260818163953" - "@atproto/lex-schema": "0.0.0-spaces-alpha-20260818163953" - "@atproto/lex-builder": "0.0.0-spaces-alpha-20260818163953" - "@atproto/lex-installer": "0.0.0-spaces-alpha-20260818163953" - "@atproto/lex-document": "0.0.0-spaces-alpha-20260818163953" + "@atproto/lex": "0.0.0-spaces-alpha-20261105160032" + "@atproto/lex-resolver": "0.0.0-spaces-alpha-20261105160032" + "@atproto/lex-client": "0.0.0-spaces-alpha-20261105160032" + "@atproto/lex-schema": "0.0.0-spaces-alpha-20261105160032" + "@atproto/lex-builder": "0.0.0-spaces-alpha-20261105160032" + "@atproto/lex-installer": "0.0.0-spaces-alpha-20261105160032" + "@atproto/lex-document": "0.0.0-spaces-alpha-20261105160032" + "@atproto/lex-cbor@^0.0.0-spaces-alpha": "0.0.0-spaces-alpha-20261105160032" + "@atproto/lex-data@^0.0.0-spaces-alpha": "0.0.0-spaces-alpha-20261105160032" + "@atproto/lex-json@^0.0.0-spaces-alpha": "0.0.0-spaces-alpha-20261105160032" + "@atproto/star": "0.0.0-spaces-alpha-20261105160032" linkWorkspacePackages: true From c73d1523eed4dcc10078fc54c88a169f74717031 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 08:50:31 +0000 Subject: [PATCH 02/16] feat(spaces): implement the 2026-11-05 spaces alpha protocol Rewrites the spaces engine and its PDS integration for the upstream alpha cut from permissioned-data-alpha@704b9e2: - Space credentials bind to a P-256 did:key and are presented with the Atproto-Space-Credential scheme, an Atproto-Space-Audience header and an HTTP message signature over both. DPoP is gone. Credentials are checked against the audience, their space and revocations received through notifyCredentialRevoked. - getSpaceCredential takes credentialKid, delegationToken and clientAttestation in the body, issues public-read credentials without a delegation token, and answers a refused user as SpaceNotFound. - Commits carry no signature: {ver, repo, space, rev, data}. Reads that return a commit or record are authenticated with a MAC derived by ECDH against the account's new #atproto_kem key (BadSpaceMac when a credential doesn't ask for one). - getRepo streams a STAR archive in record-path byte order, fencing against concurrent writes instead of buffering the whole repo. - simplespace is replaced by personalspace, memberspace (per-member read/write, public read/write, allowed apps) and managedspace policies under com.atproto.space.{create,update,delete,get}Space and com.atproto.memberspace.*, with optional published policy and member records in the authority's repo. - Writers are sequenced by space revision (listRepos cursor, spaceRev and prevSpaceRev in forwarded notifyWrites, FutureRev), and a repo host retries its notifyWrite to a foreign authority for 24 hours, coalesced to the newest revision. - New: clearRecords, removeWriter, importRepo, exportSpaceMeta and importSpaceMeta. Imported records' blobs are promoted when uploaded. - The DID document drops #atproto_space_host and publishes #atproto_kem; getRecommendedDidCredentials carries it through a migration. 'pds spaces kem' creates the key and, for did:plc, can publish it via the PDS's own PLC signing. The space DO schema version is bumped: existing space data refuses until 'pds spaces reset', per the alpha policy. @atproto/space and its alpha dependencies are bundled into @getcirrus/spaces, whose public types no longer reference any @atproto package. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LZ7qcQNQoiA6a23woGC7tB --- demos/pds/wrangler.jsonc | 2 + .../templates/pds-worker/wrangler.jsonc | 8 +- packages/oauth-provider/src/ui.ts | 2 +- packages/pds/package.json | 5 +- packages/pds/src/cli/commands/spaces.ts | 378 +++- packages/pds/src/cli/utils/secrets.ts | 30 +- packages/pds/src/cli/utils/wrangler.ts | 4 +- packages/pds/src/dashboard.html | 24 +- packages/pds/src/index.ts | 26 +- packages/pds/src/spaces.ts | 96 +- packages/pds/src/types.ts | 10 + packages/pds/src/xrpc/identity.ts | 35 +- packages/pds/src/xrpc/repo.ts | 4 + packages/pds/test/cli/key.test.ts | 35 +- packages/pds/test/identity.test.ts | 9 +- packages/pds/test/spaces.test.ts | 212 +- packages/pds/vitest.config.ts | 4 + packages/spaces/src/attestation.ts | 6 +- packages/spaces/src/auth.ts | 252 ++- packages/spaces/src/blob-keys.ts | 38 + packages/spaces/src/commit.ts | 55 - packages/spaces/src/errors.ts | 40 +- packages/spaces/src/index-do.ts | 44 +- packages/spaces/src/index.ts | 44 +- packages/spaces/src/mac.ts | 186 ++ packages/spaces/src/policy.ts | 161 ++ packages/spaces/src/routes.ts | 1731 +++++++++------ packages/spaces/src/schema.ts | 72 +- packages/spaces/src/service-jwt.ts | 4 +- packages/spaces/src/space-do.ts | 1144 +++++++--- packages/spaces/src/space-uri.ts | 7 +- packages/spaces/src/tid.ts | 11 + packages/spaces/src/tokens.ts | 40 + packages/spaces/src/types.ts | 90 +- .../test/fixtures/spaces-worker/index.ts | 4 + packages/spaces/test/index-do.test.ts | 14 + packages/spaces/test/routes.test.ts | 1976 +++++++++-------- packages/spaces/test/space-do.test.ts | 352 ++- packages/spaces/tsconfig.json | 12 +- packages/spaces/tsdown.config.ts | 5 + pnpm-lock.yaml | 3 + 41 files changed, 4635 insertions(+), 2540 deletions(-) delete mode 100644 packages/spaces/src/commit.ts create mode 100644 packages/spaces/src/mac.ts create mode 100644 packages/spaces/src/policy.ts create mode 100644 packages/spaces/src/tokens.ts diff --git a/demos/pds/wrangler.jsonc b/demos/pds/wrangler.jsonc index e66c5d6..f07c775 100644 --- a/demos/pds/wrangler.jsonc +++ b/demos/pds/wrangler.jsonc @@ -58,6 +58,7 @@ "HANDLE": "pds.mk.gg", // Atproto spaces (ALPHA). Breaking upstream changes are absorbed by // `pds spaces reset`, which wipes space data and nothing else. + // `pds spaces kem` sets SPACES_KEM_KEY and SPACES_KEM_KEY_PUBLIC. "SPACES_ENABLED": "true" }, // Secrets (set via `pds init` or `pds secret `): @@ -65,6 +66,7 @@ // - SIGNING_KEY: Private signing key (secp256k1 JWK) // - JWT_SECRET: Secret for signing session JWTs // - PASSWORD_HASH: Bcrypt hash of account password (for Bluesky app login) + // - SPACES_KEM_KEY: Spaces #atproto_kem private key (`pds spaces kem`) "observability": { "enabled": true } diff --git a/packages/create-pds/templates/pds-worker/wrangler.jsonc b/packages/create-pds/templates/pds-worker/wrangler.jsonc index 6e190d9..2de9425 100644 --- a/packages/create-pds/templates/pds-worker/wrangler.jsonc +++ b/packages/create-pds/templates/pds-worker/wrangler.jsonc @@ -65,9 +65,10 @@ // ⚠️ Changing this value after your PDS is live will break your installation. "DATA_LOCATION": "" // Atproto spaces (ALPHA). Set to "true" to enable the space and - // simplespace endpoints. Everything is alpha: a breaking upstream - // change is absorbed by `pds spaces reset`, which wipes space data - // and nothing else. + // memberspace endpoints, then run `pds spaces kem` to create the + // #atproto_kem key syncers verify space data against. Everything is + // alpha: a breaking upstream change is absorbed by `pds spaces reset`, + // which wipes space data and nothing else. // "SPACES_ENABLED": "true" }, // Secrets (set via `pds init` or `pds secret `): @@ -75,6 +76,7 @@ // - SIGNING_KEY: Private signing key (secp256k1 JWK) // - JWT_SECRET: Secret for signing session JWTs // - PASSWORD_HASH: Bcrypt hash of account password (for Bluesky app login) + // - SPACES_KEM_KEY: Spaces #atproto_kem private key (`pds spaces kem`) "observability": { "enabled": true } diff --git a/packages/oauth-provider/src/ui.ts b/packages/oauth-provider/src/ui.ts index f9ef6f9..43d7d34 100644 --- a/packages/oauth-provider/src/ui.ts +++ b/packages/oauth-provider/src/ui.ts @@ -324,7 +324,7 @@ function describeSpaceScope( } out.push(line); - if (p.manage.length > 0) { + if (p.manage && p.manage.length > 0) { const ops = p.manage.join(", "); out.push( `Manage (${ops}) ${authorityLabel} ${typeLabel}, including membership`, diff --git a/packages/pds/package.json b/packages/pds/package.json index ef0d4f3..2ed1f8c 100644 --- a/packages/pds/package.json +++ b/packages/pds/package.json @@ -50,9 +50,11 @@ "devDependencies": { "@arethetypeswrong/cli": "^0.18.2", "@atproto/api": "^0.18.9", + "@atproto/space": "0.0.0-spaces-alpha-20261105160032", "@cloudflare/vite-plugin": "^1.17.0", "@cloudflare/vitest-pool-workers": "^0.16.9", "@cloudflare/workers-types": "^4.20260524.1", + "@getcirrus/space-conformance": "workspace:*", "@ipld/car": "^5.4.2", "@types/qrcode": "^1.5.6", "@types/ws": "^8.18.1", @@ -63,8 +65,7 @@ "vite": "^6.4.1", "vitest": "4.1.0-beta.1", "wrangler": "^4.93.0", - "ws": "^8.18.3", - "@getcirrus/space-conformance": "workspace:*" + "ws": "^8.18.3" }, "repository": { "type": "git", diff --git a/packages/pds/src/cli/commands/spaces.ts b/packages/pds/src/cli/commands/spaces.ts index 3ec5c33..ca65c6d 100644 --- a/packages/pds/src/cli/commands/spaces.ts +++ b/packages/pds/src/cli/commands/spaces.ts @@ -13,6 +13,13 @@ import pc from "picocolors"; import { getVars } from "../utils/wrangler.js"; import { readDevVars } from "../utils/dotenv.js"; import { getTargetUrl } from "../utils/cli-helpers.js"; +import { + generateKemKeypair, + setPublicVar, + setSecretValue, +} from "../utils/secrets.js"; +import { PlcDirectoryClient } from "../utils/plc-client.js"; +import { DidResolver } from "../../did-resolver.js"; interface SpacesContext { baseUrl: string; @@ -78,7 +85,8 @@ async function xrpc( } throw new Error(`${nsid} failed (${res.status}): ${message}`); } - return (await res.json()) as T; + const text = await res.text(); + return (text ? JSON.parse(text) : {}) as T; } interface SpaceStatusEntry { @@ -86,6 +94,7 @@ interface SpaceStatusEntry { role: string; state: string; outdated: boolean; + policy: string | null; recordCount: number; memberCount: number; writerCount: number; @@ -94,6 +103,7 @@ interface SpaceStatusEntry { interface SpacesStatus { enabled: boolean; schemaVersion: number; + kem?: { configured: boolean; didKey?: string }; stats: { total: number; active: number; @@ -129,6 +139,9 @@ const listCommand = defineCommand({ for (const space of status.spaces) { const flags = [ space.role, + space.policy + ? space.policy.replace(/^com\.atproto\.|\.policy$/g, "") + : null, space.state !== "active" ? pc.yellow(space.state) : null, space.outdated ? pc.red("outdated") : null, ] @@ -171,9 +184,63 @@ const statusCommand = defineCommand({ ), ); } + await reportKem(ctx, status.kem); }, }); +/** + * Check that the deployed `#atproto_kem` key is the one the DID document + * publishes: syncers derive MAC secrets against the published key, so a + * mismatch fails every credentialed read that returns a commit or record. + */ +async function reportKem( + ctx: SpacesContext, + kem: SpacesStatus["kem"], +): Promise { + if (!kem?.configured) { + console.log( + pc.yellow( + " kem key: not configured — syncers cannot verify space data. Run 'pds spaces kem'.", + ), + ); + return; + } + let published: string | undefined; + try { + const doc = await new DidResolver().resolve(ctx.did, { + forceRefresh: true, + }); + const method = ( + (doc?.verificationMethod ?? []) as Array<{ + id: string; + publicKeyMultibase?: string; + }> + ).find((m) => m.id.endsWith("#atproto_kem")); + published = method?.publicKeyMultibase + ? `did:key:${method.publicKeyMultibase}` + : undefined; + } catch { + // reported below as unpublished + } + if (!kem.didKey) { + console.log( + pc.yellow( + " kem key: secret set, but SPACES_KEM_KEY_PUBLIC is missing. Re-run 'pds spaces kem'.", + ), + ); + } else if (published === kem.didKey) { + console.log( + ` kem key: ${pc.green("published")} ${pc.dim(kem.didKey)}`, + ); + } else { + console.log( + pc.yellow( + ` kem key: ${published ? "DID document publishes a different key" : "not in the DID document"}. ${ctx.did.startsWith("did:plc:") ? "Run 'pds spaces kem --publish'." : "Redeploy so the DID document picks it up."}`, + ), + ); + } +} + const createCommand = defineCommand({ meta: { name: "create", description: "Create a hosted space" }, args: { @@ -189,50 +256,89 @@ const createCommand = defineCommand({ }, policy: { type: "string", - description: "User policy: public | member-list | managing-app", - default: "member-list", + description: "Policy: personal | member | managed", + default: "member", + }, + "public-read": { + type: "boolean", + description: + "member: anyone may read, with or without a delegation token", + default: false, + }, + "public-write": { + type: "boolean", + description: "member: track anyone's writes, not only members'", + default: false, }, "managing-app": { type: "string", - description: "Managing app service identifier (managing-app policy)", + description: "managed: the managing app's service identifier", }, allow: { type: "string", description: - "Allowed OAuth client ID (repeatable); sets the allowList app policy", + "member: allowed OAuth client ID (repeatable); only these apps may read", + }, + "publish-policy": { + type: "boolean", + description: "Publish the policy to readers as a record in your repo", + default: false, + }, + "publish-members": { + type: "boolean", + description: "member: publish the member list to readers", + default: false, }, }, async run({ args }) { const ctx = loadContext(args.dev); - const policyType = args.policy; - const policy = - policyType === "public" - ? { $type: "com.atproto.simplespace.defs#publicPolicy" } - : policyType === "managing-app" - ? { - $type: "com.atproto.simplespace.defs#managingAppPolicy", - managingApp: args["managing-app"], - } - : { $type: "com.atproto.simplespace.defs#memberListPolicy" }; const allowed = args.allow ? Array.isArray(args.allow) ? args.allow : [args.allow] - : []; - const appAccess = - allowed.length > 0 - ? { $type: "com.atproto.simplespace.defs#allowList", allowed } - : { $type: "com.atproto.simplespace.defs#open" }; + : undefined; + let policy: Record; + switch (args.policy) { + case "personal": + policy = { $type: "com.atproto.personalspace.policy" }; + break; + case "managed": + if (!args["managing-app"]) { + console.error(pc.red("Error:"), "--managing-app is required"); + process.exit(1); + } + policy = { + $type: "com.atproto.managedspace.policy", + managingApp: args["managing-app"], + publishPolicy: args["publish-policy"], + }; + break; + case "member": + policy = { + $type: "com.atproto.memberspace.policy", + publicRead: args["public-read"], + publicWrite: args["public-write"], + ...(allowed ? { allowedApps: allowed } : {}), + publishPolicy: args["publish-policy"], + publishMembers: args["publish-members"], + }; + break; + default: + console.error( + pc.red("Error:"), + `Unknown policy '${args.policy}' (personal | member | managed)`, + ); + process.exit(1); + } const result = await xrpc<{ uri: string }>( ctx, "POST", - "com.atproto.simplespace.createSpace", + "com.atproto.space.createSpace", { body: { - type: args.type, + spaceType: args.type, ...(args.skey ? { skey: args.skey } : {}), policy, - appAccess, }, }, ); @@ -264,7 +370,7 @@ const deleteCommand = defineCommand({ return; } } - await xrpc(ctx, "POST", "com.atproto.simplespace.deleteSpace", { + await xrpc(ctx, "POST", "com.atproto.space.deleteSpace", { body: { space: args.space }, }); console.log(pc.green("Deleted:"), args.space); @@ -275,18 +381,40 @@ const membersCommand = defineCommand({ meta: { name: "members", description: "Manage a hosted space's member list" }, subCommands: { add: defineCommand({ - meta: { name: "add", description: "Add a member" }, + meta: { + name: "add", + description: "Add a member, or replace their access", + }, args: { ...devArg, space: { type: "positional", description: "Space URI", required: true }, did: { type: "positional", description: "Member DID", required: true }, + read: { + type: "boolean", + description: "May read (use --no-read to deny)", + default: true, + }, + write: { + type: "boolean", + description: "Writes are tracked (use --no-write to deny)", + default: true, + }, }, async run({ args }) { const ctx = loadContext(Boolean(args.dev)); - await xrpc(ctx, "POST", "com.atproto.simplespace.addMember", { - body: { space: args.space, did: args.did }, + await xrpc(ctx, "POST", "com.atproto.memberspace.putMember", { + body: { + space: args.space, + did: args.did, + read: args.read, + write: args.write, + }, }); - console.log(pc.green("Added:"), args.did); + console.log( + pc.green("Added:"), + args.did, + pc.dim(`(read: ${args.read}, write: ${args.write})`), + ); }, }), remove: defineCommand({ @@ -298,7 +426,7 @@ const membersCommand = defineCommand({ }, async run({ args }) { const ctx = loadContext(Boolean(args.dev)); - await xrpc(ctx, "POST", "com.atproto.simplespace.removeMember", { + await xrpc(ctx, "POST", "com.atproto.memberspace.removeMember", { body: { space: args.space, did: args.did }, }); console.log(pc.green("Removed:"), args.did); @@ -312,18 +440,23 @@ const membersCommand = defineCommand({ }, async run({ args }) { const ctx = loadContext(Boolean(args.dev)); - const result = await xrpc<{ members: Array<{ did: string }> }>( - ctx, - "GET", - "com.atproto.simplespace.listMembers", - { params: { space: String(args.space), limit: "1000" } }, - ); + const result = await xrpc<{ + members: Array<{ did: string; read: boolean; write: boolean }>; + }>(ctx, "GET", "com.atproto.memberspace.listMembers", { + params: { space: String(args.space), limit: "1000" }, + }); if (result.members.length === 0) { console.log(pc.dim("No members.")); return; } for (const member of result.members) { - console.log(member.did); + const access = [ + member.read ? "read" : null, + member.write ? "write" : null, + ] + .filter(Boolean) + .join(", "); + console.log(`${member.did} ${pc.dim(`(${access || "no access"})`)}`); } }, }), @@ -333,7 +466,8 @@ const membersCommand = defineCommand({ const exportCommand = defineCommand({ meta: { name: "export", - description: "Export every space repo as a CAR file", + description: + "Export every space repo as a STAR archive, plus the host-side state of hosted spaces", }, args: { ...devArg, @@ -351,38 +485,177 @@ const exportCommand = defineCommand({ "gg.mk.experimental.getSpacesStatus", ); const exportable = status.spaces.filter( - (space) => - space.state === "active" && !space.outdated && space.recordCount > 0, + (space) => space.state === "active" && !space.outdated, ); if (exportable.length === 0) { console.log(pc.dim("Nothing to export.")); return; } mkdirSync(args.out, { recursive: true }); - for (const space of exportable) { - const url = new URL(`${ctx.baseUrl}/xrpc/com.atproto.space.getRepo`); - url.searchParams.set("space", space.uri); - url.searchParams.set("repo", ctx.did); + const download = async ( + nsid: string, + params: Record, + filename: string, + label: string, + ): Promise => { + const url = new URL(`${ctx.baseUrl}/xrpc/${nsid}`); + for (const [key, value] of Object.entries(params)) { + url.searchParams.set(key, value); + } const res = await fetch(url, { headers: { Authorization: `Bearer ${ctx.authToken}` }, }); if (!res.ok) { - console.log( - pc.red("✗"), - `${space.uri}: export failed (${res.status})`, - ); - continue; + console.log(pc.red("✗"), `${label}: export failed (${res.status})`); + return; } const bytes = new Uint8Array(await res.arrayBuffer()); - const filename = `${space.uri - .replace("at://", "") - .replace(/[^a-zA-Z0-9._-]+/g, "_")}.car`; writeFileSync(join(args.out, filename), bytes); console.log( pc.green("✓"), - `${space.uri} → ${filename} (${bytes.length} bytes)`, + `${label} → ${filename} (${bytes.length} bytes)`, + ); + }; + for (const space of exportable) { + const base = space.uri + .replace("at://", "") + .replace(/[^a-zA-Z0-9._-]+/g, "_"); + // The space meta archive first: importSpaceMeta must precede + // importRepo for a space you are the authority of. + if (space.role === "authority") { + await download( + "com.atproto.space.exportSpaceMeta", + { space: space.uri }, + `${base}.meta.star`, + `${space.uri} (space)`, + ); + } + if (space.recordCount > 0) { + await download( + "com.atproto.space.getRepo", + { space: space.uri, repo: ctx.did }, + `${base}.star`, + `${space.uri} (repo)`, + ); + } + } + }, +}); + +const kemCommand = defineCommand({ + meta: { + name: "kem", + description: + "Generate the #atproto_kem key syncers verify space data against, and publish it", + }, + args: { + ...devArg, + local: { + type: "boolean", + description: "Write to .dev.vars instead of wrangler secrets/config", + default: false, + }, + publish: { + type: "boolean", + description: + "did:plc: add the key to your DID document via a PLC operation signed by this PDS", + default: false, + }, + }, + async run({ args }) { + p.intro("Spaces KEM key"); + const config = { ...readDevVars(), ...getVars() }; + const did = config.DID; + if (!did) { + p.log.error("No DID configured. Run 'pds init' first."); + process.exit(1); + } + + let publicKey = config.SPACES_KEM_KEY_PUBLIC; + if (publicKey && !args.publish) { + const replace = await p.confirm({ + message: + "A KEM key is already configured. Replace it? Syncers holding the old key will fail to verify until the DID document is updated.", + initialValue: false, + }); + if (p.isCancel(replace) || !replace) { + p.cancel("Kept the existing key."); + return; + } + } + if (!publicKey || !args.publish) { + const keypair = await generateKemKeypair(); + await setSecretValue("SPACES_KEM_KEY", keypair.privateKey, args.local); + setPublicVar("SPACES_KEM_KEY_PUBLIC", keypair.publicKey, args.local); + publicKey = keypair.publicKey; + p.log.success(`Generated did:key:${publicKey}`); + } + const didKey = `did:key:${publicKey}`; + + if (did.startsWith("did:web:")) { + p.outro( + "did:web: the DID document is served by your PDS, so it publishes #atproto_kem once you redeploy.", + ); + return; + } + if (!args.publish) { + p.note( + [ + "Your DID is a did:plc, so the key must be added to its PLC document", + "as the `atproto_kem` verification method. Redeploy, then run:", + "", + " pds spaces kem --publish", + "", + "That asks your PDS to sign the PLC operation, which works when its", + "signing key is one of your DID's rotation keys (true after migrating", + "with Cirrus). Otherwise, add it with whoever holds your rotation key.", + ].join("\n"), + "Publish the key", + ); + p.outro("Done."); + return; + } + + const ctx = loadContext(args.dev); + const spinner = p.spinner(); + spinner.start("Fetching the current PLC operation..."); + const log = await new PlcDirectoryClient().getAuditLog(did); + const current = log.filter((entry) => !entry.nullified).pop(); + if (!current) { + spinner.stop("Could not read the PLC audit log"); + process.exit(1); + } + const verificationMethods = { + ...current.operation.verificationMethods, + atproto_kem: didKey, + }; + spinner.message("Signing the PLC operation..."); + const { token } = await xrpc<{ token: string }>( + ctx, + "GET", + "gg.mk.experimental.getMigrationToken", + ); + const { operation } = await xrpc<{ operation: unknown }>( + ctx, + "POST", + "com.atproto.identity.signPlcOperation", + { body: { token, verificationMethods } }, + ); + spinner.message("Submitting to the PLC directory..."); + try { + await xrpc(ctx, "POST", "com.atproto.identity.submitPlcOperation", { + body: { operation }, + }); + } catch (err) { + spinner.stop("The PLC directory refused the operation"); + p.log.error(err instanceof Error ? err.message : String(err)); + p.log.info( + "This PDS's signing key is probably not a rotation key for your DID. Add the atproto_kem verification method with whoever holds it.", ); + process.exit(1); } + spinner.stop("Published #atproto_kem"); + p.outro(didKey); }, }); @@ -454,6 +727,7 @@ export const spacesCommand = defineCommand({ delete: deleteCommand, members: membersCommand, export: exportCommand, + kem: kemCommand, reset: resetCommand, }, }); diff --git a/packages/pds/src/cli/utils/secrets.ts b/packages/pds/src/cli/utils/secrets.ts index e7dc087..227a694 100644 --- a/packages/pds/src/cli/utils/secrets.ts +++ b/packages/pds/src/cli/utils/secrets.ts @@ -2,7 +2,7 @@ * Secret generation and management utilities for PDS CLI */ import { randomBytes } from "node:crypto"; -import { Secp256k1Keypair } from "@atproto/crypto"; +import { P256Keypair, Secp256k1Keypair } from "@atproto/crypto"; import bcrypt from "bcryptjs"; import * as p from "@clack/prompts"; import { setSecret, setVar, type SecretName } from "./wrangler.js"; @@ -30,6 +30,18 @@ export async function generateSigningKeypair(): Promise { }; } +/** + * Generate a P-256 keypair for the spaces `#atproto_kem` verification + * method, which MACs space data for syncers. + */ +export async function generateKemKeypair(): Promise { + const keypair = await P256Keypair.create({ exportable: true }); + return { + privateKey: Buffer.from(await keypair.export()).toString("hex"), + publicKey: keypair.did().replace("did:key:", ""), + }; +} + /** * Derive public key from an existing private key */ @@ -72,9 +84,7 @@ function generatePassword(): string { */ export async function promptPassword(handle?: string): Promise { const method = await promptSelect<"manual" | "generate">({ - message: handle - ? `Set a password for @${handle}:` - : "Set a password:", + message: handle ? `Set a password for @${handle}:` : "Set a password:", options: [ { value: "manual", label: "Choose a password" }, { value: "generate", label: "Generate one automatically" }, @@ -101,7 +111,11 @@ export async function promptPassword(handle?: string): Promise { } saveOptions.push( - { value: "clipboard", label: "Copy to clipboard", hint: "paste into password manager" }, + { + value: "clipboard", + label: "Copy to clipboard", + hint: "paste into password manager", + }, { value: "show", label: "Display it", hint: "shown in terminal" }, ); @@ -135,7 +149,9 @@ export async function promptPassword(handle?: string): Promise { p.log.success("Password generated and copied to clipboard"); } else { p.note(password, "Generated password"); - p.log.warn("Could not copy to clipboard — save this password somewhere safe!"); + p.log.warn( + "Could not copy to clipboard — save this password somewhere safe!", + ); } } else { p.note(password, "Generated password"); @@ -202,7 +218,7 @@ export async function setSecretValue( * Set a public var in wrangler.jsonc */ export function setPublicVar( - name: "SIGNING_KEY_PUBLIC", + name: "SIGNING_KEY_PUBLIC" | "SPACES_KEM_KEY_PUBLIC", value: string, local: boolean, ): void { diff --git a/packages/pds/src/cli/utils/wrangler.ts b/packages/pds/src/cli/utils/wrangler.ts index 6f99512..f5e31cc 100644 --- a/packages/pds/src/cli/utils/wrangler.ts +++ b/packages/pds/src/cli/utils/wrangler.ts @@ -11,13 +11,15 @@ export type VarName = | "DID" | "HANDLE" | "SIGNING_KEY_PUBLIC" + | "SPACES_KEM_KEY_PUBLIC" | "INITIAL_ACTIVE" | "DATA_LOCATION"; export type SecretName = | "AUTH_TOKEN" | "SIGNING_KEY" | "JWT_SECRET" - | "PASSWORD_HASH"; + | "PASSWORD_HASH" + | "SPACES_KEM_KEY"; export interface WranglerResult { stdout: string; diff --git a/packages/pds/src/dashboard.html b/packages/pds/src/dashboard.html index d7a17fb..bf3deba 100644 --- a/packages/pds/src/dashboard.html +++ b/packages/pds/src/dashboard.html @@ -839,7 +839,11 @@

EVENTS

for (const space of status.spaces) { const row = el("div", "space-row"); row.append(el("span", "space-uri", space.uri)); - const flags = [space.role, space.state] + const policy = space.policy + ? space.policy.replace(/^com\.atproto\.|\.policy$/g, "") + : null; + const flags = [space.role, policy, space.state] + .filter(Boolean) .concat(space.outdated ? ["OUTDATED"] : []) .join(" · "); row.append( @@ -850,6 +854,8 @@

EVENTS

), ); if (space.role === "authority" && space.state === "active") { + const isMemberspace = + space.policy === "com.atproto.memberspace.policy"; const actions = el("span", "space-actions"); const del = el("button", null, "delete"); del.addEventListener("click", async () => { @@ -857,7 +863,7 @@

EVENTS

try { await xrpc( "POST", - "com.atproto.simplespace.deleteSpace", + "com.atproto.space.deleteSpace", { body: { space: space.uri } }, ); load(); @@ -871,14 +877,14 @@

EVENTS

const members = el("div", "space-members"); const input = el("input"); input.placeholder = "did:… to add/remove"; - const mkBtn = (label, nsid) => { + const mkBtn = (label, nsid, extra = {}) => { const btn = el("button", null, label); btn.addEventListener("click", async () => { const did = input.value.trim(); if (!did) return; try { await xrpc("POST", nsid, { - body: { space: space.uri, did }, + body: { space: space.uri, did, ...extra }, }); input.value = ""; load(); @@ -890,13 +896,17 @@

EVENTS

}; members.append( input, - mkBtn("add member", "com.atproto.simplespace.addMember"), + mkBtn("add member", "com.atproto.memberspace.putMember", { + read: true, + write: true, + }), mkBtn( "remove member", - "com.atproto.simplespace.removeMember", + "com.atproto.memberspace.removeMember", ), ); - row.append(members); + // Only memberspace keeps a member list. + if (isMemberspace) row.append(members); } body.append(row); } diff --git a/packages/pds/src/index.ts b/packages/pds/src/index.ts index e949842..dd7fc42 100644 --- a/packages/pds/src/index.ts +++ b/packages/pds/src/index.ts @@ -91,7 +91,9 @@ app.use( origin: "*", allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], // Note: No allowHeaders; using "*" wildcard doesn't cover Authorization, so let Hono reflect the requested headers instead - exposeHeaders: ["Content-Type"], + // atproto-space-mac carries the MAC a browser syncer verifies space + // data with. + exposeHeaders: ["Content-Type", "atproto-space-mac"], maxAge: 86400, }), ); @@ -554,7 +556,7 @@ const oauthApp = createOAuthApp(getAccountDO); app.route("/", oauthApp); // Atproto spaces (alpha). When the flag is off none of the space or -// simplespace routes are registered, so they fall through to the proxy +// memberspace routes are registered, so they fall through to the proxy // like any unknown method, and the DID document says nothing about spaces. // // The bindings check must not throw: deploy-time startup validation @@ -563,7 +565,15 @@ app.route("/", oauthApp); // 503s rather than fail worker startup. if (env.SPACES_ENABLED === "true") { if (env.SPACES && env.SPACES_INDEX) { - app.route("/", createSpacesApp({ env, didResolver, getKeypair })); + app.route( + "/", + createSpacesApp({ + env, + didResolver, + getKeypair, + isAccountActive: () => getAccountDO(env).repo().getActive(), + }), + ); } else { console.error( "SPACES_ENABLED is set but the SPACES / SPACES_INDEX Durable Object bindings are missing. Space endpoints will return 503.", @@ -575,7 +585,15 @@ if (env.SPACES_ENABLED === "true") { // whenever the bindings exist, so `pds spaces reset` still works with the // flag off or the space DOs in their schema-refusing state. if (env.SPACES && env.SPACES_INDEX) { - app.route("/", createSpacesAdminApp({ env, didResolver, getKeypair })); + app.route( + "/", + createSpacesAdminApp({ + env, + didResolver, + getKeypair, + isAccountActive: () => getAccountDO(env).repo().getActive(), + }), + ); } // getFeed is proxied to the AppView but the service-auth JWT must be addressed diff --git a/packages/pds/src/spaces.ts b/packages/pds/src/spaces.ts index 72ebd54..cc95625 100644 --- a/packages/pds/src/spaces.ts +++ b/packages/pds/src/spaces.ts @@ -11,12 +11,13 @@ import { Hono } from "hono"; import type { Context } from "hono"; import { Secp256k1Keypair, verifySignature } from "@atproto/crypto"; -import { createSpaceToken, spaceHostAud } from "@atproto/space"; import { SpaceDurableObject as EngineSpaceDurableObject, SpaceIndexDurableObject as EngineSpaceIndexDurableObject, SPACE_SCHEMA_VERSION, + createDelegationToken, createSpaceRoutes, + promotePendingSpaceBlob, requireSpaceUri, parseSpaceErrorCode, spaceBlobRootPrefix, @@ -61,6 +62,8 @@ export interface SpacesAppDeps { env: PDSEnv; didResolver: DidResolver; getKeypair: () => Promise; + /** Whether the account is active (a deactivated authority issues nothing). */ + isAccountActive: () => Promise; } /** Data-location-aware stub creation, matching getAccountDO's handling. */ @@ -92,7 +95,26 @@ function locatedStub( return namespace.get(id); } -const SESSION_KID_ALLOWED = new Set(["#atproto", "#atproto_space"]); +/** + * After an upload: promote the blob into any space whose imported repo + * references it (`com.atproto.space.importRepo` brings records whose blobs + * are uploaded afterwards). A no-op unless the spaces bindings exist. The + * space data already lives in the bindings, so this runs with the flag off + * too, as reset and status do. + */ +export async function promoteUploadedSpaceBlob( + env: PDSEnv, + cid: string, +): Promise { + if (!env.SPACES_INDEX || !env.BLOBS) return; + await promotePendingSpaceBlob({ + bucket: env.BLOBS, + did: env.DID, + cid, + claimPendingBlob: (blobCid) => + getSpaceIndexDO(env).rpcClaimPendingBlob(blobCid), + }); +} /** * Fallback app mounted when SPACES_ENABLED is set but the SPACES / @@ -113,7 +135,7 @@ export function createSpacesUnavailableApp(): Hono { const method = c.req.param("method"); if ( !method.startsWith("com.atproto.space.") && - !method.startsWith("com.atproto.simplespace.") + !method.startsWith("com.atproto.memberspace.") ) { return next(); } @@ -131,24 +153,20 @@ export function createSpacesUnavailableApp(): Hono { /** * Build the host adapter and the complete spaces Hono app: the engine's - * space/simplespace routes plus the PDS-level getDelegationToken and + * space and memberspace routes plus the PDS-level getDelegationToken and * listSpaces. */ export function createSpacesApp(deps: SpacesAppDeps): Hono { const { env, didResolver, getKeypair } = deps; /** - * Resolve a DID's signing key to a did:key string, honouring the - * requested kid with the proposal's #atproto_space → #atproto fallback. + * Resolve a DID's `#atproto` key to a did:key string. Space tokens are + * signed with it, like any other account's. */ async function getSigningKey( iss: string, - kid: string | undefined, forceRefresh: boolean, ): Promise { - if (kid && !SESSION_KID_ALLOWED.has(kid)) { - throw new Error(`Unsupported signing key id: ${kid}`); - } // The operator's own key never goes through resolution: a Worker // cannot fetch its own hostname (same-zone subrequests are blocked), // and the delegation-for-own-space flow verifies tokens this Worker @@ -162,12 +180,11 @@ export function createSpacesApp(deps: SpacesAppDeps): Hono { id: string; publicKeyMultibase?: string; }>; - const find = (fragment: string) => - methods.find((m) => m.id === fragment || m.id.endsWith(fragment)); - const method = - (kid ? find(kid) : undefined) ?? find("#atproto"); + const method = methods.find( + (m) => m.id === "#atproto" || m.id.endsWith("#atproto"), + ); if (!method?.publicKeyMultibase) { - throw new Error(`No signing key in DID document for ${iss}`); + throw new Error(`No #atproto key in DID document for ${iss}`); } return `did:key:${method.publicKeyMultibase}`; } @@ -195,17 +212,6 @@ export function createSpacesApp(deps: SpacesAppDeps): Hono { : null; } - /** - * A space authority's host endpoint: the dedicated #atproto_space_host - * entry when published, falling back to #atproto_pds. - */ - async function resolveAuthorityEndpoint(did: string): Promise { - return ( - (await resolveServiceEndpoint(`${did}#atproto_space_host`)) ?? - (await resolveServiceEndpoint(did)) - ); - } - /** * Verify an inbound service-auth JWT from a foreign issuer (notifyWrite * and notifySpaceDeleted): ES256K signature against the issuer's @@ -219,9 +225,10 @@ export function createSpacesApp(deps: SpacesAppDeps): Hono { const parts = token.split("."); if (parts.length !== 3) throw new Error("Malformed service JWT"); const decode = (part: string) => - JSON.parse( - atob(part.replace(/-/g, "+").replace(/_/g, "/")), - ) as Record; + JSON.parse(atob(part.replace(/-/g, "+").replace(/_/g, "/"))) as Record< + string, + unknown + >; const payload = decode(parts[1]!); const iss = payload.iss; const aud = payload.aud; @@ -237,14 +244,12 @@ export function createSpacesApp(deps: SpacesAppDeps): Hono { ) { throw new Error("Service JWT expired"); } - const signingInput = new TextEncoder().encode( - `${parts[0]}.${parts[1]}`, - ); + const signingInput = new TextEncoder().encode(`${parts[0]}.${parts[1]}`); const sigB64 = parts[2]!.replace(/-/g, "+").replace(/_/g, "/"); const sig = Uint8Array.from(atob(sigB64), (ch) => ch.charCodeAt(0)); const verifyWith = async (forceRefresh: boolean) => verifySignature( - await getSigningKey(iss, undefined, forceRefresh), + await getSigningKey(iss, forceRefresh), signingInput, sig, ); @@ -349,14 +354,14 @@ export function createSpacesApp(deps: SpacesAppDeps): Hono { const host: SpaceRoutesHost = { operatorDid: env.DID, - publicOrigin: `https://${env.PDS_HOSTNAME}`, blobs: env.BLOBS, getKeypair, + getKemPrivateKey: () => env.SPACES_KEM_KEY ?? null, getSigningKey, resolveServiceEndpoint, - resolveAuthorityEndpoint, verifyServiceJwt: verifyForeignServiceJwt, authenticate, + isAccountActive: deps.isAccountActive, validateRecord: ({ collection, record, rkey, validate }) => { const result = validator.validate({ collection, record, rkey, validate }); return { record: result.record, status: result.status }; @@ -395,15 +400,9 @@ export function createSpacesApp(deps: SpacesAppDeps): Hono { ); } } - const keypair = await getKeypair(); - const token = await createSpaceToken( - "delegation", - { - iss: env.DID, - sub: ref.uri, - aud: spaceHostAud(ref.authority), - }, - keypair, + const token = await createDelegationToken( + { iss: env.DID, space: ref.uri, authority: ref.authority }, + await getKeypair(), ); return c.json({ token }); } catch (err) { @@ -415,7 +414,7 @@ export function createSpacesApp(deps: SpacesAppDeps): Hono { try { const session = await authenticate(c); if (session instanceof Response) return session; - const type = c.req.query("type"); + const type = c.req.query("spaceType"); const authority = c.req.query("did"); if (!session.fullTrust) { // An unfiltered listing needs a wildcard grant. @@ -536,6 +535,7 @@ export function createSpacesAdminApp(deps: SpacesAppDeps): Hono { role: entry.isAuthority ? "authority" : "writer", state: entry.state, outdated: status.outdated, + policy: status.policyType, recordCount: status.recordCount, memberCount: status.memberCount, writerCount: status.writerCount, @@ -545,6 +545,12 @@ export function createSpacesAdminApp(deps: SpacesAppDeps): Hono { return c.json({ enabled: env.SPACES_ENABLED === "true", schemaVersion: SPACE_SCHEMA_VERSION, + kem: { + configured: Boolean(env.SPACES_KEM_KEY), + ...(env.SPACES_KEM_KEY_PUBLIC + ? { didKey: `did:key:${env.SPACES_KEM_KEY_PUBLIC}` } + : {}), + }, stats, spaces, }); diff --git a/packages/pds/src/types.ts b/packages/pds/src/types.ts index 33a16c9..2fc6f0c 100644 --- a/packages/pds/src/types.ts +++ b/packages/pds/src/types.ts @@ -72,6 +72,16 @@ export interface PDSEnv { * unknown method. */ SPACES_ENABLED?: string; + /** + * The account's `#atproto_kem` P-256 private key (hex), with which the + * spaces alpha MACs space data for syncers. Secret. + */ + SPACES_KEM_KEY?: string; + /** + * Public half of SPACES_KEM_KEY (multibase), published as the + * `#atproto_kem` verification method in the DID document. + */ + SPACES_KEM_KEY_PUBLIC?: string; /** Durable Object namespace for spaces (one per space URI). */ SPACES?: DurableObjectNamespace; /** Durable Object namespace for the space index singleton. */ diff --git a/packages/pds/src/xrpc/identity.ts b/packages/pds/src/xrpc/identity.ts index 9c2a928..bd0e963 100644 --- a/packages/pds/src/xrpc/identity.ts +++ b/packages/pds/src/xrpc/identity.ts @@ -45,6 +45,20 @@ export function buildDidDocument(env: PDSEnv) { controller: env.DID, publicKeyMultibase: env.SIGNING_KEY_PUBLIC, }, + // Spaces alpha: the P-256 key syncers derive MAC secrets against. + // The space host is #atproto_pds and space tokens are signed with + // #atproto, like any other account, so this is the only spaces + // entry. + ...(env.SPACES_ENABLED === "true" && env.SPACES_KEM_KEY_PUBLIC + ? [ + { + id: `${env.DID}#atproto_kem`, + type: "Multikey", + controller: env.DID, + publicKeyMultibase: env.SPACES_KEM_KEY_PUBLIC, + }, + ] + : []), ], service: [ { @@ -52,19 +66,6 @@ export function buildDidDocument(env: PDSEnv) { type: "AtprotoPersonalDataServer", serviceEndpoint: `https://${env.PDS_HOSTNAME}`, }, - // Spaces alpha: advertise the space host endpoint. No dedicated - // #atproto_space verification key is added — the proposal falls - // back to #atproto, and a second key would create a rotation and - // backup story for no benefit on a single-user PDS. - ...(env.SPACES_ENABLED === "true" - ? [ - { - id: "#atproto_space_host", - type: "AtprotoSpaceHost", - serviceEndpoint: `https://${env.PDS_HOSTNAME}`, - }, - ] - : []), ], }; } @@ -86,7 +87,13 @@ export async function getRecommendedDidCredentials( return c.json({ rotationKeys: [signingKey], alsoKnownAs: [`at://${c.env.HANDLE}`], - verificationMethods: { atproto: signingKey }, + verificationMethods: { + atproto: signingKey, + // Carried through a migration so space data stays verifiable. + ...(c.env.SPACES_KEM_KEY_PUBLIC + ? { atproto_kem: `did:key:${c.env.SPACES_KEM_KEY_PUBLIC}` } + : {}), + }, services: { atproto_pds: { type: "AtprotoPersonalDataServer", diff --git a/packages/pds/src/xrpc/repo.ts b/packages/pds/src/xrpc/repo.ts index c34ddda..a61db8e 100644 --- a/packages/pds/src/xrpc/repo.ts +++ b/packages/pds/src/xrpc/repo.ts @@ -13,6 +13,7 @@ import { detectContentType } from "../format.js"; import { BlobStore, extractJsonBlobCids } from "../repo/blobs.js"; import { buildScopeChecker, requireScope } from "../middleware/auth.js"; import { pokeRelaysIfUnheard } from "../relay.js"; +import { promoteUploadedSpaceBlob } from "../spaces.js"; /** * Promote any staged blobs referenced by the given records to their public @@ -712,6 +713,9 @@ export async function uploadBlob( if (referenced) { await blobStore.promoteBlob(blobRef.ref.$link); } + // Likewise for space repos imported during migration, whose records + // already reference the blob. + await promoteUploadedSpaceBlob(c.env, blobRef.ref.$link); return c.json({ blob: blobRef }); } diff --git a/packages/pds/test/cli/key.test.ts b/packages/pds/test/cli/key.test.ts index 6ae5ea6..d022c24 100644 --- a/packages/pds/test/cli/key.test.ts +++ b/packages/pds/test/cli/key.test.ts @@ -3,7 +3,7 @@ import { mkdtempSync, rmSync, writeFileSync } from "node:fs"; import { tmpdir } from "node:os"; import { join } from "node:path"; import { execSync } from "node:child_process"; -import { Secp256k1Keypair } from "@atproto/crypto"; +import { P256Keypair, Secp256k1Keypair } from "@atproto/crypto"; import { readDevVars } from "../../src/cli/utils/dotenv.js"; import { generateSigningKeypair, @@ -73,3 +73,36 @@ describe("pds secret key CLI", () => { expect(vars.SIGNING_KEY_PUBLIC).toBe(expectedPublic); }); }); + +describe("pds spaces kem CLI", () => { + let tempDir: string; + const cliPath = join(__dirname, "../../dist/cli.js"); + + beforeEach(() => { + tempDir = mkdtempSync(join(tmpdir(), "pds-kem-test-")); + writeFileSync( + join(tempDir, "wrangler.jsonc"), + JSON.stringify({ name: "test", vars: { DID: "did:web:pds.example" } }), + ); + }); + + afterEach(() => { + rmSync(tempDir, { recursive: true, force: true }); + }); + + it("generates a P-256 #atproto_kem key whose public half matches", async () => { + const output = execSync(`node ${cliPath} spaces kem --local`, { + cwd: tempDir, + stdio: "pipe", + }).toString(); + + const vars = readDevVars(tempDir); + expect(vars.SPACES_KEM_KEY).toMatch(/^[0-9a-f]{64}$/); + const keypair = await P256Keypair.import(vars.SPACES_KEM_KEY!); + expect(vars.SPACES_KEM_KEY_PUBLIC).toBe( + keypair.did().replace("did:key:", ""), + ); + // did:web needs no PLC operation: the PDS serves the document. + expect(output).toMatch(/redeploy/i); + }); +}); diff --git a/packages/pds/test/identity.test.ts b/packages/pds/test/identity.test.ts index 10ab4a3..870d88a 100644 --- a/packages/pds/test/identity.test.ts +++ b/packages/pds/test/identity.test.ts @@ -29,7 +29,7 @@ describe("Identity Endpoints", () => { const data = (await response.json()) as { rotationKeys: string[]; alsoKnownAs: string[]; - verificationMethods: { atproto: string }; + verificationMethods: { atproto: string; atproto_kem?: string }; services: { atproto_pds: { type: string; endpoint: string }; }; @@ -41,7 +41,12 @@ describe("Identity Endpoints", () => { expect(data.rotationKeys).toEqual([expectedSigningKey]); expect(data.alsoKnownAs).toEqual([`at://${env.HANDLE}`]); - expect(data.verificationMethods).toEqual({ atproto: expectedSigningKey }); + // The test environment configures the spaces KEM key, which is + // carried through a migration alongside the signing key. + expect(data.verificationMethods).toEqual({ + atproto: expectedSigningKey, + atproto_kem: `did:key:${env.SPACES_KEM_KEY_PUBLIC}`, + }); expect(data.services).toEqual({ atproto_pds: { type: "AtprotoPersonalDataServer", diff --git a/packages/pds/test/spaces.test.ts b/packages/pds/test/spaces.test.ts index 9485187..b94fc68 100644 --- a/packages/pds/test/spaces.test.ts +++ b/packages/pds/test/spaces.test.ts @@ -1,46 +1,18 @@ import { describe, expect, it } from "vitest"; -import { createDpopProof } from "@atproto/space"; +import { P256Keypair } from "@atproto/crypto"; +import { + RECORD_MAC_TYPE, + createSpaceSigHeaders, + encapsulate, + formatWantMacHeader, + parseMacHeader, + serializeRepo, + verifyRecord, +} from "@atproto/space"; +import { encode } from "@atproto/lex-cbor"; import { env, worker, runInDurableObject } from "./helpers"; import { createSpacesUnavailableApp } from "../src/spaces"; -/** - * Minimal WebCrypto-backed DPoP key satisfying the `Key` surface - * `createDpopProof` uses (`bareJwk`, `algorithms`, `createJwt`). Avoids - * @atproto/jwk-jose, whose bundled jose resolves to its Node build under - * the vitest workers pool and fails to sign. - */ -async function makeDpopKey() { - const pair = await crypto.subtle.generateKey( - { name: "ECDSA", namedCurve: "P-256" }, - true, - ["sign"], - ); - const jwk = await crypto.subtle.exportKey("jwk", pair.publicKey); - const bareJwk = { kty: jwk.kty, crv: jwk.crv, x: jwk.x, y: jwk.y }; - const b64url = (bytes: Uint8Array) => - btoa(String.fromCharCode(...bytes)) - .replace(/\+/g, "-") - .replace(/\//g, "_") - .replace(/=+$/, ""); - const encode = (obj: unknown) => - b64url(new TextEncoder().encode(JSON.stringify(obj))); - return { - bareJwk, - algorithms: ["ES256"] as const, - async createJwt(header: unknown, payload: unknown) { - const input = `${encode(header)}.${encode(payload)}`; - const sig = new Uint8Array( - await crypto.subtle.sign( - { name: "ECDSA", hash: "SHA-256" }, - pair.privateKey, - new TextEncoder().encode(input), - ), - ); - return `${input}.${b64url(sig)}`; - }, - } as never; -} - const authed = { "Content-Type": "application/json", Authorization: `Bearer ${env.AUTH_TOKEN}`, @@ -67,33 +39,37 @@ function post( let spaceN = 0; async function createSpace(): Promise { - const res = await post("/xrpc/com.atproto.simplespace.createSpace", { - type: "app.bsky.group", + const res = await post("/xrpc/com.atproto.space.createSpace", { + spaceType: "app.bsky.group", skey: `pds${spaceN++}x`, - policy: { $type: "com.atproto.simplespace.defs#memberListPolicy" }, - appAccess: { $type: "com.atproto.simplespace.defs#open" }, + policy: { $type: "com.atproto.memberspace.policy" }, }); expect(res.status).toBe(200); return ((await res.json()) as { uri: string }).uri; } describe("spaces integration", () => { - it("advertises the space host in the DID document", async () => { + it("publishes #atproto_kem and no space-specific service entry", async () => { const res = await get("/.well-known/did.json"); const doc = (await res.json()) as { - service: Array<{ id: string; type: string; serviceEndpoint: string }>; - verificationMethod: Array<{ id: string }>; + service: Array<{ id: string }>; + verificationMethod: Array<{ id: string; publicKeyMultibase: string }>; }; - const entry = doc.service.find((s) => s.id === "#atproto_space_host"); - expect(entry).toMatchObject({ - type: "AtprotoSpaceHost", - serviceEndpoint: `https://${env.PDS_HOSTNAME}`, + // The space host is #atproto_pds and space tokens are signed with + // #atproto, like any other account. + expect(doc.service.map((s) => s.id)).toEqual(["#atproto_pds"]); + const kem = doc.verificationMethod.find((m) => m.id.endsWith("#atproto_kem")); + expect(kem?.publicKeyMultibase).toBe(env.SPACES_KEM_KEY_PUBLIC); + + const creds = await get("/xrpc/com.atproto.identity.getRecommendedDidCredentials", { + Authorization: `Bearer ${env.AUTH_TOKEN}`, }); - // No dedicated #atproto_space verification key: the proposal falls - // back to #atproto. - expect( - doc.verificationMethod.some((m) => m.id.endsWith("#atproto_space")), - ).toBe(false); + const body = (await creds.json()) as { + verificationMethods: Record; + }; + expect(body.verificationMethods.atproto_kem).toBe( + `did:key:${env.SPACES_KEM_KEY_PUBLIC}`, + ); }); it("stores and returns private records (S1)", async () => { @@ -197,7 +173,7 @@ describe("spaces integration", () => { expect(decode(payloadB64)).toMatchObject({ iss: env.DID, sub: space, - aud: `${authority}#atproto_space_host`, + aud: `${authority}#atproto_pds`, }); }); @@ -225,38 +201,118 @@ describe("spaces integration", () => { expect(delegationRes.status).toBe(200); const { token } = (await delegationRes.json()) as { token: string }; - const dpopKey = await makeDpopKey(); - const exchangeProof = await createDpopProof(dpopKey, { - htm: "POST", - htu: `https://${env.PDS_HOSTNAME}/xrpc/com.atproto.space.getSpaceCredential`, - }); + const key = await P256Keypair.create(); const credentialRes = await post( "/xrpc/com.atproto.space.getSpaceCredential", - { space }, - { - "Content-Type": "application/json", - Authorization: `Bearer ${token}`, - DPoP: exchangeProof, - }, + { space, credentialKid: key.did(), delegationToken: token }, + { "Content-Type": "application/json" }, ); expect(credentialRes.status).toBe(200); const { credential } = (await credentialRes.json()) as { credential: string; }; - const readProof = await createDpopProof(dpopKey, { - htm: "GET", - htu: `https://${env.PDS_HOSTNAME}/xrpc/com.atproto.space.getRecord`, - credential, + const headers: Record = await createSpaceSigHeaders(key, { + authorization: `Atproto-Space-Credential ${credential}`, + audience: env.DID as `did:${string}:${string}`, }); + const { keyShare, sharedSecret } = await encapsulate( + `did:key:${env.SPACES_KEM_KEY_PUBLIC}`, + ); + headers["atproto-space-want-mac"] = formatWantMacHeader(RECORD_MAC_TYPE, keyShare); const read = await get( `/xrpc/com.atproto.space.getRecord?space=${encodeURIComponent(space)}&repo=${env.DID}&collection=test.cirrus.note&rkey=roundtrip`, - { Authorization: `DPoP ${credential}`, DPoP: readProof }, + headers, ); expect(read.status).toBe(200); + // The MAC header must reach a browser app across origins. + expect(read.headers.get("Access-Control-Expose-Headers")).toMatch( + /atproto-space-mac/i, + ); + const record = (await read.json()) as { + uri: string; + cid: string; + value: { text: string }; + }; + expect(record.value.text).toBe("note"); + const mac = parseMacHeader( + read.headers.get("atproto-space-mac") ?? undefined, + RECORD_MAC_TYPE, + ); expect( - ((await read.json()) as { value: { text: string } }).value.text, - ).toBe("note"); + await verifyRecord(record as never, { uri: record.uri, sharedSecret, mac }), + ).toBe(true); + }); + + it("promotes blobs of an imported space repo when they are uploaded", async () => { + // Migration order: the space repo arrives first, its blobs after. + const bytes = new Uint8Array([0x4d, 0x49, 0x47, 0x52, 0x41, 0x54, 0x45]); + const { create, CODEC_RAW, CODEC_DCBOR, toString } = await import("@atcute/cid"); + const cid = toString(await create(CODEC_RAW, bytes)); + const record = { + $type: "test.cirrus.file", + file: { + $type: "blob", + ref: { $link: cid }, + mimeType: "application/octet-stream", + size: bytes.length, + }, + }; + const space = `at://did:web:elsewhere.test/space/app.bsky.group/migrated${spaceN++}`; + const { jsonToLex } = await import("@atproto/lex-json"); + const recordBytes = encode(jsonToLex(record) as never); + const recordCid = toString(await create(CODEC_DCBOR, recordBytes)); + const { LtHash } = await import("@atproto/space"); + const data = new LtHash().add(`test.cirrus.file/f/${recordCid}`).digest(); + const chunks: Uint8Array[] = []; + for await (const chunk of serializeRepo( + { + ver: 1, + repo: env.DID as never, + space: space as never, + rev: "3mabcdefghijk", + data, + }, + [{ collection: "test.cirrus.file" as never, rkey: "f" as never, bytes: recordBytes }], + )) { + chunks.push(chunk); + } + const archive = new Uint8Array(await new Blob(chunks).arrayBuffer()); + const imported = await worker.fetch( + new Request("http://pds.test/xrpc/com.atproto.space.importRepo", { + method: "POST", + headers: { + "Content-Type": "application/octet-stream", + Authorization: `Bearer ${env.AUTH_TOKEN}`, + }, + body: archive, + }), + env, + ); + expect(imported.status).toBe(200); + + const blobPath = `/xrpc/com.atproto.space.getBlob?space=${encodeURIComponent(space)}&repo=${env.DID}&cid=${cid}`; + const before = await get(blobPath, { Authorization: `Bearer ${env.AUTH_TOKEN}` }); + expect(before.status).toBe(404); + + const upload = await worker.fetch( + new Request("http://pds.test/xrpc/com.atproto.repo.uploadBlob", { + method: "POST", + headers: { + "Content-Type": "application/octet-stream", + Authorization: `Bearer ${env.AUTH_TOKEN}`, + }, + body: bytes, + }), + env, + ); + expect(upload.status).toBe(200); + const after = await get(blobPath, { Authorization: `Bearer ${env.AUTH_TOKEN}` }); + expect(after.status).toBe(200); + expect(new Uint8Array(await after.arrayBuffer())).toEqual(bytes); + // Still never public. + const publicBlob = await get(`/xrpc/com.atproto.sync.getBlob?did=${env.DID}&cid=${cid}`); + expect(publicBlob.status).toBe(404); }); it("lists spaces from the index", async () => { @@ -436,7 +492,7 @@ describe("spaces integration", () => { it("degrades to 503 when the flag is set without bindings", async () => { // The fallback app mounted when SPACES / SPACES_INDEX are absent: - // space and simplespace methods answer 503, everything else falls + // space and memberspace methods answer 503, everything else falls // through to later routes (the proxy). const app = createSpacesUnavailableApp(); const space = await app.request( @@ -446,11 +502,11 @@ describe("spaces integration", () => { expect(((await space.json()) as { error: string }).error).toBe( "ServiceUnavailable", ); - const simplespace = await app.request( - "/xrpc/com.atproto.simplespace.createSpace", + const memberspace = await app.request( + "/xrpc/com.atproto.memberspace.putMember", { method: "POST" }, ); - expect(simplespace.status).toBe(503); + expect(memberspace.status).toBe(503); // Non-space methods are untouched. const other = await app.request("/xrpc/com.atproto.repo.getRecord"); expect(other.status).toBe(404); diff --git a/packages/pds/vitest.config.ts b/packages/pds/vitest.config.ts index becb45b..5d410d4 100644 --- a/packages/pds/vitest.config.ts +++ b/packages/pds/vitest.config.ts @@ -51,6 +51,10 @@ export default defineConfig({ INITIAL_ACTIVE: "true", // Exercise the spaces alpha in tests SPACES_ENABLED: "true", + SPACES_KEM_KEY: + "b5952836830a94fa65c83db8c527ff76b99d69ed1ceffaa6de93d6a62df1efb5", + SPACES_KEM_KEY_PUBLIC: + "zDnaejUd5i6eEP8uo8LafaYmAtEVQqrnYm1wibThTZm5GpiDG", // Sinkhole relay pokes: write tests run with unstubbed // fetch, and the default would POST requestCrawl to the // real bsky.network from CI. diff --git a/packages/spaces/src/attestation.ts b/packages/spaces/src/attestation.ts index 98f9e9b..36a4ae0 100644 --- a/packages/spaces/src/attestation.ts +++ b/packages/spaces/src/attestation.ts @@ -69,7 +69,11 @@ export async function verifyClientAttestation( "Attestation client_id is not a URL", ); } - if (clientUrl.protocol !== "https:" || clientUrl.username || clientUrl.password) { + if ( + clientUrl.protocol !== "https:" || + clientUrl.username || + clientUrl.password + ) { throw new SpaceError( "InvalidClientAttestation", "Attestation client_id must be a plain https URL", diff --git a/packages/spaces/src/auth.ts b/packages/spaces/src/auth.ts index adcc58b..4a70094 100644 --- a/packages/spaces/src/auth.ts +++ b/packages/spaces/src/auth.ts @@ -1,27 +1,33 @@ /** * Worker-side verification of space credentials and delegation tokens. * - * Everything here is stateless except the replay checks, which are one RPC - * to the space DO's `replay` table. Key resolution goes through the host's - * DID resolver with a forced refresh on signature failure (handled inside - * `verifySpaceToken`) so key rotation doesn't strand callers. + * A space credential is presented as `Authorization: Atproto-Space-Credential + * ` (scheme case-insensitive), with an `Atproto-Space-Audience` header + * naming the service being called and an HTTP message signature over both, + * by the P-256 key the credential is bound to (`cnf.kid`). A delegation + * token arrives in the `getSpaceCredential` request body. + * + * Everything here is stateless except the revocation and replay checks, + * which are one RPC each to the space DO. Key resolution goes through the + * host's DID resolver with a forced refresh on signature failure (handled + * inside `verifySpaceToken`) so key rotation doesn't strand callers. */ import { - DpopProofError, - SPACE_TOKEN_TYPES, + SpaceSignatureError, SpaceTokenError, spaceHostAud, - verifyDpopProof, + verifyCredentialSig, verifySpaceToken, } from "@atproto/space"; import { SpaceError } from "./errors.js"; +import type { SpaceErrorCode } from "./errors.js"; +import { parseSpaceUri } from "./space-uri.js"; import type { SpaceRef } from "./space-uri.js"; -/** Resolve an issuer DID (+ key id) to a did:key string. */ +/** Resolve an issuer DID's `#atproto` key to a did:key string. */ export type GetSigningKey = ( iss: string, - kid: string | undefined, forceRefresh: boolean, ) => Promise; @@ -32,165 +38,175 @@ export type CheckReplay = ( expiresAtSec: number, ) => Promise; +/** Whether a credential has been revoked by the space's authority. */ +export type CheckRevoked = (jti: string) => Promise; + +export const SPACE_CREDENTIAL_SCHEME = "Atproto-Space-Credential"; +export const SPACE_AUDIENCE_HEADER = "atproto-space-audience"; + /** - * Peek at an unverified JWT's `typ` header. Used only for routing between - * authentication schemes — safe because neither token type verifies as the - * other. + * Split an Authorization header into scheme and token. The scheme is + * case-insensitive, as for every HTTP authentication scheme. */ -export function unverifiedJwtTyp(token: string): string | null { - const dot = token.indexOf("."); - if (dot <= 0) return null; - try { - const header = JSON.parse( - atob(token.slice(0, dot).replace(/-/g, "+").replace(/_/g, "/")), - ) as { typ?: unknown }; - return typeof header.typ === "string" ? header.typ : null; - } catch { - return null; - } +function splitAuthorization( + authorization: string | undefined, +): { scheme: string; token: string } | null { + if (!authorization) return null; + const parts = authorization.split(" "); + if (parts.length !== 2 || !parts[0] || !parts[1]) return null; + return { scheme: parts[0].toLowerCase(), token: parts[1] }; } /** Whether an Authorization header carries a space credential. */ -export function isSpaceCredentialAuth(authorization: string | undefined): boolean { - if (!authorization?.startsWith("DPoP ")) return false; +export function isSpaceCredentialAuth( + authorization: string | undefined, +): boolean { return ( - unverifiedJwtTyp(authorization.slice(5)) === - SPACE_TOKEN_TYPES.credential.typ + splitAuthorization(authorization)?.scheme === + SPACE_CREDENTIAL_SCHEME.toLowerCase() ); } -export interface VerifyRequestOpts { - /** HTTP method of the request. */ - htm: string; - /** Request URL; its path is combined with `publicOrigin` for htu. */ - url: string; +export interface VerifyCredentialOpts { + /** Request headers, lower-cased names. */ + headers: Record; /** - * The origin clients see (`https://host`). The Worker may be behind a - * proxy, so htu is reconstructed from this rather than trusted from the - * incoming URL. + * The DID this request is addressed to: the repo DID for repo-host + * reads, the authority DID for space-host methods. The signed + * `Atproto-Space-Audience` header must name it. */ - publicOrigin: string; - dpopProof: string | undefined; + audience: string; getSigningKey: GetSigningKey; - checkReplay: CheckReplay; -} - -function htuFor(opts: VerifyRequestOpts): string { - return `${opts.publicOrigin}${new URL(opts.url).pathname}`; + checkRevoked: CheckRevoked; } -const nowSec = () => Math.floor(Date.now() / 1000); - export interface SpaceCredentialResult { kind: "credential"; - /** The credential issuer — the space's authority DID. */ + /** The credential issuer: the space's authority DID. */ iss: string; + jti: string; } /** - * Verify a space credential (`Authorization: DPoP ` + `DPoP` proof) - * presented against `space`. Checks, per the proposal: signature against - * the issuer's `#atproto_space` / `#atproto` key, `sub` equal to the - * requested space, `iss` equal to the space's authority, `cnf.jkt` equal - * to the proof key's thumbprint, proof `htm`/`htu`/`ath`/`iat` valid and - * proof `jti` unseen. + * Verify a space credential presented against `space`: the token itself + * (type, signature against the issuer's `#atproto` key, expiry, lifetime), + * its issuer being the space's authority and its subject the space, the + * HTTP message signature by its bound key over the credential and the + * audience, the audience naming this service, and revocation. */ export async function verifySpaceCredentialAuth( - credential: string, space: SpaceRef, - opts: VerifyRequestOpts, + opts: VerifyCredentialOpts, ): Promise { + const authorization = splitAuthorization(opts.headers.authorization); + if ( + !authorization || + authorization.scheme !== SPACE_CREDENTIAL_SCHEME.toLowerCase() + ) { + throw new SpaceError("MissingJwt", "Missing space credential"); + } + let payload; try { - ({ payload } = await verifySpaceToken("credential", credential, { + ({ payload } = await verifySpaceToken("credential", authorization.token, { getSigningKey: opts.getSigningKey, - sub: space.uri, })); } catch (err) { - throw invalidCredential(err); + throw tokenError(err, "BadJwt"); } - if (payload.iss !== space.authority) { + const subject = parseSpaceUri(payload.sub); + if (!subject) { throw new SpaceError( - "InvalidCredential", - "Space credential issuer is not the space authority", + "BadJwtSub", + `Space token subject is not a space URI: ${payload.sub}`, ); } - const jkt = payload.cnf?.jkt; - if (!jkt) { + if (payload.iss !== subject.authority) { throw new SpaceError( - "InvalidCredential", - "Space credential is missing its cnf.jkt binding", + "BadJwtIss", + "Space credential issuer is not the space authority", ); } - if (!opts.dpopProof) { - throw new SpaceError("InvalidCredential", "Missing DPoP proof"); + + const audience = opts.headers[SPACE_AUDIENCE_HEADER]; + if (!audience?.startsWith("did:")) { + throw new SpaceError( + "BadSpaceSignature", + "Missing or invalid space audience DID", + ); } - let proof; try { - proof = await verifyDpopProof(opts.dpopProof, { - htm: opts.htm, - htu: htuFor(opts), - credential, - jkt, - }); + await verifyCredentialSig(opts.headers, payload.cnf!.kid); } catch (err) { - throw invalidCredential(err); + if (err instanceof SpaceSignatureError) { + throw new SpaceError("BadSpaceSignature", err.message); + } + throw err; } - const fresh = await opts.checkReplay( - "dpop", - proof.jti, - nowSec() + 300, - ); - if (!fresh) { - throw new SpaceError("InvalidCredential", "DPoP proof replayed"); + if (audience !== opts.audience) { + throw new SpaceError( + "BadSpaceAudience", + "Space audience does not match the request", + ); } - return { kind: "credential", iss: payload.iss }; + if (payload.sub !== space.uri) { + throw new SpaceError( + "InvalidCredential", + "Credential is not scoped to this space", + ); + } + if (await opts.checkRevoked(payload.jti)) { + throw new SpaceError( + "CredentialRevoked", + "Space credential has been revoked", + ); + } + return { kind: "credential", iss: payload.iss, jti: payload.jti }; } export interface DelegationResult { /** The user the delegation token vouches for. */ userDid: string; - /** Thumbprint of the DPoP key the credential must be bound to. */ - dpopJkt: string; } /** - * Verify a delegation token (`Authorization: Bearer ` on - * getSpaceCredential) plus its DPoP proof (no `ath` when obtaining a - * credential). Single use by `(iss, jti)`. + * Verify a delegation token from a `getSpaceCredential` body: signature + * against the issuer's `#atproto` key, audience the space authority's + * `#atproto_pds`, subject the requested space, single use by `(iss, jti)`. + * Any failure is `InvalidDelegationToken`: the token arrives in the body + * rather than as the request's authorization, so it is an invalid request, + * not an authentication failure. */ -export async function verifyDelegationAuth( +export async function verifyDelegationToken( token: string, space: SpaceRef, - opts: VerifyRequestOpts, + opts: { getSigningKey: GetSigningKey; checkReplay: CheckReplay }, ): Promise { let payload; try { ({ payload } = await verifySpaceToken("delegation", token, { getSigningKey: opts.getSigningKey, - aud: spaceHostAud(space.authority), - sub: space.uri, })); } catch (err) { - throw invalidDelegation(err); + throw tokenError(err, "InvalidDelegationToken", "InvalidDelegationToken"); } - if (!payload.iss.startsWith("did:")) { + if (payload.sub !== space.uri) { throw new SpaceError( "InvalidDelegationToken", - "Delegation token issuer is not a DID", + "Delegation token subject does not match requested space", ); } - if (!opts.dpopProof) { - throw new SpaceError("InvalidDelegationToken", "Missing DPoP proof"); + if (payload.aud !== spaceHostAud(space.authority)) { + throw new SpaceError( + "InvalidDelegationToken", + "Delegation token audience does not match the space authority", + ); } - let proof; - try { - proof = await verifyDpopProof(opts.dpopProof, { - htm: opts.htm, - htu: htuFor(opts), - }); - } catch (err) { - throw invalidDelegation(err); + if (!payload.iss.startsWith("did:")) { + throw new SpaceError( + "InvalidDelegationToken", + "Delegation token issuer is not a DID", + ); } const fresh = await opts.checkReplay( "delegation", @@ -203,25 +219,21 @@ export async function verifyDelegationAuth( "Delegation token has already been used", ); } - return { userDid: payload.iss, dpopJkt: proof.jkt }; -} - -function invalidCredential(err: unknown): SpaceError { - // Server-side detail for operators; clients get the generic message. - console.warn("space credential verification failed:", err); - return new SpaceError("InvalidCredential", authErrorMessage(err)); -} - -function invalidDelegation(err: unknown): SpaceError { - console.warn("delegation token verification failed:", err); - return new SpaceError("InvalidDelegationToken", authErrorMessage(err)); + return { userDid: payload.iss }; } -function authErrorMessage(err: unknown): string { - if (err instanceof SpaceTokenError || err instanceof DpopProofError) { - return err.message; +function tokenError( + err: unknown, + fallback: SpaceErrorCode, + override?: SpaceErrorCode, +): SpaceError { + // Server-side detail for operators; clients get the token library's + // message, never infrastructure internals. + console.warn("space token verification failed:", err); + if (err instanceof SpaceTokenError) { + return new SpaceError(override ?? err.code, err.message); } // DID resolution failures and other infrastructure errors must surface - // as 401s, never 500s — but without leaking internals. - return "Token verification failed"; + // as auth errors, never 500s. + return new SpaceError(override ?? fallback, "Token verification failed"); } diff --git a/packages/spaces/src/blob-keys.ts b/packages/spaces/src/blob-keys.ts index 2a7cc7f..01f9ca8 100644 --- a/packages/spaces/src/blob-keys.ts +++ b/packages/spaces/src/blob-keys.ts @@ -42,3 +42,41 @@ export async function spaceBlobKeyForUri( ): Promise { return spaceBlobKey(did, await spaceId(spaceUri), cid); } + +/** + * Copy a staged upload into a space's blob prefix. Idempotent; returns + * whether the blob is now at its destination (false when it was neither + * there nor staged). + */ +export async function promoteStagedBlobToSpace( + bucket: R2Bucket, + did: string, + spaceUri: string, + cid: string, +): Promise { + const destKey = await spaceBlobKeyForUri(did, spaceUri, cid); + if (await bucket.head(destKey)) return true; + const staged = await bucket.get(stagedBlobKey(did, cid)); + if (!staged) return false; + await bucket.put(destKey, staged.body, { httpMetadata: staged.httpMetadata }); + return true; +} + +/** + * Promote a freshly uploaded blob into every space whose imported records + * reference it (see `com.atproto.space.importRepo`). The host calls this + * from `com.atproto.repo.uploadBlob`, mirroring how an imported public repo's + * blobs are made permanent on upload. + */ +export async function promotePendingSpaceBlob(params: { + bucket: R2Bucket; + did: string; + cid: string; + claimPendingBlob: (cid: string) => Promise; +}): Promise { + const uris = await params.claimPendingBlob(params.cid); + for (const uri of uris) { + await promoteStagedBlobToSpace(params.bucket, params.did, uri, params.cid); + } + return uris.length; +} diff --git a/packages/spaces/src/commit.ts b/packages/spaces/src/commit.ts deleted file mode 100644 index 7a525e3..0000000 --- a/packages/spaces/src/commit.ts +++ /dev/null @@ -1,55 +0,0 @@ -/** - * Commit signing. - * - * Signing happens in the Worker, never in the Durable Object. The proposal - * requires a fresh `ikm` per reader, so a signature is never stored — each - * response that carries a commit signs the persisted LtHash state anew with - * the account keypair the Worker already holds. - */ - -import { RepoCommit } from "@atproto/space"; -import type { SignedCommit } from "@atproto/space"; -import type { Keypair } from "@atproto/crypto"; -import { toBase64 } from "@atproto/lex-data"; -import type { RepoState } from "./types.js"; - -export interface SignCommitParams { - spaceUri: string; - /** The repo author (the operator DID for every repo Cirrus serves). */ - author: string; - state: RepoState; -} - -export async function signCommit( - params: SignCommitParams, - keypair: Keypair, -): Promise { - return RepoCommit.fromState(params.state.setHash).sign( - { - space: params.spaceUri, - author: params.author, - rev: params.state.rev, - }, - keypair, - ); -} - -/** - * Lexicon JSON form of a signed commit (`com.atproto.space.defs#signedCommit`): - * bytes fields encode as `{"$bytes": ""}`. - */ -export function commitToJson(commit: SignedCommit): Record { - return { - ver: commit.ver, - hash: { $bytes: toBase64(commit.hash) }, - ikm: { $bytes: toBase64(commit.ikm) }, - sig: { $bytes: toBase64(commit.sig) }, - mac: { $bytes: toBase64(commit.mac) }, - rev: commit.rev, - }; -} - -/** Lexicon JSON form of a bare bytes value. */ -export function bytesToJson(bytes: Uint8Array): { $bytes: string } { - return { $bytes: toBase64(bytes) }; -} diff --git a/packages/spaces/src/errors.ts b/packages/spaces/src/errors.ts index 34c8000..78b78b0 100644 --- a/packages/spaces/src/errors.ts +++ b/packages/spaces/src/errors.ts @@ -8,12 +8,14 @@ * shape. */ -/** Protocol error names used across space and simplespace endpoints. */ +/** Protocol error names used across the space and policy endpoints. */ export const SPACE_ERROR_CODES = [ "SpaceNotFound", "SpaceDeleted", "SpaceAlreadyExists", "RepoNotFound", + "RepoDeactivated", + "RepoTakendown", "RecordNotFound", "RecordAlreadyExists", "BlobNotFound", @@ -24,12 +26,30 @@ export const SPACE_ERROR_CODES = [ "InvalidClientAttestation", "InvalidCredential", "NotSpaceOwner", + "PolicyMismatch", "UnsupportedPolicy", - "UnsupportedAppAccess", "ServiceNotResolvable", "MalformedCursor", "InvalidSpaceUri", "InvalidRequest", + "FutureRev", + "BadSpaceMac", + // Space credential authentication failures, named as the reference + // names them (all 401). + "MissingJwt", + "BadJwt", + "BadJwtType", + "BadJwtIss", + "BadJwtSub", + "BadJwtAudience", + "BadJwtCnf", + "BadJwtSignature", + "JwtExpired", + "BadSpaceSignature", + "BadSpaceAudience", + "CredentialRevoked", + "Forbidden", + "KemKeyUnavailable", "SpacesSchemaOutdated", ] as const; @@ -48,9 +68,21 @@ const ERROR_STATUS: Partial> = { AppNotAuthorized: 403, NotAuthorized: 403, NotSpaceOwner: 403, - InvalidDelegationToken: 401, + Forbidden: 403, InvalidClientAttestation: 401, - InvalidCredential: 401, + MissingJwt: 401, + BadJwt: 401, + BadJwtType: 401, + BadJwtIss: 401, + BadJwtSub: 401, + BadJwtAudience: 401, + BadJwtCnf: 401, + BadJwtSignature: 401, + JwtExpired: 401, + BadSpaceSignature: 401, + BadSpaceAudience: 401, + CredentialRevoked: 401, + KemKeyUnavailable: 503, SpacesSchemaOutdated: 503, }; diff --git a/packages/spaces/src/index-do.ts b/packages/spaces/src/index-do.ts index 5743acd..bc23017 100644 --- a/packages/spaces/src/index-do.ts +++ b/packages/spaces/src/index-do.ts @@ -11,7 +11,12 @@ */ import { DurableObject } from "cloudflare:workers"; -import { INDEX_DO_SCHEMA, PENDING_ENTRY_TTL_MS, SPACE_SCHEMA_VERSION } from "./schema.js"; +import { + INDEX_DO_SCHEMA, + PENDING_BLOB_TTL_MS, + PENDING_ENTRY_TTL_MS, + SPACE_SCHEMA_VERSION, +} from "./schema.js"; export type SpaceIndexState = "pending" | "active" | "deleted"; @@ -163,6 +168,39 @@ export class SpaceIndexDurableObject extends DurableObject { }; } + /** + * Note blobs an imported space repo references but whose bytes have not + * been uploaded yet, so uploadBlob can promote them when they arrive. + */ + async rpcAddPendingBlobs(uri: string, cids: string[]): Promise { + await this.ensureInitialized(); + const now = Date.now(); + for (const cid of cids) { + this.sql.exec( + "INSERT OR REPLACE INTO pending_blob (cid, uri, created_at) VALUES (?, ?, ?)", + cid, + uri, + now, + ); + } + } + + /** + * Claim a freshly uploaded blob: the spaces whose imported records + * reference it. Claimed entries are removed. + */ + async rpcClaimPendingBlob(cid: string): Promise { + await this.ensureInitialized(); + const uris = this.sql + .exec("SELECT uri FROM pending_blob WHERE cid = ?", cid) + .toArray() + .map((row) => row.uri as string); + if (uris.length > 0) { + this.sql.exec("DELETE FROM pending_blob WHERE cid = ?", cid); + } + return uris; + } + /** Wipe the registry (spaces reset). */ async rpcDestroy(): Promise { await this.ctx.storage.deleteAlarm(); @@ -185,6 +223,10 @@ export class SpaceIndexDurableObject extends DurableObject { new Date().toISOString(), cutoff, ); + this.sql.exec( + "DELETE FROM pending_blob WHERE created_at < ?", + Date.now() - PENDING_BLOB_TTL_MS, + ); await this.ctx.storage.setAlarm(Date.now() + ALARM_INTERVAL_MS); } } diff --git a/packages/spaces/src/index.ts b/packages/spaces/src/index.ts index 8c6a48f..ad9ad02 100644 --- a/packages/spaces/src/index.ts +++ b/packages/spaces/src/index.ts @@ -28,6 +28,8 @@ export { export type { SpaceRef } from "./space-uri.js"; export { + promotePendingSpaceBlob, + promoteStagedBlobToSpace, spaceBlobKey, spaceBlobKeyForUri, spaceBlobPrefix, @@ -45,16 +47,33 @@ export type { } from "./routes.js"; export { + SPACE_AUDIENCE_HEADER, + SPACE_CREDENTIAL_SCHEME, isSpaceCredentialAuth, - unverifiedJwtTyp, - verifyDelegationAuth, + verifyDelegationToken, verifySpaceCredentialAuth, } from "./auth.js"; -export type { CheckReplay, GetSigningKey } from "./auth.js"; +export type { CheckReplay, CheckRevoked, GetSigningKey } from "./auth.js"; export { verifyClientAttestation } from "./attestation.js"; -export { signCommit, commitToJson, bytesToJson } from "./commit.js"; +export { + MAC_HEADER, + WANT_MAC_HEADER, + buildCommit, + bytesToJson, + commitToJson, + generateKemKey, + kemDidKey, +} from "./mac.js"; +export type { SpaceCommit } from "./mac.js"; + +export { + MEMBER_COLLECTION, + POLICY_COLLECTION, + PUBLISHED_COLLECTIONS, + normalizePolicy, +} from "./policy.js"; export { prepareRecord, recordBytesToJson } from "./records.js"; export type { PreparedRecord } from "./records.js"; @@ -69,18 +88,29 @@ export { export { createServiceJwt } from "./service-jwt.js"; export type { ServiceJwtParams } from "./service-jwt.js"; -export { nextRev, tidCutoff } from "./tid.js"; +export { nextRev, tidCutoff, tidTimestampMs } from "./tid.js"; +export { createDelegationToken, spaceHostAud } from "./tokens.js"; + +export { + MANAGEDSPACE_POLICY, + MEMBERSPACE_POLICY, + PERSONALSPACE_POLICY, +} from "./types.js"; export type { ApplyWritesResult, + ImportedRecord, NotifyItem, OplogEntry, PreparedSpaceWrite, + RepoCommitResult, RepoState, - SpaceAppAccess, - SpaceConfig, SpaceHostConfig, + SpaceMember, SpaceMeta, SpacePolicy, SpaceRecordRow, + SpaceSequence, + SpaceSigningKeypair, + SpaceWriter, } from "./types.js"; diff --git a/packages/spaces/src/mac.ts b/packages/spaces/src/mac.ts new file mode 100644 index 0000000..8ccefea --- /dev/null +++ b/packages/spaces/src/mac.ts @@ -0,0 +1,186 @@ +/** + * Commits and MACs. + * + * A space repo commit carries no signature. A syncer authenticates what a + * repo host serves with a MAC instead: it sends an ephemeral P-256 key share + * in `Atproto-Space-Want-Mac`, both sides derive a shared secret by ECDH + * against the account's `#atproto_kem` key, and the host returns an HMAC in + * `Atproto-Space-Mac`. A leaked response therefore proves nothing to a third + * party. The KEM key is the only secret here, and it lives with the Worker. + */ + +import { + COMMIT_MAC_TYPE, + MAC_HEADER as UPSTREAM_MAC_HEADER, + RECORD_MAC_TYPE, + RepoCommit, + SpaceMacError, + WANT_MAC_HEADER as UPSTREAM_WANT_MAC_HEADER, + computeCommitMac, + computeRecordMac, + decapsulate, + formatMacHeader, + parseWantMacHeader, +} from "@atproto/space"; +import type { Commit, MacType } from "@atproto/space"; +import { P256Keypair } from "@atproto/crypto"; +import { parseCid, toBase64 } from "@atproto/lex-data"; +import { SpaceError } from "./errors.js"; +import type { RepoState } from "./types.js"; + +export { COMMIT_MAC_TYPE, RECORD_MAC_TYPE }; +export type { MacType }; + +/** The request header a syncer asks for a MAC with. */ +export const WANT_MAC_HEADER: string = UPSTREAM_WANT_MAC_HEADER; +/** The response header carrying the MAC. */ +export const MAC_HEADER: string = UPSTREAM_MAC_HEADER; + +/** A space repo commit (`com.atproto.space.defs#commit`). */ +export interface SpaceCommit { + ver: number; + repo: string; + space: string; + rev: string; + /** sha256 digest of the LtHash state. */ + data: Uint8Array; +} + +/** The commit over a repo's persisted state. */ +export function buildCommit(params: { + spaceUri: string; + /** The repo author (the operator DID for every repo Cirrus serves). */ + repo: string; + state: RepoState; +}): SpaceCommit { + return RepoCommit.fromState(params.state.setHash).toCommit({ + space: params.spaceUri as never, + repo: params.repo as never, + rev: params.state.rev, + }); +} + +/** + * Lexicon JSON form of a commit (`com.atproto.space.defs#commit`): bytes + * fields encode as `{"$bytes": ""}`. + */ +export function commitToJson(commit: SpaceCommit): Record { + return { + ver: commit.ver, + repo: commit.repo, + space: commit.space, + rev: commit.rev, + data: bytesToJson(commit.data), + }; +} + +/** Lexicon JSON form of a bare bytes value. */ +export function bytesToJson(bytes: Uint8Array): { $bytes: string } { + return { $bytes: toBase64(bytes) }; +} + +/** Import the account's `#atproto_kem` keypair from its hex private key. */ +export async function importKemKeypair( + privateKeyHex: string, +): Promise { + return P256Keypair.import(privateKeyHex); +} + +/** Generate a fresh `#atproto_kem` keypair. */ +export async function generateKemKey(): Promise<{ + privateKeyHex: string; + /** The public key as a did:key. */ + didKey: string; + /** The public key multibase, for a DID document verification method. */ + publicKeyMultibase: string; +}> { + const keypair = await P256Keypair.create({ exportable: true }); + const exported = await keypair.export(); + const didKey = keypair.did(); + return { + privateKeyHex: Array.from(exported, (b) => + b.toString(16).padStart(2, "0"), + ).join(""), + didKey, + publicKeyMultibase: didKey.slice("did:key:".length), + }; +} + +/** The public half of a KEM private key, as a did:key. */ +export async function kemDidKey(privateKeyHex: string): Promise { + return (await importKemKeypair(privateKeyHex)).did(); +} + +export interface MacRequest { + /** The `Atproto-Space-Want-Mac` request header, if any. */ + wantMac: string | undefined; + /** Whether the request was authorised by a space credential. */ + credential: boolean; + type: MacType; + getKemKeypair: () => Promise; +} + +/** + * The shared secret for a response's MAC. A space credential must ask for + * one; an account reading its own data gets one only if it asks. Returns + * undefined when no MAC is owed. + */ +export async function macSecret( + req: MacRequest, +): Promise { + if (req.wantMac === undefined && !req.credential) return undefined; + let keyShare: string; + try { + keyShare = parseWantMacHeader(req.wantMac, req.type); + } catch (err) { + throw badMac(err); + } + const keypair = await req.getKemKeypair(); + if (!keypair) { + throw new SpaceError( + "KemKeyUnavailable", + "This host has no #atproto_kem key configured, so it cannot authenticate space data to syncers", + ); + } + try { + return decapsulate(keypair, keyShare); + } catch (err) { + throw badMac(err); + } +} + +function badMac(err: unknown): SpaceError { + if (err instanceof SpaceMacError) { + return new SpaceError("BadSpaceMac", err.message); + } + return new SpaceError("BadSpaceMac", "Invalid Atproto-Space-Want-Mac header"); +} + +/** The `Atproto-Space-Mac` header for a commit, when a MAC is owed. */ +export function commitMacHeaders( + secret: Uint8Array | undefined, + commit: SpaceCommit, +): Record { + if (!secret) return {}; + return { + [MAC_HEADER]: formatMacHeader( + COMMIT_MAC_TYPE, + computeCommitMac(secret, commit as Commit), + ), + }; +} + +/** The `Atproto-Space-Mac` header for a record, when a MAC is owed. */ +export function recordMacHeaders( + secret: Uint8Array | undefined, + uri: string, + cid: string, +): Record { + if (!secret) return {}; + return { + [MAC_HEADER]: formatMacHeader( + RECORD_MAC_TYPE, + computeRecordMac(secret, uri, parseCid(cid)), + ), + }; +} diff --git a/packages/spaces/src/policy.ts b/packages/spaces/src/policy.ts new file mode 100644 index 0000000..0c076e0 --- /dev/null +++ b/packages/spaces/src/policy.ts @@ -0,0 +1,161 @@ +/** + * Space policies: the three baseline policies every PDS supports, as + * `com.atproto.space.createSpace` / `updateSpace` take them. A policy is an + * open union discriminated by `$type` that both selects the policy and + * carries its configuration. + * + * What is stored is exactly what is enforced: {@link normalizePolicy} + * refuses a policy this host doesn't implement and fills in every default. + * Unknown fields are dropped, as Lexicon evolution allows. + */ + +import { SpaceError } from "./errors.js"; +import { + MANAGEDSPACE_POLICY, + MEMBERSPACE_POLICY, + PERSONALSPACE_POLICY, + type SpacePolicy, +} from "./types.js"; + +/** The collection a published policy record lives in (rkey `self`). */ +export const POLICY_COLLECTION = "com.atproto.space.policy"; +export const POLICY_RKEY = "self"; +/** The collection published member records live in (rkey = member DID). */ +export const MEMBER_COLLECTION = "com.atproto.memberspace.member"; +/** The collections the host publishes a space's configuration to. */ +export const PUBLISHED_COLLECTIONS: readonly string[] = [ + POLICY_COLLECTION, + MEMBER_COLLECTION, +]; + +const isBool = (value: unknown): value is boolean => typeof value === "boolean"; + +function optionalBool(input: Record, key: string): boolean { + const value = input[key]; + if (value === undefined) return false; + if (!isBool(value)) { + throw new SpaceError("InvalidRequest", `Policy ${key} must be a boolean`); + } + return value; +} + +/** Validate and normalise a policy from a request or an archive. */ +export function normalizePolicy(input: unknown): SpacePolicy { + if (!input || typeof input !== "object" || Array.isArray(input)) { + throw new SpaceError("InvalidRequest", "policy must be an object"); + } + const policy = input as Record; + switch (policy.$type) { + case PERSONALSPACE_POLICY: + return { $type: PERSONALSPACE_POLICY }; + case MEMBERSPACE_POLICY: { + const allowedApps = policy.allowedApps; + if ( + allowedApps !== undefined && + (!Array.isArray(allowedApps) || + allowedApps.some((app) => typeof app !== "string")) + ) { + throw new SpaceError( + "InvalidRequest", + "allowedApps must be an array of client IDs", + ); + } + return { + $type: MEMBERSPACE_POLICY, + publicRead: optionalBool(policy, "publicRead"), + publicWrite: optionalBool(policy, "publicWrite"), + ...(allowedApps !== undefined + ? { allowedApps: [...(allowedApps as string[])] } + : {}), + publishPolicy: optionalBool(policy, "publishPolicy"), + publishMembers: optionalBool(policy, "publishMembers"), + }; + } + case MANAGEDSPACE_POLICY: { + const managingApp = policy.managingApp; + if (typeof managingApp !== "string" || !managingApp.startsWith("did:")) { + throw new SpaceError( + "InvalidRequest", + "managingApp must be a DID with an optional service fragment", + ); + } + return { + $type: MANAGEDSPACE_POLICY, + managingApp, + publishPolicy: optionalBool(policy, "publishPolicy"), + }; + } + default: + throw new SpaceError( + "UnsupportedPolicy", + `Unsupported policy: ${String(policy.$type)}`, + ); + } +} + +/** The member list and its methods belong to the memberspace policy. */ +export function assertMemberspace( + policy: SpacePolicy, +): asserts policy is Extract< + SpacePolicy, + { $type: typeof MEMBERSPACE_POLICY } +> { + if (policy.$type !== MEMBERSPACE_POLICY) { + throw new SpaceError( + "PolicyMismatch", + "Space is not governed by the memberspace policy", + ); + } +} + +/** + * Whether any user may read. Only then can a credential be minted without + * a delegation token saying who the user is. + */ +export function isPublicRead(policy: SpacePolicy): boolean { + return policy.$type === MEMBERSPACE_POLICY && policy.publicRead; +} + +export function isPolicyPublished(policy: SpacePolicy): boolean { + return policy.$type !== PERSONALSPACE_POLICY && policy.publishPolicy; +} + +export function areMembersPublished(policy: SpacePolicy): boolean { + return policy.$type === MEMBERSPACE_POLICY && policy.publishMembers; +} + +/** + * Only memberspace restricts apps, against the attested client_id, so an + * app that presents no attestation is never one of the allowed apps. + */ +export function isAppAuthorized( + policy: SpacePolicy, + clientId: string | undefined, +): boolean { + if (policy.$type !== MEMBERSPACE_POLICY || !policy.allowedApps) return true; + return clientId !== undefined && policy.allowedApps.includes(clientId); +} + +/** + * A DID as a record key, for published member records. A record key can't + * contain `%`, so the percent-encoded port of a localhost did:web is left + * unencoded, as the reference does. Unambiguous because the unencoded form + * would otherwise be a did:web path, which atproto doesn't support. + */ +export function didToRecordKey(did: string): string { + return did.replace("%3A", ":"); +} + +export function recordKeyToDid(rkey: string): string { + return rkey.replace(/^(did:web:[^:]+):(\d+)$/, "$1%3A$2"); +} + +/** Records published from a space's configuration are the host's to write. */ +export function assertNotPublishedCollection(collection: string): void { + if (PUBLISHED_COLLECTIONS.includes(collection)) { + throw new SpaceError( + "InvalidRequest", + `${collection} records are published by the PDS from a space's configuration and cannot be written directly`, + ); + } +} diff --git a/packages/spaces/src/routes.ts b/packages/spaces/src/routes.ts index a9b57da..eeefc84 100644 --- a/packages/spaces/src/routes.ts +++ b/packages/spaces/src/routes.ts @@ -1,56 +1,121 @@ /** * Hono route factory for `com.atproto.space.*` and - * `com.atproto.simplespace.*`. + * `com.atproto.memberspace.*`. * * The factory is host-agnostic: everything account-specific — session * authentication, DID resolution, record validation, the operator identity - * — arrives through {@link SpaceRoutesHost}. The host mounts the returned - * app behind its feature flag. + * and its keys — arrives through {@link SpaceRoutesHost}. The host mounts + * the returned app behind its feature flag. */ import { Hono } from "hono"; import type { Context } from "hono"; -import { createSpaceToken, serializeRepo, spaceHostAud } from "@atproto/space"; -import type { SerializedRecord } from "@atproto/space"; -import type { Keypair } from "@atproto/crypto"; -import { fromBase64, parseCid } from "@atproto/lex-data"; +import { + createSpaceToken, + isP256DidKey, + readRepoStar, + readSpaceMetaStar, + serializeRepo, + serializeSpaceMeta, + spaceHostAud, +} from "@atproto/space"; +import type { P256Keypair } from "@atproto/crypto"; +import { encode } from "@atproto/lex-cbor"; +import { + cidForCbor, + enumBlobRefs, + fromBase64, + getBlobCidString, +} from "@atproto/lex-data"; +import type { LexValue } from "@atproto/lex-data"; import { now as tidNow } from "@atcute/tid"; import { isSpaceCredentialAuth, - verifyDelegationAuth, + verifyDelegationToken, verifySpaceCredentialAuth, - type CheckReplay, type GetSigningKey, } from "./auth.js"; import { verifyClientAttestation } from "./attestation.js"; -import { bytesToJson, commitToJson, signCommit } from "./commit.js"; +import { + COMMIT_MAC_TYPE, + MAC_HEADER, + RECORD_MAC_TYPE, + WANT_MAC_HEADER, + buildCommit, + bytesToJson, + commitMacHeaders, + commitToJson, + importKemKeypair, + macSecret, + recordMacHeaders, + type MacType, +} from "./mac.js"; import { SpaceError, parseSpaceErrorCode, spaceErrorStatus } from "./errors.js"; +import { + MEMBER_COLLECTION, + PUBLISHED_COLLECTIONS, + assertNotPublishedCollection, + didToRecordKey, + isAppAuthorized, + isPublicRead, + normalizePolicy, + recordKeyToDid, +} from "./policy.js"; import { prepareRecord, recordBytesToJson } from "./records.js"; +import { + MAX_REV_CLOCK_SKEW_MS, + MAX_SPACE_RECORD_BYTES, + NOTIFY_BACKOFF_BASE_MS, + NOTIFY_WRITE_RETRY_MS, +} from "./schema.js"; import { createServiceJwt } from "./service-jwt.js"; -import { spaceBlobPrefix, spaceBlobKey, stagedBlobKey } from "./blob-keys.js"; +import { + promoteStagedBlobToSpace, + spaceBlobKey, + spaceBlobPrefix, + stagedBlobKey, +} from "./blob-keys.js"; import { requireSpaceUri, spaceId, spaceRecordUri } from "./space-uri.js"; import type { SpaceRef } from "./space-uri.js"; +import { isRetryableStatus } from "./space-do.js"; import type { SpaceDurableObject } from "./space-do.js"; import type { SpaceIndexDurableObject } from "./index-do.js"; -import type { - NotifyItem, - PreparedSpaceWrite, - SpaceAppAccess, - SpaceConfig, - SpacePolicy, +import { tidTimestampMs } from "./tid.js"; +import { + MANAGEDSPACE_POLICY, + MEMBERSPACE_POLICY, + PERSONALSPACE_POLICY, + type ImportedRecord, + type NotifyItem, + type PreparedSpaceWrite, + type RepoCommitResult, + type SpaceMember, + type SpacePolicy, + type SpaceSigningKeypair, } from "./types.js"; const NOTIFY_WRITE_LXM = "com.atproto.space.notifyWrite"; const SPACE_DELETED_LXM = "com.atproto.space.notifySpaceDeleted"; -const CHECK_USER_ACCESS_LXM = "com.atproto.simplespace.checkUserAccess"; +const CREDENTIAL_REVOKED_LXM = "com.atproto.space.notifyCredentialRevoked"; +const CHECK_USER_ACCESS_LXM = "com.atproto.managedspace.checkUserAccess"; /** A managing app that doesn't answer within this window denies access. */ const CHECK_USER_ACCESS_TIMEOUT_MS = 5000; +/** The queue key for this repo's pending write notification to a foreign authority. */ +const NOTIFY_WRITE_COALESCE_KEY = "notifyWrite:authority"; +/** Upper bound on archives accepted by importRepo / importSpaceMeta. */ +const MAX_IMPORT_BYTES = 100 * 1024 * 1024; +/** Revocations are held until any credential they name has expired. */ +const REVOCATION_TTL_SEC = 3600 + 2 * 5; export type SpaceStub = DurableObjectStub; export type SpaceIndexStub = DurableObjectStub; /** The operation shapes checked against a session's `space:` grants. */ -export type SpaceScopeMatch = { type: string; authority: string; skey: string } & ( +export type SpaceScopeMatch = { + type: string; + authority: string; + skey: string; +} & ( | { action: "read" | "read_self" } | { action: "create" | "update" | "delete"; collection: string } | { manage: "create" | "update" | "delete" } @@ -70,23 +135,24 @@ export interface SpaceSessionAuth { export interface SpaceRoutesHost { operatorDid: string; - /** Public origin clients address, e.g. `https://pds.example.com`. */ - publicOrigin: string; /** R2 bucket for blobs; space blob endpoints 503 without it. */ blobs?: R2Bucket; - getKeypair(): Promise; - /** DID-doc signing key resolution for foreign issuers. */ - getSigningKey: GetSigningKey; + /** The account's `#atproto` keypair: space tokens and service auth. */ + getKeypair(): Promise; /** - * Resolve a service identifier (`did` or `did#fragment`) to an HTTPS - * endpoint, or null when unresolvable. + * The account's `#atproto_kem` P-256 private key (hex), which MACs space + * data for syncers. Null when unconfigured: reads that owe a MAC then + * answer KemKeyUnavailable. */ - resolveServiceEndpoint(service: string): Promise; + getKemPrivateKey(): string | null | Promise; + /** DID-doc `#atproto` key resolution for foreign issuers. */ + getSigningKey: GetSigningKey; /** - * Resolve a space authority's host endpoint: try - * `#atproto_space_host`, fall back to `#atproto_pds`. + * Resolve a service identifier to an HTTPS endpoint: `did#fragment` + * names that service entry, a bare DID its `#atproto_pds`. Null when + * unresolvable. */ - resolveAuthorityEndpoint(did: string): Promise; + resolveServiceEndpoint(service: string): Promise; /** Verify an inbound service-auth JWT bound to `lxm`. */ verifyServiceJwt( token: string, @@ -97,6 +163,12 @@ export interface SpaceRoutesHost { * Response for authentication failures. */ authenticate(c: Context): Promise; + /** + * Whether the operator's account is active. A deactivated authority + * issues no credentials and lists no repos. Treated as active when + * absent. + */ + isAccountActive?(): Promise; /** * Lexicon validation with the host's validator. Throws on invalid * records; the thrown message is surfaced as an InvalidRecord error. @@ -137,18 +209,34 @@ function waitUntil(c: Context, promise: Promise): void { } } -function replayChecker(stub: SpaceStub): CheckReplay { - return (kind, key, expiresAtSec) => stub.rpcCheckReplay(kind, key, expiresAtSec); +/** Request headers as a plain object with lower-cased names. */ +function headerRecord(c: Context): Record { + return Object.fromEntries(c.req.raw.headers); +} + +/** Append to a comma-separated response header without clobbering it. */ +function appendHeader(c: Context, name: string, value: string): void { + c.header(name, value, { append: true }); } interface AuthedRead { kind: "credential" | "session"; } +type ScopeResult = Response | null; + export function createSpaceRoutes(host: SpaceRoutesHost): Hono { const app = new Hono(); const doFetch: typeof fetch = host.outboundFetch ?? fetch; + let kemKeypair: Promise | null = null; + function getKemKeypair(): Promise { + kemKeypair ??= Promise.resolve(host.getKemPrivateKey()).then((hex) => + hex ? importKemKeypair(hex) : null, + ); + return kemKeypair; + } + /** The `repo` param on every repo-host method must be the operator DID. */ function requireRepoParam(repo: unknown): void { if (repo !== host.operatorDid) { @@ -159,14 +247,20 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { } } - const verifyOpts = (c: Context, stub: SpaceStub) => ({ - htm: c.req.method, - url: c.req.url, - publicOrigin: host.publicOrigin, - dpopProof: c.req.header("DPoP"), - getSigningKey: host.getSigningKey, - checkReplay: replayChecker(stub), - }); + /** + * Verify a space credential addressed to this host. Every audience is + * the operator DID: Cirrus serves only the operator's repos, and hosts + * only spaces under the operator's authority. + */ + async function credentialAuth(c: Context, ref: SpaceRef): Promise { + const stub = host.getSpaceDO(ref.uri); + await verifySpaceCredentialAuth(ref, { + headers: headerRecord(c), + audience: host.operatorDid, + getSigningKey: host.getSigningKey, + checkRevoked: (jti) => stub.rpcIsCredentialRevoked(jti), + }); + } /** * Authenticate a read: a space credential for the requested space, or a @@ -179,53 +273,49 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { ref: SpaceRef, repo: string | undefined, ): Promise { - if (repo !== host.operatorDid) { - throw new SpaceError("RepoNotFound", `Repository not found: ${repo}`); - } - const authHeader = c.req.header("Authorization"); - if (isSpaceCredentialAuth(authHeader)) { - const stub = host.getSpaceDO(ref.uri); - await verifySpaceCredentialAuth( - authHeader!.slice(5), - ref, - verifyOpts(c, stub), - ); + requireRepoParam(repo); + if (isSpaceCredentialAuth(c.req.header("Authorization"))) { + await credentialAuth(c, ref); return { kind: "credential" }; } const session = await host.authenticate(c); if (session instanceof Response) return session; - if (!session.fullTrust) { - const allowed = session.allowsSpace({ - type: ref.type, - authority: ref.authority, - skey: ref.skey, - action: "read_self", - }); - if (!allowed) { - return c.json( - { - error: "InsufficientScope", - message: "Token does not cover reading this space", - }, - 403, - ); - } - } + const scopeError = assertScope(c, session, { + type: ref.type, + authority: ref.authority, + skey: ref.skey, + action: "read_self", + }); + if (scopeError) return scopeError; return { kind: "session" }; } - /** Session-only auth for writes and management. */ - async function sessionAuth( + /** + * The MAC secret owed by a read that returns a commit or record, with + * the response headers a browser syncer needs to read the MAC. + */ + async function readMacSecret( c: Context, - ): Promise { - return host.authenticate(c); + auth: AuthedRead, + type: MacType, + ): Promise { + appendHeader(c, "Vary", WANT_MAC_HEADER); + const wantMac = c.req.header(WANT_MAC_HEADER); + if (wantMac === undefined && auth.kind !== "credential") return undefined; + appendHeader(c, "Access-Control-Expose-Headers", MAC_HEADER); + return await macSecret({ + wantMac, + credential: auth.kind === "credential", + type, + getKemKeypair, + }); } function assertScope( c: Context, session: SpaceSessionAuth, match: SpaceScopeMatch, - ): Response | null { + ): ScopeResult { if (session.fullTrust) return null; if (session.allowsSpace(match)) return null; return c.json( @@ -244,42 +334,86 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { } } + /** As assertSpaceHost, and the authority's account must be active. */ + async function assertActiveSpaceHost(ref: SpaceRef): Promise { + assertSpaceHost(ref); + if (host.isAccountActive && !(await host.isAccountActive())) { + throw new SpaceError( + "RepoDeactivated", + `Repo has been deactivated: ${ref.authority}`, + ); + } + } + + function assertOwner(ref: SpaceRef, session: SpaceSessionAuth): void { + assertSpaceHost(ref); + if (session.did !== ref.authority) { + throw new SpaceError( + "NotSpaceOwner", + "Only the space owner may manage the space", + ); + } + } + + /** The policy of a live space this host governs. */ + async function requirePolicy( + stub: SpaceStub, + ref: SpaceRef, + ): Promise { + const { meta, policy } = await stub.rpcGetAuthorityState(); + if (!meta || meta.deletedAt || !policy) { + throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}`); + } + return policy; + } + /** - * The simplespace user-access policy, applied at credential mint and to - * inbound notifyWrite writers. The authority itself always passes; a - * managing app that errors or times out denies. + * Whether a policy authorises a user to read or write. The authority + * always passes under every policy: it alone can reconfigure the space, + * so it must not be able to lock itself out. A managing app that errors + * or times out denies. */ - async function authorizeUser( - config: SpaceConfig, - ref: SpaceRef, - userDid: string, - clientId: string | undefined, - stub: SpaceStub, - ): Promise { + async function authorizeUser(params: { + policy: SpacePolicy; + ref: SpaceRef; + userDid: string; + access: "read" | "write"; + clientId?: string; + stub: SpaceStub; + }): Promise { + const { policy, ref, userDid, access, clientId, stub } = params; if (userDid === ref.authority) return true; - switch (config.policy.kind) { - case "public": - return true; - case "member-list": - return stub.rpcIsMember(userDid); - case "managing-app": { - const managingApp = config.policy.managingApp; + switch (policy.$type) { + case PERSONALSPACE_POLICY: + return false; + case MEMBERSPACE_POLICY: { + if (access === "read" ? policy.publicRead : policy.publicWrite) { + return true; + } + const member = await stub.rpcGetMember(userDid); + if (!member) return false; + return access === "read" ? member.read : member.write; + } + case MANAGEDSPACE_POLICY: { + const managingApp = policy.managingApp; try { const endpoint = await host.resolveServiceEndpoint(managingApp); if (!endpoint) return false; - const keypair = await host.getKeypair(); const token = await createServiceJwt( { iss: host.operatorDid, aud: managingApp, lxm: CHECK_USER_ACCESS_LXM, }, - keypair, + await host.getKeypair(), ); const url = new URL(`${endpoint}/xrpc/${CHECK_USER_ACCESS_LXM}`); url.searchParams.set("space", ref.uri); url.searchParams.set("user", userDid); - if (clientId) url.searchParams.set("clientId", clientId); + url.searchParams.set("access", access); + if (clientId && access === "read") { + url.searchParams.set("clientId", clientId); + } const res = await doFetch(url.toString(), { headers: { Authorization: `Bearer ${token}` }, signal: AbortSignal.timeout(CHECK_USER_ACCESS_TIMEOUT_MS), @@ -288,7 +422,8 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { const body = (await res.json()) as { authorized?: unknown }; return body.authorized === true; } catch { - // No decision caching in the alpha; unreachable app denies. + // Failing open would hand out credentials for the spaces that + // asked for the strictest gate. No decision caching in the alpha. return false; } } @@ -296,18 +431,22 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { } /** - * Ensure the space DO exists for a write. First write into a foreign - * space registers it `pending` in the index, initialises the DO as - * repo-host, then activates the entry. Spaces under the operator's own - * authority must have been created via simplespace first. + * Ensure the space DO exists for a write. The first write into a foreign + * space registers it `pending` in the index, initialises the DO as repo + * host, then activates the entry. The operator's own spaces must already + * exist: a write must neither conjure an ungoverned space nor revive a + * deleted one. */ - async function ensureSpaceForWrite(ref: SpaceRef, stub: SpaceStub): Promise { + async function ensureSpaceForWrite( + ref: SpaceRef, + stub: SpaceStub, + ): Promise { const meta = await stub.rpcGetMeta(); if (meta && !meta.deletedAt) return; if (ref.authority === host.operatorDid) { throw new SpaceError( "SpaceNotFound", - `Space not found: ${ref.uri}. Create it with com.atproto.simplespace.createSpace.`, + `Space not found: ${ref.uri}. Create it with com.atproto.space.createSpace.`, ); } const index = host.getIndexDO(); @@ -336,74 +475,94 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { async function promoteSpaceBlobs( ref: SpaceRef, blobCids: string[], - ): Promise { - if (!host.blobs || blobCids.length === 0) return; - const id = await spaceId(ref.uri); + ): Promise { + const missing: string[] = []; + if (!host.blobs || blobCids.length === 0) return missing; await Promise.all( blobCids.map(async (cid) => { - const destKey = spaceBlobKey(host.operatorDid, id, cid); - if (await host.blobs!.head(destKey)) return; - const staged = await host.blobs!.get( - stagedBlobKey(host.operatorDid, cid), + const present = await promoteStagedBlobToSpace( + host.blobs!, + host.operatorDid, + ref.uri, + cid, ); - if (!staged) return; - await host.blobs!.put(destKey, staged.body, { - httpMetadata: staged.httpMetadata, - }); + if (!present) missing.push(cid); }), ); + return missing; + } + + /** + * Fan a sequenced repo update out to the space's registered syncers. + * Reasonable-effort: a syncer that misses one notices the gap in + * prevSpaceRev and recovers through listRepos. + */ + async function fanOutWrite( + ref: SpaceRef, + stub: SpaceStub, + body: Record, + ): Promise { + const registrations = await stub.rpcGetActiveRegistrations(); + if (registrations.length === 0) return; + const items: NotifyItem[] = registrations.map((registration) => ({ + service: registration.service, + endpoint: registration.endpoint, + lxm: NOTIFY_WRITE_LXM, + body: { ...body, space: ref.uri }, + })); + await stub.rpcEnqueueNotify(items); } /** - * Step 8 of the write path: after the commit is applied, record the - * writer and fan out (own authority) or send one best-effort - * notifyWrite to the space's authority (foreign space). + * After a commit: the authority sequences its own update into the writer + * set and fans it out; a repo host in a foreign space delivers its + * latest state to the authority, immediately, persisting a retryable + * failure for the DO's alarm to retry for up to 24 hours. Retries + * coalesce, so only the newest revision is ever pending. */ async function postWrite( ref: SpaceRef, stub: SpaceStub, - rev: string, - hash: Uint8Array, + commit: RepoCommitResult, ): Promise { + const body = { + space: ref.uri, + repo: host.operatorDid, + repoRev: commit.rev, + data: bytesToJson(commit.data), + }; if (ref.authority === host.operatorDid) { - const { advanced } = await stub.rpcRecordWriter( + const sequence = await stub.rpcRecordWriter( host.operatorDid, - rev, - hash, + commit.rev, + commit.data, ); // Own writes always advance in practice; guard anyway so a // re-ordered background task never fans out stale state. - if (!advanced) return; - const registrations = await stub.rpcGetActiveRegistrations(); - if (registrations.length === 0) return; - const body = { - space: ref.uri, - repo: host.operatorDid, - rev, - hash: bytesToJson(hash), - }; - const items: NotifyItem[] = registrations.map((registration) => ({ - service: registration.service, - endpoint: registration.endpoint, - lxm: NOTIFY_WRITE_LXM, - body, - })); - await stub.rpcEnqueueNotify(items); + if (!sequence) return; + await fanOutWrite(ref, stub, { ...body, ...sequence }); + return; + } + + const endpoint = await host + .resolveServiceEndpoint(ref.authority) + .catch(() => null); + if (!endpoint) { + console.warn(`notifyWrite: no endpoint for ${ref.authority}`); return; } - // One attempt, logged on failure: notifications are best-effort and - // syncers self-heal, so a retry queue for the writer role is not - // worth its complexity. + const retry: NotifyItem = { + service: ref.authority, + endpoint, + lxm: NOTIFY_WRITE_LXM, + body, + coalesceKey: NOTIFY_WRITE_COALESCE_KEY, + deadline: Date.now() + NOTIFY_WRITE_RETRY_MS, + }; try { - const endpoint = await host.resolveAuthorityEndpoint(ref.authority); - if (!endpoint) { - console.warn(`notifyWrite: no endpoint for ${ref.authority}`); - return; - } - const keypair = await host.getKeypair(); const token = await createServiceJwt( { iss: host.operatorDid, aud: ref.authority, lxm: NOTIFY_WRITE_LXM }, - keypair, + await host.getKeypair(), ); const res = await doFetch(`${endpoint}/xrpc/${NOTIFY_WRITE_LXM}`, { method: "POST", @@ -411,21 +570,23 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, - body: JSON.stringify({ - space: ref.uri, - repo: host.operatorDid, - rev, - hash: bytesToJson(hash), - }), + body: JSON.stringify(body), + signal: AbortSignal.timeout(10_000), }); - if (!res.ok) { - console.warn( - `notifyWrite to ${ref.authority} failed: ${res.status}`, - ); + if (res.ok || !isRetryableStatus(res.status)) { + if (!res.ok) { + console.warn( + `notifyWrite to ${ref.authority} refused: ${res.status}; not retrying`, + ); + } + await stub.rpcClearNotify(NOTIFY_WRITE_COALESCE_KEY); + return; } + console.warn(`notifyWrite to ${ref.authority} failed: ${res.status}`); } catch (err) { console.warn(`notifyWrite to ${ref.authority} errored:`, err); } + await stub.rpcEnqueueNotify([retry], { delayMs: NOTIFY_BACKOFF_BASE_MS }); } interface WriteInput { @@ -472,6 +633,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { collection: write.collection, }); if (scopeError) return scopeError; + assertNotPublishedCollection(write.collection); if (write.action === "delete") { prepared.push({ @@ -502,6 +664,12 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { ); } const preparedRecord = await prepareRecord(validated.record); + if (preparedRecord.bytes.length > MAX_SPACE_RECORD_BYTES) { + throw new SpaceError( + "InvalidRequest", + `Record exceeds the maximum space record size of ${MAX_SPACE_RECORD_BYTES} bytes`, + ); + } for (const cid of preparedRecord.blobCids) blobCids.add(cid); prepared.push({ action: write.action, @@ -522,19 +690,27 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { await ensureSpaceForWrite(ref, stub); const result = await stub.rpcApplyWrites(prepared); - waitUntil(c, postWrite(ref, stub, result.rev, result.hash)); + waitUntil(c, postWrite(ref, stub, result)); return { rev: result.rev, results: result.results.map((r, i) => ({ ...r, - ...(statuses[i] !== undefined - ? { validationStatus: statuses[i] } - : {}), + ...(statuses[i] !== undefined ? { validationStatus: statuses[i] } : {}), })), }; } + /** Notify after a configuration change that published to the repo. */ + function afterConfigCommit( + c: Context, + ref: SpaceRef, + stub: SpaceStub, + commit: RepoCommitResult | null, + ): void { + if (commit) waitUntil(c, postWrite(ref, stub, commit)); + } + // --------------------------------------------------------------- // Write endpoints (repo host, session auth) // --------------------------------------------------------------- @@ -552,7 +728,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { const ref = requireSpaceUri(body.space); requireRepoParam(body.repo); requireString(body.collection, "collection"); - const session = await sessionAuth(c); + const session = await host.authenticate(c); if (session instanceof Response) return session; const result = await runWrites( c, @@ -601,7 +777,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { requireRepoParam(body.repo); requireString(body.collection, "collection"); requireString(body.rkey, "rkey"); - const session = await sessionAuth(c); + const session = await host.authenticate(c); if (session instanceof Response) return session; // Upsert: the scope asserted is the operation actually performed. @@ -657,19 +833,13 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { requireRepoParam(body.repo); requireString(body.collection, "collection"); requireString(body.rkey, "rkey"); - const session = await sessionAuth(c); + const session = await host.authenticate(c); if (session instanceof Response) return session; const result = await runWrites( c, ref, session, - [ - { - action: "delete", - collection: body.collection!, - rkey: body.rkey, - }, - ], + [{ action: "delete", collection: body.collection!, rkey: body.rkey }], undefined, ); if (result instanceof Response) return result; @@ -705,7 +875,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { if (body.writes.length > 200) { throw new SpaceError("InvalidRequest", "Too many writes. Max: 200"); } - const session = await sessionAuth(c); + const session = await host.authenticate(c); if (session instanceof Response) return session; const inputs: WriteInput[] = body.writes.map((write, i) => { @@ -764,6 +934,136 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { } }); + app.post("/xrpc/com.atproto.space.clearRecords", async (c) => { + try { + const body = await c.req.json<{ space?: string; repo?: string }>(); + const ref = requireSpaceUri(body.space); + requireString(body.repo, "repo"); + const session = await host.authenticate(c); + if (session instanceof Response) return session; + if (body.repo !== session.did) { + throw new SpaceError("Forbidden", "repo must match authenticated user"); + } + requireRepoParam(body.repo); + const stub = host.getSpaceDO(ref.uri); + const meta = await stub.rpcGetMeta(); + if (!meta || meta.deletedAt) return c.json({}); + + // In the authority's own repo the published policy and member + // records are the host's copy of the space's configuration, not + // the account's records, so they stay, and keeping them takes no + // grant. + const keep = + ref.authority === host.operatorDid ? [...PUBLISHED_COLLECTIONS] : []; + for (const collection of await stub.rpcListCollections()) { + if (keep.includes(collection)) continue; + const scopeError = assertScope(c, session, { + type: ref.type, + authority: ref.authority, + skey: ref.skey, + action: "delete", + collection, + }); + if (scopeError) return scopeError; + } + const commit = await stub.rpcClearRecords(keep); + if (commit) waitUntil(c, postWrite(ref, stub, commit)); + return c.json({}); + } catch (err) { + return errorResponse(c, err); + } + }); + + app.post("/xrpc/com.atproto.space.importRepo", async (c) => { + try { + const session = await host.authenticate(c); + if (session instanceof Response) return session; + const bytes = await readBody(c); + + let records: ImportedRecord[]; + let space: string; + let repo: string; + try { + const archive = await readRepoStar([bytes]); + try { + space = archive.commit.space; + repo = archive.commit.repo; + records = []; + for await (const record of archive.records) { + // Stored re-encoded, as any other write is. A record that + // wasn't canonical DRISL in the archive would no longer match + // its cid, nor the commit data. + const encoded = encode(record.record as LexValue); + const cid = await cidForCbor(encoded); + if (!cid.equals(record.cid)) { + throw new SpaceError( + "InvalidRequest", + `Invalid STAR: record is not canonical DRISL at ${record.collection}/${record.rkey}`, + ); + } + const blobCids: string[] = []; + for (const ref of enumBlobRefs(record.record as LexValue, { + strict: false, + })) { + blobCids.push(getBlobCidString(ref)); + } + records.push({ + collection: record.collection, + rkey: record.rkey, + cid: cid.toString(), + bytes: encoded, + blobCids, + }); + } + } finally { + await archive[Symbol.asyncDispose](); + } + } catch (err) { + throw invalidArchive(err); + } + + if (repo !== host.operatorDid || repo !== session.did) { + throw new SpaceError( + "InvalidRequest", + "Repo does not match the authenticated account", + ); + } + const ref = requireSpaceUri(space); + for (const collection of new Set(records.map((r) => r.collection))) { + const scopeError = assertScope(c, session, { + type: ref.type, + authority: ref.authority, + skey: ref.skey, + action: "create", + collection, + }); + if (scopeError) return scopeError; + } + + const stub = host.getSpaceDO(ref.uri); + if (ref.authority === host.operatorDid) { + // The authority's space must arrive first, via importSpaceMeta. + await requirePolicy(stub, ref); + } else { + await ensureSpaceForWrite(ref, stub); + } + await stub.rpcImportRepo(records); + + // Blobs are uploaded separately. Those already staged are promoted + // now; the rest are claimed by uploadBlob when they arrive. + const missing = await promoteSpaceBlobs( + ref, + Array.from(new Set(records.flatMap((r) => r.blobCids))), + ); + if (missing.length > 0) { + await host.getIndexDO().rpcAddPendingBlobs(ref.uri, missing); + } + return c.json({}); + } catch (err) { + return errorResponse(c, err); + } + }); + // --------------------------------------------------------------- // Read and sync endpoints (credential or session auth) // --------------------------------------------------------------- @@ -777,6 +1077,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { const rkey = c.req.query("rkey"); requireString(collection, "collection"); requireString(rkey, "rkey"); + const secret = await readMacSecret(c, auth, RECORD_MAC_TYPE); const stub = host.getSpaceDO(ref.uri); await requireRepoExists(stub, ref); @@ -788,11 +1089,11 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { `Could not locate record: ${uri}`, ); } - return c.json({ - uri, - cid: record.cid, - value: recordBytesToJson(record.bytes), - }); + return c.json( + { uri, cid: record.cid, value: recordBytesToJson(record.bytes) }, + 200, + recordMacHeaders(secret, uri, record.cid), + ); } catch (err) { return errorResponse(c, err); } @@ -843,6 +1144,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { const ref = requireSpaceUri(c.req.query("space")); const auth = await readAuth(c, ref, c.req.query("repo")); if (auth instanceof Response) return auth; + const secret = await readMacSecret(c, auth, COMMIT_MAC_TYPE); const stub = host.getSpaceDO(ref.uri); await requireRepoExists(stub, ref); const state = await stub.rpcGetRepoState(); @@ -852,19 +1154,16 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { `Could not find repo for space: ${ref.uri}`, ); } - const keypair = await host.getKeypair(); - const commit = await signCommit( - { - spaceUri: ref.uri, - author: host.operatorDid, - state: { - setHash: new Uint8Array(state.setHash), - rev: state.rev, - }, - }, - keypair, + const commit = buildCommit({ + spaceUri: ref.uri, + repo: host.operatorDid, + state: { setHash: new Uint8Array(state.setHash), rev: state.rev }, + }); + return c.json( + { commit: commitToJson(commit) }, + 200, + commitMacHeaders(secret, commit), ); - return c.json({ commit: commitToJson(commit) }); } catch (err) { return errorResponse(c, err); } @@ -879,6 +1178,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { const since = c.req.query("since"); const excludeValues = c.req.query("excludeValues") === "true"; const after = parseOpsCursor(c.req.query("cursor")); + const secret = await readMacSecret(c, auth, COMMIT_MAC_TYPE); const stub = host.getSpaceDO(ref.uri); await requireRepoExists(stub, ref); @@ -905,19 +1205,19 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { ...(last ? { cursor: `${last.rev}/${last.idx}` } : {}), }); } - const keypair = await host.getKeypair(); - const commit = await signCommit( - { - spaceUri: ref.uri, - author: host.operatorDid, - state: { - setHash: new Uint8Array(page.head.setHash), - rev: page.head.rev, - }, + const commit = buildCommit({ + spaceUri: ref.uri, + repo: host.operatorDid, + state: { + setHash: new Uint8Array(page.head.setHash), + rev: page.head.rev, }, - keypair, + }); + return c.json( + { ops, commit: commitToJson(commit) }, + 200, + commitMacHeaders(secret, commit), ); - return c.json({ ops, commit: commitToJson(commit) }); } catch (err) { return errorResponse(c, err); } @@ -928,95 +1228,59 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { const ref = requireSpaceUri(c.req.query("space")); const auth = await readAuth(c, ref, c.req.query("repo")); if (auth instanceof Response) return auth; - const excludeValues = c.req.query("excludeValues") === "true"; + const secret = await readMacSecret(c, auth, COMMIT_MAC_TYPE); const stub = host.getSpaceDO(ref.uri); await requireRepoExists(stub, ref); - // The commit signs one revision, so every record page must belong - // to it: each page reports the rev it was read at, and a page from - // a different rev restarts the export. Records are collected - // before signing (serializeRepo buffers anyway — see spec open - // questions), so the CAR always matches its commit. - let state: Awaited> = null; - let records: SerializedRecord[] | null = null; - for (let attempt = 0; attempt < 3 && !records; attempt++) { - state = await stub.rpcGetRepoState(); - if (!state) { - throw new SpaceError( - "RepoNotFound", - `Could not find repo for space: ${ref.uri}`, - ); - } - const collected: SerializedRecord[] = []; - let after: { collection: string; rkey: string } | undefined; - let fenced = true; + // The archive streams page by page. Each page reports the repo + // state it was read at; a page from a later state means a write + // landed mid-export, and the stream errors rather than serve + // records that don't match the commit. The syncer's verification + // would refuse such an archive anyway; failing loudly lets it + // retry at once. + const PAGE = 500; + const first = await stub.rpcListRecordsByPath({ limit: PAGE }); + const state = first.state; + if (!state) { + throw new SpaceError( + "RepoNotFound", + `Could not find repo for space: ${ref.uri}`, + ); + } + const commit = buildCommit({ + spaceUri: ref.uri, + repo: host.operatorDid, + state: { setHash: new Uint8Array(state.setHash), rev: state.rev }, + }); + async function* records() { + let page = first; for (;;) { - const page = await stub.rpcListRecords({ - limit: 500, - after, - reverse: true, // ascending - excludeValues: false, - }); - if (page.rev !== state.rev) { - // A write landed mid-export; retry from a fresh head. - fenced = false; - break; - } for (const record of page.records) { - collected.push({ - collection: record.collection, - rkey: record.rkey, - cid: parseCid(record.cid), - bytes: new Uint8Array(record.bytes!), - }); + yield { + collection: record.collection as never, + rkey: record.rkey as never, + bytes: new Uint8Array(record.bytes), + }; } const last = page.records[page.records.length - 1]; - if (!page.hasMore || !last) break; - after = { collection: last.collection, rkey: last.rkey }; + if (!page.hasMore || !last) return; + page = await stub.rpcListRecordsByPath({ + afterPath: `${last.collection}/${last.rkey}`, + limit: PAGE, + }); + if (page.state?.rev !== state!.rev) { + throw new Error("The repo changed during export; retry getRepo"); + } } - if (fenced) records = collected; - } - if (!records || !state) { - return c.json( - { - error: "ConcurrentModification", - message: - "The repo changed repeatedly during export; retry getRepo", - }, - 409, - ); } - - const keypair = await host.getKeypair(); - const commit = await signCommit( - { - spaceUri: ref.uri, - author: host.operatorDid, - state: { - setHash: new Uint8Array(state.setHash), - rev: state.rev, - }, - }, - keypair, + const star = serializeRepo( + commit as Parameters[0], + records(), ); - - const car = serializeRepo(commit, records, { excludeValues }); - const stream = new ReadableStream({ - async start(controller) { - try { - for await (const chunk of car) { - controller.enqueue(chunk); - } - controller.close(); - } catch (err) { - controller.error(err); - } - }, - }); - return new Response(stream, { - status: 200, - headers: { "Content-Type": "application/vnd.ipld.car" }, + return c.body(asyncIterableToStream(star), 200, { + "Content-Type": "application/octet-stream", + ...commitMacHeaders(secret, commit), }); } catch (err) { return errorResponse(c, err); @@ -1070,7 +1334,21 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { throw new SpaceError("BlobNotFound", `Blob not found: ${cid}`); } const key = spaceBlobKey(host.operatorDid, await spaceId(ref.uri), cid!); - const blob = await host.blobs.get(key); + let blob = await host.blobs.get(key); + if (!blob) { + // Referenced but never promoted (an imported record whose blob + // arrived through another path): promote on first read. + if ( + await promoteStagedBlobToSpace( + host.blobs, + host.operatorDid, + ref.uri, + cid!, + ) + ) { + blob = await host.blobs.get(key); + } + } if (!blob) { throw new SpaceError("BlobNotFound", `Blob not found: ${cid}`); } @@ -1083,7 +1361,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { // A shared cache in front of the PDS must never store a // response whose authorisation was per-credential. "Cache-Control": "private, no-store", - Vary: "Authorization, DPoP", + Vary: "Authorization", "X-Content-Type-Options": "nosniff", "Content-Disposition": `attachment; filename="${cid}"`, "Content-Security-Policy": "default-src 'none'; sandbox", @@ -1102,84 +1380,89 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { try { const body = await c.req.json<{ space?: string; + credentialKid?: string; + delegationToken?: string; clientAttestation?: string; }>(); const ref = requireSpaceUri(body.space); - assertSpaceHost(ref); - - const authHeader = c.req.header("Authorization"); - if (!authHeader?.startsWith("Bearer ")) { + requireString(body.credentialKid, "credentialKid"); + if (!isP256DidKey(body.credentialKid!)) { throw new SpaceError( - "InvalidDelegationToken", - "Expected a Bearer delegation token", + "InvalidRequest", + "credentialKid must be a P-256 did:key", ); } const stub = host.getSpaceDO(ref.uri); - const delegation = await verifyDelegationAuth( - authHeader.slice(7), - ref, - verifyOpts(c, stub), - ); - const { meta, config } = await stub.rpcGetAuthorityState(); - if (meta?.deletedAt) { - // The durable signal that a space is gone: a syncer that missed - // notifySpaceDeleted learns to drop its copy here. - throw new SpaceError("SpaceDeleted", `Space deleted: ${ref.uri}`); - } - if (!meta || !config) { - throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}`); + // Absent when the request carries no delegation token, which only a + // space that does not gate on the user accepts. + let userDid: string | undefined; + if (body.delegationToken) { + ({ userDid } = await verifyDelegationToken(body.delegationToken, ref, { + getSigningKey: host.getSigningKey, + checkReplay: (kind, key, exp) => stub.rpcCheckReplay(kind, key, exp), + })); } - // App perimeter first, so a refused app is never disclosed to a - // third-party managing app. + await assertActiveSpaceHost(ref); + const { meta, policy } = await stub.rpcGetAuthorityState(); + let clientId: string | undefined; - if (config.appAccess.kind === "allowList") { - if (!body.clientAttestation) { - throw new SpaceError( - "AppNotAuthorized", - "This space requires a client attestation", - ); - } + if (body.clientAttestation) { clientId = await verifyClientAttestation(body.clientAttestation, { expectedAud: spaceHostAud(ref.authority), - // Checked pre-verification inside so a non-allowlisted - // client never triggers network I/O. - allowedClientIds: config.appAccess.allowed, - checkReplay: replayChecker(stub), + // Checked pre-verification inside, so a client the space could + // never authorise never triggers network I/O. + allowedClientIds: + policy?.$type === MEMBERSPACE_POLICY + ? policy.allowedApps + : undefined, + checkReplay: (kind, key, exp) => stub.rpcCheckReplay(kind, key, exp), fetch: host.outboundFetch, }); - if (!config.appAccess.allowed.includes(clientId)) { - throw new SpaceError( - "AppNotAuthorized", - "App is not authorized for this space", - ); - } } - const authorized = await authorizeUser( - config, - ref, - delegation.userDid, - clientId, - stub, - ); - if (!authorized) { - throw new SpaceError( - "UserNotAuthorized", - "User is not authorized for this space", - ); + // The durable signal that a space is gone: a syncer that missed + // notifySpaceDeleted learns it here, on its next renewal, with or + // without a delegation token. + if (meta?.deletedAt) { + throw new SpaceError("SpaceDeleted", `Space deleted: ${ref.uri}`); + } + if (!meta || !policy) { + throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}`); + } + + // The user goes first, and a user the policy refuses is answered as + // though the space does not exist, so that a refusal discloses + // nothing to someone without access to it. + const userAuthorized = userDid + ? await authorizeUser({ + policy, + ref, + userDid, + access: "read", + clientId, + stub, + }) + : isPublicRead(policy); + if (!userAuthorized) { + throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}`); + } + if (!isAppAuthorized(policy, clientId)) { + throw new SpaceError( + "AppNotAuthorized", + "Application not authorized for this space", + ); } - const keypair = await host.getKeypair(); const credential = await createSpaceToken( "credential", { iss: host.operatorDid, sub: ref.uri, - dpopJkt: delegation.dpopJkt, + keyId: body.credentialKid as `did:${string}:${string}`, }, - keypair, + (await host.getKeypair()) as Parameters[2], ); return c.json({ credential }); } catch (err) { @@ -1190,33 +1473,26 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { app.get("/xrpc/com.atproto.space.listRepos", async (c) => { try { const ref = requireSpaceUri(c.req.query("space")); - assertSpaceHost(ref); - const authHeader = c.req.header("Authorization"); - if (!isSpaceCredentialAuth(authHeader)) { - throw new SpaceError( - "InvalidCredential", - "listRepos requires a space credential", - ); - } + await credentialAuth(c, ref); + await assertActiveSpaceHost(ref); const stub = host.getSpaceDO(ref.uri); - await verifySpaceCredentialAuth( - authHeader!.slice(5), - ref, - verifyOpts(c, stub), - ); - const limit = clampLimit(c.req.query("limit"), 100, 1000); - const page = await stub.rpcListWriters({ + await requirePolicy(stub, ref); + const limit = clampLimit(c.req.query("limit"), 500, 1000); + const writers = await stub.rpcListWriters({ limit, - afterDid: c.req.query("cursor"), + cursor: c.req.query("cursor") || undefined, }); - const last = page.repos[page.repos.length - 1]; + const last = writers[writers.length - 1]; return c.json({ - repos: page.repos.map((repo) => ({ - did: repo.did, - rev: repo.rev, - hash: bytesToJson(new Uint8Array(repo.hash)), + repos: writers.map((writer) => ({ + did: writer.did, + repoRev: writer.repoRev, + data: bytesToJson(new Uint8Array(writer.data)), + spaceRev: writer.spaceRev, })), - ...(page.hasMore && last ? { cursor: last.did } : {}), + // As with sync.listRepos, nonempty pages carry a cursor and + // empty pages omit it. + ...(last ? { cursor: last.spaceRev } : {}), }); } catch (err) { return errorResponse(c, err); @@ -1227,29 +1503,18 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { try { const body = await c.req.json<{ space?: string; service?: string }>(); const ref = requireSpaceUri(body.space); - assertSpaceHost(ref); requireString(body.service, "service"); - const authHeader = c.req.header("Authorization"); - if (!isSpaceCredentialAuth(authHeader)) { - throw new SpaceError( - "InvalidCredential", - "registerNotify requires a space credential", - ); - } - const stub = host.getSpaceDO(ref.uri); - await verifySpaceCredentialAuth( - authHeader!.slice(5), - ref, - verifyOpts(c, stub), - ); + await credentialAuth(c, ref); + assertSpaceHost(ref); // Resolve now and store both, so fan-out never resolves DIDs. const endpoint = await host.resolveServiceEndpoint(body.service!); if (!endpoint) { throw new SpaceError( "ServiceNotResolvable", - `Could not resolve service: ${body.service}`, + `Could not resolve a service endpoint for ${body.service}`, ); } + const stub = host.getSpaceDO(ref.uri); const result = await stub.rpcRegisterNotify(body.service!, endpoint); return c.json({ expiresAt: result.expiresAt }); } catch (err) { @@ -1261,24 +1526,12 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { try { const body = await c.req.json<{ space?: string; service?: string }>(); const ref = requireSpaceUri(body.space); - assertSpaceHost(ref); requireString(body.service, "service"); - const authHeader = c.req.header("Authorization"); - if (!isSpaceCredentialAuth(authHeader)) { - throw new SpaceError( - "InvalidCredential", - "unregisterNotify requires a space credential", - ); - } - const stub = host.getSpaceDO(ref.uri); - await verifySpaceCredentialAuth( - authHeader!.slice(5), - ref, - verifyOpts(c, stub), - ); + await credentialAuth(c, ref); + assertSpaceHost(ref); // No endpoint resolution: a subscriber whose DID doc changed must // still be able to withdraw. Idempotent. - await stub.rpcUnregisterNotify(body.service!); + await host.getSpaceDO(ref.uri).rpcUnregisterNotify(body.service!); return c.json({}); } catch (err) { return errorResponse(c, err); @@ -1290,109 +1543,80 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { const body = await c.req.json<{ space?: string; repo?: string; - rev?: string; - hash?: { $bytes?: string }; + repoRev?: string; + data?: { $bytes?: string }; }>(); const ref = requireSpaceUri(body.space); - assertSpaceHost(ref); requireString(body.repo, "repo"); - requireString(body.rev, "rev"); - if (typeof body.hash?.$bytes !== "string") { - throw new SpaceError("InvalidRequest", "Missing hash bytes"); + requireString(body.repoRev, "repoRev"); + if (typeof body.data?.$bytes !== "string") { + throw new SpaceError("InvalidRequest", "Missing data bytes"); } - const authHeader = c.req.header("Authorization"); - if (!authHeader?.startsWith("Bearer ")) { - return c.json( - { - error: "AuthenticationRequired", - message: "Service auth required", - }, - 401, - ); - } - const serviceAuth = await host.verifyServiceJwt( - authHeader.slice(7), - NOTIFY_WRITE_LXM, - ); + const serviceAuth = await requireServiceAuth(c, NOTIFY_WRITE_LXM); + if (serviceAuth instanceof Response) return serviceAuth; + // iss is the signer, so requiring it to match keeps a PDS from + // notifying on another account's behalf. if (serviceAuth.iss !== body.repo) { - return c.json( - { - error: "Forbidden", - message: "notifyWrite iss does not match claimed writer", - }, - 403, + throw new SpaceError( + "Forbidden", + "notifyWrite iss does not match claimed writer", ); } - // The reference checks the bare DID as audience, not the - // #atproto_space_host fragment, and we match it. - if (serviceAuth.aud !== host.operatorDid) { - return c.json( - { - error: "Forbidden", - message: "notifyWrite aud does not match the space authority", - }, - 403, + if ( + serviceAuth.aud !== ref.authority && + serviceAuth.aud !== spaceHostAud(ref.authority) + ) { + throw new SpaceError( + "Forbidden", + "notifyWrite aud does not match the space authority", ); } - const stub = host.getSpaceDO(ref.uri); - const { meta, config } = await stub.rpcGetAuthorityState(); - if (!meta || meta.deletedAt || !config) { - // Silently ignore notifications for spaces this host does not - // (or no longer) governs. - return c.json({}); + assertSpaceHost(ref); + let revMs: number; + try { + revMs = tidTimestampMs(body.repoRev!); + } catch { + throw new SpaceError("InvalidRequest", "repoRev must be a TID"); + } + if (revMs > Date.now() + MAX_REV_CLOCK_SKEW_MS) { + throw new SpaceError("FutureRev", "Repo revision is in the future"); } - const authorized = await authorizeUser( - config, + + const stub = host.getSpaceDO(ref.uri); + const policy = await requirePolicy(stub, ref); + // The same user perimeter used when minting credentials. notifyWrite + // comes from a PDS rather than an app, so there is no attestation. + const authorized = await authorizeUser({ + policy, ref, - body.repo!, - undefined, + userDid: body.repo!, + access: "write", stub, - ); + }); if (!authorized) { - return c.json( - { - error: "Forbidden", - message: "notifyWrite writer is not authorized", - }, - 403, + throw new SpaceError( + "Forbidden", + "notifyWrite writer is not authorized", ); } - const hash = fromBase64(body.hash.$bytes); - const { advanced } = await stub.rpcRecordWriter( + const data = fromBase64(body.data.$bytes); + const sequence = await stub.rpcRecordWriter( body.repo!, - body.rev!, - hash, + body.repoRev!, + data, ); // A delayed or replayed notification carrying an older rev did not // change the writer set; do not fan stale state out again. - if (!advanced) { - return c.json({}); - } - - // Fan out to every registration except the sender. - const registrations = await stub.rpcGetActiveRegistrations(); - const senderDid = body.repo!; - const targets = registrations.filter( - (registration) => registration.service.split("#")[0] !== senderDid, - ); - if (targets.length > 0) { - const notifyBody = { - space: ref.uri, + if (sequence) { + await fanOutWrite(ref, stub, { repo: body.repo!, - rev: body.rev!, - hash: body.hash, - }; - await stub.rpcEnqueueNotify( - targets.map((registration) => ({ - service: registration.service, - endpoint: registration.endpoint, - lxm: NOTIFY_WRITE_LXM, - body: notifyBody, - })), - ); + repoRev: body.repoRev!, + data: body.data, + ...sequence, + }); } return c.json({}); } catch (err) { @@ -1404,29 +1628,13 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { try { const body = await c.req.json<{ space?: string }>(); const ref = requireSpaceUri(body.space); - - const authHeader = c.req.header("Authorization"); - if (!authHeader?.startsWith("Bearer ")) { - return c.json( - { - error: "AuthenticationRequired", - message: "Service auth required", - }, - 401, - ); - } - const serviceAuth = await host.verifyServiceJwt( - authHeader.slice(7), - SPACE_DELETED_LXM, - ); + const serviceAuth = await requireServiceAuth(c, SPACE_DELETED_LXM); + if (serviceAuth instanceof Response) return serviceAuth; // Only the space's authority may tell us to drop our copy. if (serviceAuth.iss !== ref.authority) { - return c.json( - { - error: "Forbidden", - message: "notifySpaceDeleted iss is not the space authority", - }, - 403, + throw new SpaceError( + "Forbidden", + "notifySpaceDeleted iss is not the space authority", ); } // And only when the notification was addressed to us: without the @@ -1434,16 +1642,10 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { // service could be replayed here to tombstone our repo and delete // its blobs. Registrations use service identifiers, so accept the // bare DID or any of our own #fragment forms. - if ( - serviceAuth.aud !== host.operatorDid && - !serviceAuth.aud.startsWith(`${host.operatorDid}#`) - ) { - return c.json( - { - error: "Forbidden", - message: "notifySpaceDeleted aud does not match this service", - }, - 403, + if (!isOwnAudience(serviceAuth.aud)) { + throw new SpaceError( + "Forbidden", + "notifySpaceDeleted aud does not match this service", ); } if (ref.authority === host.operatorDid) { @@ -1472,36 +1674,79 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { } }); + app.post("/xrpc/com.atproto.space.notifyCredentialRevoked", async (c) => { + try { + const body = await c.req.json<{ + space?: string; + credentials?: unknown; + }>(); + const ref = requireSpaceUri(body.space); + const credentials = body.credentials; + if ( + !Array.isArray(credentials) || + credentials.length < 1 || + credentials.length > 100 || + credentials.some((jti) => typeof jti !== "string" || jti.length === 0) + ) { + throw new SpaceError( + "InvalidRequest", + "credentials must be 1 to 100 credential jti strings", + ); + } + const serviceAuth = await requireServiceAuth(c, CREDENTIAL_REVOKED_LXM); + if (serviceAuth instanceof Response) return serviceAuth; + if (serviceAuth.iss !== ref.authority) { + throw new SpaceError( + "Forbidden", + "Revocation issuer is not the space authority", + ); + } + // Addressed to the repo DID, which here is always the operator. + if (serviceAuth.aud !== host.operatorDid) { + throw new SpaceError( + "Forbidden", + "Revocation audience does not match a repo hosted here", + ); + } + await host + .getSpaceDO(ref.uri) + .rpcRevokeCredentials( + credentials as string[], + Math.floor(Date.now() / 1000) + REVOCATION_TTL_SEC, + ); + return c.json({}); + } catch (err) { + return errorResponse(c, err); + } + }); + // --------------------------------------------------------------- - // simplespace management (authority role, session auth) + // Space management (authority role, session auth) // --------------------------------------------------------------- - app.post("/xrpc/com.atproto.simplespace.createSpace", async (c) => { + app.post("/xrpc/com.atproto.space.createSpace", async (c) => { try { const body = await c.req.json<{ - type?: string; + spaceType?: string; skey?: string; policy?: unknown; - appAccess?: unknown; }>(); - requireString(body.type, "type"); + requireString(body.spaceType, "spaceType"); const skey = body.skey ?? tidNow(); - const session = await sessionAuth(c); + const ref = requireSpaceUri( + `at://${host.operatorDid}/space/${body.spaceType}/${skey}`, + ); + const session = await host.authenticate(c); if (session instanceof Response) return session; const scopeError = assertScope(c, session, { - type: body.type!, + type: ref.type, authority: host.operatorDid, - skey, + skey: ref.skey, manage: "create", }); if (scopeError) return scopeError; - - const config: SpaceConfig = { - policy: parsePolicy(body.policy), - appAccess: parseAppAccess(body.appAccess), - }; - const uri = `at://${host.operatorDid}/space/${body.type}/${skey}`; - const ref = requireSpaceUri(uri); + await assertActiveSpaceHost(ref); + const policy = normalizePolicy(body.policy); // Two-step creation: index entry `pending`, then the DO, then // `active`. Reads never depend on the index, so a crash between @@ -1515,32 +1760,28 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { isAuthority: true, }); const stub = host.getSpaceDO(ref.uri); - await stub.rpcInit({ + const commit = await stub.rpcInit({ uri: ref.uri, authority: ref.authority, type: ref.type, skey: ref.skey, isAuthority: true, - config, + policy, }); await index.rpcActivate(ref.uri); + afterConfigCommit(c, ref, stub, commit); return c.json({ uri: ref.uri }); } catch (err) { return errorResponse(c, err); } }); - app.post("/xrpc/com.atproto.simplespace.updateSpace", async (c) => { + app.post("/xrpc/com.atproto.space.updateSpace", async (c) => { try { - const body = await c.req.json<{ - space?: string; - policy?: unknown; - appAccess?: unknown; - }>(); + const body = await c.req.json<{ space?: string; policy?: unknown }>(); const ref = requireSpaceUri(body.space); - const session = await sessionAuth(c); + const session = await host.authenticate(c); if (session instanceof Response) return session; - assertOwner(ref, session); const scopeError = assertScope(c, session, { type: ref.type, authority: ref.authority, @@ -1548,28 +1789,24 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { manage: "update", }); if (scopeError) return scopeError; + assertOwner(ref, session); + await assertActiveSpaceHost(ref); + const policy = normalizePolicy(body.policy); const stub = host.getSpaceDO(ref.uri); - await stub.rpcUpdateConfig({ - ...(body.policy !== undefined - ? { policy: parsePolicy(body.policy) } - : {}), - ...(body.appAccess !== undefined - ? { appAccess: parseAppAccess(body.appAccess) } - : {}), - }); + const commit = await stub.rpcUpdatePolicy(policy); + afterConfigCommit(c, ref, stub, commit); return c.json({}); } catch (err) { return errorResponse(c, err); } }); - app.post("/xrpc/com.atproto.simplespace.deleteSpace", async (c) => { + app.post("/xrpc/com.atproto.space.deleteSpace", async (c) => { try { const body = await c.req.json<{ space?: string }>(); const ref = requireSpaceUri(body.space); - const session = await sessionAuth(c); + const session = await host.authenticate(c); if (session instanceof Response) return session; - assertOwner(ref, session); const scopeError = assertScope(c, session, { type: ref.type, authority: ref.authority, @@ -1577,12 +1814,15 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { manage: "delete", }); if (scopeError) return scopeError; + assertOwner(ref, session); + await assertActiveSpaceHost(ref); const stub = host.getSpaceDO(ref.uri); const { registrations } = await stub.rpcDeleteSpace(); await host.getIndexDO().rpcMarkDeleted(ref.uri); - // Stop credential issuance happened with the tombstone; tell every - // registered syncer to drop its copy, then reap the blob prefix. + // Credential issuance stopped with the tombstone. Tell every + // registered syncer to drop its copy, retrying until delivered or + // the registration expires, then reap the blob prefix. if (registrations.length > 0) { await stub.rpcEnqueueNotify( registrations.map((registration) => ({ @@ -1590,6 +1830,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { endpoint: registration.endpoint, lxm: SPACE_DELETED_LXM, body: { space: ref.uri }, + deadline: Date.parse(registration.expiresAt), })), ); } @@ -1604,31 +1845,37 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { } return c.json({}); } catch (err) { - // deleteSpace is idempotent: a second delete of a tombstoned space - // (or a never-created one) reports SpaceNotFound per the lexicon. return errorResponse(c, err); } }); - app.post("/xrpc/com.atproto.simplespace.addMember", async (c) => { - return memberChange(c, "add"); - }); - - app.post("/xrpc/com.atproto.simplespace.removeMember", async (c) => { - return memberChange(c, "remove"); + app.get("/xrpc/com.atproto.space.getSpace", async (c) => { + try { + const ref = requireSpaceUri(c.req.query("space")); + const session = await host.authenticate(c); + if (session instanceof Response) return session; + const scopeError = assertScope(c, session, { + type: ref.type, + authority: ref.authority, + skey: ref.skey, + action: "read_self", + }); + if (scopeError) return scopeError; + assertOwner(ref, session); + const policy = await requirePolicy(host.getSpaceDO(ref.uri), ref); + return c.json({ uri: ref.uri, policy }); + } catch (err) { + return errorResponse(c, err); + } }); - async function memberChange( - c: Context, - op: "add" | "remove", - ): Promise { + app.post("/xrpc/com.atproto.space.removeWriter", async (c) => { try { const body = await c.req.json<{ space?: string; did?: string }>(); const ref = requireSpaceUri(body.space); - requireString(body.did, "did"); - const session = await sessionAuth(c); + requireDid(body.did, "did"); + const session = await host.authenticate(c); if (session instanceof Response) return session; - assertOwner(ref, session); const scopeError = assertScope(c, session, { type: ref.type, authority: ref.authority, @@ -1636,104 +1883,243 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { manage: "update", }); if (scopeError) return scopeError; - const stub = host.getSpaceDO(ref.uri); - await requireConfigured(stub, ref); - if (op === "add") { - await stub.rpcAddMember(body.did!); - } else { - await stub.rpcRemoveMember(body.did!); - } + assertOwner(ref, session); + await assertActiveSpaceHost(ref); + await host.getSpaceDO(ref.uri).rpcRemoveWriter(body.did!); return c.json({}); } catch (err) { return errorResponse(c, err); } - } + }); - app.get("/xrpc/com.atproto.simplespace.getSpace", async (c) => { + app.get("/xrpc/com.atproto.space.exportSpaceMeta", async (c) => { try { const ref = requireSpaceUri(c.req.query("space")); - assertSpaceHost(ref); - const stub = host.getSpaceDO(ref.uri); + const session = await host.authenticate(c); + if (session instanceof Response) return session; + const scopeError = assertScope(c, session, { + type: ref.type, + authority: ref.authority, + skey: ref.skey, + action: "read_self", + }); + if (scopeError) return scopeError; + assertOwner(ref, session); + const exported = await host.getSpaceDO(ref.uri).rpcExportMeta(); + const star = serializeSpaceMeta({ + space: ref.uri as never, + policy: exported.policy as never, + policyState: exported.members.map((member) => ({ + key: `${MEMBER_COLLECTION}/${didToRecordKey(member.did)}`, + value: { + $type: MEMBER_COLLECTION, + read: member.read, + write: member.write, + }, + })), + writers: exported.writers.map((writer) => ({ + did: writer.did as never, + rev: writer.repoRev, + data: new Uint8Array(writer.data), + spaceRev: writer.spaceRev, + })), + }); + return c.body(asyncIterableToStream(star), 200, { + "Content-Type": "application/octet-stream", + }); + } catch (err) { + return errorResponse(c, err); + } + }); - const authHeader = c.req.header("Authorization"); - if (isSpaceCredentialAuth(authHeader)) { - await verifySpaceCredentialAuth( - authHeader!.slice(5), - ref, - verifyOpts(c, stub), - ); - } else { - const session = await sessionAuth(c); - if (session instanceof Response) return session; + app.post("/xrpc/com.atproto.space.importSpaceMeta", async (c) => { + try { + const session = await host.authenticate(c); + if (session instanceof Response) return session; + const bytes = await readBody(c); + let archive; + try { + archive = await readSpaceMetaStar([bytes]); + } catch (err) { + throw invalidArchive(err); + } + const ref = requireSpaceUri(archive.space); + // Importing both creates the space here and sets its configuration. + for (const manage of ["create", "update"] as const) { const scopeError = assertScope(c, session, { type: ref.type, authority: ref.authority, skey: ref.skey, - action: "read_self", + manage, }); if (scopeError) return scopeError; } + if (ref.authority !== session.did || ref.authority !== host.operatorDid) { + throw new SpaceError("NotSpaceOwner", "Not the space owner"); + } + const policy = normalizePolicy(archive.policy); + const members = parsePolicyState(policy, archive.policyState); - const config = await requireConfigured(stub, ref); - return c.json({ + const index = host.getIndexDO(); + await index.rpcRegister({ uri: ref.uri, - policy: policyToJson(config.policy), - appAccess: appAccessToJson(config.appAccess), + authority: ref.authority, + type: ref.type, + skey: ref.skey, + isAuthority: true, + }); + await host.getSpaceDO(ref.uri).rpcImportMeta({ + uri: ref.uri, + authority: ref.authority, + type: ref.type, + skey: ref.skey, + policy, + members, + writers: archive.writers.map((writer) => ({ + did: writer.did, + repoRev: writer.rev, + data: writer.data, + spaceRev: writer.spaceRev, + })), }); + await index.rpcActivate(ref.uri); + return c.json({}); } catch (err) { return errorResponse(c, err); } }); - app.get("/xrpc/com.atproto.simplespace.listMembers", async (c) => { + // --------------------------------------------------------------- + // memberspace (authority role, session auth) + // --------------------------------------------------------------- + + app.post("/xrpc/com.atproto.memberspace.putMember", async (c) => { try { - const ref = requireSpaceUri(c.req.query("space")); - const session = await sessionAuth(c); + const body = await c.req.json<{ + space?: string; + did?: string; + read?: unknown; + write?: unknown; + }>(); + const ref = requireSpaceUri(body.space); + requireDid(body.did, "did"); + if (typeof body.read !== "boolean" || typeof body.write !== "boolean") { + throw new SpaceError( + "InvalidRequest", + "read and write must be booleans", + ); + } + const session = await host.authenticate(c); if (session instanceof Response) return session; + const scopeError = assertScope(c, session, { + type: ref.type, + authority: ref.authority, + skey: ref.skey, + manage: "update", + }); + if (scopeError) return scopeError; assertOwner(ref, session); + await assertActiveSpaceHost(ref); + const stub = host.getSpaceDO(ref.uri); + const commit = await stub.rpcPutMember(body.did!, { + read: body.read, + write: body.write, + }); + afterConfigCommit(c, ref, stub, commit); + return c.json({}); + } catch (err) { + return errorResponse(c, err); + } + }); + + app.post("/xrpc/com.atproto.memberspace.removeMember", async (c) => { + try { + const body = await c.req.json<{ space?: string; did?: string }>(); + const ref = requireSpaceUri(body.space); + requireDid(body.did, "did"); + const session = await host.authenticate(c); + if (session instanceof Response) return session; const scopeError = assertScope(c, session, { type: ref.type, authority: ref.authority, skey: ref.skey, - action: "read_self", + manage: "update", }); if (scopeError) return scopeError; + assertOwner(ref, session); + await assertActiveSpaceHost(ref); const stub = host.getSpaceDO(ref.uri); - await requireConfigured(stub, ref); + const commit = await stub.rpcRemoveMember(body.did!); + afterConfigCommit(c, ref, stub, commit); + return c.json({}); + } catch (err) { + return errorResponse(c, err); + } + }); + + app.get("/xrpc/com.atproto.memberspace.listMembers", async (c) => { + try { + const ref = requireSpaceUri(c.req.query("space")); + const session = await host.authenticate(c); + if (session instanceof Response) return session; + const scopeError = assertScope(c, session, { + type: ref.type, + authority: ref.authority, + skey: ref.skey, + action: "read_self", + }); + if (scopeError) return scopeError; + assertOwner(ref, session); const limit = clampLimit(c.req.query("limit"), 100, 1000); - const page = await stub.rpcListMembers({ + const page = await host.getSpaceDO(ref.uri).rpcListMembers({ limit, afterDid: c.req.query("cursor"), }); - const last = page.dids[page.dids.length - 1]; + const last = page.members[page.members.length - 1]; return c.json({ - members: page.dids.map((did) => ({ did })), - ...(page.hasMore && last ? { cursor: last } : {}), + members: page.members.map((member) => ({ + did: member.did, + read: member.read, + write: member.write, + })), + ...(page.hasMore && last ? { cursor: last.did } : {}), }); } catch (err) { return errorResponse(c, err); } }); - function assertOwner(ref: SpaceRef, session: SpaceSessionAuth): void { - assertSpaceHost(ref); - if (session.did !== ref.authority) { - throw new SpaceError( - "NotSpaceOwner", - "Only the space owner may manage the space", + // --------------------------------------------------------------- + // Helpers that need the host + // --------------------------------------------------------------- + + /** Service auth for inbound notifications; a Response on failure. */ + async function requireServiceAuth( + c: Context, + lxm: string, + ): Promise<{ iss: string; aud: string } | Response> { + const authHeader = c.req.header("Authorization"); + if (!authHeader?.startsWith("Bearer ")) { + return c.json( + { error: "AuthenticationRequired", message: "Service auth required" }, + 401, + ); + } + try { + return await host.verifyServiceJwt(authHeader.slice(7), lxm); + } catch (err) { + return c.json( + { + error: "AuthenticationRequired", + message: err instanceof Error ? err.message : "Invalid service auth", + }, + 401, ); } } - async function requireConfigured( - stub: SpaceStub, - ref: SpaceRef, - ): Promise { - const { meta, config } = await stub.rpcGetAuthorityState(); - if (!meta || meta.deletedAt || !config) { - throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}`); - } - return config; + function isOwnAudience(aud: string): boolean { + return aud === host.operatorDid || aud.startsWith(`${host.operatorDid}#`); } /** @@ -1765,12 +2151,19 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { // Small parsing helpers // --------------------------------------------------------------------- -function requireString( - value: unknown, - name: string, -): asserts value is string { +function requireString(value: unknown, name: string): asserts value is string { if (typeof value !== "string" || value.length === 0) { - throw new SpaceError("InvalidRequest", `Missing required parameter: ${name}`); + throw new SpaceError( + "InvalidRequest", + `Missing required parameter: ${name}`, + ); + } +} + +function requireDid(value: unknown, name: string): asserts value is string { + requireString(value, name); + if (!value.startsWith("did:")) { + throw new SpaceError("InvalidRequest", `${name} must be a DID`); } } @@ -1792,10 +2185,7 @@ function parseRecordCursor( if (slash <= 0 || slash === cursor.length - 1) { throw new SpaceError("MalformedCursor", `Malformed cursor: ${cursor}`); } - return { - collection: cursor.slice(0, slash), - rkey: cursor.slice(slash + 1), - }; + return { collection: cursor.slice(0, slash), rkey: cursor.slice(slash + 1) }; } function parseOpsCursor( @@ -1810,83 +2200,76 @@ function parseOpsCursor( return { rev: cursor.slice(0, slash), idx }; } -const POLICY_PREFIX = "com.atproto.simplespace.defs#"; - -function parsePolicy(input: unknown): SpacePolicy { - const type = (input as { $type?: string } | undefined)?.$type; - switch (type) { - case `${POLICY_PREFIX}publicPolicy`: - return { kind: "public" }; - case `${POLICY_PREFIX}memberListPolicy`: - return { kind: "member-list" }; - case `${POLICY_PREFIX}managingAppPolicy`: { - const managingApp = (input as { managingApp?: unknown }).managingApp; - if (typeof managingApp !== "string" || !managingApp.startsWith("did:")) { - throw new SpaceError( - "UnsupportedPolicy", - "managingApp must be a DID service identifier", - ); - } - return { kind: "managing-app", managingApp }; - } - default: +/** + * Read the members out of a space meta archive's policy state. A key the + * policy doesn't define is refused rather than dropped, since dropping it + * would quietly change who has access to the space. + */ +function parsePolicyState( + policy: SpacePolicy, + entries: Array<{ key: string; value: Record }>, +): SpaceMember[] { + const prefix = `${MEMBER_COLLECTION}/`; + return entries.map(({ key, value }) => { + const did = key.startsWith(prefix) + ? recordKeyToDid(key.slice(prefix.length)) + : undefined; + if (policy.$type !== MEMBERSPACE_POLICY || !did?.startsWith("did:")) { throw new SpaceError( - "UnsupportedPolicy", - `Unsupported policy: ${String(type)}`, + "InvalidRequest", + `Unrecognized policy state: ${key}`, ); - } + } + if (typeof value.read !== "boolean" || typeof value.write !== "boolean") { + throw new SpaceError("InvalidRequest", `Invalid member at ${key}`); + } + return { did, read: value.read, write: value.write }; + }); } -function policyToJson(policy: SpacePolicy): Record { - switch (policy.kind) { - case "public": - return { $type: `${POLICY_PREFIX}publicPolicy` }; - case "member-list": - return { $type: `${POLICY_PREFIX}memberListPolicy` }; - case "managing-app": - return { - $type: `${POLICY_PREFIX}managingAppPolicy`, - managingApp: policy.managingApp, - }; - } +/** A malformed archive in a request body is the caller's error. */ +function invalidArchive(err: unknown): unknown { + if (parseSpaceErrorCode(err)) return err; + return new SpaceError( + "InvalidRequest", + `Invalid archive: ${err instanceof Error ? err.message : String(err)}`, + ); } -function appAccessToJson(appAccess: SpaceAppAccess): Record { - switch (appAccess.kind) { - case "open": - return { $type: `${POLICY_PREFIX}open` }; - case "allowList": - return { - $type: `${POLICY_PREFIX}allowList`, - allowed: appAccess.allowed, - }; +async function readBody(c: Context): Promise { + const declared = Number.parseInt(c.req.header("Content-Length") ?? "", 10); + if (declared > MAX_IMPORT_BYTES) { + throw new SpaceError("InvalidRequest", "Archive is too large"); } + const bytes = new Uint8Array(await c.req.arrayBuffer()); + if (bytes.length === 0) { + throw new SpaceError("InvalidRequest", "Empty archive"); + } + if (bytes.length > MAX_IMPORT_BYTES) { + throw new SpaceError("InvalidRequest", "Archive is too large"); + } + return bytes; } -function parseAppAccess(input: unknown): SpaceAppAccess { - const type = (input as { $type?: string } | undefined)?.$type; - switch (type) { - case `${POLICY_PREFIX}open`: - return { kind: "open" }; - case `${POLICY_PREFIX}allowList`: { - const allowed = (input as { allowed?: unknown }).allowed; - if ( - !Array.isArray(allowed) || - allowed.some((entry) => typeof entry !== "string") - ) { - throw new SpaceError( - "UnsupportedAppAccess", - "allowList requires an array of client IDs", - ); +/** A pull-based stream over an async iterable, cancelling it on abort. */ +function asyncIterableToStream( + iterable: AsyncIterable, +): ReadableStream { + const iterator = iterable[Symbol.asyncIterator](); + return new ReadableStream({ + async pull(controller) { + try { + const { value, done } = await iterator.next(); + if (done) controller.close(); + else controller.enqueue(value); + } catch (err) { + controller.error(err); } - return { kind: "allowList", allowed: allowed as string[] }; - } - default: - throw new SpaceError( - "UnsupportedAppAccess", - `Unsupported appAccess: ${String(type)}`, - ); - } + }, + async cancel() { + await iterator.return?.(); + }, + }); } async function deleteR2Prefix(bucket: R2Bucket, prefix: string): Promise { @@ -1899,3 +2282,5 @@ async function deleteR2Prefix(bucket: R2Bucket, prefix: string): Promise { cursor = listed.truncated ? listed.cursor : undefined; } while (cursor); } + +export { stagedBlobKey }; diff --git a/packages/spaces/src/schema.ts b/packages/spaces/src/schema.ts index fdc470c..da797ff 100644 --- a/packages/spaces/src/schema.ts +++ b/packages/spaces/src/schema.ts @@ -9,8 +9,14 @@ * `pds spaces reset` wipes them. That is the alpha policy, applied honestly. */ -/** Bump on any breaking change to the tables below. */ -export const SPACE_SCHEMA_VERSION = 1; +/** + * Bump on any breaking change to the tables below. + * + * 2: baseline policies replace simplespace config; members carry + * read/write access; writers carry space revisions; revoked + * credentials; coalescing notification queue. + */ +export const SPACE_SCHEMA_VERSION = 2; export const SPACE_DO_SCHEMA = ` -- One row. schema_version is checked on every open. @@ -61,22 +67,28 @@ export const SPACE_DO_SCHEMA = ` PRIMARY KEY (rev, idx) ); - -- Authority role only. + -- Authority role only. The policy is stored as its normalised lexicon + -- object (com.atproto.{personal,member,managed}space.policy). CREATE TABLE IF NOT EXISTS config ( id INTEGER PRIMARY KEY CHECK (id = 1), - policy TEXT NOT NULL, - managing_app TEXT, - app_access TEXT NOT NULL, - app_allowed TEXT NOT NULL + policy TEXT NOT NULL ); - CREATE TABLE IF NOT EXISTS member (did TEXT PRIMARY KEY); + -- memberspace member list. + CREATE TABLE IF NOT EXISTS member ( + did TEXT PRIMARY KEY, + can_read INTEGER NOT NULL, + can_write INTEGER NOT NULL + ); + -- The writer set, sequenced by space revision. CREATE TABLE IF NOT EXISTS writer ( did TEXT PRIMARY KEY, - rev TEXT NOT NULL, - hash BLOB NOT NULL + repo_rev TEXT NOT NULL, + data BLOB NOT NULL, + space_rev TEXT NOT NULL ); + CREATE INDEX IF NOT EXISTS idx_writer_space_rev ON writer(space_rev); CREATE TABLE IF NOT EXISTS notify_registration ( service TEXT PRIMARY KEY, @@ -84,15 +96,26 @@ export const SPACE_DO_SCHEMA = ` expires_at TEXT NOT NULL ); + -- Outbound notifications, both roles. A row with a coalesce_key is + -- replaced by a newer one with the same key; deadline (ms) is when + -- retrying stops. CREATE TABLE IF NOT EXISTS notify_queue ( id INTEGER PRIMARY KEY AUTOINCREMENT, service TEXT NOT NULL, body TEXT NOT NULL, attempts INTEGER NOT NULL DEFAULT 0, - next_at INTEGER NOT NULL + next_at INTEGER NOT NULL, + deadline INTEGER, + coalesce_key TEXT UNIQUE ); CREATE INDEX IF NOT EXISTS idx_notify_queue_next ON notify_queue(next_at); + -- Credentials for this space revoked by its authority (repo-host role). + CREATE TABLE IF NOT EXISTS revoked_credential ( + jti TEXT PRIMARY KEY, + expires_at INTEGER NOT NULL + ); + -- Replay protection, both roles. CREATE TABLE IF NOT EXISTS replay ( kind TEXT NOT NULL, @@ -108,8 +131,20 @@ export const OPLOG_RETENTION_DAYS = 30; export const OPLOG_RETENTION_OPS = 10_000; /** Notify registrations expire after this many days. */ export const NOTIFY_REGISTRATION_DAYS = 7; -/** Give up delivering a notification after this many attempts. */ +/** + * Give up delivering a notification without its own deadline after this + * many attempts: syncer fan-out is reasonable-effort, and a syncer that + * misses one recovers through listRepos. + */ export const NOTIFY_MAX_ATTEMPTS = 5; +/** A repo host retries its write notification to the authority this long. */ +export const NOTIFY_WRITE_RETRY_MS = 24 * 60 * 60 * 1000; +/** Cap on the backoff between notification retries. */ +export const NOTIFY_BACKOFF_MAX_MS = 60 * 60 * 1000; +/** notifyWrite refuses repo revisions this far ahead of the clock. */ +export const MAX_REV_CLOCK_SKEW_MS = 5 * 60 * 1000; +/** The largest record a space repo accepts, as its DRISL encoding. */ +export const MAX_SPACE_RECORD_BYTES = 1024 * 1024; /** Base delay for notification retry backoff, in milliseconds. */ export const NOTIFY_BACKOFF_BASE_MS = 30_000; @@ -126,7 +161,20 @@ export const INDEX_DO_SCHEMA = ` schema_version INTEGER NOT NULL ); CREATE INDEX IF NOT EXISTS idx_space_state ON space(state); + + -- Blobs referenced by an imported space repo that had not been uploaded + -- yet. uploadBlob claims them and promotes the staged copy into each + -- space's blob prefix. + CREATE TABLE IF NOT EXISTS pending_blob ( + cid TEXT NOT NULL, + uri TEXT NOT NULL, + created_at INTEGER NOT NULL, + PRIMARY KEY (cid, uri) + ); `; +/** Forget pending imported-space blobs that were never uploaded. */ +export const PENDING_BLOB_TTL_MS = 30 * 24 * 60 * 60 * 1000; + /** Remove `pending` index entries that never activated after this long. */ export const PENDING_ENTRY_TTL_MS = 24 * 60 * 60 * 1000; diff --git a/packages/spaces/src/service-jwt.ts b/packages/spaces/src/service-jwt.ts index 397c26a..a62b43d 100644 --- a/packages/spaces/src/service-jwt.ts +++ b/packages/spaces/src/service-jwt.ts @@ -5,7 +5,7 @@ * iat, exp}` signed with the account signing key (alg from the keypair). */ -import type { Keypair } from "@atproto/crypto"; +import type { SpaceSigningKeypair } from "./types.js"; const encoder = new TextEncoder(); @@ -25,7 +25,7 @@ export interface ServiceJwtParams { export async function createServiceJwt( params: ServiceJwtParams, - keypair: Keypair, + keypair: SpaceSigningKeypair, ): Promise { const iat = Math.floor(Date.now() / 1000); const header = { typ: "JWT", alg: keypair.jwtAlg }; diff --git a/packages/spaces/src/space-do.ts b/packages/spaces/src/space-do.ts index cf4eb68..f940130 100644 --- a/packages/spaces/src/space-do.ts +++ b/packages/spaces/src/space-do.ts @@ -4,16 +4,17 @@ * * Holds everything Cirrus knows about that space: the operator's * permissioned repo (records, oplog, LtHash state, blob references) and, - * when the operator is the authority, the simplespace config, member list, - * writer set, notification registrations and the outbound notification - * queue. Also the replay tables for DPoP proofs and delegation tokens - * presented against the space. + * when the operator is the authority, the space's policy, member list, + * writer set (sequenced by space revision) and notification registrations. + * Both roles share the outbound notification queue, and the replay and + * revocation tables for tokens presented against the space. * * Constraints inherited from the Cirrus architecture: * - No R2 I/O in here, ever. Blobs are the Worker's job. - * - Commits are never signed here; the signing key never enters this class - * except through {@link SpaceHostConfig.getKeypair}, which is used only - * for outbound notification service JWTs from the alarm. + * - No key material in here except through + * {@link SpaceHostConfig.getKeypair}, used only for outbound notification + * service JWTs from the alarm. Commits are unsigned and MACs are the + * Worker's, so the KEM key never enters this class. * - The host supplies its identity via {@link getHostConfig}; this class * must not read `env.DID`. If it ever contains a branch on which host is * running it, the boundary has failed. @@ -22,8 +23,19 @@ import { DurableObject } from "cloudflare:workers"; import { RepoCommit } from "@atproto/space"; import { SpaceError } from "./errors.js"; +import { + MEMBER_COLLECTION, + POLICY_COLLECTION, + POLICY_RKEY, + areMembersPublished, + assertMemberspace, + didToRecordKey, + isPolicyPublished, +} from "./policy.js"; +import { prepareRecord } from "./records.js"; import { NOTIFY_BACKOFF_BASE_MS, + NOTIFY_BACKOFF_MAX_MS, NOTIFY_MAX_ATTEMPTS, NOTIFY_REGISTRATION_DAYS, OPLOG_RETENTION_DAYS, @@ -35,16 +47,19 @@ import { nextRev, tidCutoff } from "./tid.js"; import { createServiceJwt } from "./service-jwt.js"; import type { ApplyWritesResult, + ImportedRecord, NotifyItem, OplogEntry, PreparedSpaceWrite, + RepoCommitResult, RepoState, - SpaceAppAccess, - SpaceConfig, SpaceHostConfig, + SpaceMember, SpaceMeta, SpacePolicy, SpaceRecordRow, + SpaceSequence, + SpaceWriter, } from "./types.js"; const DAY_MS = 24 * 60 * 60 * 1000; @@ -59,9 +74,17 @@ interface QueueRow { body: string; attempts: number; next_at: number; + deadline: number | null; +} + +/** HTTP statuses worth retrying; anything else is a permanent refusal. */ +export function isRetryableStatus(status: number): boolean { + return status === 408 || status === 425 || status === 429 || status >= 500; } -export abstract class SpaceDurableObject extends DurableObject { +export abstract class SpaceDurableObject< + Env = unknown, +> extends DurableObject { private sql: SqlStorage; private initialized = false; private outdated = false; @@ -75,7 +98,9 @@ export abstract class SpaceDurableObject extends DurableObject; + protected abstract getHostConfig(): + | SpaceHostConfig + | Promise; // ------------------------------------------------------------------ // Initialisation and schema versioning @@ -95,10 +120,7 @@ export abstract class SpaceDurableObject extends DurableObject extends DurableObject { await this.ensureOpen(); return this.readMeta(); @@ -158,7 +190,10 @@ export abstract class SpaceDurableObject extends DurableObject extends DurableObject { + policy?: SpacePolicy; + }): Promise { await this.ensureOpen(); const existing = this.readMeta(); - if (existing) { - if (existing.uri !== params.uri) { - throw new SpaceError( - "InvalidSpaceUri", - `Space DO already holds ${existing.uri}`, - ); - } - if (!existing.deletedAt) { - if (params.isAuthority && params.config) { - const hasConfig = - this.sql.exec("SELECT id FROM config").toArray().length > 0; - if (hasConfig) { - throw new SpaceError( - "SpaceAlreadyExists", - `Space already exists: ${params.uri}`, - ); - } - this.writeConfig(params.config); - } - return; - } - // A previously deleted space may be created again: tables were - // wiped at deletion, so reviving is a fresh start. - this.sql.exec( - "UPDATE meta SET deleted_at = NULL, created_at = ?, is_authority = ?", - new Date().toISOString(), - params.isAuthority ? 1 : 0, + if (existing && existing.uri !== params.uri) { + throw new SpaceError( + "InvalidSpaceUri", + `Space DO already holds ${existing.uri}`, ); - if (params.config) this.writeConfig(params.config); - return; } - this.sql.exec( - `INSERT INTO meta (uri, authority, type, skey, is_authority, created_at, deleted_at, schema_version) - VALUES (?, ?, ?, ?, ?, ?, NULL, ?)`, - params.uri, - params.authority, - params.type, - params.skey, - params.isAuthority ? 1 : 0, - new Date().toISOString(), - SPACE_SCHEMA_VERSION, - ); - if (params.config) this.writeConfig(params.config); + if (existing && !existing.deletedAt && params.policy && this.readPolicy()) { + throw new SpaceError( + "SpaceAlreadyExists", + `Space already exists: ${params.uri}`, + ); + } + const publishWrites = params.policy + ? await this.preparePolicyRecordWrites(params.policy) + : []; + return this.ctx.storage.transactionSync(() => { + if (!existing) { + this.sql.exec( + `INSERT INTO meta (uri, authority, type, skey, is_authority, created_at, deleted_at, schema_version) + VALUES (?, ?, ?, ?, ?, ?, NULL, ?)`, + params.uri, + params.authority, + params.type, + params.skey, + params.isAuthority ? 1 : 0, + new Date().toISOString(), + SPACE_SCHEMA_VERSION, + ); + } else if (existing.deletedAt) { + this.sql.exec( + "UPDATE meta SET deleted_at = NULL, created_at = ?, is_authority = ?", + new Date().toISOString(), + params.isAuthority ? 1 : 0, + ); + } + if (!params.policy) return null; + this.writePolicy(params.policy); + return this.applyWritesSync(publishWrites); + }); } // ------------------------------------------------------------------ @@ -224,123 +255,139 @@ export abstract class SpaceDurableObject extends DurableObject { await this.ensureOpen(); this.requireLiveMeta(); + return this.ctx.storage.transactionSync( + () => this.applyWritesSync(writes)!, + ); + } - return this.ctx.storage.transactionSync(() => { - const stateRow = this.sql - .exec("SELECT set_hash, rev FROM repo_state WHERE id = 1") - .toArray()[0]; - const prevRev = stateRow ? (stateRow.rev as string) : null; - const commit = RepoCommit.fromState( - stateRow ? new Uint8Array(stateRow.set_hash as ArrayBuffer) : null, - ); - const rev = nextRev(prevRev); - const indexedAt = new Date().toISOString(); - const results: ApplyWritesResult["results"] = []; - let idx = 0; - - for (const write of writes) { - const prevRow = this.sql - .exec( - "SELECT cid FROM record WHERE collection = ? AND rkey = ?", - write.collection, - write.rkey, - ) - .toArray()[0]; - const prev = prevRow ? (prevRow.cid as string) : null; - - if (write.action === "create" && prev) { - throw new SpaceError( - "RecordAlreadyExists", - `Record already exists: ${write.collection}/${write.rkey}`, - ); - } - if (write.action !== "create" && !prev) { - throw new SpaceError( - "RecordNotFound", - `Record not found: ${write.collection}/${write.rkey}`, - ); - } - - if (write.action === "delete") { - this.sql.exec( - "DELETE FROM record WHERE collection = ? AND rkey = ?", - write.collection, - write.rkey, - ); - this.sql.exec( - "DELETE FROM record_blob WHERE collection = ? AND rkey = ?", - write.collection, - write.rkey, - ); - commit.setHash.remove( - `${write.collection}/${write.rkey}/${prev}`, - ); - this.appendOplog(rev, idx++, write.collection, write.rkey, null, prev); - results.push({ - action: "delete", - collection: write.collection, - rkey: write.rkey, - cid: null, - }); - continue; - } + /** + * Apply a batch as one commit sharing a single rev. Must run in a + * transaction. Returns null for an empty batch. Each write lands before + * the next is read, so a batch can create and then update a record, and + * a repeated create is refused rather than counted twice. + */ + private applyWritesSync( + writes: PreparedSpaceWrite[], + ): ApplyWritesResult | null { + if (writes.length === 0) return null; + const state = this.readRepoState(); + const commit = RepoCommit.fromState(state?.setHash ?? null); + const rev = nextRev(state?.rev ?? null); + const indexedAt = new Date().toISOString(); + const results: ApplyWritesResult["results"] = []; + let idx = 0; - this.sql.exec( - `INSERT OR REPLACE INTO record (collection, rkey, cid, bytes, rev, indexed_at) - VALUES (?, ?, ?, ?, ?, ?)`, - write.collection, - write.rkey, - write.cid, - write.bytes, - rev, - indexedAt, - ); - this.sql.exec( - "DELETE FROM record_blob WHERE collection = ? AND rkey = ?", + for (const write of writes) { + const prevRow = this.sql + .exec( + "SELECT cid FROM record WHERE collection = ? AND rkey = ?", write.collection, write.rkey, + ) + .toArray()[0]; + const prev = prevRow ? (prevRow.cid as string) : null; + + if (write.action === "create" && prev) { + throw new SpaceError( + "RecordAlreadyExists", + `Record already exists: ${write.collection}/${write.rkey}`, ); - for (const blobCid of write.blobCids) { - this.sql.exec( - "INSERT OR IGNORE INTO record_blob (blob_cid, collection, rkey) VALUES (?, ?, ?)", - blobCid, - write.collection, - write.rkey, - ); - } - if (prev) { - commit.setHash.remove( - `${write.collection}/${write.rkey}/${prev}`, - ); - } - commit.setHash.add( - `${write.collection}/${write.rkey}/${write.cid}`, - ); - this.appendOplog( - rev, - idx++, - write.collection, - write.rkey, - write.cid, - prev, + } + if (write.action !== "create" && !prev) { + throw new SpaceError( + "RecordNotFound", + `Record not found: ${write.collection}/${write.rkey}`, ); + } + + if (write.action === "delete") { + this.deleteRecordRow(write.collection, write.rkey); + commit.setHash.remove(`${write.collection}/${write.rkey}/${prev}`); + this.appendOplog(rev, idx++, write.collection, write.rkey, null, prev); results.push({ - action: write.action, + action: "delete", collection: write.collection, rkey: write.rkey, - cid: write.cid, + cid: null, }); + continue; } this.sql.exec( - `INSERT INTO repo_state (id, set_hash, rev) VALUES (1, ?, ?) - ON CONFLICT (id) DO UPDATE SET set_hash = excluded.set_hash, rev = excluded.rev`, - commit.setHash.state(), + `INSERT OR REPLACE INTO record (collection, rkey, cid, bytes, rev, indexed_at) + VALUES (?, ?, ?, ?, ?, ?)`, + write.collection, + write.rkey, + write.cid, + write.bytes, + rev, + indexedAt, + ); + this.replaceRecordBlobs(write.collection, write.rkey, write.blobCids); + if (prev) { + commit.setHash.remove(`${write.collection}/${write.rkey}/${prev}`); + } + commit.setHash.add(`${write.collection}/${write.rkey}/${write.cid}`); + this.appendOplog( rev, + idx++, + write.collection, + write.rkey, + write.cid, + prev, ); + results.push({ + action: write.action, + collection: write.collection, + rkey: write.rkey, + cid: write.cid, + }); + } - return { rev, hash: commit.setHash.digest(), results }; - }); + this.writeRepoState(commit.setHash.state(), rev); + return { rev, data: commit.setHash.digest(), results }; + } + + private deleteRecordRow(collection: string, rkey: string): void { + this.sql.exec( + "DELETE FROM record WHERE collection = ? AND rkey = ?", + collection, + rkey, + ); + this.sql.exec( + "DELETE FROM record_blob WHERE collection = ? AND rkey = ?", + collection, + rkey, + ); + } + + private replaceRecordBlobs( + collection: string, + rkey: string, + blobCids: string[], + ): void { + this.sql.exec( + "DELETE FROM record_blob WHERE collection = ? AND rkey = ?", + collection, + rkey, + ); + for (const blobCid of blobCids) { + this.sql.exec( + "INSERT OR IGNORE INTO record_blob (blob_cid, collection, rkey) VALUES (?, ?, ?)", + blobCid, + collection, + rkey, + ); + } + } + + private writeRepoState(setHash: Uint8Array, rev: string): void { + this.sql.exec( + `INSERT INTO repo_state (id, set_hash, rev) VALUES (1, ?, ?) + ON CONFLICT (id) DO UPDATE SET set_hash = excluded.set_hash, rev = excluded.rev`, + setHash, + rev, + ); } private appendOplog( @@ -362,10 +409,104 @@ export abstract class SpaceDurableObject extends DurableObject { + await this.ensureOpen(); + this.requireLiveMeta(); + return this.sql + .exec("SELECT DISTINCT collection FROM record ORDER BY collection") + .toArray() + .map((row) => row.collection as string); + } + + /** + * Delete every record outside `keep` and clear the oplog, leaving the + * repo at a new rev with the digest of what remains. Returns null when + * there was nothing to delete. + */ + async rpcClearRecords(keep: string[]): Promise { + await this.ensureOpen(); + this.requireLiveMeta(); + return this.ctx.storage.transactionSync(() => { + const state = this.readRepoState(); + if (!state) return null; + const placeholders = keep.map(() => "?").join(", "); + const notKept = + keep.length > 0 ? `collection NOT IN (${placeholders})` : "1=1"; + const doomed = this.sql + .exec(`SELECT COUNT(*) AS n FROM record WHERE ${notKept}`, ...keep) + .toArray()[0]?.n as number; + if (!doomed) return null; + this.sql.exec(`DELETE FROM record_blob WHERE ${notKept}`, ...keep); + this.sql.exec(`DELETE FROM record WHERE ${notKept}`, ...keep); + this.sql.exec("DELETE FROM oplog"); + const commit = new RepoCommit(); + for (const row of this.sql + .exec("SELECT collection, rkey, cid FROM record") + .toArray()) { + commit.setHash.add(`${row.collection}/${row.rkey}/${row.cid}`); + } + const rev = nextRev(state.rev); + this.writeRepoState(commit.setHash.state(), rev); + return { rev, data: commit.setHash.digest() }; + }); + } + + /** + * Replace the repo with records imported from its previous host. Takes a + * new rev here and none of its history, so the oplog starts empty. + * Returns the digest so the Worker can confirm it matches the archive's + * commit. + */ + async rpcImportRepo(records: ImportedRecord[]): Promise { + await this.ensureOpen(); + this.requireLiveMeta(); + return this.ctx.storage.transactionSync(() => { + const state = this.readRepoState(); + this.sql.exec("DELETE FROM record_blob"); + this.sql.exec("DELETE FROM record"); + this.sql.exec("DELETE FROM oplog"); + const rev = nextRev(state?.rev ?? null); + const indexedAt = new Date().toISOString(); + const commit = new RepoCommit(); + for (const record of records) { + this.sql.exec( + `INSERT INTO record (collection, rkey, cid, bytes, rev, indexed_at) + VALUES (?, ?, ?, ?, ?, ?)`, + record.collection, + record.rkey, + record.cid, + record.bytes, + rev, + indexedAt, + ); + this.replaceRecordBlobs( + record.collection, + record.rkey, + record.blobCids, + ); + commit.setHash.add(`${record.collection}/${record.rkey}/${record.cid}`); + } + this.writeRepoState(commit.setHash.state(), rev); + return { rev, data: commit.setHash.digest() }; + }); + } + // ------------------------------------------------------------------ // Permissioned repo: reads // ------------------------------------------------------------------ + private readRepoState(): RepoState | null { + const row = this.sql + .exec("SELECT set_hash, rev FROM repo_state WHERE id = 1") + .toArray()[0]; + if (!row) return null; + return { + setHash: new Uint8Array(row.set_hash as ArrayBuffer), + rev: row.rev as string, + }; + } + async rpcGetRecord( collection: string, rkey: string, @@ -390,10 +531,6 @@ export abstract class SpaceDurableObject extends DurableObject extends DurableObject { + }): Promise<{ records: SpaceRecordRow[]; hasMore: boolean }> { await this.ensureOpen(); this.requireLiveMeta(); - const stateRow = this.sql - .exec("SELECT rev FROM repo_state WHERE id = 1") - .toArray()[0]; - const rev = stateRow ? (stateRow.rev as string) : null; const asc = params.reverse === true; const op = asc ? ">" : "<"; const order = asc ? "ASC" : "DESC"; @@ -423,7 +552,11 @@ export abstract class SpaceDurableObject extends DurableObject extends DurableObject { + /** + * Records in strict byte order of their `{collection}/{rkey}` path, as a + * repo archive requires — not (collection, rkey) order, which differs + * when one collection NSID prefixes another. `state` is the repo state + * the page was read at: the page and the state are one snapshot + * (synchronous reads, single-threaded DO), so a streaming export can + * fence against concurrent writes. + */ + async rpcListRecordsByPath(params: { + afterPath?: string; + limit: number; + }): Promise<{ + records: Array<{ collection: string; rkey: string; bytes: Uint8Array }>; + hasMore: boolean; + state: RepoState | null; + }> { await this.ensureOpen(); this.requireLiveMeta(); - const row = this.sql - .exec("SELECT set_hash, rev FROM repo_state WHERE id = 1") - .toArray()[0]; - if (!row) return null; + const state = this.readRepoState(); + // SQLite's default BINARY collation compares UTF-8 bytes, which is + // the archive's order. + const rows = this.sql + .exec( + `SELECT collection, rkey, bytes FROM record + ${params.afterPath !== undefined ? "WHERE collection || '/' || rkey > ?" : ""} + ORDER BY collection || '/' || rkey ASC + LIMIT ?`, + ...(params.afterPath !== undefined ? [params.afterPath] : []), + params.limit + 1, + ) + .toArray(); + const hasMore = rows.length > params.limit; + const page = hasMore ? rows.slice(0, params.limit) : rows; return { - setHash: new Uint8Array(row.set_hash as ArrayBuffer), - rev: row.rev as string, + records: page.map((row) => ({ + collection: row.collection as string, + rkey: row.rkey as string, + bytes: new Uint8Array(row.bytes as ArrayBuffer), + })), + hasMore, + state, }; } + async rpcGetRepoState(): Promise { + await this.ensureOpen(); + this.requireLiveMeta(); + return this.readRepoState(); + } + /** * List oplog entries after `since` (a rev) or `after` (an exact cursor * position). Creates and updates carry the record's current bytes when * the oplog cid still matches the live record; superseded values are * omitted. When the page reaches the head, `head` carries the repo - * state read in the same transaction so the Worker can attach a freshly - * signed commit without a state race. + * state read in the same transaction so the Worker can attach the + * commit without a state race. */ async rpcListRepoOps(params: { since?: string; @@ -490,9 +659,7 @@ export abstract class SpaceDurableObject extends DurableObject extends DurableObject extends DurableObject extends DurableObject 0; } + /** + * Record credentials the authority revoked (repo-host role). Held until + * any credential with that jti must have expired anyway. Needs no live + * repo: a revocation can precede the first write. + */ + async rpcRevokeCredentials( + jtis: string[], + expiresAtSec: number, + ): Promise { + await this.ensureOpen(); + for (const jti of jtis) { + this.sql.exec( + `INSERT INTO revoked_credential (jti, expires_at) VALUES (?, ?) + ON CONFLICT (jti) DO UPDATE SET expires_at = excluded.expires_at`, + jti, + expiresAtSec, + ); + } + await this.scheduleNextAlarm(); + } + + async rpcIsCredentialRevoked(jti: string): Promise { + await this.ensureOpen(); + return ( + this.sql + .exec( + "SELECT 1 FROM revoked_credential WHERE jti = ? AND expires_at > ?", + jti, + Math.floor(Date.now() / 1000), + ) + .toArray().length > 0 + ); + } + // ------------------------------------------------------------------ - // Authority role: config, members, writers, notifications + // Authority role: policy, members, writers, notifications // ------------------------------------------------------------------ - private writeConfig(config: SpaceConfig): void { + private writePolicy(policy: SpacePolicy): void { this.sql.exec( - `INSERT INTO config (id, policy, managing_app, app_access, app_allowed) - VALUES (1, ?, ?, ?, ?) - ON CONFLICT (id) DO UPDATE SET - policy = excluded.policy, - managing_app = excluded.managing_app, - app_access = excluded.app_access, - app_allowed = excluded.app_allowed`, - config.policy.kind, - config.policy.kind === "managing-app" ? config.policy.managingApp : null, - config.appAccess.kind, - JSON.stringify( - config.appAccess.kind === "allowList" ? config.appAccess.allowed : [], - ), + `INSERT INTO config (id, policy) VALUES (1, ?) + ON CONFLICT (id) DO UPDATE SET policy = excluded.policy`, + JSON.stringify(policy), ); } - private readConfig(): SpaceConfig | null { - const row = this.sql.exec("SELECT * FROM config WHERE id = 1").toArray()[0]; - if (!row) return null; - const policyKind = row.policy as string; - const policy: SpacePolicy = - policyKind === "managing-app" - ? { - kind: "managing-app", - managingApp: row.managing_app as string, - } - : policyKind === "member-list" - ? { kind: "member-list" } - : { kind: "public" }; - const appAccess: SpaceAppAccess = - (row.app_access as string) === "allowList" - ? { - kind: "allowList", - allowed: JSON.parse(row.app_allowed as string) as string[], - } - : { kind: "open" }; - return { policy, appAccess }; + private readPolicy(): SpacePolicy | null { + const row = this.sql + .exec("SELECT policy FROM config WHERE id = 1") + .toArray()[0]; + return row ? (JSON.parse(row.policy as string) as SpacePolicy) : null; } /** - * State needed to answer getSpaceCredential: meta (including the - * deletion tombstone) and the simplespace config. Never throws on a + * State needed to answer getSpaceCredential and notifyWrite: meta + * (including the deletion tombstone) and the policy. Never throws on a * deleted space — a late credential request must get SpaceDeleted, not * SpaceNotFound, and that mapping is the caller's. */ async rpcGetAuthorityState(): Promise<{ meta: SpaceMeta | null; - config: SpaceConfig | null; + policy: SpacePolicy | null; }> { await this.ensureOpen(); - return { meta: this.readMeta(), config: this.readConfig() }; + return { meta: this.readMeta(), policy: this.readPolicy() }; } - async rpcUpdateConfig(update: { - policy?: SpacePolicy; - appAccess?: SpaceAppAccess; - }): Promise { + private hasRecord(collection: string, rkey: string): boolean { + return ( + this.sql + .exec( + "SELECT 1 FROM record WHERE collection = ? AND rkey = ?", + collection, + rkey, + ) + .toArray().length > 0 + ); + } + + private async preparePut( + collection: string, + rkey: string, + record: Record, + ): Promise { + const prepared = await prepareRecord(record); + return { + action: this.hasRecord(collection, rkey) ? "update" : "create", + collection, + rkey, + cid: prepared.cid, + bytes: prepared.bytes, + blobCids: prepared.blobCids, + }; + } + + private prepareDeleteIfExists( + collection: string, + rkey: string, + ): PreparedSpaceWrite[] { + return this.hasRecord(collection, rkey) + ? [{ action: "delete", collection, rkey }] + : []; + } + + /** Publish, update or withdraw the policy record to match the policy. */ + private async preparePolicyRecordWrites( + policy: SpacePolicy, + ): Promise { + if (isPolicyPublished(policy)) { + return [ + await this.preparePut(POLICY_COLLECTION, POLICY_RKEY, { + $type: POLICY_COLLECTION, + policy, + }), + ]; + } + return this.prepareDeleteIfExists(POLICY_COLLECTION, POLICY_RKEY); + } + + /** + * Publish, update or withdraw a member's record to match their entry. + * `access` is omitted for a DID that is no longer a member. + */ + private async prepareMemberRecordWrites( + policy: SpacePolicy, + did: string, + access?: { read: boolean; write: boolean }, + ): Promise { + const rkey = didToRecordKey(did); + if (access && areMembersPublished(policy)) { + return [ + await this.preparePut(MEMBER_COLLECTION, rkey, { + $type: MEMBER_COLLECTION, + read: access.read, + write: access.write, + }), + ]; + } + return this.prepareDeleteIfExists(MEMBER_COLLECTION, rkey); + } + + private readMembers(): SpaceMember[] { + return this.sql + .exec("SELECT did, can_read, can_write FROM member ORDER BY did") + .toArray() + .map((row) => ({ + did: row.did as string, + read: (row.can_read as number) === 1, + write: (row.can_write as number) === 1, + })); + } + + /** + * Replace the policy wholesale. A different `$type` migrates the space: + * state held by the previous policy (the member list) is discarded, and + * a published member list is withdrawn with it. + */ + async rpcUpdatePolicy(next: SpacePolicy): Promise { await this.ensureOpen(); - this.requireLiveMeta(); - const current = this.readConfig(); - if (!current) { - throw new SpaceError("SpaceNotFound", "Space has no configuration"); + const { policy: current } = this.requirePolicy(); + const writes = await this.preparePolicyRecordWrites(next); + if (areMembersPublished(current) !== areMembersPublished(next)) { + for (const member of this.readMembers()) { + writes.push( + ...(await this.prepareMemberRecordWrites(next, member.did, member)), + ); + } } - this.writeConfig({ - policy: update.policy ?? current.policy, - appAccess: update.appAccess ?? current.appAccess, + return this.ctx.storage.transactionSync(() => { + this.writePolicy(next); + if (current.$type !== next.$type) { + this.sql.exec("DELETE FROM member"); + } + return this.applyWritesSync(writes); }); } - async rpcAddMember(did: string): Promise { + async rpcPutMember( + did: string, + access: { read: boolean; write: boolean }, + ): Promise { await this.ensureOpen(); - this.requireLiveMeta(); - this.sql.exec("INSERT OR IGNORE INTO member (did) VALUES (?)", did); + const { policy } = this.requirePolicy(); + assertMemberspace(policy); + const writes = await this.prepareMemberRecordWrites(policy, did, access); + return this.ctx.storage.transactionSync(() => { + this.sql.exec( + `INSERT INTO member (did, can_read, can_write) VALUES (?, ?, ?) + ON CONFLICT (did) DO UPDATE SET can_read = excluded.can_read, can_write = excluded.can_write`, + did, + access.read ? 1 : 0, + access.write ? 1 : 0, + ); + if (!access.write) { + this.sql.exec("DELETE FROM writer WHERE did = ?", did); + } + return this.applyWritesSync(writes); + }); } - async rpcRemoveMember(did: string): Promise { + async rpcRemoveMember(did: string): Promise { await this.ensureOpen(); - this.requireLiveMeta(); - this.sql.exec("DELETE FROM member WHERE did = ?", did); + const { policy } = this.requirePolicy(); + assertMemberspace(policy); + const writes = await this.prepareMemberRecordWrites(policy, did); + return this.ctx.storage.transactionSync(() => { + this.sql.exec("DELETE FROM member WHERE did = ?", did); + this.sql.exec("DELETE FROM writer WHERE did = ?", did); + return this.applyWritesSync(writes); + }); } - async rpcIsMember(did: string): Promise { + async rpcGetMember(did: string): Promise { await this.ensureOpen(); - this.requireLiveMeta(); - return ( - this.sql.exec("SELECT 1 FROM member WHERE did = ?", did).toArray() - .length > 0 - ); + this.requirePolicy(); + const row = this.sql + .exec("SELECT did, can_read, can_write FROM member WHERE did = ?", did) + .toArray()[0]; + if (!row) return null; + return { + did: row.did as string, + read: (row.can_read as number) === 1, + write: (row.can_write as number) === 1, + }; } async rpcListMembers(params: { limit: number; afterDid?: string; - }): Promise<{ dids: string[]; hasMore: boolean }> { + }): Promise<{ members: SpaceMember[]; hasMore: boolean }> { await this.ensureOpen(); - this.requireLiveMeta(); + const { policy } = this.requirePolicy(); + assertMemberspace(policy); const args: unknown[] = []; let where = "1=1"; if (params.afterDid) { @@ -716,72 +1000,170 @@ export abstract class SpaceDurableObject extends DurableObject params.limit; const page = hasMore ? rows.slice(0, params.limit) : rows; - return { dids: page.map((r) => r.did as string), hasMore }; + return { + members: page.map((row) => ({ + did: row.did as string, + read: (row.can_read as number) === 1, + write: (row.can_write as number) === 1, + })), + hasMore, + }; } /** - * Record a writer's latest (rev, hash), from notifyWrite or own writes. - * Monotonic per writer: a delayed or replayed notification with an older - * rev never rolls the writer set backwards. Returns whether the write - * advanced state, so callers can skip fan-out for stale notifications. + * Record a writer's latest (repoRev, data), from notifyWrite or own + * writes, and advance the space sequence. Monotonic per writer: a + * delayed or replayed notification with an older (or equal) rev changes + * nothing and returns null, so callers skip fan-out for stale state. */ async rpcRecordWriter( did: string, - rev: string, - hash: Uint8Array, - ): Promise<{ advanced: boolean }> { + repoRev: string, + data: Uint8Array, + ): Promise { await this.ensureOpen(); - this.requireLiveMeta(); - const result = this.sql.exec( - `INSERT INTO writer (did, rev, hash) VALUES (?, ?, ?) - ON CONFLICT (did) DO UPDATE SET rev = excluded.rev, hash = excluded.hash - WHERE excluded.rev > writer.rev`, - did, - rev, - hash, - ); - return { advanced: result.rowsWritten > 0 }; + this.requirePolicy(); + return this.ctx.storage.transactionSync(() => { + const existing = this.sql + .exec("SELECT repo_rev FROM writer WHERE did = ?", did) + .toArray()[0]; + if (existing && (existing.repo_rev as string) >= repoRev) return null; + const latest = this.sql + .exec("SELECT MAX(space_rev) AS rev FROM writer") + .toArray()[0]?.rev as string | null; + const spaceRev = nextRev(latest); + this.sql.exec( + `INSERT INTO writer (did, repo_rev, data, space_rev) VALUES (?, ?, ?, ?) + ON CONFLICT (did) DO UPDATE SET repo_rev = excluded.repo_rev, data = excluded.data, space_rev = excluded.space_rev`, + did, + repoRev, + data, + spaceRev, + ); + return { spaceRev, ...(latest ? { prevSpaceRev: latest } : {}) }; + }); + } + + /** + * Drop an account from the writer set. It is tracked again if it later + * writes while still authorised. Idempotent. + */ + async rpcRemoveWriter(did: string): Promise { + await this.ensureOpen(); + this.requirePolicy(); + this.sql.exec("DELETE FROM writer WHERE did = ?", did); } + /** The writer set in ascending space revision, after `cursor`. */ async rpcListWriters(params: { limit: number; - afterDid?: string; - }): Promise<{ - repos: Array<{ did: string; rev: string; hash: Uint8Array }>; - hasMore: boolean; - }> { + cursor?: string; + }): Promise { await this.ensureOpen(); - this.requireLiveMeta(); - const args: unknown[] = []; - let where = "1=1"; - if (params.afterDid) { - where += " AND did > ?"; - args.push(params.afterDid); - } - const rows = this.sql + this.requirePolicy(); + return this.sql .exec( - `SELECT did, rev, hash FROM writer WHERE ${where} ORDER BY did ASC LIMIT ?`, - ...args, - params.limit + 1, + `SELECT did, repo_rev, data, space_rev FROM writer + ${params.cursor ? "WHERE space_rev > ?" : ""} + ORDER BY space_rev ASC LIMIT ?`, + ...(params.cursor ? [params.cursor] : []), + params.limit, ) - .toArray(); - const hasMore = rows.length > params.limit; - const page = hasMore ? rows.slice(0, params.limit) : rows; - return { - repos: page.map((r) => ({ - did: r.did as string, - rev: r.rev as string, - hash: new Uint8Array(r.hash as ArrayBuffer), - })), - hasMore, - }; + .toArray() + .map((row) => ({ + did: row.did as string, + repoRev: row.repo_rev as string, + data: new Uint8Array(row.data as ArrayBuffer), + spaceRev: row.space_rev as string, + })); + } + + /** The space's host-side state, for migrating its authority's account. */ + async rpcExportMeta(): Promise<{ + policy: SpacePolicy; + members: SpaceMember[]; + writers: SpaceWriter[]; + }> { + await this.ensureOpen(); + const { policy } = this.requirePolicy(); + const writers = this.sql + .exec("SELECT did, repo_rev, data, space_rev FROM writer ORDER BY did") + .toArray() + .map((row) => ({ + did: row.did as string, + repoRev: row.repo_rev as string, + data: new Uint8Array(row.data as ArrayBuffer), + spaceRev: row.space_rev as string, + })); + return { policy, members: this.readMembers(), writers }; + } + + /** + * Import a space exported by its previous host, replacing whatever this + * host held for it, so a migration step can be retried. Publishing is + * left to the authority's repo, which arrives afterwards with importRepo. + * Registrations, revocations and tombstones are not carried over. + */ + async rpcImportMeta(params: { + uri: string; + authority: string; + type: string; + skey: string; + policy: SpacePolicy; + members: SpaceMember[]; + writers: SpaceWriter[]; + }): Promise { + await this.ensureOpen(); + const existing = this.readMeta(); + if (existing && existing.uri !== params.uri) { + throw new SpaceError( + "InvalidSpaceUri", + `Space DO already holds ${existing.uri}`, + ); + } + this.ctx.storage.transactionSync(() => { + if (!existing) { + this.sql.exec( + `INSERT INTO meta (uri, authority, type, skey, is_authority, created_at, deleted_at, schema_version) + VALUES (?, ?, ?, ?, 1, ?, NULL, ?)`, + params.uri, + params.authority, + params.type, + params.skey, + new Date().toISOString(), + SPACE_SCHEMA_VERSION, + ); + } else { + this.sql.exec("UPDATE meta SET deleted_at = NULL, is_authority = 1"); + } + this.writePolicy(params.policy); + this.sql.exec("DELETE FROM member"); + for (const member of params.members) { + this.sql.exec( + "INSERT INTO member (did, can_read, can_write) VALUES (?, ?, ?)", + member.did, + member.read ? 1 : 0, + member.write ? 1 : 0, + ); + } + this.sql.exec("DELETE FROM writer"); + for (const writer of params.writers) { + this.sql.exec( + "INSERT INTO writer (did, repo_rev, data, space_rev) VALUES (?, ?, ?, ?)", + writer.did, + writer.repoRev, + writer.data, + writer.spaceRev, + ); + } + }); } /** @@ -794,7 +1176,7 @@ export abstract class SpaceDurableObject extends DurableObject { await this.ensureOpen(); - this.requireLiveMeta(); + this.requirePolicy(); const expiresAt = new Date( Date.now() + NOTIFY_REGISTRATION_DAYS * DAY_MS, ).toISOString(); @@ -815,60 +1197,91 @@ export abstract class SpaceDurableObject extends DurableObject - > { - await this.ensureOpen(); + private activeRegistrations(): Array<{ + service: string; + endpoint: string; + expiresAt: string; + }> { return this.sql .exec( - "SELECT service, endpoint FROM notify_registration WHERE expires_at > ?", + "SELECT service, endpoint, expires_at FROM notify_registration WHERE expires_at > ?", new Date().toISOString(), ) .toArray() .map((r) => ({ service: r.service as string, endpoint: r.endpoint as string, + expiresAt: r.expires_at as string, })); } + async rpcGetActiveRegistrations(): Promise< + Array<{ service: string; endpoint: string; expiresAt: string }> + > { + await this.ensureOpen(); + return this.activeRegistrations(); + } + /** * Queue outbound notifications for the alarm to deliver with bounded - * retries. The Worker only enqueues; delivery happens here because this - * DO holds no WebSocket and does no storage-bound work that a slow - * outbound fetch could pin. + * retries. An item with a coalesce key replaces any pending item with + * the same key, resetting its backoff and deadline. */ - async rpcEnqueueNotify(items: NotifyItem[]): Promise { + async rpcEnqueueNotify( + items: NotifyItem[], + opts: { delayMs?: number } = {}, + ): Promise { await this.ensureOpen(); if (items.length === 0) return; - const now = Date.now(); + const nextAt = Date.now() + (opts.delayMs ?? 0); for (const item of items) { + const body = JSON.stringify({ + endpoint: item.endpoint, + lxm: item.lxm, + body: item.body, + }); this.sql.exec( - "INSERT INTO notify_queue (service, body, attempts, next_at) VALUES (?, ?, 0, ?)", + `INSERT INTO notify_queue (service, body, attempts, next_at, deadline, coalesce_key) + VALUES (?, ?, 0, ?, ?, ?) + ON CONFLICT (coalesce_key) DO UPDATE SET + service = excluded.service, body = excluded.body, attempts = 0, + next_at = excluded.next_at, deadline = excluded.deadline`, item.service, - JSON.stringify({ - endpoint: item.endpoint, - lxm: item.lxm, - body: item.body, - }), - now, + body, + nextAt, + item.deadline ?? null, + item.coalesceKey ?? null, ); } await this.scheduleNextAlarm(); } + /** Drop a pending coalesced notification, e.g. once a newer one landed. */ + async rpcClearNotify(coalesceKey: string): Promise { + await this.ensureOpen(); + this.sql.exec( + "DELETE FROM notify_queue WHERE coalesce_key = ?", + coalesceKey, + ); + } + // ------------------------------------------------------------------ // Deletion and status // ------------------------------------------------------------------ /** - * Tombstone the space (authority role). Enqueues nothing itself — the - * caller reads the registrations from the result and enqueues - * `notifySpaceDeleted` before the queue rows would be unreachable. The - * meta row is retained so a late getSpaceCredential can answer - * SpaceDeleted rather than SpaceNotFound. Idempotent. + * Tombstone the space (authority role) and delete the authority's own + * repo in it. Enqueues nothing itself — the caller enqueues + * `notifySpaceDeleted` to the returned registrations. The meta row is + * retained so a late getSpaceCredential can answer SpaceDeleted rather + * than SpaceNotFound. Idempotent. */ async rpcDeleteSpace(): Promise<{ - registrations: Array<{ service: string; endpoint: string }>; + registrations: Array<{ + service: string; + endpoint: string; + expiresAt: string; + }>; }> { await this.ensureOpen(); const meta = this.readMeta(); @@ -876,12 +1289,9 @@ export abstract class SpaceDurableObject extends DurableObject { - this.sql.exec( - "UPDATE meta SET deleted_at = ?", - new Date().toISOString(), - ); + this.sql.exec("UPDATE meta SET deleted_at = ?", new Date().toISOString()); for (const table of [ "record", "record_blob", @@ -910,6 +1320,7 @@ export abstract class SpaceDurableObject extends DurableObject extends DurableObject extends DurableObject extends DurableObject { @@ -953,25 +1366,26 @@ export abstract class SpaceDurableObject extends DurableObject { + const now = Date.now(); + this.sql.exec( + "DELETE FROM notify_queue WHERE deadline IS NOT NULL AND deadline <= ?", + now, + ); const due = this.sql .exec( - "SELECT id, service, body, attempts, next_at FROM notify_queue WHERE next_at <= ? ORDER BY next_at ASC LIMIT ?", - Date.now(), + "SELECT id, service, body, attempts, next_at, deadline FROM notify_queue WHERE next_at <= ? ORDER BY next_at ASC LIMIT ?", + now, NOTIFY_BATCH, ) .toArray() as unknown as QueueRow[]; if (due.length === 0) return; - const meta = this.readMeta(); - if (!meta) { - this.sql.exec("DELETE FROM notify_queue"); - return; - } const host = await this.getHostConfig(); const keypair = await host.getKeypair(); for (const row of due) { let delivered = false; + let retryable = true; try { const parsed = JSON.parse(row.body) as { endpoint: string; @@ -979,7 +1393,7 @@ export abstract class SpaceDurableObject extends DurableObject; }; const token = await createServiceJwt( - { iss: meta.authority, aud: row.service, lxm: parsed.lxm }, + { iss: host.operatorDid, aud: row.service, lxm: parsed.lxm }, keypair, ); const res = await fetch(`${parsed.endpoint}/xrpc/${parsed.lxm}`, { @@ -989,9 +1403,11 @@ export abstract class SpaceDurableObject extends DurableObject extends DurableObject= NOTIFY_MAX_ATTEMPTS) { + const attempts = row.attempts + 1; + const exhausted = + row.deadline === null ? attempts >= NOTIFY_MAX_ATTEMPTS : false; + if (delivered || !retryable || exhausted) { this.sql.exec("DELETE FROM notify_queue WHERE id = ?", row.id); } else { this.sql.exec( "UPDATE notify_queue SET attempts = ?, next_at = ? WHERE id = ?", - row.attempts + 1, - Date.now() + NOTIFY_BACKOFF_BASE_MS * 2 ** row.attempts, + attempts, + Date.now() + + Math.min( + NOTIFY_BACKOFF_BASE_MS * 2 ** row.attempts, + NOTIFY_BACKOFF_MAX_MS, + ), row.id, ); } @@ -1045,10 +1468,15 @@ export abstract class SpaceDurableObject extends DurableObject> 10n) / 1000; +} diff --git a/packages/spaces/src/tokens.ts b/packages/spaces/src/tokens.ts new file mode 100644 index 0000000..af6f5c5 --- /dev/null +++ b/packages/spaces/src/tokens.ts @@ -0,0 +1,40 @@ +/** + * Delegation tokens, minted by the user's PDS for a space hosted anywhere. + * + * Thin wrappers over `@atproto/space`, which is bundled into this package + * (consumers must never resolve its alpha dependency ranges), so a host + * gets them without depending on that build or its types. + */ + +import { + createSpaceToken, + spaceHostAud as upstreamSpaceHostAud, +} from "@atproto/space"; +import type { SpaceSigningKeypair } from "./types.js"; + +/** + * How a space authority is addressed as the space host: its `#atproto_pds` + * service entry, the audience of delegation tokens and client attestations. + */ +export function spaceHostAud(authority: string): string { + return upstreamSpaceHostAud(authority); +} + +/** + * Mint a delegation token: the user's PDS vouching, for 60 seconds and one + * use, that `iss` wants a credential for `space` from its authority. + */ +export function createDelegationToken( + params: { iss: string; space: string; authority: string }, + keypair: SpaceSigningKeypair, +): Promise { + return createSpaceToken( + "delegation", + { + iss: params.iss, + sub: params.space, + aud: upstreamSpaceHostAud(params.authority), + }, + keypair as Parameters[2], + ); +} diff --git a/packages/spaces/src/types.ts b/packages/spaces/src/types.ts index 7acd4e0..0cf901a 100644 --- a/packages/spaces/src/types.ts +++ b/packages/spaces/src/types.ts @@ -2,7 +2,17 @@ * Shared types crossing the Worker ↔ Durable Object RPC boundary. */ -import type { Keypair } from "@atproto/crypto"; +/** + * The minimal keypair shape the engine signs with: the account's + * `#atproto` key, for space tokens and service-auth JWTs. Structural, so a + * host can pass any `@atproto/crypto` keypair without the engine's public + * types depending on a particular build of that package. + */ +export interface SpaceSigningKeypair { + jwtAlg: string; + did(): string; + sign(msg: Uint8Array): Promise; +} /** A write prepared by the Worker: validated, CBOR-encoded, CID computed. */ export type PreparedSpaceWrite = @@ -21,10 +31,14 @@ export type PreparedSpaceWrite = rkey: string; }; -export interface ApplyWritesResult { +/** A repo revision that is owed a write notification. */ +export interface RepoCommitResult { rev: string; - /** sha256 digest of the LtHash state after the batch. */ - hash: Uint8Array; + /** sha256 digest of the LtHash state: the commit's `data`. */ + data: Uint8Array; +} + +export interface ApplyWritesResult extends RepoCommitResult { results: Array<{ action: "create" | "update" | "delete"; collection: string; @@ -43,18 +57,48 @@ export interface SpaceMeta { deletedAt: string | null; } +export const PERSONALSPACE_POLICY = "com.atproto.personalspace.policy"; +export const MEMBERSPACE_POLICY = "com.atproto.memberspace.policy"; +export const MANAGEDSPACE_POLICY = "com.atproto.managedspace.policy"; + +/** + * A space policy as stored and enforced: one of the three baseline + * policies, normalised with its defaults filled in. The wire shape and the + * stored shape are the same object. + */ export type SpacePolicy = - | { kind: "public" } - | { kind: "member-list" } - | { kind: "managing-app"; managingApp: string }; + | { $type: typeof PERSONALSPACE_POLICY } + | { + $type: typeof MEMBERSPACE_POLICY; + publicRead: boolean; + publicWrite: boolean; + allowedApps?: string[]; + publishPolicy: boolean; + publishMembers: boolean; + } + | { + $type: typeof MANAGEDSPACE_POLICY; + managingApp: string; + publishPolicy: boolean; + }; -export type SpaceAppAccess = - | { kind: "open" } - | { kind: "allowList"; allowed: string[] }; +export interface SpaceMember { + did: string; + read: boolean; + write: boolean; +} + +export interface SpaceWriter { + did: string; + repoRev: string; + data: Uint8Array; + spaceRev: string; +} -export interface SpaceConfig { - policy: SpacePolicy; - appAccess: SpaceAppAccess; +/** The space sequence position assigned to an accepted repo update. */ +export interface SpaceSequence { + spaceRev: string; + prevSpaceRev?: string; } export interface RepoState { @@ -80,11 +124,27 @@ export interface OplogEntry { bytes?: Uint8Array; } +/** A record imported from a repo archive, prepared by the Worker. */ +export interface ImportedRecord { + collection: string; + rkey: string; + cid: string; + bytes: Uint8Array; + blobCids: string[]; +} + export interface NotifyItem { service: string; endpoint: string; lxm: string; body: Record; + /** + * Pending items sharing a key are coalesced: a newer one replaces the + * older, resetting its backoff and deadline. + */ + coalesceKey?: string; + /** Give up retrying after this time (ms since epoch). */ + deadline?: number; } /** @@ -96,6 +156,6 @@ export interface NotifyItem { export interface SpaceHostConfig { /** The DID whose permissioned repos this engine serves. */ operatorDid: string; - /** Signing keypair provider (service JWTs for notification fan-out). */ - getKeypair(): Promise; + /** Signing keypair provider (service JWTs for notification delivery). */ + getKeypair(): Promise; } diff --git a/packages/spaces/test/fixtures/spaces-worker/index.ts b/packages/spaces/test/fixtures/spaces-worker/index.ts index a84e416..af49c6d 100644 --- a/packages/spaces/test/fixtures/spaces-worker/index.ts +++ b/packages/spaces/test/fixtures/spaces-worker/index.ts @@ -16,6 +16,10 @@ export const TEST_SIGNING_KEY = export const TEST_OPERATOR_DID = "did:web:operator.test"; +/** Deterministic test `#atproto_kem` key (hex-encoded P-256 private key). */ +export const TEST_KEM_KEY = + "b5952836830a94fa65c83db8c527ff76b99d69ed1ceffaa6de93d6a62df1efb5"; + let keypairPromise: Promise | null = null; export class TestSpaceDurableObject extends SpaceDurableObject { diff --git a/packages/spaces/test/index-do.test.ts b/packages/spaces/test/index-do.test.ts index 30912aa..0c7b124 100644 --- a/packages/spaces/test/index-do.test.ts +++ b/packages/spaces/test/index-do.test.ts @@ -122,4 +122,18 @@ describe("SpaceIndexDurableObject", () => { page2.spaces.every((s) => s.uri > page1.spaces[1]!.uri), ).toBe(true); }); + + it("holds pending imported blobs until uploadBlob claims them", async () => { + const stub = indexStub(); + const a = entry(); + const b = entry(); + await stub.rpcAddPendingBlobs(a.uri, ["bafkpending1", "bafkpending2"]); + await stub.rpcAddPendingBlobs(b.uri, ["bafkpending1"]); + expect((await stub.rpcClaimPendingBlob("bafkpending1")).sort()).toEqual( + [a.uri, b.uri].sort(), + ); + // Claimed once. + expect(await stub.rpcClaimPendingBlob("bafkpending1")).toEqual([]); + expect(await stub.rpcClaimPendingBlob("bafkpending2")).toEqual([a.uri]); + }); }); diff --git a/packages/spaces/test/routes.test.ts b/packages/spaces/test/routes.test.ts index 3c05b6d..e8ee7d7 100644 --- a/packages/spaces/test/routes.test.ts +++ b/packages/spaces/test/routes.test.ts @@ -1,34 +1,50 @@ import { env } from "cloudflare:test"; import { describe, expect, it, vi } from "vitest"; import type { Context } from "hono"; -import { Secp256k1Keypair } from "@atproto/crypto"; +import { P256Keypair, Secp256k1Keypair } from "@atproto/crypto"; import { + COMMIT_MAC_TYPE, LtHash, - createDpopProof, + RECORD_MAC_TYPE, + createSpaceSigHeaders, createSpaceToken, + encapsulate, + formatWantMacHeader, + parseMacHeader, + readRepoStar, + serializeRepo, spaceHostAud, verifyCommit, - verifyRepoCarFull, + verifyRecord, + verifyRepoStarFull, } from "@atproto/space"; -import type { SignedCommit } from "@atproto/space"; +import type { Commit, MacType } from "@atproto/space"; import { JoseKey } from "@atproto/jwk-jose"; +import { encode } from "@atproto/lex-cbor"; import { fromBase64 } from "@atproto/lex-data"; import { create as createCid, CODEC_RAW, toString as cidToString } from "@atcute/cid"; import { createSpaceRoutes } from "../src/routes"; import type { SpaceRoutesHost, SpaceScopeMatch } from "../src/routes"; -import { TEST_OPERATOR_DID, TEST_SIGNING_KEY } from "./fixtures/spaces-worker/index"; +import { + TEST_KEM_KEY, + TEST_OPERATOR_DID, + TEST_SIGNING_KEY, +} from "./fixtures/spaces-worker/index"; const OPERATOR = TEST_OPERATOR_DID; const BOB = "did:web:bob.test"; -const ORIGIN = "https://pds.test"; +const CAROL = "did:web:carol.test"; const operatorKeypair = await Secp256k1Keypair.import(TEST_SIGNING_KEY); +const kemDid = (await P256Keypair.import(TEST_KEM_KEY)).did(); const bobKeypair = await Secp256k1Keypair.create(); +const carolKeypair = await Secp256k1Keypair.create(); /** did → did:key registry standing in for DID-document resolution. */ const signingKeys = new Map([ [OPERATOR, operatorKeypair.did()], [BOB, bobKeypair.did()], + [CAROL, carolKeypair.did()], ]); interface OutboundCall { @@ -45,9 +61,9 @@ function makeHost(overrides: Partial = {}): { let responder: (url: string) => Response | null = () => null; const host: SpaceRoutesHost = { operatorDid: OPERATOR, - publicOrigin: ORIGIN, blobs: env.BLOBS, getKeypair: async () => operatorKeypair, + getKemPrivateKey: () => TEST_KEM_KEY, getSigningKey: async (iss) => { const key = signingKeys.get(iss); if (!key) throw new Error(`Unknown issuer: ${iss}`); @@ -55,8 +71,6 @@ function makeHost(overrides: Partial = {}): { }, resolveServiceEndpoint: async (service) => `https://${service.split("#")[0]!.replace("did:web:", "")}`, - resolveAuthorityEndpoint: async (did) => - `https://${did.replace("did:web:", "")}`, // Trusted test double: decodes the payload without signature checks. // The real implementation lives in the host PDS. verifyServiceJwt: async (token, lxm) => { @@ -69,11 +83,7 @@ function makeHost(overrides: Partial = {}): { authenticate: async (c: Context) => { const auth = c.req.header("Authorization"); if (auth === "Bearer operator-session") { - return { - did: OPERATOR, - fullTrust: true, - allowsSpace: () => true, - }; + return { did: OPERATOR, fullTrust: true, allowsSpace: () => true }; } if (auth?.startsWith("Bearer scoped:")) { // "Bearer scoped:" — an OAuth session allowing exactly @@ -93,14 +103,10 @@ function makeHost(overrides: Partial = {}): { ), }; } - return c.json( - { error: "AuthenticationRequired", message: "No session" }, - 401, - ); + return c.json({ error: "AuthenticationRequired", message: "No session" }, 401); }, validateRecord: ({ record }) => ({ record, status: "unknown" }), - getSpaceDO: (uri) => - env.SPACES.get(env.SPACES.idFromName(uri)) as never, + getSpaceDO: (uri) => env.SPACES.get(env.SPACES.idFromName(uri)) as never, getIndexDO: () => env.SPACES_INDEX.get(env.SPACES_INDEX.idFromName("spaces")) as never, outboundFetch: (async (input: RequestInfo | URL, init?: RequestInit) => { @@ -118,125 +124,195 @@ function makeHost(overrides: Partial = {}): { }; } -const { host } = makeHost(); +const { host, outbound, setOutboundResponse } = makeHost(); const app = createSpaceRoutes(host); +const SESSION = { Authorization: "Bearer operator-session" }; +const MEMBERSPACE = { $type: "com.atproto.memberspace.policy" }; + let spaceN = 0; async function createSpace( - policy: Record = { - $type: "com.atproto.simplespace.defs#memberListPolicy", - }, - appAccess: Record = { - $type: "com.atproto.simplespace.defs#open", - }, + policy: Record = MEMBERSPACE, + spaceType = "app.bsky.group", ): Promise { - const res = await app.request("/xrpc/com.atproto.simplespace.createSpace", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: "Bearer operator-session", - }, - body: JSON.stringify({ - type: "app.bsky.group", - skey: `route${spaceN++}x`, - policy, - appAccess, - }), + const res = await post("/xrpc/com.atproto.space.createSpace", { + spaceType, + skey: `route${spaceN++}x`, + policy, }); expect(res.status).toBe(200); - const { uri } = (await res.json()) as { uri: string }; - return uri; + return ((await res.json()) as { uri: string }).uri; } +function post( + path: string, + body: unknown, + headers: Record = SESSION, +): Promise { + return app.request(path, { + method: "POST", + headers: { "Content-Type": "application/json", ...headers }, + body: JSON.stringify(body), + }); +} + +function get(path: string, headers: Record = SESSION): Promise { + return app.request(path, { headers }); +} + +async function errorOf(res: Response): Promise { + return ((await res.json()) as { error: string }).error; +} + +const q = encodeURIComponent; + async function createRecord( space: string, record: Record, rkey?: string, + collection = "app.bsky.feed.post", ): Promise<{ uri: string; cid: string }> { - const res = await app.request("/xrpc/com.atproto.space.createRecord", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: "Bearer operator-session", - }, - body: JSON.stringify({ - space, - repo: OPERATOR, - collection: "app.bsky.feed.post", - ...(rkey ? { rkey } : {}), - record, - }), + const res = await post("/xrpc/com.atproto.space.createRecord", { + space, + repo: OPERATOR, + collection, + ...(rkey ? { rkey } : {}), + record, }); expect(res.status).toBe(200); return (await res.json()) as { uri: string; cid: string }; } -/** Mint a delegation token + DPoP-bound credential for `user`. */ +async function putMember(space: string, did: string, read = true, write = true) { + const res = await post("/xrpc/com.atproto.memberspace.putMember", { + space, + did, + read, + write, + }); + expect(res.status).toBe(200); +} + +/** Request a credential bound to a fresh P-256 key. */ async function obtainCredential( space: string, - userKeypair: Secp256k1Keypair, - userDid: string, -): Promise<{ credential: string; dpopKey: JoseKey; status: number; body: unknown }> { - const dpopKey = await JoseKey.generate(["ES256"]); - const delegation = await createSpaceToken( - "delegation", - { iss: userDid, sub: space, aud: spaceHostAud(OPERATOR) }, - userKeypair, - ); - const proof = await createDpopProof(dpopKey, { - htm: "POST", - htu: `${ORIGIN}/xrpc/com.atproto.space.getSpaceCredential`, - }); - const res = await app.request("/xrpc/com.atproto.space.getSpaceCredential", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${delegation}`, - DPoP: proof, + opts: { + user?: { did: string; keypair: Secp256k1Keypair }; + clientAttestation?: string; + } = {}, +): Promise<{ credential: string; key: P256Keypair; status: number; body: unknown }> { + const key = await P256Keypair.create(); + const delegationToken = opts.user + ? await createSpaceToken( + "delegation", + { iss: opts.user.did, sub: space, aud: spaceHostAud(OPERATOR) }, + opts.user.keypair, + ) + : undefined; + const res = await post( + "/xrpc/com.atproto.space.getSpaceCredential", + { + space, + credentialKid: key.did(), + ...(delegationToken ? { delegationToken } : {}), + ...(opts.clientAttestation + ? { clientAttestation: opts.clientAttestation } + : {}), }, - body: JSON.stringify({ space }), - }); + {}, + ); const body = (await res.json()) as { credential?: string }; - return { - credential: body.credential ?? "", - dpopKey, - status: res.status, - body, - }; + return { credential: body.credential ?? "", key, status: res.status, body }; } -/** Perform a credential-authenticated GET. */ -async function credentialGet( +/** + * A credential-authenticated request: the credential, the audience header + * and an HTTP message signature over both, plus a MAC request when asked. + */ +async function credentialRequest( path: string, credential: string, - dpopKey: JoseKey, -): Promise { - const proof = await createDpopProof(dpopKey, { - htm: "GET", - htu: `${ORIGIN}${path.split("?")[0]}`, - credential, + key: P256Keypair, + opts: { + mac?: MacType; + audience?: string; + scheme?: string; + method?: "GET" | "POST"; + body?: unknown; + } = {}, +): Promise<{ res: Response; sharedSecret?: Uint8Array }> { + const authorization = `${opts.scheme ?? "Atproto-Space-Credential"} ${credential}`; + const headers: Record = await createSpaceSigHeaders(key, { + authorization, + audience: (opts.audience ?? OPERATOR) as `did:${string}:${string}`, }); - return app.request(path, { + let sharedSecret: Uint8Array | undefined; + if (opts.mac) { + const encapsulation = await encapsulate(kemDid); + sharedSecret = encapsulation.sharedSecret; + headers["atproto-space-want-mac"] = formatWantMacHeader( + opts.mac, + encapsulation.keyShare, + ); + } + const res = await app.request(path, { + method: opts.method ?? "GET", headers: { - Authorization: `DPoP ${credential}`, - DPoP: proof, + ...headers, + ...(opts.body ? { "Content-Type": "application/json" } : {}), }, + ...(opts.body ? { body: JSON.stringify(opts.body) } : {}), }); + return { res, sharedSecret }; } -function commitFromJson(json: Record): SignedCommit { - const bytes = (field: string) => - fromBase64((json[field] as { $bytes: string }).$bytes); +function commitFromJson(json: Record): Commit { return { - ver: json.ver as 1, - hash: bytes("hash"), - ikm: bytes("ikm"), - sig: bytes("sig"), - mac: bytes("mac"), + ver: json.ver as number, + repo: json.repo as Commit["repo"], + space: json.space as Commit["space"], rev: json.rev as string, + data: fromBase64((json.data as { $bytes: string }).$bytes), }; } +async function serviceJwt(iss: string, aud: string, lxm: string, keypair: Secp256k1Keypair) { + const { createServiceJwt } = await import("../src/service-jwt"); + return createServiceJwt({ iss, aud, lxm }, keypair); +} + +async function notifyWrite( + space: string, + writer: string, + keypair: Secp256k1Keypair, + repoRev: string, + data: Uint8Array, + aud = OPERATOR, +): Promise { + const token = await serviceJwt(writer, aud, "com.atproto.space.notifyWrite", keypair); + return post( + "/xrpc/com.atproto.space.notifyWrite", + { space, repo: writer, repoRev, data: { $bytes: btoa(String.fromCharCode(...data)) } }, + { Authorization: `Bearer ${token}` }, + ); +} + +const TID_CHARS = "234567abcdefghijklmnopqrstuvwxyz"; +/** A TID for a given time, so tests control rev order and skew. */ +function tidAt(ms: number, clock = 0): string { + let value = (BigInt(Math.floor(ms)) * 1000n << 10n) | BigInt(clock); + let out = ""; + for (let i = 0; i < 13; i++) { + out = TID_CHARS[Number(value & 31n)] + out; + value >>= 5n; + } + return out; +} + +const repoData = (n: number) => new Uint8Array(32).fill(n); + +// --------------------------------------------------------------------- + describe("space routes: personal data (S1)", () => { it("creates a space, writes and reads records with a session", async () => { const space = await createSpace(); @@ -244,16 +320,15 @@ describe("space routes: personal data (S1)", () => { $type: "app.bsky.feed.post", text: "hello spaces", }); - expect(created.uri).toBe( - `${space}/${OPERATOR}/app.bsky.feed.post/${created.uri.split("/").pop()}`, - ); - const rkey = created.uri.split("/").pop()!; - const res = await app.request( - `/xrpc/com.atproto.space.getRecord?space=${encodeURIComponent(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=${rkey}`, - { headers: { Authorization: "Bearer operator-session" } }, + expect(created.uri).toBe(`${space}/${OPERATOR}/app.bsky.feed.post/${rkey}`); + + const res = await get( + `/xrpc/com.atproto.space.getRecord?space=${q(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=${rkey}`, ); expect(res.status).toBe(200); + // A session reading its own data gets no MAC unless it asks. + expect(res.headers.get("atproto-space-mac")).toBeNull(); const body = (await res.json()) as { value: { text: string }; cid: string }; expect(body.value.text).toBe("hello spaces"); expect(body.cid).toBe(created.cid); @@ -262,1013 +337,992 @@ describe("space routes: personal data (S1)", () => { it("refuses an unauthenticated getRecord", async () => { const space = await createSpace(); await createRecord(space, { $type: "app.bsky.feed.post", text: "x" }, "aaa"); - const res = await app.request( - `/xrpc/com.atproto.space.getRecord?space=${encodeURIComponent(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=aaa`, + const res = await get( + `/xrpc/com.atproto.space.getRecord?space=${q(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=aaa`, + {}, ); expect(res.status).toBe(401); }); it("returns RepoNotFound for a repo that is not the operator", async () => { const space = await createSpace(); - const res = await app.request( - `/xrpc/com.atproto.space.getRecord?space=${encodeURIComponent(space)}&repo=${BOB}&collection=app.bsky.feed.post&rkey=aaa`, - { headers: { Authorization: "Bearer operator-session" } }, + const res = await get( + `/xrpc/com.atproto.space.getRecord?space=${q(space)}&repo=${BOB}&collection=app.bsky.feed.post&rkey=aaa`, ); expect(res.status).toBe(404); - expect(((await res.json()) as { error: string }).error).toBe( - "RepoNotFound", - ); + expect(await errorOf(res)).toBe("RepoNotFound"); }); it("requires createSpace before writing into an own-authority space", async () => { - const res = await app.request("/xrpc/com.atproto.space.createRecord", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: "Bearer operator-session", - }, - body: JSON.stringify({ - space: `at://${OPERATOR}/space/app.bsky.group/nevercreated`, - repo: OPERATOR, - collection: "app.bsky.feed.post", - record: { $type: "app.bsky.feed.post", text: "x" }, - }), + const res = await post("/xrpc/com.atproto.space.createRecord", { + space: `at://${OPERATOR}/space/app.bsky.group/nevercreated`, + repo: OPERATOR, + collection: "app.bsky.feed.post", + record: { $type: "app.bsky.feed.post", text: "x" }, }); expect(res.status).toBe(404); - expect(((await res.json()) as { error: string }).error).toBe( - "SpaceNotFound", - ); + expect(await errorOf(res)).toBe("SpaceNotFound"); }); it("enforces scoped sessions on writes and reads", async () => { const space = await createSpace(); - // Write-only scope cannot read. const writeOnly = `Bearer scoped:${JSON.stringify({ actions: ["create"] })}`; - const write = await app.request("/xrpc/com.atproto.space.createRecord", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: writeOnly, - }, - body: JSON.stringify({ + const write = await post( + "/xrpc/com.atproto.space.createRecord", + { space, repo: OPERATOR, collection: "app.bsky.feed.post", rkey: "scoped", record: { $type: "app.bsky.feed.post", text: "x" }, - }), - }); - expect(write.status).toBe(200); - - const read = await app.request( - `/xrpc/com.atproto.space.getRecord?space=${encodeURIComponent(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=scoped`, - { headers: { Authorization: writeOnly } }, + }, + { Authorization: writeOnly }, ); - expect(read.status).toBe(403); - + expect(write.status).toBe(200); + const path = `/xrpc/com.atproto.space.getRecord?space=${q(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=scoped`; + expect((await get(path, { Authorization: writeOnly })).status).toBe(403); const readOnly = `Bearer scoped:${JSON.stringify({ actions: ["read_self"] })}`; - const read2 = await app.request( - `/xrpc/com.atproto.space.getRecord?space=${encodeURIComponent(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=scoped`, - { headers: { Authorization: readOnly } }, - ); - expect(read2.status).toBe(200); - - const denyWrite = await app.request("/xrpc/com.atproto.space.createRecord", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: readOnly, - }, - body: JSON.stringify({ - space, - repo: OPERATOR, - collection: "app.bsky.feed.post", - record: { $type: "app.bsky.feed.post", text: "x" }, - }), - }); - expect(denyWrite.status).toBe(403); + expect((await get(path, { Authorization: readOnly })).status).toBe(200); }); it("applyWrites returns typed results in order", async () => { const space = await createSpace(); - await createRecord(space, { $type: "app.bsky.feed.post", text: "d" }, "del"); - const res = await app.request("/xrpc/com.atproto.space.applyWrites", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: "Bearer operator-session", - }, - body: JSON.stringify({ - space, - repo: OPERATOR, - writes: [ - { - $type: "com.atproto.space.applyWrites#create", - collection: "app.bsky.feed.post", - rkey: "batch1", - value: { $type: "app.bsky.feed.post", text: "one" }, - }, - { - $type: "com.atproto.space.applyWrites#delete", - collection: "app.bsky.feed.post", - rkey: "del", - }, - ], - }), + const res = await post("/xrpc/com.atproto.space.applyWrites", { + space, + repo: OPERATOR, + writes: [ + { + $type: "com.atproto.space.applyWrites#create", + collection: "app.bsky.feed.post", + rkey: "one", + value: { $type: "app.bsky.feed.post", text: "1" }, + }, + { + $type: "com.atproto.space.applyWrites#update", + collection: "app.bsky.feed.post", + rkey: "one", + value: { $type: "app.bsky.feed.post", text: "1b" }, + }, + { + $type: "com.atproto.space.applyWrites#delete", + collection: "app.bsky.feed.post", + rkey: "one", + }, + ], }); expect(res.status).toBe(200); - const { results } = (await res.json()) as { - results: Array<{ $type: string; uri?: string }>; - }; - expect(results[0]?.$type).toBe("com.atproto.space.applyWrites#createResult"); - expect(results[0]?.uri).toContain("/app.bsky.feed.post/batch1"); - expect(results[1]?.$type).toBe("com.atproto.space.applyWrites#deleteResult"); + const body = (await res.json()) as { results: Array<{ $type: string }> }; + expect(body.results.map((r) => r.$type)).toEqual([ + "com.atproto.space.applyWrites#createResult", + "com.atproto.space.applyWrites#updateResult", + "com.atproto.space.applyWrites#deleteResult", + ]); }); it("putRecord upserts and deleteRecord is idempotent", async () => { const space = await createSpace(); - const put = async (text: string) => - app.request("/xrpc/com.atproto.space.putRecord", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: "Bearer operator-session", - }, - body: JSON.stringify({ - space, - repo: OPERATOR, - collection: "app.bsky.feed.post", - rkey: "upsert", - record: { $type: "app.bsky.feed.post", text }, - }), + const put = (text: string) => + post("/xrpc/com.atproto.space.putRecord", { + space, + repo: OPERATOR, + collection: "app.bsky.feed.post", + rkey: "p", + record: { $type: "app.bsky.feed.post", text }, }); - const first = await put("v1"); - expect(first.status).toBe(200); - const second = await put("v2"); - expect(second.status).toBe(200); - const firstCid = ((await first.json()) as { cid: string }).cid; - const secondCid = ((await second.json()) as { cid: string }).cid; - expect(secondCid).not.toBe(firstCid); - - const del = async () => - app.request("/xrpc/com.atproto.space.deleteRecord", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: "Bearer operator-session", - }, - body: JSON.stringify({ - space, - repo: OPERATOR, - collection: "app.bsky.feed.post", - rkey: "upsert", - }), + expect((await put("a")).status).toBe(200); + expect((await put("b")).status).toBe(200); + const del = () => + post("/xrpc/com.atproto.space.deleteRecord", { + space, + repo: OPERATOR, + collection: "app.bsky.feed.post", + rkey: "p", }); expect((await del()).status).toBe(200); - // Deleting again succeeds silently. expect((await del()).status).toBe(200); }); -}); -describe("space routes: credentials (S5)", () => { - it("issues, gates and revokes space credentials", async () => { + it("refuses oversized records and direct writes to published collections", async () => { const space = await createSpace(); - await createRecord(space, { $type: "app.bsky.feed.post", text: "m" }, "mem"); - - // Not a member yet: UserNotAuthorized. - const refused = await obtainCredential(space, bobKeypair, BOB); - expect(refused.status).toBe(403); - expect((refused.body as { error: string }).error).toBe("UserNotAuthorized"); - - // Add bob, obtain a credential. - const add = await app.request("/xrpc/com.atproto.simplespace.addMember", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: "Bearer operator-session", - }, - body: JSON.stringify({ space, did: BOB }), + const big = await post("/xrpc/com.atproto.space.createRecord", { + space, + repo: OPERATOR, + collection: "app.bsky.feed.post", + record: { $type: "app.bsky.feed.post", text: "x".repeat(1024 * 1024 + 1) }, }); - expect(add.status).toBe(200); - - const granted = await obtainCredential(space, bobKeypair, BOB); - expect(granted.status).toBe(200); - expect(granted.credential).toBeTruthy(); + expect(big.status).toBe(400); + expect(await errorOf(big)).toBe("InvalidRequest"); + + for (const collection of [ + "com.atproto.space.policy", + "com.atproto.memberspace.member", + ]) { + const res = await post("/xrpc/com.atproto.space.createRecord", { + space, + repo: OPERATOR, + collection, + rkey: "self", + record: { $type: collection }, + }); + expect(res.status).toBe(400); + } + }); - // The credential reads the space. - const read = await credentialGet( - `/xrpc/com.atproto.space.getRecord?space=${encodeURIComponent(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=mem`, - granted.credential, - granted.dpopKey, + it("clearRecords empties the repo but keeps published configuration", async () => { + const space = await createSpace({ + ...MEMBERSPACE, + publishPolicy: true, + }); + await createRecord(space, { $type: "app.bsky.feed.post", text: "a" }, "a"); + await createRecord(space, { $type: "app.bsky.feed.like", subject: "x" }, "b", "app.bsky.feed.like"); + + // A scoped session needs delete on every collection being cleared. + const narrow = `Bearer scoped:${JSON.stringify({ actions: ["read_self"] })}`; + const refused = await post( + "/xrpc/com.atproto.space.clearRecords", + { space, repo: OPERATOR }, + { Authorization: narrow }, ); - expect(read.status).toBe(200); + expect(refused.status).toBe(403); - // Remove bob: next credential request fails, but the existing - // credential still works until expiry. - await app.request("/xrpc/com.atproto.simplespace.removeMember", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: "Bearer operator-session", - }, - body: JSON.stringify({ space, did: BOB }), + const res = await post("/xrpc/com.atproto.space.clearRecords", { + space, + repo: OPERATOR, }); - const refusedAgain = await obtainCredential(space, bobKeypair, BOB); - expect(refusedAgain.status).toBe(403); - expect((refusedAgain.body as { error: string }).error).toBe( - "UserNotAuthorized", + expect(res.status).toBe(200); + const list = await get( + `/xrpc/com.atproto.space.listRecords?space=${q(space)}&repo=${OPERATOR}`, ); + const { records } = (await list.json()) as { + records: Array<{ collection: string }>; + }; + expect(records.map((r) => r.collection)).toEqual(["com.atproto.space.policy"]); - const stillReads = await credentialGet( - `/xrpc/com.atproto.space.getRecord?space=${encodeURIComponent(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=mem`, - granted.credential, - granted.dpopKey, + const ops = await get( + `/xrpc/com.atproto.space.listRepoOps?space=${q(space)}&repo=${OPERATOR}`, ); - expect(stillReads.status).toBe(200); + const opsBody = (await ops.json()) as { ops: unknown[]; commit: Record }; + expect(opsBody.ops).toEqual([]); + // The digest is that of the records that remain. + const commit = commitFromJson(opsBody.commit); + const remaining = await get( + `/xrpc/com.atproto.space.getRecord?space=${q(space)}&repo=${OPERATOR}&collection=com.atproto.space.policy&rkey=self`, + ); + const { cid } = (await remaining.json()) as { cid: string }; + const expected = new LtHash(); + expected.add(`com.atproto.space.policy/self/${cid}`); + expect(commit.data).toEqual(expected.digest()); + + const other = await post( + "/xrpc/com.atproto.space.clearRecords", + { space, repo: BOB }, + ); + expect(other.status).toBe(403); }); +}); - it("rejects a replayed delegation token", async () => { - const space = await createSpace({ - $type: "com.atproto.simplespace.defs#publicPolicy", +describe("space routes: credentials (S5)", () => { + it("issues credentials to members, binds them to the request key and refuses others as SpaceNotFound", async () => { + const space = await createSpace(); + await createRecord(space, { $type: "app.bsky.feed.post", text: "hi" }, "r1"); + + const denied = await obtainCredential(space, { + user: { did: BOB, keypair: bobKeypair }, + }); + expect(denied.status).toBe(404); + expect((denied.body as { error: string }).error).toBe("SpaceNotFound"); + + await putMember(space, BOB); + const { credential, key, status } = await obtainCredential(space, { + user: { did: BOB, keypair: bobKeypair }, + }); + expect(status).toBe(200); + const payload = JSON.parse( + atob(credential.split(".")[1]!.replace(/-/g, "+").replace(/_/g, "/")), + ) as { cnf: { kid: string }; iss: string; sub: string; aud?: string }; + expect(payload.cnf.kid).toBe(key.did()); + expect(payload.iss).toBe(OPERATOR); + expect(payload.sub).toBe(space); + expect(payload.aud).toBeUndefined(); + + const path = `/xrpc/com.atproto.space.getRecord?space=${q(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=r1`; + const { res, sharedSecret } = await credentialRequest(path, credential, key, { + mac: RECORD_MAC_TYPE, }); - const dpopKey = await JoseKey.generate(["ES256"]); - const delegation = await createSpaceToken( + expect(res.status).toBe(200); + const record = (await res.json()) as { uri: string; cid: string; value: Record }; + const mac = parseMacHeader(res.headers.get("atproto-space-mac") ?? undefined, RECORD_MAC_TYPE); + expect( + await verifyRecord(record as never, { uri: record.uri, sharedSecret: sharedSecret!, mac }), + ).toBe(true); + expect(res.headers.get("access-control-expose-headers")).toContain("atproto-space-mac"); + + // A member without read access is refused like a stranger. + await putMember(space, BOB, false, true); + const noRead = await obtainCredential(space, { user: { did: BOB, keypair: bobKeypair } }); + expect(noRead.status).toBe(404); + }); + + it("validates credentialKid and the delegation token", async () => { + const space = await createSpace({ ...MEMBERSPACE, publicRead: true }); + const k256 = await post( + "/xrpc/com.atproto.space.getSpaceCredential", + { space, credentialKid: bobKeypair.did() }, + {}, + ); + expect(k256.status).toBe(400); + expect(await errorOf(k256)).toBe("InvalidRequest"); + + const key = await P256Keypair.create(); + const token = await createSpaceToken( "delegation", { iss: BOB, sub: space, aud: spaceHostAud(OPERATOR) }, bobKeypair, ); - const request = async () => { - const proof = await createDpopProof(dpopKey, { - htm: "POST", - htu: `${ORIGIN}/xrpc/com.atproto.space.getSpaceCredential`, - }); - return app.request("/xrpc/com.atproto.space.getSpaceCredential", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${delegation}`, - DPoP: proof, - }, - body: JSON.stringify({ space }), - }); - }; + const request = () => + post( + "/xrpc/com.atproto.space.getSpaceCredential", + { space, credentialKid: key.did(), delegationToken: token }, + {}, + ); expect((await request()).status).toBe(200); - const replayed = await request(); - expect(replayed.status).toBe(401); - expect(((await replayed.json()) as { error: string }).error).toBe( - "InvalidDelegationToken", + const replay = await request(); + expect(replay.status).toBe(400); + expect(await errorOf(replay)).toBe("InvalidDelegationToken"); + + const wrongAud = await createSpaceToken( + "delegation", + { iss: BOB, sub: space, aud: `${OPERATOR}#atproto_space_host` }, + bobKeypair, ); + const badAud = await post( + "/xrpc/com.atproto.space.getSpaceCredential", + { space, credentialKid: key.did(), delegationToken: wrongAud }, + {}, + ); + expect(await errorOf(badAud)).toBe("InvalidDelegationToken"); }); - it("rejects a replayed DPoP proof and a cross-space credential", async () => { - const spaceA = await createSpace({ - $type: "com.atproto.simplespace.defs#publicPolicy", - }); - const spaceB = await createSpace({ - $type: "com.atproto.simplespace.defs#publicPolicy", - }); - await createRecord(spaceA, { $type: "app.bsky.feed.post", text: "a" }, "ra"); - await createRecord(spaceB, { $type: "app.bsky.feed.post", text: "b" }, "rb"); + it("issues public-read credentials without a delegation token, and only those", async () => { + const closed = await createSpace(); + const anon = await obtainCredential(closed); + expect(anon.status).toBe(404); + expect((anon.body as { error: string }).error).toBe("SpaceNotFound"); + + const open = await createSpace({ ...MEMBERSPACE, publicRead: true }); + await createRecord(open, { $type: "app.bsky.feed.post", text: "public" }, "p"); + const { credential, key, status } = await obtainCredential(open); + expect(status).toBe(200); + const { res } = await credentialRequest( + `/xrpc/com.atproto.space.listRecords?space=${q(open)}&repo=${OPERATOR}`, + credential, + key, + ); + expect(res.status).toBe(200); + }); - const granted = await obtainCredential(spaceA, bobKeypair, BOB); - expect(granted.status).toBe(200); + it("refuses bad signatures, audiences, spaces, schemes and revoked credentials", async () => { + const space = await createSpace({ ...MEMBERSPACE, publicRead: true }); + await createRecord(space, { $type: "app.bsky.feed.post", text: "x" }, "x"); + const other = await createSpace({ ...MEMBERSPACE, publicRead: true }); + await createRecord(other, { $type: "app.bsky.feed.post", text: "y" }, "y"); + const { credential, key } = await obtainCredential(space); + const path = `/xrpc/com.atproto.space.listRecords?space=${q(space)}&repo=${OPERATOR}`; + + const ok = await credentialRequest(path, credential, key, { scheme: "atproto-space-credential" }); + expect(ok.res.status).toBe(200); + + const wrongKey = await credentialRequest(path, credential, await P256Keypair.create()); + expect(wrongKey.res.status).toBe(401); + expect(await errorOf(wrongKey.res)).toBe("BadSpaceSignature"); + + const wrongAudience = await credentialRequest(path, credential, key, { audience: BOB }); + expect(wrongAudience.res.status).toBe(401); + expect(await errorOf(wrongAudience.res)).toBe("BadSpaceAudience"); + + const crossSpace = await credentialRequest( + `/xrpc/com.atproto.space.listRecords?space=${q(other)}&repo=${OPERATOR}`, + credential, + key, + ); + expect(crossSpace.res.status).toBe(400); + expect(await errorOf(crossSpace.res)).toBe("InvalidCredential"); + + // A credential read that returns a commit must ask for a MAC. + const noMac = await credentialRequest( + `/xrpc/com.atproto.space.getLatestCommit?space=${q(space)}&repo=${OPERATOR}`, + credential, + key, + ); + expect(noMac.res.status).toBe(400); + expect(await errorOf(noMac.res)).toBe("BadSpaceMac"); - const path = `/xrpc/com.atproto.space.getRecord?space=${encodeURIComponent(spaceA)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=ra`; - const proof = await createDpopProof(granted.dpopKey, { - htm: "GET", - htu: `${ORIGIN}/xrpc/com.atproto.space.getRecord`, - credential: granted.credential, - }); - const headers = { - Authorization: `DPoP ${granted.credential}`, - DPoP: proof, - }; - expect((await app.request(path, { headers })).status).toBe(200); - // Same proof again: replayed. - const replayed = await app.request(path, { headers }); - expect(replayed.status).toBe(401); - - // Credential for space A cannot read space B. - const cross = await credentialGet( - `/xrpc/com.atproto.space.getRecord?space=${encodeURIComponent(spaceB)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=rb`, - granted.credential, - granted.dpopKey, + // Revocation, by the authority, addressed to the repo DID. + const jti = ( + JSON.parse(atob(credential.split(".")[1]!.replace(/-/g, "+").replace(/_/g, "/"))) as { + jti: string; + } + ).jti; + const forged = await serviceJwt(BOB, OPERATOR, "com.atproto.space.notifyCredentialRevoked", bobKeypair); + const forgedRes = await post( + "/xrpc/com.atproto.space.notifyCredentialRevoked", + { space, credentials: [jti] }, + { Authorization: `Bearer ${forged}` }, + ); + expect(forgedRes.status).toBe(403); + const token = await serviceJwt(OPERATOR, OPERATOR, "com.atproto.space.notifyCredentialRevoked", operatorKeypair); + const revoke = await post( + "/xrpc/com.atproto.space.notifyCredentialRevoked", + { space, credentials: [jti] }, + { Authorization: `Bearer ${token}` }, ); - expect(cross.status).toBe(401); + expect(revoke.status).toBe(200); + const revoked = await credentialRequest(path, credential, key); + expect(revoked.res.status).toBe(401); + expect(await errorOf(revoked.res)).toBe("CredentialRevoked"); }); - it("gates on the app allowList with client attestations", async () => { - const clientId = "https://app.test/client-metadata.json"; - const clientKey = await JoseKey.generate(["ES256"], "client-key-1"); - const { host: attHost, outbound, setOutboundResponse } = makeHost(); + it("gates on allowedApps with client attestations, after the user", async () => { + const clientId = "https://app.example/client-metadata.json"; + const jwk = await JoseKey.generate(["ES256"], "attest-key"); + const space = await createSpace({ ...MEMBERSPACE, publicRead: true, allowedApps: [clientId] }); + + const { host: attestHost, setOutboundResponse: respond } = makeHost(); + const attestApp = createSpaceRoutes(attestHost); // Publish a clean JWKS entry (kty/crv/x/y/kid/alg): key_ops from the // generated key would be rejected by workerd's ECDSA import. - const clientJwk = { - ...clientKey.bareJwk, - kid: clientKey.kid, - alg: "ES256", - }; - setOutboundResponse((url) => { - if (url === clientId) { - return Response.json({ jwks: { keys: [clientJwk] } }); - } - return null; - }); - const attApp = createSpaceRoutes(attHost); - - const createRes = await attApp.request( - "/xrpc/com.atproto.simplespace.createSpace", - { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: "Bearer operator-session", - }, - body: JSON.stringify({ - type: "app.bsky.group", - skey: "attested", - policy: { $type: "com.atproto.simplespace.defs#publicPolicy" }, - appAccess: { - $type: "com.atproto.simplespace.defs#allowList", - allowed: [clientId], - }, - }), - }, + const clientJwk = { ...jwk.bareJwk, kid: jwk.kid, alg: "ES256" }; + respond((url) => + url === clientId ? Response.json({ jwks: { keys: [clientJwk] } }) : null, ); - expect(createRes.status).toBe(200); - const { uri: space } = (await createRes.json()) as { uri: string }; - - const dpopKey = await JoseKey.generate(["ES256"]); - const requestCredential = async (attestation?: string) => { - const delegation = await createSpaceToken( - "delegation", - { iss: BOB, sub: space, aud: spaceHostAud(OPERATOR) }, - bobKeypair, + const attest = async (aud = spaceHostAud(OPERATOR), id = clientId) => { + const iat = Math.floor(Date.now() / 1000); + return jwk.createJwt( + { alg: "ES256", typ: "atproto-client-attestation+jwt", kid: jwk.kid }, + { iss: id, sub: id, aud, iat, exp: iat + 60, jti: crypto.randomUUID() }, ); - const proof = await createDpopProof(dpopKey, { - htm: "POST", - htu: `${ORIGIN}/xrpc/com.atproto.space.getSpaceCredential`, - }); - return attApp.request("/xrpc/com.atproto.space.getSpaceCredential", { + }; + const request = async (clientAttestation?: string) => { + const key = await P256Keypair.create(); + return attestApp.request("/xrpc/com.atproto.space.getSpaceCredential", { method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${delegation}`, - DPoP: proof, - }, + headers: { "Content-Type": "application/json" }, body: JSON.stringify({ space, - ...(attestation ? { clientAttestation: attestation } : {}), + credentialKid: key.did(), + ...(clientAttestation ? { clientAttestation } : {}), }), }); }; - // No attestation: refused on the app perimeter. - const missing = await requestCredential(); - expect(missing.status).toBe(403); - expect(((await missing.json()) as { error: string }).error).toBe( - "AppNotAuthorized", - ); + const none = await request(); + expect(none.status).toBe(403); + expect(await errorOf(none)).toBe("AppNotAuthorized"); - // Valid attestation from the allowed client. - const makeAttestation = async (iss: string) => - clientKey.createJwt( - { - alg: "ES256", - typ: "atproto-client-attestation+jwt", - kid: clientKey.kid, - }, - { - iss, - sub: iss, - aud: spaceHostAud(OPERATOR), - jti: crypto.randomUUID(), - iat: Math.floor(Date.now() / 1000), - exp: Math.floor(Date.now() / 1000) + 60, - }, - ); - const granted = await requestCredential(await makeAttestation(clientId)); - expect(granted.status).toBe(200); - - // An attested client that is not on the list is refused before any - // network I/O for it happens — the unverified client_id must never - // become an outbound-fetch target. - const otherId = "https://other.test/client-metadata.json"; - setOutboundResponse((url) => - url === otherId || url === clientId - ? Response.json({ jwks: { keys: [clientJwk] } }) - : null, - ); - const wrongClient = await requestCredential( - await makeAttestation(otherId), - ); - expect(wrongClient.status).toBe(403); - expect(((await wrongClient.json()) as { error: string }).error).toBe( - "AppNotAuthorized", - ); - expect(outbound.some((o) => o.url.startsWith(otherId))).toBe(false); - - // A non-https client_id is rejected outright, also without a fetch. - const httpId = "http://evil.internal/metadata.json"; - const badScheme = await requestCredential(await makeAttestation(httpId)); - expect(badScheme.status).toBe(401); - expect(((await badScheme.json()) as { error: string }).error).toBe( - "InvalidClientAttestation", - ); - expect(outbound.some((o) => o.url.startsWith(httpId))).toBe(false); - }); + expect((await request(await attest())).status).toBe(200); - it("consults the managing app and denies on failure", async () => { - const managingApp = "did:web:forum.test#forum"; - const { host: maHost, outbound, setOutboundResponse } = makeHost(); - const maApp = createSpaceRoutes(maHost); - const createRes = await maApp.request( - "/xrpc/com.atproto.simplespace.createSpace", - { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: "Bearer operator-session", - }, - body: JSON.stringify({ - type: "app.bsky.group", - skey: "managed", - policy: { - $type: "com.atproto.simplespace.defs#managingAppPolicy", - managingApp, - }, - appAccess: { $type: "com.atproto.simplespace.defs#open" }, - }), - }, - ); - const { uri: space } = (await createRes.json()) as { uri: string }; + const otherApp = await request(await attest(undefined, "https://other.example/client-metadata.json")); + expect(await errorOf(otherApp)).toBe("AppNotAuthorized"); - setOutboundResponse((url) => - url.includes("checkUserAccess") - ? Response.json({ authorized: true }) - : null, - ); - const dpopKey = await JoseKey.generate(["ES256"]); - const request = async () => { - const delegation = await createSpaceToken( - "delegation", - { iss: BOB, sub: space, aud: spaceHostAud(OPERATOR) }, - bobKeypair, + const wrongAud = await request(await attest(`${OPERATOR}#atproto_space_host`)); + expect(await errorOf(wrongAud)).toBe("InvalidClientAttestation"); + }); + + it("consults the managing app with the access kind and denies on failure", async () => { + const space = await createSpace({ + $type: "com.atproto.managedspace.policy", + managingApp: "did:web:manager.test#forum", + }); + setOutboundResponse((url) => { + if (!url.includes("checkUserAccess")) return null; + const user = new URL(url).searchParams.get("user"); + return Response.json({ authorized: user === BOB }); + }); + try { + const bob = await obtainCredential(space, { user: { did: BOB, keypair: bobKeypair } }); + expect(bob.status).toBe(200); + const check = outbound.filter((call) => call.url.includes("checkUserAccess")).pop()!; + const params = new URL(check.url).searchParams; + expect(params.get("access")).toBe("read"); + expect(params.get("space")).toBe(space); + + const carol = await obtainCredential(space, { user: { did: CAROL, keypair: carolKeypair } }); + expect(carol.status).toBe(404); + + setOutboundResponse((url) => + url.includes("checkUserAccess") ? new Response("boom", { status: 500 }) : null, ); - const proof = await createDpopProof(dpopKey, { - htm: "POST", - htu: `${ORIGIN}/xrpc/com.atproto.space.getSpaceCredential`, - }); - return maApp.request("/xrpc/com.atproto.space.getSpaceCredential", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${delegation}`, - DPoP: proof, - }, - body: JSON.stringify({ space }), - }); - }; - expect((await request()).status).toBe(200); - const call = outbound.find((o) => o.url.includes("checkUserAccess")); - expect(call?.url).toContain(`user=${encodeURIComponent(BOB)}`); - - // The managing app saying no (or erroring) denies. - setOutboundResponse((url) => - url.includes("checkUserAccess") - ? Response.json({ authorized: false }) - : null, - ); - expect((await request()).status).toBe(403); + const failing = await obtainCredential(space, { user: { did: BOB, keypair: bobKeypair } }); + expect(failing.status).toBe(404); + } finally { + setOutboundResponse(() => null); + } + }); + + it("personalspace authorises only the authority", async () => { + const space = await createSpace({ $type: "com.atproto.personalspace.policy" }); + const bob = await obtainCredential(space, { user: { did: BOB, keypair: bobKeypair } }); + expect(bob.status).toBe(404); + const self = await obtainCredential(space, { + user: { did: OPERATOR, keypair: operatorKeypair }, + }); + expect(self.status).toBe(200); }); }); describe("space routes: sync (S2-S4)", () => { - it("serves a verifiable signed commit", async () => { + async function syncerCredential(space: string) { + await putMember(space, BOB); + return obtainCredential(space, { user: { did: BOB, keypair: bobKeypair } }); + } + + it("serves a commit with a verifiable MAC", async () => { const space = await createSpace(); - await createRecord(space, { $type: "app.bsky.feed.post", text: "c" }, "c1"); - const res = await app.request( - `/xrpc/com.atproto.space.getLatestCommit?space=${encodeURIComponent(space)}&repo=${OPERATOR}`, - { headers: { Authorization: "Bearer operator-session" } }, + await createRecord(space, { $type: "app.bsky.feed.post", text: "a" }); + const { credential, key } = await syncerCredential(space); + const { res, sharedSecret } = await credentialRequest( + `/xrpc/com.atproto.space.getLatestCommit?space=${q(space)}&repo=${OPERATOR}`, + credential, + key, + { mac: COMMIT_MAC_TYPE }, ); expect(res.status).toBe(200); - const { commit } = (await res.json()) as { - commit: Record; - }; - const signed = commitFromJson(commit); + expect(res.headers.get("vary")).toContain("atproto-space-want-mac"); + const commit = commitFromJson(((await res.json()) as { commit: Record }).commit); + expect(commit.repo).toBe(OPERATOR); + expect(commit.space).toBe(space); + const mac = parseMacHeader(res.headers.get("atproto-space-mac") ?? undefined, COMMIT_MAC_TYPE); + expect(verifyCommit(commit, { space, repo: OPERATOR, sharedSecret: sharedSecret!, mac })).toBe(true); + // The MAC is per request: another shared secret does not verify it. + const other = await encapsulate(kemDid); expect( - await verifyCommit( - signed, - { space, author: OPERATOR, rev: signed.rev }, - operatorKeypair.did(), - ), - ).toBe(true); + verifyCommit(commit, { space, repo: OPERATOR, sharedSecret: other.sharedSecret, mac }), + ).toBe(false); }); - it("lets a syncer follow listRepoOps to a matching hash", async () => { + it("lets a syncer follow listRepoOps to the commit's data", async () => { const space = await createSpace(); - await createRecord(space, { $type: "app.bsky.feed.post", text: "1" }, "s1"); - await createRecord(space, { $type: "app.bsky.feed.post", text: "2" }, "s2"); - - const res = await app.request( - `/xrpc/com.atproto.space.listRepoOps?space=${encodeURIComponent(space)}&repo=${OPERATOR}`, - { headers: { Authorization: "Bearer operator-session" } }, + await createRecord(space, { $type: "app.bsky.feed.post", text: "a" }, "a"); + await createRecord(space, { $type: "app.bsky.feed.post", text: "b" }, "b"); + await post("/xrpc/com.atproto.space.deleteRecord", { + space, + repo: OPERATOR, + collection: "app.bsky.feed.post", + rkey: "a", + }); + const { credential, key } = await syncerCredential(space); + const { res, sharedSecret } = await credentialRequest( + `/xrpc/com.atproto.space.listRepoOps?space=${q(space)}&repo=${OPERATOR}`, + credential, + key, + { mac: COMMIT_MAC_TYPE }, ); - expect(res.status).toBe(200); const body = (await res.json()) as { - ops: Array<{ - collection: string; - rkey: string; - cid: string | null; - prev: string | null; - value?: unknown; - }>; + ops: Array<{ collection: string; rkey: string; cid: string | null; prev: string | null }>; commit: Record; - cursor?: string; }; - expect(body.cursor).toBeUndefined(); - expect(body.ops).toHaveLength(2); - expect(body.ops[0]?.value).toBeDefined(); - - // Syncer folds the ops into its own set hash and compares. - const setHash = new LtHash(); + const hash = new LtHash(); for (const op of body.ops) { - if (op.prev) setHash.remove(`${op.collection}/${op.rkey}/${op.prev}`); - if (op.cid) setHash.add(`${op.collection}/${op.rkey}/${op.cid}`); + if (op.prev) hash.remove(`${op.collection}/${op.rkey}/${op.prev}`); + if (op.cid) hash.add(`${op.collection}/${op.rkey}/${op.cid}`); } - const signed = commitFromJson(body.commit); - expect(setHash.digest()).toEqual(signed.hash); + const commit = commitFromJson(body.commit); + expect(hash.digest()).toEqual(commit.data); + const mac = parseMacHeader(res.headers.get("atproto-space-mac") ?? undefined, COMMIT_MAC_TYPE); + expect(verifyCommit(commit, { space, repo: OPERATOR, sharedSecret: sharedSecret!, mac })).toBe(true); }); - it("streams a CAR that the @atproto/space consumer verifies (S8)", async () => { + it("streams a STAR archive the @atproto/space consumer verifies (S8)", async () => { const space = await createSpace(); - await createRecord(space, { $type: "app.bsky.feed.post", text: "car1" }, "k1"); - await createRecord(space, { $type: "app.bsky.feed.post", text: "car2" }, "k2"); - - const res = await app.request( - `/xrpc/com.atproto.space.getRepo?space=${encodeURIComponent(space)}&repo=${OPERATOR}`, - { headers: { Authorization: "Bearer operator-session" } }, + // One collection NSID prefixes another: (collection, rkey) order and + // byte order of the record path disagree, and the archive needs the + // latter. + await createRecord(space, { $type: "app.bsky.feed.post", text: "1" }, "z", "app.bsky.feed"); + await createRecord(space, { $type: "app.bsky.feed.post", text: "2" }, "a", "app.bsky.feed.post"); + for (let i = 0; i < 3; i++) { + await createRecord(space, { $type: "app.bsky.feed.post", text: `n${i}` }); + } + const { credential, key } = await syncerCredential(space); + const { res, sharedSecret } = await credentialRequest( + `/xrpc/com.atproto.space.getRepo?space=${q(space)}&repo=${OPERATOR}`, + credential, + key, + { mac: COMMIT_MAC_TYPE }, ); expect(res.status).toBe(200); - expect(res.headers.get("Content-Type")).toBe("application/vnd.ipld.car"); - const car = new Uint8Array(await res.arrayBuffer()); - const verified = await verifyRepoCarFull([car], { + expect(res.headers.get("content-type")).toBe("application/octet-stream"); + const mac = parseMacHeader(res.headers.get("atproto-space-mac") ?? undefined, COMMIT_MAC_TYPE); + const bytes = new Uint8Array(await res.arrayBuffer()); + const verified = await verifyRepoStarFull([bytes], { space, - author: OPERATOR, - didKey: operatorKeypair.did(), + repo: OPERATOR, + sharedSecret: sharedSecret!, + mac, }); - expect(verified.records).toHaveLength(2); - expect( - verified.records.map((r) => r.rkey).sort(), - ).toEqual(["k1", "k2"]); + expect(verified.records).toHaveLength(5); + expect(verified.records[0]!.collection).toBe("app.bsky.feed.post"); }); - it("records writers from inbound notifyWrite and serves listRepos", async () => { - const space = await createSpace({ - $type: "com.atproto.simplespace.defs#publicPolicy", - }); - await createRecord(space, { $type: "app.bsky.feed.post", text: "w" }, "w1"); - - const hash = new LtHash().add("x").digest(); - const serviceJwt = (iss: string, aud: string, lxm: string) => { - const enc = (o: unknown) => - btoa(JSON.stringify(o)) - .replace(/\+/g, "-") - .replace(/\//g, "_") - .replace(/=+$/, ""); - return `${enc({ alg: "ES256K", typ: "JWT" })}.${enc({ iss, aud, lxm })}.sig`; - }; - - const notify = async (iss: string, repo: string) => - app.request("/xrpc/com.atproto.space.notifyWrite", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${serviceJwt(iss, OPERATOR, "com.atproto.space.notifyWrite")}`, - }, - body: JSON.stringify({ - space, - repo, - rev: "3kzzzzzzzzzz2", - hash: { $bytes: btoa(String.fromCharCode(...hash)) }, - }), - }); - - // iss must match the claimed writer. - const spoofed = await notify("did:web:mallory.test", BOB); - expect(spoofed.status).toBe(403); - - const accepted = await notify(BOB, BOB); - expect(accepted.status).toBe(200); - - // listRepos requires a space credential and shows both writers. - const granted = await obtainCredential(space, bobKeypair, BOB); - expect(granted.status).toBe(200); - const proof = await createDpopProof(granted.dpopKey, { - htm: "GET", - htu: `${ORIGIN}/xrpc/com.atproto.space.listRepos`, - credential: granted.credential, - }); - const repos = await app.request( - `/xrpc/com.atproto.space.listRepos?space=${encodeURIComponent(space)}`, - { - headers: { - Authorization: `DPoP ${granted.credential}`, - DPoP: proof, - }, - }, + it("sequences writers from notifyWrite and serves listRepos by spaceRev", async () => { + const space = await createSpace(); + await putMember(space, BOB); + await putMember(space, CAROL); + const registrar = await obtainCredential(space, { user: { did: BOB, keypair: bobKeypair } }); + const reg = await credentialRequest( + "/xrpc/com.atproto.space.registerNotify", + registrar.credential, + registrar.key, + { method: "POST", body: { space, service: "did:web:syncer.test#atproto_space_syncer" } }, ); - expect(repos.status).toBe(200); - const reposBody = (await repos.json()) as { - repos: Array<{ did: string; rev: string }>; - }; - const dids = reposBody.repos.map((r) => r.did); - expect(dids).toContain(BOB); - expect(dids).toContain(OPERATOR); - }); + expect(reg.res.status).toBe(200); - it("ignores stale notifyWrite revisions and does not fan them out", async () => { - const space = await createSpace({ - $type: "com.atproto.simplespace.defs#publicPolicy", - }); - await createRecord(space, { $type: "app.bsky.feed.post", text: "s" }, "st"); - - const serviceJwt = (iss: string, lxm: string) => { - const enc = (o: unknown) => - btoa(JSON.stringify(o)) - .replace(/\+/g, "-") - .replace(/\//g, "_") - .replace(/=+$/, ""); - return `${enc({ alg: "ES256K", typ: "JWT" })}.${enc({ iss, aud: OPERATOR, lxm })}.sig`; + const before = outbound.length; + const t = Date.now(); + expect((await notifyWrite(space, BOB, bobKeypair, tidAt(t - 3000), repoData(1))).status).toBe(200); + expect( + (await notifyWrite(space, CAROL, carolKeypair, tidAt(t - 2000), repoData(2), spaceHostAud(OPERATOR))) + .status, + ).toBe(200); + // Stale: does not advance and is not fanned out again. + expect((await notifyWrite(space, BOB, bobKeypair, tidAt(t - 4000), repoData(9))).status).toBe(200); + + const list = await credentialRequest( + `/xrpc/com.atproto.space.listRepos?space=${q(space)}&limit=1`, + registrar.credential, + registrar.key, + ); + const page1 = (await list.res.json()) as { + repos: Array<{ did: string; repoRev: string; data: { $bytes: string }; spaceRev: string }>; + cursor?: string; }; - const notify = async (rev: string, fill: number) => - app.request("/xrpc/com.atproto.space.notifyWrite", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${serviceJwt(BOB, "com.atproto.space.notifyWrite")}`, - }, - body: JSON.stringify({ - space, - repo: BOB, - rev, - hash: { - $bytes: btoa( - String.fromCharCode(...new Uint8Array(32).fill(fill)), - ), - }, - }), - }); - - // A syncer registration to fan out to (bob is the sender and is - // excluded, so this is the only target). - const granted = await obtainCredential(space, bobKeypair, BOB); - expect(granted.status).toBe(200); - const regProof = await createDpopProof(granted.dpopKey, { - htm: "POST", - htu: `${ORIGIN}/xrpc/com.atproto.space.registerNotify`, - credential: granted.credential, - }); - const registered = await app.request( - "/xrpc/com.atproto.space.registerNotify", - { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `DPoP ${granted.credential}`, - DPoP: regProof, - }, - body: JSON.stringify({ space, service: "did:web:syncer.test" }), - }, + expect(page1.repos.map((r) => r.did)).toEqual([BOB]); + expect(page1.cursor).toBe(page1.repos[0]!.spaceRev); + expect(fromBase64(page1.repos[0]!.data.$bytes)).toEqual(repoData(1)); + const list2 = await credentialRequest( + `/xrpc/com.atproto.space.listRepos?space=${q(space)}&cursor=${page1.cursor}`, + registrar.credential, + registrar.key, ); - expect(registered.status).toBe(200); + const page2 = (await list2.res.json()) as typeof page1; + expect(page2.repos.map((r) => r.did)).toEqual([CAROL]); + expect(page2.repos[0]!.spaceRev > page1.repos[0]!.spaceRev).toBe(true); + const list3 = await credentialRequest( + `/xrpc/com.atproto.space.listRepos?space=${q(space)}&cursor=${page2.cursor}`, + registrar.credential, + registrar.key, + ); + const page3 = (await list3.res.json()) as typeof page1; + expect(page3.repos).toEqual([]); + expect(page3.cursor).toBeUndefined(); + // Two accepted updates, two fan-outs queued with sequence numbers. const stub = env.SPACES.get(env.SPACES.idFromName(space)); - const queuedBefore = (await stub.rpcStatus()).queuedNotifications; - - expect((await notify("3kzzzzzzzzzz2", 1)).status).toBe(200); - const afterFresh = await stub.rpcStatus(); - expect(afterFresh.queuedNotifications).toBe(queuedBefore + 1); - - // An older (delayed or replayed) revision succeeds quietly, but - // neither regresses the writer set nor enqueues fan-out. - expect((await notify("3kaaaaaaaaaa2", 2)).status).toBe(200); - const afterStale = await stub.rpcStatus(); - expect(afterStale.queuedNotifications).toBe(afterFresh.queuedNotifications); - - const writers = await stub.rpcListWriters({ limit: 10 }); - const bob = writers.repos.find((r) => r.did === BOB); - expect(bob?.rev).toBe("3kzzzzzzzzzz2"); - expect(new Uint8Array(bob!.hash)).toEqual(new Uint8Array(32).fill(1)); + const status = await stub.rpcStatus(); + expect(status.queuedNotifications).toBe(2); + expect(outbound.length).toBe(before); }); - it("requires notifySpaceDeleted to be addressed to this service", async () => { - const authority = "did:web:elsewhere.test"; - const foreignSpace = `at://${authority}/space/app.bsky.group/deleteme`; - const { host: fHost } = makeHost(); - const fApp = createSpaceRoutes(fHost); - - // Hold a repo in the foreign space. - const write = await fApp.request("/xrpc/com.atproto.space.createRecord", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: "Bearer operator-session", - }, - body: JSON.stringify({ - space: foreignSpace, - repo: OPERATOR, - collection: "app.bsky.feed.post", - rkey: "keepme", - record: { $type: "app.bsky.feed.post", text: "x" }, - }), - }); - expect(write.status).toBe(200); + it("refuses unauthorised, mismatched and future notifyWrites", async () => { + const space = await createSpace(); + const now = Date.now(); + const stranger = await notifyWrite(space, BOB, bobKeypair, tidAt(now), repoData(1)); + expect(stranger.status).toBe(403); + + await putMember(space, BOB, true, false); + const readOnly = await notifyWrite(space, BOB, bobKeypair, tidAt(now), repoData(1)); + expect(readOnly.status).toBe(403); + + const open = await createSpace({ ...MEMBERSPACE, publicWrite: true }); + expect((await notifyWrite(open, BOB, bobKeypair, tidAt(now), repoData(1))).status).toBe(200); + const future = await notifyWrite(open, BOB, bobKeypair, tidAt(now + 10 * 60_000), repoData(1)); + expect(future.status).toBe(400); + expect(await errorOf(future)).toBe("FutureRev"); + const wrongAud = await notifyWrite(open, BOB, bobKeypair, tidAt(now + 1), repoData(1), BOB); + expect(wrongAud.status).toBe(403); + + const token = await serviceJwt(CAROL, OPERATOR, "com.atproto.space.notifyWrite", carolKeypair); + const impersonation = await post( + "/xrpc/com.atproto.space.notifyWrite", + { space: open, repo: BOB, repoRev: tidAt(now + 2), data: { $bytes: "AA==" } }, + { Authorization: `Bearer ${token}` }, + ); + expect(impersonation.status).toBe(403); - const enc = (o: unknown) => - btoa(JSON.stringify(o)) - .replace(/\+/g, "-") - .replace(/\//g, "_") - .replace(/=+$/, ""); - const notifyDeleted = async (aud: string) => - fApp.request("/xrpc/com.atproto.space.notifySpaceDeleted", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: `Bearer ${enc({ alg: "ES256K", typ: "JWT" })}.${enc({ - iss: authority, - aud, - lxm: "com.atproto.space.notifySpaceDeleted", - })}.sig`, - }, - body: JSON.stringify({ space: foreignSpace }), - }); + const unknown = await notifyWrite( + `at://${OPERATOR}/space/app.bsky.group/notreal`, + BOB, + bobKeypair, + tidAt(now), + repoData(1), + ); + expect(unknown.status).toBe(404); + expect(await errorOf(unknown)).toBe("SpaceNotFound"); + }); - const readRecord = () => - fApp.request( - `/xrpc/com.atproto.space.getRecord?space=${encodeURIComponent(foreignSpace)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=keepme`, - { headers: { Authorization: "Bearer operator-session" } }, + it("removeWriter and revoking write access drop writers from listRepos", async () => { + const space = await createSpace(); + await putMember(space, BOB); + await putMember(space, CAROL); + const t = Date.now(); + await notifyWrite(space, BOB, bobKeypair, tidAt(t - 2000), repoData(1)); + await notifyWrite(space, CAROL, carolKeypair, tidAt(t - 1000), repoData(2)); + const { credential, key } = await obtainCredential(space, { user: { did: BOB, keypair: bobKeypair } }); + const writers = async () => { + const { res } = await credentialRequest( + `/xrpc/com.atproto.space.listRepos?space=${q(space)}`, + credential, + key, ); - - // A token the authority minted for some other service must not - // tombstone our copy. - const misdirected = await notifyDeleted("did:web:someone-else.test"); - expect(misdirected.status).toBe(403); - expect((await readRecord()).status).toBe(200); - - // Addressed to us (service-identifier form): the copy is dropped. - const addressed = await notifyDeleted(`${OPERATOR}#atproto_pds`); - expect(addressed.status).toBe(200); - expect((await readRecord()).status).toBe(404); + return ((await res.json()) as { repos: Array<{ did: string }> }).repos.map((r) => r.did); + }; + expect((await writers()).sort()).toEqual([BOB, CAROL].sort()); + expect((await post("/xrpc/com.atproto.space.removeWriter", { space, did: CAROL })).status).toBe(200); + expect(await writers()).toEqual([BOB]); + await putMember(space, BOB, true, false); + expect(await writers()).toEqual([]); }); - it("sends one best-effort notifyWrite for writes into foreign spaces (S3)", async () => { - const authority = "did:web:elsewhere.test"; - const foreignSpace = `at://${authority}/space/app.bsky.group/forum1`; - const { host: fHost, outbound } = makeHost(); - const fApp = createSpaceRoutes(fHost); - - const res = await fApp.request("/xrpc/com.atproto.space.createRecord", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: "Bearer operator-session", - }, - body: JSON.stringify({ - space: foreignSpace, - repo: OPERATOR, - collection: "app.bsky.feed.post", - rkey: "foreign1", - record: { $type: "app.bsky.feed.post", text: "posted elsewhere" }, - }), + it("requires notifySpaceDeleted to be addressed to this service", async () => { + const foreign = `at://${BOB}/space/app.bsky.group/deleteme`; + await post("/xrpc/com.atproto.space.createRecord", { + space: foreign, + repo: OPERATOR, + collection: "app.bsky.feed.post", + rkey: "d", + record: { $type: "app.bsky.feed.post", text: "x" }, }); - expect(res.status).toBe(200); - - await vi.waitFor(() => { - const call = outbound.find((o) => - o.url.includes("com.atproto.space.notifyWrite"), + const send = async (aud: string, iss = BOB, keypair = bobKeypair) => + post( + "/xrpc/com.atproto.space.notifySpaceDeleted", + { space: foreign }, + { Authorization: `Bearer ${await serviceJwt(iss, aud, "com.atproto.space.notifySpaceDeleted", keypair)}` }, ); - expect(call).toBeDefined(); - expect(call!.url).toBe( - "https://elsewhere.test/xrpc/com.atproto.space.notifyWrite", - ); - const body = JSON.parse(String(call!.init?.body)) as { - space: string; - repo: string; - rev: string; - hash: { $bytes: string }; - }; - expect(body.space).toBe(foreignSpace); - expect(body.repo).toBe(OPERATOR); - expect(body.hash.$bytes).toBeTruthy(); - }); - - // The foreign space is now registered and readable locally. - const read = await fApp.request( - `/xrpc/com.atproto.space.getRecord?space=${encodeURIComponent(foreignSpace)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=foreign1`, - { headers: { Authorization: "Bearer operator-session" } }, + expect((await send("did:web:someone-else.test")).status).toBe(403); + expect((await send(OPERATOR, CAROL, carolKeypair)).status).toBe(403); + expect((await send(`${OPERATOR}#atproto_space_syncer`)).status).toBe(200); + const read = await get( + `/xrpc/com.atproto.space.getRecord?space=${q(foreign)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=d`, ); - expect(read.status).toBe(200); + expect(await errorOf(read)).toBe("SpaceNotFound"); + }); + + it("delivers writes in foreign spaces to the authority, queueing retryable failures (S3)", async () => { + const foreign = `at://${BOB}/space/app.bsky.group/writer${spaceN++}`; + const stub = env.SPACES.get(env.SPACES.idFromName(foreign)); + const before = outbound.length; + await post("/xrpc/com.atproto.space.createRecord", { + space: foreign, + repo: OPERATOR, + collection: "app.bsky.feed.post", + rkey: "w", + record: { $type: "app.bsky.feed.post", text: "x" }, + }); + await vi.waitFor(() => expect(outbound.length).toBeGreaterThan(before)); + const call = outbound[outbound.length - 1]!; + expect(call.url).toBe("https://bob.test/xrpc/com.atproto.space.notifyWrite"); + const body = JSON.parse(String(call.init!.body)) as Record; + expect(Object.keys(body).sort()).toEqual(["data", "repo", "repoRev", "space"]); + expect(body.repo).toBe(OPERATOR); + expect((await stub.rpcStatus()).queuedNotifications).toBe(0); + + setOutboundResponse((url) => (url.includes("notifyWrite") ? new Response("down", { status: 503 }) : null)); + try { + for (const rkey of ["w2", "w3"]) { + const count = outbound.length; + await post("/xrpc/com.atproto.space.createRecord", { + space: foreign, + repo: OPERATOR, + collection: "app.bsky.feed.post", + rkey, + record: { $type: "app.bsky.feed.post", text: rkey }, + }); + await vi.waitFor(() => expect(outbound.length).toBeGreaterThan(count)); + await vi.waitFor(async () => + expect((await stub.rpcStatus()).queuedNotifications).toBe(1), + ); + } + } finally { + setOutboundResponse(() => null); + } + // Coalesced: one pending retry, for the newest revision. + expect((await stub.rpcStatus()).queuedNotifications).toBe(1); }); }); describe("space routes: blobs (S6)", () => { - it("serves space blobs only with authorisation and no-store headers", async () => { - const space = await createSpace({ - $type: "com.atproto.simplespace.defs#publicPolicy", - }); - const bytes = new Uint8Array([1, 2, 3, 4, 5]); - const cidObj = await createCid(CODEC_RAW, bytes); - const cid = cidToString(cidObj); - // Simulate uploadBlob's staging write. + async function stageBlob(text: string): Promise { + const bytes = new TextEncoder().encode(text); + const cid = cidToString(await createCid(CODEC_RAW, bytes)); await env.BLOBS.put(`${OPERATOR}/staged/${cid}`, bytes, { - httpMetadata: { contentType: "image/png" }, + httpMetadata: { contentType: "text/plain" }, }); + return cid; + } + + const blobRecord = (cid: string) => ({ + $type: "app.bsky.feed.post", + text: "with blob", + embed: { + $type: "blob", + ref: { $link: cid }, + mimeType: "text/plain", + size: 9, + }, + }); - await createRecord( - space, - { - $type: "app.bsky.feed.post", - embed: { - $type: "app.bsky.embed.images", - images: [ - { - image: { - $type: "blob", - ref: { $link: cid }, - mimeType: "image/png", - size: bytes.length, - }, - alt: "", - }, - ], - }, - }, - "withblob", - ); - - const path = `/xrpc/com.atproto.space.getBlob?space=${encodeURIComponent(space)}&repo=${OPERATOR}&cid=${cid}`; - // No auth: refused. - expect((await app.request(path)).status).toBe(401); - - // Session auth streams the blob with credential-safe cache headers. - const res = await app.request(path, { - headers: { Authorization: "Bearer operator-session" }, - }); + it("serves space blobs only with authorisation and no-store headers", async () => { + const space = await createSpace(); + const cid = await stageBlob("blob data"); + await createRecord(space, blobRecord(cid), "b"); + const path = `/xrpc/com.atproto.space.getBlob?space=${q(space)}&repo=${OPERATOR}&cid=${cid}`; + expect((await get(path, {})).status).toBe(401); + const res = await get(path); expect(res.status).toBe(200); - expect(res.headers.get("Cache-Control")).toBe("private, no-store"); - expect(res.headers.get("Vary")).toBe("Authorization, DPoP"); - expect(res.headers.get("Content-Security-Policy")).toBe( - "default-src 'none'; sandbox", - ); - expect(new Uint8Array(await res.arrayBuffer())).toEqual(bytes); - - // An unreferenced CID is BlobNotFound even though it sits in staging. - const otherBytes = new Uint8Array([9, 9, 9]); - const otherCid = cidToString(await createCid(CODEC_RAW, otherBytes)); - await env.BLOBS.put(`${OPERATOR}/staged/${otherCid}`, otherBytes); - const unreferenced = await app.request( - `/xrpc/com.atproto.space.getBlob?space=${encodeURIComponent(space)}&repo=${OPERATOR}&cid=${otherCid}`, - { headers: { Authorization: "Bearer operator-session" } }, - ); - expect(unreferenced.status).toBe(404); - expect(((await unreferenced.json()) as { error: string }).error).toBe( - "BlobNotFound", - ); + expect(res.headers.get("cache-control")).toBe("private, no-store"); + expect(await res.text()).toBe("blob data"); - // listBlobs enumerates the referenced blob. - const list = await app.request( - `/xrpc/com.atproto.space.listBlobs?space=${encodeURIComponent(space)}&repo=${OPERATOR}`, - { headers: { Authorization: "Bearer operator-session" } }, + const unreferenced = await stageBlob("not referenced"); + const missing = await get( + `/xrpc/com.atproto.space.getBlob?space=${q(space)}&repo=${OPERATOR}&cid=${unreferenced}`, ); - expect(((await list.json()) as { cids: string[] }).cids).toContain(cid); + expect(await errorOf(missing)).toBe("BlobNotFound"); }); }); -describe("space routes: lifecycle (S7-ish)", () => { +describe("space routes: lifecycle and management", () => { it("deleteSpace tombstones: reads fail, credentials answer SpaceDeleted", async () => { - const space = await createSpace({ - $type: "com.atproto.simplespace.defs#publicPolicy", + const space = await createSpace({ ...MEMBERSPACE, publicRead: true }); + await createRecord(space, { $type: "app.bsky.feed.post", text: "x" }, "x"); + await putMember(space, BOB); + expect((await post("/xrpc/com.atproto.space.deleteSpace", { space })).status).toBe(200); + expect((await post("/xrpc/com.atproto.space.deleteSpace", { space })).status).toBe(200); + const read = await get( + `/xrpc/com.atproto.space.getRecord?space=${q(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=x`, + ); + expect(await errorOf(read)).toBe("SpaceNotFound"); + const withToken = await obtainCredential(space, { user: { did: BOB, keypair: bobKeypair } }); + expect((withToken.body as { error: string }).error).toBe("SpaceDeleted"); + const anon = await obtainCredential(space); + expect((anon.body as { error: string }).error).toBe("SpaceDeleted"); + }); + + it("updateSpace replaces the policy, and a new $type discards the member list", async () => { + const space = await createSpace(); + await putMember(space, BOB); + const getSpace = async () => + (await (await get(`/xrpc/com.atproto.space.getSpace?space=${q(space)}`)).json()) as { + uri: string; + policy: Record; + }; + expect((await getSpace()).policy).toEqual({ + $type: "com.atproto.memberspace.policy", + publicRead: false, + publicWrite: false, + publishPolicy: false, + publishMembers: false, }); - await createRecord(space, { $type: "app.bsky.feed.post", text: "x" }, "gone"); - const del = await app.request("/xrpc/com.atproto.simplespace.deleteSpace", { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: "Bearer operator-session", - }, - body: JSON.stringify({ space }), + expect( + (await post("/xrpc/com.atproto.space.updateSpace", { + space, + policy: { ...MEMBERSPACE, publicRead: true, extra: "dropped" }, + })).status, + ).toBe(200); + expect((await getSpace()).policy.publicRead).toBe(true); + expect((await getSpace()).policy.extra).toBeUndefined(); + const members = await get(`/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`); + expect(((await members.json()) as { members: unknown[] }).members).toEqual([ + { did: BOB, read: true, write: true }, + ]); + + await post("/xrpc/com.atproto.space.updateSpace", { + space, + policy: { $type: "com.atproto.personalspace.policy" }, }); - expect(del.status).toBe(200); + expect((await getSpace()).policy).toEqual({ $type: "com.atproto.personalspace.policy" }); + const mismatch = await get(`/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`); + expect(await errorOf(mismatch)).toBe("PolicyMismatch"); + await post("/xrpc/com.atproto.space.updateSpace", { space, policy: MEMBERSPACE }); + const after = await get(`/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`); + expect(((await after.json()) as { members: unknown[] }).members).toEqual([]); + }); - const read = await app.request( - `/xrpc/com.atproto.space.getRecord?space=${encodeURIComponent(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=gone`, - { headers: { Authorization: "Bearer operator-session" } }, + it("getSpace is the owner's, by session only", async () => { + const space = await createSpace({ ...MEMBERSPACE, publicRead: true }); + const { credential, key } = await obtainCredential(space); + const { res } = await credentialRequest( + `/xrpc/com.atproto.space.getSpace?space=${q(space)}`, + credential, + key, ); - expect(read.status).toBe(404); - expect(((await read.json()) as { error: string }).error).toBe( - "SpaceNotFound", - ); - - // A late getSpaceCredential gets SpaceDeleted, not SpaceNotFound. - const late = await obtainCredential(space, bobKeypair, BOB); - expect(late.status).toBe(400); - expect((late.body as { error: string }).error).toBe("SpaceDeleted"); + expect(res.status).toBe(401); }); - it("updateSpace changes policy and getSpace reflects it", async () => { + it("manage scopes gate management methods", async () => { const space = await createSpace(); - const update = await app.request( - "/xrpc/com.atproto.simplespace.updateSpace", - { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: "Bearer operator-session", - }, - body: JSON.stringify({ - space, - policy: { $type: "com.atproto.simplespace.defs#publicPolicy" }, - }), - }, + const readOnly = `Bearer scoped:${JSON.stringify({ actions: ["read_self"] })}`; + const update = await post( + "/xrpc/com.atproto.space.updateSpace", + { space, policy: MEMBERSPACE }, + { Authorization: readOnly }, ); - expect(update.status).toBe(200); - const got = await app.request( - `/xrpc/com.atproto.simplespace.getSpace?space=${encodeURIComponent(space)}`, - { headers: { Authorization: "Bearer operator-session" } }, + expect(update.status).toBe(403); + const manager = `Bearer scoped:${JSON.stringify({ manage: ["update"] })}`; + const member = await post( + "/xrpc/com.atproto.memberspace.putMember", + { space, did: BOB, read: true, write: false }, + { Authorization: manager }, ); - expect(got.status).toBe(200); - const body = (await got.json()) as { - policy: { $type: string }; - appAccess: { $type: string }; + expect(member.status).toBe(200); + const del = await post("/xrpc/com.atproto.space.deleteSpace", { space }, { Authorization: manager }); + expect(del.status).toBe(403); + }); + + it("refuses unsupported policies and memberspace methods elsewhere", async () => { + const res = await post("/xrpc/com.atproto.space.createSpace", { + spaceType: "app.bsky.group", + policy: { $type: "com.example.custom.policy" }, + }); + expect(res.status).toBe(400); + expect(await errorOf(res)).toBe("UnsupportedPolicy"); + + const managed = await createSpace({ + $type: "com.atproto.managedspace.policy", + managingApp: "did:web:manager.test", + }); + const put = await post("/xrpc/com.atproto.memberspace.putMember", { + space: managed, + did: BOB, + read: true, + write: true, + }); + expect(await errorOf(put)).toBe("PolicyMismatch"); + + const notOwner = await post("/xrpc/com.atproto.space.updateSpace", { + space: `at://${BOB}/space/app.bsky.group/x`, + policy: MEMBERSPACE, + }); + expect(notOwner.status).toBe(404); + }); + + it("publishes the policy and member list into the authority's repo", async () => { + const space = await createSpace({ ...MEMBERSPACE, publishPolicy: true, publishMembers: true }); + await putMember(space, BOB, true, false); + await putMember(space, CAROL); + const list = async () => { + const res = await get( + `/xrpc/com.atproto.space.listRecords?space=${q(space)}&repo=${OPERATOR}&reverse=true`, + ); + return ((await res.json()) as { + records: Array<{ collection: string; rkey: string; value: Record }>; + }).records; }; - expect(body.policy.$type).toBe( - "com.atproto.simplespace.defs#publicPolicy", - ); - expect(body.appAccess.$type).toBe("com.atproto.simplespace.defs#open"); + let records = await list(); + expect(records.map((r) => `${r.collection}/${r.rkey}`)).toEqual([ + `com.atproto.memberspace.member/${BOB}`, + `com.atproto.memberspace.member/${CAROL}`, + "com.atproto.space.policy/self", + ]); + expect(records[0]!.value).toEqual({ + $type: "com.atproto.memberspace.member", + read: true, + write: false, + }); + expect((records[2]!.value.policy as { publishMembers: boolean }).publishMembers).toBe(true); + + await post("/xrpc/com.atproto.memberspace.removeMember", { space, did: CAROL }); + await post("/xrpc/com.atproto.space.updateSpace", { + space, + policy: { ...MEMBERSPACE, publishPolicy: true }, + }); + records = await list(); + expect(records.map((r) => r.collection)).toEqual(["com.atproto.space.policy"]); }); - it("manage scopes gate simplespace methods", async () => { - const manageNone = `Bearer scoped:${JSON.stringify({ actions: ["read_self"] })}`; - const refused = await app.request( - "/xrpc/com.atproto.simplespace.createSpace", - { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: manageNone, - }, - body: JSON.stringify({ - type: "app.bsky.group", - skey: "denied1", - policy: { $type: "com.atproto.simplespace.defs#publicPolicy" }, - appAccess: { $type: "com.atproto.simplespace.defs#open" }, - }), - }, - ); - expect(refused.status).toBe(403); + it("round-trips a space through exportSpaceMeta/getRepo and their imports", async () => { + const space = await createSpace({ ...MEMBERSPACE, publishPolicy: true }); + await putMember(space, BOB, true, false); + await putMember(space, CAROL); + await notifyWrite(space, CAROL, carolKeypair, tidAt(Date.now() - 1000), repoData(7)); + await createRecord(space, { $type: "app.bsky.feed.post", text: "keep me" }, "k"); - const manageCreate = `Bearer scoped:${JSON.stringify({ manage: ["create"] })}`; - const allowed = await app.request( - "/xrpc/com.atproto.simplespace.createSpace", - { - method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: manageCreate, - }, - body: JSON.stringify({ - type: "app.bsky.group", - skey: "allowed1", - policy: { $type: "com.atproto.simplespace.defs#publicPolicy" }, - appAccess: { $type: "com.atproto.simplespace.defs#open" }, - }), - }, + const meta = await get(`/xrpc/com.atproto.space.exportSpaceMeta?space=${q(space)}`); + expect(meta.status).toBe(200); + const metaBytes = new Uint8Array(await meta.arrayBuffer()); + const repo = await get(`/xrpc/com.atproto.space.getRepo?space=${q(space)}&repo=${OPERATOR}`); + const repoBytes = new Uint8Array(await repo.arrayBuffer()); + + await post("/xrpc/com.atproto.space.deleteSpace", { space }); + + // The authority's repo can't arrive before its space. + const early = await app.request("/xrpc/com.atproto.space.importRepo", { + method: "POST", + headers: { ...SESSION, "Content-Type": "application/octet-stream" }, + body: repoBytes, + }); + expect(await errorOf(early)).toBe("SpaceNotFound"); + + const importMeta = await app.request("/xrpc/com.atproto.space.importSpaceMeta", { + method: "POST", + headers: { ...SESSION, "Content-Type": "application/octet-stream" }, + body: metaBytes, + }); + expect(importMeta.status).toBe(200); + const importRepo = await app.request("/xrpc/com.atproto.space.importRepo", { + method: "POST", + headers: { ...SESSION, "Content-Type": "application/octet-stream" }, + body: repoBytes, + }); + expect(importRepo.status).toBe(200); + + const members = await get(`/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`); + expect(((await members.json()) as { members: unknown[] }).members).toEqual([ + { did: BOB, read: true, write: false }, + { did: CAROL, read: true, write: true }, + ]); + const record = await get( + `/xrpc/com.atproto.space.getRecord?space=${q(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=k`, + ); + expect(((await record.json()) as { value: { text: string } }).value.text).toBe("keep me"); + const { credential, key } = await obtainCredential(space, { user: { did: CAROL, keypair: carolKeypair } }); + const { res } = await credentialRequest( + `/xrpc/com.atproto.space.listRepos?space=${q(space)}`, + credential, + key, ); - expect(allowed.status).toBe(200); + const writers = ((await res.json()) as { repos: Array<{ did: string }> }).repos.map((r) => r.did); + expect(writers).toContain(CAROL); }); - it("rejects unsupported policy and appAccess variants", async () => { - const res = await app.request( - "/xrpc/com.atproto.simplespace.createSpace", - { + it("importRepo refuses another account's archive and non-canonical records", async () => { + const space = `at://${BOB}/space/app.bsky.group/imp${spaceN++}`; + const record = { $type: "app.bsky.feed.post", text: "x" }; + const bytes = encode(record); + const { cidForCbor } = await import("@atproto/lex-data"); + const cid = await cidForCbor(bytes); + const data = new LtHash().add(`app.bsky.feed.post/r/${cid.toString()}`).digest(); + const archive = async (repo: string) => { + const chunks: Uint8Array[] = []; + for await (const chunk of serializeRepo( + { ver: 1, repo: repo as never, space: space as never, rev: tidAt(Date.now()), data }, + [{ collection: "app.bsky.feed.post" as never, rkey: "r" as never, bytes }], + )) { + chunks.push(chunk); + } + return new Uint8Array(await new Blob(chunks).arrayBuffer()); + }; + const send = async (body: Uint8Array) => + app.request("/xrpc/com.atproto.space.importRepo", { method: "POST", - headers: { - "Content-Type": "application/json", - Authorization: "Bearer operator-session", - }, - body: JSON.stringify({ - type: "app.bsky.group", - skey: "badpolicy", - policy: { $type: "com.example.mysteryPolicy" }, - appAccess: { $type: "com.atproto.simplespace.defs#open" }, - }), - }, - ); - expect(res.status).toBe(400); - expect(((await res.json()) as { error: string }).error).toBe( - "UnsupportedPolicy", - ); + headers: { ...SESSION, "Content-Type": "application/octet-stream" }, + body, + }); + const theirs = await send(await archive(BOB)); + expect(theirs.status).toBe(400); + const ours = await archive(OPERATOR); + // Sanity: the archive is readable before import. + const read = await readRepoStar([ours]); + await read[Symbol.asyncDispose](); + expect((await send(ours)).status).toBe(200); }); }); diff --git a/packages/spaces/test/space-do.test.ts b/packages/spaces/test/space-do.test.ts index e99a1fa..4877075 100644 --- a/packages/spaces/test/space-do.test.ts +++ b/packages/spaces/test/space-do.test.ts @@ -1,15 +1,31 @@ import { env, runInDurableObject } from "cloudflare:test"; import { describe, expect, it } from "vitest"; -import { LtHash, RepoCommit, verifyCommit } from "@atproto/space"; -import { Secp256k1Keypair } from "@atproto/crypto"; +import { + COMMIT_MAC_TYPE, + LtHash, + RepoCommit, + computeCommitMac, + encapsulate, + verifyCommit, +} from "@atproto/space"; +import { P256Keypair } from "@atproto/crypto"; import { encode } from "@atproto/lex-cbor"; -import type { PreparedSpaceWrite } from "../src/types"; +import { buildCommit, macSecret } from "../src/mac"; +import type { PreparedSpaceWrite, SpacePolicy } from "../src/types"; import { + TEST_KEM_KEY, TEST_OPERATOR_DID, - TEST_SIGNING_KEY, type TestSpaceDurableObject, } from "./fixtures/spaces-worker/index"; +const MEMBERSPACE: SpacePolicy = { + $type: "com.atproto.memberspace.policy", + publicRead: false, + publicWrite: false, + publishPolicy: false, + publishMembers: false, +}; + const AUTHORITY = TEST_OPERATOR_DID; /** @@ -54,14 +70,7 @@ async function initSpace( type: "app.bsky.group", skey: uri.split("/").pop()!, isAuthority, - ...(isAuthority - ? { - config: { - policy: { kind: "member-list" as const }, - appAccess: { kind: "open" as const }, - }, - } - : {}), + ...(isAuthority ? { policy: MEMBERSPACE } : {}), }); } @@ -113,7 +122,7 @@ describe("SpaceDurableObject", () => { const expected = new LtHash(); expected.add(`app.bsky.feed.post/aaa/${w1.cid}`); expected.add(`app.bsky.feed.post/bbb/${w2.cid}`); - expect(new Uint8Array(r1.hash)).toEqual(expected.digest()); + expect(new Uint8Array(r1.data)).toEqual(expected.digest()); // Update aaa and delete bbb. const w3 = write("update", "aaa", { $type: "app.bsky.feed.post", n: 3 }); @@ -126,7 +135,7 @@ describe("SpaceDurableObject", () => { expected.remove(`app.bsky.feed.post/aaa/${w1.cid}`); expected.add(`app.bsky.feed.post/aaa/${w3.cid}`); expected.remove(`app.bsky.feed.post/bbb/${w2.cid}`); - expect(new Uint8Array(r2.hash)).toEqual(expected.digest()); + expect(new Uint8Array(r2.data)).toEqual(expected.digest()); // The persisted state round-trips through RepoCommit and matches. const state = await stub.rpcGetRepoState(); @@ -135,19 +144,46 @@ describe("SpaceDurableObject", () => { expect(commit.setHash.digest()).toEqual(expected.digest()); }); - it("signs verifiable commits from persisted state", async () => { + it("builds commits from persisted state whose MAC verifies", async () => { const { uri, stub } = freshSpace(); await initSpace(stub, uri); - const w = write("create", "sig", { $type: "app.bsky.feed.post", n: 9 }); + const w = write("create", "mac", { $type: "app.bsky.feed.post", n: 9 }); await stub.rpcApplyWrites([w]); const state = await stub.rpcGetRepoState(); - const keypair = await Secp256k1Keypair.import(TEST_SIGNING_KEY); - const ctx = { space: uri, author: AUTHORITY, rev: state!.rev }; - const signed = await RepoCommit.fromState( - new Uint8Array(state!.setHash), - ).sign(ctx, keypair); - expect(await verifyCommit(signed, ctx, keypair.did())).toBe(true); + const commit = buildCommit({ spaceUri: uri, repo: AUTHORITY, state: state! }); + const kemDid = (await P256Keypair.import(TEST_KEM_KEY)).did(); + const { keyShare, sharedSecret } = await encapsulate(kemDid); + const { formatWantMacHeader } = await import("@atproto/space"); + const hostSecret = await macSecret({ + wantMac: formatWantMacHeader(COMMIT_MAC_TYPE, keyShare), + credential: true, + type: COMMIT_MAC_TYPE, + getKemKeypair: () => P256Keypair.import(TEST_KEM_KEY), + }); + const mac = computeCommitMac(hostSecret!, commit as never); + expect( + verifyCommit(commit as never, { space: uri, repo: AUTHORITY, sharedSecret, mac }), + ).toBe(true); + }); + + it("orders records by path bytes for archives", async () => { + const { uri, stub } = freshSpace(); + await initSpace(stub, uri); + await stub.rpcApplyWrites([ + { ...write("create", "z", { n: 1 }), collection: "app.bsky.feed" }, + { ...write("create", "a", { n: 2 }), collection: "app.bsky.feed.post" }, + ]); + const page = await stub.rpcListRecordsByPath({ limit: 1 }); + // "app.bsky.feed.post/a" < "app.bsky.feed/z" byte-wise ('.' < '/'). + expect(page.records.map((r) => r.collection)).toEqual(["app.bsky.feed.post"]); + expect(page.hasMore).toBe(true); + const next = await stub.rpcListRecordsByPath({ + afterPath: "app.bsky.feed.post/a", + limit: 10, + }); + expect(next.records.map((r) => r.collection)).toEqual(["app.bsky.feed"]); + expect(next.state?.rev).toBe(page.state?.rev); }); it("rejects duplicate creates and missing updates/deletes", async () => { @@ -298,68 +334,68 @@ describe("SpaceDurableObject", () => { expect(await stub.rpcCheckReplay("delegation", "jti-1", exp)).toBe(true); }); - it("manages members, writers and notify registrations", async () => { + it("manages members with read and write access", async () => { const { uri, stub } = freshSpace(); await initSpace(stub, uri); - await stub.rpcAddMember("did:web:bob.test"); - await stub.rpcAddMember("did:web:carol.test"); - expect(await stub.rpcIsMember("did:web:bob.test")).toBe(true); - const members = await stub.rpcListMembers({ limit: 10 }); - expect(members.dids).toEqual(["did:web:bob.test", "did:web:carol.test"]); - await stub.rpcRemoveMember("did:web:bob.test"); - expect(await stub.rpcIsMember("did:web:bob.test")).toBe(false); - - const hash = new Uint8Array(32).fill(7); - const first = await stub.rpcRecordWriter( - "did:web:bob.test", - "3kzzzzzzzzzzz", - hash, - ); - expect(first.advanced).toBe(true); - const writers = await stub.rpcListWriters({ limit: 10 }); - expect(writers.repos).toHaveLength(1); - expect(writers.repos[0]).toMatchObject({ + await stub.rpcPutMember("did:web:bob.test", { read: true, write: false }); + await stub.rpcPutMember("did:web:carol.test", { read: true, write: true }); + expect(await stub.rpcGetMember("did:web:bob.test")).toEqual({ did: "did:web:bob.test", - rev: "3kzzzzzzzzzzz", + read: true, + write: false, }); - expect(new Uint8Array(writers.repos[0]!.hash)).toEqual(hash); - - // A delayed or replayed notification with an older rev never rolls - // the writer set backwards, and reports that nothing advanced. - const staleHash = new Uint8Array(32).fill(9); - const stale = await stub.rpcRecordWriter( - "did:web:bob.test", - "3kaaaaaaaaaaa", - staleHash, - ); - expect(stale.advanced).toBe(false); - const equal = await stub.rpcRecordWriter( - "did:web:bob.test", - "3kzzzzzzzzzzz", - staleHash, - ); - expect(equal.advanced).toBe(false); - const unchanged = await stub.rpcListWriters({ limit: 10 }); - expect(unchanged.repos[0]).toMatchObject({ rev: "3kzzzzzzzzzzz" }); - expect(new Uint8Array(unchanged.repos[0]!.hash)).toEqual(hash); - - // A newer rev advances again. - const newer = await stub.rpcRecordWriter( - "did:web:bob.test", - "3lzzzzzzzzzzz", - staleHash, - ); - expect(newer.advanced).toBe(true); - const advancedState = await stub.rpcListWriters({ limit: 10 }); - expect(advancedState.repos[0]).toMatchObject({ rev: "3lzzzzzzzzzzz" }); + const members = await stub.rpcListMembers({ limit: 1 }); + expect(members.members.map((m) => m.did)).toEqual(["did:web:bob.test"]); + expect(members.hasMore).toBe(true); + await stub.rpcRemoveMember("did:web:bob.test"); + expect(await stub.rpcGetMember("did:web:bob.test")).toBe(null); + }); - const reg = await stub.rpcRegisterNotify( - "did:web:syncer.test", - "https://syncer.test", - ); + it("sequences writers by space revision, monotonic per writer", async () => { + const { uri, stub } = freshSpace(); + await initSpace(stub, uri); + const data = new Uint8Array(32).fill(7); + const first = await stub.rpcRecordWriter("did:web:bob.test", "3kzzzzzzzzzzz", data); + expect(first?.spaceRev).toMatch(/^[2-7a-z]{13}$/); + expect(first?.prevSpaceRev).toBeUndefined(); + const second = await stub.rpcRecordWriter("did:web:carol.test", "3kzzzzzzzzzzz", data); + expect(second?.prevSpaceRev).toBe(first?.spaceRev); + expect(second!.spaceRev > first!.spaceRev).toBe(true); + + // A delayed or replayed notification with an older or equal rev never + // rolls the writer set backwards, and reports that nothing advanced. + expect(await stub.rpcRecordWriter("did:web:bob.test", "3kaaaaaaaaaaa", data)).toBe(null); + expect(await stub.rpcRecordWriter("did:web:bob.test", "3kzzzzzzzzzzz", data)).toBe(null); + + // Bob advances again and moves to the end of the sequence. + const third = await stub.rpcRecordWriter("did:web:bob.test", "3lzzzzzzzzzzz", data); + expect(third?.prevSpaceRev).toBe(second?.spaceRev); + const all = await stub.rpcListWriters({ limit: 10 }); + expect(all.map((w) => w.did)).toEqual(["did:web:carol.test", "did:web:bob.test"]); + expect(all[1]).toMatchObject({ repoRev: "3lzzzzzzzzzzz", spaceRev: third!.spaceRev }); + const after = await stub.rpcListWriters({ limit: 10, cursor: all[0]!.spaceRev }); + expect(after.map((w) => w.did)).toEqual(["did:web:bob.test"]); + + await stub.rpcRemoveWriter("did:web:bob.test"); + expect((await stub.rpcListWriters({ limit: 10 })).map((w) => w.did)).toEqual([ + "did:web:carol.test", + ]); + // Revoking write access drops a member from the writer set. + await stub.rpcPutMember("did:web:carol.test", { read: true, write: false }); + expect(await stub.rpcListWriters({ limit: 10 })).toEqual([]); + }); + + it("registers and unregisters notification services", async () => { + const { uri, stub } = freshSpace(); + await initSpace(stub, uri); + const reg = await stub.rpcRegisterNotify("did:web:syncer.test", "https://syncer.test"); expect(Date.parse(reg.expiresAt)).toBeGreaterThan(Date.now()); expect(await stub.rpcGetActiveRegistrations()).toEqual([ - { service: "did:web:syncer.test", endpoint: "https://syncer.test" }, + { + service: "did:web:syncer.test", + endpoint: "https://syncer.test", + expiresAt: reg.expiresAt, + }, ]); await stub.rpcUnregisterNotify("did:web:syncer.test"); expect(await stub.rpcGetActiveRegistrations()).toEqual([]); @@ -367,32 +403,92 @@ describe("SpaceDurableObject", () => { await stub.rpcUnregisterNotify("did:web:syncer.test"); }); - it("updates and reads simplespace config", async () => { + it("replaces the policy, discarding members when its $type changes", async () => { const { uri, stub } = freshSpace(); await initSpace(stub, uri); - const s1 = await stub.rpcGetAuthorityState(); - expect(s1.config).toEqual({ - policy: { kind: "member-list" }, - appAccess: { kind: "open" }, - }); - await stub.rpcUpdateConfig({ - policy: { kind: "managing-app", managingApp: "did:web:app.test#svc" }, - }); - const s2 = await stub.rpcGetAuthorityState(); - expect(s2.config?.policy).toEqual({ - kind: "managing-app", + await stub.rpcPutMember("did:web:bob.test", { read: true, write: true }); + expect(await stub.rpcUpdatePolicy({ ...MEMBERSPACE, publicRead: true })).toBe(null); + expect((await stub.rpcGetAuthorityState()).policy).toMatchObject({ publicRead: true }); + expect(await stub.rpcGetMember("did:web:bob.test")).not.toBe(null); + await stub.rpcUpdatePolicy({ + $type: "com.atproto.managedspace.policy", managingApp: "did:web:app.test#svc", + publishPolicy: false, }); - // appAccess untouched by partial update. - expect(s2.config?.appAccess).toEqual({ kind: "open" }); - await stub.rpcUpdateConfig({ - appAccess: { kind: "allowList", allowed: ["https://app.test/client"] }, - }); - const s3 = await stub.rpcGetAuthorityState(); - expect(s3.config?.appAccess).toEqual({ - kind: "allowList", - allowed: ["https://app.test/client"], + expect(await rpcError(stub, (i) => i.rpcGetMember("did:web:bob.test"))).toBe(""); + expect(await stub.rpcGetMember("did:web:bob.test")).toBe(null); + expect(await rpcError(stub, (i) => i.rpcListMembers({ limit: 1 }))).toMatch( + /PolicyMismatch/, + ); + }); + + it("publishes the policy record on creation and withdraws it", async () => { + const { uri, stub } = freshSpace(); + const commit = await stub.rpcInit({ + uri, + authority: AUTHORITY, + type: "app.bsky.group", + skey: uri.split("/").pop()!, + isAuthority: true, + policy: { ...MEMBERSPACE, publishPolicy: true }, }); + expect(commit?.rev).toMatch(/^[2-7a-z]{13}$/); + expect(await stub.rpcGetRecord("com.atproto.space.policy", "self")).not.toBe(null); + const withdrawn = await stub.rpcUpdatePolicy(MEMBERSPACE); + expect(withdrawn?.rev && withdrawn.rev > commit!.rev).toBe(true); + expect(await stub.rpcGetRecord("com.atproto.space.policy", "self")).toBe(null); + }); + + it("clears records, keeping the given collections", async () => { + const { uri, stub } = freshSpace(); + await initSpace(stub, uri); + await stub.rpcApplyWrites([ + write("create", "a", { n: 1 }), + { ...write("create", "self", { n: 2 }), collection: "com.atproto.space.policy" }, + ]); + const cleared = await stub.rpcClearRecords(["com.atproto.space.policy"]); + const remaining = await stub.rpcListRecords({ limit: 10 }); + expect(remaining.records.map((r) => r.collection)).toEqual(["com.atproto.space.policy"]); + const expected = new LtHash().add( + `com.atproto.space.policy/self/${remaining.records[0]!.cid}`, + ); + expect(new Uint8Array(cleared!.data)).toEqual(expected.digest()); + expect((await stub.rpcListRepoOps({ limit: 10 })).ops).toEqual([]); + // Nothing left to delete: a no-op. + expect(await stub.rpcClearRecords(["com.atproto.space.policy"])).toBe(null); + }); + + it("imports a repo wholesale at a new rev", async () => { + const { uri, stub } = freshSpace(); + await initSpace(stub, uri); + const before = await stub.rpcApplyWrites([write("create", "old", { n: 1 })]); + const imported = write("create", "new", { n: 2 }, ["bafkblob"]); + const result = await stub.rpcImportRepo([ + { + collection: imported.collection, + rkey: imported.rkey, + cid: imported.cid, + bytes: imported.bytes, + blobCids: imported.blobCids, + }, + ]); + expect(result.rev > before.rev).toBe(true); + expect(await stub.rpcGetRecord("app.bsky.feed.post", "old")).toBe(null); + expect(await stub.rpcHasSpaceBlob("bafkblob")).toBe(true); + expect((await stub.rpcListRepoOps({ limit: 10 })).ops).toEqual([]); + expect(new Uint8Array(result.data)).toEqual( + new LtHash().add(`app.bsky.feed.post/new/${imported.cid}`).digest(), + ); + }); + + it("records revoked credentials until they expire", async () => { + const { stub } = freshSpace(); + const now = Math.floor(Date.now() / 1000); + await stub.rpcRevokeCredentials(["live", "lapsed"], now + 60); + expect(await stub.rpcIsCredentialRevoked("live")).toBe(true); + expect(await stub.rpcIsCredentialRevoked("other")).toBe(false); + await stub.rpcRevokeCredentials(["lapsed"], now - 1); + expect(await stub.rpcIsCredentialRevoked("lapsed")).toBe(false); }); it("createSpace conflicts on a live space and revives a deleted one", async () => { @@ -406,30 +502,24 @@ describe("SpaceDurableObject", () => { type: "app.bsky.group", skey: uri.split("/").pop()!, isAuthority: true, - config: { - policy: { kind: "member-list" }, - appAccess: { kind: "open" }, - }, + policy: MEMBERSPACE, }), ), ).toMatch(/SpaceAlreadyExists/); - await stub.rpcApplyWrites([ - write("create", "gone", { $type: "app.bsky.feed.post" }), - ]); + await stub.rpcApplyWrites([write("create", "gone", { $type: "app.bsky.feed.post" })]); const del = await stub.rpcDeleteSpace(); expect(del.registrations).toEqual([]); // Tombstone: reads fail SpaceNotFound, authority state shows deleted. - expect( - await rpcError(stub, (i) => i.rpcGetRecord("app.bsky.feed.post", "gone")), - ).toMatch(/SpaceNotFound/); + expect(await rpcError(stub, (i) => i.rpcGetRecord("app.bsky.feed.post", "gone"))).toMatch( + /SpaceNotFound/, + ); const state = await stub.rpcGetAuthorityState(); expect(state.meta?.deletedAt).not.toBe(null); - expect(state.config).toBe(null); + expect(state.policy).toBe(null); // Idempotent delete. - const again = await stub.rpcDeleteSpace(); - expect(again.registrations).toEqual([]); + expect((await stub.rpcDeleteSpace()).registrations).toEqual([]); // Re-creation revives with a clean slate. await initSpace(stub, uri); @@ -519,4 +609,44 @@ describe("SpaceDurableObject", () => { const status = await stub.rpcStatus(); expect(status.queuedNotifications).toBe(0); }); + + it("coalesces keyed notifications and stops on deadlines and permanent refusals", async () => { + const { uri, stub } = freshSpace(); + await initSpace(stub, uri); + const statuses: number[] = []; + await runInDurableObject(stub, async (instance) => { + let next = 503; + (globalThis as { fetch: typeof fetch }).fetch = (async () => { + statuses.push(next); + return new Response("{}", { status: next }); + }) as typeof fetch; + const item = (rev: string) => ({ + service: "did:web:authority.test", + endpoint: "https://authority.test", + lxm: "com.atproto.space.notifyWrite", + body: { repoRev: rev }, + coalesceKey: "notifyWrite:authority", + deadline: Date.now() + 60_000, + }); + await instance.rpcEnqueueNotify([item("1")]); + await instance.rpcEnqueueNotify([item("2")]); + expect((await instance.rpcStatus()).queuedNotifications).toBe(1); + + // Retryable: kept, with backoff. + await instance.alarm(); + expect((await instance.rpcStatus()).queuedNotifications).toBe(1); + + // A permanent refusal is not retried. + next = 400; + await instance.rpcEnqueueNotify([item("3")]); + await instance.alarm(); + expect((await instance.rpcStatus()).queuedNotifications).toBe(0); + + // A passed deadline drops the item undelivered. + await instance.rpcEnqueueNotify([{ ...item("4"), deadline: Date.now() - 1 }]); + await instance.alarm(); + expect((await instance.rpcStatus()).queuedNotifications).toBe(0); + }); + expect(statuses).toEqual([503, 400]); + }); }); diff --git a/packages/spaces/tsconfig.json b/packages/spaces/tsconfig.json index f1773d6..0b0dadd 100644 --- a/packages/spaces/tsconfig.json +++ b/packages/spaces/tsconfig.json @@ -2,7 +2,15 @@ "extends": "../../tsconfig.json", "compilerOptions": { "moduleResolution": "bundler", - "types": ["@cloudflare/workers-types"] + "types": [ + "@cloudflare/workers-types" + ], + "lib": [ + "ES2022", + "ESNext.Disposable" + ] }, - "include": ["src"] + "include": [ + "src" + ] } diff --git a/packages/spaces/tsdown.config.ts b/packages/spaces/tsdown.config.ts index b7eba59..b2e16e4 100644 --- a/packages/spaces/tsdown.config.ts +++ b/packages/spaces/tsdown.config.ts @@ -6,6 +6,11 @@ export default defineConfig([ format: ["esm"], fixedExtension: false, dts: true, + // A Workers library. The alpha @atproto packages are devDependencies, + // so they are bundled (consumers must never resolve their broken + // prerelease ranges); resolve their browser builds rather than the + // Node ones, which reach for node:crypto and node:buffer. + platform: "browser", external: [/^cloudflare:/], }, ]); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index e8a14f0..c284438 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -305,6 +305,9 @@ importers: '@atproto/api': specifier: ^0.18.9 version: 0.18.20 + '@atproto/space': + specifier: 0.0.0-spaces-alpha-20261105160032 + version: 0.0.0-spaces-alpha-20261105160032 '@cloudflare/vite-plugin': specifier: ^1.17.0 version: 1.23.1(vite@6.4.1(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0))(workerd@1.20260521.1)(wrangler@4.94.0(@cloudflare/workers-types@4.20260524.1)) From 9b64ce041899b93adb364dbae6a47e9e6f75a4f2 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 08:52:06 +0000 Subject: [PATCH 03/16] docs(spaces): document the 2026-11-05 alpha, the KEM key and the sync process Updates the spaces concepts and enable guides for credentials signed with HTTP message signatures, MAC-authenticated space data and the #atproto_kem key, the baseline policies and migration, with upgrade steps from the August alpha. Records the alpha sync process in the spaces plan, where it can be found next time. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LZ7qcQNQoiA6a23woGC7tB --- .changeset/spaces-alpha-20261105.md | 18 +++ docs/src/content/docs/concepts/spaces.md | 26 +++-- docs/src/content/docs/guides/enable-spaces.md | 41 +++++-- docs/src/content/docs/operate/secrets.md | 2 + plans/in-progress/spaces-spec.md | 2 + plans/in-progress/spaces.md | 106 +++++++++++++++++- 6 files changed, 173 insertions(+), 22 deletions(-) create mode 100644 .changeset/spaces-alpha-20261105.md diff --git a/.changeset/spaces-alpha-20261105.md b/.changeset/spaces-alpha-20261105.md new file mode 100644 index 0000000..13bc3a5 --- /dev/null +++ b/.changeset/spaces-alpha-20261105.md @@ -0,0 +1,18 @@ +--- +"@getcirrus/pds": minor +"@getcirrus/spaces": minor +"@getcirrus/oauth-provider": patch +"create-pds": patch +--- + +Update atproto spaces to the 2026-11-05 alpha (`0.0.0-spaces-alpha-20261105160032`). This is a breaking alpha change: existing space data refuses to open until you run `pds spaces reset`, and apps built against the earlier alpha need updating. + +- Space credentials are bound to a P-256 key and presented with the `Atproto-Space-Credential` scheme and an HTTP message signature, replacing DPoP. `getSpaceCredential` takes the key, delegation token and client attestation in its body, and public-read spaces issue credentials without a delegation token. +- Commits are no longer signed. Syncers verify space data with a MAC derived against a new `#atproto_kem` key. Run `pds spaces kem` to create it; on did:plc, `pds spaces kem --publish` adds it to your DID document. `pds spaces status` checks that it is published. +- `com.atproto.simplespace` is replaced by the personalspace, memberspace and managedspace policies, managed with `com.atproto.space.{create,update,delete,get}Space` and `com.atproto.memberspace.*`. Members can be given read or write access separately, and a space can publish its policy and member list to readers. +- `getRepo` serves a STAR archive, streamed rather than buffered. +- Writes are sequenced by space revision, and notifications to a space hosted elsewhere are retried for up to 24 hours. +- New: `clearRecords`, `removeWriter`, `importRepo`, `exportSpaceMeta` and `importSpaceMeta`. `pds spaces export` writes STAR archives that the new import endpoints accept. +- The DID document no longer has an `#atproto_space_host` service entry. + +`@getcirrus/spaces` now bundles `@atproto/space` and its alpha dependencies, several of which have broken releases that package managers would otherwise install in their place. diff --git a/docs/src/content/docs/concepts/spaces.md b/docs/src/content/docs/concepts/spaces.md index cb94211..c5c3a51 100644 --- a/docs/src/content/docs/concepts/spaces.md +++ b/docs/src/content/docs/concepts/spaces.md @@ -31,20 +31,26 @@ Because Cirrus is single-user, one account wears three hats: Reading a space requires a **space credential** from its authority. The flow: -1. Your app asks your PDS for a **delegation token** — a 60-second, single-use JWT proving the app acts for you. -2. The app exchanges it at the space's authority for a **credential** — a two-hour, DPoP-bound JWT. -3. Every read presents the credential plus a fresh DPoP proof. +1. Your app asks your PDS for a **delegation token**: a 60-second, single-use JWT proving the app acts for you. +2. The app generates a P-256 key and asks the space's authority for a **credential** bound to it: a ten-minute JWT. A space that is publicly readable issues one without a delegation token. +3. Every read presents the credential with an HTTP message signature by that key, naming the service it is addressed to. A stolen credential is useless without the key, and a signed request for one host can't be replayed at another. -Whether the authority grants a credential is its policy. Cirrus implements the `simplespace` policies: +Whether the authority grants a credential is up to the space's **policy**. Cirrus implements the three baseline policies every PDS supports: -- **public** — anyone with an account may read. -- **member-list** — only DIDs on the space's member list (managed from the CLI or dashboard). -- **managing-app** — a nominated app service is asked to decide, per request. +- **personalspace**: only you. For bookmarks, drafts, mutes. +- **memberspace**: a member list you manage, where each member can be allowed to read, to write, or both. It can be opened to everyone for reading (`publicRead`) or writing (`publicWrite`), and restricted to named apps (`allowedApps`, checked against client attestations). +- **managedspace**: a nominated app service is asked to decide, per user, per request. -Spaces can additionally gate on *which app* is asking, via an allow-list of OAuth client IDs backed by client attestations. +Someone the policy refuses is told the space doesn't exist, so a refusal reveals nothing about it. A memberspace or managedspace can also publish its policy, and a memberspace its member list, as records in your own repo in the space, so readers can see who else is in it. Writes never use credentials: they're ordinary authenticated requests to your own PDS, covered by OAuth `space:` grants or your own full-access session. App passwords are deliberately excluded. +## Proving data came from you + +Space data isn't signed. Instead, your PDS has a second key, published in your DID document as `#atproto_kem`. A syncer reading your repo sends an ephemeral key with each request, both sides derive a one-off shared secret, and your PDS returns a MAC over the commit or record in an `Atproto-Space-Mac` header. The syncer knows the data is yours; but because the syncer could have computed the same MAC itself, a leaked response proves nothing to anyone else. That's the point: private data shouldn't come with a signature that lets it be passed around as authentic. + +Cirrus can't serve space data to syncers without this key. `pds spaces kem` creates it; see [Enable spaces](/guides/enable-spaces/). + ## Blobs A blob referenced only from a space record is fetchable only through the credential-gated `com.atproto.space.getBlob` — never from the public `sync.getBlob`, even by someone who knows its CID. To enforce this cheaply, uploads are staged (`/staged/` in R2) until a record references them, then copied to a public or per-space key. This staging applies to the public path too, flag or no flag: it closes the gap where any uploaded blob was public the moment it was uploaded. @@ -64,6 +70,6 @@ which deletes all space data — and *can only* delete space data. There is no m ## Alpha caveats - **Interop is the point, stability is not.** Cirrus targets the reference alpha PDS and apps like bulletin.my. Expect breaking changes; expect `pds spaces reset` to be part of upgrading. -- **No migration of space data.** The protocol has no import yet. `pds spaces export` writes one CAR per space so data isn't lost, but it can't yet be imported anywhere. +- **Migration is new.** The protocol can now move space data between hosts: `pds spaces export` writes each space repo as a STAR archive (and, for spaces you own, the space's policy, members and writers as a space meta archive), which `com.atproto.space.importSpaceMeta` and `importRepo` accept on the new host. Notification registrations, revoked credentials and deleted-space tombstones don't move. Nothing migrates *between alpha builds*: that's still `pds spaces reset`. - **Access control, not encryption.** Space data is not encrypted at rest beyond what R2 and Durable Object storage already do. Your PDS (and any space host) can read what it stores. -- **Pinned dependencies.** The `@atproto/space` and `@atproto/oauth-scopes` alpha builds are pinned exactly and excluded from automatic updates. +- **Pinned dependencies.** The `@atproto/space` and `@atproto/oauth-scopes` alpha builds are pinned exactly and excluded from automatic updates. `@atproto/space` and its alpha dependencies are bundled into `@getcirrus/spaces`, because several of them have broken releases that would otherwise be installed in their place. diff --git a/docs/src/content/docs/guides/enable-spaces.md b/docs/src/content/docs/guides/enable-spaces.md index b2782df..d694e94 100644 --- a/docs/src/content/docs/guides/enable-spaces.md +++ b/docs/src/content/docs/guides/enable-spaces.md @@ -1,6 +1,6 @@ --- title: Enable spaces (alpha) -description: Turn on the atproto spaces alpha — flag, bindings, R2 lifecycle rule — and manage spaces from the CLI and dashboard. +description: Turn on the atproto spaces alpha — flag, bindings, R2 lifecycle rule, KEM key — and manage spaces from the CLI and dashboard. --- Spaces are **alpha**. Read [the concepts page](/concepts/spaces/) first, especially the caveats: breaking upstream changes are absorbed by wiping space data, and nothing else. @@ -62,30 +62,57 @@ In `wrangler.jsonc`: } ``` -Deploy. Your DID document gains an `#atproto_space_host` service entry, and the `com.atproto.space.*` and `com.atproto.simplespace.*` endpoints go live. With the flag off, none of those routes exist and the DID document says nothing about spaces. +Deploy. The `com.atproto.space.*` and `com.atproto.memberspace.*` endpoints go live. With the flag off, none of those routes exist and the DID document says nothing about spaces. + +## 4. Create and publish the KEM key + +Syncers verify space data with a MAC derived against your `#atproto_kem` key (see [the concepts page](/concepts/spaces/#proving-data-came-from-you)). Without it, your PDS can still store and serve your own space data to you, but refuses credentialed reads that need a MAC. Create the key: + +```bash +pds spaces kem +``` + +This stores the private key as the `SPACES_KEM_KEY` secret and its public half as the `SPACES_KEM_KEY_PUBLIC` var in `wrangler.jsonc`. Then: + +- **did:web**: redeploy. Your PDS serves your DID document, which now includes `#atproto_kem`. +- **did:plc**: redeploy, then run `pds spaces kem --publish`. It asks your PDS to sign a PLC operation adding the key, which works when the PDS's signing key is one of your DID's rotation keys (true if you migrated with Cirrus). Otherwise, add the `atproto_kem` verification method with whoever holds your rotation key. + +`pds spaces status` checks that the key your PDS holds is the one your DID document publishes. ## Manage spaces from the CLI ```bash pds spaces status # flag, schema version, counts pds spaces list # every space this PDS holds data in -pds spaces create --type app.bsky.group --policy member-list -pds spaces members add +pds spaces create --type app.bsky.group --policy member +pds spaces members add # read and write +pds spaces members add --no-write # read only pds spaces members remove pds spaces members list pds spaces delete -pds spaces export --out ./spaces-export # one CAR per space +pds spaces export --out ./spaces-export # STAR archives, for migration +pds spaces kem # create (and with --publish, publish) the KEM key pds spaces reset # wipe ALL space data (and nothing else) ``` -`create` accepts `--policy public | member-list | managing-app` (with `--managing-app `), and repeatable `--allow ` flags to restrict which apps may access the space. +`create` accepts `--policy personal | member | managed`. A member space takes `--public-read`, `--public-write`, repeatable `--allow ` flags to restrict which apps may read it, and `--publish-policy` / `--publish-members` to publish its configuration to readers. A managed space takes `--managing-app `. -The dashboard at `/status` gains a **Spaces** panel showing each space's role, record and member counts, with delete and member management for spaces you host. It asks for your admin token (`AUTH_TOKEN`) on first use. +The dashboard at `/status` gains a **Spaces** panel showing each space's role, policy, record and member counts, with delete and member management for spaces you host. It asks for your admin token (`AUTH_TOKEN`) on first use. ## Grant apps access Apps request access with OAuth `space:` scopes, e.g. `space:my.app.bookmarks` for the app's own space type under your authority. The consent screen shows the space type's human name and warns loudly about wildcard grants. App passwords cannot access spaces. +## Upgrading from the August alpha + +The November 2026 alpha replaced simplespace with the baseline policies, credential DPoP with HTTP message signatures, and commit signatures with MACs. Space data from the earlier build can't be read by the new one. After upgrading: + +1. Deploy. Space endpoints answer 503 until you reset. +2. Run `pds spaces kem` and publish the key (step 4 above). +3. Run `pds spaces reset`, then recreate your spaces. + +Apps built against the earlier alpha (DPoP credentials, `com.atproto.simplespace.*`) need updating too. + ## When an alpha build breaks the schema After upgrading across an incompatible alpha build, space endpoints return a 503 pointing here, and `pds spaces status` shows which spaces are outdated. Your public repo, blobs, firehose and OAuth state are unaffected. Reset and start fresh: diff --git a/docs/src/content/docs/operate/secrets.md b/docs/src/content/docs/operate/secrets.md index 9006d5a..98ef049 100644 --- a/docs/src/content/docs/operate/secrets.md +++ b/docs/src/content/docs/operate/secrets.md @@ -12,6 +12,8 @@ Cirrus stores four Worker secrets, each with a different lifetime and rotation p | `PASSWORD_HASH` | Account password verification | Low — forces a sign-in next time | | `AUTH_TOKEN` | Static bearer token for admin | Low — invalidates current scripts | +With the [spaces alpha](/concepts/spaces/) enabled there is a fifth, `SPACES_KEM_KEY`: the `#atproto_kem` key syncers verify space data against. Like the signing key it has a public sibling var, `SPACES_KEM_KEY_PUBLIC`, and changes the DID document. Rotate it by running `pds spaces kem` again (and, for did:plc, `pds spaces kem --publish`); syncers fail to verify space data until the DID document carries the new key. + The signing key has a sibling public value, `SIGNING_KEY_PUBLIC`, that lives in `wrangler.jsonc` as a `var` (not a secret). It is the public half of the signing keypair and is used to serve the DID document. Rotating the signing key requires updating both. This page covers how to rotate each. diff --git a/plans/in-progress/spaces-spec.md b/plans/in-progress/spaces-spec.md index dac0c0f..cd3d05c 100644 --- a/plans/in-progress/spaces-spec.md +++ b/plans/in-progress/spaces-spec.md @@ -5,6 +5,8 @@ - Depends on: [proposal 0016](https://github.com/bluesky-social/proposals/tree/main/0016-permissioned-data), `@atproto/space@alpha`, the `permissioned-data-alpha` branch of the reference PDS - Scope: the Cirrus PDS only. A standalone space host is discussed as a consequence of the design, not specified here. +> **Superseded in places by the 20261105 alpha.** The mechanics below describe the August build: DPoP-bound credentials, signed commits with `ikm`, CAR `getRepo`, `#atproto_space_host`, and simplespace policies. Those were replaced upstream by HTTP-signature credentials, MAC-authenticated commits (`#atproto_kem`), STAR archives, plain `#atproto_pds` discovery and the personal/member/managed baseline policies. The user stories, isolation design and phasing still hold. See [spaces.md](./spaces.md) for what changed and the sync process. + ## Summary Add atproto spaces to Cirrus behind a feature flag, with all space state isolated from the public repository so that alpha-era breaking changes can be absorbed by wiping space data and never by touching the account's MST, blobs or OAuth state. diff --git a/plans/in-progress/spaces.md b/plans/in-progress/spaces.md index 2b1b419..16fa4e6 100644 --- a/plans/in-progress/spaces.md +++ b/plans/in-progress/spaces.md @@ -45,6 +45,93 @@ Delivered as a stacked PR chain, bottom to top: User stories S1–S9 all have automated coverage (54 engine/protocol tests, 8 PDS integration tests). +## Alpha 20261105160032 (2026-11-09) + +Moved from the 0818 alpha to `0.0.0-spaces-alpha-20261105160032`, cut from +`permissioned-data-alpha@704b9e2`, following the sync process below. Five +upstream builds landed in between and the protocol changed substantially: + +- **Credentials**: DPoP replaced by HTTP message signatures. Credentials + bind a P-256 did:key (`cnf.kid`), are presented as + `Authorization: Atproto-Space-Credential ` with an + `Atproto-Space-Audience` header (the DID being called: always the + operator here), and live 600s. `getSpaceCredential` takes + `credentialKid` / `delegationToken` / `clientAttestation` in the body; + public-read spaces issue without a delegation token; refused users get + `SpaceNotFound`. Revocations arrive via `notifyCredentialRevoked` and + are kept per space DO. +- **Discovery**: `#atproto_space` / `#atproto_space_host` dropped. The + authority's `#atproto_pds` is the space host; `#atproto` signs tokens. +- **Commits and MACs**: commits are `{ver, repo, space, rev, data}` with + no signature. Credentialed reads returning a commit or record need + `Atproto-Space-Want-Mac`; the host derives a secret against its + `#atproto_kem` P-256 key (`SPACES_KEM_KEY` secret, + `SPACES_KEM_KEY_PUBLIC` var, `pds spaces kem`) and answers + `Atproto-Space-Mac`. +- **getRepo** streams STAR (`atproto-space-repo`) in record-path byte + order, fenced against concurrent writes by rev. This also retires the + "getRepo buffers the whole repo" open question. +- **Policies**: simplespace replaced by personalspace / memberspace / + managedspace (`com.atproto.space.{create,update,delete,get}Space`, + `com.atproto.memberspace.*`), stored as the normalised lexicon object. + Optional published `com.atproto.space.policy` / `memberspace.member` + records in the authority's repo, written atomically by the DO. +- **Sequencing**: writers carry `spaceRev`; `listRepos` pages by it; + forwarded `notifyWrite`s add `spaceRev` / `prevSpaceRev`; `FutureRev` + beyond 5 minutes of skew. The writer role now retries its notifyWrite + to a foreign authority for 24h, coalesced in the DO queue. +- **Migration**: `importRepo`, `exportSpaceMeta`, `importSpaceMeta`; + `clearRecords`; `removeWriter`. Imported records' blobs are registered + as pending in the index DO and promoted by `repo.uploadBlob`. +- **Schema version 2**: existing space DOs refuse until + `pds spaces reset`, per the alpha policy. + +### Packaging: the alpha is bundled + +`@atproto/space@1105` depends on the alpha `lex-cbor` / `lex-data` / +`star`, each of which has a release that outranks +`^0.0.0-spaces-alpha-*` and is broken (bare `0.0.0` with `workspace:*` +deps; `star@0.0.0-stage` is a corrupt tarball). Verified with scratch +installs: exact sibling pins (the #255 fix) no longer rescue npm once a +stable `lex-data` sits at the root, as it does under `@getcirrus/pds`. So +`@getcirrus/spaces` and `@getcirrus/space-conformance` keep every alpha +`@atproto` package in devDependencies and tsdown bundles them +(`platform: "browser"` so the browser builds are picked, not ones reaching +for `node:crypto`). `@getcirrus/pds` no longer depends on `@atproto/space` +at runtime. Public types are structural (`SpaceSigningKeypair`, +`SpaceCommit`) so no `.d.ts` references an `@atproto` package. Check after +each bump: `grep -o 'from "[^"]*"' packages/spaces/dist/*.js packages/spaces/dist/*.d.ts`. + +## Alpha sync process + +Upstream cuts a build from `permissioned-data-alpha` most Thursdays. To +move to a new one (the update loop from the space-conformance spec, #228): + +1. **Find the build and its commit.** `npm view @atproto/space dist-tags` + for the version; the source commit is the last one on + `permissioned-data-alpha` before the build's timestamp (UTC). Read the + `.changeset/*.md` files on the branch: they describe every protocol + change. +2. **Re-vendor lexicons.** Check out that commit and run + `pnpm --filter @getcirrus/space-conformance vendor-lexicons `. + The lexicon diff, through check citations, names the affected checks; + the coverage test names any new method or error without a MUST check. +3. **Bump pins in lockstep**: every `0.0.0-spaces-alpha-*` in package + manifests and the `pnpm-workspace.yaml` overrides. Check each alpha + package in the new tree for a release that outranks the alpha range + (bare `0.0.0`, or a prerelease sorting after `spaces-alpha`); add an + override for any new one. +4. **Diff the upstream packages** (`npm pack` both builds of + `@atproto/space`, `oauth-scopes`, `syntax`) and implement the changes + in the engine, PDS and oauth-provider, with tests. +5. **Recalibrate**: run the conformance suite against the reference + (`pnpm --filter @getcirrus/space-conformance-matrix test`), re-pin the + partition and update the matrix README's divergence table and its alpha + version. If a build can't be onboarded, leave pins and suite on the old + build and say so, rather than letting the matrix rot. +6. **Check the bundle** (above), update this plan and the docs, and add a + changeset. + ## Not done / next - **Interop runs** against the reference alpha Docker image and rsky. @@ -55,13 +142,17 @@ User stories S1–S9 all have automated coverage (54 engine/protocol tests, - **R2 lifecycle rule** must be applied per-install (`wrangler r2 bucket lifecycle add pds-blobs --prefix "/staged/" --expire-days 7`); `pds init` doesn't automate it yet. -- Streaming `getRepo` (currently buffers via `serializeRepo`), blob cache - tagging, per-credential rate limits, import — all "Later" per the spec. +- Blob cache tagging, per-credential rate limits — "Later" per the spec. +- Sending revocations: Cirrus receives `notifyCredentialRevoked` but, like + the reference, never revokes credentials it issued (member removal waits + out the credential's 10-minute lifetime). +- Takedowns: `RepoTakendown` is declared but Cirrus has no takedown + state; only deactivation (`RepoDeactivated`) is enforced. - Standalone host package (S9): the engine boundary is in place; no package yet. - Alpha deps (`@atproto/space`, `@atproto/oauth-scopes` at - `0.0.0-spaces-alpha-20260818163953`) need re-verification against each - upstream Thursday build; Renovate is configured to leave them alone. + `0.0.0-spaces-alpha-20261105160032`) follow the sync process above; + Renovate is configured to leave them alone. ## Implementation notes (non-obvious) @@ -75,7 +166,12 @@ User stories S1–S9 all have automated coverage (54 engine/protocol tests, the pool even when handled; engine tests capture expected errors inside `runInDurableObject` instead. - `@atproto/oauth-scopes@alpha` does not re-export `LexiconSpace`; - oauth-provider defines the shape locally. + oauth-provider defines the shape locally. Since 1105 a `SpacePermission` + without collections or manage ops has those fields `undefined`, not + empty arrays. +- The SQL order of `(collection, rkey)` is not the STAR archive's order: + `app.bsky.feed.post/a` sorts before `app.bsky.feed/z` byte-wise. The DO + orders archive pages by `collection || '/' || rkey` (BINARY collation). - `@atcute/lexicon-resolver` can't resolve a space type declaration: it validates the fetched doc against `@atcute/lexicon-doc`, whose def-type whitelist has no `type: "space"`, so a valid declaration From a3baf28560e246cb17686f2aa5ce4c154f788147 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 08:53:05 +0000 Subject: [PATCH 04/16] fix(spaces): check the space is hosted here before verifying a delegation Verifying a delegation token records its replay key in the space DO, so a well-formed request naming any foreign space would otherwise create an empty DO for it. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LZ7qcQNQoiA6a23woGC7tB --- packages/spaces/src/routes.ts | 3 +++ 1 file changed, 3 insertions(+) diff --git a/packages/spaces/src/routes.ts b/packages/spaces/src/routes.ts index eeefc84..217e9bc 100644 --- a/packages/spaces/src/routes.ts +++ b/packages/spaces/src/routes.ts @@ -1392,6 +1392,9 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { "credentialKid must be a P-256 did:key", ); } + // Before anything touches the space DO: a space this host doesn't + // govern must not get one created for it by a well-formed request. + assertSpaceHost(ref); const stub = host.getSpaceDO(ref.uri); // Absent when the request carries no delegation token, which only a From 0d08b2609754809bb221d7b78b58b28eb2c6c517 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 08:53:20 +0000 Subject: [PATCH 05/16] wip(space-conformance): port the suite to the 2026-11-05 alpha (in progress) Snapshot of the conformance suite rewrite while it is still under way: HTTP-signature credentials, MAC verification, STAR archives, the baseline policies and the new methods. Not yet green; the finished version, in-process runners and matrix recalibration follow. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LZ7qcQNQoiA6a23woGC7tB --- .../space-conformance-matrix/src/harness.ts | 136 +++ .../space-conformance-matrix/src/reference.ts | 3 + .../test/reference-matrix.test.ts | 151 ++- packages/space-conformance/src/alpha.ts | 7 + packages/space-conformance/src/car.ts | 43 - packages/space-conformance/src/changesets.ts | 26 + packages/space-conformance/src/checks/base.ts | 188 +-- .../src/checks/credential.ts | 724 ++++++++++++ packages/space-conformance/src/checks/host.ts | 372 ++++++ .../space-conformance/src/checks/operator.ts | 876 +------------- .../space-conformance/src/checks/probe.ts | 378 ++++++ .../space-conformance/src/checks/records.ts | 739 ++++++++++++ .../space-conformance/src/checks/space.ts | 586 ++++++++++ packages/space-conformance/src/cli/main.ts | 20 +- packages/space-conformance/src/cli/oauth.ts | 23 +- packages/space-conformance/src/cli/run.ts | 19 +- packages/space-conformance/src/coverage.ts | 61 +- packages/space-conformance/src/descriptors.ts | 215 +++- packages/space-conformance/src/did.ts | 130 +++ packages/space-conformance/src/dpop.ts | 96 -- packages/space-conformance/src/encoding.ts | 152 +++ packages/space-conformance/src/full.ts | 13 +- packages/space-conformance/src/full/checks.ts | 1038 +++++++++++------ .../space-conformance/src/full/helpers.ts | 169 ++- packages/space-conformance/src/http.ts | 23 +- packages/space-conformance/src/identity.ts | 107 +- packages/space-conformance/src/index.ts | 66 +- packages/space-conformance/src/model.ts | 86 +- packages/space-conformance/src/space-auth.ts | 305 +++++ packages/space-conformance/test/cli.test.ts | 147 ++- packages/space-conformance/test/core.test.ts | 62 +- packages/space-conformance/test/full.test.ts | 314 +++-- 32 files changed, 5478 insertions(+), 1797 deletions(-) create mode 100644 packages/space-conformance-matrix/src/harness.ts create mode 100644 packages/space-conformance/src/alpha.ts delete mode 100644 packages/space-conformance/src/car.ts create mode 100644 packages/space-conformance/src/changesets.ts create mode 100644 packages/space-conformance/src/checks/credential.ts create mode 100644 packages/space-conformance/src/checks/host.ts create mode 100644 packages/space-conformance/src/checks/probe.ts create mode 100644 packages/space-conformance/src/checks/records.ts create mode 100644 packages/space-conformance/src/checks/space.ts create mode 100644 packages/space-conformance/src/did.ts delete mode 100644 packages/space-conformance/src/dpop.ts create mode 100644 packages/space-conformance/src/encoding.ts create mode 100644 packages/space-conformance/src/space-auth.ts diff --git a/packages/space-conformance-matrix/src/harness.ts b/packages/space-conformance-matrix/src/harness.ts new file mode 100644 index 0000000..3fb1c83 --- /dev/null +++ b/packages/space-conformance-matrix/src/harness.ts @@ -0,0 +1,136 @@ +/** + * Resolvable harness identities and a syncer inbox for the reference run. + * + * The identity-gated checks need parties the reference can resolve: a + * reader whose delegation tokens it verifies, a writer whose service auth + * it verifies, a foreign space authority whose credentials and revocations + * it honours, and a syncer / managing app it calls. Each identity gets its + * own tiny HTTP server and a `did:web:localhost%3A` DID, which the + * reference resolves over plain http (its did:web resolver does that for + * `localhost`, and dev-env disables SSRF protection). The server publishes + * the identity's DID document — `#atproto` plus an `#atproto_pds` service + * pointing back at itself — and records every XRPC call it receives, so + * the "syncer" identity doubles as the inbox. + */ + +import { createServer, type Server } from "node:http"; +import type { AddressInfo } from "node:net"; +import type { InboxDelivery, SyncerInbox } from "@getcirrus/space-conformance"; +import { KeypairIdentityProvider } from "@getcirrus/space-conformance/full"; + +export interface HarnessServices { + identities: KeypairIdentityProvider; + inbox: SyncerInbox; + close(): Promise; +} + +export async function startHarnessServices(): Promise { + const servers: Server[] = []; + const deliveries: InboxDelivery[] = []; + const waiters = new Set<() => void>(); + const responders = new Map unknown>(); + + const identities: KeypairIdentityProvider = new KeypairIdentityProvider( + async (role) => { + let did = ""; + const server = createServer((req, res) => { + const url = new URL(req.url ?? "/", "http://localhost"); + if (url.pathname === "/.well-known/did.json") { + void identities.identity(role).then((identity) => { + res.setHeader("Content-Type", "application/json"); + res.end( + JSON.stringify( + KeypairIdentityProvider.didDocument(identity, { + serviceEndpoint: `http://localhost:${port}`, + }), + ), + ); + }); + return; + } + const lxm = url.pathname.startsWith("/xrpc/") + ? url.pathname.slice("/xrpc/".length) + : url.pathname; + let raw = ""; + req.on("data", (chunk) => (raw += chunk)); + req.on("end", () => { + let body: unknown; + try { + body = raw ? JSON.parse(raw) : undefined; + } catch { + body = raw; + } + const delivery: InboxDelivery = { + lxm, + body, + params: Object.fromEntries(url.searchParams), + ...(req.headers.authorization + ? { authorization: req.headers.authorization } + : {}), + receivedAt: Date.now(), + }; + // Only the inbox identity records; the others just publish a doc. + if (did === inboxDid) { + deliveries.push(delivery); + for (const wake of waiters) wake(); + } + const responder = did === inboxDid ? responders.get(lxm) : undefined; + res.setHeader("Content-Type", "application/json"); + res.end(JSON.stringify(responder ? responder(delivery) : {})); + }); + }); + await new Promise((resolve) => + server.listen(0, "127.0.0.1", resolve), + ); + servers.push(server); + const port = (server.address() as AddressInfo).port; + did = `did:web:localhost%3A${port}`; + return did; + }, + ); + + const syncer = await identities.identity("syncer"); + const inboxDid = syncer.did; + + const inbox: SyncerInbox = { + service: inboxDid, + async waitFor(predicate, timeoutMs) { + const deadline = Date.now() + timeoutMs; + for (;;) { + const found = deliveries.find(predicate); + if (found) return found; + const remaining = deadline - Date.now(); + if (remaining <= 0) return null; + await new Promise((resolve) => { + const timer = setTimeout(done, remaining); + function done() { + clearTimeout(timer); + waiters.delete(done); + resolve(); + } + waiters.add(done); + }); + } + }, + respond(lxm, handler) { + if (handler) responders.set(lxm, handler); + else responders.delete(lxm); + }, + }; + + return { + identities, + inbox, + close: async () => { + await Promise.all( + servers.map( + (server) => + new Promise((resolve) => { + server.closeAllConnections(); + server.close(() => resolve()); + }), + ), + ); + }, + }; +} diff --git a/packages/space-conformance-matrix/src/reference.ts b/packages/space-conformance-matrix/src/reference.ts index 78c1ba8..ea5e09c 100644 --- a/packages/space-conformance-matrix/src/reference.ts +++ b/packages/space-conformance-matrix/src/reference.ts @@ -20,6 +20,8 @@ export interface ReferencePds { operatorDid: string; /** A full-access session token for the operator account. */ operatorToken: string; + /** The dev-env PLC directory every did:plc here resolves against. */ + plcUrl: string; /** Tear down the PLC and PDS servers. */ close(): Promise; } @@ -40,6 +42,7 @@ export async function startReferencePds(): Promise { origin: network.pds.url, operatorDid: operator.did, operatorToken: operator.accessJwt, + plcUrl: network.plc.url, close: () => network.close(), }; } catch (err) { diff --git a/packages/space-conformance-matrix/test/reference-matrix.test.ts b/packages/space-conformance-matrix/test/reference-matrix.test.ts index 1058662..99548b6 100644 --- a/packages/space-conformance-matrix/test/reference-matrix.test.ts +++ b/packages/space-conformance-matrix/test/reference-matrix.test.ts @@ -22,12 +22,20 @@ import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { + ALPHA_BUILD, filterCatalog, runChecks, type RunReport, } from "@getcirrus/space-conformance"; import { fullCatalog } from "@getcirrus/space-conformance/full"; import { startReferencePds, type ReferencePds } from "../src/reference.js"; +import { + startHarnessServices, + type HarnessServices, +} from "../src/harness.js"; + +/** The alpha build this partition was calibrated against. */ +const CALIBRATED_ALPHA = "0.0.0-spaces-alpha-20261105160032"; /** * Checks the reference PDS is known to fail, with the reason it diverges from @@ -37,58 +45,53 @@ import { startReferencePds, type ReferencePds } from "../src/reference.js"; * The pin is on status, not on the reason: a divergence starting to *pass* is * caught (the partition assertion fails), but one that keeps failing for a new * reason is not. That blind spot is narrow — three checks with distinctive - * failure modes — so the reason lives in the comment, and a change of reason - * is expected to be noticed in review of whatever moved the reference. + * failure modes — so the reason lives here, and a change of reason is expected + * to be noticed in review of whatever moved the reference. */ const EXPECTED_DIVERGENCES: Record = { - // The reference is a multi-tenant did:plc host: accounts resolve through - // PLC and it serves no DID document at `${origin}/.well-known/did.json`, - // so a check that reads the space-host service entry from that document - // cannot evaluate it. On Cirrus (single-tenant did:web) it applies and - // passes. Proposal 0016 §space-authority. - "discovery.space-host-service": - "reference is multi-tenant did:plc; no DID document at the origin", - "discovery.verification-key": - "reference is multi-tenant did:plc; no DID document at the origin", - // The reference alpha refuses an *unreferenced* uploaded blob on the - // public sync.getBlob (the check's first probe passes there), but a - // reference from a space record promotes the blob to public availability - // exactly as a public-record reference would — so the private write is - // what leaks the bytes to anyone who learns the CID. The protocol intends - // space blobs to be fetched via the credential-gated space.getBlob - // (proposal 0016 §blob-sync); Cirrus enforces that with a separate - // per-space blob key layout, which is exactly the gate this check guards. - "blobs.space-blob-not-public": - "reference alpha promotes space-referenced blobs to the public sync.getBlob", + // deleteRecord declares SpaceNotFound, and deleteSpace's description says + // "afterwards, reads and writes fail with SpaceNotFound". The reference's + // deleteRecord handler checks whether the record exists *before* anything + // touches the space (`hasRecord` → return null, for idempotency), so a delete + // in a missing or deleted space is a silent 200 and the space check in + // `ensureRepo` (changeset brave-spaces-exist) is never reached. Its create, + // put and applyWrites do answer SpaceNotFound (writes.space-not-found passes). + "writes.delete-in-missing-space": + "reference deleteRecord short-circuits on an absent record before checking the space, answering 200", + // Same deleteSpace sentence, read side. The reference's read handlers never + // consult the space row: after deletion the owner's repo is gone, so they + // answer RecordNotFound / RepoNotFound / BlobNotFound or an empty 200 listing, + // never the SpaceNotFound each of them declares. + "space.reads-after-delete-not-found": + "reference reads ignore the space tombstone and answer RecordNotFound/RepoNotFound/BlobNotFound or an empty 200", + // ClientAttestationVerifier.verify calls parseSpaceToken outside its + // invalid() wrapper, so a structurally malformed attestation escapes as an + // uncaught SpaceTokenError: 500 InternalServerError, where the lexicon + // declares InvalidClientAttestation. A well-formed but unverifiable one is + // refused correctly (credential.unverifiable-attestation-refused passes). + "credential.garbage-attestation-refused": + "reference answers 500 for a malformed client attestation (parseSpaceToken throws outside invalid())", }; -/** - * Checks that need harness identities the reference cannot resolve (foreign - * reader/writer DIDs). They are exercised in-process by the @getcirrus/spaces - * fixture adapter, which wires a did:key resolver; here they skip. The - * operator's own credential flow is still covered end-to-end by - * credential.self-round-trip, which needs no foreign identity. - */ -const IDENTITY_GATED = new Set([ - "credential.round-trip", - "credential.cross-space-refused", - "delegation.replay-refused", - "delegation.wrong-audience-refused", - "host.member-list-gates", - "host.delete-space-tombstone", -]); - describe("conformance suite vs the atproto reference PDS", () => { let ref: ReferencePds; + let harness: HarnessServices; let report: RunReport; beforeAll(async () => { ref = await startReferencePds(); + harness = await startHarnessServices(); const catalog = filterCatalog(fullCatalog, { - // A full reference PDS: an operator session, the public blob - // endpoints, and its own getDelegationToken (the self credential - // flow). Identities are deliberately withheld — see IDENTITY_GATED. - capabilities: ["operator", "pds-blobs", "pds-delegation"], + // Everything: an operator session, the public blob endpoints, the + // reference's own getDelegationToken, harness identities it can + // resolve (did:web on localhost) and a syncer inbox it can reach. + capabilities: [ + "operator", + "pds-blobs", + "pds-delegation", + "identities", + "syncer-inbox", + ], destructive: true, }); report = await runChecks({ @@ -98,6 +101,7 @@ describe("conformance suite vs the atproto reference PDS", () => { origin: ref.origin, did: ref.operatorDid, implementation: "atproto-reference-pds", + plcDirectory: ref.plcUrl, }, fetch, operator: { @@ -106,22 +110,27 @@ describe("conformance suite vs the atproto reference PDS", () => { init.headers.set("Authorization", `Bearer ${ref.operatorToken}`); }, }, + identities: harness.identities, + syncerInbox: harness.inbox, }, suiteVersion: "reference-matrix", - alphaBuild: "0.0.0-spaces-alpha-20260818163953", + alphaBuild: ALPHA_BUILD, }); - }, 120_000); + }, 300_000); afterAll(async () => { + await harness?.close(); await ref?.close(); }); + it("is calibrated against the alpha the suite is pinned to", () => { + // Bumping the alpha without re-running and re-pinning this matrix must + // fail here, not silently carry the old partition forward. + expect(ALPHA_BUILD).toBe(CALIBRATED_ALPHA); + }); + const expectedStatus = (id: string): string => - id in EXPECTED_DIVERGENCES - ? "fail" - : IDENTITY_GATED.has(id) - ? "skipped" - : "pass"; + id in EXPECTED_DIVERGENCES ? "fail" : "pass"; it("behaves exactly as pinned on every check", () => { const wrong = report.results.filter( @@ -140,37 +149,53 @@ describe("conformance suite vs the atproto reference PDS", () => { ).toEqual([]); }); - it("passes every interop-critical must check the reference supports", () => { - // The load-bearing ones, named so a regression reads clearly. These are - // the write, sync, policy and credential mechanics that two independent + it("runs the whole catalog — nothing skipped", () => { + // Every capability is provided, so a skip means a check grew a need the + // harness doesn't meet; it must be wired here, not quietly dropped. + expect(report.results.filter((r) => r.status === "skipped")).toEqual([]); + expect(report.results).toHaveLength(fullCatalog.length); + }); + + it("passes every interop-critical must check", () => { + // The load-bearing ones, named so a regression reads clearly: the write, + // credential, signature, MAC, sync and policy mechanics two independent // implementations must agree on to interoperate at all. const byId = Object.fromEntries( report.results.map((r) => [r.id, r.status]), ); for (const id of [ + "discovery.kem-key", "writes.create-and-read", - "writes.duplicate-rejected", "writes.applywrites-atomic", "credential.self-round-trip", + "credential.claims", + "credential.signature-required", + "credential.audience-bound", + "mac.want-mac-required", + "mac.commit-verifies", + "mac.record-verifies", "sync.oplog-folds-to-commit", - "sync.getrepo-two-roots", - "host.listrepos-requires-credential", - "simplespace.unsupported-policy-rejected", - "simplespace.getspace-reflects-config", + "sync.getrepo-star", + "sync.listrepos-shape", + "credential.member-gate", + "revocation.revoked-credential-refused", + "notify.forwarded-notifywrite", + "managedspace.checkuseraccess", + "migration.import-repo", ]) { expect(byId[id], `${id} against the reference`).toBe("pass"); } }); - it("every pinned divergence is a real must/should check, not a typo", () => { + it("every pinned divergence is a real must check, not a typo", () => { // Guard the pin against bit-rot: an id in EXPECTED_DIVERGENCES that no - // longer exists in the catalog would silently do nothing. - const ids = new Set(fullCatalog.map((c) => c.id)); + // longer exists in the catalog would silently do nothing. A should check + // the reference fails is stale by definition and belongs out of the + // catalog, not in this list. + const byId = new Map(fullCatalog.map((c) => [c.id, c])); for (const id of Object.keys(EXPECTED_DIVERGENCES)) { - expect(ids.has(id), `${id} is not a known check`).toBe(true); - } - for (const id of IDENTITY_GATED) { - expect(ids.has(id), `${id} is not a known check`).toBe(true); + expect(byId.has(id), `${id} is not a known check`).toBe(true); + expect(byId.get(id)?.tier, `${id} must be a must check`).toBe("must"); } }); }); diff --git a/packages/space-conformance/src/alpha.ts b/packages/space-conformance/src/alpha.ts new file mode 100644 index 0000000..574dfc5 --- /dev/null +++ b/packages/space-conformance/src/alpha.ts @@ -0,0 +1,7 @@ +/** + * The alpha build the suite's verifiers are pinned to: the + * `@atproto/space` / `@atproto/crypto` versions bundled into dist, cut from + * bluesky-social/atproto `permissioned-data-alpha` at the vendored lexicon + * commit. Runners stamp it on every report. + */ +export const ALPHA_BUILD = "0.0.0-spaces-alpha-20261105160032"; diff --git a/packages/space-conformance/src/car.ts b/packages/space-conformance/src/car.ts deleted file mode 100644 index 89f5395..0000000 --- a/packages/space-conformance/src/car.ts +++ /dev/null @@ -1,43 +0,0 @@ -/** - * Just enough CARv1 reading to assert getRepo's declared shape: the - * lexicon requires exactly two roots (the signed commit, then the index). - * Reading the header needs only a varint and a dag-cbor decode — no CAR - * library, no node streams — so it stays runnable anywhere the full entry - * runs. - */ - -import { decode as cborDecode } from "@atproto/lex-cbor"; - -function readVarint(bytes: Uint8Array, offset: number): [number, number] { - let result = 0; - let shift = 0; - let pos = offset; - for (;;) { - const byte = bytes[pos]; - if (byte === undefined) throw new Error("truncated varint"); - result |= (byte & 0x7f) << shift; - pos += 1; - if ((byte & 0x80) === 0) break; - shift += 7; - } - return [result, pos]; -} - -interface CarHeaderInfo { - version: number; - rootCount: number; -} - -/** Parse just the CARv1 header block and report its version and root count. */ -export function readCarHeader(bytes: Uint8Array): CarHeaderInfo { - const [headerLen, afterVarint] = readVarint(bytes, 0); - const headerBytes = bytes.subarray(afterVarint, afterVarint + headerLen); - const header = cborDecode(headerBytes) as { - version?: number; - roots?: unknown[]; - }; - return { - version: header.version ?? 0, - rootCount: Array.isArray(header.roots) ? header.roots.length : 0, - }; -} diff --git a/packages/space-conformance/src/changesets.ts b/packages/space-conformance/src/changesets.ts new file mode 100644 index 0000000..2d38ef6 --- /dev/null +++ b/packages/space-conformance/src/changesets.ts @@ -0,0 +1,26 @@ +/** + * The upstream changesets the suite may cite, from bluesky-social/atproto + * `permissioned-data-alpha` at the vendored commit (see + * ../lexicons/MANIFEST.json). For alpha mechanics no lexicon can express — + * the credential HTTP signature, the MAC exchange, key discovery — a + * changeset is the alpha's only normative prose. Citations are checked + * against this list, the same typo guard lexicon citations get; re-vendor + * it alongside the lexicons. + */ +export const knownChangesets: readonly string[] = [ + "alpha-kem-key-backfill", + "baseline-space-policies", + "brave-spaces-exist", + "clear-spaces-sweep", + "funky-dryers-draw", + "neat-guests-pull", + "olive-crabs-fly", + "open-spaces-greet", + "plain-keys-resolve", + "quiet-spaces-mac", + "quiet-writers-leave", + "small-hornets-jam", + "space-takedown-parity", + "star-spaces-shine", + "sturdy-spaces-depart", +]; diff --git a/packages/space-conformance/src/checks/base.ts b/packages/space-conformance/src/checks/base.ts index 96a816a..347e4fa 100644 --- a/packages/space-conformance/src/checks/base.ts +++ b/packages/space-conformance/src/checks/base.ts @@ -1,59 +1,118 @@ /** - * Browser-safe checks: discovery and unauthenticated request shapes. - * - * These need only `fetch` — no token minting, no @atproto/space — so they - * run in any transport including a browser bundle. Everything crypto-bound - * lives in `../checks/full-checks.ts` behind the `./full` entry. + * Browser-safe checks that need no session: discovery and unauthenticated + * request shapes. They need only `fetch` — no token minting, no + * @atproto/space — so they run in any transport, including a browser + * bundle, against any host the user names. */ import { defineCheck } from "../registry.js"; import { xrpcGet, xrpcPost } from "../http.js"; -import { pass, fail, type Check } from "../model.js"; +import { pass, fail, type Check, type CheckContext } from "../model.js"; +import { + resolveDidDocument, + serviceEndpoint, + verificationMethodDidKey, + type DidDocument, +} from "../did.js"; +import { createCredentialKey, isP256DidKey } from "../space-auth.js"; +import { PROBE_TYPE, describe, unknownSpaceUri } from "./probe.js"; -const SPACE_HOST_FRAGMENT = "#atproto_space_host"; +const changeset = (ref: string) => ({ source: "changeset" as const, ref }); +const lexicon = (ref: string) => ({ source: "lexicon" as const, ref }); -const discoveryServiceEntry = defineCheck({ - id: "discovery.space-host-service", - title: "DID document advertises the space host service endpoint", +/** The target's DID document, resolved once per run by its DID method. */ +async function targetDoc(ctx: CheckContext): Promise { + const cached = ctx.state.get("did.doc.target"); + if (cached) return cached as DidDocument; + const doc = await resolveDidDocument(ctx, ctx.target.did); + ctx.state.set("did.doc.target", doc); + return doc; +} + +const sameOrigin = (a: string, b: string) => { + try { + return new URL(a).origin === new URL(b).origin; + } catch { + return false; + } +}; + +const discoveryPdsService = defineCheck({ + id: "discovery.pds-service", + title: "The authority's #atproto_pds service is the space host", tier: "must", - citations: [{ source: "proposal", ref: "0016#space-authority" }], + citations: [changeset("plain-keys-resolve")], needs: [], async run(ctx) { - const res = await ctx.fetch(`${ctx.target.origin}/.well-known/did.json`); - if (!res.ok) return fail(`did.json returned ${res.status}`); - const doc = (await res.json()) as { - service?: Array<{ id: string; type: string; serviceEndpoint: unknown }>; - }; - const entry = (doc.service ?? []).find((s) => - s.id.endsWith(SPACE_HOST_FRAGMENT), - ); - if (!entry) { - return fail("no #atproto_space_host service entry", doc.service); - } - return pass(`serviceEndpoint ${String(entry.serviceEndpoint)}`, entry); + // The alpha dropped #atproto_space_host: a space authority is resolved + // like any account, and its PDS is its space host. So the target DID + // must route to this origin through #atproto_pds. + const doc = await targetDoc(ctx); + const endpoint = serviceEndpoint(doc, "atproto_pds"); + if (!endpoint) return fail("no #atproto_pds service entry", doc.service); + return sameOrigin(endpoint, ctx.target.origin) + ? pass(`#atproto_pds is ${endpoint}`) + : fail( + `#atproto_pds is ${endpoint}, not the target origin ${ctx.target.origin}`, + doc.service, + ); }, }); -const discoveryVerificationKey = defineCheck({ - id: "discovery.verification-key", - title: "DID document exposes an atproto verification key", +const discoverySigningKey = defineCheck({ + id: "discovery.signing-key", + title: "The DID document exposes the #atproto key that signs space tokens", tier: "must", - citations: [{ source: "proposal", ref: "0016#space-authority" }], + citations: [changeset("plain-keys-resolve")], + needs: [], + async run(ctx) { + const doc = await targetDoc(ctx); + const key = verificationMethodDidKey(doc, "atproto"); + return key + ? pass(`#atproto is ${key}`) + : fail("no usable #atproto verification method", doc.verificationMethod); + }, +}); + +const discoveryKemKey = defineCheck({ + id: "discovery.kem-key", + title: "The DID document publishes a P-256 #atproto_kem key", + tier: "must", + citations: [ + changeset("quiet-spaces-mac"), + lexicon("com.atproto.space.getLatestCommit"), + ], + needs: [], + async run(ctx) { + // A syncer derives each request's MAC secret by ECDH against the + // repo's #atproto_kem key. Without it no credentialed read of this + // account's repos can be authenticated at all. + const doc = await targetDoc(ctx); + const key = verificationMethodDidKey(doc, "atproto_kem"); + if (!key) return fail("no #atproto_kem verification method", doc.verificationMethod); + return isP256DidKey(key) + ? pass(`#atproto_kem is ${key}`) + : fail(`#atproto_kem is not a P-256 key: ${key}`); + }, +}); + +const discoveryLegacyEntries = defineCheck({ + id: "discovery.legacy-space-entries", + title: "Reports any pre-alpha #atproto_space / #atproto_space_host entries", + tier: "info", + citations: [changeset("plain-keys-resolve")], needs: [], async run(ctx) { - const res = await ctx.fetch(`${ctx.target.origin}/.well-known/did.json`); - if (!res.ok) return fail(`did.json returned ${res.status}`); - const doc = (await res.json()) as { - verificationMethod?: Array<{ id: string }>; - }; - // The proposal falls back to #atproto when #atproto_space is absent, - // so at minimum #atproto must be present to verify space tokens. - const hasAtproto = (doc.verificationMethod ?? []).some((m) => - m.id.endsWith("#atproto"), + const doc = await targetDoc(ctx); + const legacy = [ + ...(doc.verificationMethod ?? []).map((m) => m.id), + ...(doc.service ?? []).map((s) => s.id), + ].filter((id) => /#atproto_space(_host)?$/.test(id)); + return pass( + legacy.length + ? `still publishes ${legacy.join(", ")} (ignored by the alpha)` + : "no legacy space entries", ); - return hasAtproto - ? pass("#atproto verification method present") - : fail("no #atproto verification method", doc.verificationMethod); }, }); @@ -61,7 +120,7 @@ const authGetRecordRequiresAuth = defineCheck({ id: "auth.getrecord-unauthenticated-refused", title: "space.getRecord refuses an unauthenticated request", tier: "must", - citations: [{ source: "lexicon", ref: "com.atproto.space.getRecord" }], + citations: [lexicon("com.atproto.space.getRecord")], needs: [], async run(ctx) { // A read with no credential and no session must be refused on the @@ -71,7 +130,7 @@ const authGetRecordRequiresAuth = defineCheck({ // all (there's simply no record at this probe URI to leak), and a 5xx // is a server fault, not a refusal — neither demonstrates enforcement. const res = await xrpcGet(ctx, "com.atproto.space.getRecord", { - space: `at://${ctx.target.did}/space/earth.cirrus.check.space/probe`, + space: `at://${ctx.target.did}/space/${PROBE_TYPE}/probe`, repo: ctx.target.did, collection: "app.bsky.feed.post", rkey: "whatever", @@ -80,31 +139,31 @@ const authGetRecordRequiresAuth = defineCheck({ return pass(`refused with ${res.status}`); } return fail( - `unauthenticated read was not refused with 401/403 (got ${res.status} ${res.error ?? ""})`, + `unauthenticated read was not refused with 401/403 (got ${describe(res)})`, res.json, ); }, }); -const authCredentialRequiresToken = defineCheck({ - id: "auth.getspacecredential-untoken-refused", - title: "space.getSpaceCredential refuses a request with no delegation token", +const credentialTokenlessUnknown = defineCheck({ + id: "credential.tokenless-unknown-space", + title: "A tokenless credential request for an unknown space gets SpaceNotFound", tier: "must", - citations: [ - { source: "lexicon", ref: "com.atproto.space.getSpaceCredential" }, - ], + citations: [lexicon("com.atproto.space.getSpaceCredential@error:SpaceNotFound")], needs: [], async run(ctx) { + // No delegation token, a space nobody created: there is nothing public + // to issue for, and the declared answer is SpaceNotFound — the same + // answer a non-public space gives, so existence is not disclosed. + const key = await createCredentialKey(); const res = await xrpcPost(ctx, "com.atproto.space.getSpaceCredential", { - space: `at://${ctx.target.did}/space/earth.cirrus.check.space/probe`, + space: unknownSpaceUri(ctx.target.did), + credentialKid: key.did, }); - if (res.status === 401 || res.status === 403 || res.status === 400) { - return pass(`refused with ${res.status} ${res.error ?? ""}`); - } - return fail( - `unexpected ${res.status} for a tokenless credential request`, - res.json, - ); + if (res.status === 200) return fail("issued a credential for an unknown space"); + return res.error === "SpaceNotFound" + ? pass("refused with SpaceNotFound") + : fail(`refused with ${describe(res)}, expected SpaceNotFound`, res.json); }, }); @@ -112,7 +171,7 @@ const requestInvalidSpaceUri = defineCheck({ id: "request.invalid-space-uri-rejected", title: "A malformed space reference is rejected, not misread", tier: "must", - citations: [{ source: "lexicon", ref: "com.atproto.space.getLatestCommit" }], + citations: [lexicon("com.atproto.space.getLatestCommit")], needs: [], async run(ctx) { const res = await xrpcGet(ctx, "com.atproto.space.getLatestCommit", { @@ -120,20 +179,19 @@ const requestInvalidSpaceUri = defineCheck({ repo: ctx.target.did, }); if (res.status >= 400 && res.status < 500) { - return pass(`rejected with ${res.status} ${res.error ?? ""}`); + return pass(`rejected with ${describe(res)}`); } - return fail( - `did not reject a malformed space uri (${res.status})`, - res.json, - ); + return fail(`did not reject a malformed space uri (${res.status})`, res.json); }, }); /** Checks that need no crypto and no session — safe in any transport. */ export const baseChecks: Check[] = [ - discoveryServiceEntry, - discoveryVerificationKey, + discoveryPdsService, + discoverySigningKey, + discoveryKemKey, + discoveryLegacyEntries, authGetRecordRequiresAuth, - authCredentialRequiresToken, + credentialTokenlessUnknown, requestInvalidSpaceUri, ]; diff --git a/packages/space-conformance/src/checks/credential.ts b/packages/space-conformance/src/checks/credential.ts new file mode 100644 index 0000000..68e7ae5 --- /dev/null +++ b/packages/space-conformance/src/checks/credential.ts @@ -0,0 +1,724 @@ +/** + * Space credentials, operator-side: issuance (tokenless for public-read + * spaces, via the target's own delegation tokens otherwise), the refusals + * getSpaceCredential declares, and presentation — the HTTP message + * signature, the audience binding and the MAC request every credentialed + * read of a commit or record must carry. + * + * All browser-safe: credential keys, signatures and KEM key shares are + * WebCrypto (see ../space-auth.ts). Verifying the MACs that come back + * needs the reference library and lives in ../full/checks.ts. + */ + +import { defineCheck } from "../registry.js"; +import { asOperator, xrpcGet } from "../http.js"; +import { fail, pass, type Check, type CheckContext } from "../model.js"; +import { decodeJwt, rawCid, toBase64Url, utf8 } from "../encoding.js"; +import { + COMMIT_MAC_TYPE, + MAC_HEADER, + RECORD_MAC_TYPE, + createCredentialKey, + formatWantMacHeader, + formatDidKey, +} from "../space-auth.js"; +import { + FOREIGN_DID, + POST, + createProbeSpace, + credentialCall, + credentialGet, + deleteProbeSpace, + describe, + memberspace, + mustCreateRecord, + obtainCredentialViaDelegation, + obtainPublicCredential, + personalspace, + publicRead, + requestCredential, + type Credential, + type CredentialCallOptions, + type ProbeSpace, +} from "./probe.js"; +import { fakeDid } from "./space.js"; + +const L = (ref: string) => ({ source: "lexicon" as const, ref }); +const C = (ref: string) => ({ source: "changeset" as const, ref }); + +/** A public-read probe space holding one record, plus a tokenless credential for it. */ +async function withPublicSpace( + ctx: CheckContext, + fn: (space: ProbeSpace, credential: Credential) => Promise, +): Promise { + const space = await createProbeSpace(ctx, publicRead()); + try { + await mustCreateRecord(ctx, space.uri, "shared", "visible"); + const credential = await obtainPublicCredential(ctx, space.uri); + return await fn(space, credential); + } finally { + await deleteProbeSpace(ctx, space.uri); + } +} + +const recordParams = (ctx: CheckContext, space: string) => ({ + space, + repo: ctx.target.did, + collection: POST, + rkey: "shared", +}); + +/** Read the shared record with a credential, varying one aspect of presentation. */ +const readShared = ( + ctx: CheckContext, + credential: Credential, + space: string, + opts: Omit = {}, +) => + credentialCall(ctx, credential, "com.atproto.space.getRecord", { + ...opts, + params: recordParams(ctx, space), + }); + +// --- issuance ---------------------------------------------------------- + +const credentialTokenlessPolicies = defineCheck({ + id: "credential.tokenless-by-policy", + title: "Without a delegation token only a public-read space issues; others answer SpaceNotFound", + tier: "must", + citations: [ + L("com.atproto.space.getSpaceCredential"), + L("com.atproto.space.getSpaceCredential@error:SpaceNotFound"), + L("com.atproto.memberspace.policy"), + L("com.atproto.personalspace.policy"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + const open = await createProbeSpace(ctx, publicRead()); + const closed = await createProbeSpace(ctx, memberspace()); + const personal = await createProbeSpace(ctx, personalspace()); + try { + const a = await requestCredential(ctx, open.uri); + if (!a.credential) return fail(`public-read space refused a tokenless request: ${describe(a.result)}`, a.result.json); + const misses: string[] = []; + for (const [label, space] of [["memberspace", closed], ["personalspace", personal]] as const) { + const res = await requestCredential(ctx, space.uri); + if (res.result.error !== "SpaceNotFound") misses.push(`${label} → ${describe(res.result)}`); + } + return misses.length + ? fail(`expected SpaceNotFound: ${misses.join("; ")}`) + : pass("public-read issued; closed memberspace and personalspace answered SpaceNotFound"); + } finally { + for (const s of [open, closed, personal]) await deleteProbeSpace(ctx, s.uri); + } + }, +}); + +const credentialClaims = defineCheck({ + id: "credential.claims", + title: "A credential is signed by the authority for the space, bound to the requested key", + tier: "must", + citations: [ + L("com.atproto.space.getSpaceCredential"), + C("funky-dryers-draw"), + C("plain-keys-resolve"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, publicRead()); + try { + const credential = await obtainPublicCredential(ctx, space.uri); + const { header, payload } = decodeJwt(credential.credential); + const cnf = payload.cnf as { kid?: unknown } | undefined; + const problems: string[] = []; + if (header.typ !== "atproto-space-credential+jwt") problems.push(`typ ${String(header.typ)}`); + if (header.kid !== "#atproto") problems.push(`kid ${String(header.kid)}`); + if (payload.iss !== ctx.target.did) problems.push(`iss ${String(payload.iss)}`); + if (payload.sub !== space.uri) problems.push(`sub ${String(payload.sub)}`); + if (cnf?.kid !== credential.key.did) problems.push(`cnf.kid ${String(cnf?.kid)}`); + // Credentials carry no audience: each use is bound to one by its + // HTTP signature instead. + if ("aud" in payload) problems.push(`has aud ${String(payload.aud)}`); + if (typeof payload.jti !== "string" || !payload.jti) problems.push("no jti"); + const iat = Number(payload.iat); + const exp = Number(payload.exp); + if (!(exp > iat) || exp - iat > 3600) problems.push(`lifetime ${exp - iat}s (max 3600)`); + return problems.length + ? fail(`credential claims: ${problems.join(", ")}`, { header, payload }) + : pass(`typ/kid/iss/sub/cnf correct, no aud, ${exp - iat}s lifetime`); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const credentialDefaultLifetime = defineCheck({ + id: "credential.default-lifetime", + title: "Credentials live 600 seconds, the reference default", + tier: "should", + citations: [{ source: "reference", ref: "@atproto/space SPACE_TOKEN_TYPES.credential.expiresInSec" }], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, publicRead()); + try { + const { payload } = decodeJwt((await obtainPublicCredential(ctx, space.uri)).credential); + const lifetime = Number(payload.exp) - Number(payload.iat); + return lifetime === 600 ? pass("600s") : fail(`${lifetime}s`); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const credentialKidP256 = defineCheck({ + id: "credential.kid-must-be-p256", + title: "getSpaceCredential refuses a credentialKid that is not a P-256 did:key", + tier: "must", + citations: [L("com.atproto.space.getSpaceCredential")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, publicRead()); + try { + // A well-formed secp256k1 did:key: valid syntax, wrong curve. The + // credential could never be presented — HTTP signatures are P-256. + const k256 = formatDidKey("ES256K", new Uint8Array([0x02, ...crypto.getRandomValues(new Uint8Array(32))])); + const bad = await requestCredential(ctx, space.uri, { credentialKid: k256 }); + if (bad.credential) return fail("issued a credential bound to a secp256k1 key"); + const notKey = await requestCredential(ctx, space.uri, { credentialKid: ctx.target.did }); + if (notKey.credential) return fail("issued a credential bound to a non-key DID"); + const good = await requestCredential(ctx, space.uri); + return good.credential + ? pass(`refused secp256k1 (${describe(bad.result)}) and non-key (${describe(notKey.result)}) kids; P-256 issued`) + : fail(`positive control failed: ${describe(good.result)}`, good.result.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const credentialGarbageDelegation = defineCheck({ + id: "credential.garbage-delegation-refused", + title: "A malformed delegation token is refused with InvalidDelegationToken", + tier: "must", + citations: [L("com.atproto.space.getSpaceCredential@error:InvalidDelegationToken")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, memberspace()); + try { + const res = await requestCredential(ctx, space.uri, { delegationToken: "not.a.token" }); + if (res.credential) return fail("issued a credential for a garbage delegation token"); + return res.result.error === "InvalidDelegationToken" + ? pass("refused with InvalidDelegationToken") + : fail(`refused with ${describe(res.result)}, expected InvalidDelegationToken`, res.result.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +/** + * A structurally valid client attestation for a client nobody can resolve: + * typed, addressed to the space host, iss = sub = an unresolvable + * client_id, signed by a throwaway key. Only verification can refuse it. + */ +async function unverifiableAttestation(authority: string): Promise { + const clientId = "https://app.space-conformance.invalid/client-metadata.json"; + const key = await createCredentialKey(); + const iat = Math.floor(Date.now() / 1000); + const part = (obj: unknown) => toBase64Url(utf8(JSON.stringify(obj))); + const input = `${part({ alg: "ES256", typ: "atproto-client-attestation+jwt" })}.${part({ + iss: clientId, + sub: clientId, + aud: `${authority}#atproto_pds`, + iat, + exp: iat + 60, + jti: toBase64Url(crypto.getRandomValues(new Uint8Array(16))), + })}`; + return `${input}.${toBase64Url(await key.sign(utf8(input)))}`; +} + +const attestationCitations = [L("com.atproto.space.getSpaceCredential@error:InvalidClientAttestation")]; + +const credentialUnverifiableAttestation = defineCheck({ + id: "credential.unverifiable-attestation-refused", + title: "A client attestation that cannot be verified is refused with InvalidClientAttestation", + tier: "must", + citations: attestationCitations, + needs: ["operator"], + destructive: true, + async run(ctx) { + // A public-read space would issue without it, so the refusal can only + // be the attestation's. + const space = await createProbeSpace(ctx, publicRead()); + try { + const res = await requestCredential(ctx, space.uri, { + clientAttestation: await unverifiableAttestation(ctx.target.did), + }); + if (res.credential) return fail("issued a credential on an unverifiable client attestation"); + return res.result.error === "InvalidClientAttestation" + ? pass("refused with InvalidClientAttestation") + : fail(`refused with ${describe(res.result)}, expected InvalidClientAttestation`, res.result.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const credentialGarbageAttestation = defineCheck({ + id: "credential.garbage-attestation-refused", + title: "A malformed client attestation is refused with InvalidClientAttestation", + tier: "must", + citations: attestationCitations, + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, publicRead()); + try { + const res = await requestCredential(ctx, space.uri, { clientAttestation: "not.an.attestation" }); + if (res.credential) return fail("issued a credential despite a garbage client attestation"); + return res.result.error === "InvalidClientAttestation" + ? pass("refused with InvalidClientAttestation") + : fail(`refused with ${describe(res.result)}, expected InvalidClientAttestation`, res.result.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const credentialAllowedApps = defineCheck({ + id: "credential.allowed-apps-gate", + title: "A memberspace with allowedApps refuses an unattested app with AppNotAuthorized", + tier: "must", + citations: [ + L("com.atproto.space.getSpaceCredential@error:AppNotAuthorized"), + L("com.atproto.memberspace.policy"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + // publicRead clears the user perimeter (checked first), so only the + // app perimeter is left to refuse. + const space = await createProbeSpace( + ctx, + memberspace({ publicRead: true, allowedApps: ["https://app.space-conformance.invalid/client-metadata.json"] }), + ); + try { + const res = await requestCredential(ctx, space.uri); + if (res.credential) return fail("issued a credential to an app outside allowedApps"); + return res.result.error === "AppNotAuthorized" + ? pass("refused with AppNotAuthorized") + : fail(`refused with ${describe(res.result)}, expected AppNotAuthorized`, res.result.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const credentialDeletedSpace = defineCheck({ + id: "credential.deleted-space", + title: "After deleteSpace, getSpaceCredential answers SpaceDeleted", + tier: "must", + citations: [ + L("com.atproto.space.deleteSpace"), + L("com.atproto.space.getSpaceCredential@error:SpaceDeleted"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, publicRead()); + // Positive control, so a target that never issues cannot pass. + const before = await requestCredential(ctx, space.uri); + if (!before.credential) { + await deleteProbeSpace(ctx, space.uri); + return fail(`could not obtain a credential before deletion (${describe(before.result)})`); + } + await deleteProbeSpace(ctx, space.uri); + const after = await requestCredential(ctx, space.uri); + if (after.credential) return fail("a deleted space still issued a credential"); + // The durable tombstone: a syncer that missed notifySpaceDeleted learns + // it here on renewal — tokenless, as a public space's syncer would ask. + return after.result.error === "SpaceDeleted" + ? pass("answered SpaceDeleted") + : fail(`answered ${describe(after.result)}, expected SpaceDeleted`, after.result.json); + }, +}); + +// --- delegation (the target's own tokens) -------------------------------- + +const credentialSelfRoundTrip = defineCheck({ + id: "credential.self-round-trip", + title: "Operator obtains a credential via getDelegationToken and reads with it", + tier: "must", + citations: [ + L("com.atproto.space.getDelegationToken"), + L("com.atproto.space.getSpaceCredential"), + L("com.atproto.space.getRecord"), + ], + needs: ["operator", "pds-delegation"], + destructive: true, + async run(ctx) { + // A closed memberspace: only the delegation token can get the operator in. + const space = await createProbeSpace(ctx, memberspace()); + try { + await mustCreateRecord(ctx, space.uri, "shared", "mine"); + const { result, credential, delegation } = await obtainCredentialViaDelegation(ctx, space.uri); + if (delegation.status !== 200) return fail(`getDelegationToken ${describe(delegation)}`, delegation.json); + if (!credential) return fail(`getSpaceCredential ${describe(result)}`, result.json); + const read = await readShared(ctx, credential, space.uri); + if (read.status !== 200) return fail(`credential read failed: ${describe(read)}`, read.json); + return read.headers.get(MAC_HEADER) + ? pass("delegation → credential → MAC'd read works") + : fail("the credentialed read carried no Atproto-Space-Mac header"); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const delegationClaims = defineCheck({ + id: "delegation.token-claims", + title: "getDelegationToken mints a token for the space's #atproto_pds, signed by #atproto", + tier: "must", + citations: [L("com.atproto.space.getDelegationToken"), C("plain-keys-resolve")], + needs: ["operator", "pds-delegation"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, memberspace()); + try { + const res = await xrpcGet(asOperator(ctx), "com.atproto.space.getDelegationToken", { space: space.uri }); + if (res.status !== 200) return fail(`getDelegationToken ${describe(res)}`, res.json); + const { header, payload } = decodeJwt((res.json as { token: string }).token); + const problems: string[] = []; + if (header.typ !== "atproto-space-delegation+jwt") problems.push(`typ ${String(header.typ)}`); + if (header.kid !== "#atproto") problems.push(`kid ${String(header.kid)}`); + if (payload.iss !== ctx.target.did) problems.push(`iss ${String(payload.iss)}`); + if (payload.sub !== space.uri) problems.push(`sub ${String(payload.sub)}`); + if (payload.aud !== `${ctx.target.did}#atproto_pds`) problems.push(`aud ${String(payload.aud)}`); + if (typeof payload.jti !== "string" || !payload.jti) problems.push("no jti"); + if (!(Number(payload.exp) > Math.floor(Date.now() / 1000) - 5)) problems.push("already expired"); + return problems.length + ? fail(`delegation token: ${problems.join(", ")}`, { header, payload }) + : pass("typ/kid/iss/sub/aud as specified"); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const delegationReplay = defineCheck({ + id: "delegation.replay-refused", + title: "A delegation token cannot be used twice", + tier: "must", + citations: [L("com.atproto.space.getSpaceCredential@error:InvalidDelegationToken")], + needs: ["operator", "pds-delegation"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, memberspace()); + try { + const res = await xrpcGet(asOperator(ctx), "com.atproto.space.getDelegationToken", { space: space.uri }); + if (res.status !== 200) return fail(`getDelegationToken ${describe(res)}`, res.json); + const delegationToken = (res.json as { token: string }).token; + const first = await requestCredential(ctx, space.uri, { delegationToken }); + if (!first.credential) return fail(`first exchange failed (${describe(first.result)}); cannot test replay`); + const second = await requestCredential(ctx, space.uri, { delegationToken }); + if (second.credential) return fail("a replayed delegation token was accepted"); + return second.result.error === "InvalidDelegationToken" + ? pass("replay refused with InvalidDelegationToken") + : fail(`replay refused with ${describe(second.result)}, expected InvalidDelegationToken`); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const delegationWrongSpace = defineCheck({ + id: "delegation.wrong-space-refused", + title: "A delegation token for one space is refused for another", + tier: "must", + citations: [L("com.atproto.space.getSpaceCredential@error:InvalidDelegationToken")], + needs: ["operator", "pds-delegation"], + destructive: true, + async run(ctx) { + const a = await createProbeSpace(ctx, memberspace()); + const b = await createProbeSpace(ctx, memberspace()); + try { + const res = await xrpcGet(asOperator(ctx), "com.atproto.space.getDelegationToken", { space: a.uri }); + if (res.status !== 200) return fail(`getDelegationToken ${describe(res)}`, res.json); + const cross = await requestCredential(ctx, b.uri, { delegationToken: (res.json as { token: string }).token }); + if (cross.credential) return fail("a token for space A issued a credential for space B"); + return cross.result.error === "InvalidDelegationToken" + ? pass("refused with InvalidDelegationToken") + : fail(`refused with ${describe(cross.result)}, expected InvalidDelegationToken`); + } finally { + await deleteProbeSpace(ctx, a.uri); + await deleteProbeSpace(ctx, b.uri); + } + }, +}); + +// --- presentation ----------------------------------------------------- + +const presentationCitations = [ + L("com.atproto.space.getRecord"), + L("com.atproto.space.listRepos"), + C("funky-dryers-draw"), + C("open-spaces-greet"), +]; + +const credentialSignatureRequired = defineCheck({ + id: "credential.signature-required", + title: "A credential presented without its HTTP signature is refused", + tier: "must", + citations: presentationCitations, + needs: ["operator"], + destructive: true, + async run(ctx) { + return withPublicSpace(ctx, async (space, credential) => { + const ok = await readShared(ctx, credential, space.uri); + if (ok.status !== 200) return fail(`positive control failed: ${describe(ok)}`, ok.json); + const bare = await readShared(ctx, credential, space.uri, { unsigned: true }); + return bare.status >= 400 && bare.status < 500 + ? pass(`signed read 200; unsigned read refused (${describe(bare)})`) + : fail(`an unsigned credential read returned ${describe(bare)}`, bare.json); + }); + }, +}); + +const credentialAudienceBound = defineCheck({ + id: "credential.audience-bound", + title: "A credential signed for another audience is refused", + tier: "must", + citations: presentationCitations, + needs: ["operator"], + destructive: true, + async run(ctx) { + // The audience is the service being called; a signature over some + // other DID is a request meant for someone else, replayed here. + return withPublicSpace(ctx, async (space, credential) => { + const ok = await readShared(ctx, credential, space.uri); + if (ok.status !== 200) return fail(`positive control failed: ${describe(ok)}`, ok.json); + const misaddressed = await readShared(ctx, credential, space.uri, { audience: FOREIGN_DID }); + if (misaddressed.status < 400 || misaddressed.status >= 500) { + return fail(`a misaddressed repo-host read returned ${describe(misaddressed)}`, misaddressed.json); + } + // The same at the space host, whose audience is the authority. + const listRepos = (audience: string) => + credentialCall(ctx, credential, "com.atproto.space.listRepos", { + params: { space: space.uri }, + audience, + }); + const hostOk = await listRepos(ctx.target.did); + if (hostOk.status !== 200) return fail(`listRepos positive control failed: ${describe(hostOk)}`, hostOk.json); + const hostWrong = await listRepos(FOREIGN_DID); + return hostWrong.status >= 400 && hostWrong.status < 500 + ? pass(`refused signatures over another audience at the repo host (${describe(misaddressed)}) and space host (${describe(hostWrong)})`) + : fail(`a misaddressed listRepos returned ${describe(hostWrong)}`, hostWrong.json); + }); + }, +}); + +const credentialWrongKey = defineCheck({ + id: "credential.wrong-key-refused", + title: "A credential signed by a key other than its cnf.kid is refused", + tier: "must", + citations: presentationCitations, + needs: ["operator"], + destructive: true, + async run(ctx) { + return withPublicSpace(ctx, async (space, credential) => { + const ok = await readShared(ctx, credential, space.uri); + if (ok.status !== 200) return fail(`positive control failed: ${describe(ok)}`, ok.json); + const thief = await readShared(ctx, credential, space.uri, { signWith: await createCredentialKey() }); + return thief.status >= 400 && thief.status < 500 + ? pass(`refused a signature by the wrong key (${describe(thief)})`) + : fail(`a credential signed by a stranger's key returned ${describe(thief)}`, thief.json); + }); + }, +}); + +const credentialSchemeCase = defineCheck({ + id: "credential.scheme-case-insensitive", + title: "The Atproto-Space-Credential scheme is recognised regardless of case", + tier: "must", + citations: [C("open-spaces-greet"), L("com.atproto.space.getRecord")], + needs: ["operator"], + destructive: true, + async run(ctx) { + return withPublicSpace(ctx, async (space, credential) => { + const lower = await readShared(ctx, credential, space.uri, { scheme: "atproto-space-credential" }); + return lower.status === 200 + ? pass("a lowercase scheme was accepted") + : fail(`a lowercase scheme returned ${describe(lower)}`, lower.json); + }); + }, +}); + +const credentialCrossSpace = defineCheck({ + id: "credential.cross-space-refused", + title: "A credential for one space cannot read another", + tier: "must", + citations: [L("com.atproto.space.getRecord")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const other = await createProbeSpace(ctx, publicRead()); + try { + await mustCreateRecord(ctx, other.uri, "shared", "b"); + return await withPublicSpace(ctx, async (space, credential) => { + const ok = await readShared(ctx, credential, space.uri); + if (ok.status !== 200) return fail(`positive control failed: ${describe(ok)}`, ok.json); + const cross = await readShared(ctx, credential, other.uri); + return cross.status === 200 + ? fail("a space-A credential read space B", cross.json) + : pass(`cross-space read refused (${describe(cross)})`); + }); + } finally { + await deleteProbeSpace(ctx, other.uri); + } + }, +}); + +const credentialUnhostedRepo = defineCheck({ + id: "credential.unhosted-repo-not-found", + title: "Credentialed reads of a repo the host does not hold answer RepoNotFound", + tier: "must", + citations: [ + L("com.atproto.space.getRecord@error:RepoNotFound"), + L("com.atproto.space.getLatestCommit@error:RepoNotFound"), + L("com.atproto.space.getRepo@error:RepoNotFound"), + L("com.atproto.space.listRecords@error:RepoNotFound"), + L("com.atproto.space.listRepoOps@error:RepoNotFound"), + L("com.atproto.space.listBlobs@error:RepoNotFound"), + L("com.atproto.space.getBlob@error:RepoNotFound"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + return withPublicSpace(ctx, async (space, credential) => { + // A DID no host serves. Its KEM key can't be resolved, so the MAC + // request carries a well-formed but unanswerable key share — the + // host must find no repo before it could use one. + const repo = fakeDid(); + const share = (await createCredentialKey()).did; + const base = { space: space.uri, repo }; + const reads: Array<[string, Record, string | false]> = [ + ["getRecord", { ...base, collection: POST, rkey: "shared" }, formatWantMacHeader(RECORD_MAC_TYPE, share)], + ["getLatestCommit", base, formatWantMacHeader(COMMIT_MAC_TYPE, share)], + ["getRepo", base, formatWantMacHeader(COMMIT_MAC_TYPE, share)], + ["listRepoOps", base, formatWantMacHeader(COMMIT_MAC_TYPE, share)], + ["listRecords", base, false], + ["listBlobs", base, false], + ["getBlob", { ...base, cid: await rawCid(utf8("no such blob")) }, false], + ]; + const misses: string[] = []; + for (const [name, params, wantMac] of reads) { + const res = await credentialCall(ctx, credential, `com.atproto.space.${name}`, { params, wantMac }); + if (res.error !== "RepoNotFound") misses.push(`${name} → ${describe(res)}`); + } + return misses.length + ? fail(`expected RepoNotFound: ${misses.join("; ")}`) + : pass("all seven reads answered RepoNotFound"); + }); + }, +}); + +const macWantRequired = defineCheck({ + id: "mac.want-mac-required", + title: "Credentialed reads of a commit or record without Atproto-Space-Want-Mac answer BadSpaceMac", + tier: "must", + citations: [ + L("com.atproto.space.getLatestCommit@error:BadSpaceMac"), + L("com.atproto.space.getRecord@error:BadSpaceMac"), + L("com.atproto.space.getRepo@error:BadSpaceMac"), + L("com.atproto.space.listRepoOps@error:BadSpaceMac"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + return withPublicSpace(ctx, async (space, credential) => { + const base = { space: space.uri, repo: ctx.target.did }; + const reads: Array<[string, Record]> = [ + ["getLatestCommit", base], + ["getRecord", recordParams(ctx, space.uri)], + ["getRepo", base], + ["listRepoOps", base], + ]; + const misses: string[] = []; + for (const [name, params] of reads) { + const nsid = `com.atproto.space.${name}`; + // Positive control per method: with the header it is served. + const ok = await credentialGet(ctx, credential, nsid, params); + if (ok.status !== 200) { + misses.push(`${name} with a MAC request → ${describe(ok)}`); + continue; + } + const res = await credentialCall(ctx, credential, nsid, { params, wantMac: false }); + if (res.error !== "BadSpaceMac") misses.push(`${name} without → ${describe(res)}`); + } + return misses.length + ? fail(misses.join("; ")) + : pass("each served with a MAC request and answered BadSpaceMac without one"); + }); + }, +}); + +const macMalformed = defineCheck({ + id: "mac.malformed-want-mac-rejected", + title: "A malformed or mistyped Atproto-Space-Want-Mac answers BadSpaceMac", + tier: "must", + citations: [ + L("com.atproto.space.getLatestCommit@error:BadSpaceMac"), + L("com.atproto.space.getRecord@error:BadSpaceMac"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + return withPublicSpace(ctx, async (space, credential) => { + const share = (await createCredentialKey()).did; + const commit = { space: space.uri, repo: ctx.target.did }; + const probes: Array<[string, string, Record, string]> = [ + ["bad key share", "getLatestCommit", commit, `type="${COMMIT_MAC_TYPE}", ver=1, key_share="did:key:zNotAKey"`], + ["unsupported version", "getLatestCommit", commit, `type="${COMMIT_MAC_TYPE}", ver=99, key_share="${share}"`], + ["record read asking for a commit MAC", "getRecord", recordParams(ctx, space.uri), formatWantMacHeader(COMMIT_MAC_TYPE, share)], + ["not a structured header", "getRecord", recordParams(ctx, space.uri), "please"], + ]; + const misses: string[] = []; + for (const [label, name, params, header] of probes) { + const res = await credentialCall(ctx, credential, `com.atproto.space.${name}`, { params, wantMac: header }); + if (res.error !== "BadSpaceMac") misses.push(`${label} → ${describe(res)}`); + } + return misses.length + ? fail(`expected BadSpaceMac: ${misses.join("; ")}`) + : pass("every malformed MAC request answered BadSpaceMac"); + }); + }, +}); + +export const credentialChecks: Check[] = [ + credentialTokenlessPolicies, + credentialClaims, + credentialDefaultLifetime, + credentialKidP256, + credentialGarbageDelegation, + credentialUnverifiableAttestation, + credentialGarbageAttestation, + credentialAllowedApps, + credentialDeletedSpace, + credentialSelfRoundTrip, + delegationClaims, + delegationReplay, + delegationWrongSpace, + credentialSignatureRequired, + credentialAudienceBound, + credentialWrongKey, + credentialSchemeCase, + credentialCrossSpace, + credentialUnhostedRepo, + macWantRequired, + macMalformed, +]; diff --git a/packages/space-conformance/src/checks/host.ts b/packages/space-conformance/src/checks/host.ts new file mode 100644 index 0000000..4ee0ede --- /dev/null +++ b/packages/space-conformance/src/checks/host.ts @@ -0,0 +1,372 @@ +/** + * The space-host role: the writer set (listRepos, removeWriter) and + * notification registration (registerNotify / unregisterNotify), plus — + * when the harness runs a syncer inbox — the notifications the host sends. + * Browser-safe; the inbox checks need a harness that can receive them. + */ + +import { defineCheck } from "../registry.js"; +import { asOperator, xrpcGet, xrpcPost } from "../http.js"; +import { fail, pass, type Check, type CheckContext, type InboxDelivery } from "../model.js"; +import { bytesEqual, isTid, lexBytes } from "../encoding.js"; +import { + FOREIGN_DID, + createProbeSpace, + credentialCall, + deleteProbeSpace, + describe, + mustCreateRecord, + obtainPublicCredential, + publicRead, + type Credential, +} from "./probe.js"; +import { fakeDid } from "./space.js"; + +const L = (ref: string) => ({ source: "lexicon" as const, ref }); + +interface WriterEntry { + did: string; + repoRev: unknown; + data: unknown; + spaceRev: unknown; +} + +async function listRepos( + ctx: CheckContext, + credential: Credential, + params: Record = {}, +) { + const res = await credentialCall(ctx, credential, "com.atproto.space.listRepos", { + params: { space: credential.space, ...params }, + audience: ctx.target.did, + }); + const body = res.json as { repos?: WriterEntry[]; cursor?: string } | undefined; + return { res, repos: body?.repos ?? [], cursor: body?.cursor }; +} + +const hostRequiresCredential = defineCheck({ + id: "host.listrepos-requires-credential", + title: "listRepos, registerNotify and unregisterNotify refuse an unauthenticated caller", + tier: "must", + citations: [ + L("com.atproto.space.listRepos"), + L("com.atproto.space.registerNotify"), + L("com.atproto.space.unregisterNotify"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, publicRead()); + try { + const probes = [ + ["listRepos", await xrpcGet(ctx, "com.atproto.space.listRepos", { space: space.uri })], + ["registerNotify", await xrpcPost(ctx, "com.atproto.space.registerNotify", { space: space.uri, service: ctx.target.did })], + ["unregisterNotify", await xrpcPost(ctx, "com.atproto.space.unregisterNotify", { space: space.uri, service: ctx.target.did })], + ] as const; + const served = probes.filter(([, r]) => r.status !== 401 && r.status !== 403); + return served.length + ? fail(`not refused with 401/403: ${served.map(([n, r]) => `${n} → ${describe(r)}`).join("; ")}`) + : pass("all three refused an unauthenticated caller"); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const listReposShape = defineCheck({ + id: "sync.listrepos-shape", + title: "listRepos lists writers by ascending spaceRev with a spaceRev cursor", + tier: "must", + citations: [L("com.atproto.space.listRepos")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, publicRead()); + try { + await mustCreateRecord(ctx, space.uri, "a"); + await mustCreateRecord(ctx, space.uri, "b"); + const credential = await obtainPublicCredential(ctx, space.uri); + const page = await listRepos(ctx, credential); + if (page.res.status !== 200) return fail(`listRepos ${describe(page.res)}`, page.res.json); + const problems: string[] = []; + for (const repo of page.repos) { + const data = lexBytes(repo.data); + if (!isTid(repo.repoRev)) problems.push(`${repo.did} repoRev ${String(repo.repoRev)}`); + if (!isTid(repo.spaceRev)) problems.push(`${repo.did} spaceRev ${String(repo.spaceRev)}`); + if (!data || data.length !== 32) problems.push(`${repo.did} data is not 32 bytes`); + } + const revs = page.repos.map((r) => String(r.spaceRev)); + if (revs.some((rev, i) => i > 0 && rev <= revs[i - 1]!)) problems.push(`not ascending: ${revs.join(",")}`); + if (!page.repos.some((r) => r.did === ctx.target.did)) problems.push("the authority's own repo is not listed"); + if (page.repos.length && page.cursor !== revs.at(-1)) { + problems.push(`cursor ${page.cursor} is not the last spaceRev ${revs.at(-1)}`); + } + if (problems.length) return fail(problems.join("; "), page.res.json); + // Resuming from the cursor reaches an empty page, which carries no cursor. + const next = await listRepos(ctx, credential, { cursor: page.cursor! }); + if (next.res.status !== 200) return fail(`listRepos(cursor) ${describe(next.res)}`, next.res.json); + return next.repos.length === 0 && next.cursor === undefined + ? pass(`${page.repos.length} writer(s), ascending, cursor resumes to an empty page`) + : fail(`after the last cursor: ${next.repos.length} repo(s), cursor ${next.cursor}`, next.res.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const listReposReflects = defineCheck({ + id: "sync.listrepos-reflects-writes", + title: "The authority's listRepos entry matches its latest commit", + tier: "should", + citations: [ + { source: "reference", ref: "authority repo notifies its own space host synchronously" }, + L("com.atproto.space.listRepos"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + // The lexicon allows the entry to lag ("as last reported"), so this is + // calibrated against the reference, which notifies its own host on + // commit. + const space = await createProbeSpace(ctx, publicRead()); + try { + await mustCreateRecord(ctx, space.uri, "a"); + const credential = await obtainPublicCredential(ctx, space.uri); + const { repos } = await listRepos(ctx, credential); + const mine = repos.find((r) => r.did === ctx.target.did); + const latest = await xrpcGet(asOperator(ctx), "com.atproto.space.getLatestCommit", { + space: space.uri, + repo: ctx.target.did, + }); + const commit = (latest.json as { commit?: { rev?: string; data?: unknown } } | undefined)?.commit; + const a = lexBytes(mine?.data); + const b = lexBytes(commit?.data); + return mine && commit && mine.repoRev === commit.rev && a && b && bytesEqual(a, b) + ? pass("repoRev and data match getLatestCommit") + : fail("listRepos entry differs from the latest commit", { listed: mine, commit }); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const removeWriter = defineCheck({ + id: "host.removewriter", + title: "removeWriter drops a repo from listRepos until it writes again", + tier: "must", + citations: [L("com.atproto.space.removeWriter"), L("com.atproto.space.listRepos")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, publicRead()); + const remove = (did: string) => + xrpcPost(asOperator(ctx), "com.atproto.space.removeWriter", { space: space.uri, did }); + try { + await mustCreateRecord(ctx, space.uri, "a"); + const credential = await obtainPublicCredential(ctx, space.uri); + const listed = async () => (await listRepos(ctx, credential)).repos.some((r) => r.did === ctx.target.did); + if (!(await listed())) return fail("the authority's repo was not in the writer set to begin with"); + const removed = await remove(ctx.target.did); + if (removed.status !== 200) return fail(`removeWriter ${describe(removed)}`, removed.json); + if (await listed()) return fail("removeWriter left the repo in listRepos"); + // Idempotent: removing an account that isn't a writer succeeds. + const absent = await remove(fakeDid()); + if (absent.status !== 200) return fail(`removeWriter of a non-writer returned ${describe(absent)}`, absent.json); + await mustCreateRecord(ctx, space.uri, "b"); + return (await listed()) + ? pass("removed, idempotent for a non-writer, and tracked again after a new write") + : fail("a new write by an authorised account did not return it to the writer set"); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const registerRoundTrip = defineCheck({ + id: "host.registernotify-round-trip", + title: "registerNotify returns a future expiry; unregisterNotify is idempotent", + tier: "must", + citations: [L("com.atproto.space.registerNotify"), L("com.atproto.space.unregisterNotify")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, publicRead()); + try { + const credential = await obtainPublicCredential(ctx, space.uri); + // A bare DID names an account, served by its #atproto_pds — the + // target's own DID is the one service identifier sure to resolve. + const call = (nsid: string) => + credentialCall(ctx, credential, nsid, { + body: { space: space.uri, service: ctx.target.did }, + audience: ctx.target.did, + }); + const reg = await call("com.atproto.space.registerNotify"); + if (reg.status !== 200) return fail(`registerNotify ${describe(reg)}`, reg.json); + const expiresAt = Date.parse(String((reg.json as { expiresAt?: unknown }).expiresAt)); + if (!(expiresAt > Date.now())) return fail("expiresAt is not a future datetime", reg.json); + const un1 = await call("com.atproto.space.unregisterNotify"); + const un2 = await call("com.atproto.space.unregisterNotify"); + return un1.status === 200 && un2.status === 200 + ? pass("registered with a future expiry; unregistered twice") + : fail(`unregisterNotify returned ${describe(un1)} then ${describe(un2)}`, { first: un1.json, second: un2.json }); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const registerUnresolvable = defineCheck({ + id: "host.registernotify-unresolvable", + title: "registerNotify for a service that does not resolve answers ServiceNotResolvable", + tier: "must", + citations: [L("com.atproto.space.registerNotify@error:ServiceNotResolvable")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, publicRead()); + try { + const credential = await obtainPublicCredential(ctx, space.uri); + const res = await credentialCall(ctx, credential, "com.atproto.space.registerNotify", { + body: { space: space.uri, service: `${FOREIGN_DID}#space_syncer` }, + audience: ctx.target.did, + }); + return res.error === "ServiceNotResolvable" + ? pass("answered ServiceNotResolvable") + : fail(`answered ${describe(res)}, expected ServiceNotResolvable`, res.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const hostAfterDelete = defineCheck({ + id: "host.deleted-space-not-found", + title: "Space-host methods on a deleted space answer SpaceNotFound", + tier: "must", + citations: [ + L("com.atproto.space.listRepos@error:SpaceNotFound"), + L("com.atproto.space.registerNotify@error:SpaceNotFound"), + L("com.atproto.space.unregisterNotify@error:SpaceNotFound"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + // A credential issued before deletion is still a well-formed, unexpired + // credential; what has gone is the space. + const space = await createProbeSpace(ctx, publicRead()); + const credential = await obtainPublicCredential(ctx, space.uri); + await deleteProbeSpace(ctx, space.uri); + const body = { space: space.uri, service: ctx.target.did }; + const probes = [ + ["listRepos", await listRepos(ctx, credential).then((r) => r.res)], + ["registerNotify", await credentialCall(ctx, credential, "com.atproto.space.registerNotify", { body, audience: ctx.target.did })], + ["unregisterNotify", await credentialCall(ctx, credential, "com.atproto.space.unregisterNotify", { body, audience: ctx.target.did })], + ] as const; + const misses = probes.filter(([, r]) => r.error !== "SpaceNotFound"); + return misses.length + ? fail(`expected SpaceNotFound: ${misses.map(([n, r]) => `${n} → ${describe(r)}`).join("; ")}`) + : pass("all three answered SpaceNotFound"); + }, +}); + +// --- deliveries to a harness syncer -------------------------------------- + +const NOTIFY_TIMEOUT_MS = 10_000; + +const forwardedNotifyWrite = defineCheck({ + id: "notify.forwarded-notifywrite", + title: "A registered syncer receives sequenced notifyWrite calls", + tier: "must", + citations: [L("com.atproto.space.notifyWrite"), L("com.atproto.space.registerNotify")], + needs: ["operator", "syncer-inbox"], + destructive: true, + async run(ctx) { + const inbox = ctx.syncerInbox!; + const space = await createProbeSpace(ctx, publicRead()); + try { + await mustCreateRecord(ctx, space.uri, "before"); + const credential = await obtainPublicCredential(ctx, space.uri); + const reg = await credentialCall(ctx, credential, "com.atproto.space.registerNotify", { + body: { space: space.uri, service: inbox.service }, + audience: ctx.target.did, + }); + if (reg.status !== 200) return fail(`registerNotify ${describe(reg)}`, reg.json); + const forThis = (d: InboxDelivery) => + d.lxm === "com.atproto.space.notifyWrite" && + (d.body as { space?: string } | undefined)?.space === space.uri; + const since = Date.now(); + await mustCreateRecord(ctx, space.uri, "one"); + const first = await inbox.waitFor((d) => forThis(d) && d.receivedAt >= since, NOTIFY_TIMEOUT_MS); + if (!first) return fail("no notifyWrite reached the syncer after a write"); + const a = first.body as Record; + await mustCreateRecord(ctx, space.uri, "two"); + const second = await inbox.waitFor( + (d) => forThis(d) && (d.body as { spaceRev?: string }).spaceRev !== a.spaceRev && d.receivedAt >= first.receivedAt, + NOTIFY_TIMEOUT_MS, + ); + if (!second) return fail("no notifyWrite reached the syncer after a second write"); + const b = second.body as Record; + const problems: string[] = []; + for (const [label, body] of [["first", a], ["second", b]] as const) { + if (body.repo !== ctx.target.did) problems.push(`${label} repo ${String(body.repo)}`); + if (!isTid(body.repoRev)) problems.push(`${label} repoRev ${String(body.repoRev)}`); + if (!isTid(body.spaceRev)) problems.push(`${label} has no spaceRev`); + if (lexBytes(body.data)?.length !== 32) problems.push(`${label} data is not 32 bytes`); + } + if (b.prevSpaceRev !== a.spaceRev) problems.push(`second prevSpaceRev ${String(b.prevSpaceRev)} ≠ first spaceRev ${String(a.spaceRev)}`); + if (!second.authorization?.startsWith("Bearer ")) problems.push("delivered without service auth"); + return problems.length + ? fail(problems.join("; "), { first: a, second: b }) + : pass("two sequenced deliveries; prevSpaceRev chains to the previous spaceRev"); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const spaceDeletedDelivered = defineCheck({ + id: "notify.space-deleted-delivered", + title: "A registered syncer is sent notifySpaceDeleted when the space is deleted", + tier: "must", + citations: [L("com.atproto.space.notifySpaceDeleted"), L("com.atproto.space.deleteSpace")], + needs: ["operator", "syncer-inbox"], + destructive: true, + async run(ctx) { + const inbox = ctx.syncerInbox!; + const space = await createProbeSpace(ctx, publicRead()); + let deleted = false; + try { + const credential = await obtainPublicCredential(ctx, space.uri); + const reg = await credentialCall(ctx, credential, "com.atproto.space.registerNotify", { + body: { space: space.uri, service: inbox.service }, + audience: ctx.target.did, + }); + if (reg.status !== 200) return fail(`registerNotify ${describe(reg)}`, reg.json); + await deleteProbeSpace(ctx, space.uri); + deleted = true; + const got = await inbox.waitFor( + (d) => + d.lxm === "com.atproto.space.notifySpaceDeleted" && + (d.body as { space?: string } | undefined)?.space === space.uri, + NOTIFY_TIMEOUT_MS, + ); + return got + ? pass("notifySpaceDeleted delivered") + : fail(`no notifySpaceDeleted within ${NOTIFY_TIMEOUT_MS / 1000}s`); + } finally { + if (!deleted) await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +export const hostChecks: Check[] = [ + hostRequiresCredential, + listReposShape, + listReposReflects, + removeWriter, + registerRoundTrip, + registerUnresolvable, + hostAfterDelete, + forwardedNotifyWrite, + spaceDeletedDelivered, +]; diff --git a/packages/space-conformance/src/checks/operator.ts b/packages/space-conformance/src/checks/operator.ts index f3fd836..13df004 100644 --- a/packages/space-conformance/src/checks/operator.ts +++ b/packages/space-conformance/src/checks/operator.ts @@ -2,849 +2,55 @@ * Operator checks: everything an authenticated session can prove with the * platform's own `fetch` and WebCrypto — no alpha crypto libs, no foreign * identities. They run wherever the base checks run, browsers included, as - * long as the harness supplies an `operator` capability (and, for the - * blob and credential checks, `pds-blobs` / `pds-delegation`). + * long as the harness supplies an `operator` capability (and, for some, + * `pds-blobs`, `pds-delegation` or a `syncer-inbox`). * * The split matters: checks live here or in `../full/checks.js` by what - * they *actually import*, not by topic. A check that only makes authed - * XRPC calls belongs here even if its subject is credentials — the - * operator's own delegation → credential → read flow needs nothing but an - * ES256 JWT the browser can mint. + * they *actually import*, not by topic. Presenting a space credential — + * a P-256 HTTP signature and a KEM key share — needs nothing a browser + * lacks, so every check that only presents one belongs here; verifying the + * MACs that come back needs the reference library, and lives there. */ -import { defineCheck } from "../registry.js"; -import { - asOperator, - operatorFetch, - xrpcGet, - xrpcPost, - type XrpcResult, -} from "../http.js"; -import { - fail, - pass, - type Check, - type CheckContext, - type DpopKey, -} from "../model.js"; -import { createDpopKey, createDpopProofJwt } from "../dpop.js"; -import { readCarHeader } from "../car.js"; - -// The probe collections and space type are published, resolvable -// lexicons under the suite's own authority (see ../../probe-lexicons) — -// so strict, dynamically-resolving targets can validate them, while -// AppViews ignore them (nothing under earth.cirrus.check.* is app.bsky.*). -export const POST = "earth.cirrus.check.note"; -export const note = (text: string) => ({ $type: POST, text }); - -const PROBE_TYPE = "earth.cirrus.check.space"; - -export interface ProbeSpace { - uri: string; - type: string; - skey: string; -} - -/** A run-unique skey so probe spaces never collide with real ones. */ -function probeSkey(): string { - const rand = crypto.getRandomValues(new Uint8Array(8)); - return `probe${Array.from(rand, (b) => b.toString(36)) - .join("") - .slice(0, 10)}`; -} - -/** - * Create a probe space owned by the target and cache it for the run. - * Requires an operator session with space management authority. - */ -export async function createProbeSpace( - ctx: CheckContext, - policy: Record = { - $type: "com.atproto.simplespace.defs#memberListPolicy", - }, - appAccess: Record = { - $type: "com.atproto.simplespace.defs#open", - }, -): Promise { - const skey = probeSkey(); - const res = await xrpcPost( - asOperator(ctx), - "com.atproto.simplespace.createSpace", - { - type: PROBE_TYPE, - skey, - policy, - appAccess, - }, - ); - if (res.status !== 200) { - throw new Error( - `createSpace failed: ${res.status} ${res.error ?? ""} ${JSON.stringify(res.json)}`, - ); - } - const uri = (res.json as { uri: string }).uri; - return { uri, type: PROBE_TYPE, skey }; -} - -/** Delete a probe space, best-effort (cleanup). */ -export async function deleteProbeSpace( - ctx: CheckContext, - space: string, -): Promise { - await xrpcPost(asOperator(ctx), "com.atproto.simplespace.deleteSpace", { - space, - }).catch(() => {}); -} - -/** Operator creates a record in a space; returns the response. */ -export async function operatorCreateRecord( - ctx: CheckContext, - space: string, - collection: string, - rkey: string, - record: Record, -): Promise { - return xrpcPost(asOperator(ctx), "com.atproto.space.createRecord", { - space, - repo: ctx.target.did, - collection, - rkey, - record, - }); -} - -export interface Credential { - credential: string; - dpopKey: DpopKey; -} - -/** - * Obtain a credential the way a real app does: ask the target's own - * `getDelegationToken` (with the operator session) for a delegation token, - * then exchange it at `getSpaceCredential`. This is the bulletin self-flow - * — it needs no harness-held reader key, so it runs against any real PDS - * (Cirrus, the reference) and exercises the target's own token minting. - */ -export async function obtainCredentialViaDelegation( - ctx: CheckContext, - space: string, -): Promise<{ - result: XrpcResult; - credential?: Credential; - delegation: XrpcResult; -}> { - const delegation = await xrpcGet( - asOperator(ctx), - "com.atproto.space.getDelegationToken", - { space }, - ); - if (delegation.status !== 200) { - return { result: delegation, delegation }; - } - const token = (delegation.json as { token: string }).token; - // The DPoP key is transport-owned (any ES256 key), not tied to a harness - // identity — so this flow needs no identity provider. - const dpopKey = await createDpopKey(); - const proof = await createDpopProofJwt(dpopKey, { - htm: "POST", - htu: `${ctx.target.origin}/xrpc/com.atproto.space.getSpaceCredential`, - }); - const result = await xrpcPost( - ctx, - "com.atproto.space.getSpaceCredential", - { space }, - { Authorization: `Bearer ${token}`, DPoP: proof }, - ); - if (result.status === 200) { - const credential = (result.json as { credential: string }).credential; - return { result, credential: { credential, dpopKey }, delegation }; - } - return { result, delegation }; -} - -/** A credential-authenticated GET, with a fresh proof bound to the request. */ -export async function credentialGet( - ctx: CheckContext, - credential: Credential, - nsid: string, - params: Record, -): Promise { - const url = new URL(`${ctx.target.origin}/xrpc/${nsid}`); - for (const [key, value] of Object.entries(params)) { - if (value !== undefined) url.searchParams.set(key, value); - } - const proof = await createDpopProofJwt(credential.dpopKey, { - htm: "GET", - htu: `${ctx.target.origin}/xrpc/${nsid}`, - credential: credential.credential, - }); - const response = await ctx.fetch(url.toString(), { - method: "GET", - headers: { - Authorization: `DPoP ${credential.credential}`, - DPoP: proof, - }, - }); - const contentType = response.headers.get("Content-Type") ?? ""; - let json: unknown; - let error: string | undefined; - if (contentType.includes("application/json")) { - json = await response - .clone() - .json() - .catch(() => undefined); - if (json && typeof json === "object" && "error" in json) { - error = String((json as { error: unknown }).error); - } - } - return { - status: response.status, - json, - error, - headers: response.headers, - response, - }; -} - -// --- writes ----------------------------------------------------------- - -const writesCreateRead = defineCheck({ - id: "writes.create-and-read", - title: "Operator creates a record and reads it back", - tier: "must", - citations: [ - { source: "lexicon", ref: "com.atproto.space.createRecord" }, - { source: "lexicon", ref: "com.atproto.space.getRecord" }, - ], - needs: ["operator"], - destructive: true, - async run(ctx) { - const space = await createProbeSpace(ctx); - try { - const created = await operatorCreateRecord( - ctx, - space.uri, - POST, - "rec1", - note("hello"), - ); - if (created.status !== 200) { - return fail( - `createRecord ${created.status} ${created.error ?? ""}`, - created.json, - ); - } - const read = await xrpcGet( - asOperator(ctx), - "com.atproto.space.getRecord", - { - space: space.uri, - repo: ctx.target.did, - collection: POST, - rkey: "rec1", - }, - ); - if (read.status !== 200) { - return fail(`getRecord ${read.status} ${read.error ?? ""}`, read.json); - } - const value = (read.json as { value?: { text?: string } }).value; - return value?.text === "hello" - ? pass("round-tripped the record value") - : fail("record value did not round-trip", read.json); - } finally { - await deleteProbeSpace(ctx, space.uri); - } - }, -}); - -const writesUnauthReadRefused = defineCheck({ - id: "auth.existing-record-unauth-refused", - title: "An existing space record is not readable without auth", - tier: "must", - citations: [{ source: "lexicon", ref: "com.atproto.space.getRecord" }], - needs: ["operator"], - destructive: true, - async run(ctx) { - // The browser-safe auth.getrecord-unauthenticated-refused can only - // probe a *nonexistent* space (it has no operator to create one), so on - // its own it cannot distinguish a host that enforces auth from one that - // 401s missing spaces but serves existing records to anyone. This is - // the other half: put a real record there, then read it with no - // credentials at all. - const space = await createProbeSpace(ctx); - try { - const created = await operatorCreateRecord( - ctx, - space.uri, - POST, - "private", - note("not for you"), - ); - if (created.status !== 200) { - return fail( - `createRecord ${created.status} ${created.error ?? ""}; cannot probe the unauth read`, - created.json, - ); - } - const res = await xrpcGet(ctx, "com.atproto.space.getRecord", { - space: space.uri, - repo: ctx.target.did, - collection: POST, - rkey: "private", - }); - if (res.status === 200) { - return fail( - "an existing space record was served with no auth", - res.json, - ); - } - return res.status === 401 || res.status === 403 - ? pass(`unauthenticated read of a real record refused (${res.status})`) - : fail( - `refused, but with ${res.status} ${res.error ?? ""} rather than 401/403`, - res.json, - ); - } finally { - await deleteProbeSpace(ctx, space.uri); - } - }, -}); - -const writesDuplicate = defineCheck({ - id: "writes.duplicate-rejected", - title: "A second create at the same key is refused with RecordAlreadyExists", - tier: "must", - citations: [ - { - source: "lexicon", - ref: "com.atproto.space.createRecord@error:RecordAlreadyExists", - }, - ], - needs: ["operator"], - destructive: true, - async run(ctx) { - const space = await createProbeSpace(ctx); - try { - const first = await operatorCreateRecord( - ctx, - space.uri, - POST, - "dup", - note("one"), - ); - if (first.status !== 200) { - return fail( - `first create failed (${first.status}); cannot test duplicates`, - first.json, - ); - } - const second = await operatorCreateRecord( - ctx, - space.uri, - POST, - "dup", - note("two"), - ); - if (second.status === 200) return fail("duplicate create returned 200"); - return second.error === "RecordAlreadyExists" - ? pass("refused with RecordAlreadyExists") - : fail( - `refused but error was ${second.error} (${second.status})`, - second.json, - ); - } finally { - await deleteProbeSpace(ctx, space.uri); - } - }, -}); - -const writesDeleteIdempotent = defineCheck({ - id: "writes.delete-idempotent", - title: "deleteRecord removes the record and is idempotent", - tier: "must", - citations: [ - { source: "lexicon", ref: "com.atproto.space.deleteRecord" }, - { source: "lexicon", ref: "com.atproto.space.getRecord" }, - ], - needs: ["operator"], - destructive: true, - async run(ctx) { - const space = await createProbeSpace(ctx); - try { - const del = (rkey: string) => - xrpcPost(asOperator(ctx), "com.atproto.space.deleteRecord", { - space: space.uri, - repo: ctx.target.did, - collection: POST, - rkey, - }); - - // Effect first: a delete must actually remove the record. Without - // this, a deleteRecord that is a complete no-op (200, nothing - // happens) would pass on idempotency alone. - const created = await operatorCreateRecord( - ctx, - space.uri, - POST, - "doomed", - note("bye"), - ); - if (created.status !== 200) { - return fail( - `createRecord ${created.status} ${created.error ?? ""}; cannot test deletion`, - created.json, - ); - } - const removed = await del("doomed"); - if (removed.status !== 200) { - return fail( - `delete of an existing record returned ${removed.status} ${removed.error ?? ""}`, - removed.json, - ); - } - const after = await xrpcGet( - asOperator(ctx), - "com.atproto.space.getRecord", - { - space: space.uri, - repo: ctx.target.did, - collection: POST, - rkey: "doomed", - }, - ); - if (after.status === 200) { - return fail("a deleted record was still readable", after.json); - } - - // Then idempotency: deleting it again (and deleting a key that - // never existed) both succeed. - const again = await del("doomed"); - const ghost = await del("ghost"); - if (again.status !== 200 || ghost.status !== 200) { - return fail( - `repeat delete returned ${again.status}, absent-key delete returned ${ghost.status}`, - { again: again.json, ghost: ghost.json }, - ); - } - return pass("delete removed the record; repeat and absent deletes 200"); - } finally { - await deleteProbeSpace(ctx, space.uri); - } - }, -}); - -const writesApplyWritesAtomic = defineCheck({ - id: "writes.applywrites-atomic", - title: "A failing applyWrites batch commits nothing", - tier: "must", - citations: [ - { source: "lexicon", ref: "com.atproto.space.applyWrites" }, - { - source: "lexicon", - ref: "com.atproto.space.applyWrites@error:RecordAlreadyExists", - }, - ], - needs: ["operator"], - destructive: true, - async run(ctx) { - const space = await createProbeSpace(ctx); - const op = asOperator(ctx); - try { - await operatorCreateRecord(ctx, space.uri, POST, "exists", note("here")); - - // Positive control: a non-colliding batch must commit both ops. - // Without this, a target that has no applyWrites at all (404s the - // method) would pass the rollback assertion below vacuously. - const ok = await xrpcPost(op, "com.atproto.space.applyWrites", { - space: space.uri, - repo: ctx.target.did, - writes: [ - { - $type: "com.atproto.space.applyWrites#create", - collection: POST, - rkey: "ok1", - value: note("1"), - }, - { - $type: "com.atproto.space.applyWrites#create", - collection: POST, - rkey: "ok2", - value: note("2"), - }, - ], - }); - if (ok.status !== 200) { - return fail( - `applyWrites did not accept a valid batch (${ok.status} ${ok.error ?? ""})`, - ok.json, - ); - } - - // A batch whose second op collides must fail with - // RecordAlreadyExists and roll the first op back. - const batch = await xrpcPost(op, "com.atproto.space.applyWrites", { - space: space.uri, - repo: ctx.target.did, - writes: [ - { - $type: "com.atproto.space.applyWrites#create", - collection: POST, - rkey: "fresh", - value: note("new"), - }, - { - $type: "com.atproto.space.applyWrites#create", - collection: POST, - rkey: "exists", - value: note("collide"), - }, - ], - }); - if (batch.status === 200) return fail("colliding batch returned 200"); - if (batch.error !== "RecordAlreadyExists") { - return fail( - `colliding batch refused with ${batch.error} (${batch.status}), expected RecordAlreadyExists`, - batch.json, - ); - } - const check = await xrpcGet(op, "com.atproto.space.getRecord", { - space: space.uri, - repo: ctx.target.did, - collection: POST, - rkey: "fresh", - }); - return check.status !== 200 - ? pass("a failed batch committed nothing") - : fail("a failed batch left its first op committed", check.json); - } finally { - await deleteProbeSpace(ctx, space.uri); - } - }, -}); - -// --- credential (self-flow) ------------------------------------------- - -const credentialSelfRoundTrip = defineCheck({ - id: "credential.self-round-trip", - title: - "Operator obtains a credential for its own space via getDelegationToken and reads", - tier: "must", - citations: [ - { source: "lexicon", ref: "com.atproto.space.getDelegationToken" }, - { source: "lexicon", ref: "com.atproto.space.getSpaceCredential" }, - { source: "lexicon", ref: "com.atproto.space.getRecord" }, - ], - // Needs the target's own getDelegationToken (pds-delegation) plus an - // operator session. No harness identity — the operator is its own - // reader — so this runs against any real PDS, unlike credential.round-trip. - needs: ["operator", "pds-delegation"], - destructive: true, - async run(ctx) { - const space = await createProbeSpace(ctx, { - $type: "com.atproto.simplespace.defs#publicPolicy", - }); - try { - await operatorCreateRecord(ctx, space.uri, POST, "self", note("mine")); - const { result, credential, delegation } = - await obtainCredentialViaDelegation(ctx, space.uri); - if (delegation.status !== 200) { - return fail( - `getDelegationToken ${delegation.status} ${delegation.error ?? ""}`, - delegation.json, - ); - } - if (!credential) { - return fail( - `getSpaceCredential ${result.status} ${result.error ?? ""}`, - result.json, - ); - } - const read = await credentialGet( - ctx, - credential, - "com.atproto.space.getRecord", - { - space: space.uri, - repo: ctx.target.did, - collection: POST, - rkey: "self", - }, - ); - return read.status === 200 - ? pass("delegation → credential → read round-trip works") - : fail( - `credential read failed: ${read.status} ${read.error ?? ""}`, - read.json, - ); - } finally { - await deleteProbeSpace(ctx, space.uri); - } - }, -}); - -// --- sync -------------------------------------------------------------- - -const syncGetRepoTwoRoots = defineCheck({ - id: "sync.getrepo-two-roots", - title: "getRepo returns a CAR declaring exactly two roots", - tier: "must", - citations: [{ source: "lexicon", ref: "com.atproto.space.getRepo" }], - needs: ["operator"], - destructive: true, - async run(ctx) { - const space = await createProbeSpace(ctx); - try { - await operatorCreateRecord(ctx, space.uri, POST, "x", note("car")); - const res = await operatorFetch(ctx)( - `${ctx.target.origin}/xrpc/com.atproto.space.getRepo?space=${encodeURIComponent(space.uri)}&repo=${encodeURIComponent(ctx.target.did)}`, - ); - if (res.status !== 200) return fail(`getRepo ${res.status}`); - const contentType = res.headers.get("Content-Type") ?? ""; - if (!contentType.includes("application/vnd.ipld.car")) { - return fail(`getRepo content-type was ${contentType}`); - } - const bytes = new Uint8Array(await res.arrayBuffer()); - const header = readCarHeader(bytes); - return header.rootCount === 2 - ? pass(`CAR v${header.version} with 2 roots`) - : fail(`CAR declared ${header.rootCount} roots, expected 2`); - } finally { - await deleteProbeSpace(ctx, space.uri); - } - }, -}); - -const syncListRecordsDescending = defineCheck({ - id: "sync.listrecords-descending-default", - title: "listRecords defaults to descending record order", - tier: "should", - citations: [ - { source: "reference", ref: "listRecords default order (descending)" }, - { source: "lexicon", ref: "com.atproto.space.listRecords" }, - ], - needs: ["operator"], - destructive: true, - async run(ctx) { - const space = await createProbeSpace(ctx); - try { - for (const rkey of ["aaa", "bbb", "ccc"]) { - await operatorCreateRecord(ctx, space.uri, POST, rkey, note(rkey)); - } - const res = await xrpcGet( - asOperator(ctx), - "com.atproto.space.listRecords", - { - space: space.uri, - repo: ctx.target.did, - collection: POST, - }, - ); - if (res.status !== 200) return fail(`listRecords ${res.status}`); - const rkeys = ( - res.json as { records: Array<{ rkey: string }> } - ).records.map((r) => r.rkey); - return rkeys.join(",") === "ccc,bbb,aaa" - ? pass("records returned descending by default") - : fail(`order was ${rkeys.join(",")}, reference is descending`); - } finally { - await deleteProbeSpace(ctx, space.uri); - } - }, -}); - -// --- host role --------------------------------------------------------- - -const hostListReposNeedsCredential = defineCheck({ - id: "host.listrepos-requires-credential", - title: "listRepos requires a space credential", - tier: "must", - citations: [{ source: "lexicon", ref: "com.atproto.space.listRepos" }], - needs: ["operator"], - destructive: true, - async run(ctx) { - const space = await createProbeSpace(ctx); - try { - const res = await xrpcGet(ctx, "com.atproto.space.listRepos", { - space: space.uri, - }); - return res.status === 401 || res.status === 403 - ? pass(`unauthenticated listRepos refused with ${res.status}`) - : fail(`unauthenticated listRepos returned ${res.status}`, res.json); - } finally { - await deleteProbeSpace(ctx, space.uri); - } - }, -}); - -// --- simplespace ------------------------------------------------------- - -const simplespaceUnsupportedPolicy = defineCheck({ - id: "simplespace.unsupported-policy-rejected", - title: "createSpace rejects an unknown policy variant", - tier: "must", - citations: [ - { - source: "lexicon", - ref: "com.atproto.simplespace.createSpace@error:UnsupportedPolicy", - }, - ], - needs: ["operator"], - async run(ctx) { - const res = await xrpcPost( - asOperator(ctx), - "com.atproto.simplespace.createSpace", - { - type: PROBE_TYPE, - policy: { $type: "com.example.mysteryPolicy" }, - appAccess: { $type: "com.atproto.simplespace.defs#open" }, - }, - ); - if (res.status === 200) { - await deleteProbeSpace(ctx, (res.json as { uri: string }).uri); - return fail("an unknown policy variant was accepted"); - } - return res.error === "UnsupportedPolicy" - ? pass("rejected with UnsupportedPolicy") - : fail( - `rejected with ${res.error} (${res.status}), expected UnsupportedPolicy`, - res.json, - ); - }, -}); - -const simplespaceGetSpace = defineCheck({ - id: "simplespace.getspace-reflects-config", - title: "getSpace reflects the created policy and appAccess", - tier: "must", - citations: [ - { source: "lexicon", ref: "com.atproto.simplespace.createSpace" }, - { source: "lexicon", ref: "com.atproto.simplespace.getSpace" }, - ], - needs: ["operator"], - destructive: true, - async run(ctx) { - const space = await createProbeSpace(ctx, { - $type: "com.atproto.simplespace.defs#publicPolicy", - }); - try { - const res = await xrpcGet( - asOperator(ctx), - "com.atproto.simplespace.getSpace", - { - space: space.uri, - }, - ); - if (res.status !== 200) - return fail(`getSpace ${res.status} ${res.error ?? ""}`, res.json); - const body = res.json as { - policy?: { $type?: string }; - appAccess?: { $type?: string }; - }; - const policyType = body.policy?.$type; - if (policyType !== "com.atproto.simplespace.defs#publicPolicy") { - return fail(`getSpace policy was ${policyType}`, res.json); - } - // The title promises appAccess too — createProbeSpace passed #open. - const appAccessType = body.appAccess?.$type; - return appAccessType === "com.atproto.simplespace.defs#open" - ? pass("getSpace reported the public policy and open appAccess") - : fail(`getSpace appAccess was ${appAccessType}`, res.json); - } finally { - await deleteProbeSpace(ctx, space.uri); - } - }, -}); - -// --- blobs ------------------------------------------------------------- - -/** Blob isolation (S6): a space blob is never public. */ -const blobsSpaceNotPublic = defineCheck({ - id: "blobs.space-blob-not-public", - title: "A blob is not publicly served unless a public record references it", - tier: "must", - citations: [ - { source: "lexicon", ref: "com.atproto.space.getBlob" }, - { source: "proposal", ref: "0016#blob-sync" }, - ], - // uploadBlob and sync.getBlob are host-PDS endpoints, not space methods — - // a standalone space host has neither, so gate on pds-blobs or this - // check would false-fail wherever they are absent. - needs: ["operator", "pds-blobs"], - destructive: true, - async run(ctx) { - // The principle under test is a positive gate, not cleanup: a blob must - // never be publicly addressable until a *public* record references it. - // Probe both slices of that — freshly uploaded (unreferenced), then - // referenced only from a space. Serving either from the public - // sync.getBlob leaks bytes the proposal says are fetched via the - // credential-gated space.getBlob. - const space = await createProbeSpace(ctx); - try { - const bytes = crypto.getRandomValues(new Uint8Array(16)); - const upload = await operatorFetch(ctx)( - `${ctx.target.origin}/xrpc/com.atproto.repo.uploadBlob`, - { - method: "POST", - headers: { "Content-Type": "application/octet-stream" }, - body: bytes, - }, - ); - if (upload.status !== 200) return fail(`uploadBlob ${upload.status}`); - const blob = ( - (await upload.json()) as { blob: { ref: { $link: string } } } - ).blob; - const cid = blob.ref.$link; - const publicUrl = `${ctx.target.origin}/xrpc/com.atproto.sync.getBlob?did=${encodeURIComponent(ctx.target.did)}&cid=${cid}`; - - const stagedGet = await ctx.fetch(publicUrl); - if (stagedGet.status === 200) { - return fail( - "an uploaded, unreferenced blob was served by the public sync.getBlob", - ); - } - - const write = await operatorCreateRecord( - ctx, - space.uri, - "earth.cirrus.check.withblob", - "self", - { - $type: "earth.cirrus.check.withblob", - file: blob, - }, - ); - if (write.status !== 200) - return fail( - `referencing write ${write.status} ${write.error ?? ""}`, - write.json, - ); - const publicGet = await ctx.fetch(publicUrl); - return publicGet.status === 200 - ? fail("a space blob was served by the public sync.getBlob") - : pass( - `public sync.getBlob refused the blob unreferenced (${stagedGet.status}) and space-referenced (${publicGet.status})`, - ); - } finally { - await deleteProbeSpace(ctx, space.uri); - } - }, -}); +import type { Check } from "../model.js"; +import { credentialChecks } from "./credential.js"; +import { hostChecks } from "./host.js"; +import { recordChecks } from "./records.js"; +import { spaceChecks } from "./space.js"; + +export { + FOREIGN_DID, + POST, + PROBE_TYPE, + createProbeSpace, + credentialCall, + credentialGet, + deleteProbeSpace, + managedspace, + memberspace, + note, + obtainCredentialViaDelegation, + obtainPublicCredential, + operatorCreateRecord, + personalspace, + publicRead, + requestCredential, +} from "./probe.js"; +export type { + Credential, + CredentialCallOptions, + CredentialResult, + Policy, + ProbeSpace, +} from "./probe.js"; /** * The operator catalog: runnable anywhere the harness has an operator * session — browser included. */ export const operatorChecks: Check[] = [ - writesCreateRead, - writesUnauthReadRefused, - writesDuplicate, - writesDeleteIdempotent, - writesApplyWritesAtomic, - credentialSelfRoundTrip, - syncGetRepoTwoRoots, - syncListRecordsDescending, - hostListReposNeedsCredential, - simplespaceUnsupportedPolicy, - simplespaceGetSpace, - blobsSpaceNotPublic, + ...recordChecks, + ...spaceChecks, + ...credentialChecks, + ...hostChecks, ]; diff --git a/packages/space-conformance/src/checks/probe.ts b/packages/space-conformance/src/checks/probe.ts new file mode 100644 index 0000000..9b2209b --- /dev/null +++ b/packages/space-conformance/src/checks/probe.ts @@ -0,0 +1,378 @@ +/** + * Browser-safe helpers the checks share: probe spaces, operator writes, + * obtaining a space credential, and presenting it (HTTP signature plus, + * where the method returns a commit or record, a MAC request). + * + * Everything here needs only `fetch` and WebCrypto, so the operator + * checks — which include the operator's own credential flow — run in a + * browser as well as in the CLI and the vitest adapter. + */ + +import { + asOperator, + toResult, + xrpcGet, + xrpcPost, + xrpcUrl, + type XrpcResult, +} from "../http.js"; +import type { CheckContext } from "../model.js"; +import { kemKeyFor } from "../did.js"; +import { + COMMIT_MAC_TYPE, + RECORD_MAC_TYPE, + SPACE_CREDENTIAL_SCHEME, + createCredentialKey, + encapsulate, + formatWantMacHeader, + spaceSigHeaders, + type CredentialKey, + type MacType, +} from "../space-auth.js"; + +// The probe collections and space type are published, resolvable +// lexicons under the suite's own authority (see ../../probe-lexicons) — +// so strict, dynamically-resolving targets can validate them, while +// AppViews ignore them (nothing under earth.cirrus.check.* is app.bsky.*). +export const POST = "earth.cirrus.check.note"; +export const note = (text: string) => ({ $type: POST, text }); +export const PROBE_TYPE = "earth.cirrus.check.space"; + +/** + * A syntactically valid DID no host serves: the authority of spaces the + * operator does not own, and the subject of reads of a repo no host holds. + */ +export const FOREIGN_DID = "did:web:space-conformance.invalid"; + +// --- policies ---------------------------------------------------------- + +export type Policy = { $type: string } & Record; + +export const personalspace = (): Policy => ({ + $type: "com.atproto.personalspace.policy", +}); + +export const memberspace = ( + config: { + publicRead?: boolean; + publicWrite?: boolean; + allowedApps?: string[]; + publishPolicy?: boolean; + publishMembers?: boolean; + } = {}, +): Policy => ({ $type: "com.atproto.memberspace.policy", ...config }); + +export const managedspace = ( + managingApp: string, + config: { publishPolicy?: boolean } = {}, +): Policy => ({ + $type: "com.atproto.managedspace.policy", + managingApp, + ...config, +}); + +/** A public-read memberspace: anyone may obtain a credential, no token needed. */ +export const publicRead = (): Policy => memberspace({ publicRead: true }); + +// --- probe spaces ------------------------------------------------------ + +export interface ProbeSpace { + uri: string; + type: string; + skey: string; +} + +/** A run-unique skey so probe spaces never collide with real ones. */ +export function probeSkey(): string { + const rand = crypto.getRandomValues(new Uint8Array(8)); + return `probe${Array.from(rand, (b) => b.toString(36)) + .join("") + .slice(0, 10)}`; +} + +/** A space URI under `did` that nobody has created. */ +export const unknownSpaceUri = (did: string): string => + `at://${did}/space/${PROBE_TYPE}/${probeSkey()}`; + +/** The authority DID a space URI names. */ +export const spaceAuthority = (space: string): string => + space.replace(/^at:\/\//, "").split("/")[0]!; + +/** + * Create a probe space owned by the target's operator. The default policy + * is a closed memberspace — only the authority can read it. + */ +export async function createProbeSpace( + ctx: CheckContext, + policy: Policy = memberspace(), + skey: string = probeSkey(), +): Promise { + const res = await xrpcPost( + asOperator(ctx), + "com.atproto.space.createSpace", + { spaceType: PROBE_TYPE, skey, policy }, + ); + if (res.status !== 200) { + throw new Error( + `createSpace failed: ${res.status} ${res.error ?? ""} ${JSON.stringify(res.json)}`, + ); + } + const uri = (res.json as { uri: string }).uri; + return { uri, type: PROBE_TYPE, skey }; +} + +/** Delete a probe space, best-effort (cleanup). */ +export async function deleteProbeSpace( + ctx: CheckContext, + space: string, +): Promise { + await xrpcPost(asOperator(ctx), "com.atproto.space.deleteSpace", { + space, + }).catch(() => {}); +} + +/** Operator creates a record in a space; returns the response. */ +export async function operatorCreateRecord( + ctx: CheckContext, + space: string, + collection: string, + rkey: string, + record: Record, +): Promise { + return xrpcPost(asOperator(ctx), "com.atproto.space.createRecord", { + space, + repo: ctx.target.did, + collection, + rkey, + record, + }); +} + +/** Operator write that must succeed (setup, not the thing under test). */ +export async function mustCreateRecord( + ctx: CheckContext, + space: string, + rkey: string, + text = rkey, +): Promise<{ uri: string; cid: string }> { + const res = await operatorCreateRecord(ctx, space, POST, rkey, note(text)); + if (res.status !== 200) { + throw new Error( + `setup createRecord failed: ${res.status} ${res.error ?? ""}`, + ); + } + return res.json as { uri: string; cid: string }; +} + +/** Operator's own read of its repo in a space (no MAC needed or asked). */ +export function operatorGetRecord( + ctx: CheckContext, + space: string, + rkey: string, + collection = POST, +): Promise { + return xrpcGet(asOperator(ctx), "com.atproto.space.getRecord", { + space, + repo: ctx.target.did, + collection, + rkey, + }); +} + +// --- credentials ------------------------------------------------------- + +export interface Credential { + credential: string; + key: CredentialKey; + /** The space it was issued for. */ + space: string; +} + +/** + * Ask the space's authority for a credential. Nothing authenticates the + * request itself: the body carries the key to bind, and optionally a + * delegation token (who the user is) and a client attestation (which app). + */ +export async function requestCredential( + ctx: CheckContext, + space: string, + opts: { + delegationToken?: string; + clientAttestation?: string; + credentialKid?: string; + key?: CredentialKey; + } = {}, +): Promise<{ result: XrpcResult; credential?: Credential }> { + const key = opts.key ?? (await createCredentialKey()); + const result = await xrpcPost(ctx, "com.atproto.space.getSpaceCredential", { + space, + credentialKid: opts.credentialKid ?? key.did, + ...(opts.delegationToken ? { delegationToken: opts.delegationToken } : {}), + ...(opts.clientAttestation + ? { clientAttestation: opts.clientAttestation } + : {}), + }); + if (result.status === 200) { + const credential = (result.json as { credential?: unknown }).credential; + if (typeof credential === "string") { + return { result, credential: { credential, key, space } }; + } + } + return { result }; +} + +/** A tokenless credential for a public-read space; throws if refused. */ +export async function obtainPublicCredential( + ctx: CheckContext, + space: string, +): Promise { + const { result, credential } = await requestCredential(ctx, space); + if (!credential) { + throw new Error( + `tokenless getSpaceCredential for a public-read space failed: ${result.status} ${result.error ?? ""}`, + ); + } + return credential; +} + +/** + * Obtain a credential the way a real app does: ask the target's own + * `getDelegationToken` (with the operator session) for a delegation token, + * then exchange it at `getSpaceCredential`. It needs no harness-held + * reader key, so it runs against any real PDS and exercises the target's + * own token minting. + */ +export async function obtainCredentialViaDelegation( + ctx: CheckContext, + space: string, +): Promise<{ + result: XrpcResult; + credential?: Credential; + delegation: XrpcResult; +}> { + const delegation = await xrpcGet( + asOperator(ctx), + "com.atproto.space.getDelegationToken", + { space }, + ); + if (delegation.status !== 200) { + return { result: delegation, delegation }; + } + const token = (delegation.json as { token: string }).token; + const { result, credential } = await requestCredential(ctx, space, { + delegationToken: token, + }); + return { result, delegation, ...(credential ? { credential } : {}) }; +} + +/** Which MAC each repo-host read asks for. */ +const MAC_TYPES: Record = { + "com.atproto.space.getLatestCommit": COMMIT_MAC_TYPE, + "com.atproto.space.getRepo": COMMIT_MAC_TYPE, + "com.atproto.space.listRepoOps": COMMIT_MAC_TYPE, + "com.atproto.space.getRecord": RECORD_MAC_TYPE, +}; + +export interface CredentialCallOptions { + /** Query params (GET) — or omit and pass `body` for a procedure. */ + params?: Record; + body?: unknown; + /** + * The audience DID: the service being called. Defaults to the `repo` + * param (a repo-host read), else the space's authority (a space-host + * method). + */ + audience?: string; + /** + * The MAC to ask for. Defaults to what the method returns (commit or + * record) for the four MAC'd reads, nothing otherwise. `false` omits the + * header; a string sends it verbatim (malformed-header probes). + */ + wantMac?: MacType | false | string; + /** Authorization scheme spelling; defaults to `Atproto-Space-Credential`. */ + scheme?: string; + /** Sign with this key instead of the credential's own. */ + signWith?: CredentialKey; + /** Send no signature headers at all. */ + unsigned?: boolean; +} + +export interface CredentialResult extends XrpcResult { + /** The KEM shared secret, when a MAC was requested. */ + sharedSecret?: Uint8Array; + macType?: MacType; +} + +/** Present a credential on one request: signature, audience, MAC request. */ +export async function credentialCall( + ctx: CheckContext, + credential: Credential, + nsid: string, + opts: CredentialCallOptions = {}, +): Promise { + const repo = opts.params?.repo; + const audience = + opts.audience ?? repo ?? spaceAuthority(credential.space); + const authorization = `${opts.scheme ?? SPACE_CREDENTIAL_SCHEME} ${credential.credential}`; + const headers = new Headers( + opts.unsigned + ? { authorization } + : await spaceSigHeaders(opts.signWith ?? credential.key, { + authorization, + audience, + }), + ); + + let sharedSecret: Uint8Array | undefined; + let macType: MacType | undefined; + const want = opts.wantMac ?? MAC_TYPES[nsid]; + if (typeof want === "string" && want !== COMMIT_MAC_TYPE && want !== RECORD_MAC_TYPE) { + headers.set("atproto-space-want-mac", want); + } else if (want) { + if (!repo) throw new Error(`${nsid}: a MAC request needs the repo DID`); + const { keyShare, sharedSecret: secret } = await encapsulate( + await kemKeyFor(ctx, repo), + ); + headers.set("atproto-space-want-mac", formatWantMacHeader(want, keyShare)); + sharedSecret = secret; + macType = want; + } + + let response: Response; + if (opts.body !== undefined) { + headers.set("Content-Type", "application/json"); + response = await ctx.fetch(xrpcUrl(ctx.target.origin, nsid), { + method: "POST", + headers, + body: JSON.stringify(opts.body), + }); + } else { + response = await ctx.fetch( + xrpcUrl(ctx.target.origin, nsid, opts.params), + { method: "GET", headers }, + ); + } + const result = await toResult(response); + return { + ...result, + ...(sharedSecret ? { sharedSecret } : {}), + ...(macType ? { macType } : {}), + }; +} + +/** A credential-authenticated GET with the default audience and MAC request. */ +export function credentialGet( + ctx: CheckContext, + credential: Credential, + nsid: string, + params: Record, +): Promise { + return credentialCall(ctx, credential, nsid, { params }); +} + +/** Summarise a response for a detail line. */ +export const describe = (res: XrpcResult): string => + `${res.status}${res.error ? ` ${res.error}` : ""}`; + +export const isAuthRefusal = (res: XrpcResult): boolean => + res.status === 401 || res.status === 403; diff --git a/packages/space-conformance/src/checks/records.ts b/packages/space-conformance/src/checks/records.ts new file mode 100644 index 0000000..5322e18 --- /dev/null +++ b/packages/space-conformance/src/checks/records.ts @@ -0,0 +1,739 @@ +/** + * Record writes and the owner's own reads: create/put/delete/applyWrites, + * clearRecords, listRecords, blobs, and the SpaceNotFound perimeter around + * spaces that do not exist or were deleted. Operator-only, browser-safe. + */ + +import { defineCheck } from "../registry.js"; +import { + asOperator, + operatorFetch, + xrpcGet, + xrpcPost, + type XrpcResult, +} from "../http.js"; +import { fail, pass, type Check, type CheckContext } from "../model.js"; +import { bytesEqual, lexBytes, rawCid, sha256 } from "../encoding.js"; +import { + POST, + createProbeSpace, + deleteProbeSpace, + describe, + memberspace, + mustCreateRecord, + note, + operatorCreateRecord, + operatorGetRecord, + personalspace, + unknownSpaceUri, +} from "./probe.js"; + +const L = (ref: string) => ({ source: "lexicon" as const, ref }); +const C = (ref: string) => ({ source: "changeset" as const, ref }); +const op = asOperator; + +const writesCreateRead = defineCheck({ + id: "writes.create-and-read", + title: "Operator creates a record and reads it back", + tier: "must", + citations: [L("com.atproto.space.createRecord"), L("com.atproto.space.getRecord")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx); + try { + const created = await operatorCreateRecord(ctx, space.uri, POST, "rec1", note("hello")); + if (created.status !== 200) return fail(`createRecord ${describe(created)}`, created.json); + const read = await operatorGetRecord(ctx, space.uri, "rec1"); + if (read.status !== 200) return fail(`getRecord ${describe(read)}`, read.json); + const body = read.json as { uri?: string; cid?: string; value?: { text?: string } }; + if (body.cid !== (created.json as { cid?: string }).cid) { + return fail("getRecord cid differs from the createRecord cid", read.json); + } + return body.value?.text === "hello" + ? pass("round-tripped the record value and cid") + : fail("record value did not round-trip", read.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const writesUnauthReadRefused = defineCheck({ + id: "auth.existing-record-unauth-refused", + title: "An existing space record is not readable without auth", + tier: "must", + citations: [L("com.atproto.space.getRecord")], + needs: ["operator"], + destructive: true, + async run(ctx) { + // The browser-safe auth.getrecord-unauthenticated-refused can only + // probe a *nonexistent* space, so on its own it cannot distinguish a + // host that enforces auth from one that 401s missing spaces but serves + // existing records to anyone. This is the other half. + const space = await createProbeSpace(ctx); + try { + await mustCreateRecord(ctx, space.uri, "private", "not for you"); + const res = await xrpcGet(ctx, "com.atproto.space.getRecord", { + space: space.uri, + repo: ctx.target.did, + collection: POST, + rkey: "private", + }); + if (res.status === 200) return fail("an existing space record was served with no auth", res.json); + return res.status === 401 || res.status === 403 + ? pass(`unauthenticated read of a real record refused (${res.status})`) + : fail(`refused, but with ${describe(res)} rather than 401/403`, res.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const writesDuplicate = defineCheck({ + id: "writes.duplicate-rejected", + title: "A second create at the same key is refused with RecordAlreadyExists", + tier: "must", + citations: [L("com.atproto.space.createRecord@error:RecordAlreadyExists")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx); + try { + await mustCreateRecord(ctx, space.uri, "dup", "one"); + const second = await operatorCreateRecord(ctx, space.uri, POST, "dup", note("two")); + if (second.status === 200) return fail("duplicate create returned 200"); + return second.error === "RecordAlreadyExists" + ? pass("refused with RecordAlreadyExists") + : fail(`refused but error was ${describe(second)}`, second.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const writesPutRecord = defineCheck({ + id: "writes.putrecord-upsert", + title: "putRecord creates a record and then replaces it", + tier: "must", + citations: [L("com.atproto.space.putRecord")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx); + const put = (text: string) => + xrpcPost(op(ctx), "com.atproto.space.putRecord", { + space: space.uri, + repo: ctx.target.did, + collection: POST, + rkey: "upsert", + record: note(text), + }); + try { + const first = await put("v1"); + if (first.status !== 200) return fail(`putRecord (create) ${describe(first)}`, first.json); + const second = await put("v2"); + if (second.status !== 200) return fail(`putRecord (update) ${describe(second)}`, second.json); + const read = await operatorGetRecord(ctx, space.uri, "upsert"); + const text = (read.json as { value?: { text?: string } } | undefined)?.value?.text; + return text === "v2" + ? pass("created then replaced the record") + : fail(`after two puts the record reads ${describe(read)} ${text}`, read.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const writesGetRecordMissing = defineCheck({ + id: "writes.getrecord-missing", + title: "getRecord of an absent rkey answers RecordNotFound", + tier: "must", + citations: [L("com.atproto.space.getRecord@error:RecordNotFound")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx); + try { + // The repo exists (one record), so the absence is the record's. + await mustCreateRecord(ctx, space.uri, "present"); + const res = await operatorGetRecord(ctx, space.uri, "absent"); + return res.error === "RecordNotFound" + ? pass("answered RecordNotFound") + : fail(`answered ${describe(res)}, expected RecordNotFound`, res.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const writesDeleteIdempotent = defineCheck({ + id: "writes.delete-idempotent", + title: "deleteRecord removes the record and is idempotent", + tier: "must", + citations: [L("com.atproto.space.deleteRecord"), L("com.atproto.space.getRecord")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx); + try { + const del = (rkey: string) => + xrpcPost(op(ctx), "com.atproto.space.deleteRecord", { + space: space.uri, + repo: ctx.target.did, + collection: POST, + rkey, + }); + // Effect first: without it a deleteRecord that is a no-op (200, + // nothing happens) would pass on idempotency alone. + await mustCreateRecord(ctx, space.uri, "doomed", "bye"); + const removed = await del("doomed"); + if (removed.status !== 200) return fail(`delete of an existing record returned ${describe(removed)}`, removed.json); + const after = await operatorGetRecord(ctx, space.uri, "doomed"); + if (after.status === 200) return fail("a deleted record was still readable", after.json); + const again = await del("doomed"); + const ghost = await del("ghost"); + if (again.status !== 200 || ghost.status !== 200) { + return fail(`repeat delete returned ${describe(again)}, absent-key delete returned ${describe(ghost)}`, { + again: again.json, + ghost: ghost.json, + }); + } + return pass("delete removed the record; repeat and absent deletes 200"); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const create = (rkey: string, text: string) => ({ + $type: "com.atproto.space.applyWrites#create", + collection: POST, + rkey, + value: note(text), +}); + +const writesApplyWritesAtomic = defineCheck({ + id: "writes.applywrites-atomic", + title: "A failing applyWrites batch commits nothing", + tier: "must", + citations: [ + L("com.atproto.space.applyWrites"), + L("com.atproto.space.applyWrites@error:RecordAlreadyExists"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx); + try { + await mustCreateRecord(ctx, space.uri, "exists", "here"); + // Positive control: a target with no applyWrites at all would + // otherwise pass the rollback assertion vacuously. + const ok = await xrpcPost(op(ctx), "com.atproto.space.applyWrites", { + space: space.uri, + repo: ctx.target.did, + writes: [create("ok1", "1"), create("ok2", "2")], + }); + if (ok.status !== 200) return fail(`applyWrites did not accept a valid batch (${describe(ok)})`, ok.json); + const batch = await xrpcPost(op(ctx), "com.atproto.space.applyWrites", { + space: space.uri, + repo: ctx.target.did, + writes: [create("fresh", "new"), create("exists", "collide")], + }); + if (batch.status === 200) return fail("colliding batch returned 200"); + if (batch.error !== "RecordAlreadyExists") { + return fail(`colliding batch refused with ${describe(batch)}, expected RecordAlreadyExists`, batch.json); + } + const check = await operatorGetRecord(ctx, space.uri, "fresh"); + return check.status !== 200 + ? pass("a failed batch committed nothing") + : fail("a failed batch left its first op committed", check.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const writesApplyWritesMissing = defineCheck({ + id: "writes.applywrites-update-missing", + title: "An applyWrites update of an absent record answers RecordNotFound", + tier: "must", + citations: [L("com.atproto.space.applyWrites@error:RecordNotFound")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx); + try { + await mustCreateRecord(ctx, space.uri, "present"); + const res = await xrpcPost(op(ctx), "com.atproto.space.applyWrites", { + space: space.uri, + repo: ctx.target.did, + writes: [ + { + $type: "com.atproto.space.applyWrites#update", + collection: POST, + rkey: "absent", + value: note("nope"), + }, + ], + }); + return res.error === "RecordNotFound" + ? pass("refused with RecordNotFound") + : fail(`answered ${describe(res)}, expected RecordNotFound`, res.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +/** The creating writes, each aimed at `space` (deleteRecord has its own check). */ +function writeProbes(ctx: CheckContext, space: string) { + const repo = ctx.target.did; + return [ + ["createRecord", () => xrpcPost(op(ctx), "com.atproto.space.createRecord", { space, repo, collection: POST, rkey: "w", record: note("w") })], + ["putRecord", () => xrpcPost(op(ctx), "com.atproto.space.putRecord", { space, repo, collection: POST, rkey: "w", record: note("w") })], + ["applyWrites", () => xrpcPost(op(ctx), "com.atproto.space.applyWrites", { space, repo, writes: [create("w", "w")] })], + ] as Array<[string, () => Promise]>; +} + +async function expectNotFound( + probes: Array<[string, () => Promise]>, + label: string, +): Promise { + const misses: string[] = []; + for (const [name, call] of probes) { + const res = await call(); + if (res.error !== "SpaceNotFound") misses.push(`${label} ${name} → ${describe(res)}`); + } + return misses; +} + +const writesSpaceNotFound = defineCheck({ + id: "writes.space-not-found", + title: "The authority's writes to a missing or deleted space answer SpaceNotFound", + tier: "must", + citations: [ + L("com.atproto.space.createRecord@error:SpaceNotFound"), + L("com.atproto.space.putRecord@error:SpaceNotFound"), + L("com.atproto.space.applyWrites@error:SpaceNotFound"), + L("com.atproto.space.deleteSpace"), + { source: "changeset", ref: "brave-spaces-exist" }, + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + // A write must neither conjure an ungoverned space nor revive a + // deleted one. (Writes into *another* authority's space are a + // different matter: a member's host cannot know whether it exists.) + const deleted = await createProbeSpace(ctx, personalspace()); + await mustCreateRecord(ctx, deleted.uri, "before"); + await deleteProbeSpace(ctx, deleted.uri); + const misses = [ + ...(await expectNotFound(writeProbes(ctx, unknownSpaceUri(ctx.target.did)), "unknown:")), + ...(await expectNotFound(writeProbes(ctx, deleted.uri), "deleted:")), + ]; + return misses.length + ? fail(`expected SpaceNotFound: ${misses.join("; ")}`) + : pass("create, put and applyWrites answered SpaceNotFound for a missing and a deleted space"); + }, +}); + +const writesDeleteSpaceNotFound = defineCheck({ + id: "writes.delete-in-missing-space", + title: "The authority's deleteRecord in a missing or deleted space answers SpaceNotFound", + tier: "must", + citations: [ + L("com.atproto.space.deleteRecord@error:SpaceNotFound"), + L("com.atproto.space.deleteSpace"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + // Separate from writes.space-not-found because deleteRecord is also + // idempotent ("succeeds whether or not the record was present"). That + // speaks to the record, not the space: deleteRecord declares + // SpaceNotFound, and deleteSpace says writes to a deleted space fail + // with it. + const deleted = await createProbeSpace(ctx, personalspace()); + await mustCreateRecord(ctx, deleted.uri, "w"); + await deleteProbeSpace(ctx, deleted.uri); + const misses: string[] = []; + for (const [label, space] of [["unknown", unknownSpaceUri(ctx.target.did)], ["deleted", deleted.uri]]) { + const res = await xrpcPost(op(ctx), "com.atproto.space.deleteRecord", { + space, + repo: ctx.target.did, + collection: POST, + rkey: "w", + }); + if (res.error !== "SpaceNotFound") misses.push(`${label} → ${describe(res)}`); + } + return misses.length + ? fail(`expected SpaceNotFound: ${misses.join("; ")}`) + : pass("answered SpaceNotFound for a missing and a deleted space"); + }, +}); + +const readsAfterDelete = defineCheck({ + id: "space.reads-after-delete-not-found", + title: "After deleteSpace, the owner's reads answer SpaceNotFound", + tier: "must", + citations: [ + L("com.atproto.space.deleteSpace"), + L("com.atproto.space.getRecord@error:SpaceNotFound"), + L("com.atproto.space.listRecords@error:SpaceNotFound"), + L("com.atproto.space.getLatestCommit@error:SpaceNotFound"), + L("com.atproto.space.listRepoOps@error:SpaceNotFound"), + L("com.atproto.space.getRepo@error:SpaceNotFound"), + L("com.atproto.space.listBlobs@error:SpaceNotFound"), + L("com.atproto.space.getBlob@error:SpaceNotFound"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + // deleteSpace: "Afterwards, reads and writes fail with SpaceNotFound". + const space = await createProbeSpace(ctx, personalspace()); + await mustCreateRecord(ctx, space.uri, "before"); + await deleteProbeSpace(ctx, space.uri); + const base = { space: space.uri, repo: ctx.target.did }; + const cid = await rawCid(crypto.getRandomValues(new Uint8Array(8))); + const reads: Array<[string, Record]> = [ + ["getRecord", { ...base, collection: POST, rkey: "before" }], + ["listRecords", base], + ["getLatestCommit", base], + ["listRepoOps", base], + ["getRepo", base], + ["listBlobs", base], + ["getBlob", { ...base, cid }], + ]; + const misses: string[] = []; + for (const [name, params] of reads) { + const res = await xrpcGet(op(ctx), `com.atproto.space.${name}`, params); + if (res.error !== "SpaceNotFound") misses.push(`${name} → ${describe(res)}`); + } + return misses.length + ? fail(`expected SpaceNotFound: ${misses.join("; ")}`) + : pass("every read of the deleted space answered SpaceNotFound"); + }, +}); + +const writesPublishedRefused = defineCheck({ + id: "writes.published-collections-refused", + title: "Direct writes to the policy and member collections are refused", + tier: "must", + citations: [ + C("baseline-space-policies"), + L("com.atproto.space.policy"), + L("com.atproto.memberspace.member"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + // Those records are the PDS's copy of the space's configuration; a + // forged one would mislead every reader that trusts it. + const space = await createProbeSpace(ctx, memberspace()); + try { + const attempts: Array<[string, string, Record]> = [ + ["com.atproto.space.policy", "self", { $type: "com.atproto.space.policy", policy: memberspace({ publicRead: true }) }], + ["com.atproto.memberspace.member", "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa", { $type: "com.atproto.memberspace.member", read: true, write: true }], + ]; + const accepted: string[] = []; + for (const [collection, rkey, record] of attempts) { + for (const nsid of ["createRecord", "putRecord"]) { + const res = await xrpcPost(op(ctx), `com.atproto.space.${nsid}`, { + space: space.uri, + repo: ctx.target.did, + collection, + rkey, + record, + }); + if (res.status === 200) accepted.push(`${nsid} ${collection}`); + } + } + return accepted.length + ? fail(`accepted: ${accepted.join(", ")}`) + : pass("createRecord and putRecord refused both published collections"); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +/** sha256 of an all-zero LtHash state: the commit data of an empty repo. */ +const emptyRepoData = () => sha256(new Uint8Array(2048)); + +async function latestCommit(ctx: CheckContext, space: string) { + const res = await xrpcGet(op(ctx), "com.atproto.space.getLatestCommit", { + space, + repo: ctx.target.did, + }); + const commit = (res.json as { commit?: { rev?: string; data?: unknown } } | undefined)?.commit; + return { res, rev: commit?.rev, data: lexBytes(commit?.data) }; +} + +async function listRecords(ctx: CheckContext, space: string, extra: Record = {}) { + const res = await xrpcGet(op(ctx), "com.atproto.space.listRecords", { + space, + repo: ctx.target.did, + ...extra, + }); + return { + res, + records: ((res.json as { records?: Array> } | undefined)?.records ?? []), + }; +} + +const writesClearRecords = defineCheck({ + id: "writes.clearrecords", + title: "clearRecords empties the repo at a new rev with the empty-repo digest", + tier: "must", + citations: [L("com.atproto.space.clearRecords"), L("com.atproto.space.listRecords")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx); + const clear = () => + xrpcPost(op(ctx), "com.atproto.space.clearRecords", { space: space.uri, repo: ctx.target.did }); + try { + await mustCreateRecord(ctx, space.uri, "a"); + await mustCreateRecord(ctx, space.uri, "b"); + const before = await latestCommit(ctx, space.uri); + const cleared = await clear(); + if (cleared.status !== 200) return fail(`clearRecords ${describe(cleared)}`, cleared.json); + const { records } = await listRecords(ctx, space.uri); + if (records.length) return fail(`${records.length} record(s) survived clearRecords`, records); + const after = await latestCommit(ctx, space.uri); + if (!after.rev || !before.rev || after.rev <= before.rev) { + return fail(`rev did not advance (${before.rev} → ${after.rev})`, after.res.json); + } + if (!after.data || !bytesEqual(after.data, await emptyRepoData())) { + return fail("commit data after clearRecords is not the empty repo's digest", after.res.json); + } + // "Succeeds whether or not the repo held any records to delete." + const again = await clear(); + return again.status === 200 + ? pass("cleared at a new rev with the empty digest; clearing again is a no-op") + : fail(`clearing an empty repo returned ${describe(again)}`, again.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const writesClearKeepsPublished = defineCheck({ + id: "writes.clearrecords-keeps-published", + title: "clearRecords in the authority's repo keeps the published policy record", + tier: "must", + citations: [L("com.atproto.space.clearRecords")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, memberspace({ publishPolicy: true })); + try { + await mustCreateRecord(ctx, space.uri, "mine"); + const cleared = await xrpcPost(op(ctx), "com.atproto.space.clearRecords", { + space: space.uri, + repo: ctx.target.did, + }); + if (cleared.status !== 200) return fail(`clearRecords ${describe(cleared)}`, cleared.json); + const own = await operatorGetRecord(ctx, space.uri, "mine"); + if (own.status === 200) return fail("the operator's own record survived clearRecords"); + const policy = await operatorGetRecord(ctx, space.uri, "self", "com.atproto.space.policy"); + return policy.status === 200 + ? pass("own record cleared; the published policy record kept") + : fail(`the published policy record was cleared too (${describe(policy)})`, policy.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const syncListRecords = defineCheck({ + id: "sync.listrecords-lists", + title: "listRecords lists records with values, and excludeValues omits them", + tier: "must", + citations: [L("com.atproto.space.listRecords")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx); + try { + const a = await mustCreateRecord(ctx, space.uri, "aaa", "first"); + await mustCreateRecord(ctx, space.uri, "bbb", "second"); + const full = await listRecords(ctx, space.uri, { collection: POST }); + if (full.res.status !== 200) return fail(`listRecords ${describe(full.res)}`, full.res.json); + const entry = full.records.find((r) => r.rkey === "aaa"); + if (full.records.length !== 2 || !entry) return fail(`listed ${full.records.length} record(s)`, full.records); + if (entry.collection !== POST || entry.cid !== a.cid || (entry.value as { text?: string })?.text !== "first") { + return fail("listed entry does not match the written record", entry); + } + const bare = await listRecords(ctx, space.uri, { collection: POST, excludeValues: "true" }); + if (bare.records.length !== 2) return fail(`excludeValues listed ${bare.records.length} record(s)`, bare.records); + return bare.records.some((r) => "value" in r) + ? fail("excludeValues still inlined values", bare.records) + : pass("listed both records with values; excludeValues listed metadata only"); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const syncListRecordsDescending = defineCheck({ + id: "sync.listrecords-descending-default", + title: "listRecords defaults to descending record order", + tier: "should", + citations: [ + { source: "reference", ref: "listRecords default order (descending)" }, + L("com.atproto.space.listRecords"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx); + try { + for (const rkey of ["aaa", "bbb", "ccc"]) await mustCreateRecord(ctx, space.uri, rkey); + const { res, records } = await listRecords(ctx, space.uri, { collection: POST }); + if (res.status !== 200) return fail(`listRecords ${describe(res)}`); + const rkeys = records.map((r) => r.rkey); + return rkeys.join(",") === "ccc,bbb,aaa" + ? pass("records returned descending by default") + : fail(`order was ${rkeys.join(",")}, reference is descending`); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +// --- blobs ------------------------------------------------------------- + +async function uploadBlob(ctx: CheckContext, bytes: Uint8Array) { + const upload = await operatorFetch(ctx)( + `${ctx.target.origin}/xrpc/com.atproto.repo.uploadBlob`, + { + method: "POST", + headers: { "Content-Type": "application/octet-stream" }, + body: bytes as BodyInit, + }, + ); + if (upload.status !== 200) throw new Error(`uploadBlob ${upload.status}`); + return ((await upload.json()) as { blob: { ref: { $link: string } } }).blob; +} + +/** Blob isolation: a space blob is never public. */ +const blobsSpaceNotPublic = defineCheck({ + id: "blobs.space-blob-not-public", + title: "A blob is not publicly served unless a public record references it", + tier: "must", + citations: [L("com.atproto.space.getBlob"), { source: "proposal", ref: "0016#blob-sync" }], + // uploadBlob and sync.getBlob are host-PDS endpoints, not space methods. + needs: ["operator", "pds-blobs"], + destructive: true, + async run(ctx) { + // A blob must never be publicly addressable until a *public* record + // references it. Probe both slices: freshly uploaded (unreferenced), + // then referenced only from a space. + const space = await createProbeSpace(ctx); + try { + const blob = await uploadBlob(ctx, crypto.getRandomValues(new Uint8Array(16))); + const publicUrl = `${ctx.target.origin}/xrpc/com.atproto.sync.getBlob?did=${encodeURIComponent(ctx.target.did)}&cid=${blob.ref.$link}`; + const stagedGet = await ctx.fetch(publicUrl); + if (stagedGet.status === 200) { + return fail("an uploaded, unreferenced blob was served by the public sync.getBlob"); + } + const write = await operatorCreateRecord(ctx, space.uri, "earth.cirrus.check.withblob", "self", { + $type: "earth.cirrus.check.withblob", + file: blob, + }); + if (write.status !== 200) return fail(`referencing write ${describe(write)}`, write.json); + const publicGet = await ctx.fetch(publicUrl); + return publicGet.status === 200 + ? fail("a space blob was served by the public sync.getBlob") + : pass(`public sync.getBlob refused the blob unreferenced (${stagedGet.status}) and space-referenced (${publicGet.status})`); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const blobsListAndGet = defineCheck({ + id: "blobs.listblobs-and-getblob", + title: "listBlobs lists a space record's blob and space.getBlob serves it", + tier: "must", + citations: [L("com.atproto.space.listBlobs"), L("com.atproto.space.getBlob")], + needs: ["operator", "pds-blobs"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx); + try { + const bytes = crypto.getRandomValues(new Uint8Array(24)); + const blob = await uploadBlob(ctx, bytes); + const write = await operatorCreateRecord(ctx, space.uri, "earth.cirrus.check.withblob", "self", { + $type: "earth.cirrus.check.withblob", + file: blob, + }); + if (write.status !== 200) return fail(`referencing write ${describe(write)}`, write.json); + const list = await xrpcGet(op(ctx), "com.atproto.space.listBlobs", { + space: space.uri, + repo: ctx.target.did, + }); + const cids = (list.json as { cids?: string[] } | undefined)?.cids ?? []; + if (!cids.includes(blob.ref.$link)) return fail(`listBlobs ${describe(list)} did not list the blob`, list.json); + const res = await operatorFetch(ctx)( + `${ctx.target.origin}/xrpc/com.atproto.space.getBlob?space=${encodeURIComponent(space.uri)}&repo=${encodeURIComponent(ctx.target.did)}&cid=${blob.ref.$link}`, + ); + if (res.status !== 200) return fail(`space.getBlob ${res.status}`); + const served = new Uint8Array(await res.arrayBuffer()); + return bytesEqual(served, bytes) + ? pass("listed and served the exact bytes") + : fail("space.getBlob served different bytes"); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const blobsNotFound = defineCheck({ + id: "blobs.getblob-not-found", + title: "space.getBlob of a blob the space does not reference answers BlobNotFound", + tier: "must", + citations: [L("com.atproto.space.getBlob@error:BlobNotFound")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx); + try { + await mustCreateRecord(ctx, space.uri, "present"); + const res = await xrpcGet(op(ctx), "com.atproto.space.getBlob", { + space: space.uri, + repo: ctx.target.did, + cid: await rawCid(crypto.getRandomValues(new Uint8Array(16))), + }); + return res.error === "BlobNotFound" + ? pass("answered BlobNotFound") + : fail(`answered ${describe(res)}, expected BlobNotFound`, res.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +export const recordChecks: Check[] = [ + writesCreateRead, + writesUnauthReadRefused, + writesDuplicate, + writesPutRecord, + writesGetRecordMissing, + writesDeleteIdempotent, + writesApplyWritesAtomic, + writesApplyWritesMissing, + writesSpaceNotFound, + writesDeleteSpaceNotFound, + readsAfterDelete, + writesPublishedRefused, + writesClearRecords, + writesClearKeepsPublished, + syncListRecords, + syncListRecordsDescending, + blobsSpaceNotPublic, + blobsListAndGet, + blobsNotFound, +]; diff --git a/packages/space-conformance/src/checks/space.ts b/packages/space-conformance/src/checks/space.ts new file mode 100644 index 0000000..4fe0f71 --- /dev/null +++ b/packages/space-conformance/src/checks/space.ts @@ -0,0 +1,586 @@ +/** + * Space management and the baseline policies: createSpace / updateSpace / + * deleteSpace / getSpace / listSpaces, and the memberspace member list. + * Operator-only and browser-safe. + */ + +import { defineCheck } from "../registry.js"; +import { asOperator, xrpcGet, xrpcPost, type XrpcResult } from "../http.js"; +import { fail, pass, type Check, type CheckContext } from "../model.js"; +import { isTid, toBase32 } from "../encoding.js"; +import { + FOREIGN_DID, + PROBE_TYPE, + createProbeSpace, + credentialCall, + deleteProbeSpace, + describe, + memberspace, + obtainPublicCredential, + operatorGetRecord, + personalspace, + probeSkey, + publicRead, + unknownSpaceUri, + type Policy, +} from "./probe.js"; + +const L = (ref: string) => ({ source: "lexicon" as const, ref }); +const C = (ref: string) => ({ source: "changeset" as const, ref }); + +/** A syntactically valid did:plc nobody registered — a member to list. */ +export function fakeDid(): string { + return `did:plc:${toBase32(crypto.getRandomValues(new Uint8Array(15))).slice(0, 24)}`; +} + +const op = asOperator; + +/** Run named probes and fail with every one that missed, not just the first. */ +async function expectEach( + probes: Array<[string, () => Promise, (r: XrpcResult) => boolean]>, +): Promise<{ ok: boolean; detail: string; evidence: Record }> { + const evidence: Record = {}; + const misses: string[] = []; + for (const [name, call, accept] of probes) { + const res = await call(); + evidence[name] = describe(res); + if (!accept(res)) misses.push(`${name} → ${describe(res)}`); + } + return { + ok: misses.length === 0, + detail: misses.join("; "), + evidence, + }; +} + +const errorIs = (name: string) => (r: XrpcResult) => r.error === name; + +// --- create / get ------------------------------------------------------- + +const spaceCreateAndGet = defineCheck({ + id: "space.create-and-get", + title: "createSpace anchors the space on the operator and getSpace describes it", + tier: "must", + citations: [L("com.atproto.space.createSpace"), L("com.atproto.space.getSpace")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const skey = probeSkey(); + const res = await xrpcPost(op(ctx), "com.atproto.space.createSpace", { + spaceType: PROBE_TYPE, + skey, + policy: memberspace(), + }); + if (res.status !== 200) return fail(`createSpace ${describe(res)}`, res.json); + const uri = (res.json as { uri?: string }).uri; + try { + const expected = `at://${ctx.target.did}/space/${PROBE_TYPE}/${skey}`; + if (uri !== expected) return fail(`createSpace returned ${uri}, expected ${expected}`); + const got = await xrpcGet(op(ctx), "com.atproto.space.getSpace", { space: uri }); + if (got.status !== 200) return fail(`getSpace ${describe(got)}`, got.json); + const body = got.json as { uri?: string; policy?: Policy }; + if (body.uri !== uri) return fail(`getSpace uri was ${body.uri}`, got.json); + if (body.policy?.$type !== "com.atproto.memberspace.policy") { + return fail(`getSpace policy was ${body.policy?.$type}`, got.json); + } + // Defaults are false: an unset publicRead must not read as public. + return body.policy.publicRead === true + ? fail("a memberspace created without publicRead reports publicRead: true") + : pass("created at the expected uri; getSpace reports the memberspace policy"); + } finally { + if (uri) await deleteProbeSpace(ctx, uri); + } + }, +}); + +const spaceGeneratedSkey = defineCheck({ + id: "space.create-generates-skey", + title: "createSpace without an skey generates a TID", + tier: "must", + citations: [L("com.atproto.space.createSpace")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const res = await xrpcPost(op(ctx), "com.atproto.space.createSpace", { + spaceType: PROBE_TYPE, + policy: personalspace(), + }); + if (res.status !== 200) return fail(`createSpace ${describe(res)}`, res.json); + const uri = (res.json as { uri: string }).uri; + await deleteProbeSpace(ctx, uri); + const skey = uri.split("/").at(-1); + return isTid(skey) + ? pass(`generated skey ${skey}`) + : fail(`generated skey ${skey} is not a TID`); + }, +}); + +const spaceDuplicate = defineCheck({ + id: "space.duplicate-refused", + title: "Creating an existing space is refused with SpaceAlreadyExists", + tier: "must", + citations: [L("com.atproto.space.createSpace@error:SpaceAlreadyExists")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, personalspace()); + try { + const again = await xrpcPost(op(ctx), "com.atproto.space.createSpace", { + spaceType: PROBE_TYPE, + skey: space.skey, + policy: personalspace(), + }); + if (again.status === 200) return fail("a second createSpace at the same skey returned 200"); + return again.error === "SpaceAlreadyExists" + ? pass("refused with SpaceAlreadyExists") + : fail(`refused with ${describe(again)}, expected SpaceAlreadyExists`, again.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const spaceRecreate = defineCheck({ + id: "space.recreate-after-delete", + title: "A deleted space may be created again", + tier: "must", + citations: [L("com.atproto.space.createSpace@error:SpaceAlreadyExists")], + needs: ["operator"], + destructive: true, + async run(ctx) { + // The SpaceAlreadyExists declaration itself carves this out: "A space + // that was previously deleted may be created again." + const space = await createProbeSpace(ctx, personalspace()); + await deleteProbeSpace(ctx, space.uri); + const again = await xrpcPost(op(ctx), "com.atproto.space.createSpace", { + spaceType: PROBE_TYPE, + skey: space.skey, + policy: personalspace(), + }); + await deleteProbeSpace(ctx, space.uri); + return again.status === 200 + ? pass("re-created the deleted space") + : fail(`re-creating a deleted space returned ${describe(again)}`, again.json); + }, +}); + +const spaceUnsupportedPolicy = defineCheck({ + id: "space.unsupported-policy-rejected", + title: "createSpace and updateSpace refuse a policy the host does not implement", + tier: "must", + citations: [ + L("com.atproto.space.createSpace@error:UnsupportedPolicy"), + L("com.atproto.space.updateSpace@error:UnsupportedPolicy"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + const mystery = { $type: "com.example.mysteryPolicy" }; + const space = await createProbeSpace(ctx, personalspace()); + let created: string | undefined; + try { + const result = await expectEach([ + [ + "createSpace", + async () => { + const res = await xrpcPost(op(ctx), "com.atproto.space.createSpace", { + spaceType: PROBE_TYPE, + skey: probeSkey(), + policy: mystery, + }); + if (res.status === 200) created = (res.json as { uri: string }).uri; + return res; + }, + errorIs("UnsupportedPolicy"), + ], + [ + "updateSpace", + () => + xrpcPost(op(ctx), "com.atproto.space.updateSpace", { + space: space.uri, + policy: mystery, + }), + errorIs("UnsupportedPolicy"), + ], + ]); + return result.ok + ? pass("both refused with UnsupportedPolicy") + : fail(`expected UnsupportedPolicy: ${result.detail}`, result.evidence); + } finally { + await deleteProbeSpace(ctx, space.uri); + if (created) await deleteProbeSpace(ctx, created); + } + }, +}); + +const spaceUpdateReplaces = defineCheck({ + id: "space.update-replaces-policy", + title: "updateSpace replaces the policy wholesale; a type change discards member state", + tier: "must", + citations: [ + L("com.atproto.space.updateSpace"), + L("com.atproto.space.getSpace"), + L("com.atproto.memberspace.listMembers"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, memberspace()); + const member = fakeDid(); + const policyOf = async () => + ((await xrpcGet(op(ctx), "com.atproto.space.getSpace", { space: space.uri })) + .json as { policy?: Policy } | undefined)?.policy; + const members = async () => + xrpcGet(op(ctx), "com.atproto.memberspace.listMembers", { space: space.uri }); + const update = (policy: Policy) => + xrpcPost(op(ctx), "com.atproto.space.updateSpace", { space: space.uri, policy }); + try { + await xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { + space: space.uri, + did: member, + read: true, + write: false, + }); + + // Same type: a configuration change. The member list survives. + const same = await update(memberspace({ publicRead: true })); + if (same.status !== 200) return fail(`updateSpace (config) ${describe(same)}`, same.json); + const p1 = await policyOf(); + if (p1?.publicRead !== true) return fail("getSpace does not reflect publicRead: true", p1); + const kept = (await members()).json as { members?: Array<{ did: string }> }; + if (!kept.members?.some((m) => m.did === member)) { + return fail("a same-type update dropped the member list", kept); + } + + // A different type migrates the space. + const migrate = await update(personalspace()); + if (migrate.status !== 200) return fail(`updateSpace (migrate) ${describe(migrate)}`, migrate.json); + const p2 = await policyOf(); + if (p2?.$type !== "com.atproto.personalspace.policy") { + return fail(`after migration getSpace reports ${p2?.$type}`, p2); + } + + // Migrating back does not restore the discarded member list. + const back = await update(memberspace()); + if (back.status !== 200) return fail(`updateSpace (back) ${describe(back)}`, back.json); + const after = (await members()).json as { members?: Array<{ did: string }> }; + return after.members?.some((m) => m.did === member) + ? fail("migrating away and back restored the old member list", after) + : pass("config update kept members; a type change replaced the policy and discarded them"); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const spaceNotOwner = defineCheck({ + id: "space.not-owner-refused", + title: "Managing a space anchored on another DID is refused with NotSpaceOwner", + tier: "must", + citations: [ + L("com.atproto.space.deleteSpace@error:NotSpaceOwner"), + L("com.atproto.space.updateSpace@error:NotSpaceOwner"), + L("com.atproto.space.removeWriter@error:NotSpaceOwner"), + L("com.atproto.space.exportSpaceMeta@error:NotSpaceOwner"), + L("com.atproto.memberspace.putMember@error:NotSpaceOwner"), + L("com.atproto.memberspace.removeMember@error:NotSpaceOwner"), + ], + needs: ["operator"], + async run(ctx) { + const space = unknownSpaceUri(FOREIGN_DID); + const did = fakeDid(); + const result = await expectEach([ + ["deleteSpace", () => xrpcPost(op(ctx), "com.atproto.space.deleteSpace", { space }), errorIs("NotSpaceOwner")], + ["updateSpace", () => xrpcPost(op(ctx), "com.atproto.space.updateSpace", { space, policy: personalspace() }), errorIs("NotSpaceOwner")], + ["removeWriter", () => xrpcPost(op(ctx), "com.atproto.space.removeWriter", { space, did }), errorIs("NotSpaceOwner")], + ["exportSpaceMeta", () => xrpcGet(op(ctx), "com.atproto.space.exportSpaceMeta", { space }), errorIs("NotSpaceOwner")], + ["putMember", () => xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { space, did, read: true, write: true }), errorIs("NotSpaceOwner")], + ["removeMember", () => xrpcPost(op(ctx), "com.atproto.memberspace.removeMember", { space, did }), errorIs("NotSpaceOwner")], + ]); + return result.ok + ? pass("every management method answered NotSpaceOwner") + : fail(`expected NotSpaceOwner: ${result.detail}`, result.evidence); + }, +}); + +const spaceUnknown = defineCheck({ + id: "space.unknown-space-not-found", + title: "Managing an own space that does not exist answers SpaceNotFound", + tier: "must", + citations: [ + L("com.atproto.space.getSpace@error:SpaceNotFound"), + L("com.atproto.space.updateSpace@error:SpaceNotFound"), + L("com.atproto.space.deleteSpace@error:SpaceNotFound"), + L("com.atproto.space.exportSpaceMeta@error:SpaceNotFound"), + L("com.atproto.space.removeWriter@error:SpaceNotFound"), + L("com.atproto.memberspace.putMember@error:SpaceNotFound"), + L("com.atproto.memberspace.removeMember@error:SpaceNotFound"), + L("com.atproto.memberspace.listMembers@error:SpaceNotFound"), + ], + needs: ["operator"], + async run(ctx) { + const space = unknownSpaceUri(ctx.target.did); + const did = fakeDid(); + const nf = errorIs("SpaceNotFound"); + const result = await expectEach([ + ["getSpace", () => xrpcGet(op(ctx), "com.atproto.space.getSpace", { space }), nf], + ["updateSpace", () => xrpcPost(op(ctx), "com.atproto.space.updateSpace", { space, policy: personalspace() }), nf], + ["deleteSpace", () => xrpcPost(op(ctx), "com.atproto.space.deleteSpace", { space }), nf], + ["exportSpaceMeta", () => xrpcGet(op(ctx), "com.atproto.space.exportSpaceMeta", { space }), nf], + ["removeWriter", () => xrpcPost(op(ctx), "com.atproto.space.removeWriter", { space, did }), nf], + ["putMember", () => xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { space, did, read: true, write: false }), nf], + ["removeMember", () => xrpcPost(op(ctx), "com.atproto.memberspace.removeMember", { space, did }), nf], + ["listMembers", () => xrpcGet(op(ctx), "com.atproto.memberspace.listMembers", { space }), nf], + ]); + return result.ok + ? pass("every method answered SpaceNotFound") + : fail(`expected SpaceNotFound: ${result.detail}`, result.evidence); + }, +}); + +const spaceDeleteIdempotent = defineCheck({ + id: "space.delete-idempotent", + title: "deleteSpace is idempotent", + tier: "must", + citations: [L("com.atproto.space.deleteSpace")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, personalspace()); + const first = await xrpcPost(op(ctx), "com.atproto.space.deleteSpace", { space: space.uri }); + const second = await xrpcPost(op(ctx), "com.atproto.space.deleteSpace", { space: space.uri }); + return first.status === 200 && second.status === 200 + ? pass("both deletes returned 200") + : fail(`deletes returned ${describe(first)} then ${describe(second)}`, { + first: first.json, + second: second.json, + }); + }, +}); + +const spaceListSpaces = defineCheck({ + id: "space.listspaces-filters", + title: "listSpaces lists the operator's spaces and honours spaceType and did", + tier: "must", + citations: [L("com.atproto.space.listSpaces")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, personalspace()); + try { + // Filter on both: an OAuth grant scoped to the probe type under the + // operator's authority covers exactly this listing. + const seen: string[] = []; + let cursor: string | undefined; + for (let page = 0; page < 20; page++) { + const res = await xrpcGet(op(ctx), "com.atproto.space.listSpaces", { + spaceType: PROBE_TYPE, + did: ctx.target.did, + limit: "100", + cursor, + }); + if (res.status !== 200) return fail(`listSpaces ${describe(res)}`, res.json); + const body = res.json as { spaces?: Array<{ uri: string }>; cursor?: string }; + seen.push(...(body.spaces ?? []).map((s) => s.uri)); + cursor = body.cursor; + if (!cursor || seen.includes(space.uri)) break; + } + if (!seen.includes(space.uri)) return fail("listSpaces did not list the new space"); + const stray = seen.filter( + (uri) => !uri.startsWith(`at://${ctx.target.did}/space/${PROBE_TYPE}/`), + ); + return stray.length + ? fail(`filtered listing included spaces outside the filter: ${stray.join(", ")}`) + : pass(`listed the space; ${seen.length} result(s), all within the filter`); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const spaceOwnerStateNotByCredential = defineCheck({ + id: "space.owner-state-not-by-credential", + title: "A space credential does not reach getSpace, listMembers or exportSpaceMeta", + tier: "must", + citations: [ + L("com.atproto.space.getSpace"), + L("com.atproto.memberspace.listMembers"), + L("com.atproto.space.exportSpaceMeta"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + // Each requires OAuth as the space owner: the policy and member list are + // the authority's own state, and a credential — which any reader of a + // public space can hold — must not expose them. + const space = await createProbeSpace(ctx, publicRead()); + try { + const credential = await obtainPublicCredential(ctx, space.uri); + const call = (nsid: string) => + credentialCall(ctx, credential, nsid, { + params: { space: space.uri }, + audience: ctx.target.did, + }); + const result = await expectEach([ + ["getSpace", () => call("com.atproto.space.getSpace"), (r) => r.status !== 200], + ["listMembers", () => call("com.atproto.memberspace.listMembers"), (r) => r.status !== 200], + ["exportSpaceMeta", () => call("com.atproto.space.exportSpaceMeta"), (r) => r.status !== 200], + ]); + return result.ok + ? pass(`all refused (${Object.values(result.evidence).join(", ")})`) + : fail(`served to a credential: ${result.detail}`, result.evidence); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +// --- memberspace ------------------------------------------------------ + +const memberRoundTrip = defineCheck({ + id: "memberspace.member-round-trip", + title: "putMember sets per-member read/write; listMembers and removeMember follow", + tier: "must", + citations: [ + L("com.atproto.memberspace.putMember"), + L("com.atproto.memberspace.listMembers"), + L("com.atproto.memberspace.removeMember"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, memberspace()); + const member = fakeDid(); + const list = async () => { + const res = await xrpcGet(op(ctx), "com.atproto.memberspace.listMembers", { space: space.uri }); + if (res.status !== 200) throw new Error(`listMembers ${describe(res)}`); + return ((res.json as { members?: Array<{ did: string; read: boolean; write: boolean }> }) + .members ?? []).find((m) => m.did === member); + }; + const put = (read: boolean, write: boolean) => + xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { space: space.uri, did: member, read, write }); + try { + const first = await put(true, false); + if (first.status !== 200) return fail(`putMember ${describe(first)}`, first.json); + const a = await list(); + if (!a || a.read !== true || a.write !== false) { + return fail(`after putMember(read, !write) listMembers shows ${JSON.stringify(a)}`); + } + const second = await put(false, true); + if (second.status !== 200) return fail(`putMember (replace) ${describe(second)}`, second.json); + const b = await list(); + if (!b || b.read !== false || b.write !== true) { + return fail(`putMember did not replace access: ${JSON.stringify(b)}`); + } + const removed = await xrpcPost(op(ctx), "com.atproto.memberspace.removeMember", { + space: space.uri, + did: member, + }); + if (removed.status !== 200) return fail(`removeMember ${describe(removed)}`, removed.json); + const c = await list(); + return c + ? fail(`removeMember left ${JSON.stringify(c)}`) + : pass("put, replaced and removed a member, as listMembers shows"); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const memberPolicyMismatch = defineCheck({ + id: "memberspace.policy-mismatch", + title: "Member methods on a non-memberspace answer PolicyMismatch", + tier: "must", + citations: [ + L("com.atproto.memberspace.putMember@error:PolicyMismatch"), + L("com.atproto.memberspace.removeMember@error:PolicyMismatch"), + L("com.atproto.memberspace.listMembers@error:PolicyMismatch"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, personalspace()); + const did = fakeDid(); + const mm = errorIs("PolicyMismatch"); + try { + const result = await expectEach([ + ["putMember", () => xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { space: space.uri, did, read: true, write: true }), mm], + ["removeMember", () => xrpcPost(op(ctx), "com.atproto.memberspace.removeMember", { space: space.uri, did }), mm], + ["listMembers", () => xrpcGet(op(ctx), "com.atproto.memberspace.listMembers", { space: space.uri }), mm], + ]); + return result.ok + ? pass("all three answered PolicyMismatch on a personalspace") + : fail(`expected PolicyMismatch: ${result.detail}`, result.evidence); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const memberPublish = defineCheck({ + id: "memberspace.publish-policy-and-members", + title: "publishPolicy / publishMembers keep policy and member records in the authority's repo", + tier: "must", + citations: [ + L("com.atproto.memberspace.policy"), + L("com.atproto.space.policy"), + L("com.atproto.memberspace.member"), + C("baseline-space-policies"), + ], + needs: ["operator"], + destructive: true, + async run(ctx: CheckContext) { + const space = await createProbeSpace( + ctx, + memberspace({ publishPolicy: true, publishMembers: true }), + ); + const member = fakeDid(); + try { + const policy = await operatorGetRecord(ctx, space.uri, "self", "com.atproto.space.policy"); + if (policy.status !== 200) { + return fail(`no com.atproto.space.policy/self record: ${describe(policy)}`, policy.json); + } + const published = (policy.json as { value?: { policy?: Policy } }).value?.policy; + if (published?.$type !== "com.atproto.memberspace.policy" || published.publishMembers !== true) { + return fail("the published policy record does not carry the space's policy", policy.json); + } + + await xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { + space: space.uri, + did: member, + read: true, + write: false, + }); + const rec = await operatorGetRecord(ctx, space.uri, member, "com.atproto.memberspace.member"); + const value = (rec.json as { value?: { read?: boolean; write?: boolean } } | undefined)?.value; + if (rec.status !== 200 || value?.read !== true || value.write !== false) { + return fail(`member record after putMember: ${describe(rec)}`, rec.json); + } + + await xrpcPost(op(ctx), "com.atproto.memberspace.removeMember", { space: space.uri, did: member }); + const gone = await operatorGetRecord(ctx, space.uri, member, "com.atproto.memberspace.member"); + return gone.status === 200 + ? fail("the member record outlived removeMember", gone.json) + : pass("policy record published; member record tracked putMember and removeMember"); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +export const spaceChecks: Check[] = [ + spaceCreateAndGet, + spaceGeneratedSkey, + spaceDuplicate, + spaceRecreate, + spaceUnsupportedPolicy, + spaceUpdateReplaces, + spaceNotOwner, + spaceUnknown, + spaceDeleteIdempotent, + spaceListSpaces, + spaceOwnerStateNotByCredential, + memberRoundTrip, + memberPolicyMismatch, + memberPublish, +]; diff --git a/packages/space-conformance/src/cli/main.ts b/packages/space-conformance/src/cli/main.ts index 67a122d..ecb94ab 100644 --- a/packages/space-conformance/src/cli/main.ts +++ b/packages/space-conformance/src/cli/main.ts @@ -3,8 +3,9 @@ * space-conformance CLI. * * space-conformance run --target https://host [--did did:...] \ - * [--handle alice.example.com] [--oauth] [--standalone-host] \ - * [--destructive] [--tier must,should] [--report out.json] [--json] + * [--plc https://plc.directory] [--handle alice.example.com] [--oauth] \ + * [--standalone-host] [--destructive] [--tier must,should] \ + * [--report out.json] [--json] * space-conformance coverage [--json] * * Operator auth (any one of): @@ -95,7 +96,7 @@ async function main(argv: string[]): Promise { process.stdout.write(`${JSON.stringify(report, null, 2)}\n`); } else { process.stdout.write( - `${report.covered.length}/${report.requirements.length} requirements covered, ${report.gaps.length} gaps\n`, + `${report.covered.length}/${report.requirements.length} requirements covered, ${report.exempt.length} exempt, ${report.gaps.length} gaps\n`, ); for (const gap of report.gaps) { process.stdout.write(` gap: ${gap.ref}\n`); @@ -103,8 +104,15 @@ async function main(argv: string[]): Promise { for (const d of report.danglingCitations) { process.stdout.write(` dangling: ${d.checkId} → ${d.ref}\n`); } + for (const e of report.staleExemptions) { + process.stdout.write(` stale exemption: ${e.ref}\n`); + } } - return report.danglingCitations.length > 0 ? 1 : 0; + return report.danglingCitations.length > 0 || + report.gaps.length > 0 || + report.staleExemptions.length > 0 + ? 1 + : 0; } if (command === "run") { @@ -113,6 +121,7 @@ async function main(argv: string[]): Promise { options: { target: { type: "string" }, did: { type: "string" }, + plc: { type: "string" }, implementation: { type: "string" }, "operator-token": { type: "string" }, handle: { type: "string" }, @@ -136,7 +145,7 @@ async function main(argv: string[]): Promise { values["operator-token"] ?? process.env.SPACE_CONFORMANCE_TOKEN; // The browser OAuth flow: no password ever enters this process, and - // the session is DPoP-bound (unusable as a plain bearer). + // the session's tokens are DPoP-bound (unusable as a plain bearer). let oauthOperator: OAuthOperator | undefined; if (values.oauth) { if (!values.handle) { @@ -168,6 +177,7 @@ async function main(argv: string[]): Promise { const report = await runConformance({ origin, did: values.did, + plcDirectory: values.plc, implementation: values.implementation, operatorToken, operatorFetch: oauthOperator?.fetch, diff --git a/packages/space-conformance/src/cli/oauth.ts b/packages/space-conformance/src/cli/oauth.ts index f180629..ed7a13b 100644 --- a/packages/space-conformance/src/cli/oauth.ts +++ b/packages/space-conformance/src/cli/oauth.ts @@ -2,13 +2,14 @@ * OAuth loopback sign-in for the CLI — the `gh auth login` shape: start an * ephemeral 127.0.0.1 callback server, register as an atproto loopback * client, open the authorization URL in the user's browser, and exchange - * the callback for a DPoP-bound session. + * the callback for a session. * * This is the auth path that involves no password at all and works against - * any PDS with an atproto OAuth server. The session's tokens are DPoP-bound - * — unusable as a plain bearer — so the run authenticates through - * `operator.fetch`, with the client library signing every request (and - * handling nonce challenges) rather than a static header. + * any PDS with an atproto OAuth server. OAuth access tokens are DPoP-bound + * (RFC 9449 — unrelated to space credentials, which carry their own HTTP + * message signature), so the run authenticates through `operator.fetch`, + * with the client library signing every request (and handling nonce + * challenges) rather than a static header. */ import { createServer } from "node:http"; @@ -22,11 +23,15 @@ import { /** * The scope the conformance run signs in with: generic repo access (for - * uploadBlob) plus full record actions and space management on the probe - * space type under the user's own authority. Mirrors the web checker. + * uploadBlob) plus every space action and management op on the probe space + * type. `authority=*` because the suite deliberately addresses spaces it + * does not own — NotSpaceOwner refusals, and writes into a foreign + * authority's space — and a `self`-only grant would turn those into scope + * refusals before the host's own check is reached. The grant is still + * confined to the probe type. Mirrors the web checker. */ -const OAUTH_SCOPE = - "atproto transition:generic space:earth.cirrus.check.space?collection=*&manage=create&manage=update&manage=delete"; +export const OAUTH_SCOPE = + "atproto transition:generic space:earth.cirrus.check.space?authority=*&collection=*&manage=create&manage=update&manage=delete"; /** How long to wait for the user to complete the browser flow. */ const CALLBACK_TIMEOUT_MS = 5 * 60 * 1000; diff --git a/packages/space-conformance/src/cli/run.ts b/packages/space-conformance/src/cli/run.ts index 088a3d0..401a76a 100644 --- a/packages/space-conformance/src/cli/run.ts +++ b/packages/space-conformance/src/cli/run.ts @@ -10,14 +10,17 @@ import { runChecks, type RunReport } from "../runner.js"; import { fullCatalog } from "../full.js"; import { KeypairIdentityProvider } from "../identity.js"; import type { Capability, CheckContext, Tier } from "../model.js"; - -/** The alpha build the suite's verifiers are pinned to (from our deps). */ -const ALPHA_BUILD = "0.0.0-spaces-alpha-20260818163953"; +import { ALPHA_BUILD } from "../alpha.js"; export interface RunConformanceOptions { origin: string; /** Target DID; resolved from the origin's did.json when omitted. */ did?: string; + /** + * PLC directory for did:plc resolution (the target's DID document and + * the KEM keys of the repos it reads). Defaults to https://plc.directory. + */ + plcDirectory?: string; implementation?: string; /** Operator bearer token; enables the operator capability when present. */ operatorToken?: string; @@ -36,9 +39,9 @@ export interface RunConformanceOptions { */ password?: string; /** - * An authenticated fetch for operator calls — a DPoP-bound OAuth session - * from the loopback sign-in, which must sign each request individually - * and so cannot be expressed as a bearer header. Takes precedence over + * An authenticated fetch for operator calls — an OAuth session from the + * loopback sign-in, whose DPoP proofs sign each request individually and + * so cannot be expressed as a bearer header. Takes precedence over * {@link operatorToken} and {@link handle}. */ operatorFetch?: typeof fetch; @@ -52,7 +55,8 @@ export interface RunConformanceOptions { * Provide harness identities. Only meaningful when the target can * resolve them — either an in-process fixture wired to the provider, or * a live deployment publishing the DIDs. A bare CLI against a remote - * host cannot, so identity-requiring checks skip by default. + * host cannot, so identity-requiring checks skip by default. With + * `didFor` the identities get resolvable DIDs the caller publishes. */ identities?: boolean; tiers?: Tier[]; @@ -103,6 +107,7 @@ export async function runConformance( origin, did, implementation: options.implementation, + ...(options.plcDirectory ? { plcDirectory: options.plcDirectory } : {}), }, fetch: doFetch, ...(options.operatorFetch diff --git a/packages/space-conformance/src/coverage.ts b/packages/space-conformance/src/coverage.ts index 707dd05..f9971df 100644 --- a/packages/space-conformance/src/coverage.ts +++ b/packages/space-conformance/src/coverage.ts @@ -6,6 +6,12 @@ * one `must` check citing it. When the weekly sync re-vendors a changed * lexicon, new methods and error names surface here as gaps the moment * they land — no human has to notice that an endpoint grew. + * + * A requirement no black-box harness can exercise is exempted explicitly, + * with the reason, in {@link coverageExemptions}. An exemption is a + * reviewed statement, not a silencer: one that names no requirement, or a + * requirement a check now covers, is reported as stale so the list cannot + * quietly outgrow its reasons. */ import type { Check } from "./model.js"; @@ -17,10 +23,37 @@ export interface CoverageRequirement { kind: "method" | "error"; } +/** + * A requirement the suite deliberately does not cover. `ref` is an exact + * requirement, or `*@error:Name` for that error on every method declaring + * it. + */ +export interface CoverageExemption { + ref: string; + reason: string; +} + +const TAKEDOWN_REASON = + "Needs a moderation or account-status action on the target (a takedown, suspension or deactivation of the account being read), which only the host's administrator can take. No black-box harness can arrange it without admin authority, and deactivating the operator's own account would end the session the run depends on."; + +export const coverageExemptions: CoverageExemption[] = [ + { ref: "*@error:RepoTakendown", reason: TAKEDOWN_REASON }, + { ref: "*@error:RepoSuspended", reason: TAKEDOWN_REASON }, + { ref: "*@error:RepoDeactivated", reason: TAKEDOWN_REASON }, +]; + export interface CoverageReport { requirements: CoverageRequirement[]; covered: Array<{ ref: string; by: string[] }>; + /** Requirements no `must` check covers and no exemption explains. */ gaps: CoverageRequirement[]; + /** Requirements excused by an exemption, with its reason. */ + exempt: Array<{ ref: string; reason: string }>; + /** + * Exemptions that excuse nothing: they match no requirement, or every + * requirement they match is covered by a check after all. + */ + staleExemptions: CoverageExemption[]; /** Lexicon citations on checks that match no requirement (typo guard). */ danglingCitations: Array<{ checkId: string; ref: string }>; } @@ -59,9 +92,17 @@ function citationRefs(check: Check): string[] { .map((c) => c.ref); } +function exemptionMatches(exemption: CoverageExemption, ref: string): boolean { + if (exemption.ref.startsWith("*@error:")) { + return ref.endsWith(exemption.ref.slice(1)) && ref.includes("@error:"); + } + return exemption.ref === ref; +} + export function coverageReport( catalog: Check[], docs: LexiconDoc[] = lexicons, + exemptions: CoverageExemption[] = coverageExemptions, ): CoverageReport { const requirements = coverageRequirements(docs); const known = new Set(requirements.map((r) => r.ref)); @@ -69,7 +110,7 @@ export function coverageReport( requirements.filter((r) => r.kind === "method").map((r) => r.ref), ); // Every vendored lexicon id, so a citation to a non-method document - // (e.g. `com.atproto.space.defs`, the signed-commit shape) is + // (e.g. `com.atproto.space.defs`, the commit shape) is // recognised as real rather than flagged as a typo. const knownDocIds = new Set(docs.map((d) => d.id)); @@ -109,11 +150,27 @@ export function coverageReport( } } - const gaps = requirements.filter((r) => !coveredBy.has(r.ref)); + const uncovered = requirements.filter((r) => !coveredBy.has(r.ref)); + const exempt: CoverageReport["exempt"] = []; + const gaps: CoverageRequirement[] = []; + const used = new Set(); + for (const requirement of uncovered) { + const exemption = exemptions.find((e) => + exemptionMatches(e, requirement.ref), + ); + if (exemption) { + used.add(exemption); + exempt.push({ ref: requirement.ref, reason: exemption.reason }); + } else { + gaps.push(requirement); + } + } return { requirements, covered: Array.from(coveredBy, ([ref, by]) => ({ ref, by })), gaps, + exempt, + staleExemptions: exemptions.filter((e) => !used.has(e)), danglingCitations: dangling, }; } diff --git a/packages/space-conformance/src/descriptors.ts b/packages/space-conformance/src/descriptors.ts index b9f2a1a..6f1e902 100644 --- a/packages/space-conformance/src/descriptors.ts +++ b/packages/space-conformance/src/descriptors.ts @@ -7,9 +7,10 @@ * omitted — an omitted check reads as conformant, the exact failure this * suite exists to prevent. * - * These are metadata only: id, tier, what the check needs. A drift test in - * the full test suite asserts they match the real `cryptoChecks` exactly, - * so adding a crypto check without a descriptor fails CI. + * These are the single source of the crypto checks' metadata: each real + * check in `./full/checks.ts` is defined by spreading its descriptor, so + * the two cannot drift. A test still pins that every descriptor has a + * check and vice versa. */ import type { Capability, Check, Citation, Tier } from "./model.js"; @@ -26,86 +27,228 @@ export interface CheckDescriptor { } const L = (ref: string): Citation => ({ source: "lexicon", ref }); +const C = (ref: string): Citation => ({ source: "changeset", ref }); -/** - * Every crypto-bound check, by metadata. Keep in the same order and with - * the same fields as `cryptoChecks` (enforced by the drift test). - */ +/** Refusals a policy may give a user it does not authorise. */ +const USER_REFUSALS = [ + L("com.atproto.space.getSpaceCredential@error:SpaceNotFound"), + L("com.atproto.space.getSpaceCredential@error:UserNotAuthorized"), + L("com.atproto.space.getSpaceCredential@error:NotAuthorized"), +]; + +/** Every crypto-bound check, by metadata, in catalog order. */ export const cryptoCheckDescriptors: CheckDescriptor[] = [ + // --- MAC verification ------------------------------------------------ { - id: "credential.round-trip", - title: "A member exchanges a delegation token for a credential and reads", + id: "mac.commit-verifies", + title: "getLatestCommit's commit has the specified shape and its MAC verifies", tier: "must", - needs: ["operator", "identities"], + needs: ["operator"], citations: [ - L("com.atproto.space.getSpaceCredential"), - L("com.atproto.space.getRecord"), + L("com.atproto.space.getLatestCommit"), + L("com.atproto.space.defs#commit"), + C("quiet-spaces-mac"), ], destructive: true, }, { - id: "credential.cross-space-refused", - title: "A credential for one space cannot read another", + id: "mac.record-verifies", + title: "getRecord's record MAC verifies and its value encodes to its cid", tier: "must", - needs: ["operator", "identities"], - citations: [L("com.atproto.space.getRecord")], + needs: ["operator"], + citations: [L("com.atproto.space.getRecord"), C("quiet-spaces-mac")], destructive: true, }, { - id: "delegation.replay-refused", - title: "A delegation token cannot be used twice", + id: "sync.oplog-folds-to-commit", + title: "listRepoOps' head commit MAC verifies and the ops fold to its data", tier: "must", - needs: ["operator", "identities"], + needs: ["operator"], citations: [ - L("com.atproto.space.getSpaceCredential@error:InvalidDelegationToken"), + L("com.atproto.space.listRepoOps"), + L("com.atproto.space.defs#commit"), ], destructive: true, }, { - id: "delegation.wrong-audience-refused", - title: "A delegation token addressed to another host is refused", + id: "sync.getrepo-star", + title: "getRepo serves a STAR archive that verifies against its MAC", tier: "must", - needs: ["operator", "identities"], + needs: ["operator"], citations: [ - L("com.atproto.space.getSpaceCredential@error:InvalidDelegationToken"), + L("com.atproto.space.getRepo"), + L("com.atproto.space.defs#commit"), + C("star-spaces-shine"), ], destructive: true, }, + // --- token signatures ------------------------------------------------ { - id: "sync.oplog-folds-to-commit", - title: "Folding the oplog reproduces the commit set-hash", + id: "credential.signed-by-authority", + title: "A credential verifies against the authority's #atproto key", + tier: "must", + needs: ["operator"], + citations: [L("com.atproto.space.getSpaceCredential"), C("plain-keys-resolve")], + destructive: true, + }, + { + id: "delegation.signed-by-user", + title: "A delegation token verifies against the user's #atproto key", + tier: "must", + needs: ["operator", "pds-delegation"], + citations: [L("com.atproto.space.getDelegationToken"), C("plain-keys-resolve")], + destructive: true, + }, + // --- migration ------------------------------------------------------- + { + id: "migration.export-space-meta", + title: "exportSpaceMeta serves the space's policy, members and writers", + tier: "must", + needs: ["operator"], + citations: [L("com.atproto.space.exportSpaceMeta"), C("olive-crabs-fly")], + destructive: true, + }, + { + id: "migration.import-space-meta", + title: "importSpaceMeta replaces the space's policy and member list", + tier: "must", + needs: ["operator"], + citations: [L("com.atproto.space.importSpaceMeta"), C("olive-crabs-fly")], + destructive: true, + }, + { + id: "migration.import-space-meta-not-owner", + title: "importSpaceMeta of another DID's space answers NotSpaceOwner", + tier: "must", + needs: ["operator"], + citations: [L("com.atproto.space.importSpaceMeta@error:NotSpaceOwner")], + }, + { + id: "migration.import-space-meta-unsupported-policy", + title: "importSpaceMeta of an unimplemented policy answers UnsupportedPolicy", + tier: "must", + needs: ["operator"], + citations: [L("com.atproto.space.importSpaceMeta@error:UnsupportedPolicy")], + destructive: true, + }, + { + id: "migration.import-repo", + title: "importRepo of a getRepo archive keeps the records and data at a new rev", tier: "must", needs: ["operator"], citations: [ - L("com.atproto.space.listRepoOps"), - L("com.atproto.space.defs"), + L("com.atproto.space.importRepo"), + L("com.atproto.space.getRepo"), + C("olive-crabs-fly"), ], destructive: true, }, { - id: "host.member-list-gates", - title: "member-list policy refuses a non-member and admits a member", + id: "migration.import-repo-space-not-found", + title: "importRepo into an own space that was never imported answers SpaceNotFound", + tier: "must", + needs: ["operator"], + citations: [L("com.atproto.space.importRepo@error:SpaceNotFound")], + }, + // --- foreign identities ---------------------------------------------- + { + id: "credential.member-gate", + title: "A memberspace refuses a non-member and a read:false member, and admits a reader", tier: "must", needs: ["operator", "identities"], citations: [ - L("com.atproto.space.getSpaceCredential@error:UserNotAuthorized"), - L("com.atproto.simplespace.addMember"), + ...USER_REFUSALS, + L("com.atproto.memberspace.putMember"), + L("com.atproto.memberspace.policy"), ], destructive: true, }, { - id: "host.delete-space-tombstone", - title: "After deleteSpace, getSpaceCredential answers SpaceDeleted", + id: "policy.personalspace-owner-only", + title: "A personalspace refuses every user but its authority", + tier: "must", + needs: ["operator", "identities"], + citations: [...USER_REFUSALS, L("com.atproto.personalspace.policy")], + destructive: true, + }, + { + id: "delegation.wrong-audience-refused", + title: "A delegation token addressed to another host is refused", + tier: "must", + needs: ["operator", "identities"], + citations: [L("com.atproto.space.getSpaceCredential@error:InvalidDelegationToken")], + destructive: true, + }, + { + id: "host.notifywrite-accepted", + title: "An authorised writer's notifyWrite enters the writer set", + tier: "must", + needs: ["operator", "identities"], + citations: [L("com.atproto.space.notifyWrite"), L("com.atproto.space.listRepos")], + destructive: true, + }, + { + id: "host.notifywrite-future-rev", + title: "notifyWrite with a repoRev beyond clock skew answers FutureRev", + tier: "must", + needs: ["operator", "identities"], + citations: [L("com.atproto.space.notifyWrite@error:FutureRev")], + destructive: true, + }, + { + id: "host.notifywrite-unknown-space", + title: "notifyWrite for a space the authority does not have answers SpaceNotFound", + tier: "must", + needs: ["operator", "identities"], + citations: [L("com.atproto.space.notifyWrite@error:SpaceNotFound")], + }, + { + id: "revocation.revoked-credential-refused", + title: "A repo host accepts a foreign authority's credential until it is revoked", tier: "must", needs: ["operator", "identities"], citations: [ - L("com.atproto.simplespace.deleteSpace"), - L("com.atproto.space.getSpaceCredential@error:SpaceDeleted"), + L("com.atproto.space.notifyCredentialRevoked"), + L("com.atproto.space.getRecord"), + C("funky-dryers-draw"), + ], + destructive: true, + }, + { + id: "revocation.error-name", + title: "A revoked credential is refused with CredentialRevoked", + tier: "should", + needs: ["operator", "identities"], + citations: [{ source: "reference", ref: "pds auth-verifier spaceCredentialAuth" }], + destructive: true, + }, + { + id: "revocation.non-authority-refused", + title: "notifyCredentialRevoked from anyone but the space authority is refused", + tier: "must", + needs: ["operator", "identities"], + citations: [L("com.atproto.space.notifyCredentialRevoked")], + destructive: true, + }, + { + id: "managedspace.checkuseraccess", + title: "A managedspace defers each credential decision to its managing app", + tier: "must", + needs: ["operator", "identities", "syncer-inbox"], + citations: [ + L("com.atproto.managedspace.checkUserAccess"), + L("com.atproto.managedspace.policy"), ], destructive: true, }, ]; +export function descriptor(id: string): CheckDescriptor { + const found = cryptoCheckDescriptors.find((d) => d.id === id); + if (!found) throw new Error(`no crypto check descriptor ${id}`); + return found; +} + /** * Turn a descriptor into a listable Check. Its run() is never invoked — * beyond the descriptor's own needs, the stub declares `alpha-libs` (the diff --git a/packages/space-conformance/src/did.ts b/packages/space-conformance/src/did.ts new file mode 100644 index 0000000..ff788ed --- /dev/null +++ b/packages/space-conformance/src/did.ts @@ -0,0 +1,130 @@ +/** + * Browser-safe DID resolution, just enough for the suite: fetch a DID + * document (did:web from its host, did:plc from a PLC directory) and read + * the keys and service entries the spaces protocol relies on — `#atproto` + * (signs space tokens), `#atproto_kem` (the repo's KEM key) and + * `#atproto_pds` (the account's host, which is also its space host). + * + * Resolution goes through `ctx.fetch`, so an in-process fixture that + * serves its own did:web document resolves without a network. A harness + * with unusual resolution supplies `ctx.resolveDid` instead. + */ + +import type { CheckContext } from "./model.js"; +import { fromBase58 } from "./encoding.js"; +import { compressP256, formatDidKey } from "./space-auth.js"; + +export const DEFAULT_PLC_DIRECTORY = "https://plc.directory"; + +export interface DidDocument { + id: string; + alsoKnownAs?: string[]; + verificationMethod?: Array<{ + id: string; + type: string; + controller?: string; + publicKeyMultibase?: string; + }>; + service?: Array<{ id: string; type: string; serviceEndpoint: unknown }>; +} + +/** The URL a DID document is fetched from, mirroring the reference resolver. */ +export function didDocumentUrl(did: string, plcDirectory?: string): string { + if (did.startsWith("did:web:")) { + const host = decodeURIComponent(did.slice("did:web:".length)); + if (host.includes(":") && !/^localhost:\d+$/.test(host)) { + throw new Error(`did:web with a path is not supported: ${did}`); + } + const scheme = host.split(":")[0] === "localhost" ? "http" : "https"; + return `${scheme}://${host}/.well-known/did.json`; + } + if (did.startsWith("did:plc:")) { + return `${(plcDirectory ?? DEFAULT_PLC_DIRECTORY).replace(/\/+$/, "")}/${did}`; + } + throw new Error(`unsupported DID method: ${did}`); +} + +export async function resolveDidDocument( + ctx: Pick, + did: string, +): Promise { + if (ctx.resolveDid) { + const doc = await ctx.resolveDid(did); + if (!doc) throw new Error(`could not resolve ${did}`); + return doc as DidDocument; + } + const url = didDocumentUrl(did, ctx.target.plcDirectory); + const res = await ctx.fetch(url, { + headers: { accept: "application/did+ld+json,application/json" }, + }); + if (!res.ok) throw new Error(`resolving ${did}: ${url} returned ${res.status}`); + const doc = (await res.json()) as DidDocument; + if (doc.id !== did) { + throw new Error(`DID document for ${did} names itself ${doc.id}`); + } + return doc; +} + +const matchesFragment = (id: string, did: string, fragment: string) => + id === `#${fragment}` || id === `${did}#${fragment}`; + +/** + * A verification method as a did:key, accepting the `Multikey` form and + * the legacy 2019 types PLC still emits (raw key bytes, no multicodec). + */ +export function verificationMethodDidKey( + doc: DidDocument, + fragment: string, +): string | undefined { + const method = (doc.verificationMethod ?? []).find((m) => + matchesFragment(m.id, doc.id, fragment), + ); + const multibase = method?.publicKeyMultibase; + if (!method || !multibase?.startsWith("z")) return undefined; + try { + if (method.type === "Multikey") { + return `did:key:${multibase}`; + } + const raw = fromBase58(multibase.slice(1)); + if (method.type === "EcdsaSecp256r1VerificationKey2019") { + return formatDidKey("ES256", raw.length === 65 ? compressP256(raw) : raw); + } + if (method.type === "EcdsaSecp256k1VerificationKey2019") { + // Point compression is curve-agnostic: parity of y, then x. + return formatDidKey("ES256K", raw.length === 65 ? compressP256(raw) : raw); + } + } catch { + return undefined; + } + return undefined; +} + +export function serviceEndpoint( + doc: DidDocument, + fragment: string, +): string | undefined { + const entry = (doc.service ?? []).find((s) => + matchesFragment(s.id, doc.id, fragment), + ); + return typeof entry?.serviceEndpoint === "string" + ? entry.serviceEndpoint + : undefined; +} + +/** + * The repo's `#atproto_kem` key, cached per run: every MAC request against + * a repo needs it, and a run reads the same few repos many times. + */ +export async function kemKeyFor( + ctx: Pick, + did: string, +): Promise { + const cacheKey = `did.kem.${did}`; + const cached = ctx.state.get(cacheKey); + if (typeof cached === "string") return cached; + const doc = await resolveDidDocument(ctx, did); + const kem = verificationMethodDidKey(doc, "atproto_kem"); + if (!kem) throw new Error(`${did} publishes no #atproto_kem key`); + ctx.state.set(cacheKey, kem); + return kem; +} diff --git a/packages/space-conformance/src/dpop.ts b/packages/space-conformance/src/dpop.ts deleted file mode 100644 index d465435..0000000 --- a/packages/space-conformance/src/dpop.ts +++ /dev/null @@ -1,96 +0,0 @@ -/** - * Browser-safe DPoP: WebCrypto ES256 keys and RFC 9449 proofs. - * - * This is deliberately dependency-free so the checks that only need a - * DPoP-bound credential exchange — the operator's own delegation → - * credential → read flow — can run in a browser bundle. The proof format - * mirrors `@atproto/space`'s `createDpopProof` exactly (same claims, same - * htu normalization, same `ath` hash), which the fixture adapters and the - * reference matrix verify end-to-end: a proof the servers reject fails - * those runs loudly. - */ - -import type { DpopKey } from "./model.js"; - -function b64url(bytes: Uint8Array): string { - let bin = ""; - for (const b of bytes) bin += String.fromCharCode(b); - return btoa(bin).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); -} - -/** - * WebCrypto ES256 DPoP key implementing the minimal surface a DPoP proof - * needs (`bareJwk`, `algorithms`, `createJwt`) plus the RFC 7638 - * thumbprint. Hand-rolled to avoid `@atproto/jwk-jose`, whose bundled jose - * resolves to its Node build under the workers test pool and cannot sign. - */ -export async function createDpopKey(): Promise { - const pair = await crypto.subtle.generateKey( - { name: "ECDSA", namedCurve: "P-256" }, - true, - ["sign"], - ); - const jwk = await crypto.subtle.exportKey("jwk", pair.publicKey); - // Canonical JWK for an EC key, RFC 7638 member order. - const bareJwk = { crv: jwk.crv, kty: jwk.kty, x: jwk.x, y: jwk.y } as Record< - string, - unknown - >; - const thumbInput = new TextEncoder().encode(JSON.stringify(bareJwk)); - const jkt = b64url( - new Uint8Array(await crypto.subtle.digest("SHA-256", thumbInput)), - ); - const encode = (obj: unknown) => - b64url(new TextEncoder().encode(JSON.stringify(obj))); - return { - bareJwk, - algorithms: ["ES256"], - jkt, - async createJwt(header, payload) { - const input = `${encode(header)}.${encode(payload)}`; - const sig = new Uint8Array( - await crypto.subtle.sign( - { name: "ECDSA", hash: "SHA-256" }, - pair.privateKey, - new TextEncoder().encode(input), - ), - ); - return `${input}.${b64url(sig)}`; - }, - }; -} - -/** - * An RFC 9449 DPoP proof over `key`, matching the reference verifier: - * header `{alg, typ: "dpop+jwt", jwk}`; claims `jti` (random), `htm`, - * `htu` (query and fragment stripped, RFC 9449 §4.2), `iat`, and — only - * when presenting a credential — `ath`, the base64url SHA-256 of it. - */ -export async function createDpopProofJwt( - key: DpopKey, - opts: { htm: string; htu: string; credential?: string }, -): Promise { - const htuUrl = new URL(opts.htu); - const jti = b64url(crypto.getRandomValues(new Uint8Array(16))); - const ath = - opts.credential !== undefined - ? b64url( - new Uint8Array( - await crypto.subtle.digest( - "SHA-256", - new TextEncoder().encode(opts.credential), - ), - ), - ) - : undefined; - return key.createJwt( - { alg: "ES256", typ: "dpop+jwt", jwk: key.bareJwk }, - { - jti, - htm: opts.htm, - htu: htuUrl.origin + htuUrl.pathname, - ...(ath !== undefined ? { ath } : {}), - iat: Math.floor(Date.now() / 1000), - }, - ); -} diff --git a/packages/space-conformance/src/encoding.ts b/packages/space-conformance/src/encoding.ts new file mode 100644 index 0000000..b78c902 --- /dev/null +++ b/packages/space-conformance/src/encoding.ts @@ -0,0 +1,152 @@ +/** + * Dependency-free byte encodings shared by the browser-safe helpers: + * base64 (padded, unpadded and url-safe), base58btc for did:key, base32 + * for CIDs, and a few byte utilities. Kept here so the browser catalog + * never pulls a multiformats or noble dependency for a dozen lines of code. + */ + +export const utf8 = (s: string): Uint8Array => new TextEncoder().encode(s); + +export function concatBytes(parts: Uint8Array[]): Uint8Array { + const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); + let offset = 0; + for (const part of parts) { + out.set(part, offset); + offset += part.length; + } + return out; +} + +export function bytesEqual(a: Uint8Array, b: Uint8Array): boolean { + return a.length === b.length && a.every((byte, i) => byte === b[i]); +} + +export function toBase64(bytes: Uint8Array): string { + let bin = ""; + for (const b of bytes) bin += String.fromCharCode(b); + return btoa(bin); +} + +export const toBase64Url = (bytes: Uint8Array): string => + toBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); + +/** Decode base64 or base64url, padded or not. */ +export function fromBase64(input: string): Uint8Array { + let s = input.replace(/-/g, "+").replace(/_/g, "/").replace(/=+$/, ""); + s = s.padEnd(Math.ceil(s.length / 4) * 4, "="); + const bin = atob(s); + const out = new Uint8Array(bin.length); + for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); + return out; +} + +const B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + +export function toBase58(bytes: Uint8Array): string { + let zeros = 0; + while (zeros < bytes.length && bytes[zeros] === 0) zeros++; + let n = 0n; + for (const b of bytes) n = n * 256n + BigInt(b); + let out = ""; + while (n > 0n) { + out = B58[Number(n % 58n)] + out; + n /= 58n; + } + return "1".repeat(zeros) + out; +} + +export function fromBase58(input: string): Uint8Array { + let zeros = 0; + while (zeros < input.length && input[zeros] === "1") zeros++; + let n = 0n; + for (const ch of input) { + const value = B58.indexOf(ch); + if (value < 0) throw new Error(`invalid base58 character: ${ch}`); + n = n * 58n + BigInt(value); + } + const body: number[] = []; + while (n > 0n) { + body.unshift(Number(n % 256n)); + n /= 256n; + } + return new Uint8Array([...new Array(zeros).fill(0), ...body]); +} + +const B32 = "abcdefghijklmnopqrstuvwxyz234567"; + +export function toBase32(bytes: Uint8Array): string { + let out = ""; + let bits = 0; + let value = 0; + for (const byte of bytes) { + value = (value << 8) | byte; + bits += 8; + while (bits >= 5) { + out += B32[(value >>> (bits - 5)) & 31]; + bits -= 5; + } + } + if (bits > 0) out += B32[(value << (5 - bits)) & 31]; + return out; +} + +/** A CIDv1 (raw codec, sha2-256) for some bytes — a well-formed blob CID. */ +export async function rawCid(bytes: Uint8Array): Promise { + const digest = new Uint8Array( + await crypto.subtle.digest("SHA-256", bytes as BufferSource), + ); + // version 1, codec raw (0x55), multihash sha2-256 (0x12) of 32 bytes + return `b${toBase32(concatBytes([new Uint8Array([0x01, 0x55, 0x12, 0x20]), digest]))}`; +} + +export async function sha256(bytes: Uint8Array): Promise { + return new Uint8Array( + await crypto.subtle.digest("SHA-256", bytes as BufferSource), + ); +} + +/** Decode a compact JWT's header and payload without verifying it. */ +export function decodeJwt(jwt: string): { + header: Record; + payload: Record; +} { + const parts = jwt.split("."); + if (parts.length !== 3) throw new Error("not a compact JWT"); + const decode = (part: string) => + JSON.parse(new TextDecoder().decode(fromBase64(part))) as Record< + string, + unknown + >; + return { header: decode(parts[0]!), payload: decode(parts[1]!) }; +} + +/** `$bytes` JSON wire form → bytes, or undefined if it isn't one. */ +export function lexBytes(value: unknown): Uint8Array | undefined { + if ( + value && + typeof value === "object" && + typeof (value as { $bytes?: unknown }).$bytes === "string" + ) { + return fromBase64((value as { $bytes: string }).$bytes); + } + return undefined; +} + +const TID_CHARS = "234567abcdefghijklmnopqrstuvwxyz"; +const TID_RE = /^[234567abcdefghij][234567abcdefghijklmnopqrstuvwxyz]{12}$/; + +export const isTid = (value: unknown): value is string => + typeof value === "string" && TID_RE.test(value); + +/** A TID for a given time in microseconds since the epoch (clock id 0). */ +export function tidAt(micros: bigint): string { + let n = (micros << 10n) & 0x7fffffffffffffffn; + let out = ""; + for (let i = 0; i < 13; i++) { + out = TID_CHARS[Number(n & 31n)] + out; + n >>= 5n; + } + return out; +} + +export const tidNow = (): string => tidAt(BigInt(Date.now()) * 1000n); diff --git a/packages/space-conformance/src/full.ts b/packages/space-conformance/src/full.ts index 0968598..0c7c99e 100644 --- a/packages/space-conformance/src/full.ts +++ b/packages/space-conformance/src/full.ts @@ -13,16 +13,25 @@ import { baseChecks } from "./checks/base.js"; import { operatorChecks } from "./checks/operator.js"; import { cryptoChecks } from "./full/checks.js"; -export { KeypairIdentityProvider, createDpopKey } from "./identity.js"; -export type { HarnessIdentityWithKey } from "./identity.js"; +export { KeypairIdentityProvider, createCredentialKey } from "./identity.js"; +export type { + CredentialKey, + HarnessIdentityWithKey, + IdentityDocumentOptions, +} from "./identity.js"; export { createProbeSpace, deleteProbeSpace, obtainCredential, obtainCredentialViaDelegation, + obtainPublicCredential, + credentialCall, credentialGet, + requestCredential, + mintCredential, mintDelegation, + serviceJwt, operatorCreateRecord, } from "./full/helpers.js"; export type { Credential, ProbeSpace } from "./full/helpers.js"; diff --git a/packages/space-conformance/src/full/checks.ts b/packages/space-conformance/src/full/checks.ts index fb3511c..423b8ba 100644 --- a/packages/space-conformance/src/full/checks.ts +++ b/packages/space-conformance/src/full/checks.ts @@ -2,408 +2,718 @@ * The crypto-bound check catalog: the checks that genuinely need the * alpha libs or harness-held foreign identities, and nothing else — every * check an operator session can run with plain fetch + WebCrypto lives in - * `../checks/operator.js` instead, browser included. + * `../checks/` instead, browser included. * * What keeps a check here: - * - `identities`: the harness plays a reader/member who is not the - * operator, minting delegation tokens the target must verify by - * resolving the reader's DID — only an in-process fixture with an - * injected resolver can arrange that. - * - `LtHash`: folding the oplog needs the lattice set-hash from - * `@atproto/space`, whose bundle pulls node-only dependencies. + * - verifying what a target serves — commit and record MACs, STAR + * archives, token signatures — with the reference library; + * - building archives (space meta, repo STARs) to import; + * - `identities`: the harness plays a reader, a writer's PDS or a foreign + * space authority, minting tokens the target must verify by resolving + * that party's DID. + * + * Each check's metadata comes from `../descriptors.ts`, the dependency-free + * list the browser catalog shows as "not testable here". */ -import { LtHash } from "@atproto/space"; -import { fromBase64 } from "@atproto/lex-data"; +import { + RepoCommit, + readRepoStar, + readSpaceMetaStar, + serializeRepo, + serializeSpaceMeta, + spaceHostAud, + verifyCommit, + verifyRecord, + verifyRepoStarFull, + verifySpaceToken, + type SpaceMetaArchive, +} from "@atproto/space"; +import { parseCid } from "@atproto/lex-data"; import { defineCheck } from "../registry.js"; -import { asOperator, xrpcGet, xrpcPost } from "../http.js"; -import { fail, pass, type Check } from "../model.js"; +import { descriptor } from "../descriptors.js"; +import { + asOperator, + operatorFetch, + xrpcGet, + xrpcPost, + xrpcPostBytes, +} from "../http.js"; +import { fail, pass, type Check, type CheckContext, type CheckOutcome } from "../model.js"; +import { bytesEqual, decodeJwt, isTid, lexBytes, tidAt, tidNow, toBase64 } from "../encoding.js"; +import { resolveDidDocument, verificationMethodDidKey } from "../did.js"; +import { createCredentialKey } from "../space-auth.js"; import { + FOREIGN_DID, + POST, + PROBE_TYPE, createProbeSpace, + credentialCall, credentialGet, deleteProbeSpace, - obtainCredential, + describe, + managedspace, + memberspace, + mustCreateRecord, + obtainPublicCredential, operatorCreateRecord, + personalspace, + probeSkey, + publicRead, + unknownSpaceUri, + type Credential, +} from "../checks/probe.js"; +import { fakeDid } from "../checks/space.js"; +import { + collectBytes, + commitFromJson, + mintCredential, + mintDelegation, + obtainCredential, + responseMac, + serviceJwt, } from "./helpers.js"; -import { POST, note } from "../checks/operator.js"; - -// --- credential / delegation (foreign identities) ---------------------- - -const credentialRoundTrip = defineCheck({ - id: "credential.round-trip", - title: "A member exchanges a delegation token for a credential and reads", - tier: "must", - citations: [ - { source: "lexicon", ref: "com.atproto.space.getSpaceCredential" }, - { source: "lexicon", ref: "com.atproto.space.getRecord" }, - ], - needs: ["operator", "identities"], - destructive: true, - async run(ctx) { - const reader = await ctx.identities!.identity("reader"); - const space = await createProbeSpace(ctx); + +const crypto$ = (id: string, run: (ctx: CheckContext) => Promise): Check => + defineCheck({ ...descriptor(id), run }); + +/** A public-read space with two records and a credential for it. */ +async function withPublicSpace( + ctx: CheckContext, + fn: (space: string, credential: Credential) => Promise, +): Promise { + const space = await createProbeSpace(ctx, publicRead()); + try { + await mustCreateRecord(ctx, space.uri, "a", "one"); + await mustCreateRecord(ctx, space.uri, "b", "two"); + return await fn(space.uri, await obtainPublicCredential(ctx, space.uri)); + } finally { + await deleteProbeSpace(ctx, space.uri); + } +} + +// --- MAC verification --------------------------------------------------- + +const macCommit = crypto$("mac.commit-verifies", (ctx) => + withPublicSpace(ctx, async (space, credential) => { + const res = await credentialGet(ctx, credential, "com.atproto.space.getLatestCommit", { + space, + repo: ctx.target.did, + }); + if (res.status !== 200) return fail(`getLatestCommit ${describe(res)}`, res.json); + const raw = (res.json as { commit?: Record }).commit ?? {}; + const keys = Object.keys(raw).sort().join(","); + if (keys !== "data,repo,rev,space,ver") { + return fail(`commit carries {${keys}}, expected exactly {data,repo,rev,space,ver}`, raw); + } + const commit = commitFromJson(raw); + if (!commit || commit.ver !== 1 || !isTid(commit.rev) || commit.data.length !== 32) { + return fail("commit fields malformed (ver 1, TID rev, 32-byte data)", raw); + } + const mac = responseMac(res); + if (!mac) return fail("no parseable Atproto-Space-Mac header on a MAC'd read"); + return verifyCommit(commit, { space, repo: ctx.target.did, sharedSecret: res.sharedSecret!, mac }) + ? pass("commit shape as specified; its MAC verifies") + : fail("the commit MAC does not verify", raw); + }), +); + +const macRecord = crypto$("mac.record-verifies", (ctx) => + withPublicSpace(ctx, async (space, credential) => { + const res = await credentialGet(ctx, credential, "com.atproto.space.getRecord", { + space, + repo: ctx.target.did, + collection: POST, + rkey: "a", + }); + if (res.status !== 200) return fail(`getRecord ${describe(res)}`, res.json); + const record = res.json as { uri: string; cid: string; value: Record }; + const mac = responseMac(res); + if (!mac) return fail("no parseable Atproto-Space-Mac header on a MAC'd read"); + const ok = await verifyRecord(record as never, { + uri: record.uri, + sharedSecret: res.sharedSecret!, + mac, + }); + return ok + ? pass("record MAC verifies over uri and cid; value encodes to cid") + : fail("verifyRecord rejected the response", record); + }), +); + +const oplogFolds = crypto$("sync.oplog-folds-to-commit", (ctx) => + withPublicSpace(ctx, async (space, credential) => { + // One more op that replaces a record, so the fold exercises `prev`. + await xrpcPost(asOperator(ctx), "com.atproto.space.putRecord", { + space, + repo: ctx.target.did, + collection: POST, + rkey: "a", + record: { $type: POST, text: "one, again" }, + }); + const res = await credentialGet(ctx, credential, "com.atproto.space.listRepoOps", { + space, + repo: ctx.target.did, + }); + if (res.status !== 200) return fail(`listRepoOps ${describe(res)}`, res.json); + const body = res.json as { + ops: Array<{ collection: string; rkey: string; cid: string | null; prev: string | null }>; + commit?: unknown; + }; + const commit = commitFromJson(body.commit); + if (!commit) return fail("listRepoOps reached the head but returned no commit", body); + const mac = responseMac(res); + if (!mac) return fail("a page with the commit carried no Atproto-Space-Mac header"); + if (!verifyCommit(commit, { space, repo: ctx.target.did, sharedSecret: res.sharedSecret!, mac })) { + return fail("the head commit's MAC does not verify"); + } + const folded = new RepoCommit().applyOps( + body.ops.map((op) => ({ + collection: op.collection, + rkey: op.rkey, + cid: op.cid ? parseCid(op.cid) : null, + prev: op.prev ? parseCid(op.prev) : null, + })) as never, + ); + return folded.matches(commit) + ? pass(`${body.ops.length} ops fold to the MAC-verified commit data`) + : fail("the folded oplog does not match the commit data"); + }), +); + +const getRepoStar = crypto$("sync.getrepo-star", (ctx) => + withPublicSpace(ctx, async (space, credential) => { + const res = await credentialGet(ctx, credential, "com.atproto.space.getRepo", { + space, + repo: ctx.target.did, + }); + if (res.status !== 200) return fail(`getRepo ${describe(res)}`, res.json); + const type = res.headers.get("Content-Type") ?? ""; + if (!type.includes("application/octet-stream")) return fail(`getRepo content-type was ${type}`); + const mac = responseMac(res); + if (!mac) return fail("no parseable Atproto-Space-Mac header on a MAC'd getRepo"); + const bytes = new Uint8Array(await res.response.arrayBuffer()); try { - await operatorCreateRecord( - ctx, - space.uri, - POST, - "shared", - note("visible"), - ); - // member-list policy: authorize the reader first. - await xrpcPost(asOperator(ctx), "com.atproto.simplespace.addMember", { - space: space.uri, - did: reader.did, + const { records } = await verifyRepoStarFull([bytes], { + space, + repo: ctx.target.did, + sharedSecret: res.sharedSecret!, + mac, }); - const { result, credential } = await obtainCredential( - ctx, - reader, - space.uri, - ); - if (!credential) { - return fail( - `getSpaceCredential ${result.status} ${result.error ?? ""}`, - result.json, - ); - } - const read = await credentialGet( - ctx, - credential, - "com.atproto.space.getRecord", - { - space: space.uri, - repo: ctx.target.did, - collection: POST, - rkey: "shared", - }, - ); - return read.status === 200 - ? pass("credential read the space") - : fail( - `credential read failed: ${read.status} ${read.error ?? ""}`, - read.json, - ); - } finally { - await deleteProbeSpace(ctx, space.uri); + const rkeys = records.map((r) => `${r.collection}/${r.rkey}`).sort(); + return rkeys.join(",") === `${POST}/a,${POST}/b` + ? pass("STAR archive verified against its MAC; both records present") + : fail(`archive verified but held ${rkeys.join(", ") || "no records"}`); + } catch (err) { + return fail(`verifyRepoStarFull rejected the archive: ${(err as Error).message}`); } - }, + }), +); + +// --- token signatures ------------------------------------------------- + +async function atprotoKey(ctx: CheckContext, did: string): Promise { + const key = verificationMethodDidKey(await resolveDidDocument(ctx, did), "atproto"); + if (!key) throw new Error(`${did} publishes no #atproto key`); + return key; +} + +const credentialSigned = crypto$("credential.signed-by-authority", async (ctx) => { + const space = await createProbeSpace(ctx, publicRead()); + try { + const credential = await obtainPublicCredential(ctx, space.uri); + try { + await verifySpaceToken("credential", credential.credential, { + getSigningKey: (iss) => atprotoKey(ctx, iss), + sub: space.uri, + }); + return pass("verifies against the authority's #atproto key"); + } catch (err) { + return fail(`credential did not verify: ${(err as Error).message}`); + } + } finally { + await deleteProbeSpace(ctx, space.uri); + } }); -const credentialCrossSpace = defineCheck({ - id: "credential.cross-space-refused", - title: "A credential for one space cannot read another", - tier: "must", - citations: [{ source: "lexicon", ref: "com.atproto.space.getRecord" }], - needs: ["operator", "identities"], - destructive: true, - async run(ctx) { - const reader = await ctx.identities!.identity("reader"); - const publicPolicy = { - $type: "com.atproto.simplespace.defs#publicPolicy", - }; - const spaceA = await createProbeSpace(ctx, publicPolicy); - const spaceB = await createProbeSpace(ctx, publicPolicy); +const delegationSigned = crypto$("delegation.signed-by-user", async (ctx) => { + const space = await createProbeSpace(ctx, memberspace()); + try { + const res = await xrpcGet(asOperator(ctx), "com.atproto.space.getDelegationToken", { space: space.uri }); + if (res.status !== 200) return fail(`getDelegationToken ${describe(res)}`, res.json); try { - await operatorCreateRecord(ctx, spaceB.uri, POST, "secret", note("b")); - const { credential } = await obtainCredential(ctx, reader, spaceA.uri); - if (!credential) return fail("could not obtain a credential for space A"); - const cross = await credentialGet( - ctx, - credential, - "com.atproto.space.getRecord", - { - space: spaceB.uri, - repo: ctx.target.did, - collection: POST, - rkey: "secret", - }, - ); - return cross.status === 200 - ? fail("space-A credential read space B", cross.json) - : pass( - `cross-space read refused with ${cross.status} ${cross.error ?? ""}`, - ); - } finally { - await deleteProbeSpace(ctx, spaceA.uri); - await deleteProbeSpace(ctx, spaceB.uri); + await verifySpaceToken("delegation", (res.json as { token: string }).token, { + getSigningKey: (iss) => atprotoKey(ctx, iss), + aud: spaceHostAud(ctx.target.did), + sub: space.uri, + }); + return pass("verifies against the user's #atproto key"); + } catch (err) { + return fail(`delegation token did not verify: ${(err as Error).message}`); } - }, + } finally { + await deleteProbeSpace(ctx, space.uri); + } }); -const delegationReplay = defineCheck({ - id: "delegation.replay-refused", - title: "A delegation token cannot be used twice", - tier: "must", - citations: [ - { - source: "lexicon", - ref: "com.atproto.space.getSpaceCredential@error:InvalidDelegationToken", - }, - ], - needs: ["operator", "identities"], - destructive: true, - async run(ctx) { - const reader = await ctx.identities!.identity("reader"); - const space = await createProbeSpace(ctx, { - $type: "com.atproto.simplespace.defs#publicPolicy", +// --- migration ---------------------------------------------------------- + +async function exportMeta(ctx: CheckContext, space: string) { + const res = await operatorFetch(ctx)( + `${ctx.target.origin}/xrpc/com.atproto.space.exportSpaceMeta?space=${encodeURIComponent(space)}`, + ); + if (res.status !== 200) { + throw new Error(`exportSpaceMeta ${res.status} ${await res.text().catch(() => "")}`); + } + return { + type: res.headers.get("Content-Type") ?? "", + archive: await readSpaceMetaStar([new Uint8Array(await res.arrayBuffer())]), + }; +} + +const importMeta = async (ctx: CheckContext, archive: SpaceMetaArchive) => + xrpcPostBytes( + asOperator(ctx), + "com.atproto.space.importSpaceMeta", + await collectBytes(serializeSpaceMeta(archive)), + ); + +const memberKey = (did: string) => `com.atproto.memberspace.member/${did}`; + +const exportSpaceMeta = crypto$("migration.export-space-meta", async (ctx) => { + const space = await createProbeSpace(ctx, memberspace({ publicWrite: true })); + const member = fakeDid(); + try { + await xrpcPost(asOperator(ctx), "com.atproto.memberspace.putMember", { + space: space.uri, + did: member, + read: true, + write: false, }); - try { - // Reuse one delegation token twice by minting it once. obtainCredential - // mints a fresh token each call, so drive the exchange directly. - const { createDpopProof, createSpaceToken, spaceHostAud } = - await import("@atproto/space"); - const delegation = await createSpaceToken( - "delegation", + await mustCreateRecord(ctx, space.uri, "a"); + const { type, archive } = await exportMeta(ctx, space.uri); + const problems: string[] = []; + if (!type.includes("application/octet-stream")) problems.push(`content-type ${type}`); + if (archive.space !== space.uri) problems.push(`space ${archive.space}`); + if (archive.policy.$type !== "com.atproto.memberspace.policy") problems.push(`policy ${String(archive.policy.$type)}`); + const entry = archive.policyState.find((e) => e.key === memberKey(member)); + if (!entry || entry.value.read !== true || entry.value.write !== false) problems.push("member entry missing or wrong"); + if (!archive.writers.some((w) => w.did === ctx.target.did)) problems.push("the authority is not in the writer set"); + return problems.length + ? fail(problems.join("; "), archive) + : pass("archive carries the policy, the member and the writer set"); + } catch (err) { + return fail((err as Error).message); + } finally { + await deleteProbeSpace(ctx, space.uri); + } +}); + +const importSpaceMeta = crypto$("migration.import-space-meta", async (ctx) => { + const space = await createProbeSpace(ctx, memberspace()); + const before = fakeDid(); + const after = fakeDid(); + try { + await xrpcPost(asOperator(ctx), "com.atproto.memberspace.putMember", { + space: space.uri, + did: before, + read: true, + write: true, + }); + const { archive } = await exportMeta(ctx, space.uri); + // Import a changed configuration over the space: it replaces, not merges. + const imported = await importMeta(ctx, { + ...archive, + policy: { $type: "com.atproto.memberspace.policy", publicRead: true }, + policyState: [ { - iss: reader.did, - sub: space.uri, - aud: spaceHostAud(ctx.target.did), + key: memberKey(after), + value: { $type: "com.atproto.memberspace.member", read: true, write: false }, }, - { - jwtAlg: reader.jwtAlg, - sign: (b: Uint8Array) => reader.sign(b), - } as never, - ); - const exchange = async () => { - const dpopKey = await ctx.identities!.dpopKey(); - const proof = await createDpopProof(dpopKey as never, { - htm: "POST", - htu: `${ctx.target.origin}/xrpc/com.atproto.space.getSpaceCredential`, - }); - return xrpcPost( - ctx, - "com.atproto.space.getSpaceCredential", - { space: space.uri }, - { Authorization: `Bearer ${delegation}`, DPoP: proof }, - ); - }; - const first = await exchange(); - if (first.status !== 200) { - return fail( - `first exchange failed (${first.status}); cannot test replay`, - first.json, - ); - } - const second = await exchange(); - return second.status === 200 - ? fail("a replayed delegation token was accepted") - : pass(`replay refused with ${second.status} ${second.error ?? ""}`); - } finally { - await deleteProbeSpace(ctx, space.uri); - } - }, + ], + }); + if (imported.status !== 200) return fail(`importSpaceMeta ${describe(imported)}`, imported.json); + const got = await xrpcGet(asOperator(ctx), "com.atproto.space.getSpace", { space: space.uri }); + const policy = (got.json as { policy?: { publicRead?: boolean } } | undefined)?.policy; + const list = await xrpcGet(asOperator(ctx), "com.atproto.memberspace.listMembers", { space: space.uri }); + const dids = ((list.json as { members?: Array<{ did: string }> } | undefined)?.members ?? []).map((m) => m.did); + if (policy?.publicRead !== true) return fail("getSpace does not reflect the imported policy", got.json); + return dids.includes(after) && !dids.includes(before) + ? pass("imported policy and member list replaced the old ones") + : fail(`members after import: ${dids.join(", ") || "none"}`, list.json); + } catch (err) { + return fail((err as Error).message); + } finally { + await deleteProbeSpace(ctx, space.uri); + } +}); + +const importMetaNotOwner = crypto$("migration.import-space-meta-not-owner", async (ctx) => { + const res = await importMeta(ctx, { + space: unknownSpaceUri(FOREIGN_DID) as never, + policy: { $type: "com.atproto.personalspace.policy" }, + policyState: [], + writers: [], + }); + return res.error === "NotSpaceOwner" + ? pass("answered NotSpaceOwner") + : fail(`answered ${describe(res)}, expected NotSpaceOwner`, res.json); +}); + +const importMetaUnsupported = crypto$("migration.import-space-meta-unsupported-policy", async (ctx) => { + const space = unknownSpaceUri(ctx.target.did); + const res = await importMeta(ctx, { + space: space as never, + policy: { $type: "com.example.mysteryPolicy" }, + policyState: [], + writers: [], + }); + if (res.status === 200) await deleteProbeSpace(ctx, space); + return res.error === "UnsupportedPolicy" + ? pass("answered UnsupportedPolicy") + : fail(`answered ${describe(res)}, expected UnsupportedPolicy`, res.json); }); -const delegationWrongAud = defineCheck({ - id: "delegation.wrong-audience-refused", - title: "A delegation token addressed to another host is refused", - tier: "must", - citations: [ - { - source: "lexicon", - ref: "com.atproto.space.getSpaceCredential@error:InvalidDelegationToken", - }, - ], - needs: ["operator", "identities"], - destructive: true, - async run(ctx) { - const reader = await ctx.identities!.identity("reader"); - const space = await createProbeSpace(ctx, { - $type: "com.atproto.simplespace.defs#publicPolicy", +async function ownRepoArchive(ctx: CheckContext, space: string): Promise { + const res = await operatorFetch(ctx)( + `${ctx.target.origin}/xrpc/com.atproto.space.getRepo?space=${encodeURIComponent(space)}&repo=${encodeURIComponent(ctx.target.did)}`, + ); + if (res.status !== 200) throw new Error(`getRepo ${res.status}`); + return new Uint8Array(await res.arrayBuffer()); +} + +const importRepo = crypto$("migration.import-repo", async (ctx) => { + const space = await createProbeSpace(ctx, personalspace()); + try { + await mustCreateRecord(ctx, space.uri, "a", "one"); + await mustCreateRecord(ctx, space.uri, "b", "two"); + const bytes = await ownRepoArchive(ctx, space.uri); + const exported = await readRepoStar([bytes]); + const commit = exported.commit; + await exported[Symbol.asyncDispose](); + // Change the repo after export, so the import visibly replaces it. + await mustCreateRecord(ctx, space.uri, "c", "three"); + const res = await xrpcPostBytes(asOperator(ctx), "com.atproto.space.importRepo", bytes); + if (res.status !== 200) return fail(`importRepo ${describe(res)}`, res.json); + const list = await xrpcGet(asOperator(ctx), "com.atproto.space.listRecords", { + space: space.uri, + repo: ctx.target.did, }); - try { - // Positive control: with the correct audience the same reader is - // admitted (public policy), so a refusal below is attributable to - // the audience and not to, say, an unresolvable reader DID. - const control = await obtainCredential(ctx, reader, space.uri); - if (!control.credential) { - return fail( - `correct-aud control failed (${control.result.status} ${control.result.error ?? ""}); cannot attribute the wrong-aud refusal`, - control.result.json, - ); - } - const { result } = await obtainCredential(ctx, reader, space.uri, { - audOverride: "did:web:someone-else.example#atproto_space_host", - }); - if (result.status === 200) { - return fail("a token with the wrong audience was accepted"); - } - return result.error === "InvalidDelegationToken" - ? pass("wrong-aud token refused with InvalidDelegationToken") - : pass( - `wrong-aud token refused (${result.status} ${result.error ?? ""}); InvalidDelegationToken preferred`, - ); - } finally { - await deleteProbeSpace(ctx, space.uri); - } - }, + const rkeys = ((list.json as { records?: Array<{ rkey: string }> } | undefined)?.records ?? []) + .map((r) => r.rkey) + .sort(); + if (rkeys.join(",") !== "a,b") return fail(`records after import: ${rkeys.join(",")}`, list.json); + const latest = await xrpcGet(asOperator(ctx), "com.atproto.space.getLatestCommit", { + space: space.uri, + repo: ctx.target.did, + }); + const now = commitFromJson((latest.json as { commit?: unknown } | undefined)?.commit); + if (!now) return fail(`getLatestCommit after import ${describe(latest)}`, latest.json); + if (!bytesEqual(now.data, commit.data)) return fail("commit data changed across the import"); + return now.rev > commit.rev + ? pass("records replaced from the archive; same data, new rev") + : fail(`rev ${now.rev} did not advance past the archive's ${commit.rev}`); + } catch (err) { + return fail((err as Error).message); + } finally { + await deleteProbeSpace(ctx, space.uri); + } }); -// --- sync -------------------------------------------------------------- - -const syncOplogFolds = defineCheck({ - id: "sync.oplog-folds-to-commit", - // "set-hash", not "signed": this check verifies the host's ops fold to the - // commit hash the host serves — an internal-consistency property (catching - // oplog/commit divergence, e.g. compaction bugs). It does not verify the - // commit *signature*; no check does yet, and claiming so would overstate. - title: "Folding the oplog reproduces the commit set-hash", - tier: "must", - citations: [ - { source: "lexicon", ref: "com.atproto.space.listRepoOps" }, - { source: "lexicon", ref: "com.atproto.space.defs" }, - ], - needs: ["operator"], - destructive: true, - async run(ctx) { - const space = await createProbeSpace(ctx); - try { - await operatorCreateRecord(ctx, space.uri, POST, "a", note("1")); - await operatorCreateRecord(ctx, space.uri, POST, "b", note("2")); - const res = await xrpcGet( - asOperator(ctx), - "com.atproto.space.listRepoOps", - { space: space.uri, repo: ctx.target.did }, - ); - if (res.status !== 200) { - return fail(`listRepoOps ${res.status} ${res.error ?? ""}`, res.json); - } - const body = res.json as { - ops: Array<{ - collection: string; - rkey: string; - cid: string | null; - prev: string | null; - }>; - commit?: { hash: { $bytes: string } }; - }; - if (!body.commit) { - return fail("listRepoOps reached the head but returned no commit"); - } - const setHash = new LtHash(); - for (const op of body.ops) { - if (op.prev) setHash.remove(`${op.collection}/${op.rkey}/${op.prev}`); - if (op.cid) setHash.add(`${op.collection}/${op.rkey}/${op.cid}`); - } - const folded = setHash.digest(); - const claimed = fromBase64(body.commit.hash.$bytes); - const equal = - folded.length === claimed.length && - folded.every((byte, i) => byte === claimed[i]); - return equal - ? pass("folded oplog matches the commit hash") - : fail("folded oplog does not match the commit hash"); - } finally { - await deleteProbeSpace(ctx, space.uri); - } - }, +const importRepoNotFound = crypto$("migration.import-repo-space-not-found", async (ctx) => { + // A well-formed archive of an empty repo in an own space this host has + // never heard of: the authority's space must be imported first. + const space = `at://${ctx.target.did}/space/${PROBE_TYPE}/${probeSkey()}`; + const commit = new RepoCommit().toCommit({ + space: space as never, + repo: ctx.target.did as never, + rev: tidNow(), + }); + const res = await xrpcPostBytes( + asOperator(ctx), + "com.atproto.space.importRepo", + await collectBytes(serializeRepo(commit, [])), + ); + if (res.status === 200) await deleteProbeSpace(ctx, space); + return res.error === "SpaceNotFound" + ? pass("answered SpaceNotFound") + : fail(`answered ${describe(res)}, expected SpaceNotFound`, res.json); }); -// --- host role --------------------------------------------------------- - -const hostMemberGate = defineCheck({ - id: "host.member-list-gates", - title: "member-list policy refuses a non-member and admits a member", - tier: "must", - citations: [ - { - source: "lexicon", - ref: "com.atproto.space.getSpaceCredential@error:UserNotAuthorized", - }, - { source: "lexicon", ref: "com.atproto.simplespace.addMember" }, - ], - needs: ["operator", "identities"], - destructive: true, - async run(ctx) { - const reader = await ctx.identities!.identity("reader"); - const space = await createProbeSpace(ctx); - try { - const before = await obtainCredential(ctx, reader, space.uri); - if (before.credential) { - return fail( - "a non-member obtained a credential under member-list policy", - ); - } - await xrpcPost(asOperator(ctx), "com.atproto.simplespace.addMember", { - space: space.uri, - did: reader.did, - }); - const after = await obtainCredential(ctx, reader, space.uri); - return after.credential - ? pass( - `non-member refused (${before.result.error ?? before.result.status}), member admitted`, - ) - : fail( - `a member was refused: ${after.result.status} ${after.result.error ?? ""}`, - ); - } finally { - await deleteProbeSpace(ctx, space.uri); +// --- foreign identities -------------------------------------------------- + +const isUserRefusal = (error?: string) => + error === "SpaceNotFound" || error === "UserNotAuthorized" || error === "NotAuthorized"; + +const memberGate = crypto$("credential.member-gate", async (ctx) => { + const reader = await ctx.identities!.identity("reader"); + const space = await createProbeSpace(ctx, memberspace()); + const put = (read: boolean) => + xrpcPost(asOperator(ctx), "com.atproto.memberspace.putMember", { + space: space.uri, + did: reader.did, + read, + write: false, + }); + try { + await mustCreateRecord(ctx, space.uri, "shared", "members only"); + const stranger = await obtainCredential(ctx, reader, space.uri); + if (stranger.credential) return fail("a non-member obtained a credential"); + if (!isUserRefusal(stranger.result.error)) { + return fail(`non-member refused with ${describe(stranger.result)}; expected SpaceNotFound, UserNotAuthorized or NotAuthorized`); } - }, + await put(false); + const writeOnly = await obtainCredential(ctx, reader, space.uri); + if (writeOnly.credential) return fail("a member with read: false obtained a credential"); + await put(true); + const member = await obtainCredential(ctx, reader, space.uri); + if (!member.credential) return fail(`a reader was refused: ${describe(member.result)}`, member.result.json); + const read = await credentialGet(ctx, member.credential, "com.atproto.space.getRecord", { + space: space.uri, + repo: ctx.target.did, + collection: POST, + rkey: "shared", + }); + return read.status === 200 + ? pass(`non-member refused (${stranger.result.error}), read:false refused, reader admitted and read`) + : fail(`the reader's credential could not read: ${describe(read)}`, read.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } }); -const hostDeleteTombstone = defineCheck({ - id: "host.delete-space-tombstone", - title: "After deleteSpace, getSpaceCredential answers SpaceDeleted", - tier: "must", - citations: [ - { source: "lexicon", ref: "com.atproto.simplespace.deleteSpace" }, - { - source: "lexicon", - ref: "com.atproto.space.getSpaceCredential@error:SpaceDeleted", - }, - ], - needs: ["operator", "identities"], - destructive: true, - async run(ctx) { - const reader = await ctx.identities!.identity("reader"); - const space = await createProbeSpace(ctx, { - $type: "com.atproto.simplespace.defs#publicPolicy", +const personalOnly = crypto$("policy.personalspace-owner-only", async (ctx) => { + const reader = await ctx.identities!.identity("reader"); + const space = await createProbeSpace(ctx, personalspace()); + try { + const res = await obtainCredential(ctx, reader, space.uri); + if (res.credential) return fail("a personalspace issued a credential to another user"); + return isUserRefusal(res.result.error) + ? pass(`refused with ${res.result.error}`) + : fail(`refused with ${describe(res.result)}; expected SpaceNotFound, UserNotAuthorized or NotAuthorized`); + } finally { + await deleteProbeSpace(ctx, space.uri); + } +}); + +const delegationWrongAud = crypto$("delegation.wrong-audience-refused", async (ctx) => { + const reader = await ctx.identities!.identity("reader"); + const space = await createProbeSpace(ctx, memberspace()); + try { + await xrpcPost(asOperator(ctx), "com.atproto.memberspace.putMember", { + space: space.uri, + did: reader.did, + read: true, + write: false, }); - // Positive control: before deletion the reader can obtain a - // credential. Without it, a target that simply can't resolve the - // reader (so credentials always fail) would pass the tombstone check - // without the deletion ever being exercised. - const before = await obtainCredential(ctx, reader, space.uri); - if (!before.credential) { - await deleteProbeSpace(ctx, space.uri); - return fail( - `could not obtain a credential before deletion (${before.result.status} ${before.result.error ?? ""}); cannot test the tombstone`, - before.result.json, - ); + // Positive control: with the right audience the reader is admitted, so + // the refusal below is the audience's and not an unresolvable reader. + const control = await obtainCredential(ctx, reader, space.uri); + if (!control.credential) { + return fail(`correct-aud control failed (${describe(control.result)}); cannot attribute the wrong-aud refusal`); } - const del = await xrpcPost( - asOperator(ctx), - "com.atproto.simplespace.deleteSpace", - { space: space.uri }, - ); - if (del.status !== 200) { - return fail( - `deleteSpace failed (${del.status} ${del.error ?? ""})`, - del.json, - ); + const { result, credential } = await obtainCredential(ctx, reader, space.uri, { + audOverride: `${FOREIGN_DID}#atproto_pds`, + }); + if (credential) return fail("a token addressed to another host was accepted"); + return result.error === "InvalidDelegationToken" + ? pass("refused with InvalidDelegationToken") + : fail(`refused with ${describe(result)}, expected InvalidDelegationToken`); + } finally { + await deleteProbeSpace(ctx, space.uri); + } +}); + +async function notifyWrite( + ctx: CheckContext, + writer: { did: string; jwtAlg: string; sign(b: Uint8Array): Promise }, + space: string, + repoRev: string, + data: Uint8Array, +) { + const jwt = await serviceJwt(writer, { + aud: spaceHostAud(ctx.target.did), + lxm: "com.atproto.space.notifyWrite", + }); + return xrpcPost( + ctx, + "com.atproto.space.notifyWrite", + { space, repo: writer.did, repoRev, data: { $bytes: toBase64(data).replace(/=+$/, "") } }, + { Authorization: `Bearer ${jwt}` }, + ); +} + +const notifyAccepted = crypto$("host.notifywrite-accepted", async (ctx) => { + const writer = await ctx.identities!.identity("writer"); + const space = await createProbeSpace(ctx, memberspace({ publicRead: true })); + try { + await xrpcPost(asOperator(ctx), "com.atproto.memberspace.putMember", { + space: space.uri, + did: writer.did, + read: false, + write: true, + }); + const repoRev = tidNow(); + const data = globalThis.crypto.getRandomValues(new Uint8Array(32)); + const res = await notifyWrite(ctx, writer, space.uri, repoRev, data); + if (res.status !== 200) return fail(`notifyWrite ${describe(res)}`, res.json); + const credential = await obtainPublicCredential(ctx, space.uri); + const list = await credentialCall(ctx, credential, "com.atproto.space.listRepos", { + params: { space: space.uri }, + audience: ctx.target.did, + }); + const entry = ((list.json as { repos?: Array<{ did: string; repoRev: string; data: unknown }> } | undefined) + ?.repos ?? []).find((r) => r.did === writer.did); + if (!entry) return fail("the notified writer is not in listRepos", list.json); + const listed = lexBytes(entry.data); + return entry.repoRev === repoRev && listed && bytesEqual(listed, data) + ? pass("accepted; listRepos reports the notified repoRev and data") + : fail("listRepos entry does not match the notification", entry); + } finally { + await deleteProbeSpace(ctx, space.uri); + } +}); + +const notifyFuture = crypto$("host.notifywrite-future-rev", async (ctx) => { + const writer = await ctx.identities!.identity("writer"); + const space = await createProbeSpace(ctx, memberspace({ publicWrite: true })); + try { + const hourAhead = BigInt(Date.now() + 60 * 60 * 1000) * 1000n; + const res = await notifyWrite(ctx, writer, space.uri, tidAt(hourAhead), new Uint8Array(32)); + return res.error === "FutureRev" + ? pass("a repoRev an hour ahead answered FutureRev") + : fail(`answered ${describe(res)}, expected FutureRev`, res.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } +}); + +const notifyUnknown = crypto$("host.notifywrite-unknown-space", async (ctx) => { + const writer = await ctx.identities!.identity("writer"); + const res = await notifyWrite(ctx, writer, unknownSpaceUri(ctx.target.did), tidNow(), new Uint8Array(32)); + return res.error === "SpaceNotFound" + ? pass("answered SpaceNotFound") + : fail(`answered ${describe(res)}, expected SpaceNotFound`, res.json); +}); + +/** + * The revocation flow: a harness identity plays a foreign space authority, + * the operator writes into that space (as a member's PDS would), and the + * authority's credential reads the operator's repo — until revoked. + */ +async function revocationFlow( + ctx: CheckContext, + revoker: "authority" | "stranger", +): Promise<{ before: number; after?: { status: number; error?: string }; revoke?: { status: number; error?: string }; detail?: string }> { + const authority = await ctx.identities!.identity("authority"); + const space = `at://${authority.did}/space/${PROBE_TYPE}/${probeSkey()}`; + const write = await operatorCreateRecord(ctx, space, POST, "shared", { $type: POST, text: "for the authority" }); + if (write.status !== 200) return { before: write.status, detail: `operator write into a foreign space: ${describe(write)}` }; + const key = await createCredentialKey(); + const credential: Credential = { + credential: await mintCredential(authority, space, key.did), + key, + space, + }; + const read = () => + credentialGet(ctx, credential, "com.atproto.space.getRecord", { + space, + repo: ctx.target.did, + collection: POST, + rkey: "shared", + }); + const before = await read(); + if (before.status !== 200) return { before: before.status, detail: `foreign authority's credential could not read: ${describe(before)}` }; + const signer = revoker === "authority" ? authority : await ctx.identities!.identity("stranger"); + const jwt = await serviceJwt(signer, { aud: ctx.target.did, lxm: "com.atproto.space.notifyCredentialRevoked" }); + const { payload } = decodeJwt(credential.credential); + const revoke = await xrpcPost( + ctx, + "com.atproto.space.notifyCredentialRevoked", + { space, credentials: [payload.jti] }, + { Authorization: `Bearer ${jwt}` }, + ); + const after = await read(); + return { before: 200, revoke, after }; +} + +const revocationRefused = crypto$("revocation.revoked-credential-refused", async (ctx) => { + const flow = await revocationFlow(ctx, "authority"); + if (flow.detail) return fail(flow.detail); + if (flow.revoke!.status !== 200) return fail(`notifyCredentialRevoked ${flow.revoke!.status} ${flow.revoke!.error ?? ""}`); + return flow.after!.status >= 400 && flow.after!.status < 500 + ? pass(`foreign credential read 200; after revocation refused (${flow.after!.status} ${flow.after!.error ?? ""})`) + : fail(`a revoked credential still read (${flow.after!.status})`); +}); + +const revocationName = crypto$("revocation.error-name", async (ctx) => { + const flow = await revocationFlow(ctx, "authority"); + if (flow.detail) return fail(flow.detail); + return flow.after!.error === "CredentialRevoked" + ? pass("refused with CredentialRevoked") + : fail(`refused with ${flow.after!.status} ${flow.after!.error ?? ""}`); +}); + +const revocationStranger = crypto$("revocation.non-authority-refused", async (ctx) => { + const flow = await revocationFlow(ctx, "stranger"); + if (flow.detail) return fail(flow.detail); + if (flow.revoke!.status === 200) return fail("accepted a revocation signed by someone other than the authority"); + return flow.after!.status === 200 + ? pass(`stranger's revocation refused (${flow.revoke!.status} ${flow.revoke!.error ?? ""}); credential still reads`) + : fail(`the revocation was refused but the credential stopped working (${flow.after!.status})`); +}); + +const managedSpace = crypto$("managedspace.checkuseraccess", async (ctx) => { + const inbox = ctx.syncerInbox!; + const reader = await ctx.identities!.identity("reader"); + const lxm = "com.atproto.managedspace.checkUserAccess"; + let decision = false; + inbox.respond(lxm, () => ({ authorized: decision })); + const space = await createProbeSpace(ctx, managedspace(inbox.service)); + try { + const since = Date.now(); + const denied = await obtainCredential(ctx, reader, space.uri); + if (denied.credential) return fail("issued a credential the managing app refused"); + const asked = await inbox.waitFor((d) => d.lxm === lxm && d.receivedAt >= since, 5_000); + if (!asked) return fail(`the managing app was never asked (${describe(denied.result)})`); + const p = asked.params ?? {}; + if (p.space !== space.uri || p.user !== reader.did || p.access !== "read") { + return fail("checkUserAccess carried the wrong params", p); } - const { result } = await obtainCredential(ctx, reader, space.uri); - if (result.status === 200) - return fail("a deleted space still issued a credential"); - // The proposal specifies SpaceDeleted as the durable tombstone signal - // so a syncer that missed the notification learns to drop its copy. - return result.error === "SpaceDeleted" - ? pass("getSpaceCredential answered SpaceDeleted") - : fail( - `deleted space refused with ${result.error} (${result.status}), expected SpaceDeleted`, - result.json, - ); - }, + if (!asked.authorization?.startsWith("Bearer ")) return fail("checkUserAccess was sent without service auth"); + decision = true; + const allowed = await obtainCredential(ctx, reader, space.uri); + return allowed.credential + ? pass(`asked the managing app (space, user, access=read); refused on false (${denied.result.error}), issued on true`) + : fail(`the managing app authorised but the credential was refused: ${describe(allowed.result)}`); + } finally { + inbox.respond(lxm, undefined); + await deleteProbeSpace(ctx, space.uri); + } }); -/** The crypto-bound catalog: identity checks plus the LtHash fold. */ +/** The crypto-bound catalog, in descriptor order. */ export const cryptoChecks: Check[] = [ - credentialRoundTrip, - credentialCrossSpace, - delegationReplay, + macCommit, + macRecord, + oplogFolds, + getRepoStar, + credentialSigned, + delegationSigned, + exportSpaceMeta, + importSpaceMeta, + importMetaNotOwner, + importMetaUnsupported, + importRepo, + importRepoNotFound, + memberGate, + personalOnly, delegationWrongAud, - syncOplogFolds, - hostMemberGate, - hostDeleteTombstone, + notifyAccepted, + notifyFuture, + notifyUnknown, + revocationRefused, + revocationName, + revocationStranger, + managedSpace, ]; diff --git a/packages/space-conformance/src/full/helpers.ts b/packages/space-conformance/src/full/helpers.ts index 7532eea..fcea8e9 100644 --- a/packages/space-conformance/src/full/helpers.ts +++ b/packages/space-conformance/src/full/helpers.ts @@ -1,37 +1,48 @@ /** - * Crypto-bound helpers for the identity checks: minting delegation tokens - * as harness-held reader/writer identities, and exchanging them for - * credentials — built on `@atproto/space`'s token primitives. + * Crypto-bound helpers: tokens minted as harness-held identities + * (delegation tokens as a reader, credentials as a foreign authority, + * service auth as a writer's PDS) and the reference library's verifiers + * for the MACs, commits and archives a target serves. * - * Note on using the reference lib to mint: these helpers generate tokens - * with the same library the target is expected to interoperate with. That - * is deliberate — the point of a credential check is that the *target's* - * verification accepts a correctly-formed token, and "correctly formed" is - * defined by the reference lib every implementation must interop with. - * - * Everything an operator session can do without foreign identities — - * probe spaces, record writes, the self credential flow — lives in the - * browser-safe `../checks/operator.js` and is re-exported here so the - * full entry keeps its historical surface. + * Using the reference library to mint and verify is deliberate: "correctly + * formed" is defined by the library every implementation must interoperate + * with, so a token it mints is one the target must accept, and an artefact + * it rejects is one no other implementation could consume. */ -import { createSpaceToken, spaceHostAud } from "@atproto/space"; +import { + COMMIT_MAC_TYPE, + RECORD_MAC_TYPE, + createSpaceToken, + parseMacHeader, + spaceHostAud, + type Commit, +} from "@atproto/space"; import type { CheckContext, HarnessIdentity } from "../model.js"; -import { createDpopProofJwt } from "../dpop.js"; -import { xrpcPost, type XrpcResult } from "../http.js"; -import type { Credential } from "../checks/operator.js"; +import { toBase64Url, utf8, lexBytes } from "../encoding.js"; +import { MAC_HEADER } from "../space-auth.js"; +import { + requestCredential, + spaceAuthority, + type Credential, + type CredentialResult, +} from "../checks/probe.js"; +import type { XrpcResult } from "../http.js"; export { createProbeSpace, deleteProbeSpace, operatorCreateRecord, obtainCredentialViaDelegation, + obtainPublicCredential, credentialGet, -} from "../checks/operator.js"; -export type { Credential, ProbeSpace } from "../checks/operator.js"; + credentialCall, + requestCredential, +} from "../checks/probe.js"; +export type { Credential, ProbeSpace } from "../checks/probe.js"; /** Adapt a harness identity to the `Keypair` surface token minting uses. */ -function keypairFor(identity: HarnessIdentity) { +export function keypairFor(identity: HarnessIdentity) { return { jwtAlg: identity.jwtAlg, sign: (bytes: Uint8Array) => identity.sign(bytes), @@ -39,9 +50,11 @@ function keypairFor(identity: HarnessIdentity) { } as never; } -/** Mint a delegation token for `identity` against `space`. */ -export async function mintDelegation( - ctx: CheckContext, +/** + * Mint a delegation token for `identity` against `space`, addressed (by + * default) to the space authority's `#atproto_pds` — the space host. + */ +export function mintDelegation( identity: HarnessIdentity, space: string, audOverride?: string, @@ -51,16 +64,16 @@ export async function mintDelegation( { iss: identity.did, sub: space, - aud: audOverride ?? spaceHostAud(ctx.target.did), + aud: audOverride ?? spaceHostAud(spaceAuthority(space)), }, keypairFor(identity), ); } /** - * The full obtain flow: mint a delegation token as `identity`, exchange it - * at the target for a credential bound to a fresh DPoP key. Returns the - * raw XrpcResult alongside the credential so callers can assert on refusals. + * The full obtain flow as a foreign user: mint a delegation token as + * `identity` and exchange it for a credential bound to a fresh P-256 key. + * Returns the raw result so callers can assert on refusals. */ export async function obtainCredential( ctx: CheckContext, @@ -68,33 +81,83 @@ export async function obtainCredential( space: string, opts: { audOverride?: string; clientAttestation?: string } = {}, ): Promise<{ result: XrpcResult; credential?: Credential }> { - if (!ctx.identities) - throw new Error("obtainCredential needs an identity provider"); - const dpopKey = await ctx.identities.dpopKey(); - const delegation = await mintDelegation( - ctx, - identity, - space, - opts.audOverride, - ); - const proof = await createDpopProofJwt(dpopKey, { - htm: "POST", - htu: `${ctx.target.origin}/xrpc/com.atproto.space.getSpaceCredential`, + return requestCredential(ctx, space, { + delegationToken: await mintDelegation(identity, space, opts.audOverride), + ...(opts.clientAttestation ? { clientAttestation: opts.clientAttestation } : {}), }); - const result = await xrpcPost( - ctx, - "com.atproto.space.getSpaceCredential", - { - space, - ...(opts.clientAttestation - ? { clientAttestation: opts.clientAttestation } - : {}), - }, - { Authorization: `Bearer ${delegation}`, DPoP: proof }, +} + +/** + * Mint a credential as the authority of `space` — a harness identity + * playing a foreign space authority whose credentials a repo host must + * honour for reads of its repos in that space. + */ +export async function mintCredential( + authority: HarnessIdentity, + space: string, + keyDid: string, +): Promise { + return createSpaceToken( + "credential", + { iss: authority.did, sub: space, keyId: keyDid as `did:${string}:${string}` }, + keypairFor(authority), ); - if (result.status === 200) { - const credential = (result.json as { credential: string }).credential; - return { result, credential: { credential, dpopKey } }; +} + +/** An inter-service auth JWT (`lxm`-scoped), signed as `identity`. */ +export async function serviceJwt( + identity: HarnessIdentity, + opts: { aud: string; lxm: string; expiresInSec?: number }, +): Promise { + const iat = Math.floor(Date.now() / 1000); + const header = { typ: "JWT", alg: identity.jwtAlg }; + const payload = { + iss: identity.did, + aud: opts.aud, + iat, + exp: iat + (opts.expiresInSec ?? 60), + lxm: opts.lxm, + jti: toBase64Url(crypto.getRandomValues(new Uint8Array(16))), + }; + const input = `${toBase64Url(utf8(JSON.stringify(header)))}.${toBase64Url(utf8(JSON.stringify(payload)))}`; + const sig = await identity.sign(utf8(input)); + return `${input}.${toBase64Url(sig)}`; +} + +/** A commit as the wire JSON carries it, with `data` decoded. */ +export function commitFromJson(value: unknown): Commit | undefined { + if (!value || typeof value !== "object") return undefined; + const raw = value as Record; + const data = lexBytes(raw.data); + if (!data) return undefined; + return { ...(raw as Omit), data } as Commit; +} + +/** The MAC a credentialed response carried, or undefined. */ +export function responseMac(res: CredentialResult): Uint8Array | undefined { + const header = res.headers.get(MAC_HEADER); + if (!header) return undefined; + try { + return parseMacHeader( + header, + res.macType === RECORD_MAC_TYPE ? RECORD_MAC_TYPE : COMMIT_MAC_TYPE, + ); + } catch { + return undefined; + } +} + +/** Drain an async byte stream (an archive serializer) into one buffer. */ +export async function collectBytes( + chunks: AsyncIterable, +): Promise { + const parts: Uint8Array[] = []; + for await (const chunk of chunks) parts.push(chunk); + const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0)); + let offset = 0; + for (const part of parts) { + out.set(part, offset); + offset += part.length; } - return { result }; + return out; } diff --git a/packages/space-conformance/src/http.ts b/packages/space-conformance/src/http.ts index e978181..4b4692a 100644 --- a/packages/space-conformance/src/http.ts +++ b/packages/space-conformance/src/http.ts @@ -28,7 +28,7 @@ export interface XrpcResult { response: Response; } -async function toResult(response: Response): Promise { +export async function toResult(response: Response): Promise { const contentType = response.headers.get("Content-Type") ?? ""; let json: unknown; let error: string | undefined; @@ -95,8 +95,8 @@ export async function operatorHeaders( /** * A fetch that carries the operator's credentials: the operator's own - * signing fetch when it has one (a DPoP-bound OAuth session must sign each - * request individually), otherwise the transport fetch with + * signing fetch when it has one (an OAuth session's DPoP proof must sign + * each request individually), otherwise the transport fetch with * `authorize`-injected headers. With no operator at all it falls back to * the plain transport — the runner skips operator-needing checks then, so * that path is only reached by checks that can also run anonymously. @@ -121,3 +121,20 @@ export function operatorFetch(ctx: CheckContext): typeof fetch { export function asOperator(ctx: CheckContext): CheckContext { return { ...ctx, fetch: operatorFetch(ctx) }; } + +/** POST raw bytes (an archive upload) to an XRPC procedure. */ +export async function xrpcPostBytes( + ctx: CheckContext, + nsid: string, + bytes: Uint8Array, + headers?: HeadersInit, +): Promise { + const merged = new Headers(headers); + merged.set("Content-Type", "application/octet-stream"); + const response = await ctx.fetch(xrpcUrl(ctx.target.origin, nsid), { + method: "POST", + headers: merged, + body: bytes as BodyInit, + }); + return toResult(response); +} diff --git a/packages/space-conformance/src/identity.ts b/packages/space-conformance/src/identity.ts index 43858c4..772a8f0 100644 --- a/packages/space-conformance/src/identity.ts +++ b/packages/space-conformance/src/identity.ts @@ -1,48 +1,69 @@ /** - * Harness identities and DPoP keys. + * Harness identities. * - * Multi-party checks need the harness to play a reader, a writer and a - * syncer — parties that aren't the target's operator. Each only needs a - * DID with a resolvable key the target can verify against, so the provider - * mints keypairs and the harness signs as those parties. + * Multi-party checks need the harness to play parties that aren't the + * target's operator: a reader (signing delegation tokens), a writer's PDS + * (signing notifyWrite service auth) and a foreign space authority + * (signing credentials and revocations). Each needs a DID the target can + * resolve to the key the harness holds. * - * Two facts the caller must arrange (they can't be solved in-library): - * the target has to be able to *resolve* each identity's DID to its key. - * In an in-process fixture the caller wires the target's key resolver to - * this provider's `didKey(role)`; against a live target the identities - * must be published (did:web under the checker's origin, or did:plc on a - * reachable directory). The provider is resolution-agnostic — it only - * holds keys and signs. + * Resolution is the caller's to arrange — it can't be solved in-library: + * + * - In an in-process fixture, wire the target's DID resolver to + * {@link KeypairIdentityProvider.didDocument} (or to `didKey` for a + * did:key-only resolver). + * - Against a live target, publish each identity: serve + * {@link KeypairIdentityProvider.didDocument} at a did:web the target + * can fetch (the reference matrix runs one tiny server per identity on + * `did:web:localhost%3A`), or register a did:plc. + * + * What a published identity document must carry, per the alpha: a + * `#atproto` verification method (it signs every space token and service + * JWT) and — for an identity that receives calls, such as a syncer inbox + * or a managing app — an `#atproto_pds` service, which is how a bare DID + * service identifier resolves to an endpoint. Identities never serve + * repos, so they publish no `#atproto_kem`. */ import { Secp256k1Keypair } from "@atproto/crypto"; -import type { DpopKey, HarnessIdentity, IdentityProvider } from "./model.js"; -import { createDpopKey } from "./dpop.js"; +import type { HarnessIdentity, IdentityProvider } from "./model.js"; -// DPoP keys are WebCrypto and browser-safe, so they live in ./dpop.ts; -// re-exported here because the full entry has always offered them. -export { createDpopKey } from "./dpop.js"; +// Credential keys are WebCrypto and browser-safe, so they live in +// ./space-auth.ts; re-exported here for the full entry's callers. +export { createCredentialKey } from "./space-auth.js"; +export type { CredentialKey } from "./space-auth.js"; export interface HarnessIdentityWithKey extends HarnessIdentity { - /** The did:key form of the identity's signing key, for resolver wiring. */ + /** The did:key form of the identity's `#atproto` key, for resolver wiring. */ didKey: string; } +export interface IdentityDocumentOptions { + /** Publish an `#atproto_pds` service at this endpoint (inboxes, managing apps). */ + serviceEndpoint?: string; + /** A handle to list in `alsoKnownAs`. */ + handle?: string; +} + /** * An identity provider backed by secp256k1 keypairs. Identities are keyed * by role label and reused within a run, so "reader" is stable across the * checks that mint and then present its tokens. * - * `didAt` lets the caller give each identity a resolvable DID (e.g. - * `did:web:checker.test:actors:reader`); when omitted, the identity's DID - * is its own `did:key`, which only works against a target whose resolver - * this provider is wired into. + * `didFor` gives each identity a resolvable DID (e.g. + * `did:web:localhost%3A61234`), and may be async — a harness can start the + * server that will publish the document there. When omitted, the + * identity's DID is its own `did:key`, which only works against a target + * whose resolver this provider is wired into. */ export class KeypairIdentityProvider implements IdentityProvider { private cache = new Map>(); constructor( - private readonly didAt?: (role: string, didKey: string) => string, + private readonly didFor?: ( + role: string, + didKey: string, + ) => string | Promise, ) {} identity(role: string): Promise { @@ -57,7 +78,7 @@ export class KeypairIdentityProvider implements IdentityProvider { private async mint(role: string): Promise { const keypair = await Secp256k1Keypair.create({ exportable: true }); const didKey = keypair.did(); - const did = this.didAt ? this.didAt(role, didKey) : didKey; + const did = this.didFor ? await this.didFor(role, didKey) : didKey; return { did, didKey, @@ -66,8 +87,42 @@ export class KeypairIdentityProvider implements IdentityProvider { }; } - dpopKey(): Promise { - return createDpopKey(); + /** + * The DID document a resolvable identity must publish: its `#atproto` + * key as a Multikey and, optionally, the `#atproto_pds` service the + * target delivers to. + */ + static didDocument( + identity: Pick, + opts: IdentityDocumentOptions = {}, + ): Record { + return { + "@context": [ + "https://www.w3.org/ns/did/v1", + "https://w3id.org/security/multikey/v1", + ], + id: identity.did, + ...(opts.handle ? { alsoKnownAs: [`at://${opts.handle}`] } : {}), + verificationMethod: [ + { + id: `${identity.did}#atproto`, + type: "Multikey", + controller: identity.did, + publicKeyMultibase: identity.didKey.slice("did:key:".length), + }, + ], + ...(opts.serviceEndpoint + ? { + service: [ + { + id: "#atproto_pds", + type: "AtprotoPersonalDataServer", + serviceEndpoint: opts.serviceEndpoint, + }, + ], + } + : {}), + }; } /** All minted identities so far, for resolver wiring in fixtures. */ diff --git a/packages/space-conformance/src/index.ts b/packages/space-conformance/src/index.ts index df38f9e..7debfb1 100644 --- a/packages/space-conformance/src/index.ts +++ b/packages/space-conformance/src/index.ts @@ -5,7 +5,7 @@ * One check model, multiple runners: the same tiered, citation-carrying * checks run in-process against a local implementation, from a CLI against * a live host, or inside a web checker. `must` checks cite specified - * behavior; `should` checks are calibrated against the reference + * behaviour; `should` checks are calibrated against the reference * implementation; `info` checks never fail anyone. */ @@ -18,7 +18,6 @@ export type { CheckResult, CheckStatus, Citation, - DpopKey, HarnessIdentity, IdentityProvider, InboxDelivery, @@ -40,16 +39,49 @@ export { deleteProbeSpace, operatorCreateRecord, obtainCredentialViaDelegation, + obtainPublicCredential, + requestCredential, + credentialCall, credentialGet, + memberspace, + personalspace, + managedspace, + publicRead, +} from "./checks/operator.js"; +export type { + Credential, + CredentialCallOptions, + CredentialResult, + Policy, + ProbeSpace, } from "./checks/operator.js"; -export type { Credential, ProbeSpace } from "./checks/operator.js"; -export { createDpopKey, createDpopProofJwt } from "./dpop.js"; -export { readCarHeader } from "./car.js"; +export { + createCredentialKey, + encapsulate, + formatWantMacHeader, + isP256DidKey, + spaceSigHeaders, + COMMIT_MAC_TYPE, + RECORD_MAC_TYPE, + SPACE_CREDENTIAL_SCHEME, +} from "./space-auth.js"; +export type { CredentialKey, MacType } from "./space-auth.js"; +export { + DEFAULT_PLC_DIRECTORY, + didDocumentUrl, + resolveDidDocument, + serviceEndpoint, + verificationMethodDidKey, +} from "./did.js"; +export type { DidDocument } from "./did.js"; export { cryptoCheckDescriptors, descriptorToStub } from "./descriptors.js"; export type { CheckDescriptor } from "./descriptors.js"; +export { ALPHA_BUILD } from "./alpha.js"; +export { knownChangesets } from "./changesets.js"; + import { baseChecks as base } from "./checks/base.js"; import { operatorChecks as operator } from "./checks/operator.js"; import { buildCatalog as build } from "./registry.js"; @@ -61,12 +93,12 @@ import { /** * A catalog for transports that cannot run the crypto-bound checks (the * browser). The base checks run anonymously; the operator checks — writes, - * simplespace, blobs, the self credential flow — are real and run whenever - * the harness supplies an operator session (an OAuth sign-in in the web - * checker). Only the checks that genuinely need the alpha crypto libs or - * foreign identities are metadata stubs, reported as skipped ("not - * testable here") — listed rather than omitted, so a green run never - * silently reads as fuller conformance than it proved. + * space management, blobs, credential issuance and presentation — are real + * and run whenever the harness supplies an operator session (an OAuth + * sign-in in the web checker). Only the checks that genuinely need the + * alpha crypto libs or foreign identities are metadata stubs, reported as + * skipped ("not testable here") — listed rather than omitted, so a green + * run never silently reads as fuller conformance than it proved. */ export const browserCatalog = build([ ...base, @@ -77,8 +109,16 @@ export const browserCatalog = build([ export { renderReport, runChecks } from "./runner.js"; export type { RunOptions, RunReport } from "./runner.js"; -export { coverageReport, coverageRequirements } from "./coverage.js"; -export type { CoverageReport, CoverageRequirement } from "./coverage.js"; +export { + coverageExemptions, + coverageReport, + coverageRequirements, +} from "./coverage.js"; +export type { + CoverageExemption, + CoverageReport, + CoverageRequirement, +} from "./coverage.js"; export { lexicons } from "./lexicons.js"; export type { LexiconDoc } from "./lexicons.js"; diff --git a/packages/space-conformance/src/model.ts b/packages/space-conformance/src/model.ts index 186c185..a257261 100644 --- a/packages/space-conformance/src/model.ts +++ b/packages/space-conformance/src/model.ts @@ -19,12 +19,24 @@ export type Tier = "must" | "should" | "info"; /** Where a check's claim comes from. Every `must` check needs at least one. */ export interface Citation { - /** e.g. "lexicon", "proposal", "pds-design-spec", "reference" */ - source: "lexicon" | "proposal" | "pds-design-spec" | "reference"; + /** + * - `lexicon`: a vendored lexicon (machine-checked by the coverage + * generator). + * - `proposal` / `pds-design-spec`: the upstream prose specs. + * - `changeset`: an upstream changeset (`.changeset/.md` on the + * alpha branch). For alpha protocol mechanics no lexicon can express — + * the credential HTTP signature, the MAC exchange, key discovery — the + * changeset is the alpha's only normative prose, so it is a citable + * source for a `must`. + * - `reference`: what the reference implementation happens to do. Fine + * for a `should`; never enough on its own for a `must`. + */ + source: "lexicon" | "proposal" | "pds-design-spec" | "changeset" | "reference"; /** * Locator within the source: a lexicon id (optionally `#def` or - * `@error:Name`), a proposal section anchor, or a design-spec heading. - * Lexicon locators are machine-checked by the coverage generator. + * `@error:Name`), a proposal section anchor, a design-spec heading or a + * changeset name. Lexicon locators are machine-checked by the coverage + * generator. */ ref: string; } @@ -39,15 +51,16 @@ export interface Citation { * scopes — only harnesses that can drive the target's consent flow. * - `identities`: harness-controlled DIDs with resolvable documents and * held keys, for playing reader/writer roles. - * - `syncer-inbox`: an HTTPS endpoint the harness controls that the - * target can deliver notifications to. + * - `syncer-inbox`: a service the harness controls, named by a DID the + * target can resolve, that the target can deliver notifications to (as a + * syncer) and query (as a `managedspace` managing app). * - `pds-blobs`: the target is a full PDS implementing * `com.atproto.repo.uploadBlob` and `com.atproto.sync.getBlob` — needed * to prove a space blob is not served publicly. A standalone space host, * or an isolated space-routes fixture, does not provide it. * - `pds-delegation`: the target implements * `com.atproto.space.getDelegationToken`, so the operator can obtain a - * credential for its own space (the bulletin self-flow) with no + * credential for its own non-public space (the self-flow) with no * harness-held reader key. A space-routes fixture does not provide it. * - `alpha-libs`: the transport can execute the alpha crypto libraries * (`@atproto/space`), whose bundle pulls node-only dependencies. Real @@ -83,48 +96,53 @@ export interface CheckResult { durationMs?: number; } -/** An identity the harness controls: a resolvable DID plus its keys. */ +/** + * An identity the harness controls: a DID the target can resolve, plus the + * key behind its `#atproto` verification method. The harness signs as this + * party — delegation tokens as a reader, service auth as a writer's PDS, + * credentials and revocations as a foreign space authority. + */ export interface HarnessIdentity { did: string; - /** Sign bytes with the identity's atproto signing key (ES256K/ES256). */ + /** Sign bytes with the identity's `#atproto` key (ES256K/ES256), compact. */ sign(bytes: Uint8Array): Promise; /** JWT `alg` for {@link sign}. */ jwtAlg: string; } -/** A DPoP key the harness controls (always ES256, per the proposal). */ -export interface DpopKey { - bareJwk: Record; - /** Algorithms the key supports; `["ES256"]` for DPoP. */ - algorithms: readonly string[]; - /** RFC 7638 thumbprint of {@link bareJwk}. */ - jkt: string; - createJwt( - header: Record, - payload: Record, - ): Promise; -} - export interface IdentityProvider { /** Mint (or reuse) a harness identity by role label. */ identity(role: string): Promise; - /** Mint a fresh DPoP key. */ - dpopKey(): Promise; } export interface SyncerInbox { - /** The service identifier to register (did, optionally with #fragment). */ + /** + * The service identifier to register or name as a managing app: a DID + * (optionally with a `#fragment`) whose document routes to this inbox. + */ service: string; /** Wait for a delivery matching the predicate, or time out (null). */ waitFor( predicate: (delivery: InboxDelivery) => boolean, timeoutMs: number, ): Promise; + /** + * Answer queries for `lxm` (e.g. `com.atproto.managedspace.checkUserAccess`) + * with the handler's JSON body; pass undefined to stop answering. Queries + * are recorded as deliveries either way. + */ + respond( + lxm: string, + handler: ((delivery: InboxDelivery) => unknown) | undefined, + ): void; } export interface InboxDelivery { lxm: string; + /** Parsed JSON body of a procedure. */ body: unknown; + /** Query parameters of a query. */ + params?: Record; authorization?: string; receivedAt: number; } @@ -137,6 +155,11 @@ export interface Target { did: string; /** Free-form implementation label for the report ("cirrus", "reference"). */ implementation?: string; + /** + * The PLC directory did:plc identities resolve against (the target's own + * and the repos it reads). Defaults to https://plc.directory. + */ + plcDirectory?: string; } export interface CheckContext { @@ -145,9 +168,9 @@ export interface CheckContext { /** * Present when the harness has an authenticated session on the target. * Provide `authorize` when auth is plain header injection (a bearer - * token), or `fetch` when each request must be individually signed — a - * DPoP-bound OAuth session, where the proof depends on the method and - * URL, cannot be expressed as headers alone. At least one is required; + * token), or `fetch` when each request must be individually signed — an + * OAuth session's DPoP proof depends on the method and URL, so it cannot + * be expressed as headers alone. At least one is required; * `fetch` wins when both are present. */ operator?: { @@ -160,6 +183,13 @@ export interface CheckContext { }; identities?: IdentityProvider; syncerInbox?: SyncerInbox; + /** + * Resolve a DID document. Optional: by default the suite fetches did:web + * documents from their host and did:plc documents from + * `target.plcDirectory`, over `fetch`. An in-process fixture with its own + * resolution supplies this instead. + */ + resolveDid?(did: string): Promise; /** * Scratch space shared across checks in one run — e.g. the probe space * a setup check created, reused by later checks. Keys are namespaced by diff --git a/packages/space-conformance/src/space-auth.ts b/packages/space-conformance/src/space-auth.ts new file mode 100644 index 0000000..2af281f --- /dev/null +++ b/packages/space-conformance/src/space-auth.ts @@ -0,0 +1,305 @@ +/** + * Browser-safe space credential presentation: P-256 did:key credential + * keys, the `atproto-space-credential` HTTP message signature, and the + * KEM key share a syncer sends in `Atproto-Space-Want-Mac`. + * + * Deliberately dependency-free (WebCrypto and BigInt only) so the checks + * that present a credential — the operator's own credential flow, the MAC + * and signature refusals — run in a browser bundle too. Every format here + * mirrors `@atproto/space` byte for byte (`createSpaceSigHeaders`, + * `encapsulate`, `formatWantMacHeader`); the full test suite cross-checks + * each against the reference library, so a drift fails CI rather than + * every run against a real host. + * + * Verifying a MAC (rather than requesting one) needs the reference + * library's commit and record encodings, so it lives behind the full + * entry. + */ + +import { + concatBytes, + fromBase58, + fromBase64, + toBase58, + toBase64, + utf8, +} from "./encoding.js"; + +// --- P-256 points ------------------------------------------------------ + +const P = 2n ** 256n - 2n ** 224n + 2n ** 192n + 2n ** 96n - 1n; +const B = 0x5ac635d8aa3a93e7b3ebbd55769886bc651d06b0cc53b0f63bce3c3e27d2604bn; +const N = 0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551n; + +const P256_MULTICODEC = new Uint8Array([0x80, 0x24]); // p256-pub, varint +const K256_MULTICODEC = new Uint8Array([0xe7, 0x01]); // secp256k1-pub, varint + +function bytesToBigInt(bytes: Uint8Array): bigint { + let n = 0n; + for (const b of bytes) n = (n << 8n) | BigInt(b); + return n; +} + +function bigIntToBytes(n: bigint, length: number): Uint8Array { + const out = new Uint8Array(length); + for (let i = length - 1; i >= 0; i--) { + out[i] = Number(n & 0xffn); + n >>= 8n; + } + return out; +} + +function modPow(base: bigint, exp: bigint, mod: bigint): bigint { + let result = 1n; + base %= mod; + while (exp > 0n) { + if (exp & 1n) result = (result * base) % mod; + base = (base * base) % mod; + exp >>= 1n; + } + return result; +} + +/** 0x04 || x || y → 0x02/0x03 || x. Curve-agnostic (secp256k1 too). */ +export function compressP256(uncompressed: Uint8Array): Uint8Array { + if (uncompressed.length !== 65 || uncompressed[0] !== 0x04) { + throw new Error("expected an uncompressed EC point"); + } + const prefix = (uncompressed[64]! & 1) === 1 ? 0x03 : 0x02; + return concatBytes([new Uint8Array([prefix]), uncompressed.subarray(1, 33)]); +} + +/** 0x02/0x03 || x → 0x04 || x || y. */ +export function decompressP256(compressed: Uint8Array): Uint8Array { + if (compressed.length !== 33 || (compressed[0] !== 2 && compressed[0] !== 3)) { + throw new Error("expected a compressed P-256 point"); + } + const x = bytesToBigInt(compressed.subarray(1)); + const rhs = (((x * x * x - 3n * x + B) % P) + P) % P; + // P ≡ 3 (mod 4), so the square root is rhs^((P+1)/4). + let y = modPow(rhs, (P + 1n) / 4n, P); + if ((y * y) % P !== rhs) throw new Error("point is not on P-256"); + if ((y & 1n) !== BigInt(compressed[0]! & 1)) y = P - y; + return concatBytes([ + new Uint8Array([0x04]), + bigIntToBytes(x, 32), + bigIntToBytes(y, 32), + ]); +} + +export type DidKeyAlg = "ES256" | "ES256K"; + +/** Format a did:key from a public key (compressed or, for P-256, not). */ +export function formatDidKey(alg: DidKeyAlg, keyBytes: Uint8Array): string { + if (alg === "ES256") { + const compressed = + keyBytes.length === 65 ? compressP256(keyBytes) : keyBytes; + return `did:key:z${toBase58(concatBytes([P256_MULTICODEC, compressed]))}`; + } + if (keyBytes.length !== 33) { + throw new Error("secp256k1 keys must be given compressed"); + } + return `did:key:z${toBase58(concatBytes([K256_MULTICODEC, keyBytes]))}`; +} + +/** Parse a did:key, returning its algorithm and compressed key bytes. */ +export function parseDidKey(didKey: string): { + alg: DidKeyAlg; + compressed: Uint8Array; +} { + if (!didKey.startsWith("did:key:z")) throw new Error("not a did:key"); + const bytes = fromBase58(didKey.slice("did:key:z".length)); + if (bytes[0] === 0x80 && bytes[1] === 0x24) { + return { alg: "ES256", compressed: bytes.subarray(2) }; + } + if (bytes[0] === 0xe7 && bytes[1] === 0x01) { + return { alg: "ES256K", compressed: bytes.subarray(2) }; + } + throw new Error("unsupported did:key type"); +} + +export function isP256DidKey(value: unknown): boolean { + try { + return typeof value === "string" && parseDidKey(value).alg === "ES256"; + } catch { + return false; + } +} + +// --- credential keys --------------------------------------------------- + +/** + * A P-256 key a space credential is bound to (its `cnf.kid`). Each request + * presenting the credential is signed by it. Transport-owned: any fresh + * key will do, so it is never tied to a harness identity. + */ +export interface CredentialKey { + /** The key as a P-256 did:key — what `credentialKid` carries. */ + did: string; + /** Sign with ECDSA P-256/SHA-256, returning a 64-byte compact signature. */ + sign(bytes: Uint8Array): Promise; +} + +export async function createCredentialKey(): Promise { + const pair = await crypto.subtle.generateKey( + { name: "ECDSA", namedCurve: "P-256" }, + true, + ["sign"], + ); + const raw = new Uint8Array( + await crypto.subtle.exportKey("raw", pair.publicKey), + ); + return { + did: formatDidKey("ES256", raw), + async sign(bytes) { + const sig = new Uint8Array( + await crypto.subtle.sign( + { name: "ECDSA", hash: "SHA-256" }, + pair.privateKey, + bytes as BufferSource, + ), + ); + // WebCrypto does not normalise s. Verifiers accept either form, but + // low-S is the conservative choice for a key every host must accept. + const s = bytesToBigInt(sig.subarray(32)); + if (s > N / 2n) sig.set(bigIntToBytes(N - s, 32), 32); + return sig; + }, + }; +} + +// --- HTTP message signature -------------------------------------------- + +export const SPACE_CREDENTIAL_SCHEME = "Atproto-Space-Credential"; +const SIGNATURE_LABEL = "atproto-space-credential"; +const SIGNATURE_PARAMS = `("authorization" "atproto-space-audience");tag="atproto-space-credential"`; + +/** + * The headers that present a space credential: the `Authorization` scheme, + * the audience DID (the service being called — the repo DID at a repo + * host, the authority DID at the space host) and an RFC 9421 signature by + * the credential's key covering exactly those two fields. + */ +export async function spaceSigHeaders( + key: Pick, + opts: { authorization: string; audience: string }, +): Promise> { + const base = [ + `"authorization": ${opts.authorization.trim()}`, + `"atproto-space-audience": ${opts.audience.trim()}`, + `"@signature-params": ${SIGNATURE_PARAMS}`, + ].join("\n"); + const signature = await key.sign(utf8(base)); + return { + authorization: opts.authorization, + "atproto-space-audience": opts.audience, + "signature-input": `${SIGNATURE_LABEL}=${SIGNATURE_PARAMS}`, + // RFC 9651 byte sequences are padded base64. + signature: `${SIGNATURE_LABEL}=:${toBase64(signature)}:`, + }; +} + +// --- KEM / MAC request ------------------------------------------------- + +export const COMMIT_MAC_TYPE = "atproto-space-repo"; +export const RECORD_MAC_TYPE = "atproto-space-record"; +export type MacType = typeof COMMIT_MAC_TYPE | typeof RECORD_MAC_TYPE; +export const WANT_MAC_HEADER = "atproto-space-want-mac"; +export const MAC_HEADER = "atproto-space-mac"; + +/** `type="…", ver=1, key_share="did:key:…"` — both MAC types are on v1. */ +export const formatWantMacHeader = (type: MacType, keyShare: string): string => + `type="${type}", ver=1, key_share="${keyShare}"`; + +const uint16be = (n: number) => new Uint8Array([n >>> 8, n & 0xff]); +const KEM_PREFIX = concatBytes([utf8("HPKE-v1"), utf8("KEM"), uint16be(0x0010)]); + +/** + * Syncer side of the space KEM: ECDH between a fresh ephemeral P-256 key + * and the author's `#atproto_kem` key, with the secret derived as in + * DHKEM(P-256, HKDF-SHA256) (RFC 9180 §4.1). Use once per request. + */ +export async function encapsulate( + authorKemDidKey: string, +): Promise<{ keyShare: string; sharedSecret: Uint8Array }> { + const parsed = parseDidKey(authorKemDidKey); + if (parsed.alg !== "ES256") throw new Error("KEM key must be P-256"); + const authorBytes = decompressP256(parsed.compressed); + const authorKey = await crypto.subtle.importKey( + "raw", + authorBytes as BufferSource, + { name: "ECDH", namedCurve: "P-256" }, + false, + [], + ); + const ephemeral = await crypto.subtle.generateKey( + { name: "ECDH", namedCurve: "P-256" }, + true, + ["deriveBits"], + ); + const ephemeralBytes = new Uint8Array( + await crypto.subtle.exportKey("raw", ephemeral.publicKey), + ); + const dh = new Uint8Array( + await crypto.subtle.deriveBits( + { name: "ECDH", public: authorKey }, + ephemeral.privateKey, + 256, + ), + ); + const ikm = concatBytes([KEM_PREFIX, utf8("eae_prk"), dh]); + const info = concatBytes([ + uint16be(32), + KEM_PREFIX, + utf8("shared_secret"), + ephemeralBytes, + authorBytes, + ]); + const hkdfKey = await crypto.subtle.importKey( + "raw", + ikm as BufferSource, + "HKDF", + false, + ["deriveBits"], + ); + const sharedSecret = new Uint8Array( + await crypto.subtle.deriveBits( + { + name: "HKDF", + hash: "SHA-256", + salt: new Uint8Array(0), + info: info as BufferSource, + }, + hkdfKey, + 256, + ), + ); + return { keyShare: formatDidKey("ES256", ephemeralBytes), sharedSecret }; +} + +/** + * Pull the `mac` byte sequence out of an `Atproto-Space-Mac` header, + * checking its type and version. Undefined when absent or malformed. + */ +export function parseMacHeader( + value: string | null, + type: MacType, +): Uint8Array | undefined { + if (!value) return undefined; + const fields = new Map(); + for (const member of value.split(",")) { + const eq = member.indexOf("="); + if (eq < 0) continue; + fields.set(member.slice(0, eq).trim(), member.slice(eq + 1).trim()); + } + if (fields.get("type") !== `"${type}"` || fields.get("ver") !== "1") { + return undefined; + } + const mac = fields.get("mac"); + if (!mac || !mac.startsWith(":") || !mac.endsWith(":")) return undefined; + try { + return fromBase64(mac.slice(1, -1)); + } catch { + return undefined; + } +} diff --git a/packages/space-conformance/test/cli.test.ts b/packages/space-conformance/test/cli.test.ts index 23c19ac..5f0451f 100644 --- a/packages/space-conformance/test/cli.test.ts +++ b/packages/space-conformance/test/cli.test.ts @@ -1,34 +1,45 @@ -import { describe, expect, it } from "vitest"; +import { beforeAll, describe, expect, it } from "vitest"; +import { P256Keypair, Secp256k1Keypair } from "@atproto/crypto"; import { runConformance } from "../src/cli/run"; -import { originGatedFetch } from "../src/cli/oauth"; +import { OAUTH_SCOPE, originGatedFetch } from "../src/cli/oauth"; const DID = "did:web:target.test"; +/** A DID document carrying everything the alpha requires of an authority. */ +let didDoc: Record; +beforeAll(async () => { + const signing = await Secp256k1Keypair.create(); + const kem = await P256Keypair.create(); + didDoc = { + id: DID, + verificationMethod: [ + { id: `${DID}#atproto`, type: "Multikey", controller: DID, publicKeyMultibase: signing.did().slice(8) }, + { id: `${DID}#atproto_kem`, type: "Multikey", controller: DID, publicKeyMultibase: kem.did().slice(8) }, + ], + service: [ + { id: "#atproto_pds", type: "AtprotoPersonalDataServer", serviceEndpoint: "https://target.test" }, + ], + }; +}); + /** - * A minimal fake target: a valid DID document plus refusing auth - * endpoints. Enough to exercise the base (no-crypto) checks and prove the - * crypto checks skip cleanly when no operator/identities are supplied. + * A minimal fake target: a valid DID document plus refusing endpoints. + * Enough to exercise the base (no-crypto) checks and prove the crypto + * checks skip cleanly when no operator/identities are supplied. */ function fakeTarget(): typeof fetch { return (async (input: RequestInfo | URL) => { const url = new URL(String(input)); if (url.pathname === "/.well-known/did.json") { - return Response.json({ - id: DID, - service: [ - { - id: "#atproto_space_host", - type: "AtprotoSpaceHost", - serviceEndpoint: "https://target.test", - }, - ], - verificationMethod: [{ id: `${DID}#atproto` }], - }); + return Response.json(didDoc); } if (url.pathname.startsWith("/xrpc/com.atproto.space.getLatestCommit")) { return Response.json({ error: "InvalidRequest" }, { status: 400 }); } - // Everything else (space reads, credential requests) is unauthenticated. + if (url.pathname === "/xrpc/com.atproto.space.getSpaceCredential") { + return Response.json({ error: "SpaceNotFound" }, { status: 400 }); + } + // Everything else (space reads) is unauthenticated. return Response.json({ error: "AuthMissing" }, { status: 401 }); }) as typeof fetch; } @@ -45,12 +56,19 @@ describe("runConformance (CLI core)", () => { expect(report.target.did).toBe(DID); const byId = Object.fromEntries(report.results.map((r) => [r.id, r])); // Base checks ran and passed. - expect(byId["discovery.space-host-service"]!.status).toBe("pass"); - expect(byId["auth.getrecord-unauthenticated-refused"]!.status).toBe("pass"); - expect(byId["request.invalid-space-uri-rejected"]!.status).toBe("pass"); + for (const id of [ + "discovery.pds-service", + "discovery.signing-key", + "discovery.kem-key", + "auth.getrecord-unauthenticated-refused", + "credential.tokenless-unknown-space", + "request.invalid-space-uri-rejected", + ]) { + expect(byId[id]!.status, id).toBe("pass"); + } // Crypto checks skipped for want of operator/identities — reported, // not silently passed. - expect(byId["credential.round-trip"]!.status).toBe("skipped"); + expect(byId["credential.member-gate"]!.status).toBe("skipped"); expect(byId["writes.create-and-read"]!.status).toBe("skipped"); expect(report.summary.mustFail).toBe(0); expect(report.summary.skipped).toBeGreaterThan(0); @@ -83,17 +101,7 @@ describe("runConformance (CLI core)", () => { ) => { const url = new URL(String(input)); if (url.pathname === "/.well-known/did.json") { - return Response.json({ - id: DID, - service: [ - { - id: "#atproto_space_host", - type: "AtprotoSpaceHost", - serviceEndpoint: "https://target.test", - }, - ], - verificationMethod: [{ id: `${DID}#atproto` }], - }); + return Response.json(didDoc); } if (url.pathname === "/xrpc/com.atproto.server.createSession") { const body = JSON.parse(String(init?.body)) as { @@ -106,7 +114,7 @@ describe("runConformance (CLI core)", () => { }); return Response.json({ accessJwt: "sess-tok", did: DID }); } - if (url.pathname === "/xrpc/com.atproto.simplespace.createSpace") { + if (url.pathname === "/xrpc/com.atproto.space.createSpace") { authHeaders.push(new Headers(init?.headers).get("Authorization")); } return Response.json({ error: "AuthMissing" }, { status: 401 }); @@ -173,15 +181,21 @@ describe("runConformance (CLI core)", () => { }); it("surfaces a target that fails a base check as a must failure", async () => { - // A target whose DID document lacks the space host entry must fail - // discovery. + // A pre-alpha DID document: #atproto_space_host instead of a + // #atproto_pds that routes here, and no #atproto_kem key. const brokenTarget = (async (input: RequestInfo | URL) => { const url = new URL(String(input)); if (url.pathname === "/.well-known/did.json") { return Response.json({ id: DID, - service: [], - verificationMethod: [{ id: `${DID}#atproto` }], + service: [ + { + id: "#atproto_space_host", + type: "AtprotoSpaceHost", + serviceEndpoint: "https://target.test", + }, + ], + verificationMethod: (didDoc.verificationMethod as unknown[]).slice(0, 1), }); } return Response.json({ error: "AuthMissing" }, { status: 401 }); @@ -191,30 +205,59 @@ describe("runConformance (CLI core)", () => { fetch: brokenTarget, suiteVersion: "0.0.0-test", }); - const discovery = report.results.find( - (r) => r.id === "discovery.space-host-service", - ); - expect(discovery!.status).toBe("fail"); + const status = (id: string) => report.results.find((r) => r.id === id)!.status; + expect(status("discovery.pds-service")).toBe("fail"); + expect(status("discovery.kem-key")).toBe("fail"); + expect(status("discovery.signing-key")).toBe("pass"); expect(report.summary.mustFail).toBeGreaterThan(0); }); + it("resolves a did:plc target through --plc", async () => { + const plcDid = "did:plc:abcdefghijklmnopqrstuvwx"; + const requested: string[] = []; + const plcFetch = (async (input: RequestInfo | URL) => { + const url = String(input); + requested.push(url); + if (url === `https://plc.test/${plcDid}`) { + // Relative fragment ids, as PLC renders them. + const methods = didDoc.verificationMethod as Array<{ id: string }>; + return Response.json({ + ...didDoc, + id: plcDid, + verificationMethod: methods.map((m) => ({ + ...m, + id: m.id.slice(m.id.indexOf("#")), + controller: plcDid, + })), + }); + } + return Response.json({ error: "AuthMissing" }, { status: 401 }); + }) as typeof fetch; + const report = await runConformance({ + origin: "https://target.test", + did: plcDid, + plcDirectory: "https://plc.test", + fetch: plcFetch, + suiteVersion: "0.0.0-test", + }); + expect(report.target.plcDirectory).toBe("https://plc.test"); + expect(report.results.find((r) => r.id === "discovery.kem-key")!.status).toBe("pass"); + expect(requested).toContain(`https://plc.test/${plcDid}`); + }); + + it("signs in with a scope that reaches spaces the operator does not own", () => { + // NotSpaceOwner probes and writes into a foreign authority's space + // need authority=*, still confined to the probe space type. + expect(OAUTH_SCOPE).toContain("space:earth.cirrus.check.space?authority=*"); + }); + it("counts must-tier errors so an unreachable target does not pass green", async () => { // did.json resolves, but every XRPC call throws (target down). The // base must-checks error rather than fail — the CLI must still gate. const halfDown = (async (input: RequestInfo | URL) => { const url = new URL(String(input)); if (url.pathname === "/.well-known/did.json") { - return Response.json({ - id: DID, - service: [ - { - id: "#atproto_space_host", - type: "AtprotoSpaceHost", - serviceEndpoint: "https://target.test", - }, - ], - verificationMethod: [{ id: `${DID}#atproto` }], - }); + return Response.json(didDoc); } throw new Error("connection refused"); }) as typeof fetch; diff --git a/packages/space-conformance/test/core.test.ts b/packages/space-conformance/test/core.test.ts index 6470a53..bced5e9 100644 --- a/packages/space-conformance/test/core.test.ts +++ b/packages/space-conformance/test/core.test.ts @@ -228,7 +228,9 @@ describe("coverage", () => { const refs = requirements.map((r) => r.ref); // Methods expect(refs).toContain("com.atproto.space.getRecord"); - expect(refs).toContain("com.atproto.simplespace.createSpace"); + expect(refs).toContain("com.atproto.space.createSpace"); + expect(refs).toContain("com.atproto.memberspace.putMember"); + expect(refs).toContain("com.atproto.managedspace.checkUserAccess"); // Declared errors, exactly as named expect(refs).toContain( "com.atproto.space.getSpaceCredential@error:UserNotAuthorized", @@ -237,12 +239,18 @@ describe("coverage", () => { "com.atproto.space.getSpaceCredential@error:SpaceDeleted", ); expect(refs).toContain( - "com.atproto.simplespace.createSpace@error:UnsupportedPolicy", - ); - // defs.json is not a method and contributes nothing - expect(refs.every((r) => !r.startsWith("com.atproto.space.defs"))).toBe( - true, + "com.atproto.space.createSpace@error:UnsupportedPolicy", ); + expect(refs).toContain("com.atproto.space.getRecord@error:BadSpaceMac"); + // defs, records and policy objects are not methods and contribute nothing + for (const notMethod of [ + "com.atproto.space.defs", + "com.atproto.space.policy", + "com.atproto.memberspace.member", + "com.atproto.memberspace.policy", + ]) { + expect(refs.some((r) => r.split("@")[0] === notMethod)).toBe(false); + } }); it("flags an @error typo as dangling instead of crediting the method", () => { @@ -278,7 +286,7 @@ describe("coverage", () => { const catalog = buildCatalog([ okCheck("commit.shape", { citations: [ - { source: "lexicon", ref: "com.atproto.space.defs#signedCommit" }, + { source: "lexicon", ref: "com.atproto.space.defs#commit" }, ], }), ]); @@ -318,10 +326,46 @@ describe("coverage", () => { }); it("vendored lexicons parse and are all com.atproto space documents", () => { - expect(lexicons.length).toBeGreaterThanOrEqual(29); + expect(lexicons.length).toBeGreaterThanOrEqual(38); for (const doc of lexicons) { expect(doc.lexicon).toBe(1); - expect(doc.id).toMatch(/^com\.atproto\.(space|simplespace)\./); + expect(doc.id).toMatch( + /^com\.atproto\.(space|memberspace|personalspace|managedspace)\./, + ); } + // simplespace is gone in this alpha. + expect(lexicons.some((d) => d.id.includes("simplespace"))).toBe(false); + }); + + it("excuses exempted requirements and reports stale exemptions", () => { + const catalog = buildCatalog([ + okCheck("record.get", { + citations: [ + { + source: "lexicon", + ref: "com.atproto.space.getRecord@error:RepoTakendown", + }, + ], + }), + ]); + const report = coverageReport(catalog, undefined, [ + { ref: "*@error:RepoTakendown", reason: "needs admin" }, + { ref: "com.atproto.space.getRecord@error:RecordNotFound", reason: "x" }, + { ref: "com.atproto.space.nonexistent", reason: "typo" }, + ]); + const exempt = report.exempt.map((e) => e.ref); + // The wildcard excuses every method's RepoTakendown but the covered one. + expect(exempt).toContain("com.atproto.space.getRepo@error:RepoTakendown"); + expect(exempt).not.toContain( + "com.atproto.space.getRecord@error:RepoTakendown", + ); + expect(exempt).toContain("com.atproto.space.getRecord@error:RecordNotFound"); + expect(report.gaps.map((g) => g.ref)).not.toContain( + "com.atproto.space.getRepo@error:RepoTakendown", + ); + // An exemption that matches nothing is stale, not silently kept. + expect(report.staleExemptions.map((e) => e.ref)).toEqual([ + "com.atproto.space.nonexistent", + ]); }); }); diff --git a/packages/space-conformance/test/full.test.ts b/packages/space-conformance/test/full.test.ts index 070e29c..75e02fa 100644 --- a/packages/space-conformance/test/full.test.ts +++ b/packages/space-conformance/test/full.test.ts @@ -1,51 +1,98 @@ import { describe, expect, it } from "vitest"; +import { + P256Keypair, + Secp256k1Keypair, + formatDidKey as cryptoFormatDidKey, + parseDidKey as cryptoParseDidKey, + P256_JWT_ALG, + SECP256K1_JWT_ALG, + multibaseToBytes, +} from "@atproto/crypto"; +import { + COMMIT_MAC_TYPE as REF_COMMIT_MAC_TYPE, + RECORD_MAC_TYPE as REF_RECORD_MAC_TYPE, + decapsulate, + formatMacHeader, + formatWantMacHeader as refFormatWantMacHeader, + parseWantMacHeader, + verifyCredentialSig, +} from "@atproto/space"; +import { parseCid } from "@atproto/lex-data"; import { browserCatalog, coverageReport, cryptoCheckDescriptors, filterCatalog, + knownChangesets, operatorChecks, + baseChecks, } from "../src/index"; import { KeypairIdentityProvider, - createDpopKey, + createCredentialKey, cryptoChecks, fullCatalog, } from "../src/full"; -import { readCarHeader } from "../src/car"; +import { + COMMIT_MAC_TYPE, + RECORD_MAC_TYPE, + compressP256, + decompressP256, + encapsulate, + formatWantMacHeader, + parseMacHeader, + spaceSigHeaders, +} from "../src/space-auth"; +import { verificationMethodDidKey, didDocumentUrl } from "../src/did"; +import { isTid, rawCid, tidAt, tidNow, fromBase58 } from "../src/encoding"; describe("full catalog", () => { - it("assembles base + crypto checks with unique ids", () => { + it("assembles base + operator + crypto checks with unique ids", () => { const ids = fullCatalog.map((c) => c.id); expect(new Set(ids).size).toBe(ids.length); - expect(ids).toContain("credential.round-trip"); - expect(ids).toContain("discovery.space-host-service"); + expect(ids).toContain("credential.member-gate"); + expect(ids).toContain("discovery.kem-key"); + expect(fullCatalog).toHaveLength( + baseChecks.length + operatorChecks.length + cryptoChecks.length, + ); }); - it("has no dangling lexicon citations", () => { - // Every lexicon citation must name a real vendored method/error — - // a typo would silently under-count coverage. + it("has no dangling lexicon or changeset citations", () => { + // Every lexicon citation must name a real vendored method/error, and + // every changeset citation a real upstream changeset — a typo would + // silently under-count coverage or cite nothing. const report = coverageReport(fullCatalog); expect(report.danglingCitations).toEqual([]); + const changesets = new Set(knownChangesets); + for (const check of fullCatalog) { + for (const c of check.citations) { + if (c.source === "changeset") { + expect(changesets.has(c.ref), `${check.id} cites ${c.ref}`).toBe(true); + } + } + } }); - it("covers the core method surface", () => { + it("covers every method and declared error, or exempts it with a reason", () => { const report = coverageReport(fullCatalog); - const covered = new Set(report.covered.map((c) => c.ref)); - for (const method of [ - "com.atproto.space.createRecord", - "com.atproto.space.getRecord", - "com.atproto.space.getSpaceCredential", - "com.atproto.space.listRepoOps", - "com.atproto.space.getRepo", - "com.atproto.space.listRepos", - "com.atproto.simplespace.createSpace", - ]) { - expect(covered.has(method)).toBe(true); + expect(report.gaps.map((g) => g.ref)).toEqual([]); + expect(report.staleExemptions).toEqual([]); + // Exemptions are the moderation-state errors only; anything else + // uncovered is a gap, not an exemption. + for (const { ref, reason } of report.exempt) { + expect(ref).toMatch(/@error:Repo(Takendown|Suspended|Deactivated)$/); + expect(reason.length).toBeGreaterThan(20); + } + }); + + it("every must check cites specified behaviour, not just the reference", () => { + for (const check of fullCatalog) { + if (check.tier !== "must") continue; + expect( + check.citations.some((c) => c.source !== "reference"), + `${check.id} is a must citing only the reference`, + ).toBe(true); } - // Coverage is honestly partial in the first catalog — gaps are the - // backlog, and the report names them rather than hiding them. - expect(report.gaps.length).toBeGreaterThan(0); }); it("browserCatalog lists every check, crypto ones as not-testable", () => { @@ -53,30 +100,34 @@ describe("full catalog", () => { // is reported skipped — never omitted. "not testable here" must never // silently read as conformant. const anonymous = filterCatalog(browserCatalog, { capabilities: [] }); - expect(anonymous.runnable.length).toBe(5); // the base checks + expect(anonymous.runnable.length).toBe(baseChecks.length); expect(anonymous.skipped.length).toBe( operatorChecks.length + cryptoCheckDescriptors.length, ); - expect(anonymous.runnable.length + anonymous.skipped.length).toBe( - browserCatalog.length, - ); // With an operator session (the web checker after OAuth sign-in), the - // operator checks become runnable too; only the alpha-lib stubs stay - // not-testable — even the ones whose declared needs are met, because - // the stub carries the alpha-libs marker no browser provides. + // operator checks become runnable too — all but the ones needing a + // syncer inbox no browser can host. The alpha-lib stubs stay + // not-testable even where their declared needs are met. const authed = filterCatalog(browserCatalog, { capabilities: ["operator", "pds-blobs", "pds-delegation"], destructive: true, }); - expect(authed.runnable.length).toBe(5 + operatorChecks.length); - expect(authed.skipped.length).toBe(cryptoCheckDescriptors.length); + const needsInbox = operatorChecks.filter((c) => + c.needs.includes("syncer-inbox"), + ); + expect(needsInbox.length).toBeGreaterThan(0); + expect(authed.runnable.length).toBe( + baseChecks.length + operatorChecks.length - needsInbox.length, + ); + expect(authed.skipped.length).toBe( + cryptoCheckDescriptors.length + needsInbox.length, + ); }); it("the browser descriptors match the real crypto checks exactly", () => { - // The browser adapter lists checks from these dependency-free - // descriptors. If they drift from the real crypto catalog, the - // browser would misreport coverage — so pin them here. + // The crypto checks spread their descriptor, so drift is impossible by + // construction; this pins that nobody bypasses that. const metadata = ( checks: Array<{ id: string; @@ -100,19 +151,18 @@ describe("full catalog", () => { it("every authed check declares the capabilities it uses", () => { for (const check of [...operatorChecks, ...cryptoChecks]) { - // Every authed check drives an operator session; the runner would - // otherwise hand it a context with no way to authorize a write. - expect(check.needs).toContain("operator"); - // A check that obtains a credential must say how a reader is - // realized: either harness-held identities play the reader role, - // or the target mints the delegation itself (pds-delegation). - // Declaring neither means the runner would run it with no reader - // path and it would throw. - if (check.id.startsWith("credential")) { - const hasReaderPath = - check.needs.includes("identities") || - check.needs.includes("pds-delegation"); - expect(hasReaderPath).toBe(true); + // Every authed check drives an operator session. + expect(check.needs, check.id).toContain("operator"); + // A check that uses the target's own delegation tokens must say so. + const source = check.run.toString(); + if (source.includes("getDelegationToken") || source.includes("obtainCredentialViaDelegation")) { + expect(check.needs, check.id).toContain("pds-delegation"); + } + if (source.includes("ctx.identities")) { + expect(check.needs, check.id).toContain("identities"); + } + if (source.includes("ctx.syncerInbox")) { + expect(check.needs, check.id).toContain("syncer-inbox"); } } }); @@ -128,58 +178,150 @@ describe("identity provider", () => { expect(reader1.didKey).toBe(reader1.did); const writer = await provider.identity("writer"); expect(writer.did).not.toBe(reader1.did); - // The identity actually signs. const sig = await reader1.sign(new TextEncoder().encode("hello")); - expect(sig.byteLength).toBeGreaterThan(0); + expect(sig.byteLength).toBe(64); }); - it("supports resolvable DID mapping for live targets", async () => { + it("supports resolvable (and async) DID mapping for live targets", async () => { const provider = new KeypairIdentityProvider( - (role) => `did:web:checker.test:actors:${role}`, + async (role) => `did:web:checker.test:${role}`, ); const reader = await provider.identity("reader"); - expect(reader.did).toBe("did:web:checker.test:actors:reader"); - // The did:key is still exposed for resolver wiring. + expect(reader.did).toBe("did:web:checker.test:reader"); expect(reader.didKey).toMatch(/^did:key:/); }); - it("mints ES256 DPoP keys with a valid thumbprint", async () => { - const key = await createDpopKey(); - expect(key.algorithms).toContain("ES256"); - expect(key.bareJwk.kty).toBe("EC"); - expect(key.bareJwk.crv).toBe("P-256"); - expect(key.jkt).toMatch(/^[A-Za-z0-9_-]{43}$/); // base64url sha-256 - const jwt = await key.createJwt( - { alg: "ES256", typ: "dpop+jwt" }, - { htm: "GET" }, + it("builds the DID document the protocol requires of an identity", async () => { + const provider = new KeypairIdentityProvider( + async () => "did:web:localhost%3A1234", ); - expect(jwt.split(".")).toHaveLength(3); + const syncer = await provider.identity("syncer"); + const doc = KeypairIdentityProvider.didDocument(syncer, { + serviceEndpoint: "http://localhost:1234", + }) as never; + // #atproto resolves back to the identity's own key, as a verifier would read it. + expect(verificationMethodDidKey(doc, "atproto")).toBe(syncer.didKey); + expect((doc as { service: unknown[] }).service).toEqual([ + { + id: "#atproto_pds", + type: "AtprotoPersonalDataServer", + serviceEndpoint: "http://localhost:1234", + }, + ]); }); }); -describe("CAR header reader", () => { - it("reads the version and root count of a CARv1 header", async () => { - // Build a minimal CARv1 header: varint(len) || dag-cbor({version,roots}) - // readCarHeader only counts roots, so a header with two placeholder - // root entries exercises it without the environment-specific CID - // hashing that a real CAR would need. - const { encode } = await import("@atproto/lex-cbor"); - const headerBytes = encode({ - version: 1, - roots: [new Uint8Array([1]), new Uint8Array([2])], +describe("browser-safe space auth matches @atproto/space", () => { + it("credential keys are P-256 did:keys whose signatures the reference verifies", async () => { + const key = await createCredentialKey(); + expect(cryptoParseDidKey(key.did).jwtAlg).toBe(P256_JWT_ALG); + const headers = await spaceSigHeaders(key, { + authorization: "Atproto-Space-Credential a.b.c", + audience: "did:plc:abcdefghijklmnopqrstuvwx", }); - const varint = (n: number): number[] => { - const out: number[] = []; - while (n >= 0x80) { - out.push((n & 0x7f) | 0x80); - n >>>= 7; - } - out.push(n); - return out; + await expect(verifyCredentialSig(headers, key.did as never)).resolves.toBeUndefined(); + // And a different key's did is refused — the verification is real. + const other = await createCredentialKey(); + await expect(verifyCredentialSig(headers, other.did as never)).rejects.toThrow(); + }); + + it("encapsulate derives the secret the repo host decapsulates", async () => { + const kem = await P256Keypair.create(); + const { keyShare, sharedSecret } = await encapsulate(kem.did()); + expect(decapsulate(kem, keyShare)).toEqual(sharedSecret); + }); + + it("formats Want-Mac headers the reference parses, byte for byte", async () => { + const share = (await P256Keypair.create()).did(); + for (const [ours, theirs] of [ + [COMMIT_MAC_TYPE, REF_COMMIT_MAC_TYPE], + [RECORD_MAC_TYPE, REF_RECORD_MAC_TYPE], + ] as const) { + expect(formatWantMacHeader(ours, share)).toBe(refFormatWantMacHeader(theirs, share)); + expect(parseWantMacHeader(formatWantMacHeader(ours, share), theirs)).toBe(share); + } + }); + + it("parses the reference's Atproto-Space-Mac header", () => { + const mac = crypto.getRandomValues(new Uint8Array(32)); + expect(parseMacHeader(formatMacHeader(REF_COMMIT_MAC_TYPE, mac), COMMIT_MAC_TYPE)).toEqual(mac); + // Wrong type is refused rather than misread. + expect(parseMacHeader(formatMacHeader(REF_RECORD_MAC_TYPE, mac), COMMIT_MAC_TYPE)).toBeUndefined(); + }); + + it("compresses and decompresses P-256 points like @atproto/crypto", async () => { + const kp = await P256Keypair.create(); + const uncompressed = cryptoParseDidKey(kp.did()).keyBytes; + const compressed = compressP256(uncompressed); + expect(decompressP256(compressed)).toEqual(uncompressed); + expect(cryptoFormatDidKey(P256_JWT_ALG, uncompressed)).toBe(kp.did()); + }); + + it("reads legacy 2019 verification methods as PLC publishes them", async () => { + const k256 = await Secp256k1Keypair.create(); + const p256 = await P256Keypair.create(); + // PLC renders keys as raw uncompressed multibase under the 2019 types. + const legacy = (did: string, alg: string) => { + const uncompressed = cryptoParseDidKey(did).keyBytes; + void alg; + return `z${encodeBase58(uncompressed)}`; }; - const car = new Uint8Array([...varint(headerBytes.length), ...headerBytes]); - const info = readCarHeader(car); - expect(info.version).toBe(1); - expect(info.rootCount).toBe(2); + const doc = { + id: "did:plc:abcdefghijklmnopqrstuvwx", + verificationMethod: [ + { id: "#atproto", type: "EcdsaSecp256k1VerificationKey2019", publicKeyMultibase: legacy(k256.did(), SECP256K1_JWT_ALG) }, + { id: "#atproto_kem", type: "EcdsaSecp256r1VerificationKey2019", publicKeyMultibase: legacy(p256.did(), P256_JWT_ALG) }, + ], + }; + expect(verificationMethodDidKey(doc, "atproto")).toBe(k256.did()); + expect(verificationMethodDidKey(doc, "atproto_kem")).toBe(p256.did()); + // Sanity: the legacy encoding round-trips through the reference decoder. + expect(multibaseToBytes(doc.verificationMethod[1]!.publicKeyMultibase)).toEqual( + cryptoParseDidKey(p256.did()).keyBytes, + ); }); }); + +describe("encoding helpers", () => { + it("mints TIDs that sort by time", () => { + const now = tidNow(); + expect(isTid(now)).toBe(true); + const later = tidAt(BigInt(Date.now() + 3_600_000) * 1000n); + expect(isTid(later)).toBe(true); + expect(later > now).toBe(true); + }); + + it("mints raw CIDs the reference parses", async () => { + const cid = await rawCid(new TextEncoder().encode("hello")); + expect(parseCid(cid).toString()).toBe(cid); + }); + + it("resolves did:web and did:plc document URLs like the reference", () => { + expect(didDocumentUrl("did:web:example.com")).toBe("https://example.com/.well-known/did.json"); + expect(didDocumentUrl("did:web:localhost%3A2583")).toBe("http://localhost:2583/.well-known/did.json"); + expect(didDocumentUrl("did:plc:abc", "https://plc.test/")).toBe("https://plc.test/did:plc:abc"); + expect(() => didDocumentUrl("did:web:example.com:path")).toThrow(); + }); + + it("base58 round-trips", () => { + const bytes = new Uint8Array([0, 0, 1, 2, 255, 128]); + expect(fromBase58(encodeBase58(bytes))).toEqual(bytes); + }); +}); + +// Local base58 for building legacy fixtures (independent of the code under test). +function encodeBase58(bytes: Uint8Array): string { + const alphabet = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz"; + let n = 0n; + for (const b of bytes) n = n * 256n + BigInt(b); + let out = ""; + while (n > 0n) { + out = alphabet[Number(n % 58n)] + out; + n /= 58n; + } + for (const b of bytes) { + if (b !== 0) break; + out = `1${out}`; + } + return out; +} From fa3ba7e5efc4af57ec9195755b8be4aa73ca0022 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 08:53:27 +0000 Subject: [PATCH 06/16] wip(check): port the browser spaces runner to the 2026-11-05 alpha (in progress) Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LZ7qcQNQoiA6a23woGC7tB --- apps/check/src/SpacesConformanceView.tsx | 90 +++++++++++++++++------- apps/check/src/lib/oauth.ts | 16 +++-- apps/check/src/worker.ts | 2 +- 3 files changed, 73 insertions(+), 35 deletions(-) diff --git a/apps/check/src/SpacesConformanceView.tsx b/apps/check/src/SpacesConformanceView.tsx index 04379e9..7ea2bde 100644 --- a/apps/check/src/SpacesConformanceView.tsx +++ b/apps/check/src/SpacesConformanceView.tsx @@ -2,27 +2,33 @@ * Runner #3: the browser adapter for the spaces conformance suite. * * Signed in (the landing-page flow), the run carries the operator, blob - * and delegation capabilities: probe spaces, record writes, applyWrites - * atomicity, blob isolation and the operator's own delegation → credential - * → read flow all execute for real against the user's PDS, authenticated - * through the DPoP-bound OAuth session. Results stream into the table as - * each check lands. + * and delegation capabilities: space management and the baseline + * policies, record writes, blob isolation, credential issuance, and + * credential presentation — HTTP-signed reads with a KEM key share in + * Atproto-Space-Want-Mac — all execute for real against the user's PDS. + * Operator calls go through the OAuth session; credential-presenting calls + * carry their own WebCrypto P-256 signatures. Results stream into the + * table as each check lands. * * The checks a browser genuinely cannot run — harness-held foreign - * identities, the alpha crypto libs — are not shown at all: a row (or a - * count) implies a way they could have run here, and there isn't one. - * They are covered by the CLI and vitest runners. + * identities, a syncer inbox, MAC verification with the alpha crypto libs + * — are not shown at all: a row (or a count) implies a way they could have + * run here, and there isn't one. They are covered by the CLI and vitest + * runners. * * Without a session it degrades to the anonymous slice (discovery and - * unauthenticated request shapes) against any host the user names. + * unauthenticated request shapes) against any host or DID the user names. */ import { createSignal, For, onMount, Show } from "solid-js"; import { + ALPHA_BUILD, browserCatalog, filterCatalog, operatorChecks, + resolveDidDocument, runChecks, + serviceEndpoint, type CheckContext, type CheckResult, type RunReport, @@ -44,11 +50,33 @@ async function resolveDid(origin: string): Promise { return doc.id; } +/** + * Resolve what the user typed to a target: a DID resolves through its + * method (did:plc via plc.directory) to its #atproto_pds — the space host + * for that authority — which also covers multi-tenant did:plc hosts with + * no did.json at their origin; a hostname resolves through did.json. + */ +async function resolveTarget(input: string): Promise<{ origin: string; did: string }> { + const trimmed = input.trim(); + if (trimmed.startsWith("did:")) { + const doc = await resolveDidDocument( + { fetch: window.fetch.bind(window), target: { origin: "", did: trimmed } }, + trimmed, + ); + const pds = serviceEndpoint(doc, "atproto_pds"); + if (!pds) throw new Error(`${trimmed} has no #atproto_pds service`); + return { origin: normalizeOrigin(pds), did: trimmed }; + } + const origin = normalizeOrigin(trimmed); + return { origin, did: await resolveDid(origin) }; +} + /** * A fetch that routes same-origin requests through the OAuth agent (which - * signs each one with the session's DPoP key) and everything else through - * the plain window fetch. The conformance context keeps its bare `fetch` - * for the requests that must stay anonymous. + * attaches the session's DPoP-bound access token) and everything else + * through the plain window fetch. The conformance context keeps its bare + * `fetch` for the requests that must stay anonymous — and for those that + * present a space credential, which carry their own signature. */ function agentFetch(agent: OAuthUserAgent, origin: string): typeof fetch { return (input, init) => { @@ -101,7 +129,7 @@ export function SpacesConformanceView(props: { onExit: () => void }) { catalog: filtered, context, suiteVersion: "web", - alphaBuild: "0.0.0-spaces-alpha-20260818163953", + alphaBuild: ALPHA_BUILD, // Stream rows into the table as checks land. Skipped results // are checks this transport can never run — not listing them // avoids implying they could have; the footer counts them. @@ -149,8 +177,7 @@ export function SpacesConformanceView(props: { onExit: () => void }) { if (!raw) return; setAuthedRun(false); try { - const origin = normalizeOrigin(raw); - const did = await resolveDid(origin); + const { origin, did } = await resolveTarget(raw); await runCatalog( { target: { origin, did, implementation: origin }, @@ -173,13 +200,20 @@ export function SpacesConformanceView(props: { onExit: () => void }) { }); // In an anonymous run, the operator checks were skipped but WOULD run - // with a sign-in — worth a pointer. (The alpha-lib/identity checks are - // deliberately not mentioned at all: they never run in a browser.) - const operatorIds = new Set(operatorChecks.map((c) => c.id)); + // with a sign-in — worth a pointer. (The alpha-lib, identity and inbox + // checks are deliberately not mentioned at all: they never run in a + // browser, signed in or not.) + const signInIds = new Set( + operatorChecks + .filter((c) => !c.needs.includes("syncer-inbox")) + .map((c) => c.id), + ); const signInWouldRun = () => - (report()?.results ?? []).filter( - (r) => r.status === "skipped" && operatorIds.has(r.id), - ).length; + authedRun() + ? 0 + : (report()?.results ?? []).filter( + (r) => r.status === "skipped" && signInIds.has(r.id), + ).length; return (
@@ -202,15 +236,17 @@ export function SpacesConformanceView(props: { onExit: () => void }) { when={authedRun()} fallback={ <> - Discovery and request-shape checks against a live spaces host. - Sign in from the landing page to run the write, blob and - credential checks against your own PDS. + Discovery and request-shape checks against a live spaces host + (a hostname, or a DID to check its space host). Sign in from + the landing page to run the space, write, blob and credential + checks against your own PDS. } > Running the operator checks against{" "} - {target()}: probe spaces, record - writes, blob isolation and the delegation → credential → read flow. + {target()}: probe spaces and their + policies, record writes, blob isolation, and credentials — issued, + then presented with HTTP signatures and MAC requests.

@@ -218,7 +254,7 @@ export function SpacesConformanceView(props: { onExit: () => void }) {
setTarget(e.currentTarget.value)} class="flex-1 rounded border border-faint bg-transparent px-3 py-2 text-sm" diff --git a/apps/check/src/lib/oauth.ts b/apps/check/src/lib/oauth.ts index 298e466..66c8a00 100644 --- a/apps/check/src/lib/oauth.ts +++ b/apps/check/src/lib/oauth.ts @@ -15,15 +15,17 @@ import { actorResolver } from "./resolvers"; const SCOPE = "atproto transition:generic"; /** - * The extra grant the spaces conformance run signs in with: full record - * actions on any collection plus space create/update/delete management, - * scoped to the probe space type under the user's own authority - * (`authority` defaults to `self`). A PDS without the spaces alpha - * rejects the unknown scope at sign-in, which is the right failure — the - * suite is meaningless there. + * The extra grant the spaces conformance run signs in with: every space + * action on any collection plus create/update/delete management, scoped to + * the probe space type. `authority=*` because the suite deliberately + * addresses spaces the user does not own (NotSpaceOwner refusals); with the + * default `self` those would be scope refusals before the host's own check + * is reached. A PDS without the spaces alpha rejects the unknown scope at + * sign-in, which is the right failure — the suite is meaningless there. + * Keep in sync with the CLI's OAUTH_SCOPE and the worker's registration. */ const SPACE_SCOPE = - "space:earth.cirrus.check.space?collection=*&manage=create&manage=update&manage=delete"; + "space:earth.cirrus.check.space?authority=*&collection=*&manage=create&manage=update&manage=delete"; export const SPACES_SCOPE = `${SCOPE} ${SPACE_SCOPE}`; const CALLBACK_PATH = "/oauth/callback"; diff --git a/apps/check/src/worker.ts b/apps/check/src/worker.ts index 91c33f5..8fb80fd 100644 --- a/apps/check/src/worker.ts +++ b/apps/check/src/worker.ts @@ -29,7 +29,7 @@ function clientMetadata(origin: string): Record { // the write tests, the OAuth conformance flow, and the spaces // conformance run each request a subset of this registration. scope: - "atproto transition:generic repo:earth.cirrus.check.testrecord include:site.standard.authFull space:earth.cirrus.check.space?collection=*&manage=create&manage=update&manage=delete", + "atproto transition:generic repo:earth.cirrus.check.testrecord include:site.standard.authFull space:earth.cirrus.check.space?authority=*&collection=*&manage=create&manage=update&manage=delete", grant_types: ["authorization_code", "refresh_token"], response_types: ["code"], application_type: "web", From 31caa218c8801702a822d6beaa89811d2b8858f4 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 08:57:50 +0000 Subject: [PATCH 07/16] feat(space-conformance): port the suite to the 2026-11-05 alpha and recalibrate MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Rewrites the check catalogue (24 → 92 checks) for HTTP-signature credentials, MAC-authenticated commits and records, STAR archives, the baseline policies, writer sequencing, migration and revocation. Coverage now requires zero gaps against the vendored lexicons, with explicit, stale-checked exemptions. The reference matrix runs every capability against the 1105 reference PDS (89 pass, 3 pinned divergences) and pins the alpha build it was calibrated on. apps/check follows. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LZ7qcQNQoiA6a23woGC7tB --- .../space-conformance-alpha-20261105.md | 12 + apps/check/src/App.tsx | 13 +- apps/check/src/SpacesConformanceView.tsx | 17 +- packages/space-conformance-matrix/README.md | 55 +- .../space-conformance-matrix/src/harness.ts | 3 +- .../test/reference-matrix.test.ts | 5 +- packages/space-conformance/src/checks/base.ts | 21 +- .../src/checks/credential.ts | 433 ++++++++--- packages/space-conformance/src/checks/host.ts | 334 ++++++--- .../space-conformance/src/checks/probe.ts | 27 +- .../space-conformance/src/checks/records.ts | 365 +++++++-- .../space-conformance/src/checks/space.ts | 421 ++++++++--- packages/space-conformance/src/descriptors.ts | 47 +- packages/space-conformance/src/did.ts | 8 +- packages/space-conformance/src/full/checks.ts | 696 ++++++++++++------ .../space-conformance/src/full/helpers.ts | 10 +- packages/space-conformance/src/model.ts | 7 +- packages/space-conformance/src/space-auth.ts | 11 +- packages/space-conformance/test/cli.test.ts | 32 +- packages/space-conformance/test/core.test.ts | 4 +- packages/space-conformance/test/full.test.ts | 69 +- 21 files changed, 1926 insertions(+), 664 deletions(-) create mode 100644 .changeset/space-conformance-alpha-20261105.md diff --git a/.changeset/space-conformance-alpha-20261105.md b/.changeset/space-conformance-alpha-20261105.md new file mode 100644 index 0000000..8054677 --- /dev/null +++ b/.changeset/space-conformance-alpha-20261105.md @@ -0,0 +1,12 @@ +--- +"@getcirrus/space-conformance": minor +--- + +Port the conformance suite to the 2026-11-05 spaces alpha (`0.0.0-spaces-alpha-20261105160032`). The catalogue grows from 24 to 92 checks, and every method and declared error in the vendored lexicons is now covered by a `must` check, apart from the takedown, suspension and deactivation errors, which are exempted with a reason because no black-box harness can arrange them. + +- Credentials are presented with the `Atproto-Space-Credential` scheme and an HTTP message signature by a P-256 key, and credentialed reads send `Atproto-Space-Want-Mac`. The DPoP helpers are gone; `createCredentialKey`, `spaceSigHeaders` and `encapsulate` replace them, all browser-safe. +- New checks cover the baseline policies, member management, credential issuance and refusals, signature and audience binding, MAC requests and verification, STAR archives, writer-set sequencing, notifications, revocation, and space and repo migration. +- Discovery checks resolve the target's DID by method and look for `#atproto_pds`, `#atproto` and a P-256 `#atproto_kem`, replacing the `#atproto_space_host` checks. +- `Target.plcDirectory` and `CheckContext.resolveDid` control DID resolution; the CLI takes `--plc`. `SyncerInbox` gains `respond()` so a harness can act as a managing app. `KeypairIdentityProvider` takes an async `didFor` and builds identity DID documents. +- The CLI's OAuth scope asks for `authority=*` on the probe space type, so refusals for spaces the user does not own reach the host's own checks. +- The coverage report lists exemptions and flags stale ones, and `space-conformance coverage` now exits non-zero on gaps. diff --git a/apps/check/src/App.tsx b/apps/check/src/App.tsx index 60f495f..72fa073 100644 --- a/apps/check/src/App.tsx +++ b/apps/check/src/App.tsx @@ -763,14 +763,15 @@ function ConfirmSpacesView(props: { collections inside those probe spaces
  • - · Upload one 16-byte test blob and - verify it is not served publicly + · Upload two small random test + blobs, check one is not served publicly and the other + is served only through the space
  • - · Exercise your PDS's own{" "} - getDelegationToken →{" "} - getSpaceCredential → - read flow + · Obtain space credentials for the + probe spaces (including through your PDS's own{" "} + getDelegationToken) + and present them with signed, MAC-requesting reads
  • diff --git a/apps/check/src/SpacesConformanceView.tsx b/apps/check/src/SpacesConformanceView.tsx index 7ea2bde..6b7e19d 100644 --- a/apps/check/src/SpacesConformanceView.tsx +++ b/apps/check/src/SpacesConformanceView.tsx @@ -56,11 +56,16 @@ async function resolveDid(origin: string): Promise { * for that authority — which also covers multi-tenant did:plc hosts with * no did.json at their origin; a hostname resolves through did.json. */ -async function resolveTarget(input: string): Promise<{ origin: string; did: string }> { +async function resolveTarget( + input: string, +): Promise<{ origin: string; did: string }> { const trimmed = input.trim(); if (trimmed.startsWith("did:")) { const doc = await resolveDidDocument( - { fetch: window.fetch.bind(window), target: { origin: "", did: trimmed } }, + { + fetch: window.fetch.bind(window), + target: { origin: "", did: trimmed }, + }, trimmed, ); const pds = serviceEndpoint(doc, "atproto_pds"); @@ -236,10 +241,10 @@ export function SpacesConformanceView(props: { onExit: () => void }) { when={authedRun()} fallback={ <> - Discovery and request-shape checks against a live spaces host - (a hostname, or a DID to check its space host). Sign in from - the landing page to run the space, write, blob and credential - checks against your own PDS. + Discovery and request-shape checks against a live spaces host (a + hostname, or a DID to check its space host). Sign in from the + landing page to run the space, write, blob and credential checks + against your own PDS. } > diff --git a/packages/space-conformance-matrix/README.md b/packages/space-conformance-matrix/README.md index 24e1685..04f9b18 100644 --- a/packages/space-conformance-matrix/README.md +++ b/packages/space-conformance-matrix/README.md @@ -16,30 +16,50 @@ PDS in-process with [`@atproto/dev-env`](https://www.npmjs.com/package/@atproto/ creates an operator account, and runs the full check catalog against it. - A `must` check the reference **passes** is genuinely universal. +- A `should` check the reference **fails** is stale by definition, so the + matrix allows none. - A `must` check the reference **fails** is either a real gap in the alpha reference or an over-specification in our check. Each such case is pinned and cited in [`test/reference-matrix.test.ts`](test/reference-matrix.test.ts), so "the reference fails this" is a reviewed fact, not a surprise. -The test pins the **whole partition**: which checks pass, which diverge, which -skip. If a passing check regresses, CI fails. If a pinned divergence starts -_passing_ — the reference caught up, or a check quietly weakened — CI also -fails, forcing the list to be re-examined. The matrix is only worth having if -it cannot silently rot. +The test pins the **whole partition**: which checks pass and which diverge +(nothing skips — see below). If a passing check regresses, CI fails. If a +pinned divergence starts _passing_ — the reference caught up, or a check +quietly weakened — CI also fails, forcing the list to be re-examined. The +matrix is only worth having if it cannot silently rot. -## Pinned reference divergences (alpha `0.0.0-spaces-alpha-20260818163953`) +## What the run provides -| Check | Why the reference diverges | -| ------------------------------ | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | -| `discovery.space-host-service` | Reference is multi-tenant did:plc; it serves no DID document at `${origin}/.well-known/did.json`, so the space-host service entry can't be read there. | -| `discovery.verification-key` | Same: no DID document at the origin. | -| `blobs.space-blob-not-public` | Reference refuses an unreferenced upload on public `sync.getBlob`, but a space-record reference promotes the blob to public availability as a public reference would — the private write leaks the bytes. Proposal 0016 §blob-sync intends space blobs to be fetched via the credential-gated `space.getBlob`; Cirrus enforces it with a per-space key layout. | +Every capability the catalog can ask for, so nothing skips: -The identity-gated checks (foreign reader/writer DIDs) skip here because the -reference can't resolve harness identities; they run in-process against the -`@getcirrus/spaces` fixture adapter, which wires a did:key resolver. The -operator's own credential flow is still covered end-to-end by -`credential.self-round-trip`. +- an operator account (`seed.createAccount`) and its full-access session; +- the reference's own blob endpoints and `getDelegationToken`; +- harness identities the reference can resolve — each a tiny local HTTP + server publishing a `did:web:localhost%3A` document with an + `#atproto` key and an `#atproto_pds` service (the reference resolves + `localhost` did:webs over http, and dev-env disables SSRF protection) — + playing a reader, a writer's PDS, a foreign space authority and a + stranger; +- a syncer inbox (one of those identities) that records the reference's + `notifyWrite` / `notifySpaceDeleted` deliveries and answers its + `managedspace.checkUserAccess` queries; +- the dev-env PLC as `target.plcDirectory`, so the operator's did:plc + document (and its `#atproto_kem` key) resolves. + +## Pinned reference divergences (alpha `0.0.0-spaces-alpha-20261105160032`) + +| Check | Why the reference diverges | +| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `writes.delete-in-missing-space` | `deleteRecord` declares `SpaceNotFound`, and `deleteSpace`'s description says writes to a deleted space fail with it. The reference's `deleteRecord` checks whether the record exists before anything touches the space (`hasRecord` → no-op, for idempotency), so a delete in a missing or deleted space is a silent 200 and the `ensureRepo` space check (changeset `brave-spaces-exist`) is never reached. Its create, put and applyWrites do answer `SpaceNotFound`. | +| `space.reads-after-delete-not-found` | Same `deleteSpace` sentence, read side ("afterwards, reads … fail with SpaceNotFound"). The reference's read handlers never consult the space row: once the owner's repo is deleted they answer `RecordNotFound`, `RepoNotFound`, `BlobNotFound` or an empty 200 listing, never the `SpaceNotFound` each of them declares. | +| `credential.garbage-attestation-refused` | `ClientAttestationVerifier.verify` calls `parseSpaceToken` outside its `invalid()` wrapper, so a structurally malformed client attestation escapes as an uncaught `SpaceTokenError` — 500 `InternalServerError` where the lexicon declares `InvalidClientAttestation`. A well-formed but unverifiable attestation is refused correctly (`credential.unverifiable-attestation-refused` passes). | + +Everything else in the catalog passes against the reference, including the +identity-gated checks (foreign readers, writers' `notifyWrite`, foreign +authorities' credentials and revocations) and the inbox checks, which +earlier alphas had to skip because the reference could not resolve harness +identities. ## Running @@ -48,7 +68,8 @@ pnpm --filter @getcirrus/space-conformance-matrix test ``` `@getcirrus/space-conformance` must be built first (`pnpm build`), which CI -does before `pnpm test`. The reference stack pulls `better-sqlite3` (a native +does before `pnpm test`. The test also pins the suite's `ALPHA_BUILD`: bumping +the alpha without re-running and re-pinning this matrix fails it. The reference stack pulls `better-sqlite3` (a native module) and the `@atproto/lex*` family, which the spaces alpha published with leaked `workspace:*` specifiers — both are handled by `pnpm-workspace.yaml` (`allowBuilds` and `overrides` respectively). diff --git a/packages/space-conformance-matrix/src/harness.ts b/packages/space-conformance-matrix/src/harness.ts index 3fb1c83..4e75ee6 100644 --- a/packages/space-conformance-matrix/src/harness.ts +++ b/packages/space-conformance-matrix/src/harness.ts @@ -93,7 +93,8 @@ export async function startHarnessServices(): Promise { const inboxDid = syncer.did; const inbox: SyncerInbox = { - service: inboxDid, + // Named by fragment, the form registerNotify's lexicon describes. + service: `${inboxDid}#atproto_pds`, async waitFor(predicate, timeoutMs) { const deadline = Date.now() + timeoutMs; for (;;) { diff --git a/packages/space-conformance-matrix/test/reference-matrix.test.ts b/packages/space-conformance-matrix/test/reference-matrix.test.ts index 99548b6..1a7a816 100644 --- a/packages/space-conformance-matrix/test/reference-matrix.test.ts +++ b/packages/space-conformance-matrix/test/reference-matrix.test.ts @@ -29,10 +29,7 @@ import { } from "@getcirrus/space-conformance"; import { fullCatalog } from "@getcirrus/space-conformance/full"; import { startReferencePds, type ReferencePds } from "../src/reference.js"; -import { - startHarnessServices, - type HarnessServices, -} from "../src/harness.js"; +import { startHarnessServices, type HarnessServices } from "../src/harness.js"; /** The alpha build this partition was calibrated against. */ const CALIBRATED_ALPHA = "0.0.0-spaces-alpha-20261105160032"; diff --git a/packages/space-conformance/src/checks/base.ts b/packages/space-conformance/src/checks/base.ts index 347e4fa..36a7c1b 100644 --- a/packages/space-conformance/src/checks/base.ts +++ b/packages/space-conformance/src/checks/base.ts @@ -89,7 +89,11 @@ const discoveryKemKey = defineCheck({ // account's repos can be authenticated at all. const doc = await targetDoc(ctx); const key = verificationMethodDidKey(doc, "atproto_kem"); - if (!key) return fail("no #atproto_kem verification method", doc.verificationMethod); + if (!key) + return fail( + "no #atproto_kem verification method", + doc.verificationMethod, + ); return isP256DidKey(key) ? pass(`#atproto_kem is ${key}`) : fail(`#atproto_kem is not a P-256 key: ${key}`); @@ -147,9 +151,12 @@ const authGetRecordRequiresAuth = defineCheck({ const credentialTokenlessUnknown = defineCheck({ id: "credential.tokenless-unknown-space", - title: "A tokenless credential request for an unknown space gets SpaceNotFound", + title: + "A tokenless credential request for an unknown space gets SpaceNotFound", tier: "must", - citations: [lexicon("com.atproto.space.getSpaceCredential@error:SpaceNotFound")], + citations: [ + lexicon("com.atproto.space.getSpaceCredential@error:SpaceNotFound"), + ], needs: [], async run(ctx) { // No delegation token, a space nobody created: there is nothing public @@ -160,7 +167,8 @@ const credentialTokenlessUnknown = defineCheck({ space: unknownSpaceUri(ctx.target.did), credentialKid: key.did, }); - if (res.status === 200) return fail("issued a credential for an unknown space"); + if (res.status === 200) + return fail("issued a credential for an unknown space"); return res.error === "SpaceNotFound" ? pass("refused with SpaceNotFound") : fail(`refused with ${describe(res)}, expected SpaceNotFound`, res.json); @@ -181,7 +189,10 @@ const requestInvalidSpaceUri = defineCheck({ if (res.status >= 400 && res.status < 500) { return pass(`rejected with ${describe(res)}`); } - return fail(`did not reject a malformed space uri (${res.status})`, res.json); + return fail( + `did not reject a malformed space uri (${res.status})`, + res.json, + ); }, }); diff --git a/packages/space-conformance/src/checks/credential.ts b/packages/space-conformance/src/checks/credential.ts index 68e7ae5..897006f 100644 --- a/packages/space-conformance/src/checks/credential.ts +++ b/packages/space-conformance/src/checks/credential.ts @@ -84,7 +84,8 @@ const readShared = ( const credentialTokenlessPolicies = defineCheck({ id: "credential.tokenless-by-policy", - title: "Without a delegation token only a public-read space issues; others answer SpaceNotFound", + title: + "Without a delegation token only a public-read space issues; others answer SpaceNotFound", tier: "must", citations: [ L("com.atproto.space.getSpaceCredential"), @@ -100,24 +101,36 @@ const credentialTokenlessPolicies = defineCheck({ const personal = await createProbeSpace(ctx, personalspace()); try { const a = await requestCredential(ctx, open.uri); - if (!a.credential) return fail(`public-read space refused a tokenless request: ${describe(a.result)}`, a.result.json); + if (!a.credential) + return fail( + `public-read space refused a tokenless request: ${describe(a.result)}`, + a.result.json, + ); const misses: string[] = []; - for (const [label, space] of [["memberspace", closed], ["personalspace", personal]] as const) { + for (const [label, space] of [ + ["memberspace", closed], + ["personalspace", personal], + ] as const) { const res = await requestCredential(ctx, space.uri); - if (res.result.error !== "SpaceNotFound") misses.push(`${label} → ${describe(res.result)}`); + if (res.result.error !== "SpaceNotFound") + misses.push(`${label} → ${describe(res.result)}`); } return misses.length ? fail(`expected SpaceNotFound: ${misses.join("; ")}`) - : pass("public-read issued; closed memberspace and personalspace answered SpaceNotFound"); + : pass( + "public-read issued; closed memberspace and personalspace answered SpaceNotFound", + ); } finally { - for (const s of [open, closed, personal]) await deleteProbeSpace(ctx, s.uri); + for (const s of [open, closed, personal]) + await deleteProbeSpace(ctx, s.uri); } }, }); const credentialClaims = defineCheck({ id: "credential.claims", - title: "A credential is signed by the authority for the space, bound to the requested key", + title: + "A credential is signed by the authority for the space, bound to the requested key", tier: "must", citations: [ L("com.atproto.space.getSpaceCredential"), @@ -133,18 +146,24 @@ const credentialClaims = defineCheck({ const { header, payload } = decodeJwt(credential.credential); const cnf = payload.cnf as { kid?: unknown } | undefined; const problems: string[] = []; - if (header.typ !== "atproto-space-credential+jwt") problems.push(`typ ${String(header.typ)}`); + if (header.typ !== "atproto-space-credential+jwt") + problems.push(`typ ${String(header.typ)}`); if (header.kid !== "#atproto") problems.push(`kid ${String(header.kid)}`); - if (payload.iss !== ctx.target.did) problems.push(`iss ${String(payload.iss)}`); - if (payload.sub !== space.uri) problems.push(`sub ${String(payload.sub)}`); - if (cnf?.kid !== credential.key.did) problems.push(`cnf.kid ${String(cnf?.kid)}`); + if (payload.iss !== ctx.target.did) + problems.push(`iss ${String(payload.iss)}`); + if (payload.sub !== space.uri) + problems.push(`sub ${String(payload.sub)}`); + if (cnf?.kid !== credential.key.did) + problems.push(`cnf.kid ${String(cnf?.kid)}`); // Credentials carry no audience: each use is bound to one by its // HTTP signature instead. if ("aud" in payload) problems.push(`has aud ${String(payload.aud)}`); - if (typeof payload.jti !== "string" || !payload.jti) problems.push("no jti"); + if (typeof payload.jti !== "string" || !payload.jti) + problems.push("no jti"); const iat = Number(payload.iat); const exp = Number(payload.exp); - if (!(exp > iat) || exp - iat > 3600) problems.push(`lifetime ${exp - iat}s (max 3600)`); + if (!(exp > iat) || exp - iat > 3600) + problems.push(`lifetime ${exp - iat}s (max 3600)`); return problems.length ? fail(`credential claims: ${problems.join(", ")}`, { header, payload }) : pass(`typ/kid/iss/sub/cnf correct, no aud, ${exp - iat}s lifetime`); @@ -158,13 +177,20 @@ const credentialDefaultLifetime = defineCheck({ id: "credential.default-lifetime", title: "Credentials live 600 seconds, the reference default", tier: "should", - citations: [{ source: "reference", ref: "@atproto/space SPACE_TOKEN_TYPES.credential.expiresInSec" }], + citations: [ + { + source: "reference", + ref: "@atproto/space SPACE_TOKEN_TYPES.credential.expiresInSec", + }, + ], needs: ["operator"], destructive: true, async run(ctx) { const space = await createProbeSpace(ctx, publicRead()); try { - const { payload } = decodeJwt((await obtainPublicCredential(ctx, space.uri)).credential); + const { payload } = decodeJwt( + (await obtainPublicCredential(ctx, space.uri)).credential, + ); const lifetime = Number(payload.exp) - Number(payload.iat); return lifetime === 600 ? pass("600s") : fail(`${lifetime}s`); } finally { @@ -175,7 +201,8 @@ const credentialDefaultLifetime = defineCheck({ const credentialKidP256 = defineCheck({ id: "credential.kid-must-be-p256", - title: "getSpaceCredential refuses a credentialKid that is not a P-256 did:key", + title: + "getSpaceCredential refuses a credentialKid that is not a P-256 did:key", tier: "must", citations: [L("com.atproto.space.getSpaceCredential")], needs: ["operator"], @@ -185,15 +212,29 @@ const credentialKidP256 = defineCheck({ try { // A well-formed secp256k1 did:key: valid syntax, wrong curve. The // credential could never be presented — HTTP signatures are P-256. - const k256 = formatDidKey("ES256K", new Uint8Array([0x02, ...crypto.getRandomValues(new Uint8Array(32))])); - const bad = await requestCredential(ctx, space.uri, { credentialKid: k256 }); - if (bad.credential) return fail("issued a credential bound to a secp256k1 key"); - const notKey = await requestCredential(ctx, space.uri, { credentialKid: ctx.target.did }); - if (notKey.credential) return fail("issued a credential bound to a non-key DID"); + const k256 = formatDidKey( + "ES256K", + new Uint8Array([0x02, ...crypto.getRandomValues(new Uint8Array(32))]), + ); + const bad = await requestCredential(ctx, space.uri, { + credentialKid: k256, + }); + if (bad.credential) + return fail("issued a credential bound to a secp256k1 key"); + const notKey = await requestCredential(ctx, space.uri, { + credentialKid: ctx.target.did, + }); + if (notKey.credential) + return fail("issued a credential bound to a non-key DID"); const good = await requestCredential(ctx, space.uri); return good.credential - ? pass(`refused secp256k1 (${describe(bad.result)}) and non-key (${describe(notKey.result)}) kids; P-256 issued`) - : fail(`positive control failed: ${describe(good.result)}`, good.result.json); + ? pass( + `refused secp256k1 (${describe(bad.result)}) and non-key (${describe(notKey.result)}) kids; P-256 issued`, + ) + : fail( + `positive control failed: ${describe(good.result)}`, + good.result.json, + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -204,17 +245,25 @@ const credentialGarbageDelegation = defineCheck({ id: "credential.garbage-delegation-refused", title: "A malformed delegation token is refused with InvalidDelegationToken", tier: "must", - citations: [L("com.atproto.space.getSpaceCredential@error:InvalidDelegationToken")], + citations: [ + L("com.atproto.space.getSpaceCredential@error:InvalidDelegationToken"), + ], needs: ["operator"], destructive: true, async run(ctx) { const space = await createProbeSpace(ctx, memberspace()); try { - const res = await requestCredential(ctx, space.uri, { delegationToken: "not.a.token" }); - if (res.credential) return fail("issued a credential for a garbage delegation token"); + const res = await requestCredential(ctx, space.uri, { + delegationToken: "not.a.token", + }); + if (res.credential) + return fail("issued a credential for a garbage delegation token"); return res.result.error === "InvalidDelegationToken" ? pass("refused with InvalidDelegationToken") - : fail(`refused with ${describe(res.result)}, expected InvalidDelegationToken`, res.result.json); + : fail( + `refused with ${describe(res.result)}, expected InvalidDelegationToken`, + res.result.json, + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -231,22 +280,27 @@ async function unverifiableAttestation(authority: string): Promise { const key = await createCredentialKey(); const iat = Math.floor(Date.now() / 1000); const part = (obj: unknown) => toBase64Url(utf8(JSON.stringify(obj))); - const input = `${part({ alg: "ES256", typ: "atproto-client-attestation+jwt" })}.${part({ - iss: clientId, - sub: clientId, - aud: `${authority}#atproto_pds`, - iat, - exp: iat + 60, - jti: toBase64Url(crypto.getRandomValues(new Uint8Array(16))), - })}`; + const input = `${part({ alg: "ES256", typ: "atproto-client-attestation+jwt" })}.${part( + { + iss: clientId, + sub: clientId, + aud: `${authority}#atproto_pds`, + iat, + exp: iat + 60, + jti: toBase64Url(crypto.getRandomValues(new Uint8Array(16))), + }, + )}`; return `${input}.${toBase64Url(await key.sign(utf8(input)))}`; } -const attestationCitations = [L("com.atproto.space.getSpaceCredential@error:InvalidClientAttestation")]; +const attestationCitations = [ + L("com.atproto.space.getSpaceCredential@error:InvalidClientAttestation"), +]; const credentialUnverifiableAttestation = defineCheck({ id: "credential.unverifiable-attestation-refused", - title: "A client attestation that cannot be verified is refused with InvalidClientAttestation", + title: + "A client attestation that cannot be verified is refused with InvalidClientAttestation", tier: "must", citations: attestationCitations, needs: ["operator"], @@ -259,10 +313,16 @@ const credentialUnverifiableAttestation = defineCheck({ const res = await requestCredential(ctx, space.uri, { clientAttestation: await unverifiableAttestation(ctx.target.did), }); - if (res.credential) return fail("issued a credential on an unverifiable client attestation"); + if (res.credential) + return fail( + "issued a credential on an unverifiable client attestation", + ); return res.result.error === "InvalidClientAttestation" ? pass("refused with InvalidClientAttestation") - : fail(`refused with ${describe(res.result)}, expected InvalidClientAttestation`, res.result.json); + : fail( + `refused with ${describe(res.result)}, expected InvalidClientAttestation`, + res.result.json, + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -271,7 +331,8 @@ const credentialUnverifiableAttestation = defineCheck({ const credentialGarbageAttestation = defineCheck({ id: "credential.garbage-attestation-refused", - title: "A malformed client attestation is refused with InvalidClientAttestation", + title: + "A malformed client attestation is refused with InvalidClientAttestation", tier: "must", citations: attestationCitations, needs: ["operator"], @@ -279,11 +340,17 @@ const credentialGarbageAttestation = defineCheck({ async run(ctx) { const space = await createProbeSpace(ctx, publicRead()); try { - const res = await requestCredential(ctx, space.uri, { clientAttestation: "not.an.attestation" }); - if (res.credential) return fail("issued a credential despite a garbage client attestation"); + const res = await requestCredential(ctx, space.uri, { + clientAttestation: "not.an.attestation", + }); + if (res.credential) + return fail("issued a credential despite a garbage client attestation"); return res.result.error === "InvalidClientAttestation" ? pass("refused with InvalidClientAttestation") - : fail(`refused with ${describe(res.result)}, expected InvalidClientAttestation`, res.result.json); + : fail( + `refused with ${describe(res.result)}, expected InvalidClientAttestation`, + res.result.json, + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -292,7 +359,8 @@ const credentialGarbageAttestation = defineCheck({ const credentialAllowedApps = defineCheck({ id: "credential.allowed-apps-gate", - title: "A memberspace with allowedApps refuses an unattested app with AppNotAuthorized", + title: + "A memberspace with allowedApps refuses an unattested app with AppNotAuthorized", tier: "must", citations: [ L("com.atproto.space.getSpaceCredential@error:AppNotAuthorized"), @@ -305,14 +373,23 @@ const credentialAllowedApps = defineCheck({ // app perimeter is left to refuse. const space = await createProbeSpace( ctx, - memberspace({ publicRead: true, allowedApps: ["https://app.space-conformance.invalid/client-metadata.json"] }), + memberspace({ + publicRead: true, + allowedApps: [ + "https://app.space-conformance.invalid/client-metadata.json", + ], + }), ); try { const res = await requestCredential(ctx, space.uri); - if (res.credential) return fail("issued a credential to an app outside allowedApps"); + if (res.credential) + return fail("issued a credential to an app outside allowedApps"); return res.result.error === "AppNotAuthorized" ? pass("refused with AppNotAuthorized") - : fail(`refused with ${describe(res.result)}, expected AppNotAuthorized`, res.result.json); + : fail( + `refused with ${describe(res.result)}, expected AppNotAuthorized`, + res.result.json, + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -335,16 +412,22 @@ const credentialDeletedSpace = defineCheck({ const before = await requestCredential(ctx, space.uri); if (!before.credential) { await deleteProbeSpace(ctx, space.uri); - return fail(`could not obtain a credential before deletion (${describe(before.result)})`); + return fail( + `could not obtain a credential before deletion (${describe(before.result)})`, + ); } await deleteProbeSpace(ctx, space.uri); const after = await requestCredential(ctx, space.uri); - if (after.credential) return fail("a deleted space still issued a credential"); + if (after.credential) + return fail("a deleted space still issued a credential"); // The durable tombstone: a syncer that missed notifySpaceDeleted learns // it here on renewal — tokenless, as a public space's syncer would ask. return after.result.error === "SpaceDeleted" ? pass("answered SpaceDeleted") - : fail(`answered ${describe(after.result)}, expected SpaceDeleted`, after.result.json); + : fail( + `answered ${describe(after.result)}, expected SpaceDeleted`, + after.result.json, + ); }, }); @@ -352,7 +435,8 @@ const credentialDeletedSpace = defineCheck({ const credentialSelfRoundTrip = defineCheck({ id: "credential.self-round-trip", - title: "Operator obtains a credential via getDelegationToken and reads with it", + title: + "Operator obtains a credential via getDelegationToken and reads with it", tier: "must", citations: [ L("com.atproto.space.getDelegationToken"), @@ -366,11 +450,18 @@ const credentialSelfRoundTrip = defineCheck({ const space = await createProbeSpace(ctx, memberspace()); try { await mustCreateRecord(ctx, space.uri, "shared", "mine"); - const { result, credential, delegation } = await obtainCredentialViaDelegation(ctx, space.uri); - if (delegation.status !== 200) return fail(`getDelegationToken ${describe(delegation)}`, delegation.json); - if (!credential) return fail(`getSpaceCredential ${describe(result)}`, result.json); + const { result, credential, delegation } = + await obtainCredentialViaDelegation(ctx, space.uri); + if (delegation.status !== 200) + return fail( + `getDelegationToken ${describe(delegation)}`, + delegation.json, + ); + if (!credential) + return fail(`getSpaceCredential ${describe(result)}`, result.json); const read = await readShared(ctx, credential, space.uri); - if (read.status !== 200) return fail(`credential read failed: ${describe(read)}`, read.json); + if (read.status !== 200) + return fail(`credential read failed: ${describe(read)}`, read.json); return read.headers.get(MAC_HEADER) ? pass("delegation → credential → MAC'd read works") : fail("the credentialed read carried no Atproto-Space-Mac header"); @@ -382,25 +473,42 @@ const credentialSelfRoundTrip = defineCheck({ const delegationClaims = defineCheck({ id: "delegation.token-claims", - title: "getDelegationToken mints a token for the space's #atproto_pds, signed by #atproto", + title: + "getDelegationToken mints a token for the space's #atproto_pds, signed by #atproto", tier: "must", - citations: [L("com.atproto.space.getDelegationToken"), C("plain-keys-resolve")], + citations: [ + L("com.atproto.space.getDelegationToken"), + C("plain-keys-resolve"), + ], needs: ["operator", "pds-delegation"], destructive: true, async run(ctx) { const space = await createProbeSpace(ctx, memberspace()); try { - const res = await xrpcGet(asOperator(ctx), "com.atproto.space.getDelegationToken", { space: space.uri }); - if (res.status !== 200) return fail(`getDelegationToken ${describe(res)}`, res.json); - const { header, payload } = decodeJwt((res.json as { token: string }).token); + const res = await xrpcGet( + asOperator(ctx), + "com.atproto.space.getDelegationToken", + { space: space.uri }, + ); + if (res.status !== 200) + return fail(`getDelegationToken ${describe(res)}`, res.json); + const { header, payload } = decodeJwt( + (res.json as { token: string }).token, + ); const problems: string[] = []; - if (header.typ !== "atproto-space-delegation+jwt") problems.push(`typ ${String(header.typ)}`); + if (header.typ !== "atproto-space-delegation+jwt") + problems.push(`typ ${String(header.typ)}`); if (header.kid !== "#atproto") problems.push(`kid ${String(header.kid)}`); - if (payload.iss !== ctx.target.did) problems.push(`iss ${String(payload.iss)}`); - if (payload.sub !== space.uri) problems.push(`sub ${String(payload.sub)}`); - if (payload.aud !== `${ctx.target.did}#atproto_pds`) problems.push(`aud ${String(payload.aud)}`); - if (typeof payload.jti !== "string" || !payload.jti) problems.push("no jti"); - if (!(Number(payload.exp) > Math.floor(Date.now() / 1000) - 5)) problems.push("already expired"); + if (payload.iss !== ctx.target.did) + problems.push(`iss ${String(payload.iss)}`); + if (payload.sub !== space.uri) + problems.push(`sub ${String(payload.sub)}`); + if (payload.aud !== `${ctx.target.did}#atproto_pds`) + problems.push(`aud ${String(payload.aud)}`); + if (typeof payload.jti !== "string" || !payload.jti) + problems.push("no jti"); + if (!(Number(payload.exp) > Math.floor(Date.now() / 1000) - 5)) + problems.push("already expired"); return problems.length ? fail(`delegation token: ${problems.join(", ")}`, { header, payload }) : pass("typ/kid/iss/sub/aud as specified"); @@ -414,22 +522,39 @@ const delegationReplay = defineCheck({ id: "delegation.replay-refused", title: "A delegation token cannot be used twice", tier: "must", - citations: [L("com.atproto.space.getSpaceCredential@error:InvalidDelegationToken")], + citations: [ + L("com.atproto.space.getSpaceCredential@error:InvalidDelegationToken"), + ], needs: ["operator", "pds-delegation"], destructive: true, async run(ctx) { const space = await createProbeSpace(ctx, memberspace()); try { - const res = await xrpcGet(asOperator(ctx), "com.atproto.space.getDelegationToken", { space: space.uri }); - if (res.status !== 200) return fail(`getDelegationToken ${describe(res)}`, res.json); + const res = await xrpcGet( + asOperator(ctx), + "com.atproto.space.getDelegationToken", + { space: space.uri }, + ); + if (res.status !== 200) + return fail(`getDelegationToken ${describe(res)}`, res.json); const delegationToken = (res.json as { token: string }).token; - const first = await requestCredential(ctx, space.uri, { delegationToken }); - if (!first.credential) return fail(`first exchange failed (${describe(first.result)}); cannot test replay`); - const second = await requestCredential(ctx, space.uri, { delegationToken }); - if (second.credential) return fail("a replayed delegation token was accepted"); + const first = await requestCredential(ctx, space.uri, { + delegationToken, + }); + if (!first.credential) + return fail( + `first exchange failed (${describe(first.result)}); cannot test replay`, + ); + const second = await requestCredential(ctx, space.uri, { + delegationToken, + }); + if (second.credential) + return fail("a replayed delegation token was accepted"); return second.result.error === "InvalidDelegationToken" ? pass("replay refused with InvalidDelegationToken") - : fail(`replay refused with ${describe(second.result)}, expected InvalidDelegationToken`); + : fail( + `replay refused with ${describe(second.result)}, expected InvalidDelegationToken`, + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -440,20 +565,32 @@ const delegationWrongSpace = defineCheck({ id: "delegation.wrong-space-refused", title: "A delegation token for one space is refused for another", tier: "must", - citations: [L("com.atproto.space.getSpaceCredential@error:InvalidDelegationToken")], + citations: [ + L("com.atproto.space.getSpaceCredential@error:InvalidDelegationToken"), + ], needs: ["operator", "pds-delegation"], destructive: true, async run(ctx) { const a = await createProbeSpace(ctx, memberspace()); const b = await createProbeSpace(ctx, memberspace()); try { - const res = await xrpcGet(asOperator(ctx), "com.atproto.space.getDelegationToken", { space: a.uri }); - if (res.status !== 200) return fail(`getDelegationToken ${describe(res)}`, res.json); - const cross = await requestCredential(ctx, b.uri, { delegationToken: (res.json as { token: string }).token }); - if (cross.credential) return fail("a token for space A issued a credential for space B"); + const res = await xrpcGet( + asOperator(ctx), + "com.atproto.space.getDelegationToken", + { space: a.uri }, + ); + if (res.status !== 200) + return fail(`getDelegationToken ${describe(res)}`, res.json); + const cross = await requestCredential(ctx, b.uri, { + delegationToken: (res.json as { token: string }).token, + }); + if (cross.credential) + return fail("a token for space A issued a credential for space B"); return cross.result.error === "InvalidDelegationToken" ? pass("refused with InvalidDelegationToken") - : fail(`refused with ${describe(cross.result)}, expected InvalidDelegationToken`); + : fail( + `refused with ${describe(cross.result)}, expected InvalidDelegationToken`, + ); } finally { await deleteProbeSpace(ctx, a.uri); await deleteProbeSpace(ctx, b.uri); @@ -480,11 +617,17 @@ const credentialSignatureRequired = defineCheck({ async run(ctx) { return withPublicSpace(ctx, async (space, credential) => { const ok = await readShared(ctx, credential, space.uri); - if (ok.status !== 200) return fail(`positive control failed: ${describe(ok)}`, ok.json); - const bare = await readShared(ctx, credential, space.uri, { unsigned: true }); + if (ok.status !== 200) + return fail(`positive control failed: ${describe(ok)}`, ok.json); + const bare = await readShared(ctx, credential, space.uri, { + unsigned: true, + }); return bare.status >= 400 && bare.status < 500 ? pass(`signed read 200; unsigned read refused (${describe(bare)})`) - : fail(`an unsigned credential read returned ${describe(bare)}`, bare.json); + : fail( + `an unsigned credential read returned ${describe(bare)}`, + bare.json, + ); }); }, }); @@ -501,10 +644,16 @@ const credentialAudienceBound = defineCheck({ // other DID is a request meant for someone else, replayed here. return withPublicSpace(ctx, async (space, credential) => { const ok = await readShared(ctx, credential, space.uri); - if (ok.status !== 200) return fail(`positive control failed: ${describe(ok)}`, ok.json); - const misaddressed = await readShared(ctx, credential, space.uri, { audience: FOREIGN_DID }); + if (ok.status !== 200) + return fail(`positive control failed: ${describe(ok)}`, ok.json); + const misaddressed = await readShared(ctx, credential, space.uri, { + audience: FOREIGN_DID, + }); if (misaddressed.status < 400 || misaddressed.status >= 500) { - return fail(`a misaddressed repo-host read returned ${describe(misaddressed)}`, misaddressed.json); + return fail( + `a misaddressed repo-host read returned ${describe(misaddressed)}`, + misaddressed.json, + ); } // The same at the space host, whose audience is the authority. const listRepos = (audience: string) => @@ -513,11 +662,20 @@ const credentialAudienceBound = defineCheck({ audience, }); const hostOk = await listRepos(ctx.target.did); - if (hostOk.status !== 200) return fail(`listRepos positive control failed: ${describe(hostOk)}`, hostOk.json); + if (hostOk.status !== 200) + return fail( + `listRepos positive control failed: ${describe(hostOk)}`, + hostOk.json, + ); const hostWrong = await listRepos(FOREIGN_DID); return hostWrong.status >= 400 && hostWrong.status < 500 - ? pass(`refused signatures over another audience at the repo host (${describe(misaddressed)}) and space host (${describe(hostWrong)})`) - : fail(`a misaddressed listRepos returned ${describe(hostWrong)}`, hostWrong.json); + ? pass( + `refused signatures over another audience at the repo host (${describe(misaddressed)}) and space host (${describe(hostWrong)})`, + ) + : fail( + `a misaddressed listRepos returned ${describe(hostWrong)}`, + hostWrong.json, + ); }); }, }); @@ -532,11 +690,17 @@ const credentialWrongKey = defineCheck({ async run(ctx) { return withPublicSpace(ctx, async (space, credential) => { const ok = await readShared(ctx, credential, space.uri); - if (ok.status !== 200) return fail(`positive control failed: ${describe(ok)}`, ok.json); - const thief = await readShared(ctx, credential, space.uri, { signWith: await createCredentialKey() }); + if (ok.status !== 200) + return fail(`positive control failed: ${describe(ok)}`, ok.json); + const thief = await readShared(ctx, credential, space.uri, { + signWith: await createCredentialKey(), + }); return thief.status >= 400 && thief.status < 500 ? pass(`refused a signature by the wrong key (${describe(thief)})`) - : fail(`a credential signed by a stranger's key returned ${describe(thief)}`, thief.json); + : fail( + `a credential signed by a stranger's key returned ${describe(thief)}`, + thief.json, + ); }); }, }); @@ -550,7 +714,9 @@ const credentialSchemeCase = defineCheck({ destructive: true, async run(ctx) { return withPublicSpace(ctx, async (space, credential) => { - const lower = await readShared(ctx, credential, space.uri, { scheme: "atproto-space-credential" }); + const lower = await readShared(ctx, credential, space.uri, { + scheme: "atproto-space-credential", + }); return lower.status === 200 ? pass("a lowercase scheme was accepted") : fail(`a lowercase scheme returned ${describe(lower)}`, lower.json); @@ -571,7 +737,8 @@ const credentialCrossSpace = defineCheck({ await mustCreateRecord(ctx, other.uri, "shared", "b"); return await withPublicSpace(ctx, async (space, credential) => { const ok = await readShared(ctx, credential, space.uri); - if (ok.status !== 200) return fail(`positive control failed: ${describe(ok)}`, ok.json); + if (ok.status !== 200) + return fail(`positive control failed: ${describe(ok)}`, ok.json); const cross = await readShared(ctx, credential, other.uri); return cross.status === 200 ? fail("a space-A credential read space B", cross.json) @@ -585,7 +752,8 @@ const credentialCrossSpace = defineCheck({ const credentialUnhostedRepo = defineCheck({ id: "credential.unhosted-repo-not-found", - title: "Credentialed reads of a repo the host does not hold answer RepoNotFound", + title: + "Credentialed reads of a repo the host does not hold answer RepoNotFound", tier: "must", citations: [ L("com.atproto.space.getRecord@error:RepoNotFound"), @@ -607,18 +775,32 @@ const credentialUnhostedRepo = defineCheck({ const share = (await createCredentialKey()).did; const base = { space: space.uri, repo }; const reads: Array<[string, Record, string | false]> = [ - ["getRecord", { ...base, collection: POST, rkey: "shared" }, formatWantMacHeader(RECORD_MAC_TYPE, share)], + [ + "getRecord", + { ...base, collection: POST, rkey: "shared" }, + formatWantMacHeader(RECORD_MAC_TYPE, share), + ], ["getLatestCommit", base, formatWantMacHeader(COMMIT_MAC_TYPE, share)], ["getRepo", base, formatWantMacHeader(COMMIT_MAC_TYPE, share)], ["listRepoOps", base, formatWantMacHeader(COMMIT_MAC_TYPE, share)], ["listRecords", base, false], ["listBlobs", base, false], - ["getBlob", { ...base, cid: await rawCid(utf8("no such blob")) }, false], + [ + "getBlob", + { ...base, cid: await rawCid(utf8("no such blob")) }, + false, + ], ]; const misses: string[] = []; for (const [name, params, wantMac] of reads) { - const res = await credentialCall(ctx, credential, `com.atproto.space.${name}`, { params, wantMac }); - if (res.error !== "RepoNotFound") misses.push(`${name} → ${describe(res)}`); + const res = await credentialCall( + ctx, + credential, + `com.atproto.space.${name}`, + { params, wantMac }, + ); + if (res.error !== "RepoNotFound") + misses.push(`${name} → ${describe(res)}`); } return misses.length ? fail(`expected RepoNotFound: ${misses.join("; ")}`) @@ -629,7 +811,8 @@ const credentialUnhostedRepo = defineCheck({ const macWantRequired = defineCheck({ id: "mac.want-mac-required", - title: "Credentialed reads of a commit or record without Atproto-Space-Want-Mac answer BadSpaceMac", + title: + "Credentialed reads of a commit or record without Atproto-Space-Want-Mac answer BadSpaceMac", tier: "must", citations: [ L("com.atproto.space.getLatestCommit@error:BadSpaceMac"), @@ -657,12 +840,18 @@ const macWantRequired = defineCheck({ misses.push(`${name} with a MAC request → ${describe(ok)}`); continue; } - const res = await credentialCall(ctx, credential, nsid, { params, wantMac: false }); - if (res.error !== "BadSpaceMac") misses.push(`${name} without → ${describe(res)}`); + const res = await credentialCall(ctx, credential, nsid, { + params, + wantMac: false, + }); + if (res.error !== "BadSpaceMac") + misses.push(`${name} without → ${describe(res)}`); } return misses.length ? fail(misses.join("; ")) - : pass("each served with a MAC request and answered BadSpaceMac without one"); + : pass( + "each served with a MAC request and answered BadSpaceMac without one", + ); }); }, }); @@ -682,15 +871,41 @@ const macMalformed = defineCheck({ const share = (await createCredentialKey()).did; const commit = { space: space.uri, repo: ctx.target.did }; const probes: Array<[string, string, Record, string]> = [ - ["bad key share", "getLatestCommit", commit, `type="${COMMIT_MAC_TYPE}", ver=1, key_share="did:key:zNotAKey"`], - ["unsupported version", "getLatestCommit", commit, `type="${COMMIT_MAC_TYPE}", ver=99, key_share="${share}"`], - ["record read asking for a commit MAC", "getRecord", recordParams(ctx, space.uri), formatWantMacHeader(COMMIT_MAC_TYPE, share)], - ["not a structured header", "getRecord", recordParams(ctx, space.uri), "please"], + [ + "bad key share", + "getLatestCommit", + commit, + `type="${COMMIT_MAC_TYPE}", ver=1, key_share="did:key:zNotAKey"`, + ], + [ + "unsupported version", + "getLatestCommit", + commit, + `type="${COMMIT_MAC_TYPE}", ver=99, key_share="${share}"`, + ], + [ + "record read asking for a commit MAC", + "getRecord", + recordParams(ctx, space.uri), + formatWantMacHeader(COMMIT_MAC_TYPE, share), + ], + [ + "not a structured header", + "getRecord", + recordParams(ctx, space.uri), + "please", + ], ]; const misses: string[] = []; for (const [label, name, params, header] of probes) { - const res = await credentialCall(ctx, credential, `com.atproto.space.${name}`, { params, wantMac: header }); - if (res.error !== "BadSpaceMac") misses.push(`${label} → ${describe(res)}`); + const res = await credentialCall( + ctx, + credential, + `com.atproto.space.${name}`, + { params, wantMac: header }, + ); + if (res.error !== "BadSpaceMac") + misses.push(`${label} → ${describe(res)}`); } return misses.length ? fail(`expected BadSpaceMac: ${misses.join("; ")}`) diff --git a/packages/space-conformance/src/checks/host.ts b/packages/space-conformance/src/checks/host.ts index 4ee0ede..dc3b763 100644 --- a/packages/space-conformance/src/checks/host.ts +++ b/packages/space-conformance/src/checks/host.ts @@ -7,7 +7,13 @@ import { defineCheck } from "../registry.js"; import { asOperator, xrpcGet, xrpcPost } from "../http.js"; -import { fail, pass, type Check, type CheckContext, type InboxDelivery } from "../model.js"; +import { + fail, + pass, + type Check, + type CheckContext, + type InboxDelivery, +} from "../model.js"; import { bytesEqual, isTid, lexBytes } from "../encoding.js"; import { FOREIGN_DID, @@ -24,6 +30,13 @@ import { fakeDid } from "./space.js"; const L = (ref: string) => ({ source: "lexicon" as const, ref }); +/** + * A service identifier sure to resolve: the target's own `#atproto_pds` + * entry, named explicitly by fragment (registerNotify: "a DID with an + * optional service fragment naming the entry in its DID document"). + */ +const ownService = (ctx: CheckContext) => `${ctx.target.did}#atproto_pds`; + interface WriterEntry { did: string; repoRev: unknown; @@ -36,17 +49,25 @@ async function listRepos( credential: Credential, params: Record = {}, ) { - const res = await credentialCall(ctx, credential, "com.atproto.space.listRepos", { - params: { space: credential.space, ...params }, - audience: ctx.target.did, - }); - const body = res.json as { repos?: WriterEntry[]; cursor?: string } | undefined; + const res = await credentialCall( + ctx, + credential, + "com.atproto.space.listRepos", + { + params: { space: credential.space, ...params }, + audience: ctx.target.did, + }, + ); + const body = res.json as + | { repos?: WriterEntry[]; cursor?: string } + | undefined; return { res, repos: body?.repos ?? [], cursor: body?.cursor }; } const hostRequiresCredential = defineCheck({ id: "host.listrepos-requires-credential", - title: "listRepos, registerNotify and unregisterNotify refuse an unauthenticated caller", + title: + "listRepos, registerNotify and unregisterNotify refuse an unauthenticated caller", tier: "must", citations: [ L("com.atproto.space.listRepos"), @@ -59,13 +80,34 @@ const hostRequiresCredential = defineCheck({ const space = await createProbeSpace(ctx, publicRead()); try { const probes = [ - ["listRepos", await xrpcGet(ctx, "com.atproto.space.listRepos", { space: space.uri })], - ["registerNotify", await xrpcPost(ctx, "com.atproto.space.registerNotify", { space: space.uri, service: ctx.target.did })], - ["unregisterNotify", await xrpcPost(ctx, "com.atproto.space.unregisterNotify", { space: space.uri, service: ctx.target.did })], + [ + "listRepos", + await xrpcGet(ctx, "com.atproto.space.listRepos", { + space: space.uri, + }), + ], + [ + "registerNotify", + await xrpcPost(ctx, "com.atproto.space.registerNotify", { + space: space.uri, + service: ownService(ctx), + }), + ], + [ + "unregisterNotify", + await xrpcPost(ctx, "com.atproto.space.unregisterNotify", { + space: space.uri, + service: ownService(ctx), + }), + ], ] as const; - const served = probes.filter(([, r]) => r.status !== 401 && r.status !== 403); + const served = probes.filter( + ([, r]) => r.status !== 401 && r.status !== 403, + ); return served.length - ? fail(`not refused with 401/403: ${served.map(([n, r]) => `${n} → ${describe(r)}`).join("; ")}`) + ? fail( + `not refused with 401/403: ${served.map(([n, r]) => `${n} → ${describe(r)}`).join("; ")}`, + ) : pass("all three refused an unauthenticated caller"); } finally { await deleteProbeSpace(ctx, space.uri); @@ -87,27 +129,41 @@ const listReposShape = defineCheck({ await mustCreateRecord(ctx, space.uri, "b"); const credential = await obtainPublicCredential(ctx, space.uri); const page = await listRepos(ctx, credential); - if (page.res.status !== 200) return fail(`listRepos ${describe(page.res)}`, page.res.json); + if (page.res.status !== 200) + return fail(`listRepos ${describe(page.res)}`, page.res.json); const problems: string[] = []; for (const repo of page.repos) { const data = lexBytes(repo.data); - if (!isTid(repo.repoRev)) problems.push(`${repo.did} repoRev ${String(repo.repoRev)}`); - if (!isTid(repo.spaceRev)) problems.push(`${repo.did} spaceRev ${String(repo.spaceRev)}`); - if (!data || data.length !== 32) problems.push(`${repo.did} data is not 32 bytes`); + if (!isTid(repo.repoRev)) + problems.push(`${repo.did} repoRev ${String(repo.repoRev)}`); + if (!isTid(repo.spaceRev)) + problems.push(`${repo.did} spaceRev ${String(repo.spaceRev)}`); + if (!data || data.length !== 32) + problems.push(`${repo.did} data is not 32 bytes`); } const revs = page.repos.map((r) => String(r.spaceRev)); - if (revs.some((rev, i) => i > 0 && rev <= revs[i - 1]!)) problems.push(`not ascending: ${revs.join(",")}`); - if (!page.repos.some((r) => r.did === ctx.target.did)) problems.push("the authority's own repo is not listed"); + if (revs.some((rev, i) => i > 0 && rev <= revs[i - 1]!)) + problems.push(`not ascending: ${revs.join(",")}`); + if (!page.repos.some((r) => r.did === ctx.target.did)) + problems.push("the authority's own repo is not listed"); if (page.repos.length && page.cursor !== revs.at(-1)) { - problems.push(`cursor ${page.cursor} is not the last spaceRev ${revs.at(-1)}`); + problems.push( + `cursor ${page.cursor} is not the last spaceRev ${revs.at(-1)}`, + ); } if (problems.length) return fail(problems.join("; "), page.res.json); // Resuming from the cursor reaches an empty page, which carries no cursor. const next = await listRepos(ctx, credential, { cursor: page.cursor! }); - if (next.res.status !== 200) return fail(`listRepos(cursor) ${describe(next.res)}`, next.res.json); + if (next.res.status !== 200) + return fail(`listRepos(cursor) ${describe(next.res)}`, next.res.json); return next.repos.length === 0 && next.cursor === undefined - ? pass(`${page.repos.length} writer(s), ascending, cursor resumes to an empty page`) - : fail(`after the last cursor: ${next.repos.length} repo(s), cursor ${next.cursor}`, next.res.json); + ? pass( + `${page.repos.length} writer(s), ascending, cursor resumes to an empty page`, + ) + : fail( + `after the last cursor: ${next.repos.length} repo(s), cursor ${next.cursor}`, + next.res.json, + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -119,7 +175,10 @@ const listReposReflects = defineCheck({ title: "The authority's listRepos entry matches its latest commit", tier: "should", citations: [ - { source: "reference", ref: "authority repo notifies its own space host synchronously" }, + { + source: "reference", + ref: "authority repo notifies its own space host synchronously", + }, L("com.atproto.space.listRepos"), ], needs: ["operator"], @@ -134,16 +193,30 @@ const listReposReflects = defineCheck({ const credential = await obtainPublicCredential(ctx, space.uri); const { repos } = await listRepos(ctx, credential); const mine = repos.find((r) => r.did === ctx.target.did); - const latest = await xrpcGet(asOperator(ctx), "com.atproto.space.getLatestCommit", { - space: space.uri, - repo: ctx.target.did, - }); - const commit = (latest.json as { commit?: { rev?: string; data?: unknown } } | undefined)?.commit; + const latest = await xrpcGet( + asOperator(ctx), + "com.atproto.space.getLatestCommit", + { + space: space.uri, + repo: ctx.target.did, + }, + ); + const commit = ( + latest.json as { commit?: { rev?: string; data?: unknown } } | undefined + )?.commit; const a = lexBytes(mine?.data); const b = lexBytes(commit?.data); - return mine && commit && mine.repoRev === commit.rev && a && b && bytesEqual(a, b) + return mine && + commit && + mine.repoRev === commit.rev && + a && + b && + bytesEqual(a, b) ? pass("repoRev and data match getLatestCommit") - : fail("listRepos entry differs from the latest commit", { listed: mine, commit }); + : fail("listRepos entry differs from the latest commit", { + listed: mine, + commit, + }); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -154,28 +227,50 @@ const removeWriter = defineCheck({ id: "host.removewriter", title: "removeWriter drops a repo from listRepos until it writes again", tier: "must", - citations: [L("com.atproto.space.removeWriter"), L("com.atproto.space.listRepos")], + citations: [ + L("com.atproto.space.removeWriter"), + L("com.atproto.space.listRepos"), + ], needs: ["operator"], destructive: true, async run(ctx) { const space = await createProbeSpace(ctx, publicRead()); const remove = (did: string) => - xrpcPost(asOperator(ctx), "com.atproto.space.removeWriter", { space: space.uri, did }); + xrpcPost(asOperator(ctx), "com.atproto.space.removeWriter", { + space: space.uri, + did, + }); try { await mustCreateRecord(ctx, space.uri, "a"); const credential = await obtainPublicCredential(ctx, space.uri); - const listed = async () => (await listRepos(ctx, credential)).repos.some((r) => r.did === ctx.target.did); - if (!(await listed())) return fail("the authority's repo was not in the writer set to begin with"); + const listed = async () => + (await listRepos(ctx, credential)).repos.some( + (r) => r.did === ctx.target.did, + ); + if (!(await listed())) + return fail( + "the authority's repo was not in the writer set to begin with", + ); const removed = await remove(ctx.target.did); - if (removed.status !== 200) return fail(`removeWriter ${describe(removed)}`, removed.json); - if (await listed()) return fail("removeWriter left the repo in listRepos"); + if (removed.status !== 200) + return fail(`removeWriter ${describe(removed)}`, removed.json); + if (await listed()) + return fail("removeWriter left the repo in listRepos"); // Idempotent: removing an account that isn't a writer succeeds. const absent = await remove(fakeDid()); - if (absent.status !== 200) return fail(`removeWriter of a non-writer returned ${describe(absent)}`, absent.json); + if (absent.status !== 200) + return fail( + `removeWriter of a non-writer returned ${describe(absent)}`, + absent.json, + ); await mustCreateRecord(ctx, space.uri, "b"); return (await listed()) - ? pass("removed, idempotent for a non-writer, and tracked again after a new write") - : fail("a new write by an authorised account did not return it to the writer set"); + ? pass( + "removed, idempotent for a non-writer, and tracked again after a new write", + ) + : fail( + "a new write by an authorised account did not return it to the writer set", + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -184,31 +279,40 @@ const removeWriter = defineCheck({ const registerRoundTrip = defineCheck({ id: "host.registernotify-round-trip", - title: "registerNotify returns a future expiry; unregisterNotify is idempotent", + title: + "registerNotify returns a future expiry; unregisterNotify is idempotent", tier: "must", - citations: [L("com.atproto.space.registerNotify"), L("com.atproto.space.unregisterNotify")], + citations: [ + L("com.atproto.space.registerNotify"), + L("com.atproto.space.unregisterNotify"), + ], needs: ["operator"], destructive: true, async run(ctx) { const space = await createProbeSpace(ctx, publicRead()); try { const credential = await obtainPublicCredential(ctx, space.uri); - // A bare DID names an account, served by its #atproto_pds — the - // target's own DID is the one service identifier sure to resolve. const call = (nsid: string) => credentialCall(ctx, credential, nsid, { - body: { space: space.uri, service: ctx.target.did }, + body: { space: space.uri, service: ownService(ctx) }, audience: ctx.target.did, }); const reg = await call("com.atproto.space.registerNotify"); - if (reg.status !== 200) return fail(`registerNotify ${describe(reg)}`, reg.json); - const expiresAt = Date.parse(String((reg.json as { expiresAt?: unknown }).expiresAt)); - if (!(expiresAt > Date.now())) return fail("expiresAt is not a future datetime", reg.json); + if (reg.status !== 200) + return fail(`registerNotify ${describe(reg)}`, reg.json); + const expiresAt = Date.parse( + String((reg.json as { expiresAt?: unknown }).expiresAt), + ); + if (!(expiresAt > Date.now())) + return fail("expiresAt is not a future datetime", reg.json); const un1 = await call("com.atproto.space.unregisterNotify"); const un2 = await call("com.atproto.space.unregisterNotify"); return un1.status === 200 && un2.status === 200 ? pass("registered with a future expiry; unregistered twice") - : fail(`unregisterNotify returned ${describe(un1)} then ${describe(un2)}`, { first: un1.json, second: un2.json }); + : fail( + `unregisterNotify returned ${describe(un1)} then ${describe(un2)}`, + { first: un1.json, second: un2.json }, + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -217,7 +321,8 @@ const registerRoundTrip = defineCheck({ const registerUnresolvable = defineCheck({ id: "host.registernotify-unresolvable", - title: "registerNotify for a service that does not resolve answers ServiceNotResolvable", + title: + "registerNotify for a service that does not resolve answers ServiceNotResolvable", tier: "must", citations: [L("com.atproto.space.registerNotify@error:ServiceNotResolvable")], needs: ["operator"], @@ -226,13 +331,21 @@ const registerUnresolvable = defineCheck({ const space = await createProbeSpace(ctx, publicRead()); try { const credential = await obtainPublicCredential(ctx, space.uri); - const res = await credentialCall(ctx, credential, "com.atproto.space.registerNotify", { - body: { space: space.uri, service: `${FOREIGN_DID}#space_syncer` }, - audience: ctx.target.did, - }); + const res = await credentialCall( + ctx, + credential, + "com.atproto.space.registerNotify", + { + body: { space: space.uri, service: `${FOREIGN_DID}#space_syncer` }, + audience: ctx.target.did, + }, + ); return res.error === "ServiceNotResolvable" ? pass("answered ServiceNotResolvable") - : fail(`answered ${describe(res)}, expected ServiceNotResolvable`, res.json); + : fail( + `answered ${describe(res)}, expected ServiceNotResolvable`, + res.json, + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -256,15 +369,33 @@ const hostAfterDelete = defineCheck({ const space = await createProbeSpace(ctx, publicRead()); const credential = await obtainPublicCredential(ctx, space.uri); await deleteProbeSpace(ctx, space.uri); - const body = { space: space.uri, service: ctx.target.did }; + const body = { space: space.uri, service: ownService(ctx) }; const probes = [ ["listRepos", await listRepos(ctx, credential).then((r) => r.res)], - ["registerNotify", await credentialCall(ctx, credential, "com.atproto.space.registerNotify", { body, audience: ctx.target.did })], - ["unregisterNotify", await credentialCall(ctx, credential, "com.atproto.space.unregisterNotify", { body, audience: ctx.target.did })], + [ + "registerNotify", + await credentialCall( + ctx, + credential, + "com.atproto.space.registerNotify", + { body, audience: ctx.target.did }, + ), + ], + [ + "unregisterNotify", + await credentialCall( + ctx, + credential, + "com.atproto.space.unregisterNotify", + { body, audience: ctx.target.did }, + ), + ], ] as const; const misses = probes.filter(([, r]) => r.error !== "SpaceNotFound"); return misses.length - ? fail(`expected SpaceNotFound: ${misses.map(([n, r]) => `${n} → ${describe(r)}`).join("; ")}`) + ? fail( + `expected SpaceNotFound: ${misses.map(([n, r]) => `${n} → ${describe(r)}`).join("; ")}`, + ) : pass("all three answered SpaceNotFound"); }, }); @@ -277,7 +408,10 @@ const forwardedNotifyWrite = defineCheck({ id: "notify.forwarded-notifywrite", title: "A registered syncer receives sequenced notifyWrite calls", tier: "must", - citations: [L("com.atproto.space.notifyWrite"), L("com.atproto.space.registerNotify")], + citations: [ + L("com.atproto.space.notifyWrite"), + L("com.atproto.space.registerNotify"), + ], needs: ["operator", "syncer-inbox"], destructive: true, async run(ctx) { @@ -286,38 +420,64 @@ const forwardedNotifyWrite = defineCheck({ try { await mustCreateRecord(ctx, space.uri, "before"); const credential = await obtainPublicCredential(ctx, space.uri); - const reg = await credentialCall(ctx, credential, "com.atproto.space.registerNotify", { - body: { space: space.uri, service: inbox.service }, - audience: ctx.target.did, - }); - if (reg.status !== 200) return fail(`registerNotify ${describe(reg)}`, reg.json); + const reg = await credentialCall( + ctx, + credential, + "com.atproto.space.registerNotify", + { + body: { space: space.uri, service: inbox.service }, + audience: ctx.target.did, + }, + ); + if (reg.status !== 200) + return fail(`registerNotify ${describe(reg)}`, reg.json); const forThis = (d: InboxDelivery) => d.lxm === "com.atproto.space.notifyWrite" && (d.body as { space?: string } | undefined)?.space === space.uri; const since = Date.now(); await mustCreateRecord(ctx, space.uri, "one"); - const first = await inbox.waitFor((d) => forThis(d) && d.receivedAt >= since, NOTIFY_TIMEOUT_MS); - if (!first) return fail("no notifyWrite reached the syncer after a write"); + const first = await inbox.waitFor( + (d) => forThis(d) && d.receivedAt >= since, + NOTIFY_TIMEOUT_MS, + ); + if (!first) + return fail("no notifyWrite reached the syncer after a write"); const a = first.body as Record; await mustCreateRecord(ctx, space.uri, "two"); const second = await inbox.waitFor( - (d) => forThis(d) && (d.body as { spaceRev?: string }).spaceRev !== a.spaceRev && d.receivedAt >= first.receivedAt, + (d) => + forThis(d) && + (d.body as { spaceRev?: string }).spaceRev !== a.spaceRev && + d.receivedAt >= first.receivedAt, NOTIFY_TIMEOUT_MS, ); - if (!second) return fail("no notifyWrite reached the syncer after a second write"); + if (!second) + return fail("no notifyWrite reached the syncer after a second write"); const b = second.body as Record; const problems: string[] = []; - for (const [label, body] of [["first", a], ["second", b]] as const) { - if (body.repo !== ctx.target.did) problems.push(`${label} repo ${String(body.repo)}`); - if (!isTid(body.repoRev)) problems.push(`${label} repoRev ${String(body.repoRev)}`); + for (const [label, body] of [ + ["first", a], + ["second", b], + ] as const) { + if (body.repo !== ctx.target.did) + problems.push(`${label} repo ${String(body.repo)}`); + if (!isTid(body.repoRev)) + problems.push(`${label} repoRev ${String(body.repoRev)}`); if (!isTid(body.spaceRev)) problems.push(`${label} has no spaceRev`); - if (lexBytes(body.data)?.length !== 32) problems.push(`${label} data is not 32 bytes`); + if (lexBytes(body.data)?.length !== 32) + problems.push(`${label} data is not 32 bytes`); } - if (b.prevSpaceRev !== a.spaceRev) problems.push(`second prevSpaceRev ${String(b.prevSpaceRev)} ≠ first spaceRev ${String(a.spaceRev)}`); - if (!second.authorization?.startsWith("Bearer ")) problems.push("delivered without service auth"); + if (b.prevSpaceRev !== a.spaceRev) + problems.push( + `second prevSpaceRev ${String(b.prevSpaceRev)} ≠ first spaceRev ${String(a.spaceRev)}`, + ); + if (!second.authorization?.startsWith("Bearer ")) + problems.push("delivered without service auth"); return problems.length ? fail(problems.join("; "), { first: a, second: b }) - : pass("two sequenced deliveries; prevSpaceRev chains to the previous spaceRev"); + : pass( + "two sequenced deliveries; prevSpaceRev chains to the previous spaceRev", + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -326,9 +486,13 @@ const forwardedNotifyWrite = defineCheck({ const spaceDeletedDelivered = defineCheck({ id: "notify.space-deleted-delivered", - title: "A registered syncer is sent notifySpaceDeleted when the space is deleted", + title: + "A registered syncer is sent notifySpaceDeleted when the space is deleted", tier: "must", - citations: [L("com.atproto.space.notifySpaceDeleted"), L("com.atproto.space.deleteSpace")], + citations: [ + L("com.atproto.space.notifySpaceDeleted"), + L("com.atproto.space.deleteSpace"), + ], needs: ["operator", "syncer-inbox"], destructive: true, async run(ctx) { @@ -337,11 +501,17 @@ const spaceDeletedDelivered = defineCheck({ let deleted = false; try { const credential = await obtainPublicCredential(ctx, space.uri); - const reg = await credentialCall(ctx, credential, "com.atproto.space.registerNotify", { - body: { space: space.uri, service: inbox.service }, - audience: ctx.target.did, - }); - if (reg.status !== 200) return fail(`registerNotify ${describe(reg)}`, reg.json); + const reg = await credentialCall( + ctx, + credential, + "com.atproto.space.registerNotify", + { + body: { space: space.uri, service: inbox.service }, + audience: ctx.target.did, + }, + ); + if (reg.status !== 200) + return fail(`registerNotify ${describe(reg)}`, reg.json); await deleteProbeSpace(ctx, space.uri); deleted = true; const got = await inbox.waitFor( diff --git a/packages/space-conformance/src/checks/probe.ts b/packages/space-conformance/src/checks/probe.ts index 9b2209b..e7aec2f 100644 --- a/packages/space-conformance/src/checks/probe.ts +++ b/packages/space-conformance/src/checks/probe.ts @@ -107,11 +107,11 @@ export async function createProbeSpace( policy: Policy = memberspace(), skey: string = probeSkey(), ): Promise { - const res = await xrpcPost( - asOperator(ctx), - "com.atproto.space.createSpace", - { spaceType: PROBE_TYPE, skey, policy }, - ); + const res = await xrpcPost(asOperator(ctx), "com.atproto.space.createSpace", { + spaceType: PROBE_TYPE, + skey, + policy, + }); if (res.status !== 200) { throw new Error( `createSpace failed: ${res.status} ${res.error ?? ""} ${JSON.stringify(res.json)}`, @@ -311,8 +311,7 @@ export async function credentialCall( opts: CredentialCallOptions = {}, ): Promise { const repo = opts.params?.repo; - const audience = - opts.audience ?? repo ?? spaceAuthority(credential.space); + const audience = opts.audience ?? repo ?? spaceAuthority(credential.space); const authorization = `${opts.scheme ?? SPACE_CREDENTIAL_SCHEME} ${credential.credential}`; const headers = new Headers( opts.unsigned @@ -326,7 +325,11 @@ export async function credentialCall( let sharedSecret: Uint8Array | undefined; let macType: MacType | undefined; const want = opts.wantMac ?? MAC_TYPES[nsid]; - if (typeof want === "string" && want !== COMMIT_MAC_TYPE && want !== RECORD_MAC_TYPE) { + if ( + typeof want === "string" && + want !== COMMIT_MAC_TYPE && + want !== RECORD_MAC_TYPE + ) { headers.set("atproto-space-want-mac", want); } else if (want) { if (!repo) throw new Error(`${nsid}: a MAC request needs the repo DID`); @@ -347,10 +350,10 @@ export async function credentialCall( body: JSON.stringify(opts.body), }); } else { - response = await ctx.fetch( - xrpcUrl(ctx.target.origin, nsid, opts.params), - { method: "GET", headers }, - ); + response = await ctx.fetch(xrpcUrl(ctx.target.origin, nsid, opts.params), { + method: "GET", + headers, + }); } const result = await toResult(response); return { diff --git a/packages/space-conformance/src/checks/records.ts b/packages/space-conformance/src/checks/records.ts index 5322e18..aa9cf7c 100644 --- a/packages/space-conformance/src/checks/records.ts +++ b/packages/space-conformance/src/checks/records.ts @@ -36,19 +36,37 @@ const writesCreateRead = defineCheck({ id: "writes.create-and-read", title: "Operator creates a record and reads it back", tier: "must", - citations: [L("com.atproto.space.createRecord"), L("com.atproto.space.getRecord")], + citations: [ + L("com.atproto.space.createRecord"), + L("com.atproto.space.getRecord"), + ], needs: ["operator"], destructive: true, async run(ctx) { const space = await createProbeSpace(ctx); try { - const created = await operatorCreateRecord(ctx, space.uri, POST, "rec1", note("hello")); - if (created.status !== 200) return fail(`createRecord ${describe(created)}`, created.json); + const created = await operatorCreateRecord( + ctx, + space.uri, + POST, + "rec1", + note("hello"), + ); + if (created.status !== 200) + return fail(`createRecord ${describe(created)}`, created.json); const read = await operatorGetRecord(ctx, space.uri, "rec1"); - if (read.status !== 200) return fail(`getRecord ${describe(read)}`, read.json); - const body = read.json as { uri?: string; cid?: string; value?: { text?: string } }; + if (read.status !== 200) + return fail(`getRecord ${describe(read)}`, read.json); + const body = read.json as { + uri?: string; + cid?: string; + value?: { text?: string }; + }; if (body.cid !== (created.json as { cid?: string }).cid) { - return fail("getRecord cid differs from the createRecord cid", read.json); + return fail( + "getRecord cid differs from the createRecord cid", + read.json, + ); } return body.value?.text === "hello" ? pass("round-tripped the record value and cid") @@ -80,10 +98,17 @@ const writesUnauthReadRefused = defineCheck({ collection: POST, rkey: "private", }); - if (res.status === 200) return fail("an existing space record was served with no auth", res.json); + if (res.status === 200) + return fail( + "an existing space record was served with no auth", + res.json, + ); return res.status === 401 || res.status === 403 ? pass(`unauthenticated read of a real record refused (${res.status})`) - : fail(`refused, but with ${describe(res)} rather than 401/403`, res.json); + : fail( + `refused, but with ${describe(res)} rather than 401/403`, + res.json, + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -101,7 +126,13 @@ const writesDuplicate = defineCheck({ const space = await createProbeSpace(ctx); try { await mustCreateRecord(ctx, space.uri, "dup", "one"); - const second = await operatorCreateRecord(ctx, space.uri, POST, "dup", note("two")); + const second = await operatorCreateRecord( + ctx, + space.uri, + POST, + "dup", + note("two"), + ); if (second.status === 200) return fail("duplicate create returned 200"); return second.error === "RecordAlreadyExists" ? pass("refused with RecordAlreadyExists") @@ -131,14 +162,20 @@ const writesPutRecord = defineCheck({ }); try { const first = await put("v1"); - if (first.status !== 200) return fail(`putRecord (create) ${describe(first)}`, first.json); + if (first.status !== 200) + return fail(`putRecord (create) ${describe(first)}`, first.json); const second = await put("v2"); - if (second.status !== 200) return fail(`putRecord (update) ${describe(second)}`, second.json); + if (second.status !== 200) + return fail(`putRecord (update) ${describe(second)}`, second.json); const read = await operatorGetRecord(ctx, space.uri, "upsert"); - const text = (read.json as { value?: { text?: string } } | undefined)?.value?.text; + const text = (read.json as { value?: { text?: string } } | undefined) + ?.value?.text; return text === "v2" ? pass("created then replaced the record") - : fail(`after two puts the record reads ${describe(read)} ${text}`, read.json); + : fail( + `after two puts the record reads ${describe(read)} ${text}`, + read.json, + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -171,7 +208,10 @@ const writesDeleteIdempotent = defineCheck({ id: "writes.delete-idempotent", title: "deleteRecord removes the record and is idempotent", tier: "must", - citations: [L("com.atproto.space.deleteRecord"), L("com.atproto.space.getRecord")], + citations: [ + L("com.atproto.space.deleteRecord"), + L("com.atproto.space.getRecord"), + ], needs: ["operator"], destructive: true, async run(ctx) { @@ -188,16 +228,24 @@ const writesDeleteIdempotent = defineCheck({ // nothing happens) would pass on idempotency alone. await mustCreateRecord(ctx, space.uri, "doomed", "bye"); const removed = await del("doomed"); - if (removed.status !== 200) return fail(`delete of an existing record returned ${describe(removed)}`, removed.json); + if (removed.status !== 200) + return fail( + `delete of an existing record returned ${describe(removed)}`, + removed.json, + ); const after = await operatorGetRecord(ctx, space.uri, "doomed"); - if (after.status === 200) return fail("a deleted record was still readable", after.json); + if (after.status === 200) + return fail("a deleted record was still readable", after.json); const again = await del("doomed"); const ghost = await del("ghost"); if (again.status !== 200 || ghost.status !== 200) { - return fail(`repeat delete returned ${describe(again)}, absent-key delete returned ${describe(ghost)}`, { - again: again.json, - ghost: ghost.json, - }); + return fail( + `repeat delete returned ${describe(again)}, absent-key delete returned ${describe(ghost)}`, + { + again: again.json, + ghost: ghost.json, + }, + ); } return pass("delete removed the record; repeat and absent deletes 200"); } finally { @@ -234,7 +282,11 @@ const writesApplyWritesAtomic = defineCheck({ repo: ctx.target.did, writes: [create("ok1", "1"), create("ok2", "2")], }); - if (ok.status !== 200) return fail(`applyWrites did not accept a valid batch (${describe(ok)})`, ok.json); + if (ok.status !== 200) + return fail( + `applyWrites did not accept a valid batch (${describe(ok)})`, + ok.json, + ); const batch = await xrpcPost(op(ctx), "com.atproto.space.applyWrites", { space: space.uri, repo: ctx.target.did, @@ -242,7 +294,10 @@ const writesApplyWritesAtomic = defineCheck({ }); if (batch.status === 200) return fail("colliding batch returned 200"); if (batch.error !== "RecordAlreadyExists") { - return fail(`colliding batch refused with ${describe(batch)}, expected RecordAlreadyExists`, batch.json); + return fail( + `colliding batch refused with ${describe(batch)}, expected RecordAlreadyExists`, + batch.json, + ); } const check = await operatorGetRecord(ctx, space.uri, "fresh"); return check.status !== 200 @@ -290,9 +345,37 @@ const writesApplyWritesMissing = defineCheck({ function writeProbes(ctx: CheckContext, space: string) { const repo = ctx.target.did; return [ - ["createRecord", () => xrpcPost(op(ctx), "com.atproto.space.createRecord", { space, repo, collection: POST, rkey: "w", record: note("w") })], - ["putRecord", () => xrpcPost(op(ctx), "com.atproto.space.putRecord", { space, repo, collection: POST, rkey: "w", record: note("w") })], - ["applyWrites", () => xrpcPost(op(ctx), "com.atproto.space.applyWrites", { space, repo, writes: [create("w", "w")] })], + [ + "createRecord", + () => + xrpcPost(op(ctx), "com.atproto.space.createRecord", { + space, + repo, + collection: POST, + rkey: "w", + record: note("w"), + }), + ], + [ + "putRecord", + () => + xrpcPost(op(ctx), "com.atproto.space.putRecord", { + space, + repo, + collection: POST, + rkey: "w", + record: note("w"), + }), + ], + [ + "applyWrites", + () => + xrpcPost(op(ctx), "com.atproto.space.applyWrites", { + space, + repo, + writes: [create("w", "w")], + }), + ], ] as Array<[string, () => Promise]>; } @@ -303,14 +386,16 @@ async function expectNotFound( const misses: string[] = []; for (const [name, call] of probes) { const res = await call(); - if (res.error !== "SpaceNotFound") misses.push(`${label} ${name} → ${describe(res)}`); + if (res.error !== "SpaceNotFound") + misses.push(`${label} ${name} → ${describe(res)}`); } return misses; } const writesSpaceNotFound = defineCheck({ id: "writes.space-not-found", - title: "The authority's writes to a missing or deleted space answer SpaceNotFound", + title: + "The authority's writes to a missing or deleted space answer SpaceNotFound", tier: "must", citations: [ L("com.atproto.space.createRecord@error:SpaceNotFound"), @@ -329,18 +414,24 @@ const writesSpaceNotFound = defineCheck({ await mustCreateRecord(ctx, deleted.uri, "before"); await deleteProbeSpace(ctx, deleted.uri); const misses = [ - ...(await expectNotFound(writeProbes(ctx, unknownSpaceUri(ctx.target.did)), "unknown:")), + ...(await expectNotFound( + writeProbes(ctx, unknownSpaceUri(ctx.target.did)), + "unknown:", + )), ...(await expectNotFound(writeProbes(ctx, deleted.uri), "deleted:")), ]; return misses.length ? fail(`expected SpaceNotFound: ${misses.join("; ")}`) - : pass("create, put and applyWrites answered SpaceNotFound for a missing and a deleted space"); + : pass( + "create, put and applyWrites answered SpaceNotFound for a missing and a deleted space", + ); }, }); const writesDeleteSpaceNotFound = defineCheck({ id: "writes.delete-in-missing-space", - title: "The authority's deleteRecord in a missing or deleted space answers SpaceNotFound", + title: + "The authority's deleteRecord in a missing or deleted space answers SpaceNotFound", tier: "must", citations: [ L("com.atproto.space.deleteRecord@error:SpaceNotFound"), @@ -358,14 +449,18 @@ const writesDeleteSpaceNotFound = defineCheck({ await mustCreateRecord(ctx, deleted.uri, "w"); await deleteProbeSpace(ctx, deleted.uri); const misses: string[] = []; - for (const [label, space] of [["unknown", unknownSpaceUri(ctx.target.did)], ["deleted", deleted.uri]]) { + for (const [label, space] of [ + ["unknown", unknownSpaceUri(ctx.target.did)], + ["deleted", deleted.uri], + ]) { const res = await xrpcPost(op(ctx), "com.atproto.space.deleteRecord", { space, repo: ctx.target.did, collection: POST, rkey: "w", }); - if (res.error !== "SpaceNotFound") misses.push(`${label} → ${describe(res)}`); + if (res.error !== "SpaceNotFound") + misses.push(`${label} → ${describe(res)}`); } return misses.length ? fail(`expected SpaceNotFound: ${misses.join("; ")}`) @@ -408,7 +503,8 @@ const readsAfterDelete = defineCheck({ const misses: string[] = []; for (const [name, params] of reads) { const res = await xrpcGet(op(ctx), `com.atproto.space.${name}`, params); - if (res.error !== "SpaceNotFound") misses.push(`${name} → ${describe(res)}`); + if (res.error !== "SpaceNotFound") + misses.push(`${name} → ${describe(res)}`); } return misses.length ? fail(`expected SpaceNotFound: ${misses.join("; ")}`) @@ -433,8 +529,19 @@ const writesPublishedRefused = defineCheck({ const space = await createProbeSpace(ctx, memberspace()); try { const attempts: Array<[string, string, Record]> = [ - ["com.atproto.space.policy", "self", { $type: "com.atproto.space.policy", policy: memberspace({ publicRead: true }) }], - ["com.atproto.memberspace.member", "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa", { $type: "com.atproto.memberspace.member", read: true, write: true }], + [ + "com.atproto.space.policy", + "self", + { + $type: "com.atproto.space.policy", + policy: memberspace({ publicRead: true }), + }, + ], + [ + "com.atproto.memberspace.member", + "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa", + { $type: "com.atproto.memberspace.member", read: true, write: true }, + ], ]; const accepted: string[] = []; for (const [collection, rkey, record] of attempts) { @@ -466,11 +573,17 @@ async function latestCommit(ctx: CheckContext, space: string) { space, repo: ctx.target.did, }); - const commit = (res.json as { commit?: { rev?: string; data?: unknown } } | undefined)?.commit; + const commit = ( + res.json as { commit?: { rev?: string; data?: unknown } } | undefined + )?.commit; return { res, rev: commit?.rev, data: lexBytes(commit?.data) }; } -async function listRecords(ctx: CheckContext, space: string, extra: Record = {}) { +async function listRecords( + ctx: CheckContext, + space: string, + extra: Record = {}, +) { const res = await xrpcGet(op(ctx), "com.atproto.space.listRecords", { space, repo: ctx.target.did, @@ -478,41 +591,66 @@ async function listRecords(ctx: CheckContext, space: string, extra: Record> } | undefined)?.records ?? []), + records: + (res.json as { records?: Array> } | undefined) + ?.records ?? [], }; } const writesClearRecords = defineCheck({ id: "writes.clearrecords", - title: "clearRecords empties the repo at a new rev with the empty-repo digest", + title: + "clearRecords empties the repo at a new rev with the empty-repo digest", tier: "must", - citations: [L("com.atproto.space.clearRecords"), L("com.atproto.space.listRecords")], + citations: [ + L("com.atproto.space.clearRecords"), + L("com.atproto.space.listRecords"), + ], needs: ["operator"], destructive: true, async run(ctx) { const space = await createProbeSpace(ctx); const clear = () => - xrpcPost(op(ctx), "com.atproto.space.clearRecords", { space: space.uri, repo: ctx.target.did }); + xrpcPost(op(ctx), "com.atproto.space.clearRecords", { + space: space.uri, + repo: ctx.target.did, + }); try { await mustCreateRecord(ctx, space.uri, "a"); await mustCreateRecord(ctx, space.uri, "b"); const before = await latestCommit(ctx, space.uri); const cleared = await clear(); - if (cleared.status !== 200) return fail(`clearRecords ${describe(cleared)}`, cleared.json); + if (cleared.status !== 200) + return fail(`clearRecords ${describe(cleared)}`, cleared.json); const { records } = await listRecords(ctx, space.uri); - if (records.length) return fail(`${records.length} record(s) survived clearRecords`, records); + if (records.length) + return fail( + `${records.length} record(s) survived clearRecords`, + records, + ); const after = await latestCommit(ctx, space.uri); if (!after.rev || !before.rev || after.rev <= before.rev) { - return fail(`rev did not advance (${before.rev} → ${after.rev})`, after.res.json); + return fail( + `rev did not advance (${before.rev} → ${after.rev})`, + after.res.json, + ); } if (!after.data || !bytesEqual(after.data, await emptyRepoData())) { - return fail("commit data after clearRecords is not the empty repo's digest", after.res.json); + return fail( + "commit data after clearRecords is not the empty repo's digest", + after.res.json, + ); } // "Succeeds whether or not the repo held any records to delete." const again = await clear(); return again.status === 200 - ? pass("cleared at a new rev with the empty digest; clearing again is a no-op") - : fail(`clearing an empty repo returned ${describe(again)}`, again.json); + ? pass( + "cleared at a new rev with the empty digest; clearing again is a no-op", + ) + : fail( + `clearing an empty repo returned ${describe(again)}`, + again.json, + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -521,26 +659,44 @@ const writesClearRecords = defineCheck({ const writesClearKeepsPublished = defineCheck({ id: "writes.clearrecords-keeps-published", - title: "clearRecords in the authority's repo keeps the published policy record", + title: + "clearRecords in the authority's repo keeps the published policy record", tier: "must", citations: [L("com.atproto.space.clearRecords")], needs: ["operator"], destructive: true, async run(ctx) { - const space = await createProbeSpace(ctx, memberspace({ publishPolicy: true })); + const space = await createProbeSpace( + ctx, + memberspace({ publishPolicy: true }), + ); try { await mustCreateRecord(ctx, space.uri, "mine"); - const cleared = await xrpcPost(op(ctx), "com.atproto.space.clearRecords", { - space: space.uri, - repo: ctx.target.did, - }); - if (cleared.status !== 200) return fail(`clearRecords ${describe(cleared)}`, cleared.json); + const cleared = await xrpcPost( + op(ctx), + "com.atproto.space.clearRecords", + { + space: space.uri, + repo: ctx.target.did, + }, + ); + if (cleared.status !== 200) + return fail(`clearRecords ${describe(cleared)}`, cleared.json); const own = await operatorGetRecord(ctx, space.uri, "mine"); - if (own.status === 200) return fail("the operator's own record survived clearRecords"); - const policy = await operatorGetRecord(ctx, space.uri, "self", "com.atproto.space.policy"); + if (own.status === 200) + return fail("the operator's own record survived clearRecords"); + const policy = await operatorGetRecord( + ctx, + space.uri, + "self", + "com.atproto.space.policy", + ); return policy.status === 200 ? pass("own record cleared; the published policy record kept") - : fail(`the published policy record was cleared too (${describe(policy)})`, policy.json); + : fail( + `the published policy record was cleared too (${describe(policy)})`, + policy.json, + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -560,17 +716,32 @@ const syncListRecords = defineCheck({ const a = await mustCreateRecord(ctx, space.uri, "aaa", "first"); await mustCreateRecord(ctx, space.uri, "bbb", "second"); const full = await listRecords(ctx, space.uri, { collection: POST }); - if (full.res.status !== 200) return fail(`listRecords ${describe(full.res)}`, full.res.json); + if (full.res.status !== 200) + return fail(`listRecords ${describe(full.res)}`, full.res.json); const entry = full.records.find((r) => r.rkey === "aaa"); - if (full.records.length !== 2 || !entry) return fail(`listed ${full.records.length} record(s)`, full.records); - if (entry.collection !== POST || entry.cid !== a.cid || (entry.value as { text?: string })?.text !== "first") { + if (full.records.length !== 2 || !entry) + return fail(`listed ${full.records.length} record(s)`, full.records); + if ( + entry.collection !== POST || + entry.cid !== a.cid || + (entry.value as { text?: string })?.text !== "first" + ) { return fail("listed entry does not match the written record", entry); } - const bare = await listRecords(ctx, space.uri, { collection: POST, excludeValues: "true" }); - if (bare.records.length !== 2) return fail(`excludeValues listed ${bare.records.length} record(s)`, bare.records); + const bare = await listRecords(ctx, space.uri, { + collection: POST, + excludeValues: "true", + }); + if (bare.records.length !== 2) + return fail( + `excludeValues listed ${bare.records.length} record(s)`, + bare.records, + ); return bare.records.some((r) => "value" in r) ? fail("excludeValues still inlined values", bare.records) - : pass("listed both records with values; excludeValues listed metadata only"); + : pass( + "listed both records with values; excludeValues listed metadata only", + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -590,8 +761,11 @@ const syncListRecordsDescending = defineCheck({ async run(ctx) { const space = await createProbeSpace(ctx); try { - for (const rkey of ["aaa", "bbb", "ccc"]) await mustCreateRecord(ctx, space.uri, rkey); - const { res, records } = await listRecords(ctx, space.uri, { collection: POST }); + for (const rkey of ["aaa", "bbb", "ccc"]) + await mustCreateRecord(ctx, space.uri, rkey); + const { res, records } = await listRecords(ctx, space.uri, { + collection: POST, + }); if (res.status !== 200) return fail(`listRecords ${describe(res)}`); const rkeys = records.map((r) => r.rkey); return rkeys.join(",") === "ccc,bbb,aaa" @@ -623,7 +797,10 @@ const blobsSpaceNotPublic = defineCheck({ id: "blobs.space-blob-not-public", title: "A blob is not publicly served unless a public record references it", tier: "must", - citations: [L("com.atproto.space.getBlob"), { source: "proposal", ref: "0016#blob-sync" }], + citations: [ + L("com.atproto.space.getBlob"), + { source: "proposal", ref: "0016#blob-sync" }, + ], // uploadBlob and sync.getBlob are host-PDS endpoints, not space methods. needs: ["operator", "pds-blobs"], destructive: true, @@ -633,21 +810,35 @@ const blobsSpaceNotPublic = defineCheck({ // then referenced only from a space. const space = await createProbeSpace(ctx); try { - const blob = await uploadBlob(ctx, crypto.getRandomValues(new Uint8Array(16))); + const blob = await uploadBlob( + ctx, + crypto.getRandomValues(new Uint8Array(16)), + ); const publicUrl = `${ctx.target.origin}/xrpc/com.atproto.sync.getBlob?did=${encodeURIComponent(ctx.target.did)}&cid=${blob.ref.$link}`; const stagedGet = await ctx.fetch(publicUrl); if (stagedGet.status === 200) { - return fail("an uploaded, unreferenced blob was served by the public sync.getBlob"); + return fail( + "an uploaded, unreferenced blob was served by the public sync.getBlob", + ); } - const write = await operatorCreateRecord(ctx, space.uri, "earth.cirrus.check.withblob", "self", { - $type: "earth.cirrus.check.withblob", - file: blob, - }); - if (write.status !== 200) return fail(`referencing write ${describe(write)}`, write.json); + const write = await operatorCreateRecord( + ctx, + space.uri, + "earth.cirrus.check.withblob", + "self", + { + $type: "earth.cirrus.check.withblob", + file: blob, + }, + ); + if (write.status !== 200) + return fail(`referencing write ${describe(write)}`, write.json); const publicGet = await ctx.fetch(publicUrl); return publicGet.status === 200 ? fail("a space blob was served by the public sync.getBlob") - : pass(`public sync.getBlob refused the blob unreferenced (${stagedGet.status}) and space-referenced (${publicGet.status})`); + : pass( + `public sync.getBlob refused the blob unreferenced (${stagedGet.status}) and space-referenced (${publicGet.status})`, + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -666,17 +857,28 @@ const blobsListAndGet = defineCheck({ try { const bytes = crypto.getRandomValues(new Uint8Array(24)); const blob = await uploadBlob(ctx, bytes); - const write = await operatorCreateRecord(ctx, space.uri, "earth.cirrus.check.withblob", "self", { - $type: "earth.cirrus.check.withblob", - file: blob, - }); - if (write.status !== 200) return fail(`referencing write ${describe(write)}`, write.json); + const write = await operatorCreateRecord( + ctx, + space.uri, + "earth.cirrus.check.withblob", + "self", + { + $type: "earth.cirrus.check.withblob", + file: blob, + }, + ); + if (write.status !== 200) + return fail(`referencing write ${describe(write)}`, write.json); const list = await xrpcGet(op(ctx), "com.atproto.space.listBlobs", { space: space.uri, repo: ctx.target.did, }); const cids = (list.json as { cids?: string[] } | undefined)?.cids ?? []; - if (!cids.includes(blob.ref.$link)) return fail(`listBlobs ${describe(list)} did not list the blob`, list.json); + if (!cids.includes(blob.ref.$link)) + return fail( + `listBlobs ${describe(list)} did not list the blob`, + list.json, + ); const res = await operatorFetch(ctx)( `${ctx.target.origin}/xrpc/com.atproto.space.getBlob?space=${encodeURIComponent(space.uri)}&repo=${encodeURIComponent(ctx.target.did)}&cid=${blob.ref.$link}`, ); @@ -693,7 +895,8 @@ const blobsListAndGet = defineCheck({ const blobsNotFound = defineCheck({ id: "blobs.getblob-not-found", - title: "space.getBlob of a blob the space does not reference answers BlobNotFound", + title: + "space.getBlob of a blob the space does not reference answers BlobNotFound", tier: "must", citations: [L("com.atproto.space.getBlob@error:BlobNotFound")], needs: ["operator"], diff --git a/packages/space-conformance/src/checks/space.ts b/packages/space-conformance/src/checks/space.ts index 4fe0f71..9491387 100644 --- a/packages/space-conformance/src/checks/space.ts +++ b/packages/space-conformance/src/checks/space.ts @@ -37,7 +37,9 @@ const op = asOperator; /** Run named probes and fail with every one that missed, not just the first. */ async function expectEach( - probes: Array<[string, () => Promise, (r: XrpcResult) => boolean]>, + probes: Array< + [string, () => Promise, (r: XrpcResult) => boolean] + >, ): Promise<{ ok: boolean; detail: string; evidence: Record }> { const evidence: Record = {}; const misses: string[] = []; @@ -59,9 +61,13 @@ const errorIs = (name: string) => (r: XrpcResult) => r.error === name; const spaceCreateAndGet = defineCheck({ id: "space.create-and-get", - title: "createSpace anchors the space on the operator and getSpace describes it", + title: + "createSpace anchors the space on the operator and getSpace describes it", tier: "must", - citations: [L("com.atproto.space.createSpace"), L("com.atproto.space.getSpace")], + citations: [ + L("com.atproto.space.createSpace"), + L("com.atproto.space.getSpace"), + ], needs: ["operator"], destructive: true, async run(ctx) { @@ -71,22 +77,32 @@ const spaceCreateAndGet = defineCheck({ skey, policy: memberspace(), }); - if (res.status !== 200) return fail(`createSpace ${describe(res)}`, res.json); + if (res.status !== 200) + return fail(`createSpace ${describe(res)}`, res.json); const uri = (res.json as { uri?: string }).uri; try { const expected = `at://${ctx.target.did}/space/${PROBE_TYPE}/${skey}`; - if (uri !== expected) return fail(`createSpace returned ${uri}, expected ${expected}`); - const got = await xrpcGet(op(ctx), "com.atproto.space.getSpace", { space: uri }); - if (got.status !== 200) return fail(`getSpace ${describe(got)}`, got.json); + if (uri !== expected) + return fail(`createSpace returned ${uri}, expected ${expected}`); + const got = await xrpcGet(op(ctx), "com.atproto.space.getSpace", { + space: uri, + }); + if (got.status !== 200) + return fail(`getSpace ${describe(got)}`, got.json); const body = got.json as { uri?: string; policy?: Policy }; - if (body.uri !== uri) return fail(`getSpace uri was ${body.uri}`, got.json); + if (body.uri !== uri) + return fail(`getSpace uri was ${body.uri}`, got.json); if (body.policy?.$type !== "com.atproto.memberspace.policy") { return fail(`getSpace policy was ${body.policy?.$type}`, got.json); } // Defaults are false: an unset publicRead must not read as public. return body.policy.publicRead === true - ? fail("a memberspace created without publicRead reports publicRead: true") - : pass("created at the expected uri; getSpace reports the memberspace policy"); + ? fail( + "a memberspace created without publicRead reports publicRead: true", + ) + : pass( + "created at the expected uri; getSpace reports the memberspace policy", + ); } finally { if (uri) await deleteProbeSpace(ctx, uri); } @@ -105,7 +121,8 @@ const spaceGeneratedSkey = defineCheck({ spaceType: PROBE_TYPE, policy: personalspace(), }); - if (res.status !== 200) return fail(`createSpace ${describe(res)}`, res.json); + if (res.status !== 200) + return fail(`createSpace ${describe(res)}`, res.json); const uri = (res.json as { uri: string }).uri; await deleteProbeSpace(ctx, uri); const skey = uri.split("/").at(-1); @@ -130,10 +147,14 @@ const spaceDuplicate = defineCheck({ skey: space.skey, policy: personalspace(), }); - if (again.status === 200) return fail("a second createSpace at the same skey returned 200"); + if (again.status === 200) + return fail("a second createSpace at the same skey returned 200"); return again.error === "SpaceAlreadyExists" ? pass("refused with SpaceAlreadyExists") - : fail(`refused with ${describe(again)}, expected SpaceAlreadyExists`, again.json); + : fail( + `refused with ${describe(again)}, expected SpaceAlreadyExists`, + again.json, + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -160,13 +181,17 @@ const spaceRecreate = defineCheck({ await deleteProbeSpace(ctx, space.uri); return again.status === 200 ? pass("re-created the deleted space") - : fail(`re-creating a deleted space returned ${describe(again)}`, again.json); + : fail( + `re-creating a deleted space returned ${describe(again)}`, + again.json, + ); }, }); const spaceUnsupportedPolicy = defineCheck({ id: "space.unsupported-policy-rejected", - title: "createSpace and updateSpace refuse a policy the host does not implement", + title: + "createSpace and updateSpace refuse a policy the host does not implement", tier: "must", citations: [ L("com.atproto.space.createSpace@error:UnsupportedPolicy"), @@ -183,11 +208,15 @@ const spaceUnsupportedPolicy = defineCheck({ [ "createSpace", async () => { - const res = await xrpcPost(op(ctx), "com.atproto.space.createSpace", { - spaceType: PROBE_TYPE, - skey: probeSkey(), - policy: mystery, - }); + const res = await xrpcPost( + op(ctx), + "com.atproto.space.createSpace", + { + spaceType: PROBE_TYPE, + skey: probeSkey(), + policy: mystery, + }, + ); if (res.status === 200) created = (res.json as { uri: string }).uri; return res; }, @@ -215,7 +244,8 @@ const spaceUnsupportedPolicy = defineCheck({ const spaceUpdateReplaces = defineCheck({ id: "space.update-replaces-policy", - title: "updateSpace replaces the policy wholesale; a type change discards member state", + title: + "updateSpace replaces the policy wholesale; a type change discards member state", tier: "must", citations: [ L("com.atproto.space.updateSpace"), @@ -228,12 +258,22 @@ const spaceUpdateReplaces = defineCheck({ const space = await createProbeSpace(ctx, memberspace()); const member = fakeDid(); const policyOf = async () => - ((await xrpcGet(op(ctx), "com.atproto.space.getSpace", { space: space.uri })) - .json as { policy?: Policy } | undefined)?.policy; + ( + ( + await xrpcGet(op(ctx), "com.atproto.space.getSpace", { + space: space.uri, + }) + ).json as { policy?: Policy } | undefined + )?.policy; const members = async () => - xrpcGet(op(ctx), "com.atproto.memberspace.listMembers", { space: space.uri }); + xrpcGet(op(ctx), "com.atproto.memberspace.listMembers", { + space: space.uri, + }); const update = (policy: Policy) => - xrpcPost(op(ctx), "com.atproto.space.updateSpace", { space: space.uri, policy }); + xrpcPost(op(ctx), "com.atproto.space.updateSpace", { + space: space.uri, + policy, + }); try { await xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { space: space.uri, @@ -244,17 +284,22 @@ const spaceUpdateReplaces = defineCheck({ // Same type: a configuration change. The member list survives. const same = await update(memberspace({ publicRead: true })); - if (same.status !== 200) return fail(`updateSpace (config) ${describe(same)}`, same.json); + if (same.status !== 200) + return fail(`updateSpace (config) ${describe(same)}`, same.json); const p1 = await policyOf(); - if (p1?.publicRead !== true) return fail("getSpace does not reflect publicRead: true", p1); - const kept = (await members()).json as { members?: Array<{ did: string }> }; + if (p1?.publicRead !== true) + return fail("getSpace does not reflect publicRead: true", p1); + const kept = (await members()).json as { + members?: Array<{ did: string }>; + }; if (!kept.members?.some((m) => m.did === member)) { return fail("a same-type update dropped the member list", kept); } // A different type migrates the space. const migrate = await update(personalspace()); - if (migrate.status !== 200) return fail(`updateSpace (migrate) ${describe(migrate)}`, migrate.json); + if (migrate.status !== 200) + return fail(`updateSpace (migrate) ${describe(migrate)}`, migrate.json); const p2 = await policyOf(); if (p2?.$type !== "com.atproto.personalspace.policy") { return fail(`after migration getSpace reports ${p2?.$type}`, p2); @@ -262,11 +307,16 @@ const spaceUpdateReplaces = defineCheck({ // Migrating back does not restore the discarded member list. const back = await update(memberspace()); - if (back.status !== 200) return fail(`updateSpace (back) ${describe(back)}`, back.json); - const after = (await members()).json as { members?: Array<{ did: string }> }; + if (back.status !== 200) + return fail(`updateSpace (back) ${describe(back)}`, back.json); + const after = (await members()).json as { + members?: Array<{ did: string }>; + }; return after.members?.some((m) => m.did === member) ? fail("migrating away and back restored the old member list", after) - : pass("config update kept members; a type change replaced the policy and discarded them"); + : pass( + "config update kept members; a type change replaced the policy and discarded them", + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -275,7 +325,8 @@ const spaceUpdateReplaces = defineCheck({ const spaceNotOwner = defineCheck({ id: "space.not-owner-refused", - title: "Managing a space anchored on another DID is refused with NotSpaceOwner", + title: + "Managing a space anchored on another DID is refused with NotSpaceOwner", tier: "must", citations: [ L("com.atproto.space.deleteSpace@error:NotSpaceOwner"), @@ -290,12 +341,51 @@ const spaceNotOwner = defineCheck({ const space = unknownSpaceUri(FOREIGN_DID); const did = fakeDid(); const result = await expectEach([ - ["deleteSpace", () => xrpcPost(op(ctx), "com.atproto.space.deleteSpace", { space }), errorIs("NotSpaceOwner")], - ["updateSpace", () => xrpcPost(op(ctx), "com.atproto.space.updateSpace", { space, policy: personalspace() }), errorIs("NotSpaceOwner")], - ["removeWriter", () => xrpcPost(op(ctx), "com.atproto.space.removeWriter", { space, did }), errorIs("NotSpaceOwner")], - ["exportSpaceMeta", () => xrpcGet(op(ctx), "com.atproto.space.exportSpaceMeta", { space }), errorIs("NotSpaceOwner")], - ["putMember", () => xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { space, did, read: true, write: true }), errorIs("NotSpaceOwner")], - ["removeMember", () => xrpcPost(op(ctx), "com.atproto.memberspace.removeMember", { space, did }), errorIs("NotSpaceOwner")], + [ + "deleteSpace", + () => xrpcPost(op(ctx), "com.atproto.space.deleteSpace", { space }), + errorIs("NotSpaceOwner"), + ], + [ + "updateSpace", + () => + xrpcPost(op(ctx), "com.atproto.space.updateSpace", { + space, + policy: personalspace(), + }), + errorIs("NotSpaceOwner"), + ], + [ + "removeWriter", + () => + xrpcPost(op(ctx), "com.atproto.space.removeWriter", { space, did }), + errorIs("NotSpaceOwner"), + ], + [ + "exportSpaceMeta", + () => xrpcGet(op(ctx), "com.atproto.space.exportSpaceMeta", { space }), + errorIs("NotSpaceOwner"), + ], + [ + "putMember", + () => + xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { + space, + did, + read: true, + write: true, + }), + errorIs("NotSpaceOwner"), + ], + [ + "removeMember", + () => + xrpcPost(op(ctx), "com.atproto.memberspace.removeMember", { + space, + did, + }), + errorIs("NotSpaceOwner"), + ], ]); return result.ok ? pass("every management method answered NotSpaceOwner") @@ -323,14 +413,62 @@ const spaceUnknown = defineCheck({ const did = fakeDid(); const nf = errorIs("SpaceNotFound"); const result = await expectEach([ - ["getSpace", () => xrpcGet(op(ctx), "com.atproto.space.getSpace", { space }), nf], - ["updateSpace", () => xrpcPost(op(ctx), "com.atproto.space.updateSpace", { space, policy: personalspace() }), nf], - ["deleteSpace", () => xrpcPost(op(ctx), "com.atproto.space.deleteSpace", { space }), nf], - ["exportSpaceMeta", () => xrpcGet(op(ctx), "com.atproto.space.exportSpaceMeta", { space }), nf], - ["removeWriter", () => xrpcPost(op(ctx), "com.atproto.space.removeWriter", { space, did }), nf], - ["putMember", () => xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { space, did, read: true, write: false }), nf], - ["removeMember", () => xrpcPost(op(ctx), "com.atproto.memberspace.removeMember", { space, did }), nf], - ["listMembers", () => xrpcGet(op(ctx), "com.atproto.memberspace.listMembers", { space }), nf], + [ + "getSpace", + () => xrpcGet(op(ctx), "com.atproto.space.getSpace", { space }), + nf, + ], + [ + "updateSpace", + () => + xrpcPost(op(ctx), "com.atproto.space.updateSpace", { + space, + policy: personalspace(), + }), + nf, + ], + [ + "deleteSpace", + () => xrpcPost(op(ctx), "com.atproto.space.deleteSpace", { space }), + nf, + ], + [ + "exportSpaceMeta", + () => xrpcGet(op(ctx), "com.atproto.space.exportSpaceMeta", { space }), + nf, + ], + [ + "removeWriter", + () => + xrpcPost(op(ctx), "com.atproto.space.removeWriter", { space, did }), + nf, + ], + [ + "putMember", + () => + xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { + space, + did, + read: true, + write: false, + }), + nf, + ], + [ + "removeMember", + () => + xrpcPost(op(ctx), "com.atproto.memberspace.removeMember", { + space, + did, + }), + nf, + ], + [ + "listMembers", + () => + xrpcGet(op(ctx), "com.atproto.memberspace.listMembers", { space }), + nf, + ], ]); return result.ok ? pass("every method answered SpaceNotFound") @@ -347,8 +485,12 @@ const spaceDeleteIdempotent = defineCheck({ destructive: true, async run(ctx) { const space = await createProbeSpace(ctx, personalspace()); - const first = await xrpcPost(op(ctx), "com.atproto.space.deleteSpace", { space: space.uri }); - const second = await xrpcPost(op(ctx), "com.atproto.space.deleteSpace", { space: space.uri }); + const first = await xrpcPost(op(ctx), "com.atproto.space.deleteSpace", { + space: space.uri, + }); + const second = await xrpcPost(op(ctx), "com.atproto.space.deleteSpace", { + space: space.uri, + }); return first.status === 200 && second.status === 200 ? pass("both deletes returned 200") : fail(`deletes returned ${describe(first)} then ${describe(second)}`, { @@ -379,19 +521,28 @@ const spaceListSpaces = defineCheck({ limit: "100", cursor, }); - if (res.status !== 200) return fail(`listSpaces ${describe(res)}`, res.json); - const body = res.json as { spaces?: Array<{ uri: string }>; cursor?: string }; + if (res.status !== 200) + return fail(`listSpaces ${describe(res)}`, res.json); + const body = res.json as { + spaces?: Array<{ uri: string }>; + cursor?: string; + }; seen.push(...(body.spaces ?? []).map((s) => s.uri)); cursor = body.cursor; if (!cursor || seen.includes(space.uri)) break; } - if (!seen.includes(space.uri)) return fail("listSpaces did not list the new space"); + if (!seen.includes(space.uri)) + return fail("listSpaces did not list the new space"); const stray = seen.filter( (uri) => !uri.startsWith(`at://${ctx.target.did}/space/${PROBE_TYPE}/`), ); return stray.length - ? fail(`filtered listing included spaces outside the filter: ${stray.join(", ")}`) - : pass(`listed the space; ${seen.length} result(s), all within the filter`); + ? fail( + `filtered listing included spaces outside the filter: ${stray.join(", ")}`, + ) + : pass( + `listed the space; ${seen.length} result(s), all within the filter`, + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -400,7 +551,8 @@ const spaceListSpaces = defineCheck({ const spaceOwnerStateNotByCredential = defineCheck({ id: "space.owner-state-not-by-credential", - title: "A space credential does not reach getSpace, listMembers or exportSpaceMeta", + title: + "A space credential does not reach getSpace, listMembers or exportSpaceMeta", tier: "must", citations: [ L("com.atproto.space.getSpace"), @@ -422,9 +574,21 @@ const spaceOwnerStateNotByCredential = defineCheck({ audience: ctx.target.did, }); const result = await expectEach([ - ["getSpace", () => call("com.atproto.space.getSpace"), (r) => r.status !== 200], - ["listMembers", () => call("com.atproto.memberspace.listMembers"), (r) => r.status !== 200], - ["exportSpaceMeta", () => call("com.atproto.space.exportSpaceMeta"), (r) => r.status !== 200], + [ + "getSpace", + () => call("com.atproto.space.getSpace"), + (r) => r.status !== 200, + ], + [ + "listMembers", + () => call("com.atproto.memberspace.listMembers"), + (r) => r.status !== 200, + ], + [ + "exportSpaceMeta", + () => call("com.atproto.space.exportSpaceMeta"), + (r) => r.status !== 200, + ], ]); return result.ok ? pass(`all refused (${Object.values(result.evidence).join(", ")})`) @@ -439,7 +603,8 @@ const spaceOwnerStateNotByCredential = defineCheck({ const memberRoundTrip = defineCheck({ id: "memberspace.member-round-trip", - title: "putMember sets per-member read/write; listMembers and removeMember follow", + title: + "putMember sets per-member read/write; listMembers and removeMember follow", tier: "must", citations: [ L("com.atproto.memberspace.putMember"), @@ -452,31 +617,54 @@ const memberRoundTrip = defineCheck({ const space = await createProbeSpace(ctx, memberspace()); const member = fakeDid(); const list = async () => { - const res = await xrpcGet(op(ctx), "com.atproto.memberspace.listMembers", { space: space.uri }); + const res = await xrpcGet( + op(ctx), + "com.atproto.memberspace.listMembers", + { space: space.uri }, + ); if (res.status !== 200) throw new Error(`listMembers ${describe(res)}`); - return ((res.json as { members?: Array<{ did: string; read: boolean; write: boolean }> }) - .members ?? []).find((m) => m.did === member); + return ( + ( + res.json as { + members?: Array<{ did: string; read: boolean; write: boolean }>; + } + ).members ?? [] + ).find((m) => m.did === member); }; const put = (read: boolean, write: boolean) => - xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { space: space.uri, did: member, read, write }); + xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { + space: space.uri, + did: member, + read, + write, + }); try { const first = await put(true, false); - if (first.status !== 200) return fail(`putMember ${describe(first)}`, first.json); + if (first.status !== 200) + return fail(`putMember ${describe(first)}`, first.json); const a = await list(); if (!a || a.read !== true || a.write !== false) { - return fail(`after putMember(read, !write) listMembers shows ${JSON.stringify(a)}`); + return fail( + `after putMember(read, !write) listMembers shows ${JSON.stringify(a)}`, + ); } const second = await put(false, true); - if (second.status !== 200) return fail(`putMember (replace) ${describe(second)}`, second.json); + if (second.status !== 200) + return fail(`putMember (replace) ${describe(second)}`, second.json); const b = await list(); if (!b || b.read !== false || b.write !== true) { return fail(`putMember did not replace access: ${JSON.stringify(b)}`); } - const removed = await xrpcPost(op(ctx), "com.atproto.memberspace.removeMember", { - space: space.uri, - did: member, - }); - if (removed.status !== 200) return fail(`removeMember ${describe(removed)}`, removed.json); + const removed = await xrpcPost( + op(ctx), + "com.atproto.memberspace.removeMember", + { + space: space.uri, + did: member, + }, + ); + if (removed.status !== 200) + return fail(`removeMember ${describe(removed)}`, removed.json); const c = await list(); return c ? fail(`removeMember left ${JSON.stringify(c)}`) @@ -504,9 +692,34 @@ const memberPolicyMismatch = defineCheck({ const mm = errorIs("PolicyMismatch"); try { const result = await expectEach([ - ["putMember", () => xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { space: space.uri, did, read: true, write: true }), mm], - ["removeMember", () => xrpcPost(op(ctx), "com.atproto.memberspace.removeMember", { space: space.uri, did }), mm], - ["listMembers", () => xrpcGet(op(ctx), "com.atproto.memberspace.listMembers", { space: space.uri }), mm], + [ + "putMember", + () => + xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { + space: space.uri, + did, + read: true, + write: true, + }), + mm, + ], + [ + "removeMember", + () => + xrpcPost(op(ctx), "com.atproto.memberspace.removeMember", { + space: space.uri, + did, + }), + mm, + ], + [ + "listMembers", + () => + xrpcGet(op(ctx), "com.atproto.memberspace.listMembers", { + space: space.uri, + }), + mm, + ], ]); return result.ok ? pass("all three answered PolicyMismatch on a personalspace") @@ -519,7 +732,8 @@ const memberPolicyMismatch = defineCheck({ const memberPublish = defineCheck({ id: "memberspace.publish-policy-and-members", - title: "publishPolicy / publishMembers keep policy and member records in the authority's repo", + title: + "publishPolicy / publishMembers keep policy and member records in the authority's repo", tier: "must", citations: [ L("com.atproto.memberspace.policy"), @@ -536,13 +750,28 @@ const memberPublish = defineCheck({ ); const member = fakeDid(); try { - const policy = await operatorGetRecord(ctx, space.uri, "self", "com.atproto.space.policy"); + const policy = await operatorGetRecord( + ctx, + space.uri, + "self", + "com.atproto.space.policy", + ); if (policy.status !== 200) { - return fail(`no com.atproto.space.policy/self record: ${describe(policy)}`, policy.json); + return fail( + `no com.atproto.space.policy/self record: ${describe(policy)}`, + policy.json, + ); } - const published = (policy.json as { value?: { policy?: Policy } }).value?.policy; - if (published?.$type !== "com.atproto.memberspace.policy" || published.publishMembers !== true) { - return fail("the published policy record does not carry the space's policy", policy.json); + const published = (policy.json as { value?: { policy?: Policy } }).value + ?.policy; + if ( + published?.$type !== "com.atproto.memberspace.policy" || + published.publishMembers !== true + ) { + return fail( + "the published policy record does not carry the space's policy", + policy.json, + ); } await xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { @@ -551,17 +780,37 @@ const memberPublish = defineCheck({ read: true, write: false, }); - const rec = await operatorGetRecord(ctx, space.uri, member, "com.atproto.memberspace.member"); - const value = (rec.json as { value?: { read?: boolean; write?: boolean } } | undefined)?.value; + const rec = await operatorGetRecord( + ctx, + space.uri, + member, + "com.atproto.memberspace.member", + ); + const value = ( + rec.json as { value?: { read?: boolean; write?: boolean } } | undefined + )?.value; if (rec.status !== 200 || value?.read !== true || value.write !== false) { - return fail(`member record after putMember: ${describe(rec)}`, rec.json); + return fail( + `member record after putMember: ${describe(rec)}`, + rec.json, + ); } - await xrpcPost(op(ctx), "com.atproto.memberspace.removeMember", { space: space.uri, did: member }); - const gone = await operatorGetRecord(ctx, space.uri, member, "com.atproto.memberspace.member"); + await xrpcPost(op(ctx), "com.atproto.memberspace.removeMember", { + space: space.uri, + did: member, + }); + const gone = await operatorGetRecord( + ctx, + space.uri, + member, + "com.atproto.memberspace.member", + ); return gone.status === 200 ? fail("the member record outlived removeMember", gone.json) - : pass("policy record published; member record tracked putMember and removeMember"); + : pass( + "policy record published; member record tracked putMember and removeMember", + ); } finally { await deleteProbeSpace(ctx, space.uri); } diff --git a/packages/space-conformance/src/descriptors.ts b/packages/space-conformance/src/descriptors.ts index 6f1e902..63dd76c 100644 --- a/packages/space-conformance/src/descriptors.ts +++ b/packages/space-conformance/src/descriptors.ts @@ -41,7 +41,8 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ // --- MAC verification ------------------------------------------------ { id: "mac.commit-verifies", - title: "getLatestCommit's commit has the specified shape and its MAC verifies", + title: + "getLatestCommit's commit has the specified shape and its MAC verifies", tier: "must", needs: ["operator"], citations: [ @@ -88,7 +89,10 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ title: "A credential verifies against the authority's #atproto key", tier: "must", needs: ["operator"], - citations: [L("com.atproto.space.getSpaceCredential"), C("plain-keys-resolve")], + citations: [ + L("com.atproto.space.getSpaceCredential"), + C("plain-keys-resolve"), + ], destructive: true, }, { @@ -96,7 +100,10 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ title: "A delegation token verifies against the user's #atproto key", tier: "must", needs: ["operator", "pds-delegation"], - citations: [L("com.atproto.space.getDelegationToken"), C("plain-keys-resolve")], + citations: [ + L("com.atproto.space.getDelegationToken"), + C("plain-keys-resolve"), + ], destructive: true, }, // --- migration ------------------------------------------------------- @@ -125,7 +132,8 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ }, { id: "migration.import-space-meta-unsupported-policy", - title: "importSpaceMeta of an unimplemented policy answers UnsupportedPolicy", + title: + "importSpaceMeta of an unimplemented policy answers UnsupportedPolicy", tier: "must", needs: ["operator"], citations: [L("com.atproto.space.importSpaceMeta@error:UnsupportedPolicy")], @@ -133,7 +141,8 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ }, { id: "migration.import-repo", - title: "importRepo of a getRepo archive keeps the records and data at a new rev", + title: + "importRepo of a getRepo archive keeps the records and data at a new rev", tier: "must", needs: ["operator"], citations: [ @@ -145,7 +154,8 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ }, { id: "migration.import-repo-space-not-found", - title: "importRepo into an own space that was never imported answers SpaceNotFound", + title: + "importRepo into an own space that was never imported answers SpaceNotFound", tier: "must", needs: ["operator"], citations: [L("com.atproto.space.importRepo@error:SpaceNotFound")], @@ -153,7 +163,8 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ // --- foreign identities ---------------------------------------------- { id: "credential.member-gate", - title: "A memberspace refuses a non-member and a read:false member, and admits a reader", + title: + "A memberspace refuses a non-member and a read:false member, and admits a reader", tier: "must", needs: ["operator", "identities"], citations: [ @@ -176,7 +187,9 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ title: "A delegation token addressed to another host is refused", tier: "must", needs: ["operator", "identities"], - citations: [L("com.atproto.space.getSpaceCredential@error:InvalidDelegationToken")], + citations: [ + L("com.atproto.space.getSpaceCredential@error:InvalidDelegationToken"), + ], destructive: true, }, { @@ -184,7 +197,10 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ title: "An authorised writer's notifyWrite enters the writer set", tier: "must", needs: ["operator", "identities"], - citations: [L("com.atproto.space.notifyWrite"), L("com.atproto.space.listRepos")], + citations: [ + L("com.atproto.space.notifyWrite"), + L("com.atproto.space.listRepos"), + ], destructive: true, }, { @@ -197,14 +213,16 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ }, { id: "host.notifywrite-unknown-space", - title: "notifyWrite for a space the authority does not have answers SpaceNotFound", + title: + "notifyWrite for a space the authority does not have answers SpaceNotFound", tier: "must", needs: ["operator", "identities"], citations: [L("com.atproto.space.notifyWrite@error:SpaceNotFound")], }, { id: "revocation.revoked-credential-refused", - title: "A repo host accepts a foreign authority's credential until it is revoked", + title: + "A repo host accepts a foreign authority's credential until it is revoked", tier: "must", needs: ["operator", "identities"], citations: [ @@ -219,12 +237,15 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ title: "A revoked credential is refused with CredentialRevoked", tier: "should", needs: ["operator", "identities"], - citations: [{ source: "reference", ref: "pds auth-verifier spaceCredentialAuth" }], + citations: [ + { source: "reference", ref: "pds auth-verifier spaceCredentialAuth" }, + ], destructive: true, }, { id: "revocation.non-authority-refused", - title: "notifyCredentialRevoked from anyone but the space authority is refused", + title: + "notifyCredentialRevoked from anyone but the space authority is refused", tier: "must", needs: ["operator", "identities"], citations: [L("com.atproto.space.notifyCredentialRevoked")], diff --git a/packages/space-conformance/src/did.ts b/packages/space-conformance/src/did.ts index ff788ed..f286561 100644 --- a/packages/space-conformance/src/did.ts +++ b/packages/space-conformance/src/did.ts @@ -57,7 +57,8 @@ export async function resolveDidDocument( const res = await ctx.fetch(url, { headers: { accept: "application/did+ld+json,application/json" }, }); - if (!res.ok) throw new Error(`resolving ${did}: ${url} returned ${res.status}`); + if (!res.ok) + throw new Error(`resolving ${did}: ${url} returned ${res.status}`); const doc = (await res.json()) as DidDocument; if (doc.id !== did) { throw new Error(`DID document for ${did} names itself ${doc.id}`); @@ -91,7 +92,10 @@ export function verificationMethodDidKey( } if (method.type === "EcdsaSecp256k1VerificationKey2019") { // Point compression is curve-agnostic: parity of y, then x. - return formatDidKey("ES256K", raw.length === 65 ? compressP256(raw) : raw); + return formatDidKey( + "ES256K", + raw.length === 65 ? compressP256(raw) : raw, + ); } } catch { return undefined; diff --git a/packages/space-conformance/src/full/checks.ts b/packages/space-conformance/src/full/checks.ts index 423b8ba..8138c12 100644 --- a/packages/space-conformance/src/full/checks.ts +++ b/packages/space-conformance/src/full/checks.ts @@ -39,8 +39,22 @@ import { xrpcPost, xrpcPostBytes, } from "../http.js"; -import { fail, pass, type Check, type CheckContext, type CheckOutcome } from "../model.js"; -import { bytesEqual, decodeJwt, isTid, lexBytes, tidAt, tidNow, toBase64 } from "../encoding.js"; +import { + fail, + pass, + type Check, + type CheckContext, + type CheckOutcome, +} from "../model.js"; +import { + bytesEqual, + decodeJwt, + isTid, + lexBytes, + tidAt, + tidNow, + toBase64, +} from "../encoding.js"; import { resolveDidDocument, verificationMethodDidKey } from "../did.js"; import { createCredentialKey } from "../space-auth.js"; import { @@ -74,8 +88,10 @@ import { serviceJwt, } from "./helpers.js"; -const crypto$ = (id: string, run: (ctx: CheckContext) => Promise): Check => - defineCheck({ ...descriptor(id), run }); +const crypto$ = ( + id: string, + run: (ctx: CheckContext) => Promise, +): Check => defineCheck({ ...descriptor(id), run }); /** A public-read space with two records and a credential for it. */ async function withPublicSpace( @@ -96,23 +112,46 @@ async function withPublicSpace( const macCommit = crypto$("mac.commit-verifies", (ctx) => withPublicSpace(ctx, async (space, credential) => { - const res = await credentialGet(ctx, credential, "com.atproto.space.getLatestCommit", { - space, - repo: ctx.target.did, - }); - if (res.status !== 200) return fail(`getLatestCommit ${describe(res)}`, res.json); + const res = await credentialGet( + ctx, + credential, + "com.atproto.space.getLatestCommit", + { + space, + repo: ctx.target.did, + }, + ); + if (res.status !== 200) + return fail(`getLatestCommit ${describe(res)}`, res.json); const raw = (res.json as { commit?: Record }).commit ?? {}; const keys = Object.keys(raw).sort().join(","); if (keys !== "data,repo,rev,space,ver") { - return fail(`commit carries {${keys}}, expected exactly {data,repo,rev,space,ver}`, raw); + return fail( + `commit carries {${keys}}, expected exactly {data,repo,rev,space,ver}`, + raw, + ); } const commit = commitFromJson(raw); - if (!commit || commit.ver !== 1 || !isTid(commit.rev) || commit.data.length !== 32) { - return fail("commit fields malformed (ver 1, TID rev, 32-byte data)", raw); + if ( + !commit || + commit.ver !== 1 || + !isTid(commit.rev) || + commit.data.length !== 32 + ) { + return fail( + "commit fields malformed (ver 1, TID rev, 32-byte data)", + raw, + ); } const mac = responseMac(res); - if (!mac) return fail("no parseable Atproto-Space-Mac header on a MAC'd read"); - return verifyCommit(commit, { space, repo: ctx.target.did, sharedSecret: res.sharedSecret!, mac }) + if (!mac) + return fail("no parseable Atproto-Space-Mac header on a MAC'd read"); + return verifyCommit(commit, { + space, + repo: ctx.target.did, + sharedSecret: res.sharedSecret!, + mac, + }) ? pass("commit shape as specified; its MAC verifies") : fail("the commit MAC does not verify", raw); }), @@ -120,16 +159,26 @@ const macCommit = crypto$("mac.commit-verifies", (ctx) => const macRecord = crypto$("mac.record-verifies", (ctx) => withPublicSpace(ctx, async (space, credential) => { - const res = await credentialGet(ctx, credential, "com.atproto.space.getRecord", { - space, - repo: ctx.target.did, - collection: POST, - rkey: "a", - }); + const res = await credentialGet( + ctx, + credential, + "com.atproto.space.getRecord", + { + space, + repo: ctx.target.did, + collection: POST, + rkey: "a", + }, + ); if (res.status !== 200) return fail(`getRecord ${describe(res)}`, res.json); - const record = res.json as { uri: string; cid: string; value: Record }; + const record = res.json as { + uri: string; + cid: string; + value: Record; + }; const mac = responseMac(res); - if (!mac) return fail("no parseable Atproto-Space-Mac header on a MAC'd read"); + if (!mac) + return fail("no parseable Atproto-Space-Mac header on a MAC'd read"); const ok = await verifyRecord(record as never, { uri: record.uri, sharedSecret: res.sharedSecret!, @@ -151,20 +200,40 @@ const oplogFolds = crypto$("sync.oplog-folds-to-commit", (ctx) => rkey: "a", record: { $type: POST, text: "one, again" }, }); - const res = await credentialGet(ctx, credential, "com.atproto.space.listRepoOps", { - space, - repo: ctx.target.did, - }); - if (res.status !== 200) return fail(`listRepoOps ${describe(res)}`, res.json); + const res = await credentialGet( + ctx, + credential, + "com.atproto.space.listRepoOps", + { + space, + repo: ctx.target.did, + }, + ); + if (res.status !== 200) + return fail(`listRepoOps ${describe(res)}`, res.json); const body = res.json as { - ops: Array<{ collection: string; rkey: string; cid: string | null; prev: string | null }>; + ops: Array<{ + collection: string; + rkey: string; + cid: string | null; + prev: string | null; + }>; commit?: unknown; }; const commit = commitFromJson(body.commit); - if (!commit) return fail("listRepoOps reached the head but returned no commit", body); + if (!commit) + return fail("listRepoOps reached the head but returned no commit", body); const mac = responseMac(res); - if (!mac) return fail("a page with the commit carried no Atproto-Space-Mac header"); - if (!verifyCommit(commit, { space, repo: ctx.target.did, sharedSecret: res.sharedSecret!, mac })) { + if (!mac) + return fail("a page with the commit carried no Atproto-Space-Mac header"); + if ( + !verifyCommit(commit, { + space, + repo: ctx.target.did, + sharedSecret: res.sharedSecret!, + mac, + }) + ) { return fail("the head commit's MAC does not verify"); } const folded = new RepoCommit().applyOps( @@ -183,15 +252,22 @@ const oplogFolds = crypto$("sync.oplog-folds-to-commit", (ctx) => const getRepoStar = crypto$("sync.getrepo-star", (ctx) => withPublicSpace(ctx, async (space, credential) => { - const res = await credentialGet(ctx, credential, "com.atproto.space.getRepo", { - space, - repo: ctx.target.did, - }); + const res = await credentialGet( + ctx, + credential, + "com.atproto.space.getRepo", + { + space, + repo: ctx.target.did, + }, + ); if (res.status !== 200) return fail(`getRepo ${describe(res)}`, res.json); const type = res.headers.get("Content-Type") ?? ""; - if (!type.includes("application/octet-stream")) return fail(`getRepo content-type was ${type}`); + if (!type.includes("application/octet-stream")) + return fail(`getRepo content-type was ${type}`); const mac = responseMac(res); - if (!mac) return fail("no parseable Atproto-Space-Mac header on a MAC'd getRepo"); + if (!mac) + return fail("no parseable Atproto-Space-Mac header on a MAC'd getRepo"); const bytes = new Uint8Array(await res.response.arrayBuffer()); try { const { records } = await verifyRepoStarFull([bytes], { @@ -205,7 +281,9 @@ const getRepoStar = crypto$("sync.getrepo-star", (ctx) => ? pass("STAR archive verified against its MAC; both records present") : fail(`archive verified but held ${rkeys.join(", ") || "no records"}`); } catch (err) { - return fail(`verifyRepoStarFull rejected the archive: ${(err as Error).message}`); + return fail( + `verifyRepoStarFull rejected the archive: ${(err as Error).message}`, + ); } }), ); @@ -213,40 +291,55 @@ const getRepoStar = crypto$("sync.getrepo-star", (ctx) => // --- token signatures ------------------------------------------------- async function atprotoKey(ctx: CheckContext, did: string): Promise { - const key = verificationMethodDidKey(await resolveDidDocument(ctx, did), "atproto"); + const key = verificationMethodDidKey( + await resolveDidDocument(ctx, did), + "atproto", + ); if (!key) throw new Error(`${did} publishes no #atproto key`); return key; } -const credentialSigned = crypto$("credential.signed-by-authority", async (ctx) => { - const space = await createProbeSpace(ctx, publicRead()); - try { - const credential = await obtainPublicCredential(ctx, space.uri); +const credentialSigned = crypto$( + "credential.signed-by-authority", + async (ctx) => { + const space = await createProbeSpace(ctx, publicRead()); try { - await verifySpaceToken("credential", credential.credential, { - getSigningKey: (iss) => atprotoKey(ctx, iss), - sub: space.uri, - }); - return pass("verifies against the authority's #atproto key"); - } catch (err) { - return fail(`credential did not verify: ${(err as Error).message}`); + const credential = await obtainPublicCredential(ctx, space.uri); + try { + await verifySpaceToken("credential", credential.credential, { + getSigningKey: (iss) => atprotoKey(ctx, iss), + sub: space.uri, + }); + return pass("verifies against the authority's #atproto key"); + } catch (err) { + return fail(`credential did not verify: ${(err as Error).message}`); + } + } finally { + await deleteProbeSpace(ctx, space.uri); } - } finally { - await deleteProbeSpace(ctx, space.uri); - } -}); + }, +); const delegationSigned = crypto$("delegation.signed-by-user", async (ctx) => { const space = await createProbeSpace(ctx, memberspace()); try { - const res = await xrpcGet(asOperator(ctx), "com.atproto.space.getDelegationToken", { space: space.uri }); - if (res.status !== 200) return fail(`getDelegationToken ${describe(res)}`, res.json); + const res = await xrpcGet( + asOperator(ctx), + "com.atproto.space.getDelegationToken", + { space: space.uri }, + ); + if (res.status !== 200) + return fail(`getDelegationToken ${describe(res)}`, res.json); try { - await verifySpaceToken("delegation", (res.json as { token: string }).token, { - getSigningKey: (iss) => atprotoKey(ctx, iss), - aud: spaceHostAud(ctx.target.did), - sub: space.uri, - }); + await verifySpaceToken( + "delegation", + (res.json as { token: string }).token, + { + getSigningKey: (iss) => atprotoKey(ctx, iss), + aud: spaceHostAud(ctx.target.did), + sub: space.uri, + }, + ); return pass("verifies against the user's #atproto key"); } catch (err) { return fail(`delegation token did not verify: ${(err as Error).message}`); @@ -263,7 +356,9 @@ async function exportMeta(ctx: CheckContext, space: string) { `${ctx.target.origin}/xrpc/com.atproto.space.exportSpaceMeta?space=${encodeURIComponent(space)}`, ); if (res.status !== 200) { - throw new Error(`exportSpaceMeta ${res.status} ${await res.text().catch(() => "")}`); + throw new Error( + `exportSpaceMeta ${res.status} ${await res.text().catch(() => "")}`, + ); } return { type: res.headers.get("Content-Type") ?? "", @@ -293,12 +388,16 @@ const exportSpaceMeta = crypto$("migration.export-space-meta", async (ctx) => { await mustCreateRecord(ctx, space.uri, "a"); const { type, archive } = await exportMeta(ctx, space.uri); const problems: string[] = []; - if (!type.includes("application/octet-stream")) problems.push(`content-type ${type}`); + if (!type.includes("application/octet-stream")) + problems.push(`content-type ${type}`); if (archive.space !== space.uri) problems.push(`space ${archive.space}`); - if (archive.policy.$type !== "com.atproto.memberspace.policy") problems.push(`policy ${String(archive.policy.$type)}`); + if (archive.policy.$type !== "com.atproto.memberspace.policy") + problems.push(`policy ${String(archive.policy.$type)}`); const entry = archive.policyState.find((e) => e.key === memberKey(member)); - if (!entry || entry.value.read !== true || entry.value.write !== false) problems.push("member entry missing or wrong"); - if (!archive.writers.some((w) => w.did === ctx.target.did)) problems.push("the authority is not in the writer set"); + if (!entry || entry.value.read !== true || entry.value.write !== false) + problems.push("member entry missing or wrong"); + if (!archive.writers.some((w) => w.did === ctx.target.did)) + problems.push("the authority is not in the writer set"); return problems.length ? fail(problems.join("; "), archive) : pass("archive carries the policy, the member and the writer set"); @@ -328,16 +427,33 @@ const importSpaceMeta = crypto$("migration.import-space-meta", async (ctx) => { policyState: [ { key: memberKey(after), - value: { $type: "com.atproto.memberspace.member", read: true, write: false }, + value: { + $type: "com.atproto.memberspace.member", + read: true, + write: false, + }, }, ], }); - if (imported.status !== 200) return fail(`importSpaceMeta ${describe(imported)}`, imported.json); - const got = await xrpcGet(asOperator(ctx), "com.atproto.space.getSpace", { space: space.uri }); - const policy = (got.json as { policy?: { publicRead?: boolean } } | undefined)?.policy; - const list = await xrpcGet(asOperator(ctx), "com.atproto.memberspace.listMembers", { space: space.uri }); - const dids = ((list.json as { members?: Array<{ did: string }> } | undefined)?.members ?? []).map((m) => m.did); - if (policy?.publicRead !== true) return fail("getSpace does not reflect the imported policy", got.json); + if (imported.status !== 200) + return fail(`importSpaceMeta ${describe(imported)}`, imported.json); + const got = await xrpcGet(asOperator(ctx), "com.atproto.space.getSpace", { + space: space.uri, + }); + const policy = ( + got.json as { policy?: { publicRead?: boolean } } | undefined + )?.policy; + const list = await xrpcGet( + asOperator(ctx), + "com.atproto.memberspace.listMembers", + { space: space.uri }, + ); + const dids = ( + (list.json as { members?: Array<{ did: string }> } | undefined) + ?.members ?? [] + ).map((m) => m.did); + if (policy?.publicRead !== true) + return fail("getSpace does not reflect the imported policy", got.json); return dids.includes(after) && !dids.includes(before) ? pass("imported policy and member list replaced the old ones") : fail(`members after import: ${dids.join(", ") || "none"}`, list.json); @@ -348,33 +464,42 @@ const importSpaceMeta = crypto$("migration.import-space-meta", async (ctx) => { } }); -const importMetaNotOwner = crypto$("migration.import-space-meta-not-owner", async (ctx) => { - const res = await importMeta(ctx, { - space: unknownSpaceUri(FOREIGN_DID) as never, - policy: { $type: "com.atproto.personalspace.policy" }, - policyState: [], - writers: [], - }); - return res.error === "NotSpaceOwner" - ? pass("answered NotSpaceOwner") - : fail(`answered ${describe(res)}, expected NotSpaceOwner`, res.json); -}); +const importMetaNotOwner = crypto$( + "migration.import-space-meta-not-owner", + async (ctx) => { + const res = await importMeta(ctx, { + space: unknownSpaceUri(FOREIGN_DID) as never, + policy: { $type: "com.atproto.personalspace.policy" }, + policyState: [], + writers: [], + }); + return res.error === "NotSpaceOwner" + ? pass("answered NotSpaceOwner") + : fail(`answered ${describe(res)}, expected NotSpaceOwner`, res.json); + }, +); -const importMetaUnsupported = crypto$("migration.import-space-meta-unsupported-policy", async (ctx) => { - const space = unknownSpaceUri(ctx.target.did); - const res = await importMeta(ctx, { - space: space as never, - policy: { $type: "com.example.mysteryPolicy" }, - policyState: [], - writers: [], - }); - if (res.status === 200) await deleteProbeSpace(ctx, space); - return res.error === "UnsupportedPolicy" - ? pass("answered UnsupportedPolicy") - : fail(`answered ${describe(res)}, expected UnsupportedPolicy`, res.json); -}); +const importMetaUnsupported = crypto$( + "migration.import-space-meta-unsupported-policy", + async (ctx) => { + const space = unknownSpaceUri(ctx.target.did); + const res = await importMeta(ctx, { + space: space as never, + policy: { $type: "com.example.mysteryPolicy" }, + policyState: [], + writers: [], + }); + if (res.status === 200) await deleteProbeSpace(ctx, space); + return res.error === "UnsupportedPolicy" + ? pass("answered UnsupportedPolicy") + : fail(`answered ${describe(res)}, expected UnsupportedPolicy`, res.json); + }, +); -async function ownRepoArchive(ctx: CheckContext, space: string): Promise { +async function ownRepoArchive( + ctx: CheckContext, + space: string, +): Promise { const res = await operatorFetch(ctx)( `${ctx.target.origin}/xrpc/com.atproto.space.getRepo?space=${encodeURIComponent(space)}&repo=${encodeURIComponent(ctx.target.did)}`, ); @@ -393,23 +518,47 @@ const importRepo = crypto$("migration.import-repo", async (ctx) => { await exported[Symbol.asyncDispose](); // Change the repo after export, so the import visibly replaces it. await mustCreateRecord(ctx, space.uri, "c", "three"); - const res = await xrpcPostBytes(asOperator(ctx), "com.atproto.space.importRepo", bytes); - if (res.status !== 200) return fail(`importRepo ${describe(res)}`, res.json); - const list = await xrpcGet(asOperator(ctx), "com.atproto.space.listRecords", { - space: space.uri, - repo: ctx.target.did, - }); - const rkeys = ((list.json as { records?: Array<{ rkey: string }> } | undefined)?.records ?? []) + const res = await xrpcPostBytes( + asOperator(ctx), + "com.atproto.space.importRepo", + bytes, + ); + if (res.status !== 200) + return fail(`importRepo ${describe(res)}`, res.json); + const list = await xrpcGet( + asOperator(ctx), + "com.atproto.space.listRecords", + { + space: space.uri, + repo: ctx.target.did, + }, + ); + const rkeys = ( + (list.json as { records?: Array<{ rkey: string }> } | undefined) + ?.records ?? [] + ) .map((r) => r.rkey) .sort(); - if (rkeys.join(",") !== "a,b") return fail(`records after import: ${rkeys.join(",")}`, list.json); - const latest = await xrpcGet(asOperator(ctx), "com.atproto.space.getLatestCommit", { - space: space.uri, - repo: ctx.target.did, - }); - const now = commitFromJson((latest.json as { commit?: unknown } | undefined)?.commit); - if (!now) return fail(`getLatestCommit after import ${describe(latest)}`, latest.json); - if (!bytesEqual(now.data, commit.data)) return fail("commit data changed across the import"); + if (rkeys.join(",") !== "a,b") + return fail(`records after import: ${rkeys.join(",")}`, list.json); + const latest = await xrpcGet( + asOperator(ctx), + "com.atproto.space.getLatestCommit", + { + space: space.uri, + repo: ctx.target.did, + }, + ); + const now = commitFromJson( + (latest.json as { commit?: unknown } | undefined)?.commit, + ); + if (!now) + return fail( + `getLatestCommit after import ${describe(latest)}`, + latest.json, + ); + if (!bytesEqual(now.data, commit.data)) + return fail("commit data changed across the import"); return now.rev > commit.rev ? pass("records replaced from the archive; same data, new rev") : fail(`rev ${now.rev} did not advance past the archive's ${commit.rev}`); @@ -420,30 +569,35 @@ const importRepo = crypto$("migration.import-repo", async (ctx) => { } }); -const importRepoNotFound = crypto$("migration.import-repo-space-not-found", async (ctx) => { - // A well-formed archive of an empty repo in an own space this host has - // never heard of: the authority's space must be imported first. - const space = `at://${ctx.target.did}/space/${PROBE_TYPE}/${probeSkey()}`; - const commit = new RepoCommit().toCommit({ - space: space as never, - repo: ctx.target.did as never, - rev: tidNow(), - }); - const res = await xrpcPostBytes( - asOperator(ctx), - "com.atproto.space.importRepo", - await collectBytes(serializeRepo(commit, [])), - ); - if (res.status === 200) await deleteProbeSpace(ctx, space); - return res.error === "SpaceNotFound" - ? pass("answered SpaceNotFound") - : fail(`answered ${describe(res)}, expected SpaceNotFound`, res.json); -}); +const importRepoNotFound = crypto$( + "migration.import-repo-space-not-found", + async (ctx) => { + // A well-formed archive of an empty repo in an own space this host has + // never heard of: the authority's space must be imported first. + const space = `at://${ctx.target.did}/space/${PROBE_TYPE}/${probeSkey()}`; + const commit = new RepoCommit().toCommit({ + space: space as never, + repo: ctx.target.did as never, + rev: tidNow(), + }); + const res = await xrpcPostBytes( + asOperator(ctx), + "com.atproto.space.importRepo", + await collectBytes(serializeRepo(commit, [])), + ); + if (res.status === 200) await deleteProbeSpace(ctx, space); + return res.error === "SpaceNotFound" + ? pass("answered SpaceNotFound") + : fail(`answered ${describe(res)}, expected SpaceNotFound`, res.json); + }, +); // --- foreign identities -------------------------------------------------- const isUserRefusal = (error?: string) => - error === "SpaceNotFound" || error === "UserNotAuthorized" || error === "NotAuthorized"; + error === "SpaceNotFound" || + error === "UserNotAuthorized" || + error === "NotAuthorized"; const memberGate = crypto$("credential.member-gate", async (ctx) => { const reader = await ctx.identities!.identity("reader"); @@ -460,23 +614,40 @@ const memberGate = crypto$("credential.member-gate", async (ctx) => { const stranger = await obtainCredential(ctx, reader, space.uri); if (stranger.credential) return fail("a non-member obtained a credential"); if (!isUserRefusal(stranger.result.error)) { - return fail(`non-member refused with ${describe(stranger.result)}; expected SpaceNotFound, UserNotAuthorized or NotAuthorized`); + return fail( + `non-member refused with ${describe(stranger.result)}; expected SpaceNotFound, UserNotAuthorized or NotAuthorized`, + ); } await put(false); const writeOnly = await obtainCredential(ctx, reader, space.uri); - if (writeOnly.credential) return fail("a member with read: false obtained a credential"); + if (writeOnly.credential) + return fail("a member with read: false obtained a credential"); await put(true); const member = await obtainCredential(ctx, reader, space.uri); - if (!member.credential) return fail(`a reader was refused: ${describe(member.result)}`, member.result.json); - const read = await credentialGet(ctx, member.credential, "com.atproto.space.getRecord", { - space: space.uri, - repo: ctx.target.did, - collection: POST, - rkey: "shared", - }); + if (!member.credential) + return fail( + `a reader was refused: ${describe(member.result)}`, + member.result.json, + ); + const read = await credentialGet( + ctx, + member.credential, + "com.atproto.space.getRecord", + { + space: space.uri, + repo: ctx.target.did, + collection: POST, + rkey: "shared", + }, + ); return read.status === 200 - ? pass(`non-member refused (${stranger.result.error}), read:false refused, reader admitted and read`) - : fail(`the reader's credential could not read: ${describe(read)}`, read.json); + ? pass( + `non-member refused (${stranger.result.error}), read:false refused, reader admitted and read`, + ) + : fail( + `the reader's credential could not read: ${describe(read)}`, + read.json, + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -487,46 +658,66 @@ const personalOnly = crypto$("policy.personalspace-owner-only", async (ctx) => { const space = await createProbeSpace(ctx, personalspace()); try { const res = await obtainCredential(ctx, reader, space.uri); - if (res.credential) return fail("a personalspace issued a credential to another user"); + if (res.credential) + return fail("a personalspace issued a credential to another user"); return isUserRefusal(res.result.error) ? pass(`refused with ${res.result.error}`) - : fail(`refused with ${describe(res.result)}; expected SpaceNotFound, UserNotAuthorized or NotAuthorized`); + : fail( + `refused with ${describe(res.result)}; expected SpaceNotFound, UserNotAuthorized or NotAuthorized`, + ); } finally { await deleteProbeSpace(ctx, space.uri); } }); -const delegationWrongAud = crypto$("delegation.wrong-audience-refused", async (ctx) => { - const reader = await ctx.identities!.identity("reader"); - const space = await createProbeSpace(ctx, memberspace()); - try { - await xrpcPost(asOperator(ctx), "com.atproto.memberspace.putMember", { - space: space.uri, - did: reader.did, - read: true, - write: false, - }); - // Positive control: with the right audience the reader is admitted, so - // the refusal below is the audience's and not an unresolvable reader. - const control = await obtainCredential(ctx, reader, space.uri); - if (!control.credential) { - return fail(`correct-aud control failed (${describe(control.result)}); cannot attribute the wrong-aud refusal`); +const delegationWrongAud = crypto$( + "delegation.wrong-audience-refused", + async (ctx) => { + const reader = await ctx.identities!.identity("reader"); + const space = await createProbeSpace(ctx, memberspace()); + try { + await xrpcPost(asOperator(ctx), "com.atproto.memberspace.putMember", { + space: space.uri, + did: reader.did, + read: true, + write: false, + }); + // Positive control: with the right audience the reader is admitted, so + // the refusal below is the audience's and not an unresolvable reader. + const control = await obtainCredential(ctx, reader, space.uri); + if (!control.credential) { + return fail( + `correct-aud control failed (${describe(control.result)}); cannot attribute the wrong-aud refusal`, + ); + } + const { result, credential } = await obtainCredential( + ctx, + reader, + space.uri, + { + audOverride: `${FOREIGN_DID}#atproto_pds`, + }, + ); + if (credential) + return fail("a token addressed to another host was accepted"); + return result.error === "InvalidDelegationToken" + ? pass("refused with InvalidDelegationToken") + : fail( + `refused with ${describe(result)}, expected InvalidDelegationToken`, + ); + } finally { + await deleteProbeSpace(ctx, space.uri); } - const { result, credential } = await obtainCredential(ctx, reader, space.uri, { - audOverride: `${FOREIGN_DID}#atproto_pds`, - }); - if (credential) return fail("a token addressed to another host was accepted"); - return result.error === "InvalidDelegationToken" - ? pass("refused with InvalidDelegationToken") - : fail(`refused with ${describe(result)}, expected InvalidDelegationToken`); - } finally { - await deleteProbeSpace(ctx, space.uri); - } -}); + }, +); async function notifyWrite( ctx: CheckContext, - writer: { did: string; jwtAlg: string; sign(b: Uint8Array): Promise }, + writer: { + did: string; + jwtAlg: string; + sign(b: Uint8Array): Promise; + }, space: string, repoRev: string, data: Uint8Array, @@ -538,7 +729,12 @@ async function notifyWrite( return xrpcPost( ctx, "com.atproto.space.notifyWrite", - { space, repo: writer.did, repoRev, data: { $bytes: toBase64(data).replace(/=+$/, "") } }, + { + space, + repo: writer.did, + repoRev, + data: { $bytes: toBase64(data).replace(/=+$/, "") }, + }, { Authorization: `Bearer ${jwt}` }, ); } @@ -556,15 +752,27 @@ const notifyAccepted = crypto$("host.notifywrite-accepted", async (ctx) => { const repoRev = tidNow(); const data = globalThis.crypto.getRandomValues(new Uint8Array(32)); const res = await notifyWrite(ctx, writer, space.uri, repoRev, data); - if (res.status !== 200) return fail(`notifyWrite ${describe(res)}`, res.json); + if (res.status !== 200) + return fail(`notifyWrite ${describe(res)}`, res.json); const credential = await obtainPublicCredential(ctx, space.uri); - const list = await credentialCall(ctx, credential, "com.atproto.space.listRepos", { - params: { space: space.uri }, - audience: ctx.target.did, - }); - const entry = ((list.json as { repos?: Array<{ did: string; repoRev: string; data: unknown }> } | undefined) - ?.repos ?? []).find((r) => r.did === writer.did); - if (!entry) return fail("the notified writer is not in listRepos", list.json); + const list = await credentialCall( + ctx, + credential, + "com.atproto.space.listRepos", + { + params: { space: space.uri }, + audience: ctx.target.did, + }, + ); + const entry = ( + ( + list.json as + | { repos?: Array<{ did: string; repoRev: string; data: unknown }> } + | undefined + )?.repos ?? [] + ).find((r) => r.did === writer.did); + if (!entry) + return fail("the notified writer is not in listRepos", list.json); const listed = lexBytes(entry.data); return entry.repoRev === repoRev && listed && bytesEqual(listed, data) ? pass("accepted; listRepos reports the notified repoRev and data") @@ -579,7 +787,13 @@ const notifyFuture = crypto$("host.notifywrite-future-rev", async (ctx) => { const space = await createProbeSpace(ctx, memberspace({ publicWrite: true })); try { const hourAhead = BigInt(Date.now() + 60 * 60 * 1000) * 1000n; - const res = await notifyWrite(ctx, writer, space.uri, tidAt(hourAhead), new Uint8Array(32)); + const res = await notifyWrite( + ctx, + writer, + space.uri, + tidAt(hourAhead), + new Uint8Array(32), + ); return res.error === "FutureRev" ? pass("a repoRev an hour ahead answered FutureRev") : fail(`answered ${describe(res)}, expected FutureRev`, res.json); @@ -590,7 +804,13 @@ const notifyFuture = crypto$("host.notifywrite-future-rev", async (ctx) => { const notifyUnknown = crypto$("host.notifywrite-unknown-space", async (ctx) => { const writer = await ctx.identities!.identity("writer"); - const res = await notifyWrite(ctx, writer, unknownSpaceUri(ctx.target.did), tidNow(), new Uint8Array(32)); + const res = await notifyWrite( + ctx, + writer, + unknownSpaceUri(ctx.target.did), + tidNow(), + new Uint8Array(32), + ); return res.error === "SpaceNotFound" ? pass("answered SpaceNotFound") : fail(`answered ${describe(res)}, expected SpaceNotFound`, res.json); @@ -604,11 +824,23 @@ const notifyUnknown = crypto$("host.notifywrite-unknown-space", async (ctx) => { async function revocationFlow( ctx: CheckContext, revoker: "authority" | "stranger", -): Promise<{ before: number; after?: { status: number; error?: string }; revoke?: { status: number; error?: string }; detail?: string }> { +): Promise<{ + before: number; + after?: { status: number; error?: string }; + revoke?: { status: number; error?: string }; + detail?: string; +}> { const authority = await ctx.identities!.identity("authority"); const space = `at://${authority.did}/space/${PROBE_TYPE}/${probeSkey()}`; - const write = await operatorCreateRecord(ctx, space, POST, "shared", { $type: POST, text: "for the authority" }); - if (write.status !== 200) return { before: write.status, detail: `operator write into a foreign space: ${describe(write)}` }; + const write = await operatorCreateRecord(ctx, space, POST, "shared", { + $type: POST, + text: "for the authority", + }); + if (write.status !== 200) + return { + before: write.status, + detail: `operator write into a foreign space: ${describe(write)}`, + }; const key = await createCredentialKey(); const credential: Credential = { credential: await mintCredential(authority, space, key.did), @@ -623,9 +855,19 @@ async function revocationFlow( rkey: "shared", }); const before = await read(); - if (before.status !== 200) return { before: before.status, detail: `foreign authority's credential could not read: ${describe(before)}` }; - const signer = revoker === "authority" ? authority : await ctx.identities!.identity("stranger"); - const jwt = await serviceJwt(signer, { aud: ctx.target.did, lxm: "com.atproto.space.notifyCredentialRevoked" }); + if (before.status !== 200) + return { + before: before.status, + detail: `foreign authority's credential could not read: ${describe(before)}`, + }; + const signer = + revoker === "authority" + ? authority + : await ctx.identities!.identity("stranger"); + const jwt = await serviceJwt(signer, { + aud: ctx.target.did, + lxm: "com.atproto.space.notifyCredentialRevoked", + }); const { payload } = decodeJwt(credential.credential); const revoke = await xrpcPost( ctx, @@ -637,14 +879,22 @@ async function revocationFlow( return { before: 200, revoke, after }; } -const revocationRefused = crypto$("revocation.revoked-credential-refused", async (ctx) => { - const flow = await revocationFlow(ctx, "authority"); - if (flow.detail) return fail(flow.detail); - if (flow.revoke!.status !== 200) return fail(`notifyCredentialRevoked ${flow.revoke!.status} ${flow.revoke!.error ?? ""}`); - return flow.after!.status >= 400 && flow.after!.status < 500 - ? pass(`foreign credential read 200; after revocation refused (${flow.after!.status} ${flow.after!.error ?? ""})`) - : fail(`a revoked credential still read (${flow.after!.status})`); -}); +const revocationRefused = crypto$( + "revocation.revoked-credential-refused", + async (ctx) => { + const flow = await revocationFlow(ctx, "authority"); + if (flow.detail) return fail(flow.detail); + if (flow.revoke!.status !== 200) + return fail( + `notifyCredentialRevoked ${flow.revoke!.status} ${flow.revoke!.error ?? ""}`, + ); + return flow.after!.status >= 400 && flow.after!.status < 500 + ? pass( + `foreign credential read 200; after revocation refused (${flow.after!.status} ${flow.after!.error ?? ""})`, + ) + : fail(`a revoked credential still read (${flow.after!.status})`); + }, +); const revocationName = crypto$("revocation.error-name", async (ctx) => { const flow = await revocationFlow(ctx, "authority"); @@ -654,14 +904,24 @@ const revocationName = crypto$("revocation.error-name", async (ctx) => { : fail(`refused with ${flow.after!.status} ${flow.after!.error ?? ""}`); }); -const revocationStranger = crypto$("revocation.non-authority-refused", async (ctx) => { - const flow = await revocationFlow(ctx, "stranger"); - if (flow.detail) return fail(flow.detail); - if (flow.revoke!.status === 200) return fail("accepted a revocation signed by someone other than the authority"); - return flow.after!.status === 200 - ? pass(`stranger's revocation refused (${flow.revoke!.status} ${flow.revoke!.error ?? ""}); credential still reads`) - : fail(`the revocation was refused but the credential stopped working (${flow.after!.status})`); -}); +const revocationStranger = crypto$( + "revocation.non-authority-refused", + async (ctx) => { + const flow = await revocationFlow(ctx, "stranger"); + if (flow.detail) return fail(flow.detail); + if (flow.revoke!.status === 200) + return fail( + "accepted a revocation signed by someone other than the authority", + ); + return flow.after!.status === 200 + ? pass( + `stranger's revocation refused (${flow.revoke!.status} ${flow.revoke!.error ?? ""}); credential still reads`, + ) + : fail( + `the revocation was refused but the credential stopped working (${flow.after!.status})`, + ); + }, +); const managedSpace = crypto$("managedspace.checkuseraccess", async (ctx) => { const inbox = ctx.syncerInbox!; @@ -673,19 +933,31 @@ const managedSpace = crypto$("managedspace.checkuseraccess", async (ctx) => { try { const since = Date.now(); const denied = await obtainCredential(ctx, reader, space.uri); - if (denied.credential) return fail("issued a credential the managing app refused"); - const asked = await inbox.waitFor((d) => d.lxm === lxm && d.receivedAt >= since, 5_000); - if (!asked) return fail(`the managing app was never asked (${describe(denied.result)})`); + if (denied.credential) + return fail("issued a credential the managing app refused"); + const asked = await inbox.waitFor( + (d) => d.lxm === lxm && d.receivedAt >= since, + 5_000, + ); + if (!asked) + return fail( + `the managing app was never asked (${describe(denied.result)})`, + ); const p = asked.params ?? {}; if (p.space !== space.uri || p.user !== reader.did || p.access !== "read") { return fail("checkUserAccess carried the wrong params", p); } - if (!asked.authorization?.startsWith("Bearer ")) return fail("checkUserAccess was sent without service auth"); + if (!asked.authorization?.startsWith("Bearer ")) + return fail("checkUserAccess was sent without service auth"); decision = true; const allowed = await obtainCredential(ctx, reader, space.uri); return allowed.credential - ? pass(`asked the managing app (space, user, access=read); refused on false (${denied.result.error}), issued on true`) - : fail(`the managing app authorised but the credential was refused: ${describe(allowed.result)}`); + ? pass( + `asked the managing app (space, user, access=read); refused on false (${denied.result.error}), issued on true`, + ) + : fail( + `the managing app authorised but the credential was refused: ${describe(allowed.result)}`, + ); } finally { inbox.respond(lxm, undefined); await deleteProbeSpace(ctx, space.uri); diff --git a/packages/space-conformance/src/full/helpers.ts b/packages/space-conformance/src/full/helpers.ts index fcea8e9..de59c02 100644 --- a/packages/space-conformance/src/full/helpers.ts +++ b/packages/space-conformance/src/full/helpers.ts @@ -83,7 +83,9 @@ export async function obtainCredential( ): Promise<{ result: XrpcResult; credential?: Credential }> { return requestCredential(ctx, space, { delegationToken: await mintDelegation(identity, space, opts.audOverride), - ...(opts.clientAttestation ? { clientAttestation: opts.clientAttestation } : {}), + ...(opts.clientAttestation + ? { clientAttestation: opts.clientAttestation } + : {}), }); } @@ -99,7 +101,11 @@ export async function mintCredential( ): Promise { return createSpaceToken( "credential", - { iss: authority.did, sub: space, keyId: keyDid as `did:${string}:${string}` }, + { + iss: authority.did, + sub: space, + keyId: keyDid as `did:${string}:${string}`, + }, keypairFor(authority), ); } diff --git a/packages/space-conformance/src/model.ts b/packages/space-conformance/src/model.ts index a257261..9e7e540 100644 --- a/packages/space-conformance/src/model.ts +++ b/packages/space-conformance/src/model.ts @@ -31,7 +31,12 @@ export interface Citation { * - `reference`: what the reference implementation happens to do. Fine * for a `should`; never enough on its own for a `must`. */ - source: "lexicon" | "proposal" | "pds-design-spec" | "changeset" | "reference"; + source: + | "lexicon" + | "proposal" + | "pds-design-spec" + | "changeset" + | "reference"; /** * Locator within the source: a lexicon id (optionally `#def` or * `@error:Name`), a proposal section anchor, a design-spec heading or a diff --git a/packages/space-conformance/src/space-auth.ts b/packages/space-conformance/src/space-auth.ts index 2af281f..89aa8b9 100644 --- a/packages/space-conformance/src/space-auth.ts +++ b/packages/space-conformance/src/space-auth.ts @@ -71,7 +71,10 @@ export function compressP256(uncompressed: Uint8Array): Uint8Array { /** 0x02/0x03 || x → 0x04 || x || y. */ export function decompressP256(compressed: Uint8Array): Uint8Array { - if (compressed.length !== 33 || (compressed[0] !== 2 && compressed[0] !== 3)) { + if ( + compressed.length !== 33 || + (compressed[0] !== 2 && compressed[0] !== 3) + ) { throw new Error("expected a compressed P-256 point"); } const x = bytesToBigInt(compressed.subarray(1)); @@ -212,7 +215,11 @@ export const formatWantMacHeader = (type: MacType, keyShare: string): string => `type="${type}", ver=1, key_share="${keyShare}"`; const uint16be = (n: number) => new Uint8Array([n >>> 8, n & 0xff]); -const KEM_PREFIX = concatBytes([utf8("HPKE-v1"), utf8("KEM"), uint16be(0x0010)]); +const KEM_PREFIX = concatBytes([ + utf8("HPKE-v1"), + utf8("KEM"), + uint16be(0x0010), +]); /** * Syncer side of the space KEM: ECDH between a fresh ephemeral P-256 key diff --git a/packages/space-conformance/test/cli.test.ts b/packages/space-conformance/test/cli.test.ts index 5f0451f..e665063 100644 --- a/packages/space-conformance/test/cli.test.ts +++ b/packages/space-conformance/test/cli.test.ts @@ -13,11 +13,25 @@ beforeAll(async () => { didDoc = { id: DID, verificationMethod: [ - { id: `${DID}#atproto`, type: "Multikey", controller: DID, publicKeyMultibase: signing.did().slice(8) }, - { id: `${DID}#atproto_kem`, type: "Multikey", controller: DID, publicKeyMultibase: kem.did().slice(8) }, + { + id: `${DID}#atproto`, + type: "Multikey", + controller: DID, + publicKeyMultibase: signing.did().slice(8), + }, + { + id: `${DID}#atproto_kem`, + type: "Multikey", + controller: DID, + publicKeyMultibase: kem.did().slice(8), + }, ], service: [ - { id: "#atproto_pds", type: "AtprotoPersonalDataServer", serviceEndpoint: "https://target.test" }, + { + id: "#atproto_pds", + type: "AtprotoPersonalDataServer", + serviceEndpoint: "https://target.test", + }, ], }; }); @@ -195,7 +209,10 @@ describe("runConformance (CLI core)", () => { serviceEndpoint: "https://target.test", }, ], - verificationMethod: (didDoc.verificationMethod as unknown[]).slice(0, 1), + verificationMethod: (didDoc.verificationMethod as unknown[]).slice( + 0, + 1, + ), }); } return Response.json({ error: "AuthMissing" }, { status: 401 }); @@ -205,7 +222,8 @@ describe("runConformance (CLI core)", () => { fetch: brokenTarget, suiteVersion: "0.0.0-test", }); - const status = (id: string) => report.results.find((r) => r.id === id)!.status; + const status = (id: string) => + report.results.find((r) => r.id === id)!.status; expect(status("discovery.pds-service")).toBe("fail"); expect(status("discovery.kem-key")).toBe("fail"); expect(status("discovery.signing-key")).toBe("pass"); @@ -241,7 +259,9 @@ describe("runConformance (CLI core)", () => { suiteVersion: "0.0.0-test", }); expect(report.target.plcDirectory).toBe("https://plc.test"); - expect(report.results.find((r) => r.id === "discovery.kem-key")!.status).toBe("pass"); + expect( + report.results.find((r) => r.id === "discovery.kem-key")!.status, + ).toBe("pass"); expect(requested).toContain(`https://plc.test/${plcDid}`); }); diff --git a/packages/space-conformance/test/core.test.ts b/packages/space-conformance/test/core.test.ts index bced5e9..dad4c80 100644 --- a/packages/space-conformance/test/core.test.ts +++ b/packages/space-conformance/test/core.test.ts @@ -359,7 +359,9 @@ describe("coverage", () => { expect(exempt).not.toContain( "com.atproto.space.getRecord@error:RepoTakendown", ); - expect(exempt).toContain("com.atproto.space.getRecord@error:RecordNotFound"); + expect(exempt).toContain( + "com.atproto.space.getRecord@error:RecordNotFound", + ); expect(report.gaps.map((g) => g.ref)).not.toContain( "com.atproto.space.getRepo@error:RepoTakendown", ); diff --git a/packages/space-conformance/test/full.test.ts b/packages/space-conformance/test/full.test.ts index 75e02fa..2d27861 100644 --- a/packages/space-conformance/test/full.test.ts +++ b/packages/space-conformance/test/full.test.ts @@ -67,7 +67,9 @@ describe("full catalog", () => { for (const check of fullCatalog) { for (const c of check.citations) { if (c.source === "changeset") { - expect(changesets.has(c.ref), `${check.id} cites ${c.ref}`).toBe(true); + expect(changesets.has(c.ref), `${check.id} cites ${c.ref}`).toBe( + true, + ); } } } @@ -155,7 +157,10 @@ describe("full catalog", () => { expect(check.needs, check.id).toContain("operator"); // A check that uses the target's own delegation tokens must say so. const source = check.run.toString(); - if (source.includes("getDelegationToken") || source.includes("obtainCredentialViaDelegation")) { + if ( + source.includes("getDelegationToken") || + source.includes("obtainCredentialViaDelegation") + ) { expect(check.needs, check.id).toContain("pds-delegation"); } if (source.includes("ctx.identities")) { @@ -219,10 +224,14 @@ describe("browser-safe space auth matches @atproto/space", () => { authorization: "Atproto-Space-Credential a.b.c", audience: "did:plc:abcdefghijklmnopqrstuvwx", }); - await expect(verifyCredentialSig(headers, key.did as never)).resolves.toBeUndefined(); + await expect( + verifyCredentialSig(headers, key.did as never), + ).resolves.toBeUndefined(); // And a different key's did is refused — the verification is real. const other = await createCredentialKey(); - await expect(verifyCredentialSig(headers, other.did as never)).rejects.toThrow(); + await expect( + verifyCredentialSig(headers, other.did as never), + ).rejects.toThrow(); }); it("encapsulate derives the secret the repo host decapsulates", async () => { @@ -237,16 +246,30 @@ describe("browser-safe space auth matches @atproto/space", () => { [COMMIT_MAC_TYPE, REF_COMMIT_MAC_TYPE], [RECORD_MAC_TYPE, REF_RECORD_MAC_TYPE], ] as const) { - expect(formatWantMacHeader(ours, share)).toBe(refFormatWantMacHeader(theirs, share)); - expect(parseWantMacHeader(formatWantMacHeader(ours, share), theirs)).toBe(share); + expect(formatWantMacHeader(ours, share)).toBe( + refFormatWantMacHeader(theirs, share), + ); + expect(parseWantMacHeader(formatWantMacHeader(ours, share), theirs)).toBe( + share, + ); } }); it("parses the reference's Atproto-Space-Mac header", () => { const mac = crypto.getRandomValues(new Uint8Array(32)); - expect(parseMacHeader(formatMacHeader(REF_COMMIT_MAC_TYPE, mac), COMMIT_MAC_TYPE)).toEqual(mac); + expect( + parseMacHeader( + formatMacHeader(REF_COMMIT_MAC_TYPE, mac), + COMMIT_MAC_TYPE, + ), + ).toEqual(mac); // Wrong type is refused rather than misread. - expect(parseMacHeader(formatMacHeader(REF_RECORD_MAC_TYPE, mac), COMMIT_MAC_TYPE)).toBeUndefined(); + expect( + parseMacHeader( + formatMacHeader(REF_RECORD_MAC_TYPE, mac), + COMMIT_MAC_TYPE, + ), + ).toBeUndefined(); }); it("compresses and decompresses P-256 points like @atproto/crypto", async () => { @@ -269,16 +292,24 @@ describe("browser-safe space auth matches @atproto/space", () => { const doc = { id: "did:plc:abcdefghijklmnopqrstuvwx", verificationMethod: [ - { id: "#atproto", type: "EcdsaSecp256k1VerificationKey2019", publicKeyMultibase: legacy(k256.did(), SECP256K1_JWT_ALG) }, - { id: "#atproto_kem", type: "EcdsaSecp256r1VerificationKey2019", publicKeyMultibase: legacy(p256.did(), P256_JWT_ALG) }, + { + id: "#atproto", + type: "EcdsaSecp256k1VerificationKey2019", + publicKeyMultibase: legacy(k256.did(), SECP256K1_JWT_ALG), + }, + { + id: "#atproto_kem", + type: "EcdsaSecp256r1VerificationKey2019", + publicKeyMultibase: legacy(p256.did(), P256_JWT_ALG), + }, ], }; expect(verificationMethodDidKey(doc, "atproto")).toBe(k256.did()); expect(verificationMethodDidKey(doc, "atproto_kem")).toBe(p256.did()); // Sanity: the legacy encoding round-trips through the reference decoder. - expect(multibaseToBytes(doc.verificationMethod[1]!.publicKeyMultibase)).toEqual( - cryptoParseDidKey(p256.did()).keyBytes, - ); + expect( + multibaseToBytes(doc.verificationMethod[1]!.publicKeyMultibase), + ).toEqual(cryptoParseDidKey(p256.did()).keyBytes); }); }); @@ -297,9 +328,15 @@ describe("encoding helpers", () => { }); it("resolves did:web and did:plc document URLs like the reference", () => { - expect(didDocumentUrl("did:web:example.com")).toBe("https://example.com/.well-known/did.json"); - expect(didDocumentUrl("did:web:localhost%3A2583")).toBe("http://localhost:2583/.well-known/did.json"); - expect(didDocumentUrl("did:plc:abc", "https://plc.test/")).toBe("https://plc.test/did:plc:abc"); + expect(didDocumentUrl("did:web:example.com")).toBe( + "https://example.com/.well-known/did.json", + ); + expect(didDocumentUrl("did:web:localhost%3A2583")).toBe( + "http://localhost:2583/.well-known/did.json", + ); + expect(didDocumentUrl("did:plc:abc", "https://plc.test/")).toBe( + "https://plc.test/did:plc:abc", + ); expect(() => didDocumentUrl("did:web:example.com:path")).toThrow(); }); From a3daa5f371c76a99673b130c4788f811d70be0d9 Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 09:10:23 +0000 Subject: [PATCH 08/16] test(spaces,pds): run the ported conformance suite in-process, and fix what it found Rewires both in-process runners to the 2026-11-05 suite. The space-routes run now offers every capability except the PDS-level ones: harness did:key identities, real service-auth verification, and an in-process syncer inbox that also receives the space DO alarm's deliveries. The PDS run adds the #atproto_kem discovery check and the MAC'd self-flow. Fixes the suite turned up: - getBlob answered 503 without blob storage before checking the space and the reference, instead of SpaceNotFound / BlobNotFound. - Managing another authority's space answered SpaceNotFound rather than the declared NotSpaceOwner. - listSpaces moves into the engine, which owns the space index. - The PDS resolved its own DID's #atproto_pds by fetching its DID document, which a Worker can't do for its own hostname, so a syncer registering the operator's own service failed on a deployed PDS. Also drops knip ignores and devDependencies left over from the 0818 pins. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LZ7qcQNQoiA6a23woGC7tB --- knip.json | 23 +- packages/pds/src/spaces.ts | 62 +- packages/pds/test/conformance.test.ts | 28 +- packages/pds/test/spaces.test.ts | 70 ++- packages/space-conformance/package.json | 1 - .../space-conformance/src/checks/operator.ts | 4 - .../space-conformance/src/checks/probe.ts | 2 +- .../space-conformance/src/full/helpers.ts | 2 +- packages/space-conformance/src/space-auth.ts | 4 +- packages/spaces/package.json | 2 - packages/spaces/src/routes.ts | 59 +- packages/spaces/test/conformance.test.ts | 315 +++++++--- .../test/fixtures/spaces-worker/index.ts | 5 +- packages/spaces/test/index-do.test.ts | 4 +- packages/spaces/test/routes.test.ts | 563 ++++++++++++++---- packages/spaces/test/space-do.test.ts | 116 +++- pnpm-lock.yaml | 9 - 17 files changed, 908 insertions(+), 361 deletions(-) diff --git a/knip.json b/knip.json index 4d6796f..7b75bf9 100644 --- a/knip.json +++ b/knip.json @@ -13,30 +13,11 @@ }, "packages/pds": { "ignore": ["scripts/**", "test/fixtures/**", "e2e/fixture/**"], - "ignoreDependencies": [ - "tsx", - "vite", - "@cloudflare/vite-plugin", - "@atproto/common", - "@atproto/common-web" - ] + "ignoreDependencies": ["tsx", "vite", "@cloudflare/vite-plugin"] }, "packages/spaces": { "ignore": ["test/fixtures/**"], - "ignoreDependencies": [ - "wrangler", - "@atproto/common", - "@atproto/common-web" - ] - }, - "packages/space-conformance": { - "ignoreDependencies": [ - "@atproto/common", - "@atproto/common-web", - "@atproto/lexicon", - "@atproto/oauth-client", - "@atproto/xrpc" - ] + "ignoreDependencies": ["wrangler"] }, "apps/check": { "entry": ["src/worker.ts"] diff --git a/packages/pds/src/spaces.ts b/packages/pds/src/spaces.ts index cc95625..a2609af 100644 --- a/packages/pds/src/spaces.ts +++ b/packages/pds/src/spaces.ts @@ -4,8 +4,8 @@ * The engine lives in @getcirrus/spaces; this module supplies the * account-specific pieces: the concrete Durable Object classes, the host * adapter (operator identity, DID resolution, session auth, record - * validation), and the user's-PDS role endpoints (getDelegationToken, - * listSpaces). Everything mounts behind the SPACES_ENABLED flag. + * validation), and the user's-PDS role endpoint getDelegationToken. + * Everything mounts behind the SPACES_ENABLED flag. */ import { Hono } from "hono"; @@ -153,8 +153,7 @@ export function createSpacesUnavailableApp(): Hono { /** * Build the host adapter and the complete spaces Hono app: the engine's - * space and memberspace routes plus the PDS-level getDelegationToken and - * listSpaces. + * space and memberspace routes plus the PDS-level getDelegationToken. */ export function createSpacesApp(deps: SpacesAppDeps): Hono { const { env, didResolver, getKeypair } = deps; @@ -194,6 +193,12 @@ export function createSpacesApp(deps: SpacesAppDeps): Hono { service: string, ): Promise { const [did, fragment] = service.split("#") as [string, string?]; + // A Worker cannot fetch its own hostname, so the operator's own + // service (a syncer registering this PDS, a space it writes into + // as its own authority) is answered from the env. + if (did === env.DID && (!fragment || fragment === "atproto_pds")) { + return `https://${env.PDS_HOSTNAME}`; + } const doc = await didResolver.resolve(did); if (!doc) return null; const services = (doc.service ?? []) as Array<{ @@ -373,7 +378,7 @@ export function createSpacesApp(deps: SpacesAppDeps): Hono { const app = createSpaceRoutes(host); // ------------------------------------------------------------------ - // User's-PDS role: delegation minting and the space index + // User's-PDS role: delegation minting // ------------------------------------------------------------------ app.get("/xrpc/com.atproto.space.getDelegationToken", async (c) => { @@ -410,53 +415,6 @@ export function createSpacesApp(deps: SpacesAppDeps): Hono { } }); - app.get("/xrpc/com.atproto.space.listSpaces", async (c) => { - try { - const session = await authenticate(c); - if (session instanceof Response) return session; - const type = c.req.query("spaceType"); - const authority = c.req.query("did"); - if (!session.fullTrust) { - // An unfiltered listing needs a wildcard grant. - const allowed = session.allowsSpace({ - type: type ?? "*", - authority: authority ?? "*", - skey: "*", - action: "read_self", - }); - if (!allowed) { - return c.json( - { - error: "InsufficientScope", - message: "Token does not cover listing these spaces", - }, - 403, - ); - } - } - const limitRaw = c.req.query("limit"); - const limit = Math.min( - Math.max(limitRaw ? Number.parseInt(limitRaw, 10) || 50 : 50, 1), - 100, - ); - const index = getSpaceIndexDO(env); - const page = await index.rpcList({ - type, - authority, - state: "active", - limit, - afterUri: c.req.query("cursor"), - }); - const last = page.spaces[page.spaces.length - 1]; - return c.json({ - spaces: page.spaces.map((space) => ({ uri: space.uri })), - ...(page.hasMore && last ? { cursor: last.uri } : {}), - }); - } catch (err) { - return spacesErrorResponse(c, err); - } - }); - return app; } diff --git a/packages/pds/test/conformance.test.ts b/packages/pds/test/conformance.test.ts index efa0ed1..0ad597e 100644 --- a/packages/pds/test/conformance.test.ts +++ b/packages/pds/test/conformance.test.ts @@ -13,7 +13,11 @@ */ import { describe, expect, it } from "vitest"; -import { filterCatalog, runChecks } from "@getcirrus/space-conformance"; +import { + ALPHA_BUILD, + filterCatalog, + runChecks, +} from "@getcirrus/space-conformance"; import { fullCatalog } from "@getcirrus/space-conformance/full"; import { env, worker } from "./helpers"; @@ -26,7 +30,7 @@ describe("conformance suite vs the integrated PDS", () => { // A full PDS: operator session, the public blob endpoints, and its // own getDelegationToken — so the operator can mint a credential for // its own space (the bulletin self-flow) without a foreign identity. - capabilities: ["operator", "pds-blobs", "pds-delegation"], + capabilities: ["operator", "pds-blobs", "pds-delegation", "alpha-libs"], destructive: true, }); const report = await runChecks({ @@ -46,11 +50,11 @@ describe("conformance suite vs the integrated PDS", () => { }, }, suiteVersion: "in-process", - alphaBuild: "0.0.0-spaces-alpha-20260818163953", + alphaBuild: ALPHA_BUILD, }); const failures = report.results.filter( - (r) => r.status === "fail" || r.status === "error", + (r) => (r.status === "fail" || r.status === "error") && r.tier !== "info", ); if (failures.length > 0) { throw new Error( @@ -63,17 +67,19 @@ describe("conformance suite vs the integrated PDS", () => { const byId = Object.fromEntries( report.results.map((r) => [r.id, r.status]), ); - // Discovery and blob isolation ran against the real worker. - expect(byId["discovery.space-host-service"]).toBe("pass"); + // Discovery (including the published #atproto_kem) and blob + // isolation ran against the real worker. + expect(byId["discovery.pds-service"]).toBe("pass"); + expect(byId["discovery.kem-key"]).toBe("pass"); expect(byId["blobs.space-blob-not-public"]).toBe("pass"); expect(byId["writes.create-and-read"]).toBe("pass"); - expect(byId["sync.getrepo-two-roots"]).toBe("pass"); + expect(byId["sync.getrepo-star"]).toBe("pass"); // The self-flow credential round-trip runs end-to-end: the worker mints - // its own delegation token, exchanges it for a DPoP-bound credential, - // and serves the read. This is the interop-critical path the reference - // matrix also exercises. + // its own delegation token, exchanges it for a credential bound to a + // P-256 key, and serves the signed, MAC'd read. This is the + // interop-critical path the reference matrix also exercises. expect(byId["credential.self-round-trip"]).toBe("pass"); // Identity-requiring checks skip here (no foreign resolution). - expect(byId["credential.round-trip"]).toBe("skipped"); + expect(byId["credential.member-gate"]).toBe("skipped"); }); }); diff --git a/packages/pds/test/spaces.test.ts b/packages/pds/test/spaces.test.ts index b94fc68..23c6bdf 100644 --- a/packages/pds/test/spaces.test.ts +++ b/packages/pds/test/spaces.test.ts @@ -58,12 +58,17 @@ describe("spaces integration", () => { // The space host is #atproto_pds and space tokens are signed with // #atproto, like any other account. expect(doc.service.map((s) => s.id)).toEqual(["#atproto_pds"]); - const kem = doc.verificationMethod.find((m) => m.id.endsWith("#atproto_kem")); + const kem = doc.verificationMethod.find((m) => + m.id.endsWith("#atproto_kem"), + ); expect(kem?.publicKeyMultibase).toBe(env.SPACES_KEM_KEY_PUBLIC); - const creds = await get("/xrpc/com.atproto.identity.getRecommendedDidCredentials", { - Authorization: `Bearer ${env.AUTH_TOKEN}`, - }); + const creds = await get( + "/xrpc/com.atproto.identity.getRecommendedDidCredentials", + { + Authorization: `Bearer ${env.AUTH_TOKEN}`, + }, + ); const body = (await creds.json()) as { verificationMethods: Record; }; @@ -83,9 +88,7 @@ describe("spaces integration", () => { }); expect(create.status).toBe(200); const created = (await create.json()) as { uri: string; cid: string }; - expect(created.uri).toBe( - `${space}/${env.DID}/test.cirrus.note/note1`, - ); + expect(created.uri).toBe(`${space}/${env.DID}/test.cirrus.note/note1`); const read = await get( `/xrpc/com.atproto.space.getRecord?space=${encodeURIComponent(space)}&repo=${env.DID}&collection=test.cirrus.note&rkey=note1`, @@ -219,7 +222,10 @@ describe("spaces integration", () => { const { keyShare, sharedSecret } = await encapsulate( `did:key:${env.SPACES_KEM_KEY_PUBLIC}`, ); - headers["atproto-space-want-mac"] = formatWantMacHeader(RECORD_MAC_TYPE, keyShare); + headers["atproto-space-want-mac"] = formatWantMacHeader( + RECORD_MAC_TYPE, + keyShare, + ); const read = await get( `/xrpc/com.atproto.space.getRecord?space=${encodeURIComponent(space)}&repo=${env.DID}&collection=test.cirrus.note&rkey=roundtrip`, headers, @@ -240,14 +246,19 @@ describe("spaces integration", () => { RECORD_MAC_TYPE, ); expect( - await verifyRecord(record as never, { uri: record.uri, sharedSecret, mac }), + await verifyRecord(record as never, { + uri: record.uri, + sharedSecret, + mac, + }), ).toBe(true); }); it("promotes blobs of an imported space repo when they are uploaded", async () => { // Migration order: the space repo arrives first, its blobs after. const bytes = new Uint8Array([0x4d, 0x49, 0x47, 0x52, 0x41, 0x54, 0x45]); - const { create, CODEC_RAW, CODEC_DCBOR, toString } = await import("@atcute/cid"); + const { create, CODEC_RAW, CODEC_DCBOR, toString } = + await import("@atcute/cid"); const cid = toString(await create(CODEC_RAW, bytes)); const record = { $type: "test.cirrus.file", @@ -273,7 +284,13 @@ describe("spaces integration", () => { rev: "3mabcdefghijk", data, }, - [{ collection: "test.cirrus.file" as never, rkey: "f" as never, bytes: recordBytes }], + [ + { + collection: "test.cirrus.file" as never, + rkey: "f" as never, + bytes: recordBytes, + }, + ], )) { chunks.push(chunk); } @@ -292,7 +309,9 @@ describe("spaces integration", () => { expect(imported.status).toBe(200); const blobPath = `/xrpc/com.atproto.space.getBlob?space=${encodeURIComponent(space)}&repo=${env.DID}&cid=${cid}`; - const before = await get(blobPath, { Authorization: `Bearer ${env.AUTH_TOKEN}` }); + const before = await get(blobPath, { + Authorization: `Bearer ${env.AUTH_TOKEN}`, + }); expect(before.status).toBe(404); const upload = await worker.fetch( @@ -307,11 +326,15 @@ describe("spaces integration", () => { env, ); expect(upload.status).toBe(200); - const after = await get(blobPath, { Authorization: `Bearer ${env.AUTH_TOKEN}` }); + const after = await get(blobPath, { + Authorization: `Bearer ${env.AUTH_TOKEN}`, + }); expect(after.status).toBe(200); expect(new Uint8Array(await after.arrayBuffer())).toEqual(bytes); // Still never public. - const publicBlob = await get(`/xrpc/com.atproto.sync.getBlob?did=${env.DID}&cid=${cid}`); + const publicBlob = await get( + `/xrpc/com.atproto.sync.getBlob?did=${env.DID}&cid=${cid}`, + ); expect(publicBlob.status).toBe(404); }); @@ -329,10 +352,9 @@ describe("spaces integration", () => { it("refuses app-password sessions on spaces but not the public repo", async () => { // Create an app password and log in with it. - const created = await post( - "/xrpc/com.atproto.server.createAppPassword", - { name: "spaces-test" }, - ); + const created = await post("/xrpc/com.atproto.server.createAppPassword", { + name: "spaces-test", + }); expect(created.status).toBe(200); const { password } = (await created.json()) as { password: string }; @@ -419,9 +441,7 @@ describe("spaces integration", () => { const listed = await get("/xrpc/com.atproto.space.listSpaces", { Authorization: `Bearer ${env.AUTH_TOKEN}`, }); - expect(((await listed.json()) as { spaces: unknown[] }).spaces).toEqual( - [], - ); + expect(((await listed.json()) as { spaces: unknown[] }).spaces).toEqual([]); const read = await get( `/xrpc/com.atproto.space.getRecord?space=${encodeURIComponent(space)}&repo=${env.DID}&collection=test.cirrus.note&rkey=x`, { Authorization: `Bearer ${env.AUTH_TOKEN}` }, @@ -440,9 +460,7 @@ describe("spaces integration", () => { // initialisation and the index activation: a pending entry with a // live, never-activated DO behind it. const uri = `at://${env.DID}/space/app.bsky.group/orphaned1`; - const index = env.SPACES_INDEX!.get( - env.SPACES_INDEX!.idFromName("spaces"), - ); + const index = env.SPACES_INDEX!.get(env.SPACES_INDEX!.idFromName("spaces")); await index.rpcRegister({ uri, authority: env.DID, @@ -480,9 +498,7 @@ describe("spaces integration", () => { const statusBody = (await status.json()) as { spaces: Array<{ uri: string; state: string }>; }; - expect(statusBody.spaces.find((s) => s.uri === uri)?.state).toBe( - "deleted", - ); + expect(statusBody.spaces.find((s) => s.uri === uri)?.state).toBe("deleted"); // Reset finds it through the tombstone and destroys the DO storage. const reset = await post("/xrpc/gg.mk.experimental.spacesReset", {}); diff --git a/packages/space-conformance/package.json b/packages/space-conformance/package.json index 20d9de4..5a8b5c8 100644 --- a/packages/space-conformance/package.json +++ b/packages/space-conformance/package.json @@ -22,7 +22,6 @@ "devDependencies": { "@arethetypeswrong/cli": "^0.18.2", "@atproto/crypto": "0.0.0-spaces-alpha-20261105160032", - "@atproto/lex-cbor": "0.0.0-spaces-alpha-20261105160032", "@atproto/lex-data": "0.0.0-spaces-alpha-20261105160032", "@atproto/oauth-client-node": "0.0.0-spaces-alpha-20261105160032", "@atproto/space": "0.0.0-spaces-alpha-20261105160032", diff --git a/packages/space-conformance/src/checks/operator.ts b/packages/space-conformance/src/checks/operator.ts index 13df004..198d09d 100644 --- a/packages/space-conformance/src/checks/operator.ts +++ b/packages/space-conformance/src/checks/operator.ts @@ -19,16 +19,12 @@ import { recordChecks } from "./records.js"; import { spaceChecks } from "./space.js"; export { - FOREIGN_DID, - POST, - PROBE_TYPE, createProbeSpace, credentialCall, credentialGet, deleteProbeSpace, managedspace, memberspace, - note, obtainCredentialViaDelegation, obtainPublicCredential, operatorCreateRecord, diff --git a/packages/space-conformance/src/checks/probe.ts b/packages/space-conformance/src/checks/probe.ts index e7aec2f..c988e37 100644 --- a/packages/space-conformance/src/checks/probe.ts +++ b/packages/space-conformance/src/checks/probe.ts @@ -377,5 +377,5 @@ export function credentialGet( export const describe = (res: XrpcResult): string => `${res.status}${res.error ? ` ${res.error}` : ""}`; -export const isAuthRefusal = (res: XrpcResult): boolean => +const isAuthRefusal = (res: XrpcResult): boolean => res.status === 401 || res.status === 403; diff --git a/packages/space-conformance/src/full/helpers.ts b/packages/space-conformance/src/full/helpers.ts index de59c02..3dadda2 100644 --- a/packages/space-conformance/src/full/helpers.ts +++ b/packages/space-conformance/src/full/helpers.ts @@ -42,7 +42,7 @@ export { export type { Credential, ProbeSpace } from "../checks/probe.js"; /** Adapt a harness identity to the `Keypair` surface token minting uses. */ -export function keypairFor(identity: HarnessIdentity) { +function keypairFor(identity: HarnessIdentity) { return { jwtAlg: identity.jwtAlg, sign: (bytes: Uint8Array) => identity.sign(bytes), diff --git a/packages/space-conformance/src/space-auth.ts b/packages/space-conformance/src/space-auth.ts index 89aa8b9..0cf0033 100644 --- a/packages/space-conformance/src/space-auth.ts +++ b/packages/space-conformance/src/space-auth.ts @@ -106,7 +106,7 @@ export function formatDidKey(alg: DidKeyAlg, keyBytes: Uint8Array): string { } /** Parse a did:key, returning its algorithm and compressed key bytes. */ -export function parseDidKey(didKey: string): { +function parseDidKey(didKey: string): { alg: DidKeyAlg; compressed: Uint8Array; } { @@ -207,7 +207,7 @@ export async function spaceSigHeaders( export const COMMIT_MAC_TYPE = "atproto-space-repo"; export const RECORD_MAC_TYPE = "atproto-space-record"; export type MacType = typeof COMMIT_MAC_TYPE | typeof RECORD_MAC_TYPE; -export const WANT_MAC_HEADER = "atproto-space-want-mac"; +const WANT_MAC_HEADER = "atproto-space-want-mac"; export const MAC_HEADER = "atproto-space-mac"; /** `type="…", ver=1, key_share="did:key:…"` — both MAC types are on v1. */ diff --git a/packages/spaces/package.json b/packages/spaces/package.json index 6ba7ec0..0afed3f 100644 --- a/packages/spaces/package.json +++ b/packages/spaces/package.json @@ -31,8 +31,6 @@ "@atproto/lex-data": "0.0.0-spaces-alpha-20261105160032", "@atproto/lex-json": "0.0.0-spaces-alpha-20261105160032", "@atproto/space": "0.0.0-spaces-alpha-20261105160032", - "@atproto/star": "0.0.0-spaces-alpha-20261105160032", - "@atproto/syntax": "0.0.0-spaces-alpha-20261105160032", "@cloudflare/vitest-pool-workers": "^0.16.9", "@cloudflare/workers-types": "^4.20260524.1", "@getcirrus/space-conformance": "workspace:*", diff --git a/packages/spaces/src/routes.ts b/packages/spaces/src/routes.ts index 217e9bc..a3ddf66 100644 --- a/packages/spaces/src/routes.ts +++ b/packages/spaces/src/routes.ts @@ -73,7 +73,6 @@ import { promoteStagedBlobToSpace, spaceBlobKey, spaceBlobPrefix, - stagedBlobKey, } from "./blob-keys.js"; import { requireSpaceUri, spaceId, spaceRecordUri } from "./space-uri.js"; import type { SpaceRef } from "./space-uri.js"; @@ -345,14 +344,18 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { } } + /** + * A space created here is anchored on its creator's DID, so ownership + * is a comparison against the space URI, made before anything else. + */ function assertOwner(ref: SpaceRef, session: SpaceSessionAuth): void { - assertSpaceHost(ref); if (session.did !== ref.authority) { throw new SpaceError( "NotSpaceOwner", "Only the space owner may manage the space", ); } + assertSpaceHost(ref); } /** The policy of a live space this host governs. */ @@ -1316,6 +1319,14 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { if (auth instanceof Response) return auth; const cid = c.req.query("cid"); requireString(cid, "cid"); + + const stub = host.getSpaceDO(ref.uri); + await requireRepoExists(stub, ref); + // Refuse before touching the blobstore: do not reveal whether an + // unreferenced blob exists. + if (!(await stub.rpcHasSpaceBlob(cid!))) { + throw new SpaceError("BlobNotFound", `Blob not found: ${cid}`); + } if (!host.blobs) { return c.json( { @@ -1325,14 +1336,6 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { 503, ); } - - const stub = host.getSpaceDO(ref.uri); - await requireRepoExists(stub, ref); - // Refuse before touching the blobstore: do not reveal whether an - // unreferenced blob exists. - if (!(await stub.rpcHasSpaceBlob(cid!))) { - throw new SpaceError("BlobNotFound", `Blob not found: ${cid}`); - } const key = spaceBlobKey(host.operatorDid, await spaceId(ref.uri), cid!); let blob = await host.blobs.get(key); if (!blob) { @@ -1992,6 +1995,40 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { } }); + app.get("/xrpc/com.atproto.space.listSpaces", async (c) => { + try { + const session = await host.authenticate(c); + if (session instanceof Response) return session; + const type = c.req.query("spaceType") || undefined; + const authority = c.req.query("did") || undefined; + // No one space to check against, so the filters are the target: + // an unfiltered listing needs a wildcard grant. It lists only the + // caller's own spaces, so read_self is the grant that fits. + const scopeError = assertScope(c, session, { + type: type ?? "*", + authority: authority ?? "*", + skey: "*", + action: "read_self", + }); + if (scopeError) return scopeError; + const limit = clampLimit(c.req.query("limit"), 50, 100); + const page = await host.getIndexDO().rpcList({ + type, + authority, + state: "active", + limit, + afterUri: c.req.query("cursor") || undefined, + }); + const last = page.spaces[page.spaces.length - 1]; + return c.json({ + spaces: page.spaces.map((space) => ({ uri: space.uri })), + ...(page.hasMore && last ? { cursor: last.uri } : {}), + }); + } catch (err) { + return errorResponse(c, err); + } + }); + // --------------------------------------------------------------- // memberspace (authority role, session auth) // --------------------------------------------------------------- @@ -2285,5 +2322,3 @@ async function deleteR2Prefix(bucket: R2Bucket, prefix: string): Promise { cursor = listed.truncated ? listed.cursor : undefined; } while (cursor); } - -export { stagedBlobKey }; diff --git a/packages/spaces/test/conformance.test.ts b/packages/spaces/test/conformance.test.ts index 48ffed4..67e6492 100644 --- a/packages/spaces/test/conformance.test.ts +++ b/packages/spaces/test/conformance.test.ts @@ -1,52 +1,169 @@ /** * The conformance suite, run in-process against Cirrus's own space routes. * - * This is the runner that exercises the crypto-bound catalog end to end: - * harness reader identities (did:key) are resolved by this fixture's - * `getSigningKey`, so the full delegation → credential → read dance and the - * host-role checks actually execute against the real route handlers. + * Every capability except the PDS-level ones runs here. Harness identities + * are did:key, which self-describe their key, so this fixture resolves them + * without a network. Every outbound call — the routes' own and the space + * DO alarm's notification deliveries — is routed to an in-process syncer + * inbox, so fan-out and managing-app checks see real deliveries. * - * Blob isolation needs PDS-level endpoints outside the space routes, so it - * declares the `pds-blobs` capability this fixture does not provide and is - * reported as skipped here; the PDS integration test covers it. + * Blob isolation and delegation minting need PDS-level endpoints outside + * the space routes (`pds-blobs`, `pds-delegation`); the PDS integration + * test covers those. */ import { env } from "cloudflare:test"; -import { describe, expect, it } from "vitest"; +import { afterAll, beforeAll, describe, expect, it } from "vitest"; import { Hono } from "hono"; import type { Context } from "hono"; -import { Secp256k1Keypair } from "@atproto/crypto"; -import { filterCatalog, runChecks } from "@getcirrus/space-conformance"; +import { + P256Keypair, + Secp256k1Keypair, + verifySignature, +} from "@atproto/crypto"; +import { + ALPHA_BUILD, + filterCatalog, + runChecks, + type InboxDelivery, + type SyncerInbox, +} from "@getcirrus/space-conformance"; import { KeypairIdentityProvider, fullCatalog, } from "@getcirrus/space-conformance/full"; import { createSpaceRoutes } from "../src/routes"; import type { SpaceRoutesHost } from "../src/routes"; -import { TEST_OPERATOR_DID, TEST_SIGNING_KEY } from "./fixtures/spaces-worker/index"; +import { + TEST_KEM_KEY, + TEST_OPERATOR_DID, + TEST_SIGNING_KEY, +} from "./fixtures/spaces-worker/index"; const OPERATOR = TEST_OPERATOR_DID; const ORIGIN = "https://pds.test"; +/** The harness syncer / managing app: a did:web whose host is the inbox. */ +const INBOX_DID = "did:web:inbox.test"; +const INBOX_ORIGIN = "https://inbox.test"; +/** Where notifications to a harness (did:key) authority are delivered. */ +const AUTHORITY_ORIGIN = "https://authority.test"; const operatorKeypair = await Secp256k1Keypair.import(TEST_SIGNING_KEY); +const kemKeypair = await P256Keypair.import(TEST_KEM_KEY); + +/** An in-process syncer inbox, also answering managing-app queries. */ +function createInbox(): SyncerInbox & { + handle(req: Request): Promise; +} { + const deliveries: InboxDelivery[] = []; + const waiters = new Set<() => void>(); + const responders = new Map unknown>(); + return { + service: `${INBOX_DID}#atproto_space_syncer`, + async handle(req) { + const url = new URL(req.url); + const lxm = url.pathname.replace(/^\/xrpc\//, ""); + const body = + req.method === "POST" ? await req.json().catch(() => null) : undefined; + const delivery: InboxDelivery = { + lxm, + body, + params: Object.fromEntries(url.searchParams), + authorization: req.headers.get("Authorization") ?? undefined, + receivedAt: Date.now(), + }; + deliveries.push(delivery); + for (const wake of waiters) wake(); + const responder = responders.get(lxm); + return Response.json(responder ? responder(delivery) : {}); + }, + async waitFor(predicate, timeoutMs) { + const deadline = Date.now() + timeoutMs; + for (;;) { + const found = deliveries.find(predicate); + if (found) return found; + const remaining = deadline - Date.now(); + if (remaining <= 0) return null; + await new Promise((resolve) => { + const wake = () => { + waiters.delete(wake); + resolve(); + }; + waiters.add(wake); + setTimeout(wake, Math.min(remaining, 250)); + }); + } + }, + respond(lxm, handler) { + if (handler) responders.set(lxm, handler); + else responders.delete(lxm); + }, + }; +} + +const inbox = createInbox(); + +/** Outbound fetch: harness services are answered in-process. */ +const routedFetch = (async (input: RequestInfo | URL, init?: RequestInit) => { + const req = new Request(input as RequestInfo, init); + const { origin } = new URL(req.url); + if (origin === INBOX_ORIGIN || origin === AUTHORITY_ORIGIN) { + return inbox.handle(req); + } + return new Response("unroutable in the conformance fixture", { status: 502 }); +}) as typeof fetch; + +/** did:key → itself; the operator from the env. */ +async function signingKeyFor(iss: string): Promise { + if (iss === OPERATOR) return operatorKeypair.did(); + if (iss.startsWith("did:key:")) return iss; + throw new Error(`unknown issuer: ${iss}`); +} + +function b64urlDecode(part: string): Uint8Array { + const b64 = part.replace(/-/g, "+").replace(/_/g, "/"); + return Uint8Array.from(atob(b64), (ch) => ch.charCodeAt(0)); +} + +/** Real service-auth verification against the issuer's key. */ +async function verifyServiceJwt(token: string, lxm: string) { + const [header, payload, sig] = token.split(".") as [string, string, string]; + const claims = JSON.parse( + new TextDecoder().decode(b64urlDecode(payload)), + ) as { + iss: string; + aud: string; + lxm?: string; + exp?: number; + }; + if (claims.lxm !== lxm) throw new Error(`service JWT not bound to ${lxm}`); + if (!claims.exp || claims.exp < Math.floor(Date.now() / 1000) - 5) { + throw new Error("service JWT expired"); + } + const valid = await verifySignature( + await signingKeyFor(claims.iss), + new TextEncoder().encode(`${header}.${payload}`), + b64urlDecode(sig), + ); + if (!valid) throw new Error("invalid service JWT signature"); + return { iss: claims.iss, aud: claims.aud }; +} function buildTarget() { const host: SpaceRoutesHost = { operatorDid: OPERATOR, - publicOrigin: ORIGIN, // No blobs: the pds-blobs capability is not offered by this fixture. getKeypair: async () => operatorKeypair, - getSigningKey: async (iss) => { - if (iss === OPERATOR) return operatorKeypair.did(); - // Harness identities are did:key, which self-describe their key. - if (iss.startsWith("did:key:")) return iss; - throw new Error(`unknown issuer: ${iss}`); - }, - resolveServiceEndpoint: async () => null, - resolveAuthorityEndpoint: async () => null, - verifyServiceJwt: async () => { - throw new Error("service auth not exercised by the conformance run"); + getKemPrivateKey: () => TEST_KEM_KEY, + getSigningKey: (iss) => signingKeyFor(iss), + resolveServiceEndpoint: async (service) => { + const did = service.split("#")[0]!; + if (did === OPERATOR) return ORIGIN; + if (did === INBOX_DID) return INBOX_ORIGIN; + if (did.startsWith("did:key:")) return AUTHORITY_ORIGIN; + return null; }, + verifyServiceJwt, authenticate: async (c: Context) => { if (c.req.header("Authorization") === "Bearer operator-session") { return { did: OPERATOR, fullTrust: true, allowsSpace: () => true }; @@ -57,25 +174,43 @@ function buildTarget() { getSpaceDO: (uri) => env.SPACES.get(env.SPACES.idFromName(uri)) as never, getIndexDO: () => env.SPACES_INDEX.get(env.SPACES_INDEX.idFromName("spaces")) as never, + outboundFetch: routedFetch, }; - const spaceApp = createSpaceRoutes(host); - // Wrap the space routes with the discovery document the suite probes. const app = new Hono(); + // The discovery document the suite probes: #atproto_pds, #atproto and + // the P-256 #atproto_kem syncers derive MAC secrets against. app.get("/.well-known/did.json", (c) => c.json({ + "@context": [ + "https://www.w3.org/ns/did/v1", + "https://w3id.org/security/multikey/v1", + ], id: OPERATOR, + verificationMethod: [ + { + id: `${OPERATOR}#atproto`, + type: "Multikey", + controller: OPERATOR, + publicKeyMultibase: operatorKeypair.did().slice("did:key:".length), + }, + { + id: `${OPERATOR}#atproto_kem`, + type: "Multikey", + controller: OPERATOR, + publicKeyMultibase: kemKeypair.did().slice("did:key:".length), + }, + ], service: [ { - id: "#atproto_space_host", - type: "AtprotoSpaceHost", + id: "#atproto_pds", + type: "AtprotoPersonalDataServer", serviceEndpoint: ORIGIN, }, ], - verificationMethod: [{ id: `${OPERATOR}#atproto` }], }), ); - app.route("/", spaceApp); + app.route("/", createSpaceRoutes(host)); const fetchAdapter: typeof fetch = (input, init) => app.fetch(new Request(input as RequestInfo, init)); @@ -83,52 +218,86 @@ function buildTarget() { } describe("conformance suite vs Cirrus space routes", () => { - it("passes every runnable must and should check", async () => { - const { fetchAdapter } = buildTarget(); - const catalog = filterCatalog(fullCatalog, { - capabilities: ["operator", "identities"], - destructive: true, - }); - const report = await runChecks({ - catalog, - context: { - target: { origin: ORIGIN, did: OPERATOR, implementation: "cirrus" }, - fetch: fetchAdapter, - operator: { - oauth: false, - async authorize(reqInit) { - reqInit.headers.set("Authorization", "Bearer operator-session"); + // The space DO's alarm delivers notifications with the global fetch. + const realFetch = globalThis.fetch; + beforeAll(() => { + globalThis.fetch = routedFetch; + }); + afterAll(() => { + globalThis.fetch = realFetch; + }); + + it( + "passes every runnable must and should check", + { timeout: 180_000 }, + async () => { + const { fetchAdapter } = buildTarget(); + const catalog = filterCatalog(fullCatalog, { + capabilities: ["operator", "identities", "syncer-inbox", "alpha-libs"], + destructive: true, + }); + const report = await runChecks({ + catalog, + context: { + target: { origin: ORIGIN, did: OPERATOR, implementation: "cirrus" }, + fetch: fetchAdapter, + operator: { + oauth: false, + async authorize(reqInit) { + reqInit.headers.set("Authorization", "Bearer operator-session"); + }, }, + identities: new KeypairIdentityProvider(), + syncerInbox: inbox, }, - identities: new KeypairIdentityProvider(), - }, - suiteVersion: "in-process", - alphaBuild: "0.0.0-spaces-alpha-20260818163953", - }); - - const failures = report.results.filter( - (r) => r.status === "fail" || r.status === "error", - ); - // Surface every failing check's detail so a regression is legible. - if (failures.length > 0) { - throw new Error( - `conformance failures:\n${failures - .map((f) => ` [${f.tier}] ${f.id}: ${f.status} — ${f.detail}`) - .join("\n")}`, + suiteVersion: "in-process", + alphaBuild: ALPHA_BUILD, + }); + + const failures = report.results.filter( + (r) => + (r.status === "fail" || r.status === "error") && r.tier !== "info", ); - } - - // A meaningful number of checks actually ran (not all skipped). - const ran = report.results.filter((r) => r.status === "pass"); - expect(ran.length).toBeGreaterThanOrEqual(15); - // The credential dance, delegation refusals and host gating ran here. - const byId = Object.fromEntries(report.results.map((r) => [r.id, r.status])); - expect(byId["credential.round-trip"]).toBe("pass"); - expect(byId["delegation.replay-refused"]).toBe("pass"); - expect(byId["host.member-list-gates"]).toBe("pass"); - expect(byId["sync.oplog-folds-to-commit"]).toBe("pass"); - expect(byId["host.delete-space-tombstone"]).toBe("pass"); - // Blob isolation needs a full PDS — skipped here, covered elsewhere. - expect(byId["blobs.space-blob-not-public"]).toBe("skipped"); - }); + // Surface every failing check's detail so a regression is legible. + if (failures.length > 0) { + throw new Error( + `conformance failures:\n${failures + .map((f) => ` [${f.tier}] ${f.id}: ${f.status} — ${f.detail}`) + .join("\n")}`, + ); + } + + const byId = Object.fromEntries( + report.results.map((r) => [r.id, r.status]), + ); + // Everything this fixture can offer actually ran. + const skipped = report.results + .filter((r) => r.status === "skipped") + .map((r) => r.id) + .sort(); + expect(skipped).toEqual( + [ + "blobs.listblobs-and-getblob", + "blobs.space-blob-not-public", + "credential.self-round-trip", + "delegation.replay-refused", + "delegation.signed-by-user", + "delegation.token-claims", + "delegation.wrong-space-refused", + ].sort(), + ); + for (const id of [ + "credential.member-gate", + "sync.oplog-folds-to-commit", + "sync.getrepo-star", + "credential.deleted-space", + "revocation.revoked-credential-refused", + "notify.forwarded-notifywrite", + "notify.space-deleted-delivered", + "managedspace.checkuseraccess", + ]) { + expect(byId[id], id).toBe("pass"); + } + }, + ); }); diff --git a/packages/spaces/test/fixtures/spaces-worker/index.ts b/packages/spaces/test/fixtures/spaces-worker/index.ts index af49c6d..0dce6b4 100644 --- a/packages/spaces/test/fixtures/spaces-worker/index.ts +++ b/packages/spaces/test/fixtures/spaces-worker/index.ts @@ -7,7 +7,10 @@ */ import { Secp256k1Keypair } from "@atproto/crypto"; -import { SpaceDurableObject, SpaceIndexDurableObject } from "../../../src/index"; +import { + SpaceDurableObject, + SpaceIndexDurableObject, +} from "../../../src/index"; import type { SpaceHostConfig } from "../../../src/index"; /** Deterministic test signing key (hex-encoded secp256k1 private key). */ diff --git a/packages/spaces/test/index-do.test.ts b/packages/spaces/test/index-do.test.ts index 0c7b124..f56b14d 100644 --- a/packages/spaces/test/index-do.test.ts +++ b/packages/spaces/test/index-do.test.ts @@ -118,9 +118,7 @@ describe("SpaceIndexDurableObject", () => { afterUri: page1.spaces[1]!.uri, }); expect(page2.spaces.length).toBeGreaterThan(0); - expect( - page2.spaces.every((s) => s.uri > page1.spaces[1]!.uri), - ).toBe(true); + expect(page2.spaces.every((s) => s.uri > page1.spaces[1]!.uri)).toBe(true); }); it("holds pending imported blobs until uploadBlob claims them", async () => { diff --git a/packages/spaces/test/routes.test.ts b/packages/spaces/test/routes.test.ts index e8ee7d7..9654abc 100644 --- a/packages/spaces/test/routes.test.ts +++ b/packages/spaces/test/routes.test.ts @@ -22,7 +22,11 @@ import type { Commit, MacType } from "@atproto/space"; import { JoseKey } from "@atproto/jwk-jose"; import { encode } from "@atproto/lex-cbor"; import { fromBase64 } from "@atproto/lex-data"; -import { create as createCid, CODEC_RAW, toString as cidToString } from "@atcute/cid"; +import { + create as createCid, + CODEC_RAW, + toString as cidToString, +} from "@atcute/cid"; import { createSpaceRoutes } from "../src/routes"; import type { SpaceRoutesHost, SpaceScopeMatch } from "../src/routes"; import { @@ -103,7 +107,10 @@ function makeHost(overrides: Partial = {}): { ), }; } - return c.json({ error: "AuthenticationRequired", message: "No session" }, 401); + return c.json( + { error: "AuthenticationRequired", message: "No session" }, + 401, + ); }, validateRecord: ({ record }) => ({ record, status: "unknown" }), getSpaceDO: (uri) => env.SPACES.get(env.SPACES.idFromName(uri)) as never, @@ -156,7 +163,10 @@ function post( }); } -function get(path: string, headers: Record = SESSION): Promise { +function get( + path: string, + headers: Record = SESSION, +): Promise { return app.request(path, { headers }); } @@ -183,7 +193,12 @@ async function createRecord( return (await res.json()) as { uri: string; cid: string }; } -async function putMember(space: string, did: string, read = true, write = true) { +async function putMember( + space: string, + did: string, + read = true, + write = true, +) { const res = await post("/xrpc/com.atproto.memberspace.putMember", { space, did, @@ -200,7 +215,12 @@ async function obtainCredential( user?: { did: string; keypair: Secp256k1Keypair }; clientAttestation?: string; } = {}, -): Promise<{ credential: string; key: P256Keypair; status: number; body: unknown }> { +): Promise<{ + credential: string; + key: P256Keypair; + status: number; + body: unknown; +}> { const key = await P256Keypair.create(); const delegationToken = opts.user ? await createSpaceToken( @@ -276,7 +296,12 @@ function commitFromJson(json: Record): Commit { }; } -async function serviceJwt(iss: string, aud: string, lxm: string, keypair: Secp256k1Keypair) { +async function serviceJwt( + iss: string, + aud: string, + lxm: string, + keypair: Secp256k1Keypair, +) { const { createServiceJwt } = await import("../src/service-jwt"); return createServiceJwt({ iss, aud, lxm }, keypair); } @@ -289,10 +314,20 @@ async function notifyWrite( data: Uint8Array, aud = OPERATOR, ): Promise { - const token = await serviceJwt(writer, aud, "com.atproto.space.notifyWrite", keypair); + const token = await serviceJwt( + writer, + aud, + "com.atproto.space.notifyWrite", + keypair, + ); return post( "/xrpc/com.atproto.space.notifyWrite", - { space, repo: writer, repoRev, data: { $bytes: btoa(String.fromCharCode(...data)) } }, + { + space, + repo: writer, + repoRev, + data: { $bytes: btoa(String.fromCharCode(...data)) }, + }, { Authorization: `Bearer ${token}` }, ); } @@ -300,7 +335,7 @@ async function notifyWrite( const TID_CHARS = "234567abcdefghijklmnopqrstuvwxyz"; /** A TID for a given time, so tests control rev order and skew. */ function tidAt(ms: number, clock = 0): string { - let value = (BigInt(Math.floor(ms)) * 1000n << 10n) | BigInt(clock); + let value = ((BigInt(Math.floor(ms)) * 1000n) << 10n) | BigInt(clock); let out = ""; for (let i = 0; i < 13; i++) { out = TID_CHARS[Number(value & 31n)] + out; @@ -336,7 +371,11 @@ describe("space routes: personal data (S1)", () => { it("refuses an unauthenticated getRecord", async () => { const space = await createSpace(); - await createRecord(space, { $type: "app.bsky.feed.post", text: "x" }, "aaa"); + await createRecord( + space, + { $type: "app.bsky.feed.post", text: "x" }, + "aaa", + ); const res = await get( `/xrpc/com.atproto.space.getRecord?space=${q(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=aaa`, {}, @@ -448,7 +487,10 @@ describe("space routes: personal data (S1)", () => { space, repo: OPERATOR, collection: "app.bsky.feed.post", - record: { $type: "app.bsky.feed.post", text: "x".repeat(1024 * 1024 + 1) }, + record: { + $type: "app.bsky.feed.post", + text: "x".repeat(1024 * 1024 + 1), + }, }); expect(big.status).toBe(400); expect(await errorOf(big)).toBe("InvalidRequest"); @@ -474,7 +516,12 @@ describe("space routes: personal data (S1)", () => { publishPolicy: true, }); await createRecord(space, { $type: "app.bsky.feed.post", text: "a" }, "a"); - await createRecord(space, { $type: "app.bsky.feed.like", subject: "x" }, "b", "app.bsky.feed.like"); + await createRecord( + space, + { $type: "app.bsky.feed.like", subject: "x" }, + "b", + "app.bsky.feed.like", + ); // A scoped session needs delete on every collection being cleared. const narrow = `Bearer scoped:${JSON.stringify({ actions: ["read_self"] })}`; @@ -496,12 +543,17 @@ describe("space routes: personal data (S1)", () => { const { records } = (await list.json()) as { records: Array<{ collection: string }>; }; - expect(records.map((r) => r.collection)).toEqual(["com.atproto.space.policy"]); + expect(records.map((r) => r.collection)).toEqual([ + "com.atproto.space.policy", + ]); const ops = await get( `/xrpc/com.atproto.space.listRepoOps?space=${q(space)}&repo=${OPERATOR}`, ); - const opsBody = (await ops.json()) as { ops: unknown[]; commit: Record }; + const opsBody = (await ops.json()) as { + ops: unknown[]; + commit: Record; + }; expect(opsBody.ops).toEqual([]); // The digest is that of the records that remain. const commit = commitFromJson(opsBody.commit); @@ -513,10 +565,10 @@ describe("space routes: personal data (S1)", () => { expected.add(`com.atproto.space.policy/self/${cid}`); expect(commit.data).toEqual(expected.digest()); - const other = await post( - "/xrpc/com.atproto.space.clearRecords", - { space, repo: BOB }, - ); + const other = await post("/xrpc/com.atproto.space.clearRecords", { + space, + repo: BOB, + }); expect(other.status).toBe(403); }); }); @@ -524,7 +576,11 @@ describe("space routes: personal data (S1)", () => { describe("space routes: credentials (S5)", () => { it("issues credentials to members, binds them to the request key and refuses others as SpaceNotFound", async () => { const space = await createSpace(); - await createRecord(space, { $type: "app.bsky.feed.post", text: "hi" }, "r1"); + await createRecord( + space, + { $type: "app.bsky.feed.post", text: "hi" }, + "r1", + ); const denied = await obtainCredential(space, { user: { did: BOB, keypair: bobKeypair }, @@ -546,20 +602,40 @@ describe("space routes: credentials (S5)", () => { expect(payload.aud).toBeUndefined(); const path = `/xrpc/com.atproto.space.getRecord?space=${q(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=r1`; - const { res, sharedSecret } = await credentialRequest(path, credential, key, { - mac: RECORD_MAC_TYPE, - }); + const { res, sharedSecret } = await credentialRequest( + path, + credential, + key, + { + mac: RECORD_MAC_TYPE, + }, + ); expect(res.status).toBe(200); - const record = (await res.json()) as { uri: string; cid: string; value: Record }; - const mac = parseMacHeader(res.headers.get("atproto-space-mac") ?? undefined, RECORD_MAC_TYPE); + const record = (await res.json()) as { + uri: string; + cid: string; + value: Record; + }; + const mac = parseMacHeader( + res.headers.get("atproto-space-mac") ?? undefined, + RECORD_MAC_TYPE, + ); expect( - await verifyRecord(record as never, { uri: record.uri, sharedSecret: sharedSecret!, mac }), + await verifyRecord(record as never, { + uri: record.uri, + sharedSecret: sharedSecret!, + mac, + }), ).toBe(true); - expect(res.headers.get("access-control-expose-headers")).toContain("atproto-space-mac"); + expect(res.headers.get("access-control-expose-headers")).toContain( + "atproto-space-mac", + ); // A member without read access is refused like a stranger. await putMember(space, BOB, false, true); - const noRead = await obtainCredential(space, { user: { did: BOB, keypair: bobKeypair } }); + const noRead = await obtainCredential(space, { + user: { did: BOB, keypair: bobKeypair }, + }); expect(noRead.status).toBe(404); }); @@ -610,7 +686,11 @@ describe("space routes: credentials (S5)", () => { expect((anon.body as { error: string }).error).toBe("SpaceNotFound"); const open = await createSpace({ ...MEMBERSPACE, publicRead: true }); - await createRecord(open, { $type: "app.bsky.feed.post", text: "public" }, "p"); + await createRecord( + open, + { $type: "app.bsky.feed.post", text: "public" }, + "p", + ); const { credential, key, status } = await obtainCredential(open); expect(status).toBe(200); const { res } = await credentialRequest( @@ -629,14 +709,22 @@ describe("space routes: credentials (S5)", () => { const { credential, key } = await obtainCredential(space); const path = `/xrpc/com.atproto.space.listRecords?space=${q(space)}&repo=${OPERATOR}`; - const ok = await credentialRequest(path, credential, key, { scheme: "atproto-space-credential" }); + const ok = await credentialRequest(path, credential, key, { + scheme: "atproto-space-credential", + }); expect(ok.res.status).toBe(200); - const wrongKey = await credentialRequest(path, credential, await P256Keypair.create()); + const wrongKey = await credentialRequest( + path, + credential, + await P256Keypair.create(), + ); expect(wrongKey.res.status).toBe(401); expect(await errorOf(wrongKey.res)).toBe("BadSpaceSignature"); - const wrongAudience = await credentialRequest(path, credential, key, { audience: BOB }); + const wrongAudience = await credentialRequest(path, credential, key, { + audience: BOB, + }); expect(wrongAudience.res.status).toBe(401); expect(await errorOf(wrongAudience.res)).toBe("BadSpaceAudience"); @@ -659,18 +747,30 @@ describe("space routes: credentials (S5)", () => { // Revocation, by the authority, addressed to the repo DID. const jti = ( - JSON.parse(atob(credential.split(".")[1]!.replace(/-/g, "+").replace(/_/g, "/"))) as { + JSON.parse( + atob(credential.split(".")[1]!.replace(/-/g, "+").replace(/_/g, "/")), + ) as { jti: string; } ).jti; - const forged = await serviceJwt(BOB, OPERATOR, "com.atproto.space.notifyCredentialRevoked", bobKeypair); + const forged = await serviceJwt( + BOB, + OPERATOR, + "com.atproto.space.notifyCredentialRevoked", + bobKeypair, + ); const forgedRes = await post( "/xrpc/com.atproto.space.notifyCredentialRevoked", { space, credentials: [jti] }, { Authorization: `Bearer ${forged}` }, ); expect(forgedRes.status).toBe(403); - const token = await serviceJwt(OPERATOR, OPERATOR, "com.atproto.space.notifyCredentialRevoked", operatorKeypair); + const token = await serviceJwt( + OPERATOR, + OPERATOR, + "com.atproto.space.notifyCredentialRevoked", + operatorKeypair, + ); const revoke = await post( "/xrpc/com.atproto.space.notifyCredentialRevoked", { space, credentials: [jti] }, @@ -685,7 +785,11 @@ describe("space routes: credentials (S5)", () => { it("gates on allowedApps with client attestations, after the user", async () => { const clientId = "https://app.example/client-metadata.json"; const jwk = await JoseKey.generate(["ES256"], "attest-key"); - const space = await createSpace({ ...MEMBERSPACE, publicRead: true, allowedApps: [clientId] }); + const space = await createSpace({ + ...MEMBERSPACE, + publicRead: true, + allowedApps: [clientId], + }); const { host: attestHost, setOutboundResponse: respond } = makeHost(); const attestApp = createSpaceRoutes(attestHost); @@ -721,10 +825,14 @@ describe("space routes: credentials (S5)", () => { expect((await request(await attest())).status).toBe(200); - const otherApp = await request(await attest(undefined, "https://other.example/client-metadata.json")); + const otherApp = await request( + await attest(undefined, "https://other.example/client-metadata.json"), + ); expect(await errorOf(otherApp)).toBe("AppNotAuthorized"); - const wrongAud = await request(await attest(`${OPERATOR}#atproto_space_host`)); + const wrongAud = await request( + await attest(`${OPERATOR}#atproto_space_host`), + ); expect(await errorOf(wrongAud)).toBe("InvalidClientAttestation"); }); @@ -739,20 +847,30 @@ describe("space routes: credentials (S5)", () => { return Response.json({ authorized: user === BOB }); }); try { - const bob = await obtainCredential(space, { user: { did: BOB, keypair: bobKeypair } }); + const bob = await obtainCredential(space, { + user: { did: BOB, keypair: bobKeypair }, + }); expect(bob.status).toBe(200); - const check = outbound.filter((call) => call.url.includes("checkUserAccess")).pop()!; + const check = outbound + .filter((call) => call.url.includes("checkUserAccess")) + .pop()!; const params = new URL(check.url).searchParams; expect(params.get("access")).toBe("read"); expect(params.get("space")).toBe(space); - const carol = await obtainCredential(space, { user: { did: CAROL, keypair: carolKeypair } }); + const carol = await obtainCredential(space, { + user: { did: CAROL, keypair: carolKeypair }, + }); expect(carol.status).toBe(404); setOutboundResponse((url) => - url.includes("checkUserAccess") ? new Response("boom", { status: 500 }) : null, + url.includes("checkUserAccess") + ? new Response("boom", { status: 500 }) + : null, ); - const failing = await obtainCredential(space, { user: { did: BOB, keypair: bobKeypair } }); + const failing = await obtainCredential(space, { + user: { did: BOB, keypair: bobKeypair }, + }); expect(failing.status).toBe(404); } finally { setOutboundResponse(() => null); @@ -760,8 +878,12 @@ describe("space routes: credentials (S5)", () => { }); it("personalspace authorises only the authority", async () => { - const space = await createSpace({ $type: "com.atproto.personalspace.policy" }); - const bob = await obtainCredential(space, { user: { did: BOB, keypair: bobKeypair } }); + const space = await createSpace({ + $type: "com.atproto.personalspace.policy", + }); + const bob = await obtainCredential(space, { + user: { did: BOB, keypair: bobKeypair }, + }); expect(bob.status).toBe(404); const self = await obtainCredential(space, { user: { did: OPERATOR, keypair: operatorKeypair }, @@ -788,15 +910,32 @@ describe("space routes: sync (S2-S4)", () => { ); expect(res.status).toBe(200); expect(res.headers.get("vary")).toContain("atproto-space-want-mac"); - const commit = commitFromJson(((await res.json()) as { commit: Record }).commit); + const commit = commitFromJson( + ((await res.json()) as { commit: Record }).commit, + ); expect(commit.repo).toBe(OPERATOR); expect(commit.space).toBe(space); - const mac = parseMacHeader(res.headers.get("atproto-space-mac") ?? undefined, COMMIT_MAC_TYPE); - expect(verifyCommit(commit, { space, repo: OPERATOR, sharedSecret: sharedSecret!, mac })).toBe(true); + const mac = parseMacHeader( + res.headers.get("atproto-space-mac") ?? undefined, + COMMIT_MAC_TYPE, + ); + expect( + verifyCommit(commit, { + space, + repo: OPERATOR, + sharedSecret: sharedSecret!, + mac, + }), + ).toBe(true); // The MAC is per request: another shared secret does not verify it. const other = await encapsulate(kemDid); expect( - verifyCommit(commit, { space, repo: OPERATOR, sharedSecret: other.sharedSecret, mac }), + verifyCommit(commit, { + space, + repo: OPERATOR, + sharedSecret: other.sharedSecret, + mac, + }), ).toBe(false); }); @@ -818,7 +957,12 @@ describe("space routes: sync (S2-S4)", () => { { mac: COMMIT_MAC_TYPE }, ); const body = (await res.json()) as { - ops: Array<{ collection: string; rkey: string; cid: string | null; prev: string | null }>; + ops: Array<{ + collection: string; + rkey: string; + cid: string | null; + prev: string | null; + }>; commit: Record; }; const hash = new LtHash(); @@ -828,8 +972,18 @@ describe("space routes: sync (S2-S4)", () => { } const commit = commitFromJson(body.commit); expect(hash.digest()).toEqual(commit.data); - const mac = parseMacHeader(res.headers.get("atproto-space-mac") ?? undefined, COMMIT_MAC_TYPE); - expect(verifyCommit(commit, { space, repo: OPERATOR, sharedSecret: sharedSecret!, mac })).toBe(true); + const mac = parseMacHeader( + res.headers.get("atproto-space-mac") ?? undefined, + COMMIT_MAC_TYPE, + ); + expect( + verifyCommit(commit, { + space, + repo: OPERATOR, + sharedSecret: sharedSecret!, + mac, + }), + ).toBe(true); }); it("streams a STAR archive the @atproto/space consumer verifies (S8)", async () => { @@ -837,8 +991,18 @@ describe("space routes: sync (S2-S4)", () => { // One collection NSID prefixes another: (collection, rkey) order and // byte order of the record path disagree, and the archive needs the // latter. - await createRecord(space, { $type: "app.bsky.feed.post", text: "1" }, "z", "app.bsky.feed"); - await createRecord(space, { $type: "app.bsky.feed.post", text: "2" }, "a", "app.bsky.feed.post"); + await createRecord( + space, + { $type: "app.bsky.feed.post", text: "1" }, + "z", + "app.bsky.feed", + ); + await createRecord( + space, + { $type: "app.bsky.feed.post", text: "2" }, + "a", + "app.bsky.feed.post", + ); for (let i = 0; i < 3; i++) { await createRecord(space, { $type: "app.bsky.feed.post", text: `n${i}` }); } @@ -851,7 +1015,10 @@ describe("space routes: sync (S2-S4)", () => { ); expect(res.status).toBe(200); expect(res.headers.get("content-type")).toBe("application/octet-stream"); - const mac = parseMacHeader(res.headers.get("atproto-space-mac") ?? undefined, COMMIT_MAC_TYPE); + const mac = parseMacHeader( + res.headers.get("atproto-space-mac") ?? undefined, + COMMIT_MAC_TYPE, + ); const bytes = new Uint8Array(await res.arrayBuffer()); const verified = await verifyRepoStarFull([bytes], { space, @@ -867,24 +1034,43 @@ describe("space routes: sync (S2-S4)", () => { const space = await createSpace(); await putMember(space, BOB); await putMember(space, CAROL); - const registrar = await obtainCredential(space, { user: { did: BOB, keypair: bobKeypair } }); + const registrar = await obtainCredential(space, { + user: { did: BOB, keypair: bobKeypair }, + }); const reg = await credentialRequest( "/xrpc/com.atproto.space.registerNotify", registrar.credential, registrar.key, - { method: "POST", body: { space, service: "did:web:syncer.test#atproto_space_syncer" } }, + { + method: "POST", + body: { space, service: "did:web:syncer.test#atproto_space_syncer" }, + }, ); expect(reg.res.status).toBe(200); const before = outbound.length; const t = Date.now(); - expect((await notifyWrite(space, BOB, bobKeypair, tidAt(t - 3000), repoData(1))).status).toBe(200); expect( - (await notifyWrite(space, CAROL, carolKeypair, tidAt(t - 2000), repoData(2), spaceHostAud(OPERATOR))) + (await notifyWrite(space, BOB, bobKeypair, tidAt(t - 3000), repoData(1))) .status, ).toBe(200); + expect( + ( + await notifyWrite( + space, + CAROL, + carolKeypair, + tidAt(t - 2000), + repoData(2), + spaceHostAud(OPERATOR), + ) + ).status, + ).toBe(200); // Stale: does not advance and is not fanned out again. - expect((await notifyWrite(space, BOB, bobKeypair, tidAt(t - 4000), repoData(9))).status).toBe(200); + expect( + (await notifyWrite(space, BOB, bobKeypair, tidAt(t - 4000), repoData(9))) + .status, + ).toBe(200); const list = await credentialRequest( `/xrpc/com.atproto.space.listRepos?space=${q(space)}&limit=1`, @@ -892,7 +1078,12 @@ describe("space routes: sync (S2-S4)", () => { registrar.key, ); const page1 = (await list.res.json()) as { - repos: Array<{ did: string; repoRev: string; data: { $bytes: string }; spaceRev: string }>; + repos: Array<{ + did: string; + repoRev: string; + data: { $bytes: string }; + spaceRev: string; + }>; cursor?: string; }; expect(page1.repos.map((r) => r.did)).toEqual([BOB]); @@ -925,25 +1116,63 @@ describe("space routes: sync (S2-S4)", () => { it("refuses unauthorised, mismatched and future notifyWrites", async () => { const space = await createSpace(); const now = Date.now(); - const stranger = await notifyWrite(space, BOB, bobKeypair, tidAt(now), repoData(1)); + const stranger = await notifyWrite( + space, + BOB, + bobKeypair, + tidAt(now), + repoData(1), + ); expect(stranger.status).toBe(403); await putMember(space, BOB, true, false); - const readOnly = await notifyWrite(space, BOB, bobKeypair, tidAt(now), repoData(1)); + const readOnly = await notifyWrite( + space, + BOB, + bobKeypair, + tidAt(now), + repoData(1), + ); expect(readOnly.status).toBe(403); const open = await createSpace({ ...MEMBERSPACE, publicWrite: true }); - expect((await notifyWrite(open, BOB, bobKeypair, tidAt(now), repoData(1))).status).toBe(200); - const future = await notifyWrite(open, BOB, bobKeypair, tidAt(now + 10 * 60_000), repoData(1)); + expect( + (await notifyWrite(open, BOB, bobKeypair, tidAt(now), repoData(1))) + .status, + ).toBe(200); + const future = await notifyWrite( + open, + BOB, + bobKeypair, + tidAt(now + 10 * 60_000), + repoData(1), + ); expect(future.status).toBe(400); expect(await errorOf(future)).toBe("FutureRev"); - const wrongAud = await notifyWrite(open, BOB, bobKeypair, tidAt(now + 1), repoData(1), BOB); + const wrongAud = await notifyWrite( + open, + BOB, + bobKeypair, + tidAt(now + 1), + repoData(1), + BOB, + ); expect(wrongAud.status).toBe(403); - const token = await serviceJwt(CAROL, OPERATOR, "com.atproto.space.notifyWrite", carolKeypair); + const token = await serviceJwt( + CAROL, + OPERATOR, + "com.atproto.space.notifyWrite", + carolKeypair, + ); const impersonation = await post( "/xrpc/com.atproto.space.notifyWrite", - { space: open, repo: BOB, repoRev: tidAt(now + 2), data: { $bytes: "AA==" } }, + { + space: open, + repo: BOB, + repoRev: tidAt(now + 2), + data: { $bytes: "AA==" }, + }, { Authorization: `Bearer ${token}` }, ); expect(impersonation.status).toBe(403); @@ -966,17 +1195,28 @@ describe("space routes: sync (S2-S4)", () => { const t = Date.now(); await notifyWrite(space, BOB, bobKeypair, tidAt(t - 2000), repoData(1)); await notifyWrite(space, CAROL, carolKeypair, tidAt(t - 1000), repoData(2)); - const { credential, key } = await obtainCredential(space, { user: { did: BOB, keypair: bobKeypair } }); + const { credential, key } = await obtainCredential(space, { + user: { did: BOB, keypair: bobKeypair }, + }); const writers = async () => { const { res } = await credentialRequest( `/xrpc/com.atproto.space.listRepos?space=${q(space)}`, credential, key, ); - return ((await res.json()) as { repos: Array<{ did: string }> }).repos.map((r) => r.did); + return ( + (await res.json()) as { repos: Array<{ did: string }> } + ).repos.map((r) => r.did); }; expect((await writers()).sort()).toEqual([BOB, CAROL].sort()); - expect((await post("/xrpc/com.atproto.space.removeWriter", { space, did: CAROL })).status).toBe(200); + expect( + ( + await post("/xrpc/com.atproto.space.removeWriter", { + space, + did: CAROL, + }) + ).status, + ).toBe(200); expect(await writers()).toEqual([BOB]); await putMember(space, BOB, true, false); expect(await writers()).toEqual([]); @@ -995,7 +1235,9 @@ describe("space routes: sync (S2-S4)", () => { post( "/xrpc/com.atproto.space.notifySpaceDeleted", { space: foreign }, - { Authorization: `Bearer ${await serviceJwt(iss, aud, "com.atproto.space.notifySpaceDeleted", keypair)}` }, + { + Authorization: `Bearer ${await serviceJwt(iss, aud, "com.atproto.space.notifySpaceDeleted", keypair)}`, + }, ); expect((await send("did:web:someone-else.test")).status).toBe(403); expect((await send(OPERATOR, CAROL, carolKeypair)).status).toBe(403); @@ -1019,13 +1261,24 @@ describe("space routes: sync (S2-S4)", () => { }); await vi.waitFor(() => expect(outbound.length).toBeGreaterThan(before)); const call = outbound[outbound.length - 1]!; - expect(call.url).toBe("https://bob.test/xrpc/com.atproto.space.notifyWrite"); + expect(call.url).toBe( + "https://bob.test/xrpc/com.atproto.space.notifyWrite", + ); const body = JSON.parse(String(call.init!.body)) as Record; - expect(Object.keys(body).sort()).toEqual(["data", "repo", "repoRev", "space"]); + expect(Object.keys(body).sort()).toEqual([ + "data", + "repo", + "repoRev", + "space", + ]); expect(body.repo).toBe(OPERATOR); expect((await stub.rpcStatus()).queuedNotifications).toBe(0); - setOutboundResponse((url) => (url.includes("notifyWrite") ? new Response("down", { status: 503 }) : null)); + setOutboundResponse((url) => + url.includes("notifyWrite") + ? new Response("down", { status: 503 }) + : null, + ); try { for (const rkey of ["w2", "w3"]) { const count = outbound.length; @@ -1094,13 +1347,19 @@ describe("space routes: lifecycle and management", () => { const space = await createSpace({ ...MEMBERSPACE, publicRead: true }); await createRecord(space, { $type: "app.bsky.feed.post", text: "x" }, "x"); await putMember(space, BOB); - expect((await post("/xrpc/com.atproto.space.deleteSpace", { space })).status).toBe(200); - expect((await post("/xrpc/com.atproto.space.deleteSpace", { space })).status).toBe(200); + expect( + (await post("/xrpc/com.atproto.space.deleteSpace", { space })).status, + ).toBe(200); + expect( + (await post("/xrpc/com.atproto.space.deleteSpace", { space })).status, + ).toBe(200); const read = await get( `/xrpc/com.atproto.space.getRecord?space=${q(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=x`, ); expect(await errorOf(read)).toBe("SpaceNotFound"); - const withToken = await obtainCredential(space, { user: { did: BOB, keypair: bobKeypair } }); + const withToken = await obtainCredential(space, { + user: { did: BOB, keypair: bobKeypair }, + }); expect((withToken.body as { error: string }).error).toBe("SpaceDeleted"); const anon = await obtainCredential(space); expect((anon.body as { error: string }).error).toBe("SpaceDeleted"); @@ -1110,7 +1369,9 @@ describe("space routes: lifecycle and management", () => { const space = await createSpace(); await putMember(space, BOB); const getSpace = async () => - (await (await get(`/xrpc/com.atproto.space.getSpace?space=${q(space)}`)).json()) as { + (await ( + await get(`/xrpc/com.atproto.space.getSpace?space=${q(space)}`) + ).json()) as { uri: string; policy: Record; }; @@ -1123,14 +1384,18 @@ describe("space routes: lifecycle and management", () => { }); expect( - (await post("/xrpc/com.atproto.space.updateSpace", { - space, - policy: { ...MEMBERSPACE, publicRead: true, extra: "dropped" }, - })).status, + ( + await post("/xrpc/com.atproto.space.updateSpace", { + space, + policy: { ...MEMBERSPACE, publicRead: true, extra: "dropped" }, + }) + ).status, ).toBe(200); expect((await getSpace()).policy.publicRead).toBe(true); expect((await getSpace()).policy.extra).toBeUndefined(); - const members = await get(`/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`); + const members = await get( + `/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`, + ); expect(((await members.json()) as { members: unknown[] }).members).toEqual([ { did: BOB, read: true, write: true }, ]); @@ -1139,12 +1404,23 @@ describe("space routes: lifecycle and management", () => { space, policy: { $type: "com.atproto.personalspace.policy" }, }); - expect((await getSpace()).policy).toEqual({ $type: "com.atproto.personalspace.policy" }); - const mismatch = await get(`/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`); + expect((await getSpace()).policy).toEqual({ + $type: "com.atproto.personalspace.policy", + }); + const mismatch = await get( + `/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`, + ); expect(await errorOf(mismatch)).toBe("PolicyMismatch"); - await post("/xrpc/com.atproto.space.updateSpace", { space, policy: MEMBERSPACE }); - const after = await get(`/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`); - expect(((await after.json()) as { members: unknown[] }).members).toEqual([]); + await post("/xrpc/com.atproto.space.updateSpace", { + space, + policy: MEMBERSPACE, + }); + const after = await get( + `/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`, + ); + expect(((await after.json()) as { members: unknown[] }).members).toEqual( + [], + ); }); it("getSpace is the owner's, by session only", async () => { @@ -1174,7 +1450,11 @@ describe("space routes: lifecycle and management", () => { { Authorization: manager }, ); expect(member.status).toBe(200); - const del = await post("/xrpc/com.atproto.space.deleteSpace", { space }, { Authorization: manager }); + const del = await post( + "/xrpc/com.atproto.space.deleteSpace", + { space }, + { Authorization: manager }, + ); expect(del.status).toBe(403); }); @@ -1202,20 +1482,31 @@ describe("space routes: lifecycle and management", () => { space: `at://${BOB}/space/app.bsky.group/x`, policy: MEMBERSPACE, }); - expect(notOwner.status).toBe(404); + expect(notOwner.status).toBe(403); + expect(await errorOf(notOwner)).toBe("NotSpaceOwner"); }); it("publishes the policy and member list into the authority's repo", async () => { - const space = await createSpace({ ...MEMBERSPACE, publishPolicy: true, publishMembers: true }); + const space = await createSpace({ + ...MEMBERSPACE, + publishPolicy: true, + publishMembers: true, + }); await putMember(space, BOB, true, false); await putMember(space, CAROL); const list = async () => { const res = await get( `/xrpc/com.atproto.space.listRecords?space=${q(space)}&repo=${OPERATOR}&reverse=true`, ); - return ((await res.json()) as { - records: Array<{ collection: string; rkey: string; value: Record }>; - }).records; + return ( + (await res.json()) as { + records: Array<{ + collection: string; + rkey: string; + value: Record; + }>; + } + ).records; }; let records = await list(); expect(records.map((r) => `${r.collection}/${r.rkey}`)).toEqual([ @@ -1228,28 +1519,49 @@ describe("space routes: lifecycle and management", () => { read: true, write: false, }); - expect((records[2]!.value.policy as { publishMembers: boolean }).publishMembers).toBe(true); + expect( + (records[2]!.value.policy as { publishMembers: boolean }).publishMembers, + ).toBe(true); - await post("/xrpc/com.atproto.memberspace.removeMember", { space, did: CAROL }); + await post("/xrpc/com.atproto.memberspace.removeMember", { + space, + did: CAROL, + }); await post("/xrpc/com.atproto.space.updateSpace", { space, policy: { ...MEMBERSPACE, publishPolicy: true }, }); records = await list(); - expect(records.map((r) => r.collection)).toEqual(["com.atproto.space.policy"]); + expect(records.map((r) => r.collection)).toEqual([ + "com.atproto.space.policy", + ]); }); it("round-trips a space through exportSpaceMeta/getRepo and their imports", async () => { const space = await createSpace({ ...MEMBERSPACE, publishPolicy: true }); await putMember(space, BOB, true, false); await putMember(space, CAROL); - await notifyWrite(space, CAROL, carolKeypair, tidAt(Date.now() - 1000), repoData(7)); - await createRecord(space, { $type: "app.bsky.feed.post", text: "keep me" }, "k"); + await notifyWrite( + space, + CAROL, + carolKeypair, + tidAt(Date.now() - 1000), + repoData(7), + ); + await createRecord( + space, + { $type: "app.bsky.feed.post", text: "keep me" }, + "k", + ); - const meta = await get(`/xrpc/com.atproto.space.exportSpaceMeta?space=${q(space)}`); + const meta = await get( + `/xrpc/com.atproto.space.exportSpaceMeta?space=${q(space)}`, + ); expect(meta.status).toBe(200); const metaBytes = new Uint8Array(await meta.arrayBuffer()); - const repo = await get(`/xrpc/com.atproto.space.getRepo?space=${q(space)}&repo=${OPERATOR}`); + const repo = await get( + `/xrpc/com.atproto.space.getRepo?space=${q(space)}&repo=${OPERATOR}`, + ); const repoBytes = new Uint8Array(await repo.arrayBuffer()); await post("/xrpc/com.atproto.space.deleteSpace", { space }); @@ -1262,11 +1574,14 @@ describe("space routes: lifecycle and management", () => { }); expect(await errorOf(early)).toBe("SpaceNotFound"); - const importMeta = await app.request("/xrpc/com.atproto.space.importSpaceMeta", { - method: "POST", - headers: { ...SESSION, "Content-Type": "application/octet-stream" }, - body: metaBytes, - }); + const importMeta = await app.request( + "/xrpc/com.atproto.space.importSpaceMeta", + { + method: "POST", + headers: { ...SESSION, "Content-Type": "application/octet-stream" }, + body: metaBytes, + }, + ); expect(importMeta.status).toBe(200); const importRepo = await app.request("/xrpc/com.atproto.space.importRepo", { method: "POST", @@ -1275,7 +1590,9 @@ describe("space routes: lifecycle and management", () => { }); expect(importRepo.status).toBe(200); - const members = await get(`/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`); + const members = await get( + `/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`, + ); expect(((await members.json()) as { members: unknown[] }).members).toEqual([ { did: BOB, read: true, write: false }, { did: CAROL, read: true, write: true }, @@ -1283,14 +1600,20 @@ describe("space routes: lifecycle and management", () => { const record = await get( `/xrpc/com.atproto.space.getRecord?space=${q(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=k`, ); - expect(((await record.json()) as { value: { text: string } }).value.text).toBe("keep me"); - const { credential, key } = await obtainCredential(space, { user: { did: CAROL, keypair: carolKeypair } }); + expect( + ((await record.json()) as { value: { text: string } }).value.text, + ).toBe("keep me"); + const { credential, key } = await obtainCredential(space, { + user: { did: CAROL, keypair: carolKeypair }, + }); const { res } = await credentialRequest( `/xrpc/com.atproto.space.listRepos?space=${q(space)}`, credential, key, ); - const writers = ((await res.json()) as { repos: Array<{ did: string }> }).repos.map((r) => r.did); + const writers = ( + (await res.json()) as { repos: Array<{ did: string }> } + ).repos.map((r) => r.did); expect(writers).toContain(CAROL); }); @@ -1300,12 +1623,26 @@ describe("space routes: lifecycle and management", () => { const bytes = encode(record); const { cidForCbor } = await import("@atproto/lex-data"); const cid = await cidForCbor(bytes); - const data = new LtHash().add(`app.bsky.feed.post/r/${cid.toString()}`).digest(); + const data = new LtHash() + .add(`app.bsky.feed.post/r/${cid.toString()}`) + .digest(); const archive = async (repo: string) => { const chunks: Uint8Array[] = []; for await (const chunk of serializeRepo( - { ver: 1, repo: repo as never, space: space as never, rev: tidAt(Date.now()), data }, - [{ collection: "app.bsky.feed.post" as never, rkey: "r" as never, bytes }], + { + ver: 1, + repo: repo as never, + space: space as never, + rev: tidAt(Date.now()), + data, + }, + [ + { + collection: "app.bsky.feed.post" as never, + rkey: "r" as never, + bytes, + }, + ], )) { chunks.push(chunk); } diff --git a/packages/spaces/test/space-do.test.ts b/packages/spaces/test/space-do.test.ts index 4877075..83b2093 100644 --- a/packages/spaces/test/space-do.test.ts +++ b/packages/spaces/test/space-do.test.ts @@ -151,7 +151,11 @@ describe("SpaceDurableObject", () => { await stub.rpcApplyWrites([w]); const state = await stub.rpcGetRepoState(); - const commit = buildCommit({ spaceUri: uri, repo: AUTHORITY, state: state! }); + const commit = buildCommit({ + spaceUri: uri, + repo: AUTHORITY, + state: state!, + }); const kemDid = (await P256Keypair.import(TEST_KEM_KEY)).did(); const { keyShare, sharedSecret } = await encapsulate(kemDid); const { formatWantMacHeader } = await import("@atproto/space"); @@ -163,7 +167,12 @@ describe("SpaceDurableObject", () => { }); const mac = computeCommitMac(hostSecret!, commit as never); expect( - verifyCommit(commit as never, { space: uri, repo: AUTHORITY, sharedSecret, mac }), + verifyCommit(commit as never, { + space: uri, + repo: AUTHORITY, + sharedSecret, + mac, + }), ).toBe(true); }); @@ -176,7 +185,9 @@ describe("SpaceDurableObject", () => { ]); const page = await stub.rpcListRecordsByPath({ limit: 1 }); // "app.bsky.feed.post/a" < "app.bsky.feed/z" byte-wise ('.' < '/'). - expect(page.records.map((r) => r.collection)).toEqual(["app.bsky.feed.post"]); + expect(page.records.map((r) => r.collection)).toEqual([ + "app.bsky.feed.post", + ]); expect(page.hasMore).toBe(true); const next = await stub.rpcListRecordsByPath({ afterPath: "app.bsky.feed.post/a", @@ -355,31 +366,56 @@ describe("SpaceDurableObject", () => { const { uri, stub } = freshSpace(); await initSpace(stub, uri); const data = new Uint8Array(32).fill(7); - const first = await stub.rpcRecordWriter("did:web:bob.test", "3kzzzzzzzzzzz", data); + const first = await stub.rpcRecordWriter( + "did:web:bob.test", + "3kzzzzzzzzzzz", + data, + ); expect(first?.spaceRev).toMatch(/^[2-7a-z]{13}$/); expect(first?.prevSpaceRev).toBeUndefined(); - const second = await stub.rpcRecordWriter("did:web:carol.test", "3kzzzzzzzzzzz", data); + const second = await stub.rpcRecordWriter( + "did:web:carol.test", + "3kzzzzzzzzzzz", + data, + ); expect(second?.prevSpaceRev).toBe(first?.spaceRev); expect(second!.spaceRev > first!.spaceRev).toBe(true); // A delayed or replayed notification with an older or equal rev never // rolls the writer set backwards, and reports that nothing advanced. - expect(await stub.rpcRecordWriter("did:web:bob.test", "3kaaaaaaaaaaa", data)).toBe(null); - expect(await stub.rpcRecordWriter("did:web:bob.test", "3kzzzzzzzzzzz", data)).toBe(null); + expect( + await stub.rpcRecordWriter("did:web:bob.test", "3kaaaaaaaaaaa", data), + ).toBe(null); + expect( + await stub.rpcRecordWriter("did:web:bob.test", "3kzzzzzzzzzzz", data), + ).toBe(null); // Bob advances again and moves to the end of the sequence. - const third = await stub.rpcRecordWriter("did:web:bob.test", "3lzzzzzzzzzzz", data); + const third = await stub.rpcRecordWriter( + "did:web:bob.test", + "3lzzzzzzzzzzz", + data, + ); expect(third?.prevSpaceRev).toBe(second?.spaceRev); const all = await stub.rpcListWriters({ limit: 10 }); - expect(all.map((w) => w.did)).toEqual(["did:web:carol.test", "did:web:bob.test"]); - expect(all[1]).toMatchObject({ repoRev: "3lzzzzzzzzzzz", spaceRev: third!.spaceRev }); - const after = await stub.rpcListWriters({ limit: 10, cursor: all[0]!.spaceRev }); + expect(all.map((w) => w.did)).toEqual([ + "did:web:carol.test", + "did:web:bob.test", + ]); + expect(all[1]).toMatchObject({ + repoRev: "3lzzzzzzzzzzz", + spaceRev: third!.spaceRev, + }); + const after = await stub.rpcListWriters({ + limit: 10, + cursor: all[0]!.spaceRev, + }); expect(after.map((w) => w.did)).toEqual(["did:web:bob.test"]); await stub.rpcRemoveWriter("did:web:bob.test"); - expect((await stub.rpcListWriters({ limit: 10 })).map((w) => w.did)).toEqual([ - "did:web:carol.test", - ]); + expect( + (await stub.rpcListWriters({ limit: 10 })).map((w) => w.did), + ).toEqual(["did:web:carol.test"]); // Revoking write access drops a member from the writer set. await stub.rpcPutMember("did:web:carol.test", { read: true, write: false }); expect(await stub.rpcListWriters({ limit: 10 })).toEqual([]); @@ -388,7 +424,10 @@ describe("SpaceDurableObject", () => { it("registers and unregisters notification services", async () => { const { uri, stub } = freshSpace(); await initSpace(stub, uri); - const reg = await stub.rpcRegisterNotify("did:web:syncer.test", "https://syncer.test"); + const reg = await stub.rpcRegisterNotify( + "did:web:syncer.test", + "https://syncer.test", + ); expect(Date.parse(reg.expiresAt)).toBeGreaterThan(Date.now()); expect(await stub.rpcGetActiveRegistrations()).toEqual([ { @@ -407,15 +446,21 @@ describe("SpaceDurableObject", () => { const { uri, stub } = freshSpace(); await initSpace(stub, uri); await stub.rpcPutMember("did:web:bob.test", { read: true, write: true }); - expect(await stub.rpcUpdatePolicy({ ...MEMBERSPACE, publicRead: true })).toBe(null); - expect((await stub.rpcGetAuthorityState()).policy).toMatchObject({ publicRead: true }); + expect( + await stub.rpcUpdatePolicy({ ...MEMBERSPACE, publicRead: true }), + ).toBe(null); + expect((await stub.rpcGetAuthorityState()).policy).toMatchObject({ + publicRead: true, + }); expect(await stub.rpcGetMember("did:web:bob.test")).not.toBe(null); await stub.rpcUpdatePolicy({ $type: "com.atproto.managedspace.policy", managingApp: "did:web:app.test#svc", publishPolicy: false, }); - expect(await rpcError(stub, (i) => i.rpcGetMember("did:web:bob.test"))).toBe(""); + expect( + await rpcError(stub, (i) => i.rpcGetMember("did:web:bob.test")), + ).toBe(""); expect(await stub.rpcGetMember("did:web:bob.test")).toBe(null); expect(await rpcError(stub, (i) => i.rpcListMembers({ limit: 1 }))).toMatch( /PolicyMismatch/, @@ -433,10 +478,14 @@ describe("SpaceDurableObject", () => { policy: { ...MEMBERSPACE, publishPolicy: true }, }); expect(commit?.rev).toMatch(/^[2-7a-z]{13}$/); - expect(await stub.rpcGetRecord("com.atproto.space.policy", "self")).not.toBe(null); + expect( + await stub.rpcGetRecord("com.atproto.space.policy", "self"), + ).not.toBe(null); const withdrawn = await stub.rpcUpdatePolicy(MEMBERSPACE); expect(withdrawn?.rev && withdrawn.rev > commit!.rev).toBe(true); - expect(await stub.rpcGetRecord("com.atproto.space.policy", "self")).toBe(null); + expect(await stub.rpcGetRecord("com.atproto.space.policy", "self")).toBe( + null, + ); }); it("clears records, keeping the given collections", async () => { @@ -444,11 +493,16 @@ describe("SpaceDurableObject", () => { await initSpace(stub, uri); await stub.rpcApplyWrites([ write("create", "a", { n: 1 }), - { ...write("create", "self", { n: 2 }), collection: "com.atproto.space.policy" }, + { + ...write("create", "self", { n: 2 }), + collection: "com.atproto.space.policy", + }, ]); const cleared = await stub.rpcClearRecords(["com.atproto.space.policy"]); const remaining = await stub.rpcListRecords({ limit: 10 }); - expect(remaining.records.map((r) => r.collection)).toEqual(["com.atproto.space.policy"]); + expect(remaining.records.map((r) => r.collection)).toEqual([ + "com.atproto.space.policy", + ]); const expected = new LtHash().add( `com.atproto.space.policy/self/${remaining.records[0]!.cid}`, ); @@ -461,7 +515,9 @@ describe("SpaceDurableObject", () => { it("imports a repo wholesale at a new rev", async () => { const { uri, stub } = freshSpace(); await initSpace(stub, uri); - const before = await stub.rpcApplyWrites([write("create", "old", { n: 1 })]); + const before = await stub.rpcApplyWrites([ + write("create", "old", { n: 1 }), + ]); const imported = write("create", "new", { n: 2 }, ["bafkblob"]); const result = await stub.rpcImportRepo([ { @@ -507,14 +563,16 @@ describe("SpaceDurableObject", () => { ), ).toMatch(/SpaceAlreadyExists/); - await stub.rpcApplyWrites([write("create", "gone", { $type: "app.bsky.feed.post" })]); + await stub.rpcApplyWrites([ + write("create", "gone", { $type: "app.bsky.feed.post" }), + ]); const del = await stub.rpcDeleteSpace(); expect(del.registrations).toEqual([]); // Tombstone: reads fail SpaceNotFound, authority state shows deleted. - expect(await rpcError(stub, (i) => i.rpcGetRecord("app.bsky.feed.post", "gone"))).toMatch( - /SpaceNotFound/, - ); + expect( + await rpcError(stub, (i) => i.rpcGetRecord("app.bsky.feed.post", "gone")), + ).toMatch(/SpaceNotFound/); const state = await stub.rpcGetAuthorityState(); expect(state.meta?.deletedAt).not.toBe(null); expect(state.policy).toBe(null); @@ -643,7 +701,9 @@ describe("SpaceDurableObject", () => { expect((await instance.rpcStatus()).queuedNotifications).toBe(0); // A passed deadline drops the item undelivered. - await instance.rpcEnqueueNotify([{ ...item("4"), deadline: Date.now() - 1 }]); + await instance.rpcEnqueueNotify([ + { ...item("4"), deadline: Date.now() - 1 }, + ]); await instance.alarm(); expect((await instance.rpcStatus()).queuedNotifications).toBe(0); }); diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index c284438..2ecd981 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -362,9 +362,6 @@ importers: '@atproto/crypto': specifier: 0.0.0-spaces-alpha-20261105160032 version: 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-cbor': - specifier: 0.0.0-spaces-alpha-20261105160032 - version: 0.0.0-spaces-alpha-20261105160032 '@atproto/lex-data': specifier: 0.0.0-spaces-alpha-20261105160032 version: 0.0.0-spaces-alpha-20261105160032 @@ -441,12 +438,6 @@ importers: '@atproto/space': specifier: 0.0.0-spaces-alpha-20261105160032 version: 0.0.0-spaces-alpha-20261105160032 - '@atproto/star': - specifier: 0.0.0-spaces-alpha-20261105160032 - version: 0.0.0-spaces-alpha-20261105160032 - '@atproto/syntax': - specifier: 0.0.0-spaces-alpha-20261105160032 - version: 0.0.0-spaces-alpha-20261105160032 '@cloudflare/vitest-pool-workers': specifier: ^0.16.9 version: 0.16.9(@cloudflare/workers-types@4.20260524.1)(@vitest/runner@4.1.7)(@vitest/snapshot@4.1.7)(vitest@4.1.0-beta.1(@opentelemetry/api@1.9.1)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0)) From bd13253b075f1738cc4f82b17219dd5e67b00a3e Mon Sep 17 00:00:00 2001 From: Claude Date: Mon, 9 Nov 2026 09:10:36 +0000 Subject: [PATCH 09/16] docs(plans): record the 1105 conformance results Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LZ7qcQNQoiA6a23woGC7tB --- plans/in-progress/spaces.md | 24 +++++++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) diff --git a/plans/in-progress/spaces.md b/plans/in-progress/spaces.md index 16fa4e6..8e5bc62 100644 --- a/plans/in-progress/spaces.md +++ b/plans/in-progress/spaces.md @@ -86,6 +86,27 @@ upstream builds landed in between and the protocol changed substantially: - **Schema version 2**: existing space DOs refuse until `pds spaces reset`, per the alpha policy. +### Conformance at 1105 + +The suite grew from 24 to 92 checks (87 must, 4 should, 1 info), with +coverage requiring zero gaps against the vendored lexicons (the only +exemptions are the admin-only `RepoTakendown` / `RepoSuspended` / +`RepoDeactivated` errors). Results on 2026-11-09: + +- **Reference (matrix):** 89 pass, 3 pinned divergences, nothing + skipped: `writes.delete-in-missing-space` (its deleteRecord answers 200 + before checking the space), `space.reads-after-delete-not-found` (reads + of a deleted space don't answer `SpaceNotFound`) and + `credential.garbage-attestation-refused` (a malformed attestation is a + 500). See the matrix README. +- **Cirrus space routes (in-process):** every runnable must and should + check passes, the three above included. Only the `pds-blobs` and + `pds-delegation` checks skip; the PDS run covers them. +- Running it found four Cirrus bugs, all fixed: getBlob's order of + checks, `NotSpaceOwner` on foreign spaces, `listSpaces` living outside + the engine, and the PDS fetching its own DID document to resolve its own + `#atproto_pds`. + ### Packaging: the alpha is bundled `@atproto/space@1105` depends on the alpha `lex-cbor` / `lex-data` / @@ -134,7 +155,8 @@ move to a new one (the update loop from the space-conformance spec, #228): ## Not done / next -- **Interop runs** against the reference alpha Docker image and rsky. +- **Interop runs** against rsky and a live deployment. The reference is + covered in-process by the conformance matrix (above). bulletin.my's S1 flow is verified live against pds.mk.gg (2026-08-29): OAuth with space: scopes, board space creation, delegation → credential exchange, reads, registerNotify and listRepos all work. From e5cefe34fc6c7cb11e9e2dc533546fc4cc76c043 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 04:20:23 +0000 Subject: [PATCH 10/16] chore(spaces): bump spaces alpha to 20261112204144 and re-vendor lexicons Pins the 2026-11-12 alpha, cut from permissioned-data-alpha@b27a037 (the 20261112203312 build has identical code). Re-vendors the space lexicons: getSpaceCredential becomes authorizeSpaceSync, listRepos listWriters, notifyWrite notifyRepoUpdate, putMember/removeMember the batched putMembers/removeMembers and checkUserAccess checkAccess; registerNotify, unregisterNotify and notifySpaceDeleted give way to confirmRegistration and notifySpaceUpdate. @atproto/lex-rpc and @atproto/oauth-resolver now publish a corrupt 0.0.0-stage, and bsync and lex-password-session a broken bare 0.0.0, all outranking the alpha range; they join the workspace overrides. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LZ7qcQNQoiA6a23woGC7tB --- packages/oauth-provider/package.json | 2 +- packages/pds/package.json | 2 +- .../space-conformance-matrix/package.json | 2 +- .../space-conformance/lexicons/MANIFEST.json | 4 +- .../lexicons/managedspace/checkAccess.json | 44 + .../managedspace/checkUserAccess.json | 48 - .../lexicons/managedspace/policy.json | 6 +- .../lexicons/memberspace/defs.json | 22 + .../lexicons/memberspace/listMembers.json | 34 +- .../lexicons/memberspace/member.json | 8 +- .../lexicons/memberspace/policy.json | 14 +- .../lexicons/memberspace/putMember.json | 49 - .../lexicons/memberspace/putMembers.json | 43 + .../lexicons/memberspace/removeMember.json | 41 - .../lexicons/memberspace/removeMembers.json | 43 + .../lexicons/personalspace/policy.json | 2 +- .../lexicons/space/applyWrites.json | 17 +- .../lexicons/space/authorizeSpaceSync.json | 109 + .../lexicons/space/clearRecords.json | 8 +- .../lexicons/space/confirmRegistration.json | 44 + .../lexicons/space/createRecord.json | 21 +- .../lexicons/space/createSpace.json | 22 +- .../lexicons/space/defs.json | 62 +- .../lexicons/space/deleteRecord.json | 14 +- .../lexicons/space/deleteSpace.json | 7 +- .../lexicons/space/exportSpaceMeta.json | 9 +- .../lexicons/space/getBlob.json | 11 +- .../lexicons/space/getDelegationToken.json | 8 +- .../lexicons/space/getLatestCommit.json | 15 +- .../lexicons/space/getRecord.json | 18 +- .../lexicons/space/getRepo.json | 14 +- .../lexicons/space/getSpace.json | 16 +- .../lexicons/space/getSpaceCredential.json | 84 - .../lexicons/space/importRepo.json | 14 +- .../lexicons/space/importSpaceMeta.json | 13 +- .../lexicons/space/listBlobs.json | 13 +- .../lexicons/space/listRecords.json | 26 +- .../lexicons/space/listRepoOps.json | 44 +- .../lexicons/space/listRepos.json | 91 - .../lexicons/space/listSpaces.json | 44 +- .../lexicons/space/listWriters.json | 66 + ...ked.json => notifyCredentialsRevoked.json} | 9 +- .../lexicons/space/notifyRepoUpdate.json | 43 + .../lexicons/space/notifySpaceDeleted.json | 24 - .../lexicons/space/notifySpaceUpdate.json | 53 + .../lexicons/space/notifyWrite.json | 57 - .../lexicons/space/policy.json | 4 +- .../lexicons/space/putRecord.json | 21 +- .../lexicons/space/registerNotify.json | 49 - .../lexicons/space/removeWriter.json | 14 +- .../lexicons/space/unregisterNotify.json | 29 - .../lexicons/space/updateSpace.json | 12 +- packages/space-conformance/package.json | 8 +- packages/space-conformance/src/lexicons.ts | 40 +- packages/spaces/package.json | 10 +- pnpm-lock.yaml | 2891 ++++++++--------- pnpm-workspace.yaml | 81 +- 57 files changed, 2182 insertions(+), 2317 deletions(-) create mode 100644 packages/space-conformance/lexicons/managedspace/checkAccess.json delete mode 100644 packages/space-conformance/lexicons/managedspace/checkUserAccess.json create mode 100644 packages/space-conformance/lexicons/memberspace/defs.json delete mode 100644 packages/space-conformance/lexicons/memberspace/putMember.json create mode 100644 packages/space-conformance/lexicons/memberspace/putMembers.json delete mode 100644 packages/space-conformance/lexicons/memberspace/removeMember.json create mode 100644 packages/space-conformance/lexicons/memberspace/removeMembers.json create mode 100644 packages/space-conformance/lexicons/space/authorizeSpaceSync.json create mode 100644 packages/space-conformance/lexicons/space/confirmRegistration.json delete mode 100644 packages/space-conformance/lexicons/space/getSpaceCredential.json delete mode 100644 packages/space-conformance/lexicons/space/listRepos.json create mode 100644 packages/space-conformance/lexicons/space/listWriters.json rename packages/space-conformance/lexicons/space/{notifyCredentialRevoked.json => notifyCredentialsRevoked.json} (58%) create mode 100644 packages/space-conformance/lexicons/space/notifyRepoUpdate.json delete mode 100644 packages/space-conformance/lexicons/space/notifySpaceDeleted.json create mode 100644 packages/space-conformance/lexicons/space/notifySpaceUpdate.json delete mode 100644 packages/space-conformance/lexicons/space/notifyWrite.json delete mode 100644 packages/space-conformance/lexicons/space/registerNotify.json delete mode 100644 packages/space-conformance/lexicons/space/unregisterNotify.json diff --git a/packages/oauth-provider/package.json b/packages/oauth-provider/package.json index 3ad1dec..97f67d0 100644 --- a/packages/oauth-provider/package.json +++ b/packages/oauth-provider/package.json @@ -26,7 +26,7 @@ "@atcute/lexicon-resolver": "^0.1.6", "@atcute/lexicons": "^1.2.6", "@atcute/repo": "^0.1.1", - "@atproto/oauth-scopes": "0.0.0-spaces-alpha-20261105160032", + "@atproto/oauth-scopes": "0.0.0-spaces-alpha-20261112204144", "@atproto/oauth-types": "^0.6.3", "@atproto/syntax": "^0.4.2", "jose": "^6.1.3" diff --git a/packages/pds/package.json b/packages/pds/package.json index 2ed1f8c..f1b19dc 100644 --- a/packages/pds/package.json +++ b/packages/pds/package.json @@ -50,7 +50,7 @@ "devDependencies": { "@arethetypeswrong/cli": "^0.18.2", "@atproto/api": "^0.18.9", - "@atproto/space": "0.0.0-spaces-alpha-20261105160032", + "@atproto/space": "0.0.0-spaces-alpha-20261112204144", "@cloudflare/vite-plugin": "^1.17.0", "@cloudflare/vitest-pool-workers": "^0.16.9", "@cloudflare/workers-types": "^4.20260524.1", diff --git a/packages/space-conformance-matrix/package.json b/packages/space-conformance-matrix/package.json index e8b5415..4dbd2e6 100644 --- a/packages/space-conformance-matrix/package.json +++ b/packages/space-conformance-matrix/package.json @@ -9,7 +9,7 @@ "check": "tsc --noEmit -p tsconfig.json" }, "devDependencies": { - "@atproto/dev-env": "0.0.0-spaces-alpha-20261105160032", + "@atproto/dev-env": "0.0.0-spaces-alpha-20261112204144", "@getcirrus/space-conformance": "workspace:*", "typescript": "^5.9.3", "vitest": "4.1.0-beta.1" diff --git a/packages/space-conformance/lexicons/MANIFEST.json b/packages/space-conformance/lexicons/MANIFEST.json index 891a6b5..2c7a0fe 100644 --- a/packages/space-conformance/lexicons/MANIFEST.json +++ b/packages/space-conformance/lexicons/MANIFEST.json @@ -1,7 +1,7 @@ { "source": "https://github.com/bluesky-social/atproto", "branch": "permissioned-data-alpha", - "commit": "704b9e2ac", - "vendoredAt": "2026-11-09", + "commit": "b27a037c7", + "vendoredAt": "2026-11-13", "note": "Vendored verbatim from lexicons/com/atproto/{space,memberspace,personalspace,managedspace} by scripts/vendor-lexicons.mjs. A diff here identifies affected checks via their citations." } diff --git a/packages/space-conformance/lexicons/managedspace/checkAccess.json b/packages/space-conformance/lexicons/managedspace/checkAccess.json new file mode 100644 index 0000000..dfe5f2d --- /dev/null +++ b/packages/space-conformance/lexicons/managedspace/checkAccess.json @@ -0,0 +1,44 @@ +{ + "lexicon": 1, + "id": "com.atproto.managedspace.checkAccess", + "defs": { + "main": { + "type": "query", + "description": "Check an account's read and write access to a managed space. Called by the space host, implemented by the space's managing app. Requires service auth.", + "parameters": { + "type": "params", + "required": ["space"], + "properties": { + "space": { + "type": "string", + "format": "space-ref" + }, + "repo": { + "type": "string", + "format": "did" + }, + "clientId": { + "type": "string", + "format": "uri", + "description": "OAuth client ID of the requesting app, if attested." + } + } + }, + "output": { + "encoding": "application/json", + "schema": { + "type": "object", + "required": ["read", "write"], + "properties": { + "read": { + "type": "boolean" + }, + "write": { + "type": "boolean" + } + } + } + } + } + } +} diff --git a/packages/space-conformance/lexicons/managedspace/checkUserAccess.json b/packages/space-conformance/lexicons/managedspace/checkUserAccess.json deleted file mode 100644 index bf32fa5..0000000 --- a/packages/space-conformance/lexicons/managedspace/checkUserAccess.json +++ /dev/null @@ -1,48 +0,0 @@ -{ - "lexicon": 1, - "id": "com.atproto.managedspace.checkUserAccess", - "defs": { - "main": { - "type": "query", - "description": "Ask a space's managing app whether to authorize a user to read or write. Served by the managingApp (not the PDS), called by the authority of a space governed by the managedspace policy. Authenticated with service auth from the authority.", - "parameters": { - "type": "params", - "required": ["space", "user", "access"], - "properties": { - "space": { - "type": "string", - "format": "space-ref", - "description": "Reference to the space." - }, - "user": { - "type": "string", - "format": "did", - "description": "The DID of the requesting user." - }, - "access": { - "type": "string", - "knownValues": ["read", "write"], - "description": "The kind of access being checked." - }, - "clientId": { - "type": "string", - "description": "The attested client_id, if a client attestation was presented. Omitted for write checks." - } - } - }, - "output": { - "encoding": "application/json", - "schema": { - "type": "object", - "required": ["authorized"], - "properties": { - "authorized": { - "type": "boolean", - "description": "Whether the managing app authorizes the request." - } - } - } - } - } - } -} diff --git a/packages/space-conformance/lexicons/managedspace/policy.json b/packages/space-conformance/lexicons/managedspace/policy.json index a3fc21c..908f4c4 100644 --- a/packages/space-conformance/lexicons/managedspace/policy.json +++ b/packages/space-conformance/lexicons/managedspace/policy.json @@ -4,17 +4,17 @@ "defs": { "main": { "type": "object", - "description": "Space policy that defers each user access decision to an external managing app, which the authority asks via checkUserAccess.", + "description": "Space policy that delegates access decisions to an external app through checkAccess.", "required": ["managingApp"], "properties": { "managingApp": { "type": "string", - "description": "Service identifier of the managing app: a DID with an optional service fragment (e.g. 'did:web:example.com#forum')." + "description": "The `did#serviceId` reference of the managing app." }, "publishPolicy": { "type": "boolean", "default": false, - "description": "Publish the policy to readers as a com.atproto.space.policy record in the authority's repo in the space." + "description": "Publish the policy as a com.atproto.space.policy record in the space." } } } diff --git a/packages/space-conformance/lexicons/memberspace/defs.json b/packages/space-conformance/lexicons/memberspace/defs.json new file mode 100644 index 0000000..34f9f35 --- /dev/null +++ b/packages/space-conformance/lexicons/memberspace/defs.json @@ -0,0 +1,22 @@ +{ + "lexicon": 1, + "id": "com.atproto.memberspace.defs", + "defs": { + "member": { + "type": "object", + "required": ["did", "read", "write"], + "properties": { + "did": { + "type": "string", + "format": "did" + }, + "read": { + "type": "boolean" + }, + "write": { + "type": "boolean" + } + } + } + } +} diff --git a/packages/space-conformance/lexicons/memberspace/listMembers.json b/packages/space-conformance/lexicons/memberspace/listMembers.json index 54d03a5..83a1279 100644 --- a/packages/space-conformance/lexicons/memberspace/listMembers.json +++ b/packages/space-conformance/lexicons/memberspace/listMembers.json @@ -4,22 +4,20 @@ "defs": { "main": { "type": "query", - "description": "List the members of a space governed by the memberspace policy, and their read and write access. Must be called on the space authority's PDS. Requires OAuth with a covering read_self grant; a space credential is not sufficient, so members hosted elsewhere cannot enumerate the list. To make the list visible to readers, set the policy's publishMembers.", + "description": "List the members of a space with a memberspace policy. Requires auth as the space authority, implemented by PDS.", "parameters": { "type": "params", "required": ["space"], "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space." + "format": "space-ref" }, "limit": { "type": "integer", "minimum": 1, "maximum": 1000, - "default": 100, - "description": "Maximum number of members to return." + "default": 100 }, "cursor": { "type": "string" @@ -39,7 +37,7 @@ "type": "array", "items": { "type": "ref", - "ref": "#member" + "ref": "com.atproto.memberspace.defs#member" } } } @@ -50,26 +48,16 @@ "name": "SpaceNotFound" }, { - "name": "PolicyMismatch", - "description": "The space is not governed by the memberspace policy." - } - ] - }, - "member": { - "type": "object", - "required": ["did", "read", "write"], - "properties": { - "did": { - "type": "string", - "format": "did" + "name": "NotAuthorized" }, - "read": { - "type": "boolean" + { + "name": "PolicyMismatch", + "description": "The space does not have a memberspace policy." }, - "write": { - "type": "boolean" + { + "name": "InvalidCursor" } - } + ] } } } diff --git a/packages/space-conformance/lexicons/memberspace/member.json b/packages/space-conformance/lexicons/memberspace/member.json index 6a2932c..26cbf5f 100644 --- a/packages/space-conformance/lexicons/memberspace/member.json +++ b/packages/space-conformance/lexicons/memberspace/member.json @@ -4,19 +4,17 @@ "defs": { "main": { "type": "record", - "description": "An entry in the member list of a space governed by the memberspace policy, published to readers when the policy's publishMembers is set. Keyed by the member's DID. Written by the space authority's PDS to the authority's own repo in the space, and kept in sync with the member list. Only authoritative in the authority's repo.", + "description": "A published entry in a space's member list, keyed by the member's DID. Only authoritative in the space authority's repo.", "key": "any", "record": { "type": "object", "required": ["read", "write"], "properties": { "read": { - "type": "boolean", - "description": "Whether the member may read when the policy's publicRead is not set." + "type": "boolean" }, "write": { - "type": "boolean", - "description": "Whether the member's writes are tracked when the policy's publicWrite is not set." + "type": "boolean" } } } diff --git a/packages/space-conformance/lexicons/memberspace/policy.json b/packages/space-conformance/lexicons/memberspace/policy.json index 77320c9..e4fc53d 100644 --- a/packages/space-conformance/lexicons/memberspace/policy.json +++ b/packages/space-conformance/lexicons/memberspace/policy.json @@ -4,35 +4,35 @@ "defs": { "main": { "type": "object", - "description": "Space policy that governs access via a member list maintained by the space host, managed with putMember and removeMember.", + "description": "Space policy that grants access based on a member list.", "properties": { "publicRead": { "type": "boolean", "default": false, - "description": "If true, the authority issues a space credential to anyone, with or without a delegation token. Otherwise, only to members whose entry has read set." + "description": "If true, anyone may read the space. Otherwise, only members with read access." }, "publicWrite": { "type": "boolean", "default": false, - "description": "If true, the authority tracks and forwards notifications for any user's writes. Otherwise, only for members whose entry has write set." + "description": "If true, any account's writes are tracked in the writer set, except members without write access. Otherwise, only members with write access." }, "allowedApps": { "type": "array", - "description": "If set, the authority mints a credential only for these apps, evaluated against the attested client_id. When omitted, any app may read the space and no client attestation is required. Does not apply to writes.", + "description": "If set, only these apps (by OAuth client ID) may read the space.", "items": { "type": "string", - "description": "An OAuth client ID." + "format": "uri" } }, "publishPolicy": { "type": "boolean", "default": false, - "description": "Publish the policy to readers as a com.atproto.space.policy record in the authority's repo in the space." + "description": "Publish the policy as a com.atproto.space.policy record in the space." }, "publishMembers": { "type": "boolean", "default": false, - "description": "Publish the member list to readers as com.atproto.memberspace.member records in the authority's repo in the space." + "description": "Publish the member list as com.atproto.memberspace.member records in the space." } } } diff --git a/packages/space-conformance/lexicons/memberspace/putMember.json b/packages/space-conformance/lexicons/memberspace/putMember.json deleted file mode 100644 index f5befb8..0000000 --- a/packages/space-conformance/lexicons/memberspace/putMember.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "lexicon": 1, - "id": "com.atproto.memberspace.putMember", - "defs": { - "main": { - "type": "procedure", - "description": "Add a member to the member list of a space governed by the memberspace policy, or replace their read and write access. Requires auth as the space owner.", - "input": { - "encoding": "application/json", - "schema": { - "type": "object", - "required": ["space", "did", "read", "write"], - "properties": { - "space": { - "type": "string", - "format": "space-ref", - "description": "Reference to the space." - }, - "did": { - "type": "string", - "format": "did", - "description": "The DID of the member." - }, - "read": { - "type": "boolean", - "description": "Whether the member may read when the policy's publicRead is not set." - }, - "write": { - "type": "boolean", - "description": "Whether the member's writes are tracked when the policy's publicWrite is not set." - } - } - } - }, - "errors": [ - { - "name": "SpaceNotFound" - }, - { - "name": "NotSpaceOwner" - }, - { - "name": "PolicyMismatch", - "description": "The space is not governed by the memberspace policy." - } - ] - } - } -} diff --git a/packages/space-conformance/lexicons/memberspace/putMembers.json b/packages/space-conformance/lexicons/memberspace/putMembers.json new file mode 100644 index 0000000..4dc779e --- /dev/null +++ b/packages/space-conformance/lexicons/memberspace/putMembers.json @@ -0,0 +1,43 @@ +{ + "lexicon": 1, + "id": "com.atproto.memberspace.putMembers", + "defs": { + "main": { + "type": "procedure", + "description": "Add members to a space, or update existing members' access, in a single commit. Requires auth as the space authority, implemented by PDS.", + "input": { + "encoding": "application/json", + "schema": { + "type": "object", + "required": ["space", "members"], + "properties": { + "space": { + "type": "string", + "format": "space-ref" + }, + "members": { + "type": "array", + "maxLength": 100, + "items": { + "type": "ref", + "ref": "com.atproto.memberspace.defs#member" + } + } + } + } + }, + "errors": [ + { + "name": "SpaceNotFound" + }, + { + "name": "NotAuthorized" + }, + { + "name": "PolicyMismatch", + "description": "The space does not have a memberspace policy." + } + ] + } + } +} diff --git a/packages/space-conformance/lexicons/memberspace/removeMember.json b/packages/space-conformance/lexicons/memberspace/removeMember.json deleted file mode 100644 index bb259cc..0000000 --- a/packages/space-conformance/lexicons/memberspace/removeMember.json +++ /dev/null @@ -1,41 +0,0 @@ -{ - "lexicon": 1, - "id": "com.atproto.memberspace.removeMember", - "defs": { - "main": { - "type": "procedure", - "description": "Remove a member from the member list of a space governed by the memberspace policy. Requires auth as the space owner.", - "input": { - "encoding": "application/json", - "schema": { - "type": "object", - "required": ["space", "did"], - "properties": { - "space": { - "type": "string", - "format": "space-ref", - "description": "Reference to the space." - }, - "did": { - "type": "string", - "format": "did", - "description": "The DID of the member to remove." - } - } - } - }, - "errors": [ - { - "name": "SpaceNotFound" - }, - { - "name": "NotSpaceOwner" - }, - { - "name": "PolicyMismatch", - "description": "The space is not governed by the memberspace policy." - } - ] - } - } -} diff --git a/packages/space-conformance/lexicons/memberspace/removeMembers.json b/packages/space-conformance/lexicons/memberspace/removeMembers.json new file mode 100644 index 0000000..137e609 --- /dev/null +++ b/packages/space-conformance/lexicons/memberspace/removeMembers.json @@ -0,0 +1,43 @@ +{ + "lexicon": 1, + "id": "com.atproto.memberspace.removeMembers", + "defs": { + "main": { + "type": "procedure", + "description": "Remove members from a space in a single commit. DIDs that are not members are ignored. Requires auth as the space authority, implemented by PDS.", + "input": { + "encoding": "application/json", + "schema": { + "type": "object", + "required": ["space", "dids"], + "properties": { + "space": { + "type": "string", + "format": "space-ref" + }, + "dids": { + "type": "array", + "maxLength": 100, + "items": { + "type": "string", + "format": "did" + } + } + } + } + }, + "errors": [ + { + "name": "SpaceNotFound" + }, + { + "name": "NotAuthorized" + }, + { + "name": "PolicyMismatch", + "description": "The space does not have a memberspace policy." + } + ] + } + } +} diff --git a/packages/space-conformance/lexicons/personalspace/policy.json b/packages/space-conformance/lexicons/personalspace/policy.json index 689fe16..f29e654 100644 --- a/packages/space-conformance/lexicons/personalspace/policy.json +++ b/packages/space-conformance/lexicons/personalspace/policy.json @@ -4,7 +4,7 @@ "defs": { "main": { "type": "object", - "description": "Space policy for data that only its owner should see, such as bookmarks, mutes, or drafts. Only the space authority's own account is authorized to read, and the authority tracks no other writers. Has no configuration fields.", + "description": "Space policy for personal data that only the space authority and authorized apps can read, such as bookmarks or drafts.", "properties": {} } } diff --git a/packages/space-conformance/lexicons/space/applyWrites.json b/packages/space-conformance/lexicons/space/applyWrites.json index 85858d2..9c0dba6 100644 --- a/packages/space-conformance/lexicons/space/applyWrites.json +++ b/packages/space-conformance/lexicons/space/applyWrites.json @@ -4,7 +4,7 @@ "defs": { "main": { "type": "procedure", - "description": "Apply a batch transaction of creates, updates, and deletes in a permissioned space. Requires auth, implemented by PDS.", + "description": "Apply a batch transaction of creates, updates, and deletes to a space repo. Requires auth, implemented by PDS.", "input": { "encoding": "application/json", "schema": { @@ -13,13 +13,11 @@ "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space." + "format": "space-ref" }, "repo": { "type": "string", - "format": "did", - "description": "The DID of the repo to write to (the authenticated member)." + "format": "did" }, "validate": { "type": "boolean", @@ -57,12 +55,10 @@ "name": "SpaceNotFound" }, { - "name": "RecordNotFound", - "description": "An update or delete targeted a record that does not exist." + "name": "RecordNotFound" }, { - "name": "RecordAlreadyExists", - "description": "A create targeted a collection and rkey that already holds a record." + "name": "RecordAlreadyExists" } ] }, @@ -77,8 +73,7 @@ }, "rkey": { "type": "string", - "format": "record-key", - "maxLength": 512 + "format": "record-key" }, "value": { "type": "unknown" diff --git a/packages/space-conformance/lexicons/space/authorizeSpaceSync.json b/packages/space-conformance/lexicons/space/authorizeSpaceSync.json new file mode 100644 index 0000000..33d3b18 --- /dev/null +++ b/packages/space-conformance/lexicons/space/authorizeSpaceSync.json @@ -0,0 +1,109 @@ +{ + "lexicon": 1, + "id": "com.atproto.space.authorizeSpaceSync", + "defs": { + "main": { + "type": "procedure", + "description": "Authorize syncing a space, returning a new credential for reading data across it and the space's current revision, and optionally registering for notifications of updates to it. Depending on the space's policy, a delegation token and/or client attestation may be required. Implemented by the space host.", + "input": { + "encoding": "application/json", + "schema": { + "type": "object", + "required": ["space", "credentialKey"], + "properties": { + "space": { + "type": "string", + "format": "space-ref" + }, + "credentialKey": { + "type": "string", + "description": "P-256 did:key that the credential is bound to." + }, + "delegationToken": { + "type": "string", + "description": "Obtained from getDelegationToken." + }, + "clientAttestation": { + "type": "string" + }, + "notify": { + "type": "ref", + "ref": "#notify", + "description": "Register an endpoint to be notified of updates to the space via notifySpaceUpdate. The registration stays active while this credential is valid. After it expires, the endpoint receives only a prompt to reauthorize, or notice of the space's deletion." + } + } + } + }, + "output": { + "encoding": "application/json", + "schema": { + "type": "object", + "required": ["credential"], + "properties": { + "credential": { + "type": "string" + }, + "spaceRev": { + "type": "string", + "format": "tid", + "description": "The space's current revision. Omitted before the space's first update." + } + } + } + }, + "errors": [ + { + "name": "SpaceNotFound", + "description": "May also be returned in place of AccountNotAuthorized, to avoid revealing that the space exists." + }, + { + "name": "SpaceDeleted" + }, + { + "name": "AccountNotAuthorized" + }, + { + "name": "AppNotAuthorized" + }, + { + "name": "NotAuthorized", + "description": "Generic refusal. May be returned in place of AccountNotAuthorized or AppNotAuthorized." + }, + { + "name": "InvalidDelegationToken" + }, + { + "name": "InvalidClientAttestation" + }, + { + "name": "RegistrationNotConfirmed", + "description": "The notify endpoint did not confirm the registration." + }, + { + "name": "RepoTakendown", + "description": "The space authority has been taken down." + }, + { + "name": "RepoDeactivated", + "description": "The space authority has been deactivated." + } + ] + }, + "notify": { + "type": "object", + "required": ["endpoint", "token"], + "properties": { + "endpoint": { + "type": "string", + "format": "uri", + "description": "Base HTTPS URL that notification methods are called against." + }, + "token": { + "type": "string", + "maxLength": 512, + "description": "Opaque secret, included in the body of each request to the endpoint. The endpoint and token together identify the registration, so the token should stay the same across authorizations." + } + } + } + } +} diff --git a/packages/space-conformance/lexicons/space/clearRecords.json b/packages/space-conformance/lexicons/space/clearRecords.json index a6d2cbe..de524d6 100644 --- a/packages/space-conformance/lexicons/space/clearRecords.json +++ b/packages/space-conformance/lexicons/space/clearRecords.json @@ -4,7 +4,7 @@ "defs": { "main": { "type": "procedure", - "description": "Delete every record in the authenticated account's space repo. The repo advances to a new revision with the empty repo's digest, and its oplog is cleared. In the space authority's own repo, the records the host publishes from the space's configuration (com.atproto.space.policy and com.atproto.memberspace.member) are kept, and the digest is that of the records that remain. Succeeds whether or not the repo held any records to delete. Requires auth, implemented by PDS.", + "description": "Delete all records in the authenticated account's space repo. In the space authority's repo, records published from the space's configuration (such as its policy) are kept. Requires auth, implemented by PDS.", "input": { "encoding": "application/json", "schema": { @@ -13,13 +13,11 @@ "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space." + "format": "space-ref" }, "repo": { "type": "string", - "format": "did", - "description": "The DID of the repo to clear (the authenticated member)." + "format": "did" } } } diff --git a/packages/space-conformance/lexicons/space/confirmRegistration.json b/packages/space-conformance/lexicons/space/confirmRegistration.json new file mode 100644 index 0000000..e5e0231 --- /dev/null +++ b/packages/space-conformance/lexicons/space/confirmRegistration.json @@ -0,0 +1,44 @@ +{ + "lexicon": 1, + "id": "com.atproto.space.confirmRegistration", + "defs": { + "main": { + "type": "procedure", + "description": "Confirm a new notification registration. Called by the space host on an endpoint passed to authorizeSpaceSync, before registering it. The syncing service checks that it issued the token for the space, and echoes back the challenge.", + "input": { + "encoding": "application/json", + "schema": { + "type": "object", + "required": ["space", "token", "challenge"], + "properties": { + "space": { + "type": "string", + "format": "space-ref" + }, + "token": { + "type": "string", + "maxLength": 512 + }, + "challenge": { + "type": "string", + "maxLength": 512 + } + } + } + }, + "output": { + "encoding": "application/json", + "schema": { + "type": "object", + "required": ["challenge"], + "properties": { + "challenge": { + "type": "string", + "maxLength": 512 + } + } + } + } + } + } +} diff --git a/packages/space-conformance/lexicons/space/createRecord.json b/packages/space-conformance/lexicons/space/createRecord.json index 5254cca..509cabc 100644 --- a/packages/space-conformance/lexicons/space/createRecord.json +++ b/packages/space-conformance/lexicons/space/createRecord.json @@ -4,7 +4,7 @@ "defs": { "main": { "type": "procedure", - "description": "Create a single new record in a permissioned space. Requires auth, implemented by PDS.", + "description": "Create a single new record in a space repo. Requires auth, implemented by PDS.", "input": { "encoding": "application/json", "schema": { @@ -13,24 +13,19 @@ "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space." + "format": "space-ref" }, "repo": { "type": "string", - "format": "did", - "description": "The DID of the repo to write to (the authenticated member)." + "format": "did" }, "collection": { "type": "string", - "format": "nsid", - "description": "The NSID of the record collection." + "format": "nsid" }, "rkey": { "type": "string", - "format": "record-key", - "description": "The Record Key.", - "maxLength": 512 + "format": "record-key" }, "validate": { "type": "boolean", @@ -51,8 +46,7 @@ "properties": { "uri": { "type": "string", - "format": "at-uri", - "description": "URI of the created record." + "format": "at-uri" }, "cid": { "type": "string", @@ -70,8 +64,7 @@ "name": "SpaceNotFound" }, { - "name": "RecordAlreadyExists", - "description": "A record already exists at this collection and rkey. Retry with a different rkey, or use putRecord." + "name": "RecordAlreadyExists" } ] } diff --git a/packages/space-conformance/lexicons/space/createSpace.json b/packages/space-conformance/lexicons/space/createSpace.json index 8aab935..3f1c9bd 100644 --- a/packages/space-conformance/lexicons/space/createSpace.json +++ b/packages/space-conformance/lexicons/space/createSpace.json @@ -4,7 +4,7 @@ "defs": { "main": { "type": "procedure", - "description": "Create a new space governed by the given policy. The space is anchored on the authenticated user's DID, who becomes the space owner. Requires auth, implemented by PDS.", + "description": "Create a new space, with the authenticated account as its authority. Requires auth, implemented by PDS.", "input": { "encoding": "application/json", "schema": { @@ -13,17 +13,16 @@ "properties": { "spaceType": { "type": "string", - "format": "nsid", - "description": "The NSID of the space type, describing the modality of the space (e.g. app.bsky.group, app.bsky.personal)." + "format": "nsid" }, "skey": { "type": "string", "format": "record-key", - "description": "The space key. Used to differentiate multiple spaces of the same type under the same owner. Same syntax requirements as a record key. If not provided, one will be auto-generated (TID)." + "description": "Space key. Generated as a TID if not provided." }, "policy": { "type": "union", - "description": "The policy governing the space, including its configuration.", + "description": "PDSes must support all of the listed policies. Other space hosts may support only some of them, and any host may support policies beyond those listed.", "refs": [ "com.atproto.personalspace.policy", "com.atproto.memberspace.policy", @@ -37,24 +36,21 @@ "encoding": "application/json", "schema": { "type": "object", - "required": ["uri"], + "required": ["space"], "properties": { - "uri": { + "space": { "type": "string", - "format": "space-ref", - "description": "URI of the created space." + "format": "space-ref" } } } }, "errors": [ { - "name": "SpaceAlreadyExists", - "description": "A space with this owner, type, and skey already exists. A space that was previously deleted may be created again." + "name": "SpaceAlreadyExists" }, { - "name": "UnsupportedPolicy", - "description": "The requested policy is not one the host implements." + "name": "UnsupportedPolicy" } ] } diff --git a/packages/space-conformance/lexicons/space/defs.json b/packages/space-conformance/lexicons/space/defs.json index 7cc0ae0..2d3de93 100644 --- a/packages/space-conformance/lexicons/space/defs.json +++ b/packages/space-conformance/lexicons/space/defs.json @@ -4,7 +4,7 @@ "defs": { "commit": { "type": "object", - "description": "A commit over the current state of a permissioned repo. Carries no signature: the repo host authenticates it to a syncer with a MAC in the Atproto-Space-Mac response header.", + "description": "Commit to the current state of a space repo. Not signed; authenticated by the repo host with a MAC instead.", "required": ["ver", "repo", "space", "rev", "data"], "properties": { "ver": { @@ -13,22 +13,68 @@ }, "repo": { "type": "string", - "format": "did", - "description": "The author DID of the repo." + "format": "did" }, "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space." + "format": "space-ref" }, "rev": { "type": "string", - "format": "tid", - "description": "Commit revision (TID)." + "format": "tid" }, "data": { "type": "bytes", - "description": "sha256 digest of the LtHash state (32 bytes)." + "description": "SHA-256 digest of the repo's LtHash state." + } + } + }, + "repoWrite": { + "type": "object", + "description": "A repo in the space advanced to a new revision.", + "required": ["repo", "repoRev", "data", "spaceRev"], + "properties": { + "repo": { + "type": "string", + "format": "did" + }, + "repoRev": { + "type": "string", + "format": "tid" + }, + "data": { + "type": "bytes" + }, + "spaceRev": { + "type": "string", + "format": "tid", + "description": "The space revision at which this update was sequenced." + }, + "prevSpaceRev": { + "type": "string", + "format": "tid", + "description": "The space revision before this update, if any. Set in notifySpaceUpdate, where a gap indicates missed notifications, which can be recovered with listWriters." + } + } + }, + "repoRemoved": { + "type": "object", + "description": "A repo was removed from the writer set.", + "required": ["repo", "spaceRev"], + "properties": { + "repo": { + "type": "string", + "format": "did" + }, + "spaceRev": { + "type": "string", + "format": "tid", + "description": "The space revision at which this update was sequenced." + }, + "prevSpaceRev": { + "type": "string", + "format": "tid", + "description": "The space revision before this update, if any. Set in notifySpaceUpdate, where a gap indicates missed notifications, which can be recovered with listWriters." } } } diff --git a/packages/space-conformance/lexicons/space/deleteRecord.json b/packages/space-conformance/lexicons/space/deleteRecord.json index 1d076cd..49c54bb 100644 --- a/packages/space-conformance/lexicons/space/deleteRecord.json +++ b/packages/space-conformance/lexicons/space/deleteRecord.json @@ -4,7 +4,7 @@ "defs": { "main": { "type": "procedure", - "description": "Delete a record from a permissioned space, or ensure it doesn't exist. Succeeds whether or not the record was present. Requires auth, implemented by PDS.", + "description": "Delete a record from a space repo, or ensure it doesn't exist. Requires auth, implemented by PDS.", "input": { "encoding": "application/json", "schema": { @@ -13,23 +13,19 @@ "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space." + "format": "space-ref" }, "repo": { "type": "string", - "format": "did", - "description": "The DID of the repo to delete from (the authenticated member)." + "format": "did" }, "collection": { "type": "string", - "format": "nsid", - "description": "The NSID of the record collection." + "format": "nsid" }, "rkey": { "type": "string", - "format": "record-key", - "description": "The Record Key." + "format": "record-key" } } } diff --git a/packages/space-conformance/lexicons/space/deleteSpace.json b/packages/space-conformance/lexicons/space/deleteSpace.json index 5de6875..59f8fc5 100644 --- a/packages/space-conformance/lexicons/space/deleteSpace.json +++ b/packages/space-conformance/lexicons/space/deleteSpace.json @@ -4,7 +4,7 @@ "defs": { "main": { "type": "procedure", - "description": "Delete a space. Requires auth as the space owner. Deletes the owner's own repo in the space; other members' repos are left in place. Afterwards, reads and writes fail with SpaceNotFound and getSpaceCredential returns SpaceDeleted. Idempotent. Implemented by PDS.", + "description": "Delete a space, along with the authority's space repo. Requires auth as the space authority, implemented by PDS.", "input": { "encoding": "application/json", "schema": { @@ -13,8 +13,7 @@ "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space to delete." + "format": "space-ref" } } } @@ -24,7 +23,7 @@ "name": "SpaceNotFound" }, { - "name": "NotSpaceOwner" + "name": "NotAuthorized" } ] } diff --git a/packages/space-conformance/lexicons/space/exportSpaceMeta.json b/packages/space-conformance/lexicons/space/exportSpaceMeta.json index 11b0453..1c74f6c 100644 --- a/packages/space-conformance/lexicons/space/exportSpaceMeta.json +++ b/packages/space-conformance/lexicons/space/exportSpaceMeta.json @@ -4,27 +4,26 @@ "defs": { "main": { "type": "query", - "description": "Download a space's host-side state as a space meta archive, for account migration: a STAR file with the atproto-space-meta profile. The archive's metadata is the space. Its body is the space's policy, then any state the policy keeps (such as a memberspace member list), then the writer set. Served by the space host. Requires OAuth as the space owner with a covering read_self grant.", + "description": "Export a space's state, such as its policy and member list, as a STAR file for account migration. Requires auth as the space authority, implemented by PDS.", "parameters": { "type": "params", "required": ["space"], "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space." + "format": "space-ref" } } }, "output": { - "encoding": "application/octet-stream" + "encoding": "application/vnd.dasl.star" }, "errors": [ { "name": "SpaceNotFound" }, { - "name": "NotSpaceOwner" + "name": "NotAuthorized" } ] } diff --git a/packages/space-conformance/lexicons/space/getBlob.json b/packages/space-conformance/lexicons/space/getBlob.json index 4106324..8ea177b 100644 --- a/packages/space-conformance/lexicons/space/getBlob.json +++ b/packages/space-conformance/lexicons/space/getBlob.json @@ -4,25 +4,22 @@ "defs": { "main": { "type": "query", - "description": "Get a blob referenced from a record in a permissioned space. Returns the full blob as originally uploaded. Blobs are not uploaded through this namespace: a space record references a blob uploaded via com.atproto.repo.uploadBlob, so a client writing blob-bearing records into a space needs a blob permission alongside its space permission. Use listBlobs to enumerate a repo's blobs in a space. Callable with either OAuth (for the authenticated user's own data) or a space credential (for syncing services).", + "description": "Get a blob referenced by a record in a space repo. Returns the full blob as originally uploaded. Requires auth as the repo's account or with a space credential; implemented by PDS.", "parameters": { "type": "params", "required": ["space", "repo", "cid"], "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space." + "format": "space-ref" }, "repo": { "type": "string", - "format": "did", - "description": "The DID of the account whose repo holds the blob." + "format": "did" }, "cid": { "type": "string", - "format": "cid", - "description": "The CID of the blob to fetch." + "format": "cid" } } }, diff --git a/packages/space-conformance/lexicons/space/getDelegationToken.json b/packages/space-conformance/lexicons/space/getDelegationToken.json index 26e379d..c32cf8a 100644 --- a/packages/space-conformance/lexicons/space/getDelegationToken.json +++ b/packages/space-conformance/lexicons/space/getDelegationToken.json @@ -4,15 +4,14 @@ "defs": { "main": { "type": "query", - "description": "Mint a delegation token for a space, proving the requesting app is acting on the user's behalf. Exchanged with the space authority for a space credential. Served by the requesting user's PDS. Requires OAuth auth.", + "description": "Get a delegation token for a space, to exchange with the space host for a space credential. Requires auth, implemented by PDS.", "parameters": { "type": "params", "required": ["space"], "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space." + "format": "space-ref" } } }, @@ -23,8 +22,7 @@ "required": ["token"], "properties": { "token": { - "type": "string", - "description": "A signed JWT delegation token." + "type": "string" } } } diff --git a/packages/space-conformance/lexicons/space/getLatestCommit.json b/packages/space-conformance/lexicons/space/getLatestCommit.json index 1151558..24ae13d 100644 --- a/packages/space-conformance/lexicons/space/getLatestCommit.json +++ b/packages/space-conformance/lexicons/space/getLatestCommit.json @@ -4,20 +4,18 @@ "defs": { "main": { "type": "query", - "description": "Get the current commit for an account's permissioned repo within a space. Served by a repo host. When called with a space credential, the caller must send an Atproto-Space-Want-Mac header, and the commit's MAC is returned in the Atproto-Space-Mac response header. Throws RepoNotFound when the account holds no repo in the space, including the case of a member that has never written to it. Callable with either OAuth (for the authenticated user's own data) or a space credential (for syncing services).", + "description": "Get the current commit of a space repo. Responses are authenticated with a MAC. Requires auth as the repo's account or with a space credential; implemented by PDS.", "parameters": { "type": "params", "required": ["space", "repo"], "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space." + "format": "space-ref" }, "repo": { "type": "string", - "format": "did", - "description": "The DID of the account whose latest commit to retrieve." + "format": "did" } } }, @@ -28,8 +26,7 @@ "properties": { "commit": { "type": "ref", - "ref": "com.atproto.space.defs#commit", - "description": "The account's current commit." + "ref": "com.atproto.space.defs#commit" } }, "required": ["commit"] @@ -37,8 +34,8 @@ }, "errors": [ { - "name": "BadSpaceMac", - "description": "The Atproto-Space-Want-Mac header is missing or malformed, names an unsupported type or version, or carries an invalid key share." + "name": "InvalidSpaceMac", + "description": "The MAC requested in the Accept-Signature header is missing or invalid." }, { "name": "SpaceNotFound" diff --git a/packages/space-conformance/lexicons/space/getRecord.json b/packages/space-conformance/lexicons/space/getRecord.json index 7ef6f87..2576aec 100644 --- a/packages/space-conformance/lexicons/space/getRecord.json +++ b/packages/space-conformance/lexicons/space/getRecord.json @@ -4,30 +4,26 @@ "defs": { "main": { "type": "query", - "description": "Get a single record from a permissioned space. Callable with either OAuth (for the authenticated user's own data) or a space credential (for syncing services). When called with a space credential, the caller must send an Atproto-Space-Want-Mac header, and the record's MAC is returned in the Atproto-Space-Mac response header. Throws RepoNotFound when the account holds no repo in the space; this does not distinguish a member that has never written from a non-member.", + "description": "Get a single record from a space repo. Responses are authenticated with a MAC. Requires auth as the repo's account or with a space credential; implemented by PDS.", "parameters": { "type": "params", "required": ["space", "repo", "collection", "rkey"], "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space." + "format": "space-ref" }, "repo": { "type": "string", - "format": "did", - "description": "The DID of the account whose repo to read from." + "format": "did" }, "collection": { "type": "string", - "format": "nsid", - "description": "The NSID of the record collection." + "format": "nsid" }, "rkey": { "type": "string", - "format": "record-key", - "description": "The Record Key." + "format": "record-key" } } }, @@ -53,8 +49,8 @@ }, "errors": [ { - "name": "BadSpaceMac", - "description": "The Atproto-Space-Want-Mac header is missing or malformed, names an unsupported type or version, or carries an invalid key share." + "name": "InvalidSpaceMac", + "description": "The MAC requested in the Accept-Signature header is missing or invalid." }, { "name": "RecordNotFound" diff --git a/packages/space-conformance/lexicons/space/getRepo.json b/packages/space-conformance/lexicons/space/getRepo.json index f184698..9a0fa02 100644 --- a/packages/space-conformance/lexicons/space/getRepo.json +++ b/packages/space-conformance/lexicons/space/getRepo.json @@ -4,30 +4,28 @@ "defs": { "main": { "type": "query", - "description": "Download an account's permissioned repo within a space as a STAR file, for full-state recovery. The archive's metadata is the repo's commit; each key/value pair is a record path ('{collection}/{rkey}') and the record's DRISL encoding, in strict lexicographic order of the path. Blobs are not included and are fetched separately via getBlob. Served by a repo host. Callable with either OAuth (for the authenticated user's own data) or a space credential (for syncing services). When called with a space credential, the caller must send an Atproto-Space-Want-Mac header, and the commit's MAC is returned in the Atproto-Space-Mac response header.", + "description": "Download a space repo as a STAR file. Responses are authenticated with a MAC. Requires auth as the repo's account or with a space credential; implemented by PDS.", "parameters": { "type": "params", "required": ["space", "repo"], "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space." + "format": "space-ref" }, "repo": { "type": "string", - "format": "did", - "description": "The DID of the account whose repo to download." + "format": "did" } } }, "output": { - "encoding": "application/octet-stream" + "encoding": "application/vnd.dasl.star" }, "errors": [ { - "name": "BadSpaceMac", - "description": "The Atproto-Space-Want-Mac header is missing or malformed, names an unsupported type or version, or carries an invalid key share." + "name": "InvalidSpaceMac", + "description": "The MAC requested in the Accept-Signature header is missing or invalid." }, { "name": "SpaceNotFound" }, { "name": "RepoNotFound" }, diff --git a/packages/space-conformance/lexicons/space/getSpace.json b/packages/space-conformance/lexicons/space/getSpace.json index de0709b..b1d80ed 100644 --- a/packages/space-conformance/lexicons/space/getSpace.json +++ b/packages/space-conformance/lexicons/space/getSpace.json @@ -4,15 +4,14 @@ "defs": { "main": { "type": "query", - "description": "Describe a space, including the policy that governs it. Served by the space host for every space it hosts, regardless of policy. Requires OAuth as the space owner with a covering read_self grant. A policy may optionally be published in the space, as a com.atproto.space.policy record, so that syncers can view it.", + "description": "Get a space and its policy. Requires auth as the space authority, implemented by PDS.", "parameters": { "type": "params", "required": ["space"], "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space." + "format": "space-ref" } } }, @@ -20,16 +19,15 @@ "encoding": "application/json", "schema": { "type": "object", - "required": ["uri", "policy"], + "required": ["space", "policy"], "properties": { - "uri": { + "space": { "type": "string", - "format": "space-ref", - "description": "URI of the space." + "format": "space-ref" }, "policy": { "type": "union", - "description": "The policy governing the space, including its configuration.", + "description": "PDSes must support all of the listed policies. Other space hosts may support only some of them, and any host may support policies beyond those listed.", "refs": [ "com.atproto.personalspace.policy", "com.atproto.memberspace.policy", @@ -39,7 +37,7 @@ } } }, - "errors": [{ "name": "SpaceNotFound" }] + "errors": [{ "name": "SpaceNotFound" }, { "name": "NotAuthorized" }] } } } diff --git a/packages/space-conformance/lexicons/space/getSpaceCredential.json b/packages/space-conformance/lexicons/space/getSpaceCredential.json deleted file mode 100644 index 12d6b77..0000000 --- a/packages/space-conformance/lexicons/space/getSpaceCredential.json +++ /dev/null @@ -1,84 +0,0 @@ -{ - "lexicon": 1, - "id": "com.atproto.space.getSpaceCredential", - "defs": { - "main": { - "type": "procedure", - "description": "Request a space credential. Called on the space authority. A delegation token is required when the space gates on the user. A client attestation is required when the space gates on app identity. A space that requires neither offers public access. The resulting space credential reads repos across the space.", - "input": { - "encoding": "application/json", - "schema": { - "type": "object", - "required": ["space", "credentialKid"], - "properties": { - "space": { - "type": "string", - "format": "space-ref", - "description": "Reference to the space." - }, - "credentialKid": { - "type": "string", - "description": "P-256 did:key to bind the credential to. Each request using the credential is signed by this key." - }, - "delegationToken": { - "type": "string", - "description": "Optional delegation token establishing the user being acted for. Required only when the space gates on the user." - }, - "clientAttestation": { - "type": "string", - "description": "Optional client attestation JWT establishing the app's identity. Required only when the space gates on app identity." - } - } - } - }, - "output": { - "encoding": "application/json", - "schema": { - "type": "object", - "required": ["credential"], - "properties": { - "credential": { - "type": "string", - "description": "A signed JWT space credential." - } - } - } - }, - "errors": [ - { - "name": "SpaceNotFound", - "description": "The space does not exist. An authority may also answer this in place of UserNotAuthorized, so that a refusal does not disclose that the space exists to a user who may not read it." - }, - { - "name": "SpaceDeleted" - }, - { - "name": "UserNotAuthorized", - "description": "Refused on the basis of the requesting user." - }, - { - "name": "AppNotAuthorized", - "description": "Refused on the basis of the requesting app." - }, - { - "name": "NotAuthorized", - "description": "Refused without attributing the refusal to the user or the app. Authorities that do not wish to disclose which perimeter failed may return this in place of UserNotAuthorized or AppNotAuthorized." - }, - { - "name": "InvalidDelegationToken" - }, - { - "name": "InvalidClientAttestation" - }, - { - "name": "RepoTakendown", - "description": "The space authority has been taken down." - }, - { - "name": "RepoDeactivated", - "description": "The space authority has been deactivated." - } - ] - } - } -} diff --git a/packages/space-conformance/lexicons/space/importRepo.json b/packages/space-conformance/lexicons/space/importRepo.json index f6b1713..2729dc7 100644 --- a/packages/space-conformance/lexicons/space/importRepo.json +++ b/packages/space-conformance/lexicons/space/importRepo.json @@ -4,14 +4,22 @@ "defs": { "main": { "type": "procedure", - "description": "Import the authenticated account's repo in a space from a STAR file, as served by getRepo, during account migration, replacing whatever this host holds for that repo. The archive's commit names the space and must name the account as its repo. If the account is the space's authority, the space must first be imported with importSpaceMeta. Blobs are not included and are uploaded separately. Requires OAuth with a create grant for every collection in the archive, implemented by PDS.", + "description": "Import the authenticated account's space repo from a STAR file, for account migration. If the account is the space's authority, the space must first be imported with importSpaceMeta. Requires auth, implemented by PDS.", "input": { - "encoding": "application/octet-stream" + "encoding": "application/vnd.dasl.star" }, "errors": [ { "name": "SpaceNotFound", - "description": "The account is the space's authority, and the space has not been imported." + "description": "The account is the space's authority, and the space has not been imported yet." + }, + { + "name": "InvalidRepoFile", + "description": "The STAR file is malformed or fails verification." + }, + { + "name": "RepoMismatch", + "description": "The repo in the STAR file does not belong to the authenticated account." } ] } diff --git a/packages/space-conformance/lexicons/space/importSpaceMeta.json b/packages/space-conformance/lexicons/space/importSpaceMeta.json index b85126a..c4861d5 100644 --- a/packages/space-conformance/lexicons/space/importSpaceMeta.json +++ b/packages/space-conformance/lexicons/space/importSpaceMeta.json @@ -4,17 +4,20 @@ "defs": { "main": { "type": "procedure", - "description": "Import a space from a space meta archive, as served by exportSpaceMeta, during account migration, replacing whatever this host holds for that space. The space must be anchored on the authenticated account's DID. Must come before importing the account's own repo in the space with importRepo. Notification registrations, credential revocations, and deleted space tombstones are not carried over. Requires OAuth with manage=create and manage=update grants for the space, implemented by PDS.", + "description": "Import a space's state from an archive produced by exportSpaceMeta, for account migration. Must be called before importing the authority's space repo with importRepo. Requires auth as the space authority, implemented by PDS.", "input": { - "encoding": "application/octet-stream" + "encoding": "application/vnd.dasl.star" }, "errors": [ { - "name": "NotSpaceOwner" + "name": "NotAuthorized" }, { - "name": "UnsupportedPolicy", - "description": "The archive's policy, or a value within it, is not one the host implements. A host will not store a policy it cannot enforce." + "name": "UnsupportedPolicy" + }, + { + "name": "InvalidSpaceMeta", + "description": "The STAR file is malformed or fails verification." } ] } diff --git a/packages/space-conformance/lexicons/space/listBlobs.json b/packages/space-conformance/lexicons/space/listBlobs.json index 40a62eb..44327b0 100644 --- a/packages/space-conformance/lexicons/space/listBlobs.json +++ b/packages/space-conformance/lexicons/space/listBlobs.json @@ -4,25 +4,18 @@ "defs": { "main": { "type": "query", - "description": "List the CIDs of blobs referenced by an account's records within a permissioned space, optionally since some revision of that repo. Lets a syncer discover which blobs to fetch via getBlob, and lets an account enumerate the blobs it must carry when migrating a permissioned repo. Scoped to one space: blobs behind permissioned records are never enumerated by com.atproto.sync.listBlobs, which is unauthenticated. Callable with either OAuth (for the authenticated user's own data) or a space credential (for syncing services).", + "description": "List blob CIDs referenced by records in a space repo. Requires auth as the repo's account or with a space credential; implemented by PDS.", "parameters": { "type": "params", "required": ["space", "repo"], "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space." + "format": "space-ref" }, "repo": { "type": "string", - "format": "did", - "description": "The DID of the account whose blobs to list." - }, - "since": { - "type": "string", - "format": "tid", - "description": "Optional revision of the permissioned repo to list blobs since." + "format": "did" }, "limit": { "type": "integer", diff --git a/packages/space-conformance/lexicons/space/listRecords.json b/packages/space-conformance/lexicons/space/listRecords.json index 7755c8e..6469337 100644 --- a/packages/space-conformance/lexicons/space/listRecords.json +++ b/packages/space-conformance/lexicons/space/listRecords.json @@ -4,44 +4,36 @@ "defs": { "main": { "type": "query", - "description": "List the records in an account's repo within a permissioned space, optionally filtered by collection. By default each record's value is inlined; set excludeValues for a metadata-only listing (collection, rkey, cid). Used for full-state recovery. Callable with either OAuth (for the authenticated user's own data) or a space credential (for syncing services). Throws RepoNotFound when the account holds no repo in the space; this does not distinguish a member that has never written from a non-member.", + "description": "List records in a space repo, optionally filtered by collection. Requires auth as the repo's account or with a space credential; implemented by PDS.", "parameters": { "type": "params", "required": ["space", "repo"], "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space." + "format": "space-ref" }, "repo": { "type": "string", - "format": "did", - "description": "The DID of the account whose repo to list." + "format": "did" }, "collection": { "type": "string", "format": "nsid", - "description": "The NSID of the record collection. If omitted, lists records across all collections." + "description": "If omitted, lists records across all collections." }, "limit": { "type": "integer", "minimum": 1, "maximum": 1000, - "default": 50, - "description": "The number of records to return." + "default": 50 }, "cursor": { "type": "string" }, - "reverse": { - "type": "boolean", - "description": "Flag to reverse the order of the returned records." - }, "excludeValues": { "type": "boolean", - "default": false, - "description": "If true, omit inlined record values and return only metadata (collection, rkey, cid)." + "default": false } } }, @@ -79,6 +71,9 @@ }, { "name": "RepoDeactivated" + }, + { + "name": "InvalidCursor" } ] }, @@ -99,8 +94,7 @@ "format": "cid" }, "value": { - "type": "unknown", - "description": "The record's value. Inlined by default; omitted when excludeValues is set." + "type": "unknown" } } } diff --git a/packages/space-conformance/lexicons/space/listRepoOps.json b/packages/space-conformance/lexicons/space/listRepoOps.json index 9a96b1a..794fda3 100644 --- a/packages/space-conformance/lexicons/space/listRepoOps.json +++ b/packages/space-conformance/lexicons/space/listRepoOps.json @@ -4,41 +4,35 @@ "defs": { "main": { "type": "query", - "description": "List the operation log for an account's permissioned repo within a space, returning operations after a given revision. Primary incremental sync mechanism. By default each created or updated operation inlines the record's current value; set excludeValues for metadata-only entries. Note the oplog is a transport optimization with no history guarantee: a host may compact it or drop it, and it does not survive account migration, so omitting `since` returns the retained window rather than the repo's full history. Use getRepo for an initial sync or when a `since` revision is no longer available. Callable with either OAuth (for the authenticated user's own data) or a space credential (for syncing services). When called with a space credential, the caller must send an Atproto-Space-Want-Mac header, and a response that includes the commit carries its MAC in the Atproto-Space-Mac response header.", + "description": "List operations on a space repo after a given revision. Used for incremental sync. Hosts may truncate the log, so use getRepo for a full sync. Responses are authenticated with a MAC. Requires auth as the repo's account or with a space credential; implemented by PDS.", "parameters": { "type": "params", "required": ["space", "repo"], "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space." + "format": "space-ref" }, "repo": { "type": "string", - "format": "did", - "description": "The DID of the account whose oplog to retrieve." + "format": "did" }, "since": { "type": "string", - "format": "tid", - "description": "Return operations after this revision. The caller's own sync position; use `cursor` to continue a paginated response." + "format": "tid" }, "limit": { "type": "integer", "minimum": 1, "maximum": 1000, - "default": 100, - "description": "Maximum number of operations to return." + "default": 100 }, "cursor": { - "type": "string", - "description": "Opaque pagination cursor from a previous response. Takes precedence over `since` when both are supplied." + "type": "string" }, "excludeValues": { "type": "boolean", - "default": false, - "description": "If true, omit inlined record values and return only operation metadata." + "default": false } } }, @@ -46,7 +40,7 @@ "encoding": "application/json", "schema": { "type": "object", - "required": ["ops"], + "required": ["ops", "commit"], "properties": { "ops": { "type": "array", @@ -58,30 +52,30 @@ "commit": { "type": "ref", "ref": "com.atproto.space.defs#commit", - "description": "The account's current commit. Included when the response reaches the head of the oplog; omitted on backfill responses." + "description": "The repo's current commit. A syncer compares it against its own set hash once it has applied the last page, which has no cursor." }, "cursor": { - "type": "string", - "description": "Pass as `cursor` to fetch the next page. Absent once the response reaches the head of the oplog." + "type": "string" } } } }, "errors": [ { - "name": "BadSpaceMac", - "description": "The Atproto-Space-Want-Mac header is missing or malformed, names an unsupported type or version, or carries an invalid key share." + "name": "InvalidSpaceMac", + "description": "The MAC requested in the Accept-Signature header is missing or invalid." }, { "name": "SpaceNotFound" }, { "name": "RepoNotFound" }, { "name": "RepoTakendown" }, { "name": "RepoSuspended" }, - { "name": "RepoDeactivated" } + { "name": "RepoDeactivated" }, + { "name": "InvalidCursor" } ] }, "opEntry": { "type": "object", - "description": "A single operation in a permissioned repo's oplog. cid is null for deletes; prev is null for creates. Operations sharing the same rev belong to the same batch. value carries the record's current value for creates and updates, unless excludeValues was set or the value is stale (superseded by a later operation).", + "description": "Operations that share a rev were applied in the same commit.", "required": ["rev", "collection", "rkey", "cid", "prev"], "nullable": ["cid", "prev"], "properties": { @@ -99,15 +93,17 @@ }, "cid": { "type": "string", - "format": "cid" + "format": "cid", + "description": "CID of the record after the operation. Null for deletes." }, "prev": { "type": "string", - "format": "cid" + "format": "cid", + "description": "CID of the record before the operation. Null for creates." }, "value": { "type": "unknown", - "description": "The record's current value, inlined for create and update operations. Omitted when excludeValues is set, for deletes, or when the value has been superseded by a later operation." + "description": "Omitted for deletes, if excludeValues is set, or if the record has since changed." } } } diff --git a/packages/space-conformance/lexicons/space/listRepos.json b/packages/space-conformance/lexicons/space/listRepos.json deleted file mode 100644 index 357e96b..0000000 --- a/packages/space-conformance/lexicons/space/listRepos.json +++ /dev/null @@ -1,91 +0,0 @@ -{ - "lexicon": 1, - "id": "com.atproto.space.listRepos", - "defs": { - "main": { - "type": "query", - "description": "List the known repos that hold data in a space (the writer set), with each repo's current repoRev and commit data. Served by the space host. This is the sync boundary, not an access-control list: it enumerates only writers, never readers. The set is what the authority claims from write notifications and is not itself authoritative; a repo's host is the source of truth.", - "parameters": { - "type": "params", - "required": ["space"], - "properties": { - "space": { - "type": "string", - "format": "space-ref", - "description": "Reference to the space." - }, - "limit": { - "type": "integer", - "minimum": 1, - "maximum": 1000, - "default": 100, - "description": "Maximum number of repos to return." - }, - "cursor": { - "type": "string", - "description": "Return repos updated after this space revision (exclusive). Use a previous response's cursor or a previously processed spaceRev." - } - } - }, - "output": { - "encoding": "application/json", - "schema": { - "type": "object", - "required": ["repos"], - "properties": { - "repos": { - "type": "array", - "items": { - "type": "ref", - "ref": "#repo" - }, - "description": "Returned in ascending spaceRev order. A repo may reappear if updated while paginating." - }, - "cursor": { - "type": "string", - "description": "Pass this cursor on the next request. Omitted when no repos are returned." - } - } - } - }, - "errors": [ - { - "name": "SpaceNotFound" - }, - { - "name": "RepoTakendown", - "description": "The space authority has been taken down." - }, - { - "name": "RepoDeactivated", - "description": "The space authority has been deactivated." - } - ] - }, - "repo": { - "type": "object", - "required": ["did", "repoRev", "data", "spaceRev"], - "properties": { - "did": { - "type": "string", - "format": "did", - "description": "The DID of a repo that holds data in the space." - }, - "repoRev": { - "type": "string", - "description": "The repo's current revision (TID), as last reported to the authority. May lag the repo host, which is the source of truth.", - "format": "tid" - }, - "data": { - "type": "bytes", - "description": "The repo's current commit data (sha256 of the LtHash state), as last reported to the authority." - }, - "spaceRev": { - "type": "string", - "format": "tid", - "description": "The space revision at which this repo was last updated." - } - } - } - } -} diff --git a/packages/space-conformance/lexicons/space/listSpaces.json b/packages/space-conformance/lexicons/space/listSpaces.json index 959a80a..432ed45 100644 --- a/packages/space-conformance/lexicons/space/listSpaces.json +++ b/packages/space-conformance/lexicons/space/listSpaces.json @@ -4,26 +4,24 @@ "defs": { "main": { "type": "query", - "description": "List the spaces the authenticated user holds a repo in (i.e. spaces the user has written data to) or is the authority of, optionally filtered by type and/or authority DID. Note this is not 'spaces I'm a member of' — a member's PDS only tracks spaces its user has written to. Requires auth, implemented by PDS.", + "description": "List spaces that the authenticated account has written to or is the authority for. Requires auth, implemented by PDS.", "parameters": { "type": "params", "properties": { - "spaceType": { + "spaceDid": { "type": "string", - "format": "nsid", - "description": "Filter to spaces of this space type." + "format": "did", + "description": "Filter to spaces with this DID as their authority." }, - "did": { + "spaceType": { "type": "string", - "format": "did", - "description": "Filter to spaces under this authority DID." + "format": "nsid" }, "limit": { "type": "integer", "minimum": 1, "maximum": 100, - "default": 50, - "description": "The number of spaces to return." + "default": 50 }, "cursor": { "type": "string" @@ -48,16 +46,34 @@ } } } - } + }, + "errors": [ + { + "name": "InvalidCursor" + } + ] }, "spaceView": { "type": "object", - "required": ["uri"], + "required": ["space"], "properties": { - "uri": { + "space": { + "type": "string", + "format": "space-ref" + }, + "repoRev": { + "type": "string", + "format": "tid", + "description": "The current revision of the account's repo in the space, if it has one." + }, + "data": { + "type": "bytes", + "description": "The current commit data of the account's repo in the space, if it has one." + }, + "spaceRev": { "type": "string", - "format": "space-ref", - "description": "URI of the space." + "format": "tid", + "description": "The current revision of the space. Only included if the account is the space's authority." } } } diff --git a/packages/space-conformance/lexicons/space/listWriters.json b/packages/space-conformance/lexicons/space/listWriters.json new file mode 100644 index 0000000..9a72768 --- /dev/null +++ b/packages/space-conformance/lexicons/space/listWriters.json @@ -0,0 +1,66 @@ +{ + "lexicon": 1, + "id": "com.atproto.space.listWriters", + "defs": { + "main": { + "type": "query", + "description": "List the repos in a space's writer set, with the latest known state of each: its current revision, or its removal from the writer set. Requires a space credential, implemented by the space host.", + "parameters": { + "type": "params", + "required": ["space"], + "properties": { + "space": { + "type": "string", + "format": "space-ref" + }, + "limit": { + "type": "integer", + "minimum": 1, + "maximum": 1000, + "default": 100 + }, + "cursor": { + "type": "string", + "description": "Return repos updated after this space revision. Removed repos may be garbage collected after 72 hrs, so a syncer whose last seen space revision is older should list the whole writer set instead." + } + } + }, + "output": { + "encoding": "application/json", + "schema": { + "type": "object", + "required": ["repos"], + "properties": { + "repos": { + "type": "array", + "items": { + "type": "union", + "refs": [ + "com.atproto.space.defs#repoWrite", + "com.atproto.space.defs#repoRemoved" + ] + }, + "description": "The latest update to each repo, ordered by spaceRev, ascending. prevSpaceRev is not set." + }, + "cursor": { + "type": "string" + } + } + } + }, + "errors": [ + { + "name": "SpaceNotFound" + }, + { + "name": "RepoTakendown", + "description": "The space authority has been taken down." + }, + { + "name": "RepoDeactivated", + "description": "The space authority has been deactivated." + } + ] + } + } +} diff --git a/packages/space-conformance/lexicons/space/notifyCredentialRevoked.json b/packages/space-conformance/lexicons/space/notifyCredentialsRevoked.json similarity index 58% rename from packages/space-conformance/lexicons/space/notifyCredentialRevoked.json rename to packages/space-conformance/lexicons/space/notifyCredentialsRevoked.json index 6259d44..03906b2 100644 --- a/packages/space-conformance/lexicons/space/notifyCredentialRevoked.json +++ b/packages/space-conformance/lexicons/space/notifyCredentialsRevoked.json @@ -1,10 +1,10 @@ { "lexicon": 1, - "id": "com.atproto.space.notifyCredentialRevoked", + "id": "com.atproto.space.notifyCredentialsRevoked", "defs": { "main": { "type": "procedure", - "description": "Notify a repo host that the space authority has revoked one or more credentials. Authenticated with service auth from the space authority, addressed to the repo DID.", + "description": "Notify a repo host that space credentials have been revoked. Sent by the space host. Requires service auth, implemented by PDS.", "input": { "encoding": "application/json", "schema": { @@ -13,14 +13,13 @@ "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space." + "format": "space-ref" }, "credentials": { "type": "array", "minLength": 1, "maxLength": 100, - "description": "The jti of the revoked credentials.", + "description": "The IDs (jti) of the revoked credentials.", "items": { "type": "string", "minLength": 1 } } } diff --git a/packages/space-conformance/lexicons/space/notifyRepoUpdate.json b/packages/space-conformance/lexicons/space/notifyRepoUpdate.json new file mode 100644 index 0000000..2b2bbd9 --- /dev/null +++ b/packages/space-conformance/lexicons/space/notifyRepoUpdate.json @@ -0,0 +1,43 @@ +{ + "lexicon": 1, + "id": "com.atproto.space.notifyRepoUpdate", + "defs": { + "main": { + "type": "procedure", + "description": "Notify the space host that a space repo has been updated. Sent by repo hosts, with service auth.", + "input": { + "encoding": "application/json", + "schema": { + "type": "object", + "required": ["space", "repo", "repoRev", "data"], + "properties": { + "space": { + "type": "string", + "format": "space-ref" + }, + "repo": { + "type": "string", + "format": "did" + }, + "repoRev": { + "type": "string", + "format": "tid" + }, + "data": { + "type": "bytes" + } + } + } + }, + "errors": [ + { + "name": "SpaceNotFound" + }, + { + "name": "FutureRev", + "description": "The repo revision is too far in the future." + } + ] + } + } +} diff --git a/packages/space-conformance/lexicons/space/notifySpaceDeleted.json b/packages/space-conformance/lexicons/space/notifySpaceDeleted.json deleted file mode 100644 index dc50a9c..0000000 --- a/packages/space-conformance/lexicons/space/notifySpaceDeleted.json +++ /dev/null @@ -1,24 +0,0 @@ -{ - "lexicon": 1, - "id": "com.atproto.space.notifySpaceDeleted", - "defs": { - "main": { - "type": "procedure", - "description": "Notify a syncing service that a space was deleted and its copy should be dropped. Sent by the space authority to registered services, retried until delivered or the registration expires. Requires service auth.", - "input": { - "encoding": "application/json", - "schema": { - "type": "object", - "required": ["space"], - "properties": { - "space": { - "type": "string", - "format": "space-ref", - "description": "Reference to the deleted space." - } - } - } - } - } - } -} diff --git a/packages/space-conformance/lexicons/space/notifySpaceUpdate.json b/packages/space-conformance/lexicons/space/notifySpaceUpdate.json new file mode 100644 index 0000000..12ef671 --- /dev/null +++ b/packages/space-conformance/lexicons/space/notifySpaceUpdate.json @@ -0,0 +1,53 @@ +{ + "lexicon": 1, + "id": "com.atproto.space.notifySpaceUpdate", + "defs": { + "main": { + "type": "procedure", + "description": "Notify a syncing service of an update to a space. Sent by the space host to the notification endpoint registered through authorizeSpaceSync.", + "input": { + "encoding": "application/json", + "schema": { + "type": "object", + "required": ["space", "token", "update"], + "properties": { + "space": { + "type": "string", + "format": "space-ref" + }, + "token": { + "type": "string", + "maxLength": 512, + "description": "The token the endpoint was registered with." + }, + "update": { + "type": "union", + "refs": [ + "com.atproto.space.defs#repoWrite", + "com.atproto.space.defs#repoRemoved", + "#spaceDeleted", + "#registrationExpired" + ] + } + } + } + } + }, + "spaceDeleted": { + "type": "object", + "description": "The space has been deleted. Confirm with authorizeSpaceSync before dropping its data.", + "properties": {} + }, + "registrationExpired": { + "type": "object", + "description": "The endpoint's registration has expired. Sent in place of the first update after expiry. Call authorizeSpaceSync to keep receiving notifications.", + "required": ["spaceRev"], + "properties": { + "spaceRev": { + "type": "string", + "format": "tid" + } + } + } + } +} diff --git a/packages/space-conformance/lexicons/space/notifyWrite.json b/packages/space-conformance/lexicons/space/notifyWrite.json deleted file mode 100644 index c93cb57..0000000 --- a/packages/space-conformance/lexicons/space/notifyWrite.json +++ /dev/null @@ -1,57 +0,0 @@ -{ - "lexicon": 1, - "id": "com.atproto.space.notifyWrite", - "defs": { - "main": { - "type": "procedure", - "description": "Notify that a repo in a space has advanced. Repo hosts reliably deliver their latest state to the space host, which sequences updates and forwards them to registered syncers with reasonable-effort delivery. Authenticated with service auth.", - "input": { - "encoding": "application/json", - "schema": { - "type": "object", - "required": ["space", "repo", "repoRev", "data"], - "properties": { - "space": { - "type": "string", - "format": "space-ref", - "description": "Reference to the space." - }, - "repo": { - "type": "string", - "format": "did", - "description": "The DID of the account whose repo advanced." - }, - "repoRev": { - "type": "string", - "description": "The repo revision after the write.", - "format": "tid" - }, - "data": { - "type": "bytes", - "description": "The repo's current commit data (sha256 of the LtHash state) after the write. Lets the space host maintain each repo's commit data for listRepos." - }, - "spaceRev": { - "type": "string", - "format": "tid", - "description": "The space revision assigned by the space host. Present only on notifications forwarded to syncers." - }, - "prevSpaceRev": { - "type": "string", - "format": "tid", - "description": "The previous space revision. Omitted on the first update in a space. A gap indicates missed notifications; recover using listRepos with cursor." - } - } - } - }, - "errors": [ - { - "name": "SpaceNotFound" - }, - { - "name": "FutureRev", - "description": "The repo revision exceeds the permitted clock skew." - } - ] - } - } -} diff --git a/packages/space-conformance/lexicons/space/policy.json b/packages/space-conformance/lexicons/space/policy.json index b7fedcd..028d1f5 100644 --- a/packages/space-conformance/lexicons/space/policy.json +++ b/packages/space-conformance/lexicons/space/policy.json @@ -4,7 +4,7 @@ "defs": { "main": { "type": "record", - "description": "The policy governing a space, optionally published in the space so that syncers can view a description of the space's policy. Written to the space authority's own repo in the space, and kept in sync with the policy. Only authoritative in the authority's repo.", + "description": "A published copy of a space's policy. Only authoritative in the space authority's repo.", "key": "literal:self", "record": { "type": "object", @@ -12,7 +12,7 @@ "properties": { "policy": { "type": "union", - "description": "The current policy governing the space, including its configuration.", + "description": "PDSes must support all of the listed policies. Other space hosts may support only some of them, and any host may support policies beyond those listed.", "refs": [ "com.atproto.personalspace.policy", "com.atproto.memberspace.policy", diff --git a/packages/space-conformance/lexicons/space/putRecord.json b/packages/space-conformance/lexicons/space/putRecord.json index aa8c7d6..df09a74 100644 --- a/packages/space-conformance/lexicons/space/putRecord.json +++ b/packages/space-conformance/lexicons/space/putRecord.json @@ -4,7 +4,7 @@ "defs": { "main": { "type": "procedure", - "description": "Write a record in a permissioned space, creating or updating it as needed. Requires auth, implemented by PDS.", + "description": "Write a record in a space repo, creating or updating it as needed. Requires auth, implemented by PDS.", "input": { "encoding": "application/json", "schema": { @@ -13,32 +13,26 @@ "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space." + "format": "space-ref" }, "repo": { "type": "string", - "format": "did", - "description": "The DID of the repo to write to (the authenticated member)." + "format": "did" }, "collection": { "type": "string", - "format": "nsid", - "description": "The NSID of the record collection." + "format": "nsid" }, "rkey": { "type": "string", - "format": "record-key", - "description": "The Record Key.", - "maxLength": 512 + "format": "record-key" }, "validate": { "type": "boolean", "description": "Can be set to 'false' to skip Lexicon schema validation of record data, 'true' to require it, or leave unset to validate only for known Lexicons." }, "record": { - "type": "unknown", - "description": "The record to write." + "type": "unknown" } } } @@ -51,8 +45,7 @@ "properties": { "uri": { "type": "string", - "format": "at-uri", - "description": "URI of the written record." + "format": "at-uri" }, "cid": { "type": "string", diff --git a/packages/space-conformance/lexicons/space/registerNotify.json b/packages/space-conformance/lexicons/space/registerNotify.json deleted file mode 100644 index 91b0003..0000000 --- a/packages/space-conformance/lexicons/space/registerNotify.json +++ /dev/null @@ -1,49 +0,0 @@ -{ - "lexicon": 1, - "id": "com.atproto.space.registerNotify", - "defs": { - "main": { - "type": "procedure", - "description": "Register a service to be notified of writes to any repo in a space. Called on the space host. The registering service is named by its service identifier rather than a bare URL, because notifyWrite is delivered with service auth addressed to that identifier; the delivery endpoint is resolved from the service's DID document. Authenticated with a space credential. Re-registering an existing service replaces its registration and extends the expiry.", - "input": { - "encoding": "application/json", - "schema": { - "type": "object", - "required": ["space", "service"], - "properties": { - "space": { - "type": "string", - "format": "space-ref", - "description": "Reference to the space." - }, - "service": { - "type": "string", - "description": "Service identifier of the subscriber: a DID with an optional service fragment naming the entry in its DID document to deliver to (e.g. 'did:web:syncer.example.com#atproto_space_syncer'). notifyWrite calls are addressed to this identifier." - } - } - } - }, - "output": { - "encoding": "application/json", - "schema": { - "type": "object", - "required": ["expiresAt"], - "properties": { - "expiresAt": { - "type": "string", - "format": "datetime", - "description": "When the registration expires. May be later than the expiry of the space credential the request was authenticated with; renew before this time to stay subscribed." - } - } - } - }, - "errors": [ - { "name": "SpaceNotFound" }, - { - "name": "ServiceNotResolvable", - "description": "The service identifier could not be resolved to a DID document with a matching service endpoint." - } - ] - } - } -} diff --git a/packages/space-conformance/lexicons/space/removeWriter.json b/packages/space-conformance/lexicons/space/removeWriter.json index e3d05c1..0264669 100644 --- a/packages/space-conformance/lexicons/space/removeWriter.json +++ b/packages/space-conformance/lexicons/space/removeWriter.json @@ -4,22 +4,20 @@ "defs": { "main": { "type": "procedure", - "description": "Remove an account from a space's writer set, so that listRepos no longer lists it. The account is tracked again if it later writes while still authorized. Idempotent: succeeds whether or not the account was in the writer set. Requires auth as an account that may manage the space.", + "description": "Remove an account from a space's writer set, as returned by listWriters. The removal is sent to registered syncers. The account is added back if it makes another authorized write to the space. Does nothing if the account is not in the writer set. Requires auth as the space authority, implemented by PDS.", "input": { "encoding": "application/json", "schema": { "type": "object", - "required": ["space", "did"], + "required": ["space", "repo"], "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space." + "format": "space-ref" }, - "did": { + "repo": { "type": "string", - "format": "did", - "description": "The DID of the writer to remove." + "format": "did" } } } @@ -29,7 +27,7 @@ "name": "SpaceNotFound" }, { - "name": "NotSpaceOwner" + "name": "NotAuthorized" } ] } diff --git a/packages/space-conformance/lexicons/space/unregisterNotify.json b/packages/space-conformance/lexicons/space/unregisterNotify.json deleted file mode 100644 index 22effd8..0000000 --- a/packages/space-conformance/lexicons/space/unregisterNotify.json +++ /dev/null @@ -1,29 +0,0 @@ -{ - "lexicon": 1, - "id": "com.atproto.space.unregisterNotify", - "defs": { - "main": { - "type": "procedure", - "description": "Withdraw a write-notification registration made through registerNotify. Called on the space host. Idempotent: succeeds whether or not a matching registration existed. Registrations also lapse on their own at the expiry returned by registerNotify, so this is for explicit withdrawal rather than cleanup. Authenticated with a space credential.", - "input": { - "encoding": "application/json", - "schema": { - "type": "object", - "required": ["space", "service"], - "properties": { - "space": { - "type": "string", - "format": "space-ref", - "description": "Reference to the space." - }, - "service": { - "type": "string", - "description": "Service identifier of the subscriber to remove, as passed to registerNotify." - } - } - } - }, - "errors": [{ "name": "SpaceNotFound" }] - } - } -} diff --git a/packages/space-conformance/lexicons/space/updateSpace.json b/packages/space-conformance/lexicons/space/updateSpace.json index 4ce170a..781c723 100644 --- a/packages/space-conformance/lexicons/space/updateSpace.json +++ b/packages/space-conformance/lexicons/space/updateSpace.json @@ -4,7 +4,7 @@ "defs": { "main": { "type": "procedure", - "description": "Replace the policy of a space wholesale. A policy with a different $type migrates the space, discarding state held by the previous policy (such as a member list). The authenticated user must be the space owner. Requires auth, implemented by PDS.", + "description": "Replace the policy of a space. Changing to a different policy type discards state held by the previous policy, such as a member list. Requires auth as the space authority, implemented by PDS.", "input": { "encoding": "application/json", "schema": { @@ -13,12 +13,11 @@ "properties": { "space": { "type": "string", - "format": "space-ref", - "description": "Reference to the space to update." + "format": "space-ref" }, "policy": { "type": "union", - "description": "The policy governing the space, including its configuration. Replaces the current policy.", + "description": "PDSes must support all of the listed policies. Other space hosts may support only some of them, and any host may support policies beyond those listed.", "refs": [ "com.atproto.personalspace.policy", "com.atproto.memberspace.policy", @@ -33,11 +32,10 @@ "name": "SpaceNotFound" }, { - "name": "NotSpaceOwner" + "name": "NotAuthorized" }, { - "name": "UnsupportedPolicy", - "description": "The requested policy is not one the host implements." + "name": "UnsupportedPolicy" } ] } diff --git a/packages/space-conformance/package.json b/packages/space-conformance/package.json index 5a8b5c8..ff5777f 100644 --- a/packages/space-conformance/package.json +++ b/packages/space-conformance/package.json @@ -21,10 +21,10 @@ }, "devDependencies": { "@arethetypeswrong/cli": "^0.18.2", - "@atproto/crypto": "0.0.0-spaces-alpha-20261105160032", - "@atproto/lex-data": "0.0.0-spaces-alpha-20261105160032", - "@atproto/oauth-client-node": "0.0.0-spaces-alpha-20261105160032", - "@atproto/space": "0.0.0-spaces-alpha-20261105160032", + "@atproto/crypto": "0.0.0-spaces-alpha-20261112204144", + "@atproto/lex-data": "0.0.0-spaces-alpha-20261112204144", + "@atproto/oauth-client-node": "0.0.0-spaces-alpha-20261112204144", + "@atproto/space": "0.0.0-spaces-alpha-20261112204144", "publint": "^0.3.16", "tsdown": "^0.18.3", "typescript": "^5.9.3", diff --git a/packages/space-conformance/src/lexicons.ts b/packages/space-conformance/src/lexicons.ts index 6152e8d..f9b7ce5 100644 --- a/packages/space-conformance/src/lexicons.ts +++ b/packages/space-conformance/src/lexicons.ts @@ -5,7 +5,9 @@ */ import space_applyWrites from "../lexicons/space/applyWrites.json" with { type: "json" }; +import space_authorizeSpaceSync from "../lexicons/space/authorizeSpaceSync.json" with { type: "json" }; import space_clearRecords from "../lexicons/space/clearRecords.json" with { type: "json" }; +import space_confirmRegistration from "../lexicons/space/confirmRegistration.json" with { type: "json" }; import space_createRecord from "../lexicons/space/createRecord.json" with { type: "json" }; import space_createSpace from "../lexicons/space/createSpace.json" with { type: "json" }; import space_defs from "../lexicons/space/defs.json" with { type: "json" }; @@ -18,30 +20,28 @@ import space_getLatestCommit from "../lexicons/space/getLatestCommit.json" with import space_getRecord from "../lexicons/space/getRecord.json" with { type: "json" }; import space_getRepo from "../lexicons/space/getRepo.json" with { type: "json" }; import space_getSpace from "../lexicons/space/getSpace.json" with { type: "json" }; -import space_getSpaceCredential from "../lexicons/space/getSpaceCredential.json" with { type: "json" }; import space_importRepo from "../lexicons/space/importRepo.json" with { type: "json" }; import space_importSpaceMeta from "../lexicons/space/importSpaceMeta.json" with { type: "json" }; import space_listBlobs from "../lexicons/space/listBlobs.json" with { type: "json" }; import space_listRecords from "../lexicons/space/listRecords.json" with { type: "json" }; import space_listRepoOps from "../lexicons/space/listRepoOps.json" with { type: "json" }; -import space_listRepos from "../lexicons/space/listRepos.json" with { type: "json" }; import space_listSpaces from "../lexicons/space/listSpaces.json" with { type: "json" }; -import space_notifyCredentialRevoked from "../lexicons/space/notifyCredentialRevoked.json" with { type: "json" }; -import space_notifySpaceDeleted from "../lexicons/space/notifySpaceDeleted.json" with { type: "json" }; -import space_notifyWrite from "../lexicons/space/notifyWrite.json" with { type: "json" }; +import space_listWriters from "../lexicons/space/listWriters.json" with { type: "json" }; +import space_notifyCredentialsRevoked from "../lexicons/space/notifyCredentialsRevoked.json" with { type: "json" }; +import space_notifyRepoUpdate from "../lexicons/space/notifyRepoUpdate.json" with { type: "json" }; +import space_notifySpaceUpdate from "../lexicons/space/notifySpaceUpdate.json" with { type: "json" }; import space_policy from "../lexicons/space/policy.json" with { type: "json" }; import space_putRecord from "../lexicons/space/putRecord.json" with { type: "json" }; -import space_registerNotify from "../lexicons/space/registerNotify.json" with { type: "json" }; import space_removeWriter from "../lexicons/space/removeWriter.json" with { type: "json" }; -import space_unregisterNotify from "../lexicons/space/unregisterNotify.json" with { type: "json" }; import space_updateSpace from "../lexicons/space/updateSpace.json" with { type: "json" }; +import memberspace_defs from "../lexicons/memberspace/defs.json" with { type: "json" }; import memberspace_listMembers from "../lexicons/memberspace/listMembers.json" with { type: "json" }; import memberspace_member from "../lexicons/memberspace/member.json" with { type: "json" }; import memberspace_policy from "../lexicons/memberspace/policy.json" with { type: "json" }; -import memberspace_putMember from "../lexicons/memberspace/putMember.json" with { type: "json" }; -import memberspace_removeMember from "../lexicons/memberspace/removeMember.json" with { type: "json" }; +import memberspace_putMembers from "../lexicons/memberspace/putMembers.json" with { type: "json" }; +import memberspace_removeMembers from "../lexicons/memberspace/removeMembers.json" with { type: "json" }; import personalspace_policy from "../lexicons/personalspace/policy.json" with { type: "json" }; -import managedspace_checkUserAccess from "../lexicons/managedspace/checkUserAccess.json" with { type: "json" }; +import managedspace_checkAccess from "../lexicons/managedspace/checkAccess.json" with { type: "json" }; import managedspace_policy from "../lexicons/managedspace/policy.json" with { type: "json" }; export interface LexiconDoc { @@ -52,7 +52,9 @@ export interface LexiconDoc { export const lexicons: LexiconDoc[] = [ space_applyWrites as LexiconDoc, + space_authorizeSpaceSync as LexiconDoc, space_clearRecords as LexiconDoc, + space_confirmRegistration as LexiconDoc, space_createRecord as LexiconDoc, space_createSpace as LexiconDoc, space_defs as LexiconDoc, @@ -65,29 +67,27 @@ export const lexicons: LexiconDoc[] = [ space_getRecord as LexiconDoc, space_getRepo as LexiconDoc, space_getSpace as LexiconDoc, - space_getSpaceCredential as LexiconDoc, space_importRepo as LexiconDoc, space_importSpaceMeta as LexiconDoc, space_listBlobs as LexiconDoc, space_listRecords as LexiconDoc, space_listRepoOps as LexiconDoc, - space_listRepos as LexiconDoc, space_listSpaces as LexiconDoc, - space_notifyCredentialRevoked as LexiconDoc, - space_notifySpaceDeleted as LexiconDoc, - space_notifyWrite as LexiconDoc, + space_listWriters as LexiconDoc, + space_notifyCredentialsRevoked as LexiconDoc, + space_notifyRepoUpdate as LexiconDoc, + space_notifySpaceUpdate as LexiconDoc, space_policy as LexiconDoc, space_putRecord as LexiconDoc, - space_registerNotify as LexiconDoc, space_removeWriter as LexiconDoc, - space_unregisterNotify as LexiconDoc, space_updateSpace as LexiconDoc, + memberspace_defs as LexiconDoc, memberspace_listMembers as LexiconDoc, memberspace_member as LexiconDoc, memberspace_policy as LexiconDoc, - memberspace_putMember as LexiconDoc, - memberspace_removeMember as LexiconDoc, + memberspace_putMembers as LexiconDoc, + memberspace_removeMembers as LexiconDoc, personalspace_policy as LexiconDoc, - managedspace_checkUserAccess as LexiconDoc, + managedspace_checkAccess as LexiconDoc, managedspace_policy as LexiconDoc, ]; diff --git a/packages/spaces/package.json b/packages/spaces/package.json index 0afed3f..b0de511 100644 --- a/packages/spaces/package.json +++ b/packages/spaces/package.json @@ -25,12 +25,12 @@ }, "devDependencies": { "@arethetypeswrong/cli": "^0.18.2", - "@atproto/crypto": "0.0.0-spaces-alpha-20261105160032", + "@atproto/crypto": "0.0.0-spaces-alpha-20261112204144", "@atproto/jwk-jose": "^0.2.1", - "@atproto/lex-cbor": "0.0.0-spaces-alpha-20261105160032", - "@atproto/lex-data": "0.0.0-spaces-alpha-20261105160032", - "@atproto/lex-json": "0.0.0-spaces-alpha-20261105160032", - "@atproto/space": "0.0.0-spaces-alpha-20261105160032", + "@atproto/lex-cbor": "0.0.0-spaces-alpha-20261112204144", + "@atproto/lex-data": "0.0.0-spaces-alpha-20261112204144", + "@atproto/lex-json": "0.0.0-spaces-alpha-20261112204144", + "@atproto/space": "0.0.0-spaces-alpha-20261112204144", "@cloudflare/vitest-pool-workers": "^0.16.9", "@cloudflare/workers-types": "^4.20260524.1", "@getcirrus/space-conformance": "workspace:*", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index 2ecd981..9587ce5 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -5,17 +5,21 @@ settings: excludeLinksFromLockfile: false overrides: - '@atproto/lex': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-resolver': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-client': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-schema': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-builder': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-installer': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-document': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-cbor@^0.0.0-spaces-alpha': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-data@^0.0.0-spaces-alpha': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-json@^0.0.0-spaces-alpha': 0.0.0-spaces-alpha-20261105160032 - '@atproto/star': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-resolver': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-client': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-builder': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-installer': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-document': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-cbor@^0.0.0-spaces-alpha': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-data@^0.0.0-spaces-alpha': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-json@^0.0.0-spaces-alpha': 0.0.0-spaces-alpha-20261112204144 + '@atproto/star': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-rpc@^0.0.0-spaces-alpha': 0.0.0-spaces-alpha-20261112204144 + '@atproto/oauth-resolver@^0.0.0-spaces-alpha': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-password-session@^0.0.0-spaces-alpha': 0.0.0-spaces-alpha-20261112204144 + '@atproto/bsync@^0.0.0-spaces-alpha': 0.0.0-spaces-alpha-20261112204144 importers: @@ -41,7 +45,7 @@ importers: version: 5.9.3 vitest: specifier: 4.1.0-beta.1 - version: 4.1.0-beta.1(@opentelemetry/api@1.9.1)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0) + version: 4.1.0-beta.1(@opentelemetry/api@1.10.0)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0) apps/check: dependencies: @@ -187,8 +191,8 @@ importers: specifier: ^0.1.1 version: 0.1.4 '@atproto/oauth-scopes': - specifier: 0.0.0-spaces-alpha-20261105160032 - version: 0.0.0-spaces-alpha-20261105160032 + specifier: 0.0.0-spaces-alpha-20261112204144 + version: 0.0.0-spaces-alpha-20261112204144 '@atproto/oauth-types': specifier: ^0.6.3 version: 0.6.3 @@ -222,7 +226,7 @@ importers: version: 5.9.3 vitest: specifier: 4.1.0-beta.1 - version: 4.1.0-beta.1(@opentelemetry/api@1.9.1)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0) + version: 4.1.0-beta.1(@opentelemetry/api@1.10.0)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0) packages/pds: dependencies: @@ -306,14 +310,14 @@ importers: specifier: ^0.18.9 version: 0.18.20 '@atproto/space': - specifier: 0.0.0-spaces-alpha-20261105160032 - version: 0.0.0-spaces-alpha-20261105160032 + specifier: 0.0.0-spaces-alpha-20261112204144 + version: 0.0.0-spaces-alpha-20261112204144 '@cloudflare/vite-plugin': specifier: ^1.17.0 version: 1.23.1(vite@6.4.1(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0))(workerd@1.20260521.1)(wrangler@4.94.0(@cloudflare/workers-types@4.20260524.1)) '@cloudflare/vitest-pool-workers': specifier: ^0.16.9 - version: 0.16.9(@cloudflare/workers-types@4.20260524.1)(@vitest/runner@4.1.7)(@vitest/snapshot@4.1.7)(vitest@4.1.0-beta.1(@opentelemetry/api@1.9.1)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0)) + version: 0.16.9(@cloudflare/workers-types@4.20260524.1)(@vitest/runner@4.1.7)(@vitest/snapshot@4.1.7)(vitest@4.1.0-beta.1(@opentelemetry/api@1.10.0)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0)) '@cloudflare/workers-types': specifier: ^4.20260524.1 version: 4.20260524.1 @@ -346,7 +350,7 @@ importers: version: 6.4.1(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0) vitest: specifier: 4.1.0-beta.1 - version: 4.1.0-beta.1(@opentelemetry/api@1.9.1)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0) + version: 4.1.0-beta.1(@opentelemetry/api@1.10.0)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0) wrangler: specifier: ^4.93.0 version: 4.94.0(@cloudflare/workers-types@4.20260524.1) @@ -360,17 +364,17 @@ importers: specifier: ^0.18.2 version: 0.18.2 '@atproto/crypto': - specifier: 0.0.0-spaces-alpha-20261105160032 - version: 0.0.0-spaces-alpha-20261105160032 + specifier: 0.0.0-spaces-alpha-20261112204144 + version: 0.0.0-spaces-alpha-20261112204144 '@atproto/lex-data': - specifier: 0.0.0-spaces-alpha-20261105160032 - version: 0.0.0-spaces-alpha-20261105160032 + specifier: 0.0.0-spaces-alpha-20261112204144 + version: 0.0.0-spaces-alpha-20261112204144 '@atproto/oauth-client-node': - specifier: 0.0.0-spaces-alpha-20261105160032 - version: 0.0.0-spaces-alpha-20261105160032 + specifier: 0.0.0-spaces-alpha-20261112204144 + version: 0.0.0-spaces-alpha-20261112204144 '@atproto/space': - specifier: 0.0.0-spaces-alpha-20261105160032 - version: 0.0.0-spaces-alpha-20261105160032 + specifier: 0.0.0-spaces-alpha-20261112204144 + version: 0.0.0-spaces-alpha-20261112204144 publint: specifier: ^0.3.16 version: 0.3.17 @@ -382,13 +386,13 @@ importers: version: 5.9.3 vitest: specifier: 4.1.0-beta.1 - version: 4.1.0-beta.1(@opentelemetry/api@1.9.1)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0) + version: 4.1.0-beta.1(@opentelemetry/api@1.10.0)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0) packages/space-conformance-matrix: devDependencies: '@atproto/dev-env': - specifier: 0.0.0-spaces-alpha-20261105160032 - version: 0.0.0-spaces-alpha-20261105160032(@opentelemetry/api@1.9.1)(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) + specifier: 0.0.0-spaces-alpha-20261112204144 + version: 0.0.0-spaces-alpha-20261112204144(@opentelemetry/api@1.10.0)(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) '@getcirrus/space-conformance': specifier: workspace:* version: link:../space-conformance @@ -397,7 +401,7 @@ importers: version: 5.9.3 vitest: specifier: 4.1.0-beta.1 - version: 4.1.0-beta.1(@opentelemetry/api@1.9.1)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0) + version: 4.1.0-beta.1(@opentelemetry/api@1.10.0)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0) packages/spaces: dependencies: @@ -421,26 +425,26 @@ importers: specifier: ^0.18.2 version: 0.18.2 '@atproto/crypto': - specifier: 0.0.0-spaces-alpha-20261105160032 - version: 0.0.0-spaces-alpha-20261105160032 + specifier: 0.0.0-spaces-alpha-20261112204144 + version: 0.0.0-spaces-alpha-20261112204144 '@atproto/jwk-jose': specifier: ^0.2.1 version: 0.2.4 '@atproto/lex-cbor': - specifier: 0.0.0-spaces-alpha-20261105160032 - version: 0.0.0-spaces-alpha-20261105160032 + specifier: 0.0.0-spaces-alpha-20261112204144 + version: 0.0.0-spaces-alpha-20261112204144 '@atproto/lex-data': - specifier: 0.0.0-spaces-alpha-20261105160032 - version: 0.0.0-spaces-alpha-20261105160032 + specifier: 0.0.0-spaces-alpha-20261112204144 + version: 0.0.0-spaces-alpha-20261112204144 '@atproto/lex-json': - specifier: 0.0.0-spaces-alpha-20261105160032 - version: 0.0.0-spaces-alpha-20261105160032 + specifier: 0.0.0-spaces-alpha-20261112204144 + version: 0.0.0-spaces-alpha-20261112204144 '@atproto/space': - specifier: 0.0.0-spaces-alpha-20261105160032 - version: 0.0.0-spaces-alpha-20261105160032 + specifier: 0.0.0-spaces-alpha-20261112204144 + version: 0.0.0-spaces-alpha-20261112204144 '@cloudflare/vitest-pool-workers': specifier: ^0.16.9 - version: 0.16.9(@cloudflare/workers-types@4.20260524.1)(@vitest/runner@4.1.7)(@vitest/snapshot@4.1.7)(vitest@4.1.0-beta.1(@opentelemetry/api@1.9.1)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0)) + version: 0.16.9(@cloudflare/workers-types@4.20260524.1)(@vitest/runner@4.1.7)(@vitest/snapshot@4.1.7)(vitest@4.1.0-beta.1(@opentelemetry/api@1.10.0)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0)) '@cloudflare/workers-types': specifier: ^4.20260524.1 version: 4.20260524.1 @@ -458,7 +462,7 @@ importers: version: 5.9.3 vitest: specifier: 4.1.0-beta.1 - version: 4.1.0-beta.1(@opentelemetry/api@1.9.1)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0) + version: 4.1.0-beta.1(@opentelemetry/api@1.10.0)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0) wrangler: specifier: ^4.93.0 version: 4.94.0(@cloudflare/workers-types@4.20260524.1) @@ -653,36 +657,36 @@ packages: '@atcute/varint@2.0.2': resolution: {integrity: sha512-/+hS1juMgnmf6eL6lICUkTw7wcGTo3I+Q0L1PI521mUz77rGSC6nXAUNKtvm2wYJpuWdEGq+GILGoYkOArn0TQ==} - '@atproto-labs/did-resolver@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-pqiH1Niu/pyMQ0ja7n87VshYeVrzRlv0X2lM3u81CODoKAvU9bCnN9Jhhoh805dPzNonW2o2BeotsDcAM6U9dw==} + '@atproto-labs/did-resolver@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-j/bTiTl28Pk0L/4rj/IDeeHQdlJEiE9af/3X/WWudpzGSZuD6zJuWjYLS3OlzOKfDSdMoSHMEcUhVsVmb7XG2A==} engines: {node: '>=22'} - '@atproto-labs/fetch-node@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-Yjjo+eu0NNU+lFtPd2hekriSSPTdYVpx09rtSsTMWUpWh5wf4GmSpQgEeCG8mc66DKO59qL8xgSEpx/LJnyUqA==} + '@atproto-labs/fetch-node@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-dwLKw1JNXceuuSIybD14CNqf9DaPKVbIvwgsajnsVI+DwEJQcaWI+geTZEpUlXtyE0j5jyoaq6udu8M2utF35w==} engines: {node: '>=22'} - '@atproto-labs/fetch@0.3.5': - resolution: {integrity: sha512-iDFZEoNqfL17EVKE+uNzdUD7YF8LWhEhxeBtP6x+PNuAxoXv3ip9vLmB8nNzNxFwVn++FipfDtSiPqmziv1bdA==} + '@atproto-labs/fetch@0.4.2': + resolution: {integrity: sha512-9mgISMM2eY/w373HUNrtWq4onPzES1K6DaeAv9BDcEgovcKTkcI60H9Jjp38thU2i/dQaGpKrxmxR9qc0FZocg==} engines: {node: '>=22'} - '@atproto-labs/handle-resolver-node@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-O4fYwo4NrXEhcihLcvnOjYaltmwe8UeYiamBVTH5daTcvsuvH1fkZAxXbvBEGlxG0TSXfszwT/lyPX97ClNcZg==} + '@atproto-labs/handle-resolver-node@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-9+qnBfI1b+5mrbJeZC0ct7DbohyHegbSDKTEzBxWkOe6FQdiZl1bb0X1XgB7QZ3Ge/BHaUKIDeuAnlrVQOrC8A==} engines: {node: '>=22'} - '@atproto-labs/handle-resolver@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-lmLXB3xLPZLx3ljjHp1BySE9NHpSdWotfmZSf/csNRFqR+SouxN7hPIylTyNEe1fGcrSPS7nMXl5qFV+JDWweA==} + '@atproto-labs/handle-resolver@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-nB4K/QTO6p5VcGTFr1TBs/8TwKcFxL/5R71b6WyC8HEBU2f/uNvZMYTMOJr4C/aMdxJ4lShNPykQvKV9j5UhzQ==} engines: {node: '>=22'} - '@atproto-labs/identity-resolver@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-IpY6TbqGlJKikEdmgR27bsXeGFcp6aK6+dVXIQw17lg7Jjv1GrfvwT6CjEiCroBO896JEIknfp/qv4lu+YUerg==} + '@atproto-labs/identity-resolver@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-2vF2C9cLkXPhKzQEJ1Rbfa1vIjyQUoX8+47nqZYBbovRWiNCfhx1X7gJJ/oQE43ReA8jvm+K54GJzIiXF+bdzg==} engines: {node: '>=22'} - '@atproto-labs/opentelemetry-node@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-jr6sQf5/8PZ7EA6rjf1FIQ3YWoJL1sBYsXaFMQeXWTo7LfFxM6TbnAgyB0CTkfdGpItHbqOKok0VzEK2FOnrzQ==} - engines: {node: '>=22'} + '@atproto-labs/opentelemetry-node@0.5.0': + resolution: {integrity: sha512-tuiHRuKtvjYVHT0Y1fNevAhzPL64OFdYxPv34AhOcbTxEIAwSRaywYifVwKiH9hz03IcRDr5PDjqfnnTHqQlMQ==} + engines: {node: '>=22.15.0'} - '@atproto-labs/pipe@0.2.4': - resolution: {integrity: sha512-n67jCcrC+ouAeO10cWkpPzzLMlDi/lDCU30Us+LGqhOPhT6c4t5ASdBLQi9W3jUQtRzQBt3G9zipF+xKWNvVbw==} + '@atproto-labs/pipe@0.2.5': + resolution: {integrity: sha512-1R1nYs/nHmBcYa4yzTjk5H/46MF5nZm342Ha9kKQTOMp/fr2Yn67qD1pTXUS7L2Mx8AEf3m7Z/TTxRfnERLc8w==} engines: {node: '>=22'} '@atproto-labs/simple-store-memory@0.2.6': @@ -699,44 +703,42 @@ packages: resolution: {integrity: sha512-vfvoDhu6ds6BT3Pqe+d2/LBU1WpDRtt69y6zltlfMCoucPm82m1j50/Wb6xTvv+oZ+2j0JyZVXsmXQ12SWYQJg==} engines: {node: '>=22'} - '@atproto-labs/xrpc-utils@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-ETXqS9SJonX0a9gUPz6c45ulrbSiI/ehnlJa19R+a0jffXMJSZ4v03PUxi/OjJtCpJtv5gMcE/+jgqS1R1pxKA==} + '@atproto-labs/xrpc-utils@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-VwOS8yu1oUlDO2u3kPOBEs2hC8TGxQmYoPNfmbviVHpoFzJvSkvV+Nouo/G/agbkC47dBLeMZQW9BrRLbEWg9Q==} engines: {node: '>=22'} - '@atproto/api@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-/QrFn46Mh7w5ht1teDq10SLQ44e+NFoUKyEg1yLG7Aer7iXTAicjC1YcFvua9nORY46N3oljLS55nMcj8LqIcQ==} + '@atproto/api@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-niT3D6b7xwWW2YM3rQfDoE8Te82f5Ew4Jr/6zKaqKFAiyfmgvttjzC4094kYVCLPF7RyxWIxCRNeUznBBm5b1A==} engines: {node: '>=22'} '@atproto/api@0.18.20': resolution: {integrity: sha512-BZYZkh2VJIFCXEnc/vzKwAwWjAQQTgbNJ8FBxpBK+z+KYh99O0uPCsRYKoCQsRrnkgrhzdU9+g2G+7zanTIGbw==} - '@atproto/aws@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-HyOHMTcbUjHmNENccdpd8E8BiSZ21334rJ86vVySUqQCsYmx/ysVGNPu3FFiDllWn7LnV+homWUPC04UNuEeaA==} + '@atproto/aws@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-ncKUDUuswNE+j4eQq9i/DEhHnucYviJ6L0IxTunf444RTVlrYPjQqgNo5cqCF5LW3C+Rv3hX3IM5+m3h7xgGiA==} engines: {node: '>=22'} - '@atproto/bsky@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-U5BwLzG6UF/7b9YlsZ1YqlfcpHpwZFlpHYXp4xuJxTtYFi+xsxuHC9s8/C+cF44t8hQ/DNb72vrVV92hTzzijw==} + '@atproto/bsky@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-v53ob1kjtImvKME1WyzzdhbzonMqInZwEbOXdVWxEYg6K3Bone0ogB0RUNb3lqpy8o7WtqaRdVAE15XSt27Pdg==} engines: {node: '>=22'} - '@atproto/bsync@0.0.0': - resolution: {integrity: sha512-gv0dOnKGPhB0xyqLJhu3U3osZAPXLnaZQTRzwZlC5tm/Yc+c8myv2E3nIF+3Ojekh/cbg9SC8qRae4pEL0WHYg==} - - '@atproto/car@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-YDq+BHlfUkDsbOII+BuqQQFtsCSM3+SX6reVgigJbXOJMgn4EgQvb2L5IXLQNvSGMXBHK9Du2ltraOA9X7bBOg==} + '@atproto/bsync@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-wCFDwqKzErONcGt7gcnbkO9MJXNCl9+xMhLbq7ddQx8jK3EZTiJL9QlW45f5TT+f3TSqmcUmBjUu5k/Lztczcg==} engines: {node: '>=22'} - '@atproto/common-web@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-mYAUpD1QborMVi6GtJwl4zGQOk1ZYbtxZ8rp7OdH2kYWoqVemSdrm0y27vrA3HMoE+KE7XrMtZAtsaV8IQf8OQ==} + '@atproto/car@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-wtTmHbgmgcs39n9mun3X1lHyeeGt21+zZ/DrRKoCW37uYSaaF7XbuZB1dVuekSxeDt0biRl9ETS/PEIzb8ACfA==} engines: {node: '>=22'} - '@atproto/common-web@0.2.4': - resolution: {integrity: sha512-6+DOhQcTklFmeiSkZRx6iFeqi4OFtGl4yEDGATk00q4tEcPoPvyOBtYHN6+G9lrfJIfx5RfmggamvXlJv1PxxA==} + '@atproto/common-web@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-q1Pti2tZ3040Q/pgDwlINrshaz0SEso803CkCRt7wb4leQQ8NWb8GpoFUij+v+K35EafA5BtKXfCfI2UeCPA/Q==} + engines: {node: '>=22'} '@atproto/common-web@0.4.16': resolution: {integrity: sha512-Ufvaff5JgxUyUyTAG0/3o7ltpy3lnZ1DvLjyAnvAf+hHfiK7OMQg+8byr+orN+KP9MtIQaRTsCgYPX+PxMKUoA==} - '@atproto/common@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-DVkrueYwAJTO+KKu/IkW+krlixWPuUZHGrzggXt8wrJwenChh5IvtSMbsQM8KnbJX9D9v1xOiyyybqmVIyHVCQ==} + '@atproto/common@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-BfrQnuqM3PJ2ILA4ctYsZv/G615tmlhFVOatKLpaKAYRJiYbrud1V5cWAoS+P64B6YDfnEkpxsfrq1d12SI+Mw==} engines: {node: '>=22'} '@atproto/common@0.1.0': @@ -745,15 +747,12 @@ packages: '@atproto/common@0.1.1': resolution: {integrity: sha512-GYwot5wF/z8iYGSPjrLHuratLc0CVgovmwfJss7+BUOB6y2/Vw8+1Vw0n9DDI0gb5vmx3UI8z0uJgC8aa8yuJg==} - '@atproto/common@0.3.4': - resolution: {integrity: sha512-qjOHcyeHjGRJseYbdnl+0PViDlMRN9GR0/1ToGKAmXh0voz4LbBWU1FwtGF7CvTlbom9MZYhu21lF5pD5RqBwQ==} - '@atproto/common@0.5.11': resolution: {integrity: sha512-WRlT4s+wv80WdQuzkQub9D5vTD82O8dH2p91u4b+x3O17q5IQbmA3Lj+1NICINNSy2voqloqAWdqXEkRfdlAPw==} engines: {node: '>=18.7.0'} - '@atproto/crypto@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-3fKgpldF14VvEn/awMuBUdiJNEqtgu5PIizeMx4puOXTOu6oWZ9p0OqDOdPFqQ7VQOgSGtSZzeCBIMCD+Q4kKQ==} + '@atproto/crypto@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-hCvDczNGlchdxlGLk4AMh0rpAQBNC9gem/K8G6SlugS7i+2XwzVT9CWrsLnJNGGSxMhsHGU3aSyYvml59K+GEA==} engines: {node: '>=22'} '@atproto/crypto@0.1.0': @@ -763,28 +762,36 @@ packages: resolution: {integrity: sha512-n40aKkMoCatP0u9Yvhrdk6fXyOHFDDbkdm4h4HCyWW+KlKl8iXfD5iV+ECq+w5BM+QH25aIpt3/j6EUNerhLxw==} engines: {node: '>=18.7.0'} - '@atproto/dev-env@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-gWN4edHdJDjXhgilRWte2msMEsFRnk/wgFtqxskHdrcuwj9c/iW6Ym6nvnZBKxcWRiNOYmep8MK5mxeUf+qOrA==} + '@atproto/dev-env@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-j6R394R9Zw57tKVDr0OlDCpMISRlO/TqIVmOoiBdMLeFIPFmf/BX3xpuUuebkQNTT/vRgEdniZ6f2VmD7KDInA==} engines: {node: '>=22'} hasBin: true - '@atproto/did@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-aiI8nvHhGVn3c7BY+T/Rpqn8/ydrEsuT8wNSS0tPIimqtEouViZCqEwoTSaM54nif3P6Cs3s/NmsLBFshtRb3Q==} + '@atproto/did@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-XA7dEedsSLD15fdHNNGkNChktE8z5Sx/4XUBinR3u41jS2mWNAOUb+Hgy5kvMt45vPUhGEkyjhyI1ClJlHCBRg==} engines: {node: '>=22'} '@atproto/did@0.3.0': resolution: {integrity: sha512-raUPzUGegtW/6OxwCmM8bhZvuIMzxG5t9oWsth6Tp91Kb5fTnHV2h/KKNF1C82doeA4BdXCErTyg7ISwLbQkzA==} - '@atproto/identity@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-eD0VsntdfWiMZtT/17nb3cDPzko8XipLM1sjSqEifaLQ/WVkLYMNAiq27bQZl0UP6ZPPQfmjkbYoBn4UyAoCFg==} + '@atproto/identity@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-slGw1/Cgyq8Ks6BOHR5bCYKWY8e33pwhnyBuYZpdVxj/Ds3G2HrT3Fun3V8XDqLBpU/f989Jgc4ZFZ2iggZkcA==} + engines: {node: '>=22'} + + '@atproto/jwk-jose@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-a560HC/cWYAl2FWYTQSIoSXeRnhkoKEHeelLH0LcNieRc9pJRshNziUbcpQUZzDO8O0sVfrimz09QotrHObQjQ==} engines: {node: '>=22'} '@atproto/jwk-jose@0.2.4': resolution: {integrity: sha512-gzDoA0JTwnc0ZJOBLM7WX9xFxtynRS2K1Bofb8epzoMWDQvyvfbPcfkdPrKFM7NXCFUVpGpBnsCB8KFPTf1rCg==} engines: {node: '>=22'} - '@atproto/jwk-webcrypto@0.3.4': - resolution: {integrity: sha512-UsFIUozqnRecXPo6HgKV4PW4FqYHxX1V3iAe0rRV6Q2RSfYD8V2mZ89pv8NpvJynnaqJArBQ7HZlcg0F4tRYhA==} + '@atproto/jwk-webcrypto@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-MYKAgGE17Z9QmHcd9gaQ8guX4iWO7Um/CkceI7C2f5Azsp9/T87JTeP5Dc8o8aWm0CLc9xC9YB7LsrvtX6whbQ==} + engines: {node: '>=22'} + + '@atproto/jwk@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-JhcZrh1GGexC0VlP1ad1JLUglMsCR+ryqRK3qcfnAntyIn7FA7uCX9oqg3Jm2lxqm/St2P+HzEys26jNoqshIQ==} engines: {node: '>=22'} '@atproto/jwk@0.6.0': @@ -794,12 +801,8 @@ packages: resolution: {integrity: sha512-tq7TUDmNfe1yDfpRgdGQMJdl9TUlJmREQNCag9yg5w8Evu+TOiFiLgiOCbo7X4ouRPSgd1DpOzXbUa8UyKKMZA==} engines: {node: '>=22'} - '@atproto/lex-builder@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-NPiH+H3m6s34Z7FVPsfRPoWcLy0wqoh1y4tDHVb+IDkv80ABA52UgvHqHzkQ9is53igKf4xBc+NsXN2QAZSMng==} - engines: {node: '>=22'} - - '@atproto/lex-cbor@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-dO/dTNO7MBEeNpG8gcEe4nnZEYk6sDm1PR0S2GwCeAseO/9XgzJqYar0FhG92zRtimFxfJio5GAKmdVJzFdAjw==} + '@atproto/lex-cbor@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-9RORgsnvI0RQTGKJ80Ucz++cWXgY6knaoPqmeZIFLxkRak2mp+4SQp+QNAjtfGtMlzpUqDLiI/kNaa+C0dGm/w==} engines: {node: '>=22'} '@atproto/lex-cbor@0.0.11': @@ -808,12 +811,12 @@ packages: '@atproto/lex-cbor@0.0.3': resolution: {integrity: sha512-N8lCV3kK5ZcjSOWxKLWqzlnaSpK4isjXRZ0EqApl/5y9KB64s78hQ/U3KIE5qnPRlBbW5kSH3YACoU27u9nTOA==} - '@atproto/lex-client@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-2vmImywMxhn9n2iDDZiKXdUGYsmKXBbk98s2pq3W3wVJ94R8524cBnEb3eVKqnZry39tR8p26KlgyyuB1GERWQ==} + '@atproto/lex-client@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-UHAf925NXxpFNY42UQrMMtcnIPaHWX0R7wDrYe16RKd7y0HPtKDyaP4HLXh2eS4DGA/A+XcpAuM+vIiGGgOm9g==} engines: {node: '>=22'} - '@atproto/lex-data@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-oPBQ35NDU5re/b0tRvKm7PKlEzn1LcbJ/L8UpbixOSFwbE33/EYj836WmVY8JESshOkXFcSGjPm0p8Ne//Kiog==} + '@atproto/lex-data@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-+91aJCNktoYtmWiMeJ6xaUXzdjQQaBuwTRJaTWmy+dIeq+tOVsnIGqslWIK9zC4306OdmFsd7k7yz3adOhjLdQ==} engines: {node: '>=22'} '@atproto/lex-data@0.0.11': @@ -822,126 +825,123 @@ packages: '@atproto/lex-data@0.0.3': resolution: {integrity: sha512-ivo1IpY/EX+RIpxPgCf4cPhQo5bfu4nrpa1vJCt8hCm9SfoonJkDFGa0n4SMw4JnXZoUcGcrJ46L+D8bH6GI2g==} - '@atproto/lex-document@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-AWei82KuHFAQ/QG/mqUbNFCfqhKt4jMLjGmsKf0huSnkZUP0NeikIR8OH/AZooJ1vpsY13Y5q/7BKMCc3I7+Sw==} - engines: {node: '>=22'} - - '@atproto/lex-installer@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-oUGar5m1tLp9GyeXOYLHWHhnrlD9vvwDmWJWDQzJW8rW3i73gV9YlWiQjfVD0ro7zoGWFnEfdPe9C2y8gr3U1Q==} + '@atproto/lex-document@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-URa0URI8eyFB0ahFYP6d9zD9Vu3dO0yG1NDF4PVOJk3GNTDI/C84OtMxP1NPz3u3+0ENAdRCjwr1LEvRnuVVOQ==} engines: {node: '>=22'} - '@atproto/lex-json@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-0wLiDyR1DG9hY55uspAXoe3jqo76WJtG5yae13cTI69lhAeraC7ZPkn5As/L8qIXRBidh4goHBj1RmxqdeRWWg==} + '@atproto/lex-json@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-zRN14kr/BdDDfM+sQzwYgmHmGTtJ6gBFxTFK+4GwArLwfthAcq65N01MnqmvnKqfeVdFAADffHuPsCF/7B90Sw==} engines: {node: '>=22'} '@atproto/lex-json@0.0.11': resolution: {integrity: sha512-2IExAoQ4KsR5fyPa1JjIvtR316PvdgRH/l3BVGLBd3cSxM3m5MftIv1B6qZ9HjNiK60SgkWp0mi9574bTNDhBQ==} - '@atproto/lex-password-session@0.0.0': - resolution: {integrity: sha512-7IsFdFyeAldr+l9Jz1EGgBECXKf4LVSvkfxUQFEIPPhfGSSlhQpqqHM3ZVsrc4Hjd63S8ZtOmO7wYQLp9fslVw==} + '@atproto/lex-password-session@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-gNMmLIbWy/QI+LTcSKm2s+EAi7s6P0yk8hvJTl5aY5RCZt3GUzu7lQiUgkm1nDGBIwkpfb29Z//fji7G1JU2ag==} + engines: {node: '>=22'} - '@atproto/lex-resolver@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-HaCrrcZX0ZS1NyVdW0+Jxi7zNLL4XwcDFrgfcjDpFxzUl1KnaAyGAYAyQiaSDTGLKTgxg4F1JBjDWGtdmsoz/g==} + '@atproto/lex-resolver@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-mWXEX/Q0a+UJx1aqY8VDSdgUFwUJhwWjPqecXpDEzbR+i++rSSq9Vgh/Wt7zl8ub5JcVCqJI/M4WxZSHVUNcPA==} engines: {node: '>=22'} - '@atproto/lex-schema@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-i88pl575dXkJc01l1wJJXMlTdGNyQI0GWVKLaqCqcnF+Q7ZTCWpDw6JHTdpjVxiPEriF3EL9BI98dUOORYEVpw==} + '@atproto/lex-rpc@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-zENtE1MvAbTIfaNXe8yoCmfE0fDBlkZm+D6j0+Ef03qk+51PtMtBaQ4LaXJm10vNgi5NS4gJ7KIMF22AlWQEYg==} engines: {node: '>=22'} - '@atproto/lex@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-BAIndja10iJJz5NZBPXOmqGeh2NNhcTesBfVxGyrU6hdBwEZdUEzGf3hoZRybOnHGq8dsq3Bi9NSRn2kV8SLJA==} + '@atproto/lex-schema@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-ArUTVp05xVw7jVV4ZoSNDH29/gd2hjFstXiePKuprZpK9tc9rBeaqvGTdXgbQ6wwltCWdBX9cbpMht1Lzfe7DA==} engines: {node: '>=22'} - hasBin: true - '@atproto/lexicon@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-6gFzYj8u3c31oxisnbwzthm74z+y41ssniWkqLR5cCYD8K3kG9ggIdZP6c3V4iJQ9NB/vP81oOaDgFDFfBDq3g==} + '@atproto/lexicon@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-qzq9Jw8e6DsXMn67nECnI31cmO65TgjibbYI7Xd2q8yBdjMm+JPZzNMVNTIocPLMZ5gJPZNa8eBjU1CrS1iAVw==} engines: {node: '>=22'} '@atproto/lexicon@0.6.1': resolution: {integrity: sha512-/vI1kVlY50Si+5MXpvOucelnYwb0UJ6Qto5mCp+7Q5C+Jtp+SoSykAPVvjVtTnQUH2vrKOFOwpb3C375vSKzXw==} - '@atproto/oauth-client-node@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-8TtrUULBv63G15g4YqcvB7TH5Ti1cX2nZAB4x6D79RuWg4FU3StrqhxZFmzlknpqf+iybDNJcv+uBcw0EJrqKQ==} + '@atproto/oauth-client-node@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-pXZSugbm5RnWrOBchoHXlU9jO+AGIO/01RA4FJ0165hsm0Atwc+6Jj/NueCHCDRufnkvppNBSEZJROe/bQ2zGA==} + engines: {node: '>=22'} + + '@atproto/oauth-client@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-Jzlp2T7WTmdQ+7YVUt2GsY3/NQY/ixneBdKGnDVdGnd10V5OnG7PP4nt/sQGIL8cqBRywYxrsLIAV+4DNnfCrw==} engines: {node: '>=22'} - '@atproto/oauth-client@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-yrgioKn0jPYmzDxHUMHXAoM1RaYekIKJPMRs3EpTRhcNNiZj2e/RZquqWAf2IW+1vk5EspDNPvCL5wMs6hfOkw==} + '@atproto/oauth-provider-api@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-zHQcrOM9JkqbMl/Pd3SNNIM4CUedeAKGiBmlRe3UAbo0x5526Jb5NbFWQD/1R6kkX9fEmIG8UdgNg5kMK3+IkQ==} engines: {node: '>=22'} - '@atproto/oauth-provider-api@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-fMfgsM5LVEN/aBeDQE3/zTsQ/Rp7mZB/urzye7uLCR/pATjbJkbm+efXTIgrUOOj4sBeSJ7KlNOTFz2qP+M8lQ==} + '@atproto/oauth-provider-ui@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-vpbGHArTtdJMfPblg3Tsi+vyYBsyLgrus5jDaEA7azdoLgjG3bbM4QLPS/gLBxkfBShjEPwQr/mfF+a7CP35XA==} engines: {node: '>=22'} - '@atproto/oauth-provider-ui@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-QwM+dHfJnuRj6i6rwHwUyz2ks2OwqpHPxaHMhvYH1sAQrXcjMHwExiZk0A/iACetePpJzbUup+cqL28JKsps0A==} + '@atproto/oauth-provider@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-OK0+6ePNbHokvm+ONHTkh0u17zbVO1jAmVR7EJuBp1xK6+dcEMvWWmsLbwa90g+4kRsdquG3Omttezb0UMk44Q==} engines: {node: '>=22'} - '@atproto/oauth-provider@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-4ZqYQ+qDorAuaypw9MtlFnlKYhQzHaPhhizKg1FCd2B62X8b9QKGofTsBAQ+fx2vtpxB1ZTq/t3sniraz8YZlw==} + '@atproto/oauth-resolver@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-givAH5Zk0dZVa3F1LOpw934XCG4gYwIfrl1jam9maecwpWZ2aTPA7CiRX6QhWEcXoAKAGgc8LcAWBv453crztg==} engines: {node: '>=22'} - '@atproto/oauth-scopes@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-7F7I5mATu78oF3EE/ujjmn3O3z7szGNiFoVm1cX0HOp99phVUoKud/bo4LuaK6fb9WeJ/vwneMDCmxd1BFNOUg==} + '@atproto/oauth-scopes@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-7yuQRB368bfds1jPd/z5mUjSjyNk+xnx5vucVVrKSLDYXIfdmkicsS4e+d3E7xmdBqhFktVSpL7H7f09TgIMAQ==} engines: {node: '>=22'} - '@atproto/oauth-types@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-eXF+KRdhVlvkIdnIqzR9QPyI+jakNsp2fsMuTO3NZmV7libBm19BJbhSHEywF98ZMLbRIEU9WgQfa60XtwCCdQ==} + '@atproto/oauth-types@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-KOr69pUlkfyBwsVXkC2/1LpKYH/mz0eg5FU0AQzu3kHSFk7+ohgnsx2pvcg85Y/AvjsvzGD3+ncPspd5pn1Cnw==} engines: {node: '>=22'} '@atproto/oauth-types@0.6.3': resolution: {integrity: sha512-jdKuoPknJuh/WjI+mYk7agSbx9mNVMbS6Dr3k1z2YMY2oRiCQjxYBuo4MLKATbxj05nMQaZRWlHRUazoAu5Cng==} - '@atproto/ozone@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-vEmjdnqe3oi3YXU8jzdgq+gMQzfvJJfWxwJhLWoBcKBnwQQYVVxtuba81c7sm9+gDDaK6my0O0iOW5cy/1J9kg==} + '@atproto/ozone@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-L/9ZLuLaOAYl7tqKqQzwfsg2Q31RU7ZqadekrMiqEcdEKHrf6nAqMtI7v/7H5j5wVvzLj8t6Fn0GhPvIM/13tQ==} engines: {node: '>=22'} - '@atproto/pds@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-DLG6BIPkRIcDjitqmEKmScqqp9aStW/6nJhOkd/b66BKbDRuT7ro2fYhe7pbPSV/pToc2JUL9X5oDXGd1HC3Wg==} + '@atproto/pds@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-+WJkSLWiLvOXx/vQsadyci0vDZkJummAMV56RKkBxNhZnZJXO+nodm4jf0V8nSf7xQtAFW3kf8rnq2b/KT7JcQ==} engines: {node: '>=22'} - '@atproto/repo@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-nqC7dakknV0dWHoyA6YJuVs1IRHJm7Smfq7Mp/SeFjjNCaGm5CRABzraeUd8ebk6ot+mBbvqhh7TTek+cWwzJA==} + '@atproto/repo@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-hXAkZFkr2d2dkYsErdBfn2Xd9J9SlElbn1It/yMgM36XIIsk1bEdhrDmUNKWfUXd7LV8C/S8DhW4XLslvU8fEw==} engines: {node: '>=22'} '@atproto/repo@0.8.12': resolution: {integrity: sha512-QpVTVulgfz5PUiCTELlDBiRvnsnwrFWi+6CfY88VwXzrRHd9NE8GItK7sfxQ6U65vD/idH8ddCgFrlrsn1REPQ==} engines: {node: '>=18.7.0'} - '@atproto/space@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-+ICI+XXW0pNYRE01aq+xZZurza9j0VrVrE3mG/Gv9F+rBioSv+99miExXF6A/naJW+jIPgFrgc8a753nKWmSzg==} + '@atproto/space@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-vrgINVJcTnWsHjNW8xNuuVD2Y2/XFy2UNzg00+9slXFffXAXMXRBxIpdqtOIEYRHQ0YkW0A9b3TXNdxcMmNuTw==} engines: {node: '>=22'} - '@atproto/star@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-MTeZW52Ym8gPUxcWdDOFqzHi9qgVZy6B7ZbenjRGL84sPWtKwZDKJstUmp0NgH8TykcklZOjmO1X10v0QBximQ==} + '@atproto/star@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-/CxyfM7LEZ6XKFgU6JwKw4mr4MrM/l26WYjzbNyoW8nUvYQtxCqDBXV7ApVM9Jo8Cv6HrfUbxAl9HT/9qFKaqQ==} engines: {node: '>=22'} - '@atproto/sync@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-UDtnHF/WO0geM1V3gIG04GZ/TtRtjhQYFhQCRtrTN0yacg8XS8hZgwwFqMJfI8hfe5w3ANWdNh57xk1cf+STuA==} + '@atproto/sync@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-EqSO0InQLrY6KmNe3Hy9CbUq2miMXiUTI4BACiX+KgF7TMtX8VLs3krGF+0ndaWwSLVcEBndTN+Qb5+Udj/gZQ==} engines: {node: '>=22'} - '@atproto/syntax@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-XW+S/xGd3AbmLLtOIxhTKjZWvq+dI3YoXX2UD7IKt4VJCBW0/LMTV/esh24m1jWzj1wNjnmPgPDpUIr3NWrgPQ==} + '@atproto/syntax@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-3qoGi/vxD/gOzb3u/W0deqR9CqZquU20rOLq2tpW66ufFMcuMnSFHMGSmOaDL7yrdz0xDfh22vPu8WWFQDG0Dg==} engines: {node: '>=22'} - '@atproto/syntax@0.1.5': - resolution: {integrity: sha512-pbY5lOnThoAbsmrdbN9LC/dNmckfqODJiX9zjW2t3BIHYFeGBc6w9bK3Vre8A0Hg8yWkQpv6gaBLu+ykgi2DJQ==} - '@atproto/syntax@0.4.2': resolution: {integrity: sha512-X9XSRPinBy/0VQ677j8VXlBsYSsUXaiqxWVpGGxJYsAhugdQRb0jqaVKJFtm6RskeNkV6y9xclSUi9UYG/COrA==} '@atproto/syntax@0.4.3': resolution: {integrity: sha512-YoZUz40YAJr5nPwvCDWgodEOlt5IftZqPJvA0JDWjuZKD8yXddTwSzXSaKQAzGOpuM+/A3uXRtPzJJqlScc+iA==} - '@atproto/ws-client@0.2.1': - resolution: {integrity: sha512-HCGkqH/Ksxpgg/xCyIvH5hK6o8Lg2PxcEA790GCEV9MspCZB/xIesHZVgJN0cEvklGe+6pNCOZE1B5kj9q1ONA==} + '@atproto/ws-client@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-8k16/auYN80tE+Ssfb9RZkW44p7LTvLJOd+xCP+YukuXfkkdJHtYSM65R4p+H4GC49AKC8fyZEIpgDZSdl4p8A==} engines: {node: '>=22'} - '@atproto/xrpc-server@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-LIv4nyekvtjgiKl59lALlvnlMiDpwJltIFyZu/GH3CbfI5Z0gwTX9xvAW3XnjgSSHqFqk0CriLB6l5duM7E03g==} + '@atproto/xrpc-server@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-y72SXKmYZh5PGZKIjM60faqFojSNL8QMouylydGIXPMDKBuhSc7UZlzJeN8oyrhQpvapcurg/oFr7SzyVVQWRg==} engines: {node: '>=22'} - '@atproto/xrpc@0.0.0-spaces-alpha-20261105160032': - resolution: {integrity: sha512-uT9Z5hsxdRiO96b2Os1CdmIauDM61zydNmv4C5sga2wFnP3K+Acgn3ETF1bICqrDDdyKXACS1yvZD2/5/ks6dg==} + '@atproto/xrpc@0.0.0-spaces-alpha-20261112204144': + resolution: {integrity: sha512-SIP4nTss4Uyyx3qL1oJSwtMcz4cD8ThvgPSS6080+bObh8CCqswccCLfEZksq5kVzO6Nl7A9RGuXz7sDAp7nTw==} engines: {node: '>=22'} '@atproto/xrpc@0.7.7': @@ -1136,36 +1136,6 @@ packages: resolution: {integrity: sha512-VERIM64vtTP1C4mxQ5thVT9fK0apjPFobqybMtA1UdUujWka24ERHbRHFGmpbbhp73MhV+KSsHQH9C6uOTdEQA==} engines: {node: '>=18'} - '@cbor-extract/cbor-extract-darwin-arm64@2.2.2': - resolution: {integrity: sha512-ZKZ/F8US7JR92J4DMct6cLW/Y66o2K576+zjlEN/MevH70bFIsB10wkZEQPLzl2oNh2SMGy55xpJ9JoBRl5DOA==} - cpu: [arm64] - os: [darwin] - - '@cbor-extract/cbor-extract-darwin-x64@2.2.2': - resolution: {integrity: sha512-32b1mgc+P61Js+KW9VZv/c+xRw5EfmOcPx990JbCBSkYJFY0l25VinvyyWfl+3KjibQmAcYwmyzKF9J4DyKP/Q==} - cpu: [x64] - os: [darwin] - - '@cbor-extract/cbor-extract-linux-arm64@2.2.2': - resolution: {integrity: sha512-wfqgzqCAy/Vn8i6WVIh7qZd0DdBFaWBjPdB6ma+Wihcjv0gHqD/mw3ouVv7kbbUNrab6dKEx/w3xQZEdeXIlzg==} - cpu: [arm64] - os: [linux] - - '@cbor-extract/cbor-extract-linux-arm@2.2.2': - resolution: {integrity: sha512-tNg0za41TpQfkhWjptD+0gSD2fggMiDCSacuIeELyb2xZhr7PrhPe5h66Jc67B/5dmpIhI2QOUtv4SBsricyYQ==} - cpu: [arm] - os: [linux] - - '@cbor-extract/cbor-extract-linux-x64@2.2.2': - resolution: {integrity: sha512-rpiLnVEsqtPJ+mXTdx1rfz4RtUGYIUg2rUAZgd1KjiC1SehYUSkJN7Yh+aVfSjvCGtVP0/bfkQkXpPXKbmSUaA==} - cpu: [x64] - os: [linux] - - '@cbor-extract/cbor-extract-win32-x64@2.2.2': - resolution: {integrity: sha512-dI+9P7cfWxkTQ+oE+7Aa6onEn92PHgfWXZivjNheCRmTBDBf2fx6RyTi0cmgpYLnD1KLZK9ZYrMxaPZ4oiXhGA==} - cpu: [x64] - os: [win32] - '@changesets/apply-release-plan@8.0.0': resolution: {integrity: sha512-kUd2pbf1w5/AYmBMb0Tt+rkIPCjFJdT0SZMrkOjJT/WV/QbtmvkyB5jkV0oaNPheavprZk+SfUiozUti7TIL2w==} engines: {node: ^22.11 || ^24 || >=26} @@ -1754,6 +1724,10 @@ packages: resolution: {integrity: sha512-k9Dj3DV/itK9D06Y8f190Qgop7/Ui+D0njFV3LHMPwPT75DpXLQohE9Wmz0QElrJnzsjB7KPWiKJbOl7IPDArQ==} engines: {node: '>=12.10.0'} + '@grpc/grpc-js@1.14.7': + resolution: {integrity: sha512-W4W/fcBMGRVtG6dW2c7cw2mnpS3hvbBd+oQXjh2iYFTZDk1JJmcNqkM5KSaPubQpamlUUurrlb7G1s9NJeERmQ==} + engines: {node: '>=12.10.0'} + '@grpc/proto-loader@0.7.15': resolution: {integrity: sha512-tMXdRCfYVixjuFK+Hk0Q1s38gV9zDiDJfWL3h1rv4Qc39oILCu1TRTDt7+fGUI8K4G1Fj125Hx/ru3azECWTyQ==} engines: {node: '>=6'} @@ -2159,513 +2133,472 @@ packages: resolution: {integrity: sha512-oGB+UxlgWcgQkgwo8GcEGwemoTFt3FIO9ababBmaGwXIoBKZ+GTy0pP185beGg7Llih/NSHSV2XAs1lnznocSg==} engines: {node: '>= 8'} - '@opentelemetry/api-logs@0.208.0': - resolution: {integrity: sha512-CjruKY9V6NMssL/T1kAFgzosF1v9o6oeN+aX5JB/C/xPNtmgIJqcXHG7fA82Ou1zCpWGl4lROQUKwUNE1pMCyg==} - engines: {node: '>=8.0.0'} - - '@opentelemetry/api-logs@0.219.0': - resolution: {integrity: sha512-FFx7YnaYJlIjqWW/AG/yAZ0L/NEY724PipXXXQLdtZPbLwBGbUMTGL1i/esI56TWfTUXxhLfpgrnWJCG8aUJyg==} - engines: {node: '>=8.0.0'} - - '@opentelemetry/api-logs@0.220.0': - resolution: {integrity: sha512-CmVa4ImJ+ynfrPMNaAXHET6Bhb44SwzmfyVJFq9ni2jgXJR/l7C6gfVFddNmHP+ZOkP9cf4f9DBe68qVLTHc9w==} + '@opentelemetry/api@1.10.0': + resolution: {integrity: sha512-lMkyes8iHrG+mk6WH7X70MdCLI2RS0FwNBY1PyQ8UemaijE2m5mv5A0Niy3HtbYTFrgkUEQjFMXmSAk2hQDuPQ==} engines: {node: '>=8.0.0'} '@opentelemetry/api@1.9.1': resolution: {integrity: sha512-gLyJlPHPZYdAk1JENA9LeHejZe1Ti77/pTeFm/nMXmQH/HFZlcS/O2XJB+L8fkbrNSqhdtlvjBVjxwUYanNH5Q==} engines: {node: '>=8.0.0'} - '@opentelemetry/auto-instrumentations-node@0.77.0': - resolution: {integrity: sha512-LkF930Cs+v+ZO/qV6LolbocvFkJJ812BBDyRNjQpwllBA+rFvGtP/voXPuh24QV3JKl5/3c3GulLHvMn8spqkQ==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/auto-instrumentations-node@0.82.0': + resolution: {integrity: sha512-WL4U3IZ9a0lHPj9l+c7IWJN+G2LPlM1/Otk15a5qrIkByEw9XCmZ2SwCf8fNZnCf5MNOP0D8LMaR8kv1MWtaFQ==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': ^1.4.1 - '@opentelemetry/core': ^2.0.0 + '@opentelemetry/api': ^1.10.0 + '@opentelemetry/core': ^3.0.0 - '@opentelemetry/configuration@0.219.0': - resolution: {integrity: sha512-wXZUYv4ngu43nA4WEhuXNacm46LW+17LRM8nKyIhBzroRA24PBYjMnakwzR/w777nFUB5xlgsYTTeuXxumZM1Q==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/configuration@0.300.0': + resolution: {integrity: sha512-vflvT+be02dmKt430t+XAQ2QvcPzjZODdVqMqbpuakuGk4i0zCZ7SyM9VOFHGuBV/HxfVlf3EvgHBGKob2P8TQ==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.9.0 - '@opentelemetry/context-async-hooks@2.8.0': - resolution: {integrity: sha512-/3FIraneMcng67SUJCxvyInk/oxzwsxyadufk0wwfOBLf5wqtAGX4MoQASwSbndBPeARzBryUM9Azr5kHIdWLw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/context-async-hooks@3.0.0': + resolution: {integrity: sha512-qDZeKSgTT+qTaL99eRbpvWO5+oZ0MKvMH4pqvzi6xYKyhiMTDBxBeTLI6BpdeMt58T5TpxHJvFl9P52i6CDWGA==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': '>=1.0.0 <1.10.0' + '@opentelemetry/api': '>=1.0.0 <1.11.0' - '@opentelemetry/core@2.10.0': - resolution: {integrity: sha512-/wNZ8twnEQQA4HoHu22+vcsdru6pWPWxW+7w+FlxT6Id7PE/WIbZmVKkte+PF72e0F2dnImFeHD2syyE1Mw6MQ==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/core@3.0.0': + resolution: {integrity: sha512-whOLlww0R/RLtCWGBXhK1fdvL9t2/TL0fqdjZvcaoUUuNilRPjXecqQdzyVwV68s6XEDA5oYbm7/bZT62GXF4A==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': '>=1.0.0 <1.10.0' + '@opentelemetry/api': '>=1.10.0 <1.11.0' - '@opentelemetry/core@2.8.0': - resolution: {integrity: sha512-hd1Lfh8p545nNz+jq1Ejfz+Mn1hyLuxYn1YzTfFNrxr8urEWMNQLPf1Th8kjOH+HxwawCrtgBp8JpBUR4ZSgww==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/core@3.1.1': + resolution: {integrity: sha512-6wc9r0zrTsAVOd/5UrZBsrHhXWNfwisolgWxd8o3Eu1HKIz8cAxQjOdGrrJB406ceFiGV+ckTcLdXzB+y/QVTA==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': '>=1.0.0 <1.10.0' + '@opentelemetry/api': '>=1.10.0 <1.11.0' - '@opentelemetry/exporter-logs-otlp-grpc@0.219.0': - resolution: {integrity: sha512-7SvzDCIclHWAcCwZ1MTOLcwn4BVNPGI3QxS/DJraPNe1TTL+4TvUBq5zeQV8tsnYvtDN7wKW2qocVmaCP2l7sQ==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/exporter-logs-otlp-grpc@0.300.0': + resolution: {integrity: sha512-y4BAcN2UBSBs+esuIyXonpV44oeENKdit1BVKvjHf/61KvZVf7u1sTRz2VGwBpGJvUD7rNPjOZnb4PpG3vFEvg==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/exporter-logs-otlp-http@0.219.0': - resolution: {integrity: sha512-mhl2HL6GmZI8b8PwPfqMws/5ovJfbRTxwc9Y5agVVHiQ+e5SL1btsFr/kJDgt7YCexDtsUn5HAreHQO9szFS0A==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/exporter-logs-otlp-http@0.300.0': + resolution: {integrity: sha512-S8yP9Fg33CU9+0fr1pnh/afPfgEpSyxQO4JRUZvmDMhAzgR/RLzvYg93MjWjbC1c2VrXffXROMO68RZ1P/ebgQ==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/exporter-logs-otlp-proto@0.219.0': - resolution: {integrity: sha512-Ayw4Gf71PS9jhBVaYywa4WsajnqfDehMkTdVH3TSAVHqPcsAv/AhH/wTNRYNt99szeYr6Gbd/D6RjZD77wAxHg==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/exporter-logs-otlp-proto@0.300.0': + resolution: {integrity: sha512-i9EqF1mvD0IrL6yBAqb2Cnv61WIYjkBxb36MulHf6/iAb/c653onKVWRJbpexBOHq+fd0VjH+1mhn+AtpFIZwQ==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/exporter-metrics-otlp-grpc@0.219.0': - resolution: {integrity: sha512-6LaaSrPxK5L55bXevWajvOMxGOpNm0n12tG53TeZaUeNzXwLPg6d2KCC1zAlGsojan+xRG71mA4Qqs9K2VVrKQ==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/exporter-metrics-otlp-grpc@0.300.0': + resolution: {integrity: sha512-Kbfh2eVuj19WxByTI+UOhzjsyhNnl4lovjl9DYr0QsEpAPDyzWxGQmBDaTgIq1Tv3/Zc9ZDczAa//T2bjzac3w==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/exporter-metrics-otlp-http@0.219.0': - resolution: {integrity: sha512-6CaDRbMVHZSDWzNXwrR8y/H4B/Z1eMNnkHiPQlTx3Ojz2OHY4X/aff/UC4P/3pHUQSuTfi3oh2UsPPZppw+Vrg==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/exporter-metrics-otlp-http@0.300.0': + resolution: {integrity: sha512-y8KYKyM69l9PG4Ax9DKlKH5jaVJCJo9hXOpT6v0/PDX+uC302AhHVitEz8M600ljqLGdPYodnyn+wbYIYXPh6g==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/exporter-metrics-otlp-proto@0.219.0': - resolution: {integrity: sha512-DUS7XyIiEnoeccQUvuKy0G2/YqeKhpN8FVIrGbrLNIVMj10yeIFLRzRv0tibCI2kXXvlTTABVexGAk78wHk2ug==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/exporter-metrics-otlp-proto@0.300.0': + resolution: {integrity: sha512-tCL75kJ0JgLmbNCcpYgYpsRht8HgQJwd6LatK9g19O2nTd2GE3v2d38I1m1cVjKw1NRR+vtqei8AzGrznYtm9A==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/exporter-prometheus@0.219.0': - resolution: {integrity: sha512-TxOnJ85eWJY5JyOJsNMXiRTYlkDcOv0u3KbXEzWCc+tUS9sjL/BC6BcdxZ0B9r2OFVqsrZFXUzSD2sZUy42Ucw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/exporter-prometheus@0.300.0': + resolution: {integrity: sha512-x8MCVBUPYZeQcL14HJUiYuF6IL4/YZ5OtR5ObnznUaTrhPdZUEvOQ4EpkLvfFph/nvk4lEs0cJ6uK5oMrFyjGQ==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': ^1.3.0 + '@opentelemetry/api': '>=1.10.0 <1.11.0' - '@opentelemetry/exporter-trace-otlp-grpc@0.219.0': - resolution: {integrity: sha512-BkDNv1UD6BscW19MxbAxVmSYSSFuyeqR6buV2/HTYqA7GrR0EbTFzqG6h86T3PtXmpdbsWjMGLDdjG2rikG27Q==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/exporter-trace-otlp-grpc@0.300.0': + resolution: {integrity: sha512-I0/XvL7lLsn8aU8wnoIjIbcjcFfltEHsgf56s1vzAxB7CLRKzv/MUpTbIHWY5Eeci1448cAqiDSuj5GU5OcfKg==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/exporter-trace-otlp-http@0.219.0': - resolution: {integrity: sha512-9t6SvBXXBEjOBcIzgozvBbd3jWrv3Gt3ngGhl1fhdZ/zRc7oZDVOFEqbi2zlBpW9BXhgDMKv422J0DL/3iQWfw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/exporter-trace-otlp-http@0.300.0': + resolution: {integrity: sha512-Dwdagba93cdhROlFGbkU4yK4hvd3l0k7WV9nvTWIoN6KwxFP+HCvy9EkgIpyfN11fVdIWxY3XqOwWOq83OPfcA==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/exporter-trace-otlp-proto@0.219.0': - resolution: {integrity: sha512-lF/LUBfhOFmxJa+SQsLN7ziV4MHa2pyKgOM6JNehSOfU+npjM4gwm9oIKEJrzrWcexMcqydiyoFy0XCb1Ql3wQ==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/exporter-trace-otlp-proto@0.300.0': + resolution: {integrity: sha512-ZCWrexCUsfp5o5Eti91uvTlXMfszknzrPt3VM+jAk/Q5T53S/ix6mF07ndSHAhreQ5bKmBg3r1Ar4wkqQ1XlPQ==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/exporter-zipkin@2.8.0': - resolution: {integrity: sha512-Mj84UkEa17BK2o903VTXW3wM8CrSZexGs4tRGVZVIMM9ni1T6TuGx5IrRfoWKAbshx42D5/kc7YV+axypLPYyA==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/exporter-zipkin@3.0.0': + resolution: {integrity: sha512-swgbcj76LgjoLPCYyyX0G27kW2+V8PifDeXRVpQ7vokwldKgLrw7GkDo5A2wD3yAWZKDvSWWjMigC3RT7xsuMA==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.0.0 - '@opentelemetry/instrumentation-amqplib@0.66.0': - resolution: {integrity: sha512-lyJgobzP0Ce+tRGOkdnrb60apfqU89xB9FeMTmo1TJU007KTMLiLFd4iCfTiBEXzBsVplx7kwrVN4FqGBUcD2Q==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-amqplib@0.71.0': + resolution: {integrity: sha512-udno0udqQshCVP1I+rMWtV66NOCEn6WBTtRvdBAiDMvGwojwPDiCX6QshMZbjdW/qisbojubizAdWdjx4mUp3w==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-aws-lambda@0.71.0': - resolution: {integrity: sha512-9Sv6flQDeNNF6ZbiLgn+NYJa220yRZdDSIdgDZsqNubpDnYAPF33OHcQDlE8mFiaOq14mngoPS48JnYc8JT+Ug==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-aws-lambda@0.76.0': + resolution: {integrity: sha512-hsaeVoaGS44qXfe23ebEVA9XsE4D/pukhfT4SeNKlhyOBeHDVFnCc2RLOa6t9v5tNTbS3D4cUXc04gjSBZAy3g==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-aws-sdk@0.74.0': - resolution: {integrity: sha512-EMLUGgx2wJSXdwMEFdwd3IaW+mkUF8PENdzDFQ1FRdztzMG1d1XN76ORIjAMsXcKQISlRRcz93AWPQeBPn4EKA==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-aws-sdk@0.79.0': + resolution: {integrity: sha512-B8dcjI9eNwHPJWRUIROcsuiXwsHNxa05J9Uy6ahlN9qUEMyBdK3sPzCsDKC5YbGFPGiC8aN9m5mSjGQdXoswwQ==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-bunyan@0.64.0': - resolution: {integrity: sha512-jrRNFvpREutmpoWhk1T8n9q/RYdxbViXwSUPHN8yQR1bzgtwfOl/y8G/p8Xfudlky9GGsqw5WRc6q6QrfgF3pw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-bunyan@0.69.0': + resolution: {integrity: sha512-Q+ur3anFLSWa28aQJg/hvjgBv81ju65qBQXj5s/bL1Xpza3wysrKGwA4gx8106Nil9iwdm+KQZF9hge8heROwQ==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': ^1.3.0 + '@opentelemetry/api': ^1.10.0 - '@opentelemetry/instrumentation-cassandra-driver@0.64.0': - resolution: {integrity: sha512-KN+iOsmPI0nkX2lfgNgHBrHNaDuxDwIbwFrlvyrZ4bAT8bTKcCOXhne70O9qihM8+T1F4tjvPXpCfhKZbmsYiw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-cassandra-driver@0.69.0': + resolution: {integrity: sha512-fdFuSVEW1QRm5wfyvHew3RseIXuPK3Fk9OhMQbgbik37Rc0tUuYf9aLUuUANu1qQlMfXr0lhLTaUekUKnUg8vg==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-connect@0.62.0': - resolution: {integrity: sha512-ZGV2sOyeffqMiqoh4RpsPTs/TUI5cCS+cEWvC9wUfvaEekR5omR6P/ClG+QDwasGBlKx2zfFPjSYPpzUo81XAw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-connect@0.67.0': + resolution: {integrity: sha512-Y7Vh+iKuOAEwUJ4JOI5OvNK56E1PixoDpK+Bfj4QnBivkqHEZEUqbnYRhvHFVXYisP/xeJKOh3pU+iOnxJHedA==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-cucumber@0.35.0': - resolution: {integrity: sha512-H9NsbcFiVOFOcOu40+VOOjxdTeonu0VHI3mte5ie5ka/bazzIPGncQoHpL6su53C3/sgMdKjE6ZuwsB7Y8gQpA==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-cucumber@0.40.0': + resolution: {integrity: sha512-CQ6UlOpTdDEvBlEWsYIeQ0A1zk89bJLhY9WEG7jrOrFXoLYW8Zicvxa1MaMq0xiEooagTrPoV6+Gtwkd28Ekzw==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.0.0 - '@opentelemetry/instrumentation-dataloader@0.36.0': - resolution: {integrity: sha512-gE0mTk+EnVaBN0mPRM1V6FqzQ9VckTp6ZFIssU5hxy+e3sqspYILBhV/0IHZ33qxGa3B9buLVZnuzVjUISfyoQ==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-dataloader@0.41.0': + resolution: {integrity: sha512-Y6wQwsfCgUW0oie1MCaK+nvx4zIN8BHV0rozno5QbmNZN/Td1N5jG0D+Y5Y6bt8Oo7Wyxz8Q8aw6Y5pz3q+iyg==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-dns@0.62.0': - resolution: {integrity: sha512-6v0X8wEqhIyv2b7MXhmipyCitJfm0vnF5mLBTWXojovoHp7P1EpN5sb12LgdhVlozhGwRZdzb6OvKUVsxKMD8g==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-dns@0.67.0': + resolution: {integrity: sha512-ENj4hL4w2ilMdq3jhf9dDg5CDzjCuTsshTRTse7j0AjIIFS1knP75BQR0Qmx2URPttW6NbwU61jW1v9vxJ4vfA==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-express@0.67.0': - resolution: {integrity: sha512-1WTWX2YNZIV+jPmEqdf/Vd1gHMT92TKA/0pf/iIItWhV6+RhzhnUUW4kSWQn8L3qVcgWEzQ860/ZOwaIwayi8A==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-express@0.72.0': + resolution: {integrity: sha512-YV1T099/8acoA7giEBWm8NJJy+zyMElFkf5DGGcNsBftrA1TLVpctAKBUaV97TOXa+RlglwmxqtOPsF5+KCbzA==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-fs@0.38.0': - resolution: {integrity: sha512-6OBofWODg0RcPkl3bA+7yPf0e4Vi3O7ZxlFGY5QHPMMLxWVMnjWPEXQ2NlLBk19Sr8LcvEyyZOStdLJrT5o2dQ==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-fs@0.43.0': + resolution: {integrity: sha512-8Q4DmSloluXR4L+nJ91IbmvvBLw3ubc06jG+AN9S+munVJCzA+b9gLm3VCzj3wyh+ZN5C08+5EaTvShnR8bEMQ==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-generic-pool@0.62.0': - resolution: {integrity: sha512-IhO2y/MaK1oZ4EbUgdkSVT+XViPq86IAz4lwPe9jaba00M2yDWs8+f9xjcH3tK5IC3dZuAxXmifGmfvuJp92jw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-generic-pool@0.67.0': + resolution: {integrity: sha512-IE8Zws++d8de9Nv1Zb32eaFfXIv7PCsV+YyvwIEb0jpkWjfh2ZqmrgZsHzGOeLvgStFY4tN380lbcMR67FdSGw==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-graphql@0.67.0': - resolution: {integrity: sha512-NMUmuhtYvv3AwkK4zsHQbTCXS81QS63hbNZRKfXc7W8f4KbWeKLmqKqvnfjUcqZoGS0eAw2kNKNYcbtbQ7baAg==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-graphql@0.72.0': + resolution: {integrity: sha512-kyDJXU6t3rPYkY94riEk8MuhTZZ9stNzd5vQ3EYRpFSCdrRwP8gWSSoFnRJVhFWIruC6d5/JdqVFKUjmJ65p+g==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-grpc@0.219.0': - resolution: {integrity: sha512-GyW1Kfbf7uiJXeBZovB/uXPUdkaZYWzB2ZPCdY2CU7+6V207u8wlCM+zVd3UwhEjOBrMbZAGq+m38aBEI/EVtA==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-grpc@0.300.0': + resolution: {integrity: sha512-znZl9LN1Dqg2rqSBRnARApBUlG7vz4FZavWoZ4TxFA7gIIqHfsbImkX/QJCNCiCGEBD8Stji9Ix6Ev25NptK9Q==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-hapi@0.65.0': - resolution: {integrity: sha512-Whhas9iU0SfK/7XBcgCwfW5c9AaxjxtZpzW21t3Ml8XZ6Irc3hF36JDolMmFa7nUjML9n9bSUAZjwCgrK+2UdQ==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-hapi@0.70.0': + resolution: {integrity: sha512-ech8E3/hv6fuTxUfA3QKPpNaRL5/s75C7+/JDMMbff0jMG4wGkAiLJqDjyfaOvP6cqW9EiHqaznZ8/uhrloJsw==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-host-metrics@0.2.0': - resolution: {integrity: sha512-NIttCEOLdg1ebbDiJpCf0Ly1OGIa10isesik+K2dnXy2P99q4muUFjpaLtTnhkENrt9SmR0Zrxzq7B+W/VNWyw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-host-metrics@0.7.0': + resolution: {integrity: sha512-S5BbKqXWDYMxWyvsIMNYfPcGfwsODg/xHnBI0SylG3yBnZuQ7Su3EMUK+pY2mBgkqtUAFPXv7P285/AmF7j+xg==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-http@0.219.0': - resolution: {integrity: sha512-nNt1fqpyah/OKjNHdEOu8xLwISppRU2qJuF8aR+fCcftVwdFkPgtworBLA+TI1HU2iF508jcQBF2gerWczJAXg==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-http@0.300.0': + resolution: {integrity: sha512-kAU01q92leb1rMuF5fhuQKjP3MkdCxSiUT/IWo409YrQMbQdLGmM4EyH6RoSmInNSulSgKWkja+IyglnZSPYXg==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-ioredis@0.67.0': - resolution: {integrity: sha512-dv64vQ4aXbJvRMMAFrMUSzDeJrNv/uQMLjfaav4LHAOar7Xn08W3pkoYoYEnzq/n2+fGgG96rp9S0gQ+VnLDiw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-ioredis@0.72.0': + resolution: {integrity: sha512-Z3btRN3tAVKbc48h4LuHTfOOnQdrhJ5PdtYAhvXkbdH2neBo8FSvpr4PIt4nvqk6XO5Gyqba3CeP48zaOmrYkQ==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-kafkajs@0.28.0': - resolution: {integrity: sha512-dztkg70nJds3Uc0Xo3NFlRqL5iYgGYWh8myuuGfRC6NnXJchY0Kw9QnBjTZxBSldXU+P6nv2snDVMmlxuy6fEw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-kafkajs@0.33.0': + resolution: {integrity: sha512-b1fUlGKB4xAQhAABxUDxINTPIUptC/fa4E5CSmVBNvd/Vr+orFbnXLCz3PWuTH8hR0Ewucwzzll3W6wJmIh1Lw==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-knex@0.63.0': - resolution: {integrity: sha512-XrpRahI/9vTrfSUfkhy8jGX8KMRKecQIPU9GyEZ8gkR030iJwQYsMmKGO5TK9R80cQGUopXwDvV55zmVNEkcPg==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-knex@0.68.0': + resolution: {integrity: sha512-sCXpcMsx4Qbg5WZ+vzmaGDJnlUjrVee+cQ812xYkcmjRoYCcQH1L631rqHfUOu9OqqCwtt2/iRIzRcJYUx5lKg==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-koa@0.67.0': - resolution: {integrity: sha512-QOGY4mjqvF85LDcrzwrQXMcsu1wMTALeL1OHyTkLpN/7cnoDtv0W/qMBjHVq4IKYK6yDH4ZDNdwlonJPhwCGcw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-koa@0.72.0': + resolution: {integrity: sha512-tldfHvVxFHK/K8PcRQjegk2md0YWbkRQepU0/7rnQV/bvTD2oGu9JeNByBSk/Ckk5rH3qq7wdXSRoIajbQIjxw==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.9.0 - '@opentelemetry/instrumentation-lru-memoizer@0.63.0': - resolution: {integrity: sha512-DlZRNXfiosmREoLbEGbYuxF70cYXjrYqoaO1sJE167i1+ARWXTq0YMPJ97i53Ws/xkZWllJNYU4mpY2LM2yTlA==} - engines: {node: ^18.19.0 || >=20.6.0} - peerDependencies: - '@opentelemetry/api': ^1.3.0 - - '@opentelemetry/instrumentation-memcached@0.62.0': - resolution: {integrity: sha512-kAajd/MtdRBh9PCrMM4fnusFRNPJDU1dv5w9cgnKtMfutRE6K03wBbGSeT3FD1M56sMYWVqPhiKUhfSZCMZrLg==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-lru-memoizer@0.68.0': + resolution: {integrity: sha512-zNcs1A+FISUHhZuKnlfuCxKn8hgYA80qHVdxFyNCMmxdZyShGRP1KA8HGrGYk0JqQK391IYCgisyt+7TI+3crA==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-mongodb@0.72.0': - resolution: {integrity: sha512-WYgGzvlHzdoxHlrhysYtjxE4RC23j/iFZ66hdMJuAoczOWoD/xb6LhRwaz4CM+LKyKtcSIadAjSUyGv2B+SNwg==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-memcached@0.67.0': + resolution: {integrity: sha512-EnjSnkxp7P/DGD3f/D/Uwa/BrsKWkRkEhR7OdTVyTnu1zk1p/vSTBnvLXVAqRqundONyWeHNeRrwDHBryFyR9Q==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-mongoose@0.65.0': - resolution: {integrity: sha512-P0iT4oKuinEFZlTIKPJC5hhnmiV9De9lEiLkGzSwnNLdkyHIWug8BfRp5ZROrYAQ9mm47H+WLB/ozvUvgzEvEA==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-mongodb@0.77.0': + resolution: {integrity: sha512-dC5tcoI/jrFvlS6CVayQ8nIU4OlTdRW6qFsCKI/C7UXRmXq7mPNA5DzwS0Pn2+KEMDGTuLamNRB9SNkFgraMVg==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-mysql2@0.65.0': - resolution: {integrity: sha512-Om6BJ/bmFBzNkGbAzj/UV5sCKX6jCGzhTl1Gqgtim/O0dnPE7F2zN65u16Fq3JgyypGAwT2iwh13tYdWkc8/RA==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-mongoose@0.70.0': + resolution: {integrity: sha512-cJSZVLCyozcoC+lDz3vhJgv6MtcppCZuZI5BpJlCxc15zR81AZ/807dyCSb7WEr5j15WkV1kLhYdJpS8Ugnwdg==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-mysql@0.65.0': - resolution: {integrity: sha512-sh1wRjFaTt+8DOhJ0134rFtJoHVUXKI8faIWTbj4zZNw847dzUgmkO8xOluJ9Css0JzT4vCeZofJmq9mQmmESA==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-mysql2@0.70.0': + resolution: {integrity: sha512-c+wyti8w8xZuXRUsmMBzKXpnTxrafCITnm+UiWIq5oyOpp+Y6n03+ASEP7K+EBLIMQZR6U3EX0iYTlUF7S3hBw==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-nestjs-core@0.65.0': - resolution: {integrity: sha512-/q8fN2M2zGl+gQRaF79dzqvyvVqHAI11c7xAQZy9W1eAtQScNwaQtPm0EUo5+aOgakaTksBrsiHUF0rQS24NsQ==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-mysql@0.70.0': + resolution: {integrity: sha512-zr+Tc6bSlqfDT+7am7iwCYVFUwI0omf7BWPBdSCcmJBY9Wzp9L4wk8LAzAWgJ4Q6kIM0Ntx4RR+lY8llGMIFTQ==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-net@0.63.0': - resolution: {integrity: sha512-fvmVdL4SlsYZf74mq6iLBPd6JJHRAe5utzN7Wt9e4nwa2S3pgExA9poOEmBL1CvIR47MceTA/A8vgVCF23ebbw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-nestjs-core@0.71.0': + resolution: {integrity: sha512-EGqspwpbOdarPoXz2TQfvxiKvYujCW2REJM65/pr9SnuF+kW9oWHbJLypKAoxF14SF0SWHIwD7T8OrTmmfqcMQ==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-openai@0.17.0': - resolution: {integrity: sha512-X3aEZnzj7SJkn1nmqEoD9IljmqENnGrd0vcJngcEApT8uqhFaeimONqKeIzKYvUgC7k4OkAUxC7yfXzxIK1KlA==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-net@0.68.0': + resolution: {integrity: sha512-SUwiNYcKWq5CVJC4CluReoDqnJdoNbwIcfJbqL0YVQN4gDWAi8vzeQMDAPfgIu4g0uuPEQV5/OTPjq4iGMgALg==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-oracledb@0.44.0': - resolution: {integrity: sha512-ncEfP4rzuZXBHJJtzWLYctK4Pq/FvZRiASxlFY9CJG9kGjaFTfzBUys0NiP27alYPvpjj0uDAMheDk9nihO8ZA==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-openai@0.22.0': + resolution: {integrity: sha512-1TIMdTkdUYpqN1Sv1kBGMJcs7kaV2j9LqblHTBpmGHd+HDVNmxmBeM9/+T7HUrICWGPYy7xvFi004N+0vLVytg==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': ^1.3.0 + '@opentelemetry/api': ^1.10.0 - '@opentelemetry/instrumentation-pg@0.71.0': - resolution: {integrity: sha512-jAhfyZeOkEKh3cQ5nm1tNWqHg7HFARyAe+p4BSoDHnB79c1woyEvDKqS11Hj/DjtceP+vrurIfcDs7Fqiy11mQ==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-oracledb@0.49.0': + resolution: {integrity: sha512-JsnPQM3ifh/8n+BKIlo1WA+r0K6DgcaEkD9+m2+r6zNQz2pyS9H2F3WYtmyNoH+FnAuHtwrUTQgapLfwiaZNag==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-pg@0.72.0': - resolution: {integrity: sha512-p9xrFc/6R8t6Y293sTYLZ83LnzZo/qY0bBPA4xabdQt0Qjt8i1SlYFsIeGY2Jmf5WcESNUdjQB3NxWnt5Ox7zw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-pg@0.77.0': + resolution: {integrity: sha512-eeM+nAWZqgwrSmGy/yt4wL8CSSXuHZXKyOOKiP0m6x7oA4AQ1Kl5bbHqdr1OkXu5LIXCnIWa6Cmw9tLdzCMLJA==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-pino@0.65.0': - resolution: {integrity: sha512-p6eh+NRmzi1F+/4QG7XDqRk4ICdCNTsM5vdcwUPnpMie2MddgY1/ENmWvCF9r0Kh6QQRA2kkpnhoJFaiRQ5kVw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-pino@0.70.0': + resolution: {integrity: sha512-JbxLZ5PhLJU0B1IWPX9/O14de8YGatiRLrlYz+cUy0no/rz6QLH8l6Bk+rF7geun4LHGqQlALIL/9SRDs+yuLg==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': ^1.3.0 + '@opentelemetry/api': ^1.10.0 - '@opentelemetry/instrumentation-redis@0.67.0': - resolution: {integrity: sha512-TBjO4bPvfGH6bRjJJ+KrJhEqpHg3SWCFZ84MqsTWF639RQZmvkMhT2/DJsBAqqkq33IvHoDJysserqAfZN1s+Q==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-redis@0.72.0': + resolution: {integrity: sha512-e9S4dMYpwq1pllqr7supmEC7ZziAzCB/D24X7+VbDbcpl7J+C0Md6RDtcE7BQcsW7428P10lxrYAxWcNIP0GrA==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-restify@0.64.0': - resolution: {integrity: sha512-X+gL4KpfPAx7Y07zKQVtyJPckhCcYJdSlEz0Kq0iR5nkQ8/AVWJ05/txl4voZbZdCuNdn+uLZTtJ60bAQwputQ==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-restify@0.69.0': + resolution: {integrity: sha512-76fmH5TQd4V6lpou7AVy2hYi0KfS+VV2zA6PWW9kuFAN/yq0hAr16l7+bHPtM2ae4MY3TSO56gkFNpAjOHXWDg==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-router@0.63.0': - resolution: {integrity: sha512-zIpsZSHGvbaqiEazwUm1X0FkPnLXIwZcL/llu/UplkeGNU58bsw70l2uMqNqTb7J+tzsBC09CLVPty5BhW3X9Q==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-router@0.68.0': + resolution: {integrity: sha512-EPc/e+ccOqYkIX4HRktNClgARaWoAsEjc4dAPt8V3bLySUktx+/Ew/+MZNtNS+CUE4n+J1BvGGdwh4+ZaHgb7A==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-runtime-node@0.32.0': - resolution: {integrity: sha512-Jo1jSgrHlah3lPpGNPsIpF0q52D5uSLRJrztWUoPc1/Tli2ZWZ+cArgNtcdmiLuKhW21MwYbbcrNw1fbOPeR3A==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-runtime-node@0.37.0': + resolution: {integrity: sha512-2QZ7M1OUTbowoExKX4eTrMAo0gO5dmxV91cARmkpHs2jzo6oFFLDTRfXluYMtNAhAhReswAsQ7BaKo7O7fo/rw==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': ^1.3.0 + '@opentelemetry/api': ^1.10.0 - '@opentelemetry/instrumentation-socket.io@0.66.0': - resolution: {integrity: sha512-XrZmLkFJktVLd3biQiP8BAhupRwPWLHGIiDCfyDAnWI6borIL0wD6BpwFKKPT/etpu4/5OaeAQ7qs/S+FY9nhQ==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-socket.io@0.71.0': + resolution: {integrity: sha512-12dOOiqCwgaQYMR7A2S4aAScn4ZTznCZdzoKiQS9AVHFOYasADgNaiYs6C1odOehnOfNMwt4Z02d5tfhauqy/A==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-tedious@0.38.0': - resolution: {integrity: sha512-9sRWyIMBHDqJvxRVZ+eQ7jHJ9Iu+DapO27WLZbQF1nyD8xIvEMuDonQ/HnlQiaRdwnqFknXSQTFusJUT3mNVyQ==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-tedious@0.43.0': + resolution: {integrity: sha512-x+v44lSHbe2a3HCxXWy57jybInwKRNHcMOArycdsHPEw+8YzH2DzQZViTO/J165qbSF0o+q9F1OtTJvr88Q45Q==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/instrumentation-undici@0.29.0': - resolution: {integrity: sha512-SnA+0XgGc595jtnwFVfWy7Vgfr5hle4D5YKIlm0U4z8aK9YoCZVUn1xAkVZ2evaJyykiDF50FBzr1XZ0uj8CPA==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-undici@0.34.0': + resolution: {integrity: sha512-RcAEj8opdr/9BVZyEzJatN7sHQCgmdCLvb8Tvf5CNxRmdWbR3FaLN0h7JaI2ganW78MKAX2lM7O5isNIweabnA==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.7.0 - '@opentelemetry/instrumentation-winston@0.63.0': - resolution: {integrity: sha512-NFMHLYODph0rWGfT/QLv75hCsu1sxVAV79L8HduBCMo181jOTSRZHaqxfrvDtFOsvgYBaiUBa7Ga50w47wM3FA==} - engines: {node: ^18.19.0 || >=20.6.0} - peerDependencies: - '@opentelemetry/api': ^1.3.0 - - '@opentelemetry/instrumentation@0.208.0': - resolution: {integrity: sha512-Eju0L4qWcQS+oXxi6pgh7zvE2byogAkcsVv0OjHF/97iOz1N/aKE6etSGowYkie+YA1uo6DNwdSxaaNnLvcRlA==} - engines: {node: ^18.19.0 || >=20.6.0} - peerDependencies: - '@opentelemetry/api': ^1.3.0 - - '@opentelemetry/instrumentation@0.219.0': - resolution: {integrity: sha512-X5t7I8GyIO9rmGHwoedZLREpQqrF1WW2nxzNNym6HOKpFiE+rvqV3ngC0xcZVO2YwIGf3KKmRdWrYwdwz3H9RQ==} - engines: {node: ^18.19.0 || >=20.6.0} - peerDependencies: - '@opentelemetry/api': ^1.3.0 - - '@opentelemetry/instrumentation@0.220.0': - resolution: {integrity: sha512-xQx3E2WxP1mDvKzxLxX+CTCtNLa560YJZ3087qYHerl2YmiKpv7AH+dAy7vmx+eVrZ5BwhfWUAVoKOoxCNHcpw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation-winston@0.69.0': + resolution: {integrity: sha512-O+zFASmPbEd1hIx5Y/VGQsbf9/OFU4KtZXI1qFig/WYeY4YZeTKiMN2nn1UGDBoxeBahbXMkt26ZCMWF/PbGIQ==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': ^1.3.0 + '@opentelemetry/api': ^1.10.0 - '@opentelemetry/otlp-exporter-base@0.219.0': - resolution: {integrity: sha512-zvIxQX/AZUVKDU+hCuYx+7UkiP7GRdnk1ZbFQRYzHvYp47cAWR4j3IhoPhV9KaeXEv2xdGq3IA6PnpzDmLcmSA==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/instrumentation@0.300.0': + resolution: {integrity: sha512-8ugx3X75uK2+rFZ9pX252ruDRELE2F7T3Zwazyll21aXksm+d2JLc9Np9SPS48K4ohGeaaXXHSX4ghxuNQ/gMg==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': ^1.3.0 + '@opentelemetry/api': '>=1.10.0 <1.11.0' - '@opentelemetry/otlp-grpc-exporter-base@0.219.0': - resolution: {integrity: sha512-iIk/s8QQu39zpTrRRmsW/Eg3SE2+Hg8tLWepr2FLRgmwUpNd0IpCTLJEHJ77hpt4hgIS8MAh44UYI4xQPZwWlw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/otlp-exporter-base@0.300.0': + resolution: {integrity: sha512-D+PhzYURtv6p7Kk1rUrilLtV+ZvS218tI0jiKTV5z1agOeELw78C+cFd3o9UUshUx1j+EIpFM62yGk8BuydQvg==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/otlp-transformer@0.219.0': - resolution: {integrity: sha512-aaYKAyXhw9VchKZVGOopD3Gw/kPsyrX2c6IQ0AW32mTjqmZOh5Y6Gf5OYqTNqVktAeBjmFinhyFaCwW6GYK9YQ==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/otlp-grpc-exporter-base@0.300.0': + resolution: {integrity: sha512-0C6rf7vVQrT7ZCUYJRZ1P4TsauCfSc4qXSpwqBWW5Ztt/4gxt5uHfLw2nTirSuPpz0sSeeRPW+Z0HyKJXB/CTQ==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.3.0 - '@opentelemetry/propagator-aws-xray@2.2.0': - resolution: {integrity: sha512-Yjvt2EjL+tfpkVOdKbhTPgpM4SIAez9nG6Q/QjQ3yfcJcjIWp59ph70SLfvmkSL6++3DCnuBG3iWcB18PwWavQ==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/otlp-transformer@0.300.0': + resolution: {integrity: sha512-T55lRmjRwvXWyTFdy/BbJ3T5RRsq3bAwQgxxA7qHFxgRd4+pZzRk02ZwOFsYK5072OXGYjYFNJcp68eQV4i0Ig==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': '>=1.0.0 <1.10.0' + '@opentelemetry/api': '>=1.10.0 <1.11.0' - '@opentelemetry/propagator-b3@2.8.0': - resolution: {integrity: sha512-SazlvuSKi5533rPHTW2TwBwdMakhjZST4SYs0YauuvfGDkT13KbG1gJS75hV0uWVeevhtVP9sAIlaZLTHdSbMg==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/propagator-aws-xray@3.0.0': + resolution: {integrity: sha512-5RHIXJFFPsX2e5Z2lUjcsCOkouW08PuFb9Vfg5l22E0PZ01tapU11wH/gb8RCGckjlvgoc+HrWmYtu/VqI2kAQ==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': '>=1.0.0 <1.10.0' + '@opentelemetry/api': '>=1.0.0 <1.11.0' - '@opentelemetry/propagator-jaeger@2.8.0': - resolution: {integrity: sha512-Xnz9zZvvQzUw+9DrOn0MomR7BxFCkA2pcfXBQuHC28ndJpSbjLs7knzYb05kw5SyCjSsEWombkZMgGcJSk8JVg==} - engines: {node: ^18.19.0 || >=20.6.0} - deprecated: Package no longer supported. See https://github.com/open-telemetry/opentelemetry-js/pull/7077 + '@opentelemetry/propagator-b3@3.0.0': + resolution: {integrity: sha512-pmG16s+UYAobPmtWfkR1/UK233qdl79WO04GnNzr7aoG/P+Aafbn8+5OJg2zl107WvLPYelCUKFiI18GksGbqg==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': '>=1.0.0 <1.10.0' + '@opentelemetry/api': '>=1.0.0 <1.11.0' - '@opentelemetry/redis-common@0.38.3': - resolution: {integrity: sha512-VCghU1JYs/4gP6Gqf/xro9MEsZ7LrMv2uONVsaESKL38ZOB9BqnI98FfS23wjMnHlpuE+TTaWSoAVNpTwYXzjw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/redis-common@0.39.0': + resolution: {integrity: sha512-LwhsURMcyCigjnQHni9RAt0ezrVRxcb6kIE2UTbVI1cxxteeH8mTpPV7xBOVEG2GEm1GniEPLeVkXFHgiIw3xg==} + engines: {node: '>=22.15.0'} - '@opentelemetry/resource-detector-alibaba-cloud@0.34.0': - resolution: {integrity: sha512-hUs4CK7MbRfffw8y5zR4Mo37MJRR3Zt8Ub4rgMkIk7gL8jozjV7k+zwIk9grz5kGAuD406BDDIghaY8090K4Zw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/resource-detector-alibaba-cloud@0.39.0': + resolution: {integrity: sha512-QRVfll/M50DqDeVawyIonXtxDBhyPiEuxtTvCuQ5t+PML7jP73p4Y9vIggAZanzdvMOKcYZfsiPmBzXUc16Oug==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.0.0 - '@opentelemetry/resource-detector-aws@2.21.0': - resolution: {integrity: sha512-Veavy+khoywR+Hv065SU5jucFTGTiW1KXo39CsJ+8wqdYYz8jiRJPnQ20Kd+X9HbV2+Abb0l5CrJIdxK1ZOqBg==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/resource-detector-aws@3.1.0': + resolution: {integrity: sha512-O9vEieI1x6dR6L78aDe+MyAKc4j3e/9Zgu39mPj095sqXISUB+1gV/sv+67mEdSoqCudFcHcq9PE5YUsnW13cw==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': ^1.0.0 + '@opentelemetry/api': ^1.10.0 - '@opentelemetry/resource-detector-azure@0.27.0': - resolution: {integrity: sha512-m6HCEmK12QpEcWbKtvGpQtoDVceXtpB14AaaW/t5f6gHeLuGq1QivkuohkvKMkxgAdwIHxEQ8qof3whWBpd8JA==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/resource-detector-azure@0.32.0': + resolution: {integrity: sha512-uVtFH5rAbD0vDnmghJHCZKllhGPifVn5Cf1XZDSPEZDxB0fD3JND+a1qTyJ088RLM959P558wFqnxp1TU8RiTw==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.0.0 - '@opentelemetry/resource-detector-container@0.8.12': - resolution: {integrity: sha512-EJRFfIY26whY0w5RDxMRXlfBDgDS001JYMHuOVuDBBsRrV4MBqoVajR9B0L9Vy728+w/HNVnSQkpJFacFr+klg==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/resource-detector-container@0.9.1': + resolution: {integrity: sha512-whlMDisUotc0r3yZV3tq/tVajkYQ23ssqAYfIaCImYxFco4I6g1DC6WP8scVEA7X2NRD06Ww0kjpY++MylTHoQ==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': ^1.0.0 + '@opentelemetry/api': ^1.10.0 - '@opentelemetry/resource-detector-gcp@0.54.0': - resolution: {integrity: sha512-u+6sBzQO03QQGFhxjzFa7uNbH6iQpWTcrpWyomxuppH3AN/+1mm3DRVseS1CiRq9VBKrFO0UosWAdD7fWVUrrg==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/resource-detector-gcp@0.59.0': + resolution: {integrity: sha512-zcZyAT9tkZIWCVRd84ivwNNZiBF2iW3HPe02LZfkRLfYaGzaRueh2imKjvjiwhhxpQHfWUREATk4oflVMAqr+A==} + engines: {node: '>=22.15.0'} peerDependencies: '@opentelemetry/api': ^1.0.0 - '@opentelemetry/resources@2.10.0': - resolution: {integrity: sha512-q6MMm2zhggzsHVNbabYwut+a6nbuQQe3URUoxaojM/8K1IBfwwPzvxIjNi2/lI1TFe+fMHMW9MWhrtDLEXEnkA==} - engines: {node: ^18.19.0 || >=20.6.0} - peerDependencies: - '@opentelemetry/api': '>=1.3.0 <1.10.0' - - '@opentelemetry/resources@2.8.0': - resolution: {integrity: sha512-qmXQ27ilDbUK/vGMqwL8D4/rhn76C+sherM4wTbjlfknR8Nvfc/hCxjRJPhkzZzUsPiNg16SA31NxMabwttRjg==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/resources@3.0.0': + resolution: {integrity: sha512-4762KVmlDroRIt+4Ra8AnwcQqdXlkAR55jDrhzna8bzhJx1mUzvHW/Lh/OemFuY9+ouM4xaDc6CbUmoJmM6BFg==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': '>=1.3.0 <1.10.0' + '@opentelemetry/api': '>=1.10.0 <1.11.0' - '@opentelemetry/sdk-logs@0.219.0': - resolution: {integrity: sha512-s6lTKRakaPClvKoWHRChxnXjDMkM/TQ30ff78jN6EBGf7MI7VzANE5PU3f4z9qDUudWjvZjOLHG0rBnBKYvoXA==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/resources@3.1.1': + resolution: {integrity: sha512-dSd0FI1rfl+WHeaZxCTCEvwv6vcmUqkOHHTGWMkmyHg+PyL/wLbCqgsGKgI0wOwT0KGy9IMPAvY85hT8IPwApA==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': '>=1.4.0 <1.10.0' + '@opentelemetry/api': '>=1.10.0 <1.11.0' - '@opentelemetry/sdk-metrics@2.8.0': - resolution: {integrity: sha512-UDBGaj6W0Rgy5rTTaoxs8gVGF/aGkAKyjurJv7se6wjRxJu7FoquTLT/vt54DZfo4crbprYfhX/SOK9+BPw1qg==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/sdk-logs@3.0.0': + resolution: {integrity: sha512-IysNZWrBk2PqYw4qU9PZcC7pjrZLa+KLk7vcLmPPNBUr97MgeamWhX0DUHsmxwJv3dnjYM6mLRmP8mw69ld+dA==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': '>=1.9.0 <1.10.0' + '@opentelemetry/api': '>=1.10.0 <1.11.0' - '@opentelemetry/sdk-node@0.219.0': - resolution: {integrity: sha512-NWLpWLEb8gV3+JBHYoIrktbM385wyHpRJoh3J/4Q52d4PR+AlPMNGJT3DzBUrDSUEVbKAXoHR+EDAPxtiNcj8g==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/sdk-metrics@3.0.0': + resolution: {integrity: sha512-YozyS2rIlizvUNLZwcWxH0x2FhX02/mcZwzM8hsl8yvQk+xeKmAc7vcSieWiO4oSwIB20B8eS/zwdopAd/J5zQ==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': '>=1.3.0 <1.10.0' + '@opentelemetry/api': '>=1.10.0 <1.11.0' - '@opentelemetry/sdk-trace-base@2.8.0': - resolution: {integrity: sha512-mhU4jp+vW0mGbFRd+GeXHvmfA4aDqWjBjLC3pE5XMpLs0IE2ryYb019Ts2AQrOq67gaTF25D91+fgvEHDZEnuQ==} - engines: {node: ^18.19.0 || >=20.6.0} - deprecated: Use @opentelemetry/sdk-trace package + '@opentelemetry/sdk-node@0.300.0': + resolution: {integrity: sha512-yRaNP91ilq0m5fBCXSo7ZTR1NDd/GPu02uq0Rur2kMw7VheHwkV8i68oYt4/vM+eofRFKYCGS5B2QrgcZS/rmw==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': '>=1.3.0 <1.10.0' + '@opentelemetry/api': '>=1.10.0 <1.11.0' - '@opentelemetry/sdk-trace-node@2.8.0': - resolution: {integrity: sha512-nZt9OGufioAc3AfoLTqA9bsAeaMJAictYDdI2VcNQ+PmT+3rfKjAZDZvgPfd8VPX0O5Bw1hdQF6kDK8VSpZiWg==} - engines: {node: ^18.19.0 || >=20.6.0} - deprecated: Use @opentelemetry/sdk-trace package + '@opentelemetry/sdk-trace@3.0.0': + resolution: {integrity: sha512-4T0DbDGdtsjNmYK5/lNalHro4fsMZ0UZ3JE+C8fcqYP25xaJC22FHg8kdJNJ21srjJY5XoT7WNFCtj88NNTl4Q==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': '>=1.0.0 <1.10.0' + '@opentelemetry/api': '>=1.10.0 <1.11.0' '@opentelemetry/semantic-conventions@1.43.0': resolution: {integrity: sha512-eSYWTm620tTk45EKSedaUL8MFYI8hW164hIXsgIHyxu3VobUB3fFCu5t0hQby6OoWRPsG1KkKUG2M5UadiLiVg==} engines: {node: '>=14'} - '@opentelemetry/sql-common@0.42.0': - resolution: {integrity: sha512-nwUwUU+8O8a4bnLqk6CodWeegGMEANgC94KTAhXcpGWLrW/2/hek/0ajNbjXnSOoNuCX+nteUPs46HFHhou9Xw==} - engines: {node: ^18.19.0 || >=20.6.0} + '@opentelemetry/sql-common@0.43.1': + resolution: {integrity: sha512-a6QbfVVjLUatgzpcE37pWK1GIHCcG6nXJF5FS+O+ExU64VPs1HtGhdZ96CERhwTY5fOP1pJfFsYUpEqtOY1Uqg==} + engines: {node: '>=22.15.0'} peerDependencies: - '@opentelemetry/api': ^1.1.0 + '@opentelemetry/api': ^1.10.0 '@oslojs/encoding@1.1.0': resolution: {integrity: sha512-70wQhgYmndg4GCPxPPxPGevRKqTIJ2Nh4OkiMWmDAVYsTQ+Ta7Sq+rPevXyXGdzr30/qZBnyOalCszoMxlyldQ==} @@ -3518,9 +3451,6 @@ packages: '@tokenizer/token@0.3.0': resolution: {integrity: sha512-OvjF+z51L3ov0OyAU0duzsYuvO01PH7x4t6DJx+guahgTnBHkhJdG7soQeTSFLWN3efnHyibZ4Z8l2EuWwJN3A==} - '@ts-morph/common@0.28.1': - resolution: {integrity: sha512-W74iWf7ILp1ZKNYXY5qbddNaml7e9Sedv5lvU1V8lftlitkc9Pq1A+jlH23ltDgWYeZFFEqGCD1Ies9hqu3O+g==} - '@tybys/wasm-util@0.10.1': resolution: {integrity: sha512-9tTaPJLSiejZKx+Bmog4uSubteqTvFrVrURwkmHixBo0G4seD0zUxp98E1DzUBJxLQ3NPwXrGKDiVjwx/DpPsg==} @@ -3542,9 +3472,6 @@ packages: '@types/bun@1.3.8': resolution: {integrity: sha512-3LvWJ2q5GerAXYxO2mffLTqOzEu5qnhEAlh48Vnu8WQfnmSwbgagjGZV6BoHKJztENYEDn6QmVd949W4uESRJA==} - '@types/bunyan@1.8.11': - resolution: {integrity: sha512-758fRH7umIMk5qt5ELmRMff4mLDlN+xyYzC+dkPTdKwbSkJFvz6xwyScrytPU0QIBbRRwbiE8/BIg8bpajerNQ==} - '@types/chai@5.2.3': resolution: {integrity: sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==} @@ -3584,18 +3511,12 @@ packages: '@types/ms@2.1.0': resolution: {integrity: sha512-GsCCIZDE/p3i96vtEqx+7dBUGXrc7zeSK3wwPHIaRThS+9OhWIXRqzs4d6k1SVU8g91DrNRWxWUGhp5KXQb2VA==} - '@types/mysql@2.15.27': - resolution: {integrity: sha512-YfWiV16IY0OeBfBCk8+hXKmdTKrKlwKN1MNKAPBu5JYxLwBEZl7QzeEpGnlZb3VMGJrrGmB84gXiH+ofs/TezA==} - '@types/nlcst@2.0.3': resolution: {integrity: sha512-vSYNSDe6Ix3q+6Z7ri9lyWqgGhJTmzRjZRqyq15N0Z/1/UnVsno9G/N40NBijoYx2seFDIl0+B2mgAb9mezUCA==} '@types/node@24.10.11': resolution: {integrity: sha512-/Af7O8r1frCVgOz0I62jWUtMohJ0/ZQU/ZoketltOJPZpnb17yoNc9BSoVuV9qlaIXJiPNOpsfq4ByFajSArNQ==} - '@types/oracledb@6.5.2': - resolution: {integrity: sha512-kK1eBS/Adeyis+3OlBDMeQQuasIDLUYXsi2T15ccNJ0iyUpQ4xDF7svFu3+bGVrI0CMBUclPciz+lsQR3JX3TQ==} - '@types/pg-pool@2.0.7': resolution: {integrity: sha512-U4CwmGVQcbEuqpyju8/ptOKg6gEC+Tqsvj2xS9o1g71bUh8twxnC6ZL5rZKCsGN0iyH0CwgUyc9VR5owNQF9Ng==} @@ -3608,9 +3529,6 @@ packages: '@types/sax@1.2.7': resolution: {integrity: sha512-rO73L89PJxeYM3s3pPPjiPgVVcymqU490g0YO5n5By0k2Erzj6tay/4lr1CHAAU4JyOWd1rpQ8bCf6cZfHU96A==} - '@types/tedious@4.0.14': - resolution: {integrity: sha512-KHPsfX/FoVbUGbyYvk1q9MMQHLPeRZhRJZdO45Q4YjvFkv4hMNghCWTvy7rdKessBsmtz4euWCWAB6/tVpI1Iw==} - '@types/unist@2.0.11': resolution: {integrity: sha512-CmBKiL6NNo/OqgmMn95Fk9Whlp2mtvIv+KNpQKN2F4SjvrEesubTRWGYSg+BnWZOnlCaSTU1sMpsBOzgbYhnsA==} @@ -3620,6 +3538,126 @@ packages: '@types/ws@8.18.1': resolution: {integrity: sha512-ThVF6DCVhA8kUGy+aazFQ4kXQ7E1Ty7A3ypFOe0IcJV8O/M511G99AW24irKrW56Wt44yG9+ij8FaqoBGkuBXg==} + '@typescript/typescript-aix-ppc64@7.0.2': + resolution: {integrity: sha512-MTKKkWB7p/0E9xi1d1tHtZ5PiLkGEMIq88pK2CubZjOsLtYTLqhgIgi6zepFa+9GHZ6h05NMCkQxGKiPXMxXtQ==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [aix] + + '@typescript/typescript-darwin-arm64@7.0.2': + resolution: {integrity: sha512-gowzar9MwS/aRWp6f3a4KUqzRjAZjOsmGNCM6LcTgXum+dBfgsBVMN+AgvOCCbguXyick6LJhpBszxMebJ8syA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [darwin] + + '@typescript/typescript-darwin-x64@7.0.2': + resolution: {integrity: sha512-SZ9xZInqApNlNGc9s0W1VSsktYSOe9cFqNOIqmN1Gs8SmkjKZYFt017G4VwPxASInODuAdbTW7sXiFUf893RgA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [darwin] + + '@typescript/typescript-freebsd-arm64@7.0.2': + resolution: {integrity: sha512-W5NH4y/J0plIIS5b2xvTEkU7JFxyqdMAOgf+Ilhl0vHQXKO5dZoxd+C/jEtq56c4F3wk71RB4BMRQ2XdI+bwYQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [freebsd] + + '@typescript/typescript-freebsd-x64@7.0.2': + resolution: {integrity: sha512-UMGDx5sTpzNw3WiPebH7l90IWfJggEd+egHt/q6p7/Cm3zqoV7VxkGXt+3DxPIw8CcmvAB0j3sVVfbhX+M4Tpw==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [freebsd] + + '@typescript/typescript-linux-arm64@7.0.2': + resolution: {integrity: sha512-Qh4eU4/y3yDjnfjjyPYihMj5/ODIlmt+Bzu17OI+fiSRDW57QmU5SiN63exPRNJPKUzcc1INa1NXdrJ+MqHjUQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [linux] + + '@typescript/typescript-linux-arm@7.0.2': + resolution: {integrity: sha512-gffT3xPz9sR7j/YJExkyPntrI0P2EP9XbOyWzth2/Gs0RstK+90RBcO0ncXoXy/beYll1SXw846Nf2zdnEz0QQ==} + engines: {node: '>=16.20.0'} + cpu: [arm] + os: [linux] + + '@typescript/typescript-linux-loong64@7.0.2': + resolution: {integrity: sha512-uEHck9i8hoAzXPiYRib1O7miOnz23SxIeVl6F4LXox+qov1K35jHcEW6VHKvZI+pyvl7fZEP4MCU5LYvIq1GuQ==} + engines: {node: '>=16.20.0'} + cpu: [loong64] + os: [linux] + + '@typescript/typescript-linux-mips64el@7.0.2': + resolution: {integrity: sha512-R4KvAMnE43W5Qeqb0Ly56O3mWMWIAgsMyz36DCaycd5nbg/9kzm0liw3JocfRqyJY0KPmzFjbswozXyW0DnIYA==} + engines: {node: '>=16.20.0'} + cpu: [mips64el] + os: [linux] + + '@typescript/typescript-linux-ppc64@7.0.2': + resolution: {integrity: sha512-DORx5b3sd/4S7eayxm4FQv+A7CrkUIGRaHiwI8oiHTAI1fAPWhF4J0vAlkC8biAlHSVVwxMQ3tjZ2/DVbnQiiA==} + engines: {node: '>=16.20.0'} + cpu: [ppc64] + os: [linux] + + '@typescript/typescript-linux-riscv64@7.0.2': + resolution: {integrity: sha512-wf0jqEDOjrPRnKwYRyyJDRo11KMbvMFrU+q4zqKyChODBzvlkbhNQfKvLxQCcwTpdDaXSHZTVuh0JoCrKCUMHQ==} + engines: {node: '>=16.20.0'} + cpu: [riscv64] + os: [linux] + + '@typescript/typescript-linux-s390x@7.0.2': + resolution: {integrity: sha512-IkwJc3L7yhytWd/ewjyxNDfOmswCm9GWMJT/ue/dU4aZNbwZeYAetq42VyLmsmSjvoX7z74X6ZaYCtzAr0EuGw==} + engines: {node: '>=16.20.0'} + cpu: [s390x] + os: [linux] + + '@typescript/typescript-linux-x64@7.0.2': + resolution: {integrity: sha512-EYdf2cNg7rgCWJnxCdJ+F3V39O8ihb37eHAu1LK8oAFizgTQbPOK7zHHXbPt8rX24COqODXeI3sIf0fCXG7H/A==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [linux] + + '@typescript/typescript-netbsd-arm64@7.0.2': + resolution: {integrity: sha512-+polYF4MF04aPpO5FTkHran9yUQDSXqy5GiSDKpsll5jy3l3+g9QLhpf39T+ePtefhXLOGrLl0QIjkQP6VnelA==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [netbsd] + + '@typescript/typescript-netbsd-x64@7.0.2': + resolution: {integrity: sha512-8YIT0EHM/3dq10ZOVF/A7pc/YSMtbcecct4rWtexrnSCHOPcpC2KTLXfTCR6vDpnSiY12heNb1GiN/wu+T/FyA==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [netbsd] + + '@typescript/typescript-openbsd-arm64@7.0.2': + resolution: {integrity: sha512-APT8+ClYnuYm1u9+kgGXoMj2VzWzcymwh2gNSQVySHfkRDGOTVkoWLjCmOQSaO+PoqQ57B0flRp9SA+7GnnkzQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [openbsd] + + '@typescript/typescript-openbsd-x64@7.0.2': + resolution: {integrity: sha512-yX7s+Q0Dln0Dt9tEzZsAjXXR/+ytBM7AlglaqyeMPxQszJ1JhlJdZ6jLA+IzldHtflX81em7lDao1xXu+aRRkg==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [openbsd] + + '@typescript/typescript-sunos-x64@7.0.2': + resolution: {integrity: sha512-dLJDGaLZ1D4HPQn62u1n8mBDkJREwMsAkCdkwd4Ieqw+x3TUyTsqY0YiBCtE6H6OzzgGk3iuZ3vFWRS+E8/d1g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [sunos] + + '@typescript/typescript-win32-arm64@7.0.2': + resolution: {integrity: sha512-Gyl1Vy6OsWesLzmq+EP0Fb7b4Nid5232AvcA2SFcdYreldpNtYFFofPjnt62y9hQy7VTaZp65ICJjuAQRaVcIQ==} + engines: {node: '>=16.20.0'} + cpu: [arm64] + os: [win32] + + '@typescript/typescript-win32-x64@7.0.2': + resolution: {integrity: sha512-0BQ3HkAHHlKLSp1qRvf3SUhGpGsDuhB/jgFw75guyqbxJqEaS0Cw/VFO8i2nHglJUzQCRtMMR/IBAKE3ETMC4g==} + engines: {node: '>=16.20.0'} + cpu: [x64] + os: [win32] + '@ungap/structured-clone@1.3.1': resolution: {integrity: sha512-mUFwbeTqrVgDQxFveS+df2yfap6iuP20NAKAsBt5jDEoOTDew+zwLAOilHCeQJOVSvmgCX4ogqIrA0mnyr08yQ==} @@ -3672,11 +3710,6 @@ packages: resolution: {integrity: sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==} engines: {node: '>= 0.6'} - acorn-import-attributes@1.9.5: - resolution: {integrity: sha512-n02Vykv5uA3eHGM/Z2dQrcD56kL8TyDb2p1+0P83PClMnC/nc+anbQRhIOWnSq4Ke/KvDPrY3C9hDtC/A3eHnQ==} - peerDependencies: - acorn: ^8 - acorn-jsx@5.3.2: resolution: {integrity: sha512-rq9s+JNhf0IChjtDXxllJ7g41oZk5SlXtp0LHwyA5cejwn7vKmKp4pPri6YEePv2PU65sAsegbXtIinmDFDXgQ==} peerDependencies: @@ -3808,10 +3841,6 @@ packages: balanced-match@1.0.2: resolution: {integrity: sha512-3oSeUO0TMV67hN1AmbXsK4yaqU7tjiHlbxRDZOpH0KW9+CeX4bRAaX0Anxt0tx2MrpRpWwQaPwIlISEJhYU5Pw==} - balanced-match@4.0.4: - resolution: {integrity: sha512-BLrgEcRTwX2o6gGxGOCNyMvGSp35YofuYzw9h1IMTRmKqttAZZVU67bdb9Pr2vUHA8+j3i2tJfjO6C6+4myGTA==} - engines: {node: 18 || 20 || >=22} - base64-js@1.5.1: resolution: {integrity: sha512-AKpaYlHn8t4SVbOHCy+b5+KKgvR4vrsD8vbvrbiQJps7fKDTkjkDry6ji0rUJjC0kzbNePLwzxq8iypo41qeWA==} @@ -3860,6 +3889,10 @@ packages: resolution: {integrity: sha512-p5tAzS57i5MV9fZFDj9LeIiTZEufbSe2eDozP+ElheSUq1m74CRq1jI4mYNDdVs9vQztXFLuk/Gd6BWTdwRJ5g==} engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16} + body-parser@1.20.9: + resolution: {integrity: sha512-FISIQxV5u91Y9gvuFq3q/tA/qTqLJn3AhRcEvyozyhJTh5OBFFtv827AdHU7Rbyct4r+Ba1/99oFa1Y3yuFsdw==} + engines: {node: '>= 0.8', npm: 1.2.8000 || >= 1.4.16} + boolbase@1.0.0: resolution: {integrity: sha512-JZOSA7Mo9sNGB8+UjSgzdLtokWAky1zbztM3WRLCbZ70/3cTANmQmOdR7y2g+J0e2WXywy1yS468tY+IruqEww==} @@ -3869,10 +3902,6 @@ packages: brace-expansion@2.1.4: resolution: {integrity: sha512-hGfVzPxthbf3+2yjg/RBs60cB0FhqBS/zvdV/4wn4/BmN0bNMMHPc4V/BbFieqf1TKAGGAHnY4eSjajCl0f2Xg==} - brace-expansion@5.0.9: - resolution: {integrity: sha512-ScQ4IuvIEF1TMlP7Zt+vjJ//9zlPb2SDcxWxM3bk8s6t6GGdJ7KO1dCcTidOPJKePW30LE/2cT7wCyPho9/Wxg==} - engines: {node: 20 || >=22} - braces@3.0.3: resolution: {integrity: sha512-yQbXgO/OSZVD2IsiLlro+7Hf6Q18EJrKSEsdoMzKePKXct3gvD8oLcOQdIzGupr5Fj+EDe8gO/lxc1BzfMpxvA==} engines: {node: '>=8'} @@ -3921,13 +3950,6 @@ packages: caniuse-lite@1.0.30001793: resolution: {integrity: sha512-iwSsYWaCOoh26cV8NwNRViHlrfUvYsHDfRVcbtmw0Kg6PJIZZXwMkj1442FYLBGkeUf1juAsU3DTfxW579mrPA==} - cbor-extract@2.2.2: - resolution: {integrity: sha512-hlSxxI9XO2yQfe9g6msd3g4xCfDqK5T5P0fRMLuaLHhxn4ViPrm+a+MUfhrvH2W962RGxcBwEGzLQyjbDG1gng==} - hasBin: true - - cbor-x@1.6.6: - resolution: {integrity: sha512-8QiD9PGOxyQHo7s2pzwTBH6lTjqekxPdl9Aq6fXvZgCuCJHOht1puDEA/fTr6mciB76c+M+Gi0qT2i1a4pm4Wg==} - cborg@1.10.2: resolution: {integrity: sha512-b3tFPA9pUr2zCUiCfRd2+wok2/LBSNUMKOuRRok+WlvvAgEt/PlbgPTsZUcwCOs53IJvLgTp0eotwtosE6njug==} hasBin: true @@ -4010,10 +4032,6 @@ packages: resolution: {integrity: sha512-BSeNnyus75C4//NQ9gQt1/csTXyo/8Sb+afLAkzAptFuMsod9HFokGNudZpi/oQV73hnVK+sR+5PVRMd+Dr7YQ==} engines: {node: '>=12'} - cliui@9.0.1: - resolution: {integrity: sha512-k7ndgKhwoQveBL+/1tqGJYNz097I7WOvwbmmU2AR5+magtbjPWQTS1C5vzGkBC8Ym8UWRzfKUzUUqFLypY4Q+w==} - engines: {node: '>=20'} - clsx@2.1.1: resolution: {integrity: sha512-eYm0QWBtUrBWZWG0d386OGAw16Z995PiOVo2B7bjWSbHedGl5e0ZWaq65kOGgUSNesEIDkB9ISbTg/JK9dhCZA==} engines: {node: '>=6'} @@ -4026,9 +4044,6 @@ packages: resolution: {integrity: sha512-gfrHV6ZPkquExvMh9IOkKsBzNDk6sDuZ6DdBGUBkvFnTCqCxzpuq48RySgP0AnaqQkw2zynOFj9yly6T1Q2G5Q==} engines: {node: '>=16'} - code-block-writer@13.0.3: - resolution: {integrity: sha512-Oofo0pq3IKnsFtuHqSF7TqBfr71aeyZDVJ0HpmqB7FBM2qEigL0iPONSCZSO9pE9dZTAxANe5XHG9Uy0YMv8cg==} - collapse-white-space@2.1.0: resolution: {integrity: sha512-loKTxY1zCOuG4j9f6EPnuyyYkf58RnhhWTvRoZEokgB+WbdXehfjFviyOVYkqzEWz1Q5kRiZdBYS5SwxbQYwzw==} @@ -4279,10 +4294,6 @@ packages: domutils@3.2.2: resolution: {integrity: sha512-6kZKyUajlDuqlHKVX1w7gyslj9MPIXzIFiz/rGu35uC1wMi+kMhQwGhl4lt9unC9Vb9INnY9Z3/ZA3+FhASLaw==} - dotenv@17.4.2: - resolution: {integrity: sha512-nI4U3TottKAcAD9LLud4Cb7b2QztQMUEfHbvhTH09bqXTxnSie8WnjPALV/WMCrJZ6UV/qHJ6L03OqO3LcdYZw==} - engines: {node: '>=12'} - dset@3.1.4: resolution: {integrity: sha512-2QF/g9/zTaPDc3BjNcVTGoBbXBgYfMTTceLaYcFJ/W9kggFUkhxD/hMEeuLKbugyef9SqAx8cpgwlIP/jinUTA==} engines: {node: '>=4'} @@ -4309,9 +4320,6 @@ packages: electron-to-chromium@1.5.361: resolution: {integrity: sha512-Q6Hts7N9FnJc5LeGRINFvLhCI9xZmNtTDe5ZbcVezQz7cU4a8Aua3GH1b8J2XY8Al9PF+OCwYqhgsOOheMdvkA==} - emoji-regex@10.6.0: - resolution: {integrity: sha512-toUI84YS5YmxW219erniWD0CIVOo46xGKColeNQRgOzDorgBi1v4D71/OFzgD9GO2UGKIv1C3Sp8DAn0+j5w7A==} - emoji-regex@8.0.0: resolution: {integrity: sha512-MSjYzcWNOA0ewAHpz0MxpYFvwg6yjy1NG3xteoqz644VCo/RPgnr1/GGt+ic3iJTzQ8Eu3TdM14SawnVUmGE6A==} @@ -4371,6 +4379,9 @@ packages: es-module-lexer@2.3.2: resolution: {integrity: sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==} + es-module-lexer@3.0.4: + resolution: {integrity: sha512-BldNY5mwkVu+cQ5Ymn3e6hB9Sx8XHx4ZevWbiUyZbfKxJxYO27Hf0wfzkxIaD5CAJMaGl3YspKELj0ff/7nCMA==} + es-object-atoms@1.1.2: resolution: {integrity: sha512-HWcBoN6NileqtSydK2FqHbS/LoDd2pqrnQHLyJzBj4kOp/ky2MWMN694xOfkK8/SnUsW2DH7EfyVlydKCsm1Zw==} engines: {node: '>= 0.4'} @@ -4615,10 +4626,6 @@ packages: resolution: {integrity: sha512-DyFP3BM/3YHTQOCUL/w0OZHR0lpKeGrxotcHWcqNEdnltqFwXVfhEBQ94eIo34AfQpo0rGki4cyIiftY06h2Fg==} engines: {node: 6.* || 8.* || >= 10.*} - get-east-asian-width@1.6.0: - resolution: {integrity: sha512-QRbvDIbx6YklUe6RxeTeleMR0yv3cYH6PsPZHcnVn7xv7zO1BHN8r0XETu8n6Ye3Q+ahtSarc3WgtNWmehIBfA==} - engines: {node: '>=18'} - get-intrinsic@1.3.0: resolution: {integrity: sha512-9fSjSaos/fRIVIp+xSJlE6lfwhES7LNtKaCBIamHsjr2na1BiABJPo0mOjjz8GJDURarmCPGqaiVg5mfjb98CQ==} engines: {node: '>= 0.4'} @@ -4664,9 +4671,6 @@ packages: graceful-fs@4.2.11: resolution: {integrity: sha512-RbJ5/jmFcNNCcDV5o9eTnBLJ/HszWV0P73bc+Ff4nS/rJj+YaS6IGyiOL0VoBYX+l1Wrl3k63h/KrH+nhJ0XvQ==} - graphemer@1.4.0: - resolution: {integrity: sha512-EtKwoO6kxCL9WO5xipiHTZlSzBm7WLT627TqC/uVRd0HKmq8NXyebnNYxDoBi7wt8eTWrUrKXCOVaFq9x1kgag==} - h3@1.15.11: resolution: {integrity: sha512-L3THSe2MPeBwgIZVSH5zLdBBU90TOxarvhK9d04IDY2AmVS8j2Jz2LIWtwsGOU3lu2I5jCN7FNvVfY2+XyF+mg==} @@ -4829,13 +4833,14 @@ packages: ieee754@1.2.1: resolution: {integrity: sha512-dcyqhDvX1C46lXZcVqCpK+FtMRQVdIMN6/Df5js2zouUsqG7I6sFxitIC+7KYK29KdXOLHdu9zL4sFnoVQnqaA==} - import-in-the-middle@2.0.6: - resolution: {integrity: sha512-3vZV3jX0XRFW3EJDTwzWoZa+RH1b8eTTx6YOCjglrLyPuepwoBti1k3L2dKwdCUrnVEfc5CuRuGstaC/uQJJaw==} - import-in-the-middle@3.3.3: resolution: {integrity: sha512-AiohS3H80sXO6owEltjGX+glb7qXaDhBoJb9XcQVH4UI207xu/bDLUcadVKp7Qe576reg9yr/PXZjV5qx8gfbA==} engines: {node: '>=18'} + import-in-the-middle@3.6.0: + resolution: {integrity: sha512-xRU7hI24S2FhucXtuZXn8EpcOjfVP6iiEQyR0USayPeaOroEmSsNlqnl95866iRdRtkHrd6Q/Z4D14R60au0+A==} + engines: {node: '>=18'} + import-meta-resolve@4.2.0: resolution: {integrity: sha512-Iqv2fzaTQN28s/FwZAoFq0ZSs/7hMAHJVX+w8PZl3cY19Pxk6jFFalxQoIfW2826i/fDLXv8IiEZRIT0lDuWcg==} @@ -4986,10 +4991,6 @@ packages: '@types/node': '>=18' typescript: '>=5.0.4 <7' - kysely@0.22.0: - resolution: {integrity: sha512-ZE3qWtnqLOalodzfK5QUEcm7AEulhxsPNuKaGFsC3XiqO92vMLm+mAHk/NnbSIOtC4RmGm0nsv700i8KDp1gfQ==} - engines: {node: '>=14.0.0'} - kysely@0.23.5: resolution: {integrity: sha512-TH+b56pVXQq0tsyooYLeNfV11j6ih7D50dyN8tkM0e7ndiUH28Nziojiog3qRFlmEj9XePYdZUrNJ2079Qjdow==} engines: {node: '>=14.0.0'} @@ -5362,10 +5363,6 @@ packages: engines: {node: '>=22.0.0'} hasBin: true - minimatch@10.2.6: - resolution: {integrity: sha512-vpLQEs+VLCr1nU0BXS07maYoFwlDAH0gngQuuttxIwutDFEMHq2blX+8vpgxDdK3J1PwjCJiep77OitTZ4Ll1A==} - engines: {node: 18 || 20 || >=22} - minimatch@9.0.9: resolution: {integrity: sha512-OBwBN9AL4dqmETlpS2zasx+vTeWclWzkblfZk7KTA5j3jeOONz/tRCnZomUyvNg83wL5Zv9Ss6HMJXAgL8R2Yg==} engines: {node: '>=16 || 14 >=14.17'} @@ -5468,10 +5465,6 @@ packages: resolution: {integrity: sha512-dRB78srN/l6gqWulah9SrxeYnxeddIG30+GOqK/9OlLVyLg3HPnr6SqOWTWOXKRwC2eGYCkZ59NNuSgvSrpgOA==} engines: {node: ^12.20.0 || ^14.13.1 || >=16.0.0} - node-gyp-build-optional-packages@5.1.1: - resolution: {integrity: sha512-+P72GAjVAbTxjjwUmwjVrqrdZROD4nf8KgpBoDxqXXTiYZZt/ud60dE5yvCSr9lRO8e8yv6kgJIC0K0PfZFVQw==} - hasBin: true - node-gyp-build@4.8.4: resolution: {integrity: sha512-LA4ZjwlnUblHVgq0oBF3Jl/6h/Nvs5fzBLwdEF4nuxnFdsfajde4WfxtJr3CaiH+F6ewcIB/q4jQ4UzPyid+CQ==} hasBin: true @@ -5542,11 +5535,6 @@ packages: oniguruma-to-es@4.3.6: resolution: {integrity: sha512-csuQ9x3Yr0cEIs/Zgx/OEt9iBw9vqIunAPQkx19R/fiMq2oGVTgcMqO/V3Ybqefr1TBvosI6jU539ksaBULJyA==} - opentelemetry-plugin-better-sqlite3@1.13.0: - resolution: {integrity: sha512-JHRGpq1KyTdlt50XmWCZ6P7nxEMGmn/EvdJKFPkZAnVtk9pQDnDwYobX/L/xeRkriihRKwHQ3UWoeIGUeolNtQ==} - peerDependencies: - better-sqlite3: ^7.1.1 || ^8.0.0 || ^9.0.0 || ^10.0.0 || ^11.0.0 || ^12.0.0 - oxc-resolver@11.17.0: resolution: {integrity: sha512-R5P2Tw6th+nQJdNcZGfuppBS/sM0x1EukqYffmlfX2xXLgLGCCPwu4ruEr9Sx29mrpkHgITc130Qps2JR90NdQ==} @@ -5629,9 +5617,6 @@ packages: resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==} engines: {node: '>= 0.8'} - path-browserify@1.0.1: - resolution: {integrity: sha512-b7uo2UCUOYZcnF/3ID0lulOJi/bafxa1xPe7ZPsammBSpjSWQkjNxlt635YGS2MiR9GjvuXCtz2emr3jbsz98g==} - path-exists@4.0.0: resolution: {integrity: sha512-ak9Qy5Q7jYb2Wwcey5Fpvg2KoAc/ZIhLSLOSBmRmygPsGwkVVt0fZa0qrtMz+m6tJTAHfZQ8FnmB4MG4LWy7/w==} engines: {node: '>=8'} @@ -5784,11 +5769,6 @@ packages: engines: {node: '>=14'} hasBin: true - prettier@3.9.6: - resolution: {integrity: sha512-OpN0zzVdiaiAhxpuuj5efpIS4sY9j7bY6uR5mnj5yPzGkdkjNKSJeUThPb60Jw29QuAZgA4o+/iB49kFiaBX6g==} - engines: {node: '>=14'} - hasBin: true - prismjs@1.30.0: resolution: {integrity: sha512-DEvV2ZF2r2/63V+tK8hQvrR2ZGn10srHbXviTlcv7Kpzw8jWiNTqbVgjO3IY8RxrrOUF8VPMQQFysYYYv0YZxw==} engines: {node: '>=6'} @@ -5847,6 +5827,10 @@ packages: resolution: {integrity: sha512-O9gl3zCl5h5blw1KGUzQKhA5oUXSl8rwUIM5o0S3nCXMliSvy5Dzx7/DJcI+SwgICv+IneSZwhBh1oSyEHA71A==} engines: {node: '>=0.6'} + qs@6.16.2: + resolution: {integrity: sha512-VYdnB5S7/0IeXzBacUtwNAaM6d7Y/PgYnNC7bJCI6meqA/OgnsQbZMtVW8Dt2D1PHgbHGtYmhSoEIgvt7xZ2ZA==} + engines: {node: '>=0.6'} + quansync@1.0.0: resolution: {integrity: sha512-5xZacEEufv3HSTPQuchrvV6soaiACMFnq1H8wkVioctoH3TRha9Sz66lOxRwPK/qZj7HPiSveih9yAyh98gvqA==} @@ -6077,9 +6061,6 @@ packages: resolution: {integrity: sha512-euNvEYki6iYYpkNbeudW+lEMMYGEmN7EBwVF8ezlbv0bZoQpVYB7W10cCeUIGV7Ed50sJynLQ0c559q5iI0ejQ==} engines: {node: '>=10'} - rxjs@7.8.2: - resolution: {integrity: sha512-dhKf903U/PQZY6boNNtAGdWbG85WAbjT/1xYoZIC7FAY0yWapOBQVsVrDl58W86//e1VpMNBtRV4MaXfdMySFA==} - sade@1.8.1: resolution: {integrity: sha512-xal3CZX1Xlo/k4ApwCFrHVACi9fBqJ7V+mwhBsuf/1IOKbBy098Fex+Wa/5QMubw09pSZ/u8EY8PWgevJsXp1A==} engines: {node: '>=6'} @@ -6271,14 +6252,6 @@ packages: resolution: {integrity: sha512-HnLOCR3vjcY8beoNLtcjZ5/nxn2afmME6lhrDrebokqMap+XbeW8n9TXpPDOqdGK5qcI3oT0GKTW6wC7EMiVqA==} engines: {node: '>=12'} - string-width@7.2.0: - resolution: {integrity: sha512-tsaTIkKW9b4N+AEj+SVA+WhJzV7/zMhcSu78mLKWSk7cXMOSHsBKFWUs0fWwq8QyK3MgJBQRX6Gbi4kYbdvGkQ==} - engines: {node: '>=18'} - - string-width@8.2.2: - resolution: {integrity: sha512-GaPUh5gfdrYzqeVNZvUfT23vYYxXzKYidUcnMtJg/3rxRV63EFZy3k6xfKlmfeJD0176lnUV/Usr3XcwSvFzpg==} - engines: {node: '>=20'} - string_decoder@1.3.0: resolution: {integrity: sha512-hkRX8U1WjJFd8LsDJ2yQ/wWWxaopEsABU1XfkM8A+j0+85JAGppt16cr1Whg6KIbb4okU6Mql6BOj+uup/wKeA==} @@ -6436,9 +6409,6 @@ packages: trough@2.2.0: resolution: {integrity: sha512-tmMpK00BjZiUyVyvrBK7knerNgmgvcV/KLVyuma/SC+TQN167GrMRciANTz09+k3zW8L8t60jWO1GpfkZdjTaw==} - ts-morph@27.0.2: - resolution: {integrity: sha512-fhUhgeljcrdZ+9DZND1De1029PrE+cMkIP7ooqkLRTrRLTqcki2AstsyJm0vRNbTbVCNJ0idGlbBrfqc7/nA8w==} - tsdown@0.18.4: resolution: {integrity: sha512-J/tRS6hsZTkvqmt4+xdELUCkQYDuUCXgBv0fw3ImV09WPGbEKfsPD65E+WUjSu3E7Z6tji9XZ1iWs8rbGqB/ZA==} engines: {node: '>=20.19.0'} @@ -6490,9 +6460,6 @@ packages: resolution: {integrity: sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==} engines: {node: '>= 0.6'} - typed-emitter@2.1.0: - resolution: {integrity: sha512-g/KzbYKbH5C2vPkaXGu8DJlHrGKHLsM25Zg9WuC9pMGfuvT+X25tZQWo5fK1BjBm8+UrVE9LDCvaY0CQk+fXDA==} - typescript@5.6.1-rc: resolution: {integrity: sha512-E3b2+1zEFu84jB0YQi9BORDjz9+jGbwwy1Zi3G0LUNw7a7cePUrHMRNy8aPh53nXpkFGVHSxIZo5vKTfYaFiBQ==} engines: {node: '>=14.17'} @@ -6508,6 +6475,11 @@ packages: engines: {node: '>=14.17'} hasBin: true + typescript@7.0.2: + resolution: {integrity: sha512-8FYau96o3NKOhbjKi/qNvG/W5jhzxkbdm5sj9AbZ/5T5sWqn3hJgLfGx27sRKZWTvyzCP8dLRBTf5tBTSRVUNA==} + engines: {node: '>=16.20.0'} + hasBin: true + ufo@1.6.4: resolution: {integrity: sha512-JFNbkD1Svwe0KvGi8GOeLcP4kAWQ609twvCdcHxq1oSL8svv39ZuSvajcD8B+5D0eL4+s1Is2D/O6KN3qcTeRA==} @@ -6542,8 +6514,8 @@ packages: resolution: {integrity: sha512-raqeBD6NQK4SkWhQzeYKd1KmIG6dllBOTt55Rmkt4HtI9mwdWtJljnrXjAFUBLTSN67HWrOIZ3EPF4kjUw80Bg==} engines: {node: '>=14.0'} - undici@6.28.0: - resolution: {integrity: sha512-LIY910g9TI13YS95lrMFrs8Rm/u/irgHeTWoKCoteeJ04CUJ92eEfj0rVn+7VKMPBpUPiUoBKfhNyLI23EE/KA==} + undici@6.29.1: + resolution: {integrity: sha512-EvRlUt/QqAEvXdQeRMYUfwOQsfzpDztykrG2owGEE/rBOBoYv9uF39ZzsNDh4lTFHhTr2XOZjKkYgueD12ZmGA==} engines: {node: '>=18.17'} undici@7.18.2: @@ -6554,8 +6526,12 @@ packages: resolution: {integrity: sha512-6KQ/+QxK49Z/p3HO6E5ZCZWNnCasyZLa5ExaVYyvPxUwKtbCPMKELJOqh7EqOle0t9cH/7d2TaaTRRa6Nhs4YQ==} engines: {node: '>=20.18.1'} - undici@8.10.0: - resolution: {integrity: sha512-HvltHd7avK13QIw/oLe4qoOLyoVSoafqJ2jYOrtMRBkbYT31eiBQ8O0ehRKZiEZCMEyLFQNIADpgCWC5fALvYQ==} + undici@7.30.2: + resolution: {integrity: sha512-mLyPQnHwUxaM/rideoK/+KL8DaAJLRl4aBCfmX444aCSLnIaomqPLtNRe2jdCYcsk5wZzXrDIQC8ZeYNRAYyIA==} + engines: {node: '>=20.18.1'} + + undici@8.12.4: + resolution: {integrity: sha512-8Mx+uNKKER2bA4AdtedkqRbwUCIJFr2nJckXRe5yrDqzePqwLP7VNcctN8/XdmDSbF7mS+jJKIszlL+vbam1VA==} engines: {node: '>=22.19.0'} unenv@2.0.0-rc.24: @@ -6962,10 +6938,6 @@ packages: resolution: {integrity: sha512-si7QWI6zUMq56bESFvagtmzMdGOtoxfR+Sez11Mobfc7tm+VkUckk9bW2UeffTGVUbOksxmSw0AA2gs8g71NCQ==} engines: {node: '>=12'} - wrap-ansi@9.0.2: - resolution: {integrity: sha512-42AtmgqjV+X1VpdOfyTGOYRi0/zsoLqtXQckTmqTeybT+BDIbM/Guxo7x3pE2vtpr1ok6xRqM9OpBe+Jyoqyww==} - engines: {node: '>=18'} - wrappy@1.0.2: resolution: {integrity: sha512-l4Sp/DRseor9wL6EvV2+TuQn63dMkPjZ/sp9XkghTEbV9KlPS1xUsZ3u7/IQO4wxtcFB4bgpQPRcR3QCvezPcQ==} @@ -7055,10 +7027,6 @@ packages: resolution: {integrity: sha512-GZtjxm/J/4TSxuL3FNYjCmLktBTnIw/rVmKSIyKeYAZpmJB2ig9VauCC5xsa82GNKVKDAqpOn3KVzNt0zmrU0g==} engines: {node: '>=12'} - yargs@18.1.0: - resolution: {integrity: sha512-2rAgRKu54VsHkqI0/tYkmluGXHD4KW7yZoycuqDQ15QOTnc2VVfy0nN/1eMhnQLO00A+dwtK20xuCnc1YGeUyg==} - engines: {node: ^20.19.0 || ^22.12.0 || >=23} - yocto-queue@1.2.2: resolution: {integrity: sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ==} engines: {node: '>=12.20'} @@ -7069,9 +7037,6 @@ packages: youch@4.1.0-beta.10: resolution: {integrity: sha512-rLfVLB4FgQneDr0dv1oddCVZmKjcJ6yX6mS4pU82Mq/Dt9a3cLZQ62pDBL4AUO+uVrCvtWz3ZFUL2HFAFJ/BXQ==} - zod@3.21.4: - resolution: {integrity: sha512-m46AKbrzKVzOzs/DZgVnG5H55N1sv1M8qZU3A8RIKbs3mrACDNeIOeilDymVb2HdmP8uwshOCF4uJ8uM9rCqJw==} - zod@3.23.8: resolution: {integrity: sha512-XBx9AXhXktjUqnepgTiE5flcKIYWi/rme0Eaj+5Y0lftuGBq+jyRu/md4WnuxqgP1ubdpNCsYEYPxrzVHD8d6g==} @@ -7449,65 +7414,66 @@ snapshots: '@atcute/varint@2.0.2': {} - '@atproto-labs/did-resolver@0.0.0-spaces-alpha-20261105160032': + '@atproto-labs/did-resolver@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto-labs/fetch': 0.3.5 - '@atproto-labs/pipe': 0.2.4 + '@atproto-labs/fetch': 0.4.2 + '@atproto-labs/pipe': 0.2.5 '@atproto-labs/simple-store': 0.5.1 '@atproto-labs/simple-store-memory': 0.2.6 - '@atproto/did': 0.0.0-spaces-alpha-20261105160032 + '@atproto/did': 0.0.0-spaces-alpha-20261112204144 zod: 3.25.76 - '@atproto-labs/fetch-node@0.0.0-spaces-alpha-20261105160032': + '@atproto-labs/fetch-node@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto-labs/fetch': 0.3.5 - '@atproto-labs/pipe': 0.2.4 + '@atproto-labs/fetch': 0.4.2 + '@atproto-labs/pipe': 0.2.5 ipaddr.js: 2.5.0 - undici_v6: undici@6.28.0 - undici_v7: undici@7.24.8 - undici_v8: undici@8.10.0 + undici_v6: undici@6.29.1 + undici_v7: undici@7.30.2 + undici_v8: undici@8.12.4 - '@atproto-labs/fetch@0.3.5': + '@atproto-labs/fetch@0.4.2': dependencies: - '@atproto-labs/pipe': 0.2.4 + '@atproto-labs/pipe': 0.2.5 - '@atproto-labs/handle-resolver-node@0.0.0-spaces-alpha-20261105160032': + '@atproto-labs/handle-resolver-node@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto-labs/fetch-node': 0.0.0-spaces-alpha-20261105160032 - '@atproto-labs/handle-resolver': 0.0.0-spaces-alpha-20261105160032 - '@atproto/did': 0.0.0-spaces-alpha-20261105160032 + '@atproto-labs/fetch-node': 0.0.0-spaces-alpha-20261112204144 + '@atproto-labs/handle-resolver': 0.0.0-spaces-alpha-20261112204144 + '@atproto/did': 0.0.0-spaces-alpha-20261112204144 - '@atproto-labs/handle-resolver@0.0.0-spaces-alpha-20261105160032': + '@atproto-labs/handle-resolver@0.0.0-spaces-alpha-20261112204144': dependencies: '@atproto-labs/simple-store': 0.5.1 '@atproto-labs/simple-store-memory': 0.2.6 - '@atproto/did': 0.0.0-spaces-alpha-20261105160032 + '@atproto/did': 0.0.0-spaces-alpha-20261112204144 zod: 3.25.76 - '@atproto-labs/identity-resolver@0.0.0-spaces-alpha-20261105160032': - dependencies: - '@atproto-labs/did-resolver': 0.0.0-spaces-alpha-20261105160032 - '@atproto-labs/handle-resolver': 0.0.0-spaces-alpha-20261105160032 - - '@atproto-labs/opentelemetry-node@0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/auto-instrumentations-node': 0.77.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.10.0(@opentelemetry/api@1.9.1))(supports-color@10.2.2) - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-express': 0.67.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-http': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-pino': 0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-runtime-node': 0.32.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-undici': 0.29.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/resource-detector-container': 0.8.12(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-node': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@atproto-labs/identity-resolver@0.0.0-spaces-alpha-20261112204144': + dependencies: + '@atproto-labs/did-resolver': 0.0.0-spaces-alpha-20261112204144 + '@atproto-labs/handle-resolver': 0.0.0-spaces-alpha-20261112204144 + + '@atproto-labs/opentelemetry-node@0.5.0(supports-color@10.2.2)': + dependencies: + '@opentelemetry/api': 1.10.0 + '@opentelemetry/auto-instrumentations-node': 0.82.0(@opentelemetry/api@1.10.0)(@opentelemetry/core@3.1.1(@opentelemetry/api@1.10.0))(supports-color@10.2.2) + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-express': 0.72.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-http': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-pino': 0.70.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-runtime-node': 0.37.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-undici': 0.34.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/resource-detector-container': 0.9.1(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-node': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 - import-in-the-middle: 3.3.3 + import-in-the-middle: 3.6.0 transitivePeerDependencies: - supports-color - '@atproto-labs/pipe@0.2.4': {} + '@atproto-labs/pipe@0.2.5': {} '@atproto-labs/simple-store-memory@0.2.6': dependencies: @@ -7521,21 +7487,21 @@ snapshots: '@atproto-labs/simple-store@0.5.1': {} - '@atproto-labs/xrpc-utils@0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2)': + '@atproto-labs/xrpc-utils@0.0.0-spaces-alpha-20261112204144(supports-color@10.2.2)': dependencies: - '@atproto/xrpc': 0.0.0-spaces-alpha-20261105160032 - '@atproto/xrpc-server': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) + '@atproto/xrpc': 0.0.0-spaces-alpha-20261112204144 + '@atproto/xrpc-server': 0.0.0-spaces-alpha-20261112204144(supports-color@10.2.2) transitivePeerDependencies: - bufferutil - supports-color - utf-8-validate - '@atproto/api@0.0.0-spaces-alpha-20261105160032': + '@atproto/api@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/common-web': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lexicon': 0.0.0-spaces-alpha-20261105160032 - '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 - '@atproto/xrpc': 0.0.0-spaces-alpha-20261105160032 + '@atproto/common-web': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lexicon': 0.0.0-spaces-alpha-20261112204144 + '@atproto/syntax': 0.0.0-spaces-alpha-20261112204144 + '@atproto/xrpc': 0.0.0-spaces-alpha-20261112204144 await-lock: 3.0.0 multiformats: 13.4.2 tlds: 1.261.0 @@ -7552,12 +7518,11 @@ snapshots: tlds: 1.261.0 zod: 3.25.76 - '@atproto/aws@0.0.0-spaces-alpha-20261105160032': + '@atproto/aws@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/common': 0.0.0-spaces-alpha-20261105160032 - '@atproto/common-web': 0.0.0-spaces-alpha-20261105160032 - '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 - '@atproto/repo': 0.0.0-spaces-alpha-20261105160032 + '@atproto/common': 0.0.0-spaces-alpha-20261112204144 + '@atproto/crypto': 0.0.0-spaces-alpha-20261112204144 + '@atproto/repo': 0.0.0-spaces-alpha-20261112204144 '@aws-sdk/client-cloudfront': 3.1121.0 '@aws-sdk/client-kms': 3.1121.0 '@aws-sdk/client-s3': 3.1121.0 @@ -7566,21 +7531,24 @@ snapshots: multiformats: 13.4.2 uint8arrays: 5.1.1 - '@atproto/bsky@0.0.0-spaces-alpha-20261105160032(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2)': - dependencies: - '@atproto-labs/fetch-node': 0.0.0-spaces-alpha-20261105160032 - '@atproto-labs/opentelemetry-node': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) - '@atproto-labs/xrpc-utils': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) - '@atproto/api': 0.0.0-spaces-alpha-20261105160032 - '@atproto/common': 0.0.0-spaces-alpha-20261105160032 - '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 - '@atproto/did': 0.0.0-spaces-alpha-20261105160032 - '@atproto/identity': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex': 0.0.0-spaces-alpha-20261105160032 - '@atproto/repo': 0.0.0-spaces-alpha-20261105160032 - '@atproto/sync': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) - '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 - '@atproto/xrpc-server': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) + '@atproto/bsky@0.0.0-spaces-alpha-20261112204144(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2)': + dependencies: + '@atproto-labs/fetch-node': 0.0.0-spaces-alpha-20261112204144 + '@atproto-labs/opentelemetry-node': 0.5.0(supports-color@10.2.2) + '@atproto-labs/xrpc-utils': 0.0.0-spaces-alpha-20261112204144(supports-color@10.2.2) + '@atproto/api': 0.0.0-spaces-alpha-20261112204144 + '@atproto/common': 0.0.0-spaces-alpha-20261112204144 + '@atproto/crypto': 0.0.0-spaces-alpha-20261112204144 + '@atproto/did': 0.0.0-spaces-alpha-20261112204144 + '@atproto/identity': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-client': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-json': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261112204144 + '@atproto/repo': 0.0.0-spaces-alpha-20261112204144 + '@atproto/sync': 0.0.0-spaces-alpha-20261112204144(supports-color@10.2.2) + '@atproto/syntax': 0.0.0-spaces-alpha-20261112204144 + '@atproto/xrpc-server': 0.0.0-spaces-alpha-20261112204144(supports-color@10.2.2) '@bufbuild/protobuf': 1.10.1 '@connectrpc/connect': 1.7.0(@bufbuild/protobuf@1.10.1) '@connectrpc/connect-express': 1.7.0(@bufbuild/protobuf@1.10.1)(@connectrpc/connect-node@1.7.0(@bufbuild/protobuf@1.10.1)(@connectrpc/connect@1.7.0(@bufbuild/protobuf@1.10.1)))(@connectrpc/connect@1.7.0(@bufbuild/protobuf@1.10.1)) @@ -7589,8 +7557,7 @@ snapshots: '@growthbook/growthbook': 1.7.0 '@hapi/address': 5.1.1 '@noble/curves': 1.9.7 - '@opentelemetry/api': 1.9.1 - '@opentelemetry/api-logs': 0.219.0 + '@opentelemetry/api': 1.10.0 '@opentelemetry/semantic-conventions': 1.43.0 '@types/http-errors': 2.0.5 compression: 1.8.1(supports-color@10.2.2) @@ -7611,11 +7578,12 @@ snapshots: pino-http: 11.0.0 sharp: 0.33.5 structured-headers: 1.0.1 + typescript: 7.0.2 uint8arrays: 5.1.1 - undici: 8.10.0 - undici_v6: undici@6.28.0 - undici_v7: undici@7.24.8 - undici_v8: undici@8.10.0 + undici: 8.12.4 + undici_v6: undici@6.29.1 + undici_v7: undici@7.30.2 + undici_v8: undici@8.12.4 zod: 3.23.8 transitivePeerDependencies: - bufferutil @@ -7624,42 +7592,36 @@ snapshots: - supports-color - utf-8-validate - '@atproto/bsync@0.0.0': + '@atproto/bsync@0.0.0-spaces-alpha-20261112204144(supports-color@10.2.2)': dependencies: - '@atproto/common': 0.3.4 - '@atproto/syntax': 0.1.5 + '@atproto-labs/opentelemetry-node': 0.5.0(supports-color@10.2.2) + '@atproto/common': 0.0.0-spaces-alpha-20261112204144 + '@atproto/syntax': 0.0.0-spaces-alpha-20261112204144 '@bufbuild/protobuf': 1.10.1 '@connectrpc/connect': 1.7.0(@bufbuild/protobuf@1.10.1) - '@connectrpc/connect-express': 1.7.0(@bufbuild/protobuf@1.10.1)(@connectrpc/connect-node@1.7.0(@bufbuild/protobuf@1.10.1)(@connectrpc/connect@1.7.0(@bufbuild/protobuf@1.10.1)))(@connectrpc/connect@1.7.0(@bufbuild/protobuf@1.10.1)) '@connectrpc/connect-node': 1.7.0(@bufbuild/protobuf@1.10.1)(@connectrpc/connect@1.7.0(@bufbuild/protobuf@1.10.1)) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/semantic-conventions': 1.43.0 http-terminator: 3.2.0 - kysely: 0.22.0 + kysely: 0.29.5 pg: 8.23.0 - pino: 8.21.0 - pino-http: 8.6.1 - typed-emitter: 2.1.0 + pino-http: 11.0.0 transitivePeerDependencies: - pg-native + - supports-color - '@atproto/car@0.0.0-spaces-alpha-20261105160032': + '@atproto/car@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261112204144 tslib: 2.8.1 varint: 6.0.0 - '@atproto/common-web@0.0.0-spaces-alpha-20261105160032': - dependencies: - '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-json': 0.0.0-spaces-alpha-20261105160032 - '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 - zod: 3.25.76 - - '@atproto/common-web@0.2.4': + '@atproto/common-web@0.0.0-spaces-alpha-20261112204144': dependencies: - graphemer: 1.4.0 - multiformats: 9.9.0 - uint8arrays: 3.0.0 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-json': 0.0.0-spaces-alpha-20261112204144 + '@atproto/syntax': 0.0.0-spaces-alpha-20261112204144 zod: 3.25.76 '@atproto/common-web@0.4.16': @@ -7669,11 +7631,11 @@ snapshots: '@atproto/syntax': 0.4.3 zod: 3.25.76 - '@atproto/common@0.0.0-spaces-alpha-20261105160032': + '@atproto/common@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/common-web': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 + '@atproto/common-web': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261112204144 multiformats: 13.4.2 pino: 10.3.1 @@ -7691,16 +7653,6 @@ snapshots: pino: 8.21.0 zod: 3.25.76 - '@atproto/common@0.3.4': - dependencies: - '@atproto/common-web': 0.2.4 - '@ipld/dag-cbor': 7.0.3 - cbor-x: 1.6.6 - iso-datestring-validator: 2.2.2 - multiformats: 9.9.0 - pino: 8.21.0 - zod: 3.21.4 - '@atproto/common@0.5.11': dependencies: '@atproto/common-web': 0.4.16 @@ -7710,7 +7662,7 @@ snapshots: multiformats: 9.9.0 pino: 8.21.0 - '@atproto/crypto@0.0.0-spaces-alpha-20261105160032': + '@atproto/crypto@0.0.0-spaces-alpha-20261112204144': dependencies: '@noble/curves': 1.9.7 '@noble/hashes': 1.8.0 @@ -7730,30 +7682,30 @@ snapshots: '@noble/hashes': 1.8.0 uint8arrays: 3.0.0 - '@atproto/dev-env@0.0.0-spaces-alpha-20261105160032(@opentelemetry/api@1.9.1)(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2)': - dependencies: - '@atproto/api': 0.0.0-spaces-alpha-20261105160032 - '@atproto/bsky': 0.0.0-spaces-alpha-20261105160032(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) - '@atproto/bsync': 0.0.0 - '@atproto/common-web': 0.0.0-spaces-alpha-20261105160032 - '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 - '@atproto/identity': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lexicon': 0.0.0-spaces-alpha-20261105160032 - '@atproto/ozone': 0.0.0-spaces-alpha-20261105160032(@opentelemetry/api@1.9.1)(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) - '@atproto/pds': 0.0.0-spaces-alpha-20261105160032(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) - '@atproto/sync': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) - '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 - '@atproto/xrpc-server': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) + '@atproto/dev-env@0.0.0-spaces-alpha-20261112204144(@opentelemetry/api@1.10.0)(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2)': + dependencies: + '@atproto/api': 0.0.0-spaces-alpha-20261112204144 + '@atproto/bsky': 0.0.0-spaces-alpha-20261112204144(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) + '@atproto/bsync': 0.0.0-spaces-alpha-20261112204144(supports-color@10.2.2) + '@atproto/common-web': 0.0.0-spaces-alpha-20261112204144 + '@atproto/crypto': 0.0.0-spaces-alpha-20261112204144 + '@atproto/identity': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-client': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lexicon': 0.0.0-spaces-alpha-20261112204144 + '@atproto/ozone': 0.0.0-spaces-alpha-20261112204144(@opentelemetry/api@1.10.0)(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) + '@atproto/pds': 0.0.0-spaces-alpha-20261112204144(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) + '@atproto/sync': 0.0.0-spaces-alpha-20261112204144(supports-color@10.2.2) + '@atproto/syntax': 0.0.0-spaces-alpha-20261112204144 + '@atproto/xrpc-server': 0.0.0-spaces-alpha-20261112204144(supports-color@10.2.2) '@did-plc/lib': 0.0.1(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) '@did-plc/server': 0.0.1(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) - dotenv: 17.4.2 express: 4.22.2(supports-color@10.2.2) get-port: 5.1.1 http-terminator: 3.2.0 multiformats: 13.4.2 uint8arrays: 5.1.1 - undici: 8.10.0 + undici: 8.12.4 transitivePeerDependencies: - '@opentelemetry/api' - bufferutil @@ -7762,7 +7714,7 @@ snapshots: - supports-color - utf-8-validate - '@atproto/did@0.0.0-spaces-alpha-20261105160032': + '@atproto/did@0.0.0-spaces-alpha-20261112204144': dependencies: zod: 3.25.76 @@ -7770,20 +7722,31 @@ snapshots: dependencies: zod: 3.25.76 - '@atproto/identity@0.0.0-spaces-alpha-20261105160032': + '@atproto/identity@0.0.0-spaces-alpha-20261112204144': + dependencies: + '@atproto-labs/fetch-node': 0.0.0-spaces-alpha-20261112204144 + '@atproto/common-web': 0.0.0-spaces-alpha-20261112204144 + '@atproto/crypto': 0.0.0-spaces-alpha-20261112204144 + + '@atproto/jwk-jose@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/common-web': 0.0.0-spaces-alpha-20261105160032 - '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 + '@atproto/jwk': 0.0.0-spaces-alpha-20261112204144 + jose: 5.10.0 '@atproto/jwk-jose@0.2.4': dependencies: '@atproto/jwk': 0.7.4 jose: 5.10.0 - '@atproto/jwk-webcrypto@0.3.4': + '@atproto/jwk-webcrypto@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/jwk': 0.7.4 - '@atproto/jwk-jose': 0.2.4 + '@atproto/jwk': 0.0.0-spaces-alpha-20261112204144 + '@atproto/jwk-jose': 0.0.0-spaces-alpha-20261112204144 + zod: 3.25.76 + + '@atproto/jwk@0.0.0-spaces-alpha-20261112204144': + dependencies: + multiformats: 13.4.2 zod: 3.25.76 '@atproto/jwk@0.6.0': @@ -7796,17 +7759,9 @@ snapshots: multiformats: 13.4.2 zod: 3.25.76 - '@atproto/lex-builder@0.0.0-spaces-alpha-20261105160032': - dependencies: - '@atproto/lex-document': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-schema': 0.0.0-spaces-alpha-20261105160032 - prettier: 3.9.6 - ts-morph: 27.0.2 - tslib: 2.8.1 - - '@atproto/lex-cbor@0.0.0-spaces-alpha-20261105160032': + '@atproto/lex-cbor@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261112204144 cborg: 4.5.8 tslib: 2.8.1 @@ -7821,14 +7776,14 @@ snapshots: multiformats: 9.9.0 tslib: 2.8.1 - '@atproto/lex-client@0.0.0-spaces-alpha-20261105160032': + '@atproto/lex-client@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-json': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-schema': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-rpc': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261112204144 tslib: 2.8.1 - '@atproto/lex-data@0.0.0-spaces-alpha-20261105160032': + '@atproto/lex-data@0.0.0-spaces-alpha-20261112204144': dependencies: multiformats: 13.4.2 tslib: 2.8.1 @@ -7849,26 +7804,15 @@ snapshots: uint8arrays: 3.0.0 unicode-segmenter: 0.14.5 - '@atproto/lex-document@0.0.0-spaces-alpha-20261105160032': + '@atproto/lex-document@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/lex-schema': 0.0.0-spaces-alpha-20261105160032 - core-js: 3.51.0 - tslib: 2.8.1 - - '@atproto/lex-installer@0.0.0-spaces-alpha-20261105160032': - dependencies: - '@atproto/lex-builder': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-document': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-resolver': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-schema': 0.0.0-spaces-alpha-20261105160032 - '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261112204144 tslib: 2.8.1 - '@atproto/lex-json@0.0.0-spaces-alpha-20261105160032': + '@atproto/lex-json@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261112204144 tslib: 2.8.1 '@atproto/lex-json@0.0.11': @@ -7876,46 +7820,42 @@ snapshots: '@atproto/lex-data': 0.0.11 tslib: 2.8.1 - '@atproto/lex-password-session@0.0.0': + '@atproto/lex-password-session@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/lex-client': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-schema': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-rpc': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261112204144 tslib: 2.8.1 - '@atproto/lex-resolver@0.0.0-spaces-alpha-20261105160032': + '@atproto/lex-resolver@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto-labs/did-resolver': 0.0.0-spaces-alpha-20261105160032 - '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-client': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-document': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-schema': 0.0.0-spaces-alpha-20261105160032 - '@atproto/repo': 0.0.0-spaces-alpha-20261105160032 - '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 + '@atproto-labs/did-resolver': 0.0.0-spaces-alpha-20261112204144 + '@atproto/crypto': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-document': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-rpc': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261112204144 + '@atproto/repo': 0.0.0-spaces-alpha-20261112204144 + '@atproto/syntax': 0.0.0-spaces-alpha-20261112204144 tslib: 2.8.1 - '@atproto/lex-schema@0.0.0-spaces-alpha-20261105160032': + '@atproto/lex-rpc@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 - '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 - '@standard-schema/spec': 1.1.0 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-json': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261112204144 tslib: 2.8.1 - '@atproto/lex@0.0.0-spaces-alpha-20261105160032': + '@atproto/lex-schema@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/lex-builder': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-client': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-installer': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-json': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-schema': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261112204144 + '@atproto/syntax': 0.0.0-spaces-alpha-20261112204144 + '@standard-schema/spec': 1.1.0 tslib: 2.8.1 - yargs: 18.1.0 - '@atproto/lexicon@0.0.0-spaces-alpha-20261105160032': + '@atproto/lexicon@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/common-web': 0.0.0-spaces-alpha-20261105160032 - '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 + '@atproto/common-web': 0.0.0-spaces-alpha-20261112204144 + '@atproto/syntax': 0.0.0-spaces-alpha-20261112204144 multiformats: 13.4.2 zod: 3.25.76 @@ -7927,63 +7867,65 @@ snapshots: multiformats: 9.9.0 zod: 3.25.76 - '@atproto/oauth-client-node@0.0.0-spaces-alpha-20261105160032': + '@atproto/oauth-client-node@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto-labs/did-resolver': 0.0.0-spaces-alpha-20261105160032 - '@atproto-labs/handle-resolver-node': 0.0.0-spaces-alpha-20261105160032 + '@atproto-labs/did-resolver': 0.0.0-spaces-alpha-20261112204144 + '@atproto-labs/handle-resolver-node': 0.0.0-spaces-alpha-20261112204144 '@atproto-labs/simple-store': 0.5.1 - '@atproto/did': 0.0.0-spaces-alpha-20261105160032 - '@atproto/jwk': 0.7.4 - '@atproto/jwk-jose': 0.2.4 - '@atproto/jwk-webcrypto': 0.3.4 - '@atproto/oauth-client': 0.0.0-spaces-alpha-20261105160032 - '@atproto/oauth-types': 0.0.0-spaces-alpha-20261105160032 - - '@atproto/oauth-client@0.0.0-spaces-alpha-20261105160032': - dependencies: - '@atproto-labs/did-resolver': 0.0.0-spaces-alpha-20261105160032 - '@atproto-labs/fetch': 0.3.5 - '@atproto-labs/handle-resolver': 0.0.0-spaces-alpha-20261105160032 - '@atproto-labs/identity-resolver': 0.0.0-spaces-alpha-20261105160032 + '@atproto/did': 0.0.0-spaces-alpha-20261112204144 + '@atproto/jwk': 0.0.0-spaces-alpha-20261112204144 + '@atproto/jwk-jose': 0.0.0-spaces-alpha-20261112204144 + '@atproto/jwk-webcrypto': 0.0.0-spaces-alpha-20261112204144 + '@atproto/oauth-client': 0.0.0-spaces-alpha-20261112204144 + '@atproto/oauth-types': 0.0.0-spaces-alpha-20261112204144 + + '@atproto/oauth-client@0.0.0-spaces-alpha-20261112204144': + dependencies: + '@atproto-labs/did-resolver': 0.0.0-spaces-alpha-20261112204144 + '@atproto-labs/fetch': 0.4.2 + '@atproto-labs/handle-resolver': 0.0.0-spaces-alpha-20261112204144 + '@atproto-labs/identity-resolver': 0.0.0-spaces-alpha-20261112204144 '@atproto-labs/simple-store': 0.5.1 '@atproto-labs/simple-store-memory': 0.2.6 - '@atproto/did': 0.0.0-spaces-alpha-20261105160032 - '@atproto/jwk': 0.7.4 - '@atproto/oauth-types': 0.0.0-spaces-alpha-20261105160032 - '@atproto/xrpc': 0.0.0-spaces-alpha-20261105160032 + '@atproto/did': 0.0.0-spaces-alpha-20261112204144 + '@atproto/jwk': 0.0.0-spaces-alpha-20261112204144 + '@atproto/oauth-resolver': 0.0.0-spaces-alpha-20261112204144 + '@atproto/oauth-types': 0.0.0-spaces-alpha-20261112204144 + '@atproto/xrpc': 0.0.0-spaces-alpha-20261112204144 core-js: 3.51.0 multiformats: 13.4.2 zod: 3.25.76 - '@atproto/oauth-provider-api@0.0.0-spaces-alpha-20261105160032': + '@atproto/oauth-provider-api@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/jwk': 0.7.4 - '@atproto/oauth-types': 0.0.0-spaces-alpha-20261105160032 - '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 + '@atproto/jwk': 0.0.0-spaces-alpha-20261112204144 + '@atproto/oauth-types': 0.0.0-spaces-alpha-20261112204144 + '@atproto/syntax': 0.0.0-spaces-alpha-20261112204144 - '@atproto/oauth-provider-ui@0.0.0-spaces-alpha-20261105160032': + '@atproto/oauth-provider-ui@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/oauth-provider-api': 0.0.0-spaces-alpha-20261105160032 + '@atproto/oauth-provider-api': 0.0.0-spaces-alpha-20261112204144 - '@atproto/oauth-provider@0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2)': + '@atproto/oauth-provider@0.0.0-spaces-alpha-20261112204144(supports-color@10.2.2)': dependencies: - '@atproto-labs/did-resolver': 0.0.0-spaces-alpha-20261105160032 - '@atproto-labs/fetch-node': 0.0.0-spaces-alpha-20261105160032 - '@atproto-labs/handle-resolver-node': 0.0.0-spaces-alpha-20261105160032 - '@atproto-labs/pipe': 0.2.4 + '@atproto-labs/did-resolver': 0.0.0-spaces-alpha-20261112204144 + '@atproto-labs/fetch-node': 0.0.0-spaces-alpha-20261112204144 + '@atproto-labs/handle-resolver-node': 0.0.0-spaces-alpha-20261112204144 + '@atproto-labs/pipe': 0.2.5 '@atproto-labs/simple-store': 0.5.1 '@atproto-labs/simple-store-memory': 0.2.6 - '@atproto/common': 0.0.0-spaces-alpha-20261105160032 - '@atproto/did': 0.0.0-spaces-alpha-20261105160032 - '@atproto/jwk': 0.7.4 - '@atproto/jwk-jose': 0.2.4 - '@atproto/lex-document': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-resolver': 0.0.0-spaces-alpha-20261105160032 - '@atproto/oauth-provider-api': 0.0.0-spaces-alpha-20261105160032 - '@atproto/oauth-provider-ui': 0.0.0-spaces-alpha-20261105160032 - '@atproto/oauth-scopes': 0.0.0-spaces-alpha-20261105160032 - '@atproto/oauth-types': 0.0.0-spaces-alpha-20261105160032 - '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 + '@atproto/common': 0.0.0-spaces-alpha-20261112204144 + '@atproto/did': 0.0.0-spaces-alpha-20261112204144 + '@atproto/jwk': 0.0.0-spaces-alpha-20261112204144 + '@atproto/jwk-jose': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-document': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-resolver': 0.0.0-spaces-alpha-20261112204144 + '@atproto/oauth-provider-api': 0.0.0-spaces-alpha-20261112204144 + '@atproto/oauth-provider-ui': 0.0.0-spaces-alpha-20261112204144 + '@atproto/oauth-resolver': 0.0.0-spaces-alpha-20261112204144 + '@atproto/oauth-scopes': 0.0.0-spaces-alpha-20261112204144 + '@atproto/oauth-types': 0.0.0-spaces-alpha-20261112204144 + '@atproto/syntax': 0.0.0-spaces-alpha-20261112204144 '@hapi/accept': 6.0.3 '@hapi/address': 5.1.1 '@hapi/bourne': 3.0.0 @@ -7998,15 +7940,25 @@ snapshots: transitivePeerDependencies: - supports-color - '@atproto/oauth-scopes@0.0.0-spaces-alpha-20261105160032': + '@atproto/oauth-resolver@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/did': 0.0.0-spaces-alpha-20261105160032 - '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 + '@atproto-labs/fetch': 0.4.2 + '@atproto-labs/identity-resolver': 0.0.0-spaces-alpha-20261112204144 + '@atproto-labs/simple-store': 0.5.1 + '@atproto-labs/simple-store-memory': 0.2.6 + '@atproto/did': 0.0.0-spaces-alpha-20261112204144 + '@atproto/oauth-types': 0.0.0-spaces-alpha-20261112204144 + zod: 3.25.76 - '@atproto/oauth-types@0.0.0-spaces-alpha-20261105160032': + '@atproto/oauth-scopes@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/did': 0.0.0-spaces-alpha-20261105160032 - '@atproto/jwk': 0.7.4 + '@atproto/did': 0.0.0-spaces-alpha-20261112204144 + '@atproto/syntax': 0.0.0-spaces-alpha-20261112204144 + + '@atproto/oauth-types@0.0.0-spaces-alpha-20261112204144': + dependencies: + '@atproto/did': 0.0.0-spaces-alpha-20261112204144 + '@atproto/jwk': 0.0.0-spaces-alpha-20261112204144 zod: 3.25.76 '@atproto/oauth-types@0.6.3': @@ -8015,23 +7967,24 @@ snapshots: '@atproto/jwk': 0.6.0 zod: 3.25.76 - '@atproto/ozone@0.0.0-spaces-alpha-20261105160032(@opentelemetry/api@1.9.1)(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2)': - dependencies: - '@atproto-labs/fetch-node': 0.0.0-spaces-alpha-20261105160032 - '@atproto-labs/opentelemetry-node': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) - '@atproto/common': 0.0.0-spaces-alpha-20261105160032 - '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 - '@atproto/identity': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-password-session': 0.0.0 - '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 - '@atproto/ws-client': 0.2.1 - '@atproto/xrpc-server': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) + '@atproto/ozone@0.0.0-spaces-alpha-20261112204144(@opentelemetry/api@1.10.0)(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2)': + dependencies: + '@atproto-labs/fetch-node': 0.0.0-spaces-alpha-20261112204144 + '@atproto-labs/opentelemetry-node': 0.5.0(supports-color@10.2.2) + '@atproto/common': 0.0.0-spaces-alpha-20261112204144 + '@atproto/crypto': 0.0.0-spaces-alpha-20261112204144 + '@atproto/identity': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-client': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-password-session': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261112204144 + '@atproto/syntax': 0.0.0-spaces-alpha-20261112204144 + '@atproto/ws-client': 0.0.0-spaces-alpha-20261112204144 + '@atproto/xrpc-server': 0.0.0-spaces-alpha-20261112204144(supports-color@10.2.2) '@did-plc/lib': 0.0.1(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) - '@opentelemetry/instrumentation-pg': 0.72.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/instrumentation-pg': 0.77.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) compression: 1.8.1(supports-color@10.2.2) cors: 2.8.6 - dotenv: 17.4.2 express: 4.22.2(supports-color@10.2.2) http-terminator: 3.2.0 kysely: 0.29.5 @@ -8043,7 +7996,7 @@ snapshots: prom-client: 15.1.3 structured-headers: 1.0.1 uint8arrays: 5.1.1 - undici: 8.10.0 + undici: 8.12.4 ws: 8.20.1 transitivePeerDependencies: - '@opentelemetry/api' @@ -8053,40 +8006,41 @@ snapshots: - supports-color - utf-8-validate - '@atproto/pds@0.0.0-spaces-alpha-20261105160032(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2)': + '@atproto/pds@0.0.0-spaces-alpha-20261112204144(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2)': dependencies: - '@atproto-labs/fetch': 0.3.5 - '@atproto-labs/fetch-node': 0.0.0-spaces-alpha-20261105160032 - '@atproto-labs/opentelemetry-node': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) + '@atproto-labs/fetch': 0.4.2 + '@atproto-labs/fetch-node': 0.0.0-spaces-alpha-20261112204144 + '@atproto-labs/opentelemetry-node': 0.5.0(supports-color@10.2.2) '@atproto-labs/simple-store': 0.5.1 '@atproto-labs/simple-store-memory': 0.2.6 '@atproto-labs/simple-store-redis': 0.1.6(ioredis@5.11.1(supports-color@10.2.2)) - '@atproto-labs/xrpc-utils': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) - '@atproto/aws': 0.0.0-spaces-alpha-20261105160032 - '@atproto/common': 0.0.0-spaces-alpha-20261105160032 - '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 - '@atproto/did': 0.0.0-spaces-alpha-20261105160032 - '@atproto/identity': 0.0.0-spaces-alpha-20261105160032 - '@atproto/jwk': 0.7.4 - '@atproto/lex': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-json': 0.0.0-spaces-alpha-20261105160032 - '@atproto/oauth-provider': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) - '@atproto/oauth-scopes': 0.0.0-spaces-alpha-20261105160032 - '@atproto/oauth-types': 0.0.0-spaces-alpha-20261105160032 - '@atproto/repo': 0.0.0-spaces-alpha-20261105160032 - '@atproto/space': 0.0.0-spaces-alpha-20261105160032 - '@atproto/star': 0.0.0-spaces-alpha-20261105160032 - '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 - '@atproto/xrpc-server': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) + '@atproto-labs/xrpc-utils': 0.0.0-spaces-alpha-20261112204144(supports-color@10.2.2) + '@atproto/aws': 0.0.0-spaces-alpha-20261112204144 + '@atproto/common': 0.0.0-spaces-alpha-20261112204144 + '@atproto/crypto': 0.0.0-spaces-alpha-20261112204144 + '@atproto/did': 0.0.0-spaces-alpha-20261112204144 + '@atproto/identity': 0.0.0-spaces-alpha-20261112204144 + '@atproto/jwk': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-client': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-document': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-json': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261112204144 + '@atproto/oauth-provider': 0.0.0-spaces-alpha-20261112204144(supports-color@10.2.2) + '@atproto/oauth-scopes': 0.0.0-spaces-alpha-20261112204144 + '@atproto/oauth-types': 0.0.0-spaces-alpha-20261112204144 + '@atproto/repo': 0.0.0-spaces-alpha-20261112204144 + '@atproto/space': 0.0.0-spaces-alpha-20261112204144 + '@atproto/star': 0.0.0-spaces-alpha-20261112204144 + '@atproto/syntax': 0.0.0-spaces-alpha-20261112204144 + '@atproto/xrpc-server': 0.0.0-spaces-alpha-20261112204144(supports-color@10.2.2) '@did-plc/lib': 0.0.4(debug@4.4.3(supports-color@10.2.2))(supports-color@10.2.2) '@hapi/address': 5.1.1 '@noble/curves': 1.9.7 - '@opentelemetry/api': 1.9.1 - '@opentelemetry/api-logs': 0.219.0 - '@opentelemetry/instrumentation-aws-sdk': 0.74.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-ioredis': 0.67.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation-aws-sdk': 0.79.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-ioredis': 0.72.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) better-sqlite3: 12.11.1 compression: 1.8.1(supports-color@10.2.2) cors: 2.8.6 @@ -8101,13 +8055,12 @@ snapshots: kysely: 0.29.5 nodemailer: 6.10.1 nodemailer-html-to-text: 3.2.0 - opentelemetry-plugin-better-sqlite3: 1.13.0(better-sqlite3@12.11.1)(supports-color@10.2.2) p-queue: 8.1.1 pino: 10.3.1 pino-http: 11.0.0 strtok3: 10.7.0 uint8arrays: 5.1.1 - undici: 8.10.0 + undici: 8.12.4 zod: 3.25.76 transitivePeerDependencies: - bufferutil @@ -8115,15 +8068,14 @@ snapshots: - supports-color - utf-8-validate - '@atproto/repo@0.0.0-spaces-alpha-20261105160032': + '@atproto/repo@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/car': 0.0.0-spaces-alpha-20261105160032 - '@atproto/common': 0.0.0-spaces-alpha-20261105160032 - '@atproto/common-web': 0.0.0-spaces-alpha-20261105160032 - '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 - '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 + '@atproto/car': 0.0.0-spaces-alpha-20261112204144 + '@atproto/common-web': 0.0.0-spaces-alpha-20261112204144 + '@atproto/crypto': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261112204144 + '@atproto/syntax': 0.0.0-spaces-alpha-20261112204144 zod: 3.25.76 '@atproto/repo@0.8.12': @@ -8138,30 +8090,31 @@ snapshots: varint: 6.0.0 zod: 3.25.76 - '@atproto/space@0.0.0-spaces-alpha-20261105160032': + '@atproto/space@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 - '@atproto/star': 0.0.0-spaces-alpha-20261105160032 - '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 + '@atproto/crypto': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261112204144 + '@atproto/star': 0.0.0-spaces-alpha-20261112204144 + '@atproto/syntax': 0.0.0-spaces-alpha-20261112204144 '@noble/hashes': 1.8.0 structured-headers: 1.0.1 - zod: 3.25.76 - '@atproto/star@0.0.0-spaces-alpha-20261105160032': + '@atproto/star@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261112204144 - '@atproto/sync@0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2)': + '@atproto/sync@0.0.0-spaces-alpha-20261112204144(supports-color@10.2.2)': dependencies: - '@atproto/common': 0.0.0-spaces-alpha-20261105160032 - '@atproto/identity': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex': 0.0.0-spaces-alpha-20261105160032 - '@atproto/repo': 0.0.0-spaces-alpha-20261105160032 - '@atproto/syntax': 0.0.0-spaces-alpha-20261105160032 - '@atproto/xrpc-server': 0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2) + '@atproto/common': 0.0.0-spaces-alpha-20261112204144 + '@atproto/identity': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261112204144 + '@atproto/repo': 0.0.0-spaces-alpha-20261112204144 + '@atproto/syntax': 0.0.0-spaces-alpha-20261112204144 + '@atproto/xrpc-server': 0.0.0-spaces-alpha-20261112204144(supports-color@10.2.2) p-queue: 8.1.1 ws: 8.20.1 transitivePeerDependencies: @@ -8169,40 +8122,37 @@ snapshots: - supports-color - utf-8-validate - '@atproto/syntax@0.0.0-spaces-alpha-20261105160032': + '@atproto/syntax@0.0.0-spaces-alpha-20261112204144': dependencies: iso-datestring-validator: 2.2.2 tslib: 2.8.1 - '@atproto/syntax@0.1.5': - dependencies: - '@atproto/common-web': 0.2.4 - '@atproto/syntax@0.4.2': {} '@atproto/syntax@0.4.3': dependencies: tslib: 2.8.1 - '@atproto/ws-client@0.2.1': + '@atproto/ws-client@0.0.0-spaces-alpha-20261112204144': dependencies: ws: 8.20.1 transitivePeerDependencies: - bufferutil - utf-8-validate - '@atproto/xrpc-server@0.0.0-spaces-alpha-20261105160032(supports-color@10.2.2)': - dependencies: - '@atproto/common': 0.0.0-spaces-alpha-20261105160032 - '@atproto/crypto': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-client': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-data': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-json': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lex-schema': 0.0.0-spaces-alpha-20261105160032 - '@atproto/lexicon': 0.0.0-spaces-alpha-20261105160032 - '@atproto/ws-client': 0.2.1 - '@atproto/xrpc': 0.0.0-spaces-alpha-20261105160032 + '@atproto/xrpc-server@0.0.0-spaces-alpha-20261112204144(supports-color@10.2.2)': + dependencies: + '@atproto/common': 0.0.0-spaces-alpha-20261112204144 + '@atproto/crypto': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-cbor': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-client': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-data': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-json': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lex-schema': 0.0.0-spaces-alpha-20261112204144 + '@atproto/lexicon': 0.0.0-spaces-alpha-20261112204144 + '@atproto/ws-client': 0.0.0-spaces-alpha-20261112204144 + '@atproto/xrpc': 0.0.0-spaces-alpha-20261112204144 + body-parser: 1.20.9(supports-color@10.2.2) express: 4.22.2(supports-color@10.2.2) http-errors: 2.0.1 mime-types: 3.0.2 @@ -8213,9 +8163,9 @@ snapshots: - supports-color - utf-8-validate - '@atproto/xrpc@0.0.0-spaces-alpha-20261105160032': + '@atproto/xrpc@0.0.0-spaces-alpha-20261112204144': dependencies: - '@atproto/lexicon': 0.0.0-spaces-alpha-20261105160032 + '@atproto/lexicon': 0.0.0-spaces-alpha-20261112204144 zod: 3.25.76 '@atproto/xrpc@0.7.7': @@ -8548,24 +8498,6 @@ snapshots: dependencies: fontkitten: 1.0.3 - '@cbor-extract/cbor-extract-darwin-arm64@2.2.2': - optional: true - - '@cbor-extract/cbor-extract-darwin-x64@2.2.2': - optional: true - - '@cbor-extract/cbor-extract-linux-arm64@2.2.2': - optional: true - - '@cbor-extract/cbor-extract-linux-arm@2.2.2': - optional: true - - '@cbor-extract/cbor-extract-linux-x64@2.2.2': - optional: true - - '@cbor-extract/cbor-extract-win32-x64@2.2.2': - optional: true - '@changesets/apply-release-plan@8.0.0': dependencies: '@changesets/config': 4.0.0 @@ -8741,14 +8673,14 @@ snapshots: - utf-8-validate - workerd - '@cloudflare/vitest-pool-workers@0.16.9(@cloudflare/workers-types@4.20260524.1)(@vitest/runner@4.1.7)(@vitest/snapshot@4.1.7)(vitest@4.1.0-beta.1(@opentelemetry/api@1.9.1)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0))': + '@cloudflare/vitest-pool-workers@0.16.9(@cloudflare/workers-types@4.20260524.1)(@vitest/runner@4.1.7)(@vitest/snapshot@4.1.7)(vitest@4.1.0-beta.1(@opentelemetry/api@1.10.0)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0))': dependencies: '@vitest/runner': 4.1.7 '@vitest/snapshot': 4.1.7 cjs-module-lexer: 1.4.3 esbuild: 0.27.3 miniflare: 4.20260521.0 - vitest: 4.1.0-beta.1(@opentelemetry/api@1.9.1)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0) + vitest: 4.1.0-beta.1(@opentelemetry/api@1.10.0)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0) wrangler: 4.94.0(@cloudflare/workers-types@4.20260524.1) zod: 3.25.76 transitivePeerDependencies: @@ -9085,6 +9017,11 @@ snapshots: '@grpc/proto-loader': 0.8.1 '@js-sdsl/ordered-map': 4.4.2 + '@grpc/grpc-js@1.14.7': + dependencies: + '@grpc/proto-loader': 0.8.1 + '@js-sdsl/ordered-map': 4.4.2 + '@grpc/proto-loader@0.7.15': dependencies: lodash.camelcase: 4.3.0 @@ -9446,745 +9383,656 @@ snapshots: '@nodelib/fs.scandir': 2.1.5 fastq: 1.20.1 - '@opentelemetry/api-logs@0.208.0': - dependencies: - '@opentelemetry/api': 1.9.1 - - '@opentelemetry/api-logs@0.219.0': - dependencies: - '@opentelemetry/api': 1.9.1 - - '@opentelemetry/api-logs@0.220.0': - dependencies: - '@opentelemetry/api': 1.9.1 + '@opentelemetry/api@1.10.0': {} '@opentelemetry/api@1.9.1': {} - '@opentelemetry/auto-instrumentations-node@0.77.0(@opentelemetry/api@1.9.1)(@opentelemetry/core@2.10.0(@opentelemetry/api@1.9.1))(supports-color@10.2.2)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-amqplib': 0.66.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-aws-lambda': 0.71.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-aws-sdk': 0.74.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-bunyan': 0.64.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-cassandra-driver': 0.64.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-connect': 0.62.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-cucumber': 0.35.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-dataloader': 0.36.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-dns': 0.62.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-express': 0.67.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-fs': 0.38.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-generic-pool': 0.62.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-graphql': 0.67.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-grpc': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-hapi': 0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-host-metrics': 0.2.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-http': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-ioredis': 0.67.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-kafkajs': 0.28.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-knex': 0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-koa': 0.67.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-lru-memoizer': 0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-memcached': 0.62.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-mongodb': 0.72.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-mongoose': 0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-mysql': 0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-mysql2': 0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-nestjs-core': 0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-net': 0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-openai': 0.17.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-oracledb': 0.44.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-pg': 0.71.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-pino': 0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-redis': 0.67.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-restify': 0.64.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-router': 0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-runtime-node': 0.32.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-socket.io': 0.66.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-tedious': 0.38.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-undici': 0.29.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/instrumentation-winston': 0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/resource-detector-alibaba-cloud': 0.34.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resource-detector-aws': 2.21.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resource-detector-azure': 0.27.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resource-detector-container': 0.8.12(@opentelemetry/api@1.9.1) - '@opentelemetry/resource-detector-gcp': 0.54.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/resources': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-node': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/auto-instrumentations-node@0.82.0(@opentelemetry/api@1.10.0)(@opentelemetry/core@3.1.1(@opentelemetry/api@1.10.0))(supports-color@10.2.2)': + dependencies: + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-amqplib': 0.71.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-aws-lambda': 0.76.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-aws-sdk': 0.79.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-bunyan': 0.69.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-cassandra-driver': 0.69.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-connect': 0.67.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-cucumber': 0.40.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-dataloader': 0.41.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-dns': 0.67.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-express': 0.72.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-fs': 0.43.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-generic-pool': 0.67.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-graphql': 0.72.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-grpc': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-hapi': 0.70.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-host-metrics': 0.7.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-http': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-ioredis': 0.72.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-kafkajs': 0.33.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-knex': 0.68.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-koa': 0.72.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-lru-memoizer': 0.68.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-memcached': 0.67.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-mongodb': 0.77.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-mongoose': 0.70.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-mysql': 0.70.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-mysql2': 0.70.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-nestjs-core': 0.71.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-net': 0.68.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-openai': 0.22.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-oracledb': 0.49.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-pg': 0.77.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-pino': 0.70.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-redis': 0.72.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-restify': 0.69.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-router': 0.68.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-runtime-node': 0.37.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-socket.io': 0.71.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-tedious': 0.43.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-undici': 0.34.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/instrumentation-winston': 0.69.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/resource-detector-alibaba-cloud': 0.39.0(@opentelemetry/api@1.10.0) + '@opentelemetry/resource-detector-aws': 3.1.0(@opentelemetry/api@1.10.0) + '@opentelemetry/resource-detector-azure': 0.32.0(@opentelemetry/api@1.10.0) + '@opentelemetry/resource-detector-container': 0.9.1(@opentelemetry/api@1.10.0) + '@opentelemetry/resource-detector-gcp': 0.59.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/resources': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-node': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/configuration@0.219.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/configuration@0.300.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) yaml: 2.9.0 - '@opentelemetry/context-async-hooks@2.8.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/context-async-hooks@3.0.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 + '@opentelemetry/api': 1.10.0 - '@opentelemetry/core@2.10.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/core@3.0.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 + '@opentelemetry/api': 1.10.0 '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/core@2.8.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/core@3.1.1(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 + '@opentelemetry/api': 1.10.0 '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/exporter-logs-otlp-grpc@0.219.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/exporter-logs-otlp-grpc@0.300.0(@opentelemetry/api@1.10.0)': dependencies: - '@grpc/grpc-js': 1.14.4 - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-exporter-base': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-grpc-exporter-base': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-transformer': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-logs': 0.219.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/otlp-exporter-base': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-grpc-exporter-base': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-transformer': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-logs': 3.0.0(@opentelemetry/api@1.10.0) - '@opentelemetry/exporter-logs-otlp-http@0.219.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/exporter-logs-otlp-http@0.300.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/api-logs': 0.219.0 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-exporter-base': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-transformer': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-logs': 0.219.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/otlp-exporter-base': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-transformer': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-logs': 3.0.0(@opentelemetry/api@1.10.0) - '@opentelemetry/exporter-logs-otlp-proto@0.219.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/exporter-logs-otlp-proto@0.300.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/api-logs': 0.219.0 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-exporter-base': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-transformer': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-logs': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-trace-base': 2.8.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/otlp-exporter-base': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-transformer': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-logs': 3.0.0(@opentelemetry/api@1.10.0) - '@opentelemetry/exporter-metrics-otlp-grpc@0.219.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/exporter-metrics-otlp-grpc@0.300.0(@opentelemetry/api@1.10.0)': dependencies: - '@grpc/grpc-js': 1.14.4 - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/exporter-metrics-otlp-http': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-exporter-base': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-grpc-exporter-base': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-transformer': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-metrics': 2.8.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/exporter-metrics-otlp-http': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-grpc-exporter-base': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-transformer': 0.300.0(@opentelemetry/api@1.10.0) - '@opentelemetry/exporter-metrics-otlp-http@0.219.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/exporter-metrics-otlp-http@0.300.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-exporter-base': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-transformer': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-metrics': 2.8.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-exporter-base': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-transformer': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-metrics': 3.0.0(@opentelemetry/api@1.10.0) - '@opentelemetry/exporter-metrics-otlp-proto@0.219.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/exporter-metrics-otlp-proto@0.300.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/exporter-metrics-otlp-http': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-exporter-base': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-transformer': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-metrics': 2.8.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/exporter-metrics-otlp-http': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-exporter-base': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-transformer': 0.300.0(@opentelemetry/api@1.10.0) - '@opentelemetry/exporter-prometheus@0.219.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/exporter-prometheus@0.300.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-metrics': 2.8.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-metrics': 3.0.0(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/exporter-trace-otlp-grpc@0.219.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/exporter-trace-otlp-grpc@0.300.0(@opentelemetry/api@1.10.0)': dependencies: - '@grpc/grpc-js': 1.14.4 - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-exporter-base': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-grpc-exporter-base': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-transformer': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-trace-base': 2.8.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/otlp-exporter-base': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-grpc-exporter-base': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-transformer': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-trace': 3.0.0(@opentelemetry/api@1.10.0) - '@opentelemetry/exporter-trace-otlp-http@0.219.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/exporter-trace-otlp-http@0.300.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-exporter-base': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-transformer': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-trace-base': 2.8.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/otlp-exporter-base': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-transformer': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-trace': 3.0.0(@opentelemetry/api@1.10.0) - '@opentelemetry/exporter-trace-otlp-proto@0.219.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/exporter-trace-otlp-proto@0.300.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-exporter-base': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-transformer': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-trace-base': 2.8.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/otlp-exporter-base': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-transformer': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-trace': 3.0.0(@opentelemetry/api@1.10.0) - '@opentelemetry/exporter-zipkin@2.8.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/exporter-zipkin@3.0.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-trace-base': 2.8.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-trace': 3.0.0(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/instrumentation-amqplib@0.66.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-amqplib@0.71.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-aws-lambda@0.71.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-aws-lambda@0.76.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/propagator-aws-xray': 2.2.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/propagator-aws-xray': 3.0.0(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions': 1.43.0 '@types/aws-lambda': 8.10.162 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-aws-sdk@0.74.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-aws-sdk@0.79.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-bunyan@0.64.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-bunyan@0.69.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/api-logs': 0.219.0 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@types/bunyan': 1.8.11 + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-cassandra-driver@0.64.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-cassandra-driver@0.69.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-connect@0.62.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-connect@0.67.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 '@types/connect': 3.4.38 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-cucumber@0.35.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-cucumber@0.40.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-dataloader@0.36.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-dataloader@0.41.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-dns@0.62.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-dns@0.67.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-express@0.67.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-express@0.72.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-fs@0.38.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-fs@0.43.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-generic-pool@0.62.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-generic-pool@0.67.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-graphql@0.67.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-graphql@0.72.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-grpc@0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-grpc@0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-hapi@0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-hapi@0.70.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-host-metrics@0.2.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-host-metrics@0.7.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) systeminformation: 5.33.6 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-http@0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-http@0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 forwarded-parse: 2.1.2 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-ioredis@0.67.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-ioredis@0.72.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/redis-common': 0.38.3 + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/redis-common': 0.39.0 '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-kafkajs@0.28.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-kafkajs@0.33.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-knex@0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-knex@0.68.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-koa@0.67.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-koa@0.72.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-lru-memoizer@0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-lru-memoizer@0.68.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-memcached@0.62.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-memcached@0.67.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 '@types/memcached': 2.2.10 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-mongodb@0.72.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-mongodb@0.77.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-mongoose@0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-mongoose@0.70.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-mysql2@0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-mysql2@0.70.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/sql-common': 0.42.0(@opentelemetry/api@1.9.1) + '@opentelemetry/sql-common': 0.43.1(@opentelemetry/api@1.10.0) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-mysql@0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-mysql@0.70.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 - '@types/mysql': 2.15.27 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-nestjs-core@0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-nestjs-core@0.71.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-net@0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-net@0.68.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-openai@0.17.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-openai@0.22.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/api-logs': 0.219.0 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-oracledb@0.44.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-oracledb@0.49.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 - '@types/oracledb': 6.5.2 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-pg@0.71.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-pg@0.77.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/sql-common': 0.42.0(@opentelemetry/api@1.9.1) + '@opentelemetry/sql-common': 0.43.1(@opentelemetry/api@1.10.0) '@types/pg': 8.15.6 '@types/pg-pool': 2.0.7 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-pg@0.72.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-pino@0.70.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.220.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/sql-common': 0.42.0(@opentelemetry/api@1.9.1) - '@types/pg': 8.15.6 - '@types/pg-pool': 2.0.7 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-pino@0.65.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-redis@0.72.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/api-logs': 0.219.0 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - transitivePeerDependencies: - - supports-color - - '@opentelemetry/instrumentation-redis@0.67.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/redis-common': 0.38.3 + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/redis-common': 0.39.0 '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-restify@0.64.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-restify@0.69.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-router@0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-router@0.68.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-runtime-node@0.32.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-runtime-node@0.37.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/api-logs': 0.219.0 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-socket.io@0.66.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-socket.io@0.71.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-tedious@0.38.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-tedious@0.43.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 - '@types/tedious': 4.0.14 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-undici@0.29.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-undici@0.34.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation-winston@0.63.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation-winston@0.69.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/api-logs': 0.219.0 - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - transitivePeerDependencies: - - supports-color - - '@opentelemetry/instrumentation@0.208.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/api-logs': 0.208.0 - import-in-the-middle: 2.0.6 - require-in-the-middle: 8.0.1(supports-color@10.2.2) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation@0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/instrumentation@0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/api-logs': 0.219.0 + '@opentelemetry/api': 1.10.0 import-in-the-middle: 3.3.3 require-in-the-middle: 8.0.1(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/instrumentation@0.220.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/otlp-exporter-base@0.300.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/api-logs': 0.220.0 - import-in-the-middle: 3.3.3 - require-in-the-middle: 8.0.1(supports-color@10.2.2) - transitivePeerDependencies: - - supports-color + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-transformer': 0.300.0(@opentelemetry/api@1.10.0) - '@opentelemetry/otlp-exporter-base@0.219.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/otlp-grpc-exporter-base@0.300.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-transformer': 0.219.0(@opentelemetry/api@1.9.1) + '@grpc/grpc-js': 1.14.7 + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-exporter-base': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-transformer': 0.300.0(@opentelemetry/api@1.10.0) - '@opentelemetry/otlp-grpc-exporter-base@0.219.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/otlp-transformer@0.300.0(@opentelemetry/api@1.10.0)': dependencies: - '@grpc/grpc-js': 1.14.4 - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-exporter-base': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-transformer': 0.219.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-logs': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-metrics': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-trace': 3.0.0(@opentelemetry/api@1.10.0) - '@opentelemetry/otlp-transformer@0.219.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/propagator-aws-xray@3.0.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/api-logs': 0.219.0 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-logs': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-metrics': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-trace-base': 2.8.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 - '@opentelemetry/propagator-aws-xray@2.2.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/propagator-b3@3.0.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) - '@opentelemetry/propagator-b3@2.8.0(@opentelemetry/api@1.9.1)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) + '@opentelemetry/redis-common@0.39.0': {} - '@opentelemetry/propagator-jaeger@2.8.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/resource-detector-alibaba-cloud@0.39.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - - '@opentelemetry/redis-common@0.38.3': {} + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 3.1.1(@opentelemetry/api@1.10.0) - '@opentelemetry/resource-detector-alibaba-cloud@0.34.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/resource-detector-aws@3.1.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.10.0(@opentelemetry/api@1.9.1) - - '@opentelemetry/resource-detector-aws@2.21.0(@opentelemetry/api@1.9.1)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.10.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 3.1.1(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/resource-detector-azure@0.27.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/resource-detector-azure@0.32.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.10.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 3.1.1(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/resource-detector-container@0.8.12(@opentelemetry/api@1.9.1)': + '@opentelemetry/resource-detector-container@0.9.1(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.10.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 3.1.1(@opentelemetry/api@1.10.0) - '@opentelemetry/resource-detector-gcp@0.54.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': + '@opentelemetry/resource-detector-gcp@0.59.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.10.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 3.1.1(@opentelemetry/api@1.10.0) gcp-metadata: 8.1.4(supports-color@10.2.2) transitivePeerDependencies: - supports-color - '@opentelemetry/resources@2.10.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/resources@3.0.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/resources@2.8.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/resources@3.1.1(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/sdk-logs@0.219.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/sdk-logs@3.0.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/api-logs': 0.219.0 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 3.0.0(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/sdk-metrics@2.8.0(@opentelemetry/api@1.9.1)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) - - '@opentelemetry/sdk-node@0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/api-logs': 0.219.0 - '@opentelemetry/configuration': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/context-async-hooks': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/exporter-logs-otlp-grpc': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/exporter-logs-otlp-http': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/exporter-logs-otlp-proto': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/exporter-metrics-otlp-grpc': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/exporter-metrics-otlp-http': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/exporter-metrics-otlp-proto': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/exporter-prometheus': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/exporter-trace-otlp-grpc': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/exporter-trace-otlp-http': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/exporter-trace-otlp-proto': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/exporter-zipkin': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.219.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/otlp-exporter-base': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/otlp-grpc-exporter-base': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/propagator-b3': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/propagator-jaeger': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-logs': 0.219.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-metrics': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-trace-base': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-trace-node': 2.8.0(@opentelemetry/api@1.9.1) + '@opentelemetry/sdk-metrics@3.0.0(@opentelemetry/api@1.10.0)': + dependencies: + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 3.0.0(@opentelemetry/api@1.10.0) + + '@opentelemetry/sdk-node@0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2)': + dependencies: + '@opentelemetry/api': 1.10.0 + '@opentelemetry/configuration': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/context-async-hooks': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/exporter-logs-otlp-grpc': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/exporter-logs-otlp-http': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/exporter-logs-otlp-proto': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/exporter-metrics-otlp-grpc': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/exporter-metrics-otlp-http': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/exporter-metrics-otlp-proto': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/exporter-prometheus': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/exporter-trace-otlp-grpc': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/exporter-trace-otlp-http': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/exporter-trace-otlp-proto': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/exporter-zipkin': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/instrumentation': 0.300.0(@opentelemetry/api@1.10.0)(supports-color@10.2.2) + '@opentelemetry/otlp-exporter-base': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/otlp-grpc-exporter-base': 0.300.0(@opentelemetry/api@1.10.0) + '@opentelemetry/propagator-b3': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-logs': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-metrics': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/sdk-trace': 3.0.0(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions': 1.43.0 transitivePeerDependencies: - supports-color - '@opentelemetry/sdk-trace-base@2.8.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/sdk-trace@3.0.0(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/resources': 2.8.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.0.0(@opentelemetry/api@1.10.0) + '@opentelemetry/resources': 3.0.0(@opentelemetry/api@1.10.0) '@opentelemetry/semantic-conventions': 1.43.0 - '@opentelemetry/sdk-trace-node@2.8.0(@opentelemetry/api@1.9.1)': - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/context-async-hooks': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/core': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/sdk-trace-base': 2.8.0(@opentelemetry/api@1.9.1) - '@opentelemetry/semantic-conventions@1.43.0': {} - '@opentelemetry/sql-common@0.42.0(@opentelemetry/api@1.9.1)': + '@opentelemetry/sql-common@0.43.1(@opentelemetry/api@1.10.0)': dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) + '@opentelemetry/api': 1.10.0 + '@opentelemetry/core': 3.1.1(@opentelemetry/api@1.10.0) '@oslojs/encoding@1.1.0': {} @@ -10829,12 +10677,6 @@ snapshots: '@tokenizer/token@0.3.0': {} - '@ts-morph/common@0.28.1': - dependencies: - minimatch: 10.2.6 - path-browserify: 1.0.1 - tinyglobby: 0.2.16 - '@tybys/wasm-util@0.10.1': dependencies: tslib: 2.8.1 @@ -10867,10 +10709,6 @@ snapshots: dependencies: bun-types: 1.3.8 - '@types/bunyan@1.8.11': - dependencies: - '@types/node': 24.10.11 - '@types/chai@5.2.3': dependencies: '@types/deep-eql': 4.0.2 @@ -10912,10 +10750,6 @@ snapshots: '@types/ms@2.1.0': {} - '@types/mysql@2.15.27': - dependencies: - '@types/node': 24.10.11 - '@types/nlcst@2.0.3': dependencies: '@types/unist': 3.0.3 @@ -10924,10 +10758,6 @@ snapshots: dependencies: undici-types: 7.16.0 - '@types/oracledb@6.5.2': - dependencies: - '@types/node': 24.10.11 - '@types/pg-pool@2.0.7': dependencies: '@types/pg': 8.15.6 @@ -10946,10 +10776,6 @@ snapshots: dependencies: '@types/node': 24.10.11 - '@types/tedious@4.0.14': - dependencies: - '@types/node': 24.10.11 - '@types/unist@2.0.11': {} '@types/unist@3.0.3': {} @@ -10958,6 +10784,66 @@ snapshots: dependencies: '@types/node': 24.10.11 + '@typescript/typescript-aix-ppc64@7.0.2': + optional: true + + '@typescript/typescript-darwin-arm64@7.0.2': + optional: true + + '@typescript/typescript-darwin-x64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-freebsd-x64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm64@7.0.2': + optional: true + + '@typescript/typescript-linux-arm@7.0.2': + optional: true + + '@typescript/typescript-linux-loong64@7.0.2': + optional: true + + '@typescript/typescript-linux-mips64el@7.0.2': + optional: true + + '@typescript/typescript-linux-ppc64@7.0.2': + optional: true + + '@typescript/typescript-linux-riscv64@7.0.2': + optional: true + + '@typescript/typescript-linux-s390x@7.0.2': + optional: true + + '@typescript/typescript-linux-x64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-netbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-arm64@7.0.2': + optional: true + + '@typescript/typescript-openbsd-x64@7.0.2': + optional: true + + '@typescript/typescript-sunos-x64@7.0.2': + optional: true + + '@typescript/typescript-win32-arm64@7.0.2': + optional: true + + '@typescript/typescript-win32-x64@7.0.2': + optional: true + '@ungap/structured-clone@1.3.1': {} '@vitest/expect@4.1.0-beta.1': @@ -11030,10 +10916,6 @@ snapshots: mime-types: 2.1.35 negotiator: 0.6.3 - acorn-import-attributes@1.9.5(acorn@8.16.0): - dependencies: - acorn: 8.16.0 - acorn-jsx@5.3.2(acorn@8.16.0): dependencies: acorn: 8.16.0 @@ -11234,8 +11116,6 @@ snapshots: balanced-match@1.0.2: {} - balanced-match@4.0.4: {} - base64-js@1.5.1: {} baseline-browser-mapping@2.10.32: {} @@ -11292,6 +11172,23 @@ snapshots: transitivePeerDependencies: - supports-color + body-parser@1.20.9(supports-color@10.2.2): + dependencies: + bytes: 3.1.2 + content-type: 1.0.5 + debug: 2.6.9(supports-color@10.2.2) + depd: 2.0.0 + destroy: 1.2.0 + http-errors: 2.0.1 + iconv-lite: 0.4.24 + on-finished: 2.4.1 + qs: 6.16.2 + raw-body: 2.5.3 + type-is: 1.6.18 + unpipe: 1.0.0 + transitivePeerDependencies: + - supports-color + boolbase@1.0.0: {} bowser@2.14.1: {} @@ -11300,10 +11197,6 @@ snapshots: dependencies: balanced-match: 1.0.2 - brace-expansion@5.0.9: - dependencies: - balanced-match: 4.0.4 - braces@3.0.3: dependencies: fill-range: 7.1.1 @@ -11355,22 +11248,6 @@ snapshots: caniuse-lite@1.0.30001793: {} - cbor-extract@2.2.2: - dependencies: - node-gyp-build-optional-packages: 5.1.1 - optionalDependencies: - '@cbor-extract/cbor-extract-darwin-arm64': 2.2.2 - '@cbor-extract/cbor-extract-darwin-x64': 2.2.2 - '@cbor-extract/cbor-extract-linux-arm': 2.2.2 - '@cbor-extract/cbor-extract-linux-arm64': 2.2.2 - '@cbor-extract/cbor-extract-linux-x64': 2.2.2 - '@cbor-extract/cbor-extract-win32-x64': 2.2.2 - optional: true - - cbor-x@1.6.6: - optionalDependencies: - cbor-extract: 2.2.2 - cborg@1.10.2: {} cborg@4.5.8: {} @@ -11447,20 +11324,12 @@ snapshots: strip-ansi: 6.0.1 wrap-ansi: 7.0.0 - cliui@9.0.1: - dependencies: - string-width: 7.2.0 - strip-ansi: 7.2.0 - wrap-ansi: 9.0.2 - clsx@2.1.1: {} cluster-key-slot@1.1.1: {} cockatiel@3.2.1: {} - code-block-writer@13.0.3: {} - collapse-white-space@2.1.0: {} color-convert@2.0.1: @@ -11676,8 +11545,6 @@ snapshots: domelementtype: 2.3.0 domhandler: 5.0.3 - dotenv@17.4.2: {} - dset@3.1.4: {} dts-resolver@2.1.3(oxc-resolver@11.17.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0)): @@ -11696,8 +11563,6 @@ snapshots: electron-to-chromium@1.5.361: {} - emoji-regex@10.6.0: {} - emoji-regex@8.0.0: {} emoji-regex@9.2.2: {} @@ -11737,6 +11602,8 @@ snapshots: es-module-lexer@2.3.2: {} + es-module-lexer@3.0.4: {} + es-object-atoms@1.1.2: dependencies: es-errors: 1.3.0 @@ -12080,8 +11947,6 @@ snapshots: get-caller-file@2.0.5: {} - get-east-asian-width@1.6.0: {} - get-intrinsic@1.3.0: dependencies: call-bind-apply-helpers: 1.0.2 @@ -12133,8 +11998,6 @@ snapshots: graceful-fs@4.2.11: {} - graphemer@1.4.0: {} - h3@1.15.11: dependencies: cookie-es: 1.2.3 @@ -12434,17 +12297,16 @@ snapshots: ieee754@1.2.1: {} - import-in-the-middle@2.0.6: + import-in-the-middle@3.3.3: dependencies: - acorn: 8.16.0 - acorn-import-attributes: 1.9.5(acorn@8.16.0) cjs-module-lexer: 2.2.1 + es-module-lexer: 2.3.2 module-details-from-path: 1.0.4 - import-in-the-middle@3.3.3: + import-in-the-middle@3.6.0: dependencies: cjs-module-lexer: 2.2.1 - es-module-lexer: 2.3.2 + es-module-lexer: 3.0.4 module-details-from-path: 1.0.4 import-meta-resolve@4.2.0: {} @@ -12572,8 +12434,6 @@ snapshots: - '@emnapi/core' - '@emnapi/runtime' - kysely@0.22.0: {} - kysely@0.23.5: {} kysely@0.29.5: {} @@ -13208,10 +13068,6 @@ snapshots: - bufferutil - utf-8-validate - minimatch@10.2.6: - dependencies: - brace-expansion: 5.0.9 - minimatch@9.0.9: dependencies: brace-expansion: 2.1.4 @@ -13287,11 +13143,6 @@ snapshots: fetch-blob: 3.2.0 formdata-polyfill: 4.0.10 - node-gyp-build-optional-packages@5.1.1: - dependencies: - detect-libc: 2.1.2 - optional: true - node-gyp-build@4.8.4: {} node-mock-http@1.0.4: {} @@ -13348,16 +13199,6 @@ snapshots: regex: 6.1.0 regex-recursion: 6.0.2 - opentelemetry-plugin-better-sqlite3@1.13.0(better-sqlite3@12.11.1)(supports-color@10.2.2): - dependencies: - '@opentelemetry/api': 1.9.1 - '@opentelemetry/core': 2.10.0(@opentelemetry/api@1.9.1) - '@opentelemetry/instrumentation': 0.208.0(@opentelemetry/api@1.9.1)(supports-color@10.2.2) - '@opentelemetry/semantic-conventions': 1.43.0 - better-sqlite3: 12.11.1 - transitivePeerDependencies: - - supports-color - oxc-resolver@11.17.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0): optionalDependencies: '@oxc-resolver/binding-android-arm-eabi': 11.17.0 @@ -13471,8 +13312,6 @@ snapshots: parseurl@1.3.3: {} - path-browserify@1.0.1: {} - path-exists@4.0.0: {} path-key@3.1.1: {} @@ -13647,8 +13486,6 @@ snapshots: prettier@3.8.1: {} - prettier@3.9.6: {} - prismjs@1.30.0: {} process-warning@3.0.0: {} @@ -13714,6 +13551,11 @@ snapshots: es-define-property: 1.0.1 side-channel: 1.1.1 + qs@6.16.2: + dependencies: + es-define-property: 1.0.1 + side-channel: 1.1.1 + quansync@1.0.0: {} queue-microtask@1.2.3: {} @@ -14086,11 +13928,6 @@ snapshots: russian-bad-words@0.5.0: optional: true - rxjs@7.8.2: - dependencies: - tslib: 2.8.1 - optional: true - sade@1.8.1: dependencies: mri: 1.2.0 @@ -14343,17 +14180,6 @@ snapshots: emoji-regex: 9.2.2 strip-ansi: 7.2.0 - string-width@7.2.0: - dependencies: - emoji-regex: 10.6.0 - get-east-asian-width: 1.6.0 - strip-ansi: 7.2.0 - - string-width@8.2.2: - dependencies: - get-east-asian-width: 1.6.0 - strip-ansi: 7.2.0 - string_decoder@1.3.0: dependencies: safe-buffer: 5.2.1 @@ -14499,11 +14325,6 @@ snapshots: trough@2.2.0: {} - ts-morph@27.0.2: - dependencies: - '@ts-morph/common': 0.28.1 - code-block-writer: 13.0.3 - tsdown@0.18.4(@arethetypeswrong/core@0.18.2)(oxc-resolver@11.17.0(@emnapi/core@1.10.0)(@emnapi/runtime@1.10.0))(publint@0.3.17)(typescript@5.9.3): dependencies: ansis: 4.2.0 @@ -14559,16 +14380,35 @@ snapshots: media-typer: 0.3.0 mime-types: 2.1.35 - typed-emitter@2.1.0: - optionalDependencies: - rxjs: 7.8.2 - typescript@5.6.1-rc: {} typescript@5.9.3: {} typescript@6.0.3: {} + typescript@7.0.2: + optionalDependencies: + '@typescript/typescript-aix-ppc64': 7.0.2 + '@typescript/typescript-darwin-arm64': 7.0.2 + '@typescript/typescript-darwin-x64': 7.0.2 + '@typescript/typescript-freebsd-arm64': 7.0.2 + '@typescript/typescript-freebsd-x64': 7.0.2 + '@typescript/typescript-linux-arm': 7.0.2 + '@typescript/typescript-linux-arm64': 7.0.2 + '@typescript/typescript-linux-loong64': 7.0.2 + '@typescript/typescript-linux-mips64el': 7.0.2 + '@typescript/typescript-linux-ppc64': 7.0.2 + '@typescript/typescript-linux-riscv64': 7.0.2 + '@typescript/typescript-linux-s390x': 7.0.2 + '@typescript/typescript-linux-x64': 7.0.2 + '@typescript/typescript-netbsd-arm64': 7.0.2 + '@typescript/typescript-netbsd-x64': 7.0.2 + '@typescript/typescript-openbsd-arm64': 7.0.2 + '@typescript/typescript-openbsd-x64': 7.0.2 + '@typescript/typescript-sunos-x64': 7.0.2 + '@typescript/typescript-win32-arm64': 7.0.2 + '@typescript/typescript-win32-x64': 7.0.2 + ufo@1.6.4: {} uglify-js@3.19.3: @@ -14599,13 +14439,15 @@ snapshots: dependencies: '@fastify/busboy': 2.1.1 - undici@6.28.0: {} + undici@6.29.1: {} undici@7.18.2: {} undici@7.24.8: {} - undici@8.10.0: {} + undici@7.30.2: {} + + undici@8.12.4: {} unenv@2.0.0-rc.24: dependencies: @@ -14802,7 +14644,7 @@ snapshots: optionalDependencies: vite: 8.0.14(@types/node@24.10.11)(esbuild@0.27.3)(jiti@2.6.1)(tsx@4.21.0)(yaml@2.9.0) - vitest@4.1.0-beta.1(@opentelemetry/api@1.9.1)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0): + vitest@4.1.0-beta.1(@opentelemetry/api@1.10.0)(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0): dependencies: '@vitest/expect': 4.1.0-beta.1 '@vitest/mocker': 4.1.0-beta.1(vite@6.4.1(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0)) @@ -14825,7 +14667,7 @@ snapshots: vite: 6.4.1(@types/node@24.10.11)(jiti@2.6.1)(lightningcss@1.32.0)(tsx@4.21.0)(yaml@2.9.0) why-is-node-running: 2.3.0 optionalDependencies: - '@opentelemetry/api': 1.9.1 + '@opentelemetry/api': 1.10.0 '@types/node': 24.10.11 transitivePeerDependencies: - jiti @@ -14913,12 +14755,6 @@ snapshots: string-width: 5.1.2 strip-ansi: 7.2.0 - wrap-ansi@9.0.2: - dependencies: - ansi-styles: 6.2.3 - string-width: 7.2.0 - strip-ansi: 7.2.0 - wrappy@1.0.2: {} ws@8.18.0: {} @@ -14984,15 +14820,6 @@ snapshots: y18n: 5.0.8 yargs-parser: 21.1.1 - yargs@18.1.0: - dependencies: - cliui: 9.0.1 - escalade: 3.2.0 - get-caller-file: 2.0.5 - string-width: 8.2.2 - y18n: 5.0.8 - yargs-parser: 22.0.0 - yocto-queue@1.2.2: {} youch-core@0.3.3: @@ -15008,8 +14835,6 @@ snapshots: cookie: 1.1.1 youch-core: 0.3.3 - zod@3.21.4: {} - zod@3.23.8: {} zod@3.25.76: {} diff --git a/pnpm-workspace.yaml b/pnpm-workspace.yaml index 8415e87..5352e3f 100644 --- a/pnpm-workspace.yaml +++ b/pnpm-workspace.yaml @@ -20,8 +20,9 @@ allowBuilds: # The spaces alpha published the @atproto/lex* family twice: once as a broken # bare `0.0.0` whose manifest still carries unresolved `workspace:*` sibling # specifiers (so it cannot install outside the atproto monorepo), and once as a -# clean `0.0.0-spaces-alpha-*` build. @atproto/star likewise has a corrupt -# `0.0.0-stage` tarball. Alpha dependency ranges are `^0.0.0-spaces-alpha-*`, +# clean `0.0.0-spaces-alpha-*` build. @atproto/star, lex-rpc and +# oauth-resolver likewise have a corrupt `0.0.0-stage` tarball, and bsync +# and lex-password-session a broken bare `0.0.0`. Alpha dependency ranges are `^0.0.0-spaces-alpha-*`, # and by semver both a bare `0.0.0` and `0.0.0-stage` outrank that prerelease, # so pnpm picks the broken build. @atproto/space and @atproto/dev-env (the # reference PDS harness the conformance matrix runs against) both reach these. @@ -36,16 +37,70 @@ allowBuilds: # Consumers never resolve an alpha range. Bump these in lockstep with # @atproto/space. overrides: - "@atproto/lex": "0.0.0-spaces-alpha-20261105160032" - "@atproto/lex-resolver": "0.0.0-spaces-alpha-20261105160032" - "@atproto/lex-client": "0.0.0-spaces-alpha-20261105160032" - "@atproto/lex-schema": "0.0.0-spaces-alpha-20261105160032" - "@atproto/lex-builder": "0.0.0-spaces-alpha-20261105160032" - "@atproto/lex-installer": "0.0.0-spaces-alpha-20261105160032" - "@atproto/lex-document": "0.0.0-spaces-alpha-20261105160032" - "@atproto/lex-cbor@^0.0.0-spaces-alpha": "0.0.0-spaces-alpha-20261105160032" - "@atproto/lex-data@^0.0.0-spaces-alpha": "0.0.0-spaces-alpha-20261105160032" - "@atproto/lex-json@^0.0.0-spaces-alpha": "0.0.0-spaces-alpha-20261105160032" - "@atproto/star": "0.0.0-spaces-alpha-20261105160032" + "@atproto/lex": "0.0.0-spaces-alpha-20261112204144" + "@atproto/lex-resolver": "0.0.0-spaces-alpha-20261112204144" + "@atproto/lex-client": "0.0.0-spaces-alpha-20261112204144" + "@atproto/lex-schema": "0.0.0-spaces-alpha-20261112204144" + "@atproto/lex-builder": "0.0.0-spaces-alpha-20261112204144" + "@atproto/lex-installer": "0.0.0-spaces-alpha-20261112204144" + "@atproto/lex-document": "0.0.0-spaces-alpha-20261112204144" + "@atproto/lex-cbor@^0.0.0-spaces-alpha": "0.0.0-spaces-alpha-20261112204144" + "@atproto/lex-data@^0.0.0-spaces-alpha": "0.0.0-spaces-alpha-20261112204144" + "@atproto/lex-json@^0.0.0-spaces-alpha": "0.0.0-spaces-alpha-20261112204144" + "@atproto/star": "0.0.0-spaces-alpha-20261112204144" + "@atproto/lex-rpc@^0.0.0-spaces-alpha": "0.0.0-spaces-alpha-20261112204144" + "@atproto/oauth-resolver@^0.0.0-spaces-alpha": "0.0.0-spaces-alpha-20261112204144" + "@atproto/lex-password-session@^0.0.0-spaces-alpha": "0.0.0-spaces-alpha-20261112204144" + "@atproto/bsync@^0.0.0-spaces-alpha": "0.0.0-spaces-alpha-20261112204144" linkWorkspacePackages: true + +minimumReleaseAgeExclude: + - '@atproto-labs/did-resolver@0.0.0-spaces-alpha-20261112204144' + - '@atproto-labs/fetch-node@0.0.0-spaces-alpha-20261112204144' + - '@atproto-labs/handle-resolver-node@0.0.0-spaces-alpha-20261112204144' + - '@atproto-labs/handle-resolver@0.0.0-spaces-alpha-20261112204144' + - '@atproto-labs/identity-resolver@0.0.0-spaces-alpha-20261112204144' + - '@atproto-labs/xrpc-utils@0.0.0-spaces-alpha-20261112204144' + - '@atproto/api@0.0.0-spaces-alpha-20261112204144' + - '@atproto/aws@0.0.0-spaces-alpha-20261112204144' + - '@atproto/bsky@0.0.0-spaces-alpha-20261112204144' + - '@atproto/bsync@0.0.0-spaces-alpha-20261112204144' + - '@atproto/car@0.0.0-spaces-alpha-20261112204144' + - '@atproto/common-web@0.0.0-spaces-alpha-20261112204144' + - '@atproto/common@0.0.0-spaces-alpha-20261112204144' + - '@atproto/crypto@0.0.0-spaces-alpha-20261112204144' + - '@atproto/dev-env@0.0.0-spaces-alpha-20261112204144' + - '@atproto/did@0.0.0-spaces-alpha-20261112204144' + - '@atproto/identity@0.0.0-spaces-alpha-20261112204144' + - '@atproto/jwk-jose@0.0.0-spaces-alpha-20261112204144' + - '@atproto/jwk-webcrypto@0.0.0-spaces-alpha-20261112204144' + - '@atproto/jwk@0.0.0-spaces-alpha-20261112204144' + - '@atproto/lex-cbor@0.0.0-spaces-alpha-20261112204144' + - '@atproto/lex-client@0.0.0-spaces-alpha-20261112204144' + - '@atproto/lex-data@0.0.0-spaces-alpha-20261112204144' + - '@atproto/lex-document@0.0.0-spaces-alpha-20261112204144' + - '@atproto/lex-json@0.0.0-spaces-alpha-20261112204144' + - '@atproto/lex-password-session@0.0.0-spaces-alpha-20261112204144' + - '@atproto/lex-resolver@0.0.0-spaces-alpha-20261112204144' + - '@atproto/lex-rpc@0.0.0-spaces-alpha-20261112204144' + - '@atproto/lex-schema@0.0.0-spaces-alpha-20261112204144' + - '@atproto/lexicon@0.0.0-spaces-alpha-20261112204144' + - '@atproto/oauth-client-node@0.0.0-spaces-alpha-20261112204144' + - '@atproto/oauth-client@0.0.0-spaces-alpha-20261112204144' + - '@atproto/oauth-provider-api@0.0.0-spaces-alpha-20261112204144' + - '@atproto/oauth-provider-ui@0.0.0-spaces-alpha-20261112204144' + - '@atproto/oauth-provider@0.0.0-spaces-alpha-20261112204144' + - '@atproto/oauth-resolver@0.0.0-spaces-alpha-20261112204144' + - '@atproto/oauth-scopes@0.0.0-spaces-alpha-20261112204144' + - '@atproto/oauth-types@0.0.0-spaces-alpha-20261112204144' + - '@atproto/ozone@0.0.0-spaces-alpha-20261112204144' + - '@atproto/pds@0.0.0-spaces-alpha-20261112204144' + - '@atproto/repo@0.0.0-spaces-alpha-20261112204144' + - '@atproto/space@0.0.0-spaces-alpha-20261112204144' + - '@atproto/star@0.0.0-spaces-alpha-20261112204144' + - '@atproto/sync@0.0.0-spaces-alpha-20261112204144' + - '@atproto/syntax@0.0.0-spaces-alpha-20261112204144' + - '@atproto/ws-client@0.0.0-spaces-alpha-20261112204144' + - '@atproto/xrpc-server@0.0.0-spaces-alpha-20261112204144' + - '@atproto/xrpc@0.0.0-spaces-alpha-20261112204144' From f4f987b7078fac8b599813f845303ed932d4d31b Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 04:44:03 +0000 Subject: [PATCH 11/16] spaces: port engine, PDS and oauth-provider to the 2026-11-12 alpha Renamed and batched methods (authorizeSpaceSync, listWriters, notifyRepoUpdate, putMembers/removeMembers, checkAccess), token-based notification registration confirmed by the syncer, sequenced writer removals, HTTP message signature MACs, STAR media type and the renamed error codes. oauth-scopes: spaceType parameter and title declarations. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LZ7qcQNQoiA6a23woGC7tB --- packages/oauth-provider/src/index.ts | 2 + .../oauth-provider/src/permission-sets.ts | 11 +- packages/oauth-provider/src/provider.ts | 12 +- packages/oauth-provider/src/scopes.ts | 40 +- packages/oauth-provider/src/ui.ts | 14 +- .../test/permission-sets.test.ts | 6 +- .../oauth-provider/test/space-scopes.test.ts | 22 +- packages/pds/src/cli/commands/spaces.ts | 17 +- packages/pds/src/dashboard.html | 14 +- packages/pds/src/index.ts | 12 +- packages/pds/src/spaces.ts | 10 +- packages/pds/src/types.ts | 2 +- packages/pds/test/spaces.test.ts | 63 +- packages/spaces/src/attestation.ts | 4 +- packages/spaces/src/auth.ts | 6 +- packages/spaces/src/errors.ts | 19 +- packages/spaces/src/index.ts | 5 +- packages/spaces/src/mac.ts | 131 +- packages/spaces/src/policy.ts | 25 +- packages/spaces/src/routes.ts | 835 ++++++------ packages/spaces/src/schema.ts | 46 +- packages/spaces/src/space-do.ts | 625 ++++++--- packages/spaces/src/tokens.ts | 19 +- packages/spaces/src/types.ts | 20 +- packages/spaces/test/routes.test.ts | 1197 +++++++++-------- packages/spaces/test/space-do.test.ts | 260 +++- 26 files changed, 2061 insertions(+), 1356 deletions(-) diff --git a/packages/oauth-provider/src/index.ts b/packages/oauth-provider/src/index.ts index 87a9d7f..0490f4d 100644 --- a/packages/oauth-provider/src/index.ts +++ b/packages/oauth-provider/src/index.ts @@ -93,11 +93,13 @@ export { parseScope, parseSpaceScope, permissionsFor, + allowsSpace, } from "./scopes.js"; export type { FinalizeSpaceScopesOptions, ParseScopeOptions, SpacePermissionType, + SpaceScopeCheck, } from "./scopes.js"; export type { SpaceScopeInfo } from "./ui.js"; diff --git a/packages/oauth-provider/src/permission-sets.ts b/packages/oauth-provider/src/permission-sets.ts index efd6c51..1f15e0f 100644 --- a/packages/oauth-provider/src/permission-sets.ts +++ b/packages/oauth-provider/src/permission-sets.ts @@ -44,8 +44,9 @@ const LEXICON_SCHEMA_COLLECTION = "com.atproto.lexicon.schema"; */ export type LexiconSpace = { readonly type: "space"; - readonly name: string; - readonly "name:lang"?: Readonly>; + /** Optional since the 2026-11-12 alpha; consumers fall back to the NSID. */ + readonly title?: string; + readonly "title:lang"?: Readonly>; readonly collections: readonly string[]; readonly description?: string; }; @@ -219,9 +220,11 @@ export function createAtcutePermissionSetResolver( // is already proof-verified above; this only guards the fields the // consent UI and grant-time collection defaulting rely on. const decl = main as Record; - if (typeof decl.name !== "string") { + // `title` is optional. A leftover pre-1112 `name` is ignored, as + // the reference ignores it: the consent screen shows the NSID. + if (decl.title !== undefined && typeof decl.title !== "string") { throw new Error( - `space type declaration is missing a name; nsid=${nsid}`, + `space type declaration has an invalid title; nsid=${nsid}`, ); } if ( diff --git a/packages/oauth-provider/src/provider.ts b/packages/oauth-provider/src/provider.ts index 52d1ef0..977e638 100644 --- a/packages/oauth-provider/src/provider.ts +++ b/packages/oauth-provider/src/provider.ts @@ -235,26 +235,26 @@ export class ATProtoOAuthProvider { const perm = parseSpaceScope(token); if (!perm) continue; const info: SpaceScopeInfo = { - type: perm.type, + type: perm.spaceType, authority: perm.authority, }; if ( - perm.type !== "*" && + perm.spaceType !== "*" && this.permissionSetResolver?.resolveSpaceDeclaration ) { try { const decl = await this.permissionSetResolver.resolveSpaceDeclaration( - perm.type as Parameters< + perm.spaceType as Parameters< NonNullable< PermissionSetResolver["resolveSpaceDeclaration"] > >[0], ); - if (decl?.name) { - info.name = decl.name; - } else { + if (!decl) { info.error = "Space type declaration was not found"; + } else if (decl.title) { + info.name = decl.title; } } catch (e) { info.error = diff --git a/packages/oauth-provider/src/scopes.ts b/packages/oauth-provider/src/scopes.ts index 49a25f9..ff85e75 100644 --- a/packages/oauth-provider/src/scopes.ts +++ b/packages/oauth-provider/src/scopes.ts @@ -300,11 +300,11 @@ export async function finalizeSpaceScopes( if ( !perm.hasCollections && - perm.type !== "*" && + perm.spaceType !== "*" && resolveSpaceCollections ) { try { - const collections = await resolveSpaceCollections(perm.type); + const collections = await resolveSpaceCollections(perm.spaceType); if (collections && collections.length > 0) { perm = perm.withDefaultCollections( collections as readonly ( @@ -335,3 +335,39 @@ export async function finalizeSpaceScopes( export function permissionsFor(scope: string): ScopePermissionsTransition { return new ScopePermissionsTransition(scope); } + +/** + * A space operation checked against `space:` grants, in one flat object: + * the space (`type`, `authority`, `skey`) and either an `action` (with a + * `collection` for writes) or a `manage` op. + */ +export type SpaceScopeCheck = { + type: string; + authority: string; + skey: string; +} & ( + | { action: "read" | "read_self"; collection?: never; manage?: never } + | { + action: "create" | "update" | "delete"; + collection: string; + manage?: never; + } + | { action?: never; collection?: never; manage: "create" | "update" | "delete" } +); + +/** + * Whether granted permissions allow a space operation. Since the + * 2026-11-12 alpha, `@atproto/oauth-scopes` takes the space and the + * operation as separate arguments; this keeps Cirrus's callers on one + * shape across alpha builds. + */ +export function allowsSpace( + permissions: ScopePermissionsTransition, + check: SpaceScopeCheck, +): boolean { + const { type, authority, skey, ...operation } = check; + return permissions.allowsSpace( + { spaceType: type, authority, skey } as never, + operation as never, + ); +} diff --git a/packages/oauth-provider/src/ui.ts b/packages/oauth-provider/src/ui.ts index 43d7d34..2736302 100644 --- a/packages/oauth-provider/src/ui.ts +++ b/packages/oauth-provider/src/ui.ts @@ -296,11 +296,11 @@ function describeSpaceScope( const out: string[] = []; const typeLabel = - p.type === "*" + p.spaceType === "*" ? "spaces of ANY type" : info?.name - ? `"${info.name}" spaces (${p.type})` - : `${p.type} spaces`; + ? `"${info.name}" spaces (${p.spaceType})` + : `${p.spaceType} spaces`; const authorityLabel = p.authority === "self" @@ -319,7 +319,7 @@ function describeSpaceScope( const skeySuffix = p.skey === "*" ? "" : ` (space "${p.skey}")`; let line = `${verb} private data in ${authorityLabel} ${typeLabel}${skeySuffix}`; - if (p.type === "*" || p.authority === "*") { + if (p.spaceType === "*" || p.authority === "*") { line = `⚠️ ${line}`; } out.push(line); @@ -333,7 +333,7 @@ function describeSpaceScope( if (info?.error) { out.push( - `⚠️ ${p.type} — could not resolve space type declaration: ${info.error}`, + `⚠️ ${p.spaceType} — could not resolve space type declaration: ${info.error}`, ); } @@ -371,7 +371,7 @@ function getScopeDescriptions( const spacePerms: SpacePermissionType[] = []; for (const s of set) { - // Space scopes may use the `space?type=...` form with no colon, so + // Space scopes may use the `space?spaceType=...` form with no colon, so // they get a dedicated parse ahead of the colon-keyed dispatch. const spacePerm = parseSpaceScope(s); if (spacePerm) { @@ -494,7 +494,7 @@ function getScopeDescriptions( } for (const p of spacePerms) { const info = spaces?.find( - (s) => s.type === p.type && s.authority === p.authority, + (s) => s.type === p.spaceType && s.authority === p.authority, ); out.push(...describeSpaceScope(p, info)); } diff --git a/packages/oauth-provider/test/permission-sets.test.ts b/packages/oauth-provider/test/permission-sets.test.ts index f6b188f..57e2a8d 100644 --- a/packages/oauth-provider/test/permission-sets.test.ts +++ b/packages/oauth-provider/test/permission-sets.test.ts @@ -33,7 +33,7 @@ const SPACE_RECORD = { defs: { main: { type: "space", - name: "Cirrus Check", + title: "Cirrus Check", collections: ["earth.cirrus.check.item", "earth.cirrus.check.result"], }, }, @@ -164,7 +164,7 @@ describe("resolveSpaceDeclaration", () => { expect(decl).not.toBeNull(); expect(decl?.type).toBe("space"); - expect(decl?.name).toBe("Cirrus Check"); + expect(decl?.title).toBe("Cirrus Check"); expect(decl?.collections).toEqual([ "earth.cirrus.check.item", "earth.cirrus.check.result", @@ -218,7 +218,7 @@ describe("resolveSpaceDeclaration", () => { defs: { main: { type: "space", - name: "Broken", + title: "Broken", collections: ["not a valid nsid"], }, }, diff --git a/packages/oauth-provider/test/space-scopes.test.ts b/packages/oauth-provider/test/space-scopes.test.ts index b67597b..c8e3d9d 100644 --- a/packages/oauth-provider/test/space-scopes.test.ts +++ b/packages/oauth-provider/test/space-scopes.test.ts @@ -3,6 +3,7 @@ import { ScopeParseError, finalizeSpaceScopes, parseScope, + allowsSpace, parseSpaceScope, permissionsFor, } from "../src/scopes.js"; @@ -19,7 +20,7 @@ describe("parseScope with space scopes", () => { it("rejects the named-param space form by default too", () => { expect(() => - parseScope("atproto space?type=app.bsky.group"), + parseScope("atproto space?spaceType=app.bsky.group"), ).toThrow(/not enabled/); }); @@ -53,10 +54,11 @@ describe("parseScope with space scopes", () => { describe("parseSpaceScope", () => { it("parses positional and named-param forms", () => { - expect(parseSpaceScope("space:app.bsky.group")?.type).toBe( + expect(parseSpaceScope("space:app.bsky.group")?.spaceType).toBe( "app.bsky.group", ); - expect(parseSpaceScope("space?type=app.bsky.group")?.type).toBe( + // The named parameter is `spaceType` since the 2026-11-12 alpha. + expect(parseSpaceScope("space?spaceType=app.bsky.group")?.spaceType).toBe( "app.bsky.group", ); }); @@ -138,7 +140,7 @@ describe("space permission checks", () => { ); const perms = permissionsFor(stored); expect( - perms.allowsSpace({ + allowsSpace(perms, { type: "app.bsky.group", authority: did, skey: "3kbcq3p7ad400", @@ -146,7 +148,7 @@ describe("space permission checks", () => { }), ).toBe(true); expect( - perms.allowsSpace({ + allowsSpace(perms, { type: "app.bsky.group", authority: did, skey: "3kbcq3p7ad400", @@ -155,7 +157,7 @@ describe("space permission checks", () => { }), ).toBe(true); expect( - perms.allowsSpace({ + allowsSpace(perms, { type: "app.bsky.group", authority: did, skey: "3kbcq3p7ad400", @@ -164,7 +166,7 @@ describe("space permission checks", () => { }), ).toBe(false); expect( - perms.allowsSpace({ + allowsSpace(perms, { type: "app.bsky.group", authority: "did:plc:someoneelse", skey: "3kbcq3p7ad400", @@ -176,7 +178,7 @@ describe("space permission checks", () => { it("transition:generic grants nothing on spaces", () => { const perms = permissionsFor("atproto transition:generic"); expect( - perms.allowsSpace({ + allowsSpace(perms, { type: "app.bsky.group", authority: "did:web:alice.test", skey: "*", @@ -193,7 +195,7 @@ describe("space permission checks", () => { ); const perms = permissionsFor(stored); expect( - perms.allowsSpace({ + allowsSpace(perms, { type: "app.bsky.group", authority: did, skey: "*", @@ -201,7 +203,7 @@ describe("space permission checks", () => { }), ).toBe(true); expect( - perms.allowsSpace({ + allowsSpace(perms, { type: "app.bsky.group", authority: did, skey: "*", diff --git a/packages/pds/src/cli/commands/spaces.ts b/packages/pds/src/cli/commands/spaces.ts index ca65c6d..8440fce 100644 --- a/packages/pds/src/cli/commands/spaces.ts +++ b/packages/pds/src/cli/commands/spaces.ts @@ -272,7 +272,8 @@ const createCommand = defineCommand({ }, "managing-app": { type: "string", - description: "managed: the managing app's service identifier", + description: + "managed: the managing app's did#serviceId reference (e.g. did:web:app.example#forum)", }, allow: { type: "string", @@ -330,7 +331,7 @@ const createCommand = defineCommand({ ); process.exit(1); } - const result = await xrpc<{ uri: string }>( + const result = await xrpc<{ space: string }>( ctx, "POST", "com.atproto.space.createSpace", @@ -342,7 +343,7 @@ const createCommand = defineCommand({ }, }, ); - console.log(pc.green("Created:"), result.uri); + console.log(pc.green("Created:"), result.space); }, }); @@ -402,12 +403,10 @@ const membersCommand = defineCommand({ }, async run({ args }) { const ctx = loadContext(Boolean(args.dev)); - await xrpc(ctx, "POST", "com.atproto.memberspace.putMember", { + await xrpc(ctx, "POST", "com.atproto.memberspace.putMembers", { body: { space: args.space, - did: args.did, - read: args.read, - write: args.write, + members: [{ did: args.did, read: args.read, write: args.write }], }, }); console.log( @@ -426,8 +425,8 @@ const membersCommand = defineCommand({ }, async run({ args }) { const ctx = loadContext(Boolean(args.dev)); - await xrpc(ctx, "POST", "com.atproto.memberspace.removeMember", { - body: { space: args.space, did: args.did }, + await xrpc(ctx, "POST", "com.atproto.memberspace.removeMembers", { + body: { space: args.space, dids: [args.did] }, }); console.log(pc.green("Removed:"), args.did); }, diff --git a/packages/pds/src/dashboard.html b/packages/pds/src/dashboard.html index bf3deba..ae285d5 100644 --- a/packages/pds/src/dashboard.html +++ b/packages/pds/src/dashboard.html @@ -877,14 +877,14 @@

    EVENTS

    const members = el("div", "space-members"); const input = el("input"); input.placeholder = "did:… to add/remove"; - const mkBtn = (label, nsid, extra = {}) => { + const mkBtn = (label, nsid, extra) => { const btn = el("button", null, label); btn.addEventListener("click", async () => { const did = input.value.trim(); if (!did) return; try { await xrpc("POST", nsid, { - body: { space: space.uri, did, ...extra }, + body: { space: space.uri, ...extra(did) }, }); input.value = ""; load(); @@ -896,13 +896,13 @@

    EVENTS

    }; members.append( input, - mkBtn("add member", "com.atproto.memberspace.putMember", { - read: true, - write: true, - }), + mkBtn("add member", "com.atproto.memberspace.putMembers", (did) => ({ + members: [{ did, read: true, write: true }], + })), mkBtn( "remove member", - "com.atproto.memberspace.removeMember", + "com.atproto.memberspace.removeMembers", + (did) => ({ dids: [did] }), ), ); // Only memberspace keeps a member list. diff --git a/packages/pds/src/index.ts b/packages/pds/src/index.ts index dd7fc42..dca57b1 100644 --- a/packages/pds/src/index.ts +++ b/packages/pds/src/index.ts @@ -91,9 +91,15 @@ app.use( origin: "*", allowMethods: ["GET", "POST", "PUT", "DELETE", "OPTIONS"], // Note: No allowHeaders; using "*" wildcard doesn't cover Authorization, so let Hono reflect the requested headers instead - // atproto-space-mac carries the MAC a browser syncer verifies space - // data with. - exposeHeaders: ["Content-Type", "atproto-space-mac"], + // A space MAC is an HTTP message signature over a header describing + // the commit or record; a browser syncer must read all three. + exposeHeaders: [ + "Content-Type", + "atproto-space-commit", + "atproto-space-record", + "signature-input", + "signature", + ], maxAge: 86400, }), ); diff --git a/packages/pds/src/spaces.ts b/packages/pds/src/spaces.ts index a2609af..4ef17c3 100644 --- a/packages/pds/src/spaces.ts +++ b/packages/pds/src/spaces.ts @@ -31,7 +31,7 @@ import type { SpaceStub, SpaceIndexStub, } from "@getcirrus/spaces"; -import { permissionsFor } from "@getcirrus/oauth-provider"; +import { allowsSpace, permissionsFor } from "@getcirrus/oauth-provider"; import { getProvider } from "./oauth.js"; import { verifyAccessToken, TokenExpiredError } from "./session.js"; import { InvalidRecordError, validator } from "./validation.js"; @@ -119,7 +119,7 @@ export async function promoteUploadedSpaceBlob( /** * Fallback app mounted when SPACES_ENABLED is set but the SPACES / * SPACES_INDEX Durable Object bindings are absent: every space and - * simplespace method answers 503 with a pointer at the fix, and + * memberspace method answers 503 with a pointer at the fix, and * everything else falls through. * * Nothing in this module may throw for a missing binding at module scope: @@ -218,8 +218,8 @@ export function createSpacesApp(deps: SpacesAppDeps): Hono { } /** - * Verify an inbound service-auth JWT from a foreign issuer (notifyWrite - * and notifySpaceDeleted): ES256K signature against the issuer's + * Verify an inbound service-auth JWT from a foreign issuer (notifyRepoUpdate + * and notifyCredentialsRevoked): ES256K signature against the issuer's * #atproto key, expiry, and the lxm method binding. Resolution failures * surface as auth errors, never 500s. */ @@ -299,7 +299,7 @@ export function createSpacesApp(deps: SpacesAppDeps): Hono { did: tokenData.sub, fullTrust: false, allowsSpace: (match: SpaceScopeMatch) => - perms.allowsSpace(match as never), + allowsSpace(perms, match as never), }; } diff --git a/packages/pds/src/types.ts b/packages/pds/src/types.ts index 2fc6f0c..9d187de 100644 --- a/packages/pds/src/types.ts +++ b/packages/pds/src/types.ts @@ -68,7 +68,7 @@ export interface PDSEnv { RELAYS?: string; /** * Atproto spaces (alpha). Unset or anything but "true" disables every - * space and simplespace route; they fall through to the proxy like any + * space and memberspace route; they fall through to the proxy like any * unknown method. */ SPACES_ENABLED?: string; diff --git a/packages/pds/test/spaces.test.ts b/packages/pds/test/spaces.test.ts index 23c6bdf..8dfeed3 100644 --- a/packages/pds/test/spaces.test.ts +++ b/packages/pds/test/spaces.test.ts @@ -1,13 +1,12 @@ import { describe, expect, it } from "vitest"; import { P256Keypair } from "@atproto/crypto"; import { - RECORD_MAC_TYPE, + RECORD_MAC_PROFILE, createSpaceSigHeaders, encapsulate, - formatWantMacHeader, - parseMacHeader, - serializeRepo, + formatMacRequest, verifyRecord, + writeRepoStar, } from "@atproto/space"; import { encode } from "@atproto/lex-cbor"; import { env, worker, runInDurableObject } from "./helpers"; @@ -45,7 +44,7 @@ async function createSpace(): Promise { policy: { $type: "com.atproto.memberspace.policy" }, }); expect(res.status).toBe(200); - return ((await res.json()) as { uri: string }).uri; + return ((await res.json()) as { space: string }).space; } describe("spaces integration", () => { @@ -206,8 +205,8 @@ describe("spaces integration", () => { const key = await P256Keypair.create(); const credentialRes = await post( - "/xrpc/com.atproto.space.getSpaceCredential", - { space, credentialKid: key.did(), delegationToken: token }, + "/xrpc/com.atproto.space.authorizeSpaceSync", + { space, credentialKey: key.did(), delegationToken: token }, { "Content-Type": "application/json" }, ); expect(credentialRes.status).toBe(200); @@ -215,15 +214,17 @@ describe("spaces integration", () => { credential: string; }; - const headers: Record = await createSpaceSigHeaders(key, { + const { headers: sigHeaders } = await createSpaceSigHeaders({ authorization: `Atproto-Space-Credential ${credential}`, audience: env.DID as `did:${string}:${string}`, + keypair: key, }); + const headers: Record = { ...sigHeaders }; const { keyShare, sharedSecret } = await encapsulate( `did:key:${env.SPACES_KEM_KEY_PUBLIC}`, ); - headers["atproto-space-want-mac"] = formatWantMacHeader( - RECORD_MAC_TYPE, + headers["accept-signature"] = formatMacRequest( + RECORD_MAC_PROFILE, keyShare, ); const read = await get( @@ -231,27 +232,28 @@ describe("spaces integration", () => { headers, ); expect(read.status).toBe(200); - // The MAC header must reach a browser app across origins. - expect(read.headers.get("Access-Control-Expose-Headers")).toMatch( - /atproto-space-mac/i, - ); + // The MAC headers must reach a browser app across origins. + const exposed = read.headers.get("Access-Control-Expose-Headers") ?? ""; + for (const header of [ + "atproto-space-record", + "signature-input", + "signature", + ]) { + expect(exposed.toLowerCase()).toContain(header); + } const record = (await read.json()) as { uri: string; cid: string; value: { text: string }; }; expect(record.value.text).toBe("note"); - const mac = parseMacHeader( - read.headers.get("atproto-space-mac") ?? undefined, - RECORD_MAC_TYPE, - ); - expect( - await verifyRecord(record as never, { - uri: record.uri, - sharedSecret, - mac, - }), - ).toBe(true); + // Throws unless the MAC verifies. + await verifyRecord(record as never, { + uri: record.uri as never, + keyShare, + sharedSecret, + headers: read.headers, + }); }); it("promotes blobs of an imported space repo when they are uploaded", async () => { @@ -276,7 +278,7 @@ describe("spaces integration", () => { const { LtHash } = await import("@atproto/space"); const data = new LtHash().add(`test.cirrus.file/f/${recordCid}`).digest(); const chunks: Uint8Array[] = []; - for await (const chunk of serializeRepo( + for await (const chunk of writeRepoStar( { ver: 1, repo: env.DID as never, @@ -299,7 +301,7 @@ describe("spaces integration", () => { new Request("http://pds.test/xrpc/com.atproto.space.importRepo", { method: "POST", headers: { - "Content-Type": "application/octet-stream", + "Content-Type": "application/vnd.dasl.star", Authorization: `Bearer ${env.AUTH_TOKEN}`, }, body: archive, @@ -345,9 +347,10 @@ describe("spaces integration", () => { }); expect(res.status).toBe(200); const { spaces } = (await res.json()) as { - spaces: Array<{ uri: string }>; + spaces: Array<{ space: string }>; }; - expect(spaces.map((s) => s.uri)).toContain(space); + expect(space).toBeTruthy(); + expect(spaces.map((s) => s.space)).toContain(space); }); it("refuses app-password sessions on spaces but not the public repo", async () => { @@ -519,7 +522,7 @@ describe("spaces integration", () => { "ServiceUnavailable", ); const memberspace = await app.request( - "/xrpc/com.atproto.memberspace.putMember", + "/xrpc/com.atproto.memberspace.putMembers", { method: "POST" }, ); expect(memberspace.status).toBe(503); diff --git a/packages/spaces/src/attestation.ts b/packages/spaces/src/attestation.ts index 36a4ae0..6915ba9 100644 --- a/packages/spaces/src/attestation.ts +++ b/packages/spaces/src/attestation.ts @@ -13,7 +13,7 @@ */ import { createLocalJWKSet, jwtVerify } from "jose"; -import { SPACE_TOKEN_TYPES, parseSpaceToken } from "@atproto/space"; +import { CLIENT_ATTESTATION_TYP, parseSpaceToken } from "@atproto/space"; import { SpaceError } from "./errors.js"; import type { CheckReplay } from "./auth.js"; @@ -147,7 +147,7 @@ export async function verifyClientAttestation( issuer: clientId, subject: clientId, audience: opts.expectedAud, - typ: SPACE_TOKEN_TYPES.clientAttestation.typ, + typ: CLIENT_ATTESTATION_TYP, requiredClaims: ["jti", "exp"], clockTolerance: 5, }); diff --git a/packages/spaces/src/auth.ts b/packages/spaces/src/auth.ts index 4a70094..5399cf7 100644 --- a/packages/spaces/src/auth.ts +++ b/packages/spaces/src/auth.ts @@ -136,7 +136,7 @@ export async function verifySpaceCredentialAuth( ); } try { - await verifyCredentialSig(opts.headers, payload.cnf!.kid); + await verifyCredentialSig(opts.headers, payload.cnf.kid); } catch (err) { if (err instanceof SpaceSignatureError) { throw new SpaceError("BadSpaceSignature", err.message); @@ -196,7 +196,9 @@ export async function verifyDelegationToken( "Delegation token subject does not match requested space", ); } - if (payload.aud !== spaceHostAud(space.authority)) { + if ( + payload.aud !== spaceHostAud(space.authority as `did:${string}:${string}`) + ) { throw new SpaceError( "InvalidDelegationToken", "Delegation token audience does not match the space authority", diff --git a/packages/spaces/src/errors.ts b/packages/spaces/src/errors.ts index 78b78b0..73ab602 100644 --- a/packages/spaces/src/errors.ts +++ b/packages/spaces/src/errors.ts @@ -19,21 +19,25 @@ export const SPACE_ERROR_CODES = [ "RecordNotFound", "RecordAlreadyExists", "BlobNotFound", - "UserNotAuthorized", "AppNotAuthorized", "NotAuthorized", + "AccountNotAuthorized", "InvalidDelegationToken", "InvalidClientAttestation", "InvalidCredential", - "NotSpaceOwner", "PolicyMismatch", "UnsupportedPolicy", "ServiceNotResolvable", - "MalformedCursor", + "InvalidCursor", "InvalidSpaceUri", "InvalidRequest", "FutureRev", - "BadSpaceMac", + "InvalidSpaceMac", + "InvalidRepoFile", + "RepoMismatch", + "InvalidSpaceMeta", + "RegistrationNotConfirmed", + "UpstreamFailure", // Space credential authentication failures, named as the reference // names them (all 401). "MissingJwt", @@ -64,11 +68,12 @@ const ERROR_STATUS: Partial> = { BlobNotFound: 404, RecordAlreadyExists: 409, SpaceAlreadyExists: 409, - UserNotAuthorized: 403, AppNotAuthorized: 403, - NotAuthorized: 403, - NotSpaceOwner: 403, + // NotAuthorized is the management methods' "not the space authority", + // a 400 as the reference answers it. + AccountNotAuthorized: 403, Forbidden: 403, + UpstreamFailure: 502, InvalidClientAttestation: 401, MissingJwt: 401, BadJwt: 401, diff --git a/packages/spaces/src/index.ts b/packages/spaces/src/index.ts index ad9ad02..ec7fa7e 100644 --- a/packages/spaces/src/index.ts +++ b/packages/spaces/src/index.ts @@ -58,8 +58,8 @@ export type { CheckReplay, CheckRevoked, GetSigningKey } from "./auth.js"; export { verifyClientAttestation } from "./attestation.js"; export { - MAC_HEADER, - WANT_MAC_HEADER, + MAC_REQUEST_HEADER, + macExposedHeaders, buildCommit, bytesToJson, commitToJson, @@ -82,7 +82,6 @@ export { SPACE_SCHEMA_VERSION, OPLOG_RETENTION_DAYS, OPLOG_RETENTION_OPS, - NOTIFY_REGISTRATION_DAYS, } from "./schema.js"; export { createServiceJwt } from "./service-jwt.js"; diff --git a/packages/spaces/src/mac.ts b/packages/spaces/src/mac.ts index 8ccefea..d14964c 100644 --- a/packages/spaces/src/mac.ts +++ b/packages/spaces/src/mac.ts @@ -2,39 +2,51 @@ * Commits and MACs. * * A space repo commit carries no signature. A syncer authenticates what a - * repo host serves with a MAC instead: it sends an ephemeral P-256 key share - * in `Atproto-Space-Want-Mac`, both sides derive a shared secret by ECDH - * against the account's `#atproto_kem` key, and the host returns an HMAC in - * `Atproto-Space-Mac`. A leaked response therefore proves nothing to a third - * party. The KEM key is the only secret here, and it lives with the Worker. + * repo host serves with a MAC instead: an HTTP message signature (RFC 9421) + * using `hmac-sha256`, keyed by a per-request secret both sides derive with + * HPKE secret export against the account's `#atproto_kem` key. The syncer + * asks with `Accept-Signature`, naming its ephemeral key and a profile tag; + * the host answers with a header describing the commit or record + * (`Atproto-Space-Commit` / `Atproto-Space-Record`) and a MAC covering it. + * A leaked response proves nothing to a third party. The KEM key is the only + * secret here, and it lives with the Worker. */ import { - COMMIT_MAC_TYPE, - MAC_HEADER as UPSTREAM_MAC_HEADER, - RECORD_MAC_TYPE, + COMMIT_MAC_PROFILE, + MAC_COVERED_HEADER, + RECORD_MAC_PROFILE, RepoCommit, + SpaceKemError, SpaceMacError, - WANT_MAC_HEADER as UPSTREAM_WANT_MAC_HEADER, - computeCommitMac, - computeRecordMac, + createCommitMacHeaders, + createRecordMacHeaders, decapsulate, - formatMacHeader, - parseWantMacHeader, + parseMacRequest, } from "@atproto/space"; -import type { Commit, MacType } from "@atproto/space"; +import type { CreateMacParams, MacProfile } from "@atproto/space"; import { P256Keypair } from "@atproto/crypto"; import { parseCid, toBase64 } from "@atproto/lex-data"; import { SpaceError } from "./errors.js"; import type { RepoState } from "./types.js"; -export { COMMIT_MAC_TYPE, RECORD_MAC_TYPE }; -export type { MacType }; +export { COMMIT_MAC_PROFILE, RECORD_MAC_PROFILE }; +export type { MacProfile }; + +/** The MAC profiles, as plain strings for the public API. */ +export type SpaceMacProfile = "atproto-space-commit" | "atproto-space-record"; /** The request header a syncer asks for a MAC with. */ -export const WANT_MAC_HEADER: string = UPSTREAM_WANT_MAC_HEADER; -/** The response header carrying the MAC. */ -export const MAC_HEADER: string = UPSTREAM_MAC_HEADER; +export const MAC_REQUEST_HEADER = "accept-signature"; + +/** The response headers a browser syncer must read to check a MAC. */ +export function macExposedHeaders(profile: SpaceMacProfile): string[] { + return [ + MAC_COVERED_HEADER[profile as MacProfile], + "signature-input", + "signature", + ]; +} /** A space repo commit (`com.atproto.space.defs#commit`). */ export interface SpaceCommit { @@ -56,7 +68,7 @@ export function buildCommit(params: { return RepoCommit.fromState(params.state.setHash).toCommit({ space: params.spaceUri as never, repo: params.repo as never, - rev: params.state.rev, + rev: params.state.rev as never, }); } @@ -111,29 +123,39 @@ export async function kemDidKey(privateKeyHex: string): Promise { return (await importKemKeypair(privateKeyHex)).did(); } -export interface MacRequest { - /** The `Atproto-Space-Want-Mac` request header, if any. */ - wantMac: string | undefined; +export interface MacRequestInput { + /** The `Accept-Signature` request header, if any. */ + acceptSignature: string | undefined; /** Whether the request was authorised by a space credential. */ credential: boolean; - type: MacType; + profile: MacProfile; getKemKeypair: () => Promise; } +/** What a MAC is computed with, once requested and decapsulated. */ +export type MacParams = CreateMacParams; + /** - * The shared secret for a response's MAC. A space credential must ask for - * one; an account reading its own data gets one only if it asks. Returns - * undefined when no MAC is owed. + * The MAC owed by a read that returns a commit or record. A space + * credential must ask for one with the profile's tag; an account reading its + * own data gets one only if it asks. Requests with other tags are ignored. + * Returns undefined when no MAC is owed. */ -export async function macSecret( - req: MacRequest, -): Promise { - if (req.wantMac === undefined && !req.credential) return undefined; - let keyShare: string; +export async function macRequest( + req: MacRequestInput, +): Promise { + let request; try { - keyShare = parseWantMacHeader(req.wantMac, req.type); + request = parseMacRequest(req.acceptSignature, req.profile); } catch (err) { - throw badMac(err); + throw invalidMac(err); + } + if (!request) { + if (!req.credential) return undefined; + throw new SpaceError( + "InvalidSpaceMac", + `A MAC must be requested with tag "${req.profile}"`, + ); } const keypair = await req.getKemKeypair(); if (!keypair) { @@ -143,44 +165,37 @@ export async function macSecret( ); } try { - return decapsulate(keypair, keyShare); + return { ...request, sharedSecret: decapsulate(keypair, request.keyShare) }; } catch (err) { - throw badMac(err); + throw invalidMac(err); } } -function badMac(err: unknown): SpaceError { - if (err instanceof SpaceMacError) { - return new SpaceError("BadSpaceMac", err.message); +function invalidMac(err: unknown): SpaceError { + if (err instanceof SpaceMacError || err instanceof SpaceKemError) { + return new SpaceError("InvalidSpaceMac", err.message); } - return new SpaceError("BadSpaceMac", "Invalid Atproto-Space-Want-Mac header"); + return new SpaceError("InvalidSpaceMac", "Invalid Accept-Signature header"); } -/** The `Atproto-Space-Mac` header for a commit, when a MAC is owed. */ +/** The MAC response headers for a commit, when one is owed. */ export function commitMacHeaders( - secret: Uint8Array | undefined, + mac: MacParams | undefined, commit: SpaceCommit, ): Record { - if (!secret) return {}; - return { - [MAC_HEADER]: formatMacHeader( - COMMIT_MAC_TYPE, - computeCommitMac(secret, commit as Commit), - ), - }; + if (!mac) return {}; + return createCommitMacHeaders( + commit as Parameters[0], + mac, + ).headers; } -/** The `Atproto-Space-Mac` header for a record, when a MAC is owed. */ +/** The MAC response headers for a record, when one is owed. */ export function recordMacHeaders( - secret: Uint8Array | undefined, + mac: MacParams | undefined, uri: string, cid: string, ): Record { - if (!secret) return {}; - return { - [MAC_HEADER]: formatMacHeader( - RECORD_MAC_TYPE, - computeRecordMac(secret, uri, parseCid(cid)), - ), - }; + if (!mac) return {}; + return createRecordMacHeaders(uri as never, parseCid(cid), mac).headers; } diff --git a/packages/spaces/src/policy.ts b/packages/spaces/src/policy.ts index 0c076e0..2fe59dc 100644 --- a/packages/spaces/src/policy.ts +++ b/packages/spaces/src/policy.ts @@ -30,6 +30,16 @@ export const PUBLISHED_COLLECTIONS: readonly string[] = [ const isBool = (value: unknown): value is boolean => typeof value === "boolean"; +function isUri(value: unknown): value is string { + if (typeof value !== "string") return false; + try { + new URL(value); + return true; + } catch { + return false; + } +} + function optionalBool(input: Record, key: string): boolean { const value = input[key]; if (value === undefined) return false; @@ -52,12 +62,11 @@ export function normalizePolicy(input: unknown): SpacePolicy { const allowedApps = policy.allowedApps; if ( allowedApps !== undefined && - (!Array.isArray(allowedApps) || - allowedApps.some((app) => typeof app !== "string")) + (!Array.isArray(allowedApps) || allowedApps.some((app) => !isUri(app))) ) { throw new SpaceError( "InvalidRequest", - "allowedApps must be an array of client IDs", + "allowedApps must be an array of OAuth client ID URIs", ); } return { @@ -73,15 +82,19 @@ export function normalizePolicy(input: unknown): SpacePolicy { } case MANAGEDSPACE_POLICY: { const managingApp = policy.managingApp; - if (typeof managingApp !== "string" || !managingApp.startsWith("did:")) { + // A did#serviceId reference: the app's service entry, which a bare + // DID (an account's #atproto_pds) is not. + const [did, fragment, extra] = + typeof managingApp === "string" ? managingApp.split("#") : []; + if (!did?.startsWith("did:") || !fragment || extra !== undefined) { throw new SpaceError( "InvalidRequest", - "managingApp must be a DID with an optional service fragment", + `managingApp must be a did#serviceId reference, got: ${String(managingApp)}`, ); } return { $type: MANAGEDSPACE_POLICY, - managingApp, + managingApp: managingApp as string, publishPolicy: optionalBool(policy, "publishPolicy"), }; } diff --git a/packages/spaces/src/routes.ts b/packages/spaces/src/routes.ts index a3ddf66..90b0635 100644 --- a/packages/spaces/src/routes.ts +++ b/packages/spaces/src/routes.ts @@ -11,13 +11,14 @@ import { Hono } from "hono"; import type { Context } from "hono"; import { - createSpaceToken, + createSpaceCredential, isP256DidKey, + parseSpaceToken, readRepoStar, readSpaceMetaStar, - serializeRepo, - serializeSpaceMeta, spaceHostAud, + writeRepoStar, + writeSpaceMetaStar, } from "@atproto/space"; import type { P256Keypair } from "@atproto/crypto"; import { encode } from "@atproto/lex-cbor"; @@ -37,18 +38,19 @@ import { } from "./auth.js"; import { verifyClientAttestation } from "./attestation.js"; import { - COMMIT_MAC_TYPE, - MAC_HEADER, - RECORD_MAC_TYPE, - WANT_MAC_HEADER, + COMMIT_MAC_PROFILE, + MAC_REQUEST_HEADER, + RECORD_MAC_PROFILE, buildCommit, bytesToJson, commitMacHeaders, commitToJson, importKemKeypair, - macSecret, + macExposedHeaders, + macRequest, recordMacHeaders, - type MacType, + type MacParams, + type MacProfile, } from "./mac.js"; import { SpaceError, parseSpaceErrorCode, spaceErrorStatus } from "./errors.js"; import { @@ -63,6 +65,7 @@ import { } from "./policy.js"; import { prepareRecord, recordBytesToJson } from "./records.js"; import { + MAX_NOTIFY_TOKEN_LENGTH, MAX_REV_CLOCK_SKEW_MS, MAX_SPACE_RECORD_BYTES, NOTIFY_BACKOFF_BASE_MS, @@ -74,7 +77,12 @@ import { spaceBlobKey, spaceBlobPrefix, } from "./blob-keys.js"; -import { requireSpaceUri, spaceId, spaceRecordUri } from "./space-uri.js"; +import { + parseSpaceUri, + requireSpaceUri, + spaceId, + spaceRecordUri, +} from "./space-uri.js"; import type { SpaceRef } from "./space-uri.js"; import { isRetryableStatus } from "./space-do.js"; import type { SpaceDurableObject } from "./space-do.js"; @@ -86,6 +94,7 @@ import { PERSONALSPACE_POLICY, type ImportedRecord, type NotifyItem, + type NotifyRegistration, type PreparedSpaceWrite, type RepoCommitResult, type SpaceMember, @@ -93,18 +102,22 @@ import { type SpaceSigningKeypair, } from "./types.js"; -const NOTIFY_WRITE_LXM = "com.atproto.space.notifyWrite"; -const SPACE_DELETED_LXM = "com.atproto.space.notifySpaceDeleted"; -const CREDENTIAL_REVOKED_LXM = "com.atproto.space.notifyCredentialRevoked"; -const CHECK_USER_ACCESS_LXM = "com.atproto.managedspace.checkUserAccess"; -/** A managing app that doesn't answer within this window denies access. */ -const CHECK_USER_ACCESS_TIMEOUT_MS = 5000; -/** The queue key for this repo's pending write notification to a foreign authority. */ -const NOTIFY_WRITE_COALESCE_KEY = "notifyWrite:authority"; +const NOTIFY_REPO_UPDATE_LXM = "com.atproto.space.notifyRepoUpdate"; +const CREDENTIALS_REVOKED_LXM = "com.atproto.space.notifyCredentialsRevoked"; +const CONFIRM_REGISTRATION_LXM = "com.atproto.space.confirmRegistration"; +const CHECK_ACCESS_LXM = "com.atproto.managedspace.checkAccess"; +/** A managing app or syncer endpoint that doesn't answer in this window fails. */ +const UPSTREAM_TIMEOUT_MS = 10_000; +/** The queue key for this repo's pending update notification to a foreign authority. */ +const NOTIFY_REPO_UPDATE_COALESCE_KEY = "notifyRepoUpdate:authority"; /** Upper bound on archives accepted by importRepo / importSpaceMeta. */ const MAX_IMPORT_BYTES = 100 * 1024 * 1024; /** Revocations are held until any credential they name has expired. */ const REVOCATION_TTL_SEC = 3600 + 2 * 5; +/** The media type of STAR archives (repos and space meta). */ +const STAR_CONTENT_TYPE = "application/vnd.dasl.star"; +/** Batched member changes take at most this many entries. */ +const MAX_MEMBER_BATCH = 100; export type SpaceStub = DurableObjectStub; export type SpaceIndexStub = DurableObjectStub; @@ -290,24 +303,27 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { } /** - * The MAC secret owed by a read that returns a commit or record, with - * the response headers a browser syncer needs to read the MAC. + * The MAC owed by a read that returns a commit or record, with the + * response headers a browser syncer needs to read the MAC. */ - async function readMacSecret( + async function readMac( c: Context, auth: AuthedRead, - type: MacType, - ): Promise { - appendHeader(c, "Vary", WANT_MAC_HEADER); - const wantMac = c.req.header(WANT_MAC_HEADER); - if (wantMac === undefined && auth.kind !== "credential") return undefined; - appendHeader(c, "Access-Control-Expose-Headers", MAC_HEADER); - return await macSecret({ - wantMac, + profile: MacProfile, + ): Promise { + appendHeader(c, "Vary", "Accept-Signature"); + const mac = await macRequest({ + acceptSignature: c.req.header(MAC_REQUEST_HEADER), credential: auth.kind === "credential", - type, + profile, getKemKeypair, }); + if (mac) { + for (const header of macExposedHeaders(profile)) { + appendHeader(c, "Access-Control-Expose-Headers", header); + } + } + return mac; } function assertScope( @@ -350,10 +366,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { */ function assertOwner(ref: SpaceRef, session: SpaceSessionAuth): void { if (session.did !== ref.authority) { - throw new SpaceError( - "NotSpaceOwner", - "Only the space owner may manage the space", - ); + throw new SpaceError("NotAuthorized", "Not the space authority"); } assertSpaceHost(ref); } @@ -371,65 +384,77 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { } /** - * Whether a policy authorises a user to read or write. The authority - * always passes under every policy: it alone can reconfigure the space, - * so it must not be able to lock itself out. A managing app that errors - * or times out denies. + * Whether a policy authorises an account to read or write. `repo` is + * absent for a read with no delegation token, which a policy authorises + * only if it does not gate on the account. The authority always passes + * under every policy: it alone can reconfigure the space, so it must not + * be able to lock itself out. + * + * A managing app that can't be reached throws UpstreamFailure rather + * than denying: denying would read as a loss of access, withdrawing a + * syncer's registration and making a repo host drop its notification. */ - async function authorizeUser(params: { + async function authorizeRepo(params: { policy: SpacePolicy; ref: SpaceRef; - userDid: string; + repo: string | undefined; access: "read" | "write"; clientId?: string; stub: SpaceStub; }): Promise { - const { policy, ref, userDid, access, clientId, stub } = params; - if (userDid === ref.authority) return true; + const { policy, ref, repo, access, clientId, stub } = params; + if (repo === ref.authority) return true; switch (policy.$type) { case PERSONALSPACE_POLICY: return false; case MEMBERSPACE_POLICY: { - if (access === "read" ? policy.publicRead : policy.publicWrite) { - return true; - } - const member = await stub.rpcGetMember(userDid); - if (!member) return false; - return access === "read" ? member.read : member.write; + if (access === "read" && policy.publicRead) return true; + if (!repo) return false; + const member = await stub.rpcGetMember(repo); + if (access === "read") return member?.read ?? false; + // A member without write access stays excluded even under + // publicWrite. + if (member) return member.write; + return policy.publicWrite; } - case MANAGEDSPACE_POLICY: { - const managingApp = policy.managingApp; - try { - const endpoint = await host.resolveServiceEndpoint(managingApp); - if (!endpoint) return false; - const token = await createServiceJwt( - { - iss: host.operatorDid, - aud: managingApp, - lxm: CHECK_USER_ACCESS_LXM, - }, - await host.getKeypair(), - ); - const url = new URL(`${endpoint}/xrpc/${CHECK_USER_ACCESS_LXM}`); - url.searchParams.set("space", ref.uri); - url.searchParams.set("user", userDid); - url.searchParams.set("access", access); - if (clientId && access === "read") { - url.searchParams.set("clientId", clientId); - } - const res = await doFetch(url.toString(), { - headers: { Authorization: `Bearer ${token}` }, - signal: AbortSignal.timeout(CHECK_USER_ACCESS_TIMEOUT_MS), - }); - if (!res.ok) return false; - const body = (await res.json()) as { authorized?: unknown }; - return body.authorized === true; - } catch { - // Failing open would hand out credentials for the spaces that - // asked for the strictest gate. No decision caching in the alpha. - return false; - } + case MANAGEDSPACE_POLICY: + return (await checkAccess(policy.managingApp, ref, repo, clientId))[ + access + ]; + } + } + + /** Ask a managed space's managing app for an account's access. */ + async function checkAccess( + managingApp: string, + ref: SpaceRef, + repo: string | undefined, + clientId: string | undefined, + ): Promise<{ read: boolean; write: boolean }> { + try { + const endpoint = await host.resolveServiceEndpoint(managingApp); + if (!endpoint) throw new Error("could not resolve the managing app"); + const token = await createServiceJwt( + { iss: host.operatorDid, aud: managingApp, lxm: CHECK_ACCESS_LXM }, + await host.getKeypair(), + ); + const url = new URL(`${endpoint}/xrpc/${CHECK_ACCESS_LXM}`); + url.searchParams.set("space", ref.uri); + if (repo) url.searchParams.set("repo", repo); + if (clientId) url.searchParams.set("clientId", clientId); + const res = await doFetch(url.toString(), { + headers: { Authorization: `Bearer ${token}` }, + signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS), + }); + if (!res.ok) throw new Error(`checkAccess answered ${res.status}`); + const body = (await res.json()) as { read?: unknown; write?: unknown }; + if (typeof body.read !== "boolean" || typeof body.write !== "boolean") { + throw new Error("checkAccess answered without read and write"); } + return { read: body.read, write: body.write }; + } catch (err) { + console.warn(`managing app check for ${ref.uri} failed:`, err); + throw new SpaceError("UpstreamFailure", "Managing app did not answer"); } } @@ -495,99 +520,72 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { return missing; } - /** - * Fan a sequenced repo update out to the space's registered syncers. - * Reasonable-effort: a syncer that misses one notices the gap in - * prevSpaceRev and recovers through listRepos. - */ - async function fanOutWrite( - ref: SpaceRef, - stub: SpaceStub, - body: Record, - ): Promise { - const registrations = await stub.rpcGetActiveRegistrations(); - if (registrations.length === 0) return; - const items: NotifyItem[] = registrations.map((registration) => ({ - service: registration.service, - endpoint: registration.endpoint, - lxm: NOTIFY_WRITE_LXM, - body: { ...body, space: ref.uri }, - })); - await stub.rpcEnqueueNotify(items); - } - /** * After a commit: the authority sequences its own update into the writer - * set and fans it out; a repo host in a foreign space delivers its - * latest state to the authority, immediately, persisting a retryable - * failure for the DO's alarm to retry for up to 24 hours. Retries - * coalesce, so only the newest revision is ever pending. + * set, which queues it for registered syncers; a repo host in a foreign + * space delivers its latest state to the authority, immediately, + * persisting a retryable failure for the DO's alarm to retry for up to + * 24 hours. Retries coalesce, so only the newest revision is pending. */ async function postWrite( ref: SpaceRef, stub: SpaceStub, commit: RepoCommitResult, ): Promise { + if (ref.authority === host.operatorDid) { + await stub.rpcRecordWriter(host.operatorDid, commit.rev, commit.data); + return; + } const body = { space: ref.uri, repo: host.operatorDid, repoRev: commit.rev, data: bytesToJson(commit.data), }; - if (ref.authority === host.operatorDid) { - const sequence = await stub.rpcRecordWriter( - host.operatorDid, - commit.rev, - commit.data, - ); - // Own writes always advance in practice; guard anyway so a - // re-ordered background task never fans out stale state. - if (!sequence) return; - await fanOutWrite(ref, stub, { ...body, ...sequence }); - return; - } - - const endpoint = await host - .resolveServiceEndpoint(ref.authority) - .catch(() => null); + const aud = spaceHostAud(ref.authority as `did:${string}:${string}`); + const endpoint = await host.resolveServiceEndpoint(aud).catch(() => null); if (!endpoint) { - console.warn(`notifyWrite: no endpoint for ${ref.authority}`); + console.warn(`notifyRepoUpdate: no endpoint for ${ref.authority}`); return; } const retry: NotifyItem = { - service: ref.authority, + service: aud, endpoint, - lxm: NOTIFY_WRITE_LXM, + lxm: NOTIFY_REPO_UPDATE_LXM, body, - coalesceKey: NOTIFY_WRITE_COALESCE_KEY, + coalesceKey: NOTIFY_REPO_UPDATE_COALESCE_KEY, deadline: Date.now() + NOTIFY_WRITE_RETRY_MS, + policy: "repo", + auth: "service", }; try { const token = await createServiceJwt( - { iss: host.operatorDid, aud: ref.authority, lxm: NOTIFY_WRITE_LXM }, + { iss: host.operatorDid, aud, lxm: NOTIFY_REPO_UPDATE_LXM }, await host.getKeypair(), ); - const res = await doFetch(`${endpoint}/xrpc/${NOTIFY_WRITE_LXM}`, { + const res = await doFetch(`${endpoint}/xrpc/${NOTIFY_REPO_UPDATE_LXM}`, { method: "POST", headers: { "Content-Type": "application/json", Authorization: `Bearer ${token}`, }, body: JSON.stringify(body), - signal: AbortSignal.timeout(10_000), + signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS), }); if (res.ok || !isRetryableStatus(res.status)) { if (!res.ok) { console.warn( - `notifyWrite to ${ref.authority} refused: ${res.status}; not retrying`, + `notifyRepoUpdate to ${ref.authority} refused: ${res.status}; not retrying`, ); } - await stub.rpcClearNotify(NOTIFY_WRITE_COALESCE_KEY); + await stub.rpcClearNotify(NOTIFY_REPO_UPDATE_COALESCE_KEY); return; } - console.warn(`notifyWrite to ${ref.authority} failed: ${res.status}`); + console.warn( + `notifyRepoUpdate to ${ref.authority} failed: ${res.status}`, + ); } catch (err) { - console.warn(`notifyWrite to ${ref.authority} errored:`, err); + console.warn(`notifyRepoUpdate to ${ref.authority} errored:`, err); } await stub.rpcEnqueueNotify([retry], { delayMs: NOTIFY_BACKOFF_BASE_MS }); } @@ -1022,12 +1020,12 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { await archive[Symbol.asyncDispose](); } } catch (err) { - throw invalidArchive(err); + throw invalidArchive(err, "InvalidRepoFile"); } if (repo !== host.operatorDid || repo !== session.did) { throw new SpaceError( - "InvalidRequest", + "RepoMismatch", "Repo does not match the authenticated account", ); } @@ -1080,7 +1078,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { const rkey = c.req.query("rkey"); requireString(collection, "collection"); requireString(rkey, "rkey"); - const secret = await readMacSecret(c, auth, RECORD_MAC_TYPE); + const mac = await readMac(c, auth, RECORD_MAC_PROFILE); const stub = host.getSpaceDO(ref.uri); await requireRepoExists(stub, ref); @@ -1095,7 +1093,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { return c.json( { uri, cid: record.cid, value: recordBytesToJson(record.bytes) }, 200, - recordMacHeaders(secret, uri, record.cid), + recordMacHeaders(mac, uri, record.cid), ); } catch (err) { return errorResponse(c, err); @@ -1109,7 +1107,6 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { if (auth instanceof Response) return auth; const collection = c.req.query("collection"); const limit = clampLimit(c.req.query("limit"), 50, 1000); - const reverse = c.req.query("reverse") === "true"; const excludeValues = c.req.query("excludeValues") === "true"; const after = parseRecordCursor(c.req.query("cursor")); @@ -1119,7 +1116,6 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { collection, limit, after, - reverse, excludeValues, }); const records = page.records.map((record) => ({ @@ -1147,7 +1143,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { const ref = requireSpaceUri(c.req.query("space")); const auth = await readAuth(c, ref, c.req.query("repo")); if (auth instanceof Response) return auth; - const secret = await readMacSecret(c, auth, COMMIT_MAC_TYPE); + const mac = await readMac(c, auth, COMMIT_MAC_PROFILE); const stub = host.getSpaceDO(ref.uri); await requireRepoExists(stub, ref); const state = await stub.rpcGetRepoState(); @@ -1165,7 +1161,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { return c.json( { commit: commitToJson(commit) }, 200, - commitMacHeaders(secret, commit), + commitMacHeaders(mac, commit), ); } catch (err) { return errorResponse(c, err); @@ -1181,7 +1177,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { const since = c.req.query("since"); const excludeValues = c.req.query("excludeValues") === "true"; const after = parseOpsCursor(c.req.query("cursor")); - const secret = await readMacSecret(c, auth, COMMIT_MAC_TYPE); + const mac = await readMac(c, auth, COMMIT_MAC_PROFILE); const stub = host.getSpaceDO(ref.uri); await requireRepoExists(stub, ref); @@ -1201,13 +1197,20 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { ? { value: recordBytesToJson(new Uint8Array(op.bytes)) } : {}), })); + // Never written: no commit to answer with. if (!page.head) { - const last = page.ops[page.ops.length - 1]; - return c.json({ - ops, - ...(last ? { cursor: `${last.rev}/${last.idx}` } : {}), - }); + throw new SpaceError( + "RepoNotFound", + `Could not find repo for space: ${ref.uri}`, + ); } + // The commit, with its MAC, is on every page. A full page carries a + // cursor, so the last page may be empty. + const last = page.ops[page.ops.length - 1]; + const cursor = + last && page.ops.length === limit + ? `${last.rev}/${last.idx}` + : undefined; const commit = buildCommit({ spaceUri: ref.uri, repo: host.operatorDid, @@ -1217,9 +1220,9 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { }, }); return c.json( - { ops, commit: commitToJson(commit) }, + { ops, commit: commitToJson(commit), ...(cursor ? { cursor } : {}) }, 200, - commitMacHeaders(secret, commit), + commitMacHeaders(mac, commit), ); } catch (err) { return errorResponse(c, err); @@ -1231,7 +1234,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { const ref = requireSpaceUri(c.req.query("space")); const auth = await readAuth(c, ref, c.req.query("repo")); if (auth instanceof Response) return auth; - const secret = await readMacSecret(c, auth, COMMIT_MAC_TYPE); + const mac = await readMac(c, auth, COMMIT_MAC_PROFILE); const stub = host.getSpaceDO(ref.uri); await requireRepoExists(stub, ref); @@ -1277,13 +1280,13 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { } } } - const star = serializeRepo( - commit as Parameters[0], + const star = writeRepoStar( + commit as Parameters[0], records(), ); return c.body(asyncIterableToStream(star), 200, { - "Content-Type": "application/octet-stream", - ...commitMacHeaders(secret, commit), + "Content-Type": STAR_CONTENT_TYPE, + ...commitMacHeaders(mac, commit), }); } catch (err) { return errorResponse(c, err); @@ -1296,12 +1299,11 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { const auth = await readAuth(c, ref, c.req.query("repo")); if (auth instanceof Response) return auth; const limit = clampLimit(c.req.query("limit"), 500, 1000); - const since = c.req.query("since"); const afterCid = c.req.query("cursor"); const stub = host.getSpaceDO(ref.uri); await requireRepoExists(stub, ref); - const page = await stub.rpcListBlobs({ since, limit, afterCid }); + const page = await stub.rpcListBlobs({ limit, afterCid }); const last = page.cids[page.cids.length - 1]; return c.json({ cids: page.cids, @@ -1379,44 +1381,57 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { // Space host endpoints (authority role) // --------------------------------------------------------------- - app.post("/xrpc/com.atproto.space.getSpaceCredential", async (c) => { + app.post("/xrpc/com.atproto.space.authorizeSpaceSync", async (c) => { try { const body = await c.req.json<{ space?: string; - credentialKid?: string; + credentialKey?: string; delegationToken?: string; clientAttestation?: string; + notify?: unknown; }>(); const ref = requireSpaceUri(body.space); - requireString(body.credentialKid, "credentialKid"); - if (!isP256DidKey(body.credentialKid!)) { + requireString(body.credentialKey, "credentialKey"); + if (!isP256DidKey(body.credentialKey!)) { throw new SpaceError( "InvalidRequest", - "credentialKid must be a P-256 did:key", + "credentialKey must be a P-256 did:key", ); } + const notify = + body.notify === undefined ? undefined : parseNotify(body.notify); + // Before anything touches the space DO: a space this host doesn't // govern must not get one created for it by a well-formed request. - assertSpaceHost(ref); + await assertActiveSpaceHost(ref); const stub = host.getSpaceDO(ref.uri); + const { meta, policy } = await stub.rpcGetAuthorityState(); + // The durable signal that a space is gone: a syncer that missed + // its deletion notice learns it here, the next time it + // reauthorises, whatever the request's authorisation. + if (meta?.deletedAt) { + throw new SpaceError("SpaceDeleted", `Space deleted: ${ref.uri}`); + } - // Absent when the request carries no delegation token, which only a - // space that does not gate on the user accepts. - let userDid: string | undefined; + // Absent when the request carries no delegation token, which only + // a space that does not gate on the account accepts. + let repo: string | undefined; if (body.delegationToken) { - ({ userDid } = await verifyDelegationToken(body.delegationToken, ref, { - getSigningKey: host.getSigningKey, - checkReplay: (kind, key, exp) => stub.rpcCheckReplay(kind, key, exp), - })); + ({ userDid: repo } = await verifyDelegationToken( + body.delegationToken, + ref, + { + getSigningKey: host.getSigningKey, + checkReplay: (kind, key, exp) => + stub.rpcCheckReplay(kind, key, exp), + }, + )); } - await assertActiveSpaceHost(ref); - const { meta, policy } = await stub.rpcGetAuthorityState(); - let clientId: string | undefined; if (body.clientAttestation) { clientId = await verifyClientAttestation(body.clientAttestation, { - expectedAud: spaceHostAud(ref.authority), + expectedAud: spaceHostAud(ref.authority as `did:${string}:${string}`), // Checked pre-verification inside, so a client the space could // never authorise never triggers network I/O. allowedClientIds: @@ -1428,55 +1443,68 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { }); } - // The durable signal that a space is gone: a syncer that missed - // notifySpaceDeleted learns it here, on its next renewal, with or - // without a delegation token. - if (meta?.deletedAt) { - throw new SpaceError("SpaceDeleted", `Space deleted: ${ref.uri}`); - } if (!meta || !policy) { throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}`); } - // The user goes first, and a user the policy refuses is answered as - // though the space does not exist, so that a refusal discloses - // nothing to someone without access to it. - const userAuthorized = userDid - ? await authorizeUser({ - policy, - ref, - userDid, - access: "read", - clientId, - stub, - }) - : isPublicRead(policy); - if (!userAuthorized) { - throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}`); + try { + // The account goes first, and one the policy refuses is answered + // as though the space does not exist, so that a refusal + // discloses nothing to someone without access to it. + const authorized = await authorizeRepo({ + policy, + ref, + repo, + access: "read", + clientId, + stub, + }); + if (!authorized) { + throw new SpaceError("SpaceNotFound", `Space not found: ${ref.uri}`); + } + if (!isAppAuthorized(policy, clientId)) { + throw new SpaceError( + "AppNotAuthorized", + "Application not authorized for this space", + ); + } + } catch (err) { + // A refusal withdraws the registration the request carries, so a + // syncer that has lost access stops being notified. A failure to + // decide, such as an unreachable managing app, is not a refusal. + if (notify && parseSpaceErrorCode(err)?.code !== "UpstreamFailure") { + await stub.rpcRemoveNotifyRegistration(notify); + } + throw err; } - if (!isAppAuthorized(policy, clientId)) { - throw new SpaceError( - "AppNotAuthorized", - "Application not authorized for this space", - ); + + if (notify && !(await stub.rpcGetNotifyRegistration(notify))) { + await confirmRegistration(ref, notify); } - const credential = await createSpaceToken( - "credential", - { - iss: host.operatorDid, - sub: ref.uri, - keyId: body.credentialKid as `did:${string}:${string}`, - }, - (await host.getKeypair()) as Parameters[2], - ); - return c.json({ credential }); + const credential = await createSpaceCredential({ + iss: host.operatorDid as `did:${string}:${string}`, + sub: ref.uri as never, + keyId: body.credentialKey as `did:${string}:${string}`, + keypair: (await host.getKeypair()) as never, + }); + + if (notify) { + // Renewed by each authorisation, to the credential's expiry, so a + // syncer that keeps reauthorising stays registered. + const { exp } = parseSpaceToken("credential", credential).payload; + await stub.rpcPutNotifyRegistration(notify, exp * 1000); + } + // Read after registering, so any update past this revision is + // notified. + const spaceRev = await stub.rpcGetSpaceRev(); + return c.json({ credential, ...(spaceRev ? { spaceRev } : {}) }); } catch (err) { return errorResponse(c, err); } }); - app.get("/xrpc/com.atproto.space.listRepos", async (c) => { + app.get("/xrpc/com.atproto.space.listWriters", async (c) => { try { const ref = requireSpaceUri(c.req.query("space")); await credentialAuth(c, ref); @@ -1490,14 +1518,22 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { }); const last = writers[writers.length - 1]; return c.json({ - repos: writers.map((writer) => ({ - did: writer.did, - repoRev: writer.repoRev, - data: bytesToJson(new Uint8Array(writer.data)), - spaceRev: writer.spaceRev, - })), - // As with sync.listRepos, nonempty pages carry a cursor and - // empty pages omit it. + repos: writers.map((writer) => + writer.removed + ? { + $type: "com.atproto.space.defs#repoRemoved", + repo: writer.did, + spaceRev: writer.spaceRev, + } + : { + $type: "com.atproto.space.defs#repoWrite", + repo: writer.did, + repoRev: writer.repoRev, + data: bytesToJson(new Uint8Array(writer.data)), + spaceRev: writer.spaceRev, + }, + ), + // Nonempty pages carry a cursor and empty pages omit it. ...(last ? { cursor: last.spaceRev } : {}), }); } catch (err) { @@ -1505,46 +1541,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { } }); - app.post("/xrpc/com.atproto.space.registerNotify", async (c) => { - try { - const body = await c.req.json<{ space?: string; service?: string }>(); - const ref = requireSpaceUri(body.space); - requireString(body.service, "service"); - await credentialAuth(c, ref); - assertSpaceHost(ref); - // Resolve now and store both, so fan-out never resolves DIDs. - const endpoint = await host.resolveServiceEndpoint(body.service!); - if (!endpoint) { - throw new SpaceError( - "ServiceNotResolvable", - `Could not resolve a service endpoint for ${body.service}`, - ); - } - const stub = host.getSpaceDO(ref.uri); - const result = await stub.rpcRegisterNotify(body.service!, endpoint); - return c.json({ expiresAt: result.expiresAt }); - } catch (err) { - return errorResponse(c, err); - } - }); - - app.post("/xrpc/com.atproto.space.unregisterNotify", async (c) => { - try { - const body = await c.req.json<{ space?: string; service?: string }>(); - const ref = requireSpaceUri(body.space); - requireString(body.service, "service"); - await credentialAuth(c, ref); - assertSpaceHost(ref); - // No endpoint resolution: a subscriber whose DID doc changed must - // still be able to withdraw. Idempotent. - await host.getSpaceDO(ref.uri).rpcUnregisterNotify(body.service!); - return c.json({}); - } catch (err) { - return errorResponse(c, err); - } - }); - - app.post("/xrpc/com.atproto.space.notifyWrite", async (c) => { + app.post("/xrpc/com.atproto.space.notifyRepoUpdate", async (c) => { try { const body = await c.req.json<{ space?: string; @@ -1559,23 +1556,24 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { throw new SpaceError("InvalidRequest", "Missing data bytes"); } - const serviceAuth = await requireServiceAuth(c, NOTIFY_WRITE_LXM); + const serviceAuth = await requireServiceAuth(c, NOTIFY_REPO_UPDATE_LXM); if (serviceAuth instanceof Response) return serviceAuth; // iss is the signer, so requiring it to match keeps a PDS from // notifying on another account's behalf. if (serviceAuth.iss !== body.repo) { throw new SpaceError( "Forbidden", - "notifyWrite iss does not match claimed writer", + "notifyRepoUpdate iss does not match the repo", ); } if ( serviceAuth.aud !== ref.authority && - serviceAuth.aud !== spaceHostAud(ref.authority) + serviceAuth.aud !== + spaceHostAud(ref.authority as `did:${string}:${string}`) ) { throw new SpaceError( "Forbidden", - "notifyWrite aud does not match the space authority", + "notifyRepoUpdate aud does not match the space authority", ); } @@ -1592,95 +1590,38 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { const stub = host.getSpaceDO(ref.uri); const policy = await requirePolicy(stub, ref); - // The same user perimeter used when minting credentials. notifyWrite - // comes from a PDS rather than an app, so there is no attestation. - const authorized = await authorizeUser({ + // The same account perimeter used when minting credentials. The + // notification comes from a PDS rather than an app, so there is no + // attestation. An unreachable managing app is an UpstreamFailure, + // which the repo host retries. + const authorized = await authorizeRepo({ policy, ref, - userDid: body.repo!, + repo: body.repo!, access: "write", stub, }); if (!authorized) { throw new SpaceError( "Forbidden", - "notifyWrite writer is not authorized", + "Repo is not authorized to write to the space", ); } - - const data = fromBase64(body.data.$bytes); - const sequence = await stub.rpcRecordWriter( + // Sequenced, and queued for registered syncers, in one transaction. + // A delayed or replayed notification with an older rev changes + // nothing. + await stub.rpcRecordWriter( body.repo!, body.repoRev!, - data, + fromBase64(body.data.$bytes), ); - // A delayed or replayed notification carrying an older rev did not - // change the writer set; do not fan stale state out again. - if (sequence) { - await fanOutWrite(ref, stub, { - repo: body.repo!, - repoRev: body.repoRev!, - data: body.data, - ...sequence, - }); - } return c.json({}); } catch (err) { return errorResponse(c, err); } }); - app.post("/xrpc/com.atproto.space.notifySpaceDeleted", async (c) => { - try { - const body = await c.req.json<{ space?: string }>(); - const ref = requireSpaceUri(body.space); - const serviceAuth = await requireServiceAuth(c, SPACE_DELETED_LXM); - if (serviceAuth instanceof Response) return serviceAuth; - // Only the space's authority may tell us to drop our copy. - if (serviceAuth.iss !== ref.authority) { - throw new SpaceError( - "Forbidden", - "notifySpaceDeleted iss is not the space authority", - ); - } - // And only when the notification was addressed to us: without the - // audience check, an authority-signed token minted for a different - // service could be replayed here to tombstone our repo and delete - // its blobs. Registrations use service identifiers, so accept the - // bare DID or any of our own #fragment forms. - if (!isOwnAudience(serviceAuth.aud)) { - throw new SpaceError( - "Forbidden", - "notifySpaceDeleted aud does not match this service", - ); - } - if (ref.authority === host.operatorDid) { - // We are the authority; nothing to drop from elsewhere. - return c.json({}); - } - - const stub = host.getSpaceDO(ref.uri); - const meta = await stub.rpcGetMeta(); - if (meta && !meta.deletedAt) { - await stub.rpcDeleteSpace(); - await host.getIndexDO().rpcMarkDeleted(ref.uri); - if (host.blobs) { - waitUntil( - c, - deleteR2Prefix( - host.blobs, - spaceBlobPrefix(host.operatorDid, await spaceId(ref.uri)), - ), - ); - } - } - return c.json({}); - } catch (err) { - return errorResponse(c, err); - } - }); - - app.post("/xrpc/com.atproto.space.notifyCredentialRevoked", async (c) => { + app.post("/xrpc/com.atproto.space.notifyCredentialsRevoked", async (c) => { try { const body = await c.req.json<{ space?: string; @@ -1699,7 +1640,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { "credentials must be 1 to 100 credential jti strings", ); } - const serviceAuth = await requireServiceAuth(c, CREDENTIAL_REVOKED_LXM); + const serviceAuth = await requireServiceAuth(c, CREDENTIALS_REVOKED_LXM); if (serviceAuth instanceof Response) return serviceAuth; if (serviceAuth.iss !== ref.authority) { throw new SpaceError( @@ -1776,7 +1717,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { }); await index.rpcActivate(ref.uri); afterConfigCommit(c, ref, stub, commit); - return c.json({ uri: ref.uri }); + return c.json({ space: ref.uri }); } catch (err) { return errorResponse(c, err); } @@ -1824,22 +1765,11 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { await assertActiveSpaceHost(ref); const stub = host.getSpaceDO(ref.uri); - const { registrations } = await stub.rpcDeleteSpace(); + // Credential issuance stops with the tombstone, and every registered + // syncer, lapsed or not, is queued a deletion notice delivered + // reliably for 72 hours. Then reap the blob prefix. + await stub.rpcDeleteSpace(); await host.getIndexDO().rpcMarkDeleted(ref.uri); - // Credential issuance stopped with the tombstone. Tell every - // registered syncer to drop its copy, retrying until delivered or - // the registration expires, then reap the blob prefix. - if (registrations.length > 0) { - await stub.rpcEnqueueNotify( - registrations.map((registration) => ({ - service: registration.service, - endpoint: registration.endpoint, - lxm: SPACE_DELETED_LXM, - body: { space: ref.uri }, - deadline: Date.parse(registration.expiresAt), - })), - ); - } if (host.blobs) { waitUntil( c, @@ -1869,7 +1799,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { if (scopeError) return scopeError; assertOwner(ref, session); const policy = await requirePolicy(host.getSpaceDO(ref.uri), ref); - return c.json({ uri: ref.uri, policy }); + return c.json({ space: ref.uri, policy }); } catch (err) { return errorResponse(c, err); } @@ -1877,9 +1807,9 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { app.post("/xrpc/com.atproto.space.removeWriter", async (c) => { try { - const body = await c.req.json<{ space?: string; did?: string }>(); + const body = await c.req.json<{ space?: string; repo?: string }>(); const ref = requireSpaceUri(body.space); - requireDid(body.did, "did"); + requireDid(body.repo, "repo"); const session = await host.authenticate(c); if (session instanceof Response) return session; const scopeError = assertScope(c, session, { @@ -1891,7 +1821,8 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { if (scopeError) return scopeError; assertOwner(ref, session); await assertActiveSpaceHost(ref); - await host.getSpaceDO(ref.uri).rpcRemoveWriter(body.did!); + // Sequenced and announced to syncers as a repoRemoved. + await host.getSpaceDO(ref.uri).rpcRemoveWriter(body.repo!); return c.json({}); } catch (err) { return errorResponse(c, err); @@ -1912,7 +1843,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { if (scopeError) return scopeError; assertOwner(ref, session); const exported = await host.getSpaceDO(ref.uri).rpcExportMeta(); - const star = serializeSpaceMeta({ + const star = writeSpaceMetaStar({ space: ref.uri as never, policy: exported.policy as never, policyState: exported.members.map((member) => ({ @@ -1925,13 +1856,13 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { })), writers: exported.writers.map((writer) => ({ did: writer.did as never, - rev: writer.repoRev, + repoRev: writer.repoRev, data: new Uint8Array(writer.data), spaceRev: writer.spaceRev, })), }); return c.body(asyncIterableToStream(star), 200, { - "Content-Type": "application/octet-stream", + "Content-Type": STAR_CONTENT_TYPE, }); } catch (err) { return errorResponse(c, err); @@ -1947,7 +1878,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { try { archive = await readSpaceMetaStar([bytes]); } catch (err) { - throw invalidArchive(err); + throw invalidArchive(err, "InvalidSpaceMeta"); } const ref = requireSpaceUri(archive.space); // Importing both creates the space here and sets its configuration. @@ -1961,7 +1892,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { if (scopeError) return scopeError; } if (ref.authority !== session.did || ref.authority !== host.operatorDid) { - throw new SpaceError("NotSpaceOwner", "Not the space owner"); + throw new SpaceError("NotAuthorized", "Not the space authority"); } const policy = normalizePolicy(archive.policy); const members = parsePolicyState(policy, archive.policyState); @@ -1983,9 +1914,10 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { members, writers: archive.writers.map((writer) => ({ did: writer.did, - repoRev: writer.rev, + repoRev: writer.repoRev, data: writer.data, spaceRev: writer.spaceRev, + removed: false, })), }); await index.rpcActivate(ref.uri); @@ -2000,7 +1932,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { const session = await host.authenticate(c); if (session instanceof Response) return session; const type = c.req.query("spaceType") || undefined; - const authority = c.req.query("did") || undefined; + const authority = c.req.query("spaceDid") || undefined; // No one space to check against, so the filters are the target: // an unfiltered listing needs a wildcard grant. It lists only the // caller's own spaces, so read_self is the grant that fits. @@ -2012,16 +1944,35 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { }); if (scopeError) return scopeError; const limit = clampLimit(c.req.query("limit"), 50, 100); + const cursor = c.req.query("cursor") || undefined; + if (cursor && !parseSpaceUri(cursor)) { + throw new SpaceError("InvalidCursor", `Malformed cursor: ${cursor}`); + } const page = await host.getIndexDO().rpcList({ type, authority, state: "active", limit, - afterUri: c.req.query("cursor") || undefined, + afterUri: cursor, }); + // The caller's repo state in each space, and the space's revision + // where the caller is its authority. + const spaces = await Promise.all( + page.spaces.map(async (space) => { + const view = await host.getSpaceDO(space.uri).rpcGetSpaceView(); + return { + space: space.uri, + ...(view?.repoRev ? { repoRev: view.repoRev } : {}), + ...(view?.data + ? { data: bytesToJson(new Uint8Array(view.data)) } + : {}), + ...(view?.spaceRev ? { spaceRev: view.spaceRev } : {}), + }; + }), + ); const last = page.spaces[page.spaces.length - 1]; return c.json({ - spaces: page.spaces.map((space) => ({ uri: space.uri })), + spaces, ...(page.hasMore && last ? { cursor: last.uri } : {}), }); } catch (err) { @@ -2033,22 +1984,11 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { // memberspace (authority role, session auth) // --------------------------------------------------------------- - app.post("/xrpc/com.atproto.memberspace.putMember", async (c) => { + app.post("/xrpc/com.atproto.memberspace.putMembers", async (c) => { try { - const body = await c.req.json<{ - space?: string; - did?: string; - read?: unknown; - write?: unknown; - }>(); + const body = await c.req.json<{ space?: string; members?: unknown }>(); const ref = requireSpaceUri(body.space); - requireDid(body.did, "did"); - if (typeof body.read !== "boolean" || typeof body.write !== "boolean") { - throw new SpaceError( - "InvalidRequest", - "read and write must be booleans", - ); - } + const members = parseMemberBatch(body.members); const session = await host.authenticate(c); if (session instanceof Response) return session; const scopeError = assertScope(c, session, { @@ -2061,10 +2001,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { assertOwner(ref, session); await assertActiveSpaceHost(ref); const stub = host.getSpaceDO(ref.uri); - const commit = await stub.rpcPutMember(body.did!, { - read: body.read, - write: body.write, - }); + const commit = await stub.rpcPutMembers(members); afterConfigCommit(c, ref, stub, commit); return c.json({}); } catch (err) { @@ -2072,11 +2009,21 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { } }); - app.post("/xrpc/com.atproto.memberspace.removeMember", async (c) => { + app.post("/xrpc/com.atproto.memberspace.removeMembers", async (c) => { try { - const body = await c.req.json<{ space?: string; did?: string }>(); + const body = await c.req.json<{ space?: string; dids?: unknown }>(); const ref = requireSpaceUri(body.space); - requireDid(body.did, "did"); + const dids = body.dids; + if ( + !Array.isArray(dids) || + dids.length > MAX_MEMBER_BATCH || + dids.some((did) => typeof did !== "string" || !did.startsWith("did:")) + ) { + throw new SpaceError( + "InvalidRequest", + `dids must be an array of at most ${MAX_MEMBER_BATCH} DIDs`, + ); + } const session = await host.authenticate(c); if (session instanceof Response) return session; const scopeError = assertScope(c, session, { @@ -2089,7 +2036,7 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { assertOwner(ref, session); await assertActiveSpaceHost(ref); const stub = host.getSpaceDO(ref.uri); - const commit = await stub.rpcRemoveMember(body.did!); + const commit = await stub.rpcRemoveMembers(dids as string[]); afterConfigCommit(c, ref, stub, commit); return c.json({}); } catch (err) { @@ -2133,6 +2080,45 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { // Helpers that need the host // --------------------------------------------------------------- + /** + * Before registering a webhook, check it asked to be: the endpoint must + * recognise the token as one it issued for this space and echo back a + * random challenge. The endpoint is the requester's choice, so it is + * fetched as untrusted: https only, no redirects, bounded in time. + */ + async function confirmRegistration( + ref: SpaceRef, + notify: NotifyRegistration, + ): Promise { + const challenge = crypto.randomUUID(); + try { + const res = await doFetch( + `${notify.endpoint.replace(/\/$/, "")}/xrpc/${CONFIRM_REGISTRATION_LXM}`, + { + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + space: ref.uri, + token: notify.token, + challenge, + }), + redirect: "manual", + signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS), + }, + ); + if (res.ok) { + const body = (await res.json()) as { challenge?: unknown }; + if (body.challenge === challenge) return; + } + } catch (err) { + console.warn(`registration for ${ref.uri} not confirmed:`, err); + } + throw new SpaceError( + "RegistrationNotConfirmed", + "Notify endpoint did not confirm the registration", + ); + } + /** Service auth for inbound notifications; a Response on failure. */ async function requireServiceAuth( c: Context, @@ -2200,6 +2186,41 @@ function requireString(value: unknown, name: string): asserts value is string { } } +/** + * An authorizeSpaceSync `notify`: an https base URL the space host calls + * XRPC methods against, and the opaque token that authenticates them. + */ +function parseNotify(input: unknown): NotifyRegistration { + const notify = input as { endpoint?: unknown; token?: unknown } | null; + const endpoint = notify?.endpoint; + const token = notify?.token; + if (typeof endpoint !== "string" || typeof token !== "string") { + throw new SpaceError( + "InvalidRequest", + "notify requires an endpoint and a token", + ); + } + let url: URL; + try { + url = new URL(endpoint); + } catch { + throw new SpaceError("InvalidRequest", "notify endpoint must be a URL"); + } + if (url.protocol !== "https:" || url.username || url.password) { + throw new SpaceError( + "InvalidRequest", + "notify endpoint must be a plain https URL", + ); + } + if (token.length === 0 || token.length > MAX_NOTIFY_TOKEN_LENGTH) { + throw new SpaceError( + "InvalidRequest", + `notify token must be 1 to ${MAX_NOTIFY_TOKEN_LENGTH} characters`, + ); + } + return { endpoint, token }; +} + function requireDid(value: unknown, name: string): asserts value is string { requireString(value, name); if (!value.startsWith("did:")) { @@ -2223,7 +2244,7 @@ function parseRecordCursor( if (!cursor) return undefined; const slash = cursor.lastIndexOf("/"); if (slash <= 0 || slash === cursor.length - 1) { - throw new SpaceError("MalformedCursor", `Malformed cursor: ${cursor}`); + throw new SpaceError("InvalidCursor", `Malformed cursor: ${cursor}`); } return { collection: cursor.slice(0, slash), rkey: cursor.slice(slash + 1) }; } @@ -2235,7 +2256,7 @@ function parseOpsCursor( const slash = cursor.indexOf("/"); const idx = slash === -1 ? NaN : Number.parseInt(cursor.slice(slash + 1), 10); if (slash <= 0 || Number.isNaN(idx)) { - throw new SpaceError("MalformedCursor", `Malformed cursor: ${cursor}`); + throw new SpaceError("InvalidCursor", `Malformed cursor: ${cursor}`); } return { rev: cursor.slice(0, slash), idx }; } @@ -2267,16 +2288,54 @@ function parsePolicyState( }); } -/** A malformed archive in a request body is the caller's error. */ -function invalidArchive(err: unknown): unknown { +/** + * A malformed archive in a request body is the caller's error, reported + * under the error name the method declares for it. + */ +function invalidArchive( + err: unknown, + code: "InvalidRepoFile" | "InvalidSpaceMeta", +): unknown { if (parseSpaceErrorCode(err)) return err; return new SpaceError( - "InvalidRequest", + code, `Invalid archive: ${err instanceof Error ? err.message : String(err)}`, ); } +/** A putMembers batch: at most 100 `{did, read, write}` entries. */ +function parseMemberBatch(input: unknown): SpaceMember[] { + if (!Array.isArray(input) || input.length > MAX_MEMBER_BATCH) { + throw new SpaceError( + "InvalidRequest", + `members must be an array of at most ${MAX_MEMBER_BATCH} entries`, + ); + } + return input.map((entry, i) => { + const member = entry as { did?: unknown; read?: unknown; write?: unknown }; + if ( + typeof member?.did !== "string" || + !member.did.startsWith("did:") || + typeof member.read !== "boolean" || + typeof member.write !== "boolean" + ) { + throw new SpaceError( + "InvalidRequest", + `members[${i}] must be {did, read, write}`, + ); + } + return { did: member.did, read: member.read, write: member.write }; + }); +} + async function readBody(c: Context): Promise { + const contentType = c.req.header("Content-Type")?.split(";")[0]?.trim(); + if (contentType !== STAR_CONTENT_TYPE) { + throw new SpaceError( + "InvalidRequest", + `Content-Type must be ${STAR_CONTENT_TYPE}`, + ); + } const declared = Number.parseInt(c.req.header("Content-Length") ?? "", 10); if (declared > MAX_IMPORT_BYTES) { throw new SpaceError("InvalidRequest", "Archive is too large"); diff --git a/packages/spaces/src/schema.ts b/packages/spaces/src/schema.ts index da797ff..0d94977 100644 --- a/packages/spaces/src/schema.ts +++ b/packages/spaces/src/schema.ts @@ -15,8 +15,11 @@ * 2: baseline policies replace simplespace config; members carry * read/write access; writers carry space revisions; revoked * credentials; coalescing notification queue. + * 3: webhook registrations (endpoint + token) replace registerNotify; + * writers keep a removal marker; queue rows carry their retry policy + * and authentication. */ -export const SPACE_SCHEMA_VERSION = 2; +export const SPACE_SCHEMA_VERSION = 3; export const SPACE_DO_SCHEMA = ` -- One row. schema_version is checked on every open. @@ -81,24 +84,34 @@ export const SPACE_DO_SCHEMA = ` can_write INTEGER NOT NULL ); - -- The writer set, sequenced by space revision. + -- The writer set, sequenced by space revision. A removed writer keeps + -- its row, marked removed at the revision of its removal, so listWriters + -- can report the removal until it writes again. CREATE TABLE IF NOT EXISTS writer ( did TEXT PRIMARY KEY, repo_rev TEXT NOT NULL, data BLOB NOT NULL, - space_rev TEXT NOT NULL + space_rev TEXT NOT NULL, + removed_at INTEGER ); CREATE INDEX IF NOT EXISTS idx_writer_space_rev ON writer(space_rev); + -- Syncer webhook registrations, made through authorizeSpaceSync. Active + -- until the credential of their latest authorization expires + -- (expires_at, ms); expiry_notified marks a lapse already announced. CREATE TABLE IF NOT EXISTS notify_registration ( - service TEXT PRIMARY KEY, endpoint TEXT NOT NULL, - expires_at TEXT NOT NULL + token TEXT NOT NULL, + expires_at INTEGER NOT NULL, + expiry_notified INTEGER NOT NULL DEFAULT 0, + PRIMARY KEY (endpoint, token) ); -- Outbound notifications, both roles. A row with a coalesce_key is -- replaced by a newer one with the same key; deadline (ms) is when - -- retrying stops. + -- retrying stops. policy picks the retry schedule ('fanout' | 'repo' | + -- 'syncer'); auth is 'service' (a service JWT from the operator) or + -- 'none' (a syncer webhook, authenticated by the token in its body). CREATE TABLE IF NOT EXISTS notify_queue ( id INTEGER PRIMARY KEY AUTOINCREMENT, service TEXT NOT NULL, @@ -106,7 +119,9 @@ export const SPACE_DO_SCHEMA = ` attempts INTEGER NOT NULL DEFAULT 0, next_at INTEGER NOT NULL, deadline INTEGER, - coalesce_key TEXT UNIQUE + coalesce_key TEXT UNIQUE, + policy TEXT NOT NULL DEFAULT 'fanout', + auth TEXT NOT NULL DEFAULT 'service' ); CREATE INDEX IF NOT EXISTS idx_notify_queue_next ON notify_queue(next_at); @@ -129,8 +144,6 @@ export const SPACE_DO_SCHEMA = ` export const OPLOG_RETENTION_DAYS = 30; /** Retain at most this many oplog entries. */ export const OPLOG_RETENTION_OPS = 10_000; -/** Notify registrations expire after this many days. */ -export const NOTIFY_REGISTRATION_DAYS = 7; /** * Give up delivering a notification without its own deadline after this * many attempts: syncer fan-out is reasonable-effort, and a syncer that @@ -139,6 +152,21 @@ export const NOTIFY_REGISTRATION_DAYS = 7; export const NOTIFY_MAX_ATTEMPTS = 5; /** A repo host retries its write notification to the authority this long. */ export const NOTIFY_WRITE_RETRY_MS = 24 * 60 * 60 * 1000; +/** + * A syncer's deletion or expiry notice is retried after each of these + * delays in turn, repeating the last, for at least + * {@link SYNCER_NOTICE_RETRY_WINDOW_MS}. + */ +export const SYNCER_NOTICE_RETRY_DELAYS_MS = [ + 60_000, + 10 * 60_000, + 60 * 60_000, + 6 * 60 * 60_000, + 12 * 60 * 60_000, +]; +export const SYNCER_NOTICE_RETRY_WINDOW_MS = 72 * 60 * 60 * 1000; +/** The largest notify token a syncer may register. */ +export const MAX_NOTIFY_TOKEN_LENGTH = 512; /** Cap on the backoff between notification retries. */ export const NOTIFY_BACKOFF_MAX_MS = 60 * 60 * 1000; /** notifyWrite refuses repo revisions this far ahead of the clock. */ diff --git a/packages/spaces/src/space-do.ts b/packages/spaces/src/space-do.ts index f940130..0b5884d 100644 --- a/packages/spaces/src/space-do.ts +++ b/packages/spaces/src/space-do.ts @@ -37,18 +37,21 @@ import { NOTIFY_BACKOFF_BASE_MS, NOTIFY_BACKOFF_MAX_MS, NOTIFY_MAX_ATTEMPTS, - NOTIFY_REGISTRATION_DAYS, OPLOG_RETENTION_DAYS, OPLOG_RETENTION_OPS, SPACE_DO_SCHEMA, SPACE_SCHEMA_VERSION, + SYNCER_NOTICE_RETRY_DELAYS_MS, + SYNCER_NOTICE_RETRY_WINDOW_MS, } from "./schema.js"; +import { bytesToJson } from "./mac.js"; import { nextRev, tidCutoff } from "./tid.js"; import { createServiceJwt } from "./service-jwt.js"; import type { ApplyWritesResult, ImportedRecord, NotifyItem, + NotifyRegistration, OplogEntry, PreparedSpaceWrite, RepoCommitResult, @@ -75,6 +78,20 @@ interface QueueRow { attempts: number; next_at: number; deadline: number | null; + policy: "fanout" | "repo" | "syncer"; + auth: "service" | "none"; +} + +const NOTIFY_SPACE_UPDATE_LXM = "com.atproto.space.notifySpaceUpdate"; +const REPO_WRITE = "com.atproto.space.defs#repoWrite"; +const REPO_REMOVED = "com.atproto.space.defs#repoRemoved"; +const SPACE_DELETED = "com.atproto.space.notifySpaceUpdate#spaceDeleted"; +const REGISTRATION_EXPIRED = + "com.atproto.space.notifySpaceUpdate#registrationExpired"; + +/** 50-100% of a delay, so retries from many spaces don't align. */ +function jitter(delay: number): number { + return Math.floor(delay * (0.5 + Math.random() / 2)); } /** HTTP statuses worth retrying; anything else is a permanent refusal. */ @@ -627,6 +644,31 @@ export abstract class SpaceDurableObject< }; } + /** + * What listSpaces reports for this space: the operator's repo state in + * it and, for a space the operator is the authority of, its revision. + */ + async rpcGetSpaceView(): Promise<{ + repoRev?: string; + data?: Uint8Array; + spaceRev?: string; + } | null> { + await this.ensureOpen(); + const meta = this.readMeta(); + if (!meta || meta.deletedAt) return null; + const state = this.readRepoState(); + const spaceRev = meta.isAuthority ? this.currentSpaceRev() : null; + return { + ...(state + ? { + repoRev: state.rev, + data: RepoCommit.fromState(state.setHash).setHash.digest(), + } + : {}), + ...(spaceRev ? { spaceRev } : {}), + }; + } + async rpcGetRepoState(): Promise { await this.ensureOpen(); this.requireLiveMeta(); @@ -646,7 +688,7 @@ export abstract class SpaceDurableObject< after?: { rev: string; idx: number }; limit: number; excludeValues?: boolean; - }): Promise<{ ops: OplogEntry[]; head?: RepoState }> { + }): Promise<{ ops: OplogEntry[]; hasMore: boolean; head?: RepoState }> { await this.ensureOpen(); this.requireLiveMeta(); return this.ctx.storage.transactionSync(() => { @@ -685,9 +727,10 @@ export abstract class SpaceDurableObject< ? { bytes: new Uint8Array(row.live_bytes as ArrayBuffer) } : {}), })); - if (hasMore) return { ops }; + // The commit is returned on every page, read in the same + // transaction so it never races the page. const head = this.readRepoState(); - return { ops, ...(head ? { head } : {}) }; + return { ops, hasMore, ...(head ? { head } : {}) }; }); } @@ -936,39 +979,67 @@ export abstract class SpaceDurableObject< }); } - async rpcPutMember( - did: string, - access: { read: boolean; write: boolean }, + /** + * Add members or replace their access, in one commit. A DID listed twice + * takes its last entry. Revoking write access removes the member from + * the writer set, sequenced and announced like any removal. + */ + async rpcPutMembers( + members: SpaceMember[], ): Promise { await this.ensureOpen(); const { policy } = this.requirePolicy(); assertMemberspace(policy); - const writes = await this.prepareMemberRecordWrites(policy, did, access); - return this.ctx.storage.transactionSync(() => { - this.sql.exec( - `INSERT INTO member (did, can_read, can_write) VALUES (?, ?, ?) - ON CONFLICT (did) DO UPDATE SET can_read = excluded.can_read, can_write = excluded.can_write`, - did, - access.read ? 1 : 0, - access.write ? 1 : 0, + const byDid = new Map(members.map((m) => [m.did, m])); + const writes: PreparedSpaceWrite[] = []; + for (const member of byDid.values()) { + writes.push( + ...(await this.prepareMemberRecordWrites(policy, member.did, member)), ); - if (!access.write) { - this.sql.exec("DELETE FROM writer WHERE did = ?", did); + } + const commit = this.ctx.storage.transactionSync(() => { + for (const member of byDid.values()) { + this.sql.exec( + `INSERT INTO member (did, can_read, can_write) VALUES (?, ?, ?) + ON CONFLICT (did) DO UPDATE SET can_read = excluded.can_read, can_write = excluded.can_write`, + member.did, + member.read ? 1 : 0, + member.write ? 1 : 0, + ); + if (!member.write) this.removeWriterSync(member.did); } return this.applyWritesSync(writes); }); + await this.scheduleNextAlarm(); + return commit; } - async rpcRemoveMember(did: string): Promise { + /** + * Remove members, in one commit, and from the writer set. DIDs that are + * not members are ignored, leaving any writer set entry alone. + */ + async rpcRemoveMembers(dids: string[]): Promise { await this.ensureOpen(); const { policy } = this.requirePolicy(); assertMemberspace(policy); - const writes = await this.prepareMemberRecordWrites(policy, did); - return this.ctx.storage.transactionSync(() => { - this.sql.exec("DELETE FROM member WHERE did = ?", did); - this.sql.exec("DELETE FROM writer WHERE did = ?", did); + const members = [...new Set(dids)].filter( + (did) => + this.sql.exec("SELECT 1 FROM member WHERE did = ?", did).toArray() + .length > 0, + ); + const writes: PreparedSpaceWrite[] = []; + for (const did of members) { + writes.push(...(await this.prepareMemberRecordWrites(policy, did))); + } + const commit = this.ctx.storage.transactionSync(() => { + for (const did of members) { + this.sql.exec("DELETE FROM member WHERE did = ?", did); + this.removeWriterSync(did); + } return this.applyWritesSync(writes); }); + await this.scheduleNextAlarm(); + return commit; } async rpcGetMember(did: string): Promise { @@ -1017,11 +1088,27 @@ export abstract class SpaceDurableObject< }; } + /** The space's current revision: the latest in its writer set, removals included. */ + private currentSpaceRev(): string | null { + return ( + (this.sql.exec("SELECT MAX(space_rev) AS rev FROM writer").toArray()[0] + ?.rev as string | null) ?? null + ); + } + + async rpcGetSpaceRev(): Promise { + await this.ensureOpen(); + this.requirePolicy(); + return this.currentSpaceRev(); + } + /** - * Record a writer's latest (repoRev, data), from notifyWrite or own - * writes, and advance the space sequence. Monotonic per writer: a + * Record a writer's latest (repoRev, data), from notifyRepoUpdate or own + * writes, advance the space sequence, and queue the update for the + * registered syncers in the same transaction. Monotonic per writer: a * delayed or replayed notification with an older (or equal) rev changes - * nothing and returns null, so callers skip fan-out for stale state. + * nothing and returns null. A newer write from a removed writer re-adds + * it. */ async rpcRecordWriter( did: string, @@ -1029,26 +1116,64 @@ export abstract class SpaceDurableObject< data: Uint8Array, ): Promise { await this.ensureOpen(); - this.requirePolicy(); - return this.ctx.storage.transactionSync(() => { + const { meta } = this.requirePolicy(); + const sequence = this.ctx.storage.transactionSync(() => { const existing = this.sql .exec("SELECT repo_rev FROM writer WHERE did = ?", did) .toArray()[0]; if (existing && (existing.repo_rev as string) >= repoRev) return null; - const latest = this.sql - .exec("SELECT MAX(space_rev) AS rev FROM writer") - .toArray()[0]?.rev as string | null; - const spaceRev = nextRev(latest); + const prevSpaceRev = this.currentSpaceRev(); + const spaceRev = nextRev(prevSpaceRev); this.sql.exec( - `INSERT INTO writer (did, repo_rev, data, space_rev) VALUES (?, ?, ?, ?) - ON CONFLICT (did) DO UPDATE SET repo_rev = excluded.repo_rev, data = excluded.data, space_rev = excluded.space_rev`, + `INSERT INTO writer (did, repo_rev, data, space_rev, removed_at) VALUES (?, ?, ?, ?, NULL) + ON CONFLICT (did) DO UPDATE SET repo_rev = excluded.repo_rev, data = excluded.data, + space_rev = excluded.space_rev, removed_at = NULL`, did, repoRev, data, spaceRev, ); - return { spaceRev, ...(latest ? { prevSpaceRev: latest } : {}) }; + const sequence = { spaceRev, ...(prevSpaceRev ? { prevSpaceRev } : {}) }; + this.queueSpaceUpdate(meta.uri, { + $type: REPO_WRITE, + repo: did, + repoRev, + data: bytesToJson(data), + ...sequence, + }); + return sequence; }); + if (sequence) await this.scheduleNextAlarm(); + return sequence; + } + + /** + * Remove a repo from the writer set at a new space revision, keeping its + * row marked removed so listWriters reports the removal, and announce it. + * Returns false when the repo is not in the writer set. Must run in a + * transaction. + */ + private removeWriterSync(did: string): boolean { + const meta = this.readMeta(); + const row = this.sql + .exec("SELECT removed_at FROM writer WHERE did = ?", did) + .toArray()[0]; + if (!meta || !row || row.removed_at !== null) return false; + const prevSpaceRev = this.currentSpaceRev(); + const spaceRev = nextRev(prevSpaceRev); + this.sql.exec( + "UPDATE writer SET space_rev = ?, removed_at = ? WHERE did = ?", + spaceRev, + Date.now(), + did, + ); + this.queueSpaceUpdate(meta.uri, { + $type: REPO_REMOVED, + repo: did, + spaceRev, + ...(prevSpaceRev ? { prevSpaceRev } : {}), + }); + return true; } /** @@ -1058,10 +1183,21 @@ export abstract class SpaceDurableObject< async rpcRemoveWriter(did: string): Promise { await this.ensureOpen(); this.requirePolicy(); - this.sql.exec("DELETE FROM writer WHERE did = ?", did); + this.ctx.storage.transactionSync(() => this.removeWriterSync(did)); + await this.scheduleNextAlarm(); + } + + private readWriter(row: Record): SpaceWriter { + return { + did: row.did as string, + repoRev: row.repo_rev as string, + data: new Uint8Array(row.data as ArrayBuffer), + spaceRev: row.space_rev as string, + removed: row.removed_at !== null, + }; } - /** The writer set in ascending space revision, after `cursor`. */ + /** The writer set, removals included, in ascending space revision after `cursor`. */ async rpcListWriters(params: { limit: number; cursor?: string; @@ -1070,19 +1206,14 @@ export abstract class SpaceDurableObject< this.requirePolicy(); return this.sql .exec( - `SELECT did, repo_rev, data, space_rev FROM writer + `SELECT did, repo_rev, data, space_rev, removed_at FROM writer ${params.cursor ? "WHERE space_rev > ?" : ""} ORDER BY space_rev ASC LIMIT ?`, ...(params.cursor ? [params.cursor] : []), params.limit, ) .toArray() - .map((row) => ({ - did: row.did as string, - repoRev: row.repo_rev as string, - data: new Uint8Array(row.data as ArrayBuffer), - spaceRev: row.space_rev as string, - })); + .map((row) => this.readWriter(row)); } /** The space's host-side state, for migrating its authority's account. */ @@ -1093,15 +1224,14 @@ export abstract class SpaceDurableObject< }> { await this.ensureOpen(); const { policy } = this.requirePolicy(); + // Removed writers stay behind: the archive carries only the writer + // set itself. const writers = this.sql - .exec("SELECT did, repo_rev, data, space_rev FROM writer ORDER BY did") + .exec( + "SELECT did, repo_rev, data, space_rev, removed_at FROM writer WHERE removed_at IS NULL ORDER BY did", + ) .toArray() - .map((row) => ({ - did: row.did as string, - repoRev: row.repo_rev as string, - data: new Uint8Array(row.data as ArrayBuffer), - spaceRev: row.space_rev as string, - })); + .map((row) => this.readWriter(row)); return { policy, members: this.readMembers(), writers }; } @@ -1156,7 +1286,7 @@ export abstract class SpaceDurableObject< this.sql.exec("DELETE FROM writer"); for (const writer of params.writers) { this.sql.exec( - "INSERT INTO writer (did, repo_rev, data, space_rev) VALUES (?, ?, ?, ?)", + "INSERT INTO writer (did, repo_rev, data, space_rev, removed_at) VALUES (?, ?, ?, ?, NULL)", writer.did, writer.repoRev, writer.data, @@ -1166,60 +1296,118 @@ export abstract class SpaceDurableObject< }); } + async rpcGetNotifyRegistration( + registration: NotifyRegistration, + ): Promise<{ expiresAt: number } | null> { + await this.ensureOpen(); + const row = this.sql + .exec( + "SELECT expires_at FROM notify_registration WHERE endpoint = ? AND token = ?", + registration.endpoint, + registration.token, + ) + .toArray()[0]; + return row ? { expiresAt: row.expires_at as number } : null; + } + /** - * Register a syncing service for write notifications. The endpoint was - * resolved by the Worker at registration time so fan-out never resolves - * DIDs. Re-registration replaces the endpoint and extends the expiry. + * Register a syncer's webhook, or renew it, to the expiry of the + * credential it was authorised with. Renewal clears a lapse already + * announced, so the next lapse is announced too. */ - async rpcRegisterNotify( - service: string, - endpoint: string, - ): Promise<{ expiresAt: string }> { + async rpcPutNotifyRegistration( + registration: NotifyRegistration, + expiresAt: number, + ): Promise { await this.ensureOpen(); - this.requirePolicy(); - const expiresAt = new Date( - Date.now() + NOTIFY_REGISTRATION_DAYS * DAY_MS, - ).toISOString(); + const meta = this.readMeta(); + if (!meta) throw new SpaceError("SpaceNotFound", "Space not found"); + if (meta.deletedAt) { + throw new SpaceError("SpaceDeleted", "Space has been deleted"); + } this.sql.exec( - `INSERT INTO notify_registration (service, endpoint, expires_at) VALUES (?, ?, ?) - ON CONFLICT (service) DO UPDATE SET endpoint = excluded.endpoint, expires_at = excluded.expires_at`, - service, - endpoint, + `INSERT INTO notify_registration (endpoint, token, expires_at, expiry_notified) VALUES (?, ?, ?, 0) + ON CONFLICT (endpoint, token) DO UPDATE SET expires_at = excluded.expires_at, expiry_notified = 0`, + registration.endpoint, + registration.token, expiresAt, ); - return { expiresAt }; } - /** Idempotent: succeeds whether or not a registration existed. */ - async rpcUnregisterNotify(service: string): Promise { + /** Withdraw a registration, as when its syncer is denied access. */ + async rpcRemoveNotifyRegistration( + registration: NotifyRegistration, + ): Promise { await this.ensureOpen(); - this.requireLiveMeta(); - this.sql.exec("DELETE FROM notify_registration WHERE service = ?", service); + this.sql.exec( + "DELETE FROM notify_registration WHERE endpoint = ? AND token = ?", + registration.endpoint, + registration.token, + ); } - private activeRegistrations(): Array<{ - service: string; - endpoint: string; - expiresAt: string; - }> { - return this.sql + /** + * Queue a sequenced writer-set change for the registered syncers: best + * effort to each active registration, and in place of the update an + * expiry notice, delivered reliably, to each registration that has + * lapsed since the last one. Each lapse is claimed once. Must run in a + * transaction. + */ + private queueSpaceUpdate( + space: string, + update: Record, + ): void { + const now = Date.now(); + const registrations = this.sql .exec( - "SELECT service, endpoint, expires_at FROM notify_registration WHERE expires_at > ?", - new Date().toISOString(), + "SELECT endpoint, token, expires_at, expiry_notified FROM notify_registration", ) - .toArray() - .map((r) => ({ - service: r.service as string, - endpoint: r.endpoint as string, - expiresAt: r.expires_at as string, - })); + .toArray(); + for (const row of registrations) { + const endpoint = row.endpoint as string; + const token = row.token as string; + if ((row.expires_at as number) > now) { + this.insertNotify({ + service: endpoint, + endpoint, + lxm: NOTIFY_SPACE_UPDATE_LXM, + body: { space, token, update }, + policy: "fanout", + auth: "none", + }); + } else if ((row.expiry_notified as number) === 0) { + this.sql.exec( + "UPDATE notify_registration SET expiry_notified = 1 WHERE endpoint = ? AND token = ?", + endpoint, + token, + ); + this.queueSyncerNotice({ endpoint, token }, space, { + $type: REGISTRATION_EXPIRED, + spaceRev: update.spaceRev, + }); + } + } } - async rpcGetActiveRegistrations(): Promise< - Array<{ service: string; endpoint: string; expiresAt: string }> - > { - await this.ensureOpen(); - return this.activeRegistrations(); + /** A deletion or expiry notice, delivered reliably for 72 hours. */ + private queueSyncerNotice( + registration: NotifyRegistration, + space: string, + notice: Record, + ): void { + this.insertNotify({ + service: registration.endpoint, + endpoint: registration.endpoint, + lxm: NOTIFY_SPACE_UPDATE_LXM, + body: { space, token: registration.token, update: notice }, + policy: "syncer", + auth: "none", + // A deletion notice replaces whatever is pending; an expiry notice + // never replaces one, so a deletion notice is never lost. + coalesceKey: `syncer\n${registration.endpoint}\n${registration.token}`, + keepPending: notice.$type !== SPACE_DELETED, + deadline: Date.now() + SYNCER_NOTICE_RETRY_WINDOW_MS, + }); } /** @@ -1234,28 +1422,37 @@ export abstract class SpaceDurableObject< await this.ensureOpen(); if (items.length === 0) return; const nextAt = Date.now() + (opts.delayMs ?? 0); - for (const item of items) { - const body = JSON.stringify({ - endpoint: item.endpoint, - lxm: item.lxm, - body: item.body, - }); - this.sql.exec( - `INSERT INTO notify_queue (service, body, attempts, next_at, deadline, coalesce_key) - VALUES (?, ?, 0, ?, ?, ?) - ON CONFLICT (coalesce_key) DO UPDATE SET - service = excluded.service, body = excluded.body, attempts = 0, - next_at = excluded.next_at, deadline = excluded.deadline`, - item.service, - body, - nextAt, - item.deadline ?? null, - item.coalesceKey ?? null, - ); - } + for (const item of items) this.insertNotify(item, nextAt); await this.scheduleNextAlarm(); } + private insertNotify(item: NotifyItem, nextAt = Date.now()): void { + const body = JSON.stringify({ + endpoint: item.endpoint, + lxm: item.lxm, + body: item.body, + }); + this.sql.exec( + `INSERT INTO notify_queue (service, body, attempts, next_at, deadline, coalesce_key, policy, auth) + VALUES (?, ?, 0, ?, ?, ?, ?, ?) + ON CONFLICT (coalesce_key) DO ${ + item.keepPending + ? "NOTHING" + : `UPDATE SET + service = excluded.service, body = excluded.body, attempts = 0, + next_at = excluded.next_at, deadline = excluded.deadline, + policy = excluded.policy, auth = excluded.auth` + }`, + item.service, + body, + nextAt, + item.deadline ?? null, + item.coalesceKey ?? null, + item.policy ?? "fanout", + item.auth ?? "service", + ); + } + /** Drop a pending coalesced notification, e.g. once a newer one landed. */ async rpcClearNotify(coalesceKey: string): Promise { await this.ensureOpen(); @@ -1270,27 +1467,29 @@ export abstract class SpaceDurableObject< // ------------------------------------------------------------------ /** - * Tombstone the space (authority role) and delete the authority's own - * repo in it. Enqueues nothing itself — the caller enqueues - * `notifySpaceDeleted` to the returned registrations. The meta row is - * retained so a late getSpaceCredential can answer SpaceDeleted rather - * than SpaceNotFound. Idempotent. + * Tombstone the space (authority role), delete the authority's own repo + * in it, and queue a deletion notice to every registered syncer, lapsed + * registrations included. The meta row is retained so a late + * authorizeSpaceSync can answer SpaceDeleted rather than SpaceNotFound. + * Idempotent. */ - async rpcDeleteSpace(): Promise<{ - registrations: Array<{ - service: string; - endpoint: string; - expiresAt: string; - }>; - }> { + async rpcDeleteSpace(): Promise { await this.ensureOpen(); const meta = this.readMeta(); if (!meta) { throw new SpaceError("SpaceNotFound", "Space is not initialised"); } - if (meta.deletedAt) return { registrations: [] }; - const registrations = this.activeRegistrations(); + if (meta.deletedAt) return; this.ctx.storage.transactionSync(() => { + for (const row of this.sql + .exec("SELECT endpoint, token FROM notify_registration") + .toArray()) { + this.queueSyncerNotice( + { endpoint: row.endpoint as string, token: row.token as string }, + meta.uri, + { $type: SPACE_DELETED }, + ); + } this.sql.exec("UPDATE meta SET deleted_at = ?", new Date().toISOString()); for (const table of [ "record", @@ -1306,7 +1505,7 @@ export abstract class SpaceDurableObject< this.sql.exec(`DELETE FROM ${table}`); } }); - return { registrations }; + await this.scheduleNextAlarm(); } /** Wipe everything, including queued notifications and alarms. */ @@ -1347,7 +1546,7 @@ export abstract class SpaceDurableObject< policyType: this.readPolicy()?.$type ?? null, recordCount: count("record"), memberCount: count("member"), - writerCount: count("writer"), + writerCount: count("writer WHERE removed_at IS NULL"), queuedNotifications: count("notify_queue"), }; } @@ -1367,13 +1566,14 @@ export abstract class SpaceDurableObject< private async deliverQueuedNotifications(): Promise { const now = Date.now(); + // Syncer notices are tried once more after their window closes. this.sql.exec( - "DELETE FROM notify_queue WHERE deadline IS NOT NULL AND deadline <= ?", + "DELETE FROM notify_queue WHERE deadline IS NOT NULL AND deadline <= ? AND policy != 'syncer'", now, ); const due = this.sql .exec( - "SELECT id, service, body, attempts, next_at, deadline FROM notify_queue WHERE next_at <= ? ORDER BY next_at ASC LIMIT ?", + "SELECT id, service, body, attempts, next_at, deadline, policy, auth FROM notify_queue WHERE next_at <= ? ORDER BY next_at ASC LIMIT ?", now, NOTIFY_BATCH, ) @@ -1383,57 +1583,138 @@ export abstract class SpaceDurableObject< const host = await this.getHostConfig(); const keypair = await host.getKeypair(); - for (const row of due) { - let delivered = false; - let retryable = true; - try { + // In parallel, so a slow endpoint doesn't hold up the others. + await Promise.all( + due.map(async (row) => { const parsed = JSON.parse(row.body) as { endpoint: string; lxm: string; body: Record; }; - const token = await createServiceJwt( - { iss: host.operatorDid, aud: row.service, lxm: parsed.lxm }, - keypair, - ); - const res = await fetch(`${parsed.endpoint}/xrpc/${parsed.lxm}`, { - method: "POST", - headers: { + if ( + row.policy === "syncer" && + !this.isSyncerNoticeOwed(parsed.endpoint, parsed.body) + ) { + this.sql.exec("DELETE FROM notify_queue WHERE id = ?", row.id); + return; + } + let delivered = false; + let retryable = true; + try { + const headers: Record = { "Content-Type": "application/json", - Authorization: `Bearer ${token}`, - }, - body: JSON.stringify(parsed.body), - signal: AbortSignal.timeout(10_000), - }); - delivered = res.ok; - if (!res.ok) { - retryable = isRetryableStatus(res.status); - console.warn( - `notify ${parsed.lxm} to ${row.service} failed: ${res.status}`, - ); + }; + if (row.auth === "service") { + const token = await createServiceJwt( + { iss: host.operatorDid, aud: row.service, lxm: parsed.lxm }, + keypair, + ); + headers.Authorization = `Bearer ${token}`; + } + const res = await fetch(`${parsed.endpoint}/xrpc/${parsed.lxm}`, { + method: "POST", + headers, + body: JSON.stringify(parsed.body), + // A syncer chose this endpoint: never follow it elsewhere. + redirect: row.auth === "none" ? "manual" : "follow", + signal: AbortSignal.timeout(10_000), + }); + delivered = res.ok; + if (!res.ok) { + retryable = isRetryableStatus(res.status); + console.warn( + `notify ${parsed.lxm} to ${row.service} failed: ${res.status}`, + ); + } + } catch (err) { + console.warn(`notify to ${row.service} errored:`, err); } - } catch (err) { - console.warn(`notify to ${row.service} errored:`, err); - } + this.settleNotify(row, parsed, delivered, retryable); + }), + ); + } - const attempts = row.attempts + 1; - const exhausted = - row.deadline === null ? attempts >= NOTIFY_MAX_ATTEMPTS : false; - if (delivered || !retryable || exhausted) { - this.sql.exec("DELETE FROM notify_queue WHERE id = ?", row.id); - } else { - this.sql.exec( - "UPDATE notify_queue SET attempts = ?, next_at = ? WHERE id = ?", - attempts, - Date.now() + - Math.min( - NOTIFY_BACKOFF_BASE_MS * 2 ** row.attempts, - NOTIFY_BACKOFF_MAX_MS, - ), - row.id, - ); + /** A deletion or expiry notice that no longer applies is dropped unsent. */ + private isSyncerNoticeOwed( + endpoint: string, + body: Record, + ): boolean { + const update = body.update as { $type?: string } | undefined; + if (update?.$type === SPACE_DELETED) { + // Not owed if the space has been recreated since. + return Boolean(this.readMeta()?.deletedAt); + } + // An expiry notice: not owed if the syncer has renewed since. + const row = this.sql + .exec( + "SELECT expires_at FROM notify_registration WHERE endpoint = ? AND token = ?", + endpoint, + body.token as string, + ) + .toArray()[0]; + return Boolean(row && (row.expires_at as number) <= Date.now()); + } + + private settleNotify( + row: QueueRow, + parsed: { endpoint: string; body: Record }, + delivered: boolean, + retryable: boolean, + ): void { + const attempts = row.attempts + 1; + const now = Date.now(); + const remove = () => + this.sql.exec("DELETE FROM notify_queue WHERE id = ?", row.id); + if (delivered) return void remove(); + if (row.policy === "syncer") { + if (!retryable || (row.deadline !== null && row.deadline <= now)) { + remove(); + this.abandonSyncerNotice(parsed.endpoint, parsed.body); + return; } + const delays = SYNCER_NOTICE_RETRY_DELAYS_MS; + const delay = delays[Math.min(attempts, delays.length) - 1]!; + this.sql.exec( + "UPDATE notify_queue SET attempts = ?, next_at = ? WHERE id = ?", + attempts, + now + jitter(delay), + row.id, + ); + return; } + const exhausted = + row.deadline === null ? attempts >= NOTIFY_MAX_ATTEMPTS : false; + if (!retryable || exhausted) return void remove(); + this.sql.exec( + "UPDATE notify_queue SET attempts = ?, next_at = ? WHERE id = ?", + attempts, + now + + jitter( + Math.min( + NOTIFY_BACKOFF_BASE_MS * 2 ** row.attempts, + NOTIFY_BACKOFF_MAX_MS, + ), + ), + row.id, + ); + } + + /** + * Give up on a notice. A syncer that rejects its expiry notice, or can't + * be reached, is unregistered, unless it has renewed since. + */ + private abandonSyncerNotice( + endpoint: string, + body: Record, + ): void { + const update = body.update as { $type?: string } | undefined; + if (update?.$type !== REGISTRATION_EXPIRED) return; + this.sql.exec( + "DELETE FROM notify_registration WHERE endpoint = ? AND token = ? AND expires_at <= ?", + endpoint, + body.token as string, + Date.now(), + ); } private runMaintenanceIfDue(): void { @@ -1478,11 +1759,9 @@ export abstract class SpaceDurableObject< "DELETE FROM revoked_credential WHERE expires_at <= ?", nowSec, ); - // Expired notify registrations. - this.sql.exec( - "DELETE FROM notify_registration WHERE expires_at <= ?", - new Date(now).toISOString(), - ); + // Lapsed registrations are kept on purpose: the next update to the + // space owes each an expiry notice, and abandoning that notice is what + // unregisters it. this.sql.exec( `INSERT INTO replay (kind, key, expires_at) VALUES ('__maintenance', 'last', ?) diff --git a/packages/spaces/src/tokens.ts b/packages/spaces/src/tokens.ts index af6f5c5..e0d91c8 100644 --- a/packages/spaces/src/tokens.ts +++ b/packages/spaces/src/tokens.ts @@ -7,7 +7,7 @@ */ import { - createSpaceToken, + createDelegationToken as upstreamCreateDelegationToken, spaceHostAud as upstreamSpaceHostAud, } from "@atproto/space"; import type { SpaceSigningKeypair } from "./types.js"; @@ -17,7 +17,7 @@ import type { SpaceSigningKeypair } from "./types.js"; * service entry, the audience of delegation tokens and client attestations. */ export function spaceHostAud(authority: string): string { - return upstreamSpaceHostAud(authority); + return upstreamSpaceHostAud(authority as `did:${string}:${string}`); } /** @@ -28,13 +28,10 @@ export function createDelegationToken( params: { iss: string; space: string; authority: string }, keypair: SpaceSigningKeypair, ): Promise { - return createSpaceToken( - "delegation", - { - iss: params.iss, - sub: params.space, - aud: upstreamSpaceHostAud(params.authority), - }, - keypair as Parameters[2], - ); + return upstreamCreateDelegationToken({ + iss: params.iss as `did:${string}:${string}`, + sub: params.space as never, + aud: spaceHostAud(params.authority) as never, + keypair: keypair as never, + }); } diff --git a/packages/spaces/src/types.ts b/packages/spaces/src/types.ts index 0cf901a..403c786 100644 --- a/packages/spaces/src/types.ts +++ b/packages/spaces/src/types.ts @@ -93,6 +93,14 @@ export interface SpaceWriter { repoRev: string; data: Uint8Array; spaceRev: string; + /** Removed from the writer set at `spaceRev`, until it writes again. */ + removed: boolean; +} + +/** A syncer's webhook registration (`authorizeSpaceSync`'s `notify`). */ +export interface NotifyRegistration { + endpoint: string; + token: string; } /** The space sequence position assigned to an accepted repo update. */ @@ -140,11 +148,21 @@ export interface NotifyItem { body: Record; /** * Pending items sharing a key are coalesced: a newer one replaces the - * older, resetting its backoff and deadline. + * older, resetting its backoff and deadline — unless `keepPending`, when + * a pending item wins. */ coalesceKey?: string; + keepPending?: boolean; /** Give up retrying after this time (ms since epoch). */ deadline?: number; + /** + * Retry schedule: `fanout` (best effort, a few attempts), `repo` (a repo + * host's notifyRepoUpdate, exponential up to the deadline) or `syncer` + * (a syncer's deletion or expiry notice, 1 minute to 12 hours). + */ + policy?: "fanout" | "repo" | "syncer"; + /** `service` signs a service JWT; `none` sends a token-bearing webhook. */ + auth?: "service" | "none"; } /** diff --git a/packages/spaces/test/routes.test.ts b/packages/spaces/test/routes.test.ts index 9654abc..e4eed08 100644 --- a/packages/spaces/test/routes.test.ts +++ b/packages/spaces/test/routes.test.ts @@ -1,27 +1,26 @@ -import { env } from "cloudflare:test"; +import { env, runInDurableObject } from "cloudflare:test"; import { describe, expect, it, vi } from "vitest"; import type { Context } from "hono"; import { P256Keypair, Secp256k1Keypair } from "@atproto/crypto"; import { - COMMIT_MAC_TYPE, + COMMIT_MAC_PROFILE, LtHash, - RECORD_MAC_TYPE, + RECORD_MAC_PROFILE, + createDelegationToken, createSpaceSigHeaders, - createSpaceToken, encapsulate, - formatWantMacHeader, - parseMacHeader, + formatMacRequest, readRepoStar, - serializeRepo, spaceHostAud, verifyCommit, verifyRecord, verifyRepoStarFull, + writeRepoStar, } from "@atproto/space"; -import type { Commit, MacType } from "@atproto/space"; +import type { MacProfile, SpaceCommit } from "@atproto/space"; import { JoseKey } from "@atproto/jwk-jose"; import { encode } from "@atproto/lex-cbor"; -import { fromBase64 } from "@atproto/lex-data"; +import { cidForCbor, fromBase64 } from "@atproto/lex-data"; import { create as createCid, CODEC_RAW, @@ -29,18 +28,22 @@ import { } from "@atcute/cid"; import { createSpaceRoutes } from "../src/routes"; import type { SpaceRoutesHost, SpaceScopeMatch } from "../src/routes"; +import { createServiceJwt } from "../src/service-jwt"; import { TEST_KEM_KEY, TEST_OPERATOR_DID, TEST_SIGNING_KEY, } from "./fixtures/spaces-worker/index"; -const OPERATOR = TEST_OPERATOR_DID; -const BOB = "did:web:bob.test"; -const CAROL = "did:web:carol.test"; +type Did = `did:${string}:${string}`; + +const OPERATOR = TEST_OPERATOR_DID as Did; +const BOB = "did:web:bob.test" as Did; +const CAROL = "did:web:carol.test" as Did; +const SYNCER = "https://syncer.test"; const operatorKeypair = await Secp256k1Keypair.import(TEST_SIGNING_KEY); -const kemDid = (await P256Keypair.import(TEST_KEM_KEY)).did(); +const kemDid = (await P256Keypair.import(TEST_KEM_KEY)).did() as Did; const bobKeypair = await Secp256k1Keypair.create(); const carolKeypair = await Secp256k1Keypair.create(); @@ -56,13 +59,20 @@ interface OutboundCall { init?: RequestInit; } +/** + * Tokens the test syncer issued, per space: it confirms a registration + * only for one of these, as a real syncer must. + */ +const syncerTokens = new Map(); + function makeHost(overrides: Partial = {}): { host: SpaceRoutesHost; outbound: OutboundCall[]; - setOutboundResponse(fn: (url: string) => Response | null): void; + setOutboundResponse(fn: (url: string, init?: RequestInit) => Response | null): void; } { const outbound: OutboundCall[] = []; - let responder: (url: string) => Response | null = () => null; + let responder: (url: string, init?: RequestInit) => Response | null = () => + null; const host: SpaceRoutesHost = { operatorDid: OPERATOR, blobs: env.BLOBS, @@ -117,8 +127,22 @@ function makeHost(overrides: Partial = {}): { getIndexDO: () => env.SPACES_INDEX.get(env.SPACES_INDEX.idFromName("spaces")) as never, outboundFetch: (async (input: RequestInfo | URL, init?: RequestInit) => { - outbound.push({ url: String(input), init }); - return responder(String(input)) ?? new Response("{}", { status: 200 }); + const url = String(input); + outbound.push({ url, init }); + const custom = responder(url, init); + if (custom) return custom; + // The test syncer: confirms registrations for tokens it issued. + if (url === `${SYNCER}/xrpc/com.atproto.space.confirmRegistration`) { + const body = JSON.parse(String(init?.body)) as { + space: string; + token: string; + challenge: string; + }; + return syncerTokens.get(body.space) === body.token + ? Response.json({ challenge: body.challenge }) + : Response.json({ error: "UnknownToken" }, { status: 400 }); + } + return new Response("{}", { status: 200 }); }) as typeof fetch, ...overrides, }; @@ -136,6 +160,7 @@ const app = createSpaceRoutes(host); const SESSION = { Authorization: "Bearer operator-session" }; const MEMBERSPACE = { $type: "com.atproto.memberspace.policy" }; +const STAR = "application/vnd.dasl.star"; let spaceN = 0; async function createSpace( @@ -148,7 +173,7 @@ async function createSpace( policy, }); expect(res.status).toBe(200); - return ((await res.json()) as { uri: string }).uri; + return ((await res.json()) as { space: string }).space; } function post( @@ -193,17 +218,10 @@ async function createRecord( return (await res.json()) as { uri: string; cid: string }; } -async function putMember( - space: string, - did: string, - read = true, - write = true, -) { - const res = await post("/xrpc/com.atproto.memberspace.putMember", { +async function putMember(space: string, did: string, read = true, write = true) { + const res = await post("/xrpc/com.atproto.memberspace.putMembers", { space, - did, - read, - write, + members: [{ did, read, write }], }); expect(res.status).toBe(200); } @@ -212,36 +230,47 @@ async function putMember( async function obtainCredential( space: string, opts: { - user?: { did: string; keypair: Secp256k1Keypair }; + user?: { did: Did; keypair: Secp256k1Keypair }; clientAttestation?: string; + notify?: { endpoint: string; token: string }; + via?: { request: typeof app.request }; } = {}, ): Promise<{ credential: string; key: P256Keypair; status: number; - body: unknown; + body: { credential?: string; spaceRev?: string; error?: string }; }> { const key = await P256Keypair.create(); const delegationToken = opts.user - ? await createSpaceToken( - "delegation", - { iss: opts.user.did, sub: space, aud: spaceHostAud(OPERATOR) }, - opts.user.keypair, - ) + ? await createDelegationToken({ + iss: opts.user.did, + sub: space as never, + aud: spaceHostAud(OPERATOR), + keypair: opts.user.keypair, + }) : undefined; - const res = await post( - "/xrpc/com.atproto.space.getSpaceCredential", + const res = await (opts.via ?? app).request( + "/xrpc/com.atproto.space.authorizeSpaceSync", { - space, - credentialKid: key.did(), - ...(delegationToken ? { delegationToken } : {}), - ...(opts.clientAttestation - ? { clientAttestation: opts.clientAttestation } - : {}), + method: "POST", + headers: { "Content-Type": "application/json" }, + body: JSON.stringify({ + space, + credentialKey: key.did(), + ...(delegationToken ? { delegationToken } : {}), + ...(opts.clientAttestation + ? { clientAttestation: opts.clientAttestation } + : {}), + ...(opts.notify ? { notify: opts.notify } : {}), + }), }, - {}, ); - const body = (await res.json()) as { credential?: string }; + const body = (await res.json()) as { + credential?: string; + spaceRev?: string; + error?: string; + }; return { credential: body.credential ?? "", key, status: res.status, body }; } @@ -254,74 +283,77 @@ async function credentialRequest( credential: string, key: P256Keypair, opts: { - mac?: MacType; - audience?: string; + mac?: MacProfile; + audience?: Did; scheme?: string; method?: "GET" | "POST"; body?: unknown; } = {}, -): Promise<{ res: Response; sharedSecret?: Uint8Array }> { +): Promise<{ + res: Response; + encapsulation?: { keyShare: Did; sharedSecret: Uint8Array }; +}> { const authorization = `${opts.scheme ?? "Atproto-Space-Credential"} ${credential}`; - const headers: Record = await createSpaceSigHeaders(key, { + const { headers } = await createSpaceSigHeaders({ authorization, - audience: (opts.audience ?? OPERATOR) as `did:${string}:${string}`, + audience: opts.audience ?? OPERATOR, + keypair: key, }); - let sharedSecret: Uint8Array | undefined; + let encapsulation: { keyShare: Did; sharedSecret: Uint8Array } | undefined; + const requestHeaders: Record = { ...headers }; if (opts.mac) { - const encapsulation = await encapsulate(kemDid); - sharedSecret = encapsulation.sharedSecret; - headers["atproto-space-want-mac"] = formatWantMacHeader( + encapsulation = (await encapsulate(kemDid)) as never; + requestHeaders["accept-signature"] = formatMacRequest( opts.mac, - encapsulation.keyShare, + encapsulation!.keyShare, ); } const res = await app.request(path, { method: opts.method ?? "GET", headers: { - ...headers, + ...requestHeaders, ...(opts.body ? { "Content-Type": "application/json" } : {}), }, ...(opts.body ? { body: JSON.stringify(opts.body) } : {}), }); - return { res, sharedSecret }; + return { res, encapsulation }; } -function commitFromJson(json: Record): Commit { +function commitFromJson(json: Record): SpaceCommit { return { ver: json.ver as number, - repo: json.repo as Commit["repo"], - space: json.space as Commit["space"], - rev: json.rev as string, + repo: json.repo as SpaceCommit["repo"], + space: json.space as SpaceCommit["space"], + rev: json.rev as SpaceCommit["rev"], data: fromBase64((json.data as { $bytes: string }).$bytes), }; } -async function serviceJwt( +function serviceJwt( iss: string, aud: string, lxm: string, keypair: Secp256k1Keypair, ) { - const { createServiceJwt } = await import("../src/service-jwt"); return createServiceJwt({ iss, aud, lxm }, keypair); } -async function notifyWrite( +async function notifyRepoUpdate( space: string, writer: string, keypair: Secp256k1Keypair, repoRev: string, data: Uint8Array, - aud = OPERATOR, + aud: string = OPERATOR, ): Promise { const token = await serviceJwt( writer, aud, - "com.atproto.space.notifyWrite", + "com.atproto.space.notifyRepoUpdate", keypair, ); return post( - "/xrpc/com.atproto.space.notifyWrite", + "/xrpc/com.atproto.space.notifyRepoUpdate", { space, repo: writer, @@ -332,6 +364,28 @@ async function notifyWrite( ); } +/** The space DO's pending notifications, decoded. */ +async function queued(space: string) { + const stub = env.SPACES.get(env.SPACES.idFromName(space)); + return runInDurableObject(stub, async (_instance, state) => + state.storage.sql + .exec("SELECT service, body, policy FROM notify_queue ORDER BY id") + .toArray() + .map((row) => { + const parsed = JSON.parse(row.body as string) as { + lxm: string; + body: Record; + }; + return { + service: row.service as string, + policy: row.policy as string, + lxm: parsed.lxm, + body: parsed.body, + }; + }), + ); +} + const TID_CHARS = "234567abcdefghijklmnopqrstuvwxyz"; /** A TID for a given time, so tests control rev order and skew. */ function tidAt(ms: number, clock = 0): string { @@ -346,6 +400,25 @@ function tidAt(ms: number, clock = 0): string { const repoData = (n: number) => new Uint8Array(32).fill(n); +async function starArchive( + commit: SpaceCommit, + records: Array<{ collection: string; rkey: string; bytes: Uint8Array }>, +): Promise { + const chunks: Uint8Array[] = []; + for await (const chunk of writeRepoStar(commit, records as never)) { + chunks.push(chunk); + } + return new Uint8Array(await new Blob(chunks).arrayBuffer()); +} + +function postStar(path: string, body: Uint8Array): Promise { + return app.request(path, { + method: "POST", + headers: { ...SESSION, "Content-Type": STAR }, + body, + }); +} + // --------------------------------------------------------------------- describe("space routes: personal data (S1)", () => { @@ -363,7 +436,7 @@ describe("space routes: personal data (S1)", () => { ); expect(res.status).toBe(200); // A session reading its own data gets no MAC unless it asks. - expect(res.headers.get("atproto-space-mac")).toBeNull(); + expect(res.headers.get("signature")).toBeNull(); const body = (await res.json()) as { value: { text: string }; cid: string }; expect(body.value.text).toBe("hello spaces"); expect(body.cid).toBe(created.cid); @@ -371,11 +444,7 @@ describe("space routes: personal data (S1)", () => { it("refuses an unauthenticated getRecord", async () => { const space = await createSpace(); - await createRecord( - space, - { $type: "app.bsky.feed.post", text: "x" }, - "aaa", - ); + await createRecord(space, { $type: "app.bsky.feed.post", text: "x" }, "aaa"); const res = await get( `/xrpc/com.atproto.space.getRecord?space=${q(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=aaa`, {}, @@ -511,10 +580,7 @@ describe("space routes: personal data (S1)", () => { }); it("clearRecords empties the repo but keeps published configuration", async () => { - const space = await createSpace({ - ...MEMBERSPACE, - publishPolicy: true, - }); + const space = await createSpace({ ...MEMBERSPACE, publishPolicy: true }); await createRecord(space, { $type: "app.bsky.feed.post", text: "a" }, "a"); await createRecord( space, @@ -576,17 +642,13 @@ describe("space routes: personal data (S1)", () => { describe("space routes: credentials (S5)", () => { it("issues credentials to members, binds them to the request key and refuses others as SpaceNotFound", async () => { const space = await createSpace(); - await createRecord( - space, - { $type: "app.bsky.feed.post", text: "hi" }, - "r1", - ); + await createRecord(space, { $type: "app.bsky.feed.post", text: "hi" }, "r1"); const denied = await obtainCredential(space, { user: { did: BOB, keypair: bobKeypair }, }); expect(denied.status).toBe(404); - expect((denied.body as { error: string }).error).toBe("SpaceNotFound"); + expect(denied.body.error).toBe("SpaceNotFound"); await putMember(space, BOB); const { credential, key, status } = await obtainCredential(space, { @@ -601,14 +663,13 @@ describe("space routes: credentials (S5)", () => { expect(payload.sub).toBe(space); expect(payload.aud).toBeUndefined(); + const uri = `${space}/${OPERATOR}/app.bsky.feed.post/r1`; const path = `/xrpc/com.atproto.space.getRecord?space=${q(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=r1`; - const { res, sharedSecret } = await credentialRequest( + const { res, encapsulation } = await credentialRequest( path, credential, key, - { - mac: RECORD_MAC_TYPE, - }, + { mac: RECORD_MAC_PROFILE }, ); expect(res.status).toBe(200); const record = (await res.json()) as { @@ -616,20 +677,19 @@ describe("space routes: credentials (S5)", () => { cid: string; value: Record; }; - const mac = parseMacHeader( - res.headers.get("atproto-space-mac") ?? undefined, - RECORD_MAC_TYPE, - ); - expect( - await verifyRecord(record as never, { - uri: record.uri, - sharedSecret: sharedSecret!, - mac, - }), - ).toBe(true); - expect(res.headers.get("access-control-expose-headers")).toContain( - "atproto-space-mac", - ); + // Throws unless the MAC covers this uri and cid and the value encodes + // to that cid. + await verifyRecord(record as never, { + uri: uri as never, + keyShare: encapsulation!.keyShare, + sharedSecret: encapsulation!.sharedSecret, + headers: res.headers, + }); + const exposed = res.headers.get("access-control-expose-headers") ?? ""; + for (const header of ["atproto-space-record", "signature-input", "signature"]) { + expect(exposed).toContain(header); + } + expect(res.headers.get("vary")).toContain("Accept-Signature"); // A member without read access is refused like a stranger. await putMember(space, BOB, false, true); @@ -639,26 +699,27 @@ describe("space routes: credentials (S5)", () => { expect(noRead.status).toBe(404); }); - it("validates credentialKid and the delegation token", async () => { + it("validates credentialKey and the delegation token", async () => { const space = await createSpace({ ...MEMBERSPACE, publicRead: true }); const k256 = await post( - "/xrpc/com.atproto.space.getSpaceCredential", - { space, credentialKid: bobKeypair.did() }, + "/xrpc/com.atproto.space.authorizeSpaceSync", + { space, credentialKey: bobKeypair.did() }, {}, ); expect(k256.status).toBe(400); expect(await errorOf(k256)).toBe("InvalidRequest"); const key = await P256Keypair.create(); - const token = await createSpaceToken( - "delegation", - { iss: BOB, sub: space, aud: spaceHostAud(OPERATOR) }, - bobKeypair, - ); + const token = await createDelegationToken({ + iss: BOB, + sub: space as never, + aud: spaceHostAud(OPERATOR), + keypair: bobKeypair, + }); const request = () => post( - "/xrpc/com.atproto.space.getSpaceCredential", - { space, credentialKid: key.did(), delegationToken: token }, + "/xrpc/com.atproto.space.authorizeSpaceSync", + { space, credentialKey: key.did(), delegationToken: token }, {}, ); expect((await request()).status).toBe(200); @@ -666,14 +727,15 @@ describe("space routes: credentials (S5)", () => { expect(replay.status).toBe(400); expect(await errorOf(replay)).toBe("InvalidDelegationToken"); - const wrongAud = await createSpaceToken( - "delegation", - { iss: BOB, sub: space, aud: `${OPERATOR}#atproto_space_host` }, - bobKeypair, - ); + const wrongAud = await createDelegationToken({ + iss: BOB, + sub: space as never, + aud: `${OPERATOR}#atproto_space_host` as never, + keypair: bobKeypair, + }); const badAud = await post( - "/xrpc/com.atproto.space.getSpaceCredential", - { space, credentialKid: key.did(), delegationToken: wrongAud }, + "/xrpc/com.atproto.space.authorizeSpaceSync", + { space, credentialKey: key.did(), delegationToken: wrongAud }, {}, ); expect(await errorOf(badAud)).toBe("InvalidDelegationToken"); @@ -683,16 +745,14 @@ describe("space routes: credentials (S5)", () => { const closed = await createSpace(); const anon = await obtainCredential(closed); expect(anon.status).toBe(404); - expect((anon.body as { error: string }).error).toBe("SpaceNotFound"); + expect(anon.body.error).toBe("SpaceNotFound"); const open = await createSpace({ ...MEMBERSPACE, publicRead: true }); - await createRecord( - open, - { $type: "app.bsky.feed.post", text: "public" }, - "p", - ); - const { credential, key, status } = await obtainCredential(open); + await createRecord(open, { $type: "app.bsky.feed.post", text: "public" }, "p"); + const { credential, key, status, body } = await obtainCredential(open); expect(status).toBe(200); + // The authority's own write sequenced the space. + expect(body.spaceRev).toMatch(/^[2-7a-z]{13}$/); const { res } = await credentialRequest( `/xrpc/com.atproto.space.listRecords?space=${q(open)}&repo=${OPERATOR}`, credential, @@ -743,36 +803,34 @@ describe("space routes: credentials (S5)", () => { key, ); expect(noMac.res.status).toBe(400); - expect(await errorOf(noMac.res)).toBe("BadSpaceMac"); + expect(await errorOf(noMac.res)).toBe("InvalidSpaceMac"); + // A MAC request under another profile's tag is ignored, so it's as + // though none was made. + const wrongTag = await credentialRequest( + `/xrpc/com.atproto.space.getLatestCommit?space=${q(space)}&repo=${OPERATOR}`, + credential, + key, + { mac: RECORD_MAC_PROFILE }, + ); + expect(await errorOf(wrongTag.res)).toBe("InvalidSpaceMac"); // Revocation, by the authority, addressed to the repo DID. const jti = ( JSON.parse( atob(credential.split(".")[1]!.replace(/-/g, "+").replace(/_/g, "/")), - ) as { - jti: string; - } + ) as { jti: string } ).jti; - const forged = await serviceJwt( - BOB, - OPERATOR, - "com.atproto.space.notifyCredentialRevoked", - bobKeypair, - ); + const lxm = "com.atproto.space.notifyCredentialsRevoked"; + const forged = await serviceJwt(BOB, OPERATOR, lxm, bobKeypair); const forgedRes = await post( - "/xrpc/com.atproto.space.notifyCredentialRevoked", + `/xrpc/${lxm}`, { space, credentials: [jti] }, { Authorization: `Bearer ${forged}` }, ); expect(forgedRes.status).toBe(403); - const token = await serviceJwt( - OPERATOR, - OPERATOR, - "com.atproto.space.notifyCredentialRevoked", - operatorKeypair, - ); + const token = await serviceJwt(OPERATOR, OPERATOR, lxm, operatorKeypair); const revoke = await post( - "/xrpc/com.atproto.space.notifyCredentialRevoked", + `/xrpc/${lxm}`, { space, credentials: [jti] }, { Authorization: `Bearer ${token}` }, ); @@ -782,7 +840,7 @@ describe("space routes: credentials (S5)", () => { expect(await errorOf(revoked.res)).toBe("CredentialRevoked"); }); - it("gates on allowedApps with client attestations, after the user", async () => { + it("gates on allowedApps with client attestations, after the account", async () => { const clientId = "https://app.example/client-metadata.json"; const jwk = await JoseKey.generate(["ES256"], "attest-key"); const space = await createSpace({ @@ -806,45 +864,35 @@ describe("space routes: credentials (S5)", () => { { iss: id, sub: id, aud, iat, exp: iat + 60, jti: crypto.randomUUID() }, ); }; - const request = async (clientAttestation?: string) => { - const key = await P256Keypair.create(); - return attestApp.request("/xrpc/com.atproto.space.getSpaceCredential", { - method: "POST", - headers: { "Content-Type": "application/json" }, - body: JSON.stringify({ - space, - credentialKid: key.did(), - ...(clientAttestation ? { clientAttestation } : {}), - }), - }); - }; + const request = async (clientAttestation?: string) => + obtainCredential(space, { clientAttestation, via: attestApp }); const none = await request(); expect(none.status).toBe(403); - expect(await errorOf(none)).toBe("AppNotAuthorized"); + expect(none.body.error).toBe("AppNotAuthorized"); expect((await request(await attest())).status).toBe(200); const otherApp = await request( await attest(undefined, "https://other.example/client-metadata.json"), ); - expect(await errorOf(otherApp)).toBe("AppNotAuthorized"); + expect(otherApp.body.error).toBe("AppNotAuthorized"); const wrongAud = await request( - await attest(`${OPERATOR}#atproto_space_host`), + await attest(`${OPERATOR}#atproto_space_host` as never), ); - expect(await errorOf(wrongAud)).toBe("InvalidClientAttestation"); + expect(wrongAud.body.error).toBe("InvalidClientAttestation"); }); - it("consults the managing app with the access kind and denies on failure", async () => { + it("asks the managing app with checkAccess, and fails upstream rather than deny", async () => { const space = await createSpace({ $type: "com.atproto.managedspace.policy", managingApp: "did:web:manager.test#forum", }); setOutboundResponse((url) => { - if (!url.includes("checkUserAccess")) return null; - const user = new URL(url).searchParams.get("user"); - return Response.json({ authorized: user === BOB }); + if (!url.includes("checkAccess")) return null; + const repo = new URL(url).searchParams.get("repo"); + return Response.json({ read: repo === BOB, write: false }); }); try { const bob = await obtainCredential(space, { @@ -852,11 +900,23 @@ describe("space routes: credentials (S5)", () => { }); expect(bob.status).toBe(200); const check = outbound - .filter((call) => call.url.includes("checkUserAccess")) + .filter((call) => call.url.includes("checkAccess")) .pop()!; const params = new URL(check.url).searchParams; - expect(params.get("access")).toBe("read"); expect(params.get("space")).toBe(space); + expect(params.get("repo")).toBe(BOB); + expect(params.has("access")).toBe(false); + expect( + new Headers(check.init?.headers).get("Authorization"), + ).toMatch(/^Bearer /); + + // Without a delegation token, the app is asked with no repo. + const anon = await obtainCredential(space); + expect(anon.status).toBe(404); + const anonCheck = outbound + .filter((call) => call.url.includes("checkAccess")) + .pop()!; + expect(new URL(anonCheck.url).searchParams.has("repo")).toBe(false); const carol = await obtainCredential(space, { user: { did: CAROL, keypair: carolKeypair }, @@ -864,14 +924,15 @@ describe("space routes: credentials (S5)", () => { expect(carol.status).toBe(404); setOutboundResponse((url) => - url.includes("checkUserAccess") + url.includes("checkAccess") ? new Response("boom", { status: 500 }) : null, ); const failing = await obtainCredential(space, { user: { did: BOB, keypair: bobKeypair }, }); - expect(failing.status).toBe(404); + expect(failing.status).toBe(502); + expect(failing.body.error).toBe("UpstreamFailure"); } finally { setOutboundResponse(() => null); } @@ -892,6 +953,133 @@ describe("space routes: credentials (S5)", () => { }); }); +describe("space routes: notification registration", () => { + it("confirms a new registration, renews it, and refuses one the syncer didn't ask for", async () => { + const space = await createSpace({ ...MEMBERSPACE, publicRead: true }); + const token = `tok-${spaceN}`; + syncerTokens.set(space, token); + const notify = { endpoint: SYNCER, token }; + + const before = outbound.filter((c) => c.url.includes("confirmRegistration")) + .length; + const first = await obtainCredential(space, { notify }); + expect(first.status).toBe(200); + const confirms = () => + outbound.filter((c) => c.url.includes("confirmRegistration")).length; + expect(confirms()).toBe(before + 1); + const confirm = outbound + .filter((c) => c.url.includes("confirmRegistration")) + .pop()!; + const confirmBody = JSON.parse(String(confirm.init?.body)) as Record< + string, + string + >; + expect(confirmBody.space).toBe(space); + expect(confirmBody.token).toBe(token); + expect(confirmBody.challenge).toBeTruthy(); + // No service auth: the token authenticates the call. + expect(new Headers(confirm.init?.headers).get("Authorization")).toBeNull(); + + // Renewal is not confirmed again. + const renew = await obtainCredential(space, { notify }); + expect(renew.status).toBe(200); + expect(confirms()).toBe(before + 1); + + // A token the syncer never issued is not confirmed. + const forged = await obtainCredential(space, { + notify: { endpoint: SYNCER, token: "not-ours" }, + }); + expect(forged.status).toBe(400); + expect(forged.body.error).toBe("RegistrationNotConfirmed"); + + // Only https endpoints, and bounded tokens. + const insecure = await obtainCredential(space, { + notify: { endpoint: "http://syncer.test", token }, + }); + expect(insecure.body.error).toBe("InvalidRequest"); + const long = await obtainCredential(space, { + notify: { endpoint: SYNCER, token: "x".repeat(513) }, + }); + expect(long.body.error).toBe("InvalidRequest"); + }); + + it("notifies registered syncers of writes and removals with token-bearing webhooks", async () => { + const space = await createSpace({ ...MEMBERSPACE, publicRead: true }); + const token = `fan-${spaceN}`; + syncerTokens.set(space, token); + await obtainCredential(space, { notify: { endpoint: SYNCER, token } }); + await putMember(space, BOB); + const t = Date.now(); + expect( + ( + await notifyRepoUpdate(space, BOB, bobKeypair, tidAt(t - 2000), repoData(1)) + ).status, + ).toBe(200); + expect( + ( + await post("/xrpc/com.atproto.space.removeWriter", { + space, + repo: BOB, + }) + ).status, + ).toBe(200); + + const updates = (await queued(space)).filter((item) => + ["com.atproto.space.defs#repoWrite", "com.atproto.space.defs#repoRemoved"].includes( + (item.body.update as { $type: string }).$type, + ), + ); + expect(updates.map((u) => u.lxm)).toEqual([ + "com.atproto.space.notifySpaceUpdate", + "com.atproto.space.notifySpaceUpdate", + ]); + const [write, removed] = updates.map( + (u) => u.body as { space: string; token: string; update: Record }, + ); + expect(write!.space).toBe(space); + expect(write!.token).toBe(token); + expect(write!.update).toMatchObject({ + $type: "com.atproto.space.defs#repoWrite", + repo: BOB, + repoRev: tidAt(t - 2000), + }); + expect(removed!.update).toMatchObject({ + $type: "com.atproto.space.defs#repoRemoved", + repo: BOB, + prevSpaceRev: write!.update.spaceRev, + }); + }); + + it("withdraws a registration when the syncer is refused, but not when the app is down", async () => { + const space = await createSpace({ + $type: "com.atproto.managedspace.policy", + managingApp: "did:web:manager.test#forum", + }); + const token = `wd-${spaceN}`; + syncerTokens.set(space, token); + const notify = { endpoint: SYNCER, token }; + const stub = env.SPACES.get(env.SPACES.idFromName(space)); + let answer: Response = Response.json({ read: true, write: false }); + setOutboundResponse((url) => + url.includes("checkAccess") ? answer.clone() : null, + ); + try { + expect((await obtainCredential(space, { notify })).status).toBe(200); + expect(await stub.rpcGetNotifyRegistration(notify)).not.toBe(null); + + answer = new Response("down", { status: 503 }); + expect((await obtainCredential(space, { notify })).status).toBe(502); + expect(await stub.rpcGetNotifyRegistration(notify)).not.toBe(null); + + answer = Response.json({ read: false, write: false }); + expect((await obtainCredential(space, { notify })).status).toBe(404); + expect(await stub.rpcGetNotifyRegistration(notify)).toBe(null); + } finally { + setOutboundResponse(() => null); + } + }); +}); + describe("space routes: sync (S2-S4)", () => { async function syncerCredential(space: string) { await putMember(space, BOB); @@ -902,44 +1090,37 @@ describe("space routes: sync (S2-S4)", () => { const space = await createSpace(); await createRecord(space, { $type: "app.bsky.feed.post", text: "a" }); const { credential, key } = await syncerCredential(space); - const { res, sharedSecret } = await credentialRequest( + const { res, encapsulation } = await credentialRequest( `/xrpc/com.atproto.space.getLatestCommit?space=${q(space)}&repo=${OPERATOR}`, credential, key, - { mac: COMMIT_MAC_TYPE }, + { mac: COMMIT_MAC_PROFILE }, ); expect(res.status).toBe(200); - expect(res.headers.get("vary")).toContain("atproto-space-want-mac"); const commit = commitFromJson( ((await res.json()) as { commit: Record }).commit, ); expect(commit.repo).toBe(OPERATOR); expect(commit.space).toBe(space); - const mac = parseMacHeader( - res.headers.get("atproto-space-mac") ?? undefined, - COMMIT_MAC_TYPE, - ); - expect( - verifyCommit(commit, { - space, - repo: OPERATOR, - sharedSecret: sharedSecret!, - mac, - }), - ).toBe(true); + verifyCommit(commit, { + space: space as never, + repo: OPERATOR, + ...encapsulation!, + headers: res.headers, + }); // The MAC is per request: another shared secret does not verify it. const other = await encapsulate(kemDid); - expect( + expect(() => verifyCommit(commit, { - space, + space: space as never, repo: OPERATOR, - sharedSecret: other.sharedSecret, - mac, + ...other, + headers: res.headers, }), - ).toBe(false); + ).toThrow(); }); - it("lets a syncer follow listRepoOps to the commit's data", async () => { + it("lets a syncer follow listRepoOps to the commit's data, with the commit on every page", async () => { const space = await createSpace(); await createRecord(space, { $type: "app.bsky.feed.post", text: "a" }, "a"); await createRecord(space, { $type: "app.bsky.feed.post", text: "b" }, "b"); @@ -950,40 +1131,53 @@ describe("space routes: sync (S2-S4)", () => { rkey: "a", }); const { credential, key } = await syncerCredential(space); - const { res, sharedSecret } = await credentialRequest( - `/xrpc/com.atproto.space.listRepoOps?space=${q(space)}&repo=${OPERATOR}`, - credential, - key, - { mac: COMMIT_MAC_TYPE }, - ); - const body = (await res.json()) as { - ops: Array<{ - collection: string; - rkey: string; - cid: string | null; - prev: string | null; - }>; - commit: Record; - }; const hash = new LtHash(); - for (const op of body.ops) { - if (op.prev) hash.remove(`${op.collection}/${op.rkey}/${op.prev}`); - if (op.cid) hash.add(`${op.collection}/${op.rkey}/${op.cid}`); - } - const commit = commitFromJson(body.commit); - expect(hash.digest()).toEqual(commit.data); - const mac = parseMacHeader( - res.headers.get("atproto-space-mac") ?? undefined, - COMMIT_MAC_TYPE, - ); - expect( + let cursor: string | undefined; + let pages = 0; + let commit: SpaceCommit; + do { + const { res, encapsulation } = await credentialRequest( + `/xrpc/com.atproto.space.listRepoOps?space=${q(space)}&repo=${OPERATOR}&limit=2${cursor ? `&cursor=${q(cursor)}` : ""}`, + credential, + key, + { mac: COMMIT_MAC_PROFILE }, + ); + const body = (await res.json()) as { + ops: Array<{ + collection: string; + rkey: string; + cid: string | null; + prev: string | null; + }>; + commit: Record; + cursor?: string; + }; + commit = commitFromJson(body.commit); verifyCommit(commit, { - space, + space: space as never, repo: OPERATOR, - sharedSecret: sharedSecret!, - mac, - }), - ).toBe(true); + ...encapsulation!, + headers: res.headers, + }); + for (const op of body.ops) { + if (op.prev) hash.remove(`${op.collection}/${op.rkey}/${op.prev}`); + if (op.cid) hash.add(`${op.collection}/${op.rkey}/${op.cid}`); + } + cursor = body.cursor; + pages++; + } while (cursor); + // Three ops at two a page: a full page, then a short one. + expect(pages).toBe(2); + expect(hash.digest()).toEqual(commit!.data); + }); + + it("answers RepoNotFound from listRepoOps for a repo never written", async () => { + const space = await createSpace(); + const res = await get( + `/xrpc/com.atproto.space.listRepoOps?space=${q(space)}&repo=${OPERATOR}`, + ); + expect(res.status).toBe(404); + expect(await errorOf(res)).toBe("RepoNotFound"); }); it("streams a STAR archive the @atproto/space consumer verifies (S8)", async () => { @@ -991,72 +1185,46 @@ describe("space routes: sync (S2-S4)", () => { // One collection NSID prefixes another: (collection, rkey) order and // byte order of the record path disagree, and the archive needs the // latter. - await createRecord( - space, - { $type: "app.bsky.feed.post", text: "1" }, - "z", - "app.bsky.feed", - ); - await createRecord( - space, - { $type: "app.bsky.feed.post", text: "2" }, - "a", - "app.bsky.feed.post", - ); + await createRecord(space, { $type: "app.bsky.feed.post", text: "1" }, "z", "app.bsky.feed"); + await createRecord(space, { $type: "app.bsky.feed.post", text: "2" }, "a", "app.bsky.feed.post"); for (let i = 0; i < 3; i++) { await createRecord(space, { $type: "app.bsky.feed.post", text: `n${i}` }); } const { credential, key } = await syncerCredential(space); - const { res, sharedSecret } = await credentialRequest( + const { res, encapsulation } = await credentialRequest( `/xrpc/com.atproto.space.getRepo?space=${q(space)}&repo=${OPERATOR}`, credential, key, - { mac: COMMIT_MAC_TYPE }, + { mac: COMMIT_MAC_PROFILE }, ); expect(res.status).toBe(200); - expect(res.headers.get("content-type")).toBe("application/octet-stream"); - const mac = parseMacHeader( - res.headers.get("atproto-space-mac") ?? undefined, - COMMIT_MAC_TYPE, - ); + expect(res.headers.get("content-type")).toBe(STAR); const bytes = new Uint8Array(await res.arrayBuffer()); const verified = await verifyRepoStarFull([bytes], { - space, + space: space as never, repo: OPERATOR, - sharedSecret: sharedSecret!, - mac, + ...encapsulation!, + headers: res.headers, }); expect(verified.records).toHaveLength(5); expect(verified.records[0]!.collection).toBe("app.bsky.feed.post"); }); - it("sequences writers from notifyWrite and serves listRepos by spaceRev", async () => { + it("sequences writers from notifyRepoUpdate and serves listWriters by spaceRev", async () => { const space = await createSpace(); await putMember(space, BOB); await putMember(space, CAROL); - const registrar = await obtainCredential(space, { + const reader = await obtainCredential(space, { user: { did: BOB, keypair: bobKeypair }, }); - const reg = await credentialRequest( - "/xrpc/com.atproto.space.registerNotify", - registrar.credential, - registrar.key, - { - method: "POST", - body: { space, service: "did:web:syncer.test#atproto_space_syncer" }, - }, - ); - expect(reg.res.status).toBe(200); - const before = outbound.length; const t = Date.now(); expect( - (await notifyWrite(space, BOB, bobKeypair, tidAt(t - 3000), repoData(1))) - .status, + (await notifyRepoUpdate(space, BOB, bobKeypair, tidAt(t - 3000), repoData(1))).status, ).toBe(200); expect( ( - await notifyWrite( + await notifyRepoUpdate( space, CAROL, carolKeypair, @@ -1066,81 +1234,70 @@ describe("space routes: sync (S2-S4)", () => { ) ).status, ).toBe(200); - // Stale: does not advance and is not fanned out again. + // Stale: does not advance. expect( - (await notifyWrite(space, BOB, bobKeypair, tidAt(t - 4000), repoData(9))) - .status, + (await notifyRepoUpdate(space, BOB, bobKeypair, tidAt(t - 4000), repoData(9))).status, ).toBe(200); - const list = await credentialRequest( - `/xrpc/com.atproto.space.listRepos?space=${q(space)}&limit=1`, - registrar.credential, - registrar.key, - ); - const page1 = (await list.res.json()) as { - repos: Array<{ - did: string; - repoRev: string; - data: { $bytes: string }; - spaceRev: string; - }>; - cursor?: string; - }; - expect(page1.repos.map((r) => r.did)).toEqual([BOB]); + const list = async (params: string) => + (await ( + await credentialRequest( + `/xrpc/com.atproto.space.listWriters?space=${q(space)}${params}`, + reader.credential, + reader.key, + ) + ).res.json()) as { + repos: Array<{ + $type: string; + repo: string; + repoRev?: string; + data?: { $bytes: string }; + spaceRev: string; + }>; + cursor?: string; + }; + const page1 = await list("&limit=1"); + expect(page1.repos.map((r) => [r.$type, r.repo])).toEqual([ + ["com.atproto.space.defs#repoWrite", BOB], + ]); expect(page1.cursor).toBe(page1.repos[0]!.spaceRev); - expect(fromBase64(page1.repos[0]!.data.$bytes)).toEqual(repoData(1)); - const list2 = await credentialRequest( - `/xrpc/com.atproto.space.listRepos?space=${q(space)}&cursor=${page1.cursor}`, - registrar.credential, - registrar.key, - ); - const page2 = (await list2.res.json()) as typeof page1; - expect(page2.repos.map((r) => r.did)).toEqual([CAROL]); - expect(page2.repos[0]!.spaceRev > page1.repos[0]!.spaceRev).toBe(true); - const list3 = await credentialRequest( - `/xrpc/com.atproto.space.listRepos?space=${q(space)}&cursor=${page2.cursor}`, - registrar.credential, - registrar.key, - ); - const page3 = (await list3.res.json()) as typeof page1; + expect(fromBase64(page1.repos[0]!.data!.$bytes)).toEqual(repoData(1)); + const page2 = await list(`&cursor=${page1.cursor}`); + expect(page2.repos.map((r) => r.repo)).toEqual([CAROL]); + const page3 = await list(`&cursor=${page2.cursor}`); expect(page3.repos).toEqual([]); expect(page3.cursor).toBeUndefined(); - // Two accepted updates, two fan-outs queued with sequence numbers. - const stub = env.SPACES.get(env.SPACES.idFromName(space)); - const status = await stub.rpcStatus(); - expect(status.queuedNotifications).toBe(2); - expect(outbound.length).toBe(before); + // A removal is listed until the repo writes again. + await post("/xrpc/com.atproto.space.removeWriter", { space, repo: CAROL }); + const after = await list(""); + expect(after.repos.map((r) => [r.repo, r.$type])).toEqual([ + [BOB, "com.atproto.space.defs#repoWrite"], + [CAROL, "com.atproto.space.defs#repoRemoved"], + ]); + expect(after.repos[1]!.repoRev).toBeUndefined(); }); - it("refuses unauthorised, mismatched and future notifyWrites", async () => { + it("refuses unauthorised, mismatched and future notifyRepoUpdates", async () => { const space = await createSpace(); const now = Date.now(); - const stranger = await notifyWrite( - space, - BOB, - bobKeypair, - tidAt(now), - repoData(1), - ); + const stranger = await notifyRepoUpdate(space, BOB, bobKeypair, tidAt(now), repoData(1)); expect(stranger.status).toBe(403); await putMember(space, BOB, true, false); - const readOnly = await notifyWrite( - space, - BOB, - bobKeypair, - tidAt(now), - repoData(1), - ); + const readOnly = await notifyRepoUpdate(space, BOB, bobKeypair, tidAt(now), repoData(1)); expect(readOnly.status).toBe(403); + // Under publicWrite, a member denied write stays excluded. const open = await createSpace({ ...MEMBERSPACE, publicWrite: true }); + await putMember(open, CAROL, true, false); + expect( + (await notifyRepoUpdate(open, CAROL, carolKeypair, tidAt(now), repoData(1))).status, + ).toBe(403); expect( - (await notifyWrite(open, BOB, bobKeypair, tidAt(now), repoData(1))) - .status, + (await notifyRepoUpdate(open, BOB, bobKeypair, tidAt(now), repoData(1))).status, ).toBe(200); - const future = await notifyWrite( + const future = await notifyRepoUpdate( open, BOB, bobKeypair, @@ -1149,7 +1306,7 @@ describe("space routes: sync (S2-S4)", () => { ); expect(future.status).toBe(400); expect(await errorOf(future)).toBe("FutureRev"); - const wrongAud = await notifyWrite( + const wrongAud = await notifyRepoUpdate( open, BOB, bobKeypair, @@ -1162,22 +1319,17 @@ describe("space routes: sync (S2-S4)", () => { const token = await serviceJwt( CAROL, OPERATOR, - "com.atproto.space.notifyWrite", + "com.atproto.space.notifyRepoUpdate", carolKeypair, ); const impersonation = await post( - "/xrpc/com.atproto.space.notifyWrite", - { - space: open, - repo: BOB, - repoRev: tidAt(now + 2), - data: { $bytes: "AA==" }, - }, + "/xrpc/com.atproto.space.notifyRepoUpdate", + { space: open, repo: BOB, repoRev: tidAt(now + 2), data: { $bytes: "AA==" } }, { Authorization: `Bearer ${token}` }, ); expect(impersonation.status).toBe(403); - const unknown = await notifyWrite( + const unknown = await notifyRepoUpdate( `at://${OPERATOR}/space/app.bsky.group/notreal`, BOB, bobKeypair, @@ -1188,66 +1340,6 @@ describe("space routes: sync (S2-S4)", () => { expect(await errorOf(unknown)).toBe("SpaceNotFound"); }); - it("removeWriter and revoking write access drop writers from listRepos", async () => { - const space = await createSpace(); - await putMember(space, BOB); - await putMember(space, CAROL); - const t = Date.now(); - await notifyWrite(space, BOB, bobKeypair, tidAt(t - 2000), repoData(1)); - await notifyWrite(space, CAROL, carolKeypair, tidAt(t - 1000), repoData(2)); - const { credential, key } = await obtainCredential(space, { - user: { did: BOB, keypair: bobKeypair }, - }); - const writers = async () => { - const { res } = await credentialRequest( - `/xrpc/com.atproto.space.listRepos?space=${q(space)}`, - credential, - key, - ); - return ( - (await res.json()) as { repos: Array<{ did: string }> } - ).repos.map((r) => r.did); - }; - expect((await writers()).sort()).toEqual([BOB, CAROL].sort()); - expect( - ( - await post("/xrpc/com.atproto.space.removeWriter", { - space, - did: CAROL, - }) - ).status, - ).toBe(200); - expect(await writers()).toEqual([BOB]); - await putMember(space, BOB, true, false); - expect(await writers()).toEqual([]); - }); - - it("requires notifySpaceDeleted to be addressed to this service", async () => { - const foreign = `at://${BOB}/space/app.bsky.group/deleteme`; - await post("/xrpc/com.atproto.space.createRecord", { - space: foreign, - repo: OPERATOR, - collection: "app.bsky.feed.post", - rkey: "d", - record: { $type: "app.bsky.feed.post", text: "x" }, - }); - const send = async (aud: string, iss = BOB, keypair = bobKeypair) => - post( - "/xrpc/com.atproto.space.notifySpaceDeleted", - { space: foreign }, - { - Authorization: `Bearer ${await serviceJwt(iss, aud, "com.atproto.space.notifySpaceDeleted", keypair)}`, - }, - ); - expect((await send("did:web:someone-else.test")).status).toBe(403); - expect((await send(OPERATOR, CAROL, carolKeypair)).status).toBe(403); - expect((await send(`${OPERATOR}#atproto_space_syncer`)).status).toBe(200); - const read = await get( - `/xrpc/com.atproto.space.getRecord?space=${q(foreign)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=d`, - ); - expect(await errorOf(read)).toBe("SpaceNotFound"); - }); - it("delivers writes in foreign spaces to the authority, queueing retryable failures (S3)", async () => { const foreign = `at://${BOB}/space/app.bsky.group/writer${spaceN++}`; const stub = env.SPACES.get(env.SPACES.idFromName(foreign)); @@ -1261,23 +1353,14 @@ describe("space routes: sync (S2-S4)", () => { }); await vi.waitFor(() => expect(outbound.length).toBeGreaterThan(before)); const call = outbound[outbound.length - 1]!; - expect(call.url).toBe( - "https://bob.test/xrpc/com.atproto.space.notifyWrite", - ); + expect(call.url).toBe("https://bob.test/xrpc/com.atproto.space.notifyRepoUpdate"); const body = JSON.parse(String(call.init!.body)) as Record; - expect(Object.keys(body).sort()).toEqual([ - "data", - "repo", - "repoRev", - "space", - ]); + expect(Object.keys(body).sort()).toEqual(["data", "repo", "repoRev", "space"]); expect(body.repo).toBe(OPERATOR); expect((await stub.rpcStatus()).queuedNotifications).toBe(0); setOutboundResponse((url) => - url.includes("notifyWrite") - ? new Response("down", { status: 503 }) - : null, + url.includes("notifyRepoUpdate") ? new Response("down", { status: 503 }) : null, ); try { for (const rkey of ["w2", "w3"]) { @@ -1298,7 +1381,12 @@ describe("space routes: sync (S2-S4)", () => { setOutboundResponse(() => null); } // Coalesced: one pending retry, for the newest revision. - expect((await stub.rpcStatus()).queuedNotifications).toBe(1); + const pending = await queued(foreign); + expect(pending).toHaveLength(1); + expect(pending[0]).toMatchObject({ + policy: "repo", + lxm: "com.atproto.space.notifyRepoUpdate", + }); }); }); @@ -1312,21 +1400,23 @@ describe("space routes: blobs (S6)", () => { return cid; } - const blobRecord = (cid: string) => ({ - $type: "app.bsky.feed.post", - text: "with blob", - embed: { - $type: "blob", - ref: { $link: cid }, - mimeType: "text/plain", - size: 9, - }, - }); - it("serves space blobs only with authorisation and no-store headers", async () => { const space = await createSpace(); const cid = await stageBlob("blob data"); - await createRecord(space, blobRecord(cid), "b"); + await createRecord( + space, + { + $type: "app.bsky.feed.post", + text: "with blob", + embed: { + $type: "blob", + ref: { $link: cid }, + mimeType: "text/plain", + size: 9, + }, + }, + "b", + ); const path = `/xrpc/com.atproto.space.getBlob?space=${q(space)}&repo=${OPERATOR}&cid=${cid}`; expect((await get(path, {})).status).toBe(401); const res = await get(path); @@ -1343,16 +1433,16 @@ describe("space routes: blobs (S6)", () => { }); describe("space routes: lifecycle and management", () => { - it("deleteSpace tombstones: reads fail, credentials answer SpaceDeleted", async () => { + it("deleteSpace tombstones: reads fail, authorisation answers SpaceDeleted, syncers are told", async () => { const space = await createSpace({ ...MEMBERSPACE, publicRead: true }); await createRecord(space, { $type: "app.bsky.feed.post", text: "x" }, "x"); + const token = `del-${spaceN}`; + syncerTokens.set(space, token); + await obtainCredential(space, { notify: { endpoint: SYNCER, token } }); await putMember(space, BOB); - expect( - (await post("/xrpc/com.atproto.space.deleteSpace", { space })).status, - ).toBe(200); - expect( - (await post("/xrpc/com.atproto.space.deleteSpace", { space })).status, - ).toBe(200); + + expect((await post("/xrpc/com.atproto.space.deleteSpace", { space })).status).toBe(200); + expect((await post("/xrpc/com.atproto.space.deleteSpace", { space })).status).toBe(200); const read = await get( `/xrpc/com.atproto.space.getRecord?space=${q(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=x`, ); @@ -1360,22 +1450,31 @@ describe("space routes: lifecycle and management", () => { const withToken = await obtainCredential(space, { user: { did: BOB, keypair: bobKeypair }, }); - expect((withToken.body as { error: string }).error).toBe("SpaceDeleted"); + expect(withToken.body.error).toBe("SpaceDeleted"); const anon = await obtainCredential(space); - expect((anon.body as { error: string }).error).toBe("SpaceDeleted"); + expect(anon.body.error).toBe("SpaceDeleted"); + + const notices = (await queued(space)).filter( + (item) => + (item.body.update as { $type: string }).$type === + "com.atproto.space.notifySpaceUpdate#spaceDeleted", + ); + expect(notices).toHaveLength(1); + expect(notices[0]).toMatchObject({ policy: "syncer", service: SYNCER }); + expect(notices[0]!.body.token).toBe(token); }); it("updateSpace replaces the policy, and a new $type discards the member list", async () => { const space = await createSpace(); await putMember(space, BOB); const getSpace = async () => - (await ( - await get(`/xrpc/com.atproto.space.getSpace?space=${q(space)}`) - ).json()) as { - uri: string; + (await (await get(`/xrpc/com.atproto.space.getSpace?space=${q(space)}`)).json()) as { + space: string; policy: Record; }; - expect((await getSpace()).policy).toEqual({ + const described = await getSpace(); + expect(described.space).toBe(space); + expect(described.policy).toEqual({ $type: "com.atproto.memberspace.policy", publicRead: false, publicWrite: false, @@ -1393,9 +1492,7 @@ describe("space routes: lifecycle and management", () => { ).toBe(200); expect((await getSpace()).policy.publicRead).toBe(true); expect((await getSpace()).policy.extra).toBeUndefined(); - const members = await get( - `/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`, - ); + const members = await get(`/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`); expect(((await members.json()) as { members: unknown[] }).members).toEqual([ { did: BOB, read: true, write: true }, ]); @@ -1407,20 +1504,54 @@ describe("space routes: lifecycle and management", () => { expect((await getSpace()).policy).toEqual({ $type: "com.atproto.personalspace.policy", }); - const mismatch = await get( - `/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`, - ); + const mismatch = await get(`/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`); expect(await errorOf(mismatch)).toBe("PolicyMismatch"); - await post("/xrpc/com.atproto.space.updateSpace", { + await post("/xrpc/com.atproto.space.updateSpace", { space, policy: MEMBERSPACE }); + const after = await get(`/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`); + expect(((await after.json()) as { members: unknown[] }).members).toEqual([]); + }); + + it("batches member changes in one commit", async () => { + const space = await createSpace({ ...MEMBERSPACE, publishMembers: true }); + const put = await post("/xrpc/com.atproto.memberspace.putMembers", { space, - policy: MEMBERSPACE, + members: [ + { did: BOB, read: true, write: true }, + { did: CAROL, read: true, write: true }, + { did: BOB, read: true, write: false }, + ], }); - const after = await get( - `/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`, - ); - expect(((await after.json()) as { members: unknown[] }).members).toEqual( - [], - ); + expect(put.status).toBe(200); + const listed = async () => + ((await ( + await get(`/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`) + ).json()) as { members: Array<{ did: string; write: boolean }> }).members; + expect(await listed()).toEqual([ + { did: BOB, read: true, write: false }, + { did: CAROL, read: true, write: true }, + ]); + const ops = (await ( + await get(`/xrpc/com.atproto.space.listRepoOps?space=${q(space)}&repo=${OPERATOR}`) + ).json()) as { ops: Array<{ rev: string }> }; + // Both member records, one commit. + expect(new Set(ops.ops.map((op) => op.rev)).size).toBe(1); + + const tooMany = await post("/xrpc/com.atproto.memberspace.putMembers", { + space, + members: Array.from({ length: 101 }, (_, i) => ({ + did: `did:web:m${i}.test`, + read: true, + write: true, + })), + }); + expect(tooMany.status).toBe(400); + + const removed = await post("/xrpc/com.atproto.memberspace.removeMembers", { + space, + dids: [CAROL, "did:web:nobody.test"], + }); + expect(removed.status).toBe(200); + expect((await listed()).map((m) => m.did)).toEqual([BOB]); }); it("getSpace is the owner's, by session only", async () => { @@ -1445,8 +1576,8 @@ describe("space routes: lifecycle and management", () => { expect(update.status).toBe(403); const manager = `Bearer scoped:${JSON.stringify({ manage: ["update"] })}`; const member = await post( - "/xrpc/com.atproto.memberspace.putMember", - { space, did: BOB, read: true, write: false }, + "/xrpc/com.atproto.memberspace.putMembers", + { space, members: [{ did: BOB, read: true, write: false }] }, { Authorization: manager }, ); expect(member.status).toBe(200); @@ -1458,7 +1589,7 @@ describe("space routes: lifecycle and management", () => { expect(del.status).toBe(403); }); - it("refuses unsupported policies and memberspace methods elsewhere", async () => { + it("refuses unsupported policies, bare managing apps and memberspace methods elsewhere", async () => { const res = await post("/xrpc/com.atproto.space.createSpace", { spaceType: "app.bsky.group", policy: { $type: "com.example.custom.policy" }, @@ -1466,15 +1597,22 @@ describe("space routes: lifecycle and management", () => { expect(res.status).toBe(400); expect(await errorOf(res)).toBe("UnsupportedPolicy"); + const bare = await post("/xrpc/com.atproto.space.createSpace", { + spaceType: "app.bsky.group", + policy: { + $type: "com.atproto.managedspace.policy", + managingApp: "did:web:manager.test", + }, + }); + expect(bare.status).toBe(400); + const managed = await createSpace({ $type: "com.atproto.managedspace.policy", - managingApp: "did:web:manager.test", + managingApp: "did:web:manager.test#forum", }); - const put = await post("/xrpc/com.atproto.memberspace.putMember", { + const put = await post("/xrpc/com.atproto.memberspace.putMembers", { space: managed, - did: BOB, - read: true, - write: true, + members: [{ did: BOB, read: true, write: true }], }); expect(await errorOf(put)).toBe("PolicyMismatch"); @@ -1482,8 +1620,7 @@ describe("space routes: lifecycle and management", () => { space: `at://${BOB}/space/app.bsky.group/x`, policy: MEMBERSPACE, }); - expect(notOwner.status).toBe(403); - expect(await errorOf(notOwner)).toBe("NotSpaceOwner"); + expect(await errorOf(notOwner)).toBe("NotAuthorized"); }); it("publishes the policy and member list into the authority's repo", async () => { @@ -1496,17 +1633,15 @@ describe("space routes: lifecycle and management", () => { await putMember(space, CAROL); const list = async () => { const res = await get( - `/xrpc/com.atproto.space.listRecords?space=${q(space)}&repo=${OPERATOR}&reverse=true`, + `/xrpc/com.atproto.space.listRecords?space=${q(space)}&repo=${OPERATOR}`, ); - return ( - (await res.json()) as { - records: Array<{ - collection: string; - rkey: string; - value: Record; - }>; - } - ).records; + return ((await res.json()) as { + records: Array<{ + collection: string; + rkey: string; + value: Record; + }>; + }).records.reverse(); }; let records = await list(); expect(records.map((r) => `${r.collection}/${r.rkey}`)).toEqual([ @@ -1519,80 +1654,74 @@ describe("space routes: lifecycle and management", () => { read: true, write: false, }); - expect( - (records[2]!.value.policy as { publishMembers: boolean }).publishMembers, - ).toBe(true); - await post("/xrpc/com.atproto.memberspace.removeMember", { + await post("/xrpc/com.atproto.memberspace.removeMembers", { space, - did: CAROL, + dids: [CAROL], }); await post("/xrpc/com.atproto.space.updateSpace", { space, policy: { ...MEMBERSPACE, publishPolicy: true }, }); records = await list(); - expect(records.map((r) => r.collection)).toEqual([ - "com.atproto.space.policy", - ]); + expect(records.map((r) => r.collection)).toEqual(["com.atproto.space.policy"]); + }); + + it("lists the operator's spaces with its repo state and the space revision", async () => { + const space = await createSpace({ ...MEMBERSPACE, publicRead: true }, "app.bsky.listtest"); + await createRecord(space, { $type: "app.bsky.feed.post", text: "x" }, "x"); + const res = await get( + `/xrpc/com.atproto.space.listSpaces?spaceType=app.bsky.listtest&spaceDid=${OPERATOR}`, + ); + const body = (await res.json()) as { + spaces: Array<{ + space: string; + repoRev?: string; + data?: { $bytes: string }; + spaceRev?: string; + }>; + }; + const entry = body.spaces.find((s) => s.space === space)!; + expect(entry.repoRev).toMatch(/^[2-7a-z]{13}$/); + expect(fromBase64(entry.data!.$bytes)).toHaveLength(32); + expect(entry.spaceRev).toMatch(/^[2-7a-z]{13}$/); + + const bad = await get("/xrpc/com.atproto.space.listSpaces?cursor=nonsense"); + expect(await errorOf(bad)).toBe("InvalidCursor"); }); it("round-trips a space through exportSpaceMeta/getRepo and their imports", async () => { const space = await createSpace({ ...MEMBERSPACE, publishPolicy: true }); await putMember(space, BOB, true, false); await putMember(space, CAROL); - await notifyWrite( - space, - CAROL, - carolKeypair, - tidAt(Date.now() - 1000), - repoData(7), - ); - await createRecord( - space, - { $type: "app.bsky.feed.post", text: "keep me" }, - "k", - ); + await notifyRepoUpdate(space, CAROL, carolKeypair, tidAt(Date.now() - 1000), repoData(7)); + await createRecord(space, { $type: "app.bsky.feed.post", text: "keep me" }, "k"); - const meta = await get( - `/xrpc/com.atproto.space.exportSpaceMeta?space=${q(space)}`, - ); + const meta = await get(`/xrpc/com.atproto.space.exportSpaceMeta?space=${q(space)}`); expect(meta.status).toBe(200); + expect(meta.headers.get("content-type")).toBe(STAR); const metaBytes = new Uint8Array(await meta.arrayBuffer()); - const repo = await get( - `/xrpc/com.atproto.space.getRepo?space=${q(space)}&repo=${OPERATOR}`, - ); + const repo = await get(`/xrpc/com.atproto.space.getRepo?space=${q(space)}&repo=${OPERATOR}`); const repoBytes = new Uint8Array(await repo.arrayBuffer()); await post("/xrpc/com.atproto.space.deleteSpace", { space }); // The authority's repo can't arrive before its space. - const early = await app.request("/xrpc/com.atproto.space.importRepo", { - method: "POST", - headers: { ...SESSION, "Content-Type": "application/octet-stream" }, - body: repoBytes, - }); + const early = await postStar("/xrpc/com.atproto.space.importRepo", repoBytes); expect(await errorOf(early)).toBe("SpaceNotFound"); - const importMeta = await app.request( - "/xrpc/com.atproto.space.importSpaceMeta", - { - method: "POST", - headers: { ...SESSION, "Content-Type": "application/octet-stream" }, - body: metaBytes, - }, - ); - expect(importMeta.status).toBe(200); - const importRepo = await app.request("/xrpc/com.atproto.space.importRepo", { + // The STAR media type is required. + const wrongType = await app.request("/xrpc/com.atproto.space.importSpaceMeta", { method: "POST", headers: { ...SESSION, "Content-Type": "application/octet-stream" }, - body: repoBytes, + body: metaBytes, }); - expect(importRepo.status).toBe(200); + expect(wrongType.status).toBe(400); - const members = await get( - `/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`, - ); + expect((await postStar("/xrpc/com.atproto.space.importSpaceMeta", metaBytes)).status).toBe(200); + expect((await postStar("/xrpc/com.atproto.space.importRepo", repoBytes)).status).toBe(200); + + const members = await get(`/xrpc/com.atproto.memberspace.listMembers?space=${q(space)}`); expect(((await members.json()) as { members: unknown[] }).members).toEqual([ { did: BOB, read: true, write: false }, { did: CAROL, read: true, write: true }, @@ -1600,66 +1729,44 @@ describe("space routes: lifecycle and management", () => { const record = await get( `/xrpc/com.atproto.space.getRecord?space=${q(space)}&repo=${OPERATOR}&collection=app.bsky.feed.post&rkey=k`, ); - expect( - ((await record.json()) as { value: { text: string } }).value.text, - ).toBe("keep me"); + expect(((await record.json()) as { value: { text: string } }).value.text).toBe("keep me"); const { credential, key } = await obtainCredential(space, { user: { did: CAROL, keypair: carolKeypair }, }); const { res } = await credentialRequest( - `/xrpc/com.atproto.space.listRepos?space=${q(space)}`, + `/xrpc/com.atproto.space.listWriters?space=${q(space)}`, credential, key, ); - const writers = ( - (await res.json()) as { repos: Array<{ did: string }> } - ).repos.map((r) => r.did); + const writers = ((await res.json()) as { repos: Array<{ repo: string }> }).repos.map( + (r) => r.repo, + ); expect(writers).toContain(CAROL); + + const garbage = await postStar("/xrpc/com.atproto.space.importSpaceMeta", new Uint8Array([1, 2, 3])); + expect(await errorOf(garbage)).toBe("InvalidSpaceMeta"); }); - it("importRepo refuses another account's archive and non-canonical records", async () => { + it("importRepo refuses another account's archive and malformed archives", async () => { const space = `at://${BOB}/space/app.bsky.group/imp${spaceN++}`; const record = { $type: "app.bsky.feed.post", text: "x" }; const bytes = encode(record); - const { cidForCbor } = await import("@atproto/lex-data"); const cid = await cidForCbor(bytes); - const data = new LtHash() - .add(`app.bsky.feed.post/r/${cid.toString()}`) - .digest(); - const archive = async (repo: string) => { - const chunks: Uint8Array[] = []; - for await (const chunk of serializeRepo( - { - ver: 1, - repo: repo as never, - space: space as never, - rev: tidAt(Date.now()), - data, - }, - [ - { - collection: "app.bsky.feed.post" as never, - rkey: "r" as never, - bytes, - }, - ], - )) { - chunks.push(chunk); - } - return new Uint8Array(await new Blob(chunks).arrayBuffer()); - }; - const send = async (body: Uint8Array) => - app.request("/xrpc/com.atproto.space.importRepo", { - method: "POST", - headers: { ...SESSION, "Content-Type": "application/octet-stream" }, - body, - }); - const theirs = await send(await archive(BOB)); + const data = new LtHash().add(`app.bsky.feed.post/r/${cid.toString()}`).digest(); + const archive = (repo: Did) => + starArchive( + { ver: 1, repo, space: space as never, rev: tidAt(Date.now()) as never, data }, + [{ collection: "app.bsky.feed.post", rkey: "r", bytes }], + ); + const theirs = await postStar("/xrpc/com.atproto.space.importRepo", await archive(BOB)); expect(theirs.status).toBe(400); + expect(await errorOf(theirs)).toBe("RepoMismatch"); + const garbage = await postStar("/xrpc/com.atproto.space.importRepo", new Uint8Array([9, 9, 9])); + expect(await errorOf(garbage)).toBe("InvalidRepoFile"); const ours = await archive(OPERATOR); // Sanity: the archive is readable before import. const read = await readRepoStar([ours]); await read[Symbol.asyncDispose](); - expect((await send(ours)).status).toBe(200); + expect((await postStar("/xrpc/com.atproto.space.importRepo", ours)).status).toBe(200); }); }); diff --git a/packages/spaces/test/space-do.test.ts b/packages/spaces/test/space-do.test.ts index 83b2093..80836e1 100644 --- a/packages/spaces/test/space-do.test.ts +++ b/packages/spaces/test/space-do.test.ts @@ -1,16 +1,16 @@ import { env, runInDurableObject } from "cloudflare:test"; import { describe, expect, it } from "vitest"; import { - COMMIT_MAC_TYPE, + COMMIT_MAC_PROFILE, LtHash, RepoCommit, - computeCommitMac, encapsulate, + formatMacRequest, verifyCommit, } from "@atproto/space"; import { P256Keypair } from "@atproto/crypto"; import { encode } from "@atproto/lex-cbor"; -import { buildCommit, macSecret } from "../src/mac"; +import { buildCommit, commitMacHeaders, macRequest } from "../src/mac"; import type { PreparedSpaceWrite, SpacePolicy } from "../src/types"; import { TEST_KEM_KEY, @@ -157,44 +157,34 @@ describe("SpaceDurableObject", () => { state: state!, }); const kemDid = (await P256Keypair.import(TEST_KEM_KEY)).did(); - const { keyShare, sharedSecret } = await encapsulate(kemDid); - const { formatWantMacHeader } = await import("@atproto/space"); - const hostSecret = await macSecret({ - wantMac: formatWantMacHeader(COMMIT_MAC_TYPE, keyShare), + const { keyShare, sharedSecret } = await encapsulate(kemDid as never); + const mac = await macRequest({ + acceptSignature: formatMacRequest(COMMIT_MAC_PROFILE, keyShare), credential: true, - type: COMMIT_MAC_TYPE, + profile: COMMIT_MAC_PROFILE, getKemKeypair: () => P256Keypair.import(TEST_KEM_KEY), }); - const mac = computeCommitMac(hostSecret!, commit as never); - expect( + const headers = new Headers(commitMacHeaders(mac, commit)); + expect(headers.get("atproto-space-commit")).toContain("ver=1"); + // Throws unless the MAC and the covered header match the commit. + verifyCommit(commit as never, { + space: uri as never, + repo: AUTHORITY as never, + keyShare, + sharedSecret, + headers, + }); + // The MAC is per request: another shared secret does not verify it. + const other = await encapsulate(kemDid as never); + expect(() => verifyCommit(commit as never, { - space: uri, - repo: AUTHORITY, - sharedSecret, - mac, + space: uri as never, + repo: AUTHORITY as never, + keyShare: other.keyShare, + sharedSecret: other.sharedSecret, + headers, }), - ).toBe(true); - }); - - it("orders records by path bytes for archives", async () => { - const { uri, stub } = freshSpace(); - await initSpace(stub, uri); - await stub.rpcApplyWrites([ - { ...write("create", "z", { n: 1 }), collection: "app.bsky.feed" }, - { ...write("create", "a", { n: 2 }), collection: "app.bsky.feed.post" }, - ]); - const page = await stub.rpcListRecordsByPath({ limit: 1 }); - // "app.bsky.feed.post/a" < "app.bsky.feed/z" byte-wise ('.' < '/'). - expect(page.records.map((r) => r.collection)).toEqual([ - "app.bsky.feed.post", - ]); - expect(page.hasMore).toBe(true); - const next = await stub.rpcListRecordsByPath({ - afterPath: "app.bsky.feed.post/a", - limit: 10, - }); - expect(next.records.map((r) => r.collection)).toEqual(["app.bsky.feed"]); - expect(next.state?.rev).toBe(page.state?.rev); + ).toThrow(); }); it("rejects duplicate creates and missing updates/deletes", async () => { @@ -296,14 +286,15 @@ describe("SpaceDurableObject", () => { expect(op3?.prev).toBe(w1.cid); expect(op3?.bytes).not.toBeUndefined(); - // since filters by rev; a full page withholds head. + // since filters by rev; every page carries the head. const sinceR1 = await stub.rpcListRepoOps({ since: r1.rev, limit: 100 }); expect(sinceR1.ops).toHaveLength(1); expect(sinceR1.ops[0]?.rev).toBe(r2.rev); const paged = await stub.rpcListRepoOps({ limit: 2 }); expect(paged.ops).toHaveLength(2); - expect(paged.head).toBeUndefined(); + expect(paged.hasMore).toBe(true); + expect(paged.head?.rev).toBe(r2.rev); const rest = await stub.rpcListRepoOps({ after: { rev: paged.ops[1]!.rev, idx: paged.ops[1]!.idx }, limit: 2, @@ -348,8 +339,12 @@ describe("SpaceDurableObject", () => { it("manages members with read and write access", async () => { const { uri, stub } = freshSpace(); await initSpace(stub, uri); - await stub.rpcPutMember("did:web:bob.test", { read: true, write: false }); - await stub.rpcPutMember("did:web:carol.test", { read: true, write: true }); + await stub.rpcPutMembers([ + { did: "did:web:bob.test", read: false, write: false }, + { did: "did:web:carol.test", read: true, write: true }, + // A DID listed twice takes its last entry. + { did: "did:web:bob.test", read: true, write: false }, + ]); expect(await stub.rpcGetMember("did:web:bob.test")).toEqual({ did: "did:web:bob.test", read: true, @@ -358,8 +353,10 @@ describe("SpaceDurableObject", () => { const members = await stub.rpcListMembers({ limit: 1 }); expect(members.members.map((m) => m.did)).toEqual(["did:web:bob.test"]); expect(members.hasMore).toBe(true); - await stub.rpcRemoveMember("did:web:bob.test"); + // Non-members are ignored. + await stub.rpcRemoveMembers(["did:web:bob.test", "did:web:nobody.test"]); expect(await stub.rpcGetMember("did:web:bob.test")).toBe(null); + expect(await stub.rpcGetMember("did:web:carol.test")).not.toBe(null); }); it("sequences writers by space revision, monotonic per writer", async () => { @@ -412,40 +409,144 @@ describe("SpaceDurableObject", () => { }); expect(after.map((w) => w.did)).toEqual(["did:web:bob.test"]); + // A removal is sequenced like a write, and listed until the repo + // writes again. + await stub.rpcRemoveWriter("did:web:bob.test"); + const removed = await stub.rpcListWriters({ limit: 10 }); + expect(removed.map((w) => [w.did, w.removed])).toEqual([ + ["did:web:carol.test", false], + ["did:web:bob.test", true], + ]); + expect(removed[1]!.spaceRev > third!.spaceRev).toBe(true); + expect(await stub.rpcGetSpaceRev()).toBe(removed[1]!.spaceRev); + // Removing again is a no-op that doesn't advance the space. await stub.rpcRemoveWriter("did:web:bob.test"); + expect(await stub.rpcGetSpaceRev()).toBe(removed[1]!.spaceRev); + // A newer write re-adds it. + await stub.rpcRecordWriter("did:web:bob.test", "3mzzzzzzzzzzz", data); + const readded = await stub.rpcListWriters({ limit: 10 }); + expect(readded.find((w) => w.did === "did:web:bob.test")?.removed).toBe( + false, + ); + // Revoking write access removes a member from the writer set, and + // the export leaves removed writers out. + await stub.rpcPutMembers([ + { did: "did:web:carol.test", read: true, write: false }, + ]); expect( - (await stub.rpcListWriters({ limit: 10 })).map((w) => w.did), - ).toEqual(["did:web:carol.test"]); - // Revoking write access drops a member from the writer set. - await stub.rpcPutMember("did:web:carol.test", { read: true, write: false }); - expect(await stub.rpcListWriters({ limit: 10 })).toEqual([]); + (await stub.rpcListWriters({ limit: 10 })).find( + (w) => w.did === "did:web:carol.test", + )?.removed, + ).toBe(true); + expect((await stub.rpcExportMeta()).writers.map((w) => w.did)).toEqual([ + "did:web:bob.test", + ]); }); - it("registers and unregisters notification services", async () => { + it("queues writer-set changes to active registrations, and one expiry notice to lapsed ones", async () => { const { uri, stub } = freshSpace(); await initSpace(stub, uri); - const reg = await stub.rpcRegisterNotify( - "did:web:syncer.test", - "https://syncer.test", - ); - expect(Date.parse(reg.expiresAt)).toBeGreaterThan(Date.now()); - expect(await stub.rpcGetActiveRegistrations()).toEqual([ + const active = { endpoint: "https://active.test", token: "a" }; + const lapsed = { endpoint: "https://lapsed.test", token: "l" }; + await stub.rpcPutNotifyRegistration(active, Date.now() + 600_000); + await stub.rpcPutNotifyRegistration(lapsed, Date.now() - 1); + expect(await stub.rpcGetNotifyRegistration(active)).not.toBe(null); + + const queued = async () => + runInDurableObject(stub, async (_i, state) => + state.storage.sql + .exec( + "SELECT service, body, policy, auth FROM notify_queue ORDER BY id", + ) + .toArray() + .map((row) => ({ + service: row.service as string, + policy: row.policy as string, + auth: row.auth as string, + update: ( + JSON.parse(row.body as string).body as { + update: { $type: string }; + } + ).update.$type, + })), + ); + + const data = new Uint8Array(32).fill(1); + await stub.rpcRecordWriter("did:web:bob.test", "3kzzzzzzzzzzz", data); + expect(await queued()).toEqual([ + { + service: "https://active.test", + policy: "fanout", + auth: "none", + update: "com.atproto.space.defs#repoWrite", + }, { - service: "did:web:syncer.test", - endpoint: "https://syncer.test", - expiresAt: reg.expiresAt, + service: "https://lapsed.test", + policy: "syncer", + auth: "none", + update: "com.atproto.space.notifySpaceUpdate#registrationExpired", }, ]); - await stub.rpcUnregisterNotify("did:web:syncer.test"); - expect(await stub.rpcGetActiveRegistrations()).toEqual([]); - // Idempotent unregister. - await stub.rpcUnregisterNotify("did:web:syncer.test"); + // The lapse is announced once, however many updates follow. + await stub.rpcRemoveWriter("did:web:bob.test"); + const after = await queued(); + expect( + after.filter((q) => q.service === "https://lapsed.test"), + ).toHaveLength(1); + expect(after.at(-1)).toMatchObject({ + service: "https://active.test", + update: "com.atproto.space.defs#repoRemoved", + }); + + // Withdrawing a registration stops its deliveries. + await stub.rpcRemoveNotifyRegistration(active); + expect(await stub.rpcGetNotifyRegistration(active)).toBe(null); + }); + + it("queues a deletion notice to every registration, lapsed included", async () => { + const { uri, stub } = freshSpace(); + await initSpace(stub, uri); + await stub.rpcPutNotifyRegistration( + { endpoint: "https://a.test", token: "a" }, + Date.now() + 600_000, + ); + await stub.rpcPutNotifyRegistration( + { endpoint: "https://b.test", token: "b" }, + Date.now() - 1, + ); + await stub.rpcDeleteSpace(); + const rows = await runInDurableObject(stub, async (_i, state) => + state.storage.sql + .exec("SELECT service, body FROM notify_queue ORDER BY service") + .toArray(), + ); + expect( + rows.map((row) => [ + row.service, + (JSON.parse(row.body as string).body as { update: { $type: string } }) + .update.$type, + ]), + ).toEqual([ + ["https://a.test", "com.atproto.space.notifySpaceUpdate#spaceDeleted"], + ["https://b.test", "com.atproto.space.notifySpaceUpdate#spaceDeleted"], + ]); + // No registration survives on a deleted space. + expect( + await rpcError(stub, (i) => + i.rpcPutNotifyRegistration( + { endpoint: "https://a.test", token: "a" }, + 1, + ), + ), + ).toMatch(/SpaceDeleted/); }); it("replaces the policy, discarding members when its $type changes", async () => { const { uri, stub } = freshSpace(); await initSpace(stub, uri); - await stub.rpcPutMember("did:web:bob.test", { read: true, write: true }); + await stub.rpcPutMembers([ + { did: "did:web:bob.test", read: true, write: true }, + ]); expect( await stub.rpcUpdatePolicy({ ...MEMBERSPACE, publicRead: true }), ).toBe(null); @@ -566,8 +667,7 @@ describe("SpaceDurableObject", () => { await stub.rpcApplyWrites([ write("create", "gone", { $type: "app.bsky.feed.post" }), ]); - const del = await stub.rpcDeleteSpace(); - expect(del.registrations).toEqual([]); + await stub.rpcDeleteSpace(); // Tombstone: reads fail SpaceNotFound, authority state shows deleted. expect( @@ -577,7 +677,7 @@ describe("SpaceDurableObject", () => { expect(state.meta?.deletedAt).not.toBe(null); expect(state.policy).toBe(null); // Idempotent delete. - expect((await stub.rpcDeleteSpace()).registrations).toEqual([]); + await stub.rpcDeleteSpace(); // Re-creation revives with a clean slate. await initSpace(stub, uri); @@ -709,4 +809,36 @@ describe("SpaceDurableObject", () => { }); expect(statuses).toEqual([503, 400]); }); + + it("unregisters a syncer that rejects its expiry notice, unless it renewed", async () => { + const { uri, stub } = freshSpace(); + await initSpace(stub, uri); + const rejecting = { endpoint: "https://reject.test", token: "r" }; + const renewing = { endpoint: "https://renew.test", token: "n" }; + await stub.rpcPutNotifyRegistration(rejecting, Date.now() - 1); + await stub.rpcPutNotifyRegistration(renewing, Date.now() - 1); + await stub.rpcRecordWriter( + "did:web:bob.test", + "3kzzzzzzzzzzz", + new Uint8Array(32), + ); + // The renewing syncer reauthorises before its notice goes out. + await stub.rpcPutNotifyRegistration(renewing, Date.now() + 600_000); + const delivered: string[] = []; + await runInDurableObject(stub, async (instance, state) => { + (globalThis as { fetch: typeof fetch }).fetch = (async ( + input: RequestInfo | URL, + ) => { + delivered.push(new URL(String(input)).origin); + return new Response("{}", { status: 400 }); + }) as typeof fetch; + state.storage.sql.exec("UPDATE notify_queue SET next_at = 0"); + await instance.alarm(); + }); + // Only the still-lapsed one was sent its notice; its rejection + // unregistered it. + expect(delivered).toEqual(["https://reject.test"]); + expect(await stub.rpcGetNotifyRegistration(rejecting)).toBe(null); + expect(await stub.rpcGetNotifyRegistration(renewing)).not.toBe(null); + }); }); From d7fabc71e0814fa8457525d2311c972d54335f42 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 04:51:11 +0000 Subject: [PATCH 12/16] spaces: rewire conformance runner, validate listMembers cursor, docs for 1112 Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LZ7qcQNQoiA6a23woGC7tB --- .changeset/spaces-alpha-20261112.md | 16 ++++ docs/src/content/docs/concepts/spaces.md | 8 +- docs/src/content/docs/guides/enable-spaces.md | 10 +++ packages/spaces/src/routes.ts | 8 +- packages/spaces/test/conformance.test.ts | 70 ++++------------ packages/spaces/test/routes.test.ts | 2 +- plans/in-progress/spaces.md | 79 ++++++++++++++++++- 7 files changed, 128 insertions(+), 65 deletions(-) create mode 100644 .changeset/spaces-alpha-20261112.md diff --git a/.changeset/spaces-alpha-20261112.md b/.changeset/spaces-alpha-20261112.md new file mode 100644 index 0000000..1c718d6 --- /dev/null +++ b/.changeset/spaces-alpha-20261112.md @@ -0,0 +1,16 @@ +--- +"@getcirrus/pds": minor +"@getcirrus/spaces": minor +"@getcirrus/oauth-provider": minor +--- + +Update atproto spaces to the 2026-11-12 alpha (`0.0.0-spaces-alpha-20261112204144`). This is a breaking alpha change: the space schema moves to version 3, so existing space data refuses to open until you run `pds spaces reset`, and apps and syncers built against the 2026-11-05 alpha need updating. + +- Renamed methods: `getSpaceCredential` is now `authorizeSpaceSync` (taking `credentialKey`), `listRepos` is `listWriters`, `notifyWrite` is `notifyRepoUpdate`, `notifyCredentialRevoked` is `notifyCredentialsRevoked` and the managing app's `checkUserAccess` is `checkAccess`. `putMember` / `removeMember` are replaced by batched `putMembers` / `removeMembers` (up to 100 at a time, in one commit). +- Syncers register for notifications by passing a webhook endpoint and token to `authorizeSpaceSync`, which the space host confirms with the syncer's `confirmRegistration` before issuing. Updates go to its `notifySpaceUpdate`; a lapsed registration gets one `registrationExpired` notice, and deleting a space tells every registered syncer, retried for up to 72 hours. `registerNotify`, `unregisterNotify` and `notifySpaceDeleted` are gone. +- Removing a writer is sequenced and announced, and `listWriters` lists removals. +- MACs are HTTP message signatures, requested with `Accept-Signature` and covering an `Atproto-Space-Commit` or `Atproto-Space-Record` header. STAR archives use the `application/vnd.dasl.star` media type. +- A managed space's `managingApp` must name a service (`did#service`). If the app fails, the request fails with `UpstreamFailure` rather than being refused. Under `publicWrite`, a member denied write stays excluded. +- `listRepoOps` returns the commit on every page; `listSpaces` returns each space's repo revision, digest and space revision. +- Error codes renamed: `NotSpaceOwner` → `NotAuthorized`, `UserNotAuthorized` → `AccountNotAuthorized`, `BadSpaceMac` → `InvalidSpaceMac`, `MalformedCursor` → `InvalidCursor`. +- oauth-provider: space permissions carry `spaceType` rather than `type`, space declarations use `title`, and a new `allowsSpace(permissions, check)` helper matches requests against granted scopes. diff --git a/docs/src/content/docs/concepts/spaces.md b/docs/src/content/docs/concepts/spaces.md index c5c3a51..df31de8 100644 --- a/docs/src/content/docs/concepts/spaces.md +++ b/docs/src/content/docs/concepts/spaces.md @@ -24,7 +24,7 @@ Every participant stores *their own* records for a space in their own PDS — th Because Cirrus is single-user, one account wears three hats: - **Repo host** — serving your own permissioned repos, one per space you have written into, whether you own the space or not. -- **Space host** — for spaces you own: issuing credentials to readers, tracking who has written, notifying syncers after writes, and managing membership. +- **Space host** — for spaces you own: issuing credentials to readers, tracking who has written (and who has been removed), notifying syncers of those changes, and managing membership. - **Your PDS** — minting short-lived delegation tokens so apps you've signed into can read spaces hosted elsewhere. ## How access control works @@ -39,15 +39,17 @@ Whether the authority grants a credential is up to the space's **policy**. Cirru - **personalspace**: only you. For bookmarks, drafts, mutes. - **memberspace**: a member list you manage, where each member can be allowed to read, to write, or both. It can be opened to everyone for reading (`publicRead`) or writing (`publicWrite`), and restricted to named apps (`allowedApps`, checked against client attestations). -- **managedspace**: a nominated app service is asked to decide, per user, per request. +- **managedspace**: a nominated app service (named as `did#service`) is asked to decide, per user, per request. If it can't be reached the request fails with `UpstreamFailure`, rather than being treated as a refusal. Someone the policy refuses is told the space doesn't exist, so a refusal reveals nothing about it. A memberspace or managedspace can also publish its policy, and a memberspace its member list, as records in your own repo in the space, so readers can see who else is in it. +A syncer that wants to hear about changes passes a webhook endpoint and a token of its own with its credential request. The first time, your PDS calls the syncer back (`confirmRegistration`) to check it really asked; after that, every writer update goes to the endpoint, with the token, until the registration lapses with the credential. A registration that lapses gets one final notice saying so, and if the space is deleted every syncer that ever registered is told, with retries for up to three days. + Writes never use credentials: they're ordinary authenticated requests to your own PDS, covered by OAuth `space:` grants or your own full-access session. App passwords are deliberately excluded. ## Proving data came from you -Space data isn't signed. Instead, your PDS has a second key, published in your DID document as `#atproto_kem`. A syncer reading your repo sends an ephemeral key with each request, both sides derive a one-off shared secret, and your PDS returns a MAC over the commit or record in an `Atproto-Space-Mac` header. The syncer knows the data is yours; but because the syncer could have computed the same MAC itself, a leaked response proves nothing to anyone else. That's the point: private data shouldn't come with a signature that lets it be passed around as authentic. +Space data isn't signed. Instead, your PDS has a second key, published in your DID document as `#atproto_kem`. A syncer reading your repo sends an ephemeral key with each request, both sides derive a one-off shared secret, and your PDS returns a MAC: an HTTP message signature keyed by that secret, over an `Atproto-Space-Commit` or `Atproto-Space-Record` header describing the data. The syncer knows the data is yours; but because the syncer could have computed the same MAC itself, a leaked response proves nothing to anyone else. That's the point: private data shouldn't come with a signature that lets it be passed around as authentic. Cirrus can't serve space data to syncers without this key. `pds spaces kem` creates it; see [Enable spaces](/guides/enable-spaces/). diff --git a/docs/src/content/docs/guides/enable-spaces.md b/docs/src/content/docs/guides/enable-spaces.md index d694e94..3ec95de 100644 --- a/docs/src/content/docs/guides/enable-spaces.md +++ b/docs/src/content/docs/guides/enable-spaces.md @@ -103,6 +103,16 @@ The dashboard at `/status` gains a **Spaces** panel showing each space's role, p Apps request access with OAuth `space:` scopes, e.g. `space:my.app.bookmarks` for the app's own space type under your authority. The consent screen shows the space type's human name and warns loudly about wildcard grants. App passwords cannot access spaces. +## Upgrading from the 2026-11-05 alpha + +The 2026-11-12 alpha renames most of the sync methods (`getSpaceCredential` is now `authorizeSpaceSync`, `listRepos` is `listWriters`, `notifyWrite` is `notifyRepoUpdate`), batches member changes (`putMembers` / `removeMembers`), replaces `registerNotify` with a webhook the syncer names in its credential request, and moves MACs onto standard HTTP message signature headers. The space schema moves to version 3, so after upgrading: + +1. Deploy. Space endpoints answer 503 until you reset. +2. Run `pds spaces reset`, then recreate your spaces. The KEM key carries over. +3. A managed space's `--managing-app` must now name a service, as `did#service`. + +Apps and syncers built against the 2026-11-05 alpha need updating too. + ## Upgrading from the August alpha The November 2026 alpha replaced simplespace with the baseline policies, credential DPoP with HTTP message signatures, and commit signatures with MACs. Space data from the earlier build can't be read by the new one. After upgrading: diff --git a/packages/spaces/src/routes.ts b/packages/spaces/src/routes.ts index 90b0635..14a4328 100644 --- a/packages/spaces/src/routes.ts +++ b/packages/spaces/src/routes.ts @@ -30,6 +30,7 @@ import { } from "@atproto/lex-data"; import type { LexValue } from "@atproto/lex-data"; import { now as tidNow } from "@atcute/tid"; +import { isDid } from "@atcute/lexicons/syntax"; import { isSpaceCredentialAuth, verifyDelegationToken, @@ -2058,9 +2059,14 @@ export function createSpaceRoutes(host: SpaceRoutesHost): Hono { if (scopeError) return scopeError; assertOwner(ref, session); const limit = clampLimit(c.req.query("limit"), 100, 1000); + // The cursor is the last member DID of the previous page. + const cursor = c.req.query("cursor"); + if (cursor !== undefined && !isDid(cursor)) { + throw new SpaceError("InvalidCursor", `Malformed cursor: ${cursor}`); + } const page = await host.getSpaceDO(ref.uri).rpcListMembers({ limit, - afterDid: c.req.query("cursor"), + afterDid: cursor, }); const last = page.members[page.members.length - 1]; return c.json({ diff --git a/packages/spaces/test/conformance.test.ts b/packages/spaces/test/conformance.test.ts index 67e6492..cab5e74 100644 --- a/packages/spaces/test/conformance.test.ts +++ b/packages/spaces/test/conformance.test.ts @@ -23,10 +23,9 @@ import { } from "@atproto/crypto"; import { ALPHA_BUILD, + createSyncerInbox, filterCatalog, runChecks, - type InboxDelivery, - type SyncerInbox, } from "@getcirrus/space-conformance"; import { KeypairIdentityProvider, @@ -51,64 +50,18 @@ const AUTHORITY_ORIGIN = "https://authority.test"; const operatorKeypair = await Secp256k1Keypair.import(TEST_SIGNING_KEY); const kemKeypair = await P256Keypair.import(TEST_KEM_KEY); -/** An in-process syncer inbox, also answering managing-app queries. */ -function createInbox(): SyncerInbox & { - handle(req: Request): Promise; -} { - const deliveries: InboxDelivery[] = []; - const waiters = new Set<() => void>(); - const responders = new Map unknown>(); - return { - service: `${INBOX_DID}#atproto_space_syncer`, - async handle(req) { - const url = new URL(req.url); - const lxm = url.pathname.replace(/^\/xrpc\//, ""); - const body = - req.method === "POST" ? await req.json().catch(() => null) : undefined; - const delivery: InboxDelivery = { - lxm, - body, - params: Object.fromEntries(url.searchParams), - authorization: req.headers.get("Authorization") ?? undefined, - receivedAt: Date.now(), - }; - deliveries.push(delivery); - for (const wake of waiters) wake(); - const responder = responders.get(lxm); - return Response.json(responder ? responder(delivery) : {}); - }, - async waitFor(predicate, timeoutMs) { - const deadline = Date.now() + timeoutMs; - for (;;) { - const found = deliveries.find(predicate); - if (found) return found; - const remaining = deadline - Date.now(); - if (remaining <= 0) return null; - await new Promise((resolve) => { - const wake = () => { - waiters.delete(wake); - resolve(); - }; - waiters.add(wake); - setTimeout(wake, Math.min(remaining, 250)); - }); - } - }, - respond(lxm, handler) { - if (handler) responders.set(lxm, handler); - else responders.delete(lxm); - }, - }; -} - -const inbox = createInbox(); +/** The suite's syncer inbox, also answering managing-app queries. */ +const { inbox, handle: inboxHandle } = createSyncerInbox({ + endpoint: INBOX_ORIGIN, + service: `${INBOX_DID}#atproto_space_syncer`, +}); /** Outbound fetch: harness services are answered in-process. */ const routedFetch = (async (input: RequestInfo | URL, init?: RequestInit) => { const req = new Request(input as RequestInfo, init); const { origin } = new URL(req.url); if (origin === INBOX_ORIGIN || origin === AUTHORITY_ORIGIN) { - return inbox.handle(req); + return inboxHandle(req); } return new Response("unroutable in the conformance fixture", { status: 502 }); }) as typeof fetch; @@ -284,6 +237,8 @@ describe("conformance suite vs Cirrus space routes", () => { "delegation.signed-by-user", "delegation.token-claims", "delegation.wrong-space-refused", + // Slow: waits out the real credential lifetime. + "notify.registration-expired", ].sort(), ); for (const id of [ @@ -292,9 +247,12 @@ describe("conformance suite vs Cirrus space routes", () => { "sync.getrepo-star", "credential.deleted-space", "revocation.revoked-credential-refused", - "notify.forwarded-notifywrite", + "notify.registration-confirmed", + "notify.repo-write-delivered", + "notify.repo-removed-delivered", "notify.space-deleted-delivered", - "managedspace.checkuseraccess", + "managedspace.check-access-account", + "managedspace.unreachable-app-upstream-failure", ]) { expect(byId[id], id).toBe("pass"); } diff --git a/packages/spaces/test/routes.test.ts b/packages/spaces/test/routes.test.ts index e4eed08..ff06ae2 100644 --- a/packages/spaces/test/routes.test.ts +++ b/packages/spaces/test/routes.test.ts @@ -302,7 +302,7 @@ async function credentialRequest( let encapsulation: { keyShare: Did; sharedSecret: Uint8Array } | undefined; const requestHeaders: Record = { ...headers }; if (opts.mac) { - encapsulation = (await encapsulate(kemDid)) as never; + encapsulation = (await encapsulate(kemDid)) as typeof encapsulation; requestHeaders["accept-signature"] = formatMacRequest( opts.mac, encapsulation!.keyShare, diff --git a/plans/in-progress/spaces.md b/plans/in-progress/spaces.md index 8e5bc62..8005a19 100644 --- a/plans/in-progress/spaces.md +++ b/plans/in-progress/spaces.md @@ -123,6 +123,76 @@ at runtime. Public types are structural (`SpaceSigningKeypair`, `SpaceCommit`) so no `.d.ts` references an `@atproto` package. Check after each bump: `grep -o 'from "[^"]*"' packages/spaces/dist/*.js packages/spaces/dist/*.d.ts`. +## Alpha 20261112204144 (2026-11-13) + +Moved to `0.0.0-spaces-alpha-20261112204144`, cut from +`permissioned-data-alpha@b27a037c7`, a week after 1105. Smaller in scope but +it renames most of the sync surface: + +- **Renames**: `getSpaceCredential` → `authorizeSpaceSync` (body takes + `credentialKey` and optional `notify`, output `{credential, spaceRev?}`), + `listRepos` → `listWriters` (typed `defs#repoWrite` / `defs#repoRemoved` + entries), `notifyWrite` → `notifyRepoUpdate`, `notifyCredentialRevoked` + → `notifyCredentialsRevoked`, `checkUserAccess` → `checkAccess` + (`{read, write}`, no `access` param; called with no `repo` for anonymous + requests), `putMember` / `removeMember` → `putMembers` / `removeMembers` + (≤100, one commit, last entry wins, non-members ignored). +- **Registration**: `registerNotify` / `unregisterNotify` / + `notifySpaceDeleted` are gone. A syncer passes `notify: {endpoint, + token}` to `authorizeSpaceSync`; a new registration is confirmed by + calling the syncer's `confirmRegistration` (token + challenge in the body, + no service auth, no redirects, 10s timeout) before the credential is + issued, else `RegistrationNotConfirmed`. The registration is keyed + `(endpoint, token)` and its expiry renewed to the credential's `exp`. + Refusal withdraws it, except on `UpstreamFailure`. Updates go to the + syncer's `notifySpaceUpdate` with the token in the body. The first update + after a lapse becomes a one-off `registrationExpired` notice instead; + `spaceDeleted` goes to every registration, lapsed or not. Those two + notices retry at 1m/10m/1h/6h/12h (jittered) for 72h, and a rejected + expiry notice unregisters the syncer. +- **Writer set**: `removeWriter` (now `repo`) sequences a removal and + announces it; removed writers stay in `listWriters` and are excluded from + `exportSpaceMeta`. Sequencing and fan-out queueing happen in one DO + transaction. +- **MACs** are RFC 9421 signatures: `Accept-Signature` with profile tags + `atproto-space-commit` / `atproto-space-record`, answered by + `Atproto-Space-Commit` / `Atproto-Space-Record` plus `Signature-Input` / + `Signature`, keyed by HPKE secret export. Routes set + `Vary: Accept-Signature` and expose the headers; the PDS CORS list + matches. +- **Errors**: `NotSpaceOwner` → `NotAuthorized` (400), + `UserNotAuthorized` → `AccountNotAuthorized`, `BadSpaceMac` → + `InvalidSpaceMac`, `MalformedCursor` → `InvalidCursor`. New + `InvalidRepoFile`, `RepoMismatch`, `InvalidSpaceMeta`, + `RegistrationNotConfirmed`, `UpstreamFailure` (502, managing app failed: + never treated as a denial). +- **Smaller**: STAR is `application/vnd.dasl.star` both ways; space meta + writer entries use `repoRev`; `managingApp` must be `did#serviceId`; + `allowedApps` entries must be URIs; `publicWrite` no longer admits a + member with `write: false`; `createSpace` / `getSpace` output `space`; + `listSpaces` takes `spaceDid` and returns `{space, repoRev?, data?, + spaceRev?}`; `listRepoOps` returns the commit on every page, a cursor only + on a full page, `RepoNotFound` for a never-written repo; `listRecords` + drops `reverse`, `listBlobs` drops `since`. +- **oauth-scopes**: `SpacePermission#type` → `spaceType`, `allowsSpace` + takes `(target, op)`, the named scope param is `spaceType`, declarations + use `title`. oauth-provider exports its own `allowsSpace(permissions, + check)` so the PDS keeps the flat match shape. +- **Schema version 3** (writer `removed_at`, re-keyed registrations, + queue `policy` / `auth`): `pds spaces reset` again. + +Four more upstream packages gained releases outranking the alpha range +(`lex-rpc`, `oauth-resolver`, `lex-password-session`, `bsync`); all are +overridden in `pnpm-workspace.yaml`. + +SSRF: the reference wraps outbound webhook calls in `safeFetch`. Cirrus +requires `https` endpoints and refuses redirects; Workers can't reach +private address space, so that covers the same ground. + +### Conformance at 1112 + +_Pending the suite port._ + ## Alpha sync process Upstream cuts a build from `permissioned-data-alpha` most Thursdays. To @@ -159,13 +229,14 @@ move to a new one (the update loop from the space-conformance spec, #228): covered in-process by the conformance matrix (above). bulletin.my's S1 flow is verified live against pds.mk.gg (2026-08-29): OAuth with space: scopes, board space creation, delegation → - credential exchange, reads, registerNotify and listRepos all work. + credential exchange, reads, registerNotify and listRepos all work + (on the 0818 alpha; not re-verified since). Cross-PDS (S2–S4) remains unexercised against a real foreign PDS. - **R2 lifecycle rule** must be applied per-install (`wrangler r2 bucket lifecycle add pds-blobs --prefix "/staged/" --expire-days 7`); `pds init` doesn't automate it yet. - Blob cache tagging, per-credential rate limits — "Later" per the spec. -- Sending revocations: Cirrus receives `notifyCredentialRevoked` but, like +- Sending revocations: Cirrus receives `notifyCredentialsRevoked` but, like the reference, never revokes credentials it issued (member removal waits out the credential's 10-minute lifetime). - Takedowns: `RepoTakendown` is declared but Cirrus has no takedown @@ -173,7 +244,7 @@ move to a new one (the update loop from the space-conformance spec, #228): - Standalone host package (S9): the engine boundary is in place; no package yet. - Alpha deps (`@atproto/space`, `@atproto/oauth-scopes` at - `0.0.0-spaces-alpha-20261105160032`) follow the sync process above; + `0.0.0-spaces-alpha-20261112204144`) follow the sync process above; Renovate is configured to leave them alone. ## Implementation notes (non-obvious) @@ -204,5 +275,5 @@ move to a new one (the update loop from the space-conformance spec, #228): full proof verification, tolerant parse. Remove once upstream lexicon-doc learns the `space` def type. - Deleted spaces read as `SpaceNotFound`, never-written spaces as - `RepoNotFound`; `getSpaceCredential` alone answers `SpaceDeleted` + `RepoNotFound`; `authorizeSpaceSync` alone answers `SpaceDeleted` (tombstone retained in the space DO). From 8eccc111dfbefb934b566c810527b14a50184560 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 04:53:38 +0000 Subject: [PATCH 13/16] space-conformance: port suite and matrix to the 2026-11-12 alpha 106 checks; syncer inbox serves confirmRegistration and notifySpaceUpdate via createSyncerInbox. Matrix recalibrated: 103 pass, 2 pinned divergences, registration-expired slow and run by hand. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LZ7qcQNQoiA6a23woGC7tB --- .../space-conformance-alpha-20261112.md | 12 + apps/check/src/SpacesConformanceView.tsx | 7 +- packages/space-conformance-matrix/README.md | 44 +- .../space-conformance-matrix/src/harness.ts | 148 ++-- .../test/reference-matrix.test.ts | 68 +- .../earth.cirrus.check.space.json | 9 +- packages/space-conformance/src/alpha.ts | 2 +- packages/space-conformance/src/changesets.ts | 8 + packages/space-conformance/src/checks/base.ts | 36 +- .../src/checks/credential.ts | 614 ++++++++++---- packages/space-conformance/src/checks/host.ts | 776 +++++++++++------- .../space-conformance/src/checks/probe.ts | 173 ++-- .../space-conformance/src/checks/records.ts | 112 +-- .../space-conformance/src/checks/space.ts | 481 +++++------ packages/space-conformance/src/coverage.ts | 19 + packages/space-conformance/src/descriptors.ts | 159 ++-- packages/space-conformance/src/encoding.ts | 2 +- packages/space-conformance/src/full.ts | 3 + packages/space-conformance/src/full/checks.ts | 728 +++++++++------- .../space-conformance/src/full/helpers.ts | 71 +- packages/space-conformance/src/http.ts | 3 +- packages/space-conformance/src/inbox.ts | 129 +++ packages/space-conformance/src/index.ts | 17 +- packages/space-conformance/src/model.ts | 35 +- packages/space-conformance/src/proposal.ts | 71 ++ packages/space-conformance/src/runner.ts | 2 +- packages/space-conformance/src/space-auth.ts | 242 ++++-- packages/space-conformance/test/cli.test.ts | 2 +- packages/space-conformance/test/core.test.ts | 26 +- packages/space-conformance/test/full.test.ts | 151 +++- plans/in-progress/spaces.md | 21 +- 31 files changed, 2739 insertions(+), 1432 deletions(-) create mode 100644 .changeset/space-conformance-alpha-20261112.md create mode 100644 packages/space-conformance/src/inbox.ts create mode 100644 packages/space-conformance/src/proposal.ts diff --git a/.changeset/space-conformance-alpha-20261112.md b/.changeset/space-conformance-alpha-20261112.md new file mode 100644 index 0000000..729c9b4 --- /dev/null +++ b/.changeset/space-conformance-alpha-20261112.md @@ -0,0 +1,12 @@ +--- +"@getcirrus/space-conformance": minor +--- + +Port the conformance suite to the 2026-11-12 spaces alpha (`0.0.0-spaces-alpha-20261112204144`). + +- Credentials come from `authorizeSpaceSync` (with `credentialKey`), and the writer set from `listWriters`, whose typed `repoWrite` / `repoRemoved` entries the checks now read. Member checks use the batched `putMembers` / `removeMembers`, and the managing-app checks use `checkAccess`, including the new tokenless call without a `repo`. +- MAC requests are `Accept-Signature` headers keyed by an HPKE-exported secret, and the full checks verify the MAC signatures that come back. Credential signatures are checked to be found by tag under any label, with `keyid`, `alg`, component and duplicate-signature refusals. +- Notification registration moves into `authorizeSpaceSync`'s `notify`. The `syncer-inbox` capability is now a webhook endpoint that answers `confirmRegistration` and receives `notifySpaceUpdate`. `createSyncerInbox()` provides one as a fetch-style handler. +- New checks cover `RegistrationNotConfirmed`, the `spaceRev` returned on authorisation, announced writer removals, `listRepoOps` commits on every page, the STAR content type, `InvalidRepoFile`, `RepoMismatch` and `InvalidSpaceMeta`. A slow check covers `registrationExpired`. +- Proposal 0016 citations are checked against its section anchors. The read methods' `SpaceNotFound` and every `InvalidCursor` are exempted from coverage with reasons, since nothing in the spec defines them. +- The probe space type declaration uses `title` in place of `name`. diff --git a/apps/check/src/SpacesConformanceView.tsx b/apps/check/src/SpacesConformanceView.tsx index 6b7e19d..79affee 100644 --- a/apps/check/src/SpacesConformanceView.tsx +++ b/apps/check/src/SpacesConformanceView.tsx @@ -3,9 +3,10 @@ * * Signed in (the landing-page flow), the run carries the operator, blob * and delegation capabilities: space management and the baseline - * policies, record writes, blob isolation, credential issuance, and - * credential presentation — HTTP-signed reads with a KEM key share in - * Atproto-Space-Want-Mac — all execute for real against the user's PDS. + * policies, record writes, blob isolation, credential issuance through + * authorizeSpaceSync, and credential presentation — HTTP-signed reads with + * an Accept-Signature MAC request keyed by an HPKE-exported secret — all + * execute for real against the user's PDS. * Operator calls go through the OAuth session; credential-presenting calls * carry their own WebCrypto P-256 signatures. Results stream into the * table as each check lands. diff --git a/packages/space-conformance-matrix/README.md b/packages/space-conformance-matrix/README.md index 04f9b18..11bcd91 100644 --- a/packages/space-conformance-matrix/README.md +++ b/packages/space-conformance-matrix/README.md @@ -31,35 +31,45 @@ matrix is only worth having if it cannot silently rot. ## What the run provides -Every capability the catalog can ask for, so nothing skips: +Every capability the catalog can ask for, so nothing skips but the one slow +check: - an operator account (`seed.createAccount`) and its full-access session; - the reference's own blob endpoints and `getDelegationToken`; - harness identities the reference can resolve — each a tiny local HTTP server publishing a `did:web:localhost%3A` document with an `#atproto` key and an `#atproto_pds` service (the reference resolves - `localhost` did:webs over http, and dev-env disables SSRF protection) — - playing a reader, a writer's PDS, a foreign space authority and a - stranger; -- a syncer inbox (one of those identities) that records the reference's - `notifyWrite` / `notifySpaceDeleted` deliveries and answers its - `managedspace.checkUserAccess` queries; + `localhost` did:webs over http, and dev-env runs it in dev mode, so its + SSRF protection is off) — playing a reader, a writer's PDS, a foreign space + authority and a stranger; +- a syncer inbox: the suite's `createSyncerInbox`, served by the "syncer" + identity's server. Its base URL is the `notify` endpoint registered through + `authorizeSpaceSync`, so it answers the reference's `confirmRegistration` + challenges and records its `notifySpaceUpdate` webhooks; and + `#atproto_pds` names it as a `managedspace` managing app + answering `checkAccess`; - the dev-env PLC as `target.plcDirectory`, so the operator's did:plc document (and its `#atproto_kem` key) resolves. -## Pinned reference divergences (alpha `0.0.0-spaces-alpha-20261105160032`) +## Pinned reference divergences (alpha `0.0.0-spaces-alpha-20261112204144`) -| Check | Why the reference diverges | -| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | -| `writes.delete-in-missing-space` | `deleteRecord` declares `SpaceNotFound`, and `deleteSpace`'s description says writes to a deleted space fail with it. The reference's `deleteRecord` checks whether the record exists before anything touches the space (`hasRecord` → no-op, for idempotency), so a delete in a missing or deleted space is a silent 200 and the `ensureRepo` space check (changeset `brave-spaces-exist`) is never reached. Its create, put and applyWrites do answer `SpaceNotFound`. | -| `space.reads-after-delete-not-found` | Same `deleteSpace` sentence, read side ("afterwards, reads … fail with SpaceNotFound"). The reference's read handlers never consult the space row: once the owner's repo is deleted they answer `RecordNotFound`, `RepoNotFound`, `BlobNotFound` or an empty 200 listing, never the `SpaceNotFound` each of them declares. | -| `credential.garbage-attestation-refused` | `ClientAttestationVerifier.verify` calls `parseSpaceToken` outside its `invalid()` wrapper, so a structurally malformed client attestation escapes as an uncaught `SpaceTokenError` — 500 `InternalServerError` where the lexicon declares `InvalidClientAttestation`. A well-formed but unverifiable attestation is refused correctly (`credential.unverifiable-attestation-refused` passes). | +| Check | Why the reference diverges | +| ---------------------------------------- | -------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `writes.delete-in-missing-space` | `deleteRecord` declares `SpaceNotFound`, and proposal 0016 (Repo lifecycle) says that when the writer is the space authority "the space must already exist" (changeset `brave-spaces-exist`: such writes are rejected with `SpaceNotFound`). The reference's `deleteRecord` checks whether the record exists first (`hasRecord` → no-op, for idempotency), so a delete in a missing or deleted space is a silent 200. Its create, put and applyWrites do answer `SpaceNotFound`. | +| `credential.garbage-attestation-refused` | `ClientAttestationVerifier.verify` calls `parseSpaceToken` outside its `invalid()` wrapper, so a structurally malformed client attestation escapes as an uncaught `SpaceTokenError` — 500 `InternalServerError` where `authorizeSpaceSync` declares `InvalidClientAttestation`. A well-formed but unverifiable attestation is refused correctly (`credential.unverifiable-attestation-refused` passes). | + +Both are carried over unchanged from the 1105 alpha. The third 1105 +divergence, `space.reads-after-delete-not-found`, is gone with the check: the +1112 lexicons dropped the `deleteSpace` sentence it cited, and the read +methods' `SpaceNotFound` is now a reasoned coverage exemption instead. + +Not run here: `notify.registration-expired`, a `slow` check that waits out a +real 10-minute credential before writing. It was run by hand against this alpha (2026-11-13, about 10 minutes) and passed: after the credential lapsed, the next write was replaced by `registrationExpired` and the `repoWrite` was not delivered. Run it with `slow: true`. Everything else in the catalog passes against the reference, including the -identity-gated checks (foreign readers, writers' `notifyWrite`, foreign -authorities' credentials and revocations) and the inbox checks, which -earlier alphas had to skip because the reference could not resolve harness -identities. +identity-gated checks (foreign readers, writers' `notifyRepoUpdate`, foreign +authorities' credentials and revocations), the notification webhooks and the +managing-app checks. ## Running diff --git a/packages/space-conformance-matrix/src/harness.ts b/packages/space-conformance-matrix/src/harness.ts index 4e75ee6..7c32623 100644 --- a/packages/space-conformance-matrix/src/harness.ts +++ b/packages/space-conformance-matrix/src/harness.ts @@ -3,20 +3,27 @@ * * The identity-gated checks need parties the reference can resolve: a * reader whose delegation tokens it verifies, a writer whose service auth - * it verifies, a foreign space authority whose credentials and revocations - * it honours, and a syncer / managing app it calls. Each identity gets its - * own tiny HTTP server and a `did:web:localhost%3A` DID, which the - * reference resolves over plain http (its did:web resolver does that for - * `localhost`, and dev-env disables SSRF protection). The server publishes - * the identity's DID document — `#atproto` plus an `#atproto_pds` service - * pointing back at itself — and records every XRPC call it receives, so - * the "syncer" identity doubles as the inbox. + * it verifies, and a foreign space authority whose credentials and + * revocations it honours. Each identity gets its own tiny HTTP server and a + * `did:web:localhost%3A` DID, which the reference resolves over plain + * http (its did:web resolver does that for `localhost`, and dev-env runs it + * in dev mode, so SSRF protection is off). The server publishes the + * identity's DID document: `#atproto` plus an `#atproto_pds` service + * pointing back at itself. + * + * The "syncer" identity's server also serves the suite's ready-made + * syncer inbox (`createSyncerInbox`) for every other path: its base URL is + * the `notify` endpoint, and `#atproto_pds` names it as a managing app. */ -import { createServer, type Server } from "node:http"; +import { createServer, type IncomingMessage, type Server } from "node:http"; import type { AddressInfo } from "node:net"; -import type { InboxDelivery, SyncerInbox } from "@getcirrus/space-conformance"; -import { KeypairIdentityProvider } from "@getcirrus/space-conformance/full"; +import type { SyncerInbox } from "@getcirrus/space-conformance"; +import { + KeypairIdentityProvider, + createSyncerInbox, + type SyncerInboxHandle, +} from "@getcirrus/space-conformance/full"; export interface HarnessServices { identities: KeypairIdentityProvider; @@ -24,104 +31,83 @@ export interface HarnessServices { close(): Promise; } +async function toRequest( + req: IncomingMessage, + origin: string, +): Promise { + const chunks: Buffer[] = []; + for await (const chunk of req) chunks.push(chunk as Buffer); + const headers = new Headers(); + for (const [k, v] of Object.entries(req.headers)) { + if (typeof v === "string") headers.set(k, v); + } + return new Request(new URL(req.url ?? "/", origin), { + method: req.method, + headers, + ...(req.method === "GET" || req.method === "HEAD" + ? {} + : { body: Buffer.concat(chunks) }), + }); +} + export async function startHarnessServices(): Promise { const servers: Server[] = []; - const deliveries: InboxDelivery[] = []; - const waiters = new Set<() => void>(); - const responders = new Map unknown>(); + let inboxHandle: SyncerInboxHandle | undefined; const identities: KeypairIdentityProvider = new KeypairIdentityProvider( async (role) => { - let did = ""; + let port = 0; const server = createServer((req, res) => { - const url = new URL(req.url ?? "/", "http://localhost"); - if (url.pathname === "/.well-known/did.json") { - void identities.identity(role).then((identity) => { + const origin = `http://localhost:${port}`; + void (async () => { + const url = new URL(req.url ?? "/", origin); + if (url.pathname === "/.well-known/did.json") { + const identity = await identities.identity(role); res.setHeader("Content-Type", "application/json"); res.end( JSON.stringify( KeypairIdentityProvider.didDocument(identity, { - serviceEndpoint: `http://localhost:${port}`, + serviceEndpoint: origin, }), ), ); - }); - return; - } - const lxm = url.pathname.startsWith("/xrpc/") - ? url.pathname.slice("/xrpc/".length) - : url.pathname; - let raw = ""; - req.on("data", (chunk) => (raw += chunk)); - req.on("end", () => { - let body: unknown; - try { - body = raw ? JSON.parse(raw) : undefined; - } catch { - body = raw; + return; } - const delivery: InboxDelivery = { - lxm, - body, - params: Object.fromEntries(url.searchParams), - ...(req.headers.authorization - ? { authorization: req.headers.authorization } - : {}), - receivedAt: Date.now(), - }; - // Only the inbox identity records; the others just publish a doc. - if (did === inboxDid) { - deliveries.push(delivery); - for (const wake of waiters) wake(); + if (role !== "syncer" || !inboxHandle) { + res.statusCode = 404; + res.end(); + return; } - const responder = did === inboxDid ? responders.get(lxm) : undefined; - res.setHeader("Content-Type", "application/json"); - res.end(JSON.stringify(responder ? responder(delivery) : {})); + const response = await inboxHandle.handle( + await toRequest(req, origin), + ); + res.statusCode = response.status; + response.headers.forEach((v, k) => res.setHeader(k, v)); + res.end(Buffer.from(await response.arrayBuffer())); + })().catch((err) => { + res.statusCode = 500; + res.end(String(err)); }); }); await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve), ); servers.push(server); - const port = (server.address() as AddressInfo).port; - did = `did:web:localhost%3A${port}`; - return did; + port = (server.address() as AddressInfo).port; + return `did:web:localhost%3A${port}`; }, ); const syncer = await identities.identity("syncer"); - const inboxDid = syncer.did; - - const inbox: SyncerInbox = { - // Named by fragment, the form registerNotify's lexicon describes. - service: `${inboxDid}#atproto_pds`, - async waitFor(predicate, timeoutMs) { - const deadline = Date.now() + timeoutMs; - for (;;) { - const found = deliveries.find(predicate); - if (found) return found; - const remaining = deadline - Date.now(); - if (remaining <= 0) return null; - await new Promise((resolve) => { - const timer = setTimeout(done, remaining); - function done() { - clearTimeout(timer); - waiters.delete(done); - resolve(); - } - waiters.add(done); - }); - } - }, - respond(lxm, handler) { - if (handler) responders.set(lxm, handler); - else responders.delete(lxm); - }, - }; + const port = decodeURIComponent(syncer.did).split(":").at(-1); + inboxHandle = createSyncerInbox({ + endpoint: `http://localhost:${port}`, + service: `${syncer.did}#atproto_pds`, + }); return { identities, - inbox, + inbox: inboxHandle.inbox, close: async () => { await Promise.all( servers.map( diff --git a/packages/space-conformance-matrix/test/reference-matrix.test.ts b/packages/space-conformance-matrix/test/reference-matrix.test.ts index 1a7a816..16e07c1 100644 --- a/packages/space-conformance-matrix/test/reference-matrix.test.ts +++ b/packages/space-conformance-matrix/test/reference-matrix.test.ts @@ -32,7 +32,7 @@ import { startReferencePds, type ReferencePds } from "../src/reference.js"; import { startHarnessServices, type HarnessServices } from "../src/harness.js"; /** The alpha build this partition was calibrated against. */ -const CALIBRATED_ALPHA = "0.0.0-spaces-alpha-20261105160032"; +const CALIBRATED_ALPHA = "0.0.0-spaces-alpha-20261112204144"; /** * Checks the reference PDS is known to fail, with the reason it diverges from @@ -46,30 +46,36 @@ const CALIBRATED_ALPHA = "0.0.0-spaces-alpha-20261105160032"; * to be noticed in review of whatever moved the reference. */ const EXPECTED_DIVERGENCES: Record = { - // deleteRecord declares SpaceNotFound, and deleteSpace's description says - // "afterwards, reads and writes fail with SpaceNotFound". The reference's - // deleteRecord handler checks whether the record exists *before* anything - // touches the space (`hasRecord` → return null, for idempotency), so a delete - // in a missing or deleted space is a silent 200 and the space check in - // `ensureRepo` (changeset brave-spaces-exist) is never reached. Its create, - // put and applyWrites do answer SpaceNotFound (writes.space-not-found passes). + // deleteRecord declares SpaceNotFound, and proposal 0016 (Repo lifecycle) + // says that when the writer is the space authority "the space must already + // exist" (changeset brave-spaces-exist: such writes are rejected with + // SpaceNotFound). The reference's deleteRecord checks whether the record + // exists first (`hasRecord` → no-op, for idempotency), so a delete in a + // missing or deleted space is a silent 200 and the `ensureRepo` space check + // is never reached. Its create, put and applyWrites do answer SpaceNotFound + // (writes.space-not-found passes). Unchanged since 1105. "writes.delete-in-missing-space": "reference deleteRecord short-circuits on an absent record before checking the space, answering 200", - // Same deleteSpace sentence, read side. The reference's read handlers never - // consult the space row: after deletion the owner's repo is gone, so they - // answer RecordNotFound / RepoNotFound / BlobNotFound or an empty 200 listing, - // never the SpaceNotFound each of them declares. - "space.reads-after-delete-not-found": - "reference reads ignore the space tombstone and answer RecordNotFound/RepoNotFound/BlobNotFound or an empty 200", - // ClientAttestationVerifier.verify calls parseSpaceToken outside its + // ClientAttestationVerifier.verify still calls parseSpaceToken outside its // invalid() wrapper, so a structurally malformed attestation escapes as an - // uncaught SpaceTokenError: 500 InternalServerError, where the lexicon + // uncaught SpaceTokenError: 500 InternalServerError, where authorizeSpaceSync // declares InvalidClientAttestation. A well-formed but unverifiable one is // refused correctly (credential.unverifiable-attestation-refused passes). + // Unchanged since 1105. "credential.garbage-attestation-refused": "reference answers 500 for a malformed client attestation (parseSpaceToken throws outside invalid())", }; +/** + * Checks the run leaves out, with why. Not divergences: the reference is not + * failing them, the matrix just does not run them on every CI pass. + */ +const NOT_RUN: Record = { + // Waits out a real credential lifetime (10 minutes) before the next write. + // Calibrated by hand against this alpha (see README); too slow for CI. + "notify.registration-expired": "slow: waits out a 10-minute credential", +}; + describe("conformance suite vs the atproto reference PDS", () => { let ref: ReferencePds; let harness: HarnessServices; @@ -127,7 +133,7 @@ describe("conformance suite vs the atproto reference PDS", () => { }); const expectedStatus = (id: string): string => - id in EXPECTED_DIVERGENCES ? "fail" : "pass"; + id in EXPECTED_DIVERGENCES ? "fail" : id in NOT_RUN ? "skipped" : "pass"; it("behaves exactly as pinned on every check", () => { const wrong = report.results.filter( @@ -146,10 +152,15 @@ describe("conformance suite vs the atproto reference PDS", () => { ).toEqual([]); }); - it("runs the whole catalog — nothing skipped", () => { - // Every capability is provided, so a skip means a check grew a need the - // harness doesn't meet; it must be wired here, not quietly dropped. - expect(report.results.filter((r) => r.status === "skipped")).toEqual([]); + it("runs the whole catalog — nothing skipped but the pinned slow checks", () => { + // Every capability is provided, so any other skip means a check grew a + // need the harness doesn't meet; it must be wired here, not dropped. + expect( + report.results + .filter((r) => r.status === "skipped") + .map((r) => r.id) + .sort(), + ).toEqual(Object.keys(NOT_RUN).sort()); expect(report.results).toHaveLength(fullCatalog.length); }); @@ -168,16 +179,20 @@ describe("conformance suite vs the atproto reference PDS", () => { "credential.claims", "credential.signature-required", "credential.audience-bound", - "mac.want-mac-required", + "mac.mac-request-required", "mac.commit-verifies", "mac.record-verifies", "sync.oplog-folds-to-commit", "sync.getrepo-star", - "sync.listrepos-shape", + "sync.listwriters-shape", + "host.removewriter", "credential.member-gate", "revocation.revoked-credential-refused", - "notify.forwarded-notifywrite", - "managedspace.checkuseraccess", + "notify.registration-confirmed", + "notify.repo-write-delivered", + "notify.repo-removed-delivered", + "managedspace.check-access-tokenless", + "managedspace.check-access-account", "migration.import-repo", ]) { expect(byId[id], `${id} against the reference`).toBe("pass"); @@ -194,5 +209,8 @@ describe("conformance suite vs the atproto reference PDS", () => { expect(byId.has(id), `${id} is not a known check`).toBe(true); expect(byId.get(id)?.tier, `${id} must be a must check`).toBe("must"); } + for (const id of Object.keys(NOT_RUN)) { + expect(byId.get(id)?.slow, `${id} is not a slow check`).toBe(true); + } }); }); diff --git a/packages/space-conformance/probe-lexicons/earth.cirrus.check.space.json b/packages/space-conformance/probe-lexicons/earth.cirrus.check.space.json index e7dd85d..8677702 100644 --- a/packages/space-conformance/probe-lexicons/earth.cirrus.check.space.json +++ b/packages/space-conformance/probe-lexicons/earth.cirrus.check.space.json @@ -6,12 +6,9 @@ "main": { "type": "space", "key": "any", - "name": "Conformance probe space", + "title": "Conformance probe space", "description": "Ephemeral probe spaces created by the @getcirrus/space-conformance suite (check.cirrus.earth). Each is created with a run-unique key and deleted when its check finishes.", - "collections": [ - "earth.cirrus.check.note", - "earth.cirrus.check.withblob" - ] + "collections": ["earth.cirrus.check.note", "earth.cirrus.check.withblob"] } } -} \ No newline at end of file +} diff --git a/packages/space-conformance/src/alpha.ts b/packages/space-conformance/src/alpha.ts index 574dfc5..71dbc5e 100644 --- a/packages/space-conformance/src/alpha.ts +++ b/packages/space-conformance/src/alpha.ts @@ -4,4 +4,4 @@ * bluesky-social/atproto `permissioned-data-alpha` at the vendored lexicon * commit. Runners stamp it on every report. */ -export const ALPHA_BUILD = "0.0.0-spaces-alpha-20261105160032"; +export const ALPHA_BUILD = "0.0.0-spaces-alpha-20261112204144"; diff --git a/packages/space-conformance/src/changesets.ts b/packages/space-conformance/src/changesets.ts index 2d38ef6..cb90ef1 100644 --- a/packages/space-conformance/src/changesets.ts +++ b/packages/space-conformance/src/changesets.ts @@ -16,11 +16,19 @@ export const knownChangesets: readonly string[] = [ "neat-guests-pull", "olive-crabs-fly", "open-spaces-greet", + "patient-managers-answer", "plain-keys-resolve", "quiet-spaces-mac", "quiet-writers-leave", + "removed-writers-notify", + "shared-writer-defs", "small-hornets-jam", + "space-hpke-secret-export", + "space-mac-http-signatures", "space-takedown-parity", + "spaces-sdk-shape", "star-spaces-shine", "sturdy-spaces-depart", + "tidy-spaces-settle", + "webhook-syncers-register", ]; diff --git a/packages/space-conformance/src/checks/base.ts b/packages/space-conformance/src/checks/base.ts index 36a7c1b..1301f2b 100644 --- a/packages/space-conformance/src/checks/base.ts +++ b/packages/space-conformance/src/checks/base.ts @@ -19,6 +19,7 @@ import { PROBE_TYPE, describe, unknownSpaceUri } from "./probe.js"; const changeset = (ref: string) => ({ source: "changeset" as const, ref }); const lexicon = (ref: string) => ({ source: "lexicon" as const, ref }); +const proposal = (ref: string) => ({ source: "proposal" as const, ref }); /** The target's DID document, resolved once per run by its DID method. */ async function targetDoc(ctx: CheckContext): Promise { @@ -41,7 +42,10 @@ const discoveryPdsService = defineCheck({ id: "discovery.pds-service", title: "The authority's #atproto_pds service is the space host", tier: "must", - citations: [changeset("plain-keys-resolve")], + citations: [ + proposal("0016#space-authority"), + changeset("plain-keys-resolve"), + ], needs: [], async run(ctx) { // The alpha dropped #atproto_space_host: a space authority is resolved @@ -63,7 +67,10 @@ const discoverySigningKey = defineCheck({ id: "discovery.signing-key", title: "The DID document exposes the #atproto key that signs space tokens", tier: "must", - citations: [changeset("plain-keys-resolve")], + citations: [ + proposal("0016#space-authority"), + changeset("plain-keys-resolve"), + ], needs: [], async run(ctx) { const doc = await targetDoc(ctx); @@ -79,7 +86,7 @@ const discoveryKemKey = defineCheck({ title: "The DID document publishes a P-256 #atproto_kem key", tier: "must", citations: [ - changeset("quiet-spaces-mac"), + proposal("0016#kem-key"), lexicon("com.atproto.space.getLatestCommit"), ], needs: [], @@ -94,9 +101,20 @@ const discoveryKemKey = defineCheck({ "no #atproto_kem verification method", doc.verificationMethod, ); - return isP256DidKey(key) - ? pass(`#atproto_kem is ${key}`) - : fail(`#atproto_kem is not a P-256 key: ${key}`); + if (!isP256DidKey(key)) + return fail(`#atproto_kem is not a P-256 key: ${key}`); + // "The entry MUST have": id {did}#atproto_kem, controller the DID, + // type Multikey. + const entry = (doc.verificationMethod ?? []).find((m) => + m.id.endsWith("#atproto_kem"), + )!; + const problems: string[] = []; + if (entry.type !== "Multikey") problems.push(`type ${entry.type}`); + if (entry.controller !== doc.id) + problems.push(`controller ${entry.controller}`); + return problems.length + ? fail(`#atproto_kem entry: ${problems.join(", ")}`, entry) + : pass(`#atproto_kem is ${key}`); }, }); @@ -155,7 +173,7 @@ const credentialTokenlessUnknown = defineCheck({ "A tokenless credential request for an unknown space gets SpaceNotFound", tier: "must", citations: [ - lexicon("com.atproto.space.getSpaceCredential@error:SpaceNotFound"), + lexicon("com.atproto.space.authorizeSpaceSync@error:SpaceNotFound"), ], needs: [], async run(ctx) { @@ -163,9 +181,9 @@ const credentialTokenlessUnknown = defineCheck({ // to issue for, and the declared answer is SpaceNotFound — the same // answer a non-public space gives, so existence is not disclosed. const key = await createCredentialKey(); - const res = await xrpcPost(ctx, "com.atproto.space.getSpaceCredential", { + const res = await xrpcPost(ctx, "com.atproto.space.authorizeSpaceSync", { space: unknownSpaceUri(ctx.target.did), - credentialKid: key.did, + credentialKey: key.did, }); if (res.status === 200) return fail("issued a credential for an unknown space"); diff --git a/packages/space-conformance/src/checks/credential.ts b/packages/space-conformance/src/checks/credential.ts index 897006f..aa7e31a 100644 --- a/packages/space-conformance/src/checks/credential.ts +++ b/packages/space-conformance/src/checks/credential.ts @@ -1,26 +1,26 @@ /** - * Space credentials, operator-side: issuance (tokenless for public-read - * spaces, via the target's own delegation tokens otherwise), the refusals - * getSpaceCredential declares, and presentation — the HTTP message - * signature, the audience binding and the MAC request every credentialed - * read of a commit or record must carry. + * Space credentials, operator-side: issuance through authorizeSpaceSync + * (tokenless for public-read spaces, via the target's own delegation + * tokens otherwise), the refusals it declares, and presentation — the + * HTTP message signature, the audience binding and the MAC request every + * credentialed read of a commit or record must carry. * - * All browser-safe: credential keys, signatures and KEM key shares are + * All browser-safe: credential keys, signatures and HPKE key shares are * WebCrypto (see ../space-auth.ts). Verifying the MACs that come back * needs the reference library and lives in ../full/checks.ts. */ import { defineCheck } from "../registry.js"; -import { asOperator, xrpcGet } from "../http.js"; +import { asOperator, xrpcGet, xrpcPost } from "../http.js"; import { fail, pass, type Check, type CheckContext } from "../model.js"; -import { decodeJwt, rawCid, toBase64Url, utf8 } from "../encoding.js"; +import { decodeJwt, isTid, rawCid, toBase64Url, utf8 } from "../encoding.js"; import { - COMMIT_MAC_TYPE, - MAC_HEADER, - RECORD_MAC_TYPE, + COMMIT_MAC_PROFILE, + RECORD_MAC_PROFILE, createCredentialKey, - formatWantMacHeader, + credentialSigMembers, formatDidKey, + formatMacRequest, } from "../space-auth.js"; import { FOREIGN_DID, @@ -30,6 +30,7 @@ import { credentialGet, deleteProbeSpace, describe, + errorIs, memberspace, mustCreateRecord, obtainCredentialViaDelegation, @@ -44,7 +45,14 @@ import { import { fakeDid } from "./space.js"; const L = (ref: string) => ({ source: "lexicon" as const, ref }); -const C = (ref: string) => ({ source: "changeset" as const, ref }); +const P = (ref: string) => ({ source: "proposal" as const, ref }); + +/** Refusals the lexicon allows for an account the policy does not authorise. */ +export const ACCOUNT_REFUSALS = [ + "SpaceNotFound", + "AccountNotAuthorized", + "NotAuthorized", +]; /** A public-read probe space holding one record, plus a tokenless credential for it. */ async function withPublicSpace( @@ -80,18 +88,21 @@ const readShared = ( params: recordParams(ctx, space), }); +const refused = (status: number) => status >= 400 && status < 500; + // --- issuance ---------------------------------------------------------- const credentialTokenlessPolicies = defineCheck({ id: "credential.tokenless-by-policy", title: - "Without a delegation token only a public-read space issues; others answer SpaceNotFound", + "Without a delegation token only a public-read space issues a credential", tier: "must", citations: [ - L("com.atproto.space.getSpaceCredential"), - L("com.atproto.space.getSpaceCredential@error:SpaceNotFound"), + L("com.atproto.space.authorizeSpaceSync"), + L("com.atproto.space.authorizeSpaceSync@error:SpaceNotFound"), L("com.atproto.memberspace.policy"), L("com.atproto.personalspace.policy"), + P("0016#memberspace"), ], needs: ["operator"], destructive: true, @@ -112,13 +123,13 @@ const credentialTokenlessPolicies = defineCheck({ ["personalspace", personal], ] as const) { const res = await requestCredential(ctx, space.uri); - if (res.result.error !== "SpaceNotFound") + if (res.credential || !errorIs(...ACCOUNT_REFUSALS)(res.result)) misses.push(`${label} → ${describe(res.result)}`); } return misses.length - ? fail(`expected SpaceNotFound: ${misses.join("; ")}`) + ? fail(`expected ${ACCOUNT_REFUSALS.join(" / ")}: ${misses.join("; ")}`) : pass( - "public-read issued; closed memberspace and personalspace answered SpaceNotFound", + "public-read issued; a closed memberspace and a personalspace refused", ); } finally { for (const s of [open, closed, personal]) @@ -133,9 +144,8 @@ const credentialClaims = defineCheck({ "A credential is signed by the authority for the space, bound to the requested key", tier: "must", citations: [ - L("com.atproto.space.getSpaceCredential"), - C("funky-dryers-draw"), - C("plain-keys-resolve"), + L("com.atproto.space.authorizeSpaceSync"), + P("0016#space-credential"), ], needs: ["operator"], destructive: true, @@ -155,8 +165,7 @@ const credentialClaims = defineCheck({ problems.push(`sub ${String(payload.sub)}`); if (cnf?.kid !== credential.key.did) problems.push(`cnf.kid ${String(cnf?.kid)}`); - // Credentials carry no audience: each use is bound to one by its - // HTTP signature instead. + // Credentials carry no audience: each use is bound to one by its signature. if ("aud" in payload) problems.push(`has aud ${String(payload.aud)}`); if (typeof payload.jti !== "string" || !payload.jti) problems.push("no jti"); @@ -175,14 +184,9 @@ const credentialClaims = defineCheck({ const credentialDefaultLifetime = defineCheck({ id: "credential.default-lifetime", - title: "Credentials live 600 seconds, the reference default", + title: "Credentials live 600 seconds, the default", tier: "should", - citations: [ - { - source: "reference", - ref: "@atproto/space SPACE_TOKEN_TYPES.credential.expiresInSec", - }, - ], + citations: [P("0016#space-credential")], needs: ["operator"], destructive: true, async run(ctx) { @@ -199,37 +203,97 @@ const credentialDefaultLifetime = defineCheck({ }, }); -const credentialKidP256 = defineCheck({ - id: "credential.kid-must-be-p256", +const credentialSpaceRev = defineCheck({ + id: "credential.space-rev", title: - "getSpaceCredential refuses a credentialKid that is not a P-256 did:key", + "authorizeSpaceSync reports the space's current revision, omitted before its first update", tier: "must", - citations: [L("com.atproto.space.getSpaceCredential")], + citations: [ + L("com.atproto.space.authorizeSpaceSync"), + P("0016#authorizing-space-sync"), + ], needs: ["operator"], destructive: true, async run(ctx) { const space = await createProbeSpace(ctx, publicRead()); try { - // A well-formed secp256k1 did:key: valid syntax, wrong curve. The - // credential could never be presented — HTTP signatures are P-256. + const fresh = await requestCredential(ctx, space.uri); + if (!fresh.credential) + return fail( + `authorizeSpaceSync ${describe(fresh.result)}`, + fresh.result.json, + ); + if (fresh.spaceRev !== undefined) + return fail( + `a space with no updates reported spaceRev ${fresh.spaceRev}`, + ); + await mustCreateRecord(ctx, space.uri, "a"); + const after = await requestCredential(ctx, space.uri); + if (!isTid(after.spaceRev)) + return fail( + `after a write, spaceRev is ${String(after.spaceRev)}`, + after.result.json, + ); + // The space's current revision is the latest one listWriters sequenced. + const list = await credentialCall( + ctx, + after.credential!, + "com.atproto.space.listWriters", + { + params: { space: space.uri }, + audience: ctx.target.did, + }, + ); + const revs = ( + (list.json as { repos?: Array<{ spaceRev?: string }> } | undefined) + ?.repos ?? [] + ).map((r) => r.spaceRev); + return revs.at(-1) === after.spaceRev + ? pass( + `omitted before the first update; then ${after.spaceRev}, the latest sequenced revision`, + ) + : fail( + `spaceRev ${after.spaceRev} is not the latest listWriters revision ${revs.at(-1)}`, + ); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const credentialKeyP256 = defineCheck({ + id: "credential.key-must-be-p256", + title: + "authorizeSpaceSync refuses a credentialKey that is not a P-256 did:key", + tier: "must", + citations: [ + L("com.atproto.space.authorizeSpaceSync"), + P("0016#credential-key-binding"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, publicRead()); + try { + // A well-formed secp256k1 did:key: valid syntax, wrong curve. const k256 = formatDidKey( "ES256K", new Uint8Array([0x02, ...crypto.getRandomValues(new Uint8Array(32))]), ); const bad = await requestCredential(ctx, space.uri, { - credentialKid: k256, + credentialKey: k256, }); if (bad.credential) return fail("issued a credential bound to a secp256k1 key"); const notKey = await requestCredential(ctx, space.uri, { - credentialKid: ctx.target.did, + credentialKey: ctx.target.did, }); if (notKey.credential) return fail("issued a credential bound to a non-key DID"); const good = await requestCredential(ctx, space.uri); return good.credential ? pass( - `refused secp256k1 (${describe(bad.result)}) and non-key (${describe(notKey.result)}) kids; P-256 issued`, + `refused secp256k1 (${describe(bad.result)}) and non-key (${describe(notKey.result)}); P-256 issued`, ) : fail( `positive control failed: ${describe(good.result)}`, @@ -246,7 +310,7 @@ const credentialGarbageDelegation = defineCheck({ title: "A malformed delegation token is refused with InvalidDelegationToken", tier: "must", citations: [ - L("com.atproto.space.getSpaceCredential@error:InvalidDelegationToken"), + L("com.atproto.space.authorizeSpaceSync@error:InvalidDelegationToken"), ], needs: ["operator"], destructive: true, @@ -280,7 +344,7 @@ async function unverifiableAttestation(authority: string): Promise { const key = await createCredentialKey(); const iat = Math.floor(Date.now() / 1000); const part = (obj: unknown) => toBase64Url(utf8(JSON.stringify(obj))); - const input = `${part({ alg: "ES256", typ: "atproto-client-attestation+jwt" })}.${part( + const input = `${part({ alg: "ES256", typ: "atproto-client-attestation+jwt", kid: "key-1" })}.${part( { iss: clientId, sub: clientId, @@ -294,7 +358,8 @@ async function unverifiableAttestation(authority: string): Promise { } const attestationCitations = [ - L("com.atproto.space.getSpaceCredential@error:InvalidClientAttestation"), + L("com.atproto.space.authorizeSpaceSync@error:InvalidClientAttestation"), + P("0016#client-attestation"), ]; const credentialUnverifiableAttestation = defineCheck({ @@ -359,18 +424,18 @@ const credentialGarbageAttestation = defineCheck({ const credentialAllowedApps = defineCheck({ id: "credential.allowed-apps-gate", - title: - "A memberspace with allowedApps refuses an unattested app with AppNotAuthorized", + title: "A memberspace with allowedApps refuses an unattested app", tier: "must", citations: [ - L("com.atproto.space.getSpaceCredential@error:AppNotAuthorized"), + L("com.atproto.space.authorizeSpaceSync@error:AppNotAuthorized"), L("com.atproto.memberspace.policy"), + P("0016#memberspace"), ], needs: ["operator"], destructive: true, async run(ctx) { - // publicRead clears the user perimeter (checked first), so only the - // app perimeter is left to refuse. + // publicRead clears the account perimeter, so only the app perimeter is + // left to refuse; NotAuthorized may stand in for AppNotAuthorized. const space = await createProbeSpace( ctx, memberspace({ @@ -384,8 +449,8 @@ const credentialAllowedApps = defineCheck({ const res = await requestCredential(ctx, space.uri); if (res.credential) return fail("issued a credential to an app outside allowedApps"); - return res.result.error === "AppNotAuthorized" - ? pass("refused with AppNotAuthorized") + return errorIs("AppNotAuthorized", "NotAuthorized")(res.result) + ? pass(`refused with ${res.result.error}`) : fail( `refused with ${describe(res.result)}, expected AppNotAuthorized`, res.result.json, @@ -398,17 +463,19 @@ const credentialAllowedApps = defineCheck({ const credentialDeletedSpace = defineCheck({ id: "credential.deleted-space", - title: "After deleteSpace, getSpaceCredential answers SpaceDeleted", + title: + "deleteSpace removes the authority's repo, and authorizeSpaceSync then answers SpaceDeleted", tier: "must", citations: [ L("com.atproto.space.deleteSpace"), - L("com.atproto.space.getSpaceCredential@error:SpaceDeleted"), + L("com.atproto.space.authorizeSpaceSync@error:SpaceDeleted"), + P("0016#space-deletion"), ], needs: ["operator"], destructive: true, async run(ctx) { const space = await createProbeSpace(ctx, publicRead()); - // Positive control, so a target that never issues cannot pass. + await mustCreateRecord(ctx, space.uri, "mine"); const before = await requestCredential(ctx, space.uri); if (!before.credential) { await deleteProbeSpace(ctx, space.uri); @@ -416,21 +483,76 @@ const credentialDeletedSpace = defineCheck({ `could not obtain a credential before deletion (${describe(before.result)})`, ); } - await deleteProbeSpace(ctx, space.uri); - const after = await requestCredential(ctx, space.uri); - if (after.credential) + const del = await xrpcPost( + asOperator(ctx), + "com.atproto.space.deleteSpace", + { space: space.uri }, + ); + if (del.status !== 200) + return fail(`deleteSpace ${describe(del)}`, del.json); + // "Delete a space, along with the authority's space repo." + const own = await xrpcGet(asOperator(ctx), "com.atproto.space.getRecord", { + space: space.uri, + repo: ctx.target.did, + collection: POST, + rkey: "mine", + }); + if (own.status === 200) + return fail("the authority's own record survived deleteSpace", own.json); + // "regardless of the request's authorization": tokenless, and with a + // garbage delegation token. + const tokenless = await requestCredential(ctx, space.uri); + const garbage = await requestCredential(ctx, space.uri, { + delegationToken: "not.a.token", + }); + if (tokenless.credential) return fail("a deleted space still issued a credential"); - // The durable tombstone: a syncer that missed notifySpaceDeleted learns - // it here on renewal — tokenless, as a public space's syncer would ask. - return after.result.error === "SpaceDeleted" - ? pass("answered SpaceDeleted") + return tokenless.result.error === "SpaceDeleted" && + garbage.result.error === "SpaceDeleted" + ? pass( + "own records gone; answered SpaceDeleted, tokenless and with a bad token", + ) : fail( - `answered ${describe(after.result)}, expected SpaceDeleted`, - after.result.json, + `answered ${describe(tokenless.result)} tokenless, ${describe(garbage.result)} with a bad token; expected SpaceDeleted`, ); }, }); +const credentialUnconfirmedRegistration = defineCheck({ + id: "credential.unconfirmed-registration-refused", + title: + "A notify endpoint that does not confirm the registration gets RegistrationNotConfirmed", + tier: "must", + citations: [ + L("com.atproto.space.authorizeSpaceSync@error:RegistrationNotConfirmed"), + P("0016#registering-for-notifications"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + // An endpoint nobody serves can't echo the challenge. + const space = await createProbeSpace(ctx, publicRead()); + try { + const res = await requestCredential(ctx, space.uri, { + notify: { + endpoint: "https://syncer.space-conformance.invalid", + token: toBase64Url(crypto.getRandomValues(new Uint8Array(32))), + }, + }); + if (res.credential) + return fail("issued a credential with an unconfirmed registration"); + return res.result.error === "RegistrationNotConfirmed" + ? pass("refused with RegistrationNotConfirmed") + : fail( + `refused with ${describe(res.result)}, expected RegistrationNotConfirmed`, + res.result.json, + ); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + // --- delegation (the target's own tokens) -------------------------------- const credentialSelfRoundTrip = defineCheck({ @@ -440,8 +562,9 @@ const credentialSelfRoundTrip = defineCheck({ tier: "must", citations: [ L("com.atproto.space.getDelegationToken"), - L("com.atproto.space.getSpaceCredential"), + L("com.atproto.space.authorizeSpaceSync"), L("com.atproto.space.getRecord"), + P("0016#credential-flow"), ], needs: ["operator", "pds-delegation"], destructive: true, @@ -458,13 +581,14 @@ const credentialSelfRoundTrip = defineCheck({ delegation.json, ); if (!credential) - return fail(`getSpaceCredential ${describe(result)}`, result.json); + return fail(`authorizeSpaceSync ${describe(result)}`, result.json); const read = await readShared(ctx, credential, space.uri); if (read.status !== 200) return fail(`credential read failed: ${describe(read)}`, read.json); - return read.headers.get(MAC_HEADER) + return read.headers.get("atproto-space-record") && + read.headers.get("signature") ? pass("delegation → credential → MAC'd read works") - : fail("the credentialed read carried no Atproto-Space-Mac header"); + : fail("the credentialed read carried no Atproto-Space-Record MAC"); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -478,7 +602,7 @@ const delegationClaims = defineCheck({ tier: "must", citations: [ L("com.atproto.space.getDelegationToken"), - C("plain-keys-resolve"), + P("0016#delegation-token"), ], needs: ["operator", "pds-delegation"], destructive: true, @@ -505,13 +629,14 @@ const delegationClaims = defineCheck({ problems.push(`sub ${String(payload.sub)}`); if (payload.aud !== `${ctx.target.did}#atproto_pds`) problems.push(`aud ${String(payload.aud)}`); + if ("lxm" in payload) problems.push("has an lxm claim"); if (typeof payload.jti !== "string" || !payload.jti) problems.push("no jti"); if (!(Number(payload.exp) > Math.floor(Date.now() / 1000) - 5)) problems.push("already expired"); return problems.length ? fail(`delegation token: ${problems.join(", ")}`, { header, payload }) - : pass("typ/kid/iss/sub/aud as specified"); + : pass("typ/kid/iss/sub/aud as specified, no lxm"); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -523,7 +648,8 @@ const delegationReplay = defineCheck({ title: "A delegation token cannot be used twice", tier: "must", citations: [ - L("com.atproto.space.getSpaceCredential@error:InvalidDelegationToken"), + L("com.atproto.space.authorizeSpaceSync@error:InvalidDelegationToken"), + P("0016#delegation-token"), ], needs: ["operator", "pds-delegation"], destructive: true, @@ -566,7 +692,8 @@ const delegationWrongSpace = defineCheck({ title: "A delegation token for one space is refused for another", tier: "must", citations: [ - L("com.atproto.space.getSpaceCredential@error:InvalidDelegationToken"), + L("com.atproto.space.authorizeSpaceSync@error:InvalidDelegationToken"), + P("0016#delegation-token"), ], needs: ["operator", "pds-delegation"], destructive: true, @@ -602,9 +729,8 @@ const delegationWrongSpace = defineCheck({ const presentationCitations = [ L("com.atproto.space.getRecord"), - L("com.atproto.space.listRepos"), - C("funky-dryers-draw"), - C("open-spaces-greet"), + L("com.atproto.space.listWriters"), + P("0016#presenting-a-space-credential"), ]; const credentialSignatureRequired = defineCheck({ @@ -622,7 +748,7 @@ const credentialSignatureRequired = defineCheck({ const bare = await readShared(ctx, credential, space.uri, { unsigned: true, }); - return bare.status >= 400 && bare.status < 500 + return refused(bare.status) ? pass(`signed read 200; unsigned read refused (${describe(bare)})`) : fail( `an unsigned credential read returned ${describe(bare)}`, @@ -632,6 +758,141 @@ const credentialSignatureRequired = defineCheck({ }, }); +const credentialSignatureByTag = defineCheck({ + id: "credential.signature-found-by-tag", + title: + "The credential signature is found by its tag under any label; other parameters are ignored", + tier: "must", + citations: presentationCitations, + needs: ["operator"], + destructive: true, + async run(ctx) { + return withPublicSpace(ctx, async (space, credential) => { + const now = Math.floor(Date.now() / 1000); + const variants: Array<[string, CredentialCallOptions["signature"]]> = [ + ["label 'x7'", { label: "x7" }], + [ + "created and nonce parameters", + { + params: [ + ["created", now], + ["nonce", "abc"], + ], + }, + ], + [ + "keyid = cnf.kid and alg = ecdsa-p256-sha256", + { + params: [ + ["keyid", credential.key.did], + ["alg", "ecdsa-p256-sha256"], + ], + }, + ], + ]; + const misses: string[] = []; + for (const [label, signature] of variants) { + const res = await readShared(ctx, credential, space.uri, { signature }); + if (res.status !== 200) misses.push(`${label} → ${describe(res)}`); + } + // A second, unrelated signature with another tag alongside is ignored. + const extra = await readShared(ctx, credential, space.uri, { + signatureHeaders: async (h) => { + const other = await credentialSigMembers(credential.key, { + authorization: h.authorization!, + audience: h["atproto-space-audience"]!, + label: "other", + tag: "some-other-app", + }); + return { + ...h, + "signature-input": `${h["signature-input"]}, ${other.input}`, + signature: `${h.signature}, ${other.signature}`, + }; + }, + }); + if (extra.status !== 200) + misses.push( + `with an extra differently-tagged signature → ${describe(extra)}`, + ); + return misses.length + ? fail(`refused a valid signature: ${misses.join("; ")}`) + : pass( + "accepted under another label, with extra parameters, and beside another tag's signature", + ); + }); + }, +}); + +const credentialSignatureRequirements = defineCheck({ + id: "credential.signature-requirements", + title: + "A credential signature with the wrong components, keyid, alg or count is refused", + tier: "must", + citations: presentationCitations, + needs: ["operator"], + destructive: true, + async run(ctx) { + return withPublicSpace(ctx, async (space, credential) => { + const ok = await readShared(ctx, credential, space.uri); + if (ok.status !== 200) + return fail(`positive control failed: ${describe(ok)}`, ok.json); + const other = await createCredentialKey(); + const variants: Array<[string, Omit]> = [ + [ + "covers only authorization", + { signature: { components: ["authorization"] } }, + ], + [ + "components out of order", + { + signature: { + components: ["atproto-space-audience", "authorization"], + }, + }, + ], + [ + "keyid of another key", + { signature: { params: [["keyid", other.did]] } }, + ], + [ + "alg hmac-sha256", + { signature: { params: [["alg", "hmac-sha256"]] } }, + ], + [ + "no atproto-space-credential tag", + { signature: { tag: "something-else" } }, + ], + [ + "two tagged signatures", + { + signatureHeaders: async (h) => { + const dup = await credentialSigMembers(credential.key, { + authorization: h.authorization!, + audience: h["atproto-space-audience"]!, + label: "dup", + }); + return { + ...h, + "signature-input": `${h["signature-input"]}, ${dup.input}`, + signature: `${h.signature}, ${dup.signature}`, + }; + }, + }, + ], + ]; + const misses: string[] = []; + for (const [label, opts] of variants) { + const res = await readShared(ctx, credential, space.uri, opts); + if (!refused(res.status)) misses.push(`${label} → ${describe(res)}`); + } + return misses.length + ? fail(`accepted: ${misses.join("; ")}`) + : pass("every malformed signature was refused"); + }); + }, +}); + const credentialAudienceBound = defineCheck({ id: "credential.audience-bound", title: "A credential signed for another audience is refused", @@ -640,8 +901,6 @@ const credentialAudienceBound = defineCheck({ needs: ["operator"], destructive: true, async run(ctx) { - // The audience is the service being called; a signature over some - // other DID is a request meant for someone else, replayed here. return withPublicSpace(ctx, async (space, credential) => { const ok = await readShared(ctx, credential, space.uri); if (ok.status !== 200) @@ -649,31 +908,30 @@ const credentialAudienceBound = defineCheck({ const misaddressed = await readShared(ctx, credential, space.uri, { audience: FOREIGN_DID, }); - if (misaddressed.status < 400 || misaddressed.status >= 500) { + if (!refused(misaddressed.status)) return fail( `a misaddressed repo-host read returned ${describe(misaddressed)}`, misaddressed.json, ); - } // The same at the space host, whose audience is the authority. - const listRepos = (audience: string) => - credentialCall(ctx, credential, "com.atproto.space.listRepos", { + const listWriters = (audience: string) => + credentialCall(ctx, credential, "com.atproto.space.listWriters", { params: { space: space.uri }, audience, }); - const hostOk = await listRepos(ctx.target.did); + const hostOk = await listWriters(ctx.target.did); if (hostOk.status !== 200) return fail( - `listRepos positive control failed: ${describe(hostOk)}`, + `listWriters positive control failed: ${describe(hostOk)}`, hostOk.json, ); - const hostWrong = await listRepos(FOREIGN_DID); - return hostWrong.status >= 400 && hostWrong.status < 500 + const hostWrong = await listWriters(FOREIGN_DID); + return refused(hostWrong.status) ? pass( - `refused signatures over another audience at the repo host (${describe(misaddressed)}) and space host (${describe(hostWrong)})`, + `refused other audiences at the repo host (${describe(misaddressed)}) and space host (${describe(hostWrong)})`, ) : fail( - `a misaddressed listRepos returned ${describe(hostWrong)}`, + `a misaddressed listWriters returned ${describe(hostWrong)}`, hostWrong.json, ); }); @@ -695,7 +953,7 @@ const credentialWrongKey = defineCheck({ const thief = await readShared(ctx, credential, space.uri, { signWith: await createCredentialKey(), }); - return thief.status >= 400 && thief.status < 500 + return refused(thief.status) ? pass(`refused a signature by the wrong key (${describe(thief)})`) : fail( `a credential signed by a stranger's key returned ${describe(thief)}`, @@ -709,7 +967,10 @@ const credentialSchemeCase = defineCheck({ id: "credential.scheme-case-insensitive", title: "The Atproto-Space-Credential scheme is recognised regardless of case", tier: "must", - citations: [C("open-spaces-greet"), L("com.atproto.space.getRecord")], + citations: [ + P("0016#presenting-a-space-credential"), + L("com.atproto.space.getRecord"), + ], needs: ["operator"], destructive: true, async run(ctx) { @@ -728,7 +989,10 @@ const credentialCrossSpace = defineCheck({ id: "credential.cross-space-refused", title: "A credential for one space cannot read another", tier: "must", - citations: [L("com.atproto.space.getRecord")], + citations: [ + L("com.atproto.space.getRecord"), + P("0016#presenting-a-space-credential"), + ], needs: ["operator"], destructive: true, async run(ctx) { @@ -772,32 +1036,23 @@ const credentialUnhostedRepo = defineCheck({ // request carries a well-formed but unanswerable key share — the // host must find no repo before it could use one. const repo = fakeDid(); - const share = (await createCredentialKey()).did; const base = { space: space.uri, repo }; - const reads: Array<[string, Record, string | false]> = [ - [ - "getRecord", - { ...base, collection: POST, rkey: "shared" }, - formatWantMacHeader(RECORD_MAC_TYPE, share), - ], - ["getLatestCommit", base, formatWantMacHeader(COMMIT_MAC_TYPE, share)], - ["getRepo", base, formatWantMacHeader(COMMIT_MAC_TYPE, share)], - ["listRepoOps", base, formatWantMacHeader(COMMIT_MAC_TYPE, share)], - ["listRecords", base, false], - ["listBlobs", base, false], - [ - "getBlob", - { ...base, cid: await rawCid(utf8("no such blob")) }, - false, - ], + const reads: Array<[string, Record]> = [ + ["getRecord", { ...base, collection: POST, rkey: "shared" }], + ["getLatestCommit", base], + ["getRepo", base], + ["listRepoOps", base], + ["listRecords", base], + ["listBlobs", base], + ["getBlob", { ...base, cid: await rawCid(utf8("no such blob")) }], ]; const misses: string[] = []; - for (const [name, params, wantMac] of reads) { + for (const [name, params] of reads) { const res = await credentialCall( ctx, credential, `com.atproto.space.${name}`, - { params, wantMac }, + { params }, ); if (res.error !== "RepoNotFound") misses.push(`${name} → ${describe(res)}`); @@ -809,16 +1064,17 @@ const credentialUnhostedRepo = defineCheck({ }, }); -const macWantRequired = defineCheck({ - id: "mac.want-mac-required", +const macRequired = defineCheck({ + id: "mac.mac-request-required", title: - "Credentialed reads of a commit or record without Atproto-Space-Want-Mac answer BadSpaceMac", + "Credentialed reads of a commit or record without a MAC request answer InvalidSpaceMac", tier: "must", citations: [ - L("com.atproto.space.getLatestCommit@error:BadSpaceMac"), - L("com.atproto.space.getRecord@error:BadSpaceMac"), - L("com.atproto.space.getRepo@error:BadSpaceMac"), - L("com.atproto.space.listRepoOps@error:BadSpaceMac"), + L("com.atproto.space.getLatestCommit@error:InvalidSpaceMac"), + L("com.atproto.space.getRecord@error:InvalidSpaceMac"), + L("com.atproto.space.getRepo@error:InvalidSpaceMac"), + L("com.atproto.space.listRepoOps@error:InvalidSpaceMac"), + P("0016#requesting-a-mac"), ], needs: ["operator"], destructive: true, @@ -834,82 +1090,132 @@ const macWantRequired = defineCheck({ const misses: string[] = []; for (const [name, params] of reads) { const nsid = `com.atproto.space.${name}`; - // Positive control per method: with the header it is served. const ok = await credentialGet(ctx, credential, nsid, params); if (ok.status !== 200) { misses.push(`${name} with a MAC request → ${describe(ok)}`); continue; } - const res = await credentialCall(ctx, credential, nsid, { + const none = await credentialCall(ctx, credential, nsid, { + params, + mac: false, + }); + if (none.error !== "InvalidSpaceMac") + misses.push(`${name} without → ${describe(none)}`); + // A request only for another tag is ignored, leaving none. + const profile = + name === "getRecord" ? RECORD_MAC_PROFILE : COMMIT_MAC_PROFILE; + const otherTag = await credentialCall(ctx, credential, nsid, { params, - wantMac: false, + mac: { + profile, + header: (k) => + formatMacRequest(profile, k).replace( + `tag="${profile}"`, + 'tag="some-other-profile"', + ), + }, }); - if (res.error !== "BadSpaceMac") - misses.push(`${name} without → ${describe(res)}`); + if (otherTag.error !== "InvalidSpaceMac") + misses.push(`${name} with only another tag → ${describe(otherTag)}`); } return misses.length ? fail(misses.join("; ")) : pass( - "each served with a MAC request and answered BadSpaceMac without one", + "each served with a MAC request and answered InvalidSpaceMac without one", ); }); }, }); const macMalformed = defineCheck({ - id: "mac.malformed-want-mac-rejected", - title: "A malformed or mistyped Atproto-Space-Want-Mac answers BadSpaceMac", + id: "mac.malformed-request-rejected", + title: "A malformed MAC request answers InvalidSpaceMac", tier: "must", citations: [ - L("com.atproto.space.getLatestCommit@error:BadSpaceMac"), - L("com.atproto.space.getRecord@error:BadSpaceMac"), + L("com.atproto.space.getLatestCommit@error:InvalidSpaceMac"), + L("com.atproto.space.getRecord@error:InvalidSpaceMac"), + P("0016#requesting-a-mac"), ], needs: ["operator"], destructive: true, async run(ctx) { return withPublicSpace(ctx, async (space, credential) => { - const share = (await createCredentialKey()).did; const commit = { space: space.uri, repo: ctx.target.did }; - const probes: Array<[string, string, Record, string]> = [ + const c = COMMIT_MAC_PROFILE; + const probes: Array< + [string, Record, (k: string) => string] + > = [ [ - "bad key share", - "getLatestCommit", + "invalid keyid", commit, - `type="${COMMIT_MAC_TYPE}", ver=1, key_share="did:key:zNotAKey"`, + () => formatMacRequest(c, "did:key:zNotAKey"), ], [ - "unsupported version", - "getLatestCommit", + "keyid not a P-256 key", commit, - `type="${COMMIT_MAC_TYPE}", ver=99, key_share="${share}"`, + () => + formatMacRequest( + c, + formatDidKey( + "ES256K", + new Uint8Array([ + 2, + ...crypto.getRandomValues(new Uint8Array(32)), + ]), + ), + ), ], [ - "record read asking for a commit MAC", - "getRecord", - recordParams(ctx, space.uri), - formatWantMacHeader(COMMIT_MAC_TYPE, share), + "two requests with the tag", + commit, + (k) => + `${formatMacRequest(c, k)}, ${formatMacRequest(c, k, { label: "mac2" })}`, + ], + [ + "an extra parameter", + commit, + (k) => + formatMacRequest(c, k, { + params: [["created", Math.floor(Date.now() / 1000)]], + }), ], [ - "not a structured header", - "getRecord", + "alg other than hmac-sha256", + commit, + (k) => + formatMacRequest(c, k, { params: [["alg", "ecdsa-p256-sha256"]] }), + ], + [ + "wrong covered header", + commit, + (k) => + formatMacRequest(c, k).replace( + '("atproto-space-commit";sf)', + '("atproto-space-record";sf)', + ), + ], + [ + "not a structured field", recordParams(ctx, space.uri), - "please", + () => "please", ], ]; const misses: string[] = []; - for (const [label, name, params, header] of probes) { - const res = await credentialCall( - ctx, - credential, - `com.atproto.space.${name}`, - { params, wantMac: header }, - ); - if (res.error !== "BadSpaceMac") + for (const [label, params, header] of probes) { + const nsid = params.rkey + ? "com.atproto.space.getRecord" + : "com.atproto.space.getLatestCommit"; + const profile = params.rkey ? RECORD_MAC_PROFILE : COMMIT_MAC_PROFILE; + const res = await credentialCall(ctx, credential, nsid, { + params, + mac: { profile, header }, + }); + if (res.error !== "InvalidSpaceMac") misses.push(`${label} → ${describe(res)}`); } return misses.length - ? fail(`expected BadSpaceMac: ${misses.join("; ")}`) - : pass("every malformed MAC request answered BadSpaceMac"); + ? fail(`expected InvalidSpaceMac: ${misses.join("; ")}`) + : pass("every malformed MAC request answered InvalidSpaceMac"); }); }, }); @@ -918,22 +1224,26 @@ export const credentialChecks: Check[] = [ credentialTokenlessPolicies, credentialClaims, credentialDefaultLifetime, - credentialKidP256, + credentialSpaceRev, + credentialKeyP256, credentialGarbageDelegation, credentialUnverifiableAttestation, credentialGarbageAttestation, credentialAllowedApps, credentialDeletedSpace, + credentialUnconfirmedRegistration, credentialSelfRoundTrip, delegationClaims, delegationReplay, delegationWrongSpace, credentialSignatureRequired, + credentialSignatureByTag, + credentialSignatureRequirements, credentialAudienceBound, credentialWrongKey, credentialSchemeCase, credentialCrossSpace, credentialUnhostedRepo, - macWantRequired, + macRequired, macMalformed, ]; diff --git a/packages/space-conformance/src/checks/host.ts b/packages/space-conformance/src/checks/host.ts index dc3b763..a67fc8a 100644 --- a/packages/space-conformance/src/checks/host.ts +++ b/packages/space-conformance/src/checks/host.ts @@ -1,8 +1,10 @@ /** - * The space-host role: the writer set (listRepos, removeWriter) and - * notification registration (registerNotify / unregisterNotify), plus — - * when the harness runs a syncer inbox — the notifications the host sends. - * Browser-safe; the inbox checks need a harness that can receive them. + * The space-host role: the writer set (listWriters, removeWriter) and, + * when the harness serves a syncer inbox, the notifications the host sends + * through `authorizeSpaceSync`'s `notify` registration — + * confirmRegistration, then notifySpaceUpdate for writes, removals and + * deletion. Browser-safe; the inbox checks need a harness the target can + * reach. */ import { defineCheck } from "../registry.js"; @@ -13,38 +15,39 @@ import { type Check, type CheckContext, type InboxDelivery, + type SyncerInbox, } from "../model.js"; -import { bytesEqual, isTid, lexBytes } from "../encoding.js"; +import { bytesEqual, decodeJwt, isTid, lexBytes } from "../encoding.js"; import { - FOREIGN_DID, createProbeSpace, + managedspace, credentialCall, deleteProbeSpace, describe, mustCreateRecord, obtainPublicCredential, publicRead, + requestCredential, type Credential, } from "./probe.js"; import { fakeDid } from "./space.js"; const L = (ref: string) => ({ source: "lexicon" as const, ref }); +const P = (ref: string) => ({ source: "proposal" as const, ref }); -/** - * A service identifier sure to resolve: the target's own `#atproto_pds` - * entry, named explicitly by fragment (registerNotify: "a DID with an - * optional service fragment naming the entry in its DID document"). - */ -const ownService = (ctx: CheckContext) => `${ctx.target.did}#atproto_pds`; +const REPO_WRITE = "com.atproto.space.defs#repoWrite"; +const REPO_REMOVED = "com.atproto.space.defs#repoRemoved"; +const SPACE_DELETED = "com.atproto.space.notifySpaceUpdate#spaceDeleted"; interface WriterEntry { - did: string; - repoRev: unknown; - data: unknown; - spaceRev: unknown; + $type?: string; + repo?: string; + repoRev?: unknown; + data?: unknown; + spaceRev?: unknown; } -async function listRepos( +export async function listWriters( ctx: CheckContext, credential: Credential, params: Record = {}, @@ -52,7 +55,7 @@ async function listRepos( const res = await credentialCall( ctx, credential, - "com.atproto.space.listRepos", + "com.atproto.space.listWriters", { params: { space: credential.space, ...params }, audience: ctx.target.did, @@ -64,62 +67,51 @@ async function listRepos( return { res, repos: body?.repos ?? [], cursor: body?.cursor }; } +/** The latest entry for `repo` in the whole writer set. */ +async function writerEntry( + ctx: CheckContext, + credential: Credential, + repo: string, +) { + const { repos } = await listWriters(ctx, credential, { limit: "1000" }); + return repos.filter((r) => r.repo === repo).at(-1); +} + const hostRequiresCredential = defineCheck({ - id: "host.listrepos-requires-credential", - title: - "listRepos, registerNotify and unregisterNotify refuse an unauthenticated caller", + id: "host.listwriters-requires-credential", + title: "listWriters refuses an unauthenticated caller", tier: "must", - citations: [ - L("com.atproto.space.listRepos"), - L("com.atproto.space.registerNotify"), - L("com.atproto.space.unregisterNotify"), - ], + citations: [L("com.atproto.space.listWriters")], needs: ["operator"], destructive: true, async run(ctx) { const space = await createProbeSpace(ctx, publicRead()); try { - const probes = [ - [ - "listRepos", - await xrpcGet(ctx, "com.atproto.space.listRepos", { - space: space.uri, - }), - ], - [ - "registerNotify", - await xrpcPost(ctx, "com.atproto.space.registerNotify", { - space: space.uri, - service: ownService(ctx), - }), - ], - [ - "unregisterNotify", - await xrpcPost(ctx, "com.atproto.space.unregisterNotify", { - space: space.uri, - service: ownService(ctx), - }), - ], - ] as const; - const served = probes.filter( - ([, r]) => r.status !== 401 && r.status !== 403, - ); - return served.length - ? fail( - `not refused with 401/403: ${served.map(([n, r]) => `${n} → ${describe(r)}`).join("; ")}`, - ) - : pass("all three refused an unauthenticated caller"); + const res = await xrpcGet(ctx, "com.atproto.space.listWriters", { + space: space.uri, + }); + return res.status === 401 || res.status === 403 + ? pass(`refused with ${res.status}`) + : fail( + `unauthenticated listWriters returned ${describe(res)}`, + res.json, + ); } finally { await deleteProbeSpace(ctx, space.uri); } }, }); -const listReposShape = defineCheck({ - id: "sync.listrepos-shape", - title: "listRepos lists writers by ascending spaceRev with a spaceRev cursor", +const listWritersShape = defineCheck({ + id: "sync.listwriters-shape", + title: + "listWriters lists typed repoWrite entries by ascending spaceRev, resumable by cursor", tier: "must", - citations: [L("com.atproto.space.listRepos")], + citations: [ + L("com.atproto.space.listWriters"), + L("com.atproto.space.defs#repoWrite"), + P("0016#the-sync-boundary-writer-set"), + ], needs: ["operator"], destructive: true, async run(ctx) { @@ -128,40 +120,46 @@ const listReposShape = defineCheck({ await mustCreateRecord(ctx, space.uri, "a"); await mustCreateRecord(ctx, space.uri, "b"); const credential = await obtainPublicCredential(ctx, space.uri); - const page = await listRepos(ctx, credential); + const page = await listWriters(ctx, credential); if (page.res.status !== 200) - return fail(`listRepos ${describe(page.res)}`, page.res.json); + return fail(`listWriters ${describe(page.res)}`, page.res.json); const problems: string[] = []; - for (const repo of page.repos) { - const data = lexBytes(repo.data); - if (!isTid(repo.repoRev)) - problems.push(`${repo.did} repoRev ${String(repo.repoRev)}`); - if (!isTid(repo.spaceRev)) - problems.push(`${repo.did} spaceRev ${String(repo.spaceRev)}`); - if (!data || data.length !== 32) - problems.push(`${repo.did} data is not 32 bytes`); + for (const entry of page.repos) { + if (entry.$type !== REPO_WRITE && entry.$type !== REPO_REMOVED) + problems.push(`entry $type ${String(entry.$type)}`); + if (!isTid(entry.spaceRev)) + problems.push(`${entry.repo} spaceRev ${String(entry.spaceRev)}`); + if (entry.$type === REPO_WRITE) { + if (!isTid(entry.repoRev)) + problems.push(`${entry.repo} repoRev ${String(entry.repoRev)}`); + if (lexBytes(entry.data)?.length !== 32) + problems.push(`${entry.repo} data is not 32 bytes`); + } + if ("prevSpaceRev" in entry) + problems.push("listWriters entries carry prevSpaceRev"); } const revs = page.repos.map((r) => String(r.spaceRev)); if (revs.some((rev, i) => i > 0 && rev <= revs[i - 1]!)) problems.push(`not ascending: ${revs.join(",")}`); - if (!page.repos.some((r) => r.did === ctx.target.did)) - problems.push("the authority's own repo is not listed"); - if (page.repos.length && page.cursor !== revs.at(-1)) { - problems.push( - `cursor ${page.cursor} is not the last spaceRev ${revs.at(-1)}`, - ); + if ( + !page.repos.some( + (r) => r.repo === ctx.target.did && r.$type === REPO_WRITE, + ) + ) { + problems.push("the authority's own repo is not listed as a repoWrite"); } + if (!page.cursor) problems.push("a non-empty page carried no cursor"); if (problems.length) return fail(problems.join("; "), page.res.json); - // Resuming from the cursor reaches an empty page, which carries no cursor. - const next = await listRepos(ctx, credential, { cursor: page.cursor! }); + // Resuming from the cursor reaches only later updates — here, none. + const next = await listWriters(ctx, credential, { cursor: page.cursor! }); if (next.res.status !== 200) - return fail(`listRepos(cursor) ${describe(next.res)}`, next.res.json); - return next.repos.length === 0 && next.cursor === undefined + return fail(`listWriters(cursor) ${describe(next.res)}`, next.res.json); + return next.repos.length === 0 ? pass( - `${page.repos.length} writer(s), ascending, cursor resumes to an empty page`, + `${page.repos.length} writer(s), typed and ascending; the cursor resumes after them`, ) : fail( - `after the last cursor: ${next.repos.length} repo(s), cursor ${next.cursor}`, + `after the last cursor: ${next.repos.length} repo(s) again`, next.res.json, ); } finally { @@ -170,29 +168,27 @@ const listReposShape = defineCheck({ }, }); -const listReposReflects = defineCheck({ - id: "sync.listrepos-reflects-writes", - title: "The authority's listRepos entry matches its latest commit", +const listWritersReflects = defineCheck({ + id: "sync.listwriters-reflects-writes", + title: "The authority's listWriters entry matches its latest commit", tier: "should", citations: [ { source: "reference", ref: "authority repo notifies its own space host synchronously", }, - L("com.atproto.space.listRepos"), + L("com.atproto.space.listWriters"), ], needs: ["operator"], destructive: true, async run(ctx) { - // The lexicon allows the entry to lag ("as last reported"), so this is - // calibrated against the reference, which notifies its own host on - // commit. + // The proposal lets the entry lag ("current as far as the authority's + // notifications have kept it"), so this is calibrated on the reference. const space = await createProbeSpace(ctx, publicRead()); try { await mustCreateRecord(ctx, space.uri, "a"); const credential = await obtainPublicCredential(ctx, space.uri); - const { repos } = await listRepos(ctx, credential); - const mine = repos.find((r) => r.did === ctx.target.did); + const mine = await writerEntry(ctx, credential, ctx.target.did); const latest = await xrpcGet( asOperator(ctx), "com.atproto.space.getLatestCommit", @@ -213,7 +209,7 @@ const listReposReflects = defineCheck({ b && bytesEqual(a, b) ? pass("repoRev and data match getLatestCommit") - : fail("listRepos entry differs from the latest commit", { + : fail("listWriters entry differs from the latest commit", { listed: mine, commit, }); @@ -225,38 +221,40 @@ const listReposReflects = defineCheck({ const removeWriter = defineCheck({ id: "host.removewriter", - title: "removeWriter drops a repo from listRepos until it writes again", + title: "removeWriter lists the repo as repoRemoved until it writes again", tier: "must", citations: [ L("com.atproto.space.removeWriter"), - L("com.atproto.space.listRepos"), + L("com.atproto.space.listWriters"), + L("com.atproto.space.defs#repoRemoved"), + P("0016#the-sync-boundary-writer-set"), ], needs: ["operator"], destructive: true, async run(ctx) { const space = await createProbeSpace(ctx, publicRead()); - const remove = (did: string) => + const remove = (repo: string) => xrpcPost(asOperator(ctx), "com.atproto.space.removeWriter", { space: space.uri, - did, + repo, }); try { await mustCreateRecord(ctx, space.uri, "a"); const credential = await obtainPublicCredential(ctx, space.uri); - const listed = async () => - (await listRepos(ctx, credential)).repos.some( - (r) => r.did === ctx.target.did, - ); - if (!(await listed())) + const before = await writerEntry(ctx, credential, ctx.target.did); + if (before?.$type !== REPO_WRITE) return fail( "the authority's repo was not in the writer set to begin with", ); const removed = await remove(ctx.target.did); if (removed.status !== 200) return fail(`removeWriter ${describe(removed)}`, removed.json); - if (await listed()) - return fail("removeWriter left the repo in listRepos"); - // Idempotent: removing an account that isn't a writer succeeds. + const gone = await writerEntry(ctx, credential, ctx.target.did); + if (gone?.$type !== REPO_REMOVED) + return fail(`after removeWriter the entry is ${JSON.stringify(gone)}`); + if (!(String(gone.spaceRev) > String(before.spaceRev))) + return fail("the removal was not sequenced after the write"); + // "Does nothing if the account is not in the writer set." const absent = await remove(fakeDid()); if (absent.status !== 200) return fail( @@ -264,153 +262,165 @@ const removeWriter = defineCheck({ absent.json, ); await mustCreateRecord(ctx, space.uri, "b"); - return (await listed()) + const back = await writerEntry(ctx, credential, ctx.target.did); + return back?.$type === REPO_WRITE ? pass( - "removed, idempotent for a non-writer, and tracked again after a new write", + "listed as repoRemoved at a later spaceRev; no-op for a non-writer; a new write re-added it", ) - : fail( - "a new write by an authorised account did not return it to the writer set", - ); + : fail(`after a new write the entry is ${JSON.stringify(back)}`); } finally { await deleteProbeSpace(ctx, space.uri); } }, }); -const registerRoundTrip = defineCheck({ - id: "host.registernotify-round-trip", - title: - "registerNotify returns a future expiry; unregisterNotify is idempotent", +const hostAfterDelete = defineCheck({ + id: "host.deleted-space-not-found", + title: "listWriters on a deleted space answers SpaceNotFound", tier: "must", - citations: [ - L("com.atproto.space.registerNotify"), - L("com.atproto.space.unregisterNotify"), - ], + citations: [L("com.atproto.space.listWriters@error:SpaceNotFound")], needs: ["operator"], destructive: true, async run(ctx) { + // A credential issued before deletion is still well-formed and + // unexpired; what has gone is the space. const space = await createProbeSpace(ctx, publicRead()); - try { - const credential = await obtainPublicCredential(ctx, space.uri); - const call = (nsid: string) => - credentialCall(ctx, credential, nsid, { - body: { space: space.uri, service: ownService(ctx) }, - audience: ctx.target.did, - }); - const reg = await call("com.atproto.space.registerNotify"); - if (reg.status !== 200) - return fail(`registerNotify ${describe(reg)}`, reg.json); - const expiresAt = Date.parse( - String((reg.json as { expiresAt?: unknown }).expiresAt), - ); - if (!(expiresAt > Date.now())) - return fail("expiresAt is not a future datetime", reg.json); - const un1 = await call("com.atproto.space.unregisterNotify"); - const un2 = await call("com.atproto.space.unregisterNotify"); - return un1.status === 200 && un2.status === 200 - ? pass("registered with a future expiry; unregistered twice") - : fail( - `unregisterNotify returned ${describe(un1)} then ${describe(un2)}`, - { first: un1.json, second: un2.json }, - ); - } finally { - await deleteProbeSpace(ctx, space.uri); - } + const credential = await obtainPublicCredential(ctx, space.uri); + await deleteProbeSpace(ctx, space.uri); + const { res } = await listWriters(ctx, credential); + return res.error === "SpaceNotFound" + ? pass("answered SpaceNotFound") + : fail(`answered ${describe(res)}, expected SpaceNotFound`, res.json); }, }); -const registerUnresolvable = defineCheck({ - id: "host.registernotify-unresolvable", +// --- notifications to a harness syncer ------------------------------------ + +const NOTIFY_TIMEOUT_MS = 10_000; + +/** Authorise with a fresh notify registration at the inbox. */ +async function register(ctx: CheckContext, inbox: SyncerInbox, space: string) { + const token = inbox.issueToken(space); + const since = Date.now(); + const res = await requestCredential(ctx, space, { + notify: { endpoint: inbox.endpoint, token }, + }); + return { token, since, ...res }; +} + +const updatesFor = + (space: string, token: string, type: string, since: number) => + (d: InboxDelivery) => { + const body = d.body as + | { space?: string; token?: string; update?: { $type?: string } } + | undefined; + return ( + d.lxm === "com.atproto.space.notifySpaceUpdate" && + d.receivedAt >= since && + body?.space === space && + body.token === token && + body.update?.$type === type + ); + }; + +const notifyConfirmed = defineCheck({ + id: "notify.registration-confirmed", title: - "registerNotify for a service that does not resolve answers ServiceNotResolvable", + "A notify registration is confirmed with a challenge before the credential is issued", tier: "must", - citations: [L("com.atproto.space.registerNotify@error:ServiceNotResolvable")], - needs: ["operator"], + citations: [ + L("com.atproto.space.confirmRegistration"), + L("com.atproto.space.authorizeSpaceSync#notify"), + P("0016#registering-for-notifications"), + ], + needs: ["operator", "syncer-inbox"], destructive: true, async run(ctx) { + const inbox = ctx.syncerInbox!; const space = await createProbeSpace(ctx, publicRead()); try { - const credential = await obtainPublicCredential(ctx, space.uri); - const res = await credentialCall( - ctx, - credential, - "com.atproto.space.registerNotify", - { - body: { space: space.uri, service: `${FOREIGN_DID}#space_syncer` }, - audience: ctx.target.did, - }, + const reg = await register(ctx, inbox, space.uri); + if (!reg.credential) + return fail( + `authorizeSpaceSync with notify ${describe(reg.result)}`, + reg.result.json, + ); + const confirm = await inbox.waitFor( + (d) => + d.lxm === "com.atproto.space.confirmRegistration" && + d.receivedAt >= reg.since && + (d.body as { token?: string } | undefined)?.token === reg.token, + 1_000, + ); + if (!confirm) + return fail( + "the credential was issued without calling confirmRegistration", + ); + const body = confirm.body as { space?: string; challenge?: unknown }; + if (body.space !== space.uri) + return fail(`confirmRegistration named space ${body.space}`); + if (typeof body.challenge !== "string" || body.challenge.length < 8) + return fail("confirmRegistration carried no real challenge", body); + return pass( + "confirmRegistration (space, token, challenge) preceded the credential", ); - return res.error === "ServiceNotResolvable" - ? pass("answered ServiceNotResolvable") - : fail( - `answered ${describe(res)}, expected ServiceNotResolvable`, - res.json, - ); } finally { await deleteProbeSpace(ctx, space.uri); } }, }); -const hostAfterDelete = defineCheck({ - id: "host.deleted-space-not-found", - title: "Space-host methods on a deleted space answer SpaceNotFound", - tier: "must", +const notifyRenewal = defineCheck({ + id: "notify.renewal-not-reconfirmed", + title: + "Reauthorizing with the same notify pair renews without confirming again", + tier: "should", citations: [ - L("com.atproto.space.listRepos@error:SpaceNotFound"), - L("com.atproto.space.registerNotify@error:SpaceNotFound"), - L("com.atproto.space.unregisterNotify@error:SpaceNotFound"), + { + source: "reference", + ref: "pds authorizeSpaceSync confirms only unregistered pairs", + }, + P("0016#registering-for-notifications"), ], - needs: ["operator"], + needs: ["operator", "syncer-inbox"], destructive: true, async run(ctx) { - // A credential issued before deletion is still a well-formed, unexpired - // credential; what has gone is the space. + const inbox = ctx.syncerInbox!; const space = await createProbeSpace(ctx, publicRead()); - const credential = await obtainPublicCredential(ctx, space.uri); - await deleteProbeSpace(ctx, space.uri); - const body = { space: space.uri, service: ownService(ctx) }; - const probes = [ - ["listRepos", await listRepos(ctx, credential).then((r) => r.res)], - [ - "registerNotify", - await credentialCall( - ctx, - credential, - "com.atproto.space.registerNotify", - { body, audience: ctx.target.did }, - ), - ], - [ - "unregisterNotify", - await credentialCall( - ctx, - credential, - "com.atproto.space.unregisterNotify", - { body, audience: ctx.target.did }, - ), - ], - ] as const; - const misses = probes.filter(([, r]) => r.error !== "SpaceNotFound"); - return misses.length - ? fail( - `expected SpaceNotFound: ${misses.map(([n, r]) => `${n} → ${describe(r)}`).join("; ")}`, - ) - : pass("all three answered SpaceNotFound"); + try { + const first = await register(ctx, inbox, space.uri); + if (!first.credential) + return fail(`authorizeSpaceSync ${describe(first.result)}`); + const since = Date.now(); + const again = await requestCredential(ctx, space.uri, { + notify: { endpoint: inbox.endpoint, token: first.token }, + }); + if (!again.credential) + return fail(`reauthorizing ${describe(again.result)}`); + const reconfirmed = await inbox.waitFor( + (d) => + d.lxm === "com.atproto.space.confirmRegistration" && + d.receivedAt >= since && + (d.body as { token?: string })?.token === first.token, + 500, + ); + return reconfirmed + ? fail("the renewal was confirmed again") + : pass("renewed without a second confirmation"); + } finally { + await deleteProbeSpace(ctx, space.uri); + } }, }); -// --- deliveries to a harness syncer -------------------------------------- - -const NOTIFY_TIMEOUT_MS = 10_000; - -const forwardedNotifyWrite = defineCheck({ - id: "notify.forwarded-notifywrite", - title: "A registered syncer receives sequenced notifyWrite calls", +const notifyRepoWrite = defineCheck({ + id: "notify.repo-write-delivered", + title: "A registered syncer receives sequenced repoWrite updates", tier: "must", citations: [ - L("com.atproto.space.notifyWrite"), - L("com.atproto.space.registerNotify"), + L("com.atproto.space.notifySpaceUpdate"), + L("com.atproto.space.defs#repoWrite"), + P("0016#write-notifications"), ], needs: ["operator", "syncer-inbox"], destructive: true, @@ -419,79 +429,115 @@ const forwardedNotifyWrite = defineCheck({ const space = await createProbeSpace(ctx, publicRead()); try { await mustCreateRecord(ctx, space.uri, "before"); - const credential = await obtainPublicCredential(ctx, space.uri); - const reg = await credentialCall( - ctx, - credential, - "com.atproto.space.registerNotify", - { - body: { space: space.uri, service: inbox.service }, - audience: ctx.target.did, - }, - ); - if (reg.status !== 200) - return fail(`registerNotify ${describe(reg)}`, reg.json); - const forThis = (d: InboxDelivery) => - d.lxm === "com.atproto.space.notifyWrite" && - (d.body as { space?: string } | undefined)?.space === space.uri; + const reg = await register(ctx, inbox, space.uri); + if (!reg.credential) + return fail( + `authorizeSpaceSync with notify ${describe(reg.result)}`, + reg.result.json, + ); const since = Date.now(); await mustCreateRecord(ctx, space.uri, "one"); const first = await inbox.waitFor( - (d) => forThis(d) && d.receivedAt >= since, + updatesFor(space.uri, reg.token, REPO_WRITE, since), NOTIFY_TIMEOUT_MS, ); - if (!first) - return fail("no notifyWrite reached the syncer after a write"); - const a = first.body as Record; + if (!first) return fail("no repoWrite reached the syncer after a write"); + const a = (first.body as { update: Record }).update; await mustCreateRecord(ctx, space.uri, "two"); const second = await inbox.waitFor( (d) => - forThis(d) && - (d.body as { spaceRev?: string }).spaceRev !== a.spaceRev && - d.receivedAt >= first.receivedAt, + updatesFor(space.uri, reg.token, REPO_WRITE, first.receivedAt)(d) && + (d.body as { update: { spaceRev?: unknown } }).update.spaceRev !== + a.spaceRev, NOTIFY_TIMEOUT_MS, ); if (!second) - return fail("no notifyWrite reached the syncer after a second write"); - const b = second.body as Record; + return fail("no repoWrite reached the syncer after a second write"); + const b = (second.body as { update: Record }).update; const problems: string[] = []; - for (const [label, body] of [ + for (const [label, u] of [ ["first", a], ["second", b], ] as const) { - if (body.repo !== ctx.target.did) - problems.push(`${label} repo ${String(body.repo)}`); - if (!isTid(body.repoRev)) - problems.push(`${label} repoRev ${String(body.repoRev)}`); - if (!isTid(body.spaceRev)) problems.push(`${label} has no spaceRev`); - if (lexBytes(body.data)?.length !== 32) + if (u.repo !== ctx.target.did) + problems.push(`${label} repo ${String(u.repo)}`); + if (!isTid(u.repoRev)) + problems.push(`${label} repoRev ${String(u.repoRev)}`); + if (!isTid(u.spaceRev)) problems.push(`${label} has no spaceRev`); + if (lexBytes(u.data)?.length !== 32) problems.push(`${label} data is not 32 bytes`); } + // The first write in the space preceded registration, so both carry one. + if (a.prevSpaceRev === undefined) + problems.push("first update has no prevSpaceRev"); if (b.prevSpaceRev !== a.spaceRev) problems.push( `second prevSpaceRev ${String(b.prevSpaceRev)} ≠ first spaceRev ${String(a.spaceRev)}`, ); - if (!second.authorization?.startsWith("Bearer ")) - problems.push("delivered without service auth"); return problems.length ? fail(problems.join("; "), { first: a, second: b }) - : pass( - "two sequenced deliveries; prevSpaceRev chains to the previous spaceRev", - ); + : pass("two repoWrite updates carrying the token; prevSpaceRev chains"); } finally { await deleteProbeSpace(ctx, space.uri); } }, }); -const spaceDeletedDelivered = defineCheck({ +const notifyRepoRemoved = defineCheck({ + id: "notify.repo-removed-delivered", + title: "removeWriter is announced to registered syncers as repoRemoved", + tier: "must", + citations: [ + L("com.atproto.space.removeWriter"), + L("com.atproto.space.defs#repoRemoved"), + L("com.atproto.space.notifySpaceUpdate"), + P("0016#the-sync-boundary-writer-set"), + ], + needs: ["operator", "syncer-inbox"], + destructive: true, + async run(ctx) { + const inbox = ctx.syncerInbox!; + const space = await createProbeSpace(ctx, publicRead()); + try { + await mustCreateRecord(ctx, space.uri, "a"); + const reg = await register(ctx, inbox, space.uri); + if (!reg.credential) + return fail( + `authorizeSpaceSync with notify ${describe(reg.result)}`, + reg.result.json, + ); + const since = Date.now(); + const removed = await xrpcPost( + asOperator(ctx), + "com.atproto.space.removeWriter", + { space: space.uri, repo: ctx.target.did }, + ); + if (removed.status !== 200) + return fail(`removeWriter ${describe(removed)}`, removed.json); + const got = await inbox.waitFor( + updatesFor(space.uri, reg.token, REPO_REMOVED, since), + NOTIFY_TIMEOUT_MS, + ); + if (!got) return fail("no repoRemoved reached the syncer"); + const u = (got.body as { update: Record }).update; + return u.repo === ctx.target.did && + isTid(u.spaceRev) && + isTid(u.prevSpaceRev) + ? pass("repoRemoved delivered with spaceRev and prevSpaceRev") + : fail("repoRemoved fields wrong", u); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const notifySpaceDeleted = defineCheck({ id: "notify.space-deleted-delivered", - title: - "A registered syncer is sent notifySpaceDeleted when the space is deleted", + title: "A registered syncer is sent spaceDeleted when the space is deleted", tier: "must", citations: [ - L("com.atproto.space.notifySpaceDeleted"), - L("com.atproto.space.deleteSpace"), + L("com.atproto.space.notifySpaceUpdate#spaceDeleted"), + P("0016#space-deletion"), ], needs: ["operator", "syncer-inbox"], destructive: true, @@ -500,43 +546,221 @@ const spaceDeletedDelivered = defineCheck({ const space = await createProbeSpace(ctx, publicRead()); let deleted = false; try { - const credential = await obtainPublicCredential(ctx, space.uri); - const reg = await credentialCall( - ctx, - credential, - "com.atproto.space.registerNotify", - { - body: { space: space.uri, service: inbox.service }, - audience: ctx.target.did, - }, - ); - if (reg.status !== 200) - return fail(`registerNotify ${describe(reg)}`, reg.json); + const reg = await register(ctx, inbox, space.uri); + if (!reg.credential) + return fail( + `authorizeSpaceSync with notify ${describe(reg.result)}`, + reg.result.json, + ); + const since = Date.now(); await deleteProbeSpace(ctx, space.uri); deleted = true; const got = await inbox.waitFor( - (d) => - d.lxm === "com.atproto.space.notifySpaceDeleted" && - (d.body as { space?: string } | undefined)?.space === space.uri, + updatesFor(space.uri, reg.token, SPACE_DELETED, since), NOTIFY_TIMEOUT_MS, ); return got - ? pass("notifySpaceDeleted delivered") - : fail(`no notifySpaceDeleted within ${NOTIFY_TIMEOUT_MS / 1000}s`); + ? pass("spaceDeleted delivered") + : fail(`no spaceDeleted within ${NOTIFY_TIMEOUT_MS / 1000}s`); } finally { if (!deleted) await deleteProbeSpace(ctx, space.uri); } }, }); +const notifyExpired = defineCheck({ + id: "notify.registration-expired", + title: + "Once its credential expires, a registration is sent registrationExpired in place of the next update", + tier: "must", + citations: [ + L("com.atproto.space.notifySpaceUpdate#registrationExpired"), + P("0016#registering-for-notifications"), + ], + needs: ["operator", "syncer-inbox"], + destructive: true, + // Waits out a real credential lifetime (10 minutes by default). + slow: true, + timeoutMs: 65 * 60_000, + async run(ctx) { + const inbox = ctx.syncerInbox!; + const space = await createProbeSpace(ctx, publicRead()); + try { + const reg = await register(ctx, inbox, space.uri); + if (!reg.credential) + return fail( + `authorizeSpaceSync with notify ${describe(reg.result)}`, + reg.result.json, + ); + const exp = + Number(decodeJwt(reg.credential.credential).payload.exp) * 1000; + await new Promise((r) => + setTimeout(r, Math.max(0, exp - Date.now()) + 5_000), + ); + const since = Date.now(); + await mustCreateRecord(ctx, space.uri, "late"); + const got = await inbox.waitFor( + (d) => + updatesFor( + space.uri, + reg.token, + "com.atproto.space.notifySpaceUpdate#registrationExpired", + since, + )(d), + NOTIFY_TIMEOUT_MS, + ); + if (!got) + return fail("no registrationExpired after the credential lapsed"); + const update = (got.body as { update: { spaceRev?: unknown } }).update; + const write = await inbox.waitFor( + updatesFor(space.uri, reg.token, REPO_WRITE, since), + 2_000, + ); + if (write) + return fail("a lapsed registration still received the repoWrite"); + return isTid(update.spaceRev) + ? pass("registrationExpired sent in place of the update") + : fail("registrationExpired has no spaceRev", update); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +// --- managedspace ------------------------------------------------------ + +const CHECK_ACCESS = "com.atproto.managedspace.checkAccess"; + +const managedTokenless = defineCheck({ + id: "managedspace.check-access-tokenless", + title: + "Without a delegation token a managedspace asks its managing app, with no repo", + tier: "must", + citations: [ + L("com.atproto.managedspace.checkAccess"), + L("com.atproto.managedspace.policy"), + P("0016#managedspace"), + ], + needs: ["operator", "syncer-inbox"], + destructive: true, + async run(ctx) { + const inbox = ctx.syncerInbox!; + let answer = { read: false, write: false }; + inbox.respond(CHECK_ACCESS, () => answer); + const space = await createProbeSpace(ctx, managedspace(inbox.service)); + try { + const since = Date.now(); + const denied = await requestCredential(ctx, space.uri); + if (denied.credential) + return fail("issued a credential the managing app refused"); + const asked = await inbox.waitFor( + (d) => d.lxm === CHECK_ACCESS && d.receivedAt >= since, + 5_000, + ); + if (!asked) + return fail( + `the managing app was never asked (${describe(denied.result)})`, + ); + const p = asked.params ?? {}; + if (p.space !== space.uri || "repo" in p || "access" in p) + return fail("checkAccess params wrong for a tokenless request", p); + const jwt = asked.authorization?.replace(/^Bearer /, ""); + const claims = jwt ? decodeJwt(jwt).payload : undefined; + if ( + claims?.lxm !== CHECK_ACCESS || + claims.iss !== ctx.target.did || + claims.aud !== inbox.service + ) { + return fail( + "checkAccess service auth does not name the method, the authority and the managing app", + claims, + ); + } + answer = { read: true, write: false }; + const allowed = await requestCredential(ctx, space.uri); + return allowed.credential + ? pass( + `asked with no repo under service auth; refused on read:false (${denied.result.error}), issued on read:true`, + ) + : fail( + `the managing app allowed reading but the credential was refused: ${describe(allowed.result)}`, + ); + } finally { + inbox.respond(CHECK_ACCESS, undefined); + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const managedFailsClosed = defineCheck({ + id: "managedspace.unreachable-app-fails-closed", + title: + "A managedspace whose managing app cannot be reached issues no credential", + tier: "must", + citations: [ + L("com.atproto.managedspace.policy"), + P("0016#managedspace"), + { source: "changeset", ref: "patient-managers-answer" }, + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace( + ctx, + managedspace("did:web:app.space-conformance.invalid#managing_app"), + ); + try { + const res = await requestCredential(ctx, space.uri); + if (res.credential) + return fail( + "issued a credential without an answer from the managing app", + ); + return pass(`refused (${describe(res.result)})`); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + +const managedUpstreamFailure = defineCheck({ + id: "managedspace.unreachable-app-upstream-failure", + title: + "An unreachable managing app is reported as UpstreamFailure, not a refusal", + tier: "should", + citations: [{ source: "changeset", ref: "patient-managers-answer" }], + needs: ["operator"], + destructive: true, + async run(ctx) { + // Distinct from a denial: a syncer keeps its registration and a repo + // host retries, rather than reading the failure as lost access. + const space = await createProbeSpace( + ctx, + managedspace("did:web:app.space-conformance.invalid#managing_app"), + ); + try { + const res = await requestCredential(ctx, space.uri); + return res.result.error === "UpstreamFailure" + ? pass("answered UpstreamFailure") + : fail(`answered ${describe(res.result)}`); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + export const hostChecks: Check[] = [ hostRequiresCredential, - listReposShape, - listReposReflects, + listWritersShape, + listWritersReflects, removeWriter, - registerRoundTrip, - registerUnresolvable, hostAfterDelete, - forwardedNotifyWrite, - spaceDeletedDelivered, + notifyConfirmed, + notifyRenewal, + notifyRepoWrite, + notifyRepoRemoved, + notifySpaceDeleted, + notifyExpired, + managedTokenless, + managedFailsClosed, + managedUpstreamFailure, ]; diff --git a/packages/space-conformance/src/checks/probe.ts b/packages/space-conformance/src/checks/probe.ts index c988e37..bcafffe 100644 --- a/packages/space-conformance/src/checks/probe.ts +++ b/packages/space-conformance/src/checks/probe.ts @@ -19,15 +19,16 @@ import { import type { CheckContext } from "../model.js"; import { kemKeyFor } from "../did.js"; import { - COMMIT_MAC_TYPE, - RECORD_MAC_TYPE, + COMMIT_MAC_PROFILE, + RECORD_MAC_PROFILE, SPACE_CREDENTIAL_SCHEME, createCredentialKey, encapsulate, - formatWantMacHeader, + formatMacRequest, spaceSigHeaders, type CredentialKey, - type MacType, + type CredentialSigOptions, + type MacProfile, } from "../space-auth.js"; // The probe collections and space type are published, resolvable @@ -117,7 +118,12 @@ export async function createProbeSpace( `createSpace failed: ${res.status} ${res.error ?? ""} ${JSON.stringify(res.json)}`, ); } - const uri = (res.json as { uri: string }).uri; + const uri = (res.json as { space: string }).space; + if (typeof uri !== "string") { + throw new Error( + `createSpace returned no space: ${JSON.stringify(res.json)}`, + ); + } return { uri, type: PROBE_TYPE, skey }; } @@ -189,9 +195,10 @@ export interface Credential { } /** - * Ask the space's authority for a credential. Nothing authenticates the + * Ask the space's authority to authorise sync. Nothing authenticates the * request itself: the body carries the key to bind, and optionally a - * delegation token (who the user is) and a client attestation (which app). + * delegation token (who the user is), a client attestation (which app) + * and a `notify` registration. */ export async function requestCredential( ctx: CheckContext, @@ -199,23 +206,35 @@ export async function requestCredential( opts: { delegationToken?: string; clientAttestation?: string; - credentialKid?: string; + credentialKey?: string; key?: CredentialKey; + notify?: { endpoint: string; token: string }; } = {}, -): Promise<{ result: XrpcResult; credential?: Credential }> { +): Promise<{ + result: XrpcResult; + credential?: Credential; + spaceRev?: string; +}> { const key = opts.key ?? (await createCredentialKey()); - const result = await xrpcPost(ctx, "com.atproto.space.getSpaceCredential", { + const result = await xrpcPost(ctx, "com.atproto.space.authorizeSpaceSync", { space, - credentialKid: opts.credentialKid ?? key.did, + credentialKey: opts.credentialKey ?? key.did, ...(opts.delegationToken ? { delegationToken: opts.delegationToken } : {}), ...(opts.clientAttestation ? { clientAttestation: opts.clientAttestation } : {}), + ...(opts.notify ? { notify: opts.notify } : {}), }); if (result.status === 200) { - const credential = (result.json as { credential?: unknown }).credential; - if (typeof credential === "string") { - return { result, credential: { credential, key, space } }; + const body = result.json as { credential?: unknown; spaceRev?: unknown }; + if (typeof body.credential === "string") { + return { + result, + credential: { credential: body.credential, key, space }, + ...(typeof body.spaceRev === "string" + ? { spaceRev: body.spaceRev } + : {}), + }; } } return { result }; @@ -229,7 +248,7 @@ export async function obtainPublicCredential( const { result, credential } = await requestCredential(ctx, space); if (!credential) { throw new Error( - `tokenless getSpaceCredential for a public-read space failed: ${result.status} ${result.error ?? ""}`, + `tokenless authorizeSpaceSync for a public-read space failed: ${result.status} ${result.error ?? ""}`, ); } return credential; @@ -238,7 +257,7 @@ export async function obtainPublicCredential( /** * Obtain a credential the way a real app does: ask the target's own * `getDelegationToken` (with the operator session) for a delegation token, - * then exchange it at `getSpaceCredential`. It needs no harness-held + * then exchange it at `authorizeSpaceSync`. It needs no harness-held * reader key, so it runs against any real PDS and exercises the target's * own token minting. */ @@ -265,12 +284,12 @@ export async function obtainCredentialViaDelegation( return { result, delegation, ...(credential ? { credential } : {}) }; } -/** Which MAC each repo-host read asks for. */ -const MAC_TYPES: Record = { - "com.atproto.space.getLatestCommit": COMMIT_MAC_TYPE, - "com.atproto.space.getRepo": COMMIT_MAC_TYPE, - "com.atproto.space.listRepoOps": COMMIT_MAC_TYPE, - "com.atproto.space.getRecord": RECORD_MAC_TYPE, +/** Which MAC profile each repo-host read asks for. */ +const MAC_PROFILES: Record = { + "com.atproto.space.getLatestCommit": COMMIT_MAC_PROFILE, + "com.atproto.space.getRepo": COMMIT_MAC_PROFILE, + "com.atproto.space.listRepoOps": COMMIT_MAC_PROFILE, + "com.atproto.space.getRecord": RECORD_MAC_PROFILE, }; export interface CredentialCallOptions { @@ -284,23 +303,40 @@ export interface CredentialCallOptions { */ audience?: string; /** - * The MAC to ask for. Defaults to what the method returns (commit or - * record) for the four MAC'd reads, nothing otherwise. `false` omits the - * header; a string sends it verbatim (malformed-header probes). + * The MAC to ask for. Defaults to the profile of what the method returns + * (commit or record) for the four MAC'd reads, nothing otherwise. `false` + * sends no `Accept-Signature`; an object requests the profile with a + * custom label or extra parameters; a function builds the whole header + * from a fresh key share (malformed-request probes). */ - wantMac?: MacType | false | string; + mac?: + | MacProfile + | false + | { + profile: MacProfile; + label?: string; + params?: Array<[string, string | number]>; + } + | { header: (keyShare: string) => string; profile: MacProfile }; /** Authorization scheme spelling; defaults to `Atproto-Space-Credential`. */ scheme?: string; /** Sign with this key instead of the credential's own. */ signWith?: CredentialKey; + /** Signature label, parameters, components or tag overrides. */ + signature?: Omit; + /** Replace the signature headers wholesale (e.g. two signatures). */ + signatureHeaders?: ( + defaults: Record, + ) => Promise>; /** Send no signature headers at all. */ unsigned?: boolean; } export interface CredentialResult extends XrpcResult { - /** The KEM shared secret, when a MAC was requested. */ + /** The MAC request's encapsulation, when a MAC was requested. */ + keyShare?: string; sharedSecret?: Uint8Array; - macType?: MacType; + macProfile?: MacProfile; } /** Present a credential on one request: signature, audience, MAC request. */ @@ -313,32 +349,43 @@ export async function credentialCall( const repo = opts.params?.repo; const audience = opts.audience ?? repo ?? spaceAuthority(credential.space); const authorization = `${opts.scheme ?? SPACE_CREDENTIAL_SCHEME} ${credential.credential}`; - const headers = new Headers( - opts.unsigned - ? { authorization } - : await spaceSigHeaders(opts.signWith ?? credential.key, { - authorization, - audience, - }), - ); - + let sigHeaders: Record = opts.unsigned + ? { authorization } + : await spaceSigHeaders(opts.signWith ?? credential.key, { + authorization, + audience, + ...opts.signature, + }); + if (opts.signatureHeaders) + sigHeaders = await opts.signatureHeaders(sigHeaders); + const headers = new Headers(sigHeaders); + + let keyShare: string | undefined; let sharedSecret: Uint8Array | undefined; - let macType: MacType | undefined; - const want = opts.wantMac ?? MAC_TYPES[nsid]; - if ( - typeof want === "string" && - want !== COMMIT_MAC_TYPE && - want !== RECORD_MAC_TYPE - ) { - headers.set("atproto-space-want-mac", want); - } else if (want) { + let macProfile: MacProfile | undefined; + const mac = opts.mac ?? MAC_PROFILES[nsid]; + if (mac) { if (!repo) throw new Error(`${nsid}: a MAC request needs the repo DID`); - const { keyShare, sharedSecret: secret } = await encapsulate( - await kemKeyFor(ctx, repo), + const profile = typeof mac === "string" ? mac : mac.profile; + // A repo nobody hosts has no KEM key to resolve; a fresh P-256 key + // stands in, giving a well-formed request the host must refuse anyway. + const kem = await kemKeyFor(ctx, repo).catch( + async () => (await createCredentialKey()).did, ); - headers.set("atproto-space-want-mac", formatWantMacHeader(want, keyShare)); - sharedSecret = secret; - macType = want; + const enc = await encapsulate(kem); + headers.set( + "accept-signature", + typeof mac === "object" && "header" in mac + ? mac.header(enc.keyShare) + : formatMacRequest( + profile, + enc.keyShare, + typeof mac === "object" ? mac : {}, + ), + ); + keyShare = enc.keyShare; + sharedSecret = enc.sharedSecret; + macProfile = profile; } let response: Response; @@ -358,8 +405,9 @@ export async function credentialCall( const result = await toResult(response); return { ...result, + ...(keyShare ? { keyShare } : {}), ...(sharedSecret ? { sharedSecret } : {}), - ...(macType ? { macType } : {}), + ...(macProfile ? { macProfile } : {}), }; } @@ -373,6 +421,27 @@ export function credentialGet( return credentialCall(ctx, credential, nsid, { params }); } +/** Run named probes and fail with every one that missed, not just the first. */ +export async function expectEach( + probes: Array< + [string, () => Promise, (r: XrpcResult) => boolean] + >, +): Promise<{ ok: boolean; detail: string; evidence: Record }> { + const evidence: Record = {}; + const misses: string[] = []; + for (const [name, call, accept] of probes) { + const res = await call(); + evidence[name] = describe(res); + if (!accept(res)) misses.push(`${name} → ${describe(res)}`); + } + return { ok: misses.length === 0, detail: misses.join("; "), evidence }; +} + +export const errorIs = + (...names: string[]) => + (r: XrpcResult) => + r.error !== undefined && names.includes(r.error); + /** Summarise a response for a detail line. */ export const describe = (res: XrpcResult): string => `${res.status}${res.error ? ` ${res.error}` : ""}`; diff --git a/packages/space-conformance/src/checks/records.ts b/packages/space-conformance/src/checks/records.ts index aa9cf7c..88870de 100644 --- a/packages/space-conformance/src/checks/records.ts +++ b/packages/space-conformance/src/checks/records.ts @@ -30,6 +30,7 @@ import { const L = (ref: string) => ({ source: "lexicon" as const, ref }); const C = (ref: string) => ({ source: "changeset" as const, ref }); +const P = (ref: string) => ({ source: "proposal" as const, ref }); const op = asOperator; const writesCreateRead = defineCheck({ @@ -401,8 +402,8 @@ const writesSpaceNotFound = defineCheck({ L("com.atproto.space.createRecord@error:SpaceNotFound"), L("com.atproto.space.putRecord@error:SpaceNotFound"), L("com.atproto.space.applyWrites@error:SpaceNotFound"), - L("com.atproto.space.deleteSpace"), - { source: "changeset", ref: "brave-spaces-exist" }, + P("0016#repo-lifecycle"), + C("brave-spaces-exist"), ], needs: ["operator"], destructive: true, @@ -435,16 +436,17 @@ const writesDeleteSpaceNotFound = defineCheck({ tier: "must", citations: [ L("com.atproto.space.deleteRecord@error:SpaceNotFound"), - L("com.atproto.space.deleteSpace"), + P("0016#repo-lifecycle"), + C("brave-spaces-exist"), ], needs: ["operator"], destructive: true, async run(ctx) { // Separate from writes.space-not-found because deleteRecord is also - // idempotent ("succeeds whether or not the record was present"). That - // speaks to the record, not the space: deleteRecord declares - // SpaceNotFound, and deleteSpace says writes to a deleted space fail - // with it. + // idempotent ("or ensure it doesn't exist"). That speaks to the record, + // not the space: deleteRecord declares SpaceNotFound, and when the + // writer is the authority "the space must already exist" (proposal, + // Repo lifecycle). const deleted = await createProbeSpace(ctx, personalspace()); await mustCreateRecord(ctx, deleted.uri, "w"); await deleteProbeSpace(ctx, deleted.uri); @@ -468,55 +470,12 @@ const writesDeleteSpaceNotFound = defineCheck({ }, }); -const readsAfterDelete = defineCheck({ - id: "space.reads-after-delete-not-found", - title: "After deleteSpace, the owner's reads answer SpaceNotFound", - tier: "must", - citations: [ - L("com.atproto.space.deleteSpace"), - L("com.atproto.space.getRecord@error:SpaceNotFound"), - L("com.atproto.space.listRecords@error:SpaceNotFound"), - L("com.atproto.space.getLatestCommit@error:SpaceNotFound"), - L("com.atproto.space.listRepoOps@error:SpaceNotFound"), - L("com.atproto.space.getRepo@error:SpaceNotFound"), - L("com.atproto.space.listBlobs@error:SpaceNotFound"), - L("com.atproto.space.getBlob@error:SpaceNotFound"), - ], - needs: ["operator"], - destructive: true, - async run(ctx) { - // deleteSpace: "Afterwards, reads and writes fail with SpaceNotFound". - const space = await createProbeSpace(ctx, personalspace()); - await mustCreateRecord(ctx, space.uri, "before"); - await deleteProbeSpace(ctx, space.uri); - const base = { space: space.uri, repo: ctx.target.did }; - const cid = await rawCid(crypto.getRandomValues(new Uint8Array(8))); - const reads: Array<[string, Record]> = [ - ["getRecord", { ...base, collection: POST, rkey: "before" }], - ["listRecords", base], - ["getLatestCommit", base], - ["listRepoOps", base], - ["getRepo", base], - ["listBlobs", base], - ["getBlob", { ...base, cid }], - ]; - const misses: string[] = []; - for (const [name, params] of reads) { - const res = await xrpcGet(op(ctx), `com.atproto.space.${name}`, params); - if (res.error !== "SpaceNotFound") - misses.push(`${name} → ${describe(res)}`); - } - return misses.length - ? fail(`expected SpaceNotFound: ${misses.join("; ")}`) - : pass("every read of the deleted space answered SpaceNotFound"); - }, -}); - const writesPublishedRefused = defineCheck({ id: "writes.published-collections-refused", title: "Direct writes to the policy and member collections are refused", - tier: "must", + tier: "should", citations: [ + P("0016#publishing-to-readers"), C("baseline-space-policies"), L("com.atproto.space.policy"), L("com.atproto.memberspace.member"), @@ -605,6 +564,8 @@ const writesClearRecords = defineCheck({ citations: [ L("com.atproto.space.clearRecords"), L("com.atproto.space.listRecords"), + P("0016#repo-lifecycle"), + C("clear-spaces-sweep"), ], needs: ["operator"], destructive: true, @@ -641,7 +602,7 @@ const writesClearRecords = defineCheck({ after.res.json, ); } - // "Succeeds whether or not the repo held any records to delete." + // "Clearing a repo with nothing to delete is a no-op." (clear-spaces-sweep) const again = await clear(); return again.status === 200 ? pass( @@ -662,7 +623,10 @@ const writesClearKeepsPublished = defineCheck({ title: "clearRecords in the authority's repo keeps the published policy record", tier: "must", - citations: [L("com.atproto.space.clearRecords")], + citations: [ + L("com.atproto.space.clearRecords"), + P("0016#publishing-to-readers"), + ], needs: ["operator"], destructive: true, async run(ctx) { @@ -707,7 +671,7 @@ const syncListRecords = defineCheck({ id: "sync.listrecords-lists", title: "listRecords lists records with values, and excludeValues omits them", tier: "must", - citations: [L("com.atproto.space.listRecords")], + citations: [L("com.atproto.space.listRecords"), P("0016#xrpc-api")], needs: ["operator"], destructive: true, async run(ctx) { @@ -777,6 +741,42 @@ const syncListRecordsDescending = defineCheck({ }, }); +const garbageCursor = defineCheck({ + id: "request.garbage-cursor-rejected", + title: "A cursor the host never issued answers InvalidCursor", + tier: "should", + citations: [ + { source: "reference", ref: "pds space readers validate cursor syntax" }, + L("com.atproto.space.listRecords@error:InvalidCursor"), + ], + needs: ["operator"], + destructive: true, + async run(ctx) { + const space = await createProbeSpace(ctx, memberspace()); + try { + await mustCreateRecord(ctx, space.uri, "a"); + const cursor = "!!not-a-cursor!!"; + const base = { space: space.uri, repo: ctx.target.did, cursor }; + const misses: string[] = []; + for (const [name, params] of [ + ["com.atproto.space.listRecords", base], + ["com.atproto.space.listRepoOps", base], + ["com.atproto.space.listSpaces", { cursor }], + ["com.atproto.memberspace.listMembers", { space: space.uri, cursor }], + ] as const) { + const res = await xrpcGet(op(ctx), name, params); + if (res.error !== "InvalidCursor") + misses.push(`${name.split(".").at(-1)} → ${describe(res)}`); + } + return misses.length + ? fail(misses.join("; ")) + : pass("all four answered InvalidCursor"); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +}); + // --- blobs ------------------------------------------------------------- async function uploadBlob(ctx: CheckContext, bytes: Uint8Array) { @@ -930,12 +930,12 @@ export const recordChecks: Check[] = [ writesApplyWritesMissing, writesSpaceNotFound, writesDeleteSpaceNotFound, - readsAfterDelete, writesPublishedRefused, writesClearRecords, writesClearKeepsPublished, syncListRecords, syncListRecordsDescending, + garbageCursor, blobsSpaceNotPublic, blobsListAndGet, blobsNotFound, diff --git a/packages/space-conformance/src/checks/space.ts b/packages/space-conformance/src/checks/space.ts index 9491387..382780b 100644 --- a/packages/space-conformance/src/checks/space.ts +++ b/packages/space-conformance/src/checks/space.ts @@ -5,9 +5,9 @@ */ import { defineCheck } from "../registry.js"; -import { asOperator, xrpcGet, xrpcPost, type XrpcResult } from "../http.js"; +import { asOperator, xrpcGet, xrpcPost } from "../http.js"; import { fail, pass, type Check, type CheckContext } from "../model.js"; -import { isTid, toBase32 } from "../encoding.js"; +import { bytesEqual, isTid, lexBytes, toBase32 } from "../encoding.js"; import { FOREIGN_DID, PROBE_TYPE, @@ -15,7 +15,11 @@ import { credentialCall, deleteProbeSpace, describe, + errorIs, + expectEach, + managedspace, memberspace, + mustCreateRecord, obtainPublicCredential, operatorGetRecord, personalspace, @@ -27,6 +31,7 @@ import { const L = (ref: string) => ({ source: "lexicon" as const, ref }); const C = (ref: string) => ({ source: "changeset" as const, ref }); +const P = (ref: string) => ({ source: "proposal" as const, ref }); /** A syntactically valid did:plc nobody registered — a member to list. */ export function fakeDid(): string { @@ -35,27 +40,33 @@ export function fakeDid(): string { const op = asOperator; -/** Run named probes and fail with every one that missed, not just the first. */ -async function expectEach( - probes: Array< - [string, () => Promise, (r: XrpcResult) => boolean] - >, -): Promise<{ ok: boolean; detail: string; evidence: Record }> { - const evidence: Record = {}; - const misses: string[] = []; - for (const [name, call, accept] of probes) { - const res = await call(); - evidence[name] = describe(res); - if (!accept(res)) misses.push(`${name} → ${describe(res)}`); - } - return { - ok: misses.length === 0, - detail: misses.join("; "), - evidence, - }; -} +type Member = { did: string; read: boolean; write: boolean }; + +export const putMembers = ( + ctx: CheckContext, + space: string, + members: Member[], +) => + xrpcPost(op(ctx), "com.atproto.memberspace.putMembers", { space, members }); -const errorIs = (name: string) => (r: XrpcResult) => r.error === name; +const removeMembers = ( + ctx: CheckContext, + space: string, + dids: string[], +) => + xrpcPost(op(ctx), "com.atproto.memberspace.removeMembers", { space, dids }); + +async function listMembers( + ctx: CheckContext, + space: string, +): Promise { + const res = await xrpcGet(op(ctx), "com.atproto.memberspace.listMembers", { + space, + limit: "100", + }); + if (res.status !== 200) throw new Error(`listMembers ${describe(res)}`); + return (res.json as { members?: Member[] }).members ?? []; +} // --- create / get ------------------------------------------------------- @@ -67,6 +78,7 @@ const spaceCreateAndGet = defineCheck({ citations: [ L("com.atproto.space.createSpace"), L("com.atproto.space.getSpace"), + P("0016#addressing"), ], needs: ["operator"], destructive: true, @@ -79,19 +91,23 @@ const spaceCreateAndGet = defineCheck({ }); if (res.status !== 200) return fail(`createSpace ${describe(res)}`, res.json); - const uri = (res.json as { uri?: string }).uri; + const uri = (res.json as { space?: string }).space; try { const expected = `at://${ctx.target.did}/space/${PROBE_TYPE}/${skey}`; - if (uri !== expected) - return fail(`createSpace returned ${uri}, expected ${expected}`); + if (uri !== expected) { + return fail( + `createSpace returned space ${uri}, expected ${expected}`, + res.json, + ); + } const got = await xrpcGet(op(ctx), "com.atproto.space.getSpace", { space: uri, }); if (got.status !== 200) return fail(`getSpace ${describe(got)}`, got.json); - const body = got.json as { uri?: string; policy?: Policy }; - if (body.uri !== uri) - return fail(`getSpace uri was ${body.uri}`, got.json); + const body = got.json as { space?: string; policy?: Policy }; + if (body.space !== uri) + return fail(`getSpace space was ${body.space}`, got.json); if (body.policy?.$type !== "com.atproto.memberspace.policy") { return fail(`getSpace policy was ${body.policy?.$type}`, got.json); } @@ -101,7 +117,7 @@ const spaceCreateAndGet = defineCheck({ "a memberspace created without publicRead reports publicRead: true", ) : pass( - "created at the expected uri; getSpace reports the memberspace policy", + "created at the expected ref; getSpace reports the memberspace policy", ); } finally { if (uri) await deleteProbeSpace(ctx, uri); @@ -123,9 +139,9 @@ const spaceGeneratedSkey = defineCheck({ }); if (res.status !== 200) return fail(`createSpace ${describe(res)}`, res.json); - const uri = (res.json as { uri: string }).uri; + const uri = (res.json as { space: string }).space; await deleteProbeSpace(ctx, uri); - const skey = uri.split("/").at(-1); + const skey = uri?.split("/").at(-1); return isTid(skey) ? pass(`generated skey ${skey}`) : fail(`generated skey ${skey} is not a TID`); @@ -165,12 +181,12 @@ const spaceRecreate = defineCheck({ id: "space.recreate-after-delete", title: "A deleted space may be created again", tier: "must", - citations: [L("com.atproto.space.createSpace@error:SpaceAlreadyExists")], + citations: [P("0016#space-deletion"), L("com.atproto.space.createSpace")], needs: ["operator"], destructive: true, async run(ctx) { - // The SpaceAlreadyExists declaration itself carves this out: "A space - // that was previously deleted may be created again." + // "An authority MAY recreate a deleted space with the same space type + // and skey" — so a host must let it. const space = await createProbeSpace(ctx, personalspace()); await deleteProbeSpace(ctx, space.uri); const again = await xrpcPost(op(ctx), "com.atproto.space.createSpace", { @@ -196,6 +212,7 @@ const spaceUnsupportedPolicy = defineCheck({ citations: [ L("com.atproto.space.createSpace@error:UnsupportedPolicy"), L("com.atproto.space.updateSpace@error:UnsupportedPolicy"), + P("0016#space-policy"), ], needs: ["operator"], destructive: true, @@ -217,7 +234,8 @@ const spaceUnsupportedPolicy = defineCheck({ policy: mystery, }, ); - if (res.status === 200) created = (res.json as { uri: string }).uri; + if (res.status === 200) + created = (res.json as { space: string }).space; return res; }, errorIs("UnsupportedPolicy"), @@ -251,6 +269,7 @@ const spaceUpdateReplaces = defineCheck({ L("com.atproto.space.updateSpace"), L("com.atproto.space.getSpace"), L("com.atproto.memberspace.listMembers"), + P("0016#space-policy"), ], needs: ["operator"], destructive: true, @@ -265,37 +284,24 @@ const spaceUpdateReplaces = defineCheck({ }) ).json as { policy?: Policy } | undefined )?.policy; - const members = async () => - xrpcGet(op(ctx), "com.atproto.memberspace.listMembers", { - space: space.uri, - }); const update = (policy: Policy) => xrpcPost(op(ctx), "com.atproto.space.updateSpace", { space: space.uri, policy, }); try { - await xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { - space: space.uri, - did: member, - read: true, - write: false, - }); - + await putMembers(ctx, space.uri, [ + { did: member, read: true, write: false }, + ]); // Same type: a configuration change. The member list survives. const same = await update(memberspace({ publicRead: true })); if (same.status !== 200) return fail(`updateSpace (config) ${describe(same)}`, same.json); - const p1 = await policyOf(); - if (p1?.publicRead !== true) - return fail("getSpace does not reflect publicRead: true", p1); - const kept = (await members()).json as { - members?: Array<{ did: string }>; - }; - if (!kept.members?.some((m) => m.did === member)) { - return fail("a same-type update dropped the member list", kept); + if ((await policyOf())?.publicRead !== true) + return fail("getSpace does not reflect publicRead: true"); + if (!(await listMembers(ctx, space.uri)).some((m) => m.did === member)) { + return fail("a same-type update dropped the member list"); } - // A different type migrates the space. const migrate = await update(personalspace()); if (migrate.status !== 200) @@ -304,16 +310,12 @@ const spaceUpdateReplaces = defineCheck({ if (p2?.$type !== "com.atproto.personalspace.policy") { return fail(`after migration getSpace reports ${p2?.$type}`, p2); } - // Migrating back does not restore the discarded member list. const back = await update(memberspace()); if (back.status !== 200) return fail(`updateSpace (back) ${describe(back)}`, back.json); - const after = (await members()).json as { - members?: Array<{ did: string }>; - }; - return after.members?.some((m) => m.did === member) - ? fail("migrating away and back restored the old member list", after) + return (await listMembers(ctx, space.uri)).some((m) => m.did === member) + ? fail("migrating away and back restored the old member list") : pass( "config update kept members; a type change replaced the policy and discarded them", ); @@ -323,28 +325,31 @@ const spaceUpdateReplaces = defineCheck({ }, }); -const spaceNotOwner = defineCheck({ - id: "space.not-owner-refused", +const spaceNotAuthority = defineCheck({ + id: "space.not-authority-refused", title: - "Managing a space anchored on another DID is refused with NotSpaceOwner", + "Managing a space anchored on another DID is refused with NotAuthorized", tier: "must", citations: [ - L("com.atproto.space.deleteSpace@error:NotSpaceOwner"), - L("com.atproto.space.updateSpace@error:NotSpaceOwner"), - L("com.atproto.space.removeWriter@error:NotSpaceOwner"), - L("com.atproto.space.exportSpaceMeta@error:NotSpaceOwner"), - L("com.atproto.memberspace.putMember@error:NotSpaceOwner"), - L("com.atproto.memberspace.removeMember@error:NotSpaceOwner"), + L("com.atproto.space.deleteSpace@error:NotAuthorized"), + L("com.atproto.space.updateSpace@error:NotAuthorized"), + L("com.atproto.space.getSpace@error:NotAuthorized"), + L("com.atproto.space.removeWriter@error:NotAuthorized"), + L("com.atproto.space.exportSpaceMeta@error:NotAuthorized"), + L("com.atproto.memberspace.putMembers@error:NotAuthorized"), + L("com.atproto.memberspace.removeMembers@error:NotAuthorized"), + L("com.atproto.memberspace.listMembers@error:NotAuthorized"), ], needs: ["operator"], async run(ctx) { const space = unknownSpaceUri(FOREIGN_DID); const did = fakeDid(); + const na = errorIs("NotAuthorized"); const result = await expectEach([ [ "deleteSpace", () => xrpcPost(op(ctx), "com.atproto.space.deleteSpace", { space }), - errorIs("NotSpaceOwner"), + na, ], [ "updateSpace", @@ -353,43 +358,43 @@ const spaceNotOwner = defineCheck({ space, policy: personalspace(), }), - errorIs("NotSpaceOwner"), + na, + ], + [ + "getSpace", + () => xrpcGet(op(ctx), "com.atproto.space.getSpace", { space }), + na, ], [ "removeWriter", () => - xrpcPost(op(ctx), "com.atproto.space.removeWriter", { space, did }), - errorIs("NotSpaceOwner"), + xrpcPost(op(ctx), "com.atproto.space.removeWriter", { + space, + repo: did, + }), + na, ], [ "exportSpaceMeta", () => xrpcGet(op(ctx), "com.atproto.space.exportSpaceMeta", { space }), - errorIs("NotSpaceOwner"), + na, ], [ - "putMember", - () => - xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { - space, - did, - read: true, - write: true, - }), - errorIs("NotSpaceOwner"), + "putMembers", + () => putMembers(ctx, space, [{ did, read: true, write: true }]), + na, ], + ["removeMembers", () => removeMembers(ctx, space, [did]), na], [ - "removeMember", + "listMembers", () => - xrpcPost(op(ctx), "com.atproto.memberspace.removeMember", { - space, - did, - }), - errorIs("NotSpaceOwner"), + xrpcGet(op(ctx), "com.atproto.memberspace.listMembers", { space }), + na, ], ]); return result.ok - ? pass("every management method answered NotSpaceOwner") - : fail(`expected NotSpaceOwner: ${result.detail}`, result.evidence); + ? pass("every authority-only method answered NotAuthorized") + : fail(`expected NotAuthorized: ${result.detail}`, result.evidence); }, }); @@ -403,8 +408,8 @@ const spaceUnknown = defineCheck({ L("com.atproto.space.deleteSpace@error:SpaceNotFound"), L("com.atproto.space.exportSpaceMeta@error:SpaceNotFound"), L("com.atproto.space.removeWriter@error:SpaceNotFound"), - L("com.atproto.memberspace.putMember@error:SpaceNotFound"), - L("com.atproto.memberspace.removeMember@error:SpaceNotFound"), + L("com.atproto.memberspace.putMembers@error:SpaceNotFound"), + L("com.atproto.memberspace.removeMembers@error:SpaceNotFound"), L("com.atproto.memberspace.listMembers@error:SpaceNotFound"), ], needs: ["operator"], @@ -440,29 +445,18 @@ const spaceUnknown = defineCheck({ [ "removeWriter", () => - xrpcPost(op(ctx), "com.atproto.space.removeWriter", { space, did }), - nf, - ], - [ - "putMember", - () => - xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { + xrpcPost(op(ctx), "com.atproto.space.removeWriter", { space, - did, - read: true, - write: false, + repo: did, }), nf, ], [ - "removeMember", - () => - xrpcPost(op(ctx), "com.atproto.memberspace.removeMember", { - space, - did, - }), + "putMembers", + () => putMembers(ctx, space, [{ did, read: true, write: false }]), nf, ], + ["removeMembers", () => removeMembers(ctx, space, [did]), nf], [ "listMembers", () => @@ -478,12 +472,20 @@ const spaceUnknown = defineCheck({ const spaceDeleteIdempotent = defineCheck({ id: "space.delete-idempotent", - title: "deleteSpace is idempotent", - tier: "must", - citations: [L("com.atproto.space.deleteSpace")], + title: "Deleting an already-deleted space succeeds", + tier: "should", + citations: [ + { + source: "reference", + ref: "pds deleteSpace returns early for a tombstoned space", + }, + L("com.atproto.space.deleteSpace"), + ], needs: ["operator"], destructive: true, async run(ctx) { + // The 1105 lexicon called deleteSpace idempotent; 1112 dropped the + // sentence, so this is now calibrated against the reference. const space = await createProbeSpace(ctx, personalspace()); const first = await xrpcPost(op(ctx), "com.atproto.space.deleteSpace", { space: space.uri, @@ -493,56 +495,82 @@ const spaceDeleteIdempotent = defineCheck({ }); return first.status === 200 && second.status === 200 ? pass("both deletes returned 200") - : fail(`deletes returned ${describe(first)} then ${describe(second)}`, { - first: first.json, - second: second.json, - }); + : fail(`deletes returned ${describe(first)} then ${describe(second)}`); }, }); const spaceListSpaces = defineCheck({ id: "space.listspaces-filters", - title: "listSpaces lists the operator's spaces and honours spaceType and did", + title: + "listSpaces lists the operator's spaces with its repo state, honouring spaceType and spaceDid", tier: "must", - citations: [L("com.atproto.space.listSpaces")], + citations: [ + L("com.atproto.space.listSpaces"), + L("com.atproto.space.listSpaces#spaceView"), + ], needs: ["operator"], destructive: true, async run(ctx) { const space = await createProbeSpace(ctx, personalspace()); try { + await mustCreateRecord(ctx, space.uri, "a"); // Filter on both: an OAuth grant scoped to the probe type under the // operator's authority covers exactly this listing. - const seen: string[] = []; + const seen: Array<{ + space: string; + repoRev?: string; + data?: unknown; + spaceRev?: string; + }> = []; let cursor: string | undefined; for (let page = 0; page < 20; page++) { const res = await xrpcGet(op(ctx), "com.atproto.space.listSpaces", { spaceType: PROBE_TYPE, - did: ctx.target.did, + spaceDid: ctx.target.did, limit: "100", cursor, }); if (res.status !== 200) return fail(`listSpaces ${describe(res)}`, res.json); - const body = res.json as { - spaces?: Array<{ uri: string }>; - cursor?: string; - }; - seen.push(...(body.spaces ?? []).map((s) => s.uri)); + const body = res.json as { spaces?: typeof seen; cursor?: string }; + seen.push(...(body.spaces ?? [])); cursor = body.cursor; - if (!cursor || seen.includes(space.uri)) break; + if (!cursor || seen.some((s) => s.space === space.uri)) break; } - if (!seen.includes(space.uri)) - return fail("listSpaces did not list the new space"); + const entry = seen.find((s) => s.space === space.uri); + if (!entry) return fail("listSpaces did not list the new space"); const stray = seen.filter( - (uri) => !uri.startsWith(`at://${ctx.target.did}/space/${PROBE_TYPE}/`), + (s) => + !s.space.startsWith(`at://${ctx.target.did}/space/${PROBE_TYPE}/`), ); - return stray.length - ? fail( - `filtered listing included spaces outside the filter: ${stray.join(", ")}`, - ) - : pass( - `listed the space; ${seen.length} result(s), all within the filter`, - ); + if (stray.length) + return fail( + `listing included spaces outside the filter: ${stray.map((s) => s.space).join(", ")}`, + ); + // The entry carries the operator's repo state, and — as authority — the spaceRev. + const latest = await xrpcGet( + op(ctx), + "com.atproto.space.getLatestCommit", + { + space: space.uri, + repo: ctx.target.did, + }, + ); + const commit = ( + latest.json as { commit?: { rev?: string; data?: unknown } } | undefined + )?.commit; + const a = lexBytes(entry.data); + const b = lexBytes(commit?.data); + const problems: string[] = []; + if (entry.repoRev !== commit?.rev) + problems.push(`repoRev ${entry.repoRev} ≠ commit rev ${commit?.rev}`); + if (!a || !b || !bytesEqual(a, b)) + problems.push("data does not match the commit"); + if (!isTid(entry.spaceRev)) + problems.push(`no spaceRev for a space the caller is authority of`); + return problems.length + ? fail(problems.join("; "), entry) + : pass("listed with the operator's repoRev, data and the spaceRev"); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -562,9 +590,9 @@ const spaceOwnerStateNotByCredential = defineCheck({ needs: ["operator"], destructive: true, async run(ctx) { - // Each requires OAuth as the space owner: the policy and member list are - // the authority's own state, and a credential — which any reader of a - // public space can hold — must not expose them. + // Each requires auth as the space authority: the policy and member list + // are its own state, and a credential — which any reader of a public + // space can hold — must not expose them. const space = await createProbeSpace(ctx, publicRead()); try { const credential = await obtainPublicCredential(ctx, space.uri); @@ -599,76 +627,85 @@ const spaceOwnerStateNotByCredential = defineCheck({ }, }); +const managedBareDid = defineCheck({ + id: "managedspace.bare-did-rejected", + title: + "A managedspace whose managingApp is not a did#serviceId reference is refused", + tier: "must", + citations: [L("com.atproto.managedspace.policy"), C("tidy-spaces-settle")], + needs: ["operator"], + destructive: true, + async run(ctx) { + const res = await xrpcPost(op(ctx), "com.atproto.space.createSpace", { + spaceType: PROBE_TYPE, + skey: probeSkey(), + policy: managedspace(FOREIGN_DID), + }); + if (res.status === 200) { + await deleteProbeSpace(ctx, (res.json as { space: string }).space); + return fail("created a managedspace whose managingApp is a bare DID"); + } + return res.status >= 400 && res.status < 500 + ? pass(`refused (${describe(res)})`) + : fail(`answered ${describe(res)}`, res.json); + }, +}); + // --- memberspace ------------------------------------------------------ const memberRoundTrip = defineCheck({ id: "memberspace.member-round-trip", - title: - "putMember sets per-member read/write; listMembers and removeMember follow", + title: "putMembers and removeMembers apply batches; listMembers follows", tier: "must", citations: [ - L("com.atproto.memberspace.putMember"), + L("com.atproto.memberspace.putMembers"), L("com.atproto.memberspace.listMembers"), - L("com.atproto.memberspace.removeMember"), + L("com.atproto.memberspace.removeMembers"), + L("com.atproto.memberspace.defs#member"), + C("tidy-spaces-settle"), ], needs: ["operator"], destructive: true, async run(ctx) { const space = await createProbeSpace(ctx, memberspace()); - const member = fakeDid(); - const list = async () => { - const res = await xrpcGet( - op(ctx), - "com.atproto.memberspace.listMembers", - { space: space.uri }, - ); - if (res.status !== 200) throw new Error(`listMembers ${describe(res)}`); - return ( - ( - res.json as { - members?: Array<{ did: string; read: boolean; write: boolean }>; - } - ).members ?? [] - ).find((m) => m.did === member); - }; - const put = (read: boolean, write: boolean) => - xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { - space: space.uri, - did: member, - read, - write, - }); + const [a, b] = [fakeDid(), fakeDid()]; + const find = (members: Member[], did: string) => + members.find((m) => m.did === did); try { - const first = await put(true, false); - if (first.status !== 200) - return fail(`putMember ${describe(first)}`, first.json); - const a = await list(); - if (!a || a.read !== true || a.write !== false) { + // One batch; `a` appears twice and its last entry wins. + const put = await putMembers(ctx, space.uri, [ + { did: a, read: false, write: false }, + { did: b, read: true, write: true }, + { did: a, read: true, write: false }, + ]); + if (put.status !== 200) + return fail(`putMembers ${describe(put)}`, put.json); + const listed = await listMembers(ctx, space.uri); + const ma = find(listed, a); + const mb = find(listed, b); + if (!ma || ma.read !== true || ma.write !== false) return fail( - `after putMember(read, !write) listMembers shows ${JSON.stringify(a)}`, + `a duplicated DID did not take its last entry: ${JSON.stringify(ma)}`, ); - } - const second = await put(false, true); - if (second.status !== 200) - return fail(`putMember (replace) ${describe(second)}`, second.json); - const b = await list(); - if (!b || b.read !== false || b.write !== true) { - return fail(`putMember did not replace access: ${JSON.stringify(b)}`); - } - const removed = await xrpcPost( - op(ctx), - "com.atproto.memberspace.removeMember", - { - space: space.uri, - did: member, - }, - ); + if (!mb || mb.read !== true || mb.write !== true) + return fail(`second member: ${JSON.stringify(mb)}`); + // Replace one member's access. + await putMembers(ctx, space.uri, [{ did: b, read: false, write: true }]); + const mb2 = find(await listMembers(ctx, space.uri), b); + if (!mb2 || mb2.read !== false || mb2.write !== true) + return fail( + `putMembers did not replace access: ${JSON.stringify(mb2)}`, + ); + // removeMembers ignores DIDs that are not members. + const removed = await removeMembers(ctx, space.uri, [a, b, fakeDid()]); if (removed.status !== 200) - return fail(`removeMember ${describe(removed)}`, removed.json); - const c = await list(); - return c - ? fail(`removeMember left ${JSON.stringify(c)}`) - : pass("put, replaced and removed a member, as listMembers shows"); + return fail(`removeMembers ${describe(removed)}`, removed.json); + const left = await listMembers(ctx, space.uri); + return find(left, a) || find(left, b) + ? fail(`removeMembers left ${JSON.stringify(left)}`) + : pass( + "batched put (last entry wins), replace, and remove (ignoring a non-member)", + ); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -680,8 +717,8 @@ const memberPolicyMismatch = defineCheck({ title: "Member methods on a non-memberspace answer PolicyMismatch", tier: "must", citations: [ - L("com.atproto.memberspace.putMember@error:PolicyMismatch"), - L("com.atproto.memberspace.removeMember@error:PolicyMismatch"), + L("com.atproto.memberspace.putMembers@error:PolicyMismatch"), + L("com.atproto.memberspace.removeMembers@error:PolicyMismatch"), L("com.atproto.memberspace.listMembers@error:PolicyMismatch"), ], needs: ["operator"], @@ -693,25 +730,11 @@ const memberPolicyMismatch = defineCheck({ try { const result = await expectEach([ [ - "putMember", - () => - xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { - space: space.uri, - did, - read: true, - write: true, - }), - mm, - ], - [ - "removeMember", - () => - xrpcPost(op(ctx), "com.atproto.memberspace.removeMember", { - space: space.uri, - did, - }), + "putMembers", + () => putMembers(ctx, space.uri, [{ did, read: true, write: true }]), mm, ], + ["removeMembers", () => removeMembers(ctx, space.uri, [did]), mm], [ "listMembers", () => @@ -739,11 +762,11 @@ const memberPublish = defineCheck({ L("com.atproto.memberspace.policy"), L("com.atproto.space.policy"), L("com.atproto.memberspace.member"), - C("baseline-space-policies"), + P("0016#publishing-to-readers"), ], needs: ["operator"], destructive: true, - async run(ctx: CheckContext) { + async run(ctx) { const space = await createProbeSpace( ctx, memberspace({ publishPolicy: true, publishMembers: true }), @@ -756,12 +779,11 @@ const memberPublish = defineCheck({ "self", "com.atproto.space.policy", ); - if (policy.status !== 200) { + if (policy.status !== 200) return fail( `no com.atproto.space.policy/self record: ${describe(policy)}`, policy.json, ); - } const published = (policy.json as { value?: { policy?: Policy } }).value ?.policy; if ( @@ -773,13 +795,9 @@ const memberPublish = defineCheck({ policy.json, ); } - - await xrpcPost(op(ctx), "com.atproto.memberspace.putMember", { - space: space.uri, - did: member, - read: true, - write: false, - }); + await putMembers(ctx, space.uri, [ + { did: member, read: true, write: false }, + ]); const rec = await operatorGetRecord( ctx, space.uri, @@ -791,15 +809,11 @@ const memberPublish = defineCheck({ )?.value; if (rec.status !== 200 || value?.read !== true || value.write !== false) { return fail( - `member record after putMember: ${describe(rec)}`, + `member record after putMembers: ${describe(rec)}`, rec.json, ); } - - await xrpcPost(op(ctx), "com.atproto.memberspace.removeMember", { - space: space.uri, - did: member, - }); + await removeMembers(ctx, space.uri, [member]); const gone = await operatorGetRecord( ctx, space.uri, @@ -807,9 +821,9 @@ const memberPublish = defineCheck({ "com.atproto.memberspace.member", ); return gone.status === 200 - ? fail("the member record outlived removeMember", gone.json) + ? fail("the member record outlived removeMembers", gone.json) : pass( - "policy record published; member record tracked putMember and removeMember", + "policy record published; member record tracked putMembers and removeMembers", ); } finally { await deleteProbeSpace(ctx, space.uri); @@ -824,11 +838,12 @@ export const spaceChecks: Check[] = [ spaceRecreate, spaceUnsupportedPolicy, spaceUpdateReplaces, - spaceNotOwner, + spaceNotAuthority, spaceUnknown, spaceDeleteIdempotent, spaceListSpaces, spaceOwnerStateNotByCredential, + managedBareDid, memberRoundTrip, memberPolicyMismatch, memberPublish, diff --git a/packages/space-conformance/src/coverage.ts b/packages/space-conformance/src/coverage.ts index f9971df..f1b86f4 100644 --- a/packages/space-conformance/src/coverage.ts +++ b/packages/space-conformance/src/coverage.ts @@ -36,10 +36,29 @@ export interface CoverageExemption { const TAKEDOWN_REASON = "Needs a moderation or account-status action on the target (a takedown, suspension or deactivation of the account being read), which only the host's administrator can take. No black-box harness can arrange it without admin authority, and deactivating the operator's own account would end the session the run depends on."; +const READ_SPACE_NOT_FOUND_REASON = + "Declared on the repo-host reads, but neither the lexicons nor proposal 0016 name a condition under which a repo host answers it: reads are answered from the repo, and an empty or never-written repo is equivalent to a nonexistent one (proposal, Repo lifecycle). A must check would be the suite's own reading. The 1105 deleteSpace description said reads of a deleted space fail with SpaceNotFound; 1112 dropped that sentence, and the check that relied on it with it."; + +const INVALID_CURSOR_REASON = + "Cursors are opaque, host-issued strings. Neither the lexicons nor the proposal define a value every host must reject, so which cursors are invalid is the host's choice. The should check request.garbage-cursor-rejected calibrates what the reference does."; + export const coverageExemptions: CoverageExemption[] = [ { ref: "*@error:RepoTakendown", reason: TAKEDOWN_REASON }, { ref: "*@error:RepoSuspended", reason: TAKEDOWN_REASON }, { ref: "*@error:RepoDeactivated", reason: TAKEDOWN_REASON }, + { ref: "*@error:InvalidCursor", reason: INVALID_CURSOR_REASON }, + ...[ + "getRecord", + "listRecords", + "getLatestCommit", + "listRepoOps", + "getRepo", + "listBlobs", + "getBlob", + ].map((method) => ({ + ref: `com.atproto.space.${method}@error:SpaceNotFound`, + reason: READ_SPACE_NOT_FOUND_REASON, + })), ]; export interface CoverageReport { diff --git a/packages/space-conformance/src/descriptors.ts b/packages/space-conformance/src/descriptors.ts index 63dd76c..9c4bd95 100644 --- a/packages/space-conformance/src/descriptors.ts +++ b/packages/space-conformance/src/descriptors.ts @@ -24,16 +24,19 @@ export interface CheckDescriptor { citations: Citation[]; destructive?: boolean; slow?: boolean; + timeoutMs?: number; } const L = (ref: string): Citation => ({ source: "lexicon", ref }); const C = (ref: string): Citation => ({ source: "changeset", ref }); -/** Refusals a policy may give a user it does not authorise. */ -const USER_REFUSALS = [ - L("com.atproto.space.getSpaceCredential@error:SpaceNotFound"), - L("com.atproto.space.getSpaceCredential@error:UserNotAuthorized"), - L("com.atproto.space.getSpaceCredential@error:NotAuthorized"), +const P = (ref: string): Citation => ({ source: "proposal", ref }); + +/** Refusals a policy may give an account it does not authorise. */ +const ACCOUNT_REFUSALS = [ + L("com.atproto.space.authorizeSpaceSync@error:SpaceNotFound"), + L("com.atproto.space.authorizeSpaceSync@error:AccountNotAuthorized"), + L("com.atproto.space.authorizeSpaceSync@error:NotAuthorized"), ]; /** Every crypto-bound check, by metadata, in catalog order. */ @@ -42,13 +45,14 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ { id: "mac.commit-verifies", title: - "getLatestCommit's commit has the specified shape and its MAC verifies", + "getLatestCommit's commit MAC verifies, under the requested label, with Vary: Accept-Signature", tier: "must", needs: ["operator"], citations: [ L("com.atproto.space.getLatestCommit"), L("com.atproto.space.defs#commit"), - C("quiet-spaces-mac"), + P("0016#requesting-a-mac"), + P("0016#commit-mac"), ], destructive: true, }, @@ -57,30 +61,29 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ title: "getRecord's record MAC verifies and its value encodes to its cid", tier: "must", needs: ["operator"], - citations: [L("com.atproto.space.getRecord"), C("quiet-spaces-mac")], + citations: [L("com.atproto.space.getRecord"), P("0016#record-mac")], destructive: true, }, { id: "sync.oplog-folds-to-commit", - title: "listRepoOps' head commit MAC verifies and the ops fold to its data", + title: + "Every listRepoOps page carries a MAC-verified commit, and the ops fold to its data", tier: "must", needs: ["operator"], citations: [ L("com.atproto.space.listRepoOps"), L("com.atproto.space.defs#commit"), + P("0016#incremental-sync"), ], destructive: true, }, { id: "sync.getrepo-star", - title: "getRepo serves a STAR archive that verifies against its MAC", + title: + "getRepo serves a STAR archive (application/vnd.dasl.star) that verifies against its MAC", tier: "must", needs: ["operator"], - citations: [ - L("com.atproto.space.getRepo"), - L("com.atproto.space.defs#commit"), - C("star-spaces-shine"), - ], + citations: [L("com.atproto.space.getRepo"), P("0016#repo-serialization")], destructive: true, }, // --- token signatures ------------------------------------------------ @@ -90,8 +93,8 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ tier: "must", needs: ["operator"], citations: [ - L("com.atproto.space.getSpaceCredential"), - C("plain-keys-resolve"), + L("com.atproto.space.authorizeSpaceSync"), + P("0016#space-credential"), ], destructive: true, }, @@ -102,17 +105,22 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ needs: ["operator", "pds-delegation"], citations: [ L("com.atproto.space.getDelegationToken"), - C("plain-keys-resolve"), + P("0016#delegation-token"), ], destructive: true, }, // --- migration ------------------------------------------------------- { id: "migration.export-space-meta", - title: "exportSpaceMeta serves the space's policy, members and writers", + title: + "exportSpaceMeta serves the policy, members and live writers (with repoRev) as a STAR file", tier: "must", needs: ["operator"], - citations: [L("com.atproto.space.exportSpaceMeta"), C("olive-crabs-fly")], + citations: [ + L("com.atproto.space.exportSpaceMeta"), + P("0016#space-meta-archive"), + C("removed-writers-notify"), + ], destructive: true, }, { @@ -120,15 +128,18 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ title: "importSpaceMeta replaces the space's policy and member list", tier: "must", needs: ["operator"], - citations: [L("com.atproto.space.importSpaceMeta"), C("olive-crabs-fly")], + citations: [ + L("com.atproto.space.importSpaceMeta"), + P("0016#space-meta-archive"), + ], destructive: true, }, { - id: "migration.import-space-meta-not-owner", - title: "importSpaceMeta of another DID's space answers NotSpaceOwner", + id: "migration.import-space-meta-not-authority", + title: "importSpaceMeta of another DID's space answers NotAuthorized", tier: "must", needs: ["operator"], - citations: [L("com.atproto.space.importSpaceMeta@error:NotSpaceOwner")], + citations: [L("com.atproto.space.importSpaceMeta@error:NotAuthorized")], }, { id: "migration.import-space-meta-unsupported-policy", @@ -136,9 +147,22 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ "importSpaceMeta of an unimplemented policy answers UnsupportedPolicy", tier: "must", needs: ["operator"], - citations: [L("com.atproto.space.importSpaceMeta@error:UnsupportedPolicy")], + citations: [ + L("com.atproto.space.importSpaceMeta@error:UnsupportedPolicy"), + P("0016#space-meta-archive"), + ], destructive: true, }, + { + id: "migration.import-space-meta-invalid", + title: "importSpaceMeta of a malformed archive answers InvalidSpaceMeta", + tier: "must", + needs: ["operator"], + citations: [ + L("com.atproto.space.importSpaceMeta@error:InvalidSpaceMeta"), + P("0016#space-meta-archive"), + ], + }, { id: "migration.import-repo", title: @@ -148,7 +172,7 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ citations: [ L("com.atproto.space.importRepo"), L("com.atproto.space.getRepo"), - C("olive-crabs-fly"), + P("0016#account-migration"), ], destructive: true, }, @@ -160,6 +184,21 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ needs: ["operator"], citations: [L("com.atproto.space.importRepo@error:SpaceNotFound")], }, + { + id: "migration.import-repo-invalid", + title: "importRepo of a malformed archive answers InvalidRepoFile", + tier: "must", + needs: ["operator"], + citations: [L("com.atproto.space.importRepo@error:InvalidRepoFile")], + }, + { + id: "migration.import-repo-mismatch", + title: "importRepo of another account's repo answers RepoMismatch", + tier: "must", + needs: ["operator"], + citations: [L("com.atproto.space.importRepo@error:RepoMismatch")], + destructive: true, + }, // --- foreign identities ---------------------------------------------- { id: "credential.member-gate", @@ -168,18 +207,23 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ tier: "must", needs: ["operator", "identities"], citations: [ - ...USER_REFUSALS, - L("com.atproto.memberspace.putMember"), + ...ACCOUNT_REFUSALS, + L("com.atproto.memberspace.putMembers"), L("com.atproto.memberspace.policy"), + P("0016#memberspace"), ], destructive: true, }, { id: "policy.personalspace-owner-only", - title: "A personalspace refuses every user but its authority", + title: "A personalspace refuses every account but its authority", tier: "must", needs: ["operator", "identities"], - citations: [...USER_REFUSALS, L("com.atproto.personalspace.policy")], + citations: [ + ...ACCOUNT_REFUSALS, + L("com.atproto.personalspace.policy"), + P("0016#personalspace"), + ], destructive: true, }, { @@ -188,36 +232,51 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ tier: "must", needs: ["operator", "identities"], citations: [ - L("com.atproto.space.getSpaceCredential@error:InvalidDelegationToken"), + L("com.atproto.space.authorizeSpaceSync@error:InvalidDelegationToken"), + P("0016#delegation-token"), ], destructive: true, }, { - id: "host.notifywrite-accepted", - title: "An authorised writer's notifyWrite enters the writer set", + id: "host.notifyrepoupdate-accepted", + title: "An authorised writer's notifyRepoUpdate enters the writer set", tier: "must", needs: ["operator", "identities"], citations: [ - L("com.atproto.space.notifyWrite"), - L("com.atproto.space.listRepos"), + L("com.atproto.space.notifyRepoUpdate"), + L("com.atproto.space.listWriters"), + P("0016#write-notifications"), ], destructive: true, }, { - id: "host.notifywrite-future-rev", - title: "notifyWrite with a repoRev beyond clock skew answers FutureRev", + id: "host.notifyrepoupdate-future-rev", + title: + "notifyRepoUpdate with a repoRev beyond clock skew answers FutureRev", tier: "must", needs: ["operator", "identities"], - citations: [L("com.atproto.space.notifyWrite@error:FutureRev")], + citations: [ + L("com.atproto.space.notifyRepoUpdate@error:FutureRev"), + P("0016#write-notifications"), + ], destructive: true, }, { - id: "host.notifywrite-unknown-space", + id: "host.notifyrepoupdate-unknown-space", title: - "notifyWrite for a space the authority does not have answers SpaceNotFound", + "notifyRepoUpdate for a space the authority does not have answers SpaceNotFound", tier: "must", needs: ["operator", "identities"], - citations: [L("com.atproto.space.notifyWrite@error:SpaceNotFound")], + citations: [L("com.atproto.space.notifyRepoUpdate@error:SpaceNotFound")], + }, + { + id: "memberspace.write-revocation-removes-writer", + title: + "Revoking a member's write access removes it from the writer set, and its writes stop being tracked", + tier: "should", + needs: ["operator", "identities"], + citations: [P("0016#memberspace"), P("0016#write-notifications")], + destructive: true, }, { id: "revocation.revoked-credential-refused", @@ -226,9 +285,9 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ tier: "must", needs: ["operator", "identities"], citations: [ - L("com.atproto.space.notifyCredentialRevoked"), + L("com.atproto.space.notifyCredentialsRevoked"), L("com.atproto.space.getRecord"), - C("funky-dryers-draw"), + P("0016#credential-expiration-and-revocation"), ], destructive: true, }, @@ -245,20 +304,24 @@ export const cryptoCheckDescriptors: CheckDescriptor[] = [ { id: "revocation.non-authority-refused", title: - "notifyCredentialRevoked from anyone but the space authority is refused", + "notifyCredentialsRevoked from anyone but the space authority is refused", tier: "must", needs: ["operator", "identities"], - citations: [L("com.atproto.space.notifyCredentialRevoked")], + citations: [ + L("com.atproto.space.notifyCredentialsRevoked"), + P("0016#credential-expiration-and-revocation"), + ], destructive: true, }, { - id: "managedspace.checkuseraccess", - title: "A managedspace defers each credential decision to its managing app", + id: "managedspace.check-access-account", + title: "A managedspace asks its managing app about the delegated account", tier: "must", needs: ["operator", "identities", "syncer-inbox"], citations: [ - L("com.atproto.managedspace.checkUserAccess"), + L("com.atproto.managedspace.checkAccess"), L("com.atproto.managedspace.policy"), + P("0016#managedspace"), ], destructive: true, }, diff --git a/packages/space-conformance/src/encoding.ts b/packages/space-conformance/src/encoding.ts index b78c902..f65d306 100644 --- a/packages/space-conformance/src/encoding.ts +++ b/packages/space-conformance/src/encoding.ts @@ -31,7 +31,7 @@ export const toBase64Url = (bytes: Uint8Array): string => toBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, ""); /** Decode base64 or base64url, padded or not. */ -export function fromBase64(input: string): Uint8Array { +function fromBase64(input: string): Uint8Array { let s = input.replace(/-/g, "+").replace(/_/g, "/").replace(/=+$/, ""); s = s.padEnd(Math.ceil(s.length / 4) * 4, "="); const bin = atob(s); diff --git a/packages/space-conformance/src/full.ts b/packages/space-conformance/src/full.ts index 0c7c99e..7b2ada6 100644 --- a/packages/space-conformance/src/full.ts +++ b/packages/space-conformance/src/full.ts @@ -36,6 +36,9 @@ export { } from "./full/helpers.js"; export type { Credential, ProbeSpace } from "./full/helpers.js"; +export { createSyncerInbox } from "./inbox.js"; +export type { SyncerInboxHandle } from "./inbox.js"; + export { cryptoChecks } from "./full/checks.js"; export { operatorChecks } from "./checks/operator.js"; export { baseChecks } from "./checks/base.js"; diff --git a/packages/space-conformance/src/full/checks.ts b/packages/space-conformance/src/full/checks.ts index 8138c12..5dba930 100644 --- a/packages/space-conformance/src/full/checks.ts +++ b/packages/space-conformance/src/full/checks.ts @@ -20,13 +20,13 @@ import { RepoCommit, readRepoStar, readSpaceMetaStar, - serializeRepo, - serializeSpaceMeta, spaceHostAud, verifyCommit, verifyRecord, verifyRepoStarFull, verifySpaceToken, + writeRepoStar, + writeSpaceMetaStar, type SpaceMetaArchive, } from "@atproto/space"; import { parseCid } from "@atproto/lex-data"; @@ -54,9 +54,14 @@ import { tidAt, tidNow, toBase64, + utf8, } from "../encoding.js"; import { resolveDidDocument, verificationMethodDidKey } from "../did.js"; -import { createCredentialKey } from "../space-auth.js"; +import { + COMMIT_MAC_PROFILE, + createCredentialKey, + formatMacRequest, +} from "../space-auth.js"; import { FOREIGN_DID, POST, @@ -77,22 +82,29 @@ import { unknownSpaceUri, type Credential, } from "../checks/probe.js"; -import { fakeDid } from "../checks/space.js"; +import { fakeDid, putMembers } from "../checks/space.js"; +import { ACCOUNT_REFUSALS } from "../checks/credential.js"; +import { listWriters } from "../checks/host.js"; import { collectBytes, commitFromJson, + macParams, mintCredential, mintDelegation, obtainCredential, - responseMac, serviceJwt, } from "./helpers.js"; +type Did = `did:${string}:${string}`; + const crypto$ = ( id: string, run: (ctx: CheckContext) => Promise, ): Check => defineCheck({ ...descriptor(id), run }); +const errMsg = (err: unknown) => + err instanceof Error ? err.message : String(err); + /** A public-read space with two records and a credential for it. */ async function withPublicSpace( ctx: CheckContext, @@ -112,25 +124,30 @@ async function withPublicSpace( const macCommit = crypto$("mac.commit-verifies", (ctx) => withPublicSpace(ctx, async (space, credential) => { - const res = await credentialGet( + // A custom label, and a request for some other profile alongside: the + // host must answer under the label asked for and ignore the stranger. + const res = await credentialCall( ctx, credential, "com.atproto.space.getLatestCommit", { - space, - repo: ctx.target.did, + params: { space, repo: ctx.target.did }, + mac: { + profile: COMMIT_MAC_PROFILE, + header: (k) => + `${formatMacRequest(COMMIT_MAC_PROFILE, k, { label: "m1" })}, other=("content-digest");tag="someone-elses"`, + }, }, ); if (res.status !== 200) return fail(`getLatestCommit ${describe(res)}`, res.json); const raw = (res.json as { commit?: Record }).commit ?? {}; const keys = Object.keys(raw).sort().join(","); - if (keys !== "data,repo,rev,space,ver") { + if (keys !== "data,repo,rev,space,ver") return fail( `commit carries {${keys}}, expected exactly {data,repo,rev,space,ver}`, raw, ); - } const commit = commitFromJson(raw); if ( !commit || @@ -143,17 +160,29 @@ const macCommit = crypto$("mac.commit-verifies", (ctx) => raw, ); } - const mac = responseMac(res); - if (!mac) - return fail("no parseable Atproto-Space-Mac header on a MAC'd read"); - return verifyCommit(commit, { - space, - repo: ctx.target.did, - sharedSecret: res.sharedSecret!, - mac, - }) - ? pass("commit shape as specified; its MAC verifies") - : fail("the commit MAC does not verify", raw); + const input = res.headers.get("signature-input") ?? ""; + if (!/^m1=/.test(input)) + return fail(`MAC not under the requested label: ${input}`); + const vary = (res.headers.get("vary") ?? "").toLowerCase(); + if ( + !vary + .split(",") + .map((v) => v.trim()) + .includes("accept-signature") + ) + return fail(`Vary does not list Accept-Signature: ${vary}`); + try { + verifyCommit(commit, { + space: space as never, + repo: ctx.target.did as Did, + ...macParams(res), + }); + return pass( + "commit shape as specified; MAC verifies under the requested label; Vary lists Accept-Signature", + ); + } catch (err) { + return fail(`verifyCommit rejected the response: ${errMsg(err)}`, raw); + } }), ); @@ -176,17 +205,15 @@ const macRecord = crypto$("mac.record-verifies", (ctx) => cid: string; value: Record; }; - const mac = responseMac(res); - if (!mac) - return fail("no parseable Atproto-Space-Mac header on a MAC'd read"); - const ok = await verifyRecord(record as never, { - uri: record.uri, - sharedSecret: res.sharedSecret!, - mac, - }); - return ok - ? pass("record MAC verifies over uri and cid; value encodes to cid") - : fail("verifyRecord rejected the response", record); + try { + await verifyRecord(record as never, { + uri: record.uri as never, + ...macParams(res), + }); + return pass("record MAC verifies over uri and cid; value encodes to cid"); + } catch (err) { + return fail(`verifyRecord rejected the response: ${errMsg(err)}`, record); + } }), ); @@ -200,52 +227,67 @@ const oplogFolds = crypto$("sync.oplog-folds-to-commit", (ctx) => rkey: "a", record: { $type: POST, text: "one, again" }, }); - const res = await credentialGet( - ctx, - credential, - "com.atproto.space.listRepoOps", - { - space, - repo: ctx.target.did, - }, - ); - if (res.status !== 200) - return fail(`listRepoOps ${describe(res)}`, res.json); - const body = res.json as { - ops: Array<{ - collection: string; - rkey: string; - cid: string | null; - prev: string | null; - }>; - commit?: unknown; - }; - const commit = commitFromJson(body.commit); - if (!commit) - return fail("listRepoOps reached the head but returned no commit", body); - const mac = responseMac(res); - if (!mac) - return fail("a page with the commit carried no Atproto-Space-Mac header"); - if ( - !verifyCommit(commit, { - space, - repo: ctx.target.did, - sharedSecret: res.sharedSecret!, - mac, - }) - ) { - return fail("the head commit's MAC does not verify"); + // One op per page: every page, not just the last, carries the commit. + const folded = new RepoCommit(); + let cursor: string | undefined; + let pages = 0; + let last: ReturnType; + for (; pages < 20; pages++) { + const res = await credentialGet( + ctx, + credential, + "com.atproto.space.listRepoOps", + { + space, + repo: ctx.target.did, + limit: "1", + cursor, + }, + ); + if (res.status !== 200) + return fail( + `listRepoOps page ${pages + 1}: ${describe(res)}`, + res.json, + ); + const body = res.json as { + ops: Array<{ + collection: string; + rkey: string; + cid: string | null; + prev: string | null; + }>; + commit?: unknown; + cursor?: string; + }; + last = commitFromJson(body.commit); + if (!last) return fail(`page ${pages + 1} carried no commit`, body); + try { + verifyCommit(last, { + space: space as never, + repo: ctx.target.did as Did, + ...macParams(res), + }); + } catch (err) { + return fail( + `page ${pages + 1}'s commit MAC does not verify: ${errMsg(err)}`, + ); + } + folded.applyOps( + body.ops.map((op) => ({ + collection: op.collection, + rkey: op.rkey, + cid: op.cid ? parseCid(op.cid) : null, + prev: op.prev ? parseCid(op.prev) : null, + })) as never, + ); + cursor = body.cursor; + if (!cursor) break; } - const folded = new RepoCommit().applyOps( - body.ops.map((op) => ({ - collection: op.collection, - rkey: op.rkey, - cid: op.cid ? parseCid(op.cid) : null, - prev: op.prev ? parseCid(op.prev) : null, - })) as never, - ); - return folded.matches(commit) - ? pass(`${body.ops.length} ops fold to the MAC-verified commit data`) + if (pages < 2) return fail("three ops at limit=1 did not paginate"); + return folded.matches(last!) + ? pass( + `${pages + 1} pages, each with a MAC-verified commit; the ops fold to its data`, + ) : fail("the folded oplog does not match the commit data"); }), ); @@ -256,34 +298,25 @@ const getRepoStar = crypto$("sync.getrepo-star", (ctx) => ctx, credential, "com.atproto.space.getRepo", - { - space, - repo: ctx.target.did, - }, + { space, repo: ctx.target.did }, ); if (res.status !== 200) return fail(`getRepo ${describe(res)}`, res.json); const type = res.headers.get("Content-Type") ?? ""; - if (!type.includes("application/octet-stream")) + if (!type.includes("application/vnd.dasl.star")) return fail(`getRepo content-type was ${type}`); - const mac = responseMac(res); - if (!mac) - return fail("no parseable Atproto-Space-Mac header on a MAC'd getRepo"); const bytes = new Uint8Array(await res.response.arrayBuffer()); try { const { records } = await verifyRepoStarFull([bytes], { - space, - repo: ctx.target.did, - sharedSecret: res.sharedSecret!, - mac, + space: space as never, + repo: ctx.target.did as Did, + ...macParams(res), }); const rkeys = records.map((r) => `${r.collection}/${r.rkey}`).sort(); return rkeys.join(",") === `${POST}/a,${POST}/b` ? pass("STAR archive verified against its MAC; both records present") : fail(`archive verified but held ${rkeys.join(", ") || "no records"}`); } catch (err) { - return fail( - `verifyRepoStarFull rejected the archive: ${(err as Error).message}`, - ); + return fail(`verifyRepoStarFull rejected the archive: ${errMsg(err)}`); } }), ); @@ -312,7 +345,7 @@ const credentialSigned = crypto$( }); return pass("verifies against the authority's #atproto key"); } catch (err) { - return fail(`credential did not verify: ${(err as Error).message}`); + return fail(`credential did not verify: ${errMsg(err)}`); } } finally { await deleteProbeSpace(ctx, space.uri); @@ -336,13 +369,13 @@ const delegationSigned = crypto$("delegation.signed-by-user", async (ctx) => { (res.json as { token: string }).token, { getSigningKey: (iss) => atprotoKey(ctx, iss), - aud: spaceHostAud(ctx.target.did), + aud: spaceHostAud(ctx.target.did as Did), sub: space.uri, }, ); return pass("verifies against the user's #atproto key"); } catch (err) { - return fail(`delegation token did not verify: ${(err as Error).message}`); + return fail(`delegation token did not verify: ${errMsg(err)}`); } } finally { await deleteProbeSpace(ctx, space.uri); @@ -355,11 +388,10 @@ async function exportMeta(ctx: CheckContext, space: string) { const res = await operatorFetch(ctx)( `${ctx.target.origin}/xrpc/com.atproto.space.exportSpaceMeta?space=${encodeURIComponent(space)}`, ); - if (res.status !== 200) { + if (res.status !== 200) throw new Error( `exportSpaceMeta ${res.status} ${await res.text().catch(() => "")}`, ); - } return { type: res.headers.get("Content-Type") ?? "", archive: await readSpaceMetaStar([new Uint8Array(await res.arrayBuffer())]), @@ -370,7 +402,7 @@ const importMeta = async (ctx: CheckContext, archive: SpaceMetaArchive) => xrpcPostBytes( asOperator(ctx), "com.atproto.space.importSpaceMeta", - await collectBytes(serializeSpaceMeta(archive)), + await collectBytes(writeSpaceMetaStar(archive)), ); const memberKey = (did: string) => `com.atproto.memberspace.member/${did}`; @@ -379,16 +411,13 @@ const exportSpaceMeta = crypto$("migration.export-space-meta", async (ctx) => { const space = await createProbeSpace(ctx, memberspace({ publicWrite: true })); const member = fakeDid(); try { - await xrpcPost(asOperator(ctx), "com.atproto.memberspace.putMember", { - space: space.uri, - did: member, - read: true, - write: false, - }); + await putMembers(ctx, space.uri, [ + { did: member, read: true, write: false }, + ]); await mustCreateRecord(ctx, space.uri, "a"); const { type, archive } = await exportMeta(ctx, space.uri); const problems: string[] = []; - if (!type.includes("application/octet-stream")) + if (!type.includes("application/vnd.dasl.star")) problems.push(`content-type ${type}`); if (archive.space !== space.uri) problems.push(`space ${archive.space}`); if (archive.policy.$type !== "com.atproto.memberspace.policy") @@ -396,13 +425,23 @@ const exportSpaceMeta = crypto$("migration.export-space-meta", async (ctx) => { const entry = archive.policyState.find((e) => e.key === memberKey(member)); if (!entry || entry.value.read !== true || entry.value.write !== false) problems.push("member entry missing or wrong"); - if (!archive.writers.some((w) => w.did === ctx.target.did)) - problems.push("the authority is not in the writer set"); - return problems.length - ? fail(problems.join("; "), archive) - : pass("archive carries the policy, the member and the writer set"); + const writer = archive.writers.find((w) => w.did === ctx.target.did); + if (!writer || !isTid(writer.repoRev)) + problems.push("the authority is not in the writer set with a repoRev"); + if (problems.length) return fail(problems.join("; "), archive); + // A removed writer is left out of the archive. + await xrpcPost(asOperator(ctx), "com.atproto.space.removeWriter", { + space: space.uri, + repo: ctx.target.did, + }); + const after = await exportMeta(ctx, space.uri); + return after.archive.writers.some((w) => w.did === ctx.target.did) + ? fail("a removed writer is still in the exported writer set") + : pass( + "archive carries the policy, the member and live writers with repoRev; removed writers are left out", + ); } catch (err) { - return fail((err as Error).message); + return fail(errMsg(err)); } finally { await deleteProbeSpace(ctx, space.uri); } @@ -413,12 +452,9 @@ const importSpaceMeta = crypto$("migration.import-space-meta", async (ctx) => { const before = fakeDid(); const after = fakeDid(); try { - await xrpcPost(asOperator(ctx), "com.atproto.memberspace.putMember", { - space: space.uri, - did: before, - read: true, - write: true, - }); + await putMembers(ctx, space.uri, [ + { did: before, read: true, write: true }, + ]); const { archive } = await exportMeta(ctx, space.uri); // Import a changed configuration over the space: it replaces, not merges. const imported = await importMeta(ctx, { @@ -458,14 +494,14 @@ const importSpaceMeta = crypto$("migration.import-space-meta", async (ctx) => { ? pass("imported policy and member list replaced the old ones") : fail(`members after import: ${dids.join(", ") || "none"}`, list.json); } catch (err) { - return fail((err as Error).message); + return fail(errMsg(err)); } finally { await deleteProbeSpace(ctx, space.uri); } }); -const importMetaNotOwner = crypto$( - "migration.import-space-meta-not-owner", +const importMetaNotAuthority = crypto$( + "migration.import-space-meta-not-authority", async (ctx) => { const res = await importMeta(ctx, { space: unknownSpaceUri(FOREIGN_DID) as never, @@ -473,9 +509,9 @@ const importMetaNotOwner = crypto$( policyState: [], writers: [], }); - return res.error === "NotSpaceOwner" - ? pass("answered NotSpaceOwner") - : fail(`answered ${describe(res)}, expected NotSpaceOwner`, res.json); + return res.error === "NotAuthorized" + ? pass("answered NotAuthorized") + : fail(`answered ${describe(res)}, expected NotAuthorized`, res.json); }, ); @@ -496,6 +532,20 @@ const importMetaUnsupported = crypto$( }, ); +const importMetaInvalid = crypto$( + "migration.import-space-meta-invalid", + async (ctx) => { + const res = await xrpcPostBytes( + asOperator(ctx), + "com.atproto.space.importSpaceMeta", + utf8("not a STAR archive"), + ); + return res.error === "InvalidSpaceMeta" + ? pass("answered InvalidSpaceMeta") + : fail(`answered ${describe(res)}, expected InvalidSpaceMeta`, res.json); + }, +); + async function ownRepoArchive( ctx: CheckContext, space: string, @@ -518,6 +568,16 @@ const importRepo = crypto$("migration.import-repo", async (ctx) => { await exported[Symbol.asyncDispose](); // Change the repo after export, so the import visibly replaces it. await mustCreateRecord(ctx, space.uri, "c", "three"); + // The lexicon's input encoding is application/vnd.dasl.star. + const wrongType = await xrpcPostBytes( + asOperator(ctx), + "com.atproto.space.importRepo", + bytes, + undefined, + "application/octet-stream", + ); + if (wrongType.status === 200) + return fail("importRepo accepted an application/octet-stream body"); const res = await xrpcPostBytes( asOperator(ctx), "com.atproto.space.importRepo", @@ -528,10 +588,7 @@ const importRepo = crypto$("migration.import-repo", async (ctx) => { const list = await xrpcGet( asOperator(ctx), "com.atproto.space.listRecords", - { - space: space.uri, - repo: ctx.target.did, - }, + { space: space.uri, repo: ctx.target.did }, ); const rkeys = ( (list.json as { records?: Array<{ rkey: string }> } | undefined) @@ -544,10 +601,7 @@ const importRepo = crypto$("migration.import-repo", async (ctx) => { const latest = await xrpcGet( asOperator(ctx), "com.atproto.space.getLatestCommit", - { - space: space.uri, - repo: ctx.target.did, - }, + { space: space.uri, repo: ctx.target.did }, ); const now = commitFromJson( (latest.json as { commit?: unknown } | undefined)?.commit, @@ -560,30 +614,39 @@ const importRepo = crypto$("migration.import-repo", async (ctx) => { if (!bytesEqual(now.data, commit.data)) return fail("commit data changed across the import"); return now.rev > commit.rev - ? pass("records replaced from the archive; same data, new rev") + ? pass( + "refused octet-stream; records replaced from the archive; same data, new rev", + ) : fail(`rev ${now.rev} did not advance past the archive's ${commit.rev}`); } catch (err) { - return fail((err as Error).message); + return fail(errMsg(err)); } finally { await deleteProbeSpace(ctx, space.uri); } }); +const emptyRepoArchive = (space: string, repo: string) => + collectBytes( + writeRepoStar( + new RepoCommit().toCommit({ + space: space as never, + repo: repo as Did, + rev: tidNow() as never, + }), + [], + ), + ); + const importRepoNotFound = crypto$( "migration.import-repo-space-not-found", async (ctx) => { // A well-formed archive of an empty repo in an own space this host has // never heard of: the authority's space must be imported first. const space = `at://${ctx.target.did}/space/${PROBE_TYPE}/${probeSkey()}`; - const commit = new RepoCommit().toCommit({ - space: space as never, - repo: ctx.target.did as never, - rev: tidNow(), - }); const res = await xrpcPostBytes( asOperator(ctx), "com.atproto.space.importRepo", - await collectBytes(serializeRepo(commit, [])), + await emptyRepoArchive(space, ctx.target.did), ); if (res.status === 200) await deleteProbeSpace(ctx, space); return res.error === "SpaceNotFound" @@ -592,30 +655,56 @@ const importRepoNotFound = crypto$( }, ); +const importRepoInvalid = crypto$( + "migration.import-repo-invalid", + async (ctx) => { + const res = await xrpcPostBytes( + asOperator(ctx), + "com.atproto.space.importRepo", + utf8("not a STAR archive"), + ); + return res.error === "InvalidRepoFile" + ? pass("answered InvalidRepoFile") + : fail(`answered ${describe(res)}, expected InvalidRepoFile`, res.json); + }, +); + +const importRepoMismatch = crypto$( + "migration.import-repo-mismatch", + async (ctx) => { + const space = await createProbeSpace(ctx, personalspace()); + try { + const res = await xrpcPostBytes( + asOperator(ctx), + "com.atproto.space.importRepo", + await emptyRepoArchive(space.uri, fakeDid()), + ); + return res.error === "RepoMismatch" + ? pass("answered RepoMismatch") + : fail(`answered ${describe(res)}, expected RepoMismatch`, res.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +); + // --- foreign identities -------------------------------------------------- -const isUserRefusal = (error?: string) => - error === "SpaceNotFound" || - error === "UserNotAuthorized" || - error === "NotAuthorized"; +const isAccountRefusal = (error?: string) => + error !== undefined && ACCOUNT_REFUSALS.includes(error); const memberGate = crypto$("credential.member-gate", async (ctx) => { const reader = await ctx.identities!.identity("reader"); const space = await createProbeSpace(ctx, memberspace()); const put = (read: boolean) => - xrpcPost(asOperator(ctx), "com.atproto.memberspace.putMember", { - space: space.uri, - did: reader.did, - read, - write: false, - }); + putMembers(ctx, space.uri, [{ did: reader.did, read, write: false }]); try { await mustCreateRecord(ctx, space.uri, "shared", "members only"); const stranger = await obtainCredential(ctx, reader, space.uri); if (stranger.credential) return fail("a non-member obtained a credential"); - if (!isUserRefusal(stranger.result.error)) { + if (!isAccountRefusal(stranger.result.error)) { return fail( - `non-member refused with ${describe(stranger.result)}; expected SpaceNotFound, UserNotAuthorized or NotAuthorized`, + `non-member refused with ${describe(stranger.result)}; expected ${ACCOUNT_REFUSALS.join(" / ")}`, ); } await put(false); @@ -659,11 +748,11 @@ const personalOnly = crypto$("policy.personalspace-owner-only", async (ctx) => { try { const res = await obtainCredential(ctx, reader, space.uri); if (res.credential) - return fail("a personalspace issued a credential to another user"); - return isUserRefusal(res.result.error) + return fail("a personalspace issued a credential to another account"); + return isAccountRefusal(res.result.error) ? pass(`refused with ${res.result.error}`) : fail( - `refused with ${describe(res.result)}; expected SpaceNotFound, UserNotAuthorized or NotAuthorized`, + `refused with ${describe(res.result)}; expected ${ACCOUNT_REFUSALS.join(" / ")}`, ); } finally { await deleteProbeSpace(ctx, space.uri); @@ -676,27 +765,20 @@ const delegationWrongAud = crypto$( const reader = await ctx.identities!.identity("reader"); const space = await createProbeSpace(ctx, memberspace()); try { - await xrpcPost(asOperator(ctx), "com.atproto.memberspace.putMember", { - space: space.uri, - did: reader.did, - read: true, - write: false, - }); - // Positive control: with the right audience the reader is admitted, so - // the refusal below is the audience's and not an unresolvable reader. + await putMembers(ctx, space.uri, [ + { did: reader.did, read: true, write: false }, + ]); + // Positive control: with the right audience the reader is admitted. const control = await obtainCredential(ctx, reader, space.uri); - if (!control.credential) { + if (!control.credential) return fail( `correct-aud control failed (${describe(control.result)}); cannot attribute the wrong-aud refusal`, ); - } const { result, credential } = await obtainCredential( ctx, reader, space.uri, - { - audOverride: `${FOREIGN_DID}#atproto_pds`, - }, + { audOverride: `${FOREIGN_DID}#atproto_pds` }, ); if (credential) return fail("a token addressed to another host was accepted"); @@ -711,7 +793,7 @@ const delegationWrongAud = crypto$( }, ); -async function notifyWrite( +async function notifyRepoUpdate( ctx: CheckContext, writer: { did: string; @@ -723,12 +805,12 @@ async function notifyWrite( data: Uint8Array, ) { const jwt = await serviceJwt(writer, { - aud: spaceHostAud(ctx.target.did), - lxm: "com.atproto.space.notifyWrite", + aud: spaceHostAud(ctx.target.did as Did), + lxm: "com.atproto.space.notifyRepoUpdate", }); return xrpcPost( ctx, - "com.atproto.space.notifyWrite", + "com.atproto.space.notifyRepoUpdate", { space, repo: writer.did, @@ -739,82 +821,144 @@ async function notifyWrite( ); } -const notifyAccepted = crypto$("host.notifywrite-accepted", async (ctx) => { - const writer = await ctx.identities!.identity("writer"); - const space = await createProbeSpace(ctx, memberspace({ publicRead: true })); - try { - await xrpcPost(asOperator(ctx), "com.atproto.memberspace.putMember", { - space: space.uri, - did: writer.did, - read: false, - write: true, - }); - const repoRev = tidNow(); - const data = globalThis.crypto.getRandomValues(new Uint8Array(32)); - const res = await notifyWrite(ctx, writer, space.uri, repoRev, data); - if (res.status !== 200) - return fail(`notifyWrite ${describe(res)}`, res.json); - const credential = await obtainPublicCredential(ctx, space.uri); - const list = await credentialCall( +const notifyAccepted = crypto$( + "host.notifyrepoupdate-accepted", + async (ctx) => { + const writer = await ctx.identities!.identity("writer"); + const space = await createProbeSpace( ctx, - credential, - "com.atproto.space.listRepos", - { - params: { space: space.uri }, - audience: ctx.target.did, - }, + memberspace({ publicRead: true }), ); - const entry = ( - ( - list.json as - | { repos?: Array<{ did: string; repoRev: string; data: unknown }> } - | undefined - )?.repos ?? [] - ).find((r) => r.did === writer.did); - if (!entry) - return fail("the notified writer is not in listRepos", list.json); - const listed = lexBytes(entry.data); - return entry.repoRev === repoRev && listed && bytesEqual(listed, data) - ? pass("accepted; listRepos reports the notified repoRev and data") - : fail("listRepos entry does not match the notification", entry); - } finally { - await deleteProbeSpace(ctx, space.uri); - } -}); + try { + await putMembers(ctx, space.uri, [ + { did: writer.did, read: false, write: true }, + ]); + const repoRev = tidNow(); + const data = globalThis.crypto.getRandomValues(new Uint8Array(32)); + const res = await notifyRepoUpdate(ctx, writer, space.uri, repoRev, data); + if (res.status !== 200) + return fail(`notifyRepoUpdate ${describe(res)}`, res.json); + const { repos } = await listWriters( + ctx, + await obtainPublicCredential(ctx, space.uri), + ); + const entry = repos.find((r) => r.repo === writer.did); + if (!entry) return fail("the notified writer is not in listWriters"); + const listed = lexBytes(entry.data); + return entry.$type === "com.atproto.space.defs#repoWrite" && + entry.repoRev === repoRev && + listed && + bytesEqual(listed, data) + ? pass("accepted; listWriters reports the notified repoRev and data") + : fail("listWriters entry does not match the notification", entry); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +); -const notifyFuture = crypto$("host.notifywrite-future-rev", async (ctx) => { - const writer = await ctx.identities!.identity("writer"); - const space = await createProbeSpace(ctx, memberspace({ publicWrite: true })); - try { - const hourAhead = BigInt(Date.now() + 60 * 60 * 1000) * 1000n; - const res = await notifyWrite( +const notifyFuture = crypto$( + "host.notifyrepoupdate-future-rev", + async (ctx) => { + const writer = await ctx.identities!.identity("writer"); + const space = await createProbeSpace( + ctx, + memberspace({ publicWrite: true }), + ); + try { + const hourAhead = BigInt(Date.now() + 60 * 60 * 1000) * 1000n; + const res = await notifyRepoUpdate( + ctx, + writer, + space.uri, + tidAt(hourAhead), + new Uint8Array(32), + ); + return res.error === "FutureRev" + ? pass("a repoRev an hour ahead answered FutureRev") + : fail(`answered ${describe(res)}, expected FutureRev`, res.json); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +); + +const notifyUnknown = crypto$( + "host.notifyrepoupdate-unknown-space", + async (ctx) => { + const writer = await ctx.identities!.identity("writer"); + const res = await notifyRepoUpdate( ctx, writer, - space.uri, - tidAt(hourAhead), + unknownSpaceUri(ctx.target.did), + tidNow(), new Uint8Array(32), ); - return res.error === "FutureRev" - ? pass("a repoRev an hour ahead answered FutureRev") - : fail(`answered ${describe(res)}, expected FutureRev`, res.json); - } finally { - await deleteProbeSpace(ctx, space.uri); - } -}); + return res.error === "SpaceNotFound" + ? pass("answered SpaceNotFound") + : fail(`answered ${describe(res)}, expected SpaceNotFound`, res.json); + }, +); -const notifyUnknown = crypto$("host.notifywrite-unknown-space", async (ctx) => { - const writer = await ctx.identities!.identity("writer"); - const res = await notifyWrite( - ctx, - writer, - unknownSpaceUri(ctx.target.did), - tidNow(), - new Uint8Array(32), - ); - return res.error === "SpaceNotFound" - ? pass("answered SpaceNotFound") - : fail(`answered ${describe(res)}, expected SpaceNotFound`, res.json); -}); +const writeRevocation = crypto$( + "memberspace.write-revocation-removes-writer", + async (ctx) => { + const writer = await ctx.identities!.identity("writer"); + const space = await createProbeSpace( + ctx, + memberspace({ publicRead: true, publicWrite: true }), + ); + try { + await putMembers(ctx, space.uri, [ + { did: writer.did, read: true, write: true }, + ]); + const first = await notifyRepoUpdate( + ctx, + writer, + space.uri, + tidNow(), + new Uint8Array(32), + ); + if (first.status !== 200) + return fail(`notifyRepoUpdate ${describe(first)}`, first.json); + const credential = await obtainPublicCredential(ctx, space.uri); + const entry = async () => + (await listWriters(ctx, credential)).repos + .filter((r) => r.repo === writer.did) + .at(-1); + if ((await entry())?.$type !== "com.atproto.space.defs#repoWrite") + return fail("the writer never entered the writer set"); + // Revoking write access removes it, announced as repoRemoved... + await putMembers(ctx, space.uri, [ + { did: writer.did, read: true, write: false }, + ]); + const removed = await entry(); + if (removed?.$type !== "com.atproto.space.defs#repoRemoved") + return fail( + `after revoking write, the entry is ${JSON.stringify(removed)}`, + ); + // ...and, even under publicWrite, a member without write is not tracked. + const again = await notifyRepoUpdate( + ctx, + writer, + space.uri, + tidNow(), + new Uint8Array(32), + ); + const after = await entry(); + return after?.$type === "com.atproto.space.defs#repoRemoved" + ? pass( + `removed as repoRemoved; a later notification was not tracked (${describe(again)})`, + ) + : fail( + "a member without write access was tracked again under publicWrite", + after, + ); + } finally { + await deleteProbeSpace(ctx, space.uri); + } + }, +); /** * The revocation flow: a harness identity plays a foreign space authority, @@ -825,10 +969,9 @@ async function revocationFlow( ctx: CheckContext, revoker: "authority" | "stranger", ): Promise<{ - before: number; - after?: { status: number; error?: string }; - revoke?: { status: number; error?: string }; detail?: string; + revoke?: { status: number; error?: string }; + after?: { status: number; error?: string }; }> { const authority = await ctx.identities!.identity("authority"); const space = `at://${authority.did}/space/${PROBE_TYPE}/${probeSkey()}`; @@ -838,7 +981,6 @@ async function revocationFlow( }); if (write.status !== 200) return { - before: write.status, detail: `operator write into a foreign space: ${describe(write)}`, }; const key = await createCredentialKey(); @@ -857,7 +999,6 @@ async function revocationFlow( const before = await read(); if (before.status !== 200) return { - before: before.status, detail: `foreign authority's credential could not read: ${describe(before)}`, }; const signer = @@ -866,17 +1007,15 @@ async function revocationFlow( : await ctx.identities!.identity("stranger"); const jwt = await serviceJwt(signer, { aud: ctx.target.did, - lxm: "com.atproto.space.notifyCredentialRevoked", + lxm: "com.atproto.space.notifyCredentialsRevoked", }); - const { payload } = decodeJwt(credential.credential); const revoke = await xrpcPost( ctx, - "com.atproto.space.notifyCredentialRevoked", - { space, credentials: [payload.jti] }, + "com.atproto.space.notifyCredentialsRevoked", + { space, credentials: [decodeJwt(credential.credential).payload.jti] }, { Authorization: `Bearer ${jwt}` }, ); - const after = await read(); - return { before: 200, revoke, after }; + return { revoke, after: await read() }; } const revocationRefused = crypto$( @@ -886,7 +1025,7 @@ const revocationRefused = crypto$( if (flow.detail) return fail(flow.detail); if (flow.revoke!.status !== 200) return fail( - `notifyCredentialRevoked ${flow.revoke!.status} ${flow.revoke!.error ?? ""}`, + `notifyCredentialsRevoked ${flow.revoke!.status} ${flow.revoke!.error ?? ""}`, ); return flow.after!.status >= 400 && flow.after!.status < 500 ? pass( @@ -923,46 +1062,49 @@ const revocationStranger = crypto$( }, ); -const managedSpace = crypto$("managedspace.checkuseraccess", async (ctx) => { - const inbox = ctx.syncerInbox!; - const reader = await ctx.identities!.identity("reader"); - const lxm = "com.atproto.managedspace.checkUserAccess"; - let decision = false; - inbox.respond(lxm, () => ({ authorized: decision })); - const space = await createProbeSpace(ctx, managedspace(inbox.service)); - try { - const since = Date.now(); - const denied = await obtainCredential(ctx, reader, space.uri); - if (denied.credential) - return fail("issued a credential the managing app refused"); - const asked = await inbox.waitFor( - (d) => d.lxm === lxm && d.receivedAt >= since, - 5_000, - ); - if (!asked) - return fail( - `the managing app was never asked (${describe(denied.result)})`, +const managedAccount = crypto$( + "managedspace.check-access-account", + async (ctx) => { + const inbox = ctx.syncerInbox!; + const reader = await ctx.identities!.identity("reader"); + const lxm = "com.atproto.managedspace.checkAccess"; + let answer = { read: false, write: false }; + inbox.respond(lxm, () => answer); + const space = await createProbeSpace(ctx, managedspace(inbox.service)); + try { + const since = Date.now(); + const denied = await obtainCredential(ctx, reader, space.uri); + if (denied.credential) + return fail("issued a credential the managing app refused"); + const asked = await inbox.waitFor( + (d) => + d.lxm === lxm && + d.receivedAt >= since && + d.params?.repo === reader.did, + 5_000, ); - const p = asked.params ?? {}; - if (p.space !== space.uri || p.user !== reader.did || p.access !== "read") { - return fail("checkUserAccess carried the wrong params", p); - } - if (!asked.authorization?.startsWith("Bearer ")) - return fail("checkUserAccess was sent without service auth"); - decision = true; - const allowed = await obtainCredential(ctx, reader, space.uri); - return allowed.credential - ? pass( - `asked the managing app (space, user, access=read); refused on false (${denied.result.error}), issued on true`, - ) - : fail( - `the managing app authorised but the credential was refused: ${describe(allowed.result)}`, + if (!asked) + return fail( + `the managing app was never asked about the reader (${describe(denied.result)})`, ); - } finally { - inbox.respond(lxm, undefined); - await deleteProbeSpace(ctx, space.uri); - } -}); + const p = asked.params ?? {}; + if (p.space !== space.uri || "access" in p) + return fail("checkAccess carried the wrong params", p); + answer = { read: true, write: false }; + const allowed = await obtainCredential(ctx, reader, space.uri); + return allowed.credential + ? pass( + `asked about the reader (space, repo); refused on read:false (${denied.result.error}), issued on read:true`, + ) + : fail( + `the managing app authorised but the credential was refused: ${describe(allowed.result)}`, + ); + } finally { + inbox.respond(lxm, undefined); + await deleteProbeSpace(ctx, space.uri); + } + }, +); /** The crypto-bound catalog, in descriptor order. */ export const cryptoChecks: Check[] = [ @@ -974,18 +1116,22 @@ export const cryptoChecks: Check[] = [ delegationSigned, exportSpaceMeta, importSpaceMeta, - importMetaNotOwner, + importMetaNotAuthority, importMetaUnsupported, + importMetaInvalid, importRepo, importRepoNotFound, + importRepoInvalid, + importRepoMismatch, memberGate, personalOnly, delegationWrongAud, notifyAccepted, notifyFuture, notifyUnknown, + writeRevocation, revocationRefused, revocationName, revocationStranger, - managedSpace, + managedAccount, ]; diff --git a/packages/space-conformance/src/full/helpers.ts b/packages/space-conformance/src/full/helpers.ts index 3dadda2..00b2fb2 100644 --- a/packages/space-conformance/src/full/helpers.ts +++ b/packages/space-conformance/src/full/helpers.ts @@ -11,16 +11,13 @@ */ import { - COMMIT_MAC_TYPE, - RECORD_MAC_TYPE, - createSpaceToken, - parseMacHeader, + createDelegationToken, + createSpaceCredential, spaceHostAud, - type Commit, + type SpaceCommit, } from "@atproto/space"; import type { CheckContext, HarnessIdentity } from "../model.js"; -import { toBase64Url, utf8, lexBytes } from "../encoding.js"; -import { MAC_HEADER } from "../space-auth.js"; +import { lexBytes, toBase64Url, utf8 } from "../encoding.js"; import { requestCredential, spaceAuthority, @@ -41,7 +38,9 @@ export { } from "../checks/probe.js"; export type { Credential, ProbeSpace } from "../checks/probe.js"; -/** Adapt a harness identity to the `Keypair` surface token minting uses. */ +type Did = `did:${string}:${string}`; + +/** Adapt a harness identity to the `Signer` surface token minting uses. */ function keypairFor(identity: HarnessIdentity) { return { jwtAlg: identity.jwtAlg, @@ -59,15 +58,12 @@ export function mintDelegation( space: string, audOverride?: string, ): Promise { - return createSpaceToken( - "delegation", - { - iss: identity.did, - sub: space, - aud: audOverride ?? spaceHostAud(spaceAuthority(space)), - }, - keypairFor(identity), - ); + return createDelegationToken({ + iss: identity.did as Did, + sub: space as never, + aud: audOverride ?? spaceHostAud(spaceAuthority(space) as Did), + keypair: keypairFor(identity), + }); } /** @@ -94,20 +90,17 @@ export async function obtainCredential( * playing a foreign space authority whose credentials a repo host must * honour for reads of its repos in that space. */ -export async function mintCredential( +export function mintCredential( authority: HarnessIdentity, space: string, keyDid: string, ): Promise { - return createSpaceToken( - "credential", - { - iss: authority.did, - sub: space, - keyId: keyDid as `did:${string}:${string}`, - }, - keypairFor(authority), - ); + return createSpaceCredential({ + iss: authority.did as Did, + sub: space as never, + keyId: keyDid as Did, + keypair: keypairFor(authority), + }); } /** An inter-service auth JWT (`lxm`-scoped), signed as `identity`. */ @@ -131,26 +124,24 @@ export async function serviceJwt( } /** A commit as the wire JSON carries it, with `data` decoded. */ -export function commitFromJson(value: unknown): Commit | undefined { +export function commitFromJson(value: unknown): SpaceCommit | undefined { if (!value || typeof value !== "object") return undefined; const raw = value as Record; const data = lexBytes(raw.data); if (!data) return undefined; - return { ...(raw as Omit), data } as Commit; + return { ...(raw as Omit), data } as SpaceCommit; } -/** The MAC a credentialed response carried, or undefined. */ -export function responseMac(res: CredentialResult): Uint8Array | undefined { - const header = res.headers.get(MAC_HEADER); - if (!header) return undefined; - try { - return parseMacHeader( - header, - res.macType === RECORD_MAC_TYPE ? RECORD_MAC_TYPE : COMMIT_MAC_TYPE, - ); - } catch { - return undefined; +/** What `verifyCommit` / `verifyRecord` / `verifyRepoStar` need from a MAC'd response. */ +export function macParams(res: CredentialResult) { + if (!res.keyShare || !res.sharedSecret) { + throw new Error("the response was not requested with a MAC"); } + return { + keyShare: res.keyShare as Did, + sharedSecret: res.sharedSecret, + headers: res.headers, + }; } /** Drain an async byte stream (an archive serializer) into one buffer. */ diff --git a/packages/space-conformance/src/http.ts b/packages/space-conformance/src/http.ts index 4b4692a..f0ae31e 100644 --- a/packages/space-conformance/src/http.ts +++ b/packages/space-conformance/src/http.ts @@ -128,9 +128,10 @@ export async function xrpcPostBytes( nsid: string, bytes: Uint8Array, headers?: HeadersInit, + contentType = "application/vnd.dasl.star", ): Promise { const merged = new Headers(headers); - merged.set("Content-Type", "application/octet-stream"); + merged.set("Content-Type", contentType); const response = await ctx.fetch(xrpcUrl(ctx.target.origin, nsid), { method: "POST", headers: merged, diff --git a/packages/space-conformance/src/inbox.ts b/packages/space-conformance/src/inbox.ts new file mode 100644 index 0000000..4c4c5ce --- /dev/null +++ b/packages/space-conformance/src/inbox.ts @@ -0,0 +1,129 @@ +/** + * A ready-made syncer inbox: the `notify` endpoint and managing app the + * notification checks need, as a fetch-style handler. A harness serves + * `handle` at `endpoint` however suits it — a node HTTP server, a route in + * an in-process fixture — and passes `inbox` as `ctx.syncerInbox`. + * + * Browser-safe (Request/Response only), though no browser can be reached + * by a remote host, so the web checker never offers it. + */ + +import type { InboxDelivery, SyncerInbox } from "./model.js"; +import { toBase64Url } from "./encoding.js"; + +export interface SyncerInboxHandle { + inbox: SyncerInbox; + /** Serve a request addressed to the inbox's endpoint. */ + handle(request: Request): Promise; + /** Every delivery so far, oldest first. */ + deliveries(): readonly InboxDelivery[]; +} + +const json = (status: number, body: unknown) => + new Response(JSON.stringify(body), { + status, + headers: { "Content-Type": "application/json" }, + }); + +export function createSyncerInbox(opts: { + /** Base URL the target will call (`{endpoint}/xrpc/`). */ + endpoint: string; + /** A `did#serviceId` reference resolving to `endpoint` (managing app). */ + service: string; +}): SyncerInboxHandle { + const deliveries: InboxDelivery[] = []; + const waiters = new Set<() => void>(); + const responders = new Map unknown>(); + const tokens = new Map(); // token → space + + const known = (body: unknown) => { + const b = body as { space?: unknown; token?: unknown } | undefined; + return ( + typeof b?.token === "string" && + typeof b.space === "string" && + tokens.get(b.token) === b.space + ); + }; + + async function handle(request: Request): Promise { + const url = new URL(request.url); + const lxm = url.pathname.replace(/^\/xrpc\//, ""); + const raw = request.method === "POST" ? await request.text() : ""; + let body: unknown; + try { + body = raw ? JSON.parse(raw) : undefined; + } catch { + body = raw; + } + let response: Response; + if (lxm === "com.atproto.space.confirmRegistration") { + // Echo the challenge only for a token issued for this space. + response = known(body) + ? json(200, { challenge: (body as { challenge: unknown }).challenge }) + : json(400, { error: "InvalidToken", message: "unknown token" }); + } else if (lxm === "com.atproto.space.notifySpaceUpdate") { + response = known(body) + ? json(200, {}) + : json(400, { error: "InvalidToken", message: "unknown token" }); + } else { + const responder = responders.get(lxm); + response = responder + ? json( + 200, + responder({ + lxm, + body, + params: Object.fromEntries(url.searchParams), + status: 200, + receivedAt: Date.now(), + }), + ) + : json(501, { error: "MethodNotImplemented" }); + } + const authorization = request.headers.get("authorization"); + deliveries.push({ + lxm, + body, + params: Object.fromEntries(url.searchParams), + ...(authorization ? { authorization } : {}), + status: response.status, + receivedAt: Date.now(), + }); + for (const wake of waiters) wake(); + return response; + } + + const inbox: SyncerInbox = { + endpoint: opts.endpoint, + service: opts.service, + issueToken(space) { + const token = toBase64Url(crypto.getRandomValues(new Uint8Array(32))); + tokens.set(token, space); + return token; + }, + async waitFor(predicate, timeoutMs) { + const deadline = Date.now() + timeoutMs; + for (;;) { + const found = deliveries.find(predicate); + if (found) return found; + const remaining = deadline - Date.now(); + if (remaining <= 0) return null; + await new Promise((resolve) => { + const done = () => { + clearTimeout(timer); + waiters.delete(done); + resolve(); + }; + const timer = setTimeout(done, remaining); + waiters.add(done); + }); + } + }, + respond(lxm, handler) { + if (handler) responders.set(lxm, handler); + else responders.delete(lxm); + }, + }; + + return { inbox, handle, deliveries: () => deliveries }; +} diff --git a/packages/space-conformance/src/index.ts b/packages/space-conformance/src/index.ts index 7debfb1..b3fbd92 100644 --- a/packages/space-conformance/src/index.ts +++ b/packages/space-conformance/src/index.ts @@ -58,15 +58,23 @@ export type { export { createCredentialKey, + credentialSigMembers, encapsulate, - formatWantMacHeader, + formatMacRequest, isP256DidKey, spaceSigHeaders, - COMMIT_MAC_TYPE, - RECORD_MAC_TYPE, + COMMIT_MAC_PROFILE, + RECORD_MAC_PROFILE, + MAC_COVERED_HEADER, SPACE_CREDENTIAL_SCHEME, } from "./space-auth.js"; -export type { CredentialKey, MacType } from "./space-auth.js"; +export type { + CredentialKey, + CredentialSigOptions, + MacProfile, +} from "./space-auth.js"; +export { createSyncerInbox } from "./inbox.js"; +export type { SyncerInboxHandle } from "./inbox.js"; export { DEFAULT_PLC_DIRECTORY, didDocumentUrl, @@ -81,6 +89,7 @@ export type { CheckDescriptor } from "./descriptors.js"; export { ALPHA_BUILD } from "./alpha.js"; export { knownChangesets } from "./changesets.js"; +export { knownProposalAnchors, PROPOSAL_COMMIT } from "./proposal.js"; import { baseChecks as base } from "./checks/base.js"; import { operatorChecks as operator } from "./checks/operator.js"; diff --git a/packages/space-conformance/src/model.ts b/packages/space-conformance/src/model.ts index 9e7e540..a7af956 100644 --- a/packages/space-conformance/src/model.ts +++ b/packages/space-conformance/src/model.ts @@ -56,9 +56,9 @@ export interface Citation { * scopes — only harnesses that can drive the target's consent flow. * - `identities`: harness-controlled DIDs with resolvable documents and * held keys, for playing reader/writer roles. - * - `syncer-inbox`: a service the harness controls, named by a DID the - * target can resolve, that the target can deliver notifications to (as a - * syncer) and query (as a `managedspace` managing app). + * - `syncer-inbox`: an endpoint the harness serves that the target can + * reach — registered as a syncer's `notify` endpoint, and named (through + * a resolvable `did#serviceId`) as a `managedspace` managing app. * - `pds-blobs`: the target is a full PDS implementing * `com.atproto.repo.uploadBlob` and `com.atproto.sync.getBlob` — needed * to prove a space blob is not served publicly. A standalone space host, @@ -120,19 +120,38 @@ export interface IdentityProvider { identity(role: string): Promise; } +/** + * A syncer endpoint the harness serves: the `notify` target of + * `authorizeSpaceSync`, which the space host calls back with + * `com.atproto.space.confirmRegistration` and `notifySpaceUpdate`. The + * same endpoint doubles as a `managedspace` managing app answering + * `com.atproto.managedspace.checkAccess`. + * + * `createSyncerInbox()` implements all of this over a fetch-style handler; + * a harness only has to route requests for `endpoint` to it. + */ export interface SyncerInbox { + /** The base URL registered as `notify.endpoint` (`{endpoint}/xrpc/...`). */ + endpoint: string; /** - * The service identifier to register or name as a managing app: a DID - * (optionally with a `#fragment`) whose document routes to this inbox. + * A `did#serviceId` reference whose DID document routes that service to + * `endpoint`, for naming the inbox as a managing app. The target sends + * service auth addressed to it. */ service: string; + /** + * Issue a fresh notify token for `space`. The inbox confirms a + * registration (echoes the challenge) and accepts notifications only for + * tokens it issued for that space; anything else is refused with 400. + */ + issueToken(space: string): string; /** Wait for a delivery matching the predicate, or time out (null). */ waitFor( predicate: (delivery: InboxDelivery) => boolean, timeoutMs: number, ): Promise; /** - * Answer queries for `lxm` (e.g. `com.atproto.managedspace.checkUserAccess`) + * Answer queries for `lxm` (e.g. `com.atproto.managedspace.checkAccess`) * with the handler's JSON body; pass undefined to stop answering. Queries * are recorded as deliveries either way. */ @@ -149,6 +168,8 @@ export interface InboxDelivery { /** Query parameters of a query. */ params?: Record; authorization?: string; + /** The HTTP status the inbox answered with. */ + status: number; receivedAt: number; } @@ -215,6 +236,8 @@ export interface Check { destructive?: boolean; /** Depends on real time passing (expiry windows); excluded by default. */ slow?: boolean; + /** Overrides the runner's per-check timeout (for slow checks). */ + timeoutMs?: number; run(ctx: CheckContext): Promise; } diff --git a/packages/space-conformance/src/proposal.ts b/packages/space-conformance/src/proposal.ts new file mode 100644 index 0000000..9e0e6bf --- /dev/null +++ b/packages/space-conformance/src/proposal.ts @@ -0,0 +1,71 @@ +/** + * The section anchors of proposal 0016 (Atproto Spaces), as combined in + * bluesky-social/proposals#143 at b54ec685 — the spec this alpha + * implements. A `proposal` citation's ref is `0016#`, checked + * against this list (the typo guard lexicon and changeset citations get). + * Regenerate it from the proposal's headings when the alpha moves. + */ +export const PROPOSAL_COMMIT = "b54ec6853bab77edd4fd373804a480633094b324"; + +export const knownProposalAnchors: readonly string[] = [ + "introduction", + "relationship-to-public-broadcast", + "terminology", + "spaces", + "addressing", + "space-authority", + "space-type", + "space-type-declarations", + "space-key-skey", + "access-control", + "credential-key-binding", + "delegation-token", + "client-attestation", + "space-credential", + "authorizing-space-sync", + "presenting-a-space-credential", + "credential-flow", + "credential-expiration-and-revocation", + "space-repos", + "repo-lifecycle", + "commit-digest", + "commit-authenticity", + "kem-key", + "shared-secret", + "requesting-a-mac", + "commit-mac", + "record-mac", + "repo-serialization", + "archive-limits", + "sync", + "incremental-sync", + "full-state-recovery", + "blob-sync", + "write-notifications", + "registering-for-notifications", + "the-sync-boundary-writer-set", + "space-deletion", + "moderation", + "label-records", + "takedowns", + "oauth-scopes", + "read-access", + "matching", + "examples", + "consent", + "permission-sets", + "xrpc-api", + "space-policy", + "baseline-policies", + "publishing-to-readers", + "personalspace", + "memberspace", + "managedspace", + "account-migration", + "space-meta-archive", + "considerations", + "access-control-in-applications", + "scaling", + "account-lifecycle", + "appendix-shared-secret-without-hpke", +]; diff --git a/packages/space-conformance/src/runner.ts b/packages/space-conformance/src/runner.ts index cc2a797..ea95f0c 100644 --- a/packages/space-conformance/src/runner.ts +++ b/packages/space-conformance/src/runner.ts @@ -86,7 +86,7 @@ export async function runChecks(options: RunOptions): Promise { try { const outcome = await withTimeout( check.run(checkCtx), - timeoutMs, + Math.max(timeoutMs, check.timeoutMs ?? 0), check.id, controller, ); diff --git a/packages/space-conformance/src/space-auth.ts b/packages/space-conformance/src/space-auth.ts index 0cf0033..450d657 100644 --- a/packages/space-conformance/src/space-auth.ts +++ b/packages/space-conformance/src/space-auth.ts @@ -1,13 +1,14 @@ /** * Browser-safe space credential presentation: P-256 did:key credential * keys, the `atproto-space-credential` HTTP message signature, and the - * KEM key share a syncer sends in `Atproto-Space-Want-Mac`. + * MAC request (`Accept-Signature`, keyed by an HPKE-exported secret) a + * syncer sends with every credentialed read of a commit or record. * * Deliberately dependency-free (WebCrypto and BigInt only) so the checks * that present a credential — the operator's own credential flow, the MAC * and signature refusals — run in a browser bundle too. Every format here * mirrors `@atproto/space` byte for byte (`createSpaceSigHeaders`, - * `encapsulate`, `formatWantMacHeader`); the full test suite cross-checks + * `encapsulate`, `formatMacRequest`); the full test suite cross-checks * each against the reference library, so a drift fails CI rather than * every run against a real host. * @@ -19,7 +20,6 @@ import { concatBytes, fromBase58, - fromBase64, toBase58, toBase64, utf8, @@ -174,57 +174,160 @@ export async function createCredentialKey(): Promise { // --- HTTP message signature -------------------------------------------- export const SPACE_CREDENTIAL_SCHEME = "Atproto-Space-Credential"; -const SIGNATURE_LABEL = "atproto-space-credential"; -const SIGNATURE_PARAMS = `("authorization" "atproto-space-audience");tag="atproto-space-credential"`; +const CREDENTIAL_SIG_TAG = "atproto-space-credential"; +const CREDENTIAL_COMPONENTS = ["authorization", "atproto-space-audience"]; + +/** Serialise RFC 9651 parameters: strings quoted, integers bare. */ +function serializeParams(params: Array<[string, string | number]>): string { + return params + .map(([k, v]) => `;${k}=${typeof v === "number" ? v : `"${v}"`}`) + .join(""); +} + +export interface CredentialSigOptions { + authorization: string; + audience: string; + /** The signature's label. Hosts find it by tag, so any label works; default `sig`. */ + label?: string; + /** Parameters after `tag` (e.g. `keyid`, `alg`, `created`), in order. */ + params?: Array<[string, string | number]>; + /** Covered components; defaults to exactly the two the protocol requires. */ + components?: string[]; + /** Replace the tag (probing hosts that must ignore other tags). */ + tag?: string; +} + +/** One signature's `Signature-Input` and `Signature` dictionary members. */ +export async function credentialSigMembers( + key: Pick, + opts: CredentialSigOptions, +): Promise<{ input: string; signature: string }> { + const components = opts.components ?? CREDENTIAL_COMPONENTS; + const label = opts.label ?? "sig"; + const signatureParams = `(${components.map((c) => `"${c}"`).join(" ")})${serializeParams( + [["tag", opts.tag ?? CREDENTIAL_SIG_TAG], ...(opts.params ?? [])], + )}`; + const values: Record = { + authorization: opts.authorization, + "atproto-space-audience": opts.audience, + }; + const base = [ + ...components.map((c) => `"${c}": ${(values[c] ?? "").trim()}`), + `"@signature-params": ${signatureParams}`, + ].join("\n"); + const signature = await key.sign(utf8(base)); + return { + input: `${label}=${signatureParams}`, + // RFC 9651 byte sequences are padded base64. + signature: `${label}=:${toBase64(signature)}:`, + }; +} /** * The headers that present a space credential: the `Authorization` scheme, * the audience DID (the service being called — the repo DID at a repo * host, the authority DID at the space host) and an RFC 9421 signature by - * the credential's key covering exactly those two fields. + * the credential's key covering exactly those two fields, tagged + * `atproto-space-credential`. */ export async function spaceSigHeaders( key: Pick, - opts: { authorization: string; audience: string }, + opts: CredentialSigOptions, ): Promise> { - const base = [ - `"authorization": ${opts.authorization.trim()}`, - `"atproto-space-audience": ${opts.audience.trim()}`, - `"@signature-params": ${SIGNATURE_PARAMS}`, - ].join("\n"); - const signature = await key.sign(utf8(base)); + const { input, signature } = await credentialSigMembers(key, opts); return { authorization: opts.authorization, "atproto-space-audience": opts.audience, - "signature-input": `${SIGNATURE_LABEL}=${SIGNATURE_PARAMS}`, - // RFC 9651 byte sequences are padded base64. - signature: `${SIGNATURE_LABEL}=:${toBase64(signature)}:`, + "signature-input": input, + signature, }; } // --- KEM / MAC request ------------------------------------------------- -export const COMMIT_MAC_TYPE = "atproto-space-repo"; -export const RECORD_MAC_TYPE = "atproto-space-record"; -export type MacType = typeof COMMIT_MAC_TYPE | typeof RECORD_MAC_TYPE; -const WANT_MAC_HEADER = "atproto-space-want-mac"; -export const MAC_HEADER = "atproto-space-mac"; +export const COMMIT_MAC_PROFILE = "atproto-space-commit"; +export const RECORD_MAC_PROFILE = "atproto-space-record"; +export type MacProfile = typeof COMMIT_MAC_PROFILE | typeof RECORD_MAC_PROFILE; -/** `type="…", ver=1, key_share="did:key:…"` — both MAC types are on v1. */ -export const formatWantMacHeader = (type: MacType, keyShare: string): string => - `type="${type}", ver=1, key_share="${keyShare}"`; +/** The response header each profile's MAC covers. */ +export const MAC_COVERED_HEADER: Record = { + [COMMIT_MAC_PROFILE]: "atproto-space-commit", + [RECORD_MAC_PROFILE]: "atproto-space-record", +}; + +/** + * One `Accept-Signature` member asking for a MAC under `profile`, keyed by + * the shared secret for `keyShare`: + * `mac=("atproto-space-commit";sf);keyid="did:key:…";tag="atproto-space-commit"`. + */ +export function formatMacRequest( + profile: MacProfile, + keyShare: string, + opts: { label?: string; params?: Array<[string, string | number]> } = {}, +): string { + return `${opts.label ?? "mac"}=("${MAC_COVERED_HEADER[profile]}";sf)${serializeParams( + [["keyid", keyShare], ["tag", profile], ...(opts.params ?? [])], + )}`; +} const uint16be = (n: number) => new Uint8Array([n >>> 8, n & 0xff]); -const KEM_PREFIX = concatBytes([ - utf8("HPKE-v1"), - utf8("KEM"), - uint16be(0x0010), +const HPKE_VERSION = utf8("HPKE-v1"); +const KEM_ID = concatBytes([utf8("KEM"), uint16be(0x0010)]); +const SUITE_ID = concatBytes([ + utf8("HPKE"), + uint16be(0x0010), // DHKEM(P-256, HKDF-SHA256) + uint16be(0x0001), // HKDF-SHA256 + uint16be(0xffff), // Export-only AEAD ]); +const EMPTY = new Uint8Array(0); + +async function hmac(key: Uint8Array, data: Uint8Array): Promise { + // An empty HMAC key is equivalent to a block of zeros (RFC 2104), and + // WebCrypto refuses zero-length keys. + const k = await crypto.subtle.importKey( + "raw", + (key.length ? key : new Uint8Array(32)) as BufferSource, + { name: "HMAC", hash: "SHA-256" }, + false, + ["sign"], + ); + return new Uint8Array( + await crypto.subtle.sign("HMAC", k, data as BufferSource), + ); +} + +const labeledExtract = ( + id: Uint8Array, + salt: Uint8Array, + label: string, + ikm: Uint8Array, +) => hmac(salt, concatBytes([HPKE_VERSION, id, utf8(label), ikm])); + +// HKDF-Expand for L = 32: a single block. +const labeledExpand = ( + id: Uint8Array, + prk: Uint8Array, + label: string, + info: Uint8Array, +) => + hmac( + prk, + concatBytes([ + uint16be(32), + HPKE_VERSION, + id, + utf8(label), + info, + new Uint8Array([1]), + ]), + ); /** - * Syncer side of the space KEM: ECDH between a fresh ephemeral P-256 key - * and the author's `#atproto_kem` key, with the secret derived as in - * DHKEM(P-256, HKDF-SHA256) (RFC 9180 §4.1). Use once per request. + * Syncer side of the space KEM: HPKE secret export (RFC 9180 §6.2) in base + * mode with DHKEM(P-256, HKDF-SHA256), HKDF-SHA256 and the Export-only + * AEAD, `info = "atproto-mac"`, an empty exporter context and L = 32 — + * spelled out as the ECDH and HKDF steps it performs. The returned + * `keyShare` is HPKE's `enc`, as a compressed did:key. Use once per request. */ export async function encapsulate( authorKemDidKey: string, @@ -244,7 +347,7 @@ export async function encapsulate( true, ["deriveBits"], ); - const ephemeralBytes = new Uint8Array( + const enc = new Uint8Array( await crypto.subtle.exportKey("raw", ephemeral.publicKey), ); const dh = new Uint8Array( @@ -254,59 +357,28 @@ export async function encapsulate( 256, ), ); - const ikm = concatBytes([KEM_PREFIX, utf8("eae_prk"), dh]); - const info = concatBytes([ - uint16be(32), - KEM_PREFIX, - utf8("shared_secret"), - ephemeralBytes, - authorBytes, - ]); - const hkdfKey = await crypto.subtle.importKey( - "raw", - ikm as BufferSource, - "HKDF", - false, - ["deriveBits"], + const eaePrk = await labeledExtract(KEM_ID, EMPTY, "eae_prk", dh); + const kemSecret = await labeledExpand( + KEM_ID, + eaePrk, + "shared_secret", + concatBytes([enc, authorBytes]), ); - const sharedSecret = new Uint8Array( - await crypto.subtle.deriveBits( - { - name: "HKDF", - hash: "SHA-256", - salt: new Uint8Array(0), - info: info as BufferSource, - }, - hkdfKey, - 256, - ), + const pskIdHash = await labeledExtract(SUITE_ID, EMPTY, "psk_id_hash", EMPTY); + const infoHash = await labeledExtract( + SUITE_ID, + EMPTY, + "info_hash", + utf8("atproto-mac"), ); - return { keyShare: formatDidKey("ES256", ephemeralBytes), sharedSecret }; -} - -/** - * Pull the `mac` byte sequence out of an `Atproto-Space-Mac` header, - * checking its type and version. Undefined when absent or malformed. - */ -export function parseMacHeader( - value: string | null, - type: MacType, -): Uint8Array | undefined { - if (!value) return undefined; - const fields = new Map(); - for (const member of value.split(",")) { - const eq = member.indexOf("="); - if (eq < 0) continue; - fields.set(member.slice(0, eq).trim(), member.slice(eq + 1).trim()); - } - if (fields.get("type") !== `"${type}"` || fields.get("ver") !== "1") { - return undefined; - } - const mac = fields.get("mac"); - if (!mac || !mac.startsWith(":") || !mac.endsWith(":")) return undefined; - try { - return fromBase64(mac.slice(1, -1)); - } catch { - return undefined; - } + const context = concatBytes([new Uint8Array([0]), pskIdHash, infoHash]); + const secret = await labeledExtract(SUITE_ID, kemSecret, "secret", EMPTY); + const exporterSecret = await labeledExpand(SUITE_ID, secret, "exp", context); + const sharedSecret = await labeledExpand( + SUITE_ID, + exporterSecret, + "sec", + EMPTY, + ); + return { keyShare: formatDidKey("ES256", enc), sharedSecret }; } diff --git a/packages/space-conformance/test/cli.test.ts b/packages/space-conformance/test/cli.test.ts index e665063..04a1392 100644 --- a/packages/space-conformance/test/cli.test.ts +++ b/packages/space-conformance/test/cli.test.ts @@ -50,7 +50,7 @@ function fakeTarget(): typeof fetch { if (url.pathname.startsWith("/xrpc/com.atproto.space.getLatestCommit")) { return Response.json({ error: "InvalidRequest" }, { status: 400 }); } - if (url.pathname === "/xrpc/com.atproto.space.getSpaceCredential") { + if (url.pathname === "/xrpc/com.atproto.space.authorizeSpaceSync") { return Response.json({ error: "SpaceNotFound" }, { status: 400 }); } // Everything else (space reads) is unauthenticated. diff --git a/packages/space-conformance/test/core.test.ts b/packages/space-conformance/test/core.test.ts index dad4c80..e0feba4 100644 --- a/packages/space-conformance/test/core.test.ts +++ b/packages/space-conformance/test/core.test.ts @@ -229,19 +229,19 @@ describe("coverage", () => { // Methods expect(refs).toContain("com.atproto.space.getRecord"); expect(refs).toContain("com.atproto.space.createSpace"); - expect(refs).toContain("com.atproto.memberspace.putMember"); - expect(refs).toContain("com.atproto.managedspace.checkUserAccess"); + expect(refs).toContain("com.atproto.memberspace.putMembers"); + expect(refs).toContain("com.atproto.managedspace.checkAccess"); // Declared errors, exactly as named expect(refs).toContain( - "com.atproto.space.getSpaceCredential@error:UserNotAuthorized", + "com.atproto.space.authorizeSpaceSync@error:AccountNotAuthorized", ); expect(refs).toContain( - "com.atproto.space.getSpaceCredential@error:SpaceDeleted", + "com.atproto.space.authorizeSpaceSync@error:RegistrationNotConfirmed", ); expect(refs).toContain( "com.atproto.space.createSpace@error:UnsupportedPolicy", ); - expect(refs).toContain("com.atproto.space.getRecord@error:BadSpaceMac"); + expect(refs).toContain("com.atproto.space.getRecord@error:InvalidSpaceMac"); // defs, records and policy objects are not methods and contribute nothing for (const notMethod of [ "com.atproto.space.defs", @@ -321,7 +321,7 @@ describe("coverage", () => { ]); // Everything not cited is a gap — e.g. listRepos is uncovered here. expect(report.gaps.map((g) => g.ref)).toContain( - "com.atproto.space.listRepos", + "com.atproto.space.listWriters", ); }); @@ -333,8 +333,18 @@ describe("coverage", () => { /^com\.atproto\.(space|memberspace|personalspace|managedspace)\./, ); } - // simplespace is gone in this alpha. - expect(lexicons.some((d) => d.id.includes("simplespace"))).toBe(false); + // Renamed or removed in this alpha. + for (const gone of [ + "simplespace", + "getSpaceCredential", + "registerNotify", + "notifyWrite", + "listRepos", + ]) { + expect( + lexicons.some((d) => d.id.endsWith(gone) || d.id.includes(`.${gone}.`)), + ).toBe(false); + } }); it("excuses exempted requirements and reports stale exemptions", () => { diff --git a/packages/space-conformance/test/full.test.ts b/packages/space-conformance/test/full.test.ts index 2d27861..b05430b 100644 --- a/packages/space-conformance/test/full.test.ts +++ b/packages/space-conformance/test/full.test.ts @@ -9,12 +9,12 @@ import { multibaseToBytes, } from "@atproto/crypto"; import { - COMMIT_MAC_TYPE as REF_COMMIT_MAC_TYPE, - RECORD_MAC_TYPE as REF_RECORD_MAC_TYPE, + COMMIT_MAC_PROFILE as REF_COMMIT_MAC_PROFILE, + RECORD_MAC_PROFILE as REF_RECORD_MAC_PROFILE, + createSpaceSigHeaders, decapsulate, - formatMacHeader, - formatWantMacHeader as refFormatWantMacHeader, - parseWantMacHeader, + formatMacRequest as refFormatMacRequest, + parseMacRequest, verifyCredentialSig, } from "@atproto/space"; import { parseCid } from "@atproto/lex-data"; @@ -24,6 +24,7 @@ import { cryptoCheckDescriptors, filterCatalog, knownChangesets, + knownProposalAnchors, operatorChecks, baseChecks, } from "../src/index"; @@ -34,15 +35,15 @@ import { fullCatalog, } from "../src/full"; import { - COMMIT_MAC_TYPE, - RECORD_MAC_TYPE, + COMMIT_MAC_PROFILE, + RECORD_MAC_PROFILE, compressP256, decompressP256, encapsulate, - formatWantMacHeader, - parseMacHeader, + formatMacRequest, spaceSigHeaders, } from "../src/space-auth"; +import { createSyncerInbox } from "../src/inbox"; import { verificationMethodDidKey, didDocumentUrl } from "../src/did"; import { isTid, rawCid, tidAt, tidNow, fromBase58 } from "../src/encoding"; @@ -64,6 +65,7 @@ describe("full catalog", () => { const report = coverageReport(fullCatalog); expect(report.danglingCitations).toEqual([]); const changesets = new Set(knownChangesets); + const anchors = new Set(knownProposalAnchors); for (const check of fullCatalog) { for (const c of check.citations) { if (c.source === "changeset") { @@ -71,6 +73,13 @@ describe("full catalog", () => { true, ); } + if (c.source === "proposal") { + expect(c.ref, `${check.id} cites ${c.ref}`).toMatch(/^0016#/); + expect( + anchors.has(c.ref.slice(5)), + `${check.id} cites ${c.ref}`, + ).toBe(true); + } } } }); @@ -82,7 +91,9 @@ describe("full catalog", () => { // Exemptions are the moderation-state errors only; anything else // uncovered is a gap, not an exemption. for (const { ref, reason } of report.exempt) { - expect(ref).toMatch(/@error:Repo(Takendown|Suspended|Deactivated)$/); + expect(ref).toMatch( + /@error:(Repo(Takendown|Suspended|Deactivated)|InvalidCursor)$|^com\.atproto\.space\.(getRecord|listRecords|getLatestCommit|listRepoOps|getRepo|listBlobs|getBlob)@error:SpaceNotFound$/, + ); expect(reason.length).toBeGreaterThan(20); } }); @@ -237,39 +248,58 @@ describe("browser-safe space auth matches @atproto/space", () => { it("encapsulate derives the secret the repo host decapsulates", async () => { const kem = await P256Keypair.create(); const { keyShare, sharedSecret } = await encapsulate(kem.did()); - expect(decapsulate(kem, keyShare)).toEqual(sharedSecret); + expect(decapsulate(kem, keyShare as never)).toEqual(sharedSecret); }); - it("formats Want-Mac headers the reference parses, byte for byte", async () => { + it("formats MAC requests exactly as the reference does, and it parses them", async () => { const share = (await P256Keypair.create()).did(); for (const [ours, theirs] of [ - [COMMIT_MAC_TYPE, REF_COMMIT_MAC_TYPE], - [RECORD_MAC_TYPE, REF_RECORD_MAC_TYPE], + [COMMIT_MAC_PROFILE, REF_COMMIT_MAC_PROFILE], + [RECORD_MAC_PROFILE, REF_RECORD_MAC_PROFILE], ] as const) { - expect(formatWantMacHeader(ours, share)).toBe( - refFormatWantMacHeader(theirs, share), - ); - expect(parseWantMacHeader(formatWantMacHeader(ours, share), theirs)).toBe( - share, + expect(formatMacRequest(ours, share)).toBe( + refFormatMacRequest(theirs, share as never), ); + expect( + parseMacRequest(formatMacRequest(ours, share, { label: "x" }), theirs), + ).toMatchObject({ + label: "x", + keyShare: share, + }); } }); - it("parses the reference's Atproto-Space-Mac header", () => { - const mac = crypto.getRandomValues(new Uint8Array(32)); - expect( - parseMacHeader( - formatMacHeader(REF_COMMIT_MAC_TYPE, mac), - COMMIT_MAC_TYPE, - ), - ).toEqual(mac); - // Wrong type is refused rather than misread. - expect( - parseMacHeader( - formatMacHeader(REF_RECORD_MAC_TYPE, mac), - COMMIT_MAC_TYPE, - ), - ).toBeUndefined(); + it("signs credential requests exactly as the reference does", async () => { + // ECDSA is randomised, so compare the signature input, and check the + // reference verifies a variant with a custom label and extra + // parameters (hosts find the signature by tag). + const ours = await createCredentialKey(); + const ref = await P256Keypair.create(); + const opts = { + authorization: "Atproto-Space-Credential a.b.c", + audience: "did:plc:abcdefghijklmnopqrstuvwx", + }; + const { headers } = await createSpaceSigHeaders({ + ...opts, + audience: opts.audience as never, + keypair: ref, + }); + const mine = await spaceSigHeaders({ sign: (b) => ref.sign(b) }, opts); + expect(mine["signature-input"]).toBe(headers["signature-input"]); + await expect( + verifyCredentialSig(mine, ref.did() as never), + ).resolves.toBeUndefined(); + const variant = await spaceSigHeaders(ours, { + ...opts, + label: "x7", + params: [ + ["created", 1], + ["keyid", ours.did], + ], + }); + await expect( + verifyCredentialSig(variant, ours.did as never), + ).resolves.toBeUndefined(); }); it("compresses and decompresses P-256 points like @atproto/crypto", async () => { @@ -313,6 +343,59 @@ describe("browser-safe space auth matches @atproto/space", () => { }); }); +describe("syncer inbox", () => { + it("confirms and accepts only tokens it issued for the space", async () => { + const { inbox, handle, deliveries } = createSyncerInbox({ + endpoint: "https://inbox.test", + service: "did:web:inbox.test#atproto_pds", + }); + const space = + "at://did:plc:abcdefghijklmnopqrstuvwx/space/earth.cirrus.check.space/x"; + const token = inbox.issueToken(space); + const post = (lxm: string, body: unknown) => + handle( + new Request(`https://inbox.test/xrpc/${lxm}`, { + method: "POST", + body: JSON.stringify(body), + }), + ); + const ok = await post("com.atproto.space.confirmRegistration", { + space, + token, + challenge: "c1", + }); + expect(await ok.json()).toEqual({ challenge: "c1" }); + const wrongSpace = await post("com.atproto.space.confirmRegistration", { + space: `${space}y`, + token, + challenge: "c2", + }); + expect(wrongSpace.status).toBe(400); + const unknown = await post("com.atproto.space.notifySpaceUpdate", { + space, + token: "nope", + update: {}, + }); + expect(unknown.status).toBe(400); + inbox.respond("com.atproto.managedspace.checkAccess", () => ({ + read: true, + write: false, + })); + const answer = await handle( + new Request( + `https://inbox.test/xrpc/com.atproto.managedspace.checkAccess?space=${encodeURIComponent(space)}`, + ), + ); + expect(await answer.json()).toEqual({ read: true, write: false }); + expect(deliveries().map((d) => d.status)).toEqual([200, 400, 400, 200]); + const seen = await inbox.waitFor( + (d) => d.lxm === "com.atproto.managedspace.checkAccess", + 10, + ); + expect(seen?.params?.space).toBe(space); + }); +}); + describe("encoding helpers", () => { it("mints TIDs that sort by time", () => { const now = tidNow(); diff --git a/plans/in-progress/spaces.md b/plans/in-progress/spaces.md index 8005a19..b4ffa34 100644 --- a/plans/in-progress/spaces.md +++ b/plans/in-progress/spaces.md @@ -191,7 +191,26 @@ private address space, so that covers the same ground. ### Conformance at 1112 -_Pending the suite port._ +106 checks (95 must, 10 should, 1 info); coverage 91 of 127 lexicon +requirements, zero gaps, 36 exempt. Results on 2026-11-13: + +- **Reference (matrix):** 103 pass, 2 pinned divergences + (`writes.delete-in-missing-space`, `credential.garbage-attestation-refused`, + both unchanged since 1105), and the slow `notify.registration-expired` + skipped in CI. Run by hand, the reference passes it too. + `space.reads-after-delete-not-found` is gone: 1112 dropped its citation. +- **Cirrus space routes (in-process):** every runnable must and should + check passes. Skips: the `pds-blobs` / `pds-delegation` checks (the PDS + run covers them) and the slow check. +- **Cirrus PDS (integrated worker):** passes, self-flow credential + round-trip included. +- Found one Cirrus bug, fixed: `listMembers` accepted a cursor that isn't + a DID instead of answering `InvalidCursor`. +- The syncer inbox is now `createSyncerInbox()` from the suite: it answers + `confirmRegistration` only for tokens it issued for that space, so + Cirrus's runner no longer hand-rolls one. +- The probe space declaration (`earth.cirrus.check.space`) uses `title` + and needs republishing (loop in `probe-lexicons/README.md`). ## Alpha sync process From ed4b4b233325b28f8ab2a78d685a324f54daed70 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 04:58:02 +0000 Subject: [PATCH 14/16] pds: give the conformance run room beyond the default test timeout Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LZ7qcQNQoiA6a23woGC7tB --- packages/pds/test/conformance.test.ts | 116 ++++++++++++++------------ 1 file changed, 62 insertions(+), 54 deletions(-) diff --git a/packages/pds/test/conformance.test.ts b/packages/pds/test/conformance.test.ts index 0ad597e..a14ce7e 100644 --- a/packages/pds/test/conformance.test.ts +++ b/packages/pds/test/conformance.test.ts @@ -22,64 +22,72 @@ import { fullCatalog } from "@getcirrus/space-conformance/full"; import { env, worker } from "./helpers"; describe("conformance suite vs the integrated PDS", () => { - it("passes the operator-tier and discovery checks, blobs included", async () => { - const fetchAdapter: typeof fetch = (input, init) => - worker.fetch(new Request(input as RequestInfo, init), env); + it( + "passes the operator-tier and discovery checks, blobs included", + { + // The catalogue runs ~10s alone; leave room for a loaded machine. + timeout: 60_000, + }, + async () => { + const fetchAdapter: typeof fetch = (input, init) => + worker.fetch(new Request(input as RequestInfo, init), env); - const catalog = filterCatalog(fullCatalog, { - // A full PDS: operator session, the public blob endpoints, and its - // own getDelegationToken — so the operator can mint a credential for - // its own space (the bulletin self-flow) without a foreign identity. - capabilities: ["operator", "pds-blobs", "pds-delegation", "alpha-libs"], - destructive: true, - }); - const report = await runChecks({ - catalog, - context: { - target: { - origin: `https://${env.PDS_HOSTNAME}`, - did: env.DID, - implementation: "cirrus-pds", - }, - fetch: fetchAdapter, - operator: { - oauth: false, - async authorize(reqInit) { - reqInit.headers.set("Authorization", `Bearer ${env.AUTH_TOKEN}`); + const catalog = filterCatalog(fullCatalog, { + // A full PDS: operator session, the public blob endpoints, and its + // own getDelegationToken — so the operator can mint a credential for + // its own space (the bulletin self-flow) without a foreign identity. + capabilities: ["operator", "pds-blobs", "pds-delegation", "alpha-libs"], + destructive: true, + }); + const report = await runChecks({ + catalog, + context: { + target: { + origin: `https://${env.PDS_HOSTNAME}`, + did: env.DID, + implementation: "cirrus-pds", + }, + fetch: fetchAdapter, + operator: { + oauth: false, + async authorize(reqInit) { + reqInit.headers.set("Authorization", `Bearer ${env.AUTH_TOKEN}`); + }, }, }, - }, - suiteVersion: "in-process", - alphaBuild: ALPHA_BUILD, - }); + suiteVersion: "in-process", + alphaBuild: ALPHA_BUILD, + }); - const failures = report.results.filter( - (r) => (r.status === "fail" || r.status === "error") && r.tier !== "info", - ); - if (failures.length > 0) { - throw new Error( - `conformance failures:\n${failures - .map((f) => ` [${f.tier}] ${f.id}: ${f.status} — ${f.detail}`) - .join("\n")}`, + const failures = report.results.filter( + (r) => + (r.status === "fail" || r.status === "error") && r.tier !== "info", ); - } + if (failures.length > 0) { + throw new Error( + `conformance failures:\n${failures + .map((f) => ` [${f.tier}] ${f.id}: ${f.status} — ${f.detail}`) + .join("\n")}`, + ); + } - const byId = Object.fromEntries( - report.results.map((r) => [r.id, r.status]), - ); - // Discovery (including the published #atproto_kem) and blob - // isolation ran against the real worker. - expect(byId["discovery.pds-service"]).toBe("pass"); - expect(byId["discovery.kem-key"]).toBe("pass"); - expect(byId["blobs.space-blob-not-public"]).toBe("pass"); - expect(byId["writes.create-and-read"]).toBe("pass"); - expect(byId["sync.getrepo-star"]).toBe("pass"); - // The self-flow credential round-trip runs end-to-end: the worker mints - // its own delegation token, exchanges it for a credential bound to a - // P-256 key, and serves the signed, MAC'd read. This is the - // interop-critical path the reference matrix also exercises. - expect(byId["credential.self-round-trip"]).toBe("pass"); - // Identity-requiring checks skip here (no foreign resolution). - expect(byId["credential.member-gate"]).toBe("skipped"); - }); + const byId = Object.fromEntries( + report.results.map((r) => [r.id, r.status]), + ); + // Discovery (including the published #atproto_kem) and blob + // isolation ran against the real worker. + expect(byId["discovery.pds-service"]).toBe("pass"); + expect(byId["discovery.kem-key"]).toBe("pass"); + expect(byId["blobs.space-blob-not-public"]).toBe("pass"); + expect(byId["writes.create-and-read"]).toBe("pass"); + expect(byId["sync.getrepo-star"]).toBe("pass"); + // The self-flow credential round-trip runs end-to-end: the worker mints + // its own delegation token, exchanges it for a credential bound to a + // P-256 key, and serves the signed, MAC'd read. This is the + // interop-critical path the reference matrix also exercises. + expect(byId["credential.self-round-trip"]).toBe("pass"); + // Identity-requiring checks skip here (no foreign resolution). + expect(byId["credential.member-gate"]).toBe("skipped"); + }, + ); }); From 44e3da6a6da70592cb966dbbba7d3689b5575892 Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 04:59:41 +0000 Subject: [PATCH 15/16] plans: record the slow registration-expired run against Cirrus Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LZ7qcQNQoiA6a23woGC7tB --- plans/in-progress/spaces.md | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/plans/in-progress/spaces.md b/plans/in-progress/spaces.md index b4ffa34..496cc32 100644 --- a/plans/in-progress/spaces.md +++ b/plans/in-progress/spaces.md @@ -201,7 +201,8 @@ requirements, zero gaps, 36 exempt. Results on 2026-11-13: `space.reads-after-delete-not-found` is gone: 1112 dropped its citation. - **Cirrus space routes (in-process):** every runnable must and should check passes. Skips: the `pds-blobs` / `pds-delegation` checks (the PDS - run covers them) and the slow check. + run covers them) and the slow check, which passes when run by hand + (607s, waiting out the credential). - **Cirrus PDS (integrated worker):** passes, self-flow credential round-trip included. - Found one Cirrus bug, fixed: `listMembers` accepted a cursor that isn't From 9452fe4924065e9fb6a5471a2fe6100b5f277e3f Mon Sep 17 00:00:00 2001 From: Claude Date: Fri, 13 Nov 2026 06:38:21 +0000 Subject: [PATCH 16/16] ci: pin publish and release workflows to Node LTS node-version: latest now resolves to a Node 27 alpha, which better-sqlite3 can't compile against, so the PR preview publish fails at install. Match claude.yml's lts/*. Co-Authored-By: Claude Opus 5.5 Claude-Session: https://claude.ai/code/session_01LZ7qcQNQoiA6a23woGC7tB --- .github/workflows/pkg-pr-new.yml | 2 +- .github/workflows/release.yml | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/.github/workflows/pkg-pr-new.yml b/.github/workflows/pkg-pr-new.yml index 1b4625a..07db69b 100644 --- a/.github/workflows/pkg-pr-new.yml +++ b/.github/workflows/pkg-pr-new.yml @@ -19,7 +19,7 @@ jobs: - name: Setup Node uses: actions/setup-node@v6 with: - node-version: latest + node-version: "lts/*" cache: "pnpm" - name: Install dependencies diff --git a/.github/workflows/release.yml b/.github/workflows/release.yml index c1af27d..b75b186 100644 --- a/.github/workflows/release.yml +++ b/.github/workflows/release.yml @@ -34,7 +34,7 @@ jobs: - name: Setup Node uses: actions/setup-node@v6 with: - node-version: latest + node-version: "lts/*" cache: "pnpm" - name: Install Dependencies