@optimystic/quereus-plugin-crypto 1.5.0 → 1.5.1
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 +91 -91
- package/README.md +522 -522
- package/dist/index.js.map +1 -1
- package/dist/plugin.js.map +1 -1
- package/package.json +4 -4
- package/src/cid.ts +200 -200
- package/src/crypto.ts +547 -547
- package/src/index.ts +58 -58
- package/src/plugin.ts +290 -290
- package/src/sd.ts +250 -250
package/src/plugin.ts
CHANGED
|
@@ -1,290 +1,290 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Quereus Plugin Entry Point for Crypto Functions
|
|
3
|
-
*
|
|
4
|
-
* This module provides the plugin registration following Quereus 0.4.5 format.
|
|
5
|
-
* All metadata is in package.json - no manifest export needed.
|
|
6
|
-
*/
|
|
7
|
-
|
|
8
|
-
import type { Database, SqlValue } from '@quereus/quereus';
|
|
9
|
-
import { FunctionFlags, TEXT_TYPE, INTEGER_TYPE, BOOLEAN_TYPE } from '@quereus/quereus';
|
|
10
|
-
import { fromString as uint8ArrayFromString, toString as uint8ArrayToString } from 'uint8arrays';
|
|
11
|
-
import {
|
|
12
|
-
sign, verify, hashMod, randomBytes,
|
|
13
|
-
digestFields, resolveHasher, resolveOutputEncoder,
|
|
14
|
-
type HashAlgorithm, type OutputEncoding, type DigestField,
|
|
15
|
-
} from './crypto.js';
|
|
16
|
-
import {
|
|
17
|
-
cid, cidV1, cidDecode,
|
|
18
|
-
type Multicodec, type MultihashCode, type Multibase,
|
|
19
|
-
} from './cid.js';
|
|
20
|
-
import {
|
|
21
|
-
setCommit, setVerify,
|
|
22
|
-
type SaltedLeaf,
|
|
23
|
-
} from './sd.js';
|
|
24
|
-
|
|
25
|
-
const DIGEST_ALGORITHMS: readonly HashAlgorithm[] = ['sha256', 'sha512', 'blake3'];
|
|
26
|
-
// SQL digest returns TEXT, so only text-producing encodings are valid here ('bytes' is JS-only).
|
|
27
|
-
const DIGEST_TEXT_ENCODINGS: readonly OutputEncoding[] = ['base64url', 'base64', 'hex'];
|
|
28
|
-
|
|
29
|
-
function configAlgorithm(config: Record<string, SqlValue>): HashAlgorithm {
|
|
30
|
-
const value = config.algorithm == null ? 'sha256' : String(config.algorithm);
|
|
31
|
-
if (!DIGEST_ALGORITHMS.includes(value as HashAlgorithm)) {
|
|
32
|
-
throw new Error(`crypto plugin: unsupported digest algorithm '${value}' (expected one of ${DIGEST_ALGORITHMS.join(', ')})`);
|
|
33
|
-
}
|
|
34
|
-
return value as HashAlgorithm;
|
|
35
|
-
}
|
|
36
|
-
|
|
37
|
-
function configEncoding(config: Record<string, SqlValue>): OutputEncoding {
|
|
38
|
-
const value = config.encoding == null ? 'base64url' : String(config.encoding);
|
|
39
|
-
if (!DIGEST_TEXT_ENCODINGS.includes(value as OutputEncoding)) {
|
|
40
|
-
throw new Error(`crypto plugin: unsupported digest encoding '${value}' (expected one of ${DIGEST_TEXT_ENCODINGS.join(', ')})`);
|
|
41
|
-
}
|
|
42
|
-
return value as OutputEncoding;
|
|
43
|
-
}
|
|
44
|
-
|
|
45
|
-
/**
|
|
46
|
-
* Coerce a SQL `data`/`digest` argument to raw bytes. A BLOB arrives as a
|
|
47
|
-
* Uint8Array and is used directly; TEXT is interpreted as base64url — the
|
|
48
|
-
* plugin's canonical text encoding — so `cid_v1(digest(...))` composes with the
|
|
49
|
-
* base64url string `digest` returns, with no extra round-trip.
|
|
50
|
-
*/
|
|
51
|
-
function toContentBytes(value: SqlValue | undefined, fnName: string): Uint8Array {
|
|
52
|
-
if (value instanceof Uint8Array) {
|
|
53
|
-
return value;
|
|
54
|
-
}
|
|
55
|
-
if (typeof value === 'string') {
|
|
56
|
-
return uint8ArrayFromString(value, 'base64url');
|
|
57
|
-
}
|
|
58
|
-
throw new Error(`${fnName}: expected a BLOB or base64url TEXT argument, got ${value == null ? 'NULL' : typeof value}`);
|
|
59
|
-
}
|
|
60
|
-
|
|
61
|
-
/**
|
|
62
|
-
* Parse one JSON leaf — either `[name, value, salt]` or `{ name, value, salt }` —
|
|
63
|
-
* into a {@link SaltedLeaf}. The JSON value maps directly to the `encodeFields` value
|
|
64
|
-
* space (INTEGER vs REAL by JS value, TEXT, BOOL, null, nested object/array → JSON).
|
|
65
|
-
*
|
|
66
|
-
* Note: a BLOB-valued attribute is passed as its base64url TEXT and committed AS TEXT
|
|
67
|
-
* (JSON has no blob type); callers needing a true BLOB value must use the JS API with a
|
|
68
|
-
* `Uint8Array`. The salt is likewise base64url TEXT (decoded to bytes by `set_commit`).
|
|
69
|
-
*/
|
|
70
|
-
function leafFromJson(entry: unknown, fnName: string): SaltedLeaf {
|
|
71
|
-
if (Array.isArray(entry)) {
|
|
72
|
-
if (entry.length < 3) {
|
|
73
|
-
throw new Error(`${fnName}: a leaf array must be [name, value, salt]`);
|
|
74
|
-
}
|
|
75
|
-
const [name, value, salt] = entry;
|
|
76
|
-
if (typeof name !== 'string') {
|
|
77
|
-
throw new Error(`${fnName}: leaf name must be a string`);
|
|
78
|
-
}
|
|
79
|
-
return { name, value: value as DigestField, salt: salt as string };
|
|
80
|
-
}
|
|
81
|
-
if (entry !== null && typeof entry === 'object') {
|
|
82
|
-
const o = entry as Record<string, unknown>;
|
|
83
|
-
if (typeof o.name !== 'string') {
|
|
84
|
-
throw new Error(`${fnName}: leaf name must be a string`);
|
|
85
|
-
}
|
|
86
|
-
// Require an explicit `value` key (symmetric with the array form, which demands all
|
|
87
|
-
// three positions): a silently-absent value would commit NULL and mask a malformed
|
|
88
|
-
// leaf. To commit a null-valued attribute, pass `value: null` explicitly.
|
|
89
|
-
if (!('value' in o)) {
|
|
90
|
-
throw new Error(`${fnName}: leaf '${o.name}' is missing a value (pass value: null for a null-valued attribute)`);
|
|
91
|
-
}
|
|
92
|
-
return { name: o.name, value: o.value as DigestField, salt: o.salt as string };
|
|
93
|
-
}
|
|
94
|
-
throw new Error(`${fnName}: each leaf must be a [name, value, salt] array or { name, value, salt } object`);
|
|
95
|
-
}
|
|
96
|
-
|
|
97
|
-
/** Parse a JSON array of leaves. Throws on unparseable / non-array input. */
|
|
98
|
-
function parseLeaves(json: string, fnName: string): SaltedLeaf[] {
|
|
99
|
-
const parsed = JSON.parse(json);
|
|
100
|
-
if (!Array.isArray(parsed)) {
|
|
101
|
-
throw new Error(`${fnName}: expected a JSON array of leaves`);
|
|
102
|
-
}
|
|
103
|
-
return parsed.map((entry) => leafFromJson(entry, fnName));
|
|
104
|
-
}
|
|
105
|
-
|
|
106
|
-
// Flags for deterministic functions (UTF8 + DETERMINISTIC)
|
|
107
|
-
const DETERMINISTIC_FLAGS = FunctionFlags.UTF8 | FunctionFlags.DETERMINISTIC;
|
|
108
|
-
// Flags for non-deterministic functions (UTF8 only)
|
|
109
|
-
const NON_DETERMINISTIC_FLAGS = FunctionFlags.UTF8;
|
|
110
|
-
|
|
111
|
-
/**
|
|
112
|
-
* Plugin registration function
|
|
113
|
-
* This is called by Quereus when the plugin is loaded
|
|
114
|
-
*/
|
|
115
|
-
export default function register(_db: Database, config: Record<string, SqlValue> = {}) {
|
|
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
|
|
118
|
-
// digest is stable for the lifetime of the database (a precondition for
|
|
119
|
-
// `replicable`: every peer that loads the plugin with the same config agrees).
|
|
120
|
-
const digestHasher = resolveHasher(configAlgorithm(config));
|
|
121
|
-
const digestEncoder = resolveOutputEncoder(configEncoding(config));
|
|
122
|
-
|
|
123
|
-
// Register crypto functions with Quereus
|
|
124
|
-
const functions = [
|
|
125
|
-
{
|
|
126
|
-
schema: {
|
|
127
|
-
name: 'digest',
|
|
128
|
-
numArgs: -1, // Variadic over data fields: digest(f1, f2, ..., fN)
|
|
129
|
-
flags: DETERMINISTIC_FLAGS, // digest is deterministic
|
|
130
|
-
// Bit-identical across peers/platforms — these digests are signed and persisted.
|
|
131
|
-
replicable: true,
|
|
132
|
-
returnType: { typeClass: 'scalar' as const, logicalType: TEXT_TYPE, nullable: false },
|
|
133
|
-
implementation: (...fields: SqlValue[]) =>
|
|
134
|
-
digestFields(fields as DigestField[], digestHasher, digestEncoder) as string,
|
|
135
|
-
},
|
|
136
|
-
},
|
|
137
|
-
{
|
|
138
|
-
schema: {
|
|
139
|
-
name: 'cid',
|
|
140
|
-
numArgs: -1, // cid(data, codec?, hash?, base?) — trailing args optional
|
|
141
|
-
flags: DETERMINISTIC_FLAGS,
|
|
142
|
-
// Self-describing content address; signed/persisted, so byte-identical across peers.
|
|
143
|
-
replicable: true,
|
|
144
|
-
returnType: { typeClass: 'scalar' as const, logicalType: TEXT_TYPE, nullable: false },
|
|
145
|
-
implementation: (...args: SqlValue[]) => {
|
|
146
|
-
const [data, codec = 'raw', hash = 'sha2-256', base = 'base32'] = args;
|
|
147
|
-
return cid(toContentBytes(data, 'cid'), codec as Multicodec, hash as MultihashCode, base as Multibase);
|
|
148
|
-
},
|
|
149
|
-
},
|
|
150
|
-
},
|
|
151
|
-
{
|
|
152
|
-
schema: {
|
|
153
|
-
name: 'cid_v1',
|
|
154
|
-
numArgs: -1, // cid_v1(digest, hash, codec?, base?) — hash required, trailing args optional
|
|
155
|
-
flags: DETERMINISTIC_FLAGS,
|
|
156
|
-
replicable: true,
|
|
157
|
-
returnType: { typeClass: 'scalar' as const, logicalType: TEXT_TYPE, nullable: false },
|
|
158
|
-
implementation: (...args: SqlValue[]) => {
|
|
159
|
-
const [digest, hash, codec = 'raw', base = 'base32'] = args;
|
|
160
|
-
if (hash == null) {
|
|
161
|
-
throw new Error("cid_v1: 'hash' argument is required (the multihash code asserting which algorithm produced the digest)");
|
|
162
|
-
}
|
|
163
|
-
return cidV1(toContentBytes(digest, 'cid_v1'), hash as MultihashCode, codec as Multicodec, base as Multibase);
|
|
164
|
-
},
|
|
165
|
-
},
|
|
166
|
-
},
|
|
167
|
-
{
|
|
168
|
-
schema: {
|
|
169
|
-
name: 'cid_decode',
|
|
170
|
-
numArgs: 1, // cid_decode(cid) -> JSON text { version, codec, hashCode, digest }
|
|
171
|
-
flags: DETERMINISTIC_FLAGS,
|
|
172
|
-
replicable: true,
|
|
173
|
-
returnType: { typeClass: 'scalar' as const, logicalType: TEXT_TYPE, nullable: false },
|
|
174
|
-
implementation: (value: SqlValue) => {
|
|
175
|
-
const parts = cidDecode(value as string);
|
|
176
|
-
// JSON object (Quereus has native JSON); digest is base64url, the plugin's canonical text encoding.
|
|
177
|
-
return JSON.stringify({
|
|
178
|
-
version: parts.version,
|
|
179
|
-
codec: parts.codec,
|
|
180
|
-
hashCode: parts.hashCode,
|
|
181
|
-
digest: uint8ArrayToString(parts.digest, 'base64url'),
|
|
182
|
-
});
|
|
183
|
-
},
|
|
184
|
-
},
|
|
185
|
-
},
|
|
186
|
-
{
|
|
187
|
-
schema: {
|
|
188
|
-
name: 'set_commit',
|
|
189
|
-
numArgs: 1, // set_commit(leaves_json) -> root over a JSON array of [name, value, salt] leaves
|
|
190
|
-
flags: DETERMINISTIC_FLAGS,
|
|
191
|
-
// The root is signed and persisted as a commitment, same bar as `digest`.
|
|
192
|
-
replicable: true,
|
|
193
|
-
returnType: { typeClass: 'scalar' as const, logicalType: TEXT_TYPE, nullable: false },
|
|
194
|
-
implementation: (leavesJson: SqlValue) => {
|
|
195
|
-
if (typeof leavesJson !== 'string') {
|
|
196
|
-
throw new Error('set_commit: expected a JSON TEXT array of [name, value, salt] leaves');
|
|
197
|
-
}
|
|
198
|
-
const leaves = parseLeaves(leavesJson, 'set_commit');
|
|
199
|
-
return setCommit(leaves, digestHasher, digestEncoder) as string;
|
|
200
|
-
},
|
|
201
|
-
},
|
|
202
|
-
},
|
|
203
|
-
{
|
|
204
|
-
schema: {
|
|
205
|
-
name: 'set_verify',
|
|
206
|
-
numArgs: 3, // set_verify(root, disclosed_json, hidden_json) -> BOOLEAN
|
|
207
|
-
flags: DETERMINISTIC_FLAGS, // pure, not persisted — matches `verify` (no `replicable`)
|
|
208
|
-
returnType: { typeClass: 'scalar' as const, logicalType: BOOLEAN_TYPE, nullable: false },
|
|
209
|
-
implementation: (root: SqlValue, disclosedJson: SqlValue, hiddenJson: SqlValue) => {
|
|
210
|
-
// Forgiving contract (mirrors `verify`): any malformed input → false, never throw.
|
|
211
|
-
try {
|
|
212
|
-
if (typeof root !== 'string' && !(root instanceof Uint8Array)) return false;
|
|
213
|
-
if (typeof disclosedJson !== 'string' || typeof hiddenJson !== 'string') return false;
|
|
214
|
-
const disclosed = parseLeaves(disclosedJson, 'set_verify');
|
|
215
|
-
const hidden = JSON.parse(hiddenJson);
|
|
216
|
-
if (!Array.isArray(hidden) || !hidden.every((h) => typeof h === 'string')) return false;
|
|
217
|
-
return setVerify(root, { disclosed, hidden: hidden as string[] }, digestHasher, digestEncoder);
|
|
218
|
-
} catch {
|
|
219
|
-
return false;
|
|
220
|
-
}
|
|
221
|
-
},
|
|
222
|
-
},
|
|
223
|
-
},
|
|
224
|
-
{
|
|
225
|
-
schema: {
|
|
226
|
-
name: 'sign',
|
|
227
|
-
numArgs: -1, // Variable arguments: data, privateKey, curve?, inputEncoding?, keyEncoding?, outputEncoding?
|
|
228
|
-
flags: DETERMINISTIC_FLAGS, // sign is deterministic (same key + data = same signature)
|
|
229
|
-
// Security: passing a private key as the second argument (literal or bound
|
|
230
|
-
// parameter) is SAFE with respect to replication. The Quereus engine rebuilds
|
|
231
|
-
// the replicated statement from evaluated column values, not from source SQL
|
|
232
|
-
// text, so the key argument is discarded before the record is written — peers
|
|
233
|
-
// re-execute `INSERT ... VALUES (<signature>)`, never `sign(..., key)`. What
|
|
234
|
-
// to avoid: storing a raw private key AS a column value, since any persisted
|
|
235
|
-
// column value is replicated. See docs/transactions.md § "Secrets and the
|
|
236
|
-
// replicated statement record" and the regression guard in
|
|
237
|
-
// quereus-plugin-optimystic/test/statement-secret-arg-redaction.spec.ts.
|
|
238
|
-
returnType: { typeClass: 'scalar' as const, logicalType: TEXT_TYPE, nullable: false },
|
|
239
|
-
implementation: (...args: SqlValue[]) => {
|
|
240
|
-
const [data, privateKey, curve = 'secp256k1', inputEncoding = 'base64url', keyEncoding = 'base64url', outputEncoding = 'base64url'] = args;
|
|
241
|
-
return sign(data as string, privateKey as string, curve as any, inputEncoding as any, keyEncoding as any, outputEncoding as any);
|
|
242
|
-
},
|
|
243
|
-
},
|
|
244
|
-
},
|
|
245
|
-
{
|
|
246
|
-
schema: {
|
|
247
|
-
name: 'verify',
|
|
248
|
-
numArgs: -1, // Variable arguments: data, signature, publicKey, curve?, inputEncoding?, sigEncoding?, keyEncoding?
|
|
249
|
-
flags: DETERMINISTIC_FLAGS, // verify is deterministic
|
|
250
|
-
returnType: { typeClass: 'scalar' as const, logicalType: BOOLEAN_TYPE, nullable: false },
|
|
251
|
-
implementation: (...args: SqlValue[]) => {
|
|
252
|
-
const [data, signature, publicKey, curve = 'secp256k1', inputEncoding = 'base64url', sigEncoding = 'base64url', keyEncoding = 'base64url'] = args;
|
|
253
|
-
const result = verify(data as string, signature as string, publicKey as string, curve as any, inputEncoding as any, sigEncoding as any, keyEncoding as any);
|
|
254
|
-
return result;
|
|
255
|
-
},
|
|
256
|
-
},
|
|
257
|
-
},
|
|
258
|
-
{
|
|
259
|
-
schema: {
|
|
260
|
-
name: 'hash_mod',
|
|
261
|
-
numArgs: -1, // Variable arguments: data, bits, algorithm?, inputEncoding?
|
|
262
|
-
flags: DETERMINISTIC_FLAGS, // hash_mod is deterministic
|
|
263
|
-
returnType: { typeClass: 'scalar' as const, logicalType: INTEGER_TYPE, nullable: false },
|
|
264
|
-
implementation: (...args: SqlValue[]) => {
|
|
265
|
-
const [data, bits, algorithm = 'sha256', inputEncoding = 'base64url'] = args;
|
|
266
|
-
return hashMod(data as string, bits as number, algorithm as any, inputEncoding as any);
|
|
267
|
-
},
|
|
268
|
-
},
|
|
269
|
-
},
|
|
270
|
-
{
|
|
271
|
-
schema: {
|
|
272
|
-
name: 'random_bytes',
|
|
273
|
-
numArgs: -1, // Variable arguments: bits?, encoding?
|
|
274
|
-
flags: NON_DETERMINISTIC_FLAGS, // random_bytes is NOT deterministic
|
|
275
|
-
returnType: { typeClass: 'scalar' as const, logicalType: TEXT_TYPE, nullable: false },
|
|
276
|
-
implementation: (...args: SqlValue[]) => {
|
|
277
|
-
const [bits = 256, encoding = 'base64url'] = args;
|
|
278
|
-
return randomBytes(bits as number, encoding as any);
|
|
279
|
-
},
|
|
280
|
-
},
|
|
281
|
-
},
|
|
282
|
-
];
|
|
283
|
-
|
|
284
|
-
return {
|
|
285
|
-
functions,
|
|
286
|
-
vtables: [],
|
|
287
|
-
collations: [],
|
|
288
|
-
};
|
|
289
|
-
}
|
|
290
|
-
|
|
1
|
+
/**
|
|
2
|
+
* Quereus Plugin Entry Point for Crypto Functions
|
|
3
|
+
*
|
|
4
|
+
* This module provides the plugin registration following Quereus 0.4.5 format.
|
|
5
|
+
* All metadata is in package.json - no manifest export needed.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import type { Database, SqlValue } from '@quereus/quereus';
|
|
9
|
+
import { FunctionFlags, TEXT_TYPE, INTEGER_TYPE, BOOLEAN_TYPE } from '@quereus/quereus';
|
|
10
|
+
import { fromString as uint8ArrayFromString, toString as uint8ArrayToString } from 'uint8arrays';
|
|
11
|
+
import {
|
|
12
|
+
sign, verify, hashMod, randomBytes,
|
|
13
|
+
digestFields, resolveHasher, resolveOutputEncoder,
|
|
14
|
+
type HashAlgorithm, type OutputEncoding, type DigestField,
|
|
15
|
+
} from './crypto.js';
|
|
16
|
+
import {
|
|
17
|
+
cid, cidV1, cidDecode,
|
|
18
|
+
type Multicodec, type MultihashCode, type Multibase,
|
|
19
|
+
} from './cid.js';
|
|
20
|
+
import {
|
|
21
|
+
setCommit, setVerify,
|
|
22
|
+
type SaltedLeaf,
|
|
23
|
+
} from './sd.js';
|
|
24
|
+
|
|
25
|
+
const DIGEST_ALGORITHMS: readonly HashAlgorithm[] = ['sha256', 'sha512', 'blake3'];
|
|
26
|
+
// SQL digest returns TEXT, so only text-producing encodings are valid here ('bytes' is JS-only).
|
|
27
|
+
const DIGEST_TEXT_ENCODINGS: readonly OutputEncoding[] = ['base64url', 'base64', 'hex'];
|
|
28
|
+
|
|
29
|
+
function configAlgorithm(config: Record<string, SqlValue>): HashAlgorithm {
|
|
30
|
+
const value = config.algorithm == null ? 'sha256' : String(config.algorithm);
|
|
31
|
+
if (!DIGEST_ALGORITHMS.includes(value as HashAlgorithm)) {
|
|
32
|
+
throw new Error(`crypto plugin: unsupported digest algorithm '${value}' (expected one of ${DIGEST_ALGORITHMS.join(', ')})`);
|
|
33
|
+
}
|
|
34
|
+
return value as HashAlgorithm;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function configEncoding(config: Record<string, SqlValue>): OutputEncoding {
|
|
38
|
+
const value = config.encoding == null ? 'base64url' : String(config.encoding);
|
|
39
|
+
if (!DIGEST_TEXT_ENCODINGS.includes(value as OutputEncoding)) {
|
|
40
|
+
throw new Error(`crypto plugin: unsupported digest encoding '${value}' (expected one of ${DIGEST_TEXT_ENCODINGS.join(', ')})`);
|
|
41
|
+
}
|
|
42
|
+
return value as OutputEncoding;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* Coerce a SQL `data`/`digest` argument to raw bytes. A BLOB arrives as a
|
|
47
|
+
* Uint8Array and is used directly; TEXT is interpreted as base64url — the
|
|
48
|
+
* plugin's canonical text encoding — so `cid_v1(digest(...))` composes with the
|
|
49
|
+
* base64url string `digest` returns, with no extra round-trip.
|
|
50
|
+
*/
|
|
51
|
+
function toContentBytes(value: SqlValue | undefined, fnName: string): Uint8Array {
|
|
52
|
+
if (value instanceof Uint8Array) {
|
|
53
|
+
return value;
|
|
54
|
+
}
|
|
55
|
+
if (typeof value === 'string') {
|
|
56
|
+
return uint8ArrayFromString(value, 'base64url');
|
|
57
|
+
}
|
|
58
|
+
throw new Error(`${fnName}: expected a BLOB or base64url TEXT argument, got ${value == null ? 'NULL' : typeof value}`);
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* Parse one JSON leaf — either `[name, value, salt]` or `{ name, value, salt }` —
|
|
63
|
+
* into a {@link SaltedLeaf}. The JSON value maps directly to the `encodeFields` value
|
|
64
|
+
* space (INTEGER vs REAL by JS value, TEXT, BOOL, null, nested object/array → JSON).
|
|
65
|
+
*
|
|
66
|
+
* Note: a BLOB-valued attribute is passed as its base64url TEXT and committed AS TEXT
|
|
67
|
+
* (JSON has no blob type); callers needing a true BLOB value must use the JS API with a
|
|
68
|
+
* `Uint8Array`. The salt is likewise base64url TEXT (decoded to bytes by `set_commit`).
|
|
69
|
+
*/
|
|
70
|
+
function leafFromJson(entry: unknown, fnName: string): SaltedLeaf {
|
|
71
|
+
if (Array.isArray(entry)) {
|
|
72
|
+
if (entry.length < 3) {
|
|
73
|
+
throw new Error(`${fnName}: a leaf array must be [name, value, salt]`);
|
|
74
|
+
}
|
|
75
|
+
const [name, value, salt] = entry;
|
|
76
|
+
if (typeof name !== 'string') {
|
|
77
|
+
throw new Error(`${fnName}: leaf name must be a string`);
|
|
78
|
+
}
|
|
79
|
+
return { name, value: value as DigestField, salt: salt as string };
|
|
80
|
+
}
|
|
81
|
+
if (entry !== null && typeof entry === 'object') {
|
|
82
|
+
const o = entry as Record<string, unknown>;
|
|
83
|
+
if (typeof o.name !== 'string') {
|
|
84
|
+
throw new Error(`${fnName}: leaf name must be a string`);
|
|
85
|
+
}
|
|
86
|
+
// Require an explicit `value` key (symmetric with the array form, which demands all
|
|
87
|
+
// three positions): a silently-absent value would commit NULL and mask a malformed
|
|
88
|
+
// leaf. To commit a null-valued attribute, pass `value: null` explicitly.
|
|
89
|
+
if (!('value' in o)) {
|
|
90
|
+
throw new Error(`${fnName}: leaf '${o.name}' is missing a value (pass value: null for a null-valued attribute)`);
|
|
91
|
+
}
|
|
92
|
+
return { name: o.name, value: o.value as DigestField, salt: o.salt as string };
|
|
93
|
+
}
|
|
94
|
+
throw new Error(`${fnName}: each leaf must be a [name, value, salt] array or { name, value, salt } object`);
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
/** Parse a JSON array of leaves. Throws on unparseable / non-array input. */
|
|
98
|
+
function parseLeaves(json: string, fnName: string): SaltedLeaf[] {
|
|
99
|
+
const parsed = JSON.parse(json);
|
|
100
|
+
if (!Array.isArray(parsed)) {
|
|
101
|
+
throw new Error(`${fnName}: expected a JSON array of leaves`);
|
|
102
|
+
}
|
|
103
|
+
return parsed.map((entry) => leafFromJson(entry, fnName));
|
|
104
|
+
}
|
|
105
|
+
|
|
106
|
+
// Flags for deterministic functions (UTF8 + DETERMINISTIC)
|
|
107
|
+
const DETERMINISTIC_FLAGS = FunctionFlags.UTF8 | FunctionFlags.DETERMINISTIC;
|
|
108
|
+
// Flags for non-deterministic functions (UTF8 only)
|
|
109
|
+
const NON_DETERMINISTIC_FLAGS = FunctionFlags.UTF8;
|
|
110
|
+
|
|
111
|
+
/**
|
|
112
|
+
* Plugin registration function
|
|
113
|
+
* This is called by Quereus when the plugin is loaded
|
|
114
|
+
*/
|
|
115
|
+
export default function register(_db: Database, config: Record<string, SqlValue> = {}) {
|
|
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
|
|
118
|
+
// digest is stable for the lifetime of the database (a precondition for
|
|
119
|
+
// `replicable`: every peer that loads the plugin with the same config agrees).
|
|
120
|
+
const digestHasher = resolveHasher(configAlgorithm(config));
|
|
121
|
+
const digestEncoder = resolveOutputEncoder(configEncoding(config));
|
|
122
|
+
|
|
123
|
+
// Register crypto functions with Quereus
|
|
124
|
+
const functions = [
|
|
125
|
+
{
|
|
126
|
+
schema: {
|
|
127
|
+
name: 'digest',
|
|
128
|
+
numArgs: -1, // Variadic over data fields: digest(f1, f2, ..., fN)
|
|
129
|
+
flags: DETERMINISTIC_FLAGS, // digest is deterministic
|
|
130
|
+
// Bit-identical across peers/platforms — these digests are signed and persisted.
|
|
131
|
+
replicable: true,
|
|
132
|
+
returnType: { typeClass: 'scalar' as const, logicalType: TEXT_TYPE, nullable: false },
|
|
133
|
+
implementation: (...fields: SqlValue[]) =>
|
|
134
|
+
digestFields(fields as DigestField[], digestHasher, digestEncoder) as string,
|
|
135
|
+
},
|
|
136
|
+
},
|
|
137
|
+
{
|
|
138
|
+
schema: {
|
|
139
|
+
name: 'cid',
|
|
140
|
+
numArgs: -1, // cid(data, codec?, hash?, base?) — trailing args optional
|
|
141
|
+
flags: DETERMINISTIC_FLAGS,
|
|
142
|
+
// Self-describing content address; signed/persisted, so byte-identical across peers.
|
|
143
|
+
replicable: true,
|
|
144
|
+
returnType: { typeClass: 'scalar' as const, logicalType: TEXT_TYPE, nullable: false },
|
|
145
|
+
implementation: (...args: SqlValue[]) => {
|
|
146
|
+
const [data, codec = 'raw', hash = 'sha2-256', base = 'base32'] = args;
|
|
147
|
+
return cid(toContentBytes(data, 'cid'), codec as Multicodec, hash as MultihashCode, base as Multibase);
|
|
148
|
+
},
|
|
149
|
+
},
|
|
150
|
+
},
|
|
151
|
+
{
|
|
152
|
+
schema: {
|
|
153
|
+
name: 'cid_v1',
|
|
154
|
+
numArgs: -1, // cid_v1(digest, hash, codec?, base?) — hash required, trailing args optional
|
|
155
|
+
flags: DETERMINISTIC_FLAGS,
|
|
156
|
+
replicable: true,
|
|
157
|
+
returnType: { typeClass: 'scalar' as const, logicalType: TEXT_TYPE, nullable: false },
|
|
158
|
+
implementation: (...args: SqlValue[]) => {
|
|
159
|
+
const [digest, hash, codec = 'raw', base = 'base32'] = args;
|
|
160
|
+
if (hash == null) {
|
|
161
|
+
throw new Error("cid_v1: 'hash' argument is required (the multihash code asserting which algorithm produced the digest)");
|
|
162
|
+
}
|
|
163
|
+
return cidV1(toContentBytes(digest, 'cid_v1'), hash as MultihashCode, codec as Multicodec, base as Multibase);
|
|
164
|
+
},
|
|
165
|
+
},
|
|
166
|
+
},
|
|
167
|
+
{
|
|
168
|
+
schema: {
|
|
169
|
+
name: 'cid_decode',
|
|
170
|
+
numArgs: 1, // cid_decode(cid) -> JSON text { version, codec, hashCode, digest }
|
|
171
|
+
flags: DETERMINISTIC_FLAGS,
|
|
172
|
+
replicable: true,
|
|
173
|
+
returnType: { typeClass: 'scalar' as const, logicalType: TEXT_TYPE, nullable: false },
|
|
174
|
+
implementation: (value: SqlValue) => {
|
|
175
|
+
const parts = cidDecode(value as string);
|
|
176
|
+
// JSON object (Quereus has native JSON); digest is base64url, the plugin's canonical text encoding.
|
|
177
|
+
return JSON.stringify({
|
|
178
|
+
version: parts.version,
|
|
179
|
+
codec: parts.codec,
|
|
180
|
+
hashCode: parts.hashCode,
|
|
181
|
+
digest: uint8ArrayToString(parts.digest, 'base64url'),
|
|
182
|
+
});
|
|
183
|
+
},
|
|
184
|
+
},
|
|
185
|
+
},
|
|
186
|
+
{
|
|
187
|
+
schema: {
|
|
188
|
+
name: 'set_commit',
|
|
189
|
+
numArgs: 1, // set_commit(leaves_json) -> root over a JSON array of [name, value, salt] leaves
|
|
190
|
+
flags: DETERMINISTIC_FLAGS,
|
|
191
|
+
// The root is signed and persisted as a commitment, same bar as `digest`.
|
|
192
|
+
replicable: true,
|
|
193
|
+
returnType: { typeClass: 'scalar' as const, logicalType: TEXT_TYPE, nullable: false },
|
|
194
|
+
implementation: (leavesJson: SqlValue) => {
|
|
195
|
+
if (typeof leavesJson !== 'string') {
|
|
196
|
+
throw new Error('set_commit: expected a JSON TEXT array of [name, value, salt] leaves');
|
|
197
|
+
}
|
|
198
|
+
const leaves = parseLeaves(leavesJson, 'set_commit');
|
|
199
|
+
return setCommit(leaves, digestHasher, digestEncoder) as string;
|
|
200
|
+
},
|
|
201
|
+
},
|
|
202
|
+
},
|
|
203
|
+
{
|
|
204
|
+
schema: {
|
|
205
|
+
name: 'set_verify',
|
|
206
|
+
numArgs: 3, // set_verify(root, disclosed_json, hidden_json) -> BOOLEAN
|
|
207
|
+
flags: DETERMINISTIC_FLAGS, // pure, not persisted — matches `verify` (no `replicable`)
|
|
208
|
+
returnType: { typeClass: 'scalar' as const, logicalType: BOOLEAN_TYPE, nullable: false },
|
|
209
|
+
implementation: (root: SqlValue, disclosedJson: SqlValue, hiddenJson: SqlValue) => {
|
|
210
|
+
// Forgiving contract (mirrors `verify`): any malformed input → false, never throw.
|
|
211
|
+
try {
|
|
212
|
+
if (typeof root !== 'string' && !(root instanceof Uint8Array)) return false;
|
|
213
|
+
if (typeof disclosedJson !== 'string' || typeof hiddenJson !== 'string') return false;
|
|
214
|
+
const disclosed = parseLeaves(disclosedJson, 'set_verify');
|
|
215
|
+
const hidden = JSON.parse(hiddenJson);
|
|
216
|
+
if (!Array.isArray(hidden) || !hidden.every((h) => typeof h === 'string')) return false;
|
|
217
|
+
return setVerify(root, { disclosed, hidden: hidden as string[] }, digestHasher, digestEncoder);
|
|
218
|
+
} catch {
|
|
219
|
+
return false;
|
|
220
|
+
}
|
|
221
|
+
},
|
|
222
|
+
},
|
|
223
|
+
},
|
|
224
|
+
{
|
|
225
|
+
schema: {
|
|
226
|
+
name: 'sign',
|
|
227
|
+
numArgs: -1, // Variable arguments: data, privateKey, curve?, inputEncoding?, keyEncoding?, outputEncoding?
|
|
228
|
+
flags: DETERMINISTIC_FLAGS, // sign is deterministic (same key + data = same signature)
|
|
229
|
+
// Security: passing a private key as the second argument (literal or bound
|
|
230
|
+
// parameter) is SAFE with respect to replication. The Quereus engine rebuilds
|
|
231
|
+
// the replicated statement from evaluated column values, not from source SQL
|
|
232
|
+
// text, so the key argument is discarded before the record is written — peers
|
|
233
|
+
// re-execute `INSERT ... VALUES (<signature>)`, never `sign(..., key)`. What
|
|
234
|
+
// to avoid: storing a raw private key AS a column value, since any persisted
|
|
235
|
+
// column value is replicated. See docs/transactions.md § "Secrets and the
|
|
236
|
+
// replicated statement record" and the regression guard in
|
|
237
|
+
// quereus-plugin-optimystic/test/statement-secret-arg-redaction.spec.ts.
|
|
238
|
+
returnType: { typeClass: 'scalar' as const, logicalType: TEXT_TYPE, nullable: false },
|
|
239
|
+
implementation: (...args: SqlValue[]) => {
|
|
240
|
+
const [data, privateKey, curve = 'secp256k1', inputEncoding = 'base64url', keyEncoding = 'base64url', outputEncoding = 'base64url'] = args;
|
|
241
|
+
return sign(data as string, privateKey as string, curve as any, inputEncoding as any, keyEncoding as any, outputEncoding as any);
|
|
242
|
+
},
|
|
243
|
+
},
|
|
244
|
+
},
|
|
245
|
+
{
|
|
246
|
+
schema: {
|
|
247
|
+
name: 'verify',
|
|
248
|
+
numArgs: -1, // Variable arguments: data, signature, publicKey, curve?, inputEncoding?, sigEncoding?, keyEncoding?
|
|
249
|
+
flags: DETERMINISTIC_FLAGS, // verify is deterministic
|
|
250
|
+
returnType: { typeClass: 'scalar' as const, logicalType: BOOLEAN_TYPE, nullable: false },
|
|
251
|
+
implementation: (...args: SqlValue[]) => {
|
|
252
|
+
const [data, signature, publicKey, curve = 'secp256k1', inputEncoding = 'base64url', sigEncoding = 'base64url', keyEncoding = 'base64url'] = args;
|
|
253
|
+
const result = verify(data as string, signature as string, publicKey as string, curve as any, inputEncoding as any, sigEncoding as any, keyEncoding as any);
|
|
254
|
+
return result;
|
|
255
|
+
},
|
|
256
|
+
},
|
|
257
|
+
},
|
|
258
|
+
{
|
|
259
|
+
schema: {
|
|
260
|
+
name: 'hash_mod',
|
|
261
|
+
numArgs: -1, // Variable arguments: data, bits, algorithm?, inputEncoding?
|
|
262
|
+
flags: DETERMINISTIC_FLAGS, // hash_mod is deterministic
|
|
263
|
+
returnType: { typeClass: 'scalar' as const, logicalType: INTEGER_TYPE, nullable: false },
|
|
264
|
+
implementation: (...args: SqlValue[]) => {
|
|
265
|
+
const [data, bits, algorithm = 'sha256', inputEncoding = 'base64url'] = args;
|
|
266
|
+
return hashMod(data as string, bits as number, algorithm as any, inputEncoding as any);
|
|
267
|
+
},
|
|
268
|
+
},
|
|
269
|
+
},
|
|
270
|
+
{
|
|
271
|
+
schema: {
|
|
272
|
+
name: 'random_bytes',
|
|
273
|
+
numArgs: -1, // Variable arguments: bits?, encoding?
|
|
274
|
+
flags: NON_DETERMINISTIC_FLAGS, // random_bytes is NOT deterministic
|
|
275
|
+
returnType: { typeClass: 'scalar' as const, logicalType: TEXT_TYPE, nullable: false },
|
|
276
|
+
implementation: (...args: SqlValue[]) => {
|
|
277
|
+
const [bits = 256, encoding = 'base64url'] = args;
|
|
278
|
+
return randomBytes(bits as number, encoding as any);
|
|
279
|
+
},
|
|
280
|
+
},
|
|
281
|
+
},
|
|
282
|
+
];
|
|
283
|
+
|
|
284
|
+
return {
|
|
285
|
+
functions,
|
|
286
|
+
vtables: [],
|
|
287
|
+
collations: [],
|
|
288
|
+
};
|
|
289
|
+
}
|
|
290
|
+
|