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/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);超限如实记录
@@ -649,6 +650,21 @@ export async function drillDump(dumpPath, manifest, snapshot, preChecks = [], op
649
650
  };
650
651
  if (orphaned.length)
651
652
  report.orphanedForeignKeys = orphaned;
653
+ // Auth 附加校验:结论(pass)上面已经定了,这里只往报告里加一节。它在同一个沙箱里补外键、
654
+ // 建触发器、模拟注册——放在所有正式检查之后,不影响它们;自己出错也只记在这一节里
655
+ const authSection = await authDrillSection(pg.connString, manifest, dumpPath, opts.authDump, opts.stopAuthDownload, {
656
+ // 托管 worker 在这一步前后换磁盘守卫的规则:Auth 阶段吃紧只叫停这一节,不判演练失败
657
+ begin: opts.supervision ? () => opts.supervision.observe({ phase: "auth" }) : undefined,
658
+ stop: opts.supervision?.authStop,
659
+ });
660
+ if (authSection) {
661
+ report.auth = authSection;
662
+ const line = `Auth users: ${authSection.summary}`;
663
+ if (authSection.status === "verified")
664
+ log.ok(line);
665
+ else
666
+ log.warn(line);
667
+ }
652
668
  if (opts.keepSandboxOnFailure && !pass) {
653
669
  // 写进报告让 --keep 可被脚本消费(拿连接串排查),不只靠人眼看日志
654
670
  report.keptSandbox = { containerId: pg.containerId, connString: pg.connString };
@@ -690,6 +706,7 @@ export async function runDrill(config, opts = {}) {
690
706
  const workdir = opts.supervision?.workdir ?? await mkdtemp(join(tmpdir(), "backupdrill-"));
691
707
  const dumpPath = join(workdir, "dump.pgcustom");
692
708
  // 下载的 dump 在这里;托管模式的目录归 supervisor 管
709
+ const authDownloadStop = new AbortController();
693
710
  const forgetWorkdir = opts.supervision
694
711
  ? () => { }
695
712
  : onInterrupt(() => rm(workdir, { recursive: true, force: true }).catch(() => { }));
@@ -731,13 +748,32 @@ export async function runDrill(config, opts = {}) {
731
748
  detail: "the manifest lists Storage files, but this snapshot location cannot hold them",
732
749
  });
733
750
  }
751
+ // 快照带 Auth 用户:在后台把 auth.dump 取下来给附加校验用,和正式演练同时进行、不让它等。
752
+ // 取不到只记进报告的 Auth 一节
753
+ let authDump;
754
+ if (manifest.auth?.status === "included" && (opts.authCheck ?? !opts.supervision)) {
755
+ const authPath = join(workdir, "auth.dump");
756
+ const download = reader.downloadAuthDump;
757
+ const stopAuthDownload = authDownloadStop;
758
+ // 下载出错的原文不进报告(里面可能有凭据、对象键之类),只给固定的说法;
759
+ // 同步抛出的错误也在这个 Promise 里接住,绝不冒到演练本身
760
+ authDump = download
761
+ ? Promise.resolve()
762
+ .then(() => download.call(reader, manifest, authPath, { signal: stopAuthDownload.signal }))
763
+ .then(() => ({ path: authPath }), () => ({ error: "the Auth archive couldn't be downloaded" }))
764
+ : Promise.resolve({ error: "this snapshot location can't read the Auth archive" });
765
+ }
734
766
  return await drillDump(dumpPath, manifest, snapshot, preChecks, {
735
767
  appCheckCommand: opts.appCheckCommand,
736
768
  keepSandboxOnFailure: opts.keepSandboxOnFailure,
737
769
  supervision: opts.supervision,
770
+ authDump,
771
+ stopAuthDownload: () => authDownloadStop.abort(),
738
772
  });
739
773
  }
740
774
  finally {
775
+ // 演练怎么结束都一样:还在下的 auth.dump 立刻停掉,不留着连接把进程拖住
776
+ authDownloadStop.abort();
741
777
  if (!opts.supervision)
742
778
  await rm(workdir, { recursive: true, force: true }).catch(() => { });
743
779
  forgetWorkdir();
@@ -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/grants.d.ts CHANGED
@@ -25,8 +25,32 @@ export interface GrantRestore {
25
25
  /** 处理过的对象数 */
26
26
  objects: number;
27
27
  }
28
+ /**
29
+ * 一次读取里的一个对象,带上它在这个库里的身份(oid;列是表的 oid 加 attnum)。
30
+ * 只在备份端比较转储前后两次读取时用,不进 manifest:换个库 oid 就不一样了。
31
+ */
32
+ export interface IdentifiedGrants {
33
+ identity: string;
34
+ object: GrantedObject;
35
+ }
28
36
  /** 备份端:读源库里这几个 schema 下每个对象给 PUBLIC 和 API 角色的授权。 */
29
37
  export declare function captureGrants(client: Client, schemas: string[]): Promise<GrantedObject[]>;
38
+ /** 同 captureGrants,另带每个对象的身份,供 grantsHeldThroughout 比较前后两次读取。 */
39
+ export declare function captureIdentifiedGrants(client: Client, schemas: string[]): Promise<IdentifiedGrants[]>;
40
+ /**
41
+ * 备份端:转储前后各读一次授权,只记两次都有的。
42
+ *
43
+ * 为什么要读两次:授权读不进 pg_dump 的快照(共用快照会拉长 TRUNCATE 的竞态窗口,函数体也不按
44
+ * 快照读),只读一次,转储期间的授权变动总有一个方向会出错。转储后读:先抹掉私有表里的数据、
45
+ * 再开放给 anon,转储里是抹之前的数据,记下的却是"开放",恢复出来 anon 就能读到原始数据。
46
+ * 转储前读:先收回授权、再写进敏感数据,同样会开放出去。两次都有的权限,转储开始前和结束后都
47
+ * 开着,拿它配转储里的数据不会比源库开得更多;只有中途收回、写进数据、抹掉、再开放这种来回漏得过去。
48
+ * 比的是同一个对象,不只是同名:两次读之间删掉重建的表(oid 变了)、删掉重加的列(attnum 变了),
49
+ * 转储里是新对象的数据,旧对象的授权不能算到它头上,按转储期间新建处理(交叉审查 2026-10-31)。
50
+ * 代价:转储期间新开放的权限要等下一次备份才记上,在那之前恢复,应用对这些对象会报 42501。
51
+ * 转储期间新建的对象(转储前没有)记成没有授权;转储期间删掉的不记,恢复端同样按没有授权处理。
52
+ */
53
+ export declare function grantsHeldThroughout(before: IdentifiedGrants[], after: IdentifiedGrants[]): GrantedObject[];
30
54
  /**
31
55
  * 把一组对象的授权写成 SQL:schema、表、序列、函数先清掉这几个角色的全部权限再照记录授,
32
56
  * 列级授权放在最后(清表权限会连带清掉列权限)。schema 也要清:源库可能靠不给 USAGE 把整个
@@ -66,7 +90,7 @@ export declare function grantsCheck(outcome: GrantRestore, context: "drill" | "r
66
90
  * 再把各 schema 下每个 schema、表、序列、函数上 PUBLIC 和三个角色的权限全部收走(扩展自带的对象不碰)、
67
91
  * 回读确认收干净,最后逐条授回记录里的。授不上的(对象、列或参数类型不在这次恢复里)跳过并告警、不中断:
68
92
  * 授权只会加权限,跳过一条最多让应用少一点访问,不会把该关的打开。前面几步出错就整段回滚、报错。
69
- * 授权是在转储完之后读的:两次读之间删掉的对象在转储里、不在记录里,只按记录逐个收权就会漏掉它,
93
+ * 2.9.0/2.9.1 的授权是在转储完之后读的:两次读之间删掉的对象在转储里、不在记录里,只按记录逐个收权就会漏掉它,
70
94
  * 它会带着默认的 PUBLIC 执行权恢复出来(交叉审查 2026-10-31);反过来,之间新加的对象(列)在记录里、
71
95
  * 不在转储里,直接授权会报错,在 Supabase 的 SQL 编辑器里整段回滚。所以整段放进一个 DO 块。
72
96
  * 旧快照没有记录,给 Supabase 以前的默认授权。
package/dist/grants.js CHANGED
@@ -27,10 +27,10 @@ const CATALOG_OBJECTS_SQL = `
27
27
  ),
28
28
  objects as (
29
29
  select case when relkind = 'S' then 'sequence' else 'table' end as kind,
30
- schema, name, null::text as column_name, null::text as args, acl
30
+ schema, name, null::text as column_name, null::text as args, oid::text as identity, acl
31
31
  from relations
32
32
  union all
33
- select 'column', r.schema, r.name, a.attname::text, null, a.attacl
33
+ select 'column', r.schema, r.name, a.attname::text, null, r.oid::text || '.' || a.attnum::text, a.attacl
34
34
  from relations r
35
35
  join pg_catalog.pg_attribute a on a.attrelid = r.oid
36
36
  where a.attnum > 0 and not a.attisdropped and a.attacl is not null
@@ -39,6 +39,7 @@ const CATALOG_OBJECTS_SQL = `
39
39
  select 'routine', n.nspname::text, p.proname::text, null,
40
40
  case when p.prokind = 'a' then pg_catalog.oidvectortypes(p.proargtypes)
41
41
  else pg_catalog.pg_get_function_identity_arguments(p.oid) end,
42
+ p.oid::text,
42
43
  coalesce(p.proacl, pg_catalog.acldefault('f', p.proowner))
43
44
  from pg_catalog.pg_proc p
44
45
  join pg_catalog.pg_namespace n on n.oid = p.pronamespace
@@ -46,25 +47,25 @@ const CATALOG_OBJECTS_SQL = `
46
47
  and not exists (select 1 from pg_catalog.pg_depend d
47
48
  where d.classid = 'pg_catalog.pg_proc'::pg_catalog.regclass and d.objid = p.oid and d.deptype = 'e')
48
49
  union all
49
- select 'schema', n.nspname::text, null, null, null, coalesce(n.nspacl, pg_catalog.acldefault('n', n.nspowner))
50
+ select 'schema', n.nspname::text, null, null, null, n.oid::text, coalesce(n.nspacl, pg_catalog.acldefault('n', n.nspowner))
50
51
  from pg_catalog.pg_namespace n
51
52
  where n.nspname = any($1::text[])
52
53
  )
53
- select o.kind, o.schema, o.name, o.column_name, o.args, r.role,
54
+ select o.kind, o.schema, o.name, o.column_name, o.args, r.role, o.identity,
54
55
  -- distinct:同一权限可以由几个授权人各给一次,ACL 里就有几条
55
56
  pg_catalog.array_agg(distinct x.privilege_type::text order by x.privilege_type::text) filter (where r.role is not null) as privileges
56
57
  from objects o
57
58
  left join lateral pg_catalog.aclexplode(o.acl) x on true
58
59
  left join api_roles r on r.oid = x.grantee
59
- group by 1, 2, 3, 4, 5, 6
60
+ group by 1, 2, 3, 4, 5, 6, 7
60
61
  order by 1, 2, 3, 4, 5, 6`;
61
62
  function objectKey(o) {
62
63
  return JSON.stringify([o.kind, o.schema, o.name ?? null, o.column ?? null, o.args ?? null]);
63
64
  }
64
65
  /** 在已开的事务里调用:search_path 必须为空(见 CATALOG_OBJECTS_SQL)。 */
65
- async function catalogObjects(client, schemas) {
66
+ async function catalogEntries(client, schemas) {
66
67
  const res = await client.query(CATALOG_OBJECTS_SQL, [schemas, [...API_ROLES]]);
67
- const objects = new Map();
68
+ const entries = new Map();
68
69
  for (const row of res.rows) {
69
70
  const object = {
70
71
  kind: row.kind,
@@ -75,13 +76,16 @@ async function catalogObjects(client, schemas) {
75
76
  privileges: {},
76
77
  };
77
78
  const key = objectKey(object);
78
- const existing = objects.get(key) ?? object;
79
- objects.set(key, existing);
79
+ const existing = entries.get(key) ?? { identity: row.identity, object };
80
+ entries.set(key, existing);
80
81
  if (row.role && row.privileges?.length)
81
- existing.privileges[row.role] = row.privileges;
82
+ existing.object.privileges[row.role] = row.privileges;
82
83
  }
83
84
  // 列级授权只给别的角色时,这一列对我们没有意义
84
- return [...objects.values()].filter((o) => o.kind !== "column" || Object.keys(o.privileges).length > 0);
85
+ return [...entries.values()].filter(({ object }) => object.kind !== "column" || Object.keys(object.privileges).length > 0);
86
+ }
87
+ async function catalogObjects(client, schemas) {
88
+ return (await catalogEntries(client, schemas)).map((entry) => entry.object);
85
89
  }
86
90
  async function withEmptySearchPath(client, work) {
87
91
  await client.query("begin");
@@ -100,6 +104,42 @@ async function withEmptySearchPath(client, work) {
100
104
  export async function captureGrants(client, schemas) {
101
105
  return withEmptySearchPath(client, () => catalogObjects(client, schemas));
102
106
  }
107
+ /** 同 captureGrants,另带每个对象的身份,供 grantsHeldThroughout 比较前后两次读取。 */
108
+ export async function captureIdentifiedGrants(client, schemas) {
109
+ return withEmptySearchPath(client, () => catalogEntries(client, schemas));
110
+ }
111
+ /**
112
+ * 备份端:转储前后各读一次授权,只记两次都有的。
113
+ *
114
+ * 为什么要读两次:授权读不进 pg_dump 的快照(共用快照会拉长 TRUNCATE 的竞态窗口,函数体也不按
115
+ * 快照读),只读一次,转储期间的授权变动总有一个方向会出错。转储后读:先抹掉私有表里的数据、
116
+ * 再开放给 anon,转储里是抹之前的数据,记下的却是"开放",恢复出来 anon 就能读到原始数据。
117
+ * 转储前读:先收回授权、再写进敏感数据,同样会开放出去。两次都有的权限,转储开始前和结束后都
118
+ * 开着,拿它配转储里的数据不会比源库开得更多;只有中途收回、写进数据、抹掉、再开放这种来回漏得过去。
119
+ * 比的是同一个对象,不只是同名:两次读之间删掉重建的表(oid 变了)、删掉重加的列(attnum 变了),
120
+ * 转储里是新对象的数据,旧对象的授权不能算到它头上,按转储期间新建处理(交叉审查 2026-10-31)。
121
+ * 代价:转储期间新开放的权限要等下一次备份才记上,在那之前恢复,应用对这些对象会报 42501。
122
+ * 转储期间新建的对象(转储前没有)记成没有授权;转储期间删掉的不记,恢复端同样按没有授权处理。
123
+ */
124
+ export function grantsHeldThroughout(before, after) {
125
+ const readBefore = new Map(before.map((entry) => [objectKey(entry.object), entry]));
126
+ const held = [];
127
+ for (const { identity, object } of after) {
128
+ const previous = readBefore.get(objectKey(object));
129
+ const earlier = previous?.identity === identity ? previous.object.privileges : {};
130
+ const privileges = {};
131
+ for (const role of GRANT_ROLES) {
132
+ const inBoth = (object.privileges[role] ?? []).filter((privilege) => earlier[role]?.includes(privilege));
133
+ if (inBoth.length > 0)
134
+ privileges[role] = inBoth;
135
+ }
136
+ // 和 catalogObjects 一样,列只在有授权时记
137
+ if (object.kind === "column" && Object.keys(privileges).length === 0)
138
+ continue;
139
+ held.push({ ...object, privileges });
140
+ }
141
+ return held;
142
+ }
103
143
  function quoteIdent(name) {
104
144
  return `"${name.replace(/"/g, '""')}"`;
105
145
  }
@@ -188,7 +228,7 @@ export async function restoreGrants(client, opts) {
188
228
  }
189
229
  else {
190
230
  const recorded = new Map(opts.recorded.map((o) => [objectKey(o), o]));
191
- // 授权在转储之后才读,转储期间新加的列不在归档里:只处理目标上真有的列
231
+ // 2.9.0/2.9.1 的授权在转储之后才读,转储期间新加的列在记录里、不在归档里:只处理目标上真有的列
192
232
  const columns = await targetColumns(client, opts.schemas);
193
233
  planned = [
194
234
  // 目标上的 schema、表、序列、函数都要过一遍:记录里没有的按"源库没给授权"处理
@@ -296,7 +336,7 @@ function sqlLiteral(value) {
296
336
  * 再把各 schema 下每个 schema、表、序列、函数上 PUBLIC 和三个角色的权限全部收走(扩展自带的对象不碰)、
297
337
  * 回读确认收干净,最后逐条授回记录里的。授不上的(对象、列或参数类型不在这次恢复里)跳过并告警、不中断:
298
338
  * 授权只会加权限,跳过一条最多让应用少一点访问,不会把该关的打开。前面几步出错就整段回滚、报错。
299
- * 授权是在转储完之后读的:两次读之间删掉的对象在转储里、不在记录里,只按记录逐个收权就会漏掉它,
339
+ * 2.9.0/2.9.1 的授权是在转储完之后读的:两次读之间删掉的对象在转储里、不在记录里,只按记录逐个收权就会漏掉它,
300
340
  * 它会带着默认的 PUBLIC 执行权恢复出来(交叉审查 2026-10-31);反过来,之间新加的对象(列)在记录里、
301
341
  * 不在转储里,直接授权会报错,在 Supabase 的 SQL 编辑器里整段回滚。所以整段放进一个 DO 块。
302
342
  * 旧快照没有记录,给 Supabase 以前的默认授权。
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;