@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.
Files changed (143) hide show
  1. package/NOTICE +2 -0
  2. package/PATENTS +12 -0
  3. package/README.md +26 -6
  4. package/dist/index.js +36 -8
  5. package/package.json +9 -5
  6. package/template/Dockerfile +4 -2
  7. package/template/README.md +297 -42
  8. package/template/_env.example +82 -13
  9. package/template/_github/workflows/ci.yml +3 -3
  10. package/template/apps/api/API.md +86 -16
  11. package/template/apps/api/package.json +9 -4
  12. package/template/apps/api/src/bound-profiles.ts +590 -0
  13. package/template/apps/api/src/claims.ts +175 -56
  14. package/template/apps/api/src/cli.ts +64 -7
  15. package/template/apps/api/src/config.ts +124 -10
  16. package/template/apps/api/src/custody.ts +241 -69
  17. package/template/apps/api/src/dev-index.ts +58 -9
  18. package/template/apps/api/src/env-file.ts +55 -0
  19. package/template/apps/api/src/epcis/exchange.ts +434 -0
  20. package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
  21. package/template/apps/api/src/epcis/routes.ts +364 -0
  22. package/template/apps/api/src/epcis/sources.ts +142 -0
  23. package/template/apps/api/src/go-live.ts +226 -0
  24. package/template/apps/api/src/http-error.ts +15 -0
  25. package/template/apps/api/src/identifiers.ts +1 -1
  26. package/template/apps/api/src/index-client.ts +131 -6
  27. package/template/apps/api/src/index-projects.ts +53 -0
  28. package/template/apps/api/src/lifecycle-authority.ts +49 -0
  29. package/template/apps/api/src/lifecycle.ts +485 -0
  30. package/template/apps/api/src/main.ts +10 -2
  31. package/template/apps/api/src/parties.ts +2 -2
  32. package/template/apps/api/src/platform.ts +72 -17
  33. package/template/apps/api/src/portability/commands.ts +224 -0
  34. package/template/apps/api/src/portability/export.ts +708 -0
  35. package/template/apps/api/src/portability/package.ts +270 -0
  36. package/template/apps/api/src/portability/restore.ts +863 -0
  37. package/template/apps/api/src/profiles.ts +38 -13
  38. package/template/apps/api/src/reader.ts +172 -3
  39. package/template/apps/api/src/resolver.ts +159 -0
  40. package/template/apps/api/src/sector-examples.ts +390 -0
  41. package/template/apps/api/src/server.ts +253 -60
  42. package/template/apps/api/src/store.ts +198 -21
  43. package/template/apps/api/src/validation-engine.ts +172 -0
  44. package/template/apps/api/src/wallet.ts +30 -17
  45. package/template/apps/api/src/worker.ts +20 -13
  46. package/template/apps/api/src/writer.ts +383 -131
  47. package/template/apps/api/test/bound-http.test.ts +496 -0
  48. package/template/apps/api/test/bound-profiles.test.ts +547 -0
  49. package/template/apps/api/test/config.test.ts +148 -3
  50. package/template/apps/api/test/custody-journal.test.ts +415 -0
  51. package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
  52. package/template/apps/api/test/custom-profile.test.ts +167 -0
  53. package/template/apps/api/test/env-file.test.ts +53 -0
  54. package/template/apps/api/test/epcis-fixtures.ts +270 -0
  55. package/template/apps/api/test/epcis-http.test.ts +1179 -0
  56. package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
  57. package/template/apps/api/test/epcis-separation.test.ts +253 -0
  58. package/template/apps/api/test/epcis-web.test.ts +230 -0
  59. package/template/apps/api/test/exit-exercise.test.ts +1038 -0
  60. package/template/apps/api/test/external-index.test.ts +3 -2
  61. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
  62. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
  63. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
  64. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
  65. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
  66. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
  67. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
  68. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
  69. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
  70. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
  71. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
  72. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
  73. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
  74. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
  75. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
  76. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
  77. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
  78. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
  79. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
  80. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
  81. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
  82. package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
  83. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
  84. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
  85. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
  86. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
  87. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
  88. package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
  89. package/template/apps/api/test/go-live.test.ts +179 -0
  90. package/template/apps/api/test/gs1-global-setup.ts +33 -0
  91. package/template/apps/api/test/gs1-test-env.ts +5 -0
  92. package/template/apps/api/test/identifier-host.test.ts +256 -0
  93. package/template/apps/api/test/index-projects.test.ts +81 -0
  94. package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
  95. package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
  96. package/template/apps/api/test/lifecycle.test.ts +17 -6
  97. package/template/apps/api/test/manifest-notice.test.ts +36 -0
  98. package/template/apps/api/test/network-guard.ts +113 -0
  99. package/template/apps/api/test/portability.test.ts +655 -0
  100. package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
  101. package/template/apps/api/test/retired-profiles.test.ts +216 -0
  102. package/template/apps/api/test/sector-cutover.test.ts +95 -0
  103. package/template/apps/api/test/sector-forms.test.ts +420 -0
  104. package/template/apps/api/test/unjoined-index.test.ts +62 -0
  105. package/template/apps/api/test/validation-engine.test.ts +328 -0
  106. package/template/apps/api/test/wallet-monitor.test.ts +38 -0
  107. package/template/apps/api/test/writer-journal.test.ts +327 -0
  108. package/template/apps/api/vitest.config.ts +3 -0
  109. package/template/apps/web/src/app.tsx +8 -4
  110. package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
  111. package/template/apps/web/src/components/bound/field-view.tsx +237 -0
  112. package/template/apps/web/src/components/bound/pieces.tsx +169 -0
  113. package/template/apps/web/src/components/bound/readings.tsx +152 -0
  114. package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
  115. package/template/apps/web/src/components/claim-dialog.tsx +344 -0
  116. package/template/apps/web/src/components/epcis-events.tsx +119 -0
  117. package/template/apps/web/src/components/layout.tsx +17 -0
  118. package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
  119. package/template/apps/web/src/components/passport-form.tsx +2 -2
  120. package/template/apps/web/src/components/read-passport.tsx +4 -3
  121. package/template/apps/web/src/components/reading.tsx +32 -39
  122. package/template/apps/web/src/lib/api.ts +136 -26
  123. package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
  124. package/template/apps/web/src/lib/bound/display.ts +122 -0
  125. package/template/apps/web/src/lib/bound/fields.ts +128 -0
  126. package/template/apps/web/src/lib/bound/form-model.ts +521 -0
  127. package/template/apps/web/src/lib/bound/forms.ts +15 -0
  128. package/template/apps/web/src/lib/bound/identity.ts +48 -0
  129. package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
  130. package/template/apps/web/src/lib/bound/units.ts +37 -0
  131. package/template/apps/web/src/lib/epcis.ts +345 -0
  132. package/template/apps/web/src/lib/format.ts +27 -4
  133. package/template/apps/web/src/lib/lifecycle.ts +350 -0
  134. package/template/apps/web/src/pages/accept.tsx +8 -3
  135. package/template/apps/web/src/pages/events.tsx +388 -0
  136. package/template/apps/web/src/pages/new-passport.tsx +25 -2
  137. package/template/apps/web/src/pages/operations.tsx +22 -3
  138. package/template/apps/web/src/pages/passport.tsx +226 -162
  139. package/template/apps/web/src/pages/public-passport.tsx +50 -10
  140. package/template/apps/web/src/pages/wallet.tsx +1 -1
  141. package/template/apps/web/vite.config.ts +12 -4
  142. package/template/deploy/compose.yml +14 -2
  143. package/template/package.json +9 -3
@@ -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
+ }
@@ -5,14 +5,17 @@
5
5
  // the code the live platform runs: the writer's six steps, the index's real
6
6
  // admission rules, managed custody, claims, and the reader's report.
7
7
  import { afterAll, beforeAll, describe, expect, it } from 'vitest'
8
- import { verifyLifecycleClaim } from '@bsv/dpp-protocol'
8
+ import { verifyEpcisLifecycleClaim } from '@bsv/dpp-credentials/epcis-lifecycle'
9
9
  import { loadConfig } from '../src/config.js'
10
+ import { managedParties } from '../src/parties.js'
10
11
  import { mintPassportId } from '../src/identifiers.js'
12
+ import { eventSchemaCheck } from '../src/lifecycle.js'
11
13
  import { openPlatform, type Platform } from '../src/platform.js'
12
14
  import { samplePayload } from '../src/profiles.js'
13
15
  import type { PassportRecord } from '../src/store.js'
14
16
  import { pendingDuties, runDuties } from '../src/worker.js'
15
17
  import { WriteRefused } from '../src/writer.js'
18
+ import { gs1Dir } from './epcis-fixtures.js'
16
19
 
17
20
  const config = loadConfig({ NETWORK: 'main', PASSPORT_HOST: 'passports.example.com', GS1_PREFIX: '952', LIVE_PUBLISHING: 'false' })
18
21
  let platform: Platform
@@ -22,8 +25,11 @@ let passportId: string
22
25
  let payload: Record<string, unknown>
23
26
 
24
27
  beforeAll(async () => {
25
- platform = await openPlatform({ config, mode: 'test', log: () => {} })
26
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
+ }) } })
27
33
  payload = samplePayload(profile, true)
28
34
  })
29
35
 
@@ -126,11 +132,16 @@ describe('a passport lifecycle under managed custody', () => {
126
132
  await expect(platform.writer.update({ record: await latest(), actor: recipient, payload, ownerFields: {} })).rejects.toMatchObject({ code: 'retired' })
127
133
  })
128
134
 
129
- it('signs a lifecycle claim on the other rail, by the recycler, without touching the passport', async () => {
135
+ it('signs a lifecycle claim on the other rail, by the recycler, from the EPCIS event it observed, without touching the passport', async () => {
130
136
  const recycler = platform.parties.member('recycler-line-3')
131
- const claim = await platform.claims.sign({ passport: await latest(), issuer: recycler, eventType: 'Disposition' })
132
- expect(verifyLifecycleClaim(claim.claim).signature).toBe('verified')
133
- expect(claim.claim.issuer).toBe(recycler.did)
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)
134
144
  expect((await platform.store.listClaims({ passportId })).length).toBe(1)
145
+ expect(JSON.stringify(await latest())).toBe(before)
135
146
  })
136
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
+ }