@solana/webcrypto-ed25519-polyfill 2.0.0-experimental.f57da91 → 2.0.0-experimental.f5d64e6

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.
@@ -1,4 +1,4 @@
1
- import { ed25519 } from '@noble/curves/ed25519';
1
+ import { utils, signAsync, verifyAsync, getPublicKeyAsync } from '@noble/ed25519';
2
2
 
3
3
  // ../build-scripts/env-shim.ts
4
4
  var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")();
@@ -10,13 +10,60 @@ var PROHIBITED_KEY_USAGES = /* @__PURE__ */ new Set([
10
10
  "unwrapKey",
11
11
  "wrapKey"
12
12
  ]);
13
+ var ED25519_PKCS8_HEADER = (
14
+ // prettier-ignore
15
+ [
16
+ /**
17
+ * PKCS#8 header
18
+ */
19
+ 48,
20
+ // ASN.1 sequence tag
21
+ 46,
22
+ // Length of sequence (46 more bytes)
23
+ 2,
24
+ // ASN.1 integer tag
25
+ 1,
26
+ // Length of integer
27
+ 0,
28
+ // Version number
29
+ 48,
30
+ // ASN.1 sequence tag
31
+ 5,
32
+ // Length of sequence
33
+ 6,
34
+ // ASN.1 object identifier tag
35
+ 3,
36
+ // Length of object identifier
37
+ // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112
38
+ 43,
39
+ // 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)
40
+ 101,
41
+ // thawte(101)
42
+ // Ed25519 identifier
43
+ 112,
44
+ // id-Ed25519(112)
45
+ /**
46
+ * Private key payload
47
+ */
48
+ 4,
49
+ // ASN.1 octet string tag
50
+ 34,
51
+ // String length (34 more bytes)
52
+ // Private key bytes as octet string
53
+ 4,
54
+ // ASN.1 octet string tag
55
+ 32
56
+ // String length (32 bytes)
57
+ ]
58
+ );
13
59
  function bufferSourceToUint8Array(data) {
14
60
  return data instanceof Uint8Array ? data : new Uint8Array(ArrayBuffer.isView(data) ? data.buffer : data);
15
61
  }
16
62
  var storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT;
63
+ var publicKeyBytesStore;
17
64
  function createKeyPairFromBytes(bytes, extractable, keyUsages) {
18
65
  const keyPair = createKeyPair_INTERNAL_ONLY_DO_NOT_EXPORT(extractable, keyUsages);
19
- const cache = storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT || (storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT = /* @__PURE__ */ new WeakMap());
66
+ const cache = storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT ||= /* @__PURE__ */ new WeakMap();
20
67
  cache.set(keyPair.privateKey, bytes);
21
68
  cache.set(keyPair.publicKey, bytes);
22
69
  return keyPair;
@@ -56,60 +103,119 @@ function getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key) {
56
103
  }
57
104
  return secretKeyBytes;
58
105
  }
59
- function exportKeyPolyfill(format, key) {
106
+ async function getPublicKeyBytes(key) {
107
+ const publicKeyStore = publicKeyBytesStore ||= /* @__PURE__ */ new WeakMap();
108
+ const fromPublicStore = publicKeyStore.get(key);
109
+ if (fromPublicStore)
110
+ return fromPublicStore;
111
+ const publicKeyBytes = await getPublicKeyAsync(getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key));
112
+ publicKeyStore.set(key, publicKeyBytes);
113
+ return publicKeyBytes;
114
+ }
115
+ async function exportKeyPolyfill(format, key) {
116
+ if (key.extractable === false) {
117
+ throw new DOMException("key is not extractable", "InvalidAccessException");
118
+ }
60
119
  switch (format) {
61
120
  case "raw": {
62
- if (key.extractable === false) {
63
- throw new DOMException("key is not extractable", "InvalidAccessException");
64
- }
65
121
  if (key.type !== "public") {
66
122
  throw new DOMException(`Unable to export a raw Ed25519 ${key.type} key`, "InvalidAccessError");
67
123
  }
68
- const publicKeyBytes = ed25519.getPublicKey(getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key));
124
+ const publicKeyBytes = await getPublicKeyBytes(key);
69
125
  return publicKeyBytes;
70
126
  }
127
+ case "pkcs8": {
128
+ if (key.type !== "private") {
129
+ throw new DOMException(`Unable to export a pkcs8 Ed25519 ${key.type} key`, "InvalidAccessError");
130
+ }
131
+ const secretKeyBytes = getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key);
132
+ return new Uint8Array([...ED25519_PKCS8_HEADER, ...secretKeyBytes]);
133
+ }
71
134
  default:
72
135
  throw new Error(`Exporting polyfilled Ed25519 keys in the "${format}" format is unimplemented`);
73
136
  }
74
137
  }
75
138
  function generateKeyPolyfill(extractable, keyUsages) {
76
- const privateKeyBytes = ed25519.utils.randomPrivateKey();
139
+ const privateKeyBytes = utils.randomPrivateKey();
77
140
  const keyPair = createKeyPairFromBytes(privateKeyBytes, extractable, keyUsages);
78
141
  return keyPair;
79
142
  }
80
143
  function isPolyfilledKey(key) {
81
- return !!storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT?.has(key);
144
+ return !!storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT?.has(key) || !!publicKeyBytesStore?.has(key);
82
145
  }
83
- function signPolyfill(key, data) {
146
+ async function signPolyfill(key, data) {
84
147
  if (key.type !== "private" || !key.usages.includes("sign")) {
85
148
  throw new DOMException("Unable to use this key to sign", "InvalidAccessError");
86
149
  }
87
150
  const privateKeyBytes = getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key);
88
151
  const payload = bufferSourceToUint8Array(data);
89
- const signature = ed25519.sign(payload, privateKeyBytes);
152
+ const signature = await signAsync(payload, privateKeyBytes);
90
153
  return signature;
91
154
  }
92
- function verifyPolyfill(key, signature, data) {
155
+ async function verifyPolyfill(key, signature, data) {
93
156
  if (key.type !== "public" || !key.usages.includes("verify")) {
94
157
  throw new DOMException("Unable to use this key to verify", "InvalidAccessError");
95
158
  }
96
- const publicKeyBytes = ed25519.getPublicKey(getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key));
159
+ const publicKeyBytes = await getPublicKeyBytes(key);
97
160
  try {
98
- return ed25519.verify(bufferSourceToUint8Array(signature), bufferSourceToUint8Array(data), publicKeyBytes);
161
+ return await verifyAsync(bufferSourceToUint8Array(signature), bufferSourceToUint8Array(data), publicKeyBytes);
99
162
  } catch {
100
163
  return false;
101
164
  }
102
165
  }
103
-
104
- // src/index.ts
166
+ function importKeyPolyfill(format, keyData, extractable, keyUsages) {
167
+ const bytes = bufferSourceToUint8Array(keyData);
168
+ if (format === "raw") {
169
+ if (keyUsages.some((usage) => usage === "sign" || PROHIBITED_KEY_USAGES.has(usage))) {
170
+ throw new DOMException("Unsupported key usage for a Ed25519 key", "SyntaxError");
171
+ }
172
+ if (bytes.length !== 32) {
173
+ throw new DOMException("Ed25519 raw keys must be exactly 32-bytes", "DataError");
174
+ }
175
+ const publicKey = {
176
+ [Symbol.toStringTag]: "CryptoKey",
177
+ algorithm: Object.freeze({ name: "Ed25519" }),
178
+ extractable,
179
+ type: "public",
180
+ usages: Object.freeze(keyUsages.filter((usage) => usage === "verify"))
181
+ };
182
+ const cache = publicKeyBytesStore ||= /* @__PURE__ */ new WeakMap();
183
+ cache.set(publicKey, bytes);
184
+ return publicKey;
185
+ }
186
+ if (format === "pkcs8") {
187
+ if (keyUsages.some((usage) => usage === "verify" || PROHIBITED_KEY_USAGES.has(usage))) {
188
+ throw new DOMException("Unsupported key usage for a Ed25519 key", "SyntaxError");
189
+ }
190
+ if (bytes.length !== 48) {
191
+ throw new DOMException("Invalid keyData", "DataError");
192
+ }
193
+ const header = bytes.slice(0, 16);
194
+ if (!header.every((val, i) => val === ED25519_PKCS8_HEADER[i])) {
195
+ throw new DOMException("Invalid keyData", "DataError");
196
+ }
197
+ const secretKeyBytes = bytes.slice(16);
198
+ const privateKey = {
199
+ [Symbol.toStringTag]: "CryptoKey",
200
+ algorithm: Object.freeze({ name: "Ed25519" }),
201
+ extractable,
202
+ type: "private",
203
+ usages: Object.freeze(keyUsages.filter((usage) => usage === "sign"))
204
+ };
205
+ const cache = storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT ||= /* @__PURE__ */ new WeakMap();
206
+ cache.set(privateKey, secretKeyBytes);
207
+ return privateKey;
208
+ }
209
+ throw new Error(`Importing Ed25519 keys in the "${format}" format is unimplemented`);
210
+ }
105
211
  {
106
- const originalCryptoObject = globalThis.crypto || (globalThis.crypto = {});
107
- const originalSubtleCrypto = originalCryptoObject.subtle || (originalCryptoObject.subtle = {});
212
+ const originalCryptoObject = globalThis.crypto ||= {};
213
+ const originalSubtleCrypto = originalCryptoObject.subtle ||= {};
108
214
  const originalExportKey = originalSubtleCrypto.exportKey;
109
215
  originalSubtleCrypto.exportKey = async (...args) => {
110
216
  const [_, key] = args;
111
217
  if (isPolyfilledKey(key)) {
112
- return exportKeyPolyfill(...args);
218
+ return await exportKeyPolyfill(...args);
113
219
  } else if (originalExportKey) {
114
220
  return await originalExportKey.apply(originalSubtleCrypto, args);
115
221
  } else {
@@ -168,7 +274,7 @@ function verifyPolyfill(key, signature, data) {
168
274
  const [_, key] = args;
169
275
  if (isPolyfilledKey(key)) {
170
276
  const [_2, ...rest] = args;
171
- return signPolyfill(...rest);
277
+ return await signPolyfill(...rest);
172
278
  } else if (originalSign) {
173
279
  return await originalSign.apply(originalSubtleCrypto, args);
174
280
  } else {
@@ -180,13 +286,60 @@ function verifyPolyfill(key, signature, data) {
180
286
  const [_, key] = args;
181
287
  if (isPolyfilledKey(key)) {
182
288
  const [_2, ...rest] = args;
183
- return verifyPolyfill(...rest);
289
+ return await verifyPolyfill(...rest);
184
290
  } else if (originalVerify) {
185
291
  return await originalVerify.apply(originalSubtleCrypto, args);
186
292
  } else {
187
293
  throw new TypeError("No native `verify` function exists to handle this call");
188
294
  }
189
295
  };
296
+ const originalImportKey = originalSubtleCrypto.importKey;
297
+ let originalImportKeySupportsEd25519;
298
+ originalSubtleCrypto.importKey = async (...args) => {
299
+ const [format, keyData, algorithm] = args;
300
+ if (algorithm !== "Ed25519") {
301
+ if (originalImportKey) {
302
+ return await originalImportKey.apply(originalSubtleCrypto, args);
303
+ } else {
304
+ throw new TypeError("No native `importKey` function exists to handle this call");
305
+ }
306
+ }
307
+ let optimisticallyImportedKey;
308
+ if (originalImportKeySupportsEd25519 === void 0) {
309
+ originalImportKeySupportsEd25519 = new Promise((resolve) => {
310
+ if (!originalImportKey) {
311
+ resolve(originalImportKeySupportsEd25519 = false);
312
+ return;
313
+ }
314
+ originalImportKey.apply(originalSubtleCrypto, args).then((key) => {
315
+ if (__DEV__) {
316
+ console.warn(
317
+ "`@solana/webcrypto-ed25519-polyfill` was included in an environment that supports Ed25519 key manipulation natively. Falling back to the native implementation. Consider including this polyfill only in environments where Ed25519 is not supported."
318
+ );
319
+ }
320
+ if (originalSubtleCrypto.importKey !== originalImportKey) {
321
+ originalSubtleCrypto.importKey = originalImportKey;
322
+ }
323
+ optimisticallyImportedKey = key;
324
+ resolve(originalImportKeySupportsEd25519 = true);
325
+ }).catch(() => {
326
+ resolve(originalImportKeySupportsEd25519 = false);
327
+ });
328
+ });
329
+ }
330
+ if (typeof originalImportKey === "boolean" ? originalImportKeySupportsEd25519 : await originalImportKeySupportsEd25519) {
331
+ if (optimisticallyImportedKey) {
332
+ return optimisticallyImportedKey;
333
+ } else if (originalImportKey) {
334
+ return await originalImportKey.apply(originalSubtleCrypto, args);
335
+ } else {
336
+ throw new TypeError("No native `importKey` function exists to handle this call");
337
+ }
338
+ } else {
339
+ const [_format, _keyData, _algorithm, extractable, keyUsages] = args;
340
+ return importKeyPolyfill(format, keyData, extractable, keyUsages);
341
+ }
342
+ };
190
343
  }
191
344
  //# sourceMappingURL=out.js.map
192
345
  //# sourceMappingURL=index.native.js.map
@@ -1 +1 @@
1
- {"version":3,"sources":["../../build-scripts/env-shim.ts","../src/secrets.ts","../src/index.ts"],"names":["_"],"mappings":";AACO,IAAM,UAA2B,uBAAO,QAAgB,KAAU,EAAE,aAAa,eAAe;;;ACc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BAAS,qCAAqC,IAAK;AAAA,QACvD,CAAC,EACA,MAAM,MAAM;AACT,kBAAS,qCAAqC,KAAM;AAAA,QACxD,CAAC;AAAA,MACT,CAAC;AAAA,IACL;AACA,QACI,OAAO,uCAAuC,YACxC,qCACA,MAAM,oCACd;AACE,UAAI,gCAAgC;AAChC,eAAO;AAAA,MACX,WAAW,qBAAqB;AAC5B,eAAO,MAAM,oBAAoB,MAAM,sBAAsB,IAAI;AAAA,MACrE,OAAO;AACH,cAAM,IAAI,UAAU,6DAA6D;AAAA,MACrF;AAAA,IACJ,OAAO;AACH,YAAM,CAAC,GAAG,aAAa,SAAS,IAAI;AACpC,aAAO,oBAAoB,aAAa,SAAS;AAAA,IACrD;AAAA,EACJ;AAKA,QAAM,eAAe,qBAAqB;AAC1C,uBAAqB,OAAQ,UAAU,SAA2C;AAC9E,UAAM,CAAC,GAAG,GAAG,IAAI;AACjB,QAAI,gBAAgB,GAAG,GAAG;AACtB,YAAM,CAACA,IAAG,GAAG,IAAI,IAAI;AACrB,aAAO,aAAa,GAAG,IAAI;AAAA,IAC/B,WAAW,cAAc;AACrB,aAAO,MAAM,aAAa,MAAM,sBAAsB,IAAI;AAAA,IAC9D,OAAO;AACH,YAAM,IAAI,UAAU,sDAAsD;AAAA,IAC9E;AAAA,EACJ;AAKA,QAAM,iBAAiB,qBAAqB;AAC5C,uBAAqB,SAAU,UAAU,SAA6C;AAClF,UAAM,CAAC,GAAG,GAAG,IAAI;AACjB,QAAI,gBAAgB,GAAG,GAAG;AACtB,YAAM,CAACA,IAAG,GAAG,IAAI,IAAI;AACrB,aAAO,eAAe,GAAG,IAAI;AAAA,IACjC,WAAW,gBAAgB;AACvB,aAAO,MAAM,eAAe,MAAM,sBAAsB,IAAI;AAAA,IAChE,OAAO;AACH,YAAM,IAAI,UAAU,wDAAwD;AAAA,IAChF;AAAA,EACJ;AACJ","sourcesContent":["// Clever obfuscation to prevent the build system from inlining the value of `NODE_ENV`\nexport const __DEV__ = /* @__PURE__ */ (() => (process as any)['en' + 'v'].NODE_ENV === 'development')();\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 { ed25519 } from '@noble/curves/ed25519';\n\nconst PROHIBITED_KEY_USAGES = new Set<KeyUsage>([\n 'decrypt',\n 'deriveBits',\n 'deriveKey',\n 'encrypt',\n 'unwrapKey',\n 'wrapKey',\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;\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 // TODO: Coded error.\n throw new Error('Could not find secret key material associated with this `CryptoKey`');\n }\n return secretKeyBytes;\n}\n\nexport function exportKeyPolyfill(format: 'jwk', key: CryptoKey): JsonWebKey;\nexport function exportKeyPolyfill(format: KeyFormat, key: CryptoKey): ArrayBuffer;\nexport function exportKeyPolyfill(format: KeyFormat, key: CryptoKey): ArrayBuffer | JsonWebKey {\n switch (format) {\n case 'raw': {\n if (key.extractable === false) {\n throw new DOMException('key is not extractable', 'InvalidAccessException');\n }\n if (key.type !== 'public') {\n throw new DOMException(`Unable to export a raw Ed25519 ${key.type} key`, 'InvalidAccessError');\n }\n const publicKeyBytes = ed25519.getPublicKey(getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key));\n return publicKeyBytes;\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 = ed25519.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);\n}\n\nexport function signPolyfill(key: CryptoKey, data: BufferSource): 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 = ed25519.sign(payload, privateKeyBytes);\n return signature;\n}\n\nexport function verifyPolyfill(key: CryptoKey, signature: BufferSource, data: BufferSource): 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 = ed25519.getPublicKey(getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key));\n try {\n return ed25519.verify(bufferSourceToUint8Array(signature), bufferSourceToUint8Array(data), publicKeyBytes);\n } catch {\n return false;\n }\n}\n","import { exportKeyPolyfill, generateKeyPolyfill, isPolyfilledKey, signPolyfill, verifyPolyfill } from './secrets';\n\nif (!__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 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 '`@solana/webcrypto-ed25519-polyfill` was included in an ' +\n 'environment that supports Ed25519 key manipulation ' +\n 'natively. Falling back to the native implementation. ' +\n 'Consider including 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 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 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"]}
1
+ {"version":3,"sources":["../../build-scripts/env-shim.ts","../src/secrets.ts","../src/index.ts"],"names":["_"],"mappings":";AACO,IAAM,UAA2B,uBAAO,QAAgB,KAAU,EAAE,aAAa,eAAe;;;ACcvG,SAAS,mBAAmB,WAAW,OAAO,mBAAmB;AAEjE,IAAM,wBAAwB,oBAAI,IAAc;AAAA,EAC5C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ,CAAC;AAED,IAAM;AAAA;AAAA,EAEF;AAAA;AAAA;AAAA;AAAA,IAII;AAAA;AAAA,IACA;AAAA;AAAA,IAEI;AAAA;AAAA,IACA;AAAA;AAAA,IACI;AAAA;AAAA,IAEJ;AAAA;AAAA,IACA;AAAA;AAAA,IACI;AAAA;AAAA,IACA;AAAA;AAAA;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A,cAAI,qBAAqB,cAAc,mBAAmB;AACtD,iCAAqB,YAAY;AAAA,UACrC;AACA,sCAA4B;AAC5B,kBAAS,mCAAmC,IAAK;AAAA,QACrD,CAAC,EACA,MAAM,MAAM;AACT,kBAAS,mCAAmC,KAAM;AAAA,QACtD,CAAC;AAAA,MACT,CAAC;AAAA,IACL;AACA,QACI,OAAO,sBAAsB,YACvB,mCACA,MAAM,kCACd;AACE,UAAI,2BAA2B;AAC3B,eAAO;AAAA,MACX,WAAW,mBAAmB;AAC1B,eAAO,MAAM,kBAAkB,MAAM,sBAAsB,IAAI;AAAA,MACnE,OAAO;AACH,cAAM,IAAI,UAAU,2DAA2D;AAAA,MACnF;AAAA,IACJ,OAAO;AACH,YAAM,CAAC,SAAS,UAAU,YAAY,aAAa,SAAS,IAAI;AAChE,aAAO,kBAAkB,QAAQ,SAAS,aAAa,SAAS;AAAA,IACpE;AAAA,EACJ;AACJ","sourcesContent":["// Clever obfuscation to prevent the build system from inlining the value of `NODE_ENV`\nexport const __DEV__ = /* @__PURE__ */ (() => (process as any)['en' + 'v'].NODE_ENV === 'development')();\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 // TODO: Coded error.\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\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 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 return new Uint8Array([...ED25519_PKCS8_HEADER, ...secretKeyBytes]);\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 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\nexport function importKeyPolyfill(\n format: KeyFormat,\n keyData: BufferSource,\n extractable: boolean,\n keyUsages: readonly KeyUsage[],\n): CryptoKey {\n const bytes = bufferSourceToUint8Array(keyData);\n\n if (format === 'raw') {\n if (keyUsages.some(usage => usage === 'sign' || PROHIBITED_KEY_USAGES.has(usage))) {\n throw new DOMException('Unsupported key usage for a Ed25519 key', 'SyntaxError');\n }\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 if (keyUsages.some(usage => usage === 'verify' || PROHIBITED_KEY_USAGES.has(usage))) {\n throw new DOMException('Unsupported key usage for a Ed25519 key', 'SyntaxError');\n }\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 throw new Error(`Importing Ed25519 keys in the \"${format}\" format is unimplemented`);\n}\n","import cryptoImpl from 'crypto-impl';\n\nimport {\n exportKeyPolyfill,\n generateKeyPolyfill,\n importKeyPolyfill,\n isPolyfilledKey,\n signPolyfill,\n verifyPolyfill,\n} from './secrets';\n\nif (__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\nif (!__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 '`@solana/webcrypto-ed25519-polyfill` was included in an ' +\n 'environment that supports Ed25519 key manipulation ' +\n 'natively. Falling back to the native implementation. ' +\n 'Consider including 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: Promise<boolean> | boolean | undefined;\n originalSubtleCrypto.importKey = (async (...args: Parameters<SubtleCrypto['importKey']>) => {\n const [format, keyData, algorithm] = args;\n if (algorithm !== 'Ed25519') {\n if (originalImportKey) {\n return await originalImportKey.apply(originalSubtleCrypto, args);\n } else {\n throw new TypeError('No native `importKey` function exists to handle this call');\n }\n }\n let optimisticallyImportedKey;\n if (originalImportKeySupportsEd25519 === undefined) {\n originalImportKeySupportsEd25519 = new Promise(resolve => {\n if (!originalImportKey) {\n resolve((originalImportKeySupportsEd25519 = false));\n return;\n }\n originalImportKey\n .apply(originalSubtleCrypto, args)\n .then(key => {\n if (__DEV__) {\n console.warn(\n '`@solana/webcrypto-ed25519-polyfill` was included in an ' +\n 'environment that supports Ed25519 key manipulation ' +\n 'natively. Falling back to the native implementation. ' +\n 'Consider including this polyfill only in environments where ' +\n 'Ed25519 is not supported.',\n );\n }\n if (originalSubtleCrypto.importKey !== originalImportKey) {\n originalSubtleCrypto.importKey = originalImportKey;\n }\n optimisticallyImportedKey = key;\n resolve((originalImportKeySupportsEd25519 = true));\n })\n .catch(() => {\n resolve((originalImportKeySupportsEd25519 = false));\n });\n });\n }\n if (\n typeof originalImportKey === 'boolean'\n ? originalImportKeySupportsEd25519\n : await originalImportKeySupportsEd25519\n ) {\n if (optimisticallyImportedKey) {\n return optimisticallyImportedKey;\n } else if (originalImportKey) {\n return await originalImportKey.apply(originalSubtleCrypto, args);\n } else {\n throw new TypeError('No native `importKey` function exists to handle this call');\n }\n } else {\n const [_format, _keyData, _algorithm, extractable, keyUsages] = args;\n return importKeyPolyfill(format, keyData, extractable, keyUsages);\n }\n }) as SubtleCrypto['importKey'];\n}\n"]}