@getcirrus/space-conformance 0.1.0 → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,852 @@
1
+ import { $ as toBase64, A as spaceUri, C as operatorCreateRecord, D as requestCredential, E as publicRead, I as verificationMethodDidKey, J as decodeJwt, L as COMMIT_MAC_PROFILE, O as spaceAuthority, P as resolveDidDocument, Q as tidNow, S as obtainPublicCredential, T as probeSkey, V as createCredentialKey, W as formatMacRequest, X as lexBytes, Y as isTid, Z as tidAt, _ as describe, a as operatorChecks, at as xrpcGet, b as mustCreateRecord, c as fakeDid, d as FOREIGN_DID, et as toBase64Url, f as POST, ft as fail, g as deleteProbeSpace, h as credentialGet, j as unknownSpaceUri, k as spaceRecordUri, l as putMembers, lt as buildCatalog, m as credentialCall, n as descriptor, nt as asOperator, o as listWriters, ot as xrpcPost, p as createProbeSpace, pt as pass, q as bytesEqual, rt as operatorFetch, s as ACCOUNT_REFUSALS, st as xrpcPostBytes, tt as utf8, u as baseChecks, ut as defineCheck, v as managedspace, w as personalspace, y as memberspace } from "./descriptors-BUCV_BuG.js";
2
+ import { RepoCommit, createDelegationToken, createSpaceCredential, readRepoStar, readSpaceMetaStar, spaceHostAud, verifyCommit, verifyRecord, verifyRepoStarFull, verifySpaceToken, writeRepoStar, writeSpaceMetaStar } from "@atproto/space";
3
+ import { parseCid } from "@atproto/lex-data";
4
+ import { Secp256k1Keypair } from "@atproto/crypto";
5
+
6
+ //#region src/full/helpers.ts
7
+ /**
8
+ * Crypto-bound helpers: tokens minted as harness-held identities
9
+ * (delegation tokens as a reader, credentials as a foreign authority,
10
+ * service auth as a writer's PDS) and the reference library's verifiers
11
+ * for the MACs, commits and archives a target serves.
12
+ *
13
+ * Using the reference library to mint and verify is deliberate: "correctly
14
+ * formed" is defined by the library every implementation must interoperate
15
+ * with, so a token it mints is one the target must accept, and an artefact
16
+ * it rejects is one no other implementation could consume.
17
+ */
18
+ /** Adapt a harness identity to the `Signer` surface token minting uses. */
19
+ function keypairFor(identity) {
20
+ return {
21
+ jwtAlg: identity.jwtAlg,
22
+ sign: (bytes) => identity.sign(bytes),
23
+ did: () => identity.did
24
+ };
25
+ }
26
+ /**
27
+ * Mint a delegation token for `identity` against `space`, addressed (by
28
+ * default) to the space authority's `#atproto_pds` — the space host.
29
+ */
30
+ function mintDelegation(identity, space, audOverride) {
31
+ return createDelegationToken({
32
+ iss: identity.did,
33
+ sub: space,
34
+ aud: audOverride ?? spaceHostAud(spaceAuthority(space)),
35
+ keypair: keypairFor(identity)
36
+ });
37
+ }
38
+ /**
39
+ * The full obtain flow as a foreign user: mint a delegation token as
40
+ * `identity` and exchange it for a credential bound to a fresh P-256 key.
41
+ * Returns the raw result so callers can assert on refusals.
42
+ */
43
+ async function obtainCredential(ctx, identity, space, opts = {}) {
44
+ return requestCredential(ctx, space, {
45
+ delegationToken: await mintDelegation(identity, space, opts.audOverride),
46
+ ...opts.clientAttestation ? { clientAttestation: opts.clientAttestation } : {}
47
+ });
48
+ }
49
+ /**
50
+ * Mint a credential as the authority of `space` — a harness identity
51
+ * playing a foreign space authority whose credentials a repo host must
52
+ * honour for reads of its repos in that space.
53
+ */
54
+ function mintCredential(authority, space, keyDid) {
55
+ return createSpaceCredential({
56
+ iss: authority.did,
57
+ sub: space,
58
+ keyId: keyDid,
59
+ keypair: keypairFor(authority)
60
+ });
61
+ }
62
+ /** An inter-service auth JWT (`lxm`-scoped), signed as `identity`. */
63
+ async function serviceJwt(identity, opts) {
64
+ const iat = Math.floor(Date.now() / 1e3);
65
+ const header = {
66
+ typ: "JWT",
67
+ alg: identity.jwtAlg
68
+ };
69
+ const payload = {
70
+ iss: identity.did,
71
+ aud: opts.aud,
72
+ iat,
73
+ exp: iat + (opts.expiresInSec ?? 60),
74
+ lxm: opts.lxm,
75
+ jti: toBase64Url(crypto.getRandomValues(new Uint8Array(16)))
76
+ };
77
+ const input = `${toBase64Url(utf8(JSON.stringify(header)))}.${toBase64Url(utf8(JSON.stringify(payload)))}`;
78
+ return `${input}.${toBase64Url(await identity.sign(utf8(input)))}`;
79
+ }
80
+ /** A commit as the wire JSON carries it, with `data` decoded. */
81
+ function commitFromJson(value) {
82
+ if (!value || typeof value !== "object") return void 0;
83
+ const raw = value;
84
+ const data = lexBytes(raw.data);
85
+ if (!data) return void 0;
86
+ return {
87
+ ...raw,
88
+ data
89
+ };
90
+ }
91
+ /** What `verifyCommit` / `verifyRecord` / `verifyRepoStar` need from a MAC'd response. */
92
+ function macParams(res) {
93
+ if (!res.keyShare || !res.sharedSecret) throw new Error("the response was not requested with a MAC");
94
+ return {
95
+ keyShare: res.keyShare,
96
+ sharedSecret: res.sharedSecret,
97
+ headers: res.headers
98
+ };
99
+ }
100
+ /** Drain an async byte stream (an archive serializer) into one buffer. */
101
+ async function collectBytes(chunks) {
102
+ const parts = [];
103
+ for await (const chunk of chunks) parts.push(chunk);
104
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
105
+ let offset = 0;
106
+ for (const part of parts) {
107
+ out.set(part, offset);
108
+ offset += part.length;
109
+ }
110
+ return out;
111
+ }
112
+
113
+ //#endregion
114
+ //#region src/full/checks.ts
115
+ /**
116
+ * The crypto-bound check catalog: the checks that genuinely need the
117
+ * alpha libs or harness-held foreign identities, and nothing else — every
118
+ * check an operator session can run with plain fetch + WebCrypto lives in
119
+ * `../checks/` instead, browser included.
120
+ *
121
+ * What keeps a check here:
122
+ * - verifying what a target serves — commit and record MACs, STAR
123
+ * archives, token signatures — with the reference library;
124
+ * - building archives (space meta, repo STARs) to import;
125
+ * - `identities`: the harness plays a reader, a writer's PDS or a foreign
126
+ * space authority, minting tokens the target must verify by resolving
127
+ * that party's DID.
128
+ *
129
+ * Each check's metadata comes from `../descriptors.ts`, the dependency-free
130
+ * list the browser catalog shows as "not testable here".
131
+ */
132
+ const crypto$ = (id, run) => defineCheck({
133
+ ...descriptor(id),
134
+ run
135
+ });
136
+ const errMsg = (err) => err instanceof Error ? err.message : String(err);
137
+ /**
138
+ * A public-read space with two records and a credential for it. `fn` gets
139
+ * the space-ref in the form the protocol fixes (`at:space/{did}/{type}/{skey}`),
140
+ * built here rather than echoed from createSpace, so the MAC checks verify
141
+ * the commit's and record's URIs against it, not against whatever the host
142
+ * emitted.
143
+ */
144
+ async function withPublicSpace(ctx, fn) {
145
+ const space = await createProbeSpace(ctx, publicRead());
146
+ try {
147
+ const ref = spaceUri(ctx.target.did, space.skey);
148
+ await mustCreateRecord(ctx, ref, "a", "one");
149
+ await mustCreateRecord(ctx, ref, "b", "two");
150
+ return await fn(ref, await obtainPublicCredential(ctx, ref));
151
+ } finally {
152
+ await deleteProbeSpace(ctx, space.uri);
153
+ }
154
+ }
155
+ const macCommit = crypto$("mac.commit-verifies", (ctx) => withPublicSpace(ctx, async (space, credential) => {
156
+ const res = await credentialCall(ctx, credential, "com.atproto.space.getLatestCommit", {
157
+ params: {
158
+ space,
159
+ repo: ctx.target.did
160
+ },
161
+ mac: {
162
+ profile: COMMIT_MAC_PROFILE,
163
+ header: (k) => `${formatMacRequest(COMMIT_MAC_PROFILE, k, { label: "m1" })}, other=("content-digest");tag="someone-elses"`
164
+ }
165
+ });
166
+ if (res.status !== 200) return fail(`getLatestCommit ${describe(res)}`, res.json);
167
+ const raw = res.json.commit ?? {};
168
+ const keys = Object.keys(raw).sort().join(",");
169
+ if (keys !== "data,repo,rev,space,ver") return fail(`commit carries {${keys}}, expected exactly {data,repo,rev,space,ver}`, raw);
170
+ const commit = commitFromJson(raw);
171
+ 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);
172
+ const input = res.headers.get("signature-input") ?? "";
173
+ if (!/^m1=/.test(input)) return fail(`MAC not under the requested label: ${input}`);
174
+ const vary = (res.headers.get("vary") ?? "").toLowerCase();
175
+ if (!vary.split(",").map((v) => v.trim()).includes("accept-signature")) return fail(`Vary does not list Accept-Signature: ${vary}`);
176
+ try {
177
+ verifyCommit(commit, {
178
+ space,
179
+ repo: ctx.target.did,
180
+ ...macParams(res)
181
+ });
182
+ return pass("commit shape as specified; commit and MAC name the at:space/ ref; MAC verifies under the requested label; Vary lists Accept-Signature");
183
+ } catch (err) {
184
+ return fail(`verifyCommit rejected the response: ${errMsg(err)}`, raw);
185
+ }
186
+ }));
187
+ const macRecord = crypto$("mac.record-verifies", (ctx) => withPublicSpace(ctx, async (space, credential) => {
188
+ const res = await credentialGet(ctx, credential, "com.atproto.space.getRecord", {
189
+ space,
190
+ repo: ctx.target.did,
191
+ collection: POST,
192
+ rkey: "a"
193
+ });
194
+ if (res.status !== 200) return fail(`getRecord ${describe(res)}`, res.json);
195
+ const record = res.json;
196
+ const uri = spaceRecordUri(space, ctx.target.did, POST, "a");
197
+ if (record.uri !== uri) return fail(`getRecord uri was ${record.uri}, expected ${uri}`, record);
198
+ try {
199
+ await verifyRecord(record, {
200
+ uri,
201
+ ...macParams(res)
202
+ });
203
+ return pass("record uri is the at:space/ form; MAC verifies over that uri and the cid; value encodes to cid");
204
+ } catch (err) {
205
+ return fail(`verifyRecord rejected the response: ${errMsg(err)}`, record);
206
+ }
207
+ }));
208
+ const oplogFolds = crypto$("sync.oplog-folds-to-commit", (ctx) => withPublicSpace(ctx, async (space, credential) => {
209
+ await xrpcPost(asOperator(ctx), "com.atproto.space.putRecord", {
210
+ space,
211
+ repo: ctx.target.did,
212
+ collection: POST,
213
+ rkey: "a",
214
+ record: {
215
+ $type: POST,
216
+ text: "one, again"
217
+ }
218
+ });
219
+ const folded = new RepoCommit();
220
+ let cursor;
221
+ let pages = 0;
222
+ let last;
223
+ for (; pages < 20; pages++) {
224
+ const res = await credentialGet(ctx, credential, "com.atproto.space.listRepoOps", {
225
+ space,
226
+ repo: ctx.target.did,
227
+ limit: "1",
228
+ cursor
229
+ });
230
+ if (res.status !== 200) return fail(`listRepoOps page ${pages + 1}: ${describe(res)}`, res.json);
231
+ const body = res.json;
232
+ last = commitFromJson(body.commit);
233
+ if (!last) return fail(`page ${pages + 1} carried no commit`, body);
234
+ try {
235
+ verifyCommit(last, {
236
+ space,
237
+ repo: ctx.target.did,
238
+ ...macParams(res)
239
+ });
240
+ } catch (err) {
241
+ return fail(`page ${pages + 1}'s commit MAC does not verify: ${errMsg(err)}`);
242
+ }
243
+ folded.applyOps(body.ops.map((op) => ({
244
+ collection: op.collection,
245
+ rkey: op.rkey,
246
+ cid: op.cid ? parseCid(op.cid) : null,
247
+ prev: op.prev ? parseCid(op.prev) : null
248
+ })));
249
+ cursor = body.cursor;
250
+ if (!cursor) break;
251
+ }
252
+ if (pages < 2) return fail("three ops at limit=1 did not paginate");
253
+ 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");
254
+ }));
255
+ const getRepoStar = crypto$("sync.getrepo-star", (ctx) => withPublicSpace(ctx, async (space, credential) => {
256
+ const res = await credentialGet(ctx, credential, "com.atproto.space.getRepo", {
257
+ space,
258
+ repo: ctx.target.did
259
+ });
260
+ if (res.status !== 200) return fail(`getRepo ${describe(res)}`, res.json);
261
+ const type = res.headers.get("Content-Type") ?? "";
262
+ if (!type.includes("application/vnd.dasl.star")) return fail(`getRepo content-type was ${type}`);
263
+ const bytes = new Uint8Array(await res.response.arrayBuffer());
264
+ try {
265
+ const { records } = await verifyRepoStarFull([bytes], {
266
+ space,
267
+ repo: ctx.target.did,
268
+ ...macParams(res)
269
+ });
270
+ const rkeys = records.map((r) => `${r.collection}/${r.rkey}`).sort();
271
+ 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"}`);
272
+ } catch (err) {
273
+ return fail(`verifyRepoStarFull rejected the archive: ${errMsg(err)}`);
274
+ }
275
+ }));
276
+ async function atprotoKey(ctx, did) {
277
+ const key = verificationMethodDidKey(await resolveDidDocument(ctx, did), "atproto");
278
+ if (!key) throw new Error(`${did} publishes no #atproto key`);
279
+ return key;
280
+ }
281
+ const credentialSigned = crypto$("credential.signed-by-authority", async (ctx) => {
282
+ const space = await createProbeSpace(ctx, publicRead());
283
+ try {
284
+ const credential = await obtainPublicCredential(ctx, space.uri);
285
+ try {
286
+ await verifySpaceToken("credential", credential.credential, {
287
+ getSigningKey: (iss) => atprotoKey(ctx, iss),
288
+ sub: space.uri
289
+ });
290
+ return pass("verifies against the authority's #atproto key");
291
+ } catch (err) {
292
+ return fail(`credential did not verify: ${errMsg(err)}`);
293
+ }
294
+ } finally {
295
+ await deleteProbeSpace(ctx, space.uri);
296
+ }
297
+ });
298
+ const delegationSigned = crypto$("delegation.signed-by-user", async (ctx) => {
299
+ const space = await createProbeSpace(ctx, memberspace());
300
+ try {
301
+ const res = await xrpcGet(asOperator(ctx), "com.atproto.space.getDelegationToken", { space: space.uri });
302
+ if (res.status !== 200) return fail(`getDelegationToken ${describe(res)}`, res.json);
303
+ try {
304
+ await verifySpaceToken("delegation", res.json.token, {
305
+ getSigningKey: (iss) => atprotoKey(ctx, iss),
306
+ aud: spaceHostAud(ctx.target.did),
307
+ sub: space.uri
308
+ });
309
+ return pass("verifies against the user's #atproto key");
310
+ } catch (err) {
311
+ return fail(`delegation token did not verify: ${errMsg(err)}`);
312
+ }
313
+ } finally {
314
+ await deleteProbeSpace(ctx, space.uri);
315
+ }
316
+ });
317
+ async function exportMeta(ctx, space) {
318
+ const res = await operatorFetch(ctx)(`${ctx.target.origin}/xrpc/com.atproto.space.exportSpaceMeta?space=${encodeURIComponent(space)}`);
319
+ if (res.status !== 200) throw new Error(`exportSpaceMeta ${res.status} ${await res.text().catch(() => "")}`);
320
+ return {
321
+ type: res.headers.get("Content-Type") ?? "",
322
+ archive: await readSpaceMetaStar([new Uint8Array(await res.arrayBuffer())])
323
+ };
324
+ }
325
+ const importMeta = async (ctx, archive) => xrpcPostBytes(asOperator(ctx), "com.atproto.space.importSpaceMeta", await collectBytes(writeSpaceMetaStar(archive)));
326
+ const memberKey = (did) => `com.atproto.memberspace.member/${did}`;
327
+ const exportSpaceMeta = crypto$("migration.export-space-meta", async (ctx) => {
328
+ const space = await createProbeSpace(ctx, memberspace({ publicWrite: true }));
329
+ const member = fakeDid();
330
+ try {
331
+ await putMembers(ctx, space.uri, [{
332
+ did: member,
333
+ read: true,
334
+ write: false
335
+ }]);
336
+ await mustCreateRecord(ctx, space.uri, "a");
337
+ const { type, archive } = await exportMeta(ctx, space.uri);
338
+ const problems = [];
339
+ if (!type.includes("application/vnd.dasl.star")) problems.push(`content-type ${type}`);
340
+ if (archive.space !== space.uri) problems.push(`space ${archive.space}`);
341
+ if (archive.policy.$type !== "com.atproto.memberspace.policy") problems.push(`policy ${String(archive.policy.$type)}`);
342
+ const entry = archive.policyState.find((e) => e.key === memberKey(member));
343
+ if (!entry || entry.value.read !== true || entry.value.write !== false) problems.push("member entry missing or wrong");
344
+ const writer = archive.writers.find((w) => w.did === ctx.target.did);
345
+ if (!writer || !isTid(writer.repoRev)) problems.push("the authority is not in the writer set with a repoRev");
346
+ if (problems.length) return fail(problems.join("; "), archive);
347
+ await xrpcPost(asOperator(ctx), "com.atproto.space.removeWriter", {
348
+ space: space.uri,
349
+ repo: ctx.target.did
350
+ });
351
+ return (await exportMeta(ctx, space.uri)).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");
352
+ } catch (err) {
353
+ return fail(errMsg(err));
354
+ } finally {
355
+ await deleteProbeSpace(ctx, space.uri);
356
+ }
357
+ });
358
+ const importSpaceMeta = crypto$("migration.import-space-meta", async (ctx) => {
359
+ const space = await createProbeSpace(ctx, memberspace());
360
+ const before = fakeDid();
361
+ const after = fakeDid();
362
+ try {
363
+ await putMembers(ctx, space.uri, [{
364
+ did: before,
365
+ read: true,
366
+ write: true
367
+ }]);
368
+ const { archive } = await exportMeta(ctx, space.uri);
369
+ const imported = await importMeta(ctx, {
370
+ ...archive,
371
+ policy: {
372
+ $type: "com.atproto.memberspace.policy",
373
+ publicRead: true
374
+ },
375
+ policyState: [{
376
+ key: memberKey(after),
377
+ value: {
378
+ $type: "com.atproto.memberspace.member",
379
+ read: true,
380
+ write: false
381
+ }
382
+ }]
383
+ });
384
+ if (imported.status !== 200) return fail(`importSpaceMeta ${describe(imported)}`, imported.json);
385
+ const got = await xrpcGet(asOperator(ctx), "com.atproto.space.getSpace", { space: space.uri });
386
+ const policy = got.json?.policy;
387
+ const list = await xrpcGet(asOperator(ctx), "com.atproto.memberspace.listMembers", { space: space.uri });
388
+ const dids = (list.json?.members ?? []).map((m) => m.did);
389
+ if (policy?.publicRead !== true) return fail("getSpace does not reflect the imported policy", got.json);
390
+ 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);
391
+ } catch (err) {
392
+ return fail(errMsg(err));
393
+ } finally {
394
+ await deleteProbeSpace(ctx, space.uri);
395
+ }
396
+ });
397
+ const importMetaNotAuthority = crypto$("migration.import-space-meta-not-authority", async (ctx) => {
398
+ const res = await importMeta(ctx, {
399
+ space: unknownSpaceUri(FOREIGN_DID),
400
+ policy: { $type: "com.atproto.personalspace.policy" },
401
+ policyState: [],
402
+ writers: []
403
+ });
404
+ return res.error === "NotAuthorized" ? pass("answered NotAuthorized") : fail(`answered ${describe(res)}, expected NotAuthorized`, res.json);
405
+ });
406
+ const importMetaUnsupported = crypto$("migration.import-space-meta-unsupported-policy", async (ctx) => {
407
+ const space = unknownSpaceUri(ctx.target.did);
408
+ const res = await importMeta(ctx, {
409
+ space,
410
+ policy: { $type: "com.example.mysteryPolicy" },
411
+ policyState: [],
412
+ writers: []
413
+ });
414
+ if (res.status === 200) await deleteProbeSpace(ctx, space);
415
+ return res.error === "UnsupportedPolicy" ? pass("answered UnsupportedPolicy") : fail(`answered ${describe(res)}, expected UnsupportedPolicy`, res.json);
416
+ });
417
+ const importMetaInvalid = crypto$("migration.import-space-meta-invalid", async (ctx) => {
418
+ const res = await xrpcPostBytes(asOperator(ctx), "com.atproto.space.importSpaceMeta", utf8("not a STAR archive"));
419
+ return res.error === "InvalidSpaceMeta" ? pass("answered InvalidSpaceMeta") : fail(`answered ${describe(res)}, expected InvalidSpaceMeta`, res.json);
420
+ });
421
+ async function ownRepoArchive(ctx, space) {
422
+ const res = await operatorFetch(ctx)(`${ctx.target.origin}/xrpc/com.atproto.space.getRepo?space=${encodeURIComponent(space)}&repo=${encodeURIComponent(ctx.target.did)}`);
423
+ if (res.status !== 200) throw new Error(`getRepo ${res.status}`);
424
+ return new Uint8Array(await res.arrayBuffer());
425
+ }
426
+ const importRepo = crypto$("migration.import-repo", async (ctx) => {
427
+ const space = await createProbeSpace(ctx, personalspace());
428
+ try {
429
+ await mustCreateRecord(ctx, space.uri, "a", "one");
430
+ await mustCreateRecord(ctx, space.uri, "b", "two");
431
+ const bytes = await ownRepoArchive(ctx, space.uri);
432
+ const exported = await readRepoStar([bytes]);
433
+ const commit = exported.commit;
434
+ await exported[Symbol.asyncDispose]();
435
+ await mustCreateRecord(ctx, space.uri, "c", "three");
436
+ if ((await xrpcPostBytes(asOperator(ctx), "com.atproto.space.importRepo", bytes, void 0, "application/octet-stream")).status === 200) return fail("importRepo accepted an application/octet-stream body");
437
+ const res = await xrpcPostBytes(asOperator(ctx), "com.atproto.space.importRepo", bytes);
438
+ if (res.status !== 200) return fail(`importRepo ${describe(res)}`, res.json);
439
+ const list = await xrpcGet(asOperator(ctx), "com.atproto.space.listRecords", {
440
+ space: space.uri,
441
+ repo: ctx.target.did
442
+ });
443
+ const rkeys = (list.json?.records ?? []).map((r) => r.rkey).sort();
444
+ if (rkeys.join(",") !== "a,b") return fail(`records after import: ${rkeys.join(",")}`, list.json);
445
+ const latest = await xrpcGet(asOperator(ctx), "com.atproto.space.getLatestCommit", {
446
+ space: space.uri,
447
+ repo: ctx.target.did
448
+ });
449
+ const now = commitFromJson(latest.json?.commit);
450
+ if (!now) return fail(`getLatestCommit after import ${describe(latest)}`, latest.json);
451
+ if (!bytesEqual(now.data, commit.data)) return fail("commit data changed across the import");
452
+ return now.rev > commit.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}`);
453
+ } catch (err) {
454
+ return fail(errMsg(err));
455
+ } finally {
456
+ await deleteProbeSpace(ctx, space.uri);
457
+ }
458
+ });
459
+ const emptyRepoArchive = (space, repo) => collectBytes(writeRepoStar(new RepoCommit().toCommit({
460
+ space,
461
+ repo,
462
+ rev: tidNow()
463
+ }), []));
464
+ const importRepoNotFound = crypto$("migration.import-repo-space-not-found", async (ctx) => {
465
+ const space = spaceUri(ctx.target.did, probeSkey());
466
+ const res = await xrpcPostBytes(asOperator(ctx), "com.atproto.space.importRepo", await emptyRepoArchive(space, ctx.target.did));
467
+ if (res.status === 200) await deleteProbeSpace(ctx, space);
468
+ return res.error === "SpaceNotFound" ? pass("answered SpaceNotFound") : fail(`answered ${describe(res)}, expected SpaceNotFound`, res.json);
469
+ });
470
+ const importRepoInvalid = crypto$("migration.import-repo-invalid", async (ctx) => {
471
+ const res = await xrpcPostBytes(asOperator(ctx), "com.atproto.space.importRepo", utf8("not a STAR archive"));
472
+ return res.error === "InvalidRepoFile" ? pass("answered InvalidRepoFile") : fail(`answered ${describe(res)}, expected InvalidRepoFile`, res.json);
473
+ });
474
+ const importRepoMismatch = crypto$("migration.import-repo-mismatch", async (ctx) => {
475
+ const space = await createProbeSpace(ctx, personalspace());
476
+ try {
477
+ const res = await xrpcPostBytes(asOperator(ctx), "com.atproto.space.importRepo", await emptyRepoArchive(space.uri, fakeDid()));
478
+ return res.error === "RepoMismatch" ? pass("answered RepoMismatch") : fail(`answered ${describe(res)}, expected RepoMismatch`, res.json);
479
+ } finally {
480
+ await deleteProbeSpace(ctx, space.uri);
481
+ }
482
+ });
483
+ const isAccountRefusal = (error) => error !== void 0 && ACCOUNT_REFUSALS.includes(error);
484
+ const memberGate = crypto$("credential.member-gate", async (ctx) => {
485
+ const reader = await ctx.identities.identity("reader");
486
+ const space = await createProbeSpace(ctx, memberspace());
487
+ const put = (read) => putMembers(ctx, space.uri, [{
488
+ did: reader.did,
489
+ read,
490
+ write: false
491
+ }]);
492
+ try {
493
+ await mustCreateRecord(ctx, space.uri, "shared", "members only");
494
+ const stranger = await obtainCredential(ctx, reader, space.uri);
495
+ if (stranger.credential) return fail("a non-member obtained a credential");
496
+ if (!isAccountRefusal(stranger.result.error)) return fail(`non-member refused with ${describe(stranger.result)}; expected ${ACCOUNT_REFUSALS.join(" / ")}`);
497
+ await put(false);
498
+ if ((await obtainCredential(ctx, reader, space.uri)).credential) return fail("a member with read: false obtained a credential");
499
+ await put(true);
500
+ const member = await obtainCredential(ctx, reader, space.uri);
501
+ if (!member.credential) return fail(`a reader was refused: ${describe(member.result)}`, member.result.json);
502
+ const read = await credentialGet(ctx, member.credential, "com.atproto.space.getRecord", {
503
+ space: space.uri,
504
+ repo: ctx.target.did,
505
+ collection: POST,
506
+ rkey: "shared"
507
+ });
508
+ 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);
509
+ } finally {
510
+ await deleteProbeSpace(ctx, space.uri);
511
+ }
512
+ });
513
+ const personalOnly = crypto$("policy.personalspace-owner-only", async (ctx) => {
514
+ const reader = await ctx.identities.identity("reader");
515
+ const space = await createProbeSpace(ctx, personalspace());
516
+ try {
517
+ const res = await obtainCredential(ctx, reader, space.uri);
518
+ if (res.credential) return fail("a personalspace issued a credential to another account");
519
+ return isAccountRefusal(res.result.error) ? pass(`refused another account with ${res.result.error} (the authority's admission is policy.personalspace-owner-admitted)`) : fail(`refused with ${describe(res.result)}; expected ${ACCOUNT_REFUSALS.join(" / ")}`);
520
+ } finally {
521
+ await deleteProbeSpace(ctx, space.uri);
522
+ }
523
+ });
524
+ const delegationWrongAud = crypto$("delegation.wrong-audience-refused", async (ctx) => {
525
+ const reader = await ctx.identities.identity("reader");
526
+ const space = await createProbeSpace(ctx, memberspace());
527
+ try {
528
+ await putMembers(ctx, space.uri, [{
529
+ did: reader.did,
530
+ read: true,
531
+ write: false
532
+ }]);
533
+ const control = await obtainCredential(ctx, reader, space.uri);
534
+ if (!control.credential) return fail(`correct-aud control failed (${describe(control.result)}); cannot attribute the wrong-aud refusal`);
535
+ const { result, credential } = await obtainCredential(ctx, reader, space.uri, { audOverride: `${FOREIGN_DID}#atproto_pds` });
536
+ if (credential) return fail("a token addressed to another host was accepted");
537
+ return result.error === "InvalidDelegationToken" ? pass("refused with InvalidDelegationToken") : fail(`refused with ${describe(result)}, expected InvalidDelegationToken`);
538
+ } finally {
539
+ await deleteProbeSpace(ctx, space.uri);
540
+ }
541
+ });
542
+ async function notifyRepoUpdate(ctx, writer, space, repoRev, data) {
543
+ const jwt = await serviceJwt(writer, {
544
+ aud: spaceHostAud(ctx.target.did),
545
+ lxm: "com.atproto.space.notifyRepoUpdate"
546
+ });
547
+ return xrpcPost(ctx, "com.atproto.space.notifyRepoUpdate", {
548
+ space,
549
+ repo: writer.did,
550
+ repoRev,
551
+ data: { $bytes: toBase64(data).replace(/=+$/, "") }
552
+ }, { Authorization: `Bearer ${jwt}` });
553
+ }
554
+ const notifyAccepted = crypto$("host.notifyrepoupdate-accepted", async (ctx) => {
555
+ const writer = await ctx.identities.identity("writer");
556
+ const space = await createProbeSpace(ctx, memberspace({ publicRead: true }));
557
+ try {
558
+ await putMembers(ctx, space.uri, [{
559
+ did: writer.did,
560
+ read: false,
561
+ write: true
562
+ }]);
563
+ const repoRev = tidNow();
564
+ const data = globalThis.crypto.getRandomValues(new Uint8Array(32));
565
+ const res = await notifyRepoUpdate(ctx, writer, space.uri, repoRev, data);
566
+ if (res.status !== 200) return fail(`notifyRepoUpdate ${describe(res)}`, res.json);
567
+ const { repos } = await listWriters(ctx, await obtainPublicCredential(ctx, space.uri));
568
+ const entry = repos.find((r) => r.repo === writer.did);
569
+ if (!entry) return fail("the notified writer is not in listWriters");
570
+ const listed = lexBytes(entry.data);
571
+ 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);
572
+ } finally {
573
+ await deleteProbeSpace(ctx, space.uri);
574
+ }
575
+ });
576
+ const notifyFuture = crypto$("host.notifyrepoupdate-future-rev", async (ctx) => {
577
+ const writer = await ctx.identities.identity("writer");
578
+ const space = await createProbeSpace(ctx, memberspace({ publicWrite: true }));
579
+ try {
580
+ const hourAhead = BigInt(Date.now() + 3600 * 1e3) * 1000n;
581
+ const res = await notifyRepoUpdate(ctx, writer, space.uri, tidAt(hourAhead), new Uint8Array(32));
582
+ return res.error === "FutureRev" ? pass("a repoRev an hour ahead answered FutureRev") : fail(`answered ${describe(res)}, expected FutureRev`, res.json);
583
+ } finally {
584
+ await deleteProbeSpace(ctx, space.uri);
585
+ }
586
+ });
587
+ const notifyUnknown = crypto$("host.notifyrepoupdate-unknown-space", async (ctx) => {
588
+ const res = await notifyRepoUpdate(ctx, await ctx.identities.identity("writer"), unknownSpaceUri(ctx.target.did), tidNow(), new Uint8Array(32));
589
+ return res.error === "SpaceNotFound" ? pass("answered SpaceNotFound") : fail(`answered ${describe(res)}, expected SpaceNotFound`, res.json);
590
+ });
591
+ const writeRevocation = crypto$("memberspace.write-revocation-removes-writer", async (ctx) => {
592
+ const writer = await ctx.identities.identity("writer");
593
+ const space = await createProbeSpace(ctx, memberspace({
594
+ publicRead: true,
595
+ publicWrite: true
596
+ }));
597
+ try {
598
+ await putMembers(ctx, space.uri, [{
599
+ did: writer.did,
600
+ read: true,
601
+ write: true
602
+ }]);
603
+ const first = await notifyRepoUpdate(ctx, writer, space.uri, tidNow(), new Uint8Array(32));
604
+ if (first.status !== 200) return fail(`notifyRepoUpdate ${describe(first)}`, first.json);
605
+ const credential = await obtainPublicCredential(ctx, space.uri);
606
+ const entry = async () => (await listWriters(ctx, credential)).repos.filter((r) => r.repo === writer.did).at(-1);
607
+ if ((await entry())?.$type !== "com.atproto.space.defs#repoWrite") return fail("the writer never entered the writer set");
608
+ await putMembers(ctx, space.uri, [{
609
+ did: writer.did,
610
+ read: true,
611
+ write: false
612
+ }]);
613
+ const removed = await entry();
614
+ if (removed?.$type !== "com.atproto.space.defs#repoRemoved") return fail(`after revoking write, the entry is ${JSON.stringify(removed)}`);
615
+ const again = await notifyRepoUpdate(ctx, writer, space.uri, tidNow(), new Uint8Array(32));
616
+ const after = await entry();
617
+ 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);
618
+ } finally {
619
+ await deleteProbeSpace(ctx, space.uri);
620
+ }
621
+ });
622
+ /**
623
+ * The revocation flow: a harness identity plays a foreign space authority,
624
+ * the operator writes into that space (as a member's PDS would), and the
625
+ * authority's credential reads the operator's repo — until revoked.
626
+ */
627
+ async function revocationFlow(ctx, revoker) {
628
+ const authority = await ctx.identities.identity("authority");
629
+ const space = spaceUri(authority.did, probeSkey());
630
+ const write = await operatorCreateRecord(ctx, space, POST, "shared", {
631
+ $type: POST,
632
+ text: "for the authority"
633
+ });
634
+ if (write.status !== 200) return { detail: `operator write into a foreign space: ${describe(write)}` };
635
+ const key = await createCredentialKey();
636
+ const credential = {
637
+ credential: await mintCredential(authority, space, key.did),
638
+ key,
639
+ space
640
+ };
641
+ const read = () => credentialGet(ctx, credential, "com.atproto.space.getRecord", {
642
+ space,
643
+ repo: ctx.target.did,
644
+ collection: POST,
645
+ rkey: "shared"
646
+ });
647
+ const before = await read();
648
+ if (before.status !== 200) return { detail: `foreign authority's credential could not read: ${describe(before)}` };
649
+ const jwt = await serviceJwt(revoker === "authority" ? authority : await ctx.identities.identity("stranger"), {
650
+ aud: ctx.target.did,
651
+ lxm: "com.atproto.space.notifyCredentialsRevoked"
652
+ });
653
+ return {
654
+ revoke: await xrpcPost(ctx, "com.atproto.space.notifyCredentialsRevoked", {
655
+ space,
656
+ credentials: [decodeJwt(credential.credential).payload.jti]
657
+ }, { Authorization: `Bearer ${jwt}` }),
658
+ after: await read()
659
+ };
660
+ }
661
+ const revocationRefused = crypto$("revocation.revoked-credential-refused", async (ctx) => {
662
+ const flow = await revocationFlow(ctx, "authority");
663
+ if (flow.detail) return fail(flow.detail);
664
+ if (flow.revoke.status !== 200) return fail(`notifyCredentialsRevoked ${flow.revoke.status} ${flow.revoke.error ?? ""}`);
665
+ 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})`);
666
+ });
667
+ const revocationName = crypto$("revocation.error-name", async (ctx) => {
668
+ const flow = await revocationFlow(ctx, "authority");
669
+ if (flow.detail) return fail(flow.detail);
670
+ return flow.after.error === "CredentialRevoked" ? pass("refused with CredentialRevoked") : fail(`refused with ${flow.after.status} ${flow.after.error ?? ""}`);
671
+ });
672
+ const revocationStranger = crypto$("revocation.non-authority-refused", async (ctx) => {
673
+ const flow = await revocationFlow(ctx, "stranger");
674
+ if (flow.detail) return fail(flow.detail);
675
+ if (flow.revoke.status === 200) return fail("accepted a revocation signed by someone other than the authority");
676
+ if (flow.revoke.status !== 401 && flow.revoke.status !== 403) return fail(`refused the stranger's revocation with ${flow.revoke.status} ${flow.revoke.error ?? ""}, expected 401/403`);
677
+ 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})`);
678
+ });
679
+ const managedAccount = crypto$("managedspace.check-access-account", async (ctx) => {
680
+ const inbox = ctx.syncerInbox;
681
+ const reader = await ctx.identities.identity("reader");
682
+ const lxm = "com.atproto.managedspace.checkAccess";
683
+ let answer = {
684
+ read: false,
685
+ write: false
686
+ };
687
+ inbox.respond(lxm, () => answer);
688
+ const space = await createProbeSpace(ctx, managedspace(inbox.service));
689
+ try {
690
+ const since = Date.now();
691
+ const denied = await obtainCredential(ctx, reader, space.uri);
692
+ if (denied.credential) return fail("issued a credential the managing app refused");
693
+ const asked = await inbox.waitFor((d) => d.lxm === lxm && d.receivedAt >= since && d.params?.repo === reader.did, 5e3);
694
+ if (!asked) return fail(`the managing app was never asked about the reader (${describe(denied.result)})`);
695
+ const p = asked.params ?? {};
696
+ if (p.space !== space.uri || "access" in p) return fail("checkAccess carried the wrong params", p);
697
+ answer = {
698
+ read: true,
699
+ write: false
700
+ };
701
+ const allowed = await obtainCredential(ctx, reader, space.uri);
702
+ 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)}`);
703
+ } finally {
704
+ inbox.respond(lxm, void 0);
705
+ await deleteProbeSpace(ctx, space.uri);
706
+ }
707
+ });
708
+ /** The crypto-bound catalog, in descriptor order. */
709
+ const cryptoChecks = [
710
+ macCommit,
711
+ macRecord,
712
+ oplogFolds,
713
+ getRepoStar,
714
+ credentialSigned,
715
+ delegationSigned,
716
+ exportSpaceMeta,
717
+ importSpaceMeta,
718
+ importMetaNotAuthority,
719
+ importMetaUnsupported,
720
+ importMetaInvalid,
721
+ importRepo,
722
+ importRepoNotFound,
723
+ importRepoInvalid,
724
+ importRepoMismatch,
725
+ memberGate,
726
+ personalOnly,
727
+ delegationWrongAud,
728
+ notifyAccepted,
729
+ notifyFuture,
730
+ notifyUnknown,
731
+ writeRevocation,
732
+ revocationRefused,
733
+ revocationName,
734
+ revocationStranger,
735
+ managedAccount
736
+ ];
737
+
738
+ //#endregion
739
+ //#region src/identity.ts
740
+ /**
741
+ * Harness identities.
742
+ *
743
+ * Multi-party checks need the harness to play parties that aren't the
744
+ * target's operator: a reader (signing delegation tokens), a writer's PDS
745
+ * (signing notifyWrite service auth) and a foreign space authority
746
+ * (signing credentials and revocations). Each needs a DID the target can
747
+ * resolve to the key the harness holds.
748
+ *
749
+ * Resolution is the caller's to arrange — it can't be solved in-library:
750
+ *
751
+ * - In an in-process fixture, wire the target's DID resolver to
752
+ * {@link KeypairIdentityProvider.didDocument} (or to `didKey` for a
753
+ * did:key-only resolver).
754
+ * - Against a live target, publish each identity: serve
755
+ * {@link KeypairIdentityProvider.didDocument} at a did:web the target
756
+ * can fetch (the reference matrix runs one tiny server per identity on
757
+ * `did:web:localhost%3A<port>`), or register a did:plc.
758
+ *
759
+ * What a published identity document must carry, per the alpha: a
760
+ * `#atproto` verification method (it signs every space token and service
761
+ * JWT) and — for an identity that receives calls, such as a syncer inbox
762
+ * or a managing app — an `#atproto_pds` service, which is how a bare DID
763
+ * service identifier resolves to an endpoint. Identities never serve
764
+ * repos, so they publish no `#atproto_kem`.
765
+ */
766
+ /**
767
+ * An identity provider backed by secp256k1 keypairs. Identities are keyed
768
+ * by role label and reused within a run, so "reader" is stable across the
769
+ * checks that mint and then present its tokens.
770
+ *
771
+ * `didFor` gives each identity a resolvable DID (e.g.
772
+ * `did:web:localhost%3A61234`), and may be async — a harness can start the
773
+ * server that will publish the document there. When omitted, the
774
+ * identity's DID is its own `did:key`, which only works against a target
775
+ * whose resolver this provider is wired into.
776
+ */
777
+ var KeypairIdentityProvider = class {
778
+ cache = /* @__PURE__ */ new Map();
779
+ constructor(didFor) {
780
+ this.didFor = didFor;
781
+ }
782
+ identity(role) {
783
+ let existing = this.cache.get(role);
784
+ if (!existing) {
785
+ existing = this.mint(role);
786
+ this.cache.set(role, existing);
787
+ }
788
+ return existing;
789
+ }
790
+ async mint(role) {
791
+ const keypair = await Secp256k1Keypair.create({ exportable: true });
792
+ const didKey = keypair.did();
793
+ return {
794
+ did: this.didFor ? await this.didFor(role, didKey) : didKey,
795
+ didKey,
796
+ jwtAlg: keypair.jwtAlg,
797
+ sign: (bytes) => keypair.sign(bytes)
798
+ };
799
+ }
800
+ /**
801
+ * The DID document a resolvable identity must publish: its `#atproto`
802
+ * key as a Multikey and, optionally, the `#atproto_pds` service the
803
+ * target delivers to.
804
+ */
805
+ static didDocument(identity, opts = {}) {
806
+ return {
807
+ "@context": ["https://www.w3.org/ns/did/v1", "https://w3id.org/security/multikey/v1"],
808
+ id: identity.did,
809
+ ...opts.handle ? { alsoKnownAs: [`at://${opts.handle}`] } : {},
810
+ verificationMethod: [{
811
+ id: `${identity.did}#atproto`,
812
+ type: "Multikey",
813
+ controller: identity.did,
814
+ publicKeyMultibase: identity.didKey.slice(8)
815
+ }],
816
+ ...opts.serviceEndpoint ? { service: [{
817
+ id: "#atproto_pds",
818
+ type: "AtprotoPersonalDataServer",
819
+ serviceEndpoint: opts.serviceEndpoint
820
+ }] } : {}
821
+ };
822
+ }
823
+ /** All minted identities so far, for resolver wiring in fixtures. */
824
+ minted() {
825
+ return Promise.all(this.cache.values());
826
+ }
827
+ };
828
+
829
+ //#endregion
830
+ //#region src/full.ts
831
+ /**
832
+ * The full check catalog and the identity provider.
833
+ *
834
+ * This entry imports `@atproto/space`, so it pulls the spaces crypto libs
835
+ * and their (node-ish) transitive graph. Import it from the CLI and the
836
+ * vitest adapter — anywhere WebCrypto and those libs run — but never
837
+ * from a browser bundle. The browser adapter imports the base catalog from
838
+ * the package root instead.
839
+ */
840
+ /**
841
+ * The complete catalog: the browser-safe base and operator checks plus
842
+ * the crypto-bound ones only this entry can run.
843
+ */
844
+ const fullCatalog = buildCatalog([
845
+ ...baseChecks,
846
+ ...operatorChecks,
847
+ ...cryptoChecks
848
+ ]);
849
+
850
+ //#endregion
851
+ export { mintDelegation as a, mintCredential as i, KeypairIdentityProvider as n, obtainCredential as o, cryptoChecks as r, serviceJwt as s, fullCatalog as t };
852
+ //# sourceMappingURL=full-CKsHg6ox.js.map