backupdrill 2.9.2 → 2.10.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (43) hide show
  1. package/README.md +23 -5
  2. package/dist/auth-backup.d.ts +110 -0
  3. package/dist/auth-backup.js +383 -0
  4. package/dist/auth-drill.d.ts +69 -0
  5. package/dist/auth-drill.js +469 -0
  6. package/dist/auth-restore.d.ts +120 -0
  7. package/dist/auth-restore.js +633 -0
  8. package/dist/backup.d.ts +17 -0
  9. package/dist/backup.js +372 -19
  10. package/dist/config.d.ts +9 -0
  11. package/dist/config.js +17 -0
  12. package/dist/drill.d.ts +24 -3
  13. package/dist/drill.js +36 -0
  14. package/dist/dump-sql.d.ts +6 -0
  15. package/dist/dump-sql.js +31 -0
  16. package/dist/external-refs.d.ts +6 -1
  17. package/dist/external-refs.js +5 -0
  18. package/dist/index.js +67 -3
  19. package/dist/lib.d.ts +9 -3
  20. package/dist/lib.js +4 -2
  21. package/dist/manifest.d.ts +63 -0
  22. package/dist/manifest.js +78 -0
  23. package/dist/orphaned-foreign-keys.d.ts +13 -0
  24. package/dist/orphaned-foreign-keys.js +75 -25
  25. package/dist/pgbin.d.ts +7 -0
  26. package/dist/pgbin.js +24 -0
  27. package/dist/ping.js +1 -0
  28. package/dist/recovery-doc.d.ts +25 -0
  29. package/dist/recovery-doc.js +232 -53
  30. package/dist/restore-engine.d.ts +73 -1
  31. package/dist/restore-engine.js +155 -77
  32. package/dist/restore-record.d.ts +47 -0
  33. package/dist/restore-record.js +57 -0
  34. package/dist/restore.d.ts +64 -0
  35. package/dist/restore.js +348 -34
  36. package/dist/snapshot-store.d.ts +13 -0
  37. package/dist/snapshot-store.js +25 -0
  38. package/dist/snapshots.d.ts +2 -0
  39. package/dist/snapshots.js +10 -3
  40. package/package.json +1 -1
  41. package/plugin/README.md +1 -1
  42. package/plugin/skills/supabase-backup/SKILL.md +7 -7
  43. package/plugin/skills/supabase-backup/assets/scheduled-backup.yml +6 -1
@@ -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
  /**
@@ -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;
@@ -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({ ok: true, manifest }) + "\n");
94
- await ping.success(backupSummary(manifest));
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
- // RECOVERY.md 的授权那一步:worker 的 Drive 版手册和这里的 S3 版用同一份 SQL
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";
@@ -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>;
@@ -103,6 +103,35 @@ export function orphanedForeignKeysCheck(orphaned) {
103
103
  * 其余错误:stopOnError(真实目标)= 回滚整个事务并抛出;否则(沙箱)按 allow 分类后继续。
104
104
  * 调用方负责连接和最终的 commit/rollback 之外的一切——这里自己 begin/commit。
105
105
  */
106
+ /** pg_dump 的外键语句里 ADD CONSTRAINT <名> 之后、分号之前那一段,就是源库上 pg_get_constraintdef 的输出 */
107
+ export function foreignKeyDefinition(fk) {
108
+ const match = /ADD CONSTRAINT (?:"(?:[^"]|"")+"|[a-z_][a-z0-9_]*) ([\s\S]*?);\s*$/.exec(fk.statement);
109
+ return match ? match[1] : fk.statement;
110
+ }
111
+ /**
112
+ * 比较外键定义:引号外的空白归一,NOT VALID 不算差别(源库的孤儿行会让恢复把它建成 NOT VALID)。
113
+ * 引号里的不动:"parent table" 和 "parent table" 是两张表
114
+ */
115
+ export function normalizedConstraintDef(def) {
116
+ let out = "";
117
+ let quoted = false;
118
+ let pendingSpace = false;
119
+ for (const ch of def.trim()) {
120
+ if (!quoted && /\s/.test(ch)) {
121
+ pendingSpace = true;
122
+ continue;
123
+ }
124
+ if (pendingSpace) {
125
+ out += " ";
126
+ pendingSpace = false;
127
+ }
128
+ // "" 是引号里的一个双引号:翻两次,quoted 不变
129
+ if (ch === '"')
130
+ quoted = !quoted;
131
+ out += ch;
132
+ }
133
+ return out.replace(/ NOT VALID$/, "");
134
+ }
106
135
  export async function addForeignKeys(client, fks, opts) {
107
136
  const result = { orphaned: [], expectedSkips: 0, failures: [] };
108
137
  // 和 pg_restore 的脚本头一样关掉超时:角色上配的 statement_timeout 会让大表的外键校验中途被掐断。
@@ -129,7 +158,51 @@ export async function addForeignKeys(client, fks, opts) {
129
158
  "where oid in (select to_regclass(name) from unnest($1::text[]) as name) and relforcerowsecurity", [[...new Set(fks.flatMap((fk) => [fk.table, fk.references]).map((t) => `${quoteIdent(t.schema)}.${quoteIdent(t.name)}`))]]);
130
159
  for (const { name } of forced.rows)
131
160
  await client.query(`alter table only ${name} no force row level security`);
161
+ /** 数违反这条外键的行;数不出来(类型没有可用的运算符等)时为 null,只影响报告 */
162
+ const countOrphans = async (fk) => {
163
+ await client.query("savepoint count_orphans");
164
+ try {
165
+ const plan = await client.query(COMPARISON_PLAN_SQL, [fk.constraint, `${quoteIdent(fk.table.schema)}.${quoteIdent(fk.table.name)}`]);
166
+ if (plan.rows.length !== fk.columns.length)
167
+ throw new Error("comparison operators not found");
168
+ const counted = await client.query(orphanCountSql(fk, {
169
+ operators: plan.rows,
170
+ referencedPartitioned: plan.rows[0].referenced_partitioned,
171
+ }));
172
+ await client.query("release savepoint count_orphans");
173
+ return Number(counted.rows[0].n);
174
+ }
175
+ catch {
176
+ await client.query("rollback to savepoint count_orphans");
177
+ return null;
178
+ }
179
+ };
180
+ const orphanedEntry = (fk, orphanRows) => ({
181
+ constraint: fk.constraint,
182
+ table: formatQualified(fk.table),
183
+ referencedTable: formatQualified(fk.references),
184
+ columns: fk.columns,
185
+ referencedColumns: fk.referencedColumns,
186
+ matchFull: fk.matchFull,
187
+ orphanRows,
188
+ });
132
189
  for (const fk of fks) {
190
+ if (opts.resume) {
191
+ const existing = await client.query(`select pg_get_constraintdef(c.oid) as def, c.convalidated as valid from pg_constraint c
192
+ where c.conrelid = to_regclass($1) and c.conname = $2 and c.contype = 'f'`, [`${quoteIdent(fk.table.schema)}.${quoteIdent(fk.table.name)}`, fk.constraint]);
193
+ if (existing.rows.length) {
194
+ if (normalizedConstraintDef(existing.rows[0].def) !== normalizedConstraintDef(foreignKeyDefinition(fk))) {
195
+ throw new Error(`${formatQualified(fk.table)} already has a foreign key ${fk.constraint} with a different definition ` +
196
+ `(${existing.rows[0].def}); it was left as it is`);
197
+ }
198
+ if (!existing.rows[0].valid) {
199
+ const orphanRows = await countOrphans(fk);
200
+ if (orphanRows !== 0)
201
+ result.orphaned.push(orphanedEntry(fk, orphanRows));
202
+ }
203
+ continue;
204
+ }
205
+ }
133
206
  await client.query("savepoint add_fk");
134
207
  try {
135
208
  await client.query(fk.statement);
@@ -163,32 +236,9 @@ export async function addForeignKeys(client, fks, opts) {
163
236
  continue;
164
237
  }
165
238
  // 计数只为报告:失败(类型没有 = 运算符等)不影响已经加上的外键
166
- await client.query("savepoint count_orphans");
167
- let orphanRows = null;
168
- try {
169
- const plan = await client.query(COMPARISON_PLAN_SQL, [fk.constraint, `${quoteIdent(fk.table.schema)}.${quoteIdent(fk.table.name)}`]);
170
- if (plan.rows.length !== fk.columns.length)
171
- throw new Error("comparison operators not found");
172
- const counted = await client.query(orphanCountSql(fk, {
173
- operators: plan.rows,
174
- referencedPartitioned: plan.rows[0].referenced_partitioned,
175
- }));
176
- orphanRows = Number(counted.rows[0].n);
177
- await client.query("release savepoint count_orphans");
178
- }
179
- catch {
180
- await client.query("rollback to savepoint count_orphans");
181
- }
239
+ const orphanRows = await countOrphans(fk);
182
240
  await client.query("release savepoint add_fk");
183
- result.orphaned.push({
184
- constraint: fk.constraint,
185
- table: formatQualified(fk.table),
186
- referencedTable: formatQualified(fk.references),
187
- columns: fk.columns,
188
- referencedColumns: fk.referencedColumns,
189
- matchFull: fk.matchFull,
190
- orphanRows,
191
- });
241
+ result.orphaned.push(orphanedEntry(fk, orphanRows));
192
242
  }
193
243
  if (opts.commentSql) {
194
244
  await client.query("savepoint add_comments");
package/dist/pgbin.d.ts CHANGED
@@ -5,6 +5,13 @@
5
5
  * 绝不能把 pg_dump 当恢复器执行。
6
6
  */
7
7
  export declare function resolvePgRestoreBin(): string;
8
+ /**
9
+ * psql 二进制(带 Auth 的恢复由它执行单事务):显式 BACKUPDRILL_PSQL 最高优先;否则和 pg_restore 同目录
10
+ * (resolvePgRestoreBin 以 pg_restore 结尾时换成 psql),它们是同一个客户端包;推不出来就用 PATH 上的 psql
11
+ */
12
+ export declare function resolvePsqlBin(): string;
13
+ /** `<工具> --version` 里的完整版本号(17.6 → [17, 6]);拿不到 → null */
14
+ export declare function localToolVersion(bin: string): Promise<[number, number] | null>;
8
15
  /**
9
16
  * Parse the major version out of `pg_dump --version` output.
10
17
  *
package/dist/pgbin.js CHANGED
@@ -18,6 +18,30 @@ export function resolvePgRestoreBin() {
18
18
  }
19
19
  return "pg_restore";
20
20
  }
21
+ /**
22
+ * psql 二进制(带 Auth 的恢复由它执行单事务):显式 BACKUPDRILL_PSQL 最高优先;否则和 pg_restore 同目录
23
+ * (resolvePgRestoreBin 以 pg_restore 结尾时换成 psql),它们是同一个客户端包;推不出来就用 PATH 上的 psql
24
+ */
25
+ export function resolvePsqlBin() {
26
+ if (process.env.BACKUPDRILL_PSQL)
27
+ return process.env.BACKUPDRILL_PSQL;
28
+ const pgRestore = resolvePgRestoreBin();
29
+ if (/(^|\/)pg_restore$/.test(pgRestore))
30
+ return pgRestore.replace(/pg_restore$/, "psql");
31
+ return "psql";
32
+ }
33
+ /** `<工具> --version` 里的完整版本号(17.6 → [17, 6]);拿不到 → null */
34
+ export async function localToolVersion(bin) {
35
+ try {
36
+ // 有上限:包装脚本之类的东西卡住时,不能把恢复挂在这里
37
+ const { stdout } = await execFileAsync(bin, ["--version"], { timeout: 10_000 });
38
+ const match = stdout.match(/\(PostgreSQL\)\s+(\d+)(?:\.(\d+))?/);
39
+ return match ? [Number(match[1]), Number(match[2] ?? 0)] : null;
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
21
45
  /**
22
46
  * Parse the major version out of `pg_dump --version` output.
23
47
  *
package/dist/ping.js CHANGED
@@ -125,6 +125,7 @@ function truncate(text) {
125
125
  export function backupSummary(manifest) {
126
126
  return (`backupdrill ${TOOL_VERSION}: backup complete, ${manifest.database.tableCount} tables` +
127
127
  (manifest.storage ? ` + ${manifest.storage.fileCount} Storage files` : " (database only)") +
128
+ (manifest.auth?.status === "included" ? ` + ${manifest.auth.rows.users} Auth users` : "") +
128
129
  `, snapshot ${manifest.dump.key.split("/").at(-2) ?? manifest.createdAt}`);
129
130
  }
130
131
  /** drill 跑完(没抛错)后发哪种 ping、带什么:通过 = 成功;没通过 = 失败,列出没过的检查 */