@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,708 @@
|
|
|
1
|
+
// The complete export of this application, as one `dpp-evidence-package@1`.
|
|
2
|
+
//
|
|
3
|
+
// Everything here is assembled from parts the packages already produce. The
|
|
4
|
+
// index's evidence for each passport is the package the index itself signs.
|
|
5
|
+
// The profiles are the bundle `exportProfileBundle` makes. The EPCIS exchange
|
|
6
|
+
// is the snapshot `exportEpcisRecovery` takes, or the public form
|
|
7
|
+
// `exportEpcisPublicEvidence` gives. This file asks for each, adds this
|
|
8
|
+
// application's own records, lists every file once in one inventory, and
|
|
9
|
+
// signs the manifest. It builds no transaction, announces nothing and changes
|
|
10
|
+
// no record: an export reads.
|
|
11
|
+
//
|
|
12
|
+
// There are two exports and they are different access paths. The authorised
|
|
13
|
+
// one is for the operator of this deployment, who is moving it or keeping a
|
|
14
|
+
// backup: it carries the journals with their sealed owner tiers, the brands,
|
|
15
|
+
// the offers, the claims and the operational records of the exchange. The
|
|
16
|
+
// public one carries only what anyone may hold. Neither carries a key, a
|
|
17
|
+
// wallet file, a secret or a credential, and before anything is handed over
|
|
18
|
+
// every byte is searched for each secret this deployment was configured
|
|
19
|
+
// with.
|
|
20
|
+
//
|
|
21
|
+
// What a signature on the manifest says: that this application, under its
|
|
22
|
+
// publisher key, assembled these bytes. It does not say they are true or
|
|
23
|
+
// complete beyond what the manifest declares, and it gives no profile any
|
|
24
|
+
// authority at the place the package is restored.
|
|
25
|
+
import { Transaction, Utils } from '@bsv/sdk'
|
|
26
|
+
import {
|
|
27
|
+
ACCEPTANCE_RECORD_REPRESENTATIONS,
|
|
28
|
+
EVIDENCE_PACKAGE_FORMAT,
|
|
29
|
+
EVIDENCE_PACKAGE_PROTOCOL,
|
|
30
|
+
EVIDENCE_PACKAGE_VERSION,
|
|
31
|
+
MANAGED_CUSTODY_EXPORT_PROFILE,
|
|
32
|
+
acceptanceCommitment,
|
|
33
|
+
bindAcceptanceToState,
|
|
34
|
+
evidencePackageSigner,
|
|
35
|
+
findDppOutputs,
|
|
36
|
+
inspectEvidencePackage,
|
|
37
|
+
inspectManagedAcceptance,
|
|
38
|
+
publicCustodyTransfers,
|
|
39
|
+
signEvidenceManifest,
|
|
40
|
+
verifyServerSignature,
|
|
41
|
+
verifyUserSignature,
|
|
42
|
+
type DppStateV2,
|
|
43
|
+
type ManagedAcceptanceRecord,
|
|
44
|
+
type EvidencePackageManifest,
|
|
45
|
+
type InventoryCategory,
|
|
46
|
+
type InventoryEntry,
|
|
47
|
+
type SourceObservation,
|
|
48
|
+
} from '@bsv/dpp-protocol'
|
|
49
|
+
import {
|
|
50
|
+
EPCIS_LIFECYCLE_MEDIA_TYPE,
|
|
51
|
+
EPCIS_LIFECYCLE_REPRESENTATION,
|
|
52
|
+
} from '@bsv/dpp-credentials/epcis-lifecycle'
|
|
53
|
+
import { describeProfileBundleOmission, exportProfileBundle, isRetiredProfile } from '@bsv/dpp-profiles'
|
|
54
|
+
import { EPCIS_GS1_ARTEFACTS } from '@bsv/dpp-credentials'
|
|
55
|
+
import { exportEpcisPublicEvidence, exportEpcisRecovery, type EpcisExchangeStorage, type EpcisSourceCredential, type ExportedEpcisRecovery } from '@bsv/dpp-credentials/epcis-exchange'
|
|
56
|
+
import type { Config } from '../config.js'
|
|
57
|
+
import { acceptanceMatchesOffer } from '../custody.js'
|
|
58
|
+
import { describeEpcisSource, type EpcisSourceConfig } from '../epcis/sources.js'
|
|
59
|
+
import type { Platform } from '../platform.js'
|
|
60
|
+
import { isProfileId } from '../profiles.js'
|
|
61
|
+
import type { PassportReading } from '../reader.js'
|
|
62
|
+
import { isEpcisLifecycleRecord, isInterrupted, type OfferRecord, type PassportRecord } from '../store.js'
|
|
63
|
+
import {
|
|
64
|
+
APPLICATION_EXPORT_DESCRIPTOR,
|
|
65
|
+
APPLICATION_EXPORT_FORMAT,
|
|
66
|
+
APPLICATION_EXPORT_LIMITS,
|
|
67
|
+
APPLICATION_EXPORT_VERSION,
|
|
68
|
+
APPLICATION_REPRESENTATIONS,
|
|
69
|
+
EPCIS_ROOT,
|
|
70
|
+
PROFILES_ROOT,
|
|
71
|
+
PortabilityRefused,
|
|
72
|
+
asNumberArrays,
|
|
73
|
+
entryOf,
|
|
74
|
+
exportScopeId,
|
|
75
|
+
passportFolder,
|
|
76
|
+
readNestedAcceptance,
|
|
77
|
+
recordBytes,
|
|
78
|
+
sha256Hex,
|
|
79
|
+
utf8,
|
|
80
|
+
type ApplicationExportAccess,
|
|
81
|
+
type ApplicationExportDescriptor,
|
|
82
|
+
type ApplicationExportOmission,
|
|
83
|
+
type ExportedPassport,
|
|
84
|
+
type ExportedReading,
|
|
85
|
+
} from './package.js'
|
|
86
|
+
|
|
87
|
+
const JSON_MEDIA_TYPE = 'application/json'
|
|
88
|
+
const SOFTWARE = 'create-dpp-app application'
|
|
89
|
+
|
|
90
|
+
export interface ExportApplicationInput {
|
|
91
|
+
platform: Platform
|
|
92
|
+
/** The exchange's store and the sources this deployment was configured with. The credentials are read to search for them, and are written nowhere. */
|
|
93
|
+
epcis: { storage: EpcisExchangeStorage; sources: EpcisSourceConfig[] }
|
|
94
|
+
access: ApplicationExportAccess
|
|
95
|
+
/** The successor carriage rules apply only when explicitly selected. */
|
|
96
|
+
custodyProfile?: typeof MANAGED_CUSTODY_EXPORT_PROFILE
|
|
97
|
+
/** The passports to cover. Default: every passport in the journal. */
|
|
98
|
+
passportIds?: readonly string[]
|
|
99
|
+
/**
|
|
100
|
+
* A public export only: the source scopes whose imports may be published.
|
|
101
|
+
* There is no default, because nothing here knows which sources a
|
|
102
|
+
* deployment may publish, so a public export with none named carries
|
|
103
|
+
* nothing of the exchange.
|
|
104
|
+
*/
|
|
105
|
+
publicSources?: readonly string[]
|
|
106
|
+
/** An authorised export only: whether the cursors of pulls are carried. Left out by default, so each unfinished pull replays from its bounds. */
|
|
107
|
+
cursors?: 'exclude' | 'include'
|
|
108
|
+
/** `complete` asks the index for its complete export even where its bounded package would do. For a test. */
|
|
109
|
+
indexRoute?: 'auto' | 'complete'
|
|
110
|
+
now?: () => Date
|
|
111
|
+
log?: (line: string) => void
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
export interface ExportedApplication {
|
|
115
|
+
manifest: EvidencePackageManifest
|
|
116
|
+
/** Every file by its path in the package, the manifest left out. */
|
|
117
|
+
files: Map<string, Uint8Array>
|
|
118
|
+
descriptor: ApplicationExportDescriptor
|
|
119
|
+
/** The key the manifest is signed under, and the identity key it derives from. A destination needs the second. */
|
|
120
|
+
exporter: { identityKey: string; signer: string }
|
|
121
|
+
}
|
|
122
|
+
|
|
123
|
+
/** A reading in the terms an export carries and a restore compares: outcomes, never values. */
|
|
124
|
+
export function summariseReading(reading: PassportReading, chainTracker: Platform['chainTracker']): ExportedReading {
|
|
125
|
+
return {
|
|
126
|
+
passportId: reading.passportId,
|
|
127
|
+
chainTracker: chainTracker === 'scripts only' ? 'scripts only' : 'header-source',
|
|
128
|
+
lineage: reading.lineage.map((state) => ({ op: state.op, txid: state.txid })),
|
|
129
|
+
checks: reading.checks.map((check) => ({ name: check.name, status: check.status, ...(check.reasonCode == null ? {} : { reasonCode: check.reasonCode }) })),
|
|
130
|
+
payloadChecks: reading.payloadChecks.map((check) => ({
|
|
131
|
+
txid: check.txid,
|
|
132
|
+
stateIndex: check.stateIndex,
|
|
133
|
+
profile: check.profile,
|
|
134
|
+
status: check.publicView.status,
|
|
135
|
+
...(check.publicView.cause == null ? {} : { cause: check.publicView.cause }),
|
|
136
|
+
steps: check.publicView.steps.map((step) => ({ step: step.step, status: step.status, ...(step.cause == null ? {} : { cause: step.cause }) })),
|
|
137
|
+
findings: check.publicView.findings.map((finding) => ({ step: finding.step, severity: finding.severity, constraint: finding.constraint, ...(finding.path == null ? {} : { path: finding.path }), ...(finding.message == null ? {} : { message: finding.message }) })),
|
|
138
|
+
withheld: check.publicView.withheld,
|
|
139
|
+
})),
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
/** The binding digest a state's public payload declares, when it is a product document under a binding. */
|
|
144
|
+
export function declaredBindingDigest(payloadPublic: string): string | undefined {
|
|
145
|
+
try {
|
|
146
|
+
const parsed = JSON.parse(payloadPublic) as { profile_binding_sha256?: unknown }
|
|
147
|
+
return typeof parsed?.profile_binding_sha256 === 'string' && /^[0-9a-f]{64}$/.test(parsed.profile_binding_sha256) ? parsed.profile_binding_sha256 : undefined
|
|
148
|
+
} catch {
|
|
149
|
+
return undefined
|
|
150
|
+
}
|
|
151
|
+
}
|
|
152
|
+
|
|
153
|
+
/** Every secret this deployment was configured with, to search an export for. Each is read here and written nowhere. */
|
|
154
|
+
function configuredSecrets(config: Config, credentials: readonly EpcisSourceCredential[]): string[] {
|
|
155
|
+
const secrets = [config.wallet.rootKeyHex, config.brandRootSecret, config.managedIdentitySecret, config.authSecret, config.index.submitToken, config.index.callbackToken, config.registry.token, config.validator.token, config.indexExport.token, config.wallet.wocApiKey]
|
|
156
|
+
for (const credential of credentials) {
|
|
157
|
+
if (credential.scheme === 'bearer') secrets.push(credential.token)
|
|
158
|
+
else if (credential.scheme === 'basic') secrets.push(credential.password, Buffer.from(`${credential.username}:${credential.password}`).toString('base64'))
|
|
159
|
+
else secrets.push(credential.value)
|
|
160
|
+
}
|
|
161
|
+
// A secret shorter than this would be found by chance in a digest or a transaction, and no setting of this application is one.
|
|
162
|
+
return [...new Set(secrets.filter((secret): secret is string => typeof secret === 'string' && secret.length >= 8))]
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/** The first file that holds a configured secret, in any of the forms a secret is passed around in. */
|
|
166
|
+
function secretCarrier(files: ReadonlyMap<string, Uint8Array>, manifestText: string, secrets: readonly string[], rawDigests: readonly string[] = []): string | undefined {
|
|
167
|
+
const forms = secrets.flatMap((secret) => [secret, encodeURIComponent(secret), Buffer.from(secret, 'utf8').toString('base64'), Buffer.from(secret, 'utf8').toString('base64url'), Buffer.from(secret, 'utf8').toString('hex')]).map((form) => Buffer.from(form, 'utf8'))
|
|
168
|
+
forms.push(...rawDigests.map(digest => Buffer.from(digest, 'hex')))
|
|
169
|
+
const holds = (bytes: Uint8Array): boolean => {
|
|
170
|
+
const buffer = Buffer.from(bytes.buffer, bytes.byteOffset, bytes.byteLength)
|
|
171
|
+
return forms.some((form) => buffer.includes(form))
|
|
172
|
+
}
|
|
173
|
+
if (holds(utf8(manifestText))) return 'manifest.json'
|
|
174
|
+
for (const [path, bytes] of files) if (holds(bytes)) return path
|
|
175
|
+
return undefined
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/** What the index gave for one passport, placed under the passport's folder and checked. */
|
|
179
|
+
interface IndexEvidence {
|
|
180
|
+
summary: ExportedPassport['index']
|
|
181
|
+
files: Array<{ path: string; bytes: Uint8Array; category: InventoryCategory; mediaType: string; represents?: string; representation?: string; acceptance?: ManagedAcceptanceRecord }>
|
|
182
|
+
snapshots: EvidencePackageManifest['completeness']['snapshots']
|
|
183
|
+
absent: string[]
|
|
184
|
+
sources: SourceObservation[]
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
const isObject = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value)
|
|
188
|
+
|
|
189
|
+
/**
|
|
190
|
+
* The index's own evidence for one passport, through the routes it already
|
|
191
|
+
* serves. The bounded package is asked for first. Where the lineage is longer
|
|
192
|
+
* than its bound, the complete export is asked for, part by part. Whatever
|
|
193
|
+
* arrives is inspected under the index's exporter key before it is carried,
|
|
194
|
+
* and an answer that does not inspect stops the export: evidence that cannot
|
|
195
|
+
* be checked here is not passed on as if it had been.
|
|
196
|
+
*/
|
|
197
|
+
async function indexEvidenceFor(input: ExportApplicationInput, passportId: string, folder: string, exporterKey: string | undefined, observedAt: string): Promise<IndexEvidence> {
|
|
198
|
+
const { index, config } = input.platform
|
|
199
|
+
const none = (reason: string, result: SourceObservation['result']): IndexEvidence => ({
|
|
200
|
+
summary: { form: 'none', reason },
|
|
201
|
+
files: [],
|
|
202
|
+
snapshots: [],
|
|
203
|
+
absent: [`index-evidence:${passportId} (${reason})`],
|
|
204
|
+
sources: [{ id: 'ls_dpp', kind: 'overlay-lookup', observedAt, result }],
|
|
205
|
+
})
|
|
206
|
+
const refuse = (detail: string, failures: string[]): never => {
|
|
207
|
+
throw new PortabilityRefused('index-evidence-refused', `The index's evidence for ${passportId} does not check: ${detail} Nothing was exported.`, { passportId, failures })
|
|
208
|
+
}
|
|
209
|
+
const place = (base: string, manifest: EvidencePackageManifest, encoded: Record<string, string>, into: IndexEvidence['files']): void => {
|
|
210
|
+
const carriesAcceptances = manifest.inventory.some(entry => ACCEPTANCE_RECORD_REPRESENTATIONS.some(format => entry.representation === format))
|
|
211
|
+
if (input.access === 'public-evidence') {
|
|
212
|
+
if (manifest.disclosure.scope !== 'public' || manifest.disclosure.recoveryBackup || carriesAcceptances) {
|
|
213
|
+
refuse('its disclosure scope or acceptance records cannot be carried by this public export.', [])
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
into.push({ path: `${base}/manifest.json`, bytes: utf8(JSON.stringify(manifest)), category: 'reports', mediaType: JSON_MEDIA_TYPE, represents: passportId, representation: APPLICATION_REPRESENTATIONS.indexManifest })
|
|
217
|
+
for (const entry of manifest.inventory) {
|
|
218
|
+
const bytes = Uint8Array.from(Buffer.from(encoded[entry.path] ?? '', 'base64'))
|
|
219
|
+
const acceptance = input.custodyProfile === MANAGED_CUSTODY_EXPORT_PROFILE && input.access === 'authorised-recovery'
|
|
220
|
+
? readNestedAcceptance(entry, bytes, passportId, input.platform.wallet.identityKey) : undefined
|
|
221
|
+
const representation = acceptance == null ? entry.representation : APPLICATION_REPRESENTATIONS.nestedAuthority
|
|
222
|
+
into.push({ path: `${base}/${entry.path}`, bytes, category: entry.category, mediaType: entry.mediaType, ...(entry.represents == null ? {} : { represents: entry.represents }), ...(representation == null ? {} : { representation }), ...(acceptance == null ? {} : { acceptance }) })
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
const signerFor = (manifest: EvidencePackageManifest): string | undefined => {
|
|
226
|
+
if (exporterKey == null) return undefined
|
|
227
|
+
// An index on an earlier release signed with its raw export key and names it as both. It still inspects under that key.
|
|
228
|
+
return manifest.exporter?.id === exporterKey && manifest.signature?.signer === exporterKey ? exporterKey : evidencePackageSigner(exporterKey, passportId)
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
const bounded = input.indexRoute === 'complete' ? undefined : await index.evidencePackage(passportId)
|
|
232
|
+
if (bounded != null && 'absent' in bounded) return none(bounded.detail, bounded.absent === 'not-held' ? 'not-found' : 'unavailable')
|
|
233
|
+
if (bounded != null) {
|
|
234
|
+
const manifest = bounded.envelope.manifest as EvidencePackageManifest
|
|
235
|
+
const encoded = isObject(bounded.envelope.files) ? (bounded.envelope.files as Record<string, string>) : {}
|
|
236
|
+
const expectedSigner = signerFor(manifest)
|
|
237
|
+
const inspection = inspectEvidencePackage(manifest, new Map(Object.entries(encoded).map(([path, base64]) => [path, Utils.toArray(base64, 'base64') as number[]])), { expectedPassportId: passportId, ...(expectedSigner == null ? {} : { expectedSigner }) })
|
|
238
|
+
if (!inspection.structureValid || !inspection.inventoryVerified || inspection.signatureValid !== true || inspection.failures.length > 0) refuse('its package fails inspection.', inspection.failures.map((failure) => failure.detail))
|
|
239
|
+
const complete = manifest.completeness.snapshots.every((snapshot) => snapshot.completeForSnapshot)
|
|
240
|
+
if (complete) {
|
|
241
|
+
const files: IndexEvidence['files'] = []
|
|
242
|
+
place(`${folder}/index`, manifest, encoded, files)
|
|
243
|
+
return { summary: { form: 'package', exporter: manifest.exporter.id, snapshotId: manifest.completeness.snapshots[0]?.snapshotId, states: manifest.inventory.filter((entry) => entry.category === 'transactions').length }, files, snapshots: manifest.completeness.snapshots, absent: manifest.completeness.absent, sources: manifest.sources }
|
|
244
|
+
}
|
|
245
|
+
// The lineage is longer than the package's bound. The complete export tiles the whole snapshot; when it cannot be had, the bounded package is carried and says what it lacks.
|
|
246
|
+
const whole = await completeExport()
|
|
247
|
+
if (whole != null) return whole
|
|
248
|
+
const files: IndexEvidence['files'] = []
|
|
249
|
+
place(`${folder}/index`, manifest, encoded, files)
|
|
250
|
+
return { summary: { form: 'bounded-package', exporter: manifest.exporter.id, snapshotId: manifest.completeness.snapshots[0]?.snapshotId, states: manifest.inventory.filter((entry) => entry.category === 'transactions').length, reason: 'the lineage is longer than the bound of the index\'s package, and its complete export could not be had' }, files, snapshots: manifest.completeness.snapshots, absent: manifest.completeness.absent, sources: manifest.sources }
|
|
251
|
+
}
|
|
252
|
+
const whole = await completeExport()
|
|
253
|
+
if (whole != null) return whole
|
|
254
|
+
return none('the index gave no part of its complete export', 'unavailable')
|
|
255
|
+
|
|
256
|
+
/** The index's complete export, joined as a reader joins it. Undefined when the index would not give it. */
|
|
257
|
+
async function completeExport(): Promise<IndexEvidence | undefined> {
|
|
258
|
+
const { joinEvidenceExport } = await import('@bsv/dpp-overlay')
|
|
259
|
+
const parts: Array<Record<string, unknown>> = []
|
|
260
|
+
let cursor: string | null = null
|
|
261
|
+
for (;;) {
|
|
262
|
+
const answer = await index.evidenceExportPart(passportId, cursor, config.indexExport.token)
|
|
263
|
+
if ('absent' in answer) {
|
|
264
|
+
input.log?.(`The index's complete export for ${passportId} could not be had: ${answer.detail}.`)
|
|
265
|
+
return undefined
|
|
266
|
+
}
|
|
267
|
+
parts.push(answer.part)
|
|
268
|
+
cursor = typeof answer.part.nextCursor === 'string' ? answer.part.nextCursor : null
|
|
269
|
+
if (cursor == null) break
|
|
270
|
+
if (parts.length > 10_000) refuse('its complete export does not end.', [])
|
|
271
|
+
}
|
|
272
|
+
const first = parts[0] as { package?: { manifest?: EvidencePackageManifest } }
|
|
273
|
+
const expectedSigner = first.package?.manifest == null ? undefined : signerFor(first.package.manifest)
|
|
274
|
+
const joined = joinEvidenceExport(parts as never, { expectedPassportId: passportId, ...(expectedSigner == null ? {} : { expectedSigner }) })
|
|
275
|
+
if (!joined.complete) refuse('the parts of its complete export do not join into one snapshot.', joined.problems)
|
|
276
|
+
const files: IndexEvidence['files'] = []
|
|
277
|
+
const snapshots: IndexEvidence['snapshots'] = []
|
|
278
|
+
const sources: SourceObservation[] = []
|
|
279
|
+
let states = 0
|
|
280
|
+
parts.forEach((part, at) => {
|
|
281
|
+
const { package: carried, nextCursor: _cursor, ...coverage } = part as { package: { manifest: EvidencePackageManifest; files: Record<string, string> }; nextCursor: unknown }
|
|
282
|
+
const base = `${folder}/index/part-${at + 1}`
|
|
283
|
+
// The coverage record is what the index signed about this part. Its cursor is not part of what it signed and is not carried.
|
|
284
|
+
files.push({ path: `${base}/coverage.json`, bytes: utf8(JSON.stringify(coverage)), category: 'reports', mediaType: JSON_MEDIA_TYPE, represents: `${passportId} part ${at + 1}`, representation: APPLICATION_REPRESENTATIONS.indexCoverage })
|
|
285
|
+
place(base, carried.manifest, carried.files, files)
|
|
286
|
+
snapshots.push(...carried.manifest.completeness.snapshots)
|
|
287
|
+
sources.push(...carried.manifest.sources)
|
|
288
|
+
states += carried.manifest.inventory.filter((entry) => entry.category === 'transactions').length
|
|
289
|
+
})
|
|
290
|
+
return { summary: { form: 'export-parts', exporter: joined.manifests[0]?.exporter.id, ...(joined.snapshotId == null ? {} : { snapshotId: joined.snapshotId }), parts: parts.length, states }, files, snapshots, absent: joined.absent, sources }
|
|
291
|
+
}
|
|
292
|
+
}
|
|
293
|
+
|
|
294
|
+
/** The selected journals, read twice and kept only when both readings agree, so what is carried stood together at one moment. */
|
|
295
|
+
async function readJournals(input: ExportApplicationInput): Promise<PassportRecord[]> {
|
|
296
|
+
const { store } = input.platform
|
|
297
|
+
const read = async (): Promise<PassportRecord[]> => {
|
|
298
|
+
const all = (await store.listPassports()).filter((record) => record.states.length > 0)
|
|
299
|
+
if (input.passportIds == null) return all.sort((a, b) => (a.passportId < b.passportId ? -1 : 1))
|
|
300
|
+
const wanted = [...new Set(input.passportIds)]
|
|
301
|
+
const missing = wanted.filter((passportId) => !all.some((record) => record.passportId === passportId))
|
|
302
|
+
if (missing.length > 0) throw new PortabilityRefused('passport-unknown', `This application's journal holds no passport ${missing.join(', ')}. Nothing was exported.`, { passportIds: missing })
|
|
303
|
+
return all.filter((record) => wanted.includes(record.passportId)).sort((a, b) => (a.passportId < b.passportId ? -1 : 1))
|
|
304
|
+
}
|
|
305
|
+
const first = await read()
|
|
306
|
+
const second = await read()
|
|
307
|
+
if (sha256Hex(recordBytes(first)) !== sha256Hex(recordBytes(second))) {
|
|
308
|
+
throw new PortabilityRefused('store-unstable', 'A passport changed while it was being read. Another writer is at work: stop the API and its worker, then export again.')
|
|
309
|
+
}
|
|
310
|
+
return first
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
/** The transfers anyone can read in the index files actually included for this passport. */
|
|
314
|
+
function publicTransfers(evidence: IndexEvidence, passportId: string): DppStateV2[] {
|
|
315
|
+
const transfers: DppStateV2[] = []
|
|
316
|
+
for (const file of evidence.files) {
|
|
317
|
+
if (file.category !== 'transactions' || file.representation !== 'raw-transaction') continue
|
|
318
|
+
for (const { state } of findDppOutputs(Transaction.fromBinary(Array.from(file.bytes)))) {
|
|
319
|
+
if (state.version === '2' && state.op === 'TRANSFER' && state.passportId === passportId && state.authorisationCommitment) transfers.push(state)
|
|
320
|
+
}
|
|
321
|
+
}
|
|
322
|
+
return transfers
|
|
323
|
+
}
|
|
324
|
+
|
|
325
|
+
/** Only a successful network answer (or the test wallet's dry run) completes a journalled handover. */
|
|
326
|
+
function journalTransfers(passport: PassportRecord, publisherKey: string) {
|
|
327
|
+
const completed: DppStateV2[] = []
|
|
328
|
+
const interrupted: DppStateV2[] = []
|
|
329
|
+
for (const [at, entry] of passport.states.entries()) {
|
|
330
|
+
let tx: Transaction
|
|
331
|
+
try {
|
|
332
|
+
tx = Transaction.fromHex(entry.rawTx)
|
|
333
|
+
} catch {
|
|
334
|
+
throw new PortabilityRefused('record-invalid', 'A journal transaction cannot be decoded.', { passportId: passport.passportId, txid: entry.txid })
|
|
335
|
+
}
|
|
336
|
+
const outputs = findDppOutputs(tx)
|
|
337
|
+
const output = outputs[0]
|
|
338
|
+
if (tx.id('hex') !== entry.txid || outputs.length !== 1 || output?.outputIndex !== entry.outputIndex
|
|
339
|
+
|| output.state.passportId !== passport.passportId || output.state.op !== entry.op) {
|
|
340
|
+
throw new PortabilityRefused('records-inconsistent', 'A journal entry differs from its transaction.', { passportId: passport.passportId, txid: entry.txid })
|
|
341
|
+
}
|
|
342
|
+
const { state } = output
|
|
343
|
+
if (state.version !== '2' || state.op !== 'TRANSFER' || !state.authorisationCommitment) continue
|
|
344
|
+
const prior = passport.states[at - 1]
|
|
345
|
+
if (prior == null || state.previousTxid !== prior.txid || state.previousOutputIndex !== prior.outputIndex
|
|
346
|
+
|| !tx.inputs.some(input => input.sourceTXID === prior.txid && input.sourceOutputIndex === prior.outputIndex)
|
|
347
|
+
|| !verifyUserSignature(state) || !verifyServerSignature(state, publisherKey)) {
|
|
348
|
+
throw new PortabilityRefused('records-inconsistent', 'A transfer does not verify for its journal predecessor and publisher.', { passportId: passport.passportId, txid: entry.txid })
|
|
349
|
+
}
|
|
350
|
+
if (entry.network === 'accepted' || entry.network === 'dry-run') completed.push(state)
|
|
351
|
+
else if (isInterrupted(entry)) interrupted.push(state)
|
|
352
|
+
else throw new PortabilityRefused('records-inconsistent', 'The transfer has an unrecognised send outcome.', { passportId: passport.passportId, txid: entry.txid })
|
|
353
|
+
}
|
|
354
|
+
return { completed, interrupted }
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
/** Resolve commitment dispositions and recovery copies from the records this custodian actually holds. */
|
|
358
|
+
function custodyEvidence(passport: PassportRecord, offers: OfferRecord[], transfers: DppStateV2[], custodian: string, nested: ManagedAcceptanceRecord[], interrupted?: DppStateV2[]) {
|
|
359
|
+
const authorised = interrupted != null
|
|
360
|
+
const held = new Map<string, ManagedAcceptanceRecord>()
|
|
361
|
+
for (const record of [...passport.acceptanceRecords, ...passport.states.flatMap(entry => entry.acceptance ?? []), ...offers.flatMap(offer => offer.record ?? [])]) {
|
|
362
|
+
held.set(acceptanceCommitment(record), record)
|
|
363
|
+
}
|
|
364
|
+
const referenced = new Map(transfers.map(state => [state.authorisationCommitment, state]))
|
|
365
|
+
for (const record of nested) {
|
|
366
|
+
const commitment = acceptanceCommitment(record)
|
|
367
|
+
const state = referenced.get(commitment)
|
|
368
|
+
if (state == null || bindAcceptanceToState(record, state).length > 0) {
|
|
369
|
+
throw new PortabilityRefused('index-evidence-refused', 'A signed index acceptance does not bind to a completed transfer in the supplied history.', { passportId: passport.passportId, commitment })
|
|
370
|
+
}
|
|
371
|
+
held.set(commitment, record)
|
|
372
|
+
}
|
|
373
|
+
const byRequest = new Map(Array.from(held.values(), record => [record.requestId, record]))
|
|
374
|
+
const authority = new Map<string, ManagedAcceptanceRecord>()
|
|
375
|
+
const absent: string[] = []
|
|
376
|
+
const withheld: string[] = []
|
|
377
|
+
for (const state of transfers) {
|
|
378
|
+
const commitment = state.authorisationCommitment
|
|
379
|
+
const reference = `acceptance:sha256:${commitment}`
|
|
380
|
+
const record = held.get(commitment)
|
|
381
|
+
if (record == null) {
|
|
382
|
+
absent.push(reference)
|
|
383
|
+
continue
|
|
384
|
+
}
|
|
385
|
+
if (inspectManagedAcceptance(record, { custodians: [custodian] }).failures.length || bindAcceptanceToState(record, state).length) {
|
|
386
|
+
throw new PortabilityRefused('records-inconsistent', 'A held acceptance does not verify for the transfer that commits to it.', { passportId: passport.passportId, commitment })
|
|
387
|
+
}
|
|
388
|
+
if (authorised) authority.set(commitment, record)
|
|
389
|
+
else withheld.push(`${reference} not-public`)
|
|
390
|
+
}
|
|
391
|
+
|
|
392
|
+
// Reattach the original record to its offer if the journal holds the only copy.
|
|
393
|
+
const offerCopies: OfferRecord[] = []
|
|
394
|
+
if (authorised) {
|
|
395
|
+
const acceptedOffers = new Map<string, ManagedAcceptanceRecord>()
|
|
396
|
+
for (const offer of offers) {
|
|
397
|
+
const accepted = offer.status === 'accepted' || offer.status === 'transferred'
|
|
398
|
+
const record = offer.record ?? (accepted ? byRequest.get(offer.requestId) : undefined)
|
|
399
|
+
if (record != null && (!accepted || !acceptanceMatchesOffer(offer, record, passport, custodian))) {
|
|
400
|
+
throw new PortabilityRefused('records-inconsistent', 'A signed acceptance does not verify for its retained offer.', { requestId: offer.requestId })
|
|
401
|
+
}
|
|
402
|
+
if (offer.status === 'accepted') {
|
|
403
|
+
if (record == null) throw new PortabilityRefused('records-inconsistent', 'An accepted offer has lost its signed record.', { requestId: offer.requestId })
|
|
404
|
+
acceptedOffers.set(acceptanceCommitment(record), record)
|
|
405
|
+
}
|
|
406
|
+
offerCopies.push(record != null && offer.record == null ? { ...offer, record } : offer)
|
|
407
|
+
}
|
|
408
|
+
for (const state of interrupted) {
|
|
409
|
+
const record = acceptedOffers.get(state.authorisationCommitment)
|
|
410
|
+
if (record == null || bindAcceptanceToState(record, state).length > 0) {
|
|
411
|
+
throw new PortabilityRefused('records-inconsistent', 'An interrupted transfer lacks its matching signed offer.', { passportId: passport.passportId })
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
}
|
|
415
|
+
const pending = authorised ? [] : offers.flatMap(offer => {
|
|
416
|
+
const record = offer.record ?? byRequest.get(offer.requestId)
|
|
417
|
+
if (offer.status !== 'accepted' || record == null) return []
|
|
418
|
+
const commitment = acceptanceCommitment(record)
|
|
419
|
+
return referenced.has(commitment) ? [] : [commitment]
|
|
420
|
+
})
|
|
421
|
+
return { authority: [...authority.values()], offers: offerCopies, absent, withheld, pending }
|
|
422
|
+
}
|
|
423
|
+
|
|
424
|
+
export async function exportApplication(input: ExportApplicationInput): Promise<ExportedApplication> {
|
|
425
|
+
const { platform, access } = input
|
|
426
|
+
const { config, store, wallet, profiles } = platform
|
|
427
|
+
const authorised = access === 'authorised-recovery'
|
|
428
|
+
if (input.custodyProfile != null && input.custodyProfile !== MANAGED_CUSTODY_EXPORT_PROFILE) {
|
|
429
|
+
throw new PortabilityRefused('not-selected', 'The requested custody export profile is unavailable.')
|
|
430
|
+
}
|
|
431
|
+
const v3 = input.custodyProfile === MANAGED_CUSTODY_EXPORT_PROFILE
|
|
432
|
+
const exportedAt = (input.now?.() ?? new Date()).toISOString()
|
|
433
|
+
const credentials = input.epcis.sources.flatMap((source) => (source.credentials == null ? [] : [source.credentials()]))
|
|
434
|
+
|
|
435
|
+
const files = new Map<string, Uint8Array>()
|
|
436
|
+
const inventory: InventoryEntry[] = []
|
|
437
|
+
const add = (path: string, category: InventoryCategory, mediaType: string, bytes: Uint8Array, extra: Pick<InventoryEntry, 'encrypted' | 'represents' | 'representation'> = {}): void => {
|
|
438
|
+
if (files.has(path)) throw new PortabilityRefused('path-duplicate', `Two files of the export would share the name ${path}.`, { path })
|
|
439
|
+
files.set(path, bytes)
|
|
440
|
+
inventory.push(entryOf(path, category, mediaType, bytes, extra))
|
|
441
|
+
}
|
|
442
|
+
const snapshots: EvidencePackageManifest['completeness']['snapshots'] = []
|
|
443
|
+
const withheld: string[] = []
|
|
444
|
+
const absent: string[] = []
|
|
445
|
+
const sources: SourceObservation[] = []
|
|
446
|
+
const omitted: ApplicationExportOmission[] = []
|
|
447
|
+
|
|
448
|
+
/* ---- the passports: the index's evidence, this application's records and a reading ---- */
|
|
449
|
+
|
|
450
|
+
const journals = await readJournals(input)
|
|
451
|
+
const exportId = exportScopeId(journals.map((record) => record.passportId))
|
|
452
|
+
const exporterKey = journals.length === 0 ? undefined : (config.indexExport.exporterKey ?? (await platform.index.exporterIdentityKey().catch(() => undefined)))
|
|
453
|
+
const passports: ExportedPassport[] = []
|
|
454
|
+
const journalCopies: PassportRecord[] = []
|
|
455
|
+
const pendingCommitments: string[] = []
|
|
456
|
+
const brandIds = new Set<string>()
|
|
457
|
+
let offers = 0
|
|
458
|
+
let claims = 0
|
|
459
|
+
// A claim that binds several passports is carried once, however many of them the export holds.
|
|
460
|
+
const claimsCarried = new Set<string>()
|
|
461
|
+
for (const record of journals) {
|
|
462
|
+
const folder = passportFolder(record.passportId)
|
|
463
|
+
const evidence = await indexEvidenceFor(input, record.passportId, folder, exporterKey, exportedAt)
|
|
464
|
+
for (const file of evidence.files) add(file.path, file.category, file.mediaType, file.bytes, { ...(file.represents == null ? {} : { represents: file.represents }), ...(file.representation == null ? {} : { representation: file.representation }) })
|
|
465
|
+
snapshots.push(...evidence.snapshots)
|
|
466
|
+
// Each nested manifest states what the index holds. The writer may hold a record the index lacks.
|
|
467
|
+
const passportOffers = await store.listOffers({ passportId: record.passportId })
|
|
468
|
+
let journal = record
|
|
469
|
+
let offerCopies = passportOffers
|
|
470
|
+
if (v3) {
|
|
471
|
+
// A handover may have changed the journal between its snapshot and the offer read.
|
|
472
|
+
if (sha256Hex(recordBytes(record)) !== sha256Hex(recordBytes(await store.getPassport(record.passportId) ?? null))) {
|
|
473
|
+
throw new PortabilityRefused('store-unstable', 'The passport changed while its custody offers were being read.', { passportId: record.passportId })
|
|
474
|
+
}
|
|
475
|
+
const history = authorised ? journalTransfers(record, wallet.identityKey) : undefined
|
|
476
|
+
let transfers = history?.completed
|
|
477
|
+
if (transfers == null) {
|
|
478
|
+
try {
|
|
479
|
+
transfers = evidence.files.flatMap(file => publicCustodyTransfers(file, file.bytes)).filter(state => state.passportId === record.passportId)
|
|
480
|
+
} catch {
|
|
481
|
+
throw new PortabilityRefused('index-evidence-refused', 'The index evidence cannot be carried as public custody evidence.', { passportId: record.passportId })
|
|
482
|
+
}
|
|
483
|
+
}
|
|
484
|
+
const custody = custodyEvidence(record, passportOffers, transfers, wallet.identityKey, evidence.files.flatMap(file => file.acceptance ?? []), history?.interrupted)
|
|
485
|
+
journal = { ...record, acceptanceRecords: custody.authority }
|
|
486
|
+
offerCopies = custody.offers
|
|
487
|
+
// The nested signature retains the index's dispositions. The outer signature states the custodian's.
|
|
488
|
+
absent.push(...evidence.absent.filter(reference => !/^acceptance:sha256:[0-9a-f]{64}$/.test(reference)), ...custody.absent)
|
|
489
|
+
withheld.push(...custody.withheld)
|
|
490
|
+
pendingCommitments.push(...custody.pending)
|
|
491
|
+
} else {
|
|
492
|
+
const heldAcceptances = new Set(record.acceptanceRecords.map(acceptance => `acceptance:sha256:${acceptanceCommitment(acceptance)}`))
|
|
493
|
+
for (const offer of passportOffers) {
|
|
494
|
+
if (offer.record != null) heldAcceptances.add(`acceptance:sha256:${acceptanceCommitment(offer.record)}`)
|
|
495
|
+
}
|
|
496
|
+
absent.push(...evidence.absent.filter(reference => !heldAcceptances.has(reference)))
|
|
497
|
+
if (!authorised) {
|
|
498
|
+
for (const state of publicTransfers(evidence, record.passportId)) {
|
|
499
|
+
const reference = `acceptance:sha256:${state.authorisationCommitment}`
|
|
500
|
+
if (heldAcceptances.has(reference)) withheld.push(`${reference} not-public`)
|
|
501
|
+
else absent.push(reference)
|
|
502
|
+
}
|
|
503
|
+
}
|
|
504
|
+
}
|
|
505
|
+
sources.push(...evidence.sources)
|
|
506
|
+
journalCopies.push(journal)
|
|
507
|
+
|
|
508
|
+
// How the passport verifies here, now, as any reader would find it. The index only finds the bytes.
|
|
509
|
+
let reading: ExportedReading | undefined
|
|
510
|
+
try {
|
|
511
|
+
reading = summariseReading(await platform.read(record.passportId, v3 ? journal.acceptanceRecords : undefined), platform.chainTracker)
|
|
512
|
+
} catch (cause) {
|
|
513
|
+
absent.push(`reading:${record.passportId} (${cause instanceof Error ? cause.message : String(cause)})`)
|
|
514
|
+
}
|
|
515
|
+
if (reading != null) add(`${folder}/reading.json`, 'reports', JSON_MEDIA_TYPE, recordBytes(reading), { represents: record.passportId, representation: APPLICATION_REPRESENTATIONS.reading })
|
|
516
|
+
|
|
517
|
+
const held = await store.listClaims({ passportId: record.passportId })
|
|
518
|
+
if (authorised) {
|
|
519
|
+
// The journal carries each state's bytes and its sealed owner tier. The tier is ciphertext, sealed to its holder's key, and stays so here.
|
|
520
|
+
add(`${folder}/journal.json`, 'reports', JSON_MEDIA_TYPE, recordBytes(journal), { represents: record.passportId, representation: APPLICATION_REPRESENTATIONS.journal })
|
|
521
|
+
for (const acceptance of journal.acceptanceRecords) {
|
|
522
|
+
const commitment = acceptanceCommitment(acceptance)
|
|
523
|
+
const path = `${folder}/authority/${commitment}.json`
|
|
524
|
+
if (!files.has(path)) add(path, 'authority', JSON_MEDIA_TYPE, recordBytes(acceptance), { represents: `sha256:${commitment}`, representation: acceptance.acceptanceFormat })
|
|
525
|
+
}
|
|
526
|
+
for (const claim of held) {
|
|
527
|
+
if (claimsCarried.has(claim.id)) continue
|
|
528
|
+
claimsCarried.add(claim.id)
|
|
529
|
+
add(`application/claims/${sha256Hex(claim.id)}.json`, 'native-claims', JSON_MEDIA_TYPE, recordBytes(claim), { represents: claim.id, representation: APPLICATION_REPRESENTATIONS.claim })
|
|
530
|
+
// An EPCIS lifecycle claim is also carried as its exact signed bytes, which verify without this application.
|
|
531
|
+
if (isEpcisLifecycleRecord(claim)) add(`application/lifecycle-claims/${sha256Hex(claim.id)}.json`, 'native-claims', EPCIS_LIFECYCLE_MEDIA_TYPE, new TextEncoder().encode(claim.bytes), { represents: claim.attestationId, representation: EPCIS_LIFECYCLE_REPRESENTATION })
|
|
532
|
+
claims += 1
|
|
533
|
+
}
|
|
534
|
+
for (const offer of offerCopies) {
|
|
535
|
+
add(`application/offers/${sha256Hex(offer.requestId)}.json`, 'reports', JSON_MEDIA_TYPE, recordBytes(offer), { represents: offer.requestId, representation: APPLICATION_REPRESENTATIONS.offer })
|
|
536
|
+
offers += 1
|
|
537
|
+
}
|
|
538
|
+
brandIds.add(record.brandId)
|
|
539
|
+
}
|
|
540
|
+
const tip = record.states[record.states.length - 1]!
|
|
541
|
+
const bindingDigest = declaredBindingDigest(tip.payloadPublic)
|
|
542
|
+
passports.push({
|
|
543
|
+
passportId: record.passportId,
|
|
544
|
+
folder,
|
|
545
|
+
profile: record.profile,
|
|
546
|
+
...(bindingDigest == null ? {} : { bindingDigest }),
|
|
547
|
+
status: record.status,
|
|
548
|
+
states: record.states.length,
|
|
549
|
+
genesis: record.states[0]!.txid,
|
|
550
|
+
tip: tip.txid,
|
|
551
|
+
index: evidence.summary,
|
|
552
|
+
acceptanceRecords: authorised ? journal.acceptanceRecords.length : 0,
|
|
553
|
+
claims: authorised ? held.length : 0,
|
|
554
|
+
})
|
|
555
|
+
}
|
|
556
|
+
let brands = 0
|
|
557
|
+
if (authorised) {
|
|
558
|
+
for (const brandId of [...brandIds].sort()) {
|
|
559
|
+
const brand = await store.getBrand(brandId)
|
|
560
|
+
if (brand == null) {
|
|
561
|
+
// Said by name, so that a restore can tell a record this deployment never held from one that was left out.
|
|
562
|
+
absent.push(`brand:${brandId} (this application holds no record of it)`)
|
|
563
|
+
continue
|
|
564
|
+
}
|
|
565
|
+
add(`application/brands/${sha256Hex(brand.id)}.json`, 'reports', JSON_MEDIA_TYPE, recordBytes(brand), { represents: brand.id, representation: APPLICATION_REPRESENTATIONS.brand })
|
|
566
|
+
brands += 1
|
|
567
|
+
}
|
|
568
|
+
snapshots.push({ source: 'application-records', snapshotId: sha256Hex(recordBytes(journalCopies)), completeForSnapshot: true, scope: `${journals.length} passport journal${journals.length === 1 ? '' : 's'} with the brands, offers and claims that belong to them, read twice and found equal` })
|
|
569
|
+
}
|
|
570
|
+
|
|
571
|
+
/* ---- the profiles those records declare ---- */
|
|
572
|
+
|
|
573
|
+
const declared = [...new Set(journals.map((record) => record.profile))].sort()
|
|
574
|
+
const carried = declared.filter((profile) => profiles.get(profile) != null)
|
|
575
|
+
const named = declared.filter((profile) => profiles.get(profile) == null)
|
|
576
|
+
for (const profile of named) {
|
|
577
|
+
// A profile a manifest of the profiles package defines ships with that package. One this deployment holds no definition of is said to be absent.
|
|
578
|
+
if (isProfileId(profile) || isRetiredProfile(profile)) withheld.push(`profile ${profile} defined-by-the-profiles-package`)
|
|
579
|
+
else absent.push(`profile:${profile} (this deployment holds no definition of it)`)
|
|
580
|
+
}
|
|
581
|
+
let bundleProfiles: string[] = []
|
|
582
|
+
if (carried.length > 0) {
|
|
583
|
+
const bundle = await exportProfileBundle({
|
|
584
|
+
registry: profiles.registry,
|
|
585
|
+
profiles: carried,
|
|
586
|
+
readNotice: (profile, path) => profiles.readNotice(profile, path),
|
|
587
|
+
licenceTexts: await profiles.licenceTexts(),
|
|
588
|
+
// GS1's files are named by address and digest. They are in no file of the package.
|
|
589
|
+
provisioned: EPCIS_GS1_ARTEFACTS,
|
|
590
|
+
root: PROFILES_ROOT,
|
|
591
|
+
})
|
|
592
|
+
if (!bundle.ok) throw new PortabilityRefused('profile-export-refused', `The profiles were not exported (${bundle.code}): ${bundle.detail} Nothing was exported.`, { code: bundle.code, ...(bundle.profile == null ? {} : { profile: bundle.profile }) })
|
|
593
|
+
bundle.inventory.forEach((entry) => add(entry.path, entry.category, entry.mediaType, bundle.files.get(entry.path)!, { represents: entry.represents, representation: entry.representation }))
|
|
594
|
+
withheld.push(...bundle.manifest.withheld)
|
|
595
|
+
bundleProfiles = bundle.manifest.profiles
|
|
596
|
+
}
|
|
597
|
+
for (const artefact of EPCIS_GS1_ARTEFACTS) {
|
|
598
|
+
const line = describeProfileBundleOmission(artefact)
|
|
599
|
+
if (!withheld.includes(line)) withheld.push(line)
|
|
600
|
+
}
|
|
601
|
+
omitted.push({ what: 'gs1-files', reason: 'provisioned-by-destination', detail: `${EPCIS_GS1_ARTEFACTS.length} files GS1 publishes, each named by address and digest in the manifest` })
|
|
602
|
+
|
|
603
|
+
/* ---- the EPCIS exchange ---- */
|
|
604
|
+
|
|
605
|
+
let epcis: ApplicationExportDescriptor['epcis'] = { scopes: [] }
|
|
606
|
+
let snapshot: ExportedEpcisRecovery | undefined
|
|
607
|
+
if (authorised) {
|
|
608
|
+
const exported = await exportEpcisRecovery({ storage: input.epcis.storage, cursors: input.cursors ?? 'exclude', credentials, root: EPCIS_ROOT, now: () => exportedAt })
|
|
609
|
+
if (exported.ok) snapshot = exported
|
|
610
|
+
else if (exported.code === 'no-source-scope') epcis = { scopes: [], reason: 'the exchange holds no source scope' }
|
|
611
|
+
else throw new PortabilityRefused('epcis-export-refused', `The EPCIS exchange was not exported (${exported.code}): ${exported.detail} Nothing was exported.`, { code: exported.code, ...(exported.breaches == null ? {} : { breaches: exported.breaches }), ...(exported.path == null ? {} : { path: exported.path }) })
|
|
612
|
+
} else if ((input.publicSources ?? []).length > 0) {
|
|
613
|
+
const allowed = new Set(input.publicSources)
|
|
614
|
+
const exported = await exportEpcisPublicEvidence({ storage: input.epcis.storage, allow: (record) => allowed.has(record.sourceId), sourceIds: [...allowed], credentials, root: EPCIS_ROOT, now: () => exportedAt })
|
|
615
|
+
if (exported.ok) snapshot = exported
|
|
616
|
+
else if (exported.code === 'nothing-public') epcis = { scopes: [], reason: 'the source scopes named hold no import a public export may carry' }
|
|
617
|
+
else throw new PortabilityRefused('epcis-export-refused', `The public form of the EPCIS exchange was not exported (${exported.code}): ${exported.detail} Nothing was exported.`, { code: exported.code, ...(exported.sourceId == null ? {} : { sourceId: exported.sourceId }) })
|
|
618
|
+
} else {
|
|
619
|
+
epcis = { scopes: [], reason: 'no source scope was named as one a public export may carry' }
|
|
620
|
+
withheld.push('epcis-exchange every-source-scope not-public')
|
|
621
|
+
}
|
|
622
|
+
if (snapshot != null) {
|
|
623
|
+
snapshot.inventory.forEach((entry) => add(entry.path, entry.category, entry.mediaType, snapshot.files.get(entry.path)!, { represents: entry.represents, representation: entry.representation }))
|
|
624
|
+
snapshots.push(...snapshot.manifest.snapshots)
|
|
625
|
+
withheld.push(...snapshot.manifest.withheld)
|
|
626
|
+
epcis = {
|
|
627
|
+
root: snapshot.root,
|
|
628
|
+
access: snapshot.descriptor.access,
|
|
629
|
+
snapshotId: snapshot.descriptor.snapshot.snapshotId,
|
|
630
|
+
scopes: snapshot.descriptor.scopes.map((scope) => scope.sourceId),
|
|
631
|
+
cursors: snapshot.descriptor.cursors,
|
|
632
|
+
// How each source was reached, for the operator who configures it again. Never its credential, and never in a public export.
|
|
633
|
+
...(authorised ? { sources: input.epcis.sources.map((source) => { const { problem: _problem, ...described } = describeEpcisSource(source); return described }) } : {}),
|
|
634
|
+
}
|
|
635
|
+
}
|
|
636
|
+
|
|
637
|
+
/* ---- what is left out, said once ---- */
|
|
638
|
+
|
|
639
|
+
omitted.push(
|
|
640
|
+
{ what: 'wallet-keys', reason: 'never-carried', detail: 'the wallet root key, the wallet file, and the secrets brand, recipient and member keys are derived from' },
|
|
641
|
+
{ what: 'endpoint-credentials', reason: 'never-carried', detail: 'the index, registry and validator tokens and every EPCIS source credential' },
|
|
642
|
+
{ what: 'sign-in', reason: 'never-carried', detail: 'accounts, sessions and memberships of brands' },
|
|
643
|
+
{ what: 'spend-ledger', reason: 'excluded', detail: 'the daily spend counter, which belongs to the wallet that is left' },
|
|
644
|
+
{ what: 'index-records', reason: 'rebuilt-at-destination', detail: 'the destination\'s index is given each state again and builds its own records' }
|
|
645
|
+
)
|
|
646
|
+
if (!authorised) {
|
|
647
|
+
omitted.push(
|
|
648
|
+
{ what: 'passport-journals', reason: 'not-public', detail: 'each state\'s sealed owner tier, its holder and its operational answers' },
|
|
649
|
+
{ what: 'brands-offers-claims', reason: 'not-public' },
|
|
650
|
+
{ what: 'epcis-operational-records', reason: 'not-public', detail: 'request bindings, observations, conflict decisions, pull state and how each source was reached' }
|
|
651
|
+
)
|
|
652
|
+
withheld.push('application passport-journals not-public', 'application brands-offers-claims not-public')
|
|
653
|
+
}
|
|
654
|
+
for (const entry of omitted) if (entry.reason === 'never-carried') withheld.push(`application ${entry.what} never-carried`)
|
|
655
|
+
|
|
656
|
+
const descriptor: ApplicationExportDescriptor = {
|
|
657
|
+
format: APPLICATION_EXPORT_FORMAT,
|
|
658
|
+
version: APPLICATION_EXPORT_VERSION,
|
|
659
|
+
access,
|
|
660
|
+
exportId,
|
|
661
|
+
exportedAt,
|
|
662
|
+
selection: input.passportIds == null ? 'all-passports' : 'listed-passports',
|
|
663
|
+
application: { network: config.network, identifiers: { host: config.passportHost, prefix: config.gs1Prefix }, publisherKey: wallet.identityKey },
|
|
664
|
+
passports,
|
|
665
|
+
profiles: { ...(bundleProfiles.length === 0 ? {} : { root: PROFILES_ROOT }), carried: bundleProfiles, named },
|
|
666
|
+
epcis,
|
|
667
|
+
records: { brands, offers, claims },
|
|
668
|
+
omitted,
|
|
669
|
+
limits: APPLICATION_EXPORT_LIMITS,
|
|
670
|
+
}
|
|
671
|
+
add(APPLICATION_EXPORT_DESCRIPTOR, 'reports', JSON_MEDIA_TYPE, recordBytes(descriptor), { represents: exportId, representation: APPLICATION_REPRESENTATIONS.descriptor })
|
|
672
|
+
|
|
673
|
+
/* ---- the manifest, signed under the publisher key ---- */
|
|
674
|
+
|
|
675
|
+
const signer = evidencePackageSigner(wallet.identityKey, exportId)
|
|
676
|
+
const manifestProfiles = [...new Set([...bundleProfiles, ...named, ...(v3 ? [MANAGED_CUSTODY_EXPORT_PROFILE] : [])])].filter((profile) => /^[a-z][a-z0-9.-]*@[0-9][0-9a-z.-]*$/.test(profile)).sort()
|
|
677
|
+
const manifest = await signEvidenceManifest(
|
|
678
|
+
{
|
|
679
|
+
format: EVIDENCE_PACKAGE_FORMAT,
|
|
680
|
+
version: EVIDENCE_PACKAGE_VERSION,
|
|
681
|
+
// A package that carries an export names the export here, not one passport (spec/portable-evidence.md section 2).
|
|
682
|
+
passportId: exportId,
|
|
683
|
+
exportedAt,
|
|
684
|
+
exporter: { id: wallet.identityKey, role: 'writer', software: SOFTWARE },
|
|
685
|
+
...(manifestProfiles.length === 0 ? {} : { profiles: manifestProfiles }),
|
|
686
|
+
disclosure: authorised ? { scope: 'all-tiers', recoveryBackup: true } : { scope: 'public', recoveryBackup: false },
|
|
687
|
+
completeness: { snapshots, withheld: [...new Set(withheld)], absent: [...new Set(absent)] },
|
|
688
|
+
sources,
|
|
689
|
+
inventory,
|
|
690
|
+
signature: { suite: 'bsv-ecdsa-der', signer },
|
|
691
|
+
},
|
|
692
|
+
// The wallet signs the preimage under the evidence package protocol, the export's name and the "anyone" counterparty, so any reader derives the signer from the publisher key alone.
|
|
693
|
+
{ sign: async (preimage) => (await wallet.custodian.createSignature({ data: preimage, protocolID: EVIDENCE_PACKAGE_PROTOCOL, keyID: exportId, counterparty: 'anyone' })).signature }
|
|
694
|
+
)
|
|
695
|
+
|
|
696
|
+
// Checked as a destination will check it, before anything is handed over.
|
|
697
|
+
const inspection = inspectEvidencePackage(manifest, asNumberArrays(files), { expectedPassportId: exportId, expectedSigner: signer })
|
|
698
|
+
if (!inspection.structureValid || !inspection.inventoryVerified || inspection.signatureValid !== true || inspection.failures.length > 0) {
|
|
699
|
+
throw new PortabilityRefused('export-unsound', `The export does not inspect as the package it should be: ${inspection.failures.map((failure) => failure.detail).join('; ')}. Nothing is handed over.`, { failures: inspection.failures.map((failure) => failure.reason) })
|
|
700
|
+
}
|
|
701
|
+
if (pendingCommitments.length > 0 && secretCarrier(files, JSON.stringify(manifest), pendingCommitments, pendingCommitments) != null) {
|
|
702
|
+
throw new PortabilityRefused('export-unsound', 'The public export exposes a commitment held only with a pending offer.')
|
|
703
|
+
}
|
|
704
|
+
const carrier = secretCarrier(files, JSON.stringify(manifest), configuredSecrets(config, credentials))
|
|
705
|
+
if (carrier != null) throw new PortabilityRefused('secret-in-export', `The file ${carrier} holds a secret this deployment was configured with. Nothing is handed over. Find how it reached a record or a retained source, and rotate it.`, { path: carrier })
|
|
706
|
+
|
|
707
|
+
return { manifest, files, descriptor, exporter: { identityKey: wallet.identityKey, signer } }
|
|
708
|
+
}
|