@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.
- package/NOTICE +2 -0
- package/PATENTS +12 -0
- package/README.md +26 -6
- package/dist/index.js +36 -8
- package/package.json +9 -5
- package/template/Dockerfile +4 -2
- package/template/README.md +297 -42
- package/template/_env.example +82 -13
- package/template/_github/workflows/ci.yml +3 -3
- package/template/apps/api/API.md +86 -16
- package/template/apps/api/package.json +9 -4
- package/template/apps/api/src/bound-profiles.ts +590 -0
- package/template/apps/api/src/claims.ts +175 -56
- package/template/apps/api/src/cli.ts +64 -7
- package/template/apps/api/src/config.ts +124 -10
- package/template/apps/api/src/custody.ts +241 -69
- package/template/apps/api/src/dev-index.ts +58 -9
- package/template/apps/api/src/env-file.ts +55 -0
- package/template/apps/api/src/epcis/exchange.ts +434 -0
- package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
- package/template/apps/api/src/epcis/routes.ts +364 -0
- package/template/apps/api/src/epcis/sources.ts +142 -0
- package/template/apps/api/src/go-live.ts +226 -0
- package/template/apps/api/src/http-error.ts +15 -0
- package/template/apps/api/src/identifiers.ts +1 -1
- package/template/apps/api/src/index-client.ts +131 -6
- package/template/apps/api/src/index-projects.ts +53 -0
- package/template/apps/api/src/lifecycle-authority.ts +49 -0
- package/template/apps/api/src/lifecycle.ts +485 -0
- package/template/apps/api/src/main.ts +10 -2
- package/template/apps/api/src/parties.ts +2 -2
- package/template/apps/api/src/platform.ts +72 -17
- package/template/apps/api/src/portability/commands.ts +224 -0
- package/template/apps/api/src/portability/export.ts +708 -0
- package/template/apps/api/src/portability/package.ts +270 -0
- package/template/apps/api/src/portability/restore.ts +863 -0
- package/template/apps/api/src/profiles.ts +38 -13
- package/template/apps/api/src/reader.ts +172 -3
- package/template/apps/api/src/resolver.ts +159 -0
- package/template/apps/api/src/sector-examples.ts +390 -0
- package/template/apps/api/src/server.ts +253 -60
- package/template/apps/api/src/store.ts +198 -21
- package/template/apps/api/src/validation-engine.ts +172 -0
- package/template/apps/api/src/wallet.ts +30 -17
- package/template/apps/api/src/worker.ts +20 -13
- package/template/apps/api/src/writer.ts +383 -131
- package/template/apps/api/test/bound-http.test.ts +496 -0
- package/template/apps/api/test/bound-profiles.test.ts +547 -0
- package/template/apps/api/test/config.test.ts +148 -3
- package/template/apps/api/test/custody-journal.test.ts +415 -0
- package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
- package/template/apps/api/test/custom-profile.test.ts +167 -0
- package/template/apps/api/test/env-file.test.ts +53 -0
- package/template/apps/api/test/epcis-fixtures.ts +270 -0
- package/template/apps/api/test/epcis-http.test.ts +1179 -0
- package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
- package/template/apps/api/test/epcis-separation.test.ts +253 -0
- package/template/apps/api/test/epcis-web.test.ts +230 -0
- package/template/apps/api/test/exit-exercise.test.ts +1038 -0
- package/template/apps/api/test/external-index.test.ts +3 -2
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
- package/template/apps/api/test/go-live.test.ts +179 -0
- package/template/apps/api/test/gs1-global-setup.ts +33 -0
- package/template/apps/api/test/gs1-test-env.ts +5 -0
- package/template/apps/api/test/identifier-host.test.ts +256 -0
- package/template/apps/api/test/index-projects.test.ts +81 -0
- package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
- package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
- package/template/apps/api/test/lifecycle.test.ts +17 -6
- package/template/apps/api/test/manifest-notice.test.ts +36 -0
- package/template/apps/api/test/network-guard.ts +113 -0
- package/template/apps/api/test/portability.test.ts +655 -0
- package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
- package/template/apps/api/test/retired-profiles.test.ts +216 -0
- package/template/apps/api/test/sector-cutover.test.ts +95 -0
- package/template/apps/api/test/sector-forms.test.ts +420 -0
- package/template/apps/api/test/unjoined-index.test.ts +62 -0
- package/template/apps/api/test/validation-engine.test.ts +328 -0
- package/template/apps/api/test/wallet-monitor.test.ts +38 -0
- package/template/apps/api/test/writer-journal.test.ts +327 -0
- package/template/apps/api/vitest.config.ts +3 -0
- package/template/apps/web/src/app.tsx +8 -4
- package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
- package/template/apps/web/src/components/bound/field-view.tsx +237 -0
- package/template/apps/web/src/components/bound/pieces.tsx +169 -0
- package/template/apps/web/src/components/bound/readings.tsx +152 -0
- package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
- package/template/apps/web/src/components/claim-dialog.tsx +344 -0
- package/template/apps/web/src/components/epcis-events.tsx +119 -0
- package/template/apps/web/src/components/layout.tsx +17 -0
- package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
- package/template/apps/web/src/components/passport-form.tsx +2 -2
- package/template/apps/web/src/components/read-passport.tsx +4 -3
- package/template/apps/web/src/components/reading.tsx +32 -39
- package/template/apps/web/src/lib/api.ts +136 -26
- package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
- package/template/apps/web/src/lib/bound/display.ts +122 -0
- package/template/apps/web/src/lib/bound/fields.ts +128 -0
- package/template/apps/web/src/lib/bound/form-model.ts +521 -0
- package/template/apps/web/src/lib/bound/forms.ts +15 -0
- package/template/apps/web/src/lib/bound/identity.ts +48 -0
- package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
- package/template/apps/web/src/lib/bound/units.ts +37 -0
- package/template/apps/web/src/lib/epcis.ts +345 -0
- package/template/apps/web/src/lib/format.ts +27 -4
- package/template/apps/web/src/lib/lifecycle.ts +350 -0
- package/template/apps/web/src/pages/accept.tsx +8 -3
- package/template/apps/web/src/pages/events.tsx +388 -0
- package/template/apps/web/src/pages/new-passport.tsx +25 -2
- package/template/apps/web/src/pages/operations.tsx +22 -3
- package/template/apps/web/src/pages/passport.tsx +226 -162
- package/template/apps/web/src/pages/public-passport.tsx +50 -10
- package/template/apps/web/src/pages/wallet.tsx +1 -1
- package/template/apps/web/vite.config.ts +12 -4
- package/template/deploy/compose.yml +14 -2
- package/template/package.json +9 -3
|
@@ -1,23 +1,31 @@
|
|
|
1
|
-
// The HTTP surface. JSON under /api; the
|
|
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 {
|
|
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 {
|
|
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 {
|
|
18
|
-
import
|
|
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
|
-
|
|
36
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
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(
|
|
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
|
-
|
|
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
|
|
214
|
-
|
|
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
|
-
|
|
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
|
-
|
|
270
|
-
|
|
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
|
|
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/
|
|
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
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
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
|
-
|
|
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
|
|
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
|
-
|
|
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
|
|