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/README.md CHANGED
@@ -77,6 +77,7 @@ All recognized variables:
77
77
  | `BACKUPDRILL_DATABASE_URL` | Source connection string (falls back to `DATABASE_URL`) | — (required) |
78
78
  | `BACKUPDRILL_PROJECT_NAME` | Readable name used in object keys and the manifest | `supabase` |
79
79
  | `BACKUPDRILL_SCHEMAS` | Comma-separated schemas to dump | `public` |
80
+ | `BACKUPDRILL_AUTH` | Supabase Auth users (`auth.users` + `auth.identities`) go into `auth.dump` next to the database dump whenever the role can read them. `off` leaves them out. `on` makes a backup that can't include them exit with code 3; the database backup still completes either way. Also `--auth` / `--no-auth`, or `"auth": true/false` in the config file | on when possible |
80
81
  | `BACKUPDRILL_S3_ENDPOINT` | S3-compatible endpoint (R2/B2/self-hosted; omit for AWS S3) | — |
81
82
  | `BACKUPDRILL_S3_REGION` | Destination bucket region | `auto` |
82
83
  | `BACKUPDRILL_S3_BUCKET` | Destination bucket | — (required) |
@@ -86,6 +87,8 @@ All recognized variables:
86
87
  | `BACKUPDRILL_SUPABASE_STORAGE_*` | Storage-file source (endpoint/region/keys/buckets) — see [Backing up Storage files](#backing-up-storage-files-too) | — |
87
88
  | `BACKUPDRILL_PG_DUMP` | Path to the `pg_dump` binary to use | `pg_dump` on `PATH` |
88
89
  | `BACKUPDRILL_PG_RESTORE` | Path to `pg_restore` (used by `drill` and `restore`) | next to `BACKUPDRILL_PG_DUMP`, else `pg_restore` on `PATH` |
90
+ | `BACKUPDRILL_PSQL` | Path to `psql`, which `restore` uses for snapshots with Auth users | next to `pg_restore`, else `psql` on `PATH` |
91
+ | `BACKUPDRILL_STATE_DIR` | Where `restore` keeps its record of restores with Auth users, for `--status` and `--finish` | `~/.backupdrill/restores` |
89
92
  | `BACKUPDRILL_PING_URL` | Healthchecks.io ping URL for `backup` and `drill` — see [Alerts with Healthchecks.io](#alerts-with-healthchecksio) | — |
90
93
 
91
94
  ### Config file
@@ -158,6 +161,7 @@ backupdrill estimate --plan pro # measures your DB + Storage, prints the proje
158
161
  ```
159
162
  <prefix>/<project>/<timestamp>/
160
163
  ├── dump.pgcustom # pg_dump --format=custom (public schema by default)
164
+ ├── auth.dump # Auth users: auth.users + auth.identities (2.10.0+, when the role can read them)
161
165
  ├── storage/<bucket>/<key> # your Storage files (if configured)
162
166
  ├── RECOVERY.md # how to restore this snapshot
163
167
  └── manifest.json # schemas, tables, row counts, grants, file list, sizes + sha256
@@ -179,6 +183,8 @@ Backups record your installed Postgres extensions in the manifest, and the drill
179
183
 
180
184
  The sandbox restore runs up to 4 parallel `pg_restore` jobs, sized from the CPUs and memory Docker reports, so a 2 vCPU / 8 GB machine gets 2. Table data and index builds run in parallel. Foreign keys, triggers and policies run on a single connection to keep their error messages separate, including errors about Supabase-managed objects such as `auth.users`. `backupdrill restore` into a real Supabase project stays on a single connection.
181
185
 
186
+ For a snapshot with Auth users, the drill does more once its usual checks are done. In the same sandbox it restores the two Auth tables and compares their row counts with the backup. It adds the foreign keys into them that it otherwise skips, recreates the triggers on them that a restore would recreate (the rest are listed as manual steps), and simulates an email sign-up as `supabase_auth_admin`, the role Supabase Auth uses, then rolls it back. If a trigger fails on that test sign-up (an email sign-up with no user metadata), the report says so. The result is an `auth` section in the report. For now it doesn't change whether the drill passes.
187
+
182
188
  Ctrl+C (or a SIGTERM from whatever runs the drill) stops it and cleans up: the CLI stops a running `--check-cmd` and `pg_restore`, removes the sandbox container and its volume, deletes the downloaded dump, and exits with 130 (143 for SIGTERM). `--keep` doesn't apply to an interrupted drill. Press Ctrl+C a second time to exit without waiting for the cleanup.
183
189
 
184
190
  ### Run your own checks against the restored copy
@@ -209,7 +215,18 @@ Prefer files on disk instead? Skip the Storage target and pass `--storage-dir ./
209
215
 
210
216
  `--dry-run` writes nothing to the target. Besides checking the target (not the source project, schemas empty, Postgres and `pg_restore` versions, extensions available), it downloads the dump to a temporary directory, checks its sha256 and looks for foreign keys that point outside the backup (see [Tables that reference auth.users](#tables-that-reference-authusers)). The real run repeats those checks before it writes anything; a foreign key into a table that one of the recorded extensions creates is checked again once the extensions are installed. The database restore then runs in a single transaction: if any statement fails, nothing from the snapshot stays on the target, and you can run it again on the same project once you've fixed the cause. (If the connection drops while it commits, the error says so and asks you to check the target first.) Right after that transaction commits, the grants for `anon`, `authenticated` and `service_role` are set in a transaction of their own (see [Grants for anon, authenticated and service_role](#grants-for-anon-authenticated-and-service_role)). Foreign keys between two tables in the backup are the exception to the single transaction: they're added after that, in one more. If rows in your data already break one of them (deleting with triggers switched off, for example under `session_replication_role = replica`, can leave rows like that), the key is added as `NOT VALID` instead of failing the restore. Those rows come back as they are, new writes are still checked, and the report names the key and, when it can count them, how many rows break it. Keys on or into partitioned tables, keys into an extension's tables, and every key in an archive whose foreign key statements BackupDrill can't fully read stay in the main transaction, so a broken one rolls the whole restore back. A key over a generated column is added in the second step but is never relaxed, because the restore recomputes those values; if it breaks, that step fails. Keys added as `NOT VALID` don't fail a drill: the drill passes and lists them in its report. If a step after the main transaction fails for any other reason, the tables and data are already on the target and the error says so. Extensions the run installed stay installed, since the next run needs them too, and the empty-target check doesn't count objects that belong to an extension (except an extension's configuration tables, whose rows a dump can carry). One transaction holds a lock on every table, index and sequence until it commits, so a very large schema can run out of lock slots: on Supabase's smallest compute size, about a thousand tables (partitions count as tables). The restore then stops with nothing written and tells you how to raise `max_locks_per_transaction`.
211
217
 
212
- Or restore the dump by hand — into an **empty** database, without `--clean`:
218
+ Snapshots taken with 2.10.0 or later usually hold the Auth users as well. For those, `restore` writes the Auth users, the database and the triggers on the Auth tables that it can recreate in **one** transaction. Triggers it can't recreate, and policies on the Auth tables, are listed as manual steps. A foreign key like `profiles.id → auth.users` then finds its users. If anything fails before the commit, the target is left as it was. The grants and some foreign keys come after the commit, as with any restore (see above). A few things come with that:
219
+
220
+ - **`psql` is needed.** It comes from the same PostgreSQL client package as `pg_restore`, and it must be 17.6, 16.10, 15.14, 14.19, 13.22 or newer. Those releases protect psql from commands smuggled into an archive.
221
+ - **The target has to be a new project.** No Auth users, and no triggers or policies of its own on the Auth tables.
222
+ - **Links and codes from before don't work.** Password-reset, email-confirmation and email or phone change links that were pending at backup time are cleared.
223
+ - **Everyone signs in again**, because sessions aren't in the snapshot.
224
+ - **Auth settings are yours to set up again.** Sign-in providers, SMTP, redirect URLs and the site URL live in the Supabase dashboard, not in the database. Users who signed in with Google or GitHub keep that sign-in method; reconfigure the same OAuth app in the new project.
225
+ - **MFA factors aren't backed up.** Users who had MFA sign in with one factor until they enroll again.
226
+
227
+ If the restore is cut off while it commits, `backupdrill restore --status` (same `BACKUPDRILL_TARGET_DATABASE_URL`, same machine) says whether it committed. If it did, `backupdrill restore --finish --confirm-target <ref>` does the grants and foreign keys that come after the commit, and it can be run again safely. `--skip-auth` leaves the Auth users out and restores the database the way 2.9 did; use it if you already copied the users into the target yourself.
228
+
229
+ Or restore by hand. For a snapshot with Auth users, follow step 4 of its `RECOVERY.md`, which restores `auth.dump` and `dump.pgcustom` in one transaction. For a snapshot without them, restore the dump into an **empty** database, without `--clean`:
213
230
 
214
231
  ```bash
215
232
  pg_restore --no-owner --no-privileges --dbname "<target-connection-string>" dump.pgcustom
@@ -223,7 +240,7 @@ supabase-js and the other client libraries reach your tables through the Data AP
223
240
 
224
241
  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
242
 
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.
243
+ 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
244
 
228
245
  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
246
 
@@ -237,9 +254,9 @@ grant execute on all functions in schema public to anon, authenticated, service_
237
254
 
238
255
  ### Tables that reference auth.users
239
256
 
240
- By default a backup covers the `public` schema only, so your Auth users are not in it. Plenty of Supabase apps have a table like `profiles` whose `id` is a foreign key to `auth.users(id)`. When the restore recreates that key in a new project, Postgres checks every `profiles` row against `auth.users`, and in a new project that table is empty, so the restore fails.
257
+ This section is about snapshots without Auth users: those taken before 2.10.0, with `--no-auth`, or by a role that couldn't read the Auth tables, and restores with `--skip-auth`. (A snapshot's `manifest.json` says under `auth` whether it has them.) Plenty of Supabase apps have a table like `profiles` whose `id` is a foreign key to `auth.users(id)`. When the restore recreates that key in a new project, Postgres checks every `profiles` row against `auth.users`, and in a new project that table is empty, so the restore fails.
241
258
 
242
- A drill can't catch this. Its sandbox has no `auth.users` at all, so the drill reports that foreign key as a skipped Supabase-managed object and passes. `restore --dry-run` checks it against the real target and tells you how many rows have nothing to point at:
259
+ A drill of such a snapshot can't catch this. Its sandbox has no `auth.users` at all, so the drill reports that foreign key as a skipped Supabase-managed object and passes. `restore --dry-run` checks it against the real target and tells you how many rows have nothing to point at:
243
260
 
244
261
  ```
245
262
  ✗ references outside the backup: public.profiles → auth.users (profiles_id_fkey): 200 of 200 row(s) point at auth.users rows the target doesn't have
@@ -256,9 +273,9 @@ PGPASSWORD="$OLD_PW" pg_dump --data-only --table=auth.users --table=auth.identit
256
273
  unset OLD_PW NEW_PW
257
274
  ```
258
275
 
259
- `auth.identities` holds each user's sign-in methods; users copied with it can sign in to the new project with their old password. If the old project is gone, the users can only come from a backup that includes the `auth` schema, such as Supabase's own daily backups on a paid plan. A backupdrill snapshot of `public` doesn't have them.
276
+ `auth.identities` holds each user's sign-in methods; users copied with it can sign in to the new project with their old password. If the old project is gone, the users can only come from a backup that includes them: a backupdrill snapshot taken with 2.10.0 or later, or Supabase's own daily backups on a paid plan.
260
277
 
261
- Triggers you created on `auth.users`, such as the common one that inserts a `profiles` row on sign-up, belong to that table, so they aren't in the backup either. Create them again after the restore.
278
+ Triggers you created on `auth.users`, such as the common one that inserts a `profiles` row on sign-up, belong to that table, so a snapshot without Auth users doesn't have them either. Create them again after the restore.
262
279
 
263
280
  ## 2.0 migration — `restore` flags changed
264
281
 
@@ -424,6 +441,7 @@ What a scrape costs: one list request per 1,000 snapshot folders and one per 1,0
424
441
  - [x] `restore` — recover a snapshot into a fresh Supabase project: database through the drill-grade engine with verification, Storage uploaded back with per-file reconciliation (local download remains an option)
425
442
  - [x] GitHub Action wrapper
426
443
  - [x] `exporter` — Prometheus metrics for backups and recorded drills
444
+ - [x] Auth users (`auth.users`, `auth.identities`): backed up, restored in the same transaction as the database, checked in drills
427
445
 
428
446
  For scheduling, automated restore drills, and alerting, use the hosted service at [backupdrill.com](https://backupdrill.com).
429
447
 
@@ -0,0 +1,110 @@
1
+ import pg from "pg";
2
+ import type { AuthSection, AuthTriggerInfo, AuthPolicyInfo } from "./manifest.js";
3
+ /**
4
+ * Supabase Auth 用户(auth.users + auth.identities)的备份。
5
+ *
6
+ * 只备这两张表:用户 ID、邮箱、密码哈希、metadata、登录方式。sessions、refresh token、MFA 因子、
7
+ * SSO 配置一律不备——恢复到新项目后用户重新登录一次即可,MFA 因子可能用旧项目的密钥加密过,
8
+ * 带过去反而可能把用户锁在外面。
9
+ *
10
+ * 不打扰现有备份是硬约束:
11
+ * - "off"(库调用的默认值)时,备份命令、上传的文件、manifest 与没有这个功能时逐字节一致。
12
+ * - 主 dump 的参数永远不动;Auth 一侧任何失败都不影响主 dump。
13
+ * - 默认开启("default")时,读不到、不支持、出错都只记进 manifest、打警告,不让备份失败;
14
+ * 只有调用方显式要求("on")时,出错才算失败。
15
+ */
16
+ export type AuthMode = "off" | "default" | "on";
17
+ export declare const AUTH_TABLES: readonly ["users", "identities"];
18
+ /** auth.dump 的技术上限:对应数百万用户或巨大的 metadata。超过就跳过,不拖慢和撑爆演练与恢复 */
19
+ export declare const AUTH_DUMP_MAX_BYTES: number;
20
+ /**
21
+ * schemas 配置和 Auth 备份的关系。单独的 Auth 备份只在每一项都是普通 schema 名字时才做:
22
+ * 模式写法(通配、正则、"库.schema")由 PostgreSQL 自己解析,我们在这里算不准它最终选中哪些 schema,
23
+ * 也就没法可靠地判断"会不会重复导出"和"恢复时目标里哪些 schema 该是空的"——干脆不做。
24
+ * - "yes":明写了 auth(主 dump 里已经有),或某个模式确定匹配得到 auth(例如 "*");
25
+ * - "maybe":有模式写法,而又不能确定它包含 auth;
26
+ * - "no":全是普通名字,且没有 auth。
27
+ */
28
+ export declare function authInSchemas(schemas: string[]): "yes" | "maybe" | "no";
29
+ /**
30
+ * 普通 schema 名字:不加引号、只有字母数字和下划线,按 pg_dump 的规则折成小写。其余一律返回 null,
31
+ * 按模式写法处理(不另备 Auth)。名字会进 RECOVERY.md 里给人复制的 SQL 和 shell,只收这种最朴素的,
32
+ * 加引号的名字(可以含换行、引号、$$)不给任何拼接出错的机会
33
+ */
34
+ export declare function plainSchemaName(pattern: string): string | null;
35
+ /** 默认模式用:确定会、或说不准,都算"可能已含 auth"——宁可少做,不碰现有备份 */
36
+ export declare function schemasMayIncludeAuth(schemas: string[]): boolean;
37
+ /**
38
+ * 连库,但能被 signal 随时打断:到点时直接断开连接,不管它还在连接池里排队、还是正在跑查询。
39
+ * Auth 这两条连接都在主 dump 之前用,绝不能让它们占着连接、把数据库备份堵在后面。
40
+ */
41
+ export declare function connectCancellable(databaseUrl: string, signal?: AbortSignal): Promise<pg.Client>;
42
+ /**
43
+ * 报错文字里可能是用户数据的部分换成 "…":冒号后面引起来的值(例如 invalid input syntax for type uuid: "…")、
44
+ * 单引号字面量、邮箱、UUID。表名、约束名这类标识符(relation "x"、constraint "y")留着,排查要用
45
+ */
46
+ export declare function redactValues(text: string): string;
47
+ /** 共享快照:导出快照的连接 + 快照号。导出连接只需活到两份 pg_dump 都导入快照为止 */
48
+ export interface SharedSnapshot {
49
+ id: string;
50
+ /** 提交并关闭导出连接;重复调用无害 */
51
+ release(): Promise<void>;
52
+ }
53
+ /**
54
+ * 开一个 REPEATABLE READ 只读事务导出快照。主 dump、auth dump、统计都导入这一个快照,
55
+ * 两份归档看到的是同一时刻的库(否则两次导出之间的注册、删号会让两份对不上)。
56
+ * 失败就返回 null:调用方按今天的方式导出主 dump,只把 Auth 段标掉。
57
+ */
58
+ export declare function exportSharedSnapshot(databaseUrl: string, signal?: AbortSignal): Promise<SharedSnapshot | null>;
59
+ /** 统计结果:只读,和两份 dump 同一个快照 */
60
+ export type AuthInspection = {
61
+ readable: false;
62
+ reason: "no_auth_schema" | "no_permission";
63
+ } | {
64
+ readable: true;
65
+ users: number;
66
+ identities: number;
67
+ passwordHashes: AuthSection["passwordHashes"];
68
+ anonymousUsers: number;
69
+ ssoUsers: number;
70
+ mfaUsers: number | null;
71
+ triggers: AuthTriggerInfo[];
72
+ policies: AuthPolicyInfo[];
73
+ grants: Array<{
74
+ table: string;
75
+ grantee: string;
76
+ privilege: string;
77
+ }>;
78
+ };
79
+ /**
80
+ * 在另一个连接里导入共享快照做统计。统计出错只影响这个连接,导出快照的事务和主 dump 不受牵连。
81
+ * 能不能读到全部行要先确认:auth.users 开着 RLS,角色既不是超级用户、又没有 BYPASSRLS 时,
82
+ * pg_dump 照样"成功",导出的却是空表——看着干净,其实什么都没备上。
83
+ */
84
+ export declare function inspectAuth(databaseUrl: string, snapshotId: string, signal?: AbortSignal): Promise<AuthInspection>;
85
+ /**
86
+ * 恢复(含 RECOVERY.md 的手工步骤)自动补建的 Auth 表对象。只建同时满足下面几条的触发器:
87
+ * - 源库里是普通启用状态(O)。D 停用、R 只在复制会话触发的,在普通会话里本来就不起作用;
88
+ * A(总是触发)恢复时 pg_dump 会带一句 ENABLE ALWAYS,那需要表的属主身份,新项目里做不到。
89
+ * - 触发函数所在的 schema 在这次备份里(或是平台 schema),否则建不出来。
90
+ * - 名字是普通标识符。
91
+ * 策略一律不自动建:CREATE POLICY 需要表的属主身份,新项目里 auth 两张表的属主是平台角色;
92
+ * 放进单事务恢复里建不出来,会让整个恢复回滚。少了它们,这两张开着 RLS 的表对 API 角色一律拒绝,
93
+ * 是收紧而不是放开。
94
+ */
95
+ export declare function restorableAuthObjects(auth: {
96
+ triggers: AuthTriggerInfo[];
97
+ policies: AuthPolicyInfo[];
98
+ }, backedUpSchemas: string[]): {
99
+ triggers: AuthTriggerInfo[];
100
+ };
101
+ /**
102
+ * 恢复时不会自动补建、需要人手处理的 Auth 表对象,写成给人看的句子。备份时提示一次(好让用户把缺的
103
+ * schema 加进备份),RECOVERY.md 和恢复报告里列成手工步骤。
104
+ */
105
+ export declare function manualAuthObjects(auth: {
106
+ triggers: AuthTriggerInfo[];
107
+ policies: AuthPolicyInfo[];
108
+ }, backedUpSchemas: string[]): string[];
109
+ /** pg_dump 参数:只导两张表(结构 + 数据 + 它们上的索引、约束、触发器、策略),同一个共享快照 */
110
+ export declare function authDumpArgs(snapshotId: string): string[];
@@ -0,0 +1,383 @@
1
+ import pg from "pg";
2
+ import { attachPgErrorGuard, pgConnectOptions } from "./supabase-ca.js";
3
+ export const AUTH_TABLES = ["users", "identities"];
4
+ /** auth.dump 的技术上限:对应数百万用户或巨大的 metadata。超过就跳过,不拖慢和撑爆演练与恢复 */
5
+ export const AUTH_DUMP_MAX_BYTES = 2 * 1024 * 1024 * 1024;
6
+ /**
7
+ * 把一个 pg_dump 的 --schema 模式转成正则。只解析最简单、两边规则一定一致的写法:
8
+ * - 双引号外:普通字符(字母折成小写、数字、_、$)和 * 任意串、? 任意一个字符;
9
+ * - 双引号内:按字面、保留大小写,"" 表示一个双引号。
10
+ * 其余写法(方括号、括号、|、+、{}、^、反斜杠,以及"库.schema"的点)走的是 PostgreSQL 自己的正则,
11
+ * 和 JavaScript 不完全一样(例如 [[:alpha:]] 这类字符类),一律返回 null,调用方按"可能包含"处理。
12
+ */
13
+ function schemaPatternRegex(pattern) {
14
+ let re = "";
15
+ let quoted = false;
16
+ for (let i = 0; i < pattern.length; i++) {
17
+ const ch = pattern[i];
18
+ if (ch === '"') {
19
+ if (quoted && pattern[i + 1] === '"') {
20
+ re += '"';
21
+ i++;
22
+ }
23
+ else {
24
+ quoted = !quoted;
25
+ }
26
+ continue;
27
+ }
28
+ if (quoted) {
29
+ re += ch.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
30
+ continue;
31
+ }
32
+ if (ch === "*")
33
+ re += ".*";
34
+ else if (ch === "?")
35
+ re += ".";
36
+ else if (ch === "$")
37
+ re += "\\$";
38
+ else if (/[A-Za-z0-9_]/.test(ch))
39
+ re += ch.toLowerCase();
40
+ else
41
+ return null;
42
+ }
43
+ return new RegExp(`^(?:${re})$`);
44
+ }
45
+ /**
46
+ * schemas 配置和 Auth 备份的关系。单独的 Auth 备份只在每一项都是普通 schema 名字时才做:
47
+ * 模式写法(通配、正则、"库.schema")由 PostgreSQL 自己解析,我们在这里算不准它最终选中哪些 schema,
48
+ * 也就没法可靠地判断"会不会重复导出"和"恢复时目标里哪些 schema 该是空的"——干脆不做。
49
+ * - "yes":明写了 auth(主 dump 里已经有),或某个模式确定匹配得到 auth(例如 "*");
50
+ * - "maybe":有模式写法,而又不能确定它包含 auth;
51
+ * - "no":全是普通名字,且没有 auth。
52
+ */
53
+ export function authInSchemas(schemas) {
54
+ let maybe = false;
55
+ for (const pattern of schemas) {
56
+ const plain = plainSchemaName(pattern);
57
+ if (plain === "auth")
58
+ return "yes";
59
+ if (plain !== null)
60
+ continue;
61
+ if (schemaPatternRegex(pattern)?.test("auth"))
62
+ return "yes";
63
+ maybe = true;
64
+ }
65
+ return maybe ? "maybe" : "no";
66
+ }
67
+ /**
68
+ * 普通 schema 名字:不加引号、只有字母数字和下划线,按 pg_dump 的规则折成小写。其余一律返回 null,
69
+ * 按模式写法处理(不另备 Auth)。名字会进 RECOVERY.md 里给人复制的 SQL 和 shell,只收这种最朴素的,
70
+ * 加引号的名字(可以含换行、引号、$$)不给任何拼接出错的机会
71
+ */
72
+ export function plainSchemaName(pattern) {
73
+ return /^[A-Za-z_][A-Za-z0-9_]*$/.test(pattern) ? pattern.toLowerCase() : null;
74
+ }
75
+ /** 默认模式用:确定会、或说不准,都算"可能已含 auth"——宁可少做,不碰现有备份 */
76
+ export function schemasMayIncludeAuth(schemas) {
77
+ return authInSchemas(schemas) !== "no";
78
+ }
79
+ /**
80
+ * 连库,但能被 signal 随时打断:到点时直接断开连接,不管它还在连接池里排队、还是正在跑查询。
81
+ * Auth 这两条连接都在主 dump 之前用,绝不能让它们占着连接、把数据库备份堵在后面。
82
+ */
83
+ export async function connectCancellable(databaseUrl, signal) {
84
+ if (signal?.aborted)
85
+ throw new Error("stopped by the caller");
86
+ // 握手最多 20 秒:连接池排队、网络卡住时不能一直挂着,更不能让 CLI 进程在备份做完后迟迟退不出去
87
+ const client = new pg.Client({ ...pgConnectOptions(databaseUrl), connectionTimeoutMillis: 20_000 });
88
+ attachPgErrorGuard(client);
89
+ let connected = false;
90
+ const onAbort = () => {
91
+ const stream = client.connection?.stream;
92
+ if (!connected) {
93
+ // 握手中途:带着错误销毁 socket,connect() 随之 reject。不能先调 end():它把 client 标成
94
+ // "主动结束",node-pg 之后就不再回调 connect(),connect() 永远等不到结果
95
+ stream?.destroy(new Error("stopped by the caller"));
96
+ return;
97
+ }
98
+ // 连上之后:直接销毁 socket,进行中的查询随之 reject(end() 在握手后是优雅关闭,对方不回应就一直等)
99
+ stream?.destroy();
100
+ void client.end().catch(() => { });
101
+ };
102
+ signal?.addEventListener("abort", onAbort, { once: true });
103
+ try {
104
+ await client.connect();
105
+ connected = true;
106
+ }
107
+ catch (error) {
108
+ signal?.removeEventListener("abort", onAbort);
109
+ throw error;
110
+ }
111
+ // 连上之后仍然听着:查询进行中被叫停也立刻断开;client 结束时把监听摘掉
112
+ client.once("end", () => signal?.removeEventListener("abort", onAbort));
113
+ // 服务端在等锁时察觉不到客户端已经走了,会一直占着连接等到锁超时。PG 14 起可以让它每秒查一次,
114
+ // 断开后很快收手、把连接还回连接池;更老的服务端不认这个参数,忽略即可
115
+ await client.query("set client_connection_check_interval = '1s'").catch(() => { });
116
+ return client;
117
+ }
118
+ /** 引号个数是奇数 = 有一个没闭合(文字在值中间被截断了):从最后那个引号起到结尾都当成值 */
119
+ function closeDanglingQuote(text, quote) {
120
+ const count = text.split(quote).length - 1;
121
+ if (count % 2 === 0)
122
+ return text;
123
+ return `${text.slice(0, text.lastIndexOf(quote))}${quote}…${quote}`;
124
+ }
125
+ /**
126
+ * 报错文字里可能是用户数据的部分换成 "…":冒号后面引起来的值(例如 invalid input syntax for type uuid: "…")、
127
+ * 单引号字面量、邮箱、UUID。表名、约束名这类标识符(relation "x"、constraint "y")留着,排查要用
128
+ */
129
+ export function redactValues(text) {
130
+ return closeDanglingQuote(closeDanglingQuote(text, "'"), '"')
131
+ .replace(/:\s*"(?:[^"]|"")*"/g, ': "…"')
132
+ .replace(/'(?:[^']|'')*'/g, "'…'")
133
+ .replace(/[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}/g, "…")
134
+ .replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/gi, "…");
135
+ }
136
+ /**
137
+ * 开一个 REPEATABLE READ 只读事务导出快照。主 dump、auth dump、统计都导入这一个快照,
138
+ * 两份归档看到的是同一时刻的库(否则两次导出之间的注册、删号会让两份对不上)。
139
+ * 失败就返回 null:调用方按今天的方式导出主 dump,只把 Auth 段标掉。
140
+ */
141
+ export async function exportSharedSnapshot(databaseUrl, signal) {
142
+ let client = null;
143
+ try {
144
+ client = await connectCancellable(databaseUrl, signal);
145
+ // 兜底:进程卡住时也不让这个空闲事务一直挂着(正常情况几秒内就释放);语句本身也不许久等
146
+ await client.query("set idle_in_transaction_session_timeout = '10min'");
147
+ await client.query("set statement_timeout = '30s'");
148
+ await client.query("begin isolation level repeatable read read only");
149
+ const res = await client.query("select pg_export_snapshot() as id");
150
+ const id = res.rows[0]?.id;
151
+ if (!id)
152
+ throw new Error("pg_export_snapshot returned nothing");
153
+ const held = client;
154
+ let released = false;
155
+ return {
156
+ id,
157
+ async release() {
158
+ if (released)
159
+ return;
160
+ released = true;
161
+ await held.query("commit").catch(() => { });
162
+ await held.end().catch(() => { });
163
+ },
164
+ };
165
+ }
166
+ catch {
167
+ await client?.end().catch(() => { });
168
+ return null;
169
+ }
170
+ }
171
+ // Supabase 平台自己的 schema。触发器函数或策略引用的函数在这些 schema 里时算平台对象
172
+ const PLATFORM_SCHEMAS = [
173
+ "auth", "storage", "realtime", "extensions", "supabase_functions", "graphql", "graphql_public",
174
+ "net", "pgsodium", "pgsodium_masks", "vault", "pg_catalog", "information_schema",
175
+ ];
176
+ /**
177
+ * 在另一个连接里导入共享快照做统计。统计出错只影响这个连接,导出快照的事务和主 dump 不受牵连。
178
+ * 能不能读到全部行要先确认:auth.users 开着 RLS,角色既不是超级用户、又没有 BYPASSRLS 时,
179
+ * pg_dump 照样"成功",导出的却是空表——看着干净,其实什么都没备上。
180
+ */
181
+ export async function inspectAuth(databaseUrl, snapshotId, signal) {
182
+ const client = await connectCancellable(databaseUrl, signal);
183
+ try {
184
+ // 这些统计跑在主 dump 之前:auth 表上有别人的锁(例如正在跑的 Auth 迁移)时不能陪着等,
185
+ // 超时就让 Auth 这次不备,主 dump 照常
186
+ await client.query("set lock_timeout = '5s'");
187
+ await client.query("set statement_timeout = '60s'");
188
+ await client.query("begin isolation level repeatable read read only");
189
+ // 快照号来自 pg_export_snapshot(),格式固定;仍按字面量转义,不拼裸值
190
+ await client.query(`set transaction snapshot ${client.escapeLiteral(snapshotId)}`);
191
+ // 存在与权限都按 OID 从系统目录查:对 auth schema 没有 USAGE 的角色,按名字解析
192
+ // (to_regclass、'auth.users'::regclass、has_table_privilege('auth.users', …))会直接报错,
193
+ // 而这种情况该记"无权读取、跳过",不是"失败"
194
+ const found = await client.query(`select count(*) as tables,
195
+ coalesce(bool_and(has_schema_privilege(n.oid, 'USAGE')
196
+ and has_table_privilege(c.oid, 'SELECT')
197
+ and (r.rolsuper or r.rolbypassrls or not c.relrowsecurity)), false) as ok
198
+ from pg_class c
199
+ join pg_namespace n on n.oid = c.relnamespace
200
+ join pg_roles r on r.rolname = current_user
201
+ where n.nspname = 'auth' and c.relname in ('users', 'identities') and c.relkind in ('r', 'p')`);
202
+ if (Number(found.rows[0]?.tables) !== 2)
203
+ return { readable: false, reason: "no_auth_schema" };
204
+ if (!found.rows[0]?.ok)
205
+ return { readable: false, reason: "no_permission" };
206
+ const counts = await client.query(`select (select count(*) from auth.users) as users,
207
+ (select count(*) from auth.identities) as identities,
208
+ count(*) filter (where encrypted_password is null or encrypted_password = '') as none,
209
+ count(*) filter (where encrypted_password ~ '^\\$2[abxy]?\\$'
210
+ or encrypted_password ~ '^\\$argon2(id|i|d)\\$'
211
+ or encrypted_password ~ '^\\$fbscrypt\\$') as portable,
212
+ count(*) filter (where encrypted_password like '{%'
213
+ and encrypted_password like '%"alg":"aes-gcm-hkdf"%') as encrypted,
214
+ count(*) filter (where encrypted_password is not null and encrypted_password <> ''
215
+ and not (encrypted_password ~ '^\\$2[abxy]?\\$'
216
+ or encrypted_password ~ '^\\$argon2(id|i|d)\\$'
217
+ or encrypted_password ~ '^\\$fbscrypt\\$')
218
+ and not (encrypted_password like '{%'
219
+ and encrypted_password like '%"alg":"aes-gcm-hkdf"%')) as unrecognized,
220
+ count(*) filter (where coalesce((to_jsonb(u) ->> 'is_anonymous')::boolean, false)) as anonymous,
221
+ count(*) filter (where coalesce((to_jsonb(u) ->> 'is_sso_user')::boolean, false)) as sso
222
+ from auth.users u`);
223
+ const c = counts.rows[0];
224
+ // MFA 人数是可选统计:表不存在或没权限都不该让 Auth 段失败,出错回滚到保存点、记为未知
225
+ let mfaUsers = null;
226
+ await client.query("savepoint mfa");
227
+ try {
228
+ const mfa = await client.query(`select count(distinct user_id) as n from auth.mfa_factors where status::text = 'verified'`);
229
+ mfaUsers = Number(mfa.rows[0].n);
230
+ await client.query("release savepoint mfa");
231
+ }
232
+ catch {
233
+ await client.query("rollback to savepoint mfa");
234
+ }
235
+ const triggers = await client.query(
236
+ // dependency_schemas:触发器依赖的全部函数(触发函数本身 + WHEN 条件里调用的)所在 schema
237
+ `select c.relname as table, t.tgname as name, t.tgenabled::text as enabled,
238
+ fn.nspname as function_schema, p.proname as function_name,
239
+ coalesce(array(
240
+ select distinct dn.nspname::text
241
+ from pg_depend d
242
+ join pg_proc dp on dp.oid = d.refobjid and d.refclassid = 'pg_proc'::regclass
243
+ join pg_namespace dn on dn.oid = dp.pronamespace
244
+ where d.classid = 'pg_trigger'::regclass and d.objid = t.oid
245
+ order by 1), '{}'::text[]) as dependency_schemas
246
+ from pg_trigger t
247
+ join pg_class c on c.oid = t.tgrelid
248
+ join pg_proc p on p.oid = t.tgfoid
249
+ join pg_namespace fn on fn.oid = p.pronamespace
250
+ where c.oid in ('auth.users'::regclass, 'auth.identities'::regclass)
251
+ and not t.tgisinternal
252
+ order by 1, 2`);
253
+ const policies = await client.query(
254
+ // 策略表达式里引用到的函数所在 schema(USING 与 WITH CHECK 都算),用来判断依赖在不在备份里
255
+ `select c.relname as table, pol.polname as name,
256
+ -- ::text:node-pg 只解析 text[],name[] 会原样返回成 "{a,b}" 字符串
257
+ coalesce(array(
258
+ select distinct n.nspname::text
259
+ from pg_depend d
260
+ join pg_proc p on p.oid = d.refobjid and d.refclassid = 'pg_proc'::regclass
261
+ join pg_namespace n on n.oid = p.pronamespace
262
+ where d.classid = 'pg_policy'::regclass and d.objid = pol.oid
263
+ order by 1), '{}'::text[]) as function_schemas
264
+ from pg_policy pol
265
+ join pg_class c on c.oid = pol.polrelid
266
+ where c.oid in ('auth.users'::regclass, 'auth.identities'::regclass)
267
+ order by 1, 2`);
268
+ const grants = await client.query(`select c.relname as table,
269
+ case when a.grantee = 0 then 'PUBLIC' else a.grantee::regrole::text end as grantee,
270
+ a.privilege_type as privilege
271
+ from pg_class c, aclexplode(c.relacl) a
272
+ where c.oid in ('auth.users'::regclass, 'auth.identities'::regclass)
273
+ order by 1, 2, 3`);
274
+ await client.query("commit");
275
+ return {
276
+ readable: true,
277
+ grants: grants.rows,
278
+ users: Number(c.users),
279
+ identities: Number(c.identities),
280
+ passwordHashes: {
281
+ none: Number(c.none),
282
+ portable: Number(c.portable),
283
+ encrypted: Number(c.encrypted),
284
+ unrecognized: Number(c.unrecognized),
285
+ },
286
+ anonymousUsers: Number(c.anonymous),
287
+ ssoUsers: Number(c.sso),
288
+ mfaUsers,
289
+ triggers: triggers.rows.map((t) => ({
290
+ table: t.table,
291
+ name: t.name,
292
+ enabled: t.enabled,
293
+ functionSchema: t.function_schema,
294
+ functionName: t.function_name,
295
+ dependencySchemas: t.dependency_schemas,
296
+ })),
297
+ policies: policies.rows.map((p) => ({
298
+ table: p.table,
299
+ name: p.name,
300
+ functionSchemas: p.function_schemas.filter((s) => !PLATFORM_SCHEMAS.includes(s)),
301
+ })),
302
+ };
303
+ }
304
+ finally {
305
+ await client.end().catch(() => { });
306
+ }
307
+ }
308
+ /**
309
+ * schema 是否在这次备份里:按 pg_dump 读模式的规则匹配 schemas(含通配)。平台 schema 不算:
310
+ * 用户自己建在 extensions 之类里的函数不在任何一份归档里,新项目里也没有。
311
+ */
312
+ function schemaCovered(schema, backedUpSchemas) {
313
+ // 走到这里的 schemas 都是普通名字(带模式写法的根本不做 Auth 备份,见 authInSchemas)
314
+ return backedUpSchemas.some((name) => plainSchemaName(name) === schema);
315
+ }
316
+ /** 触发器依赖的函数所在的全部 schema(触发函数 + WHEN 里调用的);旧记录没有 dependencySchemas 时只看触发函数 */
317
+ function triggerDependencies(t) {
318
+ return [...new Set([t.functionSchema, ...(t.dependencySchemas ?? [])])];
319
+ }
320
+ // 自动补建的对象名只收普通标识符:名字会进 pg_restore -l 的筛选,也会出现在给人复制的命令里,
321
+ // 带引号、空格之类的名字一律交给手工步骤,杜绝任何拼接注入
322
+ const PLAIN_NAME = /^[A-Za-z_][A-Za-z0-9_]*$/;
323
+ /**
324
+ * 恢复(含 RECOVERY.md 的手工步骤)自动补建的 Auth 表对象。只建同时满足下面几条的触发器:
325
+ * - 源库里是普通启用状态(O)。D 停用、R 只在复制会话触发的,在普通会话里本来就不起作用;
326
+ * A(总是触发)恢复时 pg_dump 会带一句 ENABLE ALWAYS,那需要表的属主身份,新项目里做不到。
327
+ * - 触发函数所在的 schema 在这次备份里(或是平台 schema),否则建不出来。
328
+ * - 名字是普通标识符。
329
+ * 策略一律不自动建:CREATE POLICY 需要表的属主身份,新项目里 auth 两张表的属主是平台角色;
330
+ * 放进单事务恢复里建不出来,会让整个恢复回滚。少了它们,这两张开着 RLS 的表对 API 角色一律拒绝,
331
+ * 是收紧而不是放开。
332
+ */
333
+ export function restorableAuthObjects(auth, backedUpSchemas) {
334
+ return {
335
+ triggers: auth.triggers.filter((t) => t.enabled === "O" &&
336
+ triggerDependencies(t).every((schema) => schemaCovered(schema, backedUpSchemas)) &&
337
+ PLAIN_NAME.test(t.name)),
338
+ };
339
+ }
340
+ /**
341
+ * 恢复时不会自动补建、需要人手处理的 Auth 表对象,写成给人看的句子。备份时提示一次(好让用户把缺的
342
+ * schema 加进备份),RECOVERY.md 和恢复报告里列成手工步骤。
343
+ */
344
+ export function manualAuthObjects(auth, backedUpSchemas) {
345
+ const notes = [];
346
+ for (const t of auth.triggers) {
347
+ const on = `trigger ${JSON.stringify(t.name)} on auth.${t.table}`;
348
+ if (t.enabled === "D" || t.enabled === "R") {
349
+ notes.push(`${on} was ${t.enabled === "D" ? "disabled" : "replica-only"} at the source, so it isn't recreated`);
350
+ }
351
+ else if (triggerDependencies(t).some((schema) => !schemaCovered(schema, backedUpSchemas))) {
352
+ const missing = triggerDependencies(t).filter((schema) => !schemaCovered(schema, backedUpSchemas));
353
+ notes.push(`${on} calls ${t.functionSchema}.${t.functionName}()` +
354
+ `${missing.length === 1 && missing[0] === t.functionSchema ? "" : ` and depends on functions in ${missing.join(", ")}`}, ` +
355
+ `but ${missing.length === 1 ? `schema ${missing[0]} is` : `schemas ${missing.join(", ")} are`} not in this backup, ` +
356
+ `so it can't be recreated until ${missing.length === 1 ? "that schema exists" : "those schemas exist"} on the target`);
357
+ }
358
+ else if (t.enabled === "A") {
359
+ notes.push(`${on} fires in every session (ENABLE ALWAYS), which needs the table owner to set; recreate it by hand`);
360
+ }
361
+ else if (!PLAIN_NAME.test(t.name)) {
362
+ notes.push(`${on} has a name that needs quoting; recreate it by hand`);
363
+ }
364
+ }
365
+ for (const p of auth.policies) {
366
+ const missing = p.functionSchemas.filter((s) => !schemaCovered(s, backedUpSchemas));
367
+ notes.push(`policy ${JSON.stringify(p.name)} on auth.${p.table} isn't recreated automatically (creating a policy needs the table owner)` +
368
+ (missing.length ? `; it also uses functions in ${missing.join(", ")}, which ${missing.length === 1 ? "is" : "are"} not in this backup` : ""));
369
+ }
370
+ return notes;
371
+ }
372
+ /** pg_dump 参数:只导两张表(结构 + 数据 + 它们上的索引、约束、触发器、策略),同一个共享快照 */
373
+ export function authDumpArgs(snapshotId) {
374
+ return [
375
+ "--format=custom",
376
+ "--no-owner",
377
+ "--no-privileges",
378
+ `--snapshot=${snapshotId}`,
379
+ // 拿不到两张表的共享锁就别一直等(主 dump 的参数不加这个,保持原样)
380
+ "--lock-wait-timeout=60s",
381
+ ...AUTH_TABLES.map((t) => `--table=auth.${t}`),
382
+ ];
383
+ }