ezship 0.1.11 → 0.1.12

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/access.mjs ADDED
@@ -0,0 +1,987 @@
1
+ // Row access (docs/adr/0098): who reads and writes which rows of each Table, declared once in the Global
2
+ // Workspace's db/access.sql and enforced by the Host for every artifact (a Live definition, docs/adr/0096).
3
+ // Zero dependencies, plain JavaScript, Node 20+ and the browser. The parser, the validation against the
4
+ // published schema, the SQL a condition compiles to and the printed form all live here, so the Host, `ez`
5
+ // and the Framework cannot disagree about what a rule means.
6
+
7
+ import { isReservedGroup, physicalName, RESERVED_GROUPS } from "./schema.mjs";
8
+
9
+ /**
10
+ * The Global file holding the access rules. Optional; a Table it does not name keeps its schema policy.
11
+ * @type {typeof import("./access.d.mts").ACCESS_FILE}
12
+ */
13
+ export const ACCESS_FILE = "db/access.sql";
14
+
15
+ /**
16
+ * @typedef {import("./access.d.mts").Access} Access
17
+ * @typedef {import("./access.d.mts").Rule} Rule
18
+ * @typedef {import("./access.d.mts").Condition} Condition
19
+ * @typedef {import("./access.d.mts").LookupCondition} LookupCondition
20
+ * @typedef {import("./access.d.mts").Literal} Literal
21
+ * @typedef {import("./schema.d.mts").Declaration} Declaration
22
+ * @typedef {import("./schema.d.mts").Table} Table
23
+ * @typedef {{error: string, line: number}} ParseError
24
+ * @typedef {{kind: "word" | "string" | "number" | "(" | ")" | "." | "," | "=" | ";", text: string, line: number}} Token
25
+ */
26
+
27
+ const NAME = /^[a-z][a-z0-9_]{0,62}$/;
28
+ const GROUP = /^[a-z][a-z0-9-]{0,39}$/;
29
+
30
+ // ---- tokens ---------------------------------------------------------------------------------------------
31
+
32
+ /** @param {string} sql @returns {{tokens: Token[]} | ParseError} */
33
+ function tokenize(sql) {
34
+ /** @type {Token[]} */
35
+ const tokens = [];
36
+ let line = 1;
37
+ let i = 0;
38
+ while (i < sql.length) {
39
+ const c = sql[i];
40
+ if (c === "\n") {
41
+ line++;
42
+ i++;
43
+ } else if (c === " " || c === "\t" || c === "\r") {
44
+ i++;
45
+ } else if (c === "-" && sql[i + 1] === "-") {
46
+ while (i < sql.length && sql[i] !== "\n") i++;
47
+ } else if (c === "'") {
48
+ let text = "";
49
+ let j = i + 1;
50
+ for (; j < sql.length; j++) {
51
+ if (sql[j] === "'" && sql[j + 1] === "'") {
52
+ text += "'";
53
+ j++;
54
+ } else if (sql[j] === "'") break;
55
+ else if (sql[j] === "\n") return { error: "unterminated string", line };
56
+ else text += sql[j];
57
+ }
58
+ if (j >= sql.length) return { error: "unterminated string", line };
59
+ tokens.push({ kind: "string", text, line });
60
+ i = j + 1;
61
+ } else if ("().,=;".includes(c)) {
62
+ tokens.push({ kind: /** @type {Token["kind"]} */ (c), text: c, line });
63
+ i++;
64
+ } else {
65
+ const number = /^-?[0-9]+(\.[0-9]+)?(?![A-Za-z0-9_])/.exec(sql.slice(i));
66
+ if (number) {
67
+ tokens.push({ kind: "number", text: number[0], line });
68
+ i += number[0].length;
69
+ continue;
70
+ }
71
+ const word = /^[A-Za-z_][A-Za-z0-9_-]*/.exec(sql.slice(i));
72
+ if (!word) return { error: `unexpected character ${c}`, line };
73
+ tokens.push({ kind: "word", text: word[0], line });
74
+ i += word[0].length;
75
+ }
76
+ }
77
+ return { tokens };
78
+ }
79
+
80
+ /** A statement's tokens, consumed left to right. */
81
+ class Cursor {
82
+ /** @param {Token[]} tokens @param {number} line */
83
+ constructor(tokens, line) {
84
+ this.tokens = tokens;
85
+ this.i = 0;
86
+ this.line = line;
87
+ }
88
+ /** @param {number} [k] */
89
+ peek(k = 0) {
90
+ return this.tokens[this.i + k];
91
+ }
92
+ next() {
93
+ return this.tokens[this.i++];
94
+ }
95
+ /** @param {string} word */
96
+ isWord(word, k = 0) {
97
+ const t = this.peek(k);
98
+ return t !== undefined && t.kind === "word" && t.text.toUpperCase() === word;
99
+ }
100
+ /** @param {string} word */
101
+ takeWord(word) {
102
+ if (!this.isWord(word)) return false;
103
+ this.i++;
104
+ return true;
105
+ }
106
+ /** @param {Token["kind"]} kind */
107
+ take(kind) {
108
+ const t = this.peek();
109
+ if (t === undefined || t.kind !== kind) return false;
110
+ this.i++;
111
+ return true;
112
+ }
113
+ done() {
114
+ return this.i >= this.tokens.length;
115
+ }
116
+ /** @param {string} message @returns {ParseError} */
117
+ fail(message) {
118
+ return { error: message, line: this.peek()?.line ?? this.line };
119
+ }
120
+ where() {
121
+ const t = this.peek();
122
+ return t === undefined ? "end of statement" : t.kind === "string" ? `'${t.text}'` : t.text;
123
+ }
124
+ }
125
+
126
+ // ---- statements -----------------------------------------------------------------------------------------
127
+
128
+ const SHAPE = `${ACCESS_FILE} holds READ <table> WHERE <condition>;, WRITE <table> WHERE <condition>;, WRITE <table> BY functions;, READ|WRITE <table> BY none; (each naming one Table or several, separated by commas), GROUP <name> [IMPLIES <name>, ...]; and one SCOPE`;
129
+ const GROUP_SHAPE =
130
+ "GROUP <name> [IMPLIES <name>, ...]; declares a group app code may assign and the groups holding it confers";
131
+ /** Why access.sql cannot declare or imply a Host group (docs/adr/0110). @param {string} name */
132
+ const RESERVED_DECLARED = (name) =>
133
+ `${name}: ez- groups are the Host's (${RESERVED_GROUPS.join(" for the Instance's Admins, ")} for every Builder); nothing declares, implies or assigns them`;
134
+ /** At most this many GROUP statements (docs/adr/0101), the roster's own cap on group names. */
135
+ const MAX_DECLARED = 50;
136
+ const SCOPE_SHAPE =
137
+ "SCOPE <column> FROM <savedKey> IN my(<table>.<column> [WHERE ...]); names the scoped column, the Session State key holding the active value, and where its values come from";
138
+
139
+ /**
140
+ * Parses db/access.sql. Names are checked here; whether they exist is `checkAccess`'s question.
141
+ * @type {typeof import("./access.d.mts").parseAccess}
142
+ */
143
+ export function parseAccess(sql) {
144
+ const parsed = parse(sql);
145
+ return "error" in parsed ? parsed : { access: parsed.access };
146
+ }
147
+
148
+ /**
149
+ * The rules and the line each Table and group is first named on, for checkAccess's messages.
150
+ * @param {string} sql
151
+ * @returns {{access: Access, lines: Map<string, number>} | ParseError}
152
+ */
153
+ function parse(sql) {
154
+ const tok = tokenize(sql);
155
+ if ("error" in tok) return tok;
156
+ /** @type {Token[][]} */
157
+ const statements = [];
158
+ let current = [];
159
+ for (const t of tok.tokens) {
160
+ if (t.kind === ";") {
161
+ if (current.length) statements.push(current);
162
+ current = [];
163
+ } else current.push(t);
164
+ }
165
+ if (current.length) return { error: "every statement must end with ;", line: current[0].line };
166
+ /** @type {Access} */
167
+ const access = { tables: {} };
168
+ /** @type {Map<string, number>} */
169
+ const lines = new Map();
170
+ for (const tokens of statements) {
171
+ const c = new Cursor(tokens, tokens[0].line);
172
+ const verb = c.next();
173
+ const op = verb.text.toUpperCase();
174
+ if (op === "GROUP" && verb.kind === "word") {
175
+ // GROUP <name> [IMPLIES <name>, ...]: a group app code may assign (docs/adr/0101).
176
+ const name = c.next();
177
+ if (!name || name.kind !== "word" || !GROUP.test(name.text))
178
+ return {
179
+ error: `${GROUP_SHAPE}: a group is lowercase letters, digits and -, starting with a letter (at most 40)`,
180
+ line: verb.line,
181
+ };
182
+ if (isReservedGroup(name.text))
183
+ return { error: RESERVED_DECLARED(name.text), line: verb.line };
184
+ const groups = (access.groups ??= {});
185
+ if (Object.hasOwn(groups, name.text))
186
+ return { error: `GROUP ${name.text} is declared twice`, line: verb.line };
187
+ /** @type {string[]} */
188
+ const implies = [];
189
+ if (c.takeWord("IMPLIES")) {
190
+ do {
191
+ const implied = c.next();
192
+ if (!implied || implied.kind !== "word" || !GROUP.test(implied.text))
193
+ return c.fail(`GROUP ${name.text} IMPLIES names groups, separated by commas`);
194
+ if (implied.text === name.text)
195
+ return { error: `GROUP ${name.text} cannot imply itself`, line: verb.line };
196
+ if (isReservedGroup(implied.text))
197
+ return { error: RESERVED_DECLARED(implied.text), line: verb.line };
198
+ if (!implies.includes(implied.text)) implies.push(implied.text);
199
+ } while (c.take(","));
200
+ }
201
+ if (!c.done()) return c.fail(`unexpected ${c.where()}: ${GROUP_SHAPE}`);
202
+ groups[name.text] = implies.sort();
203
+ lines.set(`group:${name.text}`, verb.line);
204
+ if (Object.keys(groups).length > MAX_DECLARED)
205
+ return { error: `${ACCESS_FILE} declares at most ${MAX_DECLARED} groups`, line: verb.line };
206
+ continue;
207
+ }
208
+ if (op === "SCOPE") {
209
+ // SCOPE <column> FROM <Saved key> IN my(<table>.<column> ...): the active scope (docs/adr/0098).
210
+ if (access.scope) return { error: "an Instance declares one SCOPE", line: verb.line };
211
+ const column = c.next();
212
+ if (!column || column.kind !== "word" || !NAME.test(column.text) || !c.takeWord("FROM"))
213
+ return { error: SCOPE_SHAPE, line: verb.line };
214
+ const key = c.next();
215
+ if (!key || key.kind !== "word" || !/^[A-Za-z_][A-Za-z0-9_]{0,62}$/.test(key.text))
216
+ return {
217
+ error: `${SCOPE_SHAPE}: FROM names a Saved key of global/session.ts`,
218
+ line: verb.line,
219
+ };
220
+ if (!c.isWord("IN")) return { error: SCOPE_SHAPE, line: verb.line };
221
+ const rest = new Cursor([column, ...tokens.slice(c.i)], verb.line);
222
+ const lookup = parseAtom(rest);
223
+ if ("error" in lookup) return lookup;
224
+ if (lookup.kind !== "my" || !rest.done()) return { error: SCOPE_SHAPE, line: verb.line };
225
+ access.scope = { column: column.text, key: key.text, lookup };
226
+ continue;
227
+ }
228
+ if (verb.kind !== "word" || (op !== "READ" && op !== "WRITE"))
229
+ return { error: `unexpected ${verb.text}: ${SHAPE}`, line: verb.line };
230
+ // One Table or several: READ a, b, c WHERE ... is one rule per Table (docs/adr/0101).
231
+ /** @type {Token[]} */
232
+ const names = [];
233
+ do {
234
+ const table = c.next();
235
+ if (!table || table.kind !== "word" || !NAME.test(table.text))
236
+ return { error: `${op} names a Table: ${SHAPE}`, line: verb.line };
237
+ names.push(table);
238
+ } while (c.take(","));
239
+ const table = names.length === 1 ? names[0] : { text: names.map((n) => n.text).join(", ") };
240
+ const key = /** @type {"read" | "write"} */ (op.toLowerCase());
241
+ for (const name of names) {
242
+ if (access.tables[name.text]?.[key])
243
+ return { error: `${op} ${name.text} is declared twice`, line: name.line };
244
+ }
245
+ /** @type {Rule} */
246
+ let rule;
247
+ if (c.takeWord("BY")) {
248
+ const who = c.next();
249
+ const by = who?.text.toLowerCase();
250
+ if (by === "none") rule = { kind: "none" };
251
+ else if (by === "functions" && key === "write") rule = { kind: "functions" };
252
+ else if (by === "functions")
253
+ return {
254
+ error: `READ ${table.text} BY functions: server functions read under the caller's READ condition; write BY functions, or give the function authority: "site"`,
255
+ line: verb.line,
256
+ };
257
+ else return { error: `BY is followed by functions or none`, line: verb.line };
258
+ } else if (c.takeWord("WHERE")) {
259
+ const cond = parseOr(c);
260
+ if ("error" in cond) return cond;
261
+ rule = { kind: "where", cond };
262
+ } else return c.fail(`after ${op} ${table.text}: WHERE <condition>, BY functions or BY none`);
263
+ if (!c.done()) return c.fail(`unexpected ${c.where()} after the rule`);
264
+ for (const name of names) {
265
+ (access.tables[name.text] ??= {})[key] = rule;
266
+ if (!lines.has(name.text)) lines.set(name.text, name.line);
267
+ }
268
+ }
269
+ if (access.groups) {
270
+ const cycle = impliedCycle(access.groups);
271
+ if (cycle)
272
+ return {
273
+ error: `GROUP ${cycle.join(" IMPLIES ")}: a group cannot imply itself, even through others`,
274
+ line: lines.get(`group:${cycle[0]}`) ?? 1,
275
+ };
276
+ }
277
+ return { access, lines };
278
+ }
279
+
280
+ /** The first chain of implications that comes back to its start, or null. @param {Record<string, string[]>} groups */
281
+ function impliedCycle(groups) {
282
+ /** @type {Set<string>} */
283
+ const done = new Set();
284
+ /** @param {string} name @param {string[]} path @returns {string[] | null} */
285
+ const visit = (name, path) => {
286
+ if (path.includes(name)) return [...path.slice(path.indexOf(name)), name];
287
+ if (done.has(name)) return null;
288
+ for (const next of groups[name] ?? []) {
289
+ const found = visit(next, [...path, name]);
290
+ if (found) return found;
291
+ }
292
+ done.add(name);
293
+ return null;
294
+ };
295
+ for (const name of Object.keys(groups).sort()) {
296
+ const found = visit(name, []);
297
+ if (found) return found;
298
+ }
299
+ return null;
300
+ }
301
+
302
+ /** @param {Cursor} c @returns {Condition | ParseError} */
303
+ function parseOr(c) {
304
+ const first = parseAnd(c);
305
+ if ("error" in first) return first;
306
+ /** @type {Condition[]} */
307
+ const items = [first];
308
+ while (c.takeWord("OR")) {
309
+ const next = parseAnd(c);
310
+ if ("error" in next) return next;
311
+ items.push(next);
312
+ }
313
+ return items.length === 1 ? first : { kind: "or", items };
314
+ }
315
+
316
+ /** @param {Cursor} c @returns {Condition | ParseError} */
317
+ function parseAnd(c) {
318
+ const first = parseAtom(c);
319
+ if ("error" in first) return first;
320
+ /** @type {Condition[]} */
321
+ const items = [first];
322
+ while (c.takeWord("AND")) {
323
+ const next = parseAtom(c);
324
+ if ("error" in next) return next;
325
+ items.push(next);
326
+ }
327
+ return items.length === 1 ? first : { kind: "and", items };
328
+ }
329
+
330
+ /** @param {Cursor} c @returns {Literal | null} */
331
+ function literal(c) {
332
+ const t = c.peek();
333
+ if (!t) return null;
334
+ if (t.kind === "string") return (c.next(), t.text);
335
+ if (t.kind === "number") return (c.next(), Number(t.text));
336
+ if (t.kind === "word" && (t.text.toLowerCase() === "true" || t.text.toLowerCase() === "false"))
337
+ return (c.next(), t.text.toLowerCase() === "true");
338
+ return null;
339
+ }
340
+
341
+ /** @param {Cursor} c @returns {Condition | ParseError} */
342
+ function parseAtom(c) {
343
+ if (c.take("(")) {
344
+ const inner = parseOr(c);
345
+ if ("error" in inner) return inner;
346
+ if (!c.take(")")) return c.fail(`expected ) but found ${c.where()}`);
347
+ return inner;
348
+ }
349
+ if (c.takeWord("OWNER")) return { kind: "owner" };
350
+ if (c.isWord("GROUP") && c.peek(1)?.kind === "(") {
351
+ c.next();
352
+ c.next();
353
+ const name = c.next();
354
+ if (!name || name.kind !== "word" || !GROUP.test(name.text))
355
+ return c.fail("group(<name>): a group is lowercase letters, digits and -");
356
+ if (!c.take(")")) return c.fail("group(<name>) needs its )");
357
+ if (
358
+ isReservedGroup(name.text) &&
359
+ !/** @type {readonly string[]} */ (RESERVED_GROUPS).includes(name.text)
360
+ )
361
+ return c.fail(
362
+ `group(${name.text}): ez- groups are the Host's, and only ${RESERVED_GROUPS.join(" and ")} exist`,
363
+ );
364
+ return { kind: "group", name: name.text };
365
+ }
366
+ const col = c.next();
367
+ if (!col || col.kind !== "word" || !NAME.test(col.text))
368
+ return c.fail(
369
+ `a condition is owner, group(<name>), <column> = me, <column> = <value>, <column> IS [NOT] NULL or <column> IN my(<table>.<column>)`,
370
+ );
371
+ const column = col.text;
372
+ if (c.takeWord("IS")) {
373
+ const not = c.takeWord("NOT");
374
+ if (!c.takeWord("NULL")) return c.fail(`${column} IS [NOT] NULL`);
375
+ return { kind: "null", column, not };
376
+ }
377
+ if (c.take("=")) {
378
+ if (c.takeWord("ME")) return { kind: "me", column };
379
+ const value = literal(c);
380
+ if (value === null)
381
+ return c.fail(`${column} = is followed by me or a quoted string, a number, true or false`);
382
+ return { kind: "eq", column, value };
383
+ }
384
+ if (c.takeWord("IN")) {
385
+ if (!c.takeWord("MY") || !c.take("("))
386
+ return c.fail(`${column} IN my(<table>.<column> [WHERE ...])`);
387
+ const table = c.next();
388
+ if (!table || table.kind !== "word" || !NAME.test(table.text) || !c.take("."))
389
+ return c.fail(`my(<table>.<column>): name the lookup Table and its column`);
390
+ const select = c.next();
391
+ if (!select || select.kind !== "word" || !NAME.test(select.text))
392
+ return c.fail(`my(<table>.<column>): name the lookup Table and its column`);
393
+ /** @type {LookupCondition[]} */
394
+ const where = [];
395
+ if (c.takeWord("WHERE")) {
396
+ do {
397
+ const inner = c.next();
398
+ if (!inner || inner.kind !== "word" || !NAME.test(inner.text))
399
+ return c.fail(
400
+ "a lookup's condition is <column> = <value>, <column> HAS '<value>' or <column> IS [NOT] NULL",
401
+ );
402
+ if (c.takeWord("HAS")) {
403
+ const v = c.next();
404
+ if (!v || v.kind !== "string") return c.fail(`${inner.text} HAS takes a quoted string`);
405
+ where.push({ kind: "has", column: inner.text, value: v.text });
406
+ } else if (c.takeWord("IS")) {
407
+ const not = c.takeWord("NOT");
408
+ if (!c.takeWord("NULL")) return c.fail(`${inner.text} IS [NOT] NULL`);
409
+ where.push({ kind: "null", column: inner.text, not });
410
+ } else if (c.take("=")) {
411
+ const value = literal(c);
412
+ if (value === null)
413
+ return c.fail(
414
+ `${inner.text} = is followed by a quoted string, a number, true or false`,
415
+ );
416
+ where.push({ kind: "eq", column: inner.text, value });
417
+ } else
418
+ return c.fail(
419
+ "a lookup's condition is <column> = <value>, <column> HAS '<value>' or <column> IS [NOT] NULL",
420
+ );
421
+ } while (c.takeWord("AND"));
422
+ }
423
+ if (!c.take(")")) return c.fail(`my(...) needs its )`);
424
+ return { kind: "my", column, table: table.text, select: select.text, where, member: "" };
425
+ }
426
+ return c.fail(`after ${column}: = me, = <value>, IS [NOT] NULL or IN my(...)`);
427
+ }
428
+
429
+ /**
430
+ * A row-free condition (docs/adr/0098): what a page's `access` or a server function's `{ access }` says,
431
+ * `group(<name>)` atoms with AND, OR and parentheses. Nothing here reads a row.
432
+ * @type {typeof import("./access.d.mts").parseGate}
433
+ */
434
+ export function parseGate(text) {
435
+ const tok = tokenize(text);
436
+ if ("error" in tok) return { error: tok.error };
437
+ if (tok.tokens.length === 0)
438
+ return { error: "an access condition names at least one group(<name>)" };
439
+ const c = new Cursor(tok.tokens, 1);
440
+ const cond = parseOr(c);
441
+ if ("error" in cond) return { error: cond.error };
442
+ if (!c.done()) return { error: `unexpected ${c.where()} in the access condition` };
443
+ /** @param {Condition} n @returns {boolean} */
444
+ const rowFree = (n) =>
445
+ n.kind === "group" || ((n.kind === "or" || n.kind === "and") && n.items.every(rowFree));
446
+ if (!rowFree(cond))
447
+ return {
448
+ error: "an access condition without a row uses group(<name>), AND, OR and parentheses only",
449
+ };
450
+ return { cond };
451
+ }
452
+
453
+ /**
454
+ * Whether a row-free condition admits a viewer's groups.
455
+ * @type {typeof import("./access.d.mts").gateAllows}
456
+ */
457
+ export function gateAllows(cond, groups) {
458
+ switch (cond.kind) {
459
+ case "group":
460
+ return groups.includes(cond.name);
461
+ case "or":
462
+ return cond.items.some((c) => gateAllows(c, groups));
463
+ case "and":
464
+ return cond.items.every((c) => gateAllows(c, groups));
465
+ // A row condition has no row here: parseGate refuses it, and it admits no one.
466
+ case "owner":
467
+ case "me":
468
+ case "eq":
469
+ case "null":
470
+ case "my":
471
+ return false;
472
+ }
473
+ }
474
+
475
+ // ---- declared groups (docs/adr/0101) --------------------------------------------------------------------
476
+
477
+ /**
478
+ * A Member's groups: the ones they were assigned plus every group those imply, transitively, sorted. What
479
+ * every test of a group reads.
480
+ * @type {typeof import("./access.d.mts").impliedGroups}
481
+ */
482
+ export function impliedGroups(access, assigned) {
483
+ const declared = access?.groups ?? {};
484
+ /** @type {Set<string>} */
485
+ const out = new Set();
486
+ /** @param {string} name */
487
+ const add = (name) => {
488
+ if (out.has(name)) return;
489
+ out.add(name);
490
+ for (const next of Object.hasOwn(declared, name) ? declared[name] : []) add(next);
491
+ };
492
+ assigned.forEach(add);
493
+ return [...out].sort();
494
+ }
495
+
496
+ /**
497
+ * The groups app code may assign: the ones db/access.sql declares, sorted.
498
+ * @type {typeof import("./access.d.mts").declaredGroups}
499
+ */
500
+ export const declaredGroups = (access) => Object.keys(access?.groups ?? {}).sort();
501
+
502
+ /**
503
+ * The GROUP statements as they are written, normalized, or null for none: what a Push compares and prints.
504
+ * @type {typeof import("./access.d.mts").printGroups}
505
+ */
506
+ export function printGroups(access) {
507
+ const names = declaredGroups(access);
508
+ if (names.length === 0) return null;
509
+ const groups = access?.groups ?? {};
510
+ return names
511
+ .map((n) => `GROUP ${n}${groups[n].length ? ` IMPLIES ${groups[n].join(", ")}` : ""};`)
512
+ .join(" ");
513
+ }
514
+
515
+ /**
516
+ * The groups whose holders change between two files' declarations: every group some group implies under
517
+ * one and not the other. Rules naming them pass for different Members after the Push.
518
+ * @type {typeof import("./access.d.mts").groupsAffected}
519
+ */
520
+ export function groupsAffected(before, next) {
521
+ /** @type {Set<string>} */
522
+ const out = new Set();
523
+ const names = new Set([...declaredGroups(before), ...declaredGroups(next)]);
524
+ for (const name of names) {
525
+ const from = new Set(impliedGroups(before, [name]));
526
+ const to = new Set(impliedGroups(next, [name]));
527
+ for (const g of from) if (!to.has(g)) out.add(g);
528
+ for (const g of to) if (!from.has(g)) out.add(g);
529
+ }
530
+ return [...out].sort();
531
+ }
532
+
533
+ /**
534
+ * The groups a rule tests.
535
+ * @type {typeof import("./access.d.mts").ruleGroups}
536
+ */
537
+ export function ruleGroups(rule) {
538
+ /** @type {Set<string>} */
539
+ const out = new Set();
540
+ /** @param {Condition} c */
541
+ const walk = (c) => {
542
+ if (c.kind === "group") out.add(c.name);
543
+ else if (c.kind === "or" || c.kind === "and") c.items.forEach(walk);
544
+ };
545
+ if (rule.kind === "where") walk(rule.cond);
546
+ return [...out].sort();
547
+ }
548
+
549
+ // ---- validation against the published schema ------------------------------------------------------------
550
+
551
+ /** @param {Table} def @param {string} column */
552
+ const typeOf = (def, column) =>
553
+ def.columns[column]?.type ??
554
+ (column === "id" || column === "created_by" || column === "updated_by"
555
+ ? "TEXT"
556
+ : column === "created_at" || column === "updated_at"
557
+ ? "TIMESTAMP"
558
+ : null);
559
+
560
+ /** Whether a column leads an index, so a condition on it is not a scan. @param {Table} def @param {string} column */
561
+ const indexed = (def, column) =>
562
+ column === "id" ||
563
+ column === "created_at" ||
564
+ [...def.indexes, ...(def.unique ?? [])].some((cols) => cols[0] === column) ||
565
+ def.columns[column]?.sequence === true;
566
+
567
+ /** Whether a literal suits a column's type; null when it does. @param {Table} def @param {string} column @param {Literal} value */
568
+ function literalError(def, column, value) {
569
+ const type = typeOf(def, column);
570
+ const col = def.columns[column];
571
+ switch (type) {
572
+ case "TEXT":
573
+ case "DATE":
574
+ if (typeof value !== "string") return `${column} is ${type}: compare it with a quoted string`;
575
+ if (col?.values && !col.values.includes(value))
576
+ return `${column} is never '${value}': its values are ${col.values.join(", ")}`;
577
+ return null;
578
+ case "INTEGER":
579
+ case "TIMESTAMP":
580
+ case "MONEY":
581
+ return typeof value === "number" && Number.isInteger(value)
582
+ ? null
583
+ : `${column} is ${type}: compare it with an integer`;
584
+ case "REAL":
585
+ return typeof value === "number" ? null : `${column} is REAL: compare it with a number`;
586
+ case "BOOLEAN":
587
+ return typeof value === "boolean"
588
+ ? null
589
+ : `${column} is BOOLEAN: compare it with true or false`;
590
+ case "MEMBER":
591
+ return `${column} is MEMBER: compare it with me`;
592
+ case "JSON":
593
+ case "FILE":
594
+ case null:
595
+ return `${column} is ${type ?? "missing"}: it cannot be compared in a condition`;
596
+ }
597
+ }
598
+
599
+ /**
600
+ * The rule that governs an operation on a Table: its db/access.sql statement, else the schema's policy.
601
+ * @type {typeof import("./access.d.mts").effectiveRule}
602
+ */
603
+ export function effectiveRule(access, table, def, op) {
604
+ const declared = access?.tables[table]?.[op];
605
+ if (declared) return declared;
606
+ const policy = op === "read" ? def.read : def.write;
607
+ // An unknown stored policy (a retired `public`, docs/adr/0036) admits no one.
608
+ return policy === undefined || policy === "member" ? { kind: "member" } : { kind: "none" };
609
+ }
610
+
611
+ /** Whether every way a condition passes needs a group: the only condition a Member cannot satisfy by writing. @param {Condition} cond @returns {boolean} */
612
+ function needsGroup(cond) {
613
+ if (cond.kind === "group") return true;
614
+ if (cond.kind === "or") return cond.items.every(needsGroup);
615
+ if (cond.kind === "and") return cond.items.some(needsGroup);
616
+ return false;
617
+ }
618
+
619
+ /**
620
+ * Whether a rule keeps Members from writing a Table on their own: BY functions, BY none, or a condition
621
+ * every branch of which needs a group. A lookup Table must be this strict, or a Member could grant themselves
622
+ * access by inserting a row.
623
+ * @param {Rule} rule
624
+ */
625
+ const strictWrite = (rule) =>
626
+ rule.kind === "none" ||
627
+ rule.kind === "functions" ||
628
+ (rule.kind === "where" && needsGroup(rule.cond));
629
+
630
+ /**
631
+ * Validates the access rules against the published schema and fills each lookup's MEMBER column. Returns the
632
+ * rules ready to compile, or the first problem with its line.
633
+ * @type {typeof import("./access.d.mts").checkAccess}
634
+ */
635
+ export function checkAccess(sql, decl) {
636
+ const parsed = parse(sql);
637
+ if ("error" in parsed) return parsed;
638
+ const { lines } = parsed;
639
+ /** @type {Access} */
640
+ const out = { tables: {}, ...(parsed.access.groups ? { groups: parsed.access.groups } : {}) };
641
+ for (const [table, ops] of Object.entries(parsed.access.tables)) {
642
+ const def = decl.tables[table];
643
+ const line = lines.get(table) ?? 1;
644
+ if (!def) return { error: `${ACCESS_FILE}: no Table "${table}" in db/schema.sql`, line };
645
+ out.tables[table] = {};
646
+ for (const op of /** @type {const} */ (["read", "write"])) {
647
+ const rule = ops[op];
648
+ if (!rule) continue;
649
+ if (rule.kind !== "where") {
650
+ out.tables[table][op] = rule;
651
+ continue;
652
+ }
653
+ const cond = checkCondition(rule.cond, table, def, decl, parsed.access);
654
+ if (typeof cond === "string") return { error: `${op.toUpperCase()} ${table}: ${cond}`, line };
655
+ out.tables[table][op] = { kind: "where", cond };
656
+ }
657
+ }
658
+ const scope = parsed.access.scope;
659
+ if (scope) {
660
+ // The scope decides nothing (every row it filters is still checked), so its lookup Table need not be
661
+ // strict; it needs the one MEMBER column that says whose values are whose.
662
+ const line = sql.split("\n").findIndex((text) => /^\s*SCOPE\b/i.test(text)) + 1;
663
+ const holder = {
664
+ columns: {
665
+ [scope.column]: {
666
+ type: /** @type {const} */ ("TEXT"),
667
+ required: false,
668
+ ref: null,
669
+ values: null,
670
+ },
671
+ },
672
+ indexes: [[scope.column]],
673
+ };
674
+ const lookup = checkCondition(
675
+ scope.lookup,
676
+ "the scoped Table",
677
+ holder,
678
+ decl,
679
+ parsed.access,
680
+ false,
681
+ );
682
+ if (typeof lookup === "string") return { error: `SCOPE ${scope.column}: ${lookup}`, line };
683
+ if (lookup.kind !== "my") return { error: SCOPE_SHAPE, line };
684
+ out.scope = { ...scope, lookup };
685
+ }
686
+ return { access: out };
687
+ }
688
+
689
+ /**
690
+ * @param {Condition} cond @param {string} table @param {Table} def @param {Declaration} decl @param {Access} access
691
+ * @param {boolean} [strict] whether a lookup Table must be one Members cannot write (not for the scope)
692
+ * @returns {Condition | string}
693
+ */
694
+ function checkCondition(cond, table, def, decl, access, strict = true) {
695
+ const missing = (/** @type {string} */ c) =>
696
+ typeOf(def, c) === null ? `no column "${c}" in ${table}` : null;
697
+ const unindexed = (/** @type {Table} */ d, /** @type {string} */ t, /** @type {string} */ c) =>
698
+ indexed(d, c)
699
+ ? null
700
+ : `${t}.${c} needs an index for this condition: CREATE INDEX ON ${t} (${c});`;
701
+ switch (cond.kind) {
702
+ case "or":
703
+ case "and": {
704
+ /** @type {Condition[]} */
705
+ const items = [];
706
+ for (const item of cond.items) {
707
+ const checked = checkCondition(item, table, def, decl, access, strict);
708
+ if (typeof checked === "string") return checked;
709
+ items.push(checked);
710
+ }
711
+ return { kind: cond.kind, items };
712
+ }
713
+ case "group":
714
+ return cond;
715
+ case "owner":
716
+ return unindexed(def, table, "created_by") ?? cond;
717
+ case "me":
718
+ return (
719
+ missing(cond.column) ??
720
+ (typeOf(def, cond.column) === "MEMBER"
721
+ ? null
722
+ : `${cond.column} = me needs a MEMBER column; ${cond.column} is ${typeOf(def, cond.column)}`) ??
723
+ unindexed(def, table, cond.column) ??
724
+ cond
725
+ );
726
+ case "eq":
727
+ return missing(cond.column) ?? literalError(def, cond.column, cond.value) ?? cond;
728
+ case "null":
729
+ return missing(cond.column) ?? cond;
730
+ case "my": {
731
+ const bad = missing(cond.column) ?? unindexed(def, table, cond.column);
732
+ if (bad) return bad;
733
+ const lookup = decl.tables[cond.table];
734
+ if (!lookup) return `my(${cond.table}.${cond.select}): no Table "${cond.table}"`;
735
+ if (typeOf(lookup, cond.select) === null)
736
+ return `my(${cond.table}.${cond.select}): no column "${cond.select}" in ${cond.table}`;
737
+ const members = Object.entries(lookup.columns)
738
+ .filter(([, c]) => c.type === "MEMBER")
739
+ .map(([c]) => c);
740
+ if (members.length !== 1)
741
+ return `my(${cond.table}...): ${cond.table} needs exactly one MEMBER column to say whose rows are whose; it has ${members.length ? members.join(", ") : "none"}`;
742
+ const member = members[0];
743
+ const memberIndex = unindexed(lookup, cond.table, member);
744
+ if (memberIndex) return memberIndex;
745
+ if (strict && !strictWrite(effectiveRule(access, cond.table, lookup, "write")))
746
+ return `my(${cond.table}...): a Member could add rows to ${cond.table} and grant themselves access. Make it WRITE ${cond.table} BY functions, BY none, or WHERE group(<name>)`;
747
+ for (const w of cond.where) {
748
+ if (typeOf(lookup, w.column) === null)
749
+ return `my(${cond.table}...): no column "${w.column}" in ${cond.table}`;
750
+ if (
751
+ w.kind === "has" &&
752
+ !(
753
+ lookup.columns[w.column]?.type === "JSON" &&
754
+ lookup.columns[w.column]?.shape === "string[]"
755
+ )
756
+ )
757
+ return `my(${cond.table}...): ${w.column} HAS needs a JSON TYPE 'string[]' column`;
758
+ if (w.kind === "eq") {
759
+ const wrong = literalError(lookup, w.column, w.value);
760
+ if (wrong) return `my(${cond.table}...): ${wrong}`;
761
+ }
762
+ }
763
+ return { ...cond, member };
764
+ }
765
+ }
766
+ }
767
+
768
+ // ---- SQL ------------------------------------------------------------------------------------------------
769
+
770
+ /** A literal in storage form: booleans as 0/1 (docs/adr/0007). @param {Literal} v */
771
+ const stored = (v) => (typeof v === "boolean" ? (v ? 1 : 0) : v);
772
+
773
+ /**
774
+ * The SQL a condition is for one viewer: `{ sql, binds }` to AND into a WHERE. `column(name)` says how the
775
+ * condition reaches a column of the governed row: its bare name for a read, `?` with the new value when a
776
+ * write checks the row it would store. Groups and a signed-out viewer fold to constants.
777
+ * @type {typeof import("./access.d.mts").compileCondition}
778
+ */
779
+ export function compileCondition(
780
+ cond,
781
+ viewer,
782
+ instance,
783
+ column = (/** @type {string} */ name) => ({ sql: name, binds: [] }),
784
+ ) {
785
+ /** @type {(string | number | null)[]} */
786
+ const binds = [];
787
+ /** @param {string} name */
788
+ const col = (name) => {
789
+ const c = column(name);
790
+ binds.push(...c.binds);
791
+ return c.sql;
792
+ };
793
+ /** @param {Condition} c @returns {string} */
794
+ const walk = (c) => {
795
+ switch (c.kind) {
796
+ case "or":
797
+ return `(${c.items.map(walk).join(" OR ")})`;
798
+ case "and":
799
+ return `(${c.items.map(walk).join(" AND ")})`;
800
+ case "group":
801
+ return viewer.groups.includes(c.name) ? "1" : "0";
802
+ case "owner":
803
+ if (!viewer.me) return "0";
804
+ return `(${col("created_by")} = ${push(viewer.me)})`;
805
+ case "me":
806
+ if (!viewer.me) return "0";
807
+ return `(${col(c.column)} = ${push(viewer.me)})`;
808
+ case "eq":
809
+ return `(${col(c.column)} = ${push(stored(c.value))})`;
810
+ case "null":
811
+ return `(${col(c.column)} IS ${c.not ? "NOT " : ""}NULL)`;
812
+ case "my": {
813
+ if (!viewer.me) return "0";
814
+ const left = col(c.column);
815
+ const inner = lookupSelect(c, viewer.me, instance);
816
+ binds.push(...inner.binds);
817
+ return `(${left} IN (${inner.sql}))`;
818
+ }
819
+ }
820
+ };
821
+ /** @param {string | number} value */
822
+ const push = (value) => {
823
+ binds.push(value);
824
+ return "?";
825
+ };
826
+ const sql = walk(cond);
827
+ return { sql, binds };
828
+ }
829
+
830
+ /**
831
+ * A lookup's values for one Member: `SELECT <table>.<select> FROM <table> WHERE <member> = ? AND ...`, what
832
+ * `IN my(...)` compares with and what the active scope's switcher lists.
833
+ * @type {typeof import("./access.d.mts").lookupSelect}
834
+ */
835
+ export function lookupSelect(lookup, me, instance) {
836
+ const table = physicalName(instance, lookup.table);
837
+ /** @type {(string | number | null)[]} */
838
+ const binds = [me];
839
+ const parts = [`${table}.${lookup.member} = ?`];
840
+ for (const w of lookup.where) {
841
+ if (w.kind === "eq") {
842
+ parts.push(`${table}.${w.column} = ?`);
843
+ binds.push(stored(w.value));
844
+ } else if (w.kind === "null") parts.push(`${table}.${w.column} IS ${w.not ? "NOT " : ""}NULL`);
845
+ else {
846
+ parts.push(
847
+ `EXISTS (SELECT 1 FROM json_each(${table}.${w.column}) WHERE json_each.value = ?)`,
848
+ );
849
+ binds.push(w.value);
850
+ }
851
+ }
852
+ return {
853
+ sql: `SELECT ${table}.${lookup.select} FROM ${table} WHERE ${parts.join(" AND ")}`,
854
+ binds,
855
+ };
856
+ }
857
+
858
+ /**
859
+ * The columns a condition reads from the governed row, for a write's check of the row it would store.
860
+ * @type {typeof import("./access.d.mts").conditionColumns}
861
+ */
862
+ export function conditionColumns(cond) {
863
+ /** @type {Set<string>} */
864
+ const out = new Set();
865
+ /** @param {Condition} c */
866
+ const walk = (c) => {
867
+ if (c.kind === "or" || c.kind === "and") c.items.forEach(walk);
868
+ else if (c.kind === "owner") out.add("created_by");
869
+ else if (c.kind !== "group") out.add(c.column);
870
+ };
871
+ walk(cond);
872
+ return [...out];
873
+ }
874
+
875
+ /**
876
+ * Every Table and column the rules read, lookups included: what must exist in the App Database before the
877
+ * rules can take effect (a Push refuses rules naming a column no Preview or Deploy has added yet).
878
+ * @type {typeof import("./access.d.mts").referencedColumns}
879
+ */
880
+ export function referencedColumns(access) {
881
+ /** @type {Map<string, Set<string>>} */
882
+ const out = new Map();
883
+ const add = (/** @type {string} */ table, /** @type {string} */ column) => {
884
+ const set = out.get(table) ?? new Set();
885
+ set.add(column);
886
+ out.set(table, set);
887
+ };
888
+ /** @param {string} table @param {Condition} c */
889
+ const walk = (table, c) => {
890
+ if (c.kind === "or" || c.kind === "and") c.items.forEach((item) => walk(table, item));
891
+ else if (c.kind === "owner") add(table, "created_by");
892
+ else if (c.kind === "my") {
893
+ add(table, c.column);
894
+ add(c.table, c.select);
895
+ add(c.table, c.member);
896
+ for (const w of c.where) add(c.table, w.column);
897
+ } else if (c.kind !== "group") add(table, c.column);
898
+ };
899
+ for (const [table, ops] of Object.entries(access.tables))
900
+ for (const rule of [ops.read, ops.write]) if (rule?.kind === "where") walk(table, rule.cond);
901
+ if (access.scope) {
902
+ const { lookup } = access.scope;
903
+ add(lookup.table, lookup.select);
904
+ add(lookup.table, lookup.member);
905
+ for (const w of lookup.where) add(lookup.table, w.column);
906
+ }
907
+ return [...out].flatMap(([table, columns]) => [...columns].map((column) => ({ table, column })));
908
+ }
909
+
910
+ /**
911
+ * The scope as it is written, or null: what a Push compares and prints.
912
+ * @type {typeof import("./access.d.mts").printScope}
913
+ */
914
+ export const printScope = (access) =>
915
+ access?.scope
916
+ ? `SCOPE ${access.scope.column} FROM ${access.scope.key} ${printCondition(access.scope.lookup).slice(access.scope.column.length + 1)}`
917
+ : null;
918
+
919
+ // ---- the printed form -----------------------------------------------------------------------------------
920
+
921
+ /** @param {Literal} v */
922
+ const printLiteral = (v) => (typeof v === "string" ? `'${v.replaceAll("'", "''")}'` : String(v));
923
+
924
+ /**
925
+ * A condition as it is written, normalized: what a Push compares and prints.
926
+ * @type {typeof import("./access.d.mts").printCondition}
927
+ */
928
+ export function printCondition(cond) {
929
+ switch (cond.kind) {
930
+ case "or":
931
+ return cond.items.map(printCondition).join(" OR ");
932
+ case "and":
933
+ return cond.items
934
+ .map((c) => (c.kind === "or" ? `(${printCondition(c)})` : printCondition(c)))
935
+ .join(" AND ");
936
+ case "group":
937
+ return `group(${cond.name})`;
938
+ case "owner":
939
+ return "owner";
940
+ case "me":
941
+ return `${cond.column} = me`;
942
+ case "eq":
943
+ return `${cond.column} = ${printLiteral(cond.value)}`;
944
+ case "null":
945
+ return `${cond.column} IS ${cond.not ? "NOT " : ""}NULL`;
946
+ case "my": {
947
+ const where = cond.where.map((w) =>
948
+ w.kind === "has"
949
+ ? `${w.column} HAS ${printLiteral(w.value)}`
950
+ : w.kind === "null"
951
+ ? `${w.column} IS ${w.not ? "NOT " : ""}NULL`
952
+ : `${w.column} = ${printLiteral(w.value)}`,
953
+ );
954
+ return `${cond.column} IN my(${cond.table}.${cond.select}${where.length ? ` WHERE ${where.join(" AND ")}` : ""})`;
955
+ }
956
+ }
957
+ }
958
+
959
+ /**
960
+ * A rule in a sentence's words: "every Member", "BY functions", "BY none", "WHERE owner".
961
+ * @type {typeof import("./access.d.mts").printRule}
962
+ */
963
+ export const printRule = (rule) =>
964
+ rule.kind === "member"
965
+ ? "every Member"
966
+ : rule.kind === "where"
967
+ ? `WHERE ${printCondition(rule.cond)}`
968
+ : `BY ${rule.kind}`;
969
+
970
+ /**
971
+ * The rules a Global Push changes (docs/adr/0096): every Table and operation whose effective rule prints
972
+ * differently under the next schema and access file than under the published ones.
973
+ * @type {typeof import("./access.d.mts").accessChanges}
974
+ */
975
+ export function accessChanges(before, beforeDecl, next, nextDecl) {
976
+ /** @type {import("./access.d.mts").AccessChange[]} */
977
+ const out = [];
978
+ for (const [table, def] of Object.entries(nextDecl.tables)) {
979
+ const old = beforeDecl.tables[table];
980
+ for (const op of /** @type {const} */ (["read", "write"])) {
981
+ const to = printRule(effectiveRule(next, table, def, op));
982
+ const from = old ? printRule(effectiveRule(before, table, old, op)) : null;
983
+ if (from !== null && from !== to) out.push({ table, op, from, to });
984
+ }
985
+ }
986
+ return out;
987
+ }