permdock 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.
Files changed (142) hide show
  1. package/dist/{adoption-scan-9brJ_mUG.js → adoption-scan-BJMEEu7V.js} +1 -1
  2. package/dist/{arazzo-Cs-3yoxR.js → arazzo-BAgh0PT6.js} +1 -1
  3. package/dist/{arazzo-C0bltfjv.js → arazzo-C_xK2Kaa.js} +1 -1
  4. package/dist/better-supabase/index.d.ts +26 -4
  5. package/dist/better-supabase/index.js +11 -2
  6. package/dist/{bsb-access-tags-B1TBUQLj.js → bsb-access-tags-CjeR7v7-.js} +10 -43
  7. package/dist/{bsb-action-keys-iKmZChtQ.js → bsb-action-keys-CYEREFMg.js} +1 -1
  8. package/dist/{casbin-DGsO-QmR.js → casbin-BErdqy1J.js} +1 -1
  9. package/dist/{casbin-s6_zDJi1.js → casbin-EwdKipQs.js} +1 -1
  10. package/dist/cli/bin.js +1 -1
  11. package/dist/cli/generate/watch-worker.js +2 -2
  12. package/dist/cli/index.d.ts +3 -3
  13. package/dist/cli/index.js +2 -2
  14. package/dist/cli/plugins/app.d.ts +1 -1
  15. package/dist/cli/plugins/app.js +1 -1
  16. package/dist/cli/plugins/better-supabase.d.ts +1 -1
  17. package/dist/cli/plugins/openapi.d.ts +1 -1
  18. package/dist/cli/plugins/openapi.js +1 -1
  19. package/dist/cli/plugins/powersync.d.ts +1 -1
  20. package/dist/cli/plugins/powersync.js +1 -1
  21. package/dist/cli/plugins/rls.d.ts +2 -2
  22. package/dist/cli/plugins/rls.js +1 -1
  23. package/dist/cli/plugins/schemas.d.ts +1 -1
  24. package/dist/cli/plugins/schemas.js +1 -1
  25. package/dist/cli/plugins/scim.d.ts +2 -2
  26. package/dist/cli/plugins/supabase-hook.d.ts +2 -2
  27. package/dist/cli/plugins/supabase-hook.js +1 -1
  28. package/dist/cli/plugins/supabase.d.ts +3 -3
  29. package/dist/cli/plugins/supabase.js +2 -2
  30. package/dist/cli/plugins/ui.d.ts +1 -1
  31. package/dist/cli/plugins/ui.js +1 -1
  32. package/dist/{client-subject-BOPbpwgm.d.ts → client-subject-xCSkKD1C.d.ts} +1 -1
  33. package/dist/{cloud-fRv3j6sq.js → cloud-DW3q3qnp.js} +2 -2
  34. package/dist/{codemod-DsqEKP6A.js → codemod-CF7NNDzA.js} +14 -11
  35. package/dist/{codemod-DT0dMVdd.js → codemod-DVDMFsTX.js} +8 -7
  36. package/dist/{collect-CCgmm5xN.js → collect-CE5wK0AX.js} +1 -1
  37. package/dist/{compile-DNVVdVWs.js → compile-BXKYYmT1.js} +3 -3
  38. package/dist/{completion-DrJkWgZa.js → completion-B59uPAnZ.js} +1 -1
  39. package/dist/{config-D8iWeV9k.js → config-7QvEq57a.js} +2 -2
  40. package/dist/{config-BaKkd6HB.js → config-VCa1RLUe.js} +1 -1
  41. package/dist/{config-report-uuD5eVEn.js → config-report-CjvA6lGI.js} +1 -1
  42. package/dist/{context-Ne0EdD45.js → context-CAFddgb9.js} +1 -1
  43. package/dist/{custom-role-rebuild-BBKC7Bt1.js → custom-role-rebuild-BK73tPib.js} +1 -1
  44. package/dist/{doctor-Ch4VGl2q.js → doctor-ELj5hrVv.js} +2 -2
  45. package/dist/{doctor-C1T2G2mn.js → doctor-ervtBRzG.js} +61 -33
  46. package/dist/{execute-BhWXiQAy.js → execute-ix7AAdWg.js} +3 -3
  47. package/dist/{gen-CGjbD8I_.js → gen-8rW_AUG5.js} +2 -2
  48. package/dist/gen-BtiGMiuH.js +1 -0
  49. package/dist/{gen-kind-thoT0NYV.js → gen-kind-C9ikF8nb.js} +1 -1
  50. package/dist/{generate-vEW8Brg8.js → generate-BmpCt5oi.js} +3 -3
  51. package/dist/{generate-eor7vXGN.js → generate-CW7gNfLr.js} +16 -12
  52. package/dist/{generate-options-MJgn0dgl.js → generate-options-DiR4r_sk.js} +7 -7
  53. package/dist/{hook-sql-DJQ_yOEC.js → hook-sql-D-abRHut.js} +5 -5
  54. package/dist/{import-CGQIK3iN.js → import-BAhoTYTk.js} +1 -1
  55. package/dist/{init-C6te_dSg.js → init-DkRHIe8-.js} +3 -3
  56. package/dist/{init-DN19mlwE.js → init-zxb0BVDJ.js} +1 -1
  57. package/dist/{interactive-only-BjYwp9mm.js → interactive-only-Dqww0ABO.js} +18 -1
  58. package/dist/{keys-qFqDoYeF.js → keys-DQsHrgBM.js} +1 -1
  59. package/dist/{login-BYXaH_yT.js → login-C1p3gmj8.js} +1 -1
  60. package/dist/{login-CMzfsdm8.js → login-DOEZveP6.js} +3 -3
  61. package/dist/{manager-chain-CStuYb7A.js → manager-chain-DdkiCw5q.js} +1 -1
  62. package/dist/{manifest-CowZuywo.js → manifest-31igzVGQ.js} +33 -33
  63. package/dist/{manifest-DdNYR_pl.js → manifest-B487A3po.js} +1 -1
  64. package/dist/{manifest-CA3E0KP8.d.ts → manifest-DgsxeAsM.d.ts} +38 -1
  65. package/dist/{manifest-schema-CLbcbDz7.js → manifest-schema-D7RQbnGY.js} +44 -1
  66. package/dist/{model-BqHWwfcg.js → model-BXhr8gUI.js} +1 -1
  67. package/dist/next/index.d.ts +2 -1
  68. package/dist/next/index.js +2 -1
  69. package/dist/next/plugin.d.ts +1 -1
  70. package/dist/next/plugin.js +1 -1
  71. package/dist/{openapi-Dsh0MDSZ.js → openapi-BeMVHVY4.js} +1 -1
  72. package/dist/{openapi-BP7YpJeF.js → openapi-DEGesHWH.js} +1 -1
  73. package/dist/{openapi-document-_QSOtSKS.js → openapi-document-CEQ6jqqR.js} +1 -1
  74. package/dist/{output-Didy9Ys4.js → output-C7EPeSZj.js} +1 -1
  75. package/dist/{ownership-CG5_N8b5.js → ownership-Csk9C3Js.js} +8 -5
  76. package/dist/{pipeline-B4iyaOK7.js → pipeline-Bbu7uw28.js} +2 -2
  77. package/dist/{plugin-DQJuZVl1.d.ts → plugin-L3G7jPGE.d.ts} +1 -1
  78. package/dist/{policy-hnVT4MC4.js → policy-CSOOQ3rR.js} +1 -1
  79. package/dist/{policy-bundle-BIDV0DZF.js → policy-bundle-KYI0EnrM.js} +3 -3
  80. package/dist/{powersync-DUvN9v5a.js → powersync-C1ix7CEY.js} +1 -1
  81. package/dist/{powersync-D7YfMHke.js → powersync-CGvu6j5U.js} +1 -1
  82. package/dist/{powersync-_2ElzOhQ.js → powersync-CM6Vg4RH.js} +6 -6
  83. package/dist/{provider-D1vlNPWo.js → provider-BV_v0JAY.js} +18 -3
  84. package/dist/{prune-config-5vtQpiLk.js → prune-config-CdoPJIGz.js} +5 -5
  85. package/dist/{pull-BnxZmo3f.js → pull-BaB401Bk.js} +2 -2
  86. package/dist/pull-Bp63vtgu.js +1 -0
  87. package/dist/{push-Bu0uCkJg.js → push-DcjvEj0m.js} +1 -1
  88. package/dist/{rbac-CwcucZPx.js → rbac-mblGDx-Z.js} +1 -1
  89. package/dist/{rename-CLoDRrbc.js → rename-BZNOV8H9.js} +2 -2
  90. package/dist/report-DCAiUc5U.js +1 -0
  91. package/dist/{report-BI_hek_d.js → report-DievqWhf.js} +75 -5
  92. package/dist/{resolve-names-CTji5IPe.js → resolve-names-Cth1UQ-8.js} +2 -2
  93. package/dist/{rls-UY6p6ztg.js → rls-BtkZgaZp.js} +7 -2
  94. package/dist/{rls-BPHCyA5v.js → rls-DUYok5e9.js} +17 -7
  95. package/dist/{rls-files-CDZdTh8v.js → rls-files-ucAI0J5j.js} +1 -1
  96. package/dist/{rls-options-BgD-KZkm.d.ts → rls-options-BFGRmdcH.d.ts} +1 -1
  97. package/dist/run-BjMxYYTe.js +1 -0
  98. package/dist/{run-C3ztA88m.js → run-WIqPbnjD.js} +3 -3
  99. package/dist/{scan-m5m1M6Qn.js → scan-Badcllgg.js} +1 -1
  100. package/dist/{schema-BpGuLrwk.js → schema-DBRKgQb4.js} +1 -1
  101. package/dist/{skills-BytzDi34.js → skills-Ba9hHGO6.js} +1 -1
  102. package/dist/{skills-CzhnDo-C.js → skills-CTKq3o8D.js} +1 -1
  103. package/dist/{sources-D5n28164.d.ts → sources-CjgZns7t.d.ts} +1 -1
  104. package/dist/supabase/index.d.ts +3 -3
  105. package/dist/supabase/index.js +1 -1
  106. package/dist/{supabase-CAswAUeb.js → supabase-CGiB83XQ.js} +1 -1
  107. package/dist/supabase-hook-CluYxKee.js +2 -0
  108. package/dist/{supabase-hook-C0LIaT7b.js → supabase-hook-CqO_0Koh.js} +9 -183
  109. package/dist/{supabase-schemas-BUFeyErz.js → supabase-schemas-BglbAG2Z.js} +9 -8
  110. package/dist/table-reads-AnHPrBp8.js +517 -0
  111. package/dist/table-reads-BviGc0L_.js +1 -0
  112. package/dist/{tables-sLA1CpuN.js → tables-CDq0HVVq.js} +7 -4
  113. package/dist/tenant-check-D7g9oNVH.js +105 -0
  114. package/dist/testing/fixtures/index.d.ts +1 -1
  115. package/dist/testing/fixtures/index.js +14 -8
  116. package/dist/testing/index.d.ts +1 -1
  117. package/dist/testing/index.js +1 -1
  118. package/dist/{types-config-BiMM_zJ-.d.ts → types-config-DNIw_Gt5.d.ts} +1 -1
  119. package/dist/{types-run-N2ffLN_Z.d.ts → types-run-Bwn1MuW0.d.ts} +1 -1
  120. package/dist/unplugin/index.d.ts +1 -1
  121. package/dist/unplugin/index.js +1 -1
  122. package/dist/{usage-DT6QK86a.js → usage-CW6xhRcV.js} +2 -2
  123. package/dist/usage-Ci7Glu-H.js +1 -0
  124. package/dist/{usage-Dcbg6zu6.js → usage-n4V2k_a6.js} +1 -1
  125. package/dist/{verify-DNERav8K.js → verify-CKzngsUH.js} +3 -3
  126. package/dist/warm-5yxlUmBh.js +32 -0
  127. package/dist/warm-BR-mrnY-.d.ts +16 -0
  128. package/dist/{watch-BsQ4n3NV.js → watch-C12Ub7x4.js} +2 -2
  129. package/dist/{watch-fldErlRf.js → watch-D-5ztqN8.js} +1 -1
  130. package/dist/watch-J1PfGMfb.js +1 -0
  131. package/package.json +1 -1
  132. package/schemas/supabase-manifest-v1.json +109 -19
  133. package/skills/permdock-data/references/queries-and-rls.md +1 -1
  134. package/dist/gen-CkUEZ5Z6.js +0 -1
  135. package/dist/platform-CSxTsLsr.js +0 -35
  136. package/dist/pull-CGncYZNZ.js +0 -1
  137. package/dist/report-BevPHMy6.js +0 -1
  138. package/dist/run-3ySqmufy.js +0 -1
  139. package/dist/supabase-hook-DXGg5bNn.js +0 -2
  140. package/dist/tenant-check-gL2miiaS.js +0 -31
  141. package/dist/usage-DdOFc5xq.js +0 -1
  142. package/dist/watch-eay1PztJ.js +0 -1
@@ -0,0 +1,517 @@
1
+ import { r as isRecord } from "./compact-C4LFuqbW.js";
2
+ import { d as scopeList } from "./scopes-B-KX9EI8.js";
3
+ import { n as parseSupabaseManifest } from "./manifest-B487A3po.js";
4
+ import { i as readJsonFile } from "./files-DAR51W3J.js";
5
+ import { t as MANIFEST_FILE } from "./manifest-json-DMaBWmcG.js";
6
+ import { i as loadConfiguredPolicy } from "./load-m7jmit3y.js";
7
+ import { a as parseSqlFile, c as readPolicy, d as sqlCalls, f as stringValues, t as SqlSyntaxError } from "./ast-Dnm2TOHN.js";
8
+ import { i as taggedAccessPolicies } from "./bsb-access-Bcw6GrQm.js";
9
+ import { a as droppedPolicy, s as reportFiles, u as isPlatformSchema } from "./report-DievqWhf.js";
10
+ import { a as tryKeyReasons, n as tenantCheck, r as keyReason } from "./tenant-check-D7g9oNVH.js";
11
+ import { existsSync, readFileSync } from "node:fs";
12
+ import { join, relative } from "node:path";
13
+ // src/cli/rls/shared-functions.ts
14
+ /** Functions that read who is asking, so the result differs per caller. */
15
+ const IDENTITY_FUNCTIONS = /* @__PURE__ */ new Set([
16
+ "current_setting",
17
+ "current_user_id",
18
+ "permdock_user_id",
19
+ "permdock_subject",
20
+ "uid",
21
+ "jwt",
22
+ "role",
23
+ "email"
24
+ ]);
25
+ /** `SQLValueFunction` ops that name the caller. */
26
+ const IDENTITY_VALUES = /* @__PURE__ */ new Set([
27
+ "SVFOP_CURRENT_USER",
28
+ "SVFOP_SESSION_USER",
29
+ "SVFOP_USER",
30
+ "SVFOP_CURRENT_ROLE"
31
+ ]);
32
+ const DEFAULT_SCHEMA = "public";
33
+ function defElems(node) {
34
+ const options = Array.isArray(node["options"]) ? node["options"] : [];
35
+ const found = {};
36
+ for (const option of options) {
37
+ const def = isRecord(option) ? option["DefElem"] : void 0;
38
+ if (isRecord(def) && typeof def["defname"] === "string") found[def["defname"]] = def["arg"];
39
+ }
40
+ return found;
41
+ }
42
+ function sval(arg) {
43
+ const text = isRecord(arg) ? arg["String"] : void 0;
44
+ return isRecord(text) && typeof text["sval"] === "string" ? text["sval"].toLowerCase() : void 0;
45
+ }
46
+ function bodyOf(arg) {
47
+ const list = isRecord(arg) ? arg["List"] : void 0;
48
+ return stringValues(isRecord(list) ? list["items"] : []).join("");
49
+ }
50
+ /** Every value stored under `key` anywhere inside `value`. */
51
+ function collect(value, key) {
52
+ const out = [];
53
+ const visit = (item) => {
54
+ if (Array.isArray(item)) {
55
+ for (const child of item) visit(child);
56
+ return;
57
+ }
58
+ if (!isRecord(item)) return;
59
+ for (const [name, child] of Object.entries(item)) {
60
+ if (name === key) out.push(child);
61
+ visit(child);
62
+ }
63
+ };
64
+ visit(value);
65
+ return out;
66
+ }
67
+ /**
68
+ * Whether `node` is a `language sql`, `security invoker`, `stable` or
69
+ * `immutable` function with a body libpg_query parses; `volatile` is the
70
+ * default, so a function that states nothing is not eligible.
71
+ */
72
+ function definitionOf(node) {
73
+ const parts = stringValues(node["funcname"]);
74
+ const name = parts.at(-1);
75
+ if (name === void 0) return;
76
+ const schema = (parts.length > 1 ? parts[0] : DEFAULT_SCHEMA) ?? DEFAULT_SCHEMA;
77
+ const defs = defElems(node);
78
+ const security = defs["security"];
79
+ const definer = isRecord(security) ? isRecord(security["Boolean"]) && security["Boolean"]["boolval"] === true : false;
80
+ const volatility = sval(defs["volatility"]);
81
+ return {
82
+ schema: schema.toLowerCase(),
83
+ name: name.toLowerCase(),
84
+ body: bodyOf(defs["as"]),
85
+ eligible: sval(defs["language"]) === "sql" && !definer && (volatility === "stable" || volatility === "immutable")
86
+ };
87
+ }
88
+ /**
89
+ * The tables a body reads and the functions it calls, or `undefined` when it
90
+ * reads the caller, calls a function outside `known`, or reads a relation that
91
+ * is not a table in `reads`.
92
+ */
93
+ async function readsOf(definition, defined, reads, helperSchema) {
94
+ let statements;
95
+ try {
96
+ statements = await parseSqlFile(definition.body);
97
+ } catch (error) {
98
+ if (error instanceof SqlSyntaxError) return;
99
+ throw error;
100
+ }
101
+ const tables = /* @__PURE__ */ new Set();
102
+ const calls = /* @__PURE__ */ new Set();
103
+ for (const statement of statements) {
104
+ if (statement.kind !== "SelectStmt") return;
105
+ if (collect(statement.node, "SQLValueFunction").some((value) => isRecord(value) && typeof value["op"] === "string" && IDENTITY_VALUES.has(value["op"]))) return;
106
+ const ctes = new Set(collect(statement.node, "CommonTableExpr").flatMap((value) => isRecord(value) && typeof value["ctename"] === "string" ? [value["ctename"].toLowerCase()] : []));
107
+ for (const value of collect(statement.node, "RangeVar")) {
108
+ if (!isRecord(value) || typeof value["relname"] !== "string") return;
109
+ const relname = value["relname"].toLowerCase();
110
+ const explicit = typeof value["schemaname"] === "string" ? value["schemaname"].toLowerCase() : void 0;
111
+ if (explicit === void 0 && ctes.has(relname)) continue;
112
+ const found = (explicit === void 0 ? [definition.schema, DEFAULT_SCHEMA] : [explicit]).map((schema) => `${schema}.${relname}`).find((table) => reads.has(table));
113
+ if (found === void 0) return;
114
+ tables.add(found);
115
+ }
116
+ for (const call of sqlCalls(statement.node)) {
117
+ const last = call.name.at(-1);
118
+ const schema = call.name.length > 1 ? call.name[0] : void 0;
119
+ if (last === void 0 || IDENTITY_FUNCTIONS.has(last) || schema === "auth") return;
120
+ if (schema === helperSchema) return;
121
+ const target = (schema === void 0 ? [`${definition.schema}.${last}`, `${DEFAULT_SCHEMA}.${last}`] : [`${schema}.${last}`]).find((name) => defined.has(name));
122
+ if (target !== void 0) calls.add(target);
123
+ else if (schema !== void 0 && schema !== "pg_catalog") return;
124
+ }
125
+ }
126
+ return {
127
+ tables,
128
+ calls
129
+ };
130
+ }
131
+ /**
132
+ * `rls.sharedFunctions`: the functions better-supabase's doctor BS430 accepts
133
+ * in a `share: "tenant"` fill, read from the same SQL files as `tableReads`. A
134
+ * function is listed when it is `language sql`, `security invoker` and `stable`
135
+ * or `immutable`, parses, reads the caller through neither `auth.*`,
136
+ * `current_user`, `current_setting` nor a helper of the `helperSchema`, calls
137
+ * only other listed functions or built-ins, and reads only tables that
138
+ * `tableReads` marks `tenant`. An overloaded name is listed when every overload
139
+ * qualifies. A file libpg_query rejects is skipped; the last definition of a
140
+ * function wins.
141
+ */
142
+ async function sharedFunctionsOf(input) {
143
+ const reads = new Map(input.tableReads.map((read) => [read.table, read]));
144
+ const byArity = /* @__PURE__ */ new Map();
145
+ for (const file of reportFiles(input.cwd, input.config)) {
146
+ let nodes;
147
+ try {
148
+ nodes = await parseSqlFile(readFileSync(file, "utf8"));
149
+ } catch (error) {
150
+ if (error instanceof SqlSyntaxError) continue;
151
+ throw error;
152
+ }
153
+ for (const node of nodes) {
154
+ if (node.kind !== "CreateFunctionStmt") continue;
155
+ const definition = definitionOf(node.node);
156
+ if (definition === void 0) continue;
157
+ const params = collect(node.node["parameters"], "FunctionParameter").map((value) => isRecord(value) && isRecord(value["argType"]) ? stringValues(value["argType"]["names"]).join(".") : "").join(",");
158
+ byArity.set(`${definition.schema}.${definition.name}(${params})`, definition);
159
+ }
160
+ }
161
+ const defined = /* @__PURE__ */ new Map();
162
+ for (const definition of byArity.values()) {
163
+ const key = `${definition.schema}.${definition.name}`;
164
+ defined.set(key, [...defined.get(key) ?? [], definition]);
165
+ }
166
+ const helperSchema = input.schema.toLowerCase();
167
+ const analysed = /* @__PURE__ */ new Map();
168
+ for (const [name, overloads] of defined) {
169
+ const merged = [];
170
+ for (const definition of overloads) {
171
+ const found = definition.eligible ? await readsOf(definition, defined, reads, helperSchema) : void 0;
172
+ if (found === void 0) break;
173
+ merged.push(found);
174
+ }
175
+ if (merged.length === overloads.length && merged.length > 0) analysed.set(name, {
176
+ tables: new Set(merged.flatMap((entry) => [...entry.tables])),
177
+ calls: new Set(merged.flatMap((entry) => [...entry.calls]))
178
+ });
179
+ }
180
+ for (let changed = true; changed;) {
181
+ changed = false;
182
+ for (const [name, entry] of analysed) if ([...entry.calls].some((call) => !analysed.has(call))) {
183
+ analysed.delete(name);
184
+ changed = true;
185
+ }
186
+ }
187
+ const close = (name, seen) => {
188
+ if (seen.has(name)) return;
189
+ seen.add(name);
190
+ for (const call of analysed.get(name)?.calls ?? []) close(call, seen);
191
+ };
192
+ return [...analysed.keys()].toSorted().flatMap((name) => {
193
+ const reached = /* @__PURE__ */ new Set();
194
+ close(name, reached);
195
+ const tables = /* @__PURE__ */ new Set();
196
+ for (const member of reached) for (const table of analysed.get(member)?.tables ?? []) tables.add(table);
197
+ if (tables.size === 0 || [...tables].some((table) => reads.get(table)?.share !== "tenant")) return [];
198
+ return [{
199
+ function: name,
200
+ tables: [...tables].toSorted(),
201
+ permissions: [...new Set([...tables].flatMap((table) => reads.get(table)?.permissions ?? []))].toSorted()
202
+ }];
203
+ });
204
+ }
205
+ /**
206
+ * `rls.tenantPureHelpers`: the helpers of the root scope that answer from the
207
+ * caller's grants of the passed key in the passed tenant and nothing else, so
208
+ * two callers with an equal `grantFingerprint` for the key get one answer.
209
+ *
210
+ * - `permdock_<root>_has(p_grant, p_tenant)` tests one grant key in one tenant.
211
+ * - `permitted_<root>_permission_keys(p_id, p_keys)` lists which of `p_keys` the
212
+ * caller holds on one tenant.
213
+ *
214
+ * Every other helper reads grants outside the tenant (`permitted_<root>_ids`,
215
+ * `permitted_<root>_ids_by_permission`, `permitted_<root>_id_array`,
216
+ * `permdock_has`), a decision of one row (`permitted_<resource>_rows`) or the
217
+ * caller (`permdock_subject`, `permdock_bootstrap_permissions`), and is left
218
+ * out. `rls generate` writes both for every scope, so the manifest names them
219
+ * whenever it has an `rls` block.
220
+ */
221
+ function tenantPureHelpersOf(manifest) {
222
+ const root = manifest.rls.scopes[0]?.name;
223
+ if (root === void 0) return [];
224
+ const prefix = `permitted_${root}`;
225
+ return [{
226
+ name: `permdock_${root}_has`,
227
+ keyArgument: "p_grant",
228
+ tenantArgument: "p_tenant"
229
+ }, {
230
+ name: `${prefix}_permission_keys`,
231
+ keyArgument: "p_keys",
232
+ tenantArgument: "p_id"
233
+ }].map((candidate) => ({
234
+ ...candidate,
235
+ name: `${manifest.rls.schema}.${candidate.name}`
236
+ }));
237
+ }
238
+ // src/cli/rls/table-reads.ts
239
+ /** better-supabase's own tables, which its block SQL owns. */
240
+ const LIBRARY_SCHEMAS = /* @__PURE__ */ new Set(["better_supabase"]);
241
+ function relationName(relation) {
242
+ if (!isRecord(relation) || typeof relation["relname"] !== "string") return;
243
+ return `${typeof relation["schemaname"] === "string" ? relation["schemaname"] : "public"}.${relation["relname"]}`.toLowerCase();
244
+ }
245
+ /** The qualified tables a `drop table` statement removes, lower case. */
246
+ function droppedTables(node) {
247
+ const objects = node["objects"];
248
+ if (node["removeType"] !== "OBJECT_TABLE" || !Array.isArray(objects)) return [];
249
+ return objects.flatMap((object) => {
250
+ const list = isRecord(object) ? object["List"] : void 0;
251
+ const items = isRecord(list) ? list["items"] : void 0;
252
+ const parts = stringValues(items);
253
+ const name = parts.at(-1);
254
+ return name === void 0 ? [] : [`${parts.length > 1 ? parts.at(-2) : "public"}.${name}`.toLowerCase()];
255
+ });
256
+ }
257
+ /** `alter table <from> rename to <to>`: the two qualified names, lower case. */
258
+ function renamedTable(node) {
259
+ const from = relationName(node["relation"]);
260
+ const name = node["newname"];
261
+ if (node["renameType"] !== "OBJECT_TABLE" || from === void 0 || typeof name !== "string") return;
262
+ return {
263
+ from,
264
+ to: `${from.slice(0, from.indexOf("."))}.${name.toLowerCase()}`
265
+ };
266
+ }
267
+ function renameTable(created, facts, renamed) {
268
+ if (renamed === void 0) return;
269
+ created.delete(renamed.from);
270
+ created.add(renamed.to);
271
+ const moved = facts.get(renamed.from);
272
+ facts.delete(renamed.from);
273
+ if (moved !== void 0) facts.set(renamed.to, moved);
274
+ }
275
+ function enablesRls(node) {
276
+ return (Array.isArray(node["cmds"]) ? node["cmds"] : []).some((cmd) => {
277
+ const alter = isRecord(cmd) ? cmd["AlterTableCmd"] : void 0;
278
+ return isRecord(alter) && alter["subtype"] === "AT_EnableRowSecurity";
279
+ });
280
+ }
281
+ function readsColumn(expr) {
282
+ if (Array.isArray(expr)) return expr.some((item) => readsColumn(item));
283
+ if (!isRecord(expr)) return false;
284
+ return Object.entries(expr).some(([key, child]) => key === "ColumnRef" || readsColumn(child));
285
+ }
286
+ function appliesToSelect(policy) {
287
+ return (policy.command === "select" || policy.command === "all") && policy.roles.some((role) => role === "authenticated" || role === "public");
288
+ }
289
+ /** The rule a permissive select policy that is not the tenant form breaks. */
290
+ function ruleOf(policy, plainHelper) {
291
+ const names = sqlCalls(policy.using).map((call) => call.name.join("."));
292
+ if (names.length > 0 && names.every((name) => name === plainHelper)) return "form";
293
+ if (names.some((name) => name.includes("follows"))) return "follows";
294
+ if (names.some((name) => name.includes("_via"))) return "via";
295
+ if (names.some((name) => name.includes("walk"))) return "walk";
296
+ if (names.some((name) => name === "auth.uid" || name.endsWith("permdock_user_id"))) return "owner";
297
+ return policy.using === void 0 ? "unknown" : "condition";
298
+ }
299
+ function keysOf(expr, helper) {
300
+ return sqlCalls(expr).flatMap((call) => {
301
+ if (call.name.join(".") !== helper) return [];
302
+ const args = Array.isArray(call.node["args"]) ? call.node["args"] : [];
303
+ const [first] = args;
304
+ const cast = isRecord(first) ? first["TypeCast"] : void 0;
305
+ const inner = isRecord(cast) && isRecord(cast["arg"]) ? cast["arg"] : first;
306
+ const constant = args.length === 1 && isRecord(inner) ? inner["A_Const"] : void 0;
307
+ const value = isRecord(constant) && isRecord(constant["sval"]) ? constant["sval"]["sval"] : void 0;
308
+ return typeof value === "string" ? [value] : [];
309
+ });
310
+ }
311
+ function readOf(table, facts, helpers, fieldTables, reasons) {
312
+ if (facts === void 0 || !facts.rls) return {
313
+ table,
314
+ share: "row",
315
+ rules: ["unknown"]
316
+ };
317
+ const selects = [...facts.policies.values()].filter(appliesToSelect);
318
+ const permissive = selects.filter((policy) => policy.permissive);
319
+ const rules = /* @__PURE__ */ new Set();
320
+ const columns = /* @__PURE__ */ new Set();
321
+ const keys = /* @__PURE__ */ new Set();
322
+ const formKeys = /* @__PURE__ */ new Set();
323
+ const stale = [];
324
+ const hasTag = [...facts.policies.values()].some((p) => p.tagged !== void 0);
325
+ if (fieldTables.has(table)) rules.add("fields");
326
+ if (permissive.length === 0) rules.add("unknown");
327
+ for (const policy of permissive) {
328
+ const check = policy.tagged ?? tenantCheck(policy.using, helpers.byPermission);
329
+ for (const key of policy.tagged === void 0 ? keysOf(policy.using, helpers.byPermission) : [policy.tagged.key]) keys.add(key);
330
+ if (check === void 0) {
331
+ const rule = ruleOf(policy, helpers.plain);
332
+ rules.add(rule);
333
+ if (rule === "form") {
334
+ if (hasTag) stale.push(policy);
335
+ for (const key of keysOf(policy.using, helpers.plain)) formKeys.add(key);
336
+ }
337
+ } else columns.add(check.column);
338
+ }
339
+ if (selects.some((policy) => !policy.permissive && readsColumn(policy.using))) rules.add("restrictive");
340
+ if (rules.size === 0 && columns.size > 1) rules.add("condition");
341
+ const permissions = [...keys].toSorted();
342
+ const listed = permissions.length === 0 ? {} : { permissions };
343
+ if (rules.size > 0) {
344
+ const parts = [...stale.map((policy) => `policy ${policy.name} is still defined${policy.file === void 0 ? "" : ` in ${policy.file}`} next to an @bsb access tag that renders the table's policy: write a migration that drops it`), ...reasons === void 0 || stale.length > 0 ? [] : [...formKeys].toSorted().map((key) => `key ${key}: ${keyReason(reasons, key)}`)];
345
+ const why = parts.length === 0 ? void 0 : parts.join("; ");
346
+ return {
347
+ table,
348
+ share: "row",
349
+ ...listed,
350
+ rules: [...rules].toSorted(),
351
+ ...why === void 0 ? {} : { reason: why }
352
+ };
353
+ }
354
+ const [column] = columns;
355
+ return {
356
+ table,
357
+ share: "tenant",
358
+ ...column === void 0 ? {} : { column },
359
+ ...listed
360
+ };
361
+ }
362
+ /**
363
+ * `rls.tableReads`: for each table the schema files and migrations create, from
364
+ * the select policies they leave defined plus the policies `@bsb access` tags
365
+ * render. A table is `tenant` only when row level security is on, it has no
366
+ * field view, every permissive select policy for `authenticated` is `<column>
367
+ * in (select <schema>.permitted_<root>_ids_by_permission('<key>'))` on one
368
+ * column, and every restrictive select policy reads no column of the row.
369
+ * Everything else is `row`, with the rules it breaks. Tables in the helpers'
370
+ * schema, `better_supabase` and platform schemas are left out. A file
371
+ * libpg_query rejects is skipped. The files are read from disk, so select
372
+ * policies a `generate` run changes in `rls.out` are recorded on the next run.
373
+ */
374
+ async function tableReads(input) {
375
+ const created = /* @__PURE__ */ new Set();
376
+ const facts = /* @__PURE__ */ new Map();
377
+ const factsOf = (table) => {
378
+ const found = facts.get(table) ?? {
379
+ rls: false,
380
+ policies: /* @__PURE__ */ new Map()
381
+ };
382
+ facts.set(table, found);
383
+ return found;
384
+ };
385
+ for (const file of reportFiles(input.cwd, input.config)) {
386
+ let nodes;
387
+ try {
388
+ nodes = await parseSqlFile(readFileSync(file, "utf8"));
389
+ } catch (error) {
390
+ if (error instanceof SqlSyntaxError) continue;
391
+ throw error;
392
+ }
393
+ for (const node of nodes) if (node.kind === "CreateStmt") {
394
+ const table = relationName(node.node["relation"]);
395
+ if (table !== void 0) created.add(table);
396
+ } else if (node.kind === "AlterTableStmt" && enablesRls(node.node)) {
397
+ const table = relationName(node.node["relation"]);
398
+ if (table !== void 0) factsOf(table).rls = true;
399
+ } else if (node.kind === "DropStmt") {
400
+ const dropped = droppedPolicy(node.node);
401
+ if (dropped !== void 0) facts.get(`${dropped.schema}.${dropped.table}`.toLowerCase())?.policies.delete(dropped.name);
402
+ for (const table of droppedTables(node.node)) {
403
+ created.delete(table);
404
+ facts.delete(table);
405
+ }
406
+ } else if (node.kind === "RenameStmt") renameTable(created, facts, renamedTable(node.node));
407
+ else {
408
+ const policy = readPolicy(node);
409
+ if (policy !== void 0) factsOf(`${policy.schema}.${policy.table}`.toLowerCase()).policies.set(policy.name, {
410
+ ...policy,
411
+ file: relative(input.cwd, file)
412
+ });
413
+ }
414
+ }
415
+ for (const tagged of await taggedAccessPolicies(input.cwd)) {
416
+ if (tagged.operation.toLowerCase() !== "read") continue;
417
+ factsOf(`${tagged.schema}.${tagged.table}`.toLowerCase()).policies.set(tagged.name, {
418
+ name: tagged.name,
419
+ command: "select",
420
+ permissive: true,
421
+ roles: ["authenticated"],
422
+ tagged: {
423
+ column: tagged.tenantColumn,
424
+ key: tagged.key
425
+ }
426
+ });
427
+ }
428
+ const helpers = {
429
+ plain: `${input.schema}.permitted_${input.root}_ids`,
430
+ byPermission: `${input.schema}.permitted_${input.root}_ids_by_permission`
431
+ };
432
+ const helperSchema = input.schema.toLowerCase();
433
+ return [...created].filter((table) => {
434
+ const schema = table.slice(0, table.indexOf("."));
435
+ return schema !== helperSchema && !LIBRARY_SCHEMAS.has(schema) && !isPlatformSchema(schema);
436
+ }).toSorted().map((table) => readOf(table, facts.get(table), helpers, input.fieldTables ?? /* @__PURE__ */ new Set(), input.reasons));
437
+ }
438
+ /** `tableReads` for the helpers, root scope and field views `manifest` names. */
439
+ function manifestTableReads(cwd, config, manifest, reasons) {
440
+ const root = manifest.rls.scopes[0]?.name;
441
+ if (root === void 0) return Promise.resolve([]);
442
+ const fieldTables = new Set(Object.values(manifest.names?.resources ?? {}).flatMap((names) => names.table === void 0 || names.visible === void 0 ? [] : [(names.table.includes(".") ? names.table : `public.${names.table}`).toLowerCase()]));
443
+ return tableReads({
444
+ cwd,
445
+ config,
446
+ schema: manifest.rls.schema,
447
+ root,
448
+ fieldTables,
449
+ ...reasons === void 0 ? {} : { reasons }
450
+ });
451
+ }
452
+ /**
453
+ * `manifest` with `rls.tableReads` from the files on disk; unchanged when the
454
+ * files create no table.
455
+ */
456
+ async function withTableReads(cwd, config, manifest, reasons) {
457
+ const reads = await manifestTableReads(cwd, config, manifest, reasons);
458
+ const tenantPureHelpers = tenantPureHelpersOf(manifest);
459
+ const pure = tenantPureHelpers.length === 0 ? {} : { tenantPureHelpers };
460
+ if (reads.length === 0) return {
461
+ ...manifest,
462
+ rls: {
463
+ ...manifest.rls,
464
+ ...pure
465
+ }
466
+ };
467
+ const sharedFunctions = await sharedFunctionsOf({
468
+ cwd,
469
+ config,
470
+ schema: manifest.rls.schema,
471
+ tableReads: reads
472
+ });
473
+ return {
474
+ ...manifest,
475
+ rls: {
476
+ ...manifest.rls,
477
+ tableReads: reads,
478
+ sharedFunctions,
479
+ ...pure
480
+ }
481
+ };
482
+ }
483
+ /**
484
+ * The committed `permdock.manifest.json`, or `undefined` when it is absent or
485
+ * unreadable.
486
+ */
487
+ function committedManifest(cwd) {
488
+ const path = join(cwd, MANIFEST_FILE);
489
+ if (!existsSync(path)) return;
490
+ try {
491
+ return parseSupabaseManifest(readJsonFile(path));
492
+ } catch {
493
+ return;
494
+ }
495
+ }
496
+ /**
497
+ * `tableReads` for the configured policy, with the reason of each `form` table.
498
+ * Field views come from the committed manifest when there is one. Without a
499
+ * policy the answer is empty; a policy the generator refuses leaves out the
500
+ * reasons only.
501
+ */
502
+ async function configuredTableReads(cwd, config) {
503
+ const policy = await loadConfiguredPolicy(cwd, config.policy);
504
+ const root = policy === void 0 ? void 0 : scopeList(policy.scopes)[0]?.name;
505
+ if (policy === void 0 || root === void 0) return [];
506
+ const reasons = tryKeyReasons(config, policy, cwd);
507
+ const manifest = committedManifest(cwd);
508
+ if (manifest !== void 0) return manifestTableReads(cwd, config, manifest, reasons);
509
+ return tableReads({
510
+ cwd,
511
+ config,
512
+ schema: config.rls?.schema ?? "permdock",
513
+ root,
514
+ ...reasons === void 0 ? {} : { reasons }
515
+ });
516
+ }
517
+ export { withTableReads as a, tableReads as i, configuredTableReads as n, sharedFunctionsOf as o, manifestTableReads as r, committedManifest as t };
@@ -0,0 +1 @@
1
+ export { t as committedManifest, n as configuredTableReads, r as manifestTableReads, i as tableReads, a as withTableReads } from "./table-reads-AnHPrBp8.js";
@@ -13,7 +13,7 @@ import { t as AUTHZ_VERSION_TABLE } from "./sources-DnjJPGfb.js";
13
13
  import { a as quoteIdent, c as quoteTable, i as qualified, o as quoteLiteral, r as helperSchema, s as quoteQualified } from "./quote-BKrTBbcH.js";
14
14
  import { C as tenantTypeOf, a as kindFilterSql, b as idTypeOf, c as roleKindSql, d as subjectClaimSql, f as subjectIdSql, i as keyTenantSql, m as userIdHelperSql, s as memberVia, u as subjectClaimJsonSql, x as scopeTypeOf } from "./subject-CrldGifz.js";
15
15
  import { i as allowEntry, n as GLOBAL_ROLES, o as rootName, r as HELPERS, s as signedIn, t as CUSTOM_ROLES } from "./shared-C6_T7QUo.js";
16
- import { $ as memberForSources, A as userActive, B as trustedReaderGrants, C as sourcesKeep, D as keyTenantLine, E as instancesActive, F as perScope, G as graphSqlText, H as CLOSURE, I as raiseSql, K as hasMemberFor, L as roleReadersSql, M as currentKeyExpr, N as customRolesSql, P as hasCustomRoleChecksFor, Q as memberForHelper, R as rolesTableScope, S as sourcesBodyOf, U as graphHelper, W as graphSqlName, X as isTeamScope, Z as linkHelper, _ as memoizes, a as interactiveSessionSql, at as permittedIdsHelper, b as sourceIdOf, c as claimTenant, ct as scopeTable, d as hasBody, dt as activeRowSql, ft as activeUserSql, g as memoizedSetofSql, h as memoWriteSql, it as permittedForHelper, j as globalRoleSource, l as disabledColumn, lt as activeInstancesSql, m as memoHitList, mt as grantPermissionSql, n as interactiveAllowsCall, nt as memberOfHelper, o as memoUserSql, ot as restrictedHelper, p as memberColumn, q as hasMemberOf, r as interactiveAllowsSql, rt as memberRoleOf, s as claimKeptLines, st as scopeSources, tt as memberIdsHelper, u as functionBody, ut as activeMembershipSql, v as scopedBody, w as sqlBody, x as sourceRows, y as sourceFilters, z as storedTenant } from "./interactive-only-BjYwp9mm.js";
16
+ import { $ as linkHelper, B as rolesTableScope, C as sourceRows, E as sqlBody, F as customRolesSql, G as graphHelper, H as trustedReaderGrants, I as hasCustomRoleChecksFor, J as hasMemberFor, K as graphSqlName, L as perScope, M as userActive, N as globalRoleSource, O as instancesActive, P as currentKeyExpr, Q as isTeamScope, R as raiseSql, S as sourceIdOf, T as sourcesKeep, V as storedTenant, W as CLOSURE, Y as hasMemberOf, _ as memoWriteSql, at as memberRoleOf, b as scopedBody, c as memoUserSql, ct as restrictedHelper, d as disabledColumn, dt as activeInstancesSql, et as memberForHelper, f as functionBody, ft as activeMembershipSql, g as memoHitList, gt as grantPermissionSql, h as memberColumn, i as interactiveAllowsSql, it as memberOfHelper, k as keyTenantLine, l as claimKeptLines, lt as scopeSources, mt as activeUserSql, n as delegatedGlobalSql, o as interactiveSessionSql, ot as permittedForHelper, p as hasBody, pt as activeRowSql, q as graphSqlText, r as interactiveAllowsCall, rt as memberIdsHelper, s as memoGlobalUserSql, st as permittedIdsHelper, tt as memberForSources, u as claimTenant, ut as scopeTable, v as memoizedSetofSql, w as sourcesBodyOf, x as sourceFilters, y as memoizes, z as roleReadersSql } from "./interactive-only-Dqww0ABO.js";
17
17
  import { n as byKey, t as byCodeUnit } from "./compare-8SNJN-9U.js";
18
18
  import { createHash } from "node:crypto";
19
19
  // src/cli/rls/graph.ts
@@ -2527,7 +2527,7 @@ function memoBody(ctx, scope, type, body) {
2527
2527
  memo: {
2528
2528
  type,
2529
2529
  scope,
2530
- user: memoUserSql(ctx, subjectIdSql(ctx)),
2530
+ user: scope === "global" ? memoGlobalUserSql(ctx, subjectIdSql(ctx)) : memoUserSql(ctx, subjectIdSql(ctx)),
2531
2531
  ...ctx.memo === void 0 ? {} : { api: ctx.memo }
2532
2532
  }
2533
2533
  };
@@ -2553,7 +2553,9 @@ function grantBodies(ctx) {
2553
2553
  };
2554
2554
  const allows = ceiling(set ? "ids.grant_key" : "p_grant", true);
2555
2555
  const keyTenant = keys === void 0 ? "" : ` and ${keyTenantSql(ctx, void 0) ?? "true"}`;
2556
- const hasAllows = ceiling(set ? "g.grant_key" : "p_grant", false);
2556
+ const delegated = delegatedGlobalSql(ctx);
2557
+ const hasCeiling = ceiling(set ? "g.grant_key" : "p_grant", false);
2558
+ const hasAllows = hasCeiling === void 0 ? delegated : delegated === void 0 ? hasCeiling : `${hasCeiling} and ${delegated}`;
2557
2559
  return {
2558
2560
  has: memoBody(ctx, "global", "boolean", sqlBody(hasAllows === void 0 ? hasBody(ctx) : set ? ` select g.grant_key
2559
2561
  from (
@@ -2583,7 +2585,8 @@ function forUserContext(ctx) {
2583
2585
  return {
2584
2586
  ...unkeyed,
2585
2587
  subjectId: "p_user",
2586
- tenants: "all"
2588
+ tenants: "all",
2589
+ namedUser: true
2587
2590
  };
2588
2591
  }
2589
2592
  // src/cli/rls/ownership-names.ts
@@ -0,0 +1,105 @@
1
+ import { r as isRecord } from "./compact-C4LFuqbW.js";
2
+ import { n as CliError } from "./errors-DgLOqc6j.js";
3
+ import { i as tableNames } from "./tables-CDq0HVVq.js";
4
+ import { r as compileGrants } from "./compile-BXKYYmT1.js";
5
+ import { i as buildContext, n as isRefusal, t as generateOptions } from "./generate-options-DiR4r_sk.js";
6
+ // src/cli/rls/key-reasons.ts
7
+ /** A grant key written as a condition group (`k#1`) or a level (`k@own`). */
8
+ function isConditionKey(permission, grantKey) {
9
+ return grantKey.startsWith(`${permission}#`) || grantKey.startsWith(`${permission}@`);
10
+ }
11
+ /** Why `row` is not an unconditional allow of its own key, or `undefined`. */
12
+ function whyNot(row, conditioned) {
13
+ const holder = `role ${row.role} on ${row.scope}`;
14
+ if (row.effect === "deny") return `${holder} denies it`;
15
+ if (row.grantKey !== row.permission) return isConditionKey(row.permission, row.grantKey) ? `${holder} grants it under a condition (grant key ${row.grantKey})` : `${holder} grants it through another key (${row.grantKey})`;
16
+ if (conditioned.has(row.grantKey)) return `${holder} grants it under a row condition or a validity window`;
17
+ }
18
+ /**
19
+ * Reads the compiled grants of `policy` and sorts each permission key into the
20
+ * ones the by-permission helper answers like the plain one, and the ones it
21
+ * does not, with the first grant that decides it.
22
+ */
23
+ function keyReasons(config, policy, cwd) {
24
+ const generate = {
25
+ cwd,
26
+ config,
27
+ target: "sql",
28
+ dialect: config.rls?.dialect ?? "supabase",
29
+ rbac: false,
30
+ check: false,
31
+ skipClosures: true,
32
+ inlineFunctions: false,
33
+ io: {
34
+ stdout: () => void 0,
35
+ stderr: () => void 0
36
+ }
37
+ };
38
+ const options = generateOptions(generate);
39
+ if (isRefusal(options)) throw new CliError("usage", options.refusal, { code: "invalid_value" });
40
+ const built = buildContext(generate, policy, options);
41
+ if (isRefusal(built)) throw new CliError("usage", built.refusal, { code: "invalid_value" });
42
+ const compiled = compileGrants(policy, built.ctx, tableNames(config.rls?.tables), [], true);
43
+ const found = /* @__PURE__ */ new Map();
44
+ const ok = /* @__PURE__ */ new Set();
45
+ for (const row of compiled.rolePermissions) {
46
+ ok.add(row.permission);
47
+ const why = whyNot(row, compiled.conditionedKeys);
48
+ if (why === void 0) continue;
49
+ const entry = found.get(row.permission);
50
+ const replace = entry === void 0 || row.effect === "deny" && !entry.deny;
51
+ found.set(row.permission, {
52
+ count: (entry?.count ?? 0) + 1,
53
+ first: replace ? why : entry.first,
54
+ deny: replace ? row.effect === "deny" : entry.deny
55
+ });
56
+ }
57
+ const reasons = new Map([...found].map(([key, { count, first }]) => [key, count === 1 ? first : `${first}; ${String(count - 1)} more grants differ`]));
58
+ return {
59
+ swappable: new Set([...ok].filter((key) => !reasons.has(key))),
60
+ reasons
61
+ };
62
+ }
63
+ /** The sentence for `key`, which `reasons` may not know. */
64
+ function keyReason(reasons, key) {
65
+ return reasons.reasons.get(key) ?? (reasons.swappable.has(key) ? "every grant of it is unconditional; permdock codemod bsb-access-tags moves the policy unless another policy or tenant column on the table prevents it" : "the policy declares no grant of it");
66
+ }
67
+ /** `keyReasons`, or `undefined` for a policy or config the generator refuses. */
68
+ function tryKeyReasons(config, policy, cwd) {
69
+ try {
70
+ return keyReasons(config, policy, cwd);
71
+ } catch (error) {
72
+ if (error instanceof CliError) return;
73
+ throw error;
74
+ }
75
+ }
76
+ // src/cli/sql/tenant-check.ts
77
+ /** The `sval` of each `String` node in a parse-tree list. */
78
+ function svals(list) {
79
+ return Array.isArray(list) ? list.flatMap((item) => isRecord(item) && isRecord(item["String"]) && typeof item["String"]["sval"] === "string" ? [item["String"]["sval"]] : []) : [];
80
+ }
81
+ /**
82
+ * `<column> in (select <schema>.permitted_<scope>_ids('<key>'))`, read from the
83
+ * node.
84
+ */
85
+ function tenantCheck(expr, helper) {
86
+ const link = isRecord(expr) ? expr["SubLink"] : void 0;
87
+ if (!isRecord(link) || link["subLinkType"] !== "ANY_SUBLINK") return;
88
+ const test = link["testexpr"];
89
+ const ref = isRecord(test) ? test["ColumnRef"] : void 0;
90
+ const column = isRecord(ref) ? svals(ref["fields"]) : [];
91
+ const select = isRecord(link["subselect"]) ? link["subselect"]["SelectStmt"] : void 0;
92
+ if (column.length !== 1 || !isRecord(select) || select["fromClause"] !== void 0) return;
93
+ const targets = Array.isArray(select["targetList"]) ? select["targetList"] : [];
94
+ const target = targets.length === 1 && isRecord(targets[0]) ? targets[0]["ResTarget"] : void 0;
95
+ const call = isRecord(target) && isRecord(target["val"]) ? target["val"]["FuncCall"] : void 0;
96
+ if (!isRecord(call) || svals(call["funcname"]).join(".") !== helper) return;
97
+ const args = Array.isArray(call["args"]) ? call["args"] : [];
98
+ const constant = args.length === 1 && isRecord(args[0]) ? args[0]["A_Const"] : void 0;
99
+ const value = isRecord(constant) && isRecord(constant["sval"]) ? constant["sval"]["sval"] : void 0;
100
+ return typeof value === "string" && column[0] !== void 0 ? {
101
+ column: column[0],
102
+ key: value
103
+ } : void 0;
104
+ }
105
+ export { tryKeyReasons as a, keyReasons as i, tenantCheck as n, keyReason as r, svals as t };
@@ -1,5 +1,5 @@
1
1
  import { a as CatalogDocument } from "../../types-CbJ5mxXv.js";
2
- import { i as SupabaseManifest } from "../../manifest-CA3E0KP8.js";
2
+ import { i as SupabaseManifest } from "../../manifest-DgsxeAsM.js";
3
3
  import { rt as MemberEntry } from "../../policy-types-CfW4X_yX.js";
4
4
  import { r as SubjectRecord } from "../../subject-cache-CnJcz2K_.js";
5
5
  import { i as SupabaseRpcClient } from "../../postgrest-PQ3zAOD2.js";