@akal/supaforge 0.0.0-stage → 0.0.32

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 (97) hide show
  1. package/README.md +350 -2
  2. package/bin/dev.js +10 -0
  3. package/bin/run.js +18 -0
  4. package/dist/base-command.d.ts +135 -0
  5. package/dist/base-command.js +9 -0
  6. package/dist/base-command.js.map +1 -0
  7. package/dist/branch-C4ndfoj5.d.ts +58 -0
  8. package/dist/chunk-2SELREHW.js +156 -0
  9. package/dist/chunk-2SELREHW.js.map +1 -0
  10. package/dist/chunk-3HGAV5CC.js +2073 -0
  11. package/dist/chunk-3HGAV5CC.js.map +1 -0
  12. package/dist/chunk-4IVN7QVY.js +632 -0
  13. package/dist/chunk-4IVN7QVY.js.map +1 -0
  14. package/dist/chunk-6LJERPUN.js +499 -0
  15. package/dist/chunk-6LJERPUN.js.map +1 -0
  16. package/dist/chunk-6Q7MHFBM.js +13 -0
  17. package/dist/chunk-6Q7MHFBM.js.map +1 -0
  18. package/dist/chunk-6WAMNZLO.js +336 -0
  19. package/dist/chunk-6WAMNZLO.js.map +1 -0
  20. package/dist/chunk-7NAZGZPV.js +868 -0
  21. package/dist/chunk-7NAZGZPV.js.map +1 -0
  22. package/dist/chunk-BLKJWDTL.js +153 -0
  23. package/dist/chunk-BLKJWDTL.js.map +1 -0
  24. package/dist/chunk-BUOWHE36.js +1311 -0
  25. package/dist/chunk-BUOWHE36.js.map +1 -0
  26. package/dist/chunk-DMIWAJRB.js +602 -0
  27. package/dist/chunk-DMIWAJRB.js.map +1 -0
  28. package/dist/chunk-DQQ5E563.js +64 -0
  29. package/dist/chunk-DQQ5E563.js.map +1 -0
  30. package/dist/chunk-G2DIPIYU.js +94 -0
  31. package/dist/chunk-G2DIPIYU.js.map +1 -0
  32. package/dist/chunk-GEHPTPNZ.js +240 -0
  33. package/dist/chunk-GEHPTPNZ.js.map +1 -0
  34. package/dist/chunk-GZREXCQZ.js +207 -0
  35. package/dist/chunk-GZREXCQZ.js.map +1 -0
  36. package/dist/chunk-MIRLB5JM.js +1292 -0
  37. package/dist/chunk-MIRLB5JM.js.map +1 -0
  38. package/dist/chunk-NTUASFQ3.js +248 -0
  39. package/dist/chunk-NTUASFQ3.js.map +1 -0
  40. package/dist/chunk-ORQJVE57.js +642 -0
  41. package/dist/chunk-ORQJVE57.js.map +1 -0
  42. package/dist/chunk-SC2XHGIS.js +122 -0
  43. package/dist/chunk-SC2XHGIS.js.map +1 -0
  44. package/dist/chunk-SQPCWGQO.js +657 -0
  45. package/dist/chunk-SQPCWGQO.js.map +1 -0
  46. package/dist/chunk-UWAVXC57.js +916 -0
  47. package/dist/chunk-UWAVXC57.js.map +1 -0
  48. package/dist/commands/clone.d.ts +66 -0
  49. package/dist/commands/clone.js +416 -0
  50. package/dist/commands/clone.js.map +1 -0
  51. package/dist/commands/diff.d.ts +81 -0
  52. package/dist/commands/diff.js +23 -0
  53. package/dist/commands/diff.js.map +1 -0
  54. package/dist/commands/help.d.ts +32 -0
  55. package/dist/commands/help.js +36 -0
  56. package/dist/commands/help.js.map +1 -0
  57. package/dist/commands/hukam.d.ts +13 -0
  58. package/dist/commands/hukam.js +28 -0
  59. package/dist/commands/hukam.js.map +1 -0
  60. package/dist/commands/init.d.ts +47 -0
  61. package/dist/commands/init.js +388 -0
  62. package/dist/commands/init.js.map +1 -0
  63. package/dist/commands/mcp.d.ts +13 -0
  64. package/dist/commands/mcp.js +43 -0
  65. package/dist/commands/mcp.js.map +1 -0
  66. package/dist/commands/migrate/baseline.d.ts +24 -0
  67. package/dist/commands/migrate/baseline.js +69 -0
  68. package/dist/commands/migrate/baseline.js.map +1 -0
  69. package/dist/commands/migrate/create.d.ts +36 -0
  70. package/dist/commands/migrate/create.js +127 -0
  71. package/dist/commands/migrate/create.js.map +1 -0
  72. package/dist/commands/migrate/list.d.ts +23 -0
  73. package/dist/commands/migrate/list.js +110 -0
  74. package/dist/commands/migrate/list.js.map +1 -0
  75. package/dist/commands/migrate/run.d.ts +61 -0
  76. package/dist/commands/migrate/run.js +18 -0
  77. package/dist/commands/migrate/run.js.map +1 -0
  78. package/dist/commands/report.d.ts +27 -0
  79. package/dist/commands/report.js +210 -0
  80. package/dist/commands/report.js.map +1 -0
  81. package/dist/commands/restore.d.ts +26 -0
  82. package/dist/commands/restore.js +266 -0
  83. package/dist/commands/restore.js.map +1 -0
  84. package/dist/commands/snapshot.d.ts +33 -0
  85. package/dist/commands/snapshot.js +249 -0
  86. package/dist/commands/snapshot.js.map +1 -0
  87. package/dist/commands/sync.d.ts +16 -0
  88. package/dist/commands/sync.js +38 -0
  89. package/dist/commands/sync.js.map +1 -0
  90. package/dist/config-CTbeRlJk.d.ts +134 -0
  91. package/dist/help.d.ts +28 -0
  92. package/dist/help.js +64 -0
  93. package/dist/help.js.map +1 -0
  94. package/dist/index.d.ts +498 -0
  95. package/dist/index.js +147 -0
  96. package/dist/index.js.map +1 -0
  97. package/package.json +74 -4
@@ -0,0 +1,2073 @@
1
+ import {
2
+ CHECK_NAMES,
3
+ RolesCheck,
4
+ applyTableFilter,
5
+ isComparisonCheck,
6
+ resolveTableFilter
7
+ } from "./chunk-UWAVXC57.js";
8
+ import {
9
+ policyOnlyKeys,
10
+ runDbDiff,
11
+ sqlSkeleton,
12
+ sqlToIssues
13
+ } from "./chunk-BUOWHE36.js";
14
+ import {
15
+ splitSqlStatements
16
+ } from "./chunk-G2DIPIYU.js";
17
+ import {
18
+ RealtimeCheck,
19
+ createPolicySql,
20
+ defaultCanonicalizer,
21
+ diffSchemaPolicies,
22
+ dropEquivalentPolicyChanges,
23
+ dropPolicySql,
24
+ schemaPolicySql
25
+ } from "./chunk-MIRLB5JM.js";
26
+ import {
27
+ Check,
28
+ CheckSkipped,
29
+ MigrationsCheck,
30
+ friendlyDbError,
31
+ isCheckSkipped,
32
+ pgQuery,
33
+ quoteIdent,
34
+ quoteLiteral,
35
+ quoteName,
36
+ readOrAbsent,
37
+ sqlLiteral
38
+ } from "./chunk-SQPCWGQO.js";
39
+ import {
40
+ DEFAULT_IGNORE_SCHEMAS,
41
+ SCORE_MAX,
42
+ SCORE_PENALTY_CRITICAL,
43
+ SCORE_PENALTY_ERROR,
44
+ SCORE_PENALTY_INFO,
45
+ SCORE_PENALTY_WARNING,
46
+ STORAGE_LIST_LIMIT,
47
+ SUPABASE_MGMT_API
48
+ } from "./chunk-6WAMNZLO.js";
49
+
50
+ // src/scoring.ts
51
+ function summarize(results) {
52
+ let total = 0;
53
+ let critical = 0;
54
+ let warning = 0;
55
+ let info = 0;
56
+ for (const r of results) {
57
+ for (const issue of r.issues) {
58
+ total++;
59
+ if (issue.severity === "critical") critical++;
60
+ else if (issue.severity === "warning") warning++;
61
+ else info++;
62
+ }
63
+ }
64
+ return { total, critical, warning, info };
65
+ }
66
+ function summarizeByKind(results) {
67
+ return {
68
+ drift: summarize(results.filter((r) => isComparisonCheck(r.check))),
69
+ posture: summarize(results.filter((r) => !isComparisonCheck(r.check)))
70
+ };
71
+ }
72
+ function scoreOf(results) {
73
+ const { total, critical, warning } = summarize(results);
74
+ const errorCount = results.filter((r) => r.status === "error").length;
75
+ if (total === 0 && errorCount === 0) return SCORE_MAX;
76
+ const penalty = critical * SCORE_PENALTY_CRITICAL + warning * SCORE_PENALTY_WARNING + (total - critical - warning) * SCORE_PENALTY_INFO + errorCount * SCORE_PENALTY_ERROR;
77
+ return Math.max(0, SCORE_MAX - penalty);
78
+ }
79
+ function computeScore(results) {
80
+ return scoreOf(results.filter((r) => isComparisonCheck(r.check)));
81
+ }
82
+ function computePostureScore(results) {
83
+ const posture = results.filter((r) => !isComparisonCheck(r.check));
84
+ if (posture.length === 0) return null;
85
+ return scoreOf(posture);
86
+ }
87
+
88
+ // src/scanner.ts
89
+ function resolveExcludedChecks(config) {
90
+ const lists = [config?.checks?.exclude, config?.environments?.[config?.target ?? ""]?.checks?.exclude];
91
+ const out = [];
92
+ for (const list of lists) {
93
+ if (!Array.isArray(list)) continue;
94
+ for (const name of list) {
95
+ if (typeof name === "string" && CHECK_NAMES.includes(name)) {
96
+ out.push(name);
97
+ }
98
+ }
99
+ }
100
+ return out;
101
+ }
102
+ function checkConcurrency() {
103
+ const raw = process.env.SUPAFORGE_CHECK_CONCURRENCY;
104
+ if (raw) {
105
+ const n = Number(raw);
106
+ if (Number.isInteger(n) && n > 0) return n;
107
+ }
108
+ return 4;
109
+ }
110
+ async function runCheck(check, ctx, name, sourceDbUrl) {
111
+ const start = performance.now();
112
+ try {
113
+ const issues = await check.scan(ctx);
114
+ return {
115
+ check: name,
116
+ status: issues.length > 0 ? "drifted" : "clean",
117
+ issues,
118
+ durationMs: Math.round(performance.now() - start)
119
+ };
120
+ } catch (err) {
121
+ const durationMs = Math.round(performance.now() - start);
122
+ if (isCheckSkipped(err)) {
123
+ return { check: name, status: "skipped", issues: [], skipReason: err.message, durationMs };
124
+ }
125
+ return {
126
+ check: name,
127
+ status: "error",
128
+ issues: [],
129
+ error: friendlyDbError(err, sourceDbUrl),
130
+ durationMs
131
+ };
132
+ }
133
+ }
134
+ async function scan(registry, options, bus) {
135
+ const { config } = options;
136
+ const skipSet = /* @__PURE__ */ new Set([...options.skip ?? [], ...resolveExcludedChecks(config)]);
137
+ const checksToScan = (options.checks ?? [...CHECK_NAMES]).filter((n) => !skipSet.has(n));
138
+ const source = config.environments[config.source];
139
+ const target = config.environments[config.target];
140
+ const tableFilter = options.tableFilter ?? resolveTableFilter(config);
141
+ const ctx = { source, target, config, tableFilter };
142
+ await bus?.emit("supaforge.scan.before", ctx);
143
+ const results = new Array(checksToScan.length);
144
+ const total = checksToScan.length;
145
+ let next = 0;
146
+ const worker = async () => {
147
+ for (; ; ) {
148
+ const i = next++;
149
+ if (i >= total) return;
150
+ const name = checksToScan[i];
151
+ const check = registry.get(name);
152
+ options.onProgress?.({ phase: "check:start", check: name, index: i, total });
153
+ const checkCtx = {
154
+ ...ctx,
155
+ onDetail: options.onDetail ? (detail) => options.onDetail?.(name, detail) : void 0
156
+ };
157
+ if (!check) {
158
+ const skipReason = "not registered";
159
+ results[i] = { check: name, status: "skipped", issues: [], skipReason, durationMs: 0 };
160
+ options.onProgress?.({ phase: "check:done", check: name, index: i, total, status: "skipped", issueCount: 0, durationMs: 0, skipReason });
161
+ continue;
162
+ }
163
+ await bus?.emit("supaforge.check.before", { check: name });
164
+ const result = await runCheck(check, checkCtx, name, source.dbUrl);
165
+ results[i] = result;
166
+ options.onProgress?.({
167
+ phase: "check:done",
168
+ check: name,
169
+ index: i,
170
+ total,
171
+ status: result.status,
172
+ issueCount: result.issues.length,
173
+ durationMs: result.durationMs,
174
+ ...result.skipReason ? { skipReason: result.skipReason } : {}
175
+ });
176
+ await bus?.emit("supaforge.check.after", { check: name, result });
177
+ }
178
+ };
179
+ await Promise.all(
180
+ Array.from({ length: Math.min(checkConcurrency(), total) }, () => worker())
181
+ );
182
+ foldDuplicatePolicyFindings(results);
183
+ foldDuplicateExtensionFindings(results);
184
+ const summary = summarize(results);
185
+ const score = computeScore(results);
186
+ const postureScore = computePostureScore(results);
187
+ const scanResult = {
188
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
189
+ source: config.source,
190
+ target: config.target,
191
+ checks: results,
192
+ score,
193
+ postureScore,
194
+ summary
195
+ };
196
+ await bus?.emit("supaforge.scan.after", scanResult);
197
+ return scanResult;
198
+ }
199
+ function foldDuplicatePolicyFindings(results) {
200
+ foldInto(results, "rls", policyOnlyKeys);
201
+ }
202
+ function foldDuplicateExtensionFindings(results) {
203
+ foldInto(results, "extensions", extensionOnlyKeys);
204
+ }
205
+ function extensionOnlyKeys(sql) {
206
+ const statements = splitSqlStatements(sql ?? "").map((s) => sqlSkeleton(s).trim()).filter(Boolean);
207
+ const keys = statements.map((s) => /^(?:CREATE\s+EXTENSION\s+(?:IF\s+NOT\s+EXISTS\s+)?|DROP\s+EXTENSION\s+(?:IF\s+EXISTS\s+)?)("[^"]+"|[\w$-]+)/i.exec(s)?.[1]);
208
+ if (keys.length === 0 || keys.some((k) => k === void 0)) return null;
209
+ return [...new Set(keys.map((k) => k.replace(/^"|"$/g, "").toLowerCase()))];
210
+ }
211
+ function foldInto(results, into, keysOf) {
212
+ const owner = results.find((r) => r?.check === into && (r.status === "drifted" || r.status === "clean"));
213
+ const schema = results.find((r) => r?.check === "schema" && r.status === "drifted");
214
+ if (!owner || !schema) return;
215
+ const covered = /* @__PURE__ */ new Set();
216
+ for (const issue of owner.issues) {
217
+ for (const key of keysOf(issue.sql?.up) ?? []) covered.add(key);
218
+ }
219
+ const before = schema.issues.length;
220
+ schema.issues = schema.issues.filter((issue) => {
221
+ const keys = keysOf(issue.sql?.up);
222
+ return !(keys && keys.length > 0 && keys.every((k) => covered.has(k)));
223
+ });
224
+ const folded = before - schema.issues.length;
225
+ if (folded === 0) return;
226
+ schema.folded = [...schema.folded ?? [], { count: folded, into }];
227
+ if (schema.issues.length === 0) schema.status = "clean";
228
+ }
229
+
230
+ // src/checks/registry.ts
231
+ var CheckRegistry = class {
232
+ checks = /* @__PURE__ */ new Map();
233
+ register(check) {
234
+ this.checks.set(check.name, check);
235
+ }
236
+ get(name) {
237
+ return this.checks.get(name);
238
+ }
239
+ all() {
240
+ return [...this.checks.values()];
241
+ }
242
+ has(name) {
243
+ return this.checks.has(name);
244
+ }
245
+ };
246
+
247
+ // src/checks/schema.ts
248
+ var SchemaCheck = class extends Check {
249
+ constructor(runFn = runDbDiff, queryFn = pgQuery) {
250
+ super();
251
+ this.runFn = runFn;
252
+ this.queryFn = queryFn;
253
+ }
254
+ name = "schema";
255
+ async scan(ctx) {
256
+ try {
257
+ const ignoreSchemas = ctx.config.ignoreSchemas ?? DEFAULT_IGNORE_SCHEMAS;
258
+ const [result, ignoredSchemaTables] = await Promise.all([
259
+ this.runFn({
260
+ sourceUrl: ctx.source.dbUrl,
261
+ targetUrl: ctx.target.dbUrl,
262
+ type: "schema",
263
+ include: "both",
264
+ timeoutSeconds: ctx.target?.checks?.schema?.timeout,
265
+ onProgress: ctx.onDetail ? ({ table, tablesSeen }) => ctx.onDetail?.(`${tablesSeen} tables \xB7 ${table}`) : void 0,
266
+ ignoreSchemas,
267
+ // dbdiff takes the include/exclude lists natively, globs and all, so
268
+ // the scope is enforced in the diff itself rather than by discarding
269
+ // findings afterwards (issue #43).
270
+ ...ctx.tableFilter?.tables?.length ? { tables: ctx.tableFilter.tables } : {},
271
+ ...ctx.tableFilter?.excludeTables?.length ? { ignoreTables: ctx.tableFilter.excludeTables } : {}
272
+ }),
273
+ this.fetchIgnoredSchemaTables(ctx.target.dbUrl, ignoreSchemas)
274
+ ]);
275
+ return sqlToIssues(result, "schema", ignoreSchemas, ignoredSchemaTables);
276
+ } catch (err) {
277
+ if (err instanceof Error && err.message.includes("@dbdiff/cli is not installed")) {
278
+ throw new CheckSkipped("@dbdiff/cli is not installed");
279
+ }
280
+ throw err;
281
+ }
282
+ }
283
+ /**
284
+ * Query the target DB for table names inside ignored schemas.
285
+ *
286
+ * These are used to detect unqualified FK REFERENCES like `REFERENCES "users"`
287
+ * where "users" lives in the ignored "auth" schema but dbdiff omitted the
288
+ * schema prefix (due to search_path or its own normalisation).
289
+ *
290
+ * Returns a Set of lowercase table names, bare and schema-qualified. Fails silently so that a transient
291
+ * DB error here never blocks the main schema diff.
292
+ */
293
+ async fetchIgnoredSchemaTables(dbUrl, ignoreSchemas) {
294
+ if (ignoreSchemas.length === 0) return /* @__PURE__ */ new Set();
295
+ try {
296
+ const placeholders = ignoreSchemas.map((_, i) => `$${i + 1}`).join(", ");
297
+ const rows = await this.queryFn(
298
+ dbUrl,
299
+ `SELECT schemaname, tablename FROM pg_tables WHERE schemaname IN (${placeholders})`,
300
+ ignoreSchemas
301
+ );
302
+ return new Set(rows.flatMap((r) => [
303
+ String(r.tablename).toLowerCase(),
304
+ `${String(r.schemaname)}.${String(r.tablename)}`.toLowerCase()
305
+ ]));
306
+ } catch {
307
+ return /* @__PURE__ */ new Set();
308
+ }
309
+ }
310
+ };
311
+
312
+ // src/checks/rls.ts
313
+ var RlsCheck = class extends Check {
314
+ constructor(queryFn = pgQuery) {
315
+ super();
316
+ this.queryFn = queryFn;
317
+ }
318
+ name = "rls";
319
+ async scan(ctx) {
320
+ const ignoreSchemas = ctx.config.ignoreSchemas ?? [];
321
+ const [sourcePolicies, targetPolicies, sourceStatus, targetStatus] = await Promise.all([
322
+ this.fetchPolicies(ctx.source.dbUrl, ignoreSchemas),
323
+ this.fetchPolicies(ctx.target.dbUrl, ignoreSchemas),
324
+ this.fetchTableRlsStatus(ctx.source.dbUrl, ignoreSchemas),
325
+ this.fetchTableRlsStatus(ctx.target.dbUrl, ignoreSchemas)
326
+ ]);
327
+ return [
328
+ ...diffRlsStatus(sourceStatus, targetStatus),
329
+ // The same policy restored from a dump renders differently; that is not
330
+ // a change (see policy-equivalence).
331
+ ...await dropEquivalentPolicyChanges(
332
+ diffPolicies(sourcePolicies, targetPolicies),
333
+ ctx,
334
+ defaultCanonicalizer(this.queryFn)
335
+ )
336
+ ];
337
+ }
338
+ async fetchPolicies(dbUrl, ignoreSchemas) {
339
+ if (ignoreSchemas.length === 0) {
340
+ return await this.queryFn(dbUrl, POLICY_SQL_NO_FILTER);
341
+ }
342
+ const placeholders = ignoreSchemas.map((_, i) => `$${i + 1}`).join(", ");
343
+ const sql = `
344
+ SELECT schemaname, tablename, policyname, permissive, roles, cmd, qual, with_check
345
+ FROM pg_policies
346
+ WHERE schemaname NOT IN (${placeholders})
347
+ ORDER BY schemaname, tablename, policyname
348
+ `;
349
+ return await this.queryFn(dbUrl, sql, ignoreSchemas);
350
+ }
351
+ async fetchTableRlsStatus(dbUrl, ignoreSchemas) {
352
+ if (ignoreSchemas.length === 0) {
353
+ return await this.queryFn(dbUrl, RLS_STATUS_SQL_NO_FILTER);
354
+ }
355
+ const placeholders = ignoreSchemas.map((_, i) => `$${i + 1}`).join(", ");
356
+ const sql = `
357
+ SELECT n.nspname AS schemaname, c.relname AS tablename, c.relrowsecurity AS rls_enabled
358
+ FROM pg_class c
359
+ JOIN pg_namespace n ON n.oid = c.relnamespace
360
+ WHERE c.relkind = 'r'
361
+ AND n.nspname NOT IN (${placeholders})
362
+ ORDER BY n.nspname, c.relname
363
+ `;
364
+ return await this.queryFn(dbUrl, sql, ignoreSchemas);
365
+ }
366
+ };
367
+ var POLICY_SQL_NO_FILTER = `
368
+ SELECT schemaname, tablename, policyname, permissive, roles, cmd, qual, with_check
369
+ FROM pg_policies
370
+ ORDER BY schemaname, tablename, policyname
371
+ `;
372
+ var RLS_STATUS_SQL_NO_FILTER = `
373
+ SELECT n.nspname AS schemaname, c.relname AS tablename, c.relrowsecurity AS rls_enabled
374
+ FROM pg_class c
375
+ JOIN pg_namespace n ON n.oid = c.relnamespace
376
+ WHERE c.relkind = 'r'
377
+ ORDER BY n.nspname, c.relname
378
+ `;
379
+ function policyKey(p) {
380
+ return `${p.schemaname}.${p.tablename}.${p.policyname}`;
381
+ }
382
+ function policiesEqual(a, b) {
383
+ return a.permissive === b.permissive && a.cmd === b.cmd && a.qual === b.qual && a.with_check === b.with_check && JSON.stringify(a.roles) === JSON.stringify(b.roles);
384
+ }
385
+ var generateCreatePolicySql = (p) => createPolicySql(p.schemaname, p);
386
+ var generateDropPolicySql = (p) => dropPolicySql(p.schemaname, p);
387
+ function diffPolicies(source, target) {
388
+ const issues = [];
389
+ const sourceMap = new Map(source.map((p) => [policyKey(p), p]));
390
+ const targetMap = new Map(target.map((p) => [policyKey(p), p]));
391
+ for (const [key, p] of sourceMap) {
392
+ if (!targetMap.has(key)) {
393
+ issues.push({
394
+ id: `rls-missing-${key}`,
395
+ check: "rls",
396
+ severity: "critical",
397
+ title: `Missing RLS policy: ${p.policyname}`,
398
+ description: `Policy "${p.policyname}" on ${p.schemaname}.${p.tablename} exists in source but is missing from target. This is a CVE-2025-48757 risk pattern.`,
399
+ sourceValue: p,
400
+ sql: {
401
+ up: generateCreatePolicySql(p),
402
+ down: generateDropPolicySql(p)
403
+ }
404
+ });
405
+ }
406
+ }
407
+ for (const [key, p] of targetMap) {
408
+ if (!sourceMap.has(key)) {
409
+ issues.push({
410
+ id: `rls-extra-${key}`,
411
+ check: "rls",
412
+ severity: "warning",
413
+ title: `Extra RLS policy: ${p.policyname}`,
414
+ description: `Policy "${p.policyname}" on ${p.schemaname}.${p.tablename} exists in target but not in source.`,
415
+ targetValue: p,
416
+ sql: {
417
+ up: generateDropPolicySql(p),
418
+ down: generateCreatePolicySql(p)
419
+ }
420
+ });
421
+ }
422
+ }
423
+ for (const [key, sp] of sourceMap) {
424
+ const tp = targetMap.get(key);
425
+ if (tp && !policiesEqual(sp, tp)) {
426
+ issues.push({
427
+ id: `rls-modified-${key}`,
428
+ check: "rls",
429
+ severity: "critical",
430
+ title: `Modified RLS policy: ${sp.policyname}`,
431
+ description: `Policy "${sp.policyname}" on ${sp.schemaname}.${sp.tablename} has different USING/WITH CHECK expressions between source and target.`,
432
+ sourceValue: sp,
433
+ targetValue: tp,
434
+ sql: {
435
+ up: [generateDropPolicySql(sp), generateCreatePolicySql(sp)].join("\n"),
436
+ down: [generateDropPolicySql(tp), generateCreatePolicySql(tp)].join("\n")
437
+ }
438
+ });
439
+ }
440
+ }
441
+ return issues;
442
+ }
443
+ function diffRlsStatus(source, target) {
444
+ const issues = [];
445
+ const targetMap = new Map(target.map((t) => [`${t.schemaname}.${t.tablename}`, t]));
446
+ for (const src of source) {
447
+ const key = `${src.schemaname}.${src.tablename}`;
448
+ const tgt = targetMap.get(key);
449
+ if (!tgt) continue;
450
+ if (src.rls_enabled && !tgt.rls_enabled) {
451
+ issues.push({
452
+ id: `rls-disabled-${key}`,
453
+ check: "rls",
454
+ severity: "critical",
455
+ title: `RLS not enabled: ${src.schemaname}.${src.tablename}`,
456
+ description: `Row Level Security is enabled on "${src.schemaname}"."${src.tablename}" in source but disabled in target. Any policies on this table have no effect until RLS is enabled.`,
457
+ sourceValue: src,
458
+ targetValue: tgt,
459
+ sql: {
460
+ up: `ALTER TABLE ${quoteName(src.schemaname)}.${quoteName(src.tablename)} ENABLE ROW LEVEL SECURITY;`,
461
+ down: `ALTER TABLE ${quoteName(src.schemaname)}.${quoteName(src.tablename)} DISABLE ROW LEVEL SECURITY;`
462
+ }
463
+ });
464
+ } else if (!src.rls_enabled && tgt.rls_enabled) {
465
+ issues.push({
466
+ id: `rls-enabled-${key}`,
467
+ check: "rls",
468
+ severity: "warning",
469
+ title: `RLS enabled unexpectedly: ${src.schemaname}.${src.tablename}`,
470
+ description: `Row Level Security is disabled on "${src.schemaname}"."${src.tablename}" in source but enabled in target.`,
471
+ sourceValue: src,
472
+ targetValue: tgt,
473
+ sql: {
474
+ up: `ALTER TABLE ${quoteName(src.schemaname)}.${quoteName(src.tablename)} DISABLE ROW LEVEL SECURITY;`,
475
+ down: `ALTER TABLE ${quoteName(src.schemaname)}.${quoteName(src.tablename)} ENABLE ROW LEVEL SECURITY;`
476
+ }
477
+ });
478
+ }
479
+ }
480
+ return issues;
481
+ }
482
+
483
+ // src/checks/rls-coverage.ts
484
+ var TABLES_WITHOUT_RLS_SQL = `
485
+ SELECT n.nspname AS schemaname, c.relname AS tablename
486
+ FROM pg_class c
487
+ JOIN pg_namespace n ON n.oid = c.relnamespace
488
+ WHERE c.relkind = 'r'
489
+ AND c.relrowsecurity = false
490
+ ORDER BY n.nspname, c.relname
491
+ `;
492
+ var RlsCoverageCheck = class extends Check {
493
+ constructor(queryFn = pgQuery) {
494
+ super();
495
+ this.queryFn = queryFn;
496
+ }
497
+ name = "rls-coverage";
498
+ async scan(ctx) {
499
+ const ignoreSchemas = ctx.config.ignoreSchemas ?? [];
500
+ const tables = await this.fetchTablesWithoutRls(ctx.target.dbUrl, ignoreSchemas);
501
+ return tables.map(buildIssue);
502
+ }
503
+ async fetchTablesWithoutRls(dbUrl, ignoreSchemas) {
504
+ if (ignoreSchemas.length === 0) {
505
+ return this.queryFn(dbUrl, TABLES_WITHOUT_RLS_SQL);
506
+ }
507
+ const placeholders = ignoreSchemas.map((_, i) => `$${i + 1}`).join(", ");
508
+ const sql = `
509
+ SELECT n.nspname AS schemaname, c.relname AS tablename
510
+ FROM pg_class c
511
+ JOIN pg_namespace n ON n.oid = c.relnamespace
512
+ WHERE c.relkind = 'r'
513
+ AND c.relrowsecurity = false
514
+ AND n.nspname NOT IN (${placeholders})
515
+ ORDER BY n.nspname, c.relname
516
+ `;
517
+ return this.queryFn(dbUrl, sql, ignoreSchemas);
518
+ }
519
+ };
520
+ function buildIssue(t) {
521
+ const tableRef = `${quoteName(t.schemaname)}.${quoteName(t.tablename)}`;
522
+ return {
523
+ id: `rls-coverage-${t.schemaname}.${t.tablename}`,
524
+ check: "rls-coverage",
525
+ severity: "critical",
526
+ title: `RLS not enabled: ${t.schemaname}.${t.tablename}`,
527
+ description: `Table ${tableRef} has Row Level Security disabled. Any authenticated user can access all rows without policy restrictions \u2014 this is the CVE-2025-48757 vulnerability pattern.`,
528
+ targetValue: t,
529
+ sql: {
530
+ up: `ALTER TABLE ${tableRef} ENABLE ROW LEVEL SECURITY;`,
531
+ down: `ALTER TABLE ${tableRef} DISABLE ROW LEVEL SECURITY;`
532
+ }
533
+ };
534
+ }
535
+
536
+ // src/edge-functions-fs.ts
537
+ import { createHash } from "crypto";
538
+ import { readdir, readFile, stat } from "fs/promises";
539
+ import { join, relative, sep } from "path";
540
+ var IGNORED = /* @__PURE__ */ new Set([".DS_Store", "Thumbs.db", ".gitkeep"]);
541
+ var NOT_FUNCTIONS = /* @__PURE__ */ new Set(["main"]);
542
+ async function hashDirectory(dir) {
543
+ const files = [];
544
+ async function walk(current) {
545
+ const entries = await readdir(current, { withFileTypes: true });
546
+ for (const entry of entries) {
547
+ if (IGNORED.has(entry.name)) continue;
548
+ const full = join(current, entry.name);
549
+ if (entry.isDirectory()) await walk(full);
550
+ else if (entry.isFile()) files.push(full);
551
+ }
552
+ }
553
+ await walk(dir);
554
+ const relative_ = files.map((f) => ({ abs: f, rel: relative(dir, f).split(sep).join("/") }));
555
+ relative_.sort((a, b) => a.rel.localeCompare(b.rel));
556
+ const hash = createHash("sha256");
557
+ for (const f of relative_) {
558
+ hash.update(f.rel);
559
+ hash.update("\0");
560
+ hash.update(await readFile(f.abs));
561
+ hash.update("\0");
562
+ }
563
+ return { hash: hash.digest("hex"), fileCount: relative_.length };
564
+ }
565
+ async function inventoryFunctions(root) {
566
+ let entries;
567
+ try {
568
+ entries = await readdir(root, { withFileTypes: true });
569
+ } catch {
570
+ return [];
571
+ }
572
+ const out = [];
573
+ for (const entry of entries) {
574
+ if (!entry.isDirectory()) continue;
575
+ if (entry.name.startsWith(".") || entry.name.startsWith("_")) continue;
576
+ if (NOT_FUNCTIONS.has(entry.name)) continue;
577
+ const dir = join(root, entry.name);
578
+ try {
579
+ await stat(dir);
580
+ const { hash, fileCount } = await hashDirectory(dir);
581
+ if (fileCount === 0) continue;
582
+ out.push({ slug: entry.name, hash, fileCount });
583
+ } catch {
584
+ }
585
+ }
586
+ return out.sort((a, b) => a.slug.localeCompare(b.slug));
587
+ }
588
+
589
+ // src/edge-functions-api.ts
590
+ import { createHash as createHash2 } from "crypto";
591
+ var DEFAULT_SELF_HOSTED_REF = "default";
592
+ function base(studioUrl, ref) {
593
+ return `${studioUrl.replace(/\/+$/, "")}/api/v1/projects/${encodeURIComponent(ref)}/functions`;
594
+ }
595
+ function parseMultipart(contentType, body) {
596
+ const match = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType);
597
+ const boundary = (match?.[1] ?? match?.[2] ?? "").trim();
598
+ if (!boundary) return [];
599
+ const files = [];
600
+ for (const section of body.split(`--${boundary}`)) {
601
+ const split = section.indexOf("\r\n\r\n");
602
+ if (split === -1) continue;
603
+ const headers = section.slice(0, split);
604
+ if (!/name="file"/i.test(headers)) continue;
605
+ const filename = /filename="([^"]*)"/i.exec(headers)?.[1] ?? "index.ts";
606
+ const content = section.slice(split + 4).replace(/\r\n$/, "");
607
+ files.push({ name: filename, body: content });
608
+ }
609
+ return files;
610
+ }
611
+ async function hashFunctionBody(res) {
612
+ const files = parseMultipart(res.headers.get("content-type") ?? "", await res.text());
613
+ files.sort((a, b) => a.name.localeCompare(b.name));
614
+ const hash = createHash2("sha256");
615
+ for (const file of files) {
616
+ hash.update(file.name);
617
+ hash.update("\0");
618
+ hash.update(file.body);
619
+ hash.update("\0");
620
+ }
621
+ return { hash: hash.digest("hex"), fileCount: files.length };
622
+ }
623
+ async function inventoryFunctionsViaStudio(studioUrl, ref, fetchFn) {
624
+ const listRes = await fetchFn(base(studioUrl, ref));
625
+ if (!listRes.ok) {
626
+ throw new Error(`Studio functions API returned ${listRes.status} for ${studioUrl}`);
627
+ }
628
+ const listed = await listRes.json();
629
+ const out = [];
630
+ for (const fn of listed) {
631
+ if (!fn?.slug) continue;
632
+ const bodyRes = await fetchFn(`${base(studioUrl, ref)}/${encodeURIComponent(fn.slug)}/body`);
633
+ if (!bodyRes.ok) {
634
+ out.push({ slug: fn.slug, hash: "", fileCount: 0 });
635
+ continue;
636
+ }
637
+ const { hash, fileCount } = await hashFunctionBody(bodyRes);
638
+ out.push({ slug: fn.slug, hash, fileCount });
639
+ }
640
+ return out.sort((a, b) => a.slug.localeCompare(b.slug));
641
+ }
642
+
643
+ // src/checks/edge-functions.ts
644
+ var EdgeFunctionsCheck = class extends Check {
645
+ constructor(fetchFn = globalThis.fetch.bind(globalThis)) {
646
+ super();
647
+ this.fetchFn = fetchFn;
648
+ }
649
+ name = "edge-functions";
650
+ async scan(ctx) {
651
+ const sourceRef = ctx.source.projectRef;
652
+ const targetRef = ctx.target.projectRef;
653
+ const sourceKey = ctx.source.accessToken;
654
+ const targetKey = ctx.target.accessToken;
655
+ const [source, target] = await Promise.all([
656
+ this.resolveInventory(ctx.source),
657
+ this.resolveInventory(ctx.target)
658
+ ]);
659
+ if (source && target) {
660
+ if (source.length === 0 && target.length === 0) {
661
+ throw new CheckSkipped("no Edge Functions found in either environment");
662
+ }
663
+ return diffFunctionInventories(source, target);
664
+ }
665
+ if (ctx.source.apiUrl || ctx.target.apiUrl) {
666
+ throw new CheckSkipped(
667
+ 'Edge Functions comparison needs a source to read from on self-hosted. Set "studioUrl" on both environments (preferred \u2014 Studio serves /api/v1/projects/{ref}/functions), or "functionsPath" to compare the mounted directories instead.'
668
+ );
669
+ }
670
+ if (!sourceRef || !targetRef || !sourceKey || !targetKey) {
671
+ throw new CheckSkipped("no projectRef or accessToken configured");
672
+ }
673
+ const [hostedSource, hostedTarget] = await Promise.all([
674
+ this.listFunctions(sourceRef, sourceKey),
675
+ this.listFunctions(targetRef, targetKey)
676
+ ]);
677
+ return diffFunctions(hostedSource, hostedTarget, targetRef, targetKey);
678
+ }
679
+ /**
680
+ * Where this environment's functions can be read from, or null if nowhere.
681
+ *
682
+ * Studio is preferred: it works remotely and returns module contents. The
683
+ * directory is the fallback for when Studio is not reachable.
684
+ */
685
+ async resolveInventory(env) {
686
+ if (env.studioUrl) {
687
+ return inventoryFunctionsViaStudio(
688
+ env.studioUrl,
689
+ env.projectRef ?? DEFAULT_SELF_HOSTED_REF,
690
+ this.fetchFn
691
+ );
692
+ }
693
+ if (env.functionsPath) return inventoryFunctions(env.functionsPath);
694
+ return null;
695
+ }
696
+ async listFunctions(projectRef, accessToken) {
697
+ const url = `${SUPABASE_MGMT_API}/${encodeURIComponent(projectRef)}/functions`;
698
+ const res = await this.fetchFn(url, {
699
+ headers: { Authorization: `Bearer ${accessToken}` }
700
+ });
701
+ if (!res.ok) throw new Error(`Failed to list functions for ${projectRef}: ${res.statusText}`);
702
+ return res.json();
703
+ }
704
+ };
705
+ function makeDeleteAction(slug, targetRef, targetKey) {
706
+ return {
707
+ method: "DELETE",
708
+ url: `${SUPABASE_MGMT_API}/${encodeURIComponent(targetRef)}/functions/${encodeURIComponent(slug)}`,
709
+ headers: { Authorization: `Bearer ${targetKey}` },
710
+ label: `Delete Edge Function "${slug}" from target`
711
+ };
712
+ }
713
+ function diffFunctions(source, target, targetRef, targetKey) {
714
+ const issues = [];
715
+ const sourceMap = new Map(source.map((f) => [f.slug, f]));
716
+ const targetMap = new Map(target.map((f) => [f.slug, f]));
717
+ for (const [slug, f] of sourceMap) {
718
+ if (!targetMap.has(slug)) {
719
+ issues.push({
720
+ id: `edge-fn-missing-${slug}`,
721
+ check: "edge-functions",
722
+ severity: "warning",
723
+ title: `Missing Edge Function: ${slug}`,
724
+ description: `Function "${f.name}" (${slug}) exists in source but not in target. Deploy it via "supabase functions deploy ${slug}" against the target project.`,
725
+ sourceValue: f
726
+ // Cannot auto-deploy: source code is not available via the Management API.
727
+ // User must deploy from their local supabase/functions/ directory.
728
+ });
729
+ }
730
+ }
731
+ for (const [slug, f] of targetMap) {
732
+ if (!sourceMap.has(slug)) {
733
+ issues.push({
734
+ id: `edge-fn-extra-${slug}`,
735
+ check: "edge-functions",
736
+ severity: "info",
737
+ title: `Extra Edge Function: ${slug}`,
738
+ description: `Function "${f.name}" (${slug}) exists in target but not in source.`,
739
+ targetValue: f,
740
+ action: makeDeleteAction(slug, targetRef, targetKey)
741
+ });
742
+ }
743
+ }
744
+ for (const [slug, sf] of sourceMap) {
745
+ const tf = targetMap.get(slug);
746
+ if (tf && sf.version !== tf.version) {
747
+ issues.push({
748
+ id: `edge-fn-version-${slug}`,
749
+ check: "edge-functions",
750
+ severity: "warning",
751
+ title: `Version mismatch: ${slug}`,
752
+ description: `Function "${slug}" is at version ${sf.version} in source but version ${tf.version} in target. Redeploy via "supabase functions deploy ${slug}" against the target project.`,
753
+ sourceValue: sf,
754
+ targetValue: tf
755
+ // Cannot auto-deploy: source code is not available via the Management API.
756
+ });
757
+ }
758
+ }
759
+ return issues;
760
+ }
761
+ function diffFunctionInventories(source, target) {
762
+ const issues = [];
763
+ const sourceMap = new Map(source.map((f) => [f.slug, f]));
764
+ const targetMap = new Map(target.map((f) => [f.slug, f]));
765
+ for (const [slug, sf] of sourceMap) {
766
+ if (targetMap.has(slug)) continue;
767
+ issues.push({
768
+ id: `edge-fn-missing-${slug}`,
769
+ check: "edge-functions",
770
+ severity: "warning",
771
+ title: `Missing Edge Function: ${slug}`,
772
+ description: `Function "${slug}" (${sf.fileCount} file(s)) exists in source but not in target. Deploy it with: supabase functions deploy ${slug}`,
773
+ sourceValue: { slug, fileCount: sf.fileCount }
774
+ });
775
+ }
776
+ for (const [slug, tf] of targetMap) {
777
+ if (sourceMap.has(slug)) continue;
778
+ issues.push({
779
+ id: `edge-fn-extra-${slug}`,
780
+ check: "edge-functions",
781
+ severity: "info",
782
+ title: `Extra Edge Function: ${slug}`,
783
+ description: `Function "${slug}" exists in target but not in source. Remove it with: supabase functions delete ${slug}`,
784
+ targetValue: { slug, fileCount: tf.fileCount }
785
+ });
786
+ }
787
+ for (const [slug, sf] of sourceMap) {
788
+ const tf = targetMap.get(slug);
789
+ if (!tf || tf.hash === sf.hash) continue;
790
+ issues.push({
791
+ id: `edge-fn-changed-${slug}`,
792
+ check: "edge-functions",
793
+ severity: "warning",
794
+ title: `Edge Function differs: ${slug}`,
795
+ description: `Function "${slug}" has different contents in source and target. Redeploy with: supabase functions deploy ${slug}`,
796
+ // Hashes, not source: the point is that they differ, and function code
797
+ // can contain secrets that have no business in a drift report.
798
+ sourceValue: { slug, sha256: sf.hash.slice(0, 12) },
799
+ targetValue: { slug, sha256: tf.hash.slice(0, 12) }
800
+ });
801
+ }
802
+ return issues;
803
+ }
804
+
805
+ // src/storage-files.ts
806
+ import { createClient } from "@supabase/supabase-js";
807
+ import { createHash as createHash3 } from "crypto";
808
+ var JSON_MIME_TYPES = ["application/json", "text/json"];
809
+ function buildSupabaseUrl(projectRef, apiUrl) {
810
+ if (apiUrl) return apiUrl;
811
+ return `https://${projectRef}.supabase.co`;
812
+ }
813
+ async function listBucketFiles(client, bucket, folder = "") {
814
+ const results = [];
815
+ const { data, error } = await client.storage.from(bucket).list(folder, {
816
+ limit: STORAGE_LIST_LIMIT,
817
+ sortBy: { column: "name", order: "asc" }
818
+ });
819
+ if (error || !data) return results;
820
+ for (const item of data) {
821
+ const itemPath = folder ? `${folder}/${item.name}` : item.name;
822
+ if (item.id === null) {
823
+ const children = await listBucketFiles(client, bucket, itemPath);
824
+ results.push(...children);
825
+ } else {
826
+ results.push({
827
+ name: item.name,
828
+ path: itemPath,
829
+ metadata: item.metadata
830
+ });
831
+ }
832
+ }
833
+ return results;
834
+ }
835
+ function toFileInfo(bucket, entry) {
836
+ const meta = entry.metadata ?? {};
837
+ return {
838
+ bucket,
839
+ path: entry.path,
840
+ name: entry.name,
841
+ size: typeof meta.size === "number" ? meta.size : 0,
842
+ createdAt: typeof meta.lastModified === "string" ? meta.lastModified : null,
843
+ updatedAt: typeof meta.lastModified === "string" ? meta.lastModified : null,
844
+ mimeType: typeof meta.mimetype === "string" ? meta.mimetype : null,
845
+ checksum: null
846
+ // populated later for JSON files
847
+ };
848
+ }
849
+ function md5(content) {
850
+ return createHash3("md5").update(content).digest("hex");
851
+ }
852
+ function isJsonFile(file) {
853
+ if (file.mimeType && JSON_MIME_TYPES.includes(file.mimeType)) return true;
854
+ return file.name.endsWith(".json");
855
+ }
856
+ async function inventoryFiles(client, buckets, computeChecksums) {
857
+ const allFiles = [];
858
+ for (const bucket of buckets) {
859
+ const entries = await listBucketFiles(client, bucket);
860
+ const files = entries.map((e) => toFileInfo(bucket, e));
861
+ if (computeChecksums) {
862
+ for (const file of files) {
863
+ if (isJsonFile(file)) {
864
+ try {
865
+ const { data, error } = await client.storage.from(bucket).download(file.path);
866
+ if (!error && data) {
867
+ const text = await data.text();
868
+ file.checksum = md5(text);
869
+ }
870
+ } catch {
871
+ }
872
+ }
873
+ }
874
+ }
875
+ allFiles.push(...files);
876
+ }
877
+ return allFiles;
878
+ }
879
+ function fileKey(file) {
880
+ return `${file.bucket}/${file.path}`;
881
+ }
882
+ function diffFileInventories(sourceFiles, targetFiles) {
883
+ const diffs = [];
884
+ const sourceMap = new Map(sourceFiles.map((f) => [fileKey(f), f]));
885
+ const targetMap = new Map(targetFiles.map((f) => [fileKey(f), f]));
886
+ for (const [key, sf] of sourceMap) {
887
+ if (!targetMap.has(key)) {
888
+ diffs.push({
889
+ bucket: sf.bucket,
890
+ path: sf.path,
891
+ type: "missing",
892
+ details: `File "${sf.path}" exists in source bucket "${sf.bucket}" but not in target.`,
893
+ sourceFile: sf
894
+ });
895
+ }
896
+ }
897
+ for (const [key, tf] of targetMap) {
898
+ if (!sourceMap.has(key)) {
899
+ diffs.push({
900
+ bucket: tf.bucket,
901
+ path: tf.path,
902
+ type: "extra",
903
+ details: `File "${tf.path}" exists in target bucket "${tf.bucket}" but not in source.`,
904
+ targetFile: tf
905
+ });
906
+ }
907
+ }
908
+ for (const [key, sf] of sourceMap) {
909
+ const tf = targetMap.get(key);
910
+ if (!tf) continue;
911
+ const changes = [];
912
+ if (sf.checksum && tf.checksum) {
913
+ if (sf.checksum !== tf.checksum) {
914
+ changes.push(`content differs (source md5: ${sf.checksum.slice(0, 12)}\u2026, target md5: ${tf.checksum.slice(0, 12)}\u2026)`);
915
+ }
916
+ } else {
917
+ if (sf.size !== tf.size) {
918
+ changes.push(`size differs (source: ${sf.size} bytes, target: ${tf.size} bytes)`);
919
+ }
920
+ if (sf.updatedAt && tf.updatedAt && sf.updatedAt !== tf.updatedAt) {
921
+ changes.push(`last modified differs (source: ${sf.updatedAt}, target: ${tf.updatedAt})`);
922
+ }
923
+ }
924
+ if (changes.length > 0) {
925
+ diffs.push({
926
+ bucket: sf.bucket,
927
+ path: sf.path,
928
+ type: "changed",
929
+ details: `File "${sf.path}" in bucket "${sf.bucket}": ${changes.join("; ")}.`,
930
+ sourceFile: sf,
931
+ targetFile: tf
932
+ });
933
+ }
934
+ }
935
+ return diffs;
936
+ }
937
+ function fileDiffsToIssues(diffs) {
938
+ return diffs.map((d) => ({
939
+ id: `storage-file-${d.type}-${d.bucket}-${d.path.replace(/[^a-zA-Z0-9]/g, "-")}`,
940
+ check: "storage",
941
+ severity: d.type === "missing" ? "warning" : d.type === "extra" ? "info" : "warning",
942
+ title: d.type === "missing" ? `Missing file: ${d.bucket}/${d.path}` : d.type === "extra" ? `Extra file: ${d.bucket}/${d.path}` : `Changed file: ${d.bucket}/${d.path}`,
943
+ description: d.details,
944
+ sourceValue: d.sourceFile,
945
+ targetValue: d.targetFile
946
+ }));
947
+ }
948
+ async function scanStorageFiles(options) {
949
+ const factory = options.createClientFn ?? createClient;
950
+ const sourceClient = factory(
951
+ buildSupabaseUrl(options.sourceRef, options.sourceApiUrl),
952
+ options.sourceKey
953
+ );
954
+ const targetClient = factory(
955
+ buildSupabaseUrl(options.targetRef, options.targetApiUrl),
956
+ options.targetKey
957
+ );
958
+ let buckets;
959
+ if (options.buckets?.length) {
960
+ buckets = options.buckets;
961
+ } else {
962
+ const [{ data: sb }, { data: tb }] = await Promise.all([
963
+ sourceClient.storage.listBuckets(),
964
+ targetClient.storage.listBuckets()
965
+ ]);
966
+ const sourceNames = new Set((sb ?? []).map((b) => b.name));
967
+ const targetNames = new Set((tb ?? []).map((b) => b.name));
968
+ buckets = [...sourceNames].filter((n) => targetNames.has(n));
969
+ }
970
+ if (buckets.length === 0) return [];
971
+ const [sourceFiles, targetFiles] = await Promise.all([
972
+ inventoryFiles(sourceClient, buckets, true),
973
+ inventoryFiles(targetClient, buckets, true)
974
+ ]);
975
+ const diffs = diffFileInventories(sourceFiles, targetFiles);
976
+ return fileDiffsToIssues(diffs);
977
+ }
978
+
979
+ // src/checks/storage.ts
980
+ var StorageCheck = class extends Check {
981
+ constructor(queryFn = pgQuery, includeFiles = false) {
982
+ super();
983
+ this.queryFn = queryFn;
984
+ this.includeFiles = includeFiles;
985
+ }
986
+ name = "storage";
987
+ async scan(ctx) {
988
+ const [srcHasStorage, tgtHasStorage] = await Promise.all([
989
+ this.hasStorageSchema(ctx.source.dbUrl),
990
+ this.hasStorageSchema(ctx.target.dbUrl)
991
+ ]);
992
+ if (!srcHasStorage || !tgtHasStorage) {
993
+ const which = !srcHasStorage && !tgtHasStorage ? "neither environment has" : !srcHasStorage ? "the source does not have" : "the target does not have";
994
+ throw new CheckSkipped(
995
+ `${which} a storage schema \u2014 not a Supabase project. Skip this check explicitly with --skip=storage to keep runs quiet.`
996
+ );
997
+ }
998
+ const bucketIssues = await this.scanBuckets(ctx);
999
+ const typedBucketIssues = await this.scanTypedBuckets(ctx);
1000
+ const policyIssues = await this.scanPolicies(ctx);
1001
+ let fileIssues = [];
1002
+ if (this.includeFiles) {
1003
+ fileIssues = await this.scanFiles(ctx);
1004
+ }
1005
+ return [...bucketIssues, ...typedBucketIssues, ...policyIssues, ...fileIssues];
1006
+ }
1007
+ /**
1008
+ * Analytics and vector buckets live in their own tables, not storage.buckets,
1009
+ * so creating one was invisible: the check read storage.buckets and reported
1010
+ * no drift at all.
1011
+ *
1012
+ * Both tables arrived with newer storage migrations (0038 analytics, 0044/45
1013
+ * vectors), so each is probed before being read.
1014
+ */
1015
+ async scanTypedBuckets(ctx) {
1016
+ const issues = [];
1017
+ for (const spec of TYPED_BUCKET_TABLES) {
1018
+ const [srcHas, tgtHas] = await Promise.all([
1019
+ this.hasTable(ctx.source.dbUrl, spec.table),
1020
+ this.hasTable(ctx.target.dbUrl, spec.table)
1021
+ ]);
1022
+ if (!srcHas || !tgtHas) continue;
1023
+ const [source, target] = await Promise.all([
1024
+ this.listTypedBuckets(ctx.source.dbUrl, spec),
1025
+ this.listTypedBuckets(ctx.target.dbUrl, spec)
1026
+ ]);
1027
+ issues.push(...diffTypedBuckets(source, target, spec));
1028
+ }
1029
+ return issues;
1030
+ }
1031
+ async hasTable(dbUrl, table) {
1032
+ const rows = await this.queryFn(dbUrl, tableExistsSql(table));
1033
+ return rows[0]?.present === true;
1034
+ }
1035
+ async listTypedBuckets(dbUrl, spec) {
1036
+ return await this.queryFn(dbUrl, spec.sql);
1037
+ }
1038
+ async scanBuckets(ctx) {
1039
+ const [source, target] = await Promise.all([
1040
+ this.listBuckets(ctx.source.dbUrl),
1041
+ this.listBuckets(ctx.target.dbUrl)
1042
+ ]);
1043
+ return diffBuckets(source, target, {
1044
+ apiUrl: ctx.target.apiUrl,
1045
+ accessToken: ctx.target.accessToken
1046
+ });
1047
+ }
1048
+ async scanPolicies(ctx) {
1049
+ const [source, target] = await Promise.all([
1050
+ this.fetchStoragePolicies(ctx.source.dbUrl),
1051
+ this.fetchStoragePolicies(ctx.target.dbUrl)
1052
+ ]);
1053
+ return dropEquivalentPolicyChanges(
1054
+ diffSchemaPolicies(source, target, {
1055
+ schema: "storage",
1056
+ check: "storage",
1057
+ idPrefix: "storage-policy",
1058
+ label: "storage"
1059
+ }),
1060
+ ctx,
1061
+ defaultCanonicalizer(this.queryFn),
1062
+ "storage"
1063
+ );
1064
+ }
1065
+ async hasStorageSchema(dbUrl) {
1066
+ const rows = await this.queryFn(dbUrl, STORAGE_PRESENT_SQL);
1067
+ return rows[0]?.present === true;
1068
+ }
1069
+ /**
1070
+ * Read the buckets, selecting only the columns this Supabase version actually
1071
+ * has. storage.buckets has grown over time (owner_id in 0018, type in 0038),
1072
+ * so a fixed column list either misses columns on a new instance or fails on
1073
+ * an old one. Resolving them per-connection handles both.
1074
+ */
1075
+ async listBuckets(dbUrl) {
1076
+ const present = await this.queryFn(dbUrl, BUCKET_COLUMNS_SQL);
1077
+ const names = new Set(present.map((r) => r.column_name));
1078
+ const cols = COMPARED_BUCKET_COLUMNS.filter((c) => names.has(c));
1079
+ const sql = `SELECT ${cols.join(", ")} FROM storage.buckets ORDER BY name`;
1080
+ return await this.queryFn(dbUrl, sql);
1081
+ }
1082
+ async fetchStoragePolicies(dbUrl) {
1083
+ return await this.queryFn(dbUrl, STORAGE_POLICY_SQL);
1084
+ }
1085
+ async scanFiles(ctx) {
1086
+ const sourceRef = ctx.source.projectRef;
1087
+ const targetRef = ctx.target.projectRef;
1088
+ const sourceKey = ctx.source.accessToken;
1089
+ const targetKey = ctx.target.accessToken;
1090
+ if (!sourceRef || !targetRef || !sourceKey || !targetKey) return [];
1091
+ const options = {
1092
+ sourceRef,
1093
+ targetRef,
1094
+ sourceKey,
1095
+ targetKey,
1096
+ sourceApiUrl: ctx.source.apiUrl,
1097
+ targetApiUrl: ctx.target.apiUrl
1098
+ };
1099
+ return await scanStorageFiles(options);
1100
+ }
1101
+ };
1102
+ var COMPARED_BUCKET_COLUMNS = [
1103
+ "id",
1104
+ "name",
1105
+ "public",
1106
+ "file_size_limit",
1107
+ "allowed_mime_types",
1108
+ "type",
1109
+ "avif_autodetection",
1110
+ "owner_id"
1111
+ ];
1112
+ var BUCKET_COLUMNS_SQL = `
1113
+ SELECT a.attname AS column_name
1114
+ FROM pg_attribute a
1115
+ JOIN pg_class c ON c.oid = a.attrelid
1116
+ JOIN pg_namespace n ON n.oid = c.relnamespace
1117
+ WHERE n.nspname = 'storage' AND c.relname = 'buckets' AND a.attnum > 0 AND NOT a.attisdropped
1118
+ `;
1119
+ var TYPED_BUCKET_TABLES = [
1120
+ {
1121
+ table: "buckets_analytics",
1122
+ key: "name",
1123
+ compared: ["format"],
1124
+ label: "analytics bucket",
1125
+ // deleted_at is a soft delete — a removed bucket still has its row.
1126
+ sql: `SELECT name AS key, format FROM storage.buckets_analytics
1127
+ WHERE deleted_at IS NULL ORDER BY name`
1128
+ },
1129
+ {
1130
+ table: "buckets_vectors",
1131
+ key: "id",
1132
+ compared: [],
1133
+ label: "vector bucket",
1134
+ sql: `SELECT id AS key FROM storage.buckets_vectors ORDER BY id`
1135
+ }
1136
+ ];
1137
+ function tableExistsSql(table) {
1138
+ return `
1139
+ SELECT EXISTS (
1140
+ SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
1141
+ WHERE n.nspname = 'storage' AND c.relname = '${table}'
1142
+ ) AS present
1143
+ `;
1144
+ }
1145
+ function diffTypedBuckets(source, target, spec) {
1146
+ const issues = [];
1147
+ const sourceMap = new Map(source.map((b) => [String(b.key), b]));
1148
+ const targetMap = new Map(target.map((b) => [String(b.key), b]));
1149
+ for (const [key, b] of sourceMap) {
1150
+ if (targetMap.has(key)) continue;
1151
+ issues.push({
1152
+ id: `storage-${spec.table}-missing-${key}`,
1153
+ check: "storage",
1154
+ severity: "warning",
1155
+ title: `Missing ${spec.label}: ${key}`,
1156
+ description: `${spec.label} "${key}" exists in source but not in target.`,
1157
+ sourceValue: b
1158
+ });
1159
+ }
1160
+ for (const [key, b] of targetMap) {
1161
+ if (sourceMap.has(key)) continue;
1162
+ issues.push({
1163
+ id: `storage-${spec.table}-extra-${key}`,
1164
+ check: "storage",
1165
+ severity: "info",
1166
+ title: `Extra ${spec.label}: ${key}`,
1167
+ description: `${spec.label} "${key}" exists in target but not in source.`,
1168
+ targetValue: b
1169
+ });
1170
+ }
1171
+ for (const [key, sb] of sourceMap) {
1172
+ const tb = targetMap.get(key);
1173
+ if (!tb) continue;
1174
+ for (const col of spec.compared) {
1175
+ if (sb[col] === tb[col]) continue;
1176
+ issues.push({
1177
+ id: `storage-${spec.table}-${col}-${key}`,
1178
+ check: "storage",
1179
+ severity: "warning",
1180
+ title: `${spec.label} ${col} mismatch: ${key}`,
1181
+ description: `${spec.label} "${key}" has ${col} ${String(sb[col])} in source but ${String(tb[col])} in target.`,
1182
+ sourceValue: { [col]: sb[col] },
1183
+ targetValue: { [col]: tb[col] }
1184
+ });
1185
+ }
1186
+ }
1187
+ return issues;
1188
+ }
1189
+ var STORAGE_PRESENT_SQL = `
1190
+ SELECT EXISTS (
1191
+ SELECT 1 FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
1192
+ WHERE n.nspname = 'storage' AND c.relname = 'buckets'
1193
+ ) AS present
1194
+ `;
1195
+ var STORAGE_POLICY_SQL = schemaPolicySql("storage");
1196
+ function bucketApiHeaders(accessToken) {
1197
+ if (!accessToken) return {};
1198
+ return { apikey: accessToken, Authorization: `Bearer ${accessToken}` };
1199
+ }
1200
+ function bucketAction(config, method, path, label, body) {
1201
+ return {
1202
+ method,
1203
+ url: `${config.apiUrl}/storage/v1/bucket${path}`,
1204
+ headers: bucketApiHeaders(config.accessToken),
1205
+ label,
1206
+ ...body !== void 0 && { body }
1207
+ };
1208
+ }
1209
+ function diffBuckets(source, target, config) {
1210
+ const issues = [];
1211
+ const sourceMap = new Map(source.map((b) => [b.id, b]));
1212
+ const targetMap = new Map(target.map((b) => [b.id, b]));
1213
+ const useApi = !!config?.apiUrl;
1214
+ for (const [id, b] of sourceMap) {
1215
+ if (!targetMap.has(id)) {
1216
+ const issue = {
1217
+ id: `storage-missing-${id}`,
1218
+ check: "storage",
1219
+ severity: "warning",
1220
+ title: `Missing bucket: ${b.name}`,
1221
+ description: `Bucket "${b.name}" exists in source but not in target.`,
1222
+ sourceValue: b
1223
+ };
1224
+ if (useApi) {
1225
+ issue.action = bucketAction(config, "POST", "", `Create bucket "${b.name}"`, {
1226
+ id: b.id,
1227
+ name: b.name,
1228
+ public: b.public,
1229
+ file_size_limit: b.file_size_limit,
1230
+ allowed_mime_types: b.allowed_mime_types
1231
+ });
1232
+ } else {
1233
+ issue.sql = {
1234
+ up: `INSERT INTO storage.buckets (id, name, public, file_size_limit, allowed_mime_types) VALUES (${sqlLiteral(b.id)}, ${sqlLiteral(b.name)}, ${sqlLiteral(b.public)}, ${sqlLiteral(b.file_size_limit)}, ${sqlLiteral(b.allowed_mime_types)});`,
1235
+ down: `DELETE FROM storage.buckets WHERE id = ${sqlLiteral(b.id)};`
1236
+ };
1237
+ }
1238
+ issues.push(issue);
1239
+ }
1240
+ }
1241
+ for (const [id, b] of targetMap) {
1242
+ if (!sourceMap.has(id)) {
1243
+ const issue = {
1244
+ id: `storage-extra-${id}`,
1245
+ check: "storage",
1246
+ severity: "info",
1247
+ title: `Extra bucket: ${b.name}`,
1248
+ description: `Bucket "${b.name}" exists in target but not in source.`,
1249
+ targetValue: b
1250
+ };
1251
+ if (useApi) {
1252
+ issue.action = bucketAction(config, "DELETE", `/${id}`, `Delete bucket "${b.name}"`);
1253
+ } else {
1254
+ issue.sql = {
1255
+ up: `DELETE FROM storage.buckets WHERE id = ${sqlLiteral(b.id)};`,
1256
+ down: `INSERT INTO storage.buckets (id, name, public, file_size_limit, allowed_mime_types) VALUES (${sqlLiteral(b.id)}, ${sqlLiteral(b.name)}, ${sqlLiteral(b.public)}, ${sqlLiteral(b.file_size_limit)}, ${sqlLiteral(b.allowed_mime_types)});`
1257
+ };
1258
+ }
1259
+ issues.push(issue);
1260
+ }
1261
+ }
1262
+ for (const [id, sb] of sourceMap) {
1263
+ const tb = targetMap.get(id);
1264
+ if (!tb) continue;
1265
+ const setClauses = [];
1266
+ if (sb.public !== tb.public) {
1267
+ setClauses.push(`public = ${sqlLiteral(sb.public)}`);
1268
+ issues.push({
1269
+ id: `storage-visibility-${id}`,
1270
+ check: "storage",
1271
+ severity: sb.public && !tb.public ? "warning" : "critical",
1272
+ title: `Bucket visibility mismatch: ${sb.name}`,
1273
+ description: `Bucket "${sb.name}" is ${sb.public ? "public" : "private"} in source but ${tb.public ? "public" : "private"} in target.`,
1274
+ sourceValue: { public: sb.public },
1275
+ targetValue: { public: tb.public }
1276
+ });
1277
+ }
1278
+ if (sb.file_size_limit !== tb.file_size_limit) {
1279
+ setClauses.push(`file_size_limit = ${sqlLiteral(sb.file_size_limit)}`);
1280
+ issues.push({
1281
+ id: `storage-sizelimit-${id}`,
1282
+ check: "storage",
1283
+ severity: "warning",
1284
+ title: `Bucket file size limit mismatch: ${sb.name}`,
1285
+ description: `Bucket "${sb.name}" file_size_limit is ${sb.file_size_limit ?? "unlimited"} in source but ${tb.file_size_limit ?? "unlimited"} in target.`,
1286
+ sourceValue: { file_size_limit: sb.file_size_limit },
1287
+ targetValue: { file_size_limit: tb.file_size_limit }
1288
+ });
1289
+ }
1290
+ const srcMimes = (sb.allowed_mime_types ?? []).slice().sort().join(",");
1291
+ const tgtMimes = (tb.allowed_mime_types ?? []).slice().sort().join(",");
1292
+ if (srcMimes !== tgtMimes) {
1293
+ setClauses.push(`allowed_mime_types = ${sqlLiteral(sb.allowed_mime_types)}`);
1294
+ issues.push({
1295
+ id: `storage-mimetypes-${id}`,
1296
+ check: "storage",
1297
+ severity: "warning",
1298
+ title: `Bucket allowed MIME types mismatch: ${sb.name}`,
1299
+ description: `Bucket "${sb.name}" allowed_mime_types differ between source and target.`,
1300
+ sourceValue: { allowed_mime_types: sb.allowed_mime_types },
1301
+ targetValue: { allowed_mime_types: tb.allowed_mime_types }
1302
+ });
1303
+ }
1304
+ if (sb.type !== void 0 && tb.type !== void 0 && sb.type !== tb.type) {
1305
+ setClauses.push(`type = ${sqlLiteral(sb.type)}`);
1306
+ issues.push({
1307
+ id: `storage-type-${id}`,
1308
+ check: "storage",
1309
+ severity: "critical",
1310
+ title: `Bucket type mismatch: ${sb.name}`,
1311
+ description: `Bucket "${sb.name}" is ${sb.type} in source but ${tb.type} in target \u2014 these are different storage backends, not a setting.`,
1312
+ sourceValue: { type: sb.type },
1313
+ targetValue: { type: tb.type }
1314
+ });
1315
+ }
1316
+ if (sb.avif_autodetection !== void 0 && tb.avif_autodetection !== void 0 && sb.avif_autodetection !== tb.avif_autodetection) {
1317
+ setClauses.push(`avif_autodetection = ${sqlLiteral(sb.avif_autodetection)}`);
1318
+ issues.push({
1319
+ id: `storage-avif-${id}`,
1320
+ check: "storage",
1321
+ severity: "warning",
1322
+ title: `Bucket AVIF autodetection mismatch: ${sb.name}`,
1323
+ description: `Bucket "${sb.name}" avif_autodetection is ${sb.avif_autodetection} in source but ${tb.avif_autodetection} in target.`,
1324
+ sourceValue: { avif_autodetection: sb.avif_autodetection },
1325
+ targetValue: { avif_autodetection: tb.avif_autodetection }
1326
+ });
1327
+ }
1328
+ if (sb.owner_id !== void 0 && tb.owner_id !== void 0 && sb.owner_id !== tb.owner_id) {
1329
+ issues.push({
1330
+ id: `storage-owner-${id}`,
1331
+ check: "storage",
1332
+ severity: "info",
1333
+ title: `Bucket owner mismatch: ${sb.name}`,
1334
+ description: `Bucket "${sb.name}" has a different owner_id in each environment. Not synced \u2014 the owner is an identity local to its own project.`,
1335
+ sourceValue: { owner_id: sb.owner_id },
1336
+ targetValue: { owner_id: tb.owner_id }
1337
+ });
1338
+ }
1339
+ if (setClauses.length > 0) {
1340
+ const firstBucketIssue = issues.find(
1341
+ (i) => i.id.startsWith(`storage-visibility-${id}`) || i.id.startsWith(`storage-sizelimit-${id}`) || i.id.startsWith(`storage-mimetypes-${id}`) || i.id.startsWith(`storage-type-${id}`) || i.id.startsWith(`storage-avif-${id}`)
1342
+ );
1343
+ if (firstBucketIssue) {
1344
+ if (useApi) {
1345
+ firstBucketIssue.action = bucketAction(config, "PUT", `/${id}`, `Update bucket "${sb.name}"`, {
1346
+ public: sb.public,
1347
+ file_size_limit: sb.file_size_limit,
1348
+ allowed_mime_types: sb.allowed_mime_types
1349
+ });
1350
+ } else {
1351
+ const revertClauses = [];
1352
+ if (sb.public !== tb.public) revertClauses.push(`public = ${sqlLiteral(tb.public)}`);
1353
+ if (sb.file_size_limit !== tb.file_size_limit) revertClauses.push(`file_size_limit = ${sqlLiteral(tb.file_size_limit)}`);
1354
+ if (srcMimes !== tgtMimes) revertClauses.push(`allowed_mime_types = ${sqlLiteral(tb.allowed_mime_types)}`);
1355
+ firstBucketIssue.sql = {
1356
+ up: `UPDATE storage.buckets SET ${setClauses.join(", ")} WHERE id = ${sqlLiteral(id)};`,
1357
+ down: `UPDATE storage.buckets SET ${revertClauses.join(", ")} WHERE id = ${sqlLiteral(id)};`
1358
+ };
1359
+ }
1360
+ }
1361
+ }
1362
+ }
1363
+ return issues;
1364
+ }
1365
+
1366
+ // src/checks/auth.ts
1367
+ var AUTH_SETTINGS_PATH = "/auth/v1/settings";
1368
+ function resolveAuthSource(env) {
1369
+ if (env.apiUrl && env.accessToken) {
1370
+ const apiUrl = normalizeApiUrl(env.apiUrl);
1371
+ if (!apiUrl) {
1372
+ throw new CheckSkipped(
1373
+ `apiUrl "${env.apiUrl}" is not a usable http(s) gateway URL \u2014 expected something like https://supabase.example.com`
1374
+ );
1375
+ }
1376
+ return { kind: "self-hosted", apiUrl, key: env.accessToken };
1377
+ }
1378
+ if (env.projectRef && env.accessToken) {
1379
+ return { kind: "hosted", ref: env.projectRef, token: env.accessToken };
1380
+ }
1381
+ return null;
1382
+ }
1383
+ function normalizeApiUrl(raw) {
1384
+ let parsed;
1385
+ try {
1386
+ parsed = new URL(stripTrailingSlashes(raw.trim()));
1387
+ } catch {
1388
+ return null;
1389
+ }
1390
+ if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
1391
+ if (parsed.username || parsed.password) return null;
1392
+ return parsed.origin;
1393
+ }
1394
+ function stripTrailingSlashes(url) {
1395
+ let end = url.length;
1396
+ while (end > 0 && url[end - 1] === "/") end--;
1397
+ return url.slice(0, end);
1398
+ }
1399
+ function normalizeGoTrueSettings(raw) {
1400
+ const out = {};
1401
+ const external = raw.external;
1402
+ if (external && typeof external === "object" && !Array.isArray(external)) {
1403
+ for (const [provider, enabled] of Object.entries(external)) {
1404
+ out[`EXTERNAL_${provider.toUpperCase()}_ENABLED`] = enabled;
1405
+ }
1406
+ }
1407
+ for (const [key, value] of Object.entries(raw)) {
1408
+ if (key === "external") continue;
1409
+ out[key.toUpperCase()] = value;
1410
+ }
1411
+ return out;
1412
+ }
1413
+ var CRITICAL_KEYS = /* @__PURE__ */ new Set([
1414
+ "external_email_enabled",
1415
+ "external_phone_enabled",
1416
+ "jwt_exp",
1417
+ "security_captcha_enabled",
1418
+ "security_update_password_require_reauthentication",
1419
+ "disable_signup"
1420
+ ]);
1421
+ var CRITICAL_PATTERN = /^mfa_[a-z_]+_(enroll|verify)_enabled$/;
1422
+ var SECRET_PATTERN = /(_secret|_secrets|_pass|_auth_token|_api_key|_access_key)$/;
1423
+ var ENVIRONMENT_PATTERNS = [
1424
+ /^(site_url|uri_allow_list|saml_external_url)$/,
1425
+ /^external_[a-z0-9_]+_(client_id|url)$/,
1426
+ /^nimbus_oauth_client_id$/,
1427
+ /^hook_[a-z_]+_uri$/,
1428
+ /^smtp_(host|port|user|admin_email|sender_name)$/,
1429
+ /^sms_[a-z]+_(account_sid|message_service_sid|content_sid|originator|sender|from)$/,
1430
+ /^sms_twilio_verify_(account_sid|message_service_sid)$/,
1431
+ /^sms_test_otp(_valid_until)?$/,
1432
+ /^webauthn_rp_(id|origins|display_name)$/
1433
+ ];
1434
+ function classifyAuthKey(key) {
1435
+ const k = key.toLowerCase();
1436
+ if (SECRET_PATTERN.test(k)) return "secret";
1437
+ if (ENVIRONMENT_PATTERNS.some((p) => p.test(k))) return "environment";
1438
+ return "shared";
1439
+ }
1440
+ function isCriticalAuthKey(key) {
1441
+ const k = key.toLowerCase();
1442
+ return CRITICAL_KEYS.has(k) || CRITICAL_PATTERN.test(k);
1443
+ }
1444
+ var AuthCheck = class extends Check {
1445
+ constructor(fetchFn = globalThis.fetch.bind(globalThis)) {
1446
+ super();
1447
+ this.fetchFn = fetchFn;
1448
+ }
1449
+ name = "auth";
1450
+ async scan(ctx) {
1451
+ const sourceSrc = resolveAuthSource(ctx.source);
1452
+ const targetSrc = resolveAuthSource(ctx.target);
1453
+ if (!sourceSrc || !targetSrc) {
1454
+ throw new CheckSkipped("no apiUrl/projectRef or accessToken configured");
1455
+ }
1456
+ if (sourceSrc.kind !== targetSrc.kind) {
1457
+ throw new CheckSkipped(
1458
+ "source and target are different deployment kinds (one self-hosted, one hosted) \u2014 auth config is not comparable"
1459
+ );
1460
+ }
1461
+ const [source, target] = await Promise.all([
1462
+ this.fetchAuthConfig(sourceSrc),
1463
+ this.fetchAuthConfig(targetSrc)
1464
+ ]);
1465
+ return diffAuthConfig(source, target, targetSrc);
1466
+ }
1467
+ async fetchAuthConfig(src) {
1468
+ return src.kind === "hosted" ? this.fetchHostedAuthConfig(src.ref, src.token) : this.fetchSelfHostedAuthConfig(src.apiUrl, src.key);
1469
+ }
1470
+ async fetchHostedAuthConfig(projectRef, accessToken) {
1471
+ const url = `${SUPABASE_MGMT_API}/${encodeURIComponent(projectRef)}/config/auth`;
1472
+ const res = await this.fetchFn(url, {
1473
+ headers: { Authorization: `Bearer ${accessToken}` }
1474
+ });
1475
+ if (!res.ok) throw new Error(`Failed to fetch auth config for ${projectRef}: ${res.statusText}`);
1476
+ return res.json();
1477
+ }
1478
+ /**
1479
+ * GoTrue wants the service-role key in both `apikey` and `Authorization`.
1480
+ * The gateway routes on the former and GoTrue authorises on the latter.
1481
+ */
1482
+ async fetchSelfHostedAuthConfig(apiUrl, serviceKey) {
1483
+ const url = new URL(AUTH_SETTINGS_PATH, apiUrl).toString();
1484
+ const res = await this.fetchFn(url, {
1485
+ headers: { apikey: serviceKey, Authorization: `Bearer ${serviceKey}` }
1486
+ });
1487
+ if (!res.ok) throw new Error(`Failed to fetch auth settings from ${apiUrl}: ${res.statusText}`);
1488
+ const raw = await res.json();
1489
+ return normalizeGoTrueSettings(raw);
1490
+ }
1491
+ };
1492
+ function diffAuthConfig(source, target, targetSrc) {
1493
+ const issues = [];
1494
+ const allKeys = /* @__PURE__ */ new Set([...Object.keys(source), ...Object.keys(target)]);
1495
+ for (const key of allKeys) {
1496
+ const sv = source[key];
1497
+ const tv = target[key];
1498
+ if (JSON.stringify(sv) === JSON.stringify(tv)) continue;
1499
+ const kind = classifyAuthKey(key);
1500
+ const base2 = {
1501
+ id: `auth-${key.toLowerCase()}`,
1502
+ check: "auth",
1503
+ severity: isCriticalAuthKey(key) ? "critical" : "info",
1504
+ title: `Auth config mismatch: ${key}`
1505
+ };
1506
+ if (kind === "secret") {
1507
+ issues.push({
1508
+ ...base2,
1509
+ description: `"${key}" differs between source and target. It is a secret: set it on the target directly.`,
1510
+ manualOnly: `"${key}" is a secret and is never copied. Set it on the target directly.`
1511
+ });
1512
+ continue;
1513
+ }
1514
+ const action = targetSrc.kind === "hosted" && kind === "shared" ? {
1515
+ method: "PATCH",
1516
+ url: `${SUPABASE_MGMT_API}/${encodeURIComponent(targetSrc.ref)}/config/auth`,
1517
+ headers: { Authorization: `Bearer ${targetSrc.token}` },
1518
+ body: { [key]: sv },
1519
+ label: `Set auth config "${key}" to ${JSON.stringify(sv)} in target`
1520
+ } : void 0;
1521
+ const manualOnly = kind === "environment" ? `"${key}" belongs to each environment and is not copied. Change it on the target if it is wrong there.` : action ? void 0 : "Self-hosted GoTrue is configured through its environment \u2014 update the target deployment and restart it.";
1522
+ issues.push({
1523
+ ...base2,
1524
+ description: `"${key}" differs between source (${JSON.stringify(sv)}) and target (${JSON.stringify(tv)}).` + (manualOnly ? ` ${manualOnly}` : ""),
1525
+ sourceValue: sv,
1526
+ targetValue: tv,
1527
+ ...action ? { action } : {},
1528
+ ...manualOnly ? { manualOnly } : {}
1529
+ });
1530
+ }
1531
+ return issues;
1532
+ }
1533
+
1534
+ // src/checks/cron.ts
1535
+ var CronCheck = class extends Check {
1536
+ constructor(queryFn = pgQuery) {
1537
+ super();
1538
+ this.queryFn = queryFn;
1539
+ }
1540
+ name = "cron";
1541
+ async scan(ctx) {
1542
+ const [source, target] = await Promise.all([
1543
+ this.fetchCronJobs(ctx.source.dbUrl),
1544
+ this.fetchCronJobs(ctx.target.dbUrl)
1545
+ ]);
1546
+ if (!source.available && !target.available) {
1547
+ throw new CheckSkipped("pg_cron extension not installed");
1548
+ }
1549
+ return diffCronJobs(source.jobs, target.jobs);
1550
+ }
1551
+ async fetchCronJobs(dbUrl) {
1552
+ return readOrAbsent(
1553
+ async () => ({ jobs: await this.queryFn(dbUrl, CRON_SQL), available: true }),
1554
+ { jobs: [], available: false }
1555
+ );
1556
+ }
1557
+ };
1558
+ var CRON_SQL = `
1559
+ SELECT jobid, schedule, command, nodename, nodeport, database, username, active, jobname
1560
+ FROM cron.job
1561
+ ORDER BY jobname, jobid
1562
+ `;
1563
+ function jobKey(j) {
1564
+ return j.jobname ?? `job-${j.jobid}`;
1565
+ }
1566
+ function diffCronJobs(source, target) {
1567
+ const issues = [];
1568
+ const sourceMap = new Map(source.map((j) => [jobKey(j), j]));
1569
+ const targetMap = new Map(target.map((j) => [jobKey(j), j]));
1570
+ for (const [key, j] of sourceMap) {
1571
+ if (!targetMap.has(key)) {
1572
+ issues.push({
1573
+ id: `cron-missing-${key}`,
1574
+ check: "cron",
1575
+ severity: "warning",
1576
+ title: `Missing cron job: ${key}`,
1577
+ description: `Cron job "${key}" (schedule: ${j.schedule}) exists in source but not in target.`,
1578
+ sourceValue: j,
1579
+ sql: {
1580
+ up: `SELECT cron.schedule('${key}', '${j.schedule}', $$${j.command}$$);`,
1581
+ down: `SELECT cron.unschedule('${key}');`
1582
+ }
1583
+ });
1584
+ }
1585
+ }
1586
+ for (const [key, j] of targetMap) {
1587
+ if (!sourceMap.has(key)) {
1588
+ issues.push({
1589
+ id: `cron-extra-${key}`,
1590
+ check: "cron",
1591
+ severity: "info",
1592
+ title: `Extra cron job: ${key}`,
1593
+ description: `Cron job "${key}" exists in target but not in source.`,
1594
+ targetValue: j
1595
+ });
1596
+ }
1597
+ }
1598
+ for (const [key, sj] of sourceMap) {
1599
+ const tj = targetMap.get(key);
1600
+ if (!tj) continue;
1601
+ if (sj.schedule !== tj.schedule || sj.command !== tj.command) {
1602
+ issues.push({
1603
+ id: `cron-modified-${key}`,
1604
+ check: "cron",
1605
+ severity: "warning",
1606
+ title: `Modified cron job: ${key}`,
1607
+ description: `Cron job "${key}" has different schedule or command between environments.`,
1608
+ sourceValue: sj,
1609
+ targetValue: tj,
1610
+ sql: {
1611
+ up: `SELECT cron.unschedule('${key}');
1612
+ SELECT cron.schedule('${key}', '${sj.schedule}', $$${sj.command.trim()}$$);`,
1613
+ down: `SELECT cron.unschedule('${key}');
1614
+ SELECT cron.schedule('${key}', '${tj.schedule}', $$${tj.command.trim()}$$);`
1615
+ }
1616
+ });
1617
+ }
1618
+ if (sj.active !== tj.active) {
1619
+ issues.push({
1620
+ id: `cron-active-${key}`,
1621
+ check: "cron",
1622
+ severity: "warning",
1623
+ title: `Cron job active state mismatch: ${key}`,
1624
+ description: `Cron job "${key}" is ${sj.active ? "active" : "inactive"} in source but ${tj.active ? "active" : "inactive"} in target.`,
1625
+ sourceValue: { active: sj.active },
1626
+ targetValue: { active: tj.active },
1627
+ sql: {
1628
+ up: `UPDATE cron.job SET active = ${sj.active} WHERE jobname = '${key}';`,
1629
+ down: `UPDATE cron.job SET active = ${tj.active} WHERE jobname = '${key}';`
1630
+ }
1631
+ });
1632
+ }
1633
+ }
1634
+ return issues;
1635
+ }
1636
+
1637
+ // src/checksum.ts
1638
+ async function getTableFingerprint(dbUrl, table, queryFn = pgQuery) {
1639
+ const sql = `
1640
+ SELECT count(*)::int AS row_count,
1641
+ coalesce(sum(('x' || substr(d, 1, 16))::bit(64)::bigint::numeric), 0)::text
1642
+ || ':' ||
1643
+ coalesce(sum(('x' || substr(d, 17, 16))::bit(64)::bigint::numeric), 0)::text AS content
1644
+ FROM (SELECT md5(t::text) AS d FROM ${quoteIdent(table)} t) s
1645
+ `;
1646
+ const [row] = await queryFn(dbUrl, sql);
1647
+ return {
1648
+ table,
1649
+ rowCount: row.row_count,
1650
+ content: row.content
1651
+ };
1652
+ }
1653
+ async function tablesMatch(sourceUrl, targetUrl, table, queryFn = pgQuery) {
1654
+ const [source, target] = await Promise.all([
1655
+ getTableFingerprint(sourceUrl, table, queryFn),
1656
+ getTableFingerprint(targetUrl, table, queryFn)
1657
+ ]);
1658
+ return source.rowCount === target.rowCount && source.content === target.content;
1659
+ }
1660
+ async function filterChangedTables(sourceUrl, targetUrl, tables, queryFn = pgQuery) {
1661
+ const changed = [];
1662
+ const skipped = [];
1663
+ const results = await Promise.all(
1664
+ tables.map(async (table) => {
1665
+ try {
1666
+ const match = await tablesMatch(sourceUrl, targetUrl, table, queryFn);
1667
+ return { table, match };
1668
+ } catch {
1669
+ return { table, match: false };
1670
+ }
1671
+ })
1672
+ );
1673
+ for (const { table, match } of results) {
1674
+ if (match) {
1675
+ skipped.push(table);
1676
+ } else {
1677
+ changed.push(table);
1678
+ }
1679
+ }
1680
+ return { changed, skipped };
1681
+ }
1682
+
1683
+ // src/checks/data.ts
1684
+ var DataCheck = class extends Check {
1685
+ constructor(runFn = runDbDiff, queryFn = pgQuery) {
1686
+ super();
1687
+ this.runFn = runFn;
1688
+ this.queryFn = queryFn;
1689
+ }
1690
+ name = "data";
1691
+ async scan(ctx) {
1692
+ const configured = ctx.config.checks?.data?.tables;
1693
+ if (!configured?.length) throw new CheckSkipped("no tables configured in checks.data.tables");
1694
+ const tables = applyTableFilter(configured, ctx.tableFilter);
1695
+ if (tables.length === 0) {
1696
+ throw new CheckSkipped("no configured data tables match the --tables / --exclude-tables filter");
1697
+ }
1698
+ const { changed } = await filterChangedTables(
1699
+ ctx.source.dbUrl,
1700
+ ctx.target.dbUrl,
1701
+ tables,
1702
+ this.queryFn
1703
+ );
1704
+ if (changed.length === 0) return [];
1705
+ try {
1706
+ const result = await this.runFn({
1707
+ sourceUrl: ctx.source.dbUrl,
1708
+ targetUrl: ctx.target.dbUrl,
1709
+ type: "data",
1710
+ include: "both",
1711
+ tables: changed,
1712
+ timeoutSeconds: ctx.target?.checks?.schema?.timeout
1713
+ });
1714
+ return sqlToIssues(result, "data");
1715
+ } catch (err) {
1716
+ if (err instanceof Error && err.message.includes("@dbdiff/cli is not installed")) {
1717
+ return [];
1718
+ }
1719
+ throw err;
1720
+ }
1721
+ }
1722
+ };
1723
+
1724
+ // src/checks/webhooks.ts
1725
+ function keyOf(entry) {
1726
+ return `${entry.table_name}.${entry.name}`;
1727
+ }
1728
+ var WebhooksCheck = class extends Check {
1729
+ constructor(queryFn = pgQuery) {
1730
+ super();
1731
+ this.queryFn = queryFn;
1732
+ }
1733
+ name = "webhooks";
1734
+ async scan(ctx) {
1735
+ const [sourceHooks, targetHooks, sourceNet, targetNet] = await Promise.all([
1736
+ this.fetchHooks(ctx.source.dbUrl),
1737
+ this.fetchHooks(ctx.target.dbUrl),
1738
+ this.checkPgNet(ctx.source.dbUrl),
1739
+ this.checkPgNet(ctx.target.dbUrl)
1740
+ ]);
1741
+ const issues = [];
1742
+ if (sourceNet && !targetNet) {
1743
+ issues.push({
1744
+ id: "webhooks-pgnet-missing",
1745
+ check: "webhooks",
1746
+ severity: "critical",
1747
+ title: "pg_net extension missing in target",
1748
+ description: "The pg_net extension is enabled in source but not in target. Database webhooks will silently fail.",
1749
+ sql: {
1750
+ up: "CREATE EXTENSION IF NOT EXISTS pg_net;",
1751
+ down: "DROP EXTENSION IF EXISTS pg_net;"
1752
+ }
1753
+ });
1754
+ }
1755
+ issues.push(...diffHooks(sourceHooks, targetHooks));
1756
+ return issues;
1757
+ }
1758
+ async fetchHooks(dbUrl) {
1759
+ return readOrAbsent(async () => await this.queryFn(dbUrl, HOOKS_SQL), []);
1760
+ }
1761
+ async checkPgNet(dbUrl) {
1762
+ return readOrAbsent(async () => (await this.queryFn(dbUrl, PG_NET_CHECK_SQL)).length > 0, false);
1763
+ }
1764
+ };
1765
+ var HOOKS_SQL = `
1766
+ SELECT n.nspname || '.' || c.relname AS table_name,
1767
+ format('%I.%I', n.nspname, c.relname) AS table_ref,
1768
+ t.tgname AS name,
1769
+ pg_get_triggerdef(t.oid) AS definition
1770
+ FROM pg_trigger t
1771
+ JOIN pg_class c ON c.oid = t.tgrelid
1772
+ JOIN pg_namespace n ON n.oid = c.relnamespace
1773
+ JOIN pg_proc p ON p.oid = t.tgfoid
1774
+ JOIN pg_namespace pn ON pn.oid = p.pronamespace
1775
+ WHERE NOT t.tgisinternal
1776
+ AND pn.nspname = 'supabase_functions'
1777
+ AND p.proname = 'http_request'
1778
+ ORDER BY 1, 2
1779
+ `;
1780
+ var PG_NET_CHECK_SQL = `
1781
+ SELECT 1 FROM pg_extension WHERE extname = 'pg_net'
1782
+ `;
1783
+ function dropStatement(entry) {
1784
+ return `DROP TRIGGER IF EXISTS ${quoteName(entry.name)} ON ${entry.table_ref ?? entry.table_name};`;
1785
+ }
1786
+ function createStatement(entry) {
1787
+ return `${entry.definition.replace(/;\s*$/, "")};`;
1788
+ }
1789
+ function diffHooks(source, target) {
1790
+ const issues = [];
1791
+ const sourceMap = new Map(source.map((h) => [keyOf(h), h]));
1792
+ const targetMap = new Map(target.map((h) => [keyOf(h), h]));
1793
+ for (const [key, h] of sourceMap) {
1794
+ if (targetMap.has(key)) continue;
1795
+ issues.push({
1796
+ id: `webhooks-missing-${key}`,
1797
+ check: "webhooks",
1798
+ severity: "warning",
1799
+ title: `Missing webhook: ${h.name} on ${h.table_name}`,
1800
+ description: `Webhook "${h.name}" on ${h.table_name} exists in source but not in target.`,
1801
+ sourceValue: h,
1802
+ sql: {
1803
+ up: createStatement(h),
1804
+ down: dropStatement(h)
1805
+ }
1806
+ });
1807
+ }
1808
+ for (const [key, h] of targetMap) {
1809
+ if (sourceMap.has(key)) continue;
1810
+ issues.push({
1811
+ id: `webhooks-extra-${key}`,
1812
+ check: "webhooks",
1813
+ severity: "info",
1814
+ title: `Extra webhook: ${h.name} on ${h.table_name}`,
1815
+ description: `Webhook "${h.name}" on ${h.table_name} exists in target but not in source.`,
1816
+ targetValue: h,
1817
+ // Removing one stops the target calling out, which nobody may notice
1818
+ // until something downstream goes quiet.
1819
+ destructive: "removes a webhook",
1820
+ sql: {
1821
+ up: dropStatement(h),
1822
+ // Recoverable, unlike before: the target's own definition is the way back.
1823
+ down: createStatement(h)
1824
+ }
1825
+ });
1826
+ }
1827
+ for (const [key, sh] of sourceMap) {
1828
+ const th = targetMap.get(key);
1829
+ if (!th || normalise(sh.definition) === normalise(th.definition)) continue;
1830
+ issues.push({
1831
+ id: `webhooks-modified-${key}`,
1832
+ check: "webhooks",
1833
+ severity: "warning",
1834
+ title: `Modified webhook: ${sh.name} on ${sh.table_name}`,
1835
+ description: `Webhook "${sh.name}" on ${sh.table_name} is configured differently in source and target.`,
1836
+ sourceValue: sh,
1837
+ targetValue: th,
1838
+ sql: {
1839
+ up: [dropStatement(th), createStatement(sh)].join("\n"),
1840
+ down: [dropStatement(sh), createStatement(th)].join("\n")
1841
+ }
1842
+ });
1843
+ }
1844
+ return issues;
1845
+ }
1846
+ function normalise(definition) {
1847
+ return definition.replace(/\s+/g, " ").trim();
1848
+ }
1849
+
1850
+ // src/checks/vault.ts
1851
+ var STRUCTURAL_ATTRS = ["name", "description", "unique_name"];
1852
+ var ENV_SPECIFIC_ATTRS = ["secret", "nonce", "key_id"];
1853
+ var VaultCheck = class extends Check {
1854
+ constructor(queryFn = pgQuery) {
1855
+ super();
1856
+ this.queryFn = queryFn;
1857
+ }
1858
+ name = "vault";
1859
+ async scan(ctx) {
1860
+ const [source, target] = await Promise.all([
1861
+ this.fetchSecrets(ctx.source.dbUrl),
1862
+ this.fetchSecrets(ctx.target.dbUrl)
1863
+ ]);
1864
+ return diffVaultSecrets(source, target);
1865
+ }
1866
+ async fetchSecrets(dbUrl) {
1867
+ return readOrAbsent(async () => {
1868
+ try {
1869
+ return await this.queryFn(dbUrl, VAULT_SQL);
1870
+ } catch (err) {
1871
+ if (err.code !== "42703") throw err;
1872
+ const rows = await this.queryFn(dbUrl, VAULT_SQL_FALLBACK);
1873
+ return rows.map((r) => ({ ...r, unique_name: null }));
1874
+ }
1875
+ }, []);
1876
+ }
1877
+ };
1878
+ var VAULT_SQL = `
1879
+ SELECT id, name, description, secret, unique_name, nonce, key_id,
1880
+ created_at::text, updated_at::text
1881
+ FROM vault.secrets
1882
+ ORDER BY name, id
1883
+ `;
1884
+ var VAULT_SQL_FALLBACK = `
1885
+ SELECT id, name, description, secret, nonce, key_id,
1886
+ created_at::text, updated_at::text
1887
+ FROM vault.secrets
1888
+ ORDER BY name, id
1889
+ `;
1890
+ function secretKey(s) {
1891
+ return s.unique_name ?? s.name ?? s.id;
1892
+ }
1893
+ function diffVaultSecrets(source, target) {
1894
+ const issues = [];
1895
+ const sourceMap = new Map(source.map((s) => [secretKey(s), s]));
1896
+ const targetMap = new Map(target.map((s) => [secretKey(s), s]));
1897
+ for (const [key, s] of sourceMap) {
1898
+ if (!targetMap.has(key)) {
1899
+ issues.push({
1900
+ id: `vault-missing-${key}`,
1901
+ check: "vault",
1902
+ severity: "warning",
1903
+ title: `Missing vault secret: ${key}`,
1904
+ description: `Secret "${key}" exists in source but not in target. The secret value cannot be auto-synced \u2014 it must be recreated manually in the target environment.`,
1905
+ sourceValue: { name: s.name, description: s.description, unique_name: s.unique_name },
1906
+ // No `sql`. The value exists only in the source and Vault will not give
1907
+ // it up, so there is nothing to generate — and what was generated was
1908
+ // `vault.create_secret('PLACEHOLDER_VALUE', …)`, which `--apply` ran.
1909
+ // The target then held a live secret with a bogus value, so anything
1910
+ // reading it failed at runtime instead of failing loudly as absent; and
1911
+ // because the secret now existed, the next diff stopped asking for the
1912
+ // manual step at all (issue #91).
1913
+ manualOnly: `the secret value exists only in the source and cannot be read out of Vault. Create it in the target with the real value: SELECT vault.create_secret('<value>', ${quoteLiteral(s.unique_name ?? s.name)}${s.description ? `, ${quoteLiteral(s.description)}` : ""});`
1914
+ });
1915
+ }
1916
+ }
1917
+ for (const [key] of targetMap) {
1918
+ if (!sourceMap.has(key)) {
1919
+ issues.push({
1920
+ id: `vault-extra-${key}`,
1921
+ check: "vault",
1922
+ severity: "info",
1923
+ title: `Extra vault secret: ${key}`,
1924
+ description: `Secret "${key}" exists in target but not in source.`
1925
+ });
1926
+ }
1927
+ }
1928
+ for (const [key, ss] of sourceMap) {
1929
+ const ts = targetMap.get(key);
1930
+ if (!ts) continue;
1931
+ const diffs = [];
1932
+ for (const attr of STRUCTURAL_ATTRS) {
1933
+ if (String(ss[attr] ?? "") !== String(ts[attr] ?? "")) {
1934
+ diffs.push(`${attr}: "${ss[attr] ?? ""}" \u2192 "${ts[attr] ?? ""}"`);
1935
+ }
1936
+ }
1937
+ for (const attr of ENV_SPECIFIC_ATTRS) {
1938
+ if (String(ss[attr] ?? "") !== String(ts[attr] ?? "")) {
1939
+ diffs.push(`${attr}: differs (environment-specific)`);
1940
+ }
1941
+ }
1942
+ if (diffs.length > 0) {
1943
+ const hasStructuralDiff = STRUCTURAL_ATTRS.some(
1944
+ (attr) => String(ss[attr] ?? "") !== String(ts[attr] ?? "")
1945
+ );
1946
+ issues.push({
1947
+ id: `vault-modified-${key}`,
1948
+ check: "vault",
1949
+ severity: hasStructuralDiff ? "warning" : "info",
1950
+ title: `Modified vault secret: ${key}`,
1951
+ description: `Secret "${key}" differs between environments:
1952
+ ${diffs.join("\n")}`,
1953
+ sourceValue: { name: ss.name, description: ss.description, unique_name: ss.unique_name },
1954
+ targetValue: { name: ts.name, description: ts.description, unique_name: ts.unique_name },
1955
+ sql: hasStructuralDiff ? {
1956
+ up: `SELECT vault.update_secret('${ts.id}'${ss.unique_name !== ts.unique_name ? `, NULL, ${quoteLiteral(ss.unique_name ?? "")}` : ""}${ss.description !== ts.description ? `, NULL, NULL, ${quoteLiteral(ss.description ?? "")}` : ""});`,
1957
+ down: `SELECT vault.update_secret('${ts.id}'${ts.unique_name !== ss.unique_name ? `, NULL, ${quoteLiteral(ts.unique_name ?? "")}` : ""}${ts.description !== ss.description ? `, NULL, NULL, ${quoteLiteral(ts.description ?? "")}` : ""});`
1958
+ } : void 0
1959
+ });
1960
+ }
1961
+ }
1962
+ return issues;
1963
+ }
1964
+
1965
+ // src/checks/extensions.ts
1966
+ var ExtensionsCheck = class extends Check {
1967
+ constructor(queryFn = pgQuery) {
1968
+ super();
1969
+ this.queryFn = queryFn;
1970
+ }
1971
+ name = "extensions";
1972
+ async scan(ctx) {
1973
+ const [source, target] = await Promise.all([
1974
+ this.fetchExtensions(ctx.source.dbUrl),
1975
+ this.fetchExtensions(ctx.target.dbUrl)
1976
+ ]);
1977
+ return diffExtensions(source, target);
1978
+ }
1979
+ async fetchExtensions(dbUrl) {
1980
+ return await this.queryFn(dbUrl, EXTENSIONS_SQL);
1981
+ }
1982
+ };
1983
+ var EXTENSIONS_SQL = `
1984
+ SELECT e.extname AS name,
1985
+ e.extversion AS version,
1986
+ n.nspname AS schema
1987
+ FROM pg_extension e
1988
+ JOIN pg_namespace n ON n.oid = e.extnamespace
1989
+ ORDER BY e.extname
1990
+ `;
1991
+ function diffExtensions(source, target) {
1992
+ const issues = [];
1993
+ const sourceMap = new Map(source.map((e) => [e.name, e]));
1994
+ const targetMap = new Map(target.map((e) => [e.name, e]));
1995
+ for (const [name, ext] of sourceMap) {
1996
+ if (!targetMap.has(name)) {
1997
+ issues.push({
1998
+ id: `ext-missing-${name}`,
1999
+ check: "extensions",
2000
+ severity: "warning",
2001
+ title: `Missing extension: ${name}`,
2002
+ description: `Extension "${name}" (v${ext.version}) is enabled in source (schema: ${ext.schema}) but not in target.`,
2003
+ sourceValue: ext,
2004
+ sql: {
2005
+ up: `CREATE EXTENSION IF NOT EXISTS ${quoteName(name)}${ext.schema !== "public" ? ` SCHEMA ${quoteName(ext.schema)}` : ""};`,
2006
+ down: `DROP EXTENSION IF EXISTS ${quoteName(name)};`
2007
+ }
2008
+ });
2009
+ }
2010
+ }
2011
+ for (const [name, ext] of targetMap) {
2012
+ if (!sourceMap.has(name)) {
2013
+ issues.push({
2014
+ id: `ext-extra-${name}`,
2015
+ check: "extensions",
2016
+ severity: "info",
2017
+ title: `Extra extension: ${name}`,
2018
+ description: `Extension "${name}" (v${ext.version}) is enabled in target (schema: ${ext.schema}) but not in source.`,
2019
+ targetValue: ext
2020
+ });
2021
+ }
2022
+ }
2023
+ for (const [name, srcExt] of sourceMap) {
2024
+ const tgtExt = targetMap.get(name);
2025
+ if (!tgtExt) continue;
2026
+ if (srcExt.version !== tgtExt.version) {
2027
+ issues.push({
2028
+ id: `ext-version-${name}`,
2029
+ check: "extensions",
2030
+ severity: "info",
2031
+ title: `Extension version mismatch: ${name}`,
2032
+ description: `Extension "${name}" is v${srcExt.version} in source but v${tgtExt.version} in target.`,
2033
+ sourceValue: srcExt,
2034
+ targetValue: tgtExt,
2035
+ sql: {
2036
+ up: `ALTER EXTENSION ${quoteName(name)} UPDATE TO ${quoteLiteral(srcExt.version)};`,
2037
+ down: `ALTER EXTENSION ${quoteName(name)} UPDATE TO ${quoteLiteral(tgtExt.version)};`
2038
+ }
2039
+ });
2040
+ }
2041
+ }
2042
+ return issues;
2043
+ }
2044
+
2045
+ // src/checks/index.ts
2046
+ function createDefaultRegistry(options = {}) {
2047
+ const registry = new CheckRegistry();
2048
+ registry.register(new SchemaCheck());
2049
+ registry.register(new RlsCheck());
2050
+ registry.register(new RlsCoverageCheck());
2051
+ registry.register(new EdgeFunctionsCheck());
2052
+ registry.register(new StorageCheck(void 0, options.includeFiles ?? false));
2053
+ registry.register(new AuthCheck());
2054
+ registry.register(new CronCheck());
2055
+ registry.register(new DataCheck());
2056
+ registry.register(new WebhooksCheck());
2057
+ registry.register(new RealtimeCheck());
2058
+ registry.register(new VaultCheck());
2059
+ registry.register(new ExtensionsCheck());
2060
+ registry.register(new MigrationsCheck());
2061
+ registry.register(new RolesCheck());
2062
+ return registry;
2063
+ }
2064
+
2065
+ export {
2066
+ summarize,
2067
+ summarizeByKind,
2068
+ computeScore,
2069
+ scan,
2070
+ CheckRegistry,
2071
+ createDefaultRegistry
2072
+ };
2073
+ //# sourceMappingURL=chunk-3HGAV5CC.js.map