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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (178) hide show
  1. package/LICENSE +203 -0
  2. package/NOTICE +2 -0
  3. package/PATENTS +12 -0
  4. package/README.md +93 -2
  5. package/dist/index.js +125 -0
  6. package/package.json +57 -4
  7. package/template/Dockerfile +37 -0
  8. package/template/README.md +389 -0
  9. package/template/_dockerignore +6 -0
  10. package/template/_env.example +122 -0
  11. package/template/_github/workflows/ci.yml +23 -0
  12. package/template/_gitignore +8 -0
  13. package/template/_prettierrc +6 -0
  14. package/template/apps/api/API.md +119 -0
  15. package/template/apps/api/package.json +39 -0
  16. package/template/apps/api/src/auth.ts +55 -0
  17. package/template/apps/api/src/bound-profiles.ts +590 -0
  18. package/template/apps/api/src/claims.ts +204 -0
  19. package/template/apps/api/src/cli.ts +99 -0
  20. package/template/apps/api/src/config.ts +180 -0
  21. package/template/apps/api/src/custody.ts +358 -0
  22. package/template/apps/api/src/dev-index.ts +120 -0
  23. package/template/apps/api/src/env-file.ts +55 -0
  24. package/template/apps/api/src/env.ts +14 -0
  25. package/template/apps/api/src/epcis/exchange.ts +434 -0
  26. package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
  27. package/template/apps/api/src/epcis/routes.ts +364 -0
  28. package/template/apps/api/src/epcis/sources.ts +142 -0
  29. package/template/apps/api/src/go-live.ts +226 -0
  30. package/template/apps/api/src/http-error.ts +15 -0
  31. package/template/apps/api/src/identifiers.ts +57 -0
  32. package/template/apps/api/src/index-client.ts +261 -0
  33. package/template/apps/api/src/index-projects.ts +53 -0
  34. package/template/apps/api/src/lifecycle-authority.ts +49 -0
  35. package/template/apps/api/src/lifecycle.ts +485 -0
  36. package/template/apps/api/src/main.ts +58 -0
  37. package/template/apps/api/src/parties.ts +68 -0
  38. package/template/apps/api/src/platform.ts +176 -0
  39. package/template/apps/api/src/portability/commands.ts +224 -0
  40. package/template/apps/api/src/portability/export.ts +708 -0
  41. package/template/apps/api/src/portability/package.ts +270 -0
  42. package/template/apps/api/src/portability/restore.ts +863 -0
  43. package/template/apps/api/src/profiles.ts +125 -0
  44. package/template/apps/api/src/reader.ts +265 -0
  45. package/template/apps/api/src/resolver.ts +159 -0
  46. package/template/apps/api/src/sector-examples.ts +390 -0
  47. package/template/apps/api/src/server.ts +613 -0
  48. package/template/apps/api/src/store.ts +426 -0
  49. package/template/apps/api/src/validation-engine.ts +172 -0
  50. package/template/apps/api/src/wallet.ts +359 -0
  51. package/template/apps/api/src/worker.ts +113 -0
  52. package/template/apps/api/src/writer.ts +603 -0
  53. package/template/apps/api/test/bound-http.test.ts +496 -0
  54. package/template/apps/api/test/bound-profiles.test.ts +547 -0
  55. package/template/apps/api/test/config.test.ts +160 -0
  56. package/template/apps/api/test/custody-journal.test.ts +415 -0
  57. package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
  58. package/template/apps/api/test/custom-profile.test.ts +167 -0
  59. package/template/apps/api/test/env-file.test.ts +53 -0
  60. package/template/apps/api/test/epcis-fixtures.ts +270 -0
  61. package/template/apps/api/test/epcis-http.test.ts +1179 -0
  62. package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
  63. package/template/apps/api/test/epcis-separation.test.ts +253 -0
  64. package/template/apps/api/test/epcis-web.test.ts +230 -0
  65. package/template/apps/api/test/exit-exercise.test.ts +1038 -0
  66. package/template/apps/api/test/external-index.test.ts +32 -0
  67. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
  68. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
  69. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
  70. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
  71. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
  72. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
  73. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
  74. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
  75. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
  76. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
  77. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
  78. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
  79. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
  80. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
  81. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
  82. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
  83. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
  84. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
  85. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
  86. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
  87. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
  88. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
  89. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
  90. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
  91. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
  92. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
  93. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
  94. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
  95. package/template/apps/api/test/go-live.test.ts +179 -0
  96. package/template/apps/api/test/gs1-global-setup.ts +33 -0
  97. package/template/apps/api/test/gs1-test-env.ts +5 -0
  98. package/template/apps/api/test/identifier-host.test.ts +256 -0
  99. package/template/apps/api/test/index-projects.test.ts +81 -0
  100. package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
  101. package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
  102. package/template/apps/api/test/lifecycle.test.ts +147 -0
  103. package/template/apps/api/test/manifest-notice.test.ts +36 -0
  104. package/template/apps/api/test/network-guard.ts +113 -0
  105. package/template/apps/api/test/portability.test.ts +655 -0
  106. package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
  107. package/template/apps/api/test/retired-profiles.test.ts +216 -0
  108. package/template/apps/api/test/sector-cutover.test.ts +95 -0
  109. package/template/apps/api/test/sector-forms.test.ts +420 -0
  110. package/template/apps/api/test/unjoined-index.test.ts +62 -0
  111. package/template/apps/api/test/validation-engine.test.ts +328 -0
  112. package/template/apps/api/test/wallet-monitor.test.ts +38 -0
  113. package/template/apps/api/test/writer-journal.test.ts +327 -0
  114. package/template/apps/api/tsconfig.json +9 -0
  115. package/template/apps/api/vitest.config.ts +12 -0
  116. package/template/apps/web/components.json +21 -0
  117. package/template/apps/web/index.html +12 -0
  118. package/template/apps/web/package.json +33 -0
  119. package/template/apps/web/src/app.tsx +55 -0
  120. package/template/apps/web/src/components/bits.tsx +188 -0
  121. package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
  122. package/template/apps/web/src/components/bound/field-view.tsx +237 -0
  123. package/template/apps/web/src/components/bound/pieces.tsx +169 -0
  124. package/template/apps/web/src/components/bound/readings.tsx +152 -0
  125. package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
  126. package/template/apps/web/src/components/claim-dialog.tsx +344 -0
  127. package/template/apps/web/src/components/epcis-events.tsx +119 -0
  128. package/template/apps/web/src/components/layout.tsx +135 -0
  129. package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
  130. package/template/apps/web/src/components/passport-form.tsx +244 -0
  131. package/template/apps/web/src/components/read-passport.tsx +49 -0
  132. package/template/apps/web/src/components/reading.tsx +150 -0
  133. package/template/apps/web/src/components/ui/alert.tsx +65 -0
  134. package/template/apps/web/src/components/ui/badge.tsx +47 -0
  135. package/template/apps/web/src/components/ui/button.tsx +63 -0
  136. package/template/apps/web/src/components/ui/card.tsx +91 -0
  137. package/template/apps/web/src/components/ui/dialog.tsx +156 -0
  138. package/template/apps/web/src/components/ui/input.tsx +20 -0
  139. package/template/apps/web/src/components/ui/label.tsx +21 -0
  140. package/template/apps/web/src/components/ui/select.tsx +189 -0
  141. package/template/apps/web/src/components/ui/separator.tsx +25 -0
  142. package/template/apps/web/src/components/ui/table.tsx +115 -0
  143. package/template/apps/web/src/components/ui/tabs.tsx +90 -0
  144. package/template/apps/web/src/components/ui/textarea.tsx +17 -0
  145. package/template/apps/web/src/index.css +81 -0
  146. package/template/apps/web/src/lib/api.ts +396 -0
  147. package/template/apps/web/src/lib/auth.ts +10 -0
  148. package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
  149. package/template/apps/web/src/lib/bound/display.ts +122 -0
  150. package/template/apps/web/src/lib/bound/fields.ts +128 -0
  151. package/template/apps/web/src/lib/bound/form-model.ts +521 -0
  152. package/template/apps/web/src/lib/bound/forms.ts +15 -0
  153. package/template/apps/web/src/lib/bound/identity.ts +48 -0
  154. package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
  155. package/template/apps/web/src/lib/bound/units.ts +37 -0
  156. package/template/apps/web/src/lib/epcis.ts +345 -0
  157. package/template/apps/web/src/lib/format.ts +87 -0
  158. package/template/apps/web/src/lib/lifecycle.ts +350 -0
  159. package/template/apps/web/src/lib/session.tsx +92 -0
  160. package/template/apps/web/src/lib/use-load.ts +46 -0
  161. package/template/apps/web/src/main.tsx +18 -0
  162. package/template/apps/web/src/pages/accept.tsx +113 -0
  163. package/template/apps/web/src/pages/brand.tsx +94 -0
  164. package/template/apps/web/src/pages/brands.tsx +104 -0
  165. package/template/apps/web/src/pages/events.tsx +388 -0
  166. package/template/apps/web/src/pages/home.tsx +51 -0
  167. package/template/apps/web/src/pages/new-passport.tsx +137 -0
  168. package/template/apps/web/src/pages/operations.tsx +169 -0
  169. package/template/apps/web/src/pages/passport.tsx +632 -0
  170. package/template/apps/web/src/pages/public-passport.tsx +64 -0
  171. package/template/apps/web/src/pages/sign-in.tsx +93 -0
  172. package/template/apps/web/src/pages/verify.tsx +30 -0
  173. package/template/apps/web/src/pages/wallet.tsx +141 -0
  174. package/template/apps/web/tsconfig.json +29 -0
  175. package/template/apps/web/vite.config.ts +23 -0
  176. package/template/deploy/compose.yml +38 -0
  177. package/template/package.json +48 -0
  178. package/template/tsconfig.base.json +13 -0
@@ -0,0 +1,167 @@
1
+ // What the lifecycle claim tests share: synthetic EPCIS events about this
2
+ // application's own passports, and a small stand-in for a registry that
3
+ // admits EPCIS lifecycle claims.
4
+ //
5
+ // The stand-in does what the registry contract says a registry does with
6
+ // `dpp-epcis-lifecycle-json@1`, and no more: it verifies the claim, keeps
7
+ // the exact bytes, anchors them once per bound passport in one transaction
8
+ // on the index's `tm_attestation`, and serves the bytes from its proof
9
+ // route. Its proof answer and its refusals have the members the contract
10
+ // gives them: `securedBytes` for the exact bytes, `outcome` and `issues`
11
+ // for a refusal. It is not the reference registry, listens on 127.0.0.1
12
+ // only, and funds its transactions the way the test wallet does, with
13
+ // made-up coins only an index with its header checks off takes.
14
+ import { once } from 'node:events'
15
+ import { createServer, type Server } from 'node:http'
16
+ import type { AddressInfo } from 'node:net'
17
+ import { LockingScript, MerklePath, PrivateKey, ProtoWallet, Transaction, UnlockingScript } from '@bsv/sdk'
18
+ import { buildAttestationAnchor } from '@bsv/dpp-protocol'
19
+ import {
20
+ EPCIS_LIFECYCLE_MEDIA_TYPE,
21
+ EPCIS_LIFECYCLE_REPRESENTATION,
22
+ epcisLifecycleAnchorMetadata,
23
+ parseEpcisLifecycleClaim,
24
+ verifyEpcisLifecycleClaim,
25
+ } from '@bsv/dpp-credentials/epcis-lifecycle'
26
+
27
+ export type Json = Record<string, unknown>
28
+
29
+ /* --------------------------------- identifiers ---------------------------- */
30
+
31
+ /** The SGTIN URN of a passport minted as a GS1 Digital Link: the same item, written the EPC way. */
32
+ export function sgtinOf(passportId: string): string {
33
+ const match = /\/01\/(\d{14})\/21\/([^/?#]+)$/.exec(passportId)
34
+ if (match == null) throw new Error(`${passportId} is not a Digital Link of an item`)
35
+ const gtin = match[1]!
36
+ return `urn:epc:id:sgtin:${gtin.slice(1, 8)}.${gtin[0]}${gtin.slice(8, 13)}.${match[2]}`
37
+ }
38
+
39
+ /** The class of a passport's product at model level, as a GS1 Digital Link with no serial. */
40
+ export function classOf(passportId: string): string {
41
+ const match = /\/01\/(\d{14})\//.exec(passportId)
42
+ if (match == null) throw new Error(`${passportId} carries no GTIN`)
43
+ return `https://id.gs1.org/01/${match[1]}`
44
+ }
45
+
46
+ const prefix = '9521234'
47
+ export const PARTY = { maker: `urn:epc:id:pgln:${prefix}.00001`, carrier: `urn:epc:id:pgln:${prefix}.00002`, retailer: `urn:epc:id:pgln:${prefix}.00003`, repairer: `urn:epc:id:pgln:${prefix}.00006` }
48
+ export const PLACE = { factory: `urn:epc:id:sgln:${prefix}.00001.0`, warehouse: `urn:epc:id:sgln:${prefix}.00002.0`, shop: `urn:epc:id:sgln:${prefix}.00003.0`, workshop: `urn:epc:id:sgln:${prefix}.00006.0` }
49
+ export const PALLET = `urn:epc:id:sscc:${prefix}.0000000001`
50
+
51
+ let sequence = 0
52
+ /** The members every event carries: a fresh eventID and a time in the past. */
53
+ export function base(day = 2, hour = 9): Json {
54
+ sequence += 1
55
+ return { eventTime: `2026-03-${String(day).padStart(2, '0')}T${String(hour).padStart(2, '0')}:00:00.000Z`, eventTimeZoneOffset: '+00:00', eventID: `urn:uuid:6c000000-0000-4000-8000-${String(sequence).padStart(12, '0')}` }
56
+ }
57
+
58
+ /* ---------------------------------- registry ------------------------------ */
59
+
60
+ export interface TestRegistry {
61
+ url: string
62
+ anchoredBy: string
63
+ /** Every claim it accepted, by attestation identifier, as the exact bytes. */
64
+ held: Map<string, string>
65
+ /** Every anchor transaction it wrote, in order. */
66
+ anchors: Transaction[]
67
+ /** Anchor a held claim under a subject of the test's choosing, as a careless or hostile anchoring service could. */
68
+ anchorUnder(attestationId: string, subject: string): Promise<void>
69
+ close(): Promise<void>
70
+ }
71
+
72
+ const ANYONE_CAN_SPEND = new LockingScript([{ op: 0x51 }])
73
+
74
+ function funding(): Transaction {
75
+ const tx = new Transaction()
76
+ tx.addOutput({ satoshis: 10_000, lockingScript: ANYONE_CAN_SPEND })
77
+ tx.merklePath = MerklePath.fromCoinbaseTxidAndHeight(tx.id('hex'), 800_000)
78
+ return tx
79
+ }
80
+
81
+ /** Start the stand-in. `index` is read when a claim arrives, so the registry can be started before the application whose index it writes to. */
82
+ export async function startTestRegistry(index: () => { url: string; submitToken: string }): Promise<TestRegistry> {
83
+ const key = PrivateKey.fromHex('66'.repeat(32))
84
+ const wallet = new ProtoWallet(key)
85
+ const anchoredBy = key.toPublicKey().toString()
86
+ const held = new Map<string, string>()
87
+ const anchors: Transaction[] = []
88
+ /** The transaction that anchors each held claim, by attestation identifier. */
89
+ const anchoredIn = new Map<string, string>()
90
+
91
+ const write = async (scripts: LockingScript[]): Promise<string> => {
92
+ const tx = new Transaction()
93
+ tx.addInput({ sourceTransaction: funding(), sourceOutputIndex: 0, unlockingScript: new UnlockingScript([]) })
94
+ for (const lockingScript of scripts) tx.addOutput({ satoshis: 1, lockingScript })
95
+ const { url, submitToken } = index()
96
+ const response = await fetch(`${url}/submit`, { method: 'POST', headers: { 'Content-Type': 'application/octet-stream', 'X-Topics': JSON.stringify(['tm_attestation']), Authorization: `Bearer ${submitToken}` }, body: new Uint8Array(tx.toAtomicBEEF()) })
97
+ if (!response.ok) throw new Error(`the index answered HTTP ${response.status} to the anchors`)
98
+ anchors.push(tx)
99
+ return tx.id('hex')
100
+ }
101
+
102
+ const server: Server = createServer((request, response) => {
103
+ const chunks: Buffer[] = []
104
+ request.on('data', (chunk: Buffer) => chunks.push(chunk))
105
+ request.on('end', () => {
106
+ void (async () => {
107
+ const url = new URL(request.url ?? '/', 'http://127.0.0.1')
108
+ const answer = (status: number, body: unknown): void => void response.writeHead(status, { 'content-type': 'application/json' }).end(JSON.stringify(body))
109
+ if (request.method === 'POST' && url.pathname === '/attestations') {
110
+ const body = JSON.parse(Buffer.concat(chunks).toString('utf8')) as { representation?: string; claim?: string; subject?: string }
111
+ if (body.representation !== EPCIS_LIFECYCLE_REPRESENTATION || typeof body.claim !== 'string') return answer(422, { outcome: 'unsupported', issues: ['representation-unsupported: this stand-in admits dpp-epcis-lifecycle-json@1 only'] })
112
+ const verified = await verifyEpcisLifecycleClaim(body.claim)
113
+ if (verified.findings.signature.status !== 'pass' || verified.findings.eventStructure.status === 'fail') return answer(422, { outcome: 'invalid', issues: ['the claim does not verify'], checks: verified.findings })
114
+ if (body.subject != null && !verified.boundPassports.includes(body.subject)) return answer(422, { outcome: 'invalid', issues: [`subject mismatch: the claim does not bind ${body.subject}`], checks: verified.findings })
115
+ if (!held.has(verified.attestationId!)) {
116
+ const claim = parseEpcisLifecycleClaim(body.claim)
117
+ const scripts: LockingScript[] = []
118
+ for (const metadata of epcisLifecycleAnchorMetadata(claim, anchoredBy)) scripts.push(await buildAttestationAnchor(metadata, wallet))
119
+ anchoredIn.set(verified.attestationId!, await write(scripts))
120
+ held.set(verified.attestationId!, body.claim)
121
+ }
122
+ return answer(202, { accepted: true, attestationId: verified.attestationId, digest: verified.digest, representation: EPCIS_LIFECYCLE_REPRESENTATION, mediaType: EPCIS_LIFECYCLE_MEDIA_TYPE, verdict: 'valid' })
123
+ }
124
+ const proof = /^\/attestations\/(.+)\/proof$/.exec(url.pathname)
125
+ if (request.method === 'GET' && proof != null) {
126
+ const id = decodeURIComponent(proof[1]!)
127
+ const bytes = held.get(id)
128
+ if (bytes == null) return answer(404, { error: 'not_found' })
129
+ // The contract's AnchorProof: the exact bytes travel as `securedBytes`, and as `canonical` for a reader of older records.
130
+ return answer(200, {
131
+ attestationId: id,
132
+ attestation: JSON.parse(bytes),
133
+ claimRelations: { relations: [], derived: [], conflicts: [], notProduced: ['supersedes', 'disputes'], evaluatedAt: new Date().toISOString() },
134
+ canonical: bytes,
135
+ securedBytes: bytes,
136
+ representation: EPCIS_LIFECYCLE_REPRESENTATION,
137
+ mediaType: EPCIS_LIFECYCLE_MEDIA_TYPE,
138
+ digest: id.slice('urn:sha256:'.length),
139
+ algorithm: 'SHA-256 over the exact secured bytes, hex',
140
+ anchored: true,
141
+ anchor: { recordId: anchoredIn.get(id), outputIndex: 0, format: 'bsv-attestation-anchor-v1' },
142
+ })
143
+ }
144
+ answer(404, { error: 'not_found' })
145
+ })().catch((cause: unknown) => void response.writeHead(500).end(String(cause)))
146
+ })
147
+ })
148
+ server.listen(0, '127.0.0.1')
149
+ await once(server, 'listening')
150
+ return {
151
+ url: `http://127.0.0.1:${(server.address() as AddressInfo).port}`,
152
+ anchoredBy,
153
+ held,
154
+ anchors,
155
+ async anchorUnder(attestationId, subject) {
156
+ const bytes = held.get(attestationId)
157
+ if (bytes == null) throw new Error(`the stand-in holds no claim ${attestationId}`)
158
+ const [first] = epcisLifecycleAnchorMetadata(parseEpcisLifecycleClaim(bytes), anchoredBy)
159
+ await write([await buildAttestationAnchor({ ...first!, subject }, wallet)])
160
+ },
161
+ close: () =>
162
+ new Promise<void>((resolve) => {
163
+ server.closeAllConnections()
164
+ server.close(() => resolve())
165
+ }),
166
+ }
167
+ }
@@ -0,0 +1,147 @@
1
+ // The first run: a whole passport lifecycle with no wallet, no funds, no
2
+ // Docker and no network. A test wallet with fixed keys stands in for the
3
+ // platform wallet, the index runs in this process with in-memory storage and
4
+ // its header checks off, and the records live in memory. Everything else is
5
+ // the code the live platform runs: the writer's six steps, the index's real
6
+ // admission rules, managed custody, claims, and the reader's report.
7
+ import { afterAll, beforeAll, describe, expect, it } from 'vitest'
8
+ import { verifyEpcisLifecycleClaim } from '@bsv/dpp-credentials/epcis-lifecycle'
9
+ import { loadConfig } from '../src/config.js'
10
+ import { managedParties } from '../src/parties.js'
11
+ import { mintPassportId } from '../src/identifiers.js'
12
+ import { eventSchemaCheck } from '../src/lifecycle.js'
13
+ import { openPlatform, type Platform } from '../src/platform.js'
14
+ import { samplePayload } from '../src/profiles.js'
15
+ import type { PassportRecord } from '../src/store.js'
16
+ import { pendingDuties, runDuties } from '../src/worker.js'
17
+ import { WriteRefused } from '../src/writer.js'
18
+ import { gs1Dir } from './epcis-fixtures.js'
19
+
20
+ const config = loadConfig({ NETWORK: 'main', PASSPORT_HOST: 'passports.example.com', GS1_PREFIX: '952', LIVE_PUBLISHING: 'false' })
21
+ let platform: Platform
22
+ const brandId = 'brand-test-1'
23
+ const profile = 'general@2' as const
24
+ let passportId: string
25
+ let payload: Record<string, unknown>
26
+
27
+ beforeAll(async () => {
28
+ passportId = mintPassportId({ host: config.passportHost, prefix: config.gs1Prefix }, '100000001', `TEST-${Date.now().toString(36).toUpperCase()}`)
29
+ const recycler = managedParties(config).member('recycler-line-3')
30
+ platform = await openPlatform({ config, mode: 'test', log: () => {}, lifecyclePolicy: { authorityResolver: (q) => ({
31
+ status: q.issuer === recycler.did && q.issuerKey === recycler.identityKey && q.passportId === passportId && q.purpose === 'claim' && q.role === 'observer' && q.eventTime === '2026-03-02T08:00:00.000Z' ? 'supported' : 'unsupported',
32
+ }) } })
33
+ payload = samplePayload(profile, true)
34
+ })
35
+
36
+ afterAll(async () => {
37
+ await platform.close()
38
+ })
39
+
40
+ const latest = async (): Promise<PassportRecord> => {
41
+ const record = await platform.store.getPassport(passportId)
42
+ if (record == null) throw new Error('the passport is not in the journal')
43
+ return record
44
+ }
45
+
46
+ describe('a passport lifecycle under managed custody', () => {
47
+ it('names the platform wallet as a publisher on the index', async () => {
48
+ const keys = await platform.index.publisherKeys()
49
+ expect(keys).toContain(platform.wallet.identityKey)
50
+ })
51
+
52
+ it('refuses an identifier outside the configured prefix and host', async () => {
53
+ const brand = platform.parties.brand(brandId)
54
+ await expect(
55
+ platform.writer.issue({ brandId, brand, passportId: 'https://id.gs1.org/01/09506000134352/21/7AC18477503A', profile, payload, ownerFields: {} })
56
+ ).rejects.toBeInstanceOf(WriteRefused)
57
+ })
58
+
59
+ it('refuses a payload the profile schema rejects', async () => {
60
+ const brand = platform.parties.brand(brandId)
61
+ await expect(platform.writer.issue({ brandId, brand, passportId, profile, payload: { nonsense: true }, ownerFields: {} })).rejects.toMatchObject({ code: 'payload-invalid' })
62
+ expect(await platform.store.getPassport(passportId)).toBeUndefined()
63
+ })
64
+
65
+ it('issues the passport: the genesis is admitted by the index', async () => {
66
+ const brand = platform.parties.brand(brandId)
67
+ const outcome = await platform.writer.issue({ brandId, brand, passportId, profile, payload, ownerFields: { serviceNotes: 'first revision' } })
68
+ expect(outcome.entry.op).toBe('ISSUE')
69
+ expect(outcome.entry.index).toBe('admitted')
70
+ expect(outcome.record.holder.party).toBe(brand.name)
71
+ const held = await platform.index.lineage(passportId)
72
+ expect(held.map((tx) => tx.id('hex'))).toEqual([outcome.entry.txid])
73
+ })
74
+
75
+ it('updates the passport, proving control by linkage', async () => {
76
+ const brand = platform.parties.brand(brandId)
77
+ const revised = { ...payload, careNote: 'revised by the UPDATE' }
78
+ const outcome = await platform.writer.update({ record: await latest(), actor: brand, payload: revised, ownerFields: { serviceNotes: 'second revision' } })
79
+ expect(outcome.entry.op).toBe('UPDATE')
80
+ expect(outcome.entry.index).toBe('admitted')
81
+ expect(outcome.state.controlLinkage).toHaveLength(64)
82
+ })
83
+
84
+ it('refuses an update by a party that does not control the passport', async () => {
85
+ const stranger = platform.parties.member('someone-else')
86
+ await expect(platform.writer.update({ record: await latest(), actor: stranger, payload, ownerFields: {} })).rejects.toMatchObject({ code: 'not-the-controller' })
87
+ })
88
+
89
+ it('runs the unattended duties: proofs are fetched and pushed to the index', async () => {
90
+ expect((await pendingDuties(platform.store)).map((d) => d.duty)).toEqual(['prove', 'prove'])
91
+ await runDuties({ store: platform.store, index: platform.index, writer: platform.writer })
92
+ const record = await latest()
93
+ expect(record.states.every((s) => s.proof != null && s.proofPushed === true)).toBe(true)
94
+ expect(await pendingDuties(platform.store)).toEqual([])
95
+ })
96
+
97
+ it('hands the passport on: offer, acceptance by claim code, and a TRANSFER that commits to the record', async () => {
98
+ const brand = platform.parties.brand(brandId)
99
+ const { offer, claimCode } = await platform.custody.offer({ record: await latest(), holder: brand, terms: { word: 'Passed on', note: 'Handed to the distributor' } })
100
+ expect(offer.status).toBe('open')
101
+ expect(claimCode).toMatch(/^[0-9a-f]{16}$/)
102
+ await expect(platform.custody.accept({ requestId: offer.requestId, claimCode: 'wrong' })).rejects.toMatchObject({ code: 'claim-code-wrong' })
103
+ const accepted = await platform.custody.accept({ requestId: offer.requestId, claimCode })
104
+ expect(accepted.offer.status).toBe('transferred')
105
+ expect(accepted.record.custodian).toBe(platform.wallet.identityKey)
106
+ const record = await latest()
107
+ expect(record.states.at(-1)?.op).toBe('TRANSFER')
108
+ expect(record.holder.party).toBe(`recipient:${offer.requestId}`)
109
+ expect(record.acceptanceRecords).toHaveLength(1)
110
+ })
111
+
112
+ it('reads the passport back as a stranger would, with the acceptance record supplied', async () => {
113
+ const reading = await platform.read(passportId)
114
+ expect(reading.lineage.map((s) => s.op)).toEqual(['ISSUE', 'UPDATE', 'TRANSFER'])
115
+ const status = (name: string): string | undefined => reading.checks.find((c) => c.name === name)?.status
116
+ expect(status('recordEncoding')).toBe('pass')
117
+ expect(status('actorSignatures')).toBe('pass')
118
+ expect(status('publisherSignatures')).toBe('pass')
119
+ expect(status('linkage')).toBe('pass')
120
+ expect(status('evidenceAvailability')).toBe('pass')
121
+ expect(status('issuerAuthority')).toBe('pass')
122
+ // Nothing here is mined and no header source was asked.
123
+ expect(status('inclusion')).toBe('unknown')
124
+ })
125
+
126
+ it('lets the recipient retire the passport, and nothing follows', async () => {
127
+ const record = await latest()
128
+ const recipient = platform.custody.holderOf(record)
129
+ const outcome = await platform.writer.retire({ record, actor: recipient, reason: 'recycled' })
130
+ expect(outcome.entry.op).toBe('RETIRE')
131
+ expect(outcome.record.status).toBe('retired')
132
+ await expect(platform.writer.update({ record: await latest(), actor: recipient, payload, ownerFields: {} })).rejects.toMatchObject({ code: 'retired' })
133
+ })
134
+
135
+ it('signs a lifecycle claim on the other rail, by the recycler, from the EPCIS event it observed, without touching the passport', async () => {
136
+ const recycler = platform.parties.member('recycler-line-3')
137
+ const before = JSON.stringify(await latest())
138
+ const event = { type: 'ObjectEvent', eventID: 'urn:uuid:6c000000-0000-4000-8000-00000000c011', eventTime: '2026-03-02T08:00:00.000Z', eventTimeZoneOffset: '+00:00', epcList: [passportId], action: 'OBSERVE', bizStep: 'collecting', disposition: 'in_progress' }
139
+ const claim = await platform.claims.issue({ event, issuer: recycler, assertedRole: 'observer', expectedPassport: passportId, schemaCheck: eventSchemaCheck(gs1Dir()) })
140
+ const verified = await verifyEpcisLifecycleClaim(claim.bytes)
141
+ expect(verified.findings.signature.status).toBe('pass')
142
+ expect(verified.boundPassports).toEqual([passportId])
143
+ expect(claim.issuer).toBe(recycler.did)
144
+ expect((await platform.store.listClaims({ passportId })).length).toBe(1)
145
+ expect(JSON.stringify(await latest())).toBe(before)
146
+ })
147
+ })
@@ -0,0 +1,36 @@
1
+ import { afterEach, expect, it } from 'vitest'
2
+ import { loadConfig } from '../src/config.js'
3
+ import { mintPassportId } from '../src/identifiers.js'
4
+ import { openPlatform, type Platform } from '../src/platform.js'
5
+ import { DEMONSTRATION_NOTICE, samplePayload } from '../src/profiles.js'
6
+
7
+ let platform: Platform | undefined
8
+ afterEach(async () => { await platform?.close() })
9
+ async function writer(prefix: string) {
10
+ const config = loadConfig({ PASSPORT_HOST: 'passport.example', GS1_PREFIX: prefix, NETWORK: 'test', LIVE_PUBLISHING: 'false' })
11
+ platform = await openPlatform({ config, mode: 'test', log: () => {} })
12
+ const brand = platform.parties.brand('sample-brand')
13
+ const passportId = mintPassportId({ host: config.passportHost, prefix }, '1'.repeat(12 - prefix.length), 'NOTICE-1')
14
+ return { platform, brand, passportId, issue: (payload: Record<string, unknown>) => platform!.writer.issue({ brandId: 'sample-brand', brand, passportId, profile: 'general@2', payload }) }
15
+ }
16
+
17
+ it.each(['952', '952123'])('writes the demonstration statement first for a passport under prefix %s', async (prefix) => {
18
+ const { platform, brand, issue } = await writer(prefix)
19
+ const fields = samplePayload('general@2', false)
20
+ const genesis = await issue(fields)
21
+ expect(Object.entries(JSON.parse(genesis.state.payloadPublic))[0]).toEqual(['notice', DEMONSTRATION_NOTICE])
22
+ const translated = 'Ce passeport de démonstration ne décrit aucun produit réel.'
23
+ const updated = await platform.writer.update({ actor: brand, record: genesis.record, payload: { ...fields, notice: translated } })
24
+ expect(Object.entries(JSON.parse(updated.state.payloadPublic))[0]).toEqual(['notice', translated])
25
+ expect(Object.hasOwn(fields, 'notice')).toBe(false)
26
+ })
27
+
28
+ it('refuses the demonstration statement on a real-product configuration before signing a state', async () => {
29
+ const { platform, brand, passportId, issue } = await writer('123456')
30
+ await expect(issue(samplePayload('general@2', true))).rejects.toMatchObject({ code: 'demonstration-notice-unexpected' })
31
+ expect(await platform.store.getPassport(passportId)).toBeUndefined()
32
+ const genesis = await issue(samplePayload('general@2', false))
33
+ expect(JSON.parse(genesis.state.payloadPublic)).not.toHaveProperty('notice')
34
+ await expect(platform.writer.update({ record: genesis.record, actor: brand, payload: samplePayload('general@2', true) })).rejects.toMatchObject({ code: 'demonstration-notice-unexpected' })
35
+ expect((await platform.store.getPassport(passportId))?.states).toHaveLength(1)
36
+ })
@@ -0,0 +1,113 @@
1
+ // Keeps a test's network to the services the test itself started. Every way
2
+ // out of the process is replaced: `fetch`, a name lookup, a TCP or TLS
3
+ // connection and a datagram. A connection to this machine's loopback address
4
+ // on a port the test allowed goes through. Anything else is written down and
5
+ // refused, so a test asserts afterwards that nothing was attempted, and an
6
+ // attempt fails the test even where the code that made it caught the error
7
+ // and carried on.
8
+ //
9
+ // The replacements are made on the objects Node's own modules share, so they
10
+ // also reach a library that loaded `node:net` or `node:dns` before the guard
11
+ // was installed. A connection that was already open when the guard went on is
12
+ // not touched: the guard decides about new ones.
13
+ import dgram from 'node:dgram'
14
+ import dns from 'node:dns'
15
+ import net from 'node:net'
16
+
17
+ export interface NetworkGuard {
18
+ /** Every attempt that was refused: what was tried, and where to. */
19
+ attempts: string[]
20
+ /** Permit new connections to this port of the loopback address. */
21
+ allow(port: number | string): void
22
+ /** Puts back everything the guard replaced. */
23
+ restore(): void
24
+ }
25
+
26
+ type Patchable = Record<string, unknown>
27
+ const LOOPBACK = new Set(['127.0.0.1', '::1', 'localhost', '[::1]'])
28
+
29
+ /** The host and port a `connect` call names, in any of the forms Node takes them. */
30
+ function targetOf(args: unknown[]): { host: string; port: string } {
31
+ const first = Array.isArray(args[0]) ? (args[0] as unknown[])[0] : args[0]
32
+ if (first !== null && typeof first === 'object') {
33
+ const options = first as { host?: unknown; hostname?: unknown; port?: unknown; path?: unknown }
34
+ if (options.path != null) return { host: `unix:${String(options.path)}`, port: '' }
35
+ return { host: String(options.host ?? options.hostname ?? 'localhost'), port: String(options.port ?? '') }
36
+ }
37
+ if (typeof first === 'number' || (typeof first === 'string' && /^\d+$/.test(first))) return { host: typeof args[1] === 'string' ? args[1] : 'localhost', port: String(first) }
38
+ return { host: `unix:${String(first)}`, port: '' }
39
+ }
40
+
41
+ export function guardNetwork(): NetworkGuard {
42
+ const attempts: string[] = []
43
+ const ports = new Set<string>()
44
+ const undo: Array<() => void> = []
45
+ const permitted = (host: string, port: string): boolean => LOOPBACK.has(host) && ports.has(port)
46
+
47
+ const connect = net.Socket.prototype.connect
48
+ ;(net.Socket.prototype as unknown as Patchable).connect = function (this: net.Socket, ...args: unknown[]): unknown {
49
+ const { host, port } = targetOf(args)
50
+ if (!permitted(host, port)) {
51
+ attempts.push(`connect ${host}:${port}`)
52
+ throw new Error(`the network is kept to this test's own services: connect ${host}:${port}`)
53
+ }
54
+ return (connect as (...inner: unknown[]) => unknown).apply(this, args)
55
+ }
56
+ undo.push(() => {
57
+ net.Socket.prototype.connect = connect
58
+ })
59
+
60
+ const patchLookup = (owner: Patchable, name: string, label: string): void => {
61
+ const original = owner[name]
62
+ if (typeof original !== 'function') return
63
+ owner[name] = function (this: unknown, ...args: unknown[]): unknown {
64
+ const host = String(args[0])
65
+ if (!LOOPBACK.has(host) && !net.isIP(host)) {
66
+ attempts.push(`${label} ${host}`)
67
+ throw new Error(`the network is kept to this test's own services: ${label} ${host}`)
68
+ }
69
+ return (original as (...inner: unknown[]) => unknown).apply(this, args)
70
+ }
71
+ undo.push(() => {
72
+ owner[name] = original
73
+ })
74
+ }
75
+ for (const name of ['lookup', 'resolve', 'resolve4', 'resolve6', 'resolveAny']) {
76
+ patchLookup(dns as unknown as Patchable, name, `dns.${name}`)
77
+ patchLookup(dns.promises as unknown as Patchable, name, `dns.promises.${name}`)
78
+ }
79
+
80
+ const realFetch = globalThis.fetch
81
+ globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit): Promise<Response> => {
82
+ const url = new URL(typeof input === 'string' ? input : input instanceof URL ? input.href : input.url)
83
+ const port = url.port !== '' ? url.port : url.protocol === 'https:' ? '443' : '80'
84
+ if (!permitted(url.hostname, port)) {
85
+ attempts.push(`fetch ${url.origin}`)
86
+ throw new TypeError(`the network is kept to this test's own services: fetch ${url.origin}`)
87
+ }
88
+ return await realFetch(input, init)
89
+ }) as typeof globalThis.fetch
90
+ undo.push(() => {
91
+ globalThis.fetch = realFetch
92
+ })
93
+
94
+ for (const name of ['send', 'connect']) {
95
+ const owner = dgram.Socket.prototype as unknown as Patchable
96
+ const original = owner[name]
97
+ owner[name] = function (): never {
98
+ attempts.push(`datagram ${name}`)
99
+ throw new Error(`the network is kept to this test's own services: datagram ${name}`)
100
+ }
101
+ undo.push(() => {
102
+ owner[name] = original
103
+ })
104
+ }
105
+
106
+ return {
107
+ attempts,
108
+ allow: (port) => void ports.add(String(port)),
109
+ restore: () => {
110
+ for (const put of undo.reverse()) put()
111
+ },
112
+ }
113
+ }