backupdrill 2.9.2 → 2.10.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +49 -5
  2. package/dist/auth-backup.d.ts +110 -0
  3. package/dist/auth-backup.js +383 -0
  4. package/dist/auth-drill.d.ts +69 -0
  5. package/dist/auth-drill.js +469 -0
  6. package/dist/auth-restore.d.ts +120 -0
  7. package/dist/auth-restore.js +633 -0
  8. package/dist/backup.d.ts +17 -0
  9. package/dist/backup.js +372 -19
  10. package/dist/config.d.ts +9 -0
  11. package/dist/config.js +17 -0
  12. package/dist/drill.d.ts +24 -3
  13. package/dist/drill.js +43 -3
  14. package/dist/dump-sql.d.ts +6 -0
  15. package/dist/dump-sql.js +31 -0
  16. package/dist/external-refs.d.ts +6 -1
  17. package/dist/external-refs.js +5 -0
  18. package/dist/index.js +67 -3
  19. package/dist/lib.d.ts +9 -3
  20. package/dist/lib.js +4 -2
  21. package/dist/manifest.d.ts +63 -0
  22. package/dist/manifest.js +78 -0
  23. package/dist/orphaned-foreign-keys.d.ts +13 -0
  24. package/dist/orphaned-foreign-keys.js +75 -25
  25. package/dist/pgbin.d.ts +7 -0
  26. package/dist/pgbin.js +24 -0
  27. package/dist/ping.js +1 -0
  28. package/dist/recovery-doc.d.ts +25 -0
  29. package/dist/recovery-doc.js +232 -53
  30. package/dist/restore-engine.d.ts +73 -1
  31. package/dist/restore-engine.js +155 -77
  32. package/dist/restore-record.d.ts +47 -0
  33. package/dist/restore-record.js +57 -0
  34. package/dist/restore.d.ts +64 -0
  35. package/dist/restore.js +348 -34
  36. package/dist/snapshot-store.d.ts +13 -0
  37. package/dist/snapshot-store.js +25 -0
  38. package/dist/snapshots.d.ts +2 -0
  39. package/dist/snapshots.js +10 -3
  40. package/package.json +1 -1
  41. package/plugin/README.md +1 -1
  42. package/plugin/skills/supabase-backup/SKILL.md +9 -7
  43. package/plugin/skills/supabase-backup/assets/scheduled-backup.yml +6 -1
  44. package/plugin/skills/supabase-backup/references/postgres-backup-basics.md +94 -0
@@ -0,0 +1,633 @@
1
+ /**
2
+ * 带 Auth 的恢复(2.10.0,PRD 增补 §5.2):Auth 用户、identities、应用数据、用户的触发器在**同一个事务**里写进目标。
3
+ *
4
+ * 为什么要这样:应用表上指向 auth.users 的外键(profiles.id → auth.users)要求用户先在。分两次写,
5
+ * 后一次失败就会留下半截目标;一个事务写完,失败了目标原样不动,修好原因直接重跑。
6
+ *
7
+ * 事务只由这里(协调程序)控制:起一个 psql 会话,先写 BEGIN,再把各段 SQL 依次喂进去——其中几段由
8
+ * `pg_restore -f -` 生成,不带 --single-transaction 时它们没有自己的 BEGIN/COMMIT。**只有每个生成进程都
9
+ * 0 退出、psql 一句没错时才写 COMMIT**;否则不写,psql 会话一结束服务端就回滚整个事务。不用
10
+ * `psql --single-transaction`:它在输入结束时照样提交,生成端中途失败也会被当成正常结束。
11
+ *
12
+ * 写 COMMIT 之后 psql 没报"已提交"(进程被杀、连接断了),就拿事务号问目标 pg_xact_status,不靠猜。
13
+ * 引擎在任何情况下都不自动删目标里的数据。
14
+ */
15
+ import { spawn } from "node:child_process";
16
+ import { writeFile } from "node:fs/promises";
17
+ import { join } from "node:path";
18
+ import { connectCancellable, manualAuthObjects, plainSchemaName, restorableAuthObjects } from "./auth-backup.js";
19
+ import { describeSqlstate } from "./auth-drill.js";
20
+ import { parseGeneratedColumns, parseTableColumns } from "./dump-sql.js";
21
+ import { localToolVersion, resolvePgRestoreBin, resolvePsqlBin } from "./pgbin.js";
22
+ import { afterCommit, credentialSafeDbArgs, firstRestoreError, libpqChildEnv, pgRestoreOutput, prepareMainRestore, quoteIdent, urlSslModeOf, userObjectCountSql, } from "./restore-engine.js";
23
+ import { connectPg, dumpUrlFor, isSupabaseHost } from "./supabase-ca.js";
24
+ import { interrupted, stopOnInterrupt } from "./interrupt.js";
25
+ /**
26
+ * 恢复后要清掉的待处理认证状态,和 GoTrue 的 ClearAllPendingTokens 对齐:备份时发出去的找回密码、邮箱确认、
27
+ * 改邮箱改手机的链接和验证码,在新项目上一律作废。RECOVERY.md 的手工步骤用同一句
28
+ */
29
+ export const CLEAR_PENDING_AUTH_SQL = "update auth.users set confirmation_token = '', recovery_token = '', email_change_token_new = '', " +
30
+ "email_change_token_current = '', phone_change_token = '', reauthentication_token = '', " +
31
+ "email_change = '', phone_change = '', email_change_confirm_status = 0, confirmation_sent_at = null, " +
32
+ "recovery_sent_at = null, email_change_sent_at = null, phone_change_sent_at = null, reauthentication_sent_at = null;";
33
+ /** 恢复互斥锁的键(pg_advisory_xact_lock):固定值,只给 BackupDrill 的恢复用。两次恢复写同一个目标时后一个排队 */
34
+ const RESTORE_LOCK_KEY = "7352063019441103";
35
+ // pg_restore -l 的条目行:"<id>; <oid> <oid> <类型> <schema> <名字> <属主>"
36
+ const tocType = (line) => /^\d+; \d+ \d+ (.+)$/.exec(line)?.[1] ?? null;
37
+ /** 读 auth.dump 的目录和两张表的建表语句。不碰目标 */
38
+ export async function readAuthArchive(path, manifest, workDir) {
39
+ const auth = manifest.auth;
40
+ const bin = resolvePgRestoreBin();
41
+ const listing = await pgRestoreOutput(bin, ["--list", path]);
42
+ if (listing.code !== 0) {
43
+ throw new Error(`the Auth archive couldn't be read (pg_restore --list exited with code ${listing.code})`);
44
+ }
45
+ const entries = listing.stdout.split("\n").filter((line) => /^\d+;/.test(line));
46
+ const only = (prefix, what) => {
47
+ const found = entries.filter((line) => (tocType(line) ?? "").startsWith(prefix));
48
+ if (found.length !== 1)
49
+ throw new Error(`the Auth archive doesn't have ${what}`);
50
+ return found[0];
51
+ };
52
+ const usersData = only("TABLE DATA auth users ", "the data of auth.users");
53
+ const identitiesData = only("TABLE DATA auth identities ", "the data of auth.identities");
54
+ const tablesList = join(workDir, "auth-tables.list");
55
+ await writeFile(tablesList, [only("TABLE auth users ", "the definition of auth.users"), only("TABLE auth identities ", "the definition of auth.identities")].join("\n") + "\n");
56
+ const ddl = await pgRestoreOutput(bin, ["-f", "-", `--use-list=${tablesList}`, path]);
57
+ if (ddl.code !== 0)
58
+ throw new Error(`the Auth archive couldn't be read (pg_restore exited with code ${ddl.code})`);
59
+ const types = parseTableColumns(ddl.stdout);
60
+ const generated = parseGeneratedColumns(ddl.stdout);
61
+ const dataColumns = (table) => {
62
+ const all = types.get(`auth\u0000${table}`);
63
+ if (!all?.size)
64
+ throw new Error(`the Auth archive's definition of auth.${table} couldn't be read`);
65
+ const skip = generated.get(`auth\u0000${table}`) ?? new Set();
66
+ return [...all].filter(([name]) => !skip.has(name)).map(([name, type]) => ({ name, type }));
67
+ };
68
+ // 规则同 RECOVERY.md 和演练:只补建平时启用、名字普通、依赖都在备份里的触发器(restorableAuthObjects)
69
+ const triggers = restorableAuthObjects({ triggers: auth.triggers, policies: auth.policies }, manifest.database.schemas).triggers.map((t) => {
70
+ const entry = entries.find((line) => (tocType(line) ?? "").startsWith(`TRIGGER auth ${t.table} ${t.name} `));
71
+ if (!entry)
72
+ throw new Error(`the Auth archive doesn't have the trigger ${t.name} that the snapshot lists`);
73
+ return { name: t.name, entry };
74
+ });
75
+ return { path, usersData, identitiesData, triggers, columns: { users: dataColumns("users"), identities: dataColumns("identities") } };
76
+ }
77
+ /**
78
+ * 只读预检(dry-run 和正式执行共用):目标得是一个新项目的 Auth——两张表在、没有用户、没有用户自己的触发器和策略,
79
+ * 列能装下备份的数据。返回拦下的原因,空数组 = 能恢复
80
+ */
81
+ export async function authRestorePreflight(targetUrl, archive) {
82
+ const client = await connectPg(targetUrl);
83
+ try {
84
+ // 和 pg_dump 一样在空 search_path 下取类型名:非系统类型都带 schema,两边才比得上
85
+ await client.query("select set_config('search_path', '', false)");
86
+ const tables = await client.query("select to_regclass('auth.users')::text as users, to_regclass('auth.identities')::text as identities");
87
+ if (!tables.rows[0].users || !tables.rows[0].identities) {
88
+ return [
89
+ "the target has no Supabase Auth tables (auth.users, auth.identities): restore into a Supabase project, " +
90
+ "or pass --skip-auth to restore the database without the Auth users",
91
+ ];
92
+ }
93
+ const problems = [];
94
+ const users = Number((await client.query("select count(*) as n from auth.users")).rows[0].n);
95
+ if (users > 0) {
96
+ problems.push(`the target already has ${users.toLocaleString("en-US")} Auth user(s), and restore writes Auth users only into a ` +
97
+ "new project. If you copied the users there yourself, pass --skip-auth to restore the database alone");
98
+ }
99
+ const objects = await client.query(`select (select count(*) from pg_trigger
100
+ where tgrelid in ('auth.users'::regclass, 'auth.identities'::regclass) and not tgisinternal) as triggers,
101
+ (select count(*) from pg_policy
102
+ where polrelid in ('auth.users'::regclass, 'auth.identities'::regclass)) as policies`);
103
+ const triggerCount = Number(objects.rows[0].triggers);
104
+ const policyCount = Number(objects.rows[0].policies);
105
+ if (triggerCount || policyCount) {
106
+ problems.push(`the target's Auth tables already have ${triggerCount} trigger(s) and ${policyCount} policy(ies) that aren't ` +
107
+ "Supabase's own, so it isn't a new project: restore into a new one");
108
+ }
109
+ // 结构兼容只看真正写进去的列。不做任何静默转换:对不上就拦下、说清是哪一列
110
+ for (const table of ["users", "identities"]) {
111
+ const onTarget = await client.query(`select attname as name, format_type(atttypid, atttypmod) as type, attgenerated <> '' as generated,
112
+ (attnotnull and not atthasdef and attidentity = '' and attgenerated = '') as required
113
+ from pg_attribute where attrelid = $1::regclass and attnum > 0 and not attisdropped`, [`auth.${table}`]);
114
+ const target = new Map(onTarget.rows.map((row) => [row.name, row]));
115
+ const fromBackup = new Set(archive.columns[table].map((column) => column.name));
116
+ for (const column of archive.columns[table]) {
117
+ const there = target.get(column.name);
118
+ const name = `auth.${table}.${column.name}`;
119
+ if (!there)
120
+ problems.push(`${name} is in the backup but not on the target`);
121
+ else if (there.generated)
122
+ problems.push(`${name} is a generated column on the target, so the backed-up values can't go into it`);
123
+ else if (there.type !== column.type)
124
+ problems.push(`${name} is ${column.type} in the backup but ${there.type} on the target`);
125
+ }
126
+ for (const row of onTarget.rows) {
127
+ if (row.required && !fromBackup.has(row.name)) {
128
+ problems.push(`auth.${table}.${row.name} on the target is required and has no default, and the backup has no values for it`);
129
+ }
130
+ }
131
+ }
132
+ return problems;
133
+ }
134
+ finally {
135
+ await client.end();
136
+ }
137
+ }
138
+ /**
139
+ * 主 dump 里的大对象。pg_restore 输出 SQL 时会在它们前后自己写 BEGIN; / COMMIT;,混进这个事务就会提前提交。
140
+ * 有的话这条路不能走,由调用方拦下。备份端的主 dump 总带 --schema,pg_dump 这时默认不导出大对象,
141
+ * 所以正常的快照里不会有:这是兜底,防的是别处来的归档
142
+ */
143
+ export async function largeObjectEntries(dumpPath) {
144
+ const listing = await pgRestoreOutput(resolvePgRestoreBin(), ["--list", dumpPath]);
145
+ if (listing.code !== 0)
146
+ throw new Error(`pg_restore --list exited with code ${listing.code}`);
147
+ return listing.stdout.split("\n").filter((line) => /^(BLOB|BLOBS|BLOB METADATA|LARGE OBJECT) /.test(tocType(line) ?? "")).length;
148
+ }
149
+ /**
150
+ * pg_restore 从这些小版本起在 SQL 输出开头写 `\restrict <随机密钥>`:psql 读到它就进入受限模式,在对应的
151
+ * \unrestrict 之前不执行任何元命令。归档内容(对象名、注释……)里混进来的 `\!` 之类因此不会在本机执行
152
+ * (CVE-2025-8714,2025-08 的修复版本)。18 起全部带
153
+ */
154
+ const RESTRICT_SINCE = { 13: 22, 14: 19, 15: 14, 16: 10, 17: 6 };
155
+ export function emitsRestrict([major, minor]) {
156
+ return major >= 18 || (RESTRICT_SINCE[major] !== undefined && minor >= RESTRICT_SINCE[major]);
157
+ }
158
+ /**
159
+ * psql 要能安全地执行 pg_restore 写出来的 SQL:pg_restore 得是带 \restrict 的版本,psql 和它同一个客户端包、
160
+ * 不比它旧(旧 psql 不认识 \restrict)。返回拦下的原因,null = 可以
161
+ */
162
+ export async function psqlProblem() {
163
+ const psql = await localToolVersion(resolvePsqlBin());
164
+ if (!psql) {
165
+ return "psql wasn't found; it comes with pg_restore in the PostgreSQL client package (or set BACKUPDRILL_PSQL)";
166
+ }
167
+ const pgRestore = await localToolVersion(resolvePgRestoreBin());
168
+ if (!pgRestore)
169
+ return "the pg_restore version couldn't be read";
170
+ if (!emitsRestrict(pgRestore)) {
171
+ return (`pg_restore ${pgRestore.join(".")} is too old to protect psql from commands carried in an archive ` +
172
+ "(needs 17.6, 16.10, 15.14, 14.19, 13.22 or newer); update the PostgreSQL client");
173
+ }
174
+ if (psql[0] < pgRestore[0] || (psql[0] === pgRestore[0] && psql[1] < pgRestore[1])) {
175
+ return `psql ${psql.join(".")} is older than pg_restore ${pgRestore.join(".")}; install a psql from the same client package`;
176
+ }
177
+ return null;
178
+ }
179
+ /**
180
+ * pg_restore -f - 的输出开头:第一条不是注释、不是空行的行必须是 `\restrict <密钥>`。还没读到完整的那一行时
181
+ * 返回 "more"。不是它就不交给 psql:没有受限模式,归档内容里的元命令会被执行
182
+ */
183
+ export function restrictHeader(text) {
184
+ const lines = text.split("\n");
185
+ lines.pop(); // 最后一段可能还没读完
186
+ for (const line of lines) {
187
+ if (line === "" || line.startsWith("--"))
188
+ continue;
189
+ return /^\\restrict [A-Za-z0-9]+$/.test(line) ? "ok" : "missing";
190
+ }
191
+ return "more";
192
+ }
193
+ const STAGE_TEXT = {
194
+ lock: "locking the target's Auth tables",
195
+ recheck: "checking the target is still empty",
196
+ extensions: "installing extensions",
197
+ "auth-data": "writing the Auth users",
198
+ "auth-check": "checking the Auth users",
199
+ database: "restoring the database",
200
+ triggers: "recreating your triggers on the Auth tables",
201
+ commit: "committing",
202
+ committed: "committing",
203
+ };
204
+ const STAGE_MARK = "backupdrill-stage:";
205
+ const XID_MARK = "backupdrill-xid:";
206
+ /**
207
+ * 等 stdin 能再写(drain)或者 psql 已经退出。监听用完就摘掉:大库恢复要等几十万次,
208
+ * 挂在一个直到最后才结束的 Promise 上的回调会一直攒着
209
+ */
210
+ export function drainOrExit(stdin, child) {
211
+ return new Promise((resolve) => {
212
+ const done = () => {
213
+ stdin.removeListener("drain", done);
214
+ stdin.removeListener("error", done);
215
+ child.removeListener("close", done);
216
+ child.removeListener("error", done);
217
+ resolve();
218
+ };
219
+ stdin.once("drain", done);
220
+ stdin.once("error", done);
221
+ child.once("close", done);
222
+ child.once("error", done);
223
+ });
224
+ }
225
+ /** psql 默认格式的第一条错误:主消息 + DETAIL/HINT。不带 CONTEXT(COPY 出错时那里是整行数据) */
226
+ export function firstPsqlError(stderr) {
227
+ const lines = stderr.split("\n");
228
+ const at = lines.findIndex((line) => /\bERROR:/.test(line));
229
+ if (at < 0)
230
+ return stderr.trim().replace(/\s+/g, " ").slice(0, 300) || "(no error output)";
231
+ const details = [];
232
+ for (const line of lines.slice(at + 1)) {
233
+ if (/^(DETAIL|HINT):/.test(line))
234
+ details.push(line.replace(/\s+/g, " ").trim());
235
+ else if (/^(psql:|ERROR:|FATAL:)/.test(line))
236
+ break;
237
+ }
238
+ return [lines[at].replace(/^.*?\bERROR:\s+/, "").trim(), ...details].join(" ");
239
+ }
240
+ /**
241
+ * 写过 COMMIT、却没看到 psql 确认时,用事务号问目标:提交了、回滚了,还是说不清。
242
+ * 还在进行中(原会话还没收尾)就等一会儿再问;等不到、连不上、事务号查不了,都是"说不清",不猜
243
+ */
244
+ export async function transactionOutcome(connString, xid, opts = {}) {
245
+ const { waitMs = 30_000, pollMs = 1000, graceMs = 15_000 } = opts;
246
+ const deadline = Date.now() + waitMs;
247
+ // 连接和每次查询都算在一个硬时限里:提交之后网络出问题时,这里不能一直挂着。到点直接断开连接
248
+ const giveUp = AbortSignal.timeout(waitMs + graceMs);
249
+ try {
250
+ const client = await connectCancellable(connString, giveUp);
251
+ try {
252
+ if (opts.identity) {
253
+ const now = await targetIdentity(client);
254
+ if (now.databaseOid !== opts.identity.databaseOid ||
255
+ (now.systemIdentifier !== null &&
256
+ opts.identity.systemIdentifier !== null &&
257
+ now.systemIdentifier !== opts.identity.systemIdentifier)) {
258
+ return "unknown";
259
+ }
260
+ }
261
+ for (;;) {
262
+ const res = await client.query("select pg_xact_status($1::xid8) as status", [xid]);
263
+ const status = res.rows[0].status;
264
+ if (status === "committed")
265
+ return "committed";
266
+ if (status === "aborted")
267
+ return "rolled_back";
268
+ if (status !== "in progress" || Date.now() >= deadline || giveUp.aborted)
269
+ return "unknown";
270
+ await new Promise((resolve) => setTimeout(resolve, pollMs));
271
+ }
272
+ }
273
+ finally {
274
+ await client.end().catch(() => { });
275
+ }
276
+ }
277
+ catch {
278
+ return "unknown";
279
+ }
280
+ }
281
+ /**
282
+ * 两张 Auth 表上可以延后检查的约束,现在就检查:不然它们要到 COMMIT 才报错,那时已经不在只报 SQLSTATE 的阶段,
283
+ * 报错的 DETAIL 会带出行值(邮箱之类)。之后这次恢复不再写这两张表,改成立即检查不影响别的
284
+ */
285
+ const AUTH_CONSTRAINTS_NOW_SQL = [
286
+ "do $bd$ declare c record; begin",
287
+ " for c in select n.nspname, con.conname from pg_constraint con join pg_namespace n on n.oid = con.connamespace",
288
+ " where con.conrelid in ('auth.users'::regclass, 'auth.identities'::regclass) and con.condeferrable loop",
289
+ " execute format('set constraints %I.%I immediate', c.nspname, c.conname);",
290
+ " end loop;",
291
+ "end $bd$;",
292
+ ].join("\n");
293
+ export async function targetIdentity(client) {
294
+ const db = await client.query("select oid::text as oid from pg_database where datname = current_database()");
295
+ let systemIdentifier = null;
296
+ try {
297
+ // 托管上普通角色可能没有执行权限:读不到就只比库的 OID
298
+ const sys = await client.query("select system_identifier::text as id from pg_control_system()");
299
+ systemIdentifier = sys.rows[0]?.id ?? null;
300
+ }
301
+ catch {
302
+ systemIdentifier = null;
303
+ }
304
+ return { databaseOid: db.rows[0].oid, systemIdentifier };
305
+ }
306
+ /** 两个 Auth 表名在 tableKey 里的写法:指向它们的外键和备份里的外键一样,提交后再加 */
307
+ export const AUTH_TABLE_KEYS = ["auth\u0000users", "auth\u0000identities"];
308
+ export async function restoreWithAuth(opts) {
309
+ const pgRestore = resolvePgRestoreBin();
310
+ const extensions = opts.extensions ?? [];
311
+ const prepared = await prepareMainRestore(pgRestore, opts.dumpPath, opts.connString, opts.listDir, {
312
+ alsoFullyDumped: AUTH_TABLE_KEYS,
313
+ schemasCreatedFirst: extensions.map((ext) => ext.schema),
314
+ });
315
+ if (!prepared.ok)
316
+ return { transaction: "rolled_back", failure: prepared.failure, triggers: [] };
317
+ const listFile = async (name, lines) => {
318
+ const file = join(opts.listDir, name);
319
+ await writeFile(file, lines.join("\n") + "\n");
320
+ return file;
321
+ };
322
+ const usersList = await listFile("auth-users.list", [opts.archive.usersData]);
323
+ const identitiesList = await listFile("auth-identities.list", [opts.archive.identitiesData]);
324
+ const triggersList = opts.archive.triggers.length
325
+ ? await listFile("auth-triggers.list", opts.archive.triggers.map((t) => t.entry))
326
+ : null;
327
+ // 连接方式和 pg_restore 直连目标时完全一样:TLS 校验、密码只走环境变量
328
+ const { url, env } = credentialSafeDbArgs(dumpUrlFor(opts.connString));
329
+ const childEnv = libpqChildEnv(env, process.env, { supabaseHost: isSupabaseHost(opts.connString), urlSslMode: urlSslModeOf(url) });
330
+ if (interrupted())
331
+ return { transaction: "rolled_back", failure: "interrupted before anything was written", triggers: [] };
332
+ // 开事务之前记下目标是哪个库:事后拿事务号问结果时先核对
333
+ const identityClient = await connectPg(opts.connString);
334
+ let identity;
335
+ try {
336
+ identity = await targetIdentity(identityClient);
337
+ }
338
+ finally {
339
+ await identityClient.end().catch(() => { });
340
+ }
341
+ // -X 不读用户的 psqlrc(它能改掉错误处理、把数据回显到终端);-A -t 只输出值,标记行原样可读
342
+ const psql = spawn(resolvePsqlBin(), ["-X", "-q", "-A", "-t", "-v", "ON_ERROR_STOP=1", "--dbname", url], {
343
+ stdio: ["pipe", "pipe", "pipe"],
344
+ env: childEnv,
345
+ });
346
+ const forgetPsql = stopOnInterrupt(psql);
347
+ let stage = null;
348
+ let xid;
349
+ let stderr = "";
350
+ let pending = "";
351
+ let resolveXid;
352
+ const xidSeen = new Promise((resolve) => (resolveXid = resolve));
353
+ psql.stdout.setEncoding("utf8");
354
+ psql.stdout.on("data", (chunk) => {
355
+ pending += chunk;
356
+ for (let nl = pending.indexOf("\n"); nl >= 0; nl = pending.indexOf("\n")) {
357
+ const line = pending.slice(0, nl);
358
+ pending = pending.slice(nl + 1);
359
+ if (line.startsWith(STAGE_MARK))
360
+ stage = line.slice(STAGE_MARK.length);
361
+ else if (line.startsWith(XID_MARK))
362
+ resolveXid((xid = line.slice(XID_MARK.length).trim()));
363
+ }
364
+ // 没有换行的超长输出不会是我们的标记,别让它占着内存
365
+ if (pending.length > 1_000_000)
366
+ pending = "";
367
+ });
368
+ psql.stderr.setEncoding("utf8");
369
+ psql.stderr.on("data", (chunk) => {
370
+ if (stderr.length < 64 * 1024)
371
+ stderr += chunk;
372
+ });
373
+ let spawnError;
374
+ let psqlGone = false;
375
+ const exited = new Promise((resolve) => {
376
+ psql.on("error", (error) => {
377
+ // 不透传原始 Error:node 会把 spawnargs(含连接串)挂在上面
378
+ spawnError = `psql failed to start: ${error.code ?? error.message}`;
379
+ resolve(null);
380
+ });
381
+ psql.on("close", (code) => resolve(code));
382
+ }).then((code) => {
383
+ psqlGone = true;
384
+ resolveXid(undefined);
385
+ return code;
386
+ });
387
+ // psql 因为语句出错先退出时,往它的 stdin 写会 EPIPE:由 psqlGone 处理,不让它变成未处理的异常
388
+ psql.stdin.on("error", () => { });
389
+ const send = async (data) => {
390
+ if (psqlGone || psql.stdin.destroyed)
391
+ return false;
392
+ if (!psql.stdin.write(data))
393
+ await drainOrExit(psql.stdin, psql);
394
+ return !psqlGone;
395
+ };
396
+ /** 把一个 pg_restore -f - 的输出整段喂给 psql。返回生成端的失败原因;psql 先退出了返回 null(由 psql 的报错说明) */
397
+ const generate = async (list, archivePath, what) => {
398
+ if (interrupted())
399
+ return "interrupted";
400
+ const gen = spawn(pgRestore, ["--no-owner", "--no-privileges", "-f", "-", `--use-list=${list}`, archivePath], {
401
+ stdio: ["ignore", "pipe", "pipe"],
402
+ env: libpqChildEnv(),
403
+ });
404
+ const forget = stopOnInterrupt(gen);
405
+ let genStderr = "";
406
+ gen.stderr.setEncoding("utf8");
407
+ gen.stderr.on("data", (chunk) => {
408
+ if (genStderr.length < 64 * 1024)
409
+ genStderr += chunk;
410
+ });
411
+ const closed = new Promise((resolve) => {
412
+ gen.on("error", () => resolve(-1));
413
+ gen.on("close", (code) => resolve(code));
414
+ });
415
+ void exited.then(() => gen.kill("SIGTERM"));
416
+ // 开头确认是 \restrict 之前一个字节都不交给 psql
417
+ let head = Buffer.alloc(0);
418
+ let unrestricted = false;
419
+ try {
420
+ for await (const chunk of gen.stdout) {
421
+ let data = chunk;
422
+ if (head) {
423
+ head = Buffer.concat([head, data]);
424
+ const verdict = restrictHeader(head.toString("utf8"));
425
+ if (verdict === "more" && head.length < 64 * 1024)
426
+ continue;
427
+ if (verdict !== "ok") {
428
+ unrestricted = true;
429
+ break;
430
+ }
431
+ data = head;
432
+ head = null;
433
+ }
434
+ if (!(await send(data)))
435
+ break;
436
+ }
437
+ }
438
+ catch {
439
+ // 读生成端的输出出错:按它的退出码判
440
+ }
441
+ gen.kill("SIGTERM");
442
+ const code = await closed;
443
+ forget();
444
+ if (unrestricted || (head && head.length > 0)) {
445
+ return `pg_restore's output for ${what} didn't start with \\restrict, so it wasn't passed to psql (without it, psql would run commands carried in the archive)`;
446
+ }
447
+ if (psqlGone)
448
+ return null;
449
+ if (code === 0)
450
+ return null;
451
+ return `pg_restore stopped while writing out ${what} (${code === null ? "killed by a signal" : `exit code ${code}`}): ${firstRestoreError(genStderr)}`;
452
+ };
453
+ // 带 Auth 的快照里 schemas 全是普通名字(备份端 authInSchemas 保证),按 pg_dump 的规则规范化后才是真正的 schema 名;
454
+ // plainSchemaName 只放行 [a-z0-9_],拼进 SQL 字面量是安全的
455
+ const schemaNames = opts.schemas.map((name) => plainSchemaName(name)).filter((name) => name !== null);
456
+ const schemaArray = `array[${schemaNames.map((name) => `'${name}'`).join(", ")}]::text[]`;
457
+ let commitSent = false;
458
+ let failure = null;
459
+ const run = async () => {
460
+ // 1. 开事务、加锁、锁内重查目标还是空的,再取事务号
461
+ const prelude = [
462
+ "\\set VERBOSITY default",
463
+ `\\echo ${STAGE_MARK}lock`,
464
+ "begin isolation level read committed;",
465
+ "set local lock_timeout = '60s';",
466
+ `select pg_advisory_xact_lock(${RESTORE_LOCK_KEY});`,
467
+ "lock table auth.users, auth.identities in share row exclusive mode;",
468
+ `\\echo ${STAGE_MARK}recheck`,
469
+ "set standard_conforming_strings = on;",
470
+ "do $bd$ begin",
471
+ " if exists (select 1 from auth.users) then",
472
+ " raise exception 'auth.users is no longer empty (someone signed up after the checks): restore only into a new project';",
473
+ " end if;",
474
+ " if exists (select 1 from pg_trigger where tgrelid in ('auth.users'::regclass, 'auth.identities'::regclass) and not tgisinternal)",
475
+ " or exists (select 1 from pg_policy where polrelid in ('auth.users'::regclass, 'auth.identities'::regclass)) then",
476
+ " raise exception 'the Auth tables now have triggers or policies of their own: restore only into a new project';",
477
+ " end if;",
478
+ ` if (${userObjectCountSql(schemaArray)}) > 0 then`,
479
+ " raise exception 'the target now has objects in the restored schemas (another restore may have run): restore only into a new project';",
480
+ " end if;",
481
+ "end $bd$;",
482
+ `select '${XID_MARK}' || pg_current_xact_id();`,
483
+ "",
484
+ ].join("\n");
485
+ if (!(await send(prelude)))
486
+ return;
487
+ const id = await xidSeen;
488
+ if (!id)
489
+ return;
490
+ // 先把事务号存下来再往下写:存不下就不提交(之后要靠它查结果、接着做)
491
+ try {
492
+ await opts.onTransactionId?.(id, identity);
493
+ }
494
+ catch (error) {
495
+ throw new Error(`the restore record couldn't be saved, so nothing was committed (${error.message})`);
496
+ }
497
+ // 扩展装在事务里、重查之后:重查看不到这次要装的东西(带配置表的扩展不会把自己拦下),失败时一起回滚
498
+ if (extensions.length) {
499
+ const install = extensions.flatMap((ext) => [
500
+ `create schema if not exists ${quoteIdent(ext.schema)};`,
501
+ // CASCADE 自动带上依赖扩展,免受 manifest 里的安装顺序摆布
502
+ `create extension if not exists ${quoteIdent(ext.name)} schema ${quoteIdent(ext.schema)} cascade;`,
503
+ ]);
504
+ if (!(await send(["", `\\echo ${STAGE_MARK}extensions`, ...install, ""].join("\n"))))
505
+ return;
506
+ }
507
+ // 2. Auth 用户和 identities(先 users,identities 的外键指向它),清掉待处理的认证状态。
508
+ // 这一段的报错只留 SQLSTATE:PostgreSQL 的报错会带出错行的值(邮箱、metadata)
509
+ if (!(await send(`\n\\echo ${STAGE_MARK}auth-data\n\\set VERBOSITY sqlstate\n`)))
510
+ return;
511
+ if ((failure = await generate(usersList, opts.archive.path, "the Auth users")))
512
+ return;
513
+ if ((failure = await generate(identitiesList, opts.archive.path, "the Auth identities")))
514
+ return;
515
+ if (!(await send(`\n${CLEAR_PENDING_AUTH_SQL}\n${AUTH_CONSTRAINTS_NOW_SQL}\n`)))
516
+ return;
517
+ // 3. 行数和快照一致,每条 identity 都有它的用户
518
+ const check = [
519
+ "",
520
+ `\\echo ${STAGE_MARK}auth-check`,
521
+ "\\set VERBOSITY default",
522
+ "do $bd$ begin",
523
+ ` if (select count(*) from auth.users) <> ${opts.auth.rows.users} or (select count(*) from auth.identities) <> ${opts.auth.rows.identities} then`,
524
+ " raise exception 'the Auth row counts on the target differ from this snapshot';",
525
+ " end if;",
526
+ " if exists (select 1 from auth.identities i where not exists (select 1 from auth.users u where u.id = i.user_id)) then",
527
+ " raise exception 'some Auth identities have no user';",
528
+ " end if;",
529
+ "end $bd$;",
530
+ `\\echo ${STAGE_MARK}database`,
531
+ "",
532
+ ].join("\n");
533
+ if (!(await send(check)))
534
+ return;
535
+ // 4. 应用 schema 和数据
536
+ if ((failure = await generate(prepared.listFile, opts.dumpPath, "the database")))
537
+ return;
538
+ // 5. 用户挂在 Auth 表上的触发器
539
+ if (triggersList) {
540
+ if (!(await send(`\n\\echo ${STAGE_MARK}triggers\n`)))
541
+ return;
542
+ if ((failure = await generate(triggersList, opts.archive.path, "your triggers on the Auth tables")))
543
+ return;
544
+ }
545
+ // 6. 前面全部成功才提交
546
+ if (!(await send(`\n\\echo ${STAGE_MARK}commit\n`)))
547
+ return;
548
+ commitSent = true;
549
+ await send(`commit;\n\\echo ${STAGE_MARK}committed\n`);
550
+ };
551
+ try {
552
+ await run();
553
+ }
554
+ catch (error) {
555
+ failure = `the restore stopped: ${error.message}`;
556
+ }
557
+ if (failure || !commitSent) {
558
+ // 没写 COMMIT:停掉 psql,会话一断服务端就回滚
559
+ psql.kill("SIGTERM");
560
+ }
561
+ psql.stdin.end();
562
+ const code = await exited;
563
+ forgetPsql();
564
+ // 没写 COMMIT:一定没提交(这条 SQL 流里没有别的 COMMIT,见 largeObjectEntries)。
565
+ // psql 执行完 COMMIT 才会打印 committed 标记,标记在、psql 0 退出就是提交了;写了 COMMIT 却没等到确认
566
+ // (进程被杀、连接断了),才拿事务号问目标
567
+ const transaction = !commitSent || !xid
568
+ ? "rolled_back"
569
+ : stage === "committed" && code === 0
570
+ ? "committed"
571
+ : await transactionOutcome(opts.connString, xid, { identity });
572
+ // 回滚、提交、查不清,都先告诉调用方(记进恢复记录),再往下走
573
+ await opts.onOutcome?.(transaction);
574
+ if (transaction !== "committed") {
575
+ const psqlSays = stage === "auth-data"
576
+ ? // 只给 SQLSTATE 的固定说法,不带报错原文
577
+ describeSqlstate(/\bERROR:\s+([0-9A-Z]{5})\b/.exec(stderr)?.[1])
578
+ : /\bERROR:/.test(stderr)
579
+ ? firstPsqlError(stderr)
580
+ : commitSent
581
+ ? `the connection ended before the commit was confirmed (psql exited with ${code === null ? "a signal" : `code ${code}`})`
582
+ : `psql exited with ${code === null ? "a signal" : `code ${code}`}${stderr.trim() ? `: ${firstPsqlError(stderr)}` : ""}`;
583
+ const why = spawnError ??
584
+ failure ??
585
+ (interrupted() ? "interrupted" : `${stage ? STAGE_TEXT[stage] : "connecting to the target"} failed: ${psqlSays}`);
586
+ return { transaction, failure: why, xid, triggers: [] };
587
+ }
588
+ const after = await afterCommit(opts.connString, opts.grants, prepared.deferred, { onGrantsApplied: opts.onGrantsApplied });
589
+ return { transaction, xid, afterCommit: after, triggers: opts.archive.triggers.map((t) => t.name) };
590
+ }
591
+ /**
592
+ * 没提交(或查不清)时给用户的那句话。结果只由事务本身说了算(没写 COMMIT,或 pg_xact_status 的回答),
593
+ * 不去数目标里有什么来推断:查不清就如实说查不清,并给出能查清的那条语句
594
+ */
595
+ export function authRestoreFailureMessage(run) {
596
+ if (run.transaction === "rolled_back") {
597
+ return (`database restore failed: ${run.failure}. It ran in one transaction and was rolled back, so nothing from the ` +
598
+ "snapshot (Auth users included) is on the target and you can run restore again on the same project once the cause is fixed.");
599
+ }
600
+ return (`database restore failed: ${run.failure}. The restore sent COMMIT but couldn't confirm whether the target committed it, ` +
601
+ "so the Auth users and the database are either all there or not there at all. Check before doing anything else" +
602
+ (run.xid ? `: \`select pg_xact_status('${run.xid}'::xid8);\` on the target says committed or aborted.` : ".") +
603
+ " If it committed, the grants and the foreign keys added after the commit are still missing.");
604
+ }
605
+ /**
606
+ * 恢复报告里关于 Auth 的说明(和 RECOVERY.md 同一套说法):哪些用户恢复后登录会受影响、哪些东西要手工补
607
+ */
608
+ export function authRestoreNotes(auth, schemas) {
609
+ const apiGrants = (auth.grants ?? []).filter((g) => ["anon", "authenticated", "service_role", "PUBLIC"].includes(g.grantee));
610
+ const notes = [
611
+ auth.passwordHashes.encrypted > 0
612
+ ? `${auth.passwordHashes.encrypted} user(s) have password hashes encrypted with the old project's key; they can't sign in with their old password on a new project and need a password reset.`
613
+ : "",
614
+ auth.passwordHashes.unrecognized > 0
615
+ ? `${auth.passwordHashes.unrecognized} user(s) have password hashes in a format BackupDrill doesn't recognize; whether they can sign in with their old password on a new project is unknown. Be ready to send them a password reset.`
616
+ : "",
617
+ auth.ssoUsers > 0
618
+ ? `${auth.ssoUsers} SSO user(s): their accounts are restored, but SSO providers aren't in this snapshot. Recreating a provider gives it a new ID, so these users may not land on their old accounts.`
619
+ : "",
620
+ auth.anonymousUsers > 0
621
+ ? `${auth.anonymousUsers} anonymous user(s): restored, but an anonymous user can only sign in with the session they had, and sessions aren't in this snapshot.`
622
+ : "",
623
+ auth.mfaUsers
624
+ ? `${auth.mfaUsers} user(s) had MFA. MFA factors aren't in this snapshot; those users sign in with one factor until they enroll again. Check what your app allows a user at \`aal1\`.`
625
+ : "",
626
+ apiGrants.length
627
+ ? `At backup time the Auth tables had grants to API roles (${[
628
+ ...new Set(apiGrants.map((g) => `${g.privilege} on auth.${g.table} to ${g.grantee}`)),
629
+ ].join(", ")}). A new project sets its own grants on these tables; add back any you had added yourself.`
630
+ : "",
631
+ ].filter(Boolean);
632
+ return { notes, manual: manualAuthObjects({ triggers: auth.triggers, policies: auth.policies }, schemas) };
633
+ }
package/dist/backup.d.ts CHANGED
@@ -3,6 +3,23 @@ import { type SnapshotStore } from "./snapshot-store.js";
3
3
  import type { Manifest } from "./manifest.js";
4
4
  import { parsePgDumpMajor } from "./pgbin.js";
5
5
  export { parsePgDumpMajor };
6
+ /** 主 dump 的 pg_dump 参数。snapshotId 省略时与 2.10.0 之前逐字一致(Auth 关闭时就是这样) */
7
+ export declare function mainDumpArgs(schemas: string[], snapshotId?: string): string[];
8
+ /**
9
+ * Auth 一侧的两个时限(导出供测试调短,产品里不改):
10
+ * - waitAfterMainMs:主 dump 完成后还肯等 Auth 导出多久
11
+ * - prepareDeadlineMs:主 dump 开始前,导出快照 + 统计最多花多久(连接、锁、查询都算在内)
12
+ */
13
+ export declare const AUTH_TIMEOUTS: {
14
+ waitAfterMainMs: number;
15
+ prepareDeadlineMs: number;
16
+ /**
17
+ * 两份 dump 一起启动后,主 dump 最迟多久要吐出第一个字节。连接池会排队的环境里(例如名额只有两个),
18
+ * 导出快照的连接和 Auth dump 可能占满名额、让主 dump 一直排在后面——到点就放掉 Auth 这两条连接,
19
+ * 把名额让给主 dump(它若还没导入快照,稍后会在写出任何东西之前失败,再按今天的方式重导)
20
+ */
21
+ mainStartGraceMs: number;
22
+ };
6
23
  export declare function runBackup(config: BackupConfig, opts?: {
7
24
  /** 快照写到哪;省略 = config.storage 指的 S3 兼容桶 */
8
25
  store?: SnapshotStore;