@rebasepro/server 0.31.0 → 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.
- package/dist/{GCSStorageController-sCw2c4aA.js → GCSStorageController-B3p3aUX-.js} +5 -5
- package/dist/{GCSStorageController-sCw2c4aA.js.map → GCSStorageController-B3p3aUX-.js.map} +1 -1
- package/dist/{S3StorageController-DDAq8Kt5.js → S3StorageController-C9LjuMhL.js} +5 -5
- package/dist/{S3StorageController-DDAq8Kt5.js.map → S3StorageController-C9LjuMhL.js.map} +1 -1
- package/dist/{access-Dtu87BMj.js → access-BxkEYQh1.js} +5 -5
- package/dist/{access-Dtu87BMj.js.map → access-BxkEYQh1.js.map} +1 -1
- package/dist/api/errors.d.ts +4 -0
- package/dist/api/rest/api-generator.d.ts +8 -0
- package/dist/{auth-BOz84vIr.js → auth-Bfwjg4Bg.js} +37 -13
- package/dist/auth-Bfwjg4Bg.js.map +1 -0
- package/dist/backend/create-backend.d.ts +6 -0
- package/dist/backend/options.d.ts +10 -0
- package/dist/backend/services.d.ts +9 -0
- package/dist/{backup-B-1oW6qX.js → backup-g2ohsDe0.js} +7 -7
- package/dist/{backup-B-1oW6qX.js.map → backup-g2ohsDe0.js.map} +1 -1
- package/dist/boot/bundle.d.ts +11 -1
- package/dist/boot/env.d.ts +5 -0
- package/dist/boot/security-headers.d.ts +15 -5
- package/dist/boot/static-routing.d.ts +58 -0
- package/dist/{branch-routes-0xhHXlGq.js → branch-routes-DtNtc0Vh.js} +3 -3
- package/dist/{branch-routes-0xhHXlGq.js.map → branch-routes-DtNtc0Vh.js.map} +1 -1
- package/dist/{contract-routes-o5oqNhfc.js → contract-routes-CZTlAP7p.js} +3 -3
- package/dist/{contract-routes-o5oqNhfc.js.map → contract-routes-CZTlAP7p.js.map} +1 -1
- package/dist/{cron-loader-BDN8plQK.js → cron-loader-BBP0kBIl.js} +2 -2
- package/dist/{cron-loader-BDN8plQK.js.map → cron-loader-BBP0kBIl.js.map} +1 -1
- package/dist/{cron-routes-BOu-bY7I.js → cron-routes-Du03uJ7K.js} +5 -5
- package/dist/{cron-routes-BOu-bY7I.js.map → cron-routes-Du03uJ7K.js.map} +1 -1
- package/dist/{cron-scheduler-DgrsqyQQ.js → cron-scheduler-CopTWKYB.js} +2 -2
- package/dist/{cron-scheduler-DgrsqyQQ.js.map → cron-scheduler-CopTWKYB.js.map} +1 -1
- package/dist/{cron-store-91cd9Qzv.js → cron-store-FGaZOdMf.js} +3 -3
- package/dist/{cron-store-91cd9Qzv.js.map → cron-store-FGaZOdMf.js.map} +1 -1
- package/dist/dist-C1vNURUy.js +19354 -0
- package/dist/dist-C1vNURUy.js.map +1 -0
- package/dist/{errors-DpTMfX77.js → errors-NVbAQU25.js} +5 -1
- package/dist/errors-NVbAQU25.js.map +1 -0
- package/dist/{filter-dialect-DAVl1Nsm.js → filter-dialect-XtPJOCbD.js} +2 -2
- package/dist/{filter-dialect-DAVl1Nsm.js.map → filter-dialect-XtPJOCbD.js.map} +1 -1
- package/dist/{function-loader-BeFbN1-A.js → function-loader-D3YEHF6E.js} +2 -2
- package/dist/{function-loader-BeFbN1-A.js.map → function-loader-D3YEHF6E.js.map} +1 -1
- package/dist/{function-routes-CIwLXsZF.js → function-routes-DNDFIa7t.js} +3 -3
- package/dist/{function-routes-CIwLXsZF.js.map → function-routes-DNDFIa7t.js.map} +1 -1
- package/dist/functions/index.d.ts +2 -0
- package/dist/functions/index.js +162 -1
- package/dist/functions/index.js.map +1 -1
- package/dist/functions/rate-limit.d.ts +71 -0
- package/dist/{history-recorder-CNeqtTaR.js → history-recorder-C5RkbKS2.js} +3 -3
- package/dist/{history-recorder-CNeqtTaR.js.map → history-recorder-C5RkbKS2.js.map} +1 -1
- package/dist/{history-store-DseUt_dm.js → history-store-DzrJeEKv.js} +2 -2
- package/dist/{history-store-DseUt_dm.js.map → history-store-DzrJeEKv.js.map} +1 -1
- package/dist/index.d.ts +6 -0
- package/dist/index.es.js +1241 -213
- package/dist/index.es.js.map +1 -1
- package/dist/{internal-tables-CHFJHH7N.js → internal-tables-XxM_NdR_.js} +2 -2
- package/dist/{internal-tables-CHFJHH7N.js.map → internal-tables-XxM_NdR_.js.map} +1 -1
- package/dist/{jobs-WCyKVsUf.js → jobs-CFUwQTao.js} +3 -3
- package/dist/{jobs-WCyKVsUf.js.map → jobs-CFUwQTao.js.map} +1 -1
- package/dist/{jwt-JtQiewBW.js → jwt-CqhXs8Iz.js} +3 -3
- package/dist/{jwt-JtQiewBW.js.map → jwt-CqhXs8Iz.js.map} +1 -1
- package/dist/{keys-BTPoSvUs.js → keys-Btt6ZNqF.js} +2 -2
- package/dist/{keys-BTPoSvUs.js.map → keys-Btt6ZNqF.js.map} +1 -1
- package/dist/{load-schema-Cv5XLVjW.js → load-schema-B4Nv1mwq.js} +32 -4
- package/dist/{load-schema-Cv5XLVjW.js.map → load-schema-B4Nv1mwq.js.map} +1 -1
- package/dist/{logs-routes-BT4af1Or.js → logs-routes-C3CLYP-n.js} +3 -3
- package/dist/{logs-routes-BT4af1Or.js.map → logs-routes-C3CLYP-n.js.map} +1 -1
- package/dist/{offline-D_wKJcO3-RV6C9HnX.js → offline-ET6xI1ZO-BQpLQ7wh.js} +124 -7
- package/dist/offline-ET6xI1ZO-BQpLQ7wh.js.map +1 -0
- package/dist/{offline-store-DtmBwmKE-B17N4609.js → offline-store-DtmBwmKE-C9ba2NJv.js} +3 -3
- package/dist/{offline-store-DtmBwmKE-B17N4609.js.map → offline-store-DtmBwmKE-C9ba2NJv.js.map} +1 -1
- package/dist/{openapi-generator-CoAFACMx.js → openapi-generator-CAhJiwBm.js} +3 -3
- package/dist/{openapi-generator-CoAFACMx.js.map → openapi-generator-CAhJiwBm.js.map} +1 -1
- package/dist/{project-root-qDQzmsUD.js → project-root-CIrVZi-r.js} +2 -2
- package/dist/{project-root-qDQzmsUD.js.map → project-root-CIrVZi-r.js.map} +1 -1
- package/dist/{proxy-D18_bcQI.js → proxy-clweqa43.js} +3 -3
- package/dist/{proxy-D18_bcQI.js.map → proxy-clweqa43.js.map} +1 -1
- package/dist/push/push-options.d.ts +26 -0
- package/dist/push/push-routes.d.ts +30 -0
- package/dist/push/push-service.d.ts +13 -0
- package/dist/push/push-store.d.ts +45 -0
- package/dist/push/set-up.d.ts +25 -0
- package/dist/push/subscription-input.d.ts +26 -0
- package/dist/push/vapid-config.d.ts +35 -0
- package/dist/push/web-push-crypto.d.ts +44 -0
- package/dist/push/web-push-sender.d.ts +10 -0
- package/dist/{query-parser-D9Uf8aha.js → query-parser-Cd70kZO8.js} +5 -5
- package/dist/{query-parser-D9Uf8aha.js.map → query-parser-Cd70kZO8.js.map} +1 -1
- package/dist/{request-timeout-CpOgfQPK.js → request-timeout-cC3HT1Pf.js} +3 -3
- package/dist/{request-timeout-CpOgfQPK.js.map → request-timeout-cC3HT1Pf.js.map} +1 -1
- package/dist/{rls-simulator-routes-BvH6wI64.js → rls-simulator-routes-DI2sYaQt.js} +4 -4
- package/dist/{rls-simulator-routes-BvH6wI64.js.map → rls-simulator-routes-DI2sYaQt.js.map} +1 -1
- package/dist/{schema-editor-routes-CzITcAgt.js → schema-editor-routes-DEGwyQmx.js} +5 -5
- package/dist/{schema-editor-routes-CzITcAgt.js.map → schema-editor-routes-DEGwyQmx.js.map} +1 -1
- package/dist/{schema-tables-lJHnyqj4.js → schema-tables-DKFg6vMV.js} +3 -3
- package/dist/{schema-tables-lJHnyqj4.js.map → schema-tables-DKFg6vMV.js.map} +1 -1
- package/dist/{schema-tables-routes-Uss-ljon.js → schema-tables-routes-BfsNG4c4.js} +5 -5
- package/dist/{schema-tables-routes-Uss-ljon.js.map → schema-tables-routes-BfsNG4c4.js.map} +1 -1
- package/dist/{securityRuleToConditions-DD40f3ml.js → securityRuleToConditions-Bk5zRSoa.js} +2 -2
- package/dist/{securityRuleToConditions-DD40f3ml.js.map → securityRuleToConditions-Bk5zRSoa.js.map} +1 -1
- package/dist/{selection-hgC1szl6.js → selection-BOnbJvXD.js} +2 -2
- package/dist/{selection-hgC1szl6.js.map → selection-BOnbJvXD.js.map} +1 -1
- package/dist/serve-spa.d.ts +12 -0
- package/dist/{soft-delete-params-DDRmxT2z.js → soft-delete-params-Dhn0qKFv.js} +2 -2
- package/dist/{soft-delete-params-DDRmxT2z.js.map → soft-delete-params-Dhn0qKFv.js.map} +1 -1
- package/dist/{sql-export-routes-BKmQZ3xh.js → sql-export-routes-B3oqb1Jw.js} +3 -3
- package/dist/{sql-export-routes-BKmQZ3xh.js.map → sql-export-routes-B3oqb1Jw.js.map} +1 -1
- package/dist/{src-DLIb1O9l.js → src-CNZB3fuE.js} +192 -3
- package/dist/src-CNZB3fuE.js.map +1 -0
- package/dist/{table-source-editor-qmyi5vxX.js → table-source-editor-D_zNDhEU.js} +3 -3
- package/dist/{table-source-editor-qmyi5vxX.js.map → table-source-editor-D_zNDhEU.js.map} +1 -1
- package/dist/{upload-validation-B-psYLaN.js → upload-validation-BnIwo78L.js} +2 -2
- package/dist/{upload-validation-B-psYLaN.js.map → upload-validation-BnIwo78L.js.map} +1 -1
- package/package.json +5 -5
- package/dist/auth-BOz84vIr.js.map +0 -1
- package/dist/dist-fBcYxf4h.js +0 -19354
- package/dist/dist-fBcYxf4h.js.map +0 -1
- package/dist/errors-DpTMfX77.js.map +0 -1
- package/dist/offline-D_wKJcO3-RV6C9HnX.js.map +0 -1
- package/dist/src-DLIb1O9l.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"schema-tables-lJHnyqj4.js","names":[],"sources":["../../utils/dist/sha1.es.js","../../utils/dist/policy-names.es.js","../../common/src/util/policy/policyToPostgres.ts","../../common/src/util/policy/compileRulePolicies.ts","../../common/src/util/policy/policy-table.ts","../../common/src/util/tenant.ts","../../common/src/util/auth-default-policies.ts","../../common/src/util/junction-policies.ts","../src/api/schema-tables.ts"],"sourcesContent":["//#region src/sha1.ts\n/**\n* Minimal SHA-1 implementation that runs in both Node and the browser.\n*\n* This exists because generated Postgres policy names embed a SHA-1 digest of\n* the security rule. The DDL generator runs on the server (where `node:crypto`\n* is available) but the Studio has to derive the same names in the browser to\n* tell a policy it generated apart from one it did not. `node:crypto` cannot be\n* bundled for the browser, so the shared derivation needs a portable digest.\n*\n* SHA-1 is used purely to name things deterministically — never for security.\n* The output is byte-identical to `createHash(\"sha1\").update(str).digest(\"hex\")`,\n* which `sha1.test.ts` pins against `node:crypto` directly.\n*/\n/** Rotate a 32-bit word left by `n` bits. */\nfunction rotl(value, n) {\n\treturn value << n | value >>> 32 - n;\n}\n/**\n* SHA-1 digest of a string, hex-encoded.\n*\n* The input is encoded as UTF-8, matching Node's default handling of strings\n* passed to `hash.update(str)`.\n*/\nfunction sha1Hex(input) {\n\tconst bytes = Array.from(new TextEncoder().encode(input));\n\tconst bitLength = bytes.length * 8;\n\tbytes.push(128);\n\twhile (bytes.length % 64 !== 56) bytes.push(0);\n\tconst hi = Math.floor(bitLength / 4294967296);\n\tconst lo = bitLength >>> 0;\n\tbytes.push(hi >>> 24 & 255, hi >>> 16 & 255, hi >>> 8 & 255, hi & 255);\n\tbytes.push(lo >>> 24 & 255, lo >>> 16 & 255, lo >>> 8 & 255, lo & 255);\n\tlet h0 = 1732584193;\n\tlet h1 = 4023233417;\n\tlet h2 = 2562383102;\n\tlet h3 = 271733878;\n\tlet h4 = 3285377520;\n\tconst w = new Array(80);\n\tfor (let offset = 0; offset < bytes.length; offset += 64) {\n\t\tfor (let i = 0; i < 16; i++) {\n\t\t\tconst j = offset + i * 4;\n\t\t\tw[i] = bytes[j] << 24 | bytes[j + 1] << 16 | bytes[j + 2] << 8 | bytes[j + 3] | 0;\n\t\t}\n\t\tfor (let i = 16; i < 80; i++) w[i] = rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);\n\t\tlet a = h0;\n\t\tlet b = h1;\n\t\tlet c = h2;\n\t\tlet d = h3;\n\t\tlet e = h4;\n\t\tfor (let i = 0; i < 80; i++) {\n\t\t\tlet f;\n\t\t\tlet k;\n\t\t\tif (i < 20) {\n\t\t\t\tf = b & c | ~b & d;\n\t\t\t\tk = 1518500249;\n\t\t\t} else if (i < 40) {\n\t\t\t\tf = b ^ c ^ d;\n\t\t\t\tk = 1859775393;\n\t\t\t} else if (i < 60) {\n\t\t\t\tf = b & c | b & d | c & d;\n\t\t\t\tk = 2400959708;\n\t\t\t} else {\n\t\t\t\tf = b ^ c ^ d;\n\t\t\t\tk = 3395469782;\n\t\t\t}\n\t\t\tconst temp = rotl(a, 5) + f + e + k + w[i] | 0;\n\t\t\te = d;\n\t\t\td = c;\n\t\t\tc = rotl(b, 30);\n\t\t\tb = a;\n\t\t\ta = temp;\n\t\t}\n\t\th0 = h0 + a | 0;\n\t\th1 = h1 + b | 0;\n\t\th2 = h2 + c | 0;\n\t\th3 = h3 + d | 0;\n\t\th4 = h4 + e | 0;\n\t}\n\treturn [\n\t\th0,\n\t\th1,\n\t\th2,\n\t\th3,\n\t\th4\n\t].map((word) => (word >>> 0).toString(16).padStart(8, \"0\")).join(\"\");\n}\n//#endregion\nexport { sha1Hex };\n\n//# sourceMappingURL=sha1.es.js.map","import { sha1Hex } from \"./sha1.es.js\";\nimport { toPostgresIdentifier, truncateToBytes } from \"./names.es.js\";\nimport { isPolicyShorthand } from \"@rebasepro/types\";\n//#region src/policy-names.ts\n/**\n* Naming of the Postgres policies generated from a collection's security rules.\n*\n* A rule without an explicit `name` is compiled to `<table>_<op>_<hash>`, where\n* the hash covers the rule's semantics. The Studio needs the same names to tell\n* \"this policy came from your code\" apart from \"someone wrote this in SQL\" —\n* without them it treats generated policies as foreign and offers to import\n* them back into the codebase they came from.\n*\n* This is the single definition of that naming. The DDL and Drizzle generators\n* both derive names from here, so a change cannot silently rename every policy\n* in every deployed database while the UI keeps matching the old ones.\n*/\n/**\n* Stable digest of the parts of a rule that determine what the policy does.\n*\n* Two hash inputs, never mixed:\n*\n* - **A rule of a shape every release has known** hashes\n* `JSON.stringify({ a, m, op, ops, own, rol, pg, u, w, c, ch })`, byte for\n* byte as it always has — a deployed database keeps its policies by these\n* names, so this input must never move. Its `condition` / `check` are\n* serialised in the key order they were written in, as they always were.\n* - **A rule using a newer form** ({@link isNewShapeRule}: a\n* `PolicyShorthand` condition / check, `access` combined with a\n* condition / check, or `access: \"authenticated\"` / `\"registered\"`) hashes {@link newShapeHashInput}:\n* `\"rls2:\"` followed by canonical JSON in which every object's keys are\n* sorted, so `{ a: 1, b: 2 }` and `{ b: 2, a: 1 }` name the same policy.\n* A legacy input starts with `{`, so the two spaces cannot meet.\n*/\nfunction getPolicyNameHash(rule) {\n\tif (isNewShapeRule(rule)) return sha1Hex(newShapeHashInput(rule)).substring(0, 7);\n\treturn sha1Hex(JSON.stringify({\n\t\ta: rule.access,\n\t\tm: rule.mode,\n\t\top: rule.operation,\n\t\tops: rule.operations?.slice().sort(),\n\t\town: rule.ownerField,\n\t\trol: rule.roles?.slice().sort(),\n\t\tpg: rule.pgRoles?.slice().sort(),\n\t\tu: rule.using,\n\t\tw: rule.withCheck,\n\t\tc: frozenHashSpelling(rule.condition),\n\t\tch: frozenHashSpelling(rule.check)\n\t})).substring(0, 7);\n}\n/**\n* Whether a rule uses a form newer than the legacy hash input knows: a\n* `PolicyShorthand` condition or check, `access` together with a condition or\n* check, or `access: \"authenticated\"` (which older releases did not type and\n* compiled to a deny; it now means any signed-in caller, under a new name) or\n* `access: \"registered\"` (added after it). Such a rule hashes\n* {@link newShapeHashInput}; every other rule keeps the legacy input.\n*/\nfunction isNewShapeRule(rule) {\n\tif (rule.access === \"authenticated\" || rule.access === \"registered\") return true;\n\tif (rule.access !== void 0 && (rule.condition != null || rule.check != null)) return true;\n\treturn isPolicyShorthand(rule.condition) || isPolicyShorthand(rule.check);\n}\n/**\n* The hash input of a {@link isNewShapeRule new-shape} rule:\n* `\"rls2:\" + canonicalJson({ a, c, ch, m, op, ops, own, pg, rol, u, w })`.\n*\n* `canonicalJson` is `JSON.stringify` with every object's keys sorted (arrays\n* keep their order, `undefined` members are dropped). A shorthand is encoded\n* as `{ \"=\": [[column, value], …] }`, its pairs sorted by column — the\n* `=` tag keeps it apart from an expression node, which always carries\n* `kind`. `ops`, `rol` and `pg` are sorted as in the legacy input.\n*/\nfunction newShapeHashInput(rule) {\n\treturn `rls2:${canonicalJson({\n\t\ta: rule.access,\n\t\tm: rule.mode,\n\t\top: rule.operation,\n\t\tops: rule.operations?.slice().sort(),\n\t\town: rule.ownerField,\n\t\trol: rule.roles?.slice().sort(),\n\t\tpg: rule.pgRoles?.slice().sort(),\n\t\tu: rule.using,\n\t\tw: rule.withCheck,\n\t\tc: conditionHashValue(frozenHashSpelling(rule.condition)),\n\t\tch: conditionHashValue(frozenHashSpelling(rule.check))\n\t})}`;\n}\n/**\n* The frozen spelling of the hash input: a condition as it was spelled when\n* the names in deployed databases were derived from it.\n*\n* An `existsIn` node names its join table in `table`, which was spelled\n* `collection` before tables replaced collections in the backend vocabulary.\n* Hashed as written, every unnamed policy with a membership subquery would be\n* renamed by the rename alone. So the hash reads each `existsIn` node with\n* `table` put back as `collection`, in the same key position, and nothing\n* else changes: this is the input, byte for byte, the old spelling produced.\n* Never extend it to a new field — it exists only to keep old names.\n*/\nfunction frozenHashSpelling(condition) {\n\tif (Array.isArray(condition)) return condition.map(frozenHashSpelling);\n\tif (typeof condition !== \"object\" || condition === null) return condition;\n\tconst existsIn = \"kind\" in condition && condition.kind === \"existsIn\";\n\treturn Object.fromEntries(Object.entries(condition).map(([key, value]) => [existsIn && key === \"table\" ? \"collection\" : key, frozenHashSpelling(value)]));\n}\nfunction conditionHashValue(condition) {\n\tif (!isPolicyShorthand(condition)) return condition;\n\treturn { \"=\": Object.keys(condition).sort().map((column) => [column, condition[column]]) };\n}\nfunction canonicalJson(value) {\n\treturn JSON.stringify(value, (_key, member) => {\n\t\tif (typeof member !== \"object\" || member === null || Array.isArray(member)) return member;\n\t\treturn Object.fromEntries(Object.entries(member).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));\n\t});\n}\n/** The operations a rule expands to — `operations` wins over `operation`. */\nfunction getPolicyOperations(rule) {\n\treturn rule.operations && rule.operations.length > 0 ? rule.operations : [rule.operation ?? \"all\"];\n}\n/**\n* The names a rule compiled to before {@link getPolicyNamesForRule} learned\n* about Postgres's identifier limit — and still compiles to whenever they fit.\n*/\nfunction untruncatedPolicyNames(rule, tableName) {\n\tconst ops = getPolicyOperations(rule);\n\tconst ruleHash = getPolicyNameHash(rule);\n\treturn ops.map((op, opIdx) => rule.name ? ops.length > 1 ? `${rule.name}_${op}` : rule.name : `${tableName}_${op}_${ruleHash}${ops.length > 1 ? `_${opIdx}` : \"\"}`);\n}\n/** Whether Postgres, keeping 63 bytes of each, would store two of these under one name. */\nvar collideWhenStored = (names) => new Set(names.map(toPostgresIdentifier)).size < names.length;\n/**\n* `<prefix cut to fit>_<hash8>_<op>`, at most 63 bytes. The hash is over the\n* full name, so it carries everything the cut drops; the operation stays\n* readable at the end.\n*/\nfunction suffixFirstPolicyName(fullName, op) {\n\tconst tail = `_${sha1Hex(fullName).substring(0, 8)}_${op}`;\n\treturn `${truncateToBytes(fullName, 63 - tail.length).replace(/_+$/, \"\")}${tail}`;\n}\n/**\n* Every Postgres policy name a single rule compiles to — one per operation.\n*\n* `<table>_<op>_<hash>[_<i>]`, or `<name>[_<op>]` for a named rule — byte for\n* byte what every release has written, with one exception. Postgres keeps the\n* first 63 bytes of an identifier, so a multi-operation rule whose names differ\n* only past that point (the injected `<table>_default_admin_write_<op>` on a\n* table of 42 bytes or more) used to store every operation under ONE name: each\n* `CREATE POLICY` replaced the last, only the final operation survived, and the\n* table denied the others. Only for such a rule each name is derived\n* suffix-first instead — see {@link suffixFirstPolicyName} — and\n* {@link getPolicySupersededNames} names the one policy the old names left in\n* the database, so the next boot or push replaces it. A single over-long name\n* that is unique as stored is left as it is.\n*\n* @param rule The security rule as written in the collection config.\n* @param tableName The rule's table (see `getTableName` in `@rebasepro/common`).\n*/\nfunction getPolicyNamesForRule(rule, tableName) {\n\tconst names = untruncatedPolicyNames(rule, tableName);\n\tif (!collideWhenStored(names)) return names;\n\tconst ops = getPolicyOperations(rule);\n\treturn names.map((name, index) => suffixFirstPolicyName(name, ops[index]));\n}\n/**\n* The policy names, as Postgres stored them, that the old naming wrote for\n* this rule and {@link getPolicyNamesForRule} no longer produces — empty unless\n* the rule's per-operation names collided at 63 bytes. Dropping them is what\n* turns a database a previous release left with one truncated policy into one\n* with a policy per operation.\n*/\nfunction getPolicySupersededNames(rule, tableName) {\n\tconst names = untruncatedPolicyNames(rule, tableName);\n\tif (!collideWhenStored(names)) return [];\n\treturn Array.from(new Set(names.map(toPostgresIdentifier)));\n}\n/** Every policy name a set of rules compiles to, for membership checks. */\nfunction getPolicyNamesForRules(rules, tableName) {\n\tconst names = /* @__PURE__ */ new Set();\n\tfor (const rule of rules) for (const name of getPolicyNamesForRule(rule, tableName)) names.add(name);\n\treturn names;\n}\n/** What every {@link adminRequestPolicyName} ends with: `_ar_` and eight hex digits. */\nvar ADMIN_REQUEST_POLICY_SUFFIX = /_ar_[0-9a-f]{8}$/;\n/**\n* The name of an admin-only policy's companion — the `USING (true)` grant to\n* the admin request roles (`REBASE_ADMIN_REQUEST_ROLE`): the base name cut to\n* fit, then `_ar_` and a hash of the whole base name, at most 63 bytes, so two\n* bases that share a cut prefix never share a companion.\n*/\nfunction adminRequestPolicyName(baseName) {\n\tconst tail = `_ar_${sha1Hex(baseName).substring(0, 8)}`;\n\treturn `${truncateToBytes(baseName, 63 - tail.length).replace(/_+$/, \"\")}${tail}`;\n}\n//#endregion\nexport { ADMIN_REQUEST_POLICY_SUFFIX, adminRequestPolicyName, getPolicyNameHash, getPolicyNamesForRule, getPolicyNamesForRules, getPolicyOperations, getPolicySupersededNames, isNewShapeRule, newShapeHashInput };\n\n//# sourceMappingURL=policy-names.es.js.map","import { ANONYMOUS_USER_IDS, PolicyExpression, PolicyOperand, PolicyCompareOperator, ExistsInPolicyExpression, RLS_IS_ANONYMOUS_SQL, RLS_JWT_SQL, RLS_ROLES_SQL, RLS_UID_SQL, rewriteLegacyRlsFunctions } from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\nimport type { ClaimCastType, PolicyColumn, PolicyTable, ResolvePolicyTable } from \"./policy-table\";\n\n/**\n * Options for {@link compilePolicyExpression}.\n */\nexport interface PolicyCompileOptions {\n /**\n * Resolve a table by slug. Required to compile\n * {@link ExistsInPolicyExpression} (`policy.existsIn`) — the compiler needs\n * the joined table's name and schema. When omitted, the join table falls\n * back to a snake_cased slug.\n */\n resolveTable?: ResolvePolicyTable;\n}\n\n/**\n * The lexical scope threaded through compilation. It changes when we descend\n * into an `existsIn` subquery: inside it, `field` refers to the joined table\n * (aliased) while `outerField` refers to the outer RLS row (table-qualified).\n */\ninterface CompileScope {\n /** The table whose columns a bare `field` operand resolves against. */\n fieldTable?: PolicyTable;\n /** SQL prefix for `field` operands (`\"\"` at top level, `\"alias\".` in a subquery). */\n fieldPrefix: string;\n /** The outer RLS table, for `outerField` operands. */\n outerTable?: PolicyTable;\n /** SQL prefix for `outerField` operands (`\"\"` at top level, `\"schema\".\"table\".` in a subquery). */\n outerPrefix: string;\n resolveTable?: ResolvePolicyTable;\n /** Monotonic counter for generating unique subquery aliases. */\n alias: { n: number };\n /**\n * True inside a hoisted `(SELECT …)`. The subquery already evaluates its\n * whole body once per statement, so the helpers in it are emitted bare.\n */\n inInitPlan: boolean;\n}\n\n/**\n * Compiles a {@link PolicyExpression} to a PostgreSQL boolean SQL string,\n * suitable for a `USING (...)` / `WITH CHECK (...)` clause.\n *\n * This is one of the two consumers of the shared policy model (the other being\n * {@link evaluatePolicy}); the Postgres schema generators call it so that DDL\n * and the admin UI derive from the exact same expression.\n *\n * ## Row-independent parts are evaluated once per statement\n *\n * Every part of a policy that does not read the row — `serverContext()`, a\n * roles test, a comparison of the caller with a literal, a claim — is wrapped\n * in a scalar subquery: the default baseline compiles to\n * `(SELECT (rebase.uid() IS NULL) OR (string_to_array(rebase.roles(), ',') && ARRAY['admin']))`,\n * and an owner rule to `owner_id = (SELECT rebase.uid())`. Postgres plans an\n * uncorrelated scalar subquery as an initPlan, computed once per statement.\n *\n * Bare, the same clause is a security-barrier qual Postgres evaluates per row,\n * and it estimates `uid() IS NULL OR roles && …` to pass 1.5% of the table. A\n * page past that point (offset 20,000 of a million rows) was planned as a\n * sequential scan and an on-disk sort of the whole table: 7.3 s and a 640 MB\n * sort per request, against 4 ms off the primary key once the predicate is an\n * initPlan, whose estimate is 50%.\n *\n * Same meaning, by construction: only subtrees that reference no column are\n * wrapped (never `field`, `outerField`, `existsIn` or `raw`), a scalar subquery\n * without `FROM` returns exactly one row whose value is the expression's —\n * NULL included, so three-valued logic is untouched — and the helpers are\n * STABLE, so their value cannot change within a statement anyway.\n * `policy-shapes-equivalence.test.ts` runs every shape against Postgres both\n * ways.\n */\nexport function compilePolicyExpression(expr: PolicyExpression, table?: PolicyTable, options?: PolicyCompileOptions): string {\n return compile(expr, {\n fieldTable: table,\n fieldPrefix: \"\",\n outerTable: table,\n outerPrefix: \"\",\n resolveTable: options?.resolveTable,\n alias: { n: 0 },\n inInitPlan: false\n });\n}\n\n/**\n * Whether `expr` never reads the row: no `field` / `outerField` operand, no\n * correlated `existsIn`, no `raw` SQL (which may name any column).\n */\nfunction readsNoRow(expr: PolicyExpression): boolean {\n switch (expr.kind) {\n case \"and\":\n case \"or\":\n return expr.operands.every(readsNoRow);\n case \"not\":\n return readsNoRow(expr.operand);\n case \"compare\":\n return !readsRow(expr.left) && !readsRow(expr.right);\n case \"existsIn\":\n case \"raw\":\n return false;\n default:\n return true;\n }\n}\n\nconst readsRow = (operand: PolicyOperand): boolean =>\n operand.kind === \"field\" || operand.kind === \"outerField\";\n\nconst callsHelper = (operand: PolicyOperand): boolean =>\n operand.kind === \"authUid\" || operand.kind === \"authRoles\" || operand.kind === \"authClaim\";\n\n/** Whether `expr` calls one of the `rebase.*` helpers anywhere. */\nfunction callsAuthHelper(expr: PolicyExpression): boolean {\n switch (expr.kind) {\n case \"and\":\n case \"or\":\n return expr.operands.some(callsAuthHelper);\n case \"not\":\n return callsAuthHelper(expr.operand);\n case \"compare\":\n return callsHelper(expr.left) || callsHelper(expr.right);\n case \"rolesOverlap\":\n case \"rolesContain\":\n case \"authenticated\":\n case \"registered\":\n case \"serverContext\":\n return true;\n default:\n return false;\n }\n}\n\n/**\n * Whether `expr` is compiled as one `(SELECT …)`: it reads no row and calls a\n * helper (a constant has nothing to save).\n *\n * `authenticated()` and `registered()` on their own are the exception: they\n * wrap each helper call instead — `(SELECT rebase.uid()) IS NOT NULL AND …`.\n * Their estimate is already near 100%, so there is no plan to fix, and the\n * per-call spelling is the one RLS linters can still read: `rls-check` flags a\n * policy that is nothing but \"signed in\" (every account reads every row) by\n * splitting it on AND, and it reads `( SELECT rebase.uid() AS uid)` as the\n * caller id — but a whole conjunction inside one subquery is opaque to it.\n * Inside a larger hoisted subtree they are emitted bare, like everything else\n * there.\n */\nfunction isHoistable(expr: PolicyExpression): boolean {\n if (expr.kind === \"authenticated\" || expr.kind === \"registered\") return false;\n return readsNoRow(expr) && callsAuthHelper(expr);\n}\n\n/** A helper call, as an initPlan unless it already sits inside one. */\nfunction helperSql(sqlText: string, scope: CompileScope): string {\n return scope.inInitPlan ? sqlText : `(SELECT ${sqlText})`;\n}\n\nfunction compile(expr: PolicyExpression, scope: CompileScope): string {\n if (!scope.inInitPlan && isHoistable(expr)) {\n return `(SELECT ${compile(expr, { ...scope, inInitPlan: true })})`;\n }\n switch (expr.kind) {\n case \"true\":\n return \"true\";\n case \"false\":\n return \"false\";\n case \"and\":\n return expr.operands.length === 0\n ? \"true\"\n : expr.operands.map(o => `(${compile(o, scope)})`).join(\" AND \");\n case \"or\":\n return expr.operands.length === 0\n ? \"false\"\n : expr.operands.map(o => `(${compile(o, scope)})`).join(\" OR \");\n case \"not\":\n return `NOT (${compile(expr.operand, scope)})`;\n case \"compare\": {\n // `rebase.uid()` returns text; cast the column side so uuid / integer\n // id columns compare cleanly instead of failing with\n // \"operator does not exist: uuid = text\" at CREATE POLICY time.\n const castForAuthUid = (operand: PolicyOperand, sqlText: string, other: PolicyOperand): string =>\n other.kind === \"authUid\" && (operand.kind === \"field\" || operand.kind === \"outerField\")\n ? `(${sqlText})::text`\n : sqlText;\n // A claim is text too, and the same mismatch applies — but here the\n // cast goes the OTHER way, onto the claim. Casting the column would\n // compile and would take the index off it, and this operand exists\n // to carry a tenancy predicate that is ANDed into every read of the\n // table. See {@link claimCastType}.\n const claimSql = (operand: PolicyOperand, other: PolicyOperand): string | undefined =>\n operand.kind === \"authClaim\"\n ? helperSql(authClaimSql(operand.name, claimCastType(other, scope)), scope)\n : undefined;\n const leftSql = claimSql(expr.left, expr.right)\n ?? castForAuthUid(expr.left, operandToSql(expr.left, scope), expr.right);\n const rightSql = claimSql(expr.right, expr.left)\n ?? castForAuthUid(expr.right, operandToSql(expr.right, scope), expr.left);\n return `${leftSql} ${COMPARE_SQL[expr.op]} ${rightSql}`;\n }\n case \"rolesOverlap\":\n return `string_to_array(${RLS_ROLES_SQL}, ',') && ${rolesArraySql(expr.roles)}`;\n case \"rolesContain\":\n return `string_to_array(${RLS_ROLES_SQL}, ',') @> ${rolesArraySql(expr.roles)}`;\n case \"authenticated\":\n // `IS NOT NULL` alone is a tautology on the user path: every\n // user-context request sets `app.uid`, and an anonymous one sets\n // it to a sentinel. Excluding the sentinels is what makes this mean\n // \"signed in\" rather than \"anyone at all\".\n //\n // Every sentinel, not just the current one. This clause is written\n // into the database and outlives the server that generated it: a\n // policy compiled here may be enforced against an older server that\n // still reports `'anon'`, which is exactly how excluding one\n // spelling turned this helper into a grant. See ANONYMOUS_USER_IDS.\n return `${helperSql(RLS_UID_SQL, scope)} IS NOT NULL`\n + ` AND ${helperSql(RLS_UID_SQL, scope)} NOT IN (${ANONYMOUS_USER_IDS.map(quoteLiteral).join(\", \")})`;\n case \"registered\":\n // \"Signed in\" AND \"not a guest\". The first half is the same clause\n // `authenticated` compiles to; the second is the fact anonymous\n // sign-in used not to put anywhere the database could see, so a\n // guest and an account were one principal inside every policy.\n //\n // `rebase.is_anonymous()` defaults to false when its GUC is unset,\n // so a policy compiled here and enforced by an older server reads\n // every session as an account — which is the behaviour that\n // deployment already had, rather than a lockout.\n return `${helperSql(RLS_UID_SQL, scope)} IS NOT NULL`\n + ` AND ${helperSql(RLS_UID_SQL, scope)} NOT IN (${ANONYMOUS_USER_IDS.map(quoteLiteral).join(\", \")})`\n + ` AND NOT ${helperSql(RLS_IS_ANONYMOUS_SQL, scope)}`;\n case \"serverContext\":\n // Only the built-in server flows leave `app.uid` unset.\n return `${RLS_UID_SQL} IS NULL`;\n case \"existsIn\":\n return compileExistsIn(expr, scope);\n case \"raw\": {\n // A project written against a pre-1.0 release may still spell the\n // helpers `auth.uid()`. Rewritten rather than rejected: the rule\n // means exactly the same thing, the developer cannot be expected to\n // have read a changelog mid-deploy, and the alternative is a policy\n // that compiles cleanly and then denies every row at runtime because\n // it calls a function that no longer exists.\n //\n // The counterpart is `warnOnLegacyRlsFunctions`, which says so once\n // at boot with the file to edit — silence here would leave the old\n // spelling working forever and make the migration permanent.\n const sqlText = rewriteLegacyRlsFunctions(expr.sql);\n\n // Full-power escape hatch: `{column}` denotes a column of the outer\n // RLS row. It must be table-qualified, not bare: raw SQL may open its\n // own subquery over the same table, and there a bare name binds to the\n // inner scope, collapsing `m.x = {x}` into the tautology `m.x = m.x`.\n return substituteRawPlaceholders(sqlText, (col) =>\n `${outerQualifier(scope)}${resolveColumnName(col, scope.outerTable)}`);\n }\n }\n}\n\n/**\n * Replace each `{column}` placeholder in raw SQL with `replace(column)`, but\n * only in the SQL itself: not inside a string literal (`'…'`, `E'…'` with its\n * backslash escapes, `$$…$$`, `$tag$…$tag$`), a quoted identifier (`\"…\"`) or a\n * comment (`--` to the end of the line, or a block comment, which nests).\n *\n * A placeholder inside a literal is never meant: it would put the column's\n * *name* into the text. A regex quantifier is, and it has the same shape. A\n * stored claim-tenancy policy on a uuid column guards its cast with\n * `'^[0-9a-fA-F]{8}-…{12}$'`, so imported through \"Import from table\" or the\n * Studio's \"Import to codebase\" (which keep it as `raw`), its `{8}` became\n * `\"public\".\"projects\".\"8\"`, the guard never matched, and the policy denied\n * every tenant.\n */\nfunction substituteRawPlaceholders(sql: string, replace: (column: string) => string): string {\n let out = \"\";\n let i = 0;\n while (i < sql.length) {\n const c = sql[i];\n let end = i + 1;\n if (c === \"'\") {\n end = skipQuoted(sql, i, \"'\", isEscapeStringPrefix(sql, i));\n } else if (c === \"\\\"\") {\n end = skipQuoted(sql, i, \"\\\"\", false);\n } else if (c === \"-\" && sql[i + 1] === \"-\") {\n const newline = sql.indexOf(\"\\n\", i);\n if (newline === -1) {\n // A line comment ends at a newline and nowhere else, and this\n // text is spliced into `USING (…)` and between the operands of\n // an AND / OR: unterminated, the comment swallows the closing\n // paren and whatever follows it, and `CREATE POLICY` fails.\n out += `${sql.slice(i)}\\n`;\n break;\n }\n end = newline;\n } else if (c === \"/\" && sql[i + 1] === \"*\") {\n end = skipBlockComment(sql, i);\n } else if (c === \"$\") {\n const tag = dollarQuoteTagAt(sql, i);\n if (tag) {\n const close = sql.indexOf(tag, i + tag.length);\n end = close === -1 ? sql.length : close + tag.length;\n }\n } else if (c === \"{\") {\n const placeholder = /^\\{(\\w+)\\}/.exec(sql.slice(i));\n if (placeholder) {\n out += replace(placeholder[1]);\n i += placeholder[0].length;\n continue;\n }\n }\n out += sql.slice(i, end);\n i = end;\n }\n return out;\n}\n\n/** A character that continues an identifier, `$` included (`a$b` is one name). */\nconst IDENTIFIER_CHAR = /[A-Za-z0-9_$\\u0080-\\uffff]/;\n\n/** The end of the `quote`-quoted span opening at `start`; a doubled quote stays inside. */\nfunction skipQuoted(sql: string, start: number, quote: string, backslashEscapes: boolean): number {\n let i = start + 1;\n while (i < sql.length) {\n if (backslashEscapes && sql[i] === \"\\\\\") {\n i += 2;\n } else if (sql[i] === quote) {\n if (sql[i + 1] !== quote) return i + 1;\n i += 2;\n } else {\n i++;\n }\n }\n return sql.length;\n}\n\n/** Whether the `'` at `quote` opens an `E'…'` string, where `\\'` escapes a quote. */\nfunction isEscapeStringPrefix(sql: string, quote: number): boolean {\n const prefix = sql[quote - 1];\n return (prefix === \"E\" || prefix === \"e\") && !IDENTIFIER_CHAR.test(sql[quote - 2] ?? \"\");\n}\n\n/** The end of the block comment opening at `start`. Postgres nests them. */\nfunction skipBlockComment(sql: string, start: number): number {\n let depth = 0;\n let i = start;\n while (i < sql.length) {\n if (sql[i] === \"/\" && sql[i + 1] === \"*\") {\n depth++;\n i += 2;\n } else if (sql[i] === \"*\" && sql[i + 1] === \"/\") {\n depth--;\n i += 2;\n if (depth === 0) return i;\n } else {\n i++;\n }\n }\n return sql.length;\n}\n\n/**\n * The dollar-quote tag (`$$`, `$tag$`) opening at `at`, or undefined. Not one\n * after an identifier character (`a$b$` is a name), nor `$1` (a parameter: a\n * tag cannot start with a digit).\n */\nfunction dollarQuoteTagAt(sql: string, at: number): string | undefined {\n if (at > 0 && IDENTIFIER_CHAR.test(sql[at - 1])) return undefined;\n return /^\\$(?:[A-Za-z_\\u0080-\\uffff][A-Za-z0-9_\\u0080-\\uffff]*)?\\$/.exec(sql.slice(at))?.[0];\n}\n\n/**\n * Compiles `existsIn` to a correlated `EXISTS (SELECT 1 FROM <join> WHERE ...)`.\n * Inside the subquery, `field` operands bind to the aliased join table and\n * `outerField` operands bind to the (table-qualified) outer RLS row.\n */\nfunction compileExistsIn(expr: ExistsInPolicyExpression, scope: CompileScope): string {\n const join = scope.resolveTable?.(expr.table);\n const joinTable = join ? join.table : toSnakeCase(expr.table);\n const joinSchema = join?.schema ?? scope.outerTable?.schema ?? \"public\";\n const alias = `_ex${scope.alias.n++}`;\n\n // `outerField` inside the subquery must be qualified with the outer table,\n // otherwise a bare column name would bind to the joined table instead.\n const outerPrefix = outerQualifier(scope);\n\n const innerScope: CompileScope = {\n fieldTable: join,\n fieldPrefix: `\"${alias}\".`,\n outerTable: scope.outerTable,\n outerPrefix,\n resolveTable: scope.resolveTable,\n alias: scope.alias,\n inInitPlan: scope.inInitPlan\n };\n return `EXISTS (SELECT 1 FROM \"${joinSchema}\".\"${joinTable}\" \"${alias}\" WHERE ${compile(expr.where, innerScope)})`;\n}\n\nconst COMPARE_SQL: Record<PolicyCompareOperator, string> = {\n eq: \"=\",\n neq: \"!=\",\n lt: \"<\",\n lte: \"<=\",\n gt: \">\",\n gte: \">=\"\n};\n\nfunction operandToSql(operand: PolicyOperand, scope: CompileScope): string {\n switch (operand.kind) {\n case \"field\":\n return `${scope.fieldPrefix}${resolveColumnName(operand.name, scope.fieldTable)}`;\n case \"outerField\":\n return `${scope.outerPrefix}${resolveColumnName(operand.name, scope.outerTable)}`;\n case \"literal\":\n return quoteLiteral(operand.value);\n case \"authUid\":\n return helperSql(RLS_UID_SQL, scope);\n case \"authRoles\":\n return helperSql(`string_to_array(${RLS_ROLES_SQL}, ',')`, scope);\n case \"authClaim\":\n // Uncast — the shape a claim has when nothing says what it is being\n // compared against (a claim on both sides, or against a literal).\n // The `compare` arm replaces this whenever the other operand names\n // a typed column.\n return helperSql(authClaimSql(operand.name, \"text\"), scope);\n }\n}\n\n/**\n * The Postgres type a claim has to be cast to, to be compared with `operand`.\n *\n * `\"text\"` means \"no cast\": a claim already is text, and a `text` / `varchar`\n * column compares with it directly and keeps using its index.\n *\n * Read from the column the operand names — a `belongsTo` link's foreign key\n * column has the target's key type, which is the ordinary shape of a tenant\n * field. Unknown resolves to `\"text\"`, which is the safe direction: a\n * redundant `text` comparison costs nothing, while a missing `uuid` cast is a\n * `CREATE POLICY` that fails and leaves a table with RLS enabled and no\n * policy — which denies every row.\n */\nfunction claimCastType(operand: PolicyOperand, scope: CompileScope): ClaimCastType {\n if (operand.kind !== \"field\" && operand.kind !== \"outerField\") return \"text\";\n const table = operand.kind === \"field\" ? scope.fieldTable : scope.outerTable;\n return columnOf(operand.name, table)?.claimCast ?? \"text\";\n}\n\n/**\n * `NULLIF(rebase.jwt() ->> 'name', '')`, cast to the column's type.\n *\n * Two things here are load-bearing beyond the cast:\n *\n * - **`NULLIF(…, '')`.** An absent claim already reads as NULL, but one set to\n * the empty string does not, and `''::uuid` raises rather than denying. Both\n * spellings of \"this caller has no tenant\" have to reach the comparison as\n * NULL, which is never true and therefore never a grant.\n * - **The guard.** The cast sits inside a `CASE` that first checks the text is\n * well-formed, because `'nonsense'::uuid` raises `invalid input syntax` — and\n * a policy that raises does not deny a row, it fails the whole statement. A\n * caller holding a malformed claim would get a 500 on every read of the table\n * instead of an empty list. `CASE` rather than an `AND` guard because only\n * `CASE` is guaranteed not to evaluate its arms out of order.\n *\n * The whole expression is STABLE (`rebase.jwt()` is), so Postgres evaluates it\n * once per query and can still use a btree index on the column it is compared\n * against — which is the entire reason the cast is on this side.\n */\nfunction authClaimSql(name: string, cast: ClaimCastType): string {\n const claim = `NULLIF(${RLS_JWT_SQL} ->> ${quoteLiteral(name)}, '')`;\n if (cast === \"text\") return claim;\n return `CASE WHEN ${claim} ~ '${CLAIM_CAST_GUARDS[cast]}' THEN (${claim})::${cast} END`;\n}\n\n/**\n * The text a claim must match before it is cast, per target type.\n *\n * The `bigint` guard caps the digit run at 18 rather than matching any run of\n * digits: `'99999999999999999999'::bigint` is a range error, which fails the\n * statement exactly as the syntax error would have.\n */\nconst CLAIM_CAST_GUARDS: Record<Exclude<ClaimCastType, \"text\">, string> = {\n uuid: \"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$\",\n bigint: \"^-?[0-9]{1,18}$\",\n numeric: \"^-?[0-9]+(\\\\.[0-9]+)?$\"\n};\n\n/**\n * SQL prefix that qualifies a column of the outer RLS row (`\"schema\".\"table\".`),\n * or `\"\"` when the table is unknown.\n */\nfunction outerQualifier(scope: CompileScope): string {\n const table = scope.outerTable?.table;\n if (!table) return \"\";\n return `\"${scope.outerTable?.schema ?? \"public\"}\".\"${table}\".`;\n}\n\n/**\n * The column a rule's key names: a column key, or a `belongsTo` link, which\n * addresses its foreign key column — `org` compares `org_id`. A rule naming a\n * relation (`ownerField: \"org\"`, a tenancy declaration over a `belongsTo`)\n * once compiled to a column called `org`, which does not exist; `CREATE\n * POLICY` then failed and the table denied every row.\n */\nfunction columnOf(key: string, table: PolicyTable | undefined): PolicyColumn | undefined {\n if (!table) return undefined;\n if (Object.prototype.hasOwnProperty.call(table.columns, key)) return table.columns[key];\n if (Object.prototype.hasOwnProperty.call(table.links, key)) return table.links[key];\n return undefined;\n}\n\nfunction resolveColumnName(key: string, table?: PolicyTable): string {\n return quoteColumnIdentifier(columnOf(key, table)?.column ?? toSnakeCase(key));\n}\n\n/**\n * Every PostgreSQL keyword that cannot stand as a bare column reference.\n * Appendix C's two reserved categories — plain \"reserved\", and \"reserved (can\n * be function or type name)\" — since neither may name a column unquoted.\n */\nconst RESERVED_SQL_WORDS = new Set([\n \"all\", \"analyse\", \"analyze\", \"and\", \"any\", \"array\", \"as\", \"asc\", \"asymmetric\", \"authorization\",\n \"binary\", \"both\", \"case\", \"cast\", \"check\", \"collate\", \"collation\", \"column\", \"concurrently\",\n \"constraint\", \"create\", \"cross\", \"current_catalog\", \"current_date\", \"current_role\",\n \"current_schema\", \"current_time\", \"current_timestamp\", \"current_user\", \"default\", \"deferrable\",\n \"desc\", \"distinct\", \"do\", \"else\", \"end\", \"except\", \"false\", \"fetch\", \"for\", \"foreign\", \"freeze\",\n \"from\", \"full\", \"grant\", \"group\", \"having\", \"ilike\", \"in\", \"initially\", \"inner\", \"intersect\",\n \"into\", \"is\", \"isnull\", \"join\", \"lateral\", \"leading\", \"left\", \"like\", \"limit\", \"localtime\",\n \"localtimestamp\", \"natural\", \"not\", \"notnull\", \"null\", \"offset\", \"on\", \"only\", \"or\", \"order\",\n \"outer\", \"overlaps\", \"placing\", \"primary\", \"references\", \"returning\", \"right\", \"select\",\n \"session_user\", \"similar\", \"some\", \"symmetric\", \"system_user\", \"table\", \"tablesample\", \"then\",\n \"to\", \"trailing\", \"true\", \"union\", \"unique\", \"user\", \"using\", \"variadic\", \"verbose\", \"when\",\n \"where\", \"window\", \"with\"\n]);\n\n/** An identifier Postgres reads back unchanged without quotes. */\nconst BARE_IDENTIFIER = /^[a-z_][a-z0-9_$]*$/;\n\n/**\n * Quote a column reference when Postgres would not read the bare name as that\n * column — and only then.\n *\n * Three ways a bare name goes wrong, in ascending order of how long it takes to\n * notice:\n *\n * - **Case.** `columnName` is used verbatim, and `rebase schema introspect`\n * populates it from a live database, so a legacy `\"createdAt\"` column arrives\n * spelled exactly that way. Unquoted, Postgres folds it to `createdat` and\n * `CREATE POLICY` fails with \"column does not exist\" — the collection keeps\n * RLS enabled with no policy, which denies every row.\n * - **Syntax.** A column named `order` or `default` is a syntax error mid-clause.\n * - **Silent rebinding.** `user`, `current_user`, `session_user`, `current_date`\n * and friends are *valid bare expressions*, so the policy compiles, applies,\n * and is reported as a success — while comparing against the connected role\n * or the wall clock instead of the column. Under RLS every request runs as the\n * same `rebase_user` role, so `USING (user = rebase.uid())` is a constant: it\n * denies everything, and its negation admits everything.\n *\n * Only the names that need it are quoted, so an ordinary snake_case policy body\n * is emitted byte-for-byte as before. That keeps generated artifacts and the\n * policies already stored in shipped databases stable — this fix reaches the\n * clauses that were broken and no others.\n */\nfunction quoteColumnIdentifier(name: string): string {\n if (BARE_IDENTIFIER.test(name) && !RESERVED_SQL_WORDS.has(name)) return name;\n return `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n}\n\nfunction quoteLiteral(value: string | number | boolean | null): string {\n if (value === null) return \"NULL\";\n if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n if (typeof value === \"number\") return String(value);\n return `'${value.replace(/'/g, \"''\")}'`;\n}\n\n/**\n * Sorted, single-quoted `ARRAY['a','b']` — matches the generators' output.\n *\n * Each role goes through {@link quoteLiteral}, which leaves an ordinary name\n * byte-for-byte as it is and doubles a quote inside one (`o'reilly`). An\n * unescaped quote would close the literal early: a syntax error at\n * `CREATE POLICY`, which leaves the table with RLS on and no policy, or — for a\n * name built to do it — SQL of its own in the clause.\n */\nfunction rolesArraySql(roles: readonly string[]): string {\n // An empty `ARRAY[]` has no element type, and Postgres refuses it (\"cannot\n // determine type of empty array\"): the whole `CREATE POLICY` fails, taking\n // the rest of the rule's condition with it. Typed, it means what the\n // evaluator says — overlapping no role is false, containing none is true.\n if (roles.length === 0) return \"ARRAY[]::text[]\";\n return `ARRAY[${[...roles].sort().map(quoteLiteral).join(\",\")}]`;\n}\n","import { declaredRlsPolicyShape, isRedactedSecurityRule, DEFAULT_DATA_SOURCE_KEY, REBASE_ADMIN_REQUEST_ROLE, REBASE_ADMIN_ROLE, RLS_IS_REQUEST_ROLE_SQL, type PolicyExpression, type SecurityOperation, type SecurityRule } from \"@rebasepro/types\";\nimport { adminRequestPolicyName, getPolicyNamesForRule } from \"@rebasepro/utils\";\nimport { securityRuleToConditions } from \"./securityRuleToConditions\";\nimport { policyShorthandColumns } from \"./policyCondition\";\nimport { compilePolicyExpression, type PolicyCompileOptions } from \"./policyToPostgres\";\nimport type { PolicyTable } from \"./policy-table\";\n\n/**\n * One Postgres policy a security rule compiles to: its name and the clauses\n * `CREATE POLICY` is given for it.\n */\nexport interface CompiledRulePolicy {\n name: string;\n operation: SecurityOperation;\n /** `permissive` | `restrictive`, lower-case as the rule spells it. */\n mode: \"permissive\" | \"restrictive\";\n /** The `TO` list. Sorted, `[\"public\"]` when the rule names none. */\n roles: string[];\n /** The `USING` clause, or `null` when the operation takes none. */\n using: string | null;\n /** The `WITH CHECK` clause, or `null` when the operation takes none. */\n withCheck: string | null;\n /**\n * Set when `roles` is `[\"rebase_admin\"]` because the compiler put it there\n * (`adminPolicies: \"adminRole\"`), not because the rule named it — so a\n * database where that role cannot exist may write this policy `TO public`,\n * which is exactly what it was before, and never widen a rule's own list.\n */\n adminTarget?: true;\n /**\n * Set on the companion of an admin-only policy: the same operation, `TO`\n * `rebase_admin_request`, `USING (true)` — so an admin request's plan\n * carries no policy barrier and uses the indexes the owner's does (see\n * `REBASE_ADMIN_REQUEST_ROLE`). Never written to any other role: where\n * that role cannot exist the companion is left out, never moved `TO\n * public` the way an {@link adminTarget} policy is — `TO public USING\n * (true)` would hand every row to everyone.\n */\n adminRequestTarget?: true;\n}\n\n/** The switches {@link compileTableRulePolicies} reads. */\nexport interface RulePolicySwitches {\n /**\n * The caller runs admin requests as a role inside `rebase_admin` (the\n * Postgres driver from the release that introduced `rls.adminPolicies`), so\n * a server-or-admin grant may be written `TO rebase_admin` when the\n * declaration allows it. Off by default, and that is load-bearing: the\n * managed runtime supplies this package to bundles that vendor an older\n * driver, which never switches admins to such a role — compiled `TO\n * rebase_admin` under it, every admin request would be refused.\n */\n adminRole?: boolean;\n /**\n * Give each admin-only policy its `TO rebase_admin_request USING (true)`\n * companion ({@link CompiledRulePolicy.adminRequestTarget}). Only with\n * {@link adminRole}, and off by default for the same reason: a driver that\n * does not create that role must not be handed policies naming it.\n */\n adminRequestRole?: boolean;\n}\n\n/** Options for {@link compileTableRulePolicies}. */\nexport interface RulePolicyCompileOptions extends PolicyCompileOptions, RulePolicySwitches {}\n\n/**\n * The policies one security rule compiles to — one per operation.\n *\n * The schema planner writes these into the database, and the Studio's RLS\n * editor compares the database against them; both call this, so \"what the code\n * declares\" has one meaning.\n *\n * The desugaring (`access` / `ownerField` / `roles` / structured condition /\n * raw SQL → `PolicyExpression`) is {@link securityRuleToConditions}, and the SQL\n * is {@link compilePolicyExpression}. What lives here is only the shape: which\n * operations a rule expands to, which clauses each operation takes, and the\n * deny-all fallback for a clause that compiled to nothing.\n */\nexport function compileTableRulePolicies(\n table: PolicyTable,\n rule: SecurityRule,\n options?: RulePolicyCompileOptions\n): CompiledRulePolicy[] {\n const ops = rule.operations && rule.operations.length > 0 ? rule.operations : [rule.operation ?? \"all\"];\n const tableName = table.table;\n if (isRedactedSecurityRule(rule)) {\n // The marker stands for SQL this process was not shown. A policy\n // compiled from it would grant or deny by a guess.\n throw new Error(\n `A rule on \"${tableName}\" is the \\`redacted: true\\` marker \\`GET /api/schema/tables\\` serves in place of ` +\n \"a rule whose SQL it withheld. It describes a policy; it cannot become one. Write the rule itself.\"\n );\n }\n assertShorthandColumns(table, rule);\n const policyNames = getPolicyNamesForRule(rule, tableName);\n const { usingExpr, withCheckExpr } = securityRuleToConditions(rule, { table: tableName });\n const mode = rule.mode ?? \"permissive\";\n // `rls.policyTarget: \"requestRole\"`: a grant is for the request roles only.\n // In the compiler, not on the rule, because a policy's name hashes the rule\n // — narrowing it there would rename every policy in every database. Never on\n // a restrictive policy: it can only take access away, from everyone.\n const shape = declaredRlsPolicyShape(table.database ?? DEFAULT_DATA_SOURCE_KEY);\n const narrowed = mode === \"permissive\" && shape.policyTarget === \"requestRole\";\n const forRequestRoles = (clause: string): string => narrowed ? `(${clause}) AND ${RLS_IS_REQUEST_ROLE_SQL}` : clause;\n // A grant only the server context or an admin can pass goes `TO\n // rebase_admin`, so it is not ORed into a signed-in user's plan, where it\n // costs the owner index (see `REBASE_ADMIN_ROLE`). In the compiler for the\n // reason above: the rule, and so the policy's name, stays as written. Never\n // for a rule naming its own `pgRoles`, and never for a restrictive policy —\n // narrowing whom a restriction applies to would widen everyone else.\n const adminOnly = mode === \"permissive\" && !rule.pgRoles && options?.adminRole === true\n && shape.adminPolicies === \"adminRole\";\n\n return ops.flatMap((operation, index): CompiledRulePolicy[] => {\n const needsUsing = operation !== \"insert\";\n const needsWithCheck = operation !== \"select\" && operation !== \"delete\";\n const forAdmins = adminOnly\n && (!needsUsing || requiresServerOrAdmin(usingExpr))\n && (!needsWithCheck || requiresServerOrAdmin(withCheckExpr));\n let using = needsUsing && usingExpr ? compilePolicyExpression(usingExpr, table, options) : null;\n let withCheck = needsWithCheck && withCheckExpr ? compilePolicyExpression(withCheckExpr, table, options) : null;\n // A clause that compiled to nothing denies rather than opens.\n if (!using && needsUsing) using = \"false\";\n if (!withCheck && needsWithCheck) withCheck = \"false\";\n const policy: CompiledRulePolicy = {\n name: policyNames[index],\n operation,\n mode,\n roles: rule.pgRoles ? [...rule.pgRoles].sort() : [forAdmins ? REBASE_ADMIN_ROLE : \"public\"],\n ...(forAdmins ? { adminTarget: true as const } : {}),\n using: using === null ? null : forRequestRoles(using),\n withCheck: withCheck === null ? null : forRequestRoles(withCheck)\n };\n // Only where every admin request passes the policy anyway — a request\n // runs as an admin request role only because its caller holds `admin`\n // — does the companion admit them outright, as a constant Postgres\n // folds away. `admin AND owner = me` is admin-only too, and gets none:\n // `true` would widen it. Not narrowed to the request roles: it already\n // applies to nothing else, and a non-constant clause would bring the\n // barrier back.\n const everyAdminPasses = forAdmins\n && (!needsUsing || admitsEveryAdminRequest(usingExpr))\n && (!needsWithCheck || admitsEveryAdminRequest(withCheckExpr));\n if (!everyAdminPasses || options?.adminRequestRole !== true) return [policy];\n return [policy, {\n name: adminRequestPolicyName(policyNames[index]),\n operation,\n mode: \"permissive\",\n roles: [REBASE_ADMIN_REQUEST_ROLE],\n adminRequestTarget: true,\n using: needsUsing ? \"true\" : null,\n withCheck: needsWithCheck ? \"true\" : null\n }];\n });\n}\n\n/**\n * Refuse a `PolicyShorthand` condition / check naming a key that is no column\n * of the table — no column key, and no `belongsTo` relation (which addresses\n * its foreign-key column). The compiler snake-cases a name it does not know,\n * so a typo would otherwise reach `CREATE POLICY` as a column that does not\n * exist, fail there, and leave the table with RLS on and no policy.\n */\nfunction assertShorthandColumns(table: PolicyTable, rule: SecurityRule): void {\n const clauses = [[\"condition\", rule.condition], [\"check\", rule.check]] as const;\n for (const [clause, condition] of clauses) {\n for (const column of policyShorthandColumns(condition)) {\n if (Object.prototype.hasOwnProperty.call(table.columns, column)) continue;\n if (Object.prototype.hasOwnProperty.call(table.links, column)) continue;\n const keys = [...Object.keys(table.columns), ...Object.keys(table.links)];\n throw new Error(\n `A rule on \"${table.table}\" names \"${column}\" in its \\`${clause}\\`, and \"${table.table}\" has no such ` +\n \"column. A shorthand's keys are column keys of the table: name one of \" +\n `${keys.map(k => `\"${k}\"`).join(\", \") || \"its columns\"}.`\n );\n }\n }\n}\n\n/**\n * Whether a clause is true for every request made by a caller holding the\n * `admin` role, whoever they are and whatever row: the companion test\n * (`adminRequestTarget`). Stricter than {@link requiresServerOrAdmin}, which\n * asks the opposite question: `admin AND owner = me` can only pass for an\n * admin, but not every admin passes it. Structural and conservative: anything\n * it cannot read answers `false`, and the policy gets no companion.\n */\nexport function admitsEveryAdminRequest(expr: PolicyExpression | null): boolean {\n if (!expr) return false;\n switch (expr.kind) {\n case \"rolesOverlap\":\n return expr.roles.includes(\"admin\");\n case \"rolesContain\":\n return expr.roles.length > 0 && expr.roles.every(role => role === \"admin\");\n case \"and\":\n return expr.operands.length > 0 && expr.operands.every(admitsEveryAdminRequest);\n case \"or\":\n return expr.operands.some(admitsEveryAdminRequest);\n default:\n return false;\n }\n}\n\n/**\n * Whether a clause can only be true for the server context or a caller holding\n * the `admin` role — so a policy made of such clauses loses nothing by applying\n * only to the roles those requests run as. Structural and conservative: raw\n * SQL, a role list naming anything but `admin`, or a clause that could pass for\n * someone else answers `false`, and the policy stays `TO public`.\n */\nexport function requiresServerOrAdmin(expr: PolicyExpression | null): boolean {\n if (!expr) return false;\n switch (expr.kind) {\n case \"serverContext\":\n return true;\n case \"rolesOverlap\":\n return expr.roles.length > 0 && expr.roles.every(role => role === \"admin\");\n case \"rolesContain\":\n return expr.roles.includes(\"admin\");\n case \"and\":\n return expr.operands.some(requiresServerOrAdmin);\n case \"or\":\n return expr.operands.length > 0 && expr.operands.every(requiresServerOrAdmin);\n default:\n return false;\n }\n}\n","import {\n isNumericColumnType,\n type ColumnType,\n type SecurityRule,\n type TableDescriptor,\n type TenantDescriptor\n} from \"@rebasepro/types\";\n\n/**\n * The Postgres type a text claim is cast to before it is compared with a\n * column. `\"text\"` is the no-cast case: a claim already is text, and a text\n * column compares with it directly and keeps using its index.\n *\n * @group Policies\n */\nexport type ClaimCastType = \"text\" | \"uuid\" | \"bigint\" | \"numeric\";\n\n/**\n * A column a rule can name: its SQL name, and the cast a claim compared with\n * it needs.\n *\n * @group Policies\n */\nexport interface PolicyColumn {\n /** The SQL column, unquoted. */\n column: string;\n /** What a text claim compared with the column is cast to. */\n claimCast: ClaimCastType;\n}\n\n/**\n * What the policy compiler reads of a table: the small view of a\n * `TableDescriptor` that rules compile against.\n *\n * A rule names a row by key (`ownerField: \"authorId\"`, `policy.field(\"org\")`);\n * the compiler needs that key's SQL column and the cast a claim compared with\n * it needs, the table's qualified name (for `outerField` inside an\n * `existsIn`), the rules and posture (for the injected baseline), and the\n * database the table lives in (whose declaration picks the policy shape).\n * Nothing else. Built from a descriptor by {@link policyTableFromDescriptor},\n * and for a junction by `junctionPolicyTable`.\n *\n * @group Policies\n */\nexport interface PolicyTable {\n /** The API slug: what `existsIn({ table })` and the junction rules name. */\n slug: string;\n /** The SQL table, unqualified. Policy names derive from it. */\n table: string;\n /**\n * The Postgres schema the table is declared in. Absent when it was not\n * stated (the table lives in `public`); an `existsIn` join into such a\n * table qualifies it with the outer table's schema.\n */\n schema?: string;\n /** The key of the database the table lives in, when not the default one. */\n database?: string;\n /** Every key a rule may name, by key: the table's columns. */\n columns: Readonly<Record<string, PolicyColumn>>;\n /**\n * The `belongsTo` relations, by relation name, each addressing its foreign\n * key column: `ownerField: \"org\"` compares `org_id`.\n */\n links: Readonly<Record<string, PolicyColumn>>;\n /** The key of the row id: the first primary-key column. */\n idKey: string;\n /** The declared rules, exactly as written (policy names hash them). */\n rules: readonly SecurityRule[];\n /**\n * `false` when the table switched the injected admin baseline off,\n * `true` when it switched it on regardless of its database's declaration,\n * absent when the database declaration (`rls.defaultPolicies`) decides.\n */\n defaultPolicies?: boolean;\n /** The auth table: gets the self-read rule and the admin write gate. */\n auth: boolean;\n /** Rows are scoped to a tenant. */\n tenant?: TenantDescriptor;\n}\n\n/**\n * Resolve a table by slug, for `existsIn` joins and relation targets.\n *\n * @group Policies\n */\nexport type ResolvePolicyTable = (slug: string) => PolicyTable | undefined;\n\n/**\n * What a claim compared with a column of `type` is cast to.\n *\n * `numeric` stays `numeric`; every other number type compares as `bigint`\n * (the guard caps the digits at 18). A uuid as `uuid`; everything else —\n * text, an enum, a date — as text, which is the safe direction: a redundant\n * text comparison costs nothing, while a missing cast is a `CREATE POLICY`\n * that fails and leaves the table with RLS on and no policy.\n *\n * @group Policies\n */\nexport function claimCastOf(type: ColumnType): ClaimCastType {\n if (type.kind === \"uuid\") return \"uuid\";\n if (type.kind === \"numeric\") return \"numeric\";\n if (isNumericColumnType(type)) return \"bigint\";\n return \"text\";\n}\n\n/**\n * The policy compiler's view of a compiled table.\n *\n * A `belongsTo` link addresses its foreign key column (`localKey`), cast as\n * that column is — its type is the target's key type, so no lookup through\n * the target is needed. The baseline follows the database's declaration unless\n * the table wrote `defaultPolicies` (`false` drops it, `true` keeps it). A view has no rules of its own\n * (`posture: \"view\"`), and gets none here.\n *\n * @group Policies\n */\nexport function policyTableFromDescriptor(descriptor: TableDescriptor): PolicyTable {\n const columns: Record<string, PolicyColumn> = {};\n for (const column of descriptor.columns) {\n columns[column.key] = { column: column.column, claimCast: claimCastOf(column.type) };\n }\n const links: Record<string, PolicyColumn> = {};\n for (const relation of descriptor.relations) {\n if (relation.kind !== \"belongsTo\") continue;\n links[relation.name] = {\n column: relation.localKey,\n claimCast: columns[relation.localField]?.claimCast ?? \"text\"\n };\n }\n return {\n slug: descriptor.slug,\n table: descriptor.table,\n // `public` is where an undeclared table lives; the compiler treats an\n // undeclared schema as \"the outer table's\" inside a join, so the\n // default is not spelled out.\n ...(descriptor.schema !== \"public\" ? { schema: descriptor.schema } : {}),\n ...(descriptor.database !== undefined ? { database: descriptor.database } : {}),\n columns,\n links,\n idKey: descriptor.primaryKey[0] ?? \"id\",\n rules: descriptor.rls.posture === \"rules\" ? descriptor.rls.rules : [],\n ...(descriptor.rls.posture === \"view\"\n ? { defaultPolicies: false }\n : !descriptor.rls.defaultPolicies ? { defaultPolicies: false }\n : descriptor.rls.declaredDefaultPolicies ? { defaultPolicies: true } : {}),\n auth: descriptor.auth !== undefined,\n ...(descriptor.tenant ? { tenant: descriptor.tenant } : {})\n };\n}\n\n/**\n * A resolver over compiled tables, by slug or SQL table name (an `existsIn`\n * may name either). Each table's view is built once.\n *\n * @group Policies\n */\nexport function policyTableResolver(descriptors: readonly TableDescriptor[]): ResolvePolicyTable {\n const cache = new Map<TableDescriptor, PolicyTable>();\n const view = (descriptor: TableDescriptor): PolicyTable => {\n let table = cache.get(descriptor);\n if (!table) {\n table = policyTableFromDescriptor(descriptor);\n cache.set(descriptor, table);\n }\n return table;\n };\n return (slug: string) => {\n const found = descriptors.find(d => d.slug === slug) ?? descriptors.find(d => d.table === slug);\n return found ? view(found) : undefined;\n };\n}\n","/**\n * The one reading of `collection.tenant`.\n *\n * Four things have to agree for a tenant-scoped collection to work — the\n * column, the RLS policy, the value stamped on insert and the index — and\n * before this they were four hand-written declarations that nothing compared.\n * The three that are schema become a {@link SecurityRule} and a column effect\n * derived here and in `planSchema`; the fourth, the write path, is\n * `resolveTenantWrite` (`runtime/tenant-write.ts`).\n *\n * Everything in this module is pure. The policy it builds is a `SecurityRule`\n * like any other, which is what makes `db push`, the doctor, boot-ensure, the\n * drift detector and the Studio treat the tenancy policy as what it is —\n * generated, named, and recognisable — rather than as somebody's hand-written\n * SQL that a push should offer to drop.\n */\nimport {\n DEFAULT_TENANT_BYPASS_ROLES,\n isTenantClaimSource,\n policy,\n type PolicyExpression,\n type SecurityRule,\n type TenantDescriptor\n} from \"@rebasepro/types\";\n\n/** The roles tenancy does not apply to, defaulted. */\nexport function tenantBypassRoles(tenant: Pick<TenantDescriptor, \"bypassRoles\">): readonly string[] {\n return tenant.bypassRoles ?? DEFAULT_TENANT_BYPASS_ROLES;\n}\n\n/**\n * The name of the policy a tenant declaration compiles to.\n *\n * Explicit — not a `getPolicyNameHash` of the rule — precisely because the\n * rule's *body* is compiled with more information in some callers than in\n * others (`planSchema` can resolve a relation's target collection and so knows\n * the column's type; the Studio, asking only for names, cannot). A hashed name\n * would then differ between the two, and the same policy would read as drift.\n * A frozen identifier: see `contracts/derived-names.txt`.\n */\nexport function tenantPolicyName(tableName: string): string {\n return `${tableName}_tenant_scope`;\n}\n\n/** The `reason` on the index a tenant column gets. Rendered into `schema.sql`. */\nexport const TENANT_INDEX_REASON = \"tenant scope\";\n\n/**\n * The condition a tenant declaration means, as a policy expression.\n *\n * `serverContext()` first, for the same reason every injected baseline rule\n * carries it: the trusted plane runs migrations, the auth flows and the boot,\n * and a restrictive policy that excluded it would not protect a tenant, it\n * would stop the server from starting.\n *\n * Then the bypass roles, then the tenancy test itself — a claim comparison or a\n * correlated `EXISTS` over the membership table, which are the two ways a\n * deployment answers \"which tenant is this caller in\".\n */\nexport function tenantScopeExpression(tenant: TenantDescriptor): PolicyExpression {\n const match: PolicyExpression = isTenantClaimSource(tenant.from)\n ? policy.compare(policy.field(tenant.field), \"eq\", policy.authClaim(tenant.from.claim))\n : policy.existsIn({\n table: tenant.from.membership.table,\n where: policy.and(\n policy.compare(\n policy.field(tenant.from.membership.tenantField),\n \"eq\",\n policy.outerField(tenant.field)\n ),\n policy.compare(\n policy.field(tenant.from.membership.userField),\n \"eq\",\n policy.authUid()\n )\n )\n });\n\n const bypass = tenantBypassRoles(tenant);\n return bypass.length > 0\n ? policy.or(policy.serverContext(), policy.rolesOverlap(bypass), match)\n : policy.or(policy.serverContext(), match);\n}\n\n/**\n * The rule a tenant declaration compiles to, or nothing when there is none.\n *\n * **Restrictive**, and that is the whole design. A restrictive policy is ANDed\n * with every other policy on the table, so tenancy narrows what the\n * collection's own `securityRules` allow and can never widen it. A permissive\n * one would OR with them, and a single `access: \"public\"` rule elsewhere in the\n * file would take the entire tenancy boundary off without contradicting\n * anything a reader could see.\n *\n * One rule with `operation: \"all\"` rather than four with `operations: [...]`:\n * `FOR ALL` gives Postgres the USING clause for SELECT/UPDATE/DELETE and the\n * WITH CHECK clause for INSERT/UPDATE, which is exactly the coverage wanted,\n * as one policy with one name instead of four.\n */\nexport function tenantSecurityRule(tableName: string, tenant: TenantDescriptor): SecurityRule {\n const expression = tenantScopeExpression(tenant);\n return {\n name: tenantPolicyName(tableName),\n mode: \"restrictive\",\n operation: \"all\",\n condition: expression,\n check: expression\n };\n}\n","import { SecurityRule, SecurityOperation, PolicyExpression, policy, declaredRlsPolicyShape, DEFAULT_DATA_SOURCE_KEY } from \"@rebasepro/types\";\nimport { tenantSecurityRule } from \"./tenant\";\nimport { getPolicyNamesForRules } from \"@rebasepro/utils\";\nimport type { PolicyTable } from \"./policy/policy-table\";\n\n/**\n * Default RLS policies injected by the schema generator.\n *\n * Rebase's enforcement model is unified: authenticated (user-context) requests\n * run under the restricted `rebase_user` role, so Postgres RLS binds *every*\n * statement — reads and writes. A collection's `securityRules` are the whole\n * authorization model. The server context (auth flows, migrations, raw\n * `rebase.sql`) runs as the owner and bypasses RLS.\n *\n * `rebase.dataAsAdmin` is **not** in that set, despite the name: it is scoped as\n * `{ uid: \"service\", roles: [\"admin\"] }`, so it runs as `rebase_user` like any\n * other caller and clears the baseline below through the *admin* arm, not the\n * server arm. Which is why `disableDefaultPolicies` plus a lone\n * `policy.serverContext()` rule locks it out too.\n *\n * Because RLS default-denies, every collection is **locked by default**: with\n * no rules, only the server context and admins can touch it. The generator\n * injects that safe baseline:\n *\n * **For every collection**\n * 1. A permissive **server-or-admin SELECT** grant.\n * 2. A permissive **server-or-admin write** grant (insert/update/delete).\n *\n * Author `securityRules` are permissive and OR together, so explicit rules only\n * *broaden* access from this locked baseline (e.g. \"users read/write their own\n * rows\").\n *\n * **For auth collections additionally**\n * 3. A permissive **self SELECT** grant (`id = rebase.uid()`), so users can read\n * their own row (profile, session bootstrap) without every app re-declaring\n * it.\n * 4. A **restrictive** admin write gate. Restrictive policies are AND'd with\n * every other policy, so a write is rejected unless the caller is an admin\n * (or the server context) — even if the author also wrote a permissive rule\n * such as \"a user may edit their own row\". Without this, a permissive owner\n * rule would let a user change their own `roles`.\n *\n * The server context is recognised as `rebase.uid() IS NULL` (`policy.serverContext()`)\n * — the built-in flows that run without a user (signup, migrations) set no user\n * GUC — which also lets the owner connection satisfy these policies even under\n * FORCE RLS. A *user* request never reaches that state: an anonymous one carries\n * `ANONYMOUS_USER_ID`, precisely so it cannot pass for the server here.\n *\n * **For a collection declaring `tenant`, additionally**\n * 5. A **restrictive** tenancy gate for every operation. Same kind of thing as\n * the admin write gate and injected for the same reason: it is ANDed with\n * every other policy, so it narrows what the author's permissive rules\n * grant and can never widen them. See `./tenant.ts`.\n *\n * Opt out with `disableDefaultPolicies: true` to take full responsibility for\n * the collection's RLS. The *restrictive* rules are not part of that opt-out:\n * dropping a rule that can only remove access could express nothing but \"let\n * more people in\", which is what the flag already does by removing the grants.\n */\n// Expressed structurally (not as raw SQL) so the admin UI can evaluate it\n// exactly — the framework's most security-critical policies must be reflected\n// precisely, not left as un-evaluable raw clauses. Compiles to\n// `rebase.uid() IS NULL OR (string_to_array(rebase.roles(), ',') && ARRAY['admin'])`.\n//\n// `serverContext()`, emphatically not `not(authenticated())`: the server arm of\n// this grant must match the server context and nothing else. Anonymous visitors\n// are not signed in either, so a negated `authenticated()` would hand them the\n// server-or-admin grant on every collection's default policy.\nconst SERVER_OR_ADMIN_EXPR: PolicyExpression = policy.or(\n policy.serverContext(),\n policy.rolesOverlap([\"admin\"])\n);\n\n/** Write operations that must be admin-gated by default on auth collections. */\nconst DEFAULT_GUARDED_OPS: SecurityOperation[] = [\"insert\", \"update\", \"delete\"];\n\n/**\n * Returns the security rules that should be applied to a collection: the\n * author's explicit `securityRules` plus the framework defaults described in\n * the module doc (baseline server/admin read for all collections; self-read\n * and the admin write gate for auth collections).\n *\n * Collections that opt out via `disableDefaultPolicies` are returned unchanged.\n */\n/**\n * The restrictive write gate for an auth collection.\n *\n * Restrictive, so it is ANDed with everything else: whatever an author's\n * permissive rules allow, a write to this table still has to satisfy this too.\n * It is the only thing standing between \"users may edit their own row\" and\n * \"users may grant themselves any role\".\n */\nfunction adminWriteGate(tableName: string): SecurityRule {\n return {\n name: `${tableName}_require_admin_write`,\n mode: \"restrictive\",\n operations: [...DEFAULT_GUARDED_OPS],\n condition: SERVER_OR_ADMIN_EXPR,\n check: SERVER_OR_ADMIN_EXPR\n };\n}\n\n/**\n * The restrictive tenancy policy, as a list of zero or one.\n *\n * A list so the two call sites can splice it in without a conditional, and a\n * separate function so it is obvious that it is injected on *both* paths —\n * including the `disableDefaultPolicies` one, where it is the only permissive-\n * looking thing that stays. See `./tenant.ts`.\n */\nfunction tenantRule(table: PolicyTable): SecurityRule[] {\n return table.tenant ? [tenantSecurityRule(table.table, table.tenant)] : [];\n}\n\n/**\n * Whether a table goes without the injected baseline: its own\n * `defaultPolicies` when it says, otherwise its database's\n * `rls.defaultPolicies` (`database({ rls: { defaultPolicies: false } })`).\n *\n * @group Policies\n */\nexport function tableDefaultPoliciesDisabled(table: PolicyTable): boolean {\n if (table.defaultPolicies !== undefined) return !table.defaultPolicies;\n return !declaredRlsPolicyShape(table.database ?? DEFAULT_DATA_SOURCE_KEY).defaultPolicies;\n}\n\nexport function tableEffectiveRules(table: PolicyTable): SecurityRule[] {\n const explicit = [...table.rules];\n\n const tableName = table.table;\n const injected: SecurityRule[] = [];\n\n if (tableDefaultPoliciesDisabled(table)) {\n // The opt-out drops the *permissive* defaults — the ones that grant.\n // The restrictive admin-write gate on an auth collection is not among\n // them, because it is different in kind: a restrictive policy is ANDed\n // with every other policy and can only ever remove access, so opting\n // out of it cannot express anything except \"let more people write\".\n //\n // Dropping it did exactly that. `{ disableDefaultPolicies: true,\n // securityRules: [{ operation: \"all\", ownerField: \"id\" }] }` — an\n // ordinary \"users may edit their own row\" configuration — let any\n // signed-in user set their own `roles` to `[\"admin\"]`, with no warning\n // from any boot guard, doctor check or validator.\n //\n // An author who needs a different gate can add their own restrictive\n // rule; they cannot end up with none by accident.\n // Tenancy survives the opt-out for exactly the reason the write gate\n // does: it is restrictive, so it can only ever remove access. Dropping\n // it could express nothing except \"let every tenant read every other\n // tenant's rows\", which is not a thing `disableDefaultPolicies` is for\n // — that flag is about taking over the *grants*.\n return [...explicit, ...tenantRule(table), ...(table.auth\n ? [adminWriteGate(tableName)]\n : [])];\n }\n\n // Baseline read + write: the server context and admins can always operate.\n // RLS default-denies under the user role, so without these a rule-less\n // collection would be locked to everyone — including the admin studio.\n // Author rules are permissive and broaden access from here.\n injected.push({\n name: `${tableName}_default_admin_read`,\n operations: [\"select\"],\n condition: SERVER_OR_ADMIN_EXPR\n });\n injected.push({\n name: `${tableName}_default_admin_write`,\n operations: [...DEFAULT_GUARDED_OPS],\n condition: SERVER_OR_ADMIN_EXPR,\n check: SERVER_OR_ADMIN_EXPR\n });\n\n if (table.auth) {\n // Self-read: a user can always read their own row.\n injected.push({\n name: `${tableName}_default_self_read`,\n operations: [\"select\"],\n condition: policy.compare(policy.field(table.idKey), \"eq\", policy.authUid())\n });\n\n // Restrictive gate: AND'd with all other policies, so no permissive rule\n // (e.g. an owner \"edit your own row\" rule) can let a non-admin change\n // privileged columns like `roles`. Survives `disableDefaultPolicies` —\n // see the note above the opt-out.\n injected.push(adminWriteGate(tableName));\n }\n\n // Last, so it reads as what it is: a restriction ANDed over everything\n // above it, author rules included.\n injected.push(...tenantRule(table));\n\n return [...explicit, ...injected];\n}\n\n/**\n * The framework defaults that {@link tableEffectiveRules} would add to a\n * collection, without the author's own rules.\n *\n * These policies appear in the database under names the author never wrote, and\n * a permissive policy ORs with every other permissive policy — so someone\n * reading their `securityRules` and then the real ACL sees more access than they\n * declared. Dropping them by hand does nothing either: `db push` is declarative,\n * so the next push asserts them again. Callers use this to say, in the generated\n * DDL, which policies are injected and how to take them off.\n */\nexport function tableInjectedRules(table: PolicyTable): SecurityRule[] {\n if (tableDefaultPoliciesDisabled(table)) {\n // Not empty for an auth collection, nor for a tenant-scoped one: both\n // restrictive rules are still injected, and the generated DDL has to\n // say so — a policy in the database that the author never wrote and\n // cannot find in this list is exactly the surprise this function exists\n // to prevent.\n return [...tenantRule(table), ...(table.auth\n ? [adminWriteGate(table.table)]\n : [])];\n }\n\n // tableEffectiveRules appends the defaults after the author's rules, so\n // everything past the author's count is injected.\n return tableEffectiveRules(table).slice(table.rules.length);\n}\n\n/**\n * Every policy name `rebase db push` would write for a collection.\n *\n * This is the answer to \"did the codebase produce this live policy?\", and it is\n * more than `securityRules.map(r => r.name)` for two reasons:\n *\n * - a rule without an explicit `name` compiles to `<table>_<op>_<hash>`, one\n * per operation, so comparing `rule.name` to `policyname` never matches it;\n * - the generator also injects the safe-by-default baseline\n * (`<table>_default_admin_*`), which is in no collection's `securityRules`.\n *\n * Every UI that flags drift has to get both right, and each one that derived it\n * by hand got a different subset — which is how four policies *Rebase itself\n * wrote* came to be badged as hand-written drift on every table in a project,\n * with a button offering to import them back into the codebase that produced\n * them. There is one derivation now, and this is it.\n */\nexport function tableGeneratedPolicyNames(table: PolicyTable): Set<string> {\n return getPolicyNamesForRules(tableEffectiveRules(table), table.table);\n}\n\n","import {\n JUNCTION_PIVOT_KEY,\n PolicyExpression,\n PolicyOperand,\n SecurityRule,\n policy\n} from \"@rebasepro/types\";\nimport type { ColumnDescriptor, RelationDescriptor, TableDescriptor } from \"@rebasepro/types\";\nimport { getPolicyOperations } from \"@rebasepro/utils\";\nimport { securityRuleToConditions } from \"./policy/securityRuleToConditions\";\nimport { tableDefaultPoliciesDisabled } from \"./auth-default-policies\";\nimport { claimCastOf, policyTableFromDescriptor, type PolicyColumn, type PolicyTable } from \"./policy/policy-table\";\n\n/**\n * RLS derivation for many-to-many junction tables.\n *\n * A `through` relation makes the generator create a table nobody declared as a\n * collection — `posts_tags`, `user_roles`. Those tables used to be the one kind\n * of generated table with **no** RLS at all: `rebase_user` holds full DML grants,\n * so with the endpoints locked down, any signed-up user could still read or wipe\n * every edge between them. There is also nowhere in the config to write rules\n * for a junction, so the author could not even fix it by hand.\n *\n * The architecture here is that a junction's security is *derived*, never\n * hand-written:\n *\n * 1. **Locked baseline.** The same server-or-admin `default_admin` grants every\n * collection gets, so the invariant holds again: every table the generator\n * creates is default-deny, and rules only broaden.\n *\n * 2. **Reads follow the endpoints.** An edge is visible iff *both* endpoint\n * rows are visible — two correlated `EXISTS` subqueries. The subqueries run\n * under the caller's role, so each endpoint's own RLS filters them: junction\n * visibility delegates to the endpoints' policies, whatever they become,\n * with nothing duplicated. A public blog keeps rendering its tags; a private\n * CRM's edges are exactly as hidden as its rows.\n *\n * 3. **Writes follow the owning side's update rules.** Linking or unlinking an\n * edge *is* an edit of the owning row — tagging a post is editing the post —\n * so edge writes inherit the declaring collection's explicit permissive\n * `update` rules, each wrapped in an `EXISTS` against the owning row. Where\n * a rule cannot be embedded faithfully (see below) it is dropped, so the\n * failure mode is always *too locked*, never open. Explicit **restrictive**\n * update rules are inherited as restrictive junction rules; if one of them\n * cannot be embedded, the whole derived write grant for that side is\n * suppressed — granting without the author's gate would be looser than the\n * parent itself.\n *\n * **Embeddability.** A parent rule is embedded by moving its condition inside\n * `EXISTS (SELECT 1 FROM parent WHERE parent.pk = junction.fk AND <condition>)`.\n * In that scope, `field` operands bind to the parent — which is what the author\n * meant. But `outerField` operands and `{column}` placeholders in `raw` SQL bind\n * to the RLS row, which is now the junction, not the parent the author wrote\n * them against. So: `raw` anywhere disqualifies a rule; a top-level `outerField`\n * (equivalent to `field` outside a subquery) is rewritten to `field`; an\n * `outerField` inside a nested `existsIn` cannot be re-scoped and disqualifies\n * the rule.\n *\n * Injected parent defaults are never inherited — the junction's own baseline\n * already covers the server/admin plane, and an auth collection's restrictive\n * `require_admin_write` gate exists to protect privileged parent *columns*,\n * which an edge write cannot touch. Inheriting it would stop users managing\n * e.g. their own interests through a `users_interests` junction for no gain.\n *\n * Everything flows through the shared naming machinery, so the Studio\n * recognises these policies as generated instead of offering to \"import\" them.\n */\n\n// Mirrors auth-default-policies: the server context or an admin.\nconst SERVER_OR_ADMIN_EXPR: PolicyExpression = policy.or(\n policy.serverContext(),\n policy.rolesOverlap([\"admin\"])\n);\n\n/** `EXISTS (SELECT 1 FROM endpoint WHERE endpoint.pk = junction.fk [AND extra])`. */\nfunction existsEndpoint(endpoint: PolicyJunctionEndpoint, extra?: PolicyExpression): PolicyExpression {\n const correlation = policy.compare(\n policy.field(endpoint.table.idKey),\n \"eq\",\n policy.outerField(endpoint.junctionColumn)\n );\n return policy.existsIn({\n table: endpoint.table.slug,\n where: extra ? policy.and(correlation, extra) : correlation\n });\n}\n\n/**\n * Whether a parent-rule expression keeps its meaning when moved inside the\n * junction's `EXISTS` subquery — and the re-scoped copy if it does.\n *\n * Returns `null` when the rule cannot be embedded faithfully: `raw` SQL\n * anywhere (its `{column}` placeholders would bind to the junction), or an\n * `outerField` inside a nested `existsIn` (it would bind to the junction while\n * the author meant the parent, and no operand can express \"the middle scope\").\n * Top-level `outerField`s are rewritten to `field`, which is what they meant.\n */\nexport function embedParentExpression(expr: PolicyExpression, depth = 0): PolicyExpression | null {\n switch (expr.kind) {\n case \"raw\":\n return null;\n case \"and\":\n case \"or\": {\n const parts: PolicyExpression[] = [];\n for (const child of expr.operands) {\n const embedded = embedParentExpression(child, depth);\n if (!embedded) return null;\n parts.push(embedded);\n }\n return expr.kind === \"and\" ? policy.and(...parts) : policy.or(...parts);\n }\n case \"not\": {\n const embedded = embedParentExpression(expr.operand, depth);\n return embedded ? policy.not(embedded) : null;\n }\n case \"existsIn\": {\n const where = embedParentExpression(expr.where, depth + 1);\n return where ? policy.existsIn({ table: expr.table, where }) : null;\n }\n case \"compare\": {\n const left = embedOperand(expr.left, depth);\n const right = embedOperand(expr.right, depth);\n if (!left || !right) return null;\n return { ...expr, left, right };\n }\n default:\n // Leaf expressions with no field references (true, false,\n // serverContext, authenticated, rolesOverlap, rolesContain) are\n // position-independent.\n return expr;\n }\n}\n\n/** Re-scope an operand, or return `null` if its binding cannot be preserved. */\nfunction embedOperand(operand: PolicyOperand, depth: number): PolicyOperand | null {\n if (operand.kind === \"outerField\") {\n // Outside a subquery, outerField ≡ field: the author meant their own\n // row, which after embedding is the EXISTS's joined table → field.\n if (depth === 0) return policy.field(operand.name);\n // Inside the author's own existsIn it meant the parent row; after\n // embedding it would bind to the junction. Not expressible.\n return null;\n }\n return operand;\n}\n\n/** Does the rule cover the `update` operation? */\nfunction coversUpdate(rule: SecurityRule): boolean {\n return getPolicyOperations(rule).some(op => op === \"update\" || op === \"all\");\n}\n\n/**\n * One end of a junction, as the policy compiler reads it: the table, and the\n * junction column holding its key.\n *\n * @group Policies\n */\nexport interface PolicyJunctionEndpoint {\n table: PolicyTable;\n /** Junction column holding this endpoint's key. */\n junctionColumn: string;\n}\n\n/**\n * A junction table, as its derived rules are built from: its two endpoints\n * and every table declaring a relation through it (whose update rules the\n * edge writes inherit).\n *\n * @group Policies\n */\nexport interface PolicyJunction {\n /** Bare table name. */\n table: string;\n schema: string;\n /** The two endpoints, in [source, target] order of the first declaring relation. */\n endpoints: [PolicyJunctionEndpoint, PolicyJunctionEndpoint];\n /** Every table that declares a relation through this junction. */\n declaringSides: PolicyJunctionEndpoint[];\n}\n\n/**\n * The full derived policy set for a junction table: the locked server/admin\n * baseline, the endpoint-visibility read grant, inherited write grants, and\n * inherited restrictive gates. Returns `[]` when every declaring collection set\n * `disableDefaultPolicies` — the junction is then the author's to police, and\n * stays locked (RLS is still enabled) until they write policies for it.\n */\nexport function junctionRules(spec: PolicyJunction): SecurityRule[] {\n if (spec.declaringSides.every(side => tableDefaultPoliciesDisabled(side.table))) {\n return [];\n }\n\n const rules: SecurityRule[] = [];\n\n // 1. Locked baseline — same shape and naming as every collection's.\n rules.push({\n name: `${spec.table}_default_admin_read`,\n operations: [\"select\"],\n condition: SERVER_OR_ADMIN_EXPR\n });\n rules.push({\n name: `${spec.table}_default_admin_write`,\n operations: [\"insert\", \"update\", \"delete\"],\n condition: SERVER_OR_ADMIN_EXPR,\n check: SERVER_OR_ADMIN_EXPR\n });\n\n // 2. Reads follow the endpoints: the edge is visible iff both rows are.\n // The EXISTS subqueries run under the caller's role, so each endpoint's\n // own RLS applies inside them — visibility is delegated, not copied.\n rules.push({\n name: `${spec.table}_default_edge_read`,\n operations: [\"select\"],\n condition: policy.and(\n existsEndpoint(spec.endpoints[0]),\n existsEndpoint(spec.endpoints[1])\n )\n });\n\n // 3. Writes follow the owning side's explicit update rules.\n const writeGrants: PolicyExpression[] = [];\n for (const side of spec.declaringSides) {\n const updateRules = side.table.rules.filter(coversUpdate);\n\n const permissive = updateRules.filter(r => r.mode !== \"restrictive\");\n const restrictive = updateRules.filter(r => r.mode === \"restrictive\");\n\n // Embed the restrictive gates first: if any of them cannot be carried\n // over, granting writes from this side would be looser than the parent\n // itself allows — so the whole side's grant is suppressed.\n const embeddedGates: PolicyExpression[] = [];\n let gatesEmbeddable = true;\n for (const gate of restrictive) {\n const using = securityRuleToConditions(gate).usingExpr;\n const embedded = using ? embedParentExpression(using) : null;\n if (!embedded) {\n gatesEmbeddable = false;\n break;\n }\n embeddedGates.push(embedded);\n }\n if (!gatesEmbeddable) continue;\n\n const grants: PolicyExpression[] = [];\n for (const rule of permissive) {\n const using = securityRuleToConditions(rule).usingExpr;\n const embedded = using ? embedParentExpression(using) : null;\n if (embedded) grants.push(embedded);\n }\n if (grants.length === 0) continue;\n\n // \"May update the owning row\": any permissive grant, AND every gate.\n const condition = embeddedGates.length > 0\n ? policy.and(policy.or(...grants), ...embeddedGates)\n : policy.or(...grants);\n\n writeGrants.push(existsEndpoint(side, condition));\n }\n\n if (writeGrants.length > 0) {\n rules.push({\n name: `${spec.table}_default_edge_write`,\n operations: [\"insert\", \"update\", \"delete\"],\n condition: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants),\n check: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants)\n });\n }\n\n return rules;\n}\n\n// ── Junctions of compiled tables ─────────────────────────────────────────────\n\n/** The `manyToMany` arm of {@link RelationDescriptor}. */\nexport type ManyToManyDescriptor = Extract<RelationDescriptor, { kind: \"manyToMany\" }>;\n\n/**\n * One end of a junction of compiled tables.\n *\n * @group Policies\n */\nexport interface TableJunctionEndpoint {\n descriptor: TableDescriptor;\n /** Junction column holding this endpoint's key. */\n junctionColumn: string;\n}\n\n/**\n * A table that declares a `manyToMany` through the junction.\n *\n * @group Policies\n */\nexport interface TableJunctionSide extends TableJunctionEndpoint {\n relation: ManyToManyDescriptor;\n}\n\n/**\n * A junction table, resolved from the `manyToMany` relations of compiled\n * tables: what the schema planner creates and the policy compiler derives the\n * junction's rules for.\n *\n * @group Policies\n */\nexport interface TableJunction {\n /** Bare table name. */\n table: string;\n /** Always `public`: the planner creates every junction there. */\n schema: string;\n /** The two endpoints, in [source, target] order of the first declaring relation. */\n endpoints: [TableJunctionSide, TableJunctionEndpoint];\n /** Every table that declares a relation through this junction, in input order. */\n declaringSides: TableJunctionSide[];\n /**\n * The junction's own columns beyond the two keys (`pivot`), merged across\n * every declaring side. Empty when there are none.\n */\n pivot: ColumnDescriptor[];\n}\n\n/**\n * Walk every table's `manyToMany` relations and aggregate the junction tables\n * they declare, keyed by junction table. Two tables may declare one junction\n * from opposite sides (`posts.tags` and `tags.posts` through `posts_tags`);\n * both become `declaringSides`, so the derived write grants consider both.\n * A relation whose target is not among `descriptors` is skipped.\n *\n * Pass every descriptor, views included. A view declares no junction (it has\n * no table to own one, and the planner plans none for it), so its\n * `manyToMany` relations are skipped; but a view is a valid *target* — the\n * junction keys into it without a foreign key — so it must be here for the\n * table that links to it to resolve its junction. Filtering views out before\n * the call loses every junction into a view.\n *\n * Input order decides the endpoints' order and the sides' — sort by slug at\n * the boundary, as the planner does.\n *\n * @group Policies\n */\nexport function resolveTableJunctions(descriptors: readonly TableDescriptor[]): Map<string, TableJunction> {\n const bySlug = new Map(descriptors.map(descriptor => [descriptor.slug, descriptor]));\n const junctions = new Map<string, TableJunction>();\n for (const descriptor of descriptors) {\n if (descriptor.kind === \"view\") continue;\n for (const relation of descriptor.relations) {\n if (relation.kind !== \"manyToMany\") continue;\n const target = bySlug.get(relation.target);\n if (!target) continue;\n const raw = relation.through.table;\n // The CREATE TABLE path strips a schema prefix from the name and\n // creates in `public`; the policies target the same table.\n const table = raw.includes(\".\") ? raw.split(\".\").pop() ?? raw : raw;\n const side: TableJunctionSide = { descriptor, junctionColumn: relation.through.sourceKey, relation };\n const existing = junctions.get(table);\n if (!existing) {\n junctions.set(table, {\n table,\n schema: \"public\",\n endpoints: [side, { descriptor: target, junctionColumn: relation.through.targetKey }],\n declaringSides: [side],\n pivot: mergePivot([], relation.through.pivot, table, descriptor)\n });\n continue;\n }\n // Merged whether or not this side is new: one table can reach a\n // junction under two relation names, and every column each asks\n // for has to exist.\n existing.pivot = mergePivot(existing.pivot, relation.through.pivot, table, descriptor);\n if (!existing.declaringSides.some(s => s.descriptor === descriptor)) existing.declaringSides.push(side);\n }\n }\n return junctions;\n}\n\n/**\n * Fold one side's `pivot` into the junction's, refusing a disagreement: one\n * table is created, so two descriptions of a column that are not the same\n * description have no correct answer.\n */\nfunction mergePivot(\n into: ColumnDescriptor[],\n incoming: readonly ColumnDescriptor[],\n table: string,\n descriptor: TableDescriptor\n): ColumnDescriptor[] {\n if (incoming.length === 0) return into;\n const merged = [...into];\n for (const column of incoming) {\n const already = merged.find(existing => existing.key === column.key);\n if (!already) {\n merged.push(column);\n continue;\n }\n if (JSON.stringify(already) !== JSON.stringify(column)) {\n throw new Error(\n `The junction table \"${table}\" is declared from more than one side, and they disagree ` +\n `about the pivot column \"${column.key}\": \"${descriptor.slug}\" describes it differently than ` +\n \"another declaring table does. One table is created, so both `pivot` lists have to describe \" +\n \"the same column — or only one side should declare it.\"\n );\n }\n }\n return merged;\n}\n\n/**\n * The policy compiler's view of a junction table: its two key columns (by\n * column name, as the junction rules name them) and its pivot columns.\n *\n * @group Policies\n */\nexport function junctionPolicyTable(junction: TableJunction): PolicyTable {\n const columns: Record<string, PolicyColumn> = {};\n for (const endpoint of junction.endpoints) {\n columns[endpoint.junctionColumn] = { column: endpoint.junctionColumn, claimCast: \"text\" };\n }\n // After the keys, so a pivot column colliding with a key column cannot\n // replace it.\n for (const column of junction.pivot) {\n if (column.key === JUNCTION_PIVOT_KEY || column.key in columns) continue;\n columns[column.key] = { column: column.column, claimCast: claimCastOf(column.type) };\n }\n return {\n slug: junction.table,\n table: junction.table,\n schema: junction.schema,\n columns,\n links: {},\n idKey: \"id\",\n rules: [],\n auth: false\n };\n}\n\n/**\n * The derived rules of a junction of compiled tables ({@link junctionRules}).\n *\n * @group Policies\n */\nexport function tableJunctionRules(junction: TableJunction): SecurityRule[] {\n const endpoint = (end: TableJunctionEndpoint): PolicyJunctionEndpoint => ({\n table: policyTableFromDescriptor(end.descriptor),\n junctionColumn: end.junctionColumn\n });\n return junctionRules({\n table: junction.table,\n schema: junction.schema,\n endpoints: [endpoint(junction.endpoints[0]), endpoint(junction.endpoints[1])],\n declaringSides: junction.declaringSides.map(endpoint)\n });\n}\n","import { createHash } from \"node:crypto\";\nimport {\n isRedactedSecurityRule,\n scopeGrants,\n scopeGrantsAny,\n scopeTargets,\n type ColumnDescriptor,\n type JunctionPolicyDescriptor,\n type PolicyDescriptor,\n type RedactedSecurityRule,\n type RelationDescriptor,\n type RlsDescriptor,\n type SecurityOperation,\n type SecurityRule,\n type TableDescriptor\n} from \"@rebasepro/types\";\nimport {\n canReadRelation,\n canReadWithAccess,\n compileTableRulePolicies,\n junctionPolicyTable,\n policyTableFromDescriptor,\n policyTableResolver,\n resolveTableJunctions,\n tableEffectiveRules,\n tableInjectedRules,\n tableJunctionRules,\n type CompiledRulePolicy,\n type FieldViewer,\n type PolicyTable,\n type RelatedTables\n} from \"@rebasepro/common\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * The one serializer of a backend's tables for a caller.\n *\n * `GET /api/schema/tables` serves it over HTTP, `/api/meta/contract` serves\n * its admin-level view, and the MCP surface builds its views from it — three\n * consumers, one definition of what each caller may learn about the schema.\n *\n * Fail closed, per caller:\n *\n * | Field | Who sees it |\n * |---|---|\n * | a `private` column or relation | nobody, administrators included |\n * | a column or relation the caller fails `access.read` for | dropped (`access` itself is kept on what remains) |\n * | a `belongsTo` and its foreign-key column | one fact under two names: each is described only when both pass — a link whose key column the caller cannot read is dropped, and so is a key column whose link is |\n * | a relation whose target table the caller is not served | dropped |\n * | a table | administrators and `schema:read` holders: every one; any other person (`schemaTables.persons: \"granted\"`, the default): those some rule could grant their roles something on (see {@link tableReachable}), every one with `persons: \"all\"`; a credential (API key, token): the tables its `data:*` scopes name, or all with `schema:read`; an anonymous caller (public opt-in): those with a public `select` rule |\n * | structured `rls.rules` | everyone served the table; a non-privileged person under `\"granted\"` only the rules that can apply to their roles (see {@link ruleAppliesTo}), the rest dropped |\n * | raw SQL in a rule (`using`, `withCheck`, a `policy.raw` node) | administrators and `schema:read` holders; everyone else gets a {@link RedactedSecurityRule} |\n * | `rls.policies`, `rls.junctions` (compiled policies) | administrators and `schema:read` holders |\n * | `view.query`, `indexes` | administrators and `schema:read` holders |\n * | `auth.roles`, `auth.scopes` (labels) | administrators, `schema:read` and `users:read` holders |\n * | `hooks`, column `transforms`, `auth.hooks` | everyone served the table but a non-privileged person under `\"granted\"` and an anonymous caller (presence flags; code never leaves the server, and the panel reads none of them) |\n * | `metadata`, `softDelete`, `tenant`, `history`, `search` | everyone served the table: the panel renders and gates from them (`metadata` is public to the callers served the table by definition) |\n *\n * @module\n */\n\n/**\n * Who is asking.\n *\n * - `anonymous` — nobody signed in; served only when the backend opts in\n * (`schemaTables: { public: true }`).\n * - `person` — a signed-in user, or the service key: holds what their roles\n * hold. With `schema:read` (administrators) every table; otherwise the\n * tables some rule could grant their roles something on, or every table\n * when the backend says `schemaTables: { persons: \"all\" }`.\n * - `credential` — an API key, an MCP or platform token: holds exactly the\n * scopes it was granted, and sees only the tables they name.\n *\n * @group Schema\n */\nexport interface SchemaCaller {\n kind: \"anonymous\" | \"person\" | \"credential\";\n /** The application roles columns' `access.read` is judged against. */\n roles: readonly string[];\n /** Every scope the caller holds (for a person: what their roles hold). */\n scopes: readonly string[];\n}\n\n/**\n * What a caller is served: the redaction {@link serializeTables} applies.\n * Two callers with the same view receive the same body.\n *\n * @group Schema\n */\nexport interface SchemaView {\n /** Raw SQL, compiled policies, view queries and indexes. */\n privileged: boolean;\n /** The auth table's role and scope labels. */\n accountLabels: boolean;\n /** The roles columns and relations are judged against. */\n viewer: FieldViewer;\n /**\n * Which tables. `granted`: those some rule could grant the viewer's roles\n * something on ({@link tableReachable}), with only the rules that can\n * apply to them ({@link ruleAppliesTo}).\n */\n tables: { kind: \"all\" } | { kind: \"only\"; slugs: readonly string[] } | { kind: \"public\" } | { kind: \"granted\" };\n}\n\n/**\n * What a signed-in person without `schema:read` is described:\n *\n * - `\"granted\"` (the default) — the tables some rule could grant their roles\n * something on, each with only the rules that can apply to them;\n * - `\"all\"` — every table, with every rule (raw SQL still redacted): what\n * every signed-in caller was served before this option existed.\n *\n * @group Schema\n */\nexport type SchemaTablesPersons = \"granted\" | \"all\";\n\n/**\n * Options of {@link schemaViewFor}.\n *\n * @group Schema\n */\nexport interface SchemaViewOptions {\n /** `schemaTables.persons` — see {@link SchemaTablesPersons}. Default `\"granted\"`. */\n persons?: SchemaTablesPersons;\n}\n\n/**\n * Why a caller is served nothing.\n *\n * @group Schema\n */\nexport type SchemaRefusal = { refused: \"scope\"; message: string };\n\nconst DATA_SCOPES = [\"data:read\", \"data:write\", \"data:delete\"] as const;\n\n/**\n * The view a caller is served, or why it is refused.\n *\n * A credential needs `schema:read` or a `data:*` scope: a key minted for\n * storage or functions alone has no business reading the schema.\n *\n * @group Schema\n */\nexport function schemaViewFor(caller: SchemaCaller, options: SchemaViewOptions = {}): SchemaView | SchemaRefusal {\n if (caller.kind === \"anonymous\") {\n return { privileged: false, accountLabels: false, viewer: { roles: [] }, tables: { kind: \"public\" } };\n }\n const scopes = caller.scopes;\n const privileged = scopeGrants(scopes, \"schema:read\");\n const accountLabels = privileged || scopeGrants(scopes, \"users:read\");\n const viewer: FieldViewer = { roles: [...caller.roles] };\n if (privileged) return { privileged, accountLabels, viewer, tables: { kind: \"all\" } };\n if (caller.kind === \"person\") {\n return { privileged, accountLabels, viewer, tables: { kind: options.persons === \"all\" ? \"all\" : \"granted\" } };\n }\n if (!DATA_SCOPES.some(scope => scopeGrantsAny(scopes, scope))) {\n return {\n refused: \"scope\",\n message: \"This credential holds neither `schema:read` nor a `data:*` scope, so it may not read the schema. \" +\n \"Grant it `schema:read`, or the `data:read:<table>` scopes of the tables it works with.\"\n };\n }\n const slugs = new Set<string>();\n for (const scope of DATA_SCOPES) {\n const targets = scopeTargets(scopes, scope);\n if (targets === \"all\") return { privileged, accountLabels, viewer, tables: { kind: \"all\" } };\n for (const target of targets) slugs.add(target);\n }\n return { privileged, accountLabels, viewer, tables: { kind: \"only\", slugs: [...slugs].sort() } };\n}\n\n/** The view `/api/meta/contract` serves: every table, as an administrator sees it. */\nexport const ADMIN_SCHEMA_VIEW: SchemaView = Object.freeze({\n privileged: true,\n accountLabels: true,\n viewer: Object.freeze({ roles: Object.freeze([\"admin\"]) }),\n tables: Object.freeze({ kind: \"all\" as const })\n});\n\n/**\n * A short, stable digest of everything the redaction depends on: two callers\n * with the same key are served byte-identical bodies. Part of the `ETag`.\n *\n * @group Schema\n */\nexport function schemaViewKey(view: SchemaView): string {\n const identity = {\n p: view.privileged,\n a: view.accountLabels,\n r: [...new Set(view.viewer.roles ?? [])].sort(),\n t: view.tables.kind === \"only\" ? view.tables.slugs : view.tables.kind\n };\n return createHash(\"sha256\").update(JSON.stringify(identity)).digest(\"hex\").slice(0, 16);\n}\n\n// ── Compiled policies ────────────────────────────────────────────────────────\n\n/**\n * The compiled policies of one table, and of the junctions of its\n * `manyToMany` relations.\n *\n * @group Schema\n */\nexport interface TablePolicies {\n policies: PolicyDescriptor[];\n junctions: JunctionPolicyDescriptor[];\n}\n\n/** The planner's options: this runtime switches admin requests to `rebase_admin`. */\nconst COMPILE_OPTIONS = { adminRole: true, adminRequestRole: true } as const;\n\nfunction asPolicy(compiled: CompiledRulePolicy, injected: boolean, rule: number | undefined): PolicyDescriptor {\n return {\n name: compiled.name,\n operation: compiled.operation,\n mode: compiled.mode,\n roles: [...compiled.roles],\n using: compiled.using,\n withCheck: compiled.withCheck,\n // An admin-request companion is Rebase's, whatever rule it rides on.\n injected: injected || compiled.adminRequestTarget === true,\n ...(rule !== undefined && compiled.adminRequestTarget !== true ? { rule } : {})\n };\n}\n\n/**\n * Compile the policies of every table — what the schema planner writes into\n * Postgres and the Studio's RLS editor compares the live database against —\n * from the same `compileTableRulePolicies` / `tableEffectiveRules` the planner\n * reads, keyed by slug.\n *\n * Reads the declared tables' descriptors. Introspected tables are not among\n * them: Rebase did not generate their policies and cannot say what they are.\n *\n * A rule that cannot be compiled (an `existsIn` naming a table this backend\n * does not hold) contributes no policy and is logged; the rest still are.\n *\n * @group Schema\n */\nexport function compileServedPolicies(\n tables: readonly TableDescriptor[],\n describedSlugs: ReadonlySet<string>\n): Map<string, TablePolicies> {\n const options = { ...COMPILE_OPTIONS, resolveTable: policyTableResolver(tables) };\n const out = new Map<string, TablePolicies>();\n\n const compile = (table: PolicyTable, rule: SecurityRule, injected: boolean, index: number | undefined): PolicyDescriptor[] => {\n try {\n return compileTableRulePolicies(table, rule, options).map(policy => asPolicy(policy, injected, index));\n } catch (error) {\n logger.debug(\"A rule could not be compiled for GET /api/schema/tables\", {\n table: table.table,\n error: error instanceof Error ? error.message : String(error)\n });\n return [];\n }\n };\n\n for (const descriptor of tables) {\n if (!describedSlugs.has(descriptor.slug)) continue;\n const table = policyTableFromDescriptor(descriptor);\n const explicit = table.rules.length;\n const injectedNames = new Set(tableInjectedRules(table).map(rule => rule.name));\n const policies = tableEffectiveRules(table).flatMap((rule, index) => {\n const injected = index >= explicit || (rule.name !== undefined && injectedNames.has(rule.name));\n return compile(table, rule, injected, injected ? undefined : index);\n });\n out.set(descriptor.slug, { policies, junctions: [] });\n }\n\n let junctions: ReturnType<typeof resolveTableJunctions>;\n try {\n junctions = resolveTableJunctions(tables);\n } catch (error) {\n logger.debug(\"The junction tables could not be resolved for GET /api/schema/tables\", {\n error: error instanceof Error ? error.message : String(error)\n });\n return out;\n }\n for (const junction of junctions.values()) {\n const table = junctionPolicyTable(junction);\n const policies = tableJunctionRules(junction).flatMap(rule => compile(table, rule, true, undefined));\n const entry: JunctionPolicyDescriptor = { table: junction.table, schema: junction.schema, policies };\n const sides = new Set(junction.declaringSides.map(side => side.descriptor.slug));\n for (const slug of sides) {\n const served = out.get(slug);\n if (served && !served.junctions.some(existing => existing.table === entry.table)) served.junctions.push(entry);\n }\n }\n return out;\n}\n\n// ── Redaction ────────────────────────────────────────────────────────────────\n\n/** Whether anything under `value` is a `policy.raw(…)` node. */\nfunction containsRawNode(value: unknown): boolean {\n if (Array.isArray(value)) return value.some(containsRawNode);\n if (typeof value !== \"object\" || value === null) return false;\n if (\"kind\" in value && value.kind === \"raw\") return true;\n return Object.values(value).some(containsRawNode);\n}\n\n/** Whether a rule carries SQL text anywhere: a raw clause, or a raw node inside a structured one. */\nfunction carriesSql(rule: SecurityRule): boolean {\n return rule.using !== undefined || rule.withCheck !== undefined\n || containsRawNode(rule.condition) || containsRawNode(rule.check);\n}\n\n/**\n * A rule as a caller who may not see SQL is served it: as written when it\n * carries none, else the {@link RedactedSecurityRule} marker, keeping only\n * whom the rule concerns.\n *\n * @group Schema\n */\nexport function redactRule(rule: SecurityRule): SecurityRule {\n if (isRedactedSecurityRule(rule) || !carriesSql(rule)) return rule;\n const marker: RedactedSecurityRule = {\n redacted: true,\n ...(rule.operation !== undefined ? { operation: rule.operation } : {}),\n ...(rule.operations !== undefined ? { operations: [...rule.operations] } : {}),\n ...(rule.mode !== undefined ? { mode: rule.mode } : {}),\n ...(rule.roles !== undefined ? { roles: [...rule.roles] } : {}),\n ...(rule.access !== undefined ? { access: rule.access } : {})\n };\n return marker;\n}\n\nfunction appliesTo(rule: SecurityRule, operation: SecurityOperation): boolean {\n const operations = rule.operations && rule.operations.length > 0 ? rule.operations : [rule.operation ?? \"all\"];\n return operations.includes(operation) || operations.includes(\"all\");\n}\n\n/**\n * Whether anyone, signed in or not, may read some of a table's rows: a\n * permissive `select` rule with `access: \"public\"`, not narrowed to roles or\n * to Postgres roles. What the anonymous view (the public opt-in) serves.\n *\n * @group Schema\n */\nexport function hasPublicSelectRule(table: TableDescriptor): boolean {\n if (table.kind !== \"table\" || table.rls.posture !== \"rules\") return false;\n return table.rls.rules.some(rule =>\n !isRedactedSecurityRule(rule)\n && (rule.mode ?? \"permissive\") === \"permissive\"\n && rule.access === \"public\"\n && (rule.roles === undefined || rule.roles.length === 0)\n && rule.pgRoles === undefined\n && appliesTo(rule, \"select\"));\n}\n\n/**\n * Whether a caller holding `roles` holds one of a rule's (or a view's)\n * `roles`: always when it names none, and when it names `\"public\"`, which the\n * policy compiler and the client evaluator both read as everyone.\n */\nfunction holdsOneOf(named: readonly string[] | undefined, roles: readonly string[]): boolean {\n if (!named || named.length === 0) return true;\n return named.some(role => role === \"public\" || roles.includes(role));\n}\n\n/**\n * Whether a rule can apply to a caller holding `roles`: a rule with no\n * `roles` applies to everyone (public, authenticated, registered, owner,\n * condition and raw SQL rules alike — what they admit is decided per row),\n * one with `roles` to the holders of one of them. Restrictive rules count\n * too: they narrow what the caller is granted, and the panel gates by them.\n *\n * @group Schema\n */\nexport function ruleAppliesTo(rule: SecurityRule, roles: readonly string[]): boolean {\n return holdsOneOf(rule.roles, roles);\n}\n\n/**\n * Whether some rule could grant a caller holding `roles` something on a\n * table — what a person without `schema:read` is described under\n * `schemaTables.persons: \"granted\"`:\n *\n * - a table with a permissive rule that applies to them ({@link ruleAppliesTo});\n * - the auth table: every account reads its own row (the injected self-read);\n * - a table under the admin baseline (`\"admin-only\"`, or rules with\n * `defaultPolicies`), for a caller holding `admin`;\n * - a materialized view, for a holder of one of its `view.roles`\n * (`[\"admin\"]` when it names none);\n * - a plain view: never. It has no rules of its own — it runs as the caller\n * over the tables its SQL reads, which the descriptor does not list — so\n * the conservative answer is that it reaches nobody here; `persons: \"all\"`\n * or `schema:read` describes it.\n *\n * @group Schema\n */\nexport function tableReachable(table: TableDescriptor, roles: readonly string[]): boolean {\n if (table.kind === \"view\" || table.rls.posture === \"view\") {\n const viewRoles = table.view?.roles ?? [\"admin\"];\n return table.view?.materialized === true && viewRoles.length > 0 && holdsOneOf(viewRoles, roles);\n }\n if (table.auth) return true;\n if (roles.includes(\"admin\") && (table.rls.posture === \"admin-only\" || table.rls.defaultPolicies)) return true;\n if (table.rls.posture !== \"rules\") return false;\n return table.rls.rules.some(rule => (rule.mode ?? \"permissive\") === \"permissive\" && ruleAppliesTo(rule, roles));\n}\n\nfunction tableServed(table: TableDescriptor, view: SchemaView): boolean {\n switch (view.tables.kind) {\n case \"all\":\n return true;\n case \"only\":\n return view.tables.slugs.includes(table.slug);\n case \"public\":\n return hasPublicSelectRule(table);\n case \"granted\":\n return tableReachable(table, view.viewer.roles ?? []);\n }\n}\n\n/**\n * The slugs of the tables a view is served — what `/api/admin/ui-config`\n * accepts a caller's preferences for.\n *\n * @group Schema\n */\nexport function servedTableSlugs(tables: readonly TableDescriptor[], view: SchemaView): Set<string> {\n return new Set(tables.filter(table => tableServed(table, view)).map(table => table.slug));\n}\n\n/** Whether a view withholds hook presence flags: the least-privileged views, which the panel serves. */\nfunction withholdsHookFlags(view: SchemaView): boolean {\n return !view.privileged && (view.tables.kind === \"granted\" || view.tables.kind === \"public\");\n}\n\nfunction columnServed(column: ColumnDescriptor, viewer: FieldViewer): boolean {\n return column.private !== true && canReadWithAccess(column.access, viewer);\n}\n\n/**\n * A relation as this view describes it, or `undefined` when it is withheld:\n * private, closed to the viewer, joined on a column the viewer may not read\n * on any table it passes through (a relation is exactly as readable as what\n * it is joined on), or pointing at a table the view does not serve.\n */\nfunction servedRelation(\n table: TableDescriptor,\n relation: RelationDescriptor,\n view: SchemaView,\n served: ReadonlySet<string>,\n related: RelatedTables\n): RelationDescriptor | undefined {\n if (!canReadRelation(table, relation, view.viewer, related)) return undefined;\n if (!served.has(relation.target)) return undefined;\n if (relation.kind !== \"manyToMany\") return relation;\n return {\n ...relation,\n through: { ...relation.through, pivot: relation.through.pivot.filter(column => columnServed(column, view.viewer)) }\n };\n}\n\nfunction servedRls(rls: RlsDescriptor, view: SchemaView, policies: TablePolicies | undefined): RlsDescriptor {\n const { policies: _policies, junctions: _junctions, ...base } = rls;\n if (!view.privileged) {\n const roles = view.viewer.roles ?? [];\n const rules = view.tables.kind === \"granted\" ? rls.rules.filter(rule => ruleAppliesTo(rule, roles)) : rls.rules;\n return { ...base, rules: rules.map(redactRule) };\n }\n return policies ? { ...base, policies: policies.policies, junctions: policies.junctions } : base;\n}\n\nfunction serializeTable(\n table: TableDescriptor,\n view: SchemaView,\n served: ReadonlySet<string>,\n policies: TablePolicies | undefined,\n related: RelatedTables\n): TableDescriptor {\n const relations = table.relations\n .map(relation => servedRelation(table, relation, view, served, related))\n .filter((relation): relation is RelationDescriptor => relation !== undefined);\n const relationNames = new Set(relations.map(relation => relation.name));\n // A link and its key column are one fact under two names: a key column\n // whose relation is withheld is withheld with it (as the REST read strips\n // it), derived or declared.\n const withheldKeys = new Set(table.relations\n .filter(relation => relation.kind === \"belongsTo\" && !canReadRelation(table, relation, view.viewer, related))\n .map(relation => relation.kind === \"belongsTo\" ? relation.localField : \"\"));\n const hookFlags = !withholdsHookFlags(view);\n const columns = table.columns\n .filter(column => columnServed(column, view.viewer))\n .filter(column => !withheldKeys.has(column.key))\n .map(column => {\n let served = column;\n if (!hookFlags && served.transforms !== undefined) {\n const { transforms: _transforms, ...rest } = served;\n served = rest;\n }\n // A dropped relation is not named by the column that held its key.\n if (served.foreignKeyOf === undefined || relationNames.has(served.foreignKeyOf)) return served;\n const { foreignKeyOf: _relation, ...rest } = served;\n return rest;\n });\n const columnKeys = new Set(columns.map(column => column.key));\n\n const {\n columns: _columns,\n relations: _relations,\n rls,\n indexes,\n view: viewDefinition,\n auth,\n search,\n hooks,\n ...rest\n } = table;\n\n const searchFields = search?.fields.filter(field => {\n const path = typeof field === \"string\" ? field : field.path;\n return columnKeys.has(path.split(\".\")[0] ?? path);\n });\n let servedAuth = auth;\n if (servedAuth && !view.accountLabels) {\n const { roles: _roles, scopes: _scopes, ...unlabelled } = servedAuth;\n servedAuth = unlabelled;\n }\n if (servedAuth && !hookFlags && servedAuth.hooks !== undefined) {\n const { hooks: _authHooks, ...withoutHooks } = servedAuth;\n servedAuth = withoutHooks;\n }\n let servedView = viewDefinition;\n if (viewDefinition && !view.privileged) {\n const { query: _query, ...withoutQuery } = viewDefinition;\n servedView = withoutQuery;\n }\n\n return {\n ...rest,\n columns,\n relations,\n rls: servedRls(rls, view, policies),\n ...(search && searchFields && searchFields.length > 0 ? { search: { ...search, fields: searchFields } } : {}),\n ...(indexes && view.privileged ? { indexes } : {}),\n ...(servedView ? { view: servedView } : {}),\n ...(servedAuth ? { auth: servedAuth } : {}),\n ...(hooks && hookFlags ? { hooks } : {})\n };\n}\n\n/**\n * The tables a caller is served, redacted for its view (see the module\n * documentation for the table of who sees what). Pure: the same descriptors,\n * view and policies give the same body.\n *\n * @param policies The compiled policies by slug ({@link compileServedPolicies});\n * included for a privileged view only, and only for the tables that have them.\n *\n * @group Schema\n */\nexport function serializeTables(\n tables: readonly TableDescriptor[],\n view: SchemaView,\n policies?: ReadonlyMap<string, TablePolicies>\n): TableDescriptor[] {\n const shown = tables.filter(table => tableServed(table, view));\n const served = new Set(shown.map(table => table.slug));\n // Every declared table, served or not: a join reads the columns it reads\n // whether or not this caller is described the table they are on.\n const related: RelatedTables = name => tables.find(table => table.slug === name || table.table === name);\n return shown.map(table => serializeTable(table, view, served, view.privileged ? policies?.get(table.slug) : undefined, related));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,SAAS,KAAK,OAAO,GAAG;CACvB,OAAO,SAAS,IAAI,UAAU,KAAK;AACpC;;;;;;;AAOA,SAAS,QAAQ,OAAO;CACvB,MAAM,QAAQ,MAAM,KAAK,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK,CAAC;CACxD,MAAM,YAAY,MAAM,S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AU,KAAA,GAAW;EAC5D,MAAM,EAAE,OAAO,YAAY,GAAG,iBAAiB;EAC/C,aAAa;CACjB;CACA,IAAI,aAAa;CACjB,IAAI,kBAAkB,CAAC,KAAK,YAAY;EACpC,MAAM,EAAE,OAAO,QAAQ,GAAG,iBAAiB;EAC3C,aAAa;CACjB;CAEA,OAAO;EACH,GAAG;EACH;EACA;EACA,KAAK,UAAU,KAAK,MAAM,QAAQ;EAClC,GAAI,UAAU,gBAAgB,aAAa,SAAS,IAAI,EAAE,QAAQ;GAAE,GAAG;GAAQ,QAAQ;EAAa,EAAE,IAAI,CAAC;EAC3G,GAAI,WAAW,KAAK,aAAa,EAAE,QAAQ,IAAI,CAAC;EAChD,GAAI,aAAa,EAAE,MAAM,WAAW,IAAI,CAAC;EACzC,GAAI,aAAa,EAAE,MAAM,WAAW,IAAI,CAAC;EACzC,GAAI,SAAS,YAAY,EAAE,MAAM,IAAI,CAAC;CAC1C;AACJ;;;;;;;;;;;AAYA,SAAgB,gBACZ,QACA,MACA,UACiB;CACjB,MAAM,QAAQ,OAAO,QAAO,UAAS,YAAY,OAAO,IAAI,CAAC;CAC7D,MAAM,SAAS,IAAI,IAAI,MAAM,KAAI,UAAS,MAAM,IAAI,CAAC;CAGrD,MAAM,WAAyB,SAAQ,OAAO,MAAK,UAAS,MAAM,SAAS,QAAQ,MAAM,UAAU,IAAI;CACvG,OAAO,MAAM,KAAI,UAAS,eAAe,OAAO,MAAM,QAAQ,KAAK,aAAa,UAAU,IAAI,MAAM,IAAI,IAAI,KAAA,GAAW,OAAO,CAAC;AACnI"}
|
|
1
|
+
{"version":3,"file":"schema-tables-DKFg6vMV.js","names":[],"sources":["../../utils/dist/sha1.es.js","../../utils/dist/policy-names.es.js","../../common/src/util/policy/policyToPostgres.ts","../../common/src/util/policy/compileRulePolicies.ts","../../common/src/util/policy/policy-table.ts","../../common/src/util/tenant.ts","../../common/src/util/auth-default-policies.ts","../../common/src/util/junction-policies.ts","../src/api/schema-tables.ts"],"sourcesContent":["//#region src/sha1.ts\n/**\n* Minimal SHA-1 implementation that runs in both Node and the browser.\n*\n* This exists because generated Postgres policy names embed a SHA-1 digest of\n* the security rule. The DDL generator runs on the server (where `node:crypto`\n* is available) but the Studio has to derive the same names in the browser to\n* tell a policy it generated apart from one it did not. `node:crypto` cannot be\n* bundled for the browser, so the shared derivation needs a portable digest.\n*\n* SHA-1 is used purely to name things deterministically — never for security.\n* The output is byte-identical to `createHash(\"sha1\").update(str).digest(\"hex\")`,\n* which `sha1.test.ts` pins against `node:crypto` directly.\n*/\n/** Rotate a 32-bit word left by `n` bits. */\nfunction rotl(value, n) {\n\treturn value << n | value >>> 32 - n;\n}\n/**\n* SHA-1 digest of a string, hex-encoded.\n*\n* The input is encoded as UTF-8, matching Node's default handling of strings\n* passed to `hash.update(str)`.\n*/\nfunction sha1Hex(input) {\n\tconst bytes = Array.from(new TextEncoder().encode(input));\n\tconst bitLength = bytes.length * 8;\n\tbytes.push(128);\n\twhile (bytes.length % 64 !== 56) bytes.push(0);\n\tconst hi = Math.floor(bitLength / 4294967296);\n\tconst lo = bitLength >>> 0;\n\tbytes.push(hi >>> 24 & 255, hi >>> 16 & 255, hi >>> 8 & 255, hi & 255);\n\tbytes.push(lo >>> 24 & 255, lo >>> 16 & 255, lo >>> 8 & 255, lo & 255);\n\tlet h0 = 1732584193;\n\tlet h1 = 4023233417;\n\tlet h2 = 2562383102;\n\tlet h3 = 271733878;\n\tlet h4 = 3285377520;\n\tconst w = new Array(80);\n\tfor (let offset = 0; offset < bytes.length; offset += 64) {\n\t\tfor (let i = 0; i < 16; i++) {\n\t\t\tconst j = offset + i * 4;\n\t\t\tw[i] = bytes[j] << 24 | bytes[j + 1] << 16 | bytes[j + 2] << 8 | bytes[j + 3] | 0;\n\t\t}\n\t\tfor (let i = 16; i < 80; i++) w[i] = rotl(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);\n\t\tlet a = h0;\n\t\tlet b = h1;\n\t\tlet c = h2;\n\t\tlet d = h3;\n\t\tlet e = h4;\n\t\tfor (let i = 0; i < 80; i++) {\n\t\t\tlet f;\n\t\t\tlet k;\n\t\t\tif (i < 20) {\n\t\t\t\tf = b & c | ~b & d;\n\t\t\t\tk = 1518500249;\n\t\t\t} else if (i < 40) {\n\t\t\t\tf = b ^ c ^ d;\n\t\t\t\tk = 1859775393;\n\t\t\t} else if (i < 60) {\n\t\t\t\tf = b & c | b & d | c & d;\n\t\t\t\tk = 2400959708;\n\t\t\t} else {\n\t\t\t\tf = b ^ c ^ d;\n\t\t\t\tk = 3395469782;\n\t\t\t}\n\t\t\tconst temp = rotl(a, 5) + f + e + k + w[i] | 0;\n\t\t\te = d;\n\t\t\td = c;\n\t\t\tc = rotl(b, 30);\n\t\t\tb = a;\n\t\t\ta = temp;\n\t\t}\n\t\th0 = h0 + a | 0;\n\t\th1 = h1 + b | 0;\n\t\th2 = h2 + c | 0;\n\t\th3 = h3 + d | 0;\n\t\th4 = h4 + e | 0;\n\t}\n\treturn [\n\t\th0,\n\t\th1,\n\t\th2,\n\t\th3,\n\t\th4\n\t].map((word) => (word >>> 0).toString(16).padStart(8, \"0\")).join(\"\");\n}\n//#endregion\nexport { sha1Hex };\n\n//# sourceMappingURL=sha1.es.js.map","import { sha1Hex } from \"./sha1.es.js\";\nimport { toPostgresIdentifier, truncateToBytes } from \"./names.es.js\";\nimport { isPolicyShorthand } from \"@rebasepro/types\";\n//#region src/policy-names.ts\n/**\n* Naming of the Postgres policies generated from a collection's security rules.\n*\n* A rule without an explicit `name` is compiled to `<table>_<op>_<hash>`, where\n* the hash covers the rule's semantics. The Studio needs the same names to tell\n* \"this policy came from your code\" apart from \"someone wrote this in SQL\" —\n* without them it treats generated policies as foreign and offers to import\n* them back into the codebase they came from.\n*\n* This is the single definition of that naming. The DDL and Drizzle generators\n* both derive names from here, so a change cannot silently rename every policy\n* in every deployed database while the UI keeps matching the old ones.\n*/\n/**\n* Stable digest of the parts of a rule that determine what the policy does.\n*\n* Two hash inputs, never mixed:\n*\n* - **A rule of a shape every release has known** hashes\n* `JSON.stringify({ a, m, op, ops, own, rol, pg, u, w, c, ch })`, byte for\n* byte as it always has — a deployed database keeps its policies by these\n* names, so this input must never move. Its `condition` / `check` are\n* serialised in the key order they were written in, as they always were.\n* - **A rule using a newer form** ({@link isNewShapeRule}: a\n* `PolicyShorthand` condition / check, `access` combined with a\n* condition / check, or `access: \"authenticated\"` / `\"registered\"`) hashes {@link newShapeHashInput}:\n* `\"rls2:\"` followed by canonical JSON in which every object's keys are\n* sorted, so `{ a: 1, b: 2 }` and `{ b: 2, a: 1 }` name the same policy.\n* A legacy input starts with `{`, so the two spaces cannot meet.\n*/\nfunction getPolicyNameHash(rule) {\n\tif (isNewShapeRule(rule)) return sha1Hex(newShapeHashInput(rule)).substring(0, 7);\n\treturn sha1Hex(JSON.stringify({\n\t\ta: rule.access,\n\t\tm: rule.mode,\n\t\top: rule.operation,\n\t\tops: rule.operations?.slice().sort(),\n\t\town: rule.ownerField,\n\t\trol: rule.roles?.slice().sort(),\n\t\tpg: rule.pgRoles?.slice().sort(),\n\t\tu: rule.using,\n\t\tw: rule.withCheck,\n\t\tc: frozenHashSpelling(rule.condition),\n\t\tch: frozenHashSpelling(rule.check)\n\t})).substring(0, 7);\n}\n/**\n* Whether a rule uses a form newer than the legacy hash input knows: a\n* `PolicyShorthand` condition or check, `access` together with a condition or\n* check, or `access: \"authenticated\"` (which older releases did not type and\n* compiled to a deny; it now means any signed-in caller, under a new name) or\n* `access: \"registered\"` (added after it). Such a rule hashes\n* {@link newShapeHashInput}; every other rule keeps the legacy input.\n*/\nfunction isNewShapeRule(rule) {\n\tif (rule.access === \"authenticated\" || rule.access === \"registered\") return true;\n\tif (rule.access !== void 0 && (rule.condition != null || rule.check != null)) return true;\n\treturn isPolicyShorthand(rule.condition) || isPolicyShorthand(rule.check);\n}\n/**\n* The hash input of a {@link isNewShapeRule new-shape} rule:\n* `\"rls2:\" + canonicalJson({ a, c, ch, m, op, ops, own, pg, rol, u, w })`.\n*\n* `canonicalJson` is `JSON.stringify` with every object's keys sorted (arrays\n* keep their order, `undefined` members are dropped). A shorthand is encoded\n* as `{ \"=\": [[column, value], …] }`, its pairs sorted by column — the\n* `=` tag keeps it apart from an expression node, which always carries\n* `kind`. `ops`, `rol` and `pg` are sorted as in the legacy input.\n*/\nfunction newShapeHashInput(rule) {\n\treturn `rls2:${canonicalJson({\n\t\ta: rule.access,\n\t\tm: rule.mode,\n\t\top: rule.operation,\n\t\tops: rule.operations?.slice().sort(),\n\t\town: rule.ownerField,\n\t\trol: rule.roles?.slice().sort(),\n\t\tpg: rule.pgRoles?.slice().sort(),\n\t\tu: rule.using,\n\t\tw: rule.withCheck,\n\t\tc: conditionHashValue(frozenHashSpelling(rule.condition)),\n\t\tch: conditionHashValue(frozenHashSpelling(rule.check))\n\t})}`;\n}\n/**\n* The frozen spelling of the hash input: a condition as it was spelled when\n* the names in deployed databases were derived from it.\n*\n* An `existsIn` node names its join table in `table`, which was spelled\n* `collection` before tables replaced collections in the backend vocabulary.\n* Hashed as written, every unnamed policy with a membership subquery would be\n* renamed by the rename alone. So the hash reads each `existsIn` node with\n* `table` put back as `collection`, in the same key position, and nothing\n* else changes: this is the input, byte for byte, the old spelling produced.\n* Never extend it to a new field — it exists only to keep old names.\n*/\nfunction frozenHashSpelling(condition) {\n\tif (Array.isArray(condition)) return condition.map(frozenHashSpelling);\n\tif (typeof condition !== \"object\" || condition === null) return condition;\n\tconst existsIn = \"kind\" in condition && condition.kind === \"existsIn\";\n\treturn Object.fromEntries(Object.entries(condition).map(([key, value]) => [existsIn && key === \"table\" ? \"collection\" : key, frozenHashSpelling(value)]));\n}\nfunction conditionHashValue(condition) {\n\tif (!isPolicyShorthand(condition)) return condition;\n\treturn { \"=\": Object.keys(condition).sort().map((column) => [column, condition[column]]) };\n}\nfunction canonicalJson(value) {\n\treturn JSON.stringify(value, (_key, member) => {\n\t\tif (typeof member !== \"object\" || member === null || Array.isArray(member)) return member;\n\t\treturn Object.fromEntries(Object.entries(member).sort(([a], [b]) => a < b ? -1 : a > b ? 1 : 0));\n\t});\n}\n/** The operations a rule expands to — `operations` wins over `operation`. */\nfunction getPolicyOperations(rule) {\n\treturn rule.operations && rule.operations.length > 0 ? rule.operations : [rule.operation ?? \"all\"];\n}\n/**\n* The names a rule compiled to before {@link getPolicyNamesForRule} learned\n* about Postgres's identifier limit — and still compiles to whenever they fit.\n*/\nfunction untruncatedPolicyNames(rule, tableName) {\n\tconst ops = getPolicyOperations(rule);\n\tconst ruleHash = getPolicyNameHash(rule);\n\treturn ops.map((op, opIdx) => rule.name ? ops.length > 1 ? `${rule.name}_${op}` : rule.name : `${tableName}_${op}_${ruleHash}${ops.length > 1 ? `_${opIdx}` : \"\"}`);\n}\n/** Whether Postgres, keeping 63 bytes of each, would store two of these under one name. */\nvar collideWhenStored = (names) => new Set(names.map(toPostgresIdentifier)).size < names.length;\n/**\n* `<prefix cut to fit>_<hash8>_<op>`, at most 63 bytes. The hash is over the\n* full name, so it carries everything the cut drops; the operation stays\n* readable at the end.\n*/\nfunction suffixFirstPolicyName(fullName, op) {\n\tconst tail = `_${sha1Hex(fullName).substring(0, 8)}_${op}`;\n\treturn `${truncateToBytes(fullName, 63 - tail.length).replace(/_+$/, \"\")}${tail}`;\n}\n/**\n* Every Postgres policy name a single rule compiles to — one per operation.\n*\n* `<table>_<op>_<hash>[_<i>]`, or `<name>[_<op>]` for a named rule — byte for\n* byte what every release has written, with one exception. Postgres keeps the\n* first 63 bytes of an identifier, so a multi-operation rule whose names differ\n* only past that point (the injected `<table>_default_admin_write_<op>` on a\n* table of 42 bytes or more) used to store every operation under ONE name: each\n* `CREATE POLICY` replaced the last, only the final operation survived, and the\n* table denied the others. Only for such a rule each name is derived\n* suffix-first instead — see {@link suffixFirstPolicyName} — and\n* {@link getPolicySupersededNames} names the one policy the old names left in\n* the database, so the next boot or push replaces it. A single over-long name\n* that is unique as stored is left as it is.\n*\n* @param rule The security rule as written in the collection config.\n* @param tableName The rule's table (see `getTableName` in `@rebasepro/common`).\n*/\nfunction getPolicyNamesForRule(rule, tableName) {\n\tconst names = untruncatedPolicyNames(rule, tableName);\n\tif (!collideWhenStored(names)) return names;\n\tconst ops = getPolicyOperations(rule);\n\treturn names.map((name, index) => suffixFirstPolicyName(name, ops[index]));\n}\n/**\n* The policy names, as Postgres stored them, that the old naming wrote for\n* this rule and {@link getPolicyNamesForRule} no longer produces — empty unless\n* the rule's per-operation names collided at 63 bytes. Dropping them is what\n* turns a database a previous release left with one truncated policy into one\n* with a policy per operation.\n*/\nfunction getPolicySupersededNames(rule, tableName) {\n\tconst names = untruncatedPolicyNames(rule, tableName);\n\tif (!collideWhenStored(names)) return [];\n\treturn Array.from(new Set(names.map(toPostgresIdentifier)));\n}\n/** Every policy name a set of rules compiles to, for membership checks. */\nfunction getPolicyNamesForRules(rules, tableName) {\n\tconst names = /* @__PURE__ */ new Set();\n\tfor (const rule of rules) for (const name of getPolicyNamesForRule(rule, tableName)) names.add(name);\n\treturn names;\n}\n/** What every {@link adminRequestPolicyName} ends with: `_ar_` and eight hex digits. */\nvar ADMIN_REQUEST_POLICY_SUFFIX = /_ar_[0-9a-f]{8}$/;\n/**\n* The name of an admin-only policy's companion — the `USING (true)` grant to\n* the admin request roles (`REBASE_ADMIN_REQUEST_ROLE`): the base name cut to\n* fit, then `_ar_` and a hash of the whole base name, at most 63 bytes, so two\n* bases that share a cut prefix never share a companion.\n*/\nfunction adminRequestPolicyName(baseName) {\n\tconst tail = `_ar_${sha1Hex(baseName).substring(0, 8)}`;\n\treturn `${truncateToBytes(baseName, 63 - tail.length).replace(/_+$/, \"\")}${tail}`;\n}\n//#endregion\nexport { ADMIN_REQUEST_POLICY_SUFFIX, adminRequestPolicyName, getPolicyNameHash, getPolicyNamesForRule, getPolicyNamesForRules, getPolicyOperations, getPolicySupersededNames, isNewShapeRule, newShapeHashInput };\n\n//# sourceMappingURL=policy-names.es.js.map","import { ANONYMOUS_USER_IDS, PolicyExpression, PolicyOperand, PolicyCompareOperator, ExistsInPolicyExpression, RLS_IS_ANONYMOUS_SQL, RLS_JWT_SQL, RLS_ROLES_SQL, RLS_UID_SQL, rewriteLegacyRlsFunctions } from \"@rebasepro/types\";\nimport { toSnakeCase } from \"@rebasepro/utils\";\nimport type { ClaimCastType, PolicyColumn, PolicyTable, ResolvePolicyTable } from \"./policy-table\";\n\n/**\n * Options for {@link compilePolicyExpression}.\n */\nexport interface PolicyCompileOptions {\n /**\n * Resolve a table by slug. Required to compile\n * {@link ExistsInPolicyExpression} (`policy.existsIn`) — the compiler needs\n * the joined table's name and schema. When omitted, the join table falls\n * back to a snake_cased slug.\n */\n resolveTable?: ResolvePolicyTable;\n}\n\n/**\n * The lexical scope threaded through compilation. It changes when we descend\n * into an `existsIn` subquery: inside it, `field` refers to the joined table\n * (aliased) while `outerField` refers to the outer RLS row (table-qualified).\n */\ninterface CompileScope {\n /** The table whose columns a bare `field` operand resolves against. */\n fieldTable?: PolicyTable;\n /** SQL prefix for `field` operands (`\"\"` at top level, `\"alias\".` in a subquery). */\n fieldPrefix: string;\n /** The outer RLS table, for `outerField` operands. */\n outerTable?: PolicyTable;\n /** SQL prefix for `outerField` operands (`\"\"` at top level, `\"schema\".\"table\".` in a subquery). */\n outerPrefix: string;\n resolveTable?: ResolvePolicyTable;\n /** Monotonic counter for generating unique subquery aliases. */\n alias: { n: number };\n /**\n * True inside a hoisted `(SELECT …)`. The subquery already evaluates its\n * whole body once per statement, so the helpers in it are emitted bare.\n */\n inInitPlan: boolean;\n}\n\n/**\n * Compiles a {@link PolicyExpression} to a PostgreSQL boolean SQL string,\n * suitable for a `USING (...)` / `WITH CHECK (...)` clause.\n *\n * This is one of the two consumers of the shared policy model (the other being\n * {@link evaluatePolicy}); the Postgres schema generators call it so that DDL\n * and the admin UI derive from the exact same expression.\n *\n * ## Row-independent parts are evaluated once per statement\n *\n * Every part of a policy that does not read the row — `serverContext()`, a\n * roles test, a comparison of the caller with a literal, a claim — is wrapped\n * in a scalar subquery: the default baseline compiles to\n * `(SELECT (rebase.uid() IS NULL) OR (string_to_array(rebase.roles(), ',') && ARRAY['admin']))`,\n * and an owner rule to `owner_id = (SELECT rebase.uid())`. Postgres plans an\n * uncorrelated scalar subquery as an initPlan, computed once per statement.\n *\n * Bare, the same clause is a security-barrier qual Postgres evaluates per row,\n * and it estimates `uid() IS NULL OR roles && …` to pass 1.5% of the table. A\n * page past that point (offset 20,000 of a million rows) was planned as a\n * sequential scan and an on-disk sort of the whole table: 7.3 s and a 640 MB\n * sort per request, against 4 ms off the primary key once the predicate is an\n * initPlan, whose estimate is 50%.\n *\n * Same meaning, by construction: only subtrees that reference no column are\n * wrapped (never `field`, `outerField`, `existsIn` or `raw`), a scalar subquery\n * without `FROM` returns exactly one row whose value is the expression's —\n * NULL included, so three-valued logic is untouched — and the helpers are\n * STABLE, so their value cannot change within a statement anyway.\n * `policy-shapes-equivalence.test.ts` runs every shape against Postgres both\n * ways.\n */\nexport function compilePolicyExpression(expr: PolicyExpression, table?: PolicyTable, options?: PolicyCompileOptions): string {\n return compile(expr, {\n fieldTable: table,\n fieldPrefix: \"\",\n outerTable: table,\n outerPrefix: \"\",\n resolveTable: options?.resolveTable,\n alias: { n: 0 },\n inInitPlan: false\n });\n}\n\n/**\n * Whether `expr` never reads the row: no `field` / `outerField` operand, no\n * correlated `existsIn`, no `raw` SQL (which may name any column).\n */\nfunction readsNoRow(expr: PolicyExpression): boolean {\n switch (expr.kind) {\n case \"and\":\n case \"or\":\n return expr.operands.every(readsNoRow);\n case \"not\":\n return readsNoRow(expr.operand);\n case \"compare\":\n return !readsRow(expr.left) && !readsRow(expr.right);\n case \"existsIn\":\n case \"raw\":\n return false;\n default:\n return true;\n }\n}\n\nconst readsRow = (operand: PolicyOperand): boolean =>\n operand.kind === \"field\" || operand.kind === \"outerField\";\n\nconst callsHelper = (operand: PolicyOperand): boolean =>\n operand.kind === \"authUid\" || operand.kind === \"authRoles\" || operand.kind === \"authClaim\";\n\n/** Whether `expr` calls one of the `rebase.*` helpers anywhere. */\nfunction callsAuthHelper(expr: PolicyExpression): boolean {\n switch (expr.kind) {\n case \"and\":\n case \"or\":\n return expr.operands.some(callsAuthHelper);\n case \"not\":\n return callsAuthHelper(expr.operand);\n case \"compare\":\n return callsHelper(expr.left) || callsHelper(expr.right);\n case \"rolesOverlap\":\n case \"rolesContain\":\n case \"authenticated\":\n case \"registered\":\n case \"serverContext\":\n return true;\n default:\n return false;\n }\n}\n\n/**\n * Whether `expr` is compiled as one `(SELECT …)`: it reads no row and calls a\n * helper (a constant has nothing to save).\n *\n * `authenticated()` and `registered()` on their own are the exception: they\n * wrap each helper call instead — `(SELECT rebase.uid()) IS NOT NULL AND …`.\n * Their estimate is already near 100%, so there is no plan to fix, and the\n * per-call spelling is the one RLS linters can still read: `rls-check` flags a\n * policy that is nothing but \"signed in\" (every account reads every row) by\n * splitting it on AND, and it reads `( SELECT rebase.uid() AS uid)` as the\n * caller id — but a whole conjunction inside one subquery is opaque to it.\n * Inside a larger hoisted subtree they are emitted bare, like everything else\n * there.\n */\nfunction isHoistable(expr: PolicyExpression): boolean {\n if (expr.kind === \"authenticated\" || expr.kind === \"registered\") return false;\n return readsNoRow(expr) && callsAuthHelper(expr);\n}\n\n/** A helper call, as an initPlan unless it already sits inside one. */\nfunction helperSql(sqlText: string, scope: CompileScope): string {\n return scope.inInitPlan ? sqlText : `(SELECT ${sqlText})`;\n}\n\nfunction compile(expr: PolicyExpression, scope: CompileScope): string {\n if (!scope.inInitPlan && isHoistable(expr)) {\n return `(SELECT ${compile(expr, { ...scope, inInitPlan: true })})`;\n }\n switch (expr.kind) {\n case \"true\":\n return \"true\";\n case \"false\":\n return \"false\";\n case \"and\":\n return expr.operands.length === 0\n ? \"true\"\n : expr.operands.map(o => `(${compile(o, scope)})`).join(\" AND \");\n case \"or\":\n return expr.operands.length === 0\n ? \"false\"\n : expr.operands.map(o => `(${compile(o, scope)})`).join(\" OR \");\n case \"not\":\n return `NOT (${compile(expr.operand, scope)})`;\n case \"compare\": {\n // `rebase.uid()` returns text; cast the column side so uuid / integer\n // id columns compare cleanly instead of failing with\n // \"operator does not exist: uuid = text\" at CREATE POLICY time.\n const castForAuthUid = (operand: PolicyOperand, sqlText: string, other: PolicyOperand): string =>\n other.kind === \"authUid\" && (operand.kind === \"field\" || operand.kind === \"outerField\")\n ? `(${sqlText})::text`\n : sqlText;\n // A claim is text too, and the same mismatch applies — but here the\n // cast goes the OTHER way, onto the claim. Casting the column would\n // compile and would take the index off it, and this operand exists\n // to carry a tenancy predicate that is ANDed into every read of the\n // table. See {@link claimCastType}.\n const claimSql = (operand: PolicyOperand, other: PolicyOperand): string | undefined =>\n operand.kind === \"authClaim\"\n ? helperSql(authClaimSql(operand.name, claimCastType(other, scope)), scope)\n : undefined;\n const leftSql = claimSql(expr.left, expr.right)\n ?? castForAuthUid(expr.left, operandToSql(expr.left, scope), expr.right);\n const rightSql = claimSql(expr.right, expr.left)\n ?? castForAuthUid(expr.right, operandToSql(expr.right, scope), expr.left);\n return `${leftSql} ${COMPARE_SQL[expr.op]} ${rightSql}`;\n }\n case \"rolesOverlap\":\n return `string_to_array(${RLS_ROLES_SQL}, ',') && ${rolesArraySql(expr.roles)}`;\n case \"rolesContain\":\n return `string_to_array(${RLS_ROLES_SQL}, ',') @> ${rolesArraySql(expr.roles)}`;\n case \"authenticated\":\n // `IS NOT NULL` alone is a tautology on the user path: every\n // user-context request sets `app.uid`, and an anonymous one sets\n // it to a sentinel. Excluding the sentinels is what makes this mean\n // \"signed in\" rather than \"anyone at all\".\n //\n // Every sentinel, not just the current one. This clause is written\n // into the database and outlives the server that generated it: a\n // policy compiled here may be enforced against an older server that\n // still reports `'anon'`, which is exactly how excluding one\n // spelling turned this helper into a grant. See ANONYMOUS_USER_IDS.\n return `${helperSql(RLS_UID_SQL, scope)} IS NOT NULL`\n + ` AND ${helperSql(RLS_UID_SQL, scope)} NOT IN (${ANONYMOUS_USER_IDS.map(quoteLiteral).join(\", \")})`;\n case \"registered\":\n // \"Signed in\" AND \"not a guest\". The first half is the same clause\n // `authenticated` compiles to; the second is the fact anonymous\n // sign-in used not to put anywhere the database could see, so a\n // guest and an account were one principal inside every policy.\n //\n // `rebase.is_anonymous()` defaults to false when its GUC is unset,\n // so a policy compiled here and enforced by an older server reads\n // every session as an account — which is the behaviour that\n // deployment already had, rather than a lockout.\n return `${helperSql(RLS_UID_SQL, scope)} IS NOT NULL`\n + ` AND ${helperSql(RLS_UID_SQL, scope)} NOT IN (${ANONYMOUS_USER_IDS.map(quoteLiteral).join(\", \")})`\n + ` AND NOT ${helperSql(RLS_IS_ANONYMOUS_SQL, scope)}`;\n case \"serverContext\":\n // Only the built-in server flows leave `app.uid` unset.\n return `${RLS_UID_SQL} IS NULL`;\n case \"existsIn\":\n return compileExistsIn(expr, scope);\n case \"raw\": {\n // A project written against a pre-1.0 release may still spell the\n // helpers `auth.uid()`. Rewritten rather than rejected: the rule\n // means exactly the same thing, the developer cannot be expected to\n // have read a changelog mid-deploy, and the alternative is a policy\n // that compiles cleanly and then denies every row at runtime because\n // it calls a function that no longer exists.\n //\n // The counterpart is `warnOnLegacyRlsFunctions`, which says so once\n // at boot with the file to edit — silence here would leave the old\n // spelling working forever and make the migration permanent.\n const sqlText = rewriteLegacyRlsFunctions(expr.sql);\n\n // Full-power escape hatch: `{column}` denotes a column of the outer\n // RLS row. It must be table-qualified, not bare: raw SQL may open its\n // own subquery over the same table, and there a bare name binds to the\n // inner scope, collapsing `m.x = {x}` into the tautology `m.x = m.x`.\n return substituteRawPlaceholders(sqlText, (col) =>\n `${outerQualifier(scope)}${resolveColumnName(col, scope.outerTable)}`);\n }\n }\n}\n\n/**\n * Replace each `{column}` placeholder in raw SQL with `replace(column)`, but\n * only in the SQL itself: not inside a string literal (`'…'`, `E'…'` with its\n * backslash escapes, `$$…$$`, `$tag$…$tag$`), a quoted identifier (`\"…\"`) or a\n * comment (`--` to the end of the line, or a block comment, which nests).\n *\n * A placeholder inside a literal is never meant: it would put the column's\n * *name* into the text. A regex quantifier is, and it has the same shape. A\n * stored claim-tenancy policy on a uuid column guards its cast with\n * `'^[0-9a-fA-F]{8}-…{12}$'`, so imported through \"Import from table\" or the\n * Studio's \"Import to codebase\" (which keep it as `raw`), its `{8}` became\n * `\"public\".\"projects\".\"8\"`, the guard never matched, and the policy denied\n * every tenant.\n */\nfunction substituteRawPlaceholders(sql: string, replace: (column: string) => string): string {\n let out = \"\";\n let i = 0;\n while (i < sql.length) {\n const c = sql[i];\n let end = i + 1;\n if (c === \"'\") {\n end = skipQuoted(sql, i, \"'\", isEscapeStringPrefix(sql, i));\n } else if (c === \"\\\"\") {\n end = skipQuoted(sql, i, \"\\\"\", false);\n } else if (c === \"-\" && sql[i + 1] === \"-\") {\n const newline = sql.indexOf(\"\\n\", i);\n if (newline === -1) {\n // A line comment ends at a newline and nowhere else, and this\n // text is spliced into `USING (…)` and between the operands of\n // an AND / OR: unterminated, the comment swallows the closing\n // paren and whatever follows it, and `CREATE POLICY` fails.\n out += `${sql.slice(i)}\\n`;\n break;\n }\n end = newline;\n } else if (c === \"/\" && sql[i + 1] === \"*\") {\n end = skipBlockComment(sql, i);\n } else if (c === \"$\") {\n const tag = dollarQuoteTagAt(sql, i);\n if (tag) {\n const close = sql.indexOf(tag, i + tag.length);\n end = close === -1 ? sql.length : close + tag.length;\n }\n } else if (c === \"{\") {\n const placeholder = /^\\{(\\w+)\\}/.exec(sql.slice(i));\n if (placeholder) {\n out += replace(placeholder[1]);\n i += placeholder[0].length;\n continue;\n }\n }\n out += sql.slice(i, end);\n i = end;\n }\n return out;\n}\n\n/** A character that continues an identifier, `$` included (`a$b` is one name). */\nconst IDENTIFIER_CHAR = /[A-Za-z0-9_$\\u0080-\\uffff]/;\n\n/** The end of the `quote`-quoted span opening at `start`; a doubled quote stays inside. */\nfunction skipQuoted(sql: string, start: number, quote: string, backslashEscapes: boolean): number {\n let i = start + 1;\n while (i < sql.length) {\n if (backslashEscapes && sql[i] === \"\\\\\") {\n i += 2;\n } else if (sql[i] === quote) {\n if (sql[i + 1] !== quote) return i + 1;\n i += 2;\n } else {\n i++;\n }\n }\n return sql.length;\n}\n\n/** Whether the `'` at `quote` opens an `E'…'` string, where `\\'` escapes a quote. */\nfunction isEscapeStringPrefix(sql: string, quote: number): boolean {\n const prefix = sql[quote - 1];\n return (prefix === \"E\" || prefix === \"e\") && !IDENTIFIER_CHAR.test(sql[quote - 2] ?? \"\");\n}\n\n/** The end of the block comment opening at `start`. Postgres nests them. */\nfunction skipBlockComment(sql: string, start: number): number {\n let depth = 0;\n let i = start;\n while (i < sql.length) {\n if (sql[i] === \"/\" && sql[i + 1] === \"*\") {\n depth++;\n i += 2;\n } else if (sql[i] === \"*\" && sql[i + 1] === \"/\") {\n depth--;\n i += 2;\n if (depth === 0) return i;\n } else {\n i++;\n }\n }\n return sql.length;\n}\n\n/**\n * The dollar-quote tag (`$$`, `$tag$`) opening at `at`, or undefined. Not one\n * after an identifier character (`a$b$` is a name), nor `$1` (a parameter: a\n * tag cannot start with a digit).\n */\nfunction dollarQuoteTagAt(sql: string, at: number): string | undefined {\n if (at > 0 && IDENTIFIER_CHAR.test(sql[at - 1])) return undefined;\n return /^\\$(?:[A-Za-z_\\u0080-\\uffff][A-Za-z0-9_\\u0080-\\uffff]*)?\\$/.exec(sql.slice(at))?.[0];\n}\n\n/**\n * Compiles `existsIn` to a correlated `EXISTS (SELECT 1 FROM <join> WHERE ...)`.\n * Inside the subquery, `field` operands bind to the aliased join table and\n * `outerField` operands bind to the (table-qualified) outer RLS row.\n */\nfunction compileExistsIn(expr: ExistsInPolicyExpression, scope: CompileScope): string {\n const join = scope.resolveTable?.(expr.table);\n const joinTable = join ? join.table : toSnakeCase(expr.table);\n const joinSchema = join?.schema ?? scope.outerTable?.schema ?? \"public\";\n const alias = `_ex${scope.alias.n++}`;\n\n // `outerField` inside the subquery must be qualified with the outer table,\n // otherwise a bare column name would bind to the joined table instead.\n const outerPrefix = outerQualifier(scope);\n\n const innerScope: CompileScope = {\n fieldTable: join,\n fieldPrefix: `\"${alias}\".`,\n outerTable: scope.outerTable,\n outerPrefix,\n resolveTable: scope.resolveTable,\n alias: scope.alias,\n inInitPlan: scope.inInitPlan\n };\n return `EXISTS (SELECT 1 FROM \"${joinSchema}\".\"${joinTable}\" \"${alias}\" WHERE ${compile(expr.where, innerScope)})`;\n}\n\nconst COMPARE_SQL: Record<PolicyCompareOperator, string> = {\n eq: \"=\",\n neq: \"!=\",\n lt: \"<\",\n lte: \"<=\",\n gt: \">\",\n gte: \">=\"\n};\n\nfunction operandToSql(operand: PolicyOperand, scope: CompileScope): string {\n switch (operand.kind) {\n case \"field\":\n return `${scope.fieldPrefix}${resolveColumnName(operand.name, scope.fieldTable)}`;\n case \"outerField\":\n return `${scope.outerPrefix}${resolveColumnName(operand.name, scope.outerTable)}`;\n case \"literal\":\n return quoteLiteral(operand.value);\n case \"authUid\":\n return helperSql(RLS_UID_SQL, scope);\n case \"authRoles\":\n return helperSql(`string_to_array(${RLS_ROLES_SQL}, ',')`, scope);\n case \"authClaim\":\n // Uncast — the shape a claim has when nothing says what it is being\n // compared against (a claim on both sides, or against a literal).\n // The `compare` arm replaces this whenever the other operand names\n // a typed column.\n return helperSql(authClaimSql(operand.name, \"text\"), scope);\n }\n}\n\n/**\n * The Postgres type a claim has to be cast to, to be compared with `operand`.\n *\n * `\"text\"` means \"no cast\": a claim already is text, and a `text` / `varchar`\n * column compares with it directly and keeps using its index.\n *\n * Read from the column the operand names — a `belongsTo` link's foreign key\n * column has the target's key type, which is the ordinary shape of a tenant\n * field. Unknown resolves to `\"text\"`, which is the safe direction: a\n * redundant `text` comparison costs nothing, while a missing `uuid` cast is a\n * `CREATE POLICY` that fails and leaves a table with RLS enabled and no\n * policy — which denies every row.\n */\nfunction claimCastType(operand: PolicyOperand, scope: CompileScope): ClaimCastType {\n if (operand.kind !== \"field\" && operand.kind !== \"outerField\") return \"text\";\n const table = operand.kind === \"field\" ? scope.fieldTable : scope.outerTable;\n return columnOf(operand.name, table)?.claimCast ?? \"text\";\n}\n\n/**\n * `NULLIF(rebase.jwt() ->> 'name', '')`, cast to the column's type.\n *\n * Two things here are load-bearing beyond the cast:\n *\n * - **`NULLIF(…, '')`.** An absent claim already reads as NULL, but one set to\n * the empty string does not, and `''::uuid` raises rather than denying. Both\n * spellings of \"this caller has no tenant\" have to reach the comparison as\n * NULL, which is never true and therefore never a grant.\n * - **The guard.** The cast sits inside a `CASE` that first checks the text is\n * well-formed, because `'nonsense'::uuid` raises `invalid input syntax` — and\n * a policy that raises does not deny a row, it fails the whole statement. A\n * caller holding a malformed claim would get a 500 on every read of the table\n * instead of an empty list. `CASE` rather than an `AND` guard because only\n * `CASE` is guaranteed not to evaluate its arms out of order.\n *\n * The whole expression is STABLE (`rebase.jwt()` is), so Postgres evaluates it\n * once per query and can still use a btree index on the column it is compared\n * against — which is the entire reason the cast is on this side.\n */\nfunction authClaimSql(name: string, cast: ClaimCastType): string {\n const claim = `NULLIF(${RLS_JWT_SQL} ->> ${quoteLiteral(name)}, '')`;\n if (cast === \"text\") return claim;\n return `CASE WHEN ${claim} ~ '${CLAIM_CAST_GUARDS[cast]}' THEN (${claim})::${cast} END`;\n}\n\n/**\n * The text a claim must match before it is cast, per target type.\n *\n * The `bigint` guard caps the digit run at 18 rather than matching any run of\n * digits: `'99999999999999999999'::bigint` is a range error, which fails the\n * statement exactly as the syntax error would have.\n */\nconst CLAIM_CAST_GUARDS: Record<Exclude<ClaimCastType, \"text\">, string> = {\n uuid: \"^[0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12}$\",\n bigint: \"^-?[0-9]{1,18}$\",\n numeric: \"^-?[0-9]+(\\\\.[0-9]+)?$\"\n};\n\n/**\n * SQL prefix that qualifies a column of the outer RLS row (`\"schema\".\"table\".`),\n * or `\"\"` when the table is unknown.\n */\nfunction outerQualifier(scope: CompileScope): string {\n const table = scope.outerTable?.table;\n if (!table) return \"\";\n return `\"${scope.outerTable?.schema ?? \"public\"}\".\"${table}\".`;\n}\n\n/**\n * The column a rule's key names: a column key, or a `belongsTo` link, which\n * addresses its foreign key column — `org` compares `org_id`. A rule naming a\n * relation (`ownerField: \"org\"`, a tenancy declaration over a `belongsTo`)\n * once compiled to a column called `org`, which does not exist; `CREATE\n * POLICY` then failed and the table denied every row.\n */\nfunction columnOf(key: string, table: PolicyTable | undefined): PolicyColumn | undefined {\n if (!table) return undefined;\n if (Object.prototype.hasOwnProperty.call(table.columns, key)) return table.columns[key];\n if (Object.prototype.hasOwnProperty.call(table.links, key)) return table.links[key];\n return undefined;\n}\n\nfunction resolveColumnName(key: string, table?: PolicyTable): string {\n return quoteColumnIdentifier(columnOf(key, table)?.column ?? toSnakeCase(key));\n}\n\n/**\n * Every PostgreSQL keyword that cannot stand as a bare column reference.\n * Appendix C's two reserved categories — plain \"reserved\", and \"reserved (can\n * be function or type name)\" — since neither may name a column unquoted.\n */\nconst RESERVED_SQL_WORDS = new Set([\n \"all\", \"analyse\", \"analyze\", \"and\", \"any\", \"array\", \"as\", \"asc\", \"asymmetric\", \"authorization\",\n \"binary\", \"both\", \"case\", \"cast\", \"check\", \"collate\", \"collation\", \"column\", \"concurrently\",\n \"constraint\", \"create\", \"cross\", \"current_catalog\", \"current_date\", \"current_role\",\n \"current_schema\", \"current_time\", \"current_timestamp\", \"current_user\", \"default\", \"deferrable\",\n \"desc\", \"distinct\", \"do\", \"else\", \"end\", \"except\", \"false\", \"fetch\", \"for\", \"foreign\", \"freeze\",\n \"from\", \"full\", \"grant\", \"group\", \"having\", \"ilike\", \"in\", \"initially\", \"inner\", \"intersect\",\n \"into\", \"is\", \"isnull\", \"join\", \"lateral\", \"leading\", \"left\", \"like\", \"limit\", \"localtime\",\n \"localtimestamp\", \"natural\", \"not\", \"notnull\", \"null\", \"offset\", \"on\", \"only\", \"or\", \"order\",\n \"outer\", \"overlaps\", \"placing\", \"primary\", \"references\", \"returning\", \"right\", \"select\",\n \"session_user\", \"similar\", \"some\", \"symmetric\", \"system_user\", \"table\", \"tablesample\", \"then\",\n \"to\", \"trailing\", \"true\", \"union\", \"unique\", \"user\", \"using\", \"variadic\", \"verbose\", \"when\",\n \"where\", \"window\", \"with\"\n]);\n\n/** An identifier Postgres reads back unchanged without quotes. */\nconst BARE_IDENTIFIER = /^[a-z_][a-z0-9_$]*$/;\n\n/**\n * Quote a column reference when Postgres would not read the bare name as that\n * column — and only then.\n *\n * Three ways a bare name goes wrong, in ascending order of how long it takes to\n * notice:\n *\n * - **Case.** `columnName` is used verbatim, and `rebase schema introspect`\n * populates it from a live database, so a legacy `\"createdAt\"` column arrives\n * spelled exactly that way. Unquoted, Postgres folds it to `createdat` and\n * `CREATE POLICY` fails with \"column does not exist\" — the collection keeps\n * RLS enabled with no policy, which denies every row.\n * - **Syntax.** A column named `order` or `default` is a syntax error mid-clause.\n * - **Silent rebinding.** `user`, `current_user`, `session_user`, `current_date`\n * and friends are *valid bare expressions*, so the policy compiles, applies,\n * and is reported as a success — while comparing against the connected role\n * or the wall clock instead of the column. Under RLS every request runs as the\n * same `rebase_user` role, so `USING (user = rebase.uid())` is a constant: it\n * denies everything, and its negation admits everything.\n *\n * Only the names that need it are quoted, so an ordinary snake_case policy body\n * is emitted byte-for-byte as before. That keeps generated artifacts and the\n * policies already stored in shipped databases stable — this fix reaches the\n * clauses that were broken and no others.\n */\nfunction quoteColumnIdentifier(name: string): string {\n if (BARE_IDENTIFIER.test(name) && !RESERVED_SQL_WORDS.has(name)) return name;\n return `\"${name.replace(/\"/g, \"\\\"\\\"\")}\"`;\n}\n\nfunction quoteLiteral(value: string | number | boolean | null): string {\n if (value === null) return \"NULL\";\n if (typeof value === \"boolean\") return value ? \"true\" : \"false\";\n if (typeof value === \"number\") return String(value);\n return `'${value.replace(/'/g, \"''\")}'`;\n}\n\n/**\n * Sorted, single-quoted `ARRAY['a','b']` — matches the generators' output.\n *\n * Each role goes through {@link quoteLiteral}, which leaves an ordinary name\n * byte-for-byte as it is and doubles a quote inside one (`o'reilly`). An\n * unescaped quote would close the literal early: a syntax error at\n * `CREATE POLICY`, which leaves the table with RLS on and no policy, or — for a\n * name built to do it — SQL of its own in the clause.\n */\nfunction rolesArraySql(roles: readonly string[]): string {\n // An empty `ARRAY[]` has no element type, and Postgres refuses it (\"cannot\n // determine type of empty array\"): the whole `CREATE POLICY` fails, taking\n // the rest of the rule's condition with it. Typed, it means what the\n // evaluator says — overlapping no role is false, containing none is true.\n if (roles.length === 0) return \"ARRAY[]::text[]\";\n return `ARRAY[${[...roles].sort().map(quoteLiteral).join(\",\")}]`;\n}\n","import { declaredRlsPolicyShape, isRedactedSecurityRule, DEFAULT_DATA_SOURCE_KEY, REBASE_ADMIN_REQUEST_ROLE, REBASE_ADMIN_ROLE, RLS_IS_REQUEST_ROLE_SQL, type PolicyExpression, type SecurityOperation, type SecurityRule } from \"@rebasepro/types\";\nimport { adminRequestPolicyName, getPolicyNamesForRule } from \"@rebasepro/utils\";\nimport { securityRuleToConditions } from \"./securityRuleToConditions\";\nimport { policyShorthandColumns } from \"./policyCondition\";\nimport { compilePolicyExpression, type PolicyCompileOptions } from \"./policyToPostgres\";\nimport type { PolicyTable } from \"./policy-table\";\n\n/**\n * One Postgres policy a security rule compiles to: its name and the clauses\n * `CREATE POLICY` is given for it.\n */\nexport interface CompiledRulePolicy {\n name: string;\n operation: SecurityOperation;\n /** `permissive` | `restrictive`, lower-case as the rule spells it. */\n mode: \"permissive\" | \"restrictive\";\n /** The `TO` list. Sorted, `[\"public\"]` when the rule names none. */\n roles: string[];\n /** The `USING` clause, or `null` when the operation takes none. */\n using: string | null;\n /** The `WITH CHECK` clause, or `null` when the operation takes none. */\n withCheck: string | null;\n /**\n * Set when `roles` is `[\"rebase_admin\"]` because the compiler put it there\n * (`adminPolicies: \"adminRole\"`), not because the rule named it — so a\n * database where that role cannot exist may write this policy `TO public`,\n * which is exactly what it was before, and never widen a rule's own list.\n */\n adminTarget?: true;\n /**\n * Set on the companion of an admin-only policy: the same operation, `TO`\n * `rebase_admin_request`, `USING (true)` — so an admin request's plan\n * carries no policy barrier and uses the indexes the owner's does (see\n * `REBASE_ADMIN_REQUEST_ROLE`). Never written to any other role: where\n * that role cannot exist the companion is left out, never moved `TO\n * public` the way an {@link adminTarget} policy is — `TO public USING\n * (true)` would hand every row to everyone.\n */\n adminRequestTarget?: true;\n}\n\n/** The switches {@link compileTableRulePolicies} reads. */\nexport interface RulePolicySwitches {\n /**\n * The caller runs admin requests as a role inside `rebase_admin` (the\n * Postgres driver from the release that introduced `rls.adminPolicies`), so\n * a server-or-admin grant may be written `TO rebase_admin` when the\n * declaration allows it. Off by default, and that is load-bearing: the\n * managed runtime supplies this package to bundles that vendor an older\n * driver, which never switches admins to such a role — compiled `TO\n * rebase_admin` under it, every admin request would be refused.\n */\n adminRole?: boolean;\n /**\n * Give each admin-only policy its `TO rebase_admin_request USING (true)`\n * companion ({@link CompiledRulePolicy.adminRequestTarget}). Only with\n * {@link adminRole}, and off by default for the same reason: a driver that\n * does not create that role must not be handed policies naming it.\n */\n adminRequestRole?: boolean;\n}\n\n/** Options for {@link compileTableRulePolicies}. */\nexport interface RulePolicyCompileOptions extends PolicyCompileOptions, RulePolicySwitches {}\n\n/**\n * The policies one security rule compiles to — one per operation.\n *\n * The schema planner writes these into the database, and the Studio's RLS\n * editor compares the database against them; both call this, so \"what the code\n * declares\" has one meaning.\n *\n * The desugaring (`access` / `ownerField` / `roles` / structured condition /\n * raw SQL → `PolicyExpression`) is {@link securityRuleToConditions}, and the SQL\n * is {@link compilePolicyExpression}. What lives here is only the shape: which\n * operations a rule expands to, which clauses each operation takes, and the\n * deny-all fallback for a clause that compiled to nothing.\n */\nexport function compileTableRulePolicies(\n table: PolicyTable,\n rule: SecurityRule,\n options?: RulePolicyCompileOptions\n): CompiledRulePolicy[] {\n const ops = rule.operations && rule.operations.length > 0 ? rule.operations : [rule.operation ?? \"all\"];\n const tableName = table.table;\n if (isRedactedSecurityRule(rule)) {\n // The marker stands for SQL this process was not shown. A policy\n // compiled from it would grant or deny by a guess.\n throw new Error(\n `A rule on \"${tableName}\" is the \\`redacted: true\\` marker \\`GET /api/schema/tables\\` serves in place of ` +\n \"a rule whose SQL it withheld. It describes a policy; it cannot become one. Write the rule itself.\"\n );\n }\n assertShorthandColumns(table, rule);\n const policyNames = getPolicyNamesForRule(rule, tableName);\n const { usingExpr, withCheckExpr } = securityRuleToConditions(rule, { table: tableName });\n const mode = rule.mode ?? \"permissive\";\n // `rls.policyTarget: \"requestRole\"`: a grant is for the request roles only.\n // In the compiler, not on the rule, because a policy's name hashes the rule\n // — narrowing it there would rename every policy in every database. Never on\n // a restrictive policy: it can only take access away, from everyone.\n const shape = declaredRlsPolicyShape(table.database ?? DEFAULT_DATA_SOURCE_KEY);\n const narrowed = mode === \"permissive\" && shape.policyTarget === \"requestRole\";\n const forRequestRoles = (clause: string): string => narrowed ? `(${clause}) AND ${RLS_IS_REQUEST_ROLE_SQL}` : clause;\n // A grant only the server context or an admin can pass goes `TO\n // rebase_admin`, so it is not ORed into a signed-in user's plan, where it\n // costs the owner index (see `REBASE_ADMIN_ROLE`). In the compiler for the\n // reason above: the rule, and so the policy's name, stays as written. Never\n // for a rule naming its own `pgRoles`, and never for a restrictive policy —\n // narrowing whom a restriction applies to would widen everyone else.\n const adminOnly = mode === \"permissive\" && !rule.pgRoles && options?.adminRole === true\n && shape.adminPolicies === \"adminRole\";\n\n return ops.flatMap((operation, index): CompiledRulePolicy[] => {\n const needsUsing = operation !== \"insert\";\n const needsWithCheck = operation !== \"select\" && operation !== \"delete\";\n const forAdmins = adminOnly\n && (!needsUsing || requiresServerOrAdmin(usingExpr))\n && (!needsWithCheck || requiresServerOrAdmin(withCheckExpr));\n let using = needsUsing && usingExpr ? compilePolicyExpression(usingExpr, table, options) : null;\n let withCheck = needsWithCheck && withCheckExpr ? compilePolicyExpression(withCheckExpr, table, options) : null;\n // A clause that compiled to nothing denies rather than opens.\n if (!using && needsUsing) using = \"false\";\n if (!withCheck && needsWithCheck) withCheck = \"false\";\n const policy: CompiledRulePolicy = {\n name: policyNames[index],\n operation,\n mode,\n roles: rule.pgRoles ? [...rule.pgRoles].sort() : [forAdmins ? REBASE_ADMIN_ROLE : \"public\"],\n ...(forAdmins ? { adminTarget: true as const } : {}),\n using: using === null ? null : forRequestRoles(using),\n withCheck: withCheck === null ? null : forRequestRoles(withCheck)\n };\n // Only where every admin request passes the policy anyway — a request\n // runs as an admin request role only because its caller holds `admin`\n // — does the companion admit them outright, as a constant Postgres\n // folds away. `admin AND owner = me` is admin-only too, and gets none:\n // `true` would widen it. Not narrowed to the request roles: it already\n // applies to nothing else, and a non-constant clause would bring the\n // barrier back.\n const everyAdminPasses = forAdmins\n && (!needsUsing || admitsEveryAdminRequest(usingExpr))\n && (!needsWithCheck || admitsEveryAdminRequest(withCheckExpr));\n if (!everyAdminPasses || options?.adminRequestRole !== true) return [policy];\n return [policy, {\n name: adminRequestPolicyName(policyNames[index]),\n operation,\n mode: \"permissive\",\n roles: [REBASE_ADMIN_REQUEST_ROLE],\n adminRequestTarget: true,\n using: needsUsing ? \"true\" : null,\n withCheck: needsWithCheck ? \"true\" : null\n }];\n });\n}\n\n/**\n * Refuse a `PolicyShorthand` condition / check naming a key that is no column\n * of the table — no column key, and no `belongsTo` relation (which addresses\n * its foreign-key column). The compiler snake-cases a name it does not know,\n * so a typo would otherwise reach `CREATE POLICY` as a column that does not\n * exist, fail there, and leave the table with RLS on and no policy.\n */\nfunction assertShorthandColumns(table: PolicyTable, rule: SecurityRule): void {\n const clauses = [[\"condition\", rule.condition], [\"check\", rule.check]] as const;\n for (const [clause, condition] of clauses) {\n for (const column of policyShorthandColumns(condition)) {\n if (Object.prototype.hasOwnProperty.call(table.columns, column)) continue;\n if (Object.prototype.hasOwnProperty.call(table.links, column)) continue;\n const keys = [...Object.keys(table.columns), ...Object.keys(table.links)];\n throw new Error(\n `A rule on \"${table.table}\" names \"${column}\" in its \\`${clause}\\`, and \"${table.table}\" has no such ` +\n \"column. A shorthand's keys are column keys of the table: name one of \" +\n `${keys.map(k => `\"${k}\"`).join(\", \") || \"its columns\"}.`\n );\n }\n }\n}\n\n/**\n * Whether a clause is true for every request made by a caller holding the\n * `admin` role, whoever they are and whatever row: the companion test\n * (`adminRequestTarget`). Stricter than {@link requiresServerOrAdmin}, which\n * asks the opposite question: `admin AND owner = me` can only pass for an\n * admin, but not every admin passes it. Structural and conservative: anything\n * it cannot read answers `false`, and the policy gets no companion.\n */\nexport function admitsEveryAdminRequest(expr: PolicyExpression | null): boolean {\n if (!expr) return false;\n switch (expr.kind) {\n case \"rolesOverlap\":\n return expr.roles.includes(\"admin\");\n case \"rolesContain\":\n return expr.roles.length > 0 && expr.roles.every(role => role === \"admin\");\n case \"and\":\n return expr.operands.length > 0 && expr.operands.every(admitsEveryAdminRequest);\n case \"or\":\n return expr.operands.some(admitsEveryAdminRequest);\n default:\n return false;\n }\n}\n\n/**\n * Whether a clause can only be true for the server context or a caller holding\n * the `admin` role — so a policy made of such clauses loses nothing by applying\n * only to the roles those requests run as. Structural and conservative: raw\n * SQL, a role list naming anything but `admin`, or a clause that could pass for\n * someone else answers `false`, and the policy stays `TO public`.\n */\nexport function requiresServerOrAdmin(expr: PolicyExpression | null): boolean {\n if (!expr) return false;\n switch (expr.kind) {\n case \"serverContext\":\n return true;\n case \"rolesOverlap\":\n return expr.roles.length > 0 && expr.roles.every(role => role === \"admin\");\n case \"rolesContain\":\n return expr.roles.includes(\"admin\");\n case \"and\":\n return expr.operands.some(requiresServerOrAdmin);\n case \"or\":\n return expr.operands.length > 0 && expr.operands.every(requiresServerOrAdmin);\n default:\n return false;\n }\n}\n","import {\n isNumericColumnType,\n type ColumnType,\n type SecurityRule,\n type TableDescriptor,\n type TenantDescriptor\n} from \"@rebasepro/types\";\n\n/**\n * The Postgres type a text claim is cast to before it is compared with a\n * column. `\"text\"` is the no-cast case: a claim already is text, and a text\n * column compares with it directly and keeps using its index.\n *\n * @group Policies\n */\nexport type ClaimCastType = \"text\" | \"uuid\" | \"bigint\" | \"numeric\";\n\n/**\n * A column a rule can name: its SQL name, and the cast a claim compared with\n * it needs.\n *\n * @group Policies\n */\nexport interface PolicyColumn {\n /** The SQL column, unquoted. */\n column: string;\n /** What a text claim compared with the column is cast to. */\n claimCast: ClaimCastType;\n}\n\n/**\n * What the policy compiler reads of a table: the small view of a\n * `TableDescriptor` that rules compile against.\n *\n * A rule names a row by key (`ownerField: \"authorId\"`, `policy.field(\"org\")`);\n * the compiler needs that key's SQL column and the cast a claim compared with\n * it needs, the table's qualified name (for `outerField` inside an\n * `existsIn`), the rules and posture (for the injected baseline), and the\n * database the table lives in (whose declaration picks the policy shape).\n * Nothing else. Built from a descriptor by {@link policyTableFromDescriptor},\n * and for a junction by `junctionPolicyTable`.\n *\n * @group Policies\n */\nexport interface PolicyTable {\n /** The API slug: what `existsIn({ table })` and the junction rules name. */\n slug: string;\n /** The SQL table, unqualified. Policy names derive from it. */\n table: string;\n /**\n * The Postgres schema the table is declared in. Absent when it was not\n * stated (the table lives in `public`); an `existsIn` join into such a\n * table qualifies it with the outer table's schema.\n */\n schema?: string;\n /** The key of the database the table lives in, when not the default one. */\n database?: string;\n /** Every key a rule may name, by key: the table's columns. */\n columns: Readonly<Record<string, PolicyColumn>>;\n /**\n * The `belongsTo` relations, by relation name, each addressing its foreign\n * key column: `ownerField: \"org\"` compares `org_id`.\n */\n links: Readonly<Record<string, PolicyColumn>>;\n /** The key of the row id: the first primary-key column. */\n idKey: string;\n /** The declared rules, exactly as written (policy names hash them). */\n rules: readonly SecurityRule[];\n /**\n * `false` when the table switched the injected admin baseline off,\n * `true` when it switched it on regardless of its database's declaration,\n * absent when the database declaration (`rls.defaultPolicies`) decides.\n */\n defaultPolicies?: boolean;\n /** The auth table: gets the self-read rule and the admin write gate. */\n auth: boolean;\n /** Rows are scoped to a tenant. */\n tenant?: TenantDescriptor;\n}\n\n/**\n * Resolve a table by slug, for `existsIn` joins and relation targets.\n *\n * @group Policies\n */\nexport type ResolvePolicyTable = (slug: string) => PolicyTable | undefined;\n\n/**\n * What a claim compared with a column of `type` is cast to.\n *\n * `numeric` stays `numeric`; every other number type compares as `bigint`\n * (the guard caps the digits at 18). A uuid as `uuid`; everything else —\n * text, an enum, a date — as text, which is the safe direction: a redundant\n * text comparison costs nothing, while a missing cast is a `CREATE POLICY`\n * that fails and leaves the table with RLS on and no policy.\n *\n * @group Policies\n */\nexport function claimCastOf(type: ColumnType): ClaimCastType {\n if (type.kind === \"uuid\") return \"uuid\";\n if (type.kind === \"numeric\") return \"numeric\";\n if (isNumericColumnType(type)) return \"bigint\";\n return \"text\";\n}\n\n/**\n * The policy compiler's view of a compiled table.\n *\n * A `belongsTo` link addresses its foreign key column (`localKey`), cast as\n * that column is — its type is the target's key type, so no lookup through\n * the target is needed. The baseline follows the database's declaration unless\n * the table wrote `defaultPolicies` (`false` drops it, `true` keeps it). A view has no rules of its own\n * (`posture: \"view\"`), and gets none here.\n *\n * @group Policies\n */\nexport function policyTableFromDescriptor(descriptor: TableDescriptor): PolicyTable {\n const columns: Record<string, PolicyColumn> = {};\n for (const column of descriptor.columns) {\n columns[column.key] = { column: column.column, claimCast: claimCastOf(column.type) };\n }\n const links: Record<string, PolicyColumn> = {};\n for (const relation of descriptor.relations) {\n if (relation.kind !== \"belongsTo\") continue;\n links[relation.name] = {\n column: relation.localKey,\n claimCast: columns[relation.localField]?.claimCast ?? \"text\"\n };\n }\n return {\n slug: descriptor.slug,\n table: descriptor.table,\n // `public` is where an undeclared table lives; the compiler treats an\n // undeclared schema as \"the outer table's\" inside a join, so the\n // default is not spelled out.\n ...(descriptor.schema !== \"public\" ? { schema: descriptor.schema } : {}),\n ...(descriptor.database !== undefined ? { database: descriptor.database } : {}),\n columns,\n links,\n idKey: descriptor.primaryKey[0] ?? \"id\",\n rules: descriptor.rls.posture === \"rules\" ? descriptor.rls.rules : [],\n ...(descriptor.rls.posture === \"view\"\n ? { defaultPolicies: false }\n : !descriptor.rls.defaultPolicies ? { defaultPolicies: false }\n : descriptor.rls.declaredDefaultPolicies ? { defaultPolicies: true } : {}),\n auth: descriptor.auth !== undefined,\n ...(descriptor.tenant ? { tenant: descriptor.tenant } : {})\n };\n}\n\n/**\n * A resolver over compiled tables, by slug or SQL table name (an `existsIn`\n * may name either). Each table's view is built once.\n *\n * @group Policies\n */\nexport function policyTableResolver(descriptors: readonly TableDescriptor[]): ResolvePolicyTable {\n const cache = new Map<TableDescriptor, PolicyTable>();\n const view = (descriptor: TableDescriptor): PolicyTable => {\n let table = cache.get(descriptor);\n if (!table) {\n table = policyTableFromDescriptor(descriptor);\n cache.set(descriptor, table);\n }\n return table;\n };\n return (slug: string) => {\n const found = descriptors.find(d => d.slug === slug) ?? descriptors.find(d => d.table === slug);\n return found ? view(found) : undefined;\n };\n}\n","/**\n * The one reading of `collection.tenant`.\n *\n * Four things have to agree for a tenant-scoped collection to work — the\n * column, the RLS policy, the value stamped on insert and the index — and\n * before this they were four hand-written declarations that nothing compared.\n * The three that are schema become a {@link SecurityRule} and a column effect\n * derived here and in `planSchema`; the fourth, the write path, is\n * `resolveTenantWrite` (`runtime/tenant-write.ts`).\n *\n * Everything in this module is pure. The policy it builds is a `SecurityRule`\n * like any other, which is what makes `db push`, the doctor, boot-ensure, the\n * drift detector and the Studio treat the tenancy policy as what it is —\n * generated, named, and recognisable — rather than as somebody's hand-written\n * SQL that a push should offer to drop.\n */\nimport {\n DEFAULT_TENANT_BYPASS_ROLES,\n isTenantClaimSource,\n policy,\n type PolicyExpression,\n type SecurityRule,\n type TenantDescriptor\n} from \"@rebasepro/types\";\n\n/** The roles tenancy does not apply to, defaulted. */\nexport function tenantBypassRoles(tenant: Pick<TenantDescriptor, \"bypassRoles\">): readonly string[] {\n return tenant.bypassRoles ?? DEFAULT_TENANT_BYPASS_ROLES;\n}\n\n/**\n * The name of the policy a tenant declaration compiles to.\n *\n * Explicit — not a `getPolicyNameHash` of the rule — precisely because the\n * rule's *body* is compiled with more information in some callers than in\n * others (`planSchema` can resolve a relation's target collection and so knows\n * the column's type; the Studio, asking only for names, cannot). A hashed name\n * would then differ between the two, and the same policy would read as drift.\n * A frozen identifier: see `contracts/derived-names.txt`.\n */\nexport function tenantPolicyName(tableName: string): string {\n return `${tableName}_tenant_scope`;\n}\n\n/** The `reason` on the index a tenant column gets. Rendered into `schema.sql`. */\nexport const TENANT_INDEX_REASON = \"tenant scope\";\n\n/**\n * The condition a tenant declaration means, as a policy expression.\n *\n * `serverContext()` first, for the same reason every injected baseline rule\n * carries it: the trusted plane runs migrations, the auth flows and the boot,\n * and a restrictive policy that excluded it would not protect a tenant, it\n * would stop the server from starting.\n *\n * Then the bypass roles, then the tenancy test itself — a claim comparison or a\n * correlated `EXISTS` over the membership table, which are the two ways a\n * deployment answers \"which tenant is this caller in\".\n */\nexport function tenantScopeExpression(tenant: TenantDescriptor): PolicyExpression {\n const match: PolicyExpression = isTenantClaimSource(tenant.from)\n ? policy.compare(policy.field(tenant.field), \"eq\", policy.authClaim(tenant.from.claim))\n : policy.existsIn({\n table: tenant.from.membership.table,\n where: policy.and(\n policy.compare(\n policy.field(tenant.from.membership.tenantField),\n \"eq\",\n policy.outerField(tenant.field)\n ),\n policy.compare(\n policy.field(tenant.from.membership.userField),\n \"eq\",\n policy.authUid()\n )\n )\n });\n\n const bypass = tenantBypassRoles(tenant);\n return bypass.length > 0\n ? policy.or(policy.serverContext(), policy.rolesOverlap(bypass), match)\n : policy.or(policy.serverContext(), match);\n}\n\n/**\n * The rule a tenant declaration compiles to, or nothing when there is none.\n *\n * **Restrictive**, and that is the whole design. A restrictive policy is ANDed\n * with every other policy on the table, so tenancy narrows what the\n * collection's own `securityRules` allow and can never widen it. A permissive\n * one would OR with them, and a single `access: \"public\"` rule elsewhere in the\n * file would take the entire tenancy boundary off without contradicting\n * anything a reader could see.\n *\n * One rule with `operation: \"all\"` rather than four with `operations: [...]`:\n * `FOR ALL` gives Postgres the USING clause for SELECT/UPDATE/DELETE and the\n * WITH CHECK clause for INSERT/UPDATE, which is exactly the coverage wanted,\n * as one policy with one name instead of four.\n */\nexport function tenantSecurityRule(tableName: string, tenant: TenantDescriptor): SecurityRule {\n const expression = tenantScopeExpression(tenant);\n return {\n name: tenantPolicyName(tableName),\n mode: \"restrictive\",\n operation: \"all\",\n condition: expression,\n check: expression\n };\n}\n","import { SecurityRule, SecurityOperation, PolicyExpression, policy, declaredRlsPolicyShape, DEFAULT_DATA_SOURCE_KEY } from \"@rebasepro/types\";\nimport { tenantSecurityRule } from \"./tenant\";\nimport { getPolicyNamesForRules } from \"@rebasepro/utils\";\nimport type { PolicyTable } from \"./policy/policy-table\";\n\n/**\n * Default RLS policies injected by the schema generator.\n *\n * Rebase's enforcement model is unified: authenticated (user-context) requests\n * run under the restricted `rebase_user` role, so Postgres RLS binds *every*\n * statement — reads and writes. A collection's `securityRules` are the whole\n * authorization model. The server context (auth flows, migrations, raw\n * `rebase.sql`) runs as the owner and bypasses RLS.\n *\n * `rebase.dataAsAdmin` is **not** in that set, despite the name: it is scoped as\n * `{ uid: \"service\", roles: [\"admin\"] }`, so it runs as `rebase_user` like any\n * other caller and clears the baseline below through the *admin* arm, not the\n * server arm. Which is why `disableDefaultPolicies` plus a lone\n * `policy.serverContext()` rule locks it out too.\n *\n * Because RLS default-denies, every collection is **locked by default**: with\n * no rules, only the server context and admins can touch it. The generator\n * injects that safe baseline:\n *\n * **For every collection**\n * 1. A permissive **server-or-admin SELECT** grant.\n * 2. A permissive **server-or-admin write** grant (insert/update/delete).\n *\n * Author `securityRules` are permissive and OR together, so explicit rules only\n * *broaden* access from this locked baseline (e.g. \"users read/write their own\n * rows\").\n *\n * **For auth collections additionally**\n * 3. A permissive **self SELECT** grant (`id = rebase.uid()`), so users can read\n * their own row (profile, session bootstrap) without every app re-declaring\n * it.\n * 4. A **restrictive** admin write gate. Restrictive policies are AND'd with\n * every other policy, so a write is rejected unless the caller is an admin\n * (or the server context) — even if the author also wrote a permissive rule\n * such as \"a user may edit their own row\". Without this, a permissive owner\n * rule would let a user change their own `roles`.\n *\n * The server context is recognised as `rebase.uid() IS NULL` (`policy.serverContext()`)\n * — the built-in flows that run without a user (signup, migrations) set no user\n * GUC — which also lets the owner connection satisfy these policies even under\n * FORCE RLS. A *user* request never reaches that state: an anonymous one carries\n * `ANONYMOUS_USER_ID`, precisely so it cannot pass for the server here.\n *\n * **For a collection declaring `tenant`, additionally**\n * 5. A **restrictive** tenancy gate for every operation. Same kind of thing as\n * the admin write gate and injected for the same reason: it is ANDed with\n * every other policy, so it narrows what the author's permissive rules\n * grant and can never widen them. See `./tenant.ts`.\n *\n * Opt out with `disableDefaultPolicies: true` to take full responsibility for\n * the collection's RLS. The *restrictive* rules are not part of that opt-out:\n * dropping a rule that can only remove access could express nothing but \"let\n * more people in\", which is what the flag already does by removing the grants.\n */\n// Expressed structurally (not as raw SQL) so the admin UI can evaluate it\n// exactly — the framework's most security-critical policies must be reflected\n// precisely, not left as un-evaluable raw clauses. Compiles to\n// `rebase.uid() IS NULL OR (string_to_array(rebase.roles(), ',') && ARRAY['admin'])`.\n//\n// `serverContext()`, emphatically not `not(authenticated())`: the server arm of\n// this grant must match the server context and nothing else. Anonymous visitors\n// are not signed in either, so a negated `authenticated()` would hand them the\n// server-or-admin grant on every collection's default policy.\nconst SERVER_OR_ADMIN_EXPR: PolicyExpression = policy.or(\n policy.serverContext(),\n policy.rolesOverlap([\"admin\"])\n);\n\n/** Write operations that must be admin-gated by default on auth collections. */\nconst DEFAULT_GUARDED_OPS: SecurityOperation[] = [\"insert\", \"update\", \"delete\"];\n\n/**\n * Returns the security rules that should be applied to a collection: the\n * author's explicit `securityRules` plus the framework defaults described in\n * the module doc (baseline server/admin read for all collections; self-read\n * and the admin write gate for auth collections).\n *\n * Collections that opt out via `disableDefaultPolicies` are returned unchanged.\n */\n/**\n * The restrictive write gate for an auth collection.\n *\n * Restrictive, so it is ANDed with everything else: whatever an author's\n * permissive rules allow, a write to this table still has to satisfy this too.\n * It is the only thing standing between \"users may edit their own row\" and\n * \"users may grant themselves any role\".\n */\nfunction adminWriteGate(tableName: string): SecurityRule {\n return {\n name: `${tableName}_require_admin_write`,\n mode: \"restrictive\",\n operations: [...DEFAULT_GUARDED_OPS],\n condition: SERVER_OR_ADMIN_EXPR,\n check: SERVER_OR_ADMIN_EXPR\n };\n}\n\n/**\n * The restrictive tenancy policy, as a list of zero or one.\n *\n * A list so the two call sites can splice it in without a conditional, and a\n * separate function so it is obvious that it is injected on *both* paths —\n * including the `disableDefaultPolicies` one, where it is the only permissive-\n * looking thing that stays. See `./tenant.ts`.\n */\nfunction tenantRule(table: PolicyTable): SecurityRule[] {\n return table.tenant ? [tenantSecurityRule(table.table, table.tenant)] : [];\n}\n\n/**\n * Whether a table goes without the injected baseline: its own\n * `defaultPolicies` when it says, otherwise its database's\n * `rls.defaultPolicies` (`database({ rls: { defaultPolicies: false } })`).\n *\n * @group Policies\n */\nexport function tableDefaultPoliciesDisabled(table: PolicyTable): boolean {\n if (table.defaultPolicies !== undefined) return !table.defaultPolicies;\n return !declaredRlsPolicyShape(table.database ?? DEFAULT_DATA_SOURCE_KEY).defaultPolicies;\n}\n\nexport function tableEffectiveRules(table: PolicyTable): SecurityRule[] {\n const explicit = [...table.rules];\n\n const tableName = table.table;\n const injected: SecurityRule[] = [];\n\n if (tableDefaultPoliciesDisabled(table)) {\n // The opt-out drops the *permissive* defaults — the ones that grant.\n // The restrictive admin-write gate on an auth collection is not among\n // them, because it is different in kind: a restrictive policy is ANDed\n // with every other policy and can only ever remove access, so opting\n // out of it cannot express anything except \"let more people write\".\n //\n // Dropping it did exactly that. `{ disableDefaultPolicies: true,\n // securityRules: [{ operation: \"all\", ownerField: \"id\" }] }` — an\n // ordinary \"users may edit their own row\" configuration — let any\n // signed-in user set their own `roles` to `[\"admin\"]`, with no warning\n // from any boot guard, doctor check or validator.\n //\n // An author who needs a different gate can add their own restrictive\n // rule; they cannot end up with none by accident.\n // Tenancy survives the opt-out for exactly the reason the write gate\n // does: it is restrictive, so it can only ever remove access. Dropping\n // it could express nothing except \"let every tenant read every other\n // tenant's rows\", which is not a thing `disableDefaultPolicies` is for\n // — that flag is about taking over the *grants*.\n return [...explicit, ...tenantRule(table), ...(table.auth\n ? [adminWriteGate(tableName)]\n : [])];\n }\n\n // Baseline read + write: the server context and admins can always operate.\n // RLS default-denies under the user role, so without these a rule-less\n // collection would be locked to everyone — including the admin studio.\n // Author rules are permissive and broaden access from here.\n injected.push({\n name: `${tableName}_default_admin_read`,\n operations: [\"select\"],\n condition: SERVER_OR_ADMIN_EXPR\n });\n injected.push({\n name: `${tableName}_default_admin_write`,\n operations: [...DEFAULT_GUARDED_OPS],\n condition: SERVER_OR_ADMIN_EXPR,\n check: SERVER_OR_ADMIN_EXPR\n });\n\n if (table.auth) {\n // Self-read: a user can always read their own row.\n injected.push({\n name: `${tableName}_default_self_read`,\n operations: [\"select\"],\n condition: policy.compare(policy.field(table.idKey), \"eq\", policy.authUid())\n });\n\n // Restrictive gate: AND'd with all other policies, so no permissive rule\n // (e.g. an owner \"edit your own row\" rule) can let a non-admin change\n // privileged columns like `roles`. Survives `disableDefaultPolicies` —\n // see the note above the opt-out.\n injected.push(adminWriteGate(tableName));\n }\n\n // Last, so it reads as what it is: a restriction ANDed over everything\n // above it, author rules included.\n injected.push(...tenantRule(table));\n\n return [...explicit, ...injected];\n}\n\n/**\n * The framework defaults that {@link tableEffectiveRules} would add to a\n * collection, without the author's own rules.\n *\n * These policies appear in the database under names the author never wrote, and\n * a permissive policy ORs with every other permissive policy — so someone\n * reading their `securityRules` and then the real ACL sees more access than they\n * declared. Dropping them by hand does nothing either: `db push` is declarative,\n * so the next push asserts them again. Callers use this to say, in the generated\n * DDL, which policies are injected and how to take them off.\n */\nexport function tableInjectedRules(table: PolicyTable): SecurityRule[] {\n if (tableDefaultPoliciesDisabled(table)) {\n // Not empty for an auth collection, nor for a tenant-scoped one: both\n // restrictive rules are still injected, and the generated DDL has to\n // say so — a policy in the database that the author never wrote and\n // cannot find in this list is exactly the surprise this function exists\n // to prevent.\n return [...tenantRule(table), ...(table.auth\n ? [adminWriteGate(table.table)]\n : [])];\n }\n\n // tableEffectiveRules appends the defaults after the author's rules, so\n // everything past the author's count is injected.\n return tableEffectiveRules(table).slice(table.rules.length);\n}\n\n/**\n * Every policy name `rebase db push` would write for a collection.\n *\n * This is the answer to \"did the codebase produce this live policy?\", and it is\n * more than `securityRules.map(r => r.name)` for two reasons:\n *\n * - a rule without an explicit `name` compiles to `<table>_<op>_<hash>`, one\n * per operation, so comparing `rule.name` to `policyname` never matches it;\n * - the generator also injects the safe-by-default baseline\n * (`<table>_default_admin_*`), which is in no collection's `securityRules`.\n *\n * Every UI that flags drift has to get both right, and each one that derived it\n * by hand got a different subset — which is how four policies *Rebase itself\n * wrote* came to be badged as hand-written drift on every table in a project,\n * with a button offering to import them back into the codebase that produced\n * them. There is one derivation now, and this is it.\n */\nexport function tableGeneratedPolicyNames(table: PolicyTable): Set<string> {\n return getPolicyNamesForRules(tableEffectiveRules(table), table.table);\n}\n\n","import {\n JUNCTION_PIVOT_KEY,\n PolicyExpression,\n PolicyOperand,\n SecurityRule,\n policy\n} from \"@rebasepro/types\";\nimport type { ColumnDescriptor, RelationDescriptor, TableDescriptor } from \"@rebasepro/types\";\nimport { getPolicyOperations } from \"@rebasepro/utils\";\nimport { securityRuleToConditions } from \"./policy/securityRuleToConditions\";\nimport { tableDefaultPoliciesDisabled } from \"./auth-default-policies\";\nimport { claimCastOf, policyTableFromDescriptor, type PolicyColumn, type PolicyTable } from \"./policy/policy-table\";\n\n/**\n * RLS derivation for many-to-many junction tables.\n *\n * A `through` relation makes the generator create a table nobody declared as a\n * collection — `posts_tags`, `user_roles`. Those tables used to be the one kind\n * of generated table with **no** RLS at all: `rebase_user` holds full DML grants,\n * so with the endpoints locked down, any signed-up user could still read or wipe\n * every edge between them. There is also nowhere in the config to write rules\n * for a junction, so the author could not even fix it by hand.\n *\n * The architecture here is that a junction's security is *derived*, never\n * hand-written:\n *\n * 1. **Locked baseline.** The same server-or-admin `default_admin` grants every\n * collection gets, so the invariant holds again: every table the generator\n * creates is default-deny, and rules only broaden.\n *\n * 2. **Reads follow the endpoints.** An edge is visible iff *both* endpoint\n * rows are visible — two correlated `EXISTS` subqueries. The subqueries run\n * under the caller's role, so each endpoint's own RLS filters them: junction\n * visibility delegates to the endpoints' policies, whatever they become,\n * with nothing duplicated. A public blog keeps rendering its tags; a private\n * CRM's edges are exactly as hidden as its rows.\n *\n * 3. **Writes follow the owning side's update rules.** Linking or unlinking an\n * edge *is* an edit of the owning row — tagging a post is editing the post —\n * so edge writes inherit the declaring collection's explicit permissive\n * `update` rules, each wrapped in an `EXISTS` against the owning row. Where\n * a rule cannot be embedded faithfully (see below) it is dropped, so the\n * failure mode is always *too locked*, never open. Explicit **restrictive**\n * update rules are inherited as restrictive junction rules; if one of them\n * cannot be embedded, the whole derived write grant for that side is\n * suppressed — granting without the author's gate would be looser than the\n * parent itself.\n *\n * **Embeddability.** A parent rule is embedded by moving its condition inside\n * `EXISTS (SELECT 1 FROM parent WHERE parent.pk = junction.fk AND <condition>)`.\n * In that scope, `field` operands bind to the parent — which is what the author\n * meant. But `outerField` operands and `{column}` placeholders in `raw` SQL bind\n * to the RLS row, which is now the junction, not the parent the author wrote\n * them against. So: `raw` anywhere disqualifies a rule; a top-level `outerField`\n * (equivalent to `field` outside a subquery) is rewritten to `field`; an\n * `outerField` inside a nested `existsIn` cannot be re-scoped and disqualifies\n * the rule.\n *\n * Injected parent defaults are never inherited — the junction's own baseline\n * already covers the server/admin plane, and an auth collection's restrictive\n * `require_admin_write` gate exists to protect privileged parent *columns*,\n * which an edge write cannot touch. Inheriting it would stop users managing\n * e.g. their own interests through a `users_interests` junction for no gain.\n *\n * Everything flows through the shared naming machinery, so the Studio\n * recognises these policies as generated instead of offering to \"import\" them.\n */\n\n// Mirrors auth-default-policies: the server context or an admin.\nconst SERVER_OR_ADMIN_EXPR: PolicyExpression = policy.or(\n policy.serverContext(),\n policy.rolesOverlap([\"admin\"])\n);\n\n/** `EXISTS (SELECT 1 FROM endpoint WHERE endpoint.pk = junction.fk [AND extra])`. */\nfunction existsEndpoint(endpoint: PolicyJunctionEndpoint, extra?: PolicyExpression): PolicyExpression {\n const correlation = policy.compare(\n policy.field(endpoint.table.idKey),\n \"eq\",\n policy.outerField(endpoint.junctionColumn)\n );\n return policy.existsIn({\n table: endpoint.table.slug,\n where: extra ? policy.and(correlation, extra) : correlation\n });\n}\n\n/**\n * Whether a parent-rule expression keeps its meaning when moved inside the\n * junction's `EXISTS` subquery — and the re-scoped copy if it does.\n *\n * Returns `null` when the rule cannot be embedded faithfully: `raw` SQL\n * anywhere (its `{column}` placeholders would bind to the junction), or an\n * `outerField` inside a nested `existsIn` (it would bind to the junction while\n * the author meant the parent, and no operand can express \"the middle scope\").\n * Top-level `outerField`s are rewritten to `field`, which is what they meant.\n */\nexport function embedParentExpression(expr: PolicyExpression, depth = 0): PolicyExpression | null {\n switch (expr.kind) {\n case \"raw\":\n return null;\n case \"and\":\n case \"or\": {\n const parts: PolicyExpression[] = [];\n for (const child of expr.operands) {\n const embedded = embedParentExpression(child, depth);\n if (!embedded) return null;\n parts.push(embedded);\n }\n return expr.kind === \"and\" ? policy.and(...parts) : policy.or(...parts);\n }\n case \"not\": {\n const embedded = embedParentExpression(expr.operand, depth);\n return embedded ? policy.not(embedded) : null;\n }\n case \"existsIn\": {\n const where = embedParentExpression(expr.where, depth + 1);\n return where ? policy.existsIn({ table: expr.table, where }) : null;\n }\n case \"compare\": {\n const left = embedOperand(expr.left, depth);\n const right = embedOperand(expr.right, depth);\n if (!left || !right) return null;\n return { ...expr, left, right };\n }\n default:\n // Leaf expressions with no field references (true, false,\n // serverContext, authenticated, rolesOverlap, rolesContain) are\n // position-independent.\n return expr;\n }\n}\n\n/** Re-scope an operand, or return `null` if its binding cannot be preserved. */\nfunction embedOperand(operand: PolicyOperand, depth: number): PolicyOperand | null {\n if (operand.kind === \"outerField\") {\n // Outside a subquery, outerField ≡ field: the author meant their own\n // row, which after embedding is the EXISTS's joined table → field.\n if (depth === 0) return policy.field(operand.name);\n // Inside the author's own existsIn it meant the parent row; after\n // embedding it would bind to the junction. Not expressible.\n return null;\n }\n return operand;\n}\n\n/** Does the rule cover the `update` operation? */\nfunction coversUpdate(rule: SecurityRule): boolean {\n return getPolicyOperations(rule).some(op => op === \"update\" || op === \"all\");\n}\n\n/**\n * One end of a junction, as the policy compiler reads it: the table, and the\n * junction column holding its key.\n *\n * @group Policies\n */\nexport interface PolicyJunctionEndpoint {\n table: PolicyTable;\n /** Junction column holding this endpoint's key. */\n junctionColumn: string;\n}\n\n/**\n * A junction table, as its derived rules are built from: its two endpoints\n * and every table declaring a relation through it (whose update rules the\n * edge writes inherit).\n *\n * @group Policies\n */\nexport interface PolicyJunction {\n /** Bare table name. */\n table: string;\n schema: string;\n /** The two endpoints, in [source, target] order of the first declaring relation. */\n endpoints: [PolicyJunctionEndpoint, PolicyJunctionEndpoint];\n /** Every table that declares a relation through this junction. */\n declaringSides: PolicyJunctionEndpoint[];\n}\n\n/**\n * The full derived policy set for a junction table: the locked server/admin\n * baseline, the endpoint-visibility read grant, inherited write grants, and\n * inherited restrictive gates. Returns `[]` when every declaring collection set\n * `disableDefaultPolicies` — the junction is then the author's to police, and\n * stays locked (RLS is still enabled) until they write policies for it.\n */\nexport function junctionRules(spec: PolicyJunction): SecurityRule[] {\n if (spec.declaringSides.every(side => tableDefaultPoliciesDisabled(side.table))) {\n return [];\n }\n\n const rules: SecurityRule[] = [];\n\n // 1. Locked baseline — same shape and naming as every collection's.\n rules.push({\n name: `${spec.table}_default_admin_read`,\n operations: [\"select\"],\n condition: SERVER_OR_ADMIN_EXPR\n });\n rules.push({\n name: `${spec.table}_default_admin_write`,\n operations: [\"insert\", \"update\", \"delete\"],\n condition: SERVER_OR_ADMIN_EXPR,\n check: SERVER_OR_ADMIN_EXPR\n });\n\n // 2. Reads follow the endpoints: the edge is visible iff both rows are.\n // The EXISTS subqueries run under the caller's role, so each endpoint's\n // own RLS applies inside them — visibility is delegated, not copied.\n rules.push({\n name: `${spec.table}_default_edge_read`,\n operations: [\"select\"],\n condition: policy.and(\n existsEndpoint(spec.endpoints[0]),\n existsEndpoint(spec.endpoints[1])\n )\n });\n\n // 3. Writes follow the owning side's explicit update rules.\n const writeGrants: PolicyExpression[] = [];\n for (const side of spec.declaringSides) {\n const updateRules = side.table.rules.filter(coversUpdate);\n\n const permissive = updateRules.filter(r => r.mode !== \"restrictive\");\n const restrictive = updateRules.filter(r => r.mode === \"restrictive\");\n\n // Embed the restrictive gates first: if any of them cannot be carried\n // over, granting writes from this side would be looser than the parent\n // itself allows — so the whole side's grant is suppressed.\n const embeddedGates: PolicyExpression[] = [];\n let gatesEmbeddable = true;\n for (const gate of restrictive) {\n const using = securityRuleToConditions(gate).usingExpr;\n const embedded = using ? embedParentExpression(using) : null;\n if (!embedded) {\n gatesEmbeddable = false;\n break;\n }\n embeddedGates.push(embedded);\n }\n if (!gatesEmbeddable) continue;\n\n const grants: PolicyExpression[] = [];\n for (const rule of permissive) {\n const using = securityRuleToConditions(rule).usingExpr;\n const embedded = using ? embedParentExpression(using) : null;\n if (embedded) grants.push(embedded);\n }\n if (grants.length === 0) continue;\n\n // \"May update the owning row\": any permissive grant, AND every gate.\n const condition = embeddedGates.length > 0\n ? policy.and(policy.or(...grants), ...embeddedGates)\n : policy.or(...grants);\n\n writeGrants.push(existsEndpoint(side, condition));\n }\n\n if (writeGrants.length > 0) {\n rules.push({\n name: `${spec.table}_default_edge_write`,\n operations: [\"insert\", \"update\", \"delete\"],\n condition: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants),\n check: writeGrants.length === 1 ? writeGrants[0] : policy.or(...writeGrants)\n });\n }\n\n return rules;\n}\n\n// ── Junctions of compiled tables ─────────────────────────────────────────────\n\n/** The `manyToMany` arm of {@link RelationDescriptor}. */\nexport type ManyToManyDescriptor = Extract<RelationDescriptor, { kind: \"manyToMany\" }>;\n\n/**\n * One end of a junction of compiled tables.\n *\n * @group Policies\n */\nexport interface TableJunctionEndpoint {\n descriptor: TableDescriptor;\n /** Junction column holding this endpoint's key. */\n junctionColumn: string;\n}\n\n/**\n * A table that declares a `manyToMany` through the junction.\n *\n * @group Policies\n */\nexport interface TableJunctionSide extends TableJunctionEndpoint {\n relation: ManyToManyDescriptor;\n}\n\n/**\n * A junction table, resolved from the `manyToMany` relations of compiled\n * tables: what the schema planner creates and the policy compiler derives the\n * junction's rules for.\n *\n * @group Policies\n */\nexport interface TableJunction {\n /** Bare table name. */\n table: string;\n /** Always `public`: the planner creates every junction there. */\n schema: string;\n /** The two endpoints, in [source, target] order of the first declaring relation. */\n endpoints: [TableJunctionSide, TableJunctionEndpoint];\n /** Every table that declares a relation through this junction, in input order. */\n declaringSides: TableJunctionSide[];\n /**\n * The junction's own columns beyond the two keys (`pivot`), merged across\n * every declaring side. Empty when there are none.\n */\n pivot: ColumnDescriptor[];\n}\n\n/**\n * Walk every table's `manyToMany` relations and aggregate the junction tables\n * they declare, keyed by junction table. Two tables may declare one junction\n * from opposite sides (`posts.tags` and `tags.posts` through `posts_tags`);\n * both become `declaringSides`, so the derived write grants consider both.\n * A relation whose target is not among `descriptors` is skipped.\n *\n * Pass every descriptor, views included. A view declares no junction (it has\n * no table to own one, and the planner plans none for it), so its\n * `manyToMany` relations are skipped; but a view is a valid *target* — the\n * junction keys into it without a foreign key — so it must be here for the\n * table that links to it to resolve its junction. Filtering views out before\n * the call loses every junction into a view.\n *\n * Input order decides the endpoints' order and the sides' — sort by slug at\n * the boundary, as the planner does.\n *\n * @group Policies\n */\nexport function resolveTableJunctions(descriptors: readonly TableDescriptor[]): Map<string, TableJunction> {\n const bySlug = new Map(descriptors.map(descriptor => [descriptor.slug, descriptor]));\n const junctions = new Map<string, TableJunction>();\n for (const descriptor of descriptors) {\n if (descriptor.kind === \"view\") continue;\n for (const relation of descriptor.relations) {\n if (relation.kind !== \"manyToMany\") continue;\n const target = bySlug.get(relation.target);\n if (!target) continue;\n const raw = relation.through.table;\n // The CREATE TABLE path strips a schema prefix from the name and\n // creates in `public`; the policies target the same table.\n const table = raw.includes(\".\") ? raw.split(\".\").pop() ?? raw : raw;\n const side: TableJunctionSide = { descriptor, junctionColumn: relation.through.sourceKey, relation };\n const existing = junctions.get(table);\n if (!existing) {\n junctions.set(table, {\n table,\n schema: \"public\",\n endpoints: [side, { descriptor: target, junctionColumn: relation.through.targetKey }],\n declaringSides: [side],\n pivot: mergePivot([], relation.through.pivot, table, descriptor)\n });\n continue;\n }\n // Merged whether or not this side is new: one table can reach a\n // junction under two relation names, and every column each asks\n // for has to exist.\n existing.pivot = mergePivot(existing.pivot, relation.through.pivot, table, descriptor);\n if (!existing.declaringSides.some(s => s.descriptor === descriptor)) existing.declaringSides.push(side);\n }\n }\n return junctions;\n}\n\n/**\n * Fold one side's `pivot` into the junction's, refusing a disagreement: one\n * table is created, so two descriptions of a column that are not the same\n * description have no correct answer.\n */\nfunction mergePivot(\n into: ColumnDescriptor[],\n incoming: readonly ColumnDescriptor[],\n table: string,\n descriptor: TableDescriptor\n): ColumnDescriptor[] {\n if (incoming.length === 0) return into;\n const merged = [...into];\n for (const column of incoming) {\n const already = merged.find(existing => existing.key === column.key);\n if (!already) {\n merged.push(column);\n continue;\n }\n if (JSON.stringify(already) !== JSON.stringify(column)) {\n throw new Error(\n `The junction table \"${table}\" is declared from more than one side, and they disagree ` +\n `about the pivot column \"${column.key}\": \"${descriptor.slug}\" describes it differently than ` +\n \"another declaring table does. One table is created, so both `pivot` lists have to describe \" +\n \"the same column — or only one side should declare it.\"\n );\n }\n }\n return merged;\n}\n\n/**\n * The policy compiler's view of a junction table: its two key columns (by\n * column name, as the junction rules name them) and its pivot columns.\n *\n * @group Policies\n */\nexport function junctionPolicyTable(junction: TableJunction): PolicyTable {\n const columns: Record<string, PolicyColumn> = {};\n for (const endpoint of junction.endpoints) {\n columns[endpoint.junctionColumn] = { column: endpoint.junctionColumn, claimCast: \"text\" };\n }\n // After the keys, so a pivot column colliding with a key column cannot\n // replace it.\n for (const column of junction.pivot) {\n if (column.key === JUNCTION_PIVOT_KEY || column.key in columns) continue;\n columns[column.key] = { column: column.column, claimCast: claimCastOf(column.type) };\n }\n return {\n slug: junction.table,\n table: junction.table,\n schema: junction.schema,\n columns,\n links: {},\n idKey: \"id\",\n rules: [],\n auth: false\n };\n}\n\n/**\n * The derived rules of a junction of compiled tables ({@link junctionRules}).\n *\n * @group Policies\n */\nexport function tableJunctionRules(junction: TableJunction): SecurityRule[] {\n const endpoint = (end: TableJunctionEndpoint): PolicyJunctionEndpoint => ({\n table: policyTableFromDescriptor(end.descriptor),\n junctionColumn: end.junctionColumn\n });\n return junctionRules({\n table: junction.table,\n schema: junction.schema,\n endpoints: [endpoint(junction.endpoints[0]), endpoint(junction.endpoints[1])],\n declaringSides: junction.declaringSides.map(endpoint)\n });\n}\n","import { createHash } from \"node:crypto\";\nimport {\n isRedactedSecurityRule,\n scopeGrants,\n scopeGrantsAny,\n scopeTargets,\n type ColumnDescriptor,\n type JunctionPolicyDescriptor,\n type PolicyDescriptor,\n type RedactedSecurityRule,\n type RelationDescriptor,\n type RlsDescriptor,\n type SecurityOperation,\n type SecurityRule,\n type TableDescriptor\n} from \"@rebasepro/types\";\nimport {\n canReadRelation,\n canReadWithAccess,\n compileTableRulePolicies,\n junctionPolicyTable,\n policyTableFromDescriptor,\n policyTableResolver,\n resolveTableJunctions,\n tableEffectiveRules,\n tableInjectedRules,\n tableJunctionRules,\n type CompiledRulePolicy,\n type FieldViewer,\n type PolicyTable,\n type RelatedTables\n} from \"@rebasepro/common\";\nimport { logger } from \"../utils/logger\";\n\n/**\n * The one serializer of a backend's tables for a caller.\n *\n * `GET /api/schema/tables` serves it over HTTP, `/api/meta/contract` serves\n * its admin-level view, and the MCP surface builds its views from it — three\n * consumers, one definition of what each caller may learn about the schema.\n *\n * Fail closed, per caller:\n *\n * | Field | Who sees it |\n * |---|---|\n * | a `private` column or relation | nobody, administrators included |\n * | a column or relation the caller fails `access.read` for | dropped (`access` itself is kept on what remains) |\n * | a `belongsTo` and its foreign-key column | one fact under two names: each is described only when both pass — a link whose key column the caller cannot read is dropped, and so is a key column whose link is |\n * | a relation whose target table the caller is not served | dropped |\n * | a table | administrators and `schema:read` holders: every one; any other person (`schemaTables.persons: \"granted\"`, the default): those some rule could grant their roles something on (see {@link tableReachable}), every one with `persons: \"all\"`; a credential (API key, token): the tables its `data:*` scopes name, or all with `schema:read`; an anonymous caller (public opt-in): those with a public `select` rule |\n * | structured `rls.rules` | everyone served the table; a non-privileged person under `\"granted\"` only the rules that can apply to their roles (see {@link ruleAppliesTo}), the rest dropped |\n * | raw SQL in a rule (`using`, `withCheck`, a `policy.raw` node) | administrators and `schema:read` holders; everyone else gets a {@link RedactedSecurityRule} |\n * | `rls.policies`, `rls.junctions` (compiled policies) | administrators and `schema:read` holders |\n * | `view.query`, `indexes` | administrators and `schema:read` holders |\n * | `auth.roles`, `auth.scopes` (labels) | administrators, `schema:read` and `users:read` holders |\n * | `hooks`, column `transforms`, `auth.hooks` | everyone served the table but a non-privileged person under `\"granted\"` and an anonymous caller (presence flags; code never leaves the server, and the panel reads none of them) |\n * | `metadata`, `softDelete`, `tenant`, `history`, `search` | everyone served the table: the panel renders and gates from them (`metadata` is public to the callers served the table by definition) |\n *\n * @module\n */\n\n/**\n * Who is asking.\n *\n * - `anonymous` — nobody signed in; served only when the backend opts in\n * (`schemaTables: { public: true }`).\n * - `person` — a signed-in user, or the service key: holds what their roles\n * hold. With `schema:read` (administrators) every table; otherwise the\n * tables some rule could grant their roles something on, or every table\n * when the backend says `schemaTables: { persons: \"all\" }`.\n * - `credential` — an API key, an MCP or platform token: holds exactly the\n * scopes it was granted, and sees only the tables they name.\n *\n * @group Schema\n */\nexport interface SchemaCaller {\n kind: \"anonymous\" | \"person\" | \"credential\";\n /** The application roles columns' `access.read` is judged against. */\n roles: readonly string[];\n /** Every scope the caller holds (for a person: what their roles hold). */\n scopes: readonly string[];\n}\n\n/**\n * What a caller is served: the redaction {@link serializeTables} applies.\n * Two callers with the same view receive the same body.\n *\n * @group Schema\n */\nexport interface SchemaView {\n /** Raw SQL, compiled policies, view queries and indexes. */\n privileged: boolean;\n /** The auth table's role and scope labels. */\n accountLabels: boolean;\n /** The roles columns and relations are judged against. */\n viewer: FieldViewer;\n /**\n * Which tables. `granted`: those some rule could grant the viewer's roles\n * something on ({@link tableReachable}), with only the rules that can\n * apply to them ({@link ruleAppliesTo}).\n */\n tables: { kind: \"all\" } | { kind: \"only\"; slugs: readonly string[] } | { kind: \"public\" } | { kind: \"granted\" };\n}\n\n/**\n * What a signed-in person without `schema:read` is described:\n *\n * - `\"granted\"` (the default) — the tables some rule could grant their roles\n * something on, each with only the rules that can apply to them;\n * - `\"all\"` — every table, with every rule (raw SQL still redacted): what\n * every signed-in caller was served before this option existed.\n *\n * @group Schema\n */\nexport type SchemaTablesPersons = \"granted\" | \"all\";\n\n/**\n * Options of {@link schemaViewFor}.\n *\n * @group Schema\n */\nexport interface SchemaViewOptions {\n /** `schemaTables.persons` — see {@link SchemaTablesPersons}. Default `\"granted\"`. */\n persons?: SchemaTablesPersons;\n}\n\n/**\n * Why a caller is served nothing.\n *\n * @group Schema\n */\nexport type SchemaRefusal = { refused: \"scope\"; message: string };\n\nconst DATA_SCOPES = [\"data:read\", \"data:write\", \"data:delete\"] as const;\n\n/**\n * The view a caller is served, or why it is refused.\n *\n * A credential needs `schema:read` or a `data:*` scope: a key minted for\n * storage or functions alone has no business reading the schema.\n *\n * @group Schema\n */\nexport function schemaViewFor(caller: SchemaCaller, options: SchemaViewOptions = {}): SchemaView | SchemaRefusal {\n if (caller.kind === \"anonymous\") {\n return { privileged: false, accountLabels: false, viewer: { roles: [] }, tables: { kind: \"public\" } };\n }\n const scopes = caller.scopes;\n const privileged = scopeGrants(scopes, \"schema:read\");\n const accountLabels = privileged || scopeGrants(scopes, \"users:read\");\n const viewer: FieldViewer = { roles: [...caller.roles] };\n if (privileged) return { privileged, accountLabels, viewer, tables: { kind: \"all\" } };\n if (caller.kind === \"person\") {\n return { privileged, accountLabels, viewer, tables: { kind: options.persons === \"all\" ? \"all\" : \"granted\" } };\n }\n if (!DATA_SCOPES.some(scope => scopeGrantsAny(scopes, scope))) {\n return {\n refused: \"scope\",\n message: \"This credential holds neither `schema:read` nor a `data:*` scope, so it may not read the schema. \" +\n \"Grant it `schema:read`, or the `data:read:<table>` scopes of the tables it works with.\"\n };\n }\n const slugs = new Set<string>();\n for (const scope of DATA_SCOPES) {\n const targets = scopeTargets(scopes, scope);\n if (targets === \"all\") return { privileged, accountLabels, viewer, tables: { kind: \"all\" } };\n for (const target of targets) slugs.add(target);\n }\n return { privileged, accountLabels, viewer, tables: { kind: \"only\", slugs: [...slugs].sort() } };\n}\n\n/** The view `/api/meta/contract` serves: every table, as an administrator sees it. */\nexport const ADMIN_SCHEMA_VIEW: SchemaView = Object.freeze({\n privileged: true,\n accountLabels: true,\n viewer: Object.freeze({ roles: Object.freeze([\"admin\"]) }),\n tables: Object.freeze({ kind: \"all\" as const })\n});\n\n/**\n * A short, stable digest of everything the redaction depends on: two callers\n * with the same key are served byte-identical bodies. Part of the `ETag`.\n *\n * @group Schema\n */\nexport function schemaViewKey(view: SchemaView): string {\n const identity = {\n p: view.privileged,\n a: view.accountLabels,\n r: [...new Set(view.viewer.roles ?? [])].sort(),\n t: view.tables.kind === \"only\" ? view.tables.slugs : view.tables.kind\n };\n return createHash(\"sha256\").update(JSON.stringify(identity)).digest(\"hex\").slice(0, 16);\n}\n\n// ── Compiled policies ────────────────────────────────────────────────────────\n\n/**\n * The compiled policies of one table, and of the junctions of its\n * `manyToMany` relations.\n *\n * @group Schema\n */\nexport interface TablePolicies {\n policies: PolicyDescriptor[];\n junctions: JunctionPolicyDescriptor[];\n}\n\n/** The planner's options: this runtime switches admin requests to `rebase_admin`. */\nconst COMPILE_OPTIONS = { adminRole: true, adminRequestRole: true } as const;\n\nfunction asPolicy(compiled: CompiledRulePolicy, injected: boolean, rule: number | undefined): PolicyDescriptor {\n return {\n name: compiled.name,\n operation: compiled.operation,\n mode: compiled.mode,\n roles: [...compiled.roles],\n using: compiled.using,\n withCheck: compiled.withCheck,\n // An admin-request companion is Rebase's, whatever rule it rides on.\n injected: injected || compiled.adminRequestTarget === true,\n ...(rule !== undefined && compiled.adminRequestTarget !== true ? { rule } : {})\n };\n}\n\n/**\n * Compile the policies of every table — what the schema planner writes into\n * Postgres and the Studio's RLS editor compares the live database against —\n * from the same `compileTableRulePolicies` / `tableEffectiveRules` the planner\n * reads, keyed by slug.\n *\n * Reads the declared tables' descriptors. Introspected tables are not among\n * them: Rebase did not generate their policies and cannot say what they are.\n *\n * A rule that cannot be compiled (an `existsIn` naming a table this backend\n * does not hold) contributes no policy and is logged; the rest still are.\n *\n * @group Schema\n */\nexport function compileServedPolicies(\n tables: readonly TableDescriptor[],\n describedSlugs: ReadonlySet<string>\n): Map<string, TablePolicies> {\n const options = { ...COMPILE_OPTIONS, resolveTable: policyTableResolver(tables) };\n const out = new Map<string, TablePolicies>();\n\n const compile = (table: PolicyTable, rule: SecurityRule, injected: boolean, index: number | undefined): PolicyDescriptor[] => {\n try {\n return compileTableRulePolicies(table, rule, options).map(policy => asPolicy(policy, injected, index));\n } catch (error) {\n logger.debug(\"A rule could not be compiled for GET /api/schema/tables\", {\n table: table.table,\n error: error instanceof Error ? error.message : String(error)\n });\n return [];\n }\n };\n\n for (const descriptor of tables) {\n if (!describedSlugs.has(descriptor.slug)) continue;\n const table = policyTableFromDescriptor(descriptor);\n const explicit = table.rules.length;\n const injectedNames = new Set(tableInjectedRules(table).map(rule => rule.name));\n const policies = tableEffectiveRules(table).flatMap((rule, index) => {\n const injected = index >= explicit || (rule.name !== undefined && injectedNames.has(rule.name));\n return compile(table, rule, injected, injected ? undefined : index);\n });\n out.set(descriptor.slug, { policies, junctions: [] });\n }\n\n let junctions: ReturnType<typeof resolveTableJunctions>;\n try {\n junctions = resolveTableJunctions(tables);\n } catch (error) {\n logger.debug(\"The junction tables could not be resolved for GET /api/schema/tables\", {\n error: error instanceof Error ? error.message : String(error)\n });\n return out;\n }\n for (const junction of junctions.values()) {\n const table = junctionPolicyTable(junction);\n const policies = tableJunctionRules(junction).flatMap(rule => compile(table, rule, true, undefined));\n const entry: JunctionPolicyDescriptor = { table: junction.table, schema: junction.schema, policies };\n const sides = new Set(junction.declaringSides.map(side => side.descriptor.slug));\n for (const slug of sides) {\n const served = out.get(slug);\n if (served && !served.junctions.some(existing => existing.table === entry.table)) served.junctions.push(entry);\n }\n }\n return out;\n}\n\n// ── Redaction ────────────────────────────────────────────────────────────────\n\n/** Whether anything under `value` is a `policy.raw(…)` node. */\nfunction containsRawNode(value: unknown): boolean {\n if (Array.isArray(value)) return value.some(containsRawNode);\n if (typeof value !== \"object\" || value === null) return false;\n if (\"kind\" in value && value.kind === \"raw\") return true;\n return Object.values(value).some(containsRawNode);\n}\n\n/** Whether a rule carries SQL text anywhere: a raw clause, or a raw node inside a structured one. */\nfunction carriesSql(rule: SecurityRule): boolean {\n return rule.using !== undefined || rule.withCheck !== undefined\n || containsRawNode(rule.condition) || containsRawNode(rule.check);\n}\n\n/**\n * A rule as a caller who may not see SQL is served it: as written when it\n * carries none, else the {@link RedactedSecurityRule} marker, keeping only\n * whom the rule concerns.\n *\n * @group Schema\n */\nexport function redactRule(rule: SecurityRule): SecurityRule {\n if (isRedactedSecurityRule(rule) || !carriesSql(rule)) return rule;\n const marker: RedactedSecurityRule = {\n redacted: true,\n ...(rule.operation !== undefined ? { operation: rule.operation } : {}),\n ...(rule.operations !== undefined ? { operations: [...rule.operations] } : {}),\n ...(rule.mode !== undefined ? { mode: rule.mode } : {}),\n ...(rule.roles !== undefined ? { roles: [...rule.roles] } : {}),\n ...(rule.access !== undefined ? { access: rule.access } : {})\n };\n return marker;\n}\n\nfunction appliesTo(rule: SecurityRule, operation: SecurityOperation): boolean {\n const operations = rule.operations && rule.operations.length > 0 ? rule.operations : [rule.operation ?? \"all\"];\n return operations.includes(operation) || operations.includes(\"all\");\n}\n\n/**\n * Whether anyone, signed in or not, may read some of a table's rows: a\n * permissive `select` rule with `access: \"public\"`, not narrowed to roles or\n * to Postgres roles. What the anonymous view (the public opt-in) serves.\n *\n * @group Schema\n */\nexport function hasPublicSelectRule(table: TableDescriptor): boolean {\n if (table.kind !== \"table\" || table.rls.posture !== \"rules\") return false;\n return table.rls.rules.some(rule =>\n !isRedactedSecurityRule(rule)\n && (rule.mode ?? \"permissive\") === \"permissive\"\n && rule.access === \"public\"\n && (rule.roles === undefined || rule.roles.length === 0)\n && rule.pgRoles === undefined\n && appliesTo(rule, \"select\"));\n}\n\n/**\n * Whether a caller holding `roles` holds one of a rule's (or a view's)\n * `roles`: always when it names none, and when it names `\"public\"`, which the\n * policy compiler and the client evaluator both read as everyone.\n */\nfunction holdsOneOf(named: readonly string[] | undefined, roles: readonly string[]): boolean {\n if (!named || named.length === 0) return true;\n return named.some(role => role === \"public\" || roles.includes(role));\n}\n\n/**\n * Whether a rule can apply to a caller holding `roles`: a rule with no\n * `roles` applies to everyone (public, authenticated, registered, owner,\n * condition and raw SQL rules alike — what they admit is decided per row),\n * one with `roles` to the holders of one of them. Restrictive rules count\n * too: they narrow what the caller is granted, and the panel gates by them.\n *\n * @group Schema\n */\nexport function ruleAppliesTo(rule: SecurityRule, roles: readonly string[]): boolean {\n return holdsOneOf(rule.roles, roles);\n}\n\n/**\n * Whether some rule could grant a caller holding `roles` something on a\n * table — what a person without `schema:read` is described under\n * `schemaTables.persons: \"granted\"`:\n *\n * - a table with a permissive rule that applies to them ({@link ruleAppliesTo});\n * - the auth table: every account reads its own row (the injected self-read);\n * - a table under the admin baseline (`\"admin-only\"`, or rules with\n * `defaultPolicies`), for a caller holding `admin`;\n * - a materialized view, for a holder of one of its `view.roles`\n * (`[\"admin\"]` when it names none);\n * - a plain view: never. It has no rules of its own — it runs as the caller\n * over the tables its SQL reads, which the descriptor does not list — so\n * the conservative answer is that it reaches nobody here; `persons: \"all\"`\n * or `schema:read` describes it.\n *\n * @group Schema\n */\nexport function tableReachable(table: TableDescriptor, roles: readonly string[]): boolean {\n if (table.kind === \"view\" || table.rls.posture === \"view\") {\n const viewRoles = table.view?.roles ?? [\"admin\"];\n return table.view?.materialized === true && viewRoles.length > 0 && holdsOneOf(viewRoles, roles);\n }\n if (table.auth) return true;\n if (roles.includes(\"admin\") && (table.rls.posture === \"admin-only\" || table.rls.defaultPolicies)) return true;\n if (table.rls.posture !== \"rules\") return false;\n return table.rls.rules.some(rule => (rule.mode ?? \"permissive\") === \"permissive\" && ruleAppliesTo(rule, roles));\n}\n\nfunction tableServed(table: TableDescriptor, view: SchemaView): boolean {\n switch (view.tables.kind) {\n case \"all\":\n return true;\n case \"only\":\n return view.tables.slugs.includes(table.slug);\n case \"public\":\n return hasPublicSelectRule(table);\n case \"granted\":\n return tableReachable(table, view.viewer.roles ?? []);\n }\n}\n\n/**\n * The slugs of the tables a view is served — what `/api/admin/ui-config`\n * accepts a caller's preferences for.\n *\n * @group Schema\n */\nexport function servedTableSlugs(tables: readonly TableDescriptor[], view: SchemaView): Set<string> {\n return new Set(tables.filter(table => tableServed(table, view)).map(table => table.slug));\n}\n\n/** Whether a view withholds hook presence flags: the least-privileged views, which the panel serves. */\nfunction withholdsHookFlags(view: SchemaView): boolean {\n return !view.privileged && (view.tables.kind === \"granted\" || view.tables.kind === \"public\");\n}\n\nfunction columnServed(column: ColumnDescriptor, viewer: FieldViewer): boolean {\n return column.private !== true && canReadWithAccess(column.access, viewer);\n}\n\n/**\n * A relation as this view describes it, or `undefined` when it is withheld:\n * private, closed to the viewer, joined on a column the viewer may not read\n * on any table it passes through (a relation is exactly as readable as what\n * it is joined on), or pointing at a table the view does not serve.\n */\nfunction servedRelation(\n table: TableDescriptor,\n relation: RelationDescriptor,\n view: SchemaView,\n served: ReadonlySet<string>,\n related: RelatedTables\n): RelationDescriptor | undefined {\n if (!canReadRelation(table, relation, view.viewer, related)) return undefined;\n if (!served.has(relation.target)) return undefined;\n if (relation.kind !== \"manyToMany\") return relation;\n return {\n ...relation,\n through: { ...relation.through, pivot: relation.through.pivot.filter(column => columnServed(column, view.viewer)) }\n };\n}\n\nfunction servedRls(rls: RlsDescriptor, view: SchemaView, policies: TablePolicies | undefined): RlsDescriptor {\n const { policies: _policies, junctions: _junctions, ...base } = rls;\n if (!view.privileged) {\n const roles = view.viewer.roles ?? [];\n const rules = view.tables.kind === \"granted\" ? rls.rules.filter(rule => ruleAppliesTo(rule, roles)) : rls.rules;\n return { ...base, rules: rules.map(redactRule) };\n }\n return policies ? { ...base, policies: policies.policies, junctions: policies.junctions } : base;\n}\n\nfunction serializeTable(\n table: TableDescriptor,\n view: SchemaView,\n served: ReadonlySet<string>,\n policies: TablePolicies | undefined,\n related: RelatedTables\n): TableDescriptor {\n const relations = table.relations\n .map(relation => servedRelation(table, relation, view, served, related))\n .filter((relation): relation is RelationDescriptor => relation !== undefined);\n const relationNames = new Set(relations.map(relation => relation.name));\n // A link and its key column are one fact under two names: a key column\n // whose relation is withheld is withheld with it (as the REST read strips\n // it), derived or declared.\n const withheldKeys = new Set(table.relations\n .filter(relation => relation.kind === \"belongsTo\" && !canReadRelation(table, relation, view.viewer, related))\n .map(relation => relation.kind === \"belongsTo\" ? relation.localField : \"\"));\n const hookFlags = !withholdsHookFlags(view);\n const columns = table.columns\n .filter(column => columnServed(column, view.viewer))\n .filter(column => !withheldKeys.has(column.key))\n .map(column => {\n let served = column;\n if (!hookFlags && served.transforms !== undefined) {\n const { transforms: _transforms, ...rest } = served;\n served = rest;\n }\n // A dropped relation is not named by the column that held its key.\n if (served.foreignKeyOf === undefined || relationNames.has(served.foreignKeyOf)) return served;\n const { foreignKeyOf: _relation, ...rest } = served;\n return rest;\n });\n const columnKeys = new Set(columns.map(column => column.key));\n\n const {\n columns: _columns,\n relations: _relations,\n rls,\n indexes,\n view: viewDefinition,\n auth,\n search,\n hooks,\n ...rest\n } = table;\n\n const searchFields = search?.fields.filter(field => {\n const path = typeof field === \"string\" ? field : field.path;\n return columnKeys.has(path.split(\".\")[0] ?? path);\n });\n let servedAuth = auth;\n if (servedAuth && !view.accountLabels) {\n const { roles: _roles, scopes: _scopes, ...unlabelled } = servedAuth;\n servedAuth = unlabelled;\n }\n if (servedAuth && !hookFlags && servedAuth.hooks !== undefined) {\n const { hooks: _authHooks, ...withoutHooks } = servedAuth;\n servedAuth = withoutHooks;\n }\n let servedView = viewDefinition;\n if (viewDefinition && !view.privileged) {\n const { query: _query, ...withoutQuery } = viewDefinition;\n servedView = withoutQuery;\n }\n\n return {\n ...rest,\n columns,\n relations,\n rls: servedRls(rls, view, policies),\n ...(search && searchFields && searchFields.length > 0 ? { search: { ...search, fields: searchFields } } : {}),\n ...(indexes && view.privileged ? { indexes } : {}),\n ...(servedView ? { view: servedView } : {}),\n ...(servedAuth ? { auth: servedAuth } : {}),\n ...(hooks && hookFlags ? { hooks } : {})\n };\n}\n\n/**\n * The tables a caller is served, redacted for its view (see the module\n * documentation for the table of who sees what). Pure: the same descriptors,\n * view and policies give the same body.\n *\n * @param policies The compiled policies by slug ({@link compileServedPolicies});\n * included for a privileged view only, and only for the tables that have them.\n *\n * @group Schema\n */\nexport function serializeTables(\n tables: readonly TableDescriptor[],\n view: SchemaView,\n policies?: ReadonlyMap<string, TablePolicies>\n): TableDescriptor[] {\n const shown = tables.filter(table => tableServed(table, view));\n const served = new Set(shown.map(table => table.slug));\n // Every declared table, served or not: a join reads the columns it reads\n // whether or not this caller is described the table they are on.\n const related: RelatedTables = name => tables.find(table => table.slug === name || table.table === name);\n return shown.map(table => serializeTable(table, view, served, view.privileged ? policies?.get(table.slug) : undefined, related));\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AAeA,SAAS,KAAK,OAAO,GAAG;CACvB,OAAO,SAAS,IAAI,UAAU,KAAK;AACpC;;;;;;;AAOA,SAAS,QAAQ,OAAO;CACvB,MAAM,QAAQ,MA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