@rebasepro/server 0.31.0-canary.g902a0ce → 0.32.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 (123) hide show
  1. package/dist/{GCSStorageController-sCw2c4aA.js → GCSStorageController-B3p3aUX-.js} +5 -5
  2. package/dist/{GCSStorageController-sCw2c4aA.js.map → GCSStorageController-B3p3aUX-.js.map} +1 -1
  3. package/dist/{S3StorageController-DDAq8Kt5.js → S3StorageController-C9LjuMhL.js} +5 -5
  4. package/dist/{S3StorageController-DDAq8Kt5.js.map → S3StorageController-C9LjuMhL.js.map} +1 -1
  5. package/dist/{access-CSfmyM87.js → access-BxkEYQh1.js} +6 -6
  6. package/dist/{access-CSfmyM87.js.map → access-BxkEYQh1.js.map} +1 -1
  7. package/dist/{access-CCsVee6z.js → access-D1CTJSLK.js} +3 -1
  8. package/dist/access-D1CTJSLK.js.map +1 -0
  9. package/dist/api/errors.d.ts +4 -0
  10. package/dist/api/rest/api-generator.d.ts +8 -0
  11. package/dist/{auth-Blo1R8rc.js → auth-Bfwjg4Bg.js} +37 -13
  12. package/dist/auth-Bfwjg4Bg.js.map +1 -0
  13. package/dist/auth-secrets-BZUH9916.js +60 -0
  14. package/dist/auth-secrets-BZUH9916.js.map +1 -0
  15. package/dist/backend/create-backend.d.ts +6 -0
  16. package/dist/backend/options.d.ts +10 -0
  17. package/dist/backend/services.d.ts +9 -0
  18. package/dist/{backup-B-1oW6qX.js → backup-g2ohsDe0.js} +7 -7
  19. package/dist/{backup-B-1oW6qX.js.map → backup-g2ohsDe0.js.map} +1 -1
  20. package/dist/boot/bundle.d.ts +11 -1
  21. package/dist/boot/env.d.ts +5 -0
  22. package/dist/boot/security-headers.d.ts +15 -5
  23. package/dist/boot/static-routing.d.ts +58 -0
  24. package/dist/{branch-routes-0xhHXlGq.js → branch-routes-DtNtc0Vh.js} +3 -3
  25. package/dist/{branch-routes-0xhHXlGq.js.map → branch-routes-DtNtc0Vh.js.map} +1 -1
  26. package/dist/{contract-routes-WwMWHWS9.js → contract-routes-CZTlAP7p.js} +3 -3
  27. package/dist/{contract-routes-WwMWHWS9.js.map → contract-routes-CZTlAP7p.js.map} +1 -1
  28. package/dist/{cron-loader-BDN8plQK.js → cron-loader-BBP0kBIl.js} +2 -2
  29. package/dist/{cron-loader-BDN8plQK.js.map → cron-loader-BBP0kBIl.js.map} +1 -1
  30. package/dist/{cron-routes-Cqm5wQsK.js → cron-routes-Du03uJ7K.js} +5 -5
  31. package/dist/{cron-routes-Cqm5wQsK.js.map → cron-routes-Du03uJ7K.js.map} +1 -1
  32. package/dist/{cron-scheduler-DgrsqyQQ.js → cron-scheduler-CopTWKYB.js} +2 -2
  33. package/dist/{cron-scheduler-DgrsqyQQ.js.map → cron-scheduler-CopTWKYB.js.map} +1 -1
  34. package/dist/{cron-store-91cd9Qzv.js → cron-store-FGaZOdMf.js} +3 -3
  35. package/dist/{cron-store-91cd9Qzv.js.map → cron-store-FGaZOdMf.js.map} +1 -1
  36. package/dist/dist-C1vNURUy.js +19354 -0
  37. package/dist/dist-C1vNURUy.js.map +1 -0
  38. package/dist/{errors-DpTMfX77.js → errors-NVbAQU25.js} +5 -1
  39. package/dist/errors-NVbAQU25.js.map +1 -0
  40. package/dist/{filter-dialect-DAVl1Nsm.js → filter-dialect-XtPJOCbD.js} +2 -2
  41. package/dist/{filter-dialect-DAVl1Nsm.js.map → filter-dialect-XtPJOCbD.js.map} +1 -1
  42. package/dist/{function-loader-BeFbN1-A.js → function-loader-D3YEHF6E.js} +2 -2
  43. package/dist/{function-loader-BeFbN1-A.js.map → function-loader-D3YEHF6E.js.map} +1 -1
  44. package/dist/{function-routes-CIwLXsZF.js → function-routes-DNDFIa7t.js} +3 -3
  45. package/dist/{function-routes-CIwLXsZF.js.map → function-routes-DNDFIa7t.js.map} +1 -1
  46. package/dist/functions/index.d.ts +2 -0
  47. package/dist/functions/index.js +162 -1
  48. package/dist/functions/index.js.map +1 -1
  49. package/dist/functions/rate-limit.d.ts +71 -0
  50. package/dist/{history-recorder-CNeqtTaR.js → history-recorder-C5RkbKS2.js} +3 -3
  51. package/dist/{history-recorder-CNeqtTaR.js.map → history-recorder-C5RkbKS2.js.map} +1 -1
  52. package/dist/{history-store-DseUt_dm.js → history-store-DzrJeEKv.js} +2 -2
  53. package/dist/{history-store-DseUt_dm.js.map → history-store-DzrJeEKv.js.map} +1 -1
  54. package/dist/index.d.ts +6 -0
  55. package/dist/index.es.js +1242 -214
  56. package/dist/index.es.js.map +1 -1
  57. package/dist/{internal-tables-CHFJHH7N.js → internal-tables-XxM_NdR_.js} +2 -2
  58. package/dist/{internal-tables-CHFJHH7N.js.map → internal-tables-XxM_NdR_.js.map} +1 -1
  59. package/dist/{jobs-WCyKVsUf.js → jobs-CFUwQTao.js} +3 -3
  60. package/dist/{jobs-WCyKVsUf.js.map → jobs-CFUwQTao.js.map} +1 -1
  61. package/dist/{jwt-JtQiewBW.js → jwt-CqhXs8Iz.js} +3 -3
  62. package/dist/{jwt-JtQiewBW.js.map → jwt-CqhXs8Iz.js.map} +1 -1
  63. package/dist/{keys-BTPoSvUs.js → keys-Btt6ZNqF.js} +2 -2
  64. package/dist/{keys-BTPoSvUs.js.map → keys-Btt6ZNqF.js.map} +1 -1
  65. package/dist/{load-schema-CtyLeq-H.js → load-schema-B4Nv1mwq.js} +33 -40
  66. package/dist/load-schema-B4Nv1mwq.js.map +1 -0
  67. package/dist/{logs-routes-BT4af1Or.js → logs-routes-C3CLYP-n.js} +3 -3
  68. package/dist/{logs-routes-BT4af1Or.js.map → logs-routes-C3CLYP-n.js.map} +1 -1
  69. package/dist/{offline-D_wKJcO3-RV6C9HnX.js → offline-ET6xI1ZO-BQpLQ7wh.js} +124 -7
  70. package/dist/offline-ET6xI1ZO-BQpLQ7wh.js.map +1 -0
  71. package/dist/{offline-store-DtmBwmKE-B17N4609.js → offline-store-DtmBwmKE-C9ba2NJv.js} +3 -3
  72. package/dist/{offline-store-DtmBwmKE-B17N4609.js.map → offline-store-DtmBwmKE-C9ba2NJv.js.map} +1 -1
  73. package/dist/{openapi-generator-mn6hsEmw.js → openapi-generator-CAhJiwBm.js} +4 -4
  74. package/dist/{openapi-generator-mn6hsEmw.js.map → openapi-generator-CAhJiwBm.js.map} +1 -1
  75. package/dist/{project-root-qDQzmsUD.js → project-root-CIrVZi-r.js} +2 -2
  76. package/dist/{project-root-qDQzmsUD.js.map → project-root-CIrVZi-r.js.map} +1 -1
  77. package/dist/{proxy-D18_bcQI.js → proxy-clweqa43.js} +3 -3
  78. package/dist/{proxy-D18_bcQI.js.map → proxy-clweqa43.js.map} +1 -1
  79. package/dist/push/push-options.d.ts +26 -0
  80. package/dist/push/push-routes.d.ts +30 -0
  81. package/dist/push/push-service.d.ts +13 -0
  82. package/dist/push/push-store.d.ts +45 -0
  83. package/dist/push/set-up.d.ts +25 -0
  84. package/dist/push/subscription-input.d.ts +26 -0
  85. package/dist/push/vapid-config.d.ts +35 -0
  86. package/dist/push/web-push-crypto.d.ts +44 -0
  87. package/dist/push/web-push-sender.d.ts +10 -0
  88. package/dist/{query-parser-CkKSbs1s.js → query-parser-Cd70kZO8.js} +6 -6
  89. package/dist/{query-parser-CkKSbs1s.js.map → query-parser-Cd70kZO8.js.map} +1 -1
  90. package/dist/{request-timeout-CpOgfQPK.js → request-timeout-cC3HT1Pf.js} +3 -3
  91. package/dist/{request-timeout-CpOgfQPK.js.map → request-timeout-cC3HT1Pf.js.map} +1 -1
  92. package/dist/{rls-simulator-routes-BxzeNXmI.js → rls-simulator-routes-DI2sYaQt.js} +4 -4
  93. package/dist/{rls-simulator-routes-BxzeNXmI.js.map → rls-simulator-routes-DI2sYaQt.js.map} +1 -1
  94. package/dist/{schema-editor-routes-mPCyks4X.js → schema-editor-routes-DEGwyQmx.js} +5 -5
  95. package/dist/{schema-editor-routes-mPCyks4X.js.map → schema-editor-routes-DEGwyQmx.js.map} +1 -1
  96. package/dist/{schema-tables-D4MEBZFi.js → schema-tables-DKFg6vMV.js} +4 -4
  97. package/dist/{schema-tables-D4MEBZFi.js.map → schema-tables-DKFg6vMV.js.map} +1 -1
  98. package/dist/{schema-tables-routes-D3iLb5XU.js → schema-tables-routes-BfsNG4c4.js} +5 -5
  99. package/dist/{schema-tables-routes-D3iLb5XU.js.map → schema-tables-routes-BfsNG4c4.js.map} +1 -1
  100. package/dist/{securityRuleToConditions-DD40f3ml.js → securityRuleToConditions-Bk5zRSoa.js} +2 -2
  101. package/dist/{securityRuleToConditions-DD40f3ml.js.map → securityRuleToConditions-Bk5zRSoa.js.map} +1 -1
  102. package/dist/{selection-hgC1szl6.js → selection-BOnbJvXD.js} +2 -2
  103. package/dist/{selection-hgC1szl6.js.map → selection-BOnbJvXD.js.map} +1 -1
  104. package/dist/serve-spa.d.ts +12 -0
  105. package/dist/{soft-delete-params-DDRmxT2z.js → soft-delete-params-Dhn0qKFv.js} +2 -2
  106. package/dist/{soft-delete-params-DDRmxT2z.js.map → soft-delete-params-Dhn0qKFv.js.map} +1 -1
  107. package/dist/{sql-export-routes-BKmQZ3xh.js → sql-export-routes-B3oqb1Jw.js} +3 -3
  108. package/dist/{sql-export-routes-BKmQZ3xh.js.map → sql-export-routes-B3oqb1Jw.js.map} +1 -1
  109. package/dist/{src-DLIb1O9l.js → src-CNZB3fuE.js} +192 -3
  110. package/dist/src-CNZB3fuE.js.map +1 -0
  111. package/dist/{table-source-editor-xvccIOH1.js → table-source-editor-D_zNDhEU.js} +3 -3
  112. package/dist/{table-source-editor-xvccIOH1.js.map → table-source-editor-D_zNDhEU.js.map} +1 -1
  113. package/dist/{upload-validation-B-psYLaN.js → upload-validation-BnIwo78L.js} +2 -2
  114. package/dist/{upload-validation-B-psYLaN.js.map → upload-validation-BnIwo78L.js.map} +1 -1
  115. package/package.json +5 -5
  116. package/dist/access-CCsVee6z.js.map +0 -1
  117. package/dist/auth-Blo1R8rc.js.map +0 -1
  118. package/dist/dist-CDIqWaSr.js +0 -19354
  119. package/dist/dist-CDIqWaSr.js.map +0 -1
  120. package/dist/errors-DpTMfX77.js.map +0 -1
  121. package/dist/load-schema-CtyLeq-H.js.map +0 -1
  122. package/dist/offline-D_wKJcO3-RV6C9HnX.js.map +0 -1
  123. package/dist/src-DLIb1O9l.js.map +0 -1
@@ -2,10 +2,10 @@ import { createRequire as __rebaseCreateRequire } from "module";
2
2
  import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
- import { Pn as __exportAll, Q as SCHEMA_VERSION_HEADER, Y as computeSchemaVersion } from "./src-DLIb1O9l.js";
6
- import { a as serializeTables, i as schemaViewKey, n as compileServedPolicies, r as schemaViewFor } from "./schema-tables-D4MEBZFi.js";
7
- import { t as ApiError } from "./errors-DpTMfX77.js";
8
- import { s as callerScopes } from "./access-CSfmyM87.js";
5
+ import { Q as SCHEMA_VERSION_HEADER, Rn as __exportAll, Y as computeSchemaVersion } from "./src-CNZB3fuE.js";
6
+ import { a as serializeTables, i as schemaViewKey, n as compileServedPolicies, r as schemaViewFor } from "./schema-tables-DKFg6vMV.js";
7
+ import { t as ApiError } from "./errors-NVbAQU25.js";
8
+ import { s as callerScopes } from "./access-BxkEYQh1.js";
9
9
  import { Hono } from "hono";
10
10
  //#region src/api/schema-tables-routes.ts
11
11
  var schema_tables_routes_exports = /* @__PURE__ */ __exportAll({
@@ -136,4 +136,4 @@ function createSchemaTablesRoutes(config) {
136
136
  //#endregion
137
137
  export { schema_tables_routes_exports as n, schemaCallerOf as t };
138
138
 
139
- //# sourceMappingURL=schema-tables-routes-D3iLb5XU.js.map
139
+ //# sourceMappingURL=schema-tables-routes-BfsNG4c4.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"schema-tables-routes-D3iLb5XU.js","names":[],"sources":["../src/api/schema-tables-routes.ts"],"sourcesContent":["import { Hono, type Context, type MiddlewareHandler } from \"hono\";\nimport {\n SCHEMA_VERSION_HEADER,\n computeSchemaVersion,\n type TableDescriptor\n} from \"@rebasepro/types\";\nimport type { HonoEnv } from \"./types\";\nimport { ApiError } from \"./errors\";\nimport { callerScopes } from \"../auth/access\";\nimport type { TableRegistry } from \"../schema/table-registry\";\nimport {\n compileServedPolicies,\n schemaViewFor,\n schemaViewKey,\n serializeTables,\n type SchemaCaller,\n type SchemaTablesPersons,\n type SchemaView,\n type TablePolicies\n} from \"./schema-tables\";\n\n/**\n * `GET {basePath}/schema/tables` — the tables this backend serves, as the\n * caller may see them — and `GET {basePath}/schema/tables/:slug`.\n *\n * The zero-config CMS renders every table from it, the Studio draws its schema\n * visualizer and RLS editor from it; the body is {@link serializeTables} for\n * the caller's view. Status codes:\n *\n * - `200` — a JSON array of `TableDescriptor` (one descriptor for `/:slug`),\n * with `ETag: W/\"<schemaVersion>-<view key>\"`, `Cache-Control: private,\n * no-cache` and the schema-version header. A signed-in person without\n * `schema:read` is described only the tables their roles can reach, with\n * only the rules that can apply to them, unless the backend says\n * `schemaTables: { persons: \"all\" }`; the view key carries their roles.\n * - `304` — `If-None-Match` named the current tag.\n * - `401` — nobody is signed in (and the backend did not opt into\n * `schemaTables: { public: true }`), or the credential sent is invalid.\n * - `403 SCOPE_MISSING` — a credential holding neither `schema:read` nor a\n * `data:*` scope.\n * - `404 SCHEMA_UNAVAILABLE` — no authentication is configured, so there is\n * no caller to redact for; `auth.requireAuth: false` does not change that.\n * - `404 TABLE_NOT_FOUND` — `/:slug` names a table this caller is not served.\n *\n * @module\n */\n\n/**\n * What the endpoint and `/api/meta/contract` both serve from: the registry's\n * descriptors and compiled policies, cached per registry revision.\n *\n * @group Schema\n */\nexport interface SchemaTablesService {\n /** The schema version the bodies describe. */\n version(): string;\n /** The tables a view is served. */\n tablesFor(view: SchemaView): TableDescriptor[];\n /** The `ETag` of what a view is served. */\n etagFor(view: SchemaView): string;\n}\n\n/**\n * Options of {@link createSchemaTablesService}.\n *\n * @group Schema\n */\nexport interface SchemaTablesServiceConfig {\n /** The descriptors served. Its revision invalidates every cache. */\n tableRegistry: Pick<TableRegistry, \"list\" | \"revision\">;\n /**\n * The declared tables: what the policy compiler reads. Introspected tables\n * are not among them — Rebase did not generate their policies, so it\n * serves none for them.\n */\n policySource: () => readonly TableDescriptor[];\n /**\n * The schema version the bundle recorded at build time, quoted while the\n * registry is as it was when the service was created. Recomputed from the\n * descriptors when absent, and after the registry changes: the recorded\n * stamp no longer describes it then.\n */\n schemaVersion?: string;\n}\n\n/** Distinct views cached per revision; more than this and the cache starts over. */\nconst MAX_CACHED_VIEWS = 256;\n\n/**\n * Build the cache both routes read.\n *\n * @group Schema\n */\nexport function createSchemaTablesService(config: SchemaTablesServiceConfig): SchemaTablesService {\n const registry = config.tableRegistry;\n const bootRevision = registry.revision;\n let cache: {\n revision: number;\n version: string;\n policies?: Map<string, TablePolicies>;\n bodies: Map<string, TableDescriptor[]>;\n } | undefined;\n\n const current = () => {\n if (cache && cache.revision === registry.revision) return cache;\n const version = registry.revision === bootRevision && config.schemaVersion\n ? config.schemaVersion\n : computeSchemaVersion(registry.list());\n cache = { revision: registry.revision, version, bodies: new Map() };\n return cache;\n };\n\n return {\n version: () => current().version,\n etagFor: (view) => `W/\"${current().version}-${schemaViewKey(view)}\"`,\n tablesFor: (view) => {\n const state = current();\n const key = schemaViewKey(view);\n const cached = state.bodies.get(key);\n if (cached) return cached;\n const tables = registry.list();\n if (view.privileged && !state.policies) {\n // A view has no policies of its own (`posture: \"view\"`).\n const policied = tables.filter(table => table.kind === \"table\").map(table => table.slug);\n state.policies = compileServedPolicies(config.policySource(), new Set(policied));\n }\n const body = serializeTables(tables, view, state.policies);\n if (state.bodies.size >= MAX_CACHED_VIEWS) state.bodies.clear();\n state.bodies.set(key, body);\n return body;\n }\n };\n}\n\n/**\n * Options of {@link createSchemaTablesRoutes}.\n *\n * @group Schema\n */\nexport interface SchemaTablesRoutesConfig {\n service: SchemaTablesService;\n /**\n * `false` when the backend has no authentication configured: every request\n * is answered `404 SCHEMA_UNAVAILABLE`.\n */\n available: boolean;\n /**\n * Identify the caller: verify whatever credential the request carries and\n * set `user` (and `scopes`, for a credential that narrows them). A request\n * with no credential must pass through with no `user`.\n */\n authenticate: MiddlewareHandler<HonoEnv>[];\n /** `schemaTables.public`: serve anonymous callers the tables with a public `select` rule. */\n publicTables?: boolean;\n /**\n * `schemaTables.persons`: what a signed-in person without `schema:read` is\n * described — the tables their roles can reach (`\"granted\"`, the default)\n * or every table (`\"all\"`). See {@link SchemaTablesPersons}.\n */\n persons?: SchemaTablesPersons;\n}\n\n/** The roles on the request's caller. */\nfunction rolesOf(c: Context<HonoEnv>): string[] {\n const user = c.get(\"user\");\n if (typeof user !== \"object\" || user === null || !(\"roles\" in user) || !Array.isArray(user.roles)) return [];\n return user.roles.filter((role): role is string => typeof role === \"string\");\n}\n\n/**\n * Who a request comes from, as the serializer judges it: nobody, a person\n * (their roles' scopes), or a credential (exactly the scopes it carries).\n *\n * @group Schema\n */\nexport function schemaCallerOf(c: Context<HonoEnv>): SchemaCaller {\n if (!c.get(\"user\")) return { kind: \"anonymous\", roles: [], scopes: [] };\n const narrowed = c.get(\"scopes\");\n return narrowed\n ? { kind: \"credential\", roles: rolesOf(c), scopes: narrowed }\n : { kind: \"person\", roles: rolesOf(c), scopes: callerScopes(c) };\n}\n\n/** Whether an `If-None-Match` header names this tag (or `*`). */\nfunction matches(header: string | undefined, etag: string): boolean {\n if (!header) return false;\n return header.split(\",\").map(tag => tag.trim()).some(tag => tag === etag || tag === \"*\");\n}\n\n/**\n * Mount `GET /tables` and `GET /tables/:slug` (the caller mounts the router at\n * `{basePath}/schema`).\n *\n * @group Schema\n */\nexport function createSchemaTablesRoutes(config: SchemaTablesRoutesConfig): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n\n if (!config.available) {\n router.all(\"/*\", (c) => c.json({\n error: {\n code: \"SCHEMA_UNAVAILABLE\",\n message: \"This backend serves its tables only to authenticated callers, and no authentication is \" +\n \"configured (no auth adapter and no auth.jwtSecret). Configure auth to enable GET /schema/tables.\"\n }\n }, 404));\n return router;\n }\n\n router.use(\"/*\", ...config.authenticate);\n\n const viewOf = (c: Context<HonoEnv>): SchemaView => {\n const caller = schemaCallerOf(c);\n if (caller.kind === \"anonymous\" && !config.publicTables) {\n throw ApiError.unauthenticated(\"Authentication required: the tables are described to signed-in callers and credentials only.\");\n }\n const view = schemaViewFor(caller, { persons: config.persons ?? \"granted\" });\n if (\"refused\" in view) throw new ApiError(403, \"SCOPE_MISSING\", view.message, { requiredScope: \"schema:read\" });\n return view;\n };\n\n const answer = <T>(c: Context<HonoEnv>, view: SchemaView, body: () => T): Response => {\n const etag = config.service.etagFor(view);\n c.header(\"ETag\", etag);\n c.header(\"Cache-Control\", \"private, no-cache\");\n c.header(\"Vary\", \"Authorization\");\n c.header(SCHEMA_VERSION_HEADER, config.service.version());\n if (matches(c.req.header(\"if-none-match\"), etag)) return c.body(null, 304);\n return c.json(body());\n };\n\n router.get(\"/tables\", (c) => {\n const view = viewOf(c);\n return answer(c, view, () => config.service.tablesFor(view));\n });\n\n router.get(\"/tables/:slug\", (c) => {\n const view = viewOf(c);\n const slug = c.req.param(\"slug\");\n const table = config.service.tablesFor(view).find(candidate => candidate.slug === slug);\n if (!table) throw ApiError.notFound(`No table \"${slug}\" is served to this caller.`, \"TABLE_NOT_FOUND\");\n return answer(c, view, () => table);\n });\n\n return router;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAsFA,IAAM,mBAAmB;;;;;;AAOzB,SAAgB,0BAA0B,QAAwD;CAC9F,MAAM,WAAW,OAAO;CACxB,MAAM,eAAe,SAAS;CAC9B,IAAI;CAOJ,MAAM,gBAAgB;EAClB,IAAI,SAAS,MAAM,aAAa,SAAS,UAAU,OAAO;EAC1D,MAAM,UAAU,SAAS,aAAa,gBAAgB,OAAO,gBACvD,OAAO,gBACP,qBAAqB,SAAS,KAAK,CAAC;EAC1C,QAAQ;GAAE,UAAU,SAAS;GAAU;GAAS,wBAAQ,IAAI,IAAI;EAAE;EAClE,OAAO;CACX;CAEA,OAAO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GAAG,YAAY,OAAO,QAAQ,UAAU,IAAI,CAAC;CAC/D,CAAC;CAED,OAAO,IAAI,kBAAkB,MAAM;EAC/B,MAAM,OAAO,OAAO,CAAC;EACrB,MAAM,OAAO,EAAE,IAAI,MAAM,MAAM;EAC/B,MAAM,QAAQ,OAAO,QAAQ,UAAU,IAAI,CAAC,CAAC,MAAK,cAAa,UAAU,SAAS,IAAI;EACtF,IAAI,CAAC,OAAO,MAAM,SAAS,SAAS,aAAa,KAAK,8BAA8B,iBAAiB;EACrG,OAAO,OAAO,GAAG,YAAY,KAAK;CACtC,CAAC;CAED,OAAO;AACX"}
1
+ {"version":3,"file":"schema-tables-routes-BfsNG4c4.js","names":[],"sources":["../src/api/schema-tables-routes.ts"],"sourcesContent":["import { Hono, type Context, type MiddlewareHandler } from \"hono\";\nimport {\n SCHEMA_VERSION_HEADER,\n computeSchemaVersion,\n type TableDescriptor\n} from \"@rebasepro/types\";\nimport type { HonoEnv } from \"./types\";\nimport { ApiError } from \"./errors\";\nimport { callerScopes } from \"../auth/access\";\nimport type { TableRegistry } from \"../schema/table-registry\";\nimport {\n compileServedPolicies,\n schemaViewFor,\n schemaViewKey,\n serializeTables,\n type SchemaCaller,\n type SchemaTablesPersons,\n type SchemaView,\n type TablePolicies\n} from \"./schema-tables\";\n\n/**\n * `GET {basePath}/schema/tables` — the tables this backend serves, as the\n * caller may see them — and `GET {basePath}/schema/tables/:slug`.\n *\n * The zero-config CMS renders every table from it, the Studio draws its schema\n * visualizer and RLS editor from it; the body is {@link serializeTables} for\n * the caller's view. Status codes:\n *\n * - `200` — a JSON array of `TableDescriptor` (one descriptor for `/:slug`),\n * with `ETag: W/\"<schemaVersion>-<view key>\"`, `Cache-Control: private,\n * no-cache` and the schema-version header. A signed-in person without\n * `schema:read` is described only the tables their roles can reach, with\n * only the rules that can apply to them, unless the backend says\n * `schemaTables: { persons: \"all\" }`; the view key carries their roles.\n * - `304` — `If-None-Match` named the current tag.\n * - `401` — nobody is signed in (and the backend did not opt into\n * `schemaTables: { public: true }`), or the credential sent is invalid.\n * - `403 SCOPE_MISSING` — a credential holding neither `schema:read` nor a\n * `data:*` scope.\n * - `404 SCHEMA_UNAVAILABLE` — no authentication is configured, so there is\n * no caller to redact for; `auth.requireAuth: false` does not change that.\n * - `404 TABLE_NOT_FOUND` — `/:slug` names a table this caller is not served.\n *\n * @module\n */\n\n/**\n * What the endpoint and `/api/meta/contract` both serve from: the registry's\n * descriptors and compiled policies, cached per registry revision.\n *\n * @group Schema\n */\nexport interface SchemaTablesService {\n /** The schema version the bodies describe. */\n version(): string;\n /** The tables a view is served. */\n tablesFor(view: SchemaView): TableDescriptor[];\n /** The `ETag` of what a view is served. */\n etagFor(view: SchemaView): string;\n}\n\n/**\n * Options of {@link createSchemaTablesService}.\n *\n * @group Schema\n */\nexport interface SchemaTablesServiceConfig {\n /** The descriptors served. Its revision invalidates every cache. */\n tableRegistry: Pick<TableRegistry, \"list\" | \"revision\">;\n /**\n * The declared tables: what the policy compiler reads. Introspected tables\n * are not among them — Rebase did not generate their policies, so it\n * serves none for them.\n */\n policySource: () => readonly TableDescriptor[];\n /**\n * The schema version the bundle recorded at build time, quoted while the\n * registry is as it was when the service was created. Recomputed from the\n * descriptors when absent, and after the registry changes: the recorded\n * stamp no longer describes it then.\n */\n schemaVersion?: string;\n}\n\n/** Distinct views cached per revision; more than this and the cache starts over. */\nconst MAX_CACHED_VIEWS = 256;\n\n/**\n * Build the cache both routes read.\n *\n * @group Schema\n */\nexport function createSchemaTablesService(config: SchemaTablesServiceConfig): SchemaTablesService {\n const registry = config.tableRegistry;\n const bootRevision = registry.revision;\n let cache: {\n revision: number;\n version: string;\n policies?: Map<string, TablePolicies>;\n bodies: Map<string, TableDescriptor[]>;\n } | undefined;\n\n const current = () => {\n if (cache && cache.revision === registry.revision) return cache;\n const version = registry.revision === bootRevision && config.schemaVersion\n ? config.schemaVersion\n : computeSchemaVersion(registry.list());\n cache = { revision: registry.revision, version, bodies: new Map() };\n return cache;\n };\n\n return {\n version: () => current().version,\n etagFor: (view) => `W/\"${current().version}-${schemaViewKey(view)}\"`,\n tablesFor: (view) => {\n const state = current();\n const key = schemaViewKey(view);\n const cached = state.bodies.get(key);\n if (cached) return cached;\n const tables = registry.list();\n if (view.privileged && !state.policies) {\n // A view has no policies of its own (`posture: \"view\"`).\n const policied = tables.filter(table => table.kind === \"table\").map(table => table.slug);\n state.policies = compileServedPolicies(config.policySource(), new Set(policied));\n }\n const body = serializeTables(tables, view, state.policies);\n if (state.bodies.size >= MAX_CACHED_VIEWS) state.bodies.clear();\n state.bodies.set(key, body);\n return body;\n }\n };\n}\n\n/**\n * Options of {@link createSchemaTablesRoutes}.\n *\n * @group Schema\n */\nexport interface SchemaTablesRoutesConfig {\n service: SchemaTablesService;\n /**\n * `false` when the backend has no authentication configured: every request\n * is answered `404 SCHEMA_UNAVAILABLE`.\n */\n available: boolean;\n /**\n * Identify the caller: verify whatever credential the request carries and\n * set `user` (and `scopes`, for a credential that narrows them). A request\n * with no credential must pass through with no `user`.\n */\n authenticate: MiddlewareHandler<HonoEnv>[];\n /** `schemaTables.public`: serve anonymous callers the tables with a public `select` rule. */\n publicTables?: boolean;\n /**\n * `schemaTables.persons`: what a signed-in person without `schema:read` is\n * described — the tables their roles can reach (`\"granted\"`, the default)\n * or every table (`\"all\"`). See {@link SchemaTablesPersons}.\n */\n persons?: SchemaTablesPersons;\n}\n\n/** The roles on the request's caller. */\nfunction rolesOf(c: Context<HonoEnv>): string[] {\n const user = c.get(\"user\");\n if (typeof user !== \"object\" || user === null || !(\"roles\" in user) || !Array.isArray(user.roles)) return [];\n return user.roles.filter((role): role is string => typeof role === \"string\");\n}\n\n/**\n * Who a request comes from, as the serializer judges it: nobody, a person\n * (their roles' scopes), or a credential (exactly the scopes it carries).\n *\n * @group Schema\n */\nexport function schemaCallerOf(c: Context<HonoEnv>): SchemaCaller {\n if (!c.get(\"user\")) return { kind: \"anonymous\", roles: [], scopes: [] };\n const narrowed = c.get(\"scopes\");\n return narrowed\n ? { kind: \"credential\", roles: rolesOf(c), scopes: narrowed }\n : { kind: \"person\", roles: rolesOf(c), scopes: callerScopes(c) };\n}\n\n/** Whether an `If-None-Match` header names this tag (or `*`). */\nfunction matches(header: string | undefined, etag: string): boolean {\n if (!header) return false;\n return header.split(\",\").map(tag => tag.trim()).some(tag => tag === etag || tag === \"*\");\n}\n\n/**\n * Mount `GET /tables` and `GET /tables/:slug` (the caller mounts the router at\n * `{basePath}/schema`).\n *\n * @group Schema\n */\nexport function createSchemaTablesRoutes(config: SchemaTablesRoutesConfig): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n\n if (!config.available) {\n router.all(\"/*\", (c) => c.json({\n error: {\n code: \"SCHEMA_UNAVAILABLE\",\n message: \"This backend serves its tables only to authenticated callers, and no authentication is \" +\n \"configured (no auth adapter and no auth.jwtSecret). Configure auth to enable GET /schema/tables.\"\n }\n }, 404));\n return router;\n }\n\n router.use(\"/*\", ...config.authenticate);\n\n const viewOf = (c: Context<HonoEnv>): SchemaView => {\n const caller = schemaCallerOf(c);\n if (caller.kind === \"anonymous\" && !config.publicTables) {\n throw ApiError.unauthenticated(\"Authentication required: the tables are described to signed-in callers and credentials only.\");\n }\n const view = schemaViewFor(caller, { persons: config.persons ?? \"granted\" });\n if (\"refused\" in view) throw new ApiError(403, \"SCOPE_MISSING\", view.message, { requiredScope: \"schema:read\" });\n return view;\n };\n\n const answer = <T>(c: Context<HonoEnv>, view: SchemaView, body: () => T): Response => {\n const etag = config.service.etagFor(view);\n c.header(\"ETag\", etag);\n c.header(\"Cache-Control\", \"private, no-cache\");\n c.header(\"Vary\", \"Authorization\");\n c.header(SCHEMA_VERSION_HEADER, config.service.version());\n if (matches(c.req.header(\"if-none-match\"), etag)) return c.body(null, 304);\n return c.json(body());\n };\n\n router.get(\"/tables\", (c) => {\n const view = viewOf(c);\n return answer(c, view, () => config.service.tablesFor(view));\n });\n\n router.get(\"/tables/:slug\", (c) => {\n const view = viewOf(c);\n const slug = c.req.param(\"slug\");\n const table = config.service.tablesFor(view).find(candidate => candidate.slug === slug);\n if (!table) throw ApiError.notFound(`No table \"${slug}\" is served to this caller.`, \"TABLE_NOT_FOUND\");\n return answer(c, view, () => table);\n });\n\n return router;\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAsFA,IAAM,mBAAmB;;;;;;AAOzB,SAAgB,0BAA0B,QAAwD;CAC9F,MAAM,WAAW,OAAO;CACxB,MAAM,eAAe,SAAS;CAC9B,IAAI;CAOJ,MAAM,gBAAgB;EAClB,IAAI,SAAS,MAAM,aAAa,SAAS,UAAU,OAAO;EAC1D,MAAM,UAAU,SAAS,aAAa,gBAAgB,OAAO,gBACvD,OAAO,gBACP,qBAAqB,SAAS,KAAK,CAAC;EAC1C,QAAQ;GAAE,UAAU,SAAS;GAAU;GAAS,wBAAQ,IAAI,IAAI;EAAE;EAClE,OAAO;CACX;CAEA,OAAO;EACH,eAAe,QAAQ,CAAC,CAAC;EACzB,UAAU,SAAS,MAAM,QAAQ,CAAC,CAAC,QAAQ,GAAG,cAAc,IAAI,EAAE;EAClE,YAAY,SAAS;GACjB,MAAM,QAAQ,QAAQ;GACtB,MAAM,MAAM,cAAc,IAAI;GAC9B,MAAM,SAAS,MAAM,OAAO,IAAI,GAAG;GACnC,IAAI,QAAQ,OAAO;GACnB,MAAM,SAAS,SAAS,KAAK;GAC7B,IAAI,KAAK,cAAc,CAAC,MAAM,UAAU;IAEpC,MAAM,WAAW,OAAO,QAAO,UAAS,MAAM,SAAS,OAAO,CAAC,CAAC,KAAI,UAAS,MAAM,IAAI;IACvF,MAAM,WAAW,sBAAsB,OAAO,aAAa,GAAG,IAAI,IAAI,QAAQ,CAAC;GACnF;GACA,MAAM,OAAO,gBAAgB,QAAQ,MAAM,MAAM,QAAQ;GACzD,IAAI,MAAM,OAAO,QAAQ,kBAAkB,MAAM,OAAO,MAAM;GAC9D,MAAM,OAAO,IAAI,KAAK,IAAI;GAC1B,OAAO;EACX;CACJ;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UAAU,CAAC;EAC3E,IAAI,aAAa,MAAM,MAAM,IAAI,SAAS,KAAK,iBAAiB,KAAK,SAAS,EAAE,eAAe,cAAc,CAAC;EAC9G,OAAO;CACX;CAEA,MAAM,UAAa,GAAqB,MAAkB,SAA4B;EAClF,MAAM,OAAO,OAAO,QAAQ,QAAQ,IAAI;EACxC,EAAE,OAAO,QAAQ,IAAI;EACrB,EAAE,OAAO,iBAAiB,mBAAmB;EAC7C,EAAE,OAAO,QAAQ,eAAe;EAChC,EAAE,OAAO,uBAAuB,OAAO,QAAQ,QAAQ,CAAC;EACxD,IAAI,QAAQ,EAAE,IAAI,OAAO,eAAe,GAAG,IAAI,GAAG,OAAO,EAAE,KAAK,MAAM,GAAG;EACzE,OAAO,EAAE,KAAK,KAAK,CAAC;CACxB;CAEA,OAAO,IAAI,YAAY,MAAM;EACzB,MAAM,OAAO,OAAO,CAAC;EACrB,OAAO,OAAO,GAAG,YAAY,OAAO,QAAQ,UAAU,IAAI,CAAC;CAC/D,CAAC;CAED,OAAO,IAAI,kBAAkB,MAAM;EAC/B,MAAM,OAAO,OAAO,CAAC;EACrB,MAAM,OAAO,EAAE,IAAI,MAAM,MAAM;EAC/B,MAAM,QAAQ,OAAO,QAAQ,UAAU,IAAI,CAAC,CAAC,MAAK,cAAa,UAAU,SAAS,IAAI;EACtF,IAAI,CAAC,OAAO,MAAM,SAAS,SAAS,aAAa,KAAK,8BAA8B,iBAAiB;EACrG,OAAO,OAAO,GAAG,YAAY,KAAK;CACtC,CAAC;CAED,OAAO;AACX"}
@@ -2,7 +2,7 @@ import { createRequire as __rebaseCreateRequire } from "module";
2
2
  import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
- import { gn as policy, hn as isPolicyShorthand, mn as isPolicyExpressionKind, nn as isRedactedSecurityRule, un as rewriteLegacyRlsFunctions } from "./src-DLIb1O9l.js";
5
+ import { bn as policy, mn as rewriteLegacyRlsFunctions, on as isRedactedSecurityRule, vn as isPolicyExpressionKind, yn as isPolicyShorthand } from "./src-CNZB3fuE.js";
6
6
  import { r as toSnakeCase } from "./strings.es-k0kjzQBh.js";
7
7
  //#region ../common/src/util/policy/sqlToPolicy.ts
8
8
  /**
@@ -442,4 +442,4 @@ function withRoles(base, rule) {
442
442
  //#endregion
443
443
  export { policyShorthandColumns as n, securityRuleToConditions as t };
444
444
 
445
- //# sourceMappingURL=securityRuleToConditions-DD40f3ml.js.map
445
+ //# sourceMappingURL=securityRuleToConditions-Bk5zRSoa.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"securityRuleToConditions-DD40f3ml.js","names":[],"sources":["../../common/src/util/policy/sqlToPolicy.ts","../../common/src/util/policy/policyCondition.ts","../../common/src/util/policy/securityRuleToConditions.ts"],"sourcesContent":["import { ANONYMOUS_USER_ID, ANONYMOUS_USER_IDS, LiteralPolicyOperand, PolicyExpression, policy, rewriteLegacyRlsFunctions } from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\n\n/**\n * A tiny, regex-based SQL \"parser\" for security rules.\n *\n * This is NOT a full SQL parser. It is designed to handle the subset of SQL\n * commonly used in `USING` and `WITH CHECK` clauses, enough to drive the\n * optimistic client-side UI decision.\n *\n * It handles:\n * - `field = 'literal'`\n * - `field != 'literal'`\n * - `field = current_setting('app.uid')` (or the legacy `app.user_id`)\n * - `A AND B`, `A OR B` — only where the keyword is at the top level\n * - `true`\n * - `IN (...)` (as optimistic true)\n *\n * For anything it doesn't understand, it returns a `raw` expression, which\n * the evaluator treats as \"unknown\" (and usually optimistic true).\n *\n * **This output also round-trips back into DDL** via `compilePolicyExpression` (the\n * schema/policy generators), so decomposing a clause the parser only partly\n * understands is not a cosmetic mistake — it emits invalid SQL. When in doubt,\n * prefer `raw`: it is reproduced verbatim.\n */\n/** True when `keyword` starts at `i` as a standalone word. */\nfunction isKeywordAt(upper: string, i: number, keyword: string): boolean {\n if (!upper.startsWith(keyword, i)) return false;\n const before = i === 0 ? \" \" : upper[i - 1];\n const after = upper[i + keyword.length] ?? \" \";\n return /[\\s()]/.test(before) && /[\\s()]/.test(after);\n}\n\n/**\n * Split `sql` on a boolean keyword, but only where it sits at paren depth 0 and\n * outside a string literal. Returns null when it never does, so the caller\n * leaves the clause alone.\n *\n * This used to be `sql.split(/ AND /i)`, which tore subqueries in half: the\n * `AND` inside\n * `EXISTS (SELECT 1 FROM organization_members m WHERE m.org = t.org AND m.user_id = rebase.uid())`\n * split the expression, and re-emitting the halves produced\n * `(EXISTS (...) AND m.user_id = rebase.uid())`\n * where `m` is no longer in scope — SQL that Postgres rejects outright with\n * \"missing FROM-clause entry for table\". Returning null instead keeps such a\n * clause as a `raw` expression, which round-trips verbatim.\n */\nfunction splitTopLevel(sql: string, keyword: \"AND\" | \"OR\"): string[] | null {\n const upper = sql.toUpperCase();\n const parts: string[] = [];\n let depth = 0;\n let inString = false;\n let start = 0;\n\n for (let i = 0; i < sql.length; i++) {\n const ch = sql[i];\n if (inString) {\n if (ch === \"'\") {\n if (sql[i + 1] === \"'\") i++; // '' escapes a quote inside a literal\n else inString = false;\n }\n continue;\n }\n if (ch === \"'\") { inString = true; continue; }\n if (ch === \"(\") { depth++; continue; }\n if (ch === \")\") { depth--; continue; }\n if (depth === 0 && isKeywordAt(upper, i, keyword)) {\n parts.push(sql.slice(start, i));\n i += keyword.length - 1;\n start = i + 1;\n }\n }\n\n if (parts.length === 0) return null;\n parts.push(sql.slice(start));\n const trimmedParts = parts.map(p => p.trim()).filter(p => p.length > 0);\n return trimmedParts.length > 1 ? trimmedParts : null;\n}\n\n/** `SELECT` as the first word of `sql`. */\nconst STARTS_WITH_SELECT = /^select(?=[\\s(])/i;\n\n/**\n * Drop redundant wrapping parens (`(a AND b)` → `a AND b`), never `(a) AND (b)`\n * — and never the parens of a scalar subquery: `(SELECT x)` without them is not\n * an expression at all, and re-emitted bare it is a syntax error inside\n * `USING (…)`.\n */\nfunction stripOuterParens(sql: string): string {\n let s = sql.trim();\n while (wrapsWhole(s) && !STARTS_WITH_SELECT.test(s.slice(1).trim())) {\n s = s.slice(1, -1).trim();\n }\n return s;\n}\n\n/** Whether `s` is one parenthesised group: `(a AND b)`, not `(a) AND (b)`. */\nfunction wrapsWhole(s: string): boolean {\n if (!s.startsWith(\"(\") || !s.endsWith(\")\")) return false;\n let depth = 0;\n let inString = false;\n for (let i = 0; i < s.length; i++) {\n const ch = s[i];\n if (inString) {\n if (ch === \"'\") {\n if (s[i + 1] === \"'\") i++;\n else inString = false;\n }\n continue;\n }\n if (ch === \"'\") { inString = true; continue; }\n if (ch === \"(\") depth++;\n else if (ch === \")\") {\n depth--;\n if (depth === 0 && i < s.length - 1) return false;\n }\n }\n return true;\n}\n\n/** `x` when `s` is exactly `(SELECT x)`, otherwise null. */\nfunction scalarSubqueryBody(s: string): string | null {\n if (!wrapsWhole(s)) return null;\n const inner = s.slice(1, -1).trim();\n return STARTS_WITH_SELECT.test(inner) ? inner.slice(\"select\".length).trim() : null;\n}\n\n/**\n * The names in a role array's body — `'admin', 'editor'`, each with or without\n * Postgres's `::text` — or `null` when an element is anything else. A quote\n * or a comma inside a name is not split into roles that were never there: the\n * clause stays raw and round-trips verbatim.\n */\nfunction roleArrayElements(list: string): string[] | null {\n const roles: string[] = [];\n for (const element of list.split(\",\")) {\n const match = /^'([^',]*)'(?:::text)?$/.exec(element.trim());\n if (!match) return null;\n roles.push(match[1]);\n }\n return roles;\n}\n\n/** Whether any part of `expr` fell through to `raw`. */\nfunction containsRaw(expr: PolicyExpression): boolean {\n switch (expr.kind) {\n case \"raw\":\n return true;\n case \"and\":\n case \"or\":\n return expr.operands.some(containsRaw);\n case \"not\":\n return containsRaw(expr.operand);\n case \"existsIn\":\n return containsRaw(expr.where);\n default:\n return false;\n }\n}\n\nexport function sqlToPolicy(sql: string): PolicyExpression {\n // Normalised before anything else looks at it, so every pattern below only\n // has to know the current spelling. A database migrated by a pre-1.0 release\n // still holds `auth.uid()` in its policy bodies until the next push or boot\n // recompiles them — and until then the admin UI reads those bodies back\n // through here. Without this they parse as opaque `raw`, and the framework's\n // own policies get badged as hand-written drift.\n //\n // Normalising rather than accepting both spellings throughout is deliberate:\n // it also means a legacy policy that falls through to `raw` is stored in the\n // new spelling, so editing and saving one in the Studio migrates it.\n const trimmed = stripOuterParens(rewriteLegacyRlsFunctions(sql).trim());\n\n // `(SELECT x)` — how the compiler spells a part of a policy that does not\n // read the row, so Postgres evaluates it once per statement. Read back as\n // `x` when `x` is understood completely: without a FROM a scalar subquery\n // is one row holding x's value, so the two mean the same. Anything less —\n // a FROM, a LIMIT, an alias, a clause the parser does not know — stays\n // `raw`, parens included, and is reproduced verbatim.\n const subqueryBody = scalarSubqueryBody(trimmed);\n if (subqueryBody !== null) {\n const inner = sqlToPolicy(subqueryBody);\n return containsRaw(inner) ? policy.raw(trimmed) : inner;\n }\n\n if (trimmed.toLowerCase() === \"true\") return policy.true();\n if (trimmed.toLowerCase() === \"false\") return policy.false();\n\n // Handle roles overlap (&&) and containment (@>), as the compiler writes\n // them and as Postgres stores them:\n // string_to_array(rebase.roles(), ',') && ARRAY['admin', 'editor']\n // string_to_array(rebase.roles(), ','::text) && ARRAY['admin'::text, 'editor'::text]\n // The second is what `pg_policies` holds, so what `schema introspect`\n // writes as a rule's `using`. Read as raw, a junction could not inherit\n // the rule, and its derived edge-write policies were left with none.\n const rolesMatch = trimmed.match(/^string_to_array\\s*\\(\\s*rebase\\.roles\\(\\)\\s*,\\s*','(?:::text)?\\s*\\)\\s*(&&|@>)\\s*ARRAY\\s*\\[(.+)\\]$/i);\n const roles = rolesMatch ? roleArrayElements(rolesMatch[2]) : null;\n if (rolesMatch && roles) {\n return rolesMatch[1] === \"&&\" ? policy.rolesOverlap(roles) : policy.rolesContain(roles);\n }\n\n // OR binds looser than AND, so it splits first.\n const orParts = splitTopLevel(trimmed, \"OR\");\n if (orParts) return policy.or(...orParts.map(sqlToPolicy));\n\n const andParts = splitTopLevel(trimmed, \"AND\");\n if (andParts) return policy.and(...andParts.map(sqlToPolicy));\n\n // Handle = and !=\n const match = trimmed.match(/^(.+?)\\s*(!?=)\\s*(.+)$/);\n if (match) {\n const [, leftStr, op, rightStr] = match;\n const left = parseOperand(leftStr.trim());\n const right = parseOperand(rightStr.trim());\n if (left && right) {\n return policy.compare(left, op === \"=\" ? \"eq\" : \"neq\", right);\n }\n }\n\n // Fallback to raw — the NORMALISED text, not the input. Storing the input\n // verbatim would mean a legacy policy read out of a database, edited in the\n // Studio and saved, writes `auth.uid()` back into the project's config: a\n // call to a function 1.0 no longer creates.\n return policy.raw(trimmed);\n}\n\n/**\n * Literals from other BaaS platforms that people compare `rebase.uid()` against\n * out of habit. Mirrors the driver's `FOREIGN_CONVENTION_ROLES` guard on\n * `pgRoles`, one surface over: the same muscle memory inside a `using:` string\n * is the more dangerous spelling, because it inverts a rule instead of\n * emptying a table.\n */\n/**\n * A `Map`, not an object literal.\n *\n * As `Record<string, string>` this was indexed with a literal taken straight\n * out of a policy, so every key on `Object.prototype` answered: a rule\n * comparing `rebase.uid()` to `\"valueOf\"`, `\"toString\"`, `\"constructor\"` or\n * `\"hasOwnProperty\"` found a truthy \"platform\" and reported an anonymous-grant\n * risk that does not exist — with the matched function interpolated into the\n * explanation as the platform's name. A security warning that fires on\n * innocent input is worse than none: it is what teaches people to skip the\n * warnings that are real.\n *\n * Same shape as the prototype-pollution class swept out of `setIn`, `getIn`,\n * `mergeDeep` and `unflattenObject` — a data-derived key reaching a plain\n * object. Found by a property test, on the input `\"valueOf\"`.\n */\nconst FOREIGN_CONVENTION_UIDS = new Map<string, string>([\n [\"anon\", \"Supabase\"],\n [\"authenticated\", \"Supabase\"],\n [\"service_role\", \"Supabase\"]\n]);\n\n/**\n * The same foreign literals, as a pattern for SQL that could not be parsed\n * back into structure.\n */\nconst FOREIGN_UID_LITERAL_SQL = new RegExp(\n String.raw`rebase\\.uid\\(\\)\\s*=\\s*'(${[...FOREIGN_CONVENTION_UIDS.keys()].join(\"|\")})'`,\n \"i\"\n);\n\n/** A clause that reads as a lockdown but admits anonymous callers. */\nexport interface AnonymousGrantRisk {\n /** Which spelling was found. */\n pattern: \"foreign-uid-literal\" | \"uid-not-null\";\n /** The offending fragment — the literal, or the SQL that is a tautology. */\n detail: string;\n /** Why it admits anonymous callers, and what to write instead. */\n explanation: string;\n}\n\n/**\n * `rebase.uid() IS NOT NULL` in raw SQL, the clause that is always true.\n *\n * Both schema spellings, because this runs over policy bodies read back from a\n * database, and one migrated by a pre-1.0 release still holds `auth.uid()`.\n * A security check that stops recognising a dangerous clause because the\n * framework renamed a function is a check that silently turns off.\n */\nconst UID_NOT_NULL = /\\b(?:rebase|auth)\\.uid\\(\\)\\s+IS\\s+NOT\\s+NULL/i;\n\n/**\n * Find clauses that read as \"signed-in users only\" but admit anonymous callers.\n *\n * Both spellings come from the same place — Supabase, where its own `auth.uid()`\n * really is NULL for an anonymous request. Rebase substitutes\n * {@link ANONYMOUS_USER_ID} instead (a blank id would read back as NULL, which\n * is how the trusted *server* context is recognised), so:\n *\n * - `rebase.uid() IS NOT NULL` is a tautology on the user path, and\n * - `rebase.uid() != 'anon'` excludes one spelling of anonymous and admits the\n * other. This one is not hypothetical and was not only a foreign habit:\n * rebase's own request path reported `'anon'` while everything that compiled\n * or checked a policy used `'anonymous'`, so whichever literal an author\n * picked, half the anonymous callers walked through. See\n * {@link ANONYMOUS_USER_IDS}.\n *\n * Either one turns a lockdown into a full grant, and neither looks wrong. No\n * real user id is ever one of these literals, and a user-context request is\n * never NULL, so a match is always a mistake rather than a deliberate check.\n *\n * Structured expressions are checked too, not just parsed SQL: `policy.compare`\n * can spell the same mistake.\n */\nexport function findAnonymousGrants(expr: PolicyExpression): AnonymousGrantRisk[] {\n const found: AnonymousGrantRisk[] = [];\n\n const visit = (e: PolicyExpression): void => {\n switch (e.kind) {\n case \"and\":\n case \"or\":\n e.operands.forEach(visit);\n return;\n case \"not\":\n visit(e.operand);\n return;\n case \"existsIn\":\n visit(e.where);\n return;\n case \"raw\": {\n if (UID_NOT_NULL.test(e.sql)) {\n found.push({\n pattern: \"uid-not-null\",\n detail: e.sql,\n explanation: \"`rebase.uid() IS NOT NULL` is true for every request that came from a client, \" +\n `including anonymous ones — they carry '${ANONYMOUS_USER_ID}', not NULL. ` +\n \"Use `condition: policy.authenticated()` to mean \\\"signed in\\\".\"\n });\n }\n // The foreign literals have to be looked for here too, not only\n // in `compare`. `sqlToPolicy` falls back to `raw` for anything\n // it cannot structure — an `EXISTS (...)` subquery always does —\n // so a policy read back from the database arrives as one opaque\n // string. Checking only the tautology meant a genuine\n // `rebase.uid() = 'anon'` inside an `existsIn` was structurally\n // undetectable once round-tripped, and the caller read the empty\n // result as \"no risks found\".\n const foreign = FOREIGN_UID_LITERAL_SQL.exec(e.sql);\n if (foreign) {\n const literal = foreign[1];\n found.push({\n pattern: \"foreign-uid-literal\",\n detail: literal,\n explanation: `'${literal}' is a ${FOREIGN_CONVENTION_UIDS.get(literal)} convention. Rebase ` +\n `reports an anonymous request as '${ANONYMOUS_USER_ID}', so comparing against ` +\n `'${literal}' passes for every caller. Use \\`condition: policy.authenticated()\\` to ` +\n \"mean \\\"signed in\\\".\"\n });\n }\n return;\n }\n case \"compare\": {\n const literal = [e.left, e.right].find(o => o.kind === \"literal\") as LiteralPolicyOperand | undefined;\n const comparesUid = e.left.kind === \"authUid\" || e.right.kind === \"authUid\";\n if (!comparesUid || typeof literal?.value !== \"string\") return;\n const platform = FOREIGN_CONVENTION_UIDS.get(literal.value);\n if (!platform) return;\n found.push({\n pattern: \"foreign-uid-literal\",\n detail: literal.value,\n explanation: `'${literal.value}' is a ${platform} convention. Rebase reports an anonymous ` +\n `request as '${ANONYMOUS_USER_ID}', so comparing against '${literal.value}' passes for ` +\n \"every caller. Use `condition: policy.authenticated()` to mean \\\"signed in\\\" — it \" +\n `compiles to NOT IN (${ANONYMOUS_USER_IDS.map(v => `'${v}'`).join(\", \")}), covering ` +\n \"every spelling rebase has reported rather than whichever one you remember.\"\n });\n return;\n }\n default:\n return;\n }\n };\n\n visit(expr);\n return found;\n}\n\nfunction parseOperand(str: string) {\n // current_setting('app.uid') or rebase.uid(). `app.user_id` is the\n // pre-rename spelling and stays parseable: policies are data, so a\n // database provisioned before the rename still holds rules written\n // against it, and round-tripping one must not silently drop the operand.\n //\n // ANCHORED, and that is the whole point. These tests used to be\n // unanchored — `.test(str)` rather than `^…$` — so any operand text that\n // merely *contained* a uid call was replaced wholesale by the call itself.\n // Everything else in the expression was discarded with it, including a\n // leading `NOT (`:\n //\n // NOT (rebase.uid() = rebase.uid()) parsed as rebase.uid() = rebase.uid()\n //\n // A deny became an unconditional grant. The realistic spelling is a\n // hand-written defensive rule with a uid call on both sides —\n // COALESCE(rebase.uid(), '') = COALESCE(owner_id, rebase.uid())\n // — which collapsed to the same tautology. This is not confined to the\n // admin UI: `securityRuleToConditions` feeds a rule's raw `using:` string\n // through here, and the Postgres DDL generators compile the result, so the\n // tautology was written into the database as the policy body.\n //\n // An operand this cannot identify exactly must return null, which drops the\n // whole clause to `raw` and reproduces it verbatim. That is the rule the\n // rest of this file already follows: when in doubt, prefer `raw`.\n if (/^current_setting\\s*\\(\\s*'app\\.(uid|user_id)'\\s*\\)$/i.test(str) || /^rebase\\.uid\\(\\)$/i.test(str)) {\n return policy.authUid();\n }\n // The same call as an initPlan — the compiler's spelling, `(SELECT\n // rebase.uid())`, and Postgres's re-rendering of it, `( SELECT rebase.uid()\n // AS uid)`. Anchored like the line above, for the same reason.\n if (/^\\(\\s*select\\s+rebase\\.uid\\(\\)(?:\\s+as\\s+\"?uid\"?)?\\s*\\)$/i.test(str)) {\n return policy.authUid();\n }\n\n // Literal string: 'value', with `''` decoded back to a single quote.\n //\n // `quoteLiteral` doubles every quote on the way out, and this did not undo\n // it, so a literal containing an apostrophe grew on every trip: O'Brien →\n // O''Brien → O''''Brien, doubling each time a policy was read back and\n // recompiled. Past the first trip the emitted policy compares against a\n // string no row holds.\n const literal = parseSingleQuoted(str);\n if (literal !== null) {\n return policy.literal(literal);\n }\n\n // Unquoted literals, which must be recognised BEFORE the bare-word branch\n // below or they are read as column names.\n //\n // `quoteLiteral` emits booleans, numbers and null unquoted, so `a = false`\n // came back as a comparison against a *field* called `false`, and `a = 42`\n // against a field called `42`. The recompiled SQL is identical either way,\n // which is why this survived a round-trip check on the SQL — but the\n // expression is now wrong, and the expression is what the admin UI\n // evaluates. Against a row with no `a`, Postgres denies (`NULL = false` is\n // not true) while the JS evaluator compared two missing columns, found them\n // equal, and allowed. That is precisely the client/database drift the\n // shared PolicyExpression model exists to make impossible.\n //\n // Unambiguous in both directions: a SQL identifier cannot begin with a\n // digit, and bare `true`/`false`/`null` are always the literals — a column\n // so named would have to be double-quoted to be referenced at all.\n //\n // Only a number a JS `number` holds exactly. The literal is re-emitted from\n // the parsed value, so `org_id = 1234567890123456789` came back as\n // `org_id = 1234567890123456800` — a comparison against another tenant's\n // id, written into the database as the policy. Anything wider stays `raw`.\n if (/^-?\\d+$/.test(str) || /^-?\\d*\\.\\d+$/.test(str)) {\n return isExactNumber(str) ? policy.literal(Number(str)) : null;\n }\n if (/^true$/i.test(str)) return policy.literal(true);\n if (/^false$/i.test(str)) return policy.literal(false);\n if (/^null$/i.test(str)) return policy.literal(null);\n\n // Bare field name — but only one that survives the snake-casing the\n // compiler will apply to it. `toSnakeCase(\"_\")` is the empty string, and a\n // field that compiles to an empty column reference emits `= 'x'`, which is\n // a syntax error at CREATE POLICY time. Such a name is left to `raw`, where\n // it round-trips verbatim instead. `toSnakeCase` itself is not touched:\n // column names derived by it are already in shipped databases.\n if (/^\\w+$/.test(str) && toSnakeCase(str) !== \"\") {\n return policy.field(str);\n }\n\n return null;\n}\n\n/**\n * Whether the decimal numeral `str` survives a trip through a JS `number` and\n * back to text with its value intact: `0.50` does (as `0.5`), `2^53 + 1` and\n * a twentieth decimal place do not.\n */\nfunction isExactNumber(str: string): boolean {\n const negative = str.startsWith(\"-\");\n const [whole, fraction = \"\"] = (negative ? str.slice(1) : str).split(\".\");\n const digits = whole.replace(/^0+(?=\\d)/, \"\") || \"0\";\n const decimals = fraction.replace(/0+$/, \"\");\n const canonical = decimals ? `${digits}.${decimals}` : digits;\n const value = Number(str);\n return String(Math.abs(value)) === canonical;\n}\n\n/**\n * Decode a single-quoted SQL literal, or null when `str` is not exactly one.\n *\n * Rejecting is as important as decoding: `'a' = 'b'` is two literals and an\n * operator, not one literal whose body contains a quote, and a regex anchored\n * on the outer quotes would happily read it as the latter. Every interior quote\n * must therefore be part of a `''` pair.\n */\nfunction parseSingleQuoted(str: string): string | null {\n if (str.length < 2 || !str.startsWith(\"'\") || !str.endsWith(\"'\")) return null;\n const body = str.slice(1, -1);\n let out = \"\";\n for (let i = 0; i < body.length; i++) {\n if (body[i] !== \"'\") {\n out += body[i];\n continue;\n }\n if (body[i + 1] === \"'\") {\n out += \"'\";\n i++;\n continue;\n }\n return null; // a bare quote — `str` is not a single literal\n }\n return out;\n}\n","import {\n isPolicyExpressionKind,\n isPolicyShorthand,\n policy,\n type PolicyCondition,\n type PolicyExpression,\n type PolicyShorthand\n} from \"@rebasepro/types\";\n\n/**\n * Where a condition sits, for the messages {@link policyConditionToExpression}\n * refuses one with: the table, when known, and which clause.\n */\nexport interface PolicyConditionSite {\n table?: string;\n clause?: \"condition\" | \"check\";\n}\n\n/**\n * The {@link PolicyExpression} a rule's `condition` / `check` stands for.\n *\n * An expression is returned as it is — the same object, so a rule written in\n * the long form compiles exactly as it always has. A {@link PolicyShorthand}\n * is desugared, its columns in sorted order (so the SQL, like the policy\n * name, does not depend on the order the keys were written in):\n *\n * - `{ col: value }` → `policy.compare(policy.field(\"col\"), \"eq\", policy.literal(value))`\n * - `{ col: null }` → `policy.raw(\"{col} IS NULL\")` — no comparison is ever\n * true against NULL, so `IS NULL` is the only spelling that means it. Being\n * `raw`, it is server-authoritative: the JavaScript evaluator answers\n * `\"unknown\"` for it, which enforcement callers resolve fail-closed.\n * - several keys → `policy.and(...)` of the above.\n *\n * Refused, with the table and clause named: an object with a `kind` key that\n * no expression node has (a column called `kind`, or a misspelt node — the\n * two cannot be told apart, so neither is guessed), an empty object (an AND\n * of nothing is `true`, which would grant every row), and a value that is not\n * a string, finite number, boolean or `null`.\n */\nexport function policyConditionToExpression(condition: PolicyCondition, site: PolicyConditionSite = {}): PolicyExpression {\n if (isPolicyShorthand(condition)) return shorthandToExpression(condition, site);\n if (isPolicyExpressionKind(condition.kind)) return condition;\n throw new Error(describeInvalidCondition(condition, site));\n}\n\n/**\n * The columns a {@link PolicyShorthand} condition / check names, sorted — or\n * an empty list for anything else. What a compiler checks against the table.\n */\nexport function policyShorthandColumns(condition: PolicyCondition | undefined): string[] {\n return isPolicyShorthand(condition) ? Object.keys(condition).sort() : [];\n}\n\nfunction shorthandToExpression(shorthand: PolicyShorthand, site: PolicyConditionSite): PolicyExpression {\n const terms = Object.keys(shorthand).sort().map((column): PolicyExpression => {\n const value = shorthand[column];\n if (value !== null) return policy.compare(policy.field(column), \"eq\", policy.literal(value));\n // `raw` resolves `{column}` through the table's property → column\n // mapping, as a field operand does; the placeholder only reads a word.\n if (!/^\\w+$/.test(column)) {\n throw new Error(\n `${where(site)} says \\`${JSON.stringify(column)}: null\\`, and a shorthand can only test a column ` +\n \"whose key is a plain identifier for NULL. Write the test as raw SQL: \" +\n \"`policy.raw(\\\"<column> IS NULL\\\")`.\"\n );\n }\n return policy.raw(`{${column}} IS NULL`);\n });\n return terms.length === 1 ? terms[0] : policy.and(...terms);\n}\n\nconst isShorthandValue = (value: unknown): boolean =>\n value === null || typeof value === \"string\" || typeof value === \"boolean\"\n || (typeof value === \"number\" && Number.isFinite(value));\n\nfunction where(site: PolicyConditionSite): string {\n const clause = `\\`${site.clause ?? \"condition\"}\\``;\n return site.table ? `A rule on \"${site.table}\" with a ${clause}` : `A rule's ${clause}`;\n}\n\nfunction describeInvalidCondition(condition: unknown, site: PolicyConditionSite): string {\n if (typeof condition !== \"object\" || condition === null || Array.isArray(condition)) {\n return `${where(site)} is ${JSON.stringify(condition)}, which is neither a policy expression nor a ` +\n \"shorthand object such as `{ status: \\\"published\\\" }`.\";\n }\n const entries = Object.entries(condition);\n if (entries.length === 0) {\n return `${where(site)} is \\`{}\\`. A shorthand with no column matches every row; write ` +\n \"`policy.true()` if that is meant, or name the columns to match.\";\n }\n if (\"kind\" in condition) {\n return `${where(site)} has \\`kind: ${JSON.stringify(condition.kind)}\\`, which is ` +\n \"no policy expression. If it means a column called `kind`, a shorthand cannot say so — `kind` is how \" +\n \"an expression is recognised — so write it longhand: \" +\n \"`policy.compare(policy.field(\\\"kind\\\"), \\\"eq\\\", policy.literal(…))`.\";\n }\n const bad = entries.find(([, value]) => !isShorthandValue(value));\n const column = bad?.[0] ?? entries[0][0];\n return `${where(site)} gives the column \"${column}\" the value ${JSON.stringify(bad?.[1])}. A shorthand ` +\n \"compares each column with a string, a number, a boolean or `null`; write anything else as a policy \" +\n \"expression.\";\n}\n","import { PolicyExpression, SecurityRule, isRedactedSecurityRule, policy } from \"@rebasepro/types\";\nimport { sqlToPolicy } from \"./sqlToPolicy\";\nimport { policyConditionToExpression, type PolicyConditionSite } from \"./policyCondition\";\n\n/**\n * The normalized `USING` / `WITH CHECK` conditions for a single security rule,\n * expressed in the engine-agnostic {@link PolicyExpression} model.\n *\n * A `null` clause means \"this rule contributes no condition for that clause\";\n * consumers apply the default (Postgres denies with `false`).\n */\nexport interface RuleConditions {\n usingExpr: PolicyExpression | null;\n withCheckExpr: PolicyExpression | null;\n}\n\n/**\n * Desugars a {@link SecurityRule} — its `access`/`ownerField`/`roles` shortcuts,\n * structured `condition`/`check` (an expression or the `PolicyShorthand`\n * object form, see {@link policyConditionToExpression}), and raw\n * `using`/`withCheck` — into a single normalized {@link PolicyExpression}\n * pair. `access` combined with a condition gates it: `\"public\"` leaves the\n * condition as it is, `\"authenticated\"` ANDs `policy.authenticated()` on,\n * `\"registered\"` ANDs `policy.registered()` on.\n *\n * Total: every clause a rule carries is ANDed in, never dropped because\n * another is present. The compiler refuses the combinations the\n * `SecurityRule` union excludes (`access` beside `ownerField` or raw SQL,\n * `ownerField` beside a condition…, see `ruleShapeProblems`); should one\n * reach here anyway, it compiles to the conjunction — as narrow as every\n * clause in it — rather than to whichever clause was checked first.\n *\n * **This is the linchpin against drift:** both the Postgres DDL generators and\n * the client-side evaluator consume this one function, so there is exactly one\n * definition of what a rule means. In particular, application `roles` are folded\n * into the expression here (AND'd with the base condition, matching how Postgres\n * generates the clause) rather than being handled separately by each consumer.\n *\n * A {@link RedactedSecurityRule} (the marker the server sends for a rule whose\n * SQL it withheld) desugars to a raw node for both clauses — still gated by\n * its `access` and `roles` — so the evaluator answers it \"unknown\", exactly as\n * it answers a raw rule. No policy is ever compiled from one:\n * `compileTableRulePolicies` refuses it before it gets here.\n */\nexport function securityRuleToConditions(rule: SecurityRule, site: Pick<PolicyConditionSite, \"table\"> = {}): RuleConditions {\n return {\n usingExpr: withRoles(baseUsing(rule, site), rule),\n withCheckExpr: withRoles(baseWithCheck(rule, site), rule)\n };\n}\n\n/**\n * The caller test an `access` value stands for, or `undefined` for none:\n * `\"public\"` tests nothing (`true AND c` is `c`), `\"authenticated\"` is\n * `policy.authenticated()`, `\"registered\"` is `policy.registered()`. A value\n * the type does not know — a JavaScript caller, a cast, a typo — admits\n * nobody: the compiler refuses such a rule before it gets here, and this\n * keeps the desugaring total and closed for any caller that did not.\n */\nfunction accessTest(access: unknown): PolicyExpression | undefined {\n if (access === undefined || access === null || access === \"public\") return undefined;\n if (access === \"authenticated\") return policy.authenticated();\n if (access === \"registered\") return policy.registered();\n return policy.false();\n}\n\n/**\n * Every term of a clause, ANDed under the rule's `access` test: one term\n * alone is returned as it is (so a rule of one clause compiles exactly as it\n * always has), `access` gates it as `and(test, term)`, and several terms —\n * a combination the compiler refuses, reaching here only from a caller that\n * skipped it — are all kept. A clause is never dropped for another: the\n * result is at least as narrow as every clause the rule carries.\n */\nfunction conjoin(access: unknown, terms: readonly PolicyExpression[]): PolicyExpression | null {\n const test = accessTest(access);\n if (terms.length === 0) {\n if (test) return test;\n return access === \"public\" ? policy.true() : null;\n }\n const body = terms.length === 1 ? terms[0] : policy.and(...terms);\n if (!test) return body;\n return terms.length === 1 ? policy.and(test, body) : policy.and(test, ...terms);\n}\n\n/** What a withheld clause desugars to: SQL nobody here can evaluate. */\nconst REDACTED_CLAUSE_SQL = \"/* withheld by the server */\";\n\nfunction ownerTerm(rule: SecurityRule): PolicyExpression[] {\n return rule.ownerField ? [policy.compare(policy.field(rule.ownerField), \"eq\", policy.authUid())] : [];\n}\n\n/**\n * The `USING` clause: the `access` test ANDed with every row clause the rule\n * carries — `ownerField`, `condition`, raw `using`. Total: no clause is\n * dropped because another one is present, whatever the order of the checks.\n */\nfunction baseUsing(rule: SecurityRule, site: Pick<PolicyConditionSite, \"table\">): PolicyExpression | null {\n if (isRedactedSecurityRule(rule)) return conjoin(rule.access, [policy.raw(REDACTED_CLAUSE_SQL)]);\n const terms: PolicyExpression[] = [...ownerTerm(rule)];\n if (rule.condition != null) terms.push(policyConditionToExpression(rule.condition, { ...site, clause: \"condition\" }));\n if (rule.using != null) terms.push(sqlToPolicy(rule.using));\n return conjoin(rule.access, terms);\n}\n\n/**\n * The `WITH CHECK` clause. `check` stands in for `condition` and `withCheck`\n * for `using` (each defaults to its counterpart, as Postgres does); with\n * neither, the clause is the `USING` clause. Like {@link baseUsing}, every\n * clause present is ANDed under the `access` test.\n */\nfunction baseWithCheck(rule: SecurityRule, site: Pick<PolicyConditionSite, \"table\">): PolicyExpression | null {\n if (isRedactedSecurityRule(rule)) return conjoin(rule.access, [policy.raw(REDACTED_CLAUSE_SQL)]);\n if (rule.check == null && rule.withCheck == null) return baseUsing(rule, site);\n const terms: PolicyExpression[] = [...ownerTerm(rule)];\n if (rule.check != null) terms.push(policyConditionToExpression(rule.check, { ...site, clause: \"check\" }));\n else if (rule.condition != null) terms.push(policyConditionToExpression(rule.condition, { ...site, clause: \"condition\" }));\n if (rule.withCheck != null) terms.push(sqlToPolicy(rule.withCheck));\n else if (rule.using != null) terms.push(sqlToPolicy(rule.using));\n return conjoin(rule.access, terms);\n}\n\n/**\n * AND the base condition with an application-role check, or produce a roles-only\n * condition when there is no base. Mirrors the Postgres generator so that a\n * role-scoped restrictive rule denies exactly the same set of users on both\n * sides.\n */\nfunction withRoles(base: PolicyExpression | null, rule: SecurityRule): PolicyExpression | null {\n if (!rule.roles || rule.roles.length === 0) return base;\n const rolesExpr = policy.rolesOverlap(rule.roles);\n if (rule.mode === \"restrictive\") {\n // Restrictive rule: applies ONLY if user has the roles.\n // If user DOES NOT have the roles, they are NOT restricted (passes).\n // If user HAS the roles, they must pass the base condition.\n // Logical equivalent: NOT(roles) OR base\n return base ? policy.or(policy.not(rolesExpr), base) : policy.not(rolesExpr);\n }\n return base ? policy.and(base, rolesExpr) : rolesExpr;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAS,YAAY,OAAe,GAAW,SAA0B;CACrE,IAAI,CAAC,MAAM,WAAW,SAAS,CAAC,GAAG,OAAO;CAC1C,MAAM,SAAS,MAAM,IAAI,MAAM,MAAM,IAAI;CACzC,MAAM,QAAQ,MAAM,IAAI,QAAQ,WAAW;CAC3C,OAAO,SAAS,KAAK,MAAM,KAAK,SAAS,KAAK,KAAK;AACvD;;;;;;;;;;;;;;;AAgBA,SAAS,cAAc,KAAa,SAAwC;CACxE,MAAM,QAAQ,IAAI,YAAY;CAC9B,MAAM,QAAkB,CAAC;CACzB,IAAI,QAAQ;CACZ,IAAI,WAAW;CACf,IAAI,QAAQ;CAEZ,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;EACjC,MAAM,KAAK,IAAI;EACf,IAAI,UAAU;GACV,IAAI,OAAO,KACP,IAAI,IAAI,IAAI,OAAO,KAAK;QACnB,WAAW;GAEpB;EACJ;EACA,IAAI,OAAO,KAAK;GAAE,WAAW;GAAM;EAAU;EAC7C,IAAI,OAAO,KAAK;GAAE;GAAS;EAAU;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AO,OAAO,IAAI,MAAM,SAAS,IAAI;AAChD"}
1
+ {"version":3,"file":"securityRuleToConditions-Bk5zRSoa.js","names":[],"sources":["../../common/src/util/policy/sqlToPolicy.ts","../../common/src/util/policy/policyCondition.ts","../../common/src/util/policy/securityRuleToConditions.ts"],"sourcesContent":["import { ANONYMOUS_USER_ID, ANONYMOUS_USER_IDS, LiteralPolicyOperand, PolicyExpression, policy, rewriteLegacyRlsFunctions } from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\n\n/**\n * A tiny, regex-based SQL \"parser\" for security rules.\n *\n * This is NOT a full SQL parser. It is designed to handle the subset of SQL\n * commonly used in `USING` and `WITH CHECK` clauses, enough to drive the\n * optimistic client-side UI decision.\n *\n * It handles:\n * - `field = 'literal'`\n * - `field != 'literal'`\n * - `field = current_setting('app.uid')` (or the legacy `app.user_id`)\n * - `A AND B`, `A OR B` — only where the keyword is at the top level\n * - `true`\n * - `IN (...)` (as optimistic true)\n *\n * For anything it doesn't understand, it returns a `raw` expression, which\n * the evaluator treats as \"unknown\" (and usually optimistic true).\n *\n * **This output also round-trips back into DDL** via `compilePolicyExpression` (the\n * schema/policy generators), so decomposing a clause the parser only partly\n * understands is not a cosmetic mistake — it emits invalid SQL. When in doubt,\n * prefer `raw`: it is reproduced verbatim.\n */\n/** True when `keyword` starts at `i` as a standalone word. */\nfunction isKeywordAt(upper: string, i: number, keyword: string): boolean {\n if (!upper.startsWith(keyword, i)) return false;\n const before = i === 0 ? \" \" : upper[i - 1];\n const after = upper[i + keyword.length] ?? \" \";\n return /[\\s()]/.test(before) && /[\\s()]/.test(after);\n}\n\n/**\n * Split `sql` on a boolean keyword, but only where it sits at paren depth 0 and\n * outside a string literal. Returns null when it never does, so the caller\n * leaves the clause alone.\n *\n * This used to be `sql.split(/ AND /i)`, which tore subqueries in half: the\n * `AND` inside\n * `EXISTS (SELECT 1 FROM organization_members m WHERE m.org = t.org AND m.user_id = rebase.uid())`\n * split the expression, and re-emitting the halves produced\n * `(EXISTS (...) AND m.user_id = rebase.uid())`\n * where `m` is no longer in scope — SQL that Postgres rejects outright with\n * \"missing FROM-clause entry for table\". Returning null instead keeps such a\n * clause as a `raw` expression, which round-trips verbatim.\n */\nfunction splitTopLevel(sql: string, keyword: \"AND\" | \"OR\"): string[] | null {\n const upper = sql.toUpperCase();\n const parts: string[] = [];\n let depth = 0;\n let inString = false;\n let start = 0;\n\n for (let i = 0; i < sql.length; i++) {\n const ch = sql[i];\n if (inString) {\n if (ch === \"'\") {\n if (sql[i + 1] === \"'\") i++; // '' escapes a quote inside a literal\n else inString = false;\n }\n continue;\n }\n if (ch === \"'\") { inString = true; continue; }\n if (ch === \"(\") { depth++; continue; }\n if (ch === \")\") { depth--; continue; }\n if (depth === 0 && isKeywordAt(upper, i, keyword)) {\n parts.push(sql.slice(start, i));\n i += keyword.length - 1;\n start = i + 1;\n }\n }\n\n if (parts.length === 0) return null;\n parts.push(sql.slice(start));\n const trimmedParts = parts.map(p => p.trim()).filter(p => p.length > 0);\n return trimmedParts.length > 1 ? trimmedParts : null;\n}\n\n/** `SELECT` as the first word of `sql`. */\nconst STARTS_WITH_SELECT = /^select(?=[\\s(])/i;\n\n/**\n * Drop redundant wrapping parens (`(a AND b)` → `a AND b`), never `(a) AND (b)`\n * — and never the parens of a scalar subquery: `(SELECT x)` without them is not\n * an expression at all, and re-emitted bare it is a syntax error inside\n * `USING (…)`.\n */\nfunction stripOuterParens(sql: string): string {\n let s = sql.trim();\n while (wrapsWhole(s) && !STARTS_WITH_SELECT.test(s.slice(1).trim())) {\n s = s.slice(1, -1).trim();\n }\n return s;\n}\n\n/** Whether `s` is one parenthesised group: `(a AND b)`, not `(a) AND (b)`. */\nfunction wrapsWhole(s: string): boolean {\n if (!s.startsWith(\"(\") || !s.endsWith(\")\")) return false;\n let depth = 0;\n let inString = false;\n for (let i = 0; i < s.length; i++) {\n const ch = s[i];\n if (inString) {\n if (ch === \"'\") {\n if (s[i + 1] === \"'\") i++;\n else inString = false;\n }\n continue;\n }\n if (ch === \"'\") { inString = true; continue; }\n if (ch === \"(\") depth++;\n else if (ch === \")\") {\n depth--;\n if (depth === 0 && i < s.length - 1) return false;\n }\n }\n return true;\n}\n\n/** `x` when `s` is exactly `(SELECT x)`, otherwise null. */\nfunction scalarSubqueryBody(s: string): string | null {\n if (!wrapsWhole(s)) return null;\n const inner = s.slice(1, -1).trim();\n return STARTS_WITH_SELECT.test(inner) ? inner.slice(\"select\".length).trim() : null;\n}\n\n/**\n * The names in a role array's body — `'admin', 'editor'`, each with or without\n * Postgres's `::text` — or `null` when an element is anything else. A quote\n * or a comma inside a name is not split into roles that were never there: the\n * clause stays raw and round-trips verbatim.\n */\nfunction roleArrayElements(list: string): string[] | null {\n const roles: string[] = [];\n for (const element of list.split(\",\")) {\n const match = /^'([^',]*)'(?:::text)?$/.exec(element.trim());\n if (!match) return null;\n roles.push(match[1]);\n }\n return roles;\n}\n\n/** Whether any part of `expr` fell through to `raw`. */\nfunction containsRaw(expr: PolicyExpression): boolean {\n switch (expr.kind) {\n case \"raw\":\n return true;\n case \"and\":\n case \"or\":\n return expr.operands.some(containsRaw);\n case \"not\":\n return containsRaw(expr.operand);\n case \"existsIn\":\n return containsRaw(expr.where);\n default:\n return false;\n }\n}\n\nexport function sqlToPolicy(sql: string): PolicyExpression {\n // Normalised before anything else looks at it, so every pattern below only\n // has to know the current spelling. A database migrated by a pre-1.0 release\n // still holds `auth.uid()` in its policy bodies until the next push or boot\n // recompiles them — and until then the admin UI reads those bodies back\n // through here. Without this they parse as opaque `raw`, and the framework's\n // own policies get badged as hand-written drift.\n //\n // Normalising rather than accepting both spellings throughout is deliberate:\n // it also means a legacy policy that falls through to `raw` is stored in the\n // new spelling, so editing and saving one in the Studio migrates it.\n const trimmed = stripOuterParens(rewriteLegacyRlsFunctions(sql).trim());\n\n // `(SELECT x)` — how the compiler spells a part of a policy that does not\n // read the row, so Postgres evaluates it once per statement. Read back as\n // `x` when `x` is understood completely: without a FROM a scalar subquery\n // is one row holding x's value, so the two mean the same. Anything less —\n // a FROM, a LIMIT, an alias, a clause the parser does not know — stays\n // `raw`, parens included, and is reproduced verbatim.\n const subqueryBody = scalarSubqueryBody(trimmed);\n if (subqueryBody !== null) {\n const inner = sqlToPolicy(subqueryBody);\n return containsRaw(inner) ? policy.raw(trimmed) : inner;\n }\n\n if (trimmed.toLowerCase() === \"true\") return policy.true();\n if (trimmed.toLowerCase() === \"false\") return policy.false();\n\n // Handle roles overlap (&&) and containment (@>), as the compiler writes\n // them and as Postgres stores them:\n // string_to_array(rebase.roles(), ',') && ARRAY['admin', 'editor']\n // string_to_array(rebase.roles(), ','::text) && ARRAY['admin'::text, 'editor'::text]\n // The second is what `pg_policies` holds, so what `schema introspect`\n // writes as a rule's `using`. Read as raw, a junction could not inherit\n // the rule, and its derived edge-write policies were left with none.\n const rolesMatch = trimmed.match(/^string_to_array\\s*\\(\\s*rebase\\.roles\\(\\)\\s*,\\s*','(?:::text)?\\s*\\)\\s*(&&|@>)\\s*ARRAY\\s*\\[(.+)\\]$/i);\n const roles = rolesMatch ? roleArrayElements(rolesMatch[2]) : null;\n if (rolesMatch && roles) {\n return rolesMatch[1] === \"&&\" ? policy.rolesOverlap(roles) : policy.rolesContain(roles);\n }\n\n // OR binds looser than AND, so it splits first.\n const orParts = splitTopLevel(trimmed, \"OR\");\n if (orParts) return policy.or(...orParts.map(sqlToPolicy));\n\n const andParts = splitTopLevel(trimmed, \"AND\");\n if (andParts) return policy.and(...andParts.map(sqlToPolicy));\n\n // Handle = and !=\n const match = trimmed.match(/^(.+?)\\s*(!?=)\\s*(.+)$/);\n if (match) {\n const [, leftStr, op, rightStr] = match;\n const left = parseOperand(leftStr.trim());\n const right = parseOperand(rightStr.trim());\n if (left && right) {\n return policy.compare(left, op === \"=\" ? \"eq\" : \"neq\", right);\n }\n }\n\n // Fallback to raw — the NORMALISED text, not the input. Storing the input\n // verbatim would mean a legacy policy read out of a database, edited in the\n // Studio and saved, writes `auth.uid()` back into the project's config: a\n // call to a function 1.0 no longer creates.\n return policy.raw(trimmed);\n}\n\n/**\n * Literals from other BaaS platforms that people compare `rebase.uid()` against\n * out of habit. Mirrors the driver's `FOREIGN_CONVENTION_ROLES` guard on\n * `pgRoles`, one surface over: the same muscle memory inside a `using:` string\n * is the more dangerous spelling, because it inverts a rule instead of\n * emptying a table.\n */\n/**\n * A `Map`, not an object literal.\n *\n * As `Record<string, string>` this was indexed with a literal taken straight\n * out of a policy, so every key on `Object.prototype` answered: a rule\n * comparing `rebase.uid()` to `\"valueOf\"`, `\"toString\"`, `\"constructor\"` or\n * `\"hasOwnProperty\"` found a truthy \"platform\" and reported an anonymous-grant\n * risk that does not exist — with the matched function interpolated into the\n * explanation as the platform's name. A security warning that fires on\n * innocent input is worse than none: it is what teaches people to skip the\n * warnings that are real.\n *\n * Same shape as the prototype-pollution class swept out of `setIn`, `getIn`,\n * `mergeDeep` and `unflattenObject` — a data-derived key reaching a plain\n * object. Found by a property test, on the input `\"valueOf\"`.\n */\nconst FOREIGN_CONVENTION_UIDS = new Map<string, string>([\n [\"anon\", \"Supabase\"],\n [\"authenticated\", \"Supabase\"],\n [\"service_role\", \"Supabase\"]\n]);\n\n/**\n * The same foreign literals, as a pattern for SQL that could not be parsed\n * back into structure.\n */\nconst FOREIGN_UID_LITERAL_SQL = new RegExp(\n String.raw`rebase\\.uid\\(\\)\\s*=\\s*'(${[...FOREIGN_CONVENTION_UIDS.keys()].join(\"|\")})'`,\n \"i\"\n);\n\n/** A clause that reads as a lockdown but admits anonymous callers. */\nexport interface AnonymousGrantRisk {\n /** Which spelling was found. */\n pattern: \"foreign-uid-literal\" | \"uid-not-null\";\n /** The offending fragment — the literal, or the SQL that is a tautology. */\n detail: string;\n /** Why it admits anonymous callers, and what to write instead. */\n explanation: string;\n}\n\n/**\n * `rebase.uid() IS NOT NULL` in raw SQL, the clause that is always true.\n *\n * Both schema spellings, because this runs over policy bodies read back from a\n * database, and one migrated by a pre-1.0 release still holds `auth.uid()`.\n * A security check that stops recognising a dangerous clause because the\n * framework renamed a function is a check that silently turns off.\n */\nconst UID_NOT_NULL = /\\b(?:rebase|auth)\\.uid\\(\\)\\s+IS\\s+NOT\\s+NULL/i;\n\n/**\n * Find clauses that read as \"signed-in users only\" but admit anonymous callers.\n *\n * Both spellings come from the same place — Supabase, where its own `auth.uid()`\n * really is NULL for an anonymous request. Rebase substitutes\n * {@link ANONYMOUS_USER_ID} instead (a blank id would read back as NULL, which\n * is how the trusted *server* context is recognised), so:\n *\n * - `rebase.uid() IS NOT NULL` is a tautology on the user path, and\n * - `rebase.uid() != 'anon'` excludes one spelling of anonymous and admits the\n * other. This one is not hypothetical and was not only a foreign habit:\n * rebase's own request path reported `'anon'` while everything that compiled\n * or checked a policy used `'anonymous'`, so whichever literal an author\n * picked, half the anonymous callers walked through. See\n * {@link ANONYMOUS_USER_IDS}.\n *\n * Either one turns a lockdown into a full grant, and neither looks wrong. No\n * real user id is ever one of these literals, and a user-context request is\n * never NULL, so a match is always a mistake rather than a deliberate check.\n *\n * Structured expressions are checked too, not just parsed SQL: `policy.compare`\n * can spell the same mistake.\n */\nexport function findAnonymousGrants(expr: PolicyExpression): AnonymousGrantRisk[] {\n const found: AnonymousGrantRisk[] = [];\n\n const visit = (e: PolicyExpression): void => {\n switch (e.kind) {\n case \"and\":\n case \"or\":\n e.operands.forEach(visit);\n return;\n case \"not\":\n visit(e.operand);\n return;\n case \"existsIn\":\n visit(e.where);\n return;\n case \"raw\": {\n if (UID_NOT_NULL.test(e.sql)) {\n found.push({\n pattern: \"uid-not-null\",\n detail: e.sql,\n explanation: \"`rebase.uid() IS NOT NULL` is true for every request that came from a client, \" +\n `including anonymous ones — they carry '${ANONYMOUS_USER_ID}', not NULL. ` +\n \"Use `condition: policy.authenticated()` to mean \\\"signed in\\\".\"\n });\n }\n // The foreign literals have to be looked for here too, not only\n // in `compare`. `sqlToPolicy` falls back to `raw` for anything\n // it cannot structure — an `EXISTS (...)` subquery always does —\n // so a policy read back from the database arrives as one opaque\n // string. Checking only the tautology meant a genuine\n // `rebase.uid() = 'anon'` inside an `existsIn` was structurally\n // undetectable once round-tripped, and the caller read the empty\n // result as \"no risks found\".\n const foreign = FOREIGN_UID_LITERAL_SQL.exec(e.sql);\n if (foreign) {\n const literal = foreign[1];\n found.push({\n pattern: \"foreign-uid-literal\",\n detail: literal,\n explanation: `'${literal}' is a ${FOREIGN_CONVENTION_UIDS.get(literal)} convention. Rebase ` +\n `reports an anonymous request as '${ANONYMOUS_USER_ID}', so comparing against ` +\n `'${literal}' passes for every caller. Use \\`condition: policy.authenticated()\\` to ` +\n \"mean \\\"signed in\\\".\"\n });\n }\n return;\n }\n case \"compare\": {\n const literal = [e.left, e.right].find(o => o.kind === \"literal\") as LiteralPolicyOperand | undefined;\n const comparesUid = e.left.kind === \"authUid\" || e.right.kind === \"authUid\";\n if (!comparesUid || typeof literal?.value !== \"string\") return;\n const platform = FOREIGN_CONVENTION_UIDS.get(literal.value);\n if (!platform) return;\n found.push({\n pattern: \"foreign-uid-literal\",\n detail: literal.value,\n explanation: `'${literal.value}' is a ${platform} convention. Rebase reports an anonymous ` +\n `request as '${ANONYMOUS_USER_ID}', so comparing against '${literal.value}' passes for ` +\n \"every caller. Use `condition: policy.authenticated()` to mean \\\"signed in\\\" — it \" +\n `compiles to NOT IN (${ANONYMOUS_USER_IDS.map(v => `'${v}'`).join(\", \")}), covering ` +\n \"every spelling rebase has reported rather than whichever one you remember.\"\n });\n return;\n }\n default:\n return;\n }\n };\n\n visit(expr);\n return found;\n}\n\nfunction parseOperand(str: string) {\n // current_setting('app.uid') or rebase.uid(). `app.user_id` is the\n // pre-rename spelling and stays parseable: policies are data, so a\n // database provisioned before the rename still holds rules written\n // against it, and round-tripping one must not silently drop the operand.\n //\n // ANCHORED, and that is the whole point. These tests used to be\n // unanchored — `.test(str)` rather than `^…$` — so any operand text that\n // merely *contained* a uid call was replaced wholesale by the call itself.\n // Everything else in the expression was discarded with it, including a\n // leading `NOT (`:\n //\n // NOT (rebase.uid() = rebase.uid()) parsed as rebase.uid() = rebase.uid()\n //\n // A deny became an unconditional grant. The realistic spelling is a\n // hand-written defensive rule with a uid call on both sides —\n // COALESCE(rebase.uid(), '') = COALESCE(owner_id, rebase.uid())\n // — which collapsed to the same tautology. This is not confined to the\n // admin UI: `securityRuleToConditions` feeds a rule's raw `using:` string\n // through here, and the Postgres DDL generators compile the result, so the\n // tautology was written into the database as the policy body.\n //\n // An operand this cannot identify exactly must return null, which drops the\n // whole clause to `raw` and reproduces it verbatim. That is the rule the\n // rest of this file already follows: when in doubt, prefer `raw`.\n if (/^current_setting\\s*\\(\\s*'app\\.(uid|user_id)'\\s*\\)$/i.test(str) || /^rebase\\.uid\\(\\)$/i.test(str)) {\n return policy.authUid();\n }\n // The same call as an initPlan — the compiler's spelling, `(SELECT\n // rebase.uid())`, and Postgres's re-rendering of it, `( SELECT rebase.uid()\n // AS uid)`. Anchored like the line above, for the same reason.\n if (/^\\(\\s*select\\s+rebase\\.uid\\(\\)(?:\\s+as\\s+\"?uid\"?)?\\s*\\)$/i.test(str)) {\n return policy.authUid();\n }\n\n // Literal string: 'value', with `''` decoded back to a single quote.\n //\n // `quoteLiteral` doubles every quote on the way out, and this did not undo\n // it, so a literal containing an apostrophe grew on every trip: O'Brien →\n // O''Brien → O''''Brien, doubling each time a policy was read back and\n // recompiled. Past the first trip the emitted policy compares against a\n // string no row holds.\n const literal = parseSingleQuoted(str);\n if (literal !== null) {\n return policy.literal(literal);\n }\n\n // Unquoted literals, which must be recognised BEFORE the bare-word branch\n // below or they are read as column names.\n //\n // `quoteLiteral` emits booleans, numbers and null unquoted, so `a = false`\n // came back as a comparison against a *field* called `false`, and `a = 42`\n // against a field called `42`. The recompiled SQL is identical either way,\n // which is why this survived a round-trip check on the SQL — but the\n // expression is now wrong, and the expression is what the admin UI\n // evaluates. Against a row with no `a`, Postgres denies (`NULL = false` is\n // not true) while the JS evaluator compared two missing columns, found them\n // equal, and allowed. That is precisely the client/database drift the\n // shared PolicyExpression model exists to make impossible.\n //\n // Unambiguous in both directions: a SQL identifier cannot begin with a\n // digit, and bare `true`/`false`/`null` are always the literals — a column\n // so named would have to be double-quoted to be referenced at all.\n //\n // Only a number a JS `number` holds exactly. The literal is re-emitted from\n // the parsed value, so `org_id = 1234567890123456789` came back as\n // `org_id = 1234567890123456800` — a comparison against another tenant's\n // id, written into the database as the policy. Anything wider stays `raw`.\n if (/^-?\\d+$/.test(str) || /^-?\\d*\\.\\d+$/.test(str)) {\n return isExactNumber(str) ? policy.literal(Number(str)) : null;\n }\n if (/^true$/i.test(str)) return policy.literal(true);\n if (/^false$/i.test(str)) return policy.literal(false);\n if (/^null$/i.test(str)) return policy.literal(null);\n\n // Bare field name — but only one that survives the snake-casing the\n // compiler will apply to it. `toSnakeCase(\"_\")` is the empty string, and a\n // field that compiles to an empty column reference emits `= 'x'`, which is\n // a syntax error at CREATE POLICY time. Such a name is left to `raw`, where\n // it round-trips verbatim instead. `toSnakeCase` itself is not touched:\n // column names derived by it are already in shipped databases.\n if (/^\\w+$/.test(str) && toSnakeCase(str) !== \"\") {\n return policy.field(str);\n }\n\n return null;\n}\n\n/**\n * Whether the decimal numeral `str` survives a trip through a JS `number` and\n * back to text with its value intact: `0.50` does (as `0.5`), `2^53 + 1` and\n * a twentieth decimal place do not.\n */\nfunction isExactNumber(str: string): boolean {\n const negative = str.startsWith(\"-\");\n const [whole, fraction = \"\"] = (negative ? str.slice(1) : str).split(\".\");\n const digits = whole.replace(/^0+(?=\\d)/, \"\") || \"0\";\n const decimals = fraction.replace(/0+$/, \"\");\n const canonical = decimals ? `${digits}.${decimals}` : digits;\n const value = Number(str);\n return String(Math.abs(value)) === canonical;\n}\n\n/**\n * Decode a single-quoted SQL literal, or null when `str` is not exactly one.\n *\n * Rejecting is as important as decoding: `'a' = 'b'` is two literals and an\n * operator, not one literal whose body contains a quote, and a regex anchored\n * on the outer quotes would happily read it as the latter. Every interior quote\n * must therefore be part of a `''` pair.\n */\nfunction parseSingleQuoted(str: string): string | null {\n if (str.length < 2 || !str.startsWith(\"'\") || !str.endsWith(\"'\")) return null;\n const body = str.slice(1, -1);\n let out = \"\";\n for (let i = 0; i < body.length; i++) {\n if (body[i] !== \"'\") {\n out += body[i];\n continue;\n }\n if (body[i + 1] === \"'\") {\n out += \"'\";\n i++;\n continue;\n }\n return null; // a bare quote — `str` is not a single literal\n }\n return out;\n}\n","import {\n isPolicyExpressionKind,\n isPolicyShorthand,\n policy,\n type PolicyCondition,\n type PolicyExpression,\n type PolicyShorthand\n} from \"@rebasepro/types\";\n\n/**\n * Where a condition sits, for the messages {@link policyConditionToExpression}\n * refuses one with: the table, when known, and which clause.\n */\nexport interface PolicyConditionSite {\n table?: string;\n clause?: \"condition\" | \"check\";\n}\n\n/**\n * The {@link PolicyExpression} a rule's `condition` / `check` stands for.\n *\n * An expression is returned as it is — the same object, so a rule written in\n * the long form compiles exactly as it always has. A {@link PolicyShorthand}\n * is desugared, its columns in sorted order (so the SQL, like the policy\n * name, does not depend on the order the keys were written in):\n *\n * - `{ col: value }` → `policy.compare(policy.field(\"col\"), \"eq\", policy.literal(value))`\n * - `{ col: null }` → `policy.raw(\"{col} IS NULL\")` — no comparison is ever\n * true against NULL, so `IS NULL` is the only spelling that means it. Being\n * `raw`, it is server-authoritative: the JavaScript evaluator answers\n * `\"unknown\"` for it, which enforcement callers resolve fail-closed.\n * - several keys → `policy.and(...)` of the above.\n *\n * Refused, with the table and clause named: an object with a `kind` key that\n * no expression node has (a column called `kind`, or a misspelt node — the\n * two cannot be told apart, so neither is guessed), an empty object (an AND\n * of nothing is `true`, which would grant every row), and a value that is not\n * a string, finite number, boolean or `null`.\n */\nexport function policyConditionToExpression(condition: PolicyCondition, site: PolicyConditionSite = {}): PolicyExpression {\n if (isPolicyShorthand(condition)) return shorthandToExpression(condition, site);\n if (isPolicyExpressionKind(condition.kind)) return condition;\n throw new Error(describeInvalidCondition(condition, site));\n}\n\n/**\n * The columns a {@link PolicyShorthand} condition / check names, sorted — or\n * an empty list for anything else. What a compiler checks against the table.\n */\nexport function policyShorthandColumns(condition: PolicyCondition | undefined): string[] {\n return isPolicyShorthand(condition) ? Object.keys(condition).sort() : [];\n}\n\nfunction shorthandToExpression(shorthand: PolicyShorthand, site: PolicyConditionSite): PolicyExpression {\n const terms = Object.keys(shorthand).sort().map((column): PolicyExpression => {\n const value = shorthand[column];\n if (value !== null) return policy.compare(policy.field(column), \"eq\", policy.literal(value));\n // `raw` resolves `{column}` through the table's property → column\n // mapping, as a field operand does; the placeholder only reads a word.\n if (!/^\\w+$/.test(column)) {\n throw new Error(\n `${where(site)} says \\`${JSON.stringify(column)}: null\\`, and a shorthand can only test a column ` +\n \"whose key is a plain identifier for NULL. Write the test as raw SQL: \" +\n \"`policy.raw(\\\"<column> IS NULL\\\")`.\"\n );\n }\n return policy.raw(`{${column}} IS NULL`);\n });\n return terms.length === 1 ? terms[0] : policy.and(...terms);\n}\n\nconst isShorthandValue = (value: unknown): boolean =>\n value === null || typeof value === \"string\" || typeof value === \"boolean\"\n || (typeof value === \"number\" && Number.isFinite(value));\n\nfunction where(site: PolicyConditionSite): string {\n const clause = `\\`${site.clause ?? \"condition\"}\\``;\n return site.table ? `A rule on \"${site.table}\" with a ${clause}` : `A rule's ${clause}`;\n}\n\nfunction describeInvalidCondition(condition: unknown, site: PolicyConditionSite): string {\n if (typeof condition !== \"object\" || condition === null || Array.isArray(condition)) {\n return `${where(site)} is ${JSON.stringify(condition)}, which is neither a policy expression nor a ` +\n \"shorthand object such as `{ status: \\\"published\\\" }`.\";\n }\n const entries = Object.entries(condition);\n if (entries.length === 0) {\n return `${where(site)} is \\`{}\\`. A shorthand with no column matches every row; write ` +\n \"`policy.true()` if that is meant, or name the columns to match.\";\n }\n if (\"kind\" in condition) {\n return `${where(site)} has \\`kind: ${JSON.stringify(condition.kind)}\\`, which is ` +\n \"no policy expression. If it means a column called `kind`, a shorthand cannot say so — `kind` is how \" +\n \"an expression is recognised — so write it longhand: \" +\n \"`policy.compare(policy.field(\\\"kind\\\"), \\\"eq\\\", policy.literal(…))`.\";\n }\n const bad = entries.find(([, value]) => !isShorthandValue(value));\n const column = bad?.[0] ?? entries[0][0];\n return `${where(site)} gives the column \"${column}\" the value ${JSON.stringify(bad?.[1])}. A shorthand ` +\n \"compares each column with a string, a number, a boolean or `null`; write anything else as a policy \" +\n \"expression.\";\n}\n","import { PolicyExpression, SecurityRule, isRedactedSecurityRule, policy } from \"@rebasepro/types\";\nimport { sqlToPolicy } from \"./sqlToPolicy\";\nimport { policyConditionToExpression, type PolicyConditionSite } from \"./policyCondition\";\n\n/**\n * The normalized `USING` / `WITH CHECK` conditions for a single security rule,\n * expressed in the engine-agnostic {@link PolicyExpression} model.\n *\n * A `null` clause means \"this rule contributes no condition for that clause\";\n * consumers apply the default (Postgres denies with `false`).\n */\nexport interface RuleConditions {\n usingExpr: PolicyExpression | null;\n withCheckExpr: PolicyExpression | null;\n}\n\n/**\n * Desugars a {@link SecurityRule} — its `access`/`ownerField`/`roles` shortcuts,\n * structured `condition`/`check` (an expression or the `PolicyShorthand`\n * object form, see {@link policyConditionToExpression}), and raw\n * `using`/`withCheck` — into a single normalized {@link PolicyExpression}\n * pair. `access` combined with a condition gates it: `\"public\"` leaves the\n * condition as it is, `\"authenticated\"` ANDs `policy.authenticated()` on,\n * `\"registered\"` ANDs `policy.registered()` on.\n *\n * Total: every clause a rule carries is ANDed in, never dropped because\n * another is present. The compiler refuses the combinations the\n * `SecurityRule` union excludes (`access` beside `ownerField` or raw SQL,\n * `ownerField` beside a condition…, see `ruleShapeProblems`); should one\n * reach here anyway, it compiles to the conjunction — as narrow as every\n * clause in it — rather than to whichever clause was checked first.\n *\n * **This is the linchpin against drift:** both the Postgres DDL generators and\n * the client-side evaluator consume this one function, so there is exactly one\n * definition of what a rule means. In particular, application `roles` are folded\n * into the expression here (AND'd with the base condition, matching how Postgres\n * generates the clause) rather than being handled separately by each consumer.\n *\n * A {@link RedactedSecurityRule} (the marker the server sends for a rule whose\n * SQL it withheld) desugars to a raw node for both clauses — still gated by\n * its `access` and `roles` — so the evaluator answers it \"unknown\", exactly as\n * it answers a raw rule. No policy is ever compiled from one:\n * `compileTableRulePolicies` refuses it before it gets here.\n */\nexport function securityRuleToConditions(rule: SecurityRule, site: Pick<PolicyConditionSite, \"table\"> = {}): RuleConditions {\n return {\n usingExpr: withRoles(baseUsing(rule, site), rule),\n withCheckExpr: withRoles(baseWithCheck(rule, site), rule)\n };\n}\n\n/**\n * The caller test an `access` value stands for, or `undefined` for none:\n * `\"public\"` tests nothing (`true AND c` is `c`), `\"authenticated\"` is\n * `policy.authenticated()`, `\"registered\"` is `policy.registered()`. A value\n * the type does not know — a JavaScript caller, a cast, a typo — admits\n * nobody: the compiler refuses such a rule before it gets here, and this\n * keeps the desugaring total and closed for any caller that did not.\n */\nfunction accessTest(access: unknown): PolicyExpression | undefined {\n if (access === undefined || access === null || access === \"public\") return undefined;\n if (access === \"authenticated\") return policy.authenticated();\n if (access === \"registered\") return policy.registered();\n return policy.false();\n}\n\n/**\n * Every term of a clause, ANDed under the rule's `access` test: one term\n * alone is returned as it is (so a rule of one clause compiles exactly as it\n * always has), `access` gates it as `and(test, term)`, and several terms —\n * a combination the compiler refuses, reaching here only from a caller that\n * skipped it — are all kept. A clause is never dropped for another: the\n * result is at least as narrow as every clause the rule carries.\n */\nfunction conjoin(access: unknown, terms: readonly PolicyExpression[]): PolicyExpression | null {\n const test = accessTest(access);\n if (terms.length === 0) {\n if (test) return test;\n return access === \"public\" ? policy.true() : null;\n }\n const body = terms.length === 1 ? terms[0] : policy.and(...terms);\n if (!test) return body;\n return terms.length === 1 ? policy.and(test, body) : policy.and(test, ...terms);\n}\n\n/** What a withheld clause desugars to: SQL nobody here can evaluate. */\nconst REDACTED_CLAUSE_SQL = \"/* withheld by the server */\";\n\nfunction ownerTerm(rule: SecurityRule): PolicyExpression[] {\n return rule.ownerField ? [policy.compare(policy.field(rule.ownerField), \"eq\", policy.authUid())] : [];\n}\n\n/**\n * The `USING` clause: the `access` test ANDed with every row clause the rule\n * carries — `ownerField`, `condition`, raw `using`. Total: no clause is\n * dropped because another one is present, whatever the order of the checks.\n */\nfunction baseUsing(rule: SecurityRule, site: Pick<PolicyConditionSite, \"table\">): PolicyExpression | null {\n if (isRedactedSecurityRule(rule)) return conjoin(rule.access, [policy.raw(REDACTED_CLAUSE_SQL)]);\n const terms: PolicyExpression[] = [...ownerTerm(rule)];\n if (rule.condition != null) terms.push(policyConditionToExpression(rule.condition, { ...site, clause: \"condition\" }));\n if (rule.using != null) terms.push(sqlToPolicy(rule.using));\n return conjoin(rule.access, terms);\n}\n\n/**\n * The `WITH CHECK` clause. `check` stands in for `condition` and `withCheck`\n * for `using` (each defaults to its counterpart, as Postgres does); with\n * neither, the clause is the `USING` clause. Like {@link baseUsing}, every\n * clause present is ANDed under the `access` test.\n */\nfunction baseWithCheck(rule: SecurityRule, site: Pick<PolicyConditionSite, \"table\">): PolicyExpression | null {\n if (isRedactedSecurityRule(rule)) return conjoin(rule.access, [policy.raw(REDACTED_CLAUSE_SQL)]);\n if (rule.check == null && rule.withCheck == null) return baseUsing(rule, site);\n const terms: PolicyExpression[] = [...ownerTerm(rule)];\n if (rule.check != null) terms.push(policyConditionToExpression(rule.check, { ...site, clause: \"check\" }));\n else if (rule.condition != null) terms.push(policyConditionToExpression(rule.condition, { ...site, clause: \"condition\" }));\n if (rule.withCheck != null) terms.push(sqlToPolicy(rule.withCheck));\n else if (rule.using != null) terms.push(sqlToPolicy(rule.using));\n return conjoin(rule.access, terms);\n}\n\n/**\n * AND the base condition with an application-role check, or produce a roles-only\n * condition when there is no base. Mirrors the Postgres generator so that a\n * role-scoped restrictive rule denies exactly the same set of users on both\n * sides.\n */\nfunction withRoles(base: PolicyExpression | null, rule: SecurityRule): PolicyExpression | null {\n if (!rule.roles || rule.roles.length === 0) return base;\n const rolesExpr = policy.rolesOverlap(rule.roles);\n if (rule.mode === \"restrictive\") {\n // Restrictive rule: applies ONLY if user has the roles.\n // If user DOES NOT have the roles, they are NOT restricted (passes).\n // If user HAS the roles, they must pass the base condition.\n // Logical equivalent: NOT(roles) OR base\n return base ? policy.or(policy.not(rolesExpr), base) : policy.not(rolesExpr);\n }\n return base ? policy.and(base, rolesExpr) : rolesExpr;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2BA,SAAS,YAAY,OAAe,GAAW,SAA0B;CACrE,IAAI,CAAC,MAAM,WAAW,SAAS,CAAC,GAAG,OAAO;CAC1C,MAAM,SAAS,MAAM,IAAI,MAAM,MAAM,IAAI;CACzC,MAAM,QAAQ,MAAM,IAAI,QAAQ,WAAW;CAC3C,OAAO,SAAS,KAAK,MAAM,KAAK,SAAS,KAAK,KAAK;AACvD;;;;;;;;;;;;;;;AAgBA,SAAS,cAAc,KAAa,SAAwC;CACxE,MAAM,QAAQ,IAAI,YAAY;CAC9B,MAAM,QAAkB,CAAC;CACzB,IAAI,QAAQ;CACZ,IAAI,WAAW;CACf,IAAI,QAAQ;CAEZ,KAAK,IAAI,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;EACjC,MAAM,KAAK,IAAI;EACf,IAAI,UAAU;GACV,IAAI,OAAO,KACP,IAAI,IAAI,IAAI,OAAO,KAAK;QACnB,WAAW;GAEpB;EACJ;EACA,IAAI,OAAO,KAAK;GAAE,WAAW;GAAM;EAAU;EAC7C,IAAI,OAAO,KAAK;GAAE;GAAS;EAAU;EACrC,IAAI,OAAO,KAAK;GAAE;GAAS;EAAU;EACrC,IAAI,UAAU,KAAK,YAAY,OAAO,GAAG,OAAO,GAAG;GAC/C,MAAM,KAAK,IAAI,MAAM,OAAO,CAAC,CAAC;GAC9B,KAAK,QAAQ,SAAS;GACtB,QAAQ,IAAI;EAChB;CACJ;CAEA,IAAI,MAAM,WAAW,GAAG,OAAO;CAC/B,MAAM,KAAK,IAAI,MAAM,KAAK,CAAC;CAC3B,MAAM,eAAe,MAAM,KAAI,M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;AAQA,SAAS,cAAc,MAAoB,MAAmE;CAC1G,IAAI,uBAAuB,IAAI,GAAG,OAAO,QAAQ,KAAK,QAAQ,CAAC,OAAO,IAAI,mBAAmB,CAAC,CAAC;CAC/F,IAAI,KAAK,SAAS,QAAQ,KAAK,aAAa,MAAM,OAAO,UAAU,MAAM,IAAI;CAC7E,MAAM,QAA4B,CAAC,GAAG,UAAU,IAAI,CAAC;CACrD,IAAI,KAAK,SAAS,MAAM,MAAM,KAAK,4BAA4B,KAAK,OAAO;EAAE,GAAG;EAAM,QAAQ;CAAQ,CAAC,CAAC;MACnG,IAAI,KAAK,aAAa,MAAM,MAAM,KAAK,4BAA4B,KAAK,WAAW;EAAE,GAAG;EAAM,QAAQ;CAAY,CAAC,CAAC;CACzH,IAAI,KAAK,aAAa,MAAM,MAAM,KAAK,YAAY,KAAK,SAAS,CAAC;MAC7D,IAAI,KAAK,SAAS,MAAM,MAAM,KAAK,YAAY,KAAK,KAAK,CAAC;CAC/D,OAAO,QAAQ,KAAK,QAAQ,KAAK;AACrC;;;;;;;AAQA,SAAS,UAAU,MAA+B,MAA6C;CAC3F,IAAI,CAAC,KAAK,SAAS,KAAK,MAAM,WAAW,GAAG,OAAO;CACnD,MAAM,YAAY,OAAO,aAAa,KAAK,KAAK;CAChD,IAAI,KAAK,SAAS,eAKd,OAAO,OAAO,OAAO,GAAG,OAAO,IAAI,SAAS,GAAG,IAAI,IAAI,OAAO,IAAI,SAAS;CAE/E,OAAO,OAAO,OAAO,IAAI,MAAM,SAAS,IAAI;AAChD"}
@@ -2,7 +2,7 @@ import { createRequire as __rebaseCreateRequire } from "module";
2
2
  import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
- import { Pn as __exportAll } from "./src-DLIb1O9l.js";
5
+ import { Rn as __exportAll } from "./src-CNZB3fuE.js";
6
6
  //#region src/functions/selection.ts
7
7
  var selection_exports = /* @__PURE__ */ __exportAll({
8
8
  FunctionSelectionError: () => FunctionSelectionError,
@@ -62,4 +62,4 @@ function assertAllKnown(variable, names, available) {
62
62
  //#endregion
63
63
  export { selection_exports as n, FunctionSelectionError as t };
64
64
 
65
- //# sourceMappingURL=selection-hgC1szl6.js.map
65
+ //# sourceMappingURL=selection-BOnbJvXD.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"selection-hgC1szl6.js","names":[],"sources":["../src/functions/selection.ts"],"sourcesContent":["/**\n * Choosing which of a bundle's functions this process serves.\n *\n * A functions process usually serves all of them; naming a subset is how one\n * expensive or slow function gets its own replica count, its own restarts and\n * its own blast radius without moving its code anywhere.\n *\n * Selection is by name — the filename without its extension, which is also the\n * URL segment it mounts at — because that name is already the function's stable\n * identity everywhere else: `/api/functions/<name>`, the `functions/<name>` API\n * key permission, and the listing endpoint.\n */\n\n/** A name in the selection that the bundle does not contain. */\nexport class FunctionSelectionError extends Error {\n constructor(message: string, readonly hint?: string) {\n super(message);\n this.name = \"FunctionSelectionError\";\n }\n}\n\nexport interface FunctionSelection {\n /** Serve only these. Empty or absent means all of them. */\n only?: string[];\n /** Serve none of these. Applied after `only`. */\n exclude?: string[];\n}\n\n/** The shape this needs from a loaded function: its name. */\ninterface Named {\n name: string;\n}\n\n/**\n * Apply a selection to what the loader found.\n *\n * @throws FunctionSelectionError when a named function is not in the bundle.\n * A refusal rather than a warning, and the one decision in this file worth\n * arguing about. The argument for it: a process configured with\n * `REBASE_FUNCTIONS_ONLY=send-invoice` exists *for* that function, so a typo\n * leaves a replica set serving nothing, answering 404 to the only caller it\n * has, with one skipped line in a boot log as the only evidence. A deployment\n * that will not start is read in seconds; one that starts and serves nothing\n * is read after the incident.\n *\n * `exclude` is held to the same standard for the same reason in reverse — an\n * excluded name that does not match is a function still being served by a\n * process someone believed had stopped serving it.\n */\nexport function selectFunctions<T extends Named>(\n loaded: T[],\n selection: FunctionSelection = {}\n): T[] {\n const available = loaded.map(fn => fn.name);\n const only = selection.only ?? [];\n const exclude = selection.exclude ?? [];\n\n assertAllKnown(\"REBASE_FUNCTIONS_ONLY\", only, available);\n assertAllKnown(\"REBASE_FUNCTIONS_EXCLUDE\", exclude, available);\n\n const excluded = new Set(exclude);\n return loaded\n .filter(fn => only.length === 0 || only.includes(fn.name))\n .filter(fn => !excluded.has(fn.name));\n}\n\nfunction assertAllKnown(variable: string, names: string[], available: string[]): void {\n const unknown = names.filter(name => !available.includes(name));\n if (unknown.length === 0) return;\n\n throw new FunctionSelectionError(\n `${variable} names ${unknown.length === 1 ? \"a function\" : \"functions\"} this bundle does not ` +\n `contain: ${unknown.join(\", \")}.`,\n available.length > 0\n // The available list is the whole point of the message. Without it\n // the reader's next step is to go and read the bundle by hand, and\n // the usual cause — a name that differs from the filename by an\n // extension, a dash, or a directory that the loader flattened away —\n // is visible the moment the two lists sit side by side.\n ? `This bundle contains: ${available.join(\", \")}. Names are filenames without the extension.`\n : \"This bundle contains no functions at all. Check that the build included the functions directory.\"\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAcA,IAAa,yBAAb,cAA4C,MAAM;CACR;CAAtC,YAAY,SAAiB,MAAwB;EACjD,MAAM,OAAO;EADqB,KAAA,OAAA;EAElC,KAAK,OAAO;CAChB;AACJ;;;;;;;;;;;;;;;;;AA8BA,SAAgB,gBACZ,QACA,YAA+B,CAAC,GAC7B;CACH,MAAM,YAAY,OAAO,KAAI,OAAM,GAAG,IAAI;CAC1C,MAAM,OAAO,UAAU,QAAQ,CAAC;CAChC,MAAM,UAAU,UAAU,WAAW,CAAC;CAEtC,eAAe,yBAAyB,MAAM,SAAS;CACvD,eAAe,4BAA4B,SAAS,SAAS;CAE7D,MAAM,WAAW,IAAI,IAAI,OAAO;CAChC,OAAO,OACF,QAAO,OAAM,KAAK,WAAW,KAAK,KAAK,SAAS,GAAG,IAAI,CAAC,CAAC,CACzD,QAAO,OAAM,CAAC,SAAS,IAAI,GAAG,IAAI,CAAC;AAC5C;AAEA,SAAS,eAAe,UAAkB,OAAiB,WAA2B;CAClF,MAAM,UAAU,MAAM,QAAO,SAAQ,CAAC,UAAU,SAAS,IAAI,CAAC;CAC9D,IAAI,QAAQ,WAAW,GAAG;CAE1B,MAAM,IAAI,uBACN,GAAG,SAAS,SAAS,QAAQ,WAAW,IAAI,eAAe,YAAY,iCAC3D,QAAQ,KAAK,IAAI,EAAE,IAC/B,UAAU,SAAS,IAMb,yBAAyB,UAAU,KAAK,IAAI,EAAE,gDAC9C,kGACV;AACJ"}
1
+ {"version":3,"file":"selection-BOnbJvXD.js","names":[],"sources":["../src/functions/selection.ts"],"sourcesContent":["/**\n * Choosing which of a bundle's functions this process serves.\n *\n * A functions process usually serves all of them; naming a subset is how one\n * expensive or slow function gets its own replica count, its own restarts and\n * its own blast radius without moving its code anywhere.\n *\n * Selection is by name — the filename without its extension, which is also the\n * URL segment it mounts at — because that name is already the function's stable\n * identity everywhere else: `/api/functions/<name>`, the `functions/<name>` API\n * key permission, and the listing endpoint.\n */\n\n/** A name in the selection that the bundle does not contain. */\nexport class FunctionSelectionError extends Error {\n constructor(message: string, readonly hint?: string) {\n super(message);\n this.name = \"FunctionSelectionError\";\n }\n}\n\nexport interface FunctionSelection {\n /** Serve only these. Empty or absent means all of them. */\n only?: string[];\n /** Serve none of these. Applied after `only`. */\n exclude?: string[];\n}\n\n/** The shape this needs from a loaded function: its name. */\ninterface Named {\n name: string;\n}\n\n/**\n * Apply a selection to what the loader found.\n *\n * @throws FunctionSelectionError when a named function is not in the bundle.\n * A refusal rather than a warning, and the one decision in this file worth\n * arguing about. The argument for it: a process configured with\n * `REBASE_FUNCTIONS_ONLY=send-invoice` exists *for* that function, so a typo\n * leaves a replica set serving nothing, answering 404 to the only caller it\n * has, with one skipped line in a boot log as the only evidence. A deployment\n * that will not start is read in seconds; one that starts and serves nothing\n * is read after the incident.\n *\n * `exclude` is held to the same standard for the same reason in reverse — an\n * excluded name that does not match is a function still being served by a\n * process someone believed had stopped serving it.\n */\nexport function selectFunctions<T extends Named>(\n loaded: T[],\n selection: FunctionSelection = {}\n): T[] {\n const available = loaded.map(fn => fn.name);\n const only = selection.only ?? [];\n const exclude = selection.exclude ?? [];\n\n assertAllKnown(\"REBASE_FUNCTIONS_ONLY\", only, available);\n assertAllKnown(\"REBASE_FUNCTIONS_EXCLUDE\", exclude, available);\n\n const excluded = new Set(exclude);\n return loaded\n .filter(fn => only.length === 0 || only.includes(fn.name))\n .filter(fn => !excluded.has(fn.name));\n}\n\nfunction assertAllKnown(variable: string, names: string[], available: string[]): void {\n const unknown = names.filter(name => !available.includes(name));\n if (unknown.length === 0) return;\n\n throw new FunctionSelectionError(\n `${variable} names ${unknown.length === 1 ? \"a function\" : \"functions\"} this bundle does not ` +\n `contain: ${unknown.join(\", \")}.`,\n available.length > 0\n // The available list is the whole point of the message. Without it\n // the reader's next step is to go and read the bundle by hand, and\n // the usual cause — a name that differs from the filename by an\n // extension, a dash, or a directory that the loader flattened away —\n // is visible the moment the two lists sit side by side.\n ? `This bundle contains: ${available.join(\", \")}. Names are filenames without the extension.`\n : \"This bundle contains no functions at all. Check that the build included the functions directory.\"\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;AAcA,IAAa,yBAAb,cAA4C,MAAM;CACR;CAAtC,YAAY,SAAiB,MAAwB;EACjD,MAAM,OAAO;EADqB,KAAA,OAAA;EAElC,KAAK,OAAO;CAChB;AACJ;;;;;;;;;;;;;;;;;AA8BA,SAAgB,gBACZ,QACA,YAA+B,CAAC,GAC7B;CACH,MAAM,YAAY,OAAO,KAAI,OAAM,GAAG,IAAI;CAC1C,MAAM,OAAO,UAAU,QAAQ,CAAC;CAChC,MAAM,UAAU,UAAU,WAAW,CAAC;CAEtC,eAAe,yBAAyB,MAAM,SAAS;CACvD,eAAe,4BAA4B,SAAS,SAAS;CAE7D,MAAM,WAAW,IAAI,IAAI,OAAO;CAChC,OAAO,OACF,QAAO,OAAM,KAAK,WAAW,KAAK,KAAK,SAAS,GAAG,IAAI,CAAC,CAAC,CACzD,QAAO,OAAM,CAAC,SAAS,IAAI,GAAG,IAAI,CAAC;AAC5C;AAEA,SAAS,eAAe,UAAkB,OAAiB,WAA2B;CAClF,MAAM,UAAU,MAAM,QAAO,SAAQ,CAAC,UAAU,SAAS,IAAI,CAAC;CAC9D,IAAI,QAAQ,WAAW,GAAG;CAE1B,MAAM,IAAI,uBACN,GAAG,SAAS,SAAS,QAAQ,WAAW,IAAI,eAAe,YAAY,iCAC3D,QAAQ,KAAK,IAAI,EAAE,IAC/B,UAAU,SAAS,IAMb,yBAAyB,UAAU,KAAK,IAAI,EAAE,gDAC9C,kGACV;AACJ"}
@@ -68,6 +68,18 @@ export interface ServeSPAConfig {
68
68
  * app's hostname with its own `/assets/*`.
69
69
  */
70
70
  owns?: (request: StaticAppRequest) => boolean;
71
+ /**
72
+ * Origins besides this one allowed to frame the app, added to the
73
+ * `frame-ancestors` directive of its Content-Security-Policy (default:
74
+ * none, which is `frame-ancestors 'self'`).
75
+ *
76
+ * Each must be exactly one origin, as `parseFrameAncestor` in
77
+ * `@rebasepro/types` accepts it — `https://admin.example.com` — and the
78
+ * mount throws on one that is not, because each is written into a header.
79
+ *
80
+ * @example ["https://admin.example.com"]
81
+ */
82
+ frameAncestors?: readonly string[];
71
83
  }
72
84
  /** What {@link ServeSPAConfig.owns} is asked about. */
73
85
  export interface StaticAppRequest {
@@ -2,7 +2,7 @@ import { createRequire as __rebaseCreateRequire } from "module";
2
2
  import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
- import { t as ApiError } from "./errors-DpTMfX77.js";
5
+ import { t as ApiError } from "./errors-NVbAQU25.js";
6
6
  //#region src/api/rest/soft-delete-params.ts
7
7
  /**
8
8
  * The two query parameters soft delete adds to the REST surface.
@@ -56,4 +56,4 @@ function parseHardDelete(raw) {
56
56
  //#endregion
57
57
  export { parseWithDeleted as i, HARD_DELETE_QUERY_PARAM as n, parseHardDelete as r, DELETED_QUERY_PARAM as t };
58
58
 
59
- //# sourceMappingURL=soft-delete-params-DDRmxT2z.js.map
59
+ //# sourceMappingURL=soft-delete-params-Dhn0qKFv.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"soft-delete-params-DDRmxT2z.js","names":[],"sources":["../src/api/rest/soft-delete-params.ts"],"sourcesContent":["import { ApiError } from \"../errors\";\n\n/**\n * The two query parameters soft delete adds to the REST surface.\n *\n * Kept in their own module so the call sites in `query-parser.ts` and the\n * delete routes are a single line each: the parsing rules belong to soft\n * delete, not to the parser, and a rule spread across the two files that read\n * it is a rule that drifts.\n */\n\n/** `?deleted=` — what to do about rows a soft delete has stamped. */\nexport const DELETED_QUERY_PARAM = \"deleted\";\n/** `?hard=` — ask for a real `DELETE` on a soft-delete collection. */\nexport const HARD_DELETE_QUERY_PARAM = \"hard\";\n\n/**\n * `?deleted=include|only` → the driver's `withDeleted`.\n *\n * Spelled `deleted` on the wire and `withDeleted` in the driver, deliberately:\n * the URL reads as a question about the rows (`?deleted=only` — \"only the\n * deleted ones\"), and the driver option reads as an instruction about the query.\n *\n * A value neither word is a 400 rather than a silent fallback to the default.\n * `?deleted=true` quietly hiding every deleted row is the worst of both: it\n * looks like it worked and answers the opposite question. Absent is the\n * default, which is \"hide them\".\n */\nexport function parseWithDeleted(raw: unknown): boolean | \"only\" | undefined {\n if (raw === undefined || raw === null || raw === \"\") return undefined;\n const value = String(raw).trim().toLowerCase();\n if (value === \"include\") return true;\n if (value === \"only\") return \"only\";\n throw ApiError.badRequest(\n `Invalid \\`?${DELETED_QUERY_PARAM}=${String(raw)}\\`. It takes 'include' (live rows and deleted ones) ` +\n \"or 'only' (deleted rows alone). Omit it to see only the live rows.\",\n \"INVALID_DELETED_PARAM\"\n );\n}\n\n/**\n * `?hard=true` → a real `DELETE` on a collection that soft-deletes.\n *\n * Needs no permission beyond the delete it replaces: it is the same verb, and a\n * second access-control surface for one operation is a second thing to get\n * wrong. What it changes is whether the row can be restored.\n *\n * Only the exact words `true` and `1` mean yes. Anything else is a 400, not a\n * \"no\" — a typo that silently soft-deletes when the caller asked to purge is a\n * caller who believes the data is gone.\n */\nexport function parseHardDelete(raw: unknown): boolean {\n if (raw === undefined || raw === null || raw === \"\") return false;\n const value = String(raw).trim().toLowerCase();\n if (value === \"true\" || value === \"1\") return true;\n if (value === \"false\" || value === \"0\") return false;\n throw ApiError.badRequest(\n `Invalid \\`?${HARD_DELETE_QUERY_PARAM}=${String(raw)}\\`. It takes 'true' or 'false'.`,\n \"INVALID_HARD_PARAM\"\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAYA,IAAa,sBAAsB;;AAEnC,IAAa,0BAA0B;;;;;;;;;;;;;AAcvC,SAAgB,iBAAiB,KAA4C;CACzE,IAAI,QAAQ,KAAA,KAAa,QAAQ,QAAQ,QAAQ,IAAI,OAAO,KAAA;CAC5D,MAAM,QAAQ,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,YAAY;CAC7C,IAAI,UAAU,WAAW,OAAO;CAChC,IAAI,UAAU,QAAQ,OAAO;CAC7B,MAAM,SAAS,WACX,cAAc,oBAAoB,GAAG,OAAO,GAAG,EAAE,yHAEjD,uBACJ;AACJ;;;;;;;;;;;;AAaA,SAAgB,gBAAgB,KAAuB;CACnD,IAAI,QAAQ,KAAA,KAAa,QAAQ,QAAQ,QAAQ,IAAI,OAAO;CAC5D,MAAM,QAAQ,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,YAAY;CAC7C,IAAI,UAAU,UAAU,UAAU,KAAK,OAAO;CAC9C,IAAI,UAAU,WAAW,UAAU,KAAK,OAAO;CAC/C,MAAM,SAAS,WACX,cAAc,wBAAwB,GAAG,OAAO,GAAG,EAAE,kCACrD,oBACJ;AACJ"}
1
+ {"version":3,"file":"soft-delete-params-Dhn0qKFv.js","names":[],"sources":["../src/api/rest/soft-delete-params.ts"],"sourcesContent":["import { ApiError } from \"../errors\";\n\n/**\n * The two query parameters soft delete adds to the REST surface.\n *\n * Kept in their own module so the call sites in `query-parser.ts` and the\n * delete routes are a single line each: the parsing rules belong to soft\n * delete, not to the parser, and a rule spread across the two files that read\n * it is a rule that drifts.\n */\n\n/** `?deleted=` — what to do about rows a soft delete has stamped. */\nexport const DELETED_QUERY_PARAM = \"deleted\";\n/** `?hard=` — ask for a real `DELETE` on a soft-delete collection. */\nexport const HARD_DELETE_QUERY_PARAM = \"hard\";\n\n/**\n * `?deleted=include|only` → the driver's `withDeleted`.\n *\n * Spelled `deleted` on the wire and `withDeleted` in the driver, deliberately:\n * the URL reads as a question about the rows (`?deleted=only` — \"only the\n * deleted ones\"), and the driver option reads as an instruction about the query.\n *\n * A value neither word is a 400 rather than a silent fallback to the default.\n * `?deleted=true` quietly hiding every deleted row is the worst of both: it\n * looks like it worked and answers the opposite question. Absent is the\n * default, which is \"hide them\".\n */\nexport function parseWithDeleted(raw: unknown): boolean | \"only\" | undefined {\n if (raw === undefined || raw === null || raw === \"\") return undefined;\n const value = String(raw).trim().toLowerCase();\n if (value === \"include\") return true;\n if (value === \"only\") return \"only\";\n throw ApiError.badRequest(\n `Invalid \\`?${DELETED_QUERY_PARAM}=${String(raw)}\\`. It takes 'include' (live rows and deleted ones) ` +\n \"or 'only' (deleted rows alone). Omit it to see only the live rows.\",\n \"INVALID_DELETED_PARAM\"\n );\n}\n\n/**\n * `?hard=true` → a real `DELETE` on a collection that soft-deletes.\n *\n * Needs no permission beyond the delete it replaces: it is the same verb, and a\n * second access-control surface for one operation is a second thing to get\n * wrong. What it changes is whether the row can be restored.\n *\n * Only the exact words `true` and `1` mean yes. Anything else is a 400, not a\n * \"no\" — a typo that silently soft-deletes when the caller asked to purge is a\n * caller who believes the data is gone.\n */\nexport function parseHardDelete(raw: unknown): boolean {\n if (raw === undefined || raw === null || raw === \"\") return false;\n const value = String(raw).trim().toLowerCase();\n if (value === \"true\" || value === \"1\") return true;\n if (value === \"false\" || value === \"0\") return false;\n throw ApiError.badRequest(\n `Invalid \\`?${HARD_DELETE_QUERY_PARAM}=${String(raw)}\\`. It takes 'true' or 'false'.`,\n \"INVALID_HARD_PARAM\"\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;AAYA,IAAa,sBAAsB;;AAEnC,IAAa,0BAA0B;;;;;;;;;;;;;AAcvC,SAAgB,iBAAiB,KAA4C;CACzE,IAAI,QAAQ,KAAA,KAAa,QAAQ,QAAQ,QAAQ,IAAI,OAAO,KAAA;CAC5D,MAAM,QAAQ,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,YAAY;CAC7C,IAAI,UAAU,WAAW,OAAO;CAChC,IAAI,UAAU,QAAQ,OAAO;CAC7B,MAAM,SAAS,WACX,cAAc,oBAAoB,GAAG,OAAO,GAAG,EAAE,yHAEjD,uBACJ;AACJ;;;;;;;;;;;;AAaA,SAAgB,gBAAgB,KAAuB;CACnD,IAAI,QAAQ,KAAA,KAAa,QAAQ,QAAQ,QAAQ,IAAI,OAAO;CAC5D,MAAM,QAAQ,OAAO,GAAG,CAAC,CAAC,KAAK,CAAC,CAAC,YAAY;CAC7C,IAAI,UAAU,UAAU,UAAU,KAAK,OAAO;CAC9C,IAAI,UAAU,WAAW,UAAU,KAAK,OAAO;CAC/C,MAAM,SAAS,WACX,cAAc,wBAAwB,GAAG,OAAO,GAAG,EAAE,kCACrD,oBACJ;AACJ"}
@@ -2,9 +2,9 @@ import { createRequire as __rebaseCreateRequire } from "module";
2
2
  import __rebaseProcess from "process";
3
3
  globalThis.process ??= __rebaseProcess;
4
4
  __rebaseCreateRequire(import.meta.url);
5
- import { Qt as isSQLAdmin } from "./src-DLIb1O9l.js";
5
+ import { nn as isSQLAdmin } from "./src-CNZB3fuE.js";
6
6
  import { a as logger } from "./logger-SigQ2oZJ.js";
7
- import { t as ApiError } from "./errors-DpTMfX77.js";
7
+ import { t as ApiError } from "./errors-NVbAQU25.js";
8
8
  import { Hono } from "hono";
9
9
  //#region ../utils/dist/csv.es.js
10
10
  /**
@@ -270,4 +270,4 @@ function createSqlExportRoutes(options) {
270
270
  //#endregion
271
271
  export { createSqlExportRoutes };
272
272
 
273
- //# sourceMappingURL=sql-export-routes-BKmQZ3xh.js.map
273
+ //# sourceMappingURL=sql-export-routes-B3oqb1Jw.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"sql-export-routes-BKmQZ3xh.js","names":[],"sources":["../../utils/dist/csv.es.js","../../common/src/util/sql-redaction.ts","../src/api/sql-export-routes.ts"],"sourcesContent":["//#region src/csv.ts\n/**\n* Characters that make a spreadsheet read a cell as a formula rather than text.\n*\n* Quoting is CSV *escaping* and is not enough: Excel, LibreOffice Calc and\n* Sheets strip the CSV quoting at parse time and then evaluate a cell whose\n* first character is one of these — `=HYPERLINK(…)` exfiltrates neighbouring\n* cells on click, `=cmd|'…'!A0` is worse.\n*/\nvar FORMULA_TRIGGERS = [\n\t\"=\",\n\t\"+\",\n\t\"-\",\n\t\"@\",\n\t\"\t\",\n\t\"\\r\"\n];\n/**\n* Neutralise a cell that a spreadsheet would otherwise evaluate, by prefixing a\n* single quote — the standard OWASP mitigation. The apostrophe is consumed by\n* the spreadsheet as \"treat the rest as text\", so the value reads back intact.\n*/\nfunction escapeCsvFormula(value) {\n\tconst first = value.charAt(0);\n\tif (!FORMULA_TRIGGERS.includes(first)) return value;\n\tif ((first === \"-\" || first === \"+\") && value.trim() !== \"\" && Number.isFinite(Number(value))) return value;\n\treturn \"'\" + value;\n}\n/**\n* The inverse of {@link escapeCsvFormula}, for a file read back in: a cell that\n* is an apostrophe followed by a formula trigger loses the apostrophe, as it\n* does when a spreadsheet reads it. Any other apostrophe is text.\n*/\nfunction unescapeCsvFormula(value) {\n\treturn value.charAt(0) === \"'\" && FORMULA_TRIGGERS.includes(value.charAt(1)) ? value.slice(1) : value;\n}\n/**\n* One CSV field (RFC 4180): quoted when it holds a comma, a quote or a line\n* break, with each quote doubled. SQL NULL — `null` or `undefined` — is an\n* empty field, as `COPY … CSV` writes it; an object (a plan, a parsed `jsonb`)\n* is its JSON.\n*\n* Text a spreadsheet would run as a formula (`=…`, `+…`, `-…`, `@…`, a leading\n* tab or carriage return) gets a leading `'` ({@link escapeCsvFormula}), as\n* the CMS export has always done; a signed number is left a number. Every CSV\n* the product writes goes through here, so a file opened in Excel or Sheets\n* never evaluates a cell — at the cost of not being byte-identical to\n* `COPY … CSV` for such cells.\n*/\nfunction csvField(value) {\n\tif (value === null || value === void 0) return \"\";\n\tconst text = escapeCsvFormula(typeof value === \"object\" ? JSON.stringify(value) : String(value));\n\treturn /[\",\\r\\n]/.test(text) ? `\"${text.replace(/\"/g, \"\\\"\\\"\")}\"` : text;\n}\n/** One CSV record: each value through {@link csvField}, separated by commas, with no line break. */\nfunction csvRecord(values) {\n\treturn values.map(csvField).join(\",\");\n}\n//#endregion\nexport { csvField, csvRecord, escapeCsvFormula, unescapeCsvFormula };\n\n//# sourceMappingURL=csv.es.js.map","/**\n * SQL a person ran, as the audit log may keep it: every string literal masked.\n *\n * The SQL console's audit line wrote the statement verbatim, so `ALTER ROLE app\n * PASSWORD 'hunter2'`, `CREATE USER MAPPING … OPTIONS (password 'hunter2')` and\n * `dblink_connect('host=db password=hunter2')` put the password in the\n * production logs, where the logger's redaction — by key name — never looks.\n *\n * A literal is a value the statement carries inline, which is exactly what the\n * line already declines to write when it is bound as a parameter: the\n * statement's shape is the audit signal, the values are whatever the operator\n * was touching. So every literal goes, not only the ones beside a word that\n * looks like `password` — a secret has no reliable neighbour. Identifiers,\n * keywords, numbers and comments stay.\n *\n * Read with Postgres's own lexical rules, not a regular expression over the\n * text: a quote inside a comment, a doubled quote, an `E'…\\'…'` escape or a\n * `$tag$` body must not shift where a literal is thought to end, or the mask\n * covers the statement and leaves the secret.\n */\nexport function redactSqlLiterals(sql: string): string {\n let out = \"\";\n let i = 0;\n while (i < sql.length) {\n const char = sql[i];\n const next = sql[i + 1];\n\n // -- line comment\n if (char === \"-\" && next === \"-\") {\n const end = sql.indexOf(\"\\n\", i);\n const stop = end === -1 ? sql.length : end;\n out += sql.slice(i, stop);\n i = stop;\n continue;\n }\n\n // /* block comment */ — nested, as Postgres reads them\n if (char === \"/\" && next === \"*\") {\n let depth = 1;\n let j = i + 2;\n while (j < sql.length && depth > 0) {\n if (sql[j] === \"/\" && sql[j + 1] === \"*\") { depth++; j += 2; } else if (sql[j] === \"*\" && sql[j + 1] === \"/\") { depth--; j += 2; } else j++;\n }\n out += sql.slice(i, j);\n i = j;\n continue;\n }\n\n // \"quoted identifier\"\n if (char === \"\\\"\") {\n const end = closingQuote(sql, i + 1, \"\\\"\", false);\n out += sql.slice(i, end);\n i = end;\n continue;\n }\n\n // 'string', E'string' with backslash escapes, and the B'', X'', N'',\n // U&'' prefixes — the prefix is kept, the content masked.\n if (char === \"'\") {\n const prefix = /(?:^|[^A-Za-z0-9_$])([EeBbXxNn]|[Uu]&)$/.exec(out)?.[1] ?? \"\";\n out += \"'***'\";\n i = closingQuote(sql, i + 1, \"'\", prefix.toUpperCase() === \"E\");\n continue;\n }\n\n // $tag$ … $tag$ — a dollar-quoted string. A function or DO body is SQL\n // in its own right, and its literals are masked as these are; a\n // password written as `PASSWORD $$hunter2$$` is masked whole.\n if (char === \"$\") {\n const tag = /^\\$([A-Za-z_][A-Za-z0-9_]*)?\\$/.exec(sql.slice(i));\n const precededByIdentifier = /[A-Za-z0-9_]$/.test(out);\n if (tag && !precededByIdentifier) {\n const delimiter = tag[0];\n const bodyStart = i + delimiter.length;\n const bodyEnd = sql.indexOf(delimiter, bodyStart);\n const stop = bodyEnd === -1 ? sql.length : bodyEnd;\n const body = sql.slice(bodyStart, stop);\n const isPassword = /\\bpassword\\s*$/i.test(out);\n out += delimiter + (isPassword ? \"***\" : redactSqlLiterals(body)) + (bodyEnd === -1 ? \"\" : delimiter);\n i = bodyEnd === -1 ? sql.length : bodyEnd + delimiter.length;\n continue;\n }\n }\n\n out += char;\n i++;\n }\n return out;\n}\n\n/**\n * The index just past the quote that closes a literal or identifier opened\n * before `from`. A doubled quote is one quote inside it; with `backslashEscapes`\n * (an `E''` string) so is a backslash-escaped one. Unterminated runs to the end.\n */\nfunction closingQuote(sql: string, from: number, quote: string, backslashEscapes: boolean): number {\n let j = from;\n while (j < sql.length) {\n if (backslashEscapes && sql[j] === \"\\\\\") { j += 2; continue; }\n if (sql[j] === quote) {\n if (sql[j + 1] === quote) { j += 2; continue; }\n return j + 1;\n }\n j++;\n }\n return sql.length;\n}\n","import { Hono } from \"hono\";\nimport { isSQLAdmin, type DatabaseAdmin, type SqlCursor } from \"@rebasepro/types\";\nimport { redactSqlLiterals } from \"@rebasepro/common\";\nimport { csvRecord } from \"@rebasepro/utils\";\nimport { ApiError } from \"./errors\";\nimport type { HonoEnv } from \"./types\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * The SQL console's \"Download full result as CSV\".\n *\n * The console shows at most the first 10,000 rows of a result (see\n * `SQL_CONSOLE_RESULT_LIMITS`), and its own export writes the rows on screen.\n * This route is the way to the rest: it runs ONE query through\n * `SQLAdmin.openSqlCursor` — a server-side cursor in a read-only transaction,\n * as the role the console picked — and streams it as RFC 4180 CSV, one batch\n * at a time. A batch is fetched only when the response has taken the last\n * one, so the server holds one batch however long the result is.\n *\n * Mounted under `/api/admin/sql` behind the admin gate with `database:write` —\n * the scope the socket's `EXECUTE_SQL` asks of the same console, so whoever\n * can run the query can download it and nobody else.\n */\n\n/** RFC 4180's record separator. */\nconst CRLF = \"\\r\\n\";\n\nexport interface SqlExportRoutesOptions {\n /** The default data source's admin capabilities, read per request. */\n getAdmin: () => DatabaseAdmin | undefined;\n}\n\ninterface ExportRequest {\n sql: string;\n database?: string;\n role?: string;\n}\n\nfunction readExportRequest(body: unknown): ExportRequest {\n if (typeof body !== \"object\" || body === null || !(\"sql\" in body) || typeof body.sql !== \"string\" || body.sql.trim() === \"\") {\n throw ApiError.badRequest(\"Send the query to download as `sql`, a non-empty string.\", \"INVALID_INPUT\");\n }\n const optional = (key: \"database\" | \"role\"): string | undefined => {\n const value: unknown = key in body ? Reflect.get(body, key) : undefined;\n if (value === undefined || value === null || value === \"\") return undefined;\n if (typeof value !== \"string\") throw ApiError.badRequest(`\\`${key}\\` must be a string.`, \"INVALID_INPUT\");\n return value;\n };\n return { sql: body.sql, database: optional(\"database\"), role: optional(\"role\") };\n}\n\n/**\n * The cursor's rows as CSV, a header record first. Read one batch per pull:\n * the stream asks for the next only when the response has taken this one.\n *\n * A failure after the first byte cannot change the status any more, so the\n * stream is errored instead — the download fails rather than ending early\n * with a file that looks whole.\n */\nfunction csvStream(cursor: SqlCursor, onFailure: (error: unknown) => void): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n let headerSent = false;\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n if (!headerSent) {\n headerSent = true;\n controller.enqueue(encoder.encode(csvRecord(cursor.columns) + CRLF));\n return;\n }\n const rows = await cursor.read();\n if (!rows) {\n await cursor.close();\n controller.close();\n return;\n }\n controller.enqueue(encoder.encode(rows.map(row => csvRecord(row) + CRLF).join(\"\")));\n } catch (error: unknown) {\n onFailure(error);\n await cursor.close();\n controller.error(error);\n }\n },\n async cancel() {\n // The reader went away: end the read and give the session back.\n await cursor.close();\n }\n }, { highWaterMark: 1 });\n}\n\nexport function createSqlExportRoutes(options: SqlExportRoutesOptions): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n\n router.post(\"/csv\", async (c) => {\n const request = readExportRequest(await c.req.json());\n const admin = options.getAdmin();\n if (!isSQLAdmin(admin) || typeof admin.openSqlCursor !== \"function\") {\n throw new ApiError(501, \"SQL_EXPORT_UNSUPPORTED\",\n \"This data source cannot stream a query's result. Add a LIMIT and export the rows on screen.\");\n }\n\n const caller = c.get(\"user\");\n const user = typeof caller === \"object\" && caller !== null ? caller : undefined;\n const audit = {\n // Literals masked, as on the socket: a statement's shape is the\n // audit signal, its values are whatever the operator was reading.\n sql: redactSqlLiterals(request.sql).substring(0, 500),\n database: request.database,\n role: request.role,\n uid: user?.uid ?? \"unknown\",\n roles: user?.roles ?? [],\n ...(c.get(\"apiKey\") ? { apiKey: c.get(\"apiKey\")?.id } : {}),\n requestId: c.get(\"requestId\")\n };\n\n // Opened before the response starts: a query the database refuses — a\n // write, a second statement, a syntax error — is a 400 with its\n // reason, not an empty file.\n const cursor = await admin.openSqlCursor(request.sql, { database: request.database, role: request.role });\n logger.info(\"[SQL Audit] SQL console CSV download\", audit);\n\n const body = csvStream(cursor, (error) => logger.warn(\"[SQL export] The download failed part-way and was cut off\", {\n requestId: audit.requestId,\n error: error instanceof Error ? error.message : String(error)\n }));\n return new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/csv; charset=utf-8\",\n \"Content-Disposition\": \"attachment; filename=\\\"query_results.csv\\\"\",\n \"Cache-Control\": \"no-store\"\n }\n });\n });\n\n return router;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AASA,IAAI,mBAAmB;CACtB;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;AAMA,SAAS,iBAAiB,OAAO;CAChC,MAAM,QAAQ,MAAM,OAAO,CAAC;CAC5B,IAAI,CAAC,iBAAiB,SAAS,KAAK,GAAG,OAAO;CAC9C,KAAK,UAAU,OAAO,UAAU,QAAQ,MAAM,KAAK,MAAM,MAAM,OAAO,SAAS,OAAO,KAAK,CAAC,GAAG,OAAO;CACtG,OAAO,MAAM;AACd;;;;;;;;;;;;;;AAsBA,SAAS,SAAS,OAAO;CACxB,IAAI,UAAU,QAAQ,UAAU,KAAK,GAAG,OAAO;CAC/C,MAAM,OAAO,iBAAiB,OAAO,UAAU,WAAW,KAAK,UAAU,KAAK,IAAI,OAAO,KAAK,CAAC;CAC/F,OAAO,WAAW,KAAK,IAAI,IAAI,IAAI,KAAK,QAAQ,MAAM,MAAM,EAAE,KAAK;AACpE;;AAEA,SAAS,UAAU,QAAQ;CAC1B,OAAO,OAAO,IAAI,QAAQ,CAAC,CAAC,KAAK,GAAG;AACrC;;;;;;;;;;;;;;;;;;;;;;;ACrCA,SAAgB,kBAAkB,KAAqB;CACnD,IAAI,MAAM;CACV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AC;GACzD,WAAW,EAAE,IAAI,WAAW;EAChC;EAKA,MAAM,SAAS,MAAM,MAAM,cAAc,QAAQ,KAAK;GAAE,UAAU,QAAQ;GAAU,MAAM,QAAQ;EAAK,CAAC;EACxG,OAAO,KAAK,wCAAwC,KAAK;EAEzD,MAAM,OAAO,UAAU,SAAS,UAAU,OAAO,KAAK,6DAA6D;GAC/G,WAAW,MAAM;GACjB,OAAO,iBAAiB,QAAQ,MAAM,UAAU,OAAO,KAAK;EAChE,CAAC,CAAC;EACF,OAAO,IAAI,SAAS,MAAM;GACtB,QAAQ;GACR,SAAS;IACL,gBAAgB;IAChB,uBAAuB;IACvB,iBAAiB;GACrB;EACJ,CAAC;CACL,CAAC;CAED,OAAO;AACX"}
1
+ {"version":3,"file":"sql-export-routes-B3oqb1Jw.js","names":[],"sources":["../../utils/dist/csv.es.js","../../common/src/util/sql-redaction.ts","../src/api/sql-export-routes.ts"],"sourcesContent":["//#region src/csv.ts\n/**\n* Characters that make a spreadsheet read a cell as a formula rather than text.\n*\n* Quoting is CSV *escaping* and is not enough: Excel, LibreOffice Calc and\n* Sheets strip the CSV quoting at parse time and then evaluate a cell whose\n* first character is one of these — `=HYPERLINK(…)` exfiltrates neighbouring\n* cells on click, `=cmd|'…'!A0` is worse.\n*/\nvar FORMULA_TRIGGERS = [\n\t\"=\",\n\t\"+\",\n\t\"-\",\n\t\"@\",\n\t\"\t\",\n\t\"\\r\"\n];\n/**\n* Neutralise a cell that a spreadsheet would otherwise evaluate, by prefixing a\n* single quote — the standard OWASP mitigation. The apostrophe is consumed by\n* the spreadsheet as \"treat the rest as text\", so the value reads back intact.\n*/\nfunction escapeCsvFormula(value) {\n\tconst first = value.charAt(0);\n\tif (!FORMULA_TRIGGERS.includes(first)) return value;\n\tif ((first === \"-\" || first === \"+\") && value.trim() !== \"\" && Number.isFinite(Number(value))) return value;\n\treturn \"'\" + value;\n}\n/**\n* The inverse of {@link escapeCsvFormula}, for a file read back in: a cell that\n* is an apostrophe followed by a formula trigger loses the apostrophe, as it\n* does when a spreadsheet reads it. Any other apostrophe is text.\n*/\nfunction unescapeCsvFormula(value) {\n\treturn value.charAt(0) === \"'\" && FORMULA_TRIGGERS.includes(value.charAt(1)) ? value.slice(1) : value;\n}\n/**\n* One CSV field (RFC 4180): quoted when it holds a comma, a quote or a line\n* break, with each quote doubled. SQL NULL — `null` or `undefined` — is an\n* empty field, as `COPY … CSV` writes it; an object (a plan, a parsed `jsonb`)\n* is its JSON.\n*\n* Text a spreadsheet would run as a formula (`=…`, `+…`, `-…`, `@…`, a leading\n* tab or carriage return) gets a leading `'` ({@link escapeCsvFormula}), as\n* the CMS export has always done; a signed number is left a number. Every CSV\n* the product writes goes through here, so a file opened in Excel or Sheets\n* never evaluates a cell — at the cost of not being byte-identical to\n* `COPY … CSV` for such cells.\n*/\nfunction csvField(value) {\n\tif (value === null || value === void 0) return \"\";\n\tconst text = escapeCsvFormula(typeof value === \"object\" ? JSON.stringify(value) : String(value));\n\treturn /[\",\\r\\n]/.test(text) ? `\"${text.replace(/\"/g, \"\\\"\\\"\")}\"` : text;\n}\n/** One CSV record: each value through {@link csvField}, separated by commas, with no line break. */\nfunction csvRecord(values) {\n\treturn values.map(csvField).join(\",\");\n}\n//#endregion\nexport { csvField, csvRecord, escapeCsvFormula, unescapeCsvFormula };\n\n//# sourceMappingURL=csv.es.js.map","/**\n * SQL a person ran, as the audit log may keep it: every string literal masked.\n *\n * The SQL console's audit line wrote the statement verbatim, so `ALTER ROLE app\n * PASSWORD 'hunter2'`, `CREATE USER MAPPING … OPTIONS (password 'hunter2')` and\n * `dblink_connect('host=db password=hunter2')` put the password in the\n * production logs, where the logger's redaction — by key name — never looks.\n *\n * A literal is a value the statement carries inline, which is exactly what the\n * line already declines to write when it is bound as a parameter: the\n * statement's shape is the audit signal, the values are whatever the operator\n * was touching. So every literal goes, not only the ones beside a word that\n * looks like `password` — a secret has no reliable neighbour. Identifiers,\n * keywords, numbers and comments stay.\n *\n * Read with Postgres's own lexical rules, not a regular expression over the\n * text: a quote inside a comment, a doubled quote, an `E'…\\'…'` escape or a\n * `$tag$` body must not shift where a literal is thought to end, or the mask\n * covers the statement and leaves the secret.\n */\nexport function redactSqlLiterals(sql: string): string {\n let out = \"\";\n let i = 0;\n while (i < sql.length) {\n const char = sql[i];\n const next = sql[i + 1];\n\n // -- line comment\n if (char === \"-\" && next === \"-\") {\n const end = sql.indexOf(\"\\n\", i);\n const stop = end === -1 ? sql.length : end;\n out += sql.slice(i, stop);\n i = stop;\n continue;\n }\n\n // /* block comment */ — nested, as Postgres reads them\n if (char === \"/\" && next === \"*\") {\n let depth = 1;\n let j = i + 2;\n while (j < sql.length && depth > 0) {\n if (sql[j] === \"/\" && sql[j + 1] === \"*\") { depth++; j += 2; } else if (sql[j] === \"*\" && sql[j + 1] === \"/\") { depth--; j += 2; } else j++;\n }\n out += sql.slice(i, j);\n i = j;\n continue;\n }\n\n // \"quoted identifier\"\n if (char === \"\\\"\") {\n const end = closingQuote(sql, i + 1, \"\\\"\", false);\n out += sql.slice(i, end);\n i = end;\n continue;\n }\n\n // 'string', E'string' with backslash escapes, and the B'', X'', N'',\n // U&'' prefixes — the prefix is kept, the content masked.\n if (char === \"'\") {\n const prefix = /(?:^|[^A-Za-z0-9_$])([EeBbXxNn]|[Uu]&)$/.exec(out)?.[1] ?? \"\";\n out += \"'***'\";\n i = closingQuote(sql, i + 1, \"'\", prefix.toUpperCase() === \"E\");\n continue;\n }\n\n // $tag$ … $tag$ — a dollar-quoted string. A function or DO body is SQL\n // in its own right, and its literals are masked as these are; a\n // password written as `PASSWORD $$hunter2$$` is masked whole.\n if (char === \"$\") {\n const tag = /^\\$([A-Za-z_][A-Za-z0-9_]*)?\\$/.exec(sql.slice(i));\n const precededByIdentifier = /[A-Za-z0-9_]$/.test(out);\n if (tag && !precededByIdentifier) {\n const delimiter = tag[0];\n const bodyStart = i + delimiter.length;\n const bodyEnd = sql.indexOf(delimiter, bodyStart);\n const stop = bodyEnd === -1 ? sql.length : bodyEnd;\n const body = sql.slice(bodyStart, stop);\n const isPassword = /\\bpassword\\s*$/i.test(out);\n out += delimiter + (isPassword ? \"***\" : redactSqlLiterals(body)) + (bodyEnd === -1 ? \"\" : delimiter);\n i = bodyEnd === -1 ? sql.length : bodyEnd + delimiter.length;\n continue;\n }\n }\n\n out += char;\n i++;\n }\n return out;\n}\n\n/**\n * The index just past the quote that closes a literal or identifier opened\n * before `from`. A doubled quote is one quote inside it; with `backslashEscapes`\n * (an `E''` string) so is a backslash-escaped one. Unterminated runs to the end.\n */\nfunction closingQuote(sql: string, from: number, quote: string, backslashEscapes: boolean): number {\n let j = from;\n while (j < sql.length) {\n if (backslashEscapes && sql[j] === \"\\\\\") { j += 2; continue; }\n if (sql[j] === quote) {\n if (sql[j + 1] === quote) { j += 2; continue; }\n return j + 1;\n }\n j++;\n }\n return sql.length;\n}\n","import { Hono } from \"hono\";\nimport { isSQLAdmin, type DatabaseAdmin, type SqlCursor } from \"@rebasepro/types\";\nimport { redactSqlLiterals } from \"@rebasepro/common\";\nimport { csvRecord } from \"@rebasepro/utils\";\nimport { ApiError } from \"./errors\";\nimport type { HonoEnv } from \"./types\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * The SQL console's \"Download full result as CSV\".\n *\n * The console shows at most the first 10,000 rows of a result (see\n * `SQL_CONSOLE_RESULT_LIMITS`), and its own export writes the rows on screen.\n * This route is the way to the rest: it runs ONE query through\n * `SQLAdmin.openSqlCursor` — a server-side cursor in a read-only transaction,\n * as the role the console picked — and streams it as RFC 4180 CSV, one batch\n * at a time. A batch is fetched only when the response has taken the last\n * one, so the server holds one batch however long the result is.\n *\n * Mounted under `/api/admin/sql` behind the admin gate with `database:write` —\n * the scope the socket's `EXECUTE_SQL` asks of the same console, so whoever\n * can run the query can download it and nobody else.\n */\n\n/** RFC 4180's record separator. */\nconst CRLF = \"\\r\\n\";\n\nexport interface SqlExportRoutesOptions {\n /** The default data source's admin capabilities, read per request. */\n getAdmin: () => DatabaseAdmin | undefined;\n}\n\ninterface ExportRequest {\n sql: string;\n database?: string;\n role?: string;\n}\n\nfunction readExportRequest(body: unknown): ExportRequest {\n if (typeof body !== \"object\" || body === null || !(\"sql\" in body) || typeof body.sql !== \"string\" || body.sql.trim() === \"\") {\n throw ApiError.badRequest(\"Send the query to download as `sql`, a non-empty string.\", \"INVALID_INPUT\");\n }\n const optional = (key: \"database\" | \"role\"): string | undefined => {\n const value: unknown = key in body ? Reflect.get(body, key) : undefined;\n if (value === undefined || value === null || value === \"\") return undefined;\n if (typeof value !== \"string\") throw ApiError.badRequest(`\\`${key}\\` must be a string.`, \"INVALID_INPUT\");\n return value;\n };\n return { sql: body.sql, database: optional(\"database\"), role: optional(\"role\") };\n}\n\n/**\n * The cursor's rows as CSV, a header record first. Read one batch per pull:\n * the stream asks for the next only when the response has taken this one.\n *\n * A failure after the first byte cannot change the status any more, so the\n * stream is errored instead — the download fails rather than ending early\n * with a file that looks whole.\n */\nfunction csvStream(cursor: SqlCursor, onFailure: (error: unknown) => void): ReadableStream<Uint8Array> {\n const encoder = new TextEncoder();\n let headerSent = false;\n return new ReadableStream<Uint8Array>({\n async pull(controller) {\n try {\n if (!headerSent) {\n headerSent = true;\n controller.enqueue(encoder.encode(csvRecord(cursor.columns) + CRLF));\n return;\n }\n const rows = await cursor.read();\n if (!rows) {\n await cursor.close();\n controller.close();\n return;\n }\n controller.enqueue(encoder.encode(rows.map(row => csvRecord(row) + CRLF).join(\"\")));\n } catch (error: unknown) {\n onFailure(error);\n await cursor.close();\n controller.error(error);\n }\n },\n async cancel() {\n // The reader went away: end the read and give the session back.\n await cursor.close();\n }\n }, { highWaterMark: 1 });\n}\n\nexport function createSqlExportRoutes(options: SqlExportRoutesOptions): Hono<HonoEnv> {\n const router = new Hono<HonoEnv>();\n\n router.post(\"/csv\", async (c) => {\n const request = readExportRequest(await c.req.json());\n const admin = options.getAdmin();\n if (!isSQLAdmin(admin) || typeof admin.openSqlCursor !== \"function\") {\n throw new ApiError(501, \"SQL_EXPORT_UNSUPPORTED\",\n \"This data source cannot stream a query's result. Add a LIMIT and export the rows on screen.\");\n }\n\n const caller = c.get(\"user\");\n const user = typeof caller === \"object\" && caller !== null ? caller : undefined;\n const audit = {\n // Literals masked, as on the socket: a statement's shape is the\n // audit signal, its values are whatever the operator was reading.\n sql: redactSqlLiterals(request.sql).substring(0, 500),\n database: request.database,\n role: request.role,\n uid: user?.uid ?? \"unknown\",\n roles: user?.roles ?? [],\n ...(c.get(\"apiKey\") ? { apiKey: c.get(\"apiKey\")?.id } : {}),\n requestId: c.get(\"requestId\")\n };\n\n // Opened before the response starts: a query the database refuses — a\n // write, a second statement, a syntax error — is a 400 with its\n // reason, not an empty file.\n const cursor = await admin.openSqlCursor(request.sql, { database: request.database, role: request.role });\n logger.info(\"[SQL Audit] SQL console CSV download\", audit);\n\n const body = csvStream(cursor, (error) => logger.warn(\"[SQL export] The download failed part-way and was cut off\", {\n requestId: audit.requestId,\n error: error instanceof Error ? error.message : String(error)\n }));\n return new Response(body, {\n status: 200,\n headers: {\n \"Content-Type\": \"text/csv; charset=utf-8\",\n \"Content-Disposition\": \"attachment; filename=\\\"query_results.csv\\\"\",\n \"Cache-Control\": \"no-store\"\n }\n });\n });\n\n return router;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;AASA,IAAI,mBAAmB;CACtB;CACA;CACA;CACA;CACA;CACA;AACD;;;;;;AAMA,SAAS,iBAAiB,OAAO;CAChC,MAAM,QAAQ,MAAM,OAAO,CAAC;CAC5B,IAAI,CAAC,iBAAiB,SAAS,KAAK,GAAG,OAAO;CAC9C,KAAK,UAAU,OAAO,UAAU,QAAQ,MAAM,KAAK,MAAM,MAAM,OAAO,SAAS,OAAO,KAAK,CAAC,GAAG,OAAO;CACtG,OAAO,MAAM;AACd;;;;;;;;;;;;;;AAsBA,SAAS,SAAS,OAAO;CACxB,IAAI,UAAU,QAAQ,UAAU,KAAK,GAAG,OAAO;CAC/C,MAAM,OAAO,iBAAiB,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