@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,542 @@
1
+ /**
2
+ * `prenta db:restore <source> --target <url>` — restore an encrypted backup
3
+ * produced by `db:backup` into an explicitly named database.
4
+ *
5
+ * `<source>` is a local `.dump.enc`, a Blob pathname
6
+ * (`backups/db/<stamp>.dump.enc`) or `latest`. The manifest sha256 is
7
+ * verified before decryption (a Blob dump without a manifest is refused;
8
+ * a local one only warns), and `pg_restore --clean --if-exists
9
+ * --single-transaction --exit-on-error` runs atomically against `--target`,
10
+ * which is required and never defaults to the env
11
+ * database. Restoring into the database named by DIRECT_DATABASE_URL /
12
+ * DATABASE_URL (same user + host + database name, see `databaseIdentity`)
13
+ * additionally requires `--i-understand-this-overwrites-production` and
14
+ * typing the database name at an interactive prompt — `--yes` does not
15
+ * bypass that. Each env URL is parsed on its own: an unparsable one
16
+ * (`prisma+postgres://…` Accelerate) is skipped with a warning, and only when
17
+ * neither parses is the guard blind, which requires the same flag to proceed.
18
+ * Afterwards the manifest's estimated row counts are compared with
19
+ * `count(*)` on the restored tables.
20
+ *
21
+ * `--target` must name a database in its path and may carry a password
22
+ * (DR ergonomics), but the command warns and recommends a password-free URL
23
+ * with `PGPASSWORD` set out of band — argv is visible to other processes.
24
+ *
25
+ * Exit codes: 0 ok · 1 download/verify/restore failed · 2 preconditions.
26
+ */
27
+ import { Command } from 'commander'
28
+ import { existsSync } from 'node:fs'
29
+ import { mkdtemp, readFile, rm } from 'node:fs/promises'
30
+ import { tmpdir } from 'node:os'
31
+ import { basename, join, resolve } from 'node:path'
32
+ import { createInterface } from 'node:readline/promises'
33
+ import { createBlobStore, DEFAULT_BACKUP_PREFIX, type BlobModule } from '../backup/blob-store.js'
34
+ import {
35
+ BLOB_AUTH_HINT,
36
+ databaseIdentity,
37
+ EXIT_FAILED,
38
+ EXIT_OK,
39
+ EXIT_PRECONDITION,
40
+ formatBytes,
41
+ formatDuration,
42
+ isPostgresUrl,
43
+ isSameDatabase,
44
+ namesDatabase,
45
+ resolveBlobAuth,
46
+ } from '../backup/common.js'
47
+ import { BackupKeyError, decryptFile, parseBackupKey } from '../backup/crypto.js'
48
+ import {
49
+ describeDatabase,
50
+ DUMP_EXTENSION,
51
+ manifestPathnameFor,
52
+ parseManifest,
53
+ parseStamp,
54
+ sha256File,
55
+ type BackupManifest,
56
+ } from '../backup/manifest.js'
57
+ import {
58
+ checkPgTool,
59
+ countTableRows,
60
+ nodeSpawn,
61
+ redactUrl,
62
+ runPgRestore,
63
+ type SpawnImpl,
64
+ } from '../backup/pg-tools.js'
65
+ import { loadProjectEnv } from '../utils/load-dotenv.js'
66
+ import { logger, type Logger } from '../utils/logger.js'
67
+
68
+ const MIN_PG_MAJOR = 17
69
+ export const PRODUCTION_FLAG = '--i-understand-this-overwrites-production'
70
+
71
+ export interface DbRestoreOptions {
72
+ target?: string
73
+ yes?: boolean
74
+ list?: boolean
75
+ json?: boolean
76
+ prefix?: string
77
+ iUnderstandThisOverwritesProduction?: boolean
78
+ }
79
+
80
+ export interface DbRestoreDeps {
81
+ spawnImpl: SpawnImpl
82
+ blobModule?: BlobModule
83
+ env: NodeJS.ProcessEnv
84
+ cwd: string
85
+ now: () => Date
86
+ log: Logger
87
+ print: (line: string) => void
88
+ /** Whether a human can answer prompts (stdin is a TTY). */
89
+ interactive: boolean
90
+ prompt: (question: string) => Promise<string>
91
+ }
92
+
93
+ export interface DbRestoreTableReport {
94
+ schema: string
95
+ name: string
96
+ estimate: number
97
+ restored: number | null
98
+ }
99
+
100
+ export interface DbRestoreSummary {
101
+ source: string
102
+ manifestPath: string | null
103
+ stamp: string | null
104
+ target: string
105
+ sha256Verified: boolean
106
+ tables: DbRestoreTableReport[]
107
+ durationMs: number
108
+ }
109
+
110
+ /** `{ token }` (read-write token) or `{}` (SDK resolves OIDC itself) — see `resolveBlobAuth`. */
111
+ type BlobAuth = NonNullable<ReturnType<typeof resolveBlobAuth>>
112
+
113
+ type ResolvedSource =
114
+ | { kind: 'local'; dumpPath: string; manifestPath: string | null; label: string }
115
+ | { kind: 'blob'; pathname: string; auth: BlobAuth; label: string }
116
+
117
+ async function listBackups(
118
+ opts: DbRestoreOptions,
119
+ deps: DbRestoreDeps,
120
+ auth: BlobAuth,
121
+ ): Promise<number> {
122
+ const store = createBlobStore({
123
+ ...auth,
124
+ prefix: opts.prefix ?? DEFAULT_BACKUP_PREFIX,
125
+ blobModule: deps.blobModule,
126
+ })
127
+ let dumps
128
+ try {
129
+ dumps = await store.dumps()
130
+ } catch (err) {
131
+ deps.log.error(`Could not list backups: ${err instanceof Error ? err.message : String(err)}`)
132
+ return EXIT_FAILED
133
+ }
134
+ if (opts.json) {
135
+ deps.print(
136
+ JSON.stringify(
137
+ dumps.map((d) => ({
138
+ stamp: d.stamp,
139
+ pathname: d.pathname,
140
+ size: d.size,
141
+ uploadedAt: d.uploadedAt.toISOString(),
142
+ })),
143
+ ),
144
+ )
145
+ return EXIT_OK
146
+ }
147
+ if (dumps.length === 0) {
148
+ deps.print(`No backups found under ${store.prefix}/.`)
149
+ return EXIT_OK
150
+ }
151
+ deps.print(`Backups under ${store.prefix}/ (newest first):`)
152
+ for (const d of dumps) {
153
+ deps.print(` ${d.stamp} ${formatBytes(d.size).padStart(10)} ${d.pathname}`)
154
+ }
155
+ deps.print(`Restore one with: prenta db:restore <pathname|latest> --target <url>`)
156
+ return EXIT_OK
157
+ }
158
+
159
+ /** `<prefix>/<stamp>.dump.enc` with a parseable stamp — what `--list` prints. */
160
+ function looksLikeBlobPathname(source: string, prefix: string): boolean {
161
+ const normalizedPrefix = prefix.replace(/^\/+|\/+$/g, '')
162
+ return (
163
+ source.startsWith(`${normalizedPrefix}/`) &&
164
+ source.endsWith(DUMP_EXTENSION) &&
165
+ parseStamp(source) !== null
166
+ )
167
+ }
168
+
169
+ function renderTable(rows: DbRestoreTableReport[]): string[] {
170
+ const name = (r: DbRestoreTableReport) => `${r.schema}.${r.name}`
171
+ const width = Math.max('table'.length, ...rows.map((r) => name(r).length))
172
+ const lines = [
173
+ `${'table'.padEnd(width)} ${'estimate'.padStart(10)} ${'restored'.padStart(10)} ${'delta'.padStart(8)}`,
174
+ ]
175
+ for (const r of rows) {
176
+ const restored = r.restored === null ? '?' : String(r.restored)
177
+ const delta = r.restored === null ? '?' : String(r.restored - r.estimate)
178
+ lines.push(
179
+ `${name(r).padEnd(width)} ${String(r.estimate).padStart(10)} ${restored.padStart(10)} ${delta.padStart(8)}`,
180
+ )
181
+ }
182
+ return lines
183
+ }
184
+
185
+ export async function runDbRestore(
186
+ source: string | undefined,
187
+ opts: DbRestoreOptions,
188
+ deps: DbRestoreDeps,
189
+ ): Promise<number> {
190
+ const started = Date.now()
191
+ const env = await loadProjectEnv(deps.cwd, deps.env)
192
+ const blobAuth = resolveBlobAuth(env)
193
+ const prefix = opts.prefix ?? DEFAULT_BACKUP_PREFIX
194
+
195
+ if (opts.list) {
196
+ if (!blobAuth) {
197
+ deps.log.error(`--list needs Vercel Blob credentials to read the store: ${BLOB_AUTH_HINT}.`)
198
+ return EXIT_PRECONDITION
199
+ }
200
+ return listBackups(opts, deps, blobAuth)
201
+ }
202
+
203
+ if (!source) {
204
+ deps.log.error(
205
+ 'Missing <source>: a local .dump.enc path, a Blob pathname (backups/db/<stamp>.dump.enc) or `latest`.',
206
+ )
207
+ return EXIT_PRECONDITION
208
+ }
209
+ if (!opts.target) {
210
+ deps.log.error(
211
+ '--target <url> is required. db:restore never defaults to the environment database.',
212
+ )
213
+ return EXIT_PRECONDITION
214
+ }
215
+ if (!isPostgresUrl(opts.target)) {
216
+ deps.log.error('--target must be a postgres:// or postgresql:// connection URL.')
217
+ return EXIT_PRECONDITION
218
+ }
219
+ if (!namesDatabase(opts.target)) {
220
+ deps.log.error(
221
+ `--target must name a database in its path (postgres://USER@HOST:5432/<database>); ${redactUrl(opts.target)} has none. Restoring into libpq's implicit default database is not allowed.`,
222
+ )
223
+ return EXIT_PRECONDITION
224
+ }
225
+ const target = opts.target
226
+ const targetIdentity = databaseIdentity(target)!
227
+ if (new URL(target).password) {
228
+ deps.log.warn(
229
+ 'The --target URL carries a password on the command line, where other processes and shell history can read it. Prefer a password-free URL (postgres://USER@HOST:5432/<database>) and set PGPASSWORD in the environment instead; pg_restore and psql honour it.',
230
+ )
231
+ }
232
+
233
+ let key: Buffer
234
+ try {
235
+ key = parseBackupKey(env.BACKUP_ENCRYPTION_KEY)
236
+ } catch (err) {
237
+ deps.log.error(err instanceof BackupKeyError ? err.message : String(err))
238
+ return EXIT_PRECONDITION
239
+ }
240
+
241
+ // Production guard, part 1 (flag). Cheap; fail before any download. Each env
242
+ // URL is judged on its own: the guard is blind only when none of them parses.
243
+ const envUrls: Array<{ name: 'DIRECT_DATABASE_URL' | 'DATABASE_URL'; url: string }> = []
244
+ for (const name of ['DIRECT_DATABASE_URL', 'DATABASE_URL'] as const) {
245
+ const url = env[name]
246
+ if (url) envUrls.push({ name, url })
247
+ }
248
+ const comparable = envUrls.filter((e) => databaseIdentity(e.url) !== null)
249
+ const unparsable = envUrls.filter((e) => databaseIdentity(e.url) === null)
250
+ if (unparsable.length > 0 && comparable.length === 0) {
251
+ // e.g. `prisma+postgres://accelerate…?api_key=…` — never echo the value.
252
+ deps.log.warn(
253
+ `${unparsable.map((e) => e.name).join(' and ')} is not a parseable postgres:// URL, so --target cannot be compared with it: the production guard is blind for this run.`,
254
+ )
255
+ if (!opts.iUnderstandThisOverwritesProduction) {
256
+ deps.log.error(
257
+ `Refusing to restore while the production guard is blind. Point ${unparsable[0]!.name} at a postgres:// URL, or pass ${PRODUCTION_FLAG} to proceed anyway.`,
258
+ )
259
+ return EXIT_PRECONDITION
260
+ }
261
+ } else if (unparsable.length > 0) {
262
+ deps.log.warn(
263
+ `${unparsable.map((e) => e.name).join(' and ')} is not a parseable postgres:// URL and is skipped; --target is compared with ${comparable.map((e) => e.name).join(' and ')} only.`,
264
+ )
265
+ }
266
+ const targetsProduction = comparable.some((e) => isSameDatabase(e.url, target))
267
+ if (targetsProduction && !opts.iUnderstandThisOverwritesProduction) {
268
+ deps.log.error(
269
+ `--target names the same database as DIRECT_DATABASE_URL/DATABASE_URL (${redactUrl(target)}). ` +
270
+ `Restore into a fresh database instead, or pass ${PRODUCTION_FLAG} and confirm the database name at the prompt (--yes does not skip this).`,
271
+ )
272
+ return EXIT_PRECONDITION
273
+ }
274
+ if (targetsProduction && !deps.interactive) {
275
+ deps.log.error(
276
+ `${PRODUCTION_FLAG} requires an interactive terminal to type the database name; refusing to overwrite production non-interactively.`,
277
+ )
278
+ return EXIT_PRECONDITION
279
+ }
280
+ if (!targetsProduction && !opts.yes && !deps.interactive) {
281
+ deps.log.error('Not an interactive terminal; pass --yes to confirm the restore.')
282
+ return EXIT_PRECONDITION
283
+ }
284
+
285
+ // Source classification.
286
+ let resolved: ResolvedSource
287
+ const localCandidate = resolve(deps.cwd, source)
288
+ if (source !== 'latest' && existsSync(localCandidate)) {
289
+ if (looksLikeBlobPathname(source, prefix)) {
290
+ deps.log.info(
291
+ `${source} exists locally and also looks like a Blob pathname under ${prefix}/; using the local file. Run from another directory to restore the Blob copy.`,
292
+ )
293
+ }
294
+ const manifestPath = manifestPathnameFor(localCandidate)
295
+ resolved = {
296
+ kind: 'local',
297
+ dumpPath: localCandidate,
298
+ manifestPath: existsSync(manifestPath) ? manifestPath : null,
299
+ label: localCandidate,
300
+ }
301
+ } else {
302
+ if (!blobAuth) {
303
+ deps.log.error(
304
+ `${source === 'latest' ? '`latest`' : `Blob source ${source}`} needs Vercel Blob credentials to read the store: ${BLOB_AUTH_HINT}.`,
305
+ )
306
+ return EXIT_PRECONDITION
307
+ }
308
+ resolved = { kind: 'blob', pathname: source, auth: blobAuth, label: source }
309
+ }
310
+
311
+ const pgRestore = await checkPgTool('pg_restore', MIN_PG_MAJOR, deps.spawnImpl)
312
+ if (!pgRestore.ok) {
313
+ deps.log.error(pgRestore.detail)
314
+ return EXIT_PRECONDITION
315
+ }
316
+
317
+ const scratch = await mkdtemp(join(tmpdir(), 'prenta-db-restore-'))
318
+ try {
319
+ // Acquire the dump + manifest.
320
+ let dumpPath: string
321
+ let manifestFile: string | null
322
+ let manifestLabel: string | null
323
+ if (resolved.kind === 'local') {
324
+ dumpPath = resolved.dumpPath
325
+ manifestFile = resolved.manifestPath
326
+ manifestLabel = resolved.manifestPath
327
+ } else {
328
+ const store = createBlobStore({
329
+ ...resolved.auth,
330
+ prefix,
331
+ blobModule: deps.blobModule,
332
+ })
333
+ let pathname = resolved.pathname
334
+ if (pathname === 'latest') {
335
+ let newest
336
+ try {
337
+ newest = (await store.dumps())[0]
338
+ } catch (err) {
339
+ deps.log.error(
340
+ `Could not list backups: ${err instanceof Error ? err.message : String(err)}`,
341
+ )
342
+ return EXIT_FAILED
343
+ }
344
+ if (!newest) {
345
+ deps.log.error(`No backups found under ${store.prefix}/.`)
346
+ return EXIT_FAILED
347
+ }
348
+ pathname = newest.pathname
349
+ resolved = { ...resolved, pathname, label: pathname }
350
+ }
351
+ dumpPath = join(scratch, basename(pathname))
352
+ deps.log.info(`Downloading ${pathname}…`)
353
+ try {
354
+ await store.download(pathname, dumpPath)
355
+ } catch (err) {
356
+ deps.log.error(err instanceof Error ? err.message : String(err))
357
+ return EXIT_FAILED
358
+ }
359
+ // db:backup uploads the manifest before the dump, so a Blob dump without
360
+ // one is a broken pair (or a foreign object) — never restore it blind.
361
+ const manifestPathname = manifestPathnameFor(pathname)
362
+ manifestFile = join(scratch, basename(manifestPathname))
363
+ manifestLabel = manifestPathname
364
+ try {
365
+ await store.download(manifestPathname, manifestFile)
366
+ } catch (err) {
367
+ deps.log.error(
368
+ `Backup ${pathname} has no manifest in Vercel Blob (${manifestPathname}: ${err instanceof Error ? err.message : String(err)}). Every db:backup upload has one; without it the sha256 cannot be verified — not restoring. Download the dump and restore it as a local file if you accept that.`,
369
+ )
370
+ return EXIT_FAILED
371
+ }
372
+ }
373
+
374
+ // Manifest + sha256.
375
+ let manifest: BackupManifest | null = null
376
+ if (manifestFile) {
377
+ try {
378
+ manifest = parseManifest(JSON.parse(await readFile(manifestFile, 'utf-8')))
379
+ } catch (err) {
380
+ deps.log.error(
381
+ `Backup manifest is invalid: ${err instanceof Error ? err.message : String(err)}`,
382
+ )
383
+ return EXIT_FAILED
384
+ }
385
+ const actual = await sha256File(dumpPath)
386
+ if (actual !== manifest.sha256) {
387
+ deps.log.error(
388
+ `sha256 mismatch for ${resolved.label}: manifest says ${manifest.sha256}, file is ${actual}. The backup is corrupt or was tampered with — not restoring.`,
389
+ )
390
+ return EXIT_FAILED
391
+ }
392
+ deps.log.success('Manifest sha256 verified.')
393
+ } else {
394
+ deps.log.warn(
395
+ 'No manifest found next to the local dump; skipping sha256 verification and per-table counts (GCM authentication still protects the contents).',
396
+ )
397
+ }
398
+ const stamp = manifest?.stamp ?? parseStamp(resolved.label)
399
+
400
+ // Confirmation. The expected name is the one the guard classified with
401
+ // (`databaseIdentity`, normalized) so what is shown is what confirms; an
402
+ // empty answer never matches, whatever the name.
403
+ if (targetsProduction) {
404
+ const expectedName = targetIdentity.name
405
+ const answer = (
406
+ await deps.prompt(
407
+ `About to OVERWRITE production database "${expectedName}" on ${describeDatabase(target).host} with backup ${stamp ?? resolved.label}. Type the database name to confirm: `,
408
+ )
409
+ ).trim()
410
+ if (answer === '' || answer !== expectedName) {
411
+ deps.log.error(
412
+ 'Confirmation did not match the database name. Aborted; nothing was restored.',
413
+ )
414
+ return EXIT_PRECONDITION
415
+ }
416
+ } else if (!opts.yes) {
417
+ const answer = await deps.prompt(
418
+ `Restore backup ${stamp ?? resolved.label} into ${redactUrl(target)} (existing objects are dropped first)? Type "yes" to continue: `,
419
+ )
420
+ if (answer.trim().toLowerCase() !== 'yes') {
421
+ deps.log.error('Aborted; nothing was restored.')
422
+ return EXIT_PRECONDITION
423
+ }
424
+ }
425
+
426
+ // Decrypt + restore.
427
+ const plainDump = join(scratch, `${stamp ?? 'backup'}.dump`)
428
+ try {
429
+ await decryptFile(dumpPath, plainDump, key)
430
+ } catch (err) {
431
+ deps.log.error(`Decryption failed: ${err instanceof Error ? err.message : String(err)}`)
432
+ return EXIT_FAILED
433
+ }
434
+ deps.log.info(`Restoring into ${redactUrl(target)} with pg_restore ${pgRestore.version}…`)
435
+ try {
436
+ const result = await runPgRestore(target, plainDump, deps.spawnImpl, env)
437
+ if (result.stderr.trim()) deps.log.warn(result.stderr.trim())
438
+ } catch (err) {
439
+ deps.log.error(`Restore failed: ${err instanceof Error ? err.message : String(err)}`)
440
+ return EXIT_FAILED
441
+ }
442
+ deps.log.success('pg_restore completed.')
443
+
444
+ // Post-restore counts.
445
+ const tables: DbRestoreTableReport[] = (manifest?.tables ?? []).map((t) => ({
446
+ schema: t.schema,
447
+ name: t.name,
448
+ estimate: t.rows,
449
+ restored: null,
450
+ }))
451
+ if (tables.length > 0) {
452
+ const psql = await checkPgTool('psql', 0, deps.spawnImpl)
453
+ if (psql.ok) {
454
+ try {
455
+ const counts = await countTableRows(target, tables, deps.spawnImpl, env)
456
+ for (const row of tables) {
457
+ const match = counts.find((c) => c.schema === row.schema && c.name === row.name)
458
+ if (match) row.restored = match.rows
459
+ }
460
+ } catch (err) {
461
+ deps.log.warn(
462
+ `Could not count restored rows: ${err instanceof Error ? err.message : String(err)}`,
463
+ )
464
+ }
465
+ } else {
466
+ deps.log.warn('psql is not available; skipping per-table row counts.')
467
+ }
468
+ }
469
+
470
+ const summary: DbRestoreSummary = {
471
+ source: resolved.label,
472
+ manifestPath: manifestLabel,
473
+ stamp,
474
+ target: redactUrl(target),
475
+ sha256Verified: manifest !== null,
476
+ tables,
477
+ durationMs: Date.now() - started,
478
+ }
479
+
480
+ if (opts.json) {
481
+ deps.print(JSON.stringify(summary))
482
+ } else {
483
+ if (tables.length > 0) {
484
+ deps.print('')
485
+ deps.print('Manifest estimate (pg_class.reltuples) vs restored count(*):')
486
+ for (const line of renderTable(tables)) deps.print(` ${line}`)
487
+ deps.print('')
488
+ }
489
+ deps.print(
490
+ `Restored ${stamp ?? resolved.label} into ${redactUrl(target)} in ${formatDuration(summary.durationMs)}.`,
491
+ )
492
+ }
493
+ deps.log.info(
494
+ 'Next: run `npx prisma migrate status` against the target to confirm the schema matches the deployed version, then point DATABASE_URL / DIRECT_DATABASE_URL at it if this is a cut-over.',
495
+ )
496
+ return EXIT_OK
497
+ } finally {
498
+ await rm(scratch, { recursive: true, force: true })
499
+ }
500
+ }
501
+
502
+ async function readlinePrompt(question: string): Promise<string> {
503
+ const rl = createInterface({ input: process.stdin, output: process.stderr })
504
+ try {
505
+ return await rl.question(question)
506
+ } finally {
507
+ rl.close()
508
+ }
509
+ }
510
+
511
+ export function defaultDbRestoreDeps(): DbRestoreDeps {
512
+ return {
513
+ spawnImpl: nodeSpawn,
514
+ env: process.env,
515
+ cwd: process.cwd(),
516
+ now: () => new Date(),
517
+ log: logger,
518
+ print: (line) => console.log(line),
519
+ interactive: Boolean(process.stdin.isTTY),
520
+ prompt: readlinePrompt,
521
+ }
522
+ }
523
+
524
+ export function registerDbRestoreCommand(program: Command, deps?: DbRestoreDeps): void {
525
+ program
526
+ .command('db:restore')
527
+ .description('Restore an encrypted db:backup into an explicitly named database')
528
+ .argument('[source]', `Local ${DUMP_EXTENSION} path, Blob pathname, or "latest"`)
529
+ .option('--target <url>', 'Target database URL (required; never defaults to the env database)')
530
+ .option('--yes', 'Skip the confirmation prompt for non-production targets')
531
+ .option('--list', 'List backups available in Vercel Blob and exit')
532
+ .option('--prefix <path>', 'Blob pathname prefix', DEFAULT_BACKUP_PREFIX)
533
+ .option('--json', 'Print a machine-readable JSON summary')
534
+ .option(
535
+ PRODUCTION_FLAG,
536
+ 'Allow restoring into the database named by DIRECT_DATABASE_URL/DATABASE_URL (prompts for the database name)',
537
+ )
538
+ .action(async (source: string | undefined, opts: DbRestoreOptions) => {
539
+ const code = await runDbRestore(source, opts, deps ?? defaultDbRestoreDeps())
540
+ if (code !== EXIT_OK) process.exitCode = code
541
+ })
542
+ }
@@ -2,6 +2,7 @@ import { Command } from 'commander'
2
2
  import { access, readdir, readFile } from 'node:fs/promises'
3
3
  import { resolve } from 'node:path'
4
4
  import chalk from 'chalk'
5
+ import { DB_BACKUP_WORKFLOW_PATH } from '../backup/workflow-template.js'
5
6
  import {
6
7
  buildDeploymentManifest,
7
8
  createDiagnosticReport,
@@ -21,6 +22,7 @@ import {
21
22
  import { buildEnvMatrix, type EnvMatrix } from '../vercel/env-matrix.js'
22
23
  import { loadProjectEnv } from '../utils/load-dotenv.js'
23
24
  import { logger } from '../utils/logger.js'
25
+ import { findRepoRoot } from '../utils/repo-root.js'
24
26
 
25
27
  async function fileExists(path: string): Promise<boolean> {
26
28
  try {
@@ -75,6 +77,7 @@ async function readProjectFileSignals(cwd: string): Promise<ProjectFileSignals>
75
77
  astroCatchAll,
76
78
  astroConfigMjs,
77
79
  astroConfigTs,
80
+ backupWorkflowPresent,
78
81
  ] = await Promise.all([
79
82
  readFirstExistingFile(cwd, ['app/(site)/[[...path]]/page.tsx', 'app/[[...path]]/page.tsx']),
80
83
  readOptionalFile(resolve(cwd, 'lib/cms.ts')),
@@ -91,6 +94,8 @@ async function readProjectFileSignals(cwd: string): Promise<ProjectFileSignals>
91
94
  ]),
92
95
  readOptionalFile(resolve(cwd, 'site/astro.config.mjs')),
93
96
  readOptionalFile(resolve(cwd, 'site/astro.config.ts')),
97
+ // Workflows live at the git top-level, not next to the CMS app (apps/cms).
98
+ fileExists(resolve(findRepoRoot(cwd), DB_BACKUP_WORKFLOW_PATH)),
94
99
  ])
95
100
 
96
101
  return {
@@ -105,6 +110,7 @@ async function readProjectFileSignals(cwd: string): Promise<ProjectFileSignals>
105
110
  astroCmsLib,
106
111
  astroCatchAll,
107
112
  astroConfigPresent: Boolean(astroConfigMjs || astroConfigTs),
113
+ backupWorkflowPresent,
108
114
  }
109
115
  }
110
116
 
@@ -1,3 +1,5 @@
1
+ import { DB_BACKUP_WORKFLOW_PATH } from '../backup/workflow-template.js'
2
+
1
3
  export type DiagnosticStatus = 'pass' | 'warn' | 'fail'
2
4
 
3
5
  export interface DiagnosticCheck {
@@ -82,6 +84,8 @@ export interface ProjectFileSignals {
82
84
  astroCatchAll?: string
83
85
  /** True when `site/astro.config.*` exists (astro-split scaffold). */
84
86
  astroConfigPresent?: boolean
87
+ /** True when `.github/workflows/db-backup.yml` exists (nightly `prenta db:backup`). */
88
+ backupWorkflowPresent?: boolean
85
89
  }
86
90
 
87
91
  export const RECOMMENDED_PRODUCTION_PLUGINS = [
@@ -240,7 +244,9 @@ export function createDiagnosticReport(input: DiagnosticInput): DiagnosticReport
240
244
  fix: pageBuilderRisk
241
245
  ? 'Create a design inventory, then model the page as sections (add_page_section / PageSectionEditor) or document why field-mapped mode is intentional.'
242
246
  : undefined,
243
- docs: pageBuilderRisk ? 'https://prentacms.dev/docs/design-first-page-builder' : undefined,
247
+ docs: pageBuilderRisk
248
+ ? 'https://prentacms.dev/docs/designed-frontend-best-practices'
249
+ : undefined,
244
250
  })
245
251
 
246
252
  const missingPlugins = input.configContent
@@ -384,6 +390,15 @@ export function createDiagnosticReport(input: DiagnosticInput): DiagnosticReport
384
390
  docs: missingApiCache ? 'https://prentacms.dev/docs/caching' : undefined,
385
391
  })
386
392
 
393
+ if (input.projectFiles.backupWorkflowPresent !== undefined) {
394
+ checks.push(
395
+ backupsCheck(
396
+ Boolean(input.env.BACKUP_ENCRYPTION_KEY),
397
+ input.projectFiles.backupWorkflowPresent,
398
+ ),
399
+ )
400
+ }
401
+
387
402
  const formsLaunch = detectFormsLaunchReadiness(input.configContent, input.projectFiles.seedFile)
388
403
  if (formsLaunch.hasFormsPlugin) {
389
404
  const contactReady = formsLaunch.hasContactForm && formsLaunch.hasContactPageWithForm
@@ -436,6 +451,35 @@ export function createDiagnosticReport(input: DiagnosticInput): DiagnosticReport
436
451
  return { status, checks }
437
452
  }
438
453
 
454
+ /** Off-platform database backups: encryption key + nightly workflow (spec 2026-09-18). */
455
+ export function backupsCheck(hasKey: boolean, workflowPresent: boolean): DiagnosticCheck {
456
+ const problems: string[] = []
457
+ const fixes: string[] = []
458
+ if (!hasKey) {
459
+ problems.push('BACKUP_ENCRYPTION_KEY is not set')
460
+ fixes.push(
461
+ 'Generate a key with `openssl rand -hex 32`, set BACKUP_ENCRYPTION_KEY locally and as a repository secret, and escrow it — backups cannot be decrypted without it.',
462
+ )
463
+ }
464
+ if (!workflowPresent) {
465
+ problems.push(`${DB_BACKUP_WORKFLOW_PATH} is missing`)
466
+ fixes.push(
467
+ 'Run `prenta db:backup --init-workflow` and add the DIRECT_DATABASE_URL, BLOB_READ_WRITE_TOKEN and BACKUP_ENCRYPTION_KEY secrets.',
468
+ )
469
+ }
470
+ return {
471
+ id: 'db-backups',
472
+ label: 'Database backups',
473
+ status: problems.length === 0 ? 'pass' : 'warn',
474
+ message:
475
+ problems.length === 0
476
+ ? `BACKUP_ENCRYPTION_KEY is set and ${DB_BACKUP_WORKFLOW_PATH} schedules nightly encrypted dumps to Vercel Blob.`
477
+ : `Off-platform backups are not fully configured: ${problems.join('; ')}.`,
478
+ fix: fixes.length === 0 ? undefined : fixes.join(' '),
479
+ docs: 'https://prentacms.dev/docs/backups',
480
+ }
481
+ }
482
+
439
483
  export function buildDeploymentManifest() {
440
484
  return {
441
485
  schemaVersion: 1,
package/src/index.ts CHANGED
@@ -15,6 +15,8 @@ import { registerUpdateCheckCommand } from './commands/update-check.js'
15
15
  import { registerDbInitCommand } from './commands/db-init.js'
16
16
  import { registerDbSyncCommand } from './commands/db-sync.js'
17
17
  import { registerDbStatusCommand } from './commands/db-status.js'
18
+ import { registerDbBackupCommand } from './commands/db-backup.js'
19
+ import { registerDbRestoreCommand } from './commands/db-restore.js'
18
20
  import { registerInitCommand } from './commands/init.js'
19
21
  import {
20
22
  registerDeployCheckCommand,
@@ -46,6 +48,8 @@ registerUpdateCheckCommand(program)
46
48
  registerDbInitCommand(program)
47
49
  registerDbSyncCommand(program)
48
50
  registerDbStatusCommand(program)
51
+ registerDbBackupCommand(program)
52
+ registerDbRestoreCommand(program)
49
53
  registerInitCommand(program)
50
54
  registerDoctorCommand(program)
51
55
  registerDeployCheckCommand(program)
@@ -0,0 +1,19 @@
1
+ import { existsSync } from 'node:fs'
2
+ import { dirname, resolve } from 'node:path'
3
+
4
+ /**
5
+ * Nearest ancestor of `cwd` (inclusive) that contains a `.git` entry — a
6
+ * directory, or the file a git worktree / submodule leaves behind. Falls
7
+ * back to `cwd` when there is none, so callers can always resolve
8
+ * repository-level paths (`.github/workflows/…`) against the result even in
9
+ * a scaffold that has not been `git init`ed yet.
10
+ */
11
+ export function findRepoRoot(cwd: string): string {
12
+ let dir = resolve(cwd)
13
+ for (;;) {
14
+ if (existsSync(resolve(dir, '.git'))) return dir
15
+ const parent = dirname(dir)
16
+ if (parent === dir) return resolve(cwd)
17
+ dir = parent
18
+ }
19
+ }