@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.
Files changed (143) hide show
  1. package/NOTICE +2 -0
  2. package/PATENTS +12 -0
  3. package/README.md +26 -6
  4. package/dist/index.js +36 -8
  5. package/package.json +9 -5
  6. package/template/Dockerfile +4 -2
  7. package/template/README.md +297 -42
  8. package/template/_env.example +82 -13
  9. package/template/_github/workflows/ci.yml +3 -3
  10. package/template/apps/api/API.md +86 -16
  11. package/template/apps/api/package.json +9 -4
  12. package/template/apps/api/src/bound-profiles.ts +590 -0
  13. package/template/apps/api/src/claims.ts +175 -56
  14. package/template/apps/api/src/cli.ts +64 -7
  15. package/template/apps/api/src/config.ts +124 -10
  16. package/template/apps/api/src/custody.ts +241 -69
  17. package/template/apps/api/src/dev-index.ts +58 -9
  18. package/template/apps/api/src/env-file.ts +55 -0
  19. package/template/apps/api/src/epcis/exchange.ts +434 -0
  20. package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
  21. package/template/apps/api/src/epcis/routes.ts +364 -0
  22. package/template/apps/api/src/epcis/sources.ts +142 -0
  23. package/template/apps/api/src/go-live.ts +226 -0
  24. package/template/apps/api/src/http-error.ts +15 -0
  25. package/template/apps/api/src/identifiers.ts +1 -1
  26. package/template/apps/api/src/index-client.ts +131 -6
  27. package/template/apps/api/src/index-projects.ts +53 -0
  28. package/template/apps/api/src/lifecycle-authority.ts +49 -0
  29. package/template/apps/api/src/lifecycle.ts +485 -0
  30. package/template/apps/api/src/main.ts +10 -2
  31. package/template/apps/api/src/parties.ts +2 -2
  32. package/template/apps/api/src/platform.ts +72 -17
  33. package/template/apps/api/src/portability/commands.ts +224 -0
  34. package/template/apps/api/src/portability/export.ts +708 -0
  35. package/template/apps/api/src/portability/package.ts +270 -0
  36. package/template/apps/api/src/portability/restore.ts +863 -0
  37. package/template/apps/api/src/profiles.ts +38 -13
  38. package/template/apps/api/src/reader.ts +172 -3
  39. package/template/apps/api/src/resolver.ts +159 -0
  40. package/template/apps/api/src/sector-examples.ts +390 -0
  41. package/template/apps/api/src/server.ts +253 -60
  42. package/template/apps/api/src/store.ts +198 -21
  43. package/template/apps/api/src/validation-engine.ts +172 -0
  44. package/template/apps/api/src/wallet.ts +30 -17
  45. package/template/apps/api/src/worker.ts +20 -13
  46. package/template/apps/api/src/writer.ts +383 -131
  47. package/template/apps/api/test/bound-http.test.ts +496 -0
  48. package/template/apps/api/test/bound-profiles.test.ts +547 -0
  49. package/template/apps/api/test/config.test.ts +148 -3
  50. package/template/apps/api/test/custody-journal.test.ts +415 -0
  51. package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
  52. package/template/apps/api/test/custom-profile.test.ts +167 -0
  53. package/template/apps/api/test/env-file.test.ts +53 -0
  54. package/template/apps/api/test/epcis-fixtures.ts +270 -0
  55. package/template/apps/api/test/epcis-http.test.ts +1179 -0
  56. package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
  57. package/template/apps/api/test/epcis-separation.test.ts +253 -0
  58. package/template/apps/api/test/epcis-web.test.ts +230 -0
  59. package/template/apps/api/test/exit-exercise.test.ts +1038 -0
  60. package/template/apps/api/test/external-index.test.ts +3 -2
  61. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
  62. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
  63. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
  64. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
  65. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
  66. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
  67. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
  68. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
  69. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
  70. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
  71. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
  72. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
  73. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
  74. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
  75. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
  76. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
  77. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
  78. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
  79. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
  80. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
  81. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
  82. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
  83. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
  84. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
  85. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
  86. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
  87. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
  88. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
  89. package/template/apps/api/test/go-live.test.ts +179 -0
  90. package/template/apps/api/test/gs1-global-setup.ts +33 -0
  91. package/template/apps/api/test/gs1-test-env.ts +5 -0
  92. package/template/apps/api/test/identifier-host.test.ts +256 -0
  93. package/template/apps/api/test/index-projects.test.ts +81 -0
  94. package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
  95. package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
  96. package/template/apps/api/test/lifecycle.test.ts +17 -6
  97. package/template/apps/api/test/manifest-notice.test.ts +36 -0
  98. package/template/apps/api/test/network-guard.ts +113 -0
  99. package/template/apps/api/test/portability.test.ts +655 -0
  100. package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
  101. package/template/apps/api/test/retired-profiles.test.ts +216 -0
  102. package/template/apps/api/test/sector-cutover.test.ts +95 -0
  103. package/template/apps/api/test/sector-forms.test.ts +420 -0
  104. package/template/apps/api/test/unjoined-index.test.ts +62 -0
  105. package/template/apps/api/test/validation-engine.test.ts +328 -0
  106. package/template/apps/api/test/wallet-monitor.test.ts +38 -0
  107. package/template/apps/api/test/writer-journal.test.ts +327 -0
  108. package/template/apps/api/vitest.config.ts +3 -0
  109. package/template/apps/web/src/app.tsx +8 -4
  110. package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
  111. package/template/apps/web/src/components/bound/field-view.tsx +237 -0
  112. package/template/apps/web/src/components/bound/pieces.tsx +169 -0
  113. package/template/apps/web/src/components/bound/readings.tsx +152 -0
  114. package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
  115. package/template/apps/web/src/components/claim-dialog.tsx +344 -0
  116. package/template/apps/web/src/components/epcis-events.tsx +119 -0
  117. package/template/apps/web/src/components/layout.tsx +17 -0
  118. package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
  119. package/template/apps/web/src/components/passport-form.tsx +2 -2
  120. package/template/apps/web/src/components/read-passport.tsx +4 -3
  121. package/template/apps/web/src/components/reading.tsx +32 -39
  122. package/template/apps/web/src/lib/api.ts +136 -26
  123. package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
  124. package/template/apps/web/src/lib/bound/display.ts +122 -0
  125. package/template/apps/web/src/lib/bound/fields.ts +128 -0
  126. package/template/apps/web/src/lib/bound/form-model.ts +521 -0
  127. package/template/apps/web/src/lib/bound/forms.ts +15 -0
  128. package/template/apps/web/src/lib/bound/identity.ts +48 -0
  129. package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
  130. package/template/apps/web/src/lib/bound/units.ts +37 -0
  131. package/template/apps/web/src/lib/epcis.ts +345 -0
  132. package/template/apps/web/src/lib/format.ts +27 -4
  133. package/template/apps/web/src/lib/lifecycle.ts +350 -0
  134. package/template/apps/web/src/pages/accept.tsx +8 -3
  135. package/template/apps/web/src/pages/events.tsx +388 -0
  136. package/template/apps/web/src/pages/new-passport.tsx +25 -2
  137. package/template/apps/web/src/pages/operations.tsx +22 -3
  138. package/template/apps/web/src/pages/passport.tsx +226 -162
  139. package/template/apps/web/src/pages/public-passport.tsx +50 -10
  140. package/template/apps/web/src/pages/wallet.tsx +1 -1
  141. package/template/apps/web/vite.config.ts +12 -4
  142. package/template/deploy/compose.yml +14 -2
  143. package/template/package.json +9 -3
@@ -0,0 +1,226 @@
1
+ // npm run go-live: everything a real write needs, checked in order, each
2
+ // failure printed with its fix, and nothing on the chain until all pass.
3
+ // Registration is the one step that changes the index: the wallet signs a
4
+ // dpp-index-registration@1 request, POST /register appends the publisher
5
+ // key to the index's policy and answers with this app's two write tokens,
6
+ // which go into .env beside the root key the first run generated. A passing
7
+ // run writes LIVE_PUBLISHING=true; a failing run leaves it as it was.
8
+ import { INDEX_REGISTRATION_FORMAT, signRegistration } from '@bsv/dpp-protocol'
9
+ import { KNOWN_INDEX_HOSTS, loadConfig, type Config } from './config.js'
10
+ import { generateRootKey, ROOT_KEY_GENERATED, updateEnvFile } from './env-file.js'
11
+ import { IndexClient } from './index-client.js'
12
+ import { openPlatform as openDefaultPlatform, type Platform, type PlatformOptions } from './platform.js'
13
+
14
+ export const CUSTODY_PROFILE = 'managed-custody@2'
15
+ /** A few states' worth: one costs a little over a hundred satoshis. */
16
+ export const MINIMUM_SATOSHIS = 500
17
+ const LABEL_BYTES = 128
18
+
19
+ export interface GoLiveFailure {
20
+ check: string
21
+ problem: string
22
+ fix: string
23
+ }
24
+
25
+ export interface GoLiveOptions {
26
+ env: NodeJS.ProcessEnv
27
+ /** The project's .env, which gains the root key, the tokens and LIVE_PUBLISHING. */
28
+ envFile: string
29
+ /** The label the index's operator sees for this app. */
30
+ projectName: string
31
+ out: (line: string) => void
32
+ openPlatform?: (options: PlatformOptions) => Promise<Platform>
33
+ now?: () => Date
34
+ }
35
+
36
+ export interface GoLiveResult {
37
+ ok: boolean
38
+ passed: string[]
39
+ failures: GoLiveFailure[]
40
+ }
41
+
42
+ type RegisterAnswer = { status: number; body: { status?: string; error?: string; description?: string; hint?: string; policyVersion?: number; tokens?: { submit: string; callback: string } } }
43
+
44
+ async function postRegister(url: string, request: unknown): Promise<RegisterAnswer> {
45
+ const response = await fetch(`${url}/register`, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(request) })
46
+ const body = (await response.json().catch(() => ({}))) as RegisterAnswer['body']
47
+ return { status: response.status, body }
48
+ }
49
+
50
+ /** An error's message with the reason fetch hides under `cause` (ENOTFOUND, ECONNREFUSED), so a newcomer can tell DNS from a service that is down. */
51
+ const describe = (cause: unknown): string => {
52
+ if (!(cause instanceof Error)) return String(cause)
53
+ const inner = (cause as Error & { cause?: unknown }).cause
54
+ return inner instanceof Error && inner.message !== '' && inner.message !== cause.message ? `${cause.message} (${inner.message})` : cause.message
55
+ }
56
+
57
+ /** go-live decides LIVE_PUBLISHING itself, so the file's current value never stops the run: a true left behind without tokens would otherwise send the user round in a loop. */
58
+ const configuration = (env: NodeJS.ProcessEnv): Config => loadConfig({ ...env, LIVE_PUBLISHING: 'false' })
59
+
60
+ export async function goLive(options: GoLiveOptions): Promise<GoLiveResult> {
61
+ const env = { ...options.env }
62
+ const out = options.out
63
+ const open = options.openPlatform ?? openDefaultPlatform
64
+ const now = options.now ?? (() => new Date())
65
+ const passed: string[] = []
66
+ const failures: GoLiveFailure[] = []
67
+ const pass = (check: string, detail?: string): void => {
68
+ passed.push(check)
69
+ out(`ok ${check}${detail == null ? '' : `: ${detail}`}`)
70
+ }
71
+ const fail = (check: string, problem: string, fix: string): void => {
72
+ failures.push({ check, problem, fix })
73
+ out(`no ${check}: ${problem}. Fix: ${fix}`)
74
+ }
75
+ const result = (): GoLiveResult => ({ ok: failures.length === 0, passed, failures })
76
+
77
+ // 1. Configuration.
78
+ let config: Config
79
+ if ((env.LIVE_PUBLISHING ?? '').trim() === 'true') out('note configuration: LIVE_PUBLISHING is already true in .env; this run decides it again')
80
+ try {
81
+ config = configuration(env)
82
+ } catch (cause) {
83
+ fail('configuration', describe(cause), 'edit .env as the message says, then run npm run go-live again')
84
+ return result()
85
+ }
86
+ const indexUrl = config.index.url
87
+ if (indexUrl == null) {
88
+ fail('configuration', 'INDEX_URL is empty', 'set INDEX_URL to the index this app publishes to (the default testnet index is https://dpp-overlay-testnet.bsvb.net), or run npm run connect-index -- --url <index>')
89
+ } else {
90
+ let host: string | undefined
91
+ try {
92
+ host = new URL(indexUrl).hostname
93
+ } catch {
94
+ fail('configuration', `INDEX_URL ${indexUrl} is not a URL`, 'set INDEX_URL to the index address, https://host or http://host:port')
95
+ }
96
+ const known = host == null ? undefined : KNOWN_INDEX_HOSTS[host]
97
+ if (known != null && known !== config.network) {
98
+ fail('configuration', `${host} serves ${known} and NETWORK is ${config.network}`, `set NETWORK=${known} for that index, or INDEX_URL to the ${config.network} index (${config.network === 'test' ? 'https://dpp-overlay-testnet.bsvb.net' : 'https://dpp-overlay-mainnet.bsvb.net'})`)
99
+ }
100
+ }
101
+ if (config.network === 'main') {
102
+ if (config.gs1Prefix === '952') fail('configuration', 'GS1_PREFIX is 952, the demonstration prefix, and NETWORK is main', 'set GS1_PREFIX to a prefix licensed to you before writing real passports on mainnet')
103
+ if (/^localhost(:\d+)?$/.test(config.passportHost)) fail('configuration', `PASSPORT_HOST is ${config.passportHost} and NETWORK is main`, 'set PASSPORT_HOST to a host you serve this app from, so a label opens the passport page')
104
+ } else {
105
+ if (config.gs1Prefix === '952') out('note configuration: GS1_PREFIX is 952, the demonstration prefix; fine on testnet, replace it before mainnet')
106
+ if (/^localhost(:\d+)?$/.test(config.passportHost)) out(`note configuration: PASSPORT_HOST is ${config.passportHost}; fine on testnet, set a host you serve before mainnet`)
107
+ }
108
+ if (failures.length > 0) return result()
109
+ pass('configuration', `${config.network}, index ${indexUrl}`)
110
+
111
+ // 2. Wallet.
112
+ if (config.wallet.rootKeyHex == null && (await generateRootKey(options.envFile, env))) {
113
+ config = configuration(env)
114
+ out(ROOT_KEY_GENERATED)
115
+ }
116
+ let platform: Platform
117
+ try {
118
+ platform = await open({ config, mode: 'live', log: () => {} })
119
+ } catch (cause) {
120
+ fail('wallet', `the wallet could not be opened: ${describe(cause)}`, 'check WALLET_ROOT_KEY and WALLET_FILE in .env, then run npm run go-live again')
121
+ return result()
122
+ }
123
+ try {
124
+ const publisherKey = platform.wallet.identityKey
125
+ if (config.testWallet && platform.wallet.kind === 'test') out('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. Unset it unless this is the scaffold check.')
126
+ pass('wallet', `${platform.wallet.kind} wallet on ${platform.wallet.network}, publisher key ${publisherKey}`)
127
+
128
+ // 3. The index.
129
+ const index = new IndexClient({ url: indexUrl! })
130
+ let custodyProfile: string | undefined
131
+ let registrationMode: string | undefined
132
+ let publisherKeys: string[] = []
133
+ try {
134
+ const health = await index.health()
135
+ if (health.network !== config.network) {
136
+ fail('index', `${indexUrl} serves ${health.network} and NETWORK is ${config.network}`, `set NETWORK=${health.network}, or point INDEX_URL at a ${config.network} index`)
137
+ }
138
+ const document = await index.capabilities()
139
+ const custody = document.profiles?.find((p) => p.kind === 'custody')
140
+ custodyProfile = custody == null ? undefined : `${custody.id}@${custody.version}`
141
+ registrationMode = (document.profiles?.find((p) => p.kind === 'operator')?.options?.registration as string | undefined) ?? 'off'
142
+ publisherKeys = document.publisherPolicy?.publisherKeys ?? []
143
+ if (custodyProfile !== CUSTODY_PROFILE) {
144
+ fail('index', `${indexUrl} admits under custody profile ${custodyProfile ?? 'none'} and this app writes under ${CUSTODY_PROFILE}`, `use an index on ${config.network} that advertises ${CUSTODY_PROFILE}, then run npm run connect-index`)
145
+ }
146
+ } catch (cause) {
147
+ fail('index', `${indexUrl} could not be reached: ${describe(cause)}`, 'check the address and that the index is running; to use another index, run npm run connect-index -- --url <index>')
148
+ }
149
+ if (failures.length > 0) return result()
150
+ pass('index', `${indexUrl} on ${config.network}, ${custodyProfile}, registration ${registrationMode}`)
151
+
152
+ // 4. Registration.
153
+ // Named and holding tokens: done. Named without tokens is still a request:
154
+ // an approved key collects its tokens this way, and a key the operator
155
+ // added by hand is told 409 and where to get them.
156
+ const named = publisherKeys.includes(publisherKey)
157
+ if (named && config.index.joined) {
158
+ pass('registration', 'this publisher key is registered and the tokens are held')
159
+ } else {
160
+ let answer: RegisterAnswer
161
+ try {
162
+ const request = await signRegistration(
163
+ {
164
+ registrationFormat: INDEX_REGISTRATION_FORMAT,
165
+ indexUrl: indexUrl!,
166
+ publisherKey,
167
+ network: config.network,
168
+ custodyProfile: CUSTODY_PROFILE,
169
+ label: Buffer.from(options.projectName, 'utf8').subarray(0, LABEL_BYTES).toString('utf8').replace(/�+$/, '') || 'dpp-app',
170
+ requestedAt: now().toISOString(),
171
+ },
172
+ platform.wallet.publisher
173
+ )
174
+ answer = await postRegister(indexUrl!, request)
175
+ } catch (cause) {
176
+ const message = describe(cause)
177
+ if (/label/.test(message)) {
178
+ fail('registration', `the request could not be signed: ${message}`, 'set a plain name in package.json (letters, digits and hyphens), then run npm run go-live again')
179
+ return result()
180
+ }
181
+ fail('registration', `POST /register failed: ${describe(cause)}`, 'run npm run go-live again; if it keeps failing, ask the operator')
182
+ return result()
183
+ }
184
+ const { status, body } = answer
185
+ if (status === 201 && body.tokens != null) {
186
+ await updateEnvFile(options.envFile, { INDEX_SUBMIT_TOKEN: body.tokens.submit, INDEX_CALLBACK_TOKEN: body.tokens.callback })
187
+ env.INDEX_SUBMIT_TOKEN = body.tokens.submit
188
+ env.INDEX_CALLBACK_TOKEN = body.tokens.callback
189
+ config = configuration(env)
190
+ pass('registration', `registered in policy version ${body.policyVersion}; the tokens are in .env`)
191
+ } else if (status === 202) {
192
+ fail('registration', `${indexUrl} holds the request for its operator's approval`, 'run npm run go-live again once the operator has approved; the tokens are handed over then')
193
+ } else if (status === 404) {
194
+ fail('registration', `${indexUrl} does not register publishers itself`, 'ask its operator for admission and a connection file (dpp-index connection), then run npm run connect-index -- --from <file>; or run your own index from the DPP operator preset')
195
+ } else if (status === 409 && body.error === 'already-registered') {
196
+ fail('registration', `${indexUrl} names this publisher key and holds no tokens for it to hand over`, 'ask the operator for this key\'s connection file (dpp-index connection), then run npm run connect-index -- --from <file>')
197
+ } else {
198
+ fail('registration', `${indexUrl} answered ${status}${body.error == null ? '' : ` ${body.error}`}${body.description == null ? '' : `: ${body.description}`}`, body.hint ?? 'read the message, change .env accordingly and run npm run go-live again')
199
+ }
200
+ }
201
+ if (failures.length > 0) return result()
202
+
203
+ // 5. Funds.
204
+ const balance = await platform.wallet.balance()
205
+ if (balance < MINIMUM_SATOSHIS) {
206
+ const funding = await platform.wallet.fundingAddress()
207
+ fail('funds', `the wallet holds ${balance} satoshis`, `pay a few thousand satoshis to ${funding.address}, then take the payment in with: npm run wallet fund <txid> ${funding.address} ${funding.derivationPrefix} ${funding.derivationSuffix}; then run npm run go-live again`)
208
+ return result()
209
+ }
210
+ pass('funds', `${balance} satoshis`)
211
+
212
+ // 6. Admission: the index names the key now.
213
+ const keys = await index.publisherKeys().catch(() => [] as string[])
214
+ if (!keys.includes(publisherKey)) {
215
+ fail('admission', `${indexUrl} does not yet name this publisher key`, 'run npm run go-live again in a moment; if it keeps failing, ask the operator')
216
+ return result()
217
+ }
218
+ pass('admission', 'the index admits states this key countersigns')
219
+
220
+ await updateEnvFile(options.envFile, { LIVE_PUBLISHING: 'true' })
221
+ out(`LIVE_PUBLISHING=true is written: the next passport write spends real satoshis on ${config.network === 'main' ? 'mainnet' : 'testnet'} and is permanent.`)
222
+ return result()
223
+ } finally {
224
+ await platform.close()
225
+ }
226
+ }
@@ -0,0 +1,15 @@
1
+ // An error a route answers with a status and a code. It lives in a module of
2
+ // its own so that a group of routes can use it without importing the server,
3
+ // and through the server everything the server imports.
4
+
5
+ export class HttpError extends Error {
6
+ constructor(
7
+ readonly status: number,
8
+ readonly code: string,
9
+ detail: string,
10
+ /** Further members of the answer, beside `error` and `description`. */
11
+ readonly data: Record<string, unknown> = {}
12
+ ) {
13
+ super(detail)
14
+ }
15
+ }
@@ -12,7 +12,7 @@ export interface IdentifierPolicy {
12
12
  prefix: string
13
13
  }
14
14
 
15
- export const isDemonstrationPolicy = (policy: IdentifierPolicy): boolean => policy.prefix === GS1_DEMONSTRATION_PREFIX
15
+ export const isDemonstrationPolicy = (policy: IdentifierPolicy): boolean => policy.prefix.startsWith(GS1_DEMONSTRATION_PREFIX)
16
16
 
17
17
  /** The item reference digits that, with the prefix and the check digit, make a GTIN-13 for the host's prefix. */
18
18
  export function mintGtin(prefix: string, itemReference: string): string {
@@ -3,8 +3,9 @@
3
3
  // be reached refuses nothing, and the writer sends anyway and announces the
4
4
  // same bytes again later. A 401 or 403 is this platform's own configuration
5
5
  // and stops a write while the state is still a draft.
6
- import { Beef, type MerklePath, type Transaction } from '@bsv/sdk'
7
- import { chainFromBeef } from '@bsv/dpp-protocol'
6
+ import { createHash } from 'node:crypto'
7
+ import { Beef, Transaction, type MerklePath } from '@bsv/sdk'
8
+ import { chainFromBeef, decodeAttestationAnchor } from '@bsv/dpp-protocol'
8
9
 
9
10
  export type Announcement = 'admitted' | 'duplicate' | 'refused' | 'unauthorised' | 'unreachable'
10
11
 
@@ -19,12 +20,37 @@ export interface IndexClientOptions {
19
20
  url: string
20
21
  submitToken?: string
21
22
  callbackToken?: string
23
+ /** This index can withdraw drafts admitted before the network answers. */
24
+ supportsRetraction?: boolean
22
25
  /** Silence the in-process index's logging during a call; tests use it. */
23
26
  quiet?: boolean
24
27
  }
25
28
 
29
+ /** Read a discovery response up to its wire limit, including responses without Content-Length. */
30
+ export async function boundedJson(response: Response, limit: number): Promise<unknown> {
31
+ const reader = response.body?.getReader()
32
+ if (reader == null) throw new Error('the response has no body')
33
+ const chunks: Uint8Array[] = []
34
+ let length = 0
35
+ try {
36
+ for (;;) {
37
+ const chunk = await reader.read()
38
+ if (chunk.done) break
39
+ length += chunk.value.length
40
+ if (length > limit) throw new Error(`the response exceeds the reader limit of ${limit} bytes`)
41
+ chunks.push(chunk.value)
42
+ }
43
+ } finally {
44
+ if (length > limit) await reader.cancel()
45
+ reader.releaseLock()
46
+ }
47
+ return JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(Buffer.concat(chunks)))
48
+ }
49
+
26
50
  export class IndexClient {
27
51
  readonly url: string
52
+ readonly supportsRetraction: boolean
53
+ readonly destinationId: string
28
54
  private submitToken?: string
29
55
  private callbackToken?: string
30
56
  /** The last refusal reason the index gave in X-Admission-Refusal, for the journal. */
@@ -32,6 +58,8 @@ export class IndexClient {
32
58
 
33
59
  constructor(options: IndexClientOptions) {
34
60
  this.url = options.url.replace(/\/+$/, '')
61
+ this.destinationId = createHash('sha256').update(this.url).digest('hex')
62
+ this.supportsRetraction = options.supportsRetraction ?? false
35
63
  this.submitToken = options.submitToken
36
64
  this.callbackToken = options.callbackToken
37
65
  }
@@ -40,6 +68,13 @@ export class IndexClient {
40
68
  return await fetch(`${this.url}${path}`, init)
41
69
  }
42
70
 
71
+ /** The index's own health answer, which names the network it serves. */
72
+ async health(): Promise<{ status: string; network: string }> {
73
+ const response = await this.request('/health')
74
+ if (!response.ok) throw new Error(`the index answered HTTP ${response.status} to GET /health`)
75
+ return (await response.json()) as { status: string; network: string }
76
+ }
77
+
43
78
  async capabilities(): Promise<CapabilityDocument> {
44
79
  const response = await this.request('/capabilities')
45
80
  if (!response.ok) throw new Error(`the index answered HTTP ${response.status} to GET /capabilities`)
@@ -67,7 +102,97 @@ export class IndexClient {
67
102
  return chainFromBeef(merged, passportId)
68
103
  }
69
104
 
70
- /** Announce an unsent transaction (spec/writing.md section 3). */
105
+ /**
106
+ * The attestation anchors the index holds under one selector (`ls_attestation`), each as its transaction and output.
107
+ * An anchor's metadata is unsigned by the claim's issuer: it says where to look, and the claim's own verification
108
+ * decides what the claim is about. Throws when the index cannot be reached or refuses the question.
109
+ */
110
+ async *scanAnchors(query: { subject: string } | { attestationId: string }, representation?: string, signal = AbortSignal.timeout(30_000)): AsyncGenerator<{ transaction: Transaction; outputIndex: number; attestationId: string }> {
111
+ let after: { txid: string; outputIndex: number } | undefined
112
+ let count = 0
113
+ // The lookup contract ends on an empty page. Preserve results already read if a later page fails.
114
+ const maxAnchors = 500
115
+ for (;;) {
116
+ const limit = Math.min(100, maxAnchors - count + 1)
117
+ const response = await this.request('/lookup', {
118
+ method: 'POST',
119
+ headers: { 'Content-Type': 'application/json' },
120
+ signal,
121
+ body: JSON.stringify({ service: 'ls_attestation', query: { ...query, ...(representation == null ? {} : { representation }), limit, after } }),
122
+ })
123
+ if (!response.ok) throw new Error(`the index answered HTTP ${response.status} to the anchor lookup`)
124
+ const { outputs } = (await boundedJson(response, 32 * 1024 * 1024)) as { outputs?: Array<{ beef: number[]; outputIndex: number }> }
125
+ if (!Array.isArray(outputs) || outputs.length > limit) throw new Error('the index returned an invalid anchor page')
126
+ if (outputs.length === 0) return
127
+ for (const output of outputs) {
128
+ if (count === maxAnchors) throw new Error(`the anchor lookup exceeded the reader limit of ${maxAnchors} outputs`)
129
+ const transaction = Transaction.fromBEEF(output.beef)
130
+ const txid = transaction.id('hex')
131
+ const outputIndex = output.outputIndex
132
+ if (!Number.isSafeInteger(outputIndex) || transaction.outputs[outputIndex] == null) throw new Error('the index returned an invalid anchor outpoint')
133
+ if (after != null && (txid < after.txid || (txid === after.txid && outputIndex <= after.outputIndex))) throw new Error('the anchor page did not advance in outpoint order')
134
+ const metadata = decodeAttestationAnchor(transaction.outputs[outputIndex]!.lockingScript)
135
+ if (metadata == null || ('subject' in query && metadata.subject !== query.subject) || ('attestationId' in query && metadata.attestationId !== query.attestationId) || (representation != null && metadata.representation !== representation)) {
136
+ throw new Error('the returned anchor does not match the lookup selector')
137
+ }
138
+ after = { txid, outputIndex }
139
+ count += 1
140
+ yield { transaction, outputIndex, attestationId: metadata.attestationId }
141
+ }
142
+ }
143
+ }
144
+
145
+ async anchorsFor(query: { subject: string } | { attestationId: string }, representation?: string): Promise<Array<{ transaction: Transaction; outputIndex: number }>> {
146
+ const anchors = []
147
+ for await (const { transaction, outputIndex } of this.scanAnchors(query, representation)) anchors.push({ transaction, outputIndex })
148
+ return anchors
149
+ }
150
+
151
+ /** The identity key the index signs its evidence packages under, as its capability document names it, or nothing when it signs none. */
152
+ async exporterIdentityKey(): Promise<string | undefined> {
153
+ const key = (await this.capabilities()).exporterIdentityKey
154
+ return typeof key === 'string' && /^0[23][0-9a-f]{64}$/.test(key) ? key : undefined
155
+ }
156
+
157
+ /**
158
+ * The index's bounded evidence package for one passport (GET /evidence-package), exactly as it answered: the signed
159
+ * manifest and every file by path, base64. `absent` says why there is none: the index holds no state of the
160
+ * passport, signs no package, or could not be reached. Nothing here checks the package; the caller inspects it.
161
+ */
162
+ async evidencePackage(passportId: string): Promise<{ envelope: { manifest: unknown; files: Record<string, string> } } | { absent: 'not-held' | 'export-unavailable' | 'unreachable'; detail: string }> {
163
+ let response: Response
164
+ try {
165
+ response = await this.request(`/evidence-package?${new URLSearchParams({ passportId }).toString()}`)
166
+ } catch (cause) {
167
+ return { absent: 'unreachable', detail: `the index could not be reached (${cause instanceof Error ? cause.message : String(cause)})` }
168
+ }
169
+ if (response.status === 404) return { absent: 'not-held', detail: 'the index holds no state of the passport' }
170
+ if (response.status === 503) return { absent: 'export-unavailable', detail: 'the index signs no evidence package: its operator has not set an exporter key' }
171
+ if (!response.ok) return { absent: 'unreachable', detail: `the index answered HTTP ${response.status} to GET /evidence-package` }
172
+ return { envelope: (await response.json()) as { manifest: unknown; files: Record<string, string> } }
173
+ }
174
+
175
+ /**
176
+ * One part of the index's complete export for one passport (GET /evidence-export), exactly as it answered. The
177
+ * bearer is the index's EXPORT_TOKEN, where its operator set one. `absent` says why there is no part.
178
+ */
179
+ async evidenceExportPart(passportId: string, cursor: string | null, token?: string): Promise<{ part: Record<string, unknown> } | { absent: 'not-held' | 'export-unavailable' | 'unauthorised' | 'unreachable'; detail: string }> {
180
+ const query = new URLSearchParams({ passportId })
181
+ if (cursor != null) query.set('cursor', cursor)
182
+ let response: Response
183
+ try {
184
+ response = await this.request(`/evidence-export?${query.toString()}`, token == null ? undefined : { headers: { Authorization: `Bearer ${token}` } })
185
+ } catch (cause) {
186
+ return { absent: 'unreachable', detail: `the index could not be reached (${cause instanceof Error ? cause.message : String(cause)})` }
187
+ }
188
+ if (response.status === 401 || response.status === 403) return { absent: 'unauthorised', detail: 'the index wants its export token for the complete export: set INDEX_EXPORT_TOKEN to the one its operator gave you' }
189
+ if (response.status === 404) return { absent: 'not-held', detail: 'the index holds no state of the passport' }
190
+ if (response.status === 503) return { absent: 'export-unavailable', detail: 'the index signs no evidence package: its operator has not set an exporter key' }
191
+ if (!response.ok) return { absent: 'unreachable', detail: `the index answered HTTP ${response.status} to GET /evidence-export` }
192
+ return { part: (await response.json()) as Record<string, unknown> }
193
+ }
194
+
195
+ /** Submit a signed transaction for index admission. */
71
196
  async announce(beef: number[]): Promise<Announcement> {
72
197
  this.lastRefusal = undefined
73
198
  let response: Response
@@ -101,20 +226,20 @@ export class IndexClient {
101
226
  }
102
227
 
103
228
  /** Withdraw a state the network refused after the index admitted it. */
104
- async retract(txid: string, reason: string): Promise<{ ok: boolean; detail: string }> {
229
+ async retract(txid: string, reason: string, outputIndex = 0): Promise<{ ok: boolean; detail: string; absent?: boolean }> {
105
230
  let response: Response
106
231
  try {
107
232
  response = await this.request('/retract', {
108
233
  method: 'POST',
109
234
  headers: { 'Content-Type': 'application/json', ...(this.submitToken != null ? { Authorization: `Bearer ${this.submitToken}` } : {}) },
110
- body: JSON.stringify({ txid, outputIndex: 0, reason }),
235
+ body: JSON.stringify({ txid, outputIndex, reason }),
111
236
  })
112
237
  } catch (cause) {
113
238
  return { ok: false, detail: `the index could not be reached (${cause instanceof Error ? cause.message : String(cause)})` }
114
239
  }
115
240
  const body = (await response.json().catch(() => ({}))) as { status?: string; error?: string; description?: string }
116
241
  const ok = response.ok && body.status === 'retracted'
117
- return { ok, detail: ok ? 'retracted' : `HTTP ${response.status}${body.error != null ? ` ${body.error}` : ''}${body.description != null ? `, ${body.description}` : ''}` }
242
+ return { ok, absent: response.status === 404 && body.error === 'output-unknown', detail: ok ? 'retracted' : `HTTP ${response.status}${body.error != null ? ` ${body.error}` : ''}${body.description != null ? `, ${body.description}` : ''}` }
118
243
  }
119
244
 
120
245
  /** Offer a merkle path to the index, in the shape a broadcaster's callback carries (section 7). */
@@ -0,0 +1,53 @@
1
+ // npm run connect-index: the way to an index besides the default one. It
2
+ // takes a provider's address and, when the provider handed them out, its
3
+ // tokens; without tokens, go-live registers. --from reads the same settings
4
+ // from a connection file, the one an index operator writes with
5
+ // `dpp-index connection` (the DPP repository's operator preset), so the
6
+ // tokens never pass through the command line. Either way the connection is
7
+ // written to .env and the go-live checks run.
8
+ import { existsSync } from 'node:fs'
9
+ import { loadConfig } from './config.js'
10
+ import { readEnvFile, updateEnvFile } from './env-file.js'
11
+ import { goLive, type GoLiveOptions, type GoLiveResult } from './go-live.js'
12
+
13
+ export interface ConnectIndexOptions extends GoLiveOptions {
14
+ url?: string
15
+ submitToken?: string
16
+ callbackToken?: string
17
+ /** A connection file holding NETWORK, INDEX_URL, INDEX_SUBMIT_TOKEN and INDEX_CALLBACK_TOKEN; a flag given beside it wins. */
18
+ from?: string
19
+ }
20
+
21
+ const USAGE = 'run npm run connect-index -- --from <connection file>, or npm run connect-index -- --url <index> [--submit-token <t> --callback-token <t>]'
22
+
23
+ export async function connectIndex(options: ConnectIndexOptions): Promise<GoLiveResult> {
24
+ const failure = (problem: string, fix: string): GoLiveResult => {
25
+ options.out(`no connect-index: ${problem}. Fix: ${fix}`)
26
+ return { ok: false, passed: [], failures: [{ check: 'connect-index', problem, fix }] }
27
+ }
28
+ let file: Record<string, string> = {}
29
+ if (options.from != null && options.from !== '') {
30
+ if (!existsSync(options.from)) return failure(`${options.from} does not exist`, 'give the path of the connection file the index operator wrote with dpp-index connection')
31
+ file = readEnvFile(options.from)
32
+ let network: string
33
+ try {
34
+ network = loadConfig(options.env).network
35
+ } catch (cause) {
36
+ return failure(cause instanceof Error ? cause.message : String(cause), 'edit .env as the message says, then run npm run connect-index again')
37
+ }
38
+ const theirs = (file.NETWORK ?? '').trim()
39
+ if (theirs !== '' && theirs !== network) {
40
+ return failure(`${options.from} connects to a ${theirs} index and this app's NETWORK is ${network}`, `ask the operator for a ${network} index, or set NETWORK=${theirs} in .env if this app belongs on ${theirs}`)
41
+ }
42
+ }
43
+ const url = (options.url ?? file.INDEX_URL ?? '').trim().replace(/\/+$/, '')
44
+ if (url === '') return failure(options.from == null ? 'no address given' : `${options.from} holds no INDEX_URL`, USAGE)
45
+ const values: Record<string, string> = { INDEX_URL: url }
46
+ const submitToken = options.submitToken ?? file.INDEX_SUBMIT_TOKEN
47
+ const callbackToken = options.callbackToken ?? file.INDEX_CALLBACK_TOKEN
48
+ if (submitToken != null && submitToken !== '') values.INDEX_SUBMIT_TOKEN = submitToken
49
+ if (callbackToken != null && callbackToken !== '') values.INDEX_CALLBACK_TOKEN = callbackToken
50
+ await updateEnvFile(options.envFile, values)
51
+ options.out(`Wrote the connection to .env: ${url}${values.INDEX_SUBMIT_TOKEN == null ? ', no tokens yet (go-live registers for them)' : ' with its tokens'}.`)
52
+ return await goLive({ ...options, env: { ...options.env, ...values } })
53
+ }
@@ -0,0 +1,49 @@
1
+ // Only the operator supplies these grants. Each names one identity key, product, purpose,
2
+ // role and interval of EPCIS event times. The file is read once when the platform starts.
3
+ import { readFileSync } from 'node:fs'
4
+ import { didKeyFromIdentityKey } from '@bsv/dpp-protocol'
5
+ import { EPCIS_LIFECYCLE_ROLES, parseStrictJcsJson, type EpcisLifecycleAuthorityQuestion, type EpcisLifecycleVerificationOptions } from '@bsv/dpp-credentials/epcis-lifecycle'
6
+
7
+ export type LifecycleAuthorityResolver = NonNullable<EpcisLifecycleVerificationOptions['authorityResolver']>
8
+
9
+ type Grant = Pick<EpcisLifecycleAuthorityQuestion, 'issuer' | 'issuerKey' | 'passportId' | 'purpose' | 'role'> & { from: number; until: number }
10
+ const fields = ['issuer', 'issuerKey', 'passportId', 'purpose', 'role', 'validFrom', 'validUntil'] as const
11
+ const object = (x: unknown): x is Record<string, unknown> => x != null && typeof x === 'object' && !Array.isArray(x)
12
+
13
+ function utcInstant(value: string): number {
14
+ if (!/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d{1,3})?Z$/.test(value)) return NaN
15
+ const time = Date.parse(value)
16
+ return Number.isFinite(time) && new Date(time).toISOString().slice(0, 19) === value.slice(0, 19) ? time : NaN
17
+ }
18
+
19
+ function readGrant(value: unknown, index: number): Grant {
20
+ const error = (field: string): never => { throw new Error('LIFECYCLE_AUTHORITY_GRANTS_FILE: invalid ' + field + ' in grant ' + (index + 1)) }
21
+ if (!object(value) || Object.keys(value).length !== fields.length || !fields.every((k) => typeof value[k] === 'string' && value[k] !== '')) return error('fields')
22
+ const { issuer, issuerKey, passportId, purpose, role, validFrom, validUntil } = value as Record<(typeof fields)[number], string>
23
+ if (!/^did:[a-z0-9]+:(?:[a-zA-Z0-9._:-]|%[a-fA-F0-9]{2})*(?:[a-zA-Z0-9._-]|%[a-fA-F0-9]{2})$/.test(issuer) || issuer.length > 512) return error('issuer')
24
+ if (!/^0[23][a-f0-9]{64}$/.test(issuerKey)) return error('issuerKey')
25
+ let keyDid: string
26
+ try { keyDid = didKeyFromIdentityKey(issuerKey) } catch { return error('issuerKey') }
27
+ if (issuer.startsWith('did:key:') && issuer !== keyDid) return error('issuer/issuerKey')
28
+ if (!/^(?:https?:\/\/|urn:)[^\s*]+$/.test(passportId) || passportId.length > 512 || !URL.canParse(passportId)) return error('passportId')
29
+ if (purpose !== 'claim' && purpose !== 'error-declaration') return error('purpose')
30
+ if (!(EPCIS_LIFECYCLE_ROLES as readonly string[]).includes(role)) return error('role')
31
+ const from = utcInstant(validFrom)
32
+ const until = utcInstant(validUntil)
33
+ if (!(from < until)) return error('validFrom/validUntil')
34
+ return { issuer, issuerKey, passportId, purpose, role: role as Grant['role'], from, until }
35
+ }
36
+
37
+ export function openLifecycleAuthority(path: string): LifecycleAuthorityResolver {
38
+ const document = parseStrictJcsJson(Array.from(readFileSync(path)))
39
+ if (!object(document) || Object.keys(document).length !== 1 || !Array.isArray(document.grants)) {
40
+ throw new Error('LIFECYCLE_AUTHORITY_GRANTS_FILE must contain an object with a grants array')
41
+ }
42
+ const grants = document.grants.map(readGrant)
43
+ return (question) => {
44
+ const eventTime = Date.parse(question.eventTime)
45
+ const found = grants.some((g) => g.issuer === question.issuer && g.issuerKey === question.issuerKey && g.passportId === question.passportId &&
46
+ g.role === question.role && g.purpose === question.purpose && g.from <= eventTime && eventTime < g.until)
47
+ return { status: found ? 'supported' : 'unsupported' }
48
+ }
49
+ }