@bsv/create-dpp-app 0.1.0-beta.1 → 0.1.0-beta.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/NOTICE +2 -0
- package/PATENTS +12 -0
- package/README.md +26 -6
- package/dist/index.js +36 -8
- package/package.json +9 -5
- package/template/Dockerfile +4 -2
- package/template/README.md +297 -42
- package/template/_env.example +82 -13
- package/template/_github/workflows/ci.yml +3 -3
- package/template/apps/api/API.md +86 -16
- package/template/apps/api/package.json +9 -4
- package/template/apps/api/src/bound-profiles.ts +590 -0
- package/template/apps/api/src/claims.ts +175 -56
- package/template/apps/api/src/cli.ts +64 -7
- package/template/apps/api/src/config.ts +124 -10
- package/template/apps/api/src/custody.ts +241 -69
- package/template/apps/api/src/dev-index.ts +58 -9
- package/template/apps/api/src/env-file.ts +55 -0
- package/template/apps/api/src/epcis/exchange.ts +434 -0
- package/template/apps/api/src/epcis/mongo-storage.ts +381 -0
- package/template/apps/api/src/epcis/routes.ts +364 -0
- package/template/apps/api/src/epcis/sources.ts +142 -0
- package/template/apps/api/src/go-live.ts +226 -0
- package/template/apps/api/src/http-error.ts +15 -0
- package/template/apps/api/src/identifiers.ts +1 -1
- package/template/apps/api/src/index-client.ts +131 -6
- package/template/apps/api/src/index-projects.ts +53 -0
- package/template/apps/api/src/lifecycle-authority.ts +49 -0
- package/template/apps/api/src/lifecycle.ts +485 -0
- package/template/apps/api/src/main.ts +10 -2
- package/template/apps/api/src/parties.ts +2 -2
- package/template/apps/api/src/platform.ts +72 -17
- package/template/apps/api/src/portability/commands.ts +224 -0
- package/template/apps/api/src/portability/export.ts +708 -0
- package/template/apps/api/src/portability/package.ts +270 -0
- package/template/apps/api/src/portability/restore.ts +863 -0
- package/template/apps/api/src/profiles.ts +38 -13
- package/template/apps/api/src/reader.ts +172 -3
- package/template/apps/api/src/resolver.ts +159 -0
- package/template/apps/api/src/sector-examples.ts +390 -0
- package/template/apps/api/src/server.ts +253 -60
- package/template/apps/api/src/store.ts +198 -21
- package/template/apps/api/src/validation-engine.ts +172 -0
- package/template/apps/api/src/wallet.ts +30 -17
- package/template/apps/api/src/worker.ts +20 -13
- package/template/apps/api/src/writer.ts +383 -131
- package/template/apps/api/test/bound-http.test.ts +496 -0
- package/template/apps/api/test/bound-profiles.test.ts +547 -0
- package/template/apps/api/test/config.test.ts +148 -3
- package/template/apps/api/test/custody-journal.test.ts +415 -0
- package/template/apps/api/test/custody-recovery-profile.test.ts +224 -0
- package/template/apps/api/test/custom-profile.test.ts +167 -0
- package/template/apps/api/test/env-file.test.ts +53 -0
- package/template/apps/api/test/epcis-fixtures.ts +270 -0
- package/template/apps/api/test/epcis-http.test.ts +1179 -0
- package/template/apps/api/test/epcis-mongo-storage.test.ts +313 -0
- package/template/apps/api/test/epcis-separation.test.ts +253 -0
- package/template/apps/api/test/epcis-web.test.ts +230 -0
- package/template/apps/api/test/exit-exercise.test.ts +1038 -0
- package/template/apps/api/test/external-index.test.ts +3 -2
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/background.ttl +33 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/binding.json +141 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/context.jsonld +36 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/product.schema.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/shapes.ttl +112 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-gtin.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/conflicting-serial.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/granularity-mismatch.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item-gtin-13.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/item.json +42 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/missing-required-property.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/model-as-subject.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/no-passport-identifier.json +43 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/other-product.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/part-not-dishwasher-safe.json +45 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-artefact.json +19 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/altered-background.ttl +33 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-binding.json +141 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/conflicting-second-registration.json +19 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/registration/untrusted-binding.json +13 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/unlisted-context.json +47 -0
- package/template/apps/api/test/fixtures/custom-profile/example-bottle@1/vectors/wrong-binding-digest.json +44 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/binding.json +88 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/product.schema.json +25 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/item.json +26 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/missing-required-property.json +27 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/no-passport-identifier.json +27 -0
- package/template/apps/api/test/fixtures/custom-profile/example-notebook@1/vectors/other-product.json +28 -0
- package/template/apps/api/test/go-live.test.ts +179 -0
- package/template/apps/api/test/gs1-global-setup.ts +33 -0
- package/template/apps/api/test/gs1-test-env.ts +5 -0
- package/template/apps/api/test/identifier-host.test.ts +256 -0
- package/template/apps/api/test/index-projects.test.ts +81 -0
- package/template/apps/api/test/lifecycle-claims.test.ts +546 -0
- package/template/apps/api/test/lifecycle-fixtures.ts +167 -0
- package/template/apps/api/test/lifecycle.test.ts +17 -6
- package/template/apps/api/test/manifest-notice.test.ts +36 -0
- package/template/apps/api/test/network-guard.ts +113 -0
- package/template/apps/api/test/portability.test.ts +655 -0
- package/template/apps/api/test/profile-bundle-resolver.test.ts +198 -0
- package/template/apps/api/test/retired-profiles.test.ts +216 -0
- package/template/apps/api/test/sector-cutover.test.ts +95 -0
- package/template/apps/api/test/sector-forms.test.ts +420 -0
- package/template/apps/api/test/unjoined-index.test.ts +62 -0
- package/template/apps/api/test/validation-engine.test.ts +328 -0
- package/template/apps/api/test/wallet-monitor.test.ts +38 -0
- package/template/apps/api/test/writer-journal.test.ts +327 -0
- package/template/apps/api/vitest.config.ts +3 -0
- package/template/apps/web/src/app.tsx +8 -4
- package/template/apps/web/src/components/bound/bound-passport-form.tsx +368 -0
- package/template/apps/web/src/components/bound/field-view.tsx +237 -0
- package/template/apps/web/src/components/bound/pieces.tsx +169 -0
- package/template/apps/web/src/components/bound/readings.tsx +152 -0
- package/template/apps/web/src/components/bound/structured-value.tsx +114 -0
- package/template/apps/web/src/components/claim-dialog.tsx +344 -0
- package/template/apps/web/src/components/epcis-events.tsx +119 -0
- package/template/apps/web/src/components/layout.tsx +17 -0
- package/template/apps/web/src/components/lifecycle-claims.tsx +199 -0
- package/template/apps/web/src/components/passport-form.tsx +2 -2
- package/template/apps/web/src/components/read-passport.tsx +4 -3
- package/template/apps/web/src/components/reading.tsx +32 -39
- package/template/apps/web/src/lib/api.ts +136 -26
- package/template/apps/web/src/lib/bound/battery-form.ts +269 -0
- package/template/apps/web/src/lib/bound/display.ts +122 -0
- package/template/apps/web/src/lib/bound/fields.ts +128 -0
- package/template/apps/web/src/lib/bound/form-model.ts +521 -0
- package/template/apps/web/src/lib/bound/forms.ts +15 -0
- package/template/apps/web/src/lib/bound/identity.ts +48 -0
- package/template/apps/web/src/lib/bound/textile-form.ts +236 -0
- package/template/apps/web/src/lib/bound/units.ts +37 -0
- package/template/apps/web/src/lib/epcis.ts +345 -0
- package/template/apps/web/src/lib/format.ts +27 -4
- package/template/apps/web/src/lib/lifecycle.ts +350 -0
- package/template/apps/web/src/pages/accept.tsx +8 -3
- package/template/apps/web/src/pages/events.tsx +388 -0
- package/template/apps/web/src/pages/new-passport.tsx +25 -2
- package/template/apps/web/src/pages/operations.tsx +22 -3
- package/template/apps/web/src/pages/passport.tsx +226 -162
- package/template/apps/web/src/pages/public-passport.tsx +50 -10
- package/template/apps/web/src/pages/wallet.tsx +1 -1
- package/template/apps/web/vite.config.ts +12 -4
- package/template/deploy/compose.yml +14 -2
- package/template/package.json +9 -3
|
@@ -1,15 +1,160 @@
|
|
|
1
|
+
import { inspect } from 'node:util'
|
|
1
2
|
import { describe, expect, it } from 'vitest'
|
|
2
|
-
import { loadConfig } from '../src/config.js'
|
|
3
|
+
import { KNOWN_INDEX_HOSTS, loadConfig } from '../src/config.js'
|
|
3
4
|
|
|
4
5
|
const rootKey = '11'.repeat(32)
|
|
6
|
+
const token = 'a'.repeat(64)
|
|
5
7
|
|
|
6
8
|
describe('configuration', () => {
|
|
7
9
|
it('runs without an index in development', () => {
|
|
8
10
|
expect(loadConfig({ LIVE_PUBLISHING: 'false' }).index.url).toBeUndefined()
|
|
11
|
+
expect(loadConfig({ LIVE_PUBLISHING: 'false' }).index.joined).toBe(false)
|
|
9
12
|
})
|
|
10
13
|
|
|
11
|
-
it('
|
|
14
|
+
it('has joined an index only with its address and both tokens', () => {
|
|
15
|
+
expect(loadConfig({ INDEX_URL: 'http://index.example:8080/' }).index.joined).toBe(false)
|
|
16
|
+
expect(loadConfig({ INDEX_URL: 'http://index.example:8080/', INDEX_SUBMIT_TOKEN: token }).index.joined).toBe(false)
|
|
17
|
+
const joined = loadConfig({ INDEX_URL: 'http://index.example:8080/', INDEX_SUBMIT_TOKEN: token, INDEX_CALLBACK_TOKEN: token }).index
|
|
18
|
+
expect(joined.joined).toBe(true)
|
|
19
|
+
expect(joined.url).toBe('http://index.example:8080')
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
it('limits draft admission to a known retraction-capable index or its configured base URL', () => {
|
|
23
|
+
expect(loadConfig({ INDEX_URL: 'https://dpp-overlay-testnet.bsvb.net' }).index.supportsRetraction).toBe(true)
|
|
24
|
+
expect(loadConfig({ INDEX_URL: 'https://unknown.example' }).index.supportsRetraction).toBe(false)
|
|
25
|
+
const retraction = { INDEX_RETRACTION_URL: 'https://index.example/a/' }
|
|
26
|
+
expect(loadConfig({ ...retraction, INDEX_URL: 'https://index.example/a' }).index.supportsRetraction).toBe(true)
|
|
27
|
+
expect(loadConfig({ ...retraction, INDEX_URL: 'https://index.example/b' }).index.supportsRetraction).toBe(false)
|
|
28
|
+
expect(loadConfig({ ...retraction, INDEX_URL: 'https://replacement.example/a' }).index.supportsRetraction).toBe(false)
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
it('refuses to write to the chain without an index it has joined', () => {
|
|
12
32
|
expect(() => loadConfig({ LIVE_PUBLISHING: 'true', WALLET_ROOT_KEY: rootKey })).toThrow(/INDEX_URL/)
|
|
13
|
-
expect(loadConfig({ LIVE_PUBLISHING: 'true', WALLET_ROOT_KEY: rootKey, INDEX_URL: 'http://index.example:8080/' })
|
|
33
|
+
expect(() => loadConfig({ LIVE_PUBLISHING: 'true', WALLET_ROOT_KEY: rootKey, INDEX_URL: 'http://index.example:8080/' })).toThrow(/go-live/)
|
|
34
|
+
expect(loadConfig({ LIVE_PUBLISHING: 'true', WALLET_ROOT_KEY: rootKey, INDEX_URL: 'http://index.example:8080/', INDEX_SUBMIT_TOKEN: token, INDEX_CALLBACK_TOKEN: token }).livePublishing).toBe(true)
|
|
35
|
+
})
|
|
36
|
+
|
|
37
|
+
it('refuses a secret copied from the example file, naming the setting and never the value', () => {
|
|
38
|
+
for (const [name, value] of [
|
|
39
|
+
['AUTH_SECRET', 'change-me-to-32-random-bytes-hex'],
|
|
40
|
+
['BRAND_ROOT_SECRET', 'development-only-brand-secret-replace-me'],
|
|
41
|
+
['MANAGED_IDENTITY_SECRET', 'development-only-anything'],
|
|
42
|
+
]) {
|
|
43
|
+
let message = ''
|
|
44
|
+
try {
|
|
45
|
+
loadConfig({ [name]: value })
|
|
46
|
+
} catch (cause) {
|
|
47
|
+
message = (cause as Error).message
|
|
48
|
+
}
|
|
49
|
+
expect(message).toContain(name)
|
|
50
|
+
expect(message).toContain('openssl rand -hex 32')
|
|
51
|
+
expect(message).not.toContain(value)
|
|
52
|
+
}
|
|
53
|
+
// Unset, the development default stands so a bare checkout runs.
|
|
54
|
+
expect(loadConfig({}).authSecret).toMatch(/^development-only-/)
|
|
55
|
+
expect(loadConfig({ AUTH_SECRET: 'b'.repeat(64) }).authSecret).toBe('b'.repeat(64))
|
|
56
|
+
})
|
|
57
|
+
|
|
58
|
+
it('reads the EPCIS query sources, and keeps each credential behind a function', () => {
|
|
59
|
+
// The store is the application database unless a folder is chosen: the default says so.
|
|
60
|
+
expect(loadConfig({}).epcis).toEqual({ gs1Dir: 'local/gs1', gs1Offline: false, sources: [], storage: { kind: 'mongodb' } })
|
|
61
|
+
const secret = 'configured-credential-93be11'
|
|
62
|
+
const config = loadConfig({
|
|
63
|
+
DPP_GS1_ARTEFACTS_DIR: '/var/lib/dpp/gs1',
|
|
64
|
+
DPP_GS1_ARTEFACTS_OFFLINE: 'true',
|
|
65
|
+
EPCIS_SOURCES: 'supplier-a, line-2',
|
|
66
|
+
EPCIS_SOURCE_SUPPLIER_A_URL: 'https://events.example.org/epcis/',
|
|
67
|
+
EPCIS_SOURCE_SUPPLIER_A_ORIGINS: 'https://events.example.org, https://pages.example.org',
|
|
68
|
+
EPCIS_SOURCE_SUPPLIER_A_BEARER_TOKEN: secret,
|
|
69
|
+
EPCIS_SOURCE_SUPPLIER_A_REPEAT_LISTS: 'true',
|
|
70
|
+
EPCIS_SOURCE_LINE_2_URL: 'http://127.0.0.1:8080/epcis',
|
|
71
|
+
EPCIS_SOURCE_LINE_2_LOCAL_TEST: 'true',
|
|
72
|
+
EPCIS_SOURCE_LINE_2_BASIC_USER: 'operator',
|
|
73
|
+
EPCIS_SOURCE_LINE_2_BASIC_PASSWORD: secret,
|
|
74
|
+
})
|
|
75
|
+
expect(config.epcis).toMatchObject({ gs1Dir: '/var/lib/dpp/gs1', gs1Offline: true })
|
|
76
|
+
const [first, second] = config.epcis.sources
|
|
77
|
+
expect(first).toMatchObject({ sourceId: 'supplier-a', baseUrl: 'https://events.example.org/epcis', permittedOrigins: ['https://events.example.org', 'https://pages.example.org'], localTest: false, repeatListParameters: true, credentialScheme: 'bearer' })
|
|
78
|
+
// The base address's own origin is the one permitted origin when none is listed. The local-test option is off unless it is set.
|
|
79
|
+
expect(second).toMatchObject({ sourceId: 'line-2', baseUrl: 'http://127.0.0.1:8080/epcis', permittedOrigins: ['http://127.0.0.1:8080'], localTest: true, repeatListParameters: false, credentialScheme: 'basic' })
|
|
80
|
+
expect(first!.credentials!()).toEqual({ scheme: 'bearer', token: secret })
|
|
81
|
+
expect(second!.credentials!()).toEqual({ scheme: 'basic', username: 'operator', password: secret })
|
|
82
|
+
// Serialising or printing the configuration shows that a credential is set, never what it is.
|
|
83
|
+
expect(JSON.stringify(config.epcis)).not.toContain(secret)
|
|
84
|
+
expect(inspect(config.epcis, { depth: 10, showHidden: true })).not.toContain(secret)
|
|
85
|
+
const header = loadConfig({ EPCIS_SOURCES: 'gate', EPCIS_SOURCE_GATE_URL: 'https://gate.example.org', EPCIS_SOURCE_GATE_HEADER_NAME: 'X-Api-Key', EPCIS_SOURCE_GATE_HEADER_VALUE: secret }).epcis.sources[0]!
|
|
86
|
+
expect(header.credentials!()).toEqual({ scheme: 'header', name: 'X-Api-Key', value: secret })
|
|
87
|
+
expect(loadConfig({ EPCIS_SOURCES: 'gate', EPCIS_SOURCE_GATE_URL: 'https://gate.example.org' }).epcis.sources[0]).toEqual({ sourceId: 'gate', baseUrl: 'https://gate.example.org', permittedOrigins: ['https://gate.example.org'], localTest: false, repeatListParameters: false })
|
|
88
|
+
})
|
|
89
|
+
|
|
90
|
+
it('refuses an EPCIS source it cannot use, naming the setting and never its value', () => {
|
|
91
|
+
const secret = 'configured-credential-93be11'
|
|
92
|
+
const base = { EPCIS_SOURCES: 'supplier-a', EPCIS_SOURCE_SUPPLIER_A_URL: 'https://events.example.org/epcis' }
|
|
93
|
+
const cases: Array<[Record<string, string>, RegExp]> = [
|
|
94
|
+
[{ EPCIS_SOURCES: 'Supplier A' }, /EPCIS_SOURCES holds a name/],
|
|
95
|
+
[{ ...base, EPCIS_SOURCES: 'supplier-a,supplier-a' }, /names supplier-a twice/],
|
|
96
|
+
[{ EPCIS_SOURCES: 'supplier-a' }, /EPCIS_SOURCE_SUPPLIER_A_URL is not set/],
|
|
97
|
+
[{ ...base, EPCIS_SOURCE_SUPPLIER_A_URL: `not an address ${secret}` }, /EPCIS_SOURCE_SUPPLIER_A_URL does not parse/],
|
|
98
|
+
[{ ...base, EPCIS_SOURCE_SUPPLIER_A_URL: `https://operator:${secret}@events.example.org/epcis` }, /EPCIS_SOURCE_SUPPLIER_A_URL carries user information/],
|
|
99
|
+
[{ ...base, EPCIS_SOURCE_SUPPLIER_A_URL: `https://events.example.org/epcis?key=${secret}` }, /carries a query or a fragment/],
|
|
100
|
+
[{ ...base, EPCIS_SOURCE_SUPPLIER_A_URL: 'http://events.example.org/epcis' }, /plain http address/],
|
|
101
|
+
[{ ...base, EPCIS_SOURCE_SUPPLIER_A_URL: 'ftp://events.example.org/epcis' }, /must be an https address/],
|
|
102
|
+
[{ ...base, EPCIS_SOURCE_SUPPLIER_A_ORIGINS: 'https://events.example.org/epcis' }, /EPCIS_SOURCE_SUPPLIER_A_ORIGINS holds an entry that is not an origin/],
|
|
103
|
+
[{ ...base, EPCIS_SOURCE_SUPPLIER_A_LOCAL_TEST: 'yes' }, /EPCIS_SOURCE_SUPPLIER_A_LOCAL_TEST must be true or false/],
|
|
104
|
+
[{ ...base, EPCIS_SOURCE_SUPPLIER_A_BASIC_PASSWORD: secret }, /BASIC_USER and EPCIS_SOURCE_SUPPLIER_A_BASIC_PASSWORD are set together/],
|
|
105
|
+
[{ ...base, EPCIS_SOURCE_SUPPLIER_A_HEADER_VALUE: secret }, /HEADER_NAME and EPCIS_SOURCE_SUPPLIER_A_HEADER_VALUE are set together/],
|
|
106
|
+
[{ ...base, EPCIS_SOURCE_SUPPLIER_A_BEARER_TOKEN: secret, EPCIS_SOURCE_SUPPLIER_A_HEADER_NAME: 'X-Api-Key', EPCIS_SOURCE_SUPPLIER_A_HEADER_VALUE: secret }, /more than one credential set/],
|
|
107
|
+
]
|
|
108
|
+
for (const [env, expected] of cases) {
|
|
109
|
+
let message = ''
|
|
110
|
+
try {
|
|
111
|
+
loadConfig(env)
|
|
112
|
+
} catch (cause) {
|
|
113
|
+
message = (cause as Error).message
|
|
114
|
+
}
|
|
115
|
+
expect(message, JSON.stringify(Object.keys(env))).toMatch(expected)
|
|
116
|
+
expect(message).not.toContain(secret)
|
|
117
|
+
}
|
|
118
|
+
})
|
|
119
|
+
|
|
120
|
+
it('chooses the EPCIS store, the profile resolver and the validation engine by setting', () => {
|
|
121
|
+
const plain = loadConfig({})
|
|
122
|
+
expect(plain.epcis.storage).toEqual({ kind: 'mongodb' })
|
|
123
|
+
expect(plain.profileBundleDir).toBeUndefined()
|
|
124
|
+
expect(plain.validator).toEqual({ url: undefined, token: undefined })
|
|
125
|
+
expect(loadConfig({ EPCIS_STORAGE: 'file' }).epcis.storage).toEqual({ kind: 'file', dir: 'local/epcis-store' })
|
|
126
|
+
expect(loadConfig({ EPCIS_STORAGE: 'file', EPCIS_STORAGE_DIR: '/var/lib/dpp/epcis' }).epcis.storage).toEqual({ kind: 'file', dir: '/var/lib/dpp/epcis' })
|
|
127
|
+
expect(() => loadConfig({ EPCIS_STORAGE: 'postgres' })).toThrow('EPCIS_STORAGE must be mongodb or file')
|
|
128
|
+
expect(loadConfig({ PROFILE_BUNDLE_DIR: 'local/profile-bundle' }).profileBundleDir).toBe('local/profile-bundle')
|
|
129
|
+
expect(loadConfig({ VALIDATOR_URL: 'http://validator:8090/', VALIDATOR_TOKEN: 'a-token' }).validator).toEqual({ url: 'http://validator:8090', token: 'a-token' })
|
|
130
|
+
expect(loadConfig({ INDEX_EXPORT_TOKEN: 'export-token', INDEX_EXPORTER_KEY: `02${'ab'.repeat(32)}` }).indexExport).toEqual({ token: 'export-token', exporterKey: `02${'ab'.repeat(32)}` })
|
|
131
|
+
expect(() => loadConfig({ INDEX_EXPORTER_KEY: 'not-a-key' })).toThrow(/INDEX_EXPORTER_KEY must be a compressed public key/)
|
|
132
|
+
})
|
|
133
|
+
|
|
134
|
+
it('refuses a validator setting it cannot use, by name and without repeating it', () => {
|
|
135
|
+
const secret = 'validator-token-5c1d9e'
|
|
136
|
+
for (const [env, expected] of [
|
|
137
|
+
[{ VALIDATOR_URL: 'ftp://validator.example/' }, /VALIDATOR_URL must be the http or https address/],
|
|
138
|
+
[{ VALIDATOR_URL: 'not an address' }, /VALIDATOR_URL must be the http or https address/],
|
|
139
|
+
[{ VALIDATOR_URL: `https://operator:${secret}@validator.example` }, /VALIDATOR_URL carries user information/],
|
|
140
|
+
[{ VALIDATOR_URL: `https://validator.example/?token=${secret}` }, /VALIDATOR_URL carries a query or a fragment/],
|
|
141
|
+
[{ VALIDATOR_TOKEN: secret }, /VALIDATOR_TOKEN is set without VALIDATOR_URL/],
|
|
142
|
+
[{ VALIDATOR_URL: 'https://validator.example', VALIDATOR_TOKEN: `${secret} with a space` }, /VALIDATOR_TOKEN must be visible ASCII/],
|
|
143
|
+
] as const) {
|
|
144
|
+
let message = ''
|
|
145
|
+
try {
|
|
146
|
+
loadConfig(env)
|
|
147
|
+
} catch (cause) {
|
|
148
|
+
message = (cause as Error).message
|
|
149
|
+
}
|
|
150
|
+
expect(message, JSON.stringify(Object.keys(env))).toMatch(expected)
|
|
151
|
+
expect(message).not.toContain(secret)
|
|
152
|
+
}
|
|
153
|
+
})
|
|
154
|
+
|
|
155
|
+
it('knows which network each hosted index serves', () => {
|
|
156
|
+
expect(KNOWN_INDEX_HOSTS['dpp-overlay-testnet.bsvb.net']).toBe('test')
|
|
157
|
+
expect(KNOWN_INDEX_HOSTS['dpp-overlay-mainnet.bsvb.net']).toBe('main')
|
|
158
|
+
expect(KNOWN_INDEX_HOSTS['dpp-overlay.bsvb.net']).toBe('main')
|
|
14
159
|
})
|
|
15
160
|
})
|
|
@@ -0,0 +1,415 @@
|
|
|
1
|
+
import { PushDrop, Spend, Transaction, Utils, type WalletInterface } from '@bsv/sdk'
|
|
2
|
+
import { findDppOutputs, OWNER_PROTOCOL_ID } from '@bsv/dpp-protocol'
|
|
3
|
+
import { MongoClient } from 'mongodb'
|
|
4
|
+
import { MongoMemoryServer } from 'mongodb-memory-server'
|
|
5
|
+
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
6
|
+
import { loadConfig } from '../src/config.js'
|
|
7
|
+
import { Custody } from '../src/custody.js'
|
|
8
|
+
import { mintPassportId } from '../src/identifiers.js'
|
|
9
|
+
import { openPlatform, type Platform } from '../src/platform.js'
|
|
10
|
+
import { samplePayload } from '../src/profiles.js'
|
|
11
|
+
import { MongoStore } from '../src/store.js'
|
|
12
|
+
import { developer, startApp, startMongo } from './epcis-fixtures.js'
|
|
13
|
+
|
|
14
|
+
const config = loadConfig({ PASSPORT_HOST: 'passports.example.com', GS1_PREFIX: '952', LIVE_PUBLISHING: 'false' })
|
|
15
|
+
let platform: Platform
|
|
16
|
+
|
|
17
|
+
afterEach(async () => { await platform?.close() })
|
|
18
|
+
|
|
19
|
+
async function offered(mechanism: 'claim-code' | 'named-recipient') {
|
|
20
|
+
platform = await openPlatform({ config, mode: 'test', log: () => {} })
|
|
21
|
+
const brand = platform.parties.brand('sample-brand')
|
|
22
|
+
const passportId = mintPassportId({ host: config.passportHost, prefix: config.gs1Prefix }, '100000001', 'OFFER-1')
|
|
23
|
+
await platform.writer.issue({ brandId: 'sample-brand', brand, passportId, profile: 'general@2', payload: samplePayload('general@2', true) })
|
|
24
|
+
const passport = (await platform.store.getPassport(passportId))!
|
|
25
|
+
const recipient = mechanism === 'named-recipient' ? platform.parties.member('sample-member') : undefined
|
|
26
|
+
const recipientIdentityKey = recipient?.identityKey
|
|
27
|
+
const issued = await platform.custody.offer({ record: passport, holder: brand, terms: { word: 'Handed on' }, mechanism, recipientIdentityKey })
|
|
28
|
+
return { requestId: issued.offer.requestId, claimCode: issued.claimCode, recipient, passportId }
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
describe('completion of a journalled custody transfer', () => {
|
|
32
|
+
it('allows one concurrent open offer per passport in memory and MongoDB and releases the place on withdrawal', async () => {
|
|
33
|
+
const original = await offered('claim-code')
|
|
34
|
+
const passport = (await platform.store.getPassport(original.passportId))!
|
|
35
|
+
const holder = platform.parties.brand('sample-brand')
|
|
36
|
+
await platform.custody.withdraw(original.requestId, holder)
|
|
37
|
+
const mongo = await startMongo()
|
|
38
|
+
try {
|
|
39
|
+
const database = mongo.database()
|
|
40
|
+
const store = new MongoStore(database)
|
|
41
|
+
const otherStore = new MongoStore(database)
|
|
42
|
+
await store.init()
|
|
43
|
+
await store.savePassport(passport)
|
|
44
|
+
for (const [left, right] of [[platform.store, platform.store], [store, otherStore]]) {
|
|
45
|
+
const service = (storage: typeof platform.store) => new Custody({ store: storage, wallet: platform.wallet, parties: platform.parties, writer: platform.writer })
|
|
46
|
+
const args = { record: passport, holder, terms: {} }
|
|
47
|
+
const attempts = await Promise.allSettled([service(left).offer(args), service(right).offer(args)])
|
|
48
|
+
expect(attempts.filter(attempt => attempt.status === 'fulfilled')).toHaveLength(1)
|
|
49
|
+
expect(attempts.find(attempt => attempt.status === 'rejected')).toMatchObject({ reason: { code: 'offer-open' } })
|
|
50
|
+
const open = await left.listOffers({ passportId: original.passportId, status: 'open' })
|
|
51
|
+
expect(open).toHaveLength(1)
|
|
52
|
+
await service(right).withdraw(open[0].requestId, holder)
|
|
53
|
+
expect((await service(left).offer(args)).offer.status).toBe('open')
|
|
54
|
+
}
|
|
55
|
+
} finally {
|
|
56
|
+
await mongo.stop()
|
|
57
|
+
}
|
|
58
|
+
})
|
|
59
|
+
|
|
60
|
+
it('returns the same journalled transaction for concurrent calls on a newly opened offer', async () => {
|
|
61
|
+
const args = await offered('claim-code')
|
|
62
|
+
const [first, second] = await Promise.all([platform.custody.accept(args), platform.custody.accept(args)])
|
|
63
|
+
expect(second).toEqual(first)
|
|
64
|
+
expect((await platform.store.getPassport(args.passportId))!.acceptanceRecords).toEqual([first.record])
|
|
65
|
+
expect((await platform.store.getPassport(args.passportId))!.states.map(entry => entry.op)).toEqual(['ISSUE', 'TRANSFER'])
|
|
66
|
+
})
|
|
67
|
+
|
|
68
|
+
it('keeps one transfer across two custody services sharing the store', async () => {
|
|
69
|
+
const args = await offered('claim-code')
|
|
70
|
+
const second = new Custody({ store: platform.store, wallet: platform.wallet, parties: platform.parties, writer: platform.writer })
|
|
71
|
+
const attempts = await Promise.allSettled([platform.custody.accept(args), second.accept(args)])
|
|
72
|
+
expect(attempts.some(attempt => attempt.status === 'fulfilled')).toBe(true)
|
|
73
|
+
for (const attempt of attempts) if (attempt.status === 'rejected') expect(attempt.reason).toMatchObject({ code: 'operation-interrupted' })
|
|
74
|
+
const completed = await second.accept(args)
|
|
75
|
+
expect(await platform.custody.accept(args)).toEqual(completed)
|
|
76
|
+
expect((await platform.store.getPassport(args.passportId))!.states.map(entry => entry.op)).toEqual(['ISSUE', 'TRANSFER'])
|
|
77
|
+
})
|
|
78
|
+
|
|
79
|
+
it('reconciles a completed journal write after the transfer caller loses its response', async () => {
|
|
80
|
+
const args = await offered('claim-code')
|
|
81
|
+
const transfer = platform.writer.transfer.bind(platform.writer)
|
|
82
|
+
const write = vi.spyOn(platform.writer, 'transfer').mockImplementationOnce(async input => {
|
|
83
|
+
await transfer(input)
|
|
84
|
+
throw new Error('connection closed after storing the transfer')
|
|
85
|
+
})
|
|
86
|
+
const accepted = await platform.custody.accept(args)
|
|
87
|
+
expect(accepted.transferTxid).toBe((await platform.store.getPassport(args.passportId))!.states[1].txid)
|
|
88
|
+
expect((await platform.store.getOffer(args.requestId))?.status).toBe('transferred')
|
|
89
|
+
expect(write).toHaveBeenCalledTimes(1)
|
|
90
|
+
})
|
|
91
|
+
|
|
92
|
+
it('keeps a retained transfer pending until its send has a successful answer and refuses mismatched transfer bytes', async () => {
|
|
93
|
+
const args = await offered('claim-code')
|
|
94
|
+
const completed = await platform.custody.accept(args)
|
|
95
|
+
await platform.store.saveOffer({ ...completed.offer, status: 'accepted', transferTxid: undefined })
|
|
96
|
+
const passport = (await platform.store.getPassport(args.passportId))!
|
|
97
|
+
const transfer = passport.states[1]
|
|
98
|
+
transfer.network = 'unanswered'
|
|
99
|
+
await platform.store.savePassport(passport)
|
|
100
|
+
await expect(platform.custody.accept(args)).rejects.toMatchObject({ code: 'operation-interrupted' })
|
|
101
|
+
expect((await platform.store.getOffer(args.requestId))?.status).toBe('accepted')
|
|
102
|
+
transfer.network = 'dry-run'
|
|
103
|
+
transfer.rawTx = passport.states[0].rawTx
|
|
104
|
+
await platform.store.savePassport(passport)
|
|
105
|
+
await expect(platform.custody.accept(args)).rejects.toMatchObject({ code: 'acceptance-mismatch' })
|
|
106
|
+
expect((await platform.store.getOffer(args.requestId))?.status).toBe('accepted')
|
|
107
|
+
})
|
|
108
|
+
|
|
109
|
+
it('returns the retained offer to concurrent creators and after a lost response in memory and MongoDB', async () => {
|
|
110
|
+
const original = await offered('claim-code')
|
|
111
|
+
const record = (await platform.store.getPassport(original.passportId))!
|
|
112
|
+
const holder = platform.parties.brand('sample-brand')
|
|
113
|
+
await platform.custody.withdraw(original.requestId, holder)
|
|
114
|
+
const mongo = await startMongo()
|
|
115
|
+
try {
|
|
116
|
+
const database = mongo.database()
|
|
117
|
+
const store = new MongoStore(database)
|
|
118
|
+
await store.init()
|
|
119
|
+
await store.savePassport(record)
|
|
120
|
+
for (const [left, right] of [[platform.store, platform.store], [store, new MongoStore(database)]]) {
|
|
121
|
+
const service = (storage: typeof platform.store) => new Custody({ store: storage, wallet: platform.wallet, parties: platform.parties, writer: platform.writer })
|
|
122
|
+
const args = { requestId: 'warehouse:handover-1', record, holder, terms: { word: 'Sold', note: 'In person' } }
|
|
123
|
+
const results = await Promise.all([service(left).offer(args), service(right).offer(args)])
|
|
124
|
+
expect(results.map(result => result.offer.requestId)).toEqual([args.requestId, args.requestId])
|
|
125
|
+
expect(results.filter(result => result.claimCode)).toHaveLength(1)
|
|
126
|
+
const first = results.find(result => result.claimCode)!
|
|
127
|
+
const replay = await service(right).offer({ ...args, terms: { note: 'In person', word: 'Sold' } })
|
|
128
|
+
expect(replay).toEqual({ offer: first.offer })
|
|
129
|
+
expect(await left.listOffers({ passportId: record.passportId, status: 'open' })).toHaveLength(1)
|
|
130
|
+
await expect(service(left).offer({ ...args, terms: { word: 'Gift' } })).rejects.toMatchObject({ code: 'offer-request-conflict' })
|
|
131
|
+
await expect(service(left).offer({ ...args, mechanism: 'named-recipient', recipientIdentityKey: holder.identityKey })).rejects.toMatchObject({ code: 'offer-request-conflict' })
|
|
132
|
+
await expect(service(left).offer({ ...args, requestId: 'new-request' })).rejects.toMatchObject({ code: 'offer-open' })
|
|
133
|
+
await service(left).withdraw(args.requestId, holder)
|
|
134
|
+
expect((await service(right).offer(args)).offer.status).toBe('withdrawn')
|
|
135
|
+
expect(await left.listOffers({ passportId: record.passportId, status: 'open' })).toHaveLength(0)
|
|
136
|
+
}
|
|
137
|
+
} finally {
|
|
138
|
+
await mongo.stop()
|
|
139
|
+
}
|
|
140
|
+
})
|
|
141
|
+
|
|
142
|
+
it.each(['transferred before reservation', 'unanswered before reservation', 'transferred after insertion'] as const)('returns the retained status when a matching creation overlaps a transfer: %s', async timing => {
|
|
143
|
+
const original = await offered('claim-code')
|
|
144
|
+
const record = (await platform.store.getPassport(original.passportId))!
|
|
145
|
+
const holder = platform.parties.brand('sample-brand')
|
|
146
|
+
await platform.custody.withdraw(original.requestId, holder)
|
|
147
|
+
const peer = new Custody({ store: platform.store, wallet: platform.wallet, parties: platform.parties, writer: platform.writer })
|
|
148
|
+
const requestId = 'overlapping-handover'
|
|
149
|
+
const args = { requestId, record, holder, terms: { word: 'Handed on' } }
|
|
150
|
+
const recipient = platform.parties.member('sample-member')
|
|
151
|
+
const input = timing === 'transferred after insertion'
|
|
152
|
+
? { ...args, mechanism: 'named-recipient' as const, recipientIdentityKey: recipient.identityKey }
|
|
153
|
+
: args
|
|
154
|
+
if (timing === 'transferred after insertion') {
|
|
155
|
+
const insert = platform.store.createOpenOffer.bind(platform.store)
|
|
156
|
+
vi.spyOn(platform.store, 'createOpenOffer').mockImplementationOnce(async offer => {
|
|
157
|
+
const inserted = await insert(offer)
|
|
158
|
+
expect(inserted).toBe(true)
|
|
159
|
+
expect(await peer.offer(input)).toEqual({ offer })
|
|
160
|
+
await peer.accept({ requestId, recipient })
|
|
161
|
+
return inserted
|
|
162
|
+
})
|
|
163
|
+
} else {
|
|
164
|
+
const get = platform.store.getOffer.bind(platform.store)
|
|
165
|
+
vi.spyOn(platform.store, 'getOffer').mockImplementationOnce(async id => {
|
|
166
|
+
const initial = await get(id)
|
|
167
|
+
expect(initial).toBeUndefined()
|
|
168
|
+
const winner = await peer.offer(input)
|
|
169
|
+
expect(winner.claimCode).toBeTruthy()
|
|
170
|
+
const acceptance = { requestId, claimCode: winner.claimCode }
|
|
171
|
+
if (timing === 'unanswered before reservation') {
|
|
172
|
+
vi.spyOn(platform.wallet.adapter, 'send').mockResolvedValueOnce('unanswered')
|
|
173
|
+
await expect(peer.accept(acceptance)).rejects.toMatchObject({ code: 'network-unanswered' })
|
|
174
|
+
} else {
|
|
175
|
+
await peer.accept(acceptance)
|
|
176
|
+
}
|
|
177
|
+
return initial
|
|
178
|
+
})
|
|
179
|
+
}
|
|
180
|
+
const result = await platform.custody.offer(input)
|
|
181
|
+
expect(result.offer.status).toBe(timing === 'unanswered before reservation' ? 'accepted' : 'transferred')
|
|
182
|
+
expect(result).toEqual(await peer.offer(input))
|
|
183
|
+
expect(result).not.toHaveProperty('claimCode')
|
|
184
|
+
expect(result.offer).not.toHaveProperty('record')
|
|
185
|
+
expect(result.offer).not.toHaveProperty('transferTxid')
|
|
186
|
+
await expect(peer.offer({ ...input, terms: { word: 'Repaired' } })).rejects.toMatchObject({ code: 'offer-request-conflict' })
|
|
187
|
+
await expect(peer.offer({ ...input, requestId: 'different-handover' })).rejects.toMatchObject({
|
|
188
|
+
code: timing === 'unanswered before reservation' ? 'operation-interrupted' : 'tip-moved',
|
|
189
|
+
})
|
|
190
|
+
expect(await platform.store.getOffer('different-handover')).toBeUndefined()
|
|
191
|
+
expect((await platform.store.getPassport(record.passportId))?.states.map(state => state.op)).toEqual(['ISSUE', 'TRANSFER'])
|
|
192
|
+
})
|
|
193
|
+
|
|
194
|
+
it('replays through the holder API after transfer without returning its code or signed acceptance', async () => {
|
|
195
|
+
const api = await startApp({ config, mode: 'test' })
|
|
196
|
+
try {
|
|
197
|
+
const brand = api.platform.parties.brand('dev-brand')
|
|
198
|
+
const { passportId, product } = (await api.get('/api/profiles/eu-battery@2')).body.examples[0]
|
|
199
|
+
await api.platform.writer.issue({ brandId: 'dev-brand', brand, passportId, profile: 'eu-battery@2', product })
|
|
200
|
+
const path = `/api/passports/${encodeURIComponent(passportId)}/offer`
|
|
201
|
+
const body = { requestId: 'batch:order:123', terms: { word: 'Sold' }, recipientIdentityKey: null }
|
|
202
|
+
for (const invalid of ['', '.', '..', 4, null, 'é'.repeat(65), 'field\nseparator']) {
|
|
203
|
+
const result = await api.post(path, { ...body, requestId: invalid })
|
|
204
|
+
expect(result.body.error).toBe('offer-request-id-invalid')
|
|
205
|
+
}
|
|
206
|
+
for (const key of [false, ['invalid'], '', 'invalid']) {
|
|
207
|
+
const result = await api.post(path, { ...body, mechanism: 'named-recipient', recipientIdentityKey: key })
|
|
208
|
+
expect(result.body.error).toBe('recipient-invalid')
|
|
209
|
+
}
|
|
210
|
+
const created = await api.post(path, body)
|
|
211
|
+
expect(created.body.offer.requestId).toBe(body.requestId)
|
|
212
|
+
const replay = await api.post(path, body)
|
|
213
|
+
expect(replay.body).toEqual({ offer: created.body.offer })
|
|
214
|
+
const code = created.body.claimCode
|
|
215
|
+
expect((await api.post(`/api/offers/${encodeURIComponent(body.requestId)}/accept`, { claimCode: code })).status).toBe(200)
|
|
216
|
+
const afterTransfer = await api.post(path, body)
|
|
217
|
+
expect(afterTransfer.body).toEqual({ offer: { ...created.body.offer, status: 'transferred' } })
|
|
218
|
+
expect((await api.post(path, { ...body, requestId: 'next-offer' })).status).toBe(403)
|
|
219
|
+
const next = await api.post(path, { ...body, requestId: 'next-offer', claimCode: code })
|
|
220
|
+
expect(next.status).toBe(200)
|
|
221
|
+
expect((await api.post(path, { ...body, requestId: 'next-offer', claimCode: 'incorrect' })).status).toBe(403)
|
|
222
|
+
const peer = api.platform.parties.member(developer.userId)
|
|
223
|
+
const withdraw = await api.post('/api/offers/next-offer/withdraw', { claimCode: code })
|
|
224
|
+
expect(withdraw.status).toBe(200)
|
|
225
|
+
const named = { terms: { word: 'Gift' }, requestId: 'é'.repeat(64), mechanism: 'named-recipient', recipientIdentityKey: peer.identityKey, claimCode: code }
|
|
226
|
+
const namedOffer = await api.post(path, named)
|
|
227
|
+
expect(namedOffer.status).toBe(200)
|
|
228
|
+
expect(namedOffer.body.claimCode).toBeUndefined()
|
|
229
|
+
expect((await api.post(path, named)).body).toEqual(namedOffer.body)
|
|
230
|
+
expect((await api.post(path, { ...named, recipientIdentityKey: brand.identityKey })).body.error).toBe('offer-request-conflict')
|
|
231
|
+
const anotherPassport = mintPassportId({ host: config.passportHost, prefix: config.gs1Prefix }, '100000002', 'OFFER-2')
|
|
232
|
+
await api.platform.writer.issue({ brandId: 'dev-brand', brand, passportId: anotherPassport, profile: 'general@2', payload: samplePayload('general@2', true) })
|
|
233
|
+
const conflict = await api.post(`/api/passports/${encodeURIComponent(anotherPassport)}/offer`, body)
|
|
234
|
+
expect(conflict.body.error).toBe('offer-request-conflict')
|
|
235
|
+
expect(await api.platform.store.listOffers({ passportId: anotherPassport })).toHaveLength(0)
|
|
236
|
+
} finally {
|
|
237
|
+
await api.close()
|
|
238
|
+
}
|
|
239
|
+
})
|
|
240
|
+
|
|
241
|
+
it.each(['declined', 'expired', 'moved-tip'] as const)('preserves the original offer after %s and writes no transfer', async scenario => {
|
|
242
|
+
const args = await offered('claim-code')
|
|
243
|
+
const holder = platform.parties.brand('sample-brand')
|
|
244
|
+
const original = (await platform.store.getOffer(args.requestId))!
|
|
245
|
+
if (scenario === 'declined') await platform.custody.decline(args.requestId, args.claimCode)
|
|
246
|
+
if (scenario === 'moved-tip') {
|
|
247
|
+
const record = (await platform.store.getPassport(args.passportId))!
|
|
248
|
+
await platform.writer.update({ record, actor: holder, payload: samplePayload('general@2', true) })
|
|
249
|
+
}
|
|
250
|
+
if (scenario === 'expired') {
|
|
251
|
+
vi.useFakeTimers({ toFake: ['Date'] })
|
|
252
|
+
vi.setSystemTime(new Date(original.expiresAt))
|
|
253
|
+
}
|
|
254
|
+
try {
|
|
255
|
+
const transfer = vi.spyOn(platform.writer, 'transfer')
|
|
256
|
+
const expectedCode = { declined: 'offer-closed', expired: 'offer-expired', 'moved-tip': 'tip-moved' }[scenario]
|
|
257
|
+
await expect(platform.custody.accept(args)).rejects.toMatchObject({ code: expectedCode })
|
|
258
|
+
const record = (await platform.store.getPassport(args.passportId))!
|
|
259
|
+
const replay = await platform.custody.offer({ record, holder, requestId: args.requestId, terms: original.terms })
|
|
260
|
+
expect(replay).toEqual({ offer: { ...original, status: scenario === 'moved-tip' ? 'open' : scenario } })
|
|
261
|
+
expect(await platform.store.listOffers({ passportId: record.passportId })).toHaveLength(1)
|
|
262
|
+
expect(record.acceptanceRecords).toHaveLength(0)
|
|
263
|
+
expect(transfer).not.toHaveBeenCalled()
|
|
264
|
+
} finally {
|
|
265
|
+
if (scenario === 'expired') vi.useRealTimers()
|
|
266
|
+
}
|
|
267
|
+
})
|
|
268
|
+
|
|
269
|
+
it('locks to the signed controller and accepts only that controller’s spend after handover', async () => {
|
|
270
|
+
const offer = await offered('claim-code')
|
|
271
|
+
const { record: acceptance } = await platform.custody.accept(offer)
|
|
272
|
+
const transferred = (await platform.store.getPassport(offer.passportId))!
|
|
273
|
+
const recipient = platform.custody.holderOf(transferred)
|
|
274
|
+
const { record } = await platform.writer.update({ record: transferred, actor: recipient, payload: samplePayload('general@2', true) })
|
|
275
|
+
const states = record.states.map(entry => Transaction.fromAtomicBEEF(Utils.toArray(entry.beef, 'base64')))
|
|
276
|
+
const outputs = states.map(tx => findDppOutputs(tx)[0]!)
|
|
277
|
+
for (const output of outputs) expect(output.lockingPublicKey.toString()).toBe(output.state.ownerIdentityKey)
|
|
278
|
+
expect(outputs[1]!.lockingPublicKey.toString()).toBe(acceptance.acceptance.destinationKey)
|
|
279
|
+
function spendAt(index: number, unlockingScript = states[index]!.inputs[0]!.unlockingScript!) {
|
|
280
|
+
const tx = states[index]!
|
|
281
|
+
const prev = states[index - 1]!
|
|
282
|
+
const input = tx.inputs[0]!
|
|
283
|
+
expect(input.sourceTXID ?? input.sourceTransaction?.id('hex')).toBe(prev.id('hex'))
|
|
284
|
+
const source = prev.outputs[input.sourceOutputIndex]!
|
|
285
|
+
return new Spend({
|
|
286
|
+
sourceTXID: prev.id('hex'), sourceOutputIndex: input.sourceOutputIndex, sourceSatoshis: source.satoshis!,
|
|
287
|
+
lockingScript: source.lockingScript, transactionVersion: tx.version, otherInputs: tx.inputs.slice(1),
|
|
288
|
+
unlockingScript, inputSequence: input.sequence!, inputIndex: 0, outputs: tx.outputs, lockTime: tx.lockTime,
|
|
289
|
+
}).validate()
|
|
290
|
+
}
|
|
291
|
+
expect(spendAt(1)).toBe(true)
|
|
292
|
+
expect(spendAt(2)).toBe(true)
|
|
293
|
+
// The previous holder and the funding wallet cannot authorise the new holder's input.
|
|
294
|
+
for (const wallet of [platform.parties.brand('sample-brand').wallet, platform.wallet.publisher]) {
|
|
295
|
+
const wrong = await new PushDrop(wallet as WalletInterface).unlock(OWNER_PROTOCOL_ID, offer.passportId, 'self').sign(states[2]!, 0)
|
|
296
|
+
expect(() => spendAt(2, wrong)).toThrow()
|
|
297
|
+
}
|
|
298
|
+
})
|
|
299
|
+
|
|
300
|
+
it('reserves the predecessor during transfer and lets the new holder offer after a delayed creator', async () => {
|
|
301
|
+
const first = await offered('claim-code')
|
|
302
|
+
const record = (await platform.store.getPassport(first.passportId))!
|
|
303
|
+
const oldHolder = platform.parties.brand('sample-brand')
|
|
304
|
+
const oldOffer = (await platform.store.getOffer(first.requestId))!
|
|
305
|
+
const delayed = { requestId: 'delayed', record, holder: oldHolder, terms: {} }
|
|
306
|
+
let entered!: () => void
|
|
307
|
+
let release!: () => void
|
|
308
|
+
const signingDone = new Promise<void>(resolve => { entered = resolve })
|
|
309
|
+
const resume = new Promise<void>(resolve => { release = resolve })
|
|
310
|
+
const transfer = platform.writer.transfer.bind(platform.writer)
|
|
311
|
+
vi.spyOn(platform.writer, 'transfer').mockImplementationOnce(async args => {
|
|
312
|
+
entered()
|
|
313
|
+
await resume
|
|
314
|
+
return await transfer(args)
|
|
315
|
+
})
|
|
316
|
+
const accepting = platform.custody.accept(first)
|
|
317
|
+
try {
|
|
318
|
+
await signingDone
|
|
319
|
+
await expect(platform.custody.offer(delayed)).rejects.toMatchObject({ code: 'offer-open' })
|
|
320
|
+
} finally {
|
|
321
|
+
release()
|
|
322
|
+
await accepting
|
|
323
|
+
}
|
|
324
|
+
await expect(platform.custody.offer(delayed)).rejects.toMatchObject({ code: 'tip-moved' })
|
|
325
|
+
// A prior release or a process interrupted after insertion can have left an open offer at the spent predecessor.
|
|
326
|
+
await platform.store.saveOffer({ ...oldOffer, requestId: 'abandoned-draft', status: 'open' })
|
|
327
|
+
const current = (await platform.store.getPassport(first.passportId))!
|
|
328
|
+
const next = await platform.custody.offer({ record: current, holder: platform.custody.holderOf(current), requestId: 'next-holder', terms: {} })
|
|
329
|
+
expect(next.offer.expectedPredecessor.txid).toBe(current.states[1].txid)
|
|
330
|
+
expect((await platform.store.getOffer('abandoned-draft'))?.status).toBe('withdrawn')
|
|
331
|
+
})
|
|
332
|
+
|
|
333
|
+
it('keeps an accepted predecessor reserved across two MongoDB clients while the successor is offered', async () => {
|
|
334
|
+
const first = await offered('claim-code')
|
|
335
|
+
const original = (await platform.store.getOffer(first.requestId))!
|
|
336
|
+
const completed = await platform.custody.accept(first)
|
|
337
|
+
const passport = (await platform.store.getPassport(first.passportId))!
|
|
338
|
+
const successor = await platform.custody.offer({ record: passport, holder: platform.custody.holderOf(passport), terms: {} })
|
|
339
|
+
const accepted = { ...original, status: 'accepted' as const, record: completed.record }
|
|
340
|
+
const delayed = { ...original, requestId: 'delayed-creation' }
|
|
341
|
+
const mongo = await MongoMemoryServer.create()
|
|
342
|
+
const left = new MongoClient(mongo.getUri())
|
|
343
|
+
const right = new MongoClient(mongo.getUri())
|
|
344
|
+
try {
|
|
345
|
+
const primary = new MongoStore(left.db('custody'))
|
|
346
|
+
const peer = new MongoStore(right.db('custody'))
|
|
347
|
+
await primary.init()
|
|
348
|
+
expect(await primary.createOpenOffer(original)).toBe(true)
|
|
349
|
+
expect(await Promise.all([primary.changeOfferStatus(accepted, 'open'), peer.createOpenOffer(delayed)])).toEqual([true, false])
|
|
350
|
+
expect(await peer.createOpenOffer(delayed)).toBe(false)
|
|
351
|
+
expect(await peer.changeOfferStatus({ ...original, status: 'withdrawn' }, 'open')).toBe(false)
|
|
352
|
+
expect(await peer.getOffer(delayed.requestId)).toBeUndefined()
|
|
353
|
+
// The writer has advanced the tip, but the first custodian has yet to record its transfer acknowledgement.
|
|
354
|
+
expect(await peer.createOpenOffer(successor.offer)).toBe(true)
|
|
355
|
+
expect(await primary.changeOfferStatus(completed.offer, 'accepted')).toBe(true)
|
|
356
|
+
expect(await peer.getOffer(first.requestId)).toMatchObject({ status: 'transferred', transferTxid: completed.transferTxid })
|
|
357
|
+
expect(await primary.getOffer(successor.offer.requestId)).toMatchObject({ status: 'open', expectedPredecessor: successor.offer.expectedPredecessor })
|
|
358
|
+
} finally {
|
|
359
|
+
await Promise.all([left.close(), right.close()])
|
|
360
|
+
await mongo.stop()
|
|
361
|
+
}
|
|
362
|
+
})
|
|
363
|
+
|
|
364
|
+
it('does not replace an offer based on an unsettled journal tip', async () => {
|
|
365
|
+
const original = await offered('claim-code')
|
|
366
|
+
const record = (await platform.store.getPassport(original.passportId))!
|
|
367
|
+
const heldOffer = (await platform.store.getOffer(original.requestId))!
|
|
368
|
+
const holder = platform.parties.brand('sample-brand')
|
|
369
|
+
const update = await platform.writer.update({ record, actor: holder, payload: samplePayload('general@2', true) })
|
|
370
|
+
const pending = update.record
|
|
371
|
+
pending.states[1].network = 'unanswered'
|
|
372
|
+
await platform.store.savePassport(pending)
|
|
373
|
+
await expect(platform.custody.offer({ record: pending, holder, terms: {}, requestId: 'other-offer' }))
|
|
374
|
+
.rejects.toMatchObject({ code: 'operation-interrupted' })
|
|
375
|
+
expect(await platform.store.getOffer(original.requestId)).toEqual(heldOffer)
|
|
376
|
+
expect(await platform.store.getOffer('other-offer')).toBeUndefined()
|
|
377
|
+
})
|
|
378
|
+
|
|
379
|
+
it('uses the authenticated member for a named offer through the API', async () => {
|
|
380
|
+
const api = await startApp({ config, mode: 'test' })
|
|
381
|
+
try {
|
|
382
|
+
const brand = api.platform.parties.brand('dev-brand')
|
|
383
|
+
const { passportId, product } = (await api.get('/api/profiles/eu-battery@2')).body.examples[0]
|
|
384
|
+
await api.platform.writer.issue({ brandId: 'dev-brand', brand, passportId, profile: 'eu-battery@2', product })
|
|
385
|
+
const record = (await api.platform.store.getPassport(passportId))!
|
|
386
|
+
const member = api.platform.parties.member(developer.userId)
|
|
387
|
+
const { offer } = await api.platform.custody.offer({ record, holder: brand, terms: {}, mechanism: 'named-recipient', recipientIdentityKey: member.identityKey })
|
|
388
|
+
const path = `/api/offers/${offer.requestId}/accept`
|
|
389
|
+
const accepted = await api.post(path, {})
|
|
390
|
+
expect(accepted.status).toBe(200)
|
|
391
|
+
expect(accepted.body.record.acceptance.recipientIdentityKey).toBe(member.identityKey)
|
|
392
|
+
expect((await api.post(path, {})).body.transferTxid).toBe(accepted.body.transferTxid)
|
|
393
|
+
expect((await api.platform.store.getPassport(passportId))?.holder.party).toBe(member.name)
|
|
394
|
+
expect((await api.post(`/api/passports/${encodeURIComponent(passportId)}/authorised-view`, {})).status).toBe(200)
|
|
395
|
+
} finally {
|
|
396
|
+
await api.close()
|
|
397
|
+
}
|
|
398
|
+
})
|
|
399
|
+
|
|
400
|
+
it.each(['claim-code', 'named-recipient'] as const)('completes an accepted %s offer after its transfer was journalled and checks the recipient on each retry', async (mechanism) => {
|
|
401
|
+
const args = await offered(mechanism)
|
|
402
|
+
const completed = await platform.custody.accept(args)
|
|
403
|
+
await platform.store.saveOffer({ ...completed.offer, status: 'accepted', transferTxid: undefined })
|
|
404
|
+
const wrong = mechanism === 'claim-code' ? { ...args, claimCode: 'not-this-offer' } : { ...args, recipient: platform.parties.member('different-member') }
|
|
405
|
+
const code = mechanism === 'claim-code' ? 'claim-code-wrong' : 'recipient-wrong'
|
|
406
|
+
await expect(platform.custody.accept(wrong)).rejects.toMatchObject({ code })
|
|
407
|
+
expect((await platform.store.getOffer(args.requestId))?.status).toBe('accepted')
|
|
408
|
+
const [first, second] = await Promise.all([platform.custody.accept(args), platform.custody.accept(args)])
|
|
409
|
+
expect(first).toEqual(completed)
|
|
410
|
+
expect(second).toEqual(completed)
|
|
411
|
+
expect(await platform.custody.accept(args)).toEqual(completed)
|
|
412
|
+
await expect(platform.custody.accept(wrong)).rejects.toMatchObject({ code })
|
|
413
|
+
expect((await platform.store.getPassport(args.passportId))!.states.map(entry => entry.op)).toEqual(['ISSUE', 'TRANSFER'])
|
|
414
|
+
})
|
|
415
|
+
})
|