@rebasepro/server-postgres 0.9.1-canary.fd3754b → 0.9.1-canary.ff338b5
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/PostgresBackendDriver.d.ts +25 -2
- package/dist/PostgresBootstrapper.d.ts +10 -0
- package/dist/auth/services.d.ts +16 -0
- package/dist/collections/buildRegistry.d.ts +27 -0
- package/dist/connection.d.ts +21 -0
- package/dist/data-transformer.d.ts +9 -2
- package/dist/index.es.js +2005 -2583
- package/dist/index.es.js.map +1 -1
- package/dist/schema/doctor.d.ts +1 -1
- package/dist/security/policy-drift.d.ts +46 -5
- package/dist/security/rls-enforcement.d.ts +27 -2
- package/dist/services/FetchService.d.ts +4 -24
- package/dist/services/PersistService.d.ts +27 -1
- package/dist/services/RelationService.d.ts +34 -1
- package/dist/services/collection-helpers.d.ts +79 -14
- package/dist/services/dataService.d.ts +3 -1
- package/dist/services/index.d.ts +1 -1
- package/dist/services/realtimeService.d.ts +7 -0
- package/dist/services/row-pipeline.d.ts +63 -0
- package/package.json +16 -17
- package/src/PostgresBackendDriver.ts +127 -13
- package/src/PostgresBootstrapper.ts +68 -26
- package/src/auth/ensure-tables.ts +73 -11
- package/src/auth/services.ts +49 -19
- package/src/cli-helpers.ts +2 -20
- package/src/cli.ts +60 -0
- package/src/collections/buildRegistry.ts +59 -0
- package/src/connection.ts +61 -1
- package/src/data-transformer.ts +11 -9
- package/src/databasePoolManager.ts +2 -0
- package/src/schema/doctor-cli.ts +5 -1
- package/src/schema/doctor.ts +45 -20
- package/src/schema/generate-drizzle-schema-logic.ts +24 -29
- package/src/schema/generate-postgres-ddl-logic.ts +76 -28
- package/src/schema/introspect-db.ts +19 -2
- package/src/security/policy-drift.test.ts +153 -14
- package/src/security/policy-drift.ts +128 -10
- package/src/security/rls-enforcement.ts +64 -3
- package/src/services/BranchService.ts +42 -10
- package/src/services/FetchService.ts +65 -270
- package/src/services/PersistService.ts +130 -14
- package/src/services/RelationService.ts +153 -94
- package/src/services/collection-helpers.ts +164 -47
- package/src/services/dataService.ts +3 -2
- package/src/services/index.ts +1 -0
- package/src/services/realtimeService.ts +40 -19
- package/src/services/row-pipeline.ts +239 -0
- package/src/utils/drizzle-conditions.ts +13 -0
- package/src/websocket.ts +4 -1
- package/dist/chunk-DSJWtz9O.js +0 -40
- package/dist/schema/auth-default-policies.d.ts +0 -10
- package/dist/src-Eh-CZosp.js +0 -595
- package/dist/src-Eh-CZosp.js.map +0 -1
- package/src/schema/auth-default-policies.ts +0 -125
|
@@ -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
|
/**
|
|
@@ -200,11 +202,13 @@ export async function ensureAppRole(run: RawSqlRunner, schemas: string[]): Promi
|
|
|
200
202
|
* treat `auth.uid() IS NULL` as the trusted server context, and `auth.uid()`
|
|
201
203
|
* is `NULLIF(current_setting('app.user_id'), '')` — 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
|
|
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 :
|
|
211
|
+
const userId = typeof auth.userId === "string" && auth.userId.trim() !== "" ? auth.userId : 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
|
);
|
|
@@ -226,6 +230,63 @@ const FOREIGN_CONVENTION_ROLES: Record<string, string> = {
|
|
|
226
230
|
service_role: "Supabase"
|
|
227
231
|
};
|
|
228
232
|
|
|
233
|
+
/**
|
|
234
|
+
* Warn about rules that read as "signed-in users only" but admit anonymous
|
|
235
|
+
* callers — `auth.uid() IS NOT NULL`, or a comparison against another
|
|
236
|
+
* platform's magic user id such as `'anon'`.
|
|
237
|
+
*
|
|
238
|
+
* The sibling of {@link validatePolicyPgRoles}, for the more dangerous spelling
|
|
239
|
+
* of the same habit. A foreign `pgRoles` value makes a policy unreachable and
|
|
240
|
+
* the table reads empty — loud, and that guard throws. These do the opposite:
|
|
241
|
+
* the rule compiles to a grant, and nothing looks wrong until the data is
|
|
242
|
+
* already public.
|
|
243
|
+
*
|
|
244
|
+
* Warns rather than throws. Unlike an unreachable `pgRoles`, these rules are
|
|
245
|
+
* serving traffic today: refusing to boot would take an app offline to report a
|
|
246
|
+
* problem it already has, and on the read path it would take it offline
|
|
247
|
+
* *because* its data was exposed. Rewriting the author's SQL is not an option
|
|
248
|
+
* either — this is the escape hatch whose whole promise is that it means what it
|
|
249
|
+
* says. So: say so, loudly, and leave the rule alone.
|
|
250
|
+
*/
|
|
251
|
+
export function warnOnAnonymousGrants(
|
|
252
|
+
collections: { slug?: string; securityRules?: readonly SecurityRule[] }[]
|
|
253
|
+
): void {
|
|
254
|
+
// Grouped by the mistake, not by the rule: one habit typically repeats
|
|
255
|
+
// across every collection an author wrote, and a per-rule list would repeat
|
|
256
|
+
// the same paragraph dozens of times and get skimmed.
|
|
257
|
+
const byRisk = new Map<string, { risk: AnonymousGrantRisk; sites: string[] }>();
|
|
258
|
+
|
|
259
|
+
for (const collection of collections) {
|
|
260
|
+
for (const rule of collection.securityRules ?? []) {
|
|
261
|
+
const { usingExpr, withCheckExpr } = securityRuleToConditions(rule);
|
|
262
|
+
const risks = [usingExpr, withCheckExpr]
|
|
263
|
+
.filter((e): e is PolicyExpression => e !== null)
|
|
264
|
+
.flatMap(findAnonymousGrants);
|
|
265
|
+
|
|
266
|
+
for (const risk of risks) {
|
|
267
|
+
const key = `${risk.pattern}:${risk.detail}`;
|
|
268
|
+
const site = `${collection.slug ?? "(unnamed)"} → "${rule.name ?? "(unnamed rule)"}"`;
|
|
269
|
+
const entry = byRisk.get(key) ?? { risk, sites: [] };
|
|
270
|
+
if (!entry.sites.includes(site)) entry.sites.push(site);
|
|
271
|
+
byRisk.set(key, entry);
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
if (byRisk.size === 0) return;
|
|
277
|
+
|
|
278
|
+
const problems = [...byRisk.values()].map(({ risk, sites }) =>
|
|
279
|
+
` • ${risk.explanation}\n ${sites.length} rule(s): ${sites.join(", ")}`
|
|
280
|
+
);
|
|
281
|
+
|
|
282
|
+
logger.warn(
|
|
283
|
+
`Security rules that read as a lockdown but grant access to anonymous requests. Every caller from a ` +
|
|
284
|
+
`client carries a user id ('${ANONYMOUS_USER_ID}' when nobody is signed in), so these clauses are ` +
|
|
285
|
+
`true for everyone:\n\n` +
|
|
286
|
+
problems.join("\n\n") + "\n"
|
|
287
|
+
);
|
|
288
|
+
}
|
|
289
|
+
|
|
229
290
|
/**
|
|
230
291
|
* Reject `pgRoles` that this server can never satisfy.
|
|
231
292
|
*
|
|
@@ -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
|
|
113
|
-
if (
|
|
114
|
-
|
|
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
|
|
170
|
-
if (
|
|
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
|