import assert from 'node:assert/strict'; import { spawnSync } from 'node:child_process'; import { pathToFileURL } from 'node:url'; const sdk = process.env.ZDS_SPACE_SDK_DIR; const { COMMIT_MAC_PROFILE, RECORD_MAC_PROFILE, createSpaceSigHeaders, encapsulate, formatMacRequest, readRepoStar, readSpaceMetaStar, verifyCommit, verifyCredentialSig, verifyRecord, verifyRepoStarFull, writeSpaceMetaStar } = await import(pathToFileURL(`${sdk}/node_modules/@atproto/space/dist/index.js`)); const { P256Keypair } = await import(pathToFileURL(`${sdk}/node_modules/@atproto/crypto/dist/index.js`)); const key = await P256Keypair.create(); const owner = 'did:plc:permissionsmoke'; const member = 'did:plc:spacesmokebob'; const base = process.env.SMOKE_BASE; async function call(method, { token = process.env.SMOKE_TOKEN, body, query, headers = {}, status = 200 } = {}) { const response = await fetch(`${base}/xrpc/${method}${query ? `?${new URLSearchParams(query)}` : ''}`, { method: body ? 'POST' : 'GET', headers: { ...(token ? { authorization: `Bearer ${token}` } : {}), 'content-type': 'application/json', ...headers }, body: body ? JSON.stringify(body) : undefined, }); const value = await response.json(); assert.equal(response.status, status, JSON.stringify(value)); return value; } const policy = { $type: 'com.atproto.memberspace.policy', publishPolicy: true, publishMembers: true }; const { space } = await call('com.atproto.space.createSpace', { body: { spaceType: 'test.interop.space', skey: 'self', policy } }); await call('com.atproto.memberspace.putMembers', { body: { space, members: [{ did: member, read: true, write: true }] } }); await call('com.atproto.space.createRecord', { token: process.env.SMOKE_BOB_TOKEN, body: { space, repo: member, collection: 'test.interop.record', rkey: 'one', record: { $type: 'test.interop.record', text: 'cross-implementation' } }, }); const { token: delegation } = await call('com.atproto.space.getDelegationToken', { query: { space } }); const { credential } = await call('com.atproto.space.authorizeSpaceSync', { token: null, body: { space, credentialKey: key.did(), delegationToken: delegation } }); const claims = JSON.parse(Buffer.from(credential.split('.')[1], 'base64url')); assert.equal(claims.cnf.kid, key.did()); const authorization = `Atproto-Space-Credential ${credential}`; const hostHeaders = (await createSpaceSigHeaders({ authorization, audience: owner, keypair: key })).headers; const repos = await call('com.atproto.space.listWriters', { query: { space }, headers: hostHeaders }); // Publishing the policy committed to the authority's repo, so it is a writer too. assert.deepEqual(repos.repos.map(r => r.repo).sort(), [owner, member].sort()); assert.ok(repos.repos.every(r => r.$type === 'com.atproto.space.defs#repoWrite' && typeof r.repoRev === 'string' && r.data.$bytes && r.spaceRev && !('latest' in r))); const query = { space, repo: member, collection: 'test.interop.record' }; assert.equal((await call('com.atproto.space.listRecords', { query, headers: hostHeaders, status: 401 })).error, 'BadSpaceAudience'); const repoHeaders = (await createSpaceSigHeaders({ authorization, audience: member, keypair: key })).headers; assert.equal((await call('com.atproto.space.listRecords', { query, headers: repoHeaders })).records.length, 1); const { didDoc } = await call('com.atproto.server.getSession', { token: process.env.SMOKE_BOB_TOKEN }); const kemKey = `did:key:${didDoc.verificationMethod.find(m => m.id === '#atproto_kem').publicKeyMultibase}`; async function macGet(method, params, profile) { const { keyShare, sharedSecret } = await encapsulate(kemKey); const response = await fetch(`${base}/xrpc/${method}?${new URLSearchParams(params)}`, { headers: { ...repoHeaders, 'accept-signature': formatMacRequest(profile, keyShare) }, }); assert.equal(response.status, 200, method); assert.match(response.headers.get('vary'), /accept-signature/); return { response, mac: { keyShare, sharedSecret, headers: response.headers } }; } const repoParams = { space, repo: member }; const missing = await fetch(`${base}/xrpc/com.atproto.space.getLatestCommit?${new URLSearchParams(repoParams)}`, { headers: repoHeaders }); assert.equal(missing.status, 400); assert.equal((await missing.json()).error, 'InvalidSpaceMac'); const latest = await macGet('com.atproto.space.getLatestCommit', repoParams, COMMIT_MAC_PROFILE); const { commit } = await latest.response.json(); const lexCommit = { ...commit, data: Buffer.from(commit.data.$bytes, 'base64') }; verifyCommit(lexCommit, { space, repo: member, ...latest.mac }); const otherSecret = (await encapsulate(kemKey)).sharedSecret; assert.throws(() => verifyCommit(lexCommit, { space, repo: member, ...latest.mac, sharedSecret: otherSecret })); const ops = await macGet('com.atproto.space.listRepoOps', repoParams, COMMIT_MAC_PROFILE); const opsCommit = (await ops.response.json()).commit; verifyCommit({ ...opsCommit, data: Buffer.from(opsCommit.data.$bytes, 'base64') }, { space, repo: member, ...ops.mac }); const record = await macGet('com.atproto.space.getRecord', { ...repoParams, collection: 'test.interop.record', rkey: 'one' }, RECORD_MAC_PROFILE); const recordBody = await record.response.json(); await verifyRecord(recordBody, { uri: `${space}/${member}/test.interop.record/one`, ...record.mac }); const repo = await macGet('com.atproto.space.getRepo', repoParams, COMMIT_MAC_PROFILE); assert.equal(repo.response.headers.get('content-type'), 'application/vnd.dasl.star'); const { records } = await verifyRepoStarFull([new Uint8Array(await repo.response.arrayBuffer())], { space, repo: member, ...repo.mac }); assert.deepEqual(records.map(r => `${r.collection}/${r.rkey}`), ['test.interop.record/one']); const params = `("authorization" "atproto-space-audience");tag="atproto-space-credential";keyid="${key.did()}";alg="ecdsa-p256-sha256";created=123;nonce="a,b"`; const signatureBase = `"authorization": ${authorization}\n"atproto-space-audience": ${owner}\n"@signature-params": ${params}`; const signature = await key.sign(new TextEncoder().encode(signatureBase)); const extended = { ...hostHeaders, 'signature-input': `other=("date"), atproto-space-credential=${params}`, signature: `other=:YWJj:, atproto-space-credential=:${Buffer.from(signature).toString('base64')}:` }; await verifyCredentialSig(extended, key.did()); await call('com.atproto.space.listWriters', { query: { space }, headers: extended }); const order = BigInt('0xffffffff00000000ffffffffffffffffbce6faada7179e84f3b9cac2fc632551'); const high = Buffer.from(signature); Buffer.from((order - BigInt(`0x${high.subarray(32).toString('hex')}`)).toString(16).padStart(64, '0'), 'hex').copy(high, 32); extended.signature = `atproto-space-credential=:${high.toString('base64')}:`; await call('com.atproto.space.listWriters', { query: { space }, headers: extended }); // The authority's repo carries the published configuration, and its records // fold to the commit's data as the SDK checks for a repo host import. async function readOwnRepo(token, repo) { const response = await fetch(`${base}/xrpc/com.atproto.space.getRepo?${new URLSearchParams({ space, repo })}`, { headers: { authorization: `Bearer ${token}` } }); assert.equal(response.status, 200); const archive = await readRepoStar([new Uint8Array(await response.arrayBuffer())]); const found = []; try { for await (const entry of archive.records) found.push({ path: `${entry.collection}/${entry.rkey}`, record: entry.record }); } finally { await archive[Symbol.asyncDispose](); } return { commit: archive.commit, records: found }; } const published = await readOwnRepo(process.env.SMOKE_TOKEN, owner); assert.deepEqual(published.records.map(r => r.path), ['com.atproto.memberspace.member/' + member, 'com.atproto.space.policy/self']); assert.equal(published.records[1].record.policy.$type, 'com.atproto.memberspace.policy'); assert.equal(published.records[1].record.policy.publishMembers, true); assert.deepEqual({ read: published.records[0].record.read, write: published.records[0].record.write }, { read: true, write: true }); // A cleared repo verifies as empty under the MAC'd commit. await call('com.atproto.space.clearRecords', { token: process.env.SMOKE_BOB_TOKEN, body: { space, repo: member } }); const cleared = await macGet('com.atproto.space.getRepo', repoParams, COMMIT_MAC_PROFILE); const emptied = await verifyRepoStarFull([new Uint8Array(await cleared.response.arrayBuffer())], { space, repo: member, ...cleared.mac }); assert.deepEqual(emptied.records, []); assert.equal(Buffer.from(emptied.commit.data).toString('hex'), 'e5a00aa9991ac8a5ee3109844d84a55583bd20572ad3ffcd42792f3c36b183ad'); assert.ok(emptied.commit.rev > commit.rev); // Account migration archives: the SDK reads what ZDS exports, and ZDS imports // what the SDK serializes, replacing what it held. async function octets(method, { query, body, status = 200 } = {}) { const response = await fetch(`${base}/xrpc/${method}${query ? `?${new URLSearchParams(query)}` : ''}`, { method: body ? 'POST' : 'GET', headers: { authorization: `Bearer ${process.env.SMOKE_TOKEN}`, ...(body ? { 'content-type': 'application/vnd.dasl.star' } : {}) }, body, }); assert.equal(response.status, status, body ? await response.clone().text() : method); return response; } const serialized = async (archive) => { const chunks = []; for await (const chunk of writeSpaceMetaStar(archive)) chunks.push(chunk); return Buffer.concat(chunks); }; const exported = new Uint8Array(await (await octets('com.atproto.space.exportSpaceMeta', { query: { space } })).arrayBuffer()); const meta = await readSpaceMetaStar([exported]); assert.equal(meta.space, space); assert.equal(meta.policy.$type, 'com.atproto.memberspace.policy'); assert.deepEqual(meta.policyState.map(e => e.key), [`com.atproto.memberspace.member/${member}`]); assert.deepEqual(meta.writers.map(w => w.did).sort(), [owner, member].sort()); assert.ok(meta.writers.every(w => typeof w.repoRev === 'string' && !('rev' in w))); assert.deepEqual(new Uint8Array(await serialized(meta)), exported); await octets('com.atproto.space.importSpaceMeta', { body: await serialized(meta) }); for (const [bad, error] of [ [{ ...meta, policy: { $type: 'com.example.policy' } }, 'UnsupportedPolicy'], [{ ...meta, policyState: [{ key: 'com.example.state/x', value: {} }] }, 'InvalidSpaceMeta'], ]) { const response = await octets('com.atproto.space.importSpaceMeta', { body: await serialized(bad), status: 400 }); assert.equal((await response.json()).error, error); } const ownRepo = new Uint8Array(await (await octets('com.atproto.space.getRepo', { query: { space, repo: owner } })).arrayBuffer()); const before = await readOwnRepo(process.env.SMOKE_TOKEN, owner); await octets('com.atproto.space.importRepo', { body: ownRepo }); const after = await readOwnRepo(process.env.SMOKE_TOKEN, owner); assert.deepEqual(after.records.map(r => r.path), before.records.map(r => r.path)); assert.deepEqual(Buffer.from(after.commit.data), Buffer.from(before.commit.data)); assert.ok(after.commit.rev > before.commit.rev); await call('com.atproto.space.deleteSpace', { body: { space } }); const fixed = await P256Keypair.import(new Uint8Array(32).fill(0x42)); const result = spawnSync('./zig-out/bin/zds-space-signature', [authorization, owner], { encoding: 'utf8' }); assert.equal(result.status, 0); const headers = Object.fromEntries(result.stderr.trim().split('\n').map(line => { const index = line.indexOf(': '); return [line.slice(0, index), line.slice(index + 2)]; })); headers.authorization = authorization; await verifyCredentialSig(headers, fixed.did()); console.log('Spaces SDK signatures accepted by ZDS; cross-repo audiences, high-S, commit and record MACs, STAR export, published configuration, cleared repos, and space migration archives verified');