@bsv/create-dpp-app 0.0.0-stage → 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 (178) hide show
  1. package/LICENSE +203 -0
  2. package/NOTICE +2 -0
  3. package/PATENTS +12 -0
  4. package/README.md +93 -2
  5. package/dist/index.js +125 -0
  6. package/package.json +57 -4
  7. package/template/Dockerfile +37 -0
  8. package/template/README.md +389 -0
  9. package/template/_dockerignore +6 -0
  10. package/template/_env.example +122 -0
  11. package/template/_github/workflows/ci.yml +23 -0
  12. package/template/_gitignore +8 -0
  13. package/template/_prettierrc +6 -0
  14. package/template/apps/api/API.md +119 -0
  15. package/template/apps/api/package.json +39 -0
  16. package/template/apps/api/src/auth.ts +55 -0
  17. package/template/apps/api/src/bound-profiles.ts +590 -0
  18. package/template/apps/api/src/claims.ts +204 -0
  19. package/template/apps/api/src/cli.ts +99 -0
  20. package/template/apps/api/src/config.ts +180 -0
  21. package/template/apps/api/src/custody.ts +358 -0
  22. package/template/apps/api/src/dev-index.ts +120 -0
  23. package/template/apps/api/src/env-file.ts +55 -0
  24. package/template/apps/api/src/env.ts +14 -0
  25. package/template/apps/api/src/epcis/exchange.ts +434 -0
  26. package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
  27. package/template/apps/api/src/epcis/routes.ts +364 -0
  28. package/template/apps/api/src/epcis/sources.ts +142 -0
  29. package/template/apps/api/src/go-live.ts +226 -0
  30. package/template/apps/api/src/http-error.ts +15 -0
  31. package/template/apps/api/src/identifiers.ts +57 -0
  32. package/template/apps/api/src/index-client.ts +261 -0
  33. package/template/apps/api/src/index-projects.ts +53 -0
  34. package/template/apps/api/src/lifecycle-authority.ts +49 -0
  35. package/template/apps/api/src/lifecycle.ts +485 -0
  36. package/template/apps/api/src/main.ts +58 -0
  37. package/template/apps/api/src/parties.ts +68 -0
  38. package/template/apps/api/src/platform.ts +176 -0
  39. package/template/apps/api/src/portability/commands.ts +224 -0
  40. package/template/apps/api/src/portability/export.ts +708 -0
  41. package/template/apps/api/src/portability/package.ts +270 -0
  42. package/template/apps/api/src/portability/restore.ts +863 -0
  43. package/template/apps/api/src/profiles.ts +125 -0
  44. package/template/apps/api/src/reader.ts +265 -0
  45. package/template/apps/api/src/resolver.ts +159 -0
  46. package/template/apps/api/src/sector-examples.ts +390 -0
  47. package/template/apps/api/src/server.ts +613 -0
  48. package/template/apps/api/src/store.ts +426 -0
  49. package/template/apps/api/src/validation-engine.ts +172 -0
  50. package/template/apps/api/src/wallet.ts +359 -0
  51. package/template/apps/api/src/worker.ts +113 -0
  52. package/template/apps/api/src/writer.ts +603 -0
  53. package/template/apps/api/test/bound-http.test.ts +496 -0
  54. package/template/apps/api/test/bound-profiles.test.ts +547 -0
  55. package/template/apps/api/test/config.test.ts +160 -0
  56. package/template/apps/api/test/custody-journal.test.ts +415 -0
  57. package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
  58. package/template/apps/api/test/custom-profile.test.ts +167 -0
  59. package/template/apps/api/test/env-file.test.ts +53 -0
  60. package/template/apps/api/test/epcis-fixtures.ts +270 -0
  61. package/template/apps/api/test/epcis-http.test.ts +1179 -0
  62. package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
  63. package/template/apps/api/test/epcis-separation.test.ts +253 -0
  64. package/template/apps/api/test/epcis-web.test.ts +230 -0
  65. package/template/apps/api/test/exit-exercise.test.ts +1038 -0
  66. package/template/apps/api/test/external-index.test.ts +32 -0
  67. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
  68. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
  69. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
  70. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
  71. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
  72. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
  73. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
  74. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
  75. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
  76. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
  77. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
  78. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
  79. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
  80. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
  81. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
  82. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
  83. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
  84. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
  85. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
  86. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
  87. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
  88. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
  89. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
  90. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
  91. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
  92. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
  93. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
  94. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
  95. package/template/apps/api/test/go-live.test.ts +179 -0
  96. package/template/apps/api/test/gs1-global-setup.ts +33 -0
  97. package/template/apps/api/test/gs1-test-env.ts +5 -0
  98. package/template/apps/api/test/identifier-host.test.ts +256 -0
  99. package/template/apps/api/test/index-projects.test.ts +81 -0
  100. package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
  101. package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
  102. package/template/apps/api/test/lifecycle.test.ts +147 -0
  103. package/template/apps/api/test/manifest-notice.test.ts +36 -0
  104. package/template/apps/api/test/network-guard.ts +113 -0
  105. package/template/apps/api/test/portability.test.ts +655 -0
  106. package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
  107. package/template/apps/api/test/retired-profiles.test.ts +216 -0
  108. package/template/apps/api/test/sector-cutover.test.ts +95 -0
  109. package/template/apps/api/test/sector-forms.test.ts +420 -0
  110. package/template/apps/api/test/unjoined-index.test.ts +62 -0
  111. package/template/apps/api/test/validation-engine.test.ts +328 -0
  112. package/template/apps/api/test/wallet-monitor.test.ts +38 -0
  113. package/template/apps/api/test/writer-journal.test.ts +327 -0
  114. package/template/apps/api/tsconfig.json +9 -0
  115. package/template/apps/api/vitest.config.ts +12 -0
  116. package/template/apps/web/components.json +21 -0
  117. package/template/apps/web/index.html +12 -0
  118. package/template/apps/web/package.json +33 -0
  119. package/template/apps/web/src/app.tsx +55 -0
  120. package/template/apps/web/src/components/bits.tsx +188 -0
  121. package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
  122. package/template/apps/web/src/components/bound/field-view.tsx +237 -0
  123. package/template/apps/web/src/components/bound/pieces.tsx +169 -0
  124. package/template/apps/web/src/components/bound/readings.tsx +152 -0
  125. package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
  126. package/template/apps/web/src/components/claim-dialog.tsx +344 -0
  127. package/template/apps/web/src/components/epcis-events.tsx +119 -0
  128. package/template/apps/web/src/components/layout.tsx +135 -0
  129. package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
  130. package/template/apps/web/src/components/passport-form.tsx +244 -0
  131. package/template/apps/web/src/components/read-passport.tsx +49 -0
  132. package/template/apps/web/src/components/reading.tsx +150 -0
  133. package/template/apps/web/src/components/ui/alert.tsx +65 -0
  134. package/template/apps/web/src/components/ui/badge.tsx +47 -0
  135. package/template/apps/web/src/components/ui/button.tsx +63 -0
  136. package/template/apps/web/src/components/ui/card.tsx +91 -0
  137. package/template/apps/web/src/components/ui/dialog.tsx +156 -0
  138. package/template/apps/web/src/components/ui/input.tsx +20 -0
  139. package/template/apps/web/src/components/ui/label.tsx +21 -0
  140. package/template/apps/web/src/components/ui/select.tsx +189 -0
  141. package/template/apps/web/src/components/ui/separator.tsx +25 -0
  142. package/template/apps/web/src/components/ui/table.tsx +115 -0
  143. package/template/apps/web/src/components/ui/tabs.tsx +90 -0
  144. package/template/apps/web/src/components/ui/textarea.tsx +17 -0
  145. package/template/apps/web/src/index.css +81 -0
  146. package/template/apps/web/src/lib/api.ts +396 -0
  147. package/template/apps/web/src/lib/auth.ts +10 -0
  148. package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
  149. package/template/apps/web/src/lib/bound/display.ts +122 -0
  150. package/template/apps/web/src/lib/bound/fields.ts +128 -0
  151. package/template/apps/web/src/lib/bound/form-model.ts +521 -0
  152. package/template/apps/web/src/lib/bound/forms.ts +15 -0
  153. package/template/apps/web/src/lib/bound/identity.ts +48 -0
  154. package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
  155. package/template/apps/web/src/lib/bound/units.ts +37 -0
  156. package/template/apps/web/src/lib/epcis.ts +345 -0
  157. package/template/apps/web/src/lib/format.ts +87 -0
  158. package/template/apps/web/src/lib/lifecycle.ts +350 -0
  159. package/template/apps/web/src/lib/session.tsx +92 -0
  160. package/template/apps/web/src/lib/use-load.ts +46 -0
  161. package/template/apps/web/src/main.tsx +18 -0
  162. package/template/apps/web/src/pages/accept.tsx +113 -0
  163. package/template/apps/web/src/pages/brand.tsx +94 -0
  164. package/template/apps/web/src/pages/brands.tsx +104 -0
  165. package/template/apps/web/src/pages/events.tsx +388 -0
  166. package/template/apps/web/src/pages/home.tsx +51 -0
  167. package/template/apps/web/src/pages/new-passport.tsx +137 -0
  168. package/template/apps/web/src/pages/operations.tsx +169 -0
  169. package/template/apps/web/src/pages/passport.tsx +632 -0
  170. package/template/apps/web/src/pages/public-passport.tsx +64 -0
  171. package/template/apps/web/src/pages/sign-in.tsx +93 -0
  172. package/template/apps/web/src/pages/verify.tsx +30 -0
  173. package/template/apps/web/src/pages/wallet.tsx +141 -0
  174. package/template/apps/web/tsconfig.json +29 -0
  175. package/template/apps/web/vite.config.ts +23 -0
  176. package/template/deploy/compose.yml +38 -0
  177. package/template/package.json +48 -0
  178. package/template/tsconfig.base.json +13 -0
@@ -0,0 +1,613 @@
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
3
+ // pages under everything else. Reads are open: anyone may verify a passport.
4
+ // Writes need a signed-in member of the brand that holds the passport, or,
5
+ // for a recipient under managed custody, the claim code they accepted with.
6
+ import { existsSync, readFileSync } from 'node:fs'
7
+ import { join } from 'node:path'
8
+ import { Hash, Utils } from '@bsv/sdk'
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'
11
+ import express, { type NextFunction, type Request, type Response } from 'express'
12
+ import { fromNodeHeaders, toNodeHandler } from 'better-auth/node'
13
+ import { sessionFrom, type Auth, type Session } from './auth.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'
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'
22
+ import type { Party } from './parties.js'
23
+ import type { Platform } from './platform.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'
27
+ import { pendingDuties, runDuties, summariseJournal } from './worker.js'
28
+ import { WriteRefused, refuseRetiredProfile, requireIssuableProfile } from './writer.js'
29
+
30
+ export interface ServerOptions {
31
+ platform: Platform
32
+ auth?: Auth
33
+ /**
34
+ * Without sign-in (no MongoDB), every request is this developer, a member of
35
+ * one development brand. Never set in production: it is what makes
36
+ * `npm run dev` work with no services, and nothing else.
37
+ */
38
+ devSession?: Session
39
+ /** The built web app to serve, when it exists. */
40
+ webDist?: string
41
+ /** The EPCIS exchange, opened and recovered. Without it the /api/epcis routes are not served. */
42
+ exchange?: EpcisExchange
43
+ }
44
+
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)
47
+
48
+ const sha256hex = (text: string): string => Utils.toHex(Hash.sha256(Utils.toArray(text, 'utf8')))
49
+ /** A URL-safe slug from a name: lower-case letters and digits with single hyphens, at most 64 characters, built without backtracking. */
50
+ function slugOf(name: string): string {
51
+ let slug = ''
52
+ let hyphen = false
53
+ for (const char of name.toLowerCase().slice(0, 128)) {
54
+ if (/[a-z0-9]/.test(char)) {
55
+ slug += char
56
+ hyphen = false
57
+ } else if (slug.length > 0 && !hyphen) {
58
+ slug += '-'
59
+ hyphen = true
60
+ }
61
+ if (slug.length >= 64) break
62
+ }
63
+ return slug.endsWith('-') ? slug.slice(0, -1) : slug
64
+ }
65
+ /** A route parameter as one string; Express 5 types it as possibly several. */
66
+ const param = (req: Request, name: string): string => {
67
+ const value = req.params[name]
68
+ return Array.isArray(value) ? value[0] : value
69
+ }
70
+
71
+ /** What a passport looks like over the API: the journal without the owner-tier ciphertext. */
72
+ function publicView(record: PassportRecord, policyIsDemo: boolean) {
73
+ const tip = record.states.filter((state) => state.network === 'accepted' || state.network === 'dry-run').at(-1)
74
+ const journal = summariseJournal(record)
75
+ let payload: unknown = tip?.payloadPublic
76
+ try {
77
+ payload = tip == null ? undefined : JSON.parse(tip.payloadPublic)
78
+ } catch {
79
+ // Left as the string it is.
80
+ }
81
+ return {
82
+ passportId: record.passportId,
83
+ brandId: record.brandId,
84
+ profile: record.profile,
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,
88
+ demonstration: policyIsDemo,
89
+ holder: record.holder,
90
+ createdAt: record.createdAt,
91
+ payload,
92
+ journal,
93
+ states: record.states.map((s: StateEntry) => ({
94
+ op: s.op,
95
+ txid: s.txid,
96
+ timestamp: s.timestamp,
97
+ actor: s.actor,
98
+ index: s.index,
99
+ refusal: s.refusal,
100
+ network: s.network,
101
+ proven: s.proof != null,
102
+ proofPushed: s.proofPushed === true,
103
+ blockHeight: s.proof?.blockHeight,
104
+ })),
105
+ acceptanceRecords: record.acceptanceRecords,
106
+ }
107
+ }
108
+
109
+ export function createServer(options: ServerOptions): express.Express {
110
+ const { platform, auth } = options
111
+ const { store, parties, writer, custody, claims, config } = platform
112
+ const policy = { host: config.passportHost, prefix: config.gs1Prefix }
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
+ }
124
+ const app = express()
125
+ app.disable('x-powered-by')
126
+
127
+ // Better Auth owns /api/auth; it must see the raw body, so it is mounted before the JSON parser.
128
+ if (auth != null) app.all('/api/auth/{*splat}', toNodeHandler(auth))
129
+
130
+ const session = async (req: Request): Promise<Session | undefined> => (auth == null ? options.devSession : await sessionFrom(auth, req.headers))
131
+ const requireSession = async (req: Request): Promise<Session> => {
132
+ const s = await session(req)
133
+ if (s == null) throw new HttpError(401, 'sign-in-required', 'sign in first')
134
+ return s
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
+ }
146
+ const requireMember = async (req: Request, brandId: string): Promise<Session> => {
147
+ const s = await requireSession(req)
148
+ if (!s.brandIds.includes(brandId)) throw new HttpError(403, 'not-a-member', `you are not a member of brand ${brandId}`)
149
+ return s
150
+ }
151
+ const passportFrom = async (ref: string): Promise<PassportRecord> => {
152
+ const passportId = decodeURIComponent(ref)
153
+ const record = await store.getPassport(passportId)
154
+ if (record == null) throw new HttpError(404, 'passport-unknown', `no passport ${passportId} in this platform's journal`)
155
+ return record
156
+ }
157
+ /**
158
+ * Who may act on a held passport: a member of the brand while the brand
159
+ * holds it; the recipient, with the claim code they accepted with, once a
160
+ * hand-on moved control to them.
161
+ */
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)
166
+ if (scope === 'brand') {
167
+ await requireMember(req, record.brandId)
168
+ return parties.brand(id)
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
+ }
175
+ if (scope === 'recipient') {
176
+ const claimCode = typeof req.body?.claimCode === 'string' ? req.body.claimCode : undefined
177
+ const offer = await store.getOffer(id)
178
+ if (claimCode == null || offer?.claimCodeHash == null || sha256hex(claimCode) !== offer.claimCodeHash) throw new HttpError(403, 'claim-code-required', 'the holder acts with the claim code they accepted with')
179
+ return parties.recipient(id)
180
+ }
181
+ throw new HttpError(409, 'holder-unknown', `the holder ${record.holder.party} is not one this platform acts for`)
182
+ }
183
+
184
+ // ------------------------------------------------------------------ open reads
185
+
186
+ app.get(
187
+ '/api/health',
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
+ })
207
+ )
208
+
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
+ )
216
+ app.get(
217
+ '/api/profiles/:id',
218
+ wrap(async (req) => {
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))
229
+ if (!isProfileId(id)) throw new HttpError(404, 'profile-unknown', `${id} is not a profile this platform knows`)
230
+ const manifest = manifestFor(id)
231
+ return {
232
+ id,
233
+ format: 'manifest',
234
+ title: manifest.title,
235
+ description: manifest.description,
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 })),
237
+ publicSchema: readPublicPayloadSchema(id),
238
+ restrictedSchema: readRestrictedPayloadSchema(id),
239
+ ...(() => {
240
+ const { payload, problems } = sampleWithProblems(id, demo)
241
+ return { sample: payload, sampleProblems: problems }
242
+ })(),
243
+ }
244
+ })
245
+ )
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
+
258
+ app.get(
259
+ '/api/verify',
260
+ wrap(async (req) => {
261
+ const passportId = typeof req.query.passportId === 'string' ? req.query.passportId : undefined
262
+ if (passportId == null) throw new HttpError(400, 'passport-id-required', 'give passportId')
263
+ try {
264
+ return await platform.read(passportId)
265
+ } catch (cause) {
266
+ throw new HttpError(404, 'not-found', cause instanceof Error ? cause.message : String(cause))
267
+ }
268
+ })
269
+ )
270
+
271
+ app.get('/api/passports/:ref', wrap(async (req) => publicView(await passportFrom(param(req, 'ref')), demo)))
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
+ )
284
+
285
+ app.get('/api/offers/:requestId', wrap(async (req) => await custody.preview(param(req, 'requestId'))))
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
+ }))
294
+
295
+ // ------------------------------------------------------------------ signed in
296
+
297
+ app.get(
298
+ '/api/me',
299
+ wrap(async (req) => {
300
+ const s = await requireSession(req)
301
+ return { ...s, brands: await store.listBrands(s.brandIds) }
302
+ })
303
+ )
304
+
305
+ app.get('/api/brands', wrap(async (req) => await store.listBrands((await requireSession(req)).brandIds)))
306
+ app.post(
307
+ '/api/brands',
308
+ wrap(async (req) => {
309
+ const s = await requireSession(req)
310
+ const name = typeof req.body?.name === 'string' ? req.body.name.trim().slice(0, 128) : ''
311
+ if (name === '') throw new HttpError(400, 'name-required', 'a brand needs a name')
312
+ let id: string
313
+ if (auth == null) {
314
+ // Development without sign-in: one brand per name, owned by the development session.
315
+ id = `dev-${slugOf(name)}`
316
+ if (!s.brandIds.includes(id)) s.brandIds.push(id)
317
+ } else {
318
+ const slug = `${slugOf(name)}-${Date.now().toString(36)}`
319
+ const organisation = await auth.api.createOrganization({ body: { name, slug }, headers: fromNodeHeaders(req.headers) })
320
+ if (organisation == null) throw new HttpError(500, 'brand-not-created', 'the organisation was not created')
321
+ id = organisation.id
322
+ }
323
+ const party = parties.brand(id)
324
+ const brand = { id, name, identityKey: party.identityKey, did: party.did, createdAt: new Date().toISOString() }
325
+ await store.saveBrand(brand)
326
+ return brand
327
+ })
328
+ )
329
+
330
+ app.get(
331
+ '/api/brands/:brandId/passports',
332
+ wrap(async (req) => {
333
+ await requireMember(req, param(req, 'brandId'))
334
+ return (await store.listPassports({ brandId: param(req, 'brandId') })).map((p) => publicView(p, demo))
335
+ })
336
+ )
337
+
338
+ app.post(
339
+ '/api/brands/:brandId/passports',
340
+ wrap(async (req) => {
341
+ const brandId = param(req, 'brandId')
342
+ await requireMember(req, brandId)
343
+ const brandRecord = await store.getBrand(brandId)
344
+ if (brandRecord == null) throw new HttpError(404, 'brand-unknown', `no brand ${brandId}`)
345
+ const { profile, itemReference, serial, payload, ownerFields } = req.body ?? {}
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`)
349
+ if (typeof itemReference !== 'string' || typeof serial !== 'string') throw new HttpError(400, 'identifier-required', 'give itemReference (digits) and serial')
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 ?? {} })
363
+ return publicView(outcome.record, demo)
364
+ })
365
+ )
366
+
367
+ app.post(
368
+ '/api/passports/:ref/update',
369
+ wrap(async (req) => {
370
+ const record = await passportFrom(param(req, 'ref'))
371
+ const actor = await actorFor(req, record)
372
+ // ownerFields absent carries the current owner tier unchanged; {} seals an empty one.
373
+ const ownerFields = typeof req.body?.ownerFields === 'object' && req.body.ownerFields != null ? req.body.ownerFields : undefined
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 })
377
+ return publicView(outcome.record, demo)
378
+ })
379
+ )
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.
382
+ app.post(
383
+ '/api/passports/:ref/authorised-view',
384
+ wrap(async (req) => {
385
+ const record = await passportFrom(param(req, 'ref'))
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'))
396
+ const terms = typeof req.body?.terms === 'object' && req.body.terms != null ? req.body.terms : { word: 'Handed on' }
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 })
398
+ })
399
+ )
400
+
401
+ app.post(
402
+ '/api/offers/:requestId/withdraw',
403
+ wrap(async (req) => {
404
+ const offer = await store.getOffer(param(req, 'requestId'))
405
+ if (offer == null) throw new HttpError(404, 'offer-unknown', `no offer ${param(req, 'requestId')}`)
406
+ const record = await passportFrom(encodeURIComponent(offer.passportId))
407
+ const holder = await actorFor(req, record, offerHolderName(record, offer))
408
+ return await custody.withdraw(param(req, 'requestId'), holder)
409
+ })
410
+ )
411
+
412
+ app.get(
413
+ '/api/passports/:ref/offers',
414
+ wrap(async (req) => {
415
+ const record = await passportFrom(param(req, 'ref'))
416
+ await requireMember(req, record.brandId)
417
+ return (await store.listOffers({ passportId: record.passportId })).map(({ claimCodeHash: _hidden, ...offer }) => offer)
418
+ })
419
+ )
420
+
421
+ app.post(
422
+ '/api/passports/:ref/retire',
423
+ wrap(async (req) => {
424
+ const record = await passportFrom(param(req, 'ref'))
425
+ const actor = await actorFor(req, record)
426
+ const reason = typeof req.body?.reason === 'string' ? req.body.reason : 'retired'
427
+ const outcome = await writer.retire({ record, actor, reason })
428
+ return publicView(outcome.record, demo)
429
+ })
430
+ )
431
+
432
+ app.post(
433
+ '/api/passports/:ref/states/:txid/resolve',
434
+ wrap(async (req) => {
435
+ const record = await passportFrom(param(req, 'ref'))
436
+ await requireMember(req, record.brandId)
437
+ const outcome = req.body?.outcome
438
+ if (outcome !== 'sent' && outcome !== 'abandoned') throw new HttpError(400, 'outcome-required', "outcome must be 'sent' or 'abandoned'")
439
+ return publicView(await writer.resolveInterrupted(record, param(req, 'txid'), outcome), demo)
440
+ })
441
+ )
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
+ */
450
+ app.post(
451
+ '/api/passports/:ref/claims',
452
+ wrap(async (req) => {
453
+ const s = await requireSession(req)
454
+ const record = await passportFrom(param(req, 'ref'))
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 })
517
+ })
518
+ )
519
+
520
+ app.get(
521
+ '/api/operations',
522
+ wrap(async (req) => {
523
+ await requireSession(req)
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
+ }
534
+ })
535
+ )
536
+ app.post(
537
+ '/api/operations/run',
538
+ wrap(async (req) => {
539
+ await requireSession(req)
540
+ return { done: await runDuties({ store, index: platform.index, writer }) }
541
+ })
542
+ )
543
+
544
+ app.get(
545
+ '/api/wallet',
546
+ wrap(async (req) => {
547
+ await requireSession(req)
548
+ return { kind: platform.wallet.kind, network: config.network, identityKey: platform.wallet.identityKey, balance: await platform.wallet.balance(), livePublishing: config.livePublishing }
549
+ })
550
+ )
551
+ app.post(
552
+ '/api/wallet/funding-address',
553
+ wrap(async (req) => {
554
+ await requireSession(req)
555
+ return await platform.wallet.fundingAddress()
556
+ })
557
+ )
558
+ app.post(
559
+ '/api/wallet/internalize',
560
+ wrap(async (req) => {
561
+ await requireSession(req)
562
+ const { txid, funding } = req.body ?? {}
563
+ if (typeof txid !== 'string' || typeof funding !== 'object') throw new HttpError(400, 'funding-required', 'give the txid and the funding address record it paid')
564
+ return await platform.wallet.internalize(funding, txid)
565
+ })
566
+ )
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
+
573
+ // ------------------------------------------------------------------ the web app
574
+
575
+ const webDist = options.webDist
576
+ if (webDist != null && existsSync(join(webDist, 'index.html'))) {
577
+ app.use(express.static(webDist, { index: false }))
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.
579
+ const shell = readFileSync(join(webDist, 'index.html'), 'utf8')
580
+ app.get('/{*splat}', (req, res, next) => {
581
+ if (req.path.startsWith('/api/')) return next()
582
+ res.type('html').send(shell)
583
+ })
584
+ }
585
+
586
+ app.use((error: unknown, _req: Request, res: Response, _next: NextFunction) => {
587
+ if (error instanceof HttpError) {
588
+ res.status(error.status).json({ error: error.code, description: error.message, ...error.data })
589
+ return
590
+ }
591
+ if (error instanceof WriteRefused) {
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' })
604
+ return
605
+ }
606
+ const description = error instanceof Error ? error.message : String(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}`)
609
+ res.status(500).json({ error: 'internal', description })
610
+ })
611
+
612
+ return app
613
+ }