@rebasepro/rls-check 0.25.1 → 0.26.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/index.es.js CHANGED
@@ -821,7 +821,7 @@ var COMMANDS_FOR = {
821
821
  * whose expression is an anonymous *tautology* rather than a constant are the
822
822
  * business of `policy-anonymous-tautology`, which can weigh the platform.
823
823
  */
824
- var anonymousWriteAllowed = {
824
+ var anonymousWriteAllowed$1 = {
825
825
  id: ID$14,
826
826
  title: "Unauthenticated callers can write",
827
827
  description: "A permissive INSERT/UPDATE/DELETE policy reachable without authentication whose check expression accepts any row, backed by a matching grant.",
@@ -953,7 +953,7 @@ var ID$13 = "current-setting-throws";
953
953
  * a `set_config` in the same transaction, in which case one argument is fine —
954
954
  * the check cannot see the session that will run the query.
955
955
  */
956
- var currentSettingThrows = {
956
+ var currentSettingThrows$1 = {
957
957
  id: ID$13,
958
958
  title: "Policy calls current_setting() without missing_ok",
959
959
  description: "A policy expression calling current_setting('x') with one argument, which raises rather than returning NULL when the setting is unset.",
@@ -1053,7 +1053,7 @@ var ID$12 = "grant-to-public";
1053
1053
  * given. When RLS is off it is simply open access — `rls-disabled` reports that
1054
1054
  * separately and with more force.
1055
1055
  */
1056
- var grantToPublic = {
1056
+ var grantToPublic$1 = {
1057
1057
  id: ID$12,
1058
1058
  title: "Table privileges granted to PUBLIC",
1059
1059
  description: "A SELECT/INSERT/UPDATE/DELETE privilege granted to PUBLIC on a table.",
@@ -1118,7 +1118,7 @@ var INCIDENTAL_COLUMNS = /* @__PURE__ */ new Set([
1118
1118
  * ordinary bookkeeping. A table with its own payload columns is a domain table
1119
1119
  * that happens to have two foreign keys, and is not reported here.
1120
1120
  */
1121
- var junctionTableUnprotected = {
1121
+ var junctionTableUnprotected$1 = {
1122
1122
  id: ID$11,
1123
1123
  title: "Many-to-many join table without RLS",
1124
1124
  description: "A table that is essentially just two foreign keys, both pointing at RLS-protected tables, that has no row-level security of its own.",
@@ -1200,7 +1200,7 @@ function ownerReadsPast(snapshot, owner, base) {
1200
1200
  * the rows do not depend on who asks, but heuristic: whether it hands out more
1201
1201
  * than a caller should see depends on the owner's policies.
1202
1202
  */
1203
- var viewBypassesRls = {
1203
+ var viewBypassesRls$1 = {
1204
1204
  id: ID$10,
1205
1205
  title: "View reads past its base table's RLS",
1206
1206
  description: "A view granted to an untrusted role that selects from an RLS-protected table and runs with its owner's privileges instead of the caller's.",
@@ -1252,7 +1252,7 @@ var ID$9 = "matview-bypasses-rls";
1252
1252
  * refresh time, so there is no policy anywhere that can filter a read of it. The
1253
1253
  * only controls are the grant and what the defining query selects.
1254
1254
  */
1255
- var matviewBypassesRls = {
1255
+ var matviewBypassesRls$1 = {
1256
1256
  id: ID$9,
1257
1257
  title: "Materialized view exposes RLS-protected data",
1258
1258
  description: "A materialized view granted to an untrusted role whose defining query reads a table with row-level security enabled.",
@@ -1303,7 +1303,7 @@ var ID$8 = "policy-always-true";
1303
1303
  * an accusation rather than disappearing (the restrictive policy may well not
1304
1304
  * cover the same rows).
1305
1305
  */
1306
- var policyAlwaysTrue = {
1306
+ var policyAlwaysTrue$1 = {
1307
1307
  id: ID$8,
1308
1308
  title: "Policy grants unconditional access",
1309
1309
  description: "A permissive policy whose USING or WITH CHECK expression is always true.",
@@ -1497,7 +1497,7 @@ var ID$7 = "policy-anonymous-tautology";
1497
1497
  * A guard that excludes *something else* is the interesting case — see
1498
1498
  * {@link matchTautology}.
1499
1499
  */
1500
- var policyAnonymousTautology = {
1500
+ var policyAnonymousTautology$1 = {
1501
1501
  id: ID$7,
1502
1502
  title: "Policy only checks that a caller id exists",
1503
1503
  description: "A policy whose expression is `auth.uid() IS NOT NULL`-shaped: it separates signed-in from signed-out callers but scopes no rows.",
@@ -2004,7 +2004,7 @@ var ID$6 = "policy-authenticated-tautology";
2004
2004
  * not `high`, because it is `TO authenticated USING (true)` spelled as an
2005
2005
  * expression, and the two spellings must not get different answers.
2006
2006
  */
2007
- var policyAuthenticatedTautology = {
2007
+ var policyAuthenticatedTautology$1 = {
2008
2008
  id: ID$6,
2009
2009
  title: "Policy admits every signed-in caller to every row",
2010
2010
  description: "A policy whose expression is only \"the caller is signed in and not anonymous\": it excludes signed-out callers correctly and scopes no rows between accounts.",
@@ -2099,7 +2099,7 @@ var ID$5 = "policy-role-unreachable";
2099
2099
  * answering the wrong question anyway, which is "do the requests my application
2100
2100
  * sends land on these policies?"
2101
2101
  */
2102
- var policyRoleUnreachable = {
2102
+ var policyRoleUnreachable$1 = {
2103
2103
  id: ID$5,
2104
2104
  title: "Policies target roles nothing connects as",
2105
2105
  description: "Every policy on a table names roles that do not exist, cannot log in, and that no login role inherits — so no policy ever applies and the table reads as empty.",
@@ -2154,7 +2154,7 @@ var ID$4 = "rls-disabled";
2154
2154
  * `ENABLE ROW LEVEL SECURITY` on one, so a grant to an exposed role hands over
2155
2155
  * whatever the remote server returns, and the fix is the grant, not a policy.
2156
2156
  */
2157
- var rlsDisabled = {
2157
+ var rlsDisabled$1 = {
2158
2158
  id: ID$4,
2159
2159
  title: "Table exposed without row-level security",
2160
2160
  description: "A table with RLS disabled that also grants SELECT/INSERT/UPDATE/DELETE to a role an unauthenticated or untrusted caller can reach.",
@@ -2205,7 +2205,7 @@ var ID$3 = "rls-enabled-no-policies";
2205
2205
  * is worth a finding precisely because nothing else reports it — a database in
2206
2206
  * this state passes every "is RLS enabled?" audit while serving nothing.
2207
2207
  */
2208
- var rlsEnabledNoPolicies = {
2208
+ var rlsEnabledNoPolicies$1 = {
2209
2209
  id: ID$3,
2210
2210
  title: "RLS enabled with no policies (denies everything)",
2211
2211
  description: "A table with row-level security enabled but not a single policy defined.",
@@ -2271,7 +2271,7 @@ var ID$2 = "rls-enabled-not-forced";
2271
2271
  * Reporting `high` here would be misleading — the fix is "do not connect as
2272
2272
  * this role", not "set FORCE".
2273
2273
  */
2274
- var rlsEnabledNotForced = {
2274
+ var rlsEnabledNotForced$1 = {
2275
2275
  id: ID$2,
2276
2276
  title: "RLS enabled but not forced for the table owner",
2277
2277
  description: "A table with RLS enabled where the owning role is exempt from its own policies.",
@@ -2346,7 +2346,7 @@ var ID$1 = "security-definer-mutable-search-path";
2346
2346
  * Whether it is exploitable depends on who can create objects, which is why the
2347
2347
  * impact line says so rather than claiming a working escalation.
2348
2348
  */
2349
- var securityDefinerMutableSearchPath = {
2349
+ var securityDefinerMutableSearchPath$1 = {
2350
2350
  id: ID$1,
2351
2351
  title: "SECURITY DEFINER routine with a mutable search_path",
2352
2352
  description: "A SECURITY DEFINER function or procedure that does not pin search_path, so the caller controls how its identifiers resolve.",
@@ -2366,17 +2366,26 @@ var securityDefinerMutableSearchPath = {
2366
2366
  },
2367
2367
  detail: `This routine runs with the privileges of its owner (${routine.owner}) but resolves unqualified names using the *caller's* search_path, because no \`SET search_path\` is attached to it. A caller who can create objects in any schema on that path can shadow a table or function the routine uses, and their object then runs as ${routine.owner}.`,
2368
2368
  impact: `Any role that can both execute this routine and create objects in a schema on its search_path can have arbitrary SQL run as ${routine.owner} — which bypasses row-level security on every table ${routine.owner} can reach. Without CREATE on some schema this is not directly exploitable, so check who holds CREATE (commonly PUBLIC on \`public\` in older databases).`,
2369
- fix: `-- Pin the search_path on every overload of this routine:\n` + dollarQuotedDo(`DECLARE r record;
2370
- BEGIN
2371
- FOR r IN
2372
- SELECT p.oid::regprocedure AS sig
2373
- FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
2374
- WHERE n.nspname = ${literal(routine.schema)} AND p.proname = ${literal(routine.name)}\n LOOP\n EXECUTE format('ALTER ROUTINE %s SET search_path = pg_catalog, pg_temp', r.sig);\n END LOOP;\nEND`) + "\n-- Then schema-qualify every identifier in the body, since nothing but\n-- pg_catalog is on the path any more."
2369
+ fix: `-- Pin the search_path on every overload of this routine:\n` + pinSearchPathSql(routine.schema, routine.name) + "\n-- Then schema-qualify every identifier in the body, since nothing but\n-- pg_catalog is on the path any more."
2375
2370
  }));
2376
2371
  }
2377
2372
  return findings;
2378
2373
  }
2379
2374
  };
2375
+ /**
2376
+ * A `DO` block that pins `search_path` on every overload of `schema.name`.
2377
+ *
2378
+ * Exported for the agent output, which prints the same statement as its
2379
+ * runnable SQL.
2380
+ */
2381
+ function pinSearchPathSql(schema, name) {
2382
+ return dollarQuotedDo(`DECLARE r record;
2383
+ BEGIN
2384
+ FOR r IN
2385
+ SELECT p.oid::regprocedure AS sig
2386
+ FROM pg_proc p JOIN pg_namespace n ON n.oid = p.pronamespace
2387
+ WHERE n.nspname = ${literal(schema)} AND p.proname = ${literal(name)}\n LOOP\n EXECUTE format('ALTER ROUTINE %s SET search_path = pg_catalog, pg_temp', r.sig);\n END LOOP;\nEND`);
2388
+ }
2380
2389
  var literal = (value) => `'${value.replace(/'/g, "''")}'`;
2381
2390
  /**
2382
2391
  * `DO $$ … $$;`, with a dollar-quote tag the body does not contain.
@@ -2435,7 +2444,7 @@ var ID = "unqualified-column-in-subquery";
2435
2444
  * back as `m.organization_id = m.id`, which is indistinguishable from a
2436
2445
  * comparison somebody meant.
2437
2446
  */
2438
- var unqualifiedColumnInSubquery = {
2447
+ var unqualifiedColumnInSubquery$1 = {
2439
2448
  id: ID,
2440
2449
  title: "Unqualified column inside a policy subquery",
2441
2450
  description: "A bare column name in an EXISTS/IN subquery that exists on both the inner relation and the policy's own table, so Postgres binds it to the inner one.",
@@ -2445,11 +2454,7 @@ var unqualifiedColumnInSubquery = {
2445
2454
  if (!snapshot.schemas.includes(policy.schema)) continue;
2446
2455
  const outer = relationAt(snapshot, policy.schema, policy.table);
2447
2456
  if (!outer) continue;
2448
- for (const clause of ["USING", "WITH CHECK"]) {
2449
- const expr = clause === "USING" ? policy.using : policy.withCheck;
2450
- if (!expr) continue;
2451
- for (const hit of scanExpression(snapshot, outer, expr)) findings.push(buildFinding(snapshot, policy, outer, clause, hit));
2452
- }
2457
+ for (const { clause, hit } of policyAmbiguities(snapshot, policy)) findings.push(buildFinding(snapshot, policy, outer, clause, hit));
2453
2458
  }
2454
2459
  return findings;
2455
2460
  }
@@ -2704,6 +2709,26 @@ function resolveRelation(snapshot, policySchema, item) {
2704
2709
  const candidates = snapshot.relations.filter((r) => r.name === item.name && snapshot.schemas.includes(r.schema));
2705
2710
  return candidates.length === 1 ? candidates[0] : void 0;
2706
2711
  }
2712
+ /**
2713
+ * Every ambiguity this check reports on one policy, with the clause it sits in.
2714
+ *
2715
+ * The same scan `run` makes, exposed so the agent output can rewrite the exact
2716
+ * comparison a finding names rather than restate a generic template.
2717
+ */
2718
+ function policyAmbiguities(snapshot, policy) {
2719
+ const outer = relationAt(snapshot, policy.schema, policy.table);
2720
+ if (!outer) return [];
2721
+ const out = [];
2722
+ for (const clause of ["USING", "WITH CHECK"]) {
2723
+ const expr = clause === "USING" ? policy.using : policy.withCheck;
2724
+ if (!expr) continue;
2725
+ for (const hit of scanExpression(snapshot, outer, expr)) out.push({
2726
+ clause,
2727
+ hit
2728
+ });
2729
+ }
2730
+ return out;
2731
+ }
2707
2732
  function buildFinding(snapshot, policy, outer, clause, hit) {
2708
2733
  const innerSql = qrel(hit.innerRelation.schema, hit.innerRelation.name);
2709
2734
  const self = hit.kind === "self";
@@ -2734,21 +2759,21 @@ function buildFinding(snapshot, policy, outer, clause, hit) {
2734
2759
  //#endregion
2735
2760
  //#region src/checks/index.ts
2736
2761
  var CHECKS = [
2737
- rlsDisabled,
2738
- policyAlwaysTrue,
2739
- policyAnonymousTautology,
2740
- policyAuthenticatedTautology,
2741
- viewBypassesRls,
2742
- matviewBypassesRls,
2743
- anonymousWriteAllowed,
2744
- unqualifiedColumnInSubquery,
2745
- junctionTableUnprotected,
2746
- rlsEnabledNotForced,
2747
- rlsEnabledNoPolicies,
2748
- policyRoleUnreachable,
2749
- grantToPublic,
2750
- securityDefinerMutableSearchPath,
2751
- currentSettingThrows
2762
+ rlsDisabled$1,
2763
+ policyAlwaysTrue$1,
2764
+ policyAnonymousTautology$1,
2765
+ policyAuthenticatedTautology$1,
2766
+ viewBypassesRls$1,
2767
+ matviewBypassesRls$1,
2768
+ anonymousWriteAllowed$1,
2769
+ unqualifiedColumnInSubquery$1,
2770
+ junctionTableUnprotected$1,
2771
+ rlsEnabledNotForced$1,
2772
+ rlsEnabledNoPolicies$1,
2773
+ policyRoleUnreachable$1,
2774
+ grantToPublic$1,
2775
+ securityDefinerMutableSearchPath$1,
2776
+ currentSettingThrows$1
2752
2777
  ];
2753
2778
  /**
2754
2779
  * Run every selected check and return the findings, worst first.
@@ -2961,7 +2986,7 @@ function redactConnectionString(raw) {
2961
2986
  }
2962
2987
  return `${target.scheme}://${credential}${endpoint}${database}${query}`;
2963
2988
  }
2964
- function escapeRegExp(value) {
2989
+ function escapeRegExp$1(value) {
2965
2990
  return value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
2966
2991
  }
2967
2992
  /**
@@ -2983,11 +3008,11 @@ function redactSecrets(text, connectionString) {
2983
3008
  const raw = connectionString.trim();
2984
3009
  out = out.split(raw).join(redactConnectionString(raw));
2985
3010
  const target = parseConnectionString(raw);
2986
- if (target?.user && target.user.length > 0) out = out.replace(new RegExp(`"${escapeRegExp(target.user)}"`, "g"), `"***"`);
3011
+ if (target?.user && target.user.length > 0) out = out.replace(new RegExp(`"${escapeRegExp$1(target.user)}"`, "g"), `"***"`);
2987
3012
  if (target?.password && target.password.length >= 3) {
2988
- out = out.replace(new RegExp(escapeRegExp(target.password), "g"), "***");
3013
+ out = out.replace(new RegExp(escapeRegExp$1(target.password), "g"), "***");
2989
3014
  const encoded = encodeURIComponent(target.password);
2990
- if (encoded !== target.password) out = out.replace(new RegExp(escapeRegExp(encoded), "g"), "***");
3015
+ if (encoded !== target.password) out = out.replace(new RegExp(escapeRegExp$1(encoded), "g"), "***");
2991
3016
  }
2992
3017
  }
2993
3018
  out = out.replace(/\b([a-zA-Z][a-zA-Z0-9+.-]*):\/\/([^\s"'<>]*?)@/g, (_match, scheme) => `${scheme}://***:***@`);
@@ -3022,11 +3047,13 @@ function isLoopbackEndpoint(endpoint) {
3022
3047
  * on the assumption that it will be pointed at production by someone who has
3023
3048
  * never heard of us. So:
3024
3049
  *
3025
- * - The session is opened `default_transaction_read_only` and the work runs
3026
- * inside `BEGIN READ ONLY`. Not as a convention — as a guarantee, so that a
3027
- * bug here cannot write.
3028
- * - `statement_timeout` is set before anything else runs, so a scan of a large
3029
- * catalog cannot pin a connection.
3050
+ * - The work runs inside `BEGIN READ ONLY`. Not as a convention — as a
3051
+ * guarantee, so that a bug here cannot write.
3052
+ * - `statement_timeout` is set (`SET LOCAL`) before anything else runs, so a
3053
+ * scan of a large catalog cannot pin a connection.
3054
+ * - Nothing is set for the session. The session may be shared — Rebase's
3055
+ * managed dev database, a transaction-mode pooler — and must be left as
3056
+ * it was found.
3030
3057
  * - Privileges are read from `pg_class.relacl` via `aclexplode`, not from
3031
3058
  * `information_schema.role_table_grants`. The information_schema views only
3032
3059
  * show grants involving roles the caller is a member of, so a non-superuser
@@ -3158,12 +3185,10 @@ async function introspectWithDiagnostics(opts) {
3158
3185
  const { client, tlsVerificationDisabled } = await connect(opts.connectionString);
3159
3186
  diagnostics.tlsVerificationDisabled = tlsVerificationDisabled;
3160
3187
  try {
3161
- const timeout = Math.max(1e3, Math.floor(opts.statementTimeoutMs ?? 15e3));
3162
- await client.query(`SET statement_timeout = ${timeout}`);
3163
- await client.query("SET default_transaction_read_only = on");
3164
- await client.query("BEGIN READ ONLY");
3188
+ const begin = beginReadOnly(client, Math.max(1e3, Math.floor(opts.statementTimeoutMs ?? 15e3)));
3189
+ await begin();
3165
3190
  try {
3166
- const snapshot = await readSnapshot(client, opts, diagnostics);
3191
+ const snapshot = await readSnapshot(client, opts, diagnostics, begin);
3167
3192
  await client.query("COMMIT");
3168
3193
  return {
3169
3194
  snapshot,
@@ -3332,7 +3357,24 @@ function readParam(connectionString, name) {
3332
3357
  function stripParam(connectionString, name) {
3333
3358
  return connectionString.replace(new RegExp(`([?&])${name}=[^&]*&?`, "gi"), "$1").replace(/[?&]$/, "");
3334
3359
  }
3335
- function reader(client, diagnostics) {
3360
+ /**
3361
+ * Open the scan's read-only transaction, with its statement timeout.
3362
+ *
3363
+ * Both are set for the transaction only — `BEGIN READ ONLY` and `SET LOCAL` —
3364
+ * never for the session. The session may not be ours: Rebase's managed
3365
+ * development database serves every client on ONE shared PGlite session, and
3366
+ * a session-level `default_transaction_read_only = on` left there made the
3367
+ * running dev backend, `db push` and sign-up fail every write with "cannot
3368
+ * execute … in a read-only transaction" until `rebase db stop`. A pooler in
3369
+ * transaction mode hands a session to the next client the same way.
3370
+ */
3371
+ function beginReadOnly(client, timeoutMs) {
3372
+ return async () => {
3373
+ await client.query("BEGIN READ ONLY");
3374
+ await client.query(`SET LOCAL statement_timeout = ${timeoutMs}`);
3375
+ };
3376
+ }
3377
+ function reader(client, diagnostics, begin) {
3336
3378
  return { async query(what, text, values) {
3337
3379
  try {
3338
3380
  return (await client.query(text, values)).rows;
@@ -3342,13 +3384,13 @@ function reader(client, diagnostics) {
3342
3384
  error: error instanceof Error ? error.message : String(error)
3343
3385
  });
3344
3386
  await client.query("ROLLBACK").catch(() => void 0);
3345
- await client.query("BEGIN READ ONLY").catch(() => void 0);
3387
+ await begin().catch(() => void 0);
3346
3388
  return [];
3347
3389
  }
3348
3390
  } };
3349
3391
  }
3350
- async function readSnapshot(client, opts, diagnostics) {
3351
- const db = reader(client, diagnostics);
3392
+ async function readSnapshot(client, opts, diagnostics, begin) {
3393
+ const db = reader(client, diagnostics, begin);
3352
3394
  const [server] = await db.query("server version and current role", `SELECT current_setting('server_version_num') AS version_num,
3353
3395
  current_setting('server_version') AS version,
3354
3396
  current_user AS role_name,
@@ -4361,6 +4403,804 @@ function renderCheckCatalog(checks, options) {
4361
4403
  return `${out.join("\n")}\n`;
4362
4404
  }
4363
4405
  //#endregion
4406
+ //#region src/remediation.ts
4407
+ /**
4408
+ * Remediations for `--format agent`: for every finding, the SQL that fixes it
4409
+ * and the Rebase `securityRules` that say the same thing.
4410
+ *
4411
+ * The `fix` a check writes is for a person reading a terminal — prose, options
4412
+ * and commented-out examples. A coding agent needs something else: one
4413
+ * statement it can run, a list of the blanks it has to fill before running it,
4414
+ * and a flag saying when SQL is the wrong place for the change altogether. So
4415
+ * this is written per check id, from the snapshot, rather than parsed out of
4416
+ * the `fix` text.
4417
+ *
4418
+ * Three rules hold for every builder here:
4419
+ *
4420
+ * 1. `sql` is runnable as printed, once every token in `placeholders` has been
4421
+ * replaced. Nothing in it is a comment the agent has to interpret. Where the
4422
+ * tool cannot know a value — the column that holds a row's owner, the role
4423
+ * an application connects as — it says so with a placeholder rather than
4424
+ * guessing, because a guessed column fails on paste and a guessed role can
4425
+ * widen access.
4426
+ *
4427
+ * 2. Applying `sql` clears the finding it is attached to. A fix that leaves the
4428
+ * finding standing teaches the agent to stop trusting the tool.
4429
+ *
4430
+ * 3. The Rebase rules mean what the SQL means. `ownerField` compiles to
4431
+ * `<column>::text = rebase.uid()`; a raw rule carries the corrected
4432
+ * expression. Where `securityRules` cannot express the fix at all — grants,
4433
+ * views, functions, FORCE — `rebase.applicable` is false and the note says
4434
+ * what Rebase does instead, rather than inventing a rule.
4435
+ *
4436
+ * The TypeScript in `rebase.securityRules` is type-checked against
4437
+ * `SecurityRule` from `@rebasepro/types` by `remediation.test.ts`. This package
4438
+ * cannot import that type — it ships with `pg` and nothing else — so the shapes
4439
+ * written here are held to it by the test instead.
4440
+ */
4441
+ var RULE_KEYS = [
4442
+ "name",
4443
+ "operation",
4444
+ "mode",
4445
+ "ownerField",
4446
+ "using",
4447
+ "withCheck"
4448
+ ];
4449
+ /** `{ operation: "all", ownerField: "user_id" }` — one line, fixed key order. */
4450
+ function ruleSource(rule) {
4451
+ return `{ ${RULE_KEYS.flatMap((key) => {
4452
+ const value = rule[key];
4453
+ return value === void 0 ? [] : [`${key}: ${JSON.stringify(value)}`];
4454
+ }).join(", ")} }`;
4455
+ }
4456
+ function rulesSource(rules, indent = "") {
4457
+ return `[\n${rules.map((r) => `${indent} ${ruleSource(r)}`).join(",\n")}\n${indent}]`;
4458
+ }
4459
+ function collectionSnippet(schema, table, rules) {
4460
+ return [
4461
+ `// The collection whose table is ${schema}.${table} (config/collections/ in a Rebase project)`,
4462
+ `defineCollection({`,
4463
+ ` // …name, slug, properties and the rest stay as they are…`,
4464
+ ` table: ${JSON.stringify(table)},`,
4465
+ ...schema === "public" ? [] : [` schema: ${JSON.stringify(schema)},`],
4466
+ ` securityRules: ${rulesSource(rules, " ")}`,
4467
+ `});`
4468
+ ].join("\n");
4469
+ }
4470
+ function rebaseRules(schema, table, rules, note) {
4471
+ return {
4472
+ applicable: true,
4473
+ securityRules: rulesSource(rules),
4474
+ snippet: collectionSnippet(schema, table, rules),
4475
+ note: `${note} ${SECURITY_RULES_DOCS}`
4476
+ };
4477
+ }
4478
+ function noRebaseRule(note) {
4479
+ return {
4480
+ applicable: false,
4481
+ securityRules: null,
4482
+ snippet: null,
4483
+ note
4484
+ };
4485
+ }
4486
+ var OPERATION = {
4487
+ ALL: "all",
4488
+ SELECT: "select",
4489
+ INSERT: "insert",
4490
+ UPDATE: "update",
4491
+ DELETE: "delete"
4492
+ };
4493
+ /**
4494
+ * The rule that compiles to `policy` with these clauses. A Rebase-managed
4495
+ * policy's name is derived from the rule, so it is left for Rebase to derive;
4496
+ * a hand-written one keeps its own.
4497
+ */
4498
+ function rawRule(snapshot, policy, using, withCheck) {
4499
+ return {
4500
+ ...isRebaseManagedPolicy(snapshot, policy) ? {} : { name: policy.name },
4501
+ operation: OPERATION[policy.command],
4502
+ ...policy.permissive ? {} : { mode: "restrictive" },
4503
+ ...using !== null ? { using } : {},
4504
+ ...withCheck !== null ? { withCheck } : {}
4505
+ };
4506
+ }
4507
+ function ownerRule(snapshot, policy, operation, ownerField) {
4508
+ return {
4509
+ ...policy && !isRebaseManagedPolicy(snapshot, policy) ? { name: policy.name } : {},
4510
+ operation,
4511
+ ...policy && !policy.permissive ? { mode: "restrictive" } : {},
4512
+ ownerField
4513
+ };
4514
+ }
4515
+ var OWNER_FIELD_NOTE = "Rebase enables row-level security on every collection's table and compiles each rule into a policy at boot and on `rebase db push`; `ownerField` compiles to `<column>::text = rebase.uid()`, so a row is visible and writable only to the user whose id it holds.";
4516
+ var RAW_RULE_NOTE = "A raw rule keeps the expression as SQL; Rebase writes it into the policy as is, with `{column}` standing for the row being checked.";
4517
+ /**
4518
+ * Raw expressions copied from a database Rebase did not create may call
4519
+ * Supabase's helpers. Rebase rewrites `auth.uid()` to `rebase.uid()` — which
4520
+ * returns text, where Supabase's returns uuid.
4521
+ */
4522
+ function rawRuleNote(snapshot, ...exprs) {
4523
+ const callsAuth = exprs.some((e) => e !== null && /\bauth\s*\.\s*\w+\s*\(/i.test(e));
4524
+ if (snapshot.platform === "rebase" || !callsAuth) return RAW_RULE_NOTE;
4525
+ return `${RAW_RULE_NOTE} Rebase rewrites \`auth.uid()\` to \`rebase.uid()\`, which returns text: compare a uuid column with it as \`{column}::text = rebase.uid()\`.`;
4526
+ }
4527
+ var clauseExpr = (policy, clause) => clause === "USING" ? policy.using : policy.withCheck;
4528
+ /** The clauses of `policy` whose expression `test` flags. */
4529
+ function flaggedClauses(policy, test) {
4530
+ return ["USING", "WITH CHECK"].filter((clause) => {
4531
+ const expr = clauseExpr(policy, clause);
4532
+ return expr !== null && test(expr);
4533
+ });
4534
+ }
4535
+ function alterPolicySql(policy, replace) {
4536
+ const lines = [`ALTER POLICY ${qi(policy.name)} ON ${qrel(policy.schema, policy.table)}`];
4537
+ for (const clause of ["USING", "WITH CHECK"]) {
4538
+ const expr = replace[clause];
4539
+ if (expr !== void 0) lines.push(` ${clause} (${expr})`);
4540
+ }
4541
+ return `${lines.join("\n")};`;
4542
+ }
4543
+ /** A policy name the table does not already use. */
4544
+ function freshPolicyName(snapshot, schema, table, base) {
4545
+ const taken = new Set(policiesFor(snapshot, schema, table).map((p) => p.name));
4546
+ let name = base;
4547
+ for (let i = 2; taken.has(name); i++) name = `${base}_${i}`;
4548
+ return name;
4549
+ }
4550
+ var OWNER_PLACEHOLDER = "<owner_column>";
4551
+ var APP_ROLE_PLACEHOLDER = "<app_role>";
4552
+ /** Types `auth.uid()`'s uuid can be compared with once cast to text. */
4553
+ var TEXT_TYPE = /^(text|citext|character varying|varchar)\b/;
4554
+ /**
4555
+ * "This row belongs to the caller", spelled for this table and this platform.
4556
+ *
4557
+ * The column is one that looks like the owner's id *and* compares with the
4558
+ * caller id without an error: `auth.uid()` is a uuid, so a uuid column
4559
+ * compares directly, a text column through `::text`, and an integer
4560
+ * `account_id` not at all — that table gets a placeholder rather than a
4561
+ * statement that fails with "operator does not exist". Rebase's `rebase.uid()`
4562
+ * is text, and its own compiler casts the column, so this does too.
4563
+ */
4564
+ function ownerScope(snapshot, rel) {
4565
+ const uid = callerIdCall(snapshot);
4566
+ const rebase = snapshot.platform === "rebase";
4567
+ for (const name of OWNER_COLUMNS) {
4568
+ const column = rel?.columns.find((c) => c.name === name);
4569
+ if (!column) continue;
4570
+ if (rebase) return {
4571
+ sql: `${qi(name)}::text = ${uid}`,
4572
+ ownerField: name,
4573
+ placeholders: []
4574
+ };
4575
+ if (column.type === "uuid") return {
4576
+ sql: `${qi(name)} = ${uid}`,
4577
+ ownerField: name,
4578
+ placeholders: []
4579
+ };
4580
+ if (TEXT_TYPE.test(column.type)) return {
4581
+ sql: `${qi(name)} = ${uid}::text`,
4582
+ ownerField: name,
4583
+ placeholders: []
4584
+ };
4585
+ }
4586
+ const where = rel ? `${rel.schema}.${rel.name}` : "the table";
4587
+ return {
4588
+ sql: rebase ? `${OWNER_PLACEHOLDER}::text = ${uid}` : `${OWNER_PLACEHOLDER} = ${uid}`,
4589
+ ownerField: OWNER_PLACEHOLDER,
4590
+ placeholders: [{
4591
+ token: OWNER_PLACEHOLDER,
4592
+ meaning: `The column of ${where} that holds the id of the user who owns the row, as a quoted identifier (e.g. "user_id"); in the Rebase rule, its property name. ` + (rebase ? `The SQL already casts it to text to compare with ${uid}.` : `${uid} returns uuid: for a text column write "<column>" = ${uid}::text instead.`)
4593
+ }]
4594
+ };
4595
+ }
4596
+ /**
4597
+ * `auth.uid()` exists on Supabase. Elsewhere it is this tool's best guess at
4598
+ * the convention, and the SQL that calls it fails if the function is absent.
4599
+ */
4600
+ function callerCaveats(snapshot, scope) {
4601
+ if (snapshot.platform === "supabase" || snapshot.platform === "rebase") return [];
4602
+ if (!scope.sql.includes("auth.uid()")) return [];
4603
+ return ["This database was not recognised as Supabase, so `auth.uid()` may not exist here. Replace it with however your API hands Postgres the caller's id — on PostgREST, `(current_setting('request.jwt.claims', true)::json ->> 'sub')`, cast to the owner column's type."];
4604
+ }
4605
+ var RLS_FILTERS_EVERYONE = "With row-level security on, every role that neither owns the table nor holds BYPASSRLS sees only the rows a policy admits — a backend job connecting as such a role is filtered too.";
4606
+ function managedCaveat(policy) {
4607
+ return `Policy "${policy.name}" is compiled by Rebase from a collection's \`securityRules\` and dropped and re-created on every boot, so an ALTER POLICY would be undone at the next restart. Change the rule, then redeploy or run \`rebase db push\`. A collection that declares no \`securityRules\` of its own inherits \`defaultSecurityRules\` from config/collections/index.ts — a stock scaffold's unfiltered read rule lives there.`;
4608
+ }
4609
+ function policyAt(snapshot, finding) {
4610
+ const { schema, table, policy } = finding.target;
4611
+ return snapshot.policies.find((p) => p.schema === schema && p.table === table && p.name === policy);
4612
+ }
4613
+ /** For a finding whose object is no longer in the snapshot it came from. */
4614
+ function unresolved(finding) {
4615
+ return {
4616
+ summary: `rls-check could not rebuild the object this ${finding.id} finding names from the scan, so it has no statement to offer; read the finding's detail and docs.`,
4617
+ apply: "manual",
4618
+ sql: null,
4619
+ placeholders: [],
4620
+ alternatives: [],
4621
+ caveats: [],
4622
+ rebase: noRebaseRule("No rule could be derived without the object.")
4623
+ };
4624
+ }
4625
+ /**
4626
+ * Rewrite the flagged clauses of `policy` to "the row belongs to the caller".
4627
+ *
4628
+ * Only the flagged clauses: a policy whose USING is a membership check and
4629
+ * whose WITH CHECK is `true` keeps its membership check. And every flagged
4630
+ * clause: rewriting USING while a `WITH CHECK (true)` beside it survives left
4631
+ * the policy — and the finding — standing.
4632
+ */
4633
+ function scopePolicyToOwner(snapshot, finding, clauses, words) {
4634
+ const policy = policyAt(snapshot, finding);
4635
+ if (!policy || clauses.length === 0) return unresolved(finding);
4636
+ const scope = ownerScope(snapshot, relationAt(snapshot, policy.schema, policy.table));
4637
+ const rule = ownerRule(snapshot, policy, OPERATION[policy.command], scope.ownerField);
4638
+ const rebase = rebaseRules(policy.schema, policy.table, [rule], OWNER_FIELD_NOTE);
4639
+ if (isRebaseManagedPolicy(snapshot, policy)) return {
4640
+ summary: words.managedSummary,
4641
+ apply: "rebase-config",
4642
+ sql: null,
4643
+ placeholders: scope.placeholders,
4644
+ alternatives: [],
4645
+ caveats: [managedCaveat(policy)],
4646
+ rebase
4647
+ };
4648
+ return {
4649
+ summary: words.summary,
4650
+ apply: "sql",
4651
+ sql: alterPolicySql(policy, Object.fromEntries(clauses.map((c) => [c, scope.sql]))),
4652
+ placeholders: scope.placeholders,
4653
+ alternatives: words.alternatives ?? [],
4654
+ caveats: [...callerCaveats(snapshot, scope), ...words.caveats ?? []],
4655
+ rebase
4656
+ };
4657
+ }
4658
+ function where(finding) {
4659
+ const { schema, table, policy } = finding.target;
4660
+ return `policy "${policy ?? "?"}" on ${schema}.${table ?? "?"}`;
4661
+ }
4662
+ function dropAlternative(policy) {
4663
+ if (!policy) return [];
4664
+ return [{
4665
+ summary: "If another policy already grants the access this one was meant to, drop this one instead.",
4666
+ sql: `DROP POLICY ${qi(policy.name)} ON ${qrel(policy.schema, policy.table)};`
4667
+ }];
4668
+ }
4669
+ function policyAlwaysTrue(snapshot, finding) {
4670
+ const policy = policyAt(snapshot, finding);
4671
+ const clauses = policy ? flaggedClauses(policy, isUnconditionalTrue) : [];
4672
+ return scopePolicyToOwner(snapshot, finding, clauses, {
4673
+ summary: `Replace the constant true in ${where(finding)} (${clauses.join(" and ")}) with a condition that limits each row to its owner.`,
4674
+ managedSummary: `Replace the rule that compiles to ${where(finding)} — an \`access: "public"\` rule, or a raw \`using: "true"\` — with one scoped to the row's owner.`,
4675
+ caveats: ["If unconditional access is what this table is for (a public catalogue, say), keep the policy and run rls-check with --skip policy-always-true instead: the SQL narrows what every caller sees."],
4676
+ alternatives: dropAlternative(policy)
4677
+ });
4678
+ }
4679
+ function policyAnonymousTautology(snapshot, finding) {
4680
+ const policy = policyAt(snapshot, finding);
4681
+ const clauses = policy ? flaggedClauses(policy, (e) => {
4682
+ const match = callerIdOnlyClause(e);
4683
+ return match !== null && !match.guardsSentinel;
4684
+ }) : [];
4685
+ return scopePolicyToOwner(snapshot, finding, clauses, {
4686
+ summary: `Replace the "caller id is not null" test in ${where(finding)} (${clauses.join(" and ")}) with one that compares the row's owner column to the caller id.`,
4687
+ managedSummary: `Replace the rule that compiles to ${where(finding)} with an \`ownerField\` rule — before 1.0, \`access: "authenticated"\` compiled to exactly this shape, so a database pushed then still carries it.`,
4688
+ alternatives: policy ? [{
4689
+ summary: "If the intent really is \"any signed-in user, every row\", exclude every id your stack uses for a signed-out caller — rls-check then reports it as policy-authenticated-tautology, which you can --skip.",
4690
+ sql: alterPolicySql(policy, Object.fromEntries(clauses.map((c) => {
4691
+ const uid = callerIdCall(snapshot);
4692
+ return [c, `${uid} IS NOT NULL AND ${uid}::text <> ALL (ARRAY['anonymous', 'anon'])`];
4693
+ })))
4694
+ }] : []
4695
+ });
4696
+ }
4697
+ function policyAuthenticatedTautology(snapshot, finding) {
4698
+ const policy = policyAt(snapshot, finding);
4699
+ const clauses = policy ? flaggedClauses(policy, (e) => signedInRoleOnlyClause(e) !== null || callerIdOnlyClause(e)?.guardsSentinel === true) : [];
4700
+ return scopePolicyToOwner(snapshot, finding, clauses, {
4701
+ summary: `Replace the "caller is signed in" test in ${where(finding)} (${clauses.join(" and ")}) with one that limits each row to its owner, so one account no longer reads another's rows.`,
4702
+ managedSummary: `Replace the rule that compiles to ${where(finding)} with an \`ownerField\` rule, or a \`condition\` naming the group whose members may share rows.`,
4703
+ caveats: ["Where members of a shared group (an organisation, a team) may see each other's rows, scope the policy to that membership instead of the owner. If every account genuinely may read every row, keep the policy and run rls-check with --skip policy-authenticated-tautology."]
4704
+ });
4705
+ }
4706
+ function anonymousWriteAllowed(snapshot, finding) {
4707
+ const policy = policyAt(snapshot, finding);
4708
+ const clauses = policy ? flaggedClauses(policy, isUnconditionalTrue) : [];
4709
+ const alternatives = [];
4710
+ if (policy && snapshot.platform !== "rebase") {
4711
+ const anonymous = snapshot.exposedRoles.filter((r) => ANONYMOUS_ROLES.includes(r.toLowerCase()));
4712
+ const commands = WRITE_PRIVILEGES.filter((p) => policy.command === "ALL" || p === policy.command);
4713
+ const revokes = revokesReaching(snapshot, policy.schema, policy.table, anonymous, commands);
4714
+ if (revokes.length > 0) alternatives.push({
4715
+ summary: "If no unauthenticated caller should ever write this table, also take the privilege away.",
4716
+ sql: revokes.join("\n")
4717
+ });
4718
+ }
4719
+ return scopePolicyToOwner(snapshot, finding, clauses, {
4720
+ summary: `Scope the writes ${where(finding)} admits to the row's owner, so a request without credentials — whose caller id matches no row — is refused.`,
4721
+ managedSummary: `Scope the write rule that compiles to ${where(finding)} to the caller with an \`ownerField\`, or restrict it with \`roles\`; revoking the grant instead would be re-made at boot.`,
4722
+ alternatives
4723
+ });
4724
+ }
4725
+ function rlsDisabled(snapshot, finding) {
4726
+ const { schema, table } = finding.target;
4727
+ const rel = table ? relationAt(snapshot, schema, table) : void 0;
4728
+ if (!rel) return unresolved(finding);
4729
+ const exposed = exposedGrantees(snapshot, rel.schema, rel.name, DML).map((e) => e.role);
4730
+ const revokes = revokesReaching(snapshot, rel.schema, rel.name, exposed, DML);
4731
+ if (rel.kind === "foreign_table") return {
4732
+ summary: `Revoke the API roles' privileges on ${rel.schema}.${rel.name}: it is a foreign table, and Postgres cannot put row-level security on one.`,
4733
+ apply: "sql",
4734
+ sql: revokes.join("\n"),
4735
+ placeholders: [],
4736
+ alternatives: [],
4737
+ caveats: ["Callers that need this data must then reach it through a function or view that checks the caller, kept in a schema your API does not expose."],
4738
+ rebase: noRebaseRule("Not expressible: a foreign table cannot have row-level security, and securityRules compile to policies. Keep it out of the collections a Rebase backend serves.")
4739
+ };
4740
+ const scope = ownerScope(snapshot, rel);
4741
+ const existing = policiesFor(snapshot, rel.schema, rel.name);
4742
+ const enable = `ALTER TABLE ${qrel(rel.schema, rel.name)} ENABLE ROW LEVEL SECURITY;`;
4743
+ const create = `CREATE POLICY ${qi(freshPolicyName(snapshot, rel.schema, rel.name, `${rel.name}_owner`))} ON ${qrel(rel.schema, rel.name)}\n FOR ALL\n USING (${scope.sql})\n WITH CHECK (${scope.sql});`;
4744
+ const rebase = rebaseRules(rel.schema, rel.name, [{
4745
+ operation: "all",
4746
+ ownerField: scope.ownerField
4747
+ }], `${OWNER_FIELD_NOTE} Declare the table as a collection, or add the rule to the one that maps it.`);
4748
+ const revokeAlternative = revokes.length > 0 ? [{
4749
+ summary: "If API callers should not reach this table at all, revoke their privileges instead.",
4750
+ sql: revokes.join("\n")
4751
+ }] : [];
4752
+ if (existing.length > 0) {
4753
+ const names = existing.map((p) => `"${p.name}"`).join(", ");
4754
+ return {
4755
+ summary: `Enable row-level security on ${rel.schema}.${rel.name}; its ${existing.length} existing ${existing.length === 1 ? "policy" : "policies"} (${names}) then ${existing.length === 1 ? "takes" : "take"} effect.`,
4756
+ apply: "sql",
4757
+ sql: enable,
4758
+ placeholders: [],
4759
+ alternatives: [{
4760
+ summary: "If the existing policies do not admit what callers need, add an owner-scoped policy too.",
4761
+ sql: create
4762
+ }, ...revokeAlternative],
4763
+ caveats: [`The existing policies ${names} start filtering rows immediately — re-run rls-check after enabling: any dangerous one is reported under its own check id.`, RLS_FILTERS_EVERYONE],
4764
+ rebase
4765
+ };
4766
+ }
4767
+ return {
4768
+ summary: `Enable row-level security on ${rel.schema}.${rel.name} and add a policy that limits every row to its owner.`,
4769
+ apply: "sql",
4770
+ sql: `${enable}\n${create}`,
4771
+ placeholders: scope.placeholders,
4772
+ alternatives: revokeAlternative,
4773
+ caveats: [...callerCaveats(snapshot, scope), RLS_FILTERS_EVERYONE],
4774
+ rebase
4775
+ };
4776
+ }
4777
+ function rlsEnabledNoPolicies(snapshot, finding) {
4778
+ const { schema, table } = finding.target;
4779
+ const rel = table ? relationAt(snapshot, schema, table) : void 0;
4780
+ if (!rel) return unresolved(finding);
4781
+ const scope = ownerScope(snapshot, rel);
4782
+ const exposed = exposedGrantees(snapshot, rel.schema, rel.name, DML).map((e) => e.role);
4783
+ const revokes = revokesReaching(snapshot, rel.schema, rel.name, exposed, DML);
4784
+ return {
4785
+ summary: `Add a policy to ${rel.schema}.${rel.name} that admits each row to its owner; today it admits no row to anyone but the owner role.`,
4786
+ apply: "sql",
4787
+ sql: `CREATE POLICY ${qi(freshPolicyName(snapshot, rel.schema, rel.name, `${rel.name}_owner`))} ON ${qrel(rel.schema, rel.name)}\n FOR ALL\n USING (${scope.sql})\n WITH CHECK (${scope.sql});`,
4788
+ placeholders: scope.placeholders,
4789
+ alternatives: revokes.length > 0 ? [{
4790
+ summary: "If the table is meant to be unreachable through the API, make that explicit by revoking the API roles' privileges, and run rls-check with --skip rls-enabled-no-policies.",
4791
+ sql: revokes.join("\n")
4792
+ }] : [],
4793
+ caveats: callerCaveats(snapshot, scope),
4794
+ rebase: rebaseRules(rel.schema, rel.name, [{
4795
+ operation: "all",
4796
+ ownerField: scope.ownerField
4797
+ }], OWNER_FIELD_NOTE)
4798
+ };
4799
+ }
4800
+ function rlsEnabledNotForced(snapshot, finding) {
4801
+ const { schema, table } = finding.target;
4802
+ const rel = table ? relationAt(snapshot, schema, table) : void 0;
4803
+ if (!rel) return unresolved(finding);
4804
+ const owner = roleNamed(snapshot, rel.owner);
4805
+ const bypasses = Boolean(owner?.superuser || owner?.bypassRls);
4806
+ const members = snapshot.exposedRoles.filter((role) => !isPublicRole(role) && !sameRole(role, rel.owner) && rolesUsableBy(snapshot, role).has(rel.owner.toLowerCase()));
4807
+ const revokes = members.map((role) => `REVOKE ${qi(rel.owner)} FROM ${qi(role)};`);
4808
+ const force = `ALTER TABLE ${qrel(rel.schema, rel.name)} FORCE ROW LEVEL SECURITY;`;
4809
+ const membershipCaveat = members.length > 0 ? [`If ${members.join(", ")} holds ${rel.owner} through another role rather than directly, the REVOKE is a no-op: revoke the intermediate membership instead.`] : [];
4810
+ const rebase = noRebaseRule("Not a securityRules setting. Rebase never sets FORCE: it runs every API request as rebase_user, which does not own collection tables, so the owner's exemption never reaches a caller.");
4811
+ if (snapshot.platform === "rebase") return {
4812
+ summary: `Do not FORCE row-level security on ${rel.schema}.${rel.name}: Rebase's privileged writes run as the owner ${rel.owner} and depend on its exemption. Make sure nothing untrusted connects as, or is a member of, that role.`,
4813
+ apply: revokes.length > 0 ? "sql" : "manual",
4814
+ sql: revokes.length > 0 ? revokes.join("\n") : null,
4815
+ placeholders: [],
4816
+ alternatives: [],
4817
+ caveats: [...membershipCaveat, "The finding stays until FORCE is set; on a Rebase database run rls-check with --skip rls-enabled-not-forced once the API is confirmed to connect as rebase_user."],
4818
+ rebase
4819
+ };
4820
+ return {
4821
+ summary: bypasses ? `Set FORCE ROW LEVEL SECURITY on ${rel.schema}.${rel.name}, and stop the application connecting as ${rel.owner}: it is ${owner?.superuser ? "a superuser" : "BYPASSRLS"}, which FORCE does not constrain.` : `Set FORCE ROW LEVEL SECURITY on ${rel.schema}.${rel.name} so its policies apply to the owner ${rel.owner}${members.length > 0 ? `, and take that role away from ${members.join(", ")}` : ""}.`,
4822
+ apply: "sql",
4823
+ sql: [force, ...revokes].join("\n"),
4824
+ placeholders: [],
4825
+ alternatives: [],
4826
+ caveats: [`With FORCE set, ${rel.owner} is filtered by the policies too: a migration or job that runs as it and touches rows no policy admits sees fewer rows — run those as a superuser or a BYPASSRLS role.`, ...membershipCaveat],
4827
+ rebase
4828
+ };
4829
+ }
4830
+ function junctionTableUnprotected(snapshot, finding) {
4831
+ const { schema, table } = finding.target;
4832
+ const rel = table ? relationAt(snapshot, schema, table) : void 0;
4833
+ const fks = rel ? foreignKeysOf(snapshot, rel.schema, rel.name) : [];
4834
+ if (!rel || fks.length === 0) return unresolved(finding);
4835
+ const linked = (outer) => fks.map((fk, i) => {
4836
+ const alias = `e${i + 1}`;
4837
+ const on = fk.columns.map((column, k) => `${alias}.${qi(fk.refColumns[k] ?? "id")} = ${outer(column)}`);
4838
+ return `EXISTS (SELECT 1 FROM ${qrel(fk.refSchema, fk.refTable)} AS ${alias} WHERE ${on.join(" AND ")})`;
4839
+ }).join(" AND ");
4840
+ const name = freshPolicyName(snapshot, rel.schema, rel.name, `${rel.name}_select_via_endpoints`);
4841
+ const exposed = exposedGrantees(snapshot, rel.schema, rel.name, DML).map((e) => e.role);
4842
+ const revokes = revokesReaching(snapshot, rel.schema, rel.name, exposed, DML);
4843
+ const endpoints = fks.map((fk) => `${fk.refSchema}.${fk.refTable}`);
4844
+ return {
4845
+ summary: `Enable row-level security on ${rel.schema}.${rel.name} and let a caller read a link only when it can read both rows it joins (${endpoints.join(" and ")}).`,
4846
+ apply: "sql",
4847
+ sql: `ALTER TABLE ${qrel(rel.schema, rel.name)} ENABLE ROW LEVEL SECURITY;\nCREATE POLICY ${qi(name)} ON ${qrel(rel.schema, rel.name)}\n FOR SELECT\n USING (${linked((column) => `${qi(rel.name)}.${qi(column)}`)});`,
4848
+ placeholders: [],
4849
+ alternatives: revokes.length > 0 ? [{
4850
+ summary: "If callers never read the join table directly, revoke their privileges instead.",
4851
+ sql: revokes.join("\n")
4852
+ }] : [],
4853
+ caveats: [`INSERT, UPDATE and DELETE on ${rel.schema}.${rel.name} are refused for every API role until a policy admits them: decide who may create a link — usually the owner of one endpoint — and add that policy.`, `rls-check inferred that ${rel.schema}.${rel.name} is a join table from its shape; confirm before applying.`],
4854
+ rebase: rebaseRules(rel.schema, rel.name, [{
4855
+ name,
4856
+ operation: "select",
4857
+ using: linked((column) => `{${column}}`)
4858
+ }], `If this is the junction of a many-to-many link, declare it as a \`relation\` property with \`kind: "manyToMany"\` instead: Rebase then creates the junction itself, with row-level security on and policies derived from both collections. The rule here is for a join table modelled as its own collection. ${RAW_RULE_NOTE}`)
4859
+ };
4860
+ }
4861
+ function grantToPublic(snapshot, finding) {
4862
+ const { schema, table } = finding.target;
4863
+ const grant = snapshot.grants.find((g) => g.schema === schema && g.table === table && isPublicRole(g.grantee));
4864
+ const privileges = DML.filter((p) => grant?.privileges.includes(p));
4865
+ if (!table || privileges.length === 0) return unresolved(finding);
4866
+ return {
4867
+ summary: `Revoke ${privileges.join(", ")} on ${schema}.${table} from PUBLIC, then grant it to the roles that need it.`,
4868
+ apply: "sql",
4869
+ sql: `REVOKE ${privileges.join(", ")} ON ${qrel(schema, table)} FROM PUBLIC;`,
4870
+ placeholders: [],
4871
+ alternatives: [],
4872
+ caveats: [`Every role that read or wrote this table through PUBLIC loses access. Grant it back explicitly where it is needed: GRANT ${privileges.join(", ")} ON ${qrel(schema, table)} TO "<role>";`],
4873
+ rebase: noRebaseRule("Not a securityRules setting: Rebase grants table privileges to its own request role, and the rules decide which rows each request reaches.")
4874
+ };
4875
+ }
4876
+ var VIEW_NOTE = "Not a securityRules setting: rules attach to a collection's table. Serve this data through a collection over the base table, whose rules then apply to every read, rather than through a view.";
4877
+ function viewBypassesRls(snapshot, finding) {
4878
+ const { schema } = finding.target;
4879
+ const name = finding.target.view ?? finding.target.table;
4880
+ const view = snapshot.views.find((v) => v.schema === schema && v.name === name);
4881
+ if (!view) return unresolved(finding);
4882
+ const roles = exposedGrantees(snapshot, view.schema, view.name, ["SELECT"]).map((e) => e.role);
4883
+ const revokes = revokesReaching(snapshot, view.schema, view.name, roles, ["SELECT"]);
4884
+ if (view.securityInvoker === null) return {
4885
+ summary: `PostgreSQL ${snapshot.serverVersion} has no security_invoker, so revoke the API roles' SELECT on ${view.schema}.${view.name} and let callers query the base tables, whose policies apply to them.`,
4886
+ apply: "sql",
4887
+ sql: revokes.join("\n"),
4888
+ placeholders: [],
4889
+ alternatives: [],
4890
+ caveats: ["On PostgreSQL 15 or newer, ALTER VIEW … SET (security_invoker = true) keeps the view usable instead."],
4891
+ rebase: noRebaseRule(VIEW_NOTE)
4892
+ };
4893
+ const missing = protectedBaseTables(snapshot, view).flatMap((base) => roles.filter((role) => !effectivePrivileges(snapshot, base.schema, base.name, role).has("SELECT")).map((role) => `${role} holds no SELECT on ${base.schema}.${base.name}, so its reads of the view will fail with "permission denied" until you GRANT SELECT ON ${qrel(base.schema, base.name)} TO ${isPublicRole(role) ? "PUBLIC" : qi(role)}; the policies there then decide which rows it sees.`));
4894
+ return {
4895
+ summary: `Make ${view.schema}.${view.name} run with the caller's privileges, so row-level security on the tables it reads applies to the caller rather than to the view's owner.`,
4896
+ apply: "sql",
4897
+ sql: `ALTER VIEW ${qrel(view.schema, view.name)} SET (security_invoker = true);`,
4898
+ placeholders: [],
4899
+ alternatives: revokes.length > 0 ? [{
4900
+ summary: "If callers do not need the view, revoke their SELECT on it instead.",
4901
+ sql: revokes.join("\n")
4902
+ }] : [],
4903
+ caveats: missing,
4904
+ rebase: noRebaseRule(VIEW_NOTE)
4905
+ };
4906
+ }
4907
+ function matviewBypassesRls(snapshot, finding) {
4908
+ const { schema } = finding.target;
4909
+ const name = finding.target.view ?? finding.target.table;
4910
+ if (!name) return unresolved(finding);
4911
+ const revokes = revokesReaching(snapshot, schema, name, exposedGrantees(snapshot, schema, name, ["SELECT"]).map((e) => e.role), ["SELECT"]);
4912
+ if (revokes.length === 0) return unresolved(finding);
4913
+ return {
4914
+ summary: `Revoke the API roles' SELECT on materialized view ${schema}.${name}: it stores rows computed by its owner, and no policy can filter them.`,
4915
+ apply: "sql",
4916
+ sql: revokes.join("\n"),
4917
+ placeholders: [],
4918
+ alternatives: [],
4919
+ caveats: ["If callers need this data, serve it through a plain view created WITH (security_invoker = true) over the base tables, so their policies apply to each caller."],
4920
+ rebase: noRebaseRule(VIEW_NOTE)
4921
+ };
4922
+ }
4923
+ function securityDefinerMutableSearchPath(snapshot, finding) {
4924
+ const { schema, routine } = finding.target;
4925
+ if (!routine) return unresolved(finding);
4926
+ return {
4927
+ summary: `Pin search_path on every overload of the SECURITY DEFINER routine ${schema}.${routine}.`,
4928
+ apply: "sql",
4929
+ sql: pinSearchPathSql(schema, routine),
4930
+ placeholders: [],
4931
+ alternatives: [],
4932
+ caveats: ["Only pg_catalog is on the path afterwards: schema-qualify every table and function the body uses (public.orders, not orders), or the routine fails at its next call."],
4933
+ rebase: noRebaseRule("Not a securityRules setting: it concerns a function, not a collection's rows.")
4934
+ };
4935
+ }
4936
+ var escapeRegExp = (value) => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
4937
+ /** An identifier as Postgres may print it: bare, or double-quoted. */
4938
+ var identifier = (name) => `(?:"${escapeRegExp(name.replace(/"/g, "\"\""))}"|${escapeRegExp(name)})`;
4939
+ /**
4940
+ * `expr` with the one comparison `hit` names re-pointed at the outer row, or
4941
+ * null when that comparison is not there exactly once — a rewrite that could
4942
+ * land in the wrong place is not offered.
4943
+ */
4944
+ function rewriteAmbiguity(expr, hit, outer) {
4945
+ let pattern;
4946
+ if (hit.kind === "self") {
4947
+ const [qualifier, column] = [hit.comparedTo.slice(0, hit.comparedTo.lastIndexOf(".")), hit.column];
4948
+ const side = `${identifier(qualifier)}\\s*\\.\\s*${identifier(column)}`;
4949
+ pattern = new RegExp(`(${side}\\s*${escapeRegExp(hit.operator ?? "=")})\\s*${side}(?![\\w$"])`, "gi");
4950
+ if ((expr.match(pattern) ?? []).length !== 1) return null;
4951
+ return expr.replace(pattern, (_m, left) => `${left} ${outer}`);
4952
+ }
4953
+ pattern = new RegExp(`(?<![\\w$."])(?<!\\.\\s*)${escapeRegExp(hit.column)}(?![\\w$"])(?!\\s*\\.)`, "gi");
4954
+ if ((expr.match(pattern) ?? []).length !== 1) return null;
4955
+ return expr.replace(pattern, outer);
4956
+ }
4957
+ function unqualifiedColumnInSubquery(snapshot, finding) {
4958
+ const policy = policyAt(snapshot, finding);
4959
+ if (!policy) return unresolved(finding);
4960
+ const hits = policyAmbiguities(snapshot, policy).filter((a) => a.hit.column === finding.target.column);
4961
+ if (hits.length === 0) return unresolved(finding);
4962
+ const rewrite = (outer) => {
4963
+ const out = {};
4964
+ for (const { clause, hit } of hits) {
4965
+ const current = out[clause] ?? clauseExpr(policy, clause);
4966
+ const next = current === null ? null : rewriteAmbiguity(current, hit, outer(hit.column));
4967
+ if (next === null) return null;
4968
+ out[clause] = next;
4969
+ }
4970
+ return out;
4971
+ };
4972
+ const sqlClauses = rewrite((column) => `${qi(policy.table)}.${qi(column)}`);
4973
+ const ruleClauses = rewrite((column) => `{${column}}`);
4974
+ const column = finding.target.column ?? hits[0].hit.column;
4975
+ const inner = hits[0].hit.inner;
4976
+ const confirm = `This assumes ${policy.table}.${column} — the row being checked — was meant, not ${inner}.${column}. Confirm before applying: it changes which rows the policy admits.`;
4977
+ const rebase = ruleClauses ? rebaseRules(policy.schema, policy.table, [rawRule(snapshot, policy, ruleClauses.USING ?? policy.using, ruleClauses["WITH CHECK"] ?? policy.withCheck)], `${rawRuleNote(snapshot, policy.using, policy.withCheck)} The structured form, \`policy.existsIn({ collection, where })\` with \`policy.outerField("…")\` for the outer row, makes the binding explicit and is checked by the type system.`) : noRebaseRule("The comparison could not be located in the expression exactly once, so no rule was derived.");
4978
+ if (!sqlClauses) return {
4979
+ summary: `In ${where(finding)}, qualify \`${column}\` inside the subquery over ${inner} as ${policy.table}.${column} if it is meant to name the row being checked.`,
4980
+ apply: "manual",
4981
+ sql: null,
4982
+ placeholders: [],
4983
+ alternatives: [],
4984
+ caveats: [confirm],
4985
+ rebase
4986
+ };
4987
+ if (isRebaseManagedPolicy(snapshot, policy)) return {
4988
+ summary: `Qualify \`${column}\` in the rule that compiles to ${where(finding)}, so it names the row being checked.`,
4989
+ apply: "rebase-config",
4990
+ sql: null,
4991
+ placeholders: [],
4992
+ alternatives: [],
4993
+ caveats: [managedCaveat(policy), confirm],
4994
+ rebase
4995
+ };
4996
+ return {
4997
+ summary: `Point \`${column}\` in ${where(finding)} at the row being checked, ${policy.table}.${column}.`,
4998
+ apply: "sql",
4999
+ sql: alterPolicySql(policy, sqlClauses),
5000
+ placeholders: [],
5001
+ alternatives: [],
5002
+ caveats: [confirm],
5003
+ rebase
5004
+ };
5005
+ }
5006
+ function currentSettingThrows(snapshot, finding) {
5007
+ const policy = policyAt(snapshot, finding);
5008
+ if (!policy) return unresolved(finding);
5009
+ const fixed = {};
5010
+ for (const clause of ["USING", "WITH CHECK"]) {
5011
+ const expr = clauseExpr(policy, clause);
5012
+ if (expr === null) continue;
5013
+ const next = withMissingOk(expr);
5014
+ if (next !== expr) fixed[clause] = next;
5015
+ }
5016
+ if (Object.keys(fixed).length === 0) return unresolved(finding);
5017
+ const rebase = rebaseRules(policy.schema, policy.table, [rawRule(snapshot, policy, fixed.USING ?? policy.using, fixed["WITH CHECK"] ?? policy.withCheck)], rawRuleNote(snapshot, policy.using, policy.withCheck));
5018
+ if (isRebaseManagedPolicy(snapshot, policy)) return {
5019
+ summary: `Pass missing_ok (a second argument, true) to current_setting in the rule that compiles to ${where(finding)}.`,
5020
+ apply: "rebase-config",
5021
+ sql: null,
5022
+ placeholders: [],
5023
+ alternatives: [],
5024
+ caveats: [managedCaveat(policy)],
5025
+ rebase
5026
+ };
5027
+ return {
5028
+ summary: `Pass missing_ok to current_setting in ${where(finding)}, so an unset setting denies the row instead of failing the query.`,
5029
+ apply: "sql",
5030
+ sql: alterPolicySql(policy, fixed),
5031
+ placeholders: [],
5032
+ alternatives: [],
5033
+ caveats: [],
5034
+ rebase
5035
+ };
5036
+ }
5037
+ function policyRoleUnreachable(snapshot, finding) {
5038
+ const { schema, table } = finding.target;
5039
+ const policies = table ? policiesFor(snapshot, schema, table) : [];
5040
+ if (!table || policies.length === 0) return unresolved(finding);
5041
+ const named = [...new Set(policies.flatMap((p) => p.roles))];
5042
+ const candidates = snapshot.exposedRoles.filter((role) => !isPublicRole(role) && DML.some((p) => effectivePrivileges(snapshot, schema, table, role).has(p)));
5043
+ const placeholder = {
5044
+ token: APP_ROLE_PLACEHOLDER,
5045
+ meaning: "The role your application's requests run as, as a quoted identifier — run SELECT current_user; on the application's own connection." + (candidates.length > 0 ? ` Roles that hold privileges on ${schema}.${table}: ${candidates.join(", ")}.` : "")
5046
+ };
5047
+ const rebase = rebaseRules(schema, table, policies.map((p) => rawRule(snapshot, p, p.using, p.withCheck)), `A rule without \`pgRoles\` applies TO PUBLIC — every connection — and Rebase's API decides who is signed in; \`pgRoles\` is what pointed these policies at ${named.join(", ")}. ${RAW_RULE_NOTE}`);
5048
+ if (policies.every((p) => isRebaseManagedPolicy(snapshot, p))) return {
5049
+ summary: `Remove \`pgRoles\` from the rules that compile to the policies on ${schema}.${table}, or set it to the role requests actually arrive as.`,
5050
+ apply: "rebase-config",
5051
+ sql: null,
5052
+ placeholders: [],
5053
+ alternatives: [],
5054
+ caveats: [managedCaveat(policies[0])],
5055
+ rebase
5056
+ };
5057
+ return {
5058
+ summary: `Point the ${policies.length === 1 ? "policy" : "policies"} on ${schema}.${table} at the role your application connects as; today ${policies.length === 1 ? "it names" : "they name"} only ${named.join(", ")}, which no session uses.`,
5059
+ apply: "sql",
5060
+ sql: policies.map((p) => `ALTER POLICY ${qi(p.name)} ON ${qrel(schema, table)} TO ${APP_ROLE_PLACEHOLDER};`).join("\n"),
5061
+ placeholders: [placeholder],
5062
+ alternatives: [{
5063
+ summary: `Or keep the policies as they are and make the application role a member of ${named[0]}.`,
5064
+ sql: `GRANT ${isPublicRole(named[0]) ? "PUBLIC" : qi(named[0])} TO ${APP_ROLE_PLACEHOLDER};`
5065
+ }],
5066
+ caveats: ["Once a reachable role is named, the policies' expressions decide what it sees — review them before applying."],
5067
+ rebase
5068
+ };
5069
+ }
5070
+ /** One builder per check id. A check without one is caught by `remediation.test.ts`. */
5071
+ var REMEDIATIONS = {
5072
+ "rls-disabled": rlsDisabled,
5073
+ "policy-always-true": policyAlwaysTrue,
5074
+ "policy-anonymous-tautology": policyAnonymousTautology,
5075
+ "policy-authenticated-tautology": policyAuthenticatedTautology,
5076
+ "view-bypasses-rls": viewBypassesRls,
5077
+ "matview-bypasses-rls": matviewBypassesRls,
5078
+ "anonymous-write-allowed": anonymousWriteAllowed,
5079
+ "unqualified-column-in-subquery": unqualifiedColumnInSubquery,
5080
+ "junction-table-unprotected": junctionTableUnprotected,
5081
+ "rls-enabled-not-forced": rlsEnabledNotForced,
5082
+ "rls-enabled-no-policies": rlsEnabledNoPolicies,
5083
+ "policy-role-unreachable": policyRoleUnreachable,
5084
+ "grant-to-public": grantToPublic,
5085
+ "security-definer-mutable-search-path": securityDefinerMutableSearchPath,
5086
+ "current-setting-throws": currentSettingThrows
5087
+ };
5088
+ /** The remediation for one finding, computed against the snapshot it came from. */
5089
+ function remediationFor(snapshot, finding) {
5090
+ const build = REMEDIATIONS[finding.id];
5091
+ return build ? build(snapshot, finding) : unresolved(finding);
5092
+ }
5093
+ //#endregion
5094
+ //#region src/report-agent.ts
5095
+ /**
5096
+ * `--format agent`: the scan as one JSON document a coding agent can act on.
5097
+ *
5098
+ * `--json` is the {@link ScanResult} contract, unchanged, for dashboards and CI
5099
+ * baselines. This is a different reader. An agent that ran
5100
+ * `npx @rebasepro/rls-check` against the database it is building wants, for
5101
+ * every finding, the object to change, the statement that changes it, the blanks
5102
+ * it must fill first, and — when the object is generated by Rebase — the rule to
5103
+ * edit instead. So each finding carries a {@link Remediation}, computed from the
5104
+ * snapshot rather than parsed out of the human-oriented `fix` text.
5105
+ *
5106
+ * Stability rules, because this is parsed:
5107
+ *
5108
+ * - Every key is always present. An absent object is `null`, never a missing
5109
+ * key, so a parser never has to guess which shape it got.
5110
+ * - `formatVersion` changes when a key is renamed or removed. Adding a key
5111
+ * does not change it.
5112
+ * - Findings are ordered as `--json` orders them, and `key` identifies one
5113
+ * finding across runs, so an agent can tell "fixed" from "still there".
5114
+ * - No ANSI, no prose outside string values, nothing on stdout but the document.
5115
+ */
5116
+ /** Bumped when a key is renamed or removed; adding one does not bump it. */
5117
+ var AGENT_FORMAT_VERSION = 1;
5118
+ var HOW_TO_APPLY = "For each finding, read remediation.apply. \"sql\": replace every token listed in remediation.placeholders, then run remediation.sql as a migration. \"rebase-config\": the object is generated by Rebase from a collection's securityRules and would be re-made on the next boot, so edit the rules as remediation.rebase.snippet shows and run `rebase db push`. \"manual\": remediation.summary names the decision to make. Read remediation.caveats before applying; remediation.alternatives are fixes for a different intent. Re-run rls-check afterwards: a fixed finding's key is gone.";
5119
+ function findingKey(finding) {
5120
+ const { schema, table, view, routine, policy, column } = finding.target;
5121
+ const object = view ?? table ?? (routine ? `${routine}()` : "");
5122
+ return [
5123
+ `${finding.id}:${schema}${object ? `.${object}` : ""}`,
5124
+ ...policy ? [policy] : [],
5125
+ ...column ? [column] : []
5126
+ ].join(":");
5127
+ }
5128
+ function notesFor(result) {
5129
+ const notes = [];
5130
+ if (result.scannerIsPrivileged) notes.push("The scan connected as a role row-level security cannot constrain (superuser, owner or BYPASSRLS): the findings describe what other roles get, not this connection.");
5131
+ const scanningAs = result.diagnostics?.scanningAsExposedRole;
5132
+ if (scanningAs) notes.push(`The scan connected as "${scanningAs}", which row-level security constrains, so it was treated as a role an untrusted caller can arrive as.`);
5133
+ const degraded = result.diagnostics?.degraded ?? [];
5134
+ if (degraded.length > 0) notes.push(`The scan was incomplete: ${degraded.length} catalogue read(s) or check(s) failed (see diagnostics.degraded). Missing findings are not evidence of a clean database.`);
5135
+ const unrecognized = result.diagnostics?.unrecognizedGrantees ?? [];
5136
+ if (unrecognized.length > 0) notes.push(`Roles ${unrecognized.join(", ")} can read or write scanned tables and were not assessed. If the application connects as one of them, re-run with --role ${unrecognized[0]}.`);
5137
+ if (result.diagnostics?.tlsVerificationDisabled) notes.push("TLS certificate verification was turned off to connect.");
5138
+ return notes;
5139
+ }
5140
+ /**
5141
+ * The agent document. Needs the snapshot as well as the result: a remediation
5142
+ * names columns, grants and policy expressions that the result does not carry.
5143
+ */
5144
+ function renderAgentReport(result, snapshot, options) {
5145
+ const sorted = [...result.findings].sort(compareFindings$1);
5146
+ const verdict = exitVerdict(result, options.failOn);
5147
+ const bySeverity = {
5148
+ info: 0,
5149
+ low: 0,
5150
+ medium: 0,
5151
+ high: 0,
5152
+ critical: 0
5153
+ };
5154
+ for (const finding of sorted) bySeverity[finding.severity] += 1;
5155
+ const findings = sorted.map((finding) => ({
5156
+ key: findingKey(finding),
5157
+ checkId: finding.id,
5158
+ severity: finding.severity,
5159
+ confidence: finding.confidence,
5160
+ failsRun: exceedsThreshold([finding], options.failOn),
5161
+ target: {
5162
+ schema: finding.target.schema,
5163
+ table: finding.target.table ?? null,
5164
+ policy: finding.target.policy ?? null,
5165
+ view: finding.target.view ?? null,
5166
+ routine: finding.target.routine ?? null,
5167
+ column: finding.target.column ?? null
5168
+ },
5169
+ title: finding.title,
5170
+ detail: finding.detail,
5171
+ impact: finding.impact,
5172
+ docs: finding.docs ?? null,
5173
+ remediation: remediationFor(snapshot, finding)
5174
+ }));
5175
+ const report = {
5176
+ tool: "@rebasepro/rls-check",
5177
+ format: "agent",
5178
+ formatVersion: 1,
5179
+ version: options.version,
5180
+ howToApply: HOW_TO_APPLY,
5181
+ scannedAt: result.scannedAt,
5182
+ database: result.database,
5183
+ serverVersion: result.serverVersion,
5184
+ platform: result.platform,
5185
+ exposedRoles: result.exposedRoles,
5186
+ verdict: {
5187
+ exitCode: verdict.code,
5188
+ reason: verdict.reason,
5189
+ failOn: options.failOn
5190
+ },
5191
+ complete: (result.diagnostics?.degraded.length ?? 0) === 0,
5192
+ notes: notesFor(result),
5193
+ diagnostics: result.diagnostics,
5194
+ summary: {
5195
+ findings: findings.length,
5196
+ failing: findings.filter((f) => f.failsRun).length,
5197
+ bySeverity
5198
+ },
5199
+ findings
5200
+ };
5201
+ return JSON.stringify(report, null, 2);
5202
+ }
5203
+ //#endregion
4364
5204
  //#region src/report-html.ts
4365
5205
  /**
4366
5206
  * The one primitive this whole file rests on.
@@ -4675,12 +5515,35 @@ var TABLE_KINDS = /* @__PURE__ */ new Set(["table", "partitioned_table"]);
4675
5515
  * and this has an integration test.
4676
5516
  */
4677
5517
  async function scan(options) {
5518
+ return (await scanWithSnapshot(options)).result;
5519
+ }
5520
+ /**
5521
+ * {@link scan}, also handing back the snapshot the findings were computed from.
5522
+ *
5523
+ * `--format agent` needs it: a remediation names the owner column, the grants
5524
+ * to revoke and the policy expression to rewrite, and the result carries none
5525
+ * of those.
5526
+ */
5527
+ async function scanWithSnapshot(options) {
4678
5528
  const { snapshot, diagnostics } = await introspectWithDiagnostics({
4679
5529
  connectionString: options.connectionString,
4680
5530
  schemas: options.schemas && options.schemas.length > 0 ? options.schemas : void 0,
4681
5531
  roles: options.roles && options.roles.length > 0 ? options.roles : void 0,
4682
5532
  statementTimeoutMs: options.statementTimeoutMs ?? DEFAULT_TIMEOUT_MS
4683
5533
  });
5534
+ return {
5535
+ result: scanSnapshot(snapshot, diagnostics, options),
5536
+ snapshot
5537
+ };
5538
+ }
5539
+ /**
5540
+ * The half of {@link scan} after introspection: run the checks over a snapshot
5541
+ * and assemble the result. Pure, and exported so the wiring below is tested
5542
+ * without a database — the unit suite passed with it removed.
5543
+ *
5544
+ * `diagnostics` is extended in place with any check that crashed.
5545
+ */
5546
+ function scanSnapshot(snapshot, diagnostics, options) {
4684
5547
  return buildScanResult(snapshot, runChecks(snapshot, {
4685
5548
  only: options.only,
4686
5549
  skip: options.skip,
@@ -4733,10 +5596,22 @@ function buildScanResult(snapshot, findings, meta) {
4733
5596
  diagnostics: meta.diagnostics
4734
5597
  };
4735
5598
  }
5599
+ /**
5600
+ * What stdout carries. `text` is the report for a person; `json` is the
5601
+ * {@link ScanResult} contract; `agent` is one JSON document with a remediation —
5602
+ * SQL and the Rebase `securityRules` equivalent — on every finding, for a
5603
+ * coding agent to apply.
5604
+ */
5605
+ var OUTPUT_FORMATS = [
5606
+ "text",
5607
+ "json",
5608
+ "agent"
5609
+ ];
4736
5610
  var FAIL_ON_VALUES = [...SEVERITIES, "none"];
4737
5611
  function emptyOptions() {
4738
5612
  return {
4739
5613
  connectionString: null,
5614
+ format: "text",
4740
5615
  json: false,
4741
5616
  html: null,
4742
5617
  schemas: [],
@@ -4759,6 +5634,14 @@ function splitList(value) {
4759
5634
  function parseArgs(argv) {
4760
5635
  const options = emptyOptions();
4761
5636
  let positionals = 0;
5637
+ let formatFlag = null;
5638
+ const chooseFormat = (format) => {
5639
+ if (formatFlag !== null && formatFlag !== format) return `Two output formats were asked for (${formatFlag} and ${format}). Pick one.`;
5640
+ formatFlag = format;
5641
+ options.format = format;
5642
+ options.json = format === "json";
5643
+ return null;
5644
+ };
4762
5645
  for (let index = 0; index < argv.length; index += 1) {
4763
5646
  const arg = argv[index];
4764
5647
  if (arg === "--") {
@@ -4800,9 +5683,32 @@ function parseArgs(argv) {
4800
5683
  case "--version":
4801
5684
  options.version = true;
4802
5685
  break;
4803
- case "--json":
4804
- options.json = true;
5686
+ case "--json": {
5687
+ const conflict = chooseFormat("json");
5688
+ if (conflict !== null) return {
5689
+ ok: false,
5690
+ message: conflict
5691
+ };
5692
+ break;
5693
+ }
5694
+ case "--format": {
5695
+ const value = takeValue();
5696
+ if (value === null) return {
5697
+ ok: false,
5698
+ message: `--format needs one of: ${OUTPUT_FORMATS.join(", ")}.`
5699
+ };
5700
+ const format = OUTPUT_FORMATS.find((f) => f === value.toLowerCase());
5701
+ if (format === void 0) return {
5702
+ ok: false,
5703
+ message: `--format ${value} is not a format. Use one of: ${OUTPUT_FORMATS.join(", ")}.`
5704
+ };
5705
+ const conflict = chooseFormat(format);
5706
+ if (conflict !== null) return {
5707
+ ok: false,
5708
+ message: conflict
5709
+ };
4805
5710
  break;
5711
+ }
4806
5712
  case "--quiet":
4807
5713
  case "-q":
4808
5714
  options.quiet = true;
@@ -5048,6 +5954,10 @@ fact. Its own output redacts the password everywhere.
5048
5954
 
5049
5955
  Options
5050
5956
  --json Machine-readable ScanResult on stdout, and nothing else.
5957
+ --format <name> text (default), json (the same as --json) or agent: one JSON
5958
+ document for a coding agent, where every finding carries the
5959
+ failing table and policy, the SQL that fixes it and the
5960
+ equivalent Rebase securityRules.
5051
5961
  --html <path> Also write a self-contained HTML report to <path>. One file,
5052
5962
  no network requests, safe to attach to a ticket.
5053
5963
  --schema <name> Restrict the scan to a schema. Repeatable or comma-separated.
@@ -5078,6 +5988,7 @@ Examples
5078
5988
  npx @rebasepro/rls-check
5079
5989
  npx @rebasepro/rls-check --schema public --schema billing --fail-on medium
5080
5990
  npx @rebasepro/rls-check --json > rls-report.json
5991
+ npx @rebasepro/rls-check --format agent
5081
5992
  npx @rebasepro/rls-check --html rls-report.html
5082
5993
 
5083
5994
  It is read-only: it issues SELECTs against the system catalogs, writes nothing,
@@ -5147,7 +6058,7 @@ async function runCli(argv, io = defaultIo()) {
5147
6058
  return 2;
5148
6059
  }
5149
6060
  const options = parsed.options;
5150
- const color = resolveColor(options.color, options.json, io.env, io.isTty);
6061
+ const color = resolveColor(options.color, options.format !== "text", io.env, io.isTty);
5151
6062
  const version = resolveVersion();
5152
6063
  if (options.help) {
5153
6064
  io.stdout(helpText(version));
@@ -5158,7 +6069,7 @@ async function runCli(argv, io = defaultIo()) {
5158
6069
  return 0;
5159
6070
  }
5160
6071
  if (options.listChecks) {
5161
- if (options.json) io.stdout(`${JSON.stringify(CHECKS.map((check) => ({
6072
+ if (options.format !== "text") io.stdout(`${JSON.stringify(CHECKS.map((check) => ({
5162
6073
  id: check.id,
5163
6074
  title: check.title,
5164
6075
  description: check.description
@@ -5206,15 +6117,16 @@ async function runCli(argv, io = defaultIo()) {
5206
6117
  };
5207
6118
  process.on("SIGINT", onSigint);
5208
6119
  let result;
6120
+ let snapshot;
5209
6121
  try {
5210
- result = await scan({
6122
+ ({result, snapshot} = await scanWithSnapshot({
5211
6123
  connectionString,
5212
6124
  schemas: options.schemas,
5213
6125
  roles: options.roles,
5214
6126
  only: options.only,
5215
6127
  skip: options.skip,
5216
6128
  statementTimeoutMs: options.timeoutMs
5217
- });
6129
+ }));
5218
6130
  } catch (error) {
5219
6131
  if (error instanceof UnknownRoleError) {
5220
6132
  io.stderr(formatFriendlyError({
@@ -5239,7 +6151,11 @@ async function runCli(argv, io = defaultIo()) {
5239
6151
  } finally {
5240
6152
  process.removeListener("SIGINT", onSigint);
5241
6153
  }
5242
- if (options.json) io.stdout(`${renderJson(result)}\n`);
6154
+ if (options.format === "agent") io.stdout(`${renderAgentReport(result, snapshot, {
6155
+ failOn: options.failOn,
6156
+ version
6157
+ })}\n`);
6158
+ else if (options.format === "json") io.stdout(`${renderJson(result)}\n`);
5243
6159
  else io.stdout(renderReport(result, {
5244
6160
  color,
5245
6161
  quiet: options.quiet,
@@ -5281,6 +6197,6 @@ async function runCli(argv, io = defaultIo()) {
5281
6197
  }
5282
6198
  }
5283
6199
  //#endregion
5284
- export { CHECKS, EXIT_ERROR, EXIT_FINDINGS, EXIT_OK, SEVERITIES, escapeHtml, exceedsThreshold, formatEndpoint, formatTarget, introspect, maxSeverity, parseConnectionString, redactConnectionString, redactSecrets, renderCheckCatalog, renderHtml, renderJson, renderReport, runChecks, runCli, scan, selectCheckIds, severityRank };
6200
+ export { AGENT_FORMAT_VERSION, CHECKS, EXIT_ERROR, EXIT_FINDINGS, EXIT_OK, SEVERITIES, escapeHtml, exceedsThreshold, findingKey, formatEndpoint, formatTarget, introspect, maxSeverity, parseConnectionString, redactConnectionString, redactSecrets, remediationFor, renderAgentReport, renderCheckCatalog, renderHtml, renderJson, renderReport, runChecks, runCli, scan, scanWithSnapshot, selectCheckIds, severityRank };
5285
6201
 
5286
6202
  //# sourceMappingURL=index.es.js.map