@rebasepro/studio 0.30.0 → 0.31.0-canary.g902a0ce

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 (34) hide show
  1. package/dist/{ApiKeysView-Bqf6XYR1.js → ApiKeysView-9ZvwMPyh.js} +16 -6
  2. package/dist/ApiKeysView-9ZvwMPyh.js.map +1 -0
  3. package/dist/{JSEditor-DCnPXsx6.js → JSEditor-ojAVSkaU.js} +158 -100
  4. package/dist/JSEditor-ojAVSkaU.js.map +1 -0
  5. package/dist/{RLSEditor-zAat58U0.js → RLSEditor-BAwkENpj.js} +394 -206
  6. package/dist/RLSEditor-BAwkENpj.js.map +1 -0
  7. package/dist/{SQLEditor-DV_VEEpL.js → SQLEditor-DX9LfbU7.js} +10 -8
  8. package/dist/SQLEditor-DX9LfbU7.js.map +1 -0
  9. package/dist/{SchemaVisualizer-pCYQ_Ds6.js → SchemaVisualizer-C75TENPm.js} +196 -189
  10. package/dist/SchemaVisualizer-C75TENPm.js.map +1 -0
  11. package/dist/components/JSEditor/JSEditorSidebar.d.ts +3 -6
  12. package/dist/components/JSEditor/JSMonacoEditor.d.ts +10 -10
  13. package/dist/components/JSEditor/table_access.d.ts +39 -0
  14. package/dist/components/RLSEditor/policy-presets.d.ts +1 -1
  15. package/dist/components/RLSEditor/policyListing.d.ts +32 -12
  16. package/dist/components/RLSEditor/policyRules.d.ts +32 -14
  17. package/dist/components/RLSEditor/saveRules.d.ts +48 -18
  18. package/dist/components/RLSEditor/saveSecurityRules.d.ts +5 -4
  19. package/dist/components/SchemaVisualizer/useSchemaGraph.d.ts +13 -8
  20. package/dist/components/schema-source.d.ts +37 -0
  21. package/dist/index.es.js +9 -9
  22. package/dist/index.es.js.map +1 -1
  23. package/dist/schema-source-C4ekB7WU.js +93 -0
  24. package/dist/schema-source-C4ekB7WU.js.map +1 -0
  25. package/dist/{sql_utils-DXvmxiCq.js → sql_utils-CYcgpgam.js} +14 -12
  26. package/dist/sql_utils-CYcgpgam.js.map +1 -0
  27. package/dist/utils/sql_utils.d.ts +14 -10
  28. package/package.json +9 -9
  29. package/dist/ApiKeysView-Bqf6XYR1.js.map +0 -1
  30. package/dist/JSEditor-DCnPXsx6.js.map +0 -1
  31. package/dist/RLSEditor-zAat58U0.js.map +0 -1
  32. package/dist/SQLEditor-DV_VEEpL.js.map +0 -1
  33. package/dist/SchemaVisualizer-pCYQ_Ds6.js.map +0 -1
  34. package/dist/sql_utils-DXvmxiCq.js.map +0 -1
@@ -1,12 +1,13 @@
1
- import { o as quoteIdentifier } from "./sql_utils-DXvmxiCq.js";
1
+ import { o as quoteIdentifier } from "./sql_utils-CYcgpgam.js";
2
2
  import { t as MonacoEditor } from "./MonacoEditor-7IlHFZU5.js";
3
- import { ConfirmationDialog, ErrorView, useApiBase, useApiConfig, useRebaseContext, useSnackbarController, useStudioCapabilities, useStudioCollectionRegistry, useStudioSchemaEditing, useTranslation } from "@rebasepro/app";
3
+ import { r as schemaSourceProblem, t as SchemaSourceProblemAlert } from "./schema-source-C4ekB7WU.js";
4
+ import { ConfirmationDialog, ErrorView, useApiBase, useApiConfig, useRebaseContext, useSnackbarController, useStudioCapabilities, useStudioSchemaEditing, useTableDescriptors, useTranslation } from "@rebasepro/app";
4
5
  import { useCallback, useEffect, useMemo, useRef, useState } from "react";
5
6
  import { Alert, AlertTriangleIcon, Button, Chip, CircularProgress, DatabaseIcon, Dialog, DialogActions, DialogContent, DialogTitle, HelpCircleIcon, IconButton, KeyIcon, Link2Icon, LockIcon, MultiSelect, MultiSelectItem, Paper, RefreshCwIcon, ResizablePanels, Select, SelectItem, ShieldIcon, Tab, Tabs, TextField, Tooltip, Trash2Icon, Typography, cls, defaultBorderMixin, iconSize } from "@rebasepro/ui";
6
7
  import { Fragment, jsx, jsxs } from "react/jsx-runtime";
7
- import { RLS_JWT_SQL, RLS_ROLES_SQL, RLS_UID_SQL, isPostgresCollectionConfig, policy } from "@rebasepro/types";
8
- import { adminRequestPolicyName, getPolicyNamesForRule, getPolicyNamesForRules, getPolicyOperations } from "@rebasepro/utils";
9
- import { JUNCTION_TABLES_SQL, REBASE_INTERNAL_PREFIXES, REBASE_INTERNAL_SCHEMAS, REBASE_USER_ROLE, compileRulePolicies, getEffectiveSecurityRules, getInjectedSecurityRules, getJunctionSecurityRules, getTableName, policyToPostgres, policyToSecurityRule, resolveJunctionSpecs } from "@rebasepro/common";
8
+ import { REBASE_ADMIN_REQUEST_ROLE, REBASE_ADMIN_ROLE, RLS_JWT_SQL, RLS_ROLES_SQL, RLS_UID_SQL, isRedactedSecurityRule, policy, rulePatches } from "@rebasepro/types";
9
+ import { adminRequestPolicyName, getPolicyNamesForRule, getPolicyOperations } from "@rebasepro/utils";
10
+ import { JUNCTION_TABLES_SQL, REBASE_INTERNAL_PREFIXES, REBASE_INTERNAL_SCHEMAS, REBASE_USER_ROLE, compilePolicyExpression, policyToSecurityRule } from "@rebasepro/common";
10
11
  //#region src/components/RLSEditor/policy-presets.ts
11
12
  /**
12
13
  * What the RLS editor offers before the user types anything: the roles a `TO`
@@ -74,15 +75,15 @@ function roleOptionsFor(fetched, policyRoles) {
74
75
  * Preset conditions, compiled by the framework's own policy compiler rather
75
76
  * than written out here.
76
77
  *
77
- * `policyToPostgres` is the function `db push` generates policies with, so a
78
+ * `compilePolicyExpression` is the function `db push` generates policies with, so a
78
79
  * preset cannot drift from what the framework emits — and the one that matters
79
80
  * has drifted before: `authenticated()` used to compile to a bare
80
81
  * `IS NOT NULL`, which is true for anonymous visitors, and any copy of that
81
82
  * string sitting in a preset would still be handing out the old grant today.
82
83
  */
83
- var SIGNED_IN_SQL = policyToPostgres(policy.authenticated());
84
- var IS_ADMIN_SQL = policyToPostgres(policy.rolesOverlap(["admin"]));
85
- var OWNS_ROW_SQL = policyToPostgres(policy.compare(policy.authUid(), "eq", policy.field("uid")));
84
+ var SIGNED_IN_SQL = compilePolicyExpression(policy.authenticated());
85
+ var IS_ADMIN_SQL = compilePolicyExpression(policy.rolesOverlap(["admin"]));
86
+ var OWNS_ROW_SQL = compilePolicyExpression(policy.compare(policy.authUid(), "eq", policy.field("uid")));
86
87
  /**
87
88
  * Every preset targets `TO public`, which is what the framework's generator
88
89
  * emits and what actually reaches a request running as `rebase_user`. The part
@@ -695,7 +696,8 @@ var PolicyEditor = ({ policy, schema, table, roleOptions, onSave, onCancel }) =>
695
696
  //#endregion
696
697
  //#region src/components/RLSEditor/saveSecurityRules.ts
697
698
  /**
698
- * Write a collection's security rules to its source file.
699
+ * Write a table's rule edits to its source file: `{ patches }` to the
700
+ * source-only schema editor (`/admin/schema-editor/apply`).
699
701
  *
700
702
  * The schema-editor routes sit behind an admin gate that accepts a bearer token
701
703
  * and nothing else — there is no cookie fallback — so a request without an
@@ -707,26 +709,23 @@ var PolicyEditor = ({ policy, schema, table, roleOptions, onSave, onCancel }) =>
707
709
  * It lives in its own module rather than inline in the component so that the
708
710
  * header can be asserted without rendering the whole RLS editor.
709
711
  */
710
- async function saveSecurityRulesToCodebase(options) {
711
- const { apiBase, collectionId, securityRules, getAuthToken } = options;
712
+ async function postTablePatches(options) {
713
+ const { apiBase, patches, getAuthToken } = options;
712
714
  const headers = { "Content-Type": "application/json" };
713
715
  const token = getAuthToken ? await getAuthToken() : null;
714
716
  if (token) headers["Authorization"] = `Bearer ${token}`;
715
- const response = await fetch(`${apiBase}/admin/schema-editor/collection/save`, {
717
+ const response = await fetch(`${apiBase}/admin/schema-editor/apply`, {
716
718
  method: "POST",
717
719
  headers,
718
- body: JSON.stringify({
719
- collectionId,
720
- collectionData: { securityRules },
721
- partial: true
722
- })
720
+ body: JSON.stringify({ patches })
723
721
  });
724
722
  if (response.ok) return;
725
723
  const body = await response.text().catch(() => "");
726
724
  let message;
727
725
  try {
728
726
  const parsed = JSON.parse(body);
729
- message = parsed.error?.message ?? parsed.message;
727
+ const error = typeof parsed === "object" && parsed !== null && "error" in parsed ? parsed.error : void 0;
728
+ message = typeof error === "object" && error !== null && "message" in error && typeof error.message === "string" ? error.message : void 0;
730
729
  } catch {
731
730
  message = body.trim() || void 0;
732
731
  }
@@ -735,41 +734,144 @@ async function saveSecurityRulesToCodebase(options) {
735
734
  //#endregion
736
735
  //#region src/components/RLSEditor/saveRules.ts
737
736
  /**
738
- * Where a collection's security rules go when the RLS editor saves them.
737
+ * Where a table's security rules go when the RLS editor saves them — the one
738
+ * function every RLS-editor write to the source goes through.
739
+ *
740
+ * The edit is sent as the rule operations it is (`TablePatch`): the rules the
741
+ * table declares, compared with the rules it should declare, by
742
+ * {@link rulePatches} — one `replaceRule` for an edited rule, one `addRule`
743
+ * for an imported one. A policy's name is a hash of its rule as written, so a
744
+ * rule the edit did not touch is never rewritten. A posture is `setRls`:
745
+ * removing the last rule is `"admin-only"`, never an empty list.
739
746
  *
740
- * There are two doors onto one file. The collection editor's save is planned,
741
- * shown as SQL, confirmed, and applied to the database. The RLS editor's save
742
- * POSTed the rules to `/schema-editor/collection/save` and stopped there: the
743
- * source changed, nothing said what the change implied, and the database was
744
- * left to a later `db push`. A policy declared and not enforced is the worst
745
- * outcome this editor can produce, and it was the default one.
747
+ * A table whose rules are inherited from `defaultRls` keeps `"inherit"`
748
+ * unless the person deliberately detaches it: `confirmDetach` asks (naming
749
+ * what happens), and saying no writes nothing.
746
750
  *
747
- * So a mapped-table write goes through the admin's plan/apply flow when there
748
- * is one. Studio cannot call `useLiveSchemaEditing` — `@rebasepro/cms` is a
749
- * *peer* of `@rebasepro/studio`, which has to run without it — so it arrives
750
- * over the Studio bridge as {@link StudioSchemaEditing}, and `available` is
751
- * false in the hosted console, where there is no source to edit and the direct
752
- * write is the only thing there is.
751
+ * There are two doors onto one file. With a collection editor mounted, the
752
+ * write goes through its plan/apply flow — planned, shown as SQL, confirmed,
753
+ * applied to the database — arriving over the Studio bridge as
754
+ * {@link StudioSchemaEditing} (`@rebasepro/cms` is a *peer* of
755
+ * `@rebasepro/studio`, which has to run without it). Without one, it goes to
756
+ * the source-only schema editor directly.
753
757
  *
754
- * A separate module from the component for the same reason `saveSecurityRules`
755
- * is: the decision can be asserted without a database and a rendered editor.
758
+ * A separate module from the component so the decision can be asserted
759
+ * without a database and a rendered editor.
756
760
  */
757
- async function saveRules(schemaEditing, transport, collectionId, securityRules) {
761
+ async function saveRules(schemaEditing, transport, table, rules, options) {
762
+ const patches = await rlsEdit(table, rules.map(asSecurityRule), options.confirmDetach);
763
+ if (patches.length === 0) return;
758
764
  if (schemaEditing.available) {
759
- await schemaEditing.updateCollection(collectionId, { securityRules });
765
+ await schemaEditing.applyTablePatches(table.slug, patches);
760
766
  return;
761
767
  }
762
- await saveSecurityRulesToCodebase({
768
+ await postTablePatches({
763
769
  apiBase: transport.apiBase,
764
- collectionId,
765
- securityRules,
770
+ patches,
766
771
  getAuthToken: transport.getAuthToken
767
772
  });
768
773
  }
769
774
  /**
770
- * Was this rejection the person closing the plan dialog?
775
+ * A rule the policy editor built — its fields assigned one at a time, so
776
+ * wider than any one variant — as the `SecurityRule` variant its fields make
777
+ * it. Which fields go together is the variants' rule; the editor never sets
778
+ * two that exclude each other ({@link PolicyRule}).
779
+ */
780
+ function asSecurityRule(rule) {
781
+ const { using, withCheck, ownerField, access, condition, check, redacted, ...rest } = rule;
782
+ const base = rest;
783
+ if (redacted) return {
784
+ ...base,
785
+ redacted,
786
+ ...access !== void 0 ? { access } : {}
787
+ };
788
+ if (using !== void 0) return {
789
+ ...base,
790
+ using,
791
+ ...withCheck !== void 0 ? { withCheck } : {}
792
+ };
793
+ if (withCheck !== void 0) return {
794
+ ...base,
795
+ withCheck
796
+ };
797
+ if (ownerField !== void 0) return {
798
+ ...base,
799
+ ownerField
800
+ };
801
+ if (access !== void 0) {
802
+ if (condition !== void 0) return {
803
+ ...base,
804
+ access,
805
+ condition,
806
+ ...check !== void 0 ? { check } : {}
807
+ };
808
+ if (check !== void 0) return {
809
+ ...base,
810
+ access,
811
+ check
812
+ };
813
+ switch (access) {
814
+ case "public": return {
815
+ ...base,
816
+ access: "public"
817
+ };
818
+ case "authenticated": return {
819
+ ...base,
820
+ access: "authenticated"
821
+ };
822
+ case "registered": return {
823
+ ...base,
824
+ access: "registered"
825
+ };
826
+ }
827
+ }
828
+ if (condition !== void 0) return {
829
+ ...base,
830
+ condition,
831
+ ...check !== void 0 ? { check } : {}
832
+ };
833
+ return base;
834
+ }
835
+ /** The person kept `"inherit"`: an answer, matched like the plan dialog's cancellation. */
836
+ var DetachDeclined = class extends Error {
837
+ constructor() {
838
+ super("The table keeps its inherited rules.");
839
+ this.name = "SchemaChangeCancelled";
840
+ }
841
+ };
842
+ /**
843
+ * The operations that make `table` declare `rules`.
844
+ *
845
+ * Exported for the tests: the decision is the whole of what this module adds.
846
+ */
847
+ async function rlsEdit(table, rules, confirmDetach) {
848
+ const declared = table.rls.posture === "rules" ? table.rls.rules : [];
849
+ if (table.rls.inherited) {
850
+ if (rules.length === 0 || JSON.stringify(rules) === JSON.stringify(declared)) return [];
851
+ if (!await confirmDetach(table.slug)) throw new DetachDeclined();
852
+ return [{
853
+ op: "setRls",
854
+ table: table.slug,
855
+ rls: [rules[0], ...rules.slice(1)]
856
+ }];
857
+ }
858
+ if (rules.length === 0) return declared.length === 0 ? [] : [{
859
+ op: "setRls",
860
+ table: table.slug,
861
+ rls: "admin-only"
862
+ }];
863
+ if (declared.length === 0) return [{
864
+ op: "setRls",
865
+ table: table.slug,
866
+ rls: [rules[0], ...rules.slice(1)]
867
+ }];
868
+ return rulePatches(table.slug, declared, rules);
869
+ }
870
+ /**
871
+ * Was this rejection the person closing the plan dialog, or keeping a table's
872
+ * inherited rules?
771
873
  *
772
- * Closing it is an answer, not a failure, and a caller that treats every
874
+ * Either is an answer, not a failure, and a caller that treats every
773
875
  * rejection as an error reports someone's own choice back to them in red — as
774
876
  * the collection editor once did, with "Error persisting collection: The schema
775
877
  * change was not applied."
@@ -783,30 +885,41 @@ function isCancellation(err) {
783
885
  }
784
886
  //#endregion
785
887
  //#region src/components/RLSEditor/policyRules.ts
888
+ /** The {@link PolicyRuleForm} of a declared rule. */
889
+ function ruleForm(rule) {
890
+ if (isRedactedSecurityRule(rule)) return "redacted";
891
+ if (rule.using != null || rule.withCheck != null) return "raw";
892
+ if (rule.ownerField != null) return "owner";
893
+ if (rule.access !== void 0) return rule.condition != null || rule.check != null ? "conditional_access" : "access";
894
+ if (rule.condition != null || rule.check != null) return "structured";
895
+ return "roles_only";
896
+ }
786
897
  /**
787
898
  * Write an edit of one policy back to the declared rule it compiles from.
788
899
  *
789
- * The rule is found by the policy names it compiles to, not by `rule.name`:
790
- * an unnamed rule's policy is `<table>_<op>_<hash>`, and a rule over several
791
- * operations names each `<name>_<op>`. Matching on `name` missed both, saved
792
- * the rules unchanged and reported success.
900
+ * The rule is the one the server says the policy was compiled from (the
901
+ * served policy's `rule` index, carried on the listed row) — the server is the
902
+ * one compiler, so the editor never guesses it from names. A policy with no
903
+ * rule is Rebase's own (`generated`: the admin baseline, tenancy, a junction's
904
+ * derived policies) or exists only in the database.
793
905
  *
794
906
  * A rule over several operations is refused rather than split: taking one
795
907
  * operation out renames every policy the rule compiles to.
796
908
  *
797
- * @param declared The collection's `securityRules`, as written.
798
- * @param effective Every rule the generator compiles for the table — the
799
- * declared ones plus what Rebase adds — to tell a generated
800
- * policy from one that exists only in the database.
909
+ * @param declared The table's declared rules (`rls.rules`), as written.
910
+ * @param original The listed policy the editor was opened with.
801
911
  */
802
- function applyPolicyEdit(declared, effective, tableName, original, edited) {
803
- const compilesTo = (rule) => getPolicyNamesForRule(rule, tableName).includes(original.policyname);
804
- const index = declared.findIndex(compilesTo);
805
- if (index === -1) return {
912
+ function applyPolicyEdit(declared, original, edited) {
913
+ const index = original.rule;
914
+ if (index === void 0 || declared[index] === void 0) return {
806
915
  ok: false,
807
- reason: effective.some(compilesTo) ? "generated" : "not_declared"
916
+ reason: original.generated ? "generated" : "not_declared"
808
917
  };
809
918
  const rule = declared[index];
919
+ if (ruleForm(rule) === "redacted") return {
920
+ ok: false,
921
+ reason: "redacted"
922
+ };
810
923
  if (getPolicyOperations(rule).length > 1) return {
811
924
  ok: false,
812
925
  reason: "several_operations"
@@ -903,22 +1016,25 @@ var COMMANDS = {
903
1016
  delete: "DELETE",
904
1017
  all: "ALL"
905
1018
  };
906
- /** A compiled policy, in the shape `pg_policies` describes one. */
907
- function asPostgresPolicy(compiled, tableName) {
1019
+ function commandOf(operation) {
1020
+ return operation in COMMANDS ? COMMANDS[operation] : "ALL";
1021
+ }
1022
+ /** A policy the server compiled, in the shape `pg_policies` describes one. */
1023
+ function servedAsPostgresPolicy(served, tableName) {
908
1024
  return {
909
- policyname: compiled.name,
1025
+ policyname: served.name,
910
1026
  tablename: tableName,
911
- permissive: compiled.mode === "restrictive" ? "RESTRICTIVE" : "PERMISSIVE",
912
- cmd: COMMANDS[compiled.operation],
913
- roles: compiled.roles,
914
- qual: compiled.using,
915
- with_check: compiled.withCheck
1027
+ permissive: served.mode === "restrictive" ? "RESTRICTIVE" : "PERMISSIVE",
1028
+ cmd: commandOf(served.operation),
1029
+ roles: [...served.roles],
1030
+ qual: served.using,
1031
+ with_check: served.withCheck
916
1032
  };
917
1033
  }
918
1034
  /**
919
- * The rule's own clauses, for a rule the compiler could not compile — an
920
- * `existsIn` naming a collection the registry does not hold, say. Only ever a
921
- * `code_only` row's content: nothing is compared against it.
1035
+ * The rule's own clauses, for a declared rule the server compiled no policy
1036
+ * from — an `existsIn` naming a table the backend does not hold, say. Only
1037
+ * ever a `code_only` row's content: nothing is compared against it.
922
1038
  */
923
1039
  function uncompiledPolicy(rule, operation, name, tableName) {
924
1040
  return {
@@ -955,115 +1071,111 @@ function policyDrift(declared, live) {
955
1071
  if (declared.with_check != null !== (live.with_check != null)) drift.push("WITH CHECK");
956
1072
  return drift;
957
1073
  }
1074
+ /** The {@link DeclaredPolicies} of a served table, when the server included its compiled policies. */
1075
+ function declaredPoliciesOf(rls) {
1076
+ return rls.policies ? {
1077
+ rules: rls.rules,
1078
+ policies: rls.policies
1079
+ } : void 0;
1080
+ }
958
1081
  /**
959
1082
  * The policies of one table: every policy the database has, as the database
960
- * has it, and every policy the code declares for the table that it does not.
1083
+ * has it, and every policy the server compiles for the table that it does not.
961
1084
  *
962
- * A policy in both keeps the database's fields — this list is what Postgres
963
- * enforces — and carries the declaration beside them, with where the two
964
- * differ.
1085
+ * The server is the one compiler: what it serves in `rls.policies` (and
1086
+ * `rls.junctions`) is exactly what `db push` and every server start write.
1087
+ * This only compares it with `pg_policies`. A policy in both keeps the
1088
+ * database's fields — this list is what Postgres enforces — and carries the
1089
+ * declaration beside them, with where the two differ.
965
1090
  *
966
- * @param live The table's `pg_policies` rows.
967
- * @param collection The collection the table belongs to, if any.
968
- * @param collections Every collection, to resolve the ones a rule refers to.
1091
+ * @param live The table's `pg_policies` rows.
1092
+ * @param declared What the server serves for the table, if anything.
969
1093
  */
970
- function listPolicies(live, collection, tableName, collections) {
1094
+ function listPolicies(live, declared, tableName) {
971
1095
  const listed = /* @__PURE__ */ new Map();
972
1096
  for (const policy of live) listed.set(policy.policyname, {
973
1097
  ...policy,
974
1098
  status: "live"
975
1099
  });
976
- if (!collection || !isPostgresCollectionConfig(collection)) return [...listed.values()];
977
- const resolveCollection = (slug) => collections.find((c) => c.slug === slug || getTableName(c) === slug);
978
- const injectedNames = getPolicyNamesForRules(getInjectedSecurityRules(collection), tableName);
1100
+ if (!declared) return [...listed.values()];
979
1101
  const livePolicies = new Map(live.map((policy) => [policy.policyname, policy]));
980
- for (const rule of getEffectiveSecurityRules(collection)) {
1102
+ const compiledRules = /* @__PURE__ */ new Set();
1103
+ for (const served of declared.policies) {
1104
+ if (served.rule !== void 0) compiledRules.add(served.rule);
1105
+ const existing = livePolicies.get(served.name);
1106
+ if (served.roles.includes(REBASE_ADMIN_REQUEST_ROLE) && !existing) continue;
1107
+ const compiled = servedAsPostgresPolicy(served, tableName);
1108
+ const declaredPolicy = existing !== void 0 && sameRoles(compiled.roles, [REBASE_ADMIN_ROLE]) && sameRoles(existing.roles, ["public"]) ? {
1109
+ ...compiled,
1110
+ roles: ["public"]
1111
+ } : compiled;
1112
+ const rule = served.rule !== void 0 ? { rule: served.rule } : {};
1113
+ if (existing) listed.set(served.name, {
1114
+ ...existing,
1115
+ status: "both",
1116
+ declared: declaredPolicy,
1117
+ drift: policyDrift(declaredPolicy, existing),
1118
+ generated: served.injected,
1119
+ ...rule
1120
+ });
1121
+ else listed.set(served.name, {
1122
+ ...declaredPolicy,
1123
+ status: "code_only",
1124
+ generated: served.injected,
1125
+ ...rule
1126
+ });
1127
+ }
1128
+ declared.rules.forEach((rule, index) => {
1129
+ if (compiledRules.has(index) || isRedactedSecurityRule(rule)) return;
981
1130
  const operations = getPolicyOperations(rule);
982
- let compiled;
983
- try {
984
- compiled = compileRulePolicies(collection, rule, {
985
- resolveCollection,
986
- adminRole: true
987
- });
988
- } catch {
989
- compiled = void 0;
990
- }
991
- getPolicyNamesForRule(rule, tableName).forEach((name, index) => {
992
- const existing = livePolicies.get(name);
993
- const compiledPolicy = compiled?.[index];
994
- const fellBack = compiledPolicy?.adminTarget === true && existing !== void 0 && sameRoles(existing.roles, ["public"]);
995
- const declared = compiledPolicy ? {
996
- ...asPostgresPolicy(compiledPolicy, tableName),
997
- ...fellBack ? { roles: ["public"] } : {}
998
- } : void 0;
999
- const generated = injectedNames.has(name);
1000
- if (existing) listed.set(name, {
1001
- ...existing,
1002
- status: "both",
1003
- declared,
1004
- drift: declared ? policyDrift(declared, existing) : void 0,
1005
- generated
1006
- });
1007
- else listed.set(name, {
1008
- ...declared ?? uncompiledPolicy(rule, operations[index] ?? "all", name, tableName),
1131
+ getPolicyNamesForRule(rule, tableName).forEach((name, position) => {
1132
+ const existing = listed.get(name);
1133
+ if (existing) {
1134
+ if (existing.status === "live") listed.set(name, {
1135
+ ...existing,
1136
+ status: "both",
1137
+ generated: false,
1138
+ rule: index
1139
+ });
1140
+ return;
1141
+ }
1142
+ listed.set(name, {
1143
+ ...uncompiledPolicy(rule, operations[position] ?? "all", name, tableName),
1009
1144
  status: "code_only",
1010
- generated
1145
+ generated: false,
1146
+ rule: index
1011
1147
  });
1012
1148
  });
1013
- let companions = [];
1014
- try {
1015
- companions = compileRulePolicies(collection, rule, {
1016
- resolveCollection,
1017
- adminRole: true,
1018
- adminRequestRole: true
1019
- }).filter((policy) => policy.adminRequestTarget === true);
1020
- } catch {
1021
- companions = [];
1022
- }
1023
- for (const companion of companions) {
1024
- const existing = livePolicies.get(companion.name);
1025
- if (!existing) continue;
1026
- const declared = asPostgresPolicy(companion, tableName);
1027
- listed.set(companion.name, {
1028
- ...existing,
1029
- status: "both",
1030
- declared,
1031
- drift: policyDrift(declared, existing),
1032
- generated: true
1033
- });
1034
- }
1035
- }
1149
+ });
1036
1150
  return [...listed.values()];
1037
1151
  }
1038
1152
  //#endregion
1039
1153
  //#region src/components/RLSEditor/RLSEditor.tsx
1040
1154
  /**
1041
- * Whether `collection` is the one `db push` writes `table` for: the table
1042
- * `getTableName` derives, in the schema the collection declares or `public` —
1043
- * the planner's own resolution.
1155
+ * Whether `descriptor` is the table the server declares for a live table: the
1156
+ * same SQL table in the same schema, as the server resolved both.
1044
1157
  *
1045
- * This matched a table to any collection whose `id`, `path`, `table`, `slug`
1046
- * or `collectionId` equalled its name, in any schema. So an unmapped table
1047
- * named like another collection's slug, or a same-named table in another
1048
- * schema, was taken for that collection: it listed the collection's policies
1049
- * as missing from the table, and offered to import the table's own policies
1050
- * into the collection. And a collection that leaves `table` to a slug that is
1051
- * not already snake case mapped nothing.
1158
+ * Matched once by name, a table was taken for any collection whose `id`,
1159
+ * `path`, `table`, `slug` or `collectionId` equalled its name, in any schema.
1160
+ * So an unmapped table named like another table's slug, or a same-named table
1161
+ * in another schema, was taken for that table: it listed the declared
1162
+ * policies as missing from the table, and offered to import the table's own
1163
+ * policies into the declaration. A view is never a `pg_tables` row.
1052
1164
  */
1053
- function mapsTable(collection, table) {
1054
- if (!isPostgresCollectionConfig(collection)) return false;
1055
- return getTableName(collection) === table.tableName && (collection.schema || "public") === table.schemaName;
1165
+ function mapsTable(descriptor, table) {
1166
+ return descriptor.kind === "table" && descriptor.table === table.tableName && descriptor.schema === table.schemaName;
1056
1167
  }
1057
1168
  /** What the editor says when an edit has no declared rule to go back to. */
1058
1169
  var POLICY_EDIT_REFUSALS = {
1059
1170
  generated: "studio_rls_edit_generated",
1060
1171
  not_declared: "studio_rls_edit_not_declared",
1061
- several_operations: "studio_rls_edit_several_operations"
1172
+ several_operations: "studio_rls_edit_several_operations",
1173
+ redacted: "studio_rls_edit_redacted"
1062
1174
  };
1063
- function classifyTableClient(tableName, schemaName, junctionTableNames, isMappedToCollection) {
1175
+ function classifyTableClient(tableName, schemaName, isJunction, isMappedToCollection) {
1064
1176
  if (isMappedToCollection) return "collection";
1065
1177
  if (REBASE_INTERNAL_SCHEMAS.includes(schemaName) || REBASE_INTERNAL_PREFIXES.some((prefix) => tableName.startsWith(prefix))) return "internal";
1066
- if (junctionTableNames.has(tableName)) return "junction";
1178
+ if (isJunction) return "junction";
1067
1179
  return "other";
1068
1180
  }
1069
1181
  function SidebarSection({ title, icon, expanded, onToggle, count, children }) {
@@ -1144,19 +1256,48 @@ function SidebarTableRow({ table, isSelected, onSelect, badge, dimmed, t }) {
1144
1256
  var RLSEditor = ({ apiUrl = "" }) => {
1145
1257
  const { databaseAdmin } = useRebaseContext();
1146
1258
  const snackbarController = useSnackbarController();
1147
- const collectionRegistry = useStudioCollectionRegistry();
1259
+ const descriptors = useTableDescriptors();
1260
+ const schemaProblem = schemaSourceProblem(descriptors);
1261
+ const declaredTables = descriptors.tables;
1148
1262
  const { codebase: hasCodebase } = useStudioCapabilities();
1149
1263
  const apiConfig = useApiConfig();
1150
1264
  const apiBase = useApiBase() ?? `${apiUrl.replace(/\/+$/, "")}/api`;
1151
1265
  const schemaEditing = useStudioSchemaEditing();
1152
- /** Through the plan/apply dialog when there is one — see `saveRules`. */
1153
- const saveSecurityRules = useCallback((collectionId, securityRules) => saveRules(schemaEditing, {
1154
- apiBase,
1155
- getAuthToken: apiConfig?.getAuthToken
1156
- }, collectionId, securityRules), [
1266
+ /**
1267
+ * Through the plan/apply dialog when there is one — see `saveRules`. A
1268
+ * save changes the source the served tables come from, so they are asked
1269
+ * for again: the declared side of the list follows the edit.
1270
+ */
1271
+ const reloadDeclared = descriptors.reload;
1272
+ /**
1273
+ * Saving rules on a table that inherits them from `defaultRls` detaches it
1274
+ * into rules of its own: asked here, never done silently. Settled by the
1275
+ * dialog below — "OK" detaches, "Cancel" keeps `"inherit"`.
1276
+ */
1277
+ const [detaching, setDetaching] = useState(null);
1278
+ const settleDetach = useRef(null);
1279
+ const confirmDetach = useCallback((slug) => new Promise((resolve) => {
1280
+ settleDetach.current?.(false);
1281
+ settleDetach.current = resolve;
1282
+ setDetaching(slug);
1283
+ }), []);
1284
+ const answerDetach = useCallback((detach) => {
1285
+ settleDetach.current?.(detach);
1286
+ settleDetach.current = null;
1287
+ setDetaching(null);
1288
+ }, []);
1289
+ const saveSecurityRules = useCallback(async (table, securityRules) => {
1290
+ await saveRules(schemaEditing, {
1291
+ apiBase,
1292
+ getAuthToken: apiConfig?.getAuthToken
1293
+ }, table, securityRules, { confirmDetach });
1294
+ reloadDeclared();
1295
+ }, [
1157
1296
  apiBase,
1158
1297
  apiConfig,
1159
- schemaEditing
1298
+ schemaEditing,
1299
+ reloadDeclared,
1300
+ confirmDetach
1160
1301
  ]);
1161
1302
  /** Closing the plan dialog is an answer, not a failure — see `saveRules`. */
1162
1303
  const reportSaveFailure = useCallback((e) => {
@@ -1370,6 +1511,27 @@ var RLSEditor = ({ apiUrl = "" }) => {
1370
1511
  if (!selectedTable) return null;
1371
1512
  return tables.find((t) => `${t.schemaName}.${t.tableName}` === selectedTable) || null;
1372
1513
  }, [selectedTable, tables]);
1514
+ /**
1515
+ * Every junction the server derives, with its policies, by
1516
+ * `schema.table`. A junction has no descriptor of its own: it is listed
1517
+ * under each table that declares a relation through it.
1518
+ */
1519
+ const servedJunctions = useMemo(() => {
1520
+ const junctions = /* @__PURE__ */ new Map();
1521
+ for (const table of declaredTables) {
1522
+ for (const junction of table.rls.junctions ?? []) junctions.set(`${junction.schema}.${junction.table}`, junction);
1523
+ for (const relation of table.relations) {
1524
+ if (relation.kind !== "manyToMany") continue;
1525
+ const key = `${table.schema}.${relation.through.table}`;
1526
+ if (!junctions.has(key)) junctions.set(key, {
1527
+ table: relation.through.table,
1528
+ schema: table.schema,
1529
+ policies: []
1530
+ });
1531
+ }
1532
+ }
1533
+ return junctions;
1534
+ }, [declaredTables]);
1373
1535
  /** Categorize tables into 4 buckets for the sidebar. */
1374
1536
  const categorizedTables = useMemo(() => {
1375
1537
  const groups = {
@@ -1379,54 +1541,71 @@ var RLSEditor = ({ apiUrl = "" }) => {
1379
1541
  other: []
1380
1542
  };
1381
1543
  tables.forEach((table) => {
1382
- const isMapped = !!collectionRegistry.collections?.some((c) => mapsTable(c, table));
1383
- const cat = classifyTableClient(table.tableName, table.schemaName, junctionTableNames, isMapped);
1544
+ const isMapped = declaredTables.some((descriptor) => mapsTable(descriptor, table));
1545
+ const isJunction = junctionTableNames.has(table.tableName) || servedJunctions.has(`${table.schemaName}.${table.tableName}`);
1546
+ const cat = classifyTableClient(table.tableName, table.schemaName, isJunction, isMapped);
1384
1547
  groups[cat].push(table);
1385
1548
  });
1386
1549
  return groups;
1387
1550
  }, [
1388
1551
  tables,
1389
1552
  junctionTableNames,
1390
- collectionRegistry.collections
1553
+ servedJunctions,
1554
+ declaredTables
1391
1555
  ]);
1392
- const activeCollection = useMemo(() => {
1393
- if (!activeTableData) return null;
1394
- return collectionRegistry.collections?.find((c) => mapsTable(c, activeTableData)) || null;
1395
- }, [activeTableData, collectionRegistry.collections]);
1396
- /** The category of the currently selected table. */
1397
- const activeTableCategory = useMemo(() => {
1556
+ /** The table the server declares for the selected one, if any. */
1557
+ const activeDescriptor = useMemo(() => {
1398
1558
  if (!activeTableData) return null;
1399
- const isMapped = !!activeCollection;
1400
- return classifyTableClient(activeTableData.tableName, activeTableData.schemaName, junctionTableNames, isMapped);
1401
- }, [
1402
- activeTableData,
1403
- activeCollection,
1404
- junctionTableNames
1405
- ]);
1559
+ return declaredTables.find((descriptor) => mapsTable(descriptor, activeTableData)) ?? null;
1560
+ }, [activeTableData, declaredTables]);
1406
1561
  /**
1407
1562
  * The junction a relation derives this table as, when it is one. Its
1408
1563
  * policies are Rebase's — derived from the endpoints' relations — and the
1409
- * server re-creates them on every start, like a collection's. `null` when
1410
- * the registry's collections carry no resolvable relations (serialized
1411
- * configs without relation closures).
1564
+ * server re-creates them on every start, like a declared table's.
1412
1565
  */
1413
- const activeJunctionSpec = useMemo(() => {
1414
- if (!activeTableData || activeCollection) return null;
1415
- try {
1416
- return resolveJunctionSpecs(collectionRegistry.collections ?? []).get(activeTableData.tableName) ?? null;
1417
- } catch {
1418
- return null;
1419
- }
1566
+ const activeJunction = useMemo(() => {
1567
+ if (!activeTableData || activeDescriptor) return null;
1568
+ return servedJunctions.get(`${activeTableData.schemaName}.${activeTableData.tableName}`) ?? null;
1420
1569
  }, [
1421
1570
  activeTableData,
1422
- activeCollection,
1423
- collectionRegistry.collections
1571
+ activeDescriptor,
1572
+ servedJunctions
1573
+ ]);
1574
+ /** The category of the currently selected table. */
1575
+ const activeTableCategory = useMemo(() => {
1576
+ if (!activeTableData) return null;
1577
+ const isJunction = Boolean(activeJunction) || junctionTableNames.has(activeTableData.tableName);
1578
+ return classifyTableClient(activeTableData.tableName, activeTableData.schemaName, isJunction, Boolean(activeDescriptor));
1579
+ }, [
1580
+ activeTableData,
1581
+ activeDescriptor,
1582
+ activeJunction,
1583
+ junctionTableNames
1424
1584
  ]);
1425
1585
  /**
1426
1586
  * Whether the server re-asserts this table's RLS on every start: it switches
1427
1587
  * RLS back on and re-creates every policy the project declares for it.
1428
1588
  */
1429
- const activeTableManaged = Boolean(activeCollection || activeJunctionSpec);
1589
+ const activeTableManaged = Boolean(activeDescriptor || activeJunction);
1590
+ /**
1591
+ * What the server says the selected table's policies are — `undefined`
1592
+ * when it declares none, or withheld them from this caller.
1593
+ */
1594
+ const activeDeclared = useMemo(() => {
1595
+ if (activeDescriptor) return declaredPoliciesOf(activeDescriptor.rls);
1596
+ if (activeJunction && activeJunction.policies.length > 0) return {
1597
+ rules: [],
1598
+ policies: activeJunction.policies
1599
+ };
1600
+ }, [activeDescriptor, activeJunction]);
1601
+ /**
1602
+ * The table is declared, but this caller is not shown what it compiles to
1603
+ * (no `schema:read`): the list is what the database holds, and nothing is
1604
+ * written to the declaration — its raw rules may be redacted.
1605
+ */
1606
+ const declaredWithheld = activeDescriptor !== null && activeDeclared === void 0;
1607
+ /** A save to the declaration needs the declaration, and a codebase to write it into. */
1608
+ const savesToCodebase = activeDescriptor !== null && hasCodebase;
1430
1609
  /**
1431
1610
  * What Postgres enforces on the selected table, and what the code declares
1432
1611
  * that it does not have yet.
@@ -1439,21 +1618,8 @@ var RLSEditor = ({ apiUrl = "" }) => {
1439
1618
  */
1440
1619
  const mergedPolicies = useMemo(() => {
1441
1620
  if (!activeTableData) return [];
1442
- const listed = listPolicies(activeTableData.policies || [], activeCollection, activeTableData.tableName, collectionRegistry.collections ?? []);
1443
- if (activeJunctionSpec) {
1444
- const generatedNames = getPolicyNamesForRules(getJunctionSecurityRules(activeJunctionSpec), activeJunctionSpec.table);
1445
- for (const p of listed) if (generatedNames.has(p.policyname)) {
1446
- p.status = "both";
1447
- p.generated = true;
1448
- }
1449
- }
1450
- return listed.sort((a, b) => a.policyname.localeCompare(b.policyname));
1451
- }, [
1452
- activeTableData,
1453
- activeCollection,
1454
- activeJunctionSpec,
1455
- collectionRegistry.collections
1456
- ]);
1621
+ return listPolicies(activeTableData.policies || [], activeDeclared, activeTableData.tableName).sort((a, b) => a.policyname.localeCompare(b.policyname));
1622
+ }, [activeTableData, activeDeclared]);
1457
1623
  const rlsStats = useMemo(() => {
1458
1624
  return {
1459
1625
  total: tables.length,
@@ -1812,12 +1978,19 @@ var RLSEditor = ({ apiUrl = "" }) => {
1812
1978
  table: activeTableData.tableName,
1813
1979
  roleOptions: pgRoleOptions,
1814
1980
  onSave: async (newPolicy) => {
1815
- if (activeCollection && hasCodebase) {
1816
- const existingRules = (isPostgresCollectionConfig(activeCollection) ? activeCollection.securityRules : void 0) || [];
1981
+ if (savesToCodebase && activeDescriptor) {
1982
+ if (declaredWithheld) {
1983
+ snackbarController.open({
1984
+ type: "error",
1985
+ message: t("studio_rls_save_needs_schema_read", { table: activeTableData.tableName })
1986
+ });
1987
+ return;
1988
+ }
1989
+ const existingRules = activeDescriptor.rls.rules;
1817
1990
  let newRules;
1818
1991
  if (editingPolicy === "new") newRules = [...existingRules, policyToSecurityRule(newPolicy)];
1819
1992
  else {
1820
- const edit = applyPolicyEdit(existingRules, getEffectiveSecurityRules(activeCollection), activeTableData.tableName, editingPolicy, newPolicy);
1993
+ const edit = applyPolicyEdit(existingRules, editingPolicy, newPolicy);
1821
1994
  if (!edit.ok) {
1822
1995
  snackbarController.open({
1823
1996
  type: "error",
@@ -1835,7 +2008,7 @@ var RLSEditor = ({ apiUrl = "" }) => {
1835
2008
  }
1836
2009
  }
1837
2010
  try {
1838
- await saveSecurityRules(activeCollection.slug, newRules);
2011
+ await saveSecurityRules(activeDescriptor, newRules);
1839
2012
  snackbarController.open({
1840
2013
  type: "success",
1841
2014
  message: "Policy saved successfully"
@@ -1889,7 +2062,15 @@ var RLSEditor = ({ apiUrl = "" }) => {
1889
2062
  children: /* @__PURE__ */ jsxs("div", {
1890
2063
  className: "max-w-4xl mx-auto flex flex-col gap-6",
1891
2064
  children: [
1892
- activeTableData && activeTableManaged && !(activeCollection && hasCodebase) && /* @__PURE__ */ jsx(Alert, {
2065
+ schemaProblem && /* @__PURE__ */ jsx(SchemaSourceProblemAlert, { problem: schemaProblem }),
2066
+ activeTableData && declaredWithheld && /* @__PURE__ */ jsx(Alert, {
2067
+ color: "info",
2068
+ children: /* @__PURE__ */ jsx(Typography, {
2069
+ variant: "caption",
2070
+ children: t("studio_rls_declared_withheld", { table: activeTableData.tableName })
2071
+ })
2072
+ }),
2073
+ activeTableData && activeTableManaged && !savesToCodebase && /* @__PURE__ */ jsx(Alert, {
1893
2074
  color: "info",
1894
2075
  children: /* @__PURE__ */ jsxs("div", {
1895
2076
  className: "flex items-start gap-2",
@@ -1978,7 +2159,7 @@ var RLSEditor = ({ apiUrl = "" }) => {
1978
2159
  color: "neutral",
1979
2160
  onClick: () => setEditingPolicy("new"),
1980
2161
  className: "shrink-0 whitespace-nowrap",
1981
- disabled: !activeCollection,
2162
+ disabled: !activeDescriptor,
1982
2163
  children: t("studio_rls_create_policy")
1983
2164
  })]
1984
2165
  }),
@@ -2033,15 +2214,15 @@ var RLSEditor = ({ apiUrl = "" }) => {
2033
2214
  }), /* @__PURE__ */ jsxs("div", {
2034
2215
  className: "flex gap-2 shrink-0 items-center",
2035
2216
  children: [
2036
- policy.status === "live" && activeCollection && hasCodebase && /* @__PURE__ */ jsx(Button, {
2217
+ policy.status === "live" && savesToCodebase && activeDescriptor && !declaredWithheld && /* @__PURE__ */ jsx(Button, {
2037
2218
  size: "small",
2038
2219
  variant: "outlined",
2039
2220
  color: "primary",
2040
2221
  onClick: async () => {
2041
2222
  const rule = policyToSecurityRule(policy);
2042
- const newRules = [...(isPostgresCollectionConfig(activeCollection) ? activeCollection.securityRules : void 0) || [], rule];
2223
+ const newRules = [...activeDescriptor.rls.rules, rule];
2043
2224
  try {
2044
- await saveSecurityRules(activeCollection.slug, newRules);
2225
+ await saveSecurityRules(activeDescriptor, newRules);
2045
2226
  snackbarController.open({
2046
2227
  type: "success",
2047
2228
  message: "Policy imported successfully"
@@ -2104,7 +2285,7 @@ var RLSEditor = ({ apiUrl = "" }) => {
2104
2285
  })
2105
2286
  ]
2106
2287
  }),
2107
- activeTableData && mergedPolicies.length === 0 && !activeTableData.rlsEnabled && activeCollection && /* @__PURE__ */ jsxs("div", {
2288
+ activeTableData && mergedPolicies.length === 0 && !activeTableData.rlsEnabled && activeDescriptor && /* @__PURE__ */ jsxs("div", {
2108
2289
  className: "flex flex-col items-center justify-center py-12 text-center",
2109
2290
  children: [
2110
2291
  /* @__PURE__ */ jsx(AlertTriangleIcon, {
@@ -2137,6 +2318,13 @@ var RLSEditor = ({ apiUrl = "" }) => {
2137
2318
  title: confirmToggleRls?.enabled ? t("studio_rls_disable_confirm_title") : t("studio_rls_enable_confirm_title"),
2138
2319
  body: confirmToggleRls?.enabled ? [t("studio_rls_disable_confirm_body", { table: confirmToggleRls.table }), confirmToggleRls.managed ? t("studio_rls_disable_reapplied", { table: confirmToggleRls.table }) : ""].filter(Boolean).join(" ") : t("studio_rls_enable_confirm_body", { table: confirmToggleRls?.table ?? "" })
2139
2320
  }),
2321
+ /* @__PURE__ */ jsx(ConfirmationDialog, {
2322
+ open: detaching !== null,
2323
+ onAccept: () => answerDetach(true),
2324
+ onCancel: () => answerDetach(false),
2325
+ title: t("schema_rules_detach_title"),
2326
+ body: t("schema_rules_detach_body", { table: detaching ?? "" })
2327
+ }),
2140
2328
  /* @__PURE__ */ jsx(ConfirmationDialog, {
2141
2329
  open: confirmDropPolicy !== null,
2142
2330
  loading: confirming,
@@ -2154,4 +2342,4 @@ var RLSEditor = ({ apiUrl = "" }) => {
2154
2342
  //#endregion
2155
2343
  export { RLSEditor };
2156
2344
 
2157
- //# sourceMappingURL=RLSEditor-zAat58U0.js.map
2345
+ //# sourceMappingURL=RLSEditor-BAwkENpj.js.map