@cardonjs/backups 0.0.0-stage → 0.3.3
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/FORMAT.md +147 -0
- package/LICENSE +21 -0
- package/README.md +1237 -2
- package/dist/copy.d.ts +175 -0
- package/dist/copy.d.ts.map +1 -0
- package/dist/copy.js +863 -0
- package/dist/copy.js.map +1 -0
- package/dist/encryption.d.ts +203 -0
- package/dist/encryption.d.ts.map +1 -0
- package/dist/encryption.js +609 -0
- package/dist/encryption.js.map +1 -0
- package/dist/export.d.ts +201 -0
- package/dist/export.d.ts.map +1 -0
- package/dist/export.js +447 -0
- package/dist/export.js.map +1 -0
- package/dist/index.d.ts +14 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +14 -0
- package/dist/index.js.map +1 -0
- package/dist/keys.d.ts +28 -0
- package/dist/keys.d.ts.map +1 -0
- package/dist/keys.js +97 -0
- package/dist/keys.js.map +1 -0
- package/dist/metadata.d.ts +49 -0
- package/dist/metadata.d.ts.map +1 -0
- package/dist/metadata.js +51 -0
- package/dist/metadata.js.map +1 -0
- package/dist/restore.d.ts +97 -0
- package/dist/restore.d.ts.map +1 -0
- package/dist/restore.js +276 -0
- package/dist/restore.js.map +1 -0
- package/dist/retention.d.ts +153 -0
- package/dist/retention.d.ts.map +1 -0
- package/dist/retention.js +295 -0
- package/dist/retention.js.map +1 -0
- package/dist/run.d.ts +94 -0
- package/dist/run.d.ts.map +1 -0
- package/dist/run.js +129 -0
- package/dist/run.js.map +1 -0
- package/dist/sniff.d.ts +15 -0
- package/dist/sniff.d.ts.map +1 -0
- package/dist/sniff.js +47 -0
- package/dist/sniff.js.map +1 -0
- package/dist/workflow.d.ts +102 -0
- package/dist/workflow.d.ts.map +1 -0
- package/dist/workflow.js +298 -0
- package/dist/workflow.js.map +1 -0
- package/llms.txt +249 -0
- package/package.json +76 -3
package/README.md
CHANGED
|
@@ -1,3 +1,1238 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @cardonjs/backups
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Backups of a Cloudflare D1 database into R2: Cloudflare's own D1 export, streamed into a bucket
|
|
4
|
+
on a schedule, old copies pruned by day, week and month, and a check that a backup actually
|
|
5
|
+
loads.
|
|
6
|
+
|
|
7
|
+
## What Time Travel already covers, and what this adds
|
|
8
|
+
|
|
9
|
+
D1 keeps its own history. **Time Travel** restores a database to any minute of the last 30 days
|
|
10
|
+
(7 on the Workers Free plan): use it for the usual accident (a bad migration, a `DELETE`
|
|
11
|
+
without `WHERE`), see [Restoring](#restoring). A deleted database can be undeleted for 7 days.
|
|
12
|
+
That history lives inside D1 and ends there.
|
|
13
|
+
|
|
14
|
+
This package adds what a project with data worth keeping also needs:
|
|
15
|
+
|
|
16
|
+
- copies **older than 30 days** (an audit, a dispute, "what did this look like in March");
|
|
17
|
+
- copies **outside the database**, in an R2 bucket you control;
|
|
18
|
+
- a **SQL dump** that loads into another D1 database, a local one, or `sqlite3`;
|
|
19
|
+
- a **restore check**, so a backup is known to load before the day it is needed.
|
|
20
|
+
|
|
21
|
+
What stays in your project: which databases, how often, how long copies are kept, and who can
|
|
22
|
+
read them.
|
|
23
|
+
|
|
24
|
+
## Entry points
|
|
25
|
+
|
|
26
|
+
- **`@cardonjs/backups`**: `d1Export` (the export API client), `copyExport` (the dump into R2),
|
|
27
|
+
`pruneBackups` and `planRetention`, `runBackup` (all of it in one call, for small databases),
|
|
28
|
+
`backupKey` and `backupInstanceId`, and the opt-in encryption: `backupEncryption` and
|
|
29
|
+
`decryptBackup` (see [Encrypting backups](#encrypting-backups)). No peer dependencies; runs on
|
|
30
|
+
Workers (`decryptBackup` on Node too).
|
|
31
|
+
- **`@cardonjs/backups/workflow`**: `defineBackupWorkflow`, the backup as a Cloudflare
|
|
32
|
+
Workflow. Needs `@cardonjs/workflows-cf`, `@cardonjs/core` and `zod` (optional peers, only
|
|
33
|
+
for this entry).
|
|
34
|
+
- **`@cardonjs/backups/restore`**: `restoreStatements` and `checkRestore`, for Node (tests and
|
|
35
|
+
scripts). Needs `@cardonjs/testing` and, through it, `miniflare`.
|
|
36
|
+
|
|
37
|
+
For coding agents: `llms.txt`, next to this README in the package, is a compact usage guide.
|
|
38
|
+
`FORMAT.md`, also in the package, documents the encrypted format byte by byte.
|
|
39
|
+
|
|
40
|
+
## Install
|
|
41
|
+
|
|
42
|
+
```sh
|
|
43
|
+
pnpm add @cardonjs/backups
|
|
44
|
+
# for the Workflow
|
|
45
|
+
pnpm add @cardonjs/workflows-cf @cardonjs/core zod
|
|
46
|
+
# for the restore check (dev)
|
|
47
|
+
pnpm add -D @cardonjs/testing miniflare
|
|
48
|
+
```
|
|
49
|
+
|
|
50
|
+
The R2 and Workflow types come from `@cloudflare/workers-types`.
|
|
51
|
+
|
|
52
|
+
## Before you start: what these credentials can do
|
|
53
|
+
|
|
54
|
+
Read this section before setting anything up: a backup setup holds two of the most powerful
|
|
55
|
+
things in a project, a copy of every row and a token that can change the database.
|
|
56
|
+
|
|
57
|
+
### The bucket
|
|
58
|
+
|
|
59
|
+
**Anyone who can read the bucket can read every row of the database** (unless backups are
|
|
60
|
+
[encrypted](#encrypting-backups), which is opt-in). A dump holds every table,
|
|
61
|
+
including password hashes, sessions, tokens and personal data. **Anyone who can write to the
|
|
62
|
+
bucket can decide what a restore puts in production**: a restore executes the dump as SQL, with
|
|
63
|
+
full rights, into the database that becomes production, so a tampered dump can create accounts,
|
|
64
|
+
change roles or plant data. Treat write access to the bucket like write access to the database,
|
|
65
|
+
and check a dump against a digest kept **outside** the bucket before restoring it (see
|
|
66
|
+
[The restore check](#the-restore-check)).
|
|
67
|
+
|
|
68
|
+
- a bucket **only for backups**, private: no public bucket, no `r2.dev` URL, no custom domain;
|
|
69
|
+
- bound only to the backup Worker (below), never to the Worker that serves the app;
|
|
70
|
+
- no R2 API tokens or S3 credentials shared with other tools or people; whoever restores uses
|
|
71
|
+
their own Cloudflare login;
|
|
72
|
+
- by default the dump is stored as plain SQL (R2 encrypts at rest, which does not stop anyone
|
|
73
|
+
who can read the bucket); turn on [client-side encryption](#encrypting-backups) so that
|
|
74
|
+
reading the bucket gives ciphertext only.
|
|
75
|
+
|
|
76
|
+
```sh
|
|
77
|
+
pnpm wrangler r2 bucket create my-app-backups
|
|
78
|
+
```
|
|
79
|
+
|
|
80
|
+
**Against deletion**, R2 has bucket locks: rules that keep the objects under a prefix from being
|
|
81
|
+
deleted or overwritten for a retention period. A lock and `pruneBackups` pull in opposite
|
|
82
|
+
directions: a locked backup cannot be pruned, so a lock longer than the age at which your policy
|
|
83
|
+
first deletes a backup (about `daily` days with one backup a day) makes every prune fail. Either
|
|
84
|
+
keep the lock shorter than that, or use a lock with an R2 lifecycle rule instead of
|
|
85
|
+
`pruneBackups` (see [Retention](#retention)). How R2 answers a batch delete that includes a
|
|
86
|
+
locked object was not verified here: check R2's bucket lock documentation for the commands and
|
|
87
|
+
the details before relying on one.
|
|
88
|
+
|
|
89
|
+
### The API token
|
|
90
|
+
|
|
91
|
+
The export runs through Cloudflare's REST API, not the D1 binding, so it needs an **API token**,
|
|
92
|
+
and **the export endpoint requires the D1 Write permission**. Cloudflare's documentation: "The
|
|
93
|
+
export operation requires D1 Write permission because it locks the database until the export
|
|
94
|
+
completes"; a token with D1 Read only is refused (error code 10000, which this package reports
|
|
95
|
+
as `unauthorized`).
|
|
96
|
+
|
|
97
|
+
So the backup token is far more than a backup credential. **Assume it can read, change and
|
|
98
|
+
delete every D1 database in the account**: whether a token's D1 permission can be limited to
|
|
99
|
+
one database was not verified here. Hence:
|
|
100
|
+
|
|
101
|
+
- create a custom token (dashboard → My Profile → API Tokens → Create Token) limited to **the
|
|
102
|
+
one account**, with **D1 Write** and nothing else; test it on a staging database first;
|
|
103
|
+
- give it an expiry date and a reminder to rotate it;
|
|
104
|
+
- keep it in **a Worker that does nothing but backups** (next section), as a secret of that
|
|
105
|
+
Worker only: `pnpm wrangler secret put D1_EXPORT_TOKEN --config backup-worker/wrangler.jsonc`
|
|
106
|
+
(and `--env staging` for staging's own token). Never in `wrangler.jsonc`, a log, a URL or an
|
|
107
|
+
error. The package sends it only to `https://api.cloudflare.com`, in the `Authorization`
|
|
108
|
+
header, and never returns or logs it.
|
|
109
|
+
|
|
110
|
+
The account id (32 hex characters) and the database id (`database_id` in `wrangler.jsonc`) are
|
|
111
|
+
not secrets: put them in `vars`.
|
|
112
|
+
|
|
113
|
+
### Choosing the time
|
|
114
|
+
|
|
115
|
+
**While an export runs, the database does not serve other queries**: Cloudflare documents that
|
|
116
|
+
an export locks the database until it completes, and larger databases take longer. Schedule the
|
|
117
|
+
backup when traffic is lowest (Cron Triggers run in UTC), measure how long an export of your
|
|
118
|
+
database takes on staging, keep the schedule to once a day unless you need more, and expect a
|
|
119
|
+
retried start (after a lost answer) or a restarted export (after a failed copy, see
|
|
120
|
+
[What the steps do](#what-the-steps-do)) to run another export in the same window. On
|
|
121
|
+
2026-11-20 a 15 MB database exported in under 10 seconds.
|
|
122
|
+
|
|
123
|
+
## A separate backup Worker
|
|
124
|
+
|
|
125
|
+
**Do not put the token and the backup bucket in the Worker that serves your app.** That Worker
|
|
126
|
+
runs every dependency of the app, and handles every request: a compromised dependency or a
|
|
127
|
+
request-handling bug there would get the database (through its binding), the backups (through
|
|
128
|
+
the bucket) and a token that can rewrite or delete both. A Worker of its own, with no `fetch`
|
|
129
|
+
handler and no app code, holds the token, the bucket binding, the cron and the Workflow; the app
|
|
130
|
+
Worker has none of them. It needs no D1 binding at all: the export goes through the API.
|
|
131
|
+
|
|
132
|
+
```text
|
|
133
|
+
backup-worker/
|
|
134
|
+
wrangler.jsonc
|
|
135
|
+
src/index.ts
|
|
136
|
+
src/database-backup.workflow.ts
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
```jsonc
|
|
140
|
+
// backup-worker/wrangler.jsonc: its own Worker, deployed on its own
|
|
141
|
+
{
|
|
142
|
+
"name": "my-app-backups",
|
|
143
|
+
"main": "src/index.ts",
|
|
144
|
+
"compatibility_date": "2026-11-01",
|
|
145
|
+
"workers_dev": false,
|
|
146
|
+
"triggers": { "crons": ["0 4 * * *"] },
|
|
147
|
+
"r2_buckets": [{ "binding": "BACKUPS", "bucket_name": "my-app-backups" }],
|
|
148
|
+
"workflows": [
|
|
149
|
+
{ "name": "my-app-database-backup", "binding": "DATABASE_BACKUP", "class_name": "DatabaseBackup" }
|
|
150
|
+
],
|
|
151
|
+
"vars": { "CF_ACCOUNT_ID": "<account id>", "DB_ID": "<database_id>" }
|
|
152
|
+
}
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
An export can take minutes, so the backup runs as a Workflow: each step retries on its own and a
|
|
156
|
+
restart resumes where it stopped.
|
|
157
|
+
|
|
158
|
+
```ts
|
|
159
|
+
// backup-worker/src/database-backup.workflow.ts
|
|
160
|
+
import { defineBackupWorkflow } from "@cardonjs/backups/workflow";
|
|
161
|
+
|
|
162
|
+
export type Adapters = { readonly backupBucket: R2Bucket };
|
|
163
|
+
export type Config = {
|
|
164
|
+
readonly CF_ACCOUNT_ID: string;
|
|
165
|
+
readonly DB_ID: string;
|
|
166
|
+
readonly D1_EXPORT_TOKEN: string;
|
|
167
|
+
};
|
|
168
|
+
|
|
169
|
+
export const databaseBackup = defineBackupWorkflow<Adapters, Config>({
|
|
170
|
+
name: "database-backup",
|
|
171
|
+
database: (c) => ({
|
|
172
|
+
accountId: c.config.CF_ACCOUNT_ID,
|
|
173
|
+
databaseId: c.config.DB_ID,
|
|
174
|
+
apiToken: c.config.D1_EXPORT_TOKEN,
|
|
175
|
+
}),
|
|
176
|
+
bucket: (c) => c.adapters.backupBucket,
|
|
177
|
+
prefix: "d1/main", // one prefix per database
|
|
178
|
+
keep: { daily: 7, weekly: 4, monthly: 12 },
|
|
179
|
+
});
|
|
180
|
+
```
|
|
181
|
+
|
|
182
|
+
The Worker entry exports the class Wrangler binds, and the daily Cron Trigger starts one instance
|
|
183
|
+
per day:
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
// backup-worker/src/index.ts: the whole backup Worker (no fetch handler)
|
|
187
|
+
import { backupInstanceId } from "@cardonjs/backups";
|
|
188
|
+
import { defineConfig } from "@cardonjs/core";
|
|
189
|
+
import { workflows } from "@cardonjs/workflows-cf";
|
|
190
|
+
import { workflowEntrypoint } from "@cardonjs/workflows-cf/entrypoint";
|
|
191
|
+
import { z } from "zod";
|
|
192
|
+
import { databaseBackup } from "./database-backup.workflow.js";
|
|
193
|
+
|
|
194
|
+
type Bindings = { readonly BACKUPS: R2Bucket; readonly DATABASE_BACKUP: Workflow };
|
|
195
|
+
|
|
196
|
+
const config = defineConfig(
|
|
197
|
+
z.object({ CF_ACCOUNT_ID: z.string(), DB_ID: z.string(), D1_EXPORT_TOKEN: z.string().min(20) }),
|
|
198
|
+
);
|
|
199
|
+
const adapters = (env: Bindings) => ({ backupBucket: env.BACKUPS });
|
|
200
|
+
|
|
201
|
+
export class DatabaseBackup extends workflowEntrypoint(databaseBackup, { adapters, config }) {}
|
|
202
|
+
|
|
203
|
+
export default {
|
|
204
|
+
async scheduled(controller, env, ctx) {
|
|
205
|
+
// backup-2026-11-20: a second start the same day finds the instance and starts nothing.
|
|
206
|
+
const id = backupInstanceId(new Date(controller.scheduledTime));
|
|
207
|
+
ctx.waitUntil(workflows(env.DATABASE_BACKUP, databaseBackup).start({ id, params: {} }));
|
|
208
|
+
},
|
|
209
|
+
} satisfies ExportedHandler<Bindings>;
|
|
210
|
+
```
|
|
211
|
+
|
|
212
|
+
Deploy it with `pnpm wrangler deploy --config backup-worker/wrangler.jsonc`. Each environment
|
|
213
|
+
gets its own bucket, Workflow `name` (account-wide) and token: Wrangler environments inherit none
|
|
214
|
+
of these.
|
|
215
|
+
|
|
216
|
+
### What the steps do
|
|
217
|
+
|
|
218
|
+
**Cloudflare hands out a finished export's signed URL once.** The poll that first reports the
|
|
219
|
+
export `complete` is the only answer that carries it; polling the same export again answers
|
|
220
|
+
"Not currently exporting anything." (observed on a real account on 2026-11-20). So the step that
|
|
221
|
+
receives the `complete` answer is the step that copies, and nothing polls after it:
|
|
222
|
+
|
|
223
|
+
1. **`plan backup`**: fixes the moment the backup stands for (its key), a random run identity
|
|
224
|
+
(`crypto.randomUUID()`, recorded as the object's `run` metadata) and the database id, before
|
|
225
|
+
any export starts. Cloudflare runs the Workflow's code again from the top after every sleep,
|
|
226
|
+
with the config of the version deployed then: if `DB_ID` changed since this step ran, the
|
|
227
|
+
instance fails at once (`backup: the database id changed since this instance started`)
|
|
228
|
+
instead of starting, polling or copying against the new database.
|
|
229
|
+
2. **`start export`**: one call to the export API. If the export is complete at once, this step
|
|
230
|
+
copies it (see step 3); otherwise it stores the bookmark. A failed attempt has no bookmark, so
|
|
231
|
+
a retry starts the export again.
|
|
232
|
+
3. **`wait <n>` / `poll export <n>`**: a sleep of `polling.intervalSeconds` (default 10), then one
|
|
233
|
+
poll. While the export is `active`, the step returns and the instance sleeps again. When the
|
|
234
|
+
poll reports `complete`, **the same step** downloads the dump and streams it into R2 with its
|
|
235
|
+
digest sidecar (see [The copy](#the-copy)), and returns the key, size and digest. After
|
|
236
|
+
`polling.timeoutMinutes` (default 60) of polls the instance fails. Cloudflare's API notes that
|
|
237
|
+
an export that is not polled continually is cancelled, which is why the sleeps are short.
|
|
238
|
+
4. **`restart export <n>`**: when a poll answers that no export is running (`not_exporting`, the
|
|
239
|
+
text above, or `export_lost`: any other error without a status, or an answer about another
|
|
240
|
+
export, see below), polling again cannot help. That happens when the poll step that saw
|
|
241
|
+
`complete` failed midway (a download or R2 error) and was retried, or when Cloudflare
|
|
242
|
+
cancelled the export. Before calling the export lost, the poll step looks at the backup's
|
|
243
|
+
key: if this run already finished its copy there (a step that copied but lost its result),
|
|
244
|
+
it uses it (`reused: true`), even once the restarts are used up. Otherwise the restart step
|
|
245
|
+
looks at the key again, then starts a new export (copying at once if it is already
|
|
246
|
+
complete), and polling resumes. At most **2 restarts** per instance; a third stops it with
|
|
247
|
+
`backup: the export stopped before its dump was copied (2 restarts)`. Each restart runs one
|
|
248
|
+
more export, which blocks the database while it runs.
|
|
249
|
+
|
|
250
|
+
**Do not run a manual export of the same database (`wrangler d1 export`), or a second backup
|
|
251
|
+
instance, while a backup runs.** How Cloudflare handles two exports of one database was not
|
|
252
|
+
verified. If it tracks one per database, a poll could be answered about the other export: the
|
|
253
|
+
client refuses any poll answer whose `at_bookmark` is not the polled bookmark (`export_lost`,
|
|
254
|
+
never `pending` or `ready`, and its dump is never downloaded), so the instance restarts its
|
|
255
|
+
export, but that answer may have consumed the other export's one completion, and the restarts
|
|
256
|
+
are limited.
|
|
257
|
+
5. **`prune backups`**: `pruneBackups` with `keep`, the database id and the Workflow's clock. A
|
|
258
|
+
refusal (another database's backups under the prefix, a backup dated in the future) stops the
|
|
259
|
+
instance at once: `backup: prune refused (other_database)`.
|
|
260
|
+
|
|
261
|
+
Retries never leave two objects or a partial one: the key and the run are fixed by `plan backup`,
|
|
262
|
+
so every retry and every restarted export writes the same key, and reuses the object only when
|
|
263
|
+
its run finished it (see the copy's **Retries** below). The start, restart and poll steps time
|
|
264
|
+
out after 30 minutes, since each may copy; the copy's own deadline (25 minutes, the whole copy)
|
|
265
|
+
ends it first, as `timeout`. A copy failure is logged as `backup copy failed` with its reason
|
|
266
|
+
before the step retries.
|
|
267
|
+
|
|
268
|
+
Cloudflare stores every step's result and shows it in its dashboard: they hold the bookmark, the
|
|
269
|
+
key, the run, the database id, the digest, sizes and counts. **Never the token or the signed
|
|
270
|
+
URL**: the signed URL is used inside the step that received it, and the token is read from the
|
|
271
|
+
config on each run. Failures that will never succeed (a refused token, an unknown database, a
|
|
272
|
+
failed export) stop the instance at once with a fixed message such as
|
|
273
|
+
`backup: export start failed (unauthorized)`; others retry.
|
|
274
|
+
|
|
275
|
+
The instance's output is `{ key, size, bookmark, databaseId, sha256, reused, kept, deleted }`;
|
|
276
|
+
`pnpm wrangler workflows instances describe my-app-database-backup latest` shows it. Right after
|
|
277
|
+
the copy (before pruning, which can fail the instance), the Workflow also logs
|
|
278
|
+
`backup copied` with `key`, `size`, `sha256` and `databaseId`: none of them is secret, and
|
|
279
|
+
**this line and the instance's output are the copies of the digest kept outside the bucket**,
|
|
280
|
+
the ones a restore can trust (see [The restore check](#the-restore-check)). On a reused backup
|
|
281
|
+
(`reused: true`), the digest was computed again by reading the stored dump back from R2 and
|
|
282
|
+
matched the sidecar: it vouches for the bytes in the bucket at that moment, which this run's copy
|
|
283
|
+
wrote and checked, rather than for the bytes as they streamed in. Cloudflare keeps an
|
|
284
|
+
instance's history for a limited time (how long was not verified here), so send the logs
|
|
285
|
+
somewhere that keeps them as long as the backups (a Logpush destination, say).
|
|
286
|
+
|
|
287
|
+
## Encrypting backups
|
|
288
|
+
|
|
289
|
+
**Losing the key loses the backups.** Nobody can read an encrypted backup without the key it
|
|
290
|
+
was made with: not you, not Cloudflare, not this package. There is no recovery. So, **before
|
|
291
|
+
the first encrypted backup runs**, keep every key **outside Cloudflare**, in at least two places
|
|
292
|
+
that do not fail together (the team's password manager and an offline copy in a safe, say). A
|
|
293
|
+
Worker secret cannot be read back: a key that lives only there is gone the day the Worker, the
|
|
294
|
+
account or the secret is. Keep each key for as long as any backup made with it exists,
|
|
295
|
+
downloaded copies included.
|
|
296
|
+
|
|
297
|
+
Encryption is opt-in. Without the `encryption` option nothing changes; with it, each dump is
|
|
298
|
+
encrypted in the backup Worker while it streams into R2 (AES-256-GCM in 64 KiB chunks, a key
|
|
299
|
+
derived for each backup from yours and a random salt; byte by byte in `FORMAT.md`). It uses
|
|
300
|
+
`crypto.subtle` only, no dependency.
|
|
301
|
+
|
|
302
|
+
**What it protects against**: whoever can read the bucket (an R2 token, a binding in the wrong
|
|
303
|
+
Worker, a dashboard user) gets ciphertext. A modified, cut or reordered object fails to decrypt.
|
|
304
|
+
|
|
305
|
+
**What a backup is bound to.** Its authenticated header names the D1 database id and the full
|
|
306
|
+
R2 key it was written to. Decrypting with what you expect (`decryptBackup`'s `expected`,
|
|
307
|
+
`checkRestore`'s `key` and `databaseId`, the runbook's script) refuses an authentic backup of
|
|
308
|
+
something else (`wrong_backup`): another database's, staging's under the same key, or another
|
|
309
|
+
date's copied over this key. `expected` binds the **database and the key name**, not one
|
|
310
|
+
particular write: two authentic objects can share both (a late `put` from an earlier attempt of
|
|
311
|
+
the same run, or a copy rewritten after the key was rotated mid-run), and only the digest kept
|
|
312
|
+
outside the bucket (the instance's output, the `backup copied` log line) tells them apart. Nor
|
|
313
|
+
does it decide **which key name you restore**: restoring an older date is the operator's choice
|
|
314
|
+
of key, and an attacker who can write the bucket can delete newer backups so that an older one
|
|
315
|
+
looks like the latest, which the digests and dates in your logs show. Use **a separate key per environment** anyway (`k2026-11-prod`,
|
|
316
|
+
`k2026-11-staging`): binding stops a swap, separate keys stop a staging Worker from reading or
|
|
317
|
+
writing production backups at all.
|
|
318
|
+
|
|
319
|
+
**What it does not**: the backup Worker holds the current key, so whoever controls that Worker
|
|
320
|
+
or its secrets can read and write backups made with it; a backup's size (about the dump's), its
|
|
321
|
+
timing and its metadata (database id, key id) stay visible; and whoever can write the bucket can
|
|
322
|
+
still delete backups.
|
|
323
|
+
|
|
324
|
+
### Turning it on
|
|
325
|
+
|
|
326
|
+
1. **Make a key**: 32 random bytes in base64url (43 characters).
|
|
327
|
+
|
|
328
|
+
```sh
|
|
329
|
+
node -e "process.stdout.write(require('node:crypto').randomBytes(32).toString('base64url'))"
|
|
330
|
+
```
|
|
331
|
+
|
|
332
|
+
Store it where you keep secrets (see above) first, under its **key id**: 1 to 32 lowercase
|
|
333
|
+
letters, digits, `-` or `_` (`k2026-11`, the month it was made). Key ids are not secret:
|
|
334
|
+
they go into the object's metadata, the instance's output and the encrypted file's header,
|
|
335
|
+
so a restore knows which key it needs.
|
|
336
|
+
|
|
337
|
+
2. **Give it to the backup Worker only**, as a secret:
|
|
338
|
+
`pnpm wrangler secret put BACKUP_KEY_K2026_11 --config backup-worker/wrangler.jsonc`, and add
|
|
339
|
+
it to the Worker's config schema (`BACKUP_KEY_K2026_11: z.string()`).
|
|
340
|
+
|
|
341
|
+
3. **Pass it to the Workflow** (the package reads no binding by name):
|
|
342
|
+
|
|
343
|
+
```ts
|
|
344
|
+
// backup-worker/src/database-backup.workflow.ts
|
|
345
|
+
import { backupEncryption } from "@cardonjs/backups";
|
|
346
|
+
import { defineBackupWorkflow } from "@cardonjs/backups/workflow";
|
|
347
|
+
|
|
348
|
+
export const databaseBackup = defineBackupWorkflow<Adapters, Config>({
|
|
349
|
+
name: "database-backup",
|
|
350
|
+
database: (c) => ({
|
|
351
|
+
accountId: c.config.CF_ACCOUNT_ID,
|
|
352
|
+
databaseId: c.config.DB_ID,
|
|
353
|
+
apiToken: c.config.D1_EXPORT_TOKEN,
|
|
354
|
+
}),
|
|
355
|
+
bucket: (c) => c.adapters.backupBucket,
|
|
356
|
+
prefix: "d1/main",
|
|
357
|
+
keep: { daily: 7, weekly: 4, monthly: 12 },
|
|
358
|
+
encryption: (c) =>
|
|
359
|
+
backupEncryption({
|
|
360
|
+
keys: { "k2026-11": c.config.BACKUP_KEY_K2026_11 },
|
|
361
|
+
current: "k2026-11",
|
|
362
|
+
}),
|
|
363
|
+
});
|
|
364
|
+
```
|
|
365
|
+
|
|
366
|
+
With `runBackup` or `copyExport`, pass `encryption: backupEncryption({ keys, current })`.
|
|
367
|
+
|
|
368
|
+
`backupEncryption` checks the settings once: every key 32 bytes of base64url, ids of the pattern
|
|
369
|
+
above, `current` one of the ids, no key listed under two ids. It throws a `TypeError` that names
|
|
370
|
+
neither a key nor an id. `runBackup` and `copyExport` check before anything starts; the
|
|
371
|
+
Workflow reads its secrets when an instance runs, so it checks there, before any step: invalid
|
|
372
|
+
keys stop the instance at once with `backup: invalid encryption options` (nothing exported, no
|
|
373
|
+
step stored).
|
|
374
|
+
|
|
375
|
+
**It never fails open.** Only leaving the `encryption` property out means plain. In
|
|
376
|
+
`defineBackupWorkflow`, an `encryption` property that is present but not a function
|
|
377
|
+
(`encryption: env.BACKUP_KEY ? (c) => … : undefined`) is a `TypeError` when the Workflow is
|
|
378
|
+
defined; an `encryption` function that returns `null` or `undefined` (a ternary on a secret
|
|
379
|
+
missing in this environment, say) stops the instance with `backup: invalid encryption options`;
|
|
380
|
+
an `encryption`
|
|
381
|
+
property that is present but `null` or `undefined` is a `TypeError` in `copyExport`,
|
|
382
|
+
`runBackup` and `checkRestore`. So a missing secret can never write a plain backup, nor replace
|
|
383
|
+
an encrypted copy with a plain one.
|
|
384
|
+
|
|
385
|
+
The keys are kept out of reach of logging and `JSON.stringify` (the object shows the scheme,
|
|
386
|
+
`current` and the ids only). Each key is imported as a non-extractable `CryptoKey` the first time
|
|
387
|
+
a run needs it, and its decoded bytes are zeroed right after; keys a run never uses stay decoded
|
|
388
|
+
in memory until the settings object is collected, and the base64 strings your Worker read from
|
|
389
|
+
its environment are not the package's to erase.
|
|
390
|
+
|
|
391
|
+
What changes with it on:
|
|
392
|
+
|
|
393
|
+
- the object is the encrypted format (`CARDONBK…`, `application/octet-stream`), with metadata
|
|
394
|
+
`encryption: aes-256-gcm-stream-v1` and `key-id`; the sidecar carries both too;
|
|
395
|
+
- `size`, `bytes`, `sha256` and the sidecar's digest are of the **encrypted** bytes (what R2
|
|
396
|
+
holds, what reuse and the restore check recompute); no digest of the plaintext is stored
|
|
397
|
+
anywhere outside the ciphertext;
|
|
398
|
+
- the result, the instance's output and step results gain `encryption: { scheme, keyId }`, and
|
|
399
|
+
the `backup copied` log line gains `keyId`; never a key, never plaintext;
|
|
400
|
+
- the copy takes the same paths: a dump with `Content-Length` is still one known-length `put`
|
|
401
|
+
(the encrypted size is computed from the plaintext size); the path in parts encrypts before
|
|
402
|
+
splitting into parts;
|
|
403
|
+
- **retention needs no key** and treats encrypted and plain backups alike;
|
|
404
|
+
- **reuse** (a retried step finding its own finished copy) also requires the copy to be
|
|
405
|
+
encrypted as now asked: a copy of the same run made in plain, or with another key id, is
|
|
406
|
+
**written again** under the current settings (a deploy that turned encryption on, or rotated
|
|
407
|
+
the key, while an instance was running). It is never reused nor reported as `exists`. The
|
|
408
|
+
metadata is not taken on its word: reuse reads the object back once (the same read as its
|
|
409
|
+
digest) and decrypts it whole with the current key, checking that its header names this
|
|
410
|
+
database and this key; anything else (plain bytes under forged metadata, another key's or
|
|
411
|
+
another backup's object) is written again;
|
|
412
|
+
- the step results and log line of pruning (`backups pruned`) gain `keyIds`: the key ids the
|
|
413
|
+
kept backups name. `listBackups` and `pruneBackups` report them too (`keyIds`, read from
|
|
414
|
+
metadata, no key needed). Metadata is a hint, not proof: see the check before destroying a
|
|
415
|
+
key, under [Rotating the key](#rotating-the-key).
|
|
416
|
+
|
|
417
|
+
**Backups made before** stay as they are: plain, readable without a key, restored as before.
|
|
418
|
+
Nothing re-encrypts them; prune them out or delete them when they must not stay in plain.
|
|
419
|
+
|
|
420
|
+
### Rotating the key
|
|
421
|
+
|
|
422
|
+
**The backup Worker never decrypts**: it encrypts with `current`, and reuse only accepts objects
|
|
423
|
+
made with `current`. So it needs **only the current key**; older keys belong offline, where
|
|
424
|
+
restores happen.
|
|
425
|
+
|
|
426
|
+
1. Make a new key and store it outside Cloudflare (as above), with a new id (`k2027-05`).
|
|
427
|
+
2. Give the Worker the new key only, as `current`; deploy; then delete the old secret
|
|
428
|
+
(`pnpm wrangler secret delete BACKUP_KEY_K2026_11 --config backup-worker/wrangler.jsonc`):
|
|
429
|
+
|
|
430
|
+
```ts
|
|
431
|
+
encryption: (c) =>
|
|
432
|
+
backupEncryption({
|
|
433
|
+
keys: { "k2027-05": c.config.BACKUP_KEY_K2027_05 },
|
|
434
|
+
current: "k2027-05",
|
|
435
|
+
}),
|
|
436
|
+
```
|
|
437
|
+
|
|
438
|
+
New backups use the new key; old ones stay readable offline with the old one (each file
|
|
439
|
+
names its key id).
|
|
440
|
+
3. **Destroy an old key only when nothing names it any more**: no listed backup and no downloaded
|
|
441
|
+
copy. `keyIds` of `listBackups` (or of `pruneBackups`, and the `backups pruned` log line of
|
|
442
|
+
each Workflow run, for the backups it kept) is a first hint, **not proof**: it comes from
|
|
443
|
+
custom metadata, which whoever can write the bucket can change, and it only counts objects
|
|
444
|
+
that carry the package's marker under that one prefix. An object whose metadata was stripped
|
|
445
|
+
or forged, one re-uploaded by another tool (Wrangler, the dashboard, a sync), or the same key
|
|
446
|
+
used under another prefix, bucket or database is not counted. So, before destroying a key,
|
|
447
|
+
confirm from the objects themselves: read the first bytes of **every** object under every
|
|
448
|
+
prefix the key was used for and look at the key id its header claims, with this script (one
|
|
449
|
+
range read of 46 bytes per object, no key needed):
|
|
450
|
+
|
|
451
|
+
```ts
|
|
452
|
+
// backup-worker/scripts/key-ids.ts: the key id each object's header claims, under a prefix
|
|
453
|
+
import { claimedKeyId, KEY_ID_PROBE_BYTES } from "@cardonjs/backups";
|
|
454
|
+
|
|
455
|
+
/** Key id → how many objects under `prefix` claim it (`(plain)` for the others). */
|
|
456
|
+
export async function claimedKeyIds(
|
|
457
|
+
bucket: R2Bucket,
|
|
458
|
+
prefix: string,
|
|
459
|
+
): Promise<Map<string, number>> {
|
|
460
|
+
const counts = new Map<string, number>();
|
|
461
|
+
let cursor: string | undefined;
|
|
462
|
+
do {
|
|
463
|
+
const page = await bucket.list({ prefix: `${prefix}/`, ...(cursor ? { cursor } : {}) });
|
|
464
|
+
for (const object of page.objects) {
|
|
465
|
+
const head = await bucket.get(object.key, {
|
|
466
|
+
range: { offset: 0, length: KEY_ID_PROBE_BYTES },
|
|
467
|
+
});
|
|
468
|
+
const first = new Uint8Array((await head?.arrayBuffer()) ?? new ArrayBuffer(0));
|
|
469
|
+
const id = claimedKeyId(first) ?? "(plain)";
|
|
470
|
+
counts.set(id, (counts.get(id) ?? 0) + 1);
|
|
471
|
+
}
|
|
472
|
+
cursor = page.truncated ? page.cursor : undefined;
|
|
473
|
+
} while (cursor !== undefined);
|
|
474
|
+
return counts;
|
|
475
|
+
}
|
|
476
|
+
```
|
|
477
|
+
|
|
478
|
+
Run it like the [inspection script](#when-a-backup-or-a-prune-is-refused) (a remote binding
|
|
479
|
+
through `getPlatformProxy`; not run against a real account here) and print the counts. What a
|
|
480
|
+
header claims is not authenticated either (only decrypting with the key proves it), but an
|
|
481
|
+
object that claims the key id you are about to destroy is one you would lose. Then check that
|
|
482
|
+
no copy made from those backups exists elsewhere (restores, archives) before destroying the
|
|
483
|
+
key's offline copies.
|
|
484
|
+
|
|
485
|
+
If a key may have leaked, rotate at once: backups made with it must be assumed readable by
|
|
486
|
+
whoever has it. This version cannot re-encrypt them; delete them if that matters more than
|
|
487
|
+
keeping them.
|
|
488
|
+
|
|
489
|
+
## The pieces
|
|
490
|
+
|
|
491
|
+
For small databases, a cron handler can do it all in one call (no retries: a failure is a
|
|
492
|
+
result, and the next run starts over; the one exception is an export Cloudflare stops running,
|
|
493
|
+
which is started again at most twice, within the same deadline). It copies from the answer that
|
|
494
|
+
reports the export complete and never polls after it. It still belongs in the backup Worker, not
|
|
495
|
+
the app's:
|
|
496
|
+
|
|
497
|
+
```ts
|
|
498
|
+
import { d1Export, runBackup } from "@cardonjs/backups";
|
|
499
|
+
|
|
500
|
+
const exporter = d1Export({
|
|
501
|
+
accountId: env.CF_ACCOUNT_ID,
|
|
502
|
+
databaseId: env.DB_ID,
|
|
503
|
+
apiToken: env.D1_EXPORT_TOKEN,
|
|
504
|
+
});
|
|
505
|
+
const result = await runBackup({
|
|
506
|
+
exporter,
|
|
507
|
+
bucket: env.BACKUPS,
|
|
508
|
+
prefix: "d1/main",
|
|
509
|
+
keep: { daily: 7, weekly: 4, monthly: 12 },
|
|
510
|
+
});
|
|
511
|
+
if (result.ok) {
|
|
512
|
+
// Not secret: the digest kept outside the bucket, for the restore check.
|
|
513
|
+
logger.info("backup copied", { key: result.key, size: result.size, sha256: result.sha256 });
|
|
514
|
+
} else {
|
|
515
|
+
logger.error("backup failed", { stage: result.stage, reason: result.reason });
|
|
516
|
+
}
|
|
517
|
+
```
|
|
518
|
+
|
|
519
|
+
`runBackup` fits in the 15 minutes a Cron Trigger may run, with room to spare: `start`, the
|
|
520
|
+
polls and any restarted export take at most `timeoutMs` (default 4 minutes) plus one last
|
|
521
|
+
request (30 s, the client's per-request timeout); the copy at most `copyTimeoutMs` (default 8 minutes, the whole
|
|
522
|
+
copy) plus 5 s to abort an open multipart upload. That is about 12.6 minutes, leaving over two for
|
|
523
|
+
listing and pruning (one list call per 1000 objects under the prefix, one delete call per 1000
|
|
524
|
+
keys). Raise either only with that sum in mind. A refused prune is
|
|
525
|
+
`{ ok: false, stage: "prune", reason, key }`: the backup at `key` was written, nothing was
|
|
526
|
+
deleted.
|
|
527
|
+
|
|
528
|
+
Or step by step:
|
|
529
|
+
|
|
530
|
+
```ts
|
|
531
|
+
import { backupKey, copyExport, d1Export, pruneBackups } from "@cardonjs/backups";
|
|
532
|
+
|
|
533
|
+
const exporter = d1Export({ accountId, databaseId, apiToken });
|
|
534
|
+
let answer = await exporter.start(); // pending, ready or failed
|
|
535
|
+
while (answer.status === "pending") {
|
|
536
|
+
await sleep(10_000); // keep polling: an export that is not polled is cancelled
|
|
537
|
+
answer = await exporter.poll(answer.bookmark);
|
|
538
|
+
}
|
|
539
|
+
if (answer.status === "failed") throw new Error(`export failed (${answer.reason})`);
|
|
540
|
+
// The only answer that carries the dump: Cloudflare hands its signed URL out once.
|
|
541
|
+
const info = await copyExport({
|
|
542
|
+
exporter,
|
|
543
|
+
ready: answer, // never a bookmark to poll again
|
|
544
|
+
bucket: env.BACKUPS,
|
|
545
|
+
key: backupKey("d1/main", new Date()),
|
|
546
|
+
run: crypto.randomUUID(), // this backup's identity: the same for every retry of it
|
|
547
|
+
});
|
|
548
|
+
const removed = await pruneBackups(env.BACKUPS, {
|
|
549
|
+
prefix: "d1/main",
|
|
550
|
+
databaseId: exporter.databaseId,
|
|
551
|
+
keep: { daily: 7, weekly: 4, monthly: 12 },
|
|
552
|
+
dryRun: true, // report only
|
|
553
|
+
});
|
|
554
|
+
```
|
|
555
|
+
|
|
556
|
+
`copyExport` takes the `ready` answer itself and never polls: that answer is the only one with
|
|
557
|
+
the signed URL. A copy that fails after it cannot be retried from the same export; a retry
|
|
558
|
+
starts a new export and calls `copyExport` again with **the same `key` and `run`**, so it reuses
|
|
559
|
+
the object if the failed attempt had in fact finished it. `sleep` above is any wait
|
|
560
|
+
(`scheduler.wait` on Workers).
|
|
561
|
+
|
|
562
|
+
Every expected outcome is a result, never an exception: `start` and `poll` return
|
|
563
|
+
`{ status: "pending" }`, `{ status: "ready" }` or
|
|
564
|
+
`{ status: "failed", reason, retryable }` (`unauthorized`, `not_found`, `rejected`,
|
|
565
|
+
`rate_limited`, `unavailable`, `network`, `timeout`, `malformed`, `export_failed`,
|
|
566
|
+
`not_exporting`, `export_lost`, `signed_url_refused`). `not_exporting` is Cloudflare's
|
|
567
|
+
"Not currently exporting anything." (matched exactly): the export's completion was already
|
|
568
|
+
handed out, or the export was cancelled. `export_lost` is any other error without a status, or
|
|
569
|
+
a poll's answer whose `at_bookmark` is not the polled bookmark (an answer about another export
|
|
570
|
+
of the database), read the same way. An `error` key counts even when it is `null` (it fails
|
|
571
|
+
closed). Both have `retryable: false` (polling again cannot help) and mean "start a new
|
|
572
|
+
export". `copyExport` returns `{ ok: true, key, size, sha256, … }` or
|
|
573
|
+
`{ ok: false, reason, retryable }` (`exists`, `empty`, `not_sql`, `size_mismatch`, `too_large`,
|
|
574
|
+
`read_failed`, `write_failed`, `timeout`, and the download's `expired`, `redirected`,
|
|
575
|
+
`unavailable`, `rate_limited`, `network`, `refused`), where `retryable` says whether another
|
|
576
|
+
attempt with a new export may succeed. Invalid options throw a `TypeError` that never includes
|
|
577
|
+
the value. Any answer the client does not understand is `malformed`, never `ready`.
|
|
578
|
+
|
|
579
|
+
`unauthorized` is a 401 or 403, or Cloudflare's error code 10000 whatever the status: the token
|
|
580
|
+
is wrong, expired, or lacks the permission. **A D1 Read token is not enough**: the export needs
|
|
581
|
+
D1 Write.
|
|
582
|
+
|
|
583
|
+
`d1Export` options: `accountId` and `databaseId` must have Cloudflare's shapes (32 hex
|
|
584
|
+
characters; a UUID), so they cannot change the request's host or path. `format: "sqlite3"` asks
|
|
585
|
+
for `dump_options.compatibility: "sqlite3_cli_only"`, which a database with virtual tables (FTS5)
|
|
586
|
+
needs; **that dump loads into the `sqlite3` CLI only, never back into D1**. `timeoutMs` bounds
|
|
587
|
+
each API request (default 30 s). `fetch` replaces the global `fetch` (for tests): **it receives
|
|
588
|
+
the API token (in a header) and the signed URL, so never log inside it**.
|
|
589
|
+
|
|
590
|
+
### The signed URL
|
|
591
|
+
|
|
592
|
+
A ready export comes with a signed URL to download the dump, in `result.result.signed_url` of
|
|
593
|
+
the poll that reports it complete (where the real API put it on 2026-11-20, and where Wrangler
|
|
594
|
+
reads it; `result.signed_url`, from Cloudflare's Workflows example, is accepted too). Only that
|
|
595
|
+
answer carries it. It is a capability: whoever has it can download every row until it expires.
|
|
596
|
+
So the client never returns it: `ready.download()` fetches it from a closure, and it appears in
|
|
597
|
+
no result, error or log line.
|
|
598
|
+
|
|
599
|
+
The download:
|
|
600
|
+
|
|
601
|
+
- is a `GET` with **no credentials**: no `Authorization` header, no API token;
|
|
602
|
+
- accepts **`https` only**, on the default port, with no user or password in the URL, to a
|
|
603
|
+
**DNS name** (no IP literal, no `localhost`);
|
|
604
|
+
- **follows no redirect** (`redirect: "manual"`): a 3xx is a failure (`redirected`), so the
|
|
605
|
+
request goes only to the host that was checked;
|
|
606
|
+
- `401`, `403`, `404` and `410` are `expired` (retryable, with a new export: polling again gives
|
|
607
|
+
no new URL, so the Workflow's retry gets `not_exporting` and restarts the export);
|
|
608
|
+
- takes an optional `signal`: `copyExport` passes one that aborts at its deadline (`timeout`).
|
|
609
|
+
|
|
610
|
+
Which hosts are accepted: by default, any public DNS name over https. The URL comes from an
|
|
611
|
+
answer of `https://api.cloudflare.com` authenticated with your token, over TLS, so trusting its
|
|
612
|
+
host is trusting Cloudflare's API; pinning a host this package cannot verify offline would break
|
|
613
|
+
every backup if Cloudflare changes it. **Once you have observed the host your account gets, set
|
|
614
|
+
`signedUrlHosts`**: `["exact.host"]` or `["*.suffix"]`. To observe it, run one backup on
|
|
615
|
+
staging with a `fetch` option that records `new URL(url).host` for requests that are not to
|
|
616
|
+
`api.cloudflare.com`, and nothing else: never the whole URL.
|
|
617
|
+
|
|
618
|
+
### The copy
|
|
619
|
+
|
|
620
|
+
`copyExport` streams; the dump never has to fit in memory, and the object appears only when it is
|
|
621
|
+
complete and checked:
|
|
622
|
+
|
|
623
|
+
- When the download states its length (`Content-Length`, not compressed) and it is at most
|
|
624
|
+
`singlePutLimit` (4 GiB by default), it is **one `put`** of a stream of that length (R2
|
|
625
|
+
bindings refuse a stream of unknown length). On the way it counts the bytes and reads the
|
|
626
|
+
start: a stream that ends early or late, fails, or does not start like SQL makes the `put`
|
|
627
|
+
fail, and R2 stores nothing. R2 documents a limit of about 5 GiB for a single upload; this
|
|
628
|
+
package was not able to check it, so it stays well under it.
|
|
629
|
+
- Otherwise (unknown length, or larger than `singlePutLimit`) it reads the dump in parts of
|
|
630
|
+
`partSize` (default 10 MiB, 5 to 32 MiB): a dump that fits in one part is one `put` of those
|
|
631
|
+
bytes; a larger one is a **multipart upload**, completed only after the last part and aborted
|
|
632
|
+
on any failure. The copy holds at most two parts in memory at once, so the 32 MiB ceiling keeps
|
|
633
|
+
it near 64 MiB of a Worker's 128 MB. A Worker that dies mid-upload cannot abort it: add a
|
|
634
|
+
lifecycle rule that cleans incomplete uploads,
|
|
635
|
+
`pnpm wrangler r2 bucket lifecycle add my-app-backups abort-uploads --abort-multipart-days 1`.
|
|
636
|
+
- After writing, the stored size must equal what was read.
|
|
637
|
+
- The dump must not be empty and must start like SQL (`PRAGMA`, `BEGIN`, `CREATE` or `INSERT`):
|
|
638
|
+
an HTML or XML error page is refused.
|
|
639
|
+
- **Digest.** On Workers, the dump's SHA-256 is computed as it streams (`crypto.DigestStream`)
|
|
640
|
+
and written, once the dump is stored and checked, to a sidecar object `<key>.sha256` (64 hex
|
|
641
|
+
characters, with the same marker, bookmark, run and database id, and the dump object's
|
|
642
|
+
identity in `dump-object`). It is a separate object because a
|
|
643
|
+
multipart upload's metadata is fixed when it starts, before the digest is known. The result's
|
|
644
|
+
`sha256` is the same value. Node has no incremental digest of a stream, so a copy run from Node
|
|
645
|
+
(tests) writes no sidecar and returns `sha256: null`. **The sidecar detects corruption, not
|
|
646
|
+
tampering**: it sits in the same bucket, and whoever can rewrite the dump can rewrite it too.
|
|
647
|
+
For tamper evidence, compare a restore with a digest kept outside the bucket: the Workflow
|
|
648
|
+
instance's output or its `backup copied` log line (with `runBackup`, log `key`, `size` and
|
|
649
|
+
`sha256` yourself after each backup, as in the example above).
|
|
650
|
+
- **Deadline.** `timeoutMs` (default 25 minutes, under the Workflow steps' 30) bounds the whole
|
|
651
|
+
copy: looking at the key, the download, every read of the body and every R2 call (`put`,
|
|
652
|
+
`createMultipartUpload`, `uploadPart`, `complete`, the sidecar's `put`). A stalled connection
|
|
653
|
+
or a stalled write ends as `timeout`; an open multipart upload then gets 5 seconds to abort (the
|
|
654
|
+
lifecycle rule above cleans one that does not). What a deadline cannot undo: a `put` or
|
|
655
|
+
`complete` that was already in flight may still land afterwards. It holds a whole, checked dump
|
|
656
|
+
without a sidecar, so a retry writes the key again; the copy issues no delete after the
|
|
657
|
+
deadline, since one landing late could remove what a retry wrote since. Since a retry now uses
|
|
658
|
+
a new export, such a late write could even land **after** the retry's copy: the key then holds
|
|
659
|
+
the earlier export's complete dump next to the retry's sidecar. Both exports can have the same
|
|
660
|
+
bookmark (a database that did not change in between), so the bookmark cannot tell them apart;
|
|
661
|
+
the sidecar names the exact object it was written for (its R2 `version`, see **Retries**), and
|
|
662
|
+
the late write is another object. No copy of the run accepts that pair as finished (it
|
|
663
|
+
rewrites the key), and the restore check with the digest kept outside the bucket reports a
|
|
664
|
+
dump that is not the one recorded.
|
|
665
|
+
- Custom metadata: `cardon-backup` (`"1"`), `bookmark` (what the export reported), `run` (the
|
|
666
|
+
backup run that wrote it), `database-id`, `created-at` (ISO 8601), `format`, and `bytes` when
|
|
667
|
+
the size was known before the upload (not for a multipart upload of unknown length; the
|
|
668
|
+
object's own size is the same number); with encryption, `encryption` and `key-id` too, and
|
|
669
|
+
`bytes` is the encrypted size.
|
|
670
|
+
- **Retries.** A key that already holds an object is reused (`reused: true`, nothing downloaded
|
|
671
|
+
or written) only when it is this run's finished backup: the marker, the same database id, a
|
|
672
|
+
`run` equal to **this call's run**, the stored size equal to the recorded `bytes`, and, on
|
|
673
|
+
Workers, its sidecar: the same database id, run and export bookmark as the dump, a
|
|
674
|
+
`dump-object` naming **the object now at the key** (the `version` R2 returned from the dump's
|
|
675
|
+
`put` or multipart `complete`, falling back to its `etag`; a later write of the key has
|
|
676
|
+
another), at most 66 bytes (its metadata and size are checked before its content is read), and
|
|
677
|
+
a digest equal to the one computed again by **reading the stored dump back** (an R2 read of
|
|
678
|
+
the whole dump, no export). So a reused backup's `sha256` is the digest of the bytes in the
|
|
679
|
+
bucket at that moment, checked against the sidecar: it proves the stored dump is the one the
|
|
680
|
+
run's copy wrote and checked, not merely that a sidecar says so. On Node (no incremental
|
|
681
|
+
digest, no sidecar) reuse still rests on the metadata and the size alone, and `sha256` is
|
|
682
|
+
`null`. The run is fixed before the
|
|
683
|
+
first export starts and passed unchanged to every retry; the export's bookmark is not, since a
|
|
684
|
+
restarted export has another one. So an object this run finished with an earlier export is
|
|
685
|
+
its backup (a complete, checked dump of the same database, seconds older), and is reused; an
|
|
686
|
+
object of another run at the same key (another instance or call in the same second, even with
|
|
687
|
+
the same bookmark) is `exists`. An object of this run that is not proven finished (a put that
|
|
688
|
+
went through before a check failed and its cleanup failed too, a run that died before the
|
|
689
|
+
sidecar, a sidecar of another of its exports or of another write of the key, a digest that
|
|
690
|
+
does not match the stored bytes) is written again.
|
|
691
|
+
- **The copy looks at no other key.** A stray object under the prefix (another database's backup,
|
|
692
|
+
a sidecar without its dump) never stops a backup: the backup is written, and `pruneBackups`
|
|
693
|
+
then refuses, loudly, with the backup already safe (see
|
|
694
|
+
[When a backup or a prune is refused](#when-a-backup-or-a-prune-is-refused)).
|
|
695
|
+
|
|
696
|
+
**Very large dumps.** The copy is mostly waiting on the network, but it spends CPU on every chunk
|
|
697
|
+
(counting, the SQL check, SHA-256, and AES-GCM with encryption on: one `crypto.subtle` call per
|
|
698
|
+
64 KiB). For dumps of several GB, measure a copy on staging, raise the
|
|
699
|
+
backup Worker's CPU limit (`limits.cpu_ms` in its Wrangler config) if it runs out, and keep the
|
|
700
|
+
copy inside the steps' 30 minutes. A database whose dump cannot be copied in that time is
|
|
701
|
+
beyond what this version handles.
|
|
702
|
+
|
|
703
|
+
### Keys
|
|
704
|
+
|
|
705
|
+
`<prefix>/<yyyy>/<mm>/<yyyy-mm-ddThh-mm-ssZ>.sql`, in UTC, built only by `backupKey(prefix, at)`:
|
|
706
|
+
`d1/main/2026/11/2026-11-20T04-00-03Z.sql`, and its sidecar
|
|
707
|
+
`d1/main/2026/11/2026-11-20T04-00-03Z.sql.sha256`. A prefix is 1 to 8 segments of letters,
|
|
708
|
+
digits, `-` and `_`. `copyExport` refuses any other key, and retention recognises exactly this
|
|
709
|
+
pattern.
|
|
710
|
+
|
|
711
|
+
## Retention
|
|
712
|
+
|
|
713
|
+
`pruneBackups(bucket, { prefix, databaseId, keep, dryRun, now })` keeps:
|
|
714
|
+
|
|
715
|
+
- `daily: N`: the newest backup of each of the N most recent **days that have a backup**;
|
|
716
|
+
- `weekly: N`: the same per **ISO week** (Monday to Sunday; the week-year of ISO 8601, so
|
|
717
|
+
1 January 2027, a Friday, is in week 53 of 2026);
|
|
718
|
+
- `monthly: N`: the same per calendar month.
|
|
719
|
+
|
|
720
|
+
All periods are in **UTC**, read from the key. Counts are of periods that have a backup, as in
|
|
721
|
+
restic and Borg, not of calendar days back from today: if backups stop for a month, the old ones
|
|
722
|
+
are not pruned away by the passing of time. The rules are combined (a backup kept by any rule is
|
|
723
|
+
kept). `{ daily: 7, weekly: 4, monthly: 12 }` keeps about 20 copies covering a year.
|
|
724
|
+
|
|
725
|
+
**One prefix per database.** `databaseId` is the database the backups are of
|
|
726
|
+
(`exporter.databaseId`). Two databases backed up under one prefix would prune each other's
|
|
727
|
+
backups (each would see the other's as its own newest), so `pruneBackups` **refuses**, deleting
|
|
728
|
+
nothing, while the prefix holds any backup or sidecar of another database (or a marked one with
|
|
729
|
+
no database id): it throws a `PruneRefusedError` with `reason: "other_database"` and how many.
|
|
730
|
+
The Workflow stops with `backup: prune refused (other_database)`; `runBackup` answers
|
|
731
|
+
`stage: "prune"`. The backups themselves keep being written: the refusal stops pruning only.
|
|
732
|
+
Give each database its own prefix (`d1/main`, `d1/analytics`); to find the objects behind a
|
|
733
|
+
refusal, see [When a backup or a prune is refused](#when-a-backup-or-a-prune-is-refused).
|
|
734
|
+
|
|
735
|
+
Safety:
|
|
736
|
+
|
|
737
|
+
- the **newest backup is never deleted**, whatever the policy;
|
|
738
|
+
- a policy that keeps nothing (`{}`, all zeros) is refused, and so is a plan that would delete
|
|
739
|
+
every backup;
|
|
740
|
+
- **a backup dated more than a day after `now()`** (default the current time) makes it refuse
|
|
741
|
+
too (`reason: "future_backups"`, with how many): a key far in the future would take every slot
|
|
742
|
+
and count as the newest, pushing every real backup out. Find and remove it by hand;
|
|
743
|
+
- only objects under `<prefix>/` whose key matches the pattern **exactly** and that carry the
|
|
744
|
+
`cardon-backup` marker are considered: anything else in the bucket (a manual copy, another
|
|
745
|
+
prefix, `d1/main2/…`) is never touched and is counted as `ignored`;
|
|
746
|
+
- **sidecars** (`<key>.sha256`) are never counted as backups: each is deleted with its dump
|
|
747
|
+
(`deletedDigests`), and a sidecar of this database whose dump is gone is deleted too, once its
|
|
748
|
+
key is dated more than a day before `now()` (a newer one may belong to a run still writing its
|
|
749
|
+
dump, missed by a listing that crossed a page boundary between the two);
|
|
750
|
+
- the listing follows every page before deciding (and refuses more than 100 000 objects under
|
|
751
|
+
the prefix rather than act on a partial list); deletes go in batches of 1000 keys. A batch that
|
|
752
|
+
fails throws (`a delete batch failed after N of M keys were deleted`): earlier batches stay
|
|
753
|
+
deleted, never the newest, and the next run continues;
|
|
754
|
+
- `dryRun: true` returns `kept`, `deleted` and `deletedDigests` and deletes nothing.
|
|
755
|
+
|
|
756
|
+
`planRetention(entries, keep)` is the pure decision, for tests and previews.
|
|
757
|
+
|
|
758
|
+
When "delete everything older than N days" is enough, an R2 lifecycle rule is simpler and needs
|
|
759
|
+
no code: `pnpm wrangler r2 bucket lifecycle add my-app-backups expire-backups d1/main/ --expire-days 90`.
|
|
760
|
+
Do not combine one with `pruneBackups` on the same prefix: the rule does not know which backup
|
|
761
|
+
is the newest.
|
|
762
|
+
|
|
763
|
+
### Personal data
|
|
764
|
+
|
|
765
|
+
A backup keeps every row as it was, **including the data of users who deleted their account
|
|
766
|
+
since**, until that backup is pruned. Choose `keep` with your privacy policy and legal
|
|
767
|
+
obligations in mind, say how long backups are kept in that policy, and remember that restoring
|
|
768
|
+
an old backup brings deleted data back: after a restore, re-apply the deletions made since. If a
|
|
769
|
+
person's data must be erased from backups too, the only tools are retention and deleting the
|
|
770
|
+
affected backups.
|
|
771
|
+
|
|
772
|
+
## When a backup or a prune is refused
|
|
773
|
+
|
|
774
|
+
Refusals carry counts, never keys or ids (errors and step results end up in dashboards and
|
|
775
|
+
logs), and Wrangler cannot list an object's custom metadata. To see what caused one, list the
|
|
776
|
+
prefix with this script: it prints each object's **key, database id and kind**, and nothing else
|
|
777
|
+
from its metadata (keys and database ids are not secrets; bookmarks and the rest are not printed).
|
|
778
|
+
|
|
779
|
+
```ts
|
|
780
|
+
// backup-worker/scripts/inspect-backups.ts: keys, database ids and kinds, nothing else
|
|
781
|
+
import { listBackups, METADATA } from "@cardonjs/backups";
|
|
782
|
+
import { getPlatformProxy } from "wrangler";
|
|
783
|
+
|
|
784
|
+
const DAY_MS = 86_400_000;
|
|
785
|
+
|
|
786
|
+
/** One line per object under `prefix`: key, database id, kind (and flags). */
|
|
787
|
+
export async function describeBackups(
|
|
788
|
+
bucket: R2Bucket,
|
|
789
|
+
prefix: string,
|
|
790
|
+
now: Date = new Date(),
|
|
791
|
+
): Promise<string[]> {
|
|
792
|
+
const { backups, orphanDigests, ignored } = await listBackups(bucket, prefix);
|
|
793
|
+
const idOf = (metadata: Readonly<Record<string, string>>) =>
|
|
794
|
+
metadata[METADATA.databaseId] ?? "(no database id)";
|
|
795
|
+
const lines: string[] = [];
|
|
796
|
+
for (const backup of backups) {
|
|
797
|
+
const future = backup.at.getTime() > now.getTime() + DAY_MS ? ", future-dated" : "";
|
|
798
|
+
lines.push(`${backup.key} ${idOf(backup.metadata)} backup${future}`);
|
|
799
|
+
if (backup.digestKey !== null && backup.digestMetadata !== null) {
|
|
800
|
+
lines.push(`${backup.digestKey} ${idOf(backup.digestMetadata)} sidecar`);
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
for (const digest of orphanDigests) {
|
|
804
|
+
lines.push(`${digest.key} ${idOf(digest.metadata)} orphan sidecar`);
|
|
805
|
+
}
|
|
806
|
+
lines.push(`${ignored} other object(s) under the prefix: not this package's, never touched`);
|
|
807
|
+
return lines;
|
|
808
|
+
}
|
|
809
|
+
|
|
810
|
+
// The bucket through a remote binding of a config used only by this script (below).
|
|
811
|
+
const { env, dispose } = await getPlatformProxy<{ BACKUPS: R2Bucket }>({
|
|
812
|
+
configPath: "backup-worker/inspect.jsonc",
|
|
813
|
+
});
|
|
814
|
+
try {
|
|
815
|
+
for (const line of await describeBackups(env.BACKUPS, process.argv[2] ?? "d1/main")) {
|
|
816
|
+
console.log(line);
|
|
817
|
+
}
|
|
818
|
+
} finally {
|
|
819
|
+
await dispose();
|
|
820
|
+
}
|
|
821
|
+
```
|
|
822
|
+
|
|
823
|
+
```jsonc
|
|
824
|
+
// backup-worker/inspect.jsonc: only for the script; the binding reads the real bucket
|
|
825
|
+
{
|
|
826
|
+
"name": "my-app-backups-inspect",
|
|
827
|
+
"compatibility_date": "2026-11-01",
|
|
828
|
+
"r2_buckets": [{ "binding": "BACKUPS", "bucket_name": "my-app-backups", "remote": true }]
|
|
829
|
+
}
|
|
830
|
+
```
|
|
831
|
+
|
|
832
|
+
Run it with `node backup-worker/scripts/inspect-backups.ts d1/main` (Node 22.18 or later runs
|
|
833
|
+
TypeScript directly; on older versions add `--experimental-strip-types`), logged in with
|
|
834
|
+
`pnpm wrangler login`; it needs `wrangler` installed. It only lists. The `describeBackups` logic
|
|
835
|
+
is tested here; the remote binding was not run against a real account. A line looks like
|
|
836
|
+
`d1/main/2026/11/2026-11-20T04-00-03Z.sql 0b6d4b4a-… backup`. Delete or move an object by hand
|
|
837
|
+
with `pnpm wrangler r2 object delete my-app-backups/<key> --remote`, after copying it elsewhere
|
|
838
|
+
if it is a backup worth keeping.
|
|
839
|
+
|
|
840
|
+
One entry per refusal:
|
|
841
|
+
|
|
842
|
+
- **`exists`** (`copyExport`; the Workflow: `backup: copy failed (exists)`). The backup's key
|
|
843
|
+
already holds an object that is not this run's: another database's backup taken in the same
|
|
844
|
+
second, or one written by another run. Nothing was downloaded or written (the Workflow checks
|
|
845
|
+
before starting an export, so none was started either). Run the script and look for that key:
|
|
846
|
+
another database id means two databases share the prefix (see `other_database`). Keys carry
|
|
847
|
+
the second, so the next run does not collide.
|
|
848
|
+
- **`backup: the export stopped before its dump was copied (2 restarts)`** (the Workflow).
|
|
849
|
+
Three exports in a row completed or were cancelled without their dump reaching the bucket.
|
|
850
|
+
The instance's log has a `backup copy failed` line with the reason of each failed copy (a
|
|
851
|
+
download refused, R2 failing, a dump that is not SQL): fix that, then trigger an instance by
|
|
852
|
+
hand (only once no instance is running: see **one instance per day** under
|
|
853
|
+
[Observed on Cloudflare](#observed-on-cloudflare-on-2026-11-20)) or wait for the next day's.
|
|
854
|
+
- **`other_database`** (`pruneBackups` throws a `PruneRefusedError`; the Workflow:
|
|
855
|
+
`backup: prune refused (other_database)`; `runBackup`: `stage: "prune"`). The backup was
|
|
856
|
+
written; nothing was deleted. The script shows backups or sidecars whose database id is not
|
|
857
|
+
this database's, or `(no database id)`. Another database backed up into this prefix: give it a
|
|
858
|
+
prefix of its own (in its Workflow definition file) and move its objects there. An object with
|
|
859
|
+
no database id was not written by this package: move or delete it. Pruning resumes on the next
|
|
860
|
+
run.
|
|
861
|
+
- **`future_backups`** (the Workflow: `backup: prune refused (future_backups)`). Lines marked
|
|
862
|
+
`future-dated`: keys dated more than a day after the clock (a hand-made key, a wrong clock).
|
|
863
|
+
Move or delete them.
|
|
864
|
+
- **`backup: the database id changed since this instance started`** (the Workflow). `DB_ID`
|
|
865
|
+
changed while an instance was running; it stopped before polling, copying or pruning. Start a
|
|
866
|
+
new instance (`pnpm wrangler workflows trigger my-app-database-backup --config backup-worker/wrangler.jsonc`);
|
|
867
|
+
the next day's cron does it anyway.
|
|
868
|
+
- **`backup: this instance was started by an earlier version of @cardonjs/backups; start a new one`**
|
|
869
|
+
(the Workflow). An instance started before an upgrade of this package resumed with step
|
|
870
|
+
results it cannot use (one that had seen its export complete, say); one still waiting for its
|
|
871
|
+
export carries on instead. Nothing was copied by this version. Start a new instance once no
|
|
872
|
+
other is running, or wait for the next day's.
|
|
873
|
+
- **`more than 100000 objects under the prefix`** or **`truncated without a new cursor`**
|
|
874
|
+
(`listBackups`, so `pruneBackups`). The prefix holds too many objects to act on safely: the
|
|
875
|
+
script's last line counts the ones that are not backups. Keep other files out of the prefix.
|
|
876
|
+
|
|
877
|
+
## Restoring
|
|
878
|
+
|
|
879
|
+
Never load a backup over the production database: load it into a **new** database and switch
|
|
880
|
+
the binding, so the current data stays available until the restore is confirmed.
|
|
881
|
+
|
|
882
|
+
### A point in the last 30 days: Time Travel
|
|
883
|
+
|
|
884
|
+
```sh
|
|
885
|
+
# The bookmark of a moment (RFC 3339 or a Unix timestamp)
|
|
886
|
+
pnpm wrangler d1 time-travel info my-app-db --timestamp 2026-11-19T10:00:00Z
|
|
887
|
+
# Restore the database in place to that moment
|
|
888
|
+
pnpm wrangler d1 time-travel restore my-app-db --timestamp 2026-11-19T10:00:00Z
|
|
889
|
+
```
|
|
890
|
+
|
|
891
|
+
`restore` replaces the database's current state. Wrangler prints the bookmark of the state
|
|
892
|
+
before the restore: write it down, `restore --bookmark <it>` undoes the restore. Older than 30
|
|
893
|
+
days (7 on the Free plan): use a backup.
|
|
894
|
+
|
|
895
|
+
### A backup: into a new database
|
|
896
|
+
|
|
897
|
+
The new database becomes production, and the backup Worker exports whatever database its
|
|
898
|
+
configuration names (`DB_ID`), not what the app's binding points at. So the switch changes both,
|
|
899
|
+
in one go; otherwise the daily backup keeps exporting the old database, every run reports
|
|
900
|
+
success, the new production database has no backups, and once the old one is deleted every run
|
|
901
|
+
fails.
|
|
902
|
+
|
|
903
|
+
1. **Download the backup to a folder outside the repository** (it holds every row; it must never
|
|
904
|
+
be committed, and editors and tools index the repository). The key, size and SHA-256 are in
|
|
905
|
+
the Workflow instance's output and its `backup copied` log line:
|
|
906
|
+
|
|
907
|
+
```sh
|
|
908
|
+
mkdir -p ~/restores
|
|
909
|
+
pnpm wrangler r2 object get my-app-backups/d1/main/2026/11/2026-11-20T04-00-03Z.sql --remote --file ~/restores/backup.sql
|
|
910
|
+
```
|
|
911
|
+
|
|
912
|
+
2. Run [the restore check](#the-restore-check) on it, with the size and SHA-256 recorded
|
|
913
|
+
**outside the bucket** (the output or the log line). The `<key>.sha256` sidecar next to the
|
|
914
|
+
dump only shows corruption: whoever could rewrite the dump could rewrite it too.
|
|
915
|
+
3. Create the new database and load the dump into it:
|
|
916
|
+
|
|
917
|
+
```sh
|
|
918
|
+
pnpm wrangler d1 create my-app-db-restored
|
|
919
|
+
pnpm wrangler d1 execute my-app-db-restored --remote --file ~/restores/backup.sql
|
|
920
|
+
```
|
|
921
|
+
|
|
922
|
+
4. Check it (row counts of the tables that matter, the latest rows) with
|
|
923
|
+
`pnpm wrangler d1 execute my-app-db-restored --remote --command "SELECT count(*) FROM <table>"`.
|
|
924
|
+
5. **Check that no backup instance is running** before deploying the switch:
|
|
925
|
+
|
|
926
|
+
```sh
|
|
927
|
+
pnpm wrangler workflows instances list my-app-database-backup --config backup-worker/wrangler.jsonc
|
|
928
|
+
```
|
|
929
|
+
|
|
930
|
+
No instance should be `queued`, `running`, `waiting` or `paused`; wait for it to finish, or
|
|
931
|
+
end it with `pnpm wrangler workflows instances terminate my-app-database-backup <id> --config backup-worker/wrangler.jsonc`.
|
|
932
|
+
An instance that resumes after the deploy would build the exporter for the new database with
|
|
933
|
+
the old database's stored bookmark; the Workflow refuses that (it stores the database id in its
|
|
934
|
+
first step and fails with `backup: the database id changed since this instance started`), but
|
|
935
|
+
that instance's backup is then lost.
|
|
936
|
+
6. **Switch, in the same deploy:**
|
|
937
|
+
- the app: in its `wrangler.jsonc`, point the `DB` binding's `database_name` and
|
|
938
|
+
`database_id` at the new database. The dump includes the `d1_migrations` table, so
|
|
939
|
+
migrations already applied stay applied;
|
|
940
|
+
- the backups: in `backup-worker/wrangler.jsonc`, set `DB_ID` to the new database's id; in
|
|
941
|
+
`backup-worker/src/database-backup.workflow.ts`, give the Workflow **a new `prefix`**
|
|
942
|
+
(`d1/main-2026-11`, say): one prefix per database, and the old prefix holds the old
|
|
943
|
+
database's backups, which `pruneBackups` would refuse to mix;
|
|
944
|
+
- deploy both Workers.
|
|
945
|
+
7. **Run one backup now** and check it is of the new database: start an instance of the backup
|
|
946
|
+
Workflow by hand (`pnpm wrangler workflows trigger my-app-database-backup --config backup-worker/wrangler.jsonc`),
|
|
947
|
+
wait for it to complete, and check that its output's `databaseId` (the backup's
|
|
948
|
+
`database-id` metadata) is the new database's id and its `key` is under the new prefix.
|
|
949
|
+
8. **Time Travel starts again.** The new database's Time Travel history starts when it was
|
|
950
|
+
created; the old history stays with the old database, and ends when that database is
|
|
951
|
+
deleted. Keep the old database until you are sure (its history is the only way back to a
|
|
952
|
+
minute before the restore), then delete it.
|
|
953
|
+
9. The old prefix's backups are no longer pruned by anyone: keep them as the pre-restore
|
|
954
|
+
history, or delete them by hand when they are no longer needed.
|
|
955
|
+
10. Delete `~/restores/backup.sql` when done.
|
|
956
|
+
|
|
957
|
+
### An encrypted backup
|
|
958
|
+
|
|
959
|
+
The same steps, with the dump decrypted on your machine between the download and the load. The
|
|
960
|
+
instance's output (`encryption.keyId`) says which key you need; the file's header says it too,
|
|
961
|
+
and decryption refuses another (`unknown_key`).
|
|
962
|
+
|
|
963
|
+
1. Download it as above, to `~/restores/backup.sql.enc`. Note its R2 key and the database id
|
|
964
|
+
(the instance's output `key` and `databaseId`): the file must prove it is that backup.
|
|
965
|
+
2. Run [the restore check](#the-restore-check) on that file with the key (`encryption`), the R2
|
|
966
|
+
`key` and the `databaseId`: it decrypts while it reads, refuses another backup
|
|
967
|
+
(`wrong_backup`), and `bytes` and `sha256` are those of the output (the encrypted object's).
|
|
968
|
+
3. Decrypt it to a file with this script, then load that file (step 3 above, with
|
|
969
|
+
`--file ~/restores/backup.sql`):
|
|
970
|
+
|
|
971
|
+
```js
|
|
972
|
+
// backup-worker/scripts/decrypt-backup.mjs
|
|
973
|
+
// BACKUP_KEY=… node decrypt-backup.mjs <key id> <database id> <R2 key> <encrypted file> <output file>
|
|
974
|
+
import { createReadStream, createWriteStream, existsSync } from "node:fs";
|
|
975
|
+
import { rename, rm } from "node:fs/promises";
|
|
976
|
+
import { Readable, Writable } from "node:stream";
|
|
977
|
+
import { decryptBackup } from "@cardonjs/backups";
|
|
978
|
+
|
|
979
|
+
const [keyId, databaseId, objectKey, input, output] = process.argv.slice(2);
|
|
980
|
+
// From the environment, never an argument: arguments end up in the shell's history.
|
|
981
|
+
const key = process.env.BACKUP_KEY;
|
|
982
|
+
if (!keyId || !databaseId || !objectKey || !input || !output || !key) {
|
|
983
|
+
console.error(
|
|
984
|
+
"usage: BACKUP_KEY=… node decrypt-backup.mjs <key id> <database id> <R2 key> <encrypted file> <output file>",
|
|
985
|
+
);
|
|
986
|
+
process.exit(2);
|
|
987
|
+
}
|
|
988
|
+
if (existsSync(output)) {
|
|
989
|
+
console.error(`${output} already exists: delete it or choose another name`);
|
|
990
|
+
process.exit(1);
|
|
991
|
+
}
|
|
992
|
+
// Written under another name until the whole file decrypted and authenticated; created anew
|
|
993
|
+
// only ("wx"), readable by you only (the mode is ignored on Windows).
|
|
994
|
+
const partial = `${output}.partial`;
|
|
995
|
+
const file = createWriteStream(partial, { flags: "wx", mode: 0o600 });
|
|
996
|
+
try {
|
|
997
|
+
await new Promise((resolve, reject) => {
|
|
998
|
+
file.once("open", resolve);
|
|
999
|
+
file.once("error", reject);
|
|
1000
|
+
});
|
|
1001
|
+
} catch (error) {
|
|
1002
|
+
console.error(`cannot create ${partial} (${error.code}): delete a leftover one first`);
|
|
1003
|
+
process.exit(1);
|
|
1004
|
+
}
|
|
1005
|
+
try {
|
|
1006
|
+
await Readable.toWeb(createReadStream(input))
|
|
1007
|
+
.pipeThrough(
|
|
1008
|
+
decryptBackup({ keys: { [keyId]: key } }, { expected: { databaseId, key: objectKey } }),
|
|
1009
|
+
)
|
|
1010
|
+
.pipeTo(Writable.toWeb(file));
|
|
1011
|
+
await rename(partial, output);
|
|
1012
|
+
console.log(`decrypted into ${output}`);
|
|
1013
|
+
} catch (error) {
|
|
1014
|
+
// Chunks before a failure were written: the partial file is not the backup.
|
|
1015
|
+
try {
|
|
1016
|
+
await rm(partial, { force: true });
|
|
1017
|
+
} catch {
|
|
1018
|
+
console.error(`could not delete ${partial}: delete it by hand`);
|
|
1019
|
+
}
|
|
1020
|
+
console.error(`not decrypted (${error?.reason ?? "the file could not be read or written"})`);
|
|
1021
|
+
process.exitCode = 1;
|
|
1022
|
+
}
|
|
1023
|
+
```
|
|
1024
|
+
|
|
1025
|
+
Run it from the backup Worker's folder (where `@cardonjs/backups` is installed), with the key
|
|
1026
|
+
read without echo or history: `read -rs BACKUP_KEY && export BACKUP_KEY`, then
|
|
1027
|
+
`node scripts/decrypt-backup.mjs k2026-11 <database id> d1/main/2026/11/2026-11-20T04-00-03Z.sql ~/restores/backup.sql.enc ~/restores/backup.sql`,
|
|
1028
|
+
then `unset BACKUP_KEY`. It writes to `<output>.partial` and gives the file its final name
|
|
1029
|
+
only once every chunk authenticated and the header named that database and that R2 key; on
|
|
1030
|
+
any failure (a wrong key, a modified or cut file, another backup: a `BackupDecryptError` with
|
|
1031
|
+
its `reason`) it deletes the partial file and exits with 1, so the output name never holds an
|
|
1032
|
+
incomplete dump, even if the script is interrupted. It refuses an existing output and a
|
|
1033
|
+
leftover `.partial` (delete it: it is never a complete backup). It never prints the key or
|
|
1034
|
+
any of the dump.
|
|
1035
|
+
4. Delete both files when done.
|
|
1036
|
+
|
|
1037
|
+
### The restore check
|
|
1038
|
+
|
|
1039
|
+
Do this once after setting backups up and then regularly (once a month): a backup that was
|
|
1040
|
+
never restored is a hope. It loads a backup into a **local**, empty D1 (Miniflare), compares the
|
|
1041
|
+
rows of every table with the dump's `INSERT`s, and compares the size and SHA-256 with the ones
|
|
1042
|
+
recorded when it was copied:
|
|
1043
|
+
|
|
1044
|
+
```ts
|
|
1045
|
+
// scripts/restore-check.test.ts (run with vitest, never in CI with real data)
|
|
1046
|
+
import { readFile } from "node:fs/promises";
|
|
1047
|
+
import { homedir } from "node:os";
|
|
1048
|
+
import { join } from "node:path";
|
|
1049
|
+
import { checkRestore } from "@cardonjs/backups/restore";
|
|
1050
|
+
import { startBindings } from "@cardonjs/testing/miniflare";
|
|
1051
|
+
import { expect, it } from "vitest";
|
|
1052
|
+
|
|
1053
|
+
// From the instance's output or its `backup copied` log line, never from the bucket.
|
|
1054
|
+
const recorded = {
|
|
1055
|
+
bytes: 48_213,
|
|
1056
|
+
sha256: "9f86d081884c7d659a2feaa0c55ad015a3bf4f1b2b0b822cd15d6c15b0f00a08",
|
|
1057
|
+
};
|
|
1058
|
+
|
|
1059
|
+
it("the latest backup loads", async () => {
|
|
1060
|
+
const bindings = await startBindings({ d1: 1 });
|
|
1061
|
+
try {
|
|
1062
|
+
// The file's bytes, not its text: the size and digest are checked on what was stored.
|
|
1063
|
+
const dump = await readFile(join(homedir(), "restores", "backup.sql"));
|
|
1064
|
+
const report = await checkRestore(await bindings.d1(), dump, recorded);
|
|
1065
|
+
expect(report.problems).toEqual([]);
|
|
1066
|
+
} finally {
|
|
1067
|
+
await bindings.dispose();
|
|
1068
|
+
}
|
|
1069
|
+
});
|
|
1070
|
+
```
|
|
1071
|
+
|
|
1072
|
+
For an encrypted backup, pass the downloaded (encrypted) file's bytes, the key, and what the
|
|
1073
|
+
backup must be (the R2 key you downloaded and the database id, from the instance's output):
|
|
1074
|
+
|
|
1075
|
+
```ts
|
|
1076
|
+
const report = await checkRestore(await bindings.d1(), dump, {
|
|
1077
|
+
...recorded, // the encrypted object's size and digest, as the output recorded them
|
|
1078
|
+
encryption: { keys: { "k2026-11": process.env.BACKUP_KEY ?? "" } },
|
|
1079
|
+
key: "d1/main/2026/11/2026-11-20T04-00-03Z.sql",
|
|
1080
|
+
databaseId: "0b6d4b4a-4e43-4a7c-9a4e-3b1f2a6c9d01",
|
|
1081
|
+
});
|
|
1082
|
+
```
|
|
1083
|
+
|
|
1084
|
+
It decrypts before touching the database and fails closed with a `BackupDecryptError` and a
|
|
1085
|
+
fixed `reason`: `authentication_failed` (a wrong key, a modified file), `unknown_key`,
|
|
1086
|
+
`truncated`, `not_encrypted` (a plain dump where an encrypted one was expected),
|
|
1087
|
+
`wrong_backup` (an authentic backup of another key or database), and, without `encryption`,
|
|
1088
|
+
`encrypted` (the reverse). `report.encryption` gives the scheme and key id;
|
|
1089
|
+
`report.identity` the database id and R2 key the header names, and which of the two were
|
|
1090
|
+
checked (`checked: { databaseId, key }`): leave neither out.
|
|
1091
|
+
|
|
1092
|
+
1. Download the latest backup as in step 1 above; `bytes` and `sha256` are the `size` and
|
|
1093
|
+
`sha256` of the Workflow instance's output (or of its `backup copied` log line).
|
|
1094
|
+
2. Run the check. `report.tables` lists each table with `expectedRows` and `loadedRows`;
|
|
1095
|
+
`report.problems` names what differs (table names and numbers, never row data).
|
|
1096
|
+
3. Delete the downloaded file.
|
|
1097
|
+
|
|
1098
|
+
**What it proves**: the dump loads into D1; every table it creates has the rows it inserts;
|
|
1099
|
+
and, with `bytes` and `sha256` kept outside the bucket, the file is byte for byte the one the copy
|
|
1100
|
+
stored. With the sidecar's content instead, it proves only that the file was not corrupted: the
|
|
1101
|
+
sidecar sits next to the dump and can be rewritten with it. Pass the file's bytes: a dump read as
|
|
1102
|
+
text is encoded again as UTF-8, and a TEXT value holding bytes that are not valid UTF-8 (SQLite
|
|
1103
|
+
allows it) comes out different, so the digest would not match. **What it does not prove**: that
|
|
1104
|
+
Cloudflare's dump was complete. A dump cut at a statement boundary loads cleanly and agrees with
|
|
1105
|
+
itself (its tables have exactly the rows it inserts); only the size and digest recorded at copy
|
|
1106
|
+
time show a change since, and nothing here can show that the export itself was short. Compare the
|
|
1107
|
+
row counts of the tables that matter with production, too.
|
|
1108
|
+
|
|
1109
|
+
`checkRestore` is for a **local** database. It refuses a database that already has tables, but
|
|
1110
|
+
that guard does not stop an empty production database: never give it a remote binding. When a
|
|
1111
|
+
dump does not load it throws an error that names the statements and SQLite's result code (e.g.
|
|
1112
|
+
`SQLITE_CONSTRAINT_UNIQUE`) and has no `cause`: the database's own error may quote the failing
|
|
1113
|
+
SQL statement (row data), and core's logger writes a logged error's cause chain. To see the
|
|
1114
|
+
whole message, load the statements yourself on a local database. `restoreStatements(sql)` gives the
|
|
1115
|
+
dump's statements (split like Wrangler's SQL files, without `BEGIN TRANSACTION`/`COMMIT`) for
|
|
1116
|
+
loading it some other way; it refuses a `format: "sqlite3"` dump, which D1 cannot load. Row
|
|
1117
|
+
counts assume one row per `INSERT`, which is how D1 writes dumps.
|
|
1118
|
+
|
|
1119
|
+
## Costs
|
|
1120
|
+
|
|
1121
|
+
In general terms (see Cloudflare's pricing pages for numbers): R2 storage for the copies kept;
|
|
1122
|
+
R2 write operations per backup (one for the dump and one for its sidecar, or one per part plus
|
|
1123
|
+
two for a multipart upload); a head (and, on Workers, a get of the sidecar) per copy and per
|
|
1124
|
+
Workflow start or restart, plus, when a finished backup is reused, a read of the whole dump to
|
|
1125
|
+
check its digest; list and
|
|
1126
|
+
delete operations when pruning; a few REST API calls and Workflow steps per run; no egress fee for
|
|
1127
|
+
reading from R2. The export itself blocks the database for its duration, which is the cost that
|
|
1128
|
+
matters most for a busy database.
|
|
1129
|
+
|
|
1130
|
+
## What was observed on Cloudflare, and what is not verified
|
|
1131
|
+
|
|
1132
|
+
The tests run against a fake of the REST API that answers like the real one did (below), and
|
|
1133
|
+
against R2 and D1 in Miniflare (workerd).
|
|
1134
|
+
|
|
1135
|
+
### Observed on Cloudflare on 2026-11-20
|
|
1136
|
+
|
|
1137
|
+
The package ran on a real account, through a wrapper around `fetch` that logged shapes only
|
|
1138
|
+
(never the token, the signed URL or the dump), twice, with identical results:
|
|
1139
|
+
|
|
1140
|
+
- **The requests.** The start sends `{ "output_format": "polling" }`; each poll sends
|
|
1141
|
+
`{ "output_format": "polling", "current_bookmark": … }`. Both answer HTTP 200.
|
|
1142
|
+
- **The start's answer.** The envelope has `errors` (empty), `messages`, `result` and
|
|
1143
|
+
`success: true`; `result` has `at_bookmark`, `messages` (like
|
|
1144
|
+
`["Generating <database-id>-<bookmark>.sql", "Uploaded part 2", "Uploaded part 1"]`),
|
|
1145
|
+
`status: "active"`, `success` and `type: "export"`.
|
|
1146
|
+
- **The poll that reports completion** (10 seconds after the start): `result` has
|
|
1147
|
+
`at_bookmark`, `messages` (like `["Finished uploading <file>.sql in 2 parts."]`), `result`,
|
|
1148
|
+
`status: "complete"`, `success` and `type`; the signed URL is **nested**, in
|
|
1149
|
+
`result.result.signed_url`, next to `result.result.filename` (there is no `result.signed_url`).
|
|
1150
|
+
- **The same bookmark across polls**: the completed export's `at_bookmark` is the start's.
|
|
1151
|
+
- **The completion is delivered once.** A second poll with the same bookmark answers HTTP 200,
|
|
1152
|
+
`success: true`, `errors: []`, with `result` `{ "error": "Not currently exporting anything.",
|
|
1153
|
+
"success": false }` (no `status`, no `at_bookmark`). The first version of this package polled
|
|
1154
|
+
again for a fresh URL in a separate copy step, got this answer, and failed every backup; the
|
|
1155
|
+
step that sees `complete` now copies, and this answer (`not_exporting`) restarts the export.
|
|
1156
|
+
- **Export time**: a 15 MB database was exported in under 10 seconds.
|
|
1157
|
+
|
|
1158
|
+
After the fix, on the same day, whole backups ran on the same account (a 15 MB database, three
|
|
1159
|
+
tables, 15 006 rows):
|
|
1160
|
+
|
|
1161
|
+
- **The signed URL's host** was `<account id>.r2.cloudflarestorage.com` (the account's R2 S3
|
|
1162
|
+
endpoint): an allowlist for it would be `signedUrlHosts: ["*.r2.cloudflarestorage.com"]`
|
|
1163
|
+
(the option itself was not exercised on that run). The download
|
|
1164
|
+
answered 200 **with a `Content-Length`**, no `Content-Type` and no `Content-Encoding`: the
|
|
1165
|
+
copy took the known-length path (one `put`).
|
|
1166
|
+
- **A whole instance took 15 seconds**: start (2 s), one 10 s sleep, the poll that copied
|
|
1167
|
+
15.8 MB into R2 (2 s), prune.
|
|
1168
|
+
- **`crypto.DigestStream` works in production Workers**: the sidecar's digest equalled the
|
|
1169
|
+
SHA-256 of the object downloaded with Wrangler.
|
|
1170
|
+
- **A real dump** starts with `PRAGMA defer_foreign_keys=TRUE;`, then each table's
|
|
1171
|
+
`CREATE TABLE` followed by one `INSERT INTO "table" (columns) VALUES(...)` per row, then the
|
|
1172
|
+
indexes; a line break inside a text value is written as `replace('…
|
|
1173
|
+
…','
|
|
1174
|
+
',char(10))`, so
|
|
1175
|
+
no statement spans lines. `checkRestore` loaded it into a local D1 (15 011 statements, every
|
|
1176
|
+
table's rows equal to the dump's, about a second) and reported a wrong digest when given one.
|
|
1177
|
+
- **The restore runbook**: the dump loaded into a new database with
|
|
1178
|
+
`wrangler d1 execute <new> --remote --file` (15 011 queries) and matched the original: row
|
|
1179
|
+
counts, the index, a multi-line value and non-ASCII text.
|
|
1180
|
+
- **Retention**: a second backup the same day kept the newest and deleted the first with its
|
|
1181
|
+
digest sidecar.
|
|
1182
|
+
- **One instance per day**: with a Cron Trigger firing every minute, every start for the day's
|
|
1183
|
+
id answered `created: false` and no second instance appeared. That day's instance had failed
|
|
1184
|
+
earlier (the bug above), which showed the other side of the rule: **a failed instance is not
|
|
1185
|
+
retried by the cron that day**. After fixing the cause, start one by hand with another id
|
|
1186
|
+
(`wrangler workflows trigger <workflow name> '{}' --id backup-<date>-retry`) or wait for the
|
|
1187
|
+
next day. **Only once the day's instance is `errored` or `complete`** (check with
|
|
1188
|
+
`wrangler workflows instances describe <workflow name> backup-<date>`): two instances at once
|
|
1189
|
+
mean two exports of one database (behaviour not verified, see above), and one instance's prune
|
|
1190
|
+
can delete the other's backup of the same day (retention keeps one per day).
|
|
1191
|
+
|
|
1192
|
+
### Not verified
|
|
1193
|
+
|
|
1194
|
+
- **The signed URL's lifetime** ("valid for one hour", per Wrangler), and whether its host or
|
|
1195
|
+
the presence of `Content-Length` can differ on other accounts, regions or dump sizes (hence
|
|
1196
|
+
`signedUrlHosts` stays opt-in, and without a length the copy takes the multipart path, which
|
|
1197
|
+
was only exercised in Miniflare).
|
|
1198
|
+
- **What a second `start` does while an export runs** (whether Cloudflare tracks one export per
|
|
1199
|
+
database, so that a poll could be answered about another export: such an answer is refused as
|
|
1200
|
+
`export_lost`), how long an export survives without being
|
|
1201
|
+
polled, and that a cancelled export answers like a consumed one ("Not currently exporting
|
|
1202
|
+
anything."; any other error without a status is treated the same way). Answers of other shapes
|
|
1203
|
+
fail as `malformed`, never as a false success; all of it is in one file, `src/export.ts`.
|
|
1204
|
+
- **The token.** That the export needs D1 Write and that a D1 Read token gets error 10000 is
|
|
1205
|
+
Cloudflare's documentation; whether a token can be limited to one database, and the exact
|
|
1206
|
+
status code of the refusal, were not observed.
|
|
1207
|
+
- **R2 in production**: only the known-length `put` of a 15.8 MB dump was observed. Multipart
|
|
1208
|
+
minimums (5 MiB, equal parts) and aborts behave in Miniflare as documented for R2; the
|
|
1209
|
+
single-upload limit (about 5 GiB per R2's documentation) and bucket locks were not checked
|
|
1210
|
+
against R2 itself.
|
|
1211
|
+
- **Workflow instance history**: how long Cloudflare keeps an instance's output (where the
|
|
1212
|
+
digest kept outside the bucket lives, with the log line).
|
|
1213
|
+
- **Remote bindings** (`"remote": true` with `getPlatformProxy`), used by the inspection script.
|
|
1214
|
+
- **Step limits**: the Workflow uses at most 2 × 400 + 5 steps and a 30-minute timeout for the
|
|
1215
|
+
steps that may copy; Cloudflare's limits on steps per instance, step duration and CPU depend on
|
|
1216
|
+
the plan.
|
|
1217
|
+
- **Dumps of other shapes**: only a small schema was restored (plain tables, a foreign key, a
|
|
1218
|
+
`CHECK`, an index); views, triggers, `WITHOUT ROWID` tables, BLOB columns and large databases
|
|
1219
|
+
were not.
|
|
1220
|
+
- **Availability during an export**: the export finished in seconds here, so how long a large
|
|
1221
|
+
database stays unavailable was not measured.
|
|
1222
|
+
- **Encryption on Cloudflare**: encrypted copies were tested in workerd through Miniflare (both
|
|
1223
|
+
paths, up to 12 MiB, about a second each on a development machine) and decrypted there and in
|
|
1224
|
+
Node; not yet on a deployed Worker. The CPU time AES-GCM adds to a large dump under a Worker's
|
|
1225
|
+
CPU limit, and an encrypted multipart upload on R2 itself, were not measured.
|
|
1226
|
+
|
|
1227
|
+
Run one backup and one restore check on a staging database before relying on it.
|
|
1228
|
+
|
|
1229
|
+
## Testing your project
|
|
1230
|
+
|
|
1231
|
+
- The Workflow runs in process with `memoryWorkflows` from `@cardonjs/workflows-cf/testing`;
|
|
1232
|
+
pass a fake `fetch` in the `database` options (`d1Export`'s `fetch` option) so no test reaches
|
|
1233
|
+
the network, and a Miniflare bucket (`startBindings({ r2: 1 })`).
|
|
1234
|
+
- From Node, Miniflare's R2 binding cannot take a stream (it has no length), so `copyExport`
|
|
1235
|
+
takes the path in parts there, and computes no digest; in workerd it streams and writes the
|
|
1236
|
+
sidecar. Both are tested in this package.
|
|
1237
|
+
- With encryption, generate a test key in the test (`randomBytes(32).toString("base64url")`),
|
|
1238
|
+
never commit a real one, and read objects back through `decryptBackup`.
|