@optimystic/quereus-plugin-crypto 1.20.0 → 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/src/crypto.ts CHANGED
@@ -90,12 +90,192 @@ function fromBytes(bytes: Uint8Array, encoding: Encoding = 'base64url'): string
90
90
  }
91
91
  }
92
92
 
93
- // --- Algorithm / encoding resolution (done once, no per-call switching) --- //
93
+ // --- Native crypto backend (process-wide, optional) --- //
94
94
 
95
- /** Hash algorithm → noble hasher. Keyed lookup so the digest hot path never branches. */
95
+ /**
96
+ * Synchronous native implementations; any omitted member falls back to @noble.
97
+ *
98
+ * Every member must give byte-identical results to @noble for the same input:
99
+ * `digest`, `cid` and `set_commit` are `replicable`, and their outputs are signed
100
+ * and persisted. {@link setCryptoBackend} checks each supplied member against
101
+ * @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.
105
+ */
106
+ export interface CryptoBackend {
107
+ sha256?(data: Uint8Array): Uint8Array;
108
+ sha512?(data: Uint8Array): Uint8Array;
109
+ /** Raw 64-byte signature, message, raw 32-byte public key. Returns false, or throws, for an invalid signature or key. */
110
+ ed25519Verify?(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array): boolean;
111
+ /** Message, raw 32-byte secret seed (the form noble and generatePrivateKey('ed25519') use). Returns the raw 64-byte signature. */
112
+ ed25519Sign?(message: Uint8Array, secretKey: Uint8Array): Uint8Array;
113
+ }
114
+
115
+ type BackendMember = keyof CryptoBackend;
116
+
117
+ /**
118
+ * The installed backend lives on `globalThis` rather than in a module variable:
119
+ * `dist/index.js` and `dist/plugin.js` are built as separate entries, each with its
120
+ * own copy of this module, and a second installed copy of the package has its own
121
+ * too. A `Symbol.for` key is the one slot all of them share.
122
+ */
123
+ const BACKEND_KEY: unique symbol = Symbol.for('@optimystic/quereus-plugin-crypto/backend');
124
+
125
+ interface BackendSlot {
126
+ [BACKEND_KEY]?: CryptoBackend;
127
+ }
128
+
129
+ const backendSlot = globalThis as BackendSlot;
130
+
131
+ function currentBackend(): CryptoBackend | undefined {
132
+ return backendSlot[BACKEND_KEY];
133
+ }
134
+
135
+ /**
136
+ * Install a backend for this process, or pass undefined to restore the @noble defaults.
137
+ * Throws, leaving the previous backend in place, if the backend fails its self-check.
138
+ *
139
+ * Set it once at startup. It takes effect on the next call everywhere, including in
140
+ * a plugin registered before it was set.
141
+ */
142
+ export function setCryptoBackend(backend: CryptoBackend | undefined): void {
143
+ if (backend === undefined) {
144
+ delete backendSlot[BACKEND_KEY];
145
+ return;
146
+ }
147
+ const installed = snapshotBackend(backend);
148
+ selfCheckBackend(installed);
149
+ backendSlot[BACKEND_KEY] = installed;
150
+ }
151
+
152
+ /**
153
+ * Copy the supplied members, bound to their object, into a frozen record. What is
154
+ * installed is then exactly what the self-check ran: a member added to or replaced on
155
+ * the caller's object later is never reached, and neither is a member this copy of
156
+ * the package does not know how to check.
157
+ */
158
+ function snapshotBackend(backend: CryptoBackend): CryptoBackend {
159
+ return Object.freeze({
160
+ sha256: backend.sha256?.bind(backend),
161
+ sha512: backend.sha512?.bind(backend),
162
+ ed25519Verify: backend.ed25519Verify?.bind(backend),
163
+ ed25519Sign: backend.ed25519Sign?.bind(backend),
164
+ });
165
+ }
166
+
167
+ const CHECK_MESSAGE = utf8ToBytes('@optimystic/quereus-plugin-crypto backend self-check');
168
+ const CHECK_SEED = Uint8Array.from({ length: 32 }, (_, i) => i + 1);
169
+
170
+ /** Known-answer check of every member the backend supplies, against @noble. */
171
+ function selfCheckBackend(backend: CryptoBackend): void {
172
+ if (backend.sha256) checkHash('sha256', backend.sha256, sha256);
173
+ if (backend.sha512) checkHash('sha512', backend.sha512, sha512);
174
+ if (backend.ed25519Sign) checkEd25519Sign(backend.ed25519Sign);
175
+ if (backend.ed25519Verify) checkEd25519Verify(backend.ed25519Verify);
176
+ }
177
+
178
+ function checkHash(member: BackendMember, native: DigestHasher, noble: DigestHasher): void {
179
+ const actual = runCheck(member, () => native(offsetView(CHECK_MESSAGE)));
180
+ if (!sameBytes(actual, noble(CHECK_MESSAGE))) {
181
+ throw backendRefused(member, 'returned a different hash than @noble/hashes for the same input');
182
+ }
183
+ }
184
+
185
+ /** Ed25519 signing is deterministic (RFC 8032), so noble's signature is the known answer. */
186
+ function checkEd25519Sign(native: NonNullable<CryptoBackend['ed25519Sign']>): void {
187
+ const actual = runCheck('ed25519Sign', () => native(offsetView(CHECK_MESSAGE), offsetView(CHECK_SEED)));
188
+ if (!sameBytes(actual, ed25519.sign(CHECK_MESSAGE, CHECK_SEED))) {
189
+ throw backendRefused('ed25519Sign', 'returned a different signature than @noble/curves for the same raw 32-byte seed and message');
190
+ }
191
+ }
192
+
193
+ function checkEd25519Verify(native: NonNullable<CryptoBackend['ed25519Verify']>): void {
194
+ const signature = ed25519.sign(CHECK_MESSAGE, CHECK_SEED);
195
+ const publicKey = ed25519.getPublicKey(CHECK_SEED);
196
+ const accepted = runCheck('ed25519Verify', () => native(offsetView(signature), offsetView(CHECK_MESSAGE), offsetView(publicKey)));
197
+ if (accepted !== true) {
198
+ throw backendRefused('ed25519Verify', 'did not accept a valid signature over a raw 32-byte public key');
199
+ }
200
+ const tampered = CHECK_MESSAGE.slice();
201
+ tampered[0]! ^= 0x01;
202
+ if (rejectsOrThrows(() => native(offsetView(signature), offsetView(tampered), offsetView(publicKey)))) {
203
+ return;
204
+ }
205
+ throw backendRefused('ed25519Verify', 'accepted a signature over a different message');
206
+ }
207
+
208
+ /** For the tampered vector a throw is a rejection, as the interface allows. */
209
+ function rejectsOrThrows(attempt: () => boolean): boolean {
210
+ try {
211
+ return attempt() === false;
212
+ } catch {
213
+ return true;
214
+ }
215
+ }
216
+
217
+ function runCheck<T>(member: BackendMember, attempt: () => T): T {
218
+ try {
219
+ return attempt();
220
+ } catch (cause) {
221
+ throw new Error(`setCryptoBackend: ${member} threw during its self-check; the backend was not installed`, { cause });
222
+ }
223
+ }
224
+
225
+ function backendRefused(member: BackendMember, reason: string): Error {
226
+ return new Error(`setCryptoBackend: ${member} ${reason}; the backend was not installed`);
227
+ }
228
+
229
+ /**
230
+ * Compared through hex rather than a byte-equality import: the `/plugin` bundle drops the
231
+ * setter, and an import only it used would be left dangling there. Runs once per backend.
232
+ */
233
+ function sameBytes(actual: unknown, expected: Uint8Array): boolean {
234
+ return actual instanceof Uint8Array && bytesToHex(actual) === bytesToHex(expected);
235
+ }
236
+
237
+ /**
238
+ * A copy of `bytes` at a non-zero offset inside a larger buffer. The plugin routinely
239
+ * hands a hasher a view into a larger buffer, so an adapter that passes the native side
240
+ * `data.buffer` instead of the view fails here rather than hashing the wrong bytes.
241
+ */
242
+ function offsetView(bytes: Uint8Array): Uint8Array {
243
+ const buffer = new Uint8Array(bytes.length + 2);
244
+ buffer.set(bytes, 1);
245
+ return buffer.subarray(1, 1 + bytes.length);
246
+ }
247
+
248
+ /** A hasher that reads the installed backend on every call, so one set after registration still applies. */
249
+ function dispatchHash(member: 'sha256' | 'sha512', noble: DigestHasher): DigestHasher {
250
+ return (input) => (currentBackend()?.[member] ?? noble)(input);
251
+ }
252
+
253
+ function ed25519Sign(message: Uint8Array, secretKey: Uint8Array): Uint8Array {
254
+ const native = currentBackend()?.ed25519Sign;
255
+ return native ? native(message, secretKey) : ed25519.sign(message, secretKey);
256
+ }
257
+
258
+ function ed25519Verify(signature: Uint8Array, message: Uint8Array, publicKey: Uint8Array): boolean {
259
+ const native = currentBackend()?.ed25519Verify;
260
+ // NOTE: @noble verifies under ZIP-215 (accepts some non-canonical encodings and small-order
261
+ // components) while an RFC 8032-strict native library such as OpenSSL rejects them. Honest
262
+ // signatures verify the same either way, and the self-check cannot test this without refusing
263
+ // every strict backend. Harmless while no peer re-executes a statement whose outcome depends on
264
+ // `verify` (no deployment validates transactions at pend today); once one does, a crafted
265
+ // signature could verify on a machine with a backend and not on one without. Switching noble to
266
+ // `zip215: false` was rejected: it changes existing results and still differs on small-order keys.
267
+ return native ? native(signature, message, publicKey) : ed25519.verify(signature, message, publicKey);
268
+ }
269
+
270
+ // --- Algorithm / encoding resolution (selection done once, no per-call switching) --- //
271
+
272
+ /**
273
+ * Hash algorithm → hasher. Keyed lookup so the digest hot path never branches on the
274
+ * algorithm; sha256 and sha512 read the installed backend per call (one property read).
275
+ */
96
276
  const HASHERS: Record<HashAlgorithm, DigestHasher> = {
97
- sha256,
98
- sha512,
277
+ sha256: dispatchHash('sha256', sha256),
278
+ sha512: dispatchHash('sha512', sha512),
99
279
  blake3,
100
280
  };
101
281
 
@@ -110,7 +290,8 @@ const OUTPUT_ENCODERS: Record<OutputEncoding, OutputEncoder> = {
110
290
  /**
111
291
  * Resolve a hash algorithm name to its hasher. Throws on unknown algorithm.
112
292
  * Call once (e.g. at plugin registration) and capture the result so the digest
113
- * hot path performs no per-call algorithm branching.
293
+ * hot path performs no per-call algorithm branching. The returned hasher still
294
+ * honours a backend installed later by {@link setCryptoBackend}.
114
295
  */
115
296
  export function resolveHasher(algorithm: HashAlgorithm): DigestHasher {
116
297
  const hasher = HASHERS[algorithm];
@@ -283,8 +464,8 @@ export function encodeFields(fields: readonly DigestField[]): Uint8Array {
283
464
 
284
465
  /**
285
466
  * Low-level multi-field digest: canonically encode the fields, then hash and
286
- * encode with the supplied (pre-resolved) hasher/encoder. No per-call branching
287
- * on algorithm or encoding — resolve once via {@link resolveHasher} /
467
+ * encode with the supplied (pre-resolved) hasher/encoder. No per-call selection
468
+ * of algorithm or encoding — resolve once via {@link resolveHasher} /
288
469
  * {@link resolveOutputEncoder} and reuse.
289
470
  */
290
471
  export function digestFields(
@@ -417,7 +598,7 @@ export function sign(
417
598
  sigBytes = p256.sign(dataBytes, keyBytes, { lowS: true });
418
599
  break;
419
600
  case 'ed25519':
420
- sigBytes = ed25519.sign(dataBytes, keyBytes);
601
+ sigBytes = ed25519Sign(dataBytes, keyBytes);
421
602
  break;
422
603
  default:
423
604
  throw new Error(`Unsupported curve: ${curve}`);
@@ -469,7 +650,7 @@ export function verify(
469
650
  return p256.verify(sigBytes, dataBytes, keyBytes);
470
651
  }
471
652
  case 'ed25519': {
472
- return ed25519.verify(sigBytes, dataBytes, keyBytes);
653
+ return ed25519Verify(sigBytes, dataBytes, keyBytes);
473
654
  }
474
655
  default:
475
656
  throw new Error(`Unsupported curve: ${curve}`);
package/src/index.ts CHANGED
@@ -9,6 +9,8 @@
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
14
  *
13
15
  * All functions use base64url encoding by default for SQL compatibility.
14
16
  */
@@ -26,6 +28,8 @@ export {
26
28
  randomBytes,
27
29
  generatePrivateKey,
28
30
  getPublicKey,
31
+ setCryptoBackend,
32
+ type CryptoBackend,
29
33
  type HashAlgorithm,
30
34
  type CurveType,
31
35
  type Encoding,
package/src/plugin.ts CHANGED
@@ -114,9 +114,11 @@ const NON_DETERMINISTIC_FLAGS = FunctionFlags.UTF8;
114
114
  */
115
115
  export default function register(_db: Database, config: Record<string, SqlValue> = {}) {
116
116
  // Resolve the digest algorithm + output encoding ONCE, at registration, from
117
- // load-time config — so the per-call path never branches on them, and so the
117
+ // load-time config — so the per-call path never selects between them, and so the
118
118
  // digest is stable for the lifetime of the database (a precondition for
119
119
  // `replicable`: every peer that loads the plugin with the same config agrees).
120
+ // The resolved hasher still reads the process-wide crypto backend per call, so a
121
+ // backend set after registration applies; it is byte-identical to @noble by contract.
120
122
  const digestHasher = resolveHasher(configAlgorithm(config));
121
123
  const digestEncoder = resolveOutputEncoder(configEncoding(config));
122
124