@rebasepro/server-postgres 0.26.0 → 0.27.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/dist/{BranchService-CWBnDhcv.js → BranchService-B9Lu8e-P.js} +3 -3
- package/dist/{BranchService-CWBnDhcv.js.map → BranchService-B9Lu8e-P.js.map} +1 -1
- package/dist/PostgresBackendDriver.d.ts +7 -0
- package/dist/auth/services.d.ts +15 -1
- package/dist/{backup-cli-PoRG-zEq.js → backup-cli-BZM2Fj1I.js} +4 -4
- package/dist/backup-cli-BZM2Fj1I.js.map +1 -0
- package/dist/{boot-ddl-EsgqDkx0.js → boot-ddl-yukSebLA.js} +2 -2
- package/dist/{boot-ddl-EsgqDkx0.js.map → boot-ddl-yukSebLA.js.map} +1 -1
- package/dist/{cli-console-f0k6_TsJ.js → cli-console-BtzxzzvU.js} +5 -5
- package/dist/{cli-console-f0k6_TsJ.js.map → cli-console-BtzxzzvU.js.map} +1 -1
- package/dist/{cli-errors-DsYyNYzd.js → cli-errors-BBSJqlYX.js} +6 -6
- package/dist/{cli-errors-DsYyNYzd.js.map → cli-errors-BBSJqlYX.js.map} +1 -1
- package/dist/cli.js +30 -30
- package/dist/{column-plan-helpers-IG6uFb1s.js → column-plan-helpers-BeSztMor.js} +5 -1
- package/dist/{column-plan-helpers-IG6uFb1s.js.map → column-plan-helpers-BeSztMor.js.map} +1 -1
- package/dist/{deferred-index-build-CqaOv1Xx.js → deferred-index-build-DRnoMq-O.js} +5 -5
- package/dist/{deferred-index-build-CqaOv1Xx.js.map → deferred-index-build-DRnoMq-O.js.map} +1 -1
- package/dist/{doctor-DW_mlTzz.js → doctor-Cs6AtizY.js} +6 -6
- package/dist/{doctor-DW_mlTzz.js.map → doctor-Cs6AtizY.js.map} +1 -1
- package/dist/{ensure-collection-policies-DLWgabQ2.js → ensure-collection-policies-H8HN1Gbd.js} +7 -7
- package/dist/{ensure-collection-policies-DLWgabQ2.js.map → ensure-collection-policies-H8HN1Gbd.js.map} +1 -1
- package/dist/{ensure-collection-tables-CFIRq8ni.js → ensure-collection-tables-BeF1lArf.js} +7 -7
- package/dist/{ensure-collection-tables-CFIRq8ni.js.map → ensure-collection-tables-BeF1lArf.js.map} +1 -1
- package/dist/{ensure-tables-4nA-tfwi.js → ensure-tables-DDkNaPN2.js} +3 -3
- package/dist/{ensure-tables-4nA-tfwi.js.map → ensure-tables-DDkNaPN2.js.map} +1 -1
- package/dist/{enum-labels-kept-PcPW65xy.js → enum-labels-kept-B6loB2U_.js} +3 -3
- package/dist/{enum-labels-kept-PcPW65xy.js.map → enum-labels-kept-B6loB2U_.js.map} +1 -1
- package/dist/{generate-drizzle-schema-DC0BOUpn.js → generate-drizzle-schema-D_O8_iyT.js} +2 -2
- package/dist/{generate-drizzle-schema-DC0BOUpn.js.map → generate-drizzle-schema-D_O8_iyT.js.map} +1 -1
- package/dist/{generate-drizzle-schema-logic-CPzCRD-8.js → generate-drizzle-schema-logic-D0E64iwx.js} +2 -2
- package/dist/{generate-drizzle-schema-logic-CPzCRD-8.js.map → generate-drizzle-schema-logic-D0E64iwx.js.map} +1 -1
- package/dist/{generate-files-BP-4W_gm.js → generate-files-BpgyRwhU.js} +3 -3
- package/dist/{generate-files-BP-4W_gm.js.map → generate-files-BpgyRwhU.js.map} +1 -1
- package/dist/{generate-postgres-ddl-logic-DPl1oH_z.js → generate-postgres-ddl-logic-CogQBrzs.js} +3 -3
- package/dist/{generate-postgres-ddl-logic-DPl1oH_z.js.map → generate-postgres-ddl-logic-CogQBrzs.js.map} +1 -1
- package/dist/{generated-schema-diff-eZCklRZQ.js → generated-schema-diff-X9NA2Vig.js} +2 -2
- package/dist/{generated-schema-diff-eZCklRZQ.js.map → generated-schema-diff-X9NA2Vig.js.map} +1 -1
- package/dist/index.es.js +10 -10
- package/dist/{migrate-baseline-B-2Ef4Mv.js → migrate-baseline-Bfk1LGC6.js} +2 -2
- package/dist/{migrate-baseline-B-2Ef4Mv.js.map → migrate-baseline-Bfk1LGC6.js.map} +1 -1
- package/dist/{migrate-policy-stamps-BQtFHApx.js → migrate-policy-stamps-DHxwcawC.js} +6 -6
- package/dist/{migrate-policy-stamps-BQtFHApx.js.map → migrate-policy-stamps-DHxwcawC.js.map} +1 -1
- package/dist/{open-rebase-C8jQ6s5a.js → open-rebase-DZ5JbZpg.js} +272 -24
- package/dist/open-rebase-DZ5JbZpg.js.map +1 -0
- package/dist/{pg-error-utils-DhiUTlVx.js → pg-error-utils-BueZEJ0S.js} +2 -2
- package/dist/{pg-error-utils-DhiUTlVx.js.map → pg-error-utils-BueZEJ0S.js.map} +1 -1
- package/dist/{plan-schema-Czf3q4-Q.js → plan-schema-YagMlmNE.js} +2 -2
- package/dist/{plan-schema-Czf3q4-Q.js.map → plan-schema-YagMlmNE.js.map} +1 -1
- package/dist/{policy-drift-X4A-xAzv.js → policy-drift-Dqp_yFeE.js} +2 -2
- package/dist/{policy-drift-X4A-xAzv.js.map → policy-drift-Dqp_yFeE.js.map} +1 -1
- package/dist/{push-index-prebuild-UTvB5pqH.js → push-index-prebuild-hVRrfTi-.js} +4 -4
- package/dist/{push-index-prebuild-UTvB5pqH.js.map → push-index-prebuild-hVRrfTi-.js.map} +1 -1
- package/dist/{push-kept-defaults-BGOlOqRQ.js → push-kept-defaults-M_ZCcXuy.js} +3 -3
- package/dist/{push-kept-defaults-BGOlOqRQ.js.map → push-kept-defaults-M_ZCcXuy.js.map} +1 -1
- package/dist/{push-legacy-renames-BwaKi8xF.js → push-legacy-renames-DcoAWmGt.js} +4 -4
- package/dist/{push-legacy-renames-BwaKi8xF.js.map → push-legacy-renames-DcoAWmGt.js.map} +1 -1
- package/dist/{push-policy-plan-DQ2tWceD.js → push-policy-plan-Bq1bcb3Y.js} +4 -4
- package/dist/{push-policy-plan-DQ2tWceD.js.map → push-policy-plan-Bq1bcb3Y.js.map} +1 -1
- package/dist/{render-ddl-4v88y-Gv.js → render-ddl-D5jeXKR-.js} +2 -2
- package/dist/{render-ddl-4v88y-Gv.js.map → render-ddl-D5jeXKR-.js.map} +1 -1
- package/dist/schema/doctor-cli.js +3 -3
- package/dist/schema/generate-drizzle-schema.js +1 -1
- package/dist/schema/generate-postgres-ddl.js +1 -1
- package/dist/schema/introspect-db.js +1 -1
- package/dist/services/channel-bus/PostgresChannelBus.d.ts +1 -0
- package/dist/services/realtimeService.d.ts +30 -1
- package/dist/{websocket-CKYc3V4N.js → websocket-C9Fx7iSx.js} +32 -6
- package/dist/websocket-C9Fx7iSx.js.map +1 -0
- package/package.json +7 -7
- package/dist/backup-cli-PoRG-zEq.js.map +0 -1
- package/dist/open-rebase-C8jQ6s5a.js.map +0 -1
- package/dist/websocket-CKYc3V4N.js.map +0 -1
|
@@ -1,12 +1,12 @@
|
|
|
1
1
|
import { createRequire as __createRequire } from "module";
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
3
|
import { c as pinSearchPath } from "./connection-czvI7TZL.js";
|
|
4
|
-
import { B as withAppClient } from "./cli-errors-
|
|
4
|
+
import { B as withAppClient } from "./cli-errors-BBSJqlYX.js";
|
|
5
5
|
import { a as outWarn, r as out, t as chalk } from "./source-fZb92pN8.js";
|
|
6
|
-
import { s as planCollectionPolicies } from "./generate-postgres-ddl-logic-
|
|
7
|
-
import { n as loadCollections } from "./doctor-
|
|
8
|
-
import { policyStampSql, probeRenderedPolicies, readPolicyStamps } from "./ensure-collection-policies-
|
|
9
|
-
import { underSearchPath } from "./push-policy-plan-
|
|
6
|
+
import { s as planCollectionPolicies } from "./generate-postgres-ddl-logic-CogQBrzs.js";
|
|
7
|
+
import { n as loadCollections } from "./doctor-Cs6AtizY.js";
|
|
8
|
+
import { policyStampSql, probeRenderedPolicies, readPolicyStamps } from "./ensure-collection-policies-H8HN1Gbd.js";
|
|
9
|
+
import { underSearchPath } from "./push-policy-plan-Bq1bcb3Y.js";
|
|
10
10
|
import path from "path";
|
|
11
11
|
//#region src/schema/migrate-policy-stamps.ts
|
|
12
12
|
/**
|
|
@@ -86,4 +86,4 @@ async function stampPoliciesStoredAsRendered(client, collections, options = {})
|
|
|
86
86
|
//#endregion
|
|
87
87
|
export { stampMigratedPolicies };
|
|
88
88
|
|
|
89
|
-
//# sourceMappingURL=migrate-policy-stamps-
|
|
89
|
+
//# sourceMappingURL=migrate-policy-stamps-DHxwcawC.js.map
|
package/dist/{migrate-policy-stamps-BQtFHApx.js.map → migrate-policy-stamps-DHxwcawC.js.map}
RENAMED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"migrate-policy-stamps-
|
|
1
|
+
{"version":3,"file":"migrate-policy-stamps-DHxwcawC.js","names":[],"sources":["../src/schema/migrate-policy-stamps.ts"],"sourcesContent":["/**\n * The stamps `rebase db migrate` leaves on the policies it applied.\n *\n * A boot leaves a table's policies alone only when each carries the stamp a\n * boot or a push writes (`COMMENT ON POLICY … IS 'rebase:<hash>'`, see\n * `policyStampSql`). `db push` stamps what `policies.sql` just created. A\n * migration runs the same statements — `db generate` appends `policies.sql` to\n * it — and stamped nothing, so the first boot after every migrate dropped and\n * re-created every policy once, an ACCESS EXCLUSIVE lock per table: 44 on the\n * blog scaffold.\n *\n * Migrate cannot stamp what the files hold, the way push stamps what it just\n * ran: a migration was written from the collections of its day, and the\n * database may hold something a later one, or a hand, made since. A stamp\n * there would tell the boot a policy is what the rule makes when it is not, and\n * the boot would never put it right. So each declared policy without a current\n * stamp is asked of Postgres instead, as `db push --dry-run` asks it\n * (`probeRenderedPolicies`): made again from its rule under a probe name, in a\n * transaction that is rolled back, and compared. Only a policy whose stored\n * definition is exactly what its rule makes is stamped. Any other keeps no\n * stamp, and the boot re-applies its table, as before.\n */\nimport path from \"path\";\nimport chalk from \"chalk\";\nimport type { CollectionConfig } from \"@rebasepro/types\";\nimport type { Queryable } from \"../security/policy-drift\";\nimport { withAppClient } from \"../cli-helpers\";\nimport { out, outWarn } from \"../cli-output\";\nimport { pinSearchPath } from \"../connection\";\nimport { planCollectionPolicies } from \"./generate-postgres-ddl-logic\";\nimport { policyStampSql, probeRenderedPolicies, readPolicyStamps } from \"./ensure-collection-policies\";\nimport { underSearchPath } from \"./push-policy-plan\";\nimport { loadCollections } from \"./doctor\";\n\n/**\n * `rebase db migrate`'s last step: stamp what the migration left as its rules\n * make it, on this process's connection. Never fatal — a policy left\n * unstamped costs the next boot a re-apply of its table, which is what every\n * boot after a migrate did before this.\n */\nexport async function stampMigratedPolicies(databaseUrl: string, collectionsPath: string): Promise<void> {\n try {\n const collections = await loadCollections(path.resolve(process.cwd(), collectionsPath));\n // The rule the boot's connections follow: `search_path=public` unless\n // the URL pins one of its own, in which case this connection has it too.\n const searchPath = pinSearchPath(databaseUrl) === databaseUrl ? undefined : \"public\";\n const { stamped } = await withAppClient(databaseUrl, client => stampPoliciesStoredAsRendered(\n { query: async (text, values) => ({ rows: (await client.query(text, values)).rows }) },\n collections,\n { searchPath }\n ));\n if (stamped > 0) {\n out(chalk.gray(` ✓ Stamped ${stamped} RLS ${stamped === 1 ? \"policy\" : \"policies\"} as their rules make them, so the next boot leaves ${stamped === 1 ? \"it\" : \"them\"} alone.`));\n }\n } catch (err) {\n outWarn(chalk.yellow(` ⚠️ The policies could not be stamped (${err instanceof Error ? err.message : String(err)}); the next boot applies them again.`));\n }\n}\n\n/**\n * Stamp every declared policy whose stored definition its rule would store\n * as it is, and none other.\n *\n * @param options.searchPath the `search_path` a boot reads policies under,\n * when the connection's own differs — the stamp hashes `pg_get_expr`,\n * whose spelling depends on it. See `PolicyStamping.searchPath`.\n * @returns how many policies were stamped.\n */\nexport async function stampPoliciesStoredAsRendered(\n client: Queryable,\n collections: CollectionConfig[],\n options: { searchPath?: string } = {}\n): Promise<{ stamped: number }> {\n const plans = planCollectionPolicies(collections);\n if (plans.length === 0) return { stamped: 0 };\n\n const states = await underSearchPath(client, options.searchPath, () => readPolicyStamps(client, collections));\n const unsure: { schema: string; table: string; name: string }[] = [];\n for (const plan of plans) {\n for (const [name, state] of states.get(plan.qualified) ?? []) {\n if (state !== \"current\") unsure.push({ schema: plan.schema, table: plan.table, name });\n }\n }\n if (unsure.length === 0) return { stamped: 0 };\n\n const confirmed = await probeRenderedPolicies(client, collections, unsure, { searchPath: options.searchPath });\n const statements: string[] = [];\n let stamped = 0;\n for (const plan of plans) {\n const names = new Set(unsure\n .filter(p => p.schema === plan.schema && p.table === plan.table\n && confirmed.get(`${p.schema}.${p.table}.${p.name}`) === true)\n .map(p => p.name));\n const statement = names.size > 0 ? policyStampSql(plan, names) : undefined;\n if (!statement) continue;\n statements.push(statement);\n stamped += names.size;\n }\n if (statements.length === 0) return { stamped: 0 };\n\n await underSearchPath(client, options.searchPath, async () => {\n for (const statement of statements) await client.query(statement);\n });\n return { stamped };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwCA,eAAsB,sBAAsB,aAAqB,iBAAwC;CACrG,IAAI;EACA,MAAM,cAAc,MAAM,gBAAgB,KAAK,QAAQ,QAAQ,IAAI,GAAG,eAAe,CAAC;EAGtF,MAAM,aAAa,cAAc,WAAW,MAAM,cAAc,KAAA,IAAY;EAC5E,MAAM,EAAE,YAAY,MAAM,cAAc,cAAa,WAAU,8BAC3D,EAAE,OAAO,OAAO,MAAM,YAAY,EAAE,OAAO,MAAM,OAAO,MAAM,MAAM,MAAM,EAAA,CAAG,KAAK,GAAG,GACrF,aACA,EAAE,WAAW,CACjB,CAAC;EACD,IAAI,UAAU,GACV,IAAI,MAAM,KAAK,eAAe,QAAQ,OAAO,YAAY,IAAI,WAAW,WAAW,qDAAqD,YAAY,IAAI,OAAO,OAAO,QAAQ,CAAC;CAEvL,SAAS,KAAK;EACV,QAAQ,MAAM,OAAO,4CAA4C,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG,EAAE,qCAAqC,CAAC;CAC5J;AACJ;;;;;;;;;;AAWA,eAAsB,8BAClB,QACA,aACA,UAAmC,CAAC,GACR;CAC5B,MAAM,QAAQ,uBAAuB,WAAW;CAChD,IAAI,MAAM,WAAW,GAAG,OAAO,EAAE,SAAS,EAAE;CAE5C,MAAM,SAAS,MAAM,gBAAgB,QAAQ,QAAQ,kBAAkB,iBAAiB,QAAQ,WAAW,CAAC;CAC5G,MAAM,SAA4D,CAAC;CACnE,KAAK,MAAM,QAAQ,OACf,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,IAAI,KAAK,SAAS,KAAK,CAAC,GACvD,IAAI,UAAU,WAAW,OAAO,KAAK;EAAE,QAAQ,KAAK;EAAQ,OAAO,KAAK;EAAO;CAAK,CAAC;CAG7F,IAAI,OAAO,WAAW,GAAG,OAAO,EAAE,SAAS,EAAE;CAE7C,MAAM,YAAY,MAAM,sBAAsB,QAAQ,aAAa,QAAQ,EAAE,YAAY,QAAQ,WAAW,CAAC;CAC7G,MAAM,aAAuB,CAAC;CAC9B,IAAI,UAAU;CACd,KAAK,MAAM,QAAQ,OAAO;EACtB,MAAM,QAAQ,IAAI,IAAI,OACjB,QAAO,MAAK,EAAE,WAAW,KAAK,UAAU,EAAE,UAAU,KAAK,SACnD,UAAU,IAAI,GAAG,EAAE,OAAO,GAAG,EAAE,MAAM,GAAG,EAAE,MAAM,MAAM,IAAI,CAAC,CACjE,KAAI,MAAK,EAAE,IAAI,CAAC;EACrB,MAAM,YAAY,MAAM,OAAO,IAAI,eAAe,MAAM,KAAK,IAAI,KAAA;EACjE,IAAI,CAAC,WAAW;EAChB,WAAW,KAAK,SAAS;EACzB,WAAW,MAAM;CACrB;CACA,IAAI,WAAW,WAAW,GAAG,OAAO,EAAE,SAAS,EAAE;CAEjD,MAAM,gBAAgB,QAAQ,QAAQ,YAAY,YAAY;EAC1D,KAAK,MAAM,aAAa,YAAY,MAAM,OAAO,MAAM,SAAS;CACpE,CAAC;CACD,OAAO,EAAE,QAAQ;AACrB"}
|
|
@@ -2,22 +2,22 @@ import { createRequire as __createRequire } from "module";
|
|
|
2
2
|
__createRequire(import.meta.url);
|
|
3
3
|
import { i as createPostgresDatabaseConnection } from "./connection-czvI7TZL.js";
|
|
4
4
|
import { _ as visibleColumnProjection, a as buildSearchColumnSpec, r as SEARCH_UNACCENT_FN, s as hiddenColumnsOption } from "./search-column-BM-GV6vH.js";
|
|
5
|
-
import { a as diagnoseDbError, c as isEconnrefused, n as closedDatabaseName, r as deepestErrorMessage, rt as extractCauseMessage, u as parseHostInfo } from "./cli-errors-
|
|
6
|
-
import { a as pgErrorToFriendlyMessage, i as isRowLevelSecurityDenial, n as extractPgError, o as reachedDatabase, r as isRoleSwitchingPermissionError, s as sanitizeErrorForClient, t as classifyConnectFailure } from "./pg-error-utils-
|
|
7
|
-
import { t as BranchService } from "./BranchService-
|
|
5
|
+
import { a as diagnoseDbError, c as isEconnrefused, n as closedDatabaseName, r as deepestErrorMessage, rt as extractCauseMessage, u as parseHostInfo } from "./cli-errors-BBSJqlYX.js";
|
|
6
|
+
import { a as pgErrorToFriendlyMessage, i as isRowLevelSecurityDenial, n as extractPgError, o as reachedDatabase, r as isRoleSwitchingPermissionError, s as sanitizeErrorForClient, t as classifyConnectFailure } from "./pg-error-utils-BueZEJ0S.js";
|
|
7
|
+
import { t as BranchService } from "./BranchService-B9Lu8e-P.js";
|
|
8
8
|
import { a as ensureAppRoleGrants, c as revokeUserRoleSql, d as warnOnAnonymousGrants, f as warnOnLegacyRlsFunctions, i as ensureAppRole, n as applyAuthContext, o as findExposedInternalTables, p as warnOnRoleSchemaCollision, r as detectConnectionPosture, t as REBASE_USER_ROLE$1, u as validatePolicyPgRoles } from "./rls-enforcement-BOHuHVlc.js";
|
|
9
|
-
import { u as resolveColumnName } from "./column-plan-helpers-
|
|
9
|
+
import { u as resolveColumnName } from "./column-plan-helpers-BeSztMor.js";
|
|
10
10
|
import { t as AUTH_USERS_COLUMNS } from "./auth-users-columns-C72EMoDJ.js";
|
|
11
|
-
import { n as planSchema } from "./plan-schema-
|
|
12
|
-
import { t as generateSchema } from "./generate-drizzle-schema-logic-
|
|
13
|
-
import { r as renderPgType } from "./render-ddl-
|
|
14
|
-
import { u as typesAgree } from "./deferred-index-build-
|
|
15
|
-
import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, n as BOOT_LOCK_TIMEOUT_MS } from "./boot-ddl-
|
|
16
|
-
import { a as readSchemaFactsFor, r as planCollectionSchemaEnsure } from "./ensure-collection-tables-
|
|
11
|
+
import { n as planSchema } from "./plan-schema-YagMlmNE.js";
|
|
12
|
+
import { t as generateSchema } from "./generate-drizzle-schema-logic-D0E64iwx.js";
|
|
13
|
+
import { r as renderPgType } from "./render-ddl-D5jeXKR-.js";
|
|
14
|
+
import { u as typesAgree } from "./deferred-index-build-DRnoMq-O.js";
|
|
15
|
+
import { a as isLockTimeout, c as resolveBootLockOptions, l as sleep, n as BOOT_LOCK_TIMEOUT_MS } from "./boot-ddl-yukSebLA.js";
|
|
16
|
+
import { a as readSchemaFactsFor, r as planCollectionSchemaEnsure } from "./ensure-collection-tables-BeF1lArf.js";
|
|
17
17
|
import { a as mergeDatabaseBranch, i as diffDatabaseBranch } from "./branch-diff-CxE4VlxT.js";
|
|
18
18
|
import { t as DatabasePoolManager } from "./databasePoolManager-3stMNFL-.js";
|
|
19
|
-
import { a as resolveAuthSchema, i as probeAuthSchema, r as assertAuthSchemaCompatible, t as ensureAuthTablesExist } from "./ensure-tables-
|
|
20
|
-
import { a as buildBaasSchema, c as introspectSchema, i as warnOnGeneratedSchemaDrift, l as readRlsStatus, n as diffGeneratedSchemaAgainstCatalogue, o as readCatalogueSchema, s as buildCollectionsFromSchema } from "./generated-schema-diff-
|
|
19
|
+
import { a as resolveAuthSchema, i as probeAuthSchema, r as assertAuthSchemaCompatible, t as ensureAuthTablesExist } from "./ensure-tables-DDkNaPN2.js";
|
|
20
|
+
import { a as buildBaasSchema, c as introspectSchema, i as warnOnGeneratedSchemaDrift, l as readRlsStatus, n as diffGeneratedSchemaAgainstCatalogue, o as readCatalogueSchema, s as buildCollectionsFromSchema } from "./generated-schema-diff-X9NA2Vig.js";
|
|
21
21
|
import { Client, DatabaseError, Pool } from "pg";
|
|
22
22
|
import { drizzle } from "drizzle-orm/node-postgres";
|
|
23
23
|
import { ApiError, assertQueryFieldsReadable, createDdlBootstrapper, createEmailService, logger, rawQueryLoggingEnabled, resolveBatchRefs, rowETag, splitFieldOps } from "@rebasepro/server";
|
|
@@ -9523,6 +9523,7 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
9523
9523
|
get admin() {
|
|
9524
9524
|
return {
|
|
9525
9525
|
executeSql: (...args) => this.executeSql(...args),
|
|
9526
|
+
probe: (timeoutMs) => this.probe(timeoutMs),
|
|
9526
9527
|
runSqlScript: (...args) => this.runSqlScript(...args),
|
|
9527
9528
|
openSqlCursor: (...args) => this.openSqlCursor(...args),
|
|
9528
9529
|
fetchAvailableDatabases: () => this.fetchAvailableDatabases(),
|
|
@@ -10809,6 +10810,32 @@ var PostgresBackendDriver = class PostgresBackendDriver {
|
|
|
10809
10810
|
return options?.maxResultBytes === void 0 ? rows : refuseOversizedRows(rows, options.maxResultBytes);
|
|
10810
10811
|
}
|
|
10811
10812
|
/**
|
|
10813
|
+
* `SQLAdmin.probe`: `SELECT 1` on a connection opened for it, outside the
|
|
10814
|
+
* pool, so a pool whose connections are all serving slow requests does not
|
|
10815
|
+
* read as a database that is down. Without a pg pool (PGlite) there is no
|
|
10816
|
+
* queue to bypass, and the query runs like any other.
|
|
10817
|
+
*/
|
|
10818
|
+
async probe(timeoutMs) {
|
|
10819
|
+
const pool = "$client" in this.db ? this.db.$client : void 0;
|
|
10820
|
+
if (!(pool instanceof Pool)) {
|
|
10821
|
+
await this.db.execute(sql.raw("SELECT 1"));
|
|
10822
|
+
return;
|
|
10823
|
+
}
|
|
10824
|
+
const client = new Client({
|
|
10825
|
+
...pool.options,
|
|
10826
|
+
connectionTimeoutMillis: timeoutMs,
|
|
10827
|
+
query_timeout: timeoutMs,
|
|
10828
|
+
statement_timeout: timeoutMs
|
|
10829
|
+
});
|
|
10830
|
+
client.on("error", () => {});
|
|
10831
|
+
try {
|
|
10832
|
+
await client.connect();
|
|
10833
|
+
await client.query("SELECT 1");
|
|
10834
|
+
} finally {
|
|
10835
|
+
await client.end().catch(() => {});
|
|
10836
|
+
}
|
|
10837
|
+
}
|
|
10838
|
+
/**
|
|
10812
10839
|
* Run a script a person wrote — the Studio console — and describe its
|
|
10813
10840
|
* result. See `SQLAdmin.runSqlScript` and `services/sql-script.ts`.
|
|
10814
10841
|
*/
|
|
@@ -13313,6 +13340,7 @@ var PostgresChannelBus = class {
|
|
|
13313
13340
|
connectionString;
|
|
13314
13341
|
kind = "postgres";
|
|
13315
13342
|
maxFrameBytes = PG_NOTIFY_MAX_PAYLOAD_BYTES;
|
|
13343
|
+
publishesOnDemand = true;
|
|
13316
13344
|
listener;
|
|
13317
13345
|
batchWindowMs;
|
|
13318
13346
|
/**
|
|
@@ -13495,6 +13523,15 @@ function coerceFrame(value) {
|
|
|
13495
13523
|
from: typeof obj.from === "string" ? obj.from : void 0,
|
|
13496
13524
|
seq: obj.seq
|
|
13497
13525
|
};
|
|
13526
|
+
case "channels": return {
|
|
13527
|
+
kind: "channels",
|
|
13528
|
+
sid,
|
|
13529
|
+
channel,
|
|
13530
|
+
add: Array.isArray(obj.add) ? obj.add.filter((c) => typeof c === "string") : void 0,
|
|
13531
|
+
list: Array.isArray(obj.list) ? obj.list.filter((c) => typeof c === "string") : void 0,
|
|
13532
|
+
done: obj.done === true,
|
|
13533
|
+
hello: obj.hello === true
|
|
13534
|
+
};
|
|
13498
13535
|
case "presence_diff": return {
|
|
13499
13536
|
kind: "presence_diff",
|
|
13500
13537
|
sid,
|
|
@@ -13772,6 +13809,17 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
13772
13809
|
*/
|
|
13773
13810
|
bus = new MemoryChannelBus();
|
|
13774
13811
|
/**
|
|
13812
|
+
* The other instances on an on-demand bus, and the channels each serves
|
|
13813
|
+
* (`null`: it hasn't said, so assume all of them). See {@link hasRemoteMembers}.
|
|
13814
|
+
*/
|
|
13815
|
+
busPeers = /* @__PURE__ */ new Map();
|
|
13816
|
+
/** Frames the bus took, by kind. See {@link counts}. */
|
|
13817
|
+
busFramesPublished = /* @__PURE__ */ new Map();
|
|
13818
|
+
/** Frames not sent because no other instance had members. See {@link counts}. */
|
|
13819
|
+
busFramesSkipped = 0;
|
|
13820
|
+
busStartedAt = 0;
|
|
13821
|
+
busGossipInterval;
|
|
13822
|
+
/**
|
|
13775
13823
|
* The shared presence roster, present only when a real bus is active.
|
|
13776
13824
|
*
|
|
13777
13825
|
* Fan-out alone is not enough for presence: `presence_state` has to answer
|
|
@@ -15427,7 +15475,10 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
15427
15475
|
}
|
|
15428
15476
|
/** Join a broadcast channel */
|
|
15429
15477
|
joinChannel(clientId, channel) {
|
|
15430
|
-
if (!this.channels.has(channel))
|
|
15478
|
+
if (!this.channels.has(channel)) {
|
|
15479
|
+
this.channels.set(channel, /* @__PURE__ */ new Set());
|
|
15480
|
+
this.announceChannel(channel);
|
|
15481
|
+
}
|
|
15431
15482
|
this.channels.get(channel).add(clientId);
|
|
15432
15483
|
this.indexClientChannel(this.channelsByClient, clientId, channel);
|
|
15433
15484
|
this.warnIfMemoryBusOnMultiplePods();
|
|
@@ -15608,6 +15659,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
15608
15659
|
return;
|
|
15609
15660
|
}
|
|
15610
15661
|
this.bus = bus;
|
|
15662
|
+
this.startBusGossip();
|
|
15611
15663
|
try {
|
|
15612
15664
|
const store = new ChannelPresenceStore(this.db, this.instanceId);
|
|
15613
15665
|
if (!await store.ensureTables({ provision: options.provision }) && options.provision === false) throw new Error("rebase.channel_presence does not exist, and this backend changes nothing in its database. A provisioning run with the same channel bus configured creates it.");
|
|
@@ -15632,6 +15684,10 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
15632
15684
|
*/
|
|
15633
15685
|
publishBroadcast(clientId, channel, event, payload, seq) {
|
|
15634
15686
|
if (this.bus.kind === "memory") return;
|
|
15687
|
+
if (seq === void 0 && !this.hasRemoteMembers(channel)) {
|
|
15688
|
+
this.busFramesSkipped++;
|
|
15689
|
+
return;
|
|
15690
|
+
}
|
|
15635
15691
|
const frame = {
|
|
15636
15692
|
kind: "broadcast",
|
|
15637
15693
|
sid: this.instanceId,
|
|
@@ -15660,6 +15716,7 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
15660
15716
|
async publishFrame(frame) {
|
|
15661
15717
|
try {
|
|
15662
15718
|
await this.bus.publish(frame);
|
|
15719
|
+
this.busFramesPublished.set(frame.kind, (this.busFramesPublished.get(frame.kind) ?? 0) + 1);
|
|
15663
15720
|
} catch (error) {
|
|
15664
15721
|
logger.error("❌ [ChannelBus] Failed to publish frame — other instances did not receive it", {
|
|
15665
15722
|
detail: `${frame.kind} on "${frame.channel}"`,
|
|
@@ -15692,6 +15749,11 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
15692
15749
|
* its own `sid`.
|
|
15693
15750
|
*/
|
|
15694
15751
|
async handleBusFrame(frame) {
|
|
15752
|
+
if (frame.sid !== this.instanceId) this.notePeer(frame.sid);
|
|
15753
|
+
if (frame.kind === "channels") {
|
|
15754
|
+
if (frame.sid !== this.instanceId) this.readPeerChannels(frame);
|
|
15755
|
+
return;
|
|
15756
|
+
}
|
|
15695
15757
|
const retained = (frame.kind === "broadcast" || frame.kind === "broadcast_ref") && frame.seq !== void 0;
|
|
15696
15758
|
if (frame.sid === this.instanceId && !(retained && this.bus instanceof PostgresChannelBus)) return;
|
|
15697
15759
|
if (!retained) return this.deliverBusFrame(frame);
|
|
@@ -15868,6 +15930,10 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
15868
15930
|
/** Tell the other instances about a presence change. */
|
|
15869
15931
|
publishPresenceDiff(channel, joins, leaves) {
|
|
15870
15932
|
if (this.bus.kind === "memory") return;
|
|
15933
|
+
if (!this.hasRemoteMembers(channel)) {
|
|
15934
|
+
this.busFramesSkipped++;
|
|
15935
|
+
return;
|
|
15936
|
+
}
|
|
15871
15937
|
this.publishFrame({
|
|
15872
15938
|
kind: "presence_diff",
|
|
15873
15939
|
sid: this.instanceId,
|
|
@@ -15876,6 +15942,110 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
15876
15942
|
leaves
|
|
15877
15943
|
});
|
|
15878
15944
|
}
|
|
15945
|
+
static BUS_GOSSIP_INTERVAL_MS = 15e3;
|
|
15946
|
+
static BUS_PEER_TTL_MS = 45e3;
|
|
15947
|
+
static BUS_WARMUP_MS = 6e4;
|
|
15948
|
+
/** The frames' `channel`: a transport drops a frame without one. */
|
|
15949
|
+
static BUS_PEERS_CHANNEL = "__peers";
|
|
15950
|
+
/** Whether a frame on `channel` may have a reader on another instance. */
|
|
15951
|
+
hasRemoteMembers(channel) {
|
|
15952
|
+
if (!this.bus.publishesOnDemand) return true;
|
|
15953
|
+
const now = Date.now();
|
|
15954
|
+
if (now - this.busStartedAt < RealtimeService.BUS_WARMUP_MS) return true;
|
|
15955
|
+
for (const [sid, peer] of this.busPeers) {
|
|
15956
|
+
if (now - peer.heardAt > RealtimeService.BUS_PEER_TTL_MS) {
|
|
15957
|
+
this.busPeers.delete(sid);
|
|
15958
|
+
continue;
|
|
15959
|
+
}
|
|
15960
|
+
if (peer.channels === null || peer.channels.has(channel)) return true;
|
|
15961
|
+
}
|
|
15962
|
+
return false;
|
|
15963
|
+
}
|
|
15964
|
+
/** Tell the others about a channel's first member here. */
|
|
15965
|
+
announceChannel(channel) {
|
|
15966
|
+
if (!this.bus.publishesOnDemand) return;
|
|
15967
|
+
if (!this.busPeers.size && Date.now() - this.busStartedAt >= RealtimeService.BUS_WARMUP_MS) return;
|
|
15968
|
+
this.publishFrame({
|
|
15969
|
+
kind: "channels",
|
|
15970
|
+
sid: this.instanceId,
|
|
15971
|
+
channel: RealtimeService.BUS_PEERS_CHANNEL,
|
|
15972
|
+
add: [channel]
|
|
15973
|
+
});
|
|
15974
|
+
}
|
|
15975
|
+
/** Every channel served here, in as many parts as the transport needs. */
|
|
15976
|
+
announceChannels() {
|
|
15977
|
+
if (!this.bus.publishesOnDemand) return;
|
|
15978
|
+
const channel = RealtimeService.BUS_PEERS_CHANNEL;
|
|
15979
|
+
const limit = Math.min(this.bus.maxFrameBytes, 7e3) - 200;
|
|
15980
|
+
let list = [], bytes = 0;
|
|
15981
|
+
for (const name of this.channels.keys()) {
|
|
15982
|
+
const size = Buffer.byteLength(name, "utf8") + 3;
|
|
15983
|
+
if (bytes + size > limit) {
|
|
15984
|
+
this.publishFrame({
|
|
15985
|
+
kind: "channels",
|
|
15986
|
+
sid: this.instanceId,
|
|
15987
|
+
channel,
|
|
15988
|
+
list
|
|
15989
|
+
});
|
|
15990
|
+
list = [];
|
|
15991
|
+
bytes = 0;
|
|
15992
|
+
}
|
|
15993
|
+
list.push(name);
|
|
15994
|
+
bytes += size;
|
|
15995
|
+
}
|
|
15996
|
+
this.publishFrame({
|
|
15997
|
+
kind: "channels",
|
|
15998
|
+
sid: this.instanceId,
|
|
15999
|
+
channel,
|
|
16000
|
+
list,
|
|
16001
|
+
done: true
|
|
16002
|
+
});
|
|
16003
|
+
}
|
|
16004
|
+
/** Any frame from another instance: it's alive, and a new one needs to hear what's served here. */
|
|
16005
|
+
notePeer(sid) {
|
|
16006
|
+
const peer = this.busPeers.get(sid);
|
|
16007
|
+
if (peer) {
|
|
16008
|
+
peer.heardAt = Date.now();
|
|
16009
|
+
return;
|
|
16010
|
+
}
|
|
16011
|
+
this.busPeers.set(sid, {
|
|
16012
|
+
heardAt: Date.now(),
|
|
16013
|
+
channels: null
|
|
16014
|
+
});
|
|
16015
|
+
this.announceChannels();
|
|
16016
|
+
}
|
|
16017
|
+
readPeerChannels(frame) {
|
|
16018
|
+
const peer = this.busPeers.get(frame.sid);
|
|
16019
|
+
if (!peer) return;
|
|
16020
|
+
if (frame.hello) this.announceChannels();
|
|
16021
|
+
if (frame.add) {
|
|
16022
|
+
peer.channels ??= /* @__PURE__ */ new Set();
|
|
16023
|
+
for (const channel of frame.add) peer.channels.add(channel);
|
|
16024
|
+
}
|
|
16025
|
+
if (frame.list) {
|
|
16026
|
+
peer.incoming ??= /* @__PURE__ */ new Set();
|
|
16027
|
+
for (const channel of frame.list) peer.incoming.add(channel);
|
|
16028
|
+
if (frame.done) {
|
|
16029
|
+
peer.channels = peer.incoming;
|
|
16030
|
+
peer.incoming = void 0;
|
|
16031
|
+
}
|
|
16032
|
+
}
|
|
16033
|
+
}
|
|
16034
|
+
/** Start gossiping on a bus that publishes on demand. */
|
|
16035
|
+
startBusGossip() {
|
|
16036
|
+
if (!this.bus.publishesOnDemand) return;
|
|
16037
|
+
this.busStartedAt = Date.now();
|
|
16038
|
+
this.publishFrame({
|
|
16039
|
+
kind: "channels",
|
|
16040
|
+
sid: this.instanceId,
|
|
16041
|
+
channel: RealtimeService.BUS_PEERS_CHANNEL,
|
|
16042
|
+
hello: true
|
|
16043
|
+
});
|
|
16044
|
+
this.busGossipInterval = setInterval(() => {
|
|
16045
|
+
if (this.busPeers.size) this.announceChannels();
|
|
16046
|
+
}, RealtimeService.BUS_GOSSIP_INTERVAL_MS);
|
|
16047
|
+
unref(this.busGossipInterval);
|
|
16048
|
+
}
|
|
15879
16049
|
/** Run a roster write when there is a roster, and never let it throw. */
|
|
15880
16050
|
async presenceStoreOp(op, label) {
|
|
15881
16051
|
if (!this.presenceStore) return;
|
|
@@ -15973,6 +16143,10 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
15973
16143
|
clearInterval(this.presenceSweepInterval);
|
|
15974
16144
|
this.presenceSweepInterval = void 0;
|
|
15975
16145
|
}
|
|
16146
|
+
if (this.busGossipInterval) {
|
|
16147
|
+
clearInterval(this.busGossipInterval);
|
|
16148
|
+
this.busGossipInterval = void 0;
|
|
16149
|
+
}
|
|
15976
16150
|
this.oversizedBroadcastWarned.clear();
|
|
15977
16151
|
if (this.presenceStore) {
|
|
15978
16152
|
try {
|
|
@@ -16006,6 +16180,15 @@ var RealtimeService = class RealtimeService extends EventEmitter {
|
|
|
16006
16180
|
setScopeRunner(run) {
|
|
16007
16181
|
this.runInScope = run;
|
|
16008
16182
|
}
|
|
16183
|
+
/** What this instance is carrying — see `RealtimeProvider.counts`. */
|
|
16184
|
+
counts() {
|
|
16185
|
+
return {
|
|
16186
|
+
sockets: this.clients.size,
|
|
16187
|
+
channels: this.channels.size,
|
|
16188
|
+
busFramesPublished: Object.fromEntries(this.busFramesPublished),
|
|
16189
|
+
busFramesSkipped: this.busFramesSkipped
|
|
16190
|
+
};
|
|
16191
|
+
}
|
|
16009
16192
|
/** The LISTEN connections this service depends on — see `RealtimeProvider.health`. */
|
|
16010
16193
|
health() {
|
|
16011
16194
|
const listeners = [];
|
|
@@ -17204,6 +17387,60 @@ var UserService = class {
|
|
|
17204
17387
|
};
|
|
17205
17388
|
}
|
|
17206
17389
|
/**
|
|
17390
|
+
* @see UserRepository.listGuests — what a guest is, as SQL. The list and the
|
|
17391
|
+
* delete both read this, so nothing can be listed for deletion that the
|
|
17392
|
+
* delete would not call a guest. A column name falls back to its physical
|
|
17393
|
+
* name and never to no condition: a table without the column fails the
|
|
17394
|
+
* statement rather than widening it.
|
|
17395
|
+
*/
|
|
17396
|
+
isGuest() {
|
|
17397
|
+
const users = sql.raw(this.getQualifiedUsersTableName());
|
|
17398
|
+
const column = (key, physical) => sql.identifier(getColumn(this.usersTable, key, physical)?.name ?? physical);
|
|
17399
|
+
const identities = sql.raw(qualifiedTableName(this.userIdentitiesTable));
|
|
17400
|
+
return sql`${users}.${column("isAnonymous", "is_anonymous")} = TRUE
|
|
17401
|
+
AND ${users}.${column("passwordHash", "password_hash")} IS NULL
|
|
17402
|
+
AND NOT EXISTS (SELECT 1 FROM ${identities} ui WHERE ui.uid = ${users}.${column("id", "id")})`;
|
|
17403
|
+
}
|
|
17404
|
+
/** @see UserRepository.listGuests */
|
|
17405
|
+
async listGuests(options) {
|
|
17406
|
+
const limit = options?.limit ?? 25;
|
|
17407
|
+
const offset = options?.offset ?? 0;
|
|
17408
|
+
const users = sql.raw(this.getQualifiedUsersTableName());
|
|
17409
|
+
const idColumn = sql.identifier(getColumn(this.usersTable, "id")?.name ?? "id");
|
|
17410
|
+
const createdAt = sql`${users}.${sql.identifier(getColumn(this.usersTable, "createdAt", "created_at")?.name ?? "created_at")}`;
|
|
17411
|
+
const lastSeenAt = sql`GREATEST(${createdAt}, (SELECT MAX(rt.created_at) FROM ${sql.raw(qualifiedTableName(this.refreshTokensTable))} rt WHERE rt.uid = ${users}.${idColumn}))`;
|
|
17412
|
+
const where = options?.lastSeenBefore ? sql`${this.isGuest()} AND ${lastSeenAt} < ${options.lastSeenBefore.toISOString()}::timestamptz` : this.isGuest();
|
|
17413
|
+
const counted = await this.db.execute(sql`SELECT count(*)::int AS total FROM ${users} WHERE ${where}`);
|
|
17414
|
+
return {
|
|
17415
|
+
guests: (await this.db.execute(sql`
|
|
17416
|
+
SELECT ${users}.${idColumn} AS id, ${createdAt} AS created_at, ${lastSeenAt} AS last_seen_at
|
|
17417
|
+
FROM ${users}
|
|
17418
|
+
WHERE ${where}
|
|
17419
|
+
ORDER BY last_seen_at ASC, id ASC
|
|
17420
|
+
LIMIT ${limit} OFFSET ${offset}
|
|
17421
|
+
`)).rows.map((row) => ({
|
|
17422
|
+
id: row.id,
|
|
17423
|
+
createdAt: new Date(row.created_at),
|
|
17424
|
+
lastSeenAt: new Date(row.last_seen_at)
|
|
17425
|
+
})),
|
|
17426
|
+
total: counted.rows[0].total
|
|
17427
|
+
};
|
|
17428
|
+
}
|
|
17429
|
+
/** @see UserRepository.deleteGuest */
|
|
17430
|
+
async deleteGuest(id) {
|
|
17431
|
+
const users = sql.raw(this.getQualifiedUsersTableName());
|
|
17432
|
+
const idColumn = sql.identifier(getColumn(this.usersTable, "id")?.name ?? "id");
|
|
17433
|
+
try {
|
|
17434
|
+
return (await this.withServerContext((db) => db.execute(sql`
|
|
17435
|
+
DELETE FROM ${users} WHERE ${users}.${idColumn} = ${id} AND ${this.isGuest()} RETURNING 1
|
|
17436
|
+
`))).rows.length > 0;
|
|
17437
|
+
} catch (error) {
|
|
17438
|
+
const code = extractPgError(error)?.code;
|
|
17439
|
+
if (code === "23503" || code === "23001") throw ApiError.conflict("A row of this project's own requires this guest, so it was not deleted.", "GUEST_REFERENCED");
|
|
17440
|
+
throw error;
|
|
17441
|
+
}
|
|
17442
|
+
}
|
|
17443
|
+
/**
|
|
17207
17444
|
* Update user's password hash; `null` removes the password.
|
|
17208
17445
|
*/
|
|
17209
17446
|
async updatePassword(id, passwordHash) {
|
|
@@ -17930,6 +18167,12 @@ var PostgresAuthRepository = class {
|
|
|
17930
18167
|
async listUsersPaginated(options) {
|
|
17931
18168
|
return this.userService.listUsersPaginated(options);
|
|
17932
18169
|
}
|
|
18170
|
+
async listGuests(options) {
|
|
18171
|
+
return this.userService.listGuests(options);
|
|
18172
|
+
}
|
|
18173
|
+
async deleteGuest(id) {
|
|
18174
|
+
return this.userService.deleteGuest(id);
|
|
18175
|
+
}
|
|
17933
18176
|
async firstUserIds(limit) {
|
|
17934
18177
|
return this.userService.firstUserIds(limit);
|
|
17935
18178
|
}
|
|
@@ -19321,6 +19564,7 @@ async function openPostgresDriver(pgConfig, config) {
|
|
|
19321
19564
|
const rlsStatus = await readRlsStatus(rawClient, pgSchemaName);
|
|
19322
19565
|
const unprotected = [...schema.tablesMap.keys()].filter((t) => !schema.joinTables.has(t) && !rlsStatus.get(t)?.rlsEnabled);
|
|
19323
19566
|
const policyless = [...schema.tablesMap.keys()].filter((t) => !schema.joinTables.has(t) && rlsStatus.get(t)?.rlsEnabled && rlsStatus.get(t)?.policyCount === 0);
|
|
19567
|
+
const unprotectedJoinTables = [...schema.joinTables].filter((t) => !rlsStatus.get(t)?.rlsEnabled);
|
|
19324
19568
|
if (unprotected.length > 0) if (unprotectedTables === "serve") logger.warn(`🔓 [rls] Serving ${unprotected.length} table(s) with row-level security DISABLED: ${unprotected.join(", ")}. Every authenticated request can read and write every row of these. This is baas.unprotectedTables: "serve".`);
|
|
19325
19569
|
else {
|
|
19326
19570
|
logger.warn(`🔒 [rls] Not serving ${unprotected.length} table(s) — row-level security is disabled, so they have no authorization model: ${unprotected.join(", ")}\n` + unprotected.map((t) => ` ALTER TABLE "${pgSchemaName}"."${t}" ENABLE ROW LEVEL SECURITY; -- then add a policy`).join("\n") + "\n To serve them without RLS anyway, pass baas: { unprotectedTables: \"serve\" } to the server entry: an option `rebase eject` gives you, which the managed runtime does not read from config/ or the environment.");
|
|
@@ -19330,6 +19574,10 @@ async function openPostgresDriver(pgConfig, config) {
|
|
|
19330
19574
|
table
|
|
19331
19575
|
}));
|
|
19332
19576
|
}
|
|
19577
|
+
if (unprotectedJoinTables.length > 0) {
|
|
19578
|
+
logger.warn(`🔒 [rls] ${unprotectedJoinTables.length} join table(s) have row-level security disabled: ${unprotectedJoinTables.join(", ")}. The API does not serve a join table, with RLS or without, but ${REBASE_USER_ROLE$1} keeps its grants on these, so SQL your own code runs as a caller reaches every row.`);
|
|
19579
|
+
for (const t of unprotectedJoinTables) schema.tablesMap.delete(t);
|
|
19580
|
+
}
|
|
19333
19581
|
if (policyless.length > 0) logger.warn(`🔒 [rls] ${policyless.length} table(s) have RLS enabled but no policies, so they will return no rows: ${policyless.join(", ")}`);
|
|
19334
19582
|
introspectedCollections = buildCollectionsFromSchema(schema, pgSchemaName);
|
|
19335
19583
|
({tables: introspectedTables, relations: introspectedRelations} = buildBaasSchema(schema.tablesMap, pgSchemaName, introspectedCollections));
|
|
@@ -19689,7 +19937,7 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
19689
19937
|
const openIndexBuildSession = (driverResult) => async () => {
|
|
19690
19938
|
const db = requireProvisioningDb(driverResult);
|
|
19691
19939
|
const pool = "$client" in db ? db.$client : void 0;
|
|
19692
|
-
const { isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-
|
|
19940
|
+
const { isPgPool, poolIndexBuildSession } = await import("./deferred-index-build-DRnoMq-O.js").then((n) => n.r);
|
|
19693
19941
|
if (isPgPool(pool)) return poolIndexBuildSession(pool)();
|
|
19694
19942
|
const queryable = provisioningQueryable(driverResult);
|
|
19695
19943
|
return {
|
|
@@ -19715,7 +19963,7 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
19715
19963
|
*/
|
|
19716
19964
|
const provisionRlsRuntime = async (driverResult) => {
|
|
19717
19965
|
const db = requireProvisioningDb(driverResult);
|
|
19718
|
-
const { RLS_BOOTSTRAP_STATEMENTS, rlsRuntimeIsCurrent } = await import("./migrate-baseline-
|
|
19966
|
+
const { RLS_BOOTSTRAP_STATEMENTS, rlsRuntimeIsCurrent } = await import("./migrate-baseline-Bfk1LGC6.js").then((n) => n.w);
|
|
19719
19967
|
const run = async (text) => sqlRows(await db.execute(sql.raw(text)));
|
|
19720
19968
|
if (await rlsRuntimeIsCurrent(run).catch(() => false)) return;
|
|
19721
19969
|
await db.transaction(async (tx) => {
|
|
@@ -19828,11 +20076,11 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
19828
20076
|
unavailable: historyUnavailableReason(state, { requireTransaction: false })
|
|
19829
20077
|
}) };
|
|
19830
20078
|
}
|
|
19831
|
-
const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-
|
|
20079
|
+
const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-yukSebLA.js").then((n) => n.i);
|
|
19832
20080
|
const historyTable = await ensureHistoryTableExists(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
|
|
19833
20081
|
const historyIndexes = await ensureHistoryIndexes(db, { lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS });
|
|
19834
20082
|
if (historyIndexes.length > 0) {
|
|
19835
|
-
const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-
|
|
20083
|
+
const { buildDeferredIndexes, scheduleDeferredIndexBuild } = await import("./deferred-index-build-DRnoMq-O.js").then((n) => n.r);
|
|
19836
20084
|
const indexOptions = {
|
|
19837
20085
|
log: (message) => logger.info(`[history] ${message}`),
|
|
19838
20086
|
lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS
|
|
@@ -19888,9 +20136,9 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
19888
20136
|
* proved it can bootstrap with.
|
|
19889
20137
|
*/
|
|
19890
20138
|
async ensureCollectionSchema(collections, driverResult, log) {
|
|
19891
|
-
const { ensureCollectionTables } = await import("./ensure-collection-tables-
|
|
20139
|
+
const { ensureCollectionTables } = await import("./ensure-collection-tables-BeF1lArf.js").then((n) => n.n);
|
|
19892
20140
|
const queryable = provisioningQueryable(driverResult);
|
|
19893
|
-
const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-
|
|
20141
|
+
const { BOOT_LOCK_TIMEOUT_MS } = await import("./boot-ddl-yukSebLA.js").then((n) => n.i);
|
|
19894
20142
|
const provisionOnly = ["1", "true"].includes((process.env.REBASE_PROVISION_ONLY ?? "").trim().toLowerCase());
|
|
19895
20143
|
const plan = await ensureCollectionTables(queryable, collections, log, {
|
|
19896
20144
|
lockTimeoutMs: BOOT_LOCK_TIMEOUT_MS,
|
|
@@ -19902,7 +20150,7 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
19902
20150
|
pendingIndexBuild?.cancel();
|
|
19903
20151
|
pendingIndexBuild = void 0;
|
|
19904
20152
|
if (!provisionOnly && plan.deferredIndexes.length > 0) {
|
|
19905
|
-
const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-
|
|
20153
|
+
const { scheduleDeferredIndexBuild } = await import("./deferred-index-build-DRnoMq-O.js").then((n) => n.r);
|
|
19906
20154
|
logger.info(`[schema] ${plan.deferredIndexes.length} index(es) are missing, or were left INVALID, on tables that already exist. They are built in the background once the server is serving, one at a time, without blocking reads or writes.`);
|
|
19907
20155
|
pendingIndexBuild = scheduleDeferredIndexBuild(openIndexBuildSession(driverResult), plan.deferredIndexes, {
|
|
19908
20156
|
log: (message) => logger.info(`[schema] ${message}`),
|
|
@@ -19942,7 +20190,7 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
19942
20190
|
await provisionRlsRuntime(driverResult);
|
|
19943
20191
|
},
|
|
19944
20192
|
async ensureCollectionPolicies(collections, driverResult, log) {
|
|
19945
|
-
const { ensureCollectionPolicies, describeRulesDropped } = await import("./ensure-collection-policies-
|
|
20193
|
+
const { ensureCollectionPolicies, describeRulesDropped } = await import("./ensure-collection-policies-H8HN1Gbd.js");
|
|
19946
20194
|
const queryable = provisioningQueryable(driverResult);
|
|
19947
20195
|
const { rows } = await queryable.query("SELECT to_regprocedure('rebase.roles()') IS NOT NULL AS present");
|
|
19948
20196
|
if (!rows[0]?.present) await provisionRlsRuntime(driverResult);
|
|
@@ -19967,7 +20215,7 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
19967
20215
|
for (const u of outcome.unsecured.filter((u) => u.grantWithdrawn)) logger.error(`🔐 [rls] Could not enable row-level security on "${u.table}": ${u.error}. Its privileges have been revoked from ${REBASE_USER_ROLE$1}, so the table is unreachable rather than unprotected. Reads and writes to that collection will fail until RLS can be enabled.`);
|
|
19968
20216
|
if (unrevoked.length > 0) throw new Error("Refusing to start: row-level security could not be enabled on " + unrevoked.map((u) => `"${u.table}" (${u.error})`).join(", ") + `, and the privileges granted to ${REBASE_USER_ROLE$1} could not be revoked either. The table would be served with no row filtering. Fix the database permissions (the connection role must own these tables, or be able to ALTER them) and boot again.`);
|
|
19969
20217
|
try {
|
|
19970
|
-
const { dropLegacyAuthSchema } = await import("./migrate-baseline-
|
|
20218
|
+
const { dropLegacyAuthSchema } = await import("./migrate-baseline-Bfk1LGC6.js").then((n) => n.w);
|
|
19971
20219
|
await dropLegacyAuthSchema(async (text) => (await queryable.query(text)).rows, {
|
|
19972
20220
|
info: (m) => logger.info(m),
|
|
19973
20221
|
warn: (m) => logger.warn(m)
|
|
@@ -20058,7 +20306,7 @@ function createPostgresBootstrapper(pgConfig) {
|
|
|
20058
20306
|
return driverResult.internals.driver.admin;
|
|
20059
20307
|
},
|
|
20060
20308
|
async initializeWebsockets(server, realtimeService, driver, config, adapter, limits) {
|
|
20061
|
-
const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-
|
|
20309
|
+
const { createPostgresWebSocket, isSocketRealtimeService, socketRealtimeMissing } = await import("./websocket-C9Fx7iSx.js").then((n) => n.c);
|
|
20062
20310
|
if (!isSocketRealtimeService(realtimeService)) throw new Error(`The realtime service handed to the Postgres socket cannot serve it — it has no ${socketRealtimeMissing(realtimeService).join(", ")}. Every socket would fail on its first frame.`);
|
|
20063
20311
|
const realtimeConfig = effectiveConfig().realtime;
|
|
20064
20312
|
const maxSocketsPerUser = realtimeConfig?.maxSocketsPerUser !== void 0 ? parseMaxSocketsPerUser(realtimeConfig.maxSocketsPerUser, "realtime.maxSocketsPerUser") : void 0;
|
|
@@ -20202,4 +20450,4 @@ async function openRebase(options) {
|
|
|
20202
20450
|
//#endregion
|
|
20203
20451
|
export { AuthenticatedPostgresBackendDriver as $, budgetSendBuffers as A, mfaFactors as B, PG_NOTIFY_MAX_PAYLOAD_BYTES as C, MemoryChannelBus as D, parseChannelBusPayload as E, createAuthSchema as F, recoveryCodesRelations as G, passwordResetTokens as H, magicLinkTokens as I, userIdentities as J, refreshTokens as K, magicLinkTokensRelations as L, terminateIfBacklogged as M, assertReadRequestReadable as N, frameByteLength as O, appConfig as P, usersSchema as Q, mfaChallenges as R, DEFAULT_BATCH_WINDOW_MS as S, parseChannelBusFrame as T, passwordResetTokensRelations as U, mfaFactorsRelations as V, recoveryCodes as W, users as X, userIdentitiesRelations as Y, usersRelations as Z, parseRealtimeTuning as _, listedColumnKeys as _t, openPostgresDriver as a, isRoleSwitchingOptedOut as at, resolveChannelBusSetting as b, resolveSourceUrls as c, SqlResultTooLargeError as ct, DEFAULT_RECOUNT_MIN_ROWS as d, DrizzleConditionBuilder as dt, CONNECTION_OWNER as et, PostgresRealtimeProvider as f, PostgresConditionBuilder as ft, parseMaxSubscriptionsPerSocket as g, joinColumn as gt, parseMaxSocketsPerUser as h, getUnknownFilterFieldsMode as ht, isScaffoldedLocalDatabase as i, effectiveSqlRole as it, reapSilentSockets as j, isChannelBusInstance$1 as k, PostgresCollectionRegistry as l, isNestedPath as lt, packEntityChanges as m, escapeLikePattern as mt, createPostgresBootstrapper as n, RoleSwitchUnavailableError as nt, postgresDriverConfigFromEnv as o, sqlRoleRanAs as ot, RealtimeService as p, configureUnknownFilterFields as pt, refreshTokensRelations as q, describeSchemaDriftCause as r, branchParentDatabase as rt, resolveDriftCheckName as s, SQL_RESULT_BYTE_BUDGET as st, openRebase as t, PostgresBackendDriver as tt, DEFAULT_MAX_SUBSCRIPTIONS_PER_SOCKET as u, resolveNestedPath as ut, refetchConcurrencyFor as v, PostgresChannelBus as w, CHANNEL_BUS_NOTIFY_CHANNEL as x, createChannelBus as y, mfaChallengesRelations as z };
|
|
20204
20452
|
|
|
20205
|
-
//# sourceMappingURL=open-rebase-
|
|
20453
|
+
//# sourceMappingURL=open-rebase-DZ5JbZpg.js.map
|