// Phase B (firehose persistence, option a): the lease-holder's signed #commit is written into the
// SHARED StateBaseV3 under __commit__/<rev>, so it replicates to every co-equal device (and the
// keyless membrane) — no separate core, continuous across hand-offs. This proves, over real
// StateBaseV3 replication on a testnet: (1) signing persists a firehose entry, (2) a second device
// reads the SAME entry via replication, (3) the reserved __commit__ namespace NEVER leaks into the
// signed repo, (4) the persisted commit deserializes + verifies against the signing key.
import '../lib/bare-globals.js'
import test from 'brittle'
import crypto from 'hypercore-crypto'
import fs from 'bare-fs'
import b4a from 'b4a'
import * as dagCbor from '@ipld/dag-cbor'
import createTestnet from '@hyperswarm/testnet'
import { StateBaseV3 } from 'atproto-room/lib/state-base.js'
import { SwarmDevice } from '../lib/swarm-device.js'
import { makeAttest, makeVerifyAttest, attestDeviceChain, deviceKeetKeyPair, rootIdentityPublicKey } from 'atproto-room/lib/membership.js'
import { verifyCommit } from 'atproto-repo/lib/commit.js'
import { deriveAtprotoKey } from 'atproto-identity'
import { decodeDidKey } from 'atproto-identity/lib/did-key.js'
const ROOT = 'abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon abandon about'
const DEVA = 'legal winner thank year wave sausage worth useful legal winner thank yellow'
const DEVB = 'zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo zoo wrong'
const DID = 'did:plc:swarmfh2222222222222222'
const POST = 'app.bsky.feed.post'
const signKey = deriveAtprotoKey(ROOT) // the shared #atproto signing key (deterministic from the root)
const { pubkey } = decodeDidKey(signKey.didKey)
function tmp () { const d = '/tmp/hpp-fh-' + Math.floor(Math.random() * 1e9); fs.mkdirSync(d, { recursive: true }); return d }
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
test('firehose #commit persists to the shared log, replicates to a co-equal device, never leaks into the repo', async (t) => {
const testnet = await createTestnet(3)
const rootPub = await rootIdentityPublicKey(ROOT)
const devA = await deviceKeetKeyPair(DEVA); const proofA = await attestDeviceChain({ rootMnemonic: ROOT, devicePublicKey: devA.publicKey })
const devB = await deviceKeetKeyPair(DEVB); const proofB = await attestDeviceChain({ rootMnemonic: ROOT, devicePublicKey: devB.publicKey })
const members = [
{ key: b4a.toString(devA.publicKey, 'hex'), role: 1 },
{ key: b4a.toString(devB.publicKey, 'hex'), role: 1 }
]
const roomSeed = crypto.randomBytes(32); const roomKey = crypto.randomBytes(32); const encryptionKey = crypto.randomBytes(32)
const mk = (dev, proof) => new StateBaseV3(tmp(), roomKey, {
roomSeed, encryptionKey, swarmOpts: { bootstrap: testnet.bootstrap },
selfKey: dev.publicKey, attest: makeAttest(dev, proof), verifyAttest: makeVerifyAttest(rootPub),
getMembers: async () => members
})
const A = mk(devA, proofA); await A.ready(); await A.projectMembers(members)
const B = mk(devB, proofB); await B.ready()
t.teardown(async () => { try { await A.close(); await B.close() } catch {} ; await testnet.destroy() })
const deviceB = new SwarmDevice(B, { did: DID, privateKey: signKey.privateKey, self: members[1].key, firehose: true })
// B (second device) gets admitted as a writer via attestation — the proven multi-device flow
// (StateBaseV3 uses a deterministic bootstrap key + no pinned keyPair, so a device WRITES only
// once admitted). Then B becomes the active signer and emits a firehose #commit.
let admitted = false
for (let i = 0; i < 40 && !admitted; i++) {
try { await deviceB.putRecord(POST, '3mmwu7vak2000', { $type: POST, text: 'hello from the swarm', createdAt: '2026-07-04T00:00:00.000Z' }) } catch {}
await B.set('__ping__', { i }).catch(() => {}) // nudge replication/admission
await sleep(1500)
admitted = await B.effectiveWritable().catch(() => false)
}
t.ok(admitted, 'device B admitted as a writer via attestation')
let head = null
for (let i = 0; i < 20 && !head; i++) {
await deviceB.claimLease().catch(() => {})
head = await deviceB.sign().catch(() => null)
if (!head) await sleep(500)
}
t.ok(head, 'B (lease-holder) signed a #commit')
const logB = await deviceB.firehoseLog()
t.is(logB.length, 1, 'B persisted one firehose #commit entry')
t.is(logB[0].commitCid, head.commitCid.toString(), 'firehose entry commitCid == the signed head')
// it replicates to A (a co-equal device reads the SAME firehose via StateBaseV3 replication).
const deviceA = new SwarmDevice(A, { did: DID, privateKey: signKey.privateKey, self: members[0].key })
let logA = []
for (let i = 0; i < 40 && logA.length === 0; i++) { await A.base.update().catch(() => {}); logA = await deviceA.firehoseLog(); if (!logA.length) await sleep(1000) }
t.is(logA.length, 1, 'A reads the firehose entry via replication')
t.is(logA[0].commitCid, logB[0].commitCid, 'same #commit on both devices')
// the reserved __commit__ namespace NEVER leaks into the signed repo record set.
const recsA = await deviceA.repo.listRecords()
const recsB = await deviceB.repo.listRecords()
t.ok(recsA.every((r) => r.collection !== '__commit__') && recsB.every((r) => r.collection !== '__commit__'), '__commit__ never appears as a repo record')
// the persisted commit deserializes + verifies against the shared signing key.
const signed = dagCbor.decode(b4a.from(logA[0].commit, 'hex'))
t.ok(verifyCommit(signed, pubkey), 'the persisted #commit verifies against the shared #atproto key')
})