@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
@@ -1,85 +1,204 @@
1
- // Lifecycle claims: a signed statement about a passport, such as a repair or
2
- // a recycling, on its own rail. It never spends the passport. The issuer
3
- // signs it with their own key, a registry validates and stores it and
4
- // publishes a separate anchor, and a reader checks the signature and the
5
- // anchor itself. This platform signs for a signed-in member with the
6
- // managed identity it derives for them, and sends the claim to the
7
- // configured registry over HTTP.
8
- import { PrivateKey, Utils } from '@bsv/sdk'
9
- import { lifecycleClaimDigest, signLifecycleClaim, verifyLifecycleClaim, type LifecycleClaim, type LifecycleEventType, type SignedLifecycleClaim } from '@bsv/dpp-protocol'
1
+ // Lifecycle claims: a signed statement about what happened to one or more
2
+ // products, on its own rail. It never spends a passport. This application
3
+ // issues EPCIS lifecycle claims (`dpp-epcis-lifecycle@1`): one EPCIS 2.0.1
4
+ // event, entered by a member or retained by the EPCIS exchange, in an
5
+ // envelope that binds it to the passports whose products it names and says
6
+ // in which role the member signs. The member's managed identity signs it;
7
+ // that is the wallet step. Sending it to a registry, which verifies it,
8
+ // stores the exact bytes and anchors them once per bound passport, is a
9
+ // separate step the member asks for; that is the blockchain step, and this
10
+ // application takes neither without being asked.
11
+ //
12
+ // Native claims with one of four event types (`dpp-lifecycle-v1`) are no
13
+ // longer issued here. Those this application issued before are kept, read
14
+ // and verified under their own rules, and shown as historical.
15
+ import {
16
+ EPCIS_LIFECYCLE_CLAIM_FORMAT,
17
+ EPCIS_LIFECYCLE_REPRESENTATION,
18
+ EPCIS_LIFECYCLE_ROLES,
19
+ EpcisLifecycleIssuanceRefused,
20
+ type EpcisLifecycleIssuanceOptions,
21
+ buildEpcisLifecycleClaim,
22
+ epcisLifecycleClaimBytes,
23
+ epcisLifecycleClaimDigest,
24
+ signEpcisLifecycleClaim,
25
+ verifyEpcisLifecycleClaim,
26
+ type EpcisLifecycleRole,
27
+ type EpcisLifecycleSource,
28
+ } from '@bsv/dpp-credentials/epcis-lifecycle'
29
+ import { bindingsFor, claimText, compareLifecycleProduct, type EventSchemaCheck } from './lifecycle.js'
10
30
  import type { Party } from './parties.js'
11
- import type { ClaimRecord, PassportRecord, Store } from './store.js'
12
- import { WriteRefused } from './writer.js'
31
+ import type { ClaimRecord, EpcisLifecycleClaimRecord, Store } from './store.js'
32
+ import { WriteRefused, refuseRetiredProfile } from './writer.js'
13
33
 
14
34
  export interface ClaimsOptions {
15
35
  store: Store
36
+ authorityResolver?: EpcisLifecycleIssuanceOptions['authorityResolver']
37
+ extensionRules?: EpcisLifecycleIssuanceOptions['extensionRules']
16
38
  registry?: { url: string; token?: string }
17
39
  }
18
40
 
19
- export const EVENT_TYPES: LifecycleEventType[] = ['Origin', 'Transfer', 'Transformation', 'Disposition']
41
+ export const ASSERTED_ROLES: readonly EpcisLifecycleRole[] = EPCIS_LIFECYCLE_ROLES
42
+
43
+ export interface IssueClaimInput {
44
+ /** One EPCIS 2.0.1 event, exactly as it is to be signed. */
45
+ event: Record<string, unknown>
46
+ issuer: Party
47
+ assertedRole: EpcisLifecycleRole
48
+ /** Qualified issuance covers every bound passport. An explicit scope must include them all. */
49
+ authorityScope?: string[]
50
+ /** The EPCIS party identifier the issuer is, needed to sign as owner or custodian of an event that names party roles. */
51
+ issuerParty?: string
52
+ /** The passport the claim is issued from: it must be among the passports the event names. */
53
+ expectedPassport?: string
54
+ /** Where an imported event came from: the import's digest and the event's place in it. */
55
+ source?: EpcisLifecycleSource
56
+ importedFrom?: { importId: string; pointer: string }
57
+ /** The held signed original for an explicit correction. */
58
+ corrects?: EpcisLifecycleIssuanceOptions['corrects']
59
+ /** Inline prefix declarations the event's extension members are read under. */
60
+ extensionContexts?: Array<Record<string, string>>
61
+ requiredExtensions?: string[]
62
+ /** The pinned EPCIS 2.0.1 schema check. Issuance is refused when it fails or cannot be applied. */
63
+ schemaCheck?: EventSchemaCheck
64
+ /** The issue time; now by default. */
65
+ issuedAt?: string
66
+ }
67
+
68
+ const now = (): string => new Date().toISOString().replace(/\.\d{3}Z$/, 'Z')
69
+
70
+ /**
71
+ * What a registry's answer says when it did not accept the claim, in the
72
+ * registry contract's members: a verification refusal carries `outcome` and
73
+ * `issues`, and is reported as the outcome and the first issue; any other
74
+ * refusal carries `error`.
75
+ */
76
+ function refusalDetail(body: { outcome?: unknown; issues?: unknown; error?: unknown }): string | undefined {
77
+ if (typeof body.outcome === 'string') {
78
+ const first: unknown = Array.isArray(body.issues) ? body.issues[0] : undefined
79
+ return first == null ? body.outcome : `${body.outcome}: ${typeof first === 'string' ? first : JSON.stringify(first)}`
80
+ }
81
+ return typeof body.error === 'string' ? body.error : undefined
82
+ }
20
83
 
21
84
  export class Claims {
22
85
  constructor(private readonly options: ClaimsOptions) {}
23
86
 
24
- /** Sign a claim about the passport's current state as the issuer, and keep it. */
25
- async sign(args: { passport: PassportRecord; issuer: Party; eventType: LifecycleEventType; keyId?: string }): Promise<ClaimRecord> {
26
- const tip = args.passport.states.at(-1)
27
- if (tip == null) throw new WriteRefused('not-issued', `${args.passport.passportId} has no state to claim about`)
28
- const [profile, version] = args.passport.profile.split('@')
29
- const claim: LifecycleClaim = {
30
- claimFormat: 'dpp-lifecycle-v1',
31
- passportId: args.passport.passportId,
32
- recordId: tip.txid,
33
- eventType: args.eventType,
34
- timestamp: new Date().toISOString().replace(/\.\d{3}Z$/, 'Z'),
35
- issuer: args.issuer.did,
36
- issuerKeyId: args.keyId ?? args.issuer.name,
37
- profile,
38
- profile_version: Number(version),
87
+ /**
88
+ * Sign an EPCIS lifecycle claim as the issuer, and keep its exact bytes.
89
+ * The bindings come from the event's own identifiers, matched to this
90
+ * platform's passports under the identity rules: an item identifier binds
91
+ * that item's passport, a quantity element's class binds at class level
92
+ * only. Refused, with nothing signed, when the event names none of the
93
+ * passports, does not name the one it is issued from, names one under a
94
+ * retired profile, fails the pinned schema or any issuance rule.
95
+ */
96
+ async issue(input: IssueClaimInput): Promise<EpcisLifecycleClaimRecord> {
97
+ const { store } = this.options
98
+ const passports = await store.listPassports()
99
+ const { bindings, unbound } = bindingsFor(input.event, passports.map((p) => p.passportId))
100
+ if (bindings.length === 0) {
101
+ throw new WriteRefused('event-binds-no-passport', `the event names none of this platform's passports, so there is nothing to bind it to${unbound.length === 0 ? '' : `: ${unbound.map((u) => `${u.identifier} in ${u.field}: ${u.reason}`).join('; ')}`}. Nothing was signed.`, { unbound })
102
+ }
103
+ const bound = [...new Set(bindings.map((b) => b.passportId))]
104
+ if (input.expectedPassport != null && !bound.includes(input.expectedPassport)) {
105
+ throw new WriteRefused('passport-not-bound', `the event does not name ${input.expectedPassport} under the identity rules, so a claim issued from it would not concern it. It names ${bound.join(', ')}. Nothing was signed.`, { boundPassports: bound, unbound })
106
+ }
107
+ // A passport under a retired profile gets no further claim, as it gets no further state.
108
+ for (const passportId of bound) refuseRetiredProfile(passports.find((p) => p.passportId === passportId)!.profile)
109
+
110
+ if (input.schemaCheck == null) throw new WriteRefused('event-schema-unavailable', 'the pinned EPCIS 2.0.1 schema is not available to this application, so no event is signed. Nothing was signed.')
111
+ const schema = input.schemaCheck(input.event)
112
+ if (schema.status === 'fail') throw new WriteRefused('event-schema-invalid', 'the pinned EPCIS 2.0.1 schema refuses the event. Nothing was signed.', { findings: schema.detail })
113
+ if (schema.status !== 'pass') throw new WriteRefused('event-schema-unavailable', `the pinned EPCIS 2.0.1 schema could not be applied (${String(schema.detail ?? schema.reasonCode)}). Nothing was signed.`)
114
+
115
+ const authorityScope = input.authorityScope ?? bound
116
+ const missing = bound.filter((passportId) => !authorityScope.includes(passportId))
117
+ if (missing.length > 0) throw new WriteRefused('authority-scope-incomplete', 'Qualified issuance requires the asserted role for every bound passport. Nothing was signed.', { missing })
118
+ let signed
119
+ try {
120
+ const claim = buildEpcisLifecycleClaim({
121
+ event: input.event,
122
+ ...(input.extensionContexts == null || input.extensionContexts.length === 0 ? {} : { extensionContexts: input.extensionContexts }),
123
+ bindings,
124
+ issuer: input.issuer.did,
125
+ ...(input.issuerParty == null ? {} : { issuerParty: input.issuerParty }),
126
+ assertedRole: input.assertedRole,
127
+ authorityScope,
128
+ issuedAt: input.issuedAt ?? now(),
129
+ ...(input.requiredExtensions == null || input.requiredExtensions.length === 0 ? {} : { requiredExtensions: input.requiredExtensions }),
130
+ ...(input.source == null ? {} : { source: input.source }),
131
+ })
132
+ signed = await signEpcisLifecycleClaim(claim, input.issuer.wallet, {
133
+ compareProduct: compareLifecycleProduct,
134
+ eventSchemaValidator: () => schema,
135
+ authorityResolver: this.options.authorityResolver,
136
+ extensionRules: this.options.extensionRules,
137
+ corrects: input.corrects,
138
+ })
139
+ } catch (cause) {
140
+ if (cause instanceof EpcisLifecycleIssuanceRefused) throw new WriteRefused(cause.code, cause.message + '. Nothing was signed.', { finding: cause.finding })
141
+ const detail = cause instanceof Error ? cause.message : String(cause)
142
+ const prefix = 'the claim cannot be issued: '
143
+ throw new WriteRefused('claim-refused', `${detail}. Nothing was signed.`, { reasons: detail.startsWith(prefix) ? detail.slice(prefix.length).split('; ') : [detail] })
39
144
  }
40
- const signed = await signLifecycleClaim(claim, args.issuer.wallet)
41
- if (verifyLifecycleClaim(signed).signature !== 'verified') throw new WriteRefused('claim-unsigned', 'the signed claim does not verify under its own issuer key')
42
- const record: ClaimRecord = {
43
- id: `claim-${lifecycleClaimDigest(signed).slice(0, 16)}-${Utils.toHex(PrivateKey.fromRandom().toArray().slice(0, 4))}`,
44
- passportId: args.passport.passportId,
145
+ const bytes = claimText(epcisLifecycleClaimBytes(signed))
146
+ const verified = await verifyEpcisLifecycleClaim(bytes)
147
+ if (verified.findings.signature.status !== 'pass') throw new WriteRefused('claim-unsigned', 'the signed claim does not verify under its own issuer key')
148
+ const digest = epcisLifecycleClaimDigest(signed)
149
+ const record: EpcisLifecycleClaimRecord = {
150
+ id: `claim-${digest.slice(0, 16)}`,
151
+ claimFormat: EPCIS_LIFECYCLE_CLAIM_FORMAT,
152
+ passportId: input.expectedPassport ?? bound[0]!,
153
+ boundPassports: verified.boundPassports,
154
+ attestationId: `urn:sha256:${digest}`,
155
+ digest,
156
+ eventId: String(signed.event.eventID),
157
+ eventType: String(signed.event.type),
45
158
  issuer: signed.issuer,
46
- issuedBy: args.issuer.name,
47
- claim: signed,
48
- createdAt: claim.timestamp,
159
+ issuedBy: input.issuer.name,
160
+ bytes,
161
+ ...(input.importedFrom == null ? {} : { importedFrom: input.importedFrom }),
162
+ createdAt: signed.issuedAt,
49
163
  }
50
- await this.options.store.saveClaim(record)
164
+ // Identical bytes are the same claim: kept once.
165
+ const held = (await store.listClaims({ eventId: record.eventId })).find((c) => c.id === record.id)
166
+ if (held != null) return held as EpcisLifecycleClaimRecord
167
+ await store.saveClaim(record)
51
168
  return record
52
169
  }
53
170
 
54
- /** Send a signed claim to the registry to verify, store and anchor (POST /attestations). Storing needs the registry's permission. */
171
+ /**
172
+ * Send a claim to the registry to verify, store and anchor (POST /attestations): the exact bytes, which the registry
173
+ * anchors once per bound passport. Storing needs the registry's permission. Only EPCIS lifecycle claims are sent:
174
+ * this application issues no other kind.
175
+ */
55
176
  async submit(record: ClaimRecord): Promise<ClaimRecord> {
56
177
  const registry = this.options.registry
57
178
  if (registry == null) throw new WriteRefused('registry-unset', 'REGISTRY_URL is not set')
58
- const response = await fetch(`${registry.url}/attestations`, {
59
- method: 'POST',
60
- headers: { 'Content-Type': 'application/json', ...(registry.token != null ? { Authorization: `Bearer ${registry.token}` } : {}) },
61
- body: JSON.stringify(record.claim),
62
- })
63
- const body = (await response.json().catch(() => ({}))) as { accepted?: boolean; attestationId?: string; description?: string; error?: string }
179
+ if (record.claimFormat !== EPCIS_LIFECYCLE_CLAIM_FORMAT) throw new WriteRefused('claim-historical', 'a historical native claim is kept as it is and is not sent again')
180
+ let response: Response
181
+ try {
182
+ response = await fetch(`${registry.url}/attestations`, {
183
+ method: 'POST',
184
+ headers: { 'Content-Type': 'application/json', ...(registry.token != null ? { Authorization: `Bearer ${registry.token}` } : {}) },
185
+ body: JSON.stringify({ representation: EPCIS_LIFECYCLE_REPRESENTATION, claim: record.bytes, subject: record.passportId }),
186
+ })
187
+ } catch (cause) {
188
+ record.registry = { url: registry.url, status: 0, accepted: false, detail: `the registry could not be reached (${cause instanceof Error ? cause.message : String(cause)})` }
189
+ await this.options.store.saveClaim(record)
190
+ return record
191
+ }
192
+ const body = (await response.json().catch(() => ({}))) as { accepted?: boolean; attestationId?: string; outcome?: unknown; issues?: unknown; error?: unknown }
193
+ const detail = refusalDetail(body)
64
194
  record.registry = {
65
195
  url: registry.url,
66
196
  status: response.status,
67
197
  accepted: response.status === 202 && body.accepted === true,
68
- attestationId: body.attestationId,
69
- detail: body.description ?? body.error,
198
+ ...(body.attestationId == null ? {} : { attestationId: body.attestationId }),
199
+ ...(detail == null ? {} : { detail }),
70
200
  }
71
201
  await this.options.store.saveClaim(record)
72
202
  return record
73
203
  }
74
-
75
- /** Ask the registry to check a claim without storing it (POST /validate is open on the hosted reference). */
76
- async validate(claim: SignedLifecycleClaim): Promise<unknown> {
77
- const registry = this.options.registry
78
- if (registry == null) throw new WriteRefused('registry-unset', 'REGISTRY_URL is not set')
79
- const url = new URL('/validate', registry.url)
80
- url.searchParams.set('subject', claim.passportId)
81
- const response = await fetch(url, { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(claim) })
82
- if (!response.ok) throw new WriteRefused('registry-refused', `the registry answered HTTP ${response.status} to /validate`)
83
- return await response.json()
84
- }
85
204
  }
@@ -1,26 +1,85 @@
1
1
  #!/usr/bin/env node
2
2
  // Operator commands against the running configuration, with no HTTP:
3
3
  //
4
- // node apps/api/dist/cli.js wallet publisher key, a funding address, balance
4
+ // node apps/api/dist/cli.js wallet publisher key, a funding address, balance; the first run generates WALLET_ROOT_KEY
5
5
  // node apps/api/dist/cli.js wallet fund <txid> <address> <prefix> <suffix>
6
6
  // take in a payment made to a funding address
7
7
  // node apps/api/dist/cli.js operations what is still owed, and run the duties once
8
+ // node apps/api/dist/cli.js go-live register with the index, check everything a real write needs, go live
9
+ // node apps/api/dist/cli.js connect-index --url <index> [--submit-token <t>] [--callback-token <t>]
10
+ // node apps/api/dist/cli.js connect-index --from <file>
11
+ // the connection file an index operator wrote with dpp-index connection
12
+ // node apps/api/dist/cli.js export --out <folder> [--public]
13
+ // the complete export of this application, as one signed evidence package
14
+ // node apps/api/dist/cli.js restore --from <folder> [--exporter-key <key>]
15
+ // restore an authorised export into this deployment; verifies everything first
16
+ // node apps/api/dist/cli.js epcis-remap --source <name>
17
+ // declare that an EPCIS source is now reached at its configured address
8
18
  import './env.js'
19
+ import { existsSync, readFileSync } from 'node:fs'
20
+ import { basename, dirname, join, resolve } from 'node:path'
21
+ import { fileURLToPath } from 'node:url'
22
+ import { parseArgs } from 'node:util'
9
23
  import { loadConfig } from './config.js'
24
+ import { generateRootKey, ROOT_KEY_GENERATED } from './env-file.js'
25
+ import { goLive } from './go-live.js'
26
+ import { connectIndex } from './index-projects.js'
10
27
  import { openPlatform } from './platform.js'
28
+ import { PORTABILITY_USAGE, runExportCommand, runRemapCommand, runRestoreCommand } from './portability/commands.js'
11
29
  import { pendingDuties, runDuties } from './worker.js'
12
30
  import { ANYONE_IDENTITY_KEY } from './wallet.js'
13
31
 
14
32
  const [command, ...rest] = process.argv.slice(2)
15
- const config = loadConfig()
16
- const platform = await openPlatform({ config, mode: 'live', log: () => {} })
33
+ const projectRoot = resolve(dirname(fileURLToPath(import.meta.url)), '../../..')
34
+ const envFile = join(projectRoot, '.env')
35
+ const manifest = ((): { name?: string } => {
36
+ try {
37
+ return JSON.parse(readFileSync(join(projectRoot, 'package.json'), 'utf8')) as { name?: string }
38
+ } catch {
39
+ return {}
40
+ }
41
+ })()
42
+ const projectName = manifest.name ?? basename(projectRoot)
43
+
44
+ if (command === 'export' || command === 'restore' || command === 'epcis-remap') {
45
+ // The export, the restore and the source remap are the operator's, run on the host with the API stopped (portability/commands.ts).
46
+ // npm names the directory it was called from in INIT_CWD; a relative folder is read from there.
47
+ const context = { env: process.env, out: (line: string) => console.log(line), cwd: process.env.INIT_CWD ?? process.cwd() }
48
+ process.exitCode = await (command === 'export' ? runExportCommand(rest, context) : command === 'restore' ? runRestoreCommand(rest, context) : runRemapCommand(rest, context))
49
+ } else if (command === 'go-live' || command === 'connect-index') {
50
+ const { values } = parseArgs({ args: rest, options: { url: { type: 'string' }, 'submit-token': { type: 'string' }, 'callback-token': { type: 'string' }, from: { type: 'string' } } })
51
+ const shared = { env: process.env, envFile, projectName, out: (line: string) => console.log(line) }
52
+ // npm names the directory it was called from in INIT_CWD; a relative --from is read from there.
53
+ const from = values.from == null ? undefined : resolve(process.env.INIT_CWD ?? process.cwd(), values.from)
54
+ const result =
55
+ command === 'go-live'
56
+ ? await goLive(shared)
57
+ : await connectIndex({ ...shared, url: values.url, submitToken: values['submit-token'], callbackToken: values['callback-token'], from })
58
+ if (!result.ok) process.exitCode = 1
59
+ } else {
60
+ // The publisher key wallet prints is the one an index is given. Without a
61
+ // root key it would be the stand-in test wallet's, whose private half is
62
+ // public, so in the project the first run generates the key into .env, as
63
+ // go-live does. A container has no .env to write to; wallet refuses there.
64
+ if (command === 'wallet' && rest.length === 0 && existsSync(envFile) && (await generateRootKey(envFile, process.env))) console.log(ROOT_KEY_GENERATED)
65
+ const config = loadConfig()
66
+ const platform = await openPlatform({ config, mode: 'live', log: () => {} })
67
+ try {
68
+ await operatorCommand(platform, config)
69
+ } finally {
70
+ await platform.close()
71
+ }
72
+ }
17
73
 
18
- try {
74
+ async function operatorCommand(platform: Awaited<ReturnType<typeof openPlatform>>, config: ReturnType<typeof loadConfig>): Promise<void> {
19
75
  if (command === 'wallet' && rest[0] === 'fund') {
20
76
  const [txid, address, derivationPrefix, derivationSuffix] = rest.slice(1)
21
77
  if (txid == null || address == null || derivationPrefix == null || derivationSuffix == null) throw new Error('usage: wallet fund <txid> <address> <prefix> <suffix>')
22
78
  const taken = await platform.wallet.internalize({ address, derivationPrefix, derivationSuffix, senderIdentityKey: ANYONE_IDENTITY_KEY }, txid)
23
79
  console.log(`Took in ${taken.satoshis} satoshis from ${txid}. Balance: ${await platform.wallet.balance()} satoshis.`)
80
+ } else if (command === 'wallet' && config.wallet.rootKeyHex == null) {
81
+ console.error('No publisher key: WALLET_ROOT_KEY is not set, so a test wallet with fixed, publicly known keys stands in. Never give an index its key or pay its address. Set WALLET_ROOT_KEY, or run npm run wallet in the project, which generates it into .env.')
82
+ process.exitCode = 1
24
83
  } else if (command === 'wallet') {
25
84
  const funding = await platform.wallet.fundingAddress()
26
85
  console.log(`Publisher key (give this to your index; it is public): ${platform.wallet.identityKey}`)
@@ -34,9 +93,7 @@ try {
34
93
  for (const d of duties) console.log(` ${d.op} ${d.txid.slice(0, 12)}... ${d.duty} (${d.passportId})`)
35
94
  for (const line of await runDuties({ store: platform.store, index: platform.index, writer: platform.writer })) console.log(` ${line}`)
36
95
  } else {
37
- console.error('usage: cli.js wallet | wallet fund <txid> <address> <prefix> <suffix> | operations')
96
+ console.error(`usage: cli.js wallet | wallet fund <txid> <address> <prefix> <suffix> | operations | go-live | connect-index --url <index> [--submit-token <t>] [--callback-token <t>] | connect-index --from <connection file> | ${PORTABILITY_USAGE}`)
38
97
  process.exitCode = 2
39
98
  }
40
- } finally {
41
- await platform.close()
42
99
  }
@@ -1,9 +1,18 @@
1
1
  // Configuration is environment only. Secrets are read here once and never
2
2
  // printed. `npm test` and `npm run dev` work with the defaults; the values
3
3
  // marked live in .env.example are needed only to write real passports.
4
+ import { loadEpcisSources, type EpcisSourceConfig } from './epcis/sources.js'
4
5
 
5
6
  export type Network = 'main' | 'test'
6
7
 
8
+ /**
9
+ * Where the EPCIS exchange keeps what it retains. `mongodb` is the adapter this application is built and tested on:
10
+ * the application database, or memory when there is none. `file` is the module's file-system adapter over a folder.
11
+ * It passes the same adapter suite and exists so that the storage can be replaced and a restore can be shown to land
12
+ * in another adapter; it is not offered as a second production database.
13
+ */
14
+ export type EpcisStorageChoice = { kind: 'mongodb' } | { kind: 'file'; dir: string }
15
+
7
16
  export interface Config {
8
17
  network: Network
9
18
  port: number
@@ -14,12 +23,42 @@ export interface Config {
14
23
  wallet: { rootKeyHex?: string; filePath: string; wocApiKey?: string; arcUrl?: string }
15
24
  brandRootSecret: string
16
25
  managedIdentitySecret: string
17
- index: { url?: string; submitToken?: string; callbackToken?: string }
26
+ /** `joined`: the address and both write tokens are set, so the app announces to this index; without tokens the index is one the app has not registered with yet (go-live). */
27
+ index: { url?: string; submitToken?: string; callbackToken?: string; joined: boolean; supportsRetraction: boolean }
18
28
  passportHost: string
19
29
  gs1Prefix: string
20
30
  registry: { url?: string; token?: string }
31
+ lifecycleAuthorityGrantsFile?: string
32
+ /**
33
+ * The index's evidence export, read when this application is exported: the bearer its complete export wants, when
34
+ * it wants one, and the exporter identity key to hold its packages to. Without the key, the one its capability
35
+ * document names is used and recorded.
36
+ */
37
+ indexExport: { token?: string; exporterKey?: string }
38
+ /** Profiles held by a binding in a folder of your own, and the binding digests this deployment trusts for them. */
39
+ customProfiles: { dirs: string[]; trustedBindingDigests: string[] }
40
+ /**
41
+ * Where bound profiles are resolved from. Unset, the packaged sector editions are read from the folder the profiles
42
+ * package ships. Set, they are read from this folder, which holds a profile bundle as a restore installs it, and
43
+ * the package's own folder is not read.
44
+ */
45
+ profileBundleDir?: string
46
+ /**
47
+ * The validation engine for profiles held by a binding. Without an address the JSON-LD and SHACL libraries run in
48
+ * this process. With one, a validator service at that address is asked, and the token is sent to it and nowhere
49
+ * else. The token is read here once and is never printed.
50
+ */
51
+ validator: { url?: string; token?: string }
52
+ /**
53
+ * EPCIS exchange: the folder the pinned GS1 files are provisioned into and read from, whether start-up may fetch
54
+ * them, and the query sources a pull may be made from. A source's credential is read through a function and is
55
+ * never a plain member of this object.
56
+ */
57
+ epcis: { gs1Dir: string; gs1Offline: boolean; sources: EpcisSourceConfig[]; storage: EpcisStorageChoice }
21
58
  livePublishing: boolean
22
59
  spendCapSatoshis: number
60
+ /** DPP_TEST_WALLET=1: the scaffold check's switch for the test wallet on the configured root key. */
61
+ testWallet: boolean
23
62
  }
24
63
 
25
64
  const text = (env: NodeJS.ProcessEnv, name: string): string | undefined => {
@@ -27,6 +66,37 @@ const text = (env: NodeJS.ProcessEnv, name: string): string | undefined => {
27
66
  return value == null || value === '' ? undefined : value
28
67
  }
29
68
 
69
+ /** The hosted indexes and the network each serves: go-live refuses a known host on the other network. */
70
+ export const KNOWN_INDEX_HOSTS: Record<string, Network> = {
71
+ 'dpp-overlay-testnet.bsvb.net': 'test',
72
+ 'dpp-overlay-mainnet.bsvb.net': 'main',
73
+ 'dpp-overlay.bsvb.net': 'main',
74
+ }
75
+
76
+ /** A comma-separated setting as its entries, without the empty ones. */
77
+ const list = (env: NodeJS.ProcessEnv, name: string): string[] =>
78
+ (text(env, name) ?? '')
79
+ .split(',')
80
+ .map((entry) => entry.trim())
81
+ .filter((entry) => entry !== '')
82
+
83
+ const SECRETS = ['AUTH_SECRET', 'BRAND_ROOT_SECRET', 'MANAGED_IDENTITY_SECRET'] as const
84
+ const DEVELOPMENT_DEFAULTS: Record<(typeof SECRETS)[number], string> = {
85
+ AUTH_SECRET: 'development-only-secret-replace-me-before-deploying',
86
+ BRAND_ROOT_SECRET: 'development-only-brand-secret-replace-me',
87
+ MANAGED_IDENTITY_SECRET: 'development-only-managed-identity-secret-replace-me',
88
+ }
89
+
90
+ /** A secret as set, or its development default when unset; a value copied from .env.example stops the start by name, and the value is never echoed. */
91
+ function secret(env: NodeJS.ProcessEnv, name: (typeof SECRETS)[number]): string {
92
+ const value = text(env, name)
93
+ if (value == null) return DEVELOPMENT_DEFAULTS[name]
94
+ if (value === 'change-me-to-32-random-bytes-hex' || value.startsWith('development-only-')) {
95
+ throw new Error(`${name} is a placeholder from .env.example: set it to 32 random bytes (openssl rand -hex 32), or scaffold the project again so one is generated`)
96
+ }
97
+ return value
98
+ }
99
+
30
100
  /** Read the configuration from an environment. Missing secrets get development defaults that the README says to replace. */
31
101
  export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
32
102
  const network = (text(env, 'NETWORK') ?? 'main') as Network
@@ -35,32 +105,76 @@ export function loadConfig(env: NodeJS.ProcessEnv = process.env): Config {
35
105
  const rootKeyHex = text(env, 'WALLET_ROOT_KEY')
36
106
  if (rootKeyHex != null && !/^[0-9a-fA-F]{64}$/.test(rootKeyHex)) throw new Error('WALLET_ROOT_KEY must be 64 hexadecimal characters')
37
107
  if (livePublishing && rootKeyHex == null) throw new Error('LIVE_PUBLISHING=true needs WALLET_ROOT_KEY')
108
+ const indexUrl = text(env, 'INDEX_URL')?.replace(/\/+$/, '')
109
+ // The optional retraction route is absent from core-only indexes. Bind the operator's
110
+ // confirmation to this base URL so switching provider cannot inherit it.
111
+ const retractionUrl = text(env, 'INDEX_RETRACTION_URL')?.replace(/\/+$/, '')
112
+ const supportsRetraction = retractionUrl == null
113
+ ? Object.keys(KNOWN_INDEX_HOSTS).some(host => indexUrl === `https://${host}`)
114
+ : retractionUrl === indexUrl
115
+ const submitToken = text(env, 'INDEX_SUBMIT_TOKEN')
116
+ const callbackToken = text(env, 'INDEX_CALLBACK_TOKEN')
117
+ const joined = indexUrl != null && submitToken != null && callbackToken != null
38
118
  // A real passport announced only to the in-process index would be on the chain and findable by nobody after a restart.
39
- if (livePublishing && text(env, 'INDEX_URL') == null) throw new Error('LIVE_PUBLISHING=true needs INDEX_URL: connect an index that persists before writing to the chain (README, Connect an index)')
119
+ if (livePublishing && indexUrl == null) throw new Error('LIVE_PUBLISHING=true needs INDEX_URL: connect an index that persists before writing to the chain (README, Connect an index)')
120
+ if (livePublishing && !joined) throw new Error('LIVE_PUBLISHING=true needs the index tokens: run npm run go-live, which registers this app with the index and stores them')
121
+ // Trust is the digest of exact bytes, so a value that is not a digest is a mistake to fix, never something to guess at.
122
+ const trustedBindingDigests = list(env, 'TRUSTED_BINDING_DIGESTS')
123
+ for (const digest of trustedBindingDigests) {
124
+ if (!/^[0-9a-f]{64}$/.test(digest)) throw new Error(`TRUSTED_BINDING_DIGESTS holds "${digest}", which is not a binding digest: each entry is the SHA-256 of a binding.json, 64 lower-case hexadecimal characters`)
125
+ }
126
+ const epcisStorage = text(env, 'EPCIS_STORAGE') ?? 'mongodb'
127
+ if (epcisStorage !== 'mongodb' && epcisStorage !== 'file') throw new Error('EPCIS_STORAGE must be mongodb or file')
128
+ // A mistake in the validator's address stops the start and is named. The value is not repeated: an address can carry a secret someone put there.
129
+ const validatorUrl = text(env, 'VALIDATOR_URL')?.replace(/\/+$/, '')
130
+ const validatorToken = text(env, 'VALIDATOR_TOKEN')
131
+ if (validatorUrl != null) {
132
+ let parsed: URL | undefined
133
+ try {
134
+ parsed = new URL(validatorUrl)
135
+ } catch {
136
+ // Reported below.
137
+ }
138
+ if (parsed == null || (parsed.protocol !== 'http:' && parsed.protocol !== 'https:')) throw new Error('VALIDATOR_URL must be the http or https address of a validator service')
139
+ if (parsed.username !== '' || parsed.password !== '') throw new Error('VALIDATOR_URL carries user information: set the service\'s token in VALIDATOR_TOKEN')
140
+ if (parsed.search !== '' || parsed.hash !== '') throw new Error('VALIDATOR_URL carries a query or a fragment: give the address only')
141
+ }
142
+ if (validatorToken != null && validatorUrl == null) throw new Error('VALIDATOR_TOKEN is set without VALIDATOR_URL: the token belongs to a validator service, so name its address or remove the token')
143
+ if (validatorToken != null && !/^[\x21-\x7e]+$/.test(validatorToken)) throw new Error('VALIDATOR_TOKEN must be visible ASCII with no spaces')
144
+ const indexExporterKey = text(env, 'INDEX_EXPORTER_KEY')
145
+ if (indexExporterKey != null && !/^0[23][0-9a-f]{64}$/.test(indexExporterKey)) throw new Error('INDEX_EXPORTER_KEY must be a compressed public key: 66 lower-case hexadecimal characters starting 02 or 03')
40
146
  return {
41
147
  network,
42
148
  port: Number(text(env, 'PORT') ?? 3000),
43
149
  publicUrl: (text(env, 'PUBLIC_URL') ?? 'http://localhost:3000').replace(/\/+$/, ''),
44
150
  mongoUrl: text(env, 'MONGO_URL') ?? 'mongodb://127.0.0.1:27017',
45
151
  mongoDb: text(env, 'MONGO_DB') ?? 'dpp_app',
46
- authSecret: text(env, 'AUTH_SECRET') ?? 'development-only-secret-replace-me-before-deploying',
152
+ authSecret: secret(env, 'AUTH_SECRET'),
47
153
  wallet: {
48
154
  rootKeyHex,
49
155
  filePath: text(env, 'WALLET_FILE') ?? 'local/wallet.sqlite',
50
156
  wocApiKey: text(env, 'WOC_API_KEY'),
51
157
  arcUrl: text(env, 'ARC_URL'),
52
158
  },
53
- brandRootSecret: text(env, 'BRAND_ROOT_SECRET') ?? 'development-only-brand-secret-replace-me',
54
- managedIdentitySecret: text(env, 'MANAGED_IDENTITY_SECRET') ?? 'development-only-managed-identity-secret-replace-me',
55
- index: {
56
- url: text(env, 'INDEX_URL')?.replace(/\/+$/, ''),
57
- submitToken: text(env, 'INDEX_SUBMIT_TOKEN'),
58
- callbackToken: text(env, 'INDEX_CALLBACK_TOKEN'),
59
- },
159
+ brandRootSecret: secret(env, 'BRAND_ROOT_SECRET'),
160
+ managedIdentitySecret: secret(env, 'MANAGED_IDENTITY_SECRET'),
161
+ index: { url: indexUrl, submitToken, callbackToken, joined, supportsRetraction },
60
162
  passportHost: text(env, 'PASSPORT_HOST') ?? 'localhost:3000',
61
163
  gs1Prefix: text(env, 'GS1_PREFIX') ?? '952',
62
164
  registry: { url: text(env, 'REGISTRY_URL')?.replace(/\/+$/, ''), token: text(env, 'REGISTRY_TOKEN') },
165
+ lifecycleAuthorityGrantsFile: text(env, 'LIFECYCLE_AUTHORITY_GRANTS_FILE'),
166
+ indexExport: { token: text(env, 'INDEX_EXPORT_TOKEN'), exporterKey: indexExporterKey },
167
+ customProfiles: { dirs: list(env, 'CUSTOM_PROFILE_DIRS'), trustedBindingDigests },
168
+ profileBundleDir: text(env, 'PROFILE_BUNDLE_DIR'),
169
+ validator: { url: validatorUrl, token: validatorToken },
170
+ epcis: {
171
+ gs1Dir: text(env, 'DPP_GS1_ARTEFACTS_DIR') ?? 'local/gs1',
172
+ gs1Offline: text(env, 'DPP_GS1_ARTEFACTS_OFFLINE') === 'true',
173
+ sources: loadEpcisSources(env),
174
+ storage: epcisStorage === 'file' ? { kind: 'file', dir: text(env, 'EPCIS_STORAGE_DIR') ?? 'local/epcis-store' } : { kind: 'mongodb' },
175
+ },
63
176
  livePublishing,
64
177
  spendCapSatoshis: Number(text(env, 'SPEND_CAP_SATOSHIS') ?? 20_000),
178
+ testWallet: text(env, 'DPP_TEST_WALLET') === '1',
65
179
  }
66
180
  }