@ledgerhq/revault-sdk 0.21.4 → 0.21.6

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.
@@ -73,7 +73,11 @@ function createApiDevice(options, logger) {
73
73
  );
74
74
  return {
75
75
  with: (index) => {
76
- const seed = genSeed({ salt: options.salt, index });
76
+ const __seed = genSeed({ salt: options.salt, index });
77
+ const getSeed = async () => {
78
+ if (typeof __seed === "string") return Promise.resolve(__seed);
79
+ return __seed;
80
+ };
77
81
  const authenticate = async ({
78
82
  challenge,
79
83
  workspaceName
@@ -82,7 +86,7 @@ function createApiDevice(options, logger) {
82
86
  if (role === "READ_ONLY_API_KEY")
83
87
  throw new Error("Invalid role for authenticate: READ_ONLY_API_KEY");
84
88
  const { data } = await deviceApi.post("/authenticate", {
85
- seed,
89
+ seed: await getSeed(),
86
90
  challenge: Buffer.from(challenge.challenge, "base64").toString("hex"),
87
91
  application: APPID_VAULT_ADMINISTRATOR,
88
92
  key_handle: challenge.keyHandle,
@@ -96,13 +100,13 @@ function createApiDevice(options, logger) {
96
100
  };
97
101
  const finalizePairingHandshake = async (params) => {
98
102
  const { handshake, partitionId } = params;
99
- const payload = { seed, handshake, ciphertext: partitionId };
103
+ const payload = { seed: await getSeed(), handshake, ciphertext: partitionId };
100
104
  const res = await deviceApi.post("/finalize-pairing-handshake", payload);
101
105
  return res.data;
102
106
  };
103
107
  const generateSeedFragment = async () => {
104
108
  const payload = {
105
- seed,
109
+ seed: await getSeed(),
106
110
  path: PATHS.KEY_MATERIAL,
107
111
  goal: 0
108
112
  // seed fragment
@@ -112,12 +116,14 @@ function createApiDevice(options, logger) {
112
116
  };
113
117
  const generateWrappingKeyFragment = async () => {
114
118
  const goal = 1;
115
- const payload = { seed, goal, path: PATHS.KEY_MATERIAL };
119
+ const payload = { seed: await getSeed(), goal, path: PATHS.KEY_MATERIAL };
116
120
  const res = await deviceApi.post("/generate-key-fragments", payload);
117
121
  return Buffer.from(res.data, "hex").toString("base64");
118
122
  };
119
123
  const getAttestation = async () => {
120
- const { data: attestationStr } = await deviceApi.post("/get-attestation", { seed });
124
+ const { data: attestationStr } = await deviceApi.post("/get-attestation", {
125
+ seed: await getSeed()
126
+ });
121
127
  const attestationBuffer = Buffer.from(attestationStr, "hex");
122
128
  const certLen = attestationBuffer.readInt8(32 + 65 + 1);
123
129
  return {
@@ -130,7 +136,7 @@ function createApiDevice(options, logger) {
130
136
  };
131
137
  };
132
138
  const getConfidentialityKey = async () => {
133
- const res = await deviceApi.post("/get-confidentiality-key", { seed });
139
+ const res = await deviceApi.post("/get-confidentiality-key", { seed: await getSeed() });
134
140
  return {
135
141
  confidentialityKeyCurve25519: res.data.confidentiality_key_curve25519,
136
142
  confidentialityKeySignature: res.data.confidentiality_key_signature
@@ -140,7 +146,9 @@ function createApiDevice(options, logger) {
140
146
  return getPublicKey({ path: PATHS.CONFIDENTIALITY });
141
147
  };
142
148
  const getDeviceUserId = async () => {
143
- const res = await deviceApi.post("/blue-device-id", { seed });
149
+ const res = await deviceApi.post("/blue-device-id", {
150
+ seed: await getSeed()
151
+ });
144
152
  return res.data.blue_device_id.toUpperCase();
145
153
  };
146
154
  const getU2FPubKey = async () => {
@@ -150,13 +158,13 @@ function createApiDevice(options, logger) {
150
158
  return getPublicKey({ path: PATHS.VALIDATION });
151
159
  };
152
160
  const hasPairing = async () => {
153
- const res = await deviceApi.post("/get-partition-ids", { seed });
161
+ const res = await deviceApi.post("/get-partition-ids", { seed: await getSeed() });
154
162
  return res.data.length > 0;
155
163
  };
156
164
  const initPairingHandshake = async () => {
157
165
  const { data } = await deviceApi.post(
158
166
  "/initiate-pairing-handshake",
159
- { seed }
167
+ { seed: await getSeed() }
160
168
  );
161
169
  return {
162
170
  pubKey: data.pubKey,
@@ -176,7 +184,7 @@ function createApiDevice(options, logger) {
176
184
  attestationCertificate
177
185
  ]);
178
186
  const payload = {
179
- seed,
187
+ seed: await getSeed(),
180
188
  path: PATHS.CONFIDENTIALITY,
181
189
  pubKey: secureChannel.pubKey,
182
190
  attestation: attestation.toString("hex"),
@@ -190,7 +198,7 @@ function createApiDevice(options, logger) {
190
198
  const register = async (params) => {
191
199
  const { challenge, u2fRegisterData, name, role } = params;
192
200
  const payload = {
193
- seed,
201
+ seed: await getSeed(),
194
202
  challenge,
195
203
  name,
196
204
  role: STR_ROLES[role],
@@ -215,13 +223,13 @@ function createApiDevice(options, logger) {
215
223
  };
216
224
  const registerData = async (params) => {
217
225
  const { challenge } = params;
218
- const payload = { seed, challenge };
226
+ const payload = { seed: await getSeed(), challenge };
219
227
  const res = await deviceApi.post("/u2f-register-data", payload);
220
228
  return res.data;
221
229
  };
222
230
  const setPairing = async ({ pairing }) => {
223
231
  const payload = {
224
- seed,
232
+ seed: await getSeed(),
225
233
  blob: pairing.blob,
226
234
  pairing: {
227
235
  bootstrap_enabled: pairing.pairing.bootstrapEnabled,
@@ -239,7 +247,7 @@ function createApiDevice(options, logger) {
239
247
  };
240
248
  const startKKPatternAsResponder = async (params) => {
241
249
  const payload = {
242
- seed,
250
+ seed: await getSeed(),
243
251
  script_id: SCRIPT_IDS.ACCOUNT_MANAGER_SESSION,
244
252
  handshake: params.handshake,
245
253
  // for device-api it's normal to have empty string as handshake_attestation
@@ -257,7 +265,7 @@ function createApiDevice(options, logger) {
257
265
  const startKPatternAsResponder = async (params) => {
258
266
  const { handshake, partitionId } = params;
259
267
  const payload = {
260
- seed,
268
+ seed: await getSeed(),
261
269
  script_id: SCRIPT_IDS.ACCOUNT_MANAGER_SESSION,
262
270
  handshake,
263
271
  // for device-api it's normal to have empty string as handshake_attestation
@@ -274,7 +282,7 @@ function createApiDevice(options, logger) {
274
282
  };
275
283
  const getPublicKey = async (params) => {
276
284
  const { path } = params;
277
- const payload = { seed, secp256k1: true, path };
285
+ const payload = { seed: await getSeed(), secp256k1: true, path };
278
286
  const res = await deviceApi.post("/get-public-key", payload);
279
287
  return {
280
288
  pubKey: res.data.pubKey,
@@ -284,7 +292,7 @@ function createApiDevice(options, logger) {
284
292
  const validateVaultOperation = async (params) => {
285
293
  const { actions } = params;
286
294
  const payload = {
287
- seed,
295
+ seed: await getSeed(),
288
296
  path: PATHS.VALIDATION,
289
297
  actions
290
298
  };
@@ -497,4 +505,4 @@ export {
497
505
  registerTransportModule,
498
506
  withDevicePolling
499
507
  };
500
- //# sourceMappingURL=chunk-7WN7G7BY.js.map
508
+ //# sourceMappingURL=chunk-OJW4TCAG.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/device/api-device.ts","../src/device/constants.ts","../src/device/utils.ts","../src/device/device-access.ts"],"sourcesContent":["import type {\n HsmCertificate,\n PsdAuthChallengeResponse,\n PsdPairingData,\n PubKey,\n} from \"@ledgerhq/revault-api\";\nimport axios from \"axios\";\nimport axiosRetry from \"axios-retry\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nimport type { Logger } from \"@/logger\";\n\nimport { APPID_VAULT_ADMINISTRATOR, PATHS, SCRIPT_IDS, STR_ROLES } from \"./constants\";\nimport type { Device } from \"./types\";\n\ntype Options = {\n /**\n * device-api URL\n */\n deviceApiUrl: string;\n\n /**\n * salt used by device-api\n */\n salt: string;\n\n /**\n * seed generation function used for device-api device spawn\n */\n genSeed: (p: { salt: string; index: number }) => string | Promise<string>;\n};\n\nexport type ApiDevice = {\n /**\n * bind a device to the given device index\n */\n with: (index: number) => Device;\n};\n\nexport function createApiDevice(options: Options, logger: Logger): ApiDevice {\n const { genSeed } = options;\n const sessionId = uuidv4();\n const deviceApi = axios.create({ baseURL: options.deviceApiUrl });\n\n axiosRetry(deviceApi, {\n retryDelay: axiosRetry.linearDelay(1000),\n retries: 3,\n /* v8 ignore start */\n retryCondition: () => true,\n onRetry: (retryCount, err) => {\n const formattedErr = `${err.code ?? `UNKNOWN`} on ${err.config?.method?.toUpperCase() ?? \"UNKNOWN_METHOD\"} ${err.config?.url ?? \"UNKNOWN_URL\"}`;\n logger.warning(\n `Retrying request to device-api (attempt ${retryCount}) - Cause: ${formattedErr}`,\n );\n },\n /* v8 ignore stop */\n });\n\n deviceApi.interceptors.request.use(\n (config) => {\n /* v8 ignore start */\n logger.debug(\n `[device-api] ${config.method?.toUpperCase()} ${config.url}${config.data ? ` ${JSON.stringify(config.data)}` : \"\"}`,\n );\n if ([\"post\", \"put\"].includes(config.method!)) {\n // when interceptor is called in combination with axios-retry, config.data can be a string or an object\n // and we should return either a string or an object compatible with the original type\n const isStringMode = typeof config.data === \"string\";\n const data = (isStringMode ? JSON.parse(config.data) : config.data) as Record<\n string,\n unknown\n >;\n const enhancedData = {\n sessionID: sessionId, // Used to ensure dedicated session if someones else uses same seed\n psd_model: \"02\", // Stax\n version: 3, // Used to properly enable noise channel\n ...data,\n };\n config.data = isStringMode ? JSON.stringify(enhancedData) : enhancedData;\n }\n return config;\n },\n /* v8 ignore stop */\n (error: Error) => Promise.reject(error),\n );\n\n return {\n with: (index: number): Device => {\n const __seed = genSeed({ salt: options.salt, index });\n\n const getSeed = async (): Promise<string> => {\n if (typeof __seed === \"string\") return Promise.resolve(__seed);\n return __seed;\n };\n\n const authenticate = async ({\n challenge,\n workspaceName,\n }: {\n challenge: PsdAuthChallengeResponse;\n workspaceName: string;\n }): Promise<string> => {\n const role = challenge.role;\n if (role === \"READ_ONLY_API_KEY\")\n throw new Error(\"Invalid role for authenticate: READ_ONLY_API_KEY\");\n const { data } = await deviceApi.post<string>(\"/authenticate\", {\n seed: await getSeed(),\n challenge: Buffer.from(challenge.challenge, \"base64\").toString(\"hex\"),\n application: APPID_VAULT_ADMINISTRATOR,\n key_handle: challenge.keyHandle,\n name: challenge.name,\n role: STR_ROLES[role],\n type: \"02\", // Stax\n workspaceName,\n });\n return data;\n };\n\n const finalizePairingHandshake = async (params: {\n handshake: string;\n partitionId: string;\n }): Promise<string> => {\n const { handshake, partitionId } = params;\n const payload = { seed: await getSeed(), handshake, ciphertext: partitionId };\n const res = await deviceApi.post<string>(\"/finalize-pairing-handshake\", payload);\n return res.data;\n };\n\n const generateSeedFragment = async (): Promise<string> => {\n const payload = {\n seed: await getSeed(),\n path: PATHS.KEY_MATERIAL,\n goal: 0, // seed fragment\n };\n const { data } = await deviceApi.post<string>(\"/generate-key-component\", payload);\n return data;\n };\n\n const generateWrappingKeyFragment = async (): Promise<string> => {\n const goal = 1; // means Wrapping Key\n const payload = { seed: await getSeed(), goal, path: PATHS.KEY_MATERIAL };\n const res = await deviceApi.post<string>(\"/generate-key-fragments\", payload);\n return Buffer.from(res.data, \"hex\").toString(\"base64\");\n };\n\n const getAttestation = async (): Promise<{\n attestation: {\n codeHash: string;\n attestationPub: string;\n certificate: string;\n };\n buffer: Buffer;\n }> => {\n const { data: attestationStr } = await deviceApi.post<string>(\"/get-attestation\", {\n seed: await getSeed(),\n });\n const attestationBuffer = Buffer.from(attestationStr, \"hex\");\n const certLen = attestationBuffer.readInt8(32 + 65 + 1);\n return {\n attestation: {\n codeHash: attestationBuffer.slice(0, 32).toString(\"base64\"),\n attestationPub: attestationBuffer.slice(32, 32 + 65).toString(\"base64\"),\n certificate: attestationBuffer.slice(32 + 65, 32 + 65 + 2 + certLen).toString(\"base64\"),\n },\n buffer: attestationBuffer,\n };\n };\n\n const getConfidentialityKey = async (): Promise<{\n confidentialityKeyCurve25519: string;\n confidentialityKeySignature: string;\n }> => {\n const res = await deviceApi.post<{\n confidentiality_key_curve25519: string;\n confidentiality_key_signature: string;\n }>(\"/get-confidentiality-key\", { seed: await getSeed() });\n return {\n confidentialityKeyCurve25519: res.data.confidentiality_key_curve25519,\n confidentialityKeySignature: res.data.confidentiality_key_signature,\n };\n };\n\n const getConfidentialityPubKey = async (): Promise<{ pubKey: string; signature: string }> => {\n return getPublicKey({ path: PATHS.CONFIDENTIALITY });\n };\n\n const getDeviceUserId = async (): Promise<string> => {\n const res = await deviceApi.post<{ blue_device_id: string }>(\"/blue-device-id\", {\n seed: await getSeed(),\n });\n return res.data.blue_device_id.toUpperCase();\n };\n\n const getU2FPubKey = async (): Promise<{ pubKey: string; signature: string }> => {\n return getPublicKey({ path: PATHS.U2F });\n };\n\n const getValidationPubKey = async (): Promise<{ pubKey: string; signature: string }> => {\n return getPublicKey({ path: PATHS.VALIDATION });\n };\n\n const hasPairing = async (): Promise<boolean> => {\n const res = await deviceApi.post<string[]>(\"/get-partition-ids\", { seed: await getSeed() });\n return res.data.length > 0;\n };\n\n const initPairingHandshake = async (): Promise<{ pubKey: string; signature: string }> => {\n const { data } = await deviceApi.post<{ attestation: string; pubKey: string }>(\n \"/initiate-pairing-handshake\",\n { seed: await getSeed() },\n );\n return {\n pubKey: data.pubKey,\n signature: Buffer.from(data.attestation, \"hex\").toString(\"base64\"),\n };\n };\n\n const openSession = async (params: {\n secureChannel: { pubKey: PubKey; certificate: HsmCertificate };\n }): Promise<void> => {\n const { secureChannel } = params;\n const signature = Buffer.from(secureChannel.certificate.signature, \"base64\");\n const attestationPubKey = Buffer.from(secureChannel.certificate.attestationPub, \"base64\");\n const attestationCertificate = Buffer.from(secureChannel.certificate.certificate, \"base64\");\n const attestation = Buffer.concat([\n Buffer.from([signature.length]),\n signature,\n attestationPubKey,\n Buffer.from([attestationCertificate.length]),\n attestationCertificate,\n ]);\n const payload = {\n seed: await getSeed(),\n path: PATHS.CONFIDENTIALITY,\n pubKey: secureChannel.pubKey,\n attestation: attestation.toString(\"hex\"),\n scriptId: SCRIPT_IDS.INIT_SESSION,\n };\n const { data: deviceResponse } = await deviceApi.post<string>(\"/open-session\", payload);\n if (deviceResponse !== \"9000\") {\n throw new Error(`device-api device failed with code: ${deviceResponse}`);\n }\n };\n\n const register = async (params: {\n challenge: string;\n u2fRegisterData: string;\n name: string;\n role: \"ADMIN\" | \"SHARED_OWNER\" | \"OPERATOR\";\n }): Promise<{\n u2fRegister: Buffer;\n keyHandle: Buffer;\n rfu: number;\n pubKey: string;\n }> => {\n const { challenge, u2fRegisterData, name, role } = params;\n const payload = {\n seed: await getSeed(),\n challenge,\n name,\n role: STR_ROLES[role],\n hsm_data: u2fRegisterData,\n type: \"02\", // Stax\n application: APPID_VAULT_ADMINISTRATOR,\n };\n const { data } = await deviceApi.post<string>(\"/register\", payload);\n const response = Buffer.from(data, \"hex\");\n let i = 0;\n const rfu = response.slice(i, (i += 1))[0]!;\n const pubKey = response.slice(i, (i += 65)).toString(\"hex\");\n const keyHandleLength = response.slice(i, ++i)[0]!;\n const keyHandle = response.slice(i, (i += keyHandleLength));\n return {\n u2fRegister: response.slice(0, response.length - 2),\n keyHandle,\n rfu,\n pubKey,\n };\n };\n\n const registerData = async (params: { challenge: string }): Promise<string> => {\n const { challenge } = params;\n const payload = { seed: await getSeed(), challenge };\n const res = await deviceApi.post<string>(\"/u2f-register-data\", payload);\n return res.data;\n };\n\n const setPairing = async ({ pairing }: { pairing: PsdPairingData }): Promise<void> => {\n const payload = {\n seed: await getSeed(),\n blob: pairing.blob,\n pairing: {\n bootstrap_enabled: pairing.pairing.bootstrapEnabled,\n partition_key: pairing.pairing.partitionKey,\n workspace_name: pairing.pairing.workspaceName,\n },\n partition_key_attestation: {\n code_hash: pairing.partitionKeyAttestation.codeHash,\n attestation_pub: pairing.partitionKeyAttestation.attestationPub,\n certificate: pairing.partitionKeyAttestation.certificate,\n signature: pairing.partitionKeyAttestation.signature,\n },\n };\n await deviceApi.post(\"/set-partition-key\", payload);\n };\n\n const startKKPatternAsResponder = async (params: {\n handshake: string;\n handshakeAttestation: HsmCertificate;\n partitionId: string;\n }): Promise<{ handshake: string; signature: string }> => {\n const payload = {\n seed: await getSeed(),\n script_id: SCRIPT_IDS.ACCOUNT_MANAGER_SESSION,\n handshake: params.handshake,\n // for device-api it's normal to have empty string as handshake_attestation\n handshake_attestation: \"\",\n partition_id: params.partitionId,\n };\n const { data } = await deviceApi.post<string>(\"/start-kk-pattern-as-responder\", payload);\n const buffer = Buffer.from(data, \"hex\");\n const dataLength = buffer.readInt8(0);\n return {\n handshake: buffer.slice(1, dataLength + 1).toString(\"base64\"),\n signature: buffer.slice(dataLength + 1).toString(\"base64\"),\n };\n };\n\n const startKPatternAsResponder = async (params: {\n handshake: string;\n handshakeAttestation: HsmCertificate;\n partitionId: string;\n }): Promise<void> => {\n const { handshake, partitionId } = params;\n const payload = {\n seed: await getSeed(),\n script_id: SCRIPT_IDS.ACCOUNT_MANAGER_SESSION,\n handshake,\n // for device-api it's normal to have empty string as handshake_attestation\n handshake_attestation: \"\",\n partition_id: partitionId,\n };\n const { data: deviceResponse } = await deviceApi.post<string>(\n \"/start-k-pattern-as-responder\",\n payload,\n );\n if (deviceResponse !== \"9000\") {\n throw new Error(`device-api device failed with code: ${deviceResponse}`);\n }\n };\n\n const getPublicKey = async (params: {\n path: string;\n }): Promise<{ pubKey: string; signature: string }> => {\n const { path } = params;\n type DeviceApiGetPubKeyResponse = { attestation: string; pubKey: string };\n const payload = { seed: await getSeed(), secp256k1: true, path };\n const res = await deviceApi.post<DeviceApiGetPubKeyResponse>(\"/get-public-key\", payload);\n return {\n pubKey: res.data.pubKey,\n signature: Buffer.from(res.data.attestation, \"hex\").toString(\"base64\"),\n };\n };\n\n const validateVaultOperation = async (params: { actions: string[] }): Promise<string> => {\n const { actions } = params;\n const payload = {\n seed: await getSeed(),\n path: PATHS.VALIDATION,\n actions,\n };\n const { data: signature } = await deviceApi.post<string>(\"/validate-op\", payload);\n return signature;\n };\n\n const sendAPDU = (_apdu: string): Promise<string> => {\n logger.info(\"Can't send arbitrary APDU to software device\");\n return Promise.resolve(\"9000\");\n };\n\n const getVersion = async (): Promise<string> => {\n return \"1.2.3\";\n };\n\n const poll = async (): Promise<{ isAppOpened: boolean }> => {\n await new Promise((r) => setTimeout(r, 1e3));\n return { isAppOpened: true };\n };\n\n const pollApp = async (): Promise<string> => {\n await new Promise((r) => setTimeout(r, 1e3));\n return \"9000\";\n };\n\n return {\n authenticate,\n finalizePairingHandshake,\n generateSeedFragment,\n generateWrappingKeyFragment,\n getAttestation,\n getConfidentialityKey,\n getConfidentialityPubKey,\n getDeviceUserId,\n getU2FPubKey,\n getValidationPubKey,\n hasPairing,\n initPairingHandshake,\n openSession,\n register,\n registerData,\n setPairing,\n startKKPatternAsResponder,\n startKPatternAsResponder,\n validateVaultOperation,\n getVersion,\n sendAPDU,\n poll,\n pollApp,\n };\n },\n };\n}\n","export const PATHS = {\n U2F: \"5655636'/5583430'\",\n CONFIDENTIALITY: \"5655636'/4410950'\",\n KEY_MATERIAL: \"5655636'/4932953'\",\n VALIDATION: \"5655636'/5652812'\",\n} as const;\n\nexport const STATUS_LENGTH = 2;\n\nexport const SCRIPT_IDS = {\n INIT_SESSION: 3,\n ACCOUNT_MANAGER_SESSION: 2,\n} as const;\n\nexport const STR_ROLES: Record<\"OPERATOR\" | \"ADMIN\" | \"SHARED_OWNER\", string> = {\n OPERATOR: \"00\",\n ADMIN: \"01\",\n SHARED_OWNER: \"02\",\n} as const;\n\nexport const APPID_VAULT_ADMINISTRATOR =\n \"ad5be1a1fe011ce7f53ae081a22ae000a42021f3f94106a3bac9f76e8230e4b9\";\n\nconst all61xxStatus = [];\nfor (let i = 0x6100; i <= 0x61ff; i++) {\n all61xxStatus.push(i);\n}\n\nexport const PAGINATED_STATUS = all61xxStatus;\nexport const STREAMING_RESPONSE = 0x02;\nexport const STREAMING_NEXT_ACTION = 0x01;\n","import { TransportStatusError } from \"@ledgerhq/errors\";\n\nexport const isTransportStatusError = (error: unknown): error is TransportStatusError => {\n return (\n error instanceof TransportStatusError ||\n (error instanceof Error && \"statusCode\" in error && error.message.startsWith(\"Ledger device:\"))\n );\n};\n\nconst CANCEL_STATUS_CODES = [\n 0x6985, // cancel on Ledger Blue\n\n // STAX\n 0xb00c, // cancel collect wk fragment\n 0xb00d, // cancel user registration\n 0xb010, // cancel review\n 0xb012, // cancel master seed generation\n 0xb013, // cancel login\n];\n\nexport const isDeviceCancelError = (error: Error): boolean => {\n return isTransportStatusError(error) && CANCEL_STATUS_CODES.includes(error.statusCode);\n};\n","// ------------------------------------------------------------------------------------------------\n// ------------------------------------------------------------------------------------------------\n// THIS IS SOME HORRIBLE CODE IMPORTED JUST\n// FOR THE SAKE OF NOT IMPORTING UGLY, WICKED, AND\n// BROKEN @ledgerhq/live-* LIBRARIES\n//\n// IT'S MEANT TO BE CONSIDERED AS A BLACK BOX\n// ------------------------------------------------------------------------------------------------\n// ------------------------------------------------------------------------------------------------\nimport {\n BluetoothRequired,\n CantOpenDevice,\n DeviceHalted,\n FirmwareOrAppUpdateRequired,\n TransportInterfaceNotAvailable,\n TransportStatusError,\n TransportWebUSBGestureRequired,\n} from \"@ledgerhq/errors\";\nimport type Transport from \"@ledgerhq/hw-transport\";\nimport { Observable, throwError, timer } from \"rxjs\";\nimport { catchError, mergeMap, retryWhen } from \"rxjs/operators\";\n\nconst initialErrorRemapping = (error: Error): Observable<never> =>\n throwError(\n error && error instanceof TransportStatusError && error.statusCode === 0x6faa\n ? new DeviceHalted(error.message)\n : error instanceof TransportStatusError && error.statusCode === 0x6b00\n ? new FirmwareOrAppUpdateRequired(error.message)\n : error,\n );\n\n// eslint-disable-next-line @typescript-eslint/no-empty-function\nconst never = new Promise(() => {});\n\ntype Discovery = Observable<{\n type: \"add\" | \"remove\";\n id: string;\n name: string;\n}>;\n\nexport type TransportModule = {\n // unique transport name that identify the transport module\n id: string;\n // open a device by an id, this id must be unique across all modules\n // you can typically prefix it with `something|` that identify it globally\n // returns falsy if the transport module can't handle this id\n // here, open means we want to START doing something with the transport\n open: (id: string) => Promise<Transport> | null | undefined;\n // here, close means we want to STOP doing something with the transport\n close?: (transport: Transport, id: string) => Promise<void> | null | undefined;\n // disconnect/interrupt a device connection globally\n // returns falsy if the transport module can't handle this id\n disconnect: (id: string) => Promise<void> | null | undefined;\n // optional observable that allows to discover a transport\n discovery?: Discovery;\n};\n\nconst modules: TransportModule[] = [];\n\nexport const registerTransportModule = (module: TransportModule): void => {\n modules.push(module);\n};\n\nexport const close = (transport: Transport, deviceId: string): Promise<void> => {\n for (const m of modules) {\n const p = m.close?.(transport, deviceId);\n if (p) return p;\n }\n // fallback on an actual close\n return transport.close();\n};\n\nexport const open = (deviceId: string): Promise<Transport> => {\n for (const m of modules) {\n const p = m.open(deviceId);\n if (p) return p;\n }\n return Promise.reject(new Error(`Can't find handler to open ${deviceId}`));\n};\n\nconst transportFinally =\n (cleanup: () => Promise<void>) =>\n <T>(observable: Observable<T>): Observable<T> =>\n // @ts-expect-error typescript not checking against the instanceof\n Observable.create((o) => {\n let done = false;\n\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n const finalize = (): any => {\n if (done) return never;\n done = true;\n return cleanup();\n };\n\n const sub = observable.subscribe({\n next: (e) => o.next(e),\n complete: () => {\n void finalize().then(() => o.complete());\n },\n error: (e) => {\n void finalize().then(() => o.error(e));\n },\n });\n return () => {\n sub.unsubscribe();\n void finalize();\n };\n });\n\ntype AccessHook = () => () => void;\n\nconst accessHooks: AccessHook[] = [];\n\nconst deviceQueues = {};\n\nexport const withDevice =\n (deviceId: string) =>\n <T>(job: (t: Transport) => Observable<T>): Observable<T> =>\n new Observable((o) => {\n // @ts-expect-error typescript not checking against the instanceof\n let unsubscribed;\n // @ts-expect-error typescript not checking against the instanceof\n let sub;\n // @ts-expect-error typescript not checking against the instanceof\n const deviceQueue = deviceQueues[deviceId] ?? Promise.resolve();\n\n // @ts-expect-error typescript not checking against the instanceof\n const finalize = (transport, cleanups): Promise<void> =>\n close(transport, deviceId)\n // eslint-disable-next-line @typescript-eslint/no-empty-function\n .catch(() => {})\n .then(() => {\n // @ts-expect-error typescript not checking against the instanceof\n cleanups.forEach((c) => c());\n });\n\n // when we'll finish all the current job, we'll call finish\n // @ts-expect-error typescript not checking against the instanceof\n let finish;\n // this new promise is the next exec queue\n // @ts-expect-error typescript not checking against the instanceof\n deviceQueues[deviceId] = new Promise((resolve) => {\n finish = resolve;\n });\n // for any new job, we'll now wait the exec queue to be available\n deviceQueue\n .then(() => open(deviceId)) // open the transport\n // @ts-expect-error typescript not checking against the instanceof\n .then(async (transport) => {\n // @ts-expect-error typescript not checking against the instanceof\n if (unsubscribed) {\n // it was unsubscribed prematurely\n // @ts-expect-error typescript not checking against the instanceof\n return finalize(transport, [finish]);\n }\n\n if (\n transport.requestConnectionPriority &&\n typeof transport.requestConnectionPriority === \"function\"\n ) {\n await transport.requestConnectionPriority(\"High\");\n }\n\n return transport;\n })\n // @ts-expect-error typescript not checking against the instanceof\n .catch((e) => {\n // @ts-expect-error typescript not checking against the instanceof\n finish();\n if (e instanceof BluetoothRequired) throw e;\n if (e instanceof TransportWebUSBGestureRequired) throw e;\n if (e instanceof TransportInterfaceNotAvailable) throw e;\n throw new CantOpenDevice(e.message);\n })\n // @ts-expect-error typescript not checking against the instanceof\n .then((transport) => {\n if (!transport) return;\n\n // @ts-expect-error typescript not checking against the instanceof\n if (unsubscribed) {\n // it was unsubscribed prematurely\n // @ts-expect-error typescript not checking against the instanceof\n return finalize(transport, [finish]);\n }\n\n const cleanups = accessHooks.map((hook) => hook());\n sub = job(transport) // $FlowFixMe\n .pipe(\n catchError(initialErrorRemapping),\n // $FlowFixMe\n transportFinally(() =>\n // @ts-expect-error typescript not checking against the instanceof\n finalize(transport, [...cleanups, finish]),\n ),\n )\n .subscribe(o);\n })\n // @ts-expect-error typescript not checking against the instanceof\n .catch((error) => o.error(error));\n return () => {\n unsubscribed = true;\n // @ts-expect-error typescript not checking against the instanceof\n if (sub) sub.unsubscribe();\n };\n });\n\nconst WITH_DEVICE_POLLING_DELAY = 500;\n\nexport const retryWhileErrors =\n (acceptError: (arg0: Error) => boolean) =>\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n (attempts: Observable<any>): Observable<any> =>\n attempts.pipe(\n mergeMap((error) => {\n if (!acceptError(error)) {\n return throwError(error);\n }\n\n return timer(WITH_DEVICE_POLLING_DELAY);\n }),\n );\n\nexport const withDevicePolling =\n (deviceId: string) =>\n <T>(\n job: (arg0: Transport) => Observable<T>,\n acceptError: (arg0: Error) => boolean = () => false,\n ): Observable<T> =>\n withDevice(deviceId)(job).pipe(retryWhen(retryWhileErrors(acceptError)));\n"],"m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YAAY,KAAK,GAAG;AACvB,eAAO,WAAW,KAAK;AAAA,MACzB;AAEA,aAAO,MAAM,yBAAyB;AAAA,IACxC,CAAC;AAAA,EACH;AAAA;AAEG,IAAM,oBACX,CAAC,aACD,CACE,KACA,cAAwC,MAAM,UAE9C,WAAW,QAAQ,EAAE,GAAG,EAAE,KAAK,UAAU,iBAAiB,WAAW,CAAC,CAAC;","names":["TransportStatusError"]}
@@ -1,6 +1,7 @@
1
1
  // src/crypto/utils.ts
2
2
  import crypto from "crypto";
3
3
  import elliptic2 from "elliptic";
4
+ import * as jose from "jose";
4
5
 
5
6
  // src/crypto/key-encoder.ts
6
7
  import asn1 from "asn1.js";
@@ -221,7 +222,7 @@ function extractPublicKey(pemKey) {
221
222
  pem.pop();
222
223
  const keyBuffer = Buffer.from(pem.join(""), "base64");
223
224
  const actualKeyBuffer = keyBuffer.slice(26);
224
- return actualKeyBuffer.toString("hex");
225
+ return actualKeyBuffer.toString("hex").toUpperCase();
225
226
  }
226
227
  function hexToPem(hexString, { isPrivate = true } = {}) {
227
228
  const keyEncoder = new KeyEncoder("p256");
@@ -255,8 +256,14 @@ function genKeys(entropy) {
255
256
  hexPubKey
256
257
  };
257
258
  }
259
+ var sign = async (privateKeyPem, base64Challenge) => {
260
+ const challengeDataBytes = jose.base64url.decode(base64Challenge);
261
+ const privateKey = crypto.createPrivateKey(privateKeyPem);
262
+ return await new jose.CompactSign(challengeDataBytes).setProtectedHeader({ alg: "ES256", typ: "JWT" }).sign(privateKey);
263
+ };
258
264
 
259
265
  export {
260
- genKeys
266
+ genKeys,
267
+ sign
261
268
  };
262
- //# sourceMappingURL=chunk-CZLZUISN.js.map
269
+ //# sourceMappingURL=chunk-OU3QTNYT.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../src/crypto/utils.ts","../src/crypto/key-encoder.ts"],"sourcesContent":["import crypto from \"crypto\";\nimport elliptic from \"elliptic\";\nimport * as jose from \"jose\";\n\nimport { KeyEncoder } from \"./key-encoder\";\nimport type { GeneratedKeys } from \"./types\";\n\nfunction extractPublicKey(pemKey: string): string {\n // convert the PEM formatted public key to raw public key in X9.62 uncompressed format\n // this is an oversimplified method and may not work with different curves or PEM formats\n const pem = pemKey.split(\"\\n\");\n pem.shift(); // remove the first line (BEGIN PUBLIC KEY)\n pem.pop(); // remove the last line (END PUBLIC KEY)\n // convert base64 to buffer\n const keyBuffer = Buffer.from(pem.join(\"\"), \"base64\");\n // assuming the first 26 bytes are the header for the SPKI formatted key.\n // the actual key should begin after this header.\n const actualKeyBuffer = keyBuffer.slice(26);\n return actualKeyBuffer.toString(\"hex\").toUpperCase();\n}\n\nfunction hexToPem(hexString: string, { isPrivate = true } = {}): string {\n const keyEncoder = new KeyEncoder(\"p256\");\n if (isPrivate) {\n return keyEncoder.encodePrivate(hexString, \"raw\", \"pem\");\n }\n return keyEncoder.encodePublic(hexString, \"raw\", \"pem\");\n}\n\n/**\n * If `entropy` is passed, will generate keys pair deterministically\n * else, random keys pair generated\n */\nexport function genKeys(entropy?: string): GeneratedKeys {\n if (entropy) {\n const ec = new elliptic.ec(\"p256\");\n const hashedEntropy = crypto.createHash(\"sha256\").update(entropy).digest(\"hex\");\n const keyPair = ec.genKeyPair({\n entropy: Buffer.from(hashedEntropy, \"hex\"),\n });\n return {\n privateKey: String(hexToPem(keyPair.getPrivate(\"hex\"))),\n publicKey: String(hexToPem(keyPair.getPublic(\"hex\"), { isPrivate: false })),\n hexPubKey: extractPublicKey(String(hexToPem(keyPair.getPublic(\"hex\"), { isPrivate: false }))),\n };\n }\n const { publicKey, privateKey } = crypto.generateKeyPairSync(\"ec\", {\n namedCurve: \"P-256\",\n publicKeyEncoding: { type: \"spki\", format: \"pem\" },\n privateKeyEncoding: { type: \"sec1\", format: \"pem\" },\n });\n const hexPubKey = extractPublicKey(publicKey);\n return {\n privateKey,\n publicKey,\n hexPubKey,\n };\n}\n\nexport const sign = async (privateKeyPem: string, base64Challenge: string): Promise<string> => {\n // Decode base64url challenge to bytes\n const challengeDataBytes = jose.base64url.decode(base64Challenge);\n\n // For EC private key format, we need to use a different import method\n // Since jose doesn't support SEC1 format directly, let's use Node.js crypto\n // Create a KeyObject from the EC private key\n const privateKey = crypto.createPrivateKey(privateKeyPem);\n\n // Use jose with the KeyObject\n return await new jose.CompactSign(challengeDataBytes)\n .setProtectedHeader({ alg: \"ES256\", typ: \"JWT\" })\n .sign(privateKey);\n};\n","// ========================================================================== //\n// //\n// DISCLAIMER //\n// //\n// This code has been blindly copy-pasted from: //\n// https://github.com/LedgerHQ/pkey-ts //\n// //\n// ========================================================================== //\n//\n// @ts-expect-error this library does not ship types\nimport asn1 from \"asn1.js\";\nimport BN from \"bn.js\";\nimport elliptic from \"elliptic\";\n\n/* cspell:disable */\nconst ECPrivateKeyASN = asn1.define(\"ECPrivateKey\", function () {\n // @ts-expect-error pure black box\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unnecessary-type-assertion\n const self = this as any;\n self\n .seq()\n .obj(\n self.key(\"version\").int(),\n self.key(\"privateKey\").octstr(),\n self.key(\"parameters\").explicit(0).objid().optional(),\n self.key(\"publicKey\").explicit(1).bitstr().optional(),\n );\n});\n\nconst ECPrivateKey8ASN = asn1.define(\n \"ECPrivateKey\",\n /* v8 ignore start */\n function () {\n // @ts-expect-error pure black box\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unnecessary-type-assertion\n const self = this as any;\n self\n .seq()\n .obj(\n self.key(\"version\").int(),\n self\n .key(\"privateKeyAlgorithm\")\n .seq()\n .obj(self.key(\"ecPublicKey\").objid(), self.key(\"curve\").objid()),\n self.key(\"privateKey\").octstr().contains(ECPrivateKeyASN),\n self.key(\"attributes\").explicit(0).bitstr().optional(),\n );\n },\n /* v8 ignore stop */\n);\n\nconst SubjectPublicKeyInfoASN = asn1.define(\"SubjectPublicKeyInfo\", function () {\n // @ts-expect-error pure black box\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unnecessary-type-assertion\n const self = this as any;\n self\n .seq()\n .obj(\n self.key(\"algorithm\").seq().obj(self.key(\"id\").objid(), self.key(\"curve\").objid()),\n self.key(\"pub\").bitstr(),\n );\n});\n\ntype CurveOptions = {\n curveParameters: number[];\n privatePEMOptions: { label: string };\n publicPEMOptions: { label: string };\n curve: elliptic.ec;\n};\n\nconst curves: Record<string, CurveOptions> = {\n secp256k1: {\n curveParameters: [1, 3, 132, 0, 10],\n privatePEMOptions: { label: \"EC PRIVATE KEY\" },\n publicPEMOptions: { label: \"PUBLIC KEY\" },\n curve: new elliptic.ec(\"secp256k1\"),\n },\n p256: {\n curveParameters: [1, 2, 840, 10045, 3, 1, 7], // OID for p256 curve\n privatePEMOptions: { label: \"EC PRIVATE KEY\" },\n publicPEMOptions: { label: \"PUBLIC KEY\" },\n curve: new elliptic.ec(\"p256\"),\n },\n};\n\ntype PrivateKeyPKCS1 = {\n version: BN;\n privateKey: Buffer;\n parameters: number[];\n publicKey?: {\n unused: number;\n data: Buffer;\n };\n};\n\ntype PrivateKeyPKCS8 = {\n version: BN;\n privateKey: PrivateKeyPKCS1;\n privateKeyAlgorithm: { ecPublicKey: number[]; curve: number[] };\n};\n\nexport type KeyFormat = \"raw\" | \"pem\" | \"der\";\n\nexport class KeyEncoder {\n algorithmID: number[];\n options: CurveOptions;\n\n constructor(options: string | CurveOptions) {\n if (typeof options === \"string\") {\n /* v8 ignore start */\n if (options !== \"secp256k1\" && options !== \"p256\") {\n throw new Error(\"Unknown curve \" + options);\n }\n /* v8 ignore stop */\n options = curves[options]!;\n }\n this.options = options;\n this.algorithmID = [1, 2, 840, 10045, 2, 1];\n }\n\n /* v8 ignore start */\n private PKCS1toPKCS8(privateKey: PrivateKeyPKCS1): PrivateKeyPKCS8 {\n return {\n version: new BN(0),\n privateKey,\n privateKeyAlgorithm: {\n ecPublicKey: this.algorithmID,\n curve: privateKey.parameters,\n },\n };\n }\n /* v8 ignore stop */\n\n privateKeyObject(rawPrivateKey: string, rawPublicKey: string): PrivateKeyPKCS1 {\n const privateKeyObject: PrivateKeyPKCS1 = {\n version: new BN(1),\n privateKey: Buffer.from(rawPrivateKey, \"hex\"),\n parameters: this.options.curveParameters,\n };\n\n if (rawPublicKey) {\n privateKeyObject.publicKey = {\n unused: 0,\n data: Buffer.from(rawPublicKey, \"hex\"),\n };\n }\n\n return privateKeyObject;\n }\n\n publicKeyObject(rawPublicKey: string): {\n algorithm: { id: number[]; curve: number[] };\n pub: { unused: number; data: Buffer };\n } {\n return {\n algorithm: {\n id: this.algorithmID,\n curve: this.options.curveParameters,\n },\n pub: {\n unused: 0,\n data: Buffer.from(rawPublicKey, \"hex\"),\n },\n };\n }\n\n encodePrivate(\n privateKey: string | Buffer,\n originalFormat: KeyFormat,\n destinationFormat: KeyFormat,\n destinationFormatType: \"pkcs8\" | \"pkcs1\" = \"pkcs1\",\n ): string {\n let privateKeyObject: PrivateKeyPKCS1;\n\n /* Parse the incoming private key and convert it to a private key object */\n switch (originalFormat) {\n case \"raw\": {\n if (typeof privateKey !== \"string\") {\n throw new Error(\"private key must be a string\");\n }\n const keyPair = this.options.curve.keyFromPrivate(privateKey, \"hex\");\n const rawPublicKey = keyPair.getPublic(\"hex\");\n privateKeyObject = this.privateKeyObject(privateKey, rawPublicKey);\n break;\n }\n case \"der\":\n if (typeof privateKey === \"string\") {\n privateKey = Buffer.from(privateKey, \"hex\");\n }\n privateKeyObject = ECPrivateKeyASN.decode(privateKey, \"der\");\n break;\n case \"pem\":\n if (typeof privateKey !== \"string\") {\n throw new Error(\"private key must be a string\");\n }\n privateKeyObject = ECPrivateKeyASN.decode(\n privateKey,\n \"pem\",\n this.options.privatePEMOptions,\n );\n break;\n /* v8 ignore start */\n default:\n throw new Error(\"invalid private key format\");\n /* v8 ignore stop */\n }\n\n /* Export the private key object to the desired format */\n switch (destinationFormat) {\n case \"raw\":\n if (destinationFormatType === \"pkcs1\") {\n return privateKeyObject.privateKey.toString(\"hex\");\n } else if (destinationFormatType === \"pkcs8\") {\n return this.PKCS1toPKCS8(privateKeyObject).privateKey.privateKey.toString(\"hex\");\n }\n break;\n case \"der\":\n if (destinationFormatType === \"pkcs1\") {\n return ECPrivateKeyASN.encode(privateKeyObject, \"der\").toString(\"hex\");\n } else if (destinationFormatType === \"pkcs8\") {\n return ECPrivateKey8ASN.encode(this.PKCS1toPKCS8(privateKeyObject), \"der\").toString(\n \"hex\",\n );\n }\n break;\n case \"pem\":\n if (destinationFormatType === \"pkcs1\") {\n return ECPrivateKeyASN.encode(privateKeyObject, \"pem\", this.options.privatePEMOptions);\n } else if (destinationFormatType === \"pkcs8\") {\n return ECPrivateKey8ASN.encode(this.PKCS1toPKCS8(privateKeyObject), \"pem\", {\n ...this.options.privatePEMOptions,\n label: \"PRIVATE KEY\",\n });\n }\n break;\n /* v8 ignore start */\n default:\n throw new Error(\"invalid destination format for private key\");\n /* v8 ignore stop */\n }\n\n throw new Error(\"unsupported destination format or type\");\n }\n\n encodePublic(\n publicKey: string | Buffer,\n originalFormat: KeyFormat,\n destinationFormat: KeyFormat,\n ): string {\n let publicKeyObject;\n\n switch (originalFormat) {\n case \"raw\":\n if (typeof publicKey !== \"string\") {\n throw new Error(\"public key must be a string\");\n }\n publicKeyObject = this.publicKeyObject(publicKey);\n break;\n case \"der\":\n if (typeof publicKey === \"string\") {\n publicKey = Buffer.from(publicKey, \"hex\");\n }\n publicKeyObject = SubjectPublicKeyInfoASN.decode(publicKey, \"der\");\n break;\n case \"pem\":\n if (typeof publicKey !== \"string\") {\n throw new Error(\"public key must be a string\");\n }\n publicKeyObject = SubjectPublicKeyInfoASN.decode(\n publicKey,\n \"pem\",\n this.options.publicPEMOptions,\n );\n break;\n /* v8 ignore start */\n default:\n throw new Error(\"invalid public key format\");\n /* v8 ignore stop */\n }\n\n /* Export the private key object to the desired format */\n switch (destinationFormat) {\n case \"raw\":\n return publicKeyObject.pub.data.toString(\"hex\");\n case \"der\":\n return SubjectPublicKeyInfoASN.encode(publicKeyObject, \"der\").toString(\"hex\");\n case \"pem\":\n return SubjectPublicKeyInfoASN.encode(\n publicKeyObject,\n \"pem\",\n this.options.publicPEMOptions,\n );\n /* v8 ignore start */\n default:\n throw new Error(\"invalid destination format for public key\");\n /* v8 ignore stop */\n }\n }\n}\n/* cspell:enable */\n"],"mappings":";AAAA,OAAO,YAAY;AACnB,OAAOA,eAAc;AACrB,YAAY,UAAU;;;ACQtB,OAAO,UAAU;AACjB,OAAO,QAAQ;AACf,OAAO,cAAc;AAGrB,IAAM,kBAAkB,KAAK,OAAO,gBAAgB,WAAY;AAG9D,QAAM,OAAO;AACb,OACG,IAAI,EACJ;AAAA,IACC,KAAK,IAAI,SAAS,EAAE,IAAI;AAAA,IACxB,KAAK,IAAI,YAAY,EAAE,OAAO;AAAA,IAC9B,KAAK,IAAI,YAAY,EAAE,SAAS,CAAC,EAAE,MAAM,EAAE,SAAS;AAAA,IACpD,KAAK,IAAI,WAAW,EAAE,SAAS,CAAC,EAAE,OAAO,EAAE,SAAS;AAAA,EACtD;AACJ,CAAC;AAED,IAAM,mBAAmB,KAAK;AAAA,EAC5B;AAAA;AAAA,EAEA,WAAY;AAGV,UAAM,OAAO;AACb,SACG,IAAI,EACJ;AAAA,MACC,KAAK,IAAI,SAAS,EAAE,IAAI;AAAA,MACxB,KACG,IAAI,qBAAqB,EACzB,IAAI,EACJ,IAAI,KAAK,IAAI,aAAa,EAAE,MAAM,GAAG,KAAK,IAAI,OAAO,EAAE,MAAM,CAAC;AAAA,MACjE,KAAK,IAAI,YAAY,EAAE,OAAO,EAAE,SAAS,eAAe;AAAA,MACxD,KAAK,IAAI,YAAY,EAAE,SAAS,CAAC,EAAE,OAAO,EAAE,SAAS;AAAA,IACvD;AAAA,EACJ;AAAA;AAEF;AAEA,IAAM,0BAA0B,KAAK,OAAO,wBAAwB,WAAY;AAG9E,QAAM,OAAO;AACb,OACG,IAAI,EACJ;AAAA,IACC,KAAK,IAAI,WAAW,EAAE,IAAI,EAAE,IAAI,KAAK,IA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KAAK,CAAC,CAAC;AAAA,MACtD,WAAW,OAAO,SAAS,QAAQ,UAAU,KAAK,GAAG,EAAE,WAAW,MAAM,CAAC,CAAC;AAAA,MAC1E,WAAW,iBAAiB,OAAO,SAAS,QAAQ,UAAU,KAAK,GAAG,EAAE,WAAW,MAAM,CAAC,CAAC,CAAC;AAAA,IAC9F;AAAA,EACF;AACA,QAAM,EAAE,WAAW,WAAW,IAAI,OAAO,oBAAoB,MAAM;AAAA,IACjE,YAAY;AAAA,IACZ,mBAAmB,EAAE,MAAM,QAAQ,QAAQ,MAAM;AAAA,IACjD,oBAAoB,EAAE,MAAM,QAAQ,QAAQ,MAAM;AAAA,EACpD,CAAC;AACD,QAAM,YAAY,iBAAiB,SAAS;AAC5C,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAEO,IAAM,OAAO,OAAO,eAAuB,oBAA6C;AAE7F,QAAM,qBAA0B,eAAU,OAAO,eAAe;AAKhE,QAAM,aAAa,OAAO,iBAAiB,aAAa;AAGxD,SAAO,MAAM,IAAS,iBAAY,kBAAkB,EACjD,mBAAmB,EAAE,KAAK,SAAS,KAAK,MAAM,CAAC,EAC/C,KAAK,UAAU;AACpB;","names":["elliptic","elliptic"]}
@@ -1,6 +1,7 @@
1
- "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// src/crypto/utils.ts
1
+ "use strict";Object.defineProperty(exports, "__esModule", {value: true}); function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) { newObj[key] = obj[key]; } } } newObj.default = obj; return newObj; } } function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }// src/crypto/utils.ts
2
2
  var _crypto = require('crypto'); var _crypto2 = _interopRequireDefault(_crypto);
3
3
  var _elliptic = require('elliptic'); var _elliptic2 = _interopRequireDefault(_elliptic);
4
+ var _jose = require('jose'); var jose = _interopRequireWildcard(_jose);
4
5
 
5
6
  // src/crypto/key-encoder.ts
6
7
  var _asn1js = require('asn1.js'); var _asn1js2 = _interopRequireDefault(_asn1js);
@@ -221,7 +222,7 @@ function extractPublicKey(pemKey) {
221
222
  pem.pop();
222
223
  const keyBuffer = Buffer.from(pem.join(""), "base64");
223
224
  const actualKeyBuffer = keyBuffer.slice(26);
224
- return actualKeyBuffer.toString("hex");
225
+ return actualKeyBuffer.toString("hex").toUpperCase();
225
226
  }
226
227
  function hexToPem(hexString, { isPrivate = true } = {}) {
227
228
  const keyEncoder = new KeyEncoder("p256");
@@ -255,8 +256,14 @@ function genKeys(entropy) {
255
256
  hexPubKey
256
257
  };
257
258
  }
259
+ var sign = async (privateKeyPem, base64Challenge) => {
260
+ const challengeDataBytes = jose.base64url.decode(base64Challenge);
261
+ const privateKey = _crypto2.default.createPrivateKey(privateKeyPem);
262
+ return await new jose.CompactSign(challengeDataBytes).setProtectedHeader({ alg: "ES256", typ: "JWT" }).sign(privateKey);
263
+ };
264
+
258
265
 
259
266
 
260
267
 
261
- exports.genKeys = genKeys;
262
- //# sourceMappingURL=chunk-JGXOGWYB.cjs.map
268
+ exports.genKeys = genKeys; exports.sign = sign;
269
+ //# sourceMappingURL=chunk-XO66ZFXN.cjs.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["/home/runner/_work/revault/revault/packages/sdk/lib/chunk-XO66ZFXN.cjs","../src/crypto/utils.ts","../src/crypto/key-encoder.ts"],"names":["elliptic"],"mappings":"AAAA;ACAA,gFAAmB;AACnB,wFAAqB;AACrB,uEAAsB;ADEtB;AACA;AEKA,iFAAiB;AACjB,yEAAe;AACf;AAGA,IAAM,gBAAA,EAAkB,gBAAA,CAAK,MAAA,CAAO,cAAA,EAAgB,QAAA,CAAA,EAAY;AAG9D,EAAA,MAAM,KAAA,EAAO,IAAA;AACb,EAAA,IAAA,CACG,GAAA,CAAI,CAAA,CACJ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AA,EAAW,WAAW,EAAA,EAAI,gBAAA,CAAO,mBAAA,CAAoB,IAAA,EAAM;AAAA,IACjE,UAAA,EAAY,OAAA;AAAA,IACZ,iBAAA,EAAmB,EAAE,IAAA,EAAM,MAAA,EAAQ,MAAA,EAAQ,MAAM,CAAA;AAAA,IACjD,kBAAA,EAAoB,EAAE,IAAA,EAAM,MAAA,EAAQ,MAAA,EAAQ,MAAM;AAAA,EACpD,CAAC,CAAA;AACD,EAAA,MAAM,UAAA,EAAY,gBAAA,CAAiB,SAAS,CAAA;AAC5C,EAAA,OAAO;AAAA,IACL,UAAA;AAAA,IACA,SAAA;AAAA,IACA;AAAA,EACF,CAAA;AACF;AAEO,IAAM,KAAA,EAAO,MAAA,CAAO,aAAA,EAAuB,eAAA,EAAA,GAA6C;AAE7F,EAAA,MAAM,mBAAA,EAA0B,IAAA,CAAA,SAAA,CAAU,MAAA,CAAO,eAAe,CAAA;AAKhE,EAAA,MAAM,WAAA,EAAa,gBAAA,CAAO,gBAAA,CAAiB,aAAa,CAAA;AAGxD,EAAA,OAAO,MAAM,IAAS,IAAA,CAAA,WAAA,CAAY,kBAAkB,CAAA,CACjD,kBAAA,CAAmB,EAAE,GAAA,EAAK,OAAA,EAAS,GAAA,EAAK,MAAM,CAAC,CAAA,CAC/C,IAAA,CAAK,UAAU,CAAA;AACpB,CAAA;AD+LA;AACA;AACE;AACA;AACF,+CAAC","file":"/home/runner/_work/revault/revault/packages/sdk/lib/chunk-XO66ZFXN.cjs","sourcesContent":[null,"import crypto from \"crypto\";\nimport elliptic from \"elliptic\";\nimport * as jose from \"jose\";\n\nimport { KeyEncoder } from \"./key-encoder\";\nimport type { GeneratedKeys } from \"./types\";\n\nfunction extractPublicKey(pemKey: string): string {\n // convert the PEM formatted public key to raw public key in X9.62 uncompressed format\n // this is an oversimplified method and may not work with different curves or PEM formats\n const pem = pemKey.split(\"\\n\");\n pem.shift(); // remove the first line (BEGIN PUBLIC KEY)\n pem.pop(); // remove the last line (END PUBLIC KEY)\n // convert base64 to buffer\n const keyBuffer = Buffer.from(pem.join(\"\"), \"base64\");\n // assuming the first 26 bytes are the header for the SPKI formatted key.\n // the actual key should begin after this header.\n const actualKeyBuffer = keyBuffer.slice(26);\n return actualKeyBuffer.toString(\"hex\").toUpperCase();\n}\n\nfunction hexToPem(hexString: string, { isPrivate = true } = {}): string {\n const keyEncoder = new KeyEncoder(\"p256\");\n if (isPrivate) {\n return keyEncoder.encodePrivate(hexString, \"raw\", \"pem\");\n }\n return keyEncoder.encodePublic(hexString, \"raw\", \"pem\");\n}\n\n/**\n * If `entropy` is passed, will generate keys pair deterministically\n * else, random keys pair generated\n */\nexport function genKeys(entropy?: string): GeneratedKeys {\n if (entropy) {\n const ec = new elliptic.ec(\"p256\");\n const hashedEntropy = crypto.createHash(\"sha256\").update(entropy).digest(\"hex\");\n const keyPair = ec.genKeyPair({\n entropy: Buffer.from(hashedEntropy, \"hex\"),\n });\n return {\n privateKey: String(hexToPem(keyPair.getPrivate(\"hex\"))),\n publicKey: String(hexToPem(keyPair.getPublic(\"hex\"), { isPrivate: false })),\n hexPubKey: extractPublicKey(String(hexToPem(keyPair.getPublic(\"hex\"), { isPrivate: false }))),\n };\n }\n const { publicKey, privateKey } = crypto.generateKeyPairSync(\"ec\", {\n namedCurve: \"P-256\",\n publicKeyEncoding: { type: \"spki\", format: \"pem\" },\n privateKeyEncoding: { type: \"sec1\", format: \"pem\" },\n });\n const hexPubKey = extractPublicKey(publicKey);\n return {\n privateKey,\n publicKey,\n hexPubKey,\n };\n}\n\nexport const sign = async (privateKeyPem: string, base64Challenge: string): Promise<string> => {\n // Decode base64url challenge to bytes\n const challengeDataBytes = jose.base64url.decode(base64Challenge);\n\n // For EC private key format, we need to use a different import method\n // Since jose doesn't support SEC1 format directly, let's use Node.js crypto\n // Create a KeyObject from the EC private key\n const privateKey = crypto.createPrivateKey(privateKeyPem);\n\n // Use jose with the KeyObject\n return await new jose.CompactSign(challengeDataBytes)\n .setProtectedHeader({ alg: \"ES256\", typ: \"JWT\" })\n .sign(privateKey);\n};\n","// ========================================================================== //\n// //\n// DISCLAIMER //\n// //\n// This code has been blindly copy-pasted from: //\n// https://github.com/LedgerHQ/pkey-ts //\n// //\n// ========================================================================== //\n//\n// @ts-expect-error this library does not ship types\nimport asn1 from \"asn1.js\";\nimport BN from \"bn.js\";\nimport elliptic from \"elliptic\";\n\n/* cspell:disable */\nconst ECPrivateKeyASN = asn1.define(\"ECPrivateKey\", function () {\n // @ts-expect-error pure black box\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unnecessary-type-assertion\n const self = this as any;\n self\n .seq()\n .obj(\n self.key(\"version\").int(),\n self.key(\"privateKey\").octstr(),\n self.key(\"parameters\").explicit(0).objid().optional(),\n self.key(\"publicKey\").explicit(1).bitstr().optional(),\n );\n});\n\nconst ECPrivateKey8ASN = asn1.define(\n \"ECPrivateKey\",\n /* v8 ignore start */\n function () {\n // @ts-expect-error pure black box\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unnecessary-type-assertion\n const self = this as any;\n self\n .seq()\n .obj(\n self.key(\"version\").int(),\n self\n .key(\"privateKeyAlgorithm\")\n .seq()\n .obj(self.key(\"ecPublicKey\").objid(), self.key(\"curve\").objid()),\n self.key(\"privateKey\").octstr().contains(ECPrivateKeyASN),\n self.key(\"attributes\").explicit(0).bitstr().optional(),\n );\n },\n /* v8 ignore stop */\n);\n\nconst SubjectPublicKeyInfoASN = asn1.define(\"SubjectPublicKeyInfo\", function () {\n // @ts-expect-error pure black box\n // eslint-disable-next-line @typescript-eslint/no-explicit-any, @typescript-eslint/no-unnecessary-type-assertion\n const self = this as any;\n self\n .seq()\n .obj(\n self.key(\"algorithm\").seq().obj(self.key(\"id\").objid(), self.key(\"curve\").objid()),\n self.key(\"pub\").bitstr(),\n );\n});\n\ntype CurveOptions = {\n curveParameters: number[];\n privatePEMOptions: { label: string };\n publicPEMOptions: { label: string };\n curve: elliptic.ec;\n};\n\nconst curves: Record<string, CurveOptions> = {\n secp256k1: {\n curveParameters: [1, 3, 132, 0, 10],\n privatePEMOptions: { label: \"EC PRIVATE KEY\" },\n publicPEMOptions: { label: \"PUBLIC KEY\" },\n curve: new elliptic.ec(\"secp256k1\"),\n },\n p256: {\n curveParameters: [1, 2, 840, 10045, 3, 1, 7], // OID for p256 curve\n privatePEMOptions: { label: \"EC PRIVATE KEY\" },\n publicPEMOptions: { label: \"PUBLIC KEY\" },\n curve: new elliptic.ec(\"p256\"),\n },\n};\n\ntype PrivateKeyPKCS1 = {\n version: BN;\n privateKey: Buffer;\n parameters: number[];\n publicKey?: {\n unused: number;\n data: Buffer;\n };\n};\n\ntype PrivateKeyPKCS8 = {\n version: BN;\n privateKey: PrivateKeyPKCS1;\n privateKeyAlgorithm: { ecPublicKey: number[]; curve: number[] };\n};\n\nexport type KeyFormat = \"raw\" | \"pem\" | \"der\";\n\nexport class KeyEncoder {\n algorithmID: number[];\n options: CurveOptions;\n\n constructor(options: string | CurveOptions) {\n if (typeof options === \"string\") {\n /* v8 ignore start */\n if (options !== \"secp256k1\" && options !== \"p256\") {\n throw new Error(\"Unknown curve \" + options);\n }\n /* v8 ignore stop */\n options = curves[options]!;\n }\n this.options = options;\n this.algorithmID = [1, 2, 840, 10045, 2, 1];\n }\n\n /* v8 ignore start */\n private PKCS1toPKCS8(privateKey: PrivateKeyPKCS1): PrivateKeyPKCS8 {\n return {\n version: new BN(0),\n privateKey,\n privateKeyAlgorithm: {\n ecPublicKey: this.algorithmID,\n curve: privateKey.parameters,\n },\n };\n }\n /* v8 ignore stop */\n\n privateKeyObject(rawPrivateKey: string, rawPublicKey: string): PrivateKeyPKCS1 {\n const privateKeyObject: PrivateKeyPKCS1 = {\n version: new BN(1),\n privateKey: Buffer.from(rawPrivateKey, \"hex\"),\n parameters: this.options.curveParameters,\n };\n\n if (rawPublicKey) {\n privateKeyObject.publicKey = {\n unused: 0,\n data: Buffer.from(rawPublicKey, \"hex\"),\n };\n }\n\n return privateKeyObject;\n }\n\n publicKeyObject(rawPublicKey: string): {\n algorithm: { id: number[]; curve: number[] };\n pub: { unused: number; data: Buffer };\n } {\n return {\n algorithm: {\n id: this.algorithmID,\n curve: this.options.curveParameters,\n },\n pub: {\n unused: 0,\n data: Buffer.from(rawPublicKey, \"hex\"),\n },\n };\n }\n\n encodePrivate(\n privateKey: string | Buffer,\n originalFormat: KeyFormat,\n destinationFormat: KeyFormat,\n destinationFormatType: \"pkcs8\" | \"pkcs1\" = \"pkcs1\",\n ): string {\n let privateKeyObject: PrivateKeyPKCS1;\n\n /* Parse the incoming private key and convert it to a private key object */\n switch (originalFormat) {\n case \"raw\": {\n if (typeof privateKey !== \"string\") {\n throw new Error(\"private key must be a string\");\n }\n const keyPair = this.options.curve.keyFromPrivate(privateKey, \"hex\");\n const rawPublicKey = keyPair.getPublic(\"hex\");\n privateKeyObject = this.privateKeyObject(privateKey, rawPublicKey);\n break;\n }\n case \"der\":\n if (typeof privateKey === \"string\") {\n privateKey = Buffer.from(privateKey, \"hex\");\n }\n privateKeyObject = ECPrivateKeyASN.decode(privateKey, \"der\");\n break;\n case \"pem\":\n if (typeof privateKey !== \"string\") {\n throw new Error(\"private key must be a string\");\n }\n privateKeyObject = ECPrivateKeyASN.decode(\n privateKey,\n \"pem\",\n this.options.privatePEMOptions,\n );\n break;\n /* v8 ignore start */\n default:\n throw new Error(\"invalid private key format\");\n /* v8 ignore stop */\n }\n\n /* Export the private key object to the desired format */\n switch (destinationFormat) {\n case \"raw\":\n if (destinationFormatType === \"pkcs1\") {\n return privateKeyObject.privateKey.toString(\"hex\");\n } else if (destinationFormatType === \"pkcs8\") {\n return this.PKCS1toPKCS8(privateKeyObject).privateKey.privateKey.toString(\"hex\");\n }\n break;\n case \"der\":\n if (destinationFormatType === \"pkcs1\") {\n return ECPrivateKeyASN.encode(privateKeyObject, \"der\").toString(\"hex\");\n } else if (destinationFormatType === \"pkcs8\") {\n return ECPrivateKey8ASN.encode(this.PKCS1toPKCS8(privateKeyObject), \"der\").toString(\n \"hex\",\n );\n }\n break;\n case \"pem\":\n if (destinationFormatType === \"pkcs1\") {\n return ECPrivateKeyASN.encode(privateKeyObject, \"pem\", this.options.privatePEMOptions);\n } else if (destinationFormatType === \"pkcs8\") {\n return ECPrivateKey8ASN.encode(this.PKCS1toPKCS8(privateKeyObject), \"pem\", {\n ...this.options.privatePEMOptions,\n label: \"PRIVATE KEY\",\n });\n }\n break;\n /* v8 ignore start */\n default:\n throw new Error(\"invalid destination format for private key\");\n /* v8 ignore stop */\n }\n\n throw new Error(\"unsupported destination format or type\");\n }\n\n encodePublic(\n publicKey: string | Buffer,\n originalFormat: KeyFormat,\n destinationFormat: KeyFormat,\n ): string {\n let publicKeyObject;\n\n switch (originalFormat) {\n case \"raw\":\n if (typeof publicKey !== \"string\") {\n throw new Error(\"public key must be a string\");\n }\n publicKeyObject = this.publicKeyObject(publicKey);\n break;\n case \"der\":\n if (typeof publicKey === \"string\") {\n publicKey = Buffer.from(publicKey, \"hex\");\n }\n publicKeyObject = SubjectPublicKeyInfoASN.decode(publicKey, \"der\");\n break;\n case \"pem\":\n if (typeof publicKey !== \"string\") {\n throw new Error(\"public key must be a string\");\n }\n publicKeyObject = SubjectPublicKeyInfoASN.decode(\n publicKey,\n \"pem\",\n this.options.publicPEMOptions,\n );\n break;\n /* v8 ignore start */\n default:\n throw new Error(\"invalid public key format\");\n /* v8 ignore stop */\n }\n\n /* Export the private key object to the desired format */\n switch (destinationFormat) {\n case \"raw\":\n return publicKeyObject.pub.data.toString(\"hex\");\n case \"der\":\n return SubjectPublicKeyInfoASN.encode(publicKeyObject, \"der\").toString(\"hex\");\n case \"pem\":\n return SubjectPublicKeyInfoASN.encode(\n publicKeyObject,\n \"pem\",\n this.options.publicPEMOptions,\n );\n /* v8 ignore start */\n default:\n throw new Error(\"invalid destination format for public key\");\n /* v8 ignore stop */\n }\n }\n}\n/* cspell:enable */\n"]}
package/lib/crypto.cjs CHANGED
@@ -1,7 +1,9 @@
1
1
  "use strict";Object.defineProperty(exports, "__esModule", {value: true});
2
2
 
3
- var _chunkJGXOGWYBcjs = require('./chunk-JGXOGWYB.cjs');
4
3
 
4
+ var _chunkXO66ZFXNcjs = require('./chunk-XO66ZFXN.cjs');
5
5
 
6
- exports.genKeys = _chunkJGXOGWYBcjs.genKeys;
6
+
7
+
8
+ exports.genKeys = _chunkXO66ZFXNcjs.genKeys; exports.sign = _chunkXO66ZFXNcjs.sign;
7
9
  //# sourceMappingURL=crypto.cjs.map
@@ -1 +1 @@
1
- {"version":3,"sources":["/home/runner/_work/revault/revault/packages/sdk/lib/crypto.cjs"],"names":[],"mappings":"AAAA;AACE;AACF,wDAA6B;AAC7B;AACE;AACF,4CAAC","file":"/home/runner/_work/revault/revault/packages/sdk/lib/crypto.cjs"}
1
+ {"version":3,"sources":["/home/runner/_work/revault/revault/packages/sdk/lib/crypto.cjs"],"names":[],"mappings":"AAAA;AACE;AACA;AACF,wDAA6B;AAC7B;AACE;AACA;AACF,mFAAC","file":"/home/runner/_work/revault/revault/packages/sdk/lib/crypto.cjs"}
package/lib/crypto.d.cts CHANGED
@@ -9,5 +9,6 @@ type GeneratedKeys = {
9
9
  * else, random keys pair generated
10
10
  */
11
11
  declare function genKeys(entropy?: string): GeneratedKeys;
12
+ declare const sign: (privateKeyPem: string, base64Challenge: string) => Promise<string>;
12
13
 
13
- export { type GeneratedKeys, genKeys };
14
+ export { type GeneratedKeys, genKeys, sign };
package/lib/crypto.d.ts CHANGED
@@ -9,5 +9,6 @@ type GeneratedKeys = {
9
9
  * else, random keys pair generated
10
10
  */
11
11
  declare function genKeys(entropy?: string): GeneratedKeys;
12
+ declare const sign: (privateKeyPem: string, base64Challenge: string) => Promise<string>;
12
13
 
13
- export { type GeneratedKeys, genKeys };
14
+ export { type GeneratedKeys, genKeys, sign };
package/lib/crypto.js CHANGED
@@ -1,7 +1,9 @@
1
1
  import {
2
- genKeys
3
- } from "./chunk-CZLZUISN.js";
2
+ genKeys,
3
+ sign
4
+ } from "./chunk-OU3QTNYT.js";
4
5
  export {
5
- genKeys
6
+ genKeys,
7
+ sign
6
8
  };
7
9
  //# sourceMappingURL=crypto.js.map
package/lib/device.cjs CHANGED
@@ -3,11 +3,11 @@
3
3
 
4
4
 
5
5
 
6
- var _chunkB5EUR3HTcjs = require('./chunk-B5EUR3HT.cjs');
6
+ var _chunkKS6SB3HRcjs = require('./chunk-KS6SB3HR.cjs');
7
7
 
8
8
 
9
9
 
10
10
 
11
11
 
12
- exports.createApiDevice = _chunkB5EUR3HTcjs.createApiDevice; exports.isDeviceCancelError = _chunkB5EUR3HTcjs.isDeviceCancelError; exports.isTransportStatusError = _chunkB5EUR3HTcjs.isTransportStatusError; exports.registerTransportModule = _chunkB5EUR3HTcjs.registerTransportModule;
12
+ exports.createApiDevice = _chunkKS6SB3HRcjs.createApiDevice; exports.isDeviceCancelError = _chunkKS6SB3HRcjs.isDeviceCancelError; exports.isTransportStatusError = _chunkKS6SB3HRcjs.isTransportStatusError; exports.registerTransportModule = _chunkKS6SB3HRcjs.registerTransportModule;
13
13
  //# sourceMappingURL=device.cjs.map
package/lib/device.d.cts CHANGED
@@ -20,7 +20,7 @@ type Options = {
20
20
  genSeed: (p: {
21
21
  salt: string;
22
22
  index: number;
23
- }) => string;
23
+ }) => string | Promise<string>;
24
24
  };
25
25
  type ApiDevice = {
26
26
  /**
package/lib/device.d.ts CHANGED
@@ -20,7 +20,7 @@ type Options = {
20
20
  genSeed: (p: {
21
21
  salt: string;
22
22
  index: number;
23
- }) => string;
23
+ }) => string | Promise<string>;
24
24
  };
25
25
  type ApiDevice = {
26
26
  /**
package/lib/device.js CHANGED
@@ -3,7 +3,7 @@ import {
3
3
  isDeviceCancelError,
4
4
  isTransportStatusError,
5
5
  registerTransportModule
6
- } from "./chunk-7WN7G7BY.js";
6
+ } from "./chunk-OJW4TCAG.js";
7
7
  export {
8
8
  createApiDevice,
9
9
  isDeviceCancelError,