@rebasepro/server-postgres 0.12.0 → 0.12.1-canary.g35be8cb

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 (41) hide show
  1. package/dist/auth/services.d.ts +16 -0
  2. package/dist/backup-service-DH9kPg-E.js +8866 -0
  3. package/dist/backup-service-DH9kPg-E.js.map +1 -0
  4. package/dist/connection-B5Wndbr1.js +196 -0
  5. package/dist/connection-B5Wndbr1.js.map +1 -0
  6. package/dist/ensure-collection-policies-Vl3Cv1Q9.js +57 -0
  7. package/dist/ensure-collection-policies-Vl3Cv1Q9.js.map +1 -0
  8. package/dist/ensure-collection-tables-DsDsNl6o.js +590 -0
  9. package/dist/ensure-collection-tables-DsDsNl6o.js.map +1 -0
  10. package/dist/index.es.js +452 -9609
  11. package/dist/index.es.js.map +1 -1
  12. package/dist/schema/auth-schema.d.ts +83 -144
  13. package/dist/schema/ensure-collection-policies.d.ts +60 -0
  14. package/dist/schema/ensure-collection-tables.d.ts +24 -2
  15. package/dist/schema/generate-postgres-ddl-logic.d.ts +116 -1
  16. package/dist/{src-BbFOPJ1S.js → src-DihrDFuP.js} +160 -150
  17. package/dist/src-DihrDFuP.js.map +1 -0
  18. package/dist/{src-Zqwaw3P5.js → src-DoU9yPqq.js} +3 -159
  19. package/dist/src-DoU9yPqq.js.map +1 -0
  20. package/dist/utils/pg-error-utils.d.ts +19 -0
  21. package/dist/websocket-BKcGvILX.js +528 -0
  22. package/dist/websocket-BKcGvILX.js.map +1 -0
  23. package/package.json +14 -14
  24. package/src/PostgresAdapter.ts +14 -0
  25. package/src/PostgresBootstrapper.ts +111 -13
  26. package/src/auth/ensure-tables.ts +164 -9
  27. package/src/auth/services.ts +21 -2
  28. package/src/schema/auth-schema.ts +30 -19
  29. package/src/schema/ensure-collection-policies.ts +105 -0
  30. package/src/schema/ensure-collection-tables.test.ts +105 -9
  31. package/src/schema/ensure-collection-tables.ts +142 -25
  32. package/src/schema/generate-drizzle-schema-logic.ts +7 -3
  33. package/src/schema/generate-postgres-ddl-logic.ts +335 -16
  34. package/src/schema/introspect-runtime.test.ts +56 -8
  35. package/src/schema/introspect-runtime.ts +31 -9
  36. package/src/utils/pg-error-utils.ts +46 -0
  37. package/dist/chunk-DSJWtz9O.js +0 -40
  38. package/dist/ensure-collection-tables-CNTcZGvn.js +0 -304
  39. package/dist/ensure-collection-tables-CNTcZGvn.js.map +0 -1
  40. package/dist/src-BbFOPJ1S.js.map +0 -1
  41. package/dist/src-Zqwaw3P5.js.map +0 -1
@@ -0,0 +1,196 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ import "process";
3
+ const require = __createRequire(import.meta.url);
4
+ import { Pool } from "pg";
5
+ import { drizzle } from "drizzle-orm/node-postgres";
6
+ import { logger } from "@rebasepro/server";
7
+ //#region \0rolldown/runtime.js
8
+ var __create = Object.create;
9
+ var __defProp = Object.defineProperty;
10
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
11
+ var __getOwnPropNames = Object.getOwnPropertyNames;
12
+ var __getProtoOf = Object.getPrototypeOf;
13
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
14
+ var __commonJSMin = (cb, mod) => () => (mod || (cb((mod = { exports: {} }).exports, mod), cb = null), mod.exports);
15
+ var __exportAll = (all, no_symbols) => {
16
+ let target = {};
17
+ for (var name in all) __defProp(target, name, {
18
+ get: all[name],
19
+ enumerable: true
20
+ });
21
+ if (!no_symbols) __defProp(target, Symbol.toStringTag, { value: "Module" });
22
+ return target;
23
+ };
24
+ var __copyProps = (to, from, except, desc) => {
25
+ if (from && typeof from === "object" || typeof from === "function") for (var keys = __getOwnPropNames(from), i = 0, n = keys.length, key; i < n; i++) {
26
+ key = keys[i];
27
+ if (!__hasOwnProp.call(to, key) && key !== except) __defProp(to, key, {
28
+ get: ((k) => from[k]).bind(null, key),
29
+ enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable
30
+ });
31
+ }
32
+ return to;
33
+ };
34
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", {
35
+ value: mod,
36
+ enumerable: true
37
+ }) : target, mod));
38
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, { get: (a, b) => (typeof require !== "undefined" ? require : a)[b] }) : x)(function(x) {
39
+ if (typeof require !== "undefined") return require.apply(this, arguments);
40
+ throw Error("Calling `require` for \"" + x + "\" in an environment that doesn't expose the `require` function. See https://rolldown.rs/in-depth/bundling-cjs#require-external-modules for more details.");
41
+ });
42
+ //#endregion
43
+ //#region src/connection.ts
44
+ var connection_exports = /* @__PURE__ */ __exportAll({
45
+ createDirectDatabaseConnection: () => createDirectDatabaseConnection,
46
+ createPostgresDatabaseConnection: () => createPostgresDatabaseConnection,
47
+ createReadReplicaConnection: () => createReadReplicaConnection,
48
+ guardPoolAgainstDirtyRelease: () => guardPoolAgainstDirtyRelease
49
+ });
50
+ var DEFAULT_POOL = {
51
+ max: 20,
52
+ idleTimeoutMillis: 3e4,
53
+ connectionTimeoutMillis: 1e4,
54
+ queryTimeout: 6e4,
55
+ statementTimeout: 3e4,
56
+ keepAlive: true
57
+ };
58
+ /** ReadyForQuery status byte: `I` idle, `T` in transaction, `E` failed transaction. */
59
+ var TX_IDLE = "I";
60
+ /**
61
+ * Destroy pool clients that are released while still inside a transaction.
62
+ *
63
+ * pg-pool returns a client to the idle list whenever `release()` is called
64
+ * without an error — even if the connection is still mid-transaction (status
65
+ * `T`/`E`). That happens in practice: drizzle's pool transaction releases in
66
+ * a `finally` after attempting ROLLBACK, and if the ROLLBACK itself fails
67
+ * (e.g. it was queued behind a statement that hit the client-side
68
+ * query_timeout), the client goes back dirty. The next checkout then runs
69
+ * its statements inside the zombie transaction — with the previous request's
70
+ * `app.*` RLS GUCs still applied, which turns unrelated queries into
71
+ * RLS-scoped ones (observed in production as registration failing with
72
+ * SQLSTATE 42501 under a leaked anonymous context).
73
+ *
74
+ * pg-pool emits `release` before it consults its private `_expired` set, so
75
+ * marking the client expired here makes `_release()` destroy it instead of
76
+ * pooling it. Both `client._txStatus` (pg ≥ 8.16) and `pool._expired` are
77
+ * private APIs — feature-detect and fall back to loud logging so an upstream
78
+ * change degrades to observability, never to silent corruption.
79
+ */
80
+ function guardPoolAgainstDirtyRelease(pool, label) {
81
+ pool.on("release", (err, client) => {
82
+ if (err) return;
83
+ const txStatus = client?._txStatus;
84
+ if (typeof txStatus !== "string" || txStatus === TX_IDLE) return;
85
+ const expired = pool._expired;
86
+ if (expired && typeof expired.add === "function" && typeof expired.has === "function" && client && typeof client === "object") {
87
+ expired.add(client);
88
+ logger.error(`[${label}] Client released back to the pool while still in a transaction (status '${txStatus}') — destroying it so the open transaction and its session state (RLS GUCs) cannot leak into the next request.`);
89
+ } else logger.error(`[${label}] Client released mid-transaction (status '${txStatus}') but the pool's internal expiry set is unavailable (pg-pool internals changed?). The connection may leak its open transaction into subsequent requests.`);
90
+ });
91
+ }
92
+ /**
93
+ * Create a Drizzle-backed Postgres connection with a production-grade
94
+ * connection pool.
95
+ *
96
+ * @param connectionString Postgres connection URL
97
+ * @param schema Optional Drizzle schema for the relational API
98
+ * @param poolConfig Optional pool tuning (merged over defaults)
99
+ *
100
+ * @returns `{ db, pool, connectionString }` — the `pool` is exposed so
101
+ * callers can register shutdown hooks (`pool.end()`) or monitor
102
+ * pool metrics.
103
+ */
104
+ function createPostgresDatabaseConnection(connectionString, schema, poolConfig) {
105
+ const opts = {
106
+ ...DEFAULT_POOL,
107
+ ...poolConfig
108
+ };
109
+ const pool = new Pool({
110
+ connectionString,
111
+ max: opts.max,
112
+ idleTimeoutMillis: opts.idleTimeoutMillis,
113
+ connectionTimeoutMillis: opts.connectionTimeoutMillis,
114
+ query_timeout: opts.queryTimeout,
115
+ statement_timeout: opts.statementTimeout,
116
+ keepAlive: opts.keepAlive,
117
+ keepAliveInitialDelayMillis: 0
118
+ });
119
+ pool.on("error", (err) => {
120
+ logger.error("[pg-pool] Unexpected pool error", { detail: err.message });
121
+ if (err.message.includes("ETIMEDOUT")) logger.warn("[pg-pool] Connection timeout detected — pool will auto-retry");
122
+ });
123
+ guardPoolAgainstDirtyRelease(pool, "pg-pool");
124
+ return {
125
+ db: schema ? drizzle(pool, { schema }) : drizzle(pool),
126
+ pool,
127
+ connectionString
128
+ };
129
+ }
130
+ /**
131
+ * Create a direct (non-pooled) connection for operations that require
132
+ * session-level features incompatible with PgBouncer transaction mode,
133
+ * such as LISTEN/NOTIFY, prepared statements, or advisory locks.
134
+ *
135
+ * Uses a smaller pool since this is only for specific use cases.
136
+ */
137
+ function createDirectDatabaseConnection(connectionString, schema, poolConfig) {
138
+ const opts = {
139
+ ...DEFAULT_POOL,
140
+ max: 5,
141
+ ...poolConfig
142
+ };
143
+ const pool = new Pool({
144
+ connectionString,
145
+ max: opts.max,
146
+ idleTimeoutMillis: opts.idleTimeoutMillis,
147
+ connectionTimeoutMillis: opts.connectionTimeoutMillis,
148
+ query_timeout: opts.queryTimeout,
149
+ statement_timeout: opts.statementTimeout,
150
+ keepAlive: opts.keepAlive,
151
+ keepAliveInitialDelayMillis: 0
152
+ });
153
+ pool.on("error", (err) => {
154
+ logger.error("[pg-direct-pool] Unexpected pool error", { detail: err.message });
155
+ });
156
+ guardPoolAgainstDirtyRelease(pool, "pg-direct-pool");
157
+ return {
158
+ db: schema ? drizzle(pool, { schema }) : drizzle(pool),
159
+ pool,
160
+ connectionString
161
+ };
162
+ }
163
+ /**
164
+ * Create a read-only connection for routing read queries to replicas.
165
+ * Uses a moderate pool size since reads are distributed across replicas.
166
+ */
167
+ function createReadReplicaConnection(connectionString, schema, poolConfig) {
168
+ const opts = {
169
+ ...DEFAULT_POOL,
170
+ max: 10,
171
+ ...poolConfig
172
+ };
173
+ const pool = new Pool({
174
+ connectionString,
175
+ max: opts.max,
176
+ idleTimeoutMillis: opts.idleTimeoutMillis,
177
+ connectionTimeoutMillis: opts.connectionTimeoutMillis,
178
+ query_timeout: opts.queryTimeout,
179
+ statement_timeout: opts.statementTimeout,
180
+ keepAlive: opts.keepAlive,
181
+ keepAliveInitialDelayMillis: 0
182
+ });
183
+ pool.on("error", (err) => {
184
+ logger.error("[pg-replica-pool] Unexpected pool error", { detail: err.message });
185
+ });
186
+ guardPoolAgainstDirtyRelease(pool, "pg-replica-pool");
187
+ return {
188
+ db: schema ? drizzle(pool, { schema }) : drizzle(pool),
189
+ pool,
190
+ connectionString
191
+ };
192
+ }
193
+ //#endregion
194
+ export { guardPoolAgainstDirtyRelease as a, __require as c, createReadReplicaConnection as i, __toESM as l, createDirectDatabaseConnection as n, __commonJSMin as o, createPostgresDatabaseConnection as r, __exportAll as s, connection_exports as t };
195
+
196
+ //# sourceMappingURL=connection-B5Wndbr1.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"connection-B5Wndbr1.js","names":[],"sources":["../src/connection.ts"],"sourcesContent":["import { Pool, PoolConfig } from \"pg\";\nimport { drizzle } from \"drizzle-orm/node-postgres\";\nimport { logger } from \"@rebasepro/server\";\n\n/**\n * Configuration for the Postgres connection pool.\n *\n * Sensible defaults are provided for production Cloud Run / single-instance\n * deployments. Override via environment variables or explicit config.\n */\nexport interface PostgresPoolConfig {\n /** Maximum number of connections in the pool (default: 20) */\n max?: number;\n /** Close idle connections after this many ms (default: 30 000) */\n idleTimeoutMillis?: number;\n /** Abort connection attempts after this many ms (default: 10 000) */\n connectionTimeoutMillis?: number;\n /** Per-query timeout in ms (default: 30 000) */\n queryTimeout?: number;\n /** Per-statement timeout in ms (default: 30 000) */\n statementTimeout?: number;\n /** Enable TCP keep-alive (default: true) */\n keepAlive?: boolean;\n}\n\nconst DEFAULT_POOL: Required<PostgresPoolConfig> = {\n max: 20,\n idleTimeoutMillis: 30_000,\n connectionTimeoutMillis: 10_000,\n // The client-side read timeout MUST be comfortably above the server-side\n // statement_timeout. When the client timer fires first, node-postgres\n // abandons the in-flight statement but keeps the connection — inside a\n // transaction that leaves the tx open (and any pending ROLLBACK is\n // spliced out of the client queue before it ever reaches the wire), so\n // the pooled connection is returned still in-transaction with its RLS\n // GUCs set. The server abort (SQLSTATE 57014) is the clean path; the\n // client timeout is only a backstop for a dead network.\n queryTimeout: 60_000,\n statementTimeout: 30_000,\n keepAlive: true\n};\n\n/** ReadyForQuery status byte: `I` idle, `T` in transaction, `E` failed transaction. */\nconst TX_IDLE = \"I\";\n\n/**\n * Destroy pool clients that are released while still inside a transaction.\n *\n * pg-pool returns a client to the idle list whenever `release()` is called\n * without an error — even if the connection is still mid-transaction (status\n * `T`/`E`). That happens in practice: drizzle's pool transaction releases in\n * a `finally` after attempting ROLLBACK, and if the ROLLBACK itself fails\n * (e.g. it was queued behind a statement that hit the client-side\n * query_timeout), the client goes back dirty. The next checkout then runs\n * its statements inside the zombie transaction — with the previous request's\n * `app.*` RLS GUCs still applied, which turns unrelated queries into\n * RLS-scoped ones (observed in production as registration failing with\n * SQLSTATE 42501 under a leaked anonymous context).\n *\n * pg-pool emits `release` before it consults its private `_expired` set, so\n * marking the client expired here makes `_release()` destroy it instead of\n * pooling it. Both `client._txStatus` (pg ≥ 8.16) and `pool._expired` are\n * private APIs — feature-detect and fall back to loud logging so an upstream\n * change degrades to observability, never to silent corruption.\n */\nexport function guardPoolAgainstDirtyRelease(pool: Pool, label: string): void {\n pool.on(\"release\", (err: Error | undefined, client: unknown) => {\n if (err) return; // errored clients are already destroyed by pg-pool\n const txStatus = (client as { _txStatus?: string | null })?._txStatus;\n if (typeof txStatus !== \"string\" || txStatus === TX_IDLE) return;\n\n // pg-pool keeps expired clients in a WeakSet (a plain object works too\n // if upstream ever changes it — duck-type on add/has).\n const expired = (pool as unknown as { _expired?: { add(c: object): unknown; has(c: object): boolean } })._expired;\n if (expired && typeof expired.add === \"function\" && typeof expired.has === \"function\" && client && typeof client === \"object\") {\n expired.add(client);\n logger.error(\n `[${label}] Client released back to the pool while still in a transaction ` +\n `(status '${txStatus}') — destroying it so the open transaction and its ` +\n `session state (RLS GUCs) cannot leak into the next request.`\n );\n } else {\n logger.error(\n `[${label}] Client released mid-transaction (status '${txStatus}') but the ` +\n `pool's internal expiry set is unavailable (pg-pool internals changed?). ` +\n `The connection may leak its open transaction into subsequent requests.`\n );\n }\n });\n}\n\n/**\n * Create a Drizzle-backed Postgres connection with a production-grade\n * connection pool.\n *\n * @param connectionString Postgres connection URL\n * @param schema Optional Drizzle schema for the relational API\n * @param poolConfig Optional pool tuning (merged over defaults)\n *\n * @returns `{ db, pool, connectionString }` — the `pool` is exposed so\n * callers can register shutdown hooks (`pool.end()`) or monitor\n * pool metrics.\n */\nexport function createPostgresDatabaseConnection(\n connectionString: string,\n schema?: Record<string, unknown>,\n poolConfig?: PostgresPoolConfig\n) {\n const opts = { ...DEFAULT_POOL,\n...poolConfig };\n\n const pgPoolConfig: PoolConfig = {\n connectionString,\n max: opts.max,\n idleTimeoutMillis: opts.idleTimeoutMillis,\n connectionTimeoutMillis: opts.connectionTimeoutMillis,\n query_timeout: opts.queryTimeout,\n statement_timeout: opts.statementTimeout,\n keepAlive: opts.keepAlive,\n keepAliveInitialDelayMillis: 0\n };\n\n const pool = new Pool(pgPoolConfig);\n\n // ── Pool event logging ────────────────────────────────────────────────\n // Uses console.* because the structured logger lives in server\n // (a separate package). The caller can replace these with the structured\n // logger if desired via pool.on() after creation.\n pool.on(\"error\", (err) => {\n logger.error(\"[pg-pool] Unexpected pool error\", { detail: err.message });\n if (err.message.includes(\"ETIMEDOUT\")) {\n logger.warn(\"[pg-pool] Connection timeout detected — pool will auto-retry\");\n }\n });\n guardPoolAgainstDirtyRelease(pool, \"pg-pool\");\n\n // Create drizzle instance — pass schema when available to enable db.query relational API\n const db = schema ? drizzle(pool, { schema }) : drizzle(pool);\n\n return { db,\npool,\nconnectionString };\n}\n\n/**\n * Create a direct (non-pooled) connection for operations that require\n * session-level features incompatible with PgBouncer transaction mode,\n * such as LISTEN/NOTIFY, prepared statements, or advisory locks.\n *\n * Uses a smaller pool since this is only for specific use cases.\n */\nexport function createDirectDatabaseConnection(\n connectionString: string,\n schema?: Record<string, unknown>,\n poolConfig?: PostgresPoolConfig\n) {\n const opts = {\n ...DEFAULT_POOL,\n max: 5,\n ...poolConfig\n };\n\n const pgPoolConfig: PoolConfig = {\n connectionString,\n max: opts.max,\n idleTimeoutMillis: opts.idleTimeoutMillis,\n connectionTimeoutMillis: opts.connectionTimeoutMillis,\n query_timeout: opts.queryTimeout,\n statement_timeout: opts.statementTimeout,\n keepAlive: opts.keepAlive,\n keepAliveInitialDelayMillis: 0\n };\n\n const pool = new Pool(pgPoolConfig);\n\n pool.on(\"error\", (err) => {\n logger.error(\"[pg-direct-pool] Unexpected pool error\", { detail: err.message });\n });\n guardPoolAgainstDirtyRelease(pool, \"pg-direct-pool\");\n\n const db = schema ? drizzle(pool, { schema }) : drizzle(pool);\n\n return { db,\npool,\nconnectionString };\n}\n\n/**\n * Create a read-only connection for routing read queries to replicas.\n * Uses a moderate pool size since reads are distributed across replicas.\n */\nexport function createReadReplicaConnection(\n connectionString: string,\n schema?: Record<string, unknown>,\n poolConfig?: PostgresPoolConfig\n) {\n const opts = {\n ...DEFAULT_POOL,\n max: 10,\n ...poolConfig\n };\n\n const pgPoolConfig: PoolConfig = {\n connectionString,\n max: opts.max,\n idleTimeoutMillis: opts.idleTimeoutMillis,\n connectionTimeoutMillis: opts.connectionTimeoutMillis,\n query_timeout: opts.queryTimeout,\n statement_timeout: opts.statementTimeout,\n keepAlive: opts.keepAlive,\n keepAliveInitialDelayMillis: 0\n };\n\n const pool = new Pool(pgPoolConfig);\n\n pool.on(\"error\", (err) => {\n logger.error(\"[pg-replica-pool] Unexpected pool error\", { detail: err.message });\n });\n guardPoolAgainstDirtyRelease(pool, \"pg-replica-pool\");\n\n const db = schema ? drizzle(pool, { schema }) : drizzle(pool);\n\n return { db,\npool,\nconnectionString };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyBA,IAAM,eAA6C;CAC/C,KAAK;CACL,mBAAmB;CACnB,yBAAyB;CASzB,cAAc;CACd,kBAAkB;CAClB,WAAW;AACf;;AAGA,IAAM,UAAU;;;;;;;;;;;;;;;;;;;;;AAsBhB,SAAgB,6BAA6B,MAAY,OAAqB;CAC1E,KAAK,GAAG,YAAY,KAAwB,WAAoB;EAC5D,IAAI,KAAK;EACT,MAAM,WAAY,QAA0C;EAC5D,IAAI,OAAO,aAAa,YAAY,aAAa,SAAS;EAI1D,MAAM,UAAW,KAAwF;EACzG,IAAI,WAAW,OAAO,QAAQ,QAAQ,cAAc,OAAO,QAAQ,QAAQ,cAAc,UAAU,OAAO,WAAW,UAAU;GAC3H,QAAQ,IAAI,MAAM;GAClB,OAAO,MACH,IAAI,MAAM,2EACE,SAAS,+GAEzB;EACJ,OACI,OAAO,MACH,IAAI,MAAM,6CAA6C,SAAS,0JAGpE;CAER,CAAC;AACL;;;;;;;;;;;;;AAcA,SAAgB,iCACZ,kBACA,QACA,YACF;CACE,MAAM,OAAO;EAAE,GAAG;EACtB,GAAG;CAAW;CAaV,MAAM,OAAO,IAAI,KAAK;EAVlB;EACA,KAAK,KAAK;EACV,mBAAmB,KAAK;EACxB,yBAAyB,KAAK;EAC9B,eAAe,KAAK;EACpB,mBAAmB,KAAK;EACxB,WAAW,KAAK;EAChB,6BAA6B;CAGX,CAAY;CAMlC,KAAK,GAAG,UAAU,QAAQ;EACtB,OAAO,MAAM,mCAAmC,EAAE,QAAQ,IAAI,QAAQ,CAAC;EACvE,IAAI,IAAI,QAAQ,SAAS,WAAW,GAChC,OAAO,KAAK,8DAA8D;CAElF,CAAC;CACD,6BAA6B,MAAM,SAAS;CAK5C,OAAO;EAAE,IAFE,SAAS,QAAQ,MAAM,EAAE,OAAO,CAAC,IAAI,QAAQ,IAAI;EAGhE;EACA;CAAiB;AACjB;;;;;;;;AASA,SAAgB,+BACZ,kBACA,QACA,YACF;CACE,MAAM,OAAO;EACT,GAAG;EACH,KAAK;EACL,GAAG;CACP;CAaA,MAAM,OAAO,IAAI,KAAK;EAVlB;EACA,KAAK,KAAK;EACV,mBAAmB,KAAK;EACxB,yBAAyB,KAAK;EAC9B,eAAe,KAAK;EACpB,mBAAmB,KAAK;EACxB,WAAW,KAAK;EAChB,6BAA6B;CAGX,CAAY;CAElC,KAAK,GAAG,UAAU,QAAQ;EACtB,OAAO,MAAM,0CAA0C,EAAE,QAAQ,IAAI,QAAQ,CAAC;CAClF,CAAC;CACD,6BAA6B,MAAM,gBAAgB;CAInD,OAAO;EAAE,IAFE,SAAS,QAAQ,MAAM,EAAE,OAAO,CAAC,IAAI,QAAQ,IAAI;EAGhE;EACA;CAAiB;AACjB;;;;;AAMA,SAAgB,4BACZ,kBACA,QACA,YACF;CACE,MAAM,OAAO;EACT,GAAG;EACH,KAAK;EACL,GAAG;CACP;CAaA,MAAM,OAAO,IAAI,KAAK;EAVlB;EACA,KAAK,KAAK;EACV,mBAAmB,KAAK;EACxB,yBAAyB,KAAK;EAC9B,eAAe,KAAK;EACpB,mBAAmB,KAAK;EACxB,WAAW,KAAK;EAChB,6BAA6B;CAGX,CAAY;CAElC,KAAK,GAAG,UAAU,QAAQ;EACtB,OAAO,MAAM,2CAA2C,EAAE,QAAQ,IAAI,QAAQ,CAAC;CACnF,CAAC;CACD,6BAA6B,MAAM,iBAAiB;CAIpD,OAAO;EAAE,IAFE,SAAS,QAAQ,MAAM,EAAE,OAAO,CAAC,IAAI,QAAQ,IAAI;EAGhE;EACA;CAAiB;AACjB"}
@@ -0,0 +1,57 @@
1
+ import { createRequire as __createRequire } from "module";
2
+ import "process";
3
+ __createRequire(import.meta.url);
4
+ import { readExistingSchema, t as planCollectionPolicies } from "./ensure-collection-tables-DsDsNl6o.js";
5
+ //#region src/schema/ensure-collection-policies.ts
6
+ var isCreatePolicy = (statement) => /^\s*CREATE POLICY/i.test(statement);
7
+ /**
8
+ * Bring the declared collections' RLS policies up to date. Returns what it did.
9
+ *
10
+ * Only tables that already exist are touched: the boot-time table creator runs
11
+ * first, so anything still missing is a table this additive path is not allowed
12
+ * to create (a junction, or a relation left to a migration). Enabling RLS on a
13
+ * non-existent table would error, so those are recorded as skipped, not failed.
14
+ */
15
+ async function ensureCollectionPolicies(client, collections, log) {
16
+ const result = {
17
+ policiesApplied: 0,
18
+ tablesSecured: 0,
19
+ skipped: [],
20
+ failures: []
21
+ };
22
+ const plans = planCollectionPolicies(collections);
23
+ if (plans.length === 0) return result;
24
+ const existing = await readExistingSchema(client, Array.from(new Set(plans.map((p) => p.schema))));
25
+ for (const plan of plans) {
26
+ if (!existing.tables.has(plan.qualified)) {
27
+ result.skipped.push({
28
+ table: plan.qualified,
29
+ reason: "table is not present in the database; create it with `rebase db push` / `rebase db migrate`"
30
+ });
31
+ continue;
32
+ }
33
+ try {
34
+ await client.query(plan.enableRls);
35
+ result.tablesSecured++;
36
+ let created = 0;
37
+ for (const statement of plan.policyStatements) {
38
+ await client.query(statement);
39
+ if (isCreatePolicy(statement)) {
40
+ result.policiesApplied++;
41
+ created++;
42
+ }
43
+ }
44
+ log?.(`${plan.qualified}: RLS enabled, ${created} policy(ies) applied`);
45
+ } catch (err) {
46
+ result.failures.push({
47
+ table: plan.qualified,
48
+ error: err instanceof Error ? err.message : String(err)
49
+ });
50
+ }
51
+ }
52
+ return result;
53
+ }
54
+ //#endregion
55
+ export { ensureCollectionPolicies };
56
+
57
+ //# sourceMappingURL=ensure-collection-policies-Vl3Cv1Q9.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"ensure-collection-policies-Vl3Cv1Q9.js","names":[],"sources":["../src/schema/ensure-collection-policies.ts"],"sourcesContent":["/**\n * Applying a bundle's RLS policies to a database at boot, idempotently.\n *\n * ## Why this exists\n *\n * {@link ensureCollectionTables} creates the collection *tables* a managed\n * runtime boots against, but a table with row-level security disabled and no\n * policies is not servable: authenticated requests run as the restricted\n * `rebase_user` role, so a read with no `SELECT` policy returns nothing (a\n * public collection answered 401) and a write with no `INSERT`/`UPDATE` policy\n * is denied. The policies live in the collections' `securityRules`; nothing at\n * boot applied them. `rebase db push` does — but it drives Atlas against a\n * local `DATABASE_URL`, and a managed tenant's database is reachable only from\n * inside the cluster, by the runtime that is already connected to it. So the\n * runtime is the only thing that *can* apply them, and this is where it does.\n *\n * ## Why this is safe to run on every boot\n *\n * Every statement is idempotent: `ENABLE ROW LEVEL SECURITY` is a no-op once\n * enabled, and each policy is a `DROP POLICY IF EXISTS` immediately followed by\n * a `CREATE POLICY`, so re-applying asserts exactly the declared state. It adds\n * and replaces; it never drops data. (It does not *reconcile* — a policy a\n * previous push left behind under an old name is not removed here; that stays a\n * `db push` / `db migrate` concern, alongside destructive schema changes.)\n *\n * Unlike table creation, a failure here is not fatal: RLS stays enabled, so a\n * table whose policies could not be applied fails **closed** (denies) rather\n * than leaking rows. One collection's policy failing (e.g. a rule that\n * references a table a real migration has not created yet) must not crash-loop\n * the whole deployment and take the other collections' working routes down with\n * it. Failures are reported loudly and per-table so the operator can see\n * exactly which collection is not yet servable and why.\n */\nimport { type CollectionConfig } from \"@rebasepro/types\";\nimport { planCollectionPolicies } from \"./generate-postgres-ddl-logic\";\nimport { readExistingSchema, type Queryable } from \"./ensure-collection-tables\";\n\nexport interface PolicyEnsureResult {\n /** `CREATE POLICY` statements that ran successfully. */\n policiesApplied: number;\n /** Tables that had RLS enabled. */\n tablesSecured: number;\n /** Declared tables absent from the database — left to a real migration. */\n skipped: { table: string; reason: string }[];\n /** Tables whose RLS could not be fully applied (fail closed). */\n failures: { table: string; error: string }[];\n}\n\nconst isCreatePolicy = (statement: string): boolean => /^\\s*CREATE POLICY/i.test(statement);\n\n/**\n * Bring the declared collections' RLS policies up to date. Returns what it did.\n *\n * Only tables that already exist are touched: the boot-time table creator runs\n * first, so anything still missing is a table this additive path is not allowed\n * to create (a junction, or a relation left to a migration). Enabling RLS on a\n * non-existent table would error, so those are recorded as skipped, not failed.\n */\nexport async function ensureCollectionPolicies(\n client: Queryable,\n collections: CollectionConfig[],\n log?: (message: string) => void\n): Promise<PolicyEnsureResult> {\n const result: PolicyEnsureResult = { policiesApplied: 0, tablesSecured: 0, skipped: [], failures: [] };\n\n const plans = planCollectionPolicies(collections);\n if (plans.length === 0) return result;\n\n const schemas = Array.from(new Set(plans.map(p => p.schema)));\n const existing = await readExistingSchema(client, schemas);\n\n for (const plan of plans) {\n if (!existing.tables.has(plan.qualified)) {\n result.skipped.push({\n table: plan.qualified,\n reason: \"table is not present in the database; create it with `rebase db push` / `rebase db migrate`\"\n });\n continue;\n }\n\n try {\n // Enable first: if a later policy statement fails, the table is left\n // locked (deny-all for the user role) rather than open.\n await client.query(plan.enableRls);\n result.tablesSecured++;\n\n let created = 0;\n for (const statement of plan.policyStatements) {\n await client.query(statement);\n if (isCreatePolicy(statement)) {\n result.policiesApplied++;\n created++;\n }\n }\n log?.(`${plan.qualified}: RLS enabled, ${created} policy(ies) applied`);\n } catch (err) {\n result.failures.push({\n table: plan.qualified,\n error: err instanceof Error ? err.message : String(err)\n });\n }\n }\n\n return result;\n}\n"],"mappings":";;;;;AAgDA,IAAM,kBAAkB,cAA+B,qBAAqB,KAAK,SAAS;;;;;;;;;AAU1F,eAAsB,yBAClB,QACA,aACA,KAC2B;CAC3B,MAAM,SAA6B;EAAE,iBAAiB;EAAG,eAAe;EAAG,SAAS,CAAC;EAAG,UAAU,CAAC;CAAE;CAErG,MAAM,QAAQ,uBAAuB,WAAW;CAChD,IAAI,MAAM,WAAW,GAAG,OAAO;CAG/B,MAAM,WAAW,MAAM,mBAAmB,QAD1B,MAAM,KAAK,IAAI,IAAI,MAAM,KAAI,MAAK,EAAE,MAAM,CAAC,CACT,CAAO;CAEzD,KAAK,MAAM,QAAQ,OAAO;EACtB,IAAI,CAAC,SAAS,OAAO,IAAI,KAAK,SAAS,GAAG;GACtC,OAAO,QAAQ,KAAK;IAChB,OAAO,KAAK;IACZ,QAAQ;GACZ,CAAC;GACD;EACJ;EAEA,IAAI;GAGA,MAAM,OAAO,MAAM,KAAK,SAAS;GACjC,OAAO;GAEP,IAAI,UAAU;GACd,KAAK,MAAM,aAAa,KAAK,kBAAkB;IAC3C,MAAM,OAAO,MAAM,SAAS;IAC5B,IAAI,eAAe,SAAS,GAAG;KAC3B,OAAO;KACP;IACJ;GACJ;GACA,MAAM,GAAG,KAAK,UAAU,iBAAiB,QAAQ,qBAAqB;EAC1E,SAAS,KAAK;GACV,OAAO,SAAS,KAAK;IACjB,OAAO,KAAK;IACZ,OAAO,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;GAC1D,CAAC;EACL;CACJ;CAEA,OAAO;AACX"}