@optimystic/quereus-plugin-crypto 1.27.0 → 1.28.0

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/src/crypto.ts CHANGED
@@ -12,6 +12,7 @@ import { secp256k1 } from '@noble/curves/secp256k1.js';
12
12
  import { p256 } from '@noble/curves/nist.js';
13
13
  import { ed25519 } from '@noble/curves/ed25519.js';
14
14
  import { hexToBytes, bytesToHex } from '@noble/curves/utils.js';
15
+ import type { ECDSA, ECDSAVerifyOpts } from '@noble/curves/abstract/weierstrass.js';
15
16
  import { toString as uint8ArrayToString, fromString as uint8ArrayFromString } from 'uint8arrays';
16
17
 
17
18
  // Type definitions
@@ -99,9 +100,13 @@ function fromBytes(bytes: Uint8Array, encoding: Encoding = 'base64url'): string
99
100
  * `digest`, `cid` and `set_commit` are `replicable`, and their outputs are signed
100
101
  * and persisted. {@link setCryptoBackend} checks each supplied member against
101
102
  * @noble before installing it. A member handed a malformed key or signature must
102
- * throw or return false, as @noble does; that is not checked. Each returned array
103
- * must be freshly allocated: under the `bytes` encoding it reaches the caller
104
- * uncopied, so a native library's reused output buffer would rewrite earlier results.
103
+ * throw or return false, as @noble does; beyond the ECDSA inputs listed on
104
+ * `p256Verify`, that is not checked. Each returned array must be freshly allocated:
105
+ * under the `bytes` encoding it reaches the caller uncopied, so a native library's
106
+ * reused output buffer would rewrite earlier results.
107
+ *
108
+ * There is no ECDSA signing member: a native ECDSA signer draws a random nonce unless it
109
+ * implements RFC 6979, so its signature could not be checked byte for byte against @noble's.
105
110
  */
106
111
  export interface CryptoBackend {
107
112
  sha256?(data: Uint8Array): Uint8Array;
@@ -110,6 +115,19 @@ export interface CryptoBackend {
110
115
  ed25519Verify?(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array): boolean;
111
116
  /** Message, raw 32-byte secret seed (the form noble and generatePrivateKey('ed25519') use). Returns the raw 64-byte signature. */
112
117
  ed25519Sign?(message: Uint8Array, secretKey: Uint8Array): Uint8Array;
118
+ /**
119
+ * 64-byte compact r‖s signature (big-endian, 32 bytes each), message, 33- or 65-byte SEC 1
120
+ * public key. The member hashes the message with SHA-256 itself; it is never handed a digest.
121
+ * It must decide exactly as @noble/curves' verify does: reject any signature but the 64-byte
122
+ * compact form (a DER one included: the caller's bytes are passed through unchecked), a high-S
123
+ * signature (s > n/2), r or s outside [1, n−1], and any key but 0x02/0x03 with 33 bytes or 0x04
124
+ * with 65. OpenSSL
125
+ * accepts high-S signatures and hybrid 0x06/0x07 keys, so an adapter over it must refuse both
126
+ * itself. Returns false, or throws, for an invalid signature or key.
127
+ */
128
+ p256Verify?(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array): boolean;
129
+ /** As `p256Verify`, over secp256k1. */
130
+ secp256k1Verify?(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array): boolean;
113
131
  }
114
132
 
115
133
  type BackendMember = keyof CryptoBackend;
@@ -161,6 +179,8 @@ function snapshotBackend(backend: CryptoBackend): CryptoBackend {
161
179
  sha512: backend.sha512?.bind(backend),
162
180
  ed25519Verify: backend.ed25519Verify?.bind(backend),
163
181
  ed25519Sign: backend.ed25519Sign?.bind(backend),
182
+ p256Verify: backend.p256Verify?.bind(backend),
183
+ secp256k1Verify: backend.secp256k1Verify?.bind(backend),
164
184
  });
165
185
  }
166
186
 
@@ -173,6 +193,8 @@ function selfCheckBackend(backend: CryptoBackend): void {
173
193
  if (backend.sha512) checkHash('sha512', backend.sha512, sha512);
174
194
  if (backend.ed25519Sign) checkEd25519Sign(backend.ed25519Sign);
175
195
  if (backend.ed25519Verify) checkEd25519Verify(backend.ed25519Verify);
196
+ if (backend.p256Verify) checkEcdsaVerify('p256Verify', p256, backend.p256Verify);
197
+ if (backend.secp256k1Verify) checkEcdsaVerify('secp256k1Verify', secp256k1, backend.secp256k1Verify);
176
198
  }
177
199
 
178
200
  function checkHash(member: BackendMember, native: DigestHasher, noble: DigestHasher): void {
@@ -197,15 +219,85 @@ function checkEd25519Verify(native: NonNullable<CryptoBackend['ed25519Verify']>)
197
219
  if (accepted !== true) {
198
220
  throw backendRefused('ed25519Verify', 'did not accept a valid signature over a raw 32-byte public key');
199
221
  }
200
- const tampered = CHECK_MESSAGE.slice();
201
- tampered[0]! ^= 0x01;
202
- if (rejectsOrThrows(() => native(offsetView(signature), offsetView(tampered), offsetView(publicKey)))) {
222
+ if (rejectsOrThrows(() => native(offsetView(signature), offsetView(tamperedCheckMessage()), offsetView(publicKey)))) {
203
223
  return;
204
224
  }
205
225
  throw backendRefused('ed25519Verify', 'accepted a signature over a different message');
206
226
  }
207
227
 
208
- /** For the tampered vector a throw is a rejection, as the interface allows. */
228
+ type EcdsaVerifyMember = 'p256Verify' | 'secp256k1Verify';
229
+ type EcdsaVerifier = NonNullable<CryptoBackend['p256Verify']>;
230
+
231
+ /** One verify input @noble/curves rejects, named for the refusal that reports a member accepting it. */
232
+ interface EcdsaRejection {
233
+ readonly what: string;
234
+ readonly signature: Uint8Array;
235
+ readonly message: Uint8Array;
236
+ readonly publicKey: Uint8Array;
237
+ }
238
+
239
+ /**
240
+ * The expected answers are @noble's under {@link ECDSA_VERIFY_OPTS}, written down rather than
241
+ * asked of @noble: its verify costs tens of milliseconds a call under Hermes, where this runs at
242
+ * app start. Signing is deterministic (RFC 6979), so the valid signature is fixed too.
243
+ */
244
+ function checkEcdsaVerify(member: EcdsaVerifyMember, curve: ECDSA, native: EcdsaVerifier): void {
245
+ const signature = curve.sign(CHECK_MESSAGE, CHECK_SEED, { lowS: true });
246
+ const compressed = curve.getPublicKey(CHECK_SEED);
247
+ const uncompressed = curve.getPublicKey(CHECK_SEED, false);
248
+ checkEcdsaAccepts(member, native, signature, compressed, '33-byte compressed');
249
+ checkEcdsaAccepts(member, native, signature, uncompressed, '65-byte uncompressed');
250
+ for (const vector of ecdsaRejections(curve, signature, compressed, uncompressed)) {
251
+ if (!rejectsOrThrows(() => native(offsetView(vector.signature), offsetView(vector.message), offsetView(vector.publicKey)))) {
252
+ throw backendRefused(member, `accepted ${vector.what}, which @noble/curves rejects`);
253
+ }
254
+ }
255
+ }
256
+
257
+ function checkEcdsaAccepts(
258
+ member: EcdsaVerifyMember,
259
+ native: EcdsaVerifier,
260
+ signature: Uint8Array,
261
+ publicKey: Uint8Array,
262
+ keyForm: string
263
+ ): void {
264
+ const accepted = runCheck(member, () => native(offsetView(signature), offsetView(CHECK_MESSAGE), offsetView(publicKey)));
265
+ if (accepted !== true) {
266
+ throw backendRefused(member, `did not accept a valid signature over a ${keyForm} public key`);
267
+ }
268
+ }
269
+
270
+ /**
271
+ * OpenSSL accepts the high-S copy and the hybrid key; it rejects the others, which guard
272
+ * native libraries that check less, and an adapter that verifies DER (`dsaEncoding: 'der'`, or
273
+ * a fallback to it). Every one is reachable by anyone who can write a row: flipping s to n − s,
274
+ * or re-encoding a key or a signature, needs no secret.
275
+ */
276
+ function ecdsaRejections(curve: ECDSA, signature: Uint8Array, compressed: Uint8Array, uncompressed: Uint8Array): EcdsaRejection[] {
277
+ const order = curve.Point.Fn.ORDER;
278
+ const width = signature.length / 2;
279
+ const r = signature.subarray(0, width);
280
+ const s = signature.subarray(width);
281
+ const scalar = (value: bigint): Uint8Array => hexToBytes(value.toString(16).padStart(width * 2, '0'));
282
+ const hybrid = uncompressed.slice();
283
+ hybrid[0] = 0x06 | (uncompressed[uncompressed.length - 1]! & 0x01);
284
+ return [
285
+ { what: 'a signature over a different message', signature, message: tamperedCheckMessage(), publicKey: compressed },
286
+ { what: 'a high-S signature', signature: concatBytes(r, scalar(order - BigInt(`0x${bytesToHex(s)}`))), message: CHECK_MESSAGE, publicKey: compressed },
287
+ { what: 'a signature with r = 0', signature: concatBytes(new Uint8Array(width), s), message: CHECK_MESSAGE, publicKey: compressed },
288
+ { what: 'a signature with r equal to the curve order', signature: concatBytes(scalar(order), s), message: CHECK_MESSAGE, publicKey: compressed },
289
+ { what: 'a hybrid-encoded (0x06/0x07) public key', signature, message: CHECK_MESSAGE, publicKey: hybrid },
290
+ { what: 'a DER-encoded signature', signature: curve.Signature.fromBytes(signature, 'compact').toBytes('der'), message: CHECK_MESSAGE, publicKey: compressed },
291
+ ];
292
+ }
293
+
294
+ function tamperedCheckMessage(): Uint8Array {
295
+ const tampered = CHECK_MESSAGE.slice();
296
+ tampered[0]! ^= 0x01;
297
+ return tampered;
298
+ }
299
+
300
+ /** For an input @noble rejects, a throw is a rejection, as the interface allows. */
209
301
  function rejectsOrThrows(attempt: () => boolean): boolean {
210
302
  try {
211
303
  return attempt() === false;
@@ -267,6 +359,25 @@ function ed25519Verify(signature: Uint8Array, message: Uint8Array, publicKey: Ui
267
359
  return native ? native(signature, message, publicKey) : ed25519.verify(signature, message, publicKey);
268
360
  }
269
361
 
362
+ /**
363
+ * What a native ECDSA member is checked against, spelled out rather than left to @noble's
364
+ * defaults (which equal it today), so a change of default cannot move @noble away from the
365
+ * semantics its self-check vectors encode: SHA-256 the message, reject high-S, take only the
366
+ * 64-byte compact r‖s form.
367
+ */
368
+ const ECDSA_VERIFY_OPTS: ECDSAVerifyOpts = Object.freeze({ prehash: true, lowS: true, format: 'compact' });
369
+
370
+ function ecdsaVerify(
371
+ member: EcdsaVerifyMember,
372
+ curve: ECDSA,
373
+ signature: Uint8Array,
374
+ message: Uint8Array,
375
+ publicKey: Uint8Array
376
+ ): boolean {
377
+ const native = currentBackend()?.[member];
378
+ return native ? native(signature, message, publicKey) : curve.verify(signature, message, publicKey, ECDSA_VERIFY_OPTS);
379
+ }
380
+
270
381
  // --- Algorithm / encoding resolution (selection done once, no per-call switching) --- //
271
382
 
272
383
  /**
@@ -644,10 +755,10 @@ export function verify(
644
755
 
645
756
  switch (curve) {
646
757
  case 'secp256k1': {
647
- return secp256k1.verify(sigBytes, dataBytes, keyBytes);
758
+ return ecdsaVerify('secp256k1Verify', secp256k1, sigBytes, dataBytes, keyBytes);
648
759
  }
649
760
  case 'p256': {
650
- return p256.verify(sigBytes, dataBytes, keyBytes);
761
+ return ecdsaVerify('p256Verify', p256, sigBytes, dataBytes, keyBytes);
651
762
  }
652
763
  case 'ed25519': {
653
764
  return ed25519Verify(sigBytes, dataBytes, keyBytes);
package/src/index.ts CHANGED
@@ -9,8 +9,9 @@
9
9
  * - verify: ECC signature verification
10
10
  * - hashMod: Hash with modulo for fixed-size outputs
11
11
  * - randomBytes: Generate cryptographically secure random bytes
12
- * - setCryptoBackend: Route SHA-256, SHA-512 and Ed25519 to a synchronous native
13
- * implementation for the whole process (checked against @noble when set)
12
+ * - setCryptoBackend: Route SHA-256, SHA-512, Ed25519, and P-256 and secp256k1 verify
13
+ * to a synchronous native implementation for the whole process (checked against
14
+ * @noble when set)
14
15
  *
15
16
  * All functions use base64url encoding by default for SQL compatibility.
16
17
  */