@optimystic/quereus-plugin-crypto 1.20.1 → 1.21.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/CHANGELOG.md CHANGED
@@ -1,5 +1,16 @@
1
1
  # Changelog
2
2
 
3
+ ## Unreleased — native crypto backend
4
+
5
+ - New `setCryptoBackend(backend)` and `CryptoBackend` exports. An application can route SHA-256,
6
+ SHA-512 and Ed25519 sign/verify to a synchronous native implementation for the whole process;
7
+ every member is optional and an omitted one stays on `@noble`. The setting reaches the JS API and
8
+ the SQL functions from the `/plugin` entry, including a plugin registered before the call.
9
+ - `setCryptoBackend` checks each supplied member against `@noble` on fixed inputs and throws, keeping
10
+ the previous backend, when one disagrees. `setCryptoBackend(undefined)` restores `@noble`.
11
+ - No behaviour change without a backend. See the README's
12
+ [Native crypto backend](README.md#native-crypto-backend) section.
13
+
3
14
  ## 0.14.0 — BREAKING: `digest` API rework
4
15
 
5
16
  ### What changed
package/README.md CHANGED
@@ -13,6 +13,7 @@ Quereus plugin providing cryptographic functions for SQL queries with base64url
13
13
  - **Verification Functions**: Signature verification for all supported curves
14
14
  - **Key Generation**: Generate and derive cryptographic keys
15
15
  - **Multiple Encodings**: Support for base64url, base64, hex, utf8, and raw bytes
16
+ - **Native Crypto Backend**: Optionally route SHA-256, SHA-512 and Ed25519 to a native library, checked against the JavaScript results when set
16
17
 
17
18
  ## Installation
18
19
 
@@ -345,6 +346,78 @@ break signature validation, so it is intentionally not offered for this function
345
346
  single database genuinely needs two digest configurations, register the plugin twice
346
347
  (or expose named variants) rather than flipping mutable session state.
347
348
 
349
+ ## Native crypto backend
350
+
351
+ By default every hash and signature runs in JavaScript (`@noble/hashes`, `@noble/curves`). On a
352
+ phone that already has fast native crypto, that is the slow part: on a Galaxy S7, one SQL `verify`
353
+ took 408 ms, 366 ms of it in JavaScript Ed25519, and every `digest` hashed with JavaScript SHA-256
354
+ even after the app routed `crypto.subtle.digest` to native code (this plugin never calls
355
+ `crypto.subtle`). `setCryptoBackend` routes SHA-256, SHA-512 and Ed25519 to a synchronous native
356
+ implementation for the whole process:
357
+
358
+ ```ts
359
+ import { setCryptoBackend } from '@optimystic/quereus-plugin-crypto';
360
+
361
+ setCryptoBackend({ sha256, sha512, ed25519Sign, ed25519Verify }); // every member optional
362
+ ```
363
+
364
+ - **What it speeds up.** `digest`, `cid`, `hash_mod`, `set_commit` and `set_verify` whenever they
365
+ hash with sha256 or sha512, and `sign` / `verify` with `'ed25519'`. BLAKE3, secp256k1 and P-256
366
+ stay on `@noble`, and so does any member the backend omits.
367
+ - **Set it once, at startup, for the whole process.** One call reaches the JS API and every
368
+ `Database`'s SQL functions, including those loaded from `@optimystic/quereus-plugin-crypto/plugin`
369
+ and those registered *before* the call: each hash and signature reads the installed backend when
370
+ it runs. `setCryptoBackend(undefined)` restores the `@noble` defaults. It is not a plugin load
371
+ option because plugin config is plain SQL values, which cannot carry functions, and because the
372
+ JS API is used with no plugin registration at all.
373
+ - **Checked when set.** Each member the backend supplies is run once against `@noble` on fixed
374
+ inputs: a hash must equal the `@noble/hashes` one; `ed25519Sign` must produce exactly the
375
+ `@noble/curves` signature for a fixed raw 32-byte seed (Ed25519 signing is deterministic);
376
+ `ed25519Verify` must accept that signature and reject it once one byte of the message is flipped.
377
+ The inputs are views at a non-zero offset into a larger buffer, so an adapter that hands the native
378
+ side `data.buffer` instead of the view fails too. On any failure `setCryptoBackend` throws, naming
379
+ the member, and the previously installed backend (or `@noble`) stays in place, so the mistake shows
380
+ at app start rather than as wrong signatures persisted and replicated.
381
+ - **Byte-identical, by requirement.** `digest`, `cid` and `set_commit` are `replicable`: their
382
+ outputs are signed and persisted, and every peer must compute the same bytes. A backend must
383
+ therefore agree with `@noble` on every input, not only the self-check's. The check catches an
384
+ adapter built wrong (wrong key shape, wrong bytes); it cannot prove a native library correct.
385
+ - **Errors.** A backend that throws inside `verify` makes it return `false`, exactly as a throw from
386
+ `@noble` does; in `sign`, `digest` and `cid` the throw propagates. A backend handed a malformed key
387
+ or signature must throw or return `false`, as `@noble` does. Every array a member returns must be
388
+ newly allocated: a raw-bytes result reaches the caller uncopied, so a library that reuses one output
389
+ buffer would rewrite results already returned.
390
+ - **Ed25519 strictness differs on crafted input.** `@noble` verifies under the ZIP-215 rule, which
391
+ accepts some non-canonical point encodings and small-order components that an RFC 8032-strict
392
+ library such as OpenSSL rejects. Honest signatures verify identically either way. A deliberately
393
+ crafted signature could verify on a machine without a backend and fail on one with it; that matters
394
+ only where peers re-execute a statement whose outcome depends on `verify`, which no Optimystic
395
+ deployment does today.
396
+
397
+ A working adapter for Node.js, on `node:crypto`. Raw Ed25519 keys are wrapped as DER (PKCS#8 for the
398
+ 32-byte seed, SPKI for the 32-byte public key) because that is the form the Node API takes:
399
+
400
+ ```ts
401
+ import { createHash, createPrivateKey, createPublicKey, sign, verify } from 'node:crypto';
402
+ import { setCryptoBackend } from '@optimystic/quereus-plugin-crypto';
403
+
404
+ const PKCS8_ED25519_PREFIX = Buffer.from('302e020100300506032b657004220420', 'hex');
405
+ const SPKI_ED25519_PREFIX = Buffer.from('302a300506032b6570032100', 'hex');
406
+
407
+ setCryptoBackend({
408
+ sha256: (data) => createHash('sha256').update(data).digest(),
409
+ sha512: (data) => createHash('sha512').update(data).digest(),
410
+ ed25519Sign: (message, secretKey) => sign(null, message,
411
+ createPrivateKey({ key: Buffer.concat([PKCS8_ED25519_PREFIX, secretKey]), format: 'der', type: 'pkcs8' })),
412
+ ed25519Verify: (signature, message, publicKey) => verify(null, message,
413
+ createPublicKey({ key: Buffer.concat([SPKI_ED25519_PREFIX, publicKey]), format: 'der', type: 'spki' }), signature),
414
+ });
415
+ ```
416
+
417
+ `react-native-quick-crypto` mirrors this API, so the same shape is the starting point on a phone.
418
+ Whether its synchronous Ed25519 accepts these keys unchanged has not been confirmed; if it does not,
419
+ `setCryptoBackend` throws at startup rather than producing wrong signatures.
420
+
348
421
  ## Supported Algorithms
349
422
 
350
423
  ### Hash Algorithms
@@ -503,7 +576,7 @@ Derive the public key from a private key.
503
576
 
504
577
  ## Security Notes
505
578
 
506
- - All cryptographic operations use audited libraries (@noble/*)
579
+ - All cryptographic operations use audited libraries (@noble/*), unless a [native crypto backend](#native-crypto-backend) is installed, in which case SHA-2 and Ed25519 run in that library
507
580
  - Private keys should be handled securely and never exposed
508
581
  - Random number generation uses platform CSPRNG (crypto.getRandomValues)
509
582
  - Signatures use deterministic k-generation (RFC 6979)
@@ -511,11 +584,14 @@ Derive the public key from a private key.
511
584
 
512
585
  ## React Native Compatibility
513
586
 
514
- These functions are fully compatible with React Native and don't require any native modules. They use:
587
+ These functions run on React Native without any native module. By default they use:
515
588
  - `@noble/curves` for elliptic curve operations
516
589
  - `@noble/hashes` for hashing
517
590
  - `crypto.getRandomValues()` for secure randomness (polyfill required for React Native)
518
591
 
592
+ An app that has native crypto can route SHA-256, SHA-512 and Ed25519 to it; see
593
+ [Native crypto backend](#native-crypto-backend).
594
+
519
595
  ## License
520
596
 
521
597
  MIT
package/dist/index.d.ts CHANGED
@@ -17,10 +17,38 @@ type DigestField = string | number | bigint | boolean | Uint8Array | null | unde
17
17
  type DigestHasher = (input: Uint8Array) => Uint8Array;
18
18
  /** A resolved output encoder: digest bytes in, encoded form out. */
19
19
  type OutputEncoder = (bytes: Uint8Array) => string | Uint8Array;
20
+ /**
21
+ * Synchronous native implementations; any omitted member falls back to @noble.
22
+ *
23
+ * Every member must give byte-identical results to @noble for the same input:
24
+ * `digest`, `cid` and `set_commit` are `replicable`, and their outputs are signed
25
+ * and persisted. {@link setCryptoBackend} checks each supplied member against
26
+ * @noble before installing it. A member handed a malformed key or signature must
27
+ * throw or return false, as @noble does; that is not checked. Each returned array
28
+ * must be freshly allocated: under the `bytes` encoding it reaches the caller
29
+ * uncopied, so a native library's reused output buffer would rewrite earlier results.
30
+ */
31
+ interface CryptoBackend {
32
+ sha256?(data: Uint8Array): Uint8Array;
33
+ sha512?(data: Uint8Array): Uint8Array;
34
+ /** Raw 64-byte signature, message, raw 32-byte public key. Returns false, or throws, for an invalid signature or key. */
35
+ ed25519Verify?(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array): boolean;
36
+ /** Message, raw 32-byte secret seed (the form noble and generatePrivateKey('ed25519') use). Returns the raw 64-byte signature. */
37
+ ed25519Sign?(message: Uint8Array, secretKey: Uint8Array): Uint8Array;
38
+ }
39
+ /**
40
+ * Install a backend for this process, or pass undefined to restore the @noble defaults.
41
+ * Throws, leaving the previous backend in place, if the backend fails its self-check.
42
+ *
43
+ * Set it once at startup. It takes effect on the next call everywhere, including in
44
+ * a plugin registered before it was set.
45
+ */
46
+ declare function setCryptoBackend(backend: CryptoBackend | undefined): void;
20
47
  /**
21
48
  * Resolve a hash algorithm name to its hasher. Throws on unknown algorithm.
22
49
  * Call once (e.g. at plugin registration) and capture the result so the digest
23
- * hot path performs no per-call algorithm branching.
50
+ * hot path performs no per-call algorithm branching. The returned hasher still
51
+ * honours a backend installed later by {@link setCryptoBackend}.
24
52
  */
25
53
  declare function resolveHasher(algorithm: HashAlgorithm): DigestHasher;
26
54
  /**
@@ -50,8 +78,8 @@ declare function resolveOutputEncoder(encoding: OutputEncoding): OutputEncoder;
50
78
  declare function encodeFields(fields: readonly DigestField[]): Uint8Array;
51
79
  /**
52
80
  * Low-level multi-field digest: canonically encode the fields, then hash and
53
- * encode with the supplied (pre-resolved) hasher/encoder. No per-call branching
54
- * on algorithm or encoding — resolve once via {@link resolveHasher} /
81
+ * encode with the supplied (pre-resolved) hasher/encoder. No per-call selection
82
+ * of algorithm or encoding — resolve once via {@link resolveHasher} /
55
83
  * {@link resolveOutputEncoder} and reuse.
56
84
  */
57
85
  declare function digestFields(fields: readonly DigestField[], hasher: DigestHasher, encode: OutputEncoder): string | Uint8Array;
@@ -177,7 +205,8 @@ declare function getPublicKey(privateKey: string | Uint8Array, curve?: CurveType
177
205
  * All framing/parsing comes from the audited `multiformats` library — there is
178
206
  * no bespoke byte-pushing here. The actual hashing reuses the same synchronous,
179
207
  * cross-platform `@noble/hashes` functions the rest of the plugin uses (via
180
- * {@link resolveHasher}), so the output is byte-identical to the CID an external
208
+ * {@link resolveHasher}, which routes sha2 to an installed native backend that must
209
+ * match them byte for byte), so the output is byte-identical to the CID an external
181
210
  * content-addressed store (IPFS/IPLD) computes for the same bytes:
182
211
  * `cid(utf8('hello world'))` === `bafkreifzjut3te2nhyekklss27nh3k72ysco7y32koao5eei66wof36n5e`.
183
212
  */
@@ -340,4 +369,4 @@ declare function setDisclose(leaves: readonly SaltedLeaf[], revealNames: readonl
340
369
  */
341
370
  declare function setVerify(root: string | Uint8Array, disclosure: SetDisclosure, hasher?: DigestHasher, encode?: OutputEncoder): boolean;
342
371
 
343
- export { type CidParts, type CurveType, type DigestField, type DigestHasher, type Encoding, type HashAlgorithm, type Multibase, type Multicodec, type MultihashCode, type OutputEncoder, type OutputEncoding, type SaltedLeaf, type SetDisclosure, cid, cidDecode, cidV1, digest, digestFields, encodeFields, generatePrivateKey, getPublicKey, hashMod, leafDigest, randomBytes, resolveHasher, resolveOutputEncoder, setCommit, setDisclose, setVerify, sign, verify };
372
+ export { type CidParts, type CryptoBackend, type CurveType, type DigestField, type DigestHasher, type Encoding, type HashAlgorithm, type Multibase, type Multicodec, type MultihashCode, type OutputEncoder, type OutputEncoding, type SaltedLeaf, type SetDisclosure, cid, cidDecode, cidV1, digest, digestFields, encodeFields, generatePrivateKey, getPublicKey, hashMod, leafDigest, randomBytes, resolveHasher, resolveOutputEncoder, setCommit, setCryptoBackend, setDisclose, setVerify, sign, verify };
package/dist/index.js CHANGED
@@ -1,6 +1,6 @@
1
- import { sha512, sha256 } from '@noble/hashes/sha2.js';
1
+ import { sha256, sha512 } from '@noble/hashes/sha2.js';
2
2
  import { blake3 } from '@noble/hashes/blake3.js';
3
- import { concatBytes, randomBytes as randomBytes$1, utf8ToBytes } from '@noble/hashes/utils.js';
3
+ import { utf8ToBytes, concatBytes, randomBytes as randomBytes$1 } from '@noble/hashes/utils.js';
4
4
  import { secp256k1 } from '@noble/curves/secp256k1.js';
5
5
  import { p256 } from '@noble/curves/nist.js';
6
6
  import { ed25519 } from '@noble/curves/ed25519.js';
@@ -53,9 +53,107 @@ function fromBytes(bytes, encoding = "base64url") {
53
53
  return toString(bytes, "base64url");
54
54
  }
55
55
  }
56
+ var BACKEND_KEY = /* @__PURE__ */ Symbol.for("@optimystic/quereus-plugin-crypto/backend");
57
+ var backendSlot = globalThis;
58
+ function currentBackend() {
59
+ return backendSlot[BACKEND_KEY];
60
+ }
61
+ function setCryptoBackend(backend) {
62
+ if (backend === void 0) {
63
+ delete backendSlot[BACKEND_KEY];
64
+ return;
65
+ }
66
+ const installed = snapshotBackend(backend);
67
+ selfCheckBackend(installed);
68
+ backendSlot[BACKEND_KEY] = installed;
69
+ }
70
+ function snapshotBackend(backend) {
71
+ var _a, _b, _c, _d;
72
+ return Object.freeze({
73
+ sha256: (_a = backend.sha256) == null ? void 0 : _a.bind(backend),
74
+ sha512: (_b = backend.sha512) == null ? void 0 : _b.bind(backend),
75
+ ed25519Verify: (_c = backend.ed25519Verify) == null ? void 0 : _c.bind(backend),
76
+ ed25519Sign: (_d = backend.ed25519Sign) == null ? void 0 : _d.bind(backend)
77
+ });
78
+ }
79
+ var CHECK_MESSAGE = utf8ToBytes("@optimystic/quereus-plugin-crypto backend self-check");
80
+ var CHECK_SEED = Uint8Array.from({ length: 32 }, (_, i) => i + 1);
81
+ function selfCheckBackend(backend) {
82
+ if (backend.sha256) checkHash("sha256", backend.sha256, sha256);
83
+ if (backend.sha512) checkHash("sha512", backend.sha512, sha512);
84
+ if (backend.ed25519Sign) checkEd25519Sign(backend.ed25519Sign);
85
+ if (backend.ed25519Verify) checkEd25519Verify(backend.ed25519Verify);
86
+ }
87
+ function checkHash(member, native, noble) {
88
+ const actual = runCheck(member, () => native(offsetView(CHECK_MESSAGE)));
89
+ if (!sameBytes(actual, noble(CHECK_MESSAGE))) {
90
+ throw backendRefused(member, "returned a different hash than @noble/hashes for the same input");
91
+ }
92
+ }
93
+ function checkEd25519Sign(native) {
94
+ const actual = runCheck("ed25519Sign", () => native(offsetView(CHECK_MESSAGE), offsetView(CHECK_SEED)));
95
+ if (!sameBytes(actual, ed25519.sign(CHECK_MESSAGE, CHECK_SEED))) {
96
+ throw backendRefused("ed25519Sign", "returned a different signature than @noble/curves for the same raw 32-byte seed and message");
97
+ }
98
+ }
99
+ function checkEd25519Verify(native) {
100
+ const signature = ed25519.sign(CHECK_MESSAGE, CHECK_SEED);
101
+ const publicKey = ed25519.getPublicKey(CHECK_SEED);
102
+ const accepted = runCheck("ed25519Verify", () => native(offsetView(signature), offsetView(CHECK_MESSAGE), offsetView(publicKey)));
103
+ if (accepted !== true) {
104
+ throw backendRefused("ed25519Verify", "did not accept a valid signature over a raw 32-byte public key");
105
+ }
106
+ const tampered = CHECK_MESSAGE.slice();
107
+ tampered[0] ^= 1;
108
+ if (rejectsOrThrows(() => native(offsetView(signature), offsetView(tampered), offsetView(publicKey)))) {
109
+ return;
110
+ }
111
+ throw backendRefused("ed25519Verify", "accepted a signature over a different message");
112
+ }
113
+ function rejectsOrThrows(attempt) {
114
+ try {
115
+ return attempt() === false;
116
+ } catch {
117
+ return true;
118
+ }
119
+ }
120
+ function runCheck(member, attempt) {
121
+ try {
122
+ return attempt();
123
+ } catch (cause) {
124
+ throw new Error(`setCryptoBackend: ${member} threw during its self-check; the backend was not installed`, { cause });
125
+ }
126
+ }
127
+ function backendRefused(member, reason) {
128
+ return new Error(`setCryptoBackend: ${member} ${reason}; the backend was not installed`);
129
+ }
130
+ function sameBytes(actual, expected) {
131
+ return actual instanceof Uint8Array && bytesToHex(actual) === bytesToHex(expected);
132
+ }
133
+ function offsetView(bytes) {
134
+ const buffer = new Uint8Array(bytes.length + 2);
135
+ buffer.set(bytes, 1);
136
+ return buffer.subarray(1, 1 + bytes.length);
137
+ }
138
+ function dispatchHash(member, noble) {
139
+ return (input) => {
140
+ var _a;
141
+ return (((_a = currentBackend()) == null ? void 0 : _a[member]) ?? noble)(input);
142
+ };
143
+ }
144
+ function ed25519Sign(message, secretKey) {
145
+ var _a;
146
+ const native = (_a = currentBackend()) == null ? void 0 : _a.ed25519Sign;
147
+ return native ? native(message, secretKey) : ed25519.sign(message, secretKey);
148
+ }
149
+ function ed25519Verify(signature, message, publicKey) {
150
+ var _a;
151
+ const native = (_a = currentBackend()) == null ? void 0 : _a.ed25519Verify;
152
+ return native ? native(signature, message, publicKey) : ed25519.verify(signature, message, publicKey);
153
+ }
56
154
  var HASHERS = {
57
- sha256,
58
- sha512,
155
+ sha256: dispatchHash("sha256", sha256),
156
+ sha512: dispatchHash("sha512", sha512),
59
157
  blake3
60
158
  };
61
159
  var OUTPUT_ENCODERS = {
@@ -206,7 +304,7 @@ function sign(data, privateKey, curve = "secp256k1", inputEncoding = "base64url"
206
304
  sigBytes = p256.sign(dataBytes, keyBytes, { lowS: true });
207
305
  break;
208
306
  case "ed25519":
209
- sigBytes = ed25519.sign(dataBytes, keyBytes);
307
+ sigBytes = ed25519Sign(dataBytes, keyBytes);
210
308
  break;
211
309
  default:
212
310
  throw new Error(`Unsupported curve: ${curve}`);
@@ -226,7 +324,7 @@ function verify(data, signature, publicKey, curve = "secp256k1", inputEncoding =
226
324
  return p256.verify(sigBytes, dataBytes, keyBytes);
227
325
  }
228
326
  case "ed25519": {
229
- return ed25519.verify(sigBytes, dataBytes, keyBytes);
327
+ return ed25519Verify(sigBytes, dataBytes, keyBytes);
230
328
  }
231
329
  default:
232
330
  throw new Error(`Unsupported curve: ${curve}`);
@@ -436,6 +534,6 @@ function setVerify(root, disclosure, hasher = resolveHasher("sha256"), encode =
436
534
  }
437
535
  }
438
536
 
439
- export { cid, cidDecode, cidV1, digest, digestFields, encodeFields, generatePrivateKey, getPublicKey, hashMod, leafDigest, randomBytes, resolveHasher, resolveOutputEncoder, setCommit, setDisclose, setVerify, sign, verify };
537
+ export { cid, cidDecode, cidV1, digest, digestFields, encodeFields, generatePrivateKey, getPublicKey, hashMod, leafDigest, randomBytes, resolveHasher, resolveOutputEncoder, setCommit, setCryptoBackend, setDisclose, setVerify, sign, verify };
440
538
  //# sourceMappingURL=index.js.map
441
539
  //# sourceMappingURL=index.js.map