@rebasepro/server-postgres 0.9.1-canary.fd3754b → 0.10.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.
Files changed (67) hide show
  1. package/README.md +21 -0
  2. package/dist/PostgresBackendDriver.d.ts +43 -2
  3. package/dist/PostgresBootstrapper.d.ts +17 -1
  4. package/dist/auth/services.d.ts +68 -52
  5. package/dist/collections/buildRegistry.d.ts +27 -0
  6. package/dist/connection.d.ts +21 -0
  7. package/dist/data-transformer.d.ts +9 -2
  8. package/dist/index.es.js +2711 -2772
  9. package/dist/index.es.js.map +1 -1
  10. package/dist/schema/auth-bootstrap-sql.d.ts +1 -1
  11. package/dist/schema/auth-schema.d.ts +24 -24
  12. package/dist/schema/doctor.d.ts +1 -1
  13. package/dist/schema/introspect-db-logic.d.ts +0 -5
  14. package/dist/schema/introspect-db-naming.d.ts +10 -0
  15. package/dist/security/policy-drift.d.ts +70 -5
  16. package/dist/security/rls-enforcement.d.ts +29 -4
  17. package/dist/services/FetchService.d.ts +4 -24
  18. package/dist/services/PersistService.d.ts +27 -1
  19. package/dist/services/RelationService.d.ts +34 -1
  20. package/dist/services/channel-history.d.ts +118 -0
  21. package/dist/services/collection-helpers.d.ts +79 -14
  22. package/dist/services/dataService.d.ts +3 -1
  23. package/dist/services/index.d.ts +1 -1
  24. package/dist/services/realtimeService.d.ts +76 -2
  25. package/dist/services/row-pipeline.d.ts +63 -0
  26. package/package.json +15 -40
  27. package/src/PostgresBackendDriver.ts +183 -18
  28. package/src/PostgresBootstrapper.ts +86 -27
  29. package/src/auth/ensure-tables.ts +170 -28
  30. package/src/auth/services.ts +181 -150
  31. package/src/cli-helpers.ts +2 -20
  32. package/src/cli.ts +60 -0
  33. package/src/collections/buildRegistry.ts +59 -0
  34. package/src/connection.ts +61 -1
  35. package/src/data-transformer.ts +11 -9
  36. package/src/databasePoolManager.ts +2 -0
  37. package/src/schema/auth-bootstrap-sql.ts +7 -1
  38. package/src/schema/auth-schema.ts +13 -13
  39. package/src/schema/doctor-cli.ts +5 -1
  40. package/src/schema/doctor.ts +45 -20
  41. package/src/schema/generate-drizzle-schema-logic.ts +24 -29
  42. package/src/schema/generate-postgres-ddl-logic.ts +76 -28
  43. package/src/schema/introspect-db-inference.ts +1 -1
  44. package/src/schema/introspect-db-logic.ts +1 -10
  45. package/src/schema/introspect-db-naming.ts +15 -0
  46. package/src/schema/introspect-db.ts +19 -2
  47. package/src/schema/introspect-runtime.ts +1 -1
  48. package/src/security/policy-drift.test.ts +199 -14
  49. package/src/security/policy-drift.ts +197 -13
  50. package/src/security/rls-enforcement.ts +74 -7
  51. package/src/services/BranchService.ts +42 -10
  52. package/src/services/FetchService.ts +65 -270
  53. package/src/services/PersistService.ts +130 -14
  54. package/src/services/RelationService.ts +153 -94
  55. package/src/services/channel-history.ts +343 -0
  56. package/src/services/collection-helpers.ts +164 -47
  57. package/src/services/dataService.ts +3 -2
  58. package/src/services/index.ts +1 -0
  59. package/src/services/realtimeService.ts +238 -29
  60. package/src/services/row-pipeline.ts +239 -0
  61. package/src/utils/drizzle-conditions.ts +13 -0
  62. package/src/websocket.ts +34 -12
  63. package/dist/chunk-DSJWtz9O.js +0 -40
  64. package/dist/schema/auth-default-policies.d.ts +0 -10
  65. package/dist/src-Eh-CZosp.js +0 -595
  66. package/dist/src-Eh-CZosp.js.map +0 -1
  67. package/src/schema/auth-default-policies.ts +0 -125
@@ -25,6 +25,18 @@ export interface PolicyRef {
25
25
  roles: string[];
26
26
  /** SELECT / INSERT / UPDATE / DELETE / ALL. */
27
27
  command: string;
28
+ /** Whether a USING clause is present at all (not what it says). */
29
+ hasUsing: boolean;
30
+ /** Whether a WITH CHECK clause is present at all (not what it says). */
31
+ hasWithCheck: boolean;
32
+ /**
33
+ * The live clause text, when read from `pg_policies`. Present only for live
34
+ * policies (the expected side is parsed from DDL and does not carry it).
35
+ * Used solely for the insecure-tautology scan, not for divergence — Postgres
36
+ * rewrites this text, so it is not safe to diff against expected.
37
+ */
38
+ qual?: string | null;
39
+ withCheck?: string | null;
28
40
  }
29
41
 
30
42
  export interface PolicyDrift {
@@ -34,24 +46,76 @@ export interface PolicyDrift {
34
46
  orphaned: PolicyRef[];
35
47
  /** Same policy name, different roles or command. */
36
48
  diverged: { expected: PolicyRef; actual: PolicyRef; differences: string[] }[];
49
+ /**
50
+ * A live policy whose expression is the known-permissive tautology
51
+ * `auth.uid() IS NOT NULL` — true for anonymous visitors too, because the
52
+ * user path coerces a blank id to the `'anonymous'` sentinel. This is what
53
+ * `policy.authenticated()` used to compile to, so a database pushed before
54
+ * that fix carries it, and neither the name, roles, command nor clause
55
+ * *presence* differs from the corrected policy — the only thing that changed
56
+ * is the expression text, which this checker otherwise (correctly) ignores.
57
+ * So it is the one drift that hides from every other check here.
58
+ *
59
+ * @see reason a sentence naming the clause and what to do.
60
+ */
61
+ insecure: { policy: PolicyRef; reason: string }[];
37
62
  }
38
63
 
39
64
  export interface Queryable {
40
65
  query<R>(text: string, values?: unknown[]): Promise<{ rows: R[] }>;
41
66
  }
42
67
 
43
- const CREATE_POLICY = /CREATE POLICY "([^"]+)" ON "([^"]+)"\."([^"]+)"\s+AS (\w+)\s+FOR (\w+)\s+TO ([^\n]+?)(?:\s+USING|\s+WITH CHECK|;)/gi;
68
+ // The trailing group captures whichever clause follows the TO list, which is
69
+ // what tells us the clause is present.
70
+ const CREATE_POLICY = /CREATE POLICY "([^"]+)" ON "([^"]+)"\."([^"]+)"\s+AS (\w+)\s+FOR (\w+)\s+TO ([^\n]+?)(\s+USING\s*\(|\s+WITH CHECK\s*\(|;)/gi;
71
+
72
+ const WITH_CHECK_NEXT = /^\s+WITH CHECK\s*\(/i;
73
+
74
+ /**
75
+ * Index just past the `)` closing a clause whose `(` ends at `open`.
76
+ *
77
+ * Needed because a policy expression nests parens and can contain a quoted
78
+ * literal holding either character, so "find the next `)`" would stop early and
79
+ * miss the `WITH CHECK` that follows.
80
+ */
81
+ function clauseEnd(ddl: string, open: number): number {
82
+ let depth = 1;
83
+ let inQuote = false;
84
+ for (let i = open; i < ddl.length; i++) {
85
+ const c = ddl[i];
86
+ if (inQuote) {
87
+ // '' is an escaped quote inside a string, not a close.
88
+ if (c === "'") {
89
+ if (ddl[i + 1] === "'") i++;
90
+ else inQuote = false;
91
+ }
92
+ continue;
93
+ }
94
+ if (c === "'") inQuote = true;
95
+ else if (c === "(") depth++;
96
+ else if (c === ")" && --depth === 0) return i + 1;
97
+ }
98
+ return ddl.length;
99
+ }
44
100
 
45
101
  /** Parse the generated DDL rather than rebuilding the shape by hand. */
46
102
  export function parseExpectedPolicies(ddl: string): PolicyRef[] {
47
103
  const found: PolicyRef[] = [];
48
104
  for (const m of ddl.matchAll(CREATE_POLICY)) {
49
- const [, name, schema, table, , command, rolesRaw] = m;
105
+ const [, name, schema, table, , command, rolesRaw, clause] = m;
50
106
  const roles = rolesRaw
51
107
  .split(",")
52
108
  .map((r) => r.trim().replace(/^"|"$/g, ""))
53
109
  .filter(Boolean);
54
- found.push({ schema, table, name, roles, command: command.toUpperCase() });
110
+
111
+ // The generator emits USING before WITH CHECK, so what follows the TO
112
+ // list settles USING; WITH CHECK is then whatever follows that clause.
113
+ const hasUsing = /USING/i.test(clause);
114
+ const hasWithCheck = hasUsing
115
+ ? WITH_CHECK_NEXT.test(ddl.slice(clauseEnd(ddl, m.index + m[0].length)))
116
+ : /WITH CHECK/i.test(clause);
117
+
118
+ found.push({ schema, table, name, roles, command: command.toUpperCase(), hasUsing, hasWithCheck });
55
119
  }
56
120
  return found;
57
121
  }
@@ -59,8 +123,9 @@ export function parseExpectedPolicies(ddl: string): PolicyRef[] {
59
123
  async function readLivePolicies(client: Queryable, schemas: string[]): Promise<PolicyRef[]> {
60
124
  const { rows } = await client.query<{
61
125
  schemaname: string; tablename: string; policyname: string; roles: string[] | string; cmd: string;
126
+ qual: string | null; with_check: string | null;
62
127
  }>(
63
- `SELECT schemaname, tablename, policyname, roles, cmd
128
+ `SELECT schemaname, tablename, policyname, roles, cmd, qual, with_check
64
129
  FROM pg_policies
65
130
  WHERE schemaname = ANY($1)`,
66
131
  [schemas]
@@ -74,10 +139,34 @@ async function readLivePolicies(client: Queryable, schemas: string[]): Promise<P
74
139
  roles: Array.isArray(r.roles)
75
140
  ? r.roles
76
141
  : String(r.roles ?? "").replace(/^\{|\}$/g, "").split(",").filter(Boolean),
77
- command: (r.cmd ?? "ALL").toUpperCase()
142
+ command: (r.cmd ?? "ALL").toUpperCase(),
143
+ // Presence only. Postgres rewrites the text, but it does not invent or
144
+ // drop a clause: NULL here means the policy genuinely has none.
145
+ hasUsing: r.qual != null,
146
+ hasWithCheck: r.with_check != null,
147
+ qual: r.qual,
148
+ withCheck: r.with_check
78
149
  }));
79
150
  }
80
151
 
152
+ /**
153
+ * The permissive tautology `auth.uid() IS NOT NULL`, without the
154
+ * `<> 'anonymous'` guard that makes it mean "signed in".
155
+ *
156
+ * Whitespace varies with Postgres's rewrite, so match on a collapsed form. The
157
+ * guard clause (`<> 'anonymous'`, in any spelling) is what distinguishes the
158
+ * corrected policy from the stale one, so its presence clears the text.
159
+ */
160
+ function isPermissiveAuthTautology(clause: string | null | undefined): boolean {
161
+ if (!clause) return false;
162
+ const flat = clause.toLowerCase().replace(/\s+/g, " ");
163
+ if (!/auth\.uid\(\)\s*is not null/.test(flat)) return false;
164
+ // The fix appends `AND auth.uid() <> 'anonymous'`; Postgres may store the
165
+ // literal as `'anonymous'::text`. Either spelling means it is the corrected
166
+ // policy, not the tautology.
167
+ return !/<>\s*'anonymous'/.test(flat) && !/!=\s*'anonymous'/.test(flat);
168
+ }
169
+
81
170
  const keyOf = (p: PolicyRef) => `${p.schema}.${p.table}.${p.name}`;
82
171
  const sameRoles = (a: string[], b: string[]) =>
83
172
  a.length === b.length && [...a].sort().join(",") === [...b].sort().join(",");
@@ -85,11 +174,18 @@ const sameRoles = (a: string[], b: string[]) =>
85
174
  /**
86
175
  * Diff expected against live.
87
176
  *
88
- * Compares names, roles and command only — all exact values. Policy
89
- * *expressions* are deliberately not compared: Postgres rewrites `qual`/
90
- * `with_check` when storing them (parenthesising, casting, schema-qualifying),
91
- * so text comparison reports drift that does not exist, and a check that cries
92
- * wolf gets ignored. Roles alone catch the failure this exists for.
177
+ * Compares names, roles, command, and whether each clause exists — all exact
178
+ * values. Policy expression *text* is deliberately not compared: Postgres
179
+ * rewrites `qual`/`with_check` when storing them (parenthesising, casting,
180
+ * schema-qualifying), so text comparison reports drift that does not exist, and
181
+ * a check that cries wolf gets ignored.
182
+ *
183
+ * Presence is not text, though. A NULL `qual` is not a rewrite of an
184
+ * expression, it is the absence of one, and absence has no false-positive risk:
185
+ * either the generator emitted a clause or it did not. That distinction is worth
186
+ * the extra comparison — a production database was found with a SELECT policy
187
+ * whose `qual` was NULL, matching on every field this checked and denying 100%
188
+ * of reads. The same blindness would hide a policy that fails open.
93
189
  */
94
190
  export async function checkPolicyDrift(
95
191
  client: Queryable,
@@ -99,13 +195,31 @@ export async function checkPolicyDrift(
99
195
  const schemas = [...new Set(expected.map((p) => p.schema))];
100
196
  // Nothing expected means nothing to reconcile against; scanning every
101
197
  // schema would report the whole database as orphaned.
102
- if (schemas.length === 0) return { missing: [], orphaned: [], diverged: [] };
198
+ if (schemas.length === 0) return { missing: [], orphaned: [], diverged: [], insecure: [] };
103
199
 
104
200
  const live = await readLivePolicies(client, schemas);
105
201
  const liveByKey = new Map(live.map((p) => [keyOf(p), p]));
106
202
  const expectedByKey = new Map(expected.map((p) => [keyOf(p), p]));
107
203
 
108
- const drift: PolicyDrift = { missing: [], orphaned: [], diverged: [] };
204
+ const drift: PolicyDrift = { missing: [], orphaned: [], diverged: [], insecure: [] };
205
+
206
+ // Scan every live policy for the permissive tautology. This is deliberately
207
+ // independent of the name-keyed diff below: a database pushed before the
208
+ // `authenticated()` fix matches its expected policy on name, roles, command
209
+ // and clause presence, so nothing else here would flag it.
210
+ for (const p of live) {
211
+ const clause = isPermissiveAuthTautology(p.qual)
212
+ ? "USING"
213
+ : isPermissiveAuthTautology(p.withCheck) ? "WITH CHECK" : null;
214
+ if (clause) {
215
+ drift.insecure.push({
216
+ policy: p,
217
+ reason: `${clause} is \`auth.uid() IS NOT NULL\`, which is true for anonymous ` +
218
+ `visitors too — this grants access to signed-out requests. It predates the ` +
219
+ `\`policy.authenticated()\` fix; re-run \`rebase db push\` to tighten it.`
220
+ });
221
+ }
222
+ }
109
223
 
110
224
  for (const [key, want] of expectedByKey) {
111
225
  const got = liveByKey.get(key);
@@ -120,6 +234,13 @@ export async function checkPolicyDrift(
120
234
  if (want.command !== got.command) {
121
235
  differences.push(`command: expected ${want.command}, database has ${got.command}`);
122
236
  }
237
+ for (const clause of ["USING", "WITH CHECK"] as const) {
238
+ const key = clause === "USING" ? "hasUsing" : "hasWithCheck";
239
+ if (want[key] === got[key]) continue;
240
+ differences.push(want[key]
241
+ ? `${clause}: expected an expression, database has none — this policy matches no rows`
242
+ : `${clause}: expected none, database has an expression`);
243
+ }
123
244
  if (differences.length > 0) drift.diverged.push({ expected: want, actual: got, differences });
124
245
  }
125
246
 
@@ -130,8 +251,64 @@ export async function checkPolicyDrift(
130
251
  return drift;
131
252
  }
132
253
 
254
+ /**
255
+ * Does this name look like one the generator produced for this table?
256
+ *
257
+ * Unnamed rules compile to `<table>_<op>_<sha1[0:7]>` (plus `_<idx>` when one
258
+ * rule spans several operations), and the hash covers the rule's semantics — so
259
+ * *editing* a rule renames its policy. The policy under the old name is left
260
+ * behind by `db push`, which only DROPs the names it is about to CREATE, and
261
+ * Postgres ORs PERMISSIVE policies together: a superseded `USING (true)` keeps
262
+ * granting everything no matter how tight its replacement is.
263
+ *
264
+ * Matching the shape is what makes dropping them safe. A hand-written policy
265
+ * would have to collide with a 7-hex digest to be mistaken for generated one;
266
+ * a policy named anything else is left alone and merely reported, because a
267
+ * custom name is indistinguishable from one someone wrote in SQL on purpose.
268
+ */
269
+ export function isGeneratedPolicyName(name: string, table: string): boolean {
270
+ return new RegExp(`^${table.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}_(select|insert|update|delete|all)_[0-9a-f]{7}(_\\d+)?$`)
271
+ .test(name);
272
+ }
273
+
274
+ export interface OrphanCleanup {
275
+ /** Superseded generated policies that were dropped. */
276
+ dropped: PolicyRef[];
277
+ /** Orphans left in place because their names are not generator-shaped. */
278
+ kept: PolicyRef[];
279
+ }
280
+
281
+ /**
282
+ * Drop the policies an earlier push superseded but never removed.
283
+ *
284
+ * Only touches tables the collections describe — a table with no expected
285
+ * policy is not ours to reconcile, and scanning by schema alone would sweep up
286
+ * policies belonging to something else sharing the database.
287
+ */
288
+ export async function dropOrphanedPolicies(
289
+ client: Queryable,
290
+ drift: PolicyDrift,
291
+ collections: CollectionConfig[]
292
+ ): Promise<OrphanCleanup> {
293
+ const expected = parseExpectedPolicies(generatePostgresPoliciesDdl(collections));
294
+ const managed = new Set(expected.map((p) => `${p.schema}.${p.table}`));
295
+
296
+ const cleanup: OrphanCleanup = { dropped: [], kept: [] };
297
+ for (const p of drift.orphaned) {
298
+ if (!managed.has(`${p.schema}.${p.table}`) || !isGeneratedPolicyName(p.name, p.table)) {
299
+ cleanup.kept.push(p);
300
+ continue;
301
+ }
302
+ // Identifiers are quoted, and the name came from pg_policies rather than
303
+ // from user input, so it is already a valid identifier.
304
+ await client.query(`DROP POLICY IF EXISTS "${p.name}" ON "${p.schema}"."${p.table}"`);
305
+ cleanup.dropped.push(p);
306
+ }
307
+ return cleanup;
308
+ }
309
+
133
310
  export const hasDrift = (d: PolicyDrift): boolean =>
134
- d.missing.length > 0 || d.orphaned.length > 0 || d.diverged.length > 0;
311
+ d.missing.length > 0 || d.orphaned.length > 0 || d.diverged.length > 0 || d.insecure.length > 0;
135
312
 
136
313
  /** Human-readable report; empty string when the database matches the config. */
137
314
  export function formatPolicyDrift(drift: PolicyDrift): string {
@@ -155,5 +332,12 @@ export function formatPolicyDrift(drift: PolicyDrift): string {
155
332
  for (const diff of d.differences) lines.push(` ${diff}`);
156
333
  }
157
334
  }
335
+ if (drift.insecure.length > 0) {
336
+ lines.push(" Insecure — a live policy grants access it should not:");
337
+ for (const i of drift.insecure) {
338
+ lines.push(` • ${i.policy.schema}.${i.policy.table} → "${i.policy.name}"`);
339
+ lines.push(` ${i.reason}`);
340
+ }
341
+ }
158
342
  return lines.join("\n");
159
343
  }
@@ -1,4 +1,6 @@
1
1
  import { sql as drizzleSql, SQL } from "drizzle-orm";
2
+ import { ANONYMOUS_USER_ID, PolicyExpression, SecurityRule } from "@rebasepro/types";
3
+ import { AnonymousGrantRisk, findAnonymousGrants, securityRuleToConditions } from "@rebasepro/common";
2
4
  import { logger } from "@rebasepro/server";
3
5
 
4
6
  /**
@@ -57,7 +59,7 @@ export interface ConnectionPosture {
57
59
  }
58
60
 
59
61
  export interface AuthContext {
60
- userId: string;
62
+ uid: string;
61
63
  /** Raw roles as carried on the user (strings or `{ id }` objects). */
62
64
  roles: unknown[];
63
65
  }
@@ -198,21 +200,29 @@ export async function ensureAppRole(run: RawSqlRunner, schemas: string[]): Promi
198
200
  * SECURITY: this function is only ever called on the **user** path (the server
199
201
  * context uses the base/owner driver and never calls it). The default policies
200
202
  * treat `auth.uid() IS NULL` as the trusted server context, and `auth.uid()`
201
- * is `NULLIF(current_setting('app.user_id'), '')` — so an EMPTY user id would
203
+ * is `NULLIF(current_setting('app.uid'), '')` — so an EMPTY user id would
202
204
  * be read as NULL and silently escalate a user request to server privileges.
203
- * Coerce empty/blank ids to a sentinel here, at the single chokepoint, rather
204
- * than trusting every caller (e.g. realtime subscription auth) to do it.
205
+ * Coerce empty/blank ids to `ANONYMOUS_USER_ID` here, at the single chokepoint,
206
+ * rather than trusting every caller (e.g. realtime subscription auth) to do it.
207
+ * That sentinel is exported from `@rebasepro/types` because it leaks into rule
208
+ * semantics: it is why `auth.uid() IS NOT NULL` is true for anonymous requests.
205
209
  */
206
210
  export async function applyAuthContext(tx: SqlTx, auth: AuthContext, userRole?: string): Promise<void> {
207
- const userId = typeof auth.userId === "string" && auth.userId.trim() !== "" ? auth.userId : "anonymous";
211
+ const uid = typeof auth.uid === "string" && auth.uid.trim() !== "" ? auth.uid : ANONYMOUS_USER_ID;
208
212
  const normalizedRoles = auth.roles.map((r: unknown) =>
209
213
  typeof r === "string" ? r : (r as Record<string, unknown>)?.id ?? String(r)
210
214
  );
215
+ // `app.user_id` is the pre-rename spelling, still written because policies
216
+ // are data: a database provisioned before the rename holds rules compiled
217
+ // to `current_setting('app.user_id')`, and those predicates would evaluate
218
+ // to NULL — failing open or locking out — if we stopped setting it. Drop
219
+ // the alias only once no live database carries a legacy policy.
211
220
  await tx.execute(drizzleSql`
212
221
  SELECT
213
- set_config('app.user_id', ${userId}, true),
222
+ set_config('app.uid', ${uid}, true),
223
+ set_config('app.user_id', ${uid}, true),
214
224
  set_config('app.user_roles', ${normalizedRoles.join(",")}, true),
215
- set_config('app.jwt', ${JSON.stringify({ sub: userId, roles: auth.roles })}, true)
225
+ set_config('app.jwt', ${JSON.stringify({ sub: uid, roles: auth.roles })}, true)
216
226
  `);
217
227
  if (userRole) {
218
228
  await tx.execute(drizzleSql.raw(`SET LOCAL ROLE ${quoteIdent(userRole)}`));
@@ -226,6 +236,63 @@ const FOREIGN_CONVENTION_ROLES: Record<string, string> = {
226
236
  service_role: "Supabase"
227
237
  };
228
238
 
239
+ /**
240
+ * Warn about rules that read as "signed-in users only" but admit anonymous
241
+ * callers — `auth.uid() IS NOT NULL`, or a comparison against another
242
+ * platform's magic user id such as `'anon'`.
243
+ *
244
+ * The sibling of {@link validatePolicyPgRoles}, for the more dangerous spelling
245
+ * of the same habit. A foreign `pgRoles` value makes a policy unreachable and
246
+ * the table reads empty — loud, and that guard throws. These do the opposite:
247
+ * the rule compiles to a grant, and nothing looks wrong until the data is
248
+ * already public.
249
+ *
250
+ * Warns rather than throws. Unlike an unreachable `pgRoles`, these rules are
251
+ * serving traffic today: refusing to boot would take an app offline to report a
252
+ * problem it already has, and on the read path it would take it offline
253
+ * *because* its data was exposed. Rewriting the author's SQL is not an option
254
+ * either — this is the escape hatch whose whole promise is that it means what it
255
+ * says. So: say so, loudly, and leave the rule alone.
256
+ */
257
+ export function warnOnAnonymousGrants(
258
+ collections: { slug?: string; securityRules?: readonly SecurityRule[] }[]
259
+ ): void {
260
+ // Grouped by the mistake, not by the rule: one habit typically repeats
261
+ // across every collection an author wrote, and a per-rule list would repeat
262
+ // the same paragraph dozens of times and get skimmed.
263
+ const byRisk = new Map<string, { risk: AnonymousGrantRisk; sites: string[] }>();
264
+
265
+ for (const collection of collections) {
266
+ for (const rule of collection.securityRules ?? []) {
267
+ const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
268
+ const risks = [usingExpr, withCheckExpr]
269
+ .filter((e): e is PolicyExpression => e !== null)
270
+ .flatMap(findAnonymousGrants);
271
+
272
+ for (const risk of risks) {
273
+ const key = `${risk.pattern}:${risk.detail}`;
274
+ const site = `${collection.slug ?? "(unnamed)"} → "${rule.name ?? "(unnamed rule)"}"`;
275
+ const entry = byRisk.get(key) ?? { risk, sites: [] };
276
+ if (!entry.sites.includes(site)) entry.sites.push(site);
277
+ byRisk.set(key, entry);
278
+ }
279
+ }
280
+ }
281
+
282
+ if (byRisk.size === 0) return;
283
+
284
+ const problems = [...byRisk.values()].map(({ risk, sites }) =>
285
+ ` • ${risk.explanation}\n ${sites.length} rule(s): ${sites.join(", ")}`
286
+ );
287
+
288
+ logger.warn(
289
+ `Security rules that read as a lockdown but grant access to anonymous requests. Every caller from a ` +
290
+ `client carries a user id ('${ANONYMOUS_USER_ID}' when nobody is signed in), so these clauses are ` +
291
+ `true for everyone:\n\n` +
292
+ problems.join("\n\n") + "\n"
293
+ );
294
+ }
295
+
229
296
  /**
230
297
  * Reject `pgRoles` that this server can never satisfy.
231
298
  *
@@ -11,10 +11,45 @@ import { sql } from "drizzle-orm";
11
11
  import { BranchInfo } from "@rebasepro/types";
12
12
  import { DrizzleClient } from "../interfaces";
13
13
  import { DatabasePoolManager } from "../databasePoolManager";
14
+ import { extractPgError, extractCauseMessage } from "../utils/pg-error-utils";
14
15
 
15
16
  /** Internal prefix applied to branch database names to avoid collisions. */
16
17
  const BRANCH_DB_PREFIX = "rb_";
17
18
 
19
+ /** `duplicate_database` — the target database name is already taken. */
20
+ const PG_DUPLICATE_DATABASE = "42P04";
21
+
22
+ /** `object_in_use` — the database still has connections attached. */
23
+ const PG_OBJECT_IN_USE = "55006";
24
+
25
+ /**
26
+ * Describe a failed branch DDL statement in terms a user can act on.
27
+ *
28
+ * Drizzle reports failures as `Failed query: <sql> params:` and hides the real
29
+ * PostgreSQL error in the `cause` chain, so matching on `err.message` never sees
30
+ * the actual problem. Match on the PG error code instead — it survives wrapping
31
+ * and, unlike the message text, is not locale-dependent.
32
+ */
33
+ function describeBranchDdlError(err: unknown, fallbackContext: string): Error {
34
+ const pgError = extractPgError(err);
35
+
36
+ if (pgError?.code === PG_DUPLICATE_DATABASE) {
37
+ return new Error(`Database "${fallbackContext}" already exists on the server. Choose a different branch name.`);
38
+ }
39
+ if (pgError?.code === PG_OBJECT_IN_USE) {
40
+ return new Error(
41
+ `Cannot complete the operation: the database "${fallbackContext}" has active connections. ` +
42
+ "Close other clients or connections and try again."
43
+ );
44
+ }
45
+
46
+ // Unknown failure: surface the real PG message rather than the Drizzle
47
+ // wrapper, which would otherwise show the raw SQL and no reason at all.
48
+ const detail = pgError?.message ?? extractCauseMessage(err);
49
+ if (detail) return new Error(detail);
50
+ return err instanceof Error ? err : new Error(String(err));
51
+ }
52
+
18
53
  /** Fully-qualified metadata table in the rebase schema. */
19
54
  const BRANCHES_TABLE = "rebase.branches";
20
55
 
@@ -109,18 +144,15 @@ export class BranchService {
109
144
  sql.raw(`CREATE DATABASE "${safeDbName}" TEMPLATE "${safeSourceDb}"`)
110
145
  );
111
146
  } catch (err) {
112
- const msg = err instanceof Error ? err.message : String(err);
113
- if (msg.includes("already exists")) {
114
- throw new Error(`Database "${dbName}" already exists on the server. Choose a different branch name.`);
115
- }
116
- // If template fails due to active connections, provide a helpful error
117
- if (msg.includes("being accessed by other users")) {
147
+ const pgError = extractPgError(err);
148
+ if (pgError?.code === PG_OBJECT_IN_USE) {
149
+ // The template not the new database is the one still in use.
118
150
  throw new Error(
119
151
  `Cannot create branch: the source database "${sourceDb}" has active connections. ` +
120
152
  "Close other clients or connections and try again."
121
153
  );
122
154
  }
123
- throw err;
155
+ throw describeBranchDdlError(err, dbName);
124
156
  }
125
157
 
126
158
  // Record metadata in the default database
@@ -166,14 +198,14 @@ export class BranchService {
166
198
  try {
167
199
  await this.db.execute(sql.raw(`DROP DATABASE "${safeDbName}"`));
168
200
  } catch (err) {
169
- const msg = err instanceof Error ? err.message : String(err);
170
- if (msg.includes("being accessed by other users")) {
201
+ const pgError = extractPgError(err);
202
+ if (pgError?.code === PG_OBJECT_IN_USE) {
171
203
  throw new Error(
172
204
  `Cannot delete branch "${sanitizedName}": the database has active connections. ` +
173
205
  "Close other clients and try again."
174
206
  );
175
207
  }
176
- throw err;
208
+ throw describeBranchDdlError(err, dbName);
177
209
  }
178
210
 
179
211
  // Remove metadata