@pgxsinkit/server 0.2.5 → 0.2.6
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/cli/generate.d.ts +20 -0
- package/dist/cli/generate.d.ts.map +1 -1
- package/dist/events/consumer.d.ts +282 -0
- package/dist/events/consumer.d.ts.map +1 -0
- package/dist/events/ddl.d.ts +40 -0
- package/dist/events/ddl.d.ts.map +1 -0
- package/dist/events/identity.d.ts +26 -0
- package/dist/events/identity.d.ts.map +1 -0
- package/dist/events/pgmq-queue.d.ts +41 -0
- package/dist/events/pgmq-queue.d.ts.map +1 -0
- package/dist/events/queue.d.ts +119 -0
- package/dist/events/queue.d.ts.map +1 -0
- package/dist/events/route.d.ts +99 -0
- package/dist/events/route.d.ts.map +1 -0
- package/dist/index.d.ts +58 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1022 -54
- package/dist/index.js.map +13 -7
- package/dist/migrations/utilities.d.ts.map +1 -1
- package/dist/mutations/plpgsql-apply.d.ts +30 -9
- package/dist/mutations/plpgsql-apply.d.ts.map +1 -1
- package/dist/mutations/route.d.ts +27 -1
- package/dist/mutations/route.d.ts.map +1 -1
- package/package.json +2 -2
- package/skills/deploying/SKILL.md +195 -7
- package/src/cli/generate.ts +195 -45
- package/src/events/consumer.ts +831 -0
- package/src/events/ddl.ts +79 -0
- package/src/events/identity.ts +86 -0
- package/src/events/pgmq-queue.ts +237 -0
- package/src/events/queue.ts +159 -0
- package/src/events/route.ts +488 -0
- package/src/index.ts +124 -0
- package/src/migrations/utilities.ts +22 -2
- package/src/mutations/plpgsql-apply.ts +357 -38
- package/src/mutations/route.ts +93 -16
|
@@ -1,4 +1,14 @@
|
|
|
1
|
-
import { NOW_MICROSECONDS_SQL_TEXT } from "@pgxsinkit/contracts";
|
|
1
|
+
import { buildRoleGuardedStatement, NOW_MICROSECONDS_SQL_TEXT, quoteIdentifier } from "@pgxsinkit/contracts";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* ADR-0054 decision 5: `pgxsinkit_clock_us()` is hardened in the same pass as the apply function — no
|
|
5
|
+
* pgxsinkit-emitted function relies on default privileges. Unlike the apply function it is a harmless
|
|
6
|
+
* monotonic-clock read whose legitimate callers INCLUDE RLS-context sessions (a column DEFAULT
|
|
7
|
+
* evaluates as whatever role is writing the row), so PUBLIC is revoked and the Supabase trio is
|
|
8
|
+
* granted back explicitly, through the shared role-existence guard so the migration stays portable.
|
|
9
|
+
*/
|
|
10
|
+
const CLOCK_US_SIGNATURE = "public.pgxsinkit_clock_us()";
|
|
11
|
+
const CLOCK_US_GRANTEES = ["anon", "authenticated", "service_role"] as const;
|
|
2
12
|
|
|
3
13
|
/**
|
|
4
14
|
* The canonical microsecond-clock DB function `public.pgxsinkit_clock_us()` — the ONE home for the
|
|
@@ -21,5 +31,15 @@ CREATE OR REPLACE FUNCTION public.pgxsinkit_clock_us()
|
|
|
21
31
|
VOLATILE
|
|
22
32
|
AS $$
|
|
23
33
|
SELECT ${NOW_MICROSECONDS_SQL_TEXT}
|
|
24
|
-
|
|
34
|
+
$$;
|
|
35
|
+
|
|
36
|
+
-- Deny by default, then grant back deliberately (ADR-0054 decision 5). Stated on every install: a
|
|
37
|
+
-- first install on a Supabase-shaped cluster otherwise picks up ALTER DEFAULT PRIVILEGES ... GRANT ALL
|
|
38
|
+
-- ON FUNCTIONS TO anon, authenticated, service_role, so the posture is declared here, never inherited.
|
|
39
|
+
-- The grants are real: a column DEFAULT calling this clock is evaluated as whatever role writes the row.
|
|
40
|
+
REVOKE ALL ON FUNCTION ${CLOCK_US_SIGNATURE} FROM PUBLIC;
|
|
41
|
+
|
|
42
|
+
${CLOCK_US_GRANTEES.map((role) =>
|
|
43
|
+
buildRoleGuardedStatement(role, `GRANT EXECUTE ON FUNCTION ${CLOCK_US_SIGNATURE} TO ${quoteIdentifier(role)}`),
|
|
44
|
+
).join("\n\n")}`;
|
|
25
45
|
}
|
|
@@ -3,13 +3,16 @@ import { getTableConfig, type AnyPgTable, type PgAsyncDatabase, type PgQueryResu
|
|
|
3
3
|
import { getColumns } from "drizzle-orm/utils";
|
|
4
4
|
|
|
5
5
|
import {
|
|
6
|
+
buildRoleGuardedStatement,
|
|
6
7
|
CLOCK_US_CALL_SQL_TEXT,
|
|
7
8
|
escapeSqlLiteral as toSqlLiteral,
|
|
8
9
|
getProjectedColumns,
|
|
9
10
|
hashString,
|
|
11
|
+
isManagedFieldGuarded,
|
|
10
12
|
quoteIdentifier as quoteIdent,
|
|
11
13
|
resolveServerVersionColumnName,
|
|
12
14
|
type BatchMutationRequest,
|
|
15
|
+
type ManagedFieldApplyOn,
|
|
13
16
|
type RegistryRelations,
|
|
14
17
|
type SyncTableEntry,
|
|
15
18
|
type SyncTableRegistry,
|
|
@@ -29,9 +32,95 @@ function toSqlTextOrNull(value: string): string {
|
|
|
29
32
|
return value.length > 0 ? `'${toSqlLiteral(value)}'` : "NULL";
|
|
30
33
|
}
|
|
31
34
|
|
|
35
|
+
/**
|
|
36
|
+
* The array dimensionality Drizzle records for a column (0 = scalar). It is carried SEPARATELY from
|
|
37
|
+
* `getSQLType()`, which returns the ELEMENT type for an array column (`uuid` for a `uuid[]`) — reading
|
|
38
|
+
* only the type string is what silently emitted a scalar cast for an array column and killed every
|
|
39
|
+
* non-null array write with 22P02.
|
|
40
|
+
*/
|
|
41
|
+
function columnDimensions(column: { dimensions?: number }): number {
|
|
42
|
+
return column.dimensions ?? 0;
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
/**
|
|
46
|
+
* The SQL expression that reads one writable column out of a mutation's payload (`x.p`), by column
|
|
47
|
+
* name and Drizzle type. It is embedded in the branch's `(col_name, col_value)` candidate list and
|
|
48
|
+
* substituted verbatim into the INSERT/UPDATE `format()` template at runtime.
|
|
49
|
+
*
|
|
50
|
+
* Scalars keep the long-standing `(x.p->>'col')::type` form. A one-dimensional array column expands
|
|
51
|
+
* the JSON array element-wise and applies the terminal `::<element>[]` cast, which IS the type check
|
|
52
|
+
* (no element-type allowlist: an element the target type cannot accept raises, exactly as a scalar
|
|
53
|
+
* cast does). The three payload shapes match the scalar semantics exactly:
|
|
54
|
+
*
|
|
55
|
+
* - **absent key** — never reaches here (the branch intersects the candidate list with the group's
|
|
56
|
+
* payload signature, so an unsent column is not in the statement at all);
|
|
57
|
+
* - **JSON null** — `jsonb_typeof` is `'null'`, the CASE has no ELSE ⇒ SQL NULL, mirroring
|
|
58
|
+
* `(x.p->>'col')::type` on a JSON null;
|
|
59
|
+
* - **`[]`** — an empty typed array, NOT NULL (an empty list is a value the client meant to write).
|
|
60
|
+
*
|
|
61
|
+
* Element order is pinned with `WITH ORDINALITY … ORDER BY`, so the stored array order is the
|
|
62
|
+
* client's array order by construction rather than by set-returning-function evaluation order.
|
|
63
|
+
* A JSON null ELEMENT becomes a SQL NULL element (`jsonb_array_elements_text` semantics) — except for
|
|
64
|
+
* the JSON element types, see below.
|
|
65
|
+
*
|
|
66
|
+
* The one branch inside the array branch is the ELEMENT type: `json`/`jsonb` elements expand with
|
|
67
|
+
* `jsonb_array_elements` (the JSON-valued expansion), never `jsonb_array_elements_text`. Text expansion
|
|
68
|
+
* of a JSON element STRIPS its JSON quoting, which is silent type corruption for a `jsonb[]`: the element
|
|
69
|
+
* `"123"` (a JSON string) re-parses as the JSON NUMBER `123`, and `"hi"` fails the cast outright with
|
|
70
|
+
* `invalid input syntax for type json`. `jsonb_array_elements` preserves each element VERBATIM, so a JSON
|
|
71
|
+
* null element stays a JSON null value (`jsonb_typeof(e) = 'null'`, not SQL NULL) — the faithful reading
|
|
72
|
+
* for a JSON-typed element, and what round-trips back to the client unchanged. The column-level shapes
|
|
73
|
+
* (absent key / JSON null / `[]`) are identical to the text branch.
|
|
74
|
+
*/
|
|
75
|
+
function buildPayloadValueExpression(
|
|
76
|
+
tableName: string,
|
|
77
|
+
column: { name: string; getSQLType: () => string; dimensions?: number },
|
|
78
|
+
): string {
|
|
79
|
+
const columnLiteral = `'${toSqlLiteral(column.name)}'`;
|
|
80
|
+
const dimensions = columnDimensions(column);
|
|
81
|
+
const sqlType = column.getSQLType();
|
|
82
|
+
|
|
83
|
+
if (dimensions === 0) {
|
|
84
|
+
return `(x.p->>${columnLiteral})::${sqlType}`;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
if (dimensions > 1) {
|
|
88
|
+
// Loud at GENERATE time, never a silently wrong cast: a multi-dimensional array cannot be
|
|
89
|
+
// reconstructed from a flat element expansion, and Postgres additionally requires every
|
|
90
|
+
// sub-array to be the same length — a validity rule this renderer cannot express.
|
|
91
|
+
throw new Error(
|
|
92
|
+
`plpgsql apply generator: column ${tableName}.${column.name} is a ${dimensions}-dimensional array; ` +
|
|
93
|
+
`multi-dimensional arrays are not supported by the apply function (use a single-dimension array, ` +
|
|
94
|
+
`or a jsonb column)`,
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
// A `json`/`jsonb` ELEMENT type must keep its JSON value (quoting included); every other element type
|
|
99
|
+
// is reconstructed from the element's TEXT rendering, which is what the terminal `::<type>[]` cast reads.
|
|
100
|
+
const elementExpansion = isJsonElementType(sqlType) ? "jsonb_array_elements" : "jsonb_array_elements_text";
|
|
101
|
+
|
|
102
|
+
return (
|
|
103
|
+
`CASE WHEN jsonb_typeof(x.p->${columnLiteral}) = 'array' THEN ` +
|
|
104
|
+
`ARRAY(SELECT e FROM ${elementExpansion}(x.p->${columnLiteral}) WITH ORDINALITY AS a(e, ord) ORDER BY ord)` +
|
|
105
|
+
`::${sqlType}[] END`
|
|
106
|
+
);
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
/** `json` / `jsonb` — the element types whose VALUE (not text rendering) must survive the expansion. */
|
|
110
|
+
function isJsonElementType(sqlType: string): boolean {
|
|
111
|
+
const normalized = sqlType.trim().toLowerCase();
|
|
112
|
+
return normalized === "json" || normalized === "jsonb";
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** One `(column name, payload value expression)` row of a branch's runtime candidate list. */
|
|
116
|
+
function toColumnCandidateRow(tableName: string, column: { name: string; getSQLType: () => string }): string {
|
|
117
|
+
return `('${toSqlLiteral(column.name)}', '${toSqlLiteral(buildPayloadValueExpression(tableName, column))}')`;
|
|
118
|
+
}
|
|
119
|
+
|
|
32
120
|
interface ResolvedManagedField {
|
|
33
121
|
propertyKey: string;
|
|
34
122
|
columnName: string;
|
|
123
|
+
applyOn: readonly ManagedFieldApplyOn[];
|
|
35
124
|
strategy: "nowMicroseconds" | "authClaim";
|
|
36
125
|
claimPath?: string[];
|
|
37
126
|
cast?: string;
|
|
@@ -59,28 +148,40 @@ function buildManagedFieldExpression(field: ResolvedManagedField): string {
|
|
|
59
148
|
return CLOCK_US_CALL_SQL_TEXT;
|
|
60
149
|
}
|
|
61
150
|
|
|
62
|
-
|
|
151
|
+
// Every managed field of the entry, resolved to its SQL column name and type. The two consumers slice it
|
|
152
|
+
// differently and the distinction is load-bearing: STAMPING is operation-scoped (`applyOn.includes(op)`)
|
|
153
|
+
// and decides what the applier writes, while GUARDING (contracts' `isManagedFieldGuarded`) decides which
|
|
154
|
+
// columns a client payload may never move, and so which are excluded from the candidate lists below.
|
|
155
|
+
function resolveManagedFields(entry: SyncTableEntry): ResolvedManagedField[] {
|
|
156
|
+
const tableName = getTableName(entry.table as AnyPgTable);
|
|
63
157
|
const columns = getColumns(entry.table as AnyPgTable);
|
|
64
158
|
const columnNameMap = new Map(Object.entries(columns).map(([propertyKey, column]) => [propertyKey, column.name]));
|
|
65
159
|
|
|
66
160
|
return (entry.governance?.managedFields ?? []).flatMap((field) => {
|
|
67
|
-
if (!field.applyOn.includes(operation)) {
|
|
68
|
-
return [];
|
|
69
|
-
}
|
|
70
|
-
|
|
71
161
|
const columnName = columnNameMap.get(field.column);
|
|
72
162
|
if (!columnName) {
|
|
73
163
|
return [];
|
|
74
164
|
}
|
|
75
165
|
|
|
76
166
|
const column =
|
|
77
|
-
(columns as Record<string, { getSQLType: () => string } | undefined>)[field.column] ??
|
|
167
|
+
(columns as Record<string, { getSQLType: () => string; dimensions?: number } | undefined>)[field.column] ??
|
|
78
168
|
Object.values(columns).find((candidate) => candidate.name === field.column);
|
|
79
169
|
|
|
170
|
+
if (column && columnDimensions(column) > 0) {
|
|
171
|
+
// Both stamping strategies produce a SCALAR (a microsecond clock read, or one claim at a JSON
|
|
172
|
+
// path), so an array-typed managed column could only ever be assigned a scalar — a type error at
|
|
173
|
+
// every write. Refuse at generate time instead.
|
|
174
|
+
throw new Error(
|
|
175
|
+
`plpgsql apply generator: managed field ${tableName}.${columnName} is an array column; ` +
|
|
176
|
+
`managed fields stamp a single scalar value and are not supported on array columns`,
|
|
177
|
+
);
|
|
178
|
+
}
|
|
179
|
+
|
|
80
180
|
return [
|
|
81
181
|
{
|
|
82
182
|
propertyKey: field.column,
|
|
83
183
|
columnName,
|
|
184
|
+
applyOn: field.applyOn,
|
|
84
185
|
strategy: field.strategy,
|
|
85
186
|
...(field.claimPath ? { claimPath: field.claimPath } : {}),
|
|
86
187
|
...(field.cast ? { cast: field.cast } : {}),
|
|
@@ -110,25 +211,50 @@ function buildTableBranch(entry: SyncTableEntry): string {
|
|
|
110
211
|
`the entry's primaryKey spec has drifted from its Drizzle table`,
|
|
111
212
|
);
|
|
112
213
|
}
|
|
214
|
+
if (columnDimensions(columnObject) > 0) {
|
|
215
|
+
// The canonical identity is carried as typed recordset columns and as `(x.k->>'col')::type`
|
|
216
|
+
// join predicates — both scalar forms. An array PK would need array equality semantics the
|
|
217
|
+
// entity-key wire shape (a JSON object of scalar strings) cannot express, so refuse it here
|
|
218
|
+
// rather than emit a cast that would raise 22P02 on the first update/delete.
|
|
219
|
+
throw new Error(
|
|
220
|
+
`plpgsql apply generator: primary key column ${tableName}.${columnName} is an array column; ` +
|
|
221
|
+
`array columns are not supported as primary keys by the apply function`,
|
|
222
|
+
);
|
|
223
|
+
}
|
|
113
224
|
return { name: columnName, type: columnObject.getSQLType() };
|
|
114
225
|
});
|
|
115
226
|
const primaryKeyColumnNames = new Set(primaryKeyColumns.map((pk) => pk.name));
|
|
116
227
|
|
|
117
|
-
const
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
const
|
|
228
|
+
const managedFields = resolveManagedFields(entry);
|
|
229
|
+
// STAMPING sets — operation-scoped: what the applier itself writes (the INSERT column/value fragments
|
|
230
|
+
// and the UPDATE managed-assignment fragment below).
|
|
231
|
+
const createManagedFields = managedFields.filter((field) => field.applyOn.includes("create"));
|
|
232
|
+
const updateManagedFields = managedFields.filter((field) => field.applyOn.includes("update"));
|
|
233
|
+
// EXCLUSION sets — the guard rule, from contracts' single definition: a column that is server-owned for
|
|
234
|
+
// the operation is not a candidate a client payload key can move. On create that is the create-managed
|
|
235
|
+
// columns (the applier stamps them itself); on update it is EVERY managed column, so a create-only
|
|
236
|
+
// field (`applyOn: ["create"]`, e.g. an `authClaim` owner) is inert thereafter, and an update-managed
|
|
237
|
+
// one is assigned by the static managed-assignment fragment instead.
|
|
238
|
+
const createGuardedColumnNames = new Set(
|
|
239
|
+
managedFields.filter((field) => isManagedFieldGuarded(field, "create")).map((field) => field.columnName),
|
|
240
|
+
);
|
|
241
|
+
const updateGuardedColumnNames = new Set(
|
|
242
|
+
managedFields.filter((field) => isManagedFieldGuarded(field, "update")).map((field) => field.columnName),
|
|
243
|
+
);
|
|
121
244
|
|
|
245
|
+
// Each candidate row carries the column's NAME and its fully-rendered payload value EXPRESSION.
|
|
246
|
+
// The expression is precomputed here (rather than `format()`-ed from a type at runtime) because it
|
|
247
|
+
// is no longer uniform: an array column needs an element-wise expansion, not a `->>` cast.
|
|
122
248
|
const allColumnPairs = projectedColumns
|
|
123
249
|
.map(({ column }) => column)
|
|
124
|
-
.filter((column) => !
|
|
125
|
-
.map((column) =>
|
|
250
|
+
.filter((column) => !createGuardedColumnNames.has(column.name))
|
|
251
|
+
.map((column) => toColumnCandidateRow(tableName, column))
|
|
126
252
|
.join(",\n ");
|
|
127
253
|
|
|
128
254
|
const nonPrimaryKeyColumnPairs = projectedColumns
|
|
129
255
|
.map(({ column }) => column)
|
|
130
|
-
.filter((column) => !primaryKeyColumnNames.has(column.name) && !
|
|
131
|
-
.map((column) =>
|
|
256
|
+
.filter((column) => !primaryKeyColumnNames.has(column.name) && !updateGuardedColumnNames.has(column.name))
|
|
257
|
+
.map((column) => toColumnCandidateRow(tableName, column))
|
|
132
258
|
.join(",\n ");
|
|
133
259
|
|
|
134
260
|
const createManagedColumnsSql = createManagedFields.map((field) => quoteIdent(field.columnName)).join(", ");
|
|
@@ -182,20 +308,20 @@ function buildTableBranch(entry: SyncTableEntry): string {
|
|
|
182
308
|
const createColumnSelect = allColumnPairs.length
|
|
183
309
|
? `SELECT
|
|
184
310
|
string_agg(quote_ident(col_name), ', ' ORDER BY col_name),
|
|
185
|
-
string_agg(
|
|
311
|
+
string_agg(col_value, ', ' ORDER BY col_name)
|
|
186
312
|
INTO v_cols, v_vals
|
|
187
313
|
FROM (VALUES
|
|
188
314
|
${allColumnPairs}
|
|
189
|
-
) AS col_types(col_name,
|
|
315
|
+
) AS col_types(col_name, col_value)
|
|
190
316
|
WHERE col_name = ANY(string_to_array(v_sig, ','));`
|
|
191
317
|
: `v_cols := NULL; v_vals := NULL;`;
|
|
192
318
|
|
|
193
319
|
const updateSetSelect = nonPrimaryKeyColumnPairs.length
|
|
194
|
-
? `SELECT string_agg(format('%I =
|
|
320
|
+
? `SELECT string_agg(format('%I = %s', col_name, col_value), ', ' ORDER BY col_name)
|
|
195
321
|
INTO v_set
|
|
196
322
|
FROM (VALUES
|
|
197
323
|
${nonPrimaryKeyColumnPairs}
|
|
198
|
-
) AS col_types(col_name,
|
|
324
|
+
) AS col_types(col_name, col_value)
|
|
199
325
|
WHERE col_name = ANY(string_to_array(v_sig, ','));`
|
|
200
326
|
: `v_set := NULL;`;
|
|
201
327
|
|
|
@@ -316,12 +442,198 @@ const APPLY_FUNCTION_ARG_TYPES = "jsonb, text, boolean, boolean, jsonb, text";
|
|
|
316
442
|
// an identity mismatch and the apply function refuses the write.
|
|
317
443
|
const APPLY_FINGERPRINT_PREFIX = "pgxsinkit:fp1:";
|
|
318
444
|
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
445
|
+
/**
|
|
446
|
+
* The roles Supabase's `ALTER DEFAULT PRIVILEGES … GRANT ALL ON FUNCTIONS` re-grants at every CREATE
|
|
447
|
+
* (ADR-0054). The artifact's `DROP FUNCTION` makes each install a fresh creation, so these grants come
|
|
448
|
+
* BACK on every regenerate — hence an unconditional revoke per install, not a one-off hardening.
|
|
449
|
+
*/
|
|
450
|
+
const SUPABASE_DEFAULT_PRIVILEGE_ROLES = ["anon", "authenticated", "service_role"] as const;
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* How the generated apply function is rendered. Both fields are part of the artifact's IDENTITY: they
|
|
454
|
+
* change the fingerprinted body, so a change to either forces the regenerate-and-commit flow, and the
|
|
455
|
+
* SERVER must be configured with the same values (it recomputes the expected fingerprint at runtime).
|
|
456
|
+
*/
|
|
457
|
+
export interface ApplyFunctionRenderOptions {
|
|
458
|
+
/** Schema to qualify the function with. Default: unqualified (resolved through `search_path`). */
|
|
459
|
+
functionSchema?: string;
|
|
460
|
+
/**
|
|
461
|
+
* Roles that receive `GRANT EXECUTE` on the apply function (ADR-0054 decision 2). Default `[]` —
|
|
462
|
+
* **owner-only**, which is right whenever the server connects as the function's owner or a
|
|
463
|
+
* superuser. Name ONLY server roles: the function trusts the `p_user_claims` it is handed, so a
|
|
464
|
+
* granted role can pass any claims it likes. The grant list IS the write path's trust boundary.
|
|
465
|
+
*/
|
|
466
|
+
grantExecuteTo?: readonly string[];
|
|
467
|
+
}
|
|
468
|
+
|
|
469
|
+
/** An unquoted-safe SQL role name: what `GRANT … TO <role>` may name without surprises. */
|
|
470
|
+
const GRANT_ROLE_NAME_PATTERN = /^[A-Za-z_][A-Za-z0-9_$]*$/;
|
|
471
|
+
|
|
472
|
+
/**
|
|
473
|
+
* Validate a `functionSchema` — the ONE definition, shared by the renderer (which qualifies the emitted
|
|
474
|
+
* DDL with it) and by the running server (`applyFunctionSchema`, which must qualify its invocation the
|
|
475
|
+
* same way and recompute the same fingerprint). A schema name reaches SQL as a quoted identifier, so the
|
|
476
|
+
* rule is the same plain-identifier rule role names get: an unusable name is refused loudly at generate
|
|
477
|
+
* / server-construction time rather than producing an artifact nobody can call.
|
|
478
|
+
*
|
|
479
|
+
* Returns `undefined` for an absent schema — the default, an unqualified name resolved through
|
|
480
|
+
* `search_path`.
|
|
481
|
+
*/
|
|
482
|
+
export function resolveApplyFunctionSchema(functionSchema: string | undefined): string | undefined {
|
|
483
|
+
if (functionSchema === undefined) {
|
|
484
|
+
return undefined;
|
|
485
|
+
}
|
|
486
|
+
if (typeof functionSchema !== "string" || functionSchema.trim().length === 0) {
|
|
487
|
+
throw new Error("plpgsql apply generator: functionSchema is empty");
|
|
488
|
+
}
|
|
489
|
+
if (!GRANT_ROLE_NAME_PATTERN.test(functionSchema)) {
|
|
490
|
+
throw new Error(
|
|
491
|
+
`plpgsql apply generator: functionSchema '${functionSchema}' is not a plain SQL identifier ` +
|
|
492
|
+
`(letters, digits, '_' and '$', not starting with a digit)`,
|
|
493
|
+
);
|
|
494
|
+
}
|
|
495
|
+
if (functionSchema.length > 63) {
|
|
496
|
+
throw new Error(
|
|
497
|
+
`plpgsql apply generator: functionSchema '${functionSchema}' exceeds PostgreSQL's 63-byte name limit`,
|
|
498
|
+
);
|
|
499
|
+
}
|
|
500
|
+
return functionSchema;
|
|
501
|
+
}
|
|
502
|
+
|
|
503
|
+
/**
|
|
504
|
+
* Validate `grantExecuteTo` at GENERATE time, fail-closed. A role name is emitted into DDL (as a
|
|
505
|
+
* quoted identifier and as a `pg_roles` literal), and the whole point of ADR-0054 is that who may
|
|
506
|
+
* execute is named explicitly — so an unusable name is refused loudly here rather than silently
|
|
507
|
+
* producing an artifact whose ACL does not say what its author meant.
|
|
508
|
+
*/
|
|
509
|
+
function resolveGrantExecuteRoles(grantExecuteTo: readonly string[] | undefined): readonly string[] {
|
|
510
|
+
const roles = grantExecuteTo ?? [];
|
|
511
|
+
const seen = new Set<string>();
|
|
512
|
+
|
|
513
|
+
for (const role of roles) {
|
|
514
|
+
if (typeof role !== "string" || role.trim().length === 0) {
|
|
515
|
+
throw new Error("plpgsql apply generator: grantExecuteTo contains an empty role name");
|
|
516
|
+
}
|
|
517
|
+
if (!GRANT_ROLE_NAME_PATTERN.test(role)) {
|
|
518
|
+
throw new Error(
|
|
519
|
+
`plpgsql apply generator: grantExecuteTo role '${role}' is not a plain SQL identifier ` +
|
|
520
|
+
`(letters, digits, '_' and '$', not starting with a digit)`,
|
|
521
|
+
);
|
|
522
|
+
}
|
|
523
|
+
if (role.length > 63) {
|
|
524
|
+
throw new Error(`plpgsql apply generator: grantExecuteTo role '${role}' exceeds PostgreSQL's 63-byte name limit`);
|
|
525
|
+
}
|
|
526
|
+
if (seen.has(role)) {
|
|
527
|
+
throw new Error(`plpgsql apply generator: grantExecuteTo lists role '${role}' more than once`);
|
|
528
|
+
}
|
|
529
|
+
seen.add(role);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
// Canonical (byte) order, so an equivalent SET of roles is one artifact whatever order the caller
|
|
533
|
+
// listed them in. The list is emitted into the FINGERPRINTED body, so without this
|
|
534
|
+
// `["a","b"]` and `["b","a"]` — the same authorization posture — would be two different artifacts,
|
|
535
|
+
// and a server configured with one ordering would fail `PXS01` against the other's install. Role names
|
|
536
|
+
// are validated plain identifiers (ASCII only), so JS's default code-unit sort IS byte order.
|
|
537
|
+
return [...roles].sort();
|
|
538
|
+
}
|
|
539
|
+
|
|
540
|
+
/**
|
|
541
|
+
* The GUARANTEE behind the readable revokes: converge the installed function's ACL to
|
|
542
|
+
* `owner + grantExecuteTo`, whatever it actually contains.
|
|
543
|
+
*
|
|
544
|
+
* The named revokes above close the two exposures we can NAME (Postgres's PUBLIC default, Supabase's
|
|
545
|
+
* default-privilege trio). They cannot close a grant to a role we cannot name — and a consumer's own
|
|
546
|
+
* `ALTER DEFAULT PRIVILEGES … GRANT ALL ON FUNCTIONS TO <their role>` re-grants at every `CREATE`
|
|
547
|
+
* exactly like Supabase's does, so a deployment-specific grantee would survive every install and keep a
|
|
548
|
+
* forged-claims caller on the write path indefinitely. So the artifact ENUMERATES the installed
|
|
549
|
+
* function's real grantees (`aclexplode(pg_proc.proacl)`) and revokes EXECUTE from each one that is
|
|
550
|
+
* neither the function's OWNER (`proowner` — revoking the owner is meaningless, they can re-grant at
|
|
551
|
+
* will) nor in the explicit allowlist.
|
|
552
|
+
*
|
|
553
|
+
* Two details make it total:
|
|
554
|
+
* - **A default (NULL) `proacl` explodes to nothing.** That is why the unconditional
|
|
555
|
+
* `REVOKE ALL … FROM PUBLIC` is emitted FIRST: revoking materializes the previously-implicit ACL
|
|
556
|
+
* (`NULL` → `{owner=X/owner}`), so by the time this block runs the catalog states the truth. Pinned by
|
|
557
|
+
* the PGlite unit lane, and by the integration lane against a real cluster.
|
|
558
|
+
* - **Grantee `0` is PUBLIC**, which has no role name (`pg_get_userbyid(0)` returns a placeholder
|
|
559
|
+
* string), so it is revoked by the `FROM PUBLIC` spelling rather than by name.
|
|
560
|
+
*
|
|
561
|
+
* The grantee list is snapshotted into an array BEFORE any revoke runs, so the loop never revokes while
|
|
562
|
+
* scanning the catalog it is mutating. Identifiers go through `format('%I', …)` (= `quote_ident`), and
|
|
563
|
+
* the function is named by `oid::regprocedure::text`, which schema-qualifies and quotes as required.
|
|
564
|
+
*/
|
|
565
|
+
function buildApplyFunctionAclConvergerSql(signature: string, grantExecuteTo: readonly string[]): string {
|
|
566
|
+
const keepList =
|
|
567
|
+
grantExecuteTo.length > 0
|
|
568
|
+
? `ARRAY[${grantExecuteTo.map((role) => `'${toSqlLiteral(role)}'`).join(", ")}]::text[]`
|
|
569
|
+
: `ARRAY[]::text[]`;
|
|
570
|
+
|
|
571
|
+
return `DO $$
|
|
572
|
+
DECLARE
|
|
573
|
+
_fn oid := '${toSqlLiteral(signature)}'::regprocedure;
|
|
574
|
+
_owner oid;
|
|
575
|
+
_keep text[] := ${keepList};
|
|
576
|
+
_grantees oid[];
|
|
577
|
+
_grantee oid;
|
|
578
|
+
_grantee_name text;
|
|
579
|
+
BEGIN
|
|
580
|
+
SELECT p.proowner INTO _owner FROM pg_proc AS p WHERE p.oid = _fn;
|
|
581
|
+
SELECT array_agg(DISTINCT acl.grantee) INTO _grantees
|
|
582
|
+
FROM pg_proc AS p, aclexplode(p.proacl) AS acl
|
|
583
|
+
WHERE p.oid = _fn;
|
|
584
|
+
|
|
585
|
+
FOREACH _grantee IN ARRAY COALESCE(_grantees, ARRAY[]::oid[]) LOOP
|
|
586
|
+
IF _grantee = _owner THEN
|
|
587
|
+
CONTINUE;
|
|
588
|
+
END IF;
|
|
589
|
+
IF _grantee = 0 THEN
|
|
590
|
+
EXECUTE format('REVOKE EXECUTE ON FUNCTION %s FROM PUBLIC', _fn::regprocedure::text);
|
|
591
|
+
CONTINUE;
|
|
592
|
+
END IF;
|
|
593
|
+
_grantee_name := pg_get_userbyid(_grantee);
|
|
594
|
+
IF _grantee_name = ANY (_keep) THEN
|
|
595
|
+
CONTINUE;
|
|
596
|
+
END IF;
|
|
597
|
+
EXECUTE format('REVOKE EXECUTE ON FUNCTION %s FROM %I', _fn::regprocedure::text, _grantee_name);
|
|
598
|
+
END LOOP;
|
|
599
|
+
END;
|
|
600
|
+
$$;`;
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
/**
|
|
604
|
+
* ADR-0054: the apply function is DENY-BY-DEFAULT, and converges on every install.
|
|
605
|
+
*
|
|
606
|
+
* The function trusts `p_user_claims` — it copies them into `request.jwt.claims` and switches `role`
|
|
607
|
+
* before running RLS-governed DML — which is correct for the consumer server (it passes claims it
|
|
608
|
+
* VERIFIED) and catastrophic for anyone else, who would simply choose their own. Postgres grants
|
|
609
|
+
* EXECUTE to PUBLIC on every new function and Supabase-shaped clusters additionally re-grant the
|
|
610
|
+
* `anon`/`authenticated`/`service_role` trio via default privileges; because the artifact begins with
|
|
611
|
+
* `DROP FUNCTION`, EVERY install recreates that exposure. So the revokes are emitted unconditionally
|
|
612
|
+
* (convergence must not depend on install history), the Supabase-trio ones through the shared
|
|
613
|
+
* role-existence guard so the artifact stays portable to PGlite and plain-Postgres lanes.
|
|
614
|
+
*
|
|
615
|
+
* Those named revokes are the READABLE fast path — a reviewer sees the two known exposures closed in
|
|
616
|
+
* plain SQL. The guarantee is {@link buildApplyFunctionAclConvergerSql}, which then revokes EVERY
|
|
617
|
+
* remaining grantee outside `owner + grantExecuteTo`, including ones this renderer cannot name.
|
|
618
|
+
*
|
|
619
|
+
* Grants come last, so naming a revoked role in `grantExecuteTo` is a deliberate, explicit grant.
|
|
620
|
+
*/
|
|
621
|
+
function buildApplyFunctionAclSql(functionName: string, grantExecuteTo: readonly string[]): string {
|
|
622
|
+
const signature = `${functionName}(${APPLY_FUNCTION_ARG_TYPES})`;
|
|
623
|
+
|
|
624
|
+
return [
|
|
625
|
+
`REVOKE ALL ON FUNCTION ${signature} FROM PUBLIC;`,
|
|
626
|
+
...SUPABASE_DEFAULT_PRIVILEGE_ROLES.map((role) =>
|
|
627
|
+
buildRoleGuardedStatement(role, `REVOKE ALL ON FUNCTION ${signature} FROM ${quoteIdent(role)}`),
|
|
628
|
+
),
|
|
629
|
+
buildApplyFunctionAclConvergerSql(signature, grantExecuteTo),
|
|
630
|
+
...grantExecuteTo.map((role) =>
|
|
631
|
+
buildRoleGuardedStatement(role, `GRANT EXECUTE ON FUNCTION ${signature} TO ${quoteIdent(role)}`),
|
|
632
|
+
),
|
|
633
|
+
].join("\n\n");
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
function buildApplyFunctionBody(registry: SyncTableRegistry, options: ApplyFunctionRenderOptions = {}): string {
|
|
325
637
|
const tableBranches = Object.values(registry)
|
|
326
638
|
// A read projection (ADR-0027) owns no writable table — its `table` IS the owner's, so the owner's
|
|
327
639
|
// branch already handles that physical table. Emitting a branch for the projection too would
|
|
@@ -330,7 +642,11 @@ function buildApplyFunctionBody(
|
|
|
330
642
|
.filter((entry) => !(entry as SyncTableEntry).readProjection)
|
|
331
643
|
.map((entry) => buildTableBranch(entry as SyncTableEntry))
|
|
332
644
|
.join("\n");
|
|
333
|
-
const functionName = qualifyIdent(options.functionSchema, APPLY_FUNCTION_NAME);
|
|
645
|
+
const functionName = qualifyIdent(resolveApplyFunctionSchema(options.functionSchema), APPLY_FUNCTION_NAME);
|
|
646
|
+
// ADR-0054 decision 3: the ACL is rendered INSIDE the fingerprinted body (unlike the COMMENT, which
|
|
647
|
+
// is appended around it) — an install without the revokes IS a different fingerprint and is refused
|
|
648
|
+
// at call time, so a stale PUBLIC-executable install cannot run while `--check` stays green.
|
|
649
|
+
const aclSql = buildApplyFunctionAclSql(functionName, resolveGrantExecuteRoles(options.grantExecuteTo));
|
|
334
650
|
|
|
335
651
|
return `
|
|
336
652
|
-- Install idempotently by dropping the current signature first. PostgreSQL cannot change a function's
|
|
@@ -519,6 +835,13 @@ BEGIN
|
|
|
519
835
|
FROM jsonb_array_elements(v_conflicts) AS c;
|
|
520
836
|
END;
|
|
521
837
|
$$;
|
|
838
|
+
|
|
839
|
+
-- ADR-0054: deny by default. Emitted on EVERY install because the DROP above resets the ACL to
|
|
840
|
+
-- Postgres's PUBLIC default (plus Supabase's default-privilege grants), so convergence cannot depend
|
|
841
|
+
-- on install history. EXECUTE is owner-only unless the artifact was generated with an explicit
|
|
842
|
+
-- --grant-execute-to; the grant list is the write path's ENTIRE trust boundary, because this function
|
|
843
|
+
-- trusts the claims it is handed.
|
|
844
|
+
${aclSql}
|
|
522
845
|
`.trim();
|
|
523
846
|
}
|
|
524
847
|
|
|
@@ -531,21 +854,17 @@ $$;
|
|
|
531
854
|
*/
|
|
532
855
|
export function expectedApplyFingerprint(
|
|
533
856
|
registry: SyncTableRegistry,
|
|
534
|
-
options: {
|
|
535
|
-
functionSchema?: string;
|
|
536
|
-
} = {},
|
|
857
|
+
options: ApplyFunctionRenderOptions = {},
|
|
537
858
|
): string {
|
|
538
859
|
return APPLY_FINGERPRINT_PREFIX + hashString(buildApplyFunctionBody(registry, options));
|
|
539
860
|
}
|
|
540
861
|
|
|
541
862
|
export function buildPlpgsqlBatchFunctionDdl(
|
|
542
863
|
registry: SyncTableRegistry,
|
|
543
|
-
options: {
|
|
544
|
-
functionSchema?: string;
|
|
545
|
-
} = {},
|
|
864
|
+
options: ApplyFunctionRenderOptions = {},
|
|
546
865
|
): string {
|
|
547
866
|
const body = buildApplyFunctionBody(registry, options);
|
|
548
|
-
const functionName = qualifyIdent(options.functionSchema, APPLY_FUNCTION_NAME);
|
|
867
|
+
const functionName = qualifyIdent(resolveApplyFunctionSchema(options.functionSchema), APPLY_FUNCTION_NAME);
|
|
549
868
|
const fingerprint = APPLY_FINGERPRINT_PREFIX + hashString(body);
|
|
550
869
|
|
|
551
870
|
// ADR-0018: stamp the function with the fingerprint of this exact DDL body. Stored as a COMMENT
|
|
@@ -558,9 +877,7 @@ export function buildPlpgsqlBatchFunctionDdl(
|
|
|
558
877
|
export async function installPlpgsqlBatchFunction<TRegistry extends SyncTableRegistry>(
|
|
559
878
|
db: PgAsyncDatabase<PgQueryResultHKT, RegistryRelations<TRegistry>>,
|
|
560
879
|
registry: TRegistry,
|
|
561
|
-
options: {
|
|
562
|
-
functionSchema?: string;
|
|
563
|
-
} = {},
|
|
880
|
+
options: ApplyFunctionRenderOptions = {},
|
|
564
881
|
): Promise<void> {
|
|
565
882
|
const ddl = buildPlpgsqlBatchFunctionDdl(registry, options);
|
|
566
883
|
await db.execute(sql.raw(ddl));
|
|
@@ -626,9 +943,11 @@ export async function executePlpgsqlBatch(
|
|
|
626
943
|
): Promise<MutationConflict[]> {
|
|
627
944
|
const normalizedClaims = userClaims ?? {};
|
|
628
945
|
// Typed identifier interpolation (never `sql.raw` of a hand-quoted name); the OUT-column aliases
|
|
629
|
-
// are the generated function's fixed names.
|
|
630
|
-
|
|
631
|
-
|
|
946
|
+
// are the generated function's fixed names. The schema goes through the SAME validator the renderer
|
|
947
|
+
// uses, so a server configured with `applyFunctionSchema` names exactly what the artifact installed.
|
|
948
|
+
const functionSchema = resolveApplyFunctionSchema(options.functionSchema);
|
|
949
|
+
const functionRef = functionSchema
|
|
950
|
+
? sql`${sql.identifier(functionSchema)}.${sql.identifier("pgxsinkit_apply_mutations")}`
|
|
632
951
|
: sql`${sql.identifier("pgxsinkit_apply_mutations")}`;
|
|
633
952
|
|
|
634
953
|
// The applier RETURNS the stale-write conflicts (ADR-0015). Read them from the function's result
|