@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,485 @@
1
+ // EPCIS lifecycle claims in this application (`dpp-epcis-lifecycle@1`, the
2
+ // standard's spec/epcis-lifecycle-claim.md): which of this platform's
3
+ // passports an EPCIS event names, the product comparison a verifier is given,
4
+ // the pinned schema check, and the reading of every claim that concerns one
5
+ // passport, found by its anchors and confirmed by verifying the claim.
6
+ //
7
+ // Nothing here maps a passport operation, a metadata edit or a sale to an
8
+ // event. The only input is an EPCIS event a member entered or one the EPCIS
9
+ // exchange retained, and an event that names none of this platform's
10
+ // passports binds nothing.
11
+ import { createHash } from 'node:crypto'
12
+ import { Utils, type ChainTracker } from '@bsv/sdk'
13
+ import { EPCIS_CONTEXT_IRI, classifyEpcisIdentifier, validateEpcisDocument } from '@bsv/dpp-credentials/epcis-source'
14
+ import { gs1KeyOf, granularityOf, parseGs1DigitalLinkUri, sameGs1Key, type AiValue, type Gs1Key } from '@bsv/dpp-profiles'
15
+ import {
16
+ verifyLifecycleClaim,
17
+ type PartialCheck,
18
+ type SignedLifecycleClaim,
19
+ } from '@bsv/dpp-protocol'
20
+ import {
21
+ EPCIS_LIFECYCLE_CLASS_FIELDS,
22
+ EPCIS_LIFECYCLE_INSTANCE_FIELDS,
23
+ EPCIS_LIFECYCLE_MAX_BYTES,
24
+ EPCIS_LIFECYCLE_REPRESENTATION,
25
+ parseEpcisLifecycleClaim,
26
+ verifyEpcisLifecycleClaim,
27
+ type EpcisLifecycleAnchorEvidence,
28
+ type EpcisLifecycleBinding,
29
+ type EpcisLifecycleBindingField,
30
+ type EpcisLifecycleBindingResult,
31
+ type EpcisLifecycleComparisonInput,
32
+ type EpcisLifecycleFindings,
33
+ type EpcisLifecycleIssuanceOptions,
34
+ type EpcisLifecycleRelation,
35
+ } from '@bsv/dpp-credentials/epcis-lifecycle'
36
+ import { boundedJson, type IndexClient } from './index-client.js'
37
+ import { isEpcisLifecycleRecord, type ClaimFilter, type ClaimRecord, type ClaimRegistryAnswer, type EpcisLifecycleClaimRecord, type Store } from './store.js'
38
+
39
+ /* ------------------------------------------------------------ identity rules */
40
+
41
+ /** The GS1 key of a passport identifier, when it is a GS1 Digital Link of one item; anything else is not compared. */
42
+ function passportKey(passportId: string): Gs1Key | undefined {
43
+ const parsed = parseGs1DigitalLinkUri(passportId)
44
+ if (parsed.kind !== 'uncompressed' || !parsed.primaryKey.checkDigitValid) return undefined
45
+ const key = gs1KeyOf({ gtin: parsed.primaryKey.value, qualifiers: parsed.qualifiers })
46
+ return granularityOf(key.qualifiers) === 'item' ? key : undefined
47
+ }
48
+
49
+ /**
50
+ * The GS1 key an event identifier names, read by the profiles package's
51
+ * identity rules: a GS1 Digital Link is parsed as one, and an SGTIN or LGTIN
52
+ * URN or an SGTIN pattern is read for its GTIN, lot and serial. Nothing is
53
+ * rewritten. A form these rules do not read is unknown, never a match.
54
+ */
55
+ function identifierKey(identifier: string): { key: Gs1Key; item: boolean } | { unknown: string } | { invalid: string } {
56
+ if (/^https?:\/\//.test(identifier)) {
57
+ const parsed = parseGs1DigitalLinkUri(identifier)
58
+ if (parsed.kind !== 'uncompressed') return { unknown: `${identifier} is not an uncompressed GS1 Digital Link the identity rules read` }
59
+ if (!parsed.primaryKey.checkDigitValid) return { invalid: `the GTIN in ${identifier} has a wrong check digit` }
60
+ const key = gs1KeyOf({ gtin: parsed.primaryKey.value, qualifiers: parsed.qualifiers })
61
+ return { key, item: granularityOf(key.qualifiers) === 'item' }
62
+ }
63
+ const finding = classifyEpcisIdentifier('identifier', identifier)
64
+ if (finding.gtin == null || finding.problem != null) return { unknown: `${identifier} is not a GS1 trade item identifier the identity rules read${finding.problem == null ? '' : ` (${finding.problem})`}` }
65
+ const qualifiers: AiValue[] = []
66
+ if (finding.lot != null) qualifiers.push({ ai: '10', value: finding.lot })
67
+ if (finding.serial != null) qualifiers.push({ ai: '21', value: finding.serial })
68
+ const key = gs1KeyOf({ gtin: finding.gtin, qualifiers })
69
+ return { key, item: finding.scheme === 'gs1-sgtin' && granularityOf(key.qualifiers) === 'item' }
70
+ }
71
+
72
+ /**
73
+ * Whether an event identifier denotes the passport's product (spec/profiles.md
74
+ * section 7, through `@bsv/dpp-profiles`). An instance binding holds when the
75
+ * identifier names the passport's own item: same GTIN at fourteen digits, same
76
+ * serial, host not compared. A class binding holds when the class carries the
77
+ * passport's GTIN, and it never says the passport's item took part.
78
+ */
79
+ export function compareLifecycleProduct(input: Pick<EpcisLifecycleComparisonInput, 'passportId' | 'identifier' | 'level'>): PartialCheck {
80
+ const passport = passportKey(input.passportId)
81
+ if (passport == null) return { status: 'unknown', reasonCode: 'x-comparison-unsupported', detail: `${input.passportId} is not a GS1 Digital Link of one item, so the identity rules do not compare it` }
82
+ const named = identifierKey(input.identifier)
83
+ if ('unknown' in named) return { status: 'unknown', reasonCode: 'x-comparison-unsupported', detail: named.unknown }
84
+ if ('invalid' in named) return { status: 'fail', reasonCode: 'stated-gtin-invalid', detail: named.invalid }
85
+ if (input.level === 'instance') {
86
+ if (!named.item) return { status: 'fail', reasonCode: 'x-class-as-item', detail: `${input.identifier} names a model, a lot or a pattern, which never stands in for the passport's item` }
87
+ return sameGs1Key(named.key, passport) ? { status: 'pass', detail: `${input.identifier} names the passport's item under the identity rules` } : { status: 'fail', reasonCode: 'subject-mismatch', detail: `${input.identifier} is not the item ${input.passportId}` }
88
+ }
89
+ return named.key.value === passport.value
90
+ ? { status: 'pass', detail: `${input.identifier} names a class that carries the passport's GTIN; it names no individual item${named.key.qualifiers.some((q) => q.ai === '10') ? ', and the lot is not compared' : ''}` }
91
+ : { status: 'fail', reasonCode: 'subject-mismatch', detail: `${input.identifier} is not a class of ${input.passportId}` }
92
+ }
93
+
94
+ /** An identifier of the event that names none of the passports given, and why. */
95
+ export interface UnboundIdentifier {
96
+ field: EpcisLifecycleBindingField
97
+ identifier: string
98
+ reason: string
99
+ }
100
+
101
+ /**
102
+ * The bindings an event supports to the passports given: every identifier in
103
+ * an object list or a parent (instance level) and every quantity element's
104
+ * class (class level), matched under the identity rules. An identifier that
105
+ * names a class inside an object list binds nothing, because a class is bound
106
+ * through a quantity list only.
107
+ */
108
+ export function bindingsFor(event: Record<string, unknown>, passportIds: string[]): { bindings: EpcisLifecycleBinding[]; unbound: UnboundIdentifier[] } {
109
+ const bindings: EpcisLifecycleBinding[] = []
110
+ const unbound: UnboundIdentifier[] = []
111
+ const consider = (field: EpcisLifecycleBindingField, identifier: unknown, level: 'instance' | 'class'): void => {
112
+ if (typeof identifier !== 'string') return
113
+ const answers = passportIds.map((passportId) => ({ passportId, answer: compareLifecycleProduct({ passportId, identifier, level }) }))
114
+ const matched = answers.filter((a) => a.answer.status === 'pass')
115
+ for (const { passportId } of matched) {
116
+ if (!bindings.some((b) => b.passportId === passportId && b.field === field && b.identifier === identifier)) bindings.push({ passportId, field, identifier, level })
117
+ }
118
+ if (matched.length === 0) {
119
+ const classInList = answers.find((a) => a.answer.reasonCode === 'x-class-as-item')
120
+ unbound.push({ field, identifier, reason: classInList != null ? 'it names a class of products inside a list of individual objects, so it binds no item; a class is bound through a quantity list' : 'it names none of the passports this application holds' })
121
+ }
122
+ }
123
+ for (const field of EPCIS_LIFECYCLE_INSTANCE_FIELDS) {
124
+ const value = event[field]
125
+ if (field === 'parentID') consider(field, value, 'instance')
126
+ else if (Array.isArray(value)) for (const identifier of value) consider(field, identifier, 'instance')
127
+ }
128
+ for (const field of EPCIS_LIFECYCLE_CLASS_FIELDS) {
129
+ const value = event[field]
130
+ if (Array.isArray(value)) for (const element of value) if (element != null && typeof element === 'object') consider(field, (element as Record<string, unknown>).epcClass, 'class')
131
+ }
132
+ return { bindings, unbound }
133
+ }
134
+
135
+ /* ------------------------------------------------------------ the pinned schema */
136
+
137
+ export type EventSchemaCheck = (event: Record<string, unknown>) => PartialCheck
138
+
139
+ /**
140
+ * The pinned EPCIS 2.0.1 schema check, from the GS1 files the EPCIS exchange
141
+ * provisioned. The event is checked as the one event of a document, so the
142
+ * schema reads it as it reads an imported one. Without the files the answer
143
+ * is `unknown`, never `pass`.
144
+ */
145
+ export function eventSchemaCheck(artefactsDir: string): EventSchemaCheck {
146
+ return (event) => {
147
+ try {
148
+ const document = { '@context': [EPCIS_CONTEXT_IRI], type: 'EPCISDocument', schemaVersion: '2.0', creationDate: new Date().toISOString(), epcisBody: { eventList: [event] } }
149
+ const result = validateEpcisDocument(document, { artefactsDir })
150
+ const errors = result.findings.filter((finding) => finding.severity === 'error')
151
+ if (result.schema === 'pass' && errors.length === 0) return { status: 'pass', detail: 'the pinned EPCIS 2.0.1 JSON schema accepted the event' }
152
+ return { status: 'fail', reasonCode: 'schema-invalid', detail: errors.map((finding) => `${finding.path.replace('/epcisBody/eventList/0', '') || '/'}: ${finding.message}`) }
153
+ } catch (cause) {
154
+ return { status: 'unknown', reasonCode: 'schema-unavailable', detail: cause instanceof Error ? cause.message : String(cause) }
155
+ }
156
+ }
157
+ }
158
+
159
+ /* ------------------------------------------------------------ reading */
160
+
161
+ /** A historical native claim, read under its own rules and shown as what it is. */
162
+ export interface HistoricalClaimView {
163
+ claimFormat: 'dpp-lifecycle-v1'
164
+ historical: true
165
+ id: string
166
+ passportId: string
167
+ issuer: string
168
+ issuedBy: string
169
+ createdAt: string
170
+ /** The signed native claim, exactly as it was signed. Its event type is one of the four historical categories and keeps that meaning. */
171
+ claim: SignedLifecycleClaim
172
+ /** The native claim's own signature check (spec/rules.md section 3). */
173
+ signature: string
174
+ registry?: ClaimRegistryAnswer
175
+ }
176
+
177
+ /** One EPCIS lifecycle claim as it concerns one passport: how it was found, what verifying it established, and each finding on its own. */
178
+ export interface LifecycleClaimView {
179
+ claimFormat: 'dpp-epcis-lifecycle@1'
180
+ attestationId: string
181
+ /** `anchor`: an anchor on the index names this passport as its subject. `this-application`: a local record indexes the claim for this passport. */
182
+ foundBy: Array<'anchor' | 'this-application'>
183
+ /** Whether the claim's bytes were available to verify. */
184
+ held: boolean
185
+ unavailable?: string
186
+ /** What verifying the claim established for this passport: its item took part, a class it belongs to took part, or nothing was established. An anchor's subject never decides this. */
187
+ participation: 'item' | 'class' | 'not-established'
188
+ digest?: string
189
+ eventId?: string
190
+ eventType?: string
191
+ event?: Record<string, unknown>
192
+ issuer?: string
193
+ assertedRole?: string
194
+ authorityScope?: string[]
195
+ issuedAt?: string
196
+ source?: Record<string, unknown>
197
+ /** The bindings that name this passport, as verified. */
198
+ bindingsHere: EpcisLifecycleBindingResult[]
199
+ boundPassports: string[]
200
+ itemParticipants: string[]
201
+ /** The claim's own event declares an earlier event in error. */
202
+ declaresError: boolean
203
+ findings?: EpcisLifecycleFindings
204
+ relations: Array<{ digest: string; relation: EpcisLifecycleRelation }>
205
+ anchors: number
206
+ record?: { id: string; issuedBy: string; createdAt: string; importedFrom?: { importId: string; pointer: string }; registry?: ClaimRegistryAnswer }
207
+ }
208
+
209
+ export interface PassportClaimsReading {
210
+ passportId: string
211
+ historical: HistoricalClaimView[]
212
+ lifecycle: LifecycleClaimView[]
213
+ discovery: { index: 'asked' | 'partial' | 'unreachable'; indexDetail?: string; relatedClaims: 'complete' | 'incomplete'; registry: 'configured' | 'not-configured' }
214
+ }
215
+
216
+ export interface ClaimsReaderOptions {
217
+ authorityResolver?: EpcisLifecycleIssuanceOptions['authorityResolver']
218
+ extensionRules?: EpcisLifecycleIssuanceOptions['extensionRules']
219
+ store: Store
220
+ index: IndexClient
221
+ registry?: { url: string }
222
+ chainTracker?: ChainTracker
223
+ schemaCheck?: EventSchemaCheck
224
+ }
225
+
226
+ export const historicalView = (record: ClaimRecord & { claim: SignedLifecycleClaim }): HistoricalClaimView => ({
227
+ claimFormat: 'dpp-lifecycle-v1',
228
+ historical: true,
229
+ id: record.id,
230
+ passportId: record.passportId,
231
+ issuer: record.issuer,
232
+ issuedBy: record.issuedBy,
233
+ createdAt: record.createdAt,
234
+ claim: record.claim,
235
+ signature: verifyLifecycleClaim(record.claim).signature,
236
+ ...(record.registry == null ? {} : { registry: record.registry }),
237
+ })
238
+
239
+ /** The claim's bytes from the registry's proof route, when this application does not hold them. The registry contract carries a current record's exact bytes as `securedBytes`. */
240
+ async function bytesFromRegistry(registry: { url: string } | undefined, attestationId: string, signal: AbortSignal): Promise<{ bytes: string } | { unavailable: string }> {
241
+ if (registry == null) return { unavailable: 'this application does not hold the claim, and no registry is configured to fetch its bytes from' }
242
+ try {
243
+ const response = await fetch(`${registry.url}/attestations/${encodeURIComponent(attestationId)}/proof`, { signal })
244
+ if (!response.ok) return { unavailable: `the registry answered HTTP ${response.status} for the claim's bytes` }
245
+ // The proof contract can carry the same claim as JSON, canonical text and secured text.
246
+ const body = (await boundedJson(response, EPCIS_LIFECYCLE_MAX_BYTES * 8)) as { securedBytes?: unknown }
247
+ if (typeof body.securedBytes !== 'string') return { unavailable: 'the registry returned no bytes for the claim' }
248
+ if (Buffer.byteLength(body.securedBytes) > EPCIS_LIFECYCLE_MAX_BYTES) return { unavailable: 'the registry returned a claim larger than the lifecycle claim limit' }
249
+ return { bytes: body.securedBytes }
250
+ } catch (cause) {
251
+ return { unavailable: `the registry could not be reached (${cause instanceof Error ? cause.message : String(cause)})` }
252
+ }
253
+ }
254
+
255
+ function claimEvent(bytes: string): Record<string, unknown> | undefined {
256
+ try {
257
+ return parseEpcisLifecycleClaim(bytes).event
258
+ } catch {
259
+ return undefined
260
+ }
261
+ }
262
+
263
+ const MAX_CLAIMS = 500
264
+ const MAX_CLAIM_BYTES = 32 * 1024 * 1024
265
+ const claimId = (bytes: string): string => 'urn:sha256:' + createHash('sha256').update(bytes, 'utf8').digest('hex')
266
+
267
+ /** One digest-checked, bounded set for the whole read. Event identifiers group related signed bodies. */
268
+ class RelatedClaims {
269
+ readonly byEvent = new Map<string, Set<string>>()
270
+ readonly correctiveIds = new Map<string, Set<string>>()
271
+ private readonly bytesById = new Map<string, string>()
272
+ complete = true
273
+ private byteLength = 0
274
+
275
+ add(attestationId: string, bytes: string): boolean {
276
+ const known = this.bytesById.get(attestationId)
277
+ if (known != null) return known === bytes
278
+ const length = Buffer.byteLength(bytes)
279
+ if (length > EPCIS_LIFECYCLE_MAX_BYTES || this.bytesById.size >= MAX_CLAIMS || this.byteLength + length > MAX_CLAIM_BYTES || claimId(bytes) !== attestationId) {
280
+ this.complete = false
281
+ return false
282
+ }
283
+ this.bytesById.set(attestationId, bytes)
284
+ this.byteLength += length
285
+ const event = claimEvent(bytes)
286
+ if (typeof event?.eventID === 'string') {
287
+ const others = this.byEvent.get(event.eventID) ?? new Set<string>()
288
+ others.add(bytes)
289
+ this.byEvent.set(event.eventID, others)
290
+ const corrective = (event.errorDeclaration as { correctiveEventIDs?: unknown } | undefined)?.correctiveEventIDs
291
+ if (Array.isArray(corrective)) {
292
+ const ids = this.correctiveIds.get(event.eventID) ?? new Set<string>()
293
+ for (const id of corrective) {
294
+ if (typeof id !== 'string' || ids.has(id)) continue
295
+ if (ids.size >= MAX_CLAIMS) { this.complete = false; break }
296
+ ids.add(id)
297
+ }
298
+ this.correctiveIds.set(event.eventID, ids)
299
+ }
300
+ } else {
301
+ this.complete = false
302
+ }
303
+ return true
304
+ }
305
+
306
+ async list(store: Store, filter: ClaimFilter): Promise<ClaimRecord[]> {
307
+ try {
308
+ const records = await store.listClaims({ ...filter, limit: MAX_CLAIMS + 1 })
309
+ if (records.length > MAX_CLAIMS) this.complete = false
310
+ return records.slice(0, MAX_CLAIMS)
311
+ } catch {
312
+ this.complete = false
313
+ return []
314
+ }
315
+ }
316
+
317
+ async readLocalRelations(store: Store): Promise<void> {
318
+ const read = async (ids: Set<string>) => {
319
+ if (ids.size === 0) return
320
+ if (ids.size > MAX_CLAIMS) this.complete = false
321
+ for (const record of await this.list(store, { eventId: [...ids].slice(0, MAX_CLAIMS) })) {
322
+ if (isEpcisLifecycleRecord(record)) this.add(record.attestationId, record.bytes)
323
+ }
324
+ }
325
+ const original = new Set(this.byEvent.keys())
326
+ await read(original)
327
+ const corrective = new Set<string>()
328
+ for (const eventId of original) {
329
+ for (const id of this.correctiveIds.get(eventId) ?? []) {
330
+ if (original.has(id)) continue
331
+ corrective.add(id)
332
+ if (corrective.size > MAX_CLAIMS) break
333
+ }
334
+ if (corrective.size > MAX_CLAIMS) break
335
+ }
336
+ await read(corrective)
337
+ }
338
+
339
+ forClaim(bytes: string): string[] {
340
+ const eventId = claimEvent(bytes)?.eventID
341
+ if (typeof eventId !== 'string') return []
342
+ const matches = new Set(this.byEvent.get(eventId))
343
+ for (const id of this.correctiveIds.get(eventId) ?? []) {
344
+ for (const candidate of this.byEvent.get(id) ?? []) matches.add(candidate)
345
+ }
346
+ matches.delete(bytes)
347
+ return [...matches].sort()
348
+ }
349
+ }
350
+
351
+ /** Verify against the local event records and every matching remote claim obtained in this passport read. */
352
+ export async function readLifecycleClaim(bytes: string, passportId: string, options: ClaimsReaderOptions & {
353
+ anchors?: EpcisLifecycleAnchorEvidence[]
354
+ foundBy: LifecycleClaimView['foundBy']
355
+ record?: EpcisLifecycleClaimRecord
356
+ related?: RelatedClaims
357
+ }): Promise<LifecycleClaimView> {
358
+ const related = options.related ?? new RelatedClaims()
359
+ if (options.related == null) {
360
+ related.complete = false // The local-only read has not asked the index and registry.
361
+ related.add(options.record?.attestationId ?? claimId(bytes), bytes)
362
+ await related.readLocalRelations(options.store)
363
+ }
364
+ const v = await verifyEpcisLifecycleClaim(bytes, {
365
+ expected: { passportId },
366
+ compareProduct: compareLifecycleProduct,
367
+ authorityResolver: options.authorityResolver,
368
+ extensionRules: options.extensionRules,
369
+ ...(options.schemaCheck == null ? {} : { eventSchemaValidator: options.schemaCheck }),
370
+ ...(options.anchors == null || options.anchors.length === 0 ? {} : { anchors: options.anchors }),
371
+ ...(options.chainTracker == null ? {} : { chainTracker: options.chainTracker }),
372
+ related: { claims: related.forClaim(bytes), complete: related.complete },
373
+ })
374
+ const bindingsHere = v.bindings.filter((b) => b.passportId === passportId)
375
+ const sound = v.findings.signature.status === 'pass' && v.findings.eventStructure.status !== 'fail'
376
+ const participation: LifecycleClaimView['participation'] = !sound ? 'not-established' : v.itemParticipants.includes(passportId) ? 'item' : bindingsHere.some((b) => b.level === 'class' && b.status === 'pass') ? 'class' : 'not-established'
377
+ const record = options.record
378
+ return {
379
+ claimFormat: 'dpp-epcis-lifecycle@1',
380
+ attestationId: v.attestationId ?? `urn:sha256:${v.digest}`,
381
+ foundBy: options.foundBy,
382
+ held: true,
383
+ participation,
384
+ digest: v.digest,
385
+ ...(v.eventId == null ? {} : { eventId: v.eventId }),
386
+ ...(v.eventType == null ? {} : { eventType: v.eventType }),
387
+ ...(v.claim == null
388
+ ? {}
389
+ : { event: v.claim.event, issuer: v.claim.issuer, assertedRole: v.claim.assertedRole, authorityScope: v.claim.authorityScope, issuedAt: v.claim.issuedAt, ...(v.claim.source == null ? {} : { source: v.claim.source as unknown as Record<string, unknown> }) }),
390
+ bindingsHere,
391
+ boundPassports: v.boundPassports,
392
+ itemParticipants: v.itemParticipants,
393
+ declaresError: v.claim?.event.errorDeclaration !== undefined,
394
+ findings: v.findings,
395
+ relations: v.relations,
396
+ anchors: options.anchors?.length ?? 0,
397
+ ...(record == null ? {} : { record: { id: record.id, issuedBy: record.issuedBy, createdAt: record.createdAt, ...(record.importedFrom == null ? {} : { importedFrom: record.importedFrom }), ...(record.registry == null ? {} : { registry: record.registry }) } }),
398
+ }
399
+ }
400
+
401
+ /**
402
+ * Every claim that concerns one passport. Historical native claims are read
403
+ * under their own rules. EPCIS lifecycle claims are found two ways: by the
404
+ * anchors on the index whose subject is the passport, and among the claims
405
+ * this application holds that bind it. Each one found is verified, and only
406
+ * the verified bindings say whether the passport took part: an anchor that
407
+ * names the passport while the claim binds it to nothing is listed as found
408
+ * and not established.
409
+ */
410
+ export async function readPassportClaims(passportId: string, options: ClaimsReaderOptions): Promise<PassportClaimsReading> {
411
+ const signal = AbortSignal.timeout(30_000)
412
+ const related = new RelatedClaims()
413
+ const held = await related.list(options.store, { passportId })
414
+ const historical = held.filter((r): r is ClaimRecord & { claim: SignedLifecycleClaim } => !isEpcisLifecycleRecord(r)).map(historicalView)
415
+ type Candidate = {
416
+ foundBy: Set<'anchor' | 'this-application'>
417
+ record?: EpcisLifecycleClaimRecord
418
+ anchors: Map<string, EpcisLifecycleAnchorEvidence>
419
+ }
420
+ const found = new Map<string, Candidate>()
421
+ for (const record of held.filter(isEpcisLifecycleRecord)) {
422
+ found.set(record.attestationId, { foundBy: new Set(['this-application']), record, anchors: new Map() })
423
+ }
424
+ let index: PassportClaimsReading['discovery']['index'] = 'asked'
425
+ let indexDetail: string | undefined
426
+ let anchorsRead = 0
427
+ try {
428
+ for await (const anchor of options.index.scanAnchors({ subject: passportId }, EPCIS_LIFECYCLE_REPRESENTATION, signal)) {
429
+ anchorsRead += 1
430
+ let entry = found.get(anchor.attestationId)
431
+ if (entry == null) {
432
+ if (found.size >= MAX_CLAIMS) throw new Error(`the passport read exceeded its limit of ${MAX_CLAIMS} claims`)
433
+ entry = { foundBy: new Set(), anchors: new Map() }
434
+ found.set(anchor.attestationId, entry)
435
+ }
436
+ entry.foundBy.add('anchor')
437
+ entry.anchors.set(`${anchor.transaction.id('hex')}:${anchor.outputIndex}`, anchor)
438
+ }
439
+ } catch (cause) {
440
+ index = anchorsRead > 0 ? 'partial' : 'unreachable'
441
+ indexDetail = cause instanceof Error ? cause.message : String(cause)
442
+ related.complete = false
443
+ }
444
+
445
+ const missing = [...found.keys()].filter((id) => found.get(id)!.record == null)
446
+ if (missing.length > 0) {
447
+ for (const record of await related.list(options.store, { attestationIds: missing })) {
448
+ if (isEpcisLifecycleRecord(record)) found.get(record.attestationId)!.record = record
449
+ }
450
+ }
451
+ const lifecycle: LifecycleClaimView[] = []
452
+ const ready: Array<{ bytes: string; attestationId: string; entry: Candidate }> = []
453
+ for (const [attestationId, entry] of found) {
454
+ const local = entry.record?.bytes
455
+ const validLocal = local != null && Buffer.byteLength(local) <= EPCIS_LIFECYCLE_MAX_BYTES && claimId(local) === attestationId
456
+ const obtained = validLocal ? { bytes: local } : await bytesFromRegistry(options.registry, attestationId, signal)
457
+ if ('bytes' in obtained && related.add(attestationId, obtained.bytes)) {
458
+ // Record metadata describes the locally held bytes. Bind it only when those bytes matched.
459
+ if (!validLocal) entry.record = undefined
460
+ ready.push({ bytes: obtained.bytes, attestationId, entry })
461
+ } else {
462
+ related.complete = false
463
+ const unavailable = 'unavailable' in obtained ? obtained.unavailable : 'the claim bytes do not match the requested digest or exceed the read limits'
464
+ lifecycle.push({ claimFormat: 'dpp-epcis-lifecycle@1', attestationId, foundBy: [...entry.foundBy].sort(), held: false, unavailable, participation: 'not-established', bindingsHere: [], boundPassports: [], itemParticipants: [], declaresError: false, relations: [], anchors: entry.anchors.size })
465
+ }
466
+ }
467
+ await related.readLocalRelations(options.store)
468
+ for (const { bytes, attestationId, entry } of ready) {
469
+ if (index !== 'unreachable' && !signal.aborted) {
470
+ try {
471
+ for await (const anchor of options.index.scanAnchors({ attestationId }, EPCIS_LIFECYCLE_REPRESENTATION, signal)) {
472
+ entry.anchors.set(`${anchor.transaction.id('hex')}:${anchor.outputIndex}`, anchor)
473
+ }
474
+ } catch {
475
+ // The original subject lookup and every completed page still provide evidence.
476
+ }
477
+ }
478
+ lifecycle.push(await readLifecycleClaim(bytes, passportId, { ...options, anchors: [...entry.anchors.values()], foundBy: [...entry.foundBy].sort(), record: entry.record, related }))
479
+ }
480
+ lifecycle.sort((a, b) => String(b.issuedAt ?? '').localeCompare(String(a.issuedAt ?? '')) || a.attestationId.localeCompare(b.attestationId))
481
+ return { passportId, historical, lifecycle, discovery: { index, relatedClaims: related.complete ? 'complete' : 'incomplete', ...(indexDetail == null ? {} : { indexDetail }), registry: options.registry == null ? 'not-configured' : 'configured' } }
482
+ }
483
+
484
+ /** The UTF-8 text of claim bytes. */
485
+ export const claimText = (bytes: number[]): string => Utils.toUTF8(bytes)
@@ -7,6 +7,7 @@ import { dirname, join } from 'node:path'
7
7
  import { fileURLToPath } from 'node:url'
8
8
  import { createAuth } from './auth.js'
9
9
  import { loadConfig } from './config.js'
10
+ import { startEpcisExchange } from './epcis/exchange.js'
10
11
  import { openPlatform } from './platform.js'
11
12
  import { createServer } from './server.js'
12
13
  import { startWorker } from './worker.js'
@@ -24,12 +25,16 @@ if (devSession != null) {
24
25
  console.log('Sign-in is off: every request is the developer, a member of "Development brand". Configure MongoDB for sign-in and persistence.')
25
26
  }
26
27
 
28
+ // The EPCIS exchange belongs to the API: its GS1 files are provisioned and its recovery has run before a request is accepted.
29
+ // It is opened beside the platform and is never handed the wallet or the writer.
30
+ const exchange = role === 'only' ? undefined : await startEpcisExchange({ config: config.epcis, db: platform.db, log: (line) => console.log(line) })
31
+
27
32
  let server: ReturnType<ReturnType<typeof createServer>['listen']> | undefined
28
33
  if (role !== 'only') {
29
34
  const here = dirname(fileURLToPath(import.meta.url))
30
35
  const candidates = [join(here, '..', '..', 'web', 'dist'), join(process.cwd(), 'apps', 'web', 'dist')]
31
36
  const webDist = candidates.find((path) => existsSync(join(path, 'index.html')))
32
- const app = createServer({ platform, auth, devSession, webDist })
37
+ const app = createServer({ platform, auth, devSession, webDist, exchange })
33
38
  server = app.listen(config.port, () => {
34
39
  console.log(`API on http://localhost:${config.port}${webDist == null ? ' (no built web app; run the Vite dev server for the pages)' : ', serving the web app'}`)
35
40
  })
@@ -45,6 +50,9 @@ for (const signal of ['SIGINT', 'SIGTERM'] as const) {
45
50
  console.log(`${signal} received, stopping`)
46
51
  worker?.stop()
47
52
  server?.close()
48
- void platform.close().finally(() => process.exit(0))
53
+ void (exchange?.close() ?? Promise.resolve())
54
+ .catch(() => undefined)
55
+ .then(() => platform.close())
56
+ .finally(() => process.exit(0))
49
57
  })
50
58
  }
@@ -1,6 +1,6 @@
1
1
  // Who signs. Under managed custody the platform holds every key: the
2
- // custodian (the platform wallet) publishes every state, holds the lock and
3
- // signs acceptance records; brands, recipients and members are managed
2
+ // platform wallet publishes states and signs acceptance records. The managed
3
+ // controller spends its passport output. Brands, recipients and members are
4
4
  // identities the platform derives from a secret. The `Party` interface is
5
5
  // the seam: a later implementation can be a person's own BRC-100 wallet,
6
6
  // which the standard allows for every role, without changing the writer.