backupdrill 2.12.1 → 2.14.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.
package/README.md CHANGED
@@ -166,7 +166,7 @@ Rough cost (Pro, Spend Cap OFF, backups = your only egress):
166
166
  | 10 GB | $0/month (within 250 GB) | ~$4.50/month |
167
167
  | 50 GB | ~$0/month | **~$112/month** ⚠ |
168
168
 
169
- Cost scales with **size × frequency**. Run `backupdrill estimate` to project it for *your* project, and prefer weekly (or a smaller scope) once your data is large. The compressed dump is smaller than raw DB size, so real DB egress is below the `estimate` upper bound; Storage egress is exact.
169
+ Cost scales with **size × frequency**. Run `backupdrill estimate` to project it for *your* project, and prefer weekly (or a smaller scope) once your data is large. The compressed dump is smaller than raw DB size, so real DB egress is below the `estimate` upper bound; for Storage, `estimate` totals the file sizes from the current listing, and the next backup's egress depends on what it actually downloads.
170
170
 
171
171
  ```bash
172
172
  backupdrill estimate --plan pro # measures your DB + Storage, prints the projection + warnings
@@ -250,25 +250,106 @@ Snapshots taken with 2.10.0 or later usually hold the Auth users as well. For th
250
250
  - **`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.
251
251
  - **The target has to be a new project.** No Auth users, and no triggers or policies of its own on the Auth tables.
252
252
  - **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.
253
- - **Everyone signs in again**, because sessions aren't in the snapshot.
253
+ - **Sessions don't carry over**, so users sign in again. Anonymous users can't get back into their old accounts, and users whose password hashes were encrypted with the old project's key need a password reset; the Auth notes from `backupdrill restore` and in the snapshot's `RECOVERY.md` give how many of each there are.
254
254
  - **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.
255
255
  - **MFA factors aren't backed up.** Users who had MFA sign in with one factor until they enroll again.
256
256
 
257
- 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.
257
+ If the restore is cut off while it commits, run `backupdrill restore --status` on the same machine with the same `BACKUPDRILL_TARGET_DATABASE_URL`:
258
258
 
259
- 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`:
259
+ - `in progress`: wait and run `--status` again.
260
+ - `aborted`: the restore rolled back. Fix the cause, then run the restore again.
261
+ - `committed`: the database transaction committed. If it says the grants or foreign keys after the commit may be missing, run `backupdrill restore --finish --confirm-target <ref>` with the original snapshot settings (including `--from-dir` if you used it); it can be run again safely.
262
+ - "This target isn't the database the record was written for": if `BACKUPDRILL_TARGET_DATABASE_URL` points somewhere else, set it to the target you restored into and run `--status` again. If the database was recreated since, its contents can't tell you what happened to the old one: check that the replacement has nothing in the schemas you restore before starting a new restore there.
263
+ - `unknown`, or no record on this machine: connect to the target and check for one of the snapshot's tables that wasn't there before, and whether `auth.users` has the snapshot's users. Run the restore again only once you've confirmed it rolled back.
264
+
265
+ `--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.
266
+
267
+ 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 in one transaction too, without `--clean`; a `RECOVERY.md` written by 2.13.0 or later has the same commands. Install the extensions the snapshot lists first (step 2 of its `RECOVERY.md`, or `database.extensions` in `manifest.json`): the dump uses their types. If the snapshot's schema list includes `auth`, `storage` or `realtime`, keep in mind that a new Supabase project already has those schemas, with tables of their own: if the dump creates any of those tables again, the restore rolls back there. If that happens, email support@backupdrill.com with the project name and the snapshot time.
268
+
269
+ First save Supabase's root certificate as `supabase-ca.crt` in the folder you run the restore from. The connections below use it to check the Session Pooler's certificate, as the CLI does:
270
+
271
+ ```bash
272
+ cat > supabase-ca.crt <<'PEM'
273
+ -----BEGIN CERTIFICATE-----
274
+ MIIDxDCCAqygAwIBAgIUbLxMod62P2ktCiAkxnKJwtE9VPYwDQYJKoZIhvcNAQEL
275
+ BQAwazELMAkGA1UEBhMCVVMxEDAOBgNVBAgMB0RlbHdhcmUxEzARBgNVBAcMCk5l
276
+ dyBDYXN0bGUxFTATBgNVBAoMDFN1cGFiYXNlIEluYzEeMBwGA1UEAwwVU3VwYWJh
277
+ c2UgUm9vdCAyMDIxIENBMB4XDTIxMDQyODEwNTY1M1oXDTMxMDQyNjEwNTY1M1ow
278
+ azELMAkGA1UEBhMCVVMxEDAOBgNVBAgMB0RlbHdhcmUxEzARBgNVBAcMCk5ldyBD
279
+ YXN0bGUxFTATBgNVBAoMDFN1cGFiYXNlIEluYzEeMBwGA1UEAwwVU3VwYWJhc2Ug
280
+ Um9vdCAyMDIxIENBMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEAqQXW
281
+ QyHOB+qR2GJobCq/CBmQ40G0oDmCC3mzVnn8sv4XNeWtE5XcEL0uVih7Jo4Dkx1Q
282
+ DmGHBH1zDfgs2qXiLb6xpw/CKQPypZW1JssOTMIfQppNQ87K75Ya0p25Y3ePS2t2
283
+ GtvHxNjUV6kjOZjEn2yWEcBdpOVCUYBVFBNMB4YBHkNRDa/+S4uywAoaTWnCJLUi
284
+ cvTlHmMw6xSQQn1UfRQHk50DMCEJ7Cy1RxrZJrkXXRP3LqQL2ijJ6F4yMfh+Gyb4
285
+ O4XajoVj/+R4GwywKYrrS8PrSNtwxr5StlQO8zIQUSMiq26wM8mgELFlS/32Uclt
286
+ NaQ1xBRizkzpZct9DwIDAQABo2AwXjALBgNVHQ8EBAMCAQYwHQYDVR0OBBYEFKjX
287
+ uXY32CztkhImng4yJNUtaUYsMB8GA1UdIwQYMBaAFKjXuXY32CztkhImng4yJNUt
288
+ aUYsMA8GA1UdEwEB/wQFMAMBAf8wDQYJKoZIhvcNAQELBQADggEBAB8spzNn+4VU
289
+ tVxbdMaX+39Z50sc7uATmus16jmmHjhIHz+l/9GlJ5KqAMOx26mPZgfzG7oneL2b
290
+ VW+WgYUkTT3XEPFWnTp2RJwQao8/tYPXWEJDc0WVQHrpmnWOFKU/d3MqBgBm5y+6
291
+ jB81TU/RG2rVerPDWP+1MMcNNy0491CTL5XQZ7JfDJJ9CCmXSdtTl4uUQnSuv/Qx
292
+ Cea13BX2ZgJc7Au30vihLhub52De4P/4gonKsNHYdbWjg7OWKwNv/zitGDVDB9Y2
293
+ CMTyZKG3XEu5Ghl1LEnI3QmEKsqaCLv12BnVjbkSeZsMnevJPs1Ye6TjjJwdik5P
294
+ o/bKiIz+Fq8=
295
+ -----END CERTIFICATE-----
296
+ PEM
297
+ ```
298
+
299
+ Then write `database.list`, the archive's list without the `CREATE SCHEMA` entries for schemas the target already has (`public`, the ones you created for extensions, and the ones a new project comes with). The block uses `psql` to ask the target which schemas it has: when the terminal pauses, type the target's database password and press Enter (nothing shows while you type, and the password stays out of the URL, the command line and your shell history). Go on only if it prints `database.list is ready`; if it fails, fix the error and run it again:
300
+
301
+ ```bash
302
+ (
303
+ set -euo pipefail
304
+ work=$(mktemp -d backupdrill-restore.XXXXXX)
305
+ trap 'rm -rf "$work"' EXIT
306
+ rm -f database.list
307
+ IFS= read -rs PGPASSWORD || exit; export PGPASSWORD # hidden prompt
308
+ unset PGHOSTADDR PGOPTIONS PGSERVICE PGSERVICEFILE
309
+ export PGGSSENCMODE=disable
310
+ pg_restore -l dump.pgcustom > "$work/full.list"
311
+ schema_entry='^[0-9]+; [0-9]+ [0-9]+ SCHEMA - '
312
+ while IFS= read -r entry; do
313
+ if [[ $entry =~ $schema_entry ]]; then
314
+ printf '%s\n' "$entry" > "$work/entry.list"
315
+ create=$(pg_restore -O -L "$work/entry.list" -f - dump.pgcustom | sed -n '/^CREATE SCHEMA /,$p')
316
+ exists=$(psql -X -At -v ON_ERROR_STOP=1 -v create="$create" --dbname "postgresql://postgres.<target-ref>@<target-pooler-host>:5432/postgres?sslmode=verify-full&sslrootcert=supabase-ca.crt" <<'SQL'
317
+ select exists (select 1 from pg_namespace n,
318
+ lateral (values ('CREATE SCHEMA "' || replace(n.nspname, '"', '""') || '";'),
319
+ (case when n.nspname ~ '^[a-z_][a-z0-9_]*$' then 'CREATE SCHEMA ' || n.nspname || ';' end)) c(s)
320
+ where starts_with(:'create', c.s || E'\n'));
321
+ SQL
322
+ )
323
+ if [ "$exists" = t ]; then continue; fi
324
+ fi
325
+ printf '%s\n' "$entry"
326
+ done < "$work/full.list" > "$work/database.list"
327
+ mv "$work/database.list" database.list
328
+ echo "database.list is ready"
329
+ )
330
+ ```
331
+
332
+ Then restore. Use a `pg_restore` at least as new as the `pg_dump` that wrote the archive (`database.pgDumpVersion` in `manifest.json`). pg_restore 17 and newer write `SET transaction_timeout`, which PostgreSQL 16 and older reject, so with those the target has to run PostgreSQL 17 or newer. Type the password again when the terminal pauses, and wait for `restore committed` before you set the grants:
260
333
 
261
334
  ```bash
262
- pg_restore --no-owner --no-privileges --dbname "<target-connection-string>" dump.pgcustom
335
+ (
336
+ set -euo pipefail
337
+ IFS= read -rs PGPASSWORD || exit; export PGPASSWORD # hidden prompt
338
+ unset PGHOSTADDR PGOPTIONS PGSERVICE PGSERVICEFILE
339
+ export PGGSSENCMODE=disable
340
+ pg_restore --single-transaction --exit-on-error --no-owner --no-privileges -L database.list \
341
+ --dbname "postgresql://postgres.<target-ref>@<target-pooler-host>:5432/postgres?sslmode=verify-full&sslrootcert=supabase-ca.crt" dump.pgcustom
342
+ echo "restore committed"
343
+ )
263
344
  ```
264
345
 
265
- One error is expected and harmless: `schema "public" already exists` — the target always has it. An error on a foreign key into `auth.users` means the users have to be copied in first (see [Tables that reference auth.users](#tables-that-reference-authusers)). After that, set the grants yourself (next section). Don't use `--clean` against a Supabase project: it drops and recreates the `public` schema, and with it the grants Supabase put on it. The `backupdrill restore` command above handles all of this (plus verification) for you.
346
+ An error before the commit rolls the restore back: the snapshot's tables aren't left on the target, but extensions you installed first stay, and a sequence that already existed there can keep a new value. If the connection drops during the commit, reconnect and check for one of the snapshot's tables that wasn't on the target before. Run it again only once you've confirmed the restore rolled back. If a foreign key into `auth.users` fails with `is not present in table "users"`, some restored rows point at users the target doesn't have; copy them in first, keeping their IDs (see [Tables that reference auth.users](#tables-that-reference-authusers)). If another foreign key reports a missing parent row, use the table and key values in the error to see what the restore is missing. If you need the data before you can fix that, delete that key's `FK CONSTRAINT` line from `database.list` (and its `COMMENT ... CONSTRAINT` line, if the key has a comment), run the restore again, and add the key back after fixing the reference. `backupdrill restore` can add such a key as `NOT VALID` after the commit when the snapshot has both tables and their data. That excludes keys involving partitioned tables, extension tables or generated columns, and if the CLI can't match the foreign key definitions to the archive's list, it keeps all of them in the main transaction. Don't use `--clean` against a Supabase project: it drops and recreates the `public` schema, and with it the grants Supabase put on it. `backupdrill restore` runs these steps for you and checks the target before and after; it doesn't copy in Auth users the snapshot doesn't have.
266
347
 
267
348
  ### Grants for anon, authenticated and service_role
268
349
 
269
350
  supabase-js and the other client libraries reach your tables through the Data API, as `anon`, `authenticated` or `service_role`. Postgres refuses any table those roles have no grant on, with `42501 permission denied`, before row-level security even runs.
270
351
 
271
- 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.
352
+ 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. If the target grants `anon` access to new `public` tables by default, restored tables inherit those grants, including tables you kept private on the source. Views use their owner's rights by default and can expose rows if the owner bypasses RLS. A `security_invoker` view uses the caller's rights.
272
353
 
273
354
  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.
274
355
 
@@ -292,18 +373,18 @@ A drill of such a snapshot can't catch this. Its sandbox has no `auth.users` at
292
373
  ✗ 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
293
374
  ```
294
375
 
295
- While that check fails, no snapshot data is written. Copy the users into the new project first, then run the restore. While the old project is still reachable, the Postgres tools can do it. Use the Session pooler string of each project, and type the passwords at hidden prompts so they stay out of your shell history:
376
+ While that check fails, no snapshot data is written. Copy the users into the new project first, then run the restore. While the old project is still reachable, the Postgres tools can do it. Use the Session pooler string of each project and save `supabase-ca.crt` as shown under the manual restore above. When the terminal pauses, type the old project's database password and press Enter, then the new project's (nothing shows while you type, and the passwords stay out of your shell history):
296
377
 
297
378
  ```bash
298
379
  read -rs OLD_PW; read -rs NEW_PW
299
- PGPASSWORD="$OLD_PW" pg_dump --data-only --table=auth.users --table=auth.identities \
300
- "postgresql://postgres.<old-ref>@<old-pooler-host>:5432/postgres" |
301
- PGPASSWORD="$NEW_PW" psql -v ON_ERROR_STOP=1 \
302
- "postgresql://postgres.<new-ref>@<new-pooler-host>:5432/postgres"
380
+ PGGSSENCMODE=disable PGPASSWORD="$OLD_PW" pg_dump --data-only --table=auth.users --table=auth.identities \
381
+ "postgresql://postgres.<old-ref>@<old-pooler-host>:5432/postgres?sslmode=verify-full&sslrootcert=supabase-ca.crt" |
382
+ PGGSSENCMODE=disable PGPASSWORD="$NEW_PW" psql -v ON_ERROR_STOP=1 \
383
+ "postgresql://postgres.<new-ref>@<new-pooler-host>:5432/postgres?sslmode=verify-full&sslrootcert=supabase-ca.crt"
303
384
  unset OLD_PW NEW_PW
304
385
  ```
305
386
 
306
- `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.
387
+ Copy `auth.identities` with `auth.users` to keep the sign-in records, and set up the providers again in the new project. A recreated SSO provider gets a new ID, so check whether its users can still reach their original accounts. Users can keep their old passwords if the new project can read their password hashes; users whose hashes were encrypted with the old project's key need a password reset. 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.
307
388
 
308
389
  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.
309
390
 
package/dist/lib.d.ts CHANGED
@@ -5,8 +5,8 @@ export { runRestore, restoreStatus, finishRestore } from "./restore.js";
5
5
  export { fileRestoreRecords, restoreRecordKey } from "./restore-record.js";
6
6
  export type { RestoreRecord, RestoreRecordStore, RestorePhase } from "./restore-record.js";
7
7
  export { recoveryGrantsSql } from "./grants.js";
8
- export { authRecoveryText } from "./recovery-doc.js";
9
- export type { AuthRecoveryText, RecoveryDocPlace } from "./recovery-doc.js";
8
+ export { authRecoveryText, renderRunbook, renderRecoveryDoc } from "./recovery-doc.js";
9
+ export type { AuthRecoveryText, RecoveryDocPlace, RecoveryDocSource, RecoveryDocDownloadSource, RunbookContext, DownloadRunbookContext, RecoveryDocContext } from "./recovery-doc.js";
10
10
  export { projectRefOf, assertNoHostOverride, libpqChildEnv } from "./restore-engine.js";
11
11
  export { sameDatabaseTarget } from "./restore.js";
12
12
  export { runEstimate, project } from "./estimate.js";
package/dist/lib.js CHANGED
@@ -7,9 +7,10 @@ export { SUPABASE_ROOT_CA, pgConnectOptions, PG_CLIENT_OPTIONS, normalizeConnect
7
7
  export { runDrill, drillDump } from "./drill.js";
8
8
  export { runRestore, restoreStatus, finishRestore } from "./restore.js";
9
9
  export { fileRestoreRecords, restoreRecordKey } from "./restore-record.js";
10
- // RECOVERY.md 的授权那一步和 Auth 用户那几段:worker 的 Drive 版手册和这里的 S3 版用同一份
10
+ // RECOVERY.md:自有桶、托管 worker 的 Google Drive 目标、托管存储的下载三种目标共用 renderRunbook 这一份,
11
+ // 只有"文件在哪、怎么拿到"不同。授权 SQL 和 Auth 用户那几段也单独导出(老调用方)
11
12
  export { recoveryGrantsSql } from "./grants.js";
12
- export { authRecoveryText } from "./recovery-doc.js";
13
+ export { authRecoveryText, renderRunbook, renderRecoveryDoc } from "./recovery-doc.js";
13
14
  // 身份判定三件套对外导出:托管 worker 用它们与 app 侧 shared 的副本做同规则回归(交叉审查)
14
15
  export { projectRefOf, assertNoHostOverride, libpqChildEnv } from "./restore-engine.js";
15
16
  export { sameDatabaseTarget } from "./restore.js";
@@ -6,18 +6,11 @@ import type { Manifest } from "./manifest.js";
6
6
  * 控制字符换成可见的转义,名字里的换行不会让这一段断开
7
7
  */
8
8
  export declare function markdownCode(text: string): string;
9
- /** 生成手册所需的非秘密快照坐标。刻意不收连接串/密钥类型——签名即防线。 */
10
- export interface RecoveryDocContext {
11
- snapshot: string;
12
- bucket: string;
13
- endpoint?: string;
14
- region?: string;
15
- prefix: string;
16
- projectName: string;
17
- }
18
9
  /**
19
10
  * 手册里的归档在哪。bucket = S3 兼容桶,写完整对象键;folder = 托管 worker 的 Google Drive 目标,
20
- * 手册就放在归档旁边,写文件名,name 是下载那一步说的"从哪里下"(如 "Google Drive folder")
11
+ * 手册就放在归档旁边,写文件名,name 是下载那一步说的"从哪里下"(如 "Google Drive folder");
12
+ * download = 托管存储的下载(下载脚本建的文件夹:backupdrill-download.json 索引 + files/ 下的编号文件),
13
+ * 写索引里的键 <快照名>/<文件名>
21
14
  */
22
15
  export type RecoveryDocPlace = {
23
16
  kind: "bucket";
@@ -25,6 +18,11 @@ export type RecoveryDocPlace = {
25
18
  kind: "folder";
26
19
  name: string;
27
20
  };
21
+ /** 引擎内部多一种:托管存储的下载(只由 renderRunbook 传入;导出的 RecoveryDocPlace 保持原样,不破坏下游的穷举判断) */
22
+ type RunbookPlace = RecoveryDocPlace | {
23
+ kind: "download";
24
+ snapshot: string;
25
+ };
28
26
  export interface AuthRecoveryText {
29
27
  /** "What this snapshot contains" 里 Auth 那一行(带换行);manifest 没有 auth 段时为空串 */
30
28
  contentsLine: string;
@@ -35,14 +33,61 @@ export interface AuthRecoveryText {
35
33
  } | null;
36
34
  }
37
35
  /**
38
- * RECOVERY.md 里和 Auth 用户有关的段落(2.10.0 起)。S3 版(renderRecoveryDoc)和托管 worker 的
39
- * Google Drive 版共用这一份:单事务恢复脚本里的空目标检查、清理待处理链接、行数核对,两边不能各写各的。
40
- * 没有 auth 字段的快照:included 为 null;contentsLine 只在备份范围选了 auth 时有一行(见 authMaybeInMainDump),否则为空,手册和 2.10.0 之前一样
36
+ * RECOVERY.md 里和 Auth 用户有关的段落(2.10.0 起)。S3 版、托管 worker 的 Google Drive 版和托管存储版
37
+ * 都由 renderRunbook 生成,共用这一份:单事务恢复脚本里的空目标检查、清理待处理链接、行数核对,不能各写各的。
38
+ * 没有 auth 字段的快照:included 为 null;contentsLine 只在备份范围选了 auth 时有一行(见 authMaybeInMainDump),否则为空
41
39
  */
42
40
  /**
43
41
  * 没有 auth.dump、备份范围却选了 auth 的快照:Auth 用户可能在主 dump 里。manifest 的表清单是转储前查的,
44
42
  * 证明不了归档里有(表归扩展所有、分区落在范围外、转储期间被删都会让归档里没有),手册只告诉读者怎么查,不担保
45
43
  */
46
44
  export declare function authMaybeInMainDump(manifest: Manifest): boolean;
47
- export declare function authRecoveryText(manifest: Manifest, place: RecoveryDocPlace): AuthRecoveryText;
45
+ export declare function authRecoveryText(manifest: Manifest, place: RunbookPlace): AuthRecoveryText;
46
+ /**
47
+ * 归档在哪、怎么拿到(手册里唯一随目标不同的部分)。
48
+ * - bucket:S3 兼容桶(CLI 写的 RECOVERY.md);CLI 命令用桶参数
49
+ * - drive:托管 worker 的 Google Drive 目标;开源 CLI 读不了 Drive,不给 CLI 命令
50
+ * - download:托管存储的下载(下载脚本建的文件夹);CLI 命令用 --from-dir(2.12.0 起)
51
+ */
52
+ export type RecoveryDocSource = {
53
+ kind: "bucket";
54
+ bucket: string;
55
+ endpoint?: string;
56
+ region?: string;
57
+ prefix: string;
58
+ } | {
59
+ kind: "drive";
60
+ folderPath: string;
61
+ };
62
+ /** 托管存储的下载。单独一个类型:2.13.0 导出的 RecoveryDocSource 只有 bucket 和 drive,加进去会破坏下游的穷举判断 */
63
+ export type RecoveryDocDownloadSource = {
64
+ kind: "download";
65
+ };
66
+ export interface RunbookContext {
67
+ snapshot: string;
68
+ projectName: string;
69
+ source: RecoveryDocSource;
70
+ }
71
+ /** 托管存储下载用的上下文;RunbookContext 保持 2.13.0 的样子,下游原有的赋值和判断照样编译 */
72
+ export interface DownloadRunbookContext {
73
+ snapshot: string;
74
+ projectName: string;
75
+ source: RecoveryDocDownloadSource;
76
+ }
77
+ /** 生成手册所需的非秘密快照坐标。刻意不收连接串/密钥类型——签名即防线。 */
78
+ export interface RecoveryDocContext {
79
+ snapshot: string;
80
+ bucket: string;
81
+ endpoint?: string;
82
+ region?: string;
83
+ prefix: string;
84
+ projectName: string;
85
+ }
86
+ /** S3 兼容桶里的手册(CLI 每次备份写进快照前缀) */
48
87
  export declare function renderRecoveryDoc(manifest: Manifest, ctx: RecoveryDocContext): string;
88
+ /**
89
+ * RECOVERY.md 全文。三种目标(自有桶、Google Drive、托管下载)共用这一份:恢复步骤、注意事项、授权 SQL
90
+ * 完全相同,只有"文件在哪、怎么拿到"和 CLI 命令的来源参数不同。
91
+ */
92
+ export declare function renderRunbook(manifest: Manifest, ctx: RunbookContext | DownloadRunbookContext): string;
93
+ export {};
@@ -1,6 +1,7 @@
1
1
  import { recoveryGrantsSql } from "./grants.js";
2
2
  import { plainSchemaName, restorableAuthObjects } from "./auth-backup.js";
3
3
  import { authRestoreNotes, CLEAR_PENDING_AUTH_SQL } from "./auth-restore.js";
4
+ import { SUPABASE_ROOT_CA } from "./supabase-ca.js";
4
5
  /**
5
6
  * 原样写进 RECOVERY.md 的一段文字(例如 Auth 失败的原因,里面有从系统目录读来的约束名、索引名):放进代码段里,
6
7
  * Markdown 不再解释里面的任何东西(链接、强调、HTML,GFM 也不会把裸网址自动变成链接)。按 CommonMark 的规则,
@@ -24,6 +25,95 @@ function quoteSqlIdent(name) {
24
25
  return `"${name.replace(/"/g, '""')}"`;
25
26
  }
26
27
  const ereEscape = (s) => s.replace(/[.[\]{}()*+?^$|\\]/g, "\\$&");
28
+ /**
29
+ * 手动恢复连到目标的连接串:和引擎校验 Supabase 连接一样做 verify-full,根证书见 SAVE_CA_STEP。
30
+ * 连目标的命令都在子 shell 里先 export PGGSSENCMODE=disable(和 CLI 一样不走 GSSAPI 加密绕开 TLS);
31
+ * 用环境变量而不写进连接串:12 之前的 libpq 不认 gssencmode 参数,会直接拒绝连接串
32
+ */
33
+ const TARGET_URL_TEMPLATE = "postgresql://postgres.<target-ref>@<target-pooler-host>:5432/postgres?sslmode=verify-full&sslrootcert=supabase-ca.crt";
34
+ /**
35
+ * 第 4 步开头:先存 Supabase 根证书(引擎校验源库用的同一张,所有 Supabase 项目共用),后面每个连目标的块都用它。
36
+ * 放在第 4 步而不是第 1 步:authRecoveryText 的恢复步骤会被托管 worker 单独拿去拼 Drive 手册,证书得跟着命令走
37
+ */
38
+ const SAVE_CA_STEP = ` Save Supabase's root certificate as \`supabase-ca.crt\` in the folder you run
39
+ the restore from. The connections below use it to check the Session Pooler's
40
+ certificate, as the BackupDrill CLI does:
41
+
42
+ \`\`\`bash
43
+ cat > supabase-ca.crt <<'PEM'
44
+ ${SUPABASE_ROOT_CA.trim()}
45
+ PEM
46
+ \`\`\`
47
+ `;
48
+ /** 子 shell 里读目标库密码:隐藏输入,不进连接串、命令行和 shell 历史;子 shell 结束密码就没了 */
49
+ const READ_TARGET_PASSWORD = [
50
+ "IFS= read -rs PGPASSWORD || exit; export PGPASSWORD # hidden prompt",
51
+ // 和 CLI 一样:这些环境变量能把连接改到别的地址或项目(PGOPTIONS 里的 reference 会被 Supavisor 拿去路由)
52
+ "unset PGHOSTADDR PGOPTIONS PGSERVICE PGSERVICEFILE",
53
+ "export PGGSSENCMODE=disable",
54
+ ];
55
+ /** 备份范围选了 auth、又没有单独 auth.dump 的快照:三种来源的开头都用这一句,只在这里改 */
56
+ const AUTH_IN_DUMP_OPENER = `This snapshot was set to include the
57
+ \`auth\` schema, which a new Supabase project already has: read the note at the
58
+ start of step 4 before restoring its database.`;
59
+ /** 新 Supabase 项目自带、而且里面已经有表的 schema:转储里带着它们的表,单事务恢复一定在建表时失败 */
60
+ const SUPABASE_SCHEMAS_WITH_TABLES = ["auth", "storage", "realtime"];
61
+ /**
62
+ * 生成 database.list 的几行 shell(放在 set -euo pipefail 的子 shell 里):主 dump 的目录里拿掉目标上已经有的
63
+ * schema 的 CREATE SCHEMA 条目——public、第 2 步为装扩展建好的,以及新项目自带的(比如 graphql)。和 CLI 的
64
+ * 单事务恢复(restore-engine prepareMainRestore)同一个做法:问目标库有哪些 schema,这些条目一执行就报"已存在",
65
+ * 单事务里一条错误就整体回滚。
66
+ * 目录行 "<id>; <oid> <oid> SCHEMA - <名字> <属主>" 里名字和属主都原样、都可能带空格,换行还被换成了空格,拆不准。
67
+ * 所以让 pg_restore 把每条 schema 条目写成 SQL,从 "CREATE SCHEMA " 那行取到结尾,交给目标库比:目标上某个 schema
68
+ * 按 pg_dump 的写法(fmtId:全是小写字母、数字、下划线且不以数字开头的照写,其余加双引号)写出的语句加换行,
69
+ * 是这段文字的开头,就说明它已经在。名字里有换行时语句跨行,照样比得上。
70
+ * 中间文件都在 mktemp -d 建的目录里,退出时整个删掉;写完才改名成 database.list:中途失败就没有清单,
71
+ * 后面的恢复打不开清单、什么也不做;同一目录里同时跑两次也拿不到对方的文件
72
+ */
73
+ function databaseListLines(writeDatabaseList = true) {
74
+ return [
75
+ " work=$(mktemp -d backupdrill-restore.XXXXXX)",
76
+ " trap 'rm -rf \"$work\"' EXIT",
77
+ ...(writeDatabaseList ? [" rm -f database.list"] : []),
78
+ ...READ_TARGET_PASSWORD.map((line) => ` ${line}`),
79
+ ' pg_restore -l dump.pgcustom > "$work/full.list"',
80
+ " schema_entry='^[0-9]+; [0-9]+ [0-9]+ SCHEMA - '",
81
+ " while IFS= read -r entry; do",
82
+ " if [[ $entry =~ $schema_entry ]]; then",
83
+ " printf '%s\\n' \"$entry\" > \"$work/entry.list\"",
84
+ " create=$(pg_restore -O -L \"$work/entry.list\" -f - dump.pgcustom | sed -n '/^CREATE SCHEMA /,$p')",
85
+ ` exists=$(psql -X -At -v ON_ERROR_STOP=1 -v create="$create" --dbname "${TARGET_URL_TEMPLATE}" <<'SQL'`,
86
+ "select exists (select 1 from pg_namespace n,",
87
+ " lateral (values ('CREATE SCHEMA \"' || replace(n.nspname, '\"', '\"\"') || '\";'),",
88
+ " (case when n.nspname ~ '^[a-z_][a-z0-9_]*$' then 'CREATE SCHEMA ' || n.nspname || ';' end)) c(s)",
89
+ " where starts_with(:'create', c.s || E'\\n'));",
90
+ "SQL",
91
+ " )",
92
+ ' if [ "$exists" = t ]; then continue; fi',
93
+ " fi",
94
+ " printf '%s\\n' \"$entry\"",
95
+ ' done < "$work/full.list" > "$work/database.list"',
96
+ ...(writeDatabaseList ? [' mv "$work/database.list" database.list'] : []),
97
+ ];
98
+ }
99
+ /**
100
+ * 转储里带着新项目自带、已经有表的 schema(auth、storage、realtime)时,单事务恢复一定在建这些表时回滚。
101
+ * 如实写出来,不让读者照做到失败才知道
102
+ */
103
+ function supabaseSchemaConflict(manifest) {
104
+ // auth 和开头用同一个判断(包括老 manifest 里 au* 这类模式加 schemas_include_auth 的情况)
105
+ const conflicting = SUPABASE_SCHEMAS_WITH_TABLES.filter((name) => name === "auth" ? authMaybeInMainDump(manifest) : schemaSelected(manifest, name));
106
+ if (!conflicting.length)
107
+ return "";
108
+ const quoted = conflicting.map((name) => `\`${name}\``);
109
+ const names = quoted.length === 1 ? quoted[0] : `${quoted.slice(0, -1).join(", ")} and ${quoted[quoted.length - 1]}`;
110
+ return ` This snapshot's schema list includes ${names}. A new Supabase project already
111
+ has ${conflicting.length === 1 ? "that schema" : "those schemas"}, with tables of its own: if the dump creates any of those
112
+ tables again, the restore rolls back there. If that happens, email
113
+ support@backupdrill.com with the project name and the snapshot time.
114
+
115
+ `;
116
+ }
27
117
  const AUTH_NOT_INCLUDED_TEXT = {
28
118
  no_permission: "the backup role couldn't read every row of the Auth tables",
29
119
  no_auth_schema: "the source database has no Supabase auth schema",
@@ -39,10 +129,21 @@ const AUTH_NOT_INCLUDED_TEXT = {
39
129
  function shellQuote(value) {
40
130
  return /^[A-Za-z0-9._/:@=-]+$/.test(value) ? value : `'${value.replace(/'/g, `'\\''`)}'`;
41
131
  }
132
+ /** 托管下载里的"取出归档"那一句(第 3 步开头):按索引里的键找到编号文件,复制成原文件名 */
133
+ function downloadGetArchives(snapshot, withAuth) {
134
+ return withAuth
135
+ ? `3. Get both archives out of the download: in \`backupdrill-download.json\`, the
136
+ entries whose \`key\` is \`${snapshot}/dump.pgcustom\` and \`${snapshot}/auth.dump\`
137
+ each have a \`path\` (such as \`files/000002\`). Copy those two files to
138
+ \`dump.pgcustom\` and \`auth.dump\`, then verify them:`
139
+ : `3. Get the dump out of the download: in \`backupdrill-download.json\`, the entry
140
+ whose \`key\` is \`${snapshot}/dump.pgcustom\` has a \`path\` (such as
141
+ \`files/000002\`). Copy that file to \`dump.pgcustom\`, then verify it:`;
142
+ }
42
143
  /**
43
- * RECOVERY.md 里和 Auth 用户有关的段落(2.10.0 起)。S3 版(renderRecoveryDoc)和托管 worker 的
44
- * Google Drive 版共用这一份:单事务恢复脚本里的空目标检查、清理待处理链接、行数核对,两边不能各写各的。
45
- * 没有 auth 字段的快照:included 为 null;contentsLine 只在备份范围选了 auth 时有一行(见 authMaybeInMainDump),否则为空,手册和 2.10.0 之前一样
144
+ * RECOVERY.md 里和 Auth 用户有关的段落(2.10.0 起)。S3 版、托管 worker 的 Google Drive 版和托管存储版
145
+ * 都由 renderRunbook 生成,共用这一份:单事务恢复脚本里的空目标检查、清理待处理链接、行数核对,不能各写各的。
146
+ * 没有 auth 字段的快照:included 为 null;contentsLine 只在备份范围选了 auth 时有一行(见 authMaybeInMainDump),否则为空
46
147
  */
47
148
  /**
48
149
  * 没有 auth.dump、备份范围却选了 auth 的快照:Auth 用户可能在主 dump 里。manifest 的表清单是转储前查的,
@@ -51,23 +152,53 @@ function shellQuote(value) {
51
152
  export function authMaybeInMainDump(manifest) {
52
153
  if (manifest.auth?.status === "included")
53
154
  return false;
54
- return manifest.database.schemas.includes("auth") || manifest.auth?.reason === "schemas_include_auth";
155
+ return schemaSelected(manifest, "auth") || manifest.auth?.reason === "schemas_include_auth";
156
+ }
157
+ /** 2.12.1 之前的 manifest 记的是用户写的 --schema 模式,之后记的是在源库上解析出的真实名字(见 manifest.ts) */
158
+ function schemasArePatterns(manifest) {
159
+ const m = /^(\d+)\.(\d+)\.(\d+)/.exec(manifest.toolVersion);
160
+ if (!m)
161
+ return false;
162
+ const [major, minor, patch] = m.slice(1).map(Number);
163
+ return major < 2 || (major === 2 && (minor < 12 || (minor === 12 && patch < 1)));
164
+ }
165
+ /**
166
+ * 备份范围里有没有选这个 schema。2.12.1 起记的是真实名字,只认完全相同(源库里可以真有一个叫 AUTH 的 schema);
167
+ * 更早的 manifest 记的是模式:"auth"、AUTH(不加引号会折成小写)、带双引号的 "auth" 都算
168
+ */
169
+ function schemaSelected(manifest, name) {
170
+ const schemas = manifest.database.schemas;
171
+ if (!schemasArePatterns(manifest))
172
+ return schemas.includes(name);
173
+ return schemas.some((pattern) => pattern === name || pattern === `"${name}"` || plainSchemaName(pattern) === name);
174
+ }
175
+ /**
176
+ * Storage 访问策略(storage.objects 上的策略)在不在转储里:选了 storage 就在;老 manifest 里有认不出的模式
177
+ * (通配、带引号的其他写法)时说不准,手册教读者自己查,不下结论
178
+ */
179
+ function storagePolicyCoverage(manifest) {
180
+ if (schemaSelected(manifest, "storage"))
181
+ return "included";
182
+ const unclear = schemasArePatterns(manifest) &&
183
+ manifest.database.schemas.some((pattern) => plainSchemaName(pattern) === null && !/^"[^"]+"$/.test(pattern));
184
+ return unclear ? "unknown" : "missing";
55
185
  }
56
186
  export function authRecoveryText(manifest, place) {
57
187
  const db = manifest.database;
58
188
  const mb = (bytes) => (bytes / 1024 / 1024).toFixed(1);
59
189
  // 只有 included 的快照带 auth.dump
60
190
  const auth = manifest.auth?.status === "included" ? manifest.auth : null;
61
- const dumpFile = place.kind === "bucket" ? manifest.dump.key : "dump.pgcustom";
62
- const authFile = place.kind === "bucket" ? (auth?.dump?.key ?? "auth.dump") : "auth.dump";
63
- const authListing = place.kind === "bucket" ? `\`${authFile}\`` : "`auth.dump` in this folder";
64
- const container = place.kind === "bucket" ? "bucket" : place.name;
191
+ const authListing = place.kind === "bucket"
192
+ ? `\`${auth?.dump?.key ?? "auth.dump"}\``
193
+ : place.kind === "download"
194
+ ? `\`${place.snapshot}/auth.dump\``
195
+ : "`auth.dump` in this folder";
65
196
  const authLine = auth
66
197
  ? `- **Supabase Auth users**: ${authListing}
67
198
  (pg_dump custom format, ${mb(auth.dump.bytes)} MB, sha256 \`${auth.dump.sha256}\`) — ${auth.rows.users.toLocaleString("en-US")} users, ${auth.rows.identities.toLocaleString("en-US")} sign-in identities
68
199
  `
69
200
  : authMaybeInMainDump(manifest)
70
- ? `- **Supabase Auth users**: this snapshot has no separate \`auth.dump\`. The schema list selected \`auth\`, so the database dump may hold them. Before restoring Auth users, run \`pg_restore --list dump.pgcustom\` and look for \`TABLE DATA\` entries for \`auth.users\` and \`auth.identities\`.
201
+ ? `- **Supabase Auth users**: this snapshot has no separate \`auth.dump\`. The schema list selected \`auth\`, so the database dump may hold them. To check, run \`pg_restore --list dump.pgcustom\` and look for \`TABLE DATA\` entries for \`auth.users\` and \`auth.identities\`.
71
202
  `
72
203
  : manifest.auth
73
204
  ? `- **Supabase Auth users**: not in this snapshot (${AUTH_NOT_INCLUDED_TEXT[manifest.auth.reason ?? ""] ?? markdownCode(manifest.auth.reason ?? "not captured")})
@@ -97,34 +228,51 @@ export function authRecoveryText(manifest, place) {
97
228
  : [];
98
229
  if (!auth)
99
230
  return { contentsLine: authLine, included: null };
231
+ const storagePolicies = storagePolicyCoverage(manifest) === "missing" ? "Storage access policies, " : "";
100
232
  const notCovered = `Supabase **Auth sessions and MFA factors, Auth settings (sign-in providers,
101
- SMTP, redirect URLs, email templates), secret values, Edge Function code and most
102
- platform settings are NOT in this snapshot**. After restoring, reconfigure them
103
- by hand; everyone signs in once more. The Auth users themselves (IDs, emails,
104
- password hashes, sign-in identities) are in this snapshot and are restored in
105
- step 4 below, together with the database.
233
+ SMTP, redirect URLs, email templates), ${storagePolicies}secret values, Edge Function
234
+ code and most platform settings aren't in this snapshot**. In the new project,
235
+ re-enter your secrets and redeploy your Edge Functions from your copies. Reapply
236
+ any other project settings your app depends on, and set up your sign-in providers,
237
+ SMTP, redirect URLs and email templates again.${storagePolicies ? " Recreate your policies on `storage.objects`." : ""} Sessions don't carry over, so users
238
+ sign in again, and users who had MFA enroll again. The Auth users themselves
239
+ (IDs, emails, password hashes, sign-in identities) are in this snapshot and are
240
+ restored in step 4 below, together with the database.
106
241
  ${authNotes.length ? `\n${authNotes.join("\n")}\n` : ""}`;
107
- const restoreSteps = `3. Download \`${dumpFile}\` and \`${authFile}\` from this
108
- ${container}, then verify them:
242
+ const getArchives = place.kind === "download"
243
+ ? downloadGetArchives(place.snapshot, true)
244
+ : `3. Download \`${place.kind === "bucket" ? manifest.dump.key : "dump.pgcustom"}\` and \`${place.kind === "bucket" ? (auth.dump?.key ?? "auth.dump") : "auth.dump"}\` from this
245
+ ${place.kind === "bucket" ? "bucket" : place.name}, then verify them:`;
246
+ const restoreSteps = `${getArchives}
109
247
 
110
248
  \`\`\`bash
111
249
  shasum -a 256 dump.pgcustom # must print ${manifest.dump.sha256}
112
250
  shasum -a 256 auth.dump # must print ${auth.dump.sha256}
113
251
  \`\`\`
114
252
 
115
- 4. Restore the Auth users and the database **in one transaction**, so any error
116
- leaves the target exactly as it was and you can simply run it again. First turn
117
- both archives into one SQL file; go on only if the last line prints
118
- \`restore.sql is complete\` (a half-written file would otherwise be committed):
253
+ 4. Restore the Auth users and the database **in one transaction**.
254
+ ${SAVE_CA_STEP}
255
+ Use \`pg_restore\` and \`psql\` from the same PostgreSQL client package, at least
256
+ as new as the version listed above and at least 17.6, 16.10, 15.14, 14.19 or
257
+ 13.22 in their series (18 and newer are fine): older releases let an archive run
258
+ commands on your machine through psql. pg_restore 17 and newer write
259
+ \`SET transaction_timeout\`, which PostgreSQL 16 and older reject, so with those,
260
+ check that the target runs PostgreSQL 17 or newer.
261
+
262
+ Then turn both archives into one SQL file, \`restore.sql\`. The block asks the
263
+ target which schemas it already has: when the terminal pauses, type the target's
264
+ database password and press Enter (nothing shows while you type, and the password
265
+ stays out of the URL, the command line and your shell history). Go on only if the
266
+ last line prints \`restore.sql is complete\`:
119
267
 
120
268
  \`\`\`bash
121
269
  (
122
270
  set -euo pipefail
123
- pg_restore -l dump.pgcustom > database.full.list
124
- grep -Ev '^[0-9]+; [0-9]+ [0-9]+ SCHEMA - public ' database.full.list > database.list
125
- ${authObjects.length ? ` pg_restore -l auth.dump > auth.full.list
126
- grep -E '^[0-9]+; [0-9]+ [0-9]+ (${authObjectsGrep}) ' auth.full.list > auth-objects.list
127
- test "$(wc -l < auth-objects.list)" -eq ${authObjects.length}
271
+ rm -f restore.sql
272
+ ${databaseListLines(false).join("\n")}
273
+ ${authObjects.length ? ` pg_restore -l auth.dump > "$work/auth.full.list"
274
+ grep -E '^[0-9]+; [0-9]+ [0-9]+ (${authObjectsGrep}) ' "$work/auth.full.list" > "$work/auth-objects.list"
275
+ test "$(wc -l < "$work/auth-objects.list")" -eq ${authObjects.length}
128
276
  ` : ""} {
129
277
  cat <<'SQL'
130
278
  lock table auth.users, auth.identities in share row exclusive mode;
@@ -154,43 +302,72 @@ do $bd$ begin
154
302
  end if;
155
303
  end $bd$;
156
304
  SQL
157
- pg_restore --no-owner --no-privileges -L database.list -f - dump.pgcustom
158
- ${authObjects.length ? ` pg_restore --no-owner --no-privileges -L auth-objects.list -f - auth.dump
159
- ` : ""} } > restore.sql
305
+ pg_restore --no-owner --no-privileges -L "$work/database.list" -f - dump.pgcustom
306
+ ${authObjects.length ? ` pg_restore --no-owner --no-privileges -L "$work/auth-objects.list" -f - auth.dump
307
+ ` : ""} } > "$work/restore.sql"
308
+ mv "$work/restore.sql" restore.sql
160
309
  echo "restore.sql is complete"
161
310
  )
162
311
  \`\`\`
163
312
 
164
- Then run it against the empty target. pg_restore 17 and newer write
165
- \`SET transaction_timeout\`, which PostgreSQL 16 and older reject, so restore into
166
- a PostgreSQL 17+ project (new Supabase projects are) or generate the file with a
167
- pg_restore matching the target. Enter the password at a hidden prompt so it never
168
- touches the URL, argv, or shell history:
313
+ Then run it against the empty target. Type the password again when the terminal
314
+ pauses, and wait for \`restore committed\` before setting the grants:
169
315
 
170
316
  \`\`\`bash
171
- read -rs PGPASSWORD && export PGPASSWORD # hidden prompt
172
- psql -X --single-transaction -v ON_ERROR_STOP=1 \\
173
- --dbname "postgresql://postgres.<target-ref>@<target-pooler-host>:5432/postgres" -f restore.sql
174
- unset PGPASSWORD
317
+ (
318
+ set -euo pipefail
319
+ ${READ_TARGET_PASSWORD.map((line) => ` ${line}`).join("\n")}
320
+ psql -X --single-transaction -v ON_ERROR_STOP=1 \\
321
+ --dbname "${TARGET_URL_TEMPLATE}" -f restore.sql
322
+ echo "restore committed"
323
+ )
175
324
  \`\`\`
176
325
 
177
326
  The script stops if the target already has Auth users, triggers or policies on the
178
327
  Auth tables, or tables in the restored schemas, so it never merges into an
179
- existing project. The Auth users go in first, so foreign keys into
180
- \`auth.users\` resolve, and their count is checked against this snapshot. Links
181
- and codes for password resets, email confirmations and email or phone changes
182
- that were pending at backup time are cleared. ${authObjects.length
183
- ? "Your triggers on the Auth tables are recreated at the end."
184
- : "There are no triggers of your own on the Auth tables to recreate."} Do **not** use \`--clean\` against a Supabase project: it drops and
328
+ existing project. It loads the Auth users first and keeps their original IDs, then
329
+ checks the \`auth.users\` and \`auth.identities\` row counts against this snapshot;
330
+ PostgreSQL can still reject a foreign key whose user isn't in the snapshot. Links and codes for password resets, email confirmations and email or
331
+ phone changes that were pending at backup time are cleared. ${authObjects.length
332
+ ? "The script recreates the triggers on the Auth tables that it can; the notes under \"Not covered\" list any trigger or policy left for you to recreate."
333
+ : "The script recreates no triggers on the Auth tables; the notes under \"Not covered\" list any trigger or policy left for you to recreate."} An error before the commit rolls the restore back: the Auth users and the
334
+ snapshot's tables aren't left on the target, but the extensions from step 2 stay
335
+ installed, and a sequence that already existed there (such as one belonging to an
336
+ extension) can keep a new value. Fix the cause and run it again. If the connection
337
+ drops during the commit, reconnect and check for one of the snapshot's tables that
338
+ wasn't on the target before${auth.rows.users > 0
339
+ ? `, or whether \`auth.users\`, empty before, now has ${auth.rows.users} rows`
340
+ : ""}. Run it again only once you've confirmed the restore rolled back. If a foreign
341
+ key reports a missing parent row, use the table and key values in the error to see
342
+ what the restore is missing; ${place.kind === "folder"
343
+ ? "email support@backupdrill.com with the snapshot time and the constraint name from the error."
344
+ : "`backupdrill restore` can add such a key as `NOT VALID` after the commit when the snapshot has both tables and their data. That excludes keys involving partitioned tables, extension tables or generated columns, and if the CLI can't match the foreign key definitions to the archive's list, it keeps all of them in the main transaction."} Do **not** use \`--clean\` against a Supabase project: it drops and
185
345
  recreates \`public\`, and the grants Supabase put on it go with it.
186
346
  `;
187
347
  return { contentsLine: authLine, included: { notCovered, restoreSteps } };
188
348
  }
349
+ /** S3 兼容桶里的手册(CLI 每次备份写进快照前缀) */
189
350
  export function renderRecoveryDoc(manifest, ctx) {
351
+ return renderRunbook(manifest, {
352
+ snapshot: ctx.snapshot,
353
+ projectName: ctx.projectName,
354
+ source: { kind: "bucket", bucket: ctx.bucket, endpoint: ctx.endpoint, region: ctx.region, prefix: ctx.prefix },
355
+ });
356
+ }
357
+ /**
358
+ * RECOVERY.md 全文。三种目标(自有桶、Google Drive、托管下载)共用这一份:恢复步骤、注意事项、授权 SQL
359
+ * 完全相同,只有"文件在哪、怎么拿到"和 CLI 命令的来源参数不同。
360
+ */
361
+ export function renderRunbook(manifest, ctx) {
362
+ const source = ctx.source;
363
+ // 快照目录,和 CLI 读 Storage 时一样从 dump 的键反推(snapshot-store storageBaseOf),写手册不能和读取各算各的
190
364
  const base = manifest.dump.key.replace(/\/dump\.pgcustom$/, "");
365
+ // 清单这类和 dump 放在一起的文件:按 dump 所在目录拼;dump 在桶根时就在桶根(Storage 路径另按上面 CLI 的算法)
366
+ const dumpDir = manifest.dump.key.includes("/") ? manifest.dump.key.slice(0, manifest.dump.key.lastIndexOf("/") + 1) : "";
191
367
  const db = manifest.database;
192
368
  const extensions = db.extensions ?? [];
193
- const storage = manifest.storage;
369
+ // Google Drive 备份只有数据库:manifest 里即使带了 Storage 段,Drive 版也一律按没有 Storage 写,不自相矛盾
370
+ const storage = source.kind === "drive" ? null : manifest.storage;
194
371
  // 授权 SQL 里有取自源库的 schema 和对象名,可能带反引号:围栏比 SQL 里最长的一串反引号还长,名字关不掉它
195
372
  const grantsSql = recoveryGrantsSql(db);
196
373
  let longestBacktickRun = 0;
@@ -210,75 +387,182 @@ export function renderRecoveryDoc(manifest, ctx) {
210
387
  `create extension if not exists ${quoteSqlIdent(e.name)} schema ${quoteSqlIdent(e.schema)} cascade;`)
211
388
  .join("\n")
212
389
  : "-- (this snapshot records no extensions)";
390
+ // 文件在哪:清单里怎么称呼一个文件,第 3 步怎么拿到 dump
391
+ const fileRef = (name) => source.kind === "bucket"
392
+ ? `\`${name === "dump.pgcustom" ? manifest.dump.key : `${dumpDir}${name}`}\``
393
+ : source.kind === "download"
394
+ ? `\`${ctx.snapshot}/${name}\``
395
+ : `\`${name}\` in this folder`;
396
+ const storageLocation = source.kind === "bucket"
397
+ ? `\`${base}/storage/<bucket>/<key>\``
398
+ : source.kind === "download"
399
+ ? `\`${ctx.snapshot}/storage/<bucket>/<key>\``
400
+ : "`storage/<bucket>/<key>` in this folder";
401
+ const place = source.kind === "bucket"
402
+ ? { kind: "bucket" }
403
+ : source.kind === "download"
404
+ ? { kind: "download", snapshot: ctx.snapshot }
405
+ : { kind: "folder", name: "Google Drive folder" };
213
406
  // Auth 用户(2.10.0 起):没有 auth 字段的快照,下面用到的三段都和以前一样
214
- const authText = authRecoveryText(manifest, { kind: "bucket" });
407
+ const authText = authRecoveryText(manifest, place);
215
408
  const auth = authText.included;
409
+ // 备份范围选了 auth:主 dump 里有整个 auth schema,新项目自带 auth schema,手动和 CLI 都恢复不了它,
410
+ // 备份范围选了 auth、又没有单独 auth.dump:开头换成提醒先读第 4 步,不给 CLI 那一节(CLI 的空目标检查必然拦下);手动步骤照给
411
+ const authInDump = authMaybeInMainDump(manifest);
412
+ // 不给 CLI 那一节的地方(Drive;备份范围选了 auth 的快照,CLI 的空目标检查必然拦下),正文也不拿 CLI 当退路
413
+ const hasCli = source.kind !== "drive" && !authMaybeInMainDump(manifest);
414
+ const storagePolicies = storagePolicyCoverage(manifest) === "missing" ? "Storage access policies, " : "";
216
415
  // 2.0 形态:凭据只经环境变量(argv 对全机器可见);写入需要键入目标 ref 确认。
217
416
  // DB-only 快照不出现 Storage 凭据与旗标——不为用不上的能力索要宽权限 key
417
+ const sourceArgs = source.kind === "bucket"
418
+ ? [
419
+ ` --snapshot ${shellQuote(ctx.snapshot)} \\`,
420
+ ` --bucket ${shellQuote(source.bucket)} \\`,
421
+ ...(source.endpoint ? [` --endpoint ${shellQuote(source.endpoint)} \\`] : []),
422
+ ...(source.region ? [` --region ${shellQuote(source.region)} \\`] : []),
423
+ ` --prefix ${shellQuote(source.prefix)} \\`,
424
+ ` --project-name ${shellQuote(ctx.projectName)} \\`,
425
+ ]
426
+ : [` --from-dir "<download folder>" \\`];
218
427
  const cliRestoreCommand = [
219
428
  `read -rs BACKUPDRILL_TARGET_DATABASE_URL && export BACKUPDRILL_TARGET_DATABASE_URL # hidden prompt`,
220
429
  ...(storage
221
430
  ? [`read -rs BACKUPDRILL_TARGET_SERVICE_ROLE_KEY && export BACKUPDRILL_TARGET_SERVICE_ROLE_KEY`]
222
431
  : []),
223
432
  `backupdrill restore \\`,
224
- ` --snapshot ${shellQuote(ctx.snapshot)} \\`,
225
- ` --bucket ${shellQuote(ctx.bucket)} \\`,
226
- ...(ctx.endpoint ? [` --endpoint ${shellQuote(ctx.endpoint)} \\`] : []),
227
- ...(ctx.region ? [` --region ${shellQuote(ctx.region)} \\`] : []),
228
- ` --prefix ${shellQuote(ctx.prefix)} \\`,
229
- ` --project-name ${shellQuote(ctx.projectName)} \\`,
433
+ ...sourceArgs,
230
434
  ` --database \\`,
231
435
  ...(storage ? [` --target-supabase-url https://<target-ref>.supabase.co \\`] : []),
232
436
  ` --confirm-target <target-ref>`,
233
437
  ].join("\n");
234
- // 没有 Auth 的快照:以下两段与 2.10.0 之前逐字一致。备份范围选了 auth 的快照另说:Auth 用户可能在主 dump 里,
235
- // 这里只列确实缺的东西,怎么查写在清单那一行
438
+ const cliHeading = auth ? "The BackupDrill CLI" : "Easiest path — the BackupDrill CLI";
439
+ const snapshotKind = storage
440
+ ? storage.partial
441
+ ? "This is a database snapshot with part of the Storage files (see above), not a full project image."
442
+ : "This is a database + Storage snapshot, not a full project image."
443
+ : "This is a database snapshot, not a full project image.";
444
+ // 没有 Auth 的快照。备份范围选了 auth 的快照另说:Auth 用户在主 dump 里,这里只列确实缺的东西
236
445
  const notCovered = auth
237
446
  ? auth.notCovered
238
- : authMaybeInMainDump(manifest)
239
- ? `Secret values, Edge Function code and most platform settings are **NOT in this
240
- snapshot**. After restoring, reconfigure them by hand.
447
+ : authInDump
448
+ ? `Supabase **Auth settings (sign-in providers, SMTP, redirect URLs, email templates),
449
+ ${storagePolicies}secret values, Edge Function code and most platform settings aren't
450
+ in this snapshot**. In the new project, re-enter your secrets and redeploy your Edge
451
+ Functions from your copies. Reapply any other project settings your app depends on,
452
+ and set up your sign-in providers, SMTP, redirect URLs and email templates again.${storagePolicies ? " Recreate your policies on `storage.objects`." : ""}
241
453
  `
242
- : `Supabase **Auth users/sessions, secret values, Edge Function code and most
243
- platform settings are NOT in this snapshot**. After restoring, reconfigure them
244
- by hand. This is a database + Storage snapshot, not a full project image.
245
- ${db.schemas.includes("auth")
246
- ? ""
247
- : `
454
+ : `Supabase **Auth users/sessions, ${storagePolicies}secret values, Edge Function code and
455
+ most platform settings aren't in this snapshot**. In the new project, re-enter your
456
+ secrets and redeploy your Edge Functions from your copies. Reapply your project
457
+ settings.${storagePolicies ? " Recreate your policies on `storage.objects`." : ""} ${snapshotKind}
458
+
248
459
  If a table in this snapshot has a foreign key into \`auth.users\` (a \`profiles.id\`
249
- that references it, for example), copy the Auth users into the new project
250
- **before** restoring, or that foreign key can't be created and the restore fails.
251
- \`backupdrill restore --dry-run\` checks those keys against the new project and reports
252
- the rows that have no user, plus any key it couldn't check.
460
+ that references it, for example), copy the Auth users into the new project,
461
+ keeping their original IDs, **before** restoring. When the restore adds such a key,
462
+ PostgreSQL checks the existing rows (it skips keys marked \`NOT VALID\` and, from
463
+ PostgreSQL 18, \`NOT ENFORCED\`): a row that points at a user the new project
464
+ doesn't have makes the restore stop before it commits. To see whether the dump has such keys, run
465
+ \`pg_restore --section=post-data -f - dump.pgcustom | grep -B1 -E 'REFERENCES "?auth"?\\."?users"?\\('\`.
466
+ If the old project and its users are gone for good, you can still restore the data
467
+ without those keys: the search shows each key's table (\`ALTER TABLE ONLY <table>\`)
468
+ and name (\`ADD CONSTRAINT <name>\`).
469
+ After the block in step 4 that writes \`database.list\`, delete the matching
470
+ \`FK CONSTRAINT <schema> <table> <name>\` lines from it, and the
471
+ \`COMMENT <schema> CONSTRAINT <name> ON <table>\` line of any key that has a comment,
472
+ before running the restore. Then add the keys back once the users exist, or as \`NOT VALID\` if some rows will
473
+ never have one. If PostgreSQL rejects \`NOT VALID\` on a partitioned table, leave
474
+ that key out until every row points to an existing user.${hasCli
475
+ ? `
476
+ The CLI command under "${cliHeading}" below, run with \`--dry-run\` added (it needs
477
+ \`--database\` and the target connection string), checks those keys against the
478
+ new project: look for \`references outside the backup\` in its output. It reports
479
+ missing \`auth.users\` references for the keys PostgreSQL checks during the
480
+ restore, with row counts where it has them, and warns about checks it couldn't
481
+ complete.`
482
+ : ""}
253
483
  Triggers on \`auth.users\` aren't in this snapshot either; recreate them afterwards.
254
- `}`;
484
+ `;
485
+ const getDump = source.kind === "download"
486
+ ? downloadGetArchives(ctx.snapshot, false)
487
+ : `3. Download \`${source.kind === "bucket" ? manifest.dump.key : "dump.pgcustom"}\` from this ${source.kind === "bucket" ? "bucket" : "Google Drive folder"}, then verify it:`;
255
488
  const restoreSteps = auth
256
489
  ? auth.restoreSteps
257
- : `3. Download \`${manifest.dump.key}\` from this bucket, then verify it:
490
+ : `${getDump}
258
491
 
259
492
  \`\`\`bash
260
493
  shasum -a 256 dump.pgcustom # must print ${manifest.dump.sha256}
261
494
  \`\`\`
262
495
 
263
- 4. Restore — **without \`--clean\`**, into the empty target. Enter the password at
264
- a hidden prompt so it never touches the URL, argv, or shell history:
496
+ 4. Restore the database **in one transaction**.
497
+ ${supabaseSchemaConflict(manifest)}${SAVE_CA_STEP}
498
+ Then write \`database.list\`, the archive's list without the \`CREATE SCHEMA\`
499
+ entries for schemas the target already has (\`public\`, the ones created for
500
+ extensions in step 2, and any other the new project comes with). The block uses
501
+ \`psql\` to ask the target which schemas it has: when the terminal pauses, type
502
+ the target's database password and press Enter (nothing shows while you type, and
503
+ the password stays out of the URL, the command line and your shell history). Go
504
+ on only if the last line prints \`database.list is ready\`:
505
+
506
+ \`\`\`bash
507
+ (
508
+ set -euo pipefail
509
+ ${databaseListLines().join("\n")}
510
+ echo "database.list is ready"
511
+ )
512
+ \`\`\`
513
+
514
+ Then restore into the empty target, **without \`--clean\`**, with a \`pg_restore\`
515
+ at least as new as the version listed above. pg_restore 17 and newer write
516
+ \`SET transaction_timeout\`, which PostgreSQL 16 and older reject, so with those,
517
+ check that the target runs PostgreSQL 17 or newer. Type the password again when
518
+ the terminal pauses, and wait for \`restore committed\` before setting the grants:
265
519
 
266
520
  \`\`\`bash
267
- read -rs PGPASSWORD && export PGPASSWORD # hidden prompt
268
- pg_restore --no-owner --no-privileges \\
269
- --dbname "postgresql://postgres.<target-ref>@<target-pooler-host>:5432/postgres" dump.pgcustom
270
- unset PGPASSWORD
521
+ (
522
+ set -euo pipefail
523
+ ${READ_TARGET_PASSWORD.map((line) => ` ${line}`).join("\n")}
524
+ pg_restore --single-transaction --exit-on-error --no-owner --no-privileges -L database.list \\
525
+ --dbname "${TARGET_URL_TEMPLATE}" dump.pgcustom
526
+ echo "restore committed"
527
+ )
271
528
  \`\`\`
272
529
 
273
- One error is expected and harmless: \`schema "public" already exists\` (the
274
- target always has it). A foreign key error mentioning \`auth.users\` means the
275
- Auth users were not copied in first (see "Not covered" above). Do **not** use \`--clean\` against a Supabase project:
530
+ An error before the commit rolls the restore back: the snapshot's tables aren't
531
+ left on the target, but the extensions from step 2 stay installed, and a sequence
532
+ that already existed there (such as one belonging to an extension) can keep a new
533
+ value. Fix the cause and run it again. If the connection drops during the commit,
534
+ reconnect and check for one of the snapshot's tables that wasn't on the target
535
+ before. Run it again only once you've confirmed the restore rolled back.
536
+ If a foreign key into \`auth.users\`
537
+ fails with \`is not present in table "users"\`, some restored rows point at users
538
+ the new project doesn't have: copy those users in first, keeping their IDs (see
539
+ "Not covered" above). If another foreign key reports a missing parent row, use the
540
+ table and key values in the error to see what the restore is missing. If you need
541
+ the data before you can fix that, delete that key's \`FK CONSTRAINT\` line from
542
+ \`database.list\` (and its \`COMMENT ... CONSTRAINT\` line, if the key has a
543
+ comment), run the restore again, and add the key back after fixing the reference.${hasCli
544
+ ? " `backupdrill restore` can add such a key as `NOT VALID` after the commit when the snapshot has both tables and their data. That excludes keys involving partitioned tables, extension tables or generated columns, and if the CLI can't match the foreign key definitions to the archive's list, it keeps all of them in the main transaction."
545
+ : ""} Do **not** use \`--clean\` against a Supabase project:
276
546
  it drops and recreates \`public\`, and the grants Supabase put on it go with it.
277
547
  `;
278
- const cliSection = auth
279
- ? `## The BackupDrill CLI
548
+ // 前面空一行:接在 --status 的列表后面时,不空行会被 Markdown 并进最后一条
549
+ const storageResume = storage
550
+ ? `
551
+
552
+ If the Storage part is interrupted after the database restore committed, run the
553
+ same command again without \`--database\`, skipping the line that reads
554
+ \`BACKUPDRILL_TARGET_DATABASE_URL\`, to retry Storage alone. Files already in the
555
+ target whose size and SHA-256 match the snapshot are skipped; if one differs, the
556
+ CLI stops without writing anything.`
557
+ : "";
558
+ const dryRunLine = `Run the command with \`--dry-run\` first: it checks the archive and the target
559
+ without changing the target.`;
560
+ const cliSection = !hasCli
561
+ ? ""
562
+ : auth
563
+ ? `## ${cliHeading}
280
564
 
281
- \`backupdrill restore\` 2.10.0 and newer does step 4 for you: the Auth users and the
565
+ \`backupdrill restore\` ${source.kind === "download" ? "2.12.0" : "2.10.0"} and newer does step 4 for you: the Auth users and the
282
566
  database go in one transaction, and it checks the target before writing anything.
283
567
  It needs \`psql\` from the same PostgreSQL client package as \`pg_restore\`.
284
568
 
@@ -287,62 +571,88 @@ npm install -g backupdrill
287
571
  ${cliRestoreCommand}
288
572
  \`\`\`
289
573
 
290
- Add \`--dry-run\` first to preview every check without writing anything. (Skip the
291
- \`read\` lines to have the CLI prompt you itself; \`unset\` the variables afterwards.)
292
- If it's interrupted while committing, run \`backupdrill restore --status\` with the same
293
- \`BACKUPDRILL_TARGET_DATABASE_URL\` on the same machine: it says whether the restore
294
- committed. If it did and the grants or foreign keys after the commit didn't finish,
295
- \`backupdrill restore --finish --confirm-target <target-ref>\` with the same settings
296
- does them. \`--skip-auth\` restores the database without the Auth users.
574
+ ${dryRunLine} (Skip the \`read\` lines to have the CLI prompt you itself; \`unset\` the
575
+ variables afterwards.) \`--skip-auth\` restores the database without the Auth users.
576
+
577
+ If it's interrupted while committing, run \`backupdrill restore --status\` on the same
578
+ machine with the same \`BACKUPDRILL_TARGET_DATABASE_URL\`:
579
+
580
+ - \`in progress\`: wait and check again;
581
+ - \`aborted\`: the restore rolled back; fix the cause and run it again;
582
+ - \`committed\`: the database transaction committed; if it says the grants or foreign keys after the commit may be missing, run
583
+ \`backupdrill restore${source.kind === "download" ? ' --from-dir "<download folder>"' : ""} --finish --confirm-target <target-ref>\` with the same settings${storage ? ". If Storage files are still missing, follow the Storage retry below" : ""};
584
+ - "This target isn't the database the record was written for": if
585
+ \`BACKUPDRILL_TARGET_DATABASE_URL\` points somewhere else, set it to the target you
586
+ restored into and run \`backupdrill restore --status\` again; if the database was
587
+ recreated since, its contents can't tell you what happened to the old one: check
588
+ that the replacement has nothing in the schemas you restore before starting a
589
+ new restore there;
590
+ - \`unknown\`, or no record on this machine: connect to the target and check for one
591
+ of the snapshot's tables that wasn't there before, and whether \`auth.users\` has
592
+ this snapshot's users; run the restore again only once you've confirmed it rolled
593
+ back.${storageResume}
297
594
 
298
595
  `
299
- : `## Easiest path — the BackupDrill CLI
596
+ : `## ${cliHeading}
300
597
 
301
598
  \`\`\`bash
302
599
  npm install -g backupdrill
303
600
  ${cliRestoreCommand}
304
601
  \`\`\`
305
602
 
306
- Add \`--dry-run\` first to preview every check without writing anything. (Skip the
307
- \`read\` lines to have the CLI prompt you itself; \`unset\` both variables afterwards.)
308
- The CLI verifies the archive checksum, refuses non-empty targets, checks that rows
309
- referenced outside the snapshot (such as \`auth.users\`) are on the target, installs
310
- the extensions, restores the database in a single transaction through the same
311
- engine the weekly drills use (an SQL error rolls it back and the extensions stay
312
- installed; if the connection drops while it commits, check the target before
313
- retrying), sets the grants above, verifies table counts and row presence afterwards, then rebuilds buckets, uploads the
314
- Storage files back and reconciles every one against the target.
603
+ ${dryRunLine} (Skip the \`read\` lines to have the CLI prompt you itself; \`unset\` ${storage ? "both variables" : "the variable"} afterwards.)
604
+ The CLI verifies the dump checksum and checks for existing objects in the schemas
605
+ being restored. It checks foreign keys that point outside the snapshot, such as
606
+ references to \`auth.users\`, and warns when it can't check one. It
607
+ installs the extensions, then restores the database in one transaction with the
608
+ engine BackupDrill's restore drills use: an SQL error before the commit rolls it back and the
609
+ extensions stay installed (if the connection drops while it commits, check the
610
+ target before retrying). After the commit it sets the grants above, adds foreign
611
+ keys whose rows point at a missing parent row as \`NOT VALID\` (under the conditions
612
+ in step 4), and checks table counts and row presence${storage ? ", then restores the Storage files" : ""}.${storageResume}
315
613
 
316
614
  `;
317
- return `# BackupDrill recovery runbook — ${ctx.projectName} @ ${ctx.snapshot}
318
-
319
- This file was written next to the snapshot it describes and is **self-contained**:
320
- even if BackupDrill (the service and the website) is unreachable, everything below
321
- works with standard PostgreSQL tools against this bucket alone.
615
+ const intro = source.kind === "bucket"
616
+ ? authInDump
617
+ ? `This file was written next to the snapshot it describes. ${AUTH_IN_DUMP_OPENER}`
618
+ : `This file was written next to the snapshot it describes. The manual steps below use
619
+ standard PostgreSQL tools and the files in this bucket, and don't need the BackupDrill
620
+ service or website.`
621
+ : source.kind === "drive"
622
+ ? `This file sits in the same Google Drive folder as the backup it describes:
623
+ ${markdownCode(source.folderPath)}.${authInDump
624
+ ? ` ${AUTH_IN_DUMP_OPENER}`
625
+ : " The manual steps below use standard PostgreSQL tools and the files in\nthis folder, and don't need the BackupDrill service or website."}`
626
+ : `To get this backup, open the project in BackupDrill, find this backup and select
627
+ **Download**, then run the download script it gives you in a terminal. The folder
628
+ the script creates holds \`backupdrill-download.json\` and a \`files/\` folder: every
629
+ file of the backup is in \`files/\` under a number (its \`path\`), and
630
+ \`backupdrill-download.json\` gives each one's original name (its \`key\`, such as
631
+ \`${ctx.snapshot}/dump.pgcustom\`).${authInDump
632
+ ? ` ${AUTH_IN_DUMP_OPENER}`
633
+ : ` Once you have the download, the manual steps
634
+ below don't need the BackupDrill service or website.`}`;
635
+ const storageSection = storage
636
+ ? `## Restore Storage files
322
637
 
323
- ## What this snapshot contains
638
+ ${source.kind === "download"
639
+ ? `In \`backupdrill-download.json\`, each file's original name,
640
+ \`${ctx.snapshot}/storage/<original-bucket>/<original-key>\`, is its \`key\`; its \`path\`
641
+ is where the file is in this download.`
642
+ : `Files live at \`${base}/storage/<original-bucket>/<original-key>\` in this
643
+ bucket.`} Recreate each bucket in the target project, then re-upload the files
644
+ ${storage.buckets ? "(bucket attributes — public flag, size and MIME limits — are recorded in manifest.json under `storage.buckets`)" : "(bucket attributes were not captured for this snapshot; recreate buckets with the settings you know)"}.${storage.partial
645
+ ? ` Only ${storage.partial.copied} of the ${storage.partial.total} files were copied into this snapshot; \`storage.partial\` in manifest.json counts the rest by reason.`
646
+ : ""}${storagePolicyCoverage(manifest) === "missing"
647
+ ? " Storage access policies (the policies on `storage.objects`) aren't in this snapshot; recreate them in the new project."
648
+ : storagePolicyCoverage(manifest) === "unknown"
649
+ ? " This snapshot's schema list is written as patterns, so check whether it has the Storage access policies: run `pg_restore --list dump.pgcustom` and look for `POLICY` entries on `storage.objects`, then recreate the ones that are missing."
650
+ : ""} Re-uploaded files don't keep their original owner (\`owner_id\`), so check that
651
+ policies based on the owner still give your users access.
324
652
 
325
- - **Database dump**: \`${manifest.dump.key}\`
326
- (pg_dump custom format, ${mb(manifest.dump.bytes)} MB, sha256 \`${manifest.dump.sha256}\`)
327
- - schemas: ${db.schemas.map(markdownSchemaName).join(", ")} — ${db.tableCount} tables, ~${db.estimatedRowTotal.toLocaleString("en-US")} rows at backup time
328
- - source PostgreSQL ${db.serverVersion}, archive written by ${db.pgDumpVersion} — restore with pg_restore ${requiredRestoreMajor} or newer (the archive format follows the dump tool, not the server)
329
- ${extensions.length
330
- ? ` - extensions required: ${extensions.map((e) => `${e.name} (schema "${e.schema}")`).join(", ")}`
331
- : " - no extensions recorded"}
332
- - **Storage files**: ${storage
333
- ? storage.partial
334
- ? `copied ${storage.partial.copied} of ${storage.partial.total} files (${mb(storage.totalBytes)} MB) to \`${base}/storage/<bucket>/<key>\`. ` +
335
- `See manifest.json for file checksums and \`storage.partial\` for skip counts by reason`
336
- : `${storage.fileCount} files, ${mb(storage.totalBytes)} MB under \`${base}/storage/<bucket>/<key>\` — per-file sha256 in manifest.json`
337
- : manifest.storageFailure
338
- ? `not in this snapshot — copying them failed (${manifest.storageFailure.reason}); the database part is complete`
339
- : "none (database-only snapshot)"}
340
- ${authText.contentsLine}- **Machine-readable inventory**: \`${base}/manifest.json\`
341
-
342
- ## Not covered — plan for these separately
343
-
344
- ${notCovered}
345
- ## Restore the database (into an EMPTY project)
653
+ `
654
+ : "";
655
+ const restoreDatabase = `## Restore the database (into an EMPTY project)
346
656
 
347
657
  1. Create a **fresh** Supabase project (never restore onto the source project),
348
658
  and use its **Session Pooler** connection string.
@@ -360,20 +670,50 @@ ${restoreSteps}
360
670
  these roles (and \`PUBLIC\`) on everything the restore created, then grants back
361
671
  what the source had at backup time (the same list is in manifest.json under
362
672
  \`database.grants\`). A grant whose object isn't in this restore is skipped with a warning:`
363
- : `This snapshot was taken before BackupDrill recorded grants. The statements below
364
- give the three roles Supabase's old default access to everything in \`public\`;
365
- afterwards, revoke it on any table you had kept private:`}
673
+ : `This snapshot was taken before BackupDrill recorded grants. If you kept any
674
+ objects private, replace the statements below with grants that name the objects
675
+ and privileges each role needs. As written, they give the three roles every
676
+ privilege on all tables and sequences in \`public\` and \`EXECUTE\` on its
677
+ functions, which is what new Supabase projects used to grant by default. If the
678
+ Data API exposes \`public\`, these grants can let anyone with your project's anon
679
+ key read or change rows wherever RLS is disabled or permits the operation. Views use their
680
+ owner's rights by default and can show rows a caller couldn't read directly if the
681
+ owner bypasses RLS; a \`security_invoker\` view uses the caller's rights. Schemas
682
+ other than \`public\` get no grants here:`}
366
683
 
367
684
  ${sqlFence}sql
368
685
  ${grantsSql}
369
686
  ${sqlFence}
370
687
 
371
- ## Restore Storage files
688
+ `;
689
+ return `# BackupDrill recovery runbook — ${ctx.projectName} @ ${ctx.snapshot}
372
690
 
373
- Files live at \`${base}/storage/<original-bucket>/<original-key>\` in this
374
- bucket. Recreate each bucket in the target project, then re-upload the files
375
- ${storage?.buckets ? "(bucket attributes — public flag, size and MIME limits — are recorded in manifest.json under `storage.buckets`)" : "(bucket attributes were not captured for this snapshot; recreate buckets with the settings you know)"}.
691
+ ${intro}
376
692
 
377
- ${cliSection}More: https://backupdrill.com/docs/restore
693
+ ## What this snapshot contains
694
+
695
+ - **Database dump**: ${fileRef("dump.pgcustom")}
696
+ (pg_dump custom format, ${mb(manifest.dump.bytes)} MB, sha256 \`${manifest.dump.sha256}\`)
697
+ - schemas: ${db.schemas.map(markdownSchemaName).join(", ")} — ${db.tableCount} tables, ~${db.estimatedRowTotal.toLocaleString("en-US")} rows at backup time
698
+ - source PostgreSQL ${db.serverVersion}, archive written by ${db.pgDumpVersion} — restore with pg_restore ${requiredRestoreMajor} or newer (the archive format follows the dump tool, not the server)
699
+ ${extensions.length
700
+ ? ` - extensions required: ${extensions.map((e) => `${e.name} (schema "${e.schema}")`).join(", ")}`
701
+ : " - no extensions recorded"}
702
+ - **Storage files**: ${source.kind === "drive"
703
+ ? "none. Google Drive backups contain the database only."
704
+ : storage
705
+ ? storage.partial
706
+ ? `copied ${storage.partial.copied} of ${storage.partial.total} files (${mb(storage.totalBytes)} MB) to ${storageLocation}. ` +
707
+ `See manifest.json for file checksums and \`storage.partial\` for skip counts by reason`
708
+ : `${storage.fileCount} files, ${mb(storage.totalBytes)} MB under ${storageLocation} — per-file sha256 in manifest.json`
709
+ : manifest.storageFailure
710
+ ? `not in this snapshot — copying them failed (${markdownCode(manifest.storageFailure.reason)}); the database part is complete`
711
+ : "none (database-only snapshot)"}
712
+ ${authText.contentsLine}- **Machine-readable inventory**: ${fileRef("manifest.json")}
713
+
714
+ ## Not covered — plan for these separately
715
+
716
+ ${notCovered}
717
+ ${restoreDatabase}${storageSection}${authInDump ? "" : cliSection}More: https://backupdrill.com/docs/restore
378
718
  `;
379
719
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "backupdrill",
3
- "version": "2.12.1",
3
+ "version": "2.14.0",
4
4
  "description": "Open-source CLI to back up a Supabase project to your own S3/R2/B2 bucket (the Postgres database, Auth users when your role can read them, and Storage files once you add the project's Storage S3 keys), then run a restore drill that proves the backup restores.",
5
5
  "type": "module",
6
6
  "bin": {