@prenta/cli 0.16.4 → 0.17.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/.turbo/turbo-build.log +1 -1
  2. package/.turbo/turbo-test.log +31 -21
  3. package/CHANGELOG.md +12 -0
  4. package/dist/backup/blob-store.d.ts +89 -0
  5. package/dist/backup/blob-store.d.ts.map +1 -0
  6. package/dist/backup/blob-store.js +183 -0
  7. package/dist/backup/blob-store.js.map +1 -0
  8. package/dist/backup/common.d.ts +68 -0
  9. package/dist/backup/common.d.ts.map +1 -0
  10. package/dist/backup/common.js +127 -0
  11. package/dist/backup/common.js.map +1 -0
  12. package/dist/backup/crypto.d.ts +26 -0
  13. package/dist/backup/crypto.d.ts.map +1 -0
  14. package/dist/backup/crypto.js +175 -0
  15. package/dist/backup/crypto.js.map +1 -0
  16. package/dist/backup/manifest.d.ts +69 -0
  17. package/dist/backup/manifest.d.ts.map +1 -0
  18. package/dist/backup/manifest.js +161 -0
  19. package/dist/backup/manifest.js.map +1 -0
  20. package/dist/backup/pg-tools.d.ts +74 -0
  21. package/dist/backup/pg-tools.d.ts.map +1 -0
  22. package/dist/backup/pg-tools.js +267 -0
  23. package/dist/backup/pg-tools.js.map +1 -0
  24. package/dist/backup/workflow-template.d.ts +14 -0
  25. package/dist/backup/workflow-template.d.ts.map +1 -0
  26. package/dist/backup/workflow-template.js +49 -0
  27. package/dist/backup/workflow-template.js.map +1 -0
  28. package/dist/commands/db-backup.d.ts +56 -0
  29. package/dist/commands/db-backup.d.ts.map +1 -0
  30. package/dist/commands/db-backup.js +226 -0
  31. package/dist/commands/db-backup.js.map +1 -0
  32. package/dist/commands/db-restore.d.ts +70 -0
  33. package/dist/commands/db-restore.d.ts.map +1 -0
  34. package/dist/commands/db-restore.js +380 -0
  35. package/dist/commands/db-restore.js.map +1 -0
  36. package/dist/commands/doctor.d.ts.map +1 -1
  37. package/dist/commands/doctor.js +6 -1
  38. package/dist/commands/doctor.js.map +1 -1
  39. package/dist/deployment/diagnostics.d.ts +4 -0
  40. package/dist/deployment/diagnostics.d.ts.map +1 -1
  41. package/dist/deployment/diagnostics.js +30 -1
  42. package/dist/deployment/diagnostics.js.map +1 -1
  43. package/dist/index.js +4 -0
  44. package/dist/index.js.map +1 -1
  45. package/dist/utils/repo-root.d.ts +9 -0
  46. package/dist/utils/repo-root.d.ts.map +1 -0
  47. package/dist/utils/repo-root.js +21 -0
  48. package/dist/utils/repo-root.js.map +1 -0
  49. package/package.json +10 -3
  50. package/src/__tests__/backup-blob-store.test.ts +324 -0
  51. package/src/__tests__/backup-common.test.ts +103 -0
  52. package/src/__tests__/backup-crypto.test.ts +197 -0
  53. package/src/__tests__/backup-manifest.test.ts +189 -0
  54. package/src/__tests__/backup-pg-tools.test.ts +275 -0
  55. package/src/__tests__/db-backup.test.ts +557 -0
  56. package/src/__tests__/db-restore.test.ts +784 -0
  57. package/src/__tests__/deployment-diagnostics.test.ts +56 -1
  58. package/src/__tests__/fixtures/fake-blob.ts +120 -0
  59. package/src/__tests__/fixtures/fake-spawn.ts +66 -0
  60. package/src/__tests__/fixtures/pg-url.ts +56 -0
  61. package/src/__tests__/integration/backup-roundtrip.int.test.ts +208 -0
  62. package/src/__tests__/repo-root.test.ts +49 -0
  63. package/src/backup/blob-store.ts +294 -0
  64. package/src/backup/common.ts +153 -0
  65. package/src/backup/crypto.ts +192 -0
  66. package/src/backup/manifest.ts +217 -0
  67. package/src/backup/pg-tools.ts +384 -0
  68. package/src/backup/workflow-template.ts +49 -0
  69. package/src/commands/db-backup.ts +335 -0
  70. package/src/commands/db-restore.ts +542 -0
  71. package/src/commands/doctor.ts +6 -0
  72. package/src/deployment/diagnostics.ts +45 -1
  73. package/src/index.ts +4 -0
  74. package/src/utils/repo-root.ts +19 -0
@@ -0,0 +1,557 @@
1
+ import { Command } from 'commander'
2
+ import { existsSync } from 'node:fs'
3
+ import { mkdir, mkdtemp, readdir, readFile, rm, writeFile } from 'node:fs/promises'
4
+ import { tmpdir } from 'node:os'
5
+ import path from 'node:path'
6
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest'
7
+
8
+ import { decryptFile, parseBackupKey } from '../backup/crypto.js'
9
+ import { parseManifest, sha256File } from '../backup/manifest.js'
10
+ import { DB_BACKUP_WORKFLOW_PATH, DB_BACKUP_WORKFLOW_YAML } from '../backup/workflow-template.js'
11
+ import {
12
+ type DbBackupDeps,
13
+ type DbBackupSummary,
14
+ registerDbBackupCommand,
15
+ runDbBackup,
16
+ } from '../commands/db-backup.js'
17
+ import { createFakeBlob } from './fixtures/fake-blob.js'
18
+ import { createFakeSpawn, type ScriptResolver, versionScript } from './fixtures/fake-spawn.js'
19
+ import { FAKE_PASSWORD_1, pgUrl, TEST_BLOB_TOKEN } from './fixtures/pg-url.js'
20
+
21
+ const KEY = 'c'.repeat(64)
22
+ const DIRECT_URL = pgUrl({ password: FAKE_PASSWORD_1, database: 'prod', query: 'sslmode=require' })
23
+ const DIRECT_URL_SAFE = pgUrl({ database: 'prod', query: 'sslmode=require' })
24
+ const POOLED_URL = pgUrl({
25
+ password: FAKE_PASSWORD_1,
26
+ host: 'pooler.example.net',
27
+ database: 'prod',
28
+ })
29
+ const POOLED_URL_SAFE = pgUrl({ host: 'pooler.example.net', database: 'prod' })
30
+ const FAKE_DUMP = 'PGDMP-fake-custom-format-bytes'
31
+ const NOW = new Date('2026-09-18T03:30:00.000Z')
32
+
33
+ interface Harness {
34
+ deps: DbBackupDeps
35
+ calls: ReturnType<typeof createFakeSpawn>['calls']
36
+ fakeBlob: ReturnType<typeof createFakeBlob>
37
+ logs: { info: string[]; warn: string[]; error: string[]; success: string[] }
38
+ stdout: string[]
39
+ }
40
+
41
+ function happyScripts(overrides: Partial<Record<string, ScriptResolver>> = {}): ScriptResolver {
42
+ return (call) => {
43
+ const custom = overrides[call.command]
44
+ if (custom) return custom(call)
45
+ if (call.args[0] === '--version') return versionScript(call.command, '17.4')
46
+ switch (call.command) {
47
+ case 'pg_dump': {
48
+ const fileArg = call.args.find((a) => a.startsWith('--file='))!
49
+ return {
50
+ code: 0,
51
+ onSpawn: async () => {
52
+ await writeFile(fileArg.slice('--file='.length), FAKE_DUMP)
53
+ },
54
+ }
55
+ }
56
+ case 'psql':
57
+ return { code: 0, stdout: 'public\tprenta_documents\t120\npublic\tprenta_users\t3\n' }
58
+ default:
59
+ return { code: 1, stderr: `unexpected command ${call.command}` }
60
+ }
61
+ }
62
+ }
63
+
64
+ function harness(
65
+ env: NodeJS.ProcessEnv,
66
+ cwd: string,
67
+ scripts: ScriptResolver = happyScripts(),
68
+ ): Harness {
69
+ const { spawn, calls } = createFakeSpawn(scripts)
70
+ const fakeBlob = createFakeBlob({ pageSize: 50 })
71
+ const logs = {
72
+ info: [] as string[],
73
+ warn: [] as string[],
74
+ error: [] as string[],
75
+ success: [] as string[],
76
+ }
77
+ const stdout: string[] = []
78
+ const deps: DbBackupDeps = {
79
+ spawnImpl: spawn,
80
+ blobModule: fakeBlob.module,
81
+ env,
82
+ cwd,
83
+ now: () => NOW,
84
+ log: {
85
+ info: (m) => logs.info.push(m),
86
+ warn: (m) => logs.warn.push(m),
87
+ error: (m) => logs.error.push(m),
88
+ success: (m) => logs.success.push(m),
89
+ },
90
+ print: (line) => stdout.push(line),
91
+ }
92
+ return { deps, calls, fakeBlob, logs, stdout }
93
+ }
94
+
95
+ function lastJson(stdout: string[]): DbBackupSummary {
96
+ return JSON.parse(stdout[stdout.length - 1]!) as DbBackupSummary
97
+ }
98
+
99
+ describe('prenta db:backup', () => {
100
+ let cwd: string
101
+ let out: string
102
+
103
+ beforeEach(async () => {
104
+ cwd = await mkdtemp(path.join(tmpdir(), 'prenta-db-backup-cwd-'))
105
+ out = await mkdtemp(path.join(tmpdir(), 'prenta-db-backup-out-'))
106
+ })
107
+
108
+ afterEach(async () => {
109
+ await rm(cwd, { recursive: true, force: true })
110
+ await rm(out, { recursive: true, force: true })
111
+ })
112
+
113
+ const baseEnv = (): NodeJS.ProcessEnv => ({
114
+ DIRECT_DATABASE_URL: DIRECT_URL,
115
+ BACKUP_ENCRYPTION_KEY: KEY,
116
+ })
117
+
118
+ describe('--init-workflow', () => {
119
+ it('writes the workflow YAML verbatim and exits 0 without touching the database', async () => {
120
+ const h = harness({}, cwd)
121
+ const code = await runDbBackup({ initWorkflow: true }, h.deps)
122
+ expect(code).toBe(0)
123
+ const written = await readFile(path.join(cwd, DB_BACKUP_WORKFLOW_PATH), 'utf-8')
124
+ expect(written).toBe(DB_BACKUP_WORKFLOW_YAML)
125
+ expect(written).toContain("cron: '30 3 * * *'")
126
+ expect(written).toContain('prenta db:backup --upload --retention-days 30 --json')
127
+ expect(written).toContain('${{ secrets.BACKUP_ENCRYPTION_KEY }}')
128
+ expect(h.calls).toHaveLength(0)
129
+ })
130
+
131
+ it('writes to the git top-level when run from a nested app directory (apps/cms)', async () => {
132
+ await mkdir(path.join(cwd, '.git'))
133
+ const appDir = path.join(cwd, 'apps', 'cms')
134
+ await mkdir(appDir, { recursive: true })
135
+ const h = harness({}, appDir)
136
+
137
+ expect(await runDbBackup({ initWorkflow: true }, h.deps)).toBe(0)
138
+ expect(await readFile(path.join(cwd, DB_BACKUP_WORKFLOW_PATH), 'utf-8')).toBe(
139
+ DB_BACKUP_WORKFLOW_YAML,
140
+ )
141
+ expect(existsSync(path.join(appDir, '.github'))).toBe(false)
142
+ // The success line names the absolute path so the operator sees where it went.
143
+ expect(h.logs.success.join('\n')).toContain(path.join(cwd, '.github'))
144
+
145
+ // The existing-file check looks at the same place.
146
+ expect(await runDbBackup({ initWorkflow: true }, h.deps)).toBe(1)
147
+ })
148
+
149
+ it('refuses to overwrite an existing workflow without --force', async () => {
150
+ const h = harness({}, cwd)
151
+ const file = path.join(cwd, DB_BACKUP_WORKFLOW_PATH)
152
+ await runDbBackup({ initWorkflow: true }, h.deps)
153
+ await writeFile(file, 'custom: true\n')
154
+
155
+ expect(await runDbBackup({ initWorkflow: true }, h.deps)).toBe(1)
156
+ expect(await readFile(file, 'utf-8')).toBe('custom: true\n')
157
+ expect(h.logs.error.join('\n')).toMatch(/--force/)
158
+
159
+ expect(await runDbBackup({ initWorkflow: true, force: true }, h.deps)).toBe(0)
160
+ expect(await readFile(file, 'utf-8')).toBe(DB_BACKUP_WORKFLOW_YAML)
161
+ })
162
+ })
163
+
164
+ describe('preconditions (exit 2)', () => {
165
+ it('fails when no database URL is configured', async () => {
166
+ const h = harness({ BACKUP_ENCRYPTION_KEY: KEY }, cwd)
167
+ expect(await runDbBackup({ out }, h.deps)).toBe(2)
168
+ expect(h.logs.error.join('\n')).toMatch(/DIRECT_DATABASE_URL/)
169
+ expect(h.calls).toHaveLength(0)
170
+ })
171
+
172
+ it('refuses localhost / 127.0.0.1 unless --allow-local', async () => {
173
+ for (const host of ['localhost', '127.0.0.1']) {
174
+ const h = harness(
175
+ {
176
+ DATABASE_URL: pgUrl({ user: 'u', password: 'password', host, database: 'dev' }),
177
+ BACKUP_ENCRYPTION_KEY: KEY,
178
+ },
179
+ cwd,
180
+ )
181
+ expect(await runDbBackup({ out }, h.deps)).toBe(2)
182
+ expect(h.logs.error.join('\n')).toMatch(/--allow-local/)
183
+ expect(h.calls).toHaveLength(0)
184
+ }
185
+ const allowed = harness(
186
+ {
187
+ DATABASE_URL: pgUrl({
188
+ user: 'u',
189
+ password: 'password',
190
+ host: 'localhost',
191
+ database: 'dev',
192
+ }),
193
+ BACKUP_ENCRYPTION_KEY: KEY,
194
+ },
195
+ cwd,
196
+ )
197
+ expect(await runDbBackup({ out, allowLocal: true }, allowed.deps)).toBe(0)
198
+ })
199
+
200
+ it('fails on a missing or malformed BACKUP_ENCRYPTION_KEY before running pg_dump', async () => {
201
+ const missing = harness({ DIRECT_DATABASE_URL: DIRECT_URL }, cwd)
202
+ expect(await runDbBackup({ out }, missing.deps)).toBe(2)
203
+ expect(missing.logs.error.join('\n')).toMatch(/BACKUP_ENCRYPTION_KEY/)
204
+ expect(missing.calls.filter((c) => c.command === 'pg_dump')).toHaveLength(0)
205
+
206
+ const bad = harness({ DIRECT_DATABASE_URL: DIRECT_URL, BACKUP_ENCRYPTION_KEY: 'abc' }, cwd)
207
+ expect(await runDbBackup({ out }, bad.deps)).toBe(2)
208
+ })
209
+
210
+ it('fails when pg_dump is missing or older than 17, with install hints', async () => {
211
+ const old = harness(
212
+ baseEnv(),
213
+ cwd,
214
+ happyScripts({ pg_dump: () => versionScript('pg_dump', '16.9') }),
215
+ )
216
+ expect(await runDbBackup({ out }, old.deps)).toBe(2)
217
+ expect(old.logs.error.join('\n')).toMatch(/16\.9/)
218
+ expect(old.logs.error.join('\n')).toMatch(/postgresql-client-17/)
219
+
220
+ const missing = harness(
221
+ baseEnv(),
222
+ cwd,
223
+ happyScripts({
224
+ pg_dump: () => ({
225
+ error: Object.assign(new Error('spawn pg_dump ENOENT'), { code: 'ENOENT' }),
226
+ }),
227
+ }),
228
+ )
229
+ expect(await runDbBackup({ out }, missing.deps)).toBe(2)
230
+ expect(missing.logs.error.join('\n')).toMatch(/not found/)
231
+ })
232
+
233
+ it('fails when --upload is requested without Blob credentials, naming both auth modes', async () => {
234
+ const h = harness(baseEnv(), cwd)
235
+ expect(await runDbBackup({ out, upload: true }, h.deps)).toBe(2)
236
+ const error = h.logs.error.join('\n')
237
+ expect(error).toMatch(/BLOB_READ_WRITE_TOKEN/)
238
+ expect(error).toMatch(/VERCEL_OIDC_TOKEN/)
239
+ expect(error).toMatch(/BLOB_STORE_ID/)
240
+ expect(h.calls.filter((c) => c.command === 'pg_dump')).toHaveLength(0)
241
+
242
+ // Half of the OIDC pair is not enough.
243
+ const half = harness({ ...baseEnv(), BLOB_STORE_ID: 'store_123' }, cwd)
244
+ expect(await runDbBackup({ out, upload: true }, half.deps)).toBe(2)
245
+ })
246
+
247
+ it('rejects a non-positive --retention-days', async () => {
248
+ const h = harness({ ...baseEnv(), BLOB_READ_WRITE_TOKEN: 't' }, cwd)
249
+ expect(await runDbBackup({ out, upload: true, retentionDays: 0 }, h.deps)).toBe(2)
250
+ })
251
+ })
252
+
253
+ describe('local backup', () => {
254
+ it('dumps with the exact argv, encrypts, and writes a verifiable manifest', async () => {
255
+ const h = harness(baseEnv(), cwd)
256
+ const code = await runDbBackup({ out, json: true }, h.deps)
257
+ expect(code).toBe(0)
258
+
259
+ const dump = h.calls.find((c) => c.command === 'pg_dump' && c.args[0] !== '--version')!
260
+ expect(dump.args.slice(0, 3)).toEqual(['--format=custom', '--no-owner', '--no-privileges'])
261
+ expect(dump.args[3]).toMatch(/^--file=.+\.dump$/)
262
+ expect(dump.args[4]).toBe(`--dbname=${DIRECT_URL_SAFE}`)
263
+ expect(dump.args).toHaveLength(5)
264
+ expect(dump.args.join(' ')).not.toContain(FAKE_PASSWORD_1)
265
+ expect(dump.options.env?.PGPASSWORD).toBe(FAKE_PASSWORD_1)
266
+
267
+ // Row estimate ran before the dump.
268
+ const order = h.calls.filter((c) => c.args[0] !== '--version').map((c) => c.command)
269
+ expect(order).toEqual(['psql', 'pg_dump'])
270
+
271
+ const summary = lastJson(h.stdout)
272
+ expect(summary.stamp).toBe('2026-09-18T033000Z')
273
+ expect(summary.dumpPath).toBe(path.join(out, '2026-09-18T033000Z.dump.enc'))
274
+ expect(summary.manifestPath).toBe(path.join(out, '2026-09-18T033000Z.manifest.json'))
275
+ expect(summary.tableCount).toBe(2)
276
+ expect(summary.uploaded).toBe(false)
277
+ expect(summary.pruned).toEqual([])
278
+ expect(summary.durationMs).toBeGreaterThanOrEqual(0)
279
+
280
+ // Encrypted output decrypts back to what pg_dump wrote.
281
+ const plain = path.join(out, 'roundtrip.dump')
282
+ await decryptFile(summary.dumpPath, plain, parseBackupKey(KEY))
283
+ expect(await readFile(plain, 'utf-8')).toBe(FAKE_DUMP)
284
+
285
+ const manifest = parseManifest(JSON.parse(await readFile(summary.manifestPath, 'utf-8')))
286
+ expect(manifest).toMatchObject({
287
+ version: 1,
288
+ createdAt: NOW.toISOString(),
289
+ stamp: '2026-09-18T033000Z',
290
+ database: { host: 'db.example.net', name: 'prod' },
291
+ pgDumpVersion: '17.4',
292
+ rowCounts: 'estimate',
293
+ tables: [
294
+ { schema: 'public', name: 'prenta_documents', rows: 120 },
295
+ { schema: 'public', name: 'prenta_users', rows: 3 },
296
+ ],
297
+ })
298
+ expect(manifest.sha256).toBe(await sha256File(summary.dumpPath))
299
+ expect(manifest.sizeBytes).toBe(summary.sizeBytes)
300
+ expect(JSON.stringify(manifest)).not.toContain(FAKE_PASSWORD_1)
301
+
302
+ // Only the two artifacts (plus our round-trip file) remain — no raw dump left behind.
303
+ const files = (await readdir(out)).sort()
304
+ expect(files).toEqual([
305
+ '2026-09-18T033000Z.dump.enc',
306
+ '2026-09-18T033000Z.manifest.json',
307
+ 'roundtrip.dump',
308
+ ])
309
+ })
310
+
311
+ it('falls back to DATABASE_URL with a pooled-URL warning', async () => {
312
+ const h = harness({ DATABASE_URL: POOLED_URL, BACKUP_ENCRYPTION_KEY: KEY }, cwd)
313
+ expect(await runDbBackup({ out }, h.deps)).toBe(0)
314
+ expect(h.logs.warn.join('\n')).toMatch(/DATABASE_URL/)
315
+ expect(h.logs.warn.join('\n')).toMatch(/pooled/i)
316
+ const dump = h.calls.find((c) => c.command === 'pg_dump' && c.args[0] !== '--version')!
317
+ expect(dump.args[4]).toBe(`--dbname=${POOLED_URL_SAFE}`)
318
+ })
319
+
320
+ it('reads .env from cwd without overriding the process environment', async () => {
321
+ await writeFile(
322
+ path.join(cwd, '.env'),
323
+ `DIRECT_DATABASE_URL="${DIRECT_URL}"\nBACKUP_ENCRYPTION_KEY=${KEY}\n`,
324
+ )
325
+ const h = harness({}, cwd)
326
+ expect(await runDbBackup({ out }, h.deps)).toBe(0)
327
+ })
328
+
329
+ it('exits 1 with redacted stderr when pg_dump fails, leaving no artifacts', async () => {
330
+ const h = harness(
331
+ baseEnv(),
332
+ cwd,
333
+ happyScripts({
334
+ pg_dump: (call) =>
335
+ call.args[0] === '--version'
336
+ ? versionScript('pg_dump', '17.4')
337
+ : { code: 1, stderr: `pg_dump: error: connection to ${DIRECT_URL} failed` },
338
+ }),
339
+ )
340
+ expect(await runDbBackup({ out }, h.deps)).toBe(1)
341
+ const errors = h.logs.error.join('\n')
342
+ expect(errors).toMatch(/pg_dump exited with code 1/)
343
+ expect(errors).not.toContain(FAKE_PASSWORD_1)
344
+ expect(await readdir(out)).toEqual([])
345
+ })
346
+
347
+ it('warns and records no tables when psql is unavailable', async () => {
348
+ const h = harness(
349
+ baseEnv(),
350
+ cwd,
351
+ happyScripts({
352
+ psql: () => ({
353
+ error: Object.assign(new Error('spawn psql ENOENT'), { code: 'ENOENT' }),
354
+ }),
355
+ }),
356
+ )
357
+ expect(await runDbBackup({ out, json: true }, h.deps)).toBe(0)
358
+ expect(h.logs.warn.join('\n')).toMatch(/psql/)
359
+ expect(lastJson(h.stdout).tableCount).toBe(0)
360
+ })
361
+ })
362
+
363
+ describe('--upload', () => {
364
+ const uploadEnv = (): NodeJS.ProcessEnv => ({
365
+ ...baseEnv(),
366
+ BLOB_READ_WRITE_TOKEN: TEST_BLOB_TOKEN,
367
+ })
368
+
369
+ it('uploads manifest then dump under the prefix, then prunes expired pairs', async () => {
370
+ const h = harness(uploadEnv(), cwd)
371
+ h.fakeBlob.seed('backups/db/2026-07-01T033000Z.dump.enc', 'old')
372
+ h.fakeBlob.seed('backups/db/2026-07-01T033000Z.manifest.json', '{}')
373
+ h.fakeBlob.seed('backups/db/2026-09-17T033000Z.dump.enc', 'yesterday')
374
+ h.fakeBlob.seed('backups/db/keep.txt', 'not ours')
375
+
376
+ const code = await runDbBackup({ out, upload: true, json: true }, h.deps)
377
+ expect(code).toBe(0)
378
+
379
+ // Manifest first: `--list` / `latest` only consider `.dump.enc` objects,
380
+ // so an orphan manifest is invisible while an orphan dump would be
381
+ // offered as restorable without a manifest.
382
+ const puts = h.fakeBlob.calls.filter((c) => c.op === 'put').map((c) => c.args[0])
383
+ expect(puts).toEqual([
384
+ 'backups/db/2026-09-18T033000Z.manifest.json',
385
+ 'backups/db/2026-09-18T033000Z.dump.enc',
386
+ ])
387
+ const ops = h.fakeBlob.calls.map((c) => c.op)
388
+ expect(ops.indexOf('del')).toBeGreaterThan(ops.lastIndexOf('put'))
389
+
390
+ const summary = lastJson(h.stdout)
391
+ expect(summary.uploaded).toBe(true)
392
+ expect(summary.blobPathname).toBe('backups/db/2026-09-18T033000Z.dump.enc')
393
+ expect(summary.pruned.sort()).toEqual([
394
+ 'backups/db/2026-07-01T033000Z.dump.enc',
395
+ 'backups/db/2026-07-01T033000Z.manifest.json',
396
+ ])
397
+ expect([...h.fakeBlob.objects.keys()].sort()).toEqual([
398
+ 'backups/db/2026-09-17T033000Z.dump.enc',
399
+ 'backups/db/2026-09-18T033000Z.dump.enc',
400
+ 'backups/db/2026-09-18T033000Z.manifest.json',
401
+ 'backups/db/keep.txt',
402
+ ])
403
+ // Uploaded bytes are the encrypted file, byte for byte.
404
+ const local = await readFile(summary.dumpPath)
405
+ expect(
406
+ h.fakeBlob.objects.get('backups/db/2026-09-18T033000Z.dump.enc')!.body.equals(local),
407
+ ).toBe(true)
408
+ })
409
+
410
+ it('token mode passes BLOB_READ_WRITE_TOKEN to every Blob call', async () => {
411
+ const h = harness(uploadEnv(), cwd)
412
+ h.fakeBlob.seed('backups/db/2026-07-01T033000Z.dump.enc', 'old')
413
+ expect(await runDbBackup({ out, upload: true }, h.deps)).toBe(0)
414
+ const ops = h.fakeBlob.calls.map((c) => c.op)
415
+ expect(ops).toEqual(expect.arrayContaining(['put', 'list', 'del']))
416
+ for (const call of h.fakeBlob.calls) {
417
+ expect(call.args[call.args.length - 1], call.op).toMatchObject({
418
+ token: TEST_BLOB_TOKEN,
419
+ })
420
+ }
421
+ })
422
+
423
+ it('OIDC mode (VERCEL_OIDC_TOKEN + BLOB_STORE_ID, no token) uploads and omits `token` from every Blob call', async () => {
424
+ const oidcToken = ['fake', 'oidc', 'jwt'].join('.')
425
+ const h = harness(
426
+ { ...baseEnv(), VERCEL_OIDC_TOKEN: oidcToken, BLOB_STORE_ID: 'store_123' },
427
+ cwd,
428
+ )
429
+ h.fakeBlob.seed('backups/db/2026-07-01T033000Z.dump.enc', 'old')
430
+
431
+ expect(await runDbBackup({ out, upload: true, json: true }, h.deps)).toBe(0)
432
+ expect(lastJson(h.stdout).uploaded).toBe(true)
433
+ const ops = h.fakeBlob.calls.map((c) => c.op)
434
+ expect(ops).toEqual(expect.arrayContaining(['put', 'list', 'del']))
435
+ for (const call of h.fakeBlob.calls) {
436
+ expect(Object.keys(call.args[call.args.length - 1] as object), call.op).not.toContain(
437
+ 'token',
438
+ )
439
+ }
440
+ })
441
+
442
+ it('honours --prefix and --retention-days', async () => {
443
+ const h = harness(uploadEnv(), cwd)
444
+ h.fakeBlob.seed('sites/acme/2026-09-10T033000Z.dump.enc', 'eight days old')
445
+ h.fakeBlob.seed('backups/db/2026-01-01T033000Z.dump.enc', 'other prefix, untouched')
446
+
447
+ expect(
448
+ await runDbBackup(
449
+ { out, upload: true, prefix: 'sites/acme', retentionDays: 7, json: true },
450
+ h.deps,
451
+ ),
452
+ ).toBe(0)
453
+ const summary = lastJson(h.stdout)
454
+ expect(summary.blobPathname).toBe('sites/acme/2026-09-18T033000Z.dump.enc')
455
+ expect(summary.pruned).toEqual(['sites/acme/2026-09-10T033000Z.dump.enc'])
456
+ expect(h.fakeBlob.objects.has('backups/db/2026-01-01T033000Z.dump.enc')).toBe(true)
457
+ })
458
+
459
+ it('exits 1 and never prunes when the upload fails', async () => {
460
+ const h = harness(uploadEnv(), cwd)
461
+ h.fakeBlob.seed('backups/db/2020-01-01T000000Z.dump.enc', 'ancient but safe')
462
+ h.fakeBlob.failNextPut(new Error('blob service unavailable'))
463
+
464
+ expect(await runDbBackup({ out, upload: true }, h.deps)).toBe(1)
465
+ expect(h.logs.error.join('\n')).toMatch(/blob service unavailable/)
466
+ expect(h.fakeBlob.calls.some((c) => c.op === 'del')).toBe(false)
467
+ expect(h.fakeBlob.objects.has('backups/db/2020-01-01T000000Z.dump.enc')).toBe(true)
468
+ // The local artifacts are kept so the operator can retry the upload.
469
+ expect(existsSync(path.join(out, '2026-09-18T033000Z.dump.enc'))).toBe(true)
470
+ })
471
+
472
+ it('removes the already-uploaded manifest when the dump upload fails (no orphan pair half)', async () => {
473
+ const h = harness(uploadEnv(), cwd)
474
+ h.fakeBlob.failPutOf(
475
+ 'backups/db/2026-09-18T033000Z.dump.enc',
476
+ new Error('connection reset during multipart upload'),
477
+ )
478
+
479
+ expect(await runDbBackup({ out, upload: true }, h.deps)).toBe(1)
480
+ expect(h.logs.error.join('\n')).toMatch(/connection reset/)
481
+ expect(h.fakeBlob.objects.has('backups/db/2026-09-18T033000Z.manifest.json')).toBe(false)
482
+ expect(h.fakeBlob.objects.has('backups/db/2026-09-18T033000Z.dump.enc')).toBe(false)
483
+ const del = h.fakeBlob.calls.filter((c) => c.op === 'del')
484
+ expect(del).toHaveLength(1)
485
+ expect(del[0]?.args[0]).toBe('backups/db/2026-09-18T033000Z.manifest.json')
486
+ // Nothing under the prefix was pruned - only the half-uploaded manifest went.
487
+ expect(h.logs.warn.join('\n')).not.toMatch(/prun/i)
488
+ })
489
+
490
+ it('warns (still exit 1) when the orphan manifest cannot be removed', async () => {
491
+ const h = harness(uploadEnv(), cwd)
492
+ h.fakeBlob.failPutOf('backups/db/2026-09-18T033000Z.dump.enc', new Error('dump put failed'))
493
+ const realDel = h.fakeBlob.module.del.bind(h.fakeBlob.module)
494
+ h.fakeBlob.module.del = async (paths, options) => {
495
+ await realDel(paths, options)
496
+ throw new Error('del also failed')
497
+ }
498
+
499
+ expect(await runDbBackup({ out, upload: true }, h.deps)).toBe(1)
500
+ expect(h.logs.error.join('\n')).toMatch(/dump put failed/)
501
+ expect(h.logs.warn.join('\n')).toMatch(/manifest/i)
502
+ expect(h.logs.warn.join('\n')).toMatch(/del also failed/)
503
+ })
504
+
505
+ it('prunes relative to the run start, not to the post-dump clock', async () => {
506
+ // The clock advances one day between start and prune (a slow dump); a
507
+ // backup exactly 30 days old at start must survive.
508
+ const start = new Date('2026-09-18T03:30:00.000Z')
509
+ let calls = 0
510
+ const h = harness(uploadEnv(), cwd)
511
+ h.deps.now = () => (calls++ === 0 ? start : new Date('2026-09-19T03:30:00.000Z'))
512
+ h.fakeBlob.seed('backups/db/2026-08-19T033000Z.dump.enc', 'exactly 30 days at start')
513
+
514
+ expect(await runDbBackup({ out, upload: true, json: true }, h.deps)).toBe(0)
515
+ expect(lastJson(h.stdout).pruned).toEqual([])
516
+ expect(h.fakeBlob.objects.has('backups/db/2026-08-19T033000Z.dump.enc')).toBe(true)
517
+ })
518
+ })
519
+
520
+ describe('commander wiring', () => {
521
+ it('registers db:backup, parses options and sets process.exitCode', async () => {
522
+ const h = harness(baseEnv(), cwd)
523
+ const program = new Command()
524
+ registerDbBackupCommand(program, h.deps)
525
+ await program.parseAsync(['node', 'prenta', 'db:backup', '--out', out, '--json'])
526
+ expect(process.exitCode ?? 0).toBe(0)
527
+ expect(lastJson(h.stdout).stamp).toBe('2026-09-18T033000Z')
528
+
529
+ const failing = harness({ BACKUP_ENCRYPTION_KEY: KEY }, cwd)
530
+ const program2 = new Command()
531
+ registerDbBackupCommand(program2, failing.deps)
532
+ await program2.parseAsync(['node', 'prenta', 'db:backup', '--out', out])
533
+ expect(process.exitCode).toBe(2)
534
+ process.exitCode = 0
535
+ })
536
+
537
+ it('parses --retention-days as a number', async () => {
538
+ const h = harness({ ...baseEnv(), BLOB_READ_WRITE_TOKEN: 't' }, cwd)
539
+ h.fakeBlob.seed('backups/db/2026-09-01T033000Z.dump.enc', 'x')
540
+ const program = new Command()
541
+ registerDbBackupCommand(program, h.deps)
542
+ await program.parseAsync([
543
+ 'node',
544
+ 'prenta',
545
+ 'db:backup',
546
+ '--out',
547
+ out,
548
+ '--upload',
549
+ '--retention-days',
550
+ '10',
551
+ '--json',
552
+ ])
553
+ expect(lastJson(h.stdout).pruned).toEqual(['backups/db/2026-09-01T033000Z.dump.enc'])
554
+ process.exitCode = 0
555
+ })
556
+ })
557
+ })