@akal/supaforge 0.0.0-stage → 0.0.32
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +350 -2
- package/bin/dev.js +10 -0
- package/bin/run.js +18 -0
- package/dist/base-command.d.ts +135 -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-2SELREHW.js +156 -0
- package/dist/chunk-2SELREHW.js.map +1 -0
- package/dist/chunk-3HGAV5CC.js +2073 -0
- package/dist/chunk-3HGAV5CC.js.map +1 -0
- package/dist/chunk-4IVN7QVY.js +632 -0
- package/dist/chunk-4IVN7QVY.js.map +1 -0
- package/dist/chunk-6LJERPUN.js +499 -0
- package/dist/chunk-6LJERPUN.js.map +1 -0
- package/dist/chunk-6Q7MHFBM.js +13 -0
- package/dist/chunk-6Q7MHFBM.js.map +1 -0
- package/dist/chunk-6WAMNZLO.js +336 -0
- package/dist/chunk-6WAMNZLO.js.map +1 -0
- package/dist/chunk-7NAZGZPV.js +868 -0
- package/dist/chunk-7NAZGZPV.js.map +1 -0
- package/dist/chunk-BLKJWDTL.js +153 -0
- package/dist/chunk-BLKJWDTL.js.map +1 -0
- package/dist/chunk-BUOWHE36.js +1311 -0
- package/dist/chunk-BUOWHE36.js.map +1 -0
- package/dist/chunk-DMIWAJRB.js +602 -0
- package/dist/chunk-DMIWAJRB.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-GEHPTPNZ.js +240 -0
- package/dist/chunk-GEHPTPNZ.js.map +1 -0
- package/dist/chunk-GZREXCQZ.js +207 -0
- package/dist/chunk-GZREXCQZ.js.map +1 -0
- package/dist/chunk-MIRLB5JM.js +1292 -0
- package/dist/chunk-MIRLB5JM.js.map +1 -0
- package/dist/chunk-NTUASFQ3.js +248 -0
- package/dist/chunk-NTUASFQ3.js.map +1 -0
- package/dist/chunk-ORQJVE57.js +642 -0
- package/dist/chunk-ORQJVE57.js.map +1 -0
- package/dist/chunk-SC2XHGIS.js +122 -0
- package/dist/chunk-SC2XHGIS.js.map +1 -0
- package/dist/chunk-SQPCWGQO.js +657 -0
- package/dist/chunk-SQPCWGQO.js.map +1 -0
- package/dist/chunk-UWAVXC57.js +916 -0
- package/dist/chunk-UWAVXC57.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 +81 -0
- package/dist/commands/diff.js +23 -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 +28 -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 +43 -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 +127 -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 +18 -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 +266 -0
- package/dist/commands/restore.js.map +1 -0
- package/dist/commands/snapshot.d.ts +33 -0
- package/dist/commands/snapshot.js +249 -0
- package/dist/commands/snapshot.js.map +1 -0
- package/dist/commands/sync.d.ts +16 -0
- package/dist/commands/sync.js +38 -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 +498 -0
- package/dist/index.js +147 -0
- package/dist/index.js.map +1 -0
- package/package.json +74 -4
|
@@ -0,0 +1,1292 @@
|
|
|
1
|
+
import {
|
|
2
|
+
normalizeRoles
|
|
3
|
+
} from "./chunk-DQQ5E563.js";
|
|
4
|
+
import {
|
|
5
|
+
Check,
|
|
6
|
+
errMsg,
|
|
7
|
+
inRolledBackTransaction,
|
|
8
|
+
pgClientConfig,
|
|
9
|
+
pgQuery,
|
|
10
|
+
quoteIdent,
|
|
11
|
+
quoteLiteral,
|
|
12
|
+
quoteName,
|
|
13
|
+
readOrAbsent
|
|
14
|
+
} from "./chunk-SQPCWGQO.js";
|
|
15
|
+
import {
|
|
16
|
+
DEFAULT_IGNORE_SCHEMAS,
|
|
17
|
+
MIGRATIONS_SUBDIR,
|
|
18
|
+
RELATION_NOT_FOUND,
|
|
19
|
+
SNAPSHOTS_SUBDIR,
|
|
20
|
+
SUPABASE_MGMT_API,
|
|
21
|
+
SUPABASE_PLATFORM_SCHEMAS,
|
|
22
|
+
SUPAFORGE_DIR,
|
|
23
|
+
dim,
|
|
24
|
+
ok,
|
|
25
|
+
warn
|
|
26
|
+
} from "./chunk-6WAMNZLO.js";
|
|
27
|
+
|
|
28
|
+
// src/pg-tools.ts
|
|
29
|
+
import { execFile } from "child_process";
|
|
30
|
+
import { platform } from "os";
|
|
31
|
+
import { existsSync } from "fs";
|
|
32
|
+
import pg from "pg";
|
|
33
|
+
function parsePgDumpVersion(output) {
|
|
34
|
+
const m = output.match(/(\d+)(?:\.\d+)?/);
|
|
35
|
+
return m ? Number(m[1]) : null;
|
|
36
|
+
}
|
|
37
|
+
function parseServerVersion(versionStr) {
|
|
38
|
+
const m = versionStr.match(/^(\d+)/);
|
|
39
|
+
return m ? Number(m[1]) : null;
|
|
40
|
+
}
|
|
41
|
+
async function getLocalPgDumpVersion() {
|
|
42
|
+
return new Promise((resolve2) => {
|
|
43
|
+
execFile("pg_dump", ["--version"], (err, stdout) => {
|
|
44
|
+
if (err) return resolve2(null);
|
|
45
|
+
resolve2(parsePgDumpVersion(stdout));
|
|
46
|
+
});
|
|
47
|
+
});
|
|
48
|
+
}
|
|
49
|
+
function getPgDumpVersionAt(path) {
|
|
50
|
+
return new Promise((resolve2) => {
|
|
51
|
+
execFile(path, ["--version"], (err, stdout) => {
|
|
52
|
+
if (err) return resolve2(null);
|
|
53
|
+
resolve2(parsePgDumpVersion(stdout));
|
|
54
|
+
});
|
|
55
|
+
});
|
|
56
|
+
}
|
|
57
|
+
var VERSIONED_PG_DIRS = [
|
|
58
|
+
"/usr/lib/postgresql/{v}/bin",
|
|
59
|
+
// Debian / Ubuntu (PGDG)
|
|
60
|
+
"/opt/homebrew/opt/postgresql@{v}/bin",
|
|
61
|
+
// macOS Homebrew (Apple Silicon)
|
|
62
|
+
"/usr/local/opt/postgresql@{v}/bin",
|
|
63
|
+
// macOS Homebrew (Intel)
|
|
64
|
+
"/usr/pgsql-{v}/bin"
|
|
65
|
+
// RHEL / CentOS (PGDG)
|
|
66
|
+
];
|
|
67
|
+
async function resolvePgDumpPath(serverMajor) {
|
|
68
|
+
const named = process.env.SUPAFORGE_PG_BIN?.trim();
|
|
69
|
+
if (named) {
|
|
70
|
+
if (!existsSync(`${named}/pg_dump`)) {
|
|
71
|
+
throw new Error(`SUPAFORGE_PG_BIN is set to "${named}", which has no pg_dump`);
|
|
72
|
+
}
|
|
73
|
+
const major = await getPgDumpVersionAt(`${named}/pg_dump`);
|
|
74
|
+
if (major !== null && major >= serverMajor) return { path: `${named}/pg_dump`, major };
|
|
75
|
+
}
|
|
76
|
+
const defaultMajor = await getLocalPgDumpVersion();
|
|
77
|
+
if (defaultMajor !== null && defaultMajor >= serverMajor) {
|
|
78
|
+
return { path: "pg_dump", major: defaultMajor };
|
|
79
|
+
}
|
|
80
|
+
for (const v of versionsToCheck(serverMajor)) {
|
|
81
|
+
for (const tmpl of VERSIONED_PG_DIRS) {
|
|
82
|
+
const dir = tmpl.replace("{v}", String(v));
|
|
83
|
+
const candidate = `${dir}/pg_dump`;
|
|
84
|
+
if (!existsSync(candidate)) continue;
|
|
85
|
+
const major = await getPgDumpVersionAt(candidate);
|
|
86
|
+
if (major !== null && major >= serverMajor) {
|
|
87
|
+
return { path: candidate, major };
|
|
88
|
+
}
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
return null;
|
|
92
|
+
}
|
|
93
|
+
async function describeMissingPgDump(neededMajor) {
|
|
94
|
+
const onPath = await getLocalPgDumpVersion();
|
|
95
|
+
const named = process.env.SUPAFORGE_PG_BIN?.trim();
|
|
96
|
+
const namedMajor = named ? await getPgDumpVersionAt(`${named}/pg_dump`) : null;
|
|
97
|
+
const found = [
|
|
98
|
+
onPath === null ? "none on PATH" : `${onPath} on PATH`,
|
|
99
|
+
...named ? [`${namedMajor ?? "none"} in SUPAFORGE_PG_BIN`] : []
|
|
100
|
+
].join(", ");
|
|
101
|
+
return `no pg_dump ${neededMajor} or newer (found: ${found}); set SUPAFORGE_PG_BIN to a directory of PostgreSQL ${neededMajor}+ client tools`;
|
|
102
|
+
}
|
|
103
|
+
function resolvePgRestorePath(pgDumpPath) {
|
|
104
|
+
if (pgDumpPath === "pg_dump") return "pg_restore";
|
|
105
|
+
return pgDumpPath.replace(/pg_dump$/, "pg_restore");
|
|
106
|
+
}
|
|
107
|
+
function versionsToCheck(required) {
|
|
108
|
+
const versions = [];
|
|
109
|
+
for (let v = required + 3; v >= required; v--) {
|
|
110
|
+
versions.push(v);
|
|
111
|
+
}
|
|
112
|
+
return versions;
|
|
113
|
+
}
|
|
114
|
+
async function getServerMajorVersion(dbUrl) {
|
|
115
|
+
const client = new pg.Client(pgClientConfig(dbUrl));
|
|
116
|
+
try {
|
|
117
|
+
await client.connect();
|
|
118
|
+
const { rows } = await client.query("SHOW server_version");
|
|
119
|
+
const raw = rows[0].server_version;
|
|
120
|
+
const major = parseServerVersion(raw);
|
|
121
|
+
if (!major) throw new Error(`Could not parse server version: ${raw}`);
|
|
122
|
+
return major;
|
|
123
|
+
} finally {
|
|
124
|
+
await client.end();
|
|
125
|
+
}
|
|
126
|
+
}
|
|
127
|
+
async function checkPgDumpCompat(dbUrl) {
|
|
128
|
+
const serverMajor = await getServerMajorVersion(dbUrl);
|
|
129
|
+
const resolved = await resolvePgDumpPath(serverMajor);
|
|
130
|
+
if (resolved) {
|
|
131
|
+
return {
|
|
132
|
+
localMajor: resolved.major,
|
|
133
|
+
serverMajor,
|
|
134
|
+
compatible: true,
|
|
135
|
+
message: "",
|
|
136
|
+
pgDumpPath: resolved.path,
|
|
137
|
+
pgRestorePath: resolvePgRestorePath(resolved.path)
|
|
138
|
+
};
|
|
139
|
+
}
|
|
140
|
+
const localMajor = await getLocalPgDumpVersion();
|
|
141
|
+
const message = buildInstallMessage(localMajor, serverMajor);
|
|
142
|
+
return {
|
|
143
|
+
localMajor,
|
|
144
|
+
serverMajor,
|
|
145
|
+
compatible: false,
|
|
146
|
+
message,
|
|
147
|
+
pgDumpPath: "pg_dump",
|
|
148
|
+
pgRestorePath: "pg_restore"
|
|
149
|
+
};
|
|
150
|
+
}
|
|
151
|
+
function buildInstallMessage(localMajor, serverMajor) {
|
|
152
|
+
const header = localMajor === null ? `pg_dump not found. The server is PostgreSQL ${serverMajor} \u2014 install postgresql-client-${serverMajor}:` : `pg_dump version mismatch: local v${localMajor}, server v${serverMajor}. Install postgresql-client-${serverMajor}:`;
|
|
153
|
+
const instructions = getInstallInstructions(serverMajor);
|
|
154
|
+
return `${header}
|
|
155
|
+
|
|
156
|
+
${instructions}`;
|
|
157
|
+
}
|
|
158
|
+
function getInstallInstructions(majorVersion) {
|
|
159
|
+
const os = platform();
|
|
160
|
+
const v = majorVersion;
|
|
161
|
+
switch (os) {
|
|
162
|
+
case "darwin":
|
|
163
|
+
return [
|
|
164
|
+
` brew install postgresql@${v}`,
|
|
165
|
+
` # Then add to PATH:`,
|
|
166
|
+
` export PATH="/opt/homebrew/opt/postgresql@${v}/bin:$PATH"`
|
|
167
|
+
].join("\n");
|
|
168
|
+
case "linux":
|
|
169
|
+
return [
|
|
170
|
+
` # Debian / Ubuntu:`,
|
|
171
|
+
` sudo apt-get install -y postgresql-client-${v}`,
|
|
172
|
+
` # If the package is not found, add the PGDG repository first:`,
|
|
173
|
+
` # https://www.postgresql.org/download/linux/ubuntu/`,
|
|
174
|
+
``,
|
|
175
|
+
` # RHEL / Fedora:`,
|
|
176
|
+
` sudo dnf install -y postgresql${v}`
|
|
177
|
+
].join("\n");
|
|
178
|
+
case "win32":
|
|
179
|
+
return [
|
|
180
|
+
` # Download the installer from:`,
|
|
181
|
+
` # https://www.postgresql.org/download/windows/`,
|
|
182
|
+
` # Or use Chocolatey:`,
|
|
183
|
+
` choco install postgresql${v} --params '/Password:postgres'`
|
|
184
|
+
].join("\n");
|
|
185
|
+
default:
|
|
186
|
+
return ` Download PostgreSQL ${v} client tools from: https://www.postgresql.org/download/`;
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
// src/snapshot.ts
|
|
191
|
+
import { mkdir, writeFile, readFile, readdir, rm } from "fs/promises";
|
|
192
|
+
import { join, resolve } from "path";
|
|
193
|
+
import { execFile as execFileCb } from "child_process";
|
|
194
|
+
import { promisify } from "util";
|
|
195
|
+
|
|
196
|
+
// src/schema-introspect.ts
|
|
197
|
+
import pg2 from "pg";
|
|
198
|
+
async function introspectSchema(dbUrl, ignoreSchemas, clientQueryFn) {
|
|
199
|
+
let queryFn;
|
|
200
|
+
let pool;
|
|
201
|
+
if (clientQueryFn) {
|
|
202
|
+
queryFn = clientQueryFn;
|
|
203
|
+
} else {
|
|
204
|
+
pool = new pg2.Pool({ ...pgClientConfig(dbUrl), max: 6 });
|
|
205
|
+
queryFn = async (sql, params) => {
|
|
206
|
+
const { rows } = await pool.query(sql, params);
|
|
207
|
+
return rows;
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
try {
|
|
211
|
+
const schemaFilter = buildSchemaFilter(ignoreSchemas);
|
|
212
|
+
const [tables, views, functions, triggers, sequences, enums] = await Promise.all([
|
|
213
|
+
fetchTables(queryFn, schemaFilter),
|
|
214
|
+
fetchViews(queryFn, schemaFilter),
|
|
215
|
+
fetchFunctions(queryFn, schemaFilter),
|
|
216
|
+
fetchTriggers(queryFn, schemaFilter),
|
|
217
|
+
fetchSequences(queryFn, schemaFilter),
|
|
218
|
+
fetchEnums(queryFn, schemaFilter)
|
|
219
|
+
]);
|
|
220
|
+
return { tables, views, functions, triggers, sequences, enums };
|
|
221
|
+
} finally {
|
|
222
|
+
await pool?.end();
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
function buildSchemaFilter(ignoreSchemas) {
|
|
226
|
+
if (ignoreSchemas.length === 0) {
|
|
227
|
+
return { clause: "", params: [] };
|
|
228
|
+
}
|
|
229
|
+
const placeholders = ignoreSchemas.map((_, i) => `$${i + 1}`).join(", ");
|
|
230
|
+
return {
|
|
231
|
+
clause: `AND n.nspname NOT IN (${placeholders})`,
|
|
232
|
+
params: [...ignoreSchemas]
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
async function fetchTables(query, sf) {
|
|
236
|
+
const tableRows = await query(`
|
|
237
|
+
SELECT c.oid, n.nspname AS schema, c.relname AS name
|
|
238
|
+
FROM pg_class c
|
|
239
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
240
|
+
WHERE c.relkind IN ('r', 'p')
|
|
241
|
+
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
242
|
+
${sf.clause}
|
|
243
|
+
ORDER BY n.nspname, c.relname
|
|
244
|
+
`, sf.params);
|
|
245
|
+
if (tableRows.length === 0) return [];
|
|
246
|
+
const oids = tableRows.map((t) => t.oid);
|
|
247
|
+
const [allColumns, allIndexes, allConstraints] = await Promise.all([
|
|
248
|
+
fetchColumns(query, oids),
|
|
249
|
+
fetchIndexes(query, oids),
|
|
250
|
+
fetchConstraints(query, oids)
|
|
251
|
+
]);
|
|
252
|
+
return tableRows.map((t) => ({
|
|
253
|
+
schema: t.schema,
|
|
254
|
+
name: t.name,
|
|
255
|
+
columns: allColumns.get(t.oid) ?? [],
|
|
256
|
+
indexes: allIndexes.get(t.oid) ?? [],
|
|
257
|
+
constraints: allConstraints.get(t.oid) ?? []
|
|
258
|
+
}));
|
|
259
|
+
}
|
|
260
|
+
async function fetchColumns(query, oids) {
|
|
261
|
+
const rows = await query(`
|
|
262
|
+
SELECT
|
|
263
|
+
a.attrelid AS oid,
|
|
264
|
+
a.attname AS name,
|
|
265
|
+
pg_catalog.format_type(a.atttypid, a.atttypmod) AS type,
|
|
266
|
+
NOT a.attnotnull AS nullable,
|
|
267
|
+
pg_get_expr(d.adbin, d.adrelid) AS "default",
|
|
268
|
+
CASE a.attidentity WHEN 'a' THEN 'always' WHEN 'd' THEN 'by default' ELSE NULL END AS identity,
|
|
269
|
+
CASE a.attgenerated WHEN 's' THEN pg_get_expr(d.adbin, d.adrelid) ELSE NULL END AS generated
|
|
270
|
+
FROM pg_attribute a
|
|
271
|
+
LEFT JOIN pg_attrdef d ON d.adrelid = a.attrelid AND d.adnum = a.attnum
|
|
272
|
+
WHERE a.attrelid = ANY($1)
|
|
273
|
+
AND a.attnum > 0
|
|
274
|
+
AND NOT a.attisdropped
|
|
275
|
+
ORDER BY a.attrelid, a.attnum
|
|
276
|
+
`, [oids]);
|
|
277
|
+
const map = /* @__PURE__ */ new Map();
|
|
278
|
+
for (const r of rows) {
|
|
279
|
+
const list = map.get(r.oid) ?? [];
|
|
280
|
+
list.push({ name: r.name, type: r.type, nullable: r.nullable, default: r.default, identity: r.identity, generated: r.generated });
|
|
281
|
+
map.set(r.oid, list);
|
|
282
|
+
}
|
|
283
|
+
return map;
|
|
284
|
+
}
|
|
285
|
+
async function fetchIndexes(query, oids) {
|
|
286
|
+
const rows = await query(`
|
|
287
|
+
SELECT
|
|
288
|
+
i.indrelid AS oid,
|
|
289
|
+
c.relname AS name,
|
|
290
|
+
pg_get_indexdef(i.indexrelid) AS definition,
|
|
291
|
+
i.indisunique AS unique
|
|
292
|
+
FROM pg_index i
|
|
293
|
+
JOIN pg_class c ON c.oid = i.indexrelid
|
|
294
|
+
WHERE i.indrelid = ANY($1)
|
|
295
|
+
AND NOT i.indisprimary
|
|
296
|
+
ORDER BY i.indrelid, c.relname
|
|
297
|
+
`, [oids]);
|
|
298
|
+
const map = /* @__PURE__ */ new Map();
|
|
299
|
+
for (const r of rows) {
|
|
300
|
+
const list = map.get(r.oid) ?? [];
|
|
301
|
+
list.push({ name: r.name, definition: r.definition, unique: r.unique });
|
|
302
|
+
map.set(r.oid, list);
|
|
303
|
+
}
|
|
304
|
+
return map;
|
|
305
|
+
}
|
|
306
|
+
async function fetchConstraints(query, oids) {
|
|
307
|
+
const rows = await query(`
|
|
308
|
+
SELECT
|
|
309
|
+
con.conrelid AS oid,
|
|
310
|
+
con.conname AS name,
|
|
311
|
+
CASE con.contype
|
|
312
|
+
WHEN 'p' THEN 'PRIMARY KEY'
|
|
313
|
+
WHEN 'u' THEN 'UNIQUE'
|
|
314
|
+
WHEN 'f' THEN 'FOREIGN KEY'
|
|
315
|
+
WHEN 'c' THEN 'CHECK'
|
|
316
|
+
WHEN 'x' THEN 'EXCLUDE'
|
|
317
|
+
ELSE con.contype::text
|
|
318
|
+
END AS type,
|
|
319
|
+
pg_get_constraintdef(con.oid) AS definition
|
|
320
|
+
FROM pg_constraint con
|
|
321
|
+
WHERE con.conrelid = ANY($1)
|
|
322
|
+
ORDER BY con.conrelid, con.conname
|
|
323
|
+
`, [oids]);
|
|
324
|
+
const map = /* @__PURE__ */ new Map();
|
|
325
|
+
for (const r of rows) {
|
|
326
|
+
const list = map.get(r.oid) ?? [];
|
|
327
|
+
list.push({ name: r.name, type: r.type, definition: r.definition });
|
|
328
|
+
map.set(r.oid, list);
|
|
329
|
+
}
|
|
330
|
+
return map;
|
|
331
|
+
}
|
|
332
|
+
async function fetchViews(query, sf) {
|
|
333
|
+
return await query(`
|
|
334
|
+
SELECT n.nspname AS schema, c.relname AS name, pg_get_viewdef(c.oid, true) AS definition
|
|
335
|
+
FROM pg_class c
|
|
336
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
337
|
+
WHERE c.relkind IN ('v', 'm')
|
|
338
|
+
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
339
|
+
${sf.clause}
|
|
340
|
+
ORDER BY n.nspname, c.relname
|
|
341
|
+
`, sf.params);
|
|
342
|
+
}
|
|
343
|
+
async function fetchFunctions(query, sf) {
|
|
344
|
+
return await query(`
|
|
345
|
+
SELECT
|
|
346
|
+
n.nspname AS schema,
|
|
347
|
+
p.proname AS name,
|
|
348
|
+
pg_get_function_arguments(p.oid) AS args,
|
|
349
|
+
pg_get_function_result(p.oid) AS "returnType",
|
|
350
|
+
l.lanname AS language,
|
|
351
|
+
pg_get_functiondef(p.oid) AS definition
|
|
352
|
+
FROM pg_proc p
|
|
353
|
+
JOIN pg_namespace n ON n.oid = p.pronamespace
|
|
354
|
+
JOIN pg_language l ON l.oid = p.prolang
|
|
355
|
+
WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
356
|
+
${sf.clause}
|
|
357
|
+
AND p.prokind IN ('f', 'p')
|
|
358
|
+
ORDER BY n.nspname, p.proname, pg_get_function_arguments(p.oid)
|
|
359
|
+
`, sf.params);
|
|
360
|
+
}
|
|
361
|
+
async function fetchTriggers(query, sf) {
|
|
362
|
+
return await query(`
|
|
363
|
+
SELECT
|
|
364
|
+
n.nspname AS schema,
|
|
365
|
+
c.relname AS table,
|
|
366
|
+
t.tgname AS name,
|
|
367
|
+
pg_get_triggerdef(t.oid) AS definition
|
|
368
|
+
FROM pg_trigger t
|
|
369
|
+
JOIN pg_class c ON c.oid = t.tgrelid
|
|
370
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
371
|
+
WHERE NOT t.tgisinternal
|
|
372
|
+
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
373
|
+
${sf.clause}
|
|
374
|
+
ORDER BY n.nspname, c.relname, t.tgname
|
|
375
|
+
`, sf.params);
|
|
376
|
+
}
|
|
377
|
+
async function fetchSequences(query, sf) {
|
|
378
|
+
return await query(`
|
|
379
|
+
SELECT
|
|
380
|
+
n.nspname AS schema,
|
|
381
|
+
c.relname AS name,
|
|
382
|
+
format_type(s.seqtypid, NULL) AS "dataType",
|
|
383
|
+
s.seqstart::text AS "startValue",
|
|
384
|
+
s.seqincrement::text AS increment,
|
|
385
|
+
s.seqmin::text AS "minValue",
|
|
386
|
+
s.seqmax::text AS "maxValue"
|
|
387
|
+
FROM pg_sequence s
|
|
388
|
+
JOIN pg_class c ON c.oid = s.seqrelid
|
|
389
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
390
|
+
WHERE n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
391
|
+
${sf.clause}
|
|
392
|
+
ORDER BY n.nspname, c.relname
|
|
393
|
+
`, sf.params);
|
|
394
|
+
}
|
|
395
|
+
async function fetchEnums(query, sf) {
|
|
396
|
+
const rows = await query(`
|
|
397
|
+
SELECT
|
|
398
|
+
n.nspname AS schema,
|
|
399
|
+
t.typname AS name,
|
|
400
|
+
array_agg(e.enumlabel ORDER BY e.enumsortorder) AS labels
|
|
401
|
+
FROM pg_type t
|
|
402
|
+
JOIN pg_namespace n ON n.oid = t.typnamespace
|
|
403
|
+
JOIN pg_enum e ON e.enumtypid = t.oid
|
|
404
|
+
WHERE t.typtype = 'e'
|
|
405
|
+
AND n.nspname NOT IN ('pg_catalog', 'information_schema')
|
|
406
|
+
${sf.clause}
|
|
407
|
+
GROUP BY n.nspname, t.typname
|
|
408
|
+
ORDER BY n.nspname, t.typname
|
|
409
|
+
`, sf.params);
|
|
410
|
+
return rows;
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// src/utils/schema-policies.ts
|
|
414
|
+
function schemaPolicySql(schema) {
|
|
415
|
+
return `
|
|
416
|
+
SELECT tablename, policyname, permissive, roles, cmd, qual, with_check,
|
|
417
|
+
(SELECT obj_description(p.oid, 'pg_policy') FROM pg_policy p
|
|
418
|
+
JOIN pg_class c ON c.oid = p.polrelid JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
419
|
+
WHERE n.nspname = pg_policies.schemaname AND c.relname = pg_policies.tablename
|
|
420
|
+
AND p.polname = pg_policies.policyname) AS comment
|
|
421
|
+
FROM pg_policies
|
|
422
|
+
WHERE schemaname = '${schema}'
|
|
423
|
+
ORDER BY tablename, policyname
|
|
424
|
+
`;
|
|
425
|
+
}
|
|
426
|
+
function policyKey(p) {
|
|
427
|
+
return `${p.tablename}.${p.policyname}`;
|
|
428
|
+
}
|
|
429
|
+
var policyTable = (schema, p) => `${quoteName(schema)}.${quoteName(p.tablename)}`;
|
|
430
|
+
var roleSql = (role) => role === "public" ? "PUBLIC" : quoteName(role);
|
|
431
|
+
function createPolicySql(schema, p) {
|
|
432
|
+
const roles = normalizeRoles(p.roles).map(roleSql).join(", ");
|
|
433
|
+
const lines = [
|
|
434
|
+
`CREATE POLICY ${quoteName(p.policyname)}`,
|
|
435
|
+
` ON ${policyTable(schema, p)}`,
|
|
436
|
+
` AS ${p.permissive}`,
|
|
437
|
+
` FOR ${p.cmd}`,
|
|
438
|
+
` TO ${roles}`
|
|
439
|
+
];
|
|
440
|
+
if (p.qual) lines.push(` USING (${p.qual})`);
|
|
441
|
+
if (p.with_check) lines.push(` WITH CHECK (${p.with_check})`);
|
|
442
|
+
lines.push(";");
|
|
443
|
+
if (p.comment) lines.push(commentPolicySql(schema, p));
|
|
444
|
+
return lines.join("\n");
|
|
445
|
+
}
|
|
446
|
+
function commentPolicySql(schema, p) {
|
|
447
|
+
return `COMMENT ON POLICY ${quoteName(p.policyname)} ON ${policyTable(schema, p)} IS ${p.comment ? quoteLiteral(p.comment) : "NULL"};`;
|
|
448
|
+
}
|
|
449
|
+
function dropPolicySql(schema, p) {
|
|
450
|
+
return `DROP POLICY IF EXISTS ${quoteName(p.policyname)} ON ${policyTable(schema, p)};`;
|
|
451
|
+
}
|
|
452
|
+
function policiesEqual(a, b) {
|
|
453
|
+
return a.permissive === b.permissive && a.cmd === b.cmd && a.qual === b.qual && a.with_check === b.with_check && normalizeRoles(a.roles).join(",") === normalizeRoles(b.roles).join(",");
|
|
454
|
+
}
|
|
455
|
+
function diffSchemaPolicies(source, target, opts) {
|
|
456
|
+
const { schema, check, idPrefix, label } = opts;
|
|
457
|
+
const Label = label.charAt(0).toUpperCase() + label.slice(1);
|
|
458
|
+
const issues = [];
|
|
459
|
+
const sourceMap = new Map(source.map((p) => [policyKey(p), p]));
|
|
460
|
+
const targetMap = new Map(target.map((p) => [policyKey(p), p]));
|
|
461
|
+
for (const [key, sp] of sourceMap) {
|
|
462
|
+
if (targetMap.has(key)) continue;
|
|
463
|
+
issues.push({
|
|
464
|
+
id: `${idPrefix}-missing-${key}`,
|
|
465
|
+
check,
|
|
466
|
+
severity: "critical",
|
|
467
|
+
title: `Missing ${label} policy: ${sp.policyname} on ${sp.tablename}`,
|
|
468
|
+
description: `${Label} RLS policy "${sp.policyname}" on ${schema}.${sp.tablename} exists in source but not in target.`,
|
|
469
|
+
sourceValue: sp,
|
|
470
|
+
sql: {
|
|
471
|
+
up: createPolicySql(schema, sp),
|
|
472
|
+
down: dropPolicySql(schema, sp)
|
|
473
|
+
}
|
|
474
|
+
});
|
|
475
|
+
}
|
|
476
|
+
for (const [key, tp] of targetMap) {
|
|
477
|
+
if (sourceMap.has(key)) continue;
|
|
478
|
+
issues.push({
|
|
479
|
+
id: `${idPrefix}-extra-${key}`,
|
|
480
|
+
check,
|
|
481
|
+
severity: "info",
|
|
482
|
+
title: `Extra ${label} policy: ${tp.policyname} on ${tp.tablename}`,
|
|
483
|
+
description: `${Label} RLS policy "${tp.policyname}" on ${schema}.${tp.tablename} exists in target but not in source.`,
|
|
484
|
+
targetValue: tp,
|
|
485
|
+
sql: {
|
|
486
|
+
up: dropPolicySql(schema, tp),
|
|
487
|
+
down: createPolicySql(schema, tp)
|
|
488
|
+
}
|
|
489
|
+
});
|
|
490
|
+
}
|
|
491
|
+
for (const [key, sp] of sourceMap) {
|
|
492
|
+
const tp = targetMap.get(key);
|
|
493
|
+
if (!tp || policiesEqual(sp, tp)) continue;
|
|
494
|
+
issues.push({
|
|
495
|
+
id: `${idPrefix}-changed-${key}`,
|
|
496
|
+
check,
|
|
497
|
+
severity: "critical",
|
|
498
|
+
title: `${Label} policy changed: ${sp.policyname} on ${sp.tablename}`,
|
|
499
|
+
description: `${Label} RLS policy "${sp.policyname}" on ${schema}.${sp.tablename} differs between source and target.`,
|
|
500
|
+
sourceValue: sp,
|
|
501
|
+
targetValue: tp,
|
|
502
|
+
sql: {
|
|
503
|
+
up: [dropPolicySql(schema, sp), createPolicySql(schema, sp)].join("\n"),
|
|
504
|
+
down: [dropPolicySql(schema, tp), createPolicySql(schema, tp)].join("\n")
|
|
505
|
+
}
|
|
506
|
+
});
|
|
507
|
+
}
|
|
508
|
+
for (const [key, sp] of sourceMap) {
|
|
509
|
+
const tp = targetMap.get(key);
|
|
510
|
+
if (!tp || (sp.comment ?? null) === (tp.comment ?? null)) continue;
|
|
511
|
+
issues.push({
|
|
512
|
+
id: `${idPrefix}-comment-${key}`,
|
|
513
|
+
check,
|
|
514
|
+
severity: "info",
|
|
515
|
+
title: `${Label} policy comment changed: ${sp.policyname} on ${sp.tablename}`,
|
|
516
|
+
description: `The comment on ${label} RLS policy "${sp.policyname}" on ${schema}.${sp.tablename} differs between source and target.`,
|
|
517
|
+
sourceValue: sp.comment ?? null,
|
|
518
|
+
targetValue: tp.comment ?? null,
|
|
519
|
+
sql: {
|
|
520
|
+
up: commentPolicySql(schema, sp),
|
|
521
|
+
down: commentPolicySql(schema, tp)
|
|
522
|
+
}
|
|
523
|
+
});
|
|
524
|
+
}
|
|
525
|
+
return issues;
|
|
526
|
+
}
|
|
527
|
+
|
|
528
|
+
// src/utils/policy-equivalence.ts
|
|
529
|
+
var canonicalPolicyExpressions = async (dbUrl, policy) => {
|
|
530
|
+
try {
|
|
531
|
+
return await inRolledBackTransaction(dbUrl, async (client) => {
|
|
532
|
+
await client.query(
|
|
533
|
+
`CREATE TEMP TABLE sf_canon (LIKE ${quoteName(policy.schemaname)}.${quoteName(policy.tablename)})`
|
|
534
|
+
);
|
|
535
|
+
const command = (policy.cmd ?? "ALL").toUpperCase();
|
|
536
|
+
await client.query(
|
|
537
|
+
`CREATE POLICY sf_canon_p ON sf_canon FOR ${command}` + (policy.qual ? ` USING (${policy.qual})` : "") + (policy.with_check ? ` WITH CHECK (${policy.with_check})` : "")
|
|
538
|
+
);
|
|
539
|
+
const { rows } = await client.query(
|
|
540
|
+
`SELECT pg_get_expr(polqual, polrelid) AS qual, pg_get_expr(polwithcheck, polrelid) AS with_check
|
|
541
|
+
FROM pg_policy WHERE polrelid = 'pg_temp.sf_canon'::regclass`
|
|
542
|
+
);
|
|
543
|
+
return rows[0] ?? null;
|
|
544
|
+
});
|
|
545
|
+
} catch {
|
|
546
|
+
return null;
|
|
547
|
+
}
|
|
548
|
+
};
|
|
549
|
+
function defaultCanonicalizer(queryFn) {
|
|
550
|
+
return queryFn === pgQuery ? canonicalPolicyExpressions : async () => null;
|
|
551
|
+
}
|
|
552
|
+
async function dropEquivalentPolicyChanges(issues, ctx, canonicalize, schema) {
|
|
553
|
+
const withSchema = (p) => p && typeof p === "object" ? { schemaname: schema, ...p } : void 0;
|
|
554
|
+
const kept = [];
|
|
555
|
+
for (const issue of issues) {
|
|
556
|
+
const source = withSchema(issue.sourceValue);
|
|
557
|
+
const target = withSchema(issue.targetValue);
|
|
558
|
+
if (!isPolicy(source) || !isPolicy(target) || !sameApartFromExpressions(source, target)) {
|
|
559
|
+
kept.push(issue);
|
|
560
|
+
continue;
|
|
561
|
+
}
|
|
562
|
+
const [a, b] = await Promise.all([
|
|
563
|
+
canonicalize(ctx.source.dbUrl, source),
|
|
564
|
+
canonicalize(ctx.target.dbUrl, target)
|
|
565
|
+
]);
|
|
566
|
+
if (a && b && a.qual === b.qual && a.with_check === b.with_check) continue;
|
|
567
|
+
kept.push(issue);
|
|
568
|
+
}
|
|
569
|
+
return kept;
|
|
570
|
+
}
|
|
571
|
+
function isPolicy(p) {
|
|
572
|
+
return !!p && typeof p.schemaname === "string" && typeof p.policyname === "string" && typeof p.tablename === "string" && "qual" in p;
|
|
573
|
+
}
|
|
574
|
+
function sameApartFromExpressions(a, b) {
|
|
575
|
+
return a.schemaname === b.schemaname && a.tablename === b.tablename && a.policyname === b.policyname && String(a.permissive) === String(b.permissive) && (a.cmd ?? null) === (b.cmd ?? null) && JSON.stringify(a.roles) === JSON.stringify(b.roles) && (a.qual !== b.qual || a.with_check !== b.with_check);
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
// src/checks/realtime.ts
|
|
579
|
+
var RealtimeCheck = class extends Check {
|
|
580
|
+
constructor(queryFn = pgQuery) {
|
|
581
|
+
super();
|
|
582
|
+
this.queryFn = queryFn;
|
|
583
|
+
}
|
|
584
|
+
name = "realtime";
|
|
585
|
+
async scan(ctx) {
|
|
586
|
+
const [source, target] = await Promise.all([
|
|
587
|
+
this.fetchPublications(ctx.source.dbUrl),
|
|
588
|
+
this.fetchPublications(ctx.target.dbUrl)
|
|
589
|
+
]);
|
|
590
|
+
const publicationIssues = diffPublications(source, target);
|
|
591
|
+
const [srcPolicies, tgtPolicies] = await Promise.all([
|
|
592
|
+
this.fetchPolicies(ctx.source.dbUrl),
|
|
593
|
+
this.fetchPolicies(ctx.target.dbUrl)
|
|
594
|
+
]);
|
|
595
|
+
const policyIssues = await dropEquivalentPolicyChanges(
|
|
596
|
+
diffSchemaPolicies(srcPolicies, tgtPolicies, {
|
|
597
|
+
schema: "realtime",
|
|
598
|
+
check: "realtime",
|
|
599
|
+
idPrefix: "realtime-policy",
|
|
600
|
+
label: "realtime authorization"
|
|
601
|
+
}),
|
|
602
|
+
ctx,
|
|
603
|
+
defaultCanonicalizer(this.queryFn),
|
|
604
|
+
"realtime"
|
|
605
|
+
);
|
|
606
|
+
return [...publicationIssues, ...policyIssues];
|
|
607
|
+
}
|
|
608
|
+
async fetchPolicies(dbUrl) {
|
|
609
|
+
return readOrAbsent(async () => await this.queryFn(dbUrl, schemaPolicySql("realtime")), []);
|
|
610
|
+
}
|
|
611
|
+
async fetchPublications(dbUrl) {
|
|
612
|
+
return readOrAbsent(async () => await this.queryFn(dbUrl, PUBLICATION_SQL), []);
|
|
613
|
+
}
|
|
614
|
+
};
|
|
615
|
+
var PLATFORM_PUBLICATIONS = ["supabase_realtime_messages_publication"];
|
|
616
|
+
var PUBLICATION_SQL = `
|
|
617
|
+
SELECT p.pubname, pt.schemaname, pt.tablename
|
|
618
|
+
FROM pg_publication p
|
|
619
|
+
LEFT JOIN pg_publication_tables pt
|
|
620
|
+
ON p.pubname = pt.pubname
|
|
621
|
+
AND pt.schemaname <> ALL (${sqlTextArray(DEFAULT_IGNORE_SCHEMAS)})
|
|
622
|
+
WHERE p.pubname <> ALL (${sqlTextArray(PLATFORM_PUBLICATIONS)})
|
|
623
|
+
ORDER BY p.pubname, pt.schemaname, pt.tablename
|
|
624
|
+
`;
|
|
625
|
+
function sqlTextArray(values) {
|
|
626
|
+
return `ARRAY[${values.map((v) => `'${v.replace(/'/g, "''")}'`).join(", ")}]::text[]`;
|
|
627
|
+
}
|
|
628
|
+
function diffPublications(source, target) {
|
|
629
|
+
const issues = [];
|
|
630
|
+
const sourcePubs = new Set(source.map((p) => p.pubname));
|
|
631
|
+
const targetPubs = new Set(target.map((p) => p.pubname));
|
|
632
|
+
for (const pubname of sourcePubs) {
|
|
633
|
+
if (!targetPubs.has(pubname)) {
|
|
634
|
+
const tables = source.filter((p) => p.pubname === pubname && p.tablename);
|
|
635
|
+
issues.push({
|
|
636
|
+
id: `realtime-missing-pub-${pubname}`,
|
|
637
|
+
check: "realtime",
|
|
638
|
+
severity: "warning",
|
|
639
|
+
title: `Missing publication: ${pubname}`,
|
|
640
|
+
description: `Publication "${pubname}" exists in source but not in target.`,
|
|
641
|
+
sourceValue: tables,
|
|
642
|
+
sql: {
|
|
643
|
+
up: `CREATE PUBLICATION ${quoteName(pubname)}${tables.length > 0 ? ` FOR TABLE ${tables.map((t) => `${quoteName(t.schemaname)}.${quoteName(t.tablename)}`).join(", ")}` : ""};`,
|
|
644
|
+
down: `DROP PUBLICATION IF EXISTS ${quoteName(pubname)};`
|
|
645
|
+
}
|
|
646
|
+
});
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
for (const pubname of targetPubs) {
|
|
650
|
+
if (!sourcePubs.has(pubname)) {
|
|
651
|
+
issues.push({
|
|
652
|
+
id: `realtime-extra-pub-${pubname}`,
|
|
653
|
+
check: "realtime",
|
|
654
|
+
severity: "info",
|
|
655
|
+
title: `Extra publication: ${pubname}`,
|
|
656
|
+
description: `Publication "${pubname}" exists in target but not in source.`
|
|
657
|
+
});
|
|
658
|
+
}
|
|
659
|
+
}
|
|
660
|
+
const sharedPubs = [...sourcePubs].filter((p) => targetPubs.has(p));
|
|
661
|
+
for (const pubname of sharedPubs) {
|
|
662
|
+
const sourceTables = new Set(
|
|
663
|
+
source.filter((p) => p.pubname === pubname && p.tablename).map((p) => `${p.schemaname}.${p.tablename}`)
|
|
664
|
+
);
|
|
665
|
+
const targetTables = new Set(
|
|
666
|
+
target.filter((p) => p.pubname === pubname && p.tablename).map((p) => `${p.schemaname}.${p.tablename}`)
|
|
667
|
+
);
|
|
668
|
+
for (const fqn of sourceTables) {
|
|
669
|
+
if (!targetTables.has(fqn)) {
|
|
670
|
+
issues.push({
|
|
671
|
+
id: `realtime-missing-table-${pubname}-${fqn}`,
|
|
672
|
+
check: "realtime",
|
|
673
|
+
severity: "warning",
|
|
674
|
+
title: `Table not published: ${fqn} in ${pubname}`,
|
|
675
|
+
description: `Table "${fqn}" is published in source publication "${pubname}" but not in target.`,
|
|
676
|
+
sql: {
|
|
677
|
+
up: `ALTER PUBLICATION ${quoteName(pubname)} ADD TABLE ${fqn};`,
|
|
678
|
+
down: `ALTER PUBLICATION ${quoteName(pubname)} DROP TABLE ${fqn};`
|
|
679
|
+
}
|
|
680
|
+
});
|
|
681
|
+
}
|
|
682
|
+
}
|
|
683
|
+
for (const fqn of targetTables) {
|
|
684
|
+
if (!sourceTables.has(fqn)) {
|
|
685
|
+
issues.push({
|
|
686
|
+
id: `realtime-extra-table-${pubname}-${fqn}`,
|
|
687
|
+
check: "realtime",
|
|
688
|
+
severity: "info",
|
|
689
|
+
title: `Extra published table: ${fqn} in ${pubname}`,
|
|
690
|
+
description: `Table "${fqn}" is published in target publication "${pubname}" but not in source.`
|
|
691
|
+
});
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
}
|
|
695
|
+
return issues;
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
// src/snapshot.ts
|
|
699
|
+
var execFile2 = promisify(execFileCb);
|
|
700
|
+
function generateTimestamp() {
|
|
701
|
+
return (/* @__PURE__ */ new Date()).toISOString().replace(/[-:]/g, "").replace(/\.\d+Z$/, "Z");
|
|
702
|
+
}
|
|
703
|
+
function snapshotsBaseDir(cwd) {
|
|
704
|
+
return resolve(cwd, SUPAFORGE_DIR, SNAPSHOTS_SUBDIR);
|
|
705
|
+
}
|
|
706
|
+
function snapshotDir(cwd, timestamp) {
|
|
707
|
+
return join(snapshotsBaseDir(cwd), timestamp);
|
|
708
|
+
}
|
|
709
|
+
async function captureSnapshot(options) {
|
|
710
|
+
const cwd = options.cwd ?? process.cwd();
|
|
711
|
+
const timestamp = generateTimestamp();
|
|
712
|
+
const dir = options.outputDir ? join(resolve(options.outputDir), timestamp) : snapshotDir(cwd, timestamp);
|
|
713
|
+
await mkdir(dir, { recursive: true });
|
|
714
|
+
const queryFn = options.queryFn ?? pgQuery;
|
|
715
|
+
const fetchFn = options.fetchFn ?? globalThis.fetch.bind(globalThis);
|
|
716
|
+
const ignoreSchemas = options.config.ignoreSchemas ?? DEFAULT_IGNORE_SCHEMAS;
|
|
717
|
+
const layers = {};
|
|
718
|
+
layers.schema = await captureSchema(dir, options.env.dbUrl, ignoreSchemas, queryFn);
|
|
719
|
+
layers.rls = await captureRlsPolicies(dir, options.env.dbUrl, ignoreSchemas, queryFn);
|
|
720
|
+
layers["edge-functions"] = await captureEdgeFunctions(dir, options.env, fetchFn);
|
|
721
|
+
layers.storage = await captureStorage(dir, options.env, queryFn);
|
|
722
|
+
layers.auth = await captureAuthConfig(dir, options.env, fetchFn);
|
|
723
|
+
layers.cron = await captureCronJobs(dir, options.env.dbUrl, queryFn);
|
|
724
|
+
const dataTables = options.config.checks?.data?.tables ?? [];
|
|
725
|
+
layers.data = await captureData(dir, options.env.dbUrl, dataTables, queryFn);
|
|
726
|
+
layers.webhooks = await captureWebhooks(dir, options.env.dbUrl, queryFn);
|
|
727
|
+
layers.extensions = await captureExtensions(dir, options.env.dbUrl, queryFn);
|
|
728
|
+
layers.realtime = await captureRealtime(dir, options.env.dbUrl, queryFn);
|
|
729
|
+
layers.vault = await captureVaultSecrets(dir, options.env.dbUrl, queryFn);
|
|
730
|
+
layers.roles = await captureRoleGrants(dir, options.env.dbUrl, queryFn);
|
|
731
|
+
const manifest = {
|
|
732
|
+
version: 1,
|
|
733
|
+
timestamp,
|
|
734
|
+
environment: options.envName,
|
|
735
|
+
projectRef: options.env.projectRef,
|
|
736
|
+
layers
|
|
737
|
+
};
|
|
738
|
+
await writeFile(join(dir, "manifest.json"), JSON.stringify(manifest, null, 2) + "\n");
|
|
739
|
+
return { manifest, dir, timestamp };
|
|
740
|
+
}
|
|
741
|
+
function formatSnapshotLayers(manifest) {
|
|
742
|
+
const layers = manifest.layers;
|
|
743
|
+
const lines = [];
|
|
744
|
+
for (const [name, info] of Object.entries(layers)) {
|
|
745
|
+
if (info.captured) {
|
|
746
|
+
lines.push(`${ok("\u2713")} ${name.padEnd(16)} ${info.itemCount} item(s)`);
|
|
747
|
+
} else if (info.error) {
|
|
748
|
+
lines.push(`${warn("\u2717")} ${name.padEnd(16)} ${warn(`error: ${info.error}`)}`);
|
|
749
|
+
} else {
|
|
750
|
+
const skipSuffix = info.skipReason ? ` \u2014 ${info.skipReason}` : "";
|
|
751
|
+
lines.push(`${dim("\u25CB")} ${name.padEnd(16)} ${dim(`skipped${skipSuffix}`)}`);
|
|
752
|
+
}
|
|
753
|
+
}
|
|
754
|
+
return lines;
|
|
755
|
+
}
|
|
756
|
+
async function captureSchema(dir, dbUrl, ignoreSchemas, queryFn) {
|
|
757
|
+
const file = "schema.json";
|
|
758
|
+
try {
|
|
759
|
+
const schema = await introspectSchema(dbUrl, ignoreSchemas);
|
|
760
|
+
await writeFile(join(dir, file), JSON.stringify(schema, null, 2) + "\n");
|
|
761
|
+
return {
|
|
762
|
+
captured: true,
|
|
763
|
+
file,
|
|
764
|
+
itemCount: schema.tables.length,
|
|
765
|
+
...await captureSchemaSql(dir, dbUrl, [
|
|
766
|
+
.../* @__PURE__ */ new Set([...schemasIn(schema), ...await projectSchemas(dbUrl, ignoreSchemas, queryFn)])
|
|
767
|
+
].sort())
|
|
768
|
+
};
|
|
769
|
+
} catch (err) {
|
|
770
|
+
return { captured: false, file, itemCount: 0, error: errMsg(err) };
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
async function projectSchemas(dbUrl, ignoreSchemas, queryFn) {
|
|
774
|
+
const rows = await queryFn(dbUrl, `SELECT n.nspname AS name FROM pg_namespace n
|
|
775
|
+
WHERE n.nspname NOT LIKE 'pg\\_%' AND n.nspname <> 'information_schema'
|
|
776
|
+
AND n.nspname <> ALL($1::text[])
|
|
777
|
+
AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_namespace'::regclass
|
|
778
|
+
AND d.objid = n.oid AND d.deptype = 'e')`, [ignoreSchemas]);
|
|
779
|
+
return rows.map((r) => r.name);
|
|
780
|
+
}
|
|
781
|
+
function schemasIn(schema) {
|
|
782
|
+
const names = /* @__PURE__ */ new Set();
|
|
783
|
+
for (const group of [
|
|
784
|
+
schema.tables,
|
|
785
|
+
schema.views,
|
|
786
|
+
schema.functions,
|
|
787
|
+
schema.triggers,
|
|
788
|
+
schema.sequences,
|
|
789
|
+
schema.enums
|
|
790
|
+
]) {
|
|
791
|
+
for (const item of group) {
|
|
792
|
+
if (item.schema) names.add(item.schema);
|
|
793
|
+
}
|
|
794
|
+
}
|
|
795
|
+
return names.size > 0 ? [...names].sort() : ["public"];
|
|
796
|
+
}
|
|
797
|
+
async function captureSchemaSql(dir, dbUrl, schemas) {
|
|
798
|
+
const sqlFile = "schema.sql";
|
|
799
|
+
try {
|
|
800
|
+
const serverMajor = await getServerMajorVersion(dbUrl);
|
|
801
|
+
const resolved = await resolvePgDumpPath(serverMajor);
|
|
802
|
+
if (!resolved) {
|
|
803
|
+
return {
|
|
804
|
+
sqlSkipReason: `no pg_dump new enough for this server (needs ${serverMajor} or later) \u2014 schema.json was still captured, but restore cannot replay the schema`
|
|
805
|
+
};
|
|
806
|
+
}
|
|
807
|
+
const { stdout } = await execFile2(resolved.path, [
|
|
808
|
+
dbUrl,
|
|
809
|
+
"--schema-only",
|
|
810
|
+
"--no-owner",
|
|
811
|
+
"--no-privileges",
|
|
812
|
+
// Quoted: pg_dump reads --schema as a pattern, folding `App Data` to lower case.
|
|
813
|
+
...schemas.map((s) => `--schema=${quoteName(s)}`)
|
|
814
|
+
], { maxBuffer: 256 * 1024 * 1024, timeout: 3e5 });
|
|
815
|
+
if (stdout.trim().length === 0) {
|
|
816
|
+
return { sqlSkipReason: "pg_dump produced an empty schema dump" };
|
|
817
|
+
}
|
|
818
|
+
await writeFile(join(dir, sqlFile), stdout);
|
|
819
|
+
return { sqlFile };
|
|
820
|
+
} catch (err) {
|
|
821
|
+
return { sqlSkipReason: errMsg(err) };
|
|
822
|
+
}
|
|
823
|
+
}
|
|
824
|
+
var POLICY_COMMENT = `(SELECT obj_description(p.oid, 'pg_policy') FROM pg_policy p
|
|
825
|
+
JOIN pg_class c ON c.oid = p.polrelid JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
826
|
+
WHERE n.nspname = pg_policies.schemaname AND c.relname = pg_policies.tablename
|
|
827
|
+
AND p.polname = pg_policies.policyname) AS comment`;
|
|
828
|
+
async function captureRlsPolicies(dir, dbUrl, ignoreSchemas, queryFn) {
|
|
829
|
+
const file = "rls.sql";
|
|
830
|
+
try {
|
|
831
|
+
const placeholders = ignoreSchemas.map((_, i) => `$${i + 1}`).join(", ");
|
|
832
|
+
const sql = ignoreSchemas.length > 0 ? `SELECT schemaname, tablename, policyname, permissive, roles, cmd, qual, with_check, ${POLICY_COMMENT}
|
|
833
|
+
FROM pg_policies WHERE schemaname NOT IN (${placeholders})
|
|
834
|
+
ORDER BY schemaname, tablename, policyname` : `SELECT schemaname, tablename, policyname, permissive, roles, cmd, qual, with_check, ${POLICY_COMMENT}
|
|
835
|
+
FROM pg_policies ORDER BY schemaname, tablename, policyname`;
|
|
836
|
+
const rows = await queryFn(dbUrl, sql, ignoreSchemas.length > 0 ? ignoreSchemas : void 0);
|
|
837
|
+
const statements = rows.map((p) => generateCreatePolicySql(p));
|
|
838
|
+
const output = statements.length > 0 ? `-- SupaForge RLS Policy Snapshot
|
|
839
|
+
-- ${rows.length} policies
|
|
840
|
+
|
|
841
|
+
${statements.join("\n\n")}
|
|
842
|
+
` : "-- No RLS policies found\n";
|
|
843
|
+
await writeFile(join(dir, file), output);
|
|
844
|
+
return { captured: true, file, itemCount: rows.length };
|
|
845
|
+
} catch (err) {
|
|
846
|
+
return { captured: false, file, itemCount: 0, error: errMsg(err) };
|
|
847
|
+
}
|
|
848
|
+
}
|
|
849
|
+
async function captureEdgeFunctions(dir, env, fetchFn) {
|
|
850
|
+
const file = "edge-functions.json";
|
|
851
|
+
const token = env.accessToken;
|
|
852
|
+
if (!env.projectRef || !token) {
|
|
853
|
+
return { captured: false, file, itemCount: 0, skipReason: "no projectRef or accessToken configured" };
|
|
854
|
+
}
|
|
855
|
+
try {
|
|
856
|
+
const url = `${SUPABASE_MGMT_API}/${encodeURIComponent(env.projectRef)}/functions`;
|
|
857
|
+
const res = await fetchFn(url, {
|
|
858
|
+
headers: { Authorization: `Bearer ${token}` }
|
|
859
|
+
});
|
|
860
|
+
if (!res.ok) throw new Error(res.statusText);
|
|
861
|
+
const functions = await res.json();
|
|
862
|
+
await writeFile(join(dir, file), JSON.stringify(functions, null, 2) + "\n");
|
|
863
|
+
return { captured: true, file, itemCount: functions.length };
|
|
864
|
+
} catch (err) {
|
|
865
|
+
return { captured: false, file, itemCount: 0, error: errMsg(err) };
|
|
866
|
+
}
|
|
867
|
+
}
|
|
868
|
+
async function captureStorage(dir, env, queryFn) {
|
|
869
|
+
let bucketCount = 0;
|
|
870
|
+
let policyCount = 0;
|
|
871
|
+
let storageError;
|
|
872
|
+
const bucketsFile = "storage-buckets.json";
|
|
873
|
+
try {
|
|
874
|
+
const buckets = await queryFn(env.dbUrl, `
|
|
875
|
+
SELECT id, name, public, file_size_limit, allowed_mime_types,
|
|
876
|
+
avif_autodetection, created_at, updated_at
|
|
877
|
+
FROM storage.buckets
|
|
878
|
+
ORDER BY name
|
|
879
|
+
`);
|
|
880
|
+
await writeFile(join(dir, bucketsFile), JSON.stringify(buckets, null, 2) + "\n");
|
|
881
|
+
bucketCount = buckets.length;
|
|
882
|
+
} catch {
|
|
883
|
+
}
|
|
884
|
+
const policiesFile = "storage-policies.sql";
|
|
885
|
+
try {
|
|
886
|
+
const rows = await queryFn(env.dbUrl, schemaPolicySql("storage"));
|
|
887
|
+
const statements = rows.map((p) => (
|
|
888
|
+
// Dropped first so a snapshot can be restored twice, as below.
|
|
889
|
+
`${dropPolicySql("storage", p)}
|
|
890
|
+
${createPolicySql("storage", p)}`
|
|
891
|
+
));
|
|
892
|
+
const output = statements.length > 0 ? `-- SupaForge Storage Policy Snapshot
|
|
893
|
+
-- ${rows.length} policies
|
|
894
|
+
|
|
895
|
+
${statements.join("\n\n")}
|
|
896
|
+
` : "-- No storage policies found\n";
|
|
897
|
+
await writeFile(join(dir, policiesFile), output);
|
|
898
|
+
policyCount = rows.length;
|
|
899
|
+
} catch (err) {
|
|
900
|
+
storageError = errMsg(err);
|
|
901
|
+
}
|
|
902
|
+
const captured = bucketCount > 0 || policyCount > 0;
|
|
903
|
+
return {
|
|
904
|
+
captured,
|
|
905
|
+
file: bucketsFile,
|
|
906
|
+
itemCount: bucketCount + policyCount,
|
|
907
|
+
...storageError && !policyCount ? { error: storageError } : {},
|
|
908
|
+
...!captured && !storageError ? { skipReason: "no storage buckets or policies found" } : {}
|
|
909
|
+
};
|
|
910
|
+
}
|
|
911
|
+
async function captureAuthConfig(dir, env, fetchFn) {
|
|
912
|
+
const file = "auth.json";
|
|
913
|
+
const token = env.accessToken;
|
|
914
|
+
if (!env.projectRef || !token) {
|
|
915
|
+
return { captured: false, file, itemCount: 0, skipReason: "no projectRef or accessToken configured" };
|
|
916
|
+
}
|
|
917
|
+
try {
|
|
918
|
+
const url = `${SUPABASE_MGMT_API}/${encodeURIComponent(env.projectRef)}/config/auth`;
|
|
919
|
+
const res = await fetchFn(url, {
|
|
920
|
+
headers: { Authorization: `Bearer ${token}` }
|
|
921
|
+
});
|
|
922
|
+
if (!res.ok) throw new Error(res.statusText);
|
|
923
|
+
const config = await res.json();
|
|
924
|
+
await writeFile(join(dir, file), JSON.stringify(config, null, 2) + "\n");
|
|
925
|
+
return { captured: true, file, itemCount: Object.keys(config).length };
|
|
926
|
+
} catch (err) {
|
|
927
|
+
return { captured: false, file, itemCount: 0, error: errMsg(err) };
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
async function captureCronJobs(dir, dbUrl, queryFn) {
|
|
931
|
+
const file = "cron.sql";
|
|
932
|
+
try {
|
|
933
|
+
const rows = await queryFn(dbUrl, `
|
|
934
|
+
SELECT jobid, schedule, command, nodename, nodeport, database, username, active, jobname
|
|
935
|
+
FROM cron.job ORDER BY jobname, jobid
|
|
936
|
+
`);
|
|
937
|
+
const statements = rows.map((job) => {
|
|
938
|
+
const name = job.jobname ?? `job-${job.jobid}`;
|
|
939
|
+
return `SELECT cron.schedule('${name}', '${job.schedule}', $$${job.command}$$);`;
|
|
940
|
+
});
|
|
941
|
+
const output = statements.length > 0 ? `-- SupaForge Cron Job Snapshot
|
|
942
|
+
-- ${rows.length} jobs
|
|
943
|
+
|
|
944
|
+
${statements.join("\n\n")}
|
|
945
|
+
` : "-- No cron jobs found (pg_cron may not be installed)\n";
|
|
946
|
+
await writeFile(join(dir, file), output);
|
|
947
|
+
return { captured: true, file, itemCount: rows.length };
|
|
948
|
+
} catch (err) {
|
|
949
|
+
const msg = errMsg(err);
|
|
950
|
+
await writeFile(join(dir, file), "-- pg_cron extension not available\n").catch(() => {
|
|
951
|
+
});
|
|
952
|
+
if (msg.includes(RELATION_NOT_FOUND)) {
|
|
953
|
+
return { captured: false, file, itemCount: 0, skipReason: "pg_cron extension not installed" };
|
|
954
|
+
}
|
|
955
|
+
return { captured: false, file, itemCount: 0, error: msg };
|
|
956
|
+
}
|
|
957
|
+
}
|
|
958
|
+
async function captureData(dir, dbUrl, tables, queryFn) {
|
|
959
|
+
if (tables.length === 0) {
|
|
960
|
+
return { captured: false, file: "data/", itemCount: 0, skipReason: "no tables configured in checks.data.tables" };
|
|
961
|
+
}
|
|
962
|
+
const dataDir = join(dir, "data");
|
|
963
|
+
await mkdir(dataDir, { recursive: true });
|
|
964
|
+
let captured = 0;
|
|
965
|
+
const errors = [];
|
|
966
|
+
for (const table of tables) {
|
|
967
|
+
try {
|
|
968
|
+
await writeFile(join(dataDir, `${table}.json`), await capturedRows(dbUrl, table, queryFn) + "\n");
|
|
969
|
+
captured++;
|
|
970
|
+
} catch (err) {
|
|
971
|
+
errors.push(`${table}: ${errMsg(err)}`);
|
|
972
|
+
}
|
|
973
|
+
}
|
|
974
|
+
return {
|
|
975
|
+
captured: captured > 0,
|
|
976
|
+
file: "data/",
|
|
977
|
+
itemCount: captured,
|
|
978
|
+
...errors.length > 0 ? { error: errors.join("; ") } : {}
|
|
979
|
+
};
|
|
980
|
+
}
|
|
981
|
+
async function capturedRows(dbUrl, table, queryFn) {
|
|
982
|
+
const columns = (await queryFn(dbUrl, `SELECT attname AS name FROM pg_attribute
|
|
983
|
+
WHERE attrelid = ${quoteLiteral(quoteIdent(table))}::regclass AND attnum > 0 AND NOT attisdropped ORDER BY attnum`)).map((c) => c.name);
|
|
984
|
+
const keys = columns.map(quoteLiteral).join(", ");
|
|
985
|
+
const values = columns.map((c) => `t.${quoteName(c)}::text`).join(", ");
|
|
986
|
+
const [{ rows }] = await queryFn(dbUrl, `SELECT jsonb_pretty(jsonb_build_object('format', 'text', 'rows',
|
|
987
|
+
coalesce(jsonb_agg(json_object(ARRAY[${keys}]::text[], ARRAY[${values}]::text[])::jsonb), '[]'::jsonb))) AS rows
|
|
988
|
+
FROM (SELECT * FROM ${quoteIdent(table)} ORDER BY 1) t`);
|
|
989
|
+
return rows;
|
|
990
|
+
}
|
|
991
|
+
async function captureWebhooks(dir, dbUrl, queryFn) {
|
|
992
|
+
const file = "webhooks.sql";
|
|
993
|
+
try {
|
|
994
|
+
const rows = await queryFn(dbUrl, `
|
|
995
|
+
SELECT n.nspname || '.' || c.relname AS table_name,
|
|
996
|
+
t.tgname AS name,
|
|
997
|
+
pg_get_triggerdef(t.oid) AS definition
|
|
998
|
+
FROM pg_trigger t
|
|
999
|
+
JOIN pg_class c ON c.oid = t.tgrelid
|
|
1000
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
1001
|
+
JOIN pg_proc p ON p.oid = t.tgfoid
|
|
1002
|
+
JOIN pg_namespace pn ON pn.oid = p.pronamespace
|
|
1003
|
+
WHERE NOT t.tgisinternal
|
|
1004
|
+
AND pn.nspname = 'supabase_functions'
|
|
1005
|
+
AND p.proname = 'http_request'
|
|
1006
|
+
ORDER BY 1, 2
|
|
1007
|
+
`);
|
|
1008
|
+
const statements = rows.filter((h) => h.definition).map((hook) => [
|
|
1009
|
+
`-- Webhook: ${hook.name} on ${hook.table_name}`,
|
|
1010
|
+
`${hook.definition.replace(/;\s*$/, "")};`
|
|
1011
|
+
].join("\n"));
|
|
1012
|
+
const output = statements.length > 0 ? `-- SupaForge Webhook Snapshot
|
|
1013
|
+
-- ${statements.length} webhooks
|
|
1014
|
+
|
|
1015
|
+
${statements.join("\n\n")}
|
|
1016
|
+
` : "-- No webhooks found\n";
|
|
1017
|
+
await writeFile(join(dir, file), output);
|
|
1018
|
+
return { captured: true, file, itemCount: statements.length };
|
|
1019
|
+
} catch (err) {
|
|
1020
|
+
const msg = errMsg(err);
|
|
1021
|
+
await writeFile(join(dir, file), `-- Webhook snapshot failed: ${msg}
|
|
1022
|
+
`).catch(() => {
|
|
1023
|
+
});
|
|
1024
|
+
return { captured: false, file, itemCount: 0, error: msg };
|
|
1025
|
+
}
|
|
1026
|
+
}
|
|
1027
|
+
async function captureRealtime(dir, dbUrl, queryFn) {
|
|
1028
|
+
const file = "realtime.sql";
|
|
1029
|
+
try {
|
|
1030
|
+
const rows = await queryFn(dbUrl, PUBLICATION_SQL);
|
|
1031
|
+
const byPublication = /* @__PURE__ */ new Map();
|
|
1032
|
+
for (const row of rows) {
|
|
1033
|
+
const tables = byPublication.get(row.pubname) ?? [];
|
|
1034
|
+
if (row.schemaname && row.tablename) {
|
|
1035
|
+
tables.push(`${quoteName(row.schemaname)}.${quoteName(row.tablename)}`);
|
|
1036
|
+
}
|
|
1037
|
+
byPublication.set(row.pubname, tables);
|
|
1038
|
+
}
|
|
1039
|
+
const statements = [];
|
|
1040
|
+
for (const [pubname, tables] of byPublication) {
|
|
1041
|
+
statements.push(`-- Publication: ${pubname}`);
|
|
1042
|
+
statements.push(`DO $$ BEGIN
|
|
1043
|
+
IF NOT EXISTS (SELECT 1 FROM pg_publication WHERE pubname = ${quoteLiteral(pubname)}) THEN
|
|
1044
|
+
EXECUTE ${quoteLiteral(`CREATE PUBLICATION ${quoteName(pubname)}`)};
|
|
1045
|
+
END IF;
|
|
1046
|
+
END $$;`);
|
|
1047
|
+
for (const table of tables) {
|
|
1048
|
+
statements.push(`ALTER PUBLICATION ${quoteName(pubname)} ADD TABLE ${table};`);
|
|
1049
|
+
}
|
|
1050
|
+
}
|
|
1051
|
+
const output = statements.length > 0 ? `-- SupaForge Realtime Snapshot
|
|
1052
|
+
-- ${byPublication.size} publication(s)
|
|
1053
|
+
|
|
1054
|
+
${statements.join("\n")}
|
|
1055
|
+
` : "-- No publications found\n";
|
|
1056
|
+
await writeFile(join(dir, file), output);
|
|
1057
|
+
return { captured: true, file, itemCount: byPublication.size };
|
|
1058
|
+
} catch (err) {
|
|
1059
|
+
return { captured: false, file, itemCount: 0, error: errMsg(err) };
|
|
1060
|
+
}
|
|
1061
|
+
}
|
|
1062
|
+
async function captureVaultSecrets(dir, dbUrl, queryFn) {
|
|
1063
|
+
const file = "vault.sql";
|
|
1064
|
+
try {
|
|
1065
|
+
const rows = await queryFn(dbUrl, `
|
|
1066
|
+
SELECT coalesce(name, id::text) AS name, description
|
|
1067
|
+
FROM vault.secrets
|
|
1068
|
+
ORDER BY 1
|
|
1069
|
+
`);
|
|
1070
|
+
const lines = rows.map((row) => `-- ${row.name}${row.description ? ` \u2014 ${row.description}` : ""}`);
|
|
1071
|
+
const output = rows.length > 0 ? `-- SupaForge Vault Snapshot
|
|
1072
|
+
-- ${rows.length} secret(s), names only:
|
|
1073
|
+
-- the values cannot be read out of Vault and must be recreated by hand.
|
|
1074
|
+
${lines.join("\n")}
|
|
1075
|
+
` : "-- No vault secrets found\n";
|
|
1076
|
+
await writeFile(join(dir, file), output);
|
|
1077
|
+
return { captured: true, file, itemCount: rows.length };
|
|
1078
|
+
} catch (err) {
|
|
1079
|
+
if (!await vaultInstalled(dbUrl, queryFn)) {
|
|
1080
|
+
return { captured: false, file, itemCount: 0, skipReason: "vault extension not installed" };
|
|
1081
|
+
}
|
|
1082
|
+
return { captured: false, file, itemCount: 0, error: errMsg(err) };
|
|
1083
|
+
}
|
|
1084
|
+
}
|
|
1085
|
+
async function vaultInstalled(dbUrl, queryFn) {
|
|
1086
|
+
try {
|
|
1087
|
+
const [row] = await queryFn(dbUrl, `SELECT to_regnamespace('vault') IS NOT NULL AS installed`);
|
|
1088
|
+
return row?.installed === true;
|
|
1089
|
+
} catch {
|
|
1090
|
+
return true;
|
|
1091
|
+
}
|
|
1092
|
+
}
|
|
1093
|
+
async function captureRoleGrants(dir, dbUrl, queryFn) {
|
|
1094
|
+
const file = "roles.sql";
|
|
1095
|
+
const excluded = SUPABASE_PLATFORM_SCHEMAS.map(quoteLiteral).join(", ");
|
|
1096
|
+
try {
|
|
1097
|
+
const rows = await queryFn(dbUrl, `
|
|
1098
|
+
-- From relacl, not information_schema.role_table_grants: that view
|
|
1099
|
+
-- counts the owner's own privileges as grants, which a restore then
|
|
1100
|
+
-- replayed as GRANT ... TO <owner>, creating the role on the target;
|
|
1101
|
+
-- and it hides grants the connecting role takes no part in.
|
|
1102
|
+
SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END AS grantee,
|
|
1103
|
+
n.nspname AS table_schema, c.relname AS table_name, NULL::text AS column_name,
|
|
1104
|
+
a.privilege_type, a.is_grantable,
|
|
1105
|
+
CASE c.relkind WHEN 'S' THEN 'SEQUENCE' ELSE '' END AS keyword, NULL::text AS args
|
|
1106
|
+
FROM pg_class c
|
|
1107
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
1108
|
+
CROSS JOIN LATERAL aclexplode(c.relacl) a
|
|
1109
|
+
WHERE c.relacl IS NOT NULL AND c.relkind IN ('r', 'p', 'v', 'm', 'f', 'S')
|
|
1110
|
+
AND a.grantee <> c.relowner
|
|
1111
|
+
AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (
|
|
1112
|
+
'postgres','supabase_admin','authenticator','supabase_auth_admin',
|
|
1113
|
+
'supabase_storage_admin','dashboard_user','pgbouncer','supavisor'
|
|
1114
|
+
))
|
|
1115
|
+
AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg\\_%')
|
|
1116
|
+
AND n.nspname NOT IN (${excluded})
|
|
1117
|
+
UNION ALL
|
|
1118
|
+
-- Routines, through acldefault(): a NULL proacl is EXECUTE to PUBLIC,
|
|
1119
|
+
-- and leaving routines out restored a SECURITY DEFINER function the
|
|
1120
|
+
-- source kept from the API as callable by anyone.
|
|
1121
|
+
SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END,
|
|
1122
|
+
n.nspname, p.proname, NULL::text, a.privilege_type, a.is_grantable,
|
|
1123
|
+
CASE p.prokind WHEN 'p' THEN 'PROCEDURE' ELSE 'FUNCTION' END, pg_get_function_identity_arguments(p.oid)
|
|
1124
|
+
FROM pg_proc p
|
|
1125
|
+
JOIN pg_namespace n ON n.oid = p.pronamespace
|
|
1126
|
+
CROSS JOIN LATERAL aclexplode(coalesce(p.proacl, acldefault('f', p.proowner))) a
|
|
1127
|
+
WHERE a.grantee <> p.proowner
|
|
1128
|
+
AND NOT EXISTS (SELECT 1 FROM pg_depend d WHERE d.classid = 'pg_proc'::regclass AND d.objid = p.oid AND d.deptype = 'e')
|
|
1129
|
+
AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT IN (
|
|
1130
|
+
'postgres','supabase_admin','authenticator','supabase_auth_admin',
|
|
1131
|
+
'supabase_storage_admin','dashboard_user','pgbouncer','supavisor'
|
|
1132
|
+
))
|
|
1133
|
+
AND (a.grantee = 0 OR pg_get_userbyid(a.grantee) NOT LIKE 'pg\\_%')
|
|
1134
|
+
AND n.nspname NOT IN (${excluded})
|
|
1135
|
+
UNION ALL
|
|
1136
|
+
SELECT CASE WHEN a.grantee = 0 THEN 'PUBLIC' ELSE pg_get_userbyid(a.grantee) END,
|
|
1137
|
+
n.nspname, c.relname, att.attname, a.privilege_type, a.is_grantable, '', NULL::text
|
|
1138
|
+
FROM pg_attribute att
|
|
1139
|
+
JOIN pg_class c ON c.oid = att.attrelid
|
|
1140
|
+
JOIN pg_namespace n ON n.oid = c.relnamespace
|
|
1141
|
+
CROSS JOIN LATERAL aclexplode(att.attacl) a
|
|
1142
|
+
WHERE att.attacl IS NOT NULL AND att.attnum > 0 AND NOT att.attisdropped
|
|
1143
|
+
AND a.grantee <> c.relowner
|
|
1144
|
+
AND n.nspname NOT IN (${excluded})
|
|
1145
|
+
ORDER BY 1, 2, 3, 8, 4, 5
|
|
1146
|
+
`);
|
|
1147
|
+
const grouped = /* @__PURE__ */ new Map();
|
|
1148
|
+
for (const row of rows) {
|
|
1149
|
+
const key = JSON.stringify([
|
|
1150
|
+
row.grantee,
|
|
1151
|
+
row.keyword,
|
|
1152
|
+
row.table_schema,
|
|
1153
|
+
row.table_name,
|
|
1154
|
+
row.args,
|
|
1155
|
+
row.column_name,
|
|
1156
|
+
Boolean(row.is_grantable),
|
|
1157
|
+
row.privilege_type === "MAINTAIN"
|
|
1158
|
+
]);
|
|
1159
|
+
grouped.set(key, [...grouped.get(key) ?? [], row]);
|
|
1160
|
+
}
|
|
1161
|
+
const statements = [...grouped.values()].map(([row, ...rest]) => `GRANT ${[row, ...rest].map((r) => r.privilege_type + (r.column_name ? ` (${quoteName(r.column_name)})` : "")).join(", ")} ON ${row.keyword ? `${row.keyword} ` : ""}${quoteName(row.table_schema)}.${quoteName(row.table_name)}` + (row.args !== null && row.keyword !== "SEQUENCE" && row.keyword ? `(${row.args})` : "") + ` TO ${row.grantee === "PUBLIC" ? "PUBLIC" : quoteName(row.grantee)}` + (row.is_grantable ? " WITH GRANT OPTION" : "") + ";");
|
|
1162
|
+
const output = statements.length > 0 ? `-- SupaForge Role Grants Snapshot
|
|
1163
|
+
-- ${rows.length} grant(s)
|
|
1164
|
+
|
|
1165
|
+
${statements.join("\n")}
|
|
1166
|
+
` : "-- No role grants found\n";
|
|
1167
|
+
await writeFile(join(dir, file), output);
|
|
1168
|
+
return { captured: true, file, itemCount: rows.length };
|
|
1169
|
+
} catch (err) {
|
|
1170
|
+
return { captured: false, file, itemCount: 0, error: errMsg(err) };
|
|
1171
|
+
}
|
|
1172
|
+
}
|
|
1173
|
+
async function captureExtensions(dir, dbUrl, queryFn) {
|
|
1174
|
+
const file = "extensions.sql";
|
|
1175
|
+
try {
|
|
1176
|
+
const rows = await queryFn(dbUrl, `
|
|
1177
|
+
SELECT extname, extversion, n.nspname AS schema
|
|
1178
|
+
FROM pg_extension e
|
|
1179
|
+
JOIN pg_namespace n ON n.oid = e.extnamespace
|
|
1180
|
+
ORDER BY extname
|
|
1181
|
+
`);
|
|
1182
|
+
const statements = rows.map((ext) => {
|
|
1183
|
+
return `CREATE EXTENSION IF NOT EXISTS ${quoteName(ext.extname)} WITH SCHEMA ${quoteName(ext.schema)};`;
|
|
1184
|
+
});
|
|
1185
|
+
const output = statements.length > 0 ? `-- SupaForge Extensions Snapshot
|
|
1186
|
+
-- ${rows.length} extensions
|
|
1187
|
+
|
|
1188
|
+
${statements.join("\n")}
|
|
1189
|
+
` : "-- No extensions found\n";
|
|
1190
|
+
await writeFile(join(dir, file), output);
|
|
1191
|
+
return { captured: true, file, itemCount: rows.length };
|
|
1192
|
+
} catch (err) {
|
|
1193
|
+
return { captured: false, file, itemCount: 0, error: errMsg(err) };
|
|
1194
|
+
}
|
|
1195
|
+
}
|
|
1196
|
+
async function loadSnapshot(dir) {
|
|
1197
|
+
const raw = await readFile(join(dir, "manifest.json"), "utf-8");
|
|
1198
|
+
return JSON.parse(raw);
|
|
1199
|
+
}
|
|
1200
|
+
async function findLatestSnapshot(cwd = process.cwd()) {
|
|
1201
|
+
const base = snapshotsBaseDir(cwd);
|
|
1202
|
+
try {
|
|
1203
|
+
const entries = await readdir(base);
|
|
1204
|
+
const sorted = entries.filter((e) => /^\d{8}T\d{6}Z$/.test(e)).sort();
|
|
1205
|
+
return sorted.length > 0 ? join(base, sorted[sorted.length - 1]) : null;
|
|
1206
|
+
} catch {
|
|
1207
|
+
return null;
|
|
1208
|
+
}
|
|
1209
|
+
}
|
|
1210
|
+
async function listSnapshots(cwd = process.cwd()) {
|
|
1211
|
+
const base = snapshotsBaseDir(cwd);
|
|
1212
|
+
try {
|
|
1213
|
+
const entries = await readdir(base);
|
|
1214
|
+
const sorted = entries.filter((e) => /^\d{8}T\d{6}Z$/.test(e)).sort();
|
|
1215
|
+
const results = [];
|
|
1216
|
+
for (const entry of sorted) {
|
|
1217
|
+
try {
|
|
1218
|
+
const manifest = await loadSnapshot(join(base, entry));
|
|
1219
|
+
results.push({ dir: join(base, entry), manifest });
|
|
1220
|
+
} catch {
|
|
1221
|
+
}
|
|
1222
|
+
}
|
|
1223
|
+
return results;
|
|
1224
|
+
} catch {
|
|
1225
|
+
return [];
|
|
1226
|
+
}
|
|
1227
|
+
}
|
|
1228
|
+
var DEFAULT_KEEP_COUNT = 7;
|
|
1229
|
+
async function pruneSnapshots(keep = DEFAULT_KEEP_COUNT, cwd = process.cwd()) {
|
|
1230
|
+
const snapshots = await listSnapshots(cwd);
|
|
1231
|
+
if (snapshots.length <= keep) {
|
|
1232
|
+
return { deleted: [], kept: snapshots.map((s) => s.dir) };
|
|
1233
|
+
}
|
|
1234
|
+
const candidates = snapshots.slice(0, snapshots.length - keep);
|
|
1235
|
+
const withinBudget = snapshots.slice(snapshots.length - keep);
|
|
1236
|
+
const referenced = await snapshotVersionsReferencedByMigrations(cwd);
|
|
1237
|
+
const toDelete = candidates.filter((s) => !referenced.has(versionOf(s.dir)));
|
|
1238
|
+
const retained = candidates.filter((s) => referenced.has(versionOf(s.dir)));
|
|
1239
|
+
for (const snap of toDelete) {
|
|
1240
|
+
await rm(snap.dir, { recursive: true, force: true });
|
|
1241
|
+
}
|
|
1242
|
+
return {
|
|
1243
|
+
deleted: toDelete.map((s) => s.dir),
|
|
1244
|
+
kept: [...retained, ...withinBudget].map((s) => s.dir),
|
|
1245
|
+
retainedForMigrations: retained.map((s) => s.dir)
|
|
1246
|
+
};
|
|
1247
|
+
}
|
|
1248
|
+
function versionOf(dir) {
|
|
1249
|
+
return dir.split("/").filter(Boolean).pop() ?? dir;
|
|
1250
|
+
}
|
|
1251
|
+
async function snapshotVersionsReferencedByMigrations(cwd) {
|
|
1252
|
+
const referenced = /* @__PURE__ */ new Set();
|
|
1253
|
+
try {
|
|
1254
|
+
const dir = resolve(cwd, SUPAFORGE_DIR, MIGRATIONS_SUBDIR);
|
|
1255
|
+
for (const name of await readdir(dir)) {
|
|
1256
|
+
if (!name.endsWith(".json")) continue;
|
|
1257
|
+
try {
|
|
1258
|
+
const migration = JSON.parse(await readFile(join(dir, name), "utf-8"));
|
|
1259
|
+
if (migration.parent) referenced.add(migration.parent);
|
|
1260
|
+
} catch {
|
|
1261
|
+
}
|
|
1262
|
+
}
|
|
1263
|
+
} catch {
|
|
1264
|
+
}
|
|
1265
|
+
return referenced;
|
|
1266
|
+
}
|
|
1267
|
+
function generateCreatePolicySql(p) {
|
|
1268
|
+
return `${dropPolicySql(p.schemaname, p)}
|
|
1269
|
+
${createPolicySql(p.schemaname, p)}`;
|
|
1270
|
+
}
|
|
1271
|
+
|
|
1272
|
+
export {
|
|
1273
|
+
schemaPolicySql,
|
|
1274
|
+
createPolicySql,
|
|
1275
|
+
dropPolicySql,
|
|
1276
|
+
diffSchemaPolicies,
|
|
1277
|
+
defaultCanonicalizer,
|
|
1278
|
+
dropEquivalentPolicyChanges,
|
|
1279
|
+
RealtimeCheck,
|
|
1280
|
+
resolvePgDumpPath,
|
|
1281
|
+
describeMissingPgDump,
|
|
1282
|
+
getServerMajorVersion,
|
|
1283
|
+
checkPgDumpCompat,
|
|
1284
|
+
captureSnapshot,
|
|
1285
|
+
formatSnapshotLayers,
|
|
1286
|
+
loadSnapshot,
|
|
1287
|
+
findLatestSnapshot,
|
|
1288
|
+
listSnapshots,
|
|
1289
|
+
DEFAULT_KEEP_COUNT,
|
|
1290
|
+
pruneSnapshots
|
|
1291
|
+
};
|
|
1292
|
+
//# sourceMappingURL=chunk-MIRLB5JM.js.map
|