@bsv/create-dpp-app 0.1.0-beta.1 → 0.1.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +2 -0
- package/PATENTS +12 -0
- package/README.md +26 -6
- package/dist/index.js +36 -8
- package/package.json +9 -5
- package/template/Dockerfile +4 -2
- package/template/README.md +297 -42
- package/template/_env.example +82 -13
- package/template/_github/workflows/ci.yml +3 -3
- package/template/apps/api/API.md +86 -16
- package/template/apps/api/package.json +9 -4
- package/template/apps/api/src/bound-profiles.ts +590 -0
- package/template/apps/api/src/claims.ts +175 -56
- package/template/apps/api/src/cli.ts +64 -7
- package/template/apps/api/src/config.ts +124 -10
- package/template/apps/api/src/custody.ts +241 -69
- package/template/apps/api/src/dev-index.ts +58 -9
- package/template/apps/api/src/env-file.ts +55 -0
- package/template/apps/api/src/epcis/exchange.ts +434 -0
- package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
- package/template/apps/api/src/epcis/routes.ts +364 -0
- package/template/apps/api/src/epcis/sources.ts +142 -0
- package/template/apps/api/src/go-live.ts +226 -0
- package/template/apps/api/src/http-error.ts +15 -0
- package/template/apps/api/src/identifiers.ts +1 -1
- package/template/apps/api/src/index-client.ts +131 -6
- package/template/apps/api/src/index-projects.ts +53 -0
- package/template/apps/api/src/lifecycle-authority.ts +49 -0
- package/template/apps/api/src/lifecycle.ts +485 -0
- package/template/apps/api/src/main.ts +10 -2
- package/template/apps/api/src/parties.ts +2 -2
- package/template/apps/api/src/platform.ts +72 -17
- package/template/apps/api/src/portability/commands.ts +224 -0
- package/template/apps/api/src/portability/export.ts +708 -0
- package/template/apps/api/src/portability/package.ts +270 -0
- package/template/apps/api/src/portability/restore.ts +863 -0
- package/template/apps/api/src/profiles.ts +38 -13
- package/template/apps/api/src/reader.ts +172 -3
- package/template/apps/api/src/resolver.ts +159 -0
- package/template/apps/api/src/sector-examples.ts +390 -0
- package/template/apps/api/src/server.ts +253 -60
- package/template/apps/api/src/store.ts +198 -21
- package/template/apps/api/src/validation-engine.ts +172 -0
- package/template/apps/api/src/wallet.ts +30 -17
- package/template/apps/api/src/worker.ts +20 -13
- package/template/apps/api/src/writer.ts +383 -131
- package/template/apps/api/test/bound-http.test.ts +496 -0
- package/template/apps/api/test/bound-profiles.test.ts +547 -0
- package/template/apps/api/test/config.test.ts +148 -3
- package/template/apps/api/test/custody-journal.test.ts +415 -0
- package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
- package/template/apps/api/test/custom-profile.test.ts +167 -0
- package/template/apps/api/test/env-file.test.ts +53 -0
- package/template/apps/api/test/epcis-fixtures.ts +270 -0
- package/template/apps/api/test/epcis-http.test.ts +1179 -0
- package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
- package/template/apps/api/test/epcis-separation.test.ts +253 -0
- package/template/apps/api/test/epcis-web.test.ts +230 -0
- package/template/apps/api/test/exit-exercise.test.ts +1038 -0
- package/template/apps/api/test/external-index.test.ts +3 -2
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
- package/template/apps/api/test/go-live.test.ts +179 -0
- package/template/apps/api/test/gs1-global-setup.ts +33 -0
- package/template/apps/api/test/gs1-test-env.ts +5 -0
- package/template/apps/api/test/identifier-host.test.ts +256 -0
- package/template/apps/api/test/index-projects.test.ts +81 -0
- package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
- package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
- package/template/apps/api/test/lifecycle.test.ts +17 -6
- package/template/apps/api/test/manifest-notice.test.ts +36 -0
- package/template/apps/api/test/network-guard.ts +113 -0
- package/template/apps/api/test/portability.test.ts +655 -0
- package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
- package/template/apps/api/test/retired-profiles.test.ts +216 -0
- package/template/apps/api/test/sector-cutover.test.ts +95 -0
- package/template/apps/api/test/sector-forms.test.ts +420 -0
- package/template/apps/api/test/unjoined-index.test.ts +62 -0
- package/template/apps/api/test/validation-engine.test.ts +328 -0
- package/template/apps/api/test/wallet-monitor.test.ts +38 -0
- package/template/apps/api/test/writer-journal.test.ts +327 -0
- package/template/apps/api/vitest.config.ts +3 -0
- package/template/apps/web/src/app.tsx +8 -4
- package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
- package/template/apps/web/src/components/bound/field-view.tsx +237 -0
- package/template/apps/web/src/components/bound/pieces.tsx +169 -0
- package/template/apps/web/src/components/bound/readings.tsx +152 -0
- package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
- package/template/apps/web/src/components/claim-dialog.tsx +344 -0
- package/template/apps/web/src/components/epcis-events.tsx +119 -0
- package/template/apps/web/src/components/layout.tsx +17 -0
- package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
- package/template/apps/web/src/components/passport-form.tsx +2 -2
- package/template/apps/web/src/components/read-passport.tsx +4 -3
- package/template/apps/web/src/components/reading.tsx +32 -39
- package/template/apps/web/src/lib/api.ts +136 -26
- package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
- package/template/apps/web/src/lib/bound/display.ts +122 -0
- package/template/apps/web/src/lib/bound/fields.ts +128 -0
- package/template/apps/web/src/lib/bound/form-model.ts +521 -0
- package/template/apps/web/src/lib/bound/forms.ts +15 -0
- package/template/apps/web/src/lib/bound/identity.ts +48 -0
- package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
- package/template/apps/web/src/lib/bound/units.ts +37 -0
- package/template/apps/web/src/lib/epcis.ts +345 -0
- package/template/apps/web/src/lib/format.ts +27 -4
- package/template/apps/web/src/lib/lifecycle.ts +350 -0
- package/template/apps/web/src/pages/accept.tsx +8 -3
- package/template/apps/web/src/pages/events.tsx +388 -0
- package/template/apps/web/src/pages/new-passport.tsx +25 -2
- package/template/apps/web/src/pages/operations.tsx +22 -3
- package/template/apps/web/src/pages/passport.tsx +226 -162
- package/template/apps/web/src/pages/public-passport.tsx +50 -10
- package/template/apps/web/src/pages/wallet.tsx +1 -1
- package/template/apps/web/vite.config.ts +12 -4
- package/template/deploy/compose.yml +14 -2
- package/template/package.json +9 -3
|
@@ -0,0 +1,655 @@
|
|
|
1
|
+
// The export and the restore, on the parts the exit exercise does not reach:
|
|
2
|
+
// a passport that was handed on, with its acceptance record, its offer, an
|
|
3
|
+
// EPCIS lifecycle claim that binds it and a second passport, and a
|
|
4
|
+
// historical native claim; the index's complete export in place of its bounded
|
|
5
|
+
// package; a deployment that already holds something else under an identity
|
|
6
|
+
// the package carries; and an export that would have carried a secret.
|
|
7
|
+
//
|
|
8
|
+
// Everything runs in this process with no services: the records are in
|
|
9
|
+
// memory, the wallet is the test wallet, and each platform has an index of
|
|
10
|
+
// its own with in-memory storage and its header checks off. The second
|
|
11
|
+
// platform holding the same keys as the first stands in for the wallet's own
|
|
12
|
+
// recovery. No reading here is a statement about inclusion in a block.
|
|
13
|
+
import { createHash } from 'node:crypto'
|
|
14
|
+
import { existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs'
|
|
15
|
+
import { tmpdir } from 'node:os'
|
|
16
|
+
import { join } from 'node:path'
|
|
17
|
+
import { MerklePath, PrivateKey, Transaction, Utils } from '@bsv/sdk'
|
|
18
|
+
import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
|
|
19
|
+
import { acceptanceCommitment, acceptanceRecordsInPackage, findDppOutputs, verifyOwnerBlob, evidencePackageSigner, evidencePackageSigningKey, inspectEvidencePackage, signEvidenceManifest, signLifecycleClaim, type EvidencePackageManifest } from '@bsv/dpp-protocol'
|
|
20
|
+
import { createMemoryEpcisStorage } from '@bsv/dpp-credentials/epcis-exchange'
|
|
21
|
+
import { loadConfig } from '../src/config.js'
|
|
22
|
+
import { managedParties } from '../src/parties.js'
|
|
23
|
+
import { mintPassportId } from '../src/identifiers.js'
|
|
24
|
+
import { eventSchemaCheck, readPassportClaims } from '../src/lifecycle.js'
|
|
25
|
+
import { openPlatform, type Platform } from '../src/platform.js'
|
|
26
|
+
import { exportApplication, type ExportedApplication } from '../src/portability/export.js'
|
|
27
|
+
import { EXPORT_SCOPE_PREFIX, PortabilityRefused, asNumberArrays, exportScopeId, passportFolder, readPackageFolder, stableJson, writePackageFolder } from '../src/portability/package.js'
|
|
28
|
+
import { restoreApplication, verifyApplicationPackage, type RestoreReport } from '../src/portability/restore.js'
|
|
29
|
+
import { samplePayload } from '../src/profiles.js'
|
|
30
|
+
import type { EpcisLifecycleClaimRecord } from '../src/store.js'
|
|
31
|
+
import { runDuties } from '../src/worker.js'
|
|
32
|
+
import { OWNER_DATA_PROTOCOL } from '../src/writer.js'
|
|
33
|
+
import { gs1Dir } from './epcis-fixtures.js'
|
|
34
|
+
|
|
35
|
+
const settings = { NETWORK: 'main', PASSPORT_HOST: 'passports.example.com', GS1_PREFIX: '952', LIVE_PUBLISHING: 'false' }
|
|
36
|
+
const config = loadConfig(settings)
|
|
37
|
+
const policy = { host: config.passportHost, prefix: config.gs1Prefix }
|
|
38
|
+
const brandId = 'brand-portable-1'
|
|
39
|
+
const scratch = mkdtempSync(join(tmpdir(), 'dpp-portability-'))
|
|
40
|
+
|
|
41
|
+
let first: Platform
|
|
42
|
+
let second: Platform
|
|
43
|
+
let passportId: string
|
|
44
|
+
let otherId: string
|
|
45
|
+
let claimCode: string
|
|
46
|
+
let exported: ExportedApplication
|
|
47
|
+
let lifecycleClaim: EpcisLifecycleClaimRecord
|
|
48
|
+
const exchange = () => ({ storage: createMemoryEpcisStorage(), sources: [] })
|
|
49
|
+
|
|
50
|
+
const refusal = async (attempt: Promise<unknown>): Promise<PortabilityRefused> => {
|
|
51
|
+
try {
|
|
52
|
+
await attempt
|
|
53
|
+
} catch (cause) {
|
|
54
|
+
if (cause instanceof PortabilityRefused) return cause
|
|
55
|
+
throw cause
|
|
56
|
+
}
|
|
57
|
+
throw new Error('nothing was refused')
|
|
58
|
+
}
|
|
59
|
+
const trust = (platform: Platform) => ({ exporterKey: platform.wallet.identityKey, trustedBindingDigests: [] })
|
|
60
|
+
|
|
61
|
+
beforeAll(async () => {
|
|
62
|
+
const inspectorKey = managedParties(config).member('inspector-7')
|
|
63
|
+
first = await openPlatform({ config, mode: 'test', log: () => {}, lifecyclePolicy: { authorityResolver: (q) => ({
|
|
64
|
+
status: q.issuer === inspectorKey.did && q.issuerKey === inspectorKey.identityKey && [passportId, otherId].includes(q.passportId) && q.purpose === 'claim' && q.eventTime === '2026-03-02T08:00:00.000Z' && q.role === 'observer' ? 'supported' : 'unsupported',
|
|
65
|
+
}) } })
|
|
66
|
+
second = await openPlatform({ config, mode: 'test', log: () => {} })
|
|
67
|
+
const brand = first.parties.brand(brandId)
|
|
68
|
+
await first.store.saveBrand({ id: brandId, name: 'Portable brand', identityKey: brand.identityKey, did: brand.did, createdAt: '2026-03-01T00:00:00.000Z' })
|
|
69
|
+
passportId = mintPassportId(policy, '100000201', 'PORT-0001')
|
|
70
|
+
otherId = mintPassportId(policy, '100000202', 'PORT-0002')
|
|
71
|
+
const payload = samplePayload('general@2', true)
|
|
72
|
+
await first.writer.issue({ brandId, brand, passportId, profile: 'general@2', payload, ownerFields: { serviceNotes: 'first revision' } })
|
|
73
|
+
await first.writer.update({ record: (await first.store.getPassport(passportId))!, actor: brand, payload: { ...payload, careNote: 'revised' }, ownerFields: { serviceNotes: 'second revision' } })
|
|
74
|
+
// The hand-on: an offer, its acceptance by claim code, and a TRANSFER that commits to the acceptance record.
|
|
75
|
+
const offered = await first.custody.offer({ record: (await first.store.getPassport(passportId))!, holder: brand, terms: { word: 'Passed on' } })
|
|
76
|
+
claimCode = offered.claimCode!
|
|
77
|
+
await first.custody.accept({ requestId: offered.offer.requestId, claimCode })
|
|
78
|
+
await first.writer.issue({ brandId, brand, passportId: otherId, profile: 'general@2', payload, ownerFields: {} })
|
|
79
|
+
// A historical native claim, as this application kept one before it moved to EPCIS lifecycle claims.
|
|
80
|
+
const inspector = first.parties.member('inspector-7')
|
|
81
|
+
const tip = (await first.store.getPassport(passportId))!.states.at(-1)!
|
|
82
|
+
const historical = await signLifecycleClaim({ claimFormat: 'dpp-lifecycle-v1', passportId, recordId: `${tip.txid}:${tip.outputIndex}`, eventType: 'Disposition', timestamp: '2026-03-01T00:00:00Z', issuer: inspector.did, issuerKeyId: 'inspector-7', profile: 'general', profile_version: 2 }, inspector.wallet)
|
|
83
|
+
await first.store.saveClaim({ id: 'claim-historical-portable', passportId, issuer: historical.issuer, issuedBy: inspector.name, claim: historical, createdAt: historical.timestamp })
|
|
84
|
+
// An EPCIS lifecycle claim that binds both passports: carried once, as its exact bytes.
|
|
85
|
+
const event = { type: 'ObjectEvent', eventID: 'urn:uuid:6c000000-0000-4000-8000-00000000e001', eventTime: '2026-03-02T08:00:00.000Z', eventTimeZoneOffset: '+00:00', epcList: [passportId, otherId], action: 'OBSERVE', bizStep: 'inspecting', disposition: 'conformant' }
|
|
86
|
+
lifecycleClaim = await first.claims.issue({ event, issuer: inspector, assertedRole: 'observer', expectedPassport: passportId, schemaCheck: eventSchemaCheck(gs1Dir()) })
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
afterAll(async () => {
|
|
90
|
+
await first.close()
|
|
91
|
+
await second.close()
|
|
92
|
+
rmSync(scratch, { recursive: true, force: true })
|
|
93
|
+
})
|
|
94
|
+
|
|
95
|
+
describe('the export of an application', () => {
|
|
96
|
+
it('carries a handed-on passport whole, under one signed manifest, with the index\'s complete export in place of its bounded package', async () => {
|
|
97
|
+
exported = await exportApplication({ platform: first, epcis: exchange(), access: 'authorised-recovery', indexRoute: 'complete' })
|
|
98
|
+
const { manifest, descriptor, files } = exported
|
|
99
|
+
expect(manifest.profiles).not.toContain('managed-custody@3')
|
|
100
|
+
expect(manifest.passportId).toBe(exportScopeId([passportId, otherId]))
|
|
101
|
+
expect(manifest.passportId.startsWith(EXPORT_SCOPE_PREFIX)).toBe(true)
|
|
102
|
+
expect(manifest.signature.signer).toBe(evidencePackageSigner(first.wallet.identityKey, manifest.passportId))
|
|
103
|
+
// It inspects as any evidence package does: its structure, its inventory against the files and the exporter's signature.
|
|
104
|
+
expect(inspectEvidencePackage(manifest, asNumberArrays(files), { expectedSigner: exported.exporter.signer })).toMatchObject({ structureValid: true, inventoryVerified: true, signatureValid: true, failures: [], recoveryBackup: true })
|
|
105
|
+
expect(descriptor).toMatchObject({ access: 'authorised-recovery', selection: 'all-passports', profiles: { carried: [], named: ['general@2'] }, epcis: { scopes: [], reason: 'the exchange holds no source scope' }, records: { brands: 1, offers: 1, claims: 2 } })
|
|
106
|
+
expect(manifest.completeness.withheld).toContain('profile general@2 defined-by-the-profiles-package')
|
|
107
|
+
const handedOn = descriptor.passports.find((passport) => passport.passportId === passportId)!
|
|
108
|
+
expect(handedOn).toMatchObject({ profile: 'general@2', states: 3, acceptanceRecords: 1, claims: 2, index: { form: 'export-parts', parts: 1, states: 3 } })
|
|
109
|
+
expect(descriptor.passports.find((passport) => passport.passportId === otherId)!).toMatchObject({ claims: 1, index: { form: 'export-parts', states: 1 } })
|
|
110
|
+
// The EPCIS lifecycle claim binds both passports and is carried once: its record, and its exact signed bytes beside it.
|
|
111
|
+
const claimFiles = manifest.inventory.filter((entry) => entry.path.startsWith('application/lifecycle-claims/'))
|
|
112
|
+
expect(claimFiles).toEqual([expect.objectContaining({ category: 'native-claims', mediaType: 'application/json', representation: 'dpp-epcis-lifecycle-json@1', represents: lifecycleClaim.attestationId })])
|
|
113
|
+
expect(new TextDecoder().decode(files.get(claimFiles[0]!.path)!)).toBe(lifecycleClaim.bytes)
|
|
114
|
+
expect(manifest.inventory.filter((entry) => entry.path.startsWith('application/claims/'))).toHaveLength(2)
|
|
115
|
+
|
|
116
|
+
// The acceptance record is an authority entry, in the form a reader of any evidence package finds it.
|
|
117
|
+
const record = (await first.store.getPassport(passportId))!
|
|
118
|
+
const commitment = acceptanceCommitment(record.acceptanceRecords[0]!)
|
|
119
|
+
const carried = acceptanceRecordsInPackage(manifest, asNumberArrays(files))
|
|
120
|
+
expect(carried).toHaveLength(1)
|
|
121
|
+
expect(carried[0]).toMatchObject({ path: `${passportFolder(passportId)}/authority/${commitment}.json`, represents: `sha256:${commitment}` })
|
|
122
|
+
expect(carried[0]!.failure).toBeUndefined()
|
|
123
|
+
// The index's own signature on each part is carried and still verifies under the index's exporter key.
|
|
124
|
+
const coverage = JSON.parse(new TextDecoder().decode(files.get(`${passportFolder(passportId)}/index/part-1/coverage.json`)!)) as { final: boolean; nextCursor?: unknown; signature: { signer: string } }
|
|
125
|
+
expect(coverage.final).toBe(true)
|
|
126
|
+
expect(coverage).not.toHaveProperty('nextCursor')
|
|
127
|
+
expect(coverage.signature.signer).toBe(evidencePackageSigner(first.devIndex!.exporterIdentityKey, passportId))
|
|
128
|
+
// No key, and no claim code: only the digest the offer was accepted against.
|
|
129
|
+
const everything = Buffer.concat([...files.values()].map((bytes) => Buffer.from(bytes)))
|
|
130
|
+
expect(everything.includes(Buffer.from(claimCode))).toBe(false)
|
|
131
|
+
expect(everything.includes(Buffer.from('11'.repeat(32)))).toBe(false)
|
|
132
|
+
expect(everything.includes(Buffer.from(config.brandRootSecret))).toBe(false)
|
|
133
|
+
})
|
|
134
|
+
|
|
135
|
+
it('carries the bounded package by default, and a selection of passports under a name of its own', async () => {
|
|
136
|
+
const one = await exportApplication({ platform: first, epcis: exchange(), access: 'authorised-recovery', passportIds: [otherId] })
|
|
137
|
+
// The second passport has no offer of its own, and the EPCIS lifecycle claim that binds it travels with it.
|
|
138
|
+
expect(one.descriptor).toMatchObject({ selection: 'listed-passports', records: { brands: 1, offers: 0, claims: 1 } })
|
|
139
|
+
expect(one.descriptor.passports).toHaveLength(1)
|
|
140
|
+
expect(one.descriptor.passports[0]!.index).toMatchObject({ form: 'package', states: 1, exporter: first.devIndex!.exporterIdentityKey })
|
|
141
|
+
expect(one.manifest.passportId).toBe(exportScopeId([otherId]))
|
|
142
|
+
expect(one.manifest.passportId).not.toBe(exported.manifest.passportId)
|
|
143
|
+
// A signature made for one selection does not verify as the signature of another.
|
|
144
|
+
expect(inspectEvidencePackage({ ...one.manifest, passportId: exported.manifest.passportId }, asNumberArrays(one.files)).signatureValid).toBe(false)
|
|
145
|
+
const unknown = await refusal(exportApplication({ platform: first, epcis: exchange(), access: 'authorised-recovery', passportIds: ['https://passports.example.com/01/09521000002039/21/NOT-HELD'] }))
|
|
146
|
+
expect(unknown.code).toBe('passport-unknown')
|
|
147
|
+
})
|
|
148
|
+
|
|
149
|
+
it('gives a public form with no journal, no offer, no claim and nothing of the exchange unless a source is named', async () => {
|
|
150
|
+
const open = await exportApplication({ platform: first, epcis: exchange(), access: 'public-evidence' })
|
|
151
|
+
expect(open.manifest.disclosure).toEqual({ scope: 'public', recoveryBackup: false })
|
|
152
|
+
expect(open.descriptor).toMatchObject({ access: 'public-evidence', records: { brands: 0, offers: 0, claims: 0 }, epcis: { scopes: [], reason: 'no source scope was named as one a public export may carry' } })
|
|
153
|
+
// The index's own evidence carries its publisher policy under authority, which is public. This application's acceptance records sit beside the journal, and are not here.
|
|
154
|
+
expect([...open.files.keys()].filter((path) => path.endsWith('/journal.json') || /^passports\/[0-9a-f]{64}\/authority\//.test(path) || path.startsWith('application/offers/') || path.startsWith('application/claims/') || path.startsWith('application/brands/'))).toEqual([])
|
|
155
|
+
expect(open.manifest.completeness.withheld).toEqual(expect.arrayContaining(['application passport-journals not-public', 'application brands-offers-claims not-public', 'epcis-exchange every-source-scope not-public']))
|
|
156
|
+
// The sealed owner tiers are in no file of it, in the journal's form or as bytes.
|
|
157
|
+
const everything = Buffer.concat([...open.files.values()].map((bytes) => Buffer.from(bytes)))
|
|
158
|
+
for (const state of (await first.store.getPassport(passportId))!.states) {
|
|
159
|
+
expect(everything.includes(Buffer.from(state.ownerTier!.ciphertext))).toBe(false)
|
|
160
|
+
expect(everything.includes(Buffer.from(state.ownerTier!.ciphertext, 'base64'))).toBe(false)
|
|
161
|
+
}
|
|
162
|
+
// A restore refuses it by name.
|
|
163
|
+
expect((await refusal(verifyApplicationPackage({ manifestText: JSON.stringify(open.manifest), files: open.files }, trust(first)))).code).toBe('not-a-recovery-package')
|
|
164
|
+
})
|
|
165
|
+
|
|
166
|
+
it('accounts for two completed handovers and keeps a signed, unexecuted offer recoverable', async () => {
|
|
167
|
+
const source = await openPlatform({ config, mode: 'test', log: () => {} })
|
|
168
|
+
try {
|
|
169
|
+
const id = mintPassportId(policy, '100000204', 'PORT-HANDOVERS')
|
|
170
|
+
const brand = source.parties.brand(brandId)
|
|
171
|
+
await source.writer.issue({ brandId, brand, passportId: id, profile: 'general@2', payload: samplePayload('general@2', true) })
|
|
172
|
+
async function offer() {
|
|
173
|
+
const record = (await source.store.getPassport(id))!
|
|
174
|
+
const created = await source.custody.offer({ record, holder: source.custody.holderOf(record), terms: { word: 'Handed on' } })
|
|
175
|
+
return { requestId: created.offer.requestId, claimCode: created.claimCode! }
|
|
176
|
+
}
|
|
177
|
+
const firstTransfer = await source.custody.accept(await offer())
|
|
178
|
+
const secondTransfer = await source.custody.accept(await offer())
|
|
179
|
+
const completed = [firstTransfer.record, secondTransfer.record]
|
|
180
|
+
const pending = await offer()
|
|
181
|
+
vi.spyOn(source.writer, 'transfer').mockRejectedValueOnce(new Error('wallet offline'))
|
|
182
|
+
await expect(source.custody.accept(pending)).rejects.toThrow('wallet offline')
|
|
183
|
+
const pendingOffer = (await source.store.getOffer(pending.requestId))!
|
|
184
|
+
const signed = pendingOffer.record!
|
|
185
|
+
|
|
186
|
+
const selected = { platform: source, epcis: exchange(), custodyProfile: 'managed-custody@3' as const }
|
|
187
|
+
const recovery = await exportApplication({ ...selected, access: 'authorised-recovery' })
|
|
188
|
+
expect(recovery.manifest.profiles).toContain('managed-custody@3')
|
|
189
|
+
const verified = await verifyApplicationPackage({ manifestText: JSON.stringify(recovery.manifest), files: recovery.files }, trust(source))
|
|
190
|
+
expect(verified.offers.find(item => item.requestId === pending.requestId)).toMatchObject({ status: 'accepted', record: signed })
|
|
191
|
+
const replacement = await openPlatform({ config, mode: 'test', log: () => {} })
|
|
192
|
+
try {
|
|
193
|
+
await restoreApplication({ verified, platform: replacement, epcis: exchange(), rebuildIndex: true })
|
|
194
|
+
const retried = await replacement.custody.accept(pending)
|
|
195
|
+
expect(retried.record).toEqual(signed)
|
|
196
|
+
expect((await replacement.custody.accept(pending)).transferTxid).toBe(retried.transferTxid)
|
|
197
|
+
const after = await exportApplication({ ...selected, platform: replacement, access: 'authorised-recovery' })
|
|
198
|
+
expect(acceptanceRecordsInPackage(after.manifest, asNumberArrays(after.files)).map(item => item.record)).toContainEqual(signed)
|
|
199
|
+
expect((await replacement.store.getPassport(id))!.acceptanceRecords).toEqual([...completed, signed])
|
|
200
|
+
} finally {
|
|
201
|
+
await replacement.close()
|
|
202
|
+
}
|
|
203
|
+
const authority = acceptanceRecordsInPackage(recovery.manifest, asNumberArrays(recovery.files))
|
|
204
|
+
expect(authority).toHaveLength(completed.length)
|
|
205
|
+
for (const record of completed) {
|
|
206
|
+
const path = `${passportFolder(id)}/authority/${acceptanceCommitment(record)}.json`
|
|
207
|
+
expect(Buffer.from(recovery.files.get(path)!).toString('utf8')).toBe(stableJson(record))
|
|
208
|
+
expect(authority.filter(item => item.represents === `sha256:${acceptanceCommitment(record)}`)).toEqual([
|
|
209
|
+
{ path, represents: `sha256:${acceptanceCommitment(record)}`, record },
|
|
210
|
+
])
|
|
211
|
+
}
|
|
212
|
+
const open = await exportApplication({ ...selected, access: 'public-evidence' })
|
|
213
|
+
expect(open.manifest.profiles).toContain('managed-custody@3')
|
|
214
|
+
const publicReading = JSON.parse(Buffer.from(open.files.get(`${passportFolder(id)}/reading.json`)!).toString('utf8'))
|
|
215
|
+
expect(publicReading.checks).toContainEqual({ name: 'evidenceAvailability', status: 'unknown', reasonCode: 'referenced-artefact-unavailable' })
|
|
216
|
+
expect(acceptanceRecordsInPackage(open.manifest, asNumberArrays(open.files))).toEqual([])
|
|
217
|
+
for (const record of completed) {
|
|
218
|
+
const reference = `acceptance:sha256:${acceptanceCommitment(record)}`
|
|
219
|
+
expect(recovery.manifest.completeness.absent).not.toContain(reference)
|
|
220
|
+
expect(open.manifest.completeness.absent).not.toContain(reference)
|
|
221
|
+
expect(open.manifest.completeness.withheld).toContain(`${reference} not-public`)
|
|
222
|
+
}
|
|
223
|
+
const publicBytes = Buffer.concat([Buffer.from(JSON.stringify(open.manifest)), ...Array.from(open.files.values(), bytes => Buffer.from(bytes))])
|
|
224
|
+
for (const secret of [pending.requestId, pending.claimCode, acceptanceCommitment(signed), ...[...completed, signed].map(record => record.signature)]) {
|
|
225
|
+
expect(publicBytes.includes(Buffer.from(secret))).toBe(false)
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
// The journal may hold the only copy of the pending acceptance.
|
|
229
|
+
const before = (await source.store.getPassport(id))!
|
|
230
|
+
const { record: _signed, ...pendingWithoutRecord } = pendingOffer
|
|
231
|
+
await source.store.saveOffer(pendingWithoutRecord)
|
|
232
|
+
await source.store.savePassport({ ...before, acceptanceRecords: [...before.acceptanceRecords, signed] })
|
|
233
|
+
const read = source.read.bind(source)
|
|
234
|
+
const disclose = vi.spyOn(source, 'read').mockImplementationOnce(async (...args) => {
|
|
235
|
+
const reading = await read(...args)
|
|
236
|
+
return { ...reading, checks: [...reading.checks, { name: 'unavailable', label: 'Detail', status: acceptanceCommitment(signed) }] }
|
|
237
|
+
})
|
|
238
|
+
try {
|
|
239
|
+
expect((await refusal(exportApplication({ ...selected, access: 'public-evidence' }))).code).toBe('export-unsound')
|
|
240
|
+
} finally {
|
|
241
|
+
disclose.mockRestore()
|
|
242
|
+
await source.store.saveOffer(pendingOffer)
|
|
243
|
+
await source.store.savePassport(before)
|
|
244
|
+
}
|
|
245
|
+
|
|
246
|
+
// The package signature covers the exporting store's bytes. The acceptance must separately verify for its offer.
|
|
247
|
+
for (const change of [{ record: firstTransfer.record }, { record: { ...signed, signature: '00' } }, { terms: { word: 'Different terms' } }]) {
|
|
248
|
+
await source.store.saveOffer({ ...pendingOffer, ...change })
|
|
249
|
+
const damaged = await exportApplication({ platform: source, epcis: exchange(), access: 'authorised-recovery' })
|
|
250
|
+
const result = await refusal(verifyApplicationPackage({ manifestText: JSON.stringify(damaged.manifest), files: damaged.files }, trust(source)))
|
|
251
|
+
expect(result).toMatchObject({ code: 'records-inconsistent', data: { requestId: pending.requestId } })
|
|
252
|
+
}
|
|
253
|
+
await source.store.saveOffer(pendingOffer)
|
|
254
|
+
|
|
255
|
+
// A partial store holds only the first acceptance in its offer and has lost the second altogether.
|
|
256
|
+
const journal = (await source.store.getPassport(id))!
|
|
257
|
+
await source.store.savePassport({ ...journal, acceptanceRecords: [] })
|
|
258
|
+
const { record: lost, ...secondOffer } = (await source.store.getOffer(secondTransfer.record.requestId))!
|
|
259
|
+
await source.store.saveOffer(secondOffer)
|
|
260
|
+
const partial = await exportApplication({ ...selected, access: 'public-evidence' })
|
|
261
|
+
const retained = `acceptance:sha256:${acceptanceCommitment(firstTransfer.record)}`
|
|
262
|
+
const missing = `acceptance:sha256:${acceptanceCommitment(lost!)}`
|
|
263
|
+
expect(partial.manifest.completeness.withheld).toContain(`${retained} not-public`)
|
|
264
|
+
expect(partial.manifest.completeness.absent).not.toContain(retained)
|
|
265
|
+
expect(partial.manifest.completeness.absent).toContain(missing)
|
|
266
|
+
expect(partial.manifest.completeness.withheld).not.toContain(`${missing} not-public`)
|
|
267
|
+
|
|
268
|
+
// The index can be unavailable. The source journal still establishes both completed handovers.
|
|
269
|
+
const index = vi.spyOn(source.index, 'evidencePackage').mockResolvedValue({ absent: 'not-held', detail: 'offline' })
|
|
270
|
+
const partialRecovery = await exportApplication({ ...selected, access: 'authorised-recovery' })
|
|
271
|
+
expect(partialRecovery.manifest.completeness.absent).toContain(missing)
|
|
272
|
+
expect(partialRecovery.manifest.completeness.absent).not.toContain(retained)
|
|
273
|
+
expect(acceptanceRecordsInPackage(partialRecovery.manifest, asNumberArrays(partialRecovery.files)).map(item => item.record)).toEqual([firstTransfer.record])
|
|
274
|
+
expect(partialRecovery.descriptor.passports[0]!.acceptanceRecords).toBe(1)
|
|
275
|
+
const copy = JSON.parse(Buffer.from(partialRecovery.files.get(`${passportFolder(id)}/journal.json`)!).toString('utf8'))
|
|
276
|
+
expect(copy.acceptanceRecords).toEqual([firstTransfer.record])
|
|
277
|
+
expect((await source.store.getPassport(id))!.acceptanceRecords).toEqual([])
|
|
278
|
+
const recovered = await verifyApplicationPackage({ manifestText: JSON.stringify(partialRecovery.manifest), files: partialRecovery.files }, trust(source))
|
|
279
|
+
expect(recovered.journals[0]!.acceptanceRecords).toEqual([firstTransfer.record])
|
|
280
|
+
index.mockRestore()
|
|
281
|
+
|
|
282
|
+
// An index admission and a retained acceptance cannot answer an interrupted send.
|
|
283
|
+
const secondOfferAccepted = { ...secondOffer, status: 'accepted' as const }
|
|
284
|
+
delete secondOfferAccepted.transferTxid
|
|
285
|
+
await source.store.saveOffer(secondOfferAccepted)
|
|
286
|
+
await source.store.savePassport({ ...journal, states: journal.states.map(entry =>
|
|
287
|
+
entry.txid === secondTransfer.transferTxid ? { ...entry, network: 'unanswered', acceptance: lost } : entry) })
|
|
288
|
+
const interrupted = await exportApplication({ ...selected, access: 'authorised-recovery' })
|
|
289
|
+
expect(acceptanceRecordsInPackage(interrupted.manifest, asNumberArrays(interrupted.files)).map(item => item.record)).toEqual([firstTransfer.record])
|
|
290
|
+
expect(interrupted.manifest.completeness.absent).not.toContain(missing)
|
|
291
|
+
const offered = interrupted.manifest.inventory.find(entry => entry.represents === secondOffer.requestId)!
|
|
292
|
+
expect(JSON.parse(Buffer.from(interrupted.files.get(offered.path)!).toString('utf8')).record).toEqual(lost)
|
|
293
|
+
expect((await source.store.getOffer(secondOffer.requestId))!.record).toBeUndefined()
|
|
294
|
+
|
|
295
|
+
// A pending send cannot be resumed without the signed record.
|
|
296
|
+
await source.store.savePassport({ ...journal, acceptanceRecords: [firstTransfer.record], states: journal.states.map(entry =>
|
|
297
|
+
entry.txid === secondTransfer.transferTxid ? { ...entry, network: 'unanswered' } : entry) })
|
|
298
|
+
expect(await refusal(exportApplication({ ...selected, access: 'authorised-recovery' }))).toMatchObject({ code: 'records-inconsistent' })
|
|
299
|
+
} finally {
|
|
300
|
+
await source.close()
|
|
301
|
+
}
|
|
302
|
+
})
|
|
303
|
+
|
|
304
|
+
it('requires a public index package without custody records before using it in a public export', async () => {
|
|
305
|
+
const result = await first.index.evidencePackage(passportId)
|
|
306
|
+
if (!('envelope' in result)) throw new Error('the index gave no package')
|
|
307
|
+
const original = result.envelope.manifest as EvidencePackageManifest
|
|
308
|
+
const key = PrivateKey.fromRandom()
|
|
309
|
+
const id = key.toPublicKey().toString()
|
|
310
|
+
const signingKey = evidencePackageSigningKey(key, passportId)
|
|
311
|
+
const signing = { sign: (preimage: number[]) => signingKey.sign(preimage).toDER() as number[] }
|
|
312
|
+
const identity = vi.spyOn(first.index, 'exporterIdentityKey').mockResolvedValue(id)
|
|
313
|
+
const fetchPackage = vi.spyOn(first.index, 'evidencePackage')
|
|
314
|
+
try {
|
|
315
|
+
const record = (await first.store.getPassport(passportId))!.acceptanceRecords[0]!
|
|
316
|
+
const bytes = Buffer.from(JSON.stringify(record))
|
|
317
|
+
const path = 'authority/acceptance.json'
|
|
318
|
+
const entry = { path, category: 'authority' as const, mediaType: 'application/json', byteLength: bytes.length, sha256: createHash('sha256').update(bytes).digest('hex'), represents: `sha256:${acceptanceCommitment(record)}`, representation: record.acceptanceFormat }
|
|
319
|
+
for (const includeRecord of [false, true]) {
|
|
320
|
+
const manifest = await signEvidenceManifest({
|
|
321
|
+
...original,
|
|
322
|
+
exporter: { ...original.exporter, id },
|
|
323
|
+
disclosure: includeRecord ? original.disclosure : { scope: 'all-tiers', recoveryBackup: true },
|
|
324
|
+
inventory: includeRecord ? [...original.inventory, entry] : original.inventory,
|
|
325
|
+
signature: { suite: 'bsv-ecdsa-der', signer: signingKey.toPublicKey().toString() },
|
|
326
|
+
}, signing)
|
|
327
|
+
const files = includeRecord ? { ...result.envelope.files, [path]: bytes.toString('base64') } : result.envelope.files
|
|
328
|
+
fetchPackage.mockResolvedValue({ envelope: { manifest, files } })
|
|
329
|
+
const problem = await refusal(exportApplication({ platform: first, epcis: exchange(), access: 'public-evidence', passportIds: [passportId] }))
|
|
330
|
+
expect(problem.code).toBe('index-evidence-refused')
|
|
331
|
+
if (includeRecord) {
|
|
332
|
+
const scope = { platform: first, epcis: exchange(), access: 'authorised-recovery' as const, passportIds: [passportId] }
|
|
333
|
+
const selected = { ...scope, custodyProfile: 'managed-custody@3' as const }
|
|
334
|
+
const indexFile = `${passportFolder(passportId)}/index/${path}`
|
|
335
|
+
const journal = (await first.store.getPassport(passportId))!
|
|
336
|
+
const offer = (await first.store.getOffer(record.requestId))!
|
|
337
|
+
try {
|
|
338
|
+
for (const nestedOnly of [false, true]) {
|
|
339
|
+
if (nestedOnly) {
|
|
340
|
+
await first.store.savePassport({ ...journal, acceptanceRecords: [] })
|
|
341
|
+
const { record: _record, ...withoutAcceptance } = offer
|
|
342
|
+
await first.store.saveOffer(withoutAcceptance)
|
|
343
|
+
}
|
|
344
|
+
const recovery = await exportApplication(selected)
|
|
345
|
+
expect(recovery.manifest.inventory.find(entry => entry.path === indexFile)).toMatchObject({ category: 'authority', representation: 'dpp-nested-authority@1' })
|
|
346
|
+
expect(Buffer.from(recovery.files.get(indexFile)!)).toEqual(bytes)
|
|
347
|
+
expect(JSON.parse(Buffer.from(recovery.files.get(`${passportFolder(passportId)}/index/manifest.json`)!).toString())).toEqual(manifest)
|
|
348
|
+
expect(acceptanceRecordsInPackage(recovery.manifest, asNumberArrays(recovery.files)).map(entry => entry.record)).toEqual([record])
|
|
349
|
+
const recovered = await verifyApplicationPackage({ manifestText: JSON.stringify(recovery.manifest), files: recovery.files }, { ...trust(first), indexExporterKey: id })
|
|
350
|
+
expect(recovered.journals[0]!.acceptanceRecords).toEqual([record])
|
|
351
|
+
expect(recovered.offers[0]!.record).toEqual(record)
|
|
352
|
+
}
|
|
353
|
+
} finally {
|
|
354
|
+
await first.store.savePassport(journal)
|
|
355
|
+
await first.store.saveOffer(offer)
|
|
356
|
+
}
|
|
357
|
+
const earlier = await exportApplication(scope)
|
|
358
|
+
expect(earlier.manifest.inventory.find(entry => entry.path === indexFile)?.representation).toBe(record.acceptanceFormat)
|
|
359
|
+
|
|
360
|
+
// The index signature authenticates the package, independently of the custodian's acceptance.
|
|
361
|
+
const broken = { ...record, signature: '00' }
|
|
362
|
+
const brokenBytes = Buffer.from(JSON.stringify(broken))
|
|
363
|
+
const brokenEntry = { ...entry, byteLength: brokenBytes.length, sha256: createHash('sha256').update(brokenBytes).digest('hex'), represents: `sha256:${acceptanceCommitment(broken)}` }
|
|
364
|
+
const damaged = await signEvidenceManifest({ ...manifest, inventory: [...original.inventory, brokenEntry] }, signing)
|
|
365
|
+
fetchPackage.mockResolvedValue({ envelope: { manifest: damaged, files: { ...files, [path]: brokenBytes.toString('base64') } } })
|
|
366
|
+
expect((await refusal(exportApplication(selected))).code).toBe('index-evidence-refused')
|
|
367
|
+
}
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
// A signed proof can carry the transfer without a separate raw transaction file.
|
|
371
|
+
const inventory = original.inventory.filter(entry => entry.category !== 'transactions')
|
|
372
|
+
const proofOnly = await signEvidenceManifest({
|
|
373
|
+
...original, inventory, exporter: { ...original.exporter, id },
|
|
374
|
+
signature: { suite: 'bsv-ecdsa-der', signer: signingKey.toPublicKey().toString() },
|
|
375
|
+
}, signing)
|
|
376
|
+
fetchPackage.mockResolvedValue({ envelope: { manifest: proofOnly, files: Object.fromEntries(inventory.map(entry => [entry.path, result.envelope.files[entry.path]!])) } })
|
|
377
|
+
const publicProofs = await exportApplication({ platform: first, epcis: exchange(), access: 'public-evidence', custodyProfile: 'managed-custody@3', passportIds: [passportId] })
|
|
378
|
+
expect(publicProofs.manifest.completeness.withheld).toContain(`acceptance:sha256:${acceptanceCommitment(record)} not-public`)
|
|
379
|
+
} finally {
|
|
380
|
+
fetchPackage.mockRestore()
|
|
381
|
+
identity.mockRestore()
|
|
382
|
+
}
|
|
383
|
+
})
|
|
384
|
+
|
|
385
|
+
it('refuses to hand over an export that holds a secret this deployment was configured with', async () => {
|
|
386
|
+
const secret = 'REGISTRY-TOKEN-CANARY-71D0E4B2'
|
|
387
|
+
const leaky = await openPlatform({ config: loadConfig({ ...settings, REGISTRY_URL: 'https://registry.example', REGISTRY_TOKEN: secret }), mode: 'test', log: () => {} })
|
|
388
|
+
try {
|
|
389
|
+
const brand = leaky.parties.brand(brandId)
|
|
390
|
+
// The secret reached a record: here, a brand somebody named after it.
|
|
391
|
+
await leaky.store.saveBrand({ id: brandId, name: `Brand ${secret}`, identityKey: brand.identityKey, did: brand.did, createdAt: '2026-03-01T00:00:00.000Z' })
|
|
392
|
+
await leaky.writer.issue({ brandId, brand, passportId: mintPassportId(policy, '100000203', 'PORT-LEAK-1'), profile: 'general@2', payload: samplePayload('general@2', true), ownerFields: {} })
|
|
393
|
+
const refused = await refusal(exportApplication({ platform: leaky, epcis: exchange(), access: 'authorised-recovery' }))
|
|
394
|
+
expect(refused.code).toBe('secret-in-export')
|
|
395
|
+
expect(refused.message).toMatch(/application\/brands\/[0-9a-f]{64}\.json holds a secret/)
|
|
396
|
+
expect(refused.message).not.toContain(secret)
|
|
397
|
+
} finally {
|
|
398
|
+
await leaky.close()
|
|
399
|
+
}
|
|
400
|
+
})
|
|
401
|
+
})
|
|
402
|
+
|
|
403
|
+
describe('the restore of an application', () => {
|
|
404
|
+
let folder: string
|
|
405
|
+
let report: RestoreReport
|
|
406
|
+
|
|
407
|
+
it('rebuilds delivery receipts at a replacement index and retries a retained proof without the source wallet', async () => {
|
|
408
|
+
const source = await openPlatform({ config, mode: 'test', log: () => {} })
|
|
409
|
+
const destination = await openPlatform({ config, mode: 'test', log: () => {} })
|
|
410
|
+
try {
|
|
411
|
+
const id = mintPassportId(policy, '100000205', 'PORT-PROOF')
|
|
412
|
+
const brand = source.parties.brand(brandId)
|
|
413
|
+
const issued = await source.writer.issue({ brandId, brand, passportId: id, profile: 'general@2', payload: samplePayload('general@2', true) })
|
|
414
|
+
const { txid } = issued.entry
|
|
415
|
+
await source.writer.prove(issued.record, txid)
|
|
416
|
+
const proven = (await source.store.getPassport(id))!
|
|
417
|
+
const state = proven.states[0]!
|
|
418
|
+
expect(state).toMatchObject({ index: 'admitted', proofPushed: true, sentBeef: issued.entry.beef })
|
|
419
|
+
const packageData = await exportApplication({ platform: source, epcis: exchange(), access: 'authorised-recovery' })
|
|
420
|
+
const verified = await verifyApplicationPackage({ manifestText: JSON.stringify(packageData.manifest), files: packageData.files }, trust(source))
|
|
421
|
+
const restore = (rebuildIndex: boolean) => restoreApplication({ verified, platform: destination, epcis: exchange(), rebuildIndex })
|
|
422
|
+
await restore(false)
|
|
423
|
+
const waiting = (await destination.store.getPassport(id))!.states[0]!
|
|
424
|
+
expect(waiting).toMatchObject({ index: 'not-asked', proof: state.proof, sentBeef: state.sentBeef })
|
|
425
|
+
expect(waiting.proofPushed).not.toBe(true)
|
|
426
|
+
expect(verified.journals[0]!.states[0]!.proofPushed).toBe(true)
|
|
427
|
+
|
|
428
|
+
// A repeat can encounter receipts copied by an older restore, even on a fresh index.
|
|
429
|
+
await destination.store.savePassport(proven)
|
|
430
|
+
const walletProof = vi.spyOn(destination.wallet.adapter, 'merklePathFor')
|
|
431
|
+
const send = vi.spyOn(destination.wallet.adapter, 'send')
|
|
432
|
+
const push = vi.spyOn(destination.index, 'pushProof').mockResolvedValueOnce({ ok: false, detail: 'callback unavailable' })
|
|
433
|
+
const tried = await restore(true)
|
|
434
|
+
expect(tried.index).toMatchObject({ proofsApplied: 0, proofsNotApplied: [{ passportId: id, txid, detail: 'callback unavailable' }] })
|
|
435
|
+
expect(tried.attention).toEqual(expect.arrayContaining([expect.stringContaining('callback unavailable')]))
|
|
436
|
+
expect(push.mock.calls.map(([id]) => id)).toEqual([txid])
|
|
437
|
+
expect((await destination.store.getPassport(id))!.states[0]!.proofPushed).not.toBe(true)
|
|
438
|
+
expect((await destination.index.lineage(id))[0]!.merklePath).toBeUndefined()
|
|
439
|
+
|
|
440
|
+
await runDuties({ store: destination.store, writer: destination.writer, index: destination.index })
|
|
441
|
+
expect((await destination.index.lineage(id))[0]!.merklePath?.toHex()).toBe(state.proof!.merklePath)
|
|
442
|
+
expect((await destination.store.getPassport(id))!.states[0]!.proofPushed).toBe(true)
|
|
443
|
+
expect((await restore(true)).index).toMatchObject({ duplicate: 1, proofsApplied: 1, proofsNotApplied: [] })
|
|
444
|
+
expect(push.mock.calls.map(([id, path]) => [id, path.toHex()])).toEqual(Array(3).fill([txid, state.proof!.merklePath]))
|
|
445
|
+
expect(walletProof).not.toHaveBeenCalled()
|
|
446
|
+
expect(send).not.toHaveBeenCalled()
|
|
447
|
+
|
|
448
|
+
const fresh = await openPlatform({ config, mode: 'test', log: () => {} })
|
|
449
|
+
try {
|
|
450
|
+
const rebuilt = await restoreApplication({ verified, platform: fresh, epcis: exchange(), rebuildIndex: true })
|
|
451
|
+
expect(rebuilt.index).toMatchObject({ admitted: 1, proofsApplied: 1, proofsNotApplied: [] })
|
|
452
|
+
expect((await fresh.index.lineage(id))[0]!.merklePath?.toHex()).toBe(state.proof!.merklePath)
|
|
453
|
+
} finally {
|
|
454
|
+
await fresh.close()
|
|
455
|
+
}
|
|
456
|
+
} finally {
|
|
457
|
+
await source.close()
|
|
458
|
+
await destination.close()
|
|
459
|
+
}
|
|
460
|
+
})
|
|
461
|
+
|
|
462
|
+
it('reads a package back from its folder and restores it: every state is given to the index, and the passports read as they did', async () => {
|
|
463
|
+
folder = join(scratch, 'export')
|
|
464
|
+
writePackageFolder(folder, exported.manifest, exported.files)
|
|
465
|
+
// An export is never written over anything.
|
|
466
|
+
expect(() => writePackageFolder(folder, exported.manifest, exported.files)).toThrow(/already holds files/)
|
|
467
|
+
const verified = await verifyApplicationPackage(readPackageFolder(folder), trust(first))
|
|
468
|
+
expect(verified.journals.map((record) => record.passportId).sort()).toEqual([passportId, otherId].sort())
|
|
469
|
+
expect(verified.offers).toHaveLength(1)
|
|
470
|
+
expect(verified.claims).toHaveLength(2)
|
|
471
|
+
expect(await second.store.listPassports()).toEqual([])
|
|
472
|
+
|
|
473
|
+
report = await restoreApplication({ verified, platform: second, epcis: exchange(), rebuildIndex: true })
|
|
474
|
+
expect(report).toMatchObject({
|
|
475
|
+
outcome: 'restored',
|
|
476
|
+
passports: { unchanged: [] },
|
|
477
|
+
records: { brands: { written: 1, unchanged: 0 }, offers: { written: 1, unchanged: 0 }, claims: { written: 2, unchanged: 0 } },
|
|
478
|
+
profiles: { resolver: 'package', filesWritten: 0, registered: [], notRegistered: [] },
|
|
479
|
+
index: { rebuilt: true, announced: 4, admitted: 4, duplicate: 0, notAnnounced: [] },
|
|
480
|
+
readings: { compared: 2, same: 2, different: [], notCompared: [] },
|
|
481
|
+
})
|
|
482
|
+
expect(report.epcis).toBeUndefined()
|
|
483
|
+
expect(stableJson(await second.store.getPassport(passportId))).toBe(stableJson(await first.store.getPassport(passportId)))
|
|
484
|
+
expect((await second.index.lineage(passportId)).map((tx) => tx.id('hex'))).toEqual((await first.index.lineage(passportId)).map((tx) => tx.id('hex')))
|
|
485
|
+
expect((await second.read(passportId)).lineage.map((state) => state.op)).toEqual(['ISSUE', 'UPDATE', 'TRANSFER'])
|
|
486
|
+
|
|
487
|
+
// The restored deployment holds the claims as they were and verifies them itself: the EPCIS claim from its exact bytes, binding both passports, and the historical one under its own rules.
|
|
488
|
+
for (const id of [passportId, otherId]) {
|
|
489
|
+
const reading = await readPassportClaims(id, { store: second.store, index: second.index, schemaCheck: eventSchemaCheck(gs1Dir()), ...second.lifecyclePolicy })
|
|
490
|
+
expect(reading.lifecycle[0]?.findings).toMatchObject({ signature: { status: 'pass' }, authority: { status: 'unavailable' } })
|
|
491
|
+
const [claim] = reading.lifecycle
|
|
492
|
+
expect(claim, id).toMatchObject({ attestationId: lifecycleClaim.attestationId, held: true, participation: 'item', foundBy: ['this-application'] })
|
|
493
|
+
expect([claim!.findings!.signature.status, claim!.findings!.eventStructure.status, claim!.findings!.productBinding.status]).toEqual(['pass', 'pass', 'pass'])
|
|
494
|
+
}
|
|
495
|
+
expect((await readPassportClaims(passportId, { store: second.store, index: second.index })).historical).toEqual([expect.objectContaining({ id: 'claim-historical-portable', historical: true, signature: 'verified' })])
|
|
496
|
+
})
|
|
497
|
+
|
|
498
|
+
it('L08: a restore without the original managed keys preserves signed claims and gives the replacement account no physical role', async () => {
|
|
499
|
+
const destination = await openPlatform({ config: { ...config, brandRootSecret: 'another-brand-secret-for-the-restore', managedIdentitySecret: 'another-member-secret-for-the-restore' }, mode: 'test', log: () => {} })
|
|
500
|
+
try {
|
|
501
|
+
const verified = await verifyApplicationPackage(readPackageFolder(folder), trust(first))
|
|
502
|
+
await restoreApplication({ verified, platform: destination, epcis: exchange(), rebuildIndex: false })
|
|
503
|
+
const otherInspector = destination.parties.member('inspector-7')
|
|
504
|
+
expect(otherInspector.did).not.toBe(lifecycleClaim.issuer)
|
|
505
|
+
expect(await destination.store.getBrand(brandId)).toMatchObject({ id: brandId })
|
|
506
|
+
const reading = await readPassportClaims(passportId, { store: destination.store, index: destination.index, ...destination.lifecyclePolicy, schemaCheck: eventSchemaCheck(gs1Dir()) })
|
|
507
|
+
expect(reading.lifecycle.find((v) => v.attestationId === lifecycleClaim.attestationId)?.findings).toMatchObject({ signature: { status: 'pass' }, authority: { status: 'unavailable' }, ownership: { status: 'not-asserted' }, possession: { status: 'not-asserted' } })
|
|
508
|
+
const sign = vi.spyOn(otherInspector.wallet, 'createSignature')
|
|
509
|
+
const save = vi.spyOn(destination.store, 'saveClaim')
|
|
510
|
+
try {
|
|
511
|
+
const { event } = JSON.parse(lifecycleClaim.bytes)
|
|
512
|
+
await expect(destination.claims.issue({ event, issuer: otherInspector, assertedRole: 'observer', expectedPassport: passportId, schemaCheck: eventSchemaCheck(gs1Dir()) })).rejects.toMatchObject({ code: 'authority-unavailable' })
|
|
513
|
+
expect(sign).not.toHaveBeenCalled()
|
|
514
|
+
expect(save).not.toHaveBeenCalled()
|
|
515
|
+
} finally {
|
|
516
|
+
sign.mockRestore()
|
|
517
|
+
save.mockRestore()
|
|
518
|
+
}
|
|
519
|
+
} finally {
|
|
520
|
+
await destination.close()
|
|
521
|
+
}
|
|
522
|
+
})
|
|
523
|
+
|
|
524
|
+
it('changes nothing the second time, and lets the recipient carry on with the claim code they accepted with', async () => {
|
|
525
|
+
const again = await restoreApplication({ verified: await verifyApplicationPackage(readPackageFolder(folder), trust(first)), platform: second, epcis: exchange(), rebuildIndex: true })
|
|
526
|
+
expect(again).toMatchObject({ outcome: 'unchanged', passports: { written: [] }, records: { brands: { written: 0, unchanged: 1 }, offers: { written: 0, unchanged: 1 }, claims: { written: 0, unchanged: 2 } }, index: { announced: 4, admitted: 0, duplicate: 4 }, readings: { compared: 2, same: 2 } })
|
|
527
|
+
|
|
528
|
+
// The offer's claim code was never stored and is not in the package. Its digest is, so the recipient's code is recognised here.
|
|
529
|
+
const offer = (await second.store.listOffers({ passportId }))[0]!
|
|
530
|
+
expect(offer.claimCodeHash).toBe(createHash('sha256').update(claimCode).digest('hex'))
|
|
531
|
+
// The recipient's key is derived from a secret this deployment was given by its operator, not from the package. With it the holder retires the passport here.
|
|
532
|
+
const record = (await second.store.getPassport(passportId))!
|
|
533
|
+
const holder = second.custody.holderOf(record)
|
|
534
|
+
const transferTier = record.states.at(-1)!.ownerTier!
|
|
535
|
+
const transfer = (await second.index.lineage(passportId)).at(-1)!
|
|
536
|
+
const ciphertext = Utils.toArray(transferTier.ciphertext, 'base64')
|
|
537
|
+
expect(verifyOwnerBlob(ciphertext, findDppOutputs(transfer)[0].state.payloadOwnerHash)).toBe(true)
|
|
538
|
+
expect(transferTier.senderIdentityKey).toBe(second.parties.brand(brandId).identityKey)
|
|
539
|
+
const { plaintext } = await holder.wallet.decrypt({ ciphertext, protocolID: OWNER_DATA_PROTOCOL, keyID: passportId, counterparty: transferTier.senderIdentityKey! })
|
|
540
|
+
expect(JSON.parse(Utils.toUTF8(plaintext))).toEqual({ serviceNotes: 'second revision' })
|
|
541
|
+
const updated = await second.writer.update({ record, actor: holder, payload: JSON.parse(record.states.at(-1)!.payloadPublic) })
|
|
542
|
+
expect(updated.entry.ownerTier).toEqual(transferTier)
|
|
543
|
+
const retired = await second.writer.retire({ record: updated.record, actor: holder, reason: 'recycled' })
|
|
544
|
+
expect(retired.entry).toMatchObject({ op: 'RETIRE', index: 'admitted', ownerTier: transferTier })
|
|
545
|
+
expect((await second.read(passportId)).lineage.map((state) => state.op)).toEqual(['ISSUE', 'UPDATE', 'TRANSFER', 'UPDATE', 'RETIRE'])
|
|
546
|
+
})
|
|
547
|
+
|
|
548
|
+
it('refuses a recovery export that retained an incomplete ciphertext for its signed state', async () => {
|
|
549
|
+
const original = (await first.store.getPassport(passportId))!
|
|
550
|
+
const damaged = structuredClone(original)
|
|
551
|
+
damaged.states.at(-1)!.ownerTier!.ciphertext = Buffer.from('truncated by the source store').toString('base64')
|
|
552
|
+
await first.store.savePassport(damaged)
|
|
553
|
+
try {
|
|
554
|
+
const recovery = await exportApplication({ platform: first, epcis: exchange(), access: 'authorised-recovery', passportIds: [passportId] })
|
|
555
|
+
const folder = join(scratch, 'incomplete-ciphertext')
|
|
556
|
+
writePackageFolder(folder, recovery.manifest, recovery.files)
|
|
557
|
+
const problem = await refusal(verifyApplicationPackage(readPackageFolder(folder), trust(first)))
|
|
558
|
+
expect(problem).toMatchObject({ code: 'records-inconsistent', data: { passportId, txid: original.states.at(-1)!.txid } })
|
|
559
|
+
} finally {
|
|
560
|
+
await first.store.savePassport(original)
|
|
561
|
+
}
|
|
562
|
+
})
|
|
563
|
+
|
|
564
|
+
it('refuses a signed journal that would replay another transaction or its proof', async () => {
|
|
565
|
+
const original = (await first.store.getPassport(passportId))!
|
|
566
|
+
const other = (await first.store.getPassport(otherId))!.states[0]!
|
|
567
|
+
const path = MerklePath.fromCoinbaseTxidAndHeight(other.txid, 800_011)
|
|
568
|
+
const tx = Transaction.fromHex(original.states[0]!.rawTx)
|
|
569
|
+
tx.merklePath = MerklePath.fromCoinbaseTxidAndHeight(tx.id('hex'), 800_012)
|
|
570
|
+
const anotherHeight = MerklePath.fromCoinbaseTxidAndHeight(tx.id('hex'), 800_013)
|
|
571
|
+
try {
|
|
572
|
+
for (const patch of [
|
|
573
|
+
{ sentBeef: other.beef },
|
|
574
|
+
{ proof: { merklePath: path.toHex(), blockHeight: path.blockHeight } },
|
|
575
|
+
{ beef: Utils.toBase64(tx.toAtomicBEEF()), proof: { merklePath: anotherHeight.toHex(), blockHeight: anotherHeight.blockHeight } },
|
|
576
|
+
]) {
|
|
577
|
+
const damaged = structuredClone(original)
|
|
578
|
+
Object.assign(damaged.states[0]!, patch)
|
|
579
|
+
await first.store.savePassport(damaged)
|
|
580
|
+
const recovery = await exportApplication({ platform: first, epcis: exchange(), access: 'authorised-recovery', passportIds: [passportId] })
|
|
581
|
+
const refused = await refusal(verifyApplicationPackage({ manifestText: JSON.stringify(recovery.manifest), files: recovery.files }, trust(first)))
|
|
582
|
+
expect(refused.code).toBe('records-inconsistent')
|
|
583
|
+
}
|
|
584
|
+
} finally {
|
|
585
|
+
await first.store.savePassport(original)
|
|
586
|
+
}
|
|
587
|
+
})
|
|
588
|
+
|
|
589
|
+
it('never overwrites: a deployment that now holds another journal under the same identifier is left as it is', async () => {
|
|
590
|
+
const before = stableJson(await second.store.listPassports())
|
|
591
|
+
const refused = await refusal(restoreApplication({ verified: await verifyApplicationPackage(readPackageFolder(folder), trust(first)), platform: second, epcis: exchange(), rebuildIndex: true }))
|
|
592
|
+
expect(refused.code).toBe('reconciliation-required')
|
|
593
|
+
expect(refused.data.collisions).toEqual([{ kind: 'passport', identity: passportId }])
|
|
594
|
+
expect(refused.message).toContain('Nothing was written.')
|
|
595
|
+
expect(stableJson(await second.store.listPassports())).toBe(before)
|
|
596
|
+
})
|
|
597
|
+
|
|
598
|
+
it('refuses index evidence that was changed, a manifest that names another export, and a folder that is not a package', async () => {
|
|
599
|
+
const resign = async (name: string, change: (dir: string, manifest: EvidencePackageManifest) => void): Promise<string> => {
|
|
600
|
+
const dir = join(scratch, name)
|
|
601
|
+
writePackageFolder(dir, exported.manifest, exported.files)
|
|
602
|
+
const manifest = JSON.parse(readFileSync(join(dir, 'manifest.json'), 'utf8')) as EvidencePackageManifest
|
|
603
|
+
change(dir, manifest)
|
|
604
|
+
manifest.inventory = manifest.inventory.filter((entry) => existsSync(join(dir, entry.path))).map((entry) => {
|
|
605
|
+
const bytes = readFileSync(join(dir, entry.path))
|
|
606
|
+
return { ...entry, byteLength: bytes.byteLength, sha256: createHash('sha256').update(bytes).digest('hex') }
|
|
607
|
+
})
|
|
608
|
+
const key = evidencePackageSigningKey(PrivateKey.fromHex('11'.repeat(32)), manifest.passportId)
|
|
609
|
+
// Signed as the exporter signs: by the key its identity derives for the name the manifest now carries.
|
|
610
|
+
const signature = { suite: manifest.signature.suite, signer: key.toPublicKey().toString() }
|
|
611
|
+
writeFileSync(join(dir, 'manifest.json'), JSON.stringify(await signEvidenceManifest({ ...manifest, signature }, { sign: (preimage) => key.sign(preimage).toDER() as number[] })))
|
|
612
|
+
return dir
|
|
613
|
+
}
|
|
614
|
+
// A transaction of the index's evidence is changed, and the outer manifest is signed again for the changed bytes. The index's own signature no longer covers them.
|
|
615
|
+
const part = `${passportFolder(passportId)}/index/part-1`
|
|
616
|
+
const transaction = [...exported.files.keys()].find((path) => path.startsWith(`${part}/transactions/`))!
|
|
617
|
+
const tampered = await resign('tampered', (dir) => {
|
|
618
|
+
const bytes = readFileSync(join(dir, transaction))
|
|
619
|
+
bytes[10] = bytes[10]! ^ 1
|
|
620
|
+
writeFileSync(join(dir, transaction), bytes)
|
|
621
|
+
})
|
|
622
|
+
const evidence = await refusal(verifyApplicationPackage(readPackageFolder(tampered), trust(first)))
|
|
623
|
+
expect(evidence.code).toBe('index-evidence-refused')
|
|
624
|
+
expect(evidence.data.passportId).toBe(passportId)
|
|
625
|
+
|
|
626
|
+
// An EPCIS lifecycle claim whose carried bytes were changed, with the manifest signed again for them: the bytes no longer verify as the claim the record names.
|
|
627
|
+
const claimPath = [...exported.files.keys()].find((path) => path.startsWith('application/lifecycle-claims/'))!
|
|
628
|
+
const alteredClaim = await resign('altered-claim', (dir) => {
|
|
629
|
+
writeFileSync(join(dir, claimPath), readFileSync(join(dir, claimPath), 'utf8').replace('"conformant"', '"non_conformant"'))
|
|
630
|
+
})
|
|
631
|
+
const claimRefusal = await refusal(verifyApplicationPackage(readPackageFolder(alteredClaim), trust(first)))
|
|
632
|
+
expect(claimRefusal.code).toBe('claim-invalid')
|
|
633
|
+
|
|
634
|
+
// Readers find acceptance records by category and format. The bytes alone cannot supply a mislabelled entry.
|
|
635
|
+
for (const change of [{ category: 'reports' as const }, { representation: 'dpp-managed-acceptance@1' }]) {
|
|
636
|
+
const altered = await resign(`mislabelled-acceptance-${Object.keys(change)[0]}`, (_dir, manifest) => {
|
|
637
|
+
Object.assign(manifest.inventory.find(entry => entry.representation === 'dpp-managed-acceptance@2')!, change)
|
|
638
|
+
})
|
|
639
|
+
expect((await refusal(verifyApplicationPackage(readPackageFolder(altered), trust(first)))).code).toBe('records-inconsistent')
|
|
640
|
+
}
|
|
641
|
+
|
|
642
|
+
// A manifest signed, correctly, under the name of another selection than the passports the package carries.
|
|
643
|
+
const scope = await resign('scope', (_dir, manifest) => {
|
|
644
|
+
manifest.passportId = exportScopeId([passportId])
|
|
645
|
+
})
|
|
646
|
+
expect((await refusal(verifyApplicationPackage(readPackageFolder(scope), trust(first)))).code).toBe('export-scope-mismatch')
|
|
647
|
+
|
|
648
|
+
// A package about one passport, as an index exports it, is not an export of an application.
|
|
649
|
+
const single = await first.index.evidencePackage(passportId)
|
|
650
|
+
if (!('envelope' in single)) throw new Error('the index gave no package')
|
|
651
|
+
expect((await refusal(verifyApplicationPackage({ manifestText: JSON.stringify(single.envelope.manifest), files: new Map() }, trust(first)))).code).toBe('not-an-application-export')
|
|
652
|
+
expect((await refusal(verifyApplicationPackage({ files: new Map() }, trust(first)))).code).toBe('manifest-missing')
|
|
653
|
+
expect(() => readPackageFolder(join(scratch, 'not-there'))).toThrow(/There is no folder/)
|
|
654
|
+
})
|
|
655
|
+
})
|