backupdrill 2.11.0 → 2.11.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -33,14 +33,14 @@ npx backupdrill backup
33
33
 
34
34
  ## Use it from Claude Code or Cursor
35
35
 
36
- The [`plugin/`](plugin/) folder is a plugin for Claude Code and Cursor. It teaches the agent to run `estimate`, `backup`, `drill` and `restore` for you, keeps your keys in a gitignored `.env.backupdrill` that the agent never opens, and always does a dry run before a restore. In Claude Code:
36
+ The [`plugin/`](https://github.com/backupdrill/cli/tree/main/plugin) folder is a plugin for Claude Code and Cursor. It teaches the agent to run `estimate`, `backup`, `drill` and `restore` for you. Its instructions keep your keys in a gitignored `.env.backupdrill` that the agent is told never to open, and have it do a dry run before every restore. In Claude Code:
37
37
 
38
38
  ```
39
39
  /plugin marketplace add backupdrill/cli
40
40
  /plugin install backupdrill@backupdrill
41
41
  ```
42
42
 
43
- Details are in [plugin/README.md](plugin/README.md).
43
+ Details are in [plugin/README.md](https://github.com/backupdrill/cli/blob/main/plugin/README.md).
44
44
 
45
45
  ## Use it from Pi
46
46
 
@@ -50,7 +50,7 @@ This npm package is also a Pi package. Installing it gives Pi the same skill the
50
50
  pi install npm:backupdrill
51
51
  ```
52
52
 
53
- Start a new Pi session and ask it to back up your Supabase project or run a restore drill. The skill runs the CLI through `npx`, so Node.js 20 or newer has to be on your `PATH`. Everything else it needs, and where your keys go, is in [plugin/README.md](plugin/README.md).
53
+ Start a new Pi session and ask it to back up your Supabase project or run a restore drill. The skill runs the CLI through `npx`, so Node.js 20 or newer has to be on your `PATH`. Everything else it needs, and where your keys go, is in [plugin/README.md](https://github.com/backupdrill/cli/blob/main/plugin/README.md).
54
54
 
55
55
  ## Usage
56
56
 
@@ -76,7 +76,7 @@ All recognized variables:
76
76
  |---|---|---|
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
- | `BACKUPDRILL_SCHEMAS` | Comma-separated schemas to dump | `public` |
79
+ | `BACKUPDRILL_SCHEMAS` | Comma-separated schemas to dump. If the list includes `auth`, `dump.pgcustom` copies the Auth tables as-is, including any pending password-reset and confirmation tokens, and BackupDrill skips the separate `auth.dump`. When BackupDrill writes a separate `auth.dump`, it clears those tokens before upload | `public` |
80
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 |
81
81
  | `BACKUPDRILL_S3_ENDPOINT` | S3-compatible endpoint (R2/B2/self-hosted; omit for AWS S3) | — |
82
82
  | `BACKUPDRILL_S3_REGION` | Destination bucket region | `auto` |
@@ -181,8 +181,12 @@ backupdrill drill --verify-all-files # also checksum every Storage file, not jus
181
181
 
182
182
  After the restore, the drill counts the rows of every table in the sandbox and compares each count with the number of rows that table has in the backup file. One row more or less in any table fails the drill. The backup's count comes from reading the dump itself, not from your database, so this adds no queries against production; it costs the drill one extra read of the dump. Materialized views and partitioned parent tables have no rows of their own in the dump, and tables created by an extension hold rows the extension adds itself, so these are checked for being non-empty instead. `restore` runs the same comparison on the target project.
183
183
 
184
+ If you also keep a written record of each drill for your team or an audit (which snapshot, how long the restore took, who checked the app afterwards), there's a free [restore drill log template](https://tally.so/templates/database-restore-drill-log/mZBx5m) on Tally with those fields. `--record` below stores the machine-readable side of the same result in your bucket.
185
+
184
186
  Backups record your installed Postgres extensions in the manifest, and the drill pre-installs them in the sandbox before restoring — including switching to a pgvector-enabled sandbox image when your database uses `vector` columns.
185
187
 
188
+ Every drill first pulls the sandbox image (`postgres:<major>-alpine`, or `pgvector/pgvector:pg<major>`) from Docker Hub, so an image you already have is updated to the latest published build of that tag. After the November 2026 PostgreSQL security fix, older versions of `pg_dump` can write `pg_attver` into a backup, and a sandbox without the fix rejects that option. If you already have the image and the update fails or takes more than 5 minutes, the drill uses your copy and prints a warning.
189
+
186
190
  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.
187
191
 
188
192
  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.
@@ -197,7 +201,7 @@ The drill's structural checks (tables, rows, checksums) can't know what "working
197
201
  backupdrill drill --check-cmd "npm run smoke" # BACKUPDRILL_SANDBOX_URL points at the restored copy
198
202
  ```
199
203
 
200
- Your command runs after all structural checks pass, with `BACKUPDRILL_SANDBOX_URL` set to the sandbox's connection string. Exit 0 means pass; the result shows up in the report as an `app checks` line, and a non-zero exit fails the drill (the report keeps structural and app-level failures clearly separate). Entirely optional — without the flag, nothing changes and the report has no `app checks` line. There's a 10-minute timeout (the whole process tree is killed), and `--keep` leaves the sandbox container running when a drill fails so you can inspect it — the report JSON then includes a `keptSandbox` object with the container id and connection string (`docker rm -f <id>` when done).
204
+ Your command runs after all structural checks pass, with `BACKUPDRILL_SANDBOX_URL` set to the sandbox's connection string. Exit 0 means pass; the result shows up in the report as an `app checks` line, and a non-zero exit fails the drill (the report keeps structural and app-level failures clearly separate). Entirely optional — without the flag, nothing changes and the report has no `app checks` line. There's a 10-minute timeout (the whole process tree is killed), and `--keep` leaves the sandbox container running when a drill fails so you can inspect it — the report JSON then includes a `keptSandbox` object with the container id and connection string (`docker rm -f <id>` when done). The Auth sign-up test only runs when the backup has at least one custom Auth trigger to recreate. BackupDrill waits for any `--check-cmd` to finish, then disconnects the sandbox from its Docker networks before running the test. If the drill fails with `--keep`, BackupDrill skips the sign-up test so you can still connect.
201
205
 
202
206
  **What this can and cannot verify, honestly:** `BACKUPDRILL_SANDBOX_URL` connects as the sandbox **superuser**, and superusers bypass row-level security. The sandbox does carry a stub of the Supabase runtime — an `auth` schema whose `uid()`/`jwt()`/`role()`/`email()` return null, and the `anon`/`authenticated`/`service_role` roles — so functions, column defaults and policies that reference them restore instead of being skipped. The sandbox deliberately does not create Supabase-managed *tables* such as `auth.users`: an index, constraint or policy that points at one is reported as a skipped managed object (these are restored in a second, post-data pass where that exemption applies). A skipped foreign key into `auth.users` still matters for a real restore, see [Tables that reference auth.users](#tables-that-reference-authusers). A *view* over one is created in the strict first pass instead, and fails the drill — a real gap in what a public-only backup can rebuild, shown rather than hidden. A function *body* that selects from `auth.users` is different: PostgreSQL does not validate string-literal bodies (`AS $$ … $$`) during a restore (`check_function_bodies` is off in every dump), so such a function is recreated and the drill passes — it would only fail when called. The exception is an SQL-standard `BEGIN ATOMIC … END` body, which is parsed and dependency-checked at creation regardless of that setting, so one of those referencing a managed table fails the drill like a view does. That is exactly what `--check-cmd` is for: if your application depends on such a function, call it there. So use `--check-cmd` for data and business invariants ("orders reference existing users", "the row count I care about is sane"). It is **not** an RLS behavior test — `auth.uid()` is a stub and you are a superuser; verifying RLS takes an authenticated client stack with real JWTs, which no restore sandbox can fake generically.
203
207
 
@@ -334,7 +338,7 @@ Add the secrets under Settings → Secrets and variables → Actions:
334
338
 
335
339
  The action's README lists every input and output.
336
340
 
337
- Prefer a plain workflow file? [`examples/scheduled-backup.yml`](examples/scheduled-backup.yml) runs the backup without the action and without a drill. Copy it into your own repo at `.github/workflows/scheduled-backup.yml` and add the same secrets. (It lives under `examples/` here so GitHub doesn't try to run it in this repo.) It runs daily and can also be started by hand from the Actions tab.
341
+ Prefer a plain workflow file? [`examples/scheduled-backup.yml`](https://github.com/backupdrill/cli/blob/main/examples/scheduled-backup.yml) runs the backup without the action and without a drill. Copy it into your own repo at `.github/workflows/scheduled-backup.yml` and add the same secrets. (It lives under `examples/` here so GitHub doesn't try to run it in this repo.) It runs daily and can also be started by hand from the Actions tab.
338
342
 
339
343
  Before switching to a **daily** schedule, read the egress-cost section above — every run is egress on your Supabase bill.
340
344
 
@@ -362,7 +366,7 @@ docker run -d --name backupdrill --restart unless-stopped \
362
366
  - Arguments go straight to the CLI: `docker run --rm -e … ghcr.io/backupdrill/backupdrill estimate` or `… --help`. To start a backup now in a running scheduled container: `docker exec backupdrill backupdrill backup`.
363
367
  - `BACKUPDRILL_CRON` takes a standard 5-field expression or a shortcut such as `@daily`. Anything else stops the container at start (exit code 64) instead of leaving it idle.
364
368
  - `drill` needs Docker to start its throwaway Postgres, and the image doesn't get access to your Docker daemon, so run drills where Docker is available (your machine, or the GitHub Action with `drill: "true"`).
365
- - Tags: `latest`, the CLI version (e.g. `2.10.1`), and `sha-<commit>`. Images are built for amd64 and arm64.
369
+ - Tags: `latest`, the CLI version (e.g. `2.11.1`), and `sha-<commit>`. Images are built for amd64 and arm64.
366
370
 
367
371
  ## Alerts with Healthchecks.io
368
372
 
@@ -483,14 +487,24 @@ following is the stable public surface — breaking it requires a major version
483
487
  - the layout written to your bucket, and the shape of `manifest.json` and the drill record files
484
488
  - the names and meaning of the metrics `exporter` serves
485
489
 
486
- `manifest.json` carries a `schemaVersion` so the format can evolve safely. A snapshot written by
487
- a newer release is **refused with a clear message** rather than parsed on a best-effort basis —
490
+ `manifest.json` carries a `schemaVersion` so the format can evolve safely. A snapshot whose
491
+ `schemaVersion` is newer than this CLI supports is **refused with a clear message** rather than parsed on a best-effort basis —
488
492
  for a backup tool, silently misreading an archive is the worst possible failure. Snapshots taken
489
493
  before 1.0 have no `schemaVersion` and are treated as version 1, so older backups stay readable.
490
494
 
491
495
  The package's **JavaScript exports are internal** to the hosted BackupDrill product and are not
492
496
  covered by this promise; they may change in any release. Use the CLI if you need a stable contract.
493
497
 
498
+ ## Elsewhere
499
+
500
+ - The PostgreSQL.org software catalogue lists backupdrill under [Administration/development tools](https://www.postgresql.org/download/products/1-administrationdevelopment-tools/).
501
+ - The [pgAdmin blog aggregator](https://www.pgadmin.org/blogs/) carries our guide to backing up a Supabase database with pgAdmin's Backup and Restore dialogs.
502
+ - [backupdrill on StackShare](https://stackshare.io/backupdrill).
503
+ - A [ZAP success story](https://www.zaproxy.org/success/backupdrill/) describes the weekly ZAP baseline scan we run against our website.
504
+ - The agent skill in [`plugin/`](https://github.com/backupdrill/cli/tree/main/plugin) is also published on the [Tessl registry](https://tessl.io/registry/backupdrill/supabase-backup) and [LobeHub](https://lobehub.com/skills/backupdrill-cli-supabase-backup).
505
+ - The [backupdrill/supabase-backup orb](https://circleci.com/developer/orbs/orb/backupdrill/supabase-backup) runs backups and restore drills in CircleCI pipelines.
506
+ - [Our HackerNoon author page](https://hackernoon.com/u/superlede), with an article on five ways Supabase backups fail and how to test restores for each.
507
+
494
508
  ## License
495
509
 
496
510
  MIT
@@ -0,0 +1,31 @@
1
+ import { Readable } from "node:stream";
2
+ /**
3
+ * 2.11.1 起:auth.dump 上传前,把 auth.users 里待处理的认证状态抹掉(找回密码、邮箱确认、改邮箱改手机、
4
+ * 重新认证的 token,以及它们的发送时间和待改成的新邮箱/手机号)。
5
+ *
6
+ * 为什么在备份时就抹:这些 token 在源项目上还没过期时,GoTrue 的 /verify 收 token_hash,拿到桶的人
7
+ * 可以直接用它在**源项目**上重置密码、确认邮箱。恢复时(CLEAR_PENDING_AUTH_SQL)本来就会清空,
8
+ * 所以留在备份里没有任何用处,只有风险。2.10 / 2.11.0 写的旧归档仍靠恢复端那一句清空。
9
+ *
10
+ * 为什么改归档而不是改 pg_dump:pg_dump 没有"导出时把某几列换掉"的办法;另起一份数据(COPY 查询结果)
11
+ * 又会让 auth.dump 不再是一份 pg_restore 能直接读的归档,RECOVERY.md 的手工步骤、演练、恢复都得跟着改。
12
+ * 所以 pg_dump 的参数一个不动(源库上的负载、锁、快照都和以前一样),只在它的输出流进桶之前,
13
+ * 改写 auth.users 那一段 COPY 数据;目录、其余数据段逐字节不变。sha256 和字节数按改写后的内容算,
14
+ * 和桶里的文件一致。
15
+ *
16
+ * 只认 pg_dump 在管道上写出的 custom 格式(目录里不带数据偏移),归档版本 1.12–1.16(PostgreSQL 10–17 的
17
+ * pg_dump;18 仍是 1.16)。认不出的一律报错:Auth 这一节记失败,绝不把没抹干净的归档当成功上传。
18
+ */
19
+ /**
20
+ * 要抹的列 → 抹成的 COPY 文本值。和恢复端 CLEAR_PENDING_AUTH_SQL 逐列一致(测试里对齐检查):
21
+ * token 和待改的新邮箱/手机号写空串(GoTrue 读这些列时不接受 NULL),确认状态写 0,发送时间写 NULL。
22
+ * 某个 GoTrue 版本里没有的列就跳过。
23
+ */
24
+ export declare const PENDING_AUTH_COPY_VALUES: ReadonlyArray<readonly [column: string, copyValue: string]>;
25
+ /** COPY auth.users (a, b, "c") FROM stdin; → 列名(去掉引号) */
26
+ export declare function copyColumns(copyStmt: string): string[];
27
+ /**
28
+ * 把 pg_dump 输出的 auth.dump 流改写成抹掉待处理 token 的版本。返回的流出错 = 没能抹干净,调用方必须当失败处理。
29
+ * 只读输入、只写输出,不碰数据库。
30
+ */
31
+ export declare function scrubPendingAuthTokens(input: Readable): Readable;
@@ -0,0 +1,423 @@
1
+ import { PassThrough, Readable, Transform } from "node:stream";
2
+ import { pipeline } from "node:stream/promises";
3
+ import { createDeflate, createInflate } from "node:zlib";
4
+ /**
5
+ * 2.11.1 起:auth.dump 上传前,把 auth.users 里待处理的认证状态抹掉(找回密码、邮箱确认、改邮箱改手机、
6
+ * 重新认证的 token,以及它们的发送时间和待改成的新邮箱/手机号)。
7
+ *
8
+ * 为什么在备份时就抹:这些 token 在源项目上还没过期时,GoTrue 的 /verify 收 token_hash,拿到桶的人
9
+ * 可以直接用它在**源项目**上重置密码、确认邮箱。恢复时(CLEAR_PENDING_AUTH_SQL)本来就会清空,
10
+ * 所以留在备份里没有任何用处,只有风险。2.10 / 2.11.0 写的旧归档仍靠恢复端那一句清空。
11
+ *
12
+ * 为什么改归档而不是改 pg_dump:pg_dump 没有"导出时把某几列换掉"的办法;另起一份数据(COPY 查询结果)
13
+ * 又会让 auth.dump 不再是一份 pg_restore 能直接读的归档,RECOVERY.md 的手工步骤、演练、恢复都得跟着改。
14
+ * 所以 pg_dump 的参数一个不动(源库上的负载、锁、快照都和以前一样),只在它的输出流进桶之前,
15
+ * 改写 auth.users 那一段 COPY 数据;目录、其余数据段逐字节不变。sha256 和字节数按改写后的内容算,
16
+ * 和桶里的文件一致。
17
+ *
18
+ * 只认 pg_dump 在管道上写出的 custom 格式(目录里不带数据偏移),归档版本 1.12–1.16(PostgreSQL 10–17 的
19
+ * pg_dump;18 仍是 1.16)。认不出的一律报错:Auth 这一节记失败,绝不把没抹干净的归档当成功上传。
20
+ */
21
+ /**
22
+ * 要抹的列 → 抹成的 COPY 文本值。和恢复端 CLEAR_PENDING_AUTH_SQL 逐列一致(测试里对齐检查):
23
+ * token 和待改的新邮箱/手机号写空串(GoTrue 读这些列时不接受 NULL),确认状态写 0,发送时间写 NULL。
24
+ * 某个 GoTrue 版本里没有的列就跳过。
25
+ */
26
+ export const PENDING_AUTH_COPY_VALUES = [
27
+ ["confirmation_token", ""],
28
+ ["recovery_token", ""],
29
+ ["email_change_token_new", ""],
30
+ ["email_change_token_current", ""],
31
+ ["phone_change_token", ""],
32
+ ["reauthentication_token", ""],
33
+ ["email_change", ""],
34
+ ["phone_change", ""],
35
+ ["email_change_confirm_status", "0"],
36
+ ["confirmation_sent_at", "\\N"],
37
+ ["recovery_sent_at", "\\N"],
38
+ ["email_change_sent_at", "\\N"],
39
+ ["phone_change_sent_at", "\\N"],
40
+ ["reauthentication_sent_at", "\\N"],
41
+ ];
42
+ // pg_backup_archiver.h 里的版本号:MAKE_ARCHIVE_VERSION(major, minor, rev)
43
+ const archiveVersion = (major, minor, rev) => (major * 256 + minor) * 256 + rev;
44
+ const K_VERS_1_12 = archiveVersion(1, 12, 0);
45
+ const K_VERS_1_14 = archiveVersion(1, 14, 0);
46
+ const K_VERS_1_15 = archiveVersion(1, 15, 0);
47
+ const K_VERS_1_16 = archiveVersion(1, 16, 0);
48
+ const K_VERS_MAX_KNOWN = archiveVersion(1, 16, 255);
49
+ const ARCH_CUSTOM = 1;
50
+ const BLK_DATA = 1;
51
+ const K_OFFSET_POS_NOT_SET = 1;
52
+ const K_OFFSET_POS_SET = 2;
53
+ // pg_compress_algorithm(1.15 起头部里存算法;之前存压缩级别,0 = 不压缩,其余都是 zlib)
54
+ const COMPRESSION_NONE = 0;
55
+ const COMPRESSION_GZIP = 1;
56
+ class ArchiveError extends Error {
57
+ }
58
+ /** 从异步迭代器按字节数取数据的读取器;只在需要拼接时才拷贝 */
59
+ class ByteReader {
60
+ source;
61
+ chunks = [];
62
+ buffered = 0;
63
+ ended = false;
64
+ constructor(source) {
65
+ this.source = source;
66
+ }
67
+ async fill(n) {
68
+ while (this.buffered < n && !this.ended) {
69
+ const next = await this.source.next();
70
+ if (next.done)
71
+ this.ended = true;
72
+ else if (next.value.length) {
73
+ this.chunks.push(next.value);
74
+ this.buffered += next.value.length;
75
+ }
76
+ }
77
+ return this.buffered >= n;
78
+ }
79
+ async atEnd() {
80
+ return !(await this.fill(1));
81
+ }
82
+ /** 正好 n 个字节;不够就是归档被截断了 */
83
+ async read(n) {
84
+ // 空字符串(长度 0)在目录里很常见;缓冲恰好读空时也不能去碰不存在的第一块
85
+ if (n === 0)
86
+ return Buffer.alloc(0);
87
+ if (!(await this.fill(n)))
88
+ throw new ArchiveError("the archive ended early");
89
+ const head = this.chunks[0];
90
+ if (head.length >= n) {
91
+ this.chunks[0] = head.subarray(n);
92
+ if (!this.chunks[0].length)
93
+ this.chunks.shift();
94
+ this.buffered -= n;
95
+ return head.subarray(0, n);
96
+ }
97
+ const all = Buffer.concat(this.chunks);
98
+ this.chunks = all.length > n ? [all.subarray(n)] : [];
99
+ this.buffered -= n;
100
+ return all.subarray(0, n);
101
+ }
102
+ /** 至多 n 个字节、至少 1 个,不拼接:大块数据按到手的大小往下传 */
103
+ async readUpTo(n) {
104
+ if (!(await this.fill(1)))
105
+ throw new ArchiveError("the archive ended early");
106
+ const head = this.chunks[0];
107
+ if (head.length <= n) {
108
+ this.chunks.shift();
109
+ this.buffered -= head.length;
110
+ return head;
111
+ }
112
+ this.chunks[0] = head.subarray(n);
113
+ this.buffered -= n;
114
+ return head.subarray(0, n);
115
+ }
116
+ }
117
+ /** pg_dump 的整数:1 字节符号 + intSize 字节小端 */
118
+ function decodeInt(raw) {
119
+ let value = 0;
120
+ for (let i = raw.length - 1; i >= 1; i--)
121
+ value = value * 256 + raw[i];
122
+ return raw[0] ? -value : value;
123
+ }
124
+ function encodeInt(value, intSize) {
125
+ const out = Buffer.alloc(1 + intSize);
126
+ let rest = value;
127
+ for (let i = 1; i <= intSize; i++) {
128
+ out[i] = rest % 256;
129
+ rest = Math.floor(rest / 256);
130
+ }
131
+ if (rest)
132
+ throw new ArchiveError("a data chunk is too large for this archive");
133
+ return out;
134
+ }
135
+ /** COPY auth.users (a, b, "c") FROM stdin; → 列名(去掉引号) */
136
+ export function copyColumns(copyStmt) {
137
+ const m = /^COPY\s+\S+\s+\(([\s\S]*)\)\s+FROM\s+stdin;\s*$/i.exec(copyStmt.trim());
138
+ if (!m)
139
+ throw new ArchiveError("the COPY statement of auth.users isn't in the expected form");
140
+ const columns = [];
141
+ const re = /\s*(?:"((?:[^"]|"")*)"|([^\s,"]+))\s*(,|$)/y;
142
+ let match;
143
+ let at = 0;
144
+ const list = m[1];
145
+ while (at < list.length && (match = re.exec(list))) {
146
+ columns.push(match[1] !== undefined ? match[1].replace(/""/g, '"') : match[2]);
147
+ at = re.lastIndex;
148
+ if (match[3] === "")
149
+ break;
150
+ }
151
+ if (at !== list.length || !columns.length)
152
+ throw new ArchiveError("the column list of auth.users couldn't be read");
153
+ return columns;
154
+ }
155
+ /**
156
+ * 逐字段改写 COPY 文本:按制表符和换行切字段,要抹的那几列换掉,其余字节原样往下传。COPY 文本格式里数据中的
157
+ * 制表符和换行都转义成 \t、\n,所以按原始字节 0x09 / 0x0A 切是安全的(服务端编码都兼容 ASCII)。
158
+ *
159
+ * 不按整行缓冲:一行可以非常大(metadata 很长、又压缩得很好时,解压出来的一行能远超内存)。逐块扫一遍,
160
+ * 要抹的字段直接丢、其余直接写出,占用的内存只和一块输入一样大,和行多长无关。
161
+ * 字段数和列数对不上就报错,不猜(已经写出去的半行随这次上传一起作废)。
162
+ */
163
+ function copyLineScrubber(columns, replace) {
164
+ // 第一列要抹的话就认不出 "\." 结束标记(它的字节被丢了);auth.users 的第一列从来不是 token
165
+ if (replace.has(0))
166
+ throw new ArchiveError("the first column of auth.users is unexpectedly one to clear");
167
+ let field = 0; // 当前行里的第几个字段
168
+ let skipping = false; // 当前字段要抹:它的字节不写出
169
+ let lineLength = 0; // 当前行到目前为止的字节数(只用来认结束标记,到 3 就不再数)
170
+ let lineHead = 0; // 当前行的头两个字节
171
+ // pg_dump 在每段 COPY 数据末尾写 "\.",后面只跟几个空行。结束标记必须有,之后只许是空行:
172
+ // 别的字节都说明这不是 pg_dump 写的样子,宁可失败也不上传
173
+ let afterEndMarker = false;
174
+ const afterEndError = () => new ArchiveError("the data of auth.users has something after its end marker");
175
+ const onlyNewlines = (chunk, from) => {
176
+ for (let i = from; i < chunk.length; i++)
177
+ if (chunk[i] !== 0x0a)
178
+ throw afterEndError();
179
+ };
180
+ const fieldCountError = (fields) => new ArchiveError(`a row of auth.users has ${fields} fields, but the COPY statement lists ${columns.length} columns`);
181
+ const scan = (chunk, out) => {
182
+ let start = 0; // 下一个还没写出的字节
183
+ for (let i = 0; i < chunk.length; i++) {
184
+ const b = chunk[i];
185
+ if (b !== 0x09 && b !== 0x0a) {
186
+ if (lineLength < 3) {
187
+ if (lineLength < 2)
188
+ lineHead = lineHead * 256 + b;
189
+ lineLength++;
190
+ }
191
+ continue;
192
+ }
193
+ if (skipping) {
194
+ out.push(replace.get(field));
195
+ start = i; // 分隔符本身照常写出
196
+ skipping = false;
197
+ }
198
+ if (b === 0x09) {
199
+ field++;
200
+ lineLength = 3; // 有制表符就不可能是结束标记
201
+ if (field >= columns.length)
202
+ throw fieldCountError(field + 1);
203
+ }
204
+ else {
205
+ const endMarker = field === 0 && lineLength === 2 && lineHead === 0x5c2e;
206
+ if (!endMarker && field !== columns.length - 1)
207
+ throw fieldCountError(field + 1);
208
+ field = 0;
209
+ lineLength = 0;
210
+ lineHead = 0;
211
+ if (endMarker) {
212
+ afterEndMarker = true;
213
+ onlyNewlines(chunk, i + 1);
214
+ out.push(chunk.subarray(start));
215
+ return;
216
+ }
217
+ }
218
+ if (replace.has(field)) {
219
+ out.push(chunk.subarray(start, i + 1));
220
+ start = i + 1;
221
+ skipping = true;
222
+ }
223
+ }
224
+ if (!skipping)
225
+ out.push(chunk.subarray(start));
226
+ };
227
+ return new Transform({
228
+ transform(chunk, _encoding, callback) {
229
+ try {
230
+ if (afterEndMarker) {
231
+ onlyNewlines(chunk, 0);
232
+ return callback(null, chunk);
233
+ }
234
+ const out = [];
235
+ scan(chunk, out);
236
+ callback(null, out.length === 1 ? out[0] : Buffer.concat(out));
237
+ }
238
+ catch (error) {
239
+ callback(error);
240
+ }
241
+ },
242
+ flush(callback) {
243
+ // 没有结束标记 = 数据不完整(或者不是 pg_dump 写的):不能当成抹干净了
244
+ if (!afterEndMarker)
245
+ return callback(new ArchiveError("the data of auth.users has no end marker"));
246
+ callback();
247
+ },
248
+ });
249
+ }
250
+ /**
251
+ * 把 pg_dump 输出的 auth.dump 流改写成抹掉待处理 token 的版本。返回的流出错 = 没能抹干净,调用方必须当失败处理。
252
+ * 只读输入、只写输出,不碰数据库。
253
+ */
254
+ export function scrubPendingAuthTokens(input) {
255
+ const out = new PassThrough();
256
+ const write = async (buf) => {
257
+ if (!buf.length)
258
+ return;
259
+ if (out.destroyed)
260
+ throw new ArchiveError("stopped");
261
+ if (out.write(buf))
262
+ return;
263
+ await new Promise((resolve, reject) => {
264
+ const done = () => {
265
+ out.off("drain", onDrain);
266
+ out.off("close", onClose);
267
+ };
268
+ const onDrain = () => (done(), resolve());
269
+ const onClose = () => (done(), reject(new ArchiveError("stopped")));
270
+ out.once("drain", onDrain);
271
+ out.once("close", onClose);
272
+ });
273
+ };
274
+ void (async () => {
275
+ const reader = new ByteReader(input[Symbol.asyncIterator]());
276
+ // 头部和目录原样照抄:读到多少写多少
277
+ const take = async (n) => {
278
+ const buf = await reader.read(n);
279
+ await write(buf);
280
+ return buf;
281
+ };
282
+ const magic = await take(5);
283
+ if (magic.toString("latin1") !== "PGDMP")
284
+ throw new ArchiveError("the Auth archive isn't a pg_dump custom-format archive");
285
+ const [vmaj, vmin] = await take(2);
286
+ const vrev = vmaj > 1 || (vmaj === 1 && vmin > 0) ? (await take(1))[0] : 0;
287
+ const version = archiveVersion(vmaj, vmin, vrev);
288
+ if (version < K_VERS_1_12 || version > K_VERS_MAX_KNOWN) {
289
+ throw new ArchiveError(`pg_dump wrote archive version ${vmaj}.${vmin}.${vrev}, which this CLI can't clear pending Auth tokens from`);
290
+ }
291
+ const intSize = (await take(1))[0];
292
+ const offSize = (await take(1))[0];
293
+ if (intSize < 1 || intSize > 8 || offSize < 1 || offSize > 16)
294
+ throw new ArchiveError("the archive header is malformed");
295
+ const readInt = async () => decodeInt(await take(1 + intSize));
296
+ const readStr = async () => {
297
+ const length = await readInt();
298
+ if (length < 0)
299
+ return null;
300
+ return (await take(length)).toString("utf8");
301
+ };
302
+ if ((await take(1))[0] !== ARCH_CUSTOM)
303
+ throw new ArchiveError("the Auth archive isn't in custom format");
304
+ let compression;
305
+ if (version >= K_VERS_1_15)
306
+ compression = (await take(1))[0];
307
+ else
308
+ compression = (await readInt()) === 0 ? COMPRESSION_NONE : COMPRESSION_GZIP;
309
+ if (compression !== COMPRESSION_NONE && compression !== COMPRESSION_GZIP) {
310
+ throw new ArchiveError("the Auth archive uses a compression method this CLI can't rewrite");
311
+ }
312
+ for (let i = 0; i < 7; i++)
313
+ await readInt(); // 创建时间(秒、分、时、日、月、年、夏令时)
314
+ await readStr(); // 库名
315
+ await readStr(); // 服务端版本
316
+ await readStr(); // pg_dump 版本
317
+ const tocCount = await readInt();
318
+ // 目录里声明了有数据的条目:每一条都要在后面见到它的数据段,少一段就是归档不完整
319
+ const withData = new Set();
320
+ let target = null;
321
+ for (let i = 0; i < tocCount; i++) {
322
+ const dumpId = await readInt();
323
+ await readInt(); // hadDumper
324
+ await readStr(); // tableoid
325
+ await readStr(); // oid
326
+ const tag = await readStr();
327
+ const desc = await readStr();
328
+ await readInt(); // section
329
+ await readStr(); // defn
330
+ await readStr(); // dropStmt
331
+ const copyStmt = await readStr();
332
+ const namespace = await readStr();
333
+ await readStr(); // tablespace
334
+ if (version >= K_VERS_1_14)
335
+ await readStr(); // tableam
336
+ if (version >= K_VERS_1_16)
337
+ await readInt(); // relkind
338
+ await readStr(); // owner
339
+ await readStr(); // 旧的 WITH OIDS 标记
340
+ while ((await readStr()) !== null)
341
+ ; // 依赖,以 NULL 结尾
342
+ const offsetFlag = (await take(1))[0];
343
+ await take(offSize);
344
+ if (offsetFlag === K_OFFSET_POS_NOT_SET)
345
+ withData.add(dumpId);
346
+ // 改写会改变数据段的长度:目录里记着数据偏移的归档(写进可寻址文件的)不能这样改。管道上写出的不会记
347
+ if (offsetFlag === K_OFFSET_POS_SET)
348
+ throw new ArchiveError("the Auth archive records data offsets, which this CLI can't rewrite");
349
+ if (desc === "TABLE DATA" && namespace === "auth" && tag === "users") {
350
+ if (target)
351
+ throw new ArchiveError("the Auth archive has the data of auth.users twice");
352
+ target = { dumpId, columns: copyColumns(copyStmt ?? "") };
353
+ }
354
+ }
355
+ if (!target)
356
+ throw new ArchiveError("the Auth archive has no data entry for auth.users");
357
+ const replace = new Map();
358
+ for (const [column, value] of PENDING_AUTH_COPY_VALUES) {
359
+ const index = target.columns.indexOf(column);
360
+ if (index !== -1)
361
+ replace.set(index, Buffer.from(value));
362
+ }
363
+ // 数据段:每段 = 类型字节 + dumpId + 若干 [长度, 数据] 块,长度 0 结束
364
+ let scrubbed = false;
365
+ while (!(await reader.atEnd())) {
366
+ if ((await take(1))[0] !== BLK_DATA)
367
+ throw new ArchiveError("the Auth archive has a data block of an unexpected type");
368
+ const dumpId = await readInt();
369
+ if (!withData.delete(dumpId))
370
+ throw new ArchiveError("the Auth archive contains a duplicate data block or one missing from its table of contents");
371
+ if (dumpId !== target.dumpId) {
372
+ for (let length = await readInt(); length !== 0; length = await readInt()) {
373
+ if (length < 0)
374
+ throw new ArchiveError("the archive has a malformed data chunk");
375
+ for (let left = length; left > 0;) {
376
+ const piece = await reader.readUpTo(left);
377
+ await write(piece);
378
+ left -= piece.length;
379
+ }
380
+ }
381
+ continue;
382
+ }
383
+ if (scrubbed)
384
+ throw new ArchiveError("the Auth archive has the data of auth.users twice");
385
+ scrubbed = true;
386
+ // 原来的数据块不照抄,逐块读出来解压(按头部的压缩方式)、改写、再压缩,写成新的数据块
387
+ async function* payload() {
388
+ for (let length = decodeInt(await reader.read(1 + intSize)); length !== 0; length = decodeInt(await reader.read(1 + intSize))) {
389
+ if (length < 0)
390
+ throw new ArchiveError("the archive has a malformed data chunk");
391
+ for (let left = length; left > 0;) {
392
+ const piece = await reader.readUpTo(left);
393
+ yield piece;
394
+ left -= piece.length;
395
+ }
396
+ }
397
+ }
398
+ const emitChunks = async (source) => {
399
+ for await (const piece of source) {
400
+ if (!piece.length)
401
+ continue;
402
+ await write(encodeInt(piece.length, intSize));
403
+ await write(piece);
404
+ }
405
+ };
406
+ if (compression === COMPRESSION_GZIP) {
407
+ await pipeline(Readable.from(payload()), createInflate(), copyLineScrubber(target.columns, replace), createDeflate(), emitChunks);
408
+ }
409
+ else {
410
+ await pipeline(Readable.from(payload()), copyLineScrubber(target.columns, replace), emitChunks);
411
+ }
412
+ await write(encodeInt(0, intSize));
413
+ }
414
+ if (!scrubbed)
415
+ throw new ArchiveError("the Auth archive has no data block for auth.users");
416
+ if (withData.size)
417
+ throw new ArchiveError("the Auth archive ended before all of its data blocks");
418
+ out.end();
419
+ })().catch((error) => {
420
+ out.destroy(error instanceof Error ? error : new Error(String(error)));
421
+ });
422
+ return out;
423
+ }
@@ -5,7 +5,8 @@ import type { AuthSection, AuthTriggerInfo, AuthPolicyInfo } from "./manifest.js
5
5
  *
6
6
  * 只备这两张表:用户 ID、邮箱、密码哈希、metadata、登录方式。sessions、refresh token、MFA 因子、
7
7
  * SSO 配置一律不备——恢复到新项目后用户重新登录一次即可,MFA 因子可能用旧项目的密钥加密过,
8
- * 带过去反而可能把用户锁在外面。
8
+ * 带过去反而可能把用户锁在外面。2.11.1 起 auth.users 里待处理的找回密码、邮箱确认等 token 在上传前就抹掉
9
+ * (见 auth-archive.ts),pg_dump 的参数不变。
9
10
  *
10
11
  * 不打扰现有备份是硬约束:
11
12
  * - "off"(库调用的默认值)时,备份命令、上传的文件、manifest 与没有这个功能时逐字节一致。
@@ -75,6 +76,8 @@ export type AuthInspection = {
75
76
  grantee: string;
76
77
  privilege: string;
77
78
  }>;
79
+ /** auth.users 上第一个不是 Supabase 自带的、可能拒收抹过的值的对象(见 firstNonStockObject);null = 可以抹 */
80
+ nonStockObject: string | null;
78
81
  };
79
82
  /**
80
83
  * 在另一个连接里导入共享快照做统计。统计出错只影响这个连接,导出快照的事务和主 dump 不受牵连。
@@ -82,6 +85,12 @@ export type AuthInspection = {
82
85
  * pg_dump 照样"成功",导出的却是空表——看着干净,其实什么都没备上。
83
86
  */
84
87
  export declare function inspectAuth(databaseUrl: string, snapshotId: string, signal?: AbortSignal): Promise<AuthInspection>;
88
+ /**
89
+ * 把系统目录里的名字(约束名、索引名、列名)写进日志、manifest 和 RECOVERY.md 之前用:加双引号,
90
+ * 反斜杠、引号和所有控制字符(C0、DEL、C1、U+2028/2029)都转义成可见的文字。名字可以含换行,
91
+ * 原样写进终端就能伪造一行日志
92
+ */
93
+ export declare function quotedName(name: string): string;
85
94
  /**
86
95
  * 恢复(含 RECOVERY.md 的手工步骤)自动补建的 Auth 表对象。只建同时满足下面几条的触发器:
87
96
  * - 源库里是普通启用状态(O)。D 停用、R 只在复制会话触发的,在普通会话里本来就不起作用;