backupdrill 2.11.1 → 2.12.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.
package/README.md CHANGED
@@ -133,6 +133,8 @@ export BACKUPDRILL_SUPABASE_STORAGE_SECRET_ACCESS_KEY="…"
133
133
 
134
134
  With those set, `backupdrill backup` also copies every Storage file into your bucket and records each file's checksum in the manifest. Omit them to back up the database only.
135
135
 
136
+ Since 2.12.0, if the Storage copy is incomplete, the snapshot still holds the database dump and any Auth archive, provided BackupDrill can save the manifest and recovery guide afterwards; `backup` then exits with code 3. Files deleted from your project between listing and copying go in `storage.vanished` and aren't counted as missing. A file is skipped if reading it stalls for two minutes, its full key in the backup location would be longer than 1,024 bytes, or the destination hasn't confirmed its upload 15 minutes after the read finished. The snapshot keeps the files that copied, and `storage.partial` counts the skipped ones by reason. If Storage listing, reading or writing fails outright, the manifest lists no Storage files and `storageFailure` records why. That includes a listing request getting no answer for two minutes, or a single upload request for 15 minutes. Files uploaded before the failure may still be in the backup bucket.
137
+
136
138
  ## Egress & cost — read this before scheduling daily backups
137
139
 
138
140
  A backup pulls data **out** of Supabase, which counts as **egress on your Supabase bill**. Verified rates (2026-07-10, [egress docs](https://supabase.com/docs/guides/platform/manage-your-usage/egress) + [pricing](https://supabase.com/pricing)):
@@ -185,6 +187,8 @@ If you also keep a written record of each drill for your team or an audit (which
185
187
 
186
188
  Backups record your installed Postgres extensions in the manifest, and the drill pre-installs them in the sandbox before restoring — including switching to a pgvector-enabled sandbox image when your database uses `vector` columns.
187
189
 
190
+ Every drill first pulls the sandbox image (`postgres:<major>-alpine`, or `pgvector/pgvector:pg<major>`) from Docker Hub, so an image you already have is updated to the latest published build of that tag. After the November 2026 PostgreSQL security fix, older versions of `pg_dump` can write `pg_attver` into a backup, and a sandbox without the fix rejects that option. If you already have the image and the update fails or takes more than 5 minutes, the drill uses your copy and prints a warning.
191
+
188
192
  The sandbox restore runs up to 4 parallel `pg_restore` jobs, sized from the CPUs and memory Docker reports, so a 2 vCPU / 8 GB machine gets 2. Table data and index builds run in parallel. Foreign keys, triggers and policies run on a single connection to keep their error messages separate, including errors about Supabase-managed objects such as `auth.users`. `backupdrill restore` into a real Supabase project stays on a single connection.
189
193
 
190
194
  For a snapshot with Auth users, the drill does more once its usual checks are done. In the same sandbox it restores the two Auth tables and compares their row counts with the backup. It adds the foreign keys into them that it otherwise skips, recreates the triggers on them that a restore would recreate (the rest are listed as manual steps), and simulates an email sign-up as `supabase_auth_admin`, the role Supabase Auth uses, then rolls it back. If a trigger fails on that test sign-up (an email sign-up with no user metadata), the report says so. The result is an `auth` section in the report. For now it doesn't change whether the drill passes.
@@ -217,6 +221,14 @@ backupdrill restore --database --target-supabase-url https://<ref>.supabase.co -
217
221
 
218
222
  Prefer files on disk instead? Skip the Storage target and pass `--storage-dir ./recovered`.
219
223
 
224
+ To restore a backup downloaded with BackupDrill's download script, pass `--from-dir` the folder that holds `backupdrill-download.json`. The other restore flags work as usual (`--database`, `--target-supabase-url`, `--dry-run`, `--confirm-target`); leave out `--bucket`, `--endpoint`, `--region` and `--prefix`, which `restore` refuses with `--from-dir`. Before writing to the target, `restore` checks the size and SHA-256 of the database dump and of any Auth archive and Storage files the manifest lists, and stops if one is missing or doesn't match; rerun the download script, then retry. With `--finish`, the folder needs `backupdrill-download.json`, the manifest and the database dump; the Auth archive and Storage files can be missing.
225
+
226
+ The restore works from private copies of those files, kept in your system temp folder (`TMPDIR` if set) and removed when it finishes. Without copy-on-write support, allow room there for the database dump, any Auth archive and the Storage files; a database restore also writes its own working copy of the dump and Auth archive.
227
+
228
+ ```bash
229
+ backupdrill restore --from-dir ./backupdrill-download --database --target-supabase-url https://<ref>.supabase.co --dry-run
230
+ ```
231
+
220
232
  `--dry-run` writes nothing to the target. Besides checking the target (not the source project, schemas empty, Postgres and `pg_restore` versions, extensions available), it downloads the dump to a temporary directory, checks its sha256 and looks for foreign keys that point outside the backup (see [Tables that reference auth.users](#tables-that-reference-authusers)). The real run repeats those checks before it writes anything; a foreign key into a table that one of the recorded extensions creates is checked again once the extensions are installed. The database restore then runs in a single transaction: if any statement fails, nothing from the snapshot stays on the target, and you can run it again on the same project once you've fixed the cause. (If the connection drops while it commits, the error says so and asks you to check the target first.) Right after that transaction commits, the grants for `anon`, `authenticated` and `service_role` are set in a transaction of their own (see [Grants for anon, authenticated and service_role](#grants-for-anon-authenticated-and-service_role)). Foreign keys between two tables in the backup are the exception to the single transaction: they're added after that, in one more. If rows in your data already break one of them (deleting with triggers switched off, for example under `session_replication_role = replica`, can leave rows like that), the key is added as `NOT VALID` instead of failing the restore. Those rows come back as they are, new writes are still checked, and the report names the key and, when it can count them, how many rows break it. Keys on or into partitioned tables, keys into an extension's tables, and every key in an archive whose foreign key statements BackupDrill can't fully read stay in the main transaction, so a broken one rolls the whole restore back. A key over a generated column is added in the second step but is never relaxed, because the restore recomputes those values; if it breaks, that step fails. Keys added as `NOT VALID` don't fail a drill: the drill passes and lists them in its report. If a step after the main transaction fails for any other reason, the tables and data are already on the target and the error says so. Extensions the run installed stay installed, since the next run needs them too, and the empty-target check doesn't count objects that belong to an extension (except an extension's configuration tables, whose rows a dump can carry). One transaction holds a lock on every table, index and sequence until it commits, so a very large schema can run out of lock slots: on Supabase's smallest compute size, about a thousand tables (partitions count as tables). The restore then stops with nothing written and tells you how to raise `max_locks_per_transaction`.
221
233
 
222
234
  Snapshots taken with 2.10.0 or later usually hold the Auth users as well. For those, `restore` writes the Auth users, the database and the triggers on the Auth tables that it can recreate in **one** transaction. Triggers it can't recreate, and policies on the Auth tables, are listed as manual steps. A foreign key like `profiles.id → auth.users` then finds its users. If anything fails before the commit, the target is left as it was. The grants and some foreign keys come after the commit, as with any restore (see above). A few things come with that:
@@ -500,6 +512,8 @@ covered by this promise; they may change in any release. Use the CLI if you need
500
512
  - [backupdrill on StackShare](https://stackshare.io/backupdrill).
501
513
  - A [ZAP success story](https://www.zaproxy.org/success/backupdrill/) describes the weekly ZAP baseline scan we run against our website.
502
514
  - The agent skill in [`plugin/`](https://github.com/backupdrill/cli/tree/main/plugin) is also published on the [Tessl registry](https://tessl.io/registry/backupdrill/supabase-backup) and [LobeHub](https://lobehub.com/skills/backupdrill-cli-supabase-backup).
515
+ - The [backupdrill/supabase-backup orb](https://circleci.com/developer/orbs/orb/backupdrill/supabase-backup) runs backups and restore drills in CircleCI pipelines.
516
+ - [Our HackerNoon author page](https://hackernoon.com/u/superlede), with an article on five ways Supabase backups fail and how to test restores for each.
503
517
 
504
518
  ## License
505
519
 
@@ -44,6 +44,11 @@ export declare function psqlProblem(): Promise<string | null>;
44
44
  * 返回 "more"。不是它就不交给 psql:没有受限模式,归档内容里的元命令会被执行
45
45
  */
46
46
  export declare function restrictHeader(text: string): "ok" | "missing" | "more";
47
+ /**
48
+ * 失败说明 "<阶段> failed: <主错误>" 里的主错误(按已知阶段前缀去掉);别的形状的失败原样返回。
49
+ * 给 restoreFailureAdvice 用:它只看主错误开头,语句正文里碰巧出现的字不能触发建议
50
+ */
51
+ export declare function primaryAuthRestoreError(failure: string): string;
47
52
  /**
48
53
  * 等 stdin 能再写(drain)或者 psql 已经退出。监听用完就摘掉:大库恢复要等几十万次,
49
54
  * 挂在一个直到最后才结束的 Promise 上的回调会一直攒着
@@ -201,6 +201,17 @@ const STAGE_TEXT = {
201
201
  commit: "committing",
202
202
  committed: "committing",
203
203
  };
204
+ /**
205
+ * 失败说明 "<阶段> failed: <主错误>" 里的主错误(按已知阶段前缀去掉);别的形状的失败原样返回。
206
+ * 给 restoreFailureAdvice 用:它只看主错误开头,语句正文里碰巧出现的字不能触发建议
207
+ */
208
+ export function primaryAuthRestoreError(failure) {
209
+ for (const text of [...Object.values(STAGE_TEXT), "connecting to the target"]) {
210
+ if (failure.startsWith(`${text} failed: `))
211
+ return failure.slice(text.length + " failed: ".length);
212
+ }
213
+ return failure;
214
+ }
204
215
  const STAGE_MARK = "backupdrill-stage:";
205
216
  const XID_MARK = "backupdrill-xid:";
206
217
  /**
package/dist/backup.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { BackupConfig } from "./config.js";
2
2
  import { type SnapshotStore } from "./snapshot-store.js";
3
3
  import type { Manifest } from "./manifest.js";
4
+ import { type StorageSyncOptions } from "./storage.js";
4
5
  import { parsePgDumpMajor } from "./pgbin.js";
5
6
  export { parsePgDumpMajor };
6
7
  /** 主 dump 的 pg_dump 参数。snapshotId 省略时与 2.10.0 之前逐字一致(Auth 关闭时就是这样) */
@@ -23,4 +24,6 @@ export declare const AUTH_TIMEOUTS: {
23
24
  export declare function runBackup(config: BackupConfig, opts?: {
24
25
  /** 快照写到哪;省略 = config.storage 指的 S3 兼容桶 */
25
26
  store?: SnapshotStore;
27
+ /** Storage 文件复制的时间预算、停滞阈值、写请求计数回报(见 StorageSyncOptions);省略 = 不设预算 */
28
+ storage?: StorageSyncOptions;
26
29
  }): Promise<Manifest>;
package/dist/backup.js CHANGED
@@ -6,7 +6,7 @@ import { s3SnapshotStore } from "./snapshot-store.js";
6
6
  import { MANIFEST_SCHEMA_VERSION } from "./manifest.js";
7
7
  import { AUTH_DUMP_MAX_BYTES, authDumpArgs, exportSharedSnapshot, inspectAuth, authInSchemas, manualAuthObjects, redactValues, } from "./auth-backup.js";
8
8
  import { scrubPendingAuthTokens } from "./auth-archive.js";
9
- import { syncStorage } from "./storage.js";
9
+ import { syncStorage, StorageSyncError } from "./storage.js";
10
10
  import { inspectBucketAttrs } from "./storage-catalog.js";
11
11
  import { projectRefOf, refFromStorageEndpoint, assertNoHostOverride } from "./restore-engine.js";
12
12
  import { log } from "./log.js";
@@ -535,6 +535,11 @@ function logAuthOutcome(auth, schemas) {
535
535
  log.warn(`Auth users backup failed: ${why}. The database backup itself is complete.`);
536
536
  }
537
537
  }
538
+ const STORAGE_REASON_TEXT = {
539
+ time_budget: "ran out of time",
540
+ read_stalled: "stopped sending data",
541
+ key_too_long: "name too long for the backup location",
542
+ };
538
543
  export async function runBackup(config, opts = {}) {
539
544
  // 源身份先于一切传输(评审第 12 轮):①连接串不许带 ?host=/user= 覆盖——否则
540
545
  // 快照记的 ref 与实际读取对象脱节,恢复端的同源保护随之失真;②库与 Storage
@@ -601,35 +606,58 @@ export async function runBackup(config, opts = {}) {
601
606
  if (auth)
602
607
  logAuthOutcome(auth, config.schemas);
603
608
  const grants = grantsHeldThroughout(grantsBeforeDump, await readGrants(config.databaseUrl, config.schemas));
604
- // Storage 文件同步(源配置存在才做;否则只备数据库)
609
+ // Storage 文件同步(源配置存在才做;否则只备数据库)。2.12.0 起 Storage 失败不拖累数据库:
610
+ // 列不出来、读不了、写不进目标时这份快照照常完成,manifest 记 storageFailure,storage 为 null
605
611
  let storageResult = null;
612
+ let storageFailure;
606
613
  if (config.supabaseStorage && storageFiles) {
607
614
  log.step("Syncing Storage files…");
608
- const synced = await syncStorage(config.supabaseStorage, {
609
- client: storageFiles.s3,
610
- bucket: storageFiles.bucket,
611
- base: storageFiles.base, // syncStorage 内部会加 /storage/<bucket>/<key>
612
- });
613
- // v2 bucket 属性采集,通道 = 已有的只读库连接(per-file 元数据已随 GetObject
614
- // 响应在 syncStorage 内原子捕获)。失败只降级不报错:storage schema 读不到
615
- // (如收紧的 backup_reader 角色)时,manifest 缺 buckets 字段,恢复端把缺失
616
- // 如实标 not captured(PRD §5.1.3)。
617
- let bucketAttrs;
615
+ let synced = null;
618
616
  try {
619
- bucketAttrs = await inspectBucketAttrs(config.databaseUrl, synced.buckets);
617
+ synced = await syncStorage(config.supabaseStorage, {
618
+ client: storageFiles.s3,
619
+ bucket: storageFiles.bucket,
620
+ base: storageFiles.base, // syncStorage 内部会加 /storage/<bucket>/<key>
621
+ }, opts.storage);
620
622
  }
621
623
  catch (error) {
622
- log.warn(`Bucket attributes not captured (${error.message}); ` +
623
- `this manifest will record them as absent — restore will say so instead of guessing.`);
624
+ if (!(error instanceof StorageSyncError))
625
+ throw error;
626
+ storageFailure = { reason: error.message };
627
+ log.warn(`Storage files were not backed up this time: ${error.message}. The database backup itself is complete.`);
628
+ }
629
+ if (synced) {
630
+ // v2 bucket 属性采集,通道 = 已有的只读库连接(per-file 元数据已随 GetObject
631
+ // 响应在 syncStorage 内原子捕获)。失败只降级不报错:storage schema 读不到
632
+ // (如收紧的 backup_reader 角色)时,manifest 缺 buckets 字段,恢复端把缺失
633
+ // 如实标 not captured(PRD §5.1.3)。
634
+ let bucketAttrs;
635
+ try {
636
+ bucketAttrs = await inspectBucketAttrs(config.databaseUrl, synced.buckets);
637
+ }
638
+ catch (error) {
639
+ log.warn(`Bucket attributes not captured (${error.message}); ` +
640
+ `this manifest will record them as absent — restore will say so instead of guessing.`);
641
+ }
642
+ storageResult = {
643
+ ...(bucketAttrs ? { buckets: bucketAttrs } : {}),
644
+ fileCount: synced.fileCount,
645
+ totalBytes: synced.totalBytes,
646
+ files: synced.files,
647
+ ...(synced.vanished.length ? { vanished: synced.vanished } : {}),
648
+ ...(synced.partial ? { partial: synced.partial } : {}),
649
+ };
650
+ log.ok(`Storage synced (${synced.fileCount} files, ` +
651
+ `${(synced.totalBytes / 1024 / 1024).toFixed(1)} MB)`);
652
+ if (synced.vanished.length) {
653
+ log.step(` ${synced.vanished.length} file(s) were deleted in the project while we copied; nothing to back up for those.`);
654
+ }
655
+ if (synced.partial) {
656
+ const why = synced.partial.notCopied.map((n) => `${n.count} ${STORAGE_REASON_TEXT[n.reason]}`).join(", ");
657
+ log.warn(`Storage copy is partial: ${synced.partial.copied} of ${synced.partial.total} files (not copied: ${why}). ` +
658
+ `The database backup itself is complete.`);
659
+ }
624
660
  }
625
- storageResult = {
626
- ...(bucketAttrs ? { buckets: bucketAttrs } : {}),
627
- fileCount: synced.fileCount,
628
- totalBytes: synced.totalBytes,
629
- files: synced.files,
630
- };
631
- log.ok(`Storage synced (${synced.fileCount} files, ` +
632
- `${(synced.totalBytes / 1024 / 1024).toFixed(1)} MB)`);
633
661
  }
634
662
  const manifest = {
635
663
  schemaVersion: MANIFEST_SCHEMA_VERSION,
@@ -652,6 +680,8 @@ export async function runBackup(config, opts = {}) {
652
680
  // 关闭时不写这个字段:manifest 与之前逐字节一致
653
681
  ...(auth ? { auth } : {}),
654
682
  storage: storageResult,
683
+ // 只在失败时写:没失败的 manifest 与之前逐字节一致
684
+ ...(storageFailure ? { storageFailure } : {}),
655
685
  };
656
686
  // RECOVERY.md(PRD §5.9.2.1)先于 manifest 落桶:manifest 是快照的"完成标记"
657
687
  // (演练/恢复按它找快照)——先写手册再写标记,"快照完成"就蕴含"手册在场";
@@ -0,0 +1,55 @@
1
+ import { type Manifest } from "./manifest.js";
2
+ import type { SnapshotStore } from "./snapshot-store.js";
3
+ /**
4
+ * 下载到本地的快照(托管存储的下载脚本产出,2.12.0 起)。restore --from-dir 读它,其余恢复流程与从桶恢复一样。
5
+ *
6
+ * 目录布局:索引文件 + 一律用编号命名的文件(files/000001 …)。本地文件名从不取自原始对象键:
7
+ * 没有路径穿越、大小写冲突、a 与 a/b 冲突、shell 引号问题。原始键只在索引里。
8
+ */
9
+ export declare const DOWNLOAD_INDEX_FILE = "backupdrill-download.json";
10
+ export interface DownloadIndex {
11
+ format: "backupdrill-download";
12
+ version: 1;
13
+ /** 要恢复的快照名(快照目录名,UTC 时间戳) */
14
+ snapshot: string;
15
+ /**
16
+ * key 相对于项目根目录:"<快照名>/manifest.json"、"<快照名>/dump.pgcustom"、
17
+ * "<快照名>/storage/<bucket>/<key>";增量链的工件按它们在桶里的相对路径。
18
+ * sha256 由下载脚本续传时用;恢复只认 manifest 里的校验和。
19
+ */
20
+ files: {
21
+ path: string;
22
+ key: string;
23
+ bytes: number;
24
+ sha256?: string;
25
+ }[];
26
+ }
27
+ export declare function parseDownloadIndex(json: string): DownloadIndex;
28
+ /** 一份已核对、已固定下来的本地快照 */
29
+ export interface PreparedDownload {
30
+ snapshot: string;
31
+ manifest: Manifest;
32
+ /** 核对过的文件数(数据库归档、Auth 归档、每个 Storage 文件) */
33
+ files: number;
34
+ /** 只读这份固定下来的文件;restore 用它,不再回头读下载目录 */
35
+ store: SnapshotStore;
36
+ /** 删掉暂存目录;恢复结束后一定要调 */
37
+ cleanup(): Promise<void>;
38
+ }
39
+ /**
40
+ * 把下载目录里要用的文件固定下来再核对:每个文件复制到一个只有本进程能读写的暂存目录(文件系统支持时是
41
+ * 写时复制的克隆,不占双份空间),核对的是暂存的那一份,恢复也只读暂存的那一份,manifest 用核对时读到的
42
+ * 原文。之后下载目录里的文件不管被换掉还是被就地改写,都碰不到这一份。暂存目录建在系统临时目录
43
+ * (TMPDIR)里:那里的父目录别人改不了我们的条目,下载目录的父目录则未必;需要的空间是数据库归档 +
44
+ * Storage 文件的大小(支持克隆的文件系统上几乎不占)。
45
+ *
46
+ * 核对:manifest 里登记的数据库归档、Auth 归档、每个 Storage 文件都必须在、大小和 sha256 都对。
47
+ * 任何一个不对就不开始(托管 PRD §5.7)。下载目录本身、files/ 和每个文件都不许是符号链接。
48
+ */
49
+ export declare function prepareDownloadedSnapshot(dir: string, opts?: {
50
+ /**
51
+ * "database" = 只固定、核对 manifest 和数据库归档(restore --finish 用:收尾只碰已经提交的数据库,
52
+ * 和 Storage / Auth 文件无关,它们缺了坏了不该挡住收尾)
53
+ */
54
+ scope?: "all" | "database";
55
+ }): Promise<PreparedDownload>;
@@ -0,0 +1,208 @@
1
+ import { createHash } from "node:crypto";
2
+ import { createReadStream } from "node:fs";
3
+ import { constants as fsConstants } from "node:fs";
4
+ import { chmod, copyFile, lstat, mkdtemp, readFile, realpath, rm } from "node:fs/promises";
5
+ import { tmpdir } from "node:os";
6
+ import { basename, join, posix } from "node:path";
7
+ import { parseManifest } from "./manifest.js";
8
+ /**
9
+ * 下载到本地的快照(托管存储的下载脚本产出,2.12.0 起)。restore --from-dir 读它,其余恢复流程与从桶恢复一样。
10
+ *
11
+ * 目录布局:索引文件 + 一律用编号命名的文件(files/000001 …)。本地文件名从不取自原始对象键:
12
+ * 没有路径穿越、大小写冲突、a 与 a/b 冲突、shell 引号问题。原始键只在索引里。
13
+ */
14
+ export const DOWNLOAD_INDEX_FILE = "backupdrill-download.json";
15
+ const LOCAL_FILE = /^files\/[0-9]{1,9}$/;
16
+ function unsafeKey(key) {
17
+ return (!key ||
18
+ key.startsWith("/") ||
19
+ key.includes("\\") ||
20
+ key.includes("\0") ||
21
+ key.split("/").some((seg) => seg === "" || seg === "." || seg === ".."));
22
+ }
23
+ function badIndex(what) {
24
+ throw new Error(`${DOWNLOAD_INDEX_FILE} is malformed (${what}) — download the backup again.`);
25
+ }
26
+ export function parseDownloadIndex(json) {
27
+ let raw;
28
+ try {
29
+ raw = JSON.parse(json);
30
+ }
31
+ catch (error) {
32
+ throw new Error(`${DOWNLOAD_INDEX_FILE} is not valid JSON: ${error.message}`);
33
+ }
34
+ if (typeof raw !== "object" || raw === null || raw.format !== "backupdrill-download")
35
+ badIndex("format");
36
+ if (raw.version !== 1) {
37
+ throw new Error(`${DOWNLOAD_INDEX_FILE} has version ${String(raw.version)}; this CLI reads version 1. Upgrade the CLI (npm i -g backupdrill).`);
38
+ }
39
+ if (typeof raw.snapshot !== "string" || unsafeKey(raw.snapshot) || raw.snapshot.includes("/"))
40
+ badIndex("snapshot");
41
+ if (!Array.isArray(raw.files))
42
+ badIndex("files");
43
+ const keys = new Set();
44
+ const paths = new Set();
45
+ for (const f of raw.files) {
46
+ if (typeof f?.path !== "string" || !LOCAL_FILE.test(f.path))
47
+ badIndex("files[].path");
48
+ if (typeof f.key !== "string" || unsafeKey(f.key))
49
+ badIndex("files[].key");
50
+ if (typeof f.bytes !== "number" || !Number.isSafeInteger(f.bytes) || f.bytes < 0)
51
+ badIndex("files[].bytes");
52
+ if (f.sha256 !== undefined && (typeof f.sha256 !== "string" || !/^[0-9a-f]{64}$/.test(f.sha256))) {
53
+ badIndex("files[].sha256");
54
+ }
55
+ if (keys.has(f.key) || paths.has(f.path))
56
+ badIndex("duplicate entry");
57
+ keys.add(f.key);
58
+ paths.add(f.path);
59
+ }
60
+ return raw;
61
+ }
62
+ async function hashFile(path) {
63
+ const hash = createHash("sha256");
64
+ let bytes = 0;
65
+ for await (const chunk of createReadStream(path)) {
66
+ hash.update(chunk);
67
+ bytes += chunk.length;
68
+ }
69
+ return { bytes, sha256: hash.digest("hex") };
70
+ }
71
+ /** 快照目录里一个文件的键(相对项目根):dump、auth.dump 按 manifest 里的文件名 */
72
+ function snapshotKey(snapshot, file) {
73
+ return posix.join(snapshot, file);
74
+ }
75
+ async function assertRealDirectory(path, what) {
76
+ const st = await lstat(path).catch(() => null);
77
+ if (!st || st.isSymbolicLink() || !st.isDirectory()) {
78
+ throw new Error(`${what} is not a real folder — download the backup again`);
79
+ }
80
+ }
81
+ /**
82
+ * 把下载目录里要用的文件固定下来再核对:每个文件复制到一个只有本进程能读写的暂存目录(文件系统支持时是
83
+ * 写时复制的克隆,不占双份空间),核对的是暂存的那一份,恢复也只读暂存的那一份,manifest 用核对时读到的
84
+ * 原文。之后下载目录里的文件不管被换掉还是被就地改写,都碰不到这一份。暂存目录建在系统临时目录
85
+ * (TMPDIR)里:那里的父目录别人改不了我们的条目,下载目录的父目录则未必;需要的空间是数据库归档 +
86
+ * Storage 文件的大小(支持克隆的文件系统上几乎不占)。
87
+ *
88
+ * 核对:manifest 里登记的数据库归档、Auth 归档、每个 Storage 文件都必须在、大小和 sha256 都对。
89
+ * 任何一个不对就不开始(托管 PRD §5.7)。下载目录本身、files/ 和每个文件都不许是符号链接。
90
+ */
91
+ export async function prepareDownloadedSnapshot(dir, opts = {}) {
92
+ const root = await realpath(dir).catch(() => {
93
+ throw new Error(`${dir} does not exist — point --from-dir at the folder the download script created`);
94
+ });
95
+ const indexPath = join(root, DOWNLOAD_INDEX_FILE);
96
+ const indexStat = await lstat(indexPath).catch(() => null);
97
+ if (!indexStat || indexStat.isSymbolicLink() || !indexStat.isFile()) {
98
+ throw new Error(`${dir} has no ${DOWNLOAD_INDEX_FILE} — point --from-dir at the folder the download script created`);
99
+ }
100
+ await assertRealDirectory(join(root, "files"), `${dir}/files`);
101
+ const index = parseDownloadIndex(await readFile(indexPath, "utf8"));
102
+ const byKey = new Map(index.files.map((f) => [f.key, f]));
103
+ const snapshot = index.snapshot;
104
+ const staging = await mkdtemp(join(tmpdir(), "backupdrill-restore-"));
105
+ const cleanup = () => rm(staging, { recursive: true, force: true });
106
+ // 核对没过时的报错:逐个列问题,补救办法只在末尾说一次
107
+ const stopped = (problems) => new Error(`restore stopped while checking the downloaded backup; nothing was written to the target:\n ` +
108
+ problems.slice(0, 5).join("\n ") +
109
+ (problems.length > 5 ? `\n …and more` : "") +
110
+ `\nRerun the download script if files are missing or don't match. Fix any disk or permission errors shown above before retrying.`);
111
+ try {
112
+ await chmod(staging, 0o700);
113
+ const staged = new Map();
114
+ const stage = async (key) => {
115
+ const already = staged.get(key);
116
+ if (already)
117
+ return already;
118
+ const entry = byKey.get(key);
119
+ if (!entry)
120
+ throw new Error(`Missing ${key} (not listed in ${DOWNLOAD_INDEX_FILE}).`);
121
+ const src = join(root, entry.path);
122
+ const st = await lstat(src).catch(() => null);
123
+ if (!st)
124
+ throw new Error(`Missing ${key} (${entry.path}).`);
125
+ if (st.isSymbolicLink() || !st.isFile())
126
+ throw new Error(`${entry.path} is not a regular file.`);
127
+ const dest = join(staging, String(staged.size + 1));
128
+ // 独立的一份(克隆或复制),不和原件共用存储:原件之后被就地改写也不影响它
129
+ await copyFile(src, dest, fsConstants.COPYFILE_FICLONE);
130
+ staged.set(key, dest);
131
+ return dest;
132
+ };
133
+ const manifestText = await readFile(await stage(snapshotKey(snapshot, "manifest.json")).catch((error) => {
134
+ throw stopped([error.message]);
135
+ }), "utf8");
136
+ const manifest = parseManifest(manifestText);
137
+ const expected = [
138
+ { key: snapshotKey(snapshot, basename(manifest.dump.key)), bytes: manifest.dump.bytes, sha256: manifest.dump.sha256 },
139
+ ];
140
+ const everything = (opts.scope ?? "all") === "all";
141
+ if (everything && manifest.auth?.status === "included" && manifest.auth.dump) {
142
+ const a = manifest.auth.dump;
143
+ expected.push({ key: snapshotKey(snapshot, basename(a.key)), bytes: a.bytes, sha256: a.sha256 });
144
+ }
145
+ for (const f of everything ? (manifest.storage?.files ?? []) : []) {
146
+ expected.push({ key: snapshotKey(snapshot, `storage/${f.bucket}/${f.key}`), bytes: f.bytes, sha256: f.sha256 });
147
+ }
148
+ const problems = [];
149
+ for (const e of expected) {
150
+ try {
151
+ const got = await hashFile(await stage(e.key));
152
+ if (got.bytes !== e.bytes || got.sha256 !== e.sha256)
153
+ problems.push(`${e.key} has the wrong size or SHA-256.`);
154
+ }
155
+ catch (error) {
156
+ problems.push(error.message);
157
+ }
158
+ if (problems.length >= 20)
159
+ break;
160
+ }
161
+ if (problems.length)
162
+ throw stopped(problems);
163
+ const pathOf = (key) => {
164
+ const p = staged.get(key);
165
+ if (!p)
166
+ throw new Error(`${key} is not part of this verified download`);
167
+ return p;
168
+ };
169
+ const storageSource = {
170
+ async open(bucket, key, range) {
171
+ const src = pathOf(snapshotKey(snapshot, `storage/${bucket}/${key}`));
172
+ return createReadStream(src, range ? { start: range.start, end: range.end } : {});
173
+ },
174
+ };
175
+ const copyOut = async (key, dest) => {
176
+ await copyFile(pathOf(key), dest);
177
+ return hashFile(dest);
178
+ };
179
+ const reader = {
180
+ name: snapshot,
181
+ // 返回核对时读到、解析过的同一份 manifest 原文
182
+ readManifest: async () => manifestText,
183
+ downloadDump: (m, dest) => copyOut(snapshotKey(snapshot, basename(m.dump.key)), dest),
184
+ downloadAuthDump: async (m, dest) => {
185
+ if (m.auth?.status !== "included" || !m.auth.dump)
186
+ throw new Error("this snapshot has no Auth archive");
187
+ return copyOut(snapshotKey(snapshot, basename(m.auth.dump.key)), dest);
188
+ },
189
+ storageFiles: () => null,
190
+ storageSource: (m) => (m.storage ? storageSource : null),
191
+ };
192
+ const store = {
193
+ async createSnapshot() {
194
+ throw new Error("a downloaded backup folder is read-only");
195
+ },
196
+ async openSnapshot(name) {
197
+ if (name && name !== snapshot)
198
+ throw new Error(`this download holds snapshot ${snapshot}, not ${name}`);
199
+ return reader;
200
+ },
201
+ };
202
+ return { snapshot, manifest, files: expected.length, store, cleanup };
203
+ }
204
+ catch (error) {
205
+ await cleanup();
206
+ throw error;
207
+ }
208
+ }
package/dist/drill.d.ts CHANGED
@@ -101,6 +101,8 @@ interface PostDataResult {
101
101
  /** 授权重建结果;失败时不存在,原因在 failures 里 */
102
102
  grants?: GrantRestore;
103
103
  }
104
+ /** pre-data 失败里有没有"沙箱不认 pg_attver"这一条(导出给测试) */
105
+ export declare function sandboxRejectsAttver(preDataFailures: string[]): boolean;
104
106
  /** 兼容层:历史签名保留,分类逻辑的单一权威在统一引擎(restore-engine.ts)。 */
105
107
  export declare function classifyPostDataErrors(stderr: string): PostDataResult;
106
108
  /** 兼容层:见 restore-engine.ts finalizePass(非零退出且零错误块 = 通用失败)。 */