@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
|
@@ -0,0 +1,364 @@
|
|
|
1
|
+
// The EPCIS exchange over HTTP, under /api/epcis. Every route needs a
|
|
2
|
+
// signed-in user. Every route calls the exchange (exchange.ts), which calls
|
|
3
|
+
// the module, and none does the module's work again.
|
|
4
|
+
//
|
|
5
|
+
// With sign-in on, the signed-in user is looked up in the application's
|
|
6
|
+
// database, which by default also holds the EPCIS store, and the lookup comes
|
|
7
|
+
// first. A database that does not answer therefore fails the lookup before a
|
|
8
|
+
// route reaches its store, and that failure is named here as well.
|
|
9
|
+
//
|
|
10
|
+
// These routes are mounted before the application's JSON parser, because an
|
|
11
|
+
// import takes its body as the exact bytes that arrived: they are digested,
|
|
12
|
+
// retained and exported as they are, and are never parsed here or written
|
|
13
|
+
// out again from a parsed form. The routes that do take JSON parse it
|
|
14
|
+
// themselves.
|
|
15
|
+
//
|
|
16
|
+
// Nothing here reaches the wallet, the writer or the index. An import or a
|
|
17
|
+
// pull retains data and changes no passport.
|
|
18
|
+
import { EpcisExchangeError, EpcisStorageError } from '@bsv/dpp-credentials/epcis-exchange'
|
|
19
|
+
import { EPCIS_DEFAULT_LIMITS } from '@bsv/dpp-credentials/epcis-source'
|
|
20
|
+
import express, { Router, type NextFunction, type Request, type Response } from 'express'
|
|
21
|
+
import type { Session } from '../auth.js'
|
|
22
|
+
import { HttpError } from '../http-error.js'
|
|
23
|
+
import { EPCIS_UPLOAD_SOURCE, EpcisStoreFailure, type EpcisExchange } from './exchange.js'
|
|
24
|
+
import { describeEpcisSource } from './sources.js'
|
|
25
|
+
|
|
26
|
+
export interface EpcisRoutesOptions {
|
|
27
|
+
exchange: EpcisExchange
|
|
28
|
+
/** The signed-in user behind a request. It throws the application's own 401 when there is none. */
|
|
29
|
+
requireSession: (req: Request) => Promise<Session>
|
|
30
|
+
/** Where a failure of the sign-in lookup is written for the operator. The process's error output when none is given. */
|
|
31
|
+
log?: (line: string) => void
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* The signed-in user could not be looked up: the lookup threw something
|
|
36
|
+
* other than the application's own 401, which with sign-in on means the
|
|
37
|
+
* database it is kept in did not answer. `cause` is the lookup's own error,
|
|
38
|
+
* which is logged and never sent to a caller: it can name the database's host.
|
|
39
|
+
*/
|
|
40
|
+
class SignInUnavailable extends Error {
|
|
41
|
+
constructor(cause: unknown) {
|
|
42
|
+
super('the signed-in user could not be looked up', { cause })
|
|
43
|
+
this.name = 'SignInUnavailable'
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/** The status each refusal of a transport is answered with. Anything not named is 422: the bytes arrived and cannot be read as an EPCIS document. */
|
|
48
|
+
const REFUSAL_STATUS: Record<string, number> = {
|
|
49
|
+
'unsupported-media-type': 415,
|
|
50
|
+
oversized: 413,
|
|
51
|
+
'invalid-request': 400,
|
|
52
|
+
'gs1-artefact-unavailable': 503,
|
|
53
|
+
'credentials-unavailable': 503,
|
|
54
|
+
'pull-conflict': 409,
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* A store may hold less in one record than the module can make of a document.
|
|
59
|
+
* The MongoDB store refuses such a record before it writes anything of it,
|
|
60
|
+
* and that refusal is answered as one, not as a failure of the API.
|
|
61
|
+
*/
|
|
62
|
+
async function withinStore<T>(what: string, run: () => Promise<T>): Promise<T> {
|
|
63
|
+
try {
|
|
64
|
+
return await run()
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (error instanceof EpcisStorageError && error.code === 'invalid-value') throw new HttpError(413, 'record-too-large', `${what}: the record of what it holds is larger than this store keeps as one record. There is no import of it.`, { outcome: 'refused', kept: false })
|
|
67
|
+
throw error
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const isPull = (req: Request): boolean => req.method === 'POST' && req.path.endsWith('/pulls')
|
|
72
|
+
|
|
73
|
+
/** What a caller does after a store failure, by what it had asked for. */
|
|
74
|
+
function afterStoreFailure(req: Request): string {
|
|
75
|
+
if (req.method === 'POST' && req.path === '/imports') return 'This upload was not acknowledged. Send it again with the same requestId: it is answered as one import, never a second.'
|
|
76
|
+
if (isPull(req)) return 'This run did not finish. The pages it acknowledged before the failure are kept. Run the same queryId again: it continues after the last page it acknowledged, and no page is kept twice.'
|
|
77
|
+
if (req.method === 'POST') return 'This request was not acknowledged. Send the same request again: it is recorded once.'
|
|
78
|
+
return 'Nothing was changed. Ask again.'
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
/**
|
|
82
|
+
* The answer to a failure of the store, or to a store that holds something
|
|
83
|
+
* it should not, by name. Undefined for any other error, which is not this
|
|
84
|
+
* file's to name. `retryable` says whether the same request may simply be
|
|
85
|
+
* sent again. The store's own error is never part of the answer.
|
|
86
|
+
*/
|
|
87
|
+
function storeFailureAnswer(error: unknown, req: Request): { status: number; body: Record<string, unknown> } | undefined {
|
|
88
|
+
// A pull acknowledges page by page, so a run that failed may have acknowledged some of its pages before it stopped. `acknowledged` is not said of it: the pull record says how far it got.
|
|
89
|
+
const unavailable = (code: string, what: string): { status: number; body: Record<string, unknown> } => ({ status: 503, body: { error: code, description: `${what} ${afterStoreFailure(req)}`, outcome: 'failed', retryable: true, ...(isPull(req) ? {} : { acknowledged: false }) } })
|
|
90
|
+
if (error instanceof SignInUnavailable) return unavailable('sign-in-unavailable', 'The signed-in user could not be looked up: the database sign-in is kept in did not answer, and nothing of this request reached the EPCIS store.')
|
|
91
|
+
if (error instanceof EpcisStoreFailure) return unavailable('storage-unavailable', 'The store that holds EPCIS imports did not complete a call.')
|
|
92
|
+
if (error instanceof EpcisStorageError && (error.code === 'closed' || error.code === 'locked')) return unavailable('storage-unavailable', 'The store that holds EPCIS imports is not open to this process.')
|
|
93
|
+
if (error instanceof EpcisExchangeError && error.code === 'storage-contention') return unavailable('storage-contention', 'Another writer kept changing the same records, and this process gave up after a bounded number of attempts.')
|
|
94
|
+
// What follows is not a passing failure: the store holds something other than what was recorded. Sending the request again will not help.
|
|
95
|
+
const damaged = (code: string): { status: number; body: Record<string, unknown> } => ({ status: 500, body: { error: code, description: 'The store holds something other than what was recorded for this request, and nothing was answered from it. Nothing was changed. This needs the operator: restore the store from a recovery export.', outcome: 'failed', retryable: false } })
|
|
96
|
+
if (error instanceof EpcisStorageError && error.code === 'corrupt') return damaged('storage-corrupt')
|
|
97
|
+
// A record this version does not read may be sound: written by another version of the module, which is then the one to run.
|
|
98
|
+
if (error instanceof EpcisExchangeError && error.code === 'record-unreadable') return { status: 500, body: { error: error.code, description: 'The store holds a record this version of the application does not read: it was written by another version, or it is damaged, and nothing was answered from it. Nothing was changed. This needs the operator: run the version that wrote it, or restore the store from a recovery export made by this version.', outcome: 'failed', retryable: false } }
|
|
99
|
+
if (error instanceof EpcisExchangeError) return damaged(error.code)
|
|
100
|
+
return undefined
|
|
101
|
+
}
|
|
102
|
+
|
|
103
|
+
const one = (value: unknown): string | undefined => (typeof value === 'string' && value !== '' ? value : undefined)
|
|
104
|
+
const param = (req: Request, name: string): string => {
|
|
105
|
+
const value = req.params[name]
|
|
106
|
+
return Array.isArray(value) ? value[0]! : value!
|
|
107
|
+
}
|
|
108
|
+
const objectOf = (value: unknown): Record<string, unknown> => (typeof value === 'object' && value !== null && !Array.isArray(value) ? (value as Record<string, unknown>) : {})
|
|
109
|
+
|
|
110
|
+
export function epcisRoutes(options: EpcisRoutesOptions): Router {
|
|
111
|
+
const { exchange, requireSession } = options
|
|
112
|
+
const log = options.log ?? ((line: string) => console.error(line))
|
|
113
|
+
// The application's own 401 passes as it is. Anything else the lookup throws is named, and its words go to the log only.
|
|
114
|
+
const signedIn = async (req: Request): Promise<Session> => {
|
|
115
|
+
try {
|
|
116
|
+
return await requireSession(req)
|
|
117
|
+
} catch (error) {
|
|
118
|
+
if (error instanceof HttpError) throw error
|
|
119
|
+
log(`EPCIS route: the signed-in user could not be looked up (${error instanceof Error ? `${error.name}: ${error.message}` : String(error)}).`)
|
|
120
|
+
throw new SignInUnavailable(error)
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
const router = Router()
|
|
124
|
+
const wrap = (handler: (req: Request, res: Response) => Promise<unknown>) => (req: Request, res: Response, next: NextFunction) => {
|
|
125
|
+
handler(req, res).then((body) => {
|
|
126
|
+
if (!res.headersSent) res.json(body)
|
|
127
|
+
}, next)
|
|
128
|
+
}
|
|
129
|
+
// The module refuses a document past its limit with its own words. The parser's limit sits just above it, so only a body far past the limit is cut off unread.
|
|
130
|
+
const exactBytes = express.raw({ type: () => true, limit: EPCIS_DEFAULT_LIMITS.maxDocumentBytes + 1024, inflate: false })
|
|
131
|
+
const json = express.json({ limit: '256kb' })
|
|
132
|
+
|
|
133
|
+
router.get(
|
|
134
|
+
'/status',
|
|
135
|
+
wrap(async (req) => {
|
|
136
|
+
await signedIn(req)
|
|
137
|
+
return exchange.status()
|
|
138
|
+
})
|
|
139
|
+
)
|
|
140
|
+
|
|
141
|
+
router.get(
|
|
142
|
+
'/sources',
|
|
143
|
+
wrap(async (req) => {
|
|
144
|
+
await signedIn(req)
|
|
145
|
+
// What a source is, and whether a credential is set for it. Never the credential.
|
|
146
|
+
return exchange.sources.map(describeEpcisSource)
|
|
147
|
+
})
|
|
148
|
+
)
|
|
149
|
+
|
|
150
|
+
// ------------------------------------------------------------------ imports
|
|
151
|
+
|
|
152
|
+
router.post(
|
|
153
|
+
'/imports',
|
|
154
|
+
exactBytes,
|
|
155
|
+
wrap(async (req, res) => {
|
|
156
|
+
await signedIn(req)
|
|
157
|
+
const requestId = one(req.query.requestId)
|
|
158
|
+
if (requestId == null) throw new HttpError(400, 'request-id-required', 'give requestId: an identifier you choose for this upload, so that sending it again is the same request')
|
|
159
|
+
// The parser hands over a Buffer when there was a body. Anything else means none arrived.
|
|
160
|
+
const bytes = Buffer.isBuffer(req.body) ? new Uint8Array(req.body) : new Uint8Array(0)
|
|
161
|
+
const outcome = await withinStore('the document was not imported', () =>
|
|
162
|
+
exchange.importDocument({
|
|
163
|
+
sourceId: one(req.query.sourceId) ?? EPCIS_UPLOAD_SOURCE,
|
|
164
|
+
requestId,
|
|
165
|
+
bytes,
|
|
166
|
+
mediaType: req.headers['content-type'] ?? '',
|
|
167
|
+
...(one(req.query.filename) == null ? {} : { filename: one(req.query.filename) }),
|
|
168
|
+
})
|
|
169
|
+
)
|
|
170
|
+
if (outcome.outcome === 'refused') {
|
|
171
|
+
res.status(REFUSAL_STATUS[outcome.reason] ?? 422)
|
|
172
|
+
return { error: outcome.reason, description: outcome.detail, ...(outcome.remedy == null ? {} : { remedy: outcome.remedy }), outcome: 'refused', kept: false }
|
|
173
|
+
}
|
|
174
|
+
if (outcome.outcome === 'request-conflict') {
|
|
175
|
+
res.status(409)
|
|
176
|
+
return { error: 'request-conflict', description: outcome.detail, outcome: 'request-conflict', kept: false, existingImportId: outcome.existingImportId }
|
|
177
|
+
}
|
|
178
|
+
res.status(outcome.replayed ? 200 : 201)
|
|
179
|
+
return outcome
|
|
180
|
+
})
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
router.get(
|
|
184
|
+
'/imports',
|
|
185
|
+
wrap(async (req) => {
|
|
186
|
+
await signedIn(req)
|
|
187
|
+
const limit = Math.min(Math.max(Math.trunc(Number(one(req.query.limit) ?? 50)) || 50, 1), 200)
|
|
188
|
+
const after = one(req.query.after)
|
|
189
|
+
const records = await exchange.listImports({ ...(after == null ? {} : { after }), limit })
|
|
190
|
+
return {
|
|
191
|
+
// A listing names each import and counts what it holds. The record itself is one request away.
|
|
192
|
+
imports: records.map((record) => ({
|
|
193
|
+
importId: record.importId,
|
|
194
|
+
sourceId: record.sourceId,
|
|
195
|
+
requestId: record.requestId,
|
|
196
|
+
receivedAt: record.receivedAt,
|
|
197
|
+
mediaType: record.mediaType,
|
|
198
|
+
byteLength: record.byteLength,
|
|
199
|
+
sha256: record.sha256,
|
|
200
|
+
provenance: record.sourceLocation,
|
|
201
|
+
state: record.state,
|
|
202
|
+
documentValidity: record.documentValidity,
|
|
203
|
+
events: record.events.length,
|
|
204
|
+
findings: record.findings.length + record.events.reduce((sum, event) => sum + event.validation.findings.length, 0),
|
|
205
|
+
conflicts: record.events.filter((event) => event.conflict?.state === 'open').length,
|
|
206
|
+
})),
|
|
207
|
+
...(records.length === limit ? { next: records[records.length - 1]!.importId } : {}),
|
|
208
|
+
}
|
|
209
|
+
})
|
|
210
|
+
)
|
|
211
|
+
|
|
212
|
+
router.get(
|
|
213
|
+
'/imports/:importId',
|
|
214
|
+
wrap(async (req) => {
|
|
215
|
+
await signedIn(req)
|
|
216
|
+
const record = await exchange.getImport(param(req, 'importId'))
|
|
217
|
+
if (record == null) throw new HttpError(404, 'import-unknown', 'no import with that identifier is held')
|
|
218
|
+
return record
|
|
219
|
+
})
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
router.get('/imports/:importId/original', (req, res, next) => {
|
|
223
|
+
void (async () => {
|
|
224
|
+
await signedIn(req)
|
|
225
|
+
const original = await exchange.exportOriginal(param(req, 'importId'))
|
|
226
|
+
if (original == null) throw new HttpError(404, 'import-unknown', 'no import with that identifier is held')
|
|
227
|
+
// The retained bytes, under the media type they arrived with. A Buffer is sent as it is: nothing is parsed, formatted or given a character set.
|
|
228
|
+
res.status(200)
|
|
229
|
+
res.setHeader('content-type', original.mediaType)
|
|
230
|
+
res.setHeader('content-length', String(original.byteLength))
|
|
231
|
+
res.setHeader('content-disposition', `attachment; filename="epcis-${original.sha256.slice(0, 16)}.${original.mediaType === 'application/ld+json' ? 'jsonld' : 'json'}"`)
|
|
232
|
+
res.setHeader('x-content-sha256', original.sha256)
|
|
233
|
+
res.setHeader('cache-control', 'no-store')
|
|
234
|
+
// What was uploaded is whatever someone uploaded. A browser is told to save it and not to guess at what it is.
|
|
235
|
+
res.setHeader('x-content-type-options', 'nosniff')
|
|
236
|
+
res.end(Buffer.from(original.bytes.buffer, original.bytes.byteOffset, original.bytes.byteLength))
|
|
237
|
+
})().catch(next)
|
|
238
|
+
})
|
|
239
|
+
|
|
240
|
+
// ------------------------------------------------------------------ pulls
|
|
241
|
+
|
|
242
|
+
router.post(
|
|
243
|
+
'/sources/:sourceId/pulls',
|
|
244
|
+
json,
|
|
245
|
+
wrap(async (req, res) => {
|
|
246
|
+
await signedIn(req)
|
|
247
|
+
const body = objectOf(req.body)
|
|
248
|
+
const queryId = one(body.queryId)
|
|
249
|
+
if (queryId == null) throw new HttpError(400, 'query-id-required', 'give queryId: the name of this query, under which a later run continues it')
|
|
250
|
+
const window = body.window === 'watermark' || body.window === 'query-bounds' ? body.window : undefined
|
|
251
|
+
const outcome = await withinStore('the run stopped at a page it could not import', () => exchange.pull({ sourceId: param(req, 'sourceId'), queryId, query: objectOf(body.query), ...(window == null ? {} : { window }) }))
|
|
252
|
+
if (outcome == null) throw new HttpError(404, 'source-unknown', `no EPCIS source named ${param(req, 'sourceId')} is configured`)
|
|
253
|
+
if (outcome.outcome === 'refused') {
|
|
254
|
+
res.status(REFUSAL_STATUS[outcome.reason] ?? 400)
|
|
255
|
+
return { error: outcome.reason, description: outcome.detail, ...(outcome.remedy == null ? {} : { remedy: outcome.remedy }), outcome: 'refused', requested: false }
|
|
256
|
+
}
|
|
257
|
+
// A run that ran is answered 200 whatever it found. Its outcome, reason and completion are the module's, as they are.
|
|
258
|
+
return outcome
|
|
259
|
+
})
|
|
260
|
+
)
|
|
261
|
+
|
|
262
|
+
router.get(
|
|
263
|
+
'/sources/:sourceId/pulls/:queryId',
|
|
264
|
+
wrap(async (req) => {
|
|
265
|
+
await signedIn(req)
|
|
266
|
+
const held = await exchange.getPull(param(req, 'sourceId'), param(req, 'queryId'))
|
|
267
|
+
if (held == null) throw new HttpError(404, 'pull-unknown', 'that query has not been run against that source')
|
|
268
|
+
return held
|
|
269
|
+
})
|
|
270
|
+
)
|
|
271
|
+
|
|
272
|
+
// ------------------------------------------------------------------ events
|
|
273
|
+
|
|
274
|
+
router.get(
|
|
275
|
+
'/events',
|
|
276
|
+
wrap(async (req) => {
|
|
277
|
+
await signedIn(req)
|
|
278
|
+
const identifier = one(req.query.identifier)
|
|
279
|
+
if (identifier == null || identifier.length > 2048) throw new HttpError(400, 'identifier-required', 'give identifier: the product identifier exactly as events write it')
|
|
280
|
+
const granularity = one(req.query.granularity) ?? 'instance'
|
|
281
|
+
if (granularity !== 'instance' && granularity !== 'class') throw new HttpError(400, 'granularity-unknown', 'granularity is instance, for one item, or class, for a class, a lot or a pattern')
|
|
282
|
+
const sourceId = one(req.query.sourceId)
|
|
283
|
+
const after = one(req.query.after)
|
|
284
|
+
const limit = Math.min(Math.max(Math.trunc(Number(one(req.query.limit) ?? 100)) || 100, 1), 200)
|
|
285
|
+
const page = await exchange.eventsFor({ identifier, granularity, ...(sourceId == null ? {} : { sourceId }), ...(after == null ? {} : { after }), limit })
|
|
286
|
+
return {
|
|
287
|
+
identifier,
|
|
288
|
+
granularity,
|
|
289
|
+
// Said with every answer, so no reader of this route takes a retained event for more than it is.
|
|
290
|
+
nature: 'supplied-data',
|
|
291
|
+
notice: 'These events are data a source supplied. A valid document passed a format check. It is not signed, and nothing here verifies who observed an event or that it happened.',
|
|
292
|
+
...page,
|
|
293
|
+
}
|
|
294
|
+
})
|
|
295
|
+
)
|
|
296
|
+
|
|
297
|
+
// ------------------------------------------------------------------ conflicts
|
|
298
|
+
|
|
299
|
+
router.get(
|
|
300
|
+
'/conflicts',
|
|
301
|
+
wrap(async (req) => {
|
|
302
|
+
await signedIn(req)
|
|
303
|
+
return await exchange.listConflicts()
|
|
304
|
+
})
|
|
305
|
+
)
|
|
306
|
+
|
|
307
|
+
router.get(
|
|
308
|
+
'/conflicts/:conflictId',
|
|
309
|
+
wrap(async (req) => {
|
|
310
|
+
await signedIn(req)
|
|
311
|
+
const conflict = await exchange.getConflict(param(req, 'conflictId'))
|
|
312
|
+
if (conflict == null) throw new HttpError(404, 'conflict-unknown', 'no event identity with more than one body is held under that identifier')
|
|
313
|
+
return conflict
|
|
314
|
+
})
|
|
315
|
+
)
|
|
316
|
+
|
|
317
|
+
router.post(
|
|
318
|
+
'/conflicts/:conflictId/resolutions',
|
|
319
|
+
json,
|
|
320
|
+
wrap(async (req, res) => {
|
|
321
|
+
const session = await signedIn(req)
|
|
322
|
+
const body = objectOf(req.body)
|
|
323
|
+
const outcome = await exchange.resolveConflict({
|
|
324
|
+
conflictId: param(req, 'conflictId'),
|
|
325
|
+
decision: typeof body.decision === 'string' ? body.decision : '',
|
|
326
|
+
disposition: body.disposition as never,
|
|
327
|
+
...(body.selectedBodyDigest === undefined ? {} : { selectedBodyDigest: body.selectedBodyDigest as string }),
|
|
328
|
+
...(typeof body.decidedAt === 'string' ? { decidedAt: body.decidedAt } : {}),
|
|
329
|
+
// Who decided, as this application names its users. Never a credential.
|
|
330
|
+
decidedBy: session.userId,
|
|
331
|
+
})
|
|
332
|
+
if (outcome.outcome === 'refused') {
|
|
333
|
+
res.status(outcome.reason === 'no-conflict' ? 404 : 400)
|
|
334
|
+
return { error: outcome.reason, description: outcome.detail, outcome: 'refused' }
|
|
335
|
+
}
|
|
336
|
+
res.status(outcome.replayed ? 200 : 201)
|
|
337
|
+
return outcome
|
|
338
|
+
})
|
|
339
|
+
)
|
|
340
|
+
|
|
341
|
+
// A store that failed, a sign-in lookup that failed, or a store that holds something it should not: answered by name on every route here, never as an unnamed failure of the API.
|
|
342
|
+
router.use((error: unknown, req: Request, res: Response, next: NextFunction) => {
|
|
343
|
+
const answer = storeFailureAnswer(error, req)
|
|
344
|
+
if (answer == null || res.headersSent) return next(error)
|
|
345
|
+
res.status(answer.status).json(answer.body)
|
|
346
|
+
})
|
|
347
|
+
|
|
348
|
+
// A body the parsers refused: too large, or sent under a content encoding. The parser's own error can quote the body, so only its kind is answered.
|
|
349
|
+
router.use((error: unknown, _req: Request, res: Response, next: NextFunction) => {
|
|
350
|
+
const parser = error as { type?: unknown; status?: unknown }
|
|
351
|
+
if (typeof parser?.type !== 'string' || typeof parser.status !== 'number') return next(error)
|
|
352
|
+
if (parser.type === 'entity.too.large') {
|
|
353
|
+
res.status(413).json({ error: 'oversized', description: 'the body is larger than this API reads. Nothing was kept.', outcome: 'refused', kept: false })
|
|
354
|
+
return
|
|
355
|
+
}
|
|
356
|
+
if (parser.type === 'encoding.unsupported') {
|
|
357
|
+
res.status(415).json({ error: 'content-encoding-unsupported', description: 'send the document as the bytes it is, without a content encoding. Nothing was kept.', outcome: 'refused', kept: false })
|
|
358
|
+
return
|
|
359
|
+
}
|
|
360
|
+
next(error)
|
|
361
|
+
})
|
|
362
|
+
|
|
363
|
+
return router
|
|
364
|
+
}
|
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
// The EPCIS query sources this application may pull from. A source is server
|
|
2
|
+
// configuration and nothing in it comes from a request: an identifier, the
|
|
3
|
+
// address of the source's query interface, the origins a request may go to,
|
|
4
|
+
// and a credential read from the environment.
|
|
5
|
+
//
|
|
6
|
+
// The credential is kept behind a function. Printing or serialising the
|
|
7
|
+
// configuration shows that a credential is set and which kind, never what it
|
|
8
|
+
// is. It is handed to the pull when a run begins and goes nowhere else: not
|
|
9
|
+
// into the database, a response, a log line or the web client.
|
|
10
|
+
import type { EpcisSourceCredential } from '@bsv/dpp-credentials/epcis-exchange'
|
|
11
|
+
|
|
12
|
+
export interface EpcisSourceConfig {
|
|
13
|
+
/** The name events from this source are filed under. Lower-case letters, digits and hyphens. */
|
|
14
|
+
sourceId: string
|
|
15
|
+
/** The address the events query is made under: `<baseUrl>/events`. */
|
|
16
|
+
baseUrl: string
|
|
17
|
+
/** Every origin a request may be made to. The base address's own origin when the setting is empty. */
|
|
18
|
+
permittedOrigins: string[]
|
|
19
|
+
/** Permits plain http and private addresses. For a source on your own machine only. */
|
|
20
|
+
localTest: boolean
|
|
21
|
+
/** Sends each value of a list as its own parameter, for a source that does not read the pipe-delimited form. */
|
|
22
|
+
repeatListParameters: boolean
|
|
23
|
+
/** Which kind of credential is set, when one is. */
|
|
24
|
+
credentialScheme?: EpcisSourceCredential['scheme']
|
|
25
|
+
/** Reads the credential. Absent when none is set. */
|
|
26
|
+
credentials?: () => EpcisSourceCredential
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
/** A source as the API describes it. It says whether a credential is set, and never carries one. */
|
|
30
|
+
export interface EpcisSourceDescription {
|
|
31
|
+
sourceId: string
|
|
32
|
+
baseUrl: string
|
|
33
|
+
permittedOrigins: string[]
|
|
34
|
+
localTest: boolean
|
|
35
|
+
repeatListParameters: boolean
|
|
36
|
+
credentialConfigured: boolean
|
|
37
|
+
credentialScheme?: EpcisSourceCredential['scheme']
|
|
38
|
+
/** Why a pull from this source will be refused as it is configured, when it will be. */
|
|
39
|
+
problem?: string
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
const text = (env: NodeJS.ProcessEnv, name: string): string | undefined => {
|
|
43
|
+
const value = env[name]?.trim()
|
|
44
|
+
return value == null || value === '' ? undefined : value
|
|
45
|
+
}
|
|
46
|
+
const list = (env: NodeJS.ProcessEnv, name: string): string[] =>
|
|
47
|
+
(text(env, name) ?? '')
|
|
48
|
+
.split(',')
|
|
49
|
+
.map((entry) => entry.trim())
|
|
50
|
+
.filter((entry) => entry !== '')
|
|
51
|
+
const flag = (env: NodeJS.ProcessEnv, name: string): boolean => {
|
|
52
|
+
const value = text(env, name)
|
|
53
|
+
if (value == null || value === 'false') return false
|
|
54
|
+
if (value === 'true') return true
|
|
55
|
+
throw new Error(`${name} must be true or false`)
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
/** The environment variables of one source start with this: `supplier-a` reads `EPCIS_SOURCE_SUPPLIER_A_URL` and the rest. */
|
|
59
|
+
export const sourceVariablePrefix = (sourceId: string): string => `EPCIS_SOURCE_${sourceId.toUpperCase().replace(/-/g, '_')}_`
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Read the configured sources. A setting that cannot be used stops the start
|
|
63
|
+
* and is named. Its value is never part of the message, because one of them
|
|
64
|
+
* is a credential.
|
|
65
|
+
*/
|
|
66
|
+
export function loadEpcisSources(env: NodeJS.ProcessEnv): EpcisSourceConfig[] {
|
|
67
|
+
const ids = list(env, 'EPCIS_SOURCES')
|
|
68
|
+
const seen = new Set<string>()
|
|
69
|
+
return ids.map((sourceId) => {
|
|
70
|
+
if (!/^[a-z0-9][a-z0-9-]{0,31}$/.test(sourceId)) throw new Error('EPCIS_SOURCES holds a name that is not 1 to 32 lower-case letters, digits and hyphens')
|
|
71
|
+
const prefix = sourceVariablePrefix(sourceId)
|
|
72
|
+
// Two names that differ only in case or punctuation would read the same variables.
|
|
73
|
+
if (seen.has(prefix)) throw new Error(`EPCIS_SOURCES names ${sourceId} twice`)
|
|
74
|
+
seen.add(prefix)
|
|
75
|
+
|
|
76
|
+
const address = text(env, `${prefix}URL`)
|
|
77
|
+
if (address == null) throw new Error(`${prefix}URL is not set: the source ${sourceId} needs the address of its EPCIS query interface`)
|
|
78
|
+
let url: URL
|
|
79
|
+
try {
|
|
80
|
+
url = new URL(address)
|
|
81
|
+
} catch {
|
|
82
|
+
throw new Error(`${prefix}URL does not parse as an address`)
|
|
83
|
+
}
|
|
84
|
+
if (url.protocol !== 'https:' && url.protocol !== 'http:') throw new Error(`${prefix}URL must be an https address, or an http one with ${prefix}LOCAL_TEST=true`)
|
|
85
|
+
if (url.username !== '' || url.password !== '') throw new Error(`${prefix}URL carries user information: set the credential in ${prefix}BEARER_TOKEN, ${prefix}BASIC_USER and ${prefix}BASIC_PASSWORD, or ${prefix}HEADER_NAME and ${prefix}HEADER_VALUE`)
|
|
86
|
+
if (url.search !== '' || url.hash !== '') throw new Error(`${prefix}URL carries a query or a fragment: give the base address only`)
|
|
87
|
+
const localTest = flag(env, `${prefix}LOCAL_TEST`)
|
|
88
|
+
if (url.protocol === 'http:' && !localTest) throw new Error(`${prefix}URL is a plain http address: use https, or set ${prefix}LOCAL_TEST=true for a source on your own machine`)
|
|
89
|
+
|
|
90
|
+
const origins = list(env, `${prefix}ORIGINS`)
|
|
91
|
+
for (const origin of origins) {
|
|
92
|
+
let parsed: URL | undefined
|
|
93
|
+
try {
|
|
94
|
+
parsed = new URL(origin)
|
|
95
|
+
} catch {
|
|
96
|
+
// Reported below.
|
|
97
|
+
}
|
|
98
|
+
if (parsed == null || parsed.origin !== origin) throw new Error(`${prefix}ORIGINS holds an entry that is not an origin: each is a scheme, a host and a port, such as https://events.example.org`)
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
const bearer = text(env, `${prefix}BEARER_TOKEN`)
|
|
102
|
+
const basicUser = text(env, `${prefix}BASIC_USER`)
|
|
103
|
+
const basicPassword = text(env, `${prefix}BASIC_PASSWORD`)
|
|
104
|
+
const headerName = text(env, `${prefix}HEADER_NAME`)
|
|
105
|
+
const headerValue = text(env, `${prefix}HEADER_VALUE`)
|
|
106
|
+
if ((basicUser == null) !== (basicPassword == null)) throw new Error(`${prefix}BASIC_USER and ${prefix}BASIC_PASSWORD are set together`)
|
|
107
|
+
if ((headerName == null) !== (headerValue == null)) throw new Error(`${prefix}HEADER_NAME and ${prefix}HEADER_VALUE are set together`)
|
|
108
|
+
if ([bearer, basicUser, headerName].filter((value) => value != null).length > 1) throw new Error(`the source ${sourceId} has more than one credential set: use ${prefix}BEARER_TOKEN, or the BASIC pair, or the HEADER pair`)
|
|
109
|
+
const credential: EpcisSourceCredential | undefined =
|
|
110
|
+
bearer != null
|
|
111
|
+
? { scheme: 'bearer', token: bearer }
|
|
112
|
+
: basicUser != null && basicPassword != null
|
|
113
|
+
? { scheme: 'basic', username: basicUser, password: basicPassword }
|
|
114
|
+
: headerName != null && headerValue != null
|
|
115
|
+
? { scheme: 'header', name: headerName, value: headerValue }
|
|
116
|
+
: undefined
|
|
117
|
+
|
|
118
|
+
return {
|
|
119
|
+
sourceId,
|
|
120
|
+
baseUrl: `${url.origin}${url.pathname.replace(/\/+$/, '')}`,
|
|
121
|
+
permittedOrigins: origins.length === 0 ? [url.origin] : origins,
|
|
122
|
+
localTest,
|
|
123
|
+
repeatListParameters: flag(env, `${prefix}REPEAT_LISTS`),
|
|
124
|
+
...(credential == null ? {} : { credentialScheme: credential.scheme, credentials: () => credential }),
|
|
125
|
+
}
|
|
126
|
+
})
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
export function describeEpcisSource(source: EpcisSourceConfig): EpcisSourceDescription {
|
|
130
|
+
const origin = new URL(source.baseUrl).origin
|
|
131
|
+
return {
|
|
132
|
+
sourceId: source.sourceId,
|
|
133
|
+
baseUrl: source.baseUrl,
|
|
134
|
+
permittedOrigins: source.permittedOrigins,
|
|
135
|
+
localTest: source.localTest,
|
|
136
|
+
repeatListParameters: source.repeatListParameters,
|
|
137
|
+
credentialConfigured: source.credentials != null,
|
|
138
|
+
...(source.credentialScheme == null ? {} : { credentialScheme: source.credentialScheme }),
|
|
139
|
+
// The pull itself refuses this before it asks for anything. Saying so here lets an operator see it without running one.
|
|
140
|
+
...(source.permittedOrigins.includes(origin) ? {} : { problem: `its permitted origins do not list ${origin}, the origin of its own base address, so every pull is refused` }),
|
|
141
|
+
}
|
|
142
|
+
}
|