@bsv/wallet-toolbox 1.1.24 → 1.1.25

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 (194) hide show
  1. package/docs/client.md +2319 -84
  2. package/docs/wallet.md +2319 -84
  3. package/out/src/CWIStyleWalletManager.d.ts +411 -0
  4. package/out/src/CWIStyleWalletManager.d.ts.map +1 -0
  5. package/out/src/CWIStyleWalletManager.js +1131 -0
  6. package/out/src/CWIStyleWalletManager.js.map +1 -0
  7. package/out/src/SetupClient.d.ts +249 -0
  8. package/out/src/SetupClient.d.ts.map +1 -0
  9. package/out/src/SetupClient.js +252 -0
  10. package/out/src/SetupClient.js.map +1 -0
  11. package/out/src/SimpleWalletManager.d.ts +169 -0
  12. package/out/src/SimpleWalletManager.d.ts.map +1 -0
  13. package/out/src/SimpleWalletManager.js +315 -0
  14. package/out/src/SimpleWalletManager.js.map +1 -0
  15. package/out/src/Wallet.d.ts +6 -1
  16. package/out/src/Wallet.d.ts.map +1 -1
  17. package/out/src/Wallet.js +29 -2
  18. package/out/src/Wallet.js.map +1 -1
  19. package/out/src/WalletAuthenticationManager.d.ts +33 -0
  20. package/out/src/WalletAuthenticationManager.d.ts.map +1 -0
  21. package/out/src/WalletAuthenticationManager.js +107 -0
  22. package/out/src/WalletAuthenticationManager.js.map +1 -0
  23. package/out/src/WalletPermissionsManager.d.ts +575 -0
  24. package/out/src/WalletPermissionsManager.d.ts.map +1 -0
  25. package/out/src/WalletPermissionsManager.js +1807 -0
  26. package/out/src/WalletPermissionsManager.js.map +1 -0
  27. package/out/src/WalletSettingsManager.d.ts +59 -0
  28. package/out/src/WalletSettingsManager.d.ts.map +1 -0
  29. package/out/src/WalletSettingsManager.js +168 -0
  30. package/out/src/WalletSettingsManager.js.map +1 -0
  31. package/out/src/__tests/CWIStyleWalletManager.test.d.ts +2 -0
  32. package/out/src/__tests/CWIStyleWalletManager.test.d.ts.map +1 -0
  33. package/out/src/__tests/CWIStyleWalletManager.test.js +472 -0
  34. package/out/src/__tests/CWIStyleWalletManager.test.js.map +1 -0
  35. package/out/src/__tests/WalletPermissionsManager.callbacks.test.d.ts +2 -0
  36. package/out/src/__tests/WalletPermissionsManager.callbacks.test.d.ts.map +1 -0
  37. package/out/src/__tests/WalletPermissionsManager.callbacks.test.js +239 -0
  38. package/out/src/__tests/WalletPermissionsManager.callbacks.test.js.map +1 -0
  39. package/out/src/__tests/WalletPermissionsManager.checks.test.d.ts +2 -0
  40. package/out/src/__tests/WalletPermissionsManager.checks.test.d.ts.map +1 -0
  41. package/out/src/__tests/WalletPermissionsManager.checks.test.js +644 -0
  42. package/out/src/__tests/WalletPermissionsManager.checks.test.js.map +1 -0
  43. package/out/src/__tests/WalletPermissionsManager.encryption.test.d.ts +2 -0
  44. package/out/src/__tests/WalletPermissionsManager.encryption.test.d.ts.map +1 -0
  45. package/out/src/__tests/WalletPermissionsManager.encryption.test.js +295 -0
  46. package/out/src/__tests/WalletPermissionsManager.encryption.test.js.map +1 -0
  47. package/out/src/__tests/WalletPermissionsManager.fixtures.d.ts +82 -0
  48. package/out/src/__tests/WalletPermissionsManager.fixtures.d.ts.map +1 -0
  49. package/out/src/__tests/WalletPermissionsManager.fixtures.js +260 -0
  50. package/out/src/__tests/WalletPermissionsManager.fixtures.js.map +1 -0
  51. package/out/src/__tests/WalletPermissionsManager.flows.test.d.ts +2 -0
  52. package/out/src/__tests/WalletPermissionsManager.flows.test.d.ts.map +1 -0
  53. package/out/src/__tests/WalletPermissionsManager.flows.test.js +389 -0
  54. package/out/src/__tests/WalletPermissionsManager.flows.test.js.map +1 -0
  55. package/out/src/__tests/WalletPermissionsManager.initialization.test.d.ts +2 -0
  56. package/out/src/__tests/WalletPermissionsManager.initialization.test.d.ts.map +1 -0
  57. package/out/src/__tests/WalletPermissionsManager.initialization.test.js +227 -0
  58. package/out/src/__tests/WalletPermissionsManager.initialization.test.js.map +1 -0
  59. package/out/src/__tests/WalletPermissionsManager.proxying.test.d.ts +2 -0
  60. package/out/src/__tests/WalletPermissionsManager.proxying.test.d.ts.map +1 -0
  61. package/out/src/__tests/WalletPermissionsManager.proxying.test.js +566 -0
  62. package/out/src/__tests/WalletPermissionsManager.proxying.test.js.map +1 -0
  63. package/out/src/__tests/WalletPermissionsManager.tokens.test.d.ts +2 -0
  64. package/out/src/__tests/WalletPermissionsManager.tokens.test.d.ts.map +1 -0
  65. package/out/src/__tests/WalletPermissionsManager.tokens.test.js +460 -0
  66. package/out/src/__tests/WalletPermissionsManager.tokens.test.js.map +1 -0
  67. package/out/src/index.all.d.ts +9 -0
  68. package/out/src/index.all.d.ts.map +1 -1
  69. package/out/src/index.all.js +9 -0
  70. package/out/src/index.all.js.map +1 -1
  71. package/out/src/index.client.d.ts +9 -0
  72. package/out/src/index.client.d.ts.map +1 -1
  73. package/out/src/index.client.js +9 -0
  74. package/out/src/index.client.js.map +1 -1
  75. package/out/src/utility/identityUtils.d.ts +31 -0
  76. package/out/src/utility/identityUtils.d.ts.map +1 -0
  77. package/out/src/utility/identityUtils.js +114 -0
  78. package/out/src/utility/identityUtils.js.map +1 -0
  79. package/out/src/wab-client/WABClient.d.ts +38 -0
  80. package/out/src/wab-client/WABClient.d.ts.map +1 -0
  81. package/out/src/wab-client/WABClient.js +95 -0
  82. package/out/src/wab-client/WABClient.js.map +1 -0
  83. package/out/src/wab-client/__tests/WABClient.test.d.ts +2 -0
  84. package/out/src/wab-client/__tests/WABClient.test.d.ts.map +1 -0
  85. package/out/src/wab-client/__tests/WABClient.test.js +47 -0
  86. package/out/src/wab-client/__tests/WABClient.test.js.map +1 -0
  87. package/out/src/wab-client/auth-method-interactors/AuthMethodInteractor.d.ts +34 -0
  88. package/out/src/wab-client/auth-method-interactors/AuthMethodInteractor.d.ts.map +1 -0
  89. package/out/src/wab-client/auth-method-interactors/AuthMethodInteractor.js +16 -0
  90. package/out/src/wab-client/auth-method-interactors/AuthMethodInteractor.js.map +1 -0
  91. package/out/src/wab-client/auth-method-interactors/PersonaIDInteractor.d.ts +7 -0
  92. package/out/src/wab-client/auth-method-interactors/PersonaIDInteractor.d.ts.map +1 -0
  93. package/out/src/wab-client/auth-method-interactors/PersonaIDInteractor.js +40 -0
  94. package/out/src/wab-client/auth-method-interactors/PersonaIDInteractor.js.map +1 -0
  95. package/out/src/wab-client/auth-method-interactors/TwilioPhoneInteractor.d.ts +28 -0
  96. package/out/src/wab-client/auth-method-interactors/TwilioPhoneInteractor.d.ts.map +1 -0
  97. package/out/src/wab-client/auth-method-interactors/TwilioPhoneInteractor.js +73 -0
  98. package/out/src/wab-client/auth-method-interactors/TwilioPhoneInteractor.js.map +1 -0
  99. package/out/test/Wallet/action/abortAction.test.d.ts.map +1 -0
  100. package/out/test/{wallet → Wallet}/action/abortAction.test.js.map +1 -1
  101. package/out/test/Wallet/action/createAction.test.d.ts.map +1 -0
  102. package/out/test/{wallet → Wallet}/action/createAction.test.js.map +1 -1
  103. package/out/test/{wallet → Wallet}/action/createAction2.test.d.ts.map +1 -1
  104. package/out/test/{wallet → Wallet}/action/createAction2.test.js.map +1 -1
  105. package/out/test/Wallet/action/createActionToGenerateBeefs.man.test.d.ts.map +1 -0
  106. package/out/test/{wallet → Wallet}/action/createActionToGenerateBeefs.man.test.js.map +1 -1
  107. package/out/test/Wallet/action/internalizeAction.test.d.ts.map +1 -0
  108. package/out/test/{wallet → Wallet}/action/internalizeAction.test.js.map +1 -1
  109. package/out/test/Wallet/action/relinquishOutput.test.d.ts.map +1 -0
  110. package/out/test/{wallet → Wallet}/action/relinquishOutput.test.js.map +1 -1
  111. package/out/test/Wallet/construct/Wallet.constructor.test.d.ts.map +1 -0
  112. package/out/test/{wallet → Wallet}/construct/Wallet.constructor.test.js.map +1 -1
  113. package/out/test/Wallet/list/listActions.test.d.ts.map +1 -0
  114. package/out/test/{wallet → Wallet}/list/listActions.test.js.map +1 -1
  115. package/out/test/Wallet/list/listActions2.test.d.ts.map +1 -0
  116. package/out/test/{wallet → Wallet}/list/listActions2.test.js.map +1 -1
  117. package/out/test/Wallet/list/listCertificates.test.d.ts.map +1 -0
  118. package/out/test/{wallet → Wallet}/list/listCertificates.test.js.map +1 -1
  119. package/out/test/Wallet/list/listOutputs.test.d.ts.map +1 -0
  120. package/out/test/{wallet → Wallet}/list/listOutputs.test.js.map +1 -1
  121. package/out/test/Wallet/sync/Wallet.sync.test.d.ts.map +1 -0
  122. package/out/test/{wallet → Wallet}/sync/Wallet.sync.test.js.map +1 -1
  123. package/out/tsconfig.all.tsbuildinfo +1 -1
  124. package/package.json +3 -3
  125. package/src/CWIStyleWalletManager.ts +1891 -0
  126. package/src/SimpleWalletManager.ts +553 -0
  127. package/src/Wallet.ts +47 -3
  128. package/src/WalletAuthenticationManager.ts +183 -0
  129. package/src/WalletPermissionsManager.ts +2639 -0
  130. package/src/WalletSettingsManager.ts +241 -0
  131. package/src/__tests/CWIStyleWalletManager.test.ts +709 -0
  132. package/src/__tests/WalletPermissionsManager.callbacks.test.ts +328 -0
  133. package/src/__tests/WalletPermissionsManager.checks.test.ts +857 -0
  134. package/src/__tests/WalletPermissionsManager.encryption.test.ts +407 -0
  135. package/src/__tests/WalletPermissionsManager.fixtures.ts +283 -0
  136. package/src/__tests/WalletPermissionsManager.flows.test.ts +490 -0
  137. package/src/__tests/WalletPermissionsManager.initialization.test.ts +333 -0
  138. package/src/__tests/WalletPermissionsManager.proxying.test.ts +753 -0
  139. package/src/__tests/WalletPermissionsManager.tokens.test.ts +584 -0
  140. package/src/index.all.ts +9 -0
  141. package/src/index.client.ts +9 -0
  142. package/src/utility/identityUtils.ts +170 -0
  143. package/src/wab-client/WABClient.ts +103 -0
  144. package/src/wab-client/__tests/WABClient.test.ts +58 -0
  145. package/src/wab-client/auth-method-interactors/AuthMethodInteractor.ts +47 -0
  146. package/src/wab-client/auth-method-interactors/PersonaIDInteractor.ts +45 -0
  147. package/src/wab-client/auth-method-interactors/TwilioPhoneInteractor.ts +82 -0
  148. package/out/test/wallet/action/abortAction.test.d.ts.map +0 -1
  149. package/out/test/wallet/action/createAction.test.d.ts.map +0 -1
  150. package/out/test/wallet/action/createActionToGenerateBeefs.man.test.d.ts.map +0 -1
  151. package/out/test/wallet/action/internalizeAction.test.d.ts.map +0 -1
  152. package/out/test/wallet/action/relinquishOutput.test.d.ts.map +0 -1
  153. package/out/test/wallet/construct/Wallet.constructor.test.d.ts.map +0 -1
  154. package/out/test/wallet/list/listActions.test.d.ts.map +0 -1
  155. package/out/test/wallet/list/listActions2.test.d.ts.map +0 -1
  156. package/out/test/wallet/list/listCertificates.test.d.ts.map +0 -1
  157. package/out/test/wallet/list/listOutputs.test.d.ts.map +0 -1
  158. package/out/test/wallet/sync/Wallet.sync.test.d.ts.map +0 -1
  159. /package/out/test/{wallet → Wallet}/action/abortAction.test.d.ts +0 -0
  160. /package/out/test/{wallet → Wallet}/action/abortAction.test.js +0 -0
  161. /package/out/test/{wallet → Wallet}/action/createAction.test.d.ts +0 -0
  162. /package/out/test/{wallet → Wallet}/action/createAction.test.js +0 -0
  163. /package/out/test/{wallet → Wallet}/action/createAction2.test.d.ts +0 -0
  164. /package/out/test/{wallet → Wallet}/action/createAction2.test.js +0 -0
  165. /package/out/test/{wallet → Wallet}/action/createActionToGenerateBeefs.man.test.d.ts +0 -0
  166. /package/out/test/{wallet → Wallet}/action/createActionToGenerateBeefs.man.test.js +0 -0
  167. /package/out/test/{wallet → Wallet}/action/internalizeAction.test.d.ts +0 -0
  168. /package/out/test/{wallet → Wallet}/action/internalizeAction.test.js +0 -0
  169. /package/out/test/{wallet → Wallet}/action/relinquishOutput.test.d.ts +0 -0
  170. /package/out/test/{wallet → Wallet}/action/relinquishOutput.test.js +0 -0
  171. /package/out/test/{wallet → Wallet}/construct/Wallet.constructor.test.d.ts +0 -0
  172. /package/out/test/{wallet → Wallet}/construct/Wallet.constructor.test.js +0 -0
  173. /package/out/test/{wallet → Wallet}/list/listActions.test.d.ts +0 -0
  174. /package/out/test/{wallet → Wallet}/list/listActions.test.js +0 -0
  175. /package/out/test/{wallet → Wallet}/list/listActions2.test.d.ts +0 -0
  176. /package/out/test/{wallet → Wallet}/list/listActions2.test.js +0 -0
  177. /package/out/test/{wallet → Wallet}/list/listCertificates.test.d.ts +0 -0
  178. /package/out/test/{wallet → Wallet}/list/listCertificates.test.js +0 -0
  179. /package/out/test/{wallet → Wallet}/list/listOutputs.test.d.ts +0 -0
  180. /package/out/test/{wallet → Wallet}/list/listOutputs.test.js +0 -0
  181. /package/out/test/{wallet → Wallet}/sync/Wallet.sync.test.d.ts +0 -0
  182. /package/out/test/{wallet → Wallet}/sync/Wallet.sync.test.js +0 -0
  183. /package/test/{wallet → Wallet}/action/abortAction.test.ts +0 -0
  184. /package/test/{wallet → Wallet}/action/createAction.test.ts +0 -0
  185. /package/test/{wallet → Wallet}/action/createAction2.test.ts +0 -0
  186. /package/test/{wallet → Wallet}/action/createActionToGenerateBeefs.man.test.ts +0 -0
  187. /package/test/{wallet → Wallet}/action/internalizeAction.test.ts +0 -0
  188. /package/test/{wallet → Wallet}/action/relinquishOutput.test.ts +0 -0
  189. /package/test/{wallet → Wallet}/construct/Wallet.constructor.test.ts +0 -0
  190. /package/test/{wallet → Wallet}/list/listActions.test.ts +0 -0
  191. /package/test/{wallet → Wallet}/list/listActions2.test.ts +0 -0
  192. /package/test/{wallet → Wallet}/list/listCertificates.test.ts +0 -0
  193. /package/test/{wallet → Wallet}/list/listOutputs.test.ts +0 -0
  194. /package/test/{wallet → Wallet}/sync/Wallet.sync.test.ts +0 -0
@@ -0,0 +1,709 @@
1
+ import {
2
+ WalletInterface,
3
+ Random,
4
+ Hash,
5
+ Utils,
6
+ PrivateKey,
7
+ SymmetricKey
8
+ } from '@bsv/sdk'
9
+ import { PrivilegedKeyManager } from '../sdk'
10
+ import {
11
+ CWIStyleWalletManager,
12
+ PBKDF2_NUM_ROUNDS,
13
+ UMPToken,
14
+ UMPTokenInteractor
15
+ } from '../CWIStyleWalletManager'
16
+ import { jest } from '@jest/globals'
17
+
18
+ jest.useFakeTimers()
19
+
20
+ // ------------------------------------------------------------------------------------------
21
+ // Mocks and Utilities
22
+ // ------------------------------------------------------------------------------------------
23
+
24
+ /** A utility to create an Outpoint string for test usage. */
25
+ function makeOutpoint(txid: string, vout: number): string {
26
+ return `${txid}:${vout}`
27
+ }
28
+
29
+ /**
30
+ * A mock underlying WalletInterface to verify that proxy methods:
31
+ * 1. Are not callable if not authenticated
32
+ * 2. Are disallowed if originator is admin
33
+ * 3. Forward to the real method if conditions pass
34
+ */
35
+ const mockUnderlyingWallet = {
36
+ getPublicKey: jest.fn(),
37
+ revealCounterpartyKeyLinkage: jest.fn(),
38
+ revealSpecificKeyLinkage: jest.fn(),
39
+ encrypt: jest.fn(),
40
+ decrypt: jest.fn(),
41
+ createHmac: jest.fn(),
42
+ verifyHmac: jest.fn(),
43
+ createSignature: jest.fn(),
44
+ verifySignature: jest.fn(),
45
+ createAction: jest.fn(),
46
+ signAction: jest.fn(),
47
+ abortAction: jest.fn(),
48
+ listActions: jest.fn(),
49
+ internalizeAction: jest.fn(),
50
+ listOutputs: jest.fn(),
51
+ relinquishOutput: jest.fn(),
52
+ acquireCertificate: jest.fn(),
53
+ listCertificates: jest.fn(),
54
+ proveCertificate: jest.fn(),
55
+ relinquishCertificate: jest.fn(),
56
+ discoverByIdentityKey: jest.fn(),
57
+ discoverByAttributes: jest.fn(),
58
+ isAuthenticated: jest.fn(),
59
+ waitForAuthentication: jest.fn(),
60
+ getHeight: jest.fn(),
61
+ getHeaderForHeight: jest.fn(),
62
+ getNetwork: jest.fn(),
63
+ getVersion: jest.fn()
64
+ } as unknown as WalletInterface
65
+
66
+ /**
67
+ * A mock function that simulates building an underlying wallet.
68
+ */
69
+ const mockWalletBuilder = jest.fn(async (primaryKey, privilegedKeyManager) => {
70
+ // Return our mock underlying wallet object.
71
+ return mockUnderlyingWallet
72
+ })
73
+
74
+ /**
75
+ * A mock UMPTokenInteractor implementation.
76
+ * We can track whether buildAndSend is called with the right arguments, etc.
77
+ */
78
+ const mockUMPTokenInteractor: UMPTokenInteractor = {
79
+ findByPresentationKeyHash: jest.fn(async (hash: number[]) => undefined),
80
+ findByRecoveryKeyHash: jest.fn(async (hash: number[]) => undefined),
81
+ buildAndSend: jest.fn(
82
+ async (
83
+ wallet: WalletInterface,
84
+ admin: string,
85
+ token: UMPToken,
86
+ oldToken?: UMPToken
87
+ ) => 'abcd.0'
88
+ )
89
+ }
90
+
91
+ /**
92
+ * A mock "recoveryKeySaver" that claims it always saved the key successfully.
93
+ */
94
+ const mockRecoveryKeySaver = jest.fn(async (key: number[]) => true as true)
95
+
96
+ /**
97
+ * A mock "passwordRetriever" that we can customize to return a specific password
98
+ * or throw if needed.
99
+ */
100
+ const mockPasswordRetriever = jest.fn(async () => 'test-password')
101
+
102
+ const XOR = (n1: number[], n2: number[]): number[] => {
103
+ if (n1.length !== n2.length) {
104
+ throw new Error('lengths mismatch')
105
+ }
106
+ const r = new Array<number>(n1.length)
107
+ for (let i = 0; i < n1.length; i++) {
108
+ r[i] = n1[i] ^ n2[i]
109
+ }
110
+ return r
111
+ }
112
+
113
+ // Generate some globals
114
+ const presentationKey = Random(32)
115
+ const recoveryKey = Random(32)
116
+ const passwordSalt = Random(32)
117
+ const passwordKey = Hash.pbkdf2(
118
+ Utils.toArray('test-password', 'utf8'),
119
+ passwordSalt,
120
+ PBKDF2_NUM_ROUNDS,
121
+ 32,
122
+ 'sha512'
123
+ )
124
+ const primaryKey = Random(32)
125
+ const privilegedKey = Random(32)
126
+
127
+ /**
128
+ * A helper function to create a minimal valid UMP token.
129
+ * This can be used to mock a stored token for existing users.
130
+ */
131
+ async function createMockUMPToken(): Promise<UMPToken> {
132
+ const presentationPassword = new SymmetricKey(
133
+ XOR(presentationKey, passwordKey)
134
+ )
135
+ const presentationRecovery = new SymmetricKey(
136
+ XOR(presentationKey, recoveryKey)
137
+ )
138
+ const recoveryPassword = new SymmetricKey(XOR(recoveryKey, passwordKey))
139
+ const primaryPassword = new SymmetricKey(XOR(primaryKey, passwordKey))
140
+ const tempPrivilegedKeyManager = new PrivilegedKeyManager(
141
+ async () => new PrivateKey(privilegedKey)
142
+ )
143
+ return {
144
+ passwordSalt,
145
+ passwordPresentationPrimary: presentationPassword.encrypt(
146
+ primaryKey
147
+ ) as number[],
148
+ passwordRecoveryPrimary: recoveryPassword.encrypt(primaryKey) as number[],
149
+ presentationRecoveryPrimary: presentationRecovery.encrypt(
150
+ primaryKey
151
+ ) as number[],
152
+ passwordPrimaryPrivileged: primaryPassword.encrypt(
153
+ privilegedKey
154
+ ) as number[],
155
+ presentationRecoveryPrivileged: presentationRecovery.encrypt(
156
+ privilegedKey
157
+ ) as number[],
158
+ presentationHash: Hash.sha256(presentationKey),
159
+ recoveryHash: Hash.sha256(recoveryKey),
160
+ presentationKeyEncrypted: (
161
+ await tempPrivilegedKeyManager.encrypt({
162
+ plaintext: presentationKey,
163
+ protocolID: [2, 'admin key wrapping'],
164
+ keyID: '1'
165
+ })
166
+ ).ciphertext,
167
+ passwordKeyEncrypted: (
168
+ await tempPrivilegedKeyManager.encrypt({
169
+ plaintext: passwordKey,
170
+ protocolID: [2, 'admin key wrapping'],
171
+ keyID: '1'
172
+ })
173
+ ).ciphertext,
174
+ recoveryKeyEncrypted: (
175
+ await tempPrivilegedKeyManager.encrypt({
176
+ plaintext: recoveryKey,
177
+ protocolID: [2, 'admin key wrapping'],
178
+ keyID: '1'
179
+ })
180
+ ).ciphertext,
181
+ currentOutpoint: 'abcd:0'
182
+ }
183
+ }
184
+
185
+ describe('CWIStyleWalletManager Tests', () => {
186
+ let manager: CWIStyleWalletManager
187
+
188
+ beforeEach(() => {
189
+ // Reset all mock calls
190
+ jest.clearAllMocks()
191
+
192
+ // We create a new manager for each test, with no initial snapshot
193
+ manager = new CWIStyleWalletManager(
194
+ 'admin.walletvendor.com', // admin originator
195
+ mockWalletBuilder,
196
+ mockUMPTokenInteractor,
197
+ mockRecoveryKeySaver,
198
+ mockPasswordRetriever
199
+ // no state snapshot
200
+ )
201
+ })
202
+
203
+ // ----------------------------------------------------------------------------------------
204
+ // Private method tests (just to ensure coverage).
205
+ // We'll call them via (manager as any).somePrivateMethod(...) if needed.
206
+ // ----------------------------------------------------------------------------------------
207
+
208
+ test('XOR function: verifies correctness', () => {
209
+ const fnXOR = (manager as any).XOR as (a: number[], b: number[]) => number[]
210
+
211
+ const a = [0x00, 0xff, 0xaa]
212
+ const b = [0xff, 0xff, 0x55]
213
+ const result = fnXOR(a, b)
214
+
215
+ // 0x00 ^ 0xFF = 0xFF
216
+ // 0xFF ^ 0xFF = 0x00
217
+ // 0xAA ^ 0x55 = 0xFF
218
+ expect(result).toEqual([0xff, 0x00, 0xff])
219
+ })
220
+
221
+ // ----------------------------------------------------------------------------------------
222
+ // Authentication flows
223
+ // ----------------------------------------------------------------------------------------
224
+
225
+ describe('New user flow: presentation + password', () => {
226
+ test('Successfully creates a new token and calls buildAndSend', async () => {
227
+ // New wallet funder is a mock function
228
+ const newWalletFunder = jest.fn(() => {})
229
+ ;(manager as any).newWalletFunder = newWalletFunder
230
+
231
+ // Mock that no token is found by presentation key hash
232
+ ;(
233
+ mockUMPTokenInteractor.findByPresentationKeyHash as any
234
+ ).mockResolvedValueOnce(undefined)
235
+
236
+ // Provide a presentation key
237
+ await manager.providePresentationKey(presentationKey)
238
+
239
+ expect(manager.authenticationFlow).toBe('new-user')
240
+
241
+ // Provide a password
242
+ mockPasswordRetriever.mockResolvedValueOnce('dummy-password')
243
+ await manager.providePassword('dummy-password')
244
+
245
+ // The wallet should now be built, so manager is authenticated
246
+ expect(manager.authenticated).toBe(true)
247
+
248
+ // Recovery key saver should have been called
249
+ expect(mockRecoveryKeySaver).toHaveBeenCalledTimes(1)
250
+
251
+ // The underlying wallet builder should have been called exactly once
252
+ expect(mockWalletBuilder).toHaveBeenCalledTimes(1)
253
+
254
+ // The manager should have called buildAndSend on the interactor
255
+ expect(mockUMPTokenInteractor.buildAndSend).toHaveBeenCalledTimes(1)
256
+ const buildArgs = (mockUMPTokenInteractor.buildAndSend as any).mock
257
+ .calls[0]
258
+ // [0] => the wallet, [1] => adminOriginator, [2] => newToken, [3] => oldToken
259
+ expect(buildArgs[1]).toBe('admin.walletvendor.com')
260
+ expect(buildArgs[2]).toHaveProperty('presentationHash')
261
+ expect(buildArgs[3]).toBeUndefined() // Because it's a new user (no old token)
262
+ expect(newWalletFunder).toHaveBeenCalled() // New wallet funder should have been called
263
+ })
264
+
265
+ test('Throws if user tries to provide recovery key during new-user flow', async () => {
266
+ // Mark it as new user flow by no token found
267
+ ;(
268
+ mockUMPTokenInteractor.findByPresentationKeyHash as any
269
+ ).mockResolvedValueOnce(undefined)
270
+ await manager.providePresentationKey(Array.from({ length: 32 }, () => 1))
271
+
272
+ await expect(
273
+ manager.provideRecoveryKey(Array.from({ length: 32 }, () => 2))
274
+ ).rejects.toThrow('Do not submit recovery key in new-user flow')
275
+ })
276
+ })
277
+
278
+ describe('Existing user flow: presentation + password', () => {
279
+ test('Decryption of primary key and building the wallet', async () => {
280
+ // Provide a mock UMP token
281
+ const mockToken = await createMockUMPToken()
282
+ ;(
283
+ mockUMPTokenInteractor.findByPresentationKeyHash as any
284
+ ).mockResolvedValueOnce(mockToken)
285
+
286
+ // Provide presentation
287
+ await manager.providePresentationKey(presentationKey)
288
+ expect(manager.authenticationFlow).toBe('existing-user')
289
+
290
+ // Provide password
291
+ // The manager's internal code will do PBKDF2 with the password + token.passwordSalt
292
+ // Then XOR that with the presentation key for decryption.
293
+ await manager.providePassword('test-password')
294
+
295
+ // Check that manager is authenticated
296
+ expect(manager.authenticated).toBe(true)
297
+
298
+ // Underlying wallet is built
299
+ expect(mockWalletBuilder).toHaveBeenCalledTimes(1)
300
+ })
301
+ })
302
+
303
+ describe('Existing user flow: presentation + recovery key', () => {
304
+ beforeEach(async () => {
305
+ manager.authenticationMode = 'presentation-key-and-recovery-key'
306
+ manager.authenticationFlow = 'existing-user'
307
+ })
308
+
309
+ test('Successfully decrypts with presentation+recovery', async () => {
310
+ // Provide a mock UMP token
311
+ const mockToken = await createMockUMPToken()
312
+ ;(
313
+ mockUMPTokenInteractor.findByPresentationKeyHash as any
314
+ ).mockResolvedValueOnce(mockToken)
315
+
316
+ await manager.providePresentationKey(presentationKey)
317
+
318
+ // Provide the recovery key.
319
+ // In "presentation-key-and-recovery-key" mode, the manager won't need the password at all.
320
+ await manager.provideRecoveryKey(recoveryKey)
321
+
322
+ expect(manager.authenticated).toBe(true)
323
+ expect(mockWalletBuilder).toHaveBeenCalledTimes(1)
324
+ })
325
+
326
+ test('Throws if presentation key not provided first', async () => {
327
+ const recoveryKey = Array.from({ length: 32 }, () => 8)
328
+ await expect(manager.provideRecoveryKey(recoveryKey)).rejects.toThrow(
329
+ 'Provide the presentation key first'
330
+ )
331
+ })
332
+ })
333
+
334
+ describe('Existing user flow: recovery key + password', () => {
335
+ beforeEach(async () => {
336
+ manager.authenticationMode = 'recovery-key-and-password'
337
+ manager.authenticationFlow = 'existing-user'
338
+ })
339
+
340
+ test('Works with correct keys, sets mode as existing-user', async () => {
341
+ const mockToken = await createMockUMPToken()
342
+ ;(
343
+ mockUMPTokenInteractor.findByRecoveryKeyHash as any
344
+ ).mockResolvedValueOnce(mockToken)
345
+
346
+ // Provide recovery key
347
+ await manager.provideRecoveryKey(recoveryKey)
348
+
349
+ // Provide password
350
+ await manager.providePassword('test-password')
351
+
352
+ expect(manager.authenticated).toBe(true)
353
+ expect(mockWalletBuilder).toHaveBeenCalledTimes(1)
354
+ })
355
+
356
+ test('Throws if no token found by recovery key hash', async () => {
357
+ ;(
358
+ mockUMPTokenInteractor.findByRecoveryKeyHash as any
359
+ ).mockResolvedValueOnce(undefined)
360
+ await expect(manager.provideRecoveryKey(recoveryKey)).rejects.toThrow(
361
+ 'No user found with this key'
362
+ )
363
+ })
364
+ })
365
+
366
+ // ----------------------------------------------------------------------------------------
367
+ // Snapshots
368
+ // ----------------------------------------------------------------------------------------
369
+
370
+ describe('saveSnapshot / loadSnapshot', () => {
371
+ test('Saves a snapshot and can load it into a fresh manager instance', async () => {
372
+ // We'll do a new user flow so that manager is authenticated with a real token.
373
+ ;(
374
+ mockUMPTokenInteractor.findByPresentationKeyHash as any
375
+ ).mockResolvedValueOnce(undefined)
376
+ const presKey = Array.from({ length: 32 }, () => 0xa1)
377
+ await manager.providePresentationKey(presKey)
378
+ await manager.providePassword('mypassword') // triggers creation of new user
379
+
380
+ const snapshot = manager.saveSnapshot()
381
+ expect(Array.isArray(snapshot)).toBe(true)
382
+ expect(snapshot.length).toBeGreaterThan(64) // 32 bytes + encrypted data
383
+
384
+ // Now create a fresh manager:
385
+ const freshManager = new CWIStyleWalletManager(
386
+ 'admin.walletvendor.com',
387
+ mockWalletBuilder,
388
+ mockUMPTokenInteractor,
389
+ mockRecoveryKeySaver,
390
+ mockPasswordRetriever
391
+ )
392
+
393
+ // Not authenticated yet
394
+ await expect(() =>
395
+ freshManager.getPublicKey({ identityKey: true })
396
+ ).rejects.toThrow('User is not authenticated')
397
+
398
+ // Load the snapshot
399
+ await freshManager.loadSnapshot(snapshot)
400
+
401
+ // The fresh manager is now authenticated (underlying wallet will be built).
402
+ await expect(
403
+ freshManager.getPublicKey({ identityKey: true })
404
+ ).resolves.not.toThrow()
405
+
406
+ // It calls walletBuilder again
407
+ expect(mockWalletBuilder).toHaveBeenCalledTimes(2) // once for the old manager, once for the fresh
408
+ })
409
+
410
+ test('Throws error if saving snapshot while no primary key or token set', async () => {
411
+ // Manager is not yet authenticated
412
+ expect(() => manager.saveSnapshot()).toThrow(
413
+ 'No primary key or current UMP token set'
414
+ )
415
+ })
416
+
417
+ test('Throws if snapshot is corrupt or cannot be decrypted', async () => {
418
+ // Attempt to load an invalid snapshot
419
+ await expect(() => manager.loadSnapshot([1, 2, 3])).rejects.toThrow(
420
+ 'Failed to load snapshot'
421
+ )
422
+ })
423
+ })
424
+
425
+ // ----------------------------------------------------------------------------------------
426
+ // Changing Keys
427
+ // ----------------------------------------------------------------------------------------
428
+
429
+ describe('Change Password', () => {
430
+ test('Requires authentication and updates the UMP token on-chain', async () => {
431
+ ;(
432
+ mockUMPTokenInteractor.findByPresentationKeyHash as any
433
+ ).mockResolvedValueOnce(undefined)
434
+ manager = new CWIStyleWalletManager(
435
+ 'admin.walletvendor.com',
436
+ mockWalletBuilder,
437
+ mockUMPTokenInteractor,
438
+ mockRecoveryKeySaver,
439
+ async () => 'test-password'
440
+ )
441
+ await manager.providePresentationKey(presentationKey)
442
+ await manager.providePassword('test-password')
443
+ expect(manager.authenticated).toBe(true)
444
+ await manager.changePassword('new-pass')
445
+ expect(mockUMPTokenInteractor.buildAndSend).toHaveBeenCalledTimes(2)
446
+ })
447
+
448
+ test('Throws if not authenticated', async () => {
449
+ await expect(manager.changePassword('test-password')).rejects.toThrow(
450
+ 'Not authenticated.'
451
+ )
452
+ })
453
+ })
454
+
455
+ describe('Change Recovery Key', () => {
456
+ test('Prompts to save the new key, updates the token', async () => {
457
+ ;(
458
+ mockUMPTokenInteractor.findByPresentationKeyHash as any
459
+ ).mockResolvedValueOnce(undefined)
460
+ manager = new CWIStyleWalletManager(
461
+ 'admin.walletvendor.com',
462
+ mockWalletBuilder,
463
+ mockUMPTokenInteractor,
464
+ mockRecoveryKeySaver,
465
+ async () => 'test-password'
466
+ )
467
+ await manager.providePresentationKey(presentationKey)
468
+ await manager.providePassword('test-password')
469
+ expect(manager.authenticated).toBe(true)
470
+ ;(mockUMPTokenInteractor.buildAndSend as any).mockResolvedValueOnce(
471
+ makeOutpoint('rcv1', 0)
472
+ )
473
+ await manager.changeRecoveryKey()
474
+
475
+ // The user is prompted to store the new key
476
+ expect(mockRecoveryKeySaver).toHaveBeenCalledTimes(2) // once when user created, once after changed
477
+ // The UMP token is updated
478
+ expect(mockUMPTokenInteractor.buildAndSend).toHaveBeenCalledTimes(2)
479
+ })
480
+
481
+ test('Throws if not authenticated', async () => {
482
+ await expect(manager.changeRecoveryKey()).rejects.toThrow(
483
+ 'Not authenticated.'
484
+ )
485
+ })
486
+ })
487
+
488
+ describe('Change Presentation Key', () => {
489
+ test('Requires authentication, re-publishes the token, old token consumed', async () => {
490
+ ;(
491
+ mockUMPTokenInteractor.findByPresentationKeyHash as any
492
+ ).mockResolvedValueOnce(undefined)
493
+ manager = new CWIStyleWalletManager(
494
+ 'admin.walletvendor.com',
495
+ mockWalletBuilder,
496
+ mockUMPTokenInteractor,
497
+ mockRecoveryKeySaver,
498
+ async () => 'test-password'
499
+ )
500
+ await manager.providePresentationKey(presentationKey)
501
+ await manager.providePassword('test-password')
502
+ expect(manager.authenticated).toBe(true)
503
+ ;(mockUMPTokenInteractor.buildAndSend as any).mockResolvedValueOnce(
504
+ makeOutpoint('rcv1', 0)
505
+ )
506
+ const newPresKey = Array.from({ length: 32 }, () => 0xee)
507
+ await manager.changePresentationKey(newPresKey)
508
+ expect(mockUMPTokenInteractor.buildAndSend).toHaveBeenCalledTimes(2)
509
+ })
510
+ })
511
+
512
+ test('Destroy callback clears sensitive data', async () => {
513
+ // authenticate as new user
514
+ ;(
515
+ mockUMPTokenInteractor.findByPresentationKeyHash as any
516
+ ).mockResolvedValueOnce(undefined)
517
+ await manager.providePresentationKey(Array.from({ length: 32 }, () => 12))
518
+ await manager.providePassword('some-pass')
519
+
520
+ // manager is authenticated
521
+ expect(manager.authenticated).toBe(true)
522
+
523
+ // Destroy
524
+ manager.destroy()
525
+
526
+ expect(manager.authenticated).toBe(false)
527
+ // And we can confirm that manager won't allow calls
528
+ await expect(() =>
529
+ manager.getPublicKey({ identityKey: true })
530
+ ).rejects.toThrow('User is not authenticated')
531
+ })
532
+
533
+ // ----------------------------------------------------------------------------------------
534
+ // Proxies / originator checks
535
+ // ----------------------------------------------------------------------------------------
536
+
537
+ describe('Proxy method calls', () => {
538
+ beforeEach(async () => {
539
+ // authenticate
540
+ ;(
541
+ mockUMPTokenInteractor.findByPresentationKeyHash as any
542
+ ).mockResolvedValueOnce(undefined)
543
+ await manager.providePresentationKey(presentationKey)
544
+ await manager.providePassword('test-password')
545
+ })
546
+
547
+ test('Throws if user is not authenticated', async () => {
548
+ // force de-auth
549
+ ;(manager as any).authenticated = false
550
+ await expect(() =>
551
+ manager.getPublicKey({ identityKey: true })
552
+ ).rejects.toThrow('User is not authenticated.')
553
+ })
554
+
555
+ test('Throws if originator is adminOriginator', async () => {
556
+ await expect(
557
+ manager.getPublicKey({ identityKey: true }, 'admin.walletvendor.com')
558
+ ).rejects.toThrow(
559
+ 'External applications are not allowed to use the admin originator.'
560
+ )
561
+ })
562
+
563
+ test('Passes if user is authenticated and originator is not admin', async () => {
564
+ await manager.getPublicKey({ identityKey: true }, 'example.com')
565
+ expect(mockUnderlyingWallet.getPublicKey).toHaveBeenCalledTimes(1)
566
+ })
567
+
568
+ test('All proxied methods call underlying with correct arguments', async () => {
569
+ // We'll do a quick spot-check of a few methods:
570
+ await manager.encrypt(
571
+ { plaintext: [1, 2, 3], protocolID: [1, 'tests'], keyID: '1' },
572
+ 'mydomain.com'
573
+ )
574
+ expect(mockUnderlyingWallet.encrypt).toHaveBeenCalledWith(
575
+ { plaintext: [1, 2, 3], protocolID: [1, 'tests'], keyID: '1' },
576
+ 'mydomain.com'
577
+ )
578
+
579
+ // TODO: Test all other proxied methods
580
+ })
581
+
582
+ test('isAuthenticated() rejects if originator is admin, resolves otherwise', async () => {
583
+ // If admin tries:
584
+ await expect(
585
+ manager.isAuthenticated({}, 'admin.walletvendor.com')
586
+ ).rejects.toThrow(
587
+ 'External applications are not allowed to use the admin originator.'
588
+ )
589
+ // If normal domain:
590
+ const result = await manager.isAuthenticated({}, 'normal.com')
591
+ expect(result).toEqual({ authenticated: true })
592
+ })
593
+
594
+ test('waitForAuthentication() eventually resolves', async () => {
595
+ // Already authenticated from beforeEach. So it should immediately return.
596
+ const result = await manager.waitForAuthentication({}, 'normal.com')
597
+ expect(result).toEqual({ authenticated: true })
598
+ })
599
+ })
600
+ describe('Additional Tests for Password Retriever Callback, Privileged Key Expiry, and UMP Token Serialization', () => {
601
+ let manager: CWIStyleWalletManager
602
+
603
+ beforeEach(() => {
604
+ jest.clearAllMocks()
605
+ manager = new CWIStyleWalletManager(
606
+ 'admin.walletvendor.com',
607
+ mockWalletBuilder,
608
+ mockUMPTokenInteractor,
609
+ mockRecoveryKeySaver,
610
+ mockPasswordRetriever
611
+ )
612
+ })
613
+
614
+ test('serializeUMPToken and deserializeUMPToken correctly round-trip a UMP token', async () => {
615
+ const token = await createMockUMPToken()
616
+ // We need a token with a currentOutpoint for serialization.
617
+ expect(token.currentOutpoint).toBeDefined()
618
+ const serializeFn = (manager as any).serializeUMPToken as (
619
+ token: UMPToken
620
+ ) => number[]
621
+ const deserializeFn = (manager as any).deserializeUMPToken as (
622
+ bin: number[]
623
+ ) => UMPToken
624
+
625
+ const serialized = serializeFn(token)
626
+ expect(Array.isArray(serialized)).toBe(true)
627
+ expect(serialized.length).toBeGreaterThan(0)
628
+
629
+ const deserialized = deserializeFn(serialized)
630
+ expect(deserialized).toEqual(token)
631
+ })
632
+
633
+ test('Password retriever callback: the test function is passed and returns a boolean', async () => {
634
+ let capturedTestFn: ((candidate: string) => boolean) | null = null
635
+ const customPasswordRetriever = jest.fn(
636
+ async (reason: string, testFn: (candidate: string) => boolean) => {
637
+ capturedTestFn = testFn
638
+ // In a real scenario the test function would validate a candidate.
639
+ // For our test we simply return the correct password.
640
+ return 'test-password'
641
+ }
642
+ )
643
+ ;(manager as any).passwordRetriever = customPasswordRetriever
644
+
645
+ // Force a new-user flow by having no token found.
646
+ ;(
647
+ mockUMPTokenInteractor.findByPresentationKeyHash as any
648
+ ).mockResolvedValueOnce(undefined)
649
+ await manager.providePresentationKey(presentationKey)
650
+ await manager.providePassword('test-password')
651
+ expect(manager.authenticated).toBe(true)
652
+ // Clear the privileged key so the callback gets ran
653
+ jest.advanceTimersByTime(121_000)
654
+
655
+ // Let's trigger a privileged operation
656
+ await manager.changePassword('test-password') // trigger some privileged operation...
657
+ expect(customPasswordRetriever).toHaveBeenCalled()
658
+ expect(capturedTestFn).not.toBeNull()
659
+ // Since the internal test function is defined inline, we simply check that its output is a boolean.
660
+ // (Its logic uses the outer scope and may not use its argument correctly, but we verify that it at least returns a boolean.)
661
+ const testResult = capturedTestFn!('any-input')
662
+ expect(typeof testResult).toBe('boolean')
663
+ expect(capturedTestFn!('any-input')).toBe(false)
664
+ expect(capturedTestFn!('test-password')).toBe(true)
665
+ })
666
+
667
+ test('Privileged key expiry: each call to decrypt via the privileged manager invokes passwordRetriever', async () => {
668
+ // In a new-user flow, buildUnderlying is called without a privilegedKey,
669
+ // so any later use of the privileged manager will trigger a password prompt.
670
+ const customPasswordRetriever = jest.fn(
671
+ async (reason: string, testFn: (candidate: string) => boolean) => {
672
+ return 'test-password'
673
+ }
674
+ )
675
+ ;(manager as any).passwordRetriever = customPasswordRetriever
676
+
677
+ // New-user flow (no existing token)
678
+ ;(
679
+ mockUMPTokenInteractor.findByPresentationKeyHash as any
680
+ ).mockResolvedValueOnce(undefined)
681
+ await manager.providePresentationKey(presentationKey)
682
+ await manager.providePassword('test-password')
683
+
684
+ // Clear any calls recorded during authentication.
685
+ customPasswordRetriever.mockClear()
686
+
687
+ // Call the underlying privileged key manager’s decrypt twice.
688
+ // (For example, we use the ciphertext from one of the token’s encrypted fields.)
689
+ await (manager as any).underlyingPrivilegedKeyManager.decrypt({
690
+ ciphertext: (manager as any).currentUMPToken.passwordKeyEncrypted,
691
+ protocolID: [2, 'admin key wrapping'],
692
+ keyID: '1'
693
+ })
694
+
695
+ // Key expires after 2 minutes
696
+ jest.advanceTimersByTime(121_000)
697
+
698
+ await (manager as any).underlyingPrivilegedKeyManager.decrypt({
699
+ ciphertext: (manager as any).currentUMPToken.passwordKeyEncrypted,
700
+ protocolID: [2, 'admin key wrapping'],
701
+ keyID: '1'
702
+ })
703
+
704
+ // Since no ephemeral privileged key was provided when building the underlying wallet,
705
+ // each call to decrypt should have resulted in a call to passwordRetriever.
706
+ expect(customPasswordRetriever).toHaveBeenCalledTimes(2)
707
+ })
708
+ })
709
+ })