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.
- package/README.md +49 -5
- package/dist/auth-backup.d.ts +110 -0
- package/dist/auth-backup.js +383 -0
- package/dist/auth-drill.d.ts +69 -0
- package/dist/auth-drill.js +469 -0
- package/dist/auth-restore.d.ts +120 -0
- package/dist/auth-restore.js +633 -0
- package/dist/backup.d.ts +17 -0
- package/dist/backup.js +372 -19
- package/dist/config.d.ts +9 -0
- package/dist/config.js +17 -0
- package/dist/drill.d.ts +24 -3
- package/dist/drill.js +43 -3
- package/dist/dump-sql.d.ts +6 -0
- package/dist/dump-sql.js +31 -0
- package/dist/external-refs.d.ts +6 -1
- package/dist/external-refs.js +5 -0
- package/dist/index.js +67 -3
- package/dist/lib.d.ts +9 -3
- package/dist/lib.js +4 -2
- package/dist/manifest.d.ts +63 -0
- package/dist/manifest.js +78 -0
- package/dist/orphaned-foreign-keys.d.ts +13 -0
- package/dist/orphaned-foreign-keys.js +75 -25
- package/dist/pgbin.d.ts +7 -0
- package/dist/pgbin.js +24 -0
- package/dist/ping.js +1 -0
- package/dist/recovery-doc.d.ts +25 -0
- package/dist/recovery-doc.js +232 -53
- package/dist/restore-engine.d.ts +73 -1
- package/dist/restore-engine.js +155 -77
- package/dist/restore-record.d.ts +47 -0
- package/dist/restore-record.js +57 -0
- package/dist/restore.d.ts +64 -0
- package/dist/restore.js +348 -34
- package/dist/snapshot-store.d.ts +13 -0
- package/dist/snapshot-store.js +25 -0
- package/dist/snapshots.d.ts +2 -0
- package/dist/snapshots.js +10 -3
- package/package.json +1 -1
- package/plugin/README.md +1 -1
- package/plugin/skills/supabase-backup/SKILL.md +9 -7
- package/plugin/skills/supabase-backup/assets/scheduled-backup.yml +6 -1
- package/plugin/skills/supabase-backup/references/postgres-backup-basics.md +94 -0
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);超限如实记录
|
|
@@ -171,6 +172,10 @@ async function startEphemeralPostgres(image, major, resourceName) {
|
|
|
171
172
|
await ensureImage(image);
|
|
172
173
|
// 名字先定好:Ctrl+C 可能落在 docker run 还没返回 ID 的时候,按名字才删得掉
|
|
173
174
|
const name = resourceName ?? `backupdrill-drill-${randomBytes(6).toString("hex")}`;
|
|
175
|
+
// 沙箱里是恢复出来的生产数据。端口只绑 127.0.0.1,但同机的其他系统账号照样连得上,
|
|
176
|
+
// 固定密码等于没设:每个沙箱一个随机密码。只写 "-e POSTGRES_PASSWORD" 不带值,
|
|
177
|
+
// docker 从它自己的环境变量取值,密码就不进 argv(ps 看得到 argv)
|
|
178
|
+
const password = randomBytes(16).toString("hex");
|
|
174
179
|
throwIfInterrupted();
|
|
175
180
|
const started = execFileAsync("docker", [
|
|
176
181
|
"run",
|
|
@@ -180,7 +185,7 @@ async function startEphemeralPostgres(image, major, resourceName) {
|
|
|
180
185
|
name,
|
|
181
186
|
...(resourceName ? ["--mount", `type=volume,source=${resourceName},target=${dataVolumeTarget}`] : []),
|
|
182
187
|
"-e",
|
|
183
|
-
"POSTGRES_PASSWORD
|
|
188
|
+
"POSTGRES_PASSWORD",
|
|
184
189
|
"-e",
|
|
185
190
|
"POSTGRES_DB=postgres",
|
|
186
191
|
"-p",
|
|
@@ -189,7 +194,7 @@ async function startEphemeralPostgres(image, major, resourceName) {
|
|
|
189
194
|
image,
|
|
190
195
|
"postgres",
|
|
191
196
|
...tuning.settings.flatMap((kv) => ["-c", kv]),
|
|
192
|
-
]);
|
|
197
|
+
], { env: { ...process.env, POSTGRES_PASSWORD: password } });
|
|
193
198
|
// 删容器只有一份:正常收尾(drillDump 的 finally)和中断收尾(interrupt.ts)等的是同一个 promise。
|
|
194
199
|
// 两边各发一次 docker rm 会撞上 "removal already in progress",后到的那个报删除失败,
|
|
195
200
|
// 进程又在真正删完之前就退出了(信号测试抓到的竞争)。
|
|
@@ -258,7 +263,7 @@ async function startEphemeralPostgres(image, major, resourceName) {
|
|
|
258
263
|
]);
|
|
259
264
|
// 形如 "127.0.0.1:54321"
|
|
260
265
|
const port = portOut.stdout.trim().split(":").pop().trim();
|
|
261
|
-
const connString = `postgresql://postgres
|
|
266
|
+
const connString = `postgresql://postgres:${password}@127.0.0.1:${port}/postgres`;
|
|
262
267
|
// 等就绪(容器内 pg_isready),最多 ~30s。
|
|
263
268
|
// 必须 -h 127.0.0.1 强制走 TCP:官方镜像 initdb 阶段先起一个只听 unix socket 的临时
|
|
264
269
|
// 服务跑初始化,默认(socket)检查在该阶段就通过,pg_restore 随后连 TCP 正撞上
|
|
@@ -649,6 +654,21 @@ export async function drillDump(dumpPath, manifest, snapshot, preChecks = [], op
|
|
|
649
654
|
};
|
|
650
655
|
if (orphaned.length)
|
|
651
656
|
report.orphanedForeignKeys = orphaned;
|
|
657
|
+
// Auth 附加校验:结论(pass)上面已经定了,这里只往报告里加一节。它在同一个沙箱里补外键、
|
|
658
|
+
// 建触发器、模拟注册——放在所有正式检查之后,不影响它们;自己出错也只记在这一节里
|
|
659
|
+
const authSection = await authDrillSection(pg.connString, manifest, dumpPath, opts.authDump, opts.stopAuthDownload, {
|
|
660
|
+
// 托管 worker 在这一步前后换磁盘守卫的规则:Auth 阶段吃紧只叫停这一节,不判演练失败
|
|
661
|
+
begin: opts.supervision ? () => opts.supervision.observe({ phase: "auth" }) : undefined,
|
|
662
|
+
stop: opts.supervision?.authStop,
|
|
663
|
+
});
|
|
664
|
+
if (authSection) {
|
|
665
|
+
report.auth = authSection;
|
|
666
|
+
const line = `Auth users: ${authSection.summary}`;
|
|
667
|
+
if (authSection.status === "verified")
|
|
668
|
+
log.ok(line);
|
|
669
|
+
else
|
|
670
|
+
log.warn(line);
|
|
671
|
+
}
|
|
652
672
|
if (opts.keepSandboxOnFailure && !pass) {
|
|
653
673
|
// 写进报告让 --keep 可被脚本消费(拿连接串排查),不只靠人眼看日志
|
|
654
674
|
report.keptSandbox = { containerId: pg.containerId, connString: pg.connString };
|
|
@@ -690,6 +710,7 @@ export async function runDrill(config, opts = {}) {
|
|
|
690
710
|
const workdir = opts.supervision?.workdir ?? await mkdtemp(join(tmpdir(), "backupdrill-"));
|
|
691
711
|
const dumpPath = join(workdir, "dump.pgcustom");
|
|
692
712
|
// 下载的 dump 在这里;托管模式的目录归 supervisor 管
|
|
713
|
+
const authDownloadStop = new AbortController();
|
|
693
714
|
const forgetWorkdir = opts.supervision
|
|
694
715
|
? () => { }
|
|
695
716
|
: onInterrupt(() => rm(workdir, { recursive: true, force: true }).catch(() => { }));
|
|
@@ -731,13 +752,32 @@ export async function runDrill(config, opts = {}) {
|
|
|
731
752
|
detail: "the manifest lists Storage files, but this snapshot location cannot hold them",
|
|
732
753
|
});
|
|
733
754
|
}
|
|
755
|
+
// 快照带 Auth 用户:在后台把 auth.dump 取下来给附加校验用,和正式演练同时进行、不让它等。
|
|
756
|
+
// 取不到只记进报告的 Auth 一节
|
|
757
|
+
let authDump;
|
|
758
|
+
if (manifest.auth?.status === "included" && (opts.authCheck ?? !opts.supervision)) {
|
|
759
|
+
const authPath = join(workdir, "auth.dump");
|
|
760
|
+
const download = reader.downloadAuthDump;
|
|
761
|
+
const stopAuthDownload = authDownloadStop;
|
|
762
|
+
// 下载出错的原文不进报告(里面可能有凭据、对象键之类),只给固定的说法;
|
|
763
|
+
// 同步抛出的错误也在这个 Promise 里接住,绝不冒到演练本身
|
|
764
|
+
authDump = download
|
|
765
|
+
? Promise.resolve()
|
|
766
|
+
.then(() => download.call(reader, manifest, authPath, { signal: stopAuthDownload.signal }))
|
|
767
|
+
.then(() => ({ path: authPath }), () => ({ error: "the Auth archive couldn't be downloaded" }))
|
|
768
|
+
: Promise.resolve({ error: "this snapshot location can't read the Auth archive" });
|
|
769
|
+
}
|
|
734
770
|
return await drillDump(dumpPath, manifest, snapshot, preChecks, {
|
|
735
771
|
appCheckCommand: opts.appCheckCommand,
|
|
736
772
|
keepSandboxOnFailure: opts.keepSandboxOnFailure,
|
|
737
773
|
supervision: opts.supervision,
|
|
774
|
+
authDump,
|
|
775
|
+
stopAuthDownload: () => authDownloadStop.abort(),
|
|
738
776
|
});
|
|
739
777
|
}
|
|
740
778
|
finally {
|
|
779
|
+
// 演练怎么结束都一样:还在下的 auth.dump 立刻停掉,不留着连接把进程拖住
|
|
780
|
+
authDownloadStop.abort();
|
|
741
781
|
if (!opts.supervision)
|
|
742
782
|
await rm(workdir, { recursive: true, force: true }).catch(() => { });
|
|
743
783
|
forgetWorkdir();
|
package/dist/dump-sql.d.ts
CHANGED
|
@@ -45,6 +45,12 @@ export declare function parsePartitionAttachments(sql: string): Array<{
|
|
|
45
45
|
* 带引号的列名可以跨行,所以按位置往下读,不按行切。
|
|
46
46
|
*/
|
|
47
47
|
export declare function parseTableColumns(sql: string): Map<string, Map<string, string>>;
|
|
48
|
+
/**
|
|
49
|
+
* 建表语句里的生成列(`GENERATED ALWAYS AS (…)`,STORED 和 PG 18 的 VIRTUAL 都算),按表 → 列名集合。
|
|
50
|
+
* pg_dump 不导出生成列的数据,恢复时由目标自己算:数据段的列 = 建表语句的列减去这些。
|
|
51
|
+
* 和 parseTableColumns 同样按位置读列,只是每列再看一眼这一行剩下的部分
|
|
52
|
+
*/
|
|
53
|
+
export declare function parseGeneratedColumns(sql: string): Map<string, Set<string>>;
|
|
48
54
|
/** 一个 COPY 头最长读这么多字符;超过就当作读不了,免得坏归档把内存吃满。 */
|
|
49
55
|
export declare const MAX_COPY_HEADER = 100000;
|
|
50
56
|
/**
|
package/dist/dump-sql.js
CHANGED
|
@@ -89,6 +89,37 @@ export function parseTableColumns(sql) {
|
|
|
89
89
|
}
|
|
90
90
|
return tables;
|
|
91
91
|
}
|
|
92
|
+
/**
|
|
93
|
+
* 建表语句里的生成列(`GENERATED ALWAYS AS (…)`,STORED 和 PG 18 的 VIRTUAL 都算),按表 → 列名集合。
|
|
94
|
+
* pg_dump 不导出生成列的数据,恢复时由目标自己算:数据段的列 = 建表语句的列减去这些。
|
|
95
|
+
* 和 parseTableColumns 同样按位置读列,只是每列再看一眼这一行剩下的部分
|
|
96
|
+
*/
|
|
97
|
+
export function parseGeneratedColumns(sql) {
|
|
98
|
+
const tables = new Map();
|
|
99
|
+
const header = new RegExp(String.raw `^CREATE (?:UNLOGGED )?TABLE ${QUALIFIED} \(\n`, "gm");
|
|
100
|
+
for (const match of sql.matchAll(header)) {
|
|
101
|
+
const generated = new Set();
|
|
102
|
+
tables.set(`${unquoteIdent(match[1])}\u0000${unquoteIdent(match[2])}`, generated);
|
|
103
|
+
let at = match.index + match[0].length;
|
|
104
|
+
const column = new RegExp(String.raw ` {4}(${IDENT}) (.+?)(?= COLLATE | DEFAULT | NOT NULL| GENERATED |,?\n)`, "y");
|
|
105
|
+
while (at < sql.length && !sql.startsWith(")", at)) {
|
|
106
|
+
if (sql.startsWith(" CONSTRAINT ", at)) {
|
|
107
|
+
at = sql.indexOf("\n", at) + 1 || sql.length;
|
|
108
|
+
continue;
|
|
109
|
+
}
|
|
110
|
+
column.lastIndex = at;
|
|
111
|
+
const found = column.exec(sql);
|
|
112
|
+
if (!found)
|
|
113
|
+
break;
|
|
114
|
+
const lineEnd = sql.indexOf("\n", column.lastIndex);
|
|
115
|
+
const rest = sql.slice(column.lastIndex, lineEnd < 0 ? sql.length : lineEnd);
|
|
116
|
+
if (/ GENERATED ALWAYS AS \(/.test(rest))
|
|
117
|
+
generated.add(unquoteIdent(found[1]));
|
|
118
|
+
at = lineEnd + 1 || sql.length;
|
|
119
|
+
}
|
|
120
|
+
}
|
|
121
|
+
return tables;
|
|
122
|
+
}
|
|
92
123
|
/** 一个 COPY 头最长读这么多字符;超过就当作读不了,免得坏归档把内存吃满。 */
|
|
93
124
|
export const MAX_COPY_HEADER = 100_000;
|
|
94
125
|
/**
|
package/dist/external-refs.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type pg from "pg";
|
|
2
|
-
import { type ForeignKeyDef } from "./dump-sql.js";
|
|
2
|
+
import { type ForeignKeyDef, type QualifiedName } from "./dump-sql.js";
|
|
3
3
|
export interface CheckedForeignKey {
|
|
4
4
|
fk: ForeignKeyDef;
|
|
5
5
|
/** 引用列全非空的行数(MATCH SIMPLE:有一列为空就不校验) */
|
|
@@ -36,5 +36,10 @@ export declare function checkExternalReferences(opts: {
|
|
|
36
36
|
* 每条查询包在一个保存点里、查完就回滚到保存点,检查本身留不下任何东西。
|
|
37
37
|
*/
|
|
38
38
|
inTransaction?: pg.Client;
|
|
39
|
+
/**
|
|
40
|
+
* 同一次恢复里会整表写进去的备份之外的表(带 Auth 的恢复:auth.users、auth.identities)。指向它们的外键
|
|
41
|
+
* 不算"指向备份之外":数据和引用方一起写进去,提交后按备份内的外键加,源库的孤儿行建成 NOT VALID
|
|
42
|
+
*/
|
|
43
|
+
restoredTables?: QualifiedName[];
|
|
39
44
|
}): Promise<ExternalReferenceCheck>;
|
|
40
45
|
export declare function describe(fk: ForeignKeyDef): string;
|
package/dist/external-refs.js
CHANGED
|
@@ -55,6 +55,9 @@ export async function checkExternalReferences(opts) {
|
|
|
55
55
|
result.unchecked.push(`${fkEntries.length - foreignKeys.length} foreign key definition(s) in the dump are in a form this check can't read`);
|
|
56
56
|
}
|
|
57
57
|
const dumped = new Set(opts.dumpedSchemas);
|
|
58
|
+
// 指向同一次恢复里一起写进去的表(restoredTables)的外键:结构照查(被引用列在不在、类型对不对、有没有唯一键,
|
|
59
|
+
// 目标上缺了这些,提交之后加外键必然失败),只是不查行——那些行和引用方一起写进去
|
|
60
|
+
const restoredAlongside = new Set((opts.restoredTables ?? []).map(keyOf));
|
|
58
61
|
const external = foreignKeys.filter((fk) => !dumped.has(fk.references.schema) && fk.validatesRows);
|
|
59
62
|
if (!external.length)
|
|
60
63
|
return result;
|
|
@@ -104,6 +107,8 @@ export async function checkExternalReferences(opts) {
|
|
|
104
107
|
}
|
|
105
108
|
continue;
|
|
106
109
|
}
|
|
110
|
+
if (restoredAlongside.has(keyOf(fk.references)))
|
|
111
|
+
continue;
|
|
107
112
|
const checked = { fk, rows: 0, missingRows: 0 };
|
|
108
113
|
result.checked.push(checked);
|
|
109
114
|
scans.push({ checked, comparisons: lookup.comparisons, only: lookup.only, leaves: new Set(leavesOf(fk.table).map(keyOf)), seen: new Set(), batch: new Map() });
|
package/dist/index.js
CHANGED
|
@@ -7,7 +7,8 @@ import { runEstimate } from "./estimate.js";
|
|
|
7
7
|
import { runDrill } from "./drill.js";
|
|
8
8
|
import { createInterface } from "node:readline/promises";
|
|
9
9
|
import { Writable } from "node:stream";
|
|
10
|
-
import { runRestore, NO_SOURCE_DATABASE } from "./restore.js";
|
|
10
|
+
import { runRestore, NO_SOURCE_DATABASE, restoreStatus, finishRestore } from "./restore.js";
|
|
11
|
+
import { fileRestoreRecords } from "./restore-record.js";
|
|
11
12
|
import { recordDrillOutcome } from "./drill-record.js";
|
|
12
13
|
import { DEFAULT_EXPORTER_PORT, startExporter } from "./exporter.js";
|
|
13
14
|
import { exitCleanlyOnSignals, interrupted } from "./interrupt.js";
|
|
@@ -63,6 +64,11 @@ program
|
|
|
63
64
|
.option("--endpoint <url>", "S3-compatible endpoint (required for R2/B2; omit for AWS S3)")
|
|
64
65
|
.option("--region <region>", "bucket region (default: auto)")
|
|
65
66
|
.option("--prefix <prefix>", "key prefix inside the bucket (default: backupdrill)")
|
|
67
|
+
// 先定义 --auth 再定义 --no-auth:两个都不传时值是 undefined(= 默认行为),而不是 true
|
|
68
|
+
.option("--auth", "require the Supabase Auth users (auth.users + auth.identities) in the backup, or BACKUPDRILL_AUTH=on; " +
|
|
69
|
+
"if they can't be included the database backup still completes and the command exits with code 3. " +
|
|
70
|
+
"By default they're included when possible; BACKUPDRILL_AUTH or the config file can change that")
|
|
71
|
+
.option("--no-auth", "don't back up the Supabase Auth users (emails, password hashes, sign-in methods), or BACKUPDRILL_AUTH=off")
|
|
66
72
|
.option(PING_FLAG, PING_HELP)
|
|
67
73
|
.action(async (opts) => {
|
|
68
74
|
const ping = createPinger(await resolvePingUrl({ flag: opts.pingUrl, configPath: opts.config }));
|
|
@@ -75,6 +81,7 @@ program
|
|
|
75
81
|
databaseUrl: opts.databaseUrl,
|
|
76
82
|
projectName: opts.projectName,
|
|
77
83
|
schemas: opts.schema,
|
|
84
|
+
auth: opts.auth,
|
|
78
85
|
storage: {
|
|
79
86
|
bucket: opts.bucket,
|
|
80
87
|
endpoint: opts.endpoint,
|
|
@@ -89,9 +96,23 @@ program
|
|
|
89
96
|
: " (database only)";
|
|
90
97
|
log.ok(`Backup complete — ${manifest.database.tableCount} tables` +
|
|
91
98
|
`${storageNote}.`);
|
|
99
|
+
// 只有显式要求 Auth(--auth / BACKUPDRILL_AUTH=on)而它没备上,才让这次运行报失败:
|
|
100
|
+
// 数据库备份照样完成;退出码 3 与"整个备份失败"的 1 区分开。默认情况下做不了只打警告,
|
|
101
|
+
// 升级到这个版本的定时任务不会因此变红
|
|
102
|
+
// (显式要求时 planAuth 把所有"做不了"都记成 failed;只有 schemas 已含 auth 记 skipped——那时数据就在主 dump 里)
|
|
103
|
+
const authRequiredButMissing = config.auth === "on" && manifest.auth?.status === "failed";
|
|
92
104
|
// stdout 输出机器可读结果,便于在 CI / GitHub Action 里消费
|
|
93
|
-
process.stdout.write(JSON.stringify(
|
|
94
|
-
|
|
105
|
+
process.stdout.write(JSON.stringify(authRequiredButMissing
|
|
106
|
+
? { ok: false, database: { ok: true }, auth: manifest.auth, manifest }
|
|
107
|
+
: { ok: true, manifest }) + "\n");
|
|
108
|
+
if (authRequiredButMissing) {
|
|
109
|
+
process.exitCode = 3;
|
|
110
|
+
await ping.fail(`${backupSummary(manifest)}. Auth users were required but not backed up: ` +
|
|
111
|
+
`${manifest.auth?.reason ?? "unknown reason"}`, sensitiveValuesOf(config, opts.databaseUrl));
|
|
112
|
+
}
|
|
113
|
+
else {
|
|
114
|
+
await ping.success(backupSummary(manifest));
|
|
115
|
+
}
|
|
95
116
|
}
|
|
96
117
|
catch (error) {
|
|
97
118
|
const message = error.message;
|
|
@@ -203,6 +224,10 @@ program
|
|
|
203
224
|
"including foreign keys that point outside the backup)")
|
|
204
225
|
.option("--acknowledge-unverified-source", "proceed although the source identity cannot be verified (legacy snapshot without config) — " +
|
|
205
226
|
"same-source protection is inert; double-check the target first")
|
|
227
|
+
.option("--status", "read-only: for a restore with Auth users into this target, say whether it committed and what's left to do")
|
|
228
|
+
.option("--finish", "for a restore with Auth users that committed, do the steps after the commit that didn't finish (grants, foreign keys); safe to run again")
|
|
229
|
+
.option("--skip-auth", "don't restore the snapshot's Auth users; restore the database the way 2.9 did (for example when you " +
|
|
230
|
+
"copied the users into the target yourself)")
|
|
206
231
|
.option("--storage-dir <path>", "local directory to write Storage files to (when not uploading)")
|
|
207
232
|
.option("--snapshot <timestamp>", "which snapshot to restore (default: latest)")
|
|
208
233
|
.option("--bucket <name>", "bucket the backups live in")
|
|
@@ -212,6 +237,30 @@ program
|
|
|
212
237
|
.option("--project-name <name>", "project name used in the object key")
|
|
213
238
|
.action(async (opts) => {
|
|
214
239
|
try {
|
|
240
|
+
// restore --status / --finish:只针对带 Auth 的恢复,按这台机器上的恢复记录查结果、接着做。
|
|
241
|
+
// --status 只读、只要目标连接串,放在读配置之前:不需要桶的凭据
|
|
242
|
+
if (opts.status || opts.finish) {
|
|
243
|
+
if (opts.status && opts.finish)
|
|
244
|
+
throw new Error("use --status or --finish, not both");
|
|
245
|
+
if (opts.finish && opts.dryRun) {
|
|
246
|
+
throw new Error("--finish writes to the target; for a read-only look use --status instead of --dry-run");
|
|
247
|
+
}
|
|
248
|
+
}
|
|
249
|
+
let statusTarget;
|
|
250
|
+
if (opts.status || opts.finish) {
|
|
251
|
+
statusTarget =
|
|
252
|
+
process.env.BACKUPDRILL_TARGET_DATABASE_URL?.trim() ||
|
|
253
|
+
(await promptSecret("Target database connection string (BACKUPDRILL_TARGET_DATABASE_URL)"));
|
|
254
|
+
}
|
|
255
|
+
if (opts.status) {
|
|
256
|
+
const status = await restoreStatus({ targetDatabaseUrl: statusTarget, restoreRecords: fileRestoreRecords() });
|
|
257
|
+
console.log(JSON.stringify(status));
|
|
258
|
+
const finished = status.transaction === "committed" && status.phase === "done";
|
|
259
|
+
(finished ? log.ok : log.warn)(status.recorded
|
|
260
|
+
? `${status.target}: snapshot ${status.snapshot}, transaction ${status.xid} ${status.transaction} — ${status.next}`
|
|
261
|
+
: `${status.target}: ${status.next}`);
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
215
264
|
// 源库连接串不再无条件屏蔽:配置/环境里有真实源时,runRestore 的同源阻断门
|
|
216
265
|
// 要拿它比对;纯 flag 驱动(无任何源配置)才退回占位符
|
|
217
266
|
const overrides = {
|
|
@@ -235,6 +284,18 @@ program
|
|
|
235
284
|
overrides: { ...overrides, databaseUrl: NO_SOURCE_DATABASE },
|
|
236
285
|
});
|
|
237
286
|
}
|
|
287
|
+
if (opts.finish) {
|
|
288
|
+
const finished = await finishRestore(config, {
|
|
289
|
+
targetDatabaseUrl: statusTarget,
|
|
290
|
+
confirmTarget: opts.confirmTarget,
|
|
291
|
+
restoreRecords: fileRestoreRecords(),
|
|
292
|
+
snapshot: opts.snapshot,
|
|
293
|
+
});
|
|
294
|
+
console.log(JSON.stringify(finished));
|
|
295
|
+
if ((finished.databaseChecks ?? []).some((c) => !c.pass))
|
|
296
|
+
process.exitCode = 1;
|
|
297
|
+
return;
|
|
298
|
+
}
|
|
238
299
|
// 凭据形态(决策 D6,2.0 起):env 或隐藏式交互输入,绝不经 argv。
|
|
239
300
|
// --database 只表达意图,秘密自身不上命令行
|
|
240
301
|
// 秘密只随各自的意图旗标读取(评审第 9/10 轮):环境变量残留不能把 storage-only
|
|
@@ -261,6 +322,9 @@ program
|
|
|
261
322
|
acknowledgeUnverifiedSource: opts.acknowledgeUnverifiedSource,
|
|
262
323
|
storageDir: opts.storageDir,
|
|
263
324
|
snapshot: opts.snapshot,
|
|
325
|
+
skipAuth: opts.skipAuth,
|
|
326
|
+
// 带 Auth 的恢复把事务号和进度记在本机,供 --status / --finish 用
|
|
327
|
+
restoreRecords: fileRestoreRecords(),
|
|
264
328
|
});
|
|
265
329
|
// stdout = 机器可读通道(人读日志全在 stderr):完整结构化结果供脚本/报告消费
|
|
266
330
|
console.log(JSON.stringify(result));
|
package/dist/lib.d.ts
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
export { runBackup } from "./backup.js";
|
|
2
2
|
export { SUPABASE_ROOT_CA, pgConnectOptions, PG_CLIENT_OPTIONS, normalizeConnectionTarget } from "./supabase-ca.js";
|
|
3
3
|
export { runDrill, drillDump } from "./drill.js";
|
|
4
|
-
export { runRestore } from "./restore.js";
|
|
4
|
+
export { runRestore, restoreStatus, finishRestore } from "./restore.js";
|
|
5
|
+
export { fileRestoreRecords, restoreRecordKey } from "./restore-record.js";
|
|
6
|
+
export type { RestoreRecord, RestoreRecordStore, RestorePhase } from "./restore-record.js";
|
|
5
7
|
export { recoveryGrantsSql } from "./grants.js";
|
|
8
|
+
export { authRecoveryText } from "./recovery-doc.js";
|
|
9
|
+
export type { AuthRecoveryText, RecoveryDocPlace } from "./recovery-doc.js";
|
|
6
10
|
export { projectRefOf, assertNoHostOverride, libpqChildEnv } from "./restore-engine.js";
|
|
7
11
|
export { sameDatabaseTarget } from "./restore.js";
|
|
8
12
|
export { runEstimate, project } from "./estimate.js";
|
|
@@ -11,9 +15,11 @@ export { targetClient, resolveSnapshot, getObjectText, downloadToFile, hashObjec
|
|
|
11
15
|
export { s3SnapshotStore } from "./snapshot-store.js";
|
|
12
16
|
export type { SnapshotStore, SnapshotWriter, SnapshotReader, DumpUpload, StorageFilesLocation, } from "./snapshot-store.js";
|
|
13
17
|
export type { BackupConfig, LoadedBackupConfig, StorageConfig, SupabaseStorageConfig, } from "./config.js";
|
|
14
|
-
export type { BucketAttrs, ExtensionInfo, Manifest, StorageFile, TableStat } from "./manifest.js";
|
|
18
|
+
export type { AuthPolicyInfo, AuthSection, AuthTriggerInfo, BucketAttrs, ExtensionInfo, Manifest, StorageFile, TableStat, } from "./manifest.js";
|
|
19
|
+
export type { AuthMode } from "./auth-backup.js";
|
|
15
20
|
export type { GrantedObject, GrantRestore } from "./grants.js";
|
|
16
21
|
export type { DrillReport, DrillCheck, DrillSupervision, DrillPhase } from "./drill.js";
|
|
22
|
+
export type { AuthDrillReport } from "./auth-drill.js";
|
|
17
23
|
export type { OrphanedForeignKey } from "./orphaned-foreign-keys.js";
|
|
18
|
-
export type { RestoreResult } from "./restore.js";
|
|
24
|
+
export type { RestoreResult, RestoreAuthResult, RestoreStatus } from "./restore.js";
|
|
19
25
|
export type { EgressPricing, EgressProjection } from "./estimate.js";
|
package/dist/lib.js
CHANGED
|
@@ -5,9 +5,11 @@ export { runBackup } from "./backup.js";
|
|
|
5
5
|
// 搭配使用,URL 里的 sslmode=disable 又会把它覆盖掉,等于把这次修掉的绕过再放回去。
|
|
6
6
|
export { SUPABASE_ROOT_CA, pgConnectOptions, PG_CLIENT_OPTIONS, normalizeConnectionTarget } from "./supabase-ca.js";
|
|
7
7
|
export { runDrill, drillDump } from "./drill.js";
|
|
8
|
-
export { runRestore } from "./restore.js";
|
|
9
|
-
|
|
8
|
+
export { runRestore, restoreStatus, finishRestore } from "./restore.js";
|
|
9
|
+
export { fileRestoreRecords, restoreRecordKey } from "./restore-record.js";
|
|
10
|
+
// RECOVERY.md 的授权那一步和 Auth 用户那几段:worker 的 Drive 版手册和这里的 S3 版用同一份
|
|
10
11
|
export { recoveryGrantsSql } from "./grants.js";
|
|
12
|
+
export { authRecoveryText } from "./recovery-doc.js";
|
|
11
13
|
// 身份判定三件套对外导出:托管 worker 用它们与 app 侧 shared 的副本做同规则回归(交叉审查)
|
|
12
14
|
export { projectRefOf, assertNoHostOverride, libpqChildEnv } from "./restore-engine.js";
|
|
13
15
|
export { sameDatabaseTarget } from "./restore.js";
|
package/dist/manifest.d.ts
CHANGED
|
@@ -53,6 +53,7 @@ export interface ExtensionInfo {
|
|
|
53
53
|
* 验证升级字段(本期不生成)。全部为**可加字段**——v2 读取端兼容 v1 快照。
|
|
54
54
|
* - (仍是 2)2.9.0 加 database.grants:可加字段,旧读取端忽略它、照旧恢复,不升版本,
|
|
55
55
|
* 免得还没升级的 CLI 和 worker 拒读新快照。
|
|
56
|
+
* - (仍是 2)2.10.0 加 auth:同样是可加字段。旧读取端忽略它和 auth.dump,演练和恢复与之前完全一样。
|
|
56
57
|
*/
|
|
57
58
|
export declare const MANIFEST_SCHEMA_VERSION = 2;
|
|
58
59
|
export interface Manifest {
|
|
@@ -78,6 +79,7 @@ export interface Manifest {
|
|
|
78
79
|
bytes: number;
|
|
79
80
|
sha256: string;
|
|
80
81
|
};
|
|
82
|
+
auth?: AuthSection;
|
|
81
83
|
storage: null | {
|
|
82
84
|
buckets?: BucketAttrs[];
|
|
83
85
|
fileCount: number;
|
|
@@ -85,6 +87,67 @@ export interface Manifest {
|
|
|
85
87
|
files: StorageFile[];
|
|
86
88
|
};
|
|
87
89
|
}
|
|
90
|
+
/**
|
|
91
|
+
* Auth 用户备份的结果。只有 included 的快照带 dump 和统计;其余状态说明为什么没备上。
|
|
92
|
+
* - included:auth.dump 在快照里,行数可以合法为 0
|
|
93
|
+
* - skipped:默认开启但做不了(无权读取、没有 auth schema、存储不支持、schemas 可能已含 auth、太大),不算失败
|
|
94
|
+
* - failed:权限够、却在导出或上传时出错;只有显式要求时备份才因此失败
|
|
95
|
+
*/
|
|
96
|
+
export declare const AUTH_STATUSES: readonly ["included", "skipped", "failed"];
|
|
97
|
+
export declare const AUTH_SKIP_REASONS: readonly ["no_permission", "no_auth_schema", "unsupported_destination", "schemas_include_auth", "schemas_not_plain", "too_large", "snapshot_unavailable"];
|
|
98
|
+
export interface AuthTriggerInfo {
|
|
99
|
+
table: string;
|
|
100
|
+
name: string;
|
|
101
|
+
enabled: "O" | "D" | "R" | "A";
|
|
102
|
+
functionSchema: string;
|
|
103
|
+
functionName: string;
|
|
104
|
+
/** 触发器依赖的全部函数所在 schema(触发函数 + WHEN 条件里调用的) */
|
|
105
|
+
dependencySchemas?: string[];
|
|
106
|
+
}
|
|
107
|
+
export interface AuthPolicyInfo {
|
|
108
|
+
table: string;
|
|
109
|
+
name: string;
|
|
110
|
+
/** 策略表达式里引用的函数所在的非平台 schema;不在备份里的,恢复时建不出来 */
|
|
111
|
+
functionSchemas: string[];
|
|
112
|
+
}
|
|
113
|
+
export interface AuthSection {
|
|
114
|
+
status: (typeof AUTH_STATUSES)[number];
|
|
115
|
+
/** skipped 时是 AUTH_SKIP_REASONS 之一;failed 时是一句不带行值的说明 */
|
|
116
|
+
reason?: string;
|
|
117
|
+
dump?: {
|
|
118
|
+
key: string;
|
|
119
|
+
format: "custom";
|
|
120
|
+
bytes: number;
|
|
121
|
+
sha256: string;
|
|
122
|
+
};
|
|
123
|
+
/** 两张表在共享快照里的精确行数;演练恢复后拿它核对 */
|
|
124
|
+
rows?: {
|
|
125
|
+
users: number;
|
|
126
|
+
identities: number;
|
|
127
|
+
};
|
|
128
|
+
/** 密码哈希分类计数:none = 没有密码(OAuth、魔法链接、匿名);encrypted = 用项目密钥加密过,换项目后不能用原密码登录 */
|
|
129
|
+
passwordHashes?: {
|
|
130
|
+
none: number;
|
|
131
|
+
portable: number;
|
|
132
|
+
encrypted: number;
|
|
133
|
+
unrecognized: number;
|
|
134
|
+
};
|
|
135
|
+
anonymousUsers?: number;
|
|
136
|
+
ssoUsers?: number;
|
|
137
|
+
/** 有已验证 MFA 因子的用户数;读不到时为 null */
|
|
138
|
+
mfaUsers?: number | null;
|
|
139
|
+
triggers?: AuthTriggerInfo[];
|
|
140
|
+
policies?: AuthPolicyInfo[];
|
|
141
|
+
/**
|
|
142
|
+
* 两张表上的授权(aclexplode),新项目由平台另设一套;用户自己加的(例如给 authenticated 授 SELECT)
|
|
143
|
+
* 恢复时拿它比对、列成手工步骤。2.10.0 起写入;缺席 = 当时没记
|
|
144
|
+
*/
|
|
145
|
+
grants?: Array<{
|
|
146
|
+
table: string;
|
|
147
|
+
grantee: string;
|
|
148
|
+
privilege: string;
|
|
149
|
+
}>;
|
|
150
|
+
}
|
|
88
151
|
export interface StorageFile {
|
|
89
152
|
bucket: string;
|
|
90
153
|
key: string;
|
package/dist/manifest.js
CHANGED
|
@@ -15,8 +15,25 @@ import { GRANT_PRIVILEGES, GRANT_ROLES, GRANTED_OBJECT_KINDS } from "./grants.js
|
|
|
15
15
|
* 验证升级字段(本期不生成)。全部为**可加字段**——v2 读取端兼容 v1 快照。
|
|
16
16
|
* - (仍是 2)2.9.0 加 database.grants:可加字段,旧读取端忽略它、照旧恢复,不升版本,
|
|
17
17
|
* 免得还没升级的 CLI 和 worker 拒读新快照。
|
|
18
|
+
* - (仍是 2)2.10.0 加 auth:同样是可加字段。旧读取端忽略它和 auth.dump,演练和恢复与之前完全一样。
|
|
18
19
|
*/
|
|
19
20
|
export const MANIFEST_SCHEMA_VERSION = 2;
|
|
21
|
+
/**
|
|
22
|
+
* Auth 用户备份的结果。只有 included 的快照带 dump 和统计;其余状态说明为什么没备上。
|
|
23
|
+
* - included:auth.dump 在快照里,行数可以合法为 0
|
|
24
|
+
* - skipped:默认开启但做不了(无权读取、没有 auth schema、存储不支持、schemas 可能已含 auth、太大),不算失败
|
|
25
|
+
* - failed:权限够、却在导出或上传时出错;只有显式要求时备份才因此失败
|
|
26
|
+
*/
|
|
27
|
+
export const AUTH_STATUSES = ["included", "skipped", "failed"];
|
|
28
|
+
export const AUTH_SKIP_REASONS = [
|
|
29
|
+
"no_permission",
|
|
30
|
+
"no_auth_schema",
|
|
31
|
+
"unsupported_destination",
|
|
32
|
+
"schemas_include_auth",
|
|
33
|
+
"schemas_not_plain",
|
|
34
|
+
"too_large",
|
|
35
|
+
"snapshot_unavailable",
|
|
36
|
+
];
|
|
20
37
|
/** 结构断言失败时的统一出错口径:说清哪个字段坏了,让"桶里的 manifest 被篡改/截断"可定位。 */
|
|
21
38
|
function malformed(what) {
|
|
22
39
|
throw new Error(`manifest.json is malformed: ${what}`);
|
|
@@ -54,6 +71,65 @@ function assertGrantedObject(g) {
|
|
|
54
71
|
}
|
|
55
72
|
}
|
|
56
73
|
}
|
|
74
|
+
const isCount = (n) => typeof n === "number" && Number.isInteger(n) && n >= 0;
|
|
75
|
+
const isName = (s) => typeof s === "string" && s.length > 0;
|
|
76
|
+
/**
|
|
77
|
+
* auth 段的结构校验。included 的快照会驱动恢复往目标的 auth 表里写数据——错型或缺字段要在这里拦下,
|
|
78
|
+
* 不能到写目标时才炸;也不能把一个坏掉的 included 静默当成"没备 Auth"。
|
|
79
|
+
*/
|
|
80
|
+
function assertAuthSection(a) {
|
|
81
|
+
if (typeof a !== "object" || a === null || Array.isArray(a))
|
|
82
|
+
malformed("auth");
|
|
83
|
+
if (!isName(a.status))
|
|
84
|
+
malformed("auth.status");
|
|
85
|
+
optionalString(a.reason, "auth.reason");
|
|
86
|
+
// 只有 included 会驱动往目标写数据,所以只对它严格。其余状态(包括以后版本新增的状态和原因)
|
|
87
|
+
// 读端一律当"这份快照没有 Auth",不能因为不认识就把整份快照判成坏的、让演练失败
|
|
88
|
+
if (a.status !== "included")
|
|
89
|
+
return;
|
|
90
|
+
const d = a.dump;
|
|
91
|
+
if (typeof d !== "object" || d === null)
|
|
92
|
+
malformed("auth.dump");
|
|
93
|
+
if (!isName(a.dump.key) || !isName(a.dump.sha256) || !isCount(a.dump.bytes) || a.dump.format !== "custom") {
|
|
94
|
+
malformed("auth.dump");
|
|
95
|
+
}
|
|
96
|
+
if (!a.rows || !isCount(a.rows.users) || !isCount(a.rows.identities))
|
|
97
|
+
malformed("auth.rows");
|
|
98
|
+
const h = a.passwordHashes;
|
|
99
|
+
if (!h || ![h.none, h.portable, h.encrypted, h.unrecognized].every(isCount))
|
|
100
|
+
malformed("auth.passwordHashes");
|
|
101
|
+
if (!isCount(a.anonymousUsers) || !isCount(a.ssoUsers))
|
|
102
|
+
malformed("auth.anonymousUsers/ssoUsers");
|
|
103
|
+
if (a.mfaUsers !== null && !isCount(a.mfaUsers))
|
|
104
|
+
malformed("auth.mfaUsers");
|
|
105
|
+
if (!Array.isArray(a.triggers))
|
|
106
|
+
malformed("auth.triggers");
|
|
107
|
+
for (const t of a.triggers) {
|
|
108
|
+
if (!isName(t?.table) || !isName(t?.name) || !isName(t?.functionSchema) || !isName(t?.functionName)) {
|
|
109
|
+
malformed("auth.triggers[]");
|
|
110
|
+
}
|
|
111
|
+
if (!["O", "D", "R", "A"].includes(t.enabled))
|
|
112
|
+
malformed("auth.triggers[].enabled");
|
|
113
|
+
if (t.dependencySchemas !== undefined && !(Array.isArray(t.dependencySchemas) && t.dependencySchemas.every(isName))) {
|
|
114
|
+
malformed("auth.triggers[].dependencySchemas");
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
if (a.grants !== undefined) {
|
|
118
|
+
if (!Array.isArray(a.grants))
|
|
119
|
+
malformed("auth.grants");
|
|
120
|
+
for (const g of a.grants) {
|
|
121
|
+
if (!isName(g?.table) || !isName(g?.grantee) || !isName(g?.privilege))
|
|
122
|
+
malformed("auth.grants[]");
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
if (!Array.isArray(a.policies))
|
|
126
|
+
malformed("auth.policies");
|
|
127
|
+
for (const p of a.policies) {
|
|
128
|
+
if (!isName(p?.table) || !isName(p?.name) || !Array.isArray(p.functionSchemas) || !p.functionSchemas.every(isName)) {
|
|
129
|
+
malformed("auth.policies[]");
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
}
|
|
57
133
|
function assertManifestShape(m) {
|
|
58
134
|
// ref 驱动同源安全门:malformed 值会被当"身份已知"却永远匹配不上 = 保护静默失效
|
|
59
135
|
if (m.sourceProjectRef !== undefined && !/^[a-z0-9]{16,}$/.test(m.sourceProjectRef)) {
|
|
@@ -116,6 +192,8 @@ function assertManifestShape(m) {
|
|
|
116
192
|
malformed("database.tables[].estimatedRows");
|
|
117
193
|
}
|
|
118
194
|
}
|
|
195
|
+
if (m.auth !== undefined)
|
|
196
|
+
assertAuthSection(m.auth);
|
|
119
197
|
// 写入端恒写 storage: null(DB-only)或对象——字段整体缺失只可能是截断/损坏,
|
|
120
198
|
// 静默当成 DB-only 会跳过全部 Storage 验证与恢复
|
|
121
199
|
if (m.storage === undefined)
|
|
@@ -72,9 +72,22 @@ export interface AddForeignKeysResult {
|
|
|
72
72
|
* 其余错误:stopOnError(真实目标)= 回滚整个事务并抛出;否则(沙箱)按 allow 分类后继续。
|
|
73
73
|
* 调用方负责连接和最终的 commit/rollback 之外的一切——这里自己 begin/commit。
|
|
74
74
|
*/
|
|
75
|
+
/** pg_dump 的外键语句里 ADD CONSTRAINT <名> 之后、分号之前那一段,就是源库上 pg_get_constraintdef 的输出 */
|
|
76
|
+
export declare function foreignKeyDefinition(fk: ForeignKeyDef): string;
|
|
77
|
+
/**
|
|
78
|
+
* 比较外键定义:引号外的空白归一,NOT VALID 不算差别(源库的孤儿行会让恢复把它建成 NOT VALID)。
|
|
79
|
+
* 引号里的不动:"parent table" 和 "parent table" 是两张表
|
|
80
|
+
*/
|
|
81
|
+
export declare function normalizedConstraintDef(def: string): string;
|
|
75
82
|
export declare function addForeignKeys(client: Client, fks: ForeignKeyDef[], opts: {
|
|
76
83
|
allow: RegExp;
|
|
77
84
|
stopOnError: boolean;
|
|
78
85
|
/** 这些外键上的 COMMENT(pg_restore 写出的 SQL):外键加完再执行,不然注释对象还不存在 */
|
|
79
86
|
commentSql?: string;
|
|
87
|
+
/**
|
|
88
|
+
* 接着做(restore --finish):表上已经有同名外键时,定义一样(NOT VALID 与否不论)就不再加——是 NOT VALID 的
|
|
89
|
+
* 照样数孤儿行、写进报告,和一次成功的恢复一样;定义不一样就报错,不覆盖。比较在下面的 search_path 下做,
|
|
90
|
+
* pg_get_constraintdef 和 pg_dump 一样写全限定名
|
|
91
|
+
*/
|
|
92
|
+
resume?: boolean;
|
|
80
93
|
}): Promise<AddForeignKeysResult>;
|