@prenta/cli 0.16.5 → 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 +33 -24
  3. package/CHANGELOG.md +6 -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 +27 -0
  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 +55 -0
  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 +42 -0
  73. package/src/index.ts +4 -0
  74. package/src/utils/repo-root.ts +19 -0
@@ -0,0 +1,335 @@
1
+ /**
2
+ * `prenta db:backup` — dump the database with pg_dump, encrypt it with
3
+ * AES-256-GCM under BACKUP_ENCRYPTION_KEY, write `<stamp>.dump.enc` +
4
+ * `<stamp>.manifest.json`, optionally upload both to Vercel Blob (manifest
5
+ * first, never overwriting) and prune backups older than the retention
6
+ * window measured from the run start. `--init-workflow` writes the nightly
7
+ * GitHub Actions workflow instead.
8
+ *
9
+ * Exit codes: 0 ok · 1 dump/upload failed · 2 preconditions (tools, env).
10
+ *
11
+ * Everything with a side effect is injected through `DbBackupDeps` so the
12
+ * command is unit-testable without Postgres or the network.
13
+ */
14
+ import { Command } from 'commander'
15
+ import { existsSync } from 'node:fs'
16
+ import { mkdir, mkdtemp, rm, stat, writeFile } from 'node:fs/promises'
17
+ import { tmpdir } from 'node:os'
18
+ import { dirname, join, resolve } from 'node:path'
19
+ import { createBlobStore, DEFAULT_BACKUP_PREFIX, type BlobModule } from '../backup/blob-store.js'
20
+ import {
21
+ BLOB_AUTH_HINT,
22
+ EXIT_FAILED,
23
+ EXIT_OK,
24
+ EXIT_PRECONDITION,
25
+ formatBytes,
26
+ formatDuration,
27
+ isLocalDatabaseUrl,
28
+ isPostgresUrl,
29
+ resolveBlobAuth,
30
+ resolveDatabaseUrl,
31
+ } from '../backup/common.js'
32
+ import { BackupKeyError, encryptFile, parseBackupKey } from '../backup/crypto.js'
33
+ import {
34
+ buildManifest,
35
+ DUMP_EXTENSION,
36
+ MANIFEST_EXTENSION,
37
+ sha256File,
38
+ stampFor,
39
+ type BackupTableRows,
40
+ } from '../backup/manifest.js'
41
+ import {
42
+ checkPgTool,
43
+ estimateTableRows,
44
+ nodeSpawn,
45
+ redactUrl,
46
+ runPgDump,
47
+ type SpawnImpl,
48
+ } from '../backup/pg-tools.js'
49
+ import { DB_BACKUP_WORKFLOW_PATH, DB_BACKUP_WORKFLOW_YAML } from '../backup/workflow-template.js'
50
+ import { loadProjectEnv } from '../utils/load-dotenv.js'
51
+ import { logger, type Logger } from '../utils/logger.js'
52
+ import { findRepoRoot } from '../utils/repo-root.js'
53
+
54
+ export const DEFAULT_RETENTION_DAYS = 30
55
+ const MIN_PG_MAJOR = 17
56
+
57
+ export interface DbBackupOptions {
58
+ out?: string
59
+ upload?: boolean
60
+ retentionDays?: number
61
+ prefix?: string
62
+ json?: boolean
63
+ initWorkflow?: boolean
64
+ force?: boolean
65
+ allowLocal?: boolean
66
+ }
67
+
68
+ export interface DbBackupDeps {
69
+ spawnImpl: SpawnImpl
70
+ /** Injected `@vercel/blob`; `undefined` loads the real module on demand. */
71
+ blobModule?: BlobModule
72
+ env: NodeJS.ProcessEnv
73
+ cwd: string
74
+ now: () => Date
75
+ log: Logger
76
+ /** Machine-readable / summary output (stdout). */
77
+ print: (line: string) => void
78
+ }
79
+
80
+ export interface DbBackupSummary {
81
+ stamp: string
82
+ dumpPath: string
83
+ manifestPath: string
84
+ sizeBytes: number
85
+ tableCount: number
86
+ uploaded: boolean
87
+ blobPathname?: string
88
+ dumpUrl?: string
89
+ manifestUrl?: string
90
+ pruned: string[]
91
+ durationMs: number
92
+ }
93
+
94
+ async function writeWorkflow(opts: DbBackupOptions, deps: DbBackupDeps): Promise<number> {
95
+ // GitHub only reads workflows from the repository root, so resolve against
96
+ // the git top-level even when the CMS app lives in `apps/cms`.
97
+ const root = findRepoRoot(deps.cwd)
98
+ const target = resolve(root, DB_BACKUP_WORKFLOW_PATH)
99
+ const shown = root === resolve(deps.cwd) ? DB_BACKUP_WORKFLOW_PATH : target
100
+ if (existsSync(target) && !opts.force) {
101
+ deps.log.error(`${shown} already exists. Re-run with --force to overwrite it.`)
102
+ return EXIT_FAILED
103
+ }
104
+ await mkdir(dirname(target), { recursive: true })
105
+ await writeFile(target, DB_BACKUP_WORKFLOW_YAML)
106
+ deps.log.success(`Wrote ${shown}.`)
107
+ deps.log.info(
108
+ 'Add the repository secrets DIRECT_DATABASE_URL, BLOB_READ_WRITE_TOKEN and BACKUP_ENCRYPTION_KEY, then trigger the workflow once via workflow_dispatch.',
109
+ )
110
+ return EXIT_OK
111
+ }
112
+
113
+ export async function runDbBackup(opts: DbBackupOptions, deps: DbBackupDeps): Promise<number> {
114
+ if (opts.initWorkflow) return writeWorkflow(opts, deps)
115
+
116
+ const startedAt = deps.now()
117
+ const started = Date.now()
118
+ const env = await loadProjectEnv(deps.cwd, deps.env)
119
+
120
+ // 1. Database URL.
121
+ const resolved = resolveDatabaseUrl(env)
122
+ if (!resolved) {
123
+ deps.log.error(
124
+ 'No database URL found. Set DIRECT_DATABASE_URL (preferred, non-pooled) or DATABASE_URL.',
125
+ )
126
+ return EXIT_PRECONDITION
127
+ }
128
+ if (!isPostgresUrl(resolved.url)) {
129
+ deps.log.error(`${resolved.source} is not a valid postgres:// URL.`)
130
+ return EXIT_PRECONDITION
131
+ }
132
+ if (resolved.source === 'DATABASE_URL') {
133
+ deps.log.warn(
134
+ 'DIRECT_DATABASE_URL is not set; using DATABASE_URL. Pooled URLs work for pg_dump but are slower — prefer the direct (non-pooled) connection string.',
135
+ )
136
+ }
137
+ if (isLocalDatabaseUrl(resolved.url) && !opts.allowLocal) {
138
+ deps.log.error(
139
+ `${resolved.source} points at a local database (${redactUrl(resolved.url)}). Pass --allow-local if that is intended.`,
140
+ )
141
+ return EXIT_PRECONDITION
142
+ }
143
+
144
+ // 2. Encryption key.
145
+ let key: Buffer
146
+ try {
147
+ key = parseBackupKey(env.BACKUP_ENCRYPTION_KEY)
148
+ } catch (err) {
149
+ deps.log.error(err instanceof BackupKeyError ? err.message : String(err))
150
+ return EXIT_PRECONDITION
151
+ }
152
+
153
+ // 3. Upload preconditions (checked before any expensive work).
154
+ const retentionDays = opts.retentionDays ?? DEFAULT_RETENTION_DAYS
155
+ const prefix = opts.prefix ?? DEFAULT_BACKUP_PREFIX
156
+ const blobAuth = resolveBlobAuth(env)
157
+ if (opts.upload) {
158
+ if (!blobAuth) {
159
+ deps.log.error(`--upload requires Vercel Blob credentials: ${BLOB_AUTH_HINT}.`)
160
+ return EXIT_PRECONDITION
161
+ }
162
+ if (!Number.isFinite(retentionDays) || retentionDays <= 0) {
163
+ deps.log.error('--retention-days must be a positive number of days.')
164
+ return EXIT_PRECONDITION
165
+ }
166
+ }
167
+
168
+ // 4. Tools.
169
+ const pgDump = await checkPgTool('pg_dump', MIN_PG_MAJOR, deps.spawnImpl)
170
+ if (!pgDump.ok) {
171
+ deps.log.error(pgDump.detail)
172
+ return EXIT_PRECONDITION
173
+ }
174
+
175
+ // 5. Row estimates (before the dump; psql is optional).
176
+ let tables: BackupTableRows[] = []
177
+ const psql = await checkPgTool('psql', 0, deps.spawnImpl)
178
+ if (psql.ok) {
179
+ try {
180
+ tables = await estimateTableRows(resolved.url, deps.spawnImpl, env)
181
+ } catch (err) {
182
+ deps.log.warn(
183
+ `Could not read table row estimates via psql; the manifest will list no tables. ${err instanceof Error ? err.message : String(err)}`,
184
+ )
185
+ }
186
+ } else {
187
+ deps.log.warn(
188
+ 'psql is not available; the manifest will list no tables and db:restore cannot print per-table counts.',
189
+ )
190
+ }
191
+
192
+ // 6. Dump → encrypt → manifest.
193
+ const stamp = stampFor(startedAt)
194
+ const outDir = resolve(deps.cwd, opts.out ?? join(tmpdir(), 'prenta-backups'))
195
+ await mkdir(outDir, { recursive: true })
196
+ const dumpPath = join(outDir, `${stamp}${DUMP_EXTENSION}`)
197
+ const manifestPath = join(outDir, `${stamp}${MANIFEST_EXTENSION}`)
198
+ const scratch = await mkdtemp(join(tmpdir(), 'prenta-db-backup-'))
199
+ const rawDump = join(scratch, `${stamp}.dump`)
200
+
201
+ let sizeBytes: number
202
+ try {
203
+ deps.log.info(`Dumping ${redactUrl(resolved.url)} with pg_dump ${pgDump.version}…`)
204
+ await runPgDump(resolved.url, rawDump, deps.spawnImpl, env)
205
+ await encryptFile(rawDump, dumpPath, key)
206
+ sizeBytes = (await stat(dumpPath)).size
207
+ const sha256 = await sha256File(dumpPath)
208
+ const manifest = buildManifest({
209
+ createdAt: startedAt,
210
+ databaseUrl: resolved.url,
211
+ pgDumpVersion: pgDump.version,
212
+ sizeBytes,
213
+ sha256,
214
+ tables,
215
+ })
216
+ await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`)
217
+ } catch (err) {
218
+ await rm(dumpPath, { force: true })
219
+ await rm(manifestPath, { force: true })
220
+ deps.log.error(`Backup failed: ${err instanceof Error ? err.message : String(err)}`)
221
+ return EXIT_FAILED
222
+ } finally {
223
+ await rm(scratch, { recursive: true, force: true })
224
+ }
225
+
226
+ const summary: DbBackupSummary = {
227
+ stamp,
228
+ dumpPath,
229
+ manifestPath,
230
+ sizeBytes,
231
+ tableCount: tables.length,
232
+ uploaded: false,
233
+ pruned: [],
234
+ durationMs: 0,
235
+ }
236
+
237
+ // 7. Upload + prune. Manifest first: `--list` / `latest` only consider
238
+ // `.dump.enc` objects, so a stray manifest is invisible whereas a stray
239
+ // dump would be offered as restorable without its manifest.
240
+ if (opts.upload && blobAuth) {
241
+ const store = createBlobStore({ ...blobAuth, prefix, blobModule: deps.blobModule })
242
+ const manifestName = `${stamp}${MANIFEST_EXTENSION}`
243
+ let manifestUploaded = false
244
+ try {
245
+ const manifest = await store.upload(manifestPath, manifestName)
246
+ manifestUploaded = true
247
+ const dump = await store.upload(dumpPath, `${stamp}${DUMP_EXTENSION}`)
248
+ summary.uploaded = true
249
+ summary.blobPathname = dump.pathname
250
+ summary.dumpUrl = dump.url
251
+ summary.manifestUrl = manifest.url
252
+ } catch (err) {
253
+ deps.log.error(
254
+ `Upload to Vercel Blob failed: ${err instanceof Error ? err.message : String(err)}. Local files were kept at ${outDir}; nothing was pruned.`,
255
+ )
256
+ if (manifestUploaded) {
257
+ try {
258
+ await store.remove(manifestName)
259
+ } catch (cleanupErr) {
260
+ deps.log.warn(
261
+ `Could not remove the half-uploaded manifest ${prefix}/${manifestName}: ${cleanupErr instanceof Error ? cleanupErr.message : String(cleanupErr)}. It is harmless (never listed as restorable) but delete it by hand.`,
262
+ )
263
+ }
264
+ }
265
+ return EXIT_FAILED
266
+ }
267
+ try {
268
+ // Relative to the run start: a slow dump must not widen the window.
269
+ summary.pruned = (await store.prune(retentionDays, startedAt)).deleted
270
+ } catch (err) {
271
+ // The backup itself succeeded; a prune hiccup must not fail the run.
272
+ deps.log.warn(
273
+ `Backup uploaded but pruning old backups failed: ${err instanceof Error ? err.message : String(err)}`,
274
+ )
275
+ }
276
+ }
277
+
278
+ summary.durationMs = Date.now() - started
279
+
280
+ if (opts.json) {
281
+ deps.print(JSON.stringify(summary))
282
+ } else {
283
+ const where = summary.uploaded ? `${dumpPath} → ${summary.blobPathname}` : dumpPath
284
+ deps.print(
285
+ `Backup ${stamp}: ${formatBytes(sizeBytes)}, ${tables.length} table(s), ${where}, pruned ${summary.pruned.length}, ${formatDuration(summary.durationMs)}`,
286
+ )
287
+ if (!summary.uploaded) {
288
+ deps.log.info('Run with --upload to store this backup in Vercel Blob.')
289
+ }
290
+ }
291
+ return EXIT_OK
292
+ }
293
+
294
+ function parseRetention(value: string): number {
295
+ const n = Number(value)
296
+ if (!Number.isFinite(n)) throw new Error(`--retention-days expects a number, got "${value}".`)
297
+ return n
298
+ }
299
+
300
+ export function defaultDbBackupDeps(): DbBackupDeps {
301
+ return {
302
+ spawnImpl: nodeSpawn,
303
+ env: process.env,
304
+ cwd: process.cwd(),
305
+ now: () => new Date(),
306
+ log: logger,
307
+ print: (line) => console.log(line),
308
+ }
309
+ }
310
+
311
+ export function registerDbBackupCommand(program: Command, deps?: DbBackupDeps): void {
312
+ program
313
+ .command('db:backup')
314
+ .description('Dump, encrypt and (optionally) upload the database to Vercel Blob')
315
+ .option('--out <dir>', 'Directory for <stamp>.dump.enc + <stamp>.manifest.json')
316
+ .option(
317
+ '--upload',
318
+ 'Upload both files to Vercel Blob (BLOB_READ_WRITE_TOKEN); never overwrites - a rerun within the same second fails',
319
+ )
320
+ .option(
321
+ '--retention-days <n>',
322
+ 'Prune uploaded backups older than n days (with --upload)',
323
+ parseRetention,
324
+ DEFAULT_RETENTION_DAYS,
325
+ )
326
+ .option('--prefix <path>', 'Blob pathname prefix', DEFAULT_BACKUP_PREFIX)
327
+ .option('--allow-local', 'Allow a localhost / 127.0.0.1 database URL')
328
+ .option('--json', 'Print a machine-readable JSON summary')
329
+ .option('--init-workflow', `Write ${DB_BACKUP_WORKFLOW_PATH} into this repo and exit`)
330
+ .option('--force', 'Overwrite an existing workflow file (with --init-workflow)')
331
+ .action(async (opts: DbBackupOptions) => {
332
+ const code = await runDbBackup(opts, deps ?? defaultDbBackupDeps())
333
+ if (code !== EXIT_OK) process.exitCode = code
334
+ })
335
+ }