backupdrill 2.9.1 → 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 (45) hide show
  1. package/README.md +24 -6
  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 +379 -25
  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/grants.d.ts +25 -1
  19. package/dist/grants.js +53 -13
  20. package/dist/index.js +67 -3
  21. package/dist/lib.d.ts +9 -3
  22. package/dist/lib.js +4 -2
  23. package/dist/manifest.d.ts +63 -0
  24. package/dist/manifest.js +78 -0
  25. package/dist/orphaned-foreign-keys.d.ts +13 -0
  26. package/dist/orphaned-foreign-keys.js +75 -25
  27. package/dist/pgbin.d.ts +7 -0
  28. package/dist/pgbin.js +24 -0
  29. package/dist/ping.js +1 -0
  30. package/dist/recovery-doc.d.ts +25 -0
  31. package/dist/recovery-doc.js +232 -53
  32. package/dist/restore-engine.d.ts +73 -1
  33. package/dist/restore-engine.js +155 -77
  34. package/dist/restore-record.d.ts +47 -0
  35. package/dist/restore-record.js +57 -0
  36. package/dist/restore.d.ts +64 -0
  37. package/dist/restore.js +348 -34
  38. package/dist/snapshot-store.d.ts +13 -0
  39. package/dist/snapshot-store.js +25 -0
  40. package/dist/snapshots.d.ts +2 -0
  41. package/dist/snapshots.js +10 -3
  42. package/package.json +1 -1
  43. package/plugin/README.md +1 -1
  44. package/plugin/skills/supabase-backup/SKILL.md +7 -7
  45. package/plugin/skills/supabase-backup/assets/scheduled-backup.yml +6 -1
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、带什么:通过 = 成功;没通过 = 失败,列出没过的检查 */
@@ -8,4 +8,29 @@ export interface RecoveryDocContext {
8
8
  prefix: string;
9
9
  projectName: string;
10
10
  }
11
+ /**
12
+ * 手册里的归档在哪。bucket = S3 兼容桶,写完整对象键;folder = 托管 worker 的 Google Drive 目标,
13
+ * 手册就放在归档旁边,写文件名,name 是下载那一步说的"从哪里下"(如 "Google Drive folder")
14
+ */
15
+ export type RecoveryDocPlace = {
16
+ kind: "bucket";
17
+ } | {
18
+ kind: "folder";
19
+ name: string;
20
+ };
21
+ export interface AuthRecoveryText {
22
+ /** "What this snapshot contains" 里 Auth 那一行(带换行);manifest 没有 auth 段时为空串 */
23
+ contentsLine: string;
24
+ /** 只有 Auth 为 included 的快照才有:替换"Not covered"整段和恢复的第 3、4 步 */
25
+ included: {
26
+ notCovered: string;
27
+ restoreSteps: string;
28
+ } | null;
29
+ }
30
+ /**
31
+ * RECOVERY.md 里和 Auth 用户有关的段落(2.10.0 起)。S3 版(renderRecoveryDoc)和托管 worker 的
32
+ * Google Drive 版共用这一份:单事务恢复脚本里的空目标检查、清理待处理链接、行数核对,两边不能各写各的。
33
+ * 没有 auth 字段的快照:contentsLine 为空、included 为 null,手册和 2.10.0 之前一样
34
+ */
35
+ export declare function authRecoveryText(manifest: Manifest, place: RecoveryDocPlace): AuthRecoveryText;
11
36
  export declare function renderRecoveryDoc(manifest: Manifest, ctx: RecoveryDocContext): string;
@@ -1,11 +1,158 @@
1
1
  import { recoveryGrantsSql } from "./grants.js";
2
+ import { plainSchemaName, restorableAuthObjects } from "./auth-backup.js";
3
+ import { authRestoreNotes, CLEAR_PENDING_AUTH_SQL } from "./auth-restore.js";
2
4
  function quoteSqlIdent(name) {
3
5
  return `"${name.replace(/"/g, '""')}"`;
4
6
  }
7
+ const ereEscape = (s) => s.replace(/[.[\]{}()*+?^$|\\]/g, "\\$&");
8
+ const AUTH_NOT_INCLUDED_TEXT = {
9
+ no_permission: "the backup role couldn't read every row of the Auth tables",
10
+ no_auth_schema: "the source database has no Supabase auth schema",
11
+ unsupported_destination: "this destination couldn't hold the Auth archive",
12
+ schemas_include_auth: "the auth schema is part of the database dump",
13
+ schemas_not_plain: "the schema list used a pattern or a quoted name; the Auth users are in the database dump only if one of those patterns matched auth",
14
+ too_large: "the Auth archive was larger than 2 GiB",
15
+ snapshot_unavailable: "a consistent snapshot for the Auth export couldn't be set up",
16
+ };
5
17
  /** POSIX 安全的 shell 值引用:项目名/前缀里合法的空格与元字符不得拆散或改写命令。 */
6
18
  function shellQuote(value) {
7
19
  return /^[A-Za-z0-9._/:@=-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
8
20
  }
21
+ /**
22
+ * RECOVERY.md 里和 Auth 用户有关的段落(2.10.0 起)。S3 版(renderRecoveryDoc)和托管 worker 的
23
+ * Google Drive 版共用这一份:单事务恢复脚本里的空目标检查、清理待处理链接、行数核对,两边不能各写各的。
24
+ * 没有 auth 字段的快照:contentsLine 为空、included 为 null,手册和 2.10.0 之前一样
25
+ */
26
+ export function authRecoveryText(manifest, place) {
27
+ const db = manifest.database;
28
+ const mb = (bytes) => (bytes / 1024 / 1024).toFixed(1);
29
+ // 只有 included 的快照带 auth.dump
30
+ const auth = manifest.auth?.status === "included" ? manifest.auth : null;
31
+ const dumpFile = place.kind === "bucket" ? manifest.dump.key : "dump.pgcustom";
32
+ const authFile = place.kind === "bucket" ? (auth?.dump?.key ?? "auth.dump") : "auth.dump";
33
+ const authListing = place.kind === "bucket" ? `\`${authFile}\`` : "`auth.dump` in this folder";
34
+ const container = place.kind === "bucket" ? "bucket" : place.name;
35
+ const authLine = auth
36
+ ? `- **Supabase Auth users**: ${authListing}
37
+ (pg_dump custom format, ${mb(auth.dump.bytes)} MB, sha256 \`${auth.dump.sha256}\`) — ${auth.rows.users.toLocaleString("en-US")} users, ${auth.rows.identities.toLocaleString("en-US")} sign-in identities
38
+ `
39
+ : manifest.auth
40
+ ? `- **Supabase Auth users**: not in this snapshot (${AUTH_NOT_INCLUDED_TEXT[manifest.auth.reason ?? ""] ?? manifest.auth.reason ?? "not captured"})
41
+ `
42
+ : "";
43
+ // 空目标检查用的 schema 列表(SQL 字符串字面量,单引号按 SQL 规则加倍)
44
+ // 含 Auth 的快照里 schemas 全是普通名字(见 authInSchemas),按 pg_dump 的规则规范化后逐个比较
45
+ // plainSchemaName 只放行 [a-z0-9_],拼进 SQL 字面量是安全的;万一出现别的(不该发生),整项不放进去
46
+ const schemaListSql = db.schemas
47
+ .map((name) => plainSchemaName(name))
48
+ .filter((name) => name !== null)
49
+ .map((name) => `'${name}'`)
50
+ .join(", ");
51
+ // 自动补建的只有 restorableAuthObjects 认可的触发器(名字都是普通标识符,拼进命令也安全);
52
+ // 其余写进下面的手工步骤
53
+ const restorable = auth ? restorableAuthObjects({ triggers: auth.triggers, policies: auth.policies }, db.schemas) : null;
54
+ const authObjects = restorable ? restorable.triggers.map((t) => `TRIGGER auth ${t.table} ${t.name}`) : [];
55
+ const authObjectsGrep = authObjects.map((o) => ereEscape(o)).join("|");
56
+ const authNotes = auth
57
+ ? (() => {
58
+ const { notes, manual } = authRestoreNotes(auth, db.schemas);
59
+ return [
60
+ ...notes.map((note) => `- ${note}`),
61
+ ...manual.map((note) => `- The ${note}. Its definition is in \`auth.dump\` (\`pg_restore --section=post-data -f - auth.dump\`).`),
62
+ ];
63
+ })()
64
+ : [];
65
+ if (!auth)
66
+ return { contentsLine: authLine, included: null };
67
+ const notCovered = `Supabase **Auth sessions and MFA factors, Auth settings (sign-in providers,
68
+ SMTP, redirect URLs, email templates), secret values, Edge Function code and most
69
+ platform settings are NOT in this snapshot**. After restoring, reconfigure them
70
+ by hand; everyone signs in once more. The Auth users themselves (IDs, emails,
71
+ password hashes, sign-in identities) are in this snapshot and are restored in
72
+ step 4 below, together with the database.
73
+ ${authNotes.length ? `\n${authNotes.join("\n")}\n` : ""}`;
74
+ const restoreSteps = `3. Download \`${dumpFile}\` and \`${authFile}\` from this
75
+ ${container}, then verify them:
76
+
77
+ \`\`\`bash
78
+ shasum -a 256 dump.pgcustom # must print ${manifest.dump.sha256}
79
+ shasum -a 256 auth.dump # must print ${auth.dump.sha256}
80
+ \`\`\`
81
+
82
+ 4. Restore the Auth users and the database **in one transaction**, so any error
83
+ leaves the target exactly as it was and you can simply run it again. First turn
84
+ both archives into one SQL file; go on only if the last line prints
85
+ \`restore.sql is complete\` (a half-written file would otherwise be committed):
86
+
87
+ \`\`\`bash
88
+ (
89
+ set -euo pipefail
90
+ pg_restore -l dump.pgcustom > database.full.list
91
+ grep -Ev '^[0-9]+; [0-9]+ [0-9]+ SCHEMA - public ' database.full.list > database.list
92
+ ${authObjects.length ? ` pg_restore -l auth.dump > auth.full.list
93
+ grep -E '^[0-9]+; [0-9]+ [0-9]+ (${authObjectsGrep}) ' auth.full.list > auth-objects.list
94
+ test "$(wc -l < auth-objects.list)" -eq ${authObjects.length}
95
+ ` : ""} {
96
+ cat <<'SQL'
97
+ lock table auth.users, auth.identities in share row exclusive mode;
98
+ do $bd$ begin
99
+ if exists (select 1 from auth.users) then
100
+ raise exception 'auth.users is not empty: restore only into a new project';
101
+ end if;
102
+ if exists (select 1 from pg_trigger
103
+ where tgrelid in ('auth.users'::regclass, 'auth.identities'::regclass) and not tgisinternal)
104
+ or exists (select 1 from pg_policy where polrelid in ('auth.users'::regclass, 'auth.identities'::regclass)) then
105
+ raise exception 'the Auth tables already have triggers or policies: restore only into a new project';
106
+ end if;
107
+ if exists (select 1 from pg_class c join pg_namespace n on n.oid = c.relnamespace
108
+ where n.nspname = any (array[${schemaListSql}]) and c.relkind in ('r', 'p', 'v', 'm', 'f')
109
+ and not exists (select 1 from pg_depend d where d.objid = c.oid and d.deptype = 'e')) then
110
+ raise exception 'the target already has tables in the restored schemas: restore only into a new project';
111
+ end if;
112
+ end $bd$;
113
+ SQL
114
+ pg_restore --data-only --no-owner --no-privileges -n auth -t users -f - auth.dump
115
+ pg_restore --data-only --no-owner --no-privileges -n auth -t identities -f - auth.dump
116
+ cat <<'SQL'
117
+ ${CLEAR_PENDING_AUTH_SQL}
118
+ do $bd$ begin
119
+ if (select count(*) from auth.users) <> ${auth.rows.users} or (select count(*) from auth.identities) <> ${auth.rows.identities} then
120
+ raise exception 'the Auth row counts differ from this snapshot';
121
+ end if;
122
+ end $bd$;
123
+ SQL
124
+ pg_restore --no-owner --no-privileges -L database.list -f - dump.pgcustom
125
+ ${authObjects.length ? ` pg_restore --no-owner --no-privileges -L auth-objects.list -f - auth.dump
126
+ ` : ""} } > restore.sql
127
+ echo "restore.sql is complete"
128
+ )
129
+ \`\`\`
130
+
131
+ Then run it against the empty target. pg_restore 17 and newer write
132
+ \`SET transaction_timeout\`, which PostgreSQL 16 and older reject, so restore into
133
+ a PostgreSQL 17+ project (new Supabase projects are) or generate the file with a
134
+ pg_restore matching the target. Enter the password at a hidden prompt so it never
135
+ touches the URL, argv, or shell history:
136
+
137
+ \`\`\`bash
138
+ read -rs PGPASSWORD && export PGPASSWORD # hidden prompt
139
+ psql -X --single-transaction -v ON_ERROR_STOP=1 \\
140
+ --dbname "postgresql://postgres.<target-ref>@<target-pooler-host>:5432/postgres" -f restore.sql
141
+ unset PGPASSWORD
142
+ \`\`\`
143
+
144
+ The script stops if the target already has Auth users, triggers or policies on the
145
+ Auth tables, or tables in the restored schemas, so it never merges into an
146
+ existing project. The Auth users go in first, so foreign keys into
147
+ \`auth.users\` resolve, and their count is checked against this snapshot. Links
148
+ and codes for password resets, email confirmations and email or phone changes
149
+ that were pending at backup time are cleared. ${authObjects.length
150
+ ? "Your triggers on the Auth tables are recreated at the end."
151
+ : "There are no triggers of your own on the Auth tables to recreate."} Do **not** use \`--clean\` against a Supabase project: it drops and
152
+ recreates \`public\`, and the grants Supabase put on it go with it.
153
+ `;
154
+ return { contentsLine: authLine, included: { notCovered, restoreSteps } };
155
+ }
9
156
  export function renderRecoveryDoc(manifest, ctx) {
10
157
  const base = manifest.dump.key.replace(/\/dump\.pgcustom$/, "");
11
158
  const db = manifest.database;
@@ -24,6 +171,9 @@ export function renderRecoveryDoc(manifest, ctx) {
24
171
  `create extension if not exists ${quoteSqlIdent(e.name)} schema ${quoteSqlIdent(e.schema)} cascade;`)
25
172
  .join("\n")
26
173
  : "-- (this snapshot records no extensions)";
174
+ // Auth 用户(2.10.0 起):没有 auth 字段的快照,下面用到的三段都和以前一样
175
+ const authText = authRecoveryText(manifest, { kind: "bucket" });
176
+ const auth = authText.included;
27
177
  // 2.0 形态:凭据只经环境变量(argv 对全机器可见);写入需要键入目标 ref 确认。
28
178
  // DB-only 快照不出现 Storage 凭据与旗标——不为用不上的能力索要宽权限 key
29
179
  const cliRestoreCommand = [
@@ -42,6 +192,84 @@ export function renderRecoveryDoc(manifest, ctx) {
42
192
  ...(storage ? [` --target-supabase-url https://<target-ref>.supabase.co \\`] : []),
43
193
  ` --confirm-target <target-ref>`,
44
194
  ].join("\n");
195
+ // 没有 Auth 的快照:以下两段与 2.10.0 之前逐字一致
196
+ const notCovered = auth
197
+ ? auth.notCovered
198
+ : `Supabase **Auth users/sessions, secret values, Edge Function code and most
199
+ platform settings are NOT in this snapshot**. After restoring, reconfigure them
200
+ by hand. This is a database + Storage snapshot, not a full project image.
201
+ ${db.schemas.includes("auth")
202
+ ? ""
203
+ : `
204
+ If a table in this snapshot has a foreign key into \`auth.users\` (a \`profiles.id\`
205
+ that references it, for example), copy the Auth users into the new project
206
+ **before** restoring, or that foreign key can't be created and the restore fails.
207
+ \`backupdrill restore --dry-run\` checks those keys against the new project and reports
208
+ the rows that have no user, plus any key it couldn't check.
209
+ Triggers on \`auth.users\` aren't in this snapshot either; recreate them afterwards.
210
+ `}`;
211
+ const restoreSteps = auth
212
+ ? auth.restoreSteps
213
+ : `3. Download \`${manifest.dump.key}\` from this bucket, then verify it:
214
+
215
+ \`\`\`bash
216
+ shasum -a 256 dump.pgcustom # must print ${manifest.dump.sha256}
217
+ \`\`\`
218
+
219
+ 4. Restore — **without \`--clean\`**, into the empty target. Enter the password at
220
+ a hidden prompt so it never touches the URL, argv, or shell history:
221
+
222
+ \`\`\`bash
223
+ read -rs PGPASSWORD && export PGPASSWORD # hidden prompt
224
+ pg_restore --no-owner --no-privileges \\
225
+ --dbname "postgresql://postgres.<target-ref>@<target-pooler-host>:5432/postgres" dump.pgcustom
226
+ unset PGPASSWORD
227
+ \`\`\`
228
+
229
+ One error is expected and harmless: \`schema "public" already exists\` (the
230
+ target always has it). A foreign key error mentioning \`auth.users\` means the
231
+ Auth users were not copied in first (see "Not covered" above). Do **not** use \`--clean\` against a Supabase project:
232
+ it drops and recreates \`public\`, and the grants Supabase put on it go with it.
233
+ `;
234
+ const cliSection = auth
235
+ ? `## The BackupDrill CLI
236
+
237
+ \`backupdrill restore\` 2.10.0 and newer does step 4 for you: the Auth users and the
238
+ database go in one transaction, and it checks the target before writing anything.
239
+ It needs \`psql\` from the same PostgreSQL client package as \`pg_restore\`.
240
+
241
+ \`\`\`bash
242
+ npm install -g backupdrill
243
+ ${cliRestoreCommand}
244
+ \`\`\`
245
+
246
+ Add \`--dry-run\` first to preview every check without writing anything. (Skip the
247
+ \`read\` lines to have the CLI prompt you itself; \`unset\` the variables afterwards.)
248
+ If it's interrupted while committing, run \`backupdrill restore --status\` with the same
249
+ \`BACKUPDRILL_TARGET_DATABASE_URL\` on the same machine: it says whether the restore
250
+ committed. If it did and the grants or foreign keys after the commit didn't finish,
251
+ \`backupdrill restore --finish --confirm-target <target-ref>\` with the same settings
252
+ does them. \`--skip-auth\` restores the database without the Auth users.
253
+
254
+ `
255
+ : `## Easiest path — the BackupDrill CLI
256
+
257
+ \`\`\`bash
258
+ npm install -g backupdrill
259
+ ${cliRestoreCommand}
260
+ \`\`\`
261
+
262
+ Add \`--dry-run\` first to preview every check without writing anything. (Skip the
263
+ \`read\` lines to have the CLI prompt you itself; \`unset\` both variables afterwards.)
264
+ The CLI verifies the archive checksum, refuses non-empty targets, checks that rows
265
+ referenced outside the snapshot (such as \`auth.users\`) are on the target, installs
266
+ the extensions, restores the database in a single transaction through the same
267
+ engine the weekly drills use (an SQL error rolls it back and the extensions stay
268
+ installed; if the connection drops while it commits, check the target before
269
+ retrying), sets the grants above, verifies table counts and row presence afterwards, then rebuilds buckets, uploads the
270
+ Storage files back and reconciles every one against the target.
271
+
272
+ `;
45
273
  return `# BackupDrill recovery runbook — ${ctx.projectName} @ ${ctx.snapshot}
46
274
 
47
275
  This file was written next to the snapshot it describes and is **self-contained**:
@@ -60,23 +288,11 @@ ${extensions.length
60
288
  - **Storage files**: ${storage
61
289
  ? `${storage.fileCount} files, ${mb(storage.totalBytes)} MB under \`${base}/storage/<bucket>/<key>\` — per-file sha256 in manifest.json`
62
290
  : "none (database-only snapshot)"}
63
- - **Machine-readable inventory**: \`${base}/manifest.json\`
291
+ ${authText.contentsLine}- **Machine-readable inventory**: \`${base}/manifest.json\`
64
292
 
65
293
  ## Not covered — plan for these separately
66
294
 
67
- Supabase **Auth users/sessions, secret values, Edge Function code and most
68
- platform settings are NOT in this snapshot**. After restoring, reconfigure them
69
- by hand. This is a database + Storage snapshot, not a full project image.
70
- ${db.schemas.includes("auth")
71
- ? ""
72
- : `
73
- If a table in this snapshot has a foreign key into \`auth.users\` (a \`profiles.id\`
74
- that references it, for example), copy the Auth users into the new project
75
- **before** restoring, or that foreign key can't be created and the restore fails.
76
- \`backupdrill restore --dry-run\` checks those keys against the new project and reports
77
- the rows that have no user, plus any key it couldn't check.
78
- Triggers on \`auth.users\` aren't in this snapshot either; recreate them afterwards.
79
- `}
295
+ ${notCovered}
80
296
  ## Restore the database (into an EMPTY project)
81
297
 
82
298
  1. Create a **fresh** Supabase project (never restore onto the source project),
@@ -87,27 +303,7 @@ Triggers on \`auth.users\` aren't in this snapshot either; recreate them afterwa
87
303
  ${extensionSql}
88
304
  \`\`\`
89
305
 
90
- 3. Download \`${manifest.dump.key}\` from this bucket, then verify it:
91
-
92
- \`\`\`bash
93
- shasum -a 256 dump.pgcustom # must print ${manifest.dump.sha256}
94
- \`\`\`
95
-
96
- 4. Restore — **without \`--clean\`**, into the empty target. Enter the password at
97
- a hidden prompt so it never touches the URL, argv, or shell history:
98
-
99
- \`\`\`bash
100
- read -rs PGPASSWORD && export PGPASSWORD # hidden prompt
101
- pg_restore --no-owner --no-privileges \\
102
- --dbname "postgresql://postgres.<target-ref>@<target-pooler-host>:5432/postgres" dump.pgcustom
103
- unset PGPASSWORD
104
- \`\`\`
105
-
106
- One error is expected and harmless: \`schema "public" already exists\` (the
107
- target always has it). A foreign key error mentioning \`auth.users\` means the
108
- Auth users were not copied in first (see "Not covered" above). Do **not** use \`--clean\` against a Supabase project:
109
- it drops and recreates \`public\`, and the grants Supabase put on it go with it.
110
-
306
+ ${restoreSteps}
111
307
  5. Set the grants for \`anon\`, \`authenticated\` and \`service_role\`. The dump
112
308
  carries none. With Supabase's new defaults, supabase-js requests to restored
113
309
  tables in \`public\` fail with \`42501 permission denied\` until you grant access. ${db.grants
@@ -129,23 +325,6 @@ Files live at \`${base}/storage/<original-bucket>/<original-key>\` in this
129
325
  bucket. Recreate each bucket in the target project, then re-upload the files
130
326
  ${storage?.buckets ? "(bucket attributes — public flag, size and MIME limits — are recorded in manifest.json under `storage.buckets`)" : "(bucket attributes were not captured for this snapshot; recreate buckets with the settings you know)"}.
131
327
 
132
- ## Easiest path — the BackupDrill CLI
133
-
134
- \`\`\`bash
135
- npm install -g backupdrill
136
- ${cliRestoreCommand}
137
- \`\`\`
138
-
139
- Add \`--dry-run\` first to preview every check without writing anything. (Skip the
140
- \`read\` lines to have the CLI prompt you itself; \`unset\` both variables afterwards.)
141
- The CLI verifies the archive checksum, refuses non-empty targets, checks that rows
142
- referenced outside the snapshot (such as \`auth.users\`) are on the target, installs
143
- the extensions, restores the database in a single transaction through the same
144
- engine the weekly drills use (an SQL error rolls it back and the extensions stay
145
- installed; if the connection drops while it commits, check the target before
146
- retrying), sets the grants above, verifies table counts and row presence afterwards, then rebuilds buckets, uploads the
147
- Storage files back and reconciles every one against the target.
148
-
149
- More: https://backupdrill.com/docs/restore
328
+ ${cliSection}More: https://backupdrill.com/docs/restore
150
329
  `;
151
330
  }