backupdrill 2.9.2 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +23 -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 +36 -0
  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 +7 -7
  43. package/plugin/skills/supabase-backup/assets/scheduled-backup.yml +6 -1
package/dist/backup.js CHANGED
@@ -4,6 +4,7 @@ import { Transform } from "node:stream";
4
4
  import { promisify } from "node:util";
5
5
  import { s3SnapshotStore } from "./snapshot-store.js";
6
6
  import { MANIFEST_SCHEMA_VERSION } from "./manifest.js";
7
+ import { AUTH_DUMP_MAX_BYTES, authDumpArgs, exportSharedSnapshot, inspectAuth, authInSchemas, manualAuthObjects, redactValues, } from "./auth-backup.js";
7
8
  import { syncStorage } from "./storage.js";
8
9
  import { inspectBucketAttrs } from "./storage-catalog.js";
9
10
  import { projectRefOf, refFromStorageEndpoint, assertNoHostOverride } from "./restore-engine.js";
@@ -100,43 +101,88 @@ async function readGrants(databaseUrl, schemas) {
100
101
  await client.end();
101
102
  }
102
103
  }
103
- /** 流式跑 pg_dump,边写快照边算 sha256 与字节数。返回校验和与大小。 */
104
- async function dumpToSnapshot(config, writer, pgDumpBin, dumpRelationBytes) {
104
+ /** 主 dump 的 pg_dump 参数。snapshotId 省略时与 2.10.0 之前逐字一致(Auth 关闭时就是这样) */
105
+ export function mainDumpArgs(schemas, snapshotId) {
106
+ return [
107
+ "--format=custom",
108
+ "--no-owner",
109
+ "--no-privileges",
110
+ ...(snapshotId ? [`--snapshot=${snapshotId}`] : []),
111
+ ...schemas.map((s) => `--schema=${s}`),
112
+ ];
113
+ }
114
+ class AuthDumpTooLarge extends Error {
115
+ }
116
+ /** 等 p 最多 ms 毫秒(到点就不等了,p 仍在后台结束);谁先完成都会清掉计时器,不拖住进程退出 */
117
+ async function waitAtMost(p, ms) {
118
+ let timer;
119
+ await Promise.race([
120
+ p.then(() => { }, () => { }),
121
+ new Promise((resolve) => (timer = setTimeout(resolve, ms))),
122
+ ]);
123
+ clearTimeout(timer);
124
+ }
125
+ /**
126
+ * 流式跑 pg_dump,边写快照边算 sha256 与字节数。返回校验和与大小。
127
+ * onFirstByte:pg_dump 先导入快照才会吐出第一个字节,调用方据此尽早释放导出快照的连接。
128
+ * maxBytes:超过就中止(只用于 auth.dump)。
129
+ */
130
+ async function streamPgDump(opts) {
105
131
  const hash = createHash("sha256");
106
132
  let bytes = 0;
107
133
  const meter = new Transform({
108
134
  transform(chunk, _enc, cb) {
135
+ if (bytes === 0)
136
+ opts.onFirstByte?.();
109
137
  hash.update(chunk);
110
138
  bytes += chunk.length;
139
+ if (opts.maxBytes !== undefined && bytes > opts.maxBytes) {
140
+ cb(new AuthDumpTooLarge(`archive is larger than ${opts.maxBytes} bytes`));
141
+ return;
142
+ }
111
143
  cb(null, chunk);
112
144
  },
113
145
  });
114
- const schemaArgs = config.schemas.map((s) => `--schema=${s}`);
146
+ // 中止、超限时会带错 destroy 这个流;上传一侧若没在读它,没人接的 error 事件会让整个进程崩掉。
147
+ // 错误本身由下面 dumpDone / upload.done 的 Promise 报出来,这里只需要接住
148
+ meter.on("error", () => { });
115
149
  // pg_dump(libpq):Supabase 主机才改写成 sslmode=verify-full + sslrootcert=<打包CA临时文件>
116
150
  // 凭据不进 argv(D6):argv 对同机任何进程的 `ps` 可见。与恢复路径同一个函数——
117
151
  // 先改写 SSL 再拆密码,密码经 PGPASSWORD 交给 libpq
118
- const { url: dumpDbUrl, env: credentialEnv } = credentialSafeDbArgs(dumpUrlFor(config.databaseUrl));
119
- const dump = spawn(pgDumpBin, [
120
- "--format=custom",
121
- "--no-owner",
122
- "--no-privileges",
123
- ...schemaArgs,
124
- "--dbname",
125
- dumpDbUrl,
126
- ],
152
+ const { url: dumpDbUrl, env: credentialEnv } = credentialSafeDbArgs(dumpUrlFor(opts.databaseUrl));
153
+ const dump = spawn(opts.pgDumpBin, [...opts.args, "--dbname", dumpDbUrl],
127
154
  // 环境剔除改写目标/身份的 PG* 变量:pg_dump 只认 --dbname 里的 URL(TLS 策略等保留)
128
155
  {
129
156
  stdio: ["ignore", "pipe", "pipe"],
130
157
  env: libpqChildEnv(credentialEnv, process.env, {
131
- supabaseHost: isSupabaseHost(config.databaseUrl),
158
+ supabaseHost: isSupabaseHost(opts.databaseUrl),
132
159
  urlSslMode: urlSslModeOf(dumpDbUrl),
133
160
  }),
134
161
  });
162
+ // 调用方要求停下(例如主 dump 失败了、或 Auth 等太久):杀掉 pg_dump,并直接中止上传和数据流——
163
+ // pg_dump 可能早已退出、卡住的是上传,只杀进程停不下来
164
+ let upload = null;
165
+ const onAbort = () => {
166
+ dump.kill("SIGKILL");
167
+ meter.destroy(new Error("stopped by the caller"));
168
+ void upload?.abort().catch(() => { });
169
+ };
170
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
135
171
  let stderr = "";
136
172
  dump.stderr.on("data", (d) => {
137
173
  stderr += d.toString();
138
174
  });
139
- dump.stdout.pipe(meter);
175
+ // endOnlyOnSuccess(auth.dump 用):pg_dump 成功退出才结束上传流,失败就带错中断,上传因此完不成——
176
+ // 不在用户桶里留下一个空的或半截的 auth.dump。主 dump 不传这个选项,行为与之前一致
177
+ dump.stdout.pipe(meter, { end: !opts.endOnlyOnSuccess });
178
+ if (opts.endOnlyOnSuccess) {
179
+ dump.on("close", (code) => {
180
+ if (code === 0)
181
+ meter.end();
182
+ else
183
+ meter.destroy(new Error(`pg_dump exited with code ${code}`));
184
+ });
185
+ }
140
186
  const dumpDone = new Promise((resolve, reject) => {
141
187
  dump.on("error", reject); // 启动失败(如 ENOENT)
142
188
  dump.on("close", (code) => code === 0
@@ -148,20 +194,304 @@ async function dumpToSnapshot(config, writer, pgDumpBin, dumpRelationBytes) {
148
194
  // 写入上,调用方(worker 的串行队列)随之永久挂起。Promise.all 会订阅两侧,
149
195
  // 先失败的一方抛出后,另一方稍后的 rejection 也已被视为 handled。
150
196
  // 开始上传也放进 try:实现可能在建上传时就同步抛错,那时 pg_dump 已经在跑,同样要杀掉。
151
- let upload = null;
197
+ // 调用方要求停下时立刻以失败收场,不等 pg_dump 和上传各自收尾——卡住的可能正是它们之一。
198
+ // 没传 signal(主 dump)时这个 Promise 永不 settle,行为与之前一致
199
+ const stopped = new Promise((_, reject) => {
200
+ if (opts.signal?.aborted)
201
+ reject(new Error("stopped by the caller"));
202
+ opts.signal?.addEventListener("abort", () => reject(new Error("stopped by the caller")), { once: true });
203
+ });
204
+ stopped.catch(() => { });
152
205
  try {
153
- upload = writer.uploadDump(meter, dumpRelationBytes);
154
- await Promise.all([dumpDone, upload.done]);
206
+ upload = opts.upload(meter);
207
+ const finished = Promise.all([dumpDone, upload.done]);
208
+ finished.catch(() => { }); // 被叫停后它可能才失败,不能变成没人接的 rejection
209
+ await Promise.race([finished, stopped]);
155
210
  }
156
211
  catch (error) {
157
212
  dumpDone.catch(() => { }); // 没走到 Promise.all 时,被杀的 pg_dump 的退出也得有人接住
158
213
  dump.kill("SIGKILL");
159
214
  meter.destroy();
160
- await upload?.abort().catch(() => { });
215
+ // 被叫停时中止上传但不等它(可能正卡在那)。可叫停的调用(Auth、共享快照那次)自己失败时,
216
+ // 等中止最多 5 秒——中止本身也可能卡住,不能让调用方跟着卡。主 dump 的老路径照旧等中止完成
217
+ if (opts.signal?.aborted)
218
+ void upload?.abort().catch(() => { });
219
+ else if (opts.signal || opts.boundedCleanup)
220
+ await waitAtMost(upload?.abort() ?? Promise.resolve(), 5000);
221
+ else
222
+ await upload?.abort().catch(() => { });
223
+ // 超限时先失败的往往是上传那一侧(流被 meter 报错中断),原因统一报成超限
224
+ if (opts.maxBytes !== undefined && bytes > opts.maxBytes) {
225
+ throw new AuthDumpTooLarge(`archive is larger than ${opts.maxBytes} bytes`);
226
+ }
161
227
  throw error;
162
228
  }
229
+ finally {
230
+ opts.signal?.removeEventListener("abort", onAbort);
231
+ }
163
232
  return { bytes, sha256: hash.digest("hex") };
164
233
  }
234
+ /**
235
+ * Auth 一侧的两个时限(导出供测试调短,产品里不改):
236
+ * - waitAfterMainMs:主 dump 完成后还肯等 Auth 导出多久
237
+ * - prepareDeadlineMs:主 dump 开始前,导出快照 + 统计最多花多久(连接、锁、查询都算在内)
238
+ */
239
+ export const AUTH_TIMEOUTS = {
240
+ waitAfterMainMs: 10 * 60 * 1000,
241
+ prepareDeadlineMs: 2 * 60 * 1000,
242
+ /**
243
+ * 两份 dump 一起启动后,主 dump 最迟多久要吐出第一个字节。连接池会排队的环境里(例如名额只有两个),
244
+ * 导出快照的连接和 Auth dump 可能占满名额、让主 dump 一直排在后面——到点就放掉 Auth 这两条连接,
245
+ * 把名额让给主 dump(它若还没导入快照,稍后会在写出任何东西之前失败,再按今天的方式重导)
246
+ */
247
+ mainStartGraceMs: 60 * 1000,
248
+ };
249
+ /** 做不了 Auth 备份时记什么:默认开启记 skipped(不算失败);显式要求记 failed */
250
+ function authNotDone(mode, reason) {
251
+ return mode === "on" ? { status: "failed", reason } : { status: "skipped", reason };
252
+ }
253
+ const AUTH_SKIP_TEXT = {
254
+ no_permission: "the backup role can't read every row of auth.users and auth.identities (it needs BYPASSRLS or superuser, plus read access)",
255
+ no_auth_schema: "this database has no Supabase auth schema",
256
+ unsupported_destination: "this backup destination can't hold the Auth archive yet",
257
+ schemas_include_auth: "your schema list includes auth, so the Auth users are in the database dump",
258
+ schemas_not_plain: "your schema list uses a pattern or a quoted name, so the Auth users aren't backed up separately " +
259
+ "(they are in the database dump only if one of those patterns matches auth)",
260
+ too_large: "the Auth archive is larger than 2 GiB",
261
+ snapshot_unavailable: "a consistent snapshot for the Auth export couldn't be set up",
262
+ };
263
+ /** 报错只留第一行、截短:pg_dump / 上传的错误不该把大段原文(更不能是行值)带进 manifest 和告警 */
264
+ function shortReason(error) {
265
+ return redactValues(String(error?.message ?? error).split("\n")[0]).slice(0, 300);
266
+ }
267
+ /**
268
+ * 决定这次要不要、能不能另外备 Auth。任何"不能"都在这里落成 skipped/failed,不抛错——
269
+ * 主 dump 永远不因 Auth 受影响。返回 dump 时,共享快照已经导出,调用方负责释放。
270
+ */
271
+ async function planAuth(config, writer, mode) {
272
+ if (mode === "off")
273
+ return { kind: "none" };
274
+ // schemas 已经(可能)把 auth 带进主 dump:今天怎样以后还怎样,不另备一份。
275
+ // 确定包含 → skipped(数据就在主 dump 里);说不准 → 默认模式也 skipped,显式要求时记 failed,
276
+ // 不能在 Auth 用户可能哪份归档都不在的情况下报成功
277
+ const inSchemas = authInSchemas(config.schemas);
278
+ if (inSchemas === "yes") {
279
+ return { kind: "settled", section: { status: "skipped", reason: "schemas_include_auth" } };
280
+ }
281
+ if (inSchemas === "maybe") {
282
+ return { kind: "settled", section: authNotDone(mode, "schemas_not_plain") };
283
+ }
284
+ if (!writer.uploadAuthDump || !writer.authDumpKey) {
285
+ return { kind: "settled", section: authNotDone(mode, "unsupported_destination") };
286
+ }
287
+ // 导出快照和统计都发生在主 dump 之前,必须有总时限:连接池满时新连接会一直排队,
288
+ // 不能让数据库备份陪着等。到点就按"快照不可用"放弃,并立刻断开 Auth 的两条连接
289
+ // (不管它们还在排队还是在跑查询),把连接让给主 dump
290
+ const stop = new AbortController();
291
+ const prepared = prepareAuthDump(config, writer, mode, stop.signal);
292
+ prepared.catch(() => { });
293
+ let deadline;
294
+ const timedOut = new Promise((resolve) => {
295
+ deadline = setTimeout(() => {
296
+ stop.abort();
297
+ void prepared.then((late) => (late.kind === "dump" ? late.shared.release() : undefined)).catch(() => { });
298
+ resolve({ kind: "settled", section: authNotDone(mode, "snapshot_unavailable") });
299
+ }, AUTH_TIMEOUTS.prepareDeadlineMs);
300
+ });
301
+ const plan = await Promise.race([prepared, timedOut]);
302
+ clearTimeout(deadline);
303
+ return plan;
304
+ }
305
+ async function prepareAuthDump(config, writer, mode, signal) {
306
+ const shared = await exportSharedSnapshot(config.databaseUrl, signal);
307
+ if (!shared)
308
+ return { kind: "settled", section: authNotDone(mode, "snapshot_unavailable") };
309
+ let inspection;
310
+ try {
311
+ inspection = await inspectAuth(config.databaseUrl, shared.id, signal);
312
+ }
313
+ catch (error) {
314
+ await shared.release();
315
+ // 导入快照失败(经连接池时最可能)按"快照不可用"跳过;其余是统计查询本身出错
316
+ const section = /snapshot/i.test(shortReason(error))
317
+ ? authNotDone(mode, "snapshot_unavailable")
318
+ : { status: "failed", reason: `could not inspect the Auth tables: ${shortReason(error)}` };
319
+ return { kind: "settled", section };
320
+ }
321
+ if (!inspection.readable) {
322
+ await shared.release();
323
+ return { kind: "settled", section: authNotDone(mode, inspection.reason) };
324
+ }
325
+ const uploadAuthDump = writer.uploadAuthDump.bind(writer);
326
+ return { kind: "dump", shared, inspection, key: writer.authDumpKey, upload: (body) => uploadAuthDump(body) };
327
+ }
328
+ /**
329
+ * 主 dump 和 auth dump 并行,都导入同一个共享快照。两份都吐出第一个字节(= 都已导入快照)后
330
+ * 立刻释放导出快照的连接,所以它只占几秒,和主 dump 多大无关。
331
+ * Auth 一侧失败只影响 Auth 段;主 dump 因导入快照失败而一个字节都没写出时,按今天的方式重导一次。
332
+ */
333
+ async function dumpWithAuth(config, writer, pgDumpBin, relationBytes, mode, plan) {
334
+ const { shared, inspection } = plan;
335
+ let mainStarted = false;
336
+ let markMainStarted;
337
+ let markAuthStarted;
338
+ const mainStartedP = new Promise((resolve) => (markMainStarted = resolve));
339
+ const authStartedP = new Promise((resolve) => (markAuthStarted = resolve));
340
+ void Promise.all([mainStartedP, authStartedP]).then(() => shared.release());
341
+ const authAbort = new AbortController();
342
+ const authRun = streamPgDump({
343
+ databaseUrl: config.databaseUrl,
344
+ pgDumpBin,
345
+ args: authDumpArgs(shared.id),
346
+ upload: plan.upload,
347
+ onFirstByte: () => markAuthStarted(),
348
+ maxBytes: AUTH_DUMP_MAX_BYTES,
349
+ signal: authAbort.signal,
350
+ endOnlyOnSuccess: true,
351
+ }).then((result) => ({ ok: true, ...result }), (error) => ({ ok: false, error }));
352
+ void authRun.finally(() => markAuthStarted());
353
+ // 看门狗:主 dump 迟迟没开始,就是被 Auth 的连接挤住了,先让路(见 AUTH_TIMEOUTS.mainStartGraceMs)
354
+ const mainStartWatchdog = setTimeout(() => {
355
+ if (mainStarted)
356
+ return;
357
+ log.warn("The database dump hasn't started yet; stopping the Auth export to free its connections.");
358
+ authAbort.abort();
359
+ void shared.release();
360
+ }, AUTH_TIMEOUTS.mainStartGraceMs);
361
+ let main;
362
+ try {
363
+ main = await streamPgDump({
364
+ databaseUrl: config.databaseUrl,
365
+ pgDumpBin,
366
+ args: mainDumpArgs(config.schemas, shared.id),
367
+ upload: (body) => writer.uploadDump(body, relationBytes),
368
+ onFirstByte: () => {
369
+ mainStarted = true;
370
+ clearTimeout(mainStartWatchdog);
371
+ markMainStarted();
372
+ },
373
+ // 这一次可能因导入快照失败而重来,重来写的是同一个键:失败的这次绝不能"正常结束"上传——
374
+ // 否则它那份空的 PutObject 可能晚于重来的那份完成,把好的备份盖掉
375
+ endOnlyOnSuccess: true,
376
+ boundedCleanup: true,
377
+ });
378
+ }
379
+ catch (error) {
380
+ clearTimeout(mainStartWatchdog);
381
+ markMainStarted();
382
+ authAbort.abort();
383
+ // 收尾都有上限:Auth 那边的清理(或者释放快照连接)就算卡住,也不能挡住下面的回退重导
384
+ await waitAtMost(authRun, 5000);
385
+ await waitAtMost(shared.release(), 5000);
386
+ // 主 dump 一个字节都没写出就失败了(导入快照失败、连接名额被 Auth 的两条连接占满……原因不限):
387
+ // Auth 的连接上面已经全部放掉,Auth 这次不做,主 dump 按今天的方式重导一次。
388
+ // 重导再失败,就是今天也会失败的情况,照常报错
389
+ if (!mainStarted) {
390
+ log.warn(`The database dump couldn't start alongside the Auth export (${shortReason(error)}); dumping it the usual way.`);
391
+ const plain = await plainDumpAfterAuthReleased(config, writer, pgDumpBin, relationBytes);
392
+ return { main: plain, auth: authNotDone(mode, "snapshot_unavailable") };
393
+ }
394
+ throw error;
395
+ }
396
+ clearTimeout(mainStartWatchdog);
397
+ // 主 dump 已经完成:Auth 两张表通常几秒就导完。万一那边卡住,最多再等这么久就放弃,
398
+ // 不能让整份备份(以及 worker 的串行队列)陪着它挂住。到点就立刻判失败往下走,
399
+ // 不再等 authRun 收尾——卡住的可能正是它
400
+ let authTimer;
401
+ const authResult = await Promise.race([
402
+ authRun,
403
+ new Promise((resolve) => {
404
+ authTimer = setTimeout(() => {
405
+ authAbort.abort();
406
+ resolve({ ok: false, error: new Error(`timed out ${Math.round(AUTH_TIMEOUTS.waitAfterMainMs / 1000)}s after the main dump`) });
407
+ }, AUTH_TIMEOUTS.waitAfterMainMs);
408
+ }),
409
+ ]);
410
+ clearTimeout(authTimer);
411
+ await waitAtMost(shared.release(), 5000);
412
+ if (!authResult.ok) {
413
+ const auth = authResult.error instanceof AuthDumpTooLarge
414
+ ? authNotDone(mode, "too_large")
415
+ : { status: "failed", reason: `Auth archive not written: ${shortReason(authResult.error)}` };
416
+ return { main, auth };
417
+ }
418
+ return {
419
+ main,
420
+ auth: {
421
+ status: "included",
422
+ dump: { key: plan.key, format: "custom", bytes: authResult.bytes, sha256: authResult.sha256 },
423
+ rows: { users: inspection.users, identities: inspection.identities },
424
+ passwordHashes: inspection.passwordHashes,
425
+ anonymousUsers: inspection.anonymousUsers,
426
+ ssoUsers: inspection.ssoUsers,
427
+ mfaUsers: inspection.mfaUsers,
428
+ triggers: inspection.triggers,
429
+ policies: inspection.policies,
430
+ grants: inspection.grants,
431
+ },
432
+ };
433
+ }
434
+ /**
435
+ * 共享快照那次失败后,按今天的方式重导主 dump。刚放掉的 Auth 连接在服务端要过一小会儿才真正退出,
436
+ * 连接名额紧(角色或连接池上限)时立刻重连可能还会撞上"连接满了":这类错误稍等再试,最多三次。
437
+ * 每次都只在 pg_dump 成功时才结束上传——失败那次的空上传绝不能晚到、盖掉成功的那次。
438
+ */
439
+ async function plainDumpAfterAuthReleased(config, writer, pgDumpBin, relationBytes) {
440
+ const delays = [1000, 3000];
441
+ for (let attempt = 0;; attempt++) {
442
+ let started = false;
443
+ try {
444
+ return await streamPgDump({
445
+ databaseUrl: config.databaseUrl,
446
+ pgDumpBin,
447
+ args: mainDumpArgs(config.schemas),
448
+ upload: (body) => writer.uploadDump(body, relationBytes),
449
+ onFirstByte: () => (started = true),
450
+ endOnlyOnSuccess: true,
451
+ boundedCleanup: true,
452
+ });
453
+ }
454
+ catch (error) {
455
+ const connectionsFull = /too many connections|remaining connection slots|connection limit/i.test(shortReason(error));
456
+ if (started || !connectionsFull || attempt >= delays.length)
457
+ throw error;
458
+ await new Promise((resolve) => setTimeout(resolve, delays[attempt]));
459
+ }
460
+ }
461
+ }
462
+ /** 备份结束时把 Auth 段的结果说给人听;warn 的都是不影响数据库备份的事 */
463
+ function logAuthOutcome(auth, schemas) {
464
+ if (auth.status === "included") {
465
+ log.ok(`Auth users backed up (${auth.rows.users.toLocaleString("en-US")} users, ` +
466
+ `${auth.rows.identities.toLocaleString("en-US")} sign-in identities, ` +
467
+ `${(auth.dump.bytes / 1024 / 1024).toFixed(1)} MB)`);
468
+ if (auth.passwordHashes.unrecognized > 0) {
469
+ log.warn(`${auth.passwordHashes.unrecognized} password hash(es) are in a format BackupDrill doesn't recognize; ` +
470
+ `whether those users can sign in with their old password after a restore is unknown.`);
471
+ }
472
+ if (auth.passwordHashes.encrypted > 0) {
473
+ log.warn(`${auth.passwordHashes.encrypted} password hash(es) are encrypted with this project's key; ` +
474
+ `after a restore into a new project those users can't sign in with their old password.`);
475
+ }
476
+ // 备份时只提示用户自己能补救的(把缺的 schema 加进备份);其余在 RECOVERY.md 和恢复报告里列成手工步骤
477
+ for (const note of manualAuthObjects({ triggers: auth.triggers, policies: auth.policies }, schemas)) {
478
+ if (note.includes("not in this backup"))
479
+ log.warn(`The ${note}. Add that schema to the backup to keep it.`);
480
+ }
481
+ return;
482
+ }
483
+ const why = AUTH_SKIP_TEXT[auth.reason ?? ""] ?? auth.reason ?? "unknown reason";
484
+ if (auth.status === "skipped") {
485
+ // 不是 Supabase 库时这是正常情况,不该显得像个问题
486
+ if (auth.reason === "no_auth_schema")
487
+ log.step(`Auth users: skipped (${why}).`);
488
+ else
489
+ log.warn(`Auth users not backed up: ${why}. The database backup itself is complete.`);
490
+ }
491
+ else {
492
+ log.warn(`Auth users backup failed: ${why}. The database backup itself is complete.`);
493
+ }
494
+ }
165
495
  export async function runBackup(config, opts = {}) {
166
496
  // 源身份先于一切传输(评审第 12 轮):①连接串不许带 ?host=/user= 覆盖——否则
167
497
  // 快照记的 ref 与实际读取对象脱节,恢复端的同源保护随之失真;②库与 Storage
@@ -203,9 +533,30 @@ export async function runBackup(config, opts = {}) {
203
533
  // 哪次读不到都让备份失败,不留一份缺授权记录的快照:恢复端把"没有记录"当成 2.9.0 之前的旧快照,
204
534
  // 按 Supabase 以前的默认授权开放 public,会把源库关着的表打开
205
535
  const grantsBeforeDump = await readGrants(config.databaseUrl, config.schemas);
536
+ // Auth 用户另备一份(2.10.0 起,见 auth-backup.ts)。库调用方没传 = 关闭,下面走的就是之前的那条路,
537
+ // 参数、文件、manifest 都和之前一样。共享快照在转储前一刻才导出,尽量少占连接
538
+ const authMode = config.auth ?? "off";
539
+ const authPlan = await planAuth(config, writer, authMode);
540
+ let auth = authPlan.kind === "settled" ? authPlan.section : undefined;
206
541
  log.step(`Dumping → ${writer.describe("dump.pgcustom")}`);
207
- const { bytes, sha256 } = await dumpToSnapshot(config, writer, pgDumpBin, db.relationBytes);
542
+ let bytes;
543
+ let sha256;
544
+ if (authPlan.kind === "dump") {
545
+ const result = await dumpWithAuth(config, writer, pgDumpBin, db.relationBytes, authMode, authPlan);
546
+ ({ bytes, sha256 } = result.main);
547
+ auth = result.auth;
548
+ }
549
+ else {
550
+ ({ bytes, sha256 } = await streamPgDump({
551
+ databaseUrl: config.databaseUrl,
552
+ pgDumpBin,
553
+ args: mainDumpArgs(config.schemas),
554
+ upload: (body) => writer.uploadDump(body, db.relationBytes),
555
+ }));
556
+ }
208
557
  log.ok(`Database dumped (${(bytes / 1024 / 1024).toFixed(1)} MB, sha256 ${sha256.slice(0, 12)}…)`);
558
+ if (auth)
559
+ logAuthOutcome(auth, config.schemas);
209
560
  const grants = grantsHeldThroughout(grantsBeforeDump, await readGrants(config.databaseUrl, config.schemas));
210
561
  // Storage 文件同步(源配置存在才做;否则只备数据库)
211
562
  let storageResult = null;
@@ -255,6 +606,8 @@ export async function runBackup(config, opts = {}) {
255
606
  grants,
256
607
  },
257
608
  dump: { key: dumpKey, format: "custom", bytes, sha256 },
609
+ // 关闭时不写这个字段:manifest 与之前逐字节一致
610
+ ...(auth ? { auth } : {}),
258
611
  storage: storageResult,
259
612
  };
260
613
  // RECOVERY.md(PRD §5.9.2.1)先于 manifest 落桶:manifest 是快照的"完成标记"
package/dist/config.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { AuthMode } from "./auth-backup.js";
1
2
  /**
2
3
  * 目标对象存储(S3 兼容:AWS S3 / Cloudflare R2 / Backblaze B2 / Supabase Storage 的 S3 端点均可)。
3
4
  * 凭据永远来自用户自己的环境 —— CLI 不托管任何密钥,这是"数据不落我们盘"叙事在开源侧的兑现。
@@ -28,6 +29,12 @@ export interface BackupConfig {
28
29
  schemas: string[];
29
30
  storage?: StorageConfig;
30
31
  supabaseStorage?: SupabaseStorageConfig;
32
+ /**
33
+ * 2.10.0 起:是否另外备份 Supabase Auth 用户(auth.users + auth.identities,见 auth-backup.ts)。
34
+ * 库调用方不传 = "off",备份与之前逐字节一致;托管 worker 显式传值才打开。
35
+ * CLI 的 loadConfig 默认 "default"(做得了就备,做不了只警告);--auth / BACKUPDRILL_AUTH=on 给 "on",关掉给 "off"。
36
+ */
37
+ auth?: AuthMode;
31
38
  }
32
39
  /** CLI 读出来的配置一定带桶:loadConfig 缺了桶直接报错,所以返回类型里 storage 是必填 */
33
40
  export type LoadedBackupConfig = BackupConfig & {
@@ -42,6 +49,8 @@ interface RawConfig {
42
49
  storage?: Partial<StorageConfig>;
43
50
  supabaseStorage?: Partial<SupabaseStorageConfig>;
44
51
  pingUrl?: string;
52
+ /** 配置文件里写 true / false;CLI 是 --auth / --no-auth,环境变量 BACKUPDRILL_AUTH=on|off */
53
+ auth?: boolean;
45
54
  }
46
55
  /**
47
56
  * 监控 ping 网址(Healthchecks.io 那种):flag > 环境变量 > 配置文件,空串算没配
package/dist/config.js CHANGED
@@ -6,6 +6,17 @@ export function requireBucket(config) {
6
6
  }
7
7
  return config.storage;
8
8
  }
9
+ /** BACKUPDRILL_AUTH:on/true/1 = 显式要求,off/false/0 = 不备;空串算没设(GitHub Actions 里没配的 secret) */
10
+ function authFromEnv(value) {
11
+ const v = value?.trim().toLowerCase();
12
+ if (!v)
13
+ return undefined;
14
+ if (["on", "true", "1", "yes"].includes(v))
15
+ return true;
16
+ if (["off", "false", "0", "no"].includes(v))
17
+ return false;
18
+ throw new Error(`BACKUPDRILL_AUTH must be "on" or "off" (got "${value}")`);
19
+ }
9
20
  /** "a, b" → ["a", "b"]。只有逗号和空白时算没设:空列表会盖掉配置文件里的值。 */
10
21
  function listFromEnv(value) {
11
22
  const items = value?.split(",").map((s) => s.trim()).filter(Boolean);
@@ -49,6 +60,7 @@ function fromEnv() {
49
60
  schemas: listFromEnv(env.BACKUPDRILL_SCHEMAS),
50
61
  storage,
51
62
  supabaseStorage,
63
+ auth: authFromEnv(env.BACKUPDRILL_AUTH),
52
64
  };
53
65
  }
54
66
  async function fromFile(path) {
@@ -138,9 +150,14 @@ export async function loadConfig(opts) {
138
150
  buckets: src.buckets,
139
151
  };
140
152
  }
153
+ // 显式 flag > 环境变量 > 配置文件。都没说 = "default"(2.10.0 起,PRD 决策 D4):做得了就备,
154
+ // 做不了(角色读不到 auth、目标存不下……)只警告、退出码照旧是 0,定时备份不会因此变红
155
+ const authChoice = [o.auth, env.auth, file.auth].find((v) => typeof v === "boolean");
156
+ const auth = authChoice === undefined ? "default" : authChoice ? "on" : "off";
141
157
  return {
142
158
  databaseUrl: databaseUrl,
143
159
  projectName,
160
+ auth,
144
161
  schemas: schemas.length ? schemas : ["public"],
145
162
  storage: {
146
163
  endpoint: storage.endpoint,
package/dist/drill.d.ts CHANGED
@@ -3,6 +3,7 @@ import type { Manifest } from "./manifest.js";
3
3
  import { type SnapshotStore } from "./snapshot-store.js";
4
4
  import { type OrphanedForeignKey } from "./orphaned-foreign-keys.js";
5
5
  import { type GrantRestore } from "./grants.js";
6
+ import { type AuthDrillReport, type AuthDumpForDrill } from "./auth-drill.js";
6
7
  /**
7
8
  * 无放回随机抽样:部分 Fisher-Yates,只洗出前 n 位(O(n) 次交换,不必全 shuffle)。
8
9
  * 此前恒取 manifest 顺序的前 CAP 个 → 超过 CAP 的项目里排序靠后的文件永远不被校验;
@@ -12,18 +13,23 @@ import { type GrantRestore } from "./grants.js";
12
13
  */
13
14
  export declare function sampleStorageFiles<T>(files: T[], n: number): T[];
14
15
  /** @internal 托管 worker 专用钩子;事件不携带客户数据或凭据,不属于稳定 CLI 契约。 */
15
- export type DrillPhase = "download" | "storage" | "sandbox" | "restore" | "verify" | "cleanup";
16
+ export type DrillPhase = "download" | "storage" | "sandbox" | "restore" | "verify" | "auth" | "cleanup";
16
17
  export interface DrillSupervision {
17
18
  /** 仅 runDrill 使用:supervisor 独占的空临时目录,由 supervisor 清理。 */
18
19
  workdir: string;
19
20
  /** 每次尝试唯一;即使 docker run 被中断,supervisor 也能按名字清理。 */
20
21
  resourceName: string;
21
- /** 非 cleanup 阶段抛错 = 主动中止并清理;上报失败应由调用方自行吞掉,回调须自带超时(托管 worker 另有进程级执行上限)。
22
- * cleanup 阶段同步/异步错误均忽略,最多等待 5 秒,绝不阻止 teardown。 */
22
+ /** 非 cleanup、非 auth 阶段抛错 = 主动中止并清理;上报失败应由调用方自行吞掉,回调须自带超时(托管 worker 另有进程级执行上限)。
23
+ * cleanup 阶段同步/异步错误均忽略,最多等待 5 秒,绝不阻止 teardown。auth 阶段抛错只跳过 Auth 附加检查。 */
23
24
  observe: (event: {
24
25
  phase: DrillPhase;
25
26
  dumpBytes?: number;
26
27
  }) => Promise<void>;
28
+ /**
29
+ * 2.10.0 起:supervisor 叫停 Auth 附加检查(比如磁盘吃紧)。这一节记 not_checked,演练结论不变——
30
+ * 结论在 Auth 这一节之前就定了。"auth" 阶段的 observe 被拒绝同样只跳过这一节,不中止演练
31
+ */
32
+ authStop?: AbortSignal;
27
33
  }
28
34
  export interface DrillCheck {
29
35
  name: string;
@@ -44,6 +50,11 @@ export interface DrillReport {
44
50
  };
45
51
  /** 源库自带孤儿行的外键:演练和真实恢复都把它们建成 NOT VALID,不算失败。没有时不出现 */
46
52
  orphanedForeignKeys?: OrphanedForeignKey[];
53
+ /**
54
+ * 2.10.0 起,快照带 Auth 用户时的附加校验(见 auth-drill.ts)。**不参与 pass 的判定**;
55
+ * 快照不带 Auth 时不出现
56
+ */
57
+ auth?: AuthDrillReport;
47
58
  }
48
59
  export interface SandboxTuning {
49
60
  settings: string[];
@@ -94,6 +105,10 @@ export declare function drillDump(dumpPath: string, manifest: Manifest, snapshot
94
105
  appCheckCommand?: string;
95
106
  keepSandboxOnFailure?: boolean;
96
107
  supervision?: DrillSupervision;
108
+ /** 快照带 Auth 用户时 runDrill 在后台下载的 auth.dump(和正式演练同时进行) */
109
+ authDump?: Promise<AuthDumpForDrill>;
110
+ /** Auth 那一节超时放弃时,叫停还没下完的 auth.dump */
111
+ stopAuthDownload?: () => void;
97
112
  }): Promise<DrillReport>;
98
113
  /** 演练一份快照:从桶里下载→drillDump(含 Storage 校验)→报告。 */
99
114
  export declare function runDrill(config: BackupConfig, opts?: {
@@ -105,5 +120,11 @@ export declare function runDrill(config: BackupConfig, opts?: {
105
120
  supervision?: DrillSupervision;
106
121
  /** 快照从哪读;省略 = config.storage 指的 S3 兼容桶 */
107
122
  store?: SnapshotStore;
123
+ /**
124
+ * 快照带 Auth 用户时做不做附加的 Auth 校验(不影响结论,见 auth-drill.ts)。默认:没有 supervision 时做
125
+ * (CLI);有 supervision(托管 worker)时不做——auth.dump 不在它按 dumpBytes 算的磁盘预算里,
126
+ * 等 worker 把两份都算进预算再显式打开
127
+ */
128
+ authCheck?: boolean;
108
129
  }): Promise<DrillReport>;
109
130
  export {};
package/dist/drill.js CHANGED
@@ -13,6 +13,7 @@ import { orphanedForeignKeysCheck } from "./orphaned-foreign-keys.js";
13
13
  import { grantsCheck } from "./grants.js";
14
14
  import { localPgRestoreMajor, restoreToolBreaksOnTarget, sandboxMajorFor } from "./pgbin.js";
15
15
  import { log } from "./log.js";
16
+ import { authDrillSection } from "./auth-drill.js";
16
17
  import { onInterrupt, stopOnInterrupt, throwIfInterrupted } from "./interrupt.js";
17
18
  const execFileAsync = promisify(execFile);
18
19
  // Storage 校验默认抽样上限(避免每次演练重下全部文件产生大量 egress);超限如实记录
@@ -649,6 +650,21 @@ export async function drillDump(dumpPath, manifest, snapshot, preChecks = [], op
649
650
  };
650
651
  if (orphaned.length)
651
652
  report.orphanedForeignKeys = orphaned;
653
+ // Auth 附加校验:结论(pass)上面已经定了,这里只往报告里加一节。它在同一个沙箱里补外键、
654
+ // 建触发器、模拟注册——放在所有正式检查之后,不影响它们;自己出错也只记在这一节里
655
+ const authSection = await authDrillSection(pg.connString, manifest, dumpPath, opts.authDump, opts.stopAuthDownload, {
656
+ // 托管 worker 在这一步前后换磁盘守卫的规则:Auth 阶段吃紧只叫停这一节,不判演练失败
657
+ begin: opts.supervision ? () => opts.supervision.observe({ phase: "auth" }) : undefined,
658
+ stop: opts.supervision?.authStop,
659
+ });
660
+ if (authSection) {
661
+ report.auth = authSection;
662
+ const line = `Auth users: ${authSection.summary}`;
663
+ if (authSection.status === "verified")
664
+ log.ok(line);
665
+ else
666
+ log.warn(line);
667
+ }
652
668
  if (opts.keepSandboxOnFailure && !pass) {
653
669
  // 写进报告让 --keep 可被脚本消费(拿连接串排查),不只靠人眼看日志
654
670
  report.keptSandbox = { containerId: pg.containerId, connString: pg.connString };
@@ -690,6 +706,7 @@ export async function runDrill(config, opts = {}) {
690
706
  const workdir = opts.supervision?.workdir ?? await mkdtemp(join(tmpdir(), "backupdrill-"));
691
707
  const dumpPath = join(workdir, "dump.pgcustom");
692
708
  // 下载的 dump 在这里;托管模式的目录归 supervisor 管
709
+ const authDownloadStop = new AbortController();
693
710
  const forgetWorkdir = opts.supervision
694
711
  ? () => { }
695
712
  : onInterrupt(() => rm(workdir, { recursive: true, force: true }).catch(() => { }));
@@ -731,13 +748,32 @@ export async function runDrill(config, opts = {}) {
731
748
  detail: "the manifest lists Storage files, but this snapshot location cannot hold them",
732
749
  });
733
750
  }
751
+ // 快照带 Auth 用户:在后台把 auth.dump 取下来给附加校验用,和正式演练同时进行、不让它等。
752
+ // 取不到只记进报告的 Auth 一节
753
+ let authDump;
754
+ if (manifest.auth?.status === "included" && (opts.authCheck ?? !opts.supervision)) {
755
+ const authPath = join(workdir, "auth.dump");
756
+ const download = reader.downloadAuthDump;
757
+ const stopAuthDownload = authDownloadStop;
758
+ // 下载出错的原文不进报告(里面可能有凭据、对象键之类),只给固定的说法;
759
+ // 同步抛出的错误也在这个 Promise 里接住,绝不冒到演练本身
760
+ authDump = download
761
+ ? Promise.resolve()
762
+ .then(() => download.call(reader, manifest, authPath, { signal: stopAuthDownload.signal }))
763
+ .then(() => ({ path: authPath }), () => ({ error: "the Auth archive couldn't be downloaded" }))
764
+ : Promise.resolve({ error: "this snapshot location can't read the Auth archive" });
765
+ }
734
766
  return await drillDump(dumpPath, manifest, snapshot, preChecks, {
735
767
  appCheckCommand: opts.appCheckCommand,
736
768
  keepSandboxOnFailure: opts.keepSandboxOnFailure,
737
769
  supervision: opts.supervision,
770
+ authDump,
771
+ stopAuthDownload: () => authDownloadStop.abort(),
738
772
  });
739
773
  }
740
774
  finally {
775
+ // 演练怎么结束都一样:还在下的 auth.dump 立刻停掉,不留着连接把进程拖住
776
+ authDownloadStop.abort();
741
777
  if (!opts.supervision)
742
778
  await rm(workdir, { recursive: true, force: true }).catch(() => { });
743
779
  forgetWorkdir();