@akal/supaforge 0.0.0-stage → 0.0.31
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/README.md +350 -2
- package/bin/dev.js +10 -0
- package/bin/run.js +18 -0
- package/dist/base-command.d.ts +134 -0
- package/dist/base-command.js +9 -0
- package/dist/base-command.js.map +1 -0
- package/dist/branch-C4ndfoj5.d.ts +58 -0
- package/dist/chunk-4OU7KO5Y.js +13 -0
- package/dist/chunk-4OU7KO5Y.js.map +1 -0
- package/dist/chunk-5QQBTLWO.js +642 -0
- package/dist/chunk-5QQBTLWO.js.map +1 -0
- package/dist/chunk-5Z3SAIQS.js +2807 -0
- package/dist/chunk-5Z3SAIQS.js.map +1 -0
- package/dist/chunk-6WAMNZLO.js +336 -0
- package/dist/chunk-6WAMNZLO.js.map +1 -0
- package/dist/chunk-BHYLBKYD.js +156 -0
- package/dist/chunk-BHYLBKYD.js.map +1 -0
- package/dist/chunk-BLKJWDTL.js +153 -0
- package/dist/chunk-BLKJWDTL.js.map +1 -0
- package/dist/chunk-DQQ5E563.js +64 -0
- package/dist/chunk-DQQ5E563.js.map +1 -0
- package/dist/chunk-G2DIPIYU.js +94 -0
- package/dist/chunk-G2DIPIYU.js.map +1 -0
- package/dist/chunk-H5MJ5DFX.js +16 -0
- package/dist/chunk-H5MJ5DFX.js.map +1 -0
- package/dist/chunk-KIFJGON5.js +248 -0
- package/dist/chunk-KIFJGON5.js.map +1 -0
- package/dist/chunk-LQXF65MC.js +240 -0
- package/dist/chunk-LQXF65MC.js.map +1 -0
- package/dist/chunk-NXRSAVRU.js +478 -0
- package/dist/chunk-NXRSAVRU.js.map +1 -0
- package/dist/chunk-PARSNTBD.js +837 -0
- package/dist/chunk-PARSNTBD.js.map +1 -0
- package/dist/chunk-RRMI5CZD.js +376 -0
- package/dist/chunk-RRMI5CZD.js.map +1 -0
- package/dist/chunk-SF3YA42C.js +506 -0
- package/dist/chunk-SF3YA42C.js.map +1 -0
- package/dist/chunk-TQJSQLWA.js +574 -0
- package/dist/chunk-TQJSQLWA.js.map +1 -0
- package/dist/chunk-VMTBLHN2.js +122 -0
- package/dist/chunk-VMTBLHN2.js.map +1 -0
- package/dist/chunk-VOXZWQ3N.js +948 -0
- package/dist/chunk-VOXZWQ3N.js.map +1 -0
- package/dist/chunk-X6V2GGDZ.js +333 -0
- package/dist/chunk-X6V2GGDZ.js.map +1 -0
- package/dist/chunk-XMYMIURR.js +552 -0
- package/dist/chunk-XMYMIURR.js.map +1 -0
- package/dist/chunk-YVDSR4GM.js +1264 -0
- package/dist/chunk-YVDSR4GM.js.map +1 -0
- package/dist/commands/clone.d.ts +66 -0
- package/dist/commands/clone.js +416 -0
- package/dist/commands/clone.js.map +1 -0
- package/dist/commands/diff.d.ts +65 -0
- package/dist/commands/diff.js +24 -0
- package/dist/commands/diff.js.map +1 -0
- package/dist/commands/help.d.ts +32 -0
- package/dist/commands/help.js +36 -0
- package/dist/commands/help.js.map +1 -0
- package/dist/commands/hukam.d.ts +13 -0
- package/dist/commands/hukam.js +29 -0
- package/dist/commands/hukam.js.map +1 -0
- package/dist/commands/init.d.ts +47 -0
- package/dist/commands/init.js +388 -0
- package/dist/commands/init.js.map +1 -0
- package/dist/commands/mcp.d.ts +13 -0
- package/dist/commands/mcp.js +44 -0
- package/dist/commands/mcp.js.map +1 -0
- package/dist/commands/migrate/baseline.d.ts +24 -0
- package/dist/commands/migrate/baseline.js +69 -0
- package/dist/commands/migrate/baseline.js.map +1 -0
- package/dist/commands/migrate/create.d.ts +36 -0
- package/dist/commands/migrate/create.js +128 -0
- package/dist/commands/migrate/create.js.map +1 -0
- package/dist/commands/migrate/list.d.ts +23 -0
- package/dist/commands/migrate/list.js +110 -0
- package/dist/commands/migrate/list.js.map +1 -0
- package/dist/commands/migrate/run.d.ts +61 -0
- package/dist/commands/migrate/run.js +19 -0
- package/dist/commands/migrate/run.js.map +1 -0
- package/dist/commands/report.d.ts +27 -0
- package/dist/commands/report.js +210 -0
- package/dist/commands/report.js.map +1 -0
- package/dist/commands/restore.d.ts +26 -0
- package/dist/commands/restore.js +268 -0
- package/dist/commands/restore.js.map +1 -0
- package/dist/commands/snapshot.d.ts +33 -0
- package/dist/commands/snapshot.js +251 -0
- package/dist/commands/snapshot.js.map +1 -0
- package/dist/commands/sync.d.ts +16 -0
- package/dist/commands/sync.js +39 -0
- package/dist/commands/sync.js.map +1 -0
- package/dist/config-CTbeRlJk.d.ts +134 -0
- package/dist/help.d.ts +28 -0
- package/dist/help.js +64 -0
- package/dist/help.js.map +1 -0
- package/dist/index.d.ts +493 -0
- package/dist/index.js +147 -0
- package/dist/index.js.map +1 -0
- package/package.json +74 -4
|
@@ -0,0 +1,2807 @@
|
|
|
1
|
+
import {
|
|
2
|
+
ABSENT_ON_TARGET,
|
|
3
|
+
EXTENSION_UNAVAILABLE,
|
|
4
|
+
UNDEFINED_COLUMN,
|
|
5
|
+
sqlState
|
|
6
|
+
} from "./chunk-H5MJ5DFX.js";
|
|
7
|
+
import {
|
|
8
|
+
destructiveReason,
|
|
9
|
+
runDbDiff,
|
|
10
|
+
sqlToIssues
|
|
11
|
+
} from "./chunk-VOXZWQ3N.js";
|
|
12
|
+
import {
|
|
13
|
+
bareName,
|
|
14
|
+
createdPolicies,
|
|
15
|
+
createdTriggers,
|
|
16
|
+
createsOnlyPolicies,
|
|
17
|
+
createsOnlyTriggers,
|
|
18
|
+
identifierMatcher,
|
|
19
|
+
orderStatements,
|
|
20
|
+
policyOnlyKeys,
|
|
21
|
+
referencedTables,
|
|
22
|
+
sqlSkeleton
|
|
23
|
+
} from "./chunk-RRMI5CZD.js";
|
|
24
|
+
import {
|
|
25
|
+
isCommentOnly,
|
|
26
|
+
splitSqlStatements
|
|
27
|
+
} from "./chunk-G2DIPIYU.js";
|
|
28
|
+
import {
|
|
29
|
+
RealtimeCheck,
|
|
30
|
+
createPolicySql,
|
|
31
|
+
defaultCanonicalizer,
|
|
32
|
+
diffSchemaPolicies,
|
|
33
|
+
dropEquivalentPolicyChanges,
|
|
34
|
+
dropPolicySql,
|
|
35
|
+
schemaPolicySql
|
|
36
|
+
} from "./chunk-YVDSR4GM.js";
|
|
37
|
+
import {
|
|
38
|
+
globToRegExp,
|
|
39
|
+
matchesGlob,
|
|
40
|
+
parseFlagList
|
|
41
|
+
} from "./chunk-DQQ5E563.js";
|
|
42
|
+
import {
|
|
43
|
+
Check,
|
|
44
|
+
CheckSkipped,
|
|
45
|
+
MigrationsCheck,
|
|
46
|
+
errMsg,
|
|
47
|
+
friendlyDbError,
|
|
48
|
+
isCheckSkipped,
|
|
49
|
+
pgClientConfig,
|
|
50
|
+
pgQuery,
|
|
51
|
+
quoteIdent,
|
|
52
|
+
quoteLiteral,
|
|
53
|
+
quoteName,
|
|
54
|
+
sqlLiteral
|
|
55
|
+
} from "./chunk-X6V2GGDZ.js";
|
|
56
|
+
import {
|
|
57
|
+
DEFAULT_IGNORE_SCHEMAS,
|
|
58
|
+
SCORE_MAX,
|
|
59
|
+
SCORE_PENALTY_CRITICAL,
|
|
60
|
+
SCORE_PENALTY_ERROR,
|
|
61
|
+
SCORE_PENALTY_INFO,
|
|
62
|
+
SCORE_PENALTY_WARNING,
|
|
63
|
+
STORAGE_LIST_LIMIT,
|
|
64
|
+
SUPABASE_MGMT_API,
|
|
65
|
+
SUPABASE_PLATFORM_SCHEMAS
|
|
66
|
+
} from "./chunk-6WAMNZLO.js";
|
|
67
|
+
|
|
68
|
+
// src/utils/table-filter.ts
|
|
69
|
+
var parseTableList = parseFlagList;
|
|
70
|
+
function resolveTableFilter(config, cli = {}) {
|
|
71
|
+
const cliTables = parseTableList(cli.tables);
|
|
72
|
+
const cliExclude = parseTableList(cli.excludeTables);
|
|
73
|
+
const configTables = Array.isArray(config?.checks?.tables) ? config.checks.tables : [];
|
|
74
|
+
const configExclude = Array.isArray(config?.checks?.excludeTables) ? config.checks.excludeTables : [];
|
|
75
|
+
const tables = cliTables.length > 0 ? cliTables : parseTableList(configTables);
|
|
76
|
+
const excludeTables = [.../* @__PURE__ */ new Set([...parseTableList(configExclude), ...cliExclude])];
|
|
77
|
+
const filter = {};
|
|
78
|
+
if (tables.length > 0) filter.tables = tables;
|
|
79
|
+
if (excludeTables.length > 0) filter.excludeTables = excludeTables;
|
|
80
|
+
return filter;
|
|
81
|
+
}
|
|
82
|
+
function isFiltered(filter) {
|
|
83
|
+
return Boolean(filter?.tables?.length || filter?.excludeTables?.length);
|
|
84
|
+
}
|
|
85
|
+
function describeTableFilter(filter) {
|
|
86
|
+
if (!isFiltered(filter)) return null;
|
|
87
|
+
const parts = [];
|
|
88
|
+
if (filter?.tables?.length) parts.push(`only ${filter.tables.join(", ")}`);
|
|
89
|
+
if (filter?.excludeTables?.length) parts.push(`excluding ${filter.excludeTables.join(", ")}`);
|
|
90
|
+
return `Scoped to ${parts.join(", ")} \u2014 applies to the schema and data checks; other layers are unfiltered.`;
|
|
91
|
+
}
|
|
92
|
+
function matchesPattern(name, pattern) {
|
|
93
|
+
const candidates = [name.toLowerCase()];
|
|
94
|
+
const dot = name.indexOf(".");
|
|
95
|
+
if (dot !== -1) candidates.push(name.slice(dot + 1).toLowerCase());
|
|
96
|
+
const rx = globToRegExp(pattern.toLowerCase());
|
|
97
|
+
return candidates.some((c) => rx.test(c));
|
|
98
|
+
}
|
|
99
|
+
function applyTableFilter(names, filter) {
|
|
100
|
+
if (!isFiltered(filter)) return names;
|
|
101
|
+
let out = names;
|
|
102
|
+
if (filter?.tables?.length) {
|
|
103
|
+
out = out.filter((n) => filter.tables.some((p) => matchesPattern(n, p)));
|
|
104
|
+
}
|
|
105
|
+
if (filter?.excludeTables?.length) {
|
|
106
|
+
out = out.filter((n) => !filter.excludeTables.some((p) => matchesPattern(n, p)));
|
|
107
|
+
}
|
|
108
|
+
return out;
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
// src/types/drift.ts
|
|
112
|
+
var CHECK_NAMES = [
|
|
113
|
+
"schema",
|
|
114
|
+
"rls",
|
|
115
|
+
"rls-coverage",
|
|
116
|
+
"edge-functions",
|
|
117
|
+
"storage",
|
|
118
|
+
"auth",
|
|
119
|
+
"cron",
|
|
120
|
+
"data",
|
|
121
|
+
"webhooks",
|
|
122
|
+
"realtime",
|
|
123
|
+
"vault",
|
|
124
|
+
"extensions",
|
|
125
|
+
"migrations",
|
|
126
|
+
"roles"
|
|
127
|
+
];
|
|
128
|
+
var CHECK_META = {
|
|
129
|
+
"schema": { number: 1, emoji: "\u{1F5C4}\uFE0F", label: "Schema" },
|
|
130
|
+
"rls": { number: 2, emoji: "\u{1F512}", label: "RLS Policies" },
|
|
131
|
+
"rls-coverage": { number: 3, emoji: "\u{1F6E1}\uFE0F", label: "RLS Coverage" },
|
|
132
|
+
"edge-functions": { number: 4, emoji: "\u26A1", label: "Edge Functions" },
|
|
133
|
+
"storage": { number: 5, emoji: "\u{1FAA3}", label: "Storage" },
|
|
134
|
+
"auth": { number: 6, emoji: "\u{1F511}", label: "Auth Config" },
|
|
135
|
+
"cron": { number: 7, emoji: "\u23F0", label: "Cron Jobs" },
|
|
136
|
+
"data": { number: 8, emoji: "\u{1F5C3}\uFE0F", label: "Reference Data" },
|
|
137
|
+
"webhooks": { number: 9, emoji: "\u26A1\u{1F517}", label: "Webhooks" },
|
|
138
|
+
"realtime": { number: 10, emoji: "\u{1F4E1}", label: "Realtime Publications" },
|
|
139
|
+
"vault": { number: 11, emoji: "\u{1F510}", label: "Vault Secrets" },
|
|
140
|
+
"extensions": { number: 12, emoji: "\u{1F9E9}", label: "Postgres Extensions" },
|
|
141
|
+
"migrations": { number: 13, emoji: "\u{1F4CB}", label: "Migration History" },
|
|
142
|
+
"roles": { number: 14, emoji: "\u{1F464}", label: "Postgres Roles & Grants" }
|
|
143
|
+
};
|
|
144
|
+
var CHECK_KIND = {
|
|
145
|
+
"schema": "comparison",
|
|
146
|
+
"rls": "comparison",
|
|
147
|
+
"rls-coverage": "posture",
|
|
148
|
+
"edge-functions": "comparison",
|
|
149
|
+
"storage": "comparison",
|
|
150
|
+
"auth": "comparison",
|
|
151
|
+
"cron": "comparison",
|
|
152
|
+
"data": "comparison",
|
|
153
|
+
"webhooks": "comparison",
|
|
154
|
+
"realtime": "comparison",
|
|
155
|
+
"vault": "comparison",
|
|
156
|
+
"extensions": "comparison",
|
|
157
|
+
"migrations": "posture",
|
|
158
|
+
"roles": "comparison"
|
|
159
|
+
};
|
|
160
|
+
function isComparisonCheck(name) {
|
|
161
|
+
return CHECK_KIND[name] === "comparison";
|
|
162
|
+
}
|
|
163
|
+
|
|
164
|
+
// src/scoring.ts
|
|
165
|
+
function summarize(results) {
|
|
166
|
+
let total = 0;
|
|
167
|
+
let critical = 0;
|
|
168
|
+
let warning = 0;
|
|
169
|
+
let info = 0;
|
|
170
|
+
for (const r of results) {
|
|
171
|
+
for (const issue of r.issues) {
|
|
172
|
+
total++;
|
|
173
|
+
if (issue.severity === "critical") critical++;
|
|
174
|
+
else if (issue.severity === "warning") warning++;
|
|
175
|
+
else info++;
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return { total, critical, warning, info };
|
|
179
|
+
}
|
|
180
|
+
function summarizeByKind(results) {
|
|
181
|
+
return {
|
|
182
|
+
drift: summarize(results.filter((r) => isComparisonCheck(r.check))),
|
|
183
|
+
posture: summarize(results.filter((r) => !isComparisonCheck(r.check)))
|
|
184
|
+
};
|
|
185
|
+
}
|
|
186
|
+
function scoreOf(results) {
|
|
187
|
+
const { total, critical, warning } = summarize(results);
|
|
188
|
+
const errorCount = results.filter((r) => r.status === "error").length;
|
|
189
|
+
if (total === 0 && errorCount === 0) return SCORE_MAX;
|
|
190
|
+
const penalty = critical * SCORE_PENALTY_CRITICAL + warning * SCORE_PENALTY_WARNING + (total - critical - warning) * SCORE_PENALTY_INFO + errorCount * SCORE_PENALTY_ERROR;
|
|
191
|
+
return Math.max(0, SCORE_MAX - penalty);
|
|
192
|
+
}
|
|
193
|
+
function computeScore(results) {
|
|
194
|
+
return scoreOf(results.filter((r) => isComparisonCheck(r.check)));
|
|
195
|
+
}
|
|
196
|
+
function computePostureScore(results) {
|
|
197
|
+
const posture = results.filter((r) => !isComparisonCheck(r.check));
|
|
198
|
+
if (posture.length === 0) return null;
|
|
199
|
+
return scoreOf(posture);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
// src/scanner.ts
|
|
203
|
+
function resolveExcludedChecks(config) {
|
|
204
|
+
const lists = [config?.checks?.exclude, config?.environments?.[config?.target ?? ""]?.checks?.exclude];
|
|
205
|
+
const out = [];
|
|
206
|
+
for (const list of lists) {
|
|
207
|
+
if (!Array.isArray(list)) continue;
|
|
208
|
+
for (const name of list) {
|
|
209
|
+
if (typeof name === "string" && CHECK_NAMES.includes(name)) {
|
|
210
|
+
out.push(name);
|
|
211
|
+
}
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
return out;
|
|
215
|
+
}
|
|
216
|
+
function checkConcurrency() {
|
|
217
|
+
const raw = process.env.SUPAFORGE_CHECK_CONCURRENCY;
|
|
218
|
+
if (raw) {
|
|
219
|
+
const n = Number(raw);
|
|
220
|
+
if (Number.isInteger(n) && n > 0) return n;
|
|
221
|
+
}
|
|
222
|
+
return 4;
|
|
223
|
+
}
|
|
224
|
+
async function runCheck(check, ctx, name, sourceDbUrl) {
|
|
225
|
+
const start = performance.now();
|
|
226
|
+
try {
|
|
227
|
+
const issues = await check.scan(ctx);
|
|
228
|
+
return {
|
|
229
|
+
check: name,
|
|
230
|
+
status: issues.length > 0 ? "drifted" : "clean",
|
|
231
|
+
issues,
|
|
232
|
+
durationMs: Math.round(performance.now() - start)
|
|
233
|
+
};
|
|
234
|
+
} catch (err) {
|
|
235
|
+
const durationMs = Math.round(performance.now() - start);
|
|
236
|
+
if (isCheckSkipped(err)) {
|
|
237
|
+
return { check: name, status: "skipped", issues: [], skipReason: err.message, durationMs };
|
|
238
|
+
}
|
|
239
|
+
return {
|
|
240
|
+
check: name,
|
|
241
|
+
status: "error",
|
|
242
|
+
issues: [],
|
|
243
|
+
error: friendlyDbError(err, sourceDbUrl),
|
|
244
|
+
durationMs
|
|
245
|
+
};
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
async function scan(registry, options, bus) {
|
|
249
|
+
const { config } = options;
|
|
250
|
+
const skipSet = /* @__PURE__ */ new Set([...options.skip ?? [], ...resolveExcludedChecks(config)]);
|
|
251
|
+
const checksToScan = (options.checks ?? [...CHECK_NAMES]).filter((n) => !skipSet.has(n));
|
|
252
|
+
const source = config.environments[config.source];
|
|
253
|
+
const target = config.environments[config.target];
|
|
254
|
+
const tableFilter = options.tableFilter ?? resolveTableFilter(config);
|
|
255
|
+
const ctx = { source, target, config, tableFilter };
|
|
256
|
+
await bus?.emit("supaforge.scan.before", ctx);
|
|
257
|
+
const results = new Array(checksToScan.length);
|
|
258
|
+
const total = checksToScan.length;
|
|
259
|
+
let next = 0;
|
|
260
|
+
const worker = async () => {
|
|
261
|
+
for (; ; ) {
|
|
262
|
+
const i = next++;
|
|
263
|
+
if (i >= total) return;
|
|
264
|
+
const name = checksToScan[i];
|
|
265
|
+
const check = registry.get(name);
|
|
266
|
+
options.onProgress?.({ phase: "check:start", check: name, index: i, total });
|
|
267
|
+
const checkCtx = {
|
|
268
|
+
...ctx,
|
|
269
|
+
onDetail: options.onDetail ? (detail) => options.onDetail?.(name, detail) : void 0
|
|
270
|
+
};
|
|
271
|
+
if (!check) {
|
|
272
|
+
const skipReason = "not registered";
|
|
273
|
+
results[i] = { check: name, status: "skipped", issues: [], skipReason, durationMs: 0 };
|
|
274
|
+
options.onProgress?.({ phase: "check:done", check: name, index: i, total, status: "skipped", issueCount: 0, durationMs: 0, skipReason });
|
|
275
|
+
continue;
|
|
276
|
+
}
|
|
277
|
+
await bus?.emit("supaforge.check.before", { check: name });
|
|
278
|
+
const result = await runCheck(check, checkCtx, name, source.dbUrl);
|
|
279
|
+
results[i] = result;
|
|
280
|
+
options.onProgress?.({
|
|
281
|
+
phase: "check:done",
|
|
282
|
+
check: name,
|
|
283
|
+
index: i,
|
|
284
|
+
total,
|
|
285
|
+
status: result.status,
|
|
286
|
+
issueCount: result.issues.length,
|
|
287
|
+
durationMs: result.durationMs,
|
|
288
|
+
...result.skipReason ? { skipReason: result.skipReason } : {}
|
|
289
|
+
});
|
|
290
|
+
await bus?.emit("supaforge.check.after", { check: name, result });
|
|
291
|
+
}
|
|
292
|
+
};
|
|
293
|
+
await Promise.all(
|
|
294
|
+
Array.from({ length: Math.min(checkConcurrency(), total) }, () => worker())
|
|
295
|
+
);
|
|
296
|
+
foldDuplicatePolicyFindings(results);
|
|
297
|
+
foldDuplicateExtensionFindings(results);
|
|
298
|
+
const summary = summarize(results);
|
|
299
|
+
const score = computeScore(results);
|
|
300
|
+
const postureScore = computePostureScore(results);
|
|
301
|
+
const scanResult = {
|
|
302
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
|
|
303
|
+
source: config.source,
|
|
304
|
+
target: config.target,
|
|
305
|
+
checks: results,
|
|
306
|
+
score,
|
|
307
|
+
postureScore,
|
|
308
|
+
summary
|
|
309
|
+
};
|
|
310
|
+
await bus?.emit("supaforge.scan.after", scanResult);
|
|
311
|
+
return scanResult;
|
|
312
|
+
}
|
|
313
|
+
function foldDuplicatePolicyFindings(results) {
|
|
314
|
+
foldInto(results, "rls", policyOnlyKeys);
|
|
315
|
+
}
|
|
316
|
+
function foldDuplicateExtensionFindings(results) {
|
|
317
|
+
foldInto(results, "extensions", extensionOnlyKeys);
|
|
318
|
+
}
|
|
319
|
+
function extensionOnlyKeys(sql) {
|
|
320
|
+
const statements = splitSqlStatements(sql ?? "").map((s) => sqlSkeleton(s).trim()).filter(Boolean);
|
|
321
|
+
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]);
|
|
322
|
+
if (keys.length === 0 || keys.some((k) => k === void 0)) return null;
|
|
323
|
+
return [...new Set(keys.map((k) => k.replace(/^"|"$/g, "").toLowerCase()))];
|
|
324
|
+
}
|
|
325
|
+
function foldInto(results, into, keysOf) {
|
|
326
|
+
const owner = results.find((r) => r?.check === into && (r.status === "drifted" || r.status === "clean"));
|
|
327
|
+
const schema = results.find((r) => r?.check === "schema" && r.status === "drifted");
|
|
328
|
+
if (!owner || !schema) return;
|
|
329
|
+
const covered = /* @__PURE__ */ new Set();
|
|
330
|
+
for (const issue of owner.issues) {
|
|
331
|
+
for (const key of keysOf(issue.sql?.up) ?? []) covered.add(key);
|
|
332
|
+
}
|
|
333
|
+
const before = schema.issues.length;
|
|
334
|
+
schema.issues = schema.issues.filter((issue) => {
|
|
335
|
+
const keys = keysOf(issue.sql?.up);
|
|
336
|
+
return !(keys && keys.length > 0 && keys.every((k) => covered.has(k)));
|
|
337
|
+
});
|
|
338
|
+
const folded = before - schema.issues.length;
|
|
339
|
+
if (folded === 0) return;
|
|
340
|
+
schema.folded = [...schema.folded ?? [], { count: folded, into }];
|
|
341
|
+
if (schema.issues.length === 0) schema.status = "clean";
|
|
342
|
+
}
|
|
343
|
+
|
|
344
|
+
// src/checks/registry.ts
|
|
345
|
+
var CheckRegistry = class {
|
|
346
|
+
checks = /* @__PURE__ */ new Map();
|
|
347
|
+
register(check) {
|
|
348
|
+
this.checks.set(check.name, check);
|
|
349
|
+
}
|
|
350
|
+
get(name) {
|
|
351
|
+
return this.checks.get(name);
|
|
352
|
+
}
|
|
353
|
+
all() {
|
|
354
|
+
return [...this.checks.values()];
|
|
355
|
+
}
|
|
356
|
+
has(name) {
|
|
357
|
+
return this.checks.has(name);
|
|
358
|
+
}
|
|
359
|
+
};
|
|
360
|
+
|
|
361
|
+
// src/checks/schema.ts
|
|
362
|
+
var SchemaCheck = class extends Check {
|
|
363
|
+
constructor(runFn = runDbDiff, queryFn = pgQuery) {
|
|
364
|
+
super();
|
|
365
|
+
this.runFn = runFn;
|
|
366
|
+
this.queryFn = queryFn;
|
|
367
|
+
}
|
|
368
|
+
name = "schema";
|
|
369
|
+
async scan(ctx) {
|
|
370
|
+
try {
|
|
371
|
+
const ignoreSchemas = ctx.config.ignoreSchemas ?? DEFAULT_IGNORE_SCHEMAS;
|
|
372
|
+
const [result, ignoredSchemaTables] = await Promise.all([
|
|
373
|
+
this.runFn({
|
|
374
|
+
sourceUrl: ctx.source.dbUrl,
|
|
375
|
+
targetUrl: ctx.target.dbUrl,
|
|
376
|
+
type: "schema",
|
|
377
|
+
include: "both",
|
|
378
|
+
timeoutSeconds: ctx.target?.checks?.schema?.timeout,
|
|
379
|
+
onProgress: ctx.onDetail ? ({ table, tablesSeen }) => ctx.onDetail?.(`${tablesSeen} tables \xB7 ${table}`) : void 0,
|
|
380
|
+
ignoreSchemas,
|
|
381
|
+
// dbdiff takes the include/exclude lists natively, globs and all, so
|
|
382
|
+
// the scope is enforced in the diff itself rather than by discarding
|
|
383
|
+
// findings afterwards (issue #43).
|
|
384
|
+
...ctx.tableFilter?.tables?.length ? { tables: ctx.tableFilter.tables } : {},
|
|
385
|
+
...ctx.tableFilter?.excludeTables?.length ? { ignoreTables: ctx.tableFilter.excludeTables } : {}
|
|
386
|
+
}),
|
|
387
|
+
this.fetchIgnoredSchemaTables(ctx.target.dbUrl, ignoreSchemas)
|
|
388
|
+
]);
|
|
389
|
+
return sqlToIssues(result, "schema", ignoreSchemas, ignoredSchemaTables);
|
|
390
|
+
} catch (err) {
|
|
391
|
+
if (err instanceof Error && err.message.includes("@dbdiff/cli is not installed")) {
|
|
392
|
+
throw new CheckSkipped("@dbdiff/cli is not installed");
|
|
393
|
+
}
|
|
394
|
+
throw err;
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
/**
|
|
398
|
+
* Query the target DB for table names inside ignored schemas.
|
|
399
|
+
*
|
|
400
|
+
* These are used to detect unqualified FK REFERENCES like `REFERENCES "users"`
|
|
401
|
+
* where "users" lives in the ignored "auth" schema but dbdiff omitted the
|
|
402
|
+
* schema prefix (due to search_path or its own normalisation).
|
|
403
|
+
*
|
|
404
|
+
* Returns a Set of lowercase table names, bare and schema-qualified. Fails silently so that a transient
|
|
405
|
+
* DB error here never blocks the main schema diff.
|
|
406
|
+
*/
|
|
407
|
+
async fetchIgnoredSchemaTables(dbUrl, ignoreSchemas) {
|
|
408
|
+
if (ignoreSchemas.length === 0) return /* @__PURE__ */ new Set();
|
|
409
|
+
try {
|
|
410
|
+
const placeholders = ignoreSchemas.map((_, i) => `$${i + 1}`).join(", ");
|
|
411
|
+
const rows = await this.queryFn(
|
|
412
|
+
dbUrl,
|
|
413
|
+
`SELECT schemaname, tablename FROM pg_tables WHERE schemaname IN (${placeholders})`,
|
|
414
|
+
ignoreSchemas
|
|
415
|
+
);
|
|
416
|
+
return new Set(rows.flatMap((r) => [
|
|
417
|
+
String(r.tablename).toLowerCase(),
|
|
418
|
+
`${String(r.schemaname)}.${String(r.tablename)}`.toLowerCase()
|
|
419
|
+
]));
|
|
420
|
+
} catch {
|
|
421
|
+
return /* @__PURE__ */ new Set();
|
|
422
|
+
}
|
|
423
|
+
}
|
|
424
|
+
};
|
|
425
|
+
|
|
426
|
+
// src/checks/rls.ts
|
|
427
|
+
var RlsCheck = class extends Check {
|
|
428
|
+
constructor(queryFn = pgQuery) {
|
|
429
|
+
super();
|
|
430
|
+
this.queryFn = queryFn;
|
|
431
|
+
}
|
|
432
|
+
name = "rls";
|
|
433
|
+
async scan(ctx) {
|
|
434
|
+
const ignoreSchemas = ctx.config.ignoreSchemas ?? [];
|
|
435
|
+
const [sourcePolicies, targetPolicies, sourceStatus, targetStatus] = await Promise.all([
|
|
436
|
+
this.fetchPolicies(ctx.source.dbUrl, ignoreSchemas),
|
|
437
|
+
this.fetchPolicies(ctx.target.dbUrl, ignoreSchemas),
|
|
438
|
+
this.fetchTableRlsStatus(ctx.source.dbUrl, ignoreSchemas),
|
|
439
|
+
this.fetchTableRlsStatus(ctx.target.dbUrl, ignoreSchemas)
|
|
440
|
+
]);
|
|
441
|
+
return [
|
|
442
|
+
...diffRlsStatus(sourceStatus, targetStatus),
|
|
443
|
+
// The same policy restored from a dump renders differently; that is not
|
|
444
|
+
// a change (see policy-equivalence).
|
|
445
|
+
...await dropEquivalentPolicyChanges(
|
|
446
|
+
diffPolicies(sourcePolicies, targetPolicies),
|
|
447
|
+
ctx,
|
|
448
|
+
defaultCanonicalizer(this.queryFn)
|
|
449
|
+
)
|
|
450
|
+
];
|
|
451
|
+
}
|
|
452
|
+
async fetchPolicies(dbUrl, ignoreSchemas) {
|
|
453
|
+
if (ignoreSchemas.length === 0) {
|
|
454
|
+
return await this.queryFn(dbUrl, POLICY_SQL_NO_FILTER);
|
|
455
|
+
}
|
|
456
|
+
const placeholders = ignoreSchemas.map((_, i) => `$${i + 1}`).join(", ");
|
|
457
|
+
const sql = `
|
|
458
|
+
SELECT schemaname, tablename, policyname, permissive, roles, cmd, qual, with_check
|
|
459
|
+
FROM pg_policies
|
|
460
|
+
WHERE schemaname NOT IN (${placeholders})
|
|
461
|
+
ORDER BY schemaname, tablename, policyname
|
|
462
|
+
`;
|
|
463
|
+
return await this.queryFn(dbUrl, sql, ignoreSchemas);
|
|
464
|
+
}
|
|
465
|
+
async fetchTableRlsStatus(dbUrl, ignoreSchemas) {
|
|
466
|
+
if (ignoreSchemas.length === 0) {
|
|
467
|
+
return await this.queryFn(dbUrl, RLS_STATUS_SQL_NO_FILTER);
|
|
468
|
+
}
|
|
469
|
+
const placeholders = ignoreSchemas.map((_, i) => `$${i + 1}`).join(", ");
|
|
470
|
+
const sql = `
|
|
471
|
+
SELECT n.nspname AS schemaname, c.relname AS tablename, c.relrowsecurity AS rls_enabled
|
|
472
|
+
FROM pg_class c
|
|
473
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
474
|
+
WHERE c.relkind = 'r'
|
|
475
|
+
AND n.nspname NOT IN (${placeholders})
|
|
476
|
+
ORDER BY n.nspname, c.relname
|
|
477
|
+
`;
|
|
478
|
+
return await this.queryFn(dbUrl, sql, ignoreSchemas);
|
|
479
|
+
}
|
|
480
|
+
};
|
|
481
|
+
var POLICY_SQL_NO_FILTER = `
|
|
482
|
+
SELECT schemaname, tablename, policyname, permissive, roles, cmd, qual, with_check
|
|
483
|
+
FROM pg_policies
|
|
484
|
+
ORDER BY schemaname, tablename, policyname
|
|
485
|
+
`;
|
|
486
|
+
var RLS_STATUS_SQL_NO_FILTER = `
|
|
487
|
+
SELECT n.nspname AS schemaname, c.relname AS tablename, c.relrowsecurity AS rls_enabled
|
|
488
|
+
FROM pg_class c
|
|
489
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
490
|
+
WHERE c.relkind = 'r'
|
|
491
|
+
ORDER BY n.nspname, c.relname
|
|
492
|
+
`;
|
|
493
|
+
function policyKey(p) {
|
|
494
|
+
return `${p.schemaname}.${p.tablename}.${p.policyname}`;
|
|
495
|
+
}
|
|
496
|
+
function policiesEqual(a, b) {
|
|
497
|
+
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);
|
|
498
|
+
}
|
|
499
|
+
var generateCreatePolicySql = (p) => createPolicySql(p.schemaname, p);
|
|
500
|
+
var generateDropPolicySql = (p) => dropPolicySql(p.schemaname, p);
|
|
501
|
+
function diffPolicies(source, target) {
|
|
502
|
+
const issues = [];
|
|
503
|
+
const sourceMap = new Map(source.map((p) => [policyKey(p), p]));
|
|
504
|
+
const targetMap = new Map(target.map((p) => [policyKey(p), p]));
|
|
505
|
+
for (const [key, p] of sourceMap) {
|
|
506
|
+
if (!targetMap.has(key)) {
|
|
507
|
+
issues.push({
|
|
508
|
+
id: `rls-missing-${key}`,
|
|
509
|
+
check: "rls",
|
|
510
|
+
severity: "critical",
|
|
511
|
+
title: `Missing RLS policy: ${p.policyname}`,
|
|
512
|
+
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.`,
|
|
513
|
+
sourceValue: p,
|
|
514
|
+
sql: {
|
|
515
|
+
up: generateCreatePolicySql(p),
|
|
516
|
+
down: generateDropPolicySql(p)
|
|
517
|
+
}
|
|
518
|
+
});
|
|
519
|
+
}
|
|
520
|
+
}
|
|
521
|
+
for (const [key, p] of targetMap) {
|
|
522
|
+
if (!sourceMap.has(key)) {
|
|
523
|
+
issues.push({
|
|
524
|
+
id: `rls-extra-${key}`,
|
|
525
|
+
check: "rls",
|
|
526
|
+
severity: "warning",
|
|
527
|
+
title: `Extra RLS policy: ${p.policyname}`,
|
|
528
|
+
description: `Policy "${p.policyname}" on ${p.schemaname}.${p.tablename} exists in target but not in source.`,
|
|
529
|
+
targetValue: p,
|
|
530
|
+
sql: {
|
|
531
|
+
up: generateDropPolicySql(p),
|
|
532
|
+
down: generateCreatePolicySql(p)
|
|
533
|
+
}
|
|
534
|
+
});
|
|
535
|
+
}
|
|
536
|
+
}
|
|
537
|
+
for (const [key, sp] of sourceMap) {
|
|
538
|
+
const tp = targetMap.get(key);
|
|
539
|
+
if (tp && !policiesEqual(sp, tp)) {
|
|
540
|
+
issues.push({
|
|
541
|
+
id: `rls-modified-${key}`,
|
|
542
|
+
check: "rls",
|
|
543
|
+
severity: "critical",
|
|
544
|
+
title: `Modified RLS policy: ${sp.policyname}`,
|
|
545
|
+
description: `Policy "${sp.policyname}" on ${sp.schemaname}.${sp.tablename} has different USING/WITH CHECK expressions between source and target.`,
|
|
546
|
+
sourceValue: sp,
|
|
547
|
+
targetValue: tp,
|
|
548
|
+
sql: {
|
|
549
|
+
up: [generateDropPolicySql(sp), generateCreatePolicySql(sp)].join("\n"),
|
|
550
|
+
down: [generateDropPolicySql(tp), generateCreatePolicySql(tp)].join("\n")
|
|
551
|
+
}
|
|
552
|
+
});
|
|
553
|
+
}
|
|
554
|
+
}
|
|
555
|
+
return issues;
|
|
556
|
+
}
|
|
557
|
+
function diffRlsStatus(source, target) {
|
|
558
|
+
const issues = [];
|
|
559
|
+
const targetMap = new Map(target.map((t) => [`${t.schemaname}.${t.tablename}`, t]));
|
|
560
|
+
for (const src of source) {
|
|
561
|
+
const key = `${src.schemaname}.${src.tablename}`;
|
|
562
|
+
const tgt = targetMap.get(key);
|
|
563
|
+
if (!tgt) continue;
|
|
564
|
+
if (src.rls_enabled && !tgt.rls_enabled) {
|
|
565
|
+
issues.push({
|
|
566
|
+
id: `rls-disabled-${key}`,
|
|
567
|
+
check: "rls",
|
|
568
|
+
severity: "critical",
|
|
569
|
+
title: `RLS not enabled: ${src.schemaname}.${src.tablename}`,
|
|
570
|
+
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.`,
|
|
571
|
+
sourceValue: src,
|
|
572
|
+
targetValue: tgt,
|
|
573
|
+
sql: {
|
|
574
|
+
up: `ALTER TABLE ${quoteName(src.schemaname)}.${quoteName(src.tablename)} ENABLE ROW LEVEL SECURITY;`,
|
|
575
|
+
down: `ALTER TABLE ${quoteName(src.schemaname)}.${quoteName(src.tablename)} DISABLE ROW LEVEL SECURITY;`
|
|
576
|
+
}
|
|
577
|
+
});
|
|
578
|
+
} else if (!src.rls_enabled && tgt.rls_enabled) {
|
|
579
|
+
issues.push({
|
|
580
|
+
id: `rls-enabled-${key}`,
|
|
581
|
+
check: "rls",
|
|
582
|
+
severity: "warning",
|
|
583
|
+
title: `RLS enabled unexpectedly: ${src.schemaname}.${src.tablename}`,
|
|
584
|
+
description: `Row Level Security is disabled on "${src.schemaname}"."${src.tablename}" in source but enabled in target.`,
|
|
585
|
+
sourceValue: src,
|
|
586
|
+
targetValue: tgt,
|
|
587
|
+
sql: {
|
|
588
|
+
up: `ALTER TABLE ${quoteName(src.schemaname)}.${quoteName(src.tablename)} DISABLE ROW LEVEL SECURITY;`,
|
|
589
|
+
down: `ALTER TABLE ${quoteName(src.schemaname)}.${quoteName(src.tablename)} ENABLE ROW LEVEL SECURITY;`
|
|
590
|
+
}
|
|
591
|
+
});
|
|
592
|
+
}
|
|
593
|
+
}
|
|
594
|
+
return issues;
|
|
595
|
+
}
|
|
596
|
+
|
|
597
|
+
// src/checks/rls-coverage.ts
|
|
598
|
+
var TABLES_WITHOUT_RLS_SQL = `
|
|
599
|
+
SELECT n.nspname AS schemaname, c.relname AS tablename
|
|
600
|
+
FROM pg_class c
|
|
601
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
602
|
+
WHERE c.relkind = 'r'
|
|
603
|
+
AND c.relrowsecurity = false
|
|
604
|
+
ORDER BY n.nspname, c.relname
|
|
605
|
+
`;
|
|
606
|
+
var RlsCoverageCheck = class extends Check {
|
|
607
|
+
constructor(queryFn = pgQuery) {
|
|
608
|
+
super();
|
|
609
|
+
this.queryFn = queryFn;
|
|
610
|
+
}
|
|
611
|
+
name = "rls-coverage";
|
|
612
|
+
async scan(ctx) {
|
|
613
|
+
const ignoreSchemas = ctx.config.ignoreSchemas ?? [];
|
|
614
|
+
const tables = await this.fetchTablesWithoutRls(ctx.target.dbUrl, ignoreSchemas);
|
|
615
|
+
return tables.map(buildIssue);
|
|
616
|
+
}
|
|
617
|
+
async fetchTablesWithoutRls(dbUrl, ignoreSchemas) {
|
|
618
|
+
if (ignoreSchemas.length === 0) {
|
|
619
|
+
return this.queryFn(dbUrl, TABLES_WITHOUT_RLS_SQL);
|
|
620
|
+
}
|
|
621
|
+
const placeholders = ignoreSchemas.map((_, i) => `$${i + 1}`).join(", ");
|
|
622
|
+
const sql = `
|
|
623
|
+
SELECT n.nspname AS schemaname, c.relname AS tablename
|
|
624
|
+
FROM pg_class c
|
|
625
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
626
|
+
WHERE c.relkind = 'r'
|
|
627
|
+
AND c.relrowsecurity = false
|
|
628
|
+
AND n.nspname NOT IN (${placeholders})
|
|
629
|
+
ORDER BY n.nspname, c.relname
|
|
630
|
+
`;
|
|
631
|
+
return this.queryFn(dbUrl, sql, ignoreSchemas);
|
|
632
|
+
}
|
|
633
|
+
};
|
|
634
|
+
function buildIssue(t) {
|
|
635
|
+
const tableRef = `${quoteName(t.schemaname)}.${quoteName(t.tablename)}`;
|
|
636
|
+
return {
|
|
637
|
+
id: `rls-coverage-${t.schemaname}.${t.tablename}`,
|
|
638
|
+
check: "rls-coverage",
|
|
639
|
+
severity: "critical",
|
|
640
|
+
title: `RLS not enabled: ${t.schemaname}.${t.tablename}`,
|
|
641
|
+
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.`,
|
|
642
|
+
targetValue: t,
|
|
643
|
+
sql: {
|
|
644
|
+
up: `ALTER TABLE ${tableRef} ENABLE ROW LEVEL SECURITY;`,
|
|
645
|
+
down: `ALTER TABLE ${tableRef} DISABLE ROW LEVEL SECURITY;`
|
|
646
|
+
}
|
|
647
|
+
};
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
// src/edge-functions-fs.ts
|
|
651
|
+
import { createHash } from "crypto";
|
|
652
|
+
import { readdir, readFile, stat } from "fs/promises";
|
|
653
|
+
import { join, relative, sep } from "path";
|
|
654
|
+
var IGNORED = /* @__PURE__ */ new Set([".DS_Store", "Thumbs.db", ".gitkeep"]);
|
|
655
|
+
var NOT_FUNCTIONS = /* @__PURE__ */ new Set(["main"]);
|
|
656
|
+
async function hashDirectory(dir) {
|
|
657
|
+
const files = [];
|
|
658
|
+
async function walk(current) {
|
|
659
|
+
const entries = await readdir(current, { withFileTypes: true });
|
|
660
|
+
for (const entry of entries) {
|
|
661
|
+
if (IGNORED.has(entry.name)) continue;
|
|
662
|
+
const full = join(current, entry.name);
|
|
663
|
+
if (entry.isDirectory()) await walk(full);
|
|
664
|
+
else if (entry.isFile()) files.push(full);
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
await walk(dir);
|
|
668
|
+
const relative_ = files.map((f) => ({ abs: f, rel: relative(dir, f).split(sep).join("/") }));
|
|
669
|
+
relative_.sort((a, b) => a.rel.localeCompare(b.rel));
|
|
670
|
+
const hash = createHash("sha256");
|
|
671
|
+
for (const f of relative_) {
|
|
672
|
+
hash.update(f.rel);
|
|
673
|
+
hash.update("\0");
|
|
674
|
+
hash.update(await readFile(f.abs));
|
|
675
|
+
hash.update("\0");
|
|
676
|
+
}
|
|
677
|
+
return { hash: hash.digest("hex"), fileCount: relative_.length };
|
|
678
|
+
}
|
|
679
|
+
async function inventoryFunctions(root) {
|
|
680
|
+
let entries;
|
|
681
|
+
try {
|
|
682
|
+
entries = await readdir(root, { withFileTypes: true });
|
|
683
|
+
} catch {
|
|
684
|
+
return [];
|
|
685
|
+
}
|
|
686
|
+
const out = [];
|
|
687
|
+
for (const entry of entries) {
|
|
688
|
+
if (!entry.isDirectory()) continue;
|
|
689
|
+
if (entry.name.startsWith(".") || entry.name.startsWith("_")) continue;
|
|
690
|
+
if (NOT_FUNCTIONS.has(entry.name)) continue;
|
|
691
|
+
const dir = join(root, entry.name);
|
|
692
|
+
try {
|
|
693
|
+
await stat(dir);
|
|
694
|
+
const { hash, fileCount } = await hashDirectory(dir);
|
|
695
|
+
if (fileCount === 0) continue;
|
|
696
|
+
out.push({ slug: entry.name, hash, fileCount });
|
|
697
|
+
} catch {
|
|
698
|
+
}
|
|
699
|
+
}
|
|
700
|
+
return out.sort((a, b) => a.slug.localeCompare(b.slug));
|
|
701
|
+
}
|
|
702
|
+
|
|
703
|
+
// src/edge-functions-api.ts
|
|
704
|
+
import { createHash as createHash2 } from "crypto";
|
|
705
|
+
var DEFAULT_SELF_HOSTED_REF = "default";
|
|
706
|
+
function base(studioUrl, ref) {
|
|
707
|
+
return `${studioUrl.replace(/\/+$/, "")}/api/v1/projects/${encodeURIComponent(ref)}/functions`;
|
|
708
|
+
}
|
|
709
|
+
function parseMultipart(contentType, body) {
|
|
710
|
+
const match = /boundary=(?:"([^"]+)"|([^;]+))/i.exec(contentType);
|
|
711
|
+
const boundary = (match?.[1] ?? match?.[2] ?? "").trim();
|
|
712
|
+
if (!boundary) return [];
|
|
713
|
+
const files = [];
|
|
714
|
+
for (const section of body.split(`--${boundary}`)) {
|
|
715
|
+
const split = section.indexOf("\r\n\r\n");
|
|
716
|
+
if (split === -1) continue;
|
|
717
|
+
const headers = section.slice(0, split);
|
|
718
|
+
if (!/name="file"/i.test(headers)) continue;
|
|
719
|
+
const filename = /filename="([^"]*)"/i.exec(headers)?.[1] ?? "index.ts";
|
|
720
|
+
const content = section.slice(split + 4).replace(/\r\n$/, "");
|
|
721
|
+
files.push({ name: filename, body: content });
|
|
722
|
+
}
|
|
723
|
+
return files;
|
|
724
|
+
}
|
|
725
|
+
async function hashFunctionBody(res) {
|
|
726
|
+
const files = parseMultipart(res.headers.get("content-type") ?? "", await res.text());
|
|
727
|
+
files.sort((a, b) => a.name.localeCompare(b.name));
|
|
728
|
+
const hash = createHash2("sha256");
|
|
729
|
+
for (const file of files) {
|
|
730
|
+
hash.update(file.name);
|
|
731
|
+
hash.update("\0");
|
|
732
|
+
hash.update(file.body);
|
|
733
|
+
hash.update("\0");
|
|
734
|
+
}
|
|
735
|
+
return { hash: hash.digest("hex"), fileCount: files.length };
|
|
736
|
+
}
|
|
737
|
+
async function inventoryFunctionsViaStudio(studioUrl, ref, fetchFn) {
|
|
738
|
+
const listRes = await fetchFn(base(studioUrl, ref));
|
|
739
|
+
if (!listRes.ok) {
|
|
740
|
+
throw new Error(`Studio functions API returned ${listRes.status} for ${studioUrl}`);
|
|
741
|
+
}
|
|
742
|
+
const listed = await listRes.json();
|
|
743
|
+
const out = [];
|
|
744
|
+
for (const fn of listed) {
|
|
745
|
+
if (!fn?.slug) continue;
|
|
746
|
+
const bodyRes = await fetchFn(`${base(studioUrl, ref)}/${encodeURIComponent(fn.slug)}/body`);
|
|
747
|
+
if (!bodyRes.ok) {
|
|
748
|
+
out.push({ slug: fn.slug, hash: "", fileCount: 0 });
|
|
749
|
+
continue;
|
|
750
|
+
}
|
|
751
|
+
const { hash, fileCount } = await hashFunctionBody(bodyRes);
|
|
752
|
+
out.push({ slug: fn.slug, hash, fileCount });
|
|
753
|
+
}
|
|
754
|
+
return out.sort((a, b) => a.slug.localeCompare(b.slug));
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// src/checks/edge-functions.ts
|
|
758
|
+
var EdgeFunctionsCheck = class extends Check {
|
|
759
|
+
constructor(fetchFn = globalThis.fetch.bind(globalThis)) {
|
|
760
|
+
super();
|
|
761
|
+
this.fetchFn = fetchFn;
|
|
762
|
+
}
|
|
763
|
+
name = "edge-functions";
|
|
764
|
+
async scan(ctx) {
|
|
765
|
+
const sourceRef = ctx.source.projectRef;
|
|
766
|
+
const targetRef = ctx.target.projectRef;
|
|
767
|
+
const sourceKey = ctx.source.accessToken;
|
|
768
|
+
const targetKey = ctx.target.accessToken;
|
|
769
|
+
const [source, target] = await Promise.all([
|
|
770
|
+
this.resolveInventory(ctx.source),
|
|
771
|
+
this.resolveInventory(ctx.target)
|
|
772
|
+
]);
|
|
773
|
+
if (source && target) {
|
|
774
|
+
if (source.length === 0 && target.length === 0) {
|
|
775
|
+
throw new CheckSkipped("no Edge Functions found in either environment");
|
|
776
|
+
}
|
|
777
|
+
return diffFunctionInventories(source, target);
|
|
778
|
+
}
|
|
779
|
+
if (ctx.source.apiUrl || ctx.target.apiUrl) {
|
|
780
|
+
throw new CheckSkipped(
|
|
781
|
+
'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.'
|
|
782
|
+
);
|
|
783
|
+
}
|
|
784
|
+
if (!sourceRef || !targetRef || !sourceKey || !targetKey) {
|
|
785
|
+
throw new CheckSkipped("no projectRef or accessToken configured");
|
|
786
|
+
}
|
|
787
|
+
const [hostedSource, hostedTarget] = await Promise.all([
|
|
788
|
+
this.listFunctions(sourceRef, sourceKey),
|
|
789
|
+
this.listFunctions(targetRef, targetKey)
|
|
790
|
+
]);
|
|
791
|
+
return diffFunctions(hostedSource, hostedTarget, targetRef, targetKey);
|
|
792
|
+
}
|
|
793
|
+
/**
|
|
794
|
+
* Where this environment's functions can be read from, or null if nowhere.
|
|
795
|
+
*
|
|
796
|
+
* Studio is preferred: it works remotely and returns module contents. The
|
|
797
|
+
* directory is the fallback for when Studio is not reachable.
|
|
798
|
+
*/
|
|
799
|
+
async resolveInventory(env) {
|
|
800
|
+
if (env.studioUrl) {
|
|
801
|
+
return inventoryFunctionsViaStudio(
|
|
802
|
+
env.studioUrl,
|
|
803
|
+
env.projectRef ?? DEFAULT_SELF_HOSTED_REF,
|
|
804
|
+
this.fetchFn
|
|
805
|
+
);
|
|
806
|
+
}
|
|
807
|
+
if (env.functionsPath) return inventoryFunctions(env.functionsPath);
|
|
808
|
+
return null;
|
|
809
|
+
}
|
|
810
|
+
async listFunctions(projectRef, accessToken) {
|
|
811
|
+
const url = `${SUPABASE_MGMT_API}/${encodeURIComponent(projectRef)}/functions`;
|
|
812
|
+
const res = await this.fetchFn(url, {
|
|
813
|
+
headers: { Authorization: `Bearer ${accessToken}` }
|
|
814
|
+
});
|
|
815
|
+
if (!res.ok) throw new Error(`Failed to list functions for ${projectRef}: ${res.statusText}`);
|
|
816
|
+
return res.json();
|
|
817
|
+
}
|
|
818
|
+
};
|
|
819
|
+
function makeDeleteAction(slug, targetRef, targetKey) {
|
|
820
|
+
return {
|
|
821
|
+
method: "DELETE",
|
|
822
|
+
url: `${SUPABASE_MGMT_API}/${encodeURIComponent(targetRef)}/functions/${encodeURIComponent(slug)}`,
|
|
823
|
+
headers: { Authorization: `Bearer ${targetKey}` },
|
|
824
|
+
label: `Delete Edge Function "${slug}" from target`
|
|
825
|
+
};
|
|
826
|
+
}
|
|
827
|
+
function diffFunctions(source, target, targetRef, targetKey) {
|
|
828
|
+
const issues = [];
|
|
829
|
+
const sourceMap = new Map(source.map((f) => [f.slug, f]));
|
|
830
|
+
const targetMap = new Map(target.map((f) => [f.slug, f]));
|
|
831
|
+
for (const [slug, f] of sourceMap) {
|
|
832
|
+
if (!targetMap.has(slug)) {
|
|
833
|
+
issues.push({
|
|
834
|
+
id: `edge-fn-missing-${slug}`,
|
|
835
|
+
check: "edge-functions",
|
|
836
|
+
severity: "warning",
|
|
837
|
+
title: `Missing Edge Function: ${slug}`,
|
|
838
|
+
description: `Function "${f.name}" (${slug}) exists in source but not in target. Deploy it via "supabase functions deploy ${slug}" against the target project.`,
|
|
839
|
+
sourceValue: f
|
|
840
|
+
// Cannot auto-deploy: source code is not available via the Management API.
|
|
841
|
+
// User must deploy from their local supabase/functions/ directory.
|
|
842
|
+
});
|
|
843
|
+
}
|
|
844
|
+
}
|
|
845
|
+
for (const [slug, f] of targetMap) {
|
|
846
|
+
if (!sourceMap.has(slug)) {
|
|
847
|
+
issues.push({
|
|
848
|
+
id: `edge-fn-extra-${slug}`,
|
|
849
|
+
check: "edge-functions",
|
|
850
|
+
severity: "info",
|
|
851
|
+
title: `Extra Edge Function: ${slug}`,
|
|
852
|
+
description: `Function "${f.name}" (${slug}) exists in target but not in source.`,
|
|
853
|
+
targetValue: f,
|
|
854
|
+
action: makeDeleteAction(slug, targetRef, targetKey)
|
|
855
|
+
});
|
|
856
|
+
}
|
|
857
|
+
}
|
|
858
|
+
for (const [slug, sf] of sourceMap) {
|
|
859
|
+
const tf = targetMap.get(slug);
|
|
860
|
+
if (tf && sf.version !== tf.version) {
|
|
861
|
+
issues.push({
|
|
862
|
+
id: `edge-fn-version-${slug}`,
|
|
863
|
+
check: "edge-functions",
|
|
864
|
+
severity: "warning",
|
|
865
|
+
title: `Version mismatch: ${slug}`,
|
|
866
|
+
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.`,
|
|
867
|
+
sourceValue: sf,
|
|
868
|
+
targetValue: tf
|
|
869
|
+
// Cannot auto-deploy: source code is not available via the Management API.
|
|
870
|
+
});
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
return issues;
|
|
874
|
+
}
|
|
875
|
+
function diffFunctionInventories(source, target) {
|
|
876
|
+
const issues = [];
|
|
877
|
+
const sourceMap = new Map(source.map((f) => [f.slug, f]));
|
|
878
|
+
const targetMap = new Map(target.map((f) => [f.slug, f]));
|
|
879
|
+
for (const [slug, sf] of sourceMap) {
|
|
880
|
+
if (targetMap.has(slug)) continue;
|
|
881
|
+
issues.push({
|
|
882
|
+
id: `edge-fn-missing-${slug}`,
|
|
883
|
+
check: "edge-functions",
|
|
884
|
+
severity: "warning",
|
|
885
|
+
title: `Missing Edge Function: ${slug}`,
|
|
886
|
+
description: `Function "${slug}" (${sf.fileCount} file(s)) exists in source but not in target. Deploy it with: supabase functions deploy ${slug}`,
|
|
887
|
+
sourceValue: { slug, fileCount: sf.fileCount }
|
|
888
|
+
});
|
|
889
|
+
}
|
|
890
|
+
for (const [slug, tf] of targetMap) {
|
|
891
|
+
if (sourceMap.has(slug)) continue;
|
|
892
|
+
issues.push({
|
|
893
|
+
id: `edge-fn-extra-${slug}`,
|
|
894
|
+
check: "edge-functions",
|
|
895
|
+
severity: "info",
|
|
896
|
+
title: `Extra Edge Function: ${slug}`,
|
|
897
|
+
description: `Function "${slug}" exists in target but not in source. Remove it with: supabase functions delete ${slug}`,
|
|
898
|
+
targetValue: { slug, fileCount: tf.fileCount }
|
|
899
|
+
});
|
|
900
|
+
}
|
|
901
|
+
for (const [slug, sf] of sourceMap) {
|
|
902
|
+
const tf = targetMap.get(slug);
|
|
903
|
+
if (!tf || tf.hash === sf.hash) continue;
|
|
904
|
+
issues.push({
|
|
905
|
+
id: `edge-fn-changed-${slug}`,
|
|
906
|
+
check: "edge-functions",
|
|
907
|
+
severity: "warning",
|
|
908
|
+
title: `Edge Function differs: ${slug}`,
|
|
909
|
+
description: `Function "${slug}" has different contents in source and target. Redeploy with: supabase functions deploy ${slug}`,
|
|
910
|
+
// Hashes, not source: the point is that they differ, and function code
|
|
911
|
+
// can contain secrets that have no business in a drift report.
|
|
912
|
+
sourceValue: { slug, sha256: sf.hash.slice(0, 12) },
|
|
913
|
+
targetValue: { slug, sha256: tf.hash.slice(0, 12) }
|
|
914
|
+
});
|
|
915
|
+
}
|
|
916
|
+
return issues;
|
|
917
|
+
}
|
|
918
|
+
|
|
919
|
+
// src/storage-files.ts
|
|
920
|
+
import { createClient } from "@supabase/supabase-js";
|
|
921
|
+
import { createHash as createHash3 } from "crypto";
|
|
922
|
+
var JSON_MIME_TYPES = ["application/json", "text/json"];
|
|
923
|
+
function buildSupabaseUrl(projectRef, apiUrl) {
|
|
924
|
+
if (apiUrl) return apiUrl;
|
|
925
|
+
return `https://${projectRef}.supabase.co`;
|
|
926
|
+
}
|
|
927
|
+
async function listBucketFiles(client, bucket, folder = "") {
|
|
928
|
+
const results = [];
|
|
929
|
+
const { data, error } = await client.storage.from(bucket).list(folder, {
|
|
930
|
+
limit: STORAGE_LIST_LIMIT,
|
|
931
|
+
sortBy: { column: "name", order: "asc" }
|
|
932
|
+
});
|
|
933
|
+
if (error || !data) return results;
|
|
934
|
+
for (const item of data) {
|
|
935
|
+
const itemPath = folder ? `${folder}/${item.name}` : item.name;
|
|
936
|
+
if (item.id === null) {
|
|
937
|
+
const children = await listBucketFiles(client, bucket, itemPath);
|
|
938
|
+
results.push(...children);
|
|
939
|
+
} else {
|
|
940
|
+
results.push({
|
|
941
|
+
name: item.name,
|
|
942
|
+
path: itemPath,
|
|
943
|
+
metadata: item.metadata
|
|
944
|
+
});
|
|
945
|
+
}
|
|
946
|
+
}
|
|
947
|
+
return results;
|
|
948
|
+
}
|
|
949
|
+
function toFileInfo(bucket, entry) {
|
|
950
|
+
const meta = entry.metadata ?? {};
|
|
951
|
+
return {
|
|
952
|
+
bucket,
|
|
953
|
+
path: entry.path,
|
|
954
|
+
name: entry.name,
|
|
955
|
+
size: typeof meta.size === "number" ? meta.size : 0,
|
|
956
|
+
createdAt: typeof meta.lastModified === "string" ? meta.lastModified : null,
|
|
957
|
+
updatedAt: typeof meta.lastModified === "string" ? meta.lastModified : null,
|
|
958
|
+
mimeType: typeof meta.mimetype === "string" ? meta.mimetype : null,
|
|
959
|
+
checksum: null
|
|
960
|
+
// populated later for JSON files
|
|
961
|
+
};
|
|
962
|
+
}
|
|
963
|
+
function md5(content) {
|
|
964
|
+
return createHash3("md5").update(content).digest("hex");
|
|
965
|
+
}
|
|
966
|
+
function isJsonFile(file) {
|
|
967
|
+
if (file.mimeType && JSON_MIME_TYPES.includes(file.mimeType)) return true;
|
|
968
|
+
return file.name.endsWith(".json");
|
|
969
|
+
}
|
|
970
|
+
async function inventoryFiles(client, buckets, computeChecksums) {
|
|
971
|
+
const allFiles = [];
|
|
972
|
+
for (const bucket of buckets) {
|
|
973
|
+
const entries = await listBucketFiles(client, bucket);
|
|
974
|
+
const files = entries.map((e) => toFileInfo(bucket, e));
|
|
975
|
+
if (computeChecksums) {
|
|
976
|
+
for (const file of files) {
|
|
977
|
+
if (isJsonFile(file)) {
|
|
978
|
+
try {
|
|
979
|
+
const { data, error } = await client.storage.from(bucket).download(file.path);
|
|
980
|
+
if (!error && data) {
|
|
981
|
+
const text = await data.text();
|
|
982
|
+
file.checksum = md5(text);
|
|
983
|
+
}
|
|
984
|
+
} catch {
|
|
985
|
+
}
|
|
986
|
+
}
|
|
987
|
+
}
|
|
988
|
+
}
|
|
989
|
+
allFiles.push(...files);
|
|
990
|
+
}
|
|
991
|
+
return allFiles;
|
|
992
|
+
}
|
|
993
|
+
function fileKey(file) {
|
|
994
|
+
return `${file.bucket}/${file.path}`;
|
|
995
|
+
}
|
|
996
|
+
function diffFileInventories(sourceFiles, targetFiles) {
|
|
997
|
+
const diffs = [];
|
|
998
|
+
const sourceMap = new Map(sourceFiles.map((f) => [fileKey(f), f]));
|
|
999
|
+
const targetMap = new Map(targetFiles.map((f) => [fileKey(f), f]));
|
|
1000
|
+
for (const [key, sf] of sourceMap) {
|
|
1001
|
+
if (!targetMap.has(key)) {
|
|
1002
|
+
diffs.push({
|
|
1003
|
+
bucket: sf.bucket,
|
|
1004
|
+
path: sf.path,
|
|
1005
|
+
type: "missing",
|
|
1006
|
+
details: `File "${sf.path}" exists in source bucket "${sf.bucket}" but not in target.`,
|
|
1007
|
+
sourceFile: sf
|
|
1008
|
+
});
|
|
1009
|
+
}
|
|
1010
|
+
}
|
|
1011
|
+
for (const [key, tf] of targetMap) {
|
|
1012
|
+
if (!sourceMap.has(key)) {
|
|
1013
|
+
diffs.push({
|
|
1014
|
+
bucket: tf.bucket,
|
|
1015
|
+
path: tf.path,
|
|
1016
|
+
type: "extra",
|
|
1017
|
+
details: `File "${tf.path}" exists in target bucket "${tf.bucket}" but not in source.`,
|
|
1018
|
+
targetFile: tf
|
|
1019
|
+
});
|
|
1020
|
+
}
|
|
1021
|
+
}
|
|
1022
|
+
for (const [key, sf] of sourceMap) {
|
|
1023
|
+
const tf = targetMap.get(key);
|
|
1024
|
+
if (!tf) continue;
|
|
1025
|
+
const changes = [];
|
|
1026
|
+
if (sf.checksum && tf.checksum) {
|
|
1027
|
+
if (sf.checksum !== tf.checksum) {
|
|
1028
|
+
changes.push(`content differs (source md5: ${sf.checksum.slice(0, 12)}\u2026, target md5: ${tf.checksum.slice(0, 12)}\u2026)`);
|
|
1029
|
+
}
|
|
1030
|
+
} else {
|
|
1031
|
+
if (sf.size !== tf.size) {
|
|
1032
|
+
changes.push(`size differs (source: ${sf.size} bytes, target: ${tf.size} bytes)`);
|
|
1033
|
+
}
|
|
1034
|
+
if (sf.updatedAt && tf.updatedAt && sf.updatedAt !== tf.updatedAt) {
|
|
1035
|
+
changes.push(`last modified differs (source: ${sf.updatedAt}, target: ${tf.updatedAt})`);
|
|
1036
|
+
}
|
|
1037
|
+
}
|
|
1038
|
+
if (changes.length > 0) {
|
|
1039
|
+
diffs.push({
|
|
1040
|
+
bucket: sf.bucket,
|
|
1041
|
+
path: sf.path,
|
|
1042
|
+
type: "changed",
|
|
1043
|
+
details: `File "${sf.path}" in bucket "${sf.bucket}": ${changes.join("; ")}.`,
|
|
1044
|
+
sourceFile: sf,
|
|
1045
|
+
targetFile: tf
|
|
1046
|
+
});
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
return diffs;
|
|
1050
|
+
}
|
|
1051
|
+
function fileDiffsToIssues(diffs) {
|
|
1052
|
+
return diffs.map((d) => ({
|
|
1053
|
+
id: `storage-file-${d.type}-${d.bucket}-${d.path.replace(/[^a-zA-Z0-9]/g, "-")}`,
|
|
1054
|
+
check: "storage",
|
|
1055
|
+
severity: d.type === "missing" ? "warning" : d.type === "extra" ? "info" : "warning",
|
|
1056
|
+
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}`,
|
|
1057
|
+
description: d.details,
|
|
1058
|
+
sourceValue: d.sourceFile,
|
|
1059
|
+
targetValue: d.targetFile
|
|
1060
|
+
}));
|
|
1061
|
+
}
|
|
1062
|
+
async function scanStorageFiles(options) {
|
|
1063
|
+
const factory = options.createClientFn ?? createClient;
|
|
1064
|
+
const sourceClient = factory(
|
|
1065
|
+
buildSupabaseUrl(options.sourceRef, options.sourceApiUrl),
|
|
1066
|
+
options.sourceKey
|
|
1067
|
+
);
|
|
1068
|
+
const targetClient = factory(
|
|
1069
|
+
buildSupabaseUrl(options.targetRef, options.targetApiUrl),
|
|
1070
|
+
options.targetKey
|
|
1071
|
+
);
|
|
1072
|
+
let buckets;
|
|
1073
|
+
if (options.buckets?.length) {
|
|
1074
|
+
buckets = options.buckets;
|
|
1075
|
+
} else {
|
|
1076
|
+
const [{ data: sb }, { data: tb }] = await Promise.all([
|
|
1077
|
+
sourceClient.storage.listBuckets(),
|
|
1078
|
+
targetClient.storage.listBuckets()
|
|
1079
|
+
]);
|
|
1080
|
+
const sourceNames = new Set((sb ?? []).map((b) => b.name));
|
|
1081
|
+
const targetNames = new Set((tb ?? []).map((b) => b.name));
|
|
1082
|
+
buckets = [...sourceNames].filter((n) => targetNames.has(n));
|
|
1083
|
+
}
|
|
1084
|
+
if (buckets.length === 0) return [];
|
|
1085
|
+
const [sourceFiles, targetFiles] = await Promise.all([
|
|
1086
|
+
inventoryFiles(sourceClient, buckets, true),
|
|
1087
|
+
inventoryFiles(targetClient, buckets, true)
|
|
1088
|
+
]);
|
|
1089
|
+
const diffs = diffFileInventories(sourceFiles, targetFiles);
|
|
1090
|
+
return fileDiffsToIssues(diffs);
|
|
1091
|
+
}
|
|
1092
|
+
|
|
1093
|
+
// src/checks/storage.ts
|
|
1094
|
+
var StorageCheck = class extends Check {
|
|
1095
|
+
constructor(queryFn = pgQuery, includeFiles = false) {
|
|
1096
|
+
super();
|
|
1097
|
+
this.queryFn = queryFn;
|
|
1098
|
+
this.includeFiles = includeFiles;
|
|
1099
|
+
}
|
|
1100
|
+
name = "storage";
|
|
1101
|
+
async scan(ctx) {
|
|
1102
|
+
const [srcHasStorage, tgtHasStorage] = await Promise.all([
|
|
1103
|
+
this.hasStorageSchema(ctx.source.dbUrl),
|
|
1104
|
+
this.hasStorageSchema(ctx.target.dbUrl)
|
|
1105
|
+
]);
|
|
1106
|
+
if (!srcHasStorage || !tgtHasStorage) {
|
|
1107
|
+
const which = !srcHasStorage && !tgtHasStorage ? "neither environment has" : !srcHasStorage ? "the source does not have" : "the target does not have";
|
|
1108
|
+
throw new CheckSkipped(
|
|
1109
|
+
`${which} a storage schema \u2014 not a Supabase project. Skip this check explicitly with --skip=storage to keep runs quiet.`
|
|
1110
|
+
);
|
|
1111
|
+
}
|
|
1112
|
+
const bucketIssues = await this.scanBuckets(ctx);
|
|
1113
|
+
const typedBucketIssues = await this.scanTypedBuckets(ctx);
|
|
1114
|
+
const policyIssues = await this.scanPolicies(ctx);
|
|
1115
|
+
let fileIssues = [];
|
|
1116
|
+
if (this.includeFiles) {
|
|
1117
|
+
fileIssues = await this.scanFiles(ctx);
|
|
1118
|
+
}
|
|
1119
|
+
return [...bucketIssues, ...typedBucketIssues, ...policyIssues, ...fileIssues];
|
|
1120
|
+
}
|
|
1121
|
+
/**
|
|
1122
|
+
* Analytics and vector buckets live in their own tables, not storage.buckets,
|
|
1123
|
+
* so creating one was invisible: the check read storage.buckets and reported
|
|
1124
|
+
* no drift at all.
|
|
1125
|
+
*
|
|
1126
|
+
* Both tables arrived with newer storage migrations (0038 analytics, 0044/45
|
|
1127
|
+
* vectors), so each is probed before being read.
|
|
1128
|
+
*/
|
|
1129
|
+
async scanTypedBuckets(ctx) {
|
|
1130
|
+
const issues = [];
|
|
1131
|
+
for (const spec of TYPED_BUCKET_TABLES) {
|
|
1132
|
+
const [srcHas, tgtHas] = await Promise.all([
|
|
1133
|
+
this.hasTable(ctx.source.dbUrl, spec.table),
|
|
1134
|
+
this.hasTable(ctx.target.dbUrl, spec.table)
|
|
1135
|
+
]);
|
|
1136
|
+
if (!srcHas || !tgtHas) continue;
|
|
1137
|
+
const [source, target] = await Promise.all([
|
|
1138
|
+
this.listTypedBuckets(ctx.source.dbUrl, spec),
|
|
1139
|
+
this.listTypedBuckets(ctx.target.dbUrl, spec)
|
|
1140
|
+
]);
|
|
1141
|
+
issues.push(...diffTypedBuckets(source, target, spec));
|
|
1142
|
+
}
|
|
1143
|
+
return issues;
|
|
1144
|
+
}
|
|
1145
|
+
async hasTable(dbUrl, table) {
|
|
1146
|
+
const rows = await this.queryFn(dbUrl, tableExistsSql(table));
|
|
1147
|
+
return rows[0]?.present === true;
|
|
1148
|
+
}
|
|
1149
|
+
async listTypedBuckets(dbUrl, spec) {
|
|
1150
|
+
return await this.queryFn(dbUrl, spec.sql);
|
|
1151
|
+
}
|
|
1152
|
+
async scanBuckets(ctx) {
|
|
1153
|
+
const [source, target] = await Promise.all([
|
|
1154
|
+
this.listBuckets(ctx.source.dbUrl),
|
|
1155
|
+
this.listBuckets(ctx.target.dbUrl)
|
|
1156
|
+
]);
|
|
1157
|
+
return diffBuckets(source, target, {
|
|
1158
|
+
apiUrl: ctx.target.apiUrl,
|
|
1159
|
+
accessToken: ctx.target.accessToken
|
|
1160
|
+
});
|
|
1161
|
+
}
|
|
1162
|
+
async scanPolicies(ctx) {
|
|
1163
|
+
const [source, target] = await Promise.all([
|
|
1164
|
+
this.fetchStoragePolicies(ctx.source.dbUrl),
|
|
1165
|
+
this.fetchStoragePolicies(ctx.target.dbUrl)
|
|
1166
|
+
]);
|
|
1167
|
+
return dropEquivalentPolicyChanges(
|
|
1168
|
+
diffSchemaPolicies(source, target, {
|
|
1169
|
+
schema: "storage",
|
|
1170
|
+
check: "storage",
|
|
1171
|
+
idPrefix: "storage-policy",
|
|
1172
|
+
label: "storage"
|
|
1173
|
+
}),
|
|
1174
|
+
ctx,
|
|
1175
|
+
defaultCanonicalizer(this.queryFn),
|
|
1176
|
+
"storage"
|
|
1177
|
+
);
|
|
1178
|
+
}
|
|
1179
|
+
async hasStorageSchema(dbUrl) {
|
|
1180
|
+
const rows = await this.queryFn(dbUrl, STORAGE_PRESENT_SQL);
|
|
1181
|
+
return rows[0]?.present === true;
|
|
1182
|
+
}
|
|
1183
|
+
/**
|
|
1184
|
+
* Read the buckets, selecting only the columns this Supabase version actually
|
|
1185
|
+
* has. storage.buckets has grown over time (owner_id in 0018, type in 0038),
|
|
1186
|
+
* so a fixed column list either misses columns on a new instance or fails on
|
|
1187
|
+
* an old one. Resolving them per-connection handles both.
|
|
1188
|
+
*/
|
|
1189
|
+
async listBuckets(dbUrl) {
|
|
1190
|
+
const present = await this.queryFn(dbUrl, BUCKET_COLUMNS_SQL);
|
|
1191
|
+
const names = new Set(present.map((r) => r.column_name));
|
|
1192
|
+
const cols = COMPARED_BUCKET_COLUMNS.filter((c) => names.has(c));
|
|
1193
|
+
const sql = `SELECT ${cols.join(", ")} FROM storage.buckets ORDER BY name`;
|
|
1194
|
+
return await this.queryFn(dbUrl, sql);
|
|
1195
|
+
}
|
|
1196
|
+
async fetchStoragePolicies(dbUrl) {
|
|
1197
|
+
return await this.queryFn(dbUrl, STORAGE_POLICY_SQL);
|
|
1198
|
+
}
|
|
1199
|
+
async scanFiles(ctx) {
|
|
1200
|
+
const sourceRef = ctx.source.projectRef;
|
|
1201
|
+
const targetRef = ctx.target.projectRef;
|
|
1202
|
+
const sourceKey = ctx.source.accessToken;
|
|
1203
|
+
const targetKey = ctx.target.accessToken;
|
|
1204
|
+
if (!sourceRef || !targetRef || !sourceKey || !targetKey) return [];
|
|
1205
|
+
const options = {
|
|
1206
|
+
sourceRef,
|
|
1207
|
+
targetRef,
|
|
1208
|
+
sourceKey,
|
|
1209
|
+
targetKey,
|
|
1210
|
+
sourceApiUrl: ctx.source.apiUrl,
|
|
1211
|
+
targetApiUrl: ctx.target.apiUrl
|
|
1212
|
+
};
|
|
1213
|
+
return await scanStorageFiles(options);
|
|
1214
|
+
}
|
|
1215
|
+
};
|
|
1216
|
+
var COMPARED_BUCKET_COLUMNS = [
|
|
1217
|
+
"id",
|
|
1218
|
+
"name",
|
|
1219
|
+
"public",
|
|
1220
|
+
"file_size_limit",
|
|
1221
|
+
"allowed_mime_types",
|
|
1222
|
+
"type",
|
|
1223
|
+
"avif_autodetection",
|
|
1224
|
+
"owner_id"
|
|
1225
|
+
];
|
|
1226
|
+
var BUCKET_COLUMNS_SQL = `
|
|
1227
|
+
SELECT column_name
|
|
1228
|
+
FROM information_schema.columns
|
|
1229
|
+
WHERE table_schema = 'storage' AND table_name = 'buckets'
|
|
1230
|
+
`;
|
|
1231
|
+
var TYPED_BUCKET_TABLES = [
|
|
1232
|
+
{
|
|
1233
|
+
table: "buckets_analytics",
|
|
1234
|
+
key: "name",
|
|
1235
|
+
compared: ["format"],
|
|
1236
|
+
label: "analytics bucket",
|
|
1237
|
+
// deleted_at is a soft delete — a removed bucket still has its row.
|
|
1238
|
+
sql: `SELECT name AS key, format FROM storage.buckets_analytics
|
|
1239
|
+
WHERE deleted_at IS NULL ORDER BY name`
|
|
1240
|
+
},
|
|
1241
|
+
{
|
|
1242
|
+
table: "buckets_vectors",
|
|
1243
|
+
key: "id",
|
|
1244
|
+
compared: [],
|
|
1245
|
+
label: "vector bucket",
|
|
1246
|
+
sql: `SELECT id AS key FROM storage.buckets_vectors ORDER BY id`
|
|
1247
|
+
}
|
|
1248
|
+
];
|
|
1249
|
+
function tableExistsSql(table) {
|
|
1250
|
+
return `
|
|
1251
|
+
SELECT EXISTS (
|
|
1252
|
+
SELECT 1 FROM information_schema.tables
|
|
1253
|
+
WHERE table_schema = 'storage' AND table_name = '${table}'
|
|
1254
|
+
) AS present
|
|
1255
|
+
`;
|
|
1256
|
+
}
|
|
1257
|
+
function diffTypedBuckets(source, target, spec) {
|
|
1258
|
+
const issues = [];
|
|
1259
|
+
const sourceMap = new Map(source.map((b) => [String(b.key), b]));
|
|
1260
|
+
const targetMap = new Map(target.map((b) => [String(b.key), b]));
|
|
1261
|
+
for (const [key, b] of sourceMap) {
|
|
1262
|
+
if (targetMap.has(key)) continue;
|
|
1263
|
+
issues.push({
|
|
1264
|
+
id: `storage-${spec.table}-missing-${key}`,
|
|
1265
|
+
check: "storage",
|
|
1266
|
+
severity: "warning",
|
|
1267
|
+
title: `Missing ${spec.label}: ${key}`,
|
|
1268
|
+
description: `${spec.label} "${key}" exists in source but not in target.`,
|
|
1269
|
+
sourceValue: b
|
|
1270
|
+
});
|
|
1271
|
+
}
|
|
1272
|
+
for (const [key, b] of targetMap) {
|
|
1273
|
+
if (sourceMap.has(key)) continue;
|
|
1274
|
+
issues.push({
|
|
1275
|
+
id: `storage-${spec.table}-extra-${key}`,
|
|
1276
|
+
check: "storage",
|
|
1277
|
+
severity: "info",
|
|
1278
|
+
title: `Extra ${spec.label}: ${key}`,
|
|
1279
|
+
description: `${spec.label} "${key}" exists in target but not in source.`,
|
|
1280
|
+
targetValue: b
|
|
1281
|
+
});
|
|
1282
|
+
}
|
|
1283
|
+
for (const [key, sb] of sourceMap) {
|
|
1284
|
+
const tb = targetMap.get(key);
|
|
1285
|
+
if (!tb) continue;
|
|
1286
|
+
for (const col of spec.compared) {
|
|
1287
|
+
if (sb[col] === tb[col]) continue;
|
|
1288
|
+
issues.push({
|
|
1289
|
+
id: `storage-${spec.table}-${col}-${key}`,
|
|
1290
|
+
check: "storage",
|
|
1291
|
+
severity: "warning",
|
|
1292
|
+
title: `${spec.label} ${col} mismatch: ${key}`,
|
|
1293
|
+
description: `${spec.label} "${key}" has ${col} ${String(sb[col])} in source but ${String(tb[col])} in target.`,
|
|
1294
|
+
sourceValue: { [col]: sb[col] },
|
|
1295
|
+
targetValue: { [col]: tb[col] }
|
|
1296
|
+
});
|
|
1297
|
+
}
|
|
1298
|
+
}
|
|
1299
|
+
return issues;
|
|
1300
|
+
}
|
|
1301
|
+
var STORAGE_PRESENT_SQL = `
|
|
1302
|
+
SELECT EXISTS (
|
|
1303
|
+
SELECT 1 FROM information_schema.tables
|
|
1304
|
+
WHERE table_schema = 'storage' AND table_name = 'buckets'
|
|
1305
|
+
) AS present
|
|
1306
|
+
`;
|
|
1307
|
+
var STORAGE_POLICY_SQL = schemaPolicySql("storage");
|
|
1308
|
+
function bucketApiHeaders(accessToken) {
|
|
1309
|
+
if (!accessToken) return {};
|
|
1310
|
+
return { apikey: accessToken, Authorization: `Bearer ${accessToken}` };
|
|
1311
|
+
}
|
|
1312
|
+
function bucketAction(config, method, path, label, body) {
|
|
1313
|
+
return {
|
|
1314
|
+
method,
|
|
1315
|
+
url: `${config.apiUrl}/storage/v1/bucket${path}`,
|
|
1316
|
+
headers: bucketApiHeaders(config.accessToken),
|
|
1317
|
+
label,
|
|
1318
|
+
...body !== void 0 && { body }
|
|
1319
|
+
};
|
|
1320
|
+
}
|
|
1321
|
+
function diffBuckets(source, target, config) {
|
|
1322
|
+
const issues = [];
|
|
1323
|
+
const sourceMap = new Map(source.map((b) => [b.id, b]));
|
|
1324
|
+
const targetMap = new Map(target.map((b) => [b.id, b]));
|
|
1325
|
+
const useApi = !!config?.apiUrl;
|
|
1326
|
+
for (const [id, b] of sourceMap) {
|
|
1327
|
+
if (!targetMap.has(id)) {
|
|
1328
|
+
const issue = {
|
|
1329
|
+
id: `storage-missing-${id}`,
|
|
1330
|
+
check: "storage",
|
|
1331
|
+
severity: "warning",
|
|
1332
|
+
title: `Missing bucket: ${b.name}`,
|
|
1333
|
+
description: `Bucket "${b.name}" exists in source but not in target.`,
|
|
1334
|
+
sourceValue: b
|
|
1335
|
+
};
|
|
1336
|
+
if (useApi) {
|
|
1337
|
+
issue.action = bucketAction(config, "POST", "", `Create bucket "${b.name}"`, {
|
|
1338
|
+
id: b.id,
|
|
1339
|
+
name: b.name,
|
|
1340
|
+
public: b.public,
|
|
1341
|
+
file_size_limit: b.file_size_limit,
|
|
1342
|
+
allowed_mime_types: b.allowed_mime_types
|
|
1343
|
+
});
|
|
1344
|
+
} else {
|
|
1345
|
+
issue.sql = {
|
|
1346
|
+
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)});`,
|
|
1347
|
+
down: `DELETE FROM storage.buckets WHERE id = ${sqlLiteral(b.id)};`
|
|
1348
|
+
};
|
|
1349
|
+
}
|
|
1350
|
+
issues.push(issue);
|
|
1351
|
+
}
|
|
1352
|
+
}
|
|
1353
|
+
for (const [id, b] of targetMap) {
|
|
1354
|
+
if (!sourceMap.has(id)) {
|
|
1355
|
+
const issue = {
|
|
1356
|
+
id: `storage-extra-${id}`,
|
|
1357
|
+
check: "storage",
|
|
1358
|
+
severity: "info",
|
|
1359
|
+
title: `Extra bucket: ${b.name}`,
|
|
1360
|
+
description: `Bucket "${b.name}" exists in target but not in source.`,
|
|
1361
|
+
targetValue: b
|
|
1362
|
+
};
|
|
1363
|
+
if (useApi) {
|
|
1364
|
+
issue.action = bucketAction(config, "DELETE", `/${id}`, `Delete bucket "${b.name}"`);
|
|
1365
|
+
} else {
|
|
1366
|
+
issue.sql = {
|
|
1367
|
+
up: `DELETE FROM storage.buckets WHERE id = ${sqlLiteral(b.id)};`,
|
|
1368
|
+
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)});`
|
|
1369
|
+
};
|
|
1370
|
+
}
|
|
1371
|
+
issues.push(issue);
|
|
1372
|
+
}
|
|
1373
|
+
}
|
|
1374
|
+
for (const [id, sb] of sourceMap) {
|
|
1375
|
+
const tb = targetMap.get(id);
|
|
1376
|
+
if (!tb) continue;
|
|
1377
|
+
const setClauses = [];
|
|
1378
|
+
if (sb.public !== tb.public) {
|
|
1379
|
+
setClauses.push(`public = ${sqlLiteral(sb.public)}`);
|
|
1380
|
+
issues.push({
|
|
1381
|
+
id: `storage-visibility-${id}`,
|
|
1382
|
+
check: "storage",
|
|
1383
|
+
severity: sb.public && !tb.public ? "warning" : "critical",
|
|
1384
|
+
title: `Bucket visibility mismatch: ${sb.name}`,
|
|
1385
|
+
description: `Bucket "${sb.name}" is ${sb.public ? "public" : "private"} in source but ${tb.public ? "public" : "private"} in target.`,
|
|
1386
|
+
sourceValue: { public: sb.public },
|
|
1387
|
+
targetValue: { public: tb.public }
|
|
1388
|
+
});
|
|
1389
|
+
}
|
|
1390
|
+
if (sb.file_size_limit !== tb.file_size_limit) {
|
|
1391
|
+
setClauses.push(`file_size_limit = ${sqlLiteral(sb.file_size_limit)}`);
|
|
1392
|
+
issues.push({
|
|
1393
|
+
id: `storage-sizelimit-${id}`,
|
|
1394
|
+
check: "storage",
|
|
1395
|
+
severity: "warning",
|
|
1396
|
+
title: `Bucket file size limit mismatch: ${sb.name}`,
|
|
1397
|
+
description: `Bucket "${sb.name}" file_size_limit is ${sb.file_size_limit ?? "unlimited"} in source but ${tb.file_size_limit ?? "unlimited"} in target.`,
|
|
1398
|
+
sourceValue: { file_size_limit: sb.file_size_limit },
|
|
1399
|
+
targetValue: { file_size_limit: tb.file_size_limit }
|
|
1400
|
+
});
|
|
1401
|
+
}
|
|
1402
|
+
const srcMimes = (sb.allowed_mime_types ?? []).slice().sort().join(",");
|
|
1403
|
+
const tgtMimes = (tb.allowed_mime_types ?? []).slice().sort().join(",");
|
|
1404
|
+
if (srcMimes !== tgtMimes) {
|
|
1405
|
+
setClauses.push(`allowed_mime_types = ${sqlLiteral(sb.allowed_mime_types)}`);
|
|
1406
|
+
issues.push({
|
|
1407
|
+
id: `storage-mimetypes-${id}`,
|
|
1408
|
+
check: "storage",
|
|
1409
|
+
severity: "warning",
|
|
1410
|
+
title: `Bucket allowed MIME types mismatch: ${sb.name}`,
|
|
1411
|
+
description: `Bucket "${sb.name}" allowed_mime_types differ between source and target.`,
|
|
1412
|
+
sourceValue: { allowed_mime_types: sb.allowed_mime_types },
|
|
1413
|
+
targetValue: { allowed_mime_types: tb.allowed_mime_types }
|
|
1414
|
+
});
|
|
1415
|
+
}
|
|
1416
|
+
if (sb.type !== void 0 && tb.type !== void 0 && sb.type !== tb.type) {
|
|
1417
|
+
setClauses.push(`type = ${sqlLiteral(sb.type)}`);
|
|
1418
|
+
issues.push({
|
|
1419
|
+
id: `storage-type-${id}`,
|
|
1420
|
+
check: "storage",
|
|
1421
|
+
severity: "critical",
|
|
1422
|
+
title: `Bucket type mismatch: ${sb.name}`,
|
|
1423
|
+
description: `Bucket "${sb.name}" is ${sb.type} in source but ${tb.type} in target \u2014 these are different storage backends, not a setting.`,
|
|
1424
|
+
sourceValue: { type: sb.type },
|
|
1425
|
+
targetValue: { type: tb.type }
|
|
1426
|
+
});
|
|
1427
|
+
}
|
|
1428
|
+
if (sb.avif_autodetection !== void 0 && tb.avif_autodetection !== void 0 && sb.avif_autodetection !== tb.avif_autodetection) {
|
|
1429
|
+
setClauses.push(`avif_autodetection = ${sqlLiteral(sb.avif_autodetection)}`);
|
|
1430
|
+
issues.push({
|
|
1431
|
+
id: `storage-avif-${id}`,
|
|
1432
|
+
check: "storage",
|
|
1433
|
+
severity: "warning",
|
|
1434
|
+
title: `Bucket AVIF autodetection mismatch: ${sb.name}`,
|
|
1435
|
+
description: `Bucket "${sb.name}" avif_autodetection is ${sb.avif_autodetection} in source but ${tb.avif_autodetection} in target.`,
|
|
1436
|
+
sourceValue: { avif_autodetection: sb.avif_autodetection },
|
|
1437
|
+
targetValue: { avif_autodetection: tb.avif_autodetection }
|
|
1438
|
+
});
|
|
1439
|
+
}
|
|
1440
|
+
if (sb.owner_id !== void 0 && tb.owner_id !== void 0 && sb.owner_id !== tb.owner_id) {
|
|
1441
|
+
issues.push({
|
|
1442
|
+
id: `storage-owner-${id}`,
|
|
1443
|
+
check: "storage",
|
|
1444
|
+
severity: "info",
|
|
1445
|
+
title: `Bucket owner mismatch: ${sb.name}`,
|
|
1446
|
+
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.`,
|
|
1447
|
+
sourceValue: { owner_id: sb.owner_id },
|
|
1448
|
+
targetValue: { owner_id: tb.owner_id }
|
|
1449
|
+
});
|
|
1450
|
+
}
|
|
1451
|
+
if (setClauses.length > 0) {
|
|
1452
|
+
const firstBucketIssue = issues.find(
|
|
1453
|
+
(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}`)
|
|
1454
|
+
);
|
|
1455
|
+
if (firstBucketIssue) {
|
|
1456
|
+
if (useApi) {
|
|
1457
|
+
firstBucketIssue.action = bucketAction(config, "PUT", `/${id}`, `Update bucket "${sb.name}"`, {
|
|
1458
|
+
public: sb.public,
|
|
1459
|
+
file_size_limit: sb.file_size_limit,
|
|
1460
|
+
allowed_mime_types: sb.allowed_mime_types
|
|
1461
|
+
});
|
|
1462
|
+
} else {
|
|
1463
|
+
const revertClauses = [];
|
|
1464
|
+
if (sb.public !== tb.public) revertClauses.push(`public = ${sqlLiteral(tb.public)}`);
|
|
1465
|
+
if (sb.file_size_limit !== tb.file_size_limit) revertClauses.push(`file_size_limit = ${sqlLiteral(tb.file_size_limit)}`);
|
|
1466
|
+
if (srcMimes !== tgtMimes) revertClauses.push(`allowed_mime_types = ${sqlLiteral(tb.allowed_mime_types)}`);
|
|
1467
|
+
firstBucketIssue.sql = {
|
|
1468
|
+
up: `UPDATE storage.buckets SET ${setClauses.join(", ")} WHERE id = ${sqlLiteral(id)};`,
|
|
1469
|
+
down: `UPDATE storage.buckets SET ${revertClauses.join(", ")} WHERE id = ${sqlLiteral(id)};`
|
|
1470
|
+
};
|
|
1471
|
+
}
|
|
1472
|
+
}
|
|
1473
|
+
}
|
|
1474
|
+
}
|
|
1475
|
+
return issues;
|
|
1476
|
+
}
|
|
1477
|
+
|
|
1478
|
+
// src/checks/auth.ts
|
|
1479
|
+
var AUTH_SETTINGS_PATH = "/auth/v1/settings";
|
|
1480
|
+
function resolveAuthSource(env) {
|
|
1481
|
+
if (env.apiUrl && env.accessToken) {
|
|
1482
|
+
const apiUrl = normalizeApiUrl(env.apiUrl);
|
|
1483
|
+
if (!apiUrl) {
|
|
1484
|
+
throw new CheckSkipped(
|
|
1485
|
+
`apiUrl "${env.apiUrl}" is not a usable http(s) gateway URL \u2014 expected something like https://supabase.example.com`
|
|
1486
|
+
);
|
|
1487
|
+
}
|
|
1488
|
+
return { kind: "self-hosted", apiUrl, key: env.accessToken };
|
|
1489
|
+
}
|
|
1490
|
+
if (env.projectRef && env.accessToken) {
|
|
1491
|
+
return { kind: "hosted", ref: env.projectRef, token: env.accessToken };
|
|
1492
|
+
}
|
|
1493
|
+
return null;
|
|
1494
|
+
}
|
|
1495
|
+
function normalizeApiUrl(raw) {
|
|
1496
|
+
let parsed;
|
|
1497
|
+
try {
|
|
1498
|
+
parsed = new URL(stripTrailingSlashes(raw.trim()));
|
|
1499
|
+
} catch {
|
|
1500
|
+
return null;
|
|
1501
|
+
}
|
|
1502
|
+
if (parsed.protocol !== "https:" && parsed.protocol !== "http:") return null;
|
|
1503
|
+
if (parsed.username || parsed.password) return null;
|
|
1504
|
+
return parsed.origin;
|
|
1505
|
+
}
|
|
1506
|
+
function stripTrailingSlashes(url) {
|
|
1507
|
+
let end = url.length;
|
|
1508
|
+
while (end > 0 && url[end - 1] === "/") end--;
|
|
1509
|
+
return url.slice(0, end);
|
|
1510
|
+
}
|
|
1511
|
+
function normalizeGoTrueSettings(raw) {
|
|
1512
|
+
const out = {};
|
|
1513
|
+
const external = raw.external;
|
|
1514
|
+
if (external && typeof external === "object" && !Array.isArray(external)) {
|
|
1515
|
+
for (const [provider, enabled] of Object.entries(external)) {
|
|
1516
|
+
out[`EXTERNAL_${provider.toUpperCase()}_ENABLED`] = enabled;
|
|
1517
|
+
}
|
|
1518
|
+
}
|
|
1519
|
+
for (const [key, value] of Object.entries(raw)) {
|
|
1520
|
+
if (key === "external") continue;
|
|
1521
|
+
out[key.toUpperCase()] = value;
|
|
1522
|
+
}
|
|
1523
|
+
return out;
|
|
1524
|
+
}
|
|
1525
|
+
var CRITICAL_KEYS = [
|
|
1526
|
+
"EXTERNAL_EMAIL_ENABLED",
|
|
1527
|
+
"EXTERNAL_PHONE_ENABLED",
|
|
1528
|
+
"JWT_EXP",
|
|
1529
|
+
"SECURITY_CAPTCHA_ENABLED",
|
|
1530
|
+
"MFA_ENABLED",
|
|
1531
|
+
"SECURITY_UPDATE_PASSWORD_REQUIRE_REAUTHENTICATION"
|
|
1532
|
+
];
|
|
1533
|
+
var AuthCheck = class extends Check {
|
|
1534
|
+
constructor(fetchFn = globalThis.fetch.bind(globalThis)) {
|
|
1535
|
+
super();
|
|
1536
|
+
this.fetchFn = fetchFn;
|
|
1537
|
+
}
|
|
1538
|
+
name = "auth";
|
|
1539
|
+
async scan(ctx) {
|
|
1540
|
+
const sourceSrc = resolveAuthSource(ctx.source);
|
|
1541
|
+
const targetSrc = resolveAuthSource(ctx.target);
|
|
1542
|
+
if (!sourceSrc || !targetSrc) {
|
|
1543
|
+
throw new CheckSkipped("no apiUrl/projectRef or accessToken configured");
|
|
1544
|
+
}
|
|
1545
|
+
if (sourceSrc.kind !== targetSrc.kind) {
|
|
1546
|
+
throw new CheckSkipped(
|
|
1547
|
+
"source and target are different deployment kinds (one self-hosted, one hosted) \u2014 auth config is not comparable"
|
|
1548
|
+
);
|
|
1549
|
+
}
|
|
1550
|
+
const [source, target] = await Promise.all([
|
|
1551
|
+
this.fetchAuthConfig(sourceSrc),
|
|
1552
|
+
this.fetchAuthConfig(targetSrc)
|
|
1553
|
+
]);
|
|
1554
|
+
return diffAuthConfig(source, target, targetSrc);
|
|
1555
|
+
}
|
|
1556
|
+
async fetchAuthConfig(src) {
|
|
1557
|
+
return src.kind === "hosted" ? this.fetchHostedAuthConfig(src.ref, src.token) : this.fetchSelfHostedAuthConfig(src.apiUrl, src.key);
|
|
1558
|
+
}
|
|
1559
|
+
async fetchHostedAuthConfig(projectRef, accessToken) {
|
|
1560
|
+
const url = `${SUPABASE_MGMT_API}/${encodeURIComponent(projectRef)}/config/auth`;
|
|
1561
|
+
const res = await this.fetchFn(url, {
|
|
1562
|
+
headers: { Authorization: `Bearer ${accessToken}` }
|
|
1563
|
+
});
|
|
1564
|
+
if (!res.ok) throw new Error(`Failed to fetch auth config for ${projectRef}: ${res.statusText}`);
|
|
1565
|
+
return res.json();
|
|
1566
|
+
}
|
|
1567
|
+
/**
|
|
1568
|
+
* GoTrue wants the service-role key in both `apikey` and `Authorization`.
|
|
1569
|
+
* The gateway routes on the former and GoTrue authorises on the latter.
|
|
1570
|
+
*/
|
|
1571
|
+
async fetchSelfHostedAuthConfig(apiUrl, serviceKey) {
|
|
1572
|
+
const url = new URL(AUTH_SETTINGS_PATH, apiUrl).toString();
|
|
1573
|
+
const res = await this.fetchFn(url, {
|
|
1574
|
+
headers: { apikey: serviceKey, Authorization: `Bearer ${serviceKey}` }
|
|
1575
|
+
});
|
|
1576
|
+
if (!res.ok) throw new Error(`Failed to fetch auth settings from ${apiUrl}: ${res.statusText}`);
|
|
1577
|
+
const raw = await res.json();
|
|
1578
|
+
return normalizeGoTrueSettings(raw);
|
|
1579
|
+
}
|
|
1580
|
+
};
|
|
1581
|
+
function diffAuthConfig(source, target, targetSrc) {
|
|
1582
|
+
const issues = [];
|
|
1583
|
+
const allKeys = /* @__PURE__ */ new Set([...Object.keys(source), ...Object.keys(target)]);
|
|
1584
|
+
for (const key of allKeys) {
|
|
1585
|
+
const sv = source[key];
|
|
1586
|
+
const tv = target[key];
|
|
1587
|
+
if (JSON.stringify(sv) !== JSON.stringify(tv)) {
|
|
1588
|
+
const isCritical = CRITICAL_KEYS.includes(key);
|
|
1589
|
+
const action = targetSrc.kind === "hosted" ? {
|
|
1590
|
+
method: "PATCH",
|
|
1591
|
+
url: `${SUPABASE_MGMT_API}/${encodeURIComponent(targetSrc.ref)}/config/auth`,
|
|
1592
|
+
headers: { Authorization: `Bearer ${targetSrc.token}` },
|
|
1593
|
+
body: { [key]: sv },
|
|
1594
|
+
label: `Set auth config "${key}" to ${JSON.stringify(sv)} in target`
|
|
1595
|
+
} : void 0;
|
|
1596
|
+
const remediation = action ? "" : " Self-hosted GoTrue is configured through its environment \u2014 update the target deployment and restart it.";
|
|
1597
|
+
issues.push({
|
|
1598
|
+
id: `auth-${key.toLowerCase()}`,
|
|
1599
|
+
check: "auth",
|
|
1600
|
+
severity: isCritical ? "critical" : "info",
|
|
1601
|
+
title: `Auth config mismatch: ${key}`,
|
|
1602
|
+
description: `"${key}" differs between source (${JSON.stringify(sv)}) and target (${JSON.stringify(tv)}).${remediation}`,
|
|
1603
|
+
sourceValue: sv,
|
|
1604
|
+
targetValue: tv,
|
|
1605
|
+
...action ? { action } : {}
|
|
1606
|
+
});
|
|
1607
|
+
}
|
|
1608
|
+
}
|
|
1609
|
+
return issues;
|
|
1610
|
+
}
|
|
1611
|
+
|
|
1612
|
+
// src/checks/cron.ts
|
|
1613
|
+
var CronCheck = class extends Check {
|
|
1614
|
+
constructor(queryFn = pgQuery) {
|
|
1615
|
+
super();
|
|
1616
|
+
this.queryFn = queryFn;
|
|
1617
|
+
}
|
|
1618
|
+
name = "cron";
|
|
1619
|
+
async scan(ctx) {
|
|
1620
|
+
const [source, target] = await Promise.all([
|
|
1621
|
+
this.fetchCronJobs(ctx.source.dbUrl),
|
|
1622
|
+
this.fetchCronJobs(ctx.target.dbUrl)
|
|
1623
|
+
]);
|
|
1624
|
+
if (!source.available && !target.available) {
|
|
1625
|
+
throw new CheckSkipped("pg_cron extension not installed");
|
|
1626
|
+
}
|
|
1627
|
+
return diffCronJobs(source.jobs, target.jobs);
|
|
1628
|
+
}
|
|
1629
|
+
async fetchCronJobs(dbUrl) {
|
|
1630
|
+
try {
|
|
1631
|
+
const jobs = await this.queryFn(dbUrl, CRON_SQL);
|
|
1632
|
+
return { jobs, available: true };
|
|
1633
|
+
} catch {
|
|
1634
|
+
return { jobs: [], available: false };
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
};
|
|
1638
|
+
var CRON_SQL = `
|
|
1639
|
+
SELECT jobid, schedule, command, nodename, nodeport, database, username, active, jobname
|
|
1640
|
+
FROM cron.job
|
|
1641
|
+
ORDER BY jobname, jobid
|
|
1642
|
+
`;
|
|
1643
|
+
function jobKey(j) {
|
|
1644
|
+
return j.jobname ?? `job-${j.jobid}`;
|
|
1645
|
+
}
|
|
1646
|
+
function diffCronJobs(source, target) {
|
|
1647
|
+
const issues = [];
|
|
1648
|
+
const sourceMap = new Map(source.map((j) => [jobKey(j), j]));
|
|
1649
|
+
const targetMap = new Map(target.map((j) => [jobKey(j), j]));
|
|
1650
|
+
for (const [key, j] of sourceMap) {
|
|
1651
|
+
if (!targetMap.has(key)) {
|
|
1652
|
+
issues.push({
|
|
1653
|
+
id: `cron-missing-${key}`,
|
|
1654
|
+
check: "cron",
|
|
1655
|
+
severity: "warning",
|
|
1656
|
+
title: `Missing cron job: ${key}`,
|
|
1657
|
+
description: `Cron job "${key}" (schedule: ${j.schedule}) exists in source but not in target.`,
|
|
1658
|
+
sourceValue: j,
|
|
1659
|
+
sql: {
|
|
1660
|
+
up: `SELECT cron.schedule('${key}', '${j.schedule}', $$${j.command}$$);`,
|
|
1661
|
+
down: `SELECT cron.unschedule('${key}');`
|
|
1662
|
+
}
|
|
1663
|
+
});
|
|
1664
|
+
}
|
|
1665
|
+
}
|
|
1666
|
+
for (const [key, j] of targetMap) {
|
|
1667
|
+
if (!sourceMap.has(key)) {
|
|
1668
|
+
issues.push({
|
|
1669
|
+
id: `cron-extra-${key}`,
|
|
1670
|
+
check: "cron",
|
|
1671
|
+
severity: "info",
|
|
1672
|
+
title: `Extra cron job: ${key}`,
|
|
1673
|
+
description: `Cron job "${key}" exists in target but not in source.`,
|
|
1674
|
+
targetValue: j
|
|
1675
|
+
});
|
|
1676
|
+
}
|
|
1677
|
+
}
|
|
1678
|
+
for (const [key, sj] of sourceMap) {
|
|
1679
|
+
const tj = targetMap.get(key);
|
|
1680
|
+
if (!tj) continue;
|
|
1681
|
+
if (sj.schedule !== tj.schedule || sj.command !== tj.command) {
|
|
1682
|
+
issues.push({
|
|
1683
|
+
id: `cron-modified-${key}`,
|
|
1684
|
+
check: "cron",
|
|
1685
|
+
severity: "warning",
|
|
1686
|
+
title: `Modified cron job: ${key}`,
|
|
1687
|
+
description: `Cron job "${key}" has different schedule or command between environments.`,
|
|
1688
|
+
sourceValue: sj,
|
|
1689
|
+
targetValue: tj,
|
|
1690
|
+
sql: {
|
|
1691
|
+
up: `SELECT cron.unschedule('${key}');
|
|
1692
|
+
SELECT cron.schedule('${key}', '${sj.schedule}', $$${sj.command.trim()}$$);`,
|
|
1693
|
+
down: `SELECT cron.unschedule('${key}');
|
|
1694
|
+
SELECT cron.schedule('${key}', '${tj.schedule}', $$${tj.command.trim()}$$);`
|
|
1695
|
+
}
|
|
1696
|
+
});
|
|
1697
|
+
}
|
|
1698
|
+
if (sj.active !== tj.active) {
|
|
1699
|
+
issues.push({
|
|
1700
|
+
id: `cron-active-${key}`,
|
|
1701
|
+
check: "cron",
|
|
1702
|
+
severity: "warning",
|
|
1703
|
+
title: `Cron job active state mismatch: ${key}`,
|
|
1704
|
+
description: `Cron job "${key}" is ${sj.active ? "active" : "inactive"} in source but ${tj.active ? "active" : "inactive"} in target.`,
|
|
1705
|
+
sourceValue: { active: sj.active },
|
|
1706
|
+
targetValue: { active: tj.active },
|
|
1707
|
+
sql: {
|
|
1708
|
+
up: `UPDATE cron.job SET active = ${sj.active} WHERE jobname = '${key}';`,
|
|
1709
|
+
down: `UPDATE cron.job SET active = ${tj.active} WHERE jobname = '${key}';`
|
|
1710
|
+
}
|
|
1711
|
+
});
|
|
1712
|
+
}
|
|
1713
|
+
}
|
|
1714
|
+
return issues;
|
|
1715
|
+
}
|
|
1716
|
+
|
|
1717
|
+
// src/checksum.ts
|
|
1718
|
+
async function getTableFingerprint(dbUrl, table, queryFn = pgQuery) {
|
|
1719
|
+
const sql = `
|
|
1720
|
+
SELECT count(*)::int AS row_count,
|
|
1721
|
+
coalesce(sum(('x' || substr(d, 1, 16))::bit(64)::bigint::numeric), 0)::text
|
|
1722
|
+
|| ':' ||
|
|
1723
|
+
coalesce(sum(('x' || substr(d, 17, 16))::bit(64)::bigint::numeric), 0)::text AS content
|
|
1724
|
+
FROM (SELECT md5(t::text) AS d FROM ${quoteIdent(table)} t) s
|
|
1725
|
+
`;
|
|
1726
|
+
const [row] = await queryFn(dbUrl, sql);
|
|
1727
|
+
return {
|
|
1728
|
+
table,
|
|
1729
|
+
rowCount: row.row_count,
|
|
1730
|
+
content: row.content
|
|
1731
|
+
};
|
|
1732
|
+
}
|
|
1733
|
+
async function tablesMatch(sourceUrl, targetUrl, table, queryFn = pgQuery) {
|
|
1734
|
+
const [source, target] = await Promise.all([
|
|
1735
|
+
getTableFingerprint(sourceUrl, table, queryFn),
|
|
1736
|
+
getTableFingerprint(targetUrl, table, queryFn)
|
|
1737
|
+
]);
|
|
1738
|
+
return source.rowCount === target.rowCount && source.content === target.content;
|
|
1739
|
+
}
|
|
1740
|
+
async function filterChangedTables(sourceUrl, targetUrl, tables, queryFn = pgQuery) {
|
|
1741
|
+
const changed = [];
|
|
1742
|
+
const skipped = [];
|
|
1743
|
+
const results = await Promise.all(
|
|
1744
|
+
tables.map(async (table) => {
|
|
1745
|
+
try {
|
|
1746
|
+
const match = await tablesMatch(sourceUrl, targetUrl, table, queryFn);
|
|
1747
|
+
return { table, match };
|
|
1748
|
+
} catch {
|
|
1749
|
+
return { table, match: false };
|
|
1750
|
+
}
|
|
1751
|
+
})
|
|
1752
|
+
);
|
|
1753
|
+
for (const { table, match } of results) {
|
|
1754
|
+
if (match) {
|
|
1755
|
+
skipped.push(table);
|
|
1756
|
+
} else {
|
|
1757
|
+
changed.push(table);
|
|
1758
|
+
}
|
|
1759
|
+
}
|
|
1760
|
+
return { changed, skipped };
|
|
1761
|
+
}
|
|
1762
|
+
|
|
1763
|
+
// src/checks/data.ts
|
|
1764
|
+
var DataCheck = class extends Check {
|
|
1765
|
+
constructor(runFn = runDbDiff, queryFn = pgQuery) {
|
|
1766
|
+
super();
|
|
1767
|
+
this.runFn = runFn;
|
|
1768
|
+
this.queryFn = queryFn;
|
|
1769
|
+
}
|
|
1770
|
+
name = "data";
|
|
1771
|
+
async scan(ctx) {
|
|
1772
|
+
const configured = ctx.config.checks?.data?.tables;
|
|
1773
|
+
if (!configured?.length) throw new CheckSkipped("no tables configured in checks.data.tables");
|
|
1774
|
+
const tables = applyTableFilter(configured, ctx.tableFilter);
|
|
1775
|
+
if (tables.length === 0) {
|
|
1776
|
+
throw new CheckSkipped("no configured data tables match the --tables / --exclude-tables filter");
|
|
1777
|
+
}
|
|
1778
|
+
const { changed } = await filterChangedTables(
|
|
1779
|
+
ctx.source.dbUrl,
|
|
1780
|
+
ctx.target.dbUrl,
|
|
1781
|
+
tables,
|
|
1782
|
+
this.queryFn
|
|
1783
|
+
);
|
|
1784
|
+
if (changed.length === 0) return [];
|
|
1785
|
+
try {
|
|
1786
|
+
const result = await this.runFn({
|
|
1787
|
+
sourceUrl: ctx.source.dbUrl,
|
|
1788
|
+
targetUrl: ctx.target.dbUrl,
|
|
1789
|
+
type: "data",
|
|
1790
|
+
include: "both",
|
|
1791
|
+
tables: changed,
|
|
1792
|
+
timeoutSeconds: ctx.target?.checks?.schema?.timeout
|
|
1793
|
+
});
|
|
1794
|
+
return sqlToIssues(result, "data");
|
|
1795
|
+
} catch (err) {
|
|
1796
|
+
if (err instanceof Error && err.message.includes("@dbdiff/cli is not installed")) {
|
|
1797
|
+
return [];
|
|
1798
|
+
}
|
|
1799
|
+
throw err;
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
};
|
|
1803
|
+
|
|
1804
|
+
// src/checks/webhooks.ts
|
|
1805
|
+
function keyOf(entry) {
|
|
1806
|
+
return `${entry.table_name}.${entry.name}`;
|
|
1807
|
+
}
|
|
1808
|
+
var WebhooksCheck = class extends Check {
|
|
1809
|
+
constructor(queryFn = pgQuery) {
|
|
1810
|
+
super();
|
|
1811
|
+
this.queryFn = queryFn;
|
|
1812
|
+
}
|
|
1813
|
+
name = "webhooks";
|
|
1814
|
+
async scan(ctx) {
|
|
1815
|
+
const [sourceHooks, targetHooks, sourceNet, targetNet] = await Promise.all([
|
|
1816
|
+
this.fetchHooks(ctx.source.dbUrl),
|
|
1817
|
+
this.fetchHooks(ctx.target.dbUrl),
|
|
1818
|
+
this.checkPgNet(ctx.source.dbUrl),
|
|
1819
|
+
this.checkPgNet(ctx.target.dbUrl)
|
|
1820
|
+
]);
|
|
1821
|
+
const issues = [];
|
|
1822
|
+
if (sourceNet && !targetNet) {
|
|
1823
|
+
issues.push({
|
|
1824
|
+
id: "webhooks-pgnet-missing",
|
|
1825
|
+
check: "webhooks",
|
|
1826
|
+
severity: "critical",
|
|
1827
|
+
title: "pg_net extension missing in target",
|
|
1828
|
+
description: "The pg_net extension is enabled in source but not in target. Database webhooks will silently fail.",
|
|
1829
|
+
sql: {
|
|
1830
|
+
up: "CREATE EXTENSION IF NOT EXISTS pg_net;",
|
|
1831
|
+
down: "DROP EXTENSION IF EXISTS pg_net;"
|
|
1832
|
+
}
|
|
1833
|
+
});
|
|
1834
|
+
}
|
|
1835
|
+
issues.push(...diffHooks(sourceHooks, targetHooks));
|
|
1836
|
+
return issues;
|
|
1837
|
+
}
|
|
1838
|
+
async fetchHooks(dbUrl) {
|
|
1839
|
+
try {
|
|
1840
|
+
return await this.queryFn(dbUrl, HOOKS_SQL);
|
|
1841
|
+
} catch {
|
|
1842
|
+
return [];
|
|
1843
|
+
}
|
|
1844
|
+
}
|
|
1845
|
+
async checkPgNet(dbUrl) {
|
|
1846
|
+
try {
|
|
1847
|
+
const rows = await this.queryFn(dbUrl, PG_NET_CHECK_SQL);
|
|
1848
|
+
return rows.length > 0;
|
|
1849
|
+
} catch {
|
|
1850
|
+
return false;
|
|
1851
|
+
}
|
|
1852
|
+
}
|
|
1853
|
+
};
|
|
1854
|
+
var HOOKS_SQL = `
|
|
1855
|
+
SELECT n.nspname || '.' || c.relname AS table_name,
|
|
1856
|
+
format('%I.%I', n.nspname, c.relname) AS table_ref,
|
|
1857
|
+
t.tgname AS name,
|
|
1858
|
+
pg_get_triggerdef(t.oid) AS definition
|
|
1859
|
+
FROM pg_trigger t
|
|
1860
|
+
JOIN pg_class c ON c.oid = t.tgrelid
|
|
1861
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
1862
|
+
JOIN pg_proc p ON p.oid = t.tgfoid
|
|
1863
|
+
JOIN pg_namespace pn ON pn.oid = p.pronamespace
|
|
1864
|
+
WHERE NOT t.tgisinternal
|
|
1865
|
+
AND pn.nspname = 'supabase_functions'
|
|
1866
|
+
AND p.proname = 'http_request'
|
|
1867
|
+
ORDER BY 1, 2
|
|
1868
|
+
`;
|
|
1869
|
+
var PG_NET_CHECK_SQL = `
|
|
1870
|
+
SELECT 1 FROM pg_extension WHERE extname = 'pg_net'
|
|
1871
|
+
`;
|
|
1872
|
+
function dropStatement(entry) {
|
|
1873
|
+
return `DROP TRIGGER IF EXISTS ${quoteName(entry.name)} ON ${entry.table_ref ?? entry.table_name};`;
|
|
1874
|
+
}
|
|
1875
|
+
function createStatement(entry) {
|
|
1876
|
+
return `${entry.definition.replace(/;\s*$/, "")};`;
|
|
1877
|
+
}
|
|
1878
|
+
function diffHooks(source, target) {
|
|
1879
|
+
const issues = [];
|
|
1880
|
+
const sourceMap = new Map(source.map((h) => [keyOf(h), h]));
|
|
1881
|
+
const targetMap = new Map(target.map((h) => [keyOf(h), h]));
|
|
1882
|
+
for (const [key, h] of sourceMap) {
|
|
1883
|
+
if (targetMap.has(key)) continue;
|
|
1884
|
+
issues.push({
|
|
1885
|
+
id: `webhooks-missing-${key}`,
|
|
1886
|
+
check: "webhooks",
|
|
1887
|
+
severity: "warning",
|
|
1888
|
+
title: `Missing webhook: ${h.name} on ${h.table_name}`,
|
|
1889
|
+
description: `Webhook "${h.name}" on ${h.table_name} exists in source but not in target.`,
|
|
1890
|
+
sourceValue: h,
|
|
1891
|
+
sql: {
|
|
1892
|
+
up: createStatement(h),
|
|
1893
|
+
down: dropStatement(h)
|
|
1894
|
+
}
|
|
1895
|
+
});
|
|
1896
|
+
}
|
|
1897
|
+
for (const [key, h] of targetMap) {
|
|
1898
|
+
if (sourceMap.has(key)) continue;
|
|
1899
|
+
issues.push({
|
|
1900
|
+
id: `webhooks-extra-${key}`,
|
|
1901
|
+
check: "webhooks",
|
|
1902
|
+
severity: "info",
|
|
1903
|
+
title: `Extra webhook: ${h.name} on ${h.table_name}`,
|
|
1904
|
+
description: `Webhook "${h.name}" on ${h.table_name} exists in target but not in source.`,
|
|
1905
|
+
targetValue: h,
|
|
1906
|
+
sql: {
|
|
1907
|
+
up: dropStatement(h),
|
|
1908
|
+
// Recoverable, unlike before: the target's own definition is the way back.
|
|
1909
|
+
down: createStatement(h)
|
|
1910
|
+
}
|
|
1911
|
+
});
|
|
1912
|
+
}
|
|
1913
|
+
for (const [key, sh] of sourceMap) {
|
|
1914
|
+
const th = targetMap.get(key);
|
|
1915
|
+
if (!th || normalise(sh.definition) === normalise(th.definition)) continue;
|
|
1916
|
+
issues.push({
|
|
1917
|
+
id: `webhooks-modified-${key}`,
|
|
1918
|
+
check: "webhooks",
|
|
1919
|
+
severity: "warning",
|
|
1920
|
+
title: `Modified webhook: ${sh.name} on ${sh.table_name}`,
|
|
1921
|
+
description: `Webhook "${sh.name}" on ${sh.table_name} is configured differently in source and target.`,
|
|
1922
|
+
sourceValue: sh,
|
|
1923
|
+
targetValue: th,
|
|
1924
|
+
sql: {
|
|
1925
|
+
up: [dropStatement(th), createStatement(sh)].join("\n"),
|
|
1926
|
+
down: [dropStatement(sh), createStatement(th)].join("\n")
|
|
1927
|
+
}
|
|
1928
|
+
});
|
|
1929
|
+
}
|
|
1930
|
+
return issues;
|
|
1931
|
+
}
|
|
1932
|
+
function normalise(definition) {
|
|
1933
|
+
return definition.replace(/\s+/g, " ").trim();
|
|
1934
|
+
}
|
|
1935
|
+
|
|
1936
|
+
// src/checks/vault.ts
|
|
1937
|
+
var STRUCTURAL_ATTRS = ["name", "description", "unique_name"];
|
|
1938
|
+
var ENV_SPECIFIC_ATTRS = ["secret", "nonce", "key_id"];
|
|
1939
|
+
var VaultCheck = class extends Check {
|
|
1940
|
+
constructor(queryFn = pgQuery) {
|
|
1941
|
+
super();
|
|
1942
|
+
this.queryFn = queryFn;
|
|
1943
|
+
}
|
|
1944
|
+
name = "vault";
|
|
1945
|
+
async scan(ctx) {
|
|
1946
|
+
const [source, target] = await Promise.all([
|
|
1947
|
+
this.fetchSecrets(ctx.source.dbUrl),
|
|
1948
|
+
this.fetchSecrets(ctx.target.dbUrl)
|
|
1949
|
+
]);
|
|
1950
|
+
return diffVaultSecrets(source, target);
|
|
1951
|
+
}
|
|
1952
|
+
async fetchSecrets(dbUrl) {
|
|
1953
|
+
try {
|
|
1954
|
+
return await this.queryFn(dbUrl, VAULT_SQL);
|
|
1955
|
+
} catch {
|
|
1956
|
+
try {
|
|
1957
|
+
const rows = await this.queryFn(dbUrl, VAULT_SQL_FALLBACK);
|
|
1958
|
+
return rows.map((r) => ({ ...r, unique_name: null }));
|
|
1959
|
+
} catch {
|
|
1960
|
+
return [];
|
|
1961
|
+
}
|
|
1962
|
+
}
|
|
1963
|
+
}
|
|
1964
|
+
};
|
|
1965
|
+
var VAULT_SQL = `
|
|
1966
|
+
SELECT id, name, description, secret, unique_name, nonce, key_id,
|
|
1967
|
+
created_at::text, updated_at::text
|
|
1968
|
+
FROM vault.secrets
|
|
1969
|
+
ORDER BY name, id
|
|
1970
|
+
`;
|
|
1971
|
+
var VAULT_SQL_FALLBACK = `
|
|
1972
|
+
SELECT id, name, description, secret, nonce, key_id,
|
|
1973
|
+
created_at::text, updated_at::text
|
|
1974
|
+
FROM vault.secrets
|
|
1975
|
+
ORDER BY name, id
|
|
1976
|
+
`;
|
|
1977
|
+
function secretKey(s) {
|
|
1978
|
+
return s.unique_name ?? s.name ?? s.id;
|
|
1979
|
+
}
|
|
1980
|
+
function diffVaultSecrets(source, target) {
|
|
1981
|
+
const issues = [];
|
|
1982
|
+
const sourceMap = new Map(source.map((s) => [secretKey(s), s]));
|
|
1983
|
+
const targetMap = new Map(target.map((s) => [secretKey(s), s]));
|
|
1984
|
+
for (const [key, s] of sourceMap) {
|
|
1985
|
+
if (!targetMap.has(key)) {
|
|
1986
|
+
issues.push({
|
|
1987
|
+
id: `vault-missing-${key}`,
|
|
1988
|
+
check: "vault",
|
|
1989
|
+
severity: "warning",
|
|
1990
|
+
title: `Missing vault secret: ${key}`,
|
|
1991
|
+
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.`,
|
|
1992
|
+
sourceValue: { name: s.name, description: s.description, unique_name: s.unique_name },
|
|
1993
|
+
// No `sql`. The value exists only in the source and Vault will not give
|
|
1994
|
+
// it up, so there is nothing to generate — and what was generated was
|
|
1995
|
+
// `vault.create_secret('PLACEHOLDER_VALUE', …)`, which `--apply` ran.
|
|
1996
|
+
// The target then held a live secret with a bogus value, so anything
|
|
1997
|
+
// reading it failed at runtime instead of failing loudly as absent; and
|
|
1998
|
+
// because the secret now existed, the next diff stopped asking for the
|
|
1999
|
+
// manual step at all (issue #91).
|
|
2000
|
+
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)}` : ""});`
|
|
2001
|
+
});
|
|
2002
|
+
}
|
|
2003
|
+
}
|
|
2004
|
+
for (const [key] of targetMap) {
|
|
2005
|
+
if (!sourceMap.has(key)) {
|
|
2006
|
+
issues.push({
|
|
2007
|
+
id: `vault-extra-${key}`,
|
|
2008
|
+
check: "vault",
|
|
2009
|
+
severity: "info",
|
|
2010
|
+
title: `Extra vault secret: ${key}`,
|
|
2011
|
+
description: `Secret "${key}" exists in target but not in source.`
|
|
2012
|
+
});
|
|
2013
|
+
}
|
|
2014
|
+
}
|
|
2015
|
+
for (const [key, ss] of sourceMap) {
|
|
2016
|
+
const ts = targetMap.get(key);
|
|
2017
|
+
if (!ts) continue;
|
|
2018
|
+
const diffs = [];
|
|
2019
|
+
for (const attr of STRUCTURAL_ATTRS) {
|
|
2020
|
+
if (String(ss[attr] ?? "") !== String(ts[attr] ?? "")) {
|
|
2021
|
+
diffs.push(`${attr}: "${ss[attr] ?? ""}" \u2192 "${ts[attr] ?? ""}"`);
|
|
2022
|
+
}
|
|
2023
|
+
}
|
|
2024
|
+
for (const attr of ENV_SPECIFIC_ATTRS) {
|
|
2025
|
+
if (String(ss[attr] ?? "") !== String(ts[attr] ?? "")) {
|
|
2026
|
+
diffs.push(`${attr}: differs (environment-specific)`);
|
|
2027
|
+
}
|
|
2028
|
+
}
|
|
2029
|
+
if (diffs.length > 0) {
|
|
2030
|
+
const hasStructuralDiff = STRUCTURAL_ATTRS.some(
|
|
2031
|
+
(attr) => String(ss[attr] ?? "") !== String(ts[attr] ?? "")
|
|
2032
|
+
);
|
|
2033
|
+
issues.push({
|
|
2034
|
+
id: `vault-modified-${key}`,
|
|
2035
|
+
check: "vault",
|
|
2036
|
+
severity: hasStructuralDiff ? "warning" : "info",
|
|
2037
|
+
title: `Modified vault secret: ${key}`,
|
|
2038
|
+
description: `Secret "${key}" differs between environments:
|
|
2039
|
+
${diffs.join("\n")}`,
|
|
2040
|
+
sourceValue: { name: ss.name, description: ss.description, unique_name: ss.unique_name },
|
|
2041
|
+
targetValue: { name: ts.name, description: ts.description, unique_name: ts.unique_name },
|
|
2042
|
+
sql: hasStructuralDiff ? {
|
|
2043
|
+
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 ?? "")}` : ""});`,
|
|
2044
|
+
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 ?? "")}` : ""});`
|
|
2045
|
+
} : void 0
|
|
2046
|
+
});
|
|
2047
|
+
}
|
|
2048
|
+
}
|
|
2049
|
+
return issues;
|
|
2050
|
+
}
|
|
2051
|
+
|
|
2052
|
+
// src/checks/extensions.ts
|
|
2053
|
+
var ExtensionsCheck = class extends Check {
|
|
2054
|
+
constructor(queryFn = pgQuery) {
|
|
2055
|
+
super();
|
|
2056
|
+
this.queryFn = queryFn;
|
|
2057
|
+
}
|
|
2058
|
+
name = "extensions";
|
|
2059
|
+
async scan(ctx) {
|
|
2060
|
+
const [source, target] = await Promise.all([
|
|
2061
|
+
this.fetchExtensions(ctx.source.dbUrl),
|
|
2062
|
+
this.fetchExtensions(ctx.target.dbUrl)
|
|
2063
|
+
]);
|
|
2064
|
+
return diffExtensions(source, target);
|
|
2065
|
+
}
|
|
2066
|
+
async fetchExtensions(dbUrl) {
|
|
2067
|
+
return await this.queryFn(dbUrl, EXTENSIONS_SQL);
|
|
2068
|
+
}
|
|
2069
|
+
};
|
|
2070
|
+
var EXTENSIONS_SQL = `
|
|
2071
|
+
SELECT e.extname AS name,
|
|
2072
|
+
e.extversion AS version,
|
|
2073
|
+
n.nspname AS schema
|
|
2074
|
+
FROM pg_extension e
|
|
2075
|
+
JOIN pg_namespace n ON n.oid = e.extnamespace
|
|
2076
|
+
ORDER BY e.extname
|
|
2077
|
+
`;
|
|
2078
|
+
function diffExtensions(source, target) {
|
|
2079
|
+
const issues = [];
|
|
2080
|
+
const sourceMap = new Map(source.map((e) => [e.name, e]));
|
|
2081
|
+
const targetMap = new Map(target.map((e) => [e.name, e]));
|
|
2082
|
+
for (const [name, ext] of sourceMap) {
|
|
2083
|
+
if (!targetMap.has(name)) {
|
|
2084
|
+
issues.push({
|
|
2085
|
+
id: `ext-missing-${name}`,
|
|
2086
|
+
check: "extensions",
|
|
2087
|
+
severity: "warning",
|
|
2088
|
+
title: `Missing extension: ${name}`,
|
|
2089
|
+
description: `Extension "${name}" (v${ext.version}) is enabled in source (schema: ${ext.schema}) but not in target.`,
|
|
2090
|
+
sourceValue: ext,
|
|
2091
|
+
sql: {
|
|
2092
|
+
up: `CREATE EXTENSION IF NOT EXISTS ${quoteName(name)}${ext.schema !== "public" ? ` SCHEMA ${quoteName(ext.schema)}` : ""};`,
|
|
2093
|
+
down: `DROP EXTENSION IF EXISTS ${quoteName(name)};`
|
|
2094
|
+
}
|
|
2095
|
+
});
|
|
2096
|
+
}
|
|
2097
|
+
}
|
|
2098
|
+
for (const [name, ext] of targetMap) {
|
|
2099
|
+
if (!sourceMap.has(name)) {
|
|
2100
|
+
issues.push({
|
|
2101
|
+
id: `ext-extra-${name}`,
|
|
2102
|
+
check: "extensions",
|
|
2103
|
+
severity: "info",
|
|
2104
|
+
title: `Extra extension: ${name}`,
|
|
2105
|
+
description: `Extension "${name}" (v${ext.version}) is enabled in target (schema: ${ext.schema}) but not in source.`,
|
|
2106
|
+
targetValue: ext
|
|
2107
|
+
});
|
|
2108
|
+
}
|
|
2109
|
+
}
|
|
2110
|
+
for (const [name, srcExt] of sourceMap) {
|
|
2111
|
+
const tgtExt = targetMap.get(name);
|
|
2112
|
+
if (!tgtExt) continue;
|
|
2113
|
+
if (srcExt.version !== tgtExt.version) {
|
|
2114
|
+
issues.push({
|
|
2115
|
+
id: `ext-version-${name}`,
|
|
2116
|
+
check: "extensions",
|
|
2117
|
+
severity: "info",
|
|
2118
|
+
title: `Extension version mismatch: ${name}`,
|
|
2119
|
+
description: `Extension "${name}" is v${srcExt.version} in source but v${tgtExt.version} in target.`,
|
|
2120
|
+
sourceValue: srcExt,
|
|
2121
|
+
targetValue: tgtExt,
|
|
2122
|
+
sql: {
|
|
2123
|
+
up: `ALTER EXTENSION ${quoteName(name)} UPDATE TO ${quoteLiteral(srcExt.version)};`,
|
|
2124
|
+
down: `ALTER EXTENSION ${quoteName(name)} UPDATE TO ${quoteLiteral(tgtExt.version)};`
|
|
2125
|
+
}
|
|
2126
|
+
});
|
|
2127
|
+
}
|
|
2128
|
+
}
|
|
2129
|
+
return issues;
|
|
2130
|
+
}
|
|
2131
|
+
|
|
2132
|
+
// src/checks/roles.ts
|
|
2133
|
+
var PLATFORM_ROLES = [
|
|
2134
|
+
"postgres",
|
|
2135
|
+
"supabase_admin",
|
|
2136
|
+
"authenticator",
|
|
2137
|
+
"supabase_auth_admin",
|
|
2138
|
+
"supabase_storage_admin",
|
|
2139
|
+
"dashboard_user",
|
|
2140
|
+
"pgbouncer",
|
|
2141
|
+
"supavisor",
|
|
2142
|
+
// Created by Supabase's own images for Edge Functions, Realtime, read
|
|
2143
|
+
// replicas and logical replication. Diffing a project against plain
|
|
2144
|
+
// PostgreSQL offered to create all four on the target.
|
|
2145
|
+
"supabase_functions_admin",
|
|
2146
|
+
"supabase_realtime_admin",
|
|
2147
|
+
"supabase_read_only_user",
|
|
2148
|
+
"supabase_replication_admin"
|
|
2149
|
+
];
|
|
2150
|
+
var API_ROLES = ["anon", "authenticated", "service_role"];
|
|
2151
|
+
var quoted = (names) => names.map((n) => `'${n.replace(/'/g, "''")}'`).join(", ");
|
|
2152
|
+
var ROLES_SQL = `
|
|
2153
|
+
SELECT
|
|
2154
|
+
rolname, rolsuper, rolinherit, rolcreaterole, rolcreatedb,
|
|
2155
|
+
rolcanlogin, rolreplication, rolbypassrls, rolconnlimit,
|
|
2156
|
+
rolvaliduntil::text AS rolvaliduntil
|
|
2157
|
+
FROM pg_roles
|
|
2158
|
+
WHERE NOT (rolname LIKE 'pg_%')
|
|
2159
|
+
AND rolname NOT IN (${quoted([...PLATFORM_ROLES, ...API_ROLES])})
|
|
2160
|
+
AND rolname <> current_user
|
|
2161
|
+
ORDER BY rolname
|
|
2162
|
+
`;
|
|
2163
|
+
function grantSchemaFilter(ignoreSchemas) {
|
|
2164
|
+
const excluded = [.../* @__PURE__ */ new Set([...SUPABASE_PLATFORM_SCHEMAS, ...ignoreSchemas])];
|
|
2165
|
+
return `NOT IN (${quoted(excluded)})`;
|
|
2166
|
+
}
|
|
2167
|
+
var grantsSql = (ignoreSchemas) => `
|
|
2168
|
+
SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
|
|
2169
|
+
n.nspname AS table_schema, c.relname AS table_name,
|
|
2170
|
+
a.privilege_type, a.is_grantable
|
|
2171
|
+
FROM pg_class c
|
|
2172
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
2173
|
+
CROSS JOIN LATERAL aclexplode(c.relacl) a
|
|
2174
|
+
WHERE c.relacl IS NOT NULL
|
|
2175
|
+
AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
|
|
2176
|
+
AND a.grantee <> c.relowner
|
|
2177
|
+
AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
|
|
2178
|
+
AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))
|
|
2179
|
+
AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')
|
|
2180
|
+
ORDER BY 1, 2, 3, 4
|
|
2181
|
+
`;
|
|
2182
|
+
var columnGrantsSql = (ignoreSchemas) => `
|
|
2183
|
+
SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
|
|
2184
|
+
n.nspname AS table_schema, c.relname AS table_name, att.attname AS column_name,
|
|
2185
|
+
a.privilege_type, a.is_grantable
|
|
2186
|
+
FROM pg_attribute att
|
|
2187
|
+
JOIN pg_class c ON c.oid = att.attrelid
|
|
2188
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
2189
|
+
CROSS JOIN LATERAL aclexplode(att.attacl) a
|
|
2190
|
+
WHERE att.attacl IS NOT NULL AND att.attnum > 0 AND NOT att.attisdropped
|
|
2191
|
+
AND c.relkind IN ('r', 'p', 'v', 'm', 'f')
|
|
2192
|
+
AND a.grantee <> c.relowner
|
|
2193
|
+
AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
|
|
2194
|
+
AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (${quoted(PLATFORM_ROLES)}))
|
|
2195
|
+
AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg_%')
|
|
2196
|
+
ORDER BY 1, 2, 3, 4, 5
|
|
2197
|
+
`;
|
|
2198
|
+
var relationsSql = (ignoreSchemas) => `
|
|
2199
|
+
SELECT n.nspname AS table_schema, c.relname AS table_name
|
|
2200
|
+
FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
2201
|
+
WHERE c.relkind IN ('r', 'p', 'v', 'm', 'f')
|
|
2202
|
+
AND n.nspname ${grantSchemaFilter(ignoreSchemas)}
|
|
2203
|
+
`;
|
|
2204
|
+
var DEFAULT_TABLE_GRANTS_SQL = `
|
|
2205
|
+
SELECT n.nspname AS table_schema,
|
|
2206
|
+
CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
|
|
2207
|
+
a.privilege_type, a.is_grantable
|
|
2208
|
+
FROM pg_default_acl d
|
|
2209
|
+
LEFT JOIN pg_namespace n ON n.oid = d.defaclnamespace
|
|
2210
|
+
CROSS JOIN LATERAL aclexplode(d.defaclacl) a
|
|
2211
|
+
WHERE d.defaclobjtype = 'r' AND d.defaclrole = (SELECT oid FROM pg_roles WHERE rolname = current_user)
|
|
2212
|
+
AND a.grantee <> d.defaclrole
|
|
2213
|
+
`;
|
|
2214
|
+
function grantedByDefault(relations, defaults) {
|
|
2215
|
+
const present = new Set(relations.map((r) => `${r.table_schema}.${r.table_name}`));
|
|
2216
|
+
const granted = new Set(defaults.map((d) => `${d.table_schema ?? "*"}|${d.grantee}|${d.privilege_type}|${Boolean(d.is_grantable)}`));
|
|
2217
|
+
return (g) => !g.column_name && !present.has(`${g.table_schema}.${g.table_name}`) && [g.table_schema, "*"].some((schema) => granted.has(`${schema}|${g.grantee}|${g.privilege_type}|${Boolean(g.is_grantable)}`));
|
|
2218
|
+
}
|
|
2219
|
+
function defaultGrantsToRevoke(sourceRelations, targetRelations, defaults, sourceGrants) {
|
|
2220
|
+
const present = new Set(targetRelations.map((r) => `${r.table_schema}.${r.table_name}`));
|
|
2221
|
+
const held = new Set(sourceGrants.filter((g) => !g.column_name).map((g) => `${g.table_schema}.${g.table_name}|${g.grantee}|${g.privilege_type}`));
|
|
2222
|
+
const issues = [];
|
|
2223
|
+
for (const rel of sourceRelations) {
|
|
2224
|
+
const name = `${rel.table_schema}.${rel.table_name}`;
|
|
2225
|
+
if (present.has(name)) continue;
|
|
2226
|
+
const extra = /* @__PURE__ */ new Map();
|
|
2227
|
+
for (const d of defaults) {
|
|
2228
|
+
if (d.table_schema !== null && d.table_schema !== rel.table_schema) continue;
|
|
2229
|
+
if (held.has(`${name}|${d.grantee}|${d.privilege_type}`)) continue;
|
|
2230
|
+
extra.set(d.grantee, (extra.get(d.grantee) ?? /* @__PURE__ */ new Set()).add(d.privilege_type));
|
|
2231
|
+
}
|
|
2232
|
+
for (const [grantee, privileges] of [...extra].sort(([a], [b]) => a.localeCompare(b))) {
|
|
2233
|
+
const gs = [...privileges].sort().map((privilege_type) => ({ grantee, table_schema: rel.table_schema, table_name: rel.table_name, privilege_type, is_grantable: false }));
|
|
2234
|
+
issues.push({
|
|
2235
|
+
id: `roles-grant-default-${grantee}.${name}`,
|
|
2236
|
+
check: "roles",
|
|
2237
|
+
severity: extraGrantSeverity(grantee),
|
|
2238
|
+
title: `Default grants to take back: ${describeGroup(gs)}`,
|
|
2239
|
+
description: `Creating ${name} on the target gives ${grantee} what its default privileges grant. The source does not grant "${describeGroup(gs)}", so it is revoked once the table exists.`,
|
|
2240
|
+
targetValue: gs,
|
|
2241
|
+
sql: {
|
|
2242
|
+
up: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(grantee)};`,
|
|
2243
|
+
down: `GRANT ${groupTarget(gs)} TO ${granteeSql(grantee)};`
|
|
2244
|
+
}
|
|
2245
|
+
});
|
|
2246
|
+
}
|
|
2247
|
+
}
|
|
2248
|
+
return issues;
|
|
2249
|
+
}
|
|
2250
|
+
var OPEN_GRANTEES = /* @__PURE__ */ new Set(["anon", "authenticated", "PUBLIC"]);
|
|
2251
|
+
function extraGrantSeverity(grantee) {
|
|
2252
|
+
return OPEN_GRANTEES.has(grantee) ? "critical" : "warning";
|
|
2253
|
+
}
|
|
2254
|
+
var RolesCheck = class extends Check {
|
|
2255
|
+
constructor(queryFn = pgQuery) {
|
|
2256
|
+
super();
|
|
2257
|
+
this.queryFn = queryFn;
|
|
2258
|
+
}
|
|
2259
|
+
name = "roles";
|
|
2260
|
+
async scan(ctx) {
|
|
2261
|
+
const ignore = ctx.config.ignoreSchemas ?? [];
|
|
2262
|
+
const version = async (url) => Number((await this.queryFn(url, `SELECT current_setting('server_version_num') AS v`))[0]?.v ?? 0);
|
|
2263
|
+
const [
|
|
2264
|
+
sourceRoles,
|
|
2265
|
+
targetRoles,
|
|
2266
|
+
sourceGrants,
|
|
2267
|
+
targetGrants,
|
|
2268
|
+
sourceColumns,
|
|
2269
|
+
targetColumns,
|
|
2270
|
+
sourceVersion,
|
|
2271
|
+
targetVersion,
|
|
2272
|
+
sourceRelations,
|
|
2273
|
+
targetRelations,
|
|
2274
|
+
targetDefaults
|
|
2275
|
+
] = await Promise.all([
|
|
2276
|
+
this.queryFn(ctx.source.dbUrl, ROLES_SQL),
|
|
2277
|
+
this.queryFn(ctx.target.dbUrl, ROLES_SQL),
|
|
2278
|
+
this.queryFn(ctx.source.dbUrl, grantsSql(ignore)),
|
|
2279
|
+
this.queryFn(ctx.target.dbUrl, grantsSql(ignore)),
|
|
2280
|
+
this.queryFn(ctx.source.dbUrl, columnGrantsSql(ignore)),
|
|
2281
|
+
this.queryFn(ctx.target.dbUrl, columnGrantsSql(ignore)),
|
|
2282
|
+
version(ctx.source.dbUrl),
|
|
2283
|
+
version(ctx.target.dbUrl),
|
|
2284
|
+
this.queryFn(ctx.source.dbUrl, relationsSql(ignore)),
|
|
2285
|
+
this.queryFn(ctx.target.dbUrl, relationsSql(ignore)),
|
|
2286
|
+
this.queryFn(ctx.target.dbUrl, DEFAULT_TABLE_GRANTS_SQL)
|
|
2287
|
+
]);
|
|
2288
|
+
const comparable = comparablePrivileges(sourceVersion, targetVersion);
|
|
2289
|
+
const byDefault = grantedByDefault(targetRelations ?? [], targetDefaults ?? []);
|
|
2290
|
+
return [
|
|
2291
|
+
...diffRoles(sourceRoles, targetRoles),
|
|
2292
|
+
...diffGrants(
|
|
2293
|
+
[...sourceGrants ?? [], ...sourceColumns ?? []].filter((g) => comparable(g) && !byDefault(g)),
|
|
2294
|
+
[...targetGrants ?? [], ...targetColumns ?? []].filter(comparable)
|
|
2295
|
+
),
|
|
2296
|
+
...defaultGrantsToRevoke(
|
|
2297
|
+
sourceRelations ?? [],
|
|
2298
|
+
targetRelations ?? [],
|
|
2299
|
+
(targetDefaults ?? []).filter((d) => comparable(d)),
|
|
2300
|
+
sourceGrants ?? []
|
|
2301
|
+
)
|
|
2302
|
+
];
|
|
2303
|
+
}
|
|
2304
|
+
};
|
|
2305
|
+
function roleAttrs(r) {
|
|
2306
|
+
const attrs = [];
|
|
2307
|
+
if (r.rolsuper) attrs.push("SUPERUSER");
|
|
2308
|
+
if (r.rolinherit) attrs.push("INHERIT");
|
|
2309
|
+
if (r.rolcreaterole) attrs.push("CREATEROLE");
|
|
2310
|
+
if (r.rolcreatedb) attrs.push("CREATEDB");
|
|
2311
|
+
if (r.rolcanlogin) attrs.push("LOGIN");
|
|
2312
|
+
if (r.rolreplication) attrs.push("REPLICATION");
|
|
2313
|
+
if (r.rolbypassrls) attrs.push("BYPASSRLS");
|
|
2314
|
+
if (r.rolconnlimit >= 0) attrs.push(`CONNECTION LIMIT ${r.rolconnlimit}`);
|
|
2315
|
+
if (r.rolvaliduntil) attrs.push(`VALID UNTIL '${r.rolvaliduntil}'`);
|
|
2316
|
+
return attrs.length > 0 ? attrs.join(" ") : "NOLOGIN";
|
|
2317
|
+
}
|
|
2318
|
+
function rolesEqual(a, b) {
|
|
2319
|
+
return a.rolsuper === b.rolsuper && a.rolinherit === b.rolinherit && a.rolcreaterole === b.rolcreaterole && a.rolcreatedb === b.rolcreatedb && a.rolcanlogin === b.rolcanlogin && a.rolreplication === b.rolreplication && a.rolbypassrls === b.rolbypassrls && a.rolconnlimit === b.rolconnlimit && a.rolvaliduntil === b.rolvaliduntil;
|
|
2320
|
+
}
|
|
2321
|
+
function diffRoles(source, target) {
|
|
2322
|
+
const issues = [];
|
|
2323
|
+
const sourceMap = new Map(source.map((r) => [r.rolname, r]));
|
|
2324
|
+
const targetMap = new Map(target.map((r) => [r.rolname, r]));
|
|
2325
|
+
for (const [name, sr] of sourceMap) {
|
|
2326
|
+
if (!targetMap.has(name)) {
|
|
2327
|
+
issues.push({
|
|
2328
|
+
id: `roles-missing-${name}`,
|
|
2329
|
+
check: "roles",
|
|
2330
|
+
severity: "critical",
|
|
2331
|
+
title: `Missing role: ${name}`,
|
|
2332
|
+
description: `Role "${name}" exists in source but is missing from target. Any RLS policies or grants referencing this role will be silently ineffective.`,
|
|
2333
|
+
sourceValue: sr,
|
|
2334
|
+
sql: {
|
|
2335
|
+
up: `CREATE ROLE ${quoteName(name)} ${roleAttrs(sr)};`,
|
|
2336
|
+
down: `DROP ROLE IF EXISTS ${quoteName(name)};`
|
|
2337
|
+
}
|
|
2338
|
+
});
|
|
2339
|
+
}
|
|
2340
|
+
}
|
|
2341
|
+
for (const [name, tr] of targetMap) {
|
|
2342
|
+
if (!sourceMap.has(name)) {
|
|
2343
|
+
issues.push({
|
|
2344
|
+
id: `roles-extra-${name}`,
|
|
2345
|
+
check: "roles",
|
|
2346
|
+
severity: "warning",
|
|
2347
|
+
title: `Extra role: ${name}`,
|
|
2348
|
+
description: `Role "${name}" exists in target but not in source.`,
|
|
2349
|
+
targetValue: tr,
|
|
2350
|
+
sql: {
|
|
2351
|
+
up: `DROP ROLE IF EXISTS ${quoteName(name)};`,
|
|
2352
|
+
down: `CREATE ROLE ${quoteName(name)} ${roleAttrs(tr)};`
|
|
2353
|
+
}
|
|
2354
|
+
});
|
|
2355
|
+
}
|
|
2356
|
+
}
|
|
2357
|
+
for (const [name, sr] of sourceMap) {
|
|
2358
|
+
const tr = targetMap.get(name);
|
|
2359
|
+
if (tr && !rolesEqual(sr, tr)) {
|
|
2360
|
+
issues.push({
|
|
2361
|
+
id: `roles-modified-${name}`,
|
|
2362
|
+
check: "roles",
|
|
2363
|
+
severity: "warning",
|
|
2364
|
+
title: `Modified role: ${name}`,
|
|
2365
|
+
description: `Role "${name}" has different attributes between source and target.`,
|
|
2366
|
+
sourceValue: sr,
|
|
2367
|
+
targetValue: tr,
|
|
2368
|
+
sql: {
|
|
2369
|
+
up: `ALTER ROLE ${quoteName(name)} ${roleAttrs(sr)};`,
|
|
2370
|
+
down: `ALTER ROLE ${quoteName(name)} ${roleAttrs(tr)};`
|
|
2371
|
+
}
|
|
2372
|
+
});
|
|
2373
|
+
}
|
|
2374
|
+
}
|
|
2375
|
+
return issues;
|
|
2376
|
+
}
|
|
2377
|
+
function grantKey(g) {
|
|
2378
|
+
const column = g.column_name ? `.${g.column_name}` : "";
|
|
2379
|
+
return `${g.grantee}.${g.table_schema}.${g.table_name}${column}.${g.privilege_type}`;
|
|
2380
|
+
}
|
|
2381
|
+
function granteeSql(grantee) {
|
|
2382
|
+
return grantee === "PUBLIC" ? "PUBLIC" : `"${grantee.replace(/"/g, '""')}"`;
|
|
2383
|
+
}
|
|
2384
|
+
function grantTarget(g) {
|
|
2385
|
+
const column = g.column_name ? ` ("${g.column_name.replace(/"/g, '""')}")` : "";
|
|
2386
|
+
return `${g.privilege_type}${column} ON ${quoteName(g.table_schema)}.${quoteName(g.table_name)}`;
|
|
2387
|
+
}
|
|
2388
|
+
function describeGrant(g) {
|
|
2389
|
+
const column = g.column_name ? `(${g.column_name}) ` : "";
|
|
2390
|
+
return `${g.privilege_type} ${column}ON ${g.table_schema}.${g.table_name} TO ${g.grantee}`;
|
|
2391
|
+
}
|
|
2392
|
+
var grantSql = (g, withOption = g.is_grantable) => `GRANT ${grantTarget(g)} TO ${granteeSql(g.grantee)}${withOption ? " WITH GRANT OPTION" : ""};`;
|
|
2393
|
+
function comparablePrivileges(sourceVersion, targetVersion) {
|
|
2394
|
+
const both = Math.min(sourceVersion || Infinity, targetVersion || Infinity);
|
|
2395
|
+
return (g) => g.privilege_type !== "MAINTAIN" || both >= 17e4;
|
|
2396
|
+
}
|
|
2397
|
+
function grouped(grants) {
|
|
2398
|
+
const groups = /* @__PURE__ */ new Map();
|
|
2399
|
+
for (const g of grants) {
|
|
2400
|
+
const key = `${g.grantee}.${g.table_schema}.${g.table_name}${g.column_name ? `.${g.column_name}` : ""}.${Boolean(g.is_grantable)}`;
|
|
2401
|
+
groups.set(key, [...groups.get(key) ?? [], g]);
|
|
2402
|
+
}
|
|
2403
|
+
return [...groups.values()];
|
|
2404
|
+
}
|
|
2405
|
+
function groupTarget(gs) {
|
|
2406
|
+
const column = gs[0].column_name ? ` ("${gs[0].column_name.replace(/"/g, '""')}")` : "";
|
|
2407
|
+
return `${gs.map((g) => `${g.privilege_type}${column}`).join(", ")} ON ${quoteName(gs[0].table_schema)}.${quoteName(gs[0].table_name)}`;
|
|
2408
|
+
}
|
|
2409
|
+
function describeGroup(gs) {
|
|
2410
|
+
const column = gs[0].column_name ? `(${gs[0].column_name}) ` : "";
|
|
2411
|
+
return `${gs.map((g) => g.privilege_type).join(", ")} ${column}ON ${gs[0].table_schema}.${gs[0].table_name} TO ${gs[0].grantee}`;
|
|
2412
|
+
}
|
|
2413
|
+
var groupKey = (gs) => grantKey(gs[0]).replace(/\.[^.]+$/, "");
|
|
2414
|
+
function diffGrants(source, target) {
|
|
2415
|
+
const issues = [];
|
|
2416
|
+
const sourceMap = new Map(source.map((g) => [grantKey(g), g]));
|
|
2417
|
+
const targetMap = new Map(target.map((g) => [grantKey(g), g]));
|
|
2418
|
+
const missing = [...sourceMap].filter(([key]) => !targetMap.has(key)).map(([, g]) => g);
|
|
2419
|
+
for (const gs of grouped(missing)) {
|
|
2420
|
+
const plural = gs.length > 1 ? "s" : "";
|
|
2421
|
+
issues.push({
|
|
2422
|
+
id: `roles-grant-missing-${groupKey(gs)}`,
|
|
2423
|
+
check: "roles",
|
|
2424
|
+
severity: "warning",
|
|
2425
|
+
title: `Missing grant${plural}: ${describeGroup(gs)}`,
|
|
2426
|
+
description: `Grant${plural} "${describeGroup(gs)}" ${gs.length > 1 ? "are" : "is"} missing from target.`,
|
|
2427
|
+
sourceValue: gs.length > 1 ? gs : gs[0],
|
|
2428
|
+
sql: {
|
|
2429
|
+
up: `GRANT ${groupTarget(gs)} TO ${granteeSql(gs[0].grantee)}${gs[0].is_grantable ? " WITH GRANT OPTION" : ""};`,
|
|
2430
|
+
down: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(gs[0].grantee)};`
|
|
2431
|
+
}
|
|
2432
|
+
});
|
|
2433
|
+
}
|
|
2434
|
+
for (const [key, sg] of sourceMap) {
|
|
2435
|
+
const tg = targetMap.get(key);
|
|
2436
|
+
if (tg && Boolean(sg.is_grantable) !== Boolean(tg.is_grantable)) {
|
|
2437
|
+
const revokeOption = `REVOKE GRANT OPTION FOR ${grantTarget(sg)} FROM ${granteeSql(sg.grantee)};`;
|
|
2438
|
+
issues.push({
|
|
2439
|
+
id: `roles-grant-option-${key}`,
|
|
2440
|
+
check: "roles",
|
|
2441
|
+
severity: "warning",
|
|
2442
|
+
title: `Grant option differs: ${describeGrant(sg)}`,
|
|
2443
|
+
description: `"${describeGrant(sg)}" is held ${sg.is_grantable ? "with" : "without"} the grant option in source and ${tg.is_grantable ? "with" : "without"} it in target.`,
|
|
2444
|
+
sourceValue: sg,
|
|
2445
|
+
targetValue: tg,
|
|
2446
|
+
sql: sg.is_grantable ? { up: grantSql(sg, true), down: revokeOption } : { up: revokeOption, down: grantSql(tg, true) }
|
|
2447
|
+
});
|
|
2448
|
+
}
|
|
2449
|
+
}
|
|
2450
|
+
const extra = [...targetMap].filter(([key]) => !sourceMap.has(key)).map(([, g]) => g);
|
|
2451
|
+
for (const gs of grouped(extra)) {
|
|
2452
|
+
const plural = gs.length > 1 ? "s" : "";
|
|
2453
|
+
issues.push({
|
|
2454
|
+
id: `roles-grant-extra-${groupKey(gs)}`,
|
|
2455
|
+
check: "roles",
|
|
2456
|
+
severity: extraGrantSeverity(gs[0].grantee),
|
|
2457
|
+
title: `Extra grant${plural}: ${describeGroup(gs)}`,
|
|
2458
|
+
description: `Grant${plural} "${describeGroup(gs)}" exist${gs.length > 1 ? "" : "s"} in target but not in source.`,
|
|
2459
|
+
targetValue: gs.length > 1 ? gs : gs[0],
|
|
2460
|
+
sql: {
|
|
2461
|
+
up: `REVOKE ${groupTarget(gs)} FROM ${granteeSql(gs[0].grantee)};`,
|
|
2462
|
+
down: `GRANT ${groupTarget(gs)} TO ${granteeSql(gs[0].grantee)}${gs[0].is_grantable ? " WITH GRANT OPTION" : ""};`
|
|
2463
|
+
}
|
|
2464
|
+
});
|
|
2465
|
+
}
|
|
2466
|
+
return issues;
|
|
2467
|
+
}
|
|
2468
|
+
|
|
2469
|
+
// src/checks/index.ts
|
|
2470
|
+
function createDefaultRegistry(options = {}) {
|
|
2471
|
+
const registry = new CheckRegistry();
|
|
2472
|
+
registry.register(new SchemaCheck());
|
|
2473
|
+
registry.register(new RlsCheck());
|
|
2474
|
+
registry.register(new RlsCoverageCheck());
|
|
2475
|
+
registry.register(new EdgeFunctionsCheck());
|
|
2476
|
+
registry.register(new StorageCheck(void 0, options.includeFiles ?? false));
|
|
2477
|
+
registry.register(new AuthCheck());
|
|
2478
|
+
registry.register(new CronCheck());
|
|
2479
|
+
registry.register(new DataCheck());
|
|
2480
|
+
registry.register(new WebhooksCheck());
|
|
2481
|
+
registry.register(new RealtimeCheck());
|
|
2482
|
+
registry.register(new VaultCheck());
|
|
2483
|
+
registry.register(new ExtensionsCheck());
|
|
2484
|
+
registry.register(new MigrationsCheck());
|
|
2485
|
+
registry.register(new RolesCheck());
|
|
2486
|
+
return registry;
|
|
2487
|
+
}
|
|
2488
|
+
|
|
2489
|
+
// src/promote.ts
|
|
2490
|
+
import pg from "pg";
|
|
2491
|
+
function outOfScopeReason(sql, filter) {
|
|
2492
|
+
if (!isFiltered(filter)) return null;
|
|
2493
|
+
const referenced = referencedTables(sql);
|
|
2494
|
+
if (referenced.length === 0) return null;
|
|
2495
|
+
const excluded = referenced.filter((t) => applyTableFilter([t], filter).length === 0);
|
|
2496
|
+
if (excluded.length === 0) return null;
|
|
2497
|
+
const names = excluded.map((t) => `'${t}'`).join(", ");
|
|
2498
|
+
const flag = filter?.tables?.length ? "--tables" : "--exclude-tables";
|
|
2499
|
+
const noun = excluded.length === 1 ? "table" : "tables";
|
|
2500
|
+
return `Depends on ${noun} ${names}, excluded by ${flag}`;
|
|
2501
|
+
}
|
|
2502
|
+
function isSelected(issueId, only) {
|
|
2503
|
+
if (!only?.length) return true;
|
|
2504
|
+
return only.some((pattern) => matchesGlob(issueId, pattern));
|
|
2505
|
+
}
|
|
2506
|
+
function classifyIssue(issue, options, recreatedPolicies = /* @__PURE__ */ new Set()) {
|
|
2507
|
+
if (!isSelected(issue.id, options.only)) {
|
|
2508
|
+
return { kind: "skip", reason: "Not selected by --only" };
|
|
2509
|
+
}
|
|
2510
|
+
if (issue.manualOnly) return { kind: "skip", reason: issue.manualOnly };
|
|
2511
|
+
if (!issue.sql?.up) {
|
|
2512
|
+
if (issue.action) return { kind: "api", action: issue.action };
|
|
2513
|
+
return { kind: "skip", reason: issue.manualOnly ?? "No SQL fix or API action available" };
|
|
2514
|
+
}
|
|
2515
|
+
if (!options.allowDestructive) {
|
|
2516
|
+
const why = destructiveReason(issue.sql.up, recreatedPolicies);
|
|
2517
|
+
if (why) {
|
|
2518
|
+
return { kind: "skip", reason: `Destructive \u2014 ${why}; re-run with --allow-destructive to apply` };
|
|
2519
|
+
}
|
|
2520
|
+
}
|
|
2521
|
+
const outOfScope = outOfScopeReason(issue.sql.up, options.tableFilter);
|
|
2522
|
+
if (outOfScope) return { kind: "skip", reason: outOfScope };
|
|
2523
|
+
return { kind: "sql", sql: issue.sql.up };
|
|
2524
|
+
}
|
|
2525
|
+
function policiesCreatedBySelectedFixes(checks, options) {
|
|
2526
|
+
const created = /* @__PURE__ */ new Set();
|
|
2527
|
+
for (const check of checks) {
|
|
2528
|
+
const askedForExplicitly = options.checks?.includes(check.check) ?? false;
|
|
2529
|
+
if (!isComparisonCheck(check.check) && !options.applyPosture && !askedForExplicitly) continue;
|
|
2530
|
+
for (const issue of check.issues) {
|
|
2531
|
+
const sql = issue.sql?.up;
|
|
2532
|
+
if (!sql || !isSelected(issue.id, options.only)) continue;
|
|
2533
|
+
if (!options.allowDestructive && destructiveReason(sql)) continue;
|
|
2534
|
+
if (outOfScopeReason(sql, options.tableFilter)) continue;
|
|
2535
|
+
for (const key of createdPolicies(sql)) created.add(key);
|
|
2536
|
+
}
|
|
2537
|
+
}
|
|
2538
|
+
return created;
|
|
2539
|
+
}
|
|
2540
|
+
function planWork(scanResult, options = {}) {
|
|
2541
|
+
const plan = { sqlStatements: [], apiActions: [], skipped: [] };
|
|
2542
|
+
const relevant = scanResult.checks.filter(
|
|
2543
|
+
(c) => c.status === "drifted" && (!options.checks || options.checks.includes(c.check))
|
|
2544
|
+
);
|
|
2545
|
+
const recreatedPolicies = policiesCreatedBySelectedFixes(relevant, options);
|
|
2546
|
+
const keptBack = [];
|
|
2547
|
+
for (const checkResult of relevant) {
|
|
2548
|
+
const askedForExplicitly = options.checks?.includes(checkResult.check) ?? false;
|
|
2549
|
+
if (!isComparisonCheck(checkResult.check) && !options.applyPosture && !askedForExplicitly) {
|
|
2550
|
+
for (const issue of checkResult.issues) {
|
|
2551
|
+
plan.skipped.push({
|
|
2552
|
+
check: checkResult.check,
|
|
2553
|
+
issueId: issue.id,
|
|
2554
|
+
reason: "Posture finding about the target, not drift from the source \u2014 applying it would create drift. Use --apply-posture to apply anyway."
|
|
2555
|
+
});
|
|
2556
|
+
}
|
|
2557
|
+
continue;
|
|
2558
|
+
}
|
|
2559
|
+
for (const issue of checkResult.issues) {
|
|
2560
|
+
const at = { check: checkResult.check, issueId: issue.id };
|
|
2561
|
+
const outcome = classifyIssue(issue, options, recreatedPolicies);
|
|
2562
|
+
if (outcome.kind === "sql") plan.sqlStatements.push({ ...at, sql: outcome.sql });
|
|
2563
|
+
else if (outcome.kind === "api") plan.apiActions.push({ ...at, action: outcome.action });
|
|
2564
|
+
else {
|
|
2565
|
+
plan.skipped.push({ ...at, reason: outcome.reason });
|
|
2566
|
+
if (outcome.reason.startsWith("Destructive") && issue.sql?.down) {
|
|
2567
|
+
keptBack.push({ issueId: issue.id, definition: issue.sql.down });
|
|
2568
|
+
}
|
|
2569
|
+
}
|
|
2570
|
+
}
|
|
2571
|
+
}
|
|
2572
|
+
plan.sqlStatements = holdBackDropsStillInUse(plan.sqlStatements, keptBack, plan.skipped, downsOf(relevant));
|
|
2573
|
+
const dbdiffOrder = new Map(plan.sqlStatements.filter((s) => s.check === "schema").map((s, i) => [s, i]));
|
|
2574
|
+
plan.sqlStatements = orderStatements(plan.sqlStatements, (s) => s.sql, (s) => dbdiffOrder.get(s));
|
|
2575
|
+
plan.sqlStatements = dropDuplicateObjectFixes(plan.sqlStatements, plan.skipped);
|
|
2576
|
+
return plan;
|
|
2577
|
+
}
|
|
2578
|
+
var DROPS_SUPPORTING_OBJECT = /^\s*DROP\s+(?:TYPE|DOMAIN|FUNCTION|PROCEDURE|ROUTINE|SEQUENCE)\s+(?:IF\s+EXISTS\s+)?((?:"[^"]+"|[\w$]+)(?:\s*\.\s*(?:"[^"]+"|[\w$]+))?)/i;
|
|
2579
|
+
function holdBackDropsStillInUse(statements, keptBack, skipped, downs = /* @__PURE__ */ new Map()) {
|
|
2580
|
+
const kept = keptBack.map((k) => ({ issueId: k.issueId, skeleton: sqlSkeleton(k.definition) }));
|
|
2581
|
+
let remaining = statements;
|
|
2582
|
+
for (let changed = kept.length > 0; changed; ) {
|
|
2583
|
+
changed = false;
|
|
2584
|
+
remaining = remaining.filter((statement) => {
|
|
2585
|
+
const names = droppedSupportingObjects(statement.sql);
|
|
2586
|
+
if (names.length === 0) return true;
|
|
2587
|
+
const user = kept.find((k) => names.some((n) => identifierMatcher(bareName(n)).test(k.skeleton)));
|
|
2588
|
+
if (!user) return true;
|
|
2589
|
+
skipped.push({
|
|
2590
|
+
check: statement.check,
|
|
2591
|
+
issueId: statement.issueId,
|
|
2592
|
+
reason: `Still used by what ${user.issueId} keeps, which is held back as destructive; re-run with --allow-destructive to apply both`
|
|
2593
|
+
});
|
|
2594
|
+
const definition = downs.get(statement.issueId);
|
|
2595
|
+
if (definition) kept.push({ issueId: user.issueId, skeleton: sqlSkeleton(definition) });
|
|
2596
|
+
changed = true;
|
|
2597
|
+
return false;
|
|
2598
|
+
});
|
|
2599
|
+
}
|
|
2600
|
+
return remaining;
|
|
2601
|
+
}
|
|
2602
|
+
function droppedSupportingObjects(sql) {
|
|
2603
|
+
const parts = splitSqlStatements(sql).filter((s) => !isCommentOnly(s));
|
|
2604
|
+
const names = parts.map((s) => DROPS_SUPPORTING_OBJECT.exec(sqlSkeleton(s))?.[1]);
|
|
2605
|
+
return names.length > 0 && names.every((n) => n !== void 0) ? names : [];
|
|
2606
|
+
}
|
|
2607
|
+
function downsOf(checks) {
|
|
2608
|
+
const downs = /* @__PURE__ */ new Map();
|
|
2609
|
+
for (const check of checks) {
|
|
2610
|
+
for (const issue of check.issues) {
|
|
2611
|
+
if (issue.sql?.down) downs.set(issue.id, issue.sql.down);
|
|
2612
|
+
}
|
|
2613
|
+
}
|
|
2614
|
+
return downs;
|
|
2615
|
+
}
|
|
2616
|
+
function dropDuplicateObjectFixes(statements, skipped) {
|
|
2617
|
+
const kinds = [
|
|
2618
|
+
{ what: "policy", created: createdPolicies, onlyThis: createsOnlyPolicies, seen: /* @__PURE__ */ new Set() },
|
|
2619
|
+
{ what: "trigger", created: createdTriggers, onlyThis: createsOnlyTriggers, seen: /* @__PURE__ */ new Set() }
|
|
2620
|
+
];
|
|
2621
|
+
const kept = [];
|
|
2622
|
+
for (const statement of statements) {
|
|
2623
|
+
const duplicate = kinds.find((kind) => {
|
|
2624
|
+
const names = kind.created(statement.sql);
|
|
2625
|
+
return names.length > 0 && names.every((n) => kind.seen.has(n)) && kind.onlyThis(statement.sql);
|
|
2626
|
+
});
|
|
2627
|
+
if (duplicate) {
|
|
2628
|
+
skipped.push({
|
|
2629
|
+
check: statement.check,
|
|
2630
|
+
issueId: statement.issueId,
|
|
2631
|
+
reason: `Already created by the schema fix for the same ${duplicate.what}`
|
|
2632
|
+
});
|
|
2633
|
+
continue;
|
|
2634
|
+
}
|
|
2635
|
+
for (const kind of kinds) {
|
|
2636
|
+
for (const name of kind.created(statement.sql)) kind.seen.add(name);
|
|
2637
|
+
}
|
|
2638
|
+
kept.push(statement);
|
|
2639
|
+
}
|
|
2640
|
+
return kept;
|
|
2641
|
+
}
|
|
2642
|
+
async function executeSql(dbUrl, statements, result, transactional) {
|
|
2643
|
+
if (statements.length === 0) return;
|
|
2644
|
+
const client = new pg.Client(pgClientConfig(dbUrl));
|
|
2645
|
+
await client.connect();
|
|
2646
|
+
try {
|
|
2647
|
+
if (transactional) await runInTransaction(client, statements, result);
|
|
2648
|
+
else await runIndependently(client, statements, result);
|
|
2649
|
+
} finally {
|
|
2650
|
+
await client.end();
|
|
2651
|
+
}
|
|
2652
|
+
}
|
|
2653
|
+
async function runIndependently(client, statements, result) {
|
|
2654
|
+
for (const stmt of statements) {
|
|
2655
|
+
try {
|
|
2656
|
+
await client.query(stmt.sql);
|
|
2657
|
+
result.applied.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql });
|
|
2658
|
+
} catch (err) {
|
|
2659
|
+
result.errors.push({ check: stmt.check, issueId: stmt.issueId, error: errMsg(err) });
|
|
2660
|
+
}
|
|
2661
|
+
}
|
|
2662
|
+
}
|
|
2663
|
+
function isEnumValueAddition(sql) {
|
|
2664
|
+
const statements = splitSqlStatements(sql).filter((s) => !isCommentOnly(s));
|
|
2665
|
+
return statements.length > 0 && statements.every((s) => /^\s*ALTER\s+TYPE\s+\S+\s+ADD\s+VALUE\b/i.test(sqlSkeleton(s)));
|
|
2666
|
+
}
|
|
2667
|
+
async function runInTransaction(client, statements, result) {
|
|
2668
|
+
const additions = statements.filter((s) => isEnumValueAddition(s.sql));
|
|
2669
|
+
const rest = statements.filter((s) => !isEnumValueAddition(s.sql));
|
|
2670
|
+
if (additions.length > 0 && !await runBatch(client, additions, result)) return;
|
|
2671
|
+
await runBatch(client, rest, result);
|
|
2672
|
+
}
|
|
2673
|
+
function unmetDependency(sql, err) {
|
|
2674
|
+
const code = sqlState(err);
|
|
2675
|
+
if (!code) return void 0;
|
|
2676
|
+
if (/^\s*CREATE\s+EXTENSION\b/i.test(sqlSkeleton(sql))) {
|
|
2677
|
+
return EXTENSION_UNAVAILABLE.has(code) ? "this server does not ship it" : void 0;
|
|
2678
|
+
}
|
|
2679
|
+
if (ABSENT_ON_TARGET.has(code) || code === UNDEFINED_COLUMN) {
|
|
2680
|
+
return "it needs something the target does not have";
|
|
2681
|
+
}
|
|
2682
|
+
return void 0;
|
|
2683
|
+
}
|
|
2684
|
+
async function runBatch(client, statements, result) {
|
|
2685
|
+
if (statements.length === 0) return true;
|
|
2686
|
+
const done = [];
|
|
2687
|
+
await client.query("BEGIN");
|
|
2688
|
+
let pending = statements;
|
|
2689
|
+
let unmet = [];
|
|
2690
|
+
while (pending.length > 0) {
|
|
2691
|
+
unmet = [];
|
|
2692
|
+
for (const stmt of pending) {
|
|
2693
|
+
await client.query("SAVEPOINT sf_fix");
|
|
2694
|
+
try {
|
|
2695
|
+
await client.query(stmt.sql);
|
|
2696
|
+
await client.query("RELEASE SAVEPOINT sf_fix");
|
|
2697
|
+
done.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql });
|
|
2698
|
+
} catch (err) {
|
|
2699
|
+
const why = unmetDependency(stmt.sql, err);
|
|
2700
|
+
if (why && await client.query("ROLLBACK TO SAVEPOINT sf_fix").then(() => true, () => false)) {
|
|
2701
|
+
unmet.push({ stmt, err, why });
|
|
2702
|
+
continue;
|
|
2703
|
+
}
|
|
2704
|
+
await client.query("ROLLBACK").catch(() => {
|
|
2705
|
+
});
|
|
2706
|
+
result.errors.push({ check: stmt.check, issueId: stmt.issueId, error: errMsg(err) });
|
|
2707
|
+
result.rolledBack = [...result.rolledBack ?? [], ...done];
|
|
2708
|
+
return false;
|
|
2709
|
+
}
|
|
2710
|
+
}
|
|
2711
|
+
if (unmet.length === pending.length) break;
|
|
2712
|
+
pending = unmet.map((u) => u.stmt);
|
|
2713
|
+
}
|
|
2714
|
+
await client.query("COMMIT");
|
|
2715
|
+
result.applied.push(...done);
|
|
2716
|
+
for (const { stmt, err, why } of unmet) {
|
|
2717
|
+
result.errors.push({
|
|
2718
|
+
check: stmt.check,
|
|
2719
|
+
issueId: stmt.issueId,
|
|
2720
|
+
error: `${errMsg(err)} \u2014 not applied: ${why}. The other fixes were.`
|
|
2721
|
+
});
|
|
2722
|
+
}
|
|
2723
|
+
return true;
|
|
2724
|
+
}
|
|
2725
|
+
async function executeApiActions(actions, fetchFn, result) {
|
|
2726
|
+
for (const act of actions) {
|
|
2727
|
+
try {
|
|
2728
|
+
const init = {
|
|
2729
|
+
method: act.action.method,
|
|
2730
|
+
headers: { "Content-Type": "application/json", ...act.action.headers }
|
|
2731
|
+
};
|
|
2732
|
+
if (act.action.body !== void 0) {
|
|
2733
|
+
init.body = JSON.stringify(act.action.body);
|
|
2734
|
+
}
|
|
2735
|
+
const res = await fetchFn(act.action.url, init);
|
|
2736
|
+
if (!res.ok) {
|
|
2737
|
+
const text = await res.text().catch(() => res.statusText);
|
|
2738
|
+
throw new Error(`${act.action.method} ${act.action.url} \u2192 ${res.status}: ${text}`);
|
|
2739
|
+
}
|
|
2740
|
+
result.applied.push({ check: act.check, issueId: act.issueId, action: act.action.label });
|
|
2741
|
+
} catch (err) {
|
|
2742
|
+
result.errors.push({ check: act.check, issueId: act.issueId, error: errMsg(err) });
|
|
2743
|
+
}
|
|
2744
|
+
}
|
|
2745
|
+
}
|
|
2746
|
+
async function promote(options) {
|
|
2747
|
+
const {
|
|
2748
|
+
dbUrl,
|
|
2749
|
+
scanResult,
|
|
2750
|
+
checks,
|
|
2751
|
+
dryRun = false,
|
|
2752
|
+
allowDestructive = false,
|
|
2753
|
+
tableFilter,
|
|
2754
|
+
only,
|
|
2755
|
+
applyPosture = false,
|
|
2756
|
+
transactional = true,
|
|
2757
|
+
fetchFn = globalThis.fetch.bind(globalThis)
|
|
2758
|
+
} = options;
|
|
2759
|
+
const { sqlStatements, apiActions, skipped } = planWork(scanResult, {
|
|
2760
|
+
checks,
|
|
2761
|
+
allowDestructive,
|
|
2762
|
+
tableFilter,
|
|
2763
|
+
only,
|
|
2764
|
+
applyPosture
|
|
2765
|
+
});
|
|
2766
|
+
const result = { applied: [], skipped, errors: [] };
|
|
2767
|
+
if (dryRun) {
|
|
2768
|
+
for (const stmt of sqlStatements) {
|
|
2769
|
+
result.applied.push({ check: stmt.check, issueId: stmt.issueId, sql: stmt.sql });
|
|
2770
|
+
}
|
|
2771
|
+
for (const act of apiActions) {
|
|
2772
|
+
result.applied.push({ check: act.check, issueId: act.issueId, action: act.action.label });
|
|
2773
|
+
}
|
|
2774
|
+
return result;
|
|
2775
|
+
}
|
|
2776
|
+
await executeSql(dbUrl, sqlStatements, result, transactional);
|
|
2777
|
+
if (result.rolledBack) {
|
|
2778
|
+
for (const act of apiActions) {
|
|
2779
|
+
result.skipped.push({
|
|
2780
|
+
check: act.check,
|
|
2781
|
+
issueId: act.issueId,
|
|
2782
|
+
reason: "Not attempted \u2014 the SQL fixes were rolled back"
|
|
2783
|
+
});
|
|
2784
|
+
}
|
|
2785
|
+
return result;
|
|
2786
|
+
}
|
|
2787
|
+
await executeApiActions(apiActions, fetchFn, result);
|
|
2788
|
+
return result;
|
|
2789
|
+
}
|
|
2790
|
+
|
|
2791
|
+
export {
|
|
2792
|
+
resolveTableFilter,
|
|
2793
|
+
isFiltered,
|
|
2794
|
+
describeTableFilter,
|
|
2795
|
+
CHECK_NAMES,
|
|
2796
|
+
CHECK_META,
|
|
2797
|
+
isComparisonCheck,
|
|
2798
|
+
summarize,
|
|
2799
|
+
summarizeByKind,
|
|
2800
|
+
computeScore,
|
|
2801
|
+
scan,
|
|
2802
|
+
CheckRegistry,
|
|
2803
|
+
createDefaultRegistry,
|
|
2804
|
+
planWork,
|
|
2805
|
+
promote
|
|
2806
|
+
};
|
|
2807
|
+
//# sourceMappingURL=chunk-5Z3SAIQS.js.map
|