@solana/webcrypto-ed25519-polyfill 2.0.0-experimental.ce145c8 → 2.0.0-experimental.cee6f23

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,9 +1,431 @@
1
1
  'use strict';
2
2
 
3
- var ed25519 = require('@noble/curves/ed25519');
3
+ var o = require('crypto');
4
+
5
+ function _interopDefault (e) { return e && e.__esModule ? e : { default: e }; }
6
+
7
+ var o__default = /*#__PURE__*/_interopDefault(o);
4
8
 
5
9
  // ../build-scripts/env-shim.ts
6
10
  var __DEV__ = /* @__PURE__ */ (() => process["env"].NODE_ENV === "development")();
11
+ var t = o__default.default;
12
+
13
+ // ../../node_modules/.pnpm/@noble+ed25519@2.0.0/node_modules/@noble/ed25519/index.js
14
+ var P = 2n ** 255n - 19n;
15
+ var N = 2n ** 252n + 27742317777372353535851937790883648493n;
16
+ var Gx = 0x216936d3cd6e53fec0a4e231fdd6dc5c692cc7609525a7b2c9562d608f25d51an;
17
+ var Gy = 0x6666666666666666666666666666666666666666666666666666666666666658n;
18
+ var CURVE = {
19
+ a: -1n,
20
+ d: 37095705934669439343138083508754565189542113879843219016388785533085940283555n,
21
+ p: P,
22
+ n: N,
23
+ h: 8,
24
+ Gx,
25
+ Gy
26
+ // field prime, curve (group) order, cofactor
27
+ };
28
+ var err = (m = "") => {
29
+ throw new Error(m);
30
+ };
31
+ var str = (s) => typeof s === "string";
32
+ var au8 = (a, l) => (
33
+ // is Uint8Array (of specific length)
34
+ !(a instanceof Uint8Array) || typeof l === "number" && l > 0 && a.length !== l ? err("Uint8Array expected") : a
35
+ );
36
+ var u8n = (data) => new Uint8Array(data);
37
+ var toU8 = (a, len) => au8(str(a) ? h2b(a) : u8n(a), len);
38
+ var mod = (a, b = P) => {
39
+ let r = a % b;
40
+ return r >= 0n ? r : b + r;
41
+ };
42
+ var isPoint = (p) => p instanceof Point ? p : err("Point expected");
43
+ var Gpows = void 0;
44
+ var Point = class _Point {
45
+ constructor(ex, ey, ez, et) {
46
+ this.ex = ex;
47
+ this.ey = ey;
48
+ this.ez = ez;
49
+ this.et = et;
50
+ }
51
+ static fromAffine(p) {
52
+ return new _Point(p.x, p.y, 1n, mod(p.x * p.y));
53
+ }
54
+ static fromHex(hex, strict = true) {
55
+ const { d } = CURVE;
56
+ hex = toU8(hex, 32);
57
+ const normed = hex.slice();
58
+ normed[31] = hex[31] & ~128;
59
+ const y = b2n_LE(normed);
60
+ if (y === 0n) ; else {
61
+ if (strict && !(0n < y && y < P))
62
+ err("bad y coord 1");
63
+ if (!strict && !(0n < y && y < 2n ** 256n))
64
+ err("bad y coord 2");
65
+ }
66
+ const y2 = mod(y * y);
67
+ const u = mod(y2 - 1n);
68
+ const v = mod(d * y2 + 1n);
69
+ let { isValid, value: x } = uvRatio(u, v);
70
+ if (!isValid)
71
+ err("bad y coordinate 3");
72
+ const isXOdd = (x & 1n) === 1n;
73
+ const isHeadOdd = (hex[31] & 128) !== 0;
74
+ if (isHeadOdd !== isXOdd)
75
+ x = mod(-x);
76
+ return new _Point(x, y, 1n, mod(x * y));
77
+ }
78
+ get x() {
79
+ return this.toAffine().x;
80
+ }
81
+ // .x, .y will call expensive toAffine.
82
+ get y() {
83
+ return this.toAffine().y;
84
+ }
85
+ // Should be used with care.
86
+ equals(other) {
87
+ const { ex: X1, ey: Y1, ez: Z1 } = this;
88
+ const { ex: X2, ey: Y2, ez: Z2 } = isPoint(other);
89
+ const X1Z2 = mod(X1 * Z2), X2Z1 = mod(X2 * Z1);
90
+ const Y1Z2 = mod(Y1 * Z2), Y2Z1 = mod(Y2 * Z1);
91
+ return X1Z2 === X2Z1 && Y1Z2 === Y2Z1;
92
+ }
93
+ is0() {
94
+ return this.equals(I);
95
+ }
96
+ negate() {
97
+ return new _Point(mod(-this.ex), this.ey, this.ez, mod(-this.et));
98
+ }
99
+ double() {
100
+ const { ex: X1, ey: Y1, ez: Z1 } = this;
101
+ const { a } = CURVE;
102
+ const A = mod(X1 * X1);
103
+ const B = mod(Y1 * Y1);
104
+ const C = mod(2n * mod(Z1 * Z1));
105
+ const D = mod(a * A);
106
+ const x1y1 = X1 + Y1;
107
+ const E = mod(mod(x1y1 * x1y1) - A - B);
108
+ const G2 = D + B;
109
+ const F = G2 - C;
110
+ const H = D - B;
111
+ const X3 = mod(E * F);
112
+ const Y3 = mod(G2 * H);
113
+ const T3 = mod(E * H);
114
+ const Z3 = mod(F * G2);
115
+ return new _Point(X3, Y3, Z3, T3);
116
+ }
117
+ add(other) {
118
+ const { ex: X1, ey: Y1, ez: Z1, et: T1 } = this;
119
+ const { ex: X2, ey: Y2, ez: Z2, et: T2 } = isPoint(other);
120
+ const { a, d } = CURVE;
121
+ const A = mod(X1 * X2);
122
+ const B = mod(Y1 * Y2);
123
+ const C = mod(T1 * d * T2);
124
+ const D = mod(Z1 * Z2);
125
+ const E = mod((X1 + Y1) * (X2 + Y2) - A - B);
126
+ const F = mod(D - C);
127
+ const G2 = mod(D + C);
128
+ const H = mod(B - a * A);
129
+ const X3 = mod(E * F);
130
+ const Y3 = mod(G2 * H);
131
+ const T3 = mod(E * H);
132
+ const Z3 = mod(F * G2);
133
+ return new _Point(X3, Y3, Z3, T3);
134
+ }
135
+ mul(n, safe = true) {
136
+ if (n === 0n)
137
+ return safe === true ? err("cannot multiply by 0") : I;
138
+ if (!(typeof n === "bigint" && 0n < n && n < N))
139
+ err("invalid scalar, must be < L");
140
+ if (!safe && this.is0() || n === 1n)
141
+ return this;
142
+ if (this.equals(G))
143
+ return wNAF(n).p;
144
+ let p = I, f = G;
145
+ for (let d = this; n > 0n; d = d.double(), n >>= 1n) {
146
+ if (n & 1n)
147
+ p = p.add(d);
148
+ else if (safe)
149
+ f = f.add(d);
150
+ }
151
+ return p;
152
+ }
153
+ multiply(scalar) {
154
+ return this.mul(scalar);
155
+ }
156
+ // Aliases for compatibilty
157
+ clearCofactor() {
158
+ return this.mul(BigInt(CURVE.h), false);
159
+ }
160
+ // multiply by cofactor
161
+ isSmallOrder() {
162
+ return this.clearCofactor().is0();
163
+ }
164
+ // check if P is small order
165
+ isTorsionFree() {
166
+ let p = this.mul(N / 2n, false).double();
167
+ if (N % 2n)
168
+ p = p.add(this);
169
+ return p.is0();
170
+ }
171
+ toAffine() {
172
+ const { ex: x, ey: y, ez: z } = this;
173
+ if (this.is0())
174
+ return { x: 0n, y: 0n };
175
+ const iz = invert(z);
176
+ if (mod(z * iz) !== 1n)
177
+ err("invalid inverse");
178
+ return { x: mod(x * iz), y: mod(y * iz) };
179
+ }
180
+ toRawBytes() {
181
+ const { x, y } = this.toAffine();
182
+ const b = n2b_32LE(y);
183
+ b[31] |= x & 1n ? 128 : 0;
184
+ return b;
185
+ }
186
+ toHex() {
187
+ return b2h(this.toRawBytes());
188
+ }
189
+ // encode to hex string
190
+ };
191
+ Point.BASE = new Point(Gx, Gy, 1n, mod(Gx * Gy));
192
+ Point.ZERO = new Point(0n, 1n, 1n, 0n);
193
+ var { BASE: G, ZERO: I } = Point;
194
+ var padh = (num, pad) => num.toString(16).padStart(pad, "0");
195
+ var b2h = (b) => Array.from(b).map((e) => padh(e, 2)).join("");
196
+ var h2b = (hex) => {
197
+ const l = hex.length;
198
+ if (!str(hex) || l % 2)
199
+ err("hex invalid 1");
200
+ const arr = u8n(l / 2);
201
+ for (let i = 0; i < arr.length; i++) {
202
+ const j = i * 2;
203
+ const h = hex.slice(j, j + 2);
204
+ const b = Number.parseInt(h, 16);
205
+ if (Number.isNaN(b) || b < 0)
206
+ err("hex invalid 2");
207
+ arr[i] = b;
208
+ }
209
+ return arr;
210
+ };
211
+ var n2b_32LE = (num) => h2b(padh(num, 32 * 2)).reverse();
212
+ var b2n_LE = (b) => BigInt("0x" + b2h(u8n(au8(b)).reverse()));
213
+ var concatB = (...arrs) => {
214
+ const r = u8n(arrs.reduce((sum, a) => sum + au8(a).length, 0));
215
+ let pad = 0;
216
+ arrs.forEach((a) => {
217
+ r.set(a, pad);
218
+ pad += a.length;
219
+ });
220
+ return r;
221
+ };
222
+ var invert = (num, md = P) => {
223
+ if (num === 0n || md <= 0n)
224
+ err("no inverse n=" + num + " mod=" + md);
225
+ let a = mod(num, md), b = md, x = 0n, u = 1n;
226
+ while (a !== 0n) {
227
+ const q = b / a, r = b % a;
228
+ const m = x - u * q;
229
+ b = a, a = r, x = u, u = m;
230
+ }
231
+ return b === 1n ? mod(x, md) : err("no inverse");
232
+ };
233
+ var pow2 = (x, power) => {
234
+ let r = x;
235
+ while (power-- > 0n) {
236
+ r *= r;
237
+ r %= P;
238
+ }
239
+ return r;
240
+ };
241
+ var pow_2_252_3 = (x) => {
242
+ const x2 = x * x % P;
243
+ const b2 = x2 * x % P;
244
+ const b4 = pow2(b2, 2n) * b2 % P;
245
+ const b5 = pow2(b4, 1n) * x % P;
246
+ const b10 = pow2(b5, 5n) * b5 % P;
247
+ const b20 = pow2(b10, 10n) * b10 % P;
248
+ const b40 = pow2(b20, 20n) * b20 % P;
249
+ const b80 = pow2(b40, 40n) * b40 % P;
250
+ const b160 = pow2(b80, 80n) * b80 % P;
251
+ const b240 = pow2(b160, 80n) * b80 % P;
252
+ const b250 = pow2(b240, 10n) * b10 % P;
253
+ const pow_p_5_8 = pow2(b250, 2n) * x % P;
254
+ return { pow_p_5_8, b2 };
255
+ };
256
+ var RM1 = 19681161376707505956807079304988542015446066515923890162744021073123829784752n;
257
+ var uvRatio = (u, v) => {
258
+ const v3 = mod(v * v * v);
259
+ const v7 = mod(v3 * v3 * v);
260
+ const pow = pow_2_252_3(u * v7).pow_p_5_8;
261
+ let x = mod(u * v3 * pow);
262
+ const vx2 = mod(v * x * x);
263
+ const root1 = x;
264
+ const root2 = mod(x * RM1);
265
+ const useRoot1 = vx2 === u;
266
+ const useRoot2 = vx2 === mod(-u);
267
+ const noRoot = vx2 === mod(-u * RM1);
268
+ if (useRoot1)
269
+ x = root1;
270
+ if (useRoot2 || noRoot)
271
+ x = root2;
272
+ if ((mod(x) & 1n) === 1n)
273
+ x = mod(-x);
274
+ return { isValid: useRoot1 || useRoot2, value: x };
275
+ };
276
+ var modL_LE = (hash) => mod(b2n_LE(hash), N);
277
+ var _shaS;
278
+ var sha512a = (...m) => etc.sha512Async(...m);
279
+ var sha512s = (...m) => (
280
+ // Sync SHA512, not set by default
281
+ typeof _shaS === "function" ? _shaS(...m) : err("etc.sha512Sync not set")
282
+ );
283
+ var hash2extK = (hashed) => {
284
+ const head = hashed.slice(0, 32);
285
+ head[0] &= 248;
286
+ head[31] &= 127;
287
+ head[31] |= 64;
288
+ const prefix = hashed.slice(32, 64);
289
+ const scalar = modL_LE(head);
290
+ const point = G.mul(scalar);
291
+ const pointBytes = point.toRawBytes();
292
+ return { head, prefix, scalar, point, pointBytes };
293
+ };
294
+ var getExtendedPublicKeyAsync = (priv) => sha512a(toU8(priv, 32)).then(hash2extK);
295
+ var getExtendedPublicKey = (priv) => hash2extK(sha512s(toU8(priv, 32)));
296
+ var getPublicKeyAsync = (priv) => getExtendedPublicKeyAsync(priv).then((p) => p.pointBytes);
297
+ function hashFinish(asynchronous, res) {
298
+ if (asynchronous)
299
+ return sha512a(res.hashable).then(res.finish);
300
+ return res.finish(sha512s(res.hashable));
301
+ }
302
+ var _sign = (e, rBytes, msg) => {
303
+ const { pointBytes: P2, scalar: s } = e;
304
+ const r = modL_LE(rBytes);
305
+ const R = G.mul(r).toRawBytes();
306
+ const hashable = concatB(R, P2, msg);
307
+ const finish = (hashed) => {
308
+ const S = mod(r + modL_LE(hashed) * s, N);
309
+ return au8(concatB(R, n2b_32LE(S)), 64);
310
+ };
311
+ return { hashable, finish };
312
+ };
313
+ var signAsync = async (msg, privKey) => {
314
+ const m = toU8(msg);
315
+ const e = await getExtendedPublicKeyAsync(privKey);
316
+ const rBytes = await sha512a(e.prefix, m);
317
+ return hashFinish(true, _sign(e, rBytes, m));
318
+ };
319
+ var _verify = (sig, msg, pub) => {
320
+ msg = toU8(msg);
321
+ sig = toU8(sig, 64);
322
+ const A = Point.fromHex(pub, false);
323
+ const R = Point.fromHex(sig.slice(0, 32), false);
324
+ const s = b2n_LE(sig.slice(32, 64));
325
+ const SB = G.mul(s, false);
326
+ const hashable = concatB(R.toRawBytes(), A.toRawBytes(), msg);
327
+ const finish = (hashed) => {
328
+ const k = modL_LE(hashed);
329
+ const RkA = R.add(A.mul(k, false));
330
+ return RkA.add(SB.negate()).clearCofactor().is0();
331
+ };
332
+ return { hashable, finish };
333
+ };
334
+ var verifyAsync = async (s, m, p) => hashFinish(true, _verify(s, m, p));
335
+ var cr = () => (
336
+ // We support: 1) browsers 2) node.js 19+
337
+ typeof globalThis === "object" && "crypto" in globalThis ? globalThis.crypto : void 0
338
+ );
339
+ var etc = {
340
+ bytesToHex: b2h,
341
+ hexToBytes: h2b,
342
+ concatBytes: concatB,
343
+ mod,
344
+ invert,
345
+ randomBytes: (len) => {
346
+ const crypto = cr();
347
+ if (!crypto)
348
+ err("crypto.getRandomValues must be defined");
349
+ return crypto.getRandomValues(u8n(len));
350
+ },
351
+ sha512Async: async (...messages) => {
352
+ const crypto = cr();
353
+ if (!crypto)
354
+ err("crypto.subtle or etc.sha512Async must be defined");
355
+ const m = concatB(...messages);
356
+ return u8n(await crypto.subtle.digest("SHA-512", m.buffer));
357
+ },
358
+ sha512Sync: void 0
359
+ // Actual logic below
360
+ };
361
+ Object.defineProperties(etc, { sha512Sync: {
362
+ configurable: false,
363
+ get() {
364
+ return _shaS;
365
+ },
366
+ set(f) {
367
+ if (!_shaS)
368
+ _shaS = f;
369
+ }
370
+ } });
371
+ var utils = {
372
+ getExtendedPublicKeyAsync,
373
+ getExtendedPublicKey,
374
+ randomPrivateKey: () => etc.randomBytes(32),
375
+ precompute(w = 8, p = G) {
376
+ p.multiply(3n);
377
+ return p;
378
+ }
379
+ // no-op
380
+ };
381
+ var W = 8;
382
+ var precompute = () => {
383
+ const points = [];
384
+ const windows = 256 / W + 1;
385
+ let p = G, b = p;
386
+ for (let w = 0; w < windows; w++) {
387
+ b = p;
388
+ points.push(b);
389
+ for (let i = 1; i < 2 ** (W - 1); i++) {
390
+ b = b.add(p);
391
+ points.push(b);
392
+ }
393
+ p = b.double();
394
+ }
395
+ return points;
396
+ };
397
+ var wNAF = (n) => {
398
+ const comp = Gpows || (Gpows = precompute());
399
+ const neg = (cnd, p2) => {
400
+ let n2 = p2.negate();
401
+ return cnd ? n2 : p2;
402
+ };
403
+ let p = I, f = G;
404
+ const windows = 1 + 256 / W;
405
+ const wsize = 2 ** (W - 1);
406
+ const mask = BigInt(2 ** W - 1);
407
+ const maxNum = 2 ** W;
408
+ const shiftBy = BigInt(W);
409
+ for (let w = 0; w < windows; w++) {
410
+ const off = w * wsize;
411
+ let wbits = Number(n & mask);
412
+ n >>= shiftBy;
413
+ if (wbits > wsize) {
414
+ wbits -= maxNum;
415
+ n += 1n;
416
+ }
417
+ const off1 = off, off2 = off + Math.abs(wbits) - 1;
418
+ const cnd1 = w % 2 !== 0, cnd2 = wbits < 0;
419
+ if (wbits === 0) {
420
+ f = f.add(neg(cnd1, comp[off1]));
421
+ } else {
422
+ p = p.add(neg(cnd2, comp[off2]));
423
+ }
424
+ }
425
+ return { p, f };
426
+ };
427
+
428
+ // src/secrets.ts
7
429
  var PROHIBITED_KEY_USAGES = /* @__PURE__ */ new Set([
8
430
  "decrypt",
9
431
  "deriveBits",
@@ -12,13 +434,60 @@ var PROHIBITED_KEY_USAGES = /* @__PURE__ */ new Set([
12
434
  "unwrapKey",
13
435
  "wrapKey"
14
436
  ]);
437
+ var ED25519_PKCS8_HEADER = (
438
+ // prettier-ignore
439
+ [
440
+ /**
441
+ * PKCS#8 header
442
+ */
443
+ 48,
444
+ // ASN.1 sequence tag
445
+ 46,
446
+ // Length of sequence (46 more bytes)
447
+ 2,
448
+ // ASN.1 integer tag
449
+ 1,
450
+ // Length of integer
451
+ 0,
452
+ // Version number
453
+ 48,
454
+ // ASN.1 sequence tag
455
+ 5,
456
+ // Length of sequence
457
+ 6,
458
+ // ASN.1 object identifier tag
459
+ 3,
460
+ // Length of object identifier
461
+ // Edwards curve algorithms identifier https://oid-rep.orange-labs.fr/get/1.3.101.112
462
+ 43,
463
+ // 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)
464
+ 101,
465
+ // thawte(101)
466
+ // Ed25519 identifier
467
+ 112,
468
+ // id-Ed25519(112)
469
+ /**
470
+ * Private key payload
471
+ */
472
+ 4,
473
+ // ASN.1 octet string tag
474
+ 34,
475
+ // String length (34 more bytes)
476
+ // Private key bytes as octet string
477
+ 4,
478
+ // ASN.1 octet string tag
479
+ 32
480
+ // String length (32 bytes)
481
+ ]
482
+ );
15
483
  function bufferSourceToUint8Array(data) {
16
484
  return data instanceof Uint8Array ? data : new Uint8Array(ArrayBuffer.isView(data) ? data.buffer : data);
17
485
  }
18
486
  var storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT;
487
+ var publicKeyBytesStore;
19
488
  function createKeyPairFromBytes(bytes, extractable, keyUsages) {
20
489
  const keyPair = createKeyPair_INTERNAL_ONLY_DO_NOT_EXPORT(extractable, keyUsages);
21
- const cache = storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT || (storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT = /* @__PURE__ */ new WeakMap());
490
+ const cache = storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT ||= /* @__PURE__ */ new WeakMap();
22
491
  cache.set(keyPair.privateKey, bytes);
23
492
  cache.set(keyPair.publicKey, bytes);
24
493
  return keyPair;
@@ -58,60 +527,124 @@ function getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key) {
58
527
  }
59
528
  return secretKeyBytes;
60
529
  }
61
- function exportKeyPolyfill(format, key) {
530
+ async function getPublicKeyBytes(key) {
531
+ const publicKeyStore = publicKeyBytesStore ||= /* @__PURE__ */ new WeakMap();
532
+ const fromPublicStore = publicKeyStore.get(key);
533
+ if (fromPublicStore)
534
+ return fromPublicStore;
535
+ const publicKeyBytes = await getPublicKeyAsync(getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key));
536
+ publicKeyStore.set(key, publicKeyBytes);
537
+ return publicKeyBytes;
538
+ }
539
+ async function exportKeyPolyfill(format, key) {
540
+ if (key.extractable === false) {
541
+ throw new DOMException("key is not extractable", "InvalidAccessException");
542
+ }
62
543
  switch (format) {
63
544
  case "raw": {
64
- if (key.extractable === false) {
65
- throw new DOMException("key is not extractable", "InvalidAccessException");
66
- }
67
545
  if (key.type !== "public") {
68
546
  throw new DOMException(`Unable to export a raw Ed25519 ${key.type} key`, "InvalidAccessError");
69
547
  }
70
- const publicKeyBytes = ed25519.ed25519.getPublicKey(getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key));
548
+ const publicKeyBytes = await getPublicKeyBytes(key);
71
549
  return publicKeyBytes;
72
550
  }
551
+ case "pkcs8": {
552
+ if (key.type !== "private") {
553
+ throw new DOMException(`Unable to export a pkcs8 Ed25519 ${key.type} key`, "InvalidAccessError");
554
+ }
555
+ const secretKeyBytes = getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key);
556
+ return new Uint8Array([...ED25519_PKCS8_HEADER, ...secretKeyBytes]);
557
+ }
73
558
  default:
74
559
  throw new Error(`Exporting polyfilled Ed25519 keys in the "${format}" format is unimplemented`);
75
560
  }
76
561
  }
77
562
  function generateKeyPolyfill(extractable, keyUsages) {
78
- const privateKeyBytes = ed25519.ed25519.utils.randomPrivateKey();
563
+ const privateKeyBytes = utils.randomPrivateKey();
79
564
  const keyPair = createKeyPairFromBytes(privateKeyBytes, extractable, keyUsages);
80
565
  return keyPair;
81
566
  }
82
567
  function isPolyfilledKey(key) {
83
- return !!storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT?.has(key);
568
+ return !!storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT?.has(key) || !!publicKeyBytesStore?.has(key);
84
569
  }
85
- function signPolyfill(key, data) {
570
+ async function signPolyfill(key, data) {
86
571
  if (key.type !== "private" || !key.usages.includes("sign")) {
87
572
  throw new DOMException("Unable to use this key to sign", "InvalidAccessError");
88
573
  }
89
574
  const privateKeyBytes = getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key);
90
575
  const payload = bufferSourceToUint8Array(data);
91
- const signature = ed25519.ed25519.sign(payload, privateKeyBytes);
576
+ const signature = await signAsync(payload, privateKeyBytes);
92
577
  return signature;
93
578
  }
94
- function verifyPolyfill(key, signature, data) {
579
+ async function verifyPolyfill(key, signature, data) {
95
580
  if (key.type !== "public" || !key.usages.includes("verify")) {
96
581
  throw new DOMException("Unable to use this key to verify", "InvalidAccessError");
97
582
  }
98
- const publicKeyBytes = ed25519.ed25519.getPublicKey(getSecretKeyBytes_INTERNAL_ONLY_DO_NOT_EXPORT(key));
583
+ const publicKeyBytes = await getPublicKeyBytes(key);
99
584
  try {
100
- return ed25519.ed25519.verify(bufferSourceToUint8Array(signature), bufferSourceToUint8Array(data), publicKeyBytes);
585
+ return await verifyAsync(bufferSourceToUint8Array(signature), bufferSourceToUint8Array(data), publicKeyBytes);
101
586
  } catch {
102
587
  return false;
103
588
  }
104
589
  }
590
+ function importKeyPolyfill(format, keyData, extractable, keyUsages) {
591
+ const bytes = bufferSourceToUint8Array(keyData);
592
+ if (format === "raw") {
593
+ if (keyUsages.some((usage) => usage === "sign" || PROHIBITED_KEY_USAGES.has(usage))) {
594
+ throw new DOMException("Unsupported key usage for a Ed25519 key", "SyntaxError");
595
+ }
596
+ if (bytes.length !== 32) {
597
+ throw new DOMException("Ed25519 raw keys must be exactly 32-bytes", "DataError");
598
+ }
599
+ const publicKey = {
600
+ [Symbol.toStringTag]: "CryptoKey",
601
+ algorithm: Object.freeze({ name: "Ed25519" }),
602
+ extractable,
603
+ type: "public",
604
+ usages: Object.freeze(keyUsages.filter((usage) => usage === "verify"))
605
+ };
606
+ const cache = publicKeyBytesStore ||= /* @__PURE__ */ new WeakMap();
607
+ cache.set(publicKey, bytes);
608
+ return publicKey;
609
+ }
610
+ if (format === "pkcs8") {
611
+ if (keyUsages.some((usage) => usage === "verify" || PROHIBITED_KEY_USAGES.has(usage))) {
612
+ throw new DOMException("Unsupported key usage for a Ed25519 key", "SyntaxError");
613
+ }
614
+ if (bytes.length !== 48) {
615
+ throw new DOMException("Invalid keyData", "DataError");
616
+ }
617
+ const header = bytes.slice(0, 16);
618
+ if (!header.every((val, i) => val === ED25519_PKCS8_HEADER[i])) {
619
+ throw new DOMException("Invalid keyData", "DataError");
620
+ }
621
+ const secretKeyBytes = bytes.slice(16);
622
+ const privateKey = {
623
+ [Symbol.toStringTag]: "CryptoKey",
624
+ algorithm: Object.freeze({ name: "Ed25519" }),
625
+ extractable,
626
+ type: "private",
627
+ usages: Object.freeze(keyUsages.filter((usage) => usage === "sign"))
628
+ };
629
+ const cache = storageKeyBySecretKey_INTERNAL_ONLY_DO_NOT_EXPORT ||= /* @__PURE__ */ new WeakMap();
630
+ cache.set(privateKey, secretKeyBytes);
631
+ return privateKey;
632
+ }
633
+ throw new Error(`Importing Ed25519 keys in the "${format}" format is unimplemented`);
634
+ }
105
635
 
106
636
  // src/index.ts
107
637
  {
108
- const originalCryptoObject = globalThis.crypto || (globalThis.crypto = {});
109
- const originalSubtleCrypto = originalCryptoObject.subtle || (originalCryptoObject.subtle = {});
638
+ globalThis.crypto ||= t;
639
+ }
640
+ {
641
+ const originalCryptoObject = globalThis.crypto ||= {};
642
+ const originalSubtleCrypto = originalCryptoObject.subtle ||= {};
110
643
  const originalExportKey = originalSubtleCrypto.exportKey;
111
644
  originalSubtleCrypto.exportKey = async (...args) => {
112
645
  const [_, key] = args;
113
646
  if (isPolyfilledKey(key)) {
114
- return exportKeyPolyfill(...args);
647
+ return await exportKeyPolyfill(...args);
115
648
  } else if (originalExportKey) {
116
649
  return await originalExportKey.apply(originalSubtleCrypto, args);
117
650
  } else {
@@ -170,7 +703,7 @@ function verifyPolyfill(key, signature, data) {
170
703
  const [_, key] = args;
171
704
  if (isPolyfilledKey(key)) {
172
705
  const [_2, ...rest] = args;
173
- return signPolyfill(...rest);
706
+ return await signPolyfill(...rest);
174
707
  } else if (originalSign) {
175
708
  return await originalSign.apply(originalSubtleCrypto, args);
176
709
  } else {
@@ -182,13 +715,65 @@ function verifyPolyfill(key, signature, data) {
182
715
  const [_, key] = args;
183
716
  if (isPolyfilledKey(key)) {
184
717
  const [_2, ...rest] = args;
185
- return verifyPolyfill(...rest);
718
+ return await verifyPolyfill(...rest);
186
719
  } else if (originalVerify) {
187
720
  return await originalVerify.apply(originalSubtleCrypto, args);
188
721
  } else {
189
722
  throw new TypeError("No native `verify` function exists to handle this call");
190
723
  }
191
724
  };
725
+ const originalImportKey = originalSubtleCrypto.importKey;
726
+ let originalImportKeySupportsEd25519;
727
+ originalSubtleCrypto.importKey = async (...args) => {
728
+ const [format, keyData, algorithm] = args;
729
+ if (algorithm !== "Ed25519") {
730
+ if (originalImportKey) {
731
+ return await originalImportKey.apply(originalSubtleCrypto, args);
732
+ } else {
733
+ throw new TypeError("No native `importKey` function exists to handle this call");
734
+ }
735
+ }
736
+ let optimisticallyImportedKey;
737
+ if (originalImportKeySupportsEd25519 === void 0) {
738
+ originalImportKeySupportsEd25519 = new Promise((resolve) => {
739
+ if (!originalImportKey) {
740
+ resolve(originalImportKeySupportsEd25519 = false);
741
+ return;
742
+ }
743
+ originalImportKey.apply(originalSubtleCrypto, args).then((key) => {
744
+ if (__DEV__) {
745
+ console.warn(
746
+ "`@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."
747
+ );
748
+ }
749
+ if (originalSubtleCrypto.importKey !== originalImportKey) {
750
+ originalSubtleCrypto.importKey = originalImportKey;
751
+ }
752
+ optimisticallyImportedKey = key;
753
+ resolve(originalImportKeySupportsEd25519 = true);
754
+ }).catch(() => {
755
+ resolve(originalImportKeySupportsEd25519 = false);
756
+ });
757
+ });
758
+ }
759
+ if (typeof originalImportKey === "boolean" ? originalImportKeySupportsEd25519 : await originalImportKeySupportsEd25519) {
760
+ if (optimisticallyImportedKey) {
761
+ return optimisticallyImportedKey;
762
+ } else if (originalImportKey) {
763
+ return await originalImportKey.apply(originalSubtleCrypto, args);
764
+ } else {
765
+ throw new TypeError("No native `importKey` function exists to handle this call");
766
+ }
767
+ } else {
768
+ const [_format, _keyData, _algorithm, extractable, keyUsages] = args;
769
+ return importKeyPolyfill(format, keyData, extractable, keyUsages);
770
+ }
771
+ };
192
772
  }
773
+ /*! Bundled license information:
774
+
775
+ @noble/ed25519/index.js:
776
+ (*! noble-ed25519 - MIT License (c) 2019 Paul Miller (paulmillr.com) *)
777
+ */
193
778
  //# sourceMappingURL=out.js.map
194
779
  //# sourceMappingURL=index.node.cjs.map