@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,784 @@
1
+ import { Command } from 'commander'
2
+ import { mkdir, mkdtemp, readFile, rm, writeFile } from 'node:fs/promises'
3
+ import { tmpdir } from 'node:os'
4
+ import path from 'node:path'
5
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest'
6
+
7
+ import { encryptFile, parseBackupKey } from '../backup/crypto.js'
8
+ import { buildManifest, sha256File, type BackupManifest } from '../backup/manifest.js'
9
+ import {
10
+ type DbRestoreDeps,
11
+ type DbRestoreSummary,
12
+ registerDbRestoreCommand,
13
+ runDbRestore,
14
+ } from '../commands/db-restore.js'
15
+ import { createFakeBlob } from './fixtures/fake-blob.js'
16
+ import { createFakeSpawn, type ScriptResolver, versionScript } from './fixtures/fake-spawn.js'
17
+ import { FAKE_PASSWORD_1, FAKE_PASSWORD_2, pgUrl, TEST_BLOB_TOKEN } from './fixtures/pg-url.js'
18
+
19
+ const KEY = 'd'.repeat(64)
20
+ const PROD_URL = pgUrl({ password: FAKE_PASSWORD_1, database: 'prod', query: 'sslmode=require' })
21
+ const SCRATCH_URL = pgUrl({
22
+ password: FAKE_PASSWORD_2,
23
+ host: 'scratch.example.net',
24
+ database: 'scratch_db',
25
+ })
26
+ const SCRATCH_URL_SAFE = pgUrl({ host: 'scratch.example.net', database: 'scratch_db' })
27
+ const FAKE_DUMP = 'PGDMP-fake-custom-format-bytes'
28
+ const STAMP = '2026-09-18T033000Z'
29
+
30
+ interface Harness {
31
+ deps: DbRestoreDeps
32
+ calls: ReturnType<typeof createFakeSpawn>['calls']
33
+ fakeBlob: ReturnType<typeof createFakeBlob>
34
+ logs: { info: string[]; warn: string[]; error: string[]; success: string[] }
35
+ stdout: string[]
36
+ prompts: string[]
37
+ }
38
+
39
+ function scripts(overrides: Partial<Record<string, ScriptResolver>> = {}): ScriptResolver {
40
+ return (call) => {
41
+ const custom = overrides[call.command]
42
+ if (custom) return custom(call)
43
+ if (call.args[0] === '--version') return versionScript(call.command, '17.4')
44
+ switch (call.command) {
45
+ case 'pg_restore':
46
+ return { code: 0 }
47
+ case 'psql':
48
+ return { code: 0, stdout: 'public\tprenta_documents\t118\npublic\tprenta_users\t3\n' }
49
+ default:
50
+ return { code: 1, stderr: `unexpected command ${call.command}` }
51
+ }
52
+ }
53
+ }
54
+
55
+ function harness(
56
+ env: NodeJS.ProcessEnv,
57
+ cwd: string,
58
+ opts: {
59
+ scripts?: ScriptResolver
60
+ answers?: string[]
61
+ interactive?: boolean
62
+ } = {},
63
+ ): Harness {
64
+ const { spawn, calls } = createFakeSpawn(opts.scripts ?? scripts())
65
+ const fakeBlob = createFakeBlob({ pageSize: 50 })
66
+ const logs = {
67
+ info: [] as string[],
68
+ warn: [] as string[],
69
+ error: [] as string[],
70
+ success: [] as string[],
71
+ }
72
+ const stdout: string[] = []
73
+ const prompts: string[] = []
74
+ const answers = [...(opts.answers ?? [])]
75
+ const deps: DbRestoreDeps = {
76
+ spawnImpl: spawn,
77
+ blobModule: fakeBlob.module,
78
+ env,
79
+ cwd,
80
+ now: () => new Date('2026-09-19T10:00:00.000Z'),
81
+ log: {
82
+ info: (m) => logs.info.push(m),
83
+ warn: (m) => logs.warn.push(m),
84
+ error: (m) => logs.error.push(m),
85
+ success: (m) => logs.success.push(m),
86
+ },
87
+ print: (line) => stdout.push(line),
88
+ interactive: opts.interactive ?? true,
89
+ prompt: async (question) => {
90
+ prompts.push(question)
91
+ return answers.shift() ?? ''
92
+ },
93
+ }
94
+ return { deps, calls, fakeBlob, logs, stdout, prompts }
95
+ }
96
+
97
+ async function makeBackup(
98
+ dir: string,
99
+ stamp = STAMP,
100
+ overrides: Partial<BackupManifest> = {},
101
+ ): Promise<{ dumpPath: string; manifestPath: string; manifest: BackupManifest }> {
102
+ const raw = path.join(dir, `${stamp}.raw`)
103
+ await writeFile(raw, FAKE_DUMP)
104
+ const dumpPath = path.join(dir, `${stamp}.dump.enc`)
105
+ await encryptFile(raw, dumpPath, parseBackupKey(KEY))
106
+ await rm(raw)
107
+ const manifest: BackupManifest = {
108
+ ...buildManifest({
109
+ createdAt: new Date('2026-09-18T03:30:00.000Z'),
110
+ databaseUrl: PROD_URL,
111
+ pgDumpVersion: '17.4',
112
+ sizeBytes: (await readFile(dumpPath)).length,
113
+ sha256: await sha256File(dumpPath),
114
+ tables: [
115
+ { schema: 'public', name: 'prenta_documents', rows: 120 },
116
+ { schema: 'public', name: 'prenta_users', rows: 3 },
117
+ ],
118
+ }),
119
+ ...overrides,
120
+ }
121
+ const manifestPath = path.join(dir, `${stamp}.manifest.json`)
122
+ await writeFile(manifestPath, JSON.stringify(manifest))
123
+ return { dumpPath, manifestPath, manifest }
124
+ }
125
+
126
+ /** Seed an encrypted dump + manifest pair for `stamp` into the harness's fake Blob store. */
127
+ async function seedBlob(h: Harness, stamp: string, body = FAKE_DUMP): Promise<void> {
128
+ const dir = await mkdtemp(path.join(tmpdir(), 'prenta-db-restore-seed-'))
129
+ try {
130
+ const raw = path.join(dir, 'raw')
131
+ await writeFile(raw, body)
132
+ const enc = path.join(dir, 'enc')
133
+ await encryptFile(raw, enc, parseBackupKey(KEY))
134
+ const bytes = await readFile(enc)
135
+ const manifest = buildManifest({
136
+ createdAt: new Date('2026-09-18T03:30:00.000Z'),
137
+ databaseUrl: PROD_URL,
138
+ pgDumpVersion: '17.4',
139
+ sizeBytes: bytes.length,
140
+ sha256: await sha256File(enc),
141
+ tables: [{ schema: 'public', name: 'prenta_documents', rows: 120 }],
142
+ })
143
+ h.fakeBlob.seed(`backups/db/${stamp}.dump.enc`, bytes)
144
+ h.fakeBlob.seed(`backups/db/${stamp}.manifest.json`, JSON.stringify({ ...manifest, stamp }))
145
+ } finally {
146
+ await rm(dir, { recursive: true, force: true })
147
+ }
148
+ }
149
+
150
+ function lastJson(stdout: string[]): DbRestoreSummary {
151
+ return JSON.parse(stdout[stdout.length - 1]!) as DbRestoreSummary
152
+ }
153
+
154
+ describe('prenta db:restore', () => {
155
+ let cwd: string
156
+ let backups: string
157
+
158
+ beforeEach(async () => {
159
+ cwd = await mkdtemp(path.join(tmpdir(), 'prenta-db-restore-cwd-'))
160
+ backups = await mkdtemp(path.join(tmpdir(), 'prenta-db-restore-src-'))
161
+ })
162
+
163
+ afterEach(async () => {
164
+ await rm(cwd, { recursive: true, force: true })
165
+ await rm(backups, { recursive: true, force: true })
166
+ })
167
+
168
+ const env = (): NodeJS.ProcessEnv => ({
169
+ DIRECT_DATABASE_URL: PROD_URL,
170
+ DATABASE_URL: PROD_URL,
171
+ BACKUP_ENCRYPTION_KEY: KEY,
172
+ BLOB_READ_WRITE_TOKEN: TEST_BLOB_TOKEN,
173
+ })
174
+
175
+ describe('preconditions (exit 2)', () => {
176
+ it('requires --target and never defaults to the env database', async () => {
177
+ const { dumpPath } = await makeBackup(backups)
178
+ const h = harness(env(), cwd)
179
+ expect(await runDbRestore(dumpPath, { yes: true }, h.deps)).toBe(2)
180
+ expect(h.logs.error.join('\n')).toMatch(/--target/)
181
+ expect(
182
+ h.calls.filter((c) => c.command === 'pg_restore' && c.args[0] !== '--version'),
183
+ ).toHaveLength(0)
184
+ })
185
+
186
+ it('rejects a malformed --target', async () => {
187
+ const { dumpPath } = await makeBackup(backups)
188
+ const h = harness(env(), cwd)
189
+ expect(await runDbRestore(dumpPath, { target: 'mysql://nope', yes: true }, h.deps)).toBe(2)
190
+ })
191
+
192
+ it('rejects a --target whose path names no database (empty or "/") before any download', async () => {
193
+ for (const database of [null, ''] as const) {
194
+ const target = pgUrl({ password: FAKE_PASSWORD_2, host: 'scratch.example.net', database })
195
+ const run = harness(env(), cwd)
196
+ await seedBlob(run, STAMP)
197
+ expect(await runDbRestore('latest', { target, yes: true }, run.deps), target).toBe(2)
198
+ expect(run.logs.error.join('\n'), target).toMatch(/--target must name a database/i)
199
+ expect(run.logs.error.join('\n'), target).toMatch(/\/<database>/)
200
+ expect(
201
+ run.fakeBlob.calls.filter((c) => c.op === 'get'),
202
+ target,
203
+ ).toHaveLength(0)
204
+ }
205
+ })
206
+
207
+ it('warns when --target carries a password on argv and recommends PGPASSWORD instead', async () => {
208
+ const { dumpPath } = await makeBackup(backups)
209
+ const h = harness(env(), cwd)
210
+ expect(await runDbRestore(dumpPath, { target: SCRATCH_URL, yes: true }, h.deps)).toBe(0)
211
+ const warning = h.logs.warn.join('\n')
212
+ expect(warning).toMatch(/password/i)
213
+ expect(warning).toMatch(/PGPASSWORD/)
214
+ expect(warning).not.toContain(FAKE_PASSWORD_2)
215
+
216
+ // A password-free target with PGPASSWORD set out of band: no warning, and the
217
+ // env password reaches pg_restore untouched.
218
+ const quiet = harness({ ...env(), PGPASSWORD: FAKE_PASSWORD_2 }, cwd)
219
+ expect(
220
+ await runDbRestore(dumpPath, { target: SCRATCH_URL_SAFE, yes: true }, quiet.deps),
221
+ ).toBe(0)
222
+ expect(quiet.logs.warn.join('\n')).not.toMatch(/PGPASSWORD/)
223
+ const restore = quiet.calls.find(
224
+ (c) => c.command === 'pg_restore' && c.args[0] !== '--version',
225
+ )!
226
+ expect(restore.args).toContain(`--dbname=${SCRATCH_URL_SAFE}`)
227
+ expect(restore.options.env?.PGPASSWORD).toBe(FAKE_PASSWORD_2)
228
+ })
229
+
230
+ it('requires BACKUP_ENCRYPTION_KEY', async () => {
231
+ const { dumpPath } = await makeBackup(backups)
232
+ const h = harness({ ...env(), BACKUP_ENCRYPTION_KEY: undefined }, cwd)
233
+ expect(await runDbRestore(dumpPath, { target: SCRATCH_URL, yes: true }, h.deps)).toBe(2)
234
+ expect(h.logs.error.join('\n')).toMatch(/BACKUP_ENCRYPTION_KEY/)
235
+ })
236
+
237
+ it('requires pg_restore >= 17', async () => {
238
+ const { dumpPath } = await makeBackup(backups)
239
+ const h = harness(env(), cwd, {
240
+ scripts: scripts({ pg_restore: () => versionScript('pg_restore', '15.1') }),
241
+ })
242
+ expect(await runDbRestore(dumpPath, { target: SCRATCH_URL, yes: true }, h.deps)).toBe(2)
243
+ expect(h.logs.error.join('\n')).toMatch(/15\.1/)
244
+ })
245
+
246
+ it('requires Blob credentials (token or OIDC pair) for blob sources, latest and --list', async () => {
247
+ const h = harness({ ...env(), BLOB_READ_WRITE_TOKEN: undefined }, cwd)
248
+ expect(await runDbRestore('latest', { target: SCRATCH_URL, yes: true }, h.deps)).toBe(2)
249
+ expect(await runDbRestore(undefined, { list: true }, h.deps)).toBe(2)
250
+ const errors = h.logs.error.join('\n')
251
+ expect(errors).toMatch(/BLOB_READ_WRITE_TOKEN/)
252
+ expect(errors).toMatch(/VERCEL_OIDC_TOKEN/)
253
+ expect(errors).toMatch(/BLOB_STORE_ID/)
254
+ })
255
+
256
+ it('OIDC mode (VERCEL_OIDC_TOKEN + BLOB_STORE_ID) lists and restores without passing a token', async () => {
257
+ const oidcEnv = {
258
+ ...env(),
259
+ BLOB_READ_WRITE_TOKEN: undefined,
260
+ VERCEL_OIDC_TOKEN: ['fake', 'oidc', 'jwt'].join('.'),
261
+ BLOB_STORE_ID: 'store_123',
262
+ }
263
+ const h = harness(oidcEnv, cwd)
264
+ await seedBlob(h, STAMP)
265
+ expect(await runDbRestore(undefined, { list: true, json: true }, h.deps)).toBe(0)
266
+ expect(
267
+ await runDbRestore('latest', { target: SCRATCH_URL, yes: true, json: true }, h.deps),
268
+ ).toBe(0)
269
+ expect(lastJson(h.stdout).source).toBe(`backups/db/${STAMP}.dump.enc`)
270
+ const ops = h.fakeBlob.calls.map((c) => c.op)
271
+ expect(ops).toEqual(expect.arrayContaining(['list', 'get']))
272
+ for (const call of h.fakeBlob.calls) {
273
+ expect(Object.keys(call.args[call.args.length - 1] as object), call.op).not.toContain(
274
+ 'token',
275
+ )
276
+ }
277
+
278
+ const token = harness(env(), cwd)
279
+ await seedBlob(token, STAMP)
280
+ expect(await runDbRestore('latest', { target: SCRATCH_URL, yes: true }, token.deps)).toBe(0)
281
+ for (const call of token.fakeBlob.calls) {
282
+ expect(call.args[call.args.length - 1], call.op).toMatchObject({ token: TEST_BLOB_TOKEN })
283
+ }
284
+ })
285
+ })
286
+
287
+ describe('production-target refusal', () => {
288
+ it('refuses when --target is the env database, even with --yes', async () => {
289
+ const { dumpPath } = await makeBackup(backups)
290
+ const h = harness(env(), cwd)
291
+ const sameDbDifferentPassword = pgUrl({
292
+ password: 'password',
293
+ host: 'DB.EXAMPLE.NET',
294
+ database: 'prod/',
295
+ })
296
+ expect(
297
+ await runDbRestore(dumpPath, { target: sameDbDifferentPassword, yes: true }, h.deps),
298
+ ).toBe(2)
299
+ expect(h.logs.error.join('\n')).toMatch(/--i-understand-this-overwrites-production/)
300
+ expect(h.prompts).toHaveLength(0)
301
+ expect(
302
+ h.calls.filter((c) => c.command === 'pg_restore' && c.args[0] !== '--version'),
303
+ ).toHaveLength(0)
304
+ })
305
+
306
+ it('Prisma Postgres: a fresh database (different user, same host + db) restores with --yes', async () => {
307
+ // Real shape: every database in a Prisma Postgres project shares one
308
+ // host and the `postgres` database name; only the username differs.
309
+ const prodDirect = pgUrl({
310
+ user: 'a1b2c3d4e5f6',
311
+ password: 'password',
312
+ query: 'sslmode=require',
313
+ })
314
+ const scratchDirect = pgUrl({
315
+ user: 'f6e5d4c3b2a1',
316
+ password: 'password',
317
+ query: 'sslmode=require',
318
+ })
319
+ const { dumpPath } = await makeBackup(backups)
320
+ const h = harness(
321
+ { ...env(), DIRECT_DATABASE_URL: prodDirect, DATABASE_URL: prodDirect },
322
+ cwd,
323
+ { interactive: false },
324
+ )
325
+ expect(await runDbRestore(dumpPath, { target: scratchDirect, yes: true }, h.deps)).toBe(0)
326
+ expect(h.prompts).toHaveLength(0)
327
+ expect(h.calls.some((c) => c.command === 'pg_restore' && c.args[0] !== '--version')).toBe(
328
+ true,
329
+ )
330
+
331
+ // …while the pooled string of the production database is still caught.
332
+ const pooled = pgUrl({
333
+ user: 'a1b2c3d4e5f6',
334
+ password: 'password',
335
+ host: 'pooled.db.example.net',
336
+ })
337
+ const refused = harness({ ...env(), DIRECT_DATABASE_URL: prodDirect }, cwd)
338
+ expect(await runDbRestore(dumpPath, { target: pooled, yes: true }, refused.deps)).toBe(2)
339
+ expect(refused.logs.error.join('\n')).toMatch(/--i-understand-this-overwrites-production/)
340
+ })
341
+
342
+ it('warns that the guard is blind when an env URL cannot be parsed and requires the flag', async () => {
343
+ const { dumpPath } = await makeBackup(backups)
344
+ const secretQuery = ['fake', 'accelerate', 'key'].join('-')
345
+ const accelerate = `prisma+postgres://accelerate.prisma-data.net/?api_key=${secretQuery}`
346
+ const blind = harness(
347
+ { ...env(), DATABASE_URL: accelerate, DIRECT_DATABASE_URL: undefined },
348
+ cwd,
349
+ )
350
+ expect(await runDbRestore(dumpPath, { target: SCRATCH_URL, yes: true }, blind.deps)).toBe(2)
351
+ expect(blind.logs.warn.join('\n')).toMatch(/DATABASE_URL/)
352
+ expect(blind.logs.warn.join('\n')).toMatch(/cannot (be compared|compare)/i)
353
+ expect(blind.logs.error.join('\n')).toMatch(/--i-understand-this-overwrites-production/)
354
+ expect(blind.logs.warn.join('\n')).not.toContain(secretQuery)
355
+ expect(blind.calls.some((c) => c.command === 'pg_restore' && c.args[0] !== '--version')).toBe(
356
+ false,
357
+ )
358
+
359
+ const overridden = harness(
360
+ { ...env(), DATABASE_URL: accelerate, DIRECT_DATABASE_URL: undefined },
361
+ cwd,
362
+ )
363
+ expect(
364
+ await runDbRestore(
365
+ dumpPath,
366
+ { target: SCRATCH_URL, yes: true, iUnderstandThisOverwritesProduction: true },
367
+ overridden.deps,
368
+ ),
369
+ ).toBe(0)
370
+ expect(overridden.logs.warn.join('\n')).toMatch(/DATABASE_URL/)
371
+ })
372
+
373
+ it('is not blind when DIRECT_DATABASE_URL parses even though DATABASE_URL (Accelerate) does not', async () => {
374
+ const { dumpPath } = await makeBackup(backups)
375
+ const secretQuery = ['fake', 'accelerate', 'key'].join('-')
376
+ const accelerate = `prisma+postgres://accelerate.prisma-data.net/?api_key=${secretQuery}`
377
+ const mixedEnv = { ...env(), DATABASE_URL: accelerate, DIRECT_DATABASE_URL: PROD_URL }
378
+
379
+ // Scratch target: compared with DIRECT_DATABASE_URL normally, no flag needed.
380
+ const scratch = harness(mixedEnv, cwd)
381
+ expect(await runDbRestore(dumpPath, { target: SCRATCH_URL, yes: true }, scratch.deps)).toBe(0)
382
+ expect(scratch.logs.error).toEqual([])
383
+ const warnings = scratch.logs.warn.join('\n')
384
+ expect(warnings).toMatch(/DATABASE_URL/)
385
+ expect(warnings).not.toMatch(/blind/i)
386
+ expect(warnings).not.toContain(secretQuery)
387
+
388
+ // Production target: still caught via the parseable DIRECT_DATABASE_URL.
389
+ const prod = harness(mixedEnv, cwd)
390
+ expect(await runDbRestore(dumpPath, { target: PROD_URL, yes: true }, prod.deps)).toBe(2)
391
+ expect(prod.logs.error.join('\n')).toMatch(/--i-understand-this-overwrites-production/)
392
+ expect(prod.logs.error.join('\n')).not.toMatch(/blind/i)
393
+ })
394
+
395
+ it('compares the typed name against the normalized database name and never accepts an empty answer', async () => {
396
+ const { dumpPath } = await makeBackup(backups)
397
+ // Production URL with a trailing slash: the guard classifies it as `prod`
398
+ // (same normalization as `databaseIdentity`), so `prod` is what confirms.
399
+ const trailingSlash = pgUrl({ password: FAKE_PASSWORD_1, database: 'prod/' })
400
+
401
+ const enter = harness(env(), cwd, { answers: [''] })
402
+ expect(
403
+ await runDbRestore(
404
+ dumpPath,
405
+ { target: trailingSlash, yes: true, iUnderstandThisOverwritesProduction: true },
406
+ enter.deps,
407
+ ),
408
+ ).toBe(2)
409
+ expect(enter.prompts[0]).toMatch(/"prod"/)
410
+ expect(enter.logs.error.join('\n')).toMatch(/did not match/i)
411
+ expect(
412
+ enter.calls.filter((c) => c.command === 'pg_restore' && c.args[0] !== '--version'),
413
+ ).toHaveLength(0)
414
+
415
+ const slash = harness(env(), cwd, { answers: ['prod/'] })
416
+ expect(
417
+ await runDbRestore(
418
+ dumpPath,
419
+ { target: trailingSlash, yes: true, iUnderstandThisOverwritesProduction: true },
420
+ slash.deps,
421
+ ),
422
+ ).toBe(2)
423
+
424
+ const typed = harness(env(), cwd, { answers: ['prod'] })
425
+ expect(
426
+ await runDbRestore(
427
+ dumpPath,
428
+ { target: trailingSlash, yes: true, iUnderstandThisOverwritesProduction: true },
429
+ typed.deps,
430
+ ),
431
+ ).toBe(0)
432
+ })
433
+
434
+ it('with the flag, still requires typing the database name — --yes does not skip it', async () => {
435
+ const { dumpPath } = await makeBackup(backups)
436
+ const wrong = harness(env(), cwd, { answers: ['nope'] })
437
+ expect(
438
+ await runDbRestore(
439
+ dumpPath,
440
+ { target: PROD_URL, yes: true, iUnderstandThisOverwritesProduction: true },
441
+ wrong.deps,
442
+ ),
443
+ ).toBe(2)
444
+ expect(wrong.prompts).toHaveLength(1)
445
+ expect(wrong.prompts[0]).toMatch(/prod/)
446
+ expect(wrong.logs.error.join('\n')).toMatch(/did not match/i)
447
+ expect(
448
+ wrong.calls.filter((c) => c.command === 'pg_restore' && c.args[0] !== '--version'),
449
+ ).toHaveLength(0)
450
+
451
+ const right = harness(env(), cwd, { answers: ['prod'] })
452
+ expect(
453
+ await runDbRestore(
454
+ dumpPath,
455
+ { target: PROD_URL, yes: true, iUnderstandThisOverwritesProduction: true },
456
+ right.deps,
457
+ ),
458
+ ).toBe(0)
459
+ expect(right.prompts).toHaveLength(1)
460
+ expect(right.calls.some((c) => c.command === 'pg_restore' && c.args[0] !== '--version')).toBe(
461
+ true,
462
+ )
463
+ })
464
+
465
+ it('cannot be satisfied non-interactively', async () => {
466
+ const { dumpPath } = await makeBackup(backups)
467
+ const h = harness(env(), cwd, { interactive: false, answers: ['prod'] })
468
+ expect(
469
+ await runDbRestore(
470
+ dumpPath,
471
+ { target: PROD_URL, yes: true, iUnderstandThisOverwritesProduction: true },
472
+ h.deps,
473
+ ),
474
+ ).toBe(2)
475
+ expect(h.prompts).toHaveLength(0)
476
+ })
477
+ })
478
+
479
+ describe('local source', () => {
480
+ it('verifies sha256, decrypts, runs pg_restore with the exact argv and prints counts', async () => {
481
+ const { dumpPath, manifestPath } = await makeBackup(backups)
482
+ const h = harness(env(), cwd)
483
+ const code = await runDbRestore(
484
+ dumpPath,
485
+ { target: SCRATCH_URL, yes: true, json: true },
486
+ h.deps,
487
+ )
488
+ expect(code).toBe(0)
489
+
490
+ const restore = h.calls.find((c) => c.command === 'pg_restore' && c.args[0] !== '--version')!
491
+ expect(restore.args.slice(0, 8)).toEqual([
492
+ '--clean',
493
+ '--if-exists',
494
+ '--no-owner',
495
+ '--no-privileges',
496
+ '--no-comments',
497
+ '--single-transaction',
498
+ '--exit-on-error',
499
+ `--dbname=${SCRATCH_URL_SAFE}`,
500
+ ])
501
+ expect(restore.args).toHaveLength(9)
502
+ expect(restore.args[8]).toMatch(/\.dump$/)
503
+ expect(restore.args.join(' ')).not.toContain(FAKE_PASSWORD_2)
504
+ expect(restore.options.env?.PGPASSWORD).toBe(FAKE_PASSWORD_2)
505
+
506
+ const count = h.calls.find((c) => c.command === 'psql' && c.args[0] !== '--version')!
507
+ expect(count.args).toContain(`--dbname=${SCRATCH_URL_SAFE}`)
508
+ expect(count.args.find((a) => a.startsWith('--command='))).toContain(
509
+ '"public"."prenta_documents"',
510
+ )
511
+
512
+ const summary = lastJson(h.stdout)
513
+ expect(summary).toMatchObject({
514
+ source: dumpPath,
515
+ manifestPath,
516
+ stamp: STAMP,
517
+ sha256Verified: true,
518
+ tables: [
519
+ { schema: 'public', name: 'prenta_documents', estimate: 120, restored: 118 },
520
+ { schema: 'public', name: 'prenta_users', estimate: 3, restored: 3 },
521
+ ],
522
+ })
523
+ expect(summary.durationMs).toBeGreaterThanOrEqual(0)
524
+ expect(h.logs.info.join('\n')).toMatch(/prisma migrate status/)
525
+ })
526
+
527
+ it('asks for confirmation without --yes and aborts on anything but "yes"', async () => {
528
+ const { dumpPath } = await makeBackup(backups)
529
+ const h = harness(env(), cwd, { answers: ['no'] })
530
+ expect(await runDbRestore(dumpPath, { target: SCRATCH_URL }, h.deps)).toBe(2)
531
+ expect(h.prompts).toHaveLength(1)
532
+ expect(h.calls.some((c) => c.command === 'pg_restore' && c.args[0] !== '--version')).toBe(
533
+ false,
534
+ )
535
+
536
+ const ok = harness(env(), cwd, { answers: ['yes'] })
537
+ expect(await runDbRestore(dumpPath, { target: SCRATCH_URL }, ok.deps)).toBe(0)
538
+ })
539
+
540
+ it('refuses without --yes when not interactive', async () => {
541
+ const { dumpPath } = await makeBackup(backups)
542
+ const h = harness(env(), cwd, { interactive: false })
543
+ expect(await runDbRestore(dumpPath, { target: SCRATCH_URL }, h.deps)).toBe(2)
544
+ expect(h.logs.error.join('\n')).toMatch(/--yes/)
545
+ })
546
+
547
+ it('fails (exit 1) on a sha256 mismatch before decrypting or restoring', async () => {
548
+ const { dumpPath } = await makeBackup(backups, STAMP, { sha256: '0'.repeat(64) })
549
+ const h = harness(env(), cwd)
550
+ expect(await runDbRestore(dumpPath, { target: SCRATCH_URL, yes: true }, h.deps)).toBe(1)
551
+ expect(h.logs.error.join('\n')).toMatch(/sha256/i)
552
+ expect(h.calls.some((c) => c.command === 'pg_restore' && c.args[0] !== '--version')).toBe(
553
+ false,
554
+ )
555
+ })
556
+
557
+ it('fails (exit 1) when the key does not match the file', async () => {
558
+ const { dumpPath } = await makeBackup(backups)
559
+ const h = harness({ ...env(), BACKUP_ENCRYPTION_KEY: 'e'.repeat(64) }, cwd)
560
+ expect(await runDbRestore(dumpPath, { target: SCRATCH_URL, yes: true }, h.deps)).toBe(1)
561
+ expect(h.logs.error.join('\n')).toMatch(/authentication failed/i)
562
+ })
563
+
564
+ it('fails (exit 1) with redacted stderr when pg_restore fails', async () => {
565
+ const { dumpPath } = await makeBackup(backups)
566
+ const h = harness(env(), cwd, {
567
+ scripts: scripts({
568
+ pg_restore: (call) =>
569
+ call.args[0] === '--version'
570
+ ? versionScript('pg_restore', '17.4')
571
+ : { code: 1, stderr: `pg_restore: error: could not connect to ${SCRATCH_URL}` },
572
+ }),
573
+ })
574
+ expect(await runDbRestore(dumpPath, { target: SCRATCH_URL, yes: true }, h.deps)).toBe(1)
575
+ const errors = h.logs.error.join('\n')
576
+ expect(errors).toMatch(/pg_restore exited with code 1/)
577
+ expect(errors).not.toContain(FAKE_PASSWORD_2)
578
+ })
579
+
580
+ it('warns and skips verification when a local dump has no manifest', async () => {
581
+ const { dumpPath, manifestPath } = await makeBackup(backups)
582
+ await rm(manifestPath)
583
+ const h = harness(env(), cwd)
584
+ expect(
585
+ await runDbRestore(dumpPath, { target: SCRATCH_URL, yes: true, json: true }, h.deps),
586
+ ).toBe(0)
587
+ expect(h.logs.warn.join('\n')).toMatch(/manifest/i)
588
+ const summary = lastJson(h.stdout)
589
+ expect(summary.sha256Verified).toBe(false)
590
+ expect(summary.tables).toEqual([])
591
+ })
592
+ })
593
+
594
+ describe('blob sources', () => {
595
+ it('--list prints available backups newest first with stamps and sizes', async () => {
596
+ const h = harness(env(), cwd)
597
+ await seedBlob(h, '2026-09-16T033000Z')
598
+ await seedBlob(h, '2026-09-18T033000Z')
599
+ h.fakeBlob.seed('backups/db/2026-09-17T033000Z.dump.enc', 'no manifest, still listed')
600
+
601
+ expect(await runDbRestore(undefined, { list: true }, h.deps)).toBe(0)
602
+ const text = h.stdout.join('\n')
603
+ const i18 = text.indexOf('2026-09-18T033000Z')
604
+ const i17 = text.indexOf('2026-09-17T033000Z')
605
+ const i16 = text.indexOf('2026-09-16T033000Z')
606
+ expect(i18).toBeGreaterThanOrEqual(0)
607
+ expect(i18).toBeLessThan(i17)
608
+ expect(i17).toBeLessThan(i16)
609
+ expect(text).toMatch(/\d+ B|KB/)
610
+ expect(h.calls).toHaveLength(0)
611
+
612
+ const json = harness(env(), cwd)
613
+ await seedBlob(json, '2026-09-18T033000Z')
614
+ expect(await runDbRestore(undefined, { list: true, json: true }, json.deps)).toBe(0)
615
+ const parsed = JSON.parse(json.stdout[json.stdout.length - 1]!) as Array<{
616
+ stamp: string
617
+ pathname: string
618
+ size: number
619
+ }>
620
+ expect(parsed).toEqual([
621
+ expect.objectContaining({
622
+ stamp: '2026-09-18T033000Z',
623
+ pathname: 'backups/db/2026-09-18T033000Z.dump.enc',
624
+ }),
625
+ ])
626
+ })
627
+
628
+ it('restores a blob pathname: downloads dump + manifest, verifies, restores', async () => {
629
+ const h = harness(env(), cwd)
630
+ await seedBlob(h, STAMP)
631
+ const code = await runDbRestore(
632
+ `backups/db/${STAMP}.dump.enc`,
633
+ { target: SCRATCH_URL, yes: true, json: true },
634
+ h.deps,
635
+ )
636
+ expect(code).toBe(0)
637
+ const gets = h.fakeBlob.calls.filter((c) => c.op === 'get').map((c) => c.args[0])
638
+ expect(gets).toEqual([`backups/db/${STAMP}.dump.enc`, `backups/db/${STAMP}.manifest.json`])
639
+ const summary = lastJson(h.stdout)
640
+ expect(summary.source).toBe(`backups/db/${STAMP}.dump.enc`)
641
+ expect(summary.sha256Verified).toBe(true)
642
+ expect(summary.tables).toEqual([
643
+ { schema: 'public', name: 'prenta_documents', estimate: 120, restored: 118 },
644
+ ])
645
+ })
646
+
647
+ it('"latest" selects the newest stamp under the prefix', async () => {
648
+ const h = harness(env(), cwd)
649
+ await seedBlob(h, '2026-09-16T033000Z')
650
+ await seedBlob(h, '2026-09-18T033000Z')
651
+ await seedBlob(h, '2026-09-17T033000Z')
652
+ expect(
653
+ await runDbRestore('latest', { target: SCRATCH_URL, yes: true, json: true }, h.deps),
654
+ ).toBe(0)
655
+ expect(lastJson(h.stdout).source).toBe('backups/db/2026-09-18T033000Z.dump.enc')
656
+ })
657
+
658
+ it('honours --prefix for latest', async () => {
659
+ const h = harness(env(), cwd)
660
+ await seedBlob(h, '2026-09-18T033000Z')
661
+ h.fakeBlob.objects.clear()
662
+ const dir = await mkdtemp(path.join(tmpdir(), 'prenta-db-restore-prefix-'))
663
+ const raw = path.join(dir, 'raw')
664
+ await writeFile(raw, FAKE_DUMP)
665
+ const enc = path.join(dir, 'enc')
666
+ await encryptFile(raw, enc, parseBackupKey(KEY))
667
+ const bytes = await readFile(enc)
668
+ const manifest = buildManifest({
669
+ createdAt: new Date('2026-09-18T03:30:00.000Z'),
670
+ databaseUrl: PROD_URL,
671
+ pgDumpVersion: '17.4',
672
+ sizeBytes: bytes.length,
673
+ sha256: await sha256File(enc),
674
+ tables: [],
675
+ })
676
+ h.fakeBlob.seed('sites/acme/2026-09-18T033000Z.dump.enc', bytes)
677
+ h.fakeBlob.seed('sites/acme/2026-09-18T033000Z.manifest.json', JSON.stringify(manifest))
678
+ await rm(dir, { recursive: true, force: true })
679
+
680
+ expect(
681
+ await runDbRestore(
682
+ 'latest',
683
+ { target: SCRATCH_URL, yes: true, json: true, prefix: 'sites/acme' },
684
+ h.deps,
685
+ ),
686
+ ).toBe(0)
687
+ expect(lastJson(h.stdout).source).toBe('sites/acme/2026-09-18T033000Z.dump.enc')
688
+ })
689
+
690
+ it('fails (exit 1) when a Blob dump has no manifest - unlike local files, where it only warns', async () => {
691
+ const h = harness(env(), cwd)
692
+ await seedBlob(h, STAMP)
693
+ h.fakeBlob.objects.delete(`backups/db/${STAMP}.manifest.json`)
694
+ expect(
695
+ await runDbRestore(
696
+ `backups/db/${STAMP}.dump.enc`,
697
+ { target: SCRATCH_URL, yes: true },
698
+ h.deps,
699
+ ),
700
+ ).toBe(1)
701
+ expect(h.logs.error.join('\n')).toMatch(/manifest/i)
702
+ expect(h.logs.error.join('\n')).toContain(`backups/db/${STAMP}.manifest.json`)
703
+ expect(h.calls.some((c) => c.command === 'pg_restore' && c.args[0] !== '--version')).toBe(
704
+ false,
705
+ )
706
+ })
707
+
708
+ it('says which interpretation won when <source> is both a local file and a Blob-looking pathname', async () => {
709
+ const h = harness(env(), cwd)
710
+ await seedBlob(h, STAMP)
711
+ const relative = `backups/db/${STAMP}.dump.enc`
712
+ const localDir = path.join(cwd, 'backups', 'db')
713
+ await mkdir(localDir, { recursive: true })
714
+ const { dumpPath } = await makeBackup(localDir)
715
+ expect(dumpPath).toBe(path.join(cwd, ...relative.split('/')))
716
+
717
+ expect(
718
+ await runDbRestore(relative, { target: SCRATCH_URL, yes: true, json: true }, h.deps),
719
+ ).toBe(0)
720
+ expect(h.logs.info.join('\n')).toMatch(/exists locally.*Blob/s)
721
+ expect(h.fakeBlob.calls.filter((c) => c.op === 'get')).toHaveLength(0)
722
+ expect(lastJson(h.stdout).source).toBe(dumpPath)
723
+ })
724
+
725
+ it('fails clearly when there are no backups for latest or the pathname is missing', async () => {
726
+ const h = harness(env(), cwd)
727
+ expect(await runDbRestore('latest', { target: SCRATCH_URL, yes: true }, h.deps)).toBe(1)
728
+ expect(h.logs.error.join('\n')).toMatch(/no backups/i)
729
+ expect(
730
+ await runDbRestore(
731
+ 'backups/db/2026-01-01T000000Z.dump.enc',
732
+ { target: SCRATCH_URL, yes: true },
733
+ h.deps,
734
+ ),
735
+ ).toBe(1)
736
+ expect(h.logs.error.join('\n')).toMatch(/not found/i)
737
+ })
738
+ })
739
+
740
+ describe('commander wiring', () => {
741
+ it('registers db:restore with <source>, --target and the safety flag', async () => {
742
+ const { dumpPath } = await makeBackup(backups)
743
+ const h = harness(env(), cwd)
744
+ const program = new Command()
745
+ registerDbRestoreCommand(program, h.deps)
746
+ await program.parseAsync([
747
+ 'node',
748
+ 'prenta',
749
+ 'db:restore',
750
+ dumpPath,
751
+ '--target',
752
+ SCRATCH_URL,
753
+ '--yes',
754
+ '--json',
755
+ ])
756
+ expect(process.exitCode ?? 0).toBe(0)
757
+ expect(lastJson(h.stdout).stamp).toBe(STAMP)
758
+
759
+ const refused = harness(env(), cwd)
760
+ const program2 = new Command()
761
+ registerDbRestoreCommand(program2, refused.deps)
762
+ await program2.parseAsync([
763
+ 'node',
764
+ 'prenta',
765
+ 'db:restore',
766
+ dumpPath,
767
+ '--target',
768
+ PROD_URL,
769
+ '--yes',
770
+ ])
771
+ expect(process.exitCode).toBe(2)
772
+ process.exitCode = 0
773
+ })
774
+
775
+ it('accepts --list without a source', async () => {
776
+ const h = harness(env(), cwd)
777
+ const program = new Command()
778
+ registerDbRestoreCommand(program, h.deps)
779
+ await program.parseAsync(['node', 'prenta', 'db:restore', '--list', '--json'])
780
+ expect(process.exitCode ?? 0).toBe(0)
781
+ expect(JSON.parse(h.stdout[h.stdout.length - 1]!)).toEqual([])
782
+ })
783
+ })
784
+ })