@pgxsinkit/contracts 0.2.7 → 0.3.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/dist/config.d.ts +126 -84
- package/dist/config.d.ts.map +1 -1
- package/dist/convergence-model.d.ts +2 -2
- package/dist/convergence-model.d.ts.map +1 -1
- package/dist/event-stream.d.ts +1 -1
- package/dist/fingerprint.d.ts +31 -11
- package/dist/fingerprint.d.ts.map +1 -1
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +368 -198
- package/dist/index.js.map +14 -12
- package/dist/predicate.d.ts +162 -0
- package/dist/predicate.d.ts.map +1 -0
- package/dist/projection.d.ts +1 -1
- package/dist/registry-diff.d.ts.map +1 -1
- package/dist/registry-invariant.d.ts +26 -14
- package/dist/registry-invariant.d.ts.map +1 -1
- package/dist/registry.d.ts +67 -43
- package/dist/registry.d.ts.map +1 -1
- package/dist/stream-envelope.d.ts +84 -0
- package/dist/stream-envelope.d.ts.map +1 -0
- package/dist/supabase-rls.d.ts +32 -36
- package/dist/supabase-rls.d.ts.map +1 -1
- package/package.json +1 -1
- package/skills/registry-authoring/SKILL.md +149 -149
- package/src/config.ts +154 -112
- package/src/convergence-model.ts +2 -2
- package/src/event-stream.ts +1 -1
- package/src/fingerprint.ts +76 -14
- package/src/index.ts +2 -0
- package/src/predicate.ts +274 -0
- package/src/projection.ts +1 -1
- package/src/registry-diff.ts +15 -4
- package/src/registry-invariant.ts +34 -19
- package/src/registry.ts +193 -65
- package/src/stream-envelope.ts +91 -0
- package/src/supabase-rls.ts +76 -74
package/src/predicate.ts
ADDED
|
@@ -0,0 +1,274 @@
|
|
|
1
|
+
import { getColumnTable, getTableName, type AnyColumn } from "drizzle-orm";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* The **native predicate AST** — the wire form a shape's `where` takes on the Circuits-native read
|
|
5
|
+
* path (ADR-0055), replacing the Electric path's SQL `where` **text**.
|
|
6
|
+
*
|
|
7
|
+
* This matters beyond serialization. The Electric path compiled a Drizzle `SQL` fragment down to a
|
|
8
|
+
* string that the engine then re-lexed (`where_sql.rs`); the native path never produces text at all,
|
|
9
|
+
* so there is no lexer on our path and no grammar to keep two implementations agreeing on. It is
|
|
10
|
+
* also what makes the repo's SQL-tier rule reachable at tier ① here: authoring is real column
|
|
11
|
+
* objects and typed values end to end, with no string to escape and nothing to interpolate.
|
|
12
|
+
*
|
|
13
|
+
* These types mirror `@electric-circuits/protocol`'s `Predicate` union exactly. They are restated
|
|
14
|
+
* rather than imported: this is the wire contract pgxsinkit commits to, the protocol package is
|
|
15
|
+
* alpha, and a published library should not put an alpha peer in its public types. Any divergence
|
|
16
|
+
* is a bug here — the engine's serde definitions are authoritative.
|
|
17
|
+
*/
|
|
18
|
+
export type PredicateValue = string | number | boolean | null;
|
|
19
|
+
|
|
20
|
+
/**
|
|
21
|
+
* Comparison operators for a leaf predicate.
|
|
22
|
+
*
|
|
23
|
+
* `like` is SQL `LIKE`: case-sensitive, `%` = any sequence, `_` = any single char. There is no
|
|
24
|
+
* `notLike` op — the engine models it as `Not(Like)`, which is what {@link p.notLike} builds.
|
|
25
|
+
*/
|
|
26
|
+
export type PredicateLeafOp = "eq" | "neq" | "lt" | "lte" | "gt" | "gte" | "like";
|
|
27
|
+
|
|
28
|
+
/** `col <op> value`. Three-valued: never TRUE on a NULL cell — use {@link IsNullPredicate} for that. */
|
|
29
|
+
export interface LeafPredicate {
|
|
30
|
+
col: string;
|
|
31
|
+
op: PredicateLeafOp;
|
|
32
|
+
value: PredicateValue;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
/**
|
|
36
|
+
* `col IS NULL` / `col IS NOT NULL`. A separate leaf because it is the one test that is TRUE on a
|
|
37
|
+
* NULL cell, and the only two-valued one — so it is also the only leaf that composes soundly under
|
|
38
|
+
* {@link NotPredicate}.
|
|
39
|
+
*/
|
|
40
|
+
export interface IsNullPredicate {
|
|
41
|
+
col: string;
|
|
42
|
+
isNull: boolean;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
export interface AndPredicate {
|
|
46
|
+
and: Predicate[];
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export interface OrPredicate {
|
|
50
|
+
or: Predicate[];
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export interface NotPredicate {
|
|
54
|
+
not: Predicate;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
/**
|
|
58
|
+
* The inner half of an `IN` test: the set of `project` values over `table`'s rows matching `where`.
|
|
59
|
+
* `where` may itself contain subquery leaves. Single column only — the engine has no composite
|
|
60
|
+
* `(a, b) IN (…)`. Subqueries must stay **uncorrelated**: the inner `where` references the inner
|
|
61
|
+
* table's columns only, never the outer row's.
|
|
62
|
+
*/
|
|
63
|
+
export interface SubqueryRef<TValue extends PredicateValue = PredicateValue> {
|
|
64
|
+
table: string;
|
|
65
|
+
project: string;
|
|
66
|
+
where?: Predicate;
|
|
67
|
+
/**
|
|
68
|
+
* Phantom: the projected column's value type, carried so {@link p.in} can require the OUTER column
|
|
69
|
+
* to be comparable with what the subquery actually projects. Never serialized — it is a type-level
|
|
70
|
+
* marker only, which is why it is optional and never read.
|
|
71
|
+
*/
|
|
72
|
+
readonly __value?: TValue;
|
|
73
|
+
}
|
|
74
|
+
|
|
75
|
+
/**
|
|
76
|
+
* `outer.col IN (SELECT project FROM table WHERE …)`, or `NOT IN` when `negated`. The engine
|
|
77
|
+
* maintains the inner set incrementally and shares it across every shape referencing the same
|
|
78
|
+
* subquery, which is why an entitlement-shaped subquery costs one index rather than one per shape.
|
|
79
|
+
*/
|
|
80
|
+
export interface InSubqueryPredicate {
|
|
81
|
+
col: string;
|
|
82
|
+
in: SubqueryRef;
|
|
83
|
+
negated?: boolean;
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
/** A restricted boolean predicate over one table's columns, plus single-column `IN`/`NOT IN`. */
|
|
87
|
+
export type Predicate =
|
|
88
|
+
| LeafPredicate
|
|
89
|
+
| IsNullPredicate
|
|
90
|
+
| AndPredicate
|
|
91
|
+
| OrPredicate
|
|
92
|
+
| NotPredicate
|
|
93
|
+
| InSubqueryPredicate;
|
|
94
|
+
|
|
95
|
+
export function isLeafPredicate(node: Predicate): node is LeafPredicate {
|
|
96
|
+
return "col" in node && "op" in node;
|
|
97
|
+
}
|
|
98
|
+
export function isIsNullPredicate(node: Predicate): node is IsNullPredicate {
|
|
99
|
+
return "col" in node && "isNull" in node;
|
|
100
|
+
}
|
|
101
|
+
export function isAndPredicate(node: Predicate): node is AndPredicate {
|
|
102
|
+
return "and" in node;
|
|
103
|
+
}
|
|
104
|
+
export function isOrPredicate(node: Predicate): node is OrPredicate {
|
|
105
|
+
return "or" in node;
|
|
106
|
+
}
|
|
107
|
+
export function isNotPredicate(node: Predicate): node is NotPredicate {
|
|
108
|
+
return "not" in node;
|
|
109
|
+
}
|
|
110
|
+
export function isInSubqueryPredicate(node: Predicate): node is InSubqueryPredicate {
|
|
111
|
+
return "in" in node && "col" in node;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Values reach the engine as JSON scalars, so a Drizzle column whose TS type is richer than the
|
|
116
|
+
* four Circuits column types (`int`/`text`/`bool`/`float`) has no automatic rendering here.
|
|
117
|
+
*
|
|
118
|
+
* `Date` is the case that actually turns up, and it is deliberately **not** coerced: a timestamp
|
|
119
|
+
* column syncs as `text`, and JS's ISO rendering is not Postgres's, so a silent `toISOString()`
|
|
120
|
+
* would produce a predicate that compares unequal to every row it was meant to match. Render it the
|
|
121
|
+
* way the column does and pass the string.
|
|
122
|
+
*/
|
|
123
|
+
function assertPredicateValue(column: AnyColumn, value: unknown): asserts value is PredicateValue {
|
|
124
|
+
if (value === null) return;
|
|
125
|
+
const kind = typeof value;
|
|
126
|
+
if (kind === "string" || kind === "number" || kind === "boolean") return;
|
|
127
|
+
|
|
128
|
+
const shown = value instanceof Date ? "Date" : kind === "object" ? "object" : kind;
|
|
129
|
+
throw new Error(
|
|
130
|
+
`[pgxsinkit] predicate on "${column.name}": ${shown} is not a predicate value — the wire form ` +
|
|
131
|
+
`carries JSON scalars (string | number | boolean | null). Render it to the text form the ` +
|
|
132
|
+
`column itself stores and pass that, rather than relying on a coercion that may not match.`,
|
|
133
|
+
);
|
|
134
|
+
}
|
|
135
|
+
|
|
136
|
+
/**
|
|
137
|
+
* What a builder accepts, versus {@link PredicateValue} (what goes on the wire).
|
|
138
|
+
*
|
|
139
|
+
* `bigint` is admitted because the toolkit's own timestamp convention is a **microsecond BIGINT**, so
|
|
140
|
+
* comparing against one is ordinary rather than exotic. It is narrowed to a number by `toWireValue`
|
|
141
|
+
* rather than widening the wire type: Postgres `bigint` is `ColumnType::Int` to the engine, which reads
|
|
142
|
+
* the JSON scalar as an `i64` — a decimal *string* would be rejected against an int column.
|
|
143
|
+
*/
|
|
144
|
+
export type PredicateValueInput = PredicateValue | bigint;
|
|
145
|
+
|
|
146
|
+
/** A column's TypeScript value type, as Drizzle carries it on the column object. */
|
|
147
|
+
type ColumnData<TCol extends AnyColumn> = TCol["_"]["data"];
|
|
148
|
+
|
|
149
|
+
type IsAny<T> = 0 extends 1 & T ? true : false;
|
|
150
|
+
/**
|
|
151
|
+
* Whether a column's value type is statically unknowable — `any`, or the `unknown` that Drizzle's
|
|
152
|
+
* erased column paths (`getColumns`, `PgBuildExtraConfigColumns`) yield. Those must stay PERMISSIVE:
|
|
153
|
+
* narrowing an unknowable type through `Extract` collapses it to `never`, which would refuse every
|
|
154
|
+
* comparison on a column the author cannot re-type.
|
|
155
|
+
*/
|
|
156
|
+
type IsUnknownData<T> = IsAny<T> extends true ? true : unknown extends T ? true : false;
|
|
157
|
+
|
|
158
|
+
/**
|
|
159
|
+
* What may be compared against `TCol` — the column's OWN value type, narrowed to what this wire can
|
|
160
|
+
* carry, plus `null` when the column is nullable.
|
|
161
|
+
*
|
|
162
|
+
* `Extract` is what refuses a column whose values have no scalar form at all: a `jsonb` column typed
|
|
163
|
+
* as an object, or a `timestamp` column typed as `Date`, resolves to `never` here, so the comparison
|
|
164
|
+
* is a compile error rather than the runtime throw it used to be. And because a `pgEnum` column's
|
|
165
|
+
* data type is the literal union of its labels, a mistyped label is caught too — something the SQL
|
|
166
|
+
* text form could never see.
|
|
167
|
+
*/
|
|
168
|
+
export type ColumnValue<TCol extends AnyColumn> =
|
|
169
|
+
IsUnknownData<ColumnData<TCol>> extends true
|
|
170
|
+
? PredicateValueInput
|
|
171
|
+
: Extract<ColumnData<TCol>, PredicateValueInput> | (TCol["_"]["notNull"] extends true ? never : null);
|
|
172
|
+
|
|
173
|
+
/**
|
|
174
|
+
* Narrow a builder input to its wire form, refusing the one conversion that would be silently wrong.
|
|
175
|
+
*
|
|
176
|
+
* A `bigint` past `Number.MAX_SAFE_INTEGER` cannot survive the trip: JSON's only integer carrier here
|
|
177
|
+
* is a JS `number` (an IEEE double), so serializing it would round to a nearby value and the predicate
|
|
178
|
+
* would compare unequal to the row it was written for. Microsecond timestamps sit comfortably inside
|
|
179
|
+
* the safe range, so this throws only for a value that genuinely cannot be expressed.
|
|
180
|
+
*/
|
|
181
|
+
function toWireValue(column: AnyColumn, value: PredicateValueInput): PredicateValue {
|
|
182
|
+
if (typeof value !== "bigint") {
|
|
183
|
+
assertPredicateValue(column, value);
|
|
184
|
+
return value;
|
|
185
|
+
}
|
|
186
|
+
|
|
187
|
+
if (value > BigInt(Number.MAX_SAFE_INTEGER) || value < BigInt(Number.MIN_SAFE_INTEGER)) {
|
|
188
|
+
throw new Error(
|
|
189
|
+
`[pgxsinkit] predicate on "${column.name}": ${value}n is outside the exactly-representable ` +
|
|
190
|
+
`integer range, so serializing it would silently round to a different value. Compare against ` +
|
|
191
|
+
`a value inside the safe-integer range, or split the test.`,
|
|
192
|
+
);
|
|
193
|
+
}
|
|
194
|
+
return Number(value);
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
function leaf<TCol extends AnyColumn>(column: TCol, op: PredicateLeafOp, value: ColumnValue<TCol>): LeafPredicate {
|
|
198
|
+
return { col: column.name, op, value: toWireValue(column, value as PredicateValueInput) };
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
/**
|
|
202
|
+
* The predicate builder — the tier-① authoring surface for a native `where`.
|
|
203
|
+
*
|
|
204
|
+
* Deliberately namespaced rather than exported as bare `eq`/`and`/`or`/`not`, which would collide
|
|
205
|
+
* with `drizzle-orm`'s operators of the same names in exactly the files that use both (a registry
|
|
206
|
+
* authoring RLS policies with Drizzle's `eq` and a shape `where` with this one). The shapes are
|
|
207
|
+
* intentionally the same so the two read alike; only the AST-versus-`SQL` return type differs.
|
|
208
|
+
*
|
|
209
|
+
* ```ts
|
|
210
|
+
* where: (c) => p.and(p.eq(c.published, true), p.isNotNull(c.releasedAt))
|
|
211
|
+
* ```
|
|
212
|
+
*/
|
|
213
|
+
export const p = {
|
|
214
|
+
eq: <TCol extends AnyColumn>(column: TCol, value: ColumnValue<TCol>): LeafPredicate => leaf(column, "eq", value),
|
|
215
|
+
ne: <TCol extends AnyColumn>(column: TCol, value: ColumnValue<TCol>): LeafPredicate => leaf(column, "neq", value),
|
|
216
|
+
lt: <TCol extends AnyColumn>(column: TCol, value: ColumnValue<TCol>): LeafPredicate => leaf(column, "lt", value),
|
|
217
|
+
lte: <TCol extends AnyColumn>(column: TCol, value: ColumnValue<TCol>): LeafPredicate => leaf(column, "lte", value),
|
|
218
|
+
gt: <TCol extends AnyColumn>(column: TCol, value: ColumnValue<TCol>): LeafPredicate => leaf(column, "gt", value),
|
|
219
|
+
gte: <TCol extends AnyColumn>(column: TCol, value: ColumnValue<TCol>): LeafPredicate => leaf(column, "gte", value),
|
|
220
|
+
|
|
221
|
+
/** SQL `LIKE` (case-sensitive; `%` = any sequence, `_` = any single char). Text columns only. */
|
|
222
|
+
like: <TCol extends AnyColumn<{ data: string }>>(column: TCol, pattern: string): LeafPredicate =>
|
|
223
|
+
leaf(column, "like", pattern as ColumnValue<TCol>),
|
|
224
|
+
/** SQL `NOT LIKE`. The engine has no negated-like op; it models it as `Not(Like)`, so this does too. */
|
|
225
|
+
notLike: <TCol extends AnyColumn<{ data: string }>>(column: TCol, pattern: string): NotPredicate => ({
|
|
226
|
+
not: leaf(column, "like", pattern as ColumnValue<TCol>),
|
|
227
|
+
}),
|
|
228
|
+
|
|
229
|
+
isNull: (column: AnyColumn): IsNullPredicate => ({ col: column.name, isNull: true }),
|
|
230
|
+
isNotNull: (column: AnyColumn): IsNullPredicate => ({ col: column.name, isNull: false }),
|
|
231
|
+
|
|
232
|
+
and: (...nodes: Predicate[]): AndPredicate => ({ and: nodes }),
|
|
233
|
+
or: (...nodes: Predicate[]): OrPredicate => ({ or: nodes }),
|
|
234
|
+
not: (node: Predicate): NotPredicate => ({ not: node }),
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* The inner set for an `IN` test, named by the column it projects — the table is read off that
|
|
238
|
+
* column, so there is no table name to get wrong and no way to project a column the named table
|
|
239
|
+
* does not have.
|
|
240
|
+
*/
|
|
241
|
+
subquery: <TCol extends AnyColumn>(
|
|
242
|
+
projected: TCol,
|
|
243
|
+
where?: Predicate,
|
|
244
|
+
): SubqueryRef<Extract<ColumnValue<TCol>, PredicateValue>> => ({
|
|
245
|
+
table: getTableName(getColumnTable(projected)),
|
|
246
|
+
project: projected.name,
|
|
247
|
+
...(where !== undefined ? { where } : {}),
|
|
248
|
+
}),
|
|
249
|
+
|
|
250
|
+
in: <TCol extends AnyColumn>(
|
|
251
|
+
column: TCol,
|
|
252
|
+
ref: SubqueryRef<Extract<ColumnValue<TCol>, PredicateValue>>,
|
|
253
|
+
): InSubqueryPredicate => ({ col: column.name, in: ref }),
|
|
254
|
+
notIn: <TCol extends AnyColumn>(
|
|
255
|
+
column: TCol,
|
|
256
|
+
ref: SubqueryRef<Extract<ColumnValue<TCol>, PredicateValue>>,
|
|
257
|
+
): InSubqueryPredicate => ({
|
|
258
|
+
col: column.name,
|
|
259
|
+
in: ref,
|
|
260
|
+
negated: true,
|
|
261
|
+
}),
|
|
262
|
+
} as const;
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Conjoin, dropping absent branches and collapsing the trivial cases. `undefined` when nothing is
|
|
266
|
+
* left, which is the AST's own spelling of "all rows" (an omitted `where`) — so a caller never has
|
|
267
|
+
* to invent an always-true leaf to stand in for one.
|
|
268
|
+
*/
|
|
269
|
+
export function conjoinPredicates(...nodes: (Predicate | undefined)[]): Predicate | undefined {
|
|
270
|
+
const present = nodes.filter((node): node is Predicate => node !== undefined);
|
|
271
|
+
if (present.length === 0) return undefined;
|
|
272
|
+
if (present.length === 1) return present[0];
|
|
273
|
+
return { and: present };
|
|
274
|
+
}
|
package/src/projection.ts
CHANGED
|
@@ -126,7 +126,7 @@ export function asEphemeral<TEntry extends SyncTableEntry>(entry: TEntry): TEntr
|
|
|
126
126
|
*
|
|
127
127
|
* Throws, naming the divergent tables, on any mismatch. Call it where the client registries are assembled
|
|
128
128
|
* (module-eval or a test) so a drifted projection fails closed instead of silently serving different rows
|
|
129
|
-
* to different clients. The `
|
|
129
|
+
* to different clients. The `customPredicate` body is invisible to the fingerprint — bump
|
|
130
130
|
* {@link RowFilterSpec.revision} so a logic-only divergence is caught.
|
|
131
131
|
*/
|
|
132
132
|
export function assertReadContractPreserved(
|
package/src/registry-diff.ts
CHANGED
|
@@ -109,7 +109,7 @@ function stableStringify(value: unknown): string {
|
|
|
109
109
|
* **The blind spot is real and named.** JSON Schema cannot express a zod refinement or transform, so
|
|
110
110
|
* `z.string().refine(v => v.length >= 3)` and the incompatible `>= 10` version canonicalize identically —
|
|
111
111
|
* the hash sees no change and the review gate never fires. {@link EventStreamEntry.revision} is the fix and
|
|
112
|
-
* it is the AUTHOR's obligation, exactly as `RowFilterSpec.revision` is for a `
|
|
112
|
+
* it is the AUTHOR's obligation, exactly as `RowFilterSpec.revision` is for a `customPredicate` closure: bump it
|
|
113
113
|
* on any acceptance-logic change the JSON Schema cannot carry, and the stream's hash shifts.
|
|
114
114
|
*
|
|
115
115
|
* The hash exists to DETECT change, not to VALIDATE compatibility. ADR-0053 decision 1 binds a stream's
|
|
@@ -261,9 +261,9 @@ function diffProjection(
|
|
|
261
261
|
}
|
|
262
262
|
|
|
263
263
|
/**
|
|
264
|
-
* Shape changes. The
|
|
264
|
+
* Shape changes. The shape target (table/shapeKey/physicalTable) and the row filter both
|
|
265
265
|
* govern which rows stream; a change to either needs a re-sync so the local cache is not left
|
|
266
|
-
* holding rows selected under the old definition (risky). The row filter's `
|
|
266
|
+
* holding rows selected under the old definition (risky). The row filter's `customPredicate` body
|
|
267
267
|
* is invisible to the fingerprint, so a change confined to it is not detectable here.
|
|
268
268
|
*/
|
|
269
269
|
function diffShape(
|
|
@@ -273,7 +273,7 @@ function diffShape(
|
|
|
273
273
|
changes: RegistryChange[],
|
|
274
274
|
): void {
|
|
275
275
|
const target = (shape: CanonicalTable["shape"]): string | null =>
|
|
276
|
-
shape ? `${shape.tableName}|${shape.shapeKey}|${shape.
|
|
276
|
+
shape ? `${shape.tableName}|${shape.shapeKey}|${shape.physicalTable ?? ""}` : null;
|
|
277
277
|
|
|
278
278
|
if (target(previous) !== target(next)) {
|
|
279
279
|
changes.push({ severity: "risky", table, detail: "shape target changed (re-sync required)" });
|
|
@@ -281,6 +281,17 @@ function diffShape(
|
|
|
281
281
|
if (JSON.stringify(previous?.rowFilter ?? null) !== JSON.stringify(next?.rowFilter ?? null)) {
|
|
282
282
|
changes.push({ severity: "risky", table, detail: "row filter changed (re-sync required)" });
|
|
283
283
|
}
|
|
284
|
+
|
|
285
|
+
// A change of scope columns re-partitions the whole family: rows that were in one shape land in
|
|
286
|
+
// another, and a client holding the old partition cannot reconcile itself to the new one.
|
|
287
|
+
if (JSON.stringify(previous?.scope ?? null) !== JSON.stringify(next?.scope ?? null)) {
|
|
288
|
+
changes.push({ severity: "risky", table, detail: "shape scope changed (re-sync required)" });
|
|
289
|
+
}
|
|
290
|
+
// Unlike `customPredicate`, this one IS visible — so a change confined to the static predicate is
|
|
291
|
+
// caught here rather than needing a consumer to remember to bump a revision.
|
|
292
|
+
if ((previous?.where ?? null) !== (next?.where ?? null)) {
|
|
293
|
+
changes.push({ severity: "risky", table, detail: "shape predicate changed (re-sync required)" });
|
|
294
|
+
}
|
|
284
295
|
}
|
|
285
296
|
|
|
286
297
|
/**
|
|
@@ -1,7 +1,8 @@
|
|
|
1
1
|
import type { SQL } from "drizzle-orm";
|
|
2
2
|
import { getTableConfig, PgDialect } from "drizzle-orm/pg-core";
|
|
3
3
|
|
|
4
|
-
import {
|
|
4
|
+
import { DENY_ALL_PREDICATE, type JwtClaims } from "./config";
|
|
5
|
+
import { isOrPredicate, type Predicate } from "./predicate";
|
|
5
6
|
import { getSyncRegistryRowClasses, type SyncTableEntry, type SyncTableRegistry } from "./registry";
|
|
6
7
|
|
|
7
8
|
/**
|
|
@@ -12,7 +13,7 @@ import { getSyncRegistryRowClasses, type SyncTableEntry, type SyncTableRegistry
|
|
|
12
13
|
* It exists because a privacy/visibility invariant spanning many entries drifts in two structural ways that
|
|
13
14
|
* per-entry review cannot catch:
|
|
14
15
|
*
|
|
15
|
-
* 1. **Read/write asymmetry** — the
|
|
16
|
+
* 1. **Read/write asymmetry** — the shape's row filter and the Postgres RLS policies are two engines, so one
|
|
16
17
|
* can be tightened (or loosened) without the other. The assertion audits BOTH surfaces of every bound
|
|
17
18
|
* entry in one predicate, so "readable but unwritable" (or the reverse) is a test failure, not a bug report.
|
|
18
19
|
* 2. **Under-enumeration** — an invariant expressed over a hand-maintained list of tables silently stops
|
|
@@ -20,11 +21,23 @@ import { getSyncRegistryRowClasses, type SyncTableEntry, type SyncTableRegistry
|
|
|
20
21
|
* inverts that: with a declared `rowClasses` vocabulary, a new entry cannot even be registered without
|
|
21
22
|
* being classified, so it joins its class's invariants by construction.
|
|
22
23
|
*
|
|
23
|
-
* It audits
|
|
24
|
-
* is a closure — only its presence and `RowFilterSpec.revision` are hashed). The trade: it sees exactly
|
|
25
|
-
* claims fixtures you give it, and nothing else.
|
|
24
|
+
* It audits RESOLVED output, so it sees things the fingerprint structurally cannot (the `customPredicate`
|
|
25
|
+
* BODY is a closure — only its presence and `RowFilterSpec.revision` are hashed). The trade: it sees exactly
|
|
26
|
+
* the claims fixtures you give it, and nothing else.
|
|
26
27
|
*/
|
|
27
28
|
|
|
29
|
+
/**
|
|
30
|
+
* Whether a predicate admits no row at all — the read half of "this persona sees nothing".
|
|
31
|
+
*
|
|
32
|
+
* Recognises the {@link DENY_ALL_PREDICATE} singleton by reference AND any structurally empty `or`,
|
|
33
|
+
* because both are always-FALSE on the wire and an invariant is asking about the outcome, not about
|
|
34
|
+
* which spelling produced it.
|
|
35
|
+
*/
|
|
36
|
+
export function deniesAllRows(predicate: Predicate | null): boolean {
|
|
37
|
+
if (predicate === DENY_ALL_PREDICATE) return true;
|
|
38
|
+
return predicate != null && isOrPredicate(predicate) && predicate.or.length === 0;
|
|
39
|
+
}
|
|
40
|
+
|
|
28
41
|
/** One rendered write policy on a bound entry's Postgres table, as the invariant predicate sees it. */
|
|
29
42
|
export interface RenderedPolicy {
|
|
30
43
|
/** The policy name as declared (e.g. `widgets_select_owner_or_admin`). */
|
|
@@ -48,16 +61,19 @@ export interface RegistryInvariantCell {
|
|
|
48
61
|
fixtureName: string;
|
|
49
62
|
claims: JwtClaims;
|
|
50
63
|
/**
|
|
51
|
-
* The read
|
|
52
|
-
*
|
|
64
|
+
* The read predicate this entry resolves to FOR THESE CLAIMS — the real read pipeline's output, exactly
|
|
65
|
+
* what the control plane compiles into the shape at subscribe.
|
|
53
66
|
*
|
|
54
67
|
* `null` means **unfiltered**, and covers both ways that arises: the entry declares no shape/`rowFilter`
|
|
55
|
-
* at all, or its `
|
|
56
|
-
* row is visible" answer — e.g. an admin persona). Both are the same statement about what the
|
|
57
|
-
* receives, which is what an invariant reasons about; distinguish them via
|
|
58
|
-
* predicate genuinely needs to.
|
|
68
|
+
* at all, or its `customPredicate` returned `null` for these claims (the documented "bypass filtering,
|
|
69
|
+
* every row is visible" answer — e.g. an admin persona). Both are the same statement about what the
|
|
70
|
+
* client receives, which is what an invariant reasons about; distinguish them via
|
|
71
|
+
* `entry.shape?.rowFilter` if a predicate genuinely needs to.
|
|
72
|
+
*
|
|
73
|
+
* An AST, not SQL text: an invariant matches on structure ({@link deniesAllRows}, the `isXPredicate`
|
|
74
|
+
* guards) rather than on a rendered string that could drift on formatting alone.
|
|
59
75
|
*/
|
|
60
|
-
|
|
76
|
+
readPredicate: Predicate | null;
|
|
61
77
|
/** Every RLS policy attached to the entry's Postgres table, rendered to inline SQL text. */
|
|
62
78
|
renderedPolicies: RenderedPolicy[];
|
|
63
79
|
}
|
|
@@ -111,10 +127,9 @@ function renderPolicies(entry: SyncTableEntry): RenderedPolicy[] {
|
|
|
111
127
|
}));
|
|
112
128
|
}
|
|
113
129
|
|
|
114
|
-
/** The read
|
|
115
|
-
function
|
|
116
|
-
|
|
117
|
-
return rowFilter == null ? null : buildRowFilterShape(rowFilter, claims);
|
|
130
|
+
/** The read predicate for these claims, through the real pipeline the control plane uses. */
|
|
131
|
+
function resolvePredicate(entry: SyncTableEntry, claims: JwtClaims): Predicate | null {
|
|
132
|
+
return entry.shape?.rowFilter?.customPredicate?.(claims) ?? null;
|
|
118
133
|
}
|
|
119
134
|
|
|
120
135
|
function boundEntries(
|
|
@@ -142,8 +157,8 @@ function boundEntries(
|
|
|
142
157
|
* name: "private rows are never visible to an anonymous caller",
|
|
143
158
|
* appliesTo: ["private"],
|
|
144
159
|
* claimsFixtures: { anonymous: {}, member: { sub: "u-1" } },
|
|
145
|
-
* holds: ({ fixtureName,
|
|
146
|
-
* fixtureName !== "anonymous" ||
|
|
160
|
+
* holds: ({ fixtureName, readPredicate }) =>
|
|
161
|
+
* fixtureName !== "anonymous" || deniesAllRows(readPredicate) || "anonymous read is not denied",
|
|
147
162
|
* });
|
|
148
163
|
* ```
|
|
149
164
|
*
|
|
@@ -199,7 +214,7 @@ export function assertRegistryInvariant(registry: SyncTableRegistry, spec: Regis
|
|
|
199
214
|
rowClass: entry.rowClass,
|
|
200
215
|
fixtureName,
|
|
201
216
|
claims,
|
|
202
|
-
|
|
217
|
+
readPredicate: resolvePredicate(entry, claims),
|
|
203
218
|
renderedPolicies,
|
|
204
219
|
});
|
|
205
220
|
if (verdict === true) {
|