@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
|
@@ -4,14 +4,16 @@
|
|
|
4
4
|
// claims. In development with no INDEX_URL an index runs in this process.
|
|
5
5
|
import { MongoClient, type Db } from 'mongodb'
|
|
6
6
|
import type { ChainTracker } from '@bsv/sdk'
|
|
7
|
-
import {
|
|
7
|
+
import { openBoundProfiles, type BoundProfiles } from './bound-profiles.js'
|
|
8
|
+
import { Claims, type ClaimsOptions } from './claims.js'
|
|
9
|
+
import { openLifecycleAuthority } from './lifecycle-authority.js'
|
|
8
10
|
import type { Config } from './config.js'
|
|
9
11
|
import { Custody } from './custody.js'
|
|
10
12
|
import { startDevIndex, type DevIndex } from './dev-index.js'
|
|
11
13
|
import { IndexClient } from './index-client.js'
|
|
12
|
-
import { managedParties, type Parties } from './parties.js'
|
|
13
|
-
import { headerSource, readPassport, type PassportReading } from './reader.js'
|
|
14
|
-
import { MemoryStore, MongoStore, type Store } from './store.js'
|
|
14
|
+
import { managedParties, type Parties, type Party } from './parties.js'
|
|
15
|
+
import { headerSource, readAuthorised, readPassport, type AuthorisedReading, type PassportReading } from './reader.js'
|
|
16
|
+
import { MemoryStore, MongoStore, type PassportRecord, type Store } from './store.js'
|
|
15
17
|
import { openTestWallet, openToolboxWallet, type PlatformWallet } from './wallet.js'
|
|
16
18
|
import { Writer } from './writer.js'
|
|
17
19
|
|
|
@@ -19,28 +21,47 @@ export interface Platform {
|
|
|
19
21
|
config: Config
|
|
20
22
|
store: Store
|
|
21
23
|
db?: Db
|
|
24
|
+
/** The index in this process, when the app has not joined one. */
|
|
25
|
+
devIndex?: DevIndex
|
|
22
26
|
wallet: PlatformWallet
|
|
23
27
|
parties: Parties
|
|
24
28
|
index: IndexClient
|
|
25
29
|
writer: Writer
|
|
26
30
|
custody: Custody
|
|
27
31
|
claims: Claims
|
|
32
|
+
lifecyclePolicy: Pick<ClaimsOptions, 'authorityResolver' | 'extensionRules'>
|
|
28
33
|
chainTracker: ChainTracker | 'scripts only'
|
|
29
|
-
|
|
34
|
+
/** The profiles held by a binding, the validation engine and anything refused at start-up. */
|
|
35
|
+
profiles: BoundProfiles
|
|
36
|
+
/** Exporters can limit verification to the acceptance records carried in this disclosure. */
|
|
37
|
+
read(passportId: string, acceptanceRecords?: PassportRecord['acceptanceRecords']): Promise<PassportReading>
|
|
38
|
+
/** The holder's view of a passport under a bound profile: the owner-tier check, then the two parts rejoined and checked whole. */
|
|
39
|
+
readAuthorised(record: PassportRecord, holder: Party): Promise<AuthorisedReading>
|
|
30
40
|
close(): Promise<void>
|
|
31
41
|
}
|
|
32
42
|
|
|
33
43
|
export interface PlatformOptions {
|
|
34
44
|
config: Config
|
|
45
|
+
lifecyclePolicy?: Pick<ClaimsOptions, 'authorityResolver' | 'extensionRules'>
|
|
35
46
|
/** 'test' wires a memory store, a test wallet and an in-process index with nothing live. */
|
|
36
47
|
mode: 'live' | 'test'
|
|
37
48
|
log?: (line: string) => void
|
|
49
|
+
/** How a validation library is loaded; a test passes one that fails, to stand in for libraries that are not installed. */
|
|
50
|
+
loadEngineLibrary?: (name: string) => Promise<unknown>
|
|
38
51
|
}
|
|
39
52
|
|
|
53
|
+
/** How long a call waits for MongoDB to be reachable before it fails. It bounds start-up without a database, and every call made while the database is away. */
|
|
54
|
+
export const MONGO_SERVER_SELECTION_TIMEOUT_MS = 2_000
|
|
55
|
+
|
|
40
56
|
export async function openPlatform(options: PlatformOptions): Promise<Platform> {
|
|
41
57
|
const { config, mode } = options
|
|
42
58
|
const log = options.log ?? ((line: string) => console.log(line))
|
|
43
59
|
|
|
60
|
+
const lifecyclePolicy = {
|
|
61
|
+
authorityResolver: options.lifecyclePolicy?.authorityResolver ?? (config.lifecycleAuthorityGrantsFile == null ? undefined : openLifecycleAuthority(config.lifecycleAuthorityGrantsFile)),
|
|
62
|
+
extensionRules: options.lifecyclePolicy?.extensionRules,
|
|
63
|
+
}
|
|
64
|
+
|
|
44
65
|
let client: MongoClient | undefined
|
|
45
66
|
let db: Db | undefined
|
|
46
67
|
let store: Store
|
|
@@ -50,7 +71,7 @@ export async function openPlatform(options: PlatformOptions): Promise<Platform>
|
|
|
50
71
|
// MongoDB holds the records, the journal and sign-in. Without one, development
|
|
51
72
|
// runs on memory: everything is forgotten on restart and sign-in is unavailable.
|
|
52
73
|
try {
|
|
53
|
-
client = new MongoClient(config.mongoUrl, { serverSelectionTimeoutMS:
|
|
74
|
+
client = new MongoClient(config.mongoUrl, { serverSelectionTimeoutMS: MONGO_SERVER_SELECTION_TIMEOUT_MS })
|
|
54
75
|
await client.connect()
|
|
55
76
|
db = client.db(config.mongoDb)
|
|
56
77
|
const mongo = new MongoStore(db)
|
|
@@ -64,53 +85,87 @@ export async function openPlatform(options: PlatformOptions): Promise<Platform>
|
|
|
64
85
|
}
|
|
65
86
|
}
|
|
66
87
|
|
|
88
|
+
// DPP_TEST_WALLET=1 is the scaffold check's switch: the test wallet on the
|
|
89
|
+
// configured root key, so go-live registers the key .env holds without a
|
|
90
|
+
// funded wallet. A user never sets it; live mode says so when it is set.
|
|
91
|
+
const testWalletRequested = config.testWallet && config.wallet.rootKeyHex != null
|
|
67
92
|
const wallet =
|
|
68
93
|
mode === 'test' || config.wallet.rootKeyHex == null
|
|
69
94
|
? openTestWallet(undefined, config.network)
|
|
70
|
-
:
|
|
71
|
-
|
|
95
|
+
: testWalletRequested
|
|
96
|
+
? openTestWallet(config.wallet.rootKeyHex, config.network)
|
|
97
|
+
: await openToolboxWallet({ network: config.network, rootKeyHex: config.wallet.rootKeyHex, filePath: config.wallet.filePath, wocApiKey: config.wallet.wocApiKey, arcUrl: config.wallet.arcUrl })
|
|
98
|
+
if (mode === 'live' && wallet.kind === 'test') {
|
|
99
|
+
log(testWalletRequested ? 'DPP_TEST_WALLET=1: the test wallet stands in on the configured root key, with made-up funds; nothing can be written to the chain.' : 'WALLET_ROOT_KEY is not set: a test wallet with fixed keys stands in, and nothing can be written to the chain.')
|
|
100
|
+
}
|
|
72
101
|
|
|
73
102
|
let devIndex: DevIndex | undefined
|
|
74
103
|
let index: IndexClient
|
|
75
|
-
if (config.index.
|
|
76
|
-
index = new IndexClient({ url: config.index.url
|
|
104
|
+
if (config.index.joined) {
|
|
105
|
+
index = new IndexClient({ url: config.index.url!, submitToken: config.index.submitToken, callbackToken: config.index.callbackToken, supportsRetraction: config.index.supportsRetraction })
|
|
77
106
|
} else {
|
|
78
|
-
|
|
79
|
-
|
|
80
|
-
|
|
107
|
+
// An address with no tokens is an index this app has not joined yet: it
|
|
108
|
+
// would answer 401 to every write. The in-process index stands in until
|
|
109
|
+
// go-live registers the key and stores the tokens.
|
|
110
|
+
devIndex = await startDevIndex({ publisherKey: wallet.identityKey, network: config.network })
|
|
111
|
+
index = new IndexClient({ url: devIndex.url, submitToken: devIndex.submitToken, callbackToken: devIndex.callbackToken, supportsRetraction: true })
|
|
112
|
+
if (mode === 'live') {
|
|
113
|
+
log(
|
|
114
|
+
config.index.url == null
|
|
115
|
+
? `INDEX_URL is not set: an index runs in this process at ${devIndex.url} with in-memory storage; it forgets everything on restart and claims no inclusion.`
|
|
116
|
+
: `This app has not joined ${config.index.url} yet (no tokens): an index runs in this process at ${devIndex.url} with in-memory storage until npm run go-live registers the publisher key.`
|
|
117
|
+
)
|
|
118
|
+
}
|
|
81
119
|
}
|
|
82
120
|
|
|
121
|
+
// Built once: the engine the configuration chose, the bound profiles from the package's folder or from a bundle, and any folder the configuration trusts.
|
|
122
|
+
const profiles = await openBoundProfiles({
|
|
123
|
+
customProfileDirs: config.customProfiles.dirs,
|
|
124
|
+
trustedBindingDigests: config.customProfiles.trustedBindingDigests,
|
|
125
|
+
...(config.profileBundleDir == null ? {} : { profileBundleDir: config.profileBundleDir }),
|
|
126
|
+
validator: config.validator,
|
|
127
|
+
...(options.loadEngineLibrary == null ? {} : { loadEngineLibrary: options.loadEngineLibrary }),
|
|
128
|
+
log,
|
|
129
|
+
})
|
|
130
|
+
|
|
83
131
|
const parties = managedParties({ brandRootSecret: config.brandRootSecret, managedIdentitySecret: config.managedIdentitySecret })
|
|
84
132
|
const writer = new Writer({
|
|
85
133
|
store,
|
|
86
134
|
wallet,
|
|
87
135
|
index,
|
|
88
136
|
identifiers: { host: config.passportHost, prefix: config.gs1Prefix },
|
|
137
|
+
bound: profiles,
|
|
89
138
|
livePublishing: config.livePublishing,
|
|
90
139
|
spendCapSatoshis: config.spendCapSatoshis,
|
|
91
140
|
log,
|
|
92
141
|
})
|
|
93
142
|
const custody = new Custody({ store, wallet, parties, writer })
|
|
94
|
-
const claims = new Claims({ store, registry: config.registry.url == null ? undefined : { url: config.registry.url, token: config.registry.token } })
|
|
143
|
+
const claims = new Claims({ store, ...lifecyclePolicy, registry: config.registry.url == null ? undefined : { url: config.registry.url, token: config.registry.token } })
|
|
95
144
|
// Inclusion can only be checked against a header source; the in-process index and the test wallet mine nothing.
|
|
96
|
-
const chainTracker: ChainTracker | 'scripts only' = wallet.kind === 'toolbox' && config.index.
|
|
145
|
+
const chainTracker: ChainTracker | 'scripts only' = wallet.kind === 'toolbox' && config.index.joined ? headerSource(config.network, config.wallet.wocApiKey) : 'scripts only'
|
|
97
146
|
|
|
98
147
|
return {
|
|
99
148
|
config,
|
|
100
149
|
store,
|
|
101
150
|
db,
|
|
151
|
+
...(devIndex == null ? {} : { devIndex }),
|
|
102
152
|
wallet,
|
|
103
153
|
parties,
|
|
104
154
|
index,
|
|
105
155
|
writer,
|
|
106
156
|
custody,
|
|
107
157
|
claims,
|
|
158
|
+
lifecyclePolicy,
|
|
108
159
|
chainTracker,
|
|
109
|
-
|
|
160
|
+
profiles,
|
|
161
|
+
async readAuthorised(record, holder) {
|
|
162
|
+
return await readAuthorised({ record, holder, index, profiles })
|
|
163
|
+
},
|
|
164
|
+
async read(passportId, acceptanceRecords) {
|
|
110
165
|
// A passport this platform wrote: its brand is the genesis issuer the policy names, and its acceptance records are supplied. Another platform's passport is read with what the index holds, and authority stays unknown.
|
|
111
166
|
const own = await store.getPassport(passportId)
|
|
112
167
|
const genesisIssuers = own == null ? [] : [parties.brand(own.brandId).identityKey]
|
|
113
|
-
return await readPassport(passportId, { index, chainTracker, acceptanceCustodians: [wallet.identityKey], genesisIssuers }, { acceptanceRecords: own?.acceptanceRecords ?? [] })
|
|
168
|
+
return await readPassport(passportId, { index, chainTracker, acceptanceCustodians: [wallet.identityKey], genesisIssuers, profiles }, { acceptanceRecords: acceptanceRecords ?? own?.acceptanceRecords ?? [] })
|
|
114
169
|
},
|
|
115
170
|
async close() {
|
|
116
171
|
await wallet.close()
|
|
@@ -0,0 +1,224 @@
|
|
|
1
|
+
// The operator's commands for moving this application: export, restore and
|
|
2
|
+
// declaring that an EPCIS source moved. They are run on the host, by whoever
|
|
3
|
+
// holds the deployment's settings, with the API and its worker stopped. That
|
|
4
|
+
// is the authorisation: there is no route for any of them, because the API
|
|
5
|
+
// has no operator role to give one to, and a signed-in member of a brand is
|
|
6
|
+
// not the operator of the deployment.
|
|
7
|
+
//
|
|
8
|
+
// export --out <folder> [--public] [--passport <id>]... [--public-source <name>]... [--cursors include] [--custody-profile managed-custody@3]
|
|
9
|
+
// restore --from <folder> [--exporter-key <key>] [--index-exporter-key <key>] [--report <file>] [--require-custody-profile managed-custody@3]
|
|
10
|
+
// epcis-remap --source <name>
|
|
11
|
+
//
|
|
12
|
+
// Each opens the platform from the configuration, as the API does, and calls
|
|
13
|
+
// the functions beside this file. None of them writes a state, signs for
|
|
14
|
+
// anyone but this application as the exporter of a package, or touches
|
|
15
|
+
// custody.
|
|
16
|
+
import { lookup } from 'node:dns/promises'
|
|
17
|
+
import { writeFileSync } from 'node:fs'
|
|
18
|
+
import { resolve } from 'node:path'
|
|
19
|
+
import { parseArgs } from 'node:util'
|
|
20
|
+
import { remapEpcisSourceEndpoint } from '@bsv/dpp-credentials/epcis-exchange'
|
|
21
|
+
import { MANAGED_CUSTODY_EXPORT_PROFILE } from '@bsv/dpp-protocol'
|
|
22
|
+
import { loadConfig } from '../config.js'
|
|
23
|
+
import { openExchangeStorage } from '../epcis/exchange.js'
|
|
24
|
+
import { openPlatform } from '../platform.js'
|
|
25
|
+
import { exportApplication } from './export.js'
|
|
26
|
+
import { PortabilityRefused, readPackageFolder, writePackageFolder } from './package.js'
|
|
27
|
+
import { restoreApplication, verifyApplicationPackage, type RestoreReport } from './restore.js'
|
|
28
|
+
|
|
29
|
+
export interface CommandContext {
|
|
30
|
+
env: NodeJS.ProcessEnv
|
|
31
|
+
/** One line of the command's answer. */
|
|
32
|
+
out: (line: string) => void
|
|
33
|
+
/** The folder a relative path is read from: where the command was called. */
|
|
34
|
+
cwd: string
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const PORTABILITY_USAGE =
|
|
38
|
+
'export --out <folder> [--public] [--passport <id>]... [--public-source <name>]... [--cursors include] [--custody-profile managed-custody@3] | restore --from <folder> [--exporter-key <key>] [--index-exporter-key <key>] [--report <file>] [--require-custody-profile managed-custody@3] | epcis-remap --source <name>'
|
|
39
|
+
|
|
40
|
+
/** The command's options, or nothing when one was given that the command does not take: the caller then prints how it is used. */
|
|
41
|
+
function optionsOf<T>(read: () => T, context: CommandContext): T | undefined {
|
|
42
|
+
try {
|
|
43
|
+
return read()
|
|
44
|
+
} catch (cause) {
|
|
45
|
+
context.out(cause instanceof Error ? cause.message : String(cause))
|
|
46
|
+
return undefined
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
/** A refusal is the command's answer, with its code. Anything else is a failure and is thrown on. */
|
|
51
|
+
async function answering(context: CommandContext, run: () => Promise<number>): Promise<number> {
|
|
52
|
+
try {
|
|
53
|
+
return await run()
|
|
54
|
+
} catch (cause) {
|
|
55
|
+
if (cause instanceof PortabilityRefused) {
|
|
56
|
+
context.out(`Refused (${cause.code}): ${cause.message}`)
|
|
57
|
+
return 1
|
|
58
|
+
}
|
|
59
|
+
throw cause
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
function custodyProfileOption(value: string | undefined, context: CommandContext): typeof MANAGED_CUSTODY_EXPORT_PROFILE | undefined | false {
|
|
64
|
+
if (value === undefined || value === MANAGED_CUSTODY_EXPORT_PROFILE) return value
|
|
65
|
+
context.out(`Refused (not-selected): Unsupported custody export profile ${JSON.stringify(value)}. Nothing was written.`)
|
|
66
|
+
return false
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
/** Write the complete export of this application into an empty folder. */
|
|
70
|
+
export async function runExportCommand(args: string[], context: CommandContext): Promise<number> {
|
|
71
|
+
const values = optionsOf(() => parseArgs({ args, options: { out: { type: 'string' }, public: { type: 'boolean', default: false }, passport: { type: 'string', multiple: true }, 'public-source': { type: 'string', multiple: true }, cursors: { type: 'string' }, 'custody-profile': { type: 'string' } } }).values, context)
|
|
72
|
+
if (values?.out == null) {
|
|
73
|
+
context.out('usage: export --out <folder> [--public] [--passport <id>]... [--public-source <name>]... [--cursors include] [--custody-profile managed-custody@3]')
|
|
74
|
+
return 2
|
|
75
|
+
}
|
|
76
|
+
if (values.cursors != null && values.cursors !== 'include' && values.cursors !== 'exclude') {
|
|
77
|
+
context.out('--cursors is include or exclude')
|
|
78
|
+
return 2
|
|
79
|
+
}
|
|
80
|
+
const custodyProfile = custodyProfileOption(values['custody-profile'], context)
|
|
81
|
+
if (custodyProfile === false) return 1
|
|
82
|
+
const folder = resolve(context.cwd, values.out)
|
|
83
|
+
const config = loadConfig(context.env)
|
|
84
|
+
const platform = await openPlatform({ config, mode: 'live', log: () => {} })
|
|
85
|
+
const store = await openExchangeStorage({ setting: config.epcis.storage, ...(platform.db == null ? {} : { db: platform.db }), log: () => {} })
|
|
86
|
+
try {
|
|
87
|
+
return await answering(context, async () => {
|
|
88
|
+
// Without its database this process holds no record of the deployment, and an export of nothing would read as an export of everything.
|
|
89
|
+
if (platform.db == null) throw new PortabilityRefused('source-not-reachable', 'MongoDB is not reachable, so this command has none of the deployment\'s records to export. Nothing was exported.')
|
|
90
|
+
const exported = await exportApplication({
|
|
91
|
+
platform,
|
|
92
|
+
epcis: { storage: store.storage, sources: config.epcis.sources },
|
|
93
|
+
access: values.public ? 'public-evidence' : 'authorised-recovery',
|
|
94
|
+
custodyProfile,
|
|
95
|
+
...(values.passport == null ? {} : { passportIds: values.passport }),
|
|
96
|
+
...(values['public-source'] == null ? {} : { publicSources: values['public-source'] }),
|
|
97
|
+
...(values.cursors == null ? {} : { cursors: values.cursors as 'include' | 'exclude' }),
|
|
98
|
+
})
|
|
99
|
+
writePackageFolder(folder, exported.manifest, exported.files)
|
|
100
|
+
const { descriptor } = exported
|
|
101
|
+
const withoutIndex = descriptor.passports.filter((passport) => passport.index.form === 'none')
|
|
102
|
+
context.out(`${values.public ? 'Public export' : 'Authorised export'} written to ${folder}: ${exported.files.size + 1} files under one signed manifest.`)
|
|
103
|
+
context.out(`Passports: ${descriptor.passports.length}${descriptor.selection === 'all-passports' ? ', every one in the journal' : ', the ones named'}. Profiles carried: ${descriptor.profiles.carried.join(', ') || 'none'}${descriptor.profiles.named.length === 0 ? '' : `; named and not carried: ${descriptor.profiles.named.join(', ')}`}.`)
|
|
104
|
+
context.out(descriptor.epcis.root == null ? `EPCIS exchange: nothing carried (${descriptor.epcis.reason}).` : `EPCIS exchange: the ${descriptor.epcis.access === 'authorised-recovery' ? 'recovery snapshot' : 'public form'} of ${descriptor.epcis.scopes.join(', ')}, cursors ${descriptor.epcis.cursors}.`)
|
|
105
|
+
if (withoutIndex.length > 0) context.out(`The index gave no evidence for ${withoutIndex.length} passport${withoutIndex.length === 1 ? '' : 's'}: ${withoutIndex.map((passport) => `${passport.passportId} (${passport.index.reason})`).join('; ')}. The manifest declares each absent.`)
|
|
106
|
+
context.out(`Exporter identity key, which a restore is given: ${exported.exporter.identityKey}`)
|
|
107
|
+
// The test wallet's keys are fixed and public knowledge, so anyone can make this signature. The package is then held together by its digests and vouched for by nobody.
|
|
108
|
+
if (platform.wallet.kind === 'test') context.out('This deployment has no wallet root key: the export is signed by the test wallet, whose key is public. Its signature says nothing about who assembled the package.')
|
|
109
|
+
context.out(values.public ? 'A public export is not a recovery backup, and a restore refuses it.' : 'This folder holds restricted records. It holds no key and no credential: the wallet\'s keys travel by the wallet\'s own recovery, and each credential is configured again at the destination.')
|
|
110
|
+
return 0
|
|
111
|
+
})
|
|
112
|
+
} finally {
|
|
113
|
+
await store.close()
|
|
114
|
+
await platform.close()
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
/** One line per thing the restore did, then what is the operator's to provide and what needs attention. */
|
|
119
|
+
function printReport(report: RestoreReport, out: (line: string) => void): void {
|
|
120
|
+
out(`Restore ${report.outcome}: export ${report.exportId.slice(-16)} of ${report.exportedAt}, exported by ${report.exporter}.`)
|
|
121
|
+
out(`Passports: ${report.passports.written.length} written, ${report.passports.unchanged.length} already held and equal. Brands ${report.records.brands.written}/${report.records.brands.unchanged}, offers ${report.records.offers.written}/${report.records.offers.unchanged}, claims ${report.records.claims.written}/${report.records.claims.unchanged} (written/unchanged).`)
|
|
122
|
+
out(`Profiles: resolved from ${report.profiles.resolver === 'bundle' ? `the bundle in ${report.profiles.folder}` : 'the installed profiles package'}; ${report.profiles.filesWritten} bundle files written, ${report.profiles.filesUnchanged} unchanged; held now: ${report.profiles.registered.map((entry) => entry.profile).join(', ') || 'none of the carried ones'}.`)
|
|
123
|
+
if (report.epcis != null) out(`EPCIS exchange: ${report.epcis.outcome}; ${report.epcis.written.originals} originals, ${report.epcis.written.imports} imports, ${report.epcis.written.observations} observations, ${report.epcis.written.resolutions} decisions, ${report.epcis.written.pulls} pulls and ${report.epcis.written.pullPages} pages written; ${report.epcis.relocations} originals placed${report.epcis.associationsRebuilt == null ? '' : `; ${report.epcis.associationsRebuilt} index entries rebuilt`}.`)
|
|
124
|
+
out(report.index.rebuilt ? `Index: ${report.index.announced} states announced, ${report.index.admitted} admitted and ${report.index.duplicate} already held.` : `Index: not rebuilt. ${report.index.reason}`)
|
|
125
|
+
if (report.index.rebuilt && report.index.proofsApplied + report.index.proofsNotApplied.length > 0) out(`The replacement index applied ${report.index.proofsApplied} retained proofs. ${report.index.proofsNotApplied.length} attempted deliveries still need an acknowledgement.`)
|
|
126
|
+
out(`Readings: ${report.readings.same} of ${report.readings.compared} passports read here as they read where they were exported${report.readings.notCompared.length === 0 ? '' : `; ${report.readings.notCompared.length} not compared`}.`)
|
|
127
|
+
out('Provide separately:')
|
|
128
|
+
for (const line of report.provisionSeparately) out(` ${line}`)
|
|
129
|
+
if (report.attention.length > 0) {
|
|
130
|
+
out('Needs attention:')
|
|
131
|
+
for (const line of report.attention) out(` ${line}`)
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
/** Restore an authorised export into this deployment. Everything is verified before anything is written. */
|
|
136
|
+
export async function runRestoreCommand(args: string[], context: CommandContext): Promise<number> {
|
|
137
|
+
const values = optionsOf(() => parseArgs({ args, options: { from: { type: 'string' }, 'exporter-key': { type: 'string' }, 'index-exporter-key': { type: 'string' }, report: { type: 'string' }, 'require-custody-profile': { type: 'string' } } }).values, context)
|
|
138
|
+
if (values?.from == null) {
|
|
139
|
+
context.out('usage: restore --from <folder> [--exporter-key <key>] [--index-exporter-key <key>] [--report <file>] [--require-custody-profile managed-custody@3]')
|
|
140
|
+
return 2
|
|
141
|
+
}
|
|
142
|
+
const requiredCustodyProfile = custodyProfileOption(values['require-custody-profile'], context)
|
|
143
|
+
if (requiredCustodyProfile === false) return 1
|
|
144
|
+
for (const name of ['exporter-key', 'index-exporter-key'] as const) {
|
|
145
|
+
if (values[name] != null && !/^0[23][0-9a-f]{64}$/.test(values[name]!)) {
|
|
146
|
+
context.out(`--${name} is a compressed public key: 66 lower-case hexadecimal characters starting 02 or 03`)
|
|
147
|
+
return 2
|
|
148
|
+
}
|
|
149
|
+
}
|
|
150
|
+
const config = loadConfig(context.env)
|
|
151
|
+
return await answering(context, async () => {
|
|
152
|
+
const read = readPackageFolder(resolve(context.cwd, values.from!))
|
|
153
|
+
const platform = await openPlatform({ config, mode: 'live', log: () => {} })
|
|
154
|
+
try {
|
|
155
|
+
// Without the key of the deployment that exported, the package is held to this deployment's own publisher key: the same key, once the wallet was recovered here.
|
|
156
|
+
const exporterKey = values['exporter-key'] ?? platform.wallet.identityKey
|
|
157
|
+
const verified = await verifyApplicationPackage(read, {
|
|
158
|
+
exporterKey,
|
|
159
|
+
requiredCustodyProfile,
|
|
160
|
+
trustedBindingDigests: config.customProfiles.trustedBindingDigests,
|
|
161
|
+
...(values['index-exporter-key'] ?? config.indexExport.exporterKey) == null ? {} : { indexExporterKey: (values['index-exporter-key'] ?? config.indexExport.exporterKey)! },
|
|
162
|
+
})
|
|
163
|
+
// A restore into memory would be gone when this command ends, and would have said it was done.
|
|
164
|
+
if (platform.db == null) throw new PortabilityRefused('destination-not-durable', 'MongoDB is not reachable, so this deployment would keep the restored records in memory and lose them when this command ends. Nothing was written.')
|
|
165
|
+
const store = await openExchangeStorage({ setting: config.epcis.storage, db: platform.db, log: () => {} })
|
|
166
|
+
try {
|
|
167
|
+
const report = await restoreApplication({
|
|
168
|
+
verified,
|
|
169
|
+
platform,
|
|
170
|
+
epcis: { storage: store.storage, sources: config.epcis.sources, artefactsDir: config.epcis.gs1Dir },
|
|
171
|
+
// The index inside this process is gone when the command ends. Only an index this deployment has joined is given the states.
|
|
172
|
+
rebuildIndex: config.index.joined,
|
|
173
|
+
})
|
|
174
|
+
printReport(report, context.out)
|
|
175
|
+
if (values.report != null) writeFileSync(resolve(context.cwd, values.report), `${JSON.stringify(report, null, 2)}\n`)
|
|
176
|
+
return report.attention.length === 0 ? 0 : 3
|
|
177
|
+
} finally {
|
|
178
|
+
await store.close()
|
|
179
|
+
}
|
|
180
|
+
} finally {
|
|
181
|
+
await platform.close()
|
|
182
|
+
}
|
|
183
|
+
})
|
|
184
|
+
}
|
|
185
|
+
|
|
186
|
+
/**
|
|
187
|
+
* Declare that a configured EPCIS source is now reached at the address the
|
|
188
|
+
* configuration gives it. Every pull of the source is bound to that address,
|
|
189
|
+
* with its identity, its pages and its checkpoint kept. No request is made
|
|
190
|
+
* and no credential is read.
|
|
191
|
+
*/
|
|
192
|
+
export async function runRemapCommand(args: string[], context: CommandContext): Promise<number> {
|
|
193
|
+
const values = optionsOf(() => parseArgs({ args, options: { source: { type: 'string' } } }).values, context)
|
|
194
|
+
const config = loadConfig(context.env)
|
|
195
|
+
const source = config.epcis.sources.find((candidate) => candidate.sourceId === values?.source)
|
|
196
|
+
if (values?.source == null || source == null) {
|
|
197
|
+
context.out(`usage: epcis-remap --source <name>, where the name is one of EPCIS_SOURCES${config.epcis.sources.length === 0 ? ' (none is configured)' : `: ${config.epcis.sources.map((candidate) => candidate.sourceId).join(', ')}`}`)
|
|
198
|
+
return 2
|
|
199
|
+
}
|
|
200
|
+
const platform = await openPlatform({ config, mode: 'live', log: () => {} })
|
|
201
|
+
const store = await openExchangeStorage({ setting: config.epcis.storage, ...(platform.db == null ? {} : { db: platform.db }), log: () => {} })
|
|
202
|
+
try {
|
|
203
|
+
const outcome = await remapEpcisSourceEndpoint({
|
|
204
|
+
storage: store.storage,
|
|
205
|
+
sourceId: source.sourceId,
|
|
206
|
+
baseUrl: source.baseUrl,
|
|
207
|
+
permittedOrigins: source.permittedOrigins,
|
|
208
|
+
localTest: source.localTest,
|
|
209
|
+
remappedAt: new Date().toISOString(),
|
|
210
|
+
remappedBy: 'operator',
|
|
211
|
+
resolveHost: async (hostname) => (await lookup(hostname, { all: true })).map((entry) => entry.address),
|
|
212
|
+
})
|
|
213
|
+
if (outcome.outcome === 'refused') {
|
|
214
|
+
context.out(`Refused (${outcome.reason}): ${outcome.detail}`)
|
|
215
|
+
return 1
|
|
216
|
+
}
|
|
217
|
+
for (const pull of outcome.pulls) context.out(`${pull.queryId}: ${pull.changed ? `now bound to ${pull.to.baseUrl}, from ${pull.from.baseUrl}` : `already bound to ${pull.to.baseUrl}`}; cursor ${pull.cursor}.`)
|
|
218
|
+
context.out(`The source ${source.sourceId} keeps its identity, its imports and each pull's checkpoint. A pull whose cursor was dropped replays from its retained bounds.`)
|
|
219
|
+
return 0
|
|
220
|
+
} finally {
|
|
221
|
+
await store.close()
|
|
222
|
+
await platform.close()
|
|
223
|
+
}
|
|
224
|
+
}
|