@optimystic/quereus-plugin-crypto 1.5.0 → 1.6.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/README.md CHANGED
@@ -1,522 +1,522 @@
1
- # @optimystic/quereus-plugin-crypto
2
-
3
- Quereus plugin providing cryptographic functions for SQL queries with base64url encoding by default.
4
-
5
- ## Features
6
-
7
- - **Hash Functions**: SHA-256, SHA-512, BLAKE3 hashing with base64url output
8
- - **Content Identifiers (CIDv1)**: Self-describing, interoperable IPFS/IPLD content addresses
9
- - **Selective Disclosure**: Salted-leaf set commitment — commit to a whole attribute set with one value, later reveal only a chosen subset with proof of authenticity
10
- - **Hash Modulo**: Fixed-size hash values (16-bit, 32-bit, etc.) for sharding and partitioning
11
- - **Random Bytes**: Generate cryptographically secure random bytes (default: 256 bits)
12
- - **Signature Functions**: secp256k1, P-256, Ed25519 signing with base64url encoding
13
- - **Verification Functions**: Signature verification for all supported curves
14
- - **Key Generation**: Generate and derive cryptographic keys
15
- - **Multiple Encodings**: Support for base64url, base64, hex, utf8, and raw bytes
16
-
17
- ## Installation
18
-
19
- ```bash
20
- npm install @optimystic/quereus-plugin-crypto
21
- ```
22
-
23
- ## Usage
24
-
25
- ### As a Quereus Plugin
26
-
27
- ```typescript
28
- import { Database } from '@quereus/quereus';
29
- import { loadPlugin } from '@quereus/quereus/util/plugin-loader.js';
30
-
31
- const db = new Database();
32
- await loadPlugin('npm:@optimystic/quereus-plugin-crypto', db);
33
-
34
- // Or configure the digest algorithm / output encoding once, at load time
35
- // (see "Digest configuration" below):
36
- await loadPlugin('npm:@optimystic/quereus-plugin-crypto', db, {
37
- algorithm: 'sha256', // 'sha256' (default) | 'sha512' | 'blake3'
38
- encoding: 'base64url', // 'base64url' (default) | 'base64' | 'hex'
39
- });
40
- ```
41
-
42
- ### Direct Import (for JavaScript/TypeScript code)
43
-
44
- All cryptographic functions are also exported directly so you can use the same implementations in your JavaScript code:
45
-
46
- ```typescript
47
- import {
48
- digest,
49
- hashMod,
50
- randomBytes,
51
- sign,
52
- verify,
53
- generatePrivateKey,
54
- getPublicKey
55
- } from '@optimystic/quereus-plugin-crypto';
56
-
57
- // Hash an ordered tuple of fields (injective — distinct tuples never collide)
58
- const hash = digest(['hello world', 42, null], 'sha256', 'base64url');
59
-
60
- // Get a 16-bit hash for sharding
61
- const shard = hashMod('user@example.com', 16, 'sha256', 'utf8');
62
-
63
- // Generate random bytes (256 bits by default)
64
- const nonce = randomBytes(256, 'base64url');
65
- const salt = randomBytes(128, 'hex');
66
-
67
- // Generate keys
68
- const privateKey = generatePrivateKey('secp256k1', 'base64url');
69
- const publicKey = getPublicKey(privateKey, 'secp256k1', 'base64url', 'base64url');
70
-
71
- // Sign and verify
72
- const signature = sign(hash, privateKey, 'secp256k1', 'base64url', 'base64url', 'base64url');
73
- const isValid = verify(hash, signature, publicKey, 'secp256k1', 'base64url', 'base64url', 'base64url');
74
- ```
75
-
76
- ## SQL Functions
77
-
78
- All SQL functions use **base64url encoding by default** for inputs and outputs. This is URL-safe and SQL-friendly.
79
-
80
- ### digest(field1, field2, ..., fieldN)
81
-
82
- Hash an **ordered tuple of fields** into a single digest. `digest` is variadic over
83
- *data* — every argument is a field, not a configuration option. The algorithm and
84
- output encoding are chosen once, at load time (see [Digest configuration](#digest-configuration)),
85
- so they never have to be passed per call.
86
-
87
- ```sql
88
- -- Hash a single value
89
- SELECT digest(Id) as hash;
90
-
91
- -- Hash a tuple of columns — distinct tuples never collide,
92
- -- NULL is distinguished from '', and 123 from '123'
93
- SELECT digest(Tid, Name, ImageRef, NumberRequiredTSAs) as commitment;
94
- ```
95
-
96
- **Why variadic + injective?** Hashing several fields by joining them
97
- (`a || '|' || b`) or by `String()`-concatenation is not injective: `('a|b','c')`
98
- collides with `('a','b|c')`, `NULL` collides with `''`, and `123` collides with
99
- `'123'`. `digest` instead applies a canonical, length-prefixed, type-tagged framing
100
- to each field, so distinct tuples always produce distinct digests. This matters when
101
- the digest is signed or persisted as a commitment.
102
-
103
- The framing is also why `digest(x)` is **not** a bare `sha256(x)` — it is a framed
104
- digest of a one-element tuple. For sharding a single value, use `hash_mod`.
105
-
106
- ### cid(data, codec?, hash?, base?) / cid_v1(digest, hash, codec?, base?) / cid_decode(cid)
107
-
108
- `digest` returns a **bare** hash — raw digest bytes in some text encoding, with no
109
- record of which base, content type, or hash algorithm produced it. `cid` instead
110
- produces a **self-describing CIDv1**, the same interoperable content address an
111
- IPFS/IPLD store computes for the same bytes:
112
-
113
- ```
114
- CIDv1 = multibase( version ‖ multicodec(content-type) ‖ multihash )
115
- multihash = hashFnCode ‖ digestLength ‖ digestBytes
116
- ```
117
-
118
- Because the multibase, content codec, and hash code all travel *inside* the value,
119
- a consumer can validate it without out-of-band knowledge, and an algorithm
120
- migration (e.g. sha2-256 → another hash) is unambiguous rather than a silent
121
- reinterpretation. The framing comes entirely from the audited
122
- [`multiformats`](https://github.com/multiformats/js-multiformats) library.
123
-
124
- ```sql
125
- -- Hash a blob and frame it as the canonical raw/sha2-256/base32 CID
126
- -- (== the CID IPFS shows for the same bytes)
127
- SELECT cid(SomeBlob) AS Cid;
128
-
129
- -- Pick content codec / hash / base
130
- SELECT cid(SomeBlob, 'dag-cbor', 'sha2-512', 'base58btc') AS Cid;
131
-
132
- -- A self-describing content address over a field tuple: digest() canonically
133
- -- frames + hashes the fields; cid_v1() wraps that exact digest as a CIDv1
134
- -- (no double-hash). The asserted hash must match digest()'s configured algorithm.
135
- SELECT cid_v1(digest(ColA, ColB, ColC), 'sha2-256') AS Cid;
136
-
137
- -- Validate / inspect a stored CID (returns JSON: { version, codec, hashCode, digest })
138
- SELECT cid_decode(Cid) ->> 'codec' AS codec FROM T;
139
- ```
140
-
141
- - **`cid(data, codec?, hash?, base?)`** — hash `data` then frame. `data` is a BLOB,
142
- or a base64url-encoded TEXT digest/blob (the plugin's canonical text encoding).
143
- Defaults: `codec='raw'`, `hash='sha2-256'`, `base='base32'`.
144
- - **`cid_v1(digest, hash, codec?, base?)`** — wrap an **already-computed** digest
145
- without re-hashing. `hash` is required and asserts which algorithm produced the
146
- digest; the digest length is checked against it (sha2-256/blake3 = 32 bytes,
147
- sha2-512 = 64) and a mismatch is rejected.
148
- - **`cid_decode(cid) → JSON`** — parse a CID back to `{ version, codec, hashCode,
149
- digest }` (digest as base64url). Throws cleanly on malformed input.
150
-
151
- Selectable values: `codec` ∈ `raw`, `dag-cbor`; `hash` ∈ `sha2-256`, `sha2-512`,
152
- `blake3`; `base` ∈ `base32` (default), `base58btc`, `base64url`, `base16`.
153
-
154
- **Why `base32` by default?** A CID's whole purpose is to match what an external
155
- content-addressed store computes, and IPFS renders CIDv1 canonically in base32 (the
156
- `b…` prefix). This is deliberately different from the plugin's `digest`/`random_bytes`
157
- default of base64url: base64url is compact for *internal* values that live in memory,
158
- on the wire, or in JSON, whereas base32 is case-insensitive and DNS/URL/filename-safe
159
- where interoperable addresses are copied and read. Two audiences, two defaults — pass
160
- `'base64url'` explicitly if you want the compact form.
161
-
162
- ### set_commit(leaves_json) / set_verify(root, disclosed_json, hidden_json)
163
-
164
- **Per-attribute selective disclosure.** An authority commits to a registrant's whole
165
- attribute set as a single root (which it signs / persists), then later reveals only a
166
- chosen *subset* to a recipient — with a proof the revealed values are genuinely the
167
- committed ones — **without** leaking the withheld attribute values. A flat
168
- `digest(whole set)` can't do this (verifying one field needs the whole pre-image, so
169
- it's all-or-nothing); `set_commit` supports *partial opening*.
170
-
171
- Each attribute becomes a salted leaf, and the root is the digest of all leaf digests in
172
- canonical (sort-by-leaf-digest-bytes) order:
173
-
174
- ```
175
- leafDigest = digest([SD_LEAF_DOMAIN_V1, name, value, salt]) -- raw digest bytes
176
- root = digest([SD_SET_DOMAIN_V1, sortedLeaf_0, sortedLeaf_1, ...])
177
- ```
178
-
179
- This is the same flat salted-hash shape the IETF SD-JWT standard
180
- (`draft-ietf-oauth-selective-disclosure-jwt`) settled on rather than a Merkle tree —
181
- cited as conceptual precedent only; the framing here is Optimystic's own `digest`
182
- `encodeFields` (not SD-JWT wire-compatible). The `name` is hashed into the leaf so a
183
- `(value, salt)` proof can't be replayed under another attribute; the `salt` is per-leaf
184
- and **mandatory** (low-entropy values like a DOB or a boolean are brute-forceable from a
185
- bare hash, and independent salts defeat cross-registrant correlation).
186
-
187
- ```sql
188
- -- Commit to a JSON array of [name, value, salt] leaves -> single root.
189
- -- Pair with cid() for the self-describing persisted/signed column representation:
190
- SELECT cid(set_commit(SelectiveDetails)) AS SelectiveCid;
191
-
192
- -- A schema CHECK makes a forged root impossible to store: the root is recomputed from
193
- -- the stored attribute triples, so SelectiveCid must equal the genuine commitment.
194
- CREATE TABLE Registrant (
195
- ...,
196
- SelectiveDetails TEXT, -- JSON array of [name, value, salt] triples
197
- SelectiveCid TEXT,
198
- CHECK (SelectiveCid = cid(set_commit(SelectiveDetails)))
199
- );
200
-
201
- -- A recipient verifies a disclosure: the disclosed [name, value, salt] triples plus
202
- -- the opaque leaf digests of the withheld leaves reconstruct the entire root.
203
- SELECT set_verify(root, disclosed_json, hidden_json) AS ok;
204
- ```
205
-
206
- - **`set_commit(leaves_json) → TEXT`** — `leaves_json` is a JSON array; each element is a
207
- leaf `[name, value, salt]` *or* `{ "name", "value", "salt" }`. Values follow `digest`'s
208
- rules as parsed from JSON (INTEGER vs REAL by JS value, TEXT, BOOL, null, nested
209
- object/array). Each leaf must carry all three fields — a missing `value` (object form) or
210
- a `[name, value]` array (under three elements) throws; pass `value: null` for a null-valued
211
- attribute. The salt is base64url TEXT (e.g. from `random_bytes`). **THROWS** on a duplicate
212
- name, a missing value, a missing/empty salt, or unparseable/non-array JSON (invalid states
213
- made impossible). `replicable` — the root is signed and persisted, same bar as `digest`.
214
- - **`set_verify(root, disclosed_json, hidden_json) → BOOLEAN`** — `disclosed_json` is the
215
- opened triples (same leaf shape), `hidden_json` a JSON array of the withheld leaves'
216
- opaque base64url digests. Reconstructs the **entire** root and compares — so the holder
217
- cannot add, drop, or swap a leaf. Returns `false` on any mismatch or malformed input
218
- (forgiving, like `verify`).
219
-
220
- > **Disclosure generation is JS-only** (`setDisclose`, below) — there's no SQL
221
- > `set_disclose`, because building a disclosure requires the full attribute set including
222
- > the secret salts, which lives engine-side, not in a query.
223
-
224
- **BLOB-valued attributes via SQL:** JSON has no blob type, so a blob attribute passed
225
- through `set_commit` is committed as its base64url TEXT. Callers needing a *true* BLOB
226
- value (committed as a BLOB field, `TAG_BLOB`) must use the JS `setCommit` with a
227
- `Uint8Array` value.
228
-
229
- **Privacy note:** a fixed commitment disclosed to two audiences exposes the same hidden
230
- digests and field count to both, so they can correlate that it's the same record.
231
- Re-randomizing per disclosure would require fresh salts → a new root → a new signature
232
- (out of scope here).
233
-
234
- **Framing coupling:** leaf and root reuse `digest`'s `encodeFields`, so a future digest
235
- framing-version bump changes `set_commit` output too — intentional (one canonical
236
- framing), but it means the pinned set-commitment vectors move with the digest vectors.
237
-
238
- ### hash_mod(data, bits, algorithm?, inputEncoding?)
239
-
240
- Hash data and return modulo 2^bits for fixed-size hash values.
241
-
242
- ```sql
243
- -- Get 16-bit hash (0-65535) for sharding
244
- SELECT hash_mod('user@example.com', 16, 'sha256', 'utf8') as shard_id;
245
-
246
- -- Get 32-bit hash
247
- SELECT hash_mod('session_token', 32, 'sha256', 'utf8') as hash32;
248
-
249
- -- Use with base64url input
250
- SELECT hash_mod('aGVsbG8', 16) as hash16;
251
- ```
252
-
253
- ### random_bytes(bits?, encoding?)
254
-
255
- Generate cryptographically secure random bytes.
256
-
257
- ```sql
258
- -- Generate 256 bits (32 bytes) of random data (default)
259
- SELECT random_bytes() as nonce;
260
-
261
- -- Generate 128 bits as hex
262
- SELECT random_bytes(128, 'hex') as salt;
263
-
264
- -- Generate 512 bits as base64url
265
- SELECT random_bytes(512, 'base64url') as token;
266
-
267
- -- Generate 64 bits for a random ID
268
- SELECT random_bytes(64) as random_id;
269
- ```
270
-
271
- ### sign(data, privateKey, curve?, inputEncoding?, keyEncoding?, outputEncoding?)
272
-
273
- **Security note (replication):** passing a private key to `sign()` as a literal or
274
- bound parameter is **safe** with respect to Optimystic replication. The Quereus engine
275
- rebuilds the replicated statement from evaluated column values — not from source SQL —
276
- so the key argument is evaluated away and never reaches the record. Peers re-execute
277
- `INSERT ... VALUES (<signature>)`, never the original `sign(..., key)` call. The one
278
- thing to avoid is storing a raw private key **as a column value** in an
279
- optimystic-backed table, since any persisted column value is replicated. Sign or derive
280
- and store only the public result (signature, public key, commitment). See
281
- `docs/transactions.md` § "Secrets and the replicated statement record" for full detail.
282
-
283
- Sign data using secp256k1 (default), P-256, or Ed25519.
284
-
285
- ```sql
286
- -- Sign with secp256k1 (Bitcoin/Ethereum)
287
- SELECT sign('aGVsbG8', 'cHJpdmF0ZUtleQ') as signature;
288
-
289
- -- Sign UTF-8 text
290
- SELECT sign('hello', 'cHJpdmF0ZUtleQ', 'secp256k1', 'utf8') as signature;
291
-
292
- -- Sign with P-256 (NIST)
293
- SELECT sign('data', 'cHJpdmF0ZUtleQ', 'p256', 'utf8') as p256_sig;
294
-
295
- -- Sign with Ed25519
296
- SELECT sign('message', 'cHJpdmF0ZUtleQ', 'ed25519', 'utf8') as ed25519_sig;
297
- ```
298
-
299
- ### verify(data, signature, publicKey, curve?, inputEncoding?, sigEncoding?, keyEncoding?)
300
-
301
- Verify signatures. Returns true for valid, false for invalid.
302
-
303
- ```sql
304
- -- Verify secp256k1 signature
305
- SELECT verify('aGVsbG8', 'c2lnbmF0dXJl', 'cHVibGljS2V5') as is_valid;
306
-
307
- -- Verify UTF-8 text signature
308
- SELECT verify('hello', 'c2lnbmF0dXJl', 'cHVibGljS2V5', 'secp256k1', 'utf8') as is_valid;
309
-
310
- -- Verify P-256 signature
311
- SELECT verify('data', 'c2lnbmF0dXJl', 'cHVibGljS2V5', 'p256', 'utf8') as is_valid;
312
- ```
313
-
314
- ## Migration (v0.14 breaking change)
315
-
316
- The `digest()` JS/TypeScript API changed significantly in v0.14. See [CHANGELOG.md](CHANGELOG.md) for the
317
- full migration guide, including old → new call-site examples, what changed in the SQL function, and
318
- the open bare-hash-helper question.
319
-
320
- ## Digest configuration
321
-
322
- Because `digest` is variadic over data, its **algorithm** and **output encoding** are
323
- not call arguments — they are bound once when the plugin is loaded, via the plugin
324
- config object:
325
-
326
- ```ts
327
- import { registerPlugin } from '@quereus/quereus';
328
- import cryptoPlugin from '@optimystic/quereus-plugin-crypto/plugin';
329
-
330
- await registerPlugin(db, cryptoPlugin, {
331
- algorithm: 'sha256', // 'sha256' (default) | 'sha512' | 'blake3'
332
- encoding: 'base64url', // 'base64url' (default) | 'base64' | 'hex'
333
- });
334
- ```
335
-
336
- An unknown `algorithm` or a non-text `encoding` throws at registration (fail fast),
337
- and the algorithm/encoding are resolved once so the per-call path does no branching.
338
-
339
- **Why load-time and not per-connection?** The SQL `digest` is registered as
340
- `replicable` — its output must be bit-identical across peers, platforms, and app
341
- versions, because these digests are signed and persisted as commitments. That holds
342
- only if the configuration is fixed for every peer. *Mutable* per-connection
343
- configuration (e.g. a runtime `SET`/PRAGMA) would let two peers disagree and silently
344
- break signature validation, so it is intentionally not offered for this function. If a
345
- single database genuinely needs two digest configurations, register the plugin twice
346
- (or expose named variants) rather than flipping mutable session state.
347
-
348
- ## Supported Algorithms
349
-
350
- ### Hash Algorithms
351
- - `sha256` - SHA-256 (default) - 256-bit secure hash
352
- - `sha512` - SHA-512 - 512-bit secure hash
353
- - `blake3` - BLAKE3 - Fast, secure, parallel hash
354
-
355
- ### Elliptic Curves
356
- - `secp256k1` - Bitcoin/Ethereum curve (default)
357
- - `p256` - NIST P-256 curve (secp256r1)
358
- - `ed25519` - Edwards curve for EdDSA
359
-
360
- ### Encoding Formats
361
- - `base64url` - URL-safe base64 without padding (default)
362
- - `base64` - Standard base64 encoding
363
- - `hex` - Hexadecimal encoding
364
- - `utf8` - UTF-8 text encoding
365
- - `bytes` - Raw Uint8Array (JavaScript only)
366
-
367
- ## Why base64url?
368
-
369
- Base64url is the default encoding because it's:
370
- - **URL-safe**: No `+`, `/`, or `=` characters
371
- - **SQL-friendly**: No special characters that need escaping
372
- - **Compact**: More efficient than hex (33% smaller)
373
- - **Standard**: Defined in RFC 4648
374
-
375
- ## Complete Example
376
-
377
- ```typescript
378
- import { Database } from '@quereus/quereus';
379
- import { loadPlugin } from '@quereus/quereus/util/plugin-loader.js';
380
- import {
381
- digest,
382
- randomBytes,
383
- sign,
384
- verify,
385
- generatePrivateKey,
386
- getPublicKey
387
- } from '@optimystic/quereus-plugin-crypto';
388
-
389
- // Load plugin
390
- const db = new Database();
391
- await loadPlugin('npm:@optimystic/quereus-plugin-crypto', db);
392
-
393
- // Use in SQL
394
- db.exec(`
395
- CREATE TABLE users (
396
- id INTEGER PRIMARY KEY,
397
- email TEXT,
398
- shard_id INTEGER AS (hash_mod(email, 16, 'sha256', 'utf8')),
399
- nonce TEXT DEFAULT (random_bytes(256))
400
- );
401
-
402
- INSERT INTO users (id, email) VALUES (1, 'alice@example.com');
403
-
404
- SELECT id, email, shard_id, nonce FROM users;
405
- `);
406
-
407
- // Use in JavaScript
408
- const privateKey = generatePrivateKey('secp256k1', 'base64url');
409
- const publicKey = getPublicKey(privateKey);
410
-
411
- const message = 'Hello, World!';
412
- const hash = digest([message], 'sha256', 'base64url') as string;
413
- const signature = sign(hash, privateKey);
414
- const isValid = verify(hash, signature, publicKey);
415
-
416
- console.log('Valid signature:', isValid); // true
417
-
418
- // Generate random nonce
419
- const nonce = randomBytes(256, 'base64url');
420
- console.log('Random nonce:', nonce);
421
- ```
422
-
423
- ## JavaScript API Reference
424
-
425
- ### digest(fields, algorithm?, encoding?)
426
- Injective digest over an ordered tuple of fields. `fields` is an array of values
427
- (any SQL value type). `algorithm` defaults to `'sha256'`, `encoding` to `'base64url'`.
428
- - **Returns**: Hash as string (or Uint8Array if encoding is `'bytes'`)
429
- - **Related**: `encodeFields(fields)` returns the canonical pre-hash byte framing;
430
- `digestFields(fields, hasher, encode)` / `resolveHasher` / `resolveOutputEncoder`
431
- are the building blocks the SQL function composes (resolve once, no per-call branching).
432
-
433
- ### cid(data, codec?, hash?, base?)
434
- Hash `data` (a `Uint8Array`) and frame it as a self-describing CIDv1 string. Defaults:
435
- `codec='raw'`, `hash='sha2-256'`, `base='base32'`. Byte-identical to the CID an IPFS/IPLD
436
- store computes for the same bytes.
437
- - **Returns**: CIDv1 string
438
-
439
- ### cidV1(digest, hash, codec?, base?)
440
- Frame an **already-computed** `digest` (a `Uint8Array`) as a CIDv1 without re-hashing.
441
- `hash` asserts which algorithm produced the digest; the digest length is validated
442
- against it. Use to turn a `digest(...)` result into a CID: `cidV1(digest(fields, 'sha256', 'bytes'), 'sha2-256')`.
443
- - **Returns**: CIDv1 string
444
-
445
- ### cidDecode(cid)
446
- Parse a CID string into `{ version, codec, hashCode, digest }` for validation/migration.
447
- Recognized codec/hash codes are returned as names, otherwise as numbers; `digest` is a
448
- `Uint8Array`. Throws on malformed input.
449
- - **Returns**: `{ version: number, codec: Multicodec | number, hashCode: MultihashCode | number, digest: Uint8Array }`
450
-
451
- ### setCommit(leaves, hasher?, encode?) / setDisclose(leaves, revealNames, hasher?) / setVerify(root, disclosure, hasher?, encode?)
452
- Salted-leaf set commitment for selective disclosure. `leaves` is an array of
453
- `{ name, value, salt }` (`salt` a base64url string or `Uint8Array`).
454
- - **`setCommit`** → the root (`string`, or `Uint8Array` with a bytes encoder). Throws on a
455
- duplicate name or a missing/empty salt; the empty set is well-defined, not an error.
456
- - **`setDisclose`** → `{ disclosed, hidden }`: the revealed `{ name, value, salt }` triples
457
- plus the opaque base64url leaf digests of the withheld leaves (withheld values/salts never
458
- appear). This is the engine-side generator with no SQL equivalent.
459
- - **`setVerify`** → `boolean`: reconstructs the entire root from `disclosure` and compares to
460
- `root`. `false` on mismatch or malformed input. `encode` is how the signed root is rendered
461
- (default base64url); a `Uint8Array` root is compared by raw bytes.
462
- - **`leafDigest(leaf, hasher)`** → raw leaf digest bytes (the low-level building block).
463
-
464
- ```typescript
465
- import { setCommit, setDisclose, setVerify, randomBytes } from '@optimystic/quereus-plugin-crypto';
466
-
467
- const leaves = [
468
- { name: 'name', value: 'Alice', salt: randomBytes(256) as string },
469
- { name: 'over18', value: true, salt: randomBytes(256) as string },
470
- { name: 'zip', value: '90210', salt: randomBytes(256) as string },
471
- ];
472
- const root = setCommit(leaves); // sign / persist this (often as cid(root))
473
-
474
- // Recipient gets only `over18`, with proof it belongs to the committed set:
475
- const disclosure = setDisclose(leaves, ['over18']);
476
- const ok = setVerify(root, disclosure); // true — withheld values never left the engine
477
- ```
478
-
479
- ### hashMod(data, bits, algorithm?, inputEncoding?)
480
- Hash data and return modulo 2^bits for fixed-size hash values.
481
- - **Returns**: Number between 0 and 2^bits - 1
482
-
483
- ### randomBytes(bits?, encoding?)
484
- Generate cryptographically secure random bytes.
485
- - **Default**: 256 bits, base64url encoding
486
- - **Returns**: Random bytes as string (or Uint8Array if encoding is 'bytes')
487
-
488
- ### sign(data, privateKey, curve?, inputEncoding?, keyEncoding?, outputEncoding?)
489
- Sign data using ECC (secp256k1, P-256, or Ed25519).
490
- - **Returns**: Signature as string (or Uint8Array if encoding is 'bytes')
491
-
492
- ### verify(data, signature, publicKey, curve?, inputEncoding?, sigEncoding?, keyEncoding?)
493
- Verify an ECC signature.
494
- - **Returns**: Boolean (true if valid, false if invalid)
495
-
496
- ### generatePrivateKey(curve?, encoding?)
497
- Generate a random private key for the specified curve.
498
- - **Returns**: Private key as string (or Uint8Array if encoding is 'bytes')
499
-
500
- ### getPublicKey(privateKey, curve?, keyEncoding?, outputEncoding?)
501
- Derive the public key from a private key.
502
- - **Returns**: Public key as string (or Uint8Array if encoding is 'bytes')
503
-
504
- ## Security Notes
505
-
506
- - All cryptographic operations use audited libraries (@noble/*)
507
- - Private keys should be handled securely and never exposed
508
- - Random number generation uses platform CSPRNG (crypto.getRandomValues)
509
- - Signatures use deterministic k-generation (RFC 6979)
510
- - All algorithms provide industry-standard security levels
511
-
512
- ## React Native Compatibility
513
-
514
- These functions are fully compatible with React Native and don't require any native modules. They use:
515
- - `@noble/curves` for elliptic curve operations
516
- - `@noble/hashes` for hashing
517
- - `crypto.getRandomValues()` for secure randomness (polyfill required for React Native)
518
-
519
- ## License
520
-
521
- MIT
522
-
1
+ # @optimystic/quereus-plugin-crypto
2
+
3
+ Quereus plugin providing cryptographic functions for SQL queries with base64url encoding by default.
4
+
5
+ ## Features
6
+
7
+ - **Hash Functions**: SHA-256, SHA-512, BLAKE3 hashing with base64url output
8
+ - **Content Identifiers (CIDv1)**: Self-describing, interoperable IPFS/IPLD content addresses
9
+ - **Selective Disclosure**: Salted-leaf set commitment — commit to a whole attribute set with one value, later reveal only a chosen subset with proof of authenticity
10
+ - **Hash Modulo**: Fixed-size hash values (16-bit, 32-bit, etc.) for sharding and partitioning
11
+ - **Random Bytes**: Generate cryptographically secure random bytes (default: 256 bits)
12
+ - **Signature Functions**: secp256k1, P-256, Ed25519 signing with base64url encoding
13
+ - **Verification Functions**: Signature verification for all supported curves
14
+ - **Key Generation**: Generate and derive cryptographic keys
15
+ - **Multiple Encodings**: Support for base64url, base64, hex, utf8, and raw bytes
16
+
17
+ ## Installation
18
+
19
+ ```bash
20
+ npm install @optimystic/quereus-plugin-crypto
21
+ ```
22
+
23
+ ## Usage
24
+
25
+ ### As a Quereus Plugin
26
+
27
+ ```typescript
28
+ import { Database } from '@quereus/quereus';
29
+ import { loadPlugin } from '@quereus/quereus/util/plugin-loader.js';
30
+
31
+ const db = new Database();
32
+ await loadPlugin('npm:@optimystic/quereus-plugin-crypto', db);
33
+
34
+ // Or configure the digest algorithm / output encoding once, at load time
35
+ // (see "Digest configuration" below):
36
+ await loadPlugin('npm:@optimystic/quereus-plugin-crypto', db, {
37
+ algorithm: 'sha256', // 'sha256' (default) | 'sha512' | 'blake3'
38
+ encoding: 'base64url', // 'base64url' (default) | 'base64' | 'hex'
39
+ });
40
+ ```
41
+
42
+ ### Direct Import (for JavaScript/TypeScript code)
43
+
44
+ All cryptographic functions are also exported directly so you can use the same implementations in your JavaScript code:
45
+
46
+ ```typescript
47
+ import {
48
+ digest,
49
+ hashMod,
50
+ randomBytes,
51
+ sign,
52
+ verify,
53
+ generatePrivateKey,
54
+ getPublicKey
55
+ } from '@optimystic/quereus-plugin-crypto';
56
+
57
+ // Hash an ordered tuple of fields (injective — distinct tuples never collide)
58
+ const hash = digest(['hello world', 42, null], 'sha256', 'base64url');
59
+
60
+ // Get a 16-bit hash for sharding
61
+ const shard = hashMod('user@example.com', 16, 'sha256', 'utf8');
62
+
63
+ // Generate random bytes (256 bits by default)
64
+ const nonce = randomBytes(256, 'base64url');
65
+ const salt = randomBytes(128, 'hex');
66
+
67
+ // Generate keys
68
+ const privateKey = generatePrivateKey('secp256k1', 'base64url');
69
+ const publicKey = getPublicKey(privateKey, 'secp256k1', 'base64url', 'base64url');
70
+
71
+ // Sign and verify
72
+ const signature = sign(hash, privateKey, 'secp256k1', 'base64url', 'base64url', 'base64url');
73
+ const isValid = verify(hash, signature, publicKey, 'secp256k1', 'base64url', 'base64url', 'base64url');
74
+ ```
75
+
76
+ ## SQL Functions
77
+
78
+ All SQL functions use **base64url encoding by default** for inputs and outputs. This is URL-safe and SQL-friendly.
79
+
80
+ ### digest(field1, field2, ..., fieldN)
81
+
82
+ Hash an **ordered tuple of fields** into a single digest. `digest` is variadic over
83
+ *data* — every argument is a field, not a configuration option. The algorithm and
84
+ output encoding are chosen once, at load time (see [Digest configuration](#digest-configuration)),
85
+ so they never have to be passed per call.
86
+
87
+ ```sql
88
+ -- Hash a single value
89
+ SELECT digest(Id) as hash;
90
+
91
+ -- Hash a tuple of columns — distinct tuples never collide,
92
+ -- NULL is distinguished from '', and 123 from '123'
93
+ SELECT digest(Tid, Name, ImageRef, NumberRequiredTSAs) as commitment;
94
+ ```
95
+
96
+ **Why variadic + injective?** Hashing several fields by joining them
97
+ (`a || '|' || b`) or by `String()`-concatenation is not injective: `('a|b','c')`
98
+ collides with `('a','b|c')`, `NULL` collides with `''`, and `123` collides with
99
+ `'123'`. `digest` instead applies a canonical, length-prefixed, type-tagged framing
100
+ to each field, so distinct tuples always produce distinct digests. This matters when
101
+ the digest is signed or persisted as a commitment.
102
+
103
+ The framing is also why `digest(x)` is **not** a bare `sha256(x)` — it is a framed
104
+ digest of a one-element tuple. For sharding a single value, use `hash_mod`.
105
+
106
+ ### cid(data, codec?, hash?, base?) / cid_v1(digest, hash, codec?, base?) / cid_decode(cid)
107
+
108
+ `digest` returns a **bare** hash — raw digest bytes in some text encoding, with no
109
+ record of which base, content type, or hash algorithm produced it. `cid` instead
110
+ produces a **self-describing CIDv1**, the same interoperable content address an
111
+ IPFS/IPLD store computes for the same bytes:
112
+
113
+ ```
114
+ CIDv1 = multibase( version ‖ multicodec(content-type) ‖ multihash )
115
+ multihash = hashFnCode ‖ digestLength ‖ digestBytes
116
+ ```
117
+
118
+ Because the multibase, content codec, and hash code all travel *inside* the value,
119
+ a consumer can validate it without out-of-band knowledge, and an algorithm
120
+ migration (e.g. sha2-256 → another hash) is unambiguous rather than a silent
121
+ reinterpretation. The framing comes entirely from the audited
122
+ [`multiformats`](https://github.com/multiformats/js-multiformats) library.
123
+
124
+ ```sql
125
+ -- Hash a blob and frame it as the canonical raw/sha2-256/base32 CID
126
+ -- (== the CID IPFS shows for the same bytes)
127
+ SELECT cid(SomeBlob) AS Cid;
128
+
129
+ -- Pick content codec / hash / base
130
+ SELECT cid(SomeBlob, 'dag-cbor', 'sha2-512', 'base58btc') AS Cid;
131
+
132
+ -- A self-describing content address over a field tuple: digest() canonically
133
+ -- frames + hashes the fields; cid_v1() wraps that exact digest as a CIDv1
134
+ -- (no double-hash). The asserted hash must match digest()'s configured algorithm.
135
+ SELECT cid_v1(digest(ColA, ColB, ColC), 'sha2-256') AS Cid;
136
+
137
+ -- Validate / inspect a stored CID (returns JSON: { version, codec, hashCode, digest })
138
+ SELECT cid_decode(Cid) ->> 'codec' AS codec FROM T;
139
+ ```
140
+
141
+ - **`cid(data, codec?, hash?, base?)`** — hash `data` then frame. `data` is a BLOB,
142
+ or a base64url-encoded TEXT digest/blob (the plugin's canonical text encoding).
143
+ Defaults: `codec='raw'`, `hash='sha2-256'`, `base='base32'`.
144
+ - **`cid_v1(digest, hash, codec?, base?)`** — wrap an **already-computed** digest
145
+ without re-hashing. `hash` is required and asserts which algorithm produced the
146
+ digest; the digest length is checked against it (sha2-256/blake3 = 32 bytes,
147
+ sha2-512 = 64) and a mismatch is rejected.
148
+ - **`cid_decode(cid) → JSON`** — parse a CID back to `{ version, codec, hashCode,
149
+ digest }` (digest as base64url). Throws cleanly on malformed input.
150
+
151
+ Selectable values: `codec` ∈ `raw`, `dag-cbor`; `hash` ∈ `sha2-256`, `sha2-512`,
152
+ `blake3`; `base` ∈ `base32` (default), `base58btc`, `base64url`, `base16`.
153
+
154
+ **Why `base32` by default?** A CID's whole purpose is to match what an external
155
+ content-addressed store computes, and IPFS renders CIDv1 canonically in base32 (the
156
+ `b…` prefix). This is deliberately different from the plugin's `digest`/`random_bytes`
157
+ default of base64url: base64url is compact for *internal* values that live in memory,
158
+ on the wire, or in JSON, whereas base32 is case-insensitive and DNS/URL/filename-safe
159
+ where interoperable addresses are copied and read. Two audiences, two defaults — pass
160
+ `'base64url'` explicitly if you want the compact form.
161
+
162
+ ### set_commit(leaves_json) / set_verify(root, disclosed_json, hidden_json)
163
+
164
+ **Per-attribute selective disclosure.** An authority commits to a registrant's whole
165
+ attribute set as a single root (which it signs / persists), then later reveals only a
166
+ chosen *subset* to a recipient — with a proof the revealed values are genuinely the
167
+ committed ones — **without** leaking the withheld attribute values. A flat
168
+ `digest(whole set)` can't do this (verifying one field needs the whole pre-image, so
169
+ it's all-or-nothing); `set_commit` supports *partial opening*.
170
+
171
+ Each attribute becomes a salted leaf, and the root is the digest of all leaf digests in
172
+ canonical (sort-by-leaf-digest-bytes) order:
173
+
174
+ ```
175
+ leafDigest = digest([SD_LEAF_DOMAIN_V1, name, value, salt]) -- raw digest bytes
176
+ root = digest([SD_SET_DOMAIN_V1, sortedLeaf_0, sortedLeaf_1, ...])
177
+ ```
178
+
179
+ This is the same flat salted-hash shape the IETF SD-JWT standard
180
+ (`draft-ietf-oauth-selective-disclosure-jwt`) settled on rather than a Merkle tree —
181
+ cited as conceptual precedent only; the framing here is Optimystic's own `digest`
182
+ `encodeFields` (not SD-JWT wire-compatible). The `name` is hashed into the leaf so a
183
+ `(value, salt)` proof can't be replayed under another attribute; the `salt` is per-leaf
184
+ and **mandatory** (low-entropy values like a DOB or a boolean are brute-forceable from a
185
+ bare hash, and independent salts defeat cross-registrant correlation).
186
+
187
+ ```sql
188
+ -- Commit to a JSON array of [name, value, salt] leaves -> single root.
189
+ -- Pair with cid() for the self-describing persisted/signed column representation:
190
+ SELECT cid(set_commit(SelectiveDetails)) AS SelectiveCid;
191
+
192
+ -- A schema CHECK makes a forged root impossible to store: the root is recomputed from
193
+ -- the stored attribute triples, so SelectiveCid must equal the genuine commitment.
194
+ CREATE TABLE Registrant (
195
+ ...,
196
+ SelectiveDetails TEXT, -- JSON array of [name, value, salt] triples
197
+ SelectiveCid TEXT,
198
+ CHECK (SelectiveCid = cid(set_commit(SelectiveDetails)))
199
+ );
200
+
201
+ -- A recipient verifies a disclosure: the disclosed [name, value, salt] triples plus
202
+ -- the opaque leaf digests of the withheld leaves reconstruct the entire root.
203
+ SELECT set_verify(root, disclosed_json, hidden_json) AS ok;
204
+ ```
205
+
206
+ - **`set_commit(leaves_json) → TEXT`** — `leaves_json` is a JSON array; each element is a
207
+ leaf `[name, value, salt]` *or* `{ "name", "value", "salt" }`. Values follow `digest`'s
208
+ rules as parsed from JSON (INTEGER vs REAL by JS value, TEXT, BOOL, null, nested
209
+ object/array). Each leaf must carry all three fields — a missing `value` (object form) or
210
+ a `[name, value]` array (under three elements) throws; pass `value: null` for a null-valued
211
+ attribute. The salt is base64url TEXT (e.g. from `random_bytes`). **THROWS** on a duplicate
212
+ name, a missing value, a missing/empty salt, or unparseable/non-array JSON (invalid states
213
+ made impossible). `replicable` — the root is signed and persisted, same bar as `digest`.
214
+ - **`set_verify(root, disclosed_json, hidden_json) → BOOLEAN`** — `disclosed_json` is the
215
+ opened triples (same leaf shape), `hidden_json` a JSON array of the withheld leaves'
216
+ opaque base64url digests. Reconstructs the **entire** root and compares — so the holder
217
+ cannot add, drop, or swap a leaf. Returns `false` on any mismatch or malformed input
218
+ (forgiving, like `verify`).
219
+
220
+ > **Disclosure generation is JS-only** (`setDisclose`, below) — there's no SQL
221
+ > `set_disclose`, because building a disclosure requires the full attribute set including
222
+ > the secret salts, which lives engine-side, not in a query.
223
+
224
+ **BLOB-valued attributes via SQL:** JSON has no blob type, so a blob attribute passed
225
+ through `set_commit` is committed as its base64url TEXT. Callers needing a *true* BLOB
226
+ value (committed as a BLOB field, `TAG_BLOB`) must use the JS `setCommit` with a
227
+ `Uint8Array` value.
228
+
229
+ **Privacy note:** a fixed commitment disclosed to two audiences exposes the same hidden
230
+ digests and field count to both, so they can correlate that it's the same record.
231
+ Re-randomizing per disclosure would require fresh salts → a new root → a new signature
232
+ (out of scope here).
233
+
234
+ **Framing coupling:** leaf and root reuse `digest`'s `encodeFields`, so a future digest
235
+ framing-version bump changes `set_commit` output too — intentional (one canonical
236
+ framing), but it means the pinned set-commitment vectors move with the digest vectors.
237
+
238
+ ### hash_mod(data, bits, algorithm?, inputEncoding?)
239
+
240
+ Hash data and return modulo 2^bits for fixed-size hash values.
241
+
242
+ ```sql
243
+ -- Get 16-bit hash (0-65535) for sharding
244
+ SELECT hash_mod('user@example.com', 16, 'sha256', 'utf8') as shard_id;
245
+
246
+ -- Get 32-bit hash
247
+ SELECT hash_mod('session_token', 32, 'sha256', 'utf8') as hash32;
248
+
249
+ -- Use with base64url input
250
+ SELECT hash_mod('aGVsbG8', 16) as hash16;
251
+ ```
252
+
253
+ ### random_bytes(bits?, encoding?)
254
+
255
+ Generate cryptographically secure random bytes.
256
+
257
+ ```sql
258
+ -- Generate 256 bits (32 bytes) of random data (default)
259
+ SELECT random_bytes() as nonce;
260
+
261
+ -- Generate 128 bits as hex
262
+ SELECT random_bytes(128, 'hex') as salt;
263
+
264
+ -- Generate 512 bits as base64url
265
+ SELECT random_bytes(512, 'base64url') as token;
266
+
267
+ -- Generate 64 bits for a random ID
268
+ SELECT random_bytes(64) as random_id;
269
+ ```
270
+
271
+ ### sign(data, privateKey, curve?, inputEncoding?, keyEncoding?, outputEncoding?)
272
+
273
+ **Security note (replication):** passing a private key to `sign()` as a literal or
274
+ bound parameter is **safe** with respect to Optimystic replication. The Quereus engine
275
+ rebuilds the replicated statement from evaluated column values — not from source SQL —
276
+ so the key argument is evaluated away and never reaches the record. Peers re-execute
277
+ `INSERT ... VALUES (<signature>)`, never the original `sign(..., key)` call. The one
278
+ thing to avoid is storing a raw private key **as a column value** in an
279
+ optimystic-backed table, since any persisted column value is replicated. Sign or derive
280
+ and store only the public result (signature, public key, commitment). See
281
+ `docs/transactions.md` § "Secrets and the replicated statement record" for full detail.
282
+
283
+ Sign data using secp256k1 (default), P-256, or Ed25519.
284
+
285
+ ```sql
286
+ -- Sign with secp256k1 (Bitcoin/Ethereum)
287
+ SELECT sign('aGVsbG8', 'cHJpdmF0ZUtleQ') as signature;
288
+
289
+ -- Sign UTF-8 text
290
+ SELECT sign('hello', 'cHJpdmF0ZUtleQ', 'secp256k1', 'utf8') as signature;
291
+
292
+ -- Sign with P-256 (NIST)
293
+ SELECT sign('data', 'cHJpdmF0ZUtleQ', 'p256', 'utf8') as p256_sig;
294
+
295
+ -- Sign with Ed25519
296
+ SELECT sign('message', 'cHJpdmF0ZUtleQ', 'ed25519', 'utf8') as ed25519_sig;
297
+ ```
298
+
299
+ ### verify(data, signature, publicKey, curve?, inputEncoding?, sigEncoding?, keyEncoding?)
300
+
301
+ Verify signatures. Returns true for valid, false for invalid.
302
+
303
+ ```sql
304
+ -- Verify secp256k1 signature
305
+ SELECT verify('aGVsbG8', 'c2lnbmF0dXJl', 'cHVibGljS2V5') as is_valid;
306
+
307
+ -- Verify UTF-8 text signature
308
+ SELECT verify('hello', 'c2lnbmF0dXJl', 'cHVibGljS2V5', 'secp256k1', 'utf8') as is_valid;
309
+
310
+ -- Verify P-256 signature
311
+ SELECT verify('data', 'c2lnbmF0dXJl', 'cHVibGljS2V5', 'p256', 'utf8') as is_valid;
312
+ ```
313
+
314
+ ## Migration (v0.14 breaking change)
315
+
316
+ The `digest()` JS/TypeScript API changed significantly in v0.14. See [CHANGELOG.md](CHANGELOG.md) for the
317
+ full migration guide, including old → new call-site examples, what changed in the SQL function, and
318
+ the open bare-hash-helper question.
319
+
320
+ ## Digest configuration
321
+
322
+ Because `digest` is variadic over data, its **algorithm** and **output encoding** are
323
+ not call arguments — they are bound once when the plugin is loaded, via the plugin
324
+ config object:
325
+
326
+ ```ts
327
+ import { registerPlugin } from '@quereus/quereus';
328
+ import cryptoPlugin from '@optimystic/quereus-plugin-crypto/plugin';
329
+
330
+ await registerPlugin(db, cryptoPlugin, {
331
+ algorithm: 'sha256', // 'sha256' (default) | 'sha512' | 'blake3'
332
+ encoding: 'base64url', // 'base64url' (default) | 'base64' | 'hex'
333
+ });
334
+ ```
335
+
336
+ An unknown `algorithm` or a non-text `encoding` throws at registration (fail fast),
337
+ and the algorithm/encoding are resolved once so the per-call path does no branching.
338
+
339
+ **Why load-time and not per-connection?** The SQL `digest` is registered as
340
+ `replicable` — its output must be bit-identical across peers, platforms, and app
341
+ versions, because these digests are signed and persisted as commitments. That holds
342
+ only if the configuration is fixed for every peer. *Mutable* per-connection
343
+ configuration (e.g. a runtime `SET`/PRAGMA) would let two peers disagree and silently
344
+ break signature validation, so it is intentionally not offered for this function. If a
345
+ single database genuinely needs two digest configurations, register the plugin twice
346
+ (or expose named variants) rather than flipping mutable session state.
347
+
348
+ ## Supported Algorithms
349
+
350
+ ### Hash Algorithms
351
+ - `sha256` - SHA-256 (default) - 256-bit secure hash
352
+ - `sha512` - SHA-512 - 512-bit secure hash
353
+ - `blake3` - BLAKE3 - Fast, secure, parallel hash
354
+
355
+ ### Elliptic Curves
356
+ - `secp256k1` - Bitcoin/Ethereum curve (default)
357
+ - `p256` - NIST P-256 curve (secp256r1)
358
+ - `ed25519` - Edwards curve for EdDSA
359
+
360
+ ### Encoding Formats
361
+ - `base64url` - URL-safe base64 without padding (default)
362
+ - `base64` - Standard base64 encoding
363
+ - `hex` - Hexadecimal encoding
364
+ - `utf8` - UTF-8 text encoding
365
+ - `bytes` - Raw Uint8Array (JavaScript only)
366
+
367
+ ## Why base64url?
368
+
369
+ Base64url is the default encoding because it's:
370
+ - **URL-safe**: No `+`, `/`, or `=` characters
371
+ - **SQL-friendly**: No special characters that need escaping
372
+ - **Compact**: More efficient than hex (33% smaller)
373
+ - **Standard**: Defined in RFC 4648
374
+
375
+ ## Complete Example
376
+
377
+ ```typescript
378
+ import { Database } from '@quereus/quereus';
379
+ import { loadPlugin } from '@quereus/quereus/util/plugin-loader.js';
380
+ import {
381
+ digest,
382
+ randomBytes,
383
+ sign,
384
+ verify,
385
+ generatePrivateKey,
386
+ getPublicKey
387
+ } from '@optimystic/quereus-plugin-crypto';
388
+
389
+ // Load plugin
390
+ const db = new Database();
391
+ await loadPlugin('npm:@optimystic/quereus-plugin-crypto', db);
392
+
393
+ // Use in SQL
394
+ db.exec(`
395
+ CREATE TABLE users (
396
+ id INTEGER PRIMARY KEY,
397
+ email TEXT,
398
+ shard_id INTEGER AS (hash_mod(email, 16, 'sha256', 'utf8')),
399
+ nonce TEXT DEFAULT (random_bytes(256))
400
+ );
401
+
402
+ INSERT INTO users (id, email) VALUES (1, 'alice@example.com');
403
+
404
+ SELECT id, email, shard_id, nonce FROM users;
405
+ `);
406
+
407
+ // Use in JavaScript
408
+ const privateKey = generatePrivateKey('secp256k1', 'base64url');
409
+ const publicKey = getPublicKey(privateKey);
410
+
411
+ const message = 'Hello, World!';
412
+ const hash = digest([message], 'sha256', 'base64url') as string;
413
+ const signature = sign(hash, privateKey);
414
+ const isValid = verify(hash, signature, publicKey);
415
+
416
+ console.log('Valid signature:', isValid); // true
417
+
418
+ // Generate random nonce
419
+ const nonce = randomBytes(256, 'base64url');
420
+ console.log('Random nonce:', nonce);
421
+ ```
422
+
423
+ ## JavaScript API Reference
424
+
425
+ ### digest(fields, algorithm?, encoding?)
426
+ Injective digest over an ordered tuple of fields. `fields` is an array of values
427
+ (any SQL value type). `algorithm` defaults to `'sha256'`, `encoding` to `'base64url'`.
428
+ - **Returns**: Hash as string (or Uint8Array if encoding is `'bytes'`)
429
+ - **Related**: `encodeFields(fields)` returns the canonical pre-hash byte framing;
430
+ `digestFields(fields, hasher, encode)` / `resolveHasher` / `resolveOutputEncoder`
431
+ are the building blocks the SQL function composes (resolve once, no per-call branching).
432
+
433
+ ### cid(data, codec?, hash?, base?)
434
+ Hash `data` (a `Uint8Array`) and frame it as a self-describing CIDv1 string. Defaults:
435
+ `codec='raw'`, `hash='sha2-256'`, `base='base32'`. Byte-identical to the CID an IPFS/IPLD
436
+ store computes for the same bytes.
437
+ - **Returns**: CIDv1 string
438
+
439
+ ### cidV1(digest, hash, codec?, base?)
440
+ Frame an **already-computed** `digest` (a `Uint8Array`) as a CIDv1 without re-hashing.
441
+ `hash` asserts which algorithm produced the digest; the digest length is validated
442
+ against it. Use to turn a `digest(...)` result into a CID: `cidV1(digest(fields, 'sha256', 'bytes'), 'sha2-256')`.
443
+ - **Returns**: CIDv1 string
444
+
445
+ ### cidDecode(cid)
446
+ Parse a CID string into `{ version, codec, hashCode, digest }` for validation/migration.
447
+ Recognized codec/hash codes are returned as names, otherwise as numbers; `digest` is a
448
+ `Uint8Array`. Throws on malformed input.
449
+ - **Returns**: `{ version: number, codec: Multicodec | number, hashCode: MultihashCode | number, digest: Uint8Array }`
450
+
451
+ ### setCommit(leaves, hasher?, encode?) / setDisclose(leaves, revealNames, hasher?) / setVerify(root, disclosure, hasher?, encode?)
452
+ Salted-leaf set commitment for selective disclosure. `leaves` is an array of
453
+ `{ name, value, salt }` (`salt` a base64url string or `Uint8Array`).
454
+ - **`setCommit`** → the root (`string`, or `Uint8Array` with a bytes encoder). Throws on a
455
+ duplicate name or a missing/empty salt; the empty set is well-defined, not an error.
456
+ - **`setDisclose`** → `{ disclosed, hidden }`: the revealed `{ name, value, salt }` triples
457
+ plus the opaque base64url leaf digests of the withheld leaves (withheld values/salts never
458
+ appear). This is the engine-side generator with no SQL equivalent.
459
+ - **`setVerify`** → `boolean`: reconstructs the entire root from `disclosure` and compares to
460
+ `root`. `false` on mismatch or malformed input. `encode` is how the signed root is rendered
461
+ (default base64url); a `Uint8Array` root is compared by raw bytes.
462
+ - **`leafDigest(leaf, hasher)`** → raw leaf digest bytes (the low-level building block).
463
+
464
+ ```typescript
465
+ import { setCommit, setDisclose, setVerify, randomBytes } from '@optimystic/quereus-plugin-crypto';
466
+
467
+ const leaves = [
468
+ { name: 'name', value: 'Alice', salt: randomBytes(256) as string },
469
+ { name: 'over18', value: true, salt: randomBytes(256) as string },
470
+ { name: 'zip', value: '90210', salt: randomBytes(256) as string },
471
+ ];
472
+ const root = setCommit(leaves); // sign / persist this (often as cid(root))
473
+
474
+ // Recipient gets only `over18`, with proof it belongs to the committed set:
475
+ const disclosure = setDisclose(leaves, ['over18']);
476
+ const ok = setVerify(root, disclosure); // true — withheld values never left the engine
477
+ ```
478
+
479
+ ### hashMod(data, bits, algorithm?, inputEncoding?)
480
+ Hash data and return modulo 2^bits for fixed-size hash values.
481
+ - **Returns**: Number between 0 and 2^bits - 1
482
+
483
+ ### randomBytes(bits?, encoding?)
484
+ Generate cryptographically secure random bytes.
485
+ - **Default**: 256 bits, base64url encoding
486
+ - **Returns**: Random bytes as string (or Uint8Array if encoding is 'bytes')
487
+
488
+ ### sign(data, privateKey, curve?, inputEncoding?, keyEncoding?, outputEncoding?)
489
+ Sign data using ECC (secp256k1, P-256, or Ed25519).
490
+ - **Returns**: Signature as string (or Uint8Array if encoding is 'bytes')
491
+
492
+ ### verify(data, signature, publicKey, curve?, inputEncoding?, sigEncoding?, keyEncoding?)
493
+ Verify an ECC signature.
494
+ - **Returns**: Boolean (true if valid, false if invalid)
495
+
496
+ ### generatePrivateKey(curve?, encoding?)
497
+ Generate a random private key for the specified curve.
498
+ - **Returns**: Private key as string (or Uint8Array if encoding is 'bytes')
499
+
500
+ ### getPublicKey(privateKey, curve?, keyEncoding?, outputEncoding?)
501
+ Derive the public key from a private key.
502
+ - **Returns**: Public key as string (or Uint8Array if encoding is 'bytes')
503
+
504
+ ## Security Notes
505
+
506
+ - All cryptographic operations use audited libraries (@noble/*)
507
+ - Private keys should be handled securely and never exposed
508
+ - Random number generation uses platform CSPRNG (crypto.getRandomValues)
509
+ - Signatures use deterministic k-generation (RFC 6979)
510
+ - All algorithms provide industry-standard security levels
511
+
512
+ ## React Native Compatibility
513
+
514
+ These functions are fully compatible with React Native and don't require any native modules. They use:
515
+ - `@noble/curves` for elliptic curve operations
516
+ - `@noble/hashes` for hashing
517
+ - `crypto.getRandomValues()` for secure randomness (polyfill required for React Native)
518
+
519
+ ## License
520
+
521
+ MIT
522
+