OverviewFilesCommitsIssuesDocsReleasesPeers

hyper-proto-peer / test / peer-adopt.test.js

42 lines · javascript ref:
// Peer.adopt (migration): bring-your-own existing DID + signing key (no mint), import records,
// serve under the adopted key, and reload durably. This is the mechanism behind migrating a
// custodial account (e.g. p2p.7rnx.net/wj62) to a self-custody peer.

import test from 'brittle'
import { mkdtempSync, rmSync } from 'bare-fs'
import { tmpdir } from 'bare-os'
import { join } from 'bare-path'
import { createAtprotoIdentityFromKey } from 'atproto-identity'
import { decodeDidKey } from 'atproto-identity/lib/did-key.js'
import { verifyCommit } from 'atproto-repo/lib/commit.js'
import { readCar, loadCommit, listRecords } from 'atproto-repo/lib/repo.js'
import { Peer } from '../lib/peer.js'

const PRIV = new Uint8Array(32).fill(7)
const NOW = '2026-07-03T00:00:00.000Z'

test('Peer.adopt: bring-your-own DID + key, import records, serve, reload', async (t) => {
  const dir = mkdtempSync(join(tmpdir(), 'adopt-'))
  t.teardown(() => rmSync(dir, { recursive: true, force: true }))

  // simulate an existing published identity (the migration source holds did + key + didKey)
  const id = createAtprotoIdentityFromKey(PRIV, { handle: 'x.7rnx.net', pdsUrl: 'https://pds.7rnx.net' })

  const peer = await Peer.adopt({ storage: dir, did: id.did, handle: 'x.7rnx.net', privateKey: id.privateKey, didKey: id.didKey, pdsUrl: 'https://pds.7rnx.net' })
  t.is(peer.did, id.did, 'adopted the given DID (no mint)')

  await peer.importRecords([{ collection: 'app.bsky.feed.post', rkey: '3a', record: { $type: 'app.bsky.feed.post', text: 'imported', createdAt: NOW } }])

  const { carBytes } = await peer.getRepo()
  const { pubkey } = decodeDidKey(peer.didKey)
  t.ok(verifyCommit(loadCommit(await readCar(carBytes)).value, pubkey), 'serves a signed repo under the adopted key')
  const recs = await listRecords(await readCar(carBytes))
  t.ok(recs.some((r) => r.value.text === 'imported'), 'imported record present in the served repo')
  await peer.close()

  const re = await Peer.load({ storage: dir })
  t.is(re.did, id.did, 'reloads the adopted DID durably')
  t.is((await re.store.records()).length, 1, 'imported repo persisted across reload')
  await re.close()
})