@ocap/mcrypto 1.30.24 → 1.30.25

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.
Files changed (51) hide show
  1. package/esm/crypter/aes-legacy.d.mts +11 -0
  2. package/esm/crypter/aes-legacy.mjs +67 -15
  3. package/esm/crypter/aes.d.mts +14 -2
  4. package/esm/crypter/aes.mjs +69 -3
  5. package/esm/encode.mjs +1 -1
  6. package/esm/hasher/keccak.mjs +7 -2
  7. package/esm/hasher/sha2.d.mts +1 -1
  8. package/esm/hasher/sha2.mjs +26 -11
  9. package/esm/hasher/sha3.d.mts +1 -1
  10. package/esm/hasher/sha3.mjs +21 -6
  11. package/esm/index.d.mts +1 -1
  12. package/esm/signer/ed25519.d.mts +1 -1
  13. package/esm/signer/ed25519.mjs +143 -16
  14. package/esm/signer/ethereum.mjs +7 -3
  15. package/esm/signer/secp256k1.mjs +3 -2
  16. package/esm/webauthn.d.mts +68 -2
  17. package/esm/webauthn.mjs +64 -16
  18. package/lib/_vendor/@noble/curves/LICENSE +21 -0
  19. package/lib/_vendor/@noble/curves/abstract/curve.cjs +373 -0
  20. package/lib/_vendor/@noble/curves/abstract/modular.cjs +616 -0
  21. package/lib/_vendor/@noble/curves/abstract/weierstrass.cjs +1020 -0
  22. package/lib/_vendor/@noble/curves/nist.cjs +91 -0
  23. package/lib/_vendor/@noble/curves/secp256k1.cjs +73 -0
  24. package/lib/_vendor/@noble/curves/utils.cjs +463 -0
  25. package/lib/_vendor/@noble/ed25519/LICENSE +21 -0
  26. package/lib/_vendor/@noble/ed25519/index.cjs +512 -0
  27. package/lib/_vendor/@noble/hashes/LICENSE +21 -0
  28. package/lib/_vendor/@noble/hashes/_md.cjs +230 -0
  29. package/lib/_vendor/@noble/hashes/_u64.cjs +67 -0
  30. package/lib/_vendor/@noble/hashes/hmac.cjs +86 -0
  31. package/lib/_vendor/@noble/hashes/sha2.cjs +477 -0
  32. package/lib/_vendor/@noble/hashes/sha3.cjs +329 -0
  33. package/lib/_vendor/@noble/hashes/utils.cjs +410 -0
  34. package/lib/crypter/aes-legacy.cjs +68 -21
  35. package/lib/crypter/aes-legacy.d.cts +11 -0
  36. package/lib/crypter/aes.cjs +69 -2
  37. package/lib/crypter/aes.d.cts +14 -2
  38. package/lib/encode.cjs +1 -1
  39. package/lib/hasher/keccak.cjs +13 -8
  40. package/lib/hasher/sha2.cjs +32 -17
  41. package/lib/hasher/sha2.d.cts +1 -1
  42. package/lib/hasher/sha3.cjs +27 -12
  43. package/lib/hasher/sha3.d.cts +1 -1
  44. package/lib/index.d.cts +1 -1
  45. package/lib/signer/ed25519.cjs +146 -20
  46. package/lib/signer/ed25519.d.cts +1 -1
  47. package/lib/signer/ethereum.cjs +16 -12
  48. package/lib/signer/secp256k1.cjs +11 -10
  49. package/lib/webauthn.cjs +80 -31
  50. package/lib/webauthn.d.cts +68 -2
  51. package/package.json +6 -7
@@ -1,5 +1,10 @@
1
+ import * as _noble_hashes_utils_js0 from "@noble/hashes/utils.js";
2
+ import * as _noble_hashes_sha2_js0 from "@noble/hashes/sha2.js";
3
+ import * as _noble_curves_abstract_weierstrass_js0 from "@noble/curves/abstract/weierstrass.js";
4
+
5
+ //#region src/webauthn.d.ts
1
6
  declare namespace webauthn_d_exports {
2
- export { COSEALG, COSECRV, COSEKEYS, COSEKTY, GenerateAuthenticationOptionsOpts, GenerateRegistrationOptionsOpts, ParsedAuthenticatorData, RegistrationResponseJSON, VerifiedRegistrationResponse, cose, decodeClientDataJSON, generateAuthenticationOptions, generateChallenge, generateRegistrationOptions, isoBase64URL, isoCBOR, isoUint8Array, parseAuthenticatorData, toHash, verifyRegistrationResponse, verifySignature };
7
+ export { COSEALG, COSECRV, COSEKEYS, COSEKTY, GenerateAuthenticationOptionsOpts, GenerateRegistrationOptionsOpts, ParsedAuthenticatorData, RegistrationResponseJSON, VerifiedRegistrationResponse, cose, decodeClientDataJSON, generateAuthenticationOptions, generateChallenge, generateRegistrationOptions, isoBase64URL, isoCBOR, isoUint8Array, parseAuthenticatorData, parseCoseEc2PublicKey, toHash, verifyRegistrationResponse, verifySignature };
3
8
  }
4
9
  declare const COSEKEYS: {
5
10
  readonly kty: 1;
@@ -117,6 +122,67 @@ interface ParsedAuthenticatorData {
117
122
  extensionsDataBuffer?: Uint8Array;
118
123
  }
119
124
  declare function parseAuthenticatorData(authData: Uint8Array): ParsedAuthenticatorData;
125
+ /**
126
+ * Parse an EC2 COSE public key into a validated uncompressed SEC1 point.
127
+ * Throws on any malformed input: non-map key, wrong kty, unsupported curve,
128
+ * non-bytes / empty / oversized coordinates, or a point that is not on the curve.
129
+ *
130
+ * `strict` additionally requires the exact canonical byte form: coordinates of exactly the
131
+ * curve component length, no trailing bytes, no duplicate map keys, minimal CBOR heads.
132
+ * Registration uses strict. The transaction verify path stays lenient on purpose: it verifies
133
+ * against raw on-chain `pk` bytes that clients supplied, and tightening it could invalidate
134
+ * already-declared accounts when replaying history.
135
+ */
136
+ declare function parseCoseEc2PublicKey(credentialPublicKey: Uint8Array, opts?: {
137
+ strict?: boolean;
138
+ }): {
139
+ curve: _noble_curves_abstract_weierstrass_js0.ECDSA;
140
+ hash: ({
141
+ outputLen: number;
142
+ blockLen: number;
143
+ canXOF: boolean;
144
+ } & _noble_hashes_utils_js0.HashInfo & {
145
+ (msg: _noble_hashes_utils_js0.TArg<Uint8Array>): _noble_hashes_utils_js0.TRet<Uint8Array>;
146
+ create(): _noble_hashes_sha2_js0._SHA256;
147
+ } & ((msg: _noble_hashes_utils_js0.TArg<_noble_hashes_utils_js0.TArg<Uint8Array<ArrayBufferLike>>>) => Uint8Array<ArrayBufferLike> & Uint8Array<ArrayBuffer>) & {
148
+ outputLen: number;
149
+ blockLen: number;
150
+ canXOF: boolean;
151
+ oid?: _noble_hashes_utils_js0.TRet<Uint8Array> | undefined;
152
+ create: () => _noble_hashes_sha2_js0._SHA256;
153
+ }) | ({
154
+ outputLen: number;
155
+ blockLen: number;
156
+ canXOF: boolean;
157
+ } & _noble_hashes_utils_js0.HashInfo & {
158
+ (msg: _noble_hashes_utils_js0.TArg<Uint8Array>): _noble_hashes_utils_js0.TRet<Uint8Array>;
159
+ create(): _noble_hashes_sha2_js0._SHA384;
160
+ } & ((msg: _noble_hashes_utils_js0.TArg<_noble_hashes_utils_js0.TArg<Uint8Array<ArrayBufferLike>>>) => Uint8Array<ArrayBufferLike> & Uint8Array<ArrayBuffer>) & {
161
+ outputLen: number;
162
+ blockLen: number;
163
+ canXOF: boolean;
164
+ oid?: _noble_hashes_utils_js0.TRet<Uint8Array> | undefined;
165
+ create: () => _noble_hashes_sha2_js0._SHA384;
166
+ }) | ({
167
+ outputLen: number;
168
+ blockLen: number;
169
+ canXOF: boolean;
170
+ } & _noble_hashes_utils_js0.HashInfo & {
171
+ (msg: _noble_hashes_utils_js0.TArg<Uint8Array>): _noble_hashes_utils_js0.TRet<Uint8Array>;
172
+ create(): _noble_hashes_sha2_js0._SHA512;
173
+ } & ((msg: _noble_hashes_utils_js0.TArg<_noble_hashes_utils_js0.TArg<Uint8Array<ArrayBufferLike>>>) => Uint8Array<ArrayBufferLike> & Uint8Array<ArrayBuffer>) & {
174
+ outputLen: number;
175
+ blockLen: number;
176
+ canXOF: boolean;
177
+ oid?: _noble_hashes_utils_js0.TRet<Uint8Array> | undefined;
178
+ create: () => _noble_hashes_sha2_js0._SHA512;
179
+ });
180
+ pubKeyBytes: Uint8Array<ArrayBuffer>;
181
+ };
182
+ /**
183
+ * Verify a DER ECDSA signature against a COSE public key. Never throws: any
184
+ * malformed key / signature input yields `false`.
185
+ */
120
186
  declare function verifySignature(opts: {
121
187
  signature: Uint8Array;
122
188
  data: Uint8Array;
@@ -207,4 +273,4 @@ declare function verifyRegistrationResponse(options: {
207
273
  supportedAlgorithmIDs?: number[];
208
274
  }): Promise<VerifiedRegistrationResponse>;
209
275
  //#endregion
210
- export { COSEALG, COSECRV, COSEKEYS, COSEKTY, GenerateAuthenticationOptionsOpts, GenerateRegistrationOptionsOpts, ParsedAuthenticatorData, RegistrationResponseJSON, VerifiedRegistrationResponse, cose, decodeClientDataJSON, generateAuthenticationOptions, generateChallenge, generateRegistrationOptions, isoBase64URL, isoCBOR, isoUint8Array, parseAuthenticatorData, toHash, verifyRegistrationResponse, verifySignature, webauthn_d_exports };
276
+ export { COSEALG, COSECRV, COSEKEYS, COSEKTY, GenerateAuthenticationOptionsOpts, GenerateRegistrationOptionsOpts, ParsedAuthenticatorData, RegistrationResponseJSON, VerifiedRegistrationResponse, cose, decodeClientDataJSON, generateAuthenticationOptions, generateChallenge, generateRegistrationOptions, isoBase64URL, isoCBOR, isoUint8Array, parseAuthenticatorData, parseCoseEc2PublicKey, toHash, verifyRegistrationResponse, verifySignature, webauthn_d_exports };
package/esm/webauthn.mjs CHANGED
@@ -26,6 +26,7 @@ var webauthn_exports = /* @__PURE__ */ __exportAll({
26
26
  isoCBOR: () => isoCBOR,
27
27
  isoUint8Array: () => isoUint8Array,
28
28
  parseAuthenticatorData: () => parseAuthenticatorData,
29
+ parseCoseEc2PublicKey: () => parseCoseEc2PublicKey,
29
30
  toHash: () => toHash,
30
31
  verifyRegistrationResponse: () => verifyRegistrationResponse,
31
32
  verifySignature: () => verifySignature
@@ -121,39 +122,52 @@ const isoUint8Array = {
121
122
  return bytes;
122
123
  }
123
124
  };
124
- function decodeCBORInternal(data, offset) {
125
+ function decodeCBORInternal(data, offset, depth = 0, state = { items: 0 }) {
126
+ if (depth > 16) throw new Error("CBOR: maximum nesting depth exceeded");
127
+ if (++state.items > 1024) throw new Error("CBOR: maximum item count exceeded");
128
+ if (offset >= data.length) throw new Error("CBOR: unexpected end of buffer");
125
129
  const major = data[offset] >> 5;
126
130
  const additional = data[offset] & 31;
127
131
  offset++;
128
132
  let length;
129
133
  if (additional < 24) length = additional;
130
- else if (additional === 24) length = data[offset++];
131
- else if (additional === 25) {
134
+ else if (additional === 24) {
135
+ if (offset + 1 > data.length) throw new Error("CBOR: unexpected end of buffer");
136
+ length = data[offset++];
137
+ } else if (additional === 25) {
138
+ if (offset + 2 > data.length) throw new Error("CBOR: unexpected end of buffer");
132
139
  length = data[offset] << 8 | data[offset + 1];
133
140
  offset += 2;
134
141
  } else if (additional === 26) {
135
- length = data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3];
142
+ if (offset + 4 > data.length) throw new Error("CBOR: unexpected end of buffer");
143
+ length = (data[offset] << 24 | data[offset + 1] << 16 | data[offset + 2] << 8 | data[offset + 3]) >>> 0;
136
144
  offset += 4;
137
145
  } else throw new Error(`CBOR: unsupported additional info ${additional}`);
138
146
  switch (major) {
139
147
  case 0: return [length, offset];
140
148
  case 1: return [-1 - length, offset];
141
- case 2: return [data.slice(offset, offset + length), offset + length];
142
- case 3: return [new TextDecoder().decode(data.slice(offset, offset + length)), offset + length];
149
+ case 2:
150
+ if (offset + length > data.length) throw new Error("CBOR: unexpected end of buffer");
151
+ return [data.slice(offset, offset + length), offset + length];
152
+ case 3:
153
+ if (offset + length > data.length) throw new Error("CBOR: unexpected end of buffer");
154
+ return [new TextDecoder().decode(data.slice(offset, offset + length)), offset + length];
143
155
  case 4: {
156
+ if (length > data.length - offset) throw new Error("CBOR: array length exceeds remaining buffer");
144
157
  const arr = [];
145
158
  for (let i = 0; i < length; i++) {
146
- const [value, newOffset] = decodeCBORInternal(data, offset);
159
+ const [value, newOffset] = decodeCBORInternal(data, offset, depth + 1, state);
147
160
  arr.push(value);
148
161
  offset = newOffset;
149
162
  }
150
163
  return [arr, offset];
151
164
  }
152
165
  case 5: {
166
+ if (length > data.length - offset) throw new Error("CBOR: map length exceeds remaining buffer");
153
167
  const map = /* @__PURE__ */ new Map();
154
168
  for (let i = 0; i < length; i++) {
155
- const [key, keyOffset] = decodeCBORInternal(data, offset);
156
- const [value, valueOffset] = decodeCBORInternal(data, keyOffset);
169
+ const [key, keyOffset] = decodeCBORInternal(data, offset, depth + 1, state);
170
+ const [value, valueOffset] = decodeCBORInternal(data, keyOffset, depth + 1, state);
157
171
  map.set(key, value);
158
172
  offset = valueOffset;
159
173
  }
@@ -259,9 +273,11 @@ function parseAuthenticatorData(authData) {
259
273
  let credentialID;
260
274
  let credentialPublicKey;
261
275
  if (flags.at) {
276
+ if (pointer + 18 > authData.byteLength) throw new Error("Authenticator data too short for attested credential data");
262
277
  aaguid = authData.slice(pointer, pointer += 16);
263
278
  const credIDLen = dataView.getUint16(pointer);
264
279
  pointer += 2;
280
+ if (pointer + credIDLen > authData.byteLength) throw new Error("Authenticator data too short for credential ID");
265
281
  credentialID = authData.slice(pointer, pointer += credIDLen);
266
282
  const firstDecoded = isoCBOR.decodeFirst(authData.slice(pointer));
267
283
  const firstEncoded = isoCBOR.encode(firstDecoded);
@@ -314,9 +330,21 @@ function getCurveForCrv(crv) {
314
330
  default: throw new Error(`Unsupported COSE curve: ${crv}`);
315
331
  }
316
332
  }
317
- async function verifySignature(opts) {
318
- const { signature, data, credentialPublicKey } = opts;
333
+ /**
334
+ * Parse an EC2 COSE public key into a validated uncompressed SEC1 point.
335
+ * Throws on any malformed input: non-map key, wrong kty, unsupported curve,
336
+ * non-bytes / empty / oversized coordinates, or a point that is not on the curve.
337
+ *
338
+ * `strict` additionally requires the exact canonical byte form: coordinates of exactly the
339
+ * curve component length, no trailing bytes, no duplicate map keys, minimal CBOR heads.
340
+ * Registration uses strict. The transaction verify path stays lenient on purpose: it verifies
341
+ * against raw on-chain `pk` bytes that clients supplied, and tightening it could invalidate
342
+ * already-declared accounts when replaying history.
343
+ */
344
+ function parseCoseEc2PublicKey(credentialPublicKey, opts = {}) {
319
345
  const coseKey = isoCBOR.decodeFirst(credentialPublicKey);
346
+ if (!(coseKey instanceof Map)) throw new Error("Invalid COSE public key");
347
+ if (opts.strict && !isoUint8Array.areEqual(isoCBOR.encode(coseKey), credentialPublicKey)) throw new Error("COSE public key is not in canonical form");
320
348
  const kty = coseKey.get(COSEKEYS.kty);
321
349
  if (kty !== COSEKTY.EC2) throw new Error(`Unsupported COSE key type: ${kty} (only EC2 is supported)`);
322
350
  const crv = coseKey.get(COSEKEYS.crv);
@@ -324,13 +352,31 @@ async function verifySignature(opts) {
324
352
  const y = coseKey.get(COSEKEYS.y);
325
353
  if (!x || !y) throw new Error("COSE public key missing x or y coordinate");
326
354
  const { curve, hash, componentLen } = getCurveForCrv(crv);
355
+ if (!(x instanceof Uint8Array) || !(y instanceof Uint8Array) || x.length === 0 || y.length === 0 || x.length > componentLen || y.length > componentLen || opts.strict && (x.length !== componentLen || y.length !== componentLen)) throw new Error("Invalid COSE EC2 coordinate length");
327
356
  const pubKeyBytes = new Uint8Array(1 + componentLen * 2);
328
357
  pubKeyBytes[0] = 4;
329
- pubKeyBytes.set(x.length <= componentLen ? x : x.slice(x.length - componentLen), 1 + (componentLen - x.length));
330
- pubKeyBytes.set(y.length <= componentLen ? y : y.slice(y.length - componentLen), 1 + componentLen + (componentLen - y.length));
331
- const msgHash = hash(data);
358
+ pubKeyBytes.set(x, 1 + (componentLen - x.length));
359
+ pubKeyBytes.set(y, 1 + componentLen + (componentLen - y.length));
360
+ try {
361
+ curve.Point.fromBytes(pubKeyBytes).assertValidity();
362
+ } catch {
363
+ throw new Error("COSE EC2 public key is not a valid point on the curve");
364
+ }
365
+ return {
366
+ curve,
367
+ hash,
368
+ pubKeyBytes
369
+ };
370
+ }
371
+ /**
372
+ * Verify a DER ECDSA signature against a COSE public key. Never throws: any
373
+ * malformed key / signature input yields `false`.
374
+ */
375
+ async function verifySignature(opts) {
332
376
  try {
333
- return curve.verify(signature, msgHash, pubKeyBytes, {
377
+ const { signature, data, credentialPublicKey } = opts;
378
+ const { curve, hash, pubKeyBytes } = parseCoseEc2PublicKey(credentialPublicKey);
379
+ return curve.verify(signature, hash(data), pubKeyBytes, {
334
380
  prehash: false,
335
381
  format: "der",
336
382
  lowS: false
@@ -466,11 +512,13 @@ async function verifyRegistrationResponse(options) {
466
512
  if (requireUserPresence && !flags.up) throw new Error("User presence was required, but user was not present");
467
513
  if (requireUserVerification && !flags.uv) throw new Error("User verification was required, but user could not be verified");
468
514
  if (!credentialID) throw new Error("No credential ID was provided by authenticator");
515
+ if (id !== isoBase64URL.fromBuffer(credentialID)) throw new Error("Credential ID does not match the credential ID in authenticator data");
469
516
  if (!credentialPublicKey) throw new Error("No public key was provided by authenticator");
470
517
  if (!aaguid) throw new Error("No AAGUID was present during registration");
471
518
  const alg = isoCBOR.decodeFirst(credentialPublicKey).get(COSEKEYS.alg);
472
519
  if (typeof alg !== "number") throw new Error("Credential public key was missing numeric alg");
473
520
  if (!supportedAlgorithmIDs.includes(alg)) throw new Error(`Unexpected public key alg "${alg}", expected one of "${supportedAlgorithmIDs.join(", ")}"`);
521
+ parseCoseEc2PublicKey(credentialPublicKey, { strict: true });
474
522
  let verified = false;
475
523
  if (fmt === "none") {
476
524
  if (attStmt.size > 0) throw new Error("None attestation had unexpected attestation statement");
@@ -510,4 +558,4 @@ async function verifyRegistrationResponse(options) {
510
558
  }
511
559
 
512
560
  //#endregion
513
- export { COSEALG, COSECRV, COSEKEYS, COSEKTY, cose, decodeClientDataJSON, generateAuthenticationOptions, generateChallenge, generateRegistrationOptions, isoBase64URL, isoCBOR, isoUint8Array, parseAuthenticatorData, toHash, verifyRegistrationResponse, verifySignature, webauthn_exports };
561
+ export { COSEALG, COSECRV, COSEKEYS, COSEKTY, cose, decodeClientDataJSON, generateAuthenticationOptions, generateChallenge, generateRegistrationOptions, isoBase64URL, isoCBOR, isoUint8Array, parseAuthenticatorData, parseCoseEc2PublicKey, toHash, verifyRegistrationResponse, verifySignature, webauthn_exports };
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2022 Paul Miller (https://paulmillr.com)
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the “Software”), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
@@ -0,0 +1,373 @@
1
+ const require_utils = require('../utils.cjs');
2
+ const require_modular = require('./modular.cjs');
3
+
4
+ //#region ../../node_modules/@noble/curves/abstract/curve.js
5
+ /**
6
+ * Methods for elliptic curve multiplication by scalars.
7
+ * Contains wNAF, pippenger.
8
+ * @module
9
+ */
10
+ /*! noble-curves - MIT License (c) 2022 Paul Miller (paulmillr.com) */
11
+ const _0n = /* @__PURE__ */ BigInt(0);
12
+ const _1n = /* @__PURE__ */ BigInt(1);
13
+ /**
14
+ * Computes both candidates first, but the final selection still branches on `condition`, so this
15
+ * is not a strict constant-time CMOV primitive.
16
+ * @param condition - Whether to negate the point.
17
+ * @param item - Point-like value.
18
+ * @returns Original or negated value.
19
+ * @example
20
+ * Keep the point or return its negation based on one boolean branch.
21
+ *
22
+ * ```ts
23
+ * import { negateCt } from '@noble/curves/abstract/curve.js';
24
+ * import { p256 } from '@noble/curves/nist.js';
25
+ * const maybeNegated = negateCt(true, p256.Point.BASE);
26
+ * ```
27
+ */
28
+ function negateCt(condition, item) {
29
+ const neg = item.negate();
30
+ return condition ? neg : item;
31
+ }
32
+ /**
33
+ * Takes a bunch of Projective Points but executes only one
34
+ * inversion on all of them. Inversion is very slow operation,
35
+ * so this improves performance massively.
36
+ * Optimization: converts a list of projective points to a list of identical points with Z=1.
37
+ * Input points are left unchanged; the normalized points are returned as fresh instances.
38
+ * @param c - Point constructor.
39
+ * @param points - Projective points.
40
+ * @returns Fresh projective points reconstructed from normalized affine coordinates.
41
+ * @example
42
+ * Batch-normalize projective points with a single shared inversion.
43
+ *
44
+ * ```ts
45
+ * import { normalizeZ } from '@noble/curves/abstract/curve.js';
46
+ * import { p256 } from '@noble/curves/nist.js';
47
+ * const points = normalizeZ(p256.Point, [p256.Point.BASE, p256.Point.BASE.double()]);
48
+ * ```
49
+ */
50
+ function normalizeZ(c, points) {
51
+ const invertedZs = require_modular.FpInvertBatch(c.Fp, points.map((p) => p.Z));
52
+ return points.map((p, i) => c.fromAffine(p.toAffine(invertedZs[i])));
53
+ }
54
+ function validateW(W, bits) {
55
+ if (!Number.isSafeInteger(W) || W <= 0 || W > bits) throw new Error("invalid window size, expected [1.." + bits + "], got W=" + W);
56
+ }
57
+ function calcWOpts(W, scalarBits) {
58
+ validateW(W, scalarBits);
59
+ const windows = Math.ceil(scalarBits / W) + 1;
60
+ const windowSize = 2 ** (W - 1);
61
+ const maxNumber = 2 ** W;
62
+ return {
63
+ windows,
64
+ windowSize,
65
+ mask: require_utils.bitMask(W),
66
+ maxNumber,
67
+ shiftBy: BigInt(W)
68
+ };
69
+ }
70
+ function calcOffsets(n, window, wOpts) {
71
+ const { windowSize, mask, maxNumber, shiftBy } = wOpts;
72
+ let wbits = Number(n & mask);
73
+ let nextN = n >> shiftBy;
74
+ if (wbits > windowSize) {
75
+ wbits -= maxNumber;
76
+ nextN += _1n;
77
+ }
78
+ const offsetStart = window * windowSize;
79
+ const offset = offsetStart + Math.abs(wbits) - 1;
80
+ const isZero = wbits === 0;
81
+ const isNeg = wbits < 0;
82
+ const isNegF = window % 2 !== 0;
83
+ return {
84
+ nextN,
85
+ offset,
86
+ isZero,
87
+ isNeg,
88
+ isNegF,
89
+ offsetF: offsetStart
90
+ };
91
+ }
92
+ const pointPrecomputes = /* @__PURE__ */ new WeakMap();
93
+ const pointWindowSizes = /* @__PURE__ */ new WeakMap();
94
+ function getW(P) {
95
+ return pointWindowSizes.get(P) || 1;
96
+ }
97
+ function assert0(n) {
98
+ if (n !== _0n) throw new Error("invalid wNAF");
99
+ }
100
+ /**
101
+ * Elliptic curve multiplication of Point by scalar. Fragile.
102
+ * Table generation takes **30MB of ram and 10ms on high-end CPU**,
103
+ * but may take much longer on slow devices. Actual generation will happen on
104
+ * first call of `multiply()`. By default, `BASE` point is precomputed.
105
+ *
106
+ * Scalars should always be less than curve order: this should be checked inside of a curve itself.
107
+ * Creates precomputation tables for fast multiplication:
108
+ * - private scalar is split by fixed size windows of W bits
109
+ * - every window point is collected from window's table & added to accumulator
110
+ * - since windows are different, same point inside tables won't be accessed more than once per calc
111
+ * - each multiplication is 'Math.ceil(CURVE_ORDER / 𝑊) + 1' point additions (fixed for any scalar)
112
+ * - +1 window is neccessary for wNAF
113
+ * - wNAF reduces table size: 2x less memory + 2x faster generation, but 10% slower multiplication
114
+ *
115
+ * TODO: research returning a 2d JS array of windows instead of a single window.
116
+ * This would allow windows to be in different memory locations.
117
+ * @param Point - Point constructor.
118
+ * @param bits - Scalar bit length.
119
+ * @example
120
+ * Elliptic curve multiplication of Point by scalar.
121
+ *
122
+ * ```ts
123
+ * import { wNAF } from '@noble/curves/abstract/curve.js';
124
+ * import { p256 } from '@noble/curves/nist.js';
125
+ * const ladder = new wNAF(p256.Point, p256.Point.Fn.BITS);
126
+ * ```
127
+ */
128
+ var wNAF = class {
129
+ BASE;
130
+ ZERO;
131
+ Fn;
132
+ bits;
133
+ constructor(Point, bits) {
134
+ this.BASE = Point.BASE;
135
+ this.ZERO = Point.ZERO;
136
+ this.Fn = Point.Fn;
137
+ this.bits = bits;
138
+ }
139
+ _unsafeLadder(elm, n, p = this.ZERO) {
140
+ let d = elm;
141
+ while (n > _0n) {
142
+ if (n & _1n) p = p.add(d);
143
+ d = d.double();
144
+ n >>= _1n;
145
+ }
146
+ return p;
147
+ }
148
+ /**
149
+ * Creates a wNAF precomputation window. Used for caching.
150
+ * Default window size is set by `utils.precompute()` and is equal to 8.
151
+ * Number of precomputed points depends on the curve size:
152
+ * 2^(𝑊−1) * (Math.ceil(𝑛 / 𝑊) + 1), where:
153
+ * - 𝑊 is the window size
154
+ * - 𝑛 is the bitlength of the curve order.
155
+ * For a 256-bit curve and window size 8, the number of precomputed points is 128 * 33 = 4224.
156
+ * @param point - Point instance
157
+ * @param W - window size
158
+ * @returns precomputed point tables flattened to a single array
159
+ */
160
+ precomputeWindow(point, W) {
161
+ const { windows, windowSize } = calcWOpts(W, this.bits);
162
+ const points = [];
163
+ let p = point;
164
+ let base = p;
165
+ for (let window = 0; window < windows; window++) {
166
+ base = p;
167
+ points.push(base);
168
+ for (let i = 1; i < windowSize; i++) {
169
+ base = base.add(p);
170
+ points.push(base);
171
+ }
172
+ p = base.double();
173
+ }
174
+ return points;
175
+ }
176
+ /**
177
+ * Implements ec multiplication using precomputed tables and w-ary non-adjacent form.
178
+ * More compact implementation:
179
+ * https://github.com/paulmillr/noble-secp256k1/blob/47cb1669b6e506ad66b35fe7d76132ae97465da2/index.ts#L502-L541
180
+ * @returns real and fake (for const-time) points
181
+ */
182
+ wNAF(W, precomputes, n) {
183
+ if (!this.Fn.isValid(n)) throw new Error("invalid scalar");
184
+ let p = this.ZERO;
185
+ let f = this.BASE;
186
+ const wo = calcWOpts(W, this.bits);
187
+ for (let window = 0; window < wo.windows; window++) {
188
+ const { nextN, offset, isZero, isNeg, isNegF, offsetF } = calcOffsets(n, window, wo);
189
+ n = nextN;
190
+ if (isZero) f = f.add(negateCt(isNegF, precomputes[offsetF]));
191
+ else p = p.add(negateCt(isNeg, precomputes[offset]));
192
+ }
193
+ assert0(n);
194
+ return {
195
+ p,
196
+ f
197
+ };
198
+ }
199
+ /**
200
+ * Implements unsafe EC multiplication using precomputed tables
201
+ * and w-ary non-adjacent form.
202
+ * @param acc - accumulator point to add result of multiplication
203
+ * @returns point
204
+ */
205
+ wNAFUnsafe(W, precomputes, n, acc = this.ZERO) {
206
+ const wo = calcWOpts(W, this.bits);
207
+ for (let window = 0; window < wo.windows; window++) {
208
+ if (n === _0n) break;
209
+ const { nextN, offset, isZero, isNeg } = calcOffsets(n, window, wo);
210
+ n = nextN;
211
+ if (isZero) continue;
212
+ else {
213
+ const item = precomputes[offset];
214
+ acc = acc.add(isNeg ? item.negate() : item);
215
+ }
216
+ }
217
+ assert0(n);
218
+ return acc;
219
+ }
220
+ getPrecomputes(W, point, transform) {
221
+ let comp = pointPrecomputes.get(point);
222
+ if (!comp) {
223
+ comp = this.precomputeWindow(point, W);
224
+ if (W !== 1) {
225
+ if (typeof transform === "function") comp = transform(comp);
226
+ pointPrecomputes.set(point, comp);
227
+ }
228
+ }
229
+ return comp;
230
+ }
231
+ cached(point, scalar, transform) {
232
+ const W = getW(point);
233
+ return this.wNAF(W, this.getPrecomputes(W, point, transform), scalar);
234
+ }
235
+ unsafe(point, scalar, transform, prev) {
236
+ const W = getW(point);
237
+ if (W === 1) return this._unsafeLadder(point, scalar, prev);
238
+ return this.wNAFUnsafe(W, this.getPrecomputes(W, point, transform), scalar, prev);
239
+ }
240
+ createCache(P, W) {
241
+ validateW(W, this.bits);
242
+ pointWindowSizes.set(P, W);
243
+ pointPrecomputes.delete(P);
244
+ }
245
+ hasCache(elm) {
246
+ return getW(elm) !== 1;
247
+ }
248
+ };
249
+ /**
250
+ * Endomorphism-specific multiplication for Koblitz curves.
251
+ * Cost: 128 dbl, 0-256 adds.
252
+ * @param Point - Point constructor.
253
+ * @param point - Input point.
254
+ * @param k1 - First non-negative absolute scalar chunk.
255
+ * @param k2 - Second non-negative absolute scalar chunk.
256
+ * @returns Partial multiplication results.
257
+ * @example
258
+ * Endomorphism-specific multiplication for Koblitz curves.
259
+ *
260
+ * ```ts
261
+ * import { mulEndoUnsafe } from '@noble/curves/abstract/curve.js';
262
+ * import { secp256k1 } from '@noble/curves/secp256k1.js';
263
+ * const parts = mulEndoUnsafe(secp256k1.Point, secp256k1.Point.BASE, 3n, 5n);
264
+ * ```
265
+ */
266
+ function mulEndoUnsafe(Point, point, k1, k2) {
267
+ let acc = point;
268
+ let p1 = Point.ZERO;
269
+ let p2 = Point.ZERO;
270
+ while (k1 > _0n || k2 > _0n) {
271
+ if (k1 & _1n) p1 = p1.add(acc);
272
+ if (k2 & _1n) p2 = p2.add(acc);
273
+ acc = acc.double();
274
+ k1 >>= _1n;
275
+ k2 >>= _1n;
276
+ }
277
+ return {
278
+ p1,
279
+ p2
280
+ };
281
+ }
282
+ function createField(order, field, isLE) {
283
+ if (field) {
284
+ if (field.ORDER !== order) throw new Error("Field.ORDER must match order: Fp == p, Fn == n");
285
+ require_modular.validateField(field);
286
+ return field;
287
+ } else return require_modular.Field(order, { isLE });
288
+ }
289
+ /**
290
+ * Validates basic CURVE shape and field membership, then creates fields.
291
+ * This does not prove that the generator is on-curve, that subgroup/order data are consistent, or
292
+ * that the curve equation itself is otherwise sane.
293
+ * @param type - Curve family.
294
+ * @param CURVE - Curve parameters.
295
+ * @param curveOpts - Optional field overrides:
296
+ * - `Fp` (optional): Optional base-field override.
297
+ * - `Fn` (optional): Optional scalar-field override.
298
+ * @param FpFnLE - Whether field encoding is little-endian.
299
+ * @returns Frozen curve parameters and fields.
300
+ * @throws If the curve parameters or field overrides are invalid. {@link Error}
301
+ * @example
302
+ * Build curve fields from raw constants before constructing a curve instance.
303
+ *
304
+ * ```ts
305
+ * const curve = createCurveFields('weierstrass', {
306
+ * p: 17n,
307
+ * n: 19n,
308
+ * h: 1n,
309
+ * a: 2n,
310
+ * b: 2n,
311
+ * Gx: 5n,
312
+ * Gy: 1n,
313
+ * });
314
+ * ```
315
+ */
316
+ function createCurveFields(type, CURVE, curveOpts = {}, FpFnLE) {
317
+ if (FpFnLE === void 0) FpFnLE = type === "edwards";
318
+ if (!CURVE || typeof CURVE !== "object") throw new Error(`expected valid ${type} CURVE object`);
319
+ for (const p of [
320
+ "p",
321
+ "n",
322
+ "h"
323
+ ]) {
324
+ const val = CURVE[p];
325
+ if (!(typeof val === "bigint" && val > _0n)) throw new Error(`CURVE.${p} must be positive bigint`);
326
+ }
327
+ const Fp = createField(CURVE.p, curveOpts.Fp, FpFnLE);
328
+ const Fn = createField(CURVE.n, curveOpts.Fn, FpFnLE);
329
+ const params = [
330
+ "Gx",
331
+ "Gy",
332
+ "a",
333
+ type === "weierstrass" ? "b" : "d"
334
+ ];
335
+ for (const p of params) if (!Fp.isValid(CURVE[p])) throw new Error(`CURVE.${p} must be valid field element of CURVE.Fp`);
336
+ CURVE = Object.freeze(Object.assign({}, CURVE));
337
+ return {
338
+ CURVE,
339
+ Fp,
340
+ Fn
341
+ };
342
+ }
343
+ /**
344
+ * @param randomSecretKey - Secret-key generator.
345
+ * @param getPublicKey - Public-key derivation helper.
346
+ * @returns Keypair generator.
347
+ * @example
348
+ * Build a `keygen()` helper from existing secret-key and public-key primitives.
349
+ *
350
+ * ```ts
351
+ * import { createKeygen } from '@noble/curves/abstract/curve.js';
352
+ * import { p256 } from '@noble/curves/nist.js';
353
+ * const keygen = createKeygen(p256.utils.randomSecretKey, p256.getPublicKey);
354
+ * const pair = keygen();
355
+ * ```
356
+ */
357
+ function createKeygen(randomSecretKey, getPublicKey) {
358
+ return function keygen(seed) {
359
+ const secretKey = randomSecretKey(seed);
360
+ return {
361
+ secretKey,
362
+ publicKey: getPublicKey(secretKey)
363
+ };
364
+ };
365
+ }
366
+
367
+ //#endregion
368
+ exports.createCurveFields = createCurveFields;
369
+ exports.createKeygen = createKeygen;
370
+ exports.mulEndoUnsafe = mulEndoUnsafe;
371
+ exports.negateCt = negateCt;
372
+ exports.normalizeZ = normalizeZ;
373
+ exports.wNAF = wNAF;