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