// getRepoFromCommit: assemble a full repo CAR KEYLESSLY from the store's records + a PROVIDED
// signed commit (as a bridge does with a commit read from a peer's replicated firehose). The
// MST/records rebuild without the key; the signature travels in the commit. Includes the
// integrity guard (a commit that doesn't match the records is refused).
import test from 'brittle'
import { mkdtempSync, rmSync } from 'node:fs'
import { tmpdir } from 'node:os'
import { join } from 'node:path'
import { openCorestore } from '../lib/corestore.js'
import { RepoStore } from '../lib/repo-store.js'
import { RepoManager } from '../lib/repo-manager.js'
import { getRepoFromCommit } from '../lib/read-view.js'
import { readCar, loadCommit, listRecords } from 'atproto-repo/lib/repo.js'
import { cidForBytesSync } from 'atproto-repo/lib/cid.js'
const PRIV = new Uint8Array(32).fill(7)
const NOW = '2026-07-03T00:00:00.000Z'
test('getRepoFromCommit assembles a byte-exact CAR keylessly from a provided signed commit', async (t) => {
const dir = mkdtempSync(join(tmpdir(), 'store-keyless-'))
const store = openCorestore(dir)
const repo = await new RepoStore(store, { name: 'atproto-repo' }).ready()
let micros = 1_700_000_000_000_000n
const mgr = await new RepoManager(repo, { did: 'did:plc:x', privateKey: PRIV, clock: () => (micros += 1_000_000n) }).init()
const w = await mgr.applyWrite({ action: 'create', collection: 'app.bsky.feed.post', rkey: '3a', record: { $type: 'app.bsky.feed.post', text: 'hi', createdAt: NOW } })
t.teardown(async () => { await repo.close(); await store.close(); rmSync(dir, { recursive: true, force: true }) })
// KEYLESS: no privateKey — the signed commit is provided (as read from a firehose).
const { carBytes, commitCid: cc } = await getRepoFromCommit(repo, w.signedCommit)
t.ok(cc.equals(w.commitCid), 'keyless CAR is rooted at the provided signed commit')
const car = await readCar(carBytes)
t.ok(loadCommit(car).value.sig, 'CAR carries the signed commit (signature present, not re-derived)')
const recs = await listRecords(car)
t.ok(recs.some(r => r.value.text === 'hi'), 'records present in the keyless CAR')
// integrity guard: a commit that does not commit to these records is refused
const bogus = cidForBytesSync(new Uint8Array([1, 2, 3]))
await t.exception(getRepoFromCommit(repo, { ...w.signedCommit, data: bogus }),
'refuses a signed commit whose data CID != the rebuilt MST root')
})