@cardonjs/backups 0.0.0-stage → 0.3.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/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/llms.txt
ADDED
|
@@ -0,0 +1,249 @@
|
|
|
1
|
+
# @cardonjs/backups
|
|
2
|
+
|
|
3
|
+
Backups of a Cloudflare D1 database into a private R2 bucket: Cloudflare's own D1 export (REST
|
|
4
|
+
API, needs an API token with D1 Write), streamed into R2 on a schedule (optionally encrypted
|
|
5
|
+
client-side), pruned by day / ISO week / month (UTC), plus a restore check. Time Travel already covers the last 30 days (7 on Free); this
|
|
6
|
+
adds older copies, outside the database, as SQL dumps. Workers only, except `./restore` (Node).
|
|
7
|
+
|
|
8
|
+
Full documentation: README.md in this package.
|
|
9
|
+
|
|
10
|
+
## Install
|
|
11
|
+
|
|
12
|
+
```sh
|
|
13
|
+
pnpm add @cardonjs/backups
|
|
14
|
+
pnpm add @cardonjs/workflows-cf @cardonjs/core zod # for ./workflow
|
|
15
|
+
pnpm add -D @cardonjs/testing miniflare # for ./restore
|
|
16
|
+
```
|
|
17
|
+
|
|
18
|
+
## Exports
|
|
19
|
+
|
|
20
|
+
### `@cardonjs/backups` (no peers)
|
|
21
|
+
- `d1Export({ accountId, databaseId, apiToken, format?, signedUrlHosts?, timeoutMs?, fetch? })`
|
|
22
|
+
→ `{ start(), poll(bookmark), databaseId, accountId, format }`. Results:
|
|
23
|
+
`{ status: "pending", bookmark }`, `{ status: "ready", bookmark, download({ signal? }) }`,
|
|
24
|
+
`{ status: "failed", reason, retryable, httpStatus? }`. CLOUDFLARE HANDS OUT A COMPLETED
|
|
25
|
+
EXPORT'S SIGNED URL ONCE (observed 2026-11-20): only the poll that first reports `complete`
|
|
26
|
+
carries it (nested, `result.result.signed_url`; `result.signed_url` also accepted); polling the
|
|
27
|
+
same bookmark again answers "Not currently exporting anything." → reason `not_exporting`
|
|
28
|
+
(exact text; any other `error` without `status` → `export_lost`; both `retryable: false`,
|
|
29
|
+
never ready): start a NEW export. A poll answer whose `at_bookmark` differs from the polled
|
|
30
|
+
bookmark (about ANOTHER export of the database) → `export_lost`, never pending/ready, nothing
|
|
31
|
+
downloaded. Any `error` key, even `null`, counts as an error (fails closed). Ids must be 32 hex / a UUID (TypeError otherwise). Token only to `https://api.cloudflare.com` in `Authorization`. 401/403 or
|
|
32
|
+
Cloudflare error code 10000 → `unauthorized` (a D1 Read token is not enough). The signed URL
|
|
33
|
+
is never exposed: `download()` fetches it (GET, no credentials, `redirect: "manual"`, https,
|
|
34
|
+
DNS host). `format: "sqlite3"` (FTS5 databases) → dump loads only into the sqlite3 CLI. An
|
|
35
|
+
injected `fetch` receives the token and the signed URL: never log inside it.
|
|
36
|
+
- `copyExport({ exporter, ready, bucket, key, run, partSize?, timeoutMs?, singlePutLimit?,
|
|
37
|
+
encryption? })`
|
|
38
|
+
→ `{ ok: true, key, size, bookmark, databaseId, createdAt, sha256, reused, encryption? }` |
|
|
39
|
+
`{ ok: false, reason, retryable }`. `ready` = the `start`/`poll` answer that reported complete
|
|
40
|
+
(TypeError for anything else); it NEVER polls. `run` = this backup's identity
|
|
41
|
+
(`crypto.randomUUID()`), fixed before the first export and passed unchanged to every retry; a
|
|
42
|
+
retry after a failed copy needs a NEW export, the same `key` and the same `run`. Downloads and
|
|
43
|
+
streams into R2; atomic (known length
|
|
44
|
+
≤ 4 GiB → one `put` through `FixedLengthStream`; else parts of 5-32 MiB: one `put` if it fits,
|
|
45
|
+
multipart otherwise, aborted on failure); checks size and an SQL start. `timeoutMs` (default
|
|
46
|
+
25 min) bounds the WHOLE copy (head/get, download, every R2 write, the sidecar) →
|
|
47
|
+
`timeout`; an open multipart upload gets 5 s to abort; no delete after the deadline; a write
|
|
48
|
+
already in flight may still land (whole checked dump, no sidecar: a retry rewrites it). On
|
|
49
|
+
Workers the SHA-256 is computed while streaming (`crypto.DigestStream`) and stored in a
|
|
50
|
+
sidecar `<key>.sha256` after the dump (Node: no sidecar, `sha256: null`). The sidecar detects
|
|
51
|
+
CORRUPTION, NOT TAMPERING (same bucket): keep `sha256`/`size`/`key` outside the bucket (the
|
|
52
|
+
Workflow output and its `backup copied` log line; log them yourself with runBackup). Reuses
|
|
53
|
+
an object at the key (nothing downloaded) only if it has the same database id, a `run` equal
|
|
54
|
+
to THIS CALL's run (never matched on a bookmark: a restarted export has another one), the
|
|
55
|
+
recorded size, and (Workers) its sidecar (same run and export bookmark as the dump;
|
|
56
|
+
`dump-object` = the R2 `version` (else `etag`) of THE OBJECT NOW AT THE KEY, as returned by the
|
|
57
|
+
dump's `put`/`complete`, so a late write of the key is never accepted; metadata and size ≤ 66
|
|
58
|
+
bytes checked before reading it) AND the stored dump read back and hashed equals the sidecar
|
|
59
|
+
(a reused result's `sha256` is the stored bytes' digest; Node: size and metadata only); an
|
|
60
|
+
unfinished object of the same run is rewritten; another run's object (even same bookmark) → `exists`. Never looks at other keys: a
|
|
61
|
+
shared or dirty prefix never stops a backup (pruning refuses instead). Metadata:
|
|
62
|
+
`cardon-backup: "1"`, `bookmark` (the export's), `run`, `database-id`, `created-at`, `format`,
|
|
63
|
+
`bytes` (when known before the upload); the sidecar adds `dump-object`.
|
|
64
|
+
- ENCRYPTION (opt-in; `copyExport`/`runBackup` option `encryption`, the Workflow's
|
|
65
|
+
`encryption: (c) => …`): `backupEncryption({ keys: { [id]: base64url32 }, current: id })` →
|
|
66
|
+
validated settings (TypeError naming no key or id: each key 32 random bytes as base64url, 43
|
|
67
|
+
chars; ids `^[a-z0-9][a-z0-9_-]{0,31}$`, not secret; `current` listed; no key under two ids).
|
|
68
|
+
NEVER FAILS OPEN: only an ABSENT `encryption` property means plain; present but
|
|
69
|
+
null/undefined → TypeError (copyExport, runBackup, findCopy, checkRestore); in
|
|
70
|
+
defineBackupWorkflow a present `encryption` that is not a function (`secret ? fn : undefined`)
|
|
71
|
+
→ TypeError when defined, and a function returning null/undefined → `backup: invalid
|
|
72
|
+
encryption options` before any step. With encryption, a hand-built exporter's databaseId must
|
|
73
|
+
fit the header's pattern (TypeError before any download). Keys hidden from JSON/inspect; each imported once as a non-extractable CryptoKey,
|
|
74
|
+
its decoded bytes zeroed after that first import (unused keys and the env's base64 strings are
|
|
75
|
+
not). LOSING THE KEY LOSES THE BACKUPS: keep every key outside Cloudflare (Worker secrets
|
|
76
|
+
cannot be read back). One key per environment.
|
|
77
|
+
Format `aes-256-gcm-stream-v1` (FORMAT.md in the package, with two full vectors): header
|
|
78
|
+
`CARDONBK`, version 1, chunk size 65536, key id, 32-byte random salt, then the CONTEXT:
|
|
79
|
+
database id (1-byte length) and the full R2 object key (2-byte length); data key =
|
|
80
|
+
HKDF-SHA-256(key, salt, "cardon-backups/aes-256-gcm-stream/v1"); AES-256-GCM per 64 KiB chunk,
|
|
81
|
+
nonce = 7 zero bytes || uint32 counter || last flag, the whole header as AAD; last chunk always
|
|
82
|
+
< 64 KiB (possibly empty). Size = 49 + idLen + dbIdLen + keyLen + P + 16·(⌊P/65536⌋+1); max
|
|
83
|
+
plaintext 2^48−1. With it: object/sidecar metadata `encryption`, `key-id`; `size`, `bytes`,
|
|
84
|
+
`sha256` and the sidecar are of the ENCRYPTED bytes; results/output/step results add
|
|
85
|
+
`encryption: { scheme, keyId }` (never a key); retention needs no key; a same-run copy in
|
|
86
|
+
plain or with another key id is REWRITTEN, not reused, and reuse decrypts the stored object
|
|
87
|
+
whole with the current key (header must name this database and key) before accepting it. Old
|
|
88
|
+
plain backups stay plain. Rotation: the Worker never decrypts, so it holds ONLY the current
|
|
89
|
+
key; old keys stay offline; destroy one only when no listed backup (`keyIds` of
|
|
90
|
+
`listBackups`/`pruneBackups`, the `backups pruned` log line) and no downloaded copy names it.
|
|
91
|
+
`keyIds` is a HINT: it comes from attacker-writable custom metadata of marker-carrying objects
|
|
92
|
+
under one prefix (stripped/forged metadata, objects re-uploaded by another tool, the same key
|
|
93
|
+
under another prefix or database are not counted). Before destroying a key, confirm from the
|
|
94
|
+
objects: `claimedKeyId(firstBytes)` reads the key id a header CLAIMS from the first
|
|
95
|
+
`KEY_ID_PROBE_BYTES` (46) bytes (a range GET), with no key and NO authentication; null for
|
|
96
|
+
plain/other files (README script `claimedKeyIds`).
|
|
97
|
+
- `decryptBackup(keys: { keys } | BackupEncryption, { expected?: { databaseId?, key?, keyId? } })`
|
|
98
|
+
→ `DecryptBackupStream` (a `TransformStream<Uint8Array, Uint8Array>` with `authenticated:
|
|
99
|
+
Promise<{ keyId, databaseId, key }>`; Workers and Node). Releases each chunk's plaintext only
|
|
100
|
+
after its tag verified; the header's context is compared with `expected` only after the FIRST
|
|
101
|
+
chunk authenticated and before any plaintext; `authenticated` resolves then, and rejects on
|
|
102
|
+
any failure first (decryption error, end of input, source failure or cancel in Node 22 and
|
|
103
|
+
workerd; elsewhere await it after the pipe settled, or race it with the pipe). PASS `expected`:
|
|
104
|
+
otherwise an authentic backup of another database/date/environment under the same key
|
|
105
|
+
decrypts fine. Errors with `BackupDecryptError` (fixed message, `reason`: `not_encrypted`,
|
|
106
|
+
`unsupported_format`, `invalid_header`, `unknown_key`, `authentication_failed` (wrong key,
|
|
107
|
+
tampering, reordering, trailing bytes, a cut leaving ≥16 bytes of a chunk), `truncated` (cut
|
|
108
|
+
in the header, at a chunk boundary, or leaving 1-15 bytes of the last chunk), `too_large`,
|
|
109
|
+
`wrong_backup`). On error discard everything already written. `encryptedSize(plainSize,
|
|
110
|
+
keyId, { databaseId, key })` (exact; null for invalid input), `ENCRYPTION_SCHEME`,
|
|
111
|
+
`MAX_PLAINTEXT_SIZE`.
|
|
112
|
+
- `runBackup({ exporter, bucket, prefix, keep?, pollIntervalMs?, timeoutMs?, copyTimeoutMs?,
|
|
113
|
+
partSize?, now?, sleep?, encryption? })`: start, poll, copy (from the complete answer), prune in one call
|
|
114
|
+
(small databases). No retries, except `not_exporting`/`export_lost` → a new export, at most 2
|
|
115
|
+
restarts within `timeoutMs`. Defaults fit a 15-minute Cron Trigger: 4 min start+polling (+30 s last request) +
|
|
116
|
+
8 min copy (+5 s abort) ≈ 12.6 min, >2 min left for pruning. A refused prune → `{ ok: false, stage: "prune", reason, key }` (the copy was written).
|
|
117
|
+
- `pruneBackups(bucket, { prefix, databaseId, keep: { daily?, weekly?, monthly? }, dryRun?, now? })`
|
|
118
|
+
→ `{ dryRun, kept, deleted, deletedDigests, ignored, keyIds }` (`keyIds`: key ids the kept
|
|
119
|
+
backups name). Newest always kept; empty policy
|
|
120
|
+
refused; only keys that match the pattern exactly AND carry the marker; sidecars deleted with
|
|
121
|
+
their dumps, never counted as backups; all pages listed first; deletes in 1000s. Throws
|
|
122
|
+
`PruneRefusedError` (nothing deleted) with `reason: "other_database"` when the prefix holds
|
|
123
|
+
any backup or sidecar of another database or without a database id (ONE PREFIX PER DATABASE) or
|
|
124
|
+
`"future_backups"` when a backup is dated more than a day after `now()`. Orphan sidecars are
|
|
125
|
+
deleted only once dated more than a day before `now()`. To find what caused a refusal: the
|
|
126
|
+
README's `describeBackups` script (listBackups → key, database id, kind; nothing else).
|
|
127
|
+
- `planRetention(entries, keep)` (pure), `listBackups(bucket, prefix)` (→ `{ backups (with
|
|
128
|
+
digestKey, digestMetadata), orphanDigests (with at), ignored, keyIds }`), `dayOf`, `isoWeekOf`, `monthOf`, `assertValidRetention`.
|
|
129
|
+
- `backupKey(prefix, at)` → `<prefix>/<yyyy>/<mm>/<yyyy-mm-ddThh-mm-ssZ>.sql` (UTC);
|
|
130
|
+
`parseBackupKey(prefix, key)` → `Date | null`; `assertValidPrefix`; `backupInstanceId(at)` →
|
|
131
|
+
`backup-<yyyy-mm-dd>` (UTC); `METADATA`; `digestKey(key)` / `DIGEST_SUFFIX`;
|
|
132
|
+
`isValidBookmark`; `isValidDatabaseId`.
|
|
133
|
+
|
|
134
|
+
### `@cardonjs/backups/workflow`
|
|
135
|
+
- `defineBackupWorkflow<Adapters, Config>({ name, database: (c) => D1ExportOptions, bucket: (c)
|
|
136
|
+
=> R2Bucket, prefix, keep, polling?: { intervalSeconds?: 10, timeoutMinutes?: 60 }, partSize?,
|
|
137
|
+
clock?, encryption?: (c) => backupEncryption({ keys: { id: c.config.SECRET }, current: id })
|
|
138
|
+
})` → a `defineWorkflow` definition (params `{}`, no events). Invalid keys stop an instance
|
|
139
|
+
before any step: `backup: invalid encryption options`. Steps: `plan backup` (key
|
|
140
|
+
moment, run id, database id), `start export`, `wait n` + `poll export n` (the poll that sees
|
|
141
|
+
`complete` COPIES IN THE SAME STEP; a start complete at once copies in the start step),
|
|
142
|
+
`restart export n` (after `not_exporting`/`export_lost`, e.g. a copy that failed and was
|
|
143
|
+
retried: the POLL STEP first looks for this run's finished object and uses it, even after both
|
|
144
|
+
restarts; the restart step looks again, else starts a new export; at most 2, then
|
|
145
|
+
`backup: the export stopped before its dump was copied (2 restarts)`), `prune backups`.
|
|
146
|
+
Start/restart/poll steps time out after 30 min. Logs `backup copy failed` (reason) before a
|
|
147
|
+
copy retry. Output `{ key, size, bookmark,
|
|
148
|
+
databaseId, sha256, reused, kept, deleted }`; logs `backup copied` with key, size, sha256,
|
|
149
|
+
databaseId. The plan step stores the database id: a replay after `DB_ID` changed fails
|
|
150
|
+
permanently (`backup: the database id changed since this instance started`). Step results of
|
|
151
|
+
the version before B-004 (no `copied`): a pending one goes on; anything else fails with
|
|
152
|
+
`backup: this instance was started by an earlier version of @cardonjs/backups; start a new one`.
|
|
153
|
+
Non-retryable
|
|
154
|
+
failures end with
|
|
155
|
+
`NonRetryableError` and a fixed message (`backup: export start failed (unauthorized)`,
|
|
156
|
+
`backup: prune refused (other_database)`).
|
|
157
|
+
- Bind with `workflowEntrypoint(definition, { adapters, config })` from
|
|
158
|
+
`@cardonjs/workflows-cf/entrypoint` in a SEPARATE backup-only Worker (its own Wrangler config:
|
|
159
|
+
token secret, bucket binding, cron, Workflow; no fetch handler, no D1 binding); start from its
|
|
160
|
+
daily cron with
|
|
161
|
+
`workflows(env.BINDING, definition).start({ id: backupInstanceId(new Date(controller.scheduledTime)), params: {} })`.
|
|
162
|
+
|
|
163
|
+
### `@cardonjs/backups/restore` (Node)
|
|
164
|
+
- `restoreStatements(sql)`: statements without BEGIN/COMMIT; throws for sqlite3-CLI dumps.
|
|
165
|
+
- `checkRestore(db, dump: string | Uint8Array | ArrayBuffer, { bytes?, sha256?, encryption?, key?, databaseId? })` → `{ ok, sha256, statements, tables: [{ name,
|
|
166
|
+
expectedRows, loadedRows }], problems, encryption?, identity? }`. With `encryption: { keys }`
|
|
167
|
+
the (encrypted) bytes are decrypted first, failing closed with `BackupDecryptError` before the
|
|
168
|
+
database is touched; bytes/sha256 are of the encrypted bytes; `key` (the R2 key downloaded)
|
|
169
|
+
and `databaseId` must match the authenticated header (`wrong_backup`), and `identity` reports
|
|
170
|
+
what it names and `checked: { databaseId, key }`. Without `encryption`, an encrypted backup is
|
|
171
|
+
refused (`reason: "encrypted"`) and `key`/`databaseId` are a TypeError; `encryption: null` is
|
|
172
|
+
a TypeError. `db` must be a new, empty, LOCAL database
|
|
173
|
+
(`startBindings({ d1: 1 })`): the "has tables" guard does not stop an empty production one.
|
|
174
|
+
Pass the file's BYTES (`readFile(path)`): size and digest are checked on them (a string is
|
|
175
|
+
re-encoded as UTF-8 and cannot prove byte equality with invalid UTF-8 in a TEXT value). Take
|
|
176
|
+
bytes/sha256 from outside the bucket (instance output, log line), not the sidecar.
|
|
177
|
+
Proves the dump loads and (with bytes/sha256) matches what was copied; cannot prove
|
|
178
|
+
Cloudflare's dump was complete (a dump cut at a statement boundary passes on its own). A load
|
|
179
|
+
error names the statements and SQLite's result code only, with no `cause` (D1's message may
|
|
180
|
+
quote SQL, i.e. row data).
|
|
181
|
+
|
|
182
|
+
## Example
|
|
183
|
+
|
|
184
|
+
```ts
|
|
185
|
+
// backup-worker/src/database-backup.workflow.ts (a Worker that does nothing but backups)
|
|
186
|
+
import { defineBackupWorkflow } from "@cardonjs/backups/workflow";
|
|
187
|
+
|
|
188
|
+
export const databaseBackup = defineBackupWorkflow<Adapters, Config>({
|
|
189
|
+
name: "database-backup",
|
|
190
|
+
database: (c) => ({
|
|
191
|
+
accountId: c.config.CF_ACCOUNT_ID,
|
|
192
|
+
databaseId: c.config.DB_ID,
|
|
193
|
+
apiToken: c.config.D1_EXPORT_TOKEN, // a secret of the backup Worker only
|
|
194
|
+
}),
|
|
195
|
+
bucket: (c) => c.adapters.backupBucket, // env.BACKUPS, a bucket only for backups
|
|
196
|
+
prefix: "d1/main", // one prefix per database
|
|
197
|
+
keep: { daily: 7, weekly: 4, monthly: 12 },
|
|
198
|
+
});
|
|
199
|
+
```
|
|
200
|
+
|
|
201
|
+
## Common mistakes
|
|
202
|
+
|
|
203
|
+
- Putting the token or the backup bucket in the Worker that serves the app: the token is D1
|
|
204
|
+
Write (assume it can change and delete every D1 database of the account); a compromised app
|
|
205
|
+
dependency would get the database and its backups. Use a separate backup Worker.
|
|
206
|
+
- A public bucket, an r2.dev URL or shared R2 credentials: anyone who reads the bucket reads
|
|
207
|
+
every row (unless `encryption` is on); anyone who writes it decides what a restore runs in
|
|
208
|
+
production (with encryption: can still delete backups; an authentic backup of another
|
|
209
|
+
database or key name swapped in is refused as `wrong_backup` when the restore passes
|
|
210
|
+
`expected` / checkRestore's `key` + `databaseId`; two authentic objects of the same key name
|
|
211
|
+
are told apart only by the digest kept outside the bucket).
|
|
212
|
+
- Turning encryption on with the key stored only as a Worker secret (lost key = lost backups),
|
|
213
|
+
passing a key on a command line, logging the encryption settings' source values, keeping old
|
|
214
|
+
keys in the Worker (it only needs `current`), destroying an old key while `keyIds` or a
|
|
215
|
+
downloaded copy still names it, sharing one key between environments, or decrypting a
|
|
216
|
+
restore without `expected` / `key` + `databaseId`.
|
|
217
|
+
- `encryption: env.KEY ? backupEncryption(…) : undefined`: refused on purpose (never plain by
|
|
218
|
+
accident); leave the property out to mean plain.
|
|
219
|
+
- Logging or returning the token or the signed URL; putting either in a step result; logging
|
|
220
|
+
inside an injected `fetch`.
|
|
221
|
+
- Two databases on one prefix (backups are written; pruning refuses with `other_database`).
|
|
222
|
+
- A manual `wrangler d1 export` of the same database, or a second backup instance, while a backup
|
|
223
|
+
runs (two exports of one database: not verified). Trigger a manual retry
|
|
224
|
+
(`--id backup-<date>-retry`) only once the day's instance is `errored` or `complete`: one
|
|
225
|
+
instance's prune can delete the other's same-day backup.
|
|
226
|
+
- Restoring into a new database and switching only the app's binding: the backup keeps
|
|
227
|
+
exporting the old database. Change the backup Worker's `DB_ID` (wrangler.jsonc) and `prefix`
|
|
228
|
+
(the Workflow definition file) in the same deploy, after checking no backup instance is
|
|
229
|
+
running (`wrangler workflows instances list <name>`), run one backup, check its `databaseId`.
|
|
230
|
+
- Loading a backup over the production database: load it into a NEW database
|
|
231
|
+
(`wrangler d1 create`, `wrangler d1 execute <new> --remote --file <path outside the repo>`) and
|
|
232
|
+
switch. Time Travel (`wrangler d1 time-travel restore`) for the last 30 days.
|
|
233
|
+
- Pointing `checkRestore` at a remote database.
|
|
234
|
+
- Trusting the `<key>.sha256` sidecar against tampering (it is in the same bucket), or passing
|
|
235
|
+
`checkRestore` the dump as text: compare the file's bytes with a digest kept outside the
|
|
236
|
+
bucket.
|
|
237
|
+
- Building keys by hand (refused) or putting other files under the prefix and expecting
|
|
238
|
+
retention to manage them (it ignores them).
|
|
239
|
+
- Forgetting that an export locks the database while it runs (schedule it at the quietest
|
|
240
|
+
time), and that backups keep deleted users' data until pruned.
|
|
241
|
+
- Mixing an R2 lifecycle expiry rule and `pruneBackups` on the same prefix; a bucket lock longer
|
|
242
|
+
than the age at which the policy first deletes makes every prune fail.
|
|
243
|
+
- Polling again after a `ready` answer (to get a "fresh" signed URL): Cloudflare answers
|
|
244
|
+
"Not currently exporting anything." Copy from the `ready` answer you got.
|
|
245
|
+
- Assuming everything was verified against real Cloudflare: the export API's request and answer
|
|
246
|
+
shapes, the nested signed URL and the once-only completion were observed on 2026-11-20; the
|
|
247
|
+
download (signed URL host and lifetime, `Content-Length`), R2 limits, `DigestStream` in
|
|
248
|
+
production, the token's scoping and a real dump's contents were not (README, "What was
|
|
249
|
+
observed on Cloudflare, and what is not verified").
|
package/package.json
CHANGED
|
@@ -1,6 +1,79 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@cardonjs/backups",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.3.2",
|
|
4
|
+
"description": "D1 backups for Cardón apps: Cloudflare's D1 export streamed into R2 (optionally encrypted), retention by day, week and month, a backup Workflow and a restore check.",
|
|
5
|
+
"license": "MIT",
|
|
6
|
+
"repository": {
|
|
7
|
+
"type": "git",
|
|
8
|
+
"url": "git+https://github.com/cardonjs/cardon.git",
|
|
9
|
+
"directory": "packages/backups"
|
|
10
|
+
},
|
|
11
|
+
"homepage": "https://github.com/cardonjs/cardon/tree/main/packages/backups#readme",
|
|
12
|
+
"bugs": {
|
|
13
|
+
"url": "https://github.com/cardonjs/cardon/issues"
|
|
14
|
+
},
|
|
15
|
+
"type": "module",
|
|
16
|
+
"sideEffects": false,
|
|
17
|
+
"exports": {
|
|
18
|
+
".": {
|
|
19
|
+
"types": "./dist/index.d.ts",
|
|
20
|
+
"default": "./dist/index.js"
|
|
21
|
+
},
|
|
22
|
+
"./workflow": {
|
|
23
|
+
"types": "./dist/workflow.d.ts",
|
|
24
|
+
"default": "./dist/workflow.js"
|
|
25
|
+
},
|
|
26
|
+
"./restore": {
|
|
27
|
+
"types": "./dist/restore.d.ts",
|
|
28
|
+
"default": "./dist/restore.js"
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"dist",
|
|
33
|
+
"llms.txt",
|
|
34
|
+
"FORMAT.md"
|
|
35
|
+
],
|
|
36
|
+
"publishConfig": {
|
|
37
|
+
"access": "public"
|
|
38
|
+
},
|
|
39
|
+
"peerDependencies": {
|
|
40
|
+
"zod": "^4.6.7",
|
|
41
|
+
"@cardonjs/core": "^0.5.1",
|
|
42
|
+
"@cardonjs/testing": "^0.6.0",
|
|
43
|
+
"@cardonjs/workflows-cf": "^0.3.0"
|
|
44
|
+
},
|
|
45
|
+
"peerDependenciesMeta": {
|
|
46
|
+
"@cardonjs/core": {
|
|
47
|
+
"optional": true
|
|
48
|
+
},
|
|
49
|
+
"@cardonjs/testing": {
|
|
50
|
+
"optional": true
|
|
51
|
+
},
|
|
52
|
+
"@cardonjs/workflows-cf": {
|
|
53
|
+
"optional": true
|
|
54
|
+
},
|
|
55
|
+
"zod": {
|
|
56
|
+
"optional": true
|
|
57
|
+
}
|
|
58
|
+
},
|
|
59
|
+
"devDependencies": {
|
|
60
|
+
"@cloudflare/workers-types": "5.20261114.1",
|
|
61
|
+
"@hono/zod-openapi": "1.6.3",
|
|
62
|
+
"@scalar/hono-api-reference": "0.12.20",
|
|
63
|
+
"hono": "4.13.18",
|
|
64
|
+
"miniflare": "4.20260730.0",
|
|
65
|
+
"rolldown": "1.2.19",
|
|
66
|
+
"typescript": "7.0.2",
|
|
67
|
+
"vitest": "5.1.0",
|
|
68
|
+
"zod": "4.6.7",
|
|
69
|
+
"@cardonjs/config": "0.0.0",
|
|
70
|
+
"@cardonjs/testing": "0.6.0",
|
|
71
|
+
"@cardonjs/core": "0.5.1",
|
|
72
|
+
"@cardonjs/workflows-cf": "0.3.0"
|
|
73
|
+
},
|
|
74
|
+
"scripts": {
|
|
75
|
+
"build": "tsc -p tsconfig.build.json",
|
|
76
|
+
"typecheck": "tsc -p tsconfig.json --noEmit",
|
|
77
|
+
"test": "vitest run"
|
|
78
|
+
}
|
|
6
79
|
}
|