backupdrill 2.11.0 → 2.11.2

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/dist/drill.js CHANGED
@@ -143,20 +143,77 @@ export function sandboxDataVolumeTarget(major) {
143
143
  * 停掉命令也说不准守护进程之后还会不会把容器建出来(交叉审查)。拆开之后,慢的那一步(第一次拉镜像
144
144
  * 可能好几分钟)什么都不建,中断时直接停掉;docker run 只剩建容器和启动。
145
145
  */
146
+ /**
147
+ * 本地已有镜像也要每次 pull:标签(postgres:17-alpine)跟着小版本走,只拉一次就会永远停在当时的小版本。
148
+ * 2026-11-24 事故:worker 上的沙箱停在 17.10,源库被 Supabase 升到带 CVE-2026-6460 补丁的新小版本,
149
+ * 旧 pg_dump 导出的 `ALTER COLUMN ... SET (pg_attver=…)` 在 17.10 上报 unrecognized parameter,
150
+ * 整个演练失败;17.12 会接受并忽略这句。镜像没变时 pull 只比一次清单,很快。
151
+ * 已有缓存时刷新失败(断网、仓库限流、超时)不算演练失败:退回本地镜像并提示。
152
+ *
153
+ * 收尾不等 stdio 关闭:docker 拉起的凭据助手可能还占着 stderr(交叉审查用卡住的助手复现)。
154
+ * 只等 docker 本身退出;到点或被中断时,连同它的子孙进程(凭据助手)一起 SIGKILL,再把我们这头的
155
+ * 管道关掉,CLI 才能照常退出,也不会每次超时留下一个助手。
156
+ * pull 留在演练所在的进程组里(不 detach):worker 叫停演练时按组结束,连助手一起带走。
157
+ */
158
+ // 测试用的环境变量只为把 5 分钟缩短到几秒;不对用户公开
159
+ const IMAGE_REFRESH_TIMEOUT_MS = Number(process.env.BACKUPDRILL_TEST_IMAGE_REFRESH_TIMEOUT_MS) || 5 * 60_000;
160
+ /** 子孙进程 pid(pgrep -P 逐层往下找);没有 pgrep(Windows)时返回空,只停进程本身 */
161
+ async function descendantPids(pid) {
162
+ const children = await execFileAsync("pgrep", ["-P", String(pid)], { timeout: 5_000 }).then(({ stdout }) => stdout.split("\n").map(Number).filter((n) => n > 0), () => []);
163
+ const deeper = await Promise.all(children.map(descendantPids));
164
+ return [...children, ...deeper.flat()];
165
+ }
166
+ /** 先记下子孙再停:父进程一死,子进程就被收养,pgrep -P 再也找不到它们 */
167
+ async function killProcessTree(child) {
168
+ if (!child.pid || child.exitCode !== null || child.signalCode !== null)
169
+ return;
170
+ const descendants = await descendantPids(child.pid);
171
+ child.kill("SIGKILL");
172
+ for (const pid of descendants) {
173
+ try {
174
+ process.kill(pid, "SIGKILL");
175
+ }
176
+ catch {
177
+ // 已经退出
178
+ }
179
+ }
180
+ }
146
181
  async function ensureImage(image) {
147
182
  const present = await execFileAsync("docker", ["image", "inspect", "--format", "{{.Id}}", image]).then(() => true, () => false);
148
- if (present)
149
- return;
150
183
  throwIfInterrupted();
151
- log.step(`Pulling ${image}…`);
152
- const pull = execFileAsync("docker", ["pull", "--quiet", image]);
153
- const forget = pull.child ? stopOnInterrupt(pull.child) : () => { };
154
- try {
155
- await pull;
156
- }
157
- finally {
158
- forget();
159
- }
184
+ log.step(present ? `Checking ${image} for updates…` : `Pulling ${image}…`);
185
+ const pull = spawn("docker", ["pull", "--quiet", image], { stdio: ["ignore", "ignore", "pipe"] });
186
+ const forget = onInterrupt(() => killProcessTree(pull));
187
+ // 只留开头一段用来说明失败原因,其余照样读掉,别让吵闹的 docker 把内存撑大
188
+ let stderr = "";
189
+ pull.stderr?.on("data", (chunk) => {
190
+ if (stderr.length < 4096)
191
+ stderr += chunk.toString();
192
+ });
193
+ let timer;
194
+ const outcome = await new Promise((resolve) => {
195
+ pull.on("error", (error) => {
196
+ stderr ||= error.message;
197
+ resolve("failed");
198
+ });
199
+ pull.on("exit", (code) => resolve(code === 0 ? "ok" : "failed"));
200
+ if (present)
201
+ timer = setTimeout(() => resolve("timeout"), IMAGE_REFRESH_TIMEOUT_MS);
202
+ });
203
+ clearTimeout(timer);
204
+ if (outcome === "timeout")
205
+ await killProcessTree(pull);
206
+ pull.stderr?.destroy();
207
+ forget();
208
+ throwIfInterrupted();
209
+ if (outcome === "ok")
210
+ return;
211
+ const reason = outcome === "timeout"
212
+ ? `docker pull timed out after ${Math.round(IMAGE_REFRESH_TIMEOUT_MS / 1000)}s`
213
+ : stderr.split("\n").map((line) => line.trim()).find(Boolean) ?? "docker pull failed";
214
+ if (!present)
215
+ throw new Error(`could not pull ${image}: ${reason}`);
216
+ log.warn(`Could not refresh ${image}; using the local copy (${reason})`);
160
217
  }
161
218
  async function startEphemeralPostgres(image, major, resourceName) {
162
219
  const dataVolumeTarget = sandboxDataVolumeTarget(major);
@@ -190,6 +247,8 @@ async function startEphemeralPostgres(image, major, resourceName) {
190
247
  "POSTGRES_DB=postgres",
191
248
  "-p",
192
249
  "127.0.0.1:0:5432", // 随机主机端口,避免撞端口
250
+ // 拉镜像只在 ensureImage 里做(有超时、可中断);缓存恰好在刷新时被清掉的话,这里报错而不是悄悄再拉一次
251
+ "--pull=never",
193
252
  `--shm-size=${tuning.shmSize}`,
194
253
  image,
195
254
  "postgres",
@@ -281,7 +340,7 @@ async function startEphemeralPostgres(image, major, resourceName) {
281
340
  "postgres",
282
341
  "-q",
283
342
  ]);
284
- return { containerId, port, connString, restoreJobs: tuning.restoreJobs, teardown, forgetInterruptCleanup };
343
+ return { containerId, port, connString, offline: false, restoreJobs: tuning.restoreJobs, teardown, forgetInterruptCleanup };
285
344
  }
286
345
  catch {
287
346
  await new Promise((r) => setTimeout(r, 500));
@@ -295,10 +354,203 @@ async function startEphemeralPostgres(image, major, resourceName) {
295
354
  throw error;
296
355
  }
297
356
  }
357
+ // ── 断网跑 SQL(模拟注册用,2.11.1)────────────────────────────────
358
+ /** 沙箱容器当前接着的 Docker 网络 */
359
+ async function containerNetworks(containerId) {
360
+ const { stdout } = await execFileAsync("docker", ["inspect", "-f", "{{json .NetworkSettings.Networks}}", containerId], {
361
+ timeout: 15_000,
362
+ });
363
+ return Object.keys(JSON.parse(stdout.trim() || "null") ?? {});
364
+ }
365
+ /** 在容器里跑一条命令(docker exec);timeoutMs 或 signal 到了就杀掉本地的 docker exec 客户端 */
366
+ function containerExec(containerId, command, opts) {
367
+ return new Promise((resolve) => {
368
+ const proc = spawn("docker", [
369
+ "exec",
370
+ ...(opts.input !== undefined ? ["-i"] : []),
371
+ ...(opts.env ?? []).flatMap((kv) => ["-e", kv]),
372
+ containerId,
373
+ ...command,
374
+ ], { stdio: [opts.input !== undefined ? "pipe" : "ignore", "pipe", "ignore"] });
375
+ let stdout = "";
376
+ proc.stdout.on("data", (d) => {
377
+ // 只要我们自己 select 出来的那一行;封顶,不让输出无限长
378
+ if (stdout.length < 64 * 1024)
379
+ stdout += d.toString();
380
+ });
381
+ let killed = false;
382
+ const kill = () => {
383
+ killed = true;
384
+ proc.kill("SIGKILL");
385
+ };
386
+ const timer = setTimeout(kill, opts.timeoutMs);
387
+ if (opts.signal?.aborted)
388
+ kill();
389
+ opts.signal?.addEventListener("abort", kill, { once: true });
390
+ proc.on("error", () => { });
391
+ proc.on("close", (code) => {
392
+ clearTimeout(timer);
393
+ opts.signal?.removeEventListener("abort", kill);
394
+ resolve({ code, stdout, killed });
395
+ });
396
+ if (opts.input !== undefined) {
397
+ proc.stdin.on("error", () => { });
398
+ proc.stdin.end(opts.input);
399
+ }
400
+ });
401
+ }
402
+ /** 容器里用 psql 跑 SQL(默认走 unix socket,不经网络)。官方镜像对本地 socket 和 127.0.0.1 都是 trust */
403
+ const PSQL = ["psql", "-X", "-q", "-tA", "-v", "ON_ERROR_STOP=1", "-U", "postgres", "-d", "postgres"];
404
+ /** 模拟注册在容器里的几样痕迹,都带同一个随机标记:取消标记文件、psql 的 pid 文件、会话的 application_name */
405
+ function signupTraces(marker) {
406
+ if (!/^[0-9a-f]{16}$/.test(marker))
407
+ throw new Error("bad sign-up marker");
408
+ return {
409
+ cancelFile: `/tmp/backupdrill-signup-${marker}.cancel`,
410
+ pidFile: `/tmp/backupdrill-signup-${marker}.pid`,
411
+ appName: `backupdrill-signup-${marker}`,
412
+ };
413
+ }
414
+ /**
415
+ * 模拟注册本地那一侧(docker exec 客户端)最多等多久;导出供测试调短,产品里不改。
416
+ * launchPauseSeconds 只给测试用:在启动脚本"看过取消标记"和"exec psql"之间停一会儿,复现最坏的时序
417
+ */
418
+ export const OFFLINE_SIGNUP_LIMITS = { psqlMs: 6 * 60 * 1000, launchPauseSeconds: 0 };
419
+ /**
420
+ * 容器里启动模拟注册的脚本。和 stopSignup 的约定:**先占位、再看取消**。
421
+ * - 启动脚本先独占创建 pid 文件(set -C),写进自己的 pid,然后才看取消标记,有就退出;
422
+ * - stopSignup 先建取消标记,然后才看 pid 文件。
423
+ * 所以 stopSignup 没看到 pid 文件,启动脚本之后一定会看到取消标记而退出;看到了,就按 pid 杀掉它——
424
+ * 不管它还是 sh(停在 exec 之前)还是已经 exec 成了 psql,pid 都是同一个。
425
+ *
426
+ * psql 经 127.0.0.1 连(断网后 loopback 还在):走 unix socket 时 inet_client_addr() 是 NULL,
427
+ * 真实注册经 TCP 进来,要客户端地址的触发器会被误判成坏的。官方镜像 loopback 是 trust;
428
+ * 万一不是,用容器自己的 POSTGRES_PASSWORD
429
+ */
430
+ function signupLauncher(marker) {
431
+ const { cancelFile, pidFile } = signupTraces(marker);
432
+ const pause = Math.max(0, Math.floor(OFFLINE_SIGNUP_LIMITS.launchPauseSeconds));
433
+ return (`set -C; echo $$ > ${pidFile} || exit 99; [ -e ${cancelFile} ] && exit 99; ` +
434
+ (pause ? `sleep ${pause}; ` : "") +
435
+ `PGPASSWORD="$POSTGRES_PASSWORD" exec ${PSQL.join(" ")} -h 127.0.0.1`);
436
+ }
437
+ /**
438
+ * 停掉一次没有正常结束的模拟注册,并等到它在容器里确实没了,到 deadline(时间戳)为止。本地的 docker exec 客户端被杀掉
439
+ * (超时、叫停)时,容器里的那次启动照样在跑,甚至可能还没起来。按 signupLauncher 的约定:
440
+ * 1. 先建取消标记,再看 pid 文件:没有 pid 文件 = 它以后也不会启动;有 = 那个进程(sh 或 psql)还活着就杀掉;
441
+ * 2. 终止它的会话(按 application_name,或者语句里带着这次的随机标记——触发器能改 application_name)。
442
+ * 进程没了、会话也没了才算停下来。每条 docker 命令的时限也截在 deadline 之内,整体不会超过它
443
+ */
444
+ async function stopSignup(containerId, marker, deadline) {
445
+ const { cancelFile, pidFile, appName } = signupTraces(marker);
446
+ // 输出 "alive":还有进程(刚杀掉,或者 pid 文件刚建、还没写进 pid),下一轮再看
447
+ const killLauncher = `touch ${cancelFile}; if [ -e ${pidFile} ]; then p=$(cat ${pidFile}); ` +
448
+ `if [ -z "$p" ]; then echo alive; ` +
449
+ `else c=$(cat /proc/$p/comm 2>/dev/null); if [ "$c" = sh ] || [ "$c" = psql ]; then kill -9 "$p"; echo alive; fi; fi; fi; true`;
450
+ const sessions = `select count(pg_terminate_backend(pid)) from pg_stat_activity where pid <> pg_backend_pid() ` +
451
+ `and (application_name = '${appName}' or query like '%${marker}%')`;
452
+ const left = () => deadline - Date.now();
453
+ while (left() > 0) {
454
+ const killed = await containerExec(containerId, ["sh", "-c", killLauncher], { timeoutMs: Math.max(1, left()) });
455
+ if (killed.code !== 0 || left() <= 0)
456
+ return false;
457
+ const sessionsLeft = await containerExec(containerId, [...PSQL, "-c", sessions], { timeoutMs: Math.max(1, left()) });
458
+ if (sessionsLeft.code !== 0)
459
+ return false;
460
+ if (killed.stdout.trim() === "" && sessionsLeft.stdout.trim() === "0")
461
+ return true;
462
+ await new Promise((resolve) => setTimeout(resolve, Math.min(500, Math.max(0, left()))));
463
+ }
464
+ return false;
465
+ }
466
+ /** 停掉模拟注册最多等多久(整体,从开始停算起) */
467
+ const STOP_SIGNUP_MS = 15_000;
468
+ /**
469
+ * 模拟注册用的"断网跑 SQL"(见 auth-drill.ts OfflineSandbox)。
470
+ *
471
+ * 为什么是临时断网,而不是一开始就不给沙箱联网:CLI 和 pg_restore 都从主机经发布的端口连沙箱,
472
+ * --network none 和 --internal 网络都发布不了端口。所以恢复、校验照旧,只在最后的模拟注册之前把容器从所有
473
+ * 网络上摘下来(只剩 loopback),经 docker exec 里的 psql 连 127.0.0.1 跑(见 signupLauncher)。
474
+ *
475
+ * **断了就不再接回**:能确认的只有会话和那个 psql 都没了,确认不了触发器有没有留下别的东西(后台进程等),
476
+ * 一接回它们就又能连出去。所以模拟注册是这个沙箱上的最后一件事,跑完沙箱就销毁。--keep 要留下沙箱时
477
+ * 根本不跑模拟注册(见 drillDump),留下的沙箱和 2.11.0 一样连得上。
478
+ * 每一步之前都看一眼是否已被叫停:叫停后(报告可能已经出了)不再断开任何网络。摘不干净就不跑。
479
+ */
480
+ /** @internal 演练内部用;导出只为测试能直接对一个容器验证断网、叫停和超时收尾 */
481
+ export function offlineSandbox(pg) {
482
+ let running = null;
483
+ // 同一次注册的收尾只做一次:本地超时、叫停、演练那边的 stopOfflineSessions 谁先来谁启动,其余的等同一个结果
484
+ const stopping = new Map();
485
+ const stopOnce = (marker) => {
486
+ let p = stopping.get(marker);
487
+ if (!p)
488
+ stopping.set(marker, (p = stopSignup(pg.containerId, marker, Date.now() + STOP_SIGNUP_MS)));
489
+ return p;
490
+ };
491
+ return {
492
+ offline: () => pg.offline,
493
+ async stopOfflineSessions() {
494
+ if (running)
495
+ await stopOnce(running);
496
+ },
497
+ async runOffline(script, marker, signal) {
498
+ const { appName } = signupTraces(marker);
499
+ const stopped = () => {
500
+ if (signal?.aborted)
501
+ throw new Error("stopped");
502
+ };
503
+ stopped();
504
+ const networks = await containerNetworks(pg.containerId);
505
+ for (const network of networks) {
506
+ stopped();
507
+ await execFileAsync("docker", ["network", "disconnect", network, pg.containerId], { timeout: 30_000 });
508
+ // 只记确认过的状态:这一个网络已经摘掉了,之后不会再接回
509
+ pg.offline = true;
510
+ }
511
+ const left = await containerNetworks(pg.containerId);
512
+ if (left.length)
513
+ throw new Error(`the sandbox is still on ${left.join(", ")}`);
514
+ pg.offline = true;
515
+ stopped();
516
+ running = marker;
517
+ const result = await containerExec(pg.containerId, ["sh", "-c", signupLauncher(marker)], { input: script, timeoutMs: OFFLINE_SIGNUP_LIMITS.psqlMs, signal, env: [`PGAPPNAME=${appName}`] });
518
+ // 本地超时或被叫停:容器里的那次模拟注册可能还在跑,先确实停掉它,再交出结果(之后沙箱才会被销毁)
519
+ if (result.killed || signal?.aborted) {
520
+ // 超时收尾时演练可能正同时销毁沙箱:容器已经停了(或没了),里面的注册也就跟着没了,不必提示
521
+ const stillThere = () => execFileAsync("docker", ["inspect", "-f", "{{.State.Running}}", pg.containerId], { timeout: 10_000 }).then((r) => r.stdout.trim() === "true", () => false);
522
+ if (!(await stopOnce(marker)) && (await stillThere())) {
523
+ log.warn("Couldn't confirm the stopped test sign-up ended inside the drill sandbox; it stays off the network until it is removed.");
524
+ }
525
+ }
526
+ return { code: result.killed ? null : result.code, stdout: result.stdout };
527
+ },
528
+ };
529
+ }
530
+ /** --keep 留下的沙箱:和 2.11.0 一样给连接串(留沙箱时不跑模拟注册,它一直连得上),另给一条进容器的命令 */
531
+ function keptSandboxInfo(pg) {
532
+ return { containerId: pg.containerId, connString: pg.connString, inspect: `docker exec -it ${pg.containerId.slice(0, 12)} psql -U postgres` };
533
+ }
298
534
  // 只有这些特征说明恢复失败源于沙箱缺扩展(限定类型/schema 解析不到、扩展装不上)。
299
535
  // 真实 Supabase 项目的 manifest 几乎必然含沙箱装不上的托管扩展(pg_graphql 等),
300
536
  // 若不按特征过滤,任何硬失败(归档损坏、OOM…)都会被误归因到沙箱。
301
537
  const MISSING_EXTENSION_ERROR = /type "[^"]+" does not exist|schema "[^"]+" does not exist|extension "[^"]+" is not available/i;
538
+ // 沙箱小版本早于 2026-11 安全更新(CVE-2026-6460):不认识旧 pg_dump 从已更新的源库导出的列参数。
539
+ // 逐段看 pre-data 失败:主错误(段首 ERROR: 之后、Command was: 之前)整句就是这一条才算,
540
+ // 语句正文或 DETAIL 里出现这个词不算
541
+ const PG_ATTVER_REJECTED = /^pg_restore: error: could not execute query: ERROR:\s+unrecognized parameter "pg_attver"\s+Command was:/;
542
+ /** pre-data 失败里有没有"沙箱不认 pg_attver"这一条(导出给测试) */
543
+ export function sandboxRejectsAttver(preDataFailures) {
544
+ return preDataFailures.some((failure) => PG_ATTVER_REJECTED.test(failure));
545
+ }
546
+ /** pre-data 硬失败;sandboxTooOld = 至少一段失败的主错误是沙箱不认 pg_attver */
547
+ class PreDataRestoreError extends Error {
548
+ sandboxTooOld;
549
+ constructor(message, sandboxTooOld) {
550
+ super(message);
551
+ this.sandboxTooOld = sandboxTooOld;
552
+ }
553
+ }
302
554
  /** 兼容层:历史签名保留,分类逻辑的单一权威在统一引擎(restore-engine.ts)。 */
303
555
  export function classifyPostDataErrors(stderr) {
304
556
  const classified = classifyBlocks(stderr, SANDBOX_MANAGED_ERROR);
@@ -325,7 +577,7 @@ async function pgRestore(dumpPath, connString, dumpedSchemas, jobs, grants) {
325
577
  grants: { schemas: dumpedSchemas, recorded: grants },
326
578
  });
327
579
  if (result.preData.failures.length) {
328
- throw new Error(`pg_restore failed: ${result.preData.failures.join(" | ")}`);
580
+ throw new PreDataRestoreError(`pg_restore failed: ${result.preData.failures.join(" | ")}`, sandboxRejectsAttver(result.preData.failures));
329
581
  }
330
582
  return {
331
583
  supabaseSkipped: result.postData.expectedSkips,
@@ -620,7 +872,8 @@ export async function drillDump(dumpPath, manifest, snapshot, preChecks = [], op
620
872
  const sourceMajor = parseInt(manifest.database.serverVersion, 10);
621
873
  const toolMajor = await localPgRestoreMajor();
622
874
  const sandboxMajor = sandboxMajorFor(sourceMajor, toolMajor);
623
- const pg = await startEphemeralPostgres(sandboxImage(manifest, sandboxMajor), sandboxMajor, opts.supervision?.resourceName);
875
+ const image = sandboxImage(manifest, sandboxMajor);
876
+ const pg = await startEphemeralPostgres(image, sandboxMajor, opts.supervision?.resourceName);
624
877
  let pass = false; // 异常路径视为失败,供 finally 决定 --keep 是否保留沙箱
625
878
  try {
626
879
  if (sandboxMajor !== sourceMajor) {
@@ -669,6 +922,14 @@ export async function drillDump(dumpPath, manifest, snapshot, preChecks = [], op
669
922
  // 沙箱装不上扩展 + 错误特征命中"缺类型/schema/扩展" → 假设式归因到沙箱环境
670
923
  // (不对备份健康下断言);其余失败与扩展无关,必须原样抛出
671
924
  const message = error.message;
925
+ // 必须排在缺扩展归因前面:这类失败的连带错误(type "…" does not exist)也会命中
926
+ // MISSING_EXTENSION_ERROR,2026-11-24 的告警就被误指成了 supabase_vault
927
+ if (error instanceof PreDataRestoreError && error.sandboxTooOld) {
928
+ throw new Error(`restore failed: the drill sandbox (${image}) rejected "SET (pg_attver=…)". The sandbox needs the ` +
929
+ `November 2026 PostgreSQL security fix. Run "docker pull ${image}" and rerun the drill. Older pg_dump ` +
930
+ `versions can write this line when the source already has the fix. Use the latest minor version of ` +
931
+ `pg_dump for new backups. All errors: ${message}`);
932
+ }
672
933
  if (unavailable.length && MISSING_EXTENSION_ERROR.test(message)) {
673
934
  throw new Error(`restore failed; likely because the drill sandbox cannot install ` +
674
935
  `extension(s) ${unavailable.join(", ")}. Original error: ${message}`);
@@ -728,6 +989,10 @@ export async function drillDump(dumpPath, manifest, snapshot, preChecks = [], op
728
989
  // 托管 worker 在这一步前后换磁盘守卫的规则:Auth 阶段吃紧只叫停这一节,不判演练失败
729
990
  begin: opts.supervision ? () => opts.supervision.observe({ phase: "auth" }) : undefined,
730
991
  stop: opts.supervision?.authStop,
992
+ sandbox: offlineSandbox(pg),
993
+ // --keep 要留下这个沙箱时不跑模拟注册:断了网就不能再接回,留下的沙箱就连不上了(脚本靠 keptSandbox.connString)。
994
+ // 结论(pass)这时已经定了,只有真的会留沙箱(演练没通过)才跳过
995
+ skipSignup: opts.keepSandboxOnFailure && !pass ? "--keep leaves the sandbox connected so you can inspect it" : undefined,
731
996
  });
732
997
  if (authSection) {
733
998
  report.auth = authSection;
@@ -739,7 +1004,7 @@ export async function drillDump(dumpPath, manifest, snapshot, preChecks = [], op
739
1004
  }
740
1005
  if (opts.keepSandboxOnFailure && !pass) {
741
1006
  // 写进报告让 --keep 可被脚本消费(拿连接串排查),不只靠人眼看日志
742
- report.keptSandbox = { containerId: pg.containerId, connString: pg.connString };
1007
+ report.keptSandbox = keptSandboxInfo(pg);
743
1008
  }
744
1009
  return report;
745
1010
  }
@@ -1,4 +1,11 @@
1
1
  import type { Manifest } from "./manifest.js";
2
+ /**
3
+ * 原样写进 RECOVERY.md 的一段文字(例如 Auth 失败的原因,里面有从系统目录读来的约束名、索引名):放进代码段里,
4
+ * Markdown 不再解释里面的任何东西(链接、强调、HTML,GFM 也不会把裸网址自动变成链接)。按 CommonMark 的规则,
5
+ * 包住它的反引号要比里面最长的一串反引号多一个;两边各加一个空格,文字本身以反引号或空格开头结尾也不受影响。
6
+ * 控制字符换成可见的转义,名字里的换行不会让这一段断开
7
+ */
8
+ export declare function markdownCode(text: string): string;
2
9
  /** 生成手册所需的非秘密快照坐标。刻意不收连接串/密钥类型——签名即防线。 */
3
10
  export interface RecoveryDocContext {
4
11
  snapshot: string;
@@ -1,6 +1,18 @@
1
1
  import { recoveryGrantsSql } from "./grants.js";
2
2
  import { plainSchemaName, restorableAuthObjects } from "./auth-backup.js";
3
3
  import { authRestoreNotes, CLEAR_PENDING_AUTH_SQL } from "./auth-restore.js";
4
+ /**
5
+ * 原样写进 RECOVERY.md 的一段文字(例如 Auth 失败的原因,里面有从系统目录读来的约束名、索引名):放进代码段里,
6
+ * Markdown 不再解释里面的任何东西(链接、强调、HTML,GFM 也不会把裸网址自动变成链接)。按 CommonMark 的规则,
7
+ * 包住它的反引号要比里面最长的一串反引号多一个;两边各加一个空格,文字本身以反引号或空格开头结尾也不受影响。
8
+ * 控制字符换成可见的转义,名字里的换行不会让这一段断开
9
+ */
10
+ export function markdownCode(text) {
11
+ const visible = text.replace(/[\u0000-\u001f\u007f-\u009f\u2028\u2029]/g, (ch) => `\\u${ch.charCodeAt(0).toString(16).padStart(4, "0")}`);
12
+ const longestRun = Math.max(0, ...[...visible.matchAll(/`+/g)].map((m) => m[0].length));
13
+ const fence = "`".repeat(longestRun + 1);
14
+ return `${fence} ${visible} ${fence}`;
15
+ }
4
16
  function quoteSqlIdent(name) {
5
17
  return `"${name.replace(/"/g, '""')}"`;
6
18
  }
@@ -37,7 +49,7 @@ export function authRecoveryText(manifest, place) {
37
49
  (pg_dump custom format, ${mb(auth.dump.bytes)} MB, sha256 \`${auth.dump.sha256}\`) — ${auth.rows.users.toLocaleString("en-US")} users, ${auth.rows.identities.toLocaleString("en-US")} sign-in identities
38
50
  `
39
51
  : manifest.auth
40
- ? `- **Supabase Auth users**: not in this snapshot (${AUTH_NOT_INCLUDED_TEXT[manifest.auth.reason ?? ""] ?? manifest.auth.reason ?? "not captured"})
52
+ ? `- **Supabase Auth users**: not in this snapshot (${AUTH_NOT_INCLUDED_TEXT[manifest.auth.reason ?? ""] ?? markdownCode(manifest.auth.reason ?? "not captured")})
41
53
  `
42
54
  : "";
43
55
  // 空目标检查用的 schema 列表(SQL 字符串字面量,单引号按 SQL 规则加倍)
package/dist/restore.d.ts CHANGED
@@ -97,7 +97,7 @@ export declare function nonEmptyTargetMessage(schemas: string[], objectCount: nu
97
97
  * 900 张表能过、1200 张表报 out of shared memory(2026-10-23,PG 17)。分区多的库会撞上。
98
98
  * Supabase 只能用 CLI 调这个参数(会重启数据库),照官方文档的命令给出来。
99
99
  */
100
- export declare function restoreFailureAdvice(failure: string): string;
100
+ export declare function restoreFailureAdvice(failures: string[]): string;
101
101
  /**
102
102
  * 把一份快照恢复出来:数据库经统一引擎还原进目标(与演练同一条 pg_restore 路径与
103
103
  * 错误分类),恢复后跑同一套表级验证;Storage 提供目标凭据时回传+对账(P0-D),
package/dist/restore.js CHANGED
@@ -17,7 +17,7 @@ import { orphanedForeignKeysCheck } from "./orphaned-foreign-keys.js";
17
17
  import { grantsCheck } from "./grants.js";
18
18
  import { localPgRestoreMajor, restoreToolTargetBlocker } from "./pgbin.js";
19
19
  import { describeTarget, restoreRecordKey } from "./restore-record.js";
20
- import { AUTH_TABLE_KEYS, authRestoreFailureMessage, authRestoreNotes, targetIdentity, transactionOutcome, authRestorePreflight, largeObjectEntries, psqlProblem, readAuthArchive, restoreWithAuth, } from "./auth-restore.js";
20
+ import { primaryAuthRestoreError, AUTH_TABLE_KEYS, authRestoreFailureMessage, authRestoreNotes, targetIdentity, transactionOutcome, authRestorePreflight, largeObjectEntries, psqlProblem, readAuthArchive, restoreWithAuth, } from "./auth-restore.js";
21
21
  import { parsePgDumpMajor } from "./backup.js";
22
22
  import { log } from "./log.js";
23
23
  /** 归档可读性要求:pg_restore 必须 ≥ max(写入工具版本, 源服务端版本)——格式跟随写入工具。 */
@@ -412,8 +412,17 @@ async function dryRunPreflight(config, manifest, targetUrl, storageTarget, alsoR
412
412
  * 900 张表能过、1200 张表报 out of shared memory(2026-10-23,PG 17)。分区多的库会撞上。
413
413
  * Supabase 只能用 CLI 调这个参数(会重启数据库),照官方文档的命令给出来。
414
414
  */
415
- export function restoreFailureAdvice(failure) {
416
- if (!/max_locks_per_transaction/.test(failure))
415
+ export function restoreFailureAdvice(failures) {
416
+ // 2026-11 安全更新(CVE-2026-6460)后:更新前的 pg_dump 导出已更新的源库,会写出
417
+ // `SET (pg_attver=…)`;已更新的目标会忽略它,没更新的目标直接拒绝。
418
+ // 传进来的每一项都以服务端主错误开头(firstRestoreError / 去掉阶段前缀的 psql 错误),
419
+ // 只看开头:语句正文或 DETAIL 里出现这个词不算
420
+ if (failures.some((failure) => /^unrecognized parameter "pg_attver"(?:\s|$)/.test(failure))) {
421
+ return (' The target rejected "SET (pg_attver=…)" from the snapshot. Older pg_dump versions can write this ' +
422
+ "line when the source has the November 2026 PostgreSQL security fix. Update the target to the latest " +
423
+ "minor release for its current PostgreSQL major version and retry.");
424
+ }
425
+ if (!failures.some((failure) => /max_locks_per_transaction/.test(failure)))
417
426
  return "";
418
427
  return (" The target ran out of lock slots: a single-transaction restore holds a lock on every table, index " +
419
428
  "and sequence until it commits. Raise max_locks_per_transaction on the target and retry. On Supabase " +
@@ -827,7 +836,7 @@ export async function runRestore(config, opts) {
827
836
  await advance("done");
828
837
  if (run.transaction !== "committed") {
829
838
  // 结果由事务本身说了算(没写 COMMIT,或 pg_xact_status 的回答),不再数 schema 里的对象去推断
830
- throw new Error(authRestoreFailureMessage(run) + restoreFailureAdvice(run.failure ?? ""));
839
+ throw new Error(authRestoreFailureMessage(run) + restoreFailureAdvice(run.failure ? [primaryAuthRestoreError(run.failure)] : []));
831
840
  }
832
841
  const committed = run.transaction === "committed";
833
842
  const pass = committed ? run.afterCommit.pass : { expectedSkips: 0, failures: [run.failure] };
@@ -873,7 +882,7 @@ export async function runRestore(config, opts) {
873
882
  " Check the target before doing anything else; restore won't write into it again while those " +
874
883
  "objects are there."
875
884
  : await targetStateAfterFailure(targetUrl, manifest.database.schemas)) +
876
- restoreFailureAdvice(failures.join(" ")));
885
+ restoreFailureAdvice(failures));
877
886
  }
878
887
  result.restoredToDatabase = true;
879
888
  const orphaned = engine.orphanedForeignKeys ?? [];
package/package.json CHANGED
@@ -1,7 +1,7 @@
1
1
  {
2
2
  "name": "backupdrill",
3
- "version": "2.11.0",
4
- "description": "Open-source CLI to back up a Supabase project — Postgres database and Storage files — to your own S3/R2/B2 bucket, with a checksummed manifest.",
3
+ "version": "2.11.2",
4
+ "description": "Open-source CLI to back up a Supabase project to your own S3/R2/B2 bucket (the Postgres database, Auth users when your role can read them, and Storage files once you add the project's Storage S3 keys), then run a restore drill that proves the backup restores.",
5
5
  "type": "module",
6
6
  "bin": {
7
7
  "backupdrill": "dist/index.js"
@@ -50,6 +50,8 @@
50
50
  "cloudflare-r2",
51
51
  "backblaze-b2",
52
52
  "disaster-recovery",
53
+ "supabase-auth",
54
+ "backup-verification",
53
55
  "healthchecks",
54
56
  "pi-package"
55
57
  ],
package/plugin/README.md CHANGED
@@ -7,7 +7,7 @@ Back up a Supabase project to a bucket you own and prove the backup restores, by
7
7
  - `drill` restores a snapshot into a throwaway Postgres in Docker, checks that the tables and their data came back, and checksums a sample of the Storage files.
8
8
  - `restore` puts a snapshot into a new, empty Supabase project, after a dry run and only once you confirm the target.
9
9
 
10
- The agent runs every command as `npx -y backupdrill@2.10.1`, so the CLI version stays fixed.
10
+ The agent runs every command as `npx -y backupdrill@2.11.0`, so the CLI version stays fixed.
11
11
 
12
12
  ## What you need
13
13
 
@@ -7,7 +7,7 @@ description: Use when the user wants to back up a Supabase project to their own
7
7
 
8
8
  backupdrill is an open-source (MIT) command-line tool. `backup` dumps the project's Postgres database with `pg_dump`, copies Storage files too once their S3 keys are set, and writes everything to a bucket the user owns, with a checksummed `manifest.json` and a `RECOVERY.md` in every snapshot. `drill` restores a snapshot into a throwaway Postgres in Docker and checks that it came back. The CLI runs on the user's machine. It talks to their Supabase project, their bucket and the local Docker daemon, and sends nothing to BackupDrill.
9
9
 
10
- Always run it as `npx -y backupdrill@2.10.1 <command>`, so every run uses the same version. Every command and option is documented at [backupdrill.com/docs/cli](https://backupdrill.com/docs/cli); check there before using an option this skill doesn't mention.
10
+ Always run it as `npx -y backupdrill@2.11.0 <command>`, so every run uses the same version. Every command and option is documented at [backupdrill.com/docs/cli](https://backupdrill.com/docs/cli); check there before using an option this skill doesn't mention.
11
11
 
12
12
  If the user asks what Supabase already backs up on their plan, wants a plain `pg_dump` backup without the CLI, or wants to test a restore by hand, read [references/postgres-backup-basics.md](references/postgres-backup-basics.md).
13
13
 
@@ -71,7 +71,7 @@ Every backup reads the whole database, and every configured Storage file, out of
71
71
  ```sh
72
72
  ( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
73
73
  set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
74
- npx -y backupdrill@2.10.1 estimate --plan pro )
74
+ npx -y backupdrill@2.11.0 estimate --plan pro )
75
75
  ```
76
76
 
77
77
  Use `--plan free`, `pro` or `team` to match their Supabase plan, and read the projection back before suggesting a daily schedule. On a large database, suggest weekly.
@@ -82,7 +82,7 @@ Use `--plan free`, `pro` or `team` to match their Supabase plan, and read the pr
82
82
  report="$(mktemp "${TMPDIR:-/tmp}/backupdrill-backup.XXXXXX")" || exit 1; echo "stdout → $report"
83
83
  ( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
84
84
  set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
85
- npx -y backupdrill@2.10.1 backup ) > "$report"
85
+ npx -y backupdrill@2.11.0 backup ) > "$report"
86
86
  ```
87
87
 
88
88
  - The progress lines on stderr show where everything went (`Dumping → s3://…`, `Manifest written → s3://…`) and end with `Backup complete — N tables + M Storage files`. stdout goes to the file named on the first line, a new one each run that only the user can read: one line of JSON with the whole manifest, which lists every table and Storage file, so read only the fields you need from it.
@@ -95,7 +95,7 @@ report="$(mktemp "${TMPDIR:-/tmp}/backupdrill-backup.XXXXXX")" || exit 1; echo "
95
95
  ```sh
96
96
  ( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
97
97
  set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
98
- npx -y backupdrill@2.10.1 drill )
98
+ npx -y backupdrill@2.11.0 drill )
99
99
  ```
100
100
 
101
101
  - It reads the latest snapshot from the bucket, restores it into a throwaway Postgres container, runs its checks and removes the container. It doesn't connect to the Supabase project. The first run pulls a Postgres image from Docker Hub.
@@ -114,7 +114,7 @@ A restore writes data, so go step by step and let the user drive.
114
114
  ```sh
115
115
  ( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
116
116
  set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
117
- npx -y backupdrill@2.10.1 restore --database --target-supabase-url https://<target-ref>.supabase.co --dry-run )
117
+ npx -y backupdrill@2.11.0 restore --database --target-supabase-url https://<target-ref>.supabase.co --dry-run )
118
118
  ```
119
119
 
120
120
  Leave out `--target-supabase-url` when the snapshot is database only. To write Storage files to a local folder instead of the new project, use `--storage-dir ./recovered`.
@@ -99,7 +99,7 @@ jobs:
99
99
 
100
100
  - name: Run backupdrill
101
101
  # Pinned so every run uses the same CLI. Raise it on purpose when you upgrade.
102
- run: npx -y backupdrill@2.10.1 backup
102
+ run: npx -y backupdrill@2.11.0 backup
103
103
  env:
104
104
  # --- required ---
105
105
  BACKUPDRILL_DATABASE_URL: ${{ secrets.BACKUPDRILL_DATABASE_URL }}