@ledgerhq/revault-sdk 0.25.0 → 0.26.0

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 (88) hide show
  1. package/lib/bake.cjs +1214 -1361
  2. package/lib/bake.cjs.map +1 -1
  3. package/lib/bake.d.cts +564 -562
  4. package/lib/bake.d.ts +564 -562
  5. package/lib/bake.js +1204 -1359
  6. package/lib/bake.js.map +1 -1
  7. package/lib/chunk-CKQMccvm.cjs +28 -0
  8. package/lib/crypto-BDBF_rfw.cjs +266 -0
  9. package/lib/crypto-BDBF_rfw.cjs.map +1 -0
  10. package/lib/crypto-CPCBrCSZ.js +245 -0
  11. package/lib/crypto-CPCBrCSZ.js.map +1 -0
  12. package/lib/crypto.cjs +5 -11
  13. package/lib/crypto.d.cts +10 -7
  14. package/lib/crypto.d.ts +10 -7
  15. package/lib/crypto.js +2 -11
  16. package/lib/device-0lcfYGHr.cjs +791 -0
  17. package/lib/device-0lcfYGHr.cjs.map +1 -0
  18. package/lib/device-B8Fww8_6.js +719 -0
  19. package/lib/device-B8Fww8_6.js.map +1 -0
  20. package/lib/device.cjs +6 -13
  21. package/lib/device.d.cts +2 -50
  22. package/lib/device.d.ts +2 -50
  23. package/lib/device.js +2 -13
  24. package/lib/engine.cjs +851 -888
  25. package/lib/engine.cjs.map +1 -1
  26. package/lib/engine.d.cts +3 -25
  27. package/lib/engine.d.ts +3 -25
  28. package/lib/engine.js +844 -885
  29. package/lib/engine.js.map +1 -1
  30. package/lib/index--fscLDTT.d.ts +237 -0
  31. package/lib/index-BE7oUpCb.d.cts +237 -0
  32. package/lib/index-DOn7RPPt.d.cts +23 -0
  33. package/lib/index-U0iFMp3g.d.ts +23 -0
  34. package/lib/index.cjs +0 -1
  35. package/lib/index.d.cts +10 -5
  36. package/lib/index.d.ts +10 -5
  37. package/lib/index.js +1 -1
  38. package/lib/logger-Cme0iL1f.d.cts +10 -0
  39. package/lib/logger-DWLViq7U.d.ts +10 -0
  40. package/lib/onboarding.cjs +215 -183
  41. package/lib/onboarding.cjs.map +1 -1
  42. package/lib/onboarding.d.cts +1918 -1722
  43. package/lib/onboarding.d.ts +1918 -1722
  44. package/lib/onboarding.js +211 -181
  45. package/lib/onboarding.js.map +1 -1
  46. package/lib/trpc-CWGPr8Ox.d.ts +20 -0
  47. package/lib/trpc-C_dUOB1u.d.cts +20 -0
  48. package/lib/types-BXkDuD6i.d.ts +207 -0
  49. package/lib/types-CQROu0nu.d.cts +6 -0
  50. package/lib/types-Ngwgtu_U.d.cts +207 -0
  51. package/lib/types-_QeBv1U4.d.ts +6 -0
  52. package/lib/types.cjs +0 -1
  53. package/lib/types.d.cts +3 -4
  54. package/lib/types.d.ts +3 -4
  55. package/lib/types.js +1 -1
  56. package/lib/utils-BGbdjOP9.js +61 -0
  57. package/lib/utils-BGbdjOP9.js.map +1 -0
  58. package/lib/utils-DbSFXp4c.cjs +84 -0
  59. package/lib/utils-DbSFXp4c.cjs.map +1 -0
  60. package/package.json +6 -6
  61. package/lib/chunk-2WGM7EWA.cjs +0 -282
  62. package/lib/chunk-2WGM7EWA.cjs.map +0 -1
  63. package/lib/chunk-AXI72NFY.js +0 -50
  64. package/lib/chunk-AXI72NFY.js.map +0 -1
  65. package/lib/chunk-DRMYBKL3.cjs +0 -820
  66. package/lib/chunk-DRMYBKL3.cjs.map +0 -1
  67. package/lib/chunk-KV5FO7N5.js +0 -282
  68. package/lib/chunk-KV5FO7N5.js.map +0 -1
  69. package/lib/chunk-LH4QQXUH.cjs +0 -50
  70. package/lib/chunk-LH4QQXUH.cjs.map +0 -1
  71. package/lib/chunk-PFZIW6UP.js +0 -820
  72. package/lib/chunk-PFZIW6UP.js.map +0 -1
  73. package/lib/crypto.cjs.map +0 -1
  74. package/lib/crypto.js.map +0 -1
  75. package/lib/device.cjs.map +0 -1
  76. package/lib/device.js.map +0 -1
  77. package/lib/index.cjs.map +0 -1
  78. package/lib/index.js.map +0 -1
  79. package/lib/logger-C-TPbnjv.d.cts +0 -9
  80. package/lib/logger-C-TPbnjv.d.ts +0 -9
  81. package/lib/types-C-ngtI5m.d.ts +0 -202
  82. package/lib/types-CpGEbAxh.d.cts +0 -19
  83. package/lib/types-CpGEbAxh.d.ts +0 -19
  84. package/lib/types-CryvY9pW.d.cts +0 -202
  85. package/lib/types-DJfbanPz.d.cts +0 -167
  86. package/lib/types-DJfbanPz.d.ts +0 -167
  87. package/lib/types.cjs.map +0 -1
  88. package/lib/types.js.map +0 -1
package/lib/engine.cjs CHANGED
@@ -1,899 +1,862 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } function _nullishCoalesce(lhs, rhsFn) { if (lhs != null) { return lhs; } else { return rhsFn(); } } function _optionalChain(ops) { let lastAccessLHS = undefined; let value = ops[0]; let i = 1; while (i < ops.length) { const op = ops[i]; const fn = ops[i + 1]; i += 2; if ((op === 'optionalAccess' || op === 'optionalCall') && value == null) { return undefined; } if (op === 'access' || op === 'optionalAccess') { lastAccessLHS = value; value = fn(value); } else if (op === 'call' || op === 'optionalCall') { value = fn((...args) => value.call(lastAccessLHS, ...args)); lastAccessLHS = undefined; } } return value; }
2
-
3
-
4
-
5
- var _chunkLH4QQXUHcjs = require('./chunk-LH4QQXUH.cjs');
6
-
7
-
8
-
9
-
10
-
11
-
12
-
13
-
14
-
15
-
16
-
17
-
18
-
19
-
20
- var _chunkDRMYBKL3cjs = require('./chunk-DRMYBKL3.cjs');
21
-
22
- // src/engine/index.ts
23
- var _invariant = require('invariant'); var _invariant2 = _interopRequireDefault(_invariant);
24
-
25
- // src/device/real-device.ts
26
-
27
- var _rxjs = require('rxjs');
28
- var MAX_CHUNK_LENGTH = 250;
29
- var getPathFromPathString = (pathString) => {
30
- const parts = pathString.split("'/").map((part) => Number.parseInt(part, 10));
31
- return parts.map((part) => (part | 2147483648) >>> 0);
1
+ Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
2
+ const require_chunk = require("./chunk-CKQMccvm.cjs");
3
+ const require_device = require("./device-0lcfYGHr.cjs");
4
+ const require_utils = require("./utils-DbSFXp4c.cjs");
5
+ let invariant = require("invariant");
6
+ invariant = require_chunk.__toESM(invariant);
7
+ let rxjs = require("rxjs");
8
+ let _trpc_client = require("@trpc/client");
9
+ let superjson = require("superjson");
10
+ superjson = require_chunk.__toESM(superjson);
11
+ //#region src/device/real-device.ts
12
+ const MAX_CHUNK_LENGTH = 250;
13
+ const getPathFromPathString = (pathString) => {
14
+ return pathString.split("'/").map((part) => Number.parseInt(part, 10)).map((part) => (part | 2147483648) >>> 0);
32
15
  };
33
- var splitChunks = (chunk, buffer) => {
34
- const chunks = [];
35
- for (let i = 0, size = chunk; i < buffer.length; i += size, size = chunk) {
36
- chunks.push(buffer.slice(i, i + size));
37
- }
38
- return chunks;
16
+ const splitChunks = (chunk, buffer) => {
17
+ const chunks = [];
18
+ for (let i = 0, size = chunk; i < buffer.length; i += size, size = chunk) chunks.push(buffer.slice(i, i + size));
19
+ return chunks;
39
20
  };
40
- var removeStatus = (result) => result.slice(0, result.length - _chunkDRMYBKL3cjs.STATUS_LENGTH);
41
- var sendByChunk = async (transport, command, data, chunkSize = MAX_CHUNK_LENGTH) => {
42
- const chunks = splitChunks(chunkSize, data);
43
- let response = Buffer.from([]);
44
- for (let i = 0; i < chunks.length; i++) {
45
- const chunk = chunks[i];
46
- const apdu = [...command];
47
- apdu[2] = i && 128;
48
- response = await transport.send(apdu[0], apdu[1], apdu[2], apdu[3], chunk, [
49
- 36864,
50
- ..._chunkDRMYBKL3cjs.PAGINATED_STATUS
51
- ]);
52
- }
53
- return response;
21
+ const removeStatus = (result) => result.slice(0, result.length - 2);
22
+ const sendByChunk = async (transport, command, data, chunkSize = MAX_CHUNK_LENGTH) => {
23
+ const chunks = splitChunks(chunkSize, data);
24
+ let response = Buffer.from([]);
25
+ for (let i = 0; i < chunks.length; i++) {
26
+ const chunk = chunks[i];
27
+ const apdu = [...command];
28
+ /* v8 ignore next -- @preserve */
29
+ apdu[2] = i && 128;
30
+ response = await transport.send(apdu[0], apdu[1], apdu[2], apdu[3], chunk, [36864, ...require_device.PAGINATED_STATUS]);
31
+ }
32
+ return response;
54
33
  };
55
- var buildAttestation = (params) => {
56
- const sigBuffer = Buffer.from(params.handshakeAttestation.signature, "base64");
57
- const sigLengthBuffer = Buffer.alloc(1);
58
- sigLengthBuffer.writeUIntBE(sigBuffer.length, 0, 1);
59
- const certBuffer = Buffer.from(params.handshakeAttestation.certificate, "base64");
60
- const certLengthBuffer = Buffer.alloc(1);
61
- certLengthBuffer.writeUIntBE(certBuffer.length, 0, 1);
62
- const pubBuffer = Buffer.from(params.handshakeAttestation.attestationPub, "base64");
63
- const certChainData = Buffer.concat([
64
- sigLengthBuffer,
65
- sigBuffer,
66
- pubBuffer,
67
- certLengthBuffer,
68
- certBuffer
69
- ]);
70
- const cliMsgBuffer = Buffer.from(params.handshake, "hex");
71
- const cliMsgLengthBuffer = Buffer.alloc(1);
72
- cliMsgLengthBuffer.writeUIntBE(cliMsgBuffer.length, 0, 1);
73
- const pidBuffer = Buffer.from(params.partitionId, "hex");
74
- const pidLengthBuffer = Buffer.alloc(1);
75
- pidLengthBuffer.writeUIntBE(pidBuffer.length, 0, 1);
76
- const certChainDataLengthBuff = Buffer.alloc(2);
77
- certChainDataLengthBuff.writeUInt16BE(certChainData.length, 0);
78
- const data = Buffer.concat([
79
- cliMsgLengthBuffer,
80
- cliMsgBuffer,
81
- certChainDataLengthBuff,
82
- certChainData,
83
- pidLengthBuffer,
84
- pidBuffer
85
- ]);
86
- const totalLengthBuffer = Buffer.alloc(2);
87
- totalLengthBuffer.writeUInt16BE(data.length, 0);
88
- const toSend = Buffer.concat([totalLengthBuffer, data]);
89
- return toSend;
34
+ const buildAttestation = (params) => {
35
+ const sigBuffer = Buffer.from(params.handshakeAttestation.signature, "base64");
36
+ const sigLengthBuffer = Buffer.alloc(1);
37
+ sigLengthBuffer.writeUIntBE(sigBuffer.length, 0, 1);
38
+ const certBuffer = Buffer.from(params.handshakeAttestation.certificate, "base64");
39
+ const certLengthBuffer = Buffer.alloc(1);
40
+ certLengthBuffer.writeUIntBE(certBuffer.length, 0, 1);
41
+ const pubBuffer = Buffer.from(params.handshakeAttestation.attestationPub, "base64");
42
+ const certChainData = Buffer.concat([
43
+ sigLengthBuffer,
44
+ sigBuffer,
45
+ pubBuffer,
46
+ certLengthBuffer,
47
+ certBuffer
48
+ ]);
49
+ const cliMsgBuffer = Buffer.from(params.handshake, "hex");
50
+ const cliMsgLengthBuffer = Buffer.alloc(1);
51
+ cliMsgLengthBuffer.writeUIntBE(cliMsgBuffer.length, 0, 1);
52
+ const pidBuffer = Buffer.from(params.partitionId, "hex");
53
+ const pidLengthBuffer = Buffer.alloc(1);
54
+ pidLengthBuffer.writeUIntBE(pidBuffer.length, 0, 1);
55
+ const certChainDataLengthBuff = Buffer.alloc(2);
56
+ certChainDataLengthBuff.writeUInt16BE(certChainData.length, 0);
57
+ const data = Buffer.concat([
58
+ cliMsgLengthBuffer,
59
+ cliMsgBuffer,
60
+ certChainDataLengthBuff,
61
+ certChainData,
62
+ pidLengthBuffer,
63
+ pidBuffer
64
+ ]);
65
+ const totalLengthBuffer = Buffer.alloc(2);
66
+ totalLengthBuffer.writeUInt16BE(data.length, 0);
67
+ return Buffer.concat([totalLengthBuffer, data]);
90
68
  };
91
- var genericRetryOnError = (err) => {
92
- if (err instanceof _chunkDRMYBKL3cjs.LockedDeviceError) return true;
93
- if (_chunkDRMYBKL3cjs.isTransportStatusError.call(void 0, err) && err.statusCode === 27913) return true;
94
- if (err instanceof _chunkDRMYBKL3cjs.DisconnectedDevice) return true;
95
- return false;
69
+ /* v8 ignore next -- @preserve */
70
+ const genericRetryOnError = (err) => {
71
+ if (err instanceof require_device.LockedDeviceError) return true;
72
+ if (require_device.isTransportStatusError(err) && err.statusCode === 27913) return true;
73
+ if (err instanceof require_device.DisconnectedDevice) return true;
74
+ return false;
96
75
  };
97
76
  function createRealDevice(options, logger) {
98
- const { transportId } = options;
99
- async function run(job, retryOnError = genericRetryOnError) {
100
- return _rxjs.lastValueFrom.call(void 0,
101
- _chunkDRMYBKL3cjs.withDevicePolling.call(void 0, transportId)((transport) => _rxjs.from.call(void 0, job(transport)), retryOnError)
102
- );
103
- }
104
- const noRetry = () => false;
105
- const alwaysRetry = () => true;
106
- const poll = async (opts = {}) => {
107
- await run(
108
- // eslint-disable-next-line @typescript-eslint/no-empty-function
109
- async (_transport) => {
110
- },
111
- _nullishCoalesce(opts.retryOnError, () => ( alwaysRetry))
112
- );
113
- try {
114
- await getPublicKey(_chunkDRMYBKL3cjs.PATHS.U2F, { secp256k1: true, retryOnError: noRetry });
115
- return { isAppOpened: true };
116
- } catch (err) {
117
- if (_chunkDRMYBKL3cjs.isTransportStatusError.call(void 0, err) && genericRetryOnError(err)) {
118
- return { isAppOpened: false };
119
- }
120
- throw err;
121
- }
122
- };
123
- const pollApp = async (appName) => {
124
- const res = await run(
125
- (transport) => transport.send(224, 216, 0, 0, Buffer.from(appName, "utf8"))
126
- );
127
- await new Promise((r) => setTimeout(r, 1e3));
128
- return res.toString("hex");
129
- };
130
- const getPublicKey = async (pathString, { secp256k1, retryOnError }) => {
131
- logger.info(`[device] getPublicKey (${pathString})`);
132
- const path = getPathFromPathString(pathString);
133
- const data = Buffer.concat([
134
- Buffer.from([path.length]),
135
- ...path.map((derivation) => {
136
- const buf = Buffer.alloc(4);
137
- buf.writeUInt32BE(derivation, 0);
138
- return buf;
139
- })
140
- ]);
141
- const curve = secp256k1 ? 1 : 2;
142
- const response = await run(
143
- (transport) => transport.send(224, 64, curve, 0, data),
144
- _nullishCoalesce(retryOnError, () => ( genericRetryOnError))
145
- );
146
- const pubKeyLength = response.readInt8(0);
147
- const pubKey = response.slice(1, pubKeyLength + 1).toString("hex").toUpperCase();
148
- const signature = response.slice(pubKeyLength + 1, response.length - _chunkDRMYBKL3cjs.STATUS_LENGTH).toString("base64");
149
- return { pubKey, signature };
150
- };
151
- const device = {
152
- authenticate: async ({ challenge: { challenge, name, role, keyHandle }, workspaceName }) => {
153
- logger.info(`[device] Authenticate`);
154
- _invariant2.default.call(void 0, role !== "READ_ONLY_API_KEY", "Invalid role for authenticate: READ_ONLY_API_KEY");
155
- const applicationBuffer = Buffer.from(_chunkDRMYBKL3cjs.APPID_VAULT_ADMINISTRATOR, "hex");
156
- const nameBuffer = Buffer.from(name);
157
- const workspaceBuffer = Buffer.from(workspaceName);
158
- const keyHandleData = Buffer.concat([
159
- Buffer.from(_chunkDRMYBKL3cjs.STR_ROLES[role], "hex"),
160
- Buffer.from([nameBuffer.length]),
161
- nameBuffer,
162
- Buffer.from([workspaceBuffer.length]),
163
- workspaceBuffer
164
- ]);
165
- const keyHandleDataLength = Buffer.alloc(2);
166
- keyHandleDataLength.writeUInt16BE(keyHandleData.length, 0);
167
- const data = Buffer.concat([
168
- Buffer.from(challenge, "base64"),
169
- applicationBuffer,
170
- Buffer.from([keyHandle.length]),
171
- Buffer.from(keyHandle, "hex"),
172
- keyHandleDataLength,
173
- keyHandleData
174
- ]);
175
- const authentication = await run(
176
- (transport) => sendByChunk(transport, [224, 2, 0, 0], data)
177
- );
178
- return removeStatus(authentication).toString("hex");
179
- },
180
- finalizePairingHandshake: async (params) => {
181
- const bufWithStatus = await run(
182
- (transport) => sendByChunk(transport, [224, 71, 0, 2], buildAttestation(params))
183
- );
184
- return removeStatus(bufWithStatus).toString("hex");
185
- },
186
- generateSeedFragment: async () => {
187
- logger.info(`[device] generateSeedFragment`);
188
- const path = getPathFromPathString(_chunkDRMYBKL3cjs.PATHS.KEY_MATERIAL);
189
- const data = Buffer.concat([
190
- Buffer.from([path.length]),
191
- ...path.map((derivation) => {
192
- const buf = Buffer.alloc(4);
193
- buf.writeUInt32BE(derivation, 0);
194
- return buf;
195
- })
196
- ]);
197
- const response = await run((transport) => transport.send(224, 68, 0, 0, data));
198
- return removeStatus(response).toString("base64");
199
- },
200
- generateWrappingKeyFragment: async () => {
201
- logger.info(`[device] generateWrappingKeyFragment`);
202
- const path = getPathFromPathString(_chunkDRMYBKL3cjs.PATHS.KEY_MATERIAL);
203
- const data = Buffer.concat([
204
- Buffer.from([path.length]),
205
- ...path.map((derivation) => {
206
- const buf = Buffer.alloc(4);
207
- buf.writeUInt32BE(derivation, 0);
208
- return buf;
209
- })
210
- ]);
211
- const response = await run((transport) => transport.send(224, 68, 1, 0, data));
212
- return removeStatus(response).toString("base64");
213
- },
214
- getAttestation: async () => {
215
- const bufWithStatus = await run((transport) => transport.send(224, 65, 0, 0));
216
- const buffer = removeStatus(bufWithStatus);
217
- const certLen = buffer.readInt8(32 + 65 + 1);
218
- return {
219
- attestation: {
220
- codeHash: buffer.slice(0, 32).toString("base64"),
221
- attestationPub: buffer.slice(32, 32 + 65).toString("base64"),
222
- certificate: buffer.slice(32 + 65, 32 + 65 + 2 + certLen).toString("base64")
223
- },
224
- buffer
225
- };
226
- },
227
- getConfidentialityKey: async () => {
228
- logger.info(`[device] getConfidentialityKey`);
229
- const bufWithStatus = await run((transport) => transport.send(224, 77, 0, 0));
230
- const buf = removeStatus(bufWithStatus);
231
- const keyLength = buf[0];
232
- const key = buf.slice(1, 1 + keyLength);
233
- const sig = buf.slice(1 + keyLength + 1);
234
- return {
235
- confidentialityKeyCurve25519: key.toString("hex"),
236
- confidentialityKeySignature: sig.toString("hex")
237
- };
238
- },
239
- getConfidentialityPubKey: () => getPublicKey(_chunkDRMYBKL3cjs.PATHS.CONFIDENTIALITY, { secp256k1: true }),
240
- getDeviceUserId: async () => {
241
- logger.info(`[device] getDeviceUserId`);
242
- const response = await run((transport) => transport.send(224, 82, 0, 0));
243
- return removeStatus(response).toString("hex").toUpperCase();
244
- },
245
- getU2FPubKey: () => getPublicKey(_chunkDRMYBKL3cjs.PATHS.U2F, { secp256k1: false }),
246
- getValidationPubKey: () => getPublicKey(_chunkDRMYBKL3cjs.PATHS.VALIDATION, { secp256k1: true }),
247
- hasPairing: async () => {
248
- logger.info(`[device] hasPairing`);
249
- const apdu = [224, 81, 0, 0, 181];
250
- const res = await run((transport) => transport.exchange(Buffer.from(apdu)));
251
- const hex = Buffer.from(res).toString("hex");
252
- return hex !== "6f45" && hex !== "6a87";
253
- },
254
- initPairingHandshake: async () => {
255
- const res = await run((transport) => transport.send(224, 70, 0, 0));
256
- const pubKeyLength = res.readInt8(0);
257
- const pubKey = res.slice(1, pubKeyLength + 1).toString("hex").toUpperCase();
258
- const signature = res.slice(pubKeyLength + 1, res.length - _chunkDRMYBKL3cjs.STATUS_LENGTH).toString("base64");
259
- return { pubKey, signature };
260
- },
261
- openSession: async (params) => {
262
- logger.info(`[device] openSession`);
263
- const { secureChannel } = params;
264
- const path = getPathFromPathString(_chunkDRMYBKL3cjs.PATHS.CONFIDENTIALITY);
265
- const dataDerivation = Buffer.concat([
266
- Buffer.from([path.length]),
267
- ...path.map((derivation) => {
268
- const buf = Buffer.alloc(4);
269
- buf.writeUInt32BE(derivation, 0);
270
- return buf;
271
- })
272
- ]);
273
- const pubKey = Buffer.from(secureChannel.pubKey, "hex");
274
- const sigBuffer = Buffer.from(secureChannel.certificate.signature, "base64");
275
- const attestationPubBuffer = Buffer.from(secureChannel.certificate.attestationPub, "base64");
276
- const certBuffer = Buffer.from(secureChannel.certificate.certificate, "base64");
277
- const attestation = Buffer.concat([
278
- Buffer.from([sigBuffer.length]),
279
- sigBuffer,
280
- attestationPubBuffer,
281
- Buffer.from([certBuffer.length]),
282
- certBuffer
283
- ]);
284
- const lengthAttestation = Buffer.alloc(2);
285
- lengthAttestation.writeUInt16BE(attestation.length, 0);
286
- const data = Buffer.concat([dataDerivation, pubKey, lengthAttestation, attestation]);
287
- await run(
288
- (transport) => sendByChunk(transport, [224, 66, 0, _chunkDRMYBKL3cjs.SCRIPT_IDS.INIT_SESSION], data)
289
- );
290
- },
291
- register: async (params) => {
292
- const { challenge: strChallenge, u2fRegisterData: _, name, role } = params;
293
- const challenge = Buffer.from(strChallenge, "hex");
294
- _invariant2.default.call(void 0, challenge.length === 32, "challenge hex is expected to have 32 bytes");
295
- const applicationBuf = Buffer.from(_chunkDRMYBKL3cjs.APPID_VAULT_ADMINISTRATOR, "hex");
296
- _invariant2.default.call(void 0, applicationBuf.length === 32, "application hex is expected to have 32 bytes");
297
- const userNameBuff = Buffer.from(name);
298
- const keyHandleData = Buffer.concat([
299
- Buffer.from(_chunkDRMYBKL3cjs.STR_ROLES[role], "hex"),
300
- Buffer.from([userNameBuff.length]),
301
- userNameBuff
302
- ]);
303
- const keyHandleDataLength = Buffer.alloc(2);
304
- keyHandleDataLength.writeUInt16BE(keyHandleData.length, 0);
305
- const data = Buffer.concat([challenge, applicationBuf, keyHandleDataLength, keyHandleData]);
306
- const response = await run(
307
- (transport) => sendByChunk(transport, [224, 1, 0, 0], data)
308
- );
309
- let i = 0;
310
- const rfu = response.slice(i, i + 1)[0];
311
- i += 1;
312
- const pubKey = response.slice(i, i + 65).toString("hex");
313
- i += 65;
314
- const keyHandleLength = response.slice(i, i + 1)[0];
315
- i++;
316
- const keyHandle = response.slice(i, i + keyHandleLength);
317
- i += keyHandleLength;
318
- return {
319
- u2fRegister: removeStatus(response),
320
- keyHandle,
321
- rfu,
322
- pubKey
323
- };
324
- },
325
- registerData: async (params) => {
326
- const { challenge: strChallenge } = params;
327
- const challenge = Buffer.from(strChallenge, "hex");
328
- _invariant2.default.call(void 0, challenge.length === 32, "challenge hex is expected to have 32 bytes");
329
- const response = await run((transport) => transport.send(224, 3, 0, 0, challenge));
330
- return removeStatus(response).toString("hex");
331
- },
332
- setPairing: async ({ pairing }) => {
333
- logger.info(`[device] setPairing`);
334
- const psdPayload = Buffer.from(pairing.blob, "base64");
335
- const length = Buffer.alloc(2);
336
- length.writeUInt16BE(psdPayload.length, 0);
337
- const final = Buffer.concat([length, psdPayload]);
338
- await run((transport) => sendByChunk(transport, [224, 78, 0, 0], final));
339
- },
340
- startKKPatternAsResponder: async (params) => {
341
- logger.info(`[device] startKKPatternAsResponder`);
342
- const data = buildAttestation(params);
343
- const bufWithStatus = await run(
344
- (transport) => sendByChunk(transport, [224, 76, 0, _chunkDRMYBKL3cjs.SCRIPT_IDS.ACCOUNT_MANAGER_SESSION], data)
345
- );
346
- const buffer = removeStatus(bufWithStatus);
347
- const dataLength = buffer.readInt8(0);
348
- return {
349
- handshake: buffer.slice(1, dataLength + 1).toString("base64"),
350
- signature: buffer.slice(dataLength + 1).toString("base64")
351
- };
352
- },
353
- startKPatternAsResponder: async (params) => {
354
- logger.info(`[device] startKPatternAsResponder`);
355
- const data = buildAttestation(params);
356
- await run(
357
- (transport) => sendByChunk(transport, [224, 73, 0, _chunkDRMYBKL3cjs.SCRIPT_IDS.ACCOUNT_MANAGER_SESSION], data)
358
- );
359
- },
360
- validateVaultOperation: async (params) => {
361
- logger.info(`[device] validateVaultOperation`);
362
- const path = getPathFromPathString(_chunkDRMYBKL3cjs.PATHS.VALIDATION);
363
- const paths = Buffer.concat([
364
- Buffer.from([path.length]),
365
- ...path.map((derivation) => {
366
- const buf = Buffer.alloc(4);
367
- buf.writeUInt32BE(derivation, 0);
368
- return buf;
369
- })
370
- ]);
371
- let nextActionId = 1;
372
- let finalResponse = null;
373
- while (!finalResponse) {
374
- const screen = Buffer.from(params.actions[nextActionId - 1], "base64");
375
- const length = Buffer.alloc(2);
376
- length.writeUInt16BE(screen.length, 0);
377
- const data = Buffer.concat([paths, length, screen]);
378
- const response = await run(
379
- (transport) => sendByChunk(transport, [224, 69, 0, 0], data)
380
- );
381
- const responseType = response.readInt8(0);
382
- let responseStatus = response.readUInt16BE(response.length - 2);
383
- switch (responseType) {
384
- case _chunkDRMYBKL3cjs.STREAMING_NEXT_ACTION:
385
- nextActionId = response.readUIntBE(1, 2);
386
- break;
387
- case _chunkDRMYBKL3cjs.STREAMING_RESPONSE:
388
- finalResponse = response.slice(3, response.length - 2);
389
- while (responseStatus !== 36864) {
390
- {
391
- const resp = await run((transport) => transport.send(0, 192, 0, 0));
392
- responseStatus = resp.readUInt16BE(resp.length - 2);
393
- finalResponse = Buffer.concat([finalResponse, removeStatus(resp)]);
394
- }
395
- }
396
- break;
397
- /* v8 ignore next -- @preserve */
398
- default:
399
- throw new Error(`Invalid response type: ${responseType}`);
400
- }
401
- }
402
- return finalResponse.toString("base64");
403
- },
404
- sendAPDU: async (apduCommand) => {
405
- const res = await run((transport) => transport.exchange(Buffer.from(apduCommand, "hex")));
406
- return Buffer.from(res).toString("hex");
407
- },
408
- getVersion: async () => {
409
- const res = await run((transport) => transport.send(176, 1, 0, 0));
410
- const appNameLen = res.readInt8(1);
411
- const appVersionLen = res.readInt8(2 + appNameLen);
412
- const appVersionHex = res.slice(2 + 1 + appNameLen, 2 + appNameLen + appVersionLen + 1);
413
- const appVersion = Buffer.from(appVersionHex).toString();
414
- return appVersion;
415
- },
416
- poll,
417
- pollApp
418
- };
419
- return device;
77
+ const { transportId } = options;
78
+ async function run(job, retryOnError = genericRetryOnError) {
79
+ return (0, rxjs.lastValueFrom)(require_device.withDevicePolling(transportId)((transport) => (0, rxjs.from)(job(transport)), retryOnError));
80
+ }
81
+ /* v8 ignore next -- @preserve */
82
+ const noRetry = () => false;
83
+ /* v8 ignore next -- @preserve */
84
+ const alwaysRetry = () => true;
85
+ const poll = async (opts = {}) => {
86
+ await run(async (_transport) => {}, opts.retryOnError ?? alwaysRetry);
87
+ try {
88
+ await getPublicKey(require_device.PATHS.U2F, {
89
+ secp256k1: true,
90
+ retryOnError: noRetry
91
+ });
92
+ return { isAppOpened: true };
93
+ } catch (err) {
94
+ if (require_device.isTransportStatusError(err) && genericRetryOnError(err)) return { isAppOpened: false };
95
+ throw err;
96
+ }
97
+ };
98
+ const pollApp = async (appName) => {
99
+ const res = await run((transport) => transport.send(224, 216, 0, 0, Buffer.from(appName, "utf8")));
100
+ await new Promise((r) => setTimeout(r, 1e3));
101
+ return res.toString("hex");
102
+ };
103
+ const getPublicKey = async (pathString, { secp256k1, retryOnError }) => {
104
+ logger.info(`[device] getPublicKey (${pathString})`);
105
+ const path = getPathFromPathString(pathString);
106
+ const data = Buffer.concat([Buffer.from([path.length]), ...path.map((derivation) => {
107
+ const buf = Buffer.alloc(4);
108
+ buf.writeUInt32BE(derivation, 0);
109
+ return buf;
110
+ })]);
111
+ const curve = secp256k1 ? 1 : 2;
112
+ const response = await run((transport) => transport.send(224, 64, curve, 0, data), retryOnError ?? genericRetryOnError);
113
+ const pubKeyLength = response.readInt8(0);
114
+ return {
115
+ pubKey: response.slice(1, pubKeyLength + 1).toString("hex").toUpperCase(),
116
+ signature: response.slice(pubKeyLength + 1, response.length - 2).toString("base64")
117
+ };
118
+ };
119
+ return {
120
+ authenticate: async ({ challenge: { challenge, name, role, keyHandle }, workspaceName }) => {
121
+ logger.info(`[device] Authenticate`);
122
+ (0, invariant.default)(role !== "READ_ONLY_API_KEY", "Invalid role for authenticate: READ_ONLY_API_KEY");
123
+ const applicationBuffer = Buffer.from(require_device.APPID_VAULT_ADMINISTRATOR, "hex");
124
+ const nameBuffer = Buffer.from(name);
125
+ const workspaceBuffer = Buffer.from(workspaceName);
126
+ const keyHandleData = Buffer.concat([
127
+ Buffer.from(require_device.STR_ROLES[role], "hex"),
128
+ Buffer.from([nameBuffer.length]),
129
+ nameBuffer,
130
+ Buffer.from([workspaceBuffer.length]),
131
+ workspaceBuffer
132
+ ]);
133
+ const keyHandleDataLength = Buffer.alloc(2);
134
+ keyHandleDataLength.writeUInt16BE(keyHandleData.length, 0);
135
+ const data = Buffer.concat([
136
+ Buffer.from(challenge, "base64"),
137
+ applicationBuffer,
138
+ Buffer.from([keyHandle.length]),
139
+ Buffer.from(keyHandle, "hex"),
140
+ keyHandleDataLength,
141
+ keyHandleData
142
+ ]);
143
+ return removeStatus(await run((transport) => sendByChunk(transport, [
144
+ 224,
145
+ 2,
146
+ 0,
147
+ 0
148
+ ], data))).toString("hex");
149
+ },
150
+ finalizePairingHandshake: async (params) => {
151
+ return removeStatus(await run((transport) => sendByChunk(transport, [
152
+ 224,
153
+ 71,
154
+ 0,
155
+ 2
156
+ ], buildAttestation(params)))).toString("hex");
157
+ },
158
+ generateSeedFragment: async () => {
159
+ logger.info(`[device] generateSeedFragment`);
160
+ const path = getPathFromPathString(require_device.PATHS.KEY_MATERIAL);
161
+ const data = Buffer.concat([Buffer.from([path.length]), ...path.map((derivation) => {
162
+ const buf = Buffer.alloc(4);
163
+ buf.writeUInt32BE(derivation, 0);
164
+ return buf;
165
+ })]);
166
+ return removeStatus(await run((transport) => transport.send(224, 68, 0, 0, data))).toString("base64");
167
+ },
168
+ generateWrappingKeyFragment: async () => {
169
+ logger.info(`[device] generateWrappingKeyFragment`);
170
+ const path = getPathFromPathString(require_device.PATHS.KEY_MATERIAL);
171
+ const data = Buffer.concat([Buffer.from([path.length]), ...path.map((derivation) => {
172
+ const buf = Buffer.alloc(4);
173
+ buf.writeUInt32BE(derivation, 0);
174
+ return buf;
175
+ })]);
176
+ return removeStatus(await run((transport) => transport.send(224, 68, 1, 0, data))).toString("base64");
177
+ },
178
+ getAttestation: async () => {
179
+ const buffer = removeStatus(await run((transport) => transport.send(224, 65, 0, 0)));
180
+ const certLen = buffer.readInt8(98);
181
+ return {
182
+ attestation: {
183
+ codeHash: buffer.slice(0, 32).toString("base64"),
184
+ attestationPub: buffer.slice(32, 97).toString("base64"),
185
+ certificate: buffer.slice(97, 99 + certLen).toString("base64")
186
+ },
187
+ buffer
188
+ };
189
+ },
190
+ getConfidentialityKey: async () => {
191
+ logger.info(`[device] getConfidentialityKey`);
192
+ const buf = removeStatus(await run((transport) => transport.send(224, 77, 0, 0)));
193
+ const keyLength = buf[0];
194
+ const key = buf.slice(1, 1 + keyLength);
195
+ const sig = buf.slice(1 + keyLength + 1);
196
+ return {
197
+ confidentialityKeyCurve25519: key.toString("hex"),
198
+ confidentialityKeySignature: sig.toString("hex")
199
+ };
200
+ },
201
+ getConfidentialityPubKey: () => getPublicKey(require_device.PATHS.CONFIDENTIALITY, { secp256k1: true }),
202
+ getDeviceUserId: async () => {
203
+ logger.info(`[device] getDeviceUserId`);
204
+ return removeStatus(await run((transport) => transport.send(224, 82, 0, 0))).toString("hex").toUpperCase();
205
+ },
206
+ getU2FPubKey: () => getPublicKey(require_device.PATHS.U2F, { secp256k1: false }),
207
+ getValidationPubKey: () => getPublicKey(require_device.PATHS.VALIDATION, { secp256k1: true }),
208
+ hasPairing: async () => {
209
+ logger.info(`[device] hasPairing`);
210
+ const apdu = [
211
+ 224,
212
+ 81,
213
+ 0,
214
+ 0,
215
+ 181
216
+ ];
217
+ const res = await run((transport) => transport.exchange(Buffer.from(apdu)));
218
+ const hex = Buffer.from(res).toString("hex");
219
+ return hex !== "6f45" && hex !== "6a87";
220
+ },
221
+ initPairingHandshake: async () => {
222
+ const res = await run((transport) => transport.send(224, 70, 0, 0));
223
+ const pubKeyLength = res.readInt8(0);
224
+ return {
225
+ pubKey: res.slice(1, pubKeyLength + 1).toString("hex").toUpperCase(),
226
+ signature: res.slice(pubKeyLength + 1, res.length - 2).toString("base64")
227
+ };
228
+ },
229
+ openSession: async (params) => {
230
+ logger.info(`[device] openSession`);
231
+ const { secureChannel } = params;
232
+ const path = getPathFromPathString(require_device.PATHS.CONFIDENTIALITY);
233
+ const dataDerivation = Buffer.concat([Buffer.from([path.length]), ...path.map((derivation) => {
234
+ const buf = Buffer.alloc(4);
235
+ buf.writeUInt32BE(derivation, 0);
236
+ return buf;
237
+ })]);
238
+ const pubKey = Buffer.from(secureChannel.pubKey, "hex");
239
+ const sigBuffer = Buffer.from(secureChannel.certificate.signature, "base64");
240
+ const attestationPubBuffer = Buffer.from(secureChannel.certificate.attestationPub, "base64");
241
+ const certBuffer = Buffer.from(secureChannel.certificate.certificate, "base64");
242
+ const attestation = Buffer.concat([
243
+ Buffer.from([sigBuffer.length]),
244
+ sigBuffer,
245
+ attestationPubBuffer,
246
+ Buffer.from([certBuffer.length]),
247
+ certBuffer
248
+ ]);
249
+ const lengthAttestation = Buffer.alloc(2);
250
+ lengthAttestation.writeUInt16BE(attestation.length, 0);
251
+ const data = Buffer.concat([
252
+ dataDerivation,
253
+ pubKey,
254
+ lengthAttestation,
255
+ attestation
256
+ ]);
257
+ await run((transport) => sendByChunk(transport, [
258
+ 224,
259
+ 66,
260
+ 0,
261
+ require_device.SCRIPT_IDS.INIT_SESSION
262
+ ], data));
263
+ },
264
+ register: async (params) => {
265
+ const { challenge: strChallenge, u2fRegisterData: _, name, role } = params;
266
+ const challenge = Buffer.from(strChallenge, "hex");
267
+ (0, invariant.default)(challenge.length === 32, "challenge hex is expected to have 32 bytes");
268
+ const applicationBuf = Buffer.from(require_device.APPID_VAULT_ADMINISTRATOR, "hex");
269
+ (0, invariant.default)(applicationBuf.length === 32, "application hex is expected to have 32 bytes");
270
+ const userNameBuff = Buffer.from(name);
271
+ const keyHandleData = Buffer.concat([
272
+ Buffer.from(require_device.STR_ROLES[role], "hex"),
273
+ Buffer.from([userNameBuff.length]),
274
+ userNameBuff
275
+ ]);
276
+ const keyHandleDataLength = Buffer.alloc(2);
277
+ keyHandleDataLength.writeUInt16BE(keyHandleData.length, 0);
278
+ const data = Buffer.concat([
279
+ challenge,
280
+ applicationBuf,
281
+ keyHandleDataLength,
282
+ keyHandleData
283
+ ]);
284
+ const response = await run((transport) => sendByChunk(transport, [
285
+ 224,
286
+ 1,
287
+ 0,
288
+ 0
289
+ ], data));
290
+ let i = 0;
291
+ const rfu = response.slice(i, i + 1)[0];
292
+ i += 1;
293
+ const pubKey = response.slice(i, i + 65).toString("hex");
294
+ i += 65;
295
+ const keyHandleLength = response.slice(i, i + 1)[0];
296
+ i++;
297
+ const keyHandle = response.slice(i, i + keyHandleLength);
298
+ i += keyHandleLength;
299
+ return {
300
+ u2fRegister: removeStatus(response),
301
+ keyHandle,
302
+ rfu,
303
+ pubKey
304
+ };
305
+ },
306
+ registerData: async (params) => {
307
+ const { challenge: strChallenge } = params;
308
+ const challenge = Buffer.from(strChallenge, "hex");
309
+ (0, invariant.default)(challenge.length === 32, "challenge hex is expected to have 32 bytes");
310
+ return removeStatus(await run((transport) => transport.send(224, 3, 0, 0, challenge))).toString("hex");
311
+ },
312
+ setPairing: async ({ pairing }) => {
313
+ logger.info(`[device] setPairing`);
314
+ const psdPayload = Buffer.from(pairing.blob, "base64");
315
+ const length = Buffer.alloc(2);
316
+ length.writeUInt16BE(psdPayload.length, 0);
317
+ const final = Buffer.concat([length, psdPayload]);
318
+ await run((transport) => sendByChunk(transport, [
319
+ 224,
320
+ 78,
321
+ 0,
322
+ 0
323
+ ], final));
324
+ },
325
+ startKKPatternAsResponder: async (params) => {
326
+ logger.info(`[device] startKKPatternAsResponder`);
327
+ const data = buildAttestation(params);
328
+ const buffer = removeStatus(await run((transport) => sendByChunk(transport, [
329
+ 224,
330
+ 76,
331
+ 0,
332
+ require_device.SCRIPT_IDS.ACCOUNT_MANAGER_SESSION
333
+ ], data)));
334
+ const dataLength = buffer.readInt8(0);
335
+ return {
336
+ handshake: buffer.slice(1, dataLength + 1).toString("base64"),
337
+ signature: buffer.slice(dataLength + 1).toString("base64")
338
+ };
339
+ },
340
+ startKPatternAsResponder: async (params) => {
341
+ logger.info(`[device] startKPatternAsResponder`);
342
+ const data = buildAttestation(params);
343
+ await run((transport) => sendByChunk(transport, [
344
+ 224,
345
+ 73,
346
+ 0,
347
+ require_device.SCRIPT_IDS.ACCOUNT_MANAGER_SESSION
348
+ ], data));
349
+ },
350
+ validateVaultOperation: async (params) => {
351
+ logger.info(`[device] validateVaultOperation`);
352
+ const path = getPathFromPathString(require_device.PATHS.VALIDATION);
353
+ const paths = Buffer.concat([Buffer.from([path.length]), ...path.map((derivation) => {
354
+ const buf = Buffer.alloc(4);
355
+ buf.writeUInt32BE(derivation, 0);
356
+ return buf;
357
+ })]);
358
+ let nextActionId = 1;
359
+ let finalResponse = null;
360
+ while (!finalResponse) {
361
+ const screen = Buffer.from(params.actions[nextActionId - 1], "base64");
362
+ const length = Buffer.alloc(2);
363
+ length.writeUInt16BE(screen.length, 0);
364
+ const data = Buffer.concat([
365
+ paths,
366
+ length,
367
+ screen
368
+ ]);
369
+ const response = await run((transport) => sendByChunk(transport, [
370
+ 224,
371
+ 69,
372
+ 0,
373
+ 0
374
+ ], data));
375
+ const responseType = response.readInt8(0);
376
+ let responseStatus = response.readUInt16BE(response.length - 2);
377
+ switch (responseType) {
378
+ case 1:
379
+ nextActionId = response.readUIntBE(1, 2);
380
+ break;
381
+ case 2:
382
+ finalResponse = response.slice(3, response.length - 2);
383
+ while (responseStatus !== 36864) {
384
+ const resp = await run((transport) => transport.send(0, 192, 0, 0));
385
+ responseStatus = resp.readUInt16BE(resp.length - 2);
386
+ finalResponse = Buffer.concat([finalResponse, removeStatus(resp)]);
387
+ }
388
+ break;
389
+ default: throw new Error(`Invalid response type: ${responseType}`);
390
+ }
391
+ }
392
+ return finalResponse.toString("base64");
393
+ },
394
+ sendAPDU: async (apduCommand) => {
395
+ const res = await run((transport) => transport.exchange(Buffer.from(apduCommand, "hex")));
396
+ return Buffer.from(res).toString("hex");
397
+ },
398
+ getVersion: async () => {
399
+ const res = await run((transport) => transport.send(176, 1, 0, 0));
400
+ const appNameLen = res.readInt8(1);
401
+ const appVersionLen = res.readInt8(2 + appNameLen);
402
+ const appVersionHex = res.slice(3 + appNameLen, 2 + appNameLen + appVersionLen + 1);
403
+ return Buffer.from(appVersionHex).toString();
404
+ },
405
+ poll,
406
+ pollApp
407
+ };
420
408
  }
421
-
422
- // src/trpc.ts
423
- var _client = require('@trpc/client');
424
- var _superjson = require('superjson'); var _superjson2 = _interopRequireDefault(_superjson);
425
- var createClient = (options) => {
426
- const trpc = _client.createTRPCClient.call(void 0, {
427
- links: [
428
- _client.httpLink.call(void 0, {
429
- url: `${options.baseUrl}/trpc`,
430
- transformer: _superjson2.default,
431
- headers(opts) {
432
- const contextHeaders = _optionalChain([opts, 'access', _2 => _2.op, 'access', _3 => _3.context, 'optionalAccess', _4 => _4.headers]) || {};
433
- return {
434
- ...options.debugAuthToken ? { "x-revault-debug-auth-token": options.debugAuthToken } : {},
435
- ...options.rootAuthToken ? { "x-revault-root-auth-token": options.rootAuthToken } : {},
436
- ...options.psdAuth ? { Authorization: `PsdAuth ${options.psdAuth}` } : {},
437
- ...options.apiAccessToken ? { Authorization: `Bearer ${options.apiAccessToken}` } : {},
438
- // Merge in any headers passed via context
439
- ...contextHeaders
440
- };
441
- }
442
- })
443
- ]
444
- });
445
- return trpc;
409
+ //#endregion
410
+ //#region src/trpc.ts
411
+ const createClient = (options) => {
412
+ return (0, _trpc_client.createTRPCClient)({ links: [(0, _trpc_client.httpLink)({
413
+ url: `${options.baseUrl}/trpc`,
414
+ transformer: superjson.default,
415
+ headers(opts) {
416
+ const contextHeaders = opts.op.context?.headers || {};
417
+ return {
418
+ ...options.debugAuthToken ? { "x-revault-debug-auth-token": options.debugAuthToken } : {},
419
+ ...options.rootAuthToken ? { "x-revault-root-auth-token": options.rootAuthToken } : {},
420
+ ...options.psdAuth ? { Authorization: `PsdAuth ${options.psdAuth}` } : {},
421
+ ...options.apiAccessToken ? { Authorization: `Bearer ${options.apiAccessToken}` } : {},
422
+ ...contextHeaders
423
+ };
424
+ }
425
+ })] });
446
426
  };
447
-
448
- // src/engine/index.ts
449
- async function genericRegister({
450
- device,
451
- name,
452
- role,
453
- getChallenge,
454
- submitChallenge,
455
- onScreenDisplayed
456
- }) {
457
- const [attestation, u2fPubKey, confidentialityKey] = await Promise.all([
458
- device.getAttestation(),
459
- device.getU2FPubKey(),
460
- device.getConfidentialityPubKey()
461
- ]);
462
- const ephemeralPubKey = await device.initPairingHandshake();
463
- const deviceData = {
464
- name,
465
- pubKey: u2fPubKey.pubKey,
466
- psdModel: "STAX",
467
- confidentialityKey: confidentialityKey.pubKey,
468
- psdEphemeralKey: ephemeralPubKey.pubKey,
469
- psdEphemeralKeyAttestation: {
470
- ...attestation.attestation,
471
- signature: ephemeralPubKey.signature
472
- }
473
- };
474
- const challenge = await getChallenge({ pubKey: u2fPubKey.pubKey, deviceData });
475
- const pairingPayload = await device.finalizePairingHandshake({
476
- handshake: challenge.handshake,
477
- partitionId: challenge.ciphertext,
478
- handshakeAttestation: challenge.handshakeAttestation
479
- });
480
- await _optionalChain([onScreenDisplayed, 'optionalCall', _5 => _5()]);
481
- const register = await device.register({
482
- challenge: challenge.challenge,
483
- u2fRegisterData: challenge.u2fRegisterData,
484
- name,
485
- role
486
- });
487
- const validationPubKey = await device.getValidationPubKey();
488
- const registerData = await device.registerData({ challenge: challenge.challenge });
489
- const attestationOffset = 67 + register.u2fRegister.readInt8(66);
490
- const u2fRegister = Buffer.concat([
491
- register.u2fRegister.slice(0, attestationOffset),
492
- Buffer.from([attestation.buffer.length]),
493
- attestation.buffer,
494
- register.u2fRegister.slice(attestationOffset)
495
- ]).toString("hex");
496
- const challengeResponse = {
497
- registerData,
498
- certificate: {
499
- ...attestation.attestation,
500
- signature: validationPubKey.signature
501
- },
502
- u2fRegister,
503
- u2fKeyHandle: register.keyHandle.toString("hex"),
504
- validationKey: validationPubKey.pubKey,
505
- pairingPayload
506
- };
507
- return submitChallenge({ pubKey: u2fPubKey.pubKey, challengeResponse });
427
+ //#endregion
428
+ //#region src/engine/index.ts
429
+ async function genericRegister({ device, name, role, getChallenge, submitChallenge, onScreenDisplayed }) {
430
+ const [attestation, u2fPubKey, confidentialityKey] = await Promise.all([
431
+ device.getAttestation(),
432
+ device.getU2FPubKey(),
433
+ device.getConfidentialityPubKey()
434
+ ]);
435
+ const ephemeralPubKey = await device.initPairingHandshake();
436
+ const deviceData = {
437
+ name,
438
+ pubKey: u2fPubKey.pubKey,
439
+ psdModel: "STAX",
440
+ confidentialityKey: confidentialityKey.pubKey,
441
+ psdEphemeralKey: ephemeralPubKey.pubKey,
442
+ psdEphemeralKeyAttestation: {
443
+ ...attestation.attestation,
444
+ signature: ephemeralPubKey.signature
445
+ }
446
+ };
447
+ const challenge = await getChallenge({
448
+ pubKey: u2fPubKey.pubKey,
449
+ deviceData
450
+ });
451
+ const pairingPayload = await device.finalizePairingHandshake({
452
+ handshake: challenge.handshake,
453
+ partitionId: challenge.ciphertext,
454
+ handshakeAttestation: challenge.handshakeAttestation
455
+ });
456
+ await onScreenDisplayed?.();
457
+ const register = await device.register({
458
+ challenge: challenge.challenge,
459
+ u2fRegisterData: challenge.u2fRegisterData,
460
+ name,
461
+ role
462
+ });
463
+ const validationPubKey = await device.getValidationPubKey();
464
+ const registerData = await device.registerData({ challenge: challenge.challenge });
465
+ const attestationOffset = 67 + register.u2fRegister.readInt8(66);
466
+ const u2fRegister = Buffer.concat([
467
+ register.u2fRegister.slice(0, attestationOffset),
468
+ Buffer.from([attestation.buffer.length]),
469
+ attestation.buffer,
470
+ register.u2fRegister.slice(attestationOffset)
471
+ ]).toString("hex");
472
+ const challengeResponse = {
473
+ registerData,
474
+ certificate: {
475
+ ...attestation.attestation,
476
+ signature: validationPubKey.signature
477
+ },
478
+ u2fRegister,
479
+ u2fKeyHandle: register.keyHandle.toString("hex"),
480
+ validationKey: validationPubKey.pubKey,
481
+ pairingPayload
482
+ };
483
+ return submitChallenge({
484
+ pubKey: u2fPubKey.pubKey,
485
+ challengeResponse
486
+ });
508
487
  }
509
488
  function createEngine(options, logger) {
510
- const clientOptions = {
511
- baseUrl: options.baseUrl
512
- };
513
- const client = createClient(clientOptions);
514
- const apiDevice = _chunkDRMYBKL3cjs.createApiDevice.call(void 0, options, logger);
515
- const base = {
516
- client,
517
- createClient: (overrides) => createClient({ ...clientOptions, ...overrides }),
518
- __options: options
519
- };
520
- const withDeviceIndex = function(deviceIndex) {
521
- const device = apiDevice.with(deviceIndex);
522
- const withPsd = { device };
523
- return decorateEngine({ ...this, ...withPsd });
524
- };
525
- const withTransportId = function(transportId) {
526
- const device = createRealDevice({ transportId }, logger);
527
- const withPsd = { device };
528
- return decorateEngine({ ...this, ...withPsd });
529
- };
530
- const withApiUser = function() {
531
- const withApiUser2 = { __isApiUser: true };
532
- return decorateEngine({ ...this, ...withApiUser2 });
533
- };
534
- const withWorkspace = function(workspaceName) {
535
- const withWorkspace2 = { __workspaceName: workspaceName };
536
- return decorateEngine({ ...this, ...withWorkspace2 });
537
- };
538
- const withOnboarding = function(onboardingId) {
539
- const withOnboarding2 = { __onboardingId: onboardingId };
540
- return decorateEngine({ ...this, ...withOnboarding2 });
541
- };
542
- function decorateEngine(engine) {
543
- function decorate(decorator) {
544
- Object.assign(engine, decorator(engine));
545
- }
546
- if (engine.device) {
547
- decorate(
548
- (engine2) => ({
549
- getWorkspaces: async () => {
550
- const { device, client: client2 } = engine2;
551
- const { pubKey } = await device.getU2FPubKey();
552
- const { workspaceNames } = await client2.auth.psd.findWorkspaceNames.query({ pubKey });
553
- return workspaceNames;
554
- },
555
- getWorkspacesForSso: async () => {
556
- const { device, client: client2 } = engine2;
557
- const { pubKey } = await device.getU2FPubKey();
558
- const { workspaces } = await client2.auth.sso.findWorkspaces.query({ pubKey });
559
- return workspaces;
560
- }
561
- })
562
- );
563
- }
564
- if (engine.__workspaceName && !engine.__psdToken && !engine.__apiAuth) {
565
- decorate((engine2) => {
566
- const { __workspaceName } = engine2;
567
- return {
568
- withPsdToken: function(token) {
569
- const withPsdAuth = { __psdToken: token };
570
- const psdAuth = `${__workspaceName}:${token}`;
571
- const client2 = engine2.createClient({ psdAuth });
572
- return decorateEngine({ ...this, client: client2, ...withPsdAuth });
573
- }
574
- };
575
- });
576
- }
577
- if (engine.device && engine.__onboardingId) {
578
- decorate((engine2) => {
579
- const { device, client: client2, __onboardingId } = engine2;
580
- async function enforcePairing() {
581
- if (await device.hasPairing()) return;
582
- const [{ pubKey }, confidentialityKey] = await Promise.all([
583
- device.getU2FPubKey(),
584
- device.getConfidentialityKey()
585
- ]);
586
- const pairing = await client2.onboarding.pairDevicePartition.mutate({
587
- pubKey,
588
- onboardingId: __onboardingId,
589
- data: {
590
- confidentialityKeyCurve25519: confidentialityKey.confidentialityKeyCurve25519,
591
- confidentialityKeySignature: confidentialityKey.confidentialityKeySignature
592
- }
593
- });
594
- await device.setPairing({ pairing });
595
- }
596
- return {
597
- claimDevice: async (params) => {
598
- const { role, deviceName } = params;
599
- const [{ pubKey }, { pubKey: confidentialityKey }] = await Promise.all([
600
- device.getU2FPubKey(),
601
- device.getConfidentialityPubKey()
602
- ]);
603
- await client2.onboarding.claimDevice.mutate({
604
- onboardingId: __onboardingId,
605
- claim: { role, pubKey, deviceName, confidentialityKey }
606
- });
607
- },
608
- collectWrappingKeyFragment: async (wrappingKey, params) => {
609
- const [{ pubKey }, confidentialityKey] = await Promise.all([
610
- device.getU2FPubKey(),
611
- device.getConfidentialityPubKey()
612
- ]);
613
- await device.openSession({
614
- secureChannel: {
615
- pubKey: wrappingKey.ephemeralPubKey,
616
- certificate: wrappingKey.ephemeralCertificate
617
- }
618
- });
619
- const { attestation } = await device.getAttestation();
620
- await _optionalChain([params, 'optionalAccess', _6 => _6.onScreenDisplayed, 'optionalCall', _7 => _7()]);
621
- const blob = await device.generateWrappingKeyFragment();
622
- await client2.onboarding.submitWrappingKeyFragment.mutate({
623
- pubKey,
624
- onboardingId: __onboardingId,
625
- fragment: {
626
- blob,
627
- ephemeralPubKey: confidentialityKey.pubKey,
628
- ephemeralCertificate: {
629
- ...attestation,
630
- signature: confidentialityKey.signature
631
- }
632
- }
633
- });
634
- },
635
- registerDevice: async (registerParams, params) => {
636
- const { role, name } = registerParams;
637
- const getChallengeMutation = role === "ADMIN" ? client2.onboarding.generateMasterAdminRegistrationChallenge : client2.onboarding.generateSharedOwnerRegistrationChallenge;
638
- const submitChallengeMutation = role === "ADMIN" ? client2.onboarding.submitMasterAdminRegistration : client2.onboarding.submitSharedOwnerRegistration;
639
- await genericRegister({
640
- device,
641
- name,
642
- role,
643
- getChallenge: ({ pubKey, deviceData }) => getChallengeMutation.mutate({
644
- onboardingId: __onboardingId,
645
- pubKey,
646
- deviceData
647
- }),
648
- submitChallenge: ({ pubKey, challengeResponse }) => submitChallengeMutation.mutate({
649
- onboardingId: engine2.__onboardingId,
650
- pubKey,
651
- // FIXME this should be renamed to `challengeResponse` on backend side
652
- response: challengeResponse
653
- }),
654
- onScreenDisplayed: _optionalChain([params, 'optionalAccess', _8 => _8.onScreenDisplayed])
655
- });
656
- },
657
- reviewSharedOwner: async (challenge, params) => {
658
- await enforcePairing();
659
- const { pubKey } = await device.getU2FPubKey();
660
- await device.startKPatternAsResponder({
661
- handshake: challenge.handshake,
662
- handshakeAttestation: challenge.handshakeAttestation,
663
- partitionId: challenge.partitionId
664
- });
665
- await _optionalChain([params, 'optionalAccess', _9 => _9.onScreenDisplayed, 'optionalCall', _10 => _10()]);
666
- const signature = await device.validateVaultOperation({
667
- actions: challenge.wActions
668
- });
669
- await client2.onboarding.submitReviewByMasterAdminSignature.mutate({
670
- onboardingId: __onboardingId,
671
- pubKey,
672
- signature
673
- });
674
- },
675
- collectSeedFragment: async (challenge, params) => {
676
- await enforcePairing();
677
- const [{ pubKey }, { attestation }] = await Promise.all([
678
- device.getU2FPubKey(),
679
- device.getAttestation()
680
- ]);
681
- await device.startKPatternAsResponder({
682
- handshake: challenge.handshake,
683
- handshakeAttestation: challenge.handshakeAttestation,
684
- partitionId: challenge.partitionId
685
- });
686
- await _optionalChain([params, 'optionalAccess', _11 => _11.onScreenDisplayed, 'optionalCall', _12 => _12()]);
687
- const challengeResponse = await device.validateVaultOperation({
688
- actions: challenge.wActions
689
- });
690
- const kkPattern = await device.startKKPatternAsResponder({
691
- partitionId: challenge.partitionId,
692
- handshake: challenge.kkHandshake,
693
- handshakeAttestation: challenge.kkHandshakeAttestation
694
- });
695
- const approverBlob = await device.generateSeedFragment();
696
- await client2.onboarding.submitSeedFragment.mutate({
697
- onboardingId: __onboardingId,
698
- pubKey,
699
- seedFragment: {
700
- challengeResponse,
701
- approverBlob,
702
- handshake: kkPattern.handshake,
703
- handshakeAttestation: {
704
- ...attestation,
705
- signature: kkPattern.signature
706
- }
707
- }
708
- });
709
- }
710
- };
711
- });
712
- }
713
- if (engine.device && engine.__workspaceName && !engine.__psdToken) {
714
- decorate(
715
- (engine2) => {
716
- const { device, client: client2, __workspaceName } = engine2;
717
- return {
718
- login: async function(opts) {
719
- const { pubKey } = await device.getU2FPubKey();
720
- const challenge = await client2.auth.psd.generateChallenge.mutate(
721
- {
722
- pubKey,
723
- workspaceName: __workspaceName
724
- },
725
- _chunkLH4QQXUHcjs.buildTrpcContext.call(void 0, { correlationId: _optionalChain([opts, 'optionalAccess', _13 => _13.correlationId]) })
726
- );
727
- await _optionalChain([opts, 'optionalAccess', _14 => _14.onScreenDisplayed, 'optionalCall', _15 => _15()]);
728
- const authentication = await device.authenticate({
729
- challenge,
730
- workspaceName: __workspaceName
731
- });
732
- const authPayload = {
733
- workspaceName: __workspaceName,
734
- pubKey,
735
- authentication,
736
- challengeId: challenge.challengeId,
737
- validityDurationSecs: _optionalChain([opts, 'optionalAccess', _16 => _16.validityDurationSecs])
738
- };
739
- const { token } = await client2.auth.psd.authenticate.mutate(
740
- { ...authPayload },
741
- _chunkLH4QQXUHcjs.buildTrpcContext.call(void 0, { correlationId: _optionalChain([opts, 'optionalAccess', _17 => _17.correlationId]) })
742
- );
743
- const withPsdAuth = {
744
- __psdToken: token
745
- };
746
- const psdAuth = `${engine2.__workspaceName}:${token}`;
747
- const __authClient = engine2.createClient({ psdAuth });
748
- return decorateEngine({ ...this, client: __authClient, ...withPsdAuth });
749
- },
750
- register: (registration) => {
751
- return genericRegister({
752
- device,
753
- name: registration.name,
754
- role: registration.role,
755
- getChallenge: async ({ deviceData }) => {
756
- const challenge = await client2.userRegistrations.generateChallenge.mutate({
757
- id: registration.id,
758
- workspaceName: __workspaceName,
759
- deviceData
760
- });
761
- return challenge;
762
- },
763
- submitChallenge: ({ challengeResponse }) => client2.userRegistrations.submitChallenge.mutate({
764
- workspaceName: __workspaceName,
765
- id: registration.id,
766
- challengeResponse
767
- })
768
- });
769
- }
770
- };
771
- }
772
- );
773
- }
774
- if (engine.__workspaceName && engine.__isApiUser && !engine.__apiAuth) {
775
- decorate(
776
- (engine2) => {
777
- const { client: client2, __workspaceName } = engine2;
778
- return {
779
- login: async function(credentials, opts) {
780
- const res = await client2.auth.authenticate.mutate(
781
- {
782
- apiKeyId: credentials.apiKeyId,
783
- apiKeySecret: credentials.apiKeySecret,
784
- workspace: __workspaceName
785
- },
786
- _chunkLH4QQXUHcjs.buildTrpcContext.call(void 0, { correlationId: _optionalChain([opts, 'optionalAccess', _18 => _18.correlationId]) })
787
- );
788
- const withApiAuth = {
789
- __apiAuth: res
790
- };
791
- const __authClient = engine2.createClient({ apiAccessToken: res.accessToken });
792
- return decorateEngine({ ...this, client: __authClient, ...withApiAuth });
793
- }
794
- };
795
- }
796
- );
797
- }
798
- if (engine.device && engine.__workspaceName && engine.__psdToken) {
799
- decorate((engine2) => {
800
- const { client: client2, device } = engine2;
801
- async function enforcePairing() {
802
- if (await device.hasPairing()) return;
803
- const confidentialityKey = await device.getConfidentialityKey();
804
- const pairing = await client2.debug.pairDevicePartition.mutate({
805
- confidentialityKeyCurve25519: confidentialityKey.confidentialityKeyCurve25519,
806
- confidentialityKeySignature: confidentialityKey.confidentialityKeySignature
807
- });
808
- await device.setPairing({ pairing });
809
- }
810
- const approveChallenge = async (challenge, params) => {
811
- await enforcePairing();
812
- await device.startKPatternAsResponder({
813
- handshake: challenge.handshake,
814
- handshakeAttestation: challenge.handshakeAttestation,
815
- partitionId: challenge.partitionId
816
- });
817
- await _optionalChain([params, 'optionalAccess', _19 => _19.onScreenDisplayed, 'optionalCall', _20 => _20()]);
818
- const signature = await device.validateVaultOperation({
819
- actions: challenge.wActions
820
- });
821
- return signature;
822
- };
823
- return {
824
- approve: async (request, params) => {
825
- const { challenge } = await client2.requests.getChallenge.query({ id: request.id });
826
- if (challenge.challengeType === "PSD") {
827
- const signature = await approveChallenge(challenge, params);
828
- await _optionalChain([params, 'optionalAccess', _21 => _21.onPsdChallengeSigned, 'optionalCall', _22 => _22()]);
829
- return client2.requests.approve.mutate(
830
- {
831
- id: request.id,
832
- data: { challengeType: "PSD", signature }
833
- },
834
- _chunkLH4QQXUHcjs.buildTrpcContext.call(void 0, params)
835
- );
836
- }
837
- if (challenge.challengeType === "SOFT") {
838
- return client2.requests.approve.mutate(
839
- {
840
- id: request.id,
841
- data: { challengeType: "SOFT" }
842
- },
843
- _chunkLH4QQXUHcjs.buildTrpcContext.call(void 0, params)
844
- );
845
- }
846
- throw new Error("Challenge type must be either PSD or SOFT");
847
- },
848
- approveChallenge,
849
- reject: (request, opts) => {
850
- return client2.requests.reject.mutate(
851
- { id: request.id, data: null },
852
- _chunkLH4QQXUHcjs.buildTrpcContext.call(void 0, opts)
853
- );
854
- }
855
- };
856
- });
857
- }
858
- if (engine.__workspaceName && engine.__apiAuth) {
859
- decorate((engine2) => {
860
- const { client: client2 } = engine2;
861
- return {
862
- getChallenge: async (request) => {
863
- const { challenge } = await client2.requests.getChallenge.query({ id: request.id });
864
- _invariant2.default.call(void 0, challenge.challengeType === "API", "Challenge type must be API");
865
- return challenge.payload;
866
- },
867
- approve: (request, signature) => {
868
- return client2.requests.approve.mutate({
869
- id: request.id,
870
- data: { challengeType: "API", signature }
871
- });
872
- },
873
- reject: (request, signature) => {
874
- return client2.requests.reject.mutate({
875
- id: request.id,
876
- data: { challengeType: "API", signature }
877
- });
878
- }
879
- };
880
- });
881
- }
882
- return engine;
883
- }
884
- return {
885
- ...base,
886
- withDeviceIndex,
887
- withTransportId,
888
- withApiUser,
889
- withWorkspace,
890
- withOnboarding
891
- };
489
+ const clientOptions = { baseUrl: options.baseUrl };
490
+ const client = createClient(clientOptions);
491
+ const apiDevice = require_device.createApiDevice(options, logger);
492
+ const base = {
493
+ client,
494
+ createClient: (overrides) => createClient({
495
+ ...clientOptions,
496
+ ...overrides
497
+ }),
498
+ __options: options
499
+ };
500
+ const withDeviceIndex = function(deviceIndex) {
501
+ const withPsd = { device: apiDevice.with(deviceIndex) };
502
+ return decorateEngine({
503
+ ...this,
504
+ ...withPsd
505
+ });
506
+ };
507
+ const withTransportId = function(transportId) {
508
+ const withPsd = { device: createRealDevice({ transportId }, logger) };
509
+ return decorateEngine({
510
+ ...this,
511
+ ...withPsd
512
+ });
513
+ };
514
+ const withApiUser = function() {
515
+ const withApiUser = { __isApiUser: true };
516
+ return decorateEngine({
517
+ ...this,
518
+ ...withApiUser
519
+ });
520
+ };
521
+ const withWorkspace = function(workspaceName) {
522
+ const withWorkspace = { __workspaceName: workspaceName };
523
+ return decorateEngine({
524
+ ...this,
525
+ ...withWorkspace
526
+ });
527
+ };
528
+ const withOnboarding = function(onboardingId) {
529
+ const withOnboarding = { __onboardingId: onboardingId };
530
+ return decorateEngine({
531
+ ...this,
532
+ ...withOnboarding
533
+ });
534
+ };
535
+ function decorateEngine(engine) {
536
+ function decorate(decorator) {
537
+ Object.assign(engine, decorator(engine));
538
+ }
539
+ if (engine.device) decorate((engine) => ({
540
+ getWorkspaces: async () => {
541
+ const { device, client } = engine;
542
+ const { pubKey } = await device.getU2FPubKey();
543
+ const { workspaceNames } = await client.auth.psd.findWorkspaceNames.query({ pubKey });
544
+ return workspaceNames;
545
+ },
546
+ getWorkspacesForSso: async () => {
547
+ const { device, client } = engine;
548
+ const { pubKey } = await device.getU2FPubKey();
549
+ const { workspaces } = await client.auth.sso.findWorkspaces.query({ pubKey });
550
+ return workspaces;
551
+ }
552
+ }));
553
+ if (engine.__workspaceName && !engine.__psdToken && !engine.__apiAuth) decorate((engine) => {
554
+ const { __workspaceName } = engine;
555
+ return { withPsdToken: function(token) {
556
+ const withPsdAuth = { __psdToken: token };
557
+ const psdAuth = `${__workspaceName}:${token}`;
558
+ const client = engine.createClient({ psdAuth });
559
+ return decorateEngine({
560
+ ...this,
561
+ client,
562
+ ...withPsdAuth
563
+ });
564
+ } };
565
+ });
566
+ if (engine.device && engine.__onboardingId) decorate((engine) => {
567
+ const { device, client, __onboardingId } = engine;
568
+ async function enforcePairing() {
569
+ if (await device.hasPairing()) return;
570
+ const [{ pubKey }, confidentialityKey] = await Promise.all([device.getU2FPubKey(), device.getConfidentialityKey()]);
571
+ const pairing = await client.onboarding.pairDevicePartition.mutate({
572
+ pubKey,
573
+ onboardingId: __onboardingId,
574
+ data: {
575
+ confidentialityKeyCurve25519: confidentialityKey.confidentialityKeyCurve25519,
576
+ confidentialityKeySignature: confidentialityKey.confidentialityKeySignature
577
+ }
578
+ });
579
+ await device.setPairing({ pairing });
580
+ }
581
+ return {
582
+ claimDevice: async (params) => {
583
+ const { role, deviceName } = params;
584
+ const [{ pubKey }, { pubKey: confidentialityKey }] = await Promise.all([device.getU2FPubKey(), device.getConfidentialityPubKey()]);
585
+ await client.onboarding.claimDevice.mutate({
586
+ onboardingId: __onboardingId,
587
+ claim: {
588
+ role,
589
+ pubKey,
590
+ deviceName,
591
+ confidentialityKey
592
+ }
593
+ });
594
+ },
595
+ collectWrappingKeyFragment: async (wrappingKey, params) => {
596
+ const [{ pubKey }, confidentialityKey] = await Promise.all([device.getU2FPubKey(), device.getConfidentialityPubKey()]);
597
+ await device.openSession({ secureChannel: {
598
+ pubKey: wrappingKey.ephemeralPubKey,
599
+ certificate: wrappingKey.ephemeralCertificate
600
+ } });
601
+ const { attestation } = await device.getAttestation();
602
+ await params?.onScreenDisplayed?.();
603
+ const blob = await device.generateWrappingKeyFragment();
604
+ await client.onboarding.submitWrappingKeyFragment.mutate({
605
+ pubKey,
606
+ onboardingId: __onboardingId,
607
+ fragment: {
608
+ blob,
609
+ ephemeralPubKey: confidentialityKey.pubKey,
610
+ ephemeralCertificate: {
611
+ ...attestation,
612
+ signature: confidentialityKey.signature
613
+ }
614
+ }
615
+ });
616
+ },
617
+ registerDevice: async (registerParams, params) => {
618
+ const { role, name } = registerParams;
619
+ const getChallengeMutation = role === "ADMIN" ? client.onboarding.generateMasterAdminRegistrationChallenge : client.onboarding.generateSharedOwnerRegistrationChallenge;
620
+ const submitChallengeMutation = role === "ADMIN" ? client.onboarding.submitMasterAdminRegistration : client.onboarding.submitSharedOwnerRegistration;
621
+ await genericRegister({
622
+ device,
623
+ name,
624
+ role,
625
+ getChallenge: ({ pubKey, deviceData }) => getChallengeMutation.mutate({
626
+ onboardingId: __onboardingId,
627
+ pubKey,
628
+ deviceData
629
+ }),
630
+ submitChallenge: ({ pubKey, challengeResponse }) => submitChallengeMutation.mutate({
631
+ onboardingId: engine.__onboardingId,
632
+ pubKey,
633
+ response: challengeResponse
634
+ }),
635
+ onScreenDisplayed: params?.onScreenDisplayed
636
+ });
637
+ },
638
+ reviewSharedOwner: async (challenge, params) => {
639
+ await enforcePairing();
640
+ const { pubKey } = await device.getU2FPubKey();
641
+ await device.startKPatternAsResponder({
642
+ handshake: challenge.handshake,
643
+ handshakeAttestation: challenge.handshakeAttestation,
644
+ partitionId: challenge.partitionId
645
+ });
646
+ await params?.onScreenDisplayed?.();
647
+ const signature = await device.validateVaultOperation({ actions: challenge.wActions });
648
+ await client.onboarding.submitReviewByMasterAdminSignature.mutate({
649
+ onboardingId: __onboardingId,
650
+ pubKey,
651
+ signature
652
+ });
653
+ },
654
+ reviewExternalSigners: async (challenge, params) => {
655
+ await enforcePairing();
656
+ const { pubKey } = await device.getU2FPubKey();
657
+ await device.startKPatternAsResponder({
658
+ handshake: challenge.handshake,
659
+ handshakeAttestation: challenge.handshakeAttestation,
660
+ partitionId: challenge.partitionId
661
+ });
662
+ await params?.onScreenDisplayed?.();
663
+ const signature = await device.validateVaultOperation({ actions: challenge.wActions });
664
+ await client.onboarding.submitExternalSignersRegistration.mutate({
665
+ onboardingId: __onboardingId,
666
+ pubKey,
667
+ signature
668
+ });
669
+ },
670
+ collectSeedFragment: async (challenge, params) => {
671
+ await enforcePairing();
672
+ const [{ pubKey }, { attestation }] = await Promise.all([device.getU2FPubKey(), device.getAttestation()]);
673
+ await device.startKPatternAsResponder({
674
+ handshake: challenge.handshake,
675
+ handshakeAttestation: challenge.handshakeAttestation,
676
+ partitionId: challenge.partitionId
677
+ });
678
+ await params?.onScreenDisplayed?.();
679
+ const challengeResponse = await device.validateVaultOperation({ actions: challenge.wActions });
680
+ const kkPattern = await device.startKKPatternAsResponder({
681
+ partitionId: challenge.partitionId,
682
+ handshake: challenge.kkHandshake,
683
+ handshakeAttestation: challenge.kkHandshakeAttestation
684
+ });
685
+ const approverBlob = await device.generateSeedFragment();
686
+ await client.onboarding.submitSeedFragment.mutate({
687
+ onboardingId: __onboardingId,
688
+ pubKey,
689
+ seedFragment: {
690
+ challengeResponse,
691
+ approverBlob,
692
+ handshake: kkPattern.handshake,
693
+ handshakeAttestation: {
694
+ ...attestation,
695
+ signature: kkPattern.signature
696
+ }
697
+ }
698
+ });
699
+ }
700
+ };
701
+ });
702
+ if (engine.device && engine.__workspaceName && !engine.__psdToken) decorate((engine) => {
703
+ const { device, client, __workspaceName } = engine;
704
+ return {
705
+ login: async function(opts) {
706
+ const { pubKey } = await device.getU2FPubKey();
707
+ const challenge = await client.auth.psd.generateChallenge.mutate({
708
+ pubKey,
709
+ workspaceName: __workspaceName
710
+ }, require_utils.buildTrpcContext({ correlationId: opts?.correlationId }));
711
+ await opts?.onScreenDisplayed?.();
712
+ const authPayload = {
713
+ workspaceName: __workspaceName,
714
+ pubKey,
715
+ authentication: await device.authenticate({
716
+ challenge,
717
+ workspaceName: __workspaceName
718
+ }),
719
+ challengeId: challenge.challengeId,
720
+ validityDurationSecs: opts?.validityDurationSecs
721
+ };
722
+ const { token } = await client.auth.psd.authenticate.mutate({ ...authPayload }, require_utils.buildTrpcContext({ correlationId: opts?.correlationId }));
723
+ const withPsdAuth = { __psdToken: token };
724
+ const psdAuth = `${engine.__workspaceName}:${token}`;
725
+ const __authClient = engine.createClient({ psdAuth });
726
+ return decorateEngine({
727
+ ...this,
728
+ client: __authClient,
729
+ ...withPsdAuth
730
+ });
731
+ },
732
+ register: (registration) => {
733
+ return genericRegister({
734
+ device,
735
+ name: registration.name,
736
+ role: registration.role,
737
+ getChallenge: async ({ deviceData }) => {
738
+ return await client.userRegistrations.generateChallenge.mutate({
739
+ id: registration.id,
740
+ workspaceName: __workspaceName,
741
+ deviceData
742
+ });
743
+ },
744
+ submitChallenge: ({ challengeResponse }) => client.userRegistrations.submitChallenge.mutate({
745
+ workspaceName: __workspaceName,
746
+ id: registration.id,
747
+ challengeResponse
748
+ })
749
+ });
750
+ }
751
+ };
752
+ });
753
+ if (engine.__workspaceName && engine.__isApiUser && !engine.__apiAuth) decorate((engine) => {
754
+ const { client, __workspaceName } = engine;
755
+ return { login: async function(credentials, opts) {
756
+ const res = await client.auth.authenticate.mutate({
757
+ apiKeyId: credentials.apiKeyId,
758
+ apiKeySecret: credentials.apiKeySecret,
759
+ workspace: __workspaceName
760
+ }, require_utils.buildTrpcContext({ correlationId: opts?.correlationId }));
761
+ const withApiAuth = { __apiAuth: res };
762
+ const __authClient = engine.createClient({ apiAccessToken: res.accessToken });
763
+ return decorateEngine({
764
+ ...this,
765
+ client: __authClient,
766
+ ...withApiAuth
767
+ });
768
+ } };
769
+ });
770
+ if (engine.device && engine.__workspaceName && engine.__psdToken) decorate((engine) => {
771
+ const { client, device } = engine;
772
+ async function enforcePairing() {
773
+ if (await device.hasPairing()) return;
774
+ const confidentialityKey = await device.getConfidentialityKey();
775
+ const pairing = await client.debug.pairDevicePartition.mutate({
776
+ confidentialityKeyCurve25519: confidentialityKey.confidentialityKeyCurve25519,
777
+ confidentialityKeySignature: confidentialityKey.confidentialityKeySignature
778
+ });
779
+ await device.setPairing({ pairing });
780
+ }
781
+ const approveChallenge = async (challenge, params) => {
782
+ await enforcePairing();
783
+ await device.startKPatternAsResponder({
784
+ handshake: challenge.handshake,
785
+ handshakeAttestation: challenge.handshakeAttestation,
786
+ partitionId: challenge.partitionId
787
+ });
788
+ await params?.onScreenDisplayed?.();
789
+ return await device.validateVaultOperation({ actions: challenge.wActions });
790
+ };
791
+ return {
792
+ approve: async (request, params) => {
793
+ const { challenge } = await client.requests.getChallenge.query({ id: request.id });
794
+ if (challenge.challengeType === "PSD") {
795
+ const signature = await approveChallenge(challenge, params);
796
+ await params?.onPsdChallengeSigned?.();
797
+ return client.requests.approve.mutate({
798
+ id: request.id,
799
+ data: {
800
+ challengeType: "PSD",
801
+ signature
802
+ }
803
+ }, require_utils.buildTrpcContext(params));
804
+ }
805
+ if (challenge.challengeType === "SOFT") return client.requests.approve.mutate({
806
+ id: request.id,
807
+ data: { challengeType: "SOFT" }
808
+ }, require_utils.buildTrpcContext(params));
809
+ throw new Error("Challenge type must be either PSD or SOFT");
810
+ },
811
+ approveChallenge,
812
+ reject: (request, opts) => {
813
+ return client.requests.reject.mutate({
814
+ id: request.id,
815
+ data: null
816
+ }, require_utils.buildTrpcContext(opts));
817
+ }
818
+ };
819
+ });
820
+ if (engine.__workspaceName && engine.__apiAuth) decorate((engine) => {
821
+ const { client } = engine;
822
+ return {
823
+ getChallenge: async (request) => {
824
+ const { challenge } = await client.requests.getChallenge.query({ id: request.id });
825
+ (0, invariant.default)(challenge.challengeType === "API", "Challenge type must be API");
826
+ return challenge.payload;
827
+ },
828
+ approve: (request, signature) => {
829
+ return client.requests.approve.mutate({
830
+ id: request.id,
831
+ data: {
832
+ challengeType: "API",
833
+ signature
834
+ }
835
+ });
836
+ },
837
+ reject: (request, signature) => {
838
+ return client.requests.reject.mutate({
839
+ id: request.id,
840
+ data: {
841
+ challengeType: "API",
842
+ signature
843
+ }
844
+ });
845
+ }
846
+ };
847
+ });
848
+ return engine;
849
+ }
850
+ return {
851
+ ...base,
852
+ withDeviceIndex,
853
+ withTransportId,
854
+ withApiUser,
855
+ withWorkspace,
856
+ withOnboarding
857
+ };
892
858
  }
893
-
894
-
895
-
896
-
897
- exports.createEngine = createEngine; exports.fetchAll = _chunkLH4QQXUHcjs.fetchAll; exports.fetchAllCursor = _chunkLH4QQXUHcjs.fetchAllCursor;
898
- /* v8 ignore next -- @preserve */
899
- //# sourceMappingURL=engine.cjs.map
859
+ //#endregion
860
+ exports.createEngine = createEngine;
861
+ exports.fetchAll = require_utils.fetchAll;
862
+ exports.fetchAllCursor = require_utils.fetchAllCursor;