UNPKG

@pact-toolbox/crypto

Version:
1 lines 149 kB
{"version":3,"file":"index.browser.cjs","names":["subtle","nodeCrypto","_typeof","o","_typeof","toPrimitive","toPropertyKey","_defineProperty","C","G","P","data: BufferSource","storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT: WeakMap<CryptoKey, Uint8Array> | undefined","publicKeyBytesStore: WeakMap<CryptoKey, Uint8Array> | undefined","createKeyPairFromBytes","bytes: Uint8Array","extractable: boolean","keyUsages: readonly KeyUsage[]","key: CryptoKey","value: string","format: KeyFormat","signature","signature: BufferSource","type: \"private\" | \"public\"","keyData: BufferSource | JsonWebKey","cachedEd25519Decision: PromiseLike<boolean> | boolean | undefined","subtle: SubtleCrypto","crypto","codecDescription: string","bytes: ReadonlyUint8Array | Uint8Array","expected: number","offset: number","bytesLength: number","alphabet: string","testValue: string","givenValue: string","alphabet","value: TFrom","encoder: { fixedSize: number } | { getSizeFromValue: (value: TFrom) => number }","encoder: Omit<FixedSizeEncoder<TFrom>, \"encode\"> | Omit<VariableSizeEncoder<TFrom>, \"encode\">","decoder: Omit<FixedSizeDecoder<TTo>, \"decode\"> | Omit<VariableSizeDecoder<TTo>, \"decode\">","codec:\n | Omit<FixedSizeCodec<TFrom, TTo>, \"decode\" | \"encode\">\n | Omit<VariableSizeCodec<TFrom, TTo>, \"decode\" | \"encode\">","codec: { fixedSize: number } | { maxSize?: number }","encoder: Encoder<TOldFrom>","unmap: (value: TNewFrom) => TOldFrom","value: TNewFrom","decoder: Decoder<TOldTo>","map: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo","bytes: ReadonlyUint8Array | Uint8Array","encoder: Encoder<TFrom>","decoder: Decoder<TTo>","codec: Codec<TOldFrom, TOldTo>","map?: (value: TOldTo, bytes: ReadonlyUint8Array | Uint8Array, offset: number) => TNewTo","byteArrays: Uint8Array[]","length: number","data: ReadonlyUint8Array | Uint8Array","offset: number","fixedBytes: TSize","bytes: Uint8Array","offset: Offset","codec: Codec<TFrom, TTo>","char: number","value: string","base16: VariableSizeCodec<string>","base16Encoder: Encoder<string> | undefined","putativeSignature: string","key: CryptoKey","data: ReadonlyUint8Array","signature: SignatureBytes","data: ReadonlyUint8Array | Uint8Array","signature","bytes: ReadonlyUint8Array","extractable?: boolean","privateKey: CryptoKey","extractable: boolean","randomBytes","privateKey","putativeAddress: string","putativeAddress: TAddress","addressEncoder: FixedSizeEncoder<Address, 32> | undefined","addressDecoder: FixedSizeDecoder<Address, 32> | undefined","addressCodec: FixedSizeCodec<Address, Address, 32> | undefined","key: CryptoKey","putativeAccount: string","publicKey: CryptoKey","address","alphabet: string","value: string","alphabet","tailBytes: number[]","zeroCharacter: string","value: bigint","alphabet","base10: VariableSizeCodec<string>","base58: VariableSizeCodec<string>","alphabet: string","bits: number","value: string","alphabet","input: number[]","inputBits: number","outputBits: number","useRemainder: boolean","value: string","value: string","base64Url: VariableSizeCodec<string>","value: string","chars: number","textEncoder: TextEncoder","value: string","textDecoder: TextDecoder","utf8: VariableSizeCodec<string>","input: string | Uint8Array","val: unknown","isArrayProp: boolean"],"sources":["../../../node_modules/.pnpm/uncrypto@0.1.3/node_modules/uncrypto/dist/crypto.node.mjs","../../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/typeof.js","../../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPrimitive.js","../../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/toPropertyKey.js","../../../node_modules/.pnpm/@oxc-project+runtime@0.72.2/node_modules/@oxc-project/runtime/src/helpers/defineProperty.js","../../../node_modules/.pnpm/@noble+ed25519@2.3.0/node_modules/@noble/ed25519/index.js","../src/polyfill/secrets.ts","../src/polyfill/install.ts","../src/assertions.ts","../src/codecs/core.ts","../src/codecs/strings/base16.ts","../src/keys/signatures.ts","../src/keys/keys.ts","../src/address.ts","../src/codecs/strings/baseX.ts","../src/codecs/strings/base10.ts","../src/codecs/strings/base58.ts","../src/codecs/strings/baseX-reslice.ts","../src/codecs/strings/base64.ts","../src/codecs/strings/base64-url.ts","../src/codecs/strings/null.ts","../src/codecs/text.ts","../src/codecs/strings/utf-8.ts","../src/hash/base64-url-blake2b.ts","../src/stringify.ts","../src/index.ts"],"sourcesContent":["import nodeCrypto from 'node:crypto';\n\nconst subtle = nodeCrypto.webcrypto?.subtle || {};\nconst randomUUID = () => {\n return nodeCrypto.randomUUID();\n};\nconst getRandomValues = (array) => {\n return nodeCrypto.webcrypto.getRandomValues(array);\n};\nconst _crypto = {\n randomUUID,\n getRandomValues,\n subtle\n};\n\nexport { _crypto as default, getRandomValues, randomUUID, subtle };\n","function _typeof(o) {\n \"@babel/helpers - typeof\";\n\n return module.exports = _typeof = \"function\" == typeof Symbol && \"symbol\" == typeof Symbol.iterator ? function (o) {\n return typeof o;\n } : function (o) {\n return o && \"function\" == typeof Symbol && o.constructor === Symbol && o !== Symbol.prototype ? \"symbol\" : typeof o;\n }, module.exports.__esModule = true, module.exports[\"default\"] = module.exports, _typeof(o);\n}\nmodule.exports = _typeof, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","var _typeof = require(\"./typeof.js\")[\"default\"];\nfunction toPrimitive(t, r) {\n if (\"object\" != _typeof(t) || !t) return t;\n var e = t[Symbol.toPrimitive];\n if (void 0 !== e) {\n var i = e.call(t, r || \"default\");\n if (\"object\" != _typeof(i)) return i;\n throw new TypeError(\"@@toPrimitive must return a primitive value.\");\n }\n return (\"string\" === r ? String : Number)(t);\n}\nmodule.exports = toPrimitive, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","var _typeof = require(\"./typeof.js\")[\"default\"];\nvar toPrimitive = require(\"./toPrimitive.js\");\nfunction toPropertyKey(t) {\n var i = toPrimitive(t, \"string\");\n return \"symbol\" == _typeof(i) ? i : i + \"\";\n}\nmodule.exports = toPropertyKey, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","var toPropertyKey = require(\"./toPropertyKey.js\");\nfunction _defineProperty(e, r, t) {\n return (r = toPropertyKey(r)) in e ? Object.defineProperty(e, r, {\n value: t,\n enumerable: !0,\n configurable: !0,\n writable: !0\n }) : e[r] = t, e;\n}\nmodule.exports = _defineProperty, module.exports.__esModule = true, module.exports[\"default\"] = module.exports;","/*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) */\n/**\n * 4KB JS implementation of ed25519 EdDSA signatures.\n * Compliant with RFC8032, FIPS 186-5 & ZIP215.\n * @module\n * @example\n * ```js\nimport * as ed from '@noble/ed25519';\n(async () => {\n const privKey = ed.utils.randomPrivateKey();\n const message = Uint8Array.from([0xab, 0xbc, 0xcd, 0xde]);\n const pubKey = await ed.getPublicKeyAsync(privKey); // Sync methods are also present\n const signature = await ed.signAsync(message, privKey);\n const isValid = await ed.verifyAsync(signature, message, pubKey);\n})();\n```\n */\n/**\n * Curve params. ed25519 is twisted edwards curve. Equation is −x² + y² = -a + dx²y².\n * * P = `2n**255n - 19n` // field over which calculations are done\n * * N = `2n**252n + 27742317777372353535851937790883648493n` // group order, amount of curve points\n * * h = 8 // cofactor\n * * a = `Fp.create(BigInt(-1))` // equation param\n * * d = -121665/121666 a.k.a. `Fp.neg(121665 * Fp.inv(121666))` // equation param\n * * Gx, Gy are coordinates of Generator / base point\n */\nconst ed25519_CURVE = {\n p: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffedn,\n n: 0x1000000000000000000000000000000014def9dea2f79cd65812631a5cf5d3edn,\n h: 8n,\n a: 0x7fffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffecn,\n d: 0x52036cee2b6ffe738cc740797779e89800700a4d4141d8ab75eb4dca135978a3n,\n Gx: 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an,\n Gy: 0x6666666666666666666666666666666666666666666666666666666666666658n,\n};\nconst { p: P, n: N, Gx, Gy, a: _a, d: _d } = ed25519_CURVE;\nconst h = 8n; // cofactor\nconst L = 32; // field / group byte length\nconst L2 = 64;\n// Helpers and Precomputes sections are reused between libraries\n// ## Helpers\n// ----------\n// error helper, messes-up stack trace\nconst err = (m = '') => {\n throw new Error(m);\n};\nconst isBig = (n) => typeof n === 'bigint'; // is big integer\nconst isStr = (s) => typeof s === 'string'; // is string\nconst isBytes = (a) => a instanceof Uint8Array || (ArrayBuffer.isView(a) && a.constructor.name === 'Uint8Array');\n/** assert is Uint8Array (of specific length) */\nconst abytes = (a, l) => !isBytes(a) || (typeof l === 'number' && l > 0 && a.length !== l)\n ? err('Uint8Array expected')\n : a;\n/** create Uint8Array */\nconst u8n = (len) => new Uint8Array(len);\nconst u8fr = (buf) => Uint8Array.from(buf);\nconst padh = (n, pad) => n.toString(16).padStart(pad, '0');\nconst bytesToHex = (b) => Array.from(abytes(b))\n .map((e) => padh(e, 2))\n .join('');\nconst C = { _0: 48, _9: 57, A: 65, F: 70, a: 97, f: 102 }; // ASCII characters\nconst _ch = (ch) => {\n if (ch >= C._0 && ch <= C._9)\n return ch - C._0; // '2' => 50-48\n if (ch >= C.A && ch <= C.F)\n return ch - (C.A - 10); // 'B' => 66-(65-10)\n if (ch >= C.a && ch <= C.f)\n return ch - (C.a - 10); // 'b' => 98-(97-10)\n return;\n};\nconst hexToBytes = (hex) => {\n const e = 'hex invalid';\n if (!isStr(hex))\n return err(e);\n const hl = hex.length;\n const al = hl / 2;\n if (hl % 2)\n return err(e);\n const array = u8n(al);\n for (let ai = 0, hi = 0; ai < al; ai++, hi += 2) {\n // treat each char as ASCII\n const n1 = _ch(hex.charCodeAt(hi)); // parse first char, multiply it by 16\n const n2 = _ch(hex.charCodeAt(hi + 1)); // parse second char\n if (n1 === undefined || n2 === undefined)\n return err(e);\n array[ai] = n1 * 16 + n2; // example: 'A9' => 10*16 + 9\n }\n return array;\n};\n/** normalize hex or ui8a to ui8a */\nconst toU8 = (a, len) => abytes(isStr(a) ? hexToBytes(a) : u8fr(abytes(a)), len);\nconst cr = () => globalThis?.crypto; // WebCrypto is available in all modern environments\nconst subtle = () => cr()?.subtle ?? err('crypto.subtle must be defined');\n// prettier-ignore\nconst concatBytes = (...arrs) => {\n const r = u8n(arrs.reduce((sum, a) => sum + abytes(a).length, 0)); // create u8a of summed length\n let pad = 0; // walk through each array,\n arrs.forEach(a => { r.set(a, pad); pad += a.length; }); // ensure they have proper type\n return r;\n};\n/** WebCrypto OS-level CSPRNG (random number generator). Will throw when not available. */\nconst randomBytes = (len = L) => {\n const c = cr();\n return c.getRandomValues(u8n(len));\n};\nconst big = BigInt;\nconst arange = (n, min, max, msg = 'bad number: out of range') => isBig(n) && min <= n && n < max ? n : err(msg);\n/** modular division */\nconst M = (a, b = P) => {\n const r = a % b;\n return r >= 0n ? r : b + r;\n};\nconst modN = (a) => M(a, N);\n/** Modular inversion using eucledian GCD (non-CT). No negative exponent for now. */\n// prettier-ignore\nconst invert = (num, md) => {\n if (num === 0n || md <= 0n)\n err('no inverse n=' + num + ' mod=' + md);\n let a = M(num, md), b = md, x = 0n, y = 1n, u = 1n, v = 0n;\n while (a !== 0n) {\n const q = b / a, r = b % a;\n const m = x - u * q, n = y - v * q;\n b = a, a = r, x = u, y = v, u = m, v = n;\n }\n return b === 1n ? M(x, md) : err('no inverse'); // b is gcd at this point\n};\nconst callHash = (name) => {\n // @ts-ignore\n const fn = etc[name];\n if (typeof fn !== 'function')\n err('hashes.' + name + ' not set');\n return fn;\n};\nconst apoint = (p) => (p instanceof Point ? p : err('Point expected'));\n// ## End of Helpers\n// -----------------\nconst B256 = 2n ** 256n;\n/** Point in XYZT extended coordinates. */\nclass Point {\n static BASE;\n static ZERO;\n ex;\n ey;\n ez;\n et;\n constructor(ex, ey, ez, et) {\n const max = B256;\n this.ex = arange(ex, 0n, max);\n this.ey = arange(ey, 0n, max);\n this.ez = arange(ez, 1n, max);\n this.et = arange(et, 0n, max);\n Object.freeze(this);\n }\n static fromAffine(p) {\n return new Point(p.x, p.y, 1n, M(p.x * p.y));\n }\n /** RFC8032 5.1.3: Uint8Array to Point. */\n static fromBytes(hex, zip215 = false) {\n const d = _d;\n // Copy array to not mess it up.\n const normed = u8fr(abytes(hex, L));\n // adjust first LE byte = last BE byte\n const lastByte = hex[31];\n normed[31] = lastByte & ~0x80;\n const y = bytesToNumLE(normed);\n // zip215=true: 0 <= y < 2^256\n // zip215=false, RFC8032: 0 <= y < 2^255-19\n const max = zip215 ? B256 : P;\n arange(y, 0n, max);\n const y2 = M(y * y); // y²\n const u = M(y2 - 1n); // u=y²-1\n const v = M(d * y2 + 1n); // v=dy²+1\n let { isValid, value: x } = uvRatio(u, v); // (uv³)(uv⁷)^(p-5)/8; square root\n if (!isValid)\n err('bad point: y not sqrt'); // not square root: bad point\n const isXOdd = (x & 1n) === 1n; // adjust sign of x coordinate\n const isLastByteOdd = (lastByte & 0x80) !== 0; // x_0, last bit\n if (!zip215 && x === 0n && isLastByteOdd)\n err('bad point: x==0, isLastByteOdd'); // x=0, x_0=1\n if (isLastByteOdd !== isXOdd)\n x = M(-x);\n return new Point(x, y, 1n, M(x * y)); // Z=1, T=xy\n }\n /** Checks if the point is valid and on-curve. */\n assertValidity() {\n const a = _a;\n const d = _d;\n const p = this;\n if (p.is0())\n throw new Error('bad point: ZERO'); // TODO: optimize, with vars below?\n // Equation in affine coordinates: ax² + y² = 1 + dx²y²\n // Equation in projective coordinates (X/Z, Y/Z, Z): (aX² + Y²)Z² = Z⁴ + dX²Y²\n const { ex: X, ey: Y, ez: Z, et: T } = p;\n const X2 = M(X * X); // X²\n const Y2 = M(Y * Y); // Y²\n const Z2 = M(Z * Z); // Z²\n const Z4 = M(Z2 * Z2); // Z⁴\n const aX2 = M(X2 * a); // aX²\n const left = M(Z2 * M(aX2 + Y2)); // (aX² + Y²)Z²\n const right = M(Z4 + M(d * M(X2 * Y2))); // Z⁴ + dX²Y²\n if (left !== right)\n throw new Error('bad point: equation left != right (1)');\n // In Extended coordinates we also have T, which is x*y=T/Z: check X*Y == Z*T\n const XY = M(X * Y);\n const ZT = M(Z * T);\n if (XY !== ZT)\n throw new Error('bad point: equation left != right (2)');\n return this;\n }\n /** Equality check: compare points P&Q. */\n equals(other) {\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const { ex: X2, ey: Y2, ez: Z2 } = apoint(other); // checks class equality\n const X1Z2 = M(X1 * Z2);\n const X2Z1 = M(X2 * Z1);\n const Y1Z2 = M(Y1 * Z2);\n const Y2Z1 = M(Y2 * Z1);\n return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;\n }\n is0() {\n return this.equals(I);\n }\n /** Flip point over y coordinate. */\n negate() {\n return new Point(M(-this.ex), this.ey, this.ez, M(-this.et));\n }\n /** Point doubling. Complete formula. Cost: `4M + 4S + 1*a + 6add + 1*2`. */\n double() {\n const { ex: X1, ey: Y1, ez: Z1 } = this;\n const a = _a;\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended.html#doubling-dbl-2008-hwcd\n const A = M(X1 * X1);\n const B = M(Y1 * Y1);\n const C = M(2n * M(Z1 * Z1));\n const D = M(a * A);\n const x1y1 = X1 + Y1;\n const E = M(M(x1y1 * x1y1) - A - B);\n const G = D + B;\n const F = G - C;\n const H = D - B;\n const X3 = M(E * F);\n const Y3 = M(G * H);\n const T3 = M(E * H);\n const Z3 = M(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n /** Point addition. Complete formula. Cost: `8M + 1*k + 8add + 1*2`. */\n add(other) {\n const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;\n const { ex: X2, ey: Y2, ez: Z2, et: T2 } = apoint(other); // doesn't check if other on-curve\n const a = _a;\n const d = _d;\n // https://hyperelliptic.org/EFD/g1p/auto-twisted-extended-1.html#addition-add-2008-hwcd-3\n const A = M(X1 * X2);\n const B = M(Y1 * Y2);\n const C = M(T1 * d * T2);\n const D = M(Z1 * Z2);\n const E = M((X1 + Y1) * (X2 + Y2) - A - B);\n const F = M(D - C);\n const G = M(D + C);\n const H = M(B - a * A);\n const X3 = M(E * F);\n const Y3 = M(G * H);\n const T3 = M(E * H);\n const Z3 = M(F * G);\n return new Point(X3, Y3, Z3, T3);\n }\n /**\n * Point-by-scalar multiplication. Scalar must be in range 1 <= n < CURVE.n.\n * Uses {@link wNAF} for base point.\n * Uses fake point to mitigate side-channel leakage.\n * @param n scalar by which point is multiplied\n * @param safe safe mode guards against timing attacks; unsafe mode is faster\n */\n multiply(n, safe = true) {\n if (!safe && (n === 0n || this.is0()))\n return I;\n arange(n, 1n, N);\n if (n === 1n)\n return this;\n if (this.equals(G))\n return wNAF(n).p;\n // init result point & fake point\n let p = I;\n let f = G;\n for (let d = this; n > 0n; d = d.double(), n >>= 1n) {\n // if bit is present, add to point\n // if not present, add to fake, for timing safety\n if (n & 1n)\n p = p.add(d);\n else if (safe)\n f = f.add(d);\n }\n return p;\n }\n /** Convert point to 2d xy affine point. (X, Y, Z) ∋ (x=X/Z, y=Y/Z) */\n toAffine() {\n const { ex: x, ey: y, ez: z } = this;\n // fast-paths for ZERO point OR Z=1\n if (this.equals(I))\n return { x: 0n, y: 1n };\n const iz = invert(z, P);\n // (Z * Z^-1) must be 1, otherwise bad math\n if (M(z * iz) !== 1n)\n err('invalid inverse');\n // x = X*Z^-1; y = Y*Z^-1\n return { x: M(x * iz), y: M(y * iz) };\n }\n toBytes() {\n const { x, y } = this.assertValidity().toAffine();\n const b = numTo32bLE(y);\n // store sign in first LE byte\n b[31] |= x & 1n ? 0x80 : 0;\n return b;\n }\n toHex() {\n return bytesToHex(this.toBytes());\n } // encode to hex string\n clearCofactor() {\n return this.multiply(big(h), false);\n }\n isSmallOrder() {\n return this.clearCofactor().is0();\n }\n isTorsionFree() {\n // multiply by big number CURVE.n\n let p = this.multiply(N / 2n, false).double(); // ensures the point is not \"bad\".\n if (N % 2n)\n p = p.add(this); // P^(N+1) // P*N == (P*(N/2))*2+P\n return p.is0();\n }\n static fromHex(hex, zip215) {\n return Point.fromBytes(toU8(hex), zip215);\n }\n get x() {\n return this.toAffine().x;\n }\n get y() {\n return this.toAffine().y;\n }\n toRawBytes() {\n return this.toBytes();\n }\n}\n/** Generator / base point */\nconst G = new Point(Gx, Gy, 1n, M(Gx * Gy));\n/** Identity / zero point */\nconst I = new Point(0n, 1n, 1n, 0n);\n// Static aliases\nPoint.BASE = G;\nPoint.ZERO = I;\nconst numTo32bLE = (num) => hexToBytes(padh(arange(num, 0n, B256), L2)).reverse();\nconst bytesToNumLE = (b) => big('0x' + bytesToHex(u8fr(abytes(b)).reverse()));\nconst pow2 = (x, power) => {\n // pow2(x, 4) == x^(2^4)\n let r = x;\n while (power-- > 0n) {\n r *= r;\n r %= P;\n }\n return r;\n};\n// prettier-ignore\nconst pow_2_252_3 = (x) => {\n const x2 = (x * x) % P; // x^2, bits 1\n const b2 = (x2 * x) % P; // x^3, bits 11\n const b4 = (pow2(b2, 2n) * b2) % P; // x^(2^4-1), bits 1111\n const b5 = (pow2(b4, 1n) * x) % P; // x^(2^5-1), bits 11111\n const b10 = (pow2(b5, 5n) * b5) % P; // x^(2^10)\n const b20 = (pow2(b10, 10n) * b10) % P; // x^(2^20)\n const b40 = (pow2(b20, 20n) * b20) % P; // x^(2^40)\n const b80 = (pow2(b40, 40n) * b40) % P; // x^(2^80)\n const b160 = (pow2(b80, 80n) * b80) % P; // x^(2^160)\n const b240 = (pow2(b160, 80n) * b80) % P; // x^(2^240)\n const b250 = (pow2(b240, 10n) * b10) % P; // x^(2^250)\n const pow_p_5_8 = (pow2(b250, 2n) * x) % P; // < To pow to (p+3)/8, multiply it by x.\n return { pow_p_5_8, b2 };\n};\nconst RM1 = 0x2b8324804fc1df0b2b4d00993dfbd7a72f431806ad2fe478c4ee1b274a0ea0b0n; // √-1\n// for sqrt comp\n// prettier-ignore\nconst uvRatio = (u, v) => {\n const v3 = M(v * v * v); // v³\n const v7 = M(v3 * v3 * v); // v⁷\n const pow = pow_2_252_3(u * v7).pow_p_5_8; // (uv⁷)^(p-5)/8\n let x = M(u * v3 * pow); // (uv³)(uv⁷)^(p-5)/8\n const vx2 = M(v * x * x); // vx²\n const root1 = x; // First root candidate\n const root2 = M(x * RM1); // Second root candidate; RM1 is √-1\n const useRoot1 = vx2 === u; // If vx² = u (mod p), x is a square root\n const useRoot2 = vx2 === M(-u); // If vx² = -u, set x <-- x * 2^((p-1)/4)\n const noRoot = vx2 === M(-u * RM1); // There is no valid root, vx² = -u√-1\n if (useRoot1)\n x = root1;\n if (useRoot2 || noRoot)\n x = root2; // We return root2 anyway, for const-time\n if ((M(x) & 1n) === 1n)\n x = M(-x); // edIsNegative\n return { isValid: useRoot1 || useRoot2, value: x };\n};\n// N == L, just weird naming\nconst modL_LE = (hash) => modN(bytesToNumLE(hash)); // modulo L; but little-endian\nconst sha512a = (...m) => etc.sha512Async(...m); // Async SHA512\nconst sha512s = (...m) => callHash('sha512Sync')(...m);\n// RFC8032 5.1.5\nconst hash2extK = (hashed) => {\n // slice creates a copy, unlike subarray\n const head = hashed.slice(0, L);\n head[0] &= 248; // Clamp bits: 0b1111_1000\n head[31] &= 127; // 0b0111_1111\n head[31] |= 64; // 0b0100_0000\n const prefix = hashed.slice(L, L2); // private key \"prefix\"\n const scalar = modL_LE(head); // modular division over curve order\n const point = G.multiply(scalar); // public key point\n const pointBytes = point.toBytes(); // point serialized to Uint8Array\n return { head, prefix, scalar, point, pointBytes };\n};\n// RFC8032 5.1.5; getPublicKey async, sync. Hash priv key and extract point.\nconst getExtendedPublicKeyAsync = (priv) => sha512a(toU8(priv, L)).then(hash2extK);\nconst getExtendedPublicKey = (priv) => hash2extK(sha512s(toU8(priv, L)));\n/** Creates 32-byte ed25519 public key from 32-byte private key. Async. */\nconst getPublicKeyAsync = (priv) => getExtendedPublicKeyAsync(priv).then((p) => p.pointBytes);\n/** Creates 32-byte ed25519 public key from 32-byte private key. To use, set `etc.sha512Sync` first. */\nconst getPublicKey = (priv) => getExtendedPublicKey(priv).pointBytes;\nconst hashFinishA = (res) => sha512a(res.hashable).then(res.finish);\nconst hashFinishS = (res) => res.finish(sha512s(res.hashable));\nconst _sign = (e, rBytes, msg) => {\n // sign() shared code\n const { pointBytes: P, scalar: s } = e;\n const r = modL_LE(rBytes); // r was created outside, reduce it modulo L\n const R = G.multiply(r).toBytes(); // R = [r]B\n const hashable = concatBytes(R, P, msg); // dom2(F, C) || R || A || PH(M)\n const finish = (hashed) => {\n // k = SHA512(dom2(F, C) || R || A || PH(M))\n const S = modN(r + modL_LE(hashed) * s); // S = (r + k * s) mod L; 0 <= s < l\n return abytes(concatBytes(R, numTo32bLE(S)), L2); // 64-byte sig: 32b R.x + 32b LE(S)\n };\n return { hashable, finish };\n};\n/**\n * Signs message (NOT message hash) using private key. Async.\n * Follows RFC8032 5.1.6.\n */\nconst signAsync = async (msg, privKey) => {\n const m = toU8(msg);\n const e = await getExtendedPublicKeyAsync(privKey);\n const rBytes = await sha512a(e.prefix, m); // r = SHA512(dom2(F, C) || prefix || PH(M))\n return hashFinishA(_sign(e, rBytes, m)); // gen R, k, S, then 64-byte signature\n};\n/**\n * Signs message (NOT message hash) using private key. To use, set `hashes.sha512` first.\n * Follows RFC8032 5.1.6.\n */\nconst sign = (msg, privKey) => {\n const m = toU8(msg);\n const e = getExtendedPublicKey(privKey);\n const rBytes = sha512s(e.prefix, m); // r = SHA512(dom2(F, C) || prefix || PH(M))\n return hashFinishS(_sign(e, rBytes, m)); // gen R, k, S, then 64-byte signature\n};\nconst veriOpts = { zip215: true };\nconst _verify = (sig, msg, pub, opts = veriOpts) => {\n sig = toU8(sig, L2); // Signature hex str/Bytes, must be 64 bytes\n msg = toU8(msg); // Message hex str/Bytes\n pub = toU8(pub, L);\n const { zip215 } = opts; // switch between zip215 and rfc8032 verif\n let A;\n let R;\n let s;\n let SB;\n let hashable = Uint8Array.of();\n try {\n A = Point.fromHex(pub, zip215); // public key A decoded\n R = Point.fromHex(sig.slice(0, L), zip215); // 0 <= R < 2^256: ZIP215 R can be >= P\n s = bytesToNumLE(sig.slice(L, L2)); // Decode second half as an integer S\n SB = G.multiply(s, false); // in the range 0 <= s < L\n hashable = concatBytes(R.toBytes(), A.toBytes(), msg); // dom2(F, C) || R || A || PH(M)\n }\n catch (error) { }\n const finish = (hashed) => {\n // k = SHA512(dom2(F, C) || R || A || PH(M))\n if (SB == null)\n return false; // false if try-catch catched an error\n if (!zip215 && A.isSmallOrder())\n return false; // false for SBS: Strongly Binding Signature\n const k = modL_LE(hashed); // decode in little-endian, modulo L\n const RkA = R.add(A.multiply(k, false)); // [8]R + [8][k]A'\n return RkA.add(SB.negate()).clearCofactor().is0(); // [8][S]B = [8]R + [8][k]A'\n };\n return { hashable, finish };\n};\n/** Verifies signature on message and public key. Async. Follows RFC8032 5.1.7. */\nconst verifyAsync = async (s, m, p, opts = veriOpts) => hashFinishA(_verify(s, m, p, opts));\n/** Verifies signature on message and public key. To use, set `hashes.sha512` first. Follows RFC8032 5.1.7. */\nconst verify = (s, m, p, opts = veriOpts) => hashFinishS(_verify(s, m, p, opts));\n/** Math, hex, byte helpers. Not in `utils` because utils share API with noble-curves. */\nconst etc = {\n sha512Async: async (...messages) => {\n const s = subtle();\n const m = concatBytes(...messages);\n return u8n(await s.digest('SHA-512', m.buffer));\n },\n sha512Sync: undefined,\n bytesToHex: bytesToHex,\n hexToBytes: hexToBytes,\n concatBytes: concatBytes,\n mod: M,\n invert: invert,\n randomBytes: randomBytes,\n};\n/** ed25519-specific key utilities. */\nconst utils = {\n getExtendedPublicKeyAsync: getExtendedPublicKeyAsync,\n getExtendedPublicKey: getExtendedPublicKey,\n randomPrivateKey: () => randomBytes(L),\n precompute: (w = 8, p = G) => {\n p.multiply(3n);\n w;\n return p;\n }, // no-op\n};\n// ## Precomputes\n// --------------\nconst W = 8; // W is window size\nconst scalarBits = 256;\nconst pwindows = Math.ceil(scalarBits / W) + 1; // 33 for W=8\nconst pwindowSize = 2 ** (W - 1); // 128 for W=8\nconst precompute = () => {\n const points = [];\n let p = G;\n let b = p;\n for (let w = 0; w < pwindows; w++) {\n b = p;\n points.push(b);\n for (let i = 1; i < pwindowSize; i++) {\n b = b.add(p);\n points.push(b);\n } // i=1, bc we skip 0\n p = b.double();\n }\n return points;\n};\nlet Gpows = undefined; // precomputes for base point G\n// const-time negate\nconst ctneg = (cnd, p) => {\n const n = p.negate();\n return cnd ? n : p;\n};\n/**\n * Precomputes give 12x faster getPublicKey(), 10x sign(), 2x verify() by\n * caching multiples of G (base point). Cache is stored in 32MB of RAM.\n * Any time `G.multiply` is done, precomputes are used.\n * Not used for getSharedSecret, which instead multiplies random pubkey `P.multiply`.\n *\n * w-ary non-adjacent form (wNAF) precomputation method is 10% slower than windowed method,\n * but takes 2x less RAM. RAM reduction is possible by utilizing `.subtract`.\n *\n * !! Precomputes can be disabled by commenting-out call of the wNAF() inside Point#multiply().\n */\nconst wNAF = (n) => {\n const comp = Gpows || (Gpows = precompute());\n let p = I;\n let f = G; // f must be G, or could become I in the end\n const pow_2_w = 2 ** W; // 256 for W=8\n const maxNum = pow_2_w; // 256 for W=8\n const mask = big(pow_2_w - 1); // 255 for W=8 == mask 0b11111111\n const shiftBy = big(W); // 8 for W=8\n for (let w = 0; w < pwindows; w++) {\n let wbits = Number(n & mask); // extract W bits.\n n >>= shiftBy; // shift number by W bits.\n if (wbits > pwindowSize) {\n wbits -= maxNum;\n n += 1n;\n } // split if bits > max: +224 => 256-32\n const off = w * pwindowSize;\n const offF = off; // offsets, evaluate both\n const offP = off + Math.abs(wbits) - 1;\n const isEven = w % 2 !== 0; // conditions, evaluate both\n const isNeg = wbits < 0;\n if (wbits === 0) {\n // off == I: can't add it. Adding random offF instead.\n f = f.add(ctneg(isEven, comp[offF])); // bits are 0: add garbage to fake point\n }\n else {\n p = p.add(ctneg(isNeg, comp[offP])); // bits are 1: add to result point\n }\n }\n return { p, f }; // return both real and fake points for JIT\n};\n// !! Remove the export to easily use in REPL / browser console\nexport { ed25519_CURVE as CURVE, etc, Point as ExtendedPoint, getPublicKey, getPublicKeyAsync, Point, sign, signAsync, utils, verify, verifyAsync, };\n","/**\n * HEY! <== SECRET KEY KOALA\n * |/ <== WOULD LIKE YOUR\n * ʕ·͡ᴥ·ʔ <== ATTENTION PLEASE\n *\n * Key material generated in this module must stay in this module. So long as the secrets cache and\n * the methods that interact with it are not exported from `@solana/webcrypto-ed25519-polyfill`,\n * accidental logging of the actual bytes of a secret key (eg. to the console, or to a remote\n * server) should not be possible.\n *\n * WARNING: This does not imply that the secrets cache is secure against supply-chain attacks.\n * Untrusted code in your JavaScript context can easily override `WeakMap.prototype.set` to steal\n * private keys as they are written to the cache, without alerting you to its presence or affecting\n * the regular operation of the cache.\n */\nimport { getPublicKeyAsync, signAsync, utils, verifyAsync } from \"@noble/ed25519\";\n\nconst PROHIBITED_KEY_USAGES = new Set<KeyUsage>([\n \"decrypt\",\n \"deriveBits\",\n \"deriveKey\",\n \"encrypt\",\n \"unwrapKey\",\n \"wrapKey\",\n]);\n\nconst ED25519_PKCS8_HEADER =\n // prettier-ignore\n [\n /**\n * PKCS#8 header\n */\n 0x30, // ASN.1 sequence tag\n 0x2e, // Length of sequence (46 more bytes)\n\n 0x02, // ASN.1 integer tag\n 0x01, // Length of integer\n 0x00, // Version number\n\n 0x30, // ASN.1 sequence tag\n 0x05, // Length of sequence\n 0x06, // ASN.1 object identifier tag\n 0x03, // Length of object identifier\n // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112\n 0x2b, // iso(1) / identified-organization(3) (The first node is multiplied by the decimal 40 and the result is added to the value of the second node)\n 0x65, // thawte(101)\n // Ed25519 identifier\n 0x70, // id-Ed25519(112)\n\n /**\n * Private key payload\n */\n 0x04, // ASN.1 octet string tag\n 0x22, // String length (34 more bytes)\n\n // Private key bytes as octet string\n 0x04, // ASN.1 octet string tag\n 0x20, // String length (32 bytes)\n ];\n\nfunction bufferSourceToUint8Array(data: BufferSource): Uint8Array {\n return data instanceof Uint8Array ? data : new Uint8Array(ArrayBuffer.isView(data) ? data.buffer : data);\n}\n\nlet storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT: WeakMap<CryptoKey, Uint8Array> | undefined;\n\n// Map of public key bytes. These are the result of calling `getPublicKey`\nlet publicKeyBytesStore: WeakMap<CryptoKey, Uint8Array> | undefined;\n\nfunction createKeyPairFromBytes(\n bytes: Uint8Array,\n extractable: boolean,\n keyUsages: readonly KeyUsage[],\n): CryptoKeyPair {\n const keyPair = createKeyPair_INTERNAL_ONLY_DO_NOT_EXPORT(extractable, keyUsages);\n const cache = (storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT ||= new WeakMap());\n cache.set(keyPair.privateKey, bytes);\n cache.set(keyPair.publicKey, bytes);\n return keyPair;\n}\n\nfunction createKeyPair_INTERNAL_ONLY_DO_NOT_EXPORT(\n extractable: boolean,\n keyUsages: readonly KeyUsage[],\n): CryptoKeyPair {\n if (keyUsages.length === 0) {\n throw new DOMException(\"Usages cannot be empty when creating a key.\", \"SyntaxError\");\n }\n if (keyUsages.some((usage) => PROHIBITED_KEY_USAGES.has(usage))) {\n throw new DOMException(\"Unsupported key usage for an Ed25519 key.\", \"SyntaxError\");\n }\n const base = {\n [Symbol.toStringTag]: \"CryptoKey\",\n algorithm: Object.freeze({ name: \"Ed25519\" }),\n };\n const privateKey = {\n ...base,\n extractable,\n type: \"private\",\n usages: Object.freeze(keyUsages.filter((usage) => usage === \"sign\")) as KeyUsage[],\n } as CryptoKey;\n const publicKey = {\n ...base,\n extractable: true,\n type: \"public\",\n usages: Object.freeze(keyUsages.filter((usage) => usage === \"verify\")) as KeyUsage[],\n } as CryptoKey;\n return Object.freeze({\n privateKey: Object.freeze(privateKey),\n publicKey: Object.freeze(publicKey),\n });\n}\n\nfunction getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key: CryptoKey): Uint8Array {\n const secretKeyBytes = storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT?.get(key);\n if (secretKeyBytes === undefined) {\n throw new Error(\"Could not find secret key material associated with this `CryptoKey`\");\n }\n return secretKeyBytes;\n}\n\nasync function getPublicKeyBytes(key: CryptoKey): Promise<Uint8Array> {\n // Try to find the key in the public key store first\n const publicKeyStore = (publicKeyBytesStore ||= new WeakMap());\n const fromPublicStore = publicKeyStore.get(key);\n if (fromPublicStore) return fromPublicStore;\n\n // If not available, get the key from the secrets store instead\n const publicKeyBytes = await getPublicKeyAsync(getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key));\n\n // Store the public key bytes in the public key store for next time\n publicKeyStore.set(key, publicKeyBytes);\n return publicKeyBytes;\n}\n\nfunction base64UrlEncode(bytes: Uint8Array): string {\n return btoa(Array.from(bytes, (b) => String.fromCharCode(b)).join(\"\"))\n .replace(/\\+/g, \"-\")\n .replace(/\\//g, \"_\")\n .replace(/=+$/, \"\");\n}\n\nfunction base64UrlDecode(value: string): Uint8Array {\n const m = value.length % 4;\n const base64Value = value\n .replace(/-/g, \"+\")\n .replace(/_/g, \"/\")\n .padEnd(value.length + (m === 0 ? 0 : 4 - m), \"=\");\n return Uint8Array.from(atob(base64Value), (c) => c.charCodeAt(0));\n}\n\nexport async function exportKeyPolyfill(format: \"jwk\", key: CryptoKey): Promise<JsonWebKey>;\nexport async function exportKeyPolyfill(format: KeyFormat, key: CryptoKey): Promise<ArrayBuffer>;\nexport async function exportKeyPolyfill(format: KeyFormat, key: CryptoKey): Promise<ArrayBuffer | JsonWebKey> {\n if (key.extractable === false) {\n throw new DOMException(\"key is not extractable\", \"InvalidAccessException\");\n }\n switch (format) {\n case \"raw\": {\n if (key.type !== \"public\") {\n throw new DOMException(`Unable to export a raw Ed25519 ${key.type} key`, \"InvalidAccessError\");\n }\n const publicKeyBytes = await getPublicKeyBytes(key);\n // @ts-expect-error\n return publicKeyBytes;\n }\n case \"pkcs8\": {\n if (key.type !== \"private\") {\n throw new DOMException(`Unable to export a pkcs8 Ed25519 ${key.type} key`, \"InvalidAccessError\");\n }\n const secretKeyBytes = getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key);\n // @ts-expect-error\n return new Uint8Array([...ED25519_PKCS8_HEADER, ...secretKeyBytes]);\n }\n case \"jwk\": {\n const publicKeyBytes = await getPublicKeyBytes(key);\n const base = {\n crv /* curve */: \"Ed25519\",\n ext /* extractable */: key.extractable,\n key_ops /* key operations */: key.usages,\n kty /* key type */: \"OKP\" /* octet key pair */,\n x /* public key x-coordinate (base64-URL encoded) */: base64UrlEncode(publicKeyBytes),\n };\n if (key.type === \"private\") {\n const secretKeyBytes = getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key);\n return Object.freeze({\n ...base,\n d /* private key (base64-URL encoded) */: base64UrlEncode(secretKeyBytes),\n });\n }\n return Object.freeze({ ...base });\n }\n default:\n throw new Error(`Exporting polyfilled Ed25519 keys in the \"${format}\" format is unimplemented`);\n }\n}\n\n/**\n * This function generates a key pair and stores the secret bytes associated with it in a\n * module-private cache. Instead of vending the actual secret bytes, it returns a `CryptoKeyPair`\n * that you can use with other methods in this package to produce signatures and derive public keys\n * associated with the secret.\n */\nexport function generateKeyPolyfill(extractable: boolean, keyUsages: readonly KeyUsage[]): CryptoKeyPair {\n const privateKeyBytes = utils.randomPrivateKey();\n const keyPair = createKeyPairFromBytes(privateKeyBytes, extractable, keyUsages);\n return keyPair;\n}\n\nexport function isPolyfilledKey(key: CryptoKey): boolean {\n return !!storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT?.has(key) || !!publicKeyBytesStore?.has(key);\n}\n\nexport async function signPolyfill(key: CryptoKey, data: BufferSource): Promise<ArrayBuffer> {\n if (key.type !== \"private\" || !key.usages.includes(\"sign\")) {\n throw new DOMException(\"Unable to use this key to sign\", \"InvalidAccessError\");\n }\n const privateKeyBytes = getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key);\n const payload = bufferSourceToUint8Array(data);\n const signature = await signAsync(payload, privateKeyBytes);\n // @ts-expect-error\n return signature;\n}\n\nexport async function verifyPolyfill(key: CryptoKey, signature: BufferSource, data: BufferSource): Promise<boolean> {\n if (key.type !== \"public\" || !key.usages.includes(\"verify\")) {\n throw new DOMException(\"Unable to use this key to verify\", \"InvalidAccessError\");\n }\n const publicKeyBytes = await getPublicKeyBytes(key);\n try {\n return await verifyAsync(bufferSourceToUint8Array(signature), bufferSourceToUint8Array(data), publicKeyBytes);\n } catch {\n return false;\n }\n}\n\nfunction assertValidKeyUsages(keyUsages: readonly KeyUsage[], type: \"private\" | \"public\") {\n const prohibitedKeyUses = new Set<KeyUsage>([\n ...((type === \"private\" ? [\"verify\"] : [\"sign\"]) as KeyUsage[]),\n ...PROHIBITED_KEY_USAGES,\n ]);\n if (keyUsages.some((usage) => prohibitedKeyUses.has(usage))) {\n throw new DOMException(\"Unsupported key usage for a Ed25519 key\", \"SyntaxError\");\n }\n}\n\nexport function importKeyPolyfill(\n format: \"jwk\",\n keyData: JsonWebKey,\n extractable: boolean,\n keyUsages: readonly KeyUsage[],\n): CryptoKey;\nexport function importKeyPolyfill(\n format: Exclude<KeyFormat, \"jwk\">,\n keyData: BufferSource,\n extractable: boolean,\n keyUsages: readonly KeyUsage[],\n): CryptoKey;\nexport function importKeyPolyfill(\n format: KeyFormat,\n keyData: BufferSource | JsonWebKey,\n extractable: boolean,\n keyUsages: readonly KeyUsage[],\n): CryptoKey {\n if (format === \"raw\") {\n const bytes = bufferSourceToUint8Array(keyData as BufferSource);\n assertValidKeyUsages(keyUsages, \"public\");\n if (bytes.length !== 32) {\n throw new DOMException(\"Ed25519 raw keys must be exactly 32-bytes\", \"DataError\");\n }\n const publicKey = {\n [Symbol.toStringTag]: \"CryptoKey\",\n algorithm: Object.freeze({ name: \"Ed25519\" }),\n extractable,\n type: \"public\",\n usages: Object.freeze(keyUsages.filter((usage) => usage === \"verify\")) as KeyUsage[],\n } as CryptoKey;\n\n const cache = (publicKeyBytesStore ||= new WeakMap());\n cache.set(publicKey, bytes);\n\n return publicKey;\n }\n\n if (format === \"pkcs8\") {\n const bytes = bufferSourceToUint8Array(keyData as BufferSource);\n assertValidKeyUsages(keyUsages, \"private\");\n // 48 bytes: 16-byte PKCS8 header + 32 byte secret key\n if (bytes.length !== 48) {\n throw new DOMException(\"Invalid keyData\", \"DataError\");\n }\n // Must start with exactly the Ed25519 pkcs8 header\n const header = bytes.slice(0, 16);\n if (!header.every((val, i) => val === ED25519_PKCS8_HEADER[i])) {\n throw new DOMException(\"Invalid keyData\", \"DataError\");\n }\n const secretKeyBytes = bytes.slice(16);\n\n const privateKey = {\n [Symbol.toStringTag]: \"CryptoKey\",\n algorithm: Object.freeze({ name: \"Ed25519\" }),\n extractable,\n type: \"private\",\n usages: Object.freeze(keyUsages.filter((usage) => usage === \"sign\")) as KeyUsage[],\n } as CryptoKey;\n\n const cache = (storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT ||= new WeakMap());\n cache.set(privateKey, secretKeyBytes);\n\n return privateKey;\n }\n\n if (format === \"jwk\") {\n const jwk = keyData as JsonWebKey;\n const type = \"d\" in jwk ? \"private\" : \"public\";\n assertValidKeyUsages(keyUsages, type);\n const keyOps = new Set(jwk.key_ops ?? []);\n const sameKeyUsages = keyUsages.length === keyOps.size && [...keyUsages].every((x) => keyOps.has(x));\n if (jwk.kty !== \"OKP\" || jwk.crv !== \"Ed25519\" || jwk.ext !== extractable || !sameKeyUsages) {\n throw new DOMException(\"Invalid Ed25519 JWK\", \"DataError\");\n }\n if (type === \"public\" && !jwk.x) {\n throw new DOMException(\"Ed25519 JWK is missing public key coordinates\", \"DataError\");\n }\n if (type === \"private\" && !jwk.d) {\n throw new DOMException(\"Ed25519 JWK is missing private key coordinates\", \"DataError\");\n }\n const usageToKeep = type === \"public\" ? \"verify\" : \"sign\";\n const key = Object.freeze({\n [Symbol.toStringTag]: \"CryptoKey\",\n algorithm: Object.freeze({ name: \"Ed25519\" }),\n extractable,\n type,\n usages: Object.freeze(keyUsages.filter((usage) => usage === usageToKeep)) as KeyUsage[],\n }) as CryptoKey;\n\n if (type === \"public\") {\n const cache = (publicKeyBytesStore ||= new WeakMap());\n cache.set(key, base64UrlDecode(jwk.x!));\n } else {\n const cache = (storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT ||= new WeakMap());\n cache.set(key, base64UrlDecode(jwk.d!));\n }\n\n return key;\n }\n\n throw new Error(`Importing Ed25519 keys in the \"${format}\" format is unimplemented`);\n}\n","import cryptoImpl from \"uncrypto\";\n\nimport {\n exportKeyPolyfill,\n generateKeyPolyfill,\n importKeyPolyfill,\n isPolyfilledKey,\n signPolyfill,\n verifyPolyfill,\n} from \"./secrets\";\n\nexport function install(): void {\n if (__NODEJS__) {\n /**\n * Node only sets the `crypto` global variable when run with `--experimental-global-webcrypto`.\n * Let's set it unconditionally here.\n */\n globalThis.crypto ||= cryptoImpl;\n }\n\n if (!__BROWSER__ || globalThis.isSecureContext) {\n /**\n * Create `crypto.subtle` if it doesn't exist.\n */\n const originalCryptoObject = (globalThis.crypto ||= {} as Crypto);\n const originalSubtleCrypto = ((originalCryptoObject as Crypto & { subtle: SubtleCrypto }).subtle ||=\n {} as SubtleCrypto);\n\n /**\n * Override `SubtleCrypto#exportKey`\n */\n const originalExportKey = originalSubtleCrypto.exportKey as SubtleCrypto[\"exportKey\"] | undefined;\n originalSubtleCrypto.exportKey = (async (...args: Parameters<SubtleCrypto[\"exportKey\"]>) => {\n const [_, key] = args;\n if (isPolyfilledKey(key)) {\n return await exportKeyPolyfill(...args);\n } else if (originalExportKey) {\n return await originalExportKey.apply(originalSubtleCrypto, args);\n } else {\n throw new TypeError(\"No native `exportKey` function exists to handle this call\");\n }\n }) as SubtleCrypto[\"exportKey\"];\n\n /**\n * Override `SubtleCrypto#generateKey`\n */\n const originalGenerateKey = originalSubtleCrypto.generateKey as SubtleCrypto[\"generateKey\"] | undefined;\n let originalGenerateKeySupportsEd25519: Promise<boolean> | boolean | undefined;\n originalSubtleCrypto.generateKey = (async (...args: Parameters<SubtleCrypto[\"generateKey\"]>) => {\n const [algorithm] = args;\n if (algorithm !== \"Ed25519\") {\n if (originalGenerateKey) {\n return await originalGenerateKey.apply(originalSubtleCrypto, args);\n } else {\n throw new TypeError(\"No native `generateKey` function exists to handle this call\");\n }\n }\n let optimisticallyGeneratedKeyPair;\n if (originalGenerateKeySupportsEd25519 === undefined) {\n originalGenerateKeySupportsEd25519 = new Promise((resolve) => {\n if (!originalGenerateKey) {\n resolve((originalGenerateKeySupportsEd25519 = false));\n return;\n }\n originalGenerateKey\n .apply(originalSubtleCrypto, args)\n .then((keyPair) => {\n if (__DEV__) {\n console.warn(\n \"`webcrypto-ed25519-polyfill` was installed in an \" +\n \"environment that supports Ed25519 key manipulation \" +\n \"natively. Falling back to the native implementation. \" +\n \"Consider installing this polyfill only in environments where \" +\n \"Ed25519 is not supported.\",\n );\n }\n if (originalSubtleCrypto.generateKey !== originalGenerateKey) {\n originalSubtleCrypto.generateKey = originalGenerateKey;\n }\n optimisticallyGeneratedKeyPair = keyPair;\n resolve((originalGenerateKeySupportsEd25519 = true));\n })\n .catch(() => {\n resolve((originalGenerateKeySupportsEd25519 = false));\n });\n });\n }\n if (\n typeof originalGenerateKeySupportsEd25519 === \"boolean\"\n ? originalGenerateKeySupportsEd25519\n : await originalGenerateKeySupportsEd25519\n ) {\n if (optimisticallyGeneratedKeyPair) {\n return optimisticallyGeneratedKeyPair;\n } else if (originalGenerateKey) {\n return await originalGenerateKey.apply(originalSubtleCrypto, args);\n } else {\n throw new TypeError(\"No native `generateKey` function exists to handle this call\");\n }\n } else {\n const [_, extractable, keyUsages] = args;\n return generateKeyPolyfill(extractable, keyUsages);\n }\n }) as SubtleCrypto[\"generateKey\"];\n\n /**\n * Override `SubtleCrypto#sign`\n */\n const originalSign = originalSubtleCrypto.sign as SubtleCrypto[\"sign\"] | undefined;\n originalSubtleCrypto.sign = (async (...args: Parameters<SubtleCrypto[\"sign\"]>) => {\n const [_, key] = args;\n if (isPolyfilledKey(key)) {\n const [_, ...rest] = args;\n return await signPolyfill(...rest);\n } else if (originalSign) {\n return await originalSign.apply(originalSubtleCrypto, args);\n } else {\n throw new TypeError(\"No native `sign` function exists to handle this call\");\n }\n }) as SubtleCrypto[\"sign\"];\n\n /**\n * Override `SubtleCrypto#verify`\n */\n const originalVerify = originalSubtleCrypto.verify as SubtleCrypto[\"verify\"] | undefined;\n originalSubtleCrypto.verify = (async (...args: Parameters<SubtleCrypto[\"verify\"]>) => {\n const [_, key] = args;\n if (isPolyfilledKey(key)) {\n const [_, ...rest] = args;\n return await verifyPolyfill(...rest);\n } else if (originalVerify) {\n return await originalVerify.apply(originalSubtleCrypto, args);\n } else {\n throw new TypeError(\"No native `verify` function exists to handle this call\");\n }\n }) as SubtleCrypto[\"verify\"];\n\n /**\n * Override `SubtleCrypto#importKey`\n */\n const originalImportKey = originalSubtleCrypto.importKey as SubtleCrypto[\"importKey\"] | undefined;\n let originalImportKeySupportsEd25519: Pro