@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,328 @@
1
+ // The validation engine is a setting. With no address the JSON-LD and SHACL
2
+ // libraries run in this process; with VALIDATOR_URL a validator service is
3
+ // asked instead. These tests run the same sector passport through both, and
4
+ // then take the service away: a stopped, unreachable or wrongly credentialled
5
+ // service must block a write exactly as missing libraries do, and must never
6
+ // read as a pass.
7
+ //
8
+ // The service here is the one @bsv/dpp-profiles ships, started in this
9
+ // process on the loopback address. It is the code the dpp-validator command
10
+ // and the validator image run.
11
+ import { once } from 'node:events'
12
+ import type { Server } from 'node:http'
13
+ import type { AddressInfo } from 'node:net'
14
+ import { format } from 'node:util'
15
+ import { afterAll, beforeAll, describe, expect, it, vi } from 'vitest'
16
+ import { startValidatorService, type ValidatorLogEntry, type ValidatorService } from '@bsv/dpp-profiles/validator-service'
17
+ import { loadConfig } from '../src/config.js'
18
+ import { openPlatform, type Platform } from '../src/platform.js'
19
+ import type { AuthorisedReading, PassportReading } from '../src/reader.js'
20
+ import { sectorExamples } from '../src/sector-examples.js'
21
+ import { createServer } from '../src/server.js'
22
+ import { openValidationEngine, validationEngineSettings } from '../src/validation-engine.js'
23
+ import { WriteRefused } from '../src/writer.js'
24
+
25
+ type Json = Record<string, unknown>
26
+
27
+ /** The service's token. It is in no fixture: wherever it turns up, it was copied there. */
28
+ const TOKEN = 'VALIDATOR-TOKEN-CANARY-58C3A1E7'
29
+ const base = { NETWORK: 'main', PASSPORT_HOST: 'passports.example.com', GS1_PREFIX: '952', LIVE_PUBLISHING: 'false' }
30
+ const brandId = 'brand-engine-1'
31
+
32
+ let service: ValidatorService
33
+ let withService: Platform
34
+ let inProcess: Platform
35
+ let server: Server
36
+ let api: string
37
+ const lines: string[] = []
38
+
39
+ const exampleFor = (platform: Platform, profile: string, serial: string): { passportId: string; product: Json } => {
40
+ const bound = platform.profiles.get(profile)!
41
+ const example = sectorExamples(bound, { host: 'passports.example.com', prefix: '952' })[0]!
42
+ const swap = (value: string): string => value.replaceAll(example.serial, serial)
43
+ return { passportId: swap(example.passportId), product: JSON.parse(swap(JSON.stringify(example.product))) as Json }
44
+ }
45
+ const issue = async (platform: Platform, profile: string, serial: string) => {
46
+ const { passportId, product } = exampleFor(platform, profile, serial)
47
+ return await platform.writer.issue({ brandId, brand: platform.parties.brand(brandId), passportId, profile, product })
48
+ }
49
+ const refusal = async (attempt: Promise<unknown>): Promise<WriteRefused> => {
50
+ try {
51
+ await attempt
52
+ } catch (cause) {
53
+ if (cause instanceof WriteRefused) return cause
54
+ throw cause
55
+ }
56
+ throw new Error('the write was not refused')
57
+ }
58
+ const get = async (path: string): Promise<any> => await (await fetch(`${api}${path}`)).json()
59
+
60
+ beforeAll(async () => {
61
+ service = await startValidatorService({ token: TOKEN })
62
+ withService = await openPlatform({ config: loadConfig({ ...base, VALIDATOR_URL: service.url, VALIDATOR_TOKEN: TOKEN }), mode: 'test', log: (line) => void lines.push(line) })
63
+ inProcess = await openPlatform({ config: loadConfig(base), mode: 'test', log: () => {} })
64
+ server = createServer({ platform: withService, devSession: { userId: 'developer', email: 'developer@localhost', name: 'Developer', brandIds: [brandId] } }).listen(0, '127.0.0.1')
65
+ await once(server, 'listening')
66
+ api = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
67
+ })
68
+
69
+ afterAll(async () => {
70
+ server.closeAllConnections()
71
+ server.close()
72
+ await service.close().catch(() => undefined)
73
+ await withService.close()
74
+ await inProcess.close()
75
+ })
76
+
77
+ describe('the validation engine, by configuration', () => {
78
+ it('reads the two settings and nothing else', () => {
79
+ expect(validationEngineSettings({})).toEqual({})
80
+ expect(validationEngineSettings({ VALIDATOR_URL: ' http://validator:8090 ', VALIDATOR_TOKEN: '' })).toEqual({ url: 'http://validator:8090' })
81
+ expect(validationEngineSettings({ VALIDATOR_URL: 'http://validator:8090', VALIDATOR_TOKEN: 'token' })).toEqual({ url: 'http://validator:8090', token: 'token' })
82
+ })
83
+
84
+ it('runs in this process by default, and in the service when VALIDATOR_URL names one', async () => {
85
+ expect(inProcess.profiles.engineKind).toBe('in-process')
86
+ expect(inProcess.profiles.engineProblem).toBeUndefined()
87
+ expect(withService.profiles.engineKind).toBe('service')
88
+ expect(withService.profiles.engineProblem).toBeUndefined()
89
+ // Start-up says which engine it reached, by its address, and never by its token.
90
+ expect(lines.some((line) => line.startsWith(`Validation engine: the validator service at ${service.url}`))).toBe(true)
91
+ expect(await get('/api/health')).toMatchObject({ validationEngine: true, validationEngineKind: 'service' })
92
+ expect((await get('/api/profiles/eu-battery%402')).engine).toEqual({ available: true, kind: 'service' })
93
+ })
94
+
95
+ it('gives the same answers either way: a valid document is written and read as passing, an invalid one is refused for the same cause', async () => {
96
+ for (const profile of ['eu-battery@2', 'eu-textile@2']) {
97
+ const readings: PassportReading[] = []
98
+ for (const [platform, mode] of [
99
+ [inProcess, 'IN'],
100
+ [withService, 'SV'],
101
+ ] as const) {
102
+ const written = await issue(platform, profile, `ENGINE-${mode}-0001`)
103
+ expect(written.entry.index).toBe('admitted')
104
+ readings.push(await platform.read(written.record.passportId))
105
+ }
106
+ const outcome = (reading: PassportReading) => reading.payloadChecks.map((check) => ({ status: check.publicView.status, cause: check.publicView.cause, steps: check.publicView.steps.map((step) => [step.step, step.status]), findings: check.publicView.findings.length, withheld: check.publicView.withheld }))
107
+ expect(outcome(readings[0]!)[0]!.status).toBe('pass')
108
+ expect(outcome(readings[1]!)).toEqual(outcome(readings[0]!))
109
+ expect(readings[1]!.checks.map((check) => [check.name, check.status, check.reasonCode])).toEqual(readings[0]!.checks.map((check) => [check.name, check.status, check.reasonCode]))
110
+ }
111
+ // A document about another item fails the same rule in both, before anything is signed.
112
+ const causes: unknown[] = []
113
+ for (const platform of [inProcess, withService]) {
114
+ const { product } = exampleFor(platform, 'eu-battery@2', 'ENGINE-OTHER-1')
115
+ const { passportId } = exampleFor(platform, 'eu-battery@2', 'ENGINE-MINE-1')
116
+ const refused = await refusal(platform.writer.issue({ brandId, brand: platform.parties.brand(brandId), passportId, profile: 'eu-battery@2', product }))
117
+ causes.push([refused.code, refused.data?.cause])
118
+ expect(await platform.store.getPassport(passportId)).toBeUndefined()
119
+ }
120
+ expect(causes).toEqual([
121
+ ['product-invalid', 'product-identity-mismatch'],
122
+ ['product-invalid', 'product-identity-mismatch'],
123
+ ])
124
+ })
125
+
126
+ it('blocks a write and reads as not checked when the service is stopped, exactly as missing libraries do', async () => {
127
+ const written = await issue(withService, 'eu-battery@2', 'ENGINE-STOP-0001')
128
+ const port = service.port
129
+ await service.close()
130
+
131
+ // The same refusal, by the same code, as a deployment whose libraries did not load.
132
+ const bare = await openPlatform({ config: loadConfig(base), mode: 'test', log: () => {}, loadEngineLibrary: async (name) => { throw new Error(`Cannot find package '${name}'`) } })
133
+ try {
134
+ const stopped = await refusal(issue(withService, 'eu-battery@2', 'ENGINE-STOP-0002'))
135
+ const missing = await refusal(issue(bare, 'eu-battery@2', 'ENGINE-STOP-0002'))
136
+ expect(stopped.code).toBe('product-not-validated')
137
+ expect(missing.code).toBe('product-not-validated')
138
+ expect(stopped.data?.cause).toBe(missing.data?.cause)
139
+ // Each says what is wrong with its own engine, and neither says the other's.
140
+ expect(stopped.message).toMatch(/The validation engine is not available: the validator service at http:\/\/127\.0\.0\.1:\d+ could not be reached/)
141
+ expect(stopped.message).toMatch(/Start it, or correct VALIDATOR_URL and VALIDATOR_TOKEN/)
142
+ expect(stopped.message).not.toMatch(/Install jsonld/)
143
+ expect(missing.message).toMatch(/Install jsonld@9\.0\.0 n3@2\.13\.12 shacl-engine@1\.1\.3/)
144
+ expect(stopped.message).not.toContain(TOKEN)
145
+ const { passportId } = exampleFor(withService, 'eu-battery@2', 'ENGINE-STOP-0002')
146
+ expect(await withService.store.getPassport(passportId)).toBeUndefined()
147
+ } finally {
148
+ await bare.close()
149
+ }
150
+
151
+ // A passport that read as passing is now not checked. Nothing that needs the engine passes without it.
152
+ const reading = await withService.read(written.record.passportId)
153
+ expect(reading.checks.find((check) => check.name === 'schema')).toMatchObject({ status: 'unknown', reasonCode: 'schema-unavailable' })
154
+ const view = reading.payloadChecks[0]!.publicView
155
+ expect(view).toMatchObject({ status: 'not-checked', cause: 'validator-unavailable' })
156
+ expect(view.summary).toMatch(/The validation engine is not available: the validator service at/)
157
+ expect(view.summary).toMatch(/A check that could not run is not a pass\./)
158
+ expect(view.steps.find((step) => step.step === 'passport-identity')?.status).toBe('not-checked')
159
+
160
+ // The API says so wherever a person looks: the health answer, the form's profile and the operations page.
161
+ expect(await get('/api/health')).toMatchObject({ validationEngine: false, validationEngineKind: 'service' })
162
+ const described = (await get('/api/profiles/eu-battery%402')).engine
163
+ expect(described).toMatchObject({ available: false, kind: 'service' })
164
+ expect(described.problem).toMatch(/could not be reached/)
165
+ expect(described.problem).not.toContain(TOKEN)
166
+ expect((await get('/api/operations')).profiles.engine).toMatchObject({ available: false, kind: 'service' })
167
+
168
+ // The service comes back at the same address. Nothing here is restarted: the next look finds it.
169
+ service = await startValidatorService({ token: TOKEN, port })
170
+ expect(await get('/api/health')).toMatchObject({ validationEngine: true })
171
+ expect((await get('/api/profiles/eu-battery%402')).engine).toEqual({ available: true, kind: 'service' })
172
+ expect((await issue(withService, 'eu-battery@2', 'ENGINE-STOP-0002')).entry.index).toBe('admitted')
173
+ expect((await withService.read(written.record.passportId)).payloadChecks[0]!.publicView.status).toBe('pass')
174
+ })
175
+
176
+ it('treats a service that refuses the token, or that is not there at all, the same way', async () => {
177
+ const wrong = await openValidationEngine({ url: service.url, token: 'not-the-token' })
178
+ expect(wrong.kind).toBe('service')
179
+ expect(wrong.problem).toMatch(/answered 401/)
180
+ const expansion = await wrong.engines.jsonLd!.toRdf({ document: {}, contexts: [] })
181
+ expect(expansion.ok).toBe(false)
182
+
183
+ const nowhere = await openValidationEngine({ url: 'http://127.0.0.1:9' })
184
+ expect(nowhere.problem).toMatch(/could not be reached/)
185
+ const platform = await openPlatform({ config: loadConfig({ ...base, VALIDATOR_URL: 'http://127.0.0.1:9' }), mode: 'test', log: () => {} })
186
+ try {
187
+ expect(platform.profiles.list().map((profile) => profile.profile)).toEqual(['eu-battery@1', 'eu-textile@1', 'eu-battery@2', 'eu-textile@2'])
188
+ expect((await refusal(issue(platform, 'eu-textile@2', 'ENGINE-NONE-0001'))).code).toBe('product-not-validated')
189
+ } finally {
190
+ await platform.close()
191
+ }
192
+ // Nothing that was logged or answered carries the token.
193
+ expect(lines.join('\n')).not.toContain(TOKEN)
194
+ })
195
+ })
196
+
197
+ describe('a restricted value, with the validator service configured', () => {
198
+ // With VALIDATOR_URL set, the whole document goes to the service when the holder's view or a write is checked, the
199
+ // restricted part included. This repeats the sweep of bound-http.test.ts for that arrangement: the value reaches the
200
+ // holder and the service, and nothing this application or the service prints, lists or answers to anyone else.
201
+ // A value that is in no fixture, no log line and no key: wherever it turns up, it was copied there.
202
+ const canary = 'RESTRICTED-CANARY-SERVICE-2B7D40E9'
203
+ const printed: string[] = []
204
+ const serviceLog: ValidatorLogEntry[] = []
205
+ const sentToService: string[] = []
206
+ const spies: Array<{ mockRestore: () => void }> = []
207
+ let sweepService: ValidatorService
208
+ let platform: Platform
209
+ let sweepServer: Server
210
+ let at: string
211
+
212
+ beforeAll(async () => {
213
+ // Everything the process prints is kept: the platform's own log, the console and the two streams under it.
214
+ for (const method of ['log', 'info', 'warn', 'error', 'debug'] as const) spies.push(vi.spyOn(console, method).mockImplementation((...args: unknown[]) => void printed.push(format(...args))))
215
+ for (const stream of [process.stdout, process.stderr]) {
216
+ const write = stream.write.bind(stream)
217
+ spies.push(
218
+ vi.spyOn(stream, 'write').mockImplementation(((chunk: unknown, ...rest: unknown[]) => {
219
+ printed.push(typeof chunk === 'string' ? chunk : Buffer.from(chunk as Uint8Array).toString('utf8'))
220
+ return (write as (...args: unknown[]) => boolean)(chunk, ...rest)
221
+ }) as typeof stream.write)
222
+ )
223
+ }
224
+ sweepService = await startValidatorService({ token: TOKEN, log: (entry) => void serviceLog.push(entry) })
225
+ // What the client sends the service, kept only to show the restricted part does reach it, so the search below is not empty by accident.
226
+ const realFetch = globalThis.fetch
227
+ spies.push(
228
+ vi.spyOn(globalThis, 'fetch').mockImplementation(async (input, init) => {
229
+ if (String(input instanceof Request ? input.url : input).startsWith(sweepService.url) && typeof init?.body === 'string') sentToService.push(init.body)
230
+ return await realFetch(input, init)
231
+ })
232
+ )
233
+ platform = await openPlatform({ config: loadConfig({ ...base, VALIDATOR_URL: sweepService.url, VALIDATOR_TOKEN: TOKEN }), mode: 'test', log: (line) => void printed.push(line) })
234
+ const party = platform.parties.brand(brandId)
235
+ await platform.store.saveBrand({ id: brandId, name: 'Engine brand', identityKey: party.identityKey, did: party.did, createdAt: new Date().toISOString() })
236
+ sweepServer = createServer({ platform, devSession: { userId: 'developer', email: 'developer@localhost', name: 'Developer', brandIds: [brandId] } }).listen(0, '127.0.0.1')
237
+ await once(sweepServer, 'listening')
238
+ at = `http://127.0.0.1:${(sweepServer.address() as AddressInfo).port}`
239
+ })
240
+
241
+ afterAll(async () => {
242
+ sweepServer.closeAllConnections()
243
+ sweepServer.close()
244
+ await sweepService.close().catch(() => undefined)
245
+ await platform.close()
246
+ for (const spy of spies) spy.mockRestore()
247
+ })
248
+
249
+ const call = async (path: string, body?: unknown): Promise<{ status: number; text: string; body: any }> => {
250
+ const response = await fetch(`${at}${path}`, body === undefined ? {} : { method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body) })
251
+ const text = await response.text()
252
+ return { status: response.status, text, body: text === '' ? undefined : JSON.parse(text) }
253
+ }
254
+ const ref = (passportId: string): string => encodeURIComponent(passportId)
255
+ /** The same restricted properties bound-http.test.ts plants the value in. */
256
+ const withCanary = (profile: string, product: Json): Json => {
257
+ const copy = structuredClone(product)
258
+ if (profile === 'eu-battery@2') {
259
+ copy['eubat:manufacturerIdentifier'] = canary
260
+ ;(copy['eubat:hasSupplyChainDueDiligence'] as Json)['eubat:auditBody'] = `${canary} audit body`
261
+ } else {
262
+ ;(copy['eutex:hasSubstancesOfConcern'] as Json[])[0]!['oec:substanceLocation'] = `${canary} location`
263
+ ;(copy['oec:hasOperatorInformation'] as Json)['gs1:organizationName'] = `${canary} operator`
264
+ }
265
+ return copy
266
+ }
267
+
268
+ it('reaches the holder and the service, and nothing this application or the service prints or answers to anyone else', async () => {
269
+ expect(platform.profiles.engineKind).toBe('service')
270
+ const seen: Array<[string, string]> = []
271
+ const keep = (where: string, text: string): void => void seen.push([where, text])
272
+
273
+ for (const [profile, serial] of [
274
+ ['eu-battery@2', 'SV-LEAK-BAT-0001'],
275
+ ['eu-textile@2', 'SV-LEAK-TEX-0001'],
276
+ ] as const) {
277
+ const bound = platform.profiles.get(profile)!
278
+ const example = sectorExamples(bound, { host: 'passports.example.com', prefix: '952' })[0]!
279
+ const swap = (value: string): string => value.replaceAll(example.serial, serial)
280
+ const passportId = swap(example.passportId)
281
+ const product = withCanary(profile, JSON.parse(swap(JSON.stringify(example.product))) as Json)
282
+
283
+ // Issued, then updated, so the value passes through both write paths and is checked by the service each time.
284
+ const issued = await call(`/api/brands/${brandId}/passports`, { profile, itemReference: example.itemReference, serial, product })
285
+ expect(issued.status).toBe(200)
286
+ keep(`issue response, ${profile}`, issued.text)
287
+ const updated = await call(`/api/passports/${ref(passportId)}/update`, { product: { ...product, 'oec:lastUpdated': '2026-11-16T08:00:00Z' } })
288
+ expect(updated.status).toBe(200)
289
+ keep(`update response, ${profile}`, updated.text)
290
+ // A write the service's answer refuses, with the value inside the document: the refusal goes to the writer and is not printed.
291
+ const broken = structuredClone(product)
292
+ delete broken['oec:passportStatus']
293
+ const refused = await call(`/api/brands/${brandId}/passports`, { profile, itemReference: example.itemReference, serial: `${serial}-X`, product: broken })
294
+ expect(refused.status).toBe(409)
295
+ expect(refused.body.error).toBe('product-invalid')
296
+
297
+ // The control: the holder's view carries the value, and was checked by the service.
298
+ const asked = serviceLog.length
299
+ const authorised = await call(`/api/passports/${ref(passportId)}/authorised-view`, {})
300
+ expect(authorised.text).toContain(canary)
301
+ expect((authorised.body as AuthorisedReading).authorisedView.status).toBe('pass')
302
+ expect(serviceLog.slice(asked).filter((entry) => entry.route === 'expand' || entry.route === 'validate').length).toBeGreaterThan(0)
303
+
304
+ // Everything another reader can ask for.
305
+ keep(`journal view, ${profile}`, (await call(`/api/passports/${ref(passportId)}`)).text)
306
+ keep(`verify, ${profile}`, (await call(`/api/verify?passportId=${ref(passportId)}`)).text)
307
+ }
308
+ keep('passport list', (await call(`/api/brands/${brandId}/passports`)).text)
309
+ keep('operations', (await call('/api/operations')).text)
310
+ keep('health', (await call('/api/health')).text)
311
+ keep('profiles', (await call('/api/profiles/eu-battery%402')).text)
312
+ keep('journal', JSON.stringify(await platform.store.listPassports()))
313
+ keep('everything printed', printed.join('\n'))
314
+ keep('the service log', JSON.stringify(serviceLog))
315
+
316
+ // The value did go to the service: the restricted part is in what the client sent. So an empty search is not an accident.
317
+ expect(sentToService.some((body) => body.includes(canary))).toBe(true)
318
+ // The log followed every request, the listings did return the passports and the journal holds the sealed parts.
319
+ expect(serviceLog.length).toBeGreaterThan(4)
320
+ expect(serviceLog.every((entry) => Object.keys(entry).sort().join() === 'durationMs,method,outcome,requestBytes,responseBytes,route,status')).toBe(true)
321
+ expect(seen.find(([where]) => where === 'passport list')![1]).toContain('SV-LEAK-BAT-0001')
322
+ expect(seen.find(([where]) => where === 'journal')![1]).toContain('ciphertext')
323
+
324
+ const leaks = seen.filter(([, text]) => text.includes(canary)).map(([where]) => where)
325
+ expect(leaks).toEqual([])
326
+ expect(printed.join('\n')).not.toContain(TOKEN)
327
+ })
328
+ })
@@ -0,0 +1,38 @@
1
+ import { mkdtempSync, rmSync } from 'node:fs'
2
+ import { tmpdir } from 'node:os'
3
+ import { join } from 'node:path'
4
+ import { Monitor, Task, Wallet } from '@bsv/wallet-toolbox'
5
+ import { expect, it, vi } from 'vitest'
6
+ import { openToolboxWallet } from '../src/wallet.js'
7
+
8
+ it('starts only the header and proof tasks for the wallet and stops the monitor before closing', async () => {
9
+ const folder = mkdtempSync(join(tmpdir(), 'dpp-wallet-monitor-'))
10
+ // Capture the real scheduler before its first network poll.
11
+ let finish!: () => void
12
+ const active = new Promise<void>(resolve => { finish = resolve })
13
+ const started = vi.spyOn(Monitor.prototype, 'startTasks').mockReturnValue(active)
14
+ const stopped = vi.spyOn(Monitor.prototype, 'stopTasks')
15
+ const destroyed = vi.spyOn(Wallet.prototype, 'destroy')
16
+ try {
17
+ const wallet = await openToolboxWallet({ network: 'test', rootKeyHex: '11'.repeat(32), filePath: join(folder, 'wallet.sqlite') })
18
+ try {
19
+ expect(started).toHaveBeenCalledOnce()
20
+ const monitor = started.mock.instances[0]!
21
+ expect(monitor._tasks.map(task => task.constructor)).toEqual([Task.TaskNewHeader, Task.TaskCheckForProofs])
22
+ expect(monitor.options.maxRebroadcastAttempts).toBe(0)
23
+ } finally {
24
+ const closing = wallet.close()
25
+ try {
26
+ expect(stopped.mock.instances).toEqual(started.mock.instances)
27
+ expect(destroyed).not.toHaveBeenCalled()
28
+ } finally {
29
+ finish()
30
+ await closing
31
+ }
32
+ }
33
+ expect(destroyed).toHaveBeenCalledOnce()
34
+ } finally {
35
+ vi.restoreAllMocks()
36
+ rmSync(folder, { recursive: true, force: true })
37
+ }
38
+ })