// Phase 2 OVER-THE-WIRE verify (still OFFLINE — @hyperswarm/testnet, no real DHT/prod): serve the RECOVERED
// loser-club repo via the real bootSwarmDevice -> serveMembrane path, and prove a KEYLESS client (the bridge
// model — PeerRouter announce -> replicate -> verify) fronts it: receives the pushed announce, replicates the
// firehose + repo cores, verifies the signed #commit against the DID #atproto key, and assembles the repo CAR
// with the feed records — holding NO key. Run from hyper-proto-peer with bare.
import './lib/bare-globals.js'
import process from 'bare-process'
import { readFileSync } from 'bare-fs'
import b4a from 'b4a'
import c from 'compact-encoding'
import Hyperswarm from 'hyperswarm'
import Protomux from 'protomux'
import createTestnet from '@hyperswarm/testnet'
import { bootSwarmDevice } from './lib/device-node.js'
import { deviceKeetKeyPair, attestDeviceChain, rootIdentityPublicKey } from 'atproto-room/lib/membership.js'
import { deriveAtprotoKey } from 'atproto-identity'
import { decodeDidKey } from 'atproto-identity/lib/did-key.js'
import { discoveryTopic } from 'atproto-identity/lib/discovery.js'
import { openCorestore } from 'atproto-store/lib/corestore.js'
import { RepoStore } from 'atproto-store/lib/repo-store.js'
import { FirehoseSequencer } from 'atproto-store/lib/sequencer.js'
import { decodeCommitFrame } from 'atproto-store/lib/firehose.js'
import { getRepoFromCommit } from 'atproto-store/lib/read-view.js'
import { readCar, loadCommit, listRecords } from 'atproto-repo/lib/repo.js'
import { verifyCommit } from 'atproto-repo/lib/commit.js'
const V2 = '/tmp/claude-1000/-storage-projects-code-hypercore-kb/656ea8cd-954c-48f3-8b96-8bc7edd06967/scratchpad/phase2-verify'
const MEMBRANE = 'https://pds.7rnx.net'
const s = JSON.parse(readFileSync(process.env.HOME + '/.config/loser-club/secrets.json'))
const sleep = (ms) => new Promise((r) => setTimeout(r, ms))
const assert = (cond, m) => { if (!cond) { console.error('FAIL:', m); process.exit(1) } console.log(' ok -', m) }
// DID #atproto pubkey + serve bundle from secrets (endpoint-independent; NOT provisionDevice)
const { pubkey } = decodeDidKey(deriveAtprotoKey(s.rootMnemonic).didKey)
const founderKp = await deviceKeetKeyPair(s.founderDeviceMnemonic)
const deviceProof = b4a.toString(b4a.from(await attestDeviceChain({ rootMnemonic: s.rootMnemonic, devicePublicKey: founderKp.publicKey })), 'hex')
const rootIdentityKey = b4a.toString(await rootIdentityPublicKey(s.rootMnemonic), 'hex')
const testnet = await createTestnet(3)
// SERVE: the recovered repo, via the real hpp swarm entry, over the testnet swarm (auto sign loop)
const node = await bootSwarmDevice({
storage: V2 + '/repo', deviceMnemonic: s.founderDeviceMnemonic,
did: s.did, signingKey: s.signingKey, deviceProof, rootIdentityKey,
handle: s.handle, pdsUrl: MEMBRANE,
swarm: true, swarmOpts: { bootstrap: testnet.bootstrap }, signIntervalMs: 2000
})
assert(node.did === s.did, 'serving node booted under the recovered DID over testnet')
// KEYLESS CLIENT: connect on the DID topic, replicate, receive the pushed announce (bridge PeerRouter model)
const clientSwarm = new Hyperswarm({ bootstrap: testnet.bootstrap })
const clientStore = openCorestore(V2 + '/client')
const coords = await new Promise((resolve, reject) => {
const to = setTimeout(() => reject(new Error('no announce within 60s')), 60000)
clientSwarm.on('connection', (conn) => {
clientStore.replicate(conn)
const achan = Protomux.from(conn).createChannel({ protocol: 'atproto/did-announce/v1' })
if (!achan) return
achan.addMessage({ encoding: c.json, onmessage: (a) => { clearTimeout(to); resolve(a) } })
achan.open()
})
clientSwarm.join(discoveryTopic(s.did), { client: true, server: false })
})
assert(coords.did === s.did, 'keyless client received the pushed announce carrying the DID')
assert(coords.repoKey && coords.firehoseKey, 'announce carries repo + firehose Hypercore keys')
const repo = await new RepoStore(clientStore, { key: coords.repoKey }).ready()
const seq = await new FirehoseSequencer(clientStore.get({ key: coords.firehoseKey })).ready()
for (let i = 0; i < 60 && seq.core.length === 0; i++) { await seq.core.update().catch(() => {}); if (seq.core.length === 0) await sleep(500) }
assert(seq.core.length > 0, 'the signed firehose replicated to the keyless client')
const { body } = decodeCommitFrame(await seq.core.get(seq.core.length - 1))
const signedCommit = loadCommit(await readCar(body.blocks)).value
assert(verifyCommit(signedCommit, pubkey), 'the replicated #commit VERIFIES against the loser-club #atproto key (client holds NO key)')
let recs = []
for (let i = 0; i < 60 && recs.length === 0; i++) { await repo.core.update().catch(() => {}); recs = await repo.records().catch(() => []); if (!recs.length) await sleep(500) }
const { carBytes } = await getRepoFromCommit(repo, signedCommit)
const keys = listRecords(await readCar(carBytes)).map((r) => r.key)
assert(keys.includes('app.bsky.feed.generator/loser-club'), 'keyless client assembled the repo CAR incl. feed.generator/loser-club')
assert(keys.includes('app.bsky.labeler.service/self'), 'keyless client assembled the repo CAR incl. labeler.service/self')
console.log('\nPHASE 2 (over-wire) OK: recovered repo served via bootSwarmDevice -> serveMembrane over testnet; a KEYLESS client (bridge model) replicated, verified the signed commit vs the DID key, and assembled the repo CAR with the feed records. No key held by the client.')
try { await node.close() } catch {}
try { await clientSwarm.destroy() } catch {}
try { await clientStore.close() } catch {}
try { await testnet.destroy() } catch {}
process.exit(0)