@solana/webcrypto-ed25519-polyfill 2.0.0-experimental.572d28d → 2.0.0-experimental.58b1699

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.
@@ -12,10 +12,57 @@ var PROHIBITED_KEY_USAGES = /* @__PURE__ */ new Set([
12
12
  "unwrapKey",
13
13
  "wrapKey"
14
14
  ]);
15
+ var ED25519_PKCS8_HEADER = (
16
+ // prettier-ignore
17
+ new Uint8Array([
18
+ /**
19
+ * PKCS#8 header
20
+ */
21
+ 48,
22
+ // ASN.1 sequence tag
23
+ 46,
24
+ // Length of sequence (46 more bytes)
25
+ 2,
26
+ // ASN.1 integer tag
27
+ 1,
28
+ // Length of integer
29
+ 0,
30
+ // Version number
31
+ 48,
32
+ // ASN.1 sequence tag
33
+ 5,
34
+ // Length of sequence
35
+ 6,
36
+ // ASN.1 object identifier tag
37
+ 3,
38
+ // Length of object identifier
39
+ // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112
40
+ 43,
41
+ // 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)
42
+ 101,
43
+ // thawte(101)
44
+ // Ed25519 identifier
45
+ 112,
46
+ // id-Ed25519(112)
47
+ /**
48
+ * Private key payload
49
+ */
50
+ 4,
51
+ // ASN.1 octet string tag
52
+ 34,
53
+ // String length (34 more bytes)
54
+ // Private key bytes as octet string
55
+ 4,
56
+ // ASN.1 octet string tag
57
+ 32
58
+ // String length (32 bytes)
59
+ ])
60
+ );
15
61
  function bufferSourceToUint8Array(data) {
16
62
  return data instanceof Uint8Array ? data : new Uint8Array(ArrayBuffer.isView(data) ? data.buffer : data);
17
63
  }
18
64
  var storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT;
65
+ var publicKeyBytesStore;
19
66
  function createKeyPairFromBytes(bytes, extractable, keyUsages) {
20
67
  const keyPair = createKeyPair_INTERNAL_ONLY_DO_NOT_EXPORT(extractable, keyUsages);
21
68
  const cache = storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT || (storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT = /* @__PURE__ */ new WeakMap());
@@ -58,6 +105,15 @@ function getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key) {
58
105
  }
59
106
  return secretKeyBytes;
60
107
  }
108
+ function getPublicKeyBytes(key) {
109
+ const publicKeyStore = publicKeyBytesStore || (publicKeyBytesStore = /* @__PURE__ */ new WeakMap());
110
+ const fromPublicStore = publicKeyStore.get(key);
111
+ if (fromPublicStore)
112
+ return fromPublicStore;
113
+ const publicKeyBytes = ed25519.ed25519.getPublicKey(getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key));
114
+ publicKeyStore.set(key, publicKeyBytes);
115
+ return publicKeyBytes;
116
+ }
61
117
  function exportKeyPolyfill(format, key) {
62
118
  switch (format) {
63
119
  case "raw": {
@@ -67,7 +123,7 @@ function exportKeyPolyfill(format, key) {
67
123
  if (key.type !== "public") {
68
124
  throw new DOMException(`Unable to export a raw Ed25519 ${key.type} key`, "InvalidAccessError");
69
125
  }
70
- const publicKeyBytes = ed25519.ed25519.getPublicKey(getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key));
126
+ const publicKeyBytes = getPublicKeyBytes(key);
71
127
  return publicKeyBytes;
72
128
  }
73
129
  default:
@@ -80,7 +136,7 @@ function generateKeyPolyfill(extractable, keyUsages) {
80
136
  return keyPair;
81
137
  }
82
138
  function isPolyfilledKey(key) {
83
- return !!storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT?.has(key);
139
+ return !!storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT?.has(key) || !!publicKeyBytesStore?.has(key);
84
140
  }
85
141
  function signPolyfill(key, data) {
86
142
  if (key.type !== "private" || !key.usages.includes("sign")) {
@@ -95,13 +151,58 @@ function verifyPolyfill(key, signature, data) {
95
151
  if (key.type !== "public" || !key.usages.includes("verify")) {
96
152
  throw new DOMException("Unable to use this key to verify", "InvalidAccessError");
97
153
  }
98
- const publicKeyBytes = ed25519.ed25519.getPublicKey(getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key));
154
+ const publicKeyBytes = getPublicKeyBytes(key);
99
155
  try {
100
156
  return ed25519.ed25519.verify(bufferSourceToUint8Array(signature), bufferSourceToUint8Array(data), publicKeyBytes);
101
157
  } catch {
102
158
  return false;
103
159
  }
104
160
  }
161
+ function importKeyPolyfill(format, keyData, extractable, keyUsages) {
162
+ const bytes = bufferSourceToUint8Array(keyData);
163
+ if (format === "raw") {
164
+ if (keyUsages.some((usage) => usage === "sign" || PROHIBITED_KEY_USAGES.has(usage))) {
165
+ throw new DOMException("Unsupported key usage for a Ed25519 key", "SyntaxError");
166
+ }
167
+ if (bytes.length !== 32) {
168
+ throw new DOMException("Ed25519 raw keys must be exactly 32-bytes", "DataError");
169
+ }
170
+ const publicKey = {
171
+ [Symbol.toStringTag]: "CryptoKey",
172
+ algorithm: Object.freeze({ name: "Ed25519" }),
173
+ extractable,
174
+ type: "public",
175
+ usages: Object.freeze(keyUsages.filter((usage) => usage === "verify"))
176
+ };
177
+ const cache = publicKeyBytesStore || (publicKeyBytesStore = /* @__PURE__ */ new WeakMap());
178
+ cache.set(publicKey, bytes);
179
+ return publicKey;
180
+ }
181
+ if (format === "pkcs8") {
182
+ if (keyUsages.some((usage) => usage === "verify" || PROHIBITED_KEY_USAGES.has(usage))) {
183
+ throw new DOMException("Unsupported key usage for a Ed25519 key", "SyntaxError");
184
+ }
185
+ if (bytes.length !== 48) {
186
+ throw new DOMException("Invalid keyData", "DataError");
187
+ }
188
+ const header = bytes.slice(0, 16);
189
+ if (!header.every((val, i) => val === ED25519_PKCS8_HEADER[i])) {
190
+ throw new DOMException("Invalid keyData", "DataError");
191
+ }
192
+ const secretKeyBytes = bytes.slice(16);
193
+ const privateKey = {
194
+ [Symbol.toStringTag]: "CryptoKey",
195
+ algorithm: Object.freeze({ name: "Ed25519" }),
196
+ extractable,
197
+ type: "private",
198
+ usages: Object.freeze(keyUsages.filter((usage) => usage === "sign"))
199
+ };
200
+ const cache = storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT || (storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT = /* @__PURE__ */ new WeakMap());
201
+ cache.set(privateKey, secretKeyBytes);
202
+ return privateKey;
203
+ }
204
+ throw new Error(`Importing Ed25519 keys in the "${format}" format is unimplemented`);
205
+ }
105
206
 
106
207
  // src/index.ts
107
208
  if (globalThis.isSecureContext) {
@@ -189,6 +290,53 @@ if (globalThis.isSecureContext) {
189
290
  throw new TypeError("No native `verify` function exists to handle this call");
190
291
  }
191
292
  };
293
+ const originalImportKey = originalSubtleCrypto.importKey;
294
+ let originalImportKeySupportsEd25519;
295
+ originalSubtleCrypto.importKey = async (...args) => {
296
+ const [format, keyData, algorithm] = args;
297
+ if (algorithm !== "Ed25519") {
298
+ if (originalImportKey) {
299
+ return await originalImportKey.apply(originalSubtleCrypto, args);
300
+ } else {
301
+ throw new TypeError("No native `importKey` function exists to handle this call");
302
+ }
303
+ }
304
+ let optimisticallyImportedKey;
305
+ if (originalImportKeySupportsEd25519 === void 0) {
306
+ originalImportKeySupportsEd25519 = new Promise((resolve) => {
307
+ if (!originalImportKey) {
308
+ resolve(originalImportKeySupportsEd25519 = false);
309
+ return;
310
+ }
311
+ originalImportKey.apply(originalSubtleCrypto, args).then((key) => {
312
+ if (__DEV__) {
313
+ console.warn(
314
+ "`@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."
315
+ );
316
+ }
317
+ if (originalSubtleCrypto.importKey !== originalImportKey) {
318
+ originalSubtleCrypto.importKey = originalImportKey;
319
+ }
320
+ optimisticallyImportedKey = key;
321
+ resolve(originalImportKeySupportsEd25519 = true);
322
+ }).catch(() => {
323
+ resolve(originalImportKeySupportsEd25519 = false);
324
+ });
325
+ });
326
+ }
327
+ if (typeof originalImportKey === "boolean" ? originalImportKeySupportsEd25519 : await originalImportKeySupportsEd25519) {
328
+ if (optimisticallyImportedKey) {
329
+ return optimisticallyImportedKey;
330
+ } else if (originalImportKey) {
331
+ return await originalImportKey.apply(originalSubtleCrypto, args);
332
+ } else {
333
+ throw new TypeError("No native `importKey` function exists to handle this call");
334
+ }
335
+ } else {
336
+ const [_format, _keyData, _algorithm, extractable, keyUsages] = args;
337
+ return importKeyPolyfill(format, keyData, extractable, keyUsages);
338
+ }
339
+ };
192
340
  }
193
341
  //# sourceMappingURL=out.js.map
194
342
  //# sourceMappingURL=index.browser.cjs.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;;;ACcvG,SAAS,eAAe;AAExB,IAAM,wBAAwB,oBAAI,IAAc;AAAA,EAC5C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ,CAAC;AAED,SAAS,yBAAyB,MAAgC;AAC9D,SAAO,gBAAgB,aAAa,OAAO,IAAI,WAAW,YAAY,OAAO,IAAI,IAAI,KAAK,SAAS,IAAI;AAC3G;AAEA,IAAI;AACJ,SAAS,uBACL,OACA,aACA,WACa;AACb,QAAM,UAAU,0CAA0C,aAAa,SAAS;AAChF,QAAM,QAAS,0GAAsD,oBAAI,QAAQ;AACjF,QAAM,IAAI,QAAQ,YAAY,KAAK;AACnC,QAAM,IAAI,QAAQ,WAAW,KAAK;AAClC,SAAO;AACX;AAEA,SAAS,0CACL,aACA,WACa;AACb,MAAI,UAAU,WAAW,GAAG;AACxB,UAAM,IAAI,aAAa,+CAA+C,aAAa;AAAA,EACvF;AACA,MAAI,UAAU,KAAK,WAAS,sBAAsB,IAAI,KAAK,CAAC,GAAG;AAC3D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;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,eAAe;AAExB,IAAM,wBAAwB,oBAAI,IAAc;AAAA,EAC5C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ,CAAC;AAED,IAAM;AAAA;AAAA,EAEF,IAAI,WAAW;AAAA;AAAA;AAAA;AAAA,IAIX;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;AAAA,IAEQ;AAAA;AAAA,IACA;AAAA;AAAA;AAAA,IAEA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKhB;AAAA;AAAA,IACA;AAAA;AAAA;AAAA,IAGI;AAAA;AAAA,IACA;AAAA;AAAA,EACR,CAAC;AAAA;AAEL,SAAS,yBAAyB,MAAgC;AAC9D,SAAO,gBAAgB,aAAa,OAAO,IAAI,WAAW,YAAY,OAAO,IAAI,IAAI,KAAK,SAAS,IAAI;AAC3G;AAEA,IAAI;AAGJ,IAAI;AAEJ,SAAS,uBACL,OACA,aACA,WACa;AACb,QAAM,UAAU,0CAA0C,aAAa,SAAS;AAChF,QAAM,QAAS,0GAAsD,oBAAI,QAAQ;AACjF,QAAM,IAAI,QAAQ,YAAY,KAAK;AACnC,QAAM,IAAI,QAAQ,WAAW,KAAK;AAClC,SAAO;AACX;AAEA,SAAS,0CACL,aACA,WACa;AACb,MAAI,UAAU,WAAW,GAAG;AACxB,UAAM,IAAI,aAAa,+CAA+C,aAAa;AAAA,EACvF;AACA,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AA,MACnE,OAAO;AACH,cAAM,IAAI,UAAU,2DAA2D;AAAA,MACnF;AAAA,IACJ;AACA,QAAI;AACJ,QAAI,qCAAqC,QAAW;AAChD,yCAAmC,IAAI,QAAQ,aAAW;AACtD,YAAI,CAAC,mBAAmB;AACpB,kBAAS,mCAAmC,KAAM;AAClD;AAAA,QACJ;AACA,0BACK,MAAM,sBAAsB,IAAI,EAChC,KAAK,SAAO;AACT,cAAI,SAAS;AACT,oBAAQ;AAAA,cACJ;AAAA,YAKJ;AAAA,UACJ;AACA,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 { 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\nconst ED25519_PKCS8_HEADER =\n // prettier-ignore\n new Uint8Array([\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 `ed25519.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\nfunction getPublicKeyBytes(key: CryptoKey): 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 = ed25519.getPublicKey(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 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 = getPublicKeyBytes(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) || !!publicKeyBytesStore?.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 = getPublicKeyBytes(key);\n try {\n return ed25519.verify(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 {\n exportKeyPolyfill,\n generateKeyPolyfill,\n importKeyPolyfill,\n isPolyfilledKey,\n signPolyfill,\n verifyPolyfill,\n} 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 /**\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"]}
@@ -10,10 +10,57 @@ var PROHIBITED_KEY_USAGES = /* @__PURE__ */ new Set([
10
10
  "unwrapKey",
11
11
  "wrapKey"
12
12
  ]);
13
+ var ED25519_PKCS8_HEADER = (
14
+ // prettier-ignore
15
+ new Uint8Array([
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
66
  const cache = storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT || (storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT = /* @__PURE__ */ new WeakMap());
@@ -56,6 +103,15 @@ function getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key) {
56
103
  }
57
104
  return secretKeyBytes;
58
105
  }
106
+ function getPublicKeyBytes(key) {
107
+ const publicKeyStore = publicKeyBytesStore || (publicKeyBytesStore = /* @__PURE__ */ new WeakMap());
108
+ const fromPublicStore = publicKeyStore.get(key);
109
+ if (fromPublicStore)
110
+ return fromPublicStore;
111
+ const publicKeyBytes = ed25519.getPublicKey(getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key));
112
+ publicKeyStore.set(key, publicKeyBytes);
113
+ return publicKeyBytes;
114
+ }
59
115
  function exportKeyPolyfill(format, key) {
60
116
  switch (format) {
61
117
  case "raw": {
@@ -65,7 +121,7 @@ function exportKeyPolyfill(format, key) {
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 = getPublicKeyBytes(key);
69
125
  return publicKeyBytes;
70
126
  }
71
127
  default:
@@ -78,7 +134,7 @@ function generateKeyPolyfill(extractable, keyUsages) {
78
134
  return keyPair;
79
135
  }
80
136
  function isPolyfilledKey(key) {
81
- return !!storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT?.has(key);
137
+ return !!storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT?.has(key) || !!publicKeyBytesStore?.has(key);
82
138
  }
83
139
  function signPolyfill(key, data) {
84
140
  if (key.type !== "private" || !key.usages.includes("sign")) {
@@ -93,13 +149,58 @@ function verifyPolyfill(key, signature, data) {
93
149
  if (key.type !== "public" || !key.usages.includes("verify")) {
94
150
  throw new DOMException("Unable to use this key to verify", "InvalidAccessError");
95
151
  }
96
- const publicKeyBytes = ed25519.getPublicKey(getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key));
152
+ const publicKeyBytes = getPublicKeyBytes(key);
97
153
  try {
98
154
  return ed25519.verify(bufferSourceToUint8Array(signature), bufferSourceToUint8Array(data), publicKeyBytes);
99
155
  } catch {
100
156
  return false;
101
157
  }
102
158
  }
159
+ function importKeyPolyfill(format, keyData, extractable, keyUsages) {
160
+ const bytes = bufferSourceToUint8Array(keyData);
161
+ if (format === "raw") {
162
+ if (keyUsages.some((usage) => usage === "sign" || PROHIBITED_KEY_USAGES.has(usage))) {
163
+ throw new DOMException("Unsupported key usage for a Ed25519 key", "SyntaxError");
164
+ }
165
+ if (bytes.length !== 32) {
166
+ throw new DOMException("Ed25519 raw keys must be exactly 32-bytes", "DataError");
167
+ }
168
+ const publicKey = {
169
+ [Symbol.toStringTag]: "CryptoKey",
170
+ algorithm: Object.freeze({ name: "Ed25519" }),
171
+ extractable,
172
+ type: "public",
173
+ usages: Object.freeze(keyUsages.filter((usage) => usage === "verify"))
174
+ };
175
+ const cache = publicKeyBytesStore || (publicKeyBytesStore = /* @__PURE__ */ new WeakMap());
176
+ cache.set(publicKey, bytes);
177
+ return publicKey;
178
+ }
179
+ if (format === "pkcs8") {
180
+ if (keyUsages.some((usage) => usage === "verify" || PROHIBITED_KEY_USAGES.has(usage))) {
181
+ throw new DOMException("Unsupported key usage for a Ed25519 key", "SyntaxError");
182
+ }
183
+ if (bytes.length !== 48) {
184
+ throw new DOMException("Invalid keyData", "DataError");
185
+ }
186
+ const header = bytes.slice(0, 16);
187
+ if (!header.every((val, i) => val === ED25519_PKCS8_HEADER[i])) {
188
+ throw new DOMException("Invalid keyData", "DataError");
189
+ }
190
+ const secretKeyBytes = bytes.slice(16);
191
+ const privateKey = {
192
+ [Symbol.toStringTag]: "CryptoKey",
193
+ algorithm: Object.freeze({ name: "Ed25519" }),
194
+ extractable,
195
+ type: "private",
196
+ usages: Object.freeze(keyUsages.filter((usage) => usage === "sign"))
197
+ };
198
+ const cache = storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT || (storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT = /* @__PURE__ */ new WeakMap());
199
+ cache.set(privateKey, secretKeyBytes);
200
+ return privateKey;
201
+ }
202
+ throw new Error(`Importing Ed25519 keys in the "${format}" format is unimplemented`);
203
+ }
103
204
 
104
205
  // src/index.ts
105
206
  if (globalThis.isSecureContext) {
@@ -187,6 +288,53 @@ if (globalThis.isSecureContext) {
187
288
  throw new TypeError("No native `verify` function exists to handle this call");
188
289
  }
189
290
  };
291
+ const originalImportKey = originalSubtleCrypto.importKey;
292
+ let originalImportKeySupportsEd25519;
293
+ originalSubtleCrypto.importKey = async (...args) => {
294
+ const [format, keyData, algorithm] = args;
295
+ if (algorithm !== "Ed25519") {
296
+ if (originalImportKey) {
297
+ return await originalImportKey.apply(originalSubtleCrypto, args);
298
+ } else {
299
+ throw new TypeError("No native `importKey` function exists to handle this call");
300
+ }
301
+ }
302
+ let optimisticallyImportedKey;
303
+ if (originalImportKeySupportsEd25519 === void 0) {
304
+ originalImportKeySupportsEd25519 = new Promise((resolve) => {
305
+ if (!originalImportKey) {
306
+ resolve(originalImportKeySupportsEd25519 = false);
307
+ return;
308
+ }
309
+ originalImportKey.apply(originalSubtleCrypto, args).then((key) => {
310
+ if (__DEV__) {
311
+ console.warn(
312
+ "`@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."
313
+ );
314
+ }
315
+ if (originalSubtleCrypto.importKey !== originalImportKey) {
316
+ originalSubtleCrypto.importKey = originalImportKey;
317
+ }
318
+ optimisticallyImportedKey = key;
319
+ resolve(originalImportKeySupportsEd25519 = true);
320
+ }).catch(() => {
321
+ resolve(originalImportKeySupportsEd25519 = false);
322
+ });
323
+ });
324
+ }
325
+ if (typeof originalImportKey === "boolean" ? originalImportKeySupportsEd25519 : await originalImportKeySupportsEd25519) {
326
+ if (optimisticallyImportedKey) {
327
+ return optimisticallyImportedKey;
328
+ } else if (originalImportKey) {
329
+ return await originalImportKey.apply(originalSubtleCrypto, args);
330
+ } else {
331
+ throw new TypeError("No native `importKey` function exists to handle this call");
332
+ }
333
+ } else {
334
+ const [_format, _keyData, _algorithm, extractable, keyUsages] = args;
335
+ return importKeyPolyfill(format, keyData, extractable, keyUsages);
336
+ }
337
+ };
190
338
  }
191
339
  //# sourceMappingURL=out.js.map
192
340
  //# sourceMappingURL=index.browser.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;;;ACcvG,SAAS,eAAe;AAExB,IAAM,wBAAwB,oBAAI,IAAc;AAAA,EAC5C;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACJ,CAAC;AAED,SAAS,yBAAyB,MAAgC;AAC9D,SAAO,gBAAgB,aAAa,OAAO,IAAI,WAAW,YAAY,OAAO,IAAI,IAAI,KAAK,SAAS,IAAI;AAC3G;AAEA,IAAI;AACJ,SAAS,uBACL,OACA,aACA,WACa;AACb,QAAM,UAAU,0CAA0C,aAAa,SAAS;AAChF,QAAM,QAAS,0GAAsD,oBAAI,QAAQ;AACjF,QAAM,IAAI,QAAQ,YAAY,KAAK;AACnC,QAAM,IAAI,QAAQ,WAAW,KAAK;AAClC,SAAO;AACX;AAEA,SAAS,0CACL,aACA,WACa;AACb,MAAI,UAAU,WAAW,GAAG;AACxB,UAAM,IAAI,aAAa,+CAA+C,aAAa;AAAA,EACvF;AACA,MAAI,UAAU,KAAK,WAAS,sBAAsB,IAAI,KAAK,CAAC,GAAG;AAC3D,UAAM,IAAI,aAAa,6CAA6C,aAAa;AAAA,EACrF;AACA,QAAM,OAAO;AAAA,IACT,CAAC,OAAO,WAAW,GAAG;AAA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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"]}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,QAAW;AAChD,yCAAmC,IAAI,QAAQ,aAAW;AACtD,YAAI,CAAC,mBAAmB;AACpB,kBAAS,mCAAmC,KAAM;AAClD;AAAA,QACJ;AACA,0BACK,MAAM,sBAAsB,IAAI,EAChC,KAAK,SAAO;AACT,cAAI,SAAS;AACT,oBAAQ;AAAA,cACJ;AAAA,YAKJ;AAAA,UACJ;AACA,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 { 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\nconst ED25519_PKCS8_HEADER =\n // prettier-ignore\n new Uint8Array([\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 `ed25519.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\nfunction getPublicKeyBytes(key: CryptoKey): 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 = ed25519.getPublicKey(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 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 = getPublicKeyBytes(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) || !!publicKeyBytesStore?.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 = getPublicKeyBytes(key);\n try {\n return ed25519.verify(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 {\n exportKeyPolyfill,\n generateKeyPolyfill,\n importKeyPolyfill,\n isPolyfilledKey,\n signPolyfill,\n verifyPolyfill,\n} 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 /**\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"]}