@ledgerhq/revault-sdk 0.27.10 → 0.27.12
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/lib/bake.cjs +3 -3
- package/lib/bake.d.cts +1 -1
- package/lib/bake.d.ts +1 -1
- package/lib/{crypto-C2vNZ2v5.cjs → crypto-BxlPOWD9.cjs} +2 -2
- package/lib/{crypto-C2vNZ2v5.cjs.map → crypto-BxlPOWD9.cjs.map} +1 -1
- package/lib/crypto.cjs +1 -1
- package/lib/{device-oVP-RMAE.cjs → device-B6QZOEDT.cjs} +198 -7
- package/lib/device-B6QZOEDT.cjs.map +1 -0
- package/lib/{device-CLaCrhYs.js → device-DBzLykrI.js} +215 -3
- package/lib/device-DBzLykrI.js.map +1 -0
- package/lib/device.cjs +1 -1
- package/lib/device.d.cts +1 -1
- package/lib/device.d.ts +1 -1
- package/lib/device.js +1 -1
- package/lib/engine.cjs +3 -3
- package/lib/engine.d.cts +2 -2
- package/lib/engine.d.ts +2 -2
- package/lib/engine.js +1 -1
- package/lib/{index-DFH32jX1.d.cts → index-B7SUQ6NW.d.cts} +1 -1
- package/lib/{index-ejIgqJ4-.d.ts → index-CuWiM97X.d.ts} +1 -1
- package/lib/{index-gV5kopxM.d.ts → index-DLUJ9Etg.d.ts} +1 -1
- package/lib/{index-ukfYPfWT.d.cts → index-sWTlrbOl.d.cts} +1 -1
- package/lib/index.cjs +1 -1
- package/lib/onboarding.cjs +2 -2
- package/lib/onboarding.d.cts +1 -1
- package/lib/onboarding.d.ts +1 -1
- package/lib/{rolldown-runtime-D6vf50IK.cjs → rolldown-runtime-emK7D4bc.cjs} +7 -0
- package/lib/{types-CIigMmZN.d.ts → types-BN2MzD_5.d.ts} +1 -1
- package/lib/{types-CgmE0sOT.d.cts → types-BXAwSr1F.d.cts} +1 -1
- package/lib/{utils-BToYxXna.cjs → utils-CavXJGCh.cjs} +2 -2
- package/lib/{utils-BToYxXna.cjs.map → utils-CavXJGCh.cjs.map} +1 -1
- package/package.json +4 -4
- package/lib/device-CLaCrhYs.js.map +0 -1
- package/lib/device-oVP-RMAE.cjs.map +0 -1
package/lib/bake.cjs
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_rolldown_runtime = require("./rolldown-runtime-
|
|
3
|
-
const require_utils = require("./utils-
|
|
4
|
-
const require_crypto = require("./crypto-
|
|
2
|
+
const require_rolldown_runtime = require("./rolldown-runtime-emK7D4bc.cjs");
|
|
3
|
+
const require_utils = require("./utils-CavXJGCh.cjs");
|
|
4
|
+
const require_crypto = require("./crypto-BxlPOWD9.cjs");
|
|
5
5
|
let invariant = require("invariant");
|
|
6
6
|
invariant = require_rolldown_runtime.__toESM(invariant, 1);
|
|
7
7
|
let ts_pattern = require("ts-pattern");
|
package/lib/bake.d.cts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as Logger } from "./logger-DHtgWA66.cjs";
|
|
2
2
|
import { n as RouterInputs, t as RevaultApiTRPCClient } from "./trpc-DBU35NJq.cjs";
|
|
3
|
-
import { b as WithPsdAuth, d as Engine, v as WithDevice, x as WithWorkspace } from "./types-
|
|
3
|
+
import { b as WithPsdAuth, d as Engine, v as WithDevice, x as WithWorkspace } from "./types-BXAwSr1F.cjs";
|
|
4
4
|
import z from "zod";
|
|
5
5
|
import { VaultRequestResponse } from "@ledgerhq/revault-api";
|
|
6
6
|
|
package/lib/bake.d.ts
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { t as Logger } from "./logger-DHtgWA66.js";
|
|
2
2
|
import { n as RouterInputs, t as RevaultApiTRPCClient } from "./trpc-DBU35NJq.js";
|
|
3
|
-
import { b as WithPsdAuth, d as Engine, v as WithDevice, x as WithWorkspace } from "./types-
|
|
3
|
+
import { b as WithPsdAuth, d as Engine, v as WithDevice, x as WithWorkspace } from "./types-BN2MzD_5.js";
|
|
4
4
|
import z from "zod";
|
|
5
5
|
import { VaultRequestResponse } from "@ledgerhq/revault-api";
|
|
6
6
|
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
const require_rolldown_runtime = require("./rolldown-runtime-
|
|
1
|
+
const require_rolldown_runtime = require("./rolldown-runtime-emK7D4bc.cjs");
|
|
2
2
|
let _noble_hashes_sha2_js = require("@noble/hashes/sha2.js");
|
|
3
3
|
let _scure_bip32 = require("@scure/bip32");
|
|
4
4
|
let _scure_bip39 = require("@scure/bip39");
|
|
@@ -293,4 +293,4 @@ Object.defineProperty(exports, "sign", {
|
|
|
293
293
|
}
|
|
294
294
|
});
|
|
295
295
|
|
|
296
|
-
//# sourceMappingURL=crypto-
|
|
296
|
+
//# sourceMappingURL=crypto-BxlPOWD9.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"crypto-C2vNZ2v5.cjs","names":["wordlist","HDKey","asn1","BN","crypto"],"sources":["../src/crypto/gen-seed.ts","../src/crypto/key-encoder.ts","../src/crypto/utils.ts"],"sourcesContent":["import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { HDKey } from \"@scure/bip32\";\nimport { entropyToMnemonic, mnemonicToSeed } from \"@scure/bip39\";\nimport { wordlist } from \"@scure/bip39/wordlists/english.js\";\n\n/**\n * Generate a deterministic BIP39 mnemonic from a salt and device index.\n *\n * Produces `entropyToMnemonic(SHA256(salt + \"_\" + index))`, matching\n * the behavior of `@ledgerhq/vault-common`'s `genSeed`.\n *\n * @param salt The workspace salt\n * @param index The device index (1-based)\n * @returns A 24-word BIP39 mnemonic string\n */\nexport function genSeed(salt: string, index: number): string {\n const input = new TextEncoder().encode(`${salt}_${index}`);\n const entropy = sha256(input);\n return entropyToMnemonic(entropy, wordlist);\n}\n\nconst getSeedFragment = async (salt: string, index: number): Promise<Uint8Array> => {\n const seed = await mnemonicToSeed(genSeed(salt, index));\n const secpKey = HDKey.fromMasterSeed(seed);\n const fragment = secpKey.derive(\"m/5655636'/4932953'\");\n return Buffer.concat([fragment.privateKey!, fragment.chainCode!]);\n};\n\nexport const getMasterSeed = async (salt: string): Promise<Uint8Array> => {\n const fragments = await Promise.all([\n getSeedFragment(salt, 7),\n getSeedFragment(salt, 8),\n getSeedFragment(salt, 9),\n ]);\n\n const masterSeed = new Uint8Array(fragments[0].length);\n for (let i = 0; i < fragments[0].length; i++) {\n masterSeed[i] = fragments[0][i]! ^ fragments[1][i]! ^ fragments[2][i]!;\n }\n\n return masterSeed;\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 // biome-ignore lint/suspicious/noExplicitAny: black box\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 next -- @preserve */\n function () {\n // @ts-expect-error pure black box\n // biome-ignore lint/suspicious/noExplicitAny: black box\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);\n\nconst SubjectPublicKeyInfoASN = asn1.define(\"SubjectPublicKeyInfo\", function () {\n // @ts-expect-error pure black box\n // biome-ignore lint/suspicious/noExplicitAny: black box\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 /* v8 ignore else -- @preserve */\n if (typeof options === \"string\") {\n /* v8 ignore if -- @preserve */\n if (options !== \"secp256k1\" && options !== \"p256\") {\n throw new Error(`Unknown curve ${options}`);\n }\n options = curves[options]!;\n }\n this.options = options;\n this.algorithmID = [1, 2, 840, 10045, 2, 1];\n }\n\n /* v8 ignore next -- @preserve */\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\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 /* v8 ignore else -- @preserve */\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 /* v8 ignore next -- @preserve */\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 next -- @preserve */\n default:\n throw new Error(\"invalid private key format\");\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 next -- @preserve */\n default:\n throw new Error(\"invalid destination format for private key\");\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 // biome-ignore lint/suspicious/noImplicitAnyLet: melting pot object\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 /* v8 ignore next -- @preserve */\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 next -- @preserve */\n default:\n throw new Error(\"invalid public key format\");\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 next -- @preserve */\n default:\n throw new Error(\"invalid destination format for public key\");\n }\n }\n}\n/* cspell:enable */\n","import elliptic from \"elliptic\";\nimport * as jose from \"jose\";\n\nimport { KeyEncoder } from \"./key-encoder\";\nimport type { GeneratedKeys } from \"./types\";\nimport crypto from \"node:crypto\";\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,SAAgB,QAAQ,MAAc,OAAuB;CAG3D,QAAA,GAAA,aAAA,kBAAA,EAAA,GAAA,sBAAA,OAAA,CAFc,IAAI,YAAY,CAAC,CAAC,OAAO,GAAG,KAAK,GAAG,OACvB,CACI,GAAGA,kCAAAA,QAAQ;AAC5C;AAEA,MAAM,kBAAkB,OAAO,MAAc,UAAuC;CAClF,MAAM,OAAO,OAAA,GAAA,aAAA,eAAA,CAAqB,QAAQ,MAAM,KAAK,CAAC;CAEtD,MAAM,WADUC,aAAAA,MAAM,eAAe,IACd,CAAC,CAAC,OAAO,qBAAqB;CACrD,OAAO,OAAO,OAAO,CAAC,SAAS,YAAa,SAAS,SAAU,CAAC;AAClE;AAEA,MAAa,gBAAgB,OAAO,SAAsC;CACxE,MAAM,YAAY,MAAM,QAAQ,IAAI;EAClC,gBAAgB,MAAM,CAAC;EACvB,gBAAgB,MAAM,CAAC;EACvB,gBAAgB,MAAM,CAAC;CACzB,CAAC;CAED,MAAM,aAAa,IAAI,WAAW,UAAU,EAAE,C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,KAAK;CAEzD,OAAO,WAAW,aAAa,WAAW,OAAO,KAAK;AACxD;;;;;AAMA,SAAgB,QAAQ,SAAiC;CACvD,IAAI,SAAS;EACX,MAAM,KAAK,IAAI,SAAA,QAAS,GAAG,MAAM;EACjC,MAAM,gBAAgBC,YAAAA,QAAO,WAAW,QAAQ,CAAC,CAAC,OAAO,OAAO,CAAC,CAAC,OAAO,KAAK;EAC9E,MAAM,UAAU,GAAG,WAAW,EAC5B,SAAS,OAAO,KAAK,eAAe,KAAK,EAC3C,CAAC;EACD,OAAO;GACL,YAAY,OAAO,SAAS,QAAQ,WAAW,KAAK,CAAC,CAAC;GACtD,WAAW,OAAO,SAAS,QAAQ,UAAU,KAAK,GAAG,EAAE,WAAW,MAAM,CAAC,CAAC;GAC1E,WAAW,iBAAiB,OAAO,SAAS,QAAQ,UAAU,KAAK,GAAG,EAAE,WAAW,MAAM,CAAC,CAAC,CAAC;EAC9F;CACF;CACA,MAAM,EAAE,WAAW,eAAeA,YAAAA,QAAO,oBAAoB,MAAM;EACjE,YAAY;EACZ,mBAAmB;GAAE,MAAM;GAAQ,QAAQ;EAAM;EACjD,oBAAoB;GAAE,MAAM;GAAQ,QAAQ;EAAM;CACpD,CAAC;CAED,OAAO;EACL;EACA;EACA,WAJgB,iBAAiB,SAIzB;CACV;AACF;AAEA,MAAa,OAAO,OAAO,eAAuB,oBAA6C;CAE7F,MAAM,qBAAqB,KAAK,UAAU,OAAO,eAAe;CAKhE,MAAM,aAAaA,YAAAA,QAAO,iBAAiB,aAAa;CAGxD,OAAO,MAAM,IAAI,KAAK,YAAY,kBAAkB,CAAC,CAClD,mBAAmB;EAAE,KAAK;EAAS,KAAK;CAAM,CAAC,CAAC,CAChD,KAAK,UAAU;AACpB"}
|
|
1
|
+
{"version":3,"file":"crypto-BxlPOWD9.cjs","names":["wordlist","HDKey","asn1","BN","crypto"],"sources":["../src/crypto/gen-seed.ts","../src/crypto/key-encoder.ts","../src/crypto/utils.ts"],"sourcesContent":["import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { HDKey } from \"@scure/bip32\";\nimport { entropyToMnemonic, mnemonicToSeed } from \"@scure/bip39\";\nimport { wordlist } from \"@scure/bip39/wordlists/english.js\";\n\n/**\n * Generate a deterministic BIP39 mnemonic from a salt and device index.\n *\n * Produces `entropyToMnemonic(SHA256(salt + \"_\" + index))`, matching\n * the behavior of `@ledgerhq/vault-common`'s `genSeed`.\n *\n * @param salt The workspace salt\n * @param index The device index (1-based)\n * @returns A 24-word BIP39 mnemonic string\n */\nexport function genSeed(salt: string, index: number): string {\n const input = new TextEncoder().encode(`${salt}_${index}`);\n const entropy = sha256(input);\n return entropyToMnemonic(entropy, wordlist);\n}\n\nconst getSeedFragment = async (salt: string, index: number): Promise<Uint8Array> => {\n const seed = await mnemonicToSeed(genSeed(salt, index));\n const secpKey = HDKey.fromMasterSeed(seed);\n const fragment = secpKey.derive(\"m/5655636'/4932953'\");\n return Buffer.concat([fragment.privateKey!, fragment.chainCode!]);\n};\n\nexport const getMasterSeed = async (salt: string): Promise<Uint8Array> => {\n const fragments = await Promise.all([\n getSeedFragment(salt, 7),\n getSeedFragment(salt, 8),\n getSeedFragment(salt, 9),\n ]);\n\n const masterSeed = new Uint8Array(fragments[0].length);\n for (let i = 0; i < fragments[0].length; i++) {\n masterSeed[i] = fragments[0][i]! ^ fragments[1][i]! ^ fragments[2][i]!;\n }\n\n return masterSeed;\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 // biome-ignore lint/suspicious/noExplicitAny: black box\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 next -- @preserve */\n function () {\n // @ts-expect-error pure black box\n // biome-ignore lint/suspicious/noExplicitAny: black box\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);\n\nconst SubjectPublicKeyInfoASN = asn1.define(\"SubjectPublicKeyInfo\", function () {\n // @ts-expect-error pure black box\n // biome-ignore lint/suspicious/noExplicitAny: black box\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 /* v8 ignore else -- @preserve */\n if (typeof options === \"string\") {\n /* v8 ignore if -- @preserve */\n if (options !== \"secp256k1\" && options !== \"p256\") {\n throw new Error(`Unknown curve ${options}`);\n }\n options = curves[options]!;\n }\n this.options = options;\n this.algorithmID = [1, 2, 840, 10045, 2, 1];\n }\n\n /* v8 ignore next -- @preserve */\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\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 /* v8 ignore else -- @preserve */\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 /* v8 ignore next -- @preserve */\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 next -- @preserve */\n default:\n throw new Error(\"invalid private key format\");\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 next -- @preserve */\n default:\n throw new Error(\"invalid destination format for private key\");\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 // biome-ignore lint/suspicious/noImplicitAnyLet: melting pot object\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 /* v8 ignore next -- @preserve */\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 next -- @preserve */\n default:\n throw new Error(\"invalid public key format\");\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 next -- @preserve */\n default:\n throw new Error(\"invalid destination format for public key\");\n }\n }\n}\n/* cspell:enable */\n","import elliptic from \"elliptic\";\nimport * as jose from \"jose\";\n\nimport { KeyEncoder } from \"./key-encoder\";\nimport type { GeneratedKeys } from \"./types\";\nimport crypto from \"node:crypto\";\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"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,SAAgB,QAAQ,MAAc,OAAuB;CAG3D,QAAA,GAAA,aAAA,kBAAA,EA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mBAAmB;GAAE,MAAM;GAAQ,QAAQ;EAAM;EACjD,oBAAoB;GAAE,MAAM;GAAQ,QAAQ;EAAM;CACpD,CAAC;CAED,OAAO;EACL;EACA;EACA,WAJgB,iBAAiB,SAIzB;CACV;AACF;AAEA,MAAa,OAAO,OAAO,eAAuB,oBAA6C;CAE7F,MAAM,qBAAqB,KAAK,UAAU,OAAO,eAAe;CAKhE,MAAM,aAAaA,YAAAA,QAAO,iBAAiB,aAAa;CAGxD,OAAO,MAAM,IAAI,KAAK,YAAY,kBAAkB,CAAC,CAClD,mBAAmB;EAAE,KAAK;EAAS,KAAK;CAAM,CAAC,CAAC,CAChD,KAAK,UAAU;AACpB"}
|
package/lib/crypto.cjs
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
Object.defineProperty(exports, Symbol.toStringTag, { value: "Module" });
|
|
2
|
-
const require_crypto = require("./crypto-
|
|
2
|
+
const require_crypto = require("./crypto-BxlPOWD9.cjs");
|
|
3
3
|
exports.genKeys = require_crypto.genKeys;
|
|
4
4
|
exports.genSeed = require_crypto.genSeed;
|
|
5
5
|
exports.getMasterSeed = require_crypto.getMasterSeed;
|
|
@@ -1,11 +1,195 @@
|
|
|
1
|
-
const require_rolldown_runtime = require("./rolldown-runtime-
|
|
1
|
+
const require_rolldown_runtime = require("./rolldown-runtime-emK7D4bc.cjs");
|
|
2
2
|
let axios = require("axios");
|
|
3
3
|
axios = require_rolldown_runtime.__toESM(axios, 1);
|
|
4
|
-
let axios_retry = require("axios-retry");
|
|
5
|
-
axios_retry = require_rolldown_runtime.__toESM(axios_retry, 1);
|
|
6
4
|
let uuid = require("uuid");
|
|
7
5
|
let rxjs = require("rxjs");
|
|
8
6
|
let rxjs_operators = require("rxjs/operators");
|
|
7
|
+
//#region ../../node_modules/.pnpm/is-retry-allowed@2.2.0/node_modules/is-retry-allowed/index.js
|
|
8
|
+
var require_is_retry_allowed = /* @__PURE__ */ require_rolldown_runtime.__commonJSMin(((exports, module) => {
|
|
9
|
+
const denyList = new Set([
|
|
10
|
+
"ENOTFOUND",
|
|
11
|
+
"ENETUNREACH",
|
|
12
|
+
"UNABLE_TO_GET_ISSUER_CERT",
|
|
13
|
+
"UNABLE_TO_GET_CRL",
|
|
14
|
+
"UNABLE_TO_DECRYPT_CERT_SIGNATURE",
|
|
15
|
+
"UNABLE_TO_DECRYPT_CRL_SIGNATURE",
|
|
16
|
+
"UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY",
|
|
17
|
+
"CERT_SIGNATURE_FAILURE",
|
|
18
|
+
"CRL_SIGNATURE_FAILURE",
|
|
19
|
+
"CERT_NOT_YET_VALID",
|
|
20
|
+
"CERT_HAS_EXPIRED",
|
|
21
|
+
"CRL_NOT_YET_VALID",
|
|
22
|
+
"CRL_HAS_EXPIRED",
|
|
23
|
+
"ERROR_IN_CERT_NOT_BEFORE_FIELD",
|
|
24
|
+
"ERROR_IN_CERT_NOT_AFTER_FIELD",
|
|
25
|
+
"ERROR_IN_CRL_LAST_UPDATE_FIELD",
|
|
26
|
+
"ERROR_IN_CRL_NEXT_UPDATE_FIELD",
|
|
27
|
+
"OUT_OF_MEM",
|
|
28
|
+
"DEPTH_ZERO_SELF_SIGNED_CERT",
|
|
29
|
+
"SELF_SIGNED_CERT_IN_CHAIN",
|
|
30
|
+
"UNABLE_TO_GET_ISSUER_CERT_LOCALLY",
|
|
31
|
+
"UNABLE_TO_VERIFY_LEAF_SIGNATURE",
|
|
32
|
+
"CERT_CHAIN_TOO_LONG",
|
|
33
|
+
"CERT_REVOKED",
|
|
34
|
+
"INVALID_CA",
|
|
35
|
+
"PATH_LENGTH_EXCEEDED",
|
|
36
|
+
"INVALID_PURPOSE",
|
|
37
|
+
"CERT_UNTRUSTED",
|
|
38
|
+
"CERT_REJECTED",
|
|
39
|
+
"HOSTNAME_MISMATCH"
|
|
40
|
+
]);
|
|
41
|
+
module.exports = (error) => !denyList.has(error && error.code);
|
|
42
|
+
}));
|
|
43
|
+
//#endregion
|
|
44
|
+
//#region ../../node_modules/.pnpm/axios-retry@4.5.0_axios@1.17.0/node_modules/axios-retry/dist/esm/index.js
|
|
45
|
+
var import_is_retry_allowed = /* @__PURE__ */ require_rolldown_runtime.__toESM(require_is_retry_allowed());
|
|
46
|
+
const namespace = "axios-retry";
|
|
47
|
+
function isNetworkError(error) {
|
|
48
|
+
const CODE_EXCLUDE_LIST = ["ERR_CANCELED", "ECONNABORTED"];
|
|
49
|
+
if (error.response) return false;
|
|
50
|
+
if (!error.code) return false;
|
|
51
|
+
if (CODE_EXCLUDE_LIST.includes(error.code)) return false;
|
|
52
|
+
return (0, import_is_retry_allowed.default)(error);
|
|
53
|
+
}
|
|
54
|
+
const SAFE_HTTP_METHODS = [
|
|
55
|
+
"get",
|
|
56
|
+
"head",
|
|
57
|
+
"options"
|
|
58
|
+
];
|
|
59
|
+
const IDEMPOTENT_HTTP_METHODS = SAFE_HTTP_METHODS.concat(["put", "delete"]);
|
|
60
|
+
function isRetryableError(error) {
|
|
61
|
+
return error.code !== "ECONNABORTED" && (!error.response || error.response.status === 429 || error.response.status >= 500 && error.response.status <= 599);
|
|
62
|
+
}
|
|
63
|
+
function isSafeRequestError(error) {
|
|
64
|
+
if (!error.config?.method) return false;
|
|
65
|
+
return isRetryableError(error) && SAFE_HTTP_METHODS.indexOf(error.config.method) !== -1;
|
|
66
|
+
}
|
|
67
|
+
function isIdempotentRequestError(error) {
|
|
68
|
+
if (!error.config?.method) return false;
|
|
69
|
+
return isRetryableError(error) && IDEMPOTENT_HTTP_METHODS.indexOf(error.config.method) !== -1;
|
|
70
|
+
}
|
|
71
|
+
function isNetworkOrIdempotentRequestError(error) {
|
|
72
|
+
return isNetworkError(error) || isIdempotentRequestError(error);
|
|
73
|
+
}
|
|
74
|
+
function retryAfter(error = void 0) {
|
|
75
|
+
const retryAfterHeader = error?.response?.headers["retry-after"];
|
|
76
|
+
if (!retryAfterHeader) return 0;
|
|
77
|
+
let retryAfterMs = (Number(retryAfterHeader) || 0) * 1e3;
|
|
78
|
+
if (retryAfterMs === 0) retryAfterMs = (new Date(retryAfterHeader).valueOf() || 0) - Date.now();
|
|
79
|
+
return Math.max(0, retryAfterMs);
|
|
80
|
+
}
|
|
81
|
+
function noDelay(_retryNumber = 0, error = void 0) {
|
|
82
|
+
return Math.max(0, retryAfter(error));
|
|
83
|
+
}
|
|
84
|
+
function exponentialDelay(retryNumber = 0, error = void 0, delayFactor = 100) {
|
|
85
|
+
const calculatedDelay = 2 ** retryNumber * delayFactor;
|
|
86
|
+
const delay = Math.max(calculatedDelay, retryAfter(error));
|
|
87
|
+
return delay + delay * .2 * Math.random();
|
|
88
|
+
}
|
|
89
|
+
/**
|
|
90
|
+
* Linear delay
|
|
91
|
+
* @param {number | undefined} delayFactor - delay factor in milliseconds (default: 100)
|
|
92
|
+
* @returns {function} (retryNumber: number, error: AxiosError | undefined) => number
|
|
93
|
+
*/
|
|
94
|
+
function linearDelay(delayFactor = 100) {
|
|
95
|
+
return (retryNumber = 0, error = void 0) => {
|
|
96
|
+
const delay = retryNumber * delayFactor;
|
|
97
|
+
return Math.max(delay, retryAfter(error));
|
|
98
|
+
};
|
|
99
|
+
}
|
|
100
|
+
const DEFAULT_OPTIONS = {
|
|
101
|
+
retries: 3,
|
|
102
|
+
retryCondition: isNetworkOrIdempotentRequestError,
|
|
103
|
+
retryDelay: noDelay,
|
|
104
|
+
shouldResetTimeout: false,
|
|
105
|
+
onRetry: () => {},
|
|
106
|
+
onMaxRetryTimesExceeded: () => {},
|
|
107
|
+
validateResponse: null
|
|
108
|
+
};
|
|
109
|
+
function getRequestOptions(config, defaultOptions) {
|
|
110
|
+
return {
|
|
111
|
+
...DEFAULT_OPTIONS,
|
|
112
|
+
...defaultOptions,
|
|
113
|
+
...config[namespace]
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
function setCurrentState(config, defaultOptions, resetLastRequestTime = false) {
|
|
117
|
+
const currentState = getRequestOptions(config, defaultOptions || {});
|
|
118
|
+
currentState.retryCount = currentState.retryCount || 0;
|
|
119
|
+
if (!currentState.lastRequestTime || resetLastRequestTime) currentState.lastRequestTime = Date.now();
|
|
120
|
+
config[namespace] = currentState;
|
|
121
|
+
return currentState;
|
|
122
|
+
}
|
|
123
|
+
function fixConfig(axiosInstance, config) {
|
|
124
|
+
if (axiosInstance.defaults.agent === config.agent) delete config.agent;
|
|
125
|
+
if (axiosInstance.defaults.httpAgent === config.httpAgent) delete config.httpAgent;
|
|
126
|
+
if (axiosInstance.defaults.httpsAgent === config.httpsAgent) delete config.httpsAgent;
|
|
127
|
+
}
|
|
128
|
+
async function shouldRetry(currentState, error) {
|
|
129
|
+
const { retries, retryCondition } = currentState;
|
|
130
|
+
const shouldRetryOrPromise = (currentState.retryCount || 0) < retries && retryCondition(error);
|
|
131
|
+
if (typeof shouldRetryOrPromise === "object") try {
|
|
132
|
+
return await shouldRetryOrPromise !== false;
|
|
133
|
+
} catch (_err) {
|
|
134
|
+
return false;
|
|
135
|
+
}
|
|
136
|
+
return shouldRetryOrPromise;
|
|
137
|
+
}
|
|
138
|
+
async function handleRetry(axiosInstance, currentState, error, config) {
|
|
139
|
+
currentState.retryCount += 1;
|
|
140
|
+
const { retryDelay, shouldResetTimeout, onRetry } = currentState;
|
|
141
|
+
const delay = retryDelay(currentState.retryCount, error);
|
|
142
|
+
fixConfig(axiosInstance, config);
|
|
143
|
+
if (!shouldResetTimeout && config.timeout && currentState.lastRequestTime) {
|
|
144
|
+
const lastRequestDuration = Date.now() - currentState.lastRequestTime;
|
|
145
|
+
const timeout = config.timeout - lastRequestDuration - delay;
|
|
146
|
+
if (timeout <= 0) return Promise.reject(error);
|
|
147
|
+
config.timeout = timeout;
|
|
148
|
+
}
|
|
149
|
+
config.transformRequest = [(data) => data];
|
|
150
|
+
await onRetry(currentState.retryCount, error, config);
|
|
151
|
+
if (config.signal?.aborted) return Promise.resolve(axiosInstance(config));
|
|
152
|
+
return new Promise((resolve) => {
|
|
153
|
+
const abortListener = () => {
|
|
154
|
+
clearTimeout(timeout);
|
|
155
|
+
resolve(axiosInstance(config));
|
|
156
|
+
};
|
|
157
|
+
const timeout = setTimeout(() => {
|
|
158
|
+
resolve(axiosInstance(config));
|
|
159
|
+
if (config.signal?.removeEventListener) config.signal.removeEventListener("abort", abortListener);
|
|
160
|
+
}, delay);
|
|
161
|
+
if (config.signal?.addEventListener) config.signal.addEventListener("abort", abortListener, { once: true });
|
|
162
|
+
});
|
|
163
|
+
}
|
|
164
|
+
async function handleMaxRetryTimesExceeded(currentState, error) {
|
|
165
|
+
if (currentState.retryCount >= currentState.retries) await currentState.onMaxRetryTimesExceeded(error, currentState.retryCount);
|
|
166
|
+
}
|
|
167
|
+
const axiosRetry = (axiosInstance, defaultOptions) => {
|
|
168
|
+
return {
|
|
169
|
+
requestInterceptorId: axiosInstance.interceptors.request.use((config) => {
|
|
170
|
+
setCurrentState(config, defaultOptions, true);
|
|
171
|
+
if (config["axios-retry"]?.validateResponse) config.validateStatus = () => false;
|
|
172
|
+
return config;
|
|
173
|
+
}),
|
|
174
|
+
responseInterceptorId: axiosInstance.interceptors.response.use(null, async (error) => {
|
|
175
|
+
const { config } = error;
|
|
176
|
+
if (!config) return Promise.reject(error);
|
|
177
|
+
const currentState = setCurrentState(config, defaultOptions);
|
|
178
|
+
if (error.response && currentState.validateResponse?.(error.response)) return error.response;
|
|
179
|
+
if (await shouldRetry(currentState, error)) return handleRetry(axiosInstance, currentState, error, config);
|
|
180
|
+
await handleMaxRetryTimesExceeded(currentState, error);
|
|
181
|
+
return Promise.reject(error);
|
|
182
|
+
})
|
|
183
|
+
};
|
|
184
|
+
};
|
|
185
|
+
axiosRetry.isNetworkError = isNetworkError;
|
|
186
|
+
axiosRetry.isSafeRequestError = isSafeRequestError;
|
|
187
|
+
axiosRetry.isIdempotentRequestError = isIdempotentRequestError;
|
|
188
|
+
axiosRetry.isNetworkOrIdempotentRequestError = isNetworkOrIdempotentRequestError;
|
|
189
|
+
axiosRetry.exponentialDelay = exponentialDelay;
|
|
190
|
+
axiosRetry.linearDelay = linearDelay;
|
|
191
|
+
axiosRetry.isRetryableError = isRetryableError;
|
|
192
|
+
//#endregion
|
|
9
193
|
//#region src/device/constants.ts
|
|
10
194
|
const PATHS = {
|
|
11
195
|
U2F: "5655636'/5583430'",
|
|
@@ -32,8 +216,8 @@ function createApiDevice(options, logger) {
|
|
|
32
216
|
const { genSeed } = options;
|
|
33
217
|
const sessionId = (0, uuid.v4)();
|
|
34
218
|
const deviceApi = axios.default.create({ baseURL: options.deviceApiUrl });
|
|
35
|
-
(
|
|
36
|
-
retryDelay:
|
|
219
|
+
axiosRetry(deviceApi, {
|
|
220
|
+
retryDelay: axiosRetry.linearDelay(1e3),
|
|
37
221
|
retries: 3,
|
|
38
222
|
/* v8 ignore start -- @preserve */
|
|
39
223
|
retryCondition: () => true,
|
|
@@ -322,7 +506,7 @@ function createApiDevice(options, logger) {
|
|
|
322
506
|
} };
|
|
323
507
|
}
|
|
324
508
|
//#endregion
|
|
325
|
-
//#region ../../node_modules/.pnpm/@ledgerhq+errors@6.
|
|
509
|
+
//#region ../../node_modules/.pnpm/@ledgerhq+errors@6.36.0/node_modules/@ledgerhq/errors/lib-es/helpers.js
|
|
326
510
|
const errorClasses = {};
|
|
327
511
|
const deserializers = {};
|
|
328
512
|
const addCustomErrorDeserializer = (name, deserializer) => {
|
|
@@ -470,6 +654,8 @@ createCustomErrorClass("FeeNotLoaded");
|
|
|
470
654
|
createCustomErrorClass("FeeNotLoadedSwap");
|
|
471
655
|
createCustomErrorClass("FeeRequired");
|
|
472
656
|
createCustomErrorClass("FeeTooHigh");
|
|
657
|
+
createCustomErrorClass("ValAddressRequired");
|
|
658
|
+
createCustomErrorClass("RedelegateDstValAddressRequired");
|
|
473
659
|
createCustomErrorClass("PendingOperation");
|
|
474
660
|
createCustomErrorClass("SyncError");
|
|
475
661
|
createCustomErrorClass("PairingFailed");
|
|
@@ -485,12 +671,16 @@ createCustomErrorClass("ConcordiumInsufficientFunds");
|
|
|
485
671
|
createCustomErrorClass("ConcordiumMemoTooLong");
|
|
486
672
|
createCustomErrorClass("ConcordiumPairingExpiredError");
|
|
487
673
|
createCustomErrorClass("ConcordiumSessionExpiredError");
|
|
674
|
+
createCustomErrorClass("ConcordiumTrustedMetadataServiceError");
|
|
675
|
+
createCustomErrorClass("ConcordiumAddressVerificationFailedError");
|
|
676
|
+
createCustomErrorClass("ConcordiumInvalidMaxFeeError");
|
|
488
677
|
createCustomErrorClass("LanguageNotFound");
|
|
489
678
|
createCustomErrorClass("NoDBPathGiven");
|
|
490
679
|
createCustomErrorClass("DBWrongPassword");
|
|
491
680
|
createCustomErrorClass("DBNotReset");
|
|
492
681
|
createCustomErrorClass("SequenceNumberError");
|
|
493
682
|
createCustomErrorClass("DisabledTransactionBroadcastError");
|
|
683
|
+
createCustomErrorClass("InvalidParameterError");
|
|
494
684
|
/**
|
|
495
685
|
* Type of a Transport error used to represent all equivalent errors coming from all possible implementation of Transport
|
|
496
686
|
*/
|
|
@@ -521,6 +711,7 @@ const StatusCodes = {
|
|
|
521
711
|
ACCESS_CONDITION_NOT_FULFILLED: 38916,
|
|
522
712
|
ALGORITHM_NOT_SUPPORTED: 38020,
|
|
523
713
|
CLA_NOT_SUPPORTED: 28160,
|
|
714
|
+
CLA_NOT_SUPPORTED_BOOTLOADER: 28161,
|
|
524
715
|
CODE_BLOCKED: 38976,
|
|
525
716
|
CODE_NOT_INITIALIZED: 38914,
|
|
526
717
|
COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 27009,
|
|
@@ -791,4 +982,4 @@ Object.defineProperty(exports, "withDevicePolling", {
|
|
|
791
982
|
}
|
|
792
983
|
});
|
|
793
984
|
|
|
794
|
-
//# sourceMappingURL=device-
|
|
985
|
+
//# sourceMappingURL=device-B6QZOEDT.cjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"device-B6QZOEDT.cjs","names":["Observable"],"sources":["../../../node_modules/.pnpm/is-retry-allowed@2.2.0/node_modules/is-retry-allowed/index.js","../../../node_modules/.pnpm/axios-retry@4.5.0_axios@1.17.0/node_modules/axios-retry/dist/esm/index.js","../src/device/constants.ts","../src/device/api-device.ts","../../../node_modules/.pnpm/@ledgerhq+errors@6.36.0/node_modules/@ledgerhq/errors/lib-es/helpers.js","../../../node_modules/.pnpm/@ledgerhq+errors@6.36.0/node_modules/@ledgerhq/errors/lib-es/index.js","../src/device/device-access.ts","../src/device/utils.ts"],"sourcesContent":["'use strict';\n\nconst denyList = new Set([\n\t'ENOTFOUND',\n\t'ENETUNREACH',\n\n\t// SSL errors from https://github.com/nodejs/node/blob/fc8e3e2cdc521978351de257030db0076d79e0ab/src/crypto/crypto_common.cc#L301-L328\n\t'UNABLE_TO_GET_ISSUER_CERT',\n\t'UNABLE_TO_GET_CRL',\n\t'UNABLE_TO_DECRYPT_CERT_SIGNATURE',\n\t'UNABLE_TO_DECRYPT_CRL_SIGNATURE',\n\t'UNABLE_TO_DECODE_ISSUER_PUBLIC_KEY',\n\t'CERT_SIGNATURE_FAILURE',\n\t'CRL_SIGNATURE_FAILURE',\n\t'CERT_NOT_YET_VALID',\n\t'CERT_HAS_EXPIRED',\n\t'CRL_NOT_YET_VALID',\n\t'CRL_HAS_EXPIRED',\n\t'ERROR_IN_CERT_NOT_BEFORE_FIELD',\n\t'ERROR_IN_CERT_NOT_AFTER_FIELD',\n\t'ERROR_IN_CRL_LAST_UPDATE_FIELD',\n\t'ERROR_IN_CRL_NEXT_UPDATE_FIELD',\n\t'OUT_OF_MEM',\n\t'DEPTH_ZERO_SELF_SIGNED_CERT',\n\t'SELF_SIGNED_CERT_IN_CHAIN',\n\t'UNABLE_TO_GET_ISSUER_CERT_LOCALLY',\n\t'UNABLE_TO_VERIFY_LEAF_SIGNATURE',\n\t'CERT_CHAIN_TOO_LONG',\n\t'CERT_REVOKED',\n\t'INVALID_CA',\n\t'PATH_LENGTH_EXCEEDED',\n\t'INVALID_PURPOSE',\n\t'CERT_UNTRUSTED',\n\t'CERT_REJECTED',\n\t'HOSTNAME_MISMATCH'\n]);\n\n// TODO: Use `error?.code` when targeting Node.js 14\nmodule.exports = error => !denyList.has(error && error.code);\n","import isRetryAllowed from 'is-retry-allowed';\nexport const namespace = 'axios-retry';\nexport function isNetworkError(error) {\n const CODE_EXCLUDE_LIST = ['ERR_CANCELED', 'ECONNABORTED'];\n if (error.response) {\n return false;\n }\n if (!error.code) {\n return false;\n }\n // Prevents retrying timed out & cancelled requests\n if (CODE_EXCLUDE_LIST.includes(error.code)) {\n return false;\n }\n // Prevents retrying unsafe errors\n return isRetryAllowed(error);\n}\nconst SAFE_HTTP_METHODS = ['get', 'head', 'options'];\nconst IDEMPOTENT_HTTP_METHODS = SAFE_HTTP_METHODS.concat(['put', 'delete']);\nexport function isRetryableError(error) {\n return (error.code !== 'ECONNABORTED' &&\n (!error.response ||\n error.response.status === 429 ||\n (error.response.status >= 500 && error.response.status <= 599)));\n}\nexport function isSafeRequestError(error) {\n if (!error.config?.method) {\n // Cannot determine if the request can be retried\n return false;\n }\n return isRetryableError(error) && SAFE_HTTP_METHODS.indexOf(error.config.method) !== -1;\n}\nexport function isIdempotentRequestError(error) {\n if (!error.config?.method) {\n // Cannot determine if the request can be retried\n return false;\n }\n return isRetryableError(error) && IDEMPOTENT_HTTP_METHODS.indexOf(error.config.method) !== -1;\n}\nexport function isNetworkOrIdempotentRequestError(error) {\n return isNetworkError(error) || isIdempotentRequestError(error);\n}\nexport function retryAfter(error = undefined) {\n const retryAfterHeader = error?.response?.headers['retry-after'];\n if (!retryAfterHeader) {\n return 0;\n }\n // if the retry after header is a number, convert it to milliseconds\n let retryAfterMs = (Number(retryAfterHeader) || 0) * 1000;\n // If the retry after header is a date, get the number of milliseconds until that date\n if (retryAfterMs === 0) {\n retryAfterMs = (new Date(retryAfterHeader).valueOf() || 0) - Date.now();\n }\n return Math.max(0, retryAfterMs);\n}\nfunction noDelay(_retryNumber = 0, error = undefined) {\n return Math.max(0, retryAfter(error));\n}\nexport function exponentialDelay(retryNumber = 0, error = undefined, delayFactor = 100) {\n const calculatedDelay = 2 ** retryNumber * delayFactor;\n const delay = Math.max(calculatedDelay, retryAfter(error));\n const randomSum = delay * 0.2 * Math.random(); // 0-20% of the delay\n return delay + randomSum;\n}\n/**\n * Linear delay\n * @param {number | undefined} delayFactor - delay factor in milliseconds (default: 100)\n * @returns {function} (retryNumber: number, error: AxiosError | undefined) => number\n */\nexport function linearDelay(delayFactor = 100) {\n return (retryNumber = 0, error = undefined) => {\n const delay = retryNumber * delayFactor;\n return Math.max(delay, retryAfter(error));\n };\n}\nexport const DEFAULT_OPTIONS = {\n retries: 3,\n retryCondition: isNetworkOrIdempotentRequestError,\n retryDelay: noDelay,\n shouldResetTimeout: false,\n onRetry: () => { },\n onMaxRetryTimesExceeded: () => { },\n validateResponse: null\n};\nfunction getRequestOptions(config, defaultOptions) {\n return { ...DEFAULT_OPTIONS, ...defaultOptions, ...config[namespace] };\n}\nfunction setCurrentState(config, defaultOptions, resetLastRequestTime = false) {\n const currentState = getRequestOptions(config, defaultOptions || {});\n currentState.retryCount = currentState.retryCount || 0;\n if (!currentState.lastRequestTime || resetLastRequestTime) {\n currentState.lastRequestTime = Date.now();\n }\n config[namespace] = currentState;\n return currentState;\n}\nfunction fixConfig(axiosInstance, config) {\n // @ts-ignore\n if (axiosInstance.defaults.agent === config.agent) {\n // @ts-ignore\n delete config.agent;\n }\n if (axiosInstance.defaults.httpAgent === config.httpAgent) {\n delete config.httpAgent;\n }\n if (axiosInstance.defaults.httpsAgent === config.httpsAgent) {\n delete config.httpsAgent;\n }\n}\nasync function shouldRetry(currentState, error) {\n const { retries, retryCondition } = currentState;\n const shouldRetryOrPromise = (currentState.retryCount || 0) < retries && retryCondition(error);\n // This could be a promise\n if (typeof shouldRetryOrPromise === 'object') {\n try {\n const shouldRetryPromiseResult = await shouldRetryOrPromise;\n // keep return true unless shouldRetryPromiseResult return false for compatibility\n return shouldRetryPromiseResult !== false;\n }\n catch (_err) {\n return false;\n }\n }\n return shouldRetryOrPromise;\n}\nasync function handleRetry(axiosInstance, currentState, error, config) {\n currentState.retryCount += 1;\n const { retryDelay, shouldResetTimeout, onRetry } = currentState;\n const delay = retryDelay(currentState.retryCount, error);\n // Axios fails merging this configuration to the default configuration because it has an issue\n // with circular structures: https://github.com/mzabriskie/axios/issues/370\n fixConfig(axiosInstance, config);\n if (!shouldResetTimeout && config.timeout && currentState.lastRequestTime) {\n const lastRequestDuration = Date.now() - currentState.lastRequestTime;\n const timeout = config.timeout - lastRequestDuration - delay;\n if (timeout <= 0) {\n return Promise.reject(error);\n }\n config.timeout = timeout;\n }\n config.transformRequest = [(data) => data];\n await onRetry(currentState.retryCount, error, config);\n if (config.signal?.aborted) {\n return Promise.resolve(axiosInstance(config));\n }\n return new Promise((resolve) => {\n const abortListener = () => {\n clearTimeout(timeout);\n resolve(axiosInstance(config));\n };\n const timeout = setTimeout(() => {\n resolve(axiosInstance(config));\n if (config.signal?.removeEventListener) {\n config.signal.removeEventListener('abort', abortListener);\n }\n }, delay);\n if (config.signal?.addEventListener) {\n config.signal.addEventListener('abort', abortListener, { once: true });\n }\n });\n}\nasync function handleMaxRetryTimesExceeded(currentState, error) {\n if (currentState.retryCount >= currentState.retries)\n await currentState.onMaxRetryTimesExceeded(error, currentState.retryCount);\n}\nconst axiosRetry = (axiosInstance, defaultOptions) => {\n const requestInterceptorId = axiosInstance.interceptors.request.use((config) => {\n setCurrentState(config, defaultOptions, true);\n if (config[namespace]?.validateResponse) {\n // by setting this, all HTTP responses will be go through the error interceptor first\n config.validateStatus = () => false;\n }\n return config;\n });\n const responseInterceptorId = axiosInstance.interceptors.response.use(null, async (error) => {\n const { config } = error;\n // If we have no information to retry the request\n if (!config) {\n return Promise.reject(error);\n }\n const currentState = setCurrentState(config, defaultOptions);\n if (error.response && currentState.validateResponse?.(error.response)) {\n // no issue with response\n return error.response;\n }\n if (await shouldRetry(currentState, error)) {\n return handleRetry(axiosInstance, currentState, error, config);\n }\n await handleMaxRetryTimesExceeded(currentState, error);\n return Promise.reject(error);\n });\n return { requestInterceptorId, responseInterceptorId };\n};\n// Compatibility with CommonJS\naxiosRetry.isNetworkError = isNetworkError;\naxiosRetry.isSafeRequestError = isSafeRequestError;\naxiosRetry.isIdempotentRequestError = isIdempotentRequestError;\naxiosRetry.isNetworkOrIdempotentRequestError = isNetworkOrIdempotentRequestError;\naxiosRetry.exponentialDelay = exponentialDelay;\naxiosRetry.linearDelay = linearDelay;\naxiosRetry.isRetryableError = isRetryableError;\nexport default axiosRetry;\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 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 -- @preserve */\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 /* v8 ignore start -- @preserve */\n deviceApi.interceptors.request.use(\n (config) => {\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 (error: Error) => Promise.reject(error),\n );\n /* v8 ignore stop */\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 i += 1;\n const pubKey = response.slice(i, i + 65).toString(\"hex\");\n i += 65;\n const keyHandleLength = response.slice(i, i + 1)[0]!;\n i++;\n const keyHandle = response.slice(i, i + keyHandleLength);\n 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","/* eslint-disable no-continue */\n/* eslint-disable no-unused-vars */\n/* eslint-disable no-param-reassign */\n/* eslint-disable no-prototype-builtins */\nconst errorClasses = {};\nconst deserializers = {};\nexport const addCustomErrorDeserializer = (name, deserializer) => {\n deserializers[name] = deserializer;\n};\nexport const createCustomErrorClass = (name) => {\n class CustomErrorClass extends Error {\n cause;\n constructor(message, fields, options) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n super(message || name, options);\n // Set the prototype explicitly. See https://github.com/Microsoft/TypeScript/wiki/Breaking-Changes#extending-built-ins-like-error-array-and-map-may-no-longer-work\n Object.setPrototypeOf(this, CustomErrorClass.prototype);\n this.name = name;\n if (fields) {\n for (const k in fields) {\n // eslint-disable-next-line @typescript-eslint/ban-ts-comment\n // @ts-ignore\n this[k] = fields[k];\n }\n }\n if (options && isObject(options) && \"cause\" in options && !this.cause) {\n // .cause was specified but the superconstructor\n // did not create an instance property.\n const cause = options.cause;\n this.cause = cause;\n if (\"stack\" in cause) {\n this.stack = this.stack + \"\\nCAUSE: \" + cause.stack;\n }\n }\n }\n }\n errorClasses[name] = CustomErrorClass;\n return CustomErrorClass;\n};\nfunction isObject(value) {\n return typeof value === \"object\";\n}\n// inspired from https://github.com/programble/errio/blob/master/index.js\nexport const deserializeError = (object) => {\n if (object && typeof object === \"object\") {\n try {\n if (typeof object.message === \"string\") {\n const msg = JSON.parse(object.message);\n if (msg.message && msg.name) {\n object = msg;\n }\n }\n }\n catch {\n // nothing\n }\n let error;\n if (typeof object.name === \"string\") {\n const { name } = object;\n const des = deserializers[name];\n if (des) {\n error = des(object);\n }\n else {\n let constructor = name === \"Error\" ? Error : errorClasses[name];\n if (!constructor) {\n console.warn(\"deserializing an unknown class '\" + name + \"'\");\n constructor = createCustomErrorClass(name);\n }\n error = Object.create(constructor.prototype);\n try {\n for (const prop in object) {\n if (object.hasOwnProperty(prop)) {\n error[prop] = object[prop];\n }\n }\n }\n catch {\n // sometimes setting a property can fail (e.g. .name)\n }\n }\n }\n else {\n if (typeof object.message === \"string\") {\n error = new Error(object.message);\n }\n }\n // captureStackTrace is V8/Node-specific and not in @types/node\n const Err = Error;\n if (error && !error.stack && Err.captureStackTrace) {\n Err.captureStackTrace(error, deserializeError);\n }\n return error;\n }\n return new Error(String(object));\n};\n// inspired from https://github.com/sindresorhus/serialize-error/blob/master/index.js\nexport const serializeError = (value) => {\n if (!value)\n return value;\n if (typeof value === \"object\") {\n return destroyCircular(value, []);\n }\n if (typeof value === \"function\") {\n return `[Function: ${value.name || \"anonymous\"}]`;\n }\n return value;\n};\n// https://www.npmjs.com/package/destroy-circular\nfunction destroyCircular(from, seen) {\n const to = {};\n seen.push(from);\n for (const key of Object.keys(from)) {\n const value = from[key];\n if (typeof value === \"function\") {\n continue;\n }\n if (!value || typeof value !== \"object\") {\n to[key] = value;\n continue;\n }\n if (seen.indexOf(from[key]) === -1) {\n to[key] = destroyCircular(from[key], seen.slice(0));\n continue;\n }\n to[key] = \"[Circular]\";\n }\n if (typeof from.name === \"string\") {\n to.name = from.name;\n }\n if (typeof from.message === \"string\") {\n to.message = from.message;\n }\n if (typeof from.stack === \"string\") {\n to.stack = from.stack;\n }\n return to;\n}\n//# sourceMappingURL=helpers.js.map","import { serializeError, deserializeError, createCustomErrorClass, addCustomErrorDeserializer, } from \"./helpers\";\nexport { serializeError, deserializeError, createCustomErrorClass, addCustomErrorDeserializer };\nexport const AccountNameRequiredError = createCustomErrorClass(\"AccountNameRequired\");\nexport const AccountNotSupported = createCustomErrorClass(\"AccountNotSupported\");\nexport const AccountAwaitingSendPendingOperations = createCustomErrorClass(\"AccountAwaitingSendPendingOperations\");\nexport const AmountRequired = createCustomErrorClass(\"AmountRequired\");\nexport const BluetoothRequired = createCustomErrorClass(\"BluetoothRequired\");\nexport const BtcUnmatchedApp = createCustomErrorClass(\"BtcUnmatchedApp\");\nexport const CantOpenDevice = createCustomErrorClass(\"CantOpenDevice\");\nexport const CashAddrNotSupported = createCustomErrorClass(\"CashAddrNotSupported\");\nexport const ClaimRewardsFeesWarning = createCustomErrorClass(\"ClaimRewardsFeesWarning\");\nexport const CurrencyNotSupported = createCustomErrorClass(\"CurrencyNotSupported\");\nexport const DeviceAppVerifyNotSupported = createCustomErrorClass(\"DeviceAppVerifyNotSupported\");\nexport const DeviceGenuineSocketEarlyClose = createCustomErrorClass(\"DeviceGenuineSocketEarlyClose\");\nexport const DeviceNotGenuineError = createCustomErrorClass(\"DeviceNotGenuine\");\nexport const DeviceOnDashboardExpected = createCustomErrorClass(\"DeviceOnDashboardExpected\");\nexport const DeviceOnDashboardUnexpected = createCustomErrorClass(\"DeviceOnDashboardUnexpected\");\nexport const DeviceInOSUExpected = createCustomErrorClass(\"DeviceInOSUExpected\");\nexport const DeviceHalted = createCustomErrorClass(\"DeviceHalted\");\nexport const DeviceNameInvalid = createCustomErrorClass(\"DeviceNameInvalid\");\nexport const DeviceSocketFail = createCustomErrorClass(\"DeviceSocketFail\");\nexport const DeviceSocketNoBulkStatus = createCustomErrorClass(\"DeviceSocketNoBulkStatus\");\nexport const DeviceNeedsRestart = createCustomErrorClass(\"DeviceSocketNoBulkStatus\");\nexport const UnresponsiveDeviceError = createCustomErrorClass(\"UnresponsiveDeviceError\");\nexport const DisconnectedDevice = createCustomErrorClass(\"DisconnectedDevice\");\nexport const DisconnectedDeviceDuringOperation = createCustomErrorClass(\"DisconnectedDeviceDuringOperation\");\nexport const DeviceExtractOnboardingStateError = createCustomErrorClass(\"DeviceExtractOnboardingStateError\");\nexport const DeviceOnboardingStatePollingError = createCustomErrorClass(\"DeviceOnboardingStatePollingError\");\nexport const EnpointConfigError = createCustomErrorClass(\"EnpointConfig\");\nexport const EthAppPleaseEnableContractData = createCustomErrorClass(\"EthAppPleaseEnableContractData\");\nexport const SolAppPleaseEnableContractData = createCustomErrorClass(\"SolAppPleaseEnableContractData\");\nexport const CeloAppPleaseEnableContractData = createCustomErrorClass(\"CeloAppPleaseEnableContractData\");\nexport const FeeEstimationFailed = createCustomErrorClass(\"FeeEstimationFailed\");\nexport const FirmwareNotRecognized = createCustomErrorClass(\"FirmwareNotRecognized\");\nexport const HardResetFail = createCustomErrorClass(\"HardResetFail\");\nexport const InvalidXRPTag = createCustomErrorClass(\"InvalidXRPTag\");\nexport const InvalidAddress = createCustomErrorClass(\"InvalidAddress\");\nexport const InvalidTransactionError = createCustomErrorClass(\"InvalidTransactionError\");\nexport const InvalidNonce = createCustomErrorClass(\"InvalidNonce\");\nexport const InvalidAddressBecauseDestinationIsAlsoSource = createCustomErrorClass(\"InvalidAddressBecauseDestinationIsAlsoSource\");\nexport const LatestMCUInstalledError = createCustomErrorClass(\"LatestMCUInstalledError\");\nexport const LatestFirmwareVersionRequired = createCustomErrorClass(\"LatestFirmwareVersionRequired\");\nexport const UnsupportedFeatureError = createCustomErrorClass(\"UnsupportedFeatureError\");\nexport const NanoSNotSupported = createCustomErrorClass(\"NanoSNotSupported\");\nexport const UnknownMCU = createCustomErrorClass(\"UnknownMCU\");\nexport const LedgerAPIError = createCustomErrorClass(\"LedgerAPIError\");\nexport const LedgerAPIErrorWithMessage = createCustomErrorClass(\"LedgerAPIErrorWithMessage\");\nexport const LedgerAPINotAvailable = createCustomErrorClass(\"LedgerAPINotAvailable\");\nexport const ManagerAppAlreadyInstalledError = createCustomErrorClass(\"ManagerAppAlreadyInstalled\");\nexport const ManagerAppRelyOnBTCError = createCustomErrorClass(\"ManagerAppRelyOnBTC\");\nexport const ManagerAppDepInstallRequired = createCustomErrorClass(\"ManagerAppDepInstallRequired\");\nexport const ManagerAppDepUninstallRequired = createCustomErrorClass(\"ManagerAppDepUninstallRequired\");\nexport const ManagerDeviceLockedError = createCustomErrorClass(\"ManagerDeviceLocked\");\nexport const ManagerFirmwareNotEnoughSpaceError = createCustomErrorClass(\"ManagerFirmwareNotEnoughSpace\");\nexport const ManagerNotEnoughSpaceError = createCustomErrorClass(\"ManagerNotEnoughSpace\");\nexport const ManagerUninstallBTCDep = createCustomErrorClass(\"ManagerUninstallBTCDep\");\nexport const NetworkDown = createCustomErrorClass(\"NetworkDown\");\nexport const NetworkError = createCustomErrorClass(\"NetworkError\");\nexport const NoAddressesFound = createCustomErrorClass(\"NoAddressesFound\");\nexport const NotEnoughBalance = createCustomErrorClass(\"NotEnoughBalance\");\nexport const NotEnoughBalanceFees = createCustomErrorClass(\"NotEnoughBalanceFees\");\nexport const NotEnoughBalanceSwap = createCustomErrorClass(\"NotEnoughBalanceSwap\");\nexport const NotEnoughBalanceToDelegate = createCustomErrorClass(\"NotEnoughBalanceToDelegate\");\nexport const UnstakeNotEnoughStakedBalanceLeft = createCustomErrorClass(\"UnstakeNotEnoughStakedBalanceLeft\");\nexport const RestakeNotEnoughStakedBalanceLeft = createCustomErrorClass(\"RestakeNotEnoughStakedBalanceLeft\");\nexport const NotEnoughToRestake = createCustomErrorClass(\"NotEnoughToRestake\");\nexport const NotEnoughToUnstake = createCustomErrorClass(\"NotEnoughToUnstake\");\nexport const NotEnoughBalanceInParentAccount = createCustomErrorClass(\"NotEnoughBalanceInParentAccount\");\nexport const NotEnoughSpendableBalance = createCustomErrorClass(\"NotEnoughSpendableBalance\");\nexport const NotEnoughBalanceBecauseDestinationNotCreated = createCustomErrorClass(\"NotEnoughBalanceBecauseDestinationNotCreated\");\nexport const NotEnoughToStake = createCustomErrorClass(\"NotEnoughToStake\");\nexport const NoAccessToCamera = createCustomErrorClass(\"NoAccessToCamera\");\nexport const NotEnoughGas = createCustomErrorClass(\"NotEnoughGas\");\n// Error message specifically for the PTX swap flow\nexport const NotEnoughGasSwap = createCustomErrorClass(\"NotEnoughGasSwap\");\nexport const TronEmptyAccount = createCustomErrorClass(\"TronEmptyAccount\");\nexport const MaybeKeepTronAccountAlive = createCustomErrorClass(\"MaybeKeepTronAccountAlive\");\nexport const NotSupportedLegacyAddress = createCustomErrorClass(\"NotSupportedLegacyAddress\");\nexport const GasLessThanEstimate = createCustomErrorClass(\"GasLessThanEstimate\");\nexport const PriorityFeeTooLow = createCustomErrorClass(\"PriorityFeeTooLow\");\nexport const PriorityFeeTooHigh = createCustomErrorClass(\"PriorityFeeTooHigh\");\nexport const PriorityFeeHigherThanMaxFee = createCustomErrorClass(\"PriorityFeeHigherThanMaxFee\");\nexport const MaxFeeTooLow = createCustomErrorClass(\"MaxFeeTooLow\");\nexport const PasswordsDontMatchError = createCustomErrorClass(\"PasswordsDontMatch\");\nexport const PasswordIncorrectError = createCustomErrorClass(\"PasswordIncorrect\");\nexport const RecommendSubAccountsToEmpty = createCustomErrorClass(\"RecommendSubAccountsToEmpty\");\nexport const RecommendUndelegation = createCustomErrorClass(\"RecommendUndelegation\");\nexport const TimeoutTagged = createCustomErrorClass(\"TimeoutTagged\");\nexport const UnexpectedBootloader = createCustomErrorClass(\"UnexpectedBootloader\");\nexport const MCUNotGenuineToDashboard = createCustomErrorClass(\"MCUNotGenuineToDashboard\");\nexport const RecipientRequired = createCustomErrorClass(\"RecipientRequired\");\nexport const UnavailableTezosOriginatedAccountReceive = createCustomErrorClass(\"UnavailableTezosOriginatedAccountReceive\");\nexport const UnavailableTezosOriginatedAccountSend = createCustomErrorClass(\"UnavailableTezosOriginatedAccountSend\");\nexport const UpdateFetchFileFail = createCustomErrorClass(\"UpdateFetchFileFail\");\nexport const UpdateIncorrectHash = createCustomErrorClass(\"UpdateIncorrectHash\");\nexport const UpdateIncorrectSig = createCustomErrorClass(\"UpdateIncorrectSig\");\nexport const UpdateYourApp = createCustomErrorClass(\"UpdateYourApp\");\nexport const UserRefusedDeviceNameChange = createCustomErrorClass(\"UserRefusedDeviceNameChange\");\nexport const UserRefusedAddress = createCustomErrorClass(\"UserRefusedAddress\");\nexport const UserRefusedFirmwareUpdate = createCustomErrorClass(\"UserRefusedFirmwareUpdate\");\nexport const UserRefusedAllowManager = createCustomErrorClass(\"UserRefusedAllowManager\");\nexport const UserRefusedOnDevice = createCustomErrorClass(\"UserRefusedOnDevice\"); // TODO rename because it's just for transaction refusal\nexport const PinNotSet = createCustomErrorClass(\"PinNotSet\");\nexport const ExpertModeRequired = createCustomErrorClass(\"ExpertModeRequired\");\nexport const TransportOpenUserCancelled = createCustomErrorClass(\"TransportOpenUserCancelled\");\nexport const TransportInterfaceNotAvailable = createCustomErrorClass(\"TransportInterfaceNotAvailable\");\nexport const TransportRaceCondition = createCustomErrorClass(\"TransportRaceCondition\");\nexport const TransportWebUSBGestureRequired = createCustomErrorClass(\"TransportWebUSBGestureRequired\");\nexport const TransactionHasBeenValidatedError = createCustomErrorClass(\"TransactionHasBeenValidatedError\");\nexport const TransportExchangeTimeoutError = createCustomErrorClass(\"TransportExchangeTimeoutError\");\nexport const DeviceShouldStayInApp = createCustomErrorClass(\"DeviceShouldStayInApp\");\nexport const WebsocketConnectionError = createCustomErrorClass(\"WebsocketConnectionError\");\nexport const WebsocketConnectionFailed = createCustomErrorClass(\"WebsocketConnectionFailed\");\nexport const WrongDeviceForAccount = createCustomErrorClass(\"WrongDeviceForAccount\");\nexport const WrongDeviceForAccountPayout = createCustomErrorClass(\"WrongDeviceForAccountPayout\");\nexport const MissingSwapPayloadParamaters = createCustomErrorClass(\"MissingSwapPayloadParamaters\");\nexport const WrongDeviceForAccountRefund = createCustomErrorClass(\"WrongDeviceForAccountRefund\");\nexport const WrongAppForCurrency = createCustomErrorClass(\"WrongAppForCurrency\");\nexport const ETHAddressNonEIP = createCustomErrorClass(\"ETHAddressNonEIP\");\nexport const CantScanQRCode = createCustomErrorClass(\"CantScanQRCode\");\nexport const FeeNotLoaded = createCustomErrorClass(\"FeeNotLoaded\");\nexport const FeeNotLoadedSwap = createCustomErrorClass(\"FeeNotLoadedSwap\");\nexport const FeeRequired = createCustomErrorClass(\"FeeRequired\");\nexport const FeeTooHigh = createCustomErrorClass(\"FeeTooHigh\");\nexport const ValAddressRequired = createCustomErrorClass(\"ValAddressRequired\");\nexport const RedelegateDstValAddressRequired = createCustomErrorClass(\"RedelegateDstValAddressRequired\");\nexport const PendingOperation = createCustomErrorClass(\"PendingOperation\");\nexport const SyncError = createCustomErrorClass(\"SyncError\");\nexport const PairingFailed = createCustomErrorClass(\"PairingFailed\");\nexport const PeerRemovedPairing = createCustomErrorClass(\"PeerRemovedPairing\");\nexport const GenuineCheckFailed = createCustomErrorClass(\"GenuineCheckFailed\");\nexport const LedgerAPI4xx = createCustomErrorClass(\"LedgerAPI4xx\");\nexport const LedgerAPI5xx = createCustomErrorClass(\"LedgerAPI5xx\");\nexport const FirmwareOrAppUpdateRequired = createCustomErrorClass(\"FirmwareOrAppUpdateRequired\");\n// SpeedUp / Cancel EVM tx\nexport const ReplacementTransactionUnderpriced = createCustomErrorClass(\"ReplacementTransactionUnderpriced\");\n// Bitcoin family\nexport const OpReturnDataSizeLimit = createCustomErrorClass(\"OpReturnSizeLimit\");\nexport const DustLimit = createCustomErrorClass(\"DustLimit\");\n// Concordium family\nexport const ConcordiumInsufficientFunds = createCustomErrorClass(\"ConcordiumInsufficientFunds\");\nexport const ConcordiumMemoTooLong = createCustomErrorClass(\"ConcordiumMemoTooLong\");\nexport const ConcordiumPairingExpiredError = createCustomErrorClass(\"ConcordiumPairingExpiredError\");\nexport const ConcordiumSessionExpiredError = createCustomErrorClass(\"ConcordiumSessionExpiredError\");\nexport const ConcordiumTrustedMetadataServiceError = createCustomErrorClass(\"ConcordiumTrustedMetadataServiceError\");\nexport const ConcordiumAddressVerificationFailedError = createCustomErrorClass(\"ConcordiumAddressVerificationFailedError\");\nexport const ConcordiumInvalidMaxFeeError = createCustomErrorClass(\"ConcordiumInvalidMaxFeeError\");\n// Language\nexport const LanguageNotFound = createCustomErrorClass(\"LanguageNotFound\");\n// db stuff, no need to translate\nexport const NoDBPathGiven = createCustomErrorClass(\"NoDBPathGiven\");\nexport const DBWrongPassword = createCustomErrorClass(\"DBWrongPassword\");\nexport const DBNotReset = createCustomErrorClass(\"DBNotReset\");\nexport const SequenceNumberError = createCustomErrorClass(\"SequenceNumberError\");\nexport const DisabledTransactionBroadcastError = createCustomErrorClass(\"DisabledTransactionBroadcastError\");\nexport const InvalidParameterError = createCustomErrorClass(\"InvalidParameterError\");\n/**\n * Type of a Transport error used to represent all equivalent errors coming from all possible implementation of Transport\n */\nexport var HwTransportErrorType;\n(function (HwTransportErrorType) {\n HwTransportErrorType[\"Unknown\"] = \"Unknown\";\n HwTransportErrorType[\"LocationServicesDisabled\"] = \"LocationServicesDisabled\";\n HwTransportErrorType[\"LocationServicesUnauthorized\"] = \"LocationServicesUnauthorized\";\n HwTransportErrorType[\"BluetoothScanStartFailed\"] = \"BluetoothScanStartFailed\";\n})(HwTransportErrorType || (HwTransportErrorType = {}));\n/**\n * Represents an error coming from the usage of any Transport implementation.\n *\n * Needed to map a specific implementation error into an error that\n * can be managed by any code unaware of the specific Transport implementation\n * that was used.\n */\nexport class HwTransportError extends Error {\n type;\n constructor(type, message) {\n super(message);\n this.name = \"HwTransportError\";\n this.type = type;\n // Needed as long as we target < ES6\n Object.setPrototypeOf(this, HwTransportError.prototype);\n }\n}\n/**\n * TransportError is used for any generic transport errors.\n * e.g. Error thrown when data received by exchanges are incorrect or if exchanged failed to communicate with the device for various reason.\n */\nexport class TransportError extends Error {\n id;\n constructor(message, id) {\n const name = \"TransportError\";\n super(message || name);\n this.name = name;\n this.message = message;\n this.stack = new Error(message).stack;\n this.id = id;\n }\n}\naddCustomErrorDeserializer(\"TransportError\", e => new TransportError(e.message, e.id));\nexport const StatusCodes = {\n ACCESS_CONDITION_NOT_FULFILLED: 0x9804,\n ALGORITHM_NOT_SUPPORTED: 0x9484,\n CLA_NOT_SUPPORTED: 0x6e00,\n CLA_NOT_SUPPORTED_BOOTLOADER: 0x6e01,\n CODE_BLOCKED: 0x9840,\n CODE_NOT_INITIALIZED: 0x9802,\n COMMAND_INCOMPATIBLE_FILE_STRUCTURE: 0x6981,\n CONDITIONS_OF_USE_NOT_SATISFIED: 0x6985,\n CONTRADICTION_INVALIDATION: 0x9810,\n CONTRADICTION_SECRET_CODE_STATUS: 0x9808,\n DEVICE_IN_RECOVERY_MODE: 0x662f,\n CUSTOM_IMAGE_EMPTY: 0x662e,\n FILE_ALREADY_EXISTS: 0x6a89,\n FILE_NOT_FOUND: 0x9404,\n GP_AUTH_FAILED: 0x6300,\n HALTED: 0x6faa,\n INCONSISTENT_FILE: 0x9408,\n INCORRECT_DATA: 0x6a80,\n INCORRECT_LENGTH: 0x6700,\n INCORRECT_P1_P2: 0x6b00,\n INS_NOT_SUPPORTED: 0x6d00,\n DEVICE_NOT_ONBOARDED: 0x6d07,\n DEVICE_NOT_ONBOARDED_2: 0x6611,\n INVALID_KCV: 0x9485,\n INVALID_OFFSET: 0x9402,\n LICENSING: 0x6f42,\n LOCKED_DEVICE: 0x5515,\n MAX_VALUE_REACHED: 0x9850,\n MEMORY_PROBLEM: 0x9240,\n MISSING_CRITICAL_PARAMETER: 0x6800,\n NO_EF_SELECTED: 0x9400,\n NOT_ENOUGH_MEMORY_SPACE: 0x6a84,\n OK: 0x9000,\n PIN_REMAINING_ATTEMPTS: 0x63c0,\n REFERENCED_DATA_NOT_FOUND: 0x6a88,\n SECURITY_STATUS_NOT_SATISFIED: 0x6982,\n TECHNICAL_PROBLEM: 0x6f00,\n UNKNOWN_APDU: 0x6d02,\n USER_REFUSED_ON_DEVICE: 0x5501,\n NOT_ENOUGH_SPACE: 0x5102,\n APP_NOT_FOUND_OR_INVALID_CONTEXT: 0x5123,\n INVALID_APP_NAME_LENGTH: 0x670a,\n GEN_AES_KEY_FAILED: 0x5419,\n INTERNAL_CRYPTO_OPERATION_FAILED: 0x541a,\n INTERNAL_COMPUTE_AES_CMAC_FAILED: 0x541b,\n ENCRYPT_APP_STORAGE_FAILED: 0x541c,\n INVALID_BACKUP_STATE: 0x6642,\n PIN_NOT_SET: 0x5502,\n INVALID_BACKUP_LENGTH: 0x6733,\n INVALID_RESTORE_STATE: 0x6643,\n INVALID_CHUNK_LENGTH: 0x6734,\n INVALID_BACKUP_HEADER: 0x684a,\n SW_BAD_STATE: 0xb007,\n};\nexport function getAltStatusMessage(code) {\n switch (code) {\n // improve text of most common errors\n case 0x6700:\n return \"Incorrect length\";\n case 0x6800:\n return \"Missing critical parameter\";\n case 0x6982:\n return \"Security not satisfied (dongle locked or have invalid access rights)\";\n case 0x6985:\n return \"Condition of use not satisfied (denied by the user?)\";\n case 0x6a80:\n return \"Invalid data received\";\n case 0x6b00:\n return \"Invalid parameter received\";\n case 0x5515:\n return \"Locked device\";\n case 0xb007:\n return \"Unexpected state on the device\";\n }\n if (0x6f00 <= code && code <= 0x6fff) {\n return \"Internal error, please report\";\n }\n}\n/**\n * Error thrown when a device returned a non success status.\n * the error.statusCode is one of the `StatusCodes` exported by this library.\n */\nexport class TransportStatusError extends Error {\n statusCode;\n statusText;\n /**\n * @param statusCode The error status code coming from a Transport implementation\n * @param options containing:\n * - canBeMappedToChildError: enable the mapping of TransportStatusError to an error extending/inheriting from it\n * . Ex: LockedDeviceError. Default to true.\n */\n constructor(statusCode, { canBeMappedToChildError = true } = {}) {\n const statusText = Object.keys(StatusCodes).find(k => StatusCodes[k] === statusCode) || \"UNKNOWN_ERROR\";\n const smsg = getAltStatusMessage(statusCode) || statusText;\n const statusCodeStr = statusCode.toString(16);\n const message = `Ledger device: ${smsg} (0x${statusCodeStr})`;\n super(message);\n this.name = \"TransportStatusError\";\n this.statusCode = statusCode;\n this.statusText = statusText;\n Object.setPrototypeOf(this, TransportStatusError.prototype);\n // Maps to a LockedDeviceError\n if (canBeMappedToChildError && statusCode === StatusCodes.LOCKED_DEVICE) {\n return new LockedDeviceError(message);\n }\n }\n}\nexport class LockedDeviceError extends TransportStatusError {\n constructor(message) {\n super(StatusCodes.LOCKED_DEVICE, { canBeMappedToChildError: false });\n if (message) {\n this.message = message;\n }\n this.name = \"LockedDeviceError\";\n Object.setPrototypeOf(this, LockedDeviceError.prototype);\n }\n}\nexport class DeviceMangementKitError extends Error {\n constructor(name, message) {\n super(message);\n this.name = name;\n Object.setPrototypeOf(this, DeviceMangementKitError.prototype);\n }\n}\naddCustomErrorDeserializer(\"TransportStatusError\", e => new TransportStatusError(e.statusCode));\n//# sourceMappingURL=index.js.map","// biome-ignore-all lint: outside copy-paste, not worth fixing\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","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 0x5501, // cancel openApp\n];\n\nexport const isDeviceCancelError = (error: Error): boolean => {\n return isTransportStatusError(error) && CANCEL_STATUS_CODES.includes(error.statusCode);\n};\n"],"x_google_ignoreList":[0,1,4,5],"mappings":";;;;;;;;CAEA,MAAM,WAAW,IAAI,IAAI;EACxB;EACA;EAGA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACD,CAAC;CAGD,OAAO,WAAU,UAAS,CAAC,SAAS,IAAI,SAAS,MAAM,IAAI;;;;;ACrC3D,MAAa,YAAY;AACzB,SAAgB,eAAe,OAAO;CAClC,MAAM,oBAAoB,CAAC,gBAAgB,cAAc;CACzD,IAAI,MAAM,UACN,OAAO;CAEX,IAAI,CAAC,MAAM,MACP,OAAO;CAGX,IAAI,kBAAkB,SAAS,MAAM,IAAI,GACrC,OAAO;CAGX,QAAA,GAAA,wBAAA,QAAA,CAAsB,KAAK;AAC/B;AACA,MAAM,oBAAoB;CAAC;CAAO;CAAQ;AAAS;AACnD,MAAM,0BAA0B,kBAAkB,OAAO,CAAC,OAAO,QAAQ,CAAC;AAC1E,SAAgB,iBAAiB,OAAO;CACpC,OAAQ,MAAM,SAAS,mBAClB,CAAC,MAAM,YACJ,MAAM,SAAS,WAAW,OACzB,MAAM,SAAS,UAAU,OAAO,MAAM,SAAS,UAAU;AACtE;AACA,SAAgB,mBAAmB,OAAO;CACtC,IAAI,CAAC,MAAM,QAAQ,QAEf,OAAO;CAEX,OAAO,iBAAiB,KAAK,KAAK,kBAAkB,QAAQ,MAAM,OAAO,MAAM,MAAM;AACzF;AACA,SAAgB,yBAAyB,OAAO;CAC5C,IAAI,CAAC,MAAM,QAAQ,QAEf,OAAO;CAEX,OAAO,iBAAiB,KAAK,KAAK,wBAAwB,QAAQ,MAAM,OAAO,MAAM,MAAM;AAC/F;AACA,SAAgB,kCAAkC,OAAO;CACrD,OAAO,eAAe,K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