backupdrill 2.9.0 → 2.9.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -223,11 +223,11 @@ supabase-js and the other client libraries reach your tables through the Data AP
223
223
 
224
224
  The dump doesn't carry grants, so a restored table only gets what the target project hands out by default. Supabase used to grant every new table in `public` to all three roles. It stopped doing that for new projects on May 30, 2026, and for existing projects on October 30, 2026 ([Supabase's announcement](https://github.com/orgs/supabase/discussions/45329)). On a project that has switched, a plain `pg_restore` brings back every table and row, and the app still gets `42501` on all of them. On a project that hasn't switched yet, it does the opposite: every restored table is open to `anon`, including the ones you had closed.
225
225
 
226
- So each backup also records, in `manifest.json` under `database.grants`, what `anon`, `authenticated`, `service_role` and `PUBLIC` were granted on every table, view, sequence and function in the backed-up schemas (column-level grants and schema `USAGE` included). After the data is in, `restore` and `drill` take those four roles off every restored object and grant back exactly what the source had, whatever the target's defaults are, then read the grants back to check they took. Objects that belong to an extension are left alone. The report has an `API grants` line. `pg_restore` runs in its own process, so the grants can't go into its transaction: for the moment between its commit and the grants, the restored objects have the target's defaults. If setting the grants fails, `restore` tries to revoke those roles' access to the restored objects instead. If that works, your app gets `42501` until you grant what it needs; if it fails too, the error tells you to check the target's default grants before the app goes live.
226
+ So each backup also records, in `manifest.json` under `database.grants`, what `anon`, `authenticated`, `service_role` and `PUBLIC` were granted on every table, view, sequence and function in the backed-up schemas (column-level grants and schema `USAGE` included). It reads them right before and right after the dump and keeps only the grants both reads agree on, for objects that weren't dropped and recreated in between. A grant added or removed while the dump runs is left off until the next backup. One taken away and given back during the dump looks unchanged to both reads, so it is kept. After the data is in, `restore` and `drill` take those four roles off every restored object and grant back exactly what the source had, whatever the target's defaults are, then read the grants back to check they took. Objects that belong to an extension are left alone. The report has an `API grants` line. `pg_restore` runs in its own process, so the grants can't go into its transaction: for the moment between its commit and the grants, the restored objects have the target's defaults. If setting the grants fails, `restore` tries to revoke those roles' access to the restored objects instead. If that works, your app gets `42501` until you grant what it needs; if it fails too, the error tells you to check the target's default grants before the app goes live.
227
227
 
228
228
  Snapshots taken before 2.9.0 have no record. Restoring one of those, the CLI gives the three roles Supabase's old default access to every table, sequence and function in `public`, which is what those projects had unless you revoked it, and the `API grants` line says so. Revoke it on anything you had kept private. For tables in your own schemas, the CLI leaves the target's default grants as they are.
229
229
 
230
- By hand, to get back Supabase's old defaults in `public` (then revoke on the tables you keep private):
230
+ Restoring by hand, set the grants after `pg_restore`. A snapshot made with 2.9.1 or later has the SQL in its `RECOVERY.md`: one `do` block that does what `restore` does. It takes those roles off everything the restore created, grants back what the source had, and skips with a warning any grant whose object isn't there. 2.9.0 wrote a revoke and the grants for each recorded object instead, which misses objects that changed while the backup ran, so restore those snapshots with `backupdrill restore`. Snapshots from before 2.9.0 have no record: run this to give the three roles Supabase's old defaults in `public`, then revoke on the tables you keep private:
231
231
 
232
232
  ```sql
233
233
  grant all on all tables in schema public to anon, authenticated, service_role;
package/dist/backup.js CHANGED
@@ -11,7 +11,7 @@ import { log } from "./log.js";
11
11
  import { TOOL_VERSION } from "./version.js";
12
12
  import { parsePgDumpMajor } from "./pgbin.js";
13
13
  import { relationBytes } from "./estimate.js";
14
- import { captureGrants } from "./grants.js";
14
+ import { captureIdentifiedGrants, grantsHeldThroughout } from "./grants.js";
15
15
  // 解析函数搬到了 pgbin(演练与恢复都要读 pg_restore 版本,放这里会成环);保留旧出口
16
16
  export { parsePgDumpMajor };
17
17
  import { dumpUrlFor, connectPg, isSupabaseHost } from "./supabase-ca.js";
@@ -94,7 +94,7 @@ async function inspectDatabase(databaseUrl, schemas) {
94
94
  async function readGrants(databaseUrl, schemas) {
95
95
  const client = await connectPg(databaseUrl);
96
96
  try {
97
- return await captureGrants(client, schemas);
97
+ return await captureIdentifiedGrants(client, schemas);
98
98
  }
99
99
  finally {
100
100
  await client.end();
@@ -199,13 +199,14 @@ export async function runBackup(config, opts = {}) {
199
199
  throw new Error("Storage file backup needs an S3-compatible bucket; this backup destination only holds the database.");
200
200
  }
201
201
  const dumpKey = writer.dumpKey;
202
+ // 授权在转储前后各读一次,只记两次都有的(为什么见 grantsHeldThroughout)。
203
+ // 哪次读不到都让备份失败,不留一份缺授权记录的快照:恢复端把"没有记录"当成 2.9.0 之前的旧快照,
204
+ // 按 Supabase 以前的默认授权开放 public,会把源库关着的表打开
205
+ const grantsBeforeDump = await readGrants(config.databaseUrl, config.schemas);
202
206
  log.step(`Dumping → ${writer.describe("dump.pgcustom")}`);
203
207
  const { bytes, sha256 } = await dumpToSnapshot(config, writer, pgDumpBin, db.relationBytes);
204
208
  log.ok(`Database dumped (${(bytes / 1024 / 1024).toFixed(1)} MB, sha256 ${sha256.slice(0, 12)}…)`);
205
- // 授权在转储之后读:转储期间有人收回权限,记下的是收回之后的,不会拿旧的开放授权去配新数据。
206
- // 读不到就让备份失败,不留一份缺授权记录的快照:恢复端把"没有记录"当成 2.9.0 之前的旧快照,
207
- // 按 Supabase 以前的默认授权开放 public,会把源库关着的表打开
208
- const grants = await readGrants(config.databaseUrl, config.schemas);
209
+ const grants = grantsHeldThroughout(grantsBeforeDump, await readGrants(config.databaseUrl, config.schemas));
209
210
  // Storage 文件同步(源配置存在才做;否则只备数据库)
210
211
  let storageResult = null;
211
212
  if (config.supabaseStorage && storageFiles) {
package/dist/grants.d.ts CHANGED
@@ -25,17 +25,43 @@ 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 把整个
33
57
  * schema 关起来,目标上的 public 却是 Supabase 默认开放的。
34
- * roles:目标上实际存在的角色(PUBLIC 恒在);maintain:目标是否认 MAINTAIN。
58
+ * roles:目标上实际存在的角色(PUBLIC 恒在);maintain:目标是否认 MAINTAIN;
59
+ * revoke: false = 只出授权语句(RECOVERY.md 的清权限按目标目录来,见 recoveryGrantsSql)。
35
60
  */
36
61
  export declare function grantStatements(objects: GrantedObject[], opts: {
37
62
  roles: readonly GrantRole[];
38
63
  maintain: boolean;
64
+ revoke?: boolean;
39
65
  }): string[];
40
66
  /**
41
67
  * 恢复端:在恢复出来的对象上照记录重建授权,一个事务内完成,提交前回读目录核对。
@@ -59,8 +85,21 @@ export declare function grantsCheck(outcome: GrantRestore, context: "drill" | "r
59
85
  detail: string;
60
86
  };
61
87
  /**
62
- * RECOVERY.md 手工恢复那一步的 SQL(CLI 的 S3 版和 worker 的 Drive 版共用)。有记录就逐个对象照记录重建,
63
- * 和 restoreGrants 同一套语句;旧快照没有记录,给 Supabase 以前的默认授权。
88
+ * RECOVERY.md 手工恢复那一步的 SQL(CLI 的 S3 版和 worker 的 Drive 版共用),做法和 restoreGrants 一样:
89
+ * 按恢复后的目录,先确认执行的角色是这些对象的属主(不是属主时 GRANT/REVOKE 只告警、不生效或只生效一半),
90
+ * 再把各 schema 下每个 schema、表、序列、函数上 PUBLIC 和三个角色的权限全部收走(扩展自带的对象不碰)、
91
+ * 回读确认收干净,最后逐条授回记录里的。授不上的(对象、列或参数类型不在这次恢复里)跳过并告警、不中断:
92
+ * 授权只会加权限,跳过一条最多让应用少一点访问,不会把该关的打开。前面几步出错就整段回滚、报错。
93
+ * 2.9.0/2.9.1 的授权是在转储完之后读的:两次读之间删掉的对象在转储里、不在记录里,只按记录逐个收权就会漏掉它,
94
+ * 它会带着默认的 PUBLIC 执行权恢复出来(交叉审查 2026-10-31);反过来,之间新加的对象(列)在记录里、
95
+ * 不在转储里,直接授权会报错,在 Supabase 的 SQL 编辑器里整段回滚。所以整段放进一个 DO 块。
96
+ * 旧快照没有记录,给 Supabase 以前的默认授权。
64
97
  * MAINTAIN 只会出现在 PG17+ 源库的记录里,而恢复目标的版本不低于源库,所以照写。
98
+ *
99
+ * 2.9.0 收的是授权数组(旧快照传 undefined),照旧接受:记录里每个备份的 schema 都有一条 schema 条目,
100
+ * 范围从它取。
65
101
  */
66
- export declare function recoveryGrantsSql(grants: GrantedObject[] | undefined): string;
102
+ export declare function recoveryGrantsSql(database: {
103
+ schemas: string[];
104
+ grants?: GrantedObject[];
105
+ } | GrantedObject[] | undefined): string;
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
  }
@@ -126,7 +166,8 @@ function roleName(role) {
126
166
  * 把一组对象的授权写成 SQL:schema、表、序列、函数先清掉这几个角色的全部权限再照记录授,
127
167
  * 列级授权放在最后(清表权限会连带清掉列权限)。schema 也要清:源库可能靠不给 USAGE 把整个
128
168
  * schema 关起来,目标上的 public 却是 Supabase 默认开放的。
129
- * roles:目标上实际存在的角色(PUBLIC 恒在);maintain:目标是否认 MAINTAIN。
169
+ * roles:目标上实际存在的角色(PUBLIC 恒在);maintain:目标是否认 MAINTAIN;
170
+ * revoke: false = 只出授权语句(RECOVERY.md 的清权限按目标目录来,见 recoveryGrantsSql)。
130
171
  */
131
172
  export function grantStatements(objects, opts) {
132
173
  const roles = GRANT_ROLES.filter((role) => opts.roles.includes(role));
@@ -134,7 +175,7 @@ export function grantStatements(objects, opts) {
134
175
  const statements = [];
135
176
  const columns = [];
136
177
  for (const o of objects) {
137
- if (o.kind !== "column") {
178
+ if (o.kind !== "column" && opts.revoke !== false) {
138
179
  statements.push(`revoke all on ${objectClause(o)} from ${revokeFrom}`);
139
180
  }
140
181
  for (const role of roles) {
@@ -187,7 +228,7 @@ export async function restoreGrants(client, opts) {
187
228
  }
188
229
  else {
189
230
  const recorded = new Map(opts.recorded.map((o) => [objectKey(o), o]));
190
- // 授权在转储之后才读,转储期间新加的列不在归档里:只处理目标上真有的列
231
+ // 2.9.0/2.9.1 的授权在转储之后才读,转储期间新加的列在记录里、不在归档里:只处理目标上真有的列
191
232
  const columns = await targetColumns(client, opts.schemas);
192
233
  planned = [
193
234
  // 目标上的 schema、表、序列、函数都要过一遍:记录里没有的按"源库没给授权"处理
@@ -278,19 +319,135 @@ export function grantsCheck(outcome, context) {
278
319
  `service_role ${legacyScope}. Newer backups record the grants`,
279
320
  };
280
321
  }
322
+ /** 选一个不出现在任何内容里的 dollar-quote 标签,内容原样放进去不用转义。 */
323
+ function dollarQuoteTag(base, contents) {
324
+ for (let i = 0;; i++) {
325
+ const tag = `$${base}${i || ""}$`;
326
+ if (!contents.some((text) => text.includes(tag)))
327
+ return tag;
328
+ }
329
+ }
330
+ function sqlLiteral(value) {
331
+ return `'${value.replace(/'/g, "''")}'`;
332
+ }
281
333
  /**
282
- * RECOVERY.md 手工恢复那一步的 SQL(CLI 的 S3 版和 worker 的 Drive 版共用)。有记录就逐个对象照记录重建,
283
- * 和 restoreGrants 同一套语句;旧快照没有记录,给 Supabase 以前的默认授权。
334
+ * RECOVERY.md 手工恢复那一步的 SQL(CLI 的 S3 版和 worker 的 Drive 版共用),做法和 restoreGrants 一样:
335
+ * 按恢复后的目录,先确认执行的角色是这些对象的属主(不是属主时 GRANT/REVOKE 只告警、不生效或只生效一半),
336
+ * 再把各 schema 下每个 schema、表、序列、函数上 PUBLIC 和三个角色的权限全部收走(扩展自带的对象不碰)、
337
+ * 回读确认收干净,最后逐条授回记录里的。授不上的(对象、列或参数类型不在这次恢复里)跳过并告警、不中断:
338
+ * 授权只会加权限,跳过一条最多让应用少一点访问,不会把该关的打开。前面几步出错就整段回滚、报错。
339
+ * 2.9.0/2.9.1 的授权是在转储完之后读的:两次读之间删掉的对象在转储里、不在记录里,只按记录逐个收权就会漏掉它,
340
+ * 它会带着默认的 PUBLIC 执行权恢复出来(交叉审查 2026-10-31);反过来,之间新加的对象(列)在记录里、
341
+ * 不在转储里,直接授权会报错,在 Supabase 的 SQL 编辑器里整段回滚。所以整段放进一个 DO 块。
342
+ * 旧快照没有记录,给 Supabase 以前的默认授权。
284
343
  * MAINTAIN 只会出现在 PG17+ 源库的记录里,而恢复目标的版本不低于源库,所以照写。
344
+ *
345
+ * 2.9.0 收的是授权数组(旧快照传 undefined),照旧接受:记录里每个备份的 schema 都有一条 schema 条目,
346
+ * 范围从它取。
285
347
  */
286
- export function recoveryGrantsSql(grants) {
287
- if (grants === undefined) {
348
+ export function recoveryGrantsSql(database) {
349
+ const recorded = Array.isArray(database) ? database : database?.grants;
350
+ if (recorded === undefined) {
288
351
  return [
289
352
  "grant all on all tables in schema public to anon, authenticated, service_role;",
290
353
  "grant all on all sequences in schema public to anon, authenticated, service_role;",
291
354
  "grant execute on all functions in schema public to anon, authenticated, service_role;",
292
355
  ].join("\n");
293
356
  }
294
- const statements = grantStatements(grants, { roles: GRANT_ROLES, maintain: true });
295
- return statements.length ? statements.map((s) => `${s};`).join("\n") : "-- (nothing to grant in this snapshot)";
357
+ const schemaNames = Array.isArray(database) ? [...new Set(database.map((g) => g.schema))] : database.schemas;
358
+ const grants = grantStatements(recorded, { roles: GRANT_ROLES, maintain: true, revoke: false });
359
+ const inner = dollarQuoteTag("g", grants);
360
+ const outer = dollarQuoteTag("grants", [...grants, ...schemaNames, inner]);
361
+ const schemas = `array[${schemaNames.map(sqlLiteral).join(", ")}]::text[]`;
362
+ const grantArray = grants.length
363
+ ? `array[\n${grants.map((g) => ` ${inner}${g}${inner}`).join(",\n")}\n ]`
364
+ : "array[]::text[]";
365
+ const notFromExtension = (catalog, alias) => `not exists (select 1 from pg_catalog.pg_depend d where d.classid = '${catalog}'::pg_catalog.regclass ` +
366
+ `and d.objid = ${alias}.oid and d.deptype = 'e')`;
367
+ const from = "public, anon, authenticated, service_role";
368
+ // 恢复出来的对象(扩展自带的除外):名字、收权语句(列没有,清表权限会连带清掉)、属主、当前 ACL。
369
+ // 下面三处都用它,每次现查
370
+ const restoredObjects = `
371
+ select pg_catalog.format('schema %I', n.nspname) as object,
372
+ pg_catalog.format('revoke all on schema %I from ${from}', n.nspname) as revoke_sql,
373
+ n.nspowner as owner,
374
+ coalesce(n.nspacl, pg_catalog.acldefault('n', n.nspowner)) as acl
375
+ from pg_catalog.pg_namespace n
376
+ where n.nspname = any (${schemas})
377
+ union all
378
+ select pg_catalog.format('%I.%I', n.nspname, c.relname),
379
+ pg_catalog.format('revoke all on %s %I.%I from ${from}',
380
+ case when c.relkind = 'S' then 'sequence' else 'table' end, n.nspname, c.relname),
381
+ c.relowner,
382
+ coalesce(c.relacl, pg_catalog.acldefault(case when c.relkind = 'S' then 's' else 'r' end::"char", c.relowner))
383
+ from pg_catalog.pg_class c
384
+ join pg_catalog.pg_namespace n on n.oid = c.relnamespace
385
+ where n.nspname = any (${schemas})
386
+ and c.relkind in ('r', 'p', 'v', 'm', 'f', 'S')
387
+ and ${notFromExtension("pg_catalog.pg_class", "c")}
388
+ union all
389
+ select pg_catalog.format('%I.%I.%I', n.nspname, c.relname, a.attname), null, c.relowner, a.attacl
390
+ from pg_catalog.pg_attribute a
391
+ join pg_catalog.pg_class c on c.oid = a.attrelid
392
+ join pg_catalog.pg_namespace n on n.oid = c.relnamespace
393
+ where n.nspname = any (${schemas})
394
+ and a.attnum > 0 and not a.attisdropped and a.attacl is not null
395
+ and ${notFromExtension("pg_catalog.pg_class", "c")}
396
+ union all
397
+ select pg_catalog.format('%I.%I(%s)', n.nspname, p.proname, sig.args),
398
+ pg_catalog.format('revoke all on routine %I.%I(%s) from ${from}', n.nspname, p.proname, sig.args),
399
+ p.proowner,
400
+ coalesce(p.proacl, pg_catalog.acldefault('f', p.proowner))
401
+ from pg_catalog.pg_proc p
402
+ join pg_catalog.pg_namespace n on n.oid = p.pronamespace
403
+ cross join lateral (
404
+ select case when p.prokind = 'a' then pg_catalog.oidvectortypes(p.proargtypes)
405
+ else pg_catalog.pg_get_function_identity_arguments(p.oid) end as args
406
+ ) sig
407
+ where n.nspname = any (${schemas})
408
+ and ${notFromExtension("pg_catalog.pg_proc", "p")}`;
409
+ return `do ${outer}
410
+ declare
411
+ statement text;
412
+ problem text;
413
+ begin
414
+ perform pg_catalog.set_config('search_path', '', true);
415
+ -- 0. Run as the role that owns what the restore created: for anyone else, GRANT and REVOKE
416
+ -- only warn and change nothing, or only part of it
417
+ select pg_catalog.string_agg(o.object, ', ') into problem
418
+ from (${restoredObjects}
419
+ ) o
420
+ where not pg_catalog.pg_has_role(current_user, o.owner, 'USAGE');
421
+ if problem is not null then
422
+ raise exception 'run this as the role that ran pg_restore, which owns the restored objects; % does not own: %',
423
+ current_user, pg_catalog.left(problem, 500);
424
+ end if;
425
+ -- 1. Take PUBLIC, anon, authenticated and service_role off everything the restore created
426
+ -- (objects that belong to an extension are left alone), then check nothing is left
427
+ for statement in select o.revoke_sql from (${restoredObjects}
428
+ ) o where o.revoke_sql is not null
429
+ loop
430
+ execute statement;
431
+ end loop;
432
+ select pg_catalog.string_agg(distinct o.object, ', ') into problem
433
+ from (${restoredObjects}
434
+ ) o
435
+ cross join lateral pg_catalog.aclexplode(o.acl) x
436
+ where x.grantee = 0
437
+ or x.grantee in (select r.oid from pg_catalog.pg_roles r where r.rolname in ('anon', 'authenticated', 'service_role'));
438
+ if problem is not null then
439
+ raise exception 'could not take access away on: %', pg_catalog.left(problem, 500);
440
+ end if;
441
+ -- 2. Grant back what the source had at backup time. A grant that fails (its object, column or
442
+ -- argument type isn't in this restore) is skipped with a warning: it can only leave less access
443
+ for statement in select pg_catalog.unnest(${grantArray})
444
+ loop
445
+ begin
446
+ execute statement;
447
+ exception when others then
448
+ raise warning 'not granted (%): %', sqlerrm, statement;
449
+ end;
450
+ end loop;
451
+ end
452
+ ${outer};`;
296
453
  }
@@ -111,14 +111,16 @@ it drops and recreates \`public\`, and the grants Supabase put on it go with it.
111
111
  5. Set the grants for \`anon\`, \`authenticated\` and \`service_role\`. The dump
112
112
  carries none. With Supabase's new defaults, supabase-js requests to restored
113
113
  tables in \`public\` fail with \`42501 permission denied\` until you grant access. ${db.grants
114
- ? `These statements put back exactly what the source had at backup time (also in
115
- manifest.json under \`database.grants\`):`
114
+ ? `Run this block in the SQL editor or psql. It first takes access away from
115
+ these roles (and \`PUBLIC\`) on everything the restore created, then grants back
116
+ what the source had at backup time (the same list is in manifest.json under
117
+ \`database.grants\`). A grant whose object isn't in this restore is skipped with a warning:`
116
118
  : `This snapshot was taken before BackupDrill recorded grants. The statements below
117
119
  give the three roles Supabase's old default access to everything in \`public\`;
118
120
  afterwards, revoke it on any table you had kept private:`}
119
121
 
120
122
  \`\`\`sql
121
- ${recoveryGrantsSql(db.grants)}
123
+ ${recoveryGrantsSql(db)}
122
124
  \`\`\`
123
125
 
124
126
  ## Restore Storage files
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "backupdrill",
3
- "version": "2.9.0",
3
+ "version": "2.9.2",
4
4
  "description": "Open-source CLI to back up a Supabase project — Postgres database and Storage files — to your own S3/R2/B2 bucket, with a checksummed manifest.",
5
5
  "type": "module",
6
6
  "bin": {
package/plugin/README.md CHANGED
@@ -7,7 +7,7 @@ Back up a Supabase project to a bucket you own and prove the backup restores, by
7
7
  - `drill` restores a snapshot into a throwaway Postgres in Docker, checks that the tables and their data came back, and checksums a sample of the Storage files.
8
8
  - `restore` puts a snapshot into a new, empty Supabase project, after a dry run and only once you confirm the target.
9
9
 
10
- The agent runs every command as `npx -y backupdrill@2.7.2`, so the CLI version stays fixed.
10
+ The agent runs every command as `npx -y backupdrill@2.9.2`, so the CLI version stays fixed.
11
11
 
12
12
  ## What you need
13
13
 
@@ -7,7 +7,7 @@ description: Use when the user wants to back up a Supabase project to their own
7
7
 
8
8
  backupdrill is an open-source (MIT) command-line tool. `backup` dumps the project's Postgres database with `pg_dump`, copies Storage files too once their S3 keys are set, and writes everything to a bucket the user owns, with a checksummed `manifest.json` and a `RECOVERY.md` in every snapshot. `drill` restores a snapshot into a throwaway Postgres in Docker and checks that it came back. The CLI runs on the user's machine. It talks to their Supabase project, their bucket and the local Docker daemon, and sends nothing to BackupDrill.
9
9
 
10
- Always run it as `npx -y backupdrill@2.7.2 <command>`, so every run uses the same version.
10
+ Always run it as `npx -y backupdrill@2.9.2 <command>`, so every run uses the same version.
11
11
 
12
12
  You need a shell on the user's machine for this. If you don't have one, walk the user through the same commands instead of running them.
13
13
 
@@ -69,7 +69,7 @@ Every backup reads the whole database, and every configured Storage file, out of
69
69
  ```sh
70
70
  ( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
71
71
  set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
72
- npx -y backupdrill@2.7.2 estimate --plan pro )
72
+ npx -y backupdrill@2.9.2 estimate --plan pro )
73
73
  ```
74
74
 
75
75
  Use `--plan free`, `pro` or `team` to match their Supabase plan, and read the projection back before suggesting a daily schedule. On a large database, suggest weekly.
@@ -80,12 +80,12 @@ Use `--plan free`, `pro` or `team` to match their Supabase plan, and read the pr
80
80
  report="$(mktemp "${TMPDIR:-/tmp}/backupdrill-backup.XXXXXX")" || exit 1; echo "stdout → $report"
81
81
  ( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
82
82
  set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
83
- npx -y backupdrill@2.7.2 backup ) > "$report"
83
+ npx -y backupdrill@2.9.2 backup ) > "$report"
84
84
  ```
85
85
 
86
86
  - The progress lines on stderr show where everything went (`Dumping → s3://…`, `Manifest written → s3://…`) and end with `Backup complete — N tables + M Storage files`. stdout goes to the file named on the first line, a new one each run that only the user can read: one line of JSON with the whole manifest, which lists every table and Storage file, so read only the fields you need from it.
87
87
  - Report the table count, the Storage file count (or that it was database only), and where the snapshot landed: `<prefix>/<project>/<timestamp>/` in their bucket, holding `dump.pgcustom`, `manifest.json`, `RECOVERY.md` and, with Storage keys set, `storage/`.
88
- - By default only the `public` schema is dumped (add their own schemas with `--schema`), so Supabase-managed schemas such as `auth` and `storage` aren't in it. Grants aren't either.
88
+ - By default only the `public` schema is dumped (add their own schemas with `--schema`), so Supabase-managed schemas such as `auth` and `storage` aren't in it. The dump has no grants; the manifest records what `anon`, `authenticated` and `service_role` were granted, and `restore` and `drill` set that back.
89
89
  - The CLI never deletes anything in the bucket. Old snapshots are cleaned up by the bucket's own lifecycle rules, if the user sets any.
90
90
 
91
91
  ## Prove the backup restores (drill)
@@ -93,7 +93,7 @@ report="$(mktemp "${TMPDIR:-/tmp}/backupdrill-backup.XXXXXX")" || exit 1; echo "
93
93
  ```sh
94
94
  ( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
95
95
  set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
96
- npx -y backupdrill@2.7.2 drill )
96
+ npx -y backupdrill@2.9.2 drill )
97
97
  ```
98
98
 
99
99
  - It reads the latest snapshot from the bucket, restores it into a throwaway Postgres container, runs its checks and removes the container. It doesn't connect to the Supabase project. The first run pulls a Postgres image from Docker Hub.
@@ -112,12 +112,12 @@ A restore writes data, so go step by step and let the user drive.
112
112
  ```sh
113
113
  ( set +x; unset DATABASE_URL $(env | sed -n 's/^\(BACKUPDRILL_[A-Za-z0-9_]*\)=.*/\1/p')
114
114
  set -a; . ./.env.backupdrill 2>/dev/null || { echo ".env.backupdrill could not be loaded" >&2; exit 1; }; set +a
115
- npx -y backupdrill@2.7.2 restore --database --target-supabase-url https://<target-ref>.supabase.co --dry-run )
115
+ npx -y backupdrill@2.9.2 restore --database --target-supabase-url https://<target-ref>.supabase.co --dry-run )
116
116
  ```
117
117
 
118
118
  Leave out `--target-supabase-url` when the snapshot is database only. To write Storage files to a local folder instead of the new project, use `--storage-dir ./recovered`.
119
119
  4. Show the dry-run result. It starts with `Dry run for snapshot <timestamp>`; note that timestamp. Run the real restore only after the user asks for it and gives you the target ref. Then replace `--dry-run` with `--snapshot <timestamp> --confirm-target <target-ref>`, using the timestamp from the dry run and exactly the ref they gave, so a backup that lands in between can't change what gets restored. Send stdout to a new `mktemp` file the same way as `backup` (with `backupdrill-restore.XXXXXX` as the name): the JSON result can be long. If the user wants an older snapshot, pass `--snapshot` to both runs.
120
- 5. Tell them what a restore doesn't bring back: Auth users, secret values, Edge Functions and grants. They need to set those up again. The snapshot's `RECOVERY.md` has a "Not covered" section on this.
120
+ 5. Tell them what a restore doesn't bring back: Auth users, secret values and Edge Functions. They need to set those up again. The `API grants` check line says what access `anon`, `authenticated` and `service_role` got; for a snapshot taken before 2.9.0 it is Supabase's old default access in `public`, so they should revoke it on anything they kept private. The snapshot's `RECOVERY.md` has a "Not covered" section on this.
121
121
  6. Once they're done, suggest they delete the two `TARGET` lines from `.env.backupdrill`.
122
122
 
123
123
  ## Run it on a schedule
@@ -95,7 +95,7 @@ jobs:
95
95
 
96
96
  - name: Run backupdrill
97
97
  # Pinned so every run uses the same CLI. Raise it on purpose when you upgrade.
98
- run: npx -y backupdrill@2.7.2 backup
98
+ run: npx -y backupdrill@2.9.2 backup
99
99
  env:
100
100
  # --- required ---
101
101
  BACKUPDRILL_DATABASE_URL: ${{ secrets.BACKUPDRILL_DATABASE_URL }}