@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
@@ -2,33 +2,55 @@
2
2
  // the profile's published JSON schema before anything is written. The
3
3
  // schemas and manifests come from @bsv/dpp-profiles; this module only
4
4
  // chooses the current ones and runs the validator.
5
+ //
6
+ // The earlier sector profiles are retired (RETIRED_PROFILE_IDS in the
7
+ // package). None is offered here, and a payload is neither started nor
8
+ // checked under one: each function below refuses a retired profile by name,
9
+ // whatever its frozen manifest still says about its status.
5
10
  import { Ajv2020 } from 'ajv/dist/2020.js'
6
11
  import addFormats from 'ajv-formats'
7
12
  import {
8
- PROFILE_IDS,
13
+ SUPPORTED_PROFILE_IDS,
14
+ HISTORICAL_SECTOR_BINDINGS,
15
+ CURRENT_SECTOR_BINDINGS,
16
+ assertProfileNotRetired,
9
17
  readManifest,
10
18
  readPublicPayloadSchema,
11
19
  readRestrictedPayloadSchema,
12
- type ProfileId,
13
20
  type ProfileManifest,
21
+ type SupportedProfileId,
14
22
  } from '@bsv/dpp-profiles'
15
23
 
16
- const ajv = new Ajv2020({ allErrors: true, strict: false })
24
+ /** The one JSON Schema compiler of the application. A profile held by a binding compiles its own schema into it. */
25
+ export const ajv = new Ajv2020({ allErrors: true, strict: false })
17
26
  ;(addFormats as unknown as (instance: Ajv2020) => void)(ajv)
18
27
 
19
- /** The profiles a brand may choose: every published version whose manifest says it is current. */
20
- export function currentProfiles(): Array<{ id: ProfileId; title: string; description?: string }> {
21
- return PROFILE_IDS.filter((id) => readManifest(id).status === 'current').map((id) => {
28
+ /** The sentence a record under the demonstration prefix carries first (spec/profiles.md section 5). */
29
+ export const DEMONSTRATION_NOTICE = 'This demonstration record describes no real product.'
30
+
31
+ /** A manifest profile this application writes and reads under. A retired profile is not one, though the package still publishes its files. */
32
+ export type ManifestProfileId = SupportedProfileId
33
+
34
+ export function sectorIssueSuccessor(profile: string): string | undefined {
35
+ if (!HISTORICAL_SECTOR_BINDINGS.some(entry => entry.profile === profile)) return undefined
36
+ const sector = profile.split('@')[0]
37
+ return CURRENT_SECTOR_BINDINGS.find(entry => entry.profile.split('@')[0] === sector)?.profile
38
+ }
39
+
40
+ /** The manifest profiles a brand may choose: every supported version whose manifest says it is current. No retired profile is among them. */
41
+ export function currentProfiles(): Array<{ id: ManifestProfileId; title: string; description?: string }> {
42
+ return SUPPORTED_PROFILE_IDS.filter((id) => readManifest(id).status === 'current').map((id) => {
22
43
  const manifest = readManifest(id)
23
44
  return { id, title: manifest.title, description: manifest.description }
24
45
  })
25
46
  }
26
47
 
27
- export function isProfileId(value: string): value is ProfileId {
28
- return (PROFILE_IDS as readonly string[]).includes(value)
48
+ export function isProfileId(value: unknown): value is ManifestProfileId {
49
+ return typeof value === 'string' && (SUPPORTED_PROFILE_IDS as readonly string[]).includes(value)
29
50
  }
30
51
 
31
- export function manifestFor(profile: ProfileId): ProfileManifest {
52
+ export function manifestFor(profile: ManifestProfileId): ProfileManifest {
53
+ assertProfileNotRetired(profile)
32
54
  return readManifest(profile)
33
55
  }
34
56
 
@@ -40,7 +62,9 @@ export interface Validation {
40
62
  }
41
63
 
42
64
  /** Check a payload against the profile's public or restricted schema. The problems name the field and what is wrong. */
43
- export function validatePayload(profile: ProfileId, tier: Tier, payload: unknown): Validation {
65
+ export function validatePayload(profile: ManifestProfileId, tier: Tier, payload: unknown): Validation {
66
+ // The types already exclude a retired profile. A string that arrived from a request or a stored record is held to the same rule here.
67
+ assertProfileNotRetired(profile)
44
68
  const schema = (tier === 'public' ? readPublicPayloadSchema(profile) : readRestrictedPayloadSchema(profile)) as { $id?: string }
45
69
  const validate = (schema.$id != null ? ajv.getSchema(schema.$id) : undefined) ?? ajv.compile(schema)
46
70
  const valid = validate(payload) as boolean
@@ -85,16 +109,17 @@ function placeholder(node: Record<string, unknown>, name: string): unknown {
85
109
  * that describes no real product carries. Replace every value with the
86
110
  * product's own data; a placeholder is never a statement about a product.
87
111
  */
88
- export function samplePayload(profile: ProfileId, demonstration: boolean): Record<string, unknown> {
112
+ export function samplePayload(profile: ManifestProfileId, demonstration: boolean): Record<string, unknown> {
89
113
  const { payload, problems } = sampleWithProblems(profile, demonstration)
90
114
  if (problems.length > 0) throw new Error(`the generated ${profile} sample is refused by its own schema: ${problems.join('; ')}`)
91
115
  return payload
92
116
  }
93
117
 
94
118
  /** The same sample, with whatever its own schema still refuses, so a form can start from it and show what to fix. */
95
- export function sampleWithProblems(profile: ProfileId, demonstration: boolean): { payload: Record<string, unknown>; problems: string[] } {
119
+ export function sampleWithProblems(profile: ManifestProfileId, demonstration: boolean): { payload: Record<string, unknown>; problems: string[] } {
120
+ assertProfileNotRetired(profile)
96
121
  const schema = readPublicPayloadSchema(profile) as Record<string, unknown>
97
122
  const required = placeholder(schema, 'payload') as Record<string, unknown>
98
- const payload = demonstration ? { notice: 'Demonstration record. Nothing here describes a real product.', ...required } : required
123
+ const payload = demonstration ? { notice: DEMONSTRATION_NOTICE, ...required } : required
99
124
  return { payload, problems: validatePayload(profile, 'public', payload).problems }
100
125
  }
@@ -3,10 +3,25 @@
3
3
  // every block proof is checked here, and the report says pass, fail, unknown
4
4
  // or not-applicable for each check with a reason. Missing evidence stays
5
5
  // unknown and is never treated as verified.
6
- import { WhatsOnChain, type ChainTracker, type Transaction } from '@bsv/sdk'
7
- import { EVIDENCE_CHECK_LABELS, findDppOutputs, verifyPassportEvidence, type EvidenceReport, type ManagedAcceptanceRecord } from '@bsv/dpp-protocol'
6
+ //
7
+ // A payload is checked against the profile it declares. Under a profile
8
+ // held by a binding there are two views and they are reported apart. The
9
+ // public view is what any reader has: it runs inside the report, for every
10
+ // state, against that state's own passport identifier. The authorised view
11
+ // is for the holder, who can open the restricted part: the two parts are
12
+ // rejoined and checked whole. Neither view says the restricted part is the
13
+ // one the record commits to. That is the protocol's owner-tier check, the
14
+ // stored ciphertext against the state's payload_owner_hash, and it is
15
+ // reported on its own line.
16
+ import { Utils, WhatsOnChain, type ChainTracker, type Transaction } from '@bsv/sdk'
17
+ import { EVIDENCE_CHECK_LABELS, findDppOutputs, verifyOwnerBlob, verifyPassportEvidence, type DeclaredPayload, type EvidenceReport, type ManagedAcceptanceRecord } from '@bsv/dpp-protocol'
18
+ import { assembleProduct, type PayloadValidation } from '@bsv/dpp-profiles'
19
+ import type { BoundProfiles, ViewCheck } from './bound-profiles.js'
8
20
  import type { Network } from './config.js'
9
21
  import type { IndexClient } from './index-client.js'
22
+ import type { Party } from './parties.js'
23
+ import type { PassportRecord } from './store.js'
24
+ import { OWNER_DATA_PROTOCOL } from './writer.js'
10
25
 
11
26
  /**
12
27
  * Ask the header source one question at a time, a little apart, and keep
@@ -48,6 +63,29 @@ export interface ReaderOptions {
48
63
  /** The issuers whose genesis this reader accepts; empty accepts any. */
49
64
  genesisIssuers?: string[]
50
65
  policyId?: string
66
+ /** The profiles this reader holds. With them every state's public payload is checked under the profile it declares; without them that check stays unknown. */
67
+ profiles?: BoundProfiles
68
+ }
69
+
70
+ /** The check of one state's public payload, as any reader makes it. */
71
+ export interface PayloadCheck {
72
+ txid: string
73
+ stateIndex: number
74
+ /** `id@version`, as the payload declares it. */
75
+ profile: string
76
+ publicView: ViewCheck
77
+ }
78
+
79
+ /** The product document of the newest state under a profile held by a binding: its public part, which is all a public reading has. */
80
+ export interface ProductReading {
81
+ profile: string
82
+ bindingDigest: string
83
+ /** The sentence a demonstration record carries first. */
84
+ notice?: string
85
+ /** The public properties, as written on chain. */
86
+ publicProduct: Record<string, unknown>
87
+ /** The binding's public list, when this reader holds the binding: every other property is restricted. */
88
+ access?: { policy: string; public: string[] }
51
89
  }
52
90
 
53
91
  export interface PassportReading {
@@ -56,20 +94,50 @@ export interface PassportReading {
56
94
  report: EvidenceReport
57
95
  checks: Array<{ name: string; label: string; status: string; reasonCode?: string }>
58
96
  publisherKeys: string[]
97
+ /** One entry per state whose payload declares a profile, genesis first. Empty when the reader holds no profiles. */
98
+ payloadChecks: PayloadCheck[]
99
+ /** Present when the newest state's payload is a product document under a binding. */
100
+ product?: ProductReading
101
+ }
102
+
103
+ const isObject = (value: unknown): value is Record<string, unknown> => value !== null && typeof value === 'object' && !Array.isArray(value)
104
+
105
+ /** The envelope of a payload under a binding, when the text is one. */
106
+ function envelopeOf(payloadPublic: string): { profile: string; bindingDigest: string; notice?: string; product: Record<string, unknown> } | undefined {
107
+ let parsed: unknown
108
+ try {
109
+ parsed = JSON.parse(payloadPublic)
110
+ } catch {
111
+ return undefined
112
+ }
113
+ if (!isObject(parsed) || typeof parsed.profile !== 'string' || typeof parsed.profile_version !== 'number' || typeof parsed.profile_binding_sha256 !== 'string' || !isObject(parsed.product)) return undefined
114
+ return { profile: `${parsed.profile}@${parsed.profile_version}`, bindingDigest: parsed.profile_binding_sha256, ...(typeof parsed.notice === 'string' ? { notice: parsed.notice } : {}), product: parsed.product }
59
115
  }
60
116
 
61
117
  export async function readPassport(passportId: string, options: ReaderOptions, evidence: { acceptanceRecords?: ManagedAcceptanceRecord[] } = {}): Promise<PassportReading> {
62
118
  const publisherKeys = await options.index.publisherKeys()
63
119
  const lineage: Transaction[] = await options.index.lineage(passportId)
64
120
  if (lineage.length === 0) throw new Error(`the index holds nothing for ${passportId}`)
121
+ // The report asks the validator once per state and keeps only the combined answer, so each answer is kept here for the page.
122
+ const profiles = options.profiles
123
+ const answers: Array<{ payload: DeclaredPayload; validation: PayloadValidation }> = []
124
+ const payloadValidator =
125
+ profiles == null
126
+ ? undefined
127
+ : async (payload: DeclaredPayload): Promise<PayloadValidation> => {
128
+ const validation = await profiles.validatePublic(payload)
129
+ answers.push({ payload, validation })
130
+ return validation
131
+ }
65
132
  const report = await verifyPassportEvidence(
66
133
  { tokenHistory: lineage, acceptanceRecords: evidence.acceptanceRecords ?? [] },
67
134
  { passportId, source: 'request-context' },
68
135
  {
69
- policyId: options.policyId ?? 'managed-custody@1/application',
136
+ policyId: options.policyId ?? 'managed-custody@2/application',
70
137
  publisherKeys,
71
138
  managedAcceptance: { required: true },
72
139
  chainTracker: options.chainTracker,
140
+ ...(payloadValidator == null ? {} : { payloadValidator }),
73
141
  authority: {
74
142
  required: true,
75
143
  ...(options.genesisIssuers != null && options.genesisIssuers.length > 0 ? { genesisIssuers: options.genesisIssuers } : {}),
@@ -92,5 +160,106 @@ export async function readPassport(passportId: string, options: ReaderOptions, e
92
160
  report,
93
161
  checks: report.checks.map((c) => ({ name: c.name, label: EVIDENCE_CHECK_LABELS[c.name], status: c.status, reasonCode: c.reasonCode })),
94
162
  publisherKeys,
163
+ payloadChecks:
164
+ profiles == null
165
+ ? []
166
+ : await Promise.all(
167
+ answers.map(async ({ payload, validation }) => ({
168
+ txid: payload.ref.split(':')[0],
169
+ stateIndex: payload.stateIndex,
170
+ profile: `${payload.profile}@${payload.profileVersion}`,
171
+ publicView: await profiles.viewCheck('public', validation),
172
+ }))
173
+ ),
174
+ ...(() => {
175
+ const envelope = envelopeOf(findDppOutputs(lineage[lineage.length - 1])[0].state.payloadPublic)
176
+ if (envelope == null) return {}
177
+ const access = profiles?.get(envelope.profile)?.binding.access
178
+ const product: ProductReading = {
179
+ profile: envelope.profile,
180
+ bindingDigest: envelope.bindingDigest,
181
+ ...(envelope.notice == null ? {} : { notice: envelope.notice }),
182
+ publicProduct: envelope.product,
183
+ ...(access == null ? {} : { access: { policy: access.policy, public: [...access.public] } }),
184
+ }
185
+ return { product }
186
+ })(),
187
+ }
188
+ }
189
+
190
+ /** Whether the stored ciphertext is the one the state commits to. This is the protocol's check and the only statement made about the commitment. */
191
+ export interface OwnerTierCheck {
192
+ status: 'pass' | 'fail' | 'not-checked'
193
+ /** The state whose payload_owner_hash the ciphertext was compared with. */
194
+ txid?: string
195
+ detail: string
196
+ }
197
+
198
+ export interface AuthorisedReading {
199
+ passportId: string
200
+ profile?: string
201
+ ownerTier: OwnerTierCheck
202
+ authorisedView: ViewCheck
203
+ /** The restricted part, opened for the holder. Absent when it was not opened, and when the state has none. */
204
+ restrictedProduct?: Record<string, unknown>
205
+ /** The two parts rejoined, for display. It is not what was signed. */
206
+ product?: Record<string, unknown>
207
+ access?: { policy: string; public: string[] }
208
+ }
209
+
210
+ const notChecked = (summary: string): ViewCheck => ({ view: 'authorised', status: 'not-checked', summary: `The rejoined document was not checked. ${summary} A check that could not run is not a pass.`, steps: [], findings: [], withheld: [] })
211
+
212
+ /**
213
+ * The authorised view of the newest state, for the party that holds the
214
+ * passport. The order is the record model's: the stored ciphertext is held
215
+ * to the state's payload_owner_hash before any decryption, and only then is
216
+ * it opened, rejoined with the public payload and checked whole.
217
+ */
218
+ export async function readAuthorised(args: { record: PassportRecord; holder: Party; index: IndexClient; profiles: BoundProfiles }): Promise<AuthorisedReading> {
219
+ const { record, holder, index, profiles } = args
220
+ const passportId = record.passportId
221
+ const lineage = await index.lineage(passportId)
222
+ const tip = lineage.at(-1)
223
+ if (tip == null) return { passportId, ownerTier: { status: 'not-checked', detail: 'The index holds no state for this passport.' }, authorisedView: notChecked('The index holds no state for this passport.') }
224
+ const txid = tip.id('hex')
225
+ const state = findDppOutputs(tip)[0].state
226
+ const envelope = envelopeOf(state.payloadPublic)
227
+ const bound = envelope == null ? undefined : profiles.get(envelope.profile)
228
+ const base = { passportId, ...(envelope == null ? {} : { profile: envelope.profile }), ...(bound?.binding.access == null ? {} : { access: { policy: bound.binding.access.policy, public: [...bound.binding.access.public] } }) }
229
+ const entry = record.states.find((s) => s.txid === txid)
230
+ if (entry?.ownerTier == null) {
231
+ const detail = 'This platform\'s journal holds no restricted part for the newest state the index returned.'
232
+ return { ...base, ownerTier: { status: 'not-checked', txid, detail }, authorisedView: notChecked(detail) }
233
+ }
234
+ const ciphertext = Utils.toArray(entry.ownerTier.ciphertext, 'base64') as number[]
235
+ if (!verifyOwnerBlob(ciphertext, state.payloadOwnerHash)) {
236
+ return {
237
+ ...base,
238
+ ownerTier: { status: 'fail', txid, detail: 'The stored ciphertext does not hash to the payload_owner_hash of the state. It was not decrypted.' },
239
+ authorisedView: notChecked('The stored restricted part is not the one the state commits to, so it was not opened.'),
240
+ }
241
+ }
242
+ const ownerTier: OwnerTierCheck = { status: 'pass', txid, detail: 'The stored ciphertext hashes to the payload_owner_hash of the state. This is the protocol\'s owner-tier check; nothing else here is a statement about the commitment.' }
243
+ if (envelope == null || bound == null) {
244
+ return { ...base, ownerTier, authorisedView: notChecked(envelope == null ? 'The newest state\'s payload is not a product document under a binding.' : `This application holds no binding for ${envelope.profile}.`) }
245
+ }
246
+ let restricted: unknown
247
+ try {
248
+ const { plaintext } = await holder.wallet.decrypt({ ciphertext, protocolID: OWNER_DATA_PROTOCOL, keyID: passportId, counterparty: entry.ownerTier.senderIdentityKey ?? 'self' })
249
+ restricted = JSON.parse(Utils.toUTF8(plaintext))
250
+ } catch {
251
+ // The reason is not repeated: a decryption error can quote the bytes it failed on.
252
+ return { ...base, ownerTier, authorisedView: notChecked(`The wallet for ${holder.name} could not open the committed restricted part with the recorded counterparty.`) }
253
+ }
254
+ // A state with no restricted property seals an empty object, which is no restricted part at all.
255
+ const restrictedProduct = isObject(restricted) && Object.keys(restricted).length === 0 ? undefined : restricted
256
+ const validation = await profiles.validateAuthorised({ profile: bound.id, profileVersion: bound.version, payloadPublic: state.payloadPublic, passportId: state.passportId, ...(restrictedProduct === undefined ? {} : { restrictedProduct }) })
257
+ const assembly = assembleProduct({ binding: bound.binding, publicProduct: envelope.product, ...(restrictedProduct === undefined ? {} : { restrictedProduct }) })
258
+ return {
259
+ ...base,
260
+ ownerTier,
261
+ authorisedView: await profiles.viewCheck('authorised', validation),
262
+ ...(isObject(restrictedProduct) ? { restrictedProduct } : {}),
263
+ ...(assembly.ok ? { product: assembly.product } : {}),
95
264
  }
96
265
  }
@@ -0,0 +1,159 @@
1
+ // The identifier host. A passport identifier is a GS1 Digital Link minted
2
+ // under PASSPORT_HOST, and the standard's GS1 discovery profile
3
+ // (spec/gs1-discovery.md §1, rule 6) asks the host an identifier is minted
4
+ // under to be a GS1-Conformant Resolver for primary key 01. These routes are
5
+ // that resolver, and every rule of it comes from the reference helpers of
6
+ // @bsv/dpp-profiles: the description file at /.well-known/gs1resolver, and
7
+ // every path under /01/, which sends a browser to the page and gives a client
8
+ // that asks for the links the linkset.
9
+ //
10
+ // No record is stored. The records a request is resolved against are made
11
+ // from the journal: an item this application issued a passport for has its
12
+ // passport page as its default link, and its GTIN has the product page, which
13
+ // every other request under that GTIN walks up to. A link is listed only when
14
+ // this application serves its target. Reads are open, as every read here is.
15
+ import {
16
+ GS1_LINK_TYPES,
17
+ JSON_LD_CONTEXT_RELATION,
18
+ LINKSET_CONTEXT_URI,
19
+ LINKSET_MEDIA_TYPE,
20
+ decompressGs1DigitalLink,
21
+ describeResolver,
22
+ gs1KeyOf,
23
+ linksetDocument,
24
+ parseAcceptHeader,
25
+ parseAcceptLanguage,
26
+ parseGs1DigitalLinkUri,
27
+ resolutionRecordProblems,
28
+ resolutionSetProblems,
29
+ resolveLinks,
30
+ uncompressedUri,
31
+ type Gs1Key,
32
+ type LinksetDocument,
33
+ type ParsedGs1Uri,
34
+ type ResolutionRecord,
35
+ } from '@bsv/dpp-profiles'
36
+ import { Router, type NextFunction, type Request, type Response } from 'express'
37
+ import { HttpError } from './http-error.js'
38
+ import type { IdentifierPolicy } from './identifiers.js'
39
+ import type { Store } from './store.js'
40
+
41
+ export interface ResolverOptions {
42
+ store: Store
43
+ policy: IdentifierPolicy
44
+ }
45
+
46
+ /** The pages live under this path, each at its identifier's own path after it. The web app routes the same paths (apps/web/src/app.tsx). */
47
+ const PAGE_PREFIX = '/passport'
48
+ const METHODS = 'GET, HEAD, OPTIONS'
49
+ /** The special compressed form: one path segment that begins `eh` or `ex` and carries an EPC binary string, which is sixteen characters at its shortest. */
50
+ const COMPRESSED = /^\/e[hx][A-Za-z0-9_-]{16,}\/?$/
51
+ /** The revision of the rule the records are made by. Change it when the links below change. */
52
+ const CONFIGURATION_REVISION = 'journal-1'
53
+
54
+ export function resolverRoutes({ store, policy }: ResolverOptions): Router {
55
+ const root = `https://${policy.host}`
56
+ const description = describeResolver({ resolverRoot: root })
57
+ const pageOf = (key: Gs1Key): string => `${root}${PAGE_PREFIX}${uncompressedUri('', key)}`
58
+
59
+ /**
60
+ * The records a request under one GTIN is resolved against. The item's record exists when the journal holds the
61
+ * passport whose identifier is the item's own. The GTIN's record exists when the journal holds any passport under
62
+ * that GTIN, and carries the one public default the profile's set check requires. Both checks of the profiles
63
+ * package are applied to what is made here, so a change to these links that breaks a rule stops the answer.
64
+ */
65
+ async function recordsFor(key: Gs1Key): Promise<ResolutionRecord[]> {
66
+ const product: Gs1Key = { ai: '01', value: key.value, qualifiers: [] }
67
+ const serial = key.qualifiers.find((qualifier) => qualifier.ai === '21')
68
+ const item: Gs1Key | undefined = serial == null ? undefined : { ...product, qualifiers: [serial] }
69
+ const issued = item != null && (await store.getPassport(uncompressedUri(root, item))) != null
70
+ if (!issued && !(await store.anyPassportUnder(`${uncompressedUri(root, product)}/21/`))) return []
71
+ const records: ResolutionRecord[] = [{ key: { ai: '01', value: key.value }, qualifiers: [], configurationRevision: CONFIGURATION_REVISION, links: [{ rel: GS1_LINK_TYPES.pip, href: pageOf(product), title: 'Product information', default: 'single', disclosure: 'public' }] }]
72
+ if (item != null && issued) records.unshift({ key: { ai: '01', value: key.value }, qualifiers: item.qualifiers, configurationRevision: CONFIGURATION_REVISION, links: [{ rel: GS1_LINK_TYPES.dpp, href: pageOf(item), title: 'Digital product passport', default: 'single', disclosure: 'public' }] })
73
+ const problems = [...records.flatMap(resolutionRecordProblems), ...resolutionSetProblems(records)]
74
+ if (problems.length > 0) throw new Error(`the resolver's records for GTIN ${key.value} are not admissible: ${problems.join('; ')}`)
75
+ return records
76
+ }
77
+
78
+ /** The JSON linkset, with the Link header that names GS1's context for it (resolver standard §2.10). The context is named, never served: GS1 publishes it. */
79
+ const sendLinkset = (res: Response, status: number, linkset: LinksetDocument): void => {
80
+ res.status(status).set('Link', `<${LINKSET_CONTEXT_URI}>; rel="${JSON_LD_CONTEXT_RELATION}"; type="application/ld+json"`).type(LINKSET_MEDIA_TYPE).send(JSON.stringify(linkset))
81
+ }
82
+
83
+ /** Answer one identifier as the resolver standard's flow reads it: refuse what is malformed, then the linkset when it was asked for, or else a redirect. */
84
+ async function resolve(req: Request, res: Response, parsed: ParsedGs1Uri, query: string): Promise<void> {
85
+ if (parsed.kind !== 'uncompressed') throw new HttpError(400, 'identifier-malformed', parsed.kind === 'invalid' ? parsed.detail : 'a compressed form is read at the root of this host', { reason: parsed.kind === 'invalid' ? parsed.reason : 'no-primary-key' })
86
+ // The resolver standard's validation includes the check digit (§2.4), and no passport here has a GTIN that fails it: the writer refuses one.
87
+ if (!parsed.primaryKey.checkDigitValid) throw new HttpError(400, 'identifier-malformed', `the check digit of GTIN ${parsed.primaryKey.value} does not hold`, { reason: 'check-digit' })
88
+ const key = gs1KeyOf(parsed)
89
+ const records = await recordsFor(key)
90
+ const accept = parseAcceptHeader(req.get('accept'))
91
+ const request = { key, audience: 'public' as const, resolverRoot: root, accept, acceptLanguage: parseAcceptLanguage(req.get('accept-language')) }
92
+ const unknown = (): HttpError => new HttpError(404, 'identifier-unknown', `this application issued no passport under ${uncompressedUri(root, { ...key, qualifiers: [] })}`)
93
+ // The linkset is asked for by linkType=linkset or by its media type (§2.9), and a request for JSON alone gets the same answer (§2.10). It is never redirected.
94
+ if (parsed.linkType?.linkset === true || accept.includes(LINKSET_MEDIA_TYPE) || (parsed.linkType == null && accept[0] === 'application/json')) {
95
+ const linkset = linksetDocument(records, request)
96
+ if (linkset == null) throw unknown()
97
+ sendLinkset(res, 200, linkset)
98
+ return
99
+ }
100
+ const outcome = resolveLinks(records, { ...request, linkType: parsed.linkType?.iri ?? parsed.linkType?.raw })
101
+ switch (outcome.outcome) {
102
+ case 'redirect':
103
+ // 307 is the profile's choice of status, and the whole query string is passed on (§2.12). Every target is a page of this application, so it is
104
+ // given as its path, which a client resolves against the address it asked: the redirect lands here at PASSPORT_HOST, behind a proxy and in development.
105
+ res.redirect(307, `${new URL(outcome.link.href).pathname}${query}`)
106
+ return
107
+ case 'multiple-choices':
108
+ sendLinkset(res, 300, linksetDocument(records, request) ?? { linkset: [] })
109
+ return
110
+ case 'not-found':
111
+ throw new HttpError(404, 'link-type-unknown', `no link of type ${outcome.requested} is registered for ${uncompressedUri(root, key)}`)
112
+ default:
113
+ throw unknown()
114
+ }
115
+ }
116
+
117
+ /** Every answer is open to any origin and says which request headers shaped it. OPTIONS is answered here, and a method other than GET and HEAD is refused. */
118
+ const open =
119
+ (handler: (req: Request, res: Response) => Promise<void>) =>
120
+ (req: Request, res: Response, next: NextFunction): void => {
121
+ res.set({ 'Access-Control-Allow-Origin': '*', 'Access-Control-Allow-Methods': METHODS, 'Access-Control-Allow-Headers': 'Accept, Accept-Language', 'Access-Control-Expose-Headers': 'Link', Vary: 'Accept, Accept-Language' })
122
+ if (req.method === 'OPTIONS') {
123
+ res.set('Allow', METHODS).status(204).end()
124
+ return
125
+ }
126
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
127
+ res.set('Allow', METHODS)
128
+ next(new HttpError(405, 'method-not-allowed', `an identifier is read with ${METHODS}`))
129
+ return
130
+ }
131
+ handler(req, res).catch(next)
132
+ }
133
+
134
+ const router = Router()
135
+ router.all(
136
+ '/.well-known/gs1resolver',
137
+ open(async (_req, res) => {
138
+ res.json(description)
139
+ })
140
+ )
141
+ router.all(
142
+ '/01{/*rest}',
143
+ open(async (req, res) => {
144
+ const uri = `${root}${req.originalUrl}`
145
+ const parsed = parseGs1DigitalLinkUri(uri)
146
+ await resolve(req, res, parsed, parsed.kind === 'invalid' ? '' : new URL(uri).search)
147
+ })
148
+ )
149
+ // A compressed form carries a GTIN and a serial as an EPC binary string. It is decompressed and then answered as the identifier it spells (§2.3).
150
+ router.all(
151
+ COMPRESSED,
152
+ open(async (req, res) => {
153
+ const decompressed = decompressGs1DigitalLink(`${root}${req.originalUrl}`)
154
+ if (!decompressed.ok) throw new HttpError(400, 'identifier-malformed', decompressed.detail, { reason: decompressed.reason })
155
+ await resolve(req, res, parseGs1DigitalLinkUri(decompressed.uri), new URL(decompressed.uri).search)
156
+ })
157
+ )
158
+ return router
159
+ }