@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,590 @@
1
+ // Profiles held by a binding: a data model defined outside @bsv/dpp-profiles,
2
+ // as JSON-LD contexts and SHACL shapes or as a JSON Schema, that the package
3
+ // validates through one immutable binding file. This module is assembled once
4
+ // at start-up: it opens the validation engine the configuration chose
5
+ // (validation-engine.ts), registers the profiles and any folder the
6
+ // configuration names, and then answers for the writer, the reader and the
7
+ // forms.
8
+ //
9
+ // Where the profiles come from is a setting. By default both editions of each sector
10
+ // bindings are read from the folder the profiles package ships. With
11
+ // PROFILE_BUNDLE_DIR they are read from a profile bundle in that folder, as a
12
+ // restore installs it, and the package's folder is not read. The bundle is a
13
+ // second resolver for the same registry: the files come from somewhere else,
14
+ // and every rule about them stays the same.
15
+ //
16
+ // Three rules hold throughout. Trust is a list of binding digests, and a
17
+ // folder or a bundle whose digest is not on it is refused. A check that could
18
+ // not run is never a pass, so without the engine a bound profile cannot be
19
+ // written and a reading says "not checked". No profile file is ever fetched:
20
+ // every context is read from the binding's own folder or from the bundle.
21
+ import { readFileSync } from 'node:fs'
22
+ import { dirname, isAbsolute, join, resolve } from 'node:path'
23
+ import { fileURLToPath } from 'node:url'
24
+ import {
25
+ BUNDLED_BINDINGS,
26
+ BUNDLED_BINDING_DIGESTS,
27
+ authorisedPayloadValidator,
28
+ bindingPayloadValidator,
29
+ bundledBindingLicenceTexts,
30
+ bundledBindingNotices,
31
+ createProfileRegistry,
32
+ openProfileBundle,
33
+ prepareBoundPayload,
34
+ profileBindingDigest,
35
+ profileBundleDirectory,
36
+ readProfileBinding,
37
+ registerBundledBindings,
38
+ registerProfileBundle,
39
+ type AuthorisedPayloadToValidate,
40
+ type BindingProfile,
41
+ type BindingStepOutcome,
42
+ type BindingValidationDetail,
43
+ type BoundPayloadRefusal,
44
+ type EngineFinding,
45
+ type PayloadToValidate,
46
+ type PayloadValidation,
47
+ type PreparedBoundPayload,
48
+ type ProfileRegistry,
49
+ type ValidationEngines,
50
+ type WithheldCheck,
51
+ } from '@bsv/dpp-profiles'
52
+ import { ajv } from './profiles.js'
53
+ import { openValidationEngine, type ValidationEngineSettings } from './validation-engine.js'
54
+
55
+ type Json = Record<string, unknown>
56
+ const isObject = (value: unknown): value is Json => value !== null && typeof value === 'object' && !Array.isArray(value)
57
+ const reasonOf = (cause: unknown): string => (cause instanceof Error ? cause.message : String(cause))
58
+
59
+ /** The project root, where .env lives: a relative folder in the configuration is read from here. */
60
+ const PROJECT_ROOT = resolve(dirname(fileURLToPath(import.meta.url)), '../../..')
61
+
62
+ export interface BoundProfilesOptions {
63
+ /** Folders that each hold one binding.json and the files it names. */
64
+ customProfileDirs?: string[]
65
+ /** The digests of the custom bindings this deployment reviewed and chose to trust. */
66
+ trustedBindingDigests?: string[]
67
+ /** A folder that holds a profile bundle. Set, bound profiles are registered from it and the package's own bindings folder is not read. */
68
+ profileBundleDir?: string
69
+ /** The validation engine: a validator service's address and token, or neither for the engine in this process. */
70
+ validator?: ValidationEngineSettings
71
+ /** How a validation library is loaded. Tests pass one that fails, to stand in for libraries that are not installed. */
72
+ loadEngineLibrary?: (name: string) => Promise<unknown>
73
+ /** The transport to a validator service. The platform's by default. */
74
+ fetch?: typeof globalThis.fetch
75
+ /** How long one exchange with a validator service may take, in milliseconds. */
76
+ validatorTimeoutMs?: number
77
+ log?: (line: string) => void
78
+ }
79
+
80
+ /** A licence text as a profile bundle carries it. */
81
+ export interface ProfileLicenceText {
82
+ licence: string
83
+ bytes: Uint8Array
84
+ mediaType?: string
85
+ fileName?: string
86
+ }
87
+
88
+ /** A profile that was not registered at start-up, and why. The API runs without it. */
89
+ export interface ProfileRefusal {
90
+ /** The bundled profile, or the folder the configuration named. */
91
+ source: string
92
+ code: string
93
+ detail: string
94
+ }
95
+
96
+ /**
97
+ * How a view of a payload came out, for a person. `not-checked` is every
98
+ * answer that is not a decision: no engine, an unregistered profile, a rule
99
+ * that needs the restricted part. It is never shown as a pass.
100
+ */
101
+ export type ViewStatus = 'pass' | 'fail' | 'not-checked'
102
+
103
+ /** A SHACL finding, with the place in the product document it concerns when that could be worked out. */
104
+ export interface LocatedFinding extends EngineFinding {
105
+ step: string
106
+ /** A JSON pointer into the product document: the node, then the property. */
107
+ pointer?: string
108
+ /** The property as the document writes it, such as `gs1:netWeight`. */
109
+ property?: string
110
+ }
111
+
112
+ export interface ViewCheck {
113
+ view: 'public' | 'authorised' | 'whole'
114
+ status: ViewStatus
115
+ /** The precise cause, in the validator's own word. Absent on a pass. */
116
+ cause?: string
117
+ /** One or more sentences saying what this answer means, and what it does not. */
118
+ summary: string
119
+ steps: Array<{ step: string; status: ViewStatus; cause?: string; messages: string[] }>
120
+ findings: LocatedFinding[]
121
+ /** The rules this view could not decide, because they need a property it does not hold. */
122
+ withheld: WithheldCheck[]
123
+ }
124
+
125
+ export interface BoundProfileDescription {
126
+ id: string
127
+ format: 'binding'
128
+ title: string
129
+ description: string
130
+ bindingDigest: string
131
+ steps: string[]
132
+ /** The split, when the binding makes one: every property not listed is restricted. */
133
+ access?: { policy: string; public: string[] }
134
+ /** The contexts a product document may name, by the file name the binding gives each. */
135
+ contexts: Array<{ path: string; uri: string }>
136
+ /** Prefixes the contexts define, so a property's full name can be written the way documents write it. */
137
+ prefixes: Record<string, string>
138
+ engine: { available: boolean; kind: 'in-process' | 'service'; problem?: string }
139
+ }
140
+
141
+ export interface BoundProfiles {
142
+ readonly registry: ProfileRegistry
143
+ engines: ValidationEngines
144
+ /** Where the JSON-LD and SHACL engines run: in this process, or in a validator service. */
145
+ engineKind: 'in-process' | 'service'
146
+ /** Why the JSON-LD and SHACL engines cannot be used, as last found. For a validator service this changes as the service comes and goes. */
147
+ readonly engineProblem: string | undefined
148
+ /** Look at the engine again. A validator service is asked what it is; the engine in this process answers what start-up found. */
149
+ checkEngine(): Promise<void>
150
+ /** Where bound profiles are resolved from: the folder the profiles package ships, or a profile bundle. */
151
+ source: 'package' | 'bundle'
152
+ readonly refusals: ProfileRefusal[]
153
+ /** Register every profile again from the configured sources, into a new registry. A restore calls it after it installed a bundle. */
154
+ reload(): Promise<void>
155
+ /** The bytes of a notice a registered binding lists, from wherever the binding was read. It is what an export of the profiles carries beside them. */
156
+ readNotice(profile: BindingProfile, path: string): Promise<Uint8Array | undefined>
157
+ /** The licence texts that travel with the registered profiles, where this deployment holds them. */
158
+ licenceTexts(): Promise<ProfileLicenceText[]>
159
+ /** The registered binding for `id@version`, or nothing. */
160
+ get(profile: string): BindingProfile | undefined
161
+ list(): BindingProfile[]
162
+ describe(profile: BindingProfile): BoundProfileDescription
163
+ /** The code values the profile's vocabulary defines for each class asked for, as documents write them. */
164
+ codeLists(profile: BindingProfile, classes: string[]): Promise<Record<string, Array<{ value: string; label: string }>>>
165
+ /** The writer's call: validate the whole document, split it and build the exact public payload. */
166
+ prepare(input: { profile: BindingProfile; product: Json; passportId: string; notice?: string }): Promise<PreparedBoundPayload | BoundPayloadRefusal>
167
+ /** The public view: what the report runs for every state. */
168
+ validatePublic(payload: PayloadToValidate): Promise<PayloadValidation>
169
+ /** The authorised view: the public payload rejoined with the restricted part. */
170
+ validateAuthorised(payload: AuthorisedPayloadToValidate): Promise<PayloadValidation>
171
+ /** A validation as the API reports it, with each finding placed in the document where it can be. */
172
+ viewCheck(view: ViewCheck['view'], validation: PayloadValidation, located?: { profile: BindingProfile; product: Json }): Promise<ViewCheck>
173
+ }
174
+
175
+ const detailOf = (validation: PayloadValidation): BindingValidationDetail | undefined => (isObject(validation.detail) ? (validation.detail as unknown as BindingValidationDetail) : undefined)
176
+
177
+ /** `id@version` split into the pair the registry takes; nothing for any other form. */
178
+ export function profileParts(profile: string): { id: string; version: number } | undefined {
179
+ const match = /^(.+)@([1-9][0-9]*)$/.exec(profile)
180
+ return match == null ? undefined : { id: match[1], version: Number(match[2]) }
181
+ }
182
+
183
+ const SUMMARIES: Record<ViewCheck['view'], Record<ViewStatus, string>> = {
184
+ public: {
185
+ pass: 'The public payload carries only public properties, every rule it could break was evaluated and held, and it describes this passport\'s item. This says nothing about restricted data.',
186
+ fail: 'The public payload breaks a rule of its profile, or is not about this passport\'s item.',
187
+ 'not-checked': 'The public payload was not checked to a decision.',
188
+ },
189
+ authorised: {
190
+ pass: 'The public payload rejoined with the restricted part satisfies the profile and describes this passport\'s item. This is not a statement about the on-chain commitment: that is the owner-tier check.',
191
+ fail: 'The rejoined document breaks a rule of its profile, or the two parts do not belong together.',
192
+ 'not-checked': 'The rejoined document was not checked to a decision.',
193
+ },
194
+ whole: {
195
+ pass: 'The whole product document satisfies the profile and describes this passport\'s item.',
196
+ fail: 'The whole product document breaks a rule of its profile, or is not about this passport\'s item.',
197
+ 'not-checked': 'The whole product document was not checked to a decision.',
198
+ },
199
+ }
200
+
201
+ /** A manifest profile's payload is checked against its public schema and nothing else, so its answer says no more than that. */
202
+ const SCHEMA_SUMMARIES: Record<ViewStatus, string> = {
203
+ pass: 'The public payload fits the public schema of the profile it declares. This says nothing about the owner tier.',
204
+ fail: 'The public payload does not fit the public schema of the profile it declares.',
205
+ 'not-checked': 'The public payload was not checked to a decision.',
206
+ }
207
+
208
+ const NOT_CHECKED_REASONS: Record<string, string> = {
209
+ 'profile-unknown': 'This application holds no binding for the profile the payload declares.',
210
+ 'profile-retired': 'The payload declares a retired profile. Its rules are no longer applied, so the payload is neither passed nor failed.',
211
+ 'validator-unavailable': 'A validation step could not run.',
212
+ 'product-identity-unavailable': 'The product document could not be compared with the passport identifier.',
213
+ 'restricted-tier-withheld': 'A rule needs a restricted property, which this view does not hold.',
214
+ }
215
+
216
+ /** Prefix definitions of a JSON-LD context: a term whose whole value is a namespace address. */
217
+ function prefixesOf(profile: BindingProfile): Record<string, string> {
218
+ const prefixes: Record<string, string> = {}
219
+ const read = (context: unknown): void => {
220
+ if (Array.isArray(context)) return context.forEach(read)
221
+ if (!isObject(context)) return
222
+ for (const [term, value] of Object.entries(context)) {
223
+ if (!term.startsWith('@') && typeof value === 'string' && /^[a-z][a-z0-9+.-]*:.*[/#]$/i.test(value) && prefixes[term] == null) prefixes[term] = value
224
+ }
225
+ }
226
+ for (const { artefact, bytes } of profile.artefacts) {
227
+ if (artefact.role !== 'context') continue
228
+ try {
229
+ read((JSON.parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes)) as Json)['@context'])
230
+ } catch {
231
+ // A context that does not parse was already refused or will fail validation; it defines no prefix here.
232
+ }
233
+ }
234
+ return prefixes
235
+ }
236
+
237
+ /** An address written the way documents write it, `prefix:name`, when a prefix covers it. */
238
+ function compactWith(prefixes: Record<string, string>, iri: string): string | undefined {
239
+ let best: [string, string] | undefined
240
+ for (const entry of Object.entries(prefixes)) if (iri.startsWith(entry[1]) && (best == null || entry[1].length > best[1].length)) best = entry
241
+ return best == null ? undefined : `${best[0]}:${iri.slice(best[1].length)}`
242
+ }
243
+
244
+ const escapePointer = (segment: string): string => segment.replace(/~/g, '~0').replace(/\//g, '~1')
245
+ const POINTER_NODE = 'urn:x-dpp-pointer:'
246
+
247
+ /**
248
+ * A copy of the product document in which every nested node that has no
249
+ * identifier is given one made from its place in the document. It is used
250
+ * only to find where a finding belongs and is never validated as the
251
+ * product, signed or stored: naming a node can change what a shape decides,
252
+ * so the findings themselves always come from the document as written.
253
+ */
254
+ function withPointerNodes(product: Json): { document: Json; pointers: Map<string, string> } {
255
+ const pointers = new Map<string, string>()
256
+ const visit = (value: unknown, pointer: string, root: boolean): unknown => {
257
+ if (Array.isArray(value)) return value.map((entry, index) => visit(entry, `${pointer}/${index}`, false))
258
+ if (!isObject(value)) return value
259
+ // A value object, such as text with a language, is a literal and has no identifier.
260
+ if (Object.hasOwn(value, '@value')) return value
261
+ const copy: Json = {}
262
+ for (const [key, child] of Object.entries(value)) copy[key] = key === '@context' ? child : visit(child, `${pointer}/${escapePointer(key)}`, false)
263
+ const stated = [value['@id'], value.id].find((id): id is string => typeof id === 'string')
264
+ if (stated != null) {
265
+ if (!pointers.has(stated)) pointers.set(stated, pointer)
266
+ } else if (!root && Object.keys(value).length > 0) {
267
+ const id = `${POINTER_NODE}${encodeURI(pointer)}`
268
+ copy['@id'] = id
269
+ pointers.set(id, pointer)
270
+ }
271
+ return copy
272
+ }
273
+ return { document: visit(product, '', true) as Json, pointers }
274
+ }
275
+
276
+ /**
277
+ * A result path as the steps to follow from the node: `<a>/<b>` is two
278
+ * steps, and `<a>|<b>` is one step with two spellings. Nothing for a path
279
+ * with any other operator, which is then placed at its node only.
280
+ */
281
+ function pathSteps(path: string): string[][] | undefined {
282
+ if (!/[<>]/.test(path)) return [[path]]
283
+ const names = (text: string): string[] => [...text.matchAll(/<([^<>]+)>/g)].map((match) => match[1])
284
+ if (/^<[^<>]+>(\/<[^<>]+>)*$/.test(path)) return names(path).map((name) => [name])
285
+ if (/^<[^<>]+>(\|<[^<>]+>)+$/.test(path)) return [names(path)]
286
+ return undefined
287
+ }
288
+
289
+ /** The value a JSON pointer names in a document, or nothing. */
290
+ function valueAt(document: unknown, pointer: string): unknown {
291
+ let value = document
292
+ for (const segment of pointer.split('/').slice(1)) {
293
+ if (value === null || typeof value !== 'object') return undefined
294
+ value = (value as Json)[segment.replace(/~1/g, '/').replace(/~0/g, '~')]
295
+ }
296
+ return value
297
+ }
298
+
299
+ const findingKey = (finding: EngineFinding): string => JSON.stringify([finding.severity, finding.constraint, finding.path ?? null, finding.message ?? null, finding.value ?? null])
300
+
301
+ /** What one pass over the configured sources registered: the registry, what was refused, and where each profile's notices are read from. */
302
+ interface Registered {
303
+ registry: ProfileRegistry
304
+ refusals: ProfileRefusal[]
305
+ validatePublic: BoundProfiles['validatePublic']
306
+ validateAuthorised: BoundProfiles['validateAuthorised']
307
+ /** By binding digest: how a notice of that binding is read. */
308
+ notices: Map<string, (path: string) => Promise<Uint8Array | undefined>>
309
+ licenceTexts: () => Promise<ProfileLicenceText[]>
310
+ }
311
+
312
+ export async function openBoundProfiles(options: BoundProfilesOptions = {}): Promise<BoundProfiles> {
313
+ const log = options.log ?? (() => {})
314
+
315
+ // The engine is opened once. Without it the API still starts: a bound profile then cannot be written, and a reading says "not checked".
316
+ const loadLibrary = options.loadEngineLibrary ?? ((name: string): Promise<unknown> => import(name))
317
+ const engine = await openValidationEngine(options.validator ?? {}, {
318
+ load: loadLibrary,
319
+ ...(options.fetch == null ? {} : { fetch: options.fetch }),
320
+ ...(options.validatorTimeoutMs == null ? {} : { timeoutMs: options.validatorTimeoutMs }),
321
+ log,
322
+ })
323
+ const engines: ValidationEngines = { jsonSchema: ajv, ...engine.engines }
324
+
325
+ const custom = options.customProfileDirs ?? []
326
+ const bundleDir = options.profileBundleDir == null ? undefined : isAbsolute(options.profileBundleDir) ? options.profileBundleDir : resolve(PROJECT_ROOT, options.profileBundleDir)
327
+ const source: BoundProfiles['source'] = bundleDir == null ? 'package' : 'bundle'
328
+
329
+ /** One pass over the configured sources, into a registry of its own. Trust is the same list whichever source the files come from. */
330
+ const register = async (): Promise<Registered> => {
331
+ const refusals: ProfileRefusal[] = []
332
+ const refuse = (from: string, code: string, detail: string): void => {
333
+ refusals.push({ source: from, code, detail })
334
+ log(`Profile ${from} was not registered (${code}): ${detail} The API continues without it.`)
335
+ }
336
+ const notices: Registered['notices'] = new Map()
337
+ let licenceTexts: Registered['licenceTexts'] = async () => []
338
+ const registry = createProfileRegistry({ trustedBindingDigests: [...BUNDLED_BINDING_DIGESTS, ...(options.trustedBindingDigests ?? [])] })
339
+
340
+ if (bundleDir == null) {
341
+ for (const result of await registerBundledBindings(registry)) {
342
+ if (!result.ok) refuse(result.profile ?? 'a bundled binding', result.code, result.detail)
343
+ }
344
+ const packaged = bundledBindingNotices()
345
+ for (const profile of registry.list()) if (profile.format === 'binding') notices.set(profile.bindingDigest, async (path) => packaged(profile, path))
346
+ licenceTexts = async () => bundledBindingLicenceTexts()
347
+ } else {
348
+ // The bundle is read from this deployment's own folder. A sector profile is expected under the digest the installed
349
+ // profiles package publishes for it, so a bundle that carries another definition under that name is refused whoever
350
+ // put it there, and every other binding must be on this deployment's own trusted list.
351
+ const opened = await openProfileBundle(profileBundleDirectory(bundleDir))
352
+ if (!opened.ok) {
353
+ refuse(`the profile bundle in ${bundleDir}`, opened.code, `${opened.detail} PROFILE_BUNDLE_DIR names the folder a restore installs a bundle into; until it holds one, no profile is registered from it.`)
354
+ } else {
355
+ const { bundle } = opened
356
+ for (const result of await registerProfileBundle(registry, bundle, { expected: BUNDLED_BINDINGS })) {
357
+ if (!result.ok) {
358
+ refuse(`${result.profile ?? 'a profile'} of the bundle in ${bundleDir}`, result.code, result.detail)
359
+ continue
360
+ }
361
+ const name = result.profile.profile
362
+ notices.set(result.profile.bindingDigest, (path) => bundle.noticeBytes(name, path))
363
+ log(`Profile ${name} registered from the bundle in ${bundleDir} under binding digest ${result.profile.bindingDigest}.`)
364
+ }
365
+ licenceTexts = () => bundle.licenceTexts()
366
+ }
367
+ }
368
+
369
+ for (const dir of custom) {
370
+ const folder = isAbsolute(dir) ? dir : resolve(PROJECT_ROOT, dir)
371
+ let bindingBytes: Uint8Array
372
+ try {
373
+ bindingBytes = new Uint8Array(readFileSync(join(folder, 'binding.json')))
374
+ } catch (cause) {
375
+ refuse(folder, 'binding-unavailable', `binding.json could not be read from the folder (${reasonOf(cause)}).`)
376
+ continue
377
+ }
378
+ const read = readProfileBinding(bindingBytes)
379
+ if (read.ok) {
380
+ const packaged = BUNDLED_BINDINGS.find(entry => entry.profile === read.binding.profile)
381
+ if (packaged != null && packaged.bindingDigest !== read.digest) {
382
+ refuse(folder, 'binding-conflict', `${packaged.profile} is pinned to ${packaged.bindingDigest}, and this folder holds ${read.digest}.`)
383
+ continue
384
+ }
385
+ }
386
+ const result = await registry.register({ bindingBytes, resolveArtefact: (artefact) => new Uint8Array(readFileSync(join(folder, artefact.path))) })
387
+ if (result.ok) {
388
+ // The same bytes registered before, from the bundle, keep the notices the bundle carries.
389
+ if (!notices.has(result.profile.bindingDigest)) {
390
+ notices.set(result.profile.bindingDigest, async (path) => {
391
+ // A notice path is a relative file name with no dot or dot-dot segment, and it is checked here because it becomes part of a file name.
392
+ if (!/^[A-Za-z0-9_@-][A-Za-z0-9._@-]*(\/[A-Za-z0-9_@-][A-Za-z0-9._@-]*)*$/u.test(path)) return undefined
393
+ try {
394
+ return new Uint8Array(readFileSync(join(folder, path)))
395
+ } catch {
396
+ return undefined
397
+ }
398
+ })
399
+ }
400
+ log(`Profile ${result.profile.profile} registered from ${folder} under binding digest ${result.profile.bindingDigest}.`)
401
+ } else if (result.code === 'binding-untrusted') {
402
+ // The digest is named so the operator can review the file and trust exactly these bytes. A changed file has another digest and stays refused.
403
+ refuse(folder, result.code, `Its binding.json has digest ${profileBindingDigest(bindingBytes)}, which is not in TRUSTED_BINDING_DIGESTS. Review the binding and every file it names, then add that digest to trust it. A binding that changed since you trusted it has a new digest.`)
404
+ } else {
405
+ refuse(folder, result.code, result.detail)
406
+ }
407
+ }
408
+
409
+ const held = registry.list().filter((profile) => profile.format === 'binding')
410
+ log(`Profiles held by a binding, from ${source === 'package' ? 'the profiles package' : `the bundle in ${bundleDir}`}: ${held.length === 0 ? 'none' : held.map((profile) => profile.profile).join(', ')}.${engine.problem == null ? '' : ' None can be written until the validation engine is available.'}`)
411
+ return { registry, refusals, validatePublic: bindingPayloadValidator({ registry, engines }), validateAuthorised: authorisedPayloadValidator({ registry, engines }), notices, licenceTexts }
412
+ }
413
+
414
+ let current = await register()
415
+ const prefixCache = new Map<string, Record<string, string>>()
416
+ const prefixesFor = (profile: BindingProfile): Record<string, string> => {
417
+ const kept = prefixCache.get(profile.bindingDigest)
418
+ if (kept != null) return kept
419
+ const prefixes = prefixesOf(profile)
420
+ prefixCache.set(profile.bindingDigest, prefixes)
421
+ return prefixes
422
+ }
423
+ const get = (profile: string): BindingProfile | undefined => {
424
+ const parts = profileParts(profile)
425
+ const resolved = parts == null ? undefined : current.registry.resolve(parts.id, parts.version)
426
+ return resolved?.format === 'binding' ? resolved : undefined
427
+ }
428
+
429
+ const codeCache = new Map<string, Promise<Map<string, Array<{ value: string; label: string }>>>>()
430
+ /** Every individual the profile's background files declare, by class, with its label. Read once per binding. */
431
+ const codesOf = (profile: BindingProfile): Promise<Map<string, Array<{ value: string; label: string }>>> => {
432
+ const kept = codeCache.get(profile.bindingDigest)
433
+ if (kept != null) return kept
434
+ const work = (async () => {
435
+ const byClass = new Map<string, Array<{ value: string; label: string }>>()
436
+ const loaded = (await loadLibrary('n3')) as { default?: unknown }
437
+ const n3 = (loaded.default ?? loaded) as { Parser: new (options: { format: string }) => { parse(text: string): Array<{ subject: { termType: string; value: string }; predicate: { value: string }; object: { termType: string; value: string; language?: string } }> } }
438
+ const prefixes = prefixesFor(profile)
439
+ const TYPE = 'http://www.w3.org/1999/02/22-rdf-syntax-ns#type'
440
+ const LABEL = 'http://www.w3.org/2000/01/rdf-schema#label'
441
+ const SUBCLASS = 'http://www.w3.org/2000/01/rdf-schema#subClassOf'
442
+ const labels = new Map<string, string>()
443
+ const supers = new Map<string, string[]>()
444
+ const typed: Array<[string, string]> = []
445
+ for (const { artefact, bytes } of profile.artefacts) {
446
+ if (artefact.role !== 'background' || artefact.mediaType !== 'text/turtle') continue
447
+ for (const quad of new n3.Parser({ format: 'Turtle' }).parse(new TextDecoder('utf-8', { fatal: true }).decode(bytes))) {
448
+ if (quad.subject.termType !== 'NamedNode') continue
449
+ if (quad.predicate.value === LABEL && (quad.object.language == null || quad.object.language === '' || quad.object.language === 'en') && !labels.has(quad.subject.value)) labels.set(quad.subject.value, quad.object.value)
450
+ else if (quad.predicate.value === SUBCLASS && quad.object.termType === 'NamedNode') supers.set(quad.subject.value, [...(supers.get(quad.subject.value) ?? []), quad.object.value])
451
+ else if (quad.predicate.value === TYPE && quad.object.termType === 'NamedNode') typed.push([quad.subject.value, quad.object.value])
452
+ }
453
+ }
454
+ const ancestors = (type: string, seen = new Set<string>()): Set<string> => {
455
+ if (seen.has(type)) return seen
456
+ seen.add(type)
457
+ for (const parent of supers.get(type) ?? []) ancestors(parent, seen)
458
+ return seen
459
+ }
460
+ for (const [subject, type] of typed) {
461
+ const value = compactWith(prefixes, subject)
462
+ if (value == null) continue
463
+ for (const each of ancestors(type)) {
464
+ const name = compactWith(prefixes, each)
465
+ if (name == null) continue
466
+ const list = byClass.get(name) ?? []
467
+ if (!list.some((entry) => entry.value === value)) list.push({ value, label: labels.get(subject) ?? value })
468
+ byClass.set(name, list)
469
+ }
470
+ }
471
+ return byClass
472
+ })()
473
+ codeCache.set(profile.bindingDigest, work)
474
+ return work
475
+ }
476
+
477
+ /** Where each finding of a validation belongs in the product document, worked out on a copy whose nested nodes are named by their place. */
478
+ const locate = async (profile: BindingProfile, product: Json, findings: Array<EngineFinding & { step: string }>): Promise<LocatedFinding[]> => {
479
+ if (findings.length === 0 || engines.jsonLd == null || engines.shacl == null) return findings
480
+ const prefixes = prefixesFor(profile)
481
+ const { document, pointers } = withPointerNodes(product)
482
+ const contexts = profile.artefacts.filter((a) => a.artefact.role === 'context').map((a) => ({ uri: a.artefact.uri!, bytes: a.bytes }))
483
+ const files = (role: 'shapes' | 'background') => profile.artefacts.filter((a) => a.artefact.role === role).map((a) => ({ path: a.artefact.path, mediaType: a.artefact.mediaType, bytes: a.bytes }))
484
+ let named: EngineFinding[] = []
485
+ try {
486
+ const expansion = await engines.jsonLd.toRdf({ document, contexts })
487
+ if (expansion.ok) {
488
+ const validation = await engines.shacl.validate({ nquads: expansion.nquads, shapes: files('shapes'), background: files('background') })
489
+ if (validation.ok) named = validation.findings
490
+ }
491
+ } catch {
492
+ // Without a second pass the findings are still reported, only not placed.
493
+ }
494
+ const unused = named.map((finding) => ({ finding, key: findingKey(finding), used: false }))
495
+ return findings.map((finding) => {
496
+ const key = findingKey(finding)
497
+ const twin = unused.find((candidate) => !candidate.used && candidate.key === key)
498
+ if (twin == null) return finding
499
+ twin.used = true
500
+ const node = twin.finding.focusNode == null ? undefined : pointers.get(twin.finding.focusNode)
501
+ if (node == null) return finding
502
+ const steps = finding.path == null ? undefined : pathSteps(finding.path)?.map((spellings) => spellings.map((iri) => compactWith(prefixes, iri)))
503
+ if (steps == null || steps.some((spellings) => spellings.some((name) => name == null))) return { ...finding, pointer: node }
504
+ // Where a step has two spellings, the one the document uses is the place; with neither written, the first is where a value would go.
505
+ let pointer = node
506
+ let property: string | undefined
507
+ for (const spellings of steps as string[][]) {
508
+ const here = valueAt(product, pointer)
509
+ property = spellings.find((name) => isObject(here) && Object.hasOwn(here, name)) ?? spellings[0]
510
+ pointer = `${pointer}/${escapePointer(property)}`
511
+ }
512
+ return { ...finding, pointer, ...(property == null ? {} : { property }) }
513
+ })
514
+ }
515
+
516
+ const viewStatus = (status: 'pass' | 'fail' | 'unknown'): ViewStatus => (status === 'unknown' ? 'not-checked' : status)
517
+
518
+ return {
519
+ get registry() {
520
+ return current.registry
521
+ },
522
+ engines,
523
+ engineKind: engine.kind,
524
+ get engineProblem() {
525
+ return engine.problem
526
+ },
527
+ async checkEngine() {
528
+ await engine.check()
529
+ },
530
+ source,
531
+ get refusals() {
532
+ return current.refusals
533
+ },
534
+ async reload() {
535
+ current = await register()
536
+ },
537
+ readNotice: async (profile, path) => await current.notices.get(profile.bindingDigest)?.(path),
538
+ licenceTexts: () => current.licenceTexts(),
539
+ get,
540
+ list: () => current.registry.list().filter((profile): profile is BindingProfile => profile.format === 'binding'),
541
+ describe: (profile) => ({
542
+ id: profile.profile,
543
+ format: 'binding',
544
+ title: profile.binding.title,
545
+ description: profile.binding.scope,
546
+ bindingDigest: profile.bindingDigest,
547
+ steps: [...profile.binding.validation.steps],
548
+ ...(profile.binding.access == null ? {} : { access: { policy: profile.binding.access.policy, public: [...profile.binding.access.public] } }),
549
+ contexts: profile.artefacts.filter((a) => a.artefact.role === 'context').map((a) => ({ path: a.artefact.path, uri: a.artefact.uri! })),
550
+ prefixes: prefixesFor(profile),
551
+ engine: { available: engine.problem == null, kind: engine.kind, ...(engine.problem == null ? {} : { problem: engine.problem }) },
552
+ }),
553
+ async codeLists(profile, classes) {
554
+ const out: Record<string, Array<{ value: string; label: string }>> = {}
555
+ if (engine.problem != null) return out
556
+ let all: Map<string, Array<{ value: string; label: string }>>
557
+ try {
558
+ all = await codesOf(profile)
559
+ } catch {
560
+ return out
561
+ }
562
+ for (const name of classes) out[name] = all.get(name) ?? []
563
+ return out
564
+ },
565
+ prepare: ({ profile, product, passportId, notice }) => prepareBoundPayload({ registry: current.registry, engines, profile: profile.id, profileVersion: profile.version, product, passportId, ...(notice == null ? {} : { notice }) }),
566
+ validatePublic: (payload) => current.validatePublic(payload),
567
+ validateAuthorised: (payload) => current.validateAuthorised(payload),
568
+ async viewCheck(view, validation, located) {
569
+ const status = viewStatus(validation.status)
570
+ const detail = detailOf(validation)
571
+ const steps: BindingStepOutcome[] = detail?.steps ?? []
572
+ const cause = detail?.cause
573
+ const flat = steps.flatMap((step) => (step.findings ?? []).map((finding) => ({ ...finding, step: step.step })))
574
+ const findings = located == null ? flat : await locate(located.profile, located.product, flat)
575
+ const messages = typeof validation.detail === 'string' ? [validation.detail] : Array.isArray(validation.detail) ? validation.detail : []
576
+ const replaced = cause === 'profile-retired' && detail?.replacedBy != null ? ` ${detail.replacedBy} replaces it.` : ''
577
+ const engineProblem = engine.problem
578
+ const reason = status !== 'not-checked' ? '' : ` ${cause === 'validator-unavailable' && engineProblem != null ? `The validation engine is not available: ${engineProblem}` : (NOT_CHECKED_REASONS[cause ?? ''] ?? 'A check could not run.')}${replaced} A check that could not run is not a pass.`
579
+ return {
580
+ view,
581
+ status,
582
+ ...(cause == null ? {} : { cause }),
583
+ summary: `${(detail == null || cause === 'profile-retired') && view === 'public' ? SCHEMA_SUMMARIES[status] : SUMMARIES[view][status]}${reason}`,
584
+ steps: detail == null ? (messages.length === 0 || status === 'pass' ? [] : [{ step: 'json-schema', status, messages }]) : steps.map((step) => ({ step: step.step, status: viewStatus(step.status), ...(step.cause == null ? {} : { cause: step.cause }), messages: step.messages ?? [] })),
585
+ findings,
586
+ withheld: detail?.access?.withheld ?? [],
587
+ }
588
+ },
589
+ }
590
+ }