@solana/webcrypto-ed25519-polyfill 2.0.0-experimental.5030000 → 2.0.0-experimental.5044844

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE CHANGED
@@ -1,4 +1,4 @@
1
- Copyright (c) 2018 Solana Labs, Inc
1
+ Copyright (c) 2023 Solana Labs, Inc
2
2
 
3
3
  Permission is hereby granted, free of charge, to any person obtaining
4
4
  a copy of this software and associated documentation files (the
@@ -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
+ [
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,18 +105,34 @@ 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) {
118
+ if (key.extractable === false) {
119
+ throw new DOMException("key is not extractable", "InvalidAccessException");
120
+ }
62
121
  switch (format) {
63
122
  case "raw": {
64
- if (key.extractable === false) {
65
- throw new DOMException("key is not extractable", "InvalidAccessException");
66
- }
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
  }
129
+ case "pkcs8": {
130
+ if (key.type !== "private") {
131
+ throw new DOMException(`Unable to export a pkcs8 Ed25519 ${key.type} key`, "InvalidAccessError");
132
+ }
133
+ const secretKeyBytes = getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key);
134
+ return new Uint8Array([...ED25519_PKCS8_HEADER, ...secretKeyBytes]);
135
+ }
73
136
  default:
74
137
  throw new Error(`Exporting polyfilled Ed25519 keys in the "${format}" format is unimplemented`);
75
138
  }
@@ -80,7 +143,7 @@ function generateKeyPolyfill(extractable, keyUsages) {
80
143
  return keyPair;
81
144
  }
82
145
  function isPolyfilledKey(key) {
83
- return !!storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT?.has(key);
146
+ return !!storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT?.has(key) || !!publicKeyBytesStore?.has(key);
84
147
  }
85
148
  function signPolyfill(key, data) {
86
149
  if (key.type !== "private" || !key.usages.includes("sign")) {
@@ -95,13 +158,58 @@ function verifyPolyfill(key, signature, data) {
95
158
  if (key.type !== "public" || !key.usages.includes("verify")) {
96
159
  throw new DOMException("Unable to use this key to verify", "InvalidAccessError");
97
160
  }
98
- const publicKeyBytes = ed25519.ed25519.getPublicKey(getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key));
161
+ const publicKeyBytes = getPublicKeyBytes(key);
99
162
  try {
100
163
  return ed25519.ed25519.verify(bufferSourceToUint8Array(signature), bufferSourceToUint8Array(data), publicKeyBytes);
101
164
  } catch {
102
165
  return false;
103
166
  }
104
167
  }
168
+ function importKeyPolyfill(format, keyData, extractable, keyUsages) {
169
+ const bytes = bufferSourceToUint8Array(keyData);
170
+ if (format === "raw") {
171
+ if (keyUsages.some((usage) => usage === "sign" || PROHIBITED_KEY_USAGES.has(usage))) {
172
+ throw new DOMException("Unsupported key usage for a Ed25519 key", "SyntaxError");
173
+ }
174
+ if (bytes.length !== 32) {
175
+ throw new DOMException("Ed25519 raw keys must be exactly 32-bytes", "DataError");
176
+ }
177
+ const publicKey = {
178
+ [Symbol.toStringTag]: "CryptoKey",
179
+ algorithm: Object.freeze({ name: "Ed25519" }),
180
+ extractable,
181
+ type: "public",
182
+ usages: Object.freeze(keyUsages.filter((usage) => usage === "verify"))
183
+ };
184
+ const cache = publicKeyBytesStore || (publicKeyBytesStore = /* @__PURE__ */ new WeakMap());
185
+ cache.set(publicKey, bytes);
186
+ return publicKey;
187
+ }
188
+ if (format === "pkcs8") {
189
+ if (keyUsages.some((usage) => usage === "verify" || PROHIBITED_KEY_USAGES.has(usage))) {
190
+ throw new DOMException("Unsupported key usage for a Ed25519 key", "SyntaxError");
191
+ }
192
+ if (bytes.length !== 48) {
193
+ throw new DOMException("Invalid keyData", "DataError");
194
+ }
195
+ const header = bytes.slice(0, 16);
196
+ if (!header.every((val, i) => val === ED25519_PKCS8_HEADER[i])) {
197
+ throw new DOMException("Invalid keyData", "DataError");
198
+ }
199
+ const secretKeyBytes = bytes.slice(16);
200
+ const privateKey = {
201
+ [Symbol.toStringTag]: "CryptoKey",
202
+ algorithm: Object.freeze({ name: "Ed25519" }),
203
+ extractable,
204
+ type: "private",
205
+ usages: Object.freeze(keyUsages.filter((usage) => usage === "sign"))
206
+ };
207
+ const cache = storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT || (storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT = /* @__PURE__ */ new WeakMap());
208
+ cache.set(privateKey, secretKeyBytes);
209
+ return privateKey;
210
+ }
211
+ throw new Error(`Importing Ed25519 keys in the "${format}" format is unimplemented`);
212
+ }
105
213
 
106
214
  // src/index.ts
107
215
  if (globalThis.isSecureContext) {
@@ -189,6 +297,53 @@ if (globalThis.isSecureContext) {
189
297
  throw new TypeError("No native `verify` function exists to handle this call");
190
298
  }
191
299
  };
300
+ const originalImportKey = originalSubtleCrypto.importKey;
301
+ let originalImportKeySupportsEd25519;
302
+ originalSubtleCrypto.importKey = async (...args) => {
303
+ const [format, keyData, algorithm] = args;
304
+ if (algorithm !== "Ed25519") {
305
+ if (originalImportKey) {
306
+ return await originalImportKey.apply(originalSubtleCrypto, args);
307
+ } else {
308
+ throw new TypeError("No native `importKey` function exists to handle this call");
309
+ }
310
+ }
311
+ let optimisticallyImportedKey;
312
+ if (originalImportKeySupportsEd25519 === void 0) {
313
+ originalImportKeySupportsEd25519 = new Promise((resolve) => {
314
+ if (!originalImportKey) {
315
+ resolve(originalImportKeySupportsEd25519 = false);
316
+ return;
317
+ }
318
+ originalImportKey.apply(originalSubtleCrypto, args).then((key) => {
319
+ if (__DEV__) {
320
+ console.warn(
321
+ "`@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."
322
+ );
323
+ }
324
+ if (originalSubtleCrypto.importKey !== originalImportKey) {
325
+ originalSubtleCrypto.importKey = originalImportKey;
326
+ }
327
+ optimisticallyImportedKey = key;
328
+ resolve(originalImportKeySupportsEd25519 = true);
329
+ }).catch(() => {
330
+ resolve(originalImportKeySupportsEd25519 = false);
331
+ });
332
+ });
333
+ }
334
+ if (typeof originalImportKey === "boolean" ? originalImportKeySupportsEd25519 : await originalImportKeySupportsEd25519) {
335
+ if (optimisticallyImportedKey) {
336
+ return optimisticallyImportedKey;
337
+ } else if (originalImportKey) {
338
+ return await originalImportKey.apply(originalSubtleCrypto, args);
339
+ } else {
340
+ throw new TypeError("No native `importKey` function exists to handle this call");
341
+ }
342
+ } else {
343
+ const [_format, _keyData, _algorithm, extractable, keyUsages] = args;
344
+ return importKeyPolyfill(format, keyData, extractable, keyUsages);
345
+ }
346
+ };
192
347
  }
193
348
  //# sourceMappingURL=out.js.map
194
349
  //# 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,EAC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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,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;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;AAAA,IAEQ;AAAA;AAAA,IACA;AAAA;AAAA;AAAA,IAEA;AAAA;AAAA;AAAA;AAAA;AAAA,IAKhB;AAAA;AAAA,IACA;AAAA;AAAA;AAAA,IAG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,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 [\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 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 = 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 = 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
+ [
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,18 +103,34 @@ 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) {
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 = 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
  }
@@ -78,7 +141,7 @@ function generateKeyPolyfill(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
146
  function signPolyfill(key, data) {
84
147
  if (key.type !== "private" || !key.usages.includes("sign")) {
@@ -93,13 +156,58 @@ 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 = getPublicKeyBytes(key);
97
160
  try {
98
161
  return ed25519.verify(bufferSourceToUint8Array(signature), bufferSourceToUint8Array(data), publicKeyBytes);
99
162
  } catch {
100
163
  return false;
101
164
  }
102
165
  }
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 || (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 || (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
+ }
103
211
 
104
212
  // src/index.ts
105
213
  if (globalThis.isSecureContext) {
@@ -187,6 +295,53 @@ if (globalThis.isSecureContext) {
187
295
  throw new TypeError("No native `verify` function exists to handle this call");
188
296
  }
189
297
  };
298
+ const originalImportKey = originalSubtleCrypto.importKey;
299
+ let originalImportKeySupportsEd25519;
300
+ originalSubtleCrypto.importKey = async (...args) => {
301
+ const [format, keyData, algorithm] = args;
302
+ if (algorithm !== "Ed25519") {
303
+ if (originalImportKey) {
304
+ return await originalImportKey.apply(originalSubtleCrypto, args);
305
+ } else {
306
+ throw new TypeError("No native `importKey` function exists to handle this call");
307
+ }
308
+ }
309
+ let optimisticallyImportedKey;
310
+ if (originalImportKeySupportsEd25519 === void 0) {
311
+ originalImportKeySupportsEd25519 = new Promise((resolve) => {
312
+ if (!originalImportKey) {
313
+ resolve(originalImportKeySupportsEd25519 = false);
314
+ return;
315
+ }
316
+ originalImportKey.apply(originalSubtleCrypto, args).then((key) => {
317
+ if (__DEV__) {
318
+ console.warn(
319
+ "`@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."
320
+ );
321
+ }
322
+ if (originalSubtleCrypto.importKey !== originalImportKey) {
323
+ originalSubtleCrypto.importKey = originalImportKey;
324
+ }
325
+ optimisticallyImportedKey = key;
326
+ resolve(originalImportKeySupportsEd25519 = true);
327
+ }).catch(() => {
328
+ resolve(originalImportKeySupportsEd25519 = false);
329
+ });
330
+ });
331
+ }
332
+ if (typeof originalImportKey === "boolean" ? originalImportKeySupportsEd25519 : await originalImportKeySupportsEd25519) {
333
+ if (optimisticallyImportedKey) {
334
+ return optimisticallyImportedKey;
335
+ } else if (originalImportKey) {
336
+ return await originalImportKey.apply(originalSubtleCrypto, args);
337
+ } else {
338
+ throw new TypeError("No native `importKey` function exists to handle this call");
339
+ }
340
+ } else {
341
+ const [_format, _keyData, _algorithm, extractable, keyUsages] = args;
342
+ return importKeyPolyfill(format, keyData, extractable, keyUsages);
343
+ }
344
+ };
190
345
  }
191
346
  //# sourceMappingURL=out.js.map
192
347
  //# 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;A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A,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;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;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;AAAA;AAEJ,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,MAAI,UAAU,KAAK,WAAS,sBAAsB,IAAI,KAAK,CAAC,GA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C,MAAI;AACJ,uBAAqB,YAAa,UAAU,SAAgD;AACxF,UAAM,CAAC,QAAQ,SAAS,SAAS,IAAI;AACrC,QAAI,cAAc,WAAW;AACzB,UAAI,mBAAmB;AACnB,eAAO,MAAM,kBAAkB,MAAM,sBAAsB,IAAI;AAAA,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 [\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 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 = 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 = 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"]}