@getcirrus/space-conformance 0.0.0 → 0.1.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.
Files changed (80) hide show
  1. package/dist/base-CGsQgOwR.d.ts +472 -0
  2. package/dist/base-CGsQgOwR.d.ts.map +1 -0
  3. package/dist/cli.js +79266 -26
  4. package/dist/cli.js.map +1 -1
  5. package/dist/coverage-zCMup3Nb.js +2245 -0
  6. package/dist/coverage-zCMup3Nb.js.map +1 -0
  7. package/dist/descriptors-YEk3XoDL.js +4428 -0
  8. package/dist/descriptors-YEk3XoDL.js.map +1 -0
  9. package/dist/full-Bomm2urj.js +12285 -0
  10. package/dist/full-Bomm2urj.js.map +1 -0
  11. package/dist/full.d.ts +43 -17
  12. package/dist/full.d.ts.map +1 -1
  13. package/dist/full.js +3 -3
  14. package/dist/index.d.ts +91 -28
  15. package/dist/index.d.ts.map +1 -1
  16. package/dist/index.js +115 -93
  17. package/dist/index.js.map +1 -1
  18. package/lexicons/MANIFEST.json +3 -3
  19. package/lexicons/managedspace/checkAccess.json +44 -0
  20. package/lexicons/managedspace/policy.json +22 -0
  21. package/lexicons/memberspace/defs.json +22 -0
  22. package/lexicons/{simplespace → memberspace}/listMembers.json +15 -17
  23. package/lexicons/memberspace/member.json +23 -0
  24. package/lexicons/memberspace/policy.json +40 -0
  25. package/lexicons/memberspace/putMembers.json +43 -0
  26. package/lexicons/memberspace/removeMembers.json +43 -0
  27. package/lexicons/personalspace/policy.json +11 -0
  28. package/lexicons/space/applyWrites.json +6 -11
  29. package/lexicons/space/authorizeSpaceSync.json +109 -0
  30. package/lexicons/space/clearRecords.json +34 -0
  31. package/lexicons/space/confirmRegistration.json +44 -0
  32. package/lexicons/space/createRecord.json +7 -14
  33. package/lexicons/space/createSpace.json +58 -0
  34. package/lexicons/space/defs.json +61 -17
  35. package/lexicons/space/deleteRecord.json +5 -9
  36. package/lexicons/space/deleteSpace.json +31 -0
  37. package/lexicons/space/exportSpaceMeta.json +31 -0
  38. package/lexicons/space/getBlob.json +4 -7
  39. package/lexicons/space/getDelegationToken.json +3 -5
  40. package/lexicons/space/getLatestCommit.json +8 -7
  41. package/lexicons/space/getRecord.json +9 -9
  42. package/lexicons/space/getRepo.json +8 -11
  43. package/lexicons/space/getSpace.json +43 -0
  44. package/lexicons/space/importRepo.json +27 -0
  45. package/lexicons/space/importSpaceMeta.json +25 -0
  46. package/lexicons/space/listBlobs.json +3 -10
  47. package/lexicons/space/listRecords.json +10 -16
  48. package/lexicons/space/listRepoOps.json +23 -23
  49. package/lexicons/space/listSpaces.json +30 -14
  50. package/lexicons/space/listWriters.json +66 -0
  51. package/lexicons/space/notifyCredentialsRevoked.json +30 -0
  52. package/lexicons/space/notifyRepoUpdate.json +43 -0
  53. package/lexicons/space/notifySpaceUpdate.json +53 -0
  54. package/lexicons/space/policy.json +26 -0
  55. package/lexicons/space/putRecord.json +7 -14
  56. package/lexicons/space/removeWriter.json +35 -0
  57. package/lexicons/space/updateSpace.json +43 -0
  58. package/package.json +8 -10
  59. package/dist/base-D8a-ZK57.d.ts +0 -249
  60. package/dist/base-D8a-ZK57.d.ts.map +0 -1
  61. package/dist/coverage-DhJZu8P8.js +0 -1914
  62. package/dist/coverage-DhJZu8P8.js.map +0 -1
  63. package/dist/full-D4ufJLcw.js +0 -409
  64. package/dist/full-D4ufJLcw.js.map +0 -1
  65. package/dist/operator-BErXCDow.js +0 -923
  66. package/dist/operator-BErXCDow.js.map +0 -1
  67. package/lexicons/simplespace/addMember.json +0 -37
  68. package/lexicons/simplespace/checkUserAccess.json +0 -43
  69. package/lexicons/simplespace/createSpace.json +0 -74
  70. package/lexicons/simplespace/defs.json +0 -47
  71. package/lexicons/simplespace/deleteSpace.json +0 -32
  72. package/lexicons/simplespace/getSpace.json +0 -53
  73. package/lexicons/simplespace/removeMember.json +0 -37
  74. package/lexicons/simplespace/updateSpace.json +0 -57
  75. package/lexicons/space/getSpaceCredential.json +0 -67
  76. package/lexicons/space/listRepos.json +0 -75
  77. package/lexicons/space/notifySpaceDeleted.json +0 -24
  78. package/lexicons/space/notifyWrite.json +0 -38
  79. package/lexicons/space/registerNotify.json +0 -49
  80. package/lexicons/space/unregisterNotify.json +0 -29
@@ -0,0 +1,4428 @@
1
+ //#region src/model.ts
2
+ const pass = (detail, evidence) => ({
3
+ status: "pass",
4
+ detail,
5
+ ...evidence !== void 0 ? { evidence } : {}
6
+ });
7
+ const fail = (detail, evidence) => ({
8
+ status: "fail",
9
+ detail,
10
+ ...evidence !== void 0 ? { evidence } : {}
11
+ });
12
+
13
+ //#endregion
14
+ //#region src/registry.ts
15
+ /**
16
+ * Define a check, enforcing the catalog's structural rules at
17
+ * registration time rather than in review:
18
+ *
19
+ * - ids are `area.slug`, unique within a catalog;
20
+ * - a `must` check carries at least one citation to specified behavior —
21
+ * without one it is someone's opinion and belongs in `should` or `info`.
22
+ */
23
+ function defineCheck(check) {
24
+ if (!/^[a-z0-9-]+\.[a-z0-9-]+$/.test(check.id)) throw new Error(`Check id must be "area.slug" (kebab-case): ${check.id}`);
25
+ if (check.tier === "must" && check.citations.length === 0) throw new Error(`Check ${check.id} is tier "must" but cites nothing. Cite the lexicon, proposal or design spec — or demote it.`);
26
+ return check;
27
+ }
28
+ function buildCatalog(checks) {
29
+ const seen = /* @__PURE__ */ new Set();
30
+ for (const check of checks) {
31
+ if (seen.has(check.id)) throw new Error(`Duplicate check id: ${check.id}`);
32
+ seen.add(check.id);
33
+ }
34
+ return checks;
35
+ }
36
+ /**
37
+ * Partition a catalog into runnable and skipped for a given harness. A
38
+ * skipped check is part of the report — "not testable here" must never
39
+ * silently read as "conformant".
40
+ */
41
+ function filterCatalog(catalog, filter) {
42
+ const capabilities = new Set(filter.capabilities ?? []);
43
+ const runnable = [];
44
+ const skipped = [];
45
+ const ids = filter.ids?.length ? filter.ids : void 0;
46
+ const areas = filter.areas?.length ? filter.areas : void 0;
47
+ const tiers = filter.tiers?.length ? filter.tiers : void 0;
48
+ for (const check of catalog) {
49
+ if (ids && !ids.includes(check.id)) continue;
50
+ const area = check.id.split(".")[0];
51
+ if (areas && !areas.includes(area)) continue;
52
+ if (tiers && !tiers.includes(check.tier)) {
53
+ skipped.push({
54
+ check,
55
+ reason: `tier ${check.tier} excluded`
56
+ });
57
+ continue;
58
+ }
59
+ if (check.destructive && !filter.destructive) {
60
+ skipped.push({
61
+ check,
62
+ reason: "destructive checks not enabled"
63
+ });
64
+ continue;
65
+ }
66
+ if (check.slow && !filter.slow) {
67
+ skipped.push({
68
+ check,
69
+ reason: "slow checks not enabled"
70
+ });
71
+ continue;
72
+ }
73
+ const missing = check.needs.filter((need) => !capabilities.has(need));
74
+ if (missing.length > 0) {
75
+ skipped.push({
76
+ check,
77
+ reason: `missing capabilities: ${missing.join(", ")}`
78
+ });
79
+ continue;
80
+ }
81
+ runnable.push(check);
82
+ }
83
+ return {
84
+ runnable,
85
+ skipped
86
+ };
87
+ }
88
+
89
+ //#endregion
90
+ //#region src/http.ts
91
+ function xrpcUrl(origin, nsid, params) {
92
+ const url = new URL(`${origin}/xrpc/${nsid}`);
93
+ for (const [key, value] of Object.entries(params ?? {})) if (value !== void 0) url.searchParams.set(key, value);
94
+ return url.toString();
95
+ }
96
+ async function toResult(response) {
97
+ const contentType = response.headers.get("Content-Type") ?? "";
98
+ let json$1;
99
+ let error;
100
+ if (contentType.includes("application/json")) {
101
+ json$1 = await response.clone().json().catch(() => void 0);
102
+ if (json$1 && typeof json$1 === "object" && "error" in json$1) error = String(json$1.error);
103
+ }
104
+ return {
105
+ status: response.status,
106
+ json: json$1,
107
+ error,
108
+ headers: response.headers,
109
+ response
110
+ };
111
+ }
112
+ /** GET an XRPC query. `headers` may carry auth. */
113
+ async function xrpcGet(ctx, nsid, params, headers) {
114
+ return toResult(await ctx.fetch(xrpcUrl(ctx.target.origin, nsid, params), {
115
+ method: "GET",
116
+ headers
117
+ }));
118
+ }
119
+ /** POST an XRPC procedure with a JSON body. */
120
+ async function xrpcPost(ctx, nsid, body, headers) {
121
+ const merged = new Headers(headers);
122
+ merged.set("Content-Type", "application/json");
123
+ return toResult(await ctx.fetch(xrpcUrl(ctx.target.origin, nsid), {
124
+ method: "POST",
125
+ headers: merged,
126
+ body: JSON.stringify(body)
127
+ }));
128
+ }
129
+ /** Add the operator's auth to a headers object, if a session is present. */
130
+ async function operatorHeaders(ctx, extra) {
131
+ const headers = new Headers(extra);
132
+ if (ctx.operator?.authorize) await ctx.operator.authorize({ headers });
133
+ return headers;
134
+ }
135
+ /**
136
+ * A fetch that carries the operator's credentials: the operator's own
137
+ * signing fetch when it has one (an OAuth session's DPoP proof must sign
138
+ * each request individually), otherwise the transport fetch with
139
+ * `authorize`-injected headers. With no operator at all it falls back to
140
+ * the plain transport — the runner skips operator-needing checks then, so
141
+ * that path is only reached by checks that can also run anonymously.
142
+ */
143
+ function operatorFetch(ctx) {
144
+ const operator = ctx.operator;
145
+ if (!operator) return ctx.fetch;
146
+ if (operator.fetch) return operator.fetch;
147
+ const baseFetch = ctx.fetch;
148
+ return async (input, init) => {
149
+ const headers = new Headers(init?.headers);
150
+ await operator.authorize?.({
151
+ ...init,
152
+ headers
153
+ });
154
+ return baseFetch(input, {
155
+ ...init,
156
+ headers
157
+ });
158
+ };
159
+ }
160
+ /**
161
+ * The same context with the operator's credentials on `fetch`, so a check
162
+ * can write `xrpcGet(asOperator(ctx), …)` for authenticated calls while
163
+ * keeping the bare `ctx` for requests that must stay anonymous.
164
+ */
165
+ function asOperator(ctx) {
166
+ return {
167
+ ...ctx,
168
+ fetch: operatorFetch(ctx)
169
+ };
170
+ }
171
+ /** POST raw bytes (an archive upload) to an XRPC procedure. */
172
+ async function xrpcPostBytes(ctx, nsid, bytes, headers, contentType = "application/vnd.dasl.star") {
173
+ const merged = new Headers(headers);
174
+ merged.set("Content-Type", contentType);
175
+ return toResult(await ctx.fetch(xrpcUrl(ctx.target.origin, nsid), {
176
+ method: "POST",
177
+ headers: merged,
178
+ body: bytes
179
+ }));
180
+ }
181
+
182
+ //#endregion
183
+ //#region src/encoding.ts
184
+ /**
185
+ * Dependency-free byte encodings shared by the browser-safe helpers:
186
+ * base64 (padded, unpadded and url-safe), base58btc for did:key, base32
187
+ * for CIDs, and a few byte utilities. Kept here so the browser catalog
188
+ * never pulls a multiformats or noble dependency for a dozen lines of code.
189
+ */
190
+ const utf8 = (s) => new TextEncoder().encode(s);
191
+ function concatBytes(parts) {
192
+ const out = new Uint8Array(parts.reduce((n, p) => n + p.length, 0));
193
+ let offset = 0;
194
+ for (const part of parts) {
195
+ out.set(part, offset);
196
+ offset += part.length;
197
+ }
198
+ return out;
199
+ }
200
+ function bytesEqual(a, b) {
201
+ return a.length === b.length && a.every((byte, i) => byte === b[i]);
202
+ }
203
+ function toBase64(bytes) {
204
+ let bin = "";
205
+ for (const b of bytes) bin += String.fromCharCode(b);
206
+ return btoa(bin);
207
+ }
208
+ const toBase64Url = (bytes) => toBase64(bytes).replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/, "");
209
+ /** Decode base64 or base64url, padded or not. */
210
+ function fromBase64(input) {
211
+ let s = input.replace(/-/g, "+").replace(/_/g, "/").replace(/=+$/, "");
212
+ s = s.padEnd(Math.ceil(s.length / 4) * 4, "=");
213
+ const bin = atob(s);
214
+ const out = new Uint8Array(bin.length);
215
+ for (let i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i);
216
+ return out;
217
+ }
218
+ const B58 = "123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz";
219
+ function toBase58(bytes) {
220
+ let zeros = 0;
221
+ while (zeros < bytes.length && bytes[zeros] === 0) zeros++;
222
+ let n = 0n;
223
+ for (const b of bytes) n = n * 256n + BigInt(b);
224
+ let out = "";
225
+ while (n > 0n) {
226
+ out = B58[Number(n % 58n)] + out;
227
+ n /= 58n;
228
+ }
229
+ return "1".repeat(zeros) + out;
230
+ }
231
+ function fromBase58(input) {
232
+ let zeros = 0;
233
+ while (zeros < input.length && input[zeros] === "1") zeros++;
234
+ let n = 0n;
235
+ for (const ch of input) {
236
+ const value = B58.indexOf(ch);
237
+ if (value < 0) throw new Error(`invalid base58 character: ${ch}`);
238
+ n = n * 58n + BigInt(value);
239
+ }
240
+ const body = [];
241
+ while (n > 0n) {
242
+ body.unshift(Number(n % 256n));
243
+ n /= 256n;
244
+ }
245
+ return new Uint8Array([...new Array(zeros).fill(0), ...body]);
246
+ }
247
+ const B32 = "abcdefghijklmnopqrstuvwxyz234567";
248
+ function toBase32(bytes) {
249
+ let out = "";
250
+ let bits = 0;
251
+ let value = 0;
252
+ for (const byte of bytes) {
253
+ value = value << 8 | byte;
254
+ bits += 8;
255
+ while (bits >= 5) {
256
+ out += B32[value >>> bits - 5 & 31];
257
+ bits -= 5;
258
+ }
259
+ }
260
+ if (bits > 0) out += B32[value << 5 - bits & 31];
261
+ return out;
262
+ }
263
+ /** A CIDv1 (raw codec, sha2-256) for some bytes — a well-formed blob CID. */
264
+ async function rawCid(bytes) {
265
+ const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
266
+ return `b${toBase32(concatBytes([new Uint8Array([
267
+ 1,
268
+ 85,
269
+ 18,
270
+ 32
271
+ ]), digest]))}`;
272
+ }
273
+ async function sha256(bytes) {
274
+ return new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
275
+ }
276
+ /** Decode a compact JWT's header and payload without verifying it. */
277
+ function decodeJwt(jwt) {
278
+ const parts = jwt.split(".");
279
+ if (parts.length !== 3) throw new Error("not a compact JWT");
280
+ const decode = (part) => JSON.parse(new TextDecoder().decode(fromBase64(part)));
281
+ return {
282
+ header: decode(parts[0]),
283
+ payload: decode(parts[1])
284
+ };
285
+ }
286
+ /** `$bytes` JSON wire form → bytes, or undefined if it isn't one. */
287
+ function lexBytes(value) {
288
+ if (value && typeof value === "object" && typeof value.$bytes === "string") return fromBase64(value.$bytes);
289
+ }
290
+ const TID_CHARS = "234567abcdefghijklmnopqrstuvwxyz";
291
+ const TID_RE = /^[234567abcdefghij][234567abcdefghijklmnopqrstuvwxyz]{12}$/;
292
+ const isTid = (value) => typeof value === "string" && TID_RE.test(value);
293
+ /** A TID for a given time in microseconds since the epoch (clock id 0). */
294
+ function tidAt(micros) {
295
+ let n = micros << 10n & 9223372036854775807n;
296
+ let out = "";
297
+ for (let i = 0; i < 13; i++) {
298
+ out = TID_CHARS[Number(n & 31n)] + out;
299
+ n >>= 5n;
300
+ }
301
+ return out;
302
+ }
303
+ const tidNow = () => tidAt(BigInt(Date.now()) * 1000n);
304
+
305
+ //#endregion
306
+ //#region src/space-auth.ts
307
+ /**
308
+ * Browser-safe space credential presentation: P-256 did:key credential
309
+ * keys, the `atproto-space-credential` HTTP message signature, and the
310
+ * MAC request (`Accept-Signature`, keyed by an HPKE-exported secret) a
311
+ * syncer sends with every credentialed read of a commit or record.
312
+ *
313
+ * Deliberately dependency-free (WebCrypto and BigInt only) so the checks
314
+ * that present a credential — the operator's own credential flow, the MAC
315
+ * and signature refusals — run in a browser bundle too. Every format here
316
+ * mirrors `@atproto/space` byte for byte (`createSpaceSigHeaders`,
317
+ * `encapsulate`, `formatMacRequest`); the full test suite cross-checks
318
+ * each against the reference library, so a drift fails CI rather than
319
+ * every run against a real host.
320
+ *
321
+ * Verifying a MAC (rather than requesting one) needs the reference
322
+ * library's commit and record encodings, so it lives behind the full
323
+ * entry.
324
+ */
325
+ const P$5 = 2n ** 256n - 2n ** 224n + 2n ** 192n + 2n ** 96n - 1n;
326
+ const B = 41058363725152142129326129780047268409114441015993725554835256314039467401291n;
327
+ const N = 115792089210356248762697446949407573529996955224135760342422259061068512044369n;
328
+ const P256_MULTICODEC = new Uint8Array([128, 36]);
329
+ const K256_MULTICODEC = new Uint8Array([231, 1]);
330
+ function bytesToBigInt(bytes) {
331
+ let n = 0n;
332
+ for (const b of bytes) n = n << 8n | BigInt(b);
333
+ return n;
334
+ }
335
+ function bigIntToBytes(n, length) {
336
+ const out = new Uint8Array(length);
337
+ for (let i = length - 1; i >= 0; i--) {
338
+ out[i] = Number(n & 255n);
339
+ n >>= 8n;
340
+ }
341
+ return out;
342
+ }
343
+ function modPow(base, exp, mod) {
344
+ let result = 1n;
345
+ base %= mod;
346
+ while (exp > 0n) {
347
+ if (exp & 1n) result = result * base % mod;
348
+ base = base * base % mod;
349
+ exp >>= 1n;
350
+ }
351
+ return result;
352
+ }
353
+ /** 0x04 || x || y → 0x02/0x03 || x. Curve-agnostic (secp256k1 too). */
354
+ function compressP256(uncompressed) {
355
+ if (uncompressed.length !== 65 || uncompressed[0] !== 4) throw new Error("expected an uncompressed EC point");
356
+ const prefix = (uncompressed[64] & 1) === 1 ? 3 : 2;
357
+ return concatBytes([new Uint8Array([prefix]), uncompressed.subarray(1, 33)]);
358
+ }
359
+ /** 0x02/0x03 || x → 0x04 || x || y. */
360
+ function decompressP256(compressed) {
361
+ if (compressed.length !== 33 || compressed[0] !== 2 && compressed[0] !== 3) throw new Error("expected a compressed P-256 point");
362
+ const x = bytesToBigInt(compressed.subarray(1));
363
+ const rhs = ((x * x * x - 3n * x + B) % P$5 + P$5) % P$5;
364
+ let y = modPow(rhs, (P$5 + 1n) / 4n, P$5);
365
+ if (y * y % P$5 !== rhs) throw new Error("point is not on P-256");
366
+ if ((y & 1n) !== BigInt(compressed[0] & 1)) y = P$5 - y;
367
+ return concatBytes([
368
+ new Uint8Array([4]),
369
+ bigIntToBytes(x, 32),
370
+ bigIntToBytes(y, 32)
371
+ ]);
372
+ }
373
+ /** Format a did:key from a public key (compressed or, for P-256, not). */
374
+ function formatDidKey(alg, keyBytes) {
375
+ if (alg === "ES256") return `did:key:z${toBase58(concatBytes([P256_MULTICODEC, keyBytes.length === 65 ? compressP256(keyBytes) : keyBytes]))}`;
376
+ if (keyBytes.length !== 33) throw new Error("secp256k1 keys must be given compressed");
377
+ return `did:key:z${toBase58(concatBytes([K256_MULTICODEC, keyBytes]))}`;
378
+ }
379
+ /** Parse a did:key, returning its algorithm and compressed key bytes. */
380
+ function parseDidKey(didKey) {
381
+ if (!didKey.startsWith("did:key:z")) throw new Error("not a did:key");
382
+ const bytes = fromBase58(didKey.slice(9));
383
+ if (bytes[0] === 128 && bytes[1] === 36) return {
384
+ alg: "ES256",
385
+ compressed: bytes.subarray(2)
386
+ };
387
+ if (bytes[0] === 231 && bytes[1] === 1) return {
388
+ alg: "ES256K",
389
+ compressed: bytes.subarray(2)
390
+ };
391
+ throw new Error("unsupported did:key type");
392
+ }
393
+ function isP256DidKey(value) {
394
+ try {
395
+ return typeof value === "string" && parseDidKey(value).alg === "ES256";
396
+ } catch {
397
+ return false;
398
+ }
399
+ }
400
+ async function createCredentialKey() {
401
+ const pair = await crypto.subtle.generateKey({
402
+ name: "ECDSA",
403
+ namedCurve: "P-256"
404
+ }, true, ["sign"]);
405
+ return {
406
+ did: formatDidKey("ES256", new Uint8Array(await crypto.subtle.exportKey("raw", pair.publicKey))),
407
+ async sign(bytes) {
408
+ const sig = new Uint8Array(await crypto.subtle.sign({
409
+ name: "ECDSA",
410
+ hash: "SHA-256"
411
+ }, pair.privateKey, bytes));
412
+ const s = bytesToBigInt(sig.subarray(32));
413
+ if (s > N / 2n) sig.set(bigIntToBytes(N - s, 32), 32);
414
+ return sig;
415
+ }
416
+ };
417
+ }
418
+ /** `CLIENT_ATTESTATION_TYP` of `@atproto/space`. */
419
+ const CLIENT_ATTESTATION_TYP = "atproto-client-attestation+jwt";
420
+ /**
421
+ * How a space authority is addressed as the space host — the audience of
422
+ * delegation tokens and client attestations (`spaceHostAud` of
423
+ * `@atproto/space`).
424
+ */
425
+ const spaceHostAud = (authority) => `${authority}#atproto_pds`;
426
+ /**
427
+ * A client attestation as `@atproto/space`'s `buildClientAttestation`
428
+ * shapes it — typ `atproto-client-attestation+jwt`, the signing key's
429
+ * `kid`, iss = sub = client_id, aud, iat, exp and a fresh jti — signed ES256
430
+ * by `sign` (a 64-byte compact signature).
431
+ */
432
+ async function signClientAttestation(opts) {
433
+ const iat = Math.floor(Date.now() / 1e3);
434
+ const part = (obj) => toBase64Url(utf8(JSON.stringify(obj)));
435
+ const input = `${part({
436
+ alg: "ES256",
437
+ typ: CLIENT_ATTESTATION_TYP,
438
+ kid: opts.kid
439
+ })}.${part({
440
+ iss: opts.clientId,
441
+ sub: opts.clientId,
442
+ aud: opts.aud,
443
+ iat,
444
+ exp: iat + (opts.expiresInSec ?? 60),
445
+ jti: toBase64Url(crypto.getRandomValues(new Uint8Array(16)))
446
+ })}`;
447
+ return `${input}.${toBase64Url(await opts.sign(utf8(input)))}`;
448
+ }
449
+ const SPACE_CREDENTIAL_SCHEME = "Atproto-Space-Credential";
450
+ const CREDENTIAL_SIG_TAG = "atproto-space-credential";
451
+ const CREDENTIAL_COMPONENTS = ["authorization", "atproto-space-audience"];
452
+ /** Serialise RFC 9651 parameters: strings quoted, integers bare. */
453
+ function serializeParams(params) {
454
+ return params.map(([k, v]) => `;${k}=${typeof v === "number" ? v : `"${v}"`}`).join("");
455
+ }
456
+ /** One signature's `Signature-Input` and `Signature` dictionary members. */
457
+ async function credentialSigMembers(key, opts) {
458
+ const components = opts.components ?? CREDENTIAL_COMPONENTS;
459
+ const label = opts.label ?? "sig";
460
+ const signatureParams = `(${components.map((c) => `"${c}"`).join(" ")})${serializeParams([["tag", opts.tag ?? CREDENTIAL_SIG_TAG], ...opts.params ?? []])}`;
461
+ const values = {
462
+ authorization: opts.authorization,
463
+ "atproto-space-audience": opts.audience
464
+ };
465
+ const base = [...components.map((c) => `"${c}": ${(values[c] ?? "").trim()}`), `"@signature-params": ${signatureParams}`].join("\n");
466
+ const signature = await key.sign(utf8(base));
467
+ return {
468
+ input: `${label}=${signatureParams}`,
469
+ signature: `${label}=:${toBase64(signature)}:`
470
+ };
471
+ }
472
+ /**
473
+ * The headers that present a space credential: the `Authorization` scheme,
474
+ * the audience DID (the service being called — the repo DID at a repo
475
+ * host, the authority DID at the space host) and an RFC 9421 signature by
476
+ * the credential's key covering exactly those two fields, tagged
477
+ * `atproto-space-credential`.
478
+ */
479
+ async function spaceSigHeaders(key, opts) {
480
+ const { input, signature } = await credentialSigMembers(key, opts);
481
+ return {
482
+ authorization: opts.authorization,
483
+ "atproto-space-audience": opts.audience,
484
+ "signature-input": input,
485
+ signature
486
+ };
487
+ }
488
+ const COMMIT_MAC_PROFILE = "atproto-space-commit";
489
+ const RECORD_MAC_PROFILE = "atproto-space-record";
490
+ /** The response header each profile's MAC covers. */
491
+ const MAC_COVERED_HEADER = {
492
+ [COMMIT_MAC_PROFILE]: "atproto-space-commit",
493
+ [RECORD_MAC_PROFILE]: "atproto-space-record"
494
+ };
495
+ /**
496
+ * One `Accept-Signature` member asking for a MAC under `profile`, keyed by
497
+ * the shared secret for `keyShare`:
498
+ * `mac=("atproto-space-commit";sf);keyid="did:key:…";tag="atproto-space-commit"`.
499
+ */
500
+ function formatMacRequest(profile, keyShare, opts = {}) {
501
+ return `${opts.label ?? "mac"}=("${MAC_COVERED_HEADER[profile]}";sf)${serializeParams([
502
+ ["keyid", keyShare],
503
+ ["tag", profile],
504
+ ...opts.params ?? []
505
+ ])}`;
506
+ }
507
+ const uint16be = (n) => new Uint8Array([n >>> 8, n & 255]);
508
+ const HPKE_VERSION = utf8("HPKE-v1");
509
+ const KEM_ID = concatBytes([utf8("KEM"), uint16be(16)]);
510
+ const SUITE_ID = concatBytes([
511
+ utf8("HPKE"),
512
+ uint16be(16),
513
+ uint16be(1),
514
+ uint16be(65535)
515
+ ]);
516
+ const EMPTY = new Uint8Array(0);
517
+ async function hmac(key, data) {
518
+ const k = await crypto.subtle.importKey("raw", key.length ? key : new Uint8Array(32), {
519
+ name: "HMAC",
520
+ hash: "SHA-256"
521
+ }, false, ["sign"]);
522
+ return new Uint8Array(await crypto.subtle.sign("HMAC", k, data));
523
+ }
524
+ const labeledExtract = (id, salt, label, ikm) => hmac(salt, concatBytes([
525
+ HPKE_VERSION,
526
+ id,
527
+ utf8(label),
528
+ ikm
529
+ ]));
530
+ const labeledExpand = (id, prk, label, info) => hmac(prk, concatBytes([
531
+ uint16be(32),
532
+ HPKE_VERSION,
533
+ id,
534
+ utf8(label),
535
+ info,
536
+ new Uint8Array([1])
537
+ ]));
538
+ /**
539
+ * Syncer side of the space KEM: HPKE secret export (RFC 9180 §6.2) in base
540
+ * mode with DHKEM(P-256, HKDF-SHA256), HKDF-SHA256 and the Export-only
541
+ * AEAD, `info = "atproto-mac"`, an empty exporter context and L = 32 —
542
+ * spelled out as the ECDH and HKDF steps it performs. The returned
543
+ * `keyShare` is HPKE's `enc`, as a compressed did:key. Use once per request.
544
+ */
545
+ async function encapsulate(authorKemDidKey) {
546
+ const parsed = parseDidKey(authorKemDidKey);
547
+ if (parsed.alg !== "ES256") throw new Error("KEM key must be P-256");
548
+ const authorBytes = decompressP256(parsed.compressed);
549
+ const authorKey = await crypto.subtle.importKey("raw", authorBytes, {
550
+ name: "ECDH",
551
+ namedCurve: "P-256"
552
+ }, false, []);
553
+ const ephemeral = await crypto.subtle.generateKey({
554
+ name: "ECDH",
555
+ namedCurve: "P-256"
556
+ }, true, ["deriveBits"]);
557
+ const enc = new Uint8Array(await crypto.subtle.exportKey("raw", ephemeral.publicKey));
558
+ const kemSecret = await labeledExpand(KEM_ID, await labeledExtract(KEM_ID, EMPTY, "eae_prk", new Uint8Array(await crypto.subtle.deriveBits({
559
+ name: "ECDH",
560
+ public: authorKey
561
+ }, ephemeral.privateKey, 256))), "shared_secret", concatBytes([enc, authorBytes]));
562
+ const pskIdHash = await labeledExtract(SUITE_ID, EMPTY, "psk_id_hash", EMPTY);
563
+ const infoHash = await labeledExtract(SUITE_ID, EMPTY, "info_hash", utf8("atproto-mac"));
564
+ const context = concatBytes([
565
+ new Uint8Array([0]),
566
+ pskIdHash,
567
+ infoHash
568
+ ]);
569
+ const sharedSecret = await labeledExpand(SUITE_ID, await labeledExpand(SUITE_ID, await labeledExtract(SUITE_ID, kemSecret, "secret", EMPTY), "exp", context), "sec", EMPTY);
570
+ return {
571
+ keyShare: formatDidKey("ES256", enc),
572
+ sharedSecret
573
+ };
574
+ }
575
+
576
+ //#endregion
577
+ //#region src/did.ts
578
+ const DEFAULT_PLC_DIRECTORY = "https://plc.directory";
579
+ /** The URL a DID document is fetched from, mirroring the reference resolver. */
580
+ function didDocumentUrl(did, plcDirectory) {
581
+ if (did.startsWith("did:web:")) {
582
+ const host = decodeURIComponent(did.slice(8));
583
+ if (host.includes(":") && !/^localhost:\d+$/.test(host)) throw new Error(`did:web with a path is not supported: ${did}`);
584
+ return `${host.split(":")[0] === "localhost" ? "http" : "https"}://${host}/.well-known/did.json`;
585
+ }
586
+ if (did.startsWith("did:plc:")) return `${(plcDirectory ?? DEFAULT_PLC_DIRECTORY).replace(/\/+$/, "")}/${did}`;
587
+ throw new Error(`unsupported DID method: ${did}`);
588
+ }
589
+ async function resolveDidDocument(ctx, did) {
590
+ if (ctx.resolveDid) {
591
+ const doc$1 = await ctx.resolveDid(did);
592
+ if (!doc$1) throw new Error(`could not resolve ${did}`);
593
+ return doc$1;
594
+ }
595
+ const url = didDocumentUrl(did, ctx.target.plcDirectory);
596
+ const res = await ctx.fetch(url, { headers: { accept: "application/did+ld+json,application/json" } });
597
+ if (!res.ok) throw new Error(`resolving ${did}: ${url} returned ${res.status}`);
598
+ const doc = await res.json();
599
+ if (doc.id !== did) throw new Error(`DID document for ${did} names itself ${doc.id}`);
600
+ return doc;
601
+ }
602
+ const matchesFragment = (id, did, fragment) => id === `#${fragment}` || id === `${did}#${fragment}`;
603
+ /**
604
+ * A verification method as a did:key, accepting the `Multikey` form and
605
+ * the legacy 2019 types PLC still emits (raw key bytes, no multicodec).
606
+ */
607
+ function verificationMethodDidKey(doc, fragment) {
608
+ const method = (doc.verificationMethod ?? []).find((m) => matchesFragment(m.id, doc.id, fragment));
609
+ const multibase = method?.publicKeyMultibase;
610
+ if (!method || !multibase?.startsWith("z")) return void 0;
611
+ try {
612
+ if (method.type === "Multikey") return `did:key:${multibase}`;
613
+ const raw = fromBase58(multibase.slice(1));
614
+ if (method.type === "EcdsaSecp256r1VerificationKey2019") return formatDidKey("ES256", raw.length === 65 ? compressP256(raw) : raw);
615
+ if (method.type === "EcdsaSecp256k1VerificationKey2019") return formatDidKey("ES256K", raw.length === 65 ? compressP256(raw) : raw);
616
+ } catch {
617
+ return;
618
+ }
619
+ }
620
+ function serviceEndpoint(doc, fragment) {
621
+ const entry = (doc.service ?? []).find((s) => matchesFragment(s.id, doc.id, fragment));
622
+ return typeof entry?.serviceEndpoint === "string" ? entry.serviceEndpoint : void 0;
623
+ }
624
+ /**
625
+ * The repo's `#atproto_kem` key, cached per run: every MAC request against
626
+ * a repo needs it, and a run reads the same few repos many times.
627
+ */
628
+ async function kemKeyFor(ctx, did) {
629
+ const cacheKey = `did.kem.${did}`;
630
+ const cached = ctx.state.get(cacheKey);
631
+ if (typeof cached === "string") return cached;
632
+ const kem = verificationMethodDidKey(await resolveDidDocument(ctx, did), "atproto_kem");
633
+ if (!kem) throw new Error(`${did} publishes no #atproto_kem key`);
634
+ ctx.state.set(cacheKey, kem);
635
+ return kem;
636
+ }
637
+
638
+ //#endregion
639
+ //#region src/checks/probe.ts
640
+ /**
641
+ * Browser-safe helpers the checks share: probe spaces, operator writes,
642
+ * obtaining a space credential, and presenting it (HTTP signature plus,
643
+ * where the method returns a commit or record, a MAC request).
644
+ *
645
+ * Everything here needs only `fetch` and WebCrypto, so the operator
646
+ * checks — which include the operator's own credential flow — run in a
647
+ * browser as well as in the CLI and the vitest adapter.
648
+ */
649
+ const POST = "earth.cirrus.check.note";
650
+ const note = (text) => ({
651
+ $type: POST,
652
+ text
653
+ });
654
+ const PROBE_TYPE = "earth.cirrus.check.space";
655
+ /**
656
+ * A syntactically valid DID no host serves: the authority of spaces the
657
+ * operator does not own, and the subject of reads of a repo no host holds.
658
+ */
659
+ const FOREIGN_DID = "did:web:space-conformance.invalid";
660
+ const personalspace = () => ({ $type: "com.atproto.personalspace.policy" });
661
+ const memberspace = (config = {}) => ({
662
+ $type: "com.atproto.memberspace.policy",
663
+ ...config
664
+ });
665
+ const managedspace = (managingApp, config = {}) => ({
666
+ $type: "com.atproto.managedspace.policy",
667
+ managingApp,
668
+ ...config
669
+ });
670
+ /** A public-read memberspace: anyone may obtain a credential, no token needed. */
671
+ const publicRead = () => memberspace({ publicRead: true });
672
+ /** A run-unique skey so probe spaces never collide with real ones. */
673
+ function probeSkey() {
674
+ const rand = crypto.getRandomValues(new Uint8Array(8));
675
+ return `probe${Array.from(rand, (b) => b.toString(36)).join("").slice(0, 10)}`;
676
+ }
677
+ /**
678
+ * The prefix of every space URI (`SPACE_URI_PREFIX` of `@atproto/syntax`):
679
+ * since the 2026-11-24 alpha a space is `at:space/{spaceDid}/{spaceType}/{skey}`
680
+ * and a record in it appends `/{authorDid}/{collection}/{rkey}`. There is no
681
+ * `at://` form of a space URI.
682
+ */
683
+ const SPACE_URI_PREFIX = "at:space/";
684
+ /** The space-ref of a space: `at:space/{did}/{type}/{skey}`. */
685
+ const spaceUri = (did, skey, type = PROBE_TYPE) => `${SPACE_URI_PREFIX}${did}/${type}/${skey}`;
686
+ /** The URI of a record in a space: the space-ref plus author/collection/rkey. */
687
+ const spaceRecordUri = (space, author, collection, rkey) => `${space}/${author}/${collection}/${rkey}`;
688
+ /**
689
+ * The pre-2026-11-24 form, `at://{did}/space/{type}/{skey}` — only for
690
+ * probes that a host must now refuse it in a `space` param.
691
+ */
692
+ const legacySpaceUri = (did, skey, type = PROBE_TYPE) => `at://${did}/space/${type}/${skey}`;
693
+ /** A space URI under `did` that nobody has created. */
694
+ const unknownSpaceUri = (did) => spaceUri(did, probeSkey());
695
+ /** The authority DID a space URI names: the first segment after the prefix. */
696
+ const spaceAuthority = (space) => (space.startsWith(SPACE_URI_PREFIX) ? space.slice(9) : space).split("/")[0];
697
+ /**
698
+ * Create a probe space owned by the target's operator. The default policy
699
+ * is a closed memberspace — only the authority can read it.
700
+ */
701
+ async function createProbeSpace(ctx, policy = memberspace(), skey = probeSkey()) {
702
+ const res = await xrpcPost(asOperator(ctx), "com.atproto.space.createSpace", {
703
+ spaceType: PROBE_TYPE,
704
+ skey,
705
+ policy
706
+ });
707
+ if (res.status !== 200) throw new Error(`createSpace failed: ${res.status} ${res.error ?? ""} ${JSON.stringify(res.json)}`);
708
+ const uri = res.json.space;
709
+ if (typeof uri !== "string") throw new Error(`createSpace returned no space: ${JSON.stringify(res.json)}`);
710
+ return {
711
+ uri,
712
+ type: PROBE_TYPE,
713
+ skey
714
+ };
715
+ }
716
+ /** Delete a probe space, best-effort (cleanup). */
717
+ async function deleteProbeSpace(ctx, space) {
718
+ await xrpcPost(asOperator(ctx), "com.atproto.space.deleteSpace", { space }).catch(() => {});
719
+ }
720
+ /** Operator creates a record in a space; returns the response. */
721
+ async function operatorCreateRecord(ctx, space, collection, rkey, record) {
722
+ return xrpcPost(asOperator(ctx), "com.atproto.space.createRecord", {
723
+ space,
724
+ repo: ctx.target.did,
725
+ collection,
726
+ rkey,
727
+ record
728
+ });
729
+ }
730
+ /** Operator write that must succeed (setup, not the thing under test). */
731
+ async function mustCreateRecord(ctx, space, rkey, text = rkey) {
732
+ const res = await operatorCreateRecord(ctx, space, POST, rkey, note(text));
733
+ if (res.status !== 200) throw new Error(`setup createRecord failed: ${res.status} ${res.error ?? ""}`);
734
+ return res.json;
735
+ }
736
+ /** Operator's own read of its repo in a space (no MAC needed or asked). */
737
+ function operatorGetRecord(ctx, space, rkey, collection = POST) {
738
+ return xrpcGet(asOperator(ctx), "com.atproto.space.getRecord", {
739
+ space,
740
+ repo: ctx.target.did,
741
+ collection,
742
+ rkey
743
+ });
744
+ }
745
+ /**
746
+ * Ask the space's authority to authorise sync. Nothing authenticates the
747
+ * request itself: the body carries the key to bind, and optionally a
748
+ * delegation token (who the user is), a client attestation (which app)
749
+ * and a `notify` registration.
750
+ */
751
+ async function requestCredential(ctx, space, opts = {}) {
752
+ const key = opts.key ?? await createCredentialKey();
753
+ const result = await xrpcPost(ctx, "com.atproto.space.authorizeSpaceSync", {
754
+ space,
755
+ credentialKey: opts.credentialKey ?? key.did,
756
+ ...opts.delegationToken ? { delegationToken: opts.delegationToken } : {},
757
+ ...opts.clientAttestation ? { clientAttestation: opts.clientAttestation } : {},
758
+ ...opts.notify ? { notify: opts.notify } : {}
759
+ });
760
+ if (result.status === 200) {
761
+ const body = result.json;
762
+ if (typeof body.credential === "string") return {
763
+ result,
764
+ credential: {
765
+ credential: body.credential,
766
+ key,
767
+ space
768
+ },
769
+ ...typeof body.spaceRev === "string" ? { spaceRev: body.spaceRev } : {}
770
+ };
771
+ }
772
+ return { result };
773
+ }
774
+ /** A tokenless credential for a public-read space; throws if refused. */
775
+ async function obtainPublicCredential(ctx, space) {
776
+ const { result, credential } = await requestCredential(ctx, space);
777
+ if (!credential) throw new Error(`tokenless authorizeSpaceSync for a public-read space failed: ${result.status} ${result.error ?? ""}`);
778
+ return credential;
779
+ }
780
+ /**
781
+ * Obtain a credential the way a real app does: ask the target's own
782
+ * `getDelegationToken` (with the operator session) for a delegation token,
783
+ * then exchange it at `authorizeSpaceSync`. It needs no harness-held
784
+ * reader key, so it runs against any real PDS and exercises the target's
785
+ * own token minting.
786
+ */
787
+ async function obtainCredentialViaDelegation(ctx, space) {
788
+ const delegation = await xrpcGet(asOperator(ctx), "com.atproto.space.getDelegationToken", { space });
789
+ if (delegation.status !== 200) return {
790
+ result: delegation,
791
+ delegation
792
+ };
793
+ const token = delegation.json.token;
794
+ const { result, credential } = await requestCredential(ctx, space, { delegationToken: token });
795
+ return {
796
+ result,
797
+ delegation,
798
+ ...credential ? { credential } : {}
799
+ };
800
+ }
801
+ /** Which MAC profile each repo-host read asks for. */
802
+ const MAC_PROFILES = {
803
+ "com.atproto.space.getLatestCommit": COMMIT_MAC_PROFILE,
804
+ "com.atproto.space.getRepo": COMMIT_MAC_PROFILE,
805
+ "com.atproto.space.listRepoOps": COMMIT_MAC_PROFILE,
806
+ "com.atproto.space.getRecord": RECORD_MAC_PROFILE
807
+ };
808
+ /** Present a credential on one request: signature, audience, MAC request. */
809
+ async function credentialCall(ctx, credential, nsid, opts = {}) {
810
+ const repo = opts.params?.repo;
811
+ const audience = opts.audience ?? repo ?? spaceAuthority(credential.space);
812
+ const authorization = `${opts.scheme ?? SPACE_CREDENTIAL_SCHEME} ${credential.credential}`;
813
+ let sigHeaders = opts.unsigned ? { authorization } : await spaceSigHeaders(opts.signWith ?? credential.key, {
814
+ authorization,
815
+ audience,
816
+ ...opts.signature
817
+ });
818
+ if (opts.signatureHeaders) sigHeaders = await opts.signatureHeaders(sigHeaders);
819
+ const headers = new Headers(sigHeaders);
820
+ let keyShare;
821
+ let sharedSecret;
822
+ let macProfile;
823
+ const mac = opts.mac ?? MAC_PROFILES[nsid];
824
+ if (mac) {
825
+ if (!repo) throw new Error(`${nsid}: a MAC request needs the repo DID`);
826
+ const profile = typeof mac === "string" ? mac : mac.profile;
827
+ const enc = await encapsulate(await kemKeyFor(ctx, repo).catch(async () => (await createCredentialKey()).did));
828
+ headers.set("accept-signature", typeof mac === "object" && "header" in mac ? mac.header(enc.keyShare) : formatMacRequest(profile, enc.keyShare, typeof mac === "object" ? mac : {}));
829
+ keyShare = enc.keyShare;
830
+ sharedSecret = enc.sharedSecret;
831
+ macProfile = profile;
832
+ }
833
+ let response;
834
+ if (opts.body !== void 0) {
835
+ headers.set("Content-Type", "application/json");
836
+ response = await ctx.fetch(xrpcUrl(ctx.target.origin, nsid), {
837
+ method: "POST",
838
+ headers,
839
+ body: JSON.stringify(opts.body)
840
+ });
841
+ } else response = await ctx.fetch(xrpcUrl(ctx.target.origin, nsid, opts.params), {
842
+ method: "GET",
843
+ headers
844
+ });
845
+ return {
846
+ ...await toResult(response),
847
+ ...keyShare ? { keyShare } : {},
848
+ ...sharedSecret ? { sharedSecret } : {},
849
+ ...macProfile ? { macProfile } : {}
850
+ };
851
+ }
852
+ /** A credential-authenticated GET with the default audience and MAC request. */
853
+ function credentialGet(ctx, credential, nsid, params) {
854
+ return credentialCall(ctx, credential, nsid, { params });
855
+ }
856
+ /** Run named probes and fail with every one that missed, not just the first. */
857
+ async function expectEach(probes) {
858
+ const evidence = {};
859
+ const misses = [];
860
+ for (const [name, call, accept] of probes) {
861
+ const res = await call();
862
+ evidence[name] = describe(res);
863
+ if (!accept(res)) misses.push(`${name} → ${describe(res)}`);
864
+ }
865
+ return {
866
+ ok: misses.length === 0,
867
+ detail: misses.join("; "),
868
+ evidence
869
+ };
870
+ }
871
+ const errorIs = (...names) => (r) => r.error !== void 0 && names.includes(r.error);
872
+ /** Summarise a response for a detail line. */
873
+ const describe = (res) => `${res.status}${res.error ? ` ${res.error}` : ""}`;
874
+
875
+ //#endregion
876
+ //#region src/checks/base.ts
877
+ /**
878
+ * Browser-safe checks that need no session: discovery and unauthenticated
879
+ * request shapes. They need only `fetch` — no token minting, no
880
+ * @atproto/space — so they run in any transport, including a browser
881
+ * bundle, against any host the user names.
882
+ */
883
+ const changeset = (ref) => ({
884
+ source: "changeset",
885
+ ref
886
+ });
887
+ const lexicon = (ref) => ({
888
+ source: "lexicon",
889
+ ref
890
+ });
891
+ const proposal = (ref) => ({
892
+ source: "proposal",
893
+ ref
894
+ });
895
+ /** The target's DID document, resolved once per run by its DID method. */
896
+ async function targetDoc(ctx) {
897
+ const cached = ctx.state.get("did.doc.target");
898
+ if (cached) return cached;
899
+ const doc = await resolveDidDocument(ctx, ctx.target.did);
900
+ ctx.state.set("did.doc.target", doc);
901
+ return doc;
902
+ }
903
+ const sameOrigin = (a, b) => {
904
+ try {
905
+ return new URL(a).origin === new URL(b).origin;
906
+ } catch {
907
+ return false;
908
+ }
909
+ };
910
+ const discoveryPdsService = defineCheck({
911
+ id: "discovery.pds-service",
912
+ title: "The authority's #atproto_pds service is the space host",
913
+ tier: "must",
914
+ citations: [proposal("0016#space-authority"), changeset("plain-keys-resolve")],
915
+ needs: [],
916
+ async run(ctx) {
917
+ const doc = await targetDoc(ctx);
918
+ const endpoint = serviceEndpoint(doc, "atproto_pds");
919
+ if (!endpoint) return fail("no #atproto_pds service entry", doc.service);
920
+ 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);
921
+ }
922
+ });
923
+ const discoverySigningKey = defineCheck({
924
+ id: "discovery.signing-key",
925
+ title: "The DID document exposes the #atproto key that signs space tokens",
926
+ tier: "must",
927
+ citations: [proposal("0016#space-authority"), changeset("plain-keys-resolve")],
928
+ needs: [],
929
+ async run(ctx) {
930
+ const doc = await targetDoc(ctx);
931
+ const key = verificationMethodDidKey(doc, "atproto");
932
+ return key ? pass(`#atproto is ${key}`) : fail("no usable #atproto verification method", doc.verificationMethod);
933
+ }
934
+ });
935
+ const discoveryKemKey = defineCheck({
936
+ id: "discovery.kem-key",
937
+ title: "The DID document publishes a P-256 #atproto_kem key",
938
+ tier: "must",
939
+ citations: [proposal("0016#kem-key"), lexicon("com.atproto.space.getLatestCommit")],
940
+ needs: [],
941
+ async run(ctx) {
942
+ const doc = await targetDoc(ctx);
943
+ const key = verificationMethodDidKey(doc, "atproto_kem");
944
+ if (!key) return fail("no #atproto_kem verification method", doc.verificationMethod);
945
+ if (!isP256DidKey(key)) return fail(`#atproto_kem is not a P-256 key: ${key}`);
946
+ const entry = (doc.verificationMethod ?? []).find((m) => m.id.endsWith("#atproto_kem"));
947
+ const problems = [];
948
+ if (entry.type !== "Multikey") problems.push(`type ${entry.type}`);
949
+ if (entry.controller !== doc.id) problems.push(`controller ${entry.controller}`);
950
+ return problems.length ? fail(`#atproto_kem entry: ${problems.join(", ")}`, entry) : pass(`#atproto_kem is ${key}`);
951
+ }
952
+ });
953
+ const discoveryLegacyEntries = defineCheck({
954
+ id: "discovery.legacy-space-entries",
955
+ title: "Reports any pre-alpha #atproto_space / #atproto_space_host entries",
956
+ tier: "info",
957
+ citations: [changeset("plain-keys-resolve")],
958
+ needs: [],
959
+ async run(ctx) {
960
+ const doc = await targetDoc(ctx);
961
+ const legacy = [...(doc.verificationMethod ?? []).map((m) => m.id), ...(doc.service ?? []).map((s) => s.id)].filter((id) => /#atproto_space(_host)?$/.test(id));
962
+ return pass(legacy.length ? `still publishes ${legacy.join(", ")} (ignored by the alpha)` : "no legacy space entries");
963
+ }
964
+ });
965
+ const authGetRecordRequiresAuth = defineCheck({
966
+ id: "auth.getrecord-unauthenticated-refused",
967
+ title: "space.getRecord refuses an unauthenticated request",
968
+ tier: "must",
969
+ citations: [lexicon("com.atproto.space.getRecord")],
970
+ needs: [],
971
+ async run(ctx) {
972
+ const res = await xrpcGet(ctx, "com.atproto.space.getRecord", {
973
+ space: spaceUri(ctx.target.did, "probe"),
974
+ repo: ctx.target.did,
975
+ collection: "app.bsky.feed.post",
976
+ rkey: "whatever"
977
+ });
978
+ if (res.status === 401 || res.status === 403) return pass(`refused with ${res.status}`);
979
+ return fail(`unauthenticated read was not refused with 401/403 (got ${describe(res)})`, res.json);
980
+ }
981
+ });
982
+ const credentialTokenlessUnknown = defineCheck({
983
+ id: "credential.tokenless-unknown-space",
984
+ title: "A tokenless credential request for an unknown space gets SpaceNotFound",
985
+ tier: "must",
986
+ citations: [lexicon("com.atproto.space.authorizeSpaceSync@error:SpaceNotFound")],
987
+ needs: [],
988
+ async run(ctx) {
989
+ const key = await createCredentialKey();
990
+ const res = await xrpcPost(ctx, "com.atproto.space.authorizeSpaceSync", {
991
+ space: unknownSpaceUri(ctx.target.did),
992
+ credentialKey: key.did
993
+ });
994
+ if (res.status === 200) return fail("issued a credential for an unknown space");
995
+ return res.error === "SpaceNotFound" ? pass("refused with SpaceNotFound") : fail(`refused with ${describe(res)}, expected SpaceNotFound`, res.json);
996
+ }
997
+ });
998
+ /** Checks that need no crypto and no session — safe in any transport. */
999
+ const baseChecks = [
1000
+ discoveryPdsService,
1001
+ discoverySigningKey,
1002
+ discoveryKemKey,
1003
+ discoveryLegacyEntries,
1004
+ authGetRecordRequiresAuth,
1005
+ credentialTokenlessUnknown
1006
+ ];
1007
+
1008
+ //#endregion
1009
+ //#region src/checks/space.ts
1010
+ /**
1011
+ * Space management and the baseline policies: createSpace / updateSpace /
1012
+ * deleteSpace / getSpace / listSpaces, and the memberspace member list.
1013
+ * Operator-only and browser-safe.
1014
+ */
1015
+ const L$4 = (ref) => ({
1016
+ source: "lexicon",
1017
+ ref
1018
+ });
1019
+ const C$3 = (ref) => ({
1020
+ source: "changeset",
1021
+ ref
1022
+ });
1023
+ const P$4 = (ref) => ({
1024
+ source: "proposal",
1025
+ ref
1026
+ });
1027
+ /** A syntactically valid did:plc nobody registered — a member to list. */
1028
+ function fakeDid() {
1029
+ return `did:plc:${toBase32(crypto.getRandomValues(new Uint8Array(15))).slice(0, 24)}`;
1030
+ }
1031
+ const op$1 = asOperator;
1032
+ const putMembers = (ctx, space, members) => xrpcPost(op$1(ctx), "com.atproto.memberspace.putMembers", {
1033
+ space,
1034
+ members
1035
+ });
1036
+ const removeMembers = (ctx, space, dids) => xrpcPost(op$1(ctx), "com.atproto.memberspace.removeMembers", {
1037
+ space,
1038
+ dids
1039
+ });
1040
+ async function listMembers(ctx, space) {
1041
+ const res = await xrpcGet(op$1(ctx), "com.atproto.memberspace.listMembers", {
1042
+ space,
1043
+ limit: "100"
1044
+ });
1045
+ if (res.status !== 200) throw new Error(`listMembers ${describe(res)}`);
1046
+ return res.json.members ?? [];
1047
+ }
1048
+ const spaceCreateAndGet = defineCheck({
1049
+ id: "space.create-and-get",
1050
+ title: "createSpace anchors the space on the operator at an at:space/ ref and getSpace describes it",
1051
+ tier: "must",
1052
+ citations: [
1053
+ L$4("com.atproto.space.createSpace"),
1054
+ L$4("com.atproto.space.getSpace"),
1055
+ P$4("0016#addressing"),
1056
+ C$3("spaces-syntax"),
1057
+ C$3("pds-space-uri-migration")
1058
+ ],
1059
+ needs: ["operator"],
1060
+ destructive: true,
1061
+ async run(ctx) {
1062
+ const skey = probeSkey();
1063
+ const res = await xrpcPost(op$1(ctx), "com.atproto.space.createSpace", {
1064
+ spaceType: PROBE_TYPE,
1065
+ skey,
1066
+ policy: memberspace()
1067
+ });
1068
+ if (res.status !== 200) return fail(`createSpace ${describe(res)}`, res.json);
1069
+ const uri = res.json.space;
1070
+ try {
1071
+ const expected = spaceUri(ctx.target.did, skey);
1072
+ if (uri !== expected) return fail(`createSpace returned space ${uri}, expected ${expected}`, res.json);
1073
+ const got = await xrpcGet(op$1(ctx), "com.atproto.space.getSpace", { space: uri });
1074
+ if (got.status !== 200) return fail(`getSpace ${describe(got)}`, got.json);
1075
+ const body = got.json;
1076
+ if (body.space !== uri) return fail(`getSpace space was ${body.space}`, got.json);
1077
+ if (body.policy?.$type !== "com.atproto.memberspace.policy") return fail(`getSpace policy was ${body.policy?.$type}`, got.json);
1078
+ return body.policy.publicRead === true ? fail("a memberspace created without publicRead reports publicRead: true") : pass("created at the expected at:space/ ref; getSpace reports the memberspace policy");
1079
+ } finally {
1080
+ if (uri) await deleteProbeSpace(ctx, uri);
1081
+ }
1082
+ }
1083
+ });
1084
+ const spaceGeneratedSkey = defineCheck({
1085
+ id: "space.create-generates-skey",
1086
+ title: "createSpace without an skey generates a TID",
1087
+ tier: "must",
1088
+ citations: [L$4("com.atproto.space.createSpace")],
1089
+ needs: ["operator"],
1090
+ destructive: true,
1091
+ async run(ctx) {
1092
+ const res = await xrpcPost(op$1(ctx), "com.atproto.space.createSpace", {
1093
+ spaceType: PROBE_TYPE,
1094
+ policy: personalspace()
1095
+ });
1096
+ if (res.status !== 200) return fail(`createSpace ${describe(res)}`, res.json);
1097
+ const uri = res.json.space;
1098
+ await deleteProbeSpace(ctx, uri);
1099
+ const skey = uri?.split("/").at(-1);
1100
+ return isTid(skey) ? pass(`generated skey ${skey}`) : fail(`generated skey ${skey} is not a TID`);
1101
+ }
1102
+ });
1103
+ const spaceDuplicate = defineCheck({
1104
+ id: "space.duplicate-refused",
1105
+ title: "Creating an existing space is refused with SpaceAlreadyExists",
1106
+ tier: "must",
1107
+ citations: [L$4("com.atproto.space.createSpace@error:SpaceAlreadyExists")],
1108
+ needs: ["operator"],
1109
+ destructive: true,
1110
+ async run(ctx) {
1111
+ const space = await createProbeSpace(ctx, personalspace());
1112
+ try {
1113
+ const again = await xrpcPost(op$1(ctx), "com.atproto.space.createSpace", {
1114
+ spaceType: PROBE_TYPE,
1115
+ skey: space.skey,
1116
+ policy: personalspace()
1117
+ });
1118
+ if (again.status === 200) return fail("a second createSpace at the same skey returned 200");
1119
+ return again.error === "SpaceAlreadyExists" ? pass("refused with SpaceAlreadyExists") : fail(`refused with ${describe(again)}, expected SpaceAlreadyExists`, again.json);
1120
+ } finally {
1121
+ await deleteProbeSpace(ctx, space.uri);
1122
+ }
1123
+ }
1124
+ });
1125
+ const spaceRecreate = defineCheck({
1126
+ id: "space.recreate-after-delete",
1127
+ title: "A deleted space may be created again",
1128
+ tier: "must",
1129
+ citations: [P$4("0016#space-deletion"), L$4("com.atproto.space.createSpace")],
1130
+ needs: ["operator"],
1131
+ destructive: true,
1132
+ async run(ctx) {
1133
+ const space = await createProbeSpace(ctx, personalspace());
1134
+ await deleteProbeSpace(ctx, space.uri);
1135
+ const again = await xrpcPost(op$1(ctx), "com.atproto.space.createSpace", {
1136
+ spaceType: PROBE_TYPE,
1137
+ skey: space.skey,
1138
+ policy: personalspace()
1139
+ });
1140
+ await deleteProbeSpace(ctx, space.uri);
1141
+ return again.status === 200 ? pass("re-created the deleted space") : fail(`re-creating a deleted space returned ${describe(again)}`, again.json);
1142
+ }
1143
+ });
1144
+ const spaceUnsupportedPolicy = defineCheck({
1145
+ id: "space.unsupported-policy-rejected",
1146
+ title: "createSpace and updateSpace refuse a policy the host does not implement",
1147
+ tier: "must",
1148
+ citations: [
1149
+ L$4("com.atproto.space.createSpace@error:UnsupportedPolicy"),
1150
+ L$4("com.atproto.space.updateSpace@error:UnsupportedPolicy"),
1151
+ P$4("0016#space-policy")
1152
+ ],
1153
+ needs: ["operator"],
1154
+ destructive: true,
1155
+ async run(ctx) {
1156
+ const mystery = { $type: "com.example.mysteryPolicy" };
1157
+ const space = await createProbeSpace(ctx, personalspace());
1158
+ let created;
1159
+ try {
1160
+ const result = await expectEach([[
1161
+ "createSpace",
1162
+ async () => {
1163
+ const res = await xrpcPost(op$1(ctx), "com.atproto.space.createSpace", {
1164
+ spaceType: PROBE_TYPE,
1165
+ skey: probeSkey(),
1166
+ policy: mystery
1167
+ });
1168
+ if (res.status === 200) created = res.json.space;
1169
+ return res;
1170
+ },
1171
+ errorIs("UnsupportedPolicy")
1172
+ ], [
1173
+ "updateSpace",
1174
+ () => xrpcPost(op$1(ctx), "com.atproto.space.updateSpace", {
1175
+ space: space.uri,
1176
+ policy: mystery
1177
+ }),
1178
+ errorIs("UnsupportedPolicy")
1179
+ ]]);
1180
+ return result.ok ? pass("both refused with UnsupportedPolicy") : fail(`expected UnsupportedPolicy: ${result.detail}`, result.evidence);
1181
+ } finally {
1182
+ await deleteProbeSpace(ctx, space.uri);
1183
+ if (created) await deleteProbeSpace(ctx, created);
1184
+ }
1185
+ }
1186
+ });
1187
+ const spaceUpdateReplaces = defineCheck({
1188
+ id: "space.update-replaces-policy",
1189
+ title: "updateSpace replaces the policy wholesale; a type change discards member state",
1190
+ tier: "must",
1191
+ citations: [
1192
+ L$4("com.atproto.space.updateSpace"),
1193
+ L$4("com.atproto.space.getSpace"),
1194
+ L$4("com.atproto.memberspace.listMembers"),
1195
+ P$4("0016#space-policy")
1196
+ ],
1197
+ needs: ["operator"],
1198
+ destructive: true,
1199
+ async run(ctx) {
1200
+ const space = await createProbeSpace(ctx, memberspace());
1201
+ const member = fakeDid();
1202
+ const policyOf = async () => (await xrpcGet(op$1(ctx), "com.atproto.space.getSpace", { space: space.uri })).json?.policy;
1203
+ const update = (policy) => xrpcPost(op$1(ctx), "com.atproto.space.updateSpace", {
1204
+ space: space.uri,
1205
+ policy
1206
+ });
1207
+ try {
1208
+ await putMembers(ctx, space.uri, [{
1209
+ did: member,
1210
+ read: true,
1211
+ write: false
1212
+ }]);
1213
+ const same = await update(memberspace({ publicRead: true }));
1214
+ if (same.status !== 200) return fail(`updateSpace (config) ${describe(same)}`, same.json);
1215
+ if ((await policyOf())?.publicRead !== true) return fail("getSpace does not reflect publicRead: true");
1216
+ if (!(await listMembers(ctx, space.uri)).some((m) => m.did === member)) return fail("a same-type update dropped the member list");
1217
+ const migrate = await update(personalspace());
1218
+ if (migrate.status !== 200) return fail(`updateSpace (migrate) ${describe(migrate)}`, migrate.json);
1219
+ const p2 = await policyOf();
1220
+ if (p2?.$type !== "com.atproto.personalspace.policy") return fail(`after migration getSpace reports ${p2?.$type}`, p2);
1221
+ const back = await update(memberspace());
1222
+ if (back.status !== 200) return fail(`updateSpace (back) ${describe(back)}`, back.json);
1223
+ 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");
1224
+ } finally {
1225
+ await deleteProbeSpace(ctx, space.uri);
1226
+ }
1227
+ }
1228
+ });
1229
+ const spaceNotAuthority = defineCheck({
1230
+ id: "space.not-authority-refused",
1231
+ title: "Managing a space anchored on another DID is refused with NotAuthorized",
1232
+ tier: "must",
1233
+ citations: [
1234
+ L$4("com.atproto.space.deleteSpace@error:NotAuthorized"),
1235
+ L$4("com.atproto.space.updateSpace@error:NotAuthorized"),
1236
+ L$4("com.atproto.space.getSpace@error:NotAuthorized"),
1237
+ L$4("com.atproto.space.removeWriter@error:NotAuthorized"),
1238
+ L$4("com.atproto.space.exportSpaceMeta@error:NotAuthorized"),
1239
+ L$4("com.atproto.memberspace.putMembers@error:NotAuthorized"),
1240
+ L$4("com.atproto.memberspace.removeMembers@error:NotAuthorized"),
1241
+ L$4("com.atproto.memberspace.listMembers@error:NotAuthorized")
1242
+ ],
1243
+ needs: ["operator"],
1244
+ async run(ctx) {
1245
+ const space = unknownSpaceUri(FOREIGN_DID);
1246
+ const did = fakeDid();
1247
+ const na = errorIs("NotAuthorized");
1248
+ const result = await expectEach([
1249
+ [
1250
+ "deleteSpace",
1251
+ () => xrpcPost(op$1(ctx), "com.atproto.space.deleteSpace", { space }),
1252
+ na
1253
+ ],
1254
+ [
1255
+ "updateSpace",
1256
+ () => xrpcPost(op$1(ctx), "com.atproto.space.updateSpace", {
1257
+ space,
1258
+ policy: personalspace()
1259
+ }),
1260
+ na
1261
+ ],
1262
+ [
1263
+ "getSpace",
1264
+ () => xrpcGet(op$1(ctx), "com.atproto.space.getSpace", { space }),
1265
+ na
1266
+ ],
1267
+ [
1268
+ "removeWriter",
1269
+ () => xrpcPost(op$1(ctx), "com.atproto.space.removeWriter", {
1270
+ space,
1271
+ repo: did
1272
+ }),
1273
+ na
1274
+ ],
1275
+ [
1276
+ "exportSpaceMeta",
1277
+ () => xrpcGet(op$1(ctx), "com.atproto.space.exportSpaceMeta", { space }),
1278
+ na
1279
+ ],
1280
+ [
1281
+ "putMembers",
1282
+ () => putMembers(ctx, space, [{
1283
+ did,
1284
+ read: true,
1285
+ write: true
1286
+ }]),
1287
+ na
1288
+ ],
1289
+ [
1290
+ "removeMembers",
1291
+ () => removeMembers(ctx, space, [did]),
1292
+ na
1293
+ ],
1294
+ [
1295
+ "listMembers",
1296
+ () => xrpcGet(op$1(ctx), "com.atproto.memberspace.listMembers", { space }),
1297
+ na
1298
+ ]
1299
+ ]);
1300
+ return result.ok ? pass("every authority-only method answered NotAuthorized") : fail(`expected NotAuthorized: ${result.detail}`, result.evidence);
1301
+ }
1302
+ });
1303
+ const spaceUnknown = defineCheck({
1304
+ id: "space.unknown-space-not-found",
1305
+ title: "Managing an own space that does not exist answers SpaceNotFound",
1306
+ tier: "must",
1307
+ citations: [
1308
+ L$4("com.atproto.space.getSpace@error:SpaceNotFound"),
1309
+ L$4("com.atproto.space.updateSpace@error:SpaceNotFound"),
1310
+ L$4("com.atproto.space.deleteSpace@error:SpaceNotFound"),
1311
+ L$4("com.atproto.space.exportSpaceMeta@error:SpaceNotFound"),
1312
+ L$4("com.atproto.space.removeWriter@error:SpaceNotFound"),
1313
+ L$4("com.atproto.memberspace.putMembers@error:SpaceNotFound"),
1314
+ L$4("com.atproto.memberspace.removeMembers@error:SpaceNotFound"),
1315
+ L$4("com.atproto.memberspace.listMembers@error:SpaceNotFound")
1316
+ ],
1317
+ needs: ["operator"],
1318
+ async run(ctx) {
1319
+ const space = unknownSpaceUri(ctx.target.did);
1320
+ const did = fakeDid();
1321
+ const nf = errorIs("SpaceNotFound");
1322
+ const result = await expectEach([
1323
+ [
1324
+ "getSpace",
1325
+ () => xrpcGet(op$1(ctx), "com.atproto.space.getSpace", { space }),
1326
+ nf
1327
+ ],
1328
+ [
1329
+ "updateSpace",
1330
+ () => xrpcPost(op$1(ctx), "com.atproto.space.updateSpace", {
1331
+ space,
1332
+ policy: personalspace()
1333
+ }),
1334
+ nf
1335
+ ],
1336
+ [
1337
+ "deleteSpace",
1338
+ () => xrpcPost(op$1(ctx), "com.atproto.space.deleteSpace", { space }),
1339
+ nf
1340
+ ],
1341
+ [
1342
+ "exportSpaceMeta",
1343
+ () => xrpcGet(op$1(ctx), "com.atproto.space.exportSpaceMeta", { space }),
1344
+ nf
1345
+ ],
1346
+ [
1347
+ "removeWriter",
1348
+ () => xrpcPost(op$1(ctx), "com.atproto.space.removeWriter", {
1349
+ space,
1350
+ repo: did
1351
+ }),
1352
+ nf
1353
+ ],
1354
+ [
1355
+ "putMembers",
1356
+ () => putMembers(ctx, space, [{
1357
+ did,
1358
+ read: true,
1359
+ write: false
1360
+ }]),
1361
+ nf
1362
+ ],
1363
+ [
1364
+ "removeMembers",
1365
+ () => removeMembers(ctx, space, [did]),
1366
+ nf
1367
+ ],
1368
+ [
1369
+ "listMembers",
1370
+ () => xrpcGet(op$1(ctx), "com.atproto.memberspace.listMembers", { space }),
1371
+ nf
1372
+ ]
1373
+ ]);
1374
+ return result.ok ? pass("every method answered SpaceNotFound") : fail(`expected SpaceNotFound: ${result.detail}`, result.evidence);
1375
+ }
1376
+ });
1377
+ const spaceDeleteIdempotent = defineCheck({
1378
+ id: "space.delete-idempotent",
1379
+ title: "Deleting an already-deleted space succeeds",
1380
+ tier: "should",
1381
+ citations: [{
1382
+ source: "reference",
1383
+ ref: "pds deleteSpace returns early for a tombstoned space"
1384
+ }, L$4("com.atproto.space.deleteSpace")],
1385
+ needs: ["operator"],
1386
+ destructive: true,
1387
+ async run(ctx) {
1388
+ const space = await createProbeSpace(ctx, personalspace());
1389
+ const first = await xrpcPost(op$1(ctx), "com.atproto.space.deleteSpace", { space: space.uri });
1390
+ const second = await xrpcPost(op$1(ctx), "com.atproto.space.deleteSpace", { space: space.uri });
1391
+ return first.status === 200 && second.status === 200 ? pass("both deletes returned 200") : fail(`deletes returned ${describe(first)} then ${describe(second)}`);
1392
+ }
1393
+ });
1394
+ const spaceListSpaces = defineCheck({
1395
+ id: "space.listspaces-filters",
1396
+ title: "listSpaces lists the operator's spaces with its repo state, honouring spaceType and spaceDid",
1397
+ tier: "must",
1398
+ citations: [
1399
+ L$4("com.atproto.space.listSpaces"),
1400
+ L$4("com.atproto.space.listSpaces#spaceView"),
1401
+ C$3("pds-space-uri-migration")
1402
+ ],
1403
+ needs: ["operator"],
1404
+ destructive: true,
1405
+ async run(ctx) {
1406
+ const space = await createProbeSpace(ctx, personalspace());
1407
+ try {
1408
+ await mustCreateRecord(ctx, space.uri, "a");
1409
+ const seen = [];
1410
+ let cursor;
1411
+ for (let page = 0; page < 20; page++) {
1412
+ const res = await xrpcGet(op$1(ctx), "com.atproto.space.listSpaces", {
1413
+ spaceType: PROBE_TYPE,
1414
+ spaceDid: ctx.target.did,
1415
+ limit: "100",
1416
+ cursor
1417
+ });
1418
+ if (res.status !== 200) return fail(`listSpaces ${describe(res)}`, res.json);
1419
+ const body = res.json;
1420
+ seen.push(...body.spaces ?? []);
1421
+ cursor = body.cursor;
1422
+ if (!cursor || seen.some((s) => s.space === space.uri)) break;
1423
+ }
1424
+ const entry = seen.find((s) => s.space === space.uri);
1425
+ if (!entry) return fail("listSpaces did not list the new space");
1426
+ const stray = seen.filter((s) => !s.space.startsWith(spaceUri(ctx.target.did, "")));
1427
+ if (stray.length) return fail(`listing included spaces outside the filter (or not as at:space/${ctx.target.did}/${PROBE_TYPE}/… refs): ${stray.map((s) => s.space).join(", ")}`);
1428
+ const commit = (await xrpcGet(op$1(ctx), "com.atproto.space.getLatestCommit", {
1429
+ space: space.uri,
1430
+ repo: ctx.target.did
1431
+ })).json?.commit;
1432
+ const a = lexBytes(entry.data);
1433
+ const b = lexBytes(commit?.data);
1434
+ const problems = [];
1435
+ if (entry.repoRev !== commit?.rev) problems.push(`repoRev ${entry.repoRev} ≠ commit rev ${commit?.rev}`);
1436
+ if (!a || !b || !bytesEqual(a, b)) problems.push("data does not match the commit");
1437
+ if (!isTid(entry.spaceRev)) problems.push(`no spaceRev for a space the caller is authority of`);
1438
+ return problems.length ? fail(problems.join("; "), entry) : pass("listed with the operator's repoRev, data and the spaceRev");
1439
+ } finally {
1440
+ await deleteProbeSpace(ctx, space.uri);
1441
+ }
1442
+ }
1443
+ });
1444
+ const spaceOwnerStateNotByCredential = defineCheck({
1445
+ id: "space.owner-state-not-by-credential",
1446
+ title: "A space credential does not reach getSpace, listMembers or exportSpaceMeta",
1447
+ tier: "must",
1448
+ citations: [
1449
+ L$4("com.atproto.space.getSpace"),
1450
+ L$4("com.atproto.memberspace.listMembers"),
1451
+ L$4("com.atproto.space.exportSpaceMeta")
1452
+ ],
1453
+ needs: ["operator"],
1454
+ destructive: true,
1455
+ async run(ctx) {
1456
+ const space = await createProbeSpace(ctx, publicRead());
1457
+ try {
1458
+ const credential = await obtainPublicCredential(ctx, space.uri);
1459
+ const call = (nsid) => credentialCall(ctx, credential, nsid, {
1460
+ params: { space: space.uri },
1461
+ audience: ctx.target.did
1462
+ });
1463
+ const isRefusal = (r) => r.status >= 400 && r.status < 500;
1464
+ const result = await expectEach([
1465
+ [
1466
+ "getSpace",
1467
+ () => call("com.atproto.space.getSpace"),
1468
+ isRefusal
1469
+ ],
1470
+ [
1471
+ "listMembers",
1472
+ () => call("com.atproto.memberspace.listMembers"),
1473
+ isRefusal
1474
+ ],
1475
+ [
1476
+ "exportSpaceMeta",
1477
+ () => call("com.atproto.space.exportSpaceMeta"),
1478
+ isRefusal
1479
+ ]
1480
+ ]);
1481
+ return result.ok ? pass(`all refused (${Object.values(result.evidence).join(", ")})`) : fail(`expected a 4xx refusal: ${result.detail}`, result.evidence);
1482
+ } finally {
1483
+ await deleteProbeSpace(ctx, space.uri);
1484
+ }
1485
+ }
1486
+ });
1487
+ const managedBareDid = defineCheck({
1488
+ id: "managedspace.bare-did-rejected",
1489
+ title: "A managedspace whose managingApp is not a did#serviceId reference is refused",
1490
+ tier: "must",
1491
+ citations: [L$4("com.atproto.managedspace.policy"), C$3("tidy-spaces-settle")],
1492
+ needs: ["operator"],
1493
+ destructive: true,
1494
+ async run(ctx) {
1495
+ const create$1 = (managingApp) => xrpcPost(op$1(ctx), "com.atproto.space.createSpace", {
1496
+ spaceType: PROBE_TYPE,
1497
+ skey: probeSkey(),
1498
+ policy: managedspace(managingApp)
1499
+ });
1500
+ const ok = await create$1(`${FOREIGN_DID}#managing_app`);
1501
+ if (ok.status !== 200) return fail(`positive control failed: a managedspace naming a did#serviceId was refused (${describe(ok)})`, ok.json);
1502
+ await deleteProbeSpace(ctx, ok.json.space);
1503
+ const res = await create$1(FOREIGN_DID);
1504
+ if (res.status === 200) {
1505
+ await deleteProbeSpace(ctx, res.json.space);
1506
+ return fail("created a managedspace whose managingApp is a bare DID");
1507
+ }
1508
+ return res.status === 400 && res.error === "InvalidRequest" ? pass("a did#serviceId was accepted; a bare DID refused with InvalidRequest") : fail(`answered ${describe(res)}, expected 400 InvalidRequest`, res.json);
1509
+ }
1510
+ });
1511
+ const memberRoundTrip = defineCheck({
1512
+ id: "memberspace.member-round-trip",
1513
+ title: "putMembers and removeMembers apply batches; listMembers follows",
1514
+ tier: "must",
1515
+ citations: [
1516
+ L$4("com.atproto.memberspace.putMembers"),
1517
+ L$4("com.atproto.memberspace.listMembers"),
1518
+ L$4("com.atproto.memberspace.removeMembers"),
1519
+ L$4("com.atproto.memberspace.defs#member"),
1520
+ C$3("tidy-spaces-settle")
1521
+ ],
1522
+ needs: ["operator"],
1523
+ destructive: true,
1524
+ async run(ctx) {
1525
+ const space = await createProbeSpace(ctx, memberspace());
1526
+ const [a, b] = [fakeDid(), fakeDid()];
1527
+ const find = (members, did) => members.find((m) => m.did === did);
1528
+ try {
1529
+ const put = await putMembers(ctx, space.uri, [
1530
+ {
1531
+ did: a,
1532
+ read: false,
1533
+ write: false
1534
+ },
1535
+ {
1536
+ did: b,
1537
+ read: true,
1538
+ write: true
1539
+ },
1540
+ {
1541
+ did: a,
1542
+ read: true,
1543
+ write: false
1544
+ }
1545
+ ]);
1546
+ if (put.status !== 200) return fail(`putMembers ${describe(put)}`, put.json);
1547
+ const listed = await listMembers(ctx, space.uri);
1548
+ const ma = find(listed, a);
1549
+ const mb = find(listed, b);
1550
+ if (!ma || ma.read !== true || ma.write !== false) return fail(`a duplicated DID did not take its last entry: ${JSON.stringify(ma)}`);
1551
+ if (!mb || mb.read !== true || mb.write !== true) return fail(`second member: ${JSON.stringify(mb)}`);
1552
+ await putMembers(ctx, space.uri, [{
1553
+ did: b,
1554
+ read: false,
1555
+ write: true
1556
+ }]);
1557
+ const mb2 = find(await listMembers(ctx, space.uri), b);
1558
+ if (!mb2 || mb2.read !== false || mb2.write !== true) return fail(`putMembers did not replace access: ${JSON.stringify(mb2)}`);
1559
+ const removed = await removeMembers(ctx, space.uri, [
1560
+ a,
1561
+ b,
1562
+ fakeDid()
1563
+ ]);
1564
+ if (removed.status !== 200) return fail(`removeMembers ${describe(removed)}`, removed.json);
1565
+ const left = await listMembers(ctx, space.uri);
1566
+ 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)");
1567
+ } finally {
1568
+ await deleteProbeSpace(ctx, space.uri);
1569
+ }
1570
+ }
1571
+ });
1572
+ const memberPolicyMismatch = defineCheck({
1573
+ id: "memberspace.policy-mismatch",
1574
+ title: "Member methods on a non-memberspace answer PolicyMismatch",
1575
+ tier: "must",
1576
+ citations: [
1577
+ L$4("com.atproto.memberspace.putMembers@error:PolicyMismatch"),
1578
+ L$4("com.atproto.memberspace.removeMembers@error:PolicyMismatch"),
1579
+ L$4("com.atproto.memberspace.listMembers@error:PolicyMismatch")
1580
+ ],
1581
+ needs: ["operator"],
1582
+ destructive: true,
1583
+ async run(ctx) {
1584
+ const space = await createProbeSpace(ctx, personalspace());
1585
+ const did = fakeDid();
1586
+ const mm = errorIs("PolicyMismatch");
1587
+ try {
1588
+ const result = await expectEach([
1589
+ [
1590
+ "putMembers",
1591
+ () => putMembers(ctx, space.uri, [{
1592
+ did,
1593
+ read: true,
1594
+ write: true
1595
+ }]),
1596
+ mm
1597
+ ],
1598
+ [
1599
+ "removeMembers",
1600
+ () => removeMembers(ctx, space.uri, [did]),
1601
+ mm
1602
+ ],
1603
+ [
1604
+ "listMembers",
1605
+ () => xrpcGet(op$1(ctx), "com.atproto.memberspace.listMembers", { space: space.uri }),
1606
+ mm
1607
+ ]
1608
+ ]);
1609
+ return result.ok ? pass("all three answered PolicyMismatch on a personalspace") : fail(`expected PolicyMismatch: ${result.detail}`, result.evidence);
1610
+ } finally {
1611
+ await deleteProbeSpace(ctx, space.uri);
1612
+ }
1613
+ }
1614
+ });
1615
+ const memberPublish = defineCheck({
1616
+ id: "memberspace.publish-policy-and-members",
1617
+ title: "publishPolicy / publishMembers keep policy and member records in the authority's repo",
1618
+ tier: "must",
1619
+ citations: [
1620
+ L$4("com.atproto.memberspace.policy"),
1621
+ L$4("com.atproto.space.policy"),
1622
+ L$4("com.atproto.memberspace.member"),
1623
+ P$4("0016#publishing-to-readers")
1624
+ ],
1625
+ needs: ["operator"],
1626
+ destructive: true,
1627
+ async run(ctx) {
1628
+ const space = await createProbeSpace(ctx, memberspace({
1629
+ publishPolicy: true,
1630
+ publishMembers: true
1631
+ }));
1632
+ const member = fakeDid();
1633
+ try {
1634
+ const policy = await operatorGetRecord(ctx, space.uri, "self", "com.atproto.space.policy");
1635
+ if (policy.status !== 200) return fail(`no com.atproto.space.policy/self record: ${describe(policy)}`, policy.json);
1636
+ const published = policy.json.value?.policy;
1637
+ 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);
1638
+ await putMembers(ctx, space.uri, [{
1639
+ did: member,
1640
+ read: true,
1641
+ write: false
1642
+ }]);
1643
+ const rec = await operatorGetRecord(ctx, space.uri, member, "com.atproto.memberspace.member");
1644
+ const value = rec.json?.value;
1645
+ if (rec.status !== 200 || value?.read !== true || value.write !== false) return fail(`member record after putMembers: ${describe(rec)}`, rec.json);
1646
+ await removeMembers(ctx, space.uri, [member]);
1647
+ const gone = await operatorGetRecord(ctx, space.uri, member, "com.atproto.memberspace.member");
1648
+ return gone.status === 200 ? fail("the member record outlived removeMembers", gone.json) : pass("policy record published; member record tracked putMembers and removeMembers");
1649
+ } finally {
1650
+ await deleteProbeSpace(ctx, space.uri);
1651
+ }
1652
+ }
1653
+ });
1654
+ const spaceChecks = [
1655
+ spaceCreateAndGet,
1656
+ spaceGeneratedSkey,
1657
+ spaceDuplicate,
1658
+ spaceRecreate,
1659
+ spaceUnsupportedPolicy,
1660
+ spaceUpdateReplaces,
1661
+ spaceNotAuthority,
1662
+ spaceUnknown,
1663
+ spaceDeleteIdempotent,
1664
+ spaceListSpaces,
1665
+ spaceOwnerStateNotByCredential,
1666
+ managedBareDid,
1667
+ memberRoundTrip,
1668
+ memberPolicyMismatch,
1669
+ memberPublish
1670
+ ];
1671
+
1672
+ //#endregion
1673
+ //#region src/checks/credential.ts
1674
+ /**
1675
+ * Space credentials, operator-side: issuance through authorizeSpaceSync
1676
+ * (tokenless for public-read spaces, via the target's own delegation
1677
+ * tokens otherwise), the refusals it declares, and presentation — the
1678
+ * HTTP message signature, the audience binding and the MAC request every
1679
+ * credentialed read of a commit or record must carry.
1680
+ *
1681
+ * All browser-safe: credential keys, signatures and HPKE key shares are
1682
+ * WebCrypto (see ../space-auth.ts). Verifying the MACs that come back
1683
+ * needs the reference library and lives in ../full/checks.ts.
1684
+ */
1685
+ const L$3 = (ref) => ({
1686
+ source: "lexicon",
1687
+ ref
1688
+ });
1689
+ const P$3 = (ref) => ({
1690
+ source: "proposal",
1691
+ ref
1692
+ });
1693
+ const C$2 = (ref) => ({
1694
+ source: "changeset",
1695
+ ref
1696
+ });
1697
+ /** Refusals the lexicon allows for an account the policy does not authorise. */
1698
+ const ACCOUNT_REFUSALS$1 = [
1699
+ "SpaceNotFound",
1700
+ "AccountNotAuthorized",
1701
+ "NotAuthorized"
1702
+ ];
1703
+ /** A public-read probe space holding one record, plus a tokenless credential for it. */
1704
+ async function withPublicSpace(ctx, fn) {
1705
+ const space = await createProbeSpace(ctx, publicRead());
1706
+ try {
1707
+ await mustCreateRecord(ctx, space.uri, "shared", "visible");
1708
+ return await fn(space, await obtainPublicCredential(ctx, space.uri));
1709
+ } finally {
1710
+ await deleteProbeSpace(ctx, space.uri);
1711
+ }
1712
+ }
1713
+ const recordParams = (ctx, space) => ({
1714
+ space,
1715
+ repo: ctx.target.did,
1716
+ collection: POST,
1717
+ rkey: "shared"
1718
+ });
1719
+ /** Read the shared record with a credential, varying one aspect of presentation. */
1720
+ const readShared = (ctx, credential, space, opts = {}) => credentialCall(ctx, credential, "com.atproto.space.getRecord", {
1721
+ ...opts,
1722
+ params: recordParams(ctx, space)
1723
+ });
1724
+ const refused = (status) => status >= 400 && status < 500;
1725
+ const credentialTokenlessPolicies = defineCheck({
1726
+ id: "credential.tokenless-by-policy",
1727
+ title: "Without a delegation token only a public-read space issues a credential",
1728
+ tier: "must",
1729
+ citations: [
1730
+ L$3("com.atproto.space.authorizeSpaceSync"),
1731
+ L$3("com.atproto.space.authorizeSpaceSync@error:SpaceNotFound"),
1732
+ L$3("com.atproto.memberspace.policy"),
1733
+ L$3("com.atproto.personalspace.policy"),
1734
+ P$3("0016#memberspace")
1735
+ ],
1736
+ needs: ["operator"],
1737
+ destructive: true,
1738
+ async run(ctx) {
1739
+ const open = await createProbeSpace(ctx, publicRead());
1740
+ const closed = await createProbeSpace(ctx, memberspace());
1741
+ const personal = await createProbeSpace(ctx, personalspace());
1742
+ try {
1743
+ const a = await requestCredential(ctx, open.uri);
1744
+ if (!a.credential) return fail(`public-read space refused a tokenless request: ${describe(a.result)}`, a.result.json);
1745
+ const misses = [];
1746
+ for (const [label, space] of [["memberspace", closed], ["personalspace", personal]]) {
1747
+ const res = await requestCredential(ctx, space.uri);
1748
+ if (res.credential || !errorIs(...ACCOUNT_REFUSALS$1)(res.result)) misses.push(`${label} → ${describe(res.result)}`);
1749
+ }
1750
+ return misses.length ? fail(`expected ${ACCOUNT_REFUSALS$1.join(" / ")}: ${misses.join("; ")}`) : pass("public-read issued; a closed memberspace and a personalspace refused");
1751
+ } finally {
1752
+ for (const s of [
1753
+ open,
1754
+ closed,
1755
+ personal
1756
+ ]) await deleteProbeSpace(ctx, s.uri);
1757
+ }
1758
+ }
1759
+ });
1760
+ const credentialClaims = defineCheck({
1761
+ id: "credential.claims",
1762
+ title: "A credential is signed by the authority for the space, bound to the requested key",
1763
+ tier: "must",
1764
+ citations: [
1765
+ L$3("com.atproto.space.authorizeSpaceSync"),
1766
+ P$3("0016#space-credential"),
1767
+ C$2("pds-space-uri-migration")
1768
+ ],
1769
+ needs: ["operator"],
1770
+ destructive: true,
1771
+ async run(ctx) {
1772
+ const space = await createProbeSpace(ctx, publicRead());
1773
+ try {
1774
+ const credential = await obtainPublicCredential(ctx, space.uri);
1775
+ const { header, payload } = decodeJwt(credential.credential);
1776
+ const cnf = payload.cnf;
1777
+ const problems = [];
1778
+ if (header.typ !== "atproto-space-credential+jwt") problems.push(`typ ${String(header.typ)}`);
1779
+ if (header.kid !== "#atproto") problems.push(`kid ${String(header.kid)}`);
1780
+ if (payload.iss !== ctx.target.did) problems.push(`iss ${String(payload.iss)}`);
1781
+ if (payload.sub !== spaceUri(ctx.target.did, space.skey)) problems.push(`sub ${String(payload.sub)}`);
1782
+ if (cnf?.kid !== credential.key.did) problems.push(`cnf.kid ${String(cnf?.kid)}`);
1783
+ if ("aud" in payload) problems.push(`has aud ${String(payload.aud)}`);
1784
+ if (typeof payload.jti !== "string" || !payload.jti) problems.push("no jti");
1785
+ const iat = Number(payload.iat);
1786
+ const exp = Number(payload.exp);
1787
+ if (!(exp > iat) || exp - iat > 3600) problems.push(`lifetime ${exp - iat}s (max 3600)`);
1788
+ return problems.length ? fail(`credential claims: ${problems.join(", ")}`, {
1789
+ header,
1790
+ payload
1791
+ }) : pass(`typ/kid/iss/sub (at:space/ ref)/cnf correct, no aud, ${exp - iat}s lifetime`);
1792
+ } finally {
1793
+ await deleteProbeSpace(ctx, space.uri);
1794
+ }
1795
+ }
1796
+ });
1797
+ const credentialDefaultLifetime = defineCheck({
1798
+ id: "credential.default-lifetime",
1799
+ title: "Credentials live 600 seconds, the default",
1800
+ tier: "should",
1801
+ citations: [P$3("0016#space-credential")],
1802
+ needs: ["operator"],
1803
+ destructive: true,
1804
+ async run(ctx) {
1805
+ const space = await createProbeSpace(ctx, publicRead());
1806
+ try {
1807
+ const { payload } = decodeJwt((await obtainPublicCredential(ctx, space.uri)).credential);
1808
+ const lifetime = Number(payload.exp) - Number(payload.iat);
1809
+ return lifetime === 600 ? pass("600s") : fail(`${lifetime}s`);
1810
+ } finally {
1811
+ await deleteProbeSpace(ctx, space.uri);
1812
+ }
1813
+ }
1814
+ });
1815
+ const credentialSpaceRev = defineCheck({
1816
+ id: "credential.space-rev",
1817
+ title: "authorizeSpaceSync reports the space's current revision, omitted before its first update",
1818
+ tier: "must",
1819
+ citations: [L$3("com.atproto.space.authorizeSpaceSync"), P$3("0016#authorizing-space-sync")],
1820
+ needs: ["operator"],
1821
+ destructive: true,
1822
+ async run(ctx) {
1823
+ const space = await createProbeSpace(ctx, publicRead());
1824
+ try {
1825
+ const fresh = await requestCredential(ctx, space.uri);
1826
+ if (!fresh.credential) return fail(`authorizeSpaceSync ${describe(fresh.result)}`, fresh.result.json);
1827
+ if (fresh.spaceRev !== void 0) return fail(`a space with no updates reported spaceRev ${fresh.spaceRev}`);
1828
+ await mustCreateRecord(ctx, space.uri, "a");
1829
+ const after = await requestCredential(ctx, space.uri);
1830
+ if (!isTid(after.spaceRev)) return fail(`after a write, spaceRev is ${String(after.spaceRev)}`, after.result.json);
1831
+ const revs = ((await credentialCall(ctx, after.credential, "com.atproto.space.listWriters", {
1832
+ params: { space: space.uri },
1833
+ audience: ctx.target.did
1834
+ })).json?.repos ?? []).map((r) => r.spaceRev);
1835
+ 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)}`);
1836
+ } finally {
1837
+ await deleteProbeSpace(ctx, space.uri);
1838
+ }
1839
+ }
1840
+ });
1841
+ const credentialKeyP256 = defineCheck({
1842
+ id: "credential.key-must-be-p256",
1843
+ title: "authorizeSpaceSync refuses a credentialKey that is not a P-256 did:key",
1844
+ tier: "must",
1845
+ citations: [L$3("com.atproto.space.authorizeSpaceSync"), P$3("0016#credential-key-binding")],
1846
+ needs: ["operator"],
1847
+ destructive: true,
1848
+ async run(ctx) {
1849
+ const space = await createProbeSpace(ctx, publicRead());
1850
+ try {
1851
+ const k256 = formatDidKey("ES256K", new Uint8Array([2, ...crypto.getRandomValues(new Uint8Array(32))]));
1852
+ const bad = await requestCredential(ctx, space.uri, { credentialKey: k256 });
1853
+ if (bad.credential) return fail("issued a credential bound to a secp256k1 key");
1854
+ const notKey = await requestCredential(ctx, space.uri, { credentialKey: ctx.target.did });
1855
+ if (notKey.credential) return fail("issued a credential bound to a non-key DID");
1856
+ const good = await requestCredential(ctx, space.uri);
1857
+ return good.credential ? pass(`refused secp256k1 (${describe(bad.result)}) and non-key (${describe(notKey.result)}); P-256 issued`) : fail(`positive control failed: ${describe(good.result)}`, good.result.json);
1858
+ } finally {
1859
+ await deleteProbeSpace(ctx, space.uri);
1860
+ }
1861
+ }
1862
+ });
1863
+ const credentialGarbageDelegation = defineCheck({
1864
+ id: "credential.garbage-delegation-refused",
1865
+ title: "A malformed delegation token is refused with InvalidDelegationToken",
1866
+ tier: "must",
1867
+ citations: [L$3("com.atproto.space.authorizeSpaceSync@error:InvalidDelegationToken")],
1868
+ needs: ["operator"],
1869
+ destructive: true,
1870
+ async run(ctx) {
1871
+ const space = await createProbeSpace(ctx, memberspace());
1872
+ try {
1873
+ const res = await requestCredential(ctx, space.uri, { delegationToken: "not.a.token" });
1874
+ if (res.credential) return fail("issued a credential for a garbage delegation token");
1875
+ return res.result.error === "InvalidDelegationToken" ? pass("refused with InvalidDelegationToken") : fail(`refused with ${describe(res.result)}, expected InvalidDelegationToken`, res.result.json);
1876
+ } finally {
1877
+ await deleteProbeSpace(ctx, space.uri);
1878
+ }
1879
+ }
1880
+ });
1881
+ /** A client_id no host serves: an app the target can never resolve. */
1882
+ const UNRESOLVABLE_CLIENT = "https://app.space-conformance.invalid/client-metadata.json";
1883
+ /**
1884
+ * A structurally valid client attestation for a client nobody can resolve:
1885
+ * typed, addressed to the space host, iss = sub = an unresolvable
1886
+ * client_id, signed by a throwaway key. Only verification can refuse it.
1887
+ */
1888
+ async function unverifiableAttestation(authority) {
1889
+ const key = await createCredentialKey();
1890
+ return signClientAttestation({
1891
+ clientId: UNRESOLVABLE_CLIENT,
1892
+ aud: spaceHostAud(authority),
1893
+ kid: "key-1",
1894
+ sign: (bytes) => key.sign(bytes)
1895
+ });
1896
+ }
1897
+ const attestationCitations = [L$3("com.atproto.space.authorizeSpaceSync@error:InvalidClientAttestation"), P$3("0016#client-attestation")];
1898
+ /** Said by a refusal check that could not run its success-path control. */
1899
+ const NO_VERIFIABLE_CLIENT = "the success path was not checked: no syncer inbox to publish a verifiable client";
1900
+ /**
1901
+ * The attestation success path, when the harness serves a syncer inbox: an
1902
+ * attestation signed by the inbox's published client key, for `space`,
1903
+ * must issue a credential. A refusal check runs it first, so a host that
1904
+ * refuses every attestation — verification broken — fails rather than
1905
+ * passing on the refusals alone. Returns the control's detail, or a failure.
1906
+ */
1907
+ async function attestationControl(ctx, space) {
1908
+ const inbox = ctx.syncerInbox;
1909
+ if (!inbox) return { detail: NO_VERIFIABLE_CLIENT };
1910
+ const res = await requestCredential(ctx, space, { clientAttestation: await inbox.attest(spaceHostAud(ctx.target.did)) });
1911
+ return res.credential ? { detail: `a valid attestation from ${inbox.clientId} issued` } : { failure: fail(`positive control failed: a valid attestation from ${inbox.clientId} was refused (${describe(res.result)}), so a refusal proves nothing about verification`, res.result.json) };
1912
+ }
1913
+ const credentialUnverifiableAttestation = defineCheck({
1914
+ id: "credential.unverifiable-attestation-refused",
1915
+ title: "A client attestation that cannot be verified is refused with InvalidClientAttestation",
1916
+ tier: "must",
1917
+ citations: attestationCitations,
1918
+ needs: ["operator"],
1919
+ uses: ["syncer-inbox"],
1920
+ destructive: true,
1921
+ async run(ctx) {
1922
+ const space = await createProbeSpace(ctx, publicRead());
1923
+ try {
1924
+ const control = await attestationControl(ctx, space.uri);
1925
+ if ("failure" in control) return control.failure;
1926
+ const res = await requestCredential(ctx, space.uri, { clientAttestation: await unverifiableAttestation(ctx.target.did) });
1927
+ if (res.credential) return fail("issued a credential on an unverifiable client attestation");
1928
+ return res.result.error === "InvalidClientAttestation" ? pass(`refused with InvalidClientAttestation; ${control.detail}`) : fail(`refused with ${describe(res.result)}, expected InvalidClientAttestation`, res.result.json);
1929
+ } finally {
1930
+ await deleteProbeSpace(ctx, space.uri);
1931
+ }
1932
+ }
1933
+ });
1934
+ const credentialGarbageAttestation = defineCheck({
1935
+ id: "credential.garbage-attestation-refused",
1936
+ title: "A malformed client attestation is refused with InvalidClientAttestation",
1937
+ tier: "must",
1938
+ citations: attestationCitations,
1939
+ needs: ["operator"],
1940
+ uses: ["syncer-inbox"],
1941
+ destructive: true,
1942
+ async run(ctx) {
1943
+ const space = await createProbeSpace(ctx, publicRead());
1944
+ try {
1945
+ const control = await attestationControl(ctx, space.uri);
1946
+ if ("failure" in control) return control.failure;
1947
+ const res = await requestCredential(ctx, space.uri, { clientAttestation: "not.an.attestation" });
1948
+ if (res.credential) return fail("issued a credential despite a garbage client attestation");
1949
+ return res.result.error === "InvalidClientAttestation" ? pass(`refused with InvalidClientAttestation; ${control.detail}`) : fail(`refused with ${describe(res.result)}, expected InvalidClientAttestation`, res.result.json);
1950
+ } finally {
1951
+ await deleteProbeSpace(ctx, space.uri);
1952
+ }
1953
+ }
1954
+ });
1955
+ const allowedAppsCitations = [
1956
+ L$3("com.atproto.space.authorizeSpaceSync@error:AppNotAuthorized"),
1957
+ L$3("com.atproto.memberspace.policy"),
1958
+ P$3("0016#memberspace"),
1959
+ P$3("0016#client-attestation")
1960
+ ];
1961
+ const credentialAllowedApps = defineCheck({
1962
+ id: "credential.allowed-apps-gate",
1963
+ title: "A memberspace with allowedApps refuses an unattested app",
1964
+ tier: "must",
1965
+ citations: allowedAppsCitations,
1966
+ needs: ["operator"],
1967
+ uses: ["syncer-inbox"],
1968
+ destructive: true,
1969
+ async run(ctx) {
1970
+ const inbox = ctx.syncerInbox;
1971
+ const space = await createProbeSpace(ctx, memberspace({
1972
+ publicRead: true,
1973
+ allowedApps: [UNRESOLVABLE_CLIENT, ...inbox ? [inbox.clientId] : []]
1974
+ }));
1975
+ try {
1976
+ const res = await requestCredential(ctx, space.uri);
1977
+ if (res.credential) return fail("issued a credential to an app outside allowedApps");
1978
+ if (!errorIs("AppNotAuthorized", "NotAuthorized")(res.result)) return fail(`refused with ${describe(res.result)}, expected AppNotAuthorized`, res.result.json);
1979
+ const control = await attestationControl(ctx, space.uri);
1980
+ if ("failure" in control) return control.failure;
1981
+ return pass(`unattested request refused with ${res.result.error}; ${inbox ? "a valid attestation from a listed app issued" : control.detail}`);
1982
+ } finally {
1983
+ await deleteProbeSpace(ctx, space.uri);
1984
+ }
1985
+ }
1986
+ });
1987
+ const credentialValidAttestation = defineCheck({
1988
+ id: "credential.valid-attestation-issues",
1989
+ title: "A verifiable client attestation from an app in allowedApps obtains a credential",
1990
+ tier: "must",
1991
+ citations: [
1992
+ L$3("com.atproto.space.authorizeSpaceSync"),
1993
+ L$3("com.atproto.memberspace.policy"),
1994
+ P$3("0016#client-attestation"),
1995
+ P$3("0016#memberspace")
1996
+ ],
1997
+ needs: ["operator", "syncer-inbox"],
1998
+ destructive: true,
1999
+ async run(ctx) {
2000
+ const inbox = ctx.syncerInbox;
2001
+ const space = await createProbeSpace(ctx, memberspace({
2002
+ publicRead: true,
2003
+ allowedApps: [inbox.clientId]
2004
+ }));
2005
+ try {
2006
+ const unattested = await requestCredential(ctx, space.uri);
2007
+ if (unattested.credential) return fail("issued without an attestation, so allowedApps is not enforced and issuance proves nothing");
2008
+ const res = await requestCredential(ctx, space.uri, { clientAttestation: await inbox.attest(spaceHostAud(ctx.target.did)) });
2009
+ return res.credential ? pass(`unattested refused (${describe(unattested.result)}); attested as ${inbox.clientId}, issued`) : fail(`a valid attestation from the listed ${inbox.clientId} was refused: ${describe(res.result)}`, res.result.json);
2010
+ } finally {
2011
+ await deleteProbeSpace(ctx, space.uri);
2012
+ }
2013
+ }
2014
+ });
2015
+ const credentialUnlistedAttestation = defineCheck({
2016
+ id: "credential.valid-attestation-unlisted-refused",
2017
+ title: "A verifiable client attestation from an app outside allowedApps is refused with AppNotAuthorized",
2018
+ tier: "must",
2019
+ citations: allowedAppsCitations,
2020
+ needs: ["operator", "syncer-inbox"],
2021
+ destructive: true,
2022
+ async run(ctx) {
2023
+ const inbox = ctx.syncerInbox;
2024
+ const listed = await createProbeSpace(ctx, memberspace({
2025
+ publicRead: true,
2026
+ allowedApps: [inbox.clientId]
2027
+ }));
2028
+ const unlisted = await createProbeSpace(ctx, memberspace({
2029
+ publicRead: true,
2030
+ allowedApps: [UNRESOLVABLE_CLIENT]
2031
+ }));
2032
+ try {
2033
+ const aud = spaceHostAud(ctx.target.did);
2034
+ const ok = await requestCredential(ctx, listed.uri, { clientAttestation: await inbox.attest(aud) });
2035
+ if (!ok.credential) return fail(`positive control failed: the space listing ${inbox.clientId} refused its valid attestation (${describe(ok.result)})`, ok.result.json);
2036
+ const res = await requestCredential(ctx, unlisted.uri, { clientAttestation: await inbox.attest(aud) });
2037
+ if (res.credential) return fail("issued a credential to a verified app outside allowedApps");
2038
+ return res.result.error === "AppNotAuthorized" ? pass("issued where the app is listed; refused with AppNotAuthorized where it is not") : fail(`refused with ${describe(res.result)}, expected AppNotAuthorized`, res.result.json);
2039
+ } finally {
2040
+ await deleteProbeSpace(ctx, listed.uri);
2041
+ await deleteProbeSpace(ctx, unlisted.uri);
2042
+ }
2043
+ }
2044
+ });
2045
+ const credentialDeletedSpace = defineCheck({
2046
+ id: "credential.deleted-space",
2047
+ title: "deleteSpace removes the authority's repo, and authorizeSpaceSync then answers SpaceDeleted",
2048
+ tier: "must",
2049
+ citations: [
2050
+ L$3("com.atproto.space.deleteSpace"),
2051
+ L$3("com.atproto.space.authorizeSpaceSync@error:SpaceDeleted"),
2052
+ P$3("0016#space-deletion")
2053
+ ],
2054
+ needs: ["operator"],
2055
+ destructive: true,
2056
+ async run(ctx) {
2057
+ const space = await createProbeSpace(ctx, publicRead());
2058
+ await mustCreateRecord(ctx, space.uri, "mine");
2059
+ const before = await requestCredential(ctx, space.uri);
2060
+ if (!before.credential) {
2061
+ await deleteProbeSpace(ctx, space.uri);
2062
+ return fail(`could not obtain a credential before deletion (${describe(before.result)})`);
2063
+ }
2064
+ const del = await xrpcPost(asOperator(ctx), "com.atproto.space.deleteSpace", { space: space.uri });
2065
+ if (del.status !== 200) return fail(`deleteSpace ${describe(del)}`, del.json);
2066
+ const own = await xrpcGet(asOperator(ctx), "com.atproto.space.getRecord", {
2067
+ space: space.uri,
2068
+ repo: ctx.target.did,
2069
+ collection: POST,
2070
+ rkey: "mine"
2071
+ });
2072
+ if (own.status === 200) return fail("the authority's own record survived deleteSpace", own.json);
2073
+ const tokenless = await requestCredential(ctx, space.uri);
2074
+ const garbage = await requestCredential(ctx, space.uri, { delegationToken: "not.a.token" });
2075
+ if (tokenless.credential) return fail("a deleted space still issued a credential");
2076
+ return tokenless.result.error === "SpaceDeleted" && garbage.result.error === "SpaceDeleted" ? pass("own records gone; answered SpaceDeleted, tokenless and with a bad token") : fail(`answered ${describe(tokenless.result)} tokenless, ${describe(garbage.result)} with a bad token; expected SpaceDeleted`);
2077
+ }
2078
+ });
2079
+ const credentialUnconfirmedRegistration = defineCheck({
2080
+ id: "credential.unconfirmed-registration-refused",
2081
+ title: "A notify endpoint that does not confirm the registration gets RegistrationNotConfirmed",
2082
+ tier: "must",
2083
+ citations: [L$3("com.atproto.space.authorizeSpaceSync@error:RegistrationNotConfirmed"), P$3("0016#registering-for-notifications")],
2084
+ needs: ["operator"],
2085
+ uses: ["syncer-inbox"],
2086
+ destructive: true,
2087
+ async run(ctx) {
2088
+ const inbox = ctx.syncerInbox;
2089
+ const space = await createProbeSpace(ctx, publicRead());
2090
+ const randomToken = () => toBase64Url(crypto.getRandomValues(new Uint8Array(32)));
2091
+ try {
2092
+ const refusals = [["an unreachable endpoint", {
2093
+ endpoint: "https://syncer.space-conformance.invalid",
2094
+ token: randomToken()
2095
+ }]];
2096
+ if (inbox) {
2097
+ const ok = await requestCredential(ctx, space.uri, { notify: {
2098
+ endpoint: inbox.endpoint,
2099
+ token: inbox.issueToken(space.uri)
2100
+ } });
2101
+ if (!ok.credential) return fail(`positive control failed: a registration the inbox confirms was refused (${describe(ok.result)})`, ok.result.json);
2102
+ refusals.push(["a token the endpoint did not issue", {
2103
+ endpoint: inbox.endpoint,
2104
+ token: randomToken()
2105
+ }]);
2106
+ }
2107
+ const misses = [];
2108
+ for (const [label, notify] of refusals) {
2109
+ const res = await requestCredential(ctx, space.uri, { notify });
2110
+ if (res.credential) misses.push(`${label} → issued`);
2111
+ else if (res.result.error !== "RegistrationNotConfirmed") misses.push(`${label} → ${describe(res.result)}`);
2112
+ }
2113
+ if (misses.length) return fail(`expected RegistrationNotConfirmed: ${misses.join("; ")}`);
2114
+ return pass(inbox ? "a confirmed registration issued; an unreachable endpoint and an unissued token were refused with RegistrationNotConfirmed" : "an unreachable endpoint was refused with RegistrationNotConfirmed; the success path was not checked (no syncer inbox)");
2115
+ } finally {
2116
+ await deleteProbeSpace(ctx, space.uri);
2117
+ }
2118
+ }
2119
+ });
2120
+ const credentialSelfRoundTrip = defineCheck({
2121
+ id: "credential.self-round-trip",
2122
+ title: "Operator obtains a credential via getDelegationToken and reads with it",
2123
+ tier: "must",
2124
+ citations: [
2125
+ L$3("com.atproto.space.getDelegationToken"),
2126
+ L$3("com.atproto.space.authorizeSpaceSync"),
2127
+ L$3("com.atproto.space.getRecord"),
2128
+ P$3("0016#credential-flow")
2129
+ ],
2130
+ needs: ["operator", "pds-delegation"],
2131
+ destructive: true,
2132
+ async run(ctx) {
2133
+ const space = await createProbeSpace(ctx, memberspace());
2134
+ try {
2135
+ await mustCreateRecord(ctx, space.uri, "shared", "mine");
2136
+ const { result, credential, delegation } = await obtainCredentialViaDelegation(ctx, space.uri);
2137
+ if (delegation.status !== 200) return fail(`getDelegationToken ${describe(delegation)}`, delegation.json);
2138
+ if (!credential) return fail(`authorizeSpaceSync ${describe(result)}`, result.json);
2139
+ const read = await readShared(ctx, credential, space.uri);
2140
+ if (read.status !== 200) return fail(`credential read failed: ${describe(read)}`, read.json);
2141
+ return read.headers.get("atproto-space-record") && read.headers.get("signature") ? pass("delegation → credential → read carrying an Atproto-Space-Record MAC (presence only here; mac.record-verifies checks it with the alpha libs)") : fail("the credentialed read carried no Atproto-Space-Record MAC");
2142
+ } finally {
2143
+ await deleteProbeSpace(ctx, space.uri);
2144
+ }
2145
+ }
2146
+ });
2147
+ const credentialPersonalOwner = defineCheck({
2148
+ id: "policy.personalspace-owner-admitted",
2149
+ title: "A personalspace issues its authority a credential through a delegation token",
2150
+ tier: "must",
2151
+ citations: [
2152
+ L$3("com.atproto.personalspace.policy"),
2153
+ L$3("com.atproto.space.authorizeSpaceSync"),
2154
+ P$3("0016#personalspace")
2155
+ ],
2156
+ needs: ["operator", "pds-delegation"],
2157
+ destructive: true,
2158
+ async run(ctx) {
2159
+ const space = await createProbeSpace(ctx, personalspace());
2160
+ try {
2161
+ await mustCreateRecord(ctx, space.uri, "shared", "mine");
2162
+ const tokenless = await requestCredential(ctx, space.uri);
2163
+ if (tokenless.credential) return fail("a personalspace issued a credential with no delegation token");
2164
+ const { result, credential, delegation } = await obtainCredentialViaDelegation(ctx, space.uri);
2165
+ if (delegation.status !== 200) return fail(`getDelegationToken ${describe(delegation)}`, delegation.json);
2166
+ if (!credential) return fail(`the authority was refused its own personalspace: ${describe(result)}`, result.json);
2167
+ const read = await readShared(ctx, credential, space.uri);
2168
+ return read.status === 200 ? pass(`tokenless refused (${describe(tokenless.result)}); the authority's delegation token issued, and the credential reads`) : fail(`the authority's credential could not read: ${describe(read)}`, read.json);
2169
+ } finally {
2170
+ await deleteProbeSpace(ctx, space.uri);
2171
+ }
2172
+ }
2173
+ });
2174
+ const delegationClaims = defineCheck({
2175
+ id: "delegation.token-claims",
2176
+ title: "getDelegationToken mints a token for the space's #atproto_pds, signed by #atproto",
2177
+ tier: "must",
2178
+ citations: [
2179
+ L$3("com.atproto.space.getDelegationToken"),
2180
+ P$3("0016#delegation-token"),
2181
+ C$2("pds-space-uri-migration")
2182
+ ],
2183
+ needs: ["operator", "pds-delegation"],
2184
+ destructive: true,
2185
+ async run(ctx) {
2186
+ const space = await createProbeSpace(ctx, memberspace());
2187
+ try {
2188
+ const res = await xrpcGet(asOperator(ctx), "com.atproto.space.getDelegationToken", { space: space.uri });
2189
+ if (res.status !== 200) return fail(`getDelegationToken ${describe(res)}`, res.json);
2190
+ const { header, payload } = decodeJwt(res.json.token);
2191
+ const problems = [];
2192
+ if (header.typ !== "atproto-space-delegation+jwt") problems.push(`typ ${String(header.typ)}`);
2193
+ if (header.kid !== "#atproto") problems.push(`kid ${String(header.kid)}`);
2194
+ if (payload.iss !== ctx.target.did) problems.push(`iss ${String(payload.iss)}`);
2195
+ if (payload.sub !== spaceUri(ctx.target.did, space.skey)) problems.push(`sub ${String(payload.sub)}`);
2196
+ if (payload.aud !== `${ctx.target.did}#atproto_pds`) problems.push(`aud ${String(payload.aud)}`);
2197
+ if ("lxm" in payload) problems.push("has an lxm claim");
2198
+ if (typeof payload.jti !== "string" || !payload.jti) problems.push("no jti");
2199
+ if (!(Number(payload.exp) > Math.floor(Date.now() / 1e3) - 5)) problems.push("already expired");
2200
+ return problems.length ? fail(`delegation token: ${problems.join(", ")}`, {
2201
+ header,
2202
+ payload
2203
+ }) : pass("typ/kid/iss/sub (at:space/ ref)/aud as specified, no lxm");
2204
+ } finally {
2205
+ await deleteProbeSpace(ctx, space.uri);
2206
+ }
2207
+ }
2208
+ });
2209
+ const delegationReplay = defineCheck({
2210
+ id: "delegation.replay-refused",
2211
+ title: "A delegation token cannot be used twice",
2212
+ tier: "must",
2213
+ citations: [L$3("com.atproto.space.authorizeSpaceSync@error:InvalidDelegationToken"), P$3("0016#delegation-token")],
2214
+ needs: ["operator", "pds-delegation"],
2215
+ destructive: true,
2216
+ async run(ctx) {
2217
+ const space = await createProbeSpace(ctx, memberspace());
2218
+ try {
2219
+ const res = await xrpcGet(asOperator(ctx), "com.atproto.space.getDelegationToken", { space: space.uri });
2220
+ if (res.status !== 200) return fail(`getDelegationToken ${describe(res)}`, res.json);
2221
+ const delegationToken = res.json.token;
2222
+ const first = await requestCredential(ctx, space.uri, { delegationToken });
2223
+ if (!first.credential) return fail(`first exchange failed (${describe(first.result)}); cannot test replay`);
2224
+ const second = await requestCredential(ctx, space.uri, { delegationToken });
2225
+ if (second.credential) return fail("a replayed delegation token was accepted");
2226
+ return second.result.error === "InvalidDelegationToken" ? pass("replay refused with InvalidDelegationToken") : fail(`replay refused with ${describe(second.result)}, expected InvalidDelegationToken`);
2227
+ } finally {
2228
+ await deleteProbeSpace(ctx, space.uri);
2229
+ }
2230
+ }
2231
+ });
2232
+ const delegationWrongSpace = defineCheck({
2233
+ id: "delegation.wrong-space-refused",
2234
+ title: "A delegation token for one space is refused for another",
2235
+ tier: "must",
2236
+ citations: [L$3("com.atproto.space.authorizeSpaceSync@error:InvalidDelegationToken"), P$3("0016#delegation-token")],
2237
+ needs: ["operator", "pds-delegation"],
2238
+ destructive: true,
2239
+ async run(ctx) {
2240
+ const a = await createProbeSpace(ctx, memberspace());
2241
+ const b = await createProbeSpace(ctx, memberspace());
2242
+ try {
2243
+ const res = await xrpcGet(asOperator(ctx), "com.atproto.space.getDelegationToken", { space: a.uri });
2244
+ if (res.status !== 200) return fail(`getDelegationToken ${describe(res)}`, res.json);
2245
+ const cross = await requestCredential(ctx, b.uri, { delegationToken: res.json.token });
2246
+ if (cross.credential) return fail("a token for space A issued a credential for space B");
2247
+ return cross.result.error === "InvalidDelegationToken" ? pass("refused with InvalidDelegationToken") : fail(`refused with ${describe(cross.result)}, expected InvalidDelegationToken`);
2248
+ } finally {
2249
+ await deleteProbeSpace(ctx, a.uri);
2250
+ await deleteProbeSpace(ctx, b.uri);
2251
+ }
2252
+ }
2253
+ });
2254
+ const presentationCitations = [
2255
+ L$3("com.atproto.space.getRecord"),
2256
+ L$3("com.atproto.space.listWriters"),
2257
+ P$3("0016#presenting-a-space-credential")
2258
+ ];
2259
+ const credentialSignatureRequired = defineCheck({
2260
+ id: "credential.signature-required",
2261
+ title: "A credential presented without its HTTP signature is refused",
2262
+ tier: "must",
2263
+ citations: presentationCitations,
2264
+ needs: ["operator"],
2265
+ destructive: true,
2266
+ async run(ctx) {
2267
+ return withPublicSpace(ctx, async (space, credential) => {
2268
+ const ok = await readShared(ctx, credential, space.uri);
2269
+ if (ok.status !== 200) return fail(`positive control failed: ${describe(ok)}`, ok.json);
2270
+ const bare = await readShared(ctx, credential, space.uri, { unsigned: true });
2271
+ return refused(bare.status) ? pass(`signed read 200; unsigned read refused (${describe(bare)})`) : fail(`an unsigned credential read returned ${describe(bare)}`, bare.json);
2272
+ });
2273
+ }
2274
+ });
2275
+ const credentialSignatureByTag = defineCheck({
2276
+ id: "credential.signature-found-by-tag",
2277
+ title: "The credential signature is found by its tag under any label; other parameters are ignored",
2278
+ tier: "must",
2279
+ citations: presentationCitations,
2280
+ needs: ["operator"],
2281
+ destructive: true,
2282
+ async run(ctx) {
2283
+ return withPublicSpace(ctx, async (space, credential) => {
2284
+ const variants = [
2285
+ ["label 'x7'", { label: "x7" }],
2286
+ ["created and nonce parameters", { params: [["created", Math.floor(Date.now() / 1e3)], ["nonce", "abc"]] }],
2287
+ ["keyid = cnf.kid and alg = ecdsa-p256-sha256", { params: [["keyid", credential.key.did], ["alg", "ecdsa-p256-sha256"]] }]
2288
+ ];
2289
+ const misses = [];
2290
+ for (const [label, signature] of variants) {
2291
+ const res = await readShared(ctx, credential, space.uri, { signature });
2292
+ if (res.status !== 200) misses.push(`${label} → ${describe(res)}`);
2293
+ }
2294
+ const extra = await readShared(ctx, credential, space.uri, { signatureHeaders: async (h) => {
2295
+ const other = await credentialSigMembers(credential.key, {
2296
+ authorization: h.authorization,
2297
+ audience: h["atproto-space-audience"],
2298
+ label: "other",
2299
+ tag: "some-other-app"
2300
+ });
2301
+ return {
2302
+ ...h,
2303
+ "signature-input": `${h["signature-input"]}, ${other.input}`,
2304
+ signature: `${h.signature}, ${other.signature}`
2305
+ };
2306
+ } });
2307
+ if (extra.status !== 200) misses.push(`with an extra differently-tagged signature → ${describe(extra)}`);
2308
+ return misses.length ? fail(`refused a valid signature: ${misses.join("; ")}`) : pass("accepted under another label, with extra parameters, and beside another tag's signature");
2309
+ });
2310
+ }
2311
+ });
2312
+ const credentialSignatureRequirements = defineCheck({
2313
+ id: "credential.signature-requirements",
2314
+ title: "A credential signature with the wrong components, keyid, alg or count is refused",
2315
+ tier: "must",
2316
+ citations: presentationCitations,
2317
+ needs: ["operator"],
2318
+ destructive: true,
2319
+ async run(ctx) {
2320
+ return withPublicSpace(ctx, async (space, credential) => {
2321
+ const ok = await readShared(ctx, credential, space.uri);
2322
+ if (ok.status !== 200) return fail(`positive control failed: ${describe(ok)}`, ok.json);
2323
+ const variants = [
2324
+ ["covers only authorization", { signature: { components: ["authorization"] } }],
2325
+ ["components out of order", { signature: { components: ["atproto-space-audience", "authorization"] } }],
2326
+ ["keyid of another key", { signature: { params: [["keyid", (await createCredentialKey()).did]] } }],
2327
+ ["alg hmac-sha256", { signature: { params: [["alg", "hmac-sha256"]] } }],
2328
+ ["no atproto-space-credential tag", { signature: { tag: "something-else" } }],
2329
+ ["two tagged signatures", { signatureHeaders: async (h) => {
2330
+ const dup = await credentialSigMembers(credential.key, {
2331
+ authorization: h.authorization,
2332
+ audience: h["atproto-space-audience"],
2333
+ label: "dup"
2334
+ });
2335
+ return {
2336
+ ...h,
2337
+ "signature-input": `${h["signature-input"]}, ${dup.input}`,
2338
+ signature: `${h.signature}, ${dup.signature}`
2339
+ };
2340
+ } }]
2341
+ ];
2342
+ const misses = [];
2343
+ for (const [label, opts] of variants) {
2344
+ const res = await readShared(ctx, credential, space.uri, opts);
2345
+ if (!refused(res.status)) misses.push(`${label} → ${describe(res)}`);
2346
+ }
2347
+ return misses.length ? fail(`accepted: ${misses.join("; ")}`) : pass("every malformed signature was refused");
2348
+ });
2349
+ }
2350
+ });
2351
+ const credentialAudienceBound = defineCheck({
2352
+ id: "credential.audience-bound",
2353
+ title: "A credential signed for another audience is refused",
2354
+ tier: "must",
2355
+ citations: presentationCitations,
2356
+ needs: ["operator"],
2357
+ destructive: true,
2358
+ async run(ctx) {
2359
+ return withPublicSpace(ctx, async (space, credential) => {
2360
+ const ok = await readShared(ctx, credential, space.uri);
2361
+ if (ok.status !== 200) return fail(`positive control failed: ${describe(ok)}`, ok.json);
2362
+ const misaddressed = await readShared(ctx, credential, space.uri, { audience: FOREIGN_DID });
2363
+ if (!refused(misaddressed.status)) return fail(`a misaddressed repo-host read returned ${describe(misaddressed)}`, misaddressed.json);
2364
+ const listWriters$1 = (audience) => credentialCall(ctx, credential, "com.atproto.space.listWriters", {
2365
+ params: { space: space.uri },
2366
+ audience
2367
+ });
2368
+ const hostOk = await listWriters$1(ctx.target.did);
2369
+ if (hostOk.status !== 200) return fail(`listWriters positive control failed: ${describe(hostOk)}`, hostOk.json);
2370
+ const hostWrong = await listWriters$1(FOREIGN_DID);
2371
+ return refused(hostWrong.status) ? pass(`refused other audiences at the repo host (${describe(misaddressed)}) and space host (${describe(hostWrong)})`) : fail(`a misaddressed listWriters returned ${describe(hostWrong)}`, hostWrong.json);
2372
+ });
2373
+ }
2374
+ });
2375
+ const credentialWrongKey = defineCheck({
2376
+ id: "credential.wrong-key-refused",
2377
+ title: "A credential signed by a key other than its cnf.kid is refused",
2378
+ tier: "must",
2379
+ citations: presentationCitations,
2380
+ needs: ["operator"],
2381
+ destructive: true,
2382
+ async run(ctx) {
2383
+ return withPublicSpace(ctx, async (space, credential) => {
2384
+ const ok = await readShared(ctx, credential, space.uri);
2385
+ if (ok.status !== 200) return fail(`positive control failed: ${describe(ok)}`, ok.json);
2386
+ const thief = await readShared(ctx, credential, space.uri, { signWith: await createCredentialKey() });
2387
+ 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)}`, thief.json);
2388
+ });
2389
+ }
2390
+ });
2391
+ const credentialSchemeCase = defineCheck({
2392
+ id: "credential.scheme-case-insensitive",
2393
+ title: "The Atproto-Space-Credential scheme is recognised regardless of case",
2394
+ tier: "must",
2395
+ citations: [P$3("0016#presenting-a-space-credential"), L$3("com.atproto.space.getRecord")],
2396
+ needs: ["operator"],
2397
+ destructive: true,
2398
+ async run(ctx) {
2399
+ return withPublicSpace(ctx, async (space, credential) => {
2400
+ const lower = await readShared(ctx, credential, space.uri, { scheme: "atproto-space-credential" });
2401
+ return lower.status === 200 ? pass("a lowercase scheme was accepted") : fail(`a lowercase scheme returned ${describe(lower)}`, lower.json);
2402
+ });
2403
+ }
2404
+ });
2405
+ const credentialCrossSpace = defineCheck({
2406
+ id: "credential.cross-space-refused",
2407
+ title: "A credential for one space cannot read another",
2408
+ tier: "must",
2409
+ citations: [L$3("com.atproto.space.getRecord"), P$3("0016#presenting-a-space-credential")],
2410
+ needs: ["operator"],
2411
+ destructive: true,
2412
+ async run(ctx) {
2413
+ const other = await createProbeSpace(ctx, publicRead());
2414
+ try {
2415
+ await mustCreateRecord(ctx, other.uri, "shared", "b");
2416
+ return await withPublicSpace(ctx, async (space, credential) => {
2417
+ const ok = await readShared(ctx, credential, space.uri);
2418
+ if (ok.status !== 200) return fail(`positive control failed: ${describe(ok)}`, ok.json);
2419
+ const cross = await readShared(ctx, credential, other.uri);
2420
+ if (cross.status === 200) return fail("a space-A credential read space B", cross.json);
2421
+ return refused(cross.status) ? pass(`cross-space read refused (${describe(cross)})`) : fail(`cross-space read answered ${describe(cross)}, expected a 4xx refusal`, cross.json);
2422
+ });
2423
+ } finally {
2424
+ await deleteProbeSpace(ctx, other.uri);
2425
+ }
2426
+ }
2427
+ });
2428
+ const credentialUnhostedRepo = defineCheck({
2429
+ id: "credential.unhosted-repo-not-found",
2430
+ title: "Credentialed reads of a repo the host does not hold answer RepoNotFound",
2431
+ tier: "must",
2432
+ citations: [
2433
+ L$3("com.atproto.space.getRecord@error:RepoNotFound"),
2434
+ L$3("com.atproto.space.getLatestCommit@error:RepoNotFound"),
2435
+ L$3("com.atproto.space.getRepo@error:RepoNotFound"),
2436
+ L$3("com.atproto.space.listRecords@error:RepoNotFound"),
2437
+ L$3("com.atproto.space.listRepoOps@error:RepoNotFound"),
2438
+ L$3("com.atproto.space.listBlobs@error:RepoNotFound"),
2439
+ L$3("com.atproto.space.getBlob@error:RepoNotFound")
2440
+ ],
2441
+ needs: ["operator"],
2442
+ destructive: true,
2443
+ async run(ctx) {
2444
+ return withPublicSpace(ctx, async (space, credential) => {
2445
+ const repo = fakeDid();
2446
+ const base = {
2447
+ space: space.uri,
2448
+ repo
2449
+ };
2450
+ const reads = [
2451
+ ["getRecord", {
2452
+ ...base,
2453
+ collection: POST,
2454
+ rkey: "shared"
2455
+ }],
2456
+ ["getLatestCommit", base],
2457
+ ["getRepo", base],
2458
+ ["listRepoOps", base],
2459
+ ["listRecords", base],
2460
+ ["listBlobs", base],
2461
+ ["getBlob", {
2462
+ ...base,
2463
+ cid: await rawCid(utf8("no such blob"))
2464
+ }]
2465
+ ];
2466
+ const misses = [];
2467
+ for (const [name, params] of reads) {
2468
+ const res = await credentialCall(ctx, credential, `com.atproto.space.${name}`, { params });
2469
+ if (res.error !== "RepoNotFound") misses.push(`${name} → ${describe(res)}`);
2470
+ }
2471
+ return misses.length ? fail(`expected RepoNotFound: ${misses.join("; ")}`) : pass("all seven reads answered RepoNotFound");
2472
+ });
2473
+ }
2474
+ });
2475
+ const macRequired = defineCheck({
2476
+ id: "mac.mac-request-required",
2477
+ title: "Credentialed reads of a commit or record without a MAC request answer InvalidSpaceMac",
2478
+ tier: "must",
2479
+ citations: [
2480
+ L$3("com.atproto.space.getLatestCommit@error:InvalidSpaceMac"),
2481
+ L$3("com.atproto.space.getRecord@error:InvalidSpaceMac"),
2482
+ L$3("com.atproto.space.getRepo@error:InvalidSpaceMac"),
2483
+ L$3("com.atproto.space.listRepoOps@error:InvalidSpaceMac"),
2484
+ P$3("0016#requesting-a-mac")
2485
+ ],
2486
+ needs: ["operator"],
2487
+ destructive: true,
2488
+ async run(ctx) {
2489
+ return withPublicSpace(ctx, async (space, credential) => {
2490
+ const base = {
2491
+ space: space.uri,
2492
+ repo: ctx.target.did
2493
+ };
2494
+ const reads = [
2495
+ ["getLatestCommit", base],
2496
+ ["getRecord", recordParams(ctx, space.uri)],
2497
+ ["getRepo", base],
2498
+ ["listRepoOps", base]
2499
+ ];
2500
+ const misses = [];
2501
+ for (const [name, params] of reads) {
2502
+ const nsid = `com.atproto.space.${name}`;
2503
+ const ok = await credentialGet(ctx, credential, nsid, params);
2504
+ if (ok.status !== 200) {
2505
+ misses.push(`${name} with a MAC request → ${describe(ok)}`);
2506
+ continue;
2507
+ }
2508
+ const none = await credentialCall(ctx, credential, nsid, {
2509
+ params,
2510
+ mac: false
2511
+ });
2512
+ if (none.error !== "InvalidSpaceMac") misses.push(`${name} without → ${describe(none)}`);
2513
+ const profile = name === "getRecord" ? RECORD_MAC_PROFILE : COMMIT_MAC_PROFILE;
2514
+ const otherTag = await credentialCall(ctx, credential, nsid, {
2515
+ params,
2516
+ mac: {
2517
+ profile,
2518
+ header: (k) => formatMacRequest(profile, k).replace(`tag="${profile}"`, "tag=\"some-other-profile\"")
2519
+ }
2520
+ });
2521
+ if (otherTag.error !== "InvalidSpaceMac") misses.push(`${name} with only another tag → ${describe(otherTag)}`);
2522
+ }
2523
+ return misses.length ? fail(misses.join("; ")) : pass("each served with a MAC request (not verified here: mac.commit-verifies and mac.record-verifies need the alpha libs) and answered InvalidSpaceMac without one");
2524
+ });
2525
+ }
2526
+ });
2527
+ const macMalformed = defineCheck({
2528
+ id: "mac.malformed-request-rejected",
2529
+ title: "A malformed MAC request answers InvalidSpaceMac",
2530
+ tier: "must",
2531
+ citations: [
2532
+ L$3("com.atproto.space.getLatestCommit@error:InvalidSpaceMac"),
2533
+ L$3("com.atproto.space.getRecord@error:InvalidSpaceMac"),
2534
+ P$3("0016#requesting-a-mac")
2535
+ ],
2536
+ needs: ["operator"],
2537
+ destructive: true,
2538
+ async run(ctx) {
2539
+ return withPublicSpace(ctx, async (space, credential) => {
2540
+ const commit = {
2541
+ space: space.uri,
2542
+ repo: ctx.target.did
2543
+ };
2544
+ const c = COMMIT_MAC_PROFILE;
2545
+ const probes = [
2546
+ [
2547
+ "invalid keyid",
2548
+ commit,
2549
+ () => formatMacRequest(c, "did:key:zNotAKey")
2550
+ ],
2551
+ [
2552
+ "keyid not a P-256 key",
2553
+ commit,
2554
+ () => formatMacRequest(c, formatDidKey("ES256K", new Uint8Array([2, ...crypto.getRandomValues(new Uint8Array(32))])))
2555
+ ],
2556
+ [
2557
+ "two requests with the tag",
2558
+ commit,
2559
+ (k) => `${formatMacRequest(c, k)}, ${formatMacRequest(c, k, { label: "mac2" })}`
2560
+ ],
2561
+ [
2562
+ "an extra parameter",
2563
+ commit,
2564
+ (k) => formatMacRequest(c, k, { params: [["created", Math.floor(Date.now() / 1e3)]] })
2565
+ ],
2566
+ [
2567
+ "alg other than hmac-sha256",
2568
+ commit,
2569
+ (k) => formatMacRequest(c, k, { params: [["alg", "ecdsa-p256-sha256"]] })
2570
+ ],
2571
+ [
2572
+ "wrong covered header",
2573
+ commit,
2574
+ (k) => formatMacRequest(c, k).replace("(\"atproto-space-commit\";sf)", "(\"atproto-space-record\";sf)")
2575
+ ],
2576
+ [
2577
+ "not a structured field",
2578
+ recordParams(ctx, space.uri),
2579
+ () => "please"
2580
+ ]
2581
+ ];
2582
+ const misses = [];
2583
+ for (const [label, params, header] of probes) {
2584
+ const res = await credentialCall(ctx, credential, params.rkey ? "com.atproto.space.getRecord" : "com.atproto.space.getLatestCommit", {
2585
+ params,
2586
+ mac: {
2587
+ profile: params.rkey ? RECORD_MAC_PROFILE : COMMIT_MAC_PROFILE,
2588
+ header
2589
+ }
2590
+ });
2591
+ if (res.error !== "InvalidSpaceMac") misses.push(`${label} → ${describe(res)}`);
2592
+ }
2593
+ return misses.length ? fail(`expected InvalidSpaceMac: ${misses.join("; ")}`) : pass("every malformed MAC request answered InvalidSpaceMac");
2594
+ });
2595
+ }
2596
+ });
2597
+ const credentialChecks = [
2598
+ credentialTokenlessPolicies,
2599
+ credentialClaims,
2600
+ credentialDefaultLifetime,
2601
+ credentialSpaceRev,
2602
+ credentialKeyP256,
2603
+ credentialGarbageDelegation,
2604
+ credentialUnverifiableAttestation,
2605
+ credentialGarbageAttestation,
2606
+ credentialAllowedApps,
2607
+ credentialValidAttestation,
2608
+ credentialUnlistedAttestation,
2609
+ credentialDeletedSpace,
2610
+ credentialUnconfirmedRegistration,
2611
+ credentialSelfRoundTrip,
2612
+ credentialPersonalOwner,
2613
+ delegationClaims,
2614
+ delegationReplay,
2615
+ delegationWrongSpace,
2616
+ credentialSignatureRequired,
2617
+ credentialSignatureByTag,
2618
+ credentialSignatureRequirements,
2619
+ credentialAudienceBound,
2620
+ credentialWrongKey,
2621
+ credentialSchemeCase,
2622
+ credentialCrossSpace,
2623
+ credentialUnhostedRepo,
2624
+ macRequired,
2625
+ macMalformed
2626
+ ];
2627
+
2628
+ //#endregion
2629
+ //#region src/checks/host.ts
2630
+ /**
2631
+ * The space-host role: the writer set (listWriters, removeWriter) and,
2632
+ * when the harness serves a syncer inbox, the notifications the host sends
2633
+ * through `authorizeSpaceSync`'s `notify` registration —
2634
+ * confirmRegistration, then notifySpaceUpdate for writes, removals and
2635
+ * deletion. Browser-safe; the inbox checks need a harness the target can
2636
+ * reach.
2637
+ */
2638
+ const L$2 = (ref) => ({
2639
+ source: "lexicon",
2640
+ ref
2641
+ });
2642
+ const P$2 = (ref) => ({
2643
+ source: "proposal",
2644
+ ref
2645
+ });
2646
+ const REPO_WRITE = "com.atproto.space.defs#repoWrite";
2647
+ const REPO_REMOVED = "com.atproto.space.defs#repoRemoved";
2648
+ const SPACE_DELETED = "com.atproto.space.notifySpaceUpdate#spaceDeleted";
2649
+ async function listWriters(ctx, credential, params = {}) {
2650
+ const res = await credentialCall(ctx, credential, "com.atproto.space.listWriters", {
2651
+ params: {
2652
+ space: credential.space,
2653
+ ...params
2654
+ },
2655
+ audience: ctx.target.did
2656
+ });
2657
+ const body = res.json;
2658
+ return {
2659
+ res,
2660
+ repos: body?.repos ?? [],
2661
+ cursor: body?.cursor
2662
+ };
2663
+ }
2664
+ /** The latest entry for `repo` in the whole writer set. */
2665
+ async function writerEntry(ctx, credential, repo) {
2666
+ const { repos } = await listWriters(ctx, credential, { limit: "1000" });
2667
+ return repos.filter((r) => r.repo === repo).at(-1);
2668
+ }
2669
+ const hostRequiresCredential = defineCheck({
2670
+ id: "host.listwriters-requires-credential",
2671
+ title: "listWriters refuses an unauthenticated caller",
2672
+ tier: "must",
2673
+ citations: [L$2("com.atproto.space.listWriters")],
2674
+ needs: ["operator"],
2675
+ destructive: true,
2676
+ async run(ctx) {
2677
+ const space = await createProbeSpace(ctx, publicRead());
2678
+ try {
2679
+ const res = await xrpcGet(ctx, "com.atproto.space.listWriters", { space: space.uri });
2680
+ return res.status === 401 || res.status === 403 ? pass(`refused with ${res.status}`) : fail(`unauthenticated listWriters returned ${describe(res)}`, res.json);
2681
+ } finally {
2682
+ await deleteProbeSpace(ctx, space.uri);
2683
+ }
2684
+ }
2685
+ });
2686
+ const listWritersShape = defineCheck({
2687
+ id: "sync.listwriters-shape",
2688
+ title: "listWriters lists typed repoWrite entries by ascending spaceRev, resumable by cursor",
2689
+ tier: "must",
2690
+ citations: [
2691
+ L$2("com.atproto.space.listWriters"),
2692
+ L$2("com.atproto.space.defs#repoWrite"),
2693
+ P$2("0016#the-sync-boundary-writer-set")
2694
+ ],
2695
+ needs: ["operator"],
2696
+ destructive: true,
2697
+ async run(ctx) {
2698
+ const space = await createProbeSpace(ctx, publicRead());
2699
+ try {
2700
+ await mustCreateRecord(ctx, space.uri, "a");
2701
+ await mustCreateRecord(ctx, space.uri, "b");
2702
+ const credential = await obtainPublicCredential(ctx, space.uri);
2703
+ const page = await listWriters(ctx, credential);
2704
+ if (page.res.status !== 200) return fail(`listWriters ${describe(page.res)}`, page.res.json);
2705
+ const problems = [];
2706
+ for (const entry of page.repos) {
2707
+ if (entry.$type !== REPO_WRITE && entry.$type !== REPO_REMOVED) problems.push(`entry $type ${String(entry.$type)}`);
2708
+ if (!isTid(entry.spaceRev)) problems.push(`${entry.repo} spaceRev ${String(entry.spaceRev)}`);
2709
+ if (entry.$type === REPO_WRITE) {
2710
+ if (!isTid(entry.repoRev)) problems.push(`${entry.repo} repoRev ${String(entry.repoRev)}`);
2711
+ if (lexBytes(entry.data)?.length !== 32) problems.push(`${entry.repo} data is not 32 bytes`);
2712
+ }
2713
+ if ("prevSpaceRev" in entry) problems.push("listWriters entries carry prevSpaceRev");
2714
+ }
2715
+ const revs = page.repos.map((r) => String(r.spaceRev));
2716
+ if (revs.some((rev, i) => i > 0 && rev <= revs[i - 1])) problems.push(`not ascending: ${revs.join(",")}`);
2717
+ 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");
2718
+ if (!page.cursor) problems.push("a non-empty page carried no cursor");
2719
+ if (problems.length) return fail(problems.join("; "), page.res.json);
2720
+ const next = await listWriters(ctx, credential, { cursor: page.cursor });
2721
+ if (next.res.status !== 200) return fail(`listWriters(cursor) ${describe(next.res)}`, next.res.json);
2722
+ return next.repos.length === 0 ? pass(`${page.repos.length} writer(s), typed and ascending; the cursor resumes after them`) : fail(`after the last cursor: ${next.repos.length} repo(s) again`, next.res.json);
2723
+ } finally {
2724
+ await deleteProbeSpace(ctx, space.uri);
2725
+ }
2726
+ }
2727
+ });
2728
+ const listWritersReflects = defineCheck({
2729
+ id: "sync.listwriters-reflects-writes",
2730
+ title: "The authority's listWriters entry matches its latest commit",
2731
+ tier: "should",
2732
+ citations: [{
2733
+ source: "reference",
2734
+ ref: "authority repo notifies its own space host synchronously"
2735
+ }, L$2("com.atproto.space.listWriters")],
2736
+ needs: ["operator"],
2737
+ destructive: true,
2738
+ async run(ctx) {
2739
+ const space = await createProbeSpace(ctx, publicRead());
2740
+ try {
2741
+ await mustCreateRecord(ctx, space.uri, "a");
2742
+ const mine = await writerEntry(ctx, await obtainPublicCredential(ctx, space.uri), ctx.target.did);
2743
+ const commit = (await xrpcGet(asOperator(ctx), "com.atproto.space.getLatestCommit", {
2744
+ space: space.uri,
2745
+ repo: ctx.target.did
2746
+ })).json?.commit;
2747
+ const a = lexBytes(mine?.data);
2748
+ const b = lexBytes(commit?.data);
2749
+ return mine && commit && mine.repoRev === commit.rev && a && b && bytesEqual(a, b) ? pass("repoRev and data match getLatestCommit") : fail("listWriters entry differs from the latest commit", {
2750
+ listed: mine,
2751
+ commit
2752
+ });
2753
+ } finally {
2754
+ await deleteProbeSpace(ctx, space.uri);
2755
+ }
2756
+ }
2757
+ });
2758
+ const removeWriter = defineCheck({
2759
+ id: "host.removewriter",
2760
+ title: "removeWriter lists the repo as repoRemoved until it writes again",
2761
+ tier: "must",
2762
+ citations: [
2763
+ L$2("com.atproto.space.removeWriter"),
2764
+ L$2("com.atproto.space.listWriters"),
2765
+ L$2("com.atproto.space.defs#repoRemoved"),
2766
+ P$2("0016#the-sync-boundary-writer-set")
2767
+ ],
2768
+ needs: ["operator"],
2769
+ destructive: true,
2770
+ async run(ctx) {
2771
+ const space = await createProbeSpace(ctx, publicRead());
2772
+ const remove = (repo) => xrpcPost(asOperator(ctx), "com.atproto.space.removeWriter", {
2773
+ space: space.uri,
2774
+ repo
2775
+ });
2776
+ try {
2777
+ await mustCreateRecord(ctx, space.uri, "a");
2778
+ const credential = await obtainPublicCredential(ctx, space.uri);
2779
+ const before = await writerEntry(ctx, credential, ctx.target.did);
2780
+ if (before?.$type !== REPO_WRITE) return fail("the authority's repo was not in the writer set to begin with");
2781
+ const removed = await remove(ctx.target.did);
2782
+ if (removed.status !== 200) return fail(`removeWriter ${describe(removed)}`, removed.json);
2783
+ const gone = await writerEntry(ctx, credential, ctx.target.did);
2784
+ if (gone?.$type !== REPO_REMOVED) return fail(`after removeWriter the entry is ${JSON.stringify(gone)}`);
2785
+ if (!(String(gone.spaceRev) > String(before.spaceRev))) return fail("the removal was not sequenced after the write");
2786
+ const absent = await remove(fakeDid());
2787
+ if (absent.status !== 200) return fail(`removeWriter of a non-writer returned ${describe(absent)}`, absent.json);
2788
+ await mustCreateRecord(ctx, space.uri, "b");
2789
+ const back = await writerEntry(ctx, credential, ctx.target.did);
2790
+ return back?.$type === REPO_WRITE ? pass("listed as repoRemoved at a later spaceRev; no-op for a non-writer; a new write re-added it") : fail(`after a new write the entry is ${JSON.stringify(back)}`);
2791
+ } finally {
2792
+ await deleteProbeSpace(ctx, space.uri);
2793
+ }
2794
+ }
2795
+ });
2796
+ const hostAfterDelete = defineCheck({
2797
+ id: "host.deleted-space-not-found",
2798
+ title: "listWriters on a deleted space answers SpaceNotFound",
2799
+ tier: "must",
2800
+ citations: [L$2("com.atproto.space.listWriters@error:SpaceNotFound")],
2801
+ needs: ["operator"],
2802
+ destructive: true,
2803
+ async run(ctx) {
2804
+ const space = await createProbeSpace(ctx, publicRead());
2805
+ const credential = await obtainPublicCredential(ctx, space.uri);
2806
+ await deleteProbeSpace(ctx, space.uri);
2807
+ const { res } = await listWriters(ctx, credential);
2808
+ return res.error === "SpaceNotFound" ? pass("answered SpaceNotFound") : fail(`answered ${describe(res)}, expected SpaceNotFound`, res.json);
2809
+ }
2810
+ });
2811
+ const NOTIFY_TIMEOUT_MS = 1e4;
2812
+ /** Authorise with a fresh notify registration at the inbox. */
2813
+ async function register(ctx, inbox, space) {
2814
+ const token = inbox.issueToken(space);
2815
+ return {
2816
+ token,
2817
+ since: Date.now(),
2818
+ ...await requestCredential(ctx, space, { notify: {
2819
+ endpoint: inbox.endpoint,
2820
+ token
2821
+ } })
2822
+ };
2823
+ }
2824
+ const updatesFor = (space, token, type, since) => (d) => {
2825
+ const body = d.body;
2826
+ return d.lxm === "com.atproto.space.notifySpaceUpdate" && d.receivedAt >= since && body?.space === space && body.token === token && body.update?.$type === type;
2827
+ };
2828
+ const notifyConfirmed = defineCheck({
2829
+ id: "notify.registration-confirmed",
2830
+ title: "A notify registration is confirmed with a challenge before the credential is issued",
2831
+ tier: "must",
2832
+ citations: [
2833
+ L$2("com.atproto.space.confirmRegistration"),
2834
+ L$2("com.atproto.space.authorizeSpaceSync#notify"),
2835
+ P$2("0016#registering-for-notifications")
2836
+ ],
2837
+ needs: ["operator", "syncer-inbox"],
2838
+ destructive: true,
2839
+ async run(ctx) {
2840
+ const inbox = ctx.syncerInbox;
2841
+ const space = await createProbeSpace(ctx, publicRead());
2842
+ try {
2843
+ const reg = await register(ctx, inbox, space.uri);
2844
+ if (!reg.credential) return fail(`authorizeSpaceSync with notify ${describe(reg.result)}`, reg.result.json);
2845
+ const confirm = await inbox.waitFor((d) => d.lxm === "com.atproto.space.confirmRegistration" && d.receivedAt >= reg.since && d.body?.token === reg.token, 1e3);
2846
+ if (!confirm) return fail("the credential was issued without calling confirmRegistration");
2847
+ const body = confirm.body;
2848
+ if (body.space !== space.uri) return fail(`confirmRegistration named space ${body.space}`);
2849
+ if (typeof body.challenge !== "string" || body.challenge.length < 8) return fail("confirmRegistration carried no real challenge", body);
2850
+ return pass("confirmRegistration (space, token, challenge) preceded the credential");
2851
+ } finally {
2852
+ await deleteProbeSpace(ctx, space.uri);
2853
+ }
2854
+ }
2855
+ });
2856
+ const notifyRenewal = defineCheck({
2857
+ id: "notify.renewal-not-reconfirmed",
2858
+ title: "Reauthorizing with the same notify pair renews without confirming again",
2859
+ tier: "should",
2860
+ citations: [{
2861
+ source: "reference",
2862
+ ref: "pds authorizeSpaceSync confirms only unregistered pairs"
2863
+ }, P$2("0016#registering-for-notifications")],
2864
+ needs: ["operator", "syncer-inbox"],
2865
+ destructive: true,
2866
+ async run(ctx) {
2867
+ const inbox = ctx.syncerInbox;
2868
+ const space = await createProbeSpace(ctx, publicRead());
2869
+ try {
2870
+ const first = await register(ctx, inbox, space.uri);
2871
+ if (!first.credential) return fail(`authorizeSpaceSync ${describe(first.result)}`);
2872
+ if (!await inbox.waitFor((d) => d.lxm === "com.atproto.space.confirmRegistration" && d.receivedAt >= first.since && d.body?.token === first.token, 1e3)) return fail("the first registration was never confirmed, so the renewal's lack of one proves nothing");
2873
+ const since = Date.now();
2874
+ const again = await requestCredential(ctx, space.uri, { notify: {
2875
+ endpoint: inbox.endpoint,
2876
+ token: first.token
2877
+ } });
2878
+ if (!again.credential) return fail(`reauthorizing ${describe(again.result)}`);
2879
+ return await inbox.waitFor((d) => d.lxm === "com.atproto.space.confirmRegistration" && d.receivedAt >= since && d.body?.token === first.token, 500) ? fail("the renewal was confirmed again") : pass("the first registration was confirmed; the renewal was not confirmed again");
2880
+ } finally {
2881
+ await deleteProbeSpace(ctx, space.uri);
2882
+ }
2883
+ }
2884
+ });
2885
+ const notifyRepoWrite = defineCheck({
2886
+ id: "notify.repo-write-delivered",
2887
+ title: "A registered syncer receives sequenced repoWrite updates",
2888
+ tier: "must",
2889
+ citations: [
2890
+ L$2("com.atproto.space.notifySpaceUpdate"),
2891
+ L$2("com.atproto.space.defs#repoWrite"),
2892
+ P$2("0016#write-notifications")
2893
+ ],
2894
+ needs: ["operator", "syncer-inbox"],
2895
+ destructive: true,
2896
+ async run(ctx) {
2897
+ const inbox = ctx.syncerInbox;
2898
+ const space = await createProbeSpace(ctx, publicRead());
2899
+ try {
2900
+ await mustCreateRecord(ctx, space.uri, "before");
2901
+ const reg = await register(ctx, inbox, space.uri);
2902
+ if (!reg.credential) return fail(`authorizeSpaceSync with notify ${describe(reg.result)}`, reg.result.json);
2903
+ const since = Date.now();
2904
+ await mustCreateRecord(ctx, space.uri, "one");
2905
+ const first = await inbox.waitFor(updatesFor(space.uri, reg.token, REPO_WRITE, since), NOTIFY_TIMEOUT_MS);
2906
+ if (!first) return fail("no repoWrite reached the syncer after a write");
2907
+ const a = first.body.update;
2908
+ await mustCreateRecord(ctx, space.uri, "two");
2909
+ const second = await inbox.waitFor((d) => updatesFor(space.uri, reg.token, REPO_WRITE, first.receivedAt)(d) && d.body.update.spaceRev !== a.spaceRev, NOTIFY_TIMEOUT_MS);
2910
+ if (!second) return fail("no repoWrite reached the syncer after a second write");
2911
+ const b = second.body.update;
2912
+ const problems = [];
2913
+ for (const [label, u] of [["first", a], ["second", b]]) {
2914
+ if (u.repo !== ctx.target.did) problems.push(`${label} repo ${String(u.repo)}`);
2915
+ if (!isTid(u.repoRev)) problems.push(`${label} repoRev ${String(u.repoRev)}`);
2916
+ if (!isTid(u.spaceRev)) problems.push(`${label} has no spaceRev`);
2917
+ if (lexBytes(u.data)?.length !== 32) problems.push(`${label} data is not 32 bytes`);
2918
+ }
2919
+ if (a.prevSpaceRev === void 0) problems.push("first update has no prevSpaceRev");
2920
+ if (b.prevSpaceRev !== a.spaceRev) problems.push(`second prevSpaceRev ${String(b.prevSpaceRev)} ≠ first spaceRev ${String(a.spaceRev)}`);
2921
+ return problems.length ? fail(problems.join("; "), {
2922
+ first: a,
2923
+ second: b
2924
+ }) : pass("two repoWrite updates carrying the token; prevSpaceRev chains");
2925
+ } finally {
2926
+ await deleteProbeSpace(ctx, space.uri);
2927
+ }
2928
+ }
2929
+ });
2930
+ const notifyRepoRemoved = defineCheck({
2931
+ id: "notify.repo-removed-delivered",
2932
+ title: "removeWriter is announced to registered syncers as repoRemoved",
2933
+ tier: "must",
2934
+ citations: [
2935
+ L$2("com.atproto.space.removeWriter"),
2936
+ L$2("com.atproto.space.defs#repoRemoved"),
2937
+ L$2("com.atproto.space.notifySpaceUpdate"),
2938
+ P$2("0016#the-sync-boundary-writer-set")
2939
+ ],
2940
+ needs: ["operator", "syncer-inbox"],
2941
+ destructive: true,
2942
+ async run(ctx) {
2943
+ const inbox = ctx.syncerInbox;
2944
+ const space = await createProbeSpace(ctx, publicRead());
2945
+ try {
2946
+ await mustCreateRecord(ctx, space.uri, "a");
2947
+ const reg = await register(ctx, inbox, space.uri);
2948
+ if (!reg.credential) return fail(`authorizeSpaceSync with notify ${describe(reg.result)}`, reg.result.json);
2949
+ const since = Date.now();
2950
+ const removed = await xrpcPost(asOperator(ctx), "com.atproto.space.removeWriter", {
2951
+ space: space.uri,
2952
+ repo: ctx.target.did
2953
+ });
2954
+ if (removed.status !== 200) return fail(`removeWriter ${describe(removed)}`, removed.json);
2955
+ const got = await inbox.waitFor(updatesFor(space.uri, reg.token, REPO_REMOVED, since), NOTIFY_TIMEOUT_MS);
2956
+ if (!got) return fail("no repoRemoved reached the syncer");
2957
+ const u = got.body.update;
2958
+ return u.repo === ctx.target.did && isTid(u.spaceRev) && isTid(u.prevSpaceRev) ? pass("repoRemoved delivered with spaceRev and prevSpaceRev") : fail("repoRemoved fields wrong", u);
2959
+ } finally {
2960
+ await deleteProbeSpace(ctx, space.uri);
2961
+ }
2962
+ }
2963
+ });
2964
+ const notifySpaceDeleted = defineCheck({
2965
+ id: "notify.space-deleted-delivered",
2966
+ title: "A registered syncer is sent spaceDeleted when the space is deleted",
2967
+ tier: "must",
2968
+ citations: [L$2("com.atproto.space.notifySpaceUpdate#spaceDeleted"), P$2("0016#space-deletion")],
2969
+ needs: ["operator", "syncer-inbox"],
2970
+ destructive: true,
2971
+ async run(ctx) {
2972
+ const inbox = ctx.syncerInbox;
2973
+ const space = await createProbeSpace(ctx, publicRead());
2974
+ let deleted = false;
2975
+ try {
2976
+ const reg = await register(ctx, inbox, space.uri);
2977
+ if (!reg.credential) return fail(`authorizeSpaceSync with notify ${describe(reg.result)}`, reg.result.json);
2978
+ const since = Date.now();
2979
+ await deleteProbeSpace(ctx, space.uri);
2980
+ deleted = true;
2981
+ return await inbox.waitFor(updatesFor(space.uri, reg.token, SPACE_DELETED, since), NOTIFY_TIMEOUT_MS) ? pass("spaceDeleted delivered") : fail(`no spaceDeleted within ${NOTIFY_TIMEOUT_MS / 1e3}s`);
2982
+ } finally {
2983
+ if (!deleted) await deleteProbeSpace(ctx, space.uri);
2984
+ }
2985
+ }
2986
+ });
2987
+ const notifyExpired = defineCheck({
2988
+ id: "notify.registration-expired",
2989
+ title: "Once its credential expires, a registration is sent registrationExpired in place of the next update",
2990
+ tier: "must",
2991
+ citations: [L$2("com.atproto.space.notifySpaceUpdate#registrationExpired"), P$2("0016#registering-for-notifications")],
2992
+ needs: ["operator", "syncer-inbox"],
2993
+ destructive: true,
2994
+ slow: true,
2995
+ timeoutMs: 65 * 6e4,
2996
+ async run(ctx) {
2997
+ const inbox = ctx.syncerInbox;
2998
+ const space = await createProbeSpace(ctx, publicRead());
2999
+ try {
3000
+ const reg = await register(ctx, inbox, space.uri);
3001
+ if (!reg.credential) return fail(`authorizeSpaceSync with notify ${describe(reg.result)}`, reg.result.json);
3002
+ const exp = Number(decodeJwt(reg.credential.credential).payload.exp) * 1e3;
3003
+ await new Promise((r) => setTimeout(r, Math.max(0, exp - Date.now()) + 5e3));
3004
+ const since = Date.now();
3005
+ await mustCreateRecord(ctx, space.uri, "late");
3006
+ const got = await inbox.waitFor((d) => updatesFor(space.uri, reg.token, "com.atproto.space.notifySpaceUpdate#registrationExpired", since)(d), NOTIFY_TIMEOUT_MS);
3007
+ if (!got) return fail("no registrationExpired after the credential lapsed");
3008
+ const update = got.body.update;
3009
+ if (await inbox.waitFor(updatesFor(space.uri, reg.token, REPO_WRITE, since), 2e3)) return fail("a lapsed registration still received the repoWrite");
3010
+ return isTid(update.spaceRev) ? pass("registrationExpired sent in place of the update") : fail("registrationExpired has no spaceRev", update);
3011
+ } finally {
3012
+ await deleteProbeSpace(ctx, space.uri);
3013
+ }
3014
+ }
3015
+ });
3016
+ const CHECK_ACCESS = "com.atproto.managedspace.checkAccess";
3017
+ const managedTokenless = defineCheck({
3018
+ id: "managedspace.check-access-tokenless",
3019
+ title: "Without a delegation token a managedspace asks its managing app, with no repo",
3020
+ tier: "must",
3021
+ citations: [
3022
+ L$2("com.atproto.managedspace.checkAccess"),
3023
+ L$2("com.atproto.managedspace.policy"),
3024
+ P$2("0016#managedspace")
3025
+ ],
3026
+ needs: ["operator", "syncer-inbox"],
3027
+ destructive: true,
3028
+ async run(ctx) {
3029
+ const inbox = ctx.syncerInbox;
3030
+ let answer = {
3031
+ read: false,
3032
+ write: false
3033
+ };
3034
+ inbox.respond(CHECK_ACCESS, () => answer);
3035
+ const space = await createProbeSpace(ctx, managedspace(inbox.service));
3036
+ try {
3037
+ const since = Date.now();
3038
+ const denied = await requestCredential(ctx, space.uri);
3039
+ if (denied.credential) return fail("issued a credential the managing app refused");
3040
+ const asked = await inbox.waitFor((d) => d.lxm === CHECK_ACCESS && d.receivedAt >= since, 5e3);
3041
+ if (!asked) return fail(`the managing app was never asked (${describe(denied.result)})`);
3042
+ const p = asked.params ?? {};
3043
+ if (p.space !== space.uri || "repo" in p || "access" in p) return fail("checkAccess params wrong for a tokenless request", p);
3044
+ const jwt = asked.authorization?.replace(/^Bearer /, "");
3045
+ const claims = jwt ? decodeJwt(jwt).payload : void 0;
3046
+ 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);
3047
+ answer = {
3048
+ read: true,
3049
+ write: false
3050
+ };
3051
+ const allowed = await requestCredential(ctx, space.uri);
3052
+ 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)}`);
3053
+ } finally {
3054
+ inbox.respond(CHECK_ACCESS, void 0);
3055
+ await deleteProbeSpace(ctx, space.uri);
3056
+ }
3057
+ }
3058
+ });
3059
+ /** A managing app no host can resolve, let alone reach. */
3060
+ const UNREACHABLE_APP = "did:web:app.space-conformance.invalid#managing_app";
3061
+ /**
3062
+ * Ask for a tokenless credential from a managedspace whose managing app
3063
+ * cannot answer, two ways — unresolvable, and the inbox answering
3064
+ * checkAccess with an error — after a same-run control: the inbox, answering
3065
+ * `{read: true}`, gets one issued. Without the control a host that refuses
3066
+ * every managedspace would pass for failing closed.
3067
+ */
3068
+ async function unansweredManagingApp(ctx) {
3069
+ const inbox = ctx.syncerInbox;
3070
+ const reachable = await createProbeSpace(ctx, managedspace(inbox.service));
3071
+ const erroring = await createProbeSpace(ctx, managedspace(inbox.service));
3072
+ const unreachable = await createProbeSpace(ctx, managedspace(UNREACHABLE_APP));
3073
+ try {
3074
+ inbox.respond(CHECK_ACCESS, () => ({
3075
+ read: true,
3076
+ write: false
3077
+ }));
3078
+ const ok = await requestCredential(ctx, reachable.uri);
3079
+ if (!ok.credential) return { failure: fail(`positive control failed: a managing app answering read:true got no credential issued (${describe(ok.result)})`, ok.result.json) };
3080
+ inbox.respond(CHECK_ACCESS, void 0);
3081
+ return { results: [["unresolvable app", await requestCredential(ctx, unreachable.uri)], ["app answering with an error", await requestCredential(ctx, erroring.uri)]] };
3082
+ } finally {
3083
+ inbox.respond(CHECK_ACCESS, void 0);
3084
+ for (const s of [
3085
+ reachable,
3086
+ erroring,
3087
+ unreachable
3088
+ ]) await deleteProbeSpace(ctx, s.uri);
3089
+ }
3090
+ }
3091
+ const managedFailsClosed = defineCheck({
3092
+ id: "managedspace.unreachable-app-fails-closed",
3093
+ title: "A managedspace whose managing app cannot be reached issues no credential",
3094
+ tier: "must",
3095
+ citations: [
3096
+ L$2("com.atproto.managedspace.policy"),
3097
+ P$2("0016#managedspace"),
3098
+ {
3099
+ source: "changeset",
3100
+ ref: "patient-managers-answer"
3101
+ }
3102
+ ],
3103
+ needs: ["operator", "syncer-inbox"],
3104
+ destructive: true,
3105
+ async run(ctx) {
3106
+ const outcome = await unansweredManagingApp(ctx);
3107
+ if ("failure" in outcome) return outcome.failure;
3108
+ const misses = outcome.results.filter(([, r]) => r.credential || r.result.status < 400).map(([label, r]) => r.credential ? `${label} → issued` : `${label} → ${describe(r.result)}`);
3109
+ return misses.length ? fail(`did not fail closed: ${misses.join("; ")}`) : pass(`a managing app answering read:true issued; without an answer refused (${outcome.results.map(([l, r]) => `${l}: ${describe(r.result)}`).join(", ")})`);
3110
+ }
3111
+ });
3112
+ const managedUpstreamFailure = defineCheck({
3113
+ id: "managedspace.unreachable-app-upstream-failure",
3114
+ title: "An unreachable managing app is reported as UpstreamFailure, not a refusal",
3115
+ tier: "should",
3116
+ citations: [{
3117
+ source: "changeset",
3118
+ ref: "patient-managers-answer"
3119
+ }],
3120
+ needs: ["operator", "syncer-inbox"],
3121
+ destructive: true,
3122
+ async run(ctx) {
3123
+ const outcome = await unansweredManagingApp(ctx);
3124
+ if ("failure" in outcome) return outcome.failure;
3125
+ const misses = outcome.results.filter(([, r]) => r.result.error !== "UpstreamFailure").map(([label, r]) => `${label} → ${describe(r.result)}`);
3126
+ return misses.length ? fail(`expected UpstreamFailure: ${misses.join("; ")}`) : pass("a managing app answering read:true issued; unresolvable and erroring apps answered UpstreamFailure");
3127
+ }
3128
+ });
3129
+ const hostChecks = [
3130
+ hostRequiresCredential,
3131
+ listWritersShape,
3132
+ listWritersReflects,
3133
+ removeWriter,
3134
+ hostAfterDelete,
3135
+ notifyConfirmed,
3136
+ notifyRenewal,
3137
+ notifyRepoWrite,
3138
+ notifyRepoRemoved,
3139
+ notifySpaceDeleted,
3140
+ notifyExpired,
3141
+ managedTokenless,
3142
+ managedFailsClosed,
3143
+ managedUpstreamFailure
3144
+ ];
3145
+
3146
+ //#endregion
3147
+ //#region src/checks/records.ts
3148
+ /**
3149
+ * Record writes and the owner's own reads: create/put/delete/applyWrites,
3150
+ * clearRecords, listRecords, blobs, and the SpaceNotFound perimeter around
3151
+ * spaces that do not exist or were deleted. Operator-only, browser-safe.
3152
+ */
3153
+ const L$1 = (ref) => ({
3154
+ source: "lexicon",
3155
+ ref
3156
+ });
3157
+ const C$1 = (ref) => ({
3158
+ source: "changeset",
3159
+ ref
3160
+ });
3161
+ const P$1 = (ref) => ({
3162
+ source: "proposal",
3163
+ ref
3164
+ });
3165
+ const op = asOperator;
3166
+ const writesCreateRead = defineCheck({
3167
+ id: "writes.create-and-read",
3168
+ title: "Operator creates a record and reads it back, addressed by its at:space/ uri",
3169
+ tier: "must",
3170
+ citations: [
3171
+ L$1("com.atproto.space.createRecord"),
3172
+ L$1("com.atproto.space.getRecord"),
3173
+ C$1("spaces-syntax"),
3174
+ C$1("pds-space-uri-migration")
3175
+ ],
3176
+ needs: ["operator"],
3177
+ destructive: true,
3178
+ async run(ctx) {
3179
+ const space = await createProbeSpace(ctx);
3180
+ try {
3181
+ const created = await operatorCreateRecord(ctx, space.uri, POST, "rec1", note("hello"));
3182
+ if (created.status !== 200) return fail(`createRecord ${describe(created)}`, created.json);
3183
+ const read = await operatorGetRecord(ctx, space.uri, "rec1");
3184
+ if (read.status !== 200) return fail(`getRecord ${describe(read)}`, read.json);
3185
+ const body = read.json;
3186
+ if (body.cid !== created.json.cid) return fail("getRecord cid differs from the createRecord cid", read.json);
3187
+ const uri = spaceRecordUri(spaceUri(ctx.target.did, space.skey), ctx.target.did, POST, "rec1");
3188
+ const createdUri = created.json.uri;
3189
+ if (createdUri !== uri || body.uri !== uri) return fail(`record uri was ${createdUri} (createRecord) / ${body.uri} (getRecord), expected ${uri}`, {
3190
+ created: created.json,
3191
+ read: read.json
3192
+ });
3193
+ return body.value?.text === "hello" ? pass("round-tripped the record value and cid, at its at:space/ uri") : fail("record value did not round-trip", read.json);
3194
+ } finally {
3195
+ await deleteProbeSpace(ctx, space.uri);
3196
+ }
3197
+ }
3198
+ });
3199
+ const writesUnauthReadRefused = defineCheck({
3200
+ id: "auth.existing-record-unauth-refused",
3201
+ title: "An existing space record is not readable without auth",
3202
+ tier: "must",
3203
+ citations: [L$1("com.atproto.space.getRecord")],
3204
+ needs: ["operator"],
3205
+ destructive: true,
3206
+ async run(ctx) {
3207
+ const space = await createProbeSpace(ctx);
3208
+ try {
3209
+ await mustCreateRecord(ctx, space.uri, "private", "not for you");
3210
+ const res = await xrpcGet(ctx, "com.atproto.space.getRecord", {
3211
+ space: space.uri,
3212
+ repo: ctx.target.did,
3213
+ collection: POST,
3214
+ rkey: "private"
3215
+ });
3216
+ if (res.status === 200) return fail("an existing space record was served with no auth", res.json);
3217
+ 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);
3218
+ } finally {
3219
+ await deleteProbeSpace(ctx, space.uri);
3220
+ }
3221
+ }
3222
+ });
3223
+ const writesDuplicate = defineCheck({
3224
+ id: "writes.duplicate-rejected",
3225
+ title: "A second create at the same key is refused with RecordAlreadyExists",
3226
+ tier: "must",
3227
+ citations: [L$1("com.atproto.space.createRecord@error:RecordAlreadyExists")],
3228
+ needs: ["operator"],
3229
+ destructive: true,
3230
+ async run(ctx) {
3231
+ const space = await createProbeSpace(ctx);
3232
+ try {
3233
+ await mustCreateRecord(ctx, space.uri, "dup", "one");
3234
+ const second = await operatorCreateRecord(ctx, space.uri, POST, "dup", note("two"));
3235
+ if (second.status === 200) return fail("duplicate create returned 200");
3236
+ return second.error === "RecordAlreadyExists" ? pass("refused with RecordAlreadyExists") : fail(`refused but error was ${describe(second)}`, second.json);
3237
+ } finally {
3238
+ await deleteProbeSpace(ctx, space.uri);
3239
+ }
3240
+ }
3241
+ });
3242
+ const writesPutRecord = defineCheck({
3243
+ id: "writes.putrecord-upsert",
3244
+ title: "putRecord creates a record and then replaces it",
3245
+ tier: "must",
3246
+ citations: [L$1("com.atproto.space.putRecord")],
3247
+ needs: ["operator"],
3248
+ destructive: true,
3249
+ async run(ctx) {
3250
+ const space = await createProbeSpace(ctx);
3251
+ const put = (text) => xrpcPost(op(ctx), "com.atproto.space.putRecord", {
3252
+ space: space.uri,
3253
+ repo: ctx.target.did,
3254
+ collection: POST,
3255
+ rkey: "upsert",
3256
+ record: note(text)
3257
+ });
3258
+ try {
3259
+ const first = await put("v1");
3260
+ if (first.status !== 200) return fail(`putRecord (create) ${describe(first)}`, first.json);
3261
+ const second = await put("v2");
3262
+ if (second.status !== 200) return fail(`putRecord (update) ${describe(second)}`, second.json);
3263
+ const read = await operatorGetRecord(ctx, space.uri, "upsert");
3264
+ const text = read.json?.value?.text;
3265
+ return text === "v2" ? pass("created then replaced the record") : fail(`after two puts the record reads ${describe(read)} ${text}`, read.json);
3266
+ } finally {
3267
+ await deleteProbeSpace(ctx, space.uri);
3268
+ }
3269
+ }
3270
+ });
3271
+ const writesGetRecordMissing = defineCheck({
3272
+ id: "writes.getrecord-missing",
3273
+ title: "getRecord of an absent rkey answers RecordNotFound",
3274
+ tier: "must",
3275
+ citations: [L$1("com.atproto.space.getRecord@error:RecordNotFound")],
3276
+ needs: ["operator"],
3277
+ destructive: true,
3278
+ async run(ctx) {
3279
+ const space = await createProbeSpace(ctx);
3280
+ try {
3281
+ await mustCreateRecord(ctx, space.uri, "present");
3282
+ const res = await operatorGetRecord(ctx, space.uri, "absent");
3283
+ return res.error === "RecordNotFound" ? pass("answered RecordNotFound") : fail(`answered ${describe(res)}, expected RecordNotFound`, res.json);
3284
+ } finally {
3285
+ await deleteProbeSpace(ctx, space.uri);
3286
+ }
3287
+ }
3288
+ });
3289
+ const writesDeleteIdempotent = defineCheck({
3290
+ id: "writes.delete-idempotent",
3291
+ title: "deleteRecord removes the record and is idempotent",
3292
+ tier: "must",
3293
+ citations: [L$1("com.atproto.space.deleteRecord"), L$1("com.atproto.space.getRecord")],
3294
+ needs: ["operator"],
3295
+ destructive: true,
3296
+ async run(ctx) {
3297
+ const space = await createProbeSpace(ctx);
3298
+ try {
3299
+ const del = (rkey) => xrpcPost(op(ctx), "com.atproto.space.deleteRecord", {
3300
+ space: space.uri,
3301
+ repo: ctx.target.did,
3302
+ collection: POST,
3303
+ rkey
3304
+ });
3305
+ await mustCreateRecord(ctx, space.uri, "doomed", "bye");
3306
+ const removed = await del("doomed");
3307
+ if (removed.status !== 200) return fail(`delete of an existing record returned ${describe(removed)}`, removed.json);
3308
+ const after = await operatorGetRecord(ctx, space.uri, "doomed");
3309
+ if (after.status === 200) return fail("a deleted record was still readable", after.json);
3310
+ const again = await del("doomed");
3311
+ const ghost = await del("ghost");
3312
+ if (again.status !== 200 || ghost.status !== 200) return fail(`repeat delete returned ${describe(again)}, absent-key delete returned ${describe(ghost)}`, {
3313
+ again: again.json,
3314
+ ghost: ghost.json
3315
+ });
3316
+ return pass("delete removed the record; repeat and absent deletes 200");
3317
+ } finally {
3318
+ await deleteProbeSpace(ctx, space.uri);
3319
+ }
3320
+ }
3321
+ });
3322
+ const create = (rkey, text) => ({
3323
+ $type: "com.atproto.space.applyWrites#create",
3324
+ collection: POST,
3325
+ rkey,
3326
+ value: note(text)
3327
+ });
3328
+ const writesApplyWritesAtomic = defineCheck({
3329
+ id: "writes.applywrites-atomic",
3330
+ title: "A failing applyWrites batch commits nothing",
3331
+ tier: "must",
3332
+ citations: [L$1("com.atproto.space.applyWrites"), L$1("com.atproto.space.applyWrites@error:RecordAlreadyExists")],
3333
+ needs: ["operator"],
3334
+ destructive: true,
3335
+ async run(ctx) {
3336
+ const space = await createProbeSpace(ctx);
3337
+ try {
3338
+ await mustCreateRecord(ctx, space.uri, "exists", "here");
3339
+ const ok = await xrpcPost(op(ctx), "com.atproto.space.applyWrites", {
3340
+ space: space.uri,
3341
+ repo: ctx.target.did,
3342
+ writes: [create("ok1", "1"), create("ok2", "2")]
3343
+ });
3344
+ if (ok.status !== 200) return fail(`applyWrites did not accept a valid batch (${describe(ok)})`, ok.json);
3345
+ const batch = await xrpcPost(op(ctx), "com.atproto.space.applyWrites", {
3346
+ space: space.uri,
3347
+ repo: ctx.target.did,
3348
+ writes: [create("fresh", "new"), create("exists", "collide")]
3349
+ });
3350
+ if (batch.status === 200) return fail("colliding batch returned 200");
3351
+ if (batch.error !== "RecordAlreadyExists") return fail(`colliding batch refused with ${describe(batch)}, expected RecordAlreadyExists`, batch.json);
3352
+ const check = await operatorGetRecord(ctx, space.uri, "fresh");
3353
+ return check.status !== 200 ? pass("a failed batch committed nothing") : fail("a failed batch left its first op committed", check.json);
3354
+ } finally {
3355
+ await deleteProbeSpace(ctx, space.uri);
3356
+ }
3357
+ }
3358
+ });
3359
+ const writesApplyWritesMissing = defineCheck({
3360
+ id: "writes.applywrites-update-missing",
3361
+ title: "An applyWrites update of an absent record answers RecordNotFound",
3362
+ tier: "must",
3363
+ citations: [L$1("com.atproto.space.applyWrites"), L$1("com.atproto.space.applyWrites@error:RecordNotFound")],
3364
+ needs: ["operator"],
3365
+ destructive: true,
3366
+ async run(ctx) {
3367
+ const space = await createProbeSpace(ctx);
3368
+ const update = (rkey, text) => xrpcPost(op(ctx), "com.atproto.space.applyWrites", {
3369
+ space: space.uri,
3370
+ repo: ctx.target.did,
3371
+ writes: [{
3372
+ $type: "com.atproto.space.applyWrites#update",
3373
+ collection: POST,
3374
+ rkey,
3375
+ value: note(text)
3376
+ }]
3377
+ });
3378
+ try {
3379
+ await mustCreateRecord(ctx, space.uri, "present");
3380
+ const ok = await update("present", "updated");
3381
+ if (ok.status !== 200) return fail(`positive control failed: updating an existing record answered ${describe(ok)}`, ok.json);
3382
+ const read = await operatorGetRecord(ctx, space.uri, "present");
3383
+ const text = read.json?.value?.text;
3384
+ if (text !== "updated") return fail(`the update of an existing record answered 200 but the record reads ${JSON.stringify(text)}`, read.json);
3385
+ const res = await update("absent", "nope");
3386
+ return res.error === "RecordNotFound" ? pass("an existing record updated; an absent one refused with RecordNotFound") : fail(`answered ${describe(res)}, expected RecordNotFound`, res.json);
3387
+ } finally {
3388
+ await deleteProbeSpace(ctx, space.uri);
3389
+ }
3390
+ }
3391
+ });
3392
+ /** The creating writes, each aimed at `space` (deleteRecord has its own check). */
3393
+ function writeProbes(ctx, space) {
3394
+ const repo = ctx.target.did;
3395
+ return [
3396
+ ["createRecord", () => xrpcPost(op(ctx), "com.atproto.space.createRecord", {
3397
+ space,
3398
+ repo,
3399
+ collection: POST,
3400
+ rkey: "w",
3401
+ record: note("w")
3402
+ })],
3403
+ ["putRecord", () => xrpcPost(op(ctx), "com.atproto.space.putRecord", {
3404
+ space,
3405
+ repo,
3406
+ collection: POST,
3407
+ rkey: "w",
3408
+ record: note("w")
3409
+ })],
3410
+ ["applyWrites", () => xrpcPost(op(ctx), "com.atproto.space.applyWrites", {
3411
+ space,
3412
+ repo,
3413
+ writes: [create("w", "w")]
3414
+ })]
3415
+ ];
3416
+ }
3417
+ async function expectNotFound(probes, label) {
3418
+ const misses = [];
3419
+ for (const [name, call] of probes) {
3420
+ const res = await call();
3421
+ if (res.error !== "SpaceNotFound") misses.push(`${label} ${name} → ${describe(res)}`);
3422
+ }
3423
+ return misses;
3424
+ }
3425
+ const writesSpaceNotFound = defineCheck({
3426
+ id: "writes.space-not-found",
3427
+ title: "The authority's writes to a missing or deleted space answer SpaceNotFound",
3428
+ tier: "must",
3429
+ citations: [
3430
+ L$1("com.atproto.space.createRecord@error:SpaceNotFound"),
3431
+ L$1("com.atproto.space.putRecord@error:SpaceNotFound"),
3432
+ L$1("com.atproto.space.applyWrites@error:SpaceNotFound"),
3433
+ P$1("0016#repo-lifecycle"),
3434
+ C$1("brave-spaces-exist")
3435
+ ],
3436
+ needs: ["operator"],
3437
+ destructive: true,
3438
+ async run(ctx) {
3439
+ const deleted = await createProbeSpace(ctx, personalspace());
3440
+ await mustCreateRecord(ctx, deleted.uri, "before");
3441
+ await deleteProbeSpace(ctx, deleted.uri);
3442
+ const misses = [...await expectNotFound(writeProbes(ctx, unknownSpaceUri(ctx.target.did)), "unknown:"), ...await expectNotFound(writeProbes(ctx, deleted.uri), "deleted:")];
3443
+ return misses.length ? fail(`expected SpaceNotFound: ${misses.join("; ")}`) : pass("create, put and applyWrites answered SpaceNotFound for a missing and a deleted space");
3444
+ }
3445
+ });
3446
+ const writesDeleteSpaceNotFound = defineCheck({
3447
+ id: "writes.delete-in-missing-space",
3448
+ title: "The authority's deleteRecord in a missing or deleted space answers SpaceNotFound",
3449
+ tier: "must",
3450
+ citations: [
3451
+ L$1("com.atproto.space.deleteRecord@error:SpaceNotFound"),
3452
+ P$1("0016#repo-lifecycle"),
3453
+ C$1("brave-spaces-exist")
3454
+ ],
3455
+ needs: ["operator"],
3456
+ destructive: true,
3457
+ async run(ctx) {
3458
+ const deleted = await createProbeSpace(ctx, personalspace());
3459
+ await mustCreateRecord(ctx, deleted.uri, "w");
3460
+ await deleteProbeSpace(ctx, deleted.uri);
3461
+ const misses = [];
3462
+ for (const [label, space] of [["unknown", unknownSpaceUri(ctx.target.did)], ["deleted", deleted.uri]]) {
3463
+ const res = await xrpcPost(op(ctx), "com.atproto.space.deleteRecord", {
3464
+ space,
3465
+ repo: ctx.target.did,
3466
+ collection: POST,
3467
+ rkey: "w"
3468
+ });
3469
+ if (res.error !== "SpaceNotFound") misses.push(`${label} → ${describe(res)}`);
3470
+ }
3471
+ return misses.length ? fail(`expected SpaceNotFound: ${misses.join("; ")}`) : pass("answered SpaceNotFound for a missing and a deleted space");
3472
+ }
3473
+ });
3474
+ const writesPublishedRefused = defineCheck({
3475
+ id: "writes.published-collections-refused",
3476
+ title: "Direct writes to the policy and member collections are refused",
3477
+ tier: "should",
3478
+ citations: [
3479
+ P$1("0016#publishing-to-readers"),
3480
+ C$1("baseline-space-policies"),
3481
+ L$1("com.atproto.space.policy"),
3482
+ L$1("com.atproto.memberspace.member")
3483
+ ],
3484
+ needs: ["operator"],
3485
+ destructive: true,
3486
+ async run(ctx) {
3487
+ const space = await createProbeSpace(ctx, memberspace());
3488
+ try {
3489
+ const attempts = [[
3490
+ "com.atproto.space.policy",
3491
+ "self",
3492
+ {
3493
+ $type: "com.atproto.space.policy",
3494
+ policy: memberspace({ publicRead: true })
3495
+ }
3496
+ ], [
3497
+ "com.atproto.memberspace.member",
3498
+ "did:plc:aaaaaaaaaaaaaaaaaaaaaaaa",
3499
+ {
3500
+ $type: "com.atproto.memberspace.member",
3501
+ read: true,
3502
+ write: true
3503
+ }
3504
+ ]];
3505
+ const accepted = [];
3506
+ const misanswered = [];
3507
+ for (const [collection, rkey, record] of attempts) for (const nsid of ["createRecord", "putRecord"]) {
3508
+ const res = await xrpcPost(op(ctx), `com.atproto.space.${nsid}`, {
3509
+ space: space.uri,
3510
+ repo: ctx.target.did,
3511
+ collection,
3512
+ rkey,
3513
+ record
3514
+ });
3515
+ if (res.status === 200) accepted.push(`${nsid} ${collection}`);
3516
+ else if (res.status < 400 || res.status >= 500) misanswered.push(`${nsid} ${collection} → ${describe(res)}`);
3517
+ }
3518
+ if (accepted.length) return fail(`accepted: ${accepted.join(", ")}`);
3519
+ return misanswered.length ? fail(`expected a 4xx refusal: ${misanswered.join(", ")}`) : pass("createRecord and putRecord refused both published collections with a 4xx");
3520
+ } finally {
3521
+ await deleteProbeSpace(ctx, space.uri);
3522
+ }
3523
+ }
3524
+ });
3525
+ /** sha256 of an all-zero LtHash state: the commit data of an empty repo. */
3526
+ const emptyRepoData = () => sha256(new Uint8Array(2048));
3527
+ async function latestCommit(ctx, space) {
3528
+ const res = await xrpcGet(op(ctx), "com.atproto.space.getLatestCommit", {
3529
+ space,
3530
+ repo: ctx.target.did
3531
+ });
3532
+ const commit = res.json?.commit;
3533
+ return {
3534
+ res,
3535
+ rev: commit?.rev,
3536
+ data: lexBytes(commit?.data)
3537
+ };
3538
+ }
3539
+ async function listRecords(ctx, space, extra = {}) {
3540
+ const res = await xrpcGet(op(ctx), "com.atproto.space.listRecords", {
3541
+ space,
3542
+ repo: ctx.target.did,
3543
+ ...extra
3544
+ });
3545
+ return {
3546
+ res,
3547
+ records: res.json?.records ?? []
3548
+ };
3549
+ }
3550
+ const writesClearRecords = defineCheck({
3551
+ id: "writes.clearrecords",
3552
+ title: "clearRecords empties the repo at a new rev with the empty-repo digest",
3553
+ tier: "must",
3554
+ citations: [
3555
+ L$1("com.atproto.space.clearRecords"),
3556
+ L$1("com.atproto.space.listRecords"),
3557
+ P$1("0016#repo-lifecycle"),
3558
+ C$1("clear-spaces-sweep")
3559
+ ],
3560
+ needs: ["operator"],
3561
+ destructive: true,
3562
+ async run(ctx) {
3563
+ const space = await createProbeSpace(ctx);
3564
+ const clear = () => xrpcPost(op(ctx), "com.atproto.space.clearRecords", {
3565
+ space: space.uri,
3566
+ repo: ctx.target.did
3567
+ });
3568
+ try {
3569
+ await mustCreateRecord(ctx, space.uri, "a");
3570
+ await mustCreateRecord(ctx, space.uri, "b");
3571
+ const before = await latestCommit(ctx, space.uri);
3572
+ const cleared = await clear();
3573
+ if (cleared.status !== 200) return fail(`clearRecords ${describe(cleared)}`, cleared.json);
3574
+ const { records } = await listRecords(ctx, space.uri);
3575
+ if (records.length) return fail(`${records.length} record(s) survived clearRecords`, records);
3576
+ const after = await latestCommit(ctx, space.uri);
3577
+ if (!after.rev || !before.rev || after.rev <= before.rev) return fail(`rev did not advance (${before.rev} → ${after.rev})`, after.res.json);
3578
+ if (!after.data || !bytesEqual(after.data, await emptyRepoData())) return fail("commit data after clearRecords is not the empty repo's digest", after.res.json);
3579
+ const again = await clear();
3580
+ 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);
3581
+ } finally {
3582
+ await deleteProbeSpace(ctx, space.uri);
3583
+ }
3584
+ }
3585
+ });
3586
+ const writesClearKeepsPublished = defineCheck({
3587
+ id: "writes.clearrecords-keeps-published",
3588
+ title: "clearRecords in the authority's repo keeps the published policy record",
3589
+ tier: "must",
3590
+ citations: [L$1("com.atproto.space.clearRecords"), P$1("0016#publishing-to-readers")],
3591
+ needs: ["operator"],
3592
+ destructive: true,
3593
+ async run(ctx) {
3594
+ const space = await createProbeSpace(ctx, memberspace({ publishPolicy: true }));
3595
+ try {
3596
+ await mustCreateRecord(ctx, space.uri, "mine");
3597
+ const cleared = await xrpcPost(op(ctx), "com.atproto.space.clearRecords", {
3598
+ space: space.uri,
3599
+ repo: ctx.target.did
3600
+ });
3601
+ if (cleared.status !== 200) return fail(`clearRecords ${describe(cleared)}`, cleared.json);
3602
+ if ((await operatorGetRecord(ctx, space.uri, "mine")).status === 200) return fail("the operator's own record survived clearRecords");
3603
+ const policy = await operatorGetRecord(ctx, space.uri, "self", "com.atproto.space.policy");
3604
+ 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);
3605
+ } finally {
3606
+ await deleteProbeSpace(ctx, space.uri);
3607
+ }
3608
+ }
3609
+ });
3610
+ const syncListRecords = defineCheck({
3611
+ id: "sync.listrecords-lists",
3612
+ title: "listRecords lists records with values, and excludeValues omits them",
3613
+ tier: "must",
3614
+ citations: [L$1("com.atproto.space.listRecords"), P$1("0016#xrpc-api")],
3615
+ needs: ["operator"],
3616
+ destructive: true,
3617
+ async run(ctx) {
3618
+ const space = await createProbeSpace(ctx);
3619
+ try {
3620
+ const a = await mustCreateRecord(ctx, space.uri, "aaa", "first");
3621
+ await mustCreateRecord(ctx, space.uri, "bbb", "second");
3622
+ const full = await listRecords(ctx, space.uri, { collection: POST });
3623
+ if (full.res.status !== 200) return fail(`listRecords ${describe(full.res)}`, full.res.json);
3624
+ const entry = full.records.find((r) => r.rkey === "aaa");
3625
+ if (full.records.length !== 2 || !entry) return fail(`listed ${full.records.length} record(s)`, full.records);
3626
+ if (entry.collection !== POST || entry.cid !== a.cid || entry.value?.text !== "first") return fail("listed entry does not match the written record", entry);
3627
+ const bare = await listRecords(ctx, space.uri, {
3628
+ collection: POST,
3629
+ excludeValues: "true"
3630
+ });
3631
+ if (bare.records.length !== 2) return fail(`excludeValues listed ${bare.records.length} record(s)`, bare.records);
3632
+ 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");
3633
+ } finally {
3634
+ await deleteProbeSpace(ctx, space.uri);
3635
+ }
3636
+ }
3637
+ });
3638
+ const syncListRecordsDescending = defineCheck({
3639
+ id: "sync.listrecords-descending-default",
3640
+ title: "listRecords defaults to descending record order",
3641
+ tier: "should",
3642
+ citations: [{
3643
+ source: "reference",
3644
+ ref: "listRecords default order (descending)"
3645
+ }, L$1("com.atproto.space.listRecords")],
3646
+ needs: ["operator"],
3647
+ destructive: true,
3648
+ async run(ctx) {
3649
+ const space = await createProbeSpace(ctx);
3650
+ try {
3651
+ for (const rkey of [
3652
+ "aaa",
3653
+ "bbb",
3654
+ "ccc"
3655
+ ]) await mustCreateRecord(ctx, space.uri, rkey);
3656
+ const { res, records } = await listRecords(ctx, space.uri, { collection: POST });
3657
+ if (res.status !== 200) return fail(`listRecords ${describe(res)}`);
3658
+ const rkeys = records.map((r) => r.rkey);
3659
+ return rkeys.join(",") === "ccc,bbb,aaa" ? pass("records returned descending by default") : fail(`order was ${rkeys.join(",")}, reference is descending`);
3660
+ } finally {
3661
+ await deleteProbeSpace(ctx, space.uri);
3662
+ }
3663
+ }
3664
+ });
3665
+ const garbageCursor = defineCheck({
3666
+ id: "request.garbage-cursor-rejected",
3667
+ title: "A cursor the host never issued answers InvalidCursor",
3668
+ tier: "should",
3669
+ citations: [{
3670
+ source: "reference",
3671
+ ref: "pds space readers validate cursor syntax"
3672
+ }, L$1("com.atproto.space.listRecords@error:InvalidCursor")],
3673
+ needs: ["operator"],
3674
+ destructive: true,
3675
+ async run(ctx) {
3676
+ const space = await createProbeSpace(ctx, memberspace());
3677
+ try {
3678
+ await mustCreateRecord(ctx, space.uri, "a");
3679
+ const cursor = "!!not-a-cursor!!";
3680
+ const base = {
3681
+ space: space.uri,
3682
+ repo: ctx.target.did,
3683
+ cursor
3684
+ };
3685
+ const misses = [];
3686
+ for (const [name, params] of [
3687
+ ["com.atproto.space.listRecords", base],
3688
+ ["com.atproto.space.listRepoOps", base],
3689
+ ["com.atproto.space.listSpaces", {
3690
+ cursor,
3691
+ spaceType: PROBE_TYPE,
3692
+ spaceDid: ctx.target.did
3693
+ }],
3694
+ ["com.atproto.memberspace.listMembers", {
3695
+ space: space.uri,
3696
+ cursor
3697
+ }]
3698
+ ]) {
3699
+ const res = await xrpcGet(op(ctx), name, params);
3700
+ if (res.error !== "InvalidCursor") misses.push(`${name.split(".").at(-1)} → ${describe(res)}`);
3701
+ }
3702
+ return misses.length ? fail(misses.join("; ")) : pass("all four answered InvalidCursor");
3703
+ } finally {
3704
+ await deleteProbeSpace(ctx, space.uri);
3705
+ }
3706
+ }
3707
+ });
3708
+ async function uploadBlob(ctx, bytes) {
3709
+ const upload = await operatorFetch(ctx)(`${ctx.target.origin}/xrpc/com.atproto.repo.uploadBlob`, {
3710
+ method: "POST",
3711
+ headers: { "Content-Type": "application/octet-stream" },
3712
+ body: bytes
3713
+ });
3714
+ if (upload.status !== 200) throw new Error(`uploadBlob ${upload.status}`);
3715
+ return (await upload.json()).blob;
3716
+ }
3717
+ /** Blob isolation: a space blob is never public. */
3718
+ const blobsSpaceNotPublic = defineCheck({
3719
+ id: "blobs.space-blob-not-public",
3720
+ title: "A blob is not publicly served unless a public record references it",
3721
+ tier: "must",
3722
+ citations: [L$1("com.atproto.space.getBlob"), {
3723
+ source: "proposal",
3724
+ ref: "0016#blob-sync"
3725
+ }],
3726
+ needs: ["operator", "pds-blobs"],
3727
+ destructive: true,
3728
+ async run(ctx) {
3729
+ const blobUrl = (cid) => `${ctx.target.origin}/xrpc/com.atproto.sync.getBlob?did=${encodeURIComponent(ctx.target.did)}&cid=${cid}`;
3730
+ const publicBytes = crypto.getRandomValues(new Uint8Array(16));
3731
+ const publicBlob = await uploadBlob(ctx, publicBytes);
3732
+ const publicRkey = probeSkey();
3733
+ const publicWrite = await xrpcPost(op(ctx), "com.atproto.repo.createRecord", {
3734
+ repo: ctx.target.did,
3735
+ collection: "earth.cirrus.check.withblob",
3736
+ rkey: publicRkey,
3737
+ record: {
3738
+ $type: "earth.cirrus.check.withblob",
3739
+ file: publicBlob
3740
+ }
3741
+ });
3742
+ const space = await createProbeSpace(ctx);
3743
+ try {
3744
+ if (publicWrite.status !== 200) return fail(`public referencing write (repo.createRecord) ${describe(publicWrite)}`, publicWrite.json);
3745
+ const served = await ctx.fetch(blobUrl(publicBlob.ref.$link));
3746
+ if (served.status !== 200) return fail(`positive control failed: a blob a public record references was not served by sync.getBlob (${served.status})`);
3747
+ if (!bytesEqual(new Uint8Array(await served.arrayBuffer()), publicBytes)) return fail("sync.getBlob served a publicly referenced blob's bytes wrong");
3748
+ const blob = await uploadBlob(ctx, crypto.getRandomValues(new Uint8Array(16)));
3749
+ const publicUrl = blobUrl(blob.ref.$link);
3750
+ const stagedGet = await ctx.fetch(publicUrl);
3751
+ if (stagedGet.status === 200) return fail("an uploaded, unreferenced blob was served by the public sync.getBlob");
3752
+ const write = await operatorCreateRecord(ctx, space.uri, "earth.cirrus.check.withblob", "self", {
3753
+ $type: "earth.cirrus.check.withblob",
3754
+ file: blob
3755
+ });
3756
+ if (write.status !== 200) return fail(`referencing write ${describe(write)}`, write.json);
3757
+ const publicGet = await ctx.fetch(publicUrl);
3758
+ return publicGet.status === 200 ? fail("a space blob was served by the public sync.getBlob") : pass(`public sync.getBlob served a publicly referenced blob, and refused one unreferenced (${stagedGet.status}) and one space-referenced (${publicGet.status})`);
3759
+ } finally {
3760
+ await deleteProbeSpace(ctx, space.uri);
3761
+ if (publicWrite.status === 200) await xrpcPost(op(ctx), "com.atproto.repo.deleteRecord", {
3762
+ repo: ctx.target.did,
3763
+ collection: "earth.cirrus.check.withblob",
3764
+ rkey: publicRkey
3765
+ }).catch(() => {});
3766
+ }
3767
+ }
3768
+ });
3769
+ const blobsListAndGet = defineCheck({
3770
+ id: "blobs.listblobs-and-getblob",
3771
+ title: "listBlobs lists a space record's blob and space.getBlob serves it",
3772
+ tier: "must",
3773
+ citations: [L$1("com.atproto.space.listBlobs"), L$1("com.atproto.space.getBlob")],
3774
+ needs: ["operator", "pds-blobs"],
3775
+ destructive: true,
3776
+ async run(ctx) {
3777
+ const space = await createProbeSpace(ctx);
3778
+ try {
3779
+ const bytes = crypto.getRandomValues(new Uint8Array(24));
3780
+ const blob = await uploadBlob(ctx, bytes);
3781
+ const write = await operatorCreateRecord(ctx, space.uri, "earth.cirrus.check.withblob", "self", {
3782
+ $type: "earth.cirrus.check.withblob",
3783
+ file: blob
3784
+ });
3785
+ if (write.status !== 200) return fail(`referencing write ${describe(write)}`, write.json);
3786
+ const list = await xrpcGet(op(ctx), "com.atproto.space.listBlobs", {
3787
+ space: space.uri,
3788
+ repo: ctx.target.did
3789
+ });
3790
+ if (!(list.json?.cids ?? []).includes(blob.ref.$link)) return fail(`listBlobs ${describe(list)} did not list the blob`, list.json);
3791
+ 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}`);
3792
+ if (res.status !== 200) return fail(`space.getBlob ${res.status}`);
3793
+ return bytesEqual(new Uint8Array(await res.arrayBuffer()), bytes) ? pass("listed and served the exact bytes") : fail("space.getBlob served different bytes");
3794
+ } finally {
3795
+ await deleteProbeSpace(ctx, space.uri);
3796
+ }
3797
+ }
3798
+ });
3799
+ const blobsNotFound = defineCheck({
3800
+ id: "blobs.getblob-not-found",
3801
+ title: "space.getBlob of a blob the space does not reference answers BlobNotFound",
3802
+ tier: "must",
3803
+ citations: [L$1("com.atproto.space.getBlob@error:BlobNotFound")],
3804
+ needs: ["operator"],
3805
+ destructive: true,
3806
+ async run(ctx) {
3807
+ const space = await createProbeSpace(ctx);
3808
+ try {
3809
+ await mustCreateRecord(ctx, space.uri, "present");
3810
+ const res = await xrpcGet(op(ctx), "com.atproto.space.getBlob", {
3811
+ space: space.uri,
3812
+ repo: ctx.target.did,
3813
+ cid: await rawCid(crypto.getRandomValues(new Uint8Array(16)))
3814
+ });
3815
+ return res.error === "BlobNotFound" ? pass("answered BlobNotFound") : fail(`answered ${describe(res)}, expected BlobNotFound`, res.json);
3816
+ } finally {
3817
+ await deleteProbeSpace(ctx, space.uri);
3818
+ }
3819
+ }
3820
+ });
3821
+ const requestInvalidSpaceUri = defineCheck({
3822
+ id: "request.invalid-space-uri-rejected",
3823
+ title: "A malformed space reference is rejected as a bad request, not misread",
3824
+ tier: "must",
3825
+ citations: [L$1("com.atproto.space.getLatestCommit")],
3826
+ needs: ["operator"],
3827
+ async run(ctx) {
3828
+ const res = await xrpcGet(op(ctx), "com.atproto.space.getLatestCommit", {
3829
+ space: "not-a-space-uri",
3830
+ repo: ctx.target.did
3831
+ });
3832
+ return res.status === 400 && res.error === "InvalidRequest" ? pass(`rejected the authenticated request with ${describe(res)}`) : fail(`answered ${describe(res)} to an authenticated request with a malformed space uri, expected 400 InvalidRequest`, res.json);
3833
+ }
3834
+ });
3835
+ const getSpace = (ctx, space) => xrpcGet(op(ctx), "com.atproto.space.getSpace", { space });
3836
+ const requestLegacySpaceUri = defineCheck({
3837
+ id: "request.legacy-space-uri-rejected",
3838
+ title: "A space param in the retired at://{did}/space/… form is rejected; the at:space/ ref of the same space is served",
3839
+ tier: "must",
3840
+ citations: [
3841
+ L$1("com.atproto.space.getRecord"),
3842
+ L$1("com.atproto.space.createRecord"),
3843
+ L$1("com.atproto.space.getSpace"),
3844
+ P$1("0016#addressing"),
3845
+ C$1("pds-space-uri-migration"),
3846
+ C$1("alpha-space-uris")
3847
+ ],
3848
+ needs: ["operator"],
3849
+ destructive: true,
3850
+ async run(ctx) {
3851
+ const space = await createProbeSpace(ctx, personalspace());
3852
+ const ref = spaceUri(ctx.target.did, space.skey);
3853
+ const legacy = legacySpaceUri(ctx.target.did, space.skey);
3854
+ const invalid = (r) => r.status === 400 && errorIs("InvalidRequest")(r);
3855
+ const ok = (r) => r.status === 200;
3856
+ try {
3857
+ await mustCreateRecord(ctx, ref, "a");
3858
+ const { ok: passed, detail, evidence } = await expectEach([
3859
+ [
3860
+ "getRecord at:space/",
3861
+ () => operatorGetRecord(ctx, ref, "a"),
3862
+ ok
3863
+ ],
3864
+ [
3865
+ "getSpace at:space/",
3866
+ () => getSpace(ctx, ref),
3867
+ ok
3868
+ ],
3869
+ [
3870
+ "createRecord at:space/",
3871
+ () => operatorCreateRecord(ctx, ref, POST, "b", note("b")),
3872
+ ok
3873
+ ],
3874
+ [
3875
+ "getRecord at://",
3876
+ () => operatorGetRecord(ctx, legacy, "a"),
3877
+ invalid
3878
+ ],
3879
+ [
3880
+ "getSpace at://",
3881
+ () => getSpace(ctx, legacy),
3882
+ invalid
3883
+ ],
3884
+ [
3885
+ "createRecord at://",
3886
+ () => operatorCreateRecord(ctx, legacy, POST, "c", note("c")),
3887
+ invalid
3888
+ ]
3889
+ ]);
3890
+ return passed ? pass("the at:space/ ref was served; the at:// form was rejected 400 InvalidRequest by getRecord, getSpace and createRecord", evidence) : fail(`expected 200 for at:space/, 400 InvalidRequest for at://: ${detail}`, evidence);
3891
+ } finally {
3892
+ await deleteProbeSpace(ctx, space.uri);
3893
+ }
3894
+ }
3895
+ });
3896
+ const requestHandleAuthority = defineCheck({
3897
+ id: "request.handle-space-authority-rejected",
3898
+ title: "A space ref naming its authority by handle is rejected; the DID ref of the same space is served",
3899
+ tier: "must",
3900
+ citations: [
3901
+ L$1("com.atproto.space.getSpace"),
3902
+ L$1("com.atproto.space.getRecord"),
3903
+ P$1("0016#addressing"),
3904
+ C$1("spaces-syntax")
3905
+ ],
3906
+ needs: ["operator"],
3907
+ destructive: true,
3908
+ async run(ctx) {
3909
+ const authority = await resolveDidDocument(ctx, ctx.target.did).then((doc) => doc.alsoKnownAs?.find((aka) => aka.startsWith("at://"))?.slice(5)).catch(() => void 0) || "space-conformance.invalid";
3910
+ const space = await createProbeSpace(ctx, personalspace());
3911
+ const ref = spaceUri(ctx.target.did, space.skey);
3912
+ const byHandle = spaceUri(authority, space.skey);
3913
+ const invalid = (r) => r.status === 400 && errorIs("InvalidRequest")(r);
3914
+ const ok = (r) => r.status === 200;
3915
+ try {
3916
+ await mustCreateRecord(ctx, ref, "a");
3917
+ const { ok: passed, detail, evidence } = await expectEach([
3918
+ [
3919
+ "getSpace by DID",
3920
+ () => getSpace(ctx, ref),
3921
+ ok
3922
+ ],
3923
+ [
3924
+ "getRecord by DID",
3925
+ () => operatorGetRecord(ctx, ref, "a"),
3926
+ ok
3927
+ ],
3928
+ [
3929
+ "getSpace by handle",
3930
+ () => getSpace(ctx, byHandle),
3931
+ invalid
3932
+ ],
3933
+ [
3934
+ "getRecord by handle",
3935
+ () => operatorGetRecord(ctx, byHandle, "a"),
3936
+ invalid
3937
+ ]
3938
+ ]);
3939
+ return passed ? pass(`the DID ref was served; ${byHandle} was rejected 400 InvalidRequest`, evidence) : fail(`expected 200 by DID, 400 InvalidRequest by handle (${authority}): ${detail}`, evidence);
3940
+ } finally {
3941
+ await deleteProbeSpace(ctx, space.uri);
3942
+ }
3943
+ }
3944
+ });
3945
+ const recordChecks = [
3946
+ writesCreateRead,
3947
+ writesUnauthReadRefused,
3948
+ writesDuplicate,
3949
+ writesPutRecord,
3950
+ writesGetRecordMissing,
3951
+ writesDeleteIdempotent,
3952
+ writesApplyWritesAtomic,
3953
+ writesApplyWritesMissing,
3954
+ writesSpaceNotFound,
3955
+ writesDeleteSpaceNotFound,
3956
+ writesPublishedRefused,
3957
+ writesClearRecords,
3958
+ writesClearKeepsPublished,
3959
+ syncListRecords,
3960
+ syncListRecordsDescending,
3961
+ garbageCursor,
3962
+ requestInvalidSpaceUri,
3963
+ requestLegacySpaceUri,
3964
+ requestHandleAuthority,
3965
+ blobsSpaceNotPublic,
3966
+ blobsListAndGet,
3967
+ blobsNotFound
3968
+ ];
3969
+
3970
+ //#endregion
3971
+ //#region src/checks/operator.ts
3972
+ /**
3973
+ * The operator catalog: runnable anywhere the harness has an operator
3974
+ * session — browser included.
3975
+ */
3976
+ const operatorChecks = [
3977
+ ...recordChecks,
3978
+ ...spaceChecks,
3979
+ ...credentialChecks,
3980
+ ...hostChecks
3981
+ ];
3982
+
3983
+ //#endregion
3984
+ //#region src/inbox.ts
3985
+ const json = (status, body) => new Response(JSON.stringify(body), {
3986
+ status,
3987
+ headers: { "Content-Type": "application/json" }
3988
+ });
3989
+ function createSyncerInbox(opts) {
3990
+ const deliveries = [];
3991
+ const waiters = /* @__PURE__ */ new Set();
3992
+ const responders = /* @__PURE__ */ new Map();
3993
+ const tokens = /* @__PURE__ */ new Map();
3994
+ const base = new URL(opts.endpoint);
3995
+ const metadataPath = `${base.pathname.replace(/\/$/, "")}/client-metadata.json`;
3996
+ const clientId = `${base.origin}${metadataPath}`;
3997
+ const kid = "space-conformance-1";
3998
+ const keyPair = crypto.subtle.generateKey({
3999
+ name: "ECDSA",
4000
+ namedCurve: "P-256"
4001
+ }, true, ["sign", "verify"]);
4002
+ async function clientMetadata() {
4003
+ const { kty, crv, x, y } = await crypto.subtle.exportKey("jwk", (await keyPair).publicKey);
4004
+ return {
4005
+ client_id: clientId,
4006
+ client_name: "space-conformance",
4007
+ application_type: "web",
4008
+ grant_types: ["authorization_code"],
4009
+ response_types: ["code"],
4010
+ redirect_uris: ["http://127.0.0.1/callback"],
4011
+ scope: "atproto",
4012
+ dpop_bound_access_tokens: true,
4013
+ token_endpoint_auth_method: "private_key_jwt",
4014
+ token_endpoint_auth_signing_alg: "ES256",
4015
+ jwks: { keys: [{
4016
+ kty,
4017
+ crv,
4018
+ x,
4019
+ y,
4020
+ kid,
4021
+ alg: "ES256",
4022
+ use: "sig"
4023
+ }] }
4024
+ };
4025
+ }
4026
+ const known = (body) => {
4027
+ const b = body;
4028
+ return typeof b?.token === "string" && typeof b.space === "string" && tokens.get(b.token) === b.space;
4029
+ };
4030
+ async function handle(request) {
4031
+ const url = new URL(request.url);
4032
+ if (request.method === "GET" && url.pathname === metadataPath) return json(200, await clientMetadata());
4033
+ const lxm = url.pathname.replace(/^\/xrpc\//, "");
4034
+ const raw = request.method === "POST" ? await request.text() : "";
4035
+ let body;
4036
+ try {
4037
+ body = raw ? JSON.parse(raw) : void 0;
4038
+ } catch {
4039
+ body = raw;
4040
+ }
4041
+ let response;
4042
+ if (lxm === "com.atproto.space.confirmRegistration") response = known(body) ? json(200, { challenge: body.challenge }) : json(400, {
4043
+ error: "InvalidToken",
4044
+ message: "unknown token"
4045
+ });
4046
+ else if (lxm === "com.atproto.space.notifySpaceUpdate") response = known(body) ? json(200, {}) : json(400, {
4047
+ error: "InvalidToken",
4048
+ message: "unknown token"
4049
+ });
4050
+ else {
4051
+ const responder = responders.get(lxm);
4052
+ response = responder ? json(200, responder({
4053
+ lxm,
4054
+ body,
4055
+ params: Object.fromEntries(url.searchParams),
4056
+ status: 200,
4057
+ receivedAt: Date.now()
4058
+ })) : json(501, { error: "MethodNotImplemented" });
4059
+ }
4060
+ const authorization = request.headers.get("authorization");
4061
+ deliveries.push({
4062
+ lxm,
4063
+ body,
4064
+ params: Object.fromEntries(url.searchParams),
4065
+ ...authorization ? { authorization } : {},
4066
+ status: response.status,
4067
+ receivedAt: Date.now()
4068
+ });
4069
+ for (const wake of waiters) wake();
4070
+ return response;
4071
+ }
4072
+ return {
4073
+ inbox: {
4074
+ endpoint: opts.endpoint,
4075
+ service: opts.service,
4076
+ issueToken(space) {
4077
+ const token = toBase64Url(crypto.getRandomValues(new Uint8Array(32)));
4078
+ tokens.set(token, space);
4079
+ return token;
4080
+ },
4081
+ async waitFor(predicate, timeoutMs) {
4082
+ const deadline = Date.now() + timeoutMs;
4083
+ for (;;) {
4084
+ const found = deliveries.find(predicate);
4085
+ if (found) return found;
4086
+ const remaining = deadline - Date.now();
4087
+ if (remaining <= 0) return null;
4088
+ await new Promise((resolve) => {
4089
+ const done = () => {
4090
+ clearTimeout(timer);
4091
+ waiters.delete(done);
4092
+ resolve();
4093
+ };
4094
+ const timer = setTimeout(done, remaining);
4095
+ waiters.add(done);
4096
+ });
4097
+ }
4098
+ },
4099
+ respond(lxm, handler) {
4100
+ if (handler) responders.set(lxm, handler);
4101
+ else responders.delete(lxm);
4102
+ },
4103
+ clientId,
4104
+ async attest(aud) {
4105
+ const { privateKey } = await keyPair;
4106
+ return signClientAttestation({
4107
+ clientId,
4108
+ aud,
4109
+ kid,
4110
+ sign: async (bytes) => new Uint8Array(await crypto.subtle.sign({
4111
+ name: "ECDSA",
4112
+ hash: "SHA-256"
4113
+ }, privateKey, bytes))
4114
+ });
4115
+ }
4116
+ },
4117
+ handle,
4118
+ deliveries: () => deliveries
4119
+ };
4120
+ }
4121
+
4122
+ //#endregion
4123
+ //#region src/descriptors.ts
4124
+ const L = (ref) => ({
4125
+ source: "lexicon",
4126
+ ref
4127
+ });
4128
+ const C = (ref) => ({
4129
+ source: "changeset",
4130
+ ref
4131
+ });
4132
+ const P = (ref) => ({
4133
+ source: "proposal",
4134
+ ref
4135
+ });
4136
+ /** Refusals a policy may give an account it does not authorise. */
4137
+ const ACCOUNT_REFUSALS = [
4138
+ L("com.atproto.space.authorizeSpaceSync@error:SpaceNotFound"),
4139
+ L("com.atproto.space.authorizeSpaceSync@error:AccountNotAuthorized"),
4140
+ L("com.atproto.space.authorizeSpaceSync@error:NotAuthorized")
4141
+ ];
4142
+ /** Every crypto-bound check, by metadata, in catalog order. */
4143
+ const cryptoCheckDescriptors = [
4144
+ {
4145
+ id: "mac.commit-verifies",
4146
+ title: "getLatestCommit's commit MAC verifies, under the requested label, with Vary: Accept-Signature, naming the at:space/ ref",
4147
+ tier: "must",
4148
+ needs: ["operator"],
4149
+ citations: [
4150
+ L("com.atproto.space.getLatestCommit"),
4151
+ L("com.atproto.space.defs#commit"),
4152
+ P("0016#requesting-a-mac"),
4153
+ P("0016#commit-mac"),
4154
+ C("pds-space-uri-migration")
4155
+ ],
4156
+ destructive: true
4157
+ },
4158
+ {
4159
+ id: "mac.record-verifies",
4160
+ title: "getRecord's record MAC verifies over its at:space/ uri, and its value encodes to its cid",
4161
+ tier: "must",
4162
+ needs: ["operator"],
4163
+ citations: [
4164
+ L("com.atproto.space.getRecord"),
4165
+ P("0016#record-mac"),
4166
+ C("spaces-syntax")
4167
+ ],
4168
+ destructive: true
4169
+ },
4170
+ {
4171
+ id: "sync.oplog-folds-to-commit",
4172
+ title: "Every listRepoOps page carries a MAC-verified commit, and the ops fold to its data",
4173
+ tier: "must",
4174
+ needs: ["operator"],
4175
+ citations: [
4176
+ L("com.atproto.space.listRepoOps"),
4177
+ L("com.atproto.space.defs#commit"),
4178
+ P("0016#incremental-sync")
4179
+ ],
4180
+ destructive: true
4181
+ },
4182
+ {
4183
+ id: "sync.getrepo-star",
4184
+ title: "getRepo serves a STAR archive (application/vnd.dasl.star) that verifies against its MAC",
4185
+ tier: "must",
4186
+ needs: ["operator"],
4187
+ citations: [L("com.atproto.space.getRepo"), P("0016#repo-serialization")],
4188
+ destructive: true
4189
+ },
4190
+ {
4191
+ id: "credential.signed-by-authority",
4192
+ title: "A credential verifies against the authority's #atproto key",
4193
+ tier: "must",
4194
+ needs: ["operator"],
4195
+ citations: [L("com.atproto.space.authorizeSpaceSync"), P("0016#space-credential")],
4196
+ destructive: true
4197
+ },
4198
+ {
4199
+ id: "delegation.signed-by-user",
4200
+ title: "A delegation token verifies against the user's #atproto key",
4201
+ tier: "must",
4202
+ needs: ["operator", "pds-delegation"],
4203
+ citations: [L("com.atproto.space.getDelegationToken"), P("0016#delegation-token")],
4204
+ destructive: true
4205
+ },
4206
+ {
4207
+ id: "migration.export-space-meta",
4208
+ title: "exportSpaceMeta serves the policy, members and live writers (with repoRev) as a STAR file",
4209
+ tier: "must",
4210
+ needs: ["operator"],
4211
+ citations: [
4212
+ L("com.atproto.space.exportSpaceMeta"),
4213
+ P("0016#space-meta-archive"),
4214
+ C("removed-writers-notify")
4215
+ ],
4216
+ destructive: true
4217
+ },
4218
+ {
4219
+ id: "migration.import-space-meta",
4220
+ title: "importSpaceMeta replaces the space's policy and member list",
4221
+ tier: "must",
4222
+ needs: ["operator"],
4223
+ citations: [L("com.atproto.space.importSpaceMeta"), P("0016#space-meta-archive")],
4224
+ destructive: true
4225
+ },
4226
+ {
4227
+ id: "migration.import-space-meta-not-authority",
4228
+ title: "importSpaceMeta of another DID's space answers NotAuthorized",
4229
+ tier: "must",
4230
+ needs: ["operator"],
4231
+ citations: [L("com.atproto.space.importSpaceMeta@error:NotAuthorized")]
4232
+ },
4233
+ {
4234
+ id: "migration.import-space-meta-unsupported-policy",
4235
+ title: "importSpaceMeta of an unimplemented policy answers UnsupportedPolicy",
4236
+ tier: "must",
4237
+ needs: ["operator"],
4238
+ citations: [L("com.atproto.space.importSpaceMeta@error:UnsupportedPolicy"), P("0016#space-meta-archive")],
4239
+ destructive: true
4240
+ },
4241
+ {
4242
+ id: "migration.import-space-meta-invalid",
4243
+ title: "importSpaceMeta of a malformed archive answers InvalidSpaceMeta",
4244
+ tier: "must",
4245
+ needs: ["operator"],
4246
+ citations: [L("com.atproto.space.importSpaceMeta@error:InvalidSpaceMeta"), P("0016#space-meta-archive")]
4247
+ },
4248
+ {
4249
+ id: "migration.import-repo",
4250
+ title: "importRepo of a getRepo archive keeps the records and data at a new rev",
4251
+ tier: "must",
4252
+ needs: ["operator"],
4253
+ citations: [
4254
+ L("com.atproto.space.importRepo"),
4255
+ L("com.atproto.space.getRepo"),
4256
+ P("0016#account-migration")
4257
+ ],
4258
+ destructive: true
4259
+ },
4260
+ {
4261
+ id: "migration.import-repo-space-not-found",
4262
+ title: "importRepo into an own space that was never imported answers SpaceNotFound",
4263
+ tier: "must",
4264
+ needs: ["operator"],
4265
+ citations: [L("com.atproto.space.importRepo@error:SpaceNotFound")]
4266
+ },
4267
+ {
4268
+ id: "migration.import-repo-invalid",
4269
+ title: "importRepo of a malformed archive answers InvalidRepoFile",
4270
+ tier: "must",
4271
+ needs: ["operator"],
4272
+ citations: [L("com.atproto.space.importRepo@error:InvalidRepoFile")]
4273
+ },
4274
+ {
4275
+ id: "migration.import-repo-mismatch",
4276
+ title: "importRepo of another account's repo answers RepoMismatch",
4277
+ tier: "must",
4278
+ needs: ["operator"],
4279
+ citations: [L("com.atproto.space.importRepo@error:RepoMismatch")],
4280
+ destructive: true
4281
+ },
4282
+ {
4283
+ id: "credential.member-gate",
4284
+ title: "A memberspace refuses a non-member and a read:false member, and admits a reader",
4285
+ tier: "must",
4286
+ needs: ["operator", "identities"],
4287
+ citations: [
4288
+ ...ACCOUNT_REFUSALS,
4289
+ L("com.atproto.memberspace.putMembers"),
4290
+ L("com.atproto.memberspace.policy"),
4291
+ P("0016#memberspace")
4292
+ ],
4293
+ destructive: true
4294
+ },
4295
+ {
4296
+ id: "policy.personalspace-owner-only",
4297
+ title: "A personalspace refuses every account but its authority",
4298
+ tier: "must",
4299
+ needs: ["operator", "identities"],
4300
+ citations: [
4301
+ ...ACCOUNT_REFUSALS,
4302
+ L("com.atproto.personalspace.policy"),
4303
+ P("0016#personalspace")
4304
+ ],
4305
+ destructive: true
4306
+ },
4307
+ {
4308
+ id: "delegation.wrong-audience-refused",
4309
+ title: "A delegation token addressed to another host is refused",
4310
+ tier: "must",
4311
+ needs: ["operator", "identities"],
4312
+ citations: [L("com.atproto.space.authorizeSpaceSync@error:InvalidDelegationToken"), P("0016#delegation-token")],
4313
+ destructive: true
4314
+ },
4315
+ {
4316
+ id: "host.notifyrepoupdate-accepted",
4317
+ title: "An authorised writer's notifyRepoUpdate enters the writer set",
4318
+ tier: "must",
4319
+ needs: ["operator", "identities"],
4320
+ citations: [
4321
+ L("com.atproto.space.notifyRepoUpdate"),
4322
+ L("com.atproto.space.listWriters"),
4323
+ P("0016#write-notifications")
4324
+ ],
4325
+ destructive: true
4326
+ },
4327
+ {
4328
+ id: "host.notifyrepoupdate-future-rev",
4329
+ title: "notifyRepoUpdate with a repoRev beyond clock skew answers FutureRev",
4330
+ tier: "must",
4331
+ needs: ["operator", "identities"],
4332
+ citations: [L("com.atproto.space.notifyRepoUpdate@error:FutureRev"), P("0016#write-notifications")],
4333
+ destructive: true
4334
+ },
4335
+ {
4336
+ id: "host.notifyrepoupdate-unknown-space",
4337
+ title: "notifyRepoUpdate for a space the authority does not have answers SpaceNotFound",
4338
+ tier: "must",
4339
+ needs: ["operator", "identities"],
4340
+ citations: [L("com.atproto.space.notifyRepoUpdate@error:SpaceNotFound")]
4341
+ },
4342
+ {
4343
+ id: "memberspace.write-revocation-removes-writer",
4344
+ title: "Revoking a member's write access removes it from the writer set, and its writes stop being tracked",
4345
+ tier: "should",
4346
+ needs: ["operator", "identities"],
4347
+ citations: [P("0016#memberspace"), P("0016#write-notifications")],
4348
+ destructive: true
4349
+ },
4350
+ {
4351
+ id: "revocation.revoked-credential-refused",
4352
+ title: "A repo host accepts a foreign authority's credential until it is revoked",
4353
+ tier: "must",
4354
+ needs: ["operator", "identities"],
4355
+ citations: [
4356
+ L("com.atproto.space.notifyCredentialsRevoked"),
4357
+ L("com.atproto.space.getRecord"),
4358
+ P("0016#credential-expiration-and-revocation")
4359
+ ],
4360
+ destructive: true
4361
+ },
4362
+ {
4363
+ id: "revocation.error-name",
4364
+ title: "A revoked credential is refused with CredentialRevoked",
4365
+ tier: "should",
4366
+ needs: ["operator", "identities"],
4367
+ citations: [{
4368
+ source: "reference",
4369
+ ref: "pds auth-verifier spaceCredentialAuth"
4370
+ }],
4371
+ destructive: true
4372
+ },
4373
+ {
4374
+ id: "revocation.non-authority-refused",
4375
+ title: "notifyCredentialsRevoked from anyone but the space authority is refused",
4376
+ tier: "must",
4377
+ needs: ["operator", "identities"],
4378
+ citations: [L("com.atproto.space.notifyCredentialsRevoked"), P("0016#credential-expiration-and-revocation")],
4379
+ destructive: true
4380
+ },
4381
+ {
4382
+ id: "managedspace.check-access-account",
4383
+ title: "A managedspace asks its managing app about the delegated account",
4384
+ tier: "must",
4385
+ needs: [
4386
+ "operator",
4387
+ "identities",
4388
+ "syncer-inbox"
4389
+ ],
4390
+ citations: [
4391
+ L("com.atproto.managedspace.checkAccess"),
4392
+ L("com.atproto.managedspace.policy"),
4393
+ P("0016#managedspace")
4394
+ ],
4395
+ destructive: true
4396
+ }
4397
+ ];
4398
+ function descriptor(id) {
4399
+ const found = cryptoCheckDescriptors.find((d) => d.id === id);
4400
+ if (!found) throw new Error(`no crypto check descriptor ${id}`);
4401
+ return found;
4402
+ }
4403
+ /**
4404
+ * Turn a descriptor into a listable Check. Its run() is never invoked —
4405
+ * beyond the descriptor's own needs, the stub declares `alpha-libs` (the
4406
+ * ability to execute the alpha crypto code), which no browser harness
4407
+ * provides, so the runner always filters it into `skipped` — but it
4408
+ * throws if reached, so a mistaken run surfaces loudly rather than
4409
+ * passing.
4410
+ */
4411
+ function descriptorToStub(d) {
4412
+ return {
4413
+ id: d.id,
4414
+ title: d.title,
4415
+ tier: d.tier,
4416
+ needs: [...d.needs, "alpha-libs"],
4417
+ citations: d.citations,
4418
+ ...d.destructive ? { destructive: true } : {},
4419
+ ...d.slow ? { slow: true } : {},
4420
+ run: async () => {
4421
+ throw new Error(`${d.id} is a metadata stub and cannot run in this transport`);
4422
+ }
4423
+ };
4424
+ }
4425
+
4426
+ //#endregion
4427
+ export { toBase64 as $, spaceUri as A, SPACE_CREDENTIAL_SCHEME as B, operatorCreateRecord as C, requestCredential as D, publicRead as E, serviceEndpoint as F, isP256DidKey as G, credentialSigMembers as H, verificationMethodDidKey as I, decodeJwt as J, spaceSigHeaders as K, COMMIT_MAC_PROFILE as L, DEFAULT_PLC_DIRECTORY as M, didDocumentUrl as N, spaceAuthority as O, resolveDidDocument as P, tidNow as Q, MAC_COVERED_HEADER as R, obtainPublicCredential as S, probeSkey as T, encapsulate as U, createCredentialKey as V, formatMacRequest as W, lexBytes as X, isTid as Y, tidAt as Z, describe as _, operatorChecks as a, xrpcGet as at, mustCreateRecord as b, fakeDid as c, xrpcUrl as ct, FOREIGN_DID as d, filterCatalog as dt, toBase64Url as et, POST as f, fail as ft, deleteProbeSpace as g, credentialGet as h, createSyncerInbox as i, operatorHeaders as it, unknownSpaceUri as j, spaceRecordUri as k, putMembers as l, buildCatalog as lt, credentialCall as m, descriptor as n, asOperator as nt, listWriters as o, xrpcPost as ot, createProbeSpace as p, pass as pt, bytesEqual as q, descriptorToStub as r, operatorFetch as rt, ACCOUNT_REFUSALS$1 as s, xrpcPostBytes as st, cryptoCheckDescriptors as t, utf8 as tt, baseChecks as u, defineCheck as ut, managedspace as v, personalspace as w, obtainCredentialViaDelegation as x, memberspace as y, RECORD_MAC_PROFILE as z };
4428
+ //# sourceMappingURL=descriptors-YEk3XoDL.js.map