@bsv/create-dpp-app 0.1.0-beta.1 → 0.1.0-beta.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (143) hide show
  1. package/NOTICE +2 -0
  2. package/PATENTS +12 -0
  3. package/README.md +26 -6
  4. package/dist/index.js +36 -8
  5. package/package.json +9 -5
  6. package/template/Dockerfile +4 -2
  7. package/template/README.md +297 -42
  8. package/template/_env.example +82 -13
  9. package/template/_github/workflows/ci.yml +3 -3
  10. package/template/apps/api/API.md +86 -16
  11. package/template/apps/api/package.json +9 -4
  12. package/template/apps/api/src/bound-profiles.ts +590 -0
  13. package/template/apps/api/src/claims.ts +175 -56
  14. package/template/apps/api/src/cli.ts +64 -7
  15. package/template/apps/api/src/config.ts +124 -10
  16. package/template/apps/api/src/custody.ts +241 -69
  17. package/template/apps/api/src/dev-index.ts +58 -9
  18. package/template/apps/api/src/env-file.ts +55 -0
  19. package/template/apps/api/src/epcis/exchange.ts +434 -0
  20. package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
  21. package/template/apps/api/src/epcis/routes.ts +364 -0
  22. package/template/apps/api/src/epcis/sources.ts +142 -0
  23. package/template/apps/api/src/go-live.ts +226 -0
  24. package/template/apps/api/src/http-error.ts +15 -0
  25. package/template/apps/api/src/identifiers.ts +1 -1
  26. package/template/apps/api/src/index-client.ts +131 -6
  27. package/template/apps/api/src/index-projects.ts +53 -0
  28. package/template/apps/api/src/lifecycle-authority.ts +49 -0
  29. package/template/apps/api/src/lifecycle.ts +485 -0
  30. package/template/apps/api/src/main.ts +10 -2
  31. package/template/apps/api/src/parties.ts +2 -2
  32. package/template/apps/api/src/platform.ts +72 -17
  33. package/template/apps/api/src/portability/commands.ts +224 -0
  34. package/template/apps/api/src/portability/export.ts +708 -0
  35. package/template/apps/api/src/portability/package.ts +270 -0
  36. package/template/apps/api/src/portability/restore.ts +863 -0
  37. package/template/apps/api/src/profiles.ts +38 -13
  38. package/template/apps/api/src/reader.ts +172 -3
  39. package/template/apps/api/src/resolver.ts +159 -0
  40. package/template/apps/api/src/sector-examples.ts +390 -0
  41. package/template/apps/api/src/server.ts +253 -60
  42. package/template/apps/api/src/store.ts +198 -21
  43. package/template/apps/api/src/validation-engine.ts +172 -0
  44. package/template/apps/api/src/wallet.ts +30 -17
  45. package/template/apps/api/src/worker.ts +20 -13
  46. package/template/apps/api/src/writer.ts +383 -131
  47. package/template/apps/api/test/bound-http.test.ts +496 -0
  48. package/template/apps/api/test/bound-profiles.test.ts +547 -0
  49. package/template/apps/api/test/config.test.ts +148 -3
  50. package/template/apps/api/test/custody-journal.test.ts +415 -0
  51. package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
  52. package/template/apps/api/test/custom-profile.test.ts +167 -0
  53. package/template/apps/api/test/env-file.test.ts +53 -0
  54. package/template/apps/api/test/epcis-fixtures.ts +270 -0
  55. package/template/apps/api/test/epcis-http.test.ts +1179 -0
  56. package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
  57. package/template/apps/api/test/epcis-separation.test.ts +253 -0
  58. package/template/apps/api/test/epcis-web.test.ts +230 -0
  59. package/template/apps/api/test/exit-exercise.test.ts +1038 -0
  60. package/template/apps/api/test/external-index.test.ts +3 -2
  61. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
  62. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
  63. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
  64. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
  65. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
  66. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
  67. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
  68. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
  69. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
  70. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
  71. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
  72. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
  73. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
  74. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
  75. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
  76. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
  77. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
  78. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
  79. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
  80. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
  81. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
  82. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
  83. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
  84. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
  85. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
  86. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
  87. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
  88. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
  89. package/template/apps/api/test/go-live.test.ts +179 -0
  90. package/template/apps/api/test/gs1-global-setup.ts +33 -0
  91. package/template/apps/api/test/gs1-test-env.ts +5 -0
  92. package/template/apps/api/test/identifier-host.test.ts +256 -0
  93. package/template/apps/api/test/index-projects.test.ts +81 -0
  94. package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
  95. package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
  96. package/template/apps/api/test/lifecycle.test.ts +17 -6
  97. package/template/apps/api/test/manifest-notice.test.ts +36 -0
  98. package/template/apps/api/test/network-guard.ts +113 -0
  99. package/template/apps/api/test/portability.test.ts +655 -0
  100. package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
  101. package/template/apps/api/test/retired-profiles.test.ts +216 -0
  102. package/template/apps/api/test/sector-cutover.test.ts +95 -0
  103. package/template/apps/api/test/sector-forms.test.ts +420 -0
  104. package/template/apps/api/test/unjoined-index.test.ts +62 -0
  105. package/template/apps/api/test/validation-engine.test.ts +328 -0
  106. package/template/apps/api/test/wallet-monitor.test.ts +38 -0
  107. package/template/apps/api/test/writer-journal.test.ts +327 -0
  108. package/template/apps/api/vitest.config.ts +3 -0
  109. package/template/apps/web/src/app.tsx +8 -4
  110. package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
  111. package/template/apps/web/src/components/bound/field-view.tsx +237 -0
  112. package/template/apps/web/src/components/bound/pieces.tsx +169 -0
  113. package/template/apps/web/src/components/bound/readings.tsx +152 -0
  114. package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
  115. package/template/apps/web/src/components/claim-dialog.tsx +344 -0
  116. package/template/apps/web/src/components/epcis-events.tsx +119 -0
  117. package/template/apps/web/src/components/layout.tsx +17 -0
  118. package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
  119. package/template/apps/web/src/components/passport-form.tsx +2 -2
  120. package/template/apps/web/src/components/read-passport.tsx +4 -3
  121. package/template/apps/web/src/components/reading.tsx +32 -39
  122. package/template/apps/web/src/lib/api.ts +136 -26
  123. package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
  124. package/template/apps/web/src/lib/bound/display.ts +122 -0
  125. package/template/apps/web/src/lib/bound/fields.ts +128 -0
  126. package/template/apps/web/src/lib/bound/form-model.ts +521 -0
  127. package/template/apps/web/src/lib/bound/forms.ts +15 -0
  128. package/template/apps/web/src/lib/bound/identity.ts +48 -0
  129. package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
  130. package/template/apps/web/src/lib/bound/units.ts +37 -0
  131. package/template/apps/web/src/lib/epcis.ts +345 -0
  132. package/template/apps/web/src/lib/format.ts +27 -4
  133. package/template/apps/web/src/lib/lifecycle.ts +350 -0
  134. package/template/apps/web/src/pages/accept.tsx +8 -3
  135. package/template/apps/web/src/pages/events.tsx +388 -0
  136. package/template/apps/web/src/pages/new-passport.tsx +25 -2
  137. package/template/apps/web/src/pages/operations.tsx +22 -3
  138. package/template/apps/web/src/pages/passport.tsx +226 -162
  139. package/template/apps/web/src/pages/public-passport.tsx +50 -10
  140. package/template/apps/web/src/pages/wallet.tsx +1 -1
  141. package/template/apps/web/vite.config.ts +12 -4
  142. package/template/deploy/compose.yml +14 -2
  143. package/template/package.json +9 -3
@@ -1,23 +1,31 @@
1
- // The HTTP surface. JSON under /api; the built web app and the passport
1
+ // The HTTP surface. JSON under /api; the identifier host under /01 and
2
+ // /.well-known/gs1resolver (resolver.ts); the built web app and the passport
2
3
  // pages under everything else. Reads are open: anyone may verify a passport.
3
4
  // Writes need a signed-in member of the brand that holds the passport, or,
4
5
  // for a recipient under managed custody, the claim code they accepted with.
5
6
  import { existsSync, readFileSync } from 'node:fs'
6
7
  import { join } from 'node:path'
7
8
  import { Hash, Utils } from '@bsv/sdk'
8
- import { verifyLifecycleClaim } from '@bsv/dpp-protocol'
9
- import { readPublicPayloadSchema, readRestrictedPayloadSchema } from '@bsv/dpp-profiles'
9
+ import { EPCIS_LIFECYCLE_MEDIA_TYPE, EPCIS_LIFECYCLE_ROLES, parseEpcisLifecycleClaim, type EpcisLifecycleRole, type EpcisLifecycleSource } from '@bsv/dpp-credentials/epcis-lifecycle'
10
+ import { PROFILE_RETIRED, ProfileRetiredError, RETIRED_PROFILE_REPLACEMENTS, describeRetiredProfile, isRetiredProfile, readPublicPayloadSchema, readRestrictedPayloadSchema } from '@bsv/dpp-profiles'
10
11
  import express, { type NextFunction, type Request, type Response } from 'express'
11
12
  import { fromNodeHeaders, toNodeHandler } from 'better-auth/node'
12
13
  import { sessionFrom, type Auth, type Session } from './auth.js'
13
- import { EVENT_TYPES } from './claims.js'
14
+ import type { IssueClaimInput } from './claims.js'
15
+ import type { EpcisExchange } from './epcis/exchange.js'
16
+ import { epcisRoutes } from './epcis/routes.js'
17
+ import { HttpError } from './http-error.js'
14
18
  import { isDemonstrationPolicy, mintPassportId } from './identifiers.js'
19
+ import { eventSchemaCheck, readLifecycleClaim, readPassportClaims, type ClaimsReaderOptions } from './lifecycle.js'
20
+ import { sectorExamples } from './sector-examples.js'
21
+ import { offerHolderName } from './custody.js'
15
22
  import type { Party } from './parties.js'
16
23
  import type { Platform } from './platform.js'
17
- import { currentProfiles, isProfileId, manifestFor, sampleWithProblems } from './profiles.js'
18
- import type { PassportRecord, StateEntry } from './store.js'
24
+ import { resolverRoutes } from './resolver.js'
25
+ import { currentProfiles, isProfileId, manifestFor, sampleWithProblems, sectorIssueSuccessor } from './profiles.js'
26
+ import { isEpcisLifecycleRecord, type PassportRecord, type StateEntry } from './store.js'
19
27
  import { pendingDuties, runDuties, summariseJournal } from './worker.js'
20
- import { WriteRefused } from './writer.js'
28
+ import { WriteRefused, refuseRetiredProfile, requireIssuableProfile } from './writer.js'
21
29
 
22
30
  export interface ServerOptions {
23
31
  platform: Platform
@@ -30,17 +38,12 @@ export interface ServerOptions {
30
38
  devSession?: Session
31
39
  /** The built web app to serve, when it exists. */
32
40
  webDist?: string
41
+ /** The EPCIS exchange, opened and recovered. Without it the /api/epcis routes are not served. */
42
+ exchange?: EpcisExchange
33
43
  }
34
44
 
35
- class HttpError extends Error {
36
- constructor(
37
- readonly status: number,
38
- readonly code: string,
39
- detail: string
40
- ) {
41
- super(detail)
42
- }
43
- }
45
+ /** A JSON object from a request body, or nothing: a product document is always one object. */
46
+ const objectOf = (value: unknown): Record<string, unknown> | undefined => (typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : undefined)
44
47
 
45
48
  const sha256hex = (text: string): string => Utils.toHex(Hash.sha256(Utils.toArray(text, 'utf8')))
46
49
  /** A URL-safe slug from a name: lower-case letters and digits with single hyphens, at most 64 characters, built without backtracking. */
@@ -67,7 +70,8 @@ const param = (req: Request, name: string): string => {
67
70
 
68
71
  /** What a passport looks like over the API: the journal without the owner-tier ciphertext. */
69
72
  function publicView(record: PassportRecord, policyIsDemo: boolean) {
70
- const tip = record.states.at(-1)
73
+ const tip = record.states.filter((state) => state.network === 'accepted' || state.network === 'dry-run').at(-1)
74
+ const journal = summariseJournal(record)
71
75
  let payload: unknown = tip?.payloadPublic
72
76
  try {
73
77
  payload = tip == null ? undefined : JSON.parse(tip.payloadPublic)
@@ -78,12 +82,14 @@ function publicView(record: PassportRecord, policyIsDemo: boolean) {
78
82
  passportId: record.passportId,
79
83
  brandId: record.brandId,
80
84
  profile: record.profile,
81
- status: record.status,
85
+ // Present only for a passport journalled under a retired profile: the page then offers no write and names the replacement.
86
+ ...(isRetiredProfile(record.profile) ? { profileRetired: { replacedBy: RETIRED_PROFILE_REPLACEMENTS[record.profile] } } : {}),
87
+ status: journal.status,
82
88
  demonstration: policyIsDemo,
83
89
  holder: record.holder,
84
90
  createdAt: record.createdAt,
85
91
  payload,
86
- journal: summariseJournal(record),
92
+ journal,
87
93
  states: record.states.map((s: StateEntry) => ({
88
94
  op: s.op,
89
95
  txid: s.txid,
@@ -105,24 +111,38 @@ export function createServer(options: ServerOptions): express.Express {
105
111
  const { store, parties, writer, custody, claims, config } = platform
106
112
  const policy = { host: config.passportHost, prefix: config.gs1Prefix }
107
113
  const demo = isDemonstrationPolicy(policy)
114
+ // How lifecycle claims are read: by the index's anchors and this application's records, each verified with the pinned schema the EPCIS exchange provisioned.
115
+ const schemaCheck = options.exchange == null ? undefined : eventSchemaCheck(options.exchange.artefactsDir)
116
+ const claimsReader: ClaimsReaderOptions = {
117
+ ...platform.lifecyclePolicy,
118
+ store,
119
+ index: platform.index,
120
+ ...(config.registry.url == null ? {} : { registry: { url: config.registry.url } }),
121
+ ...(platform.chainTracker === 'scripts only' ? {} : { chainTracker: platform.chainTracker }),
122
+ ...(schemaCheck == null ? {} : { schemaCheck }),
123
+ }
108
124
  const app = express()
109
125
  app.disable('x-powered-by')
110
126
 
111
127
  // Better Auth owns /api/auth; it must see the raw body, so it is mounted before the JSON parser.
112
128
  if (auth != null) app.all('/api/auth/{*splat}', toNodeHandler(auth))
113
- app.use(express.json({ limit: '1mb' }))
114
129
 
115
- const wrap = (handler: (req: Request, res: Response) => Promise<unknown>) => (req: Request, res: Response, next: NextFunction) => {
116
- handler(req, res).then((body) => {
117
- if (!res.headersSent) res.json(body)
118
- }, next)
119
- }
120
130
  const session = async (req: Request): Promise<Session | undefined> => (auth == null ? options.devSession : await sessionFrom(auth, req.headers))
121
131
  const requireSession = async (req: Request): Promise<Session> => {
122
132
  const s = await session(req)
123
133
  if (s == null) throw new HttpError(401, 'sign-in-required', 'sign in first')
124
134
  return s
125
135
  }
136
+ // The EPCIS routes come before the JSON parser too: an import is taken as the exact bytes that arrived. They are handed
137
+ // the exchange and the sign-in check and nothing else of the platform, so no import or pull can reach the wallet or the writer.
138
+ if (options.exchange != null) app.use('/api/epcis', epcisRoutes({ exchange: options.exchange, requireSession }))
139
+ app.use(express.json({ limit: '1mb' }))
140
+
141
+ const wrap = (handler: (req: Request, res: Response) => Promise<unknown>) => (req: Request, res: Response, next: NextFunction) => {
142
+ handler(req, res).then((body) => {
143
+ if (!res.headersSent) res.json(body)
144
+ }, next)
145
+ }
126
146
  const requireMember = async (req: Request, brandId: string): Promise<Session> => {
127
147
  const s = await requireSession(req)
128
148
  if (!s.brandIds.includes(brandId)) throw new HttpError(403, 'not-a-member', `you are not a member of brand ${brandId}`)
@@ -139,12 +159,19 @@ export function createServer(options: ServerOptions): express.Express {
139
159
  * holds it; the recipient, with the claim code they accepted with, once a
140
160
  * hand-on moved control to them.
141
161
  */
142
- const actorFor = async (req: Request, record: PassportRecord): Promise<Party> => {
143
- const [scope, id] = record.holder.party.split(':', 2)
162
+ const actorFor = async (req: Request, record: PassportRecord, partyName = record.holder.party): Promise<Party> => {
163
+ const separator = partyName.indexOf(':')
164
+ const scope = partyName.slice(0, separator)
165
+ const id = partyName.slice(separator + 1)
144
166
  if (scope === 'brand') {
145
167
  await requireMember(req, record.brandId)
146
168
  return parties.brand(id)
147
169
  }
170
+ if (scope === 'member') {
171
+ const member = parties.member((await requireSession(req)).userId)
172
+ if (member.name !== partyName) throw new HttpError(403, 'recipient-wrong', 'only the named member holds this passport')
173
+ return member
174
+ }
148
175
  if (scope === 'recipient') {
149
176
  const claimCode = typeof req.body?.claimCode === 'string' ? req.body.claimCode : undefined
150
177
  const offer = await store.getOffer(id)
@@ -158,28 +185,52 @@ export function createServer(options: ServerOptions): express.Express {
158
185
 
159
186
  app.get(
160
187
  '/api/health',
161
- wrap(async () => ({
162
- ok: true,
163
- network: config.network,
164
- index: platform.index.url,
165
- publisherKey: platform.wallet.identityKey,
166
- wallet: platform.wallet.kind,
167
- livePublishing: config.livePublishing,
168
- identifiers: { host: policy.host, prefix: policy.prefix, demonstration: demo },
169
- signIn: auth != null,
170
- devSession: auth == null && options.devSession != null ? { name: options.devSession.name, brandIds: options.devSession.brandIds } : undefined,
171
- }))
188
+ wrap(async () => {
189
+ // A validator service is asked again each time, so one that was started or stopped since the last look is reported as it is now.
190
+ await platform.profiles.checkEngine()
191
+ return {
192
+ ok: true,
193
+ network: config.network,
194
+ index: { url: platform.index.url, joined: config.index.joined, inProcess: platform.devIndex != null, configured: config.index.url },
195
+ publisherKey: platform.wallet.identityKey,
196
+ wallet: platform.wallet.kind,
197
+ livePublishing: config.livePublishing,
198
+ // Without the engine a profile held by a binding cannot be written, and its readings say "not checked".
199
+ validationEngine: platform.profiles.engineProblem == null,
200
+ // Where the engine runs: in this process, or in the validator service VALIDATOR_URL names.
201
+ validationEngineKind: platform.profiles.engineKind,
202
+ identifiers: { host: policy.host, prefix: policy.prefix, demonstration: demo },
203
+ signIn: auth != null,
204
+ devSession: auth == null && options.devSession != null ? { name: options.devSession.name, brandIds: options.devSession.brandIds } : undefined,
205
+ }
206
+ })
172
207
  )
173
208
 
174
- app.get('/api/profiles', wrap(async () => currentProfiles()))
209
+ app.get(
210
+ '/api/profiles',
211
+ wrap(async () => [
212
+ ...currentProfiles().map((profile) => ({ ...profile, format: 'manifest' })),
213
+ ...platform.profiles.list().map((profile) => ({ id: profile.profile, title: profile.binding.title, description: profile.binding.scope, format: 'binding', issueSuccessor: sectorIssueSuccessor(profile.profile) })),
214
+ ])
215
+ )
175
216
  app.get(
176
217
  '/api/profiles/:id',
177
218
  wrap(async (req) => {
178
219
  const id = param(req, 'id')
220
+ const bound = platform.profiles.get(id)
221
+ // A profile held by a binding has no field list: its product document is the profile's own data model, and the form asks for its code lists as it needs them.
222
+ // The form is closed while the engine is unavailable, so the engine is looked at again here: a validator service that came back opens it.
223
+ if (bound != null) {
224
+ await platform.profiles.checkEngine()
225
+ return { ...platform.profiles.describe(bound), examples: sectorExamples(bound, policy), demonstration: demo }
226
+ }
227
+ // Gone, not unknown: the profile was published and is retired, so no form, sample or schema is served for it.
228
+ if (isRetiredProfile(id)) throw new HttpError(410, PROFILE_RETIRED, describeRetiredProfile(id))
179
229
  if (!isProfileId(id)) throw new HttpError(404, 'profile-unknown', `${id} is not a profile this platform knows`)
180
230
  const manifest = manifestFor(id)
181
231
  return {
182
232
  id,
233
+ format: 'manifest',
183
234
  title: manifest.title,
184
235
  description: manifest.description,
185
236
  fields: manifest.fields.map((f) => ({ key: f.key, label: f.label, valueType: f.valueType, unit: f.unit, accessTier: f.accessTier, obligation: f.obligation, cardinality: f.cardinality, codeList: f.codeList, constraints: f.constraints, note: f.note, group: f.group })),
@@ -193,6 +244,17 @@ export function createServer(options: ServerOptions): express.Express {
193
244
  })
194
245
  )
195
246
 
247
+ app.get(
248
+ '/api/profiles/:id/codes',
249
+ wrap(async (req) => {
250
+ const bound = platform.profiles.get(param(req, 'id'))
251
+ if (bound == null) throw new HttpError(404, 'profile-unknown', `${param(req, 'id')} is not a profile held by a binding here`)
252
+ const asked = req.query.class
253
+ const classes = (Array.isArray(asked) ? asked : [asked]).filter((name): name is string => typeof name === 'string').slice(0, 64)
254
+ return await platform.profiles.codeLists(bound, classes)
255
+ })
256
+ )
257
+
196
258
  app.get(
197
259
  '/api/verify',
198
260
  wrap(async (req) => {
@@ -207,11 +269,28 @@ export function createServer(options: ServerOptions): express.Express {
207
269
  )
208
270
 
209
271
  app.get('/api/passports/:ref', wrap(async (req) => publicView(await passportFrom(param(req, 'ref')), demo)))
210
- app.get('/api/passports/:ref/claims', wrap(async (req) => (await store.listClaims({ passportId: (await passportFrom(param(req, 'ref'))).passportId })).map((c) => ({ ...c, verified: verifyLifecycleClaim(c.claim).signature }))))
272
+ // Every lifecycle claim that concerns the passport: EPCIS lifecycle claims found by its anchors and this application's records, each verified, and historical native claims read under their own rules.
273
+ app.get('/api/passports/:ref/claims', wrap(async (req) => await readPassportClaims((await passportFrom(param(req, 'ref'))).passportId, claimsReader)))
274
+ // The exact bytes of an EPCIS lifecycle claim this application holds: what was signed, sent and anchored, verifiable without this application.
275
+ app.get(
276
+ '/api/lifecycle-claims/:id',
277
+ wrap(async (req, res) => {
278
+ const id = decodeURIComponent(param(req, 'id'))
279
+ const record = (await store.listClaims()).filter(isEpcisLifecycleRecord).find((c) => c.attestationId === id || c.id === id)
280
+ if (record == null) throw new HttpError(404, 'claim-unknown', `this application holds no EPCIS lifecycle claim ${id}`)
281
+ res.type(EPCIS_LIFECYCLE_MEDIA_TYPE).send(Buffer.from(record.bytes, 'utf8'))
282
+ })
283
+ )
211
284
 
212
285
  app.get('/api/offers/:requestId', wrap(async (req) => await custody.preview(param(req, 'requestId'))))
213
- app.post('/api/offers/:requestId/accept', wrap(async (req) => await custody.accept({ requestId: param(req, 'requestId'), claimCode: req.body?.claimCode })))
214
- app.post('/api/offers/:requestId/decline', wrap(async (req) => await custody.decline(param(req, 'requestId'), req.body?.claimCode)))
286
+ app.post('/api/offers/:requestId/accept', wrap(async req => {
287
+ const member = await session(req)
288
+ return await custody.accept({ requestId: param(req, 'requestId'), claimCode: req.body?.claimCode, recipient: member == null ? undefined : parties.member(member.userId) })
289
+ }))
290
+ app.post('/api/offers/:requestId/decline', wrap(async req => {
291
+ const member = await session(req)
292
+ return await custody.decline(param(req, 'requestId'), req.body?.claimCode, member == null ? undefined : parties.member(member.userId).identityKey)
293
+ }))
215
294
 
216
295
  // ------------------------------------------------------------------ signed in
217
296
 
@@ -264,10 +343,23 @@ export function createServer(options: ServerOptions): express.Express {
264
343
  const brandRecord = await store.getBrand(brandId)
265
344
  if (brandRecord == null) throw new HttpError(404, 'brand-unknown', `no brand ${brandId}`)
266
345
  const { profile, itemReference, serial, payload, ownerFields } = req.body ?? {}
267
- if (!isProfileId(profile)) throw new HttpError(400, 'profile-unknown', `${profile} is not a profile this platform knows`)
346
+ const bound = typeof profile === 'string' ? platform.profiles.get(profile) : undefined
347
+ if (typeof profile === 'string') requireIssuableProfile(profile)
348
+ if (bound == null && !isProfileId(profile)) throw new HttpError(400, 'profile-unknown', `${String(profile)} is not a profile this platform knows`)
268
349
  if (typeof itemReference !== 'string' || typeof serial !== 'string') throw new HttpError(400, 'identifier-required', 'give itemReference (digits) and serial')
269
- const passportId = mintPassportId(policy, itemReference, serial)
270
- const outcome = await writer.issue({ brandId, brand: parties.brand(brandId), passportId, profile, payload: payload ?? {}, ownerFields: ownerFields ?? {} })
350
+ let passportId: string
351
+ try {
352
+ passportId = mintPassportId(policy, itemReference, serial)
353
+ } catch (cause) {
354
+ throw new HttpError(400, 'identifier-refused', cause instanceof Error ? cause.message : String(cause))
355
+ }
356
+ // Under a binding the body carries the complete product document. It is validated against the identifier minted here, which is the one the state signs.
357
+ const product = objectOf(req.body?.product)
358
+ if (bound != null && product == null) throw new HttpError(400, 'product-required', `${bound.profile} is held by a binding: send the complete product document as product`)
359
+ const outcome =
360
+ bound != null
361
+ ? await writer.issue({ brandId, brand: parties.brand(brandId), passportId, profile: bound.profile, product })
362
+ : await writer.issue({ brandId, brand: parties.brand(brandId), passportId, profile, payload: payload ?? {}, ownerFields: ownerFields ?? {} })
271
363
  return publicView(outcome.record, demo)
272
364
  })
273
365
  )
@@ -279,18 +371,30 @@ export function createServer(options: ServerOptions): express.Express {
279
371
  const actor = await actorFor(req, record)
280
372
  // ownerFields absent carries the current owner tier unchanged; {} seals an empty one.
281
373
  const ownerFields = typeof req.body?.ownerFields === 'object' && req.body.ownerFields != null ? req.body.ownerFields : undefined
282
- const outcome = await writer.update({ record, actor, payload: req.body?.payload ?? {}, ownerFields, eventData: req.body?.eventData })
374
+ const product = objectOf(req.body?.product)
375
+ // Under a binding the body carries the complete product document; the writer refuses the wrong one of the two for the passport's profile.
376
+ const outcome = await writer.update({ record, actor, ...(product == null ? { payload: req.body?.payload ?? {}, ownerFields } : { product }), eventData: req.body?.eventData })
283
377
  return publicView(outcome.record, demo)
284
378
  })
285
379
  )
286
380
 
381
+ // The holder's view of a passport under a profile held by a binding. A POST, because a recipient proves they hold it with the claim code in the body.
287
382
  app.post(
288
- '/api/passports/:ref/offer',
383
+ '/api/passports/:ref/authorised-view',
289
384
  wrap(async (req) => {
290
385
  const record = await passportFrom(param(req, 'ref'))
291
386
  const holder = await actorFor(req, record)
387
+ if (platform.profiles.get(record.profile) == null) throw new HttpError(409, 'profile-not-bound', `${record.profile} is not held by a binding this application registered: this view exists for product documents that are split into a public and a restricted part`)
388
+ return await platform.readAuthorised(record, holder)
389
+ })
390
+ )
391
+
392
+ app.post(
393
+ '/api/passports/:ref/offer',
394
+ wrap(async (req) => {
395
+ const record = await passportFrom(param(req, 'ref'))
292
396
  const terms = typeof req.body?.terms === 'object' && req.body.terms != null ? req.body.terms : { word: 'Handed on' }
293
- return await custody.offer({ record, holder, terms, mechanism: req.body?.mechanism, recipientIdentityKey: req.body?.recipientIdentityKey })
397
+ return await custody.offer({ record, holder: name => actorFor(req, record, name), requestId: req.body?.requestId, terms, mechanism: req.body?.mechanism, recipientIdentityKey: req.body?.recipientIdentityKey })
294
398
  })
295
399
  )
296
400
 
@@ -300,7 +404,7 @@ export function createServer(options: ServerOptions): express.Express {
300
404
  const offer = await store.getOffer(param(req, 'requestId'))
301
405
  if (offer == null) throw new HttpError(404, 'offer-unknown', `no offer ${param(req, 'requestId')}`)
302
406
  const record = await passportFrom(encodeURIComponent(offer.passportId))
303
- const holder = await actorFor(req, record)
407
+ const holder = await actorFor(req, record, offerHolderName(record, offer))
304
408
  return await custody.withdraw(param(req, 'requestId'), holder)
305
409
  })
306
410
  )
@@ -336,17 +440,80 @@ export function createServer(options: ServerOptions): express.Express {
336
440
  })
337
441
  )
338
442
 
443
+ /**
444
+ * Sign an EPCIS lifecycle claim about the passport, as the signed-in member. The body names the event in one of three
445
+ * ways: `event`, an EPCIS 2.0.1 event the member entered; `imported`, an event the EPCIS exchange retained, by its
446
+ * import and pointer, which is signed with a source link back to the import; or `correctionOf`, a claim this
447
+ * application holds, which a new claim declares in error with the event's own error declaration. The original is
448
+ * never changed. `submit: true` then sends it to the registry, a separate step.
449
+ */
339
450
  app.post(
340
451
  '/api/passports/:ref/claims',
341
452
  wrap(async (req) => {
342
453
  const s = await requireSession(req)
343
454
  const record = await passportFrom(param(req, 'ref'))
344
- const eventType = req.body?.eventType
345
- if (!EVENT_TYPES.includes(eventType)) throw new HttpError(400, 'event-type-unknown', `eventType must be one of ${EVENT_TYPES.join(', ')}`)
346
- const issuer = parties.member(s.userId)
347
- let claim = await claims.sign({ passport: record, issuer, eventType, keyId: s.email })
348
- if (req.body?.submit === true) claim = await claims.submit(claim)
349
- return { ...claim, verified: verifyLifecycleClaim(claim.claim).signature }
455
+ refuseRetiredProfile(record.profile)
456
+ const body = objectOf(req.body) ?? {}
457
+ if (body.eventType !== undefined) {
458
+ throw new HttpError(400, 'four-category-claims-retired', 'This application no longer issues dpp-lifecycle-v1 claims with an Origin, Transfer, Transformation or Disposition event type. Send the EPCIS event that happened as event, or name an event the EPCIS exchange retained as imported. Nothing was signed.')
459
+ }
460
+ // A declaration of error keeps the role of the claim it corrects; every other claim states its own.
461
+ const role = typeof body.correctionOf === 'string' && body.assertedRole === undefined ? 'authorised-reporter' : body.assertedRole
462
+ if (typeof role !== 'string' || !(EPCIS_LIFECYCLE_ROLES as readonly string[]).includes(role)) throw new HttpError(400, 'asserted-role-required', `assertedRole must be one of ${EPCIS_LIFECYCLE_ROLES.join(', ')}`)
463
+ const strings = (value: unknown): string[] | undefined => (Array.isArray(value) && value.every((v) => typeof v === 'string') ? (value as string[]) : undefined)
464
+ if (body.authorityScope !== undefined && strings(body.authorityScope) == null) throw new HttpError(400, 'authority-scope-invalid', 'authorityScope must be an array of passport identifiers')
465
+ if (body.requiredExtensions !== undefined && strings(body.requiredExtensions) == null) throw new HttpError(400, 'required-extensions-invalid', 'requiredExtensions must be an array of rule identifiers')
466
+ const issue: Omit<IssueClaimInput, 'event'> = {
467
+ issuer: parties.member(s.userId),
468
+ assertedRole: role as EpcisLifecycleRole,
469
+ expectedPassport: record.passportId,
470
+ ...(strings(body.authorityScope) == null ? {} : { authorityScope: strings(body.authorityScope) }),
471
+ ...(typeof body.issuerParty === 'string' && body.issuerParty !== '' ? { issuerParty: body.issuerParty } : {}),
472
+ ...(strings(body.requiredExtensions) == null ? {} : { requiredExtensions: strings(body.requiredExtensions) }),
473
+ ...(Array.isArray(body.extensionContexts) ? { extensionContexts: body.extensionContexts as Array<Record<string, string>> } : {}),
474
+ ...(schemaCheck == null ? {} : { schemaCheck }),
475
+ }
476
+ let event: Record<string, unknown> | undefined
477
+ const imported = objectOf(body.imported)
478
+ if (imported != null) {
479
+ // An event someone else supplied. The member did not observe it, so it is never signed as the observer.
480
+ if (role === 'observer') throw new HttpError(409, 'importer-not-observer', 'An imported event was observed by whoever supplied it, not by this application, so it is not signed as the observer. Sign it as authorised-reporter, or as owner or custodian with your party identifier. Nothing was signed.')
481
+ if (options.exchange == null) throw new HttpError(409, 'epcis-unavailable', 'the EPCIS exchange is not running in this process')
482
+ const importId = typeof imported.importId === 'string' ? imported.importId : ''
483
+ const pointer = typeof imported.pointer === 'string' ? imported.pointer : ''
484
+ const retained = await options.exchange.retainedEvent(importId, pointer)
485
+ if (retained == null) throw new HttpError(404, 'event-unknown', `the EPCIS exchange retains no event at ${pointer} in ${importId}`)
486
+ if (retained.event.conflict?.state === 'open') throw new HttpError(409, 'event-in-conflict', 'Another body is held under this event identifier and the conflict is not decided. Decide it on the Events page first. Nothing was signed.')
487
+ if (retained.event.eventId == null) throw new HttpError(409, 'event-id-missing', 'The retained event declares no eventID. A lifecycle claim carries the event\'s own identifier and never mints one. Nothing was signed.')
488
+ event = retained.body
489
+ const source: EpcisLifecycleSource = { relation: 'imported', sourceDigest: retained.record.sha256, mediaType: retained.record.mediaType, eventPointer: pointer }
490
+ Object.assign(issue, { source, importedFrom: { importId, pointer }, ...(retained.inlineContexts.length === 0 || issue.extensionContexts != null ? {} : { extensionContexts: retained.inlineContexts }) })
491
+ } else if (typeof body.correctionOf === 'string') {
492
+ const original = (await store.listClaims({ passportId: record.passportId })).filter(isEpcisLifecycleRecord).find((c) => c.attestationId === body.correctionOf || c.id === body.correctionOf)
493
+ if (original == null) throw new HttpError(404, 'claim-unknown', `this application holds no EPCIS lifecycle claim ${String(body.correctionOf)} about ${record.passportId}`)
494
+ const claim = parseEpcisLifecycleClaim(original.bytes)
495
+ if (claim.event.errorDeclaration !== undefined) throw new HttpError(409, 'claim-is-declaration', 'That claim already declares its event in error.')
496
+ // EPCIS 2.0.1 section 7.4.1: the same event, with an error declaration added. Nothing else of it changes.
497
+ const reason = body.reason === 'did_not_occur' || body.reason === 'incorrect_data' ? body.reason : undefined
498
+ const corrective = strings(body.correctiveEventIDs)
499
+ event = { ...claim.event, errorDeclaration: { declarationTime: new Date().toISOString(), ...(reason == null ? {} : { reason }), ...(corrective == null || corrective.length === 0 ? {} : { correctiveEventIDs: corrective }) } }
500
+ Object.assign(issue, {
501
+ corrects: claim,
502
+ assertedRole: claim.assertedRole,
503
+ ...(claim.issuerParty == null ? {} : { issuerParty: claim.issuerParty }),
504
+ ...(claim.source == null ? {} : { source: claim.source }),
505
+ ...(original.importedFrom == null ? {} : { importedFrom: original.importedFrom }),
506
+ extensionContexts: claim.eventContext.flatMap((entry) => ('inline' in entry ? [entry.inline] : [])),
507
+ ...(claim.requiredExtensions == null ? {} : { requiredExtensions: claim.requiredExtensions }),
508
+ })
509
+ } else {
510
+ event = objectOf(body.event)
511
+ if (event == null) throw new HttpError(400, 'event-required', 'give the EPCIS event as event, a retained one as imported { importId, pointer }, or a claim to declare in error as correctionOf')
512
+ }
513
+ const issued = await claims.issue({ ...issue, event })
514
+ const claim = body.submit === true ? await claims.submit(issued) : issued
515
+ if (!isEpcisLifecycleRecord(claim)) throw new HttpError(500, 'internal', 'the claim issued is not an EPCIS lifecycle claim')
516
+ return await readLifecycleClaim(claim.bytes, record.passportId, { ...claimsReader, foundBy: ['this-application'], record: claim })
350
517
  })
351
518
  )
352
519
 
@@ -354,7 +521,16 @@ export function createServer(options: ServerOptions): express.Express {
354
521
  '/api/operations',
355
522
  wrap(async (req) => {
356
523
  await requireSession(req)
357
- return { duties: await pendingDuties(store), passports: (await store.listPassports()).map((p) => ({ passportId: p.passportId, brandId: p.brandId, status: p.status, journal: summariseJournal(p) })) }
524
+ await platform.profiles.checkEngine()
525
+ return {
526
+ duties: await pendingDuties(store),
527
+ passports: (await store.listPassports()).map((p) => {
528
+ const journal = summariseJournal(p)
529
+ return { passportId: p.passportId, brandId: p.brandId, status: journal.status, journal }
530
+ }),
531
+ // The engine's problem as it is now, where bound profiles are read from, and each profile folder or bundle that was refused.
532
+ profiles: { engine: { available: platform.profiles.engineProblem == null, kind: platform.profiles.engineKind, problem: platform.profiles.engineProblem }, source: platform.profiles.source, refused: platform.profiles.refusals },
533
+ }
358
534
  })
359
535
  )
360
536
  app.post(
@@ -389,12 +565,17 @@ export function createServer(options: ServerOptions): express.Express {
389
565
  })
390
566
  )
391
567
 
568
+ // ------------------------------------------------------------------ the identifier host
569
+
570
+ // Each identifier's own path is the resolver's: it redirects a browser to the passport page and gives the linkset to a client that asks for it.
571
+ app.use(resolverRoutes({ store, policy }))
572
+
392
573
  // ------------------------------------------------------------------ the web app
393
574
 
394
575
  const webDist = options.webDist
395
576
  if (webDist != null && existsSync(join(webDist, 'index.html'))) {
396
577
  app.use(express.static(webDist, { index: false }))
397
- // The passport page lives at the identifier's own path, and every other path is the single-page app's. Its shell is read once, not per request.
578
+ // The passport page lives under /passport, at its identifier's path after it, and every other path is the single-page app's. Its shell is read once, not per request.
398
579
  const shell = readFileSync(join(webDist, 'index.html'), 'utf8')
399
580
  app.get('/{*splat}', (req, res, next) => {
400
581
  if (req.path.startsWith('/api/')) return next()
@@ -404,15 +585,27 @@ export function createServer(options: ServerOptions): express.Express {
404
585
 
405
586
  app.use((error: unknown, _req: Request, res: Response, _next: NextFunction) => {
406
587
  if (error instanceof HttpError) {
407
- res.status(error.status).json({ error: error.code, description: error.message })
588
+ res.status(error.status).json({ error: error.code, description: error.message, ...error.data })
408
589
  return
409
590
  }
410
591
  if (error instanceof WriteRefused) {
411
- res.status(error.code.endsWith('-unknown') ? 404 : 409).json({ error: error.code, description: error.message })
592
+ res.status(error.code.endsWith('-unknown') ? 404 : 409).json({ error: error.code, description: error.message, ...error.data })
593
+ return
594
+ }
595
+ // The package's own refusal of a retired profile, from a helper that checks or starts a payload.
596
+ if (error instanceof ProfileRetiredError) {
597
+ res.status(409).json({ error: error.code, description: error.message, replacedBy: error.replacedBy })
598
+ return
599
+ }
600
+ // A body the JSON parser refused. Its error quotes the body, and a body may hold restricted product data, so neither is logged or sent back.
601
+ const parser = error as { type?: unknown; status?: unknown }
602
+ if (typeof parser?.type === 'string' && parser.type.startsWith('entity.') && typeof parser.status === 'number') {
603
+ res.status(parser.status).json({ error: parser.type === 'entity.too.large' ? 'body-too-large' : 'body-not-json', description: parser.type === 'entity.too.large' ? 'the request body is larger than this API takes' : 'the request body is not JSON' })
412
604
  return
413
605
  }
414
606
  const description = error instanceof Error ? error.message : String(error)
415
- console.error('request failed:', error)
607
+ // The name and the stack only. An error object can carry the request body among its properties, and printing the object would print them.
608
+ console.error(`request failed: ${error instanceof Error ? (error.stack ?? `${error.name}: ${error.message}`) : description}`)
416
609
  res.status(500).json({ error: 'internal', description })
417
610
  })
418
611