@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,294 @@
1
+ /**
2
+ * Vercel Blob storage for encrypted database backups.
3
+ *
4
+ * Backups live under `<prefix>/<stamp>.dump.enc` + `<prefix>/<stamp>.manifest.json`
5
+ * (default prefix `backups/db`) with `access: 'private'` and no random suffix,
6
+ * so a stamp maps to exactly one pair of objects. Blob is a different vendor
7
+ * from the database and every site already has `BLOB_READ_WRITE_TOKEN`.
8
+ *
9
+ * `@vercel/blob` is an optional peer of `@prenta/cli` (>= 2, for `get()` on
10
+ * private blobs); the host project normally has it through
11
+ * `@prenta/platform-vercel`. It is loaded with a dynamic import whose
12
+ * specifier is assembled at runtime (same pattern as cms-core's
13
+ * `ai/plugin-import.ts`) so bundlers do not try to resolve it, the loaded
14
+ * module is shape-checked before use, and the module is injectable so tests
15
+ * use an in-memory fake instead.
16
+ *
17
+ * Uploads never overwrite: `put` is called without `allowOverwrite`, so a
18
+ * second upload of the same pathname (a rerun within the same second) fails
19
+ * instead of silently replacing a backup.
20
+ *
21
+ * Prune (and `list` / `latest`) only ever consider objects directly under the
22
+ * prefix whose basename is exactly `<stamp>.dump.enc` or
23
+ * `<stamp>.manifest.json` (stamp anchored to the whole basename). Anything
24
+ * else under the prefix — `old-<stamp>.dump.enc`, `sub/<stamp>.dump.enc` —
25
+ * is left alone.
26
+ *
27
+ * Auth: when `BLOB_READ_WRITE_TOKEN` is set it is passed as `token`.
28
+ * Otherwise `token` is omitted entirely so the SDK's own resolution applies
29
+ * (`VERCEL_OIDC_TOKEN` + `BLOB_STORE_ID`, the Marketplace store mode — see
30
+ * `@prenta/platform-vercel`'s `blob-auth.ts`). An explicit `token: undefined`
31
+ * would shadow that lookup, so the key must be absent, not undefined.
32
+ */
33
+ import { createReadStream, createWriteStream } from 'node:fs'
34
+ import { Readable } from 'node:stream'
35
+ import { pipeline } from 'node:stream/promises'
36
+ import type { ReadableStream as WebReadableStream } from 'node:stream/web'
37
+ import {
38
+ compareStamps,
39
+ DUMP_EXTENSION,
40
+ isOlderThan,
41
+ MANIFEST_EXTENSION,
42
+ parseStamp,
43
+ } from './manifest.js'
44
+
45
+ export const DEFAULT_BACKUP_PREFIX = 'backups/db'
46
+
47
+ /** `{ token }` in read-write-token mode; `{}` when the SDK resolves OIDC auth itself. */
48
+ export interface BlobAuthOptions {
49
+ token?: string
50
+ }
51
+
52
+ export interface BlobPutOptions extends BlobAuthOptions {
53
+ access: 'private'
54
+ addRandomSuffix: false
55
+ contentType?: string
56
+ multipart?: boolean
57
+ }
58
+
59
+ export interface BlobPutResult {
60
+ url: string
61
+ pathname: string
62
+ }
63
+
64
+ export interface BlobListedItem {
65
+ pathname: string
66
+ size: number
67
+ uploadedAt: Date
68
+ url: string
69
+ }
70
+
71
+ export interface BlobListOptions extends BlobAuthOptions {
72
+ prefix: string
73
+ cursor?: string
74
+ limit?: number
75
+ }
76
+
77
+ export interface BlobListResult {
78
+ blobs: BlobListedItem[]
79
+ cursor?: string
80
+ hasMore: boolean
81
+ }
82
+
83
+ export interface BlobGetResult {
84
+ statusCode: number
85
+ stream: WebReadableStream<Uint8Array> | null
86
+ }
87
+
88
+ /** The slice of `@vercel/blob` the backup commands use. */
89
+ export interface BlobModule {
90
+ put(pathname: string, body: Readable, options: BlobPutOptions): Promise<BlobPutResult>
91
+ list(options: BlobListOptions): Promise<BlobListResult>
92
+ del(urlsOrPathnames: string | string[], options: BlobAuthOptions): Promise<void>
93
+ get(
94
+ pathname: string,
95
+ options: BlobAuthOptions & { access: 'private' },
96
+ ): Promise<BlobGetResult | null>
97
+ }
98
+
99
+ export type BackupBlobKind = 'dump' | 'manifest'
100
+
101
+ export interface BackupBlob extends BlobListedItem {
102
+ stamp: string
103
+ kind: BackupBlobKind
104
+ }
105
+
106
+ export interface BlobStore {
107
+ readonly prefix: string
108
+ /** Upload a local file to `<prefix>/<name>`. */
109
+ upload(localPath: string, name: string): Promise<BlobPutResult>
110
+ /** Every backup object under the prefix, newest stamp first. */
111
+ list(): Promise<BackupBlob[]>
112
+ /** Only the `.dump.enc` objects, newest first (restorable backups). */
113
+ dumps(): Promise<BackupBlob[]>
114
+ /** Stream a private blob to `dest`. */
115
+ download(pathname: string, dest: string): Promise<void>
116
+ /** Delete one object under the prefix by name (used to undo a half-uploaded pair). */
117
+ remove(name: string): Promise<void>
118
+ /** Delete expired backup pairs. Returns the pathnames removed. */
119
+ prune(retentionDays: number, now?: Date): Promise<{ deleted: string[] }>
120
+ }
121
+
122
+ export interface CreateBlobStoreOptions {
123
+ /** `BLOB_READ_WRITE_TOKEN`; omit to let `@vercel/blob` resolve OIDC auth from the environment. */
124
+ token?: string
125
+ prefix?: string
126
+ /** Injected `@vercel/blob` (tests). Wins over `loadBlobModule`. */
127
+ blobModule?: BlobModule
128
+ /**
129
+ * Loader for the real module; defaults to a runtime-assembled dynamic
130
+ * import. Whatever it resolves to is shape-checked by `assertBlobModule`.
131
+ */
132
+ loadBlobModule?: () => Promise<unknown>
133
+ }
134
+
135
+ async function defaultLoadBlobModule(): Promise<unknown> {
136
+ const specifier = '@vercel/' + 'blob'
137
+ return import(/* webpackIgnore: true */ /* turbopackIgnore: true */ /* @vite-ignore */ specifier)
138
+ }
139
+
140
+ const BLOB_MODULE_FUNCTIONS = ['put', 'list', 'del', 'get'] as const
141
+
142
+ /**
143
+ * Narrow an arbitrary loaded module to the `BlobModule` slice. `get()` is
144
+ * the >= 2 marker: private blobs (which backups require) cannot be read
145
+ * without it, so an older install fails here with a version message rather
146
+ * than later with "get is not a function".
147
+ */
148
+ export function assertBlobModule(mod: unknown): BlobModule {
149
+ const record = typeof mod === 'object' && mod !== null ? (mod as Record<string, unknown>) : {}
150
+ const missing = BLOB_MODULE_FUNCTIONS.filter((name) => typeof record[name] !== 'function')
151
+ if (missing.length === 0) return mod as BlobModule
152
+ if (missing.includes('get') && missing.length === 1) {
153
+ throw new Error('@prenta/cli db:backup requires @vercel/blob >= 2 (private blobs).')
154
+ }
155
+ throw new Error(
156
+ `The loaded @vercel/blob module is missing ${missing.join(', ')}; @prenta/cli db:backup requires @vercel/blob >= 2.`,
157
+ )
158
+ }
159
+
160
+ function isModuleNotFound(err: unknown): boolean {
161
+ if (!(err instanceof Error)) return false
162
+ const code = (err as NodeJS.ErrnoException).code
163
+ return code === 'ERR_MODULE_NOT_FOUND' || code === 'MODULE_NOT_FOUND'
164
+ }
165
+
166
+ /**
167
+ * Classify a basename that is exactly `<stamp>.dump.enc` or
168
+ * `<stamp>.manifest.json`; anything else (`old-<stamp>.dump.enc`,
169
+ * `<stamp>.dump.enc.bak`) is not ours.
170
+ */
171
+ function classifyBasename(basename: string): { stamp: string; kind: BackupBlobKind } | null {
172
+ const kind: BackupBlobKind | null = basename.endsWith(DUMP_EXTENSION)
173
+ ? 'dump'
174
+ : basename.endsWith(MANIFEST_EXTENSION)
175
+ ? 'manifest'
176
+ : null
177
+ if (!kind) return null
178
+ const extension = kind === 'dump' ? DUMP_EXTENSION : MANIFEST_EXTENSION
179
+ const stem = basename.slice(0, -extension.length)
180
+ const stamp = parseStamp(stem)
181
+ // `parseStamp` searches for a stamp inside the string; require the stem to be nothing else.
182
+ if (stamp === null || stamp !== stem) return null
183
+ return { stamp, kind }
184
+ }
185
+
186
+ function contentTypeFor(name: string): string {
187
+ return name.endsWith(MANIFEST_EXTENSION) ? 'application/json' : 'application/octet-stream'
188
+ }
189
+
190
+ const DEL_BATCH_SIZE = 100
191
+
192
+ export function createBlobStore(options: CreateBlobStoreOptions): BlobStore {
193
+ // Spread into every SDK call: `{ token }` or `{}` — never `{ token: undefined }`.
194
+ const auth: BlobAuthOptions = options.token ? { token: options.token } : {}
195
+ const prefix = (options.prefix ?? DEFAULT_BACKUP_PREFIX).replace(/^\/+|\/+$/g, '')
196
+ const load = options.loadBlobModule ?? defaultLoadBlobModule
197
+ let modulePromise: Promise<BlobModule> | null = options.blobModule
198
+ ? Promise.resolve(options.blobModule)
199
+ : null
200
+
201
+ async function blob(): Promise<BlobModule> {
202
+ if (!modulePromise) {
203
+ modulePromise = load()
204
+ .then(assertBlobModule)
205
+ .catch((err: unknown) => {
206
+ modulePromise = null
207
+ if (isModuleNotFound(err)) {
208
+ throw new Error(
209
+ '@vercel/blob is not installed. Backups upload through Vercel Blob; install it in the project (`pnpm add @vercel/blob`, or via @prenta/platform-vercel) and re-run.',
210
+ )
211
+ }
212
+ throw err
213
+ })
214
+ }
215
+ return modulePromise
216
+ }
217
+
218
+ /** `<prefix>/<stamp>.dump.enc` | `<prefix>/<stamp>.manifest.json`, exactly — else null. */
219
+ const classify = (pathname: string): { stamp: string; kind: BackupBlobKind } | null => {
220
+ if (!pathname.startsWith(`${prefix}/`)) return null
221
+ const basename = pathname.slice(prefix.length + 1)
222
+ if (basename.includes('/')) return null
223
+ return classifyBasename(basename)
224
+ }
225
+
226
+ async function list(): Promise<BackupBlob[]> {
227
+ const mod = await blob()
228
+ const items: BackupBlob[] = []
229
+ let cursor: string | undefined
230
+ do {
231
+ const page = await mod.list({ prefix: `${prefix}/`, cursor, limit: 1000, ...auth })
232
+ for (const item of page.blobs) {
233
+ const ours = classify(item.pathname)
234
+ if (!ours) continue
235
+ items.push({ ...item, stamp: ours.stamp, kind: ours.kind })
236
+ }
237
+ cursor = page.hasMore ? page.cursor : undefined
238
+ } while (cursor)
239
+ // Newest first; the dump sorts before its manifest for the same stamp.
240
+ return items.sort(
241
+ (a, b) =>
242
+ compareStamps(b.stamp, a.stamp) || (a.kind === b.kind ? 0 : a.kind === 'dump' ? -1 : 1),
243
+ )
244
+ }
245
+
246
+ return {
247
+ prefix,
248
+
249
+ async upload(localPath, name) {
250
+ const mod = await blob()
251
+ const pathname = `${prefix}/${name}`
252
+ return mod.put(pathname, createReadStream(localPath), {
253
+ access: 'private',
254
+ addRandomSuffix: false,
255
+ contentType: contentTypeFor(name),
256
+ multipart: true,
257
+ ...auth,
258
+ })
259
+ },
260
+
261
+ list,
262
+
263
+ async dumps() {
264
+ return (await list()).filter((item) => item.kind === 'dump')
265
+ },
266
+
267
+ async download(pathname, dest) {
268
+ const mod = await blob()
269
+ const result = await mod.get(pathname, { access: 'private', ...auth })
270
+ if (!result || !result.stream) {
271
+ throw new Error(`Backup ${pathname} was not found in Vercel Blob.`)
272
+ }
273
+ await pipeline(Readable.fromWeb(result.stream), createWriteStream(dest))
274
+ },
275
+
276
+ async remove(name) {
277
+ const mod = await blob()
278
+ await mod.del(`${prefix}/${name}`, { ...auth })
279
+ },
280
+
281
+ async prune(retentionDays, now = new Date()) {
282
+ if (!Number.isFinite(retentionDays) || retentionDays <= 0) return { deleted: [] }
283
+ const expired = (await list())
284
+ .filter((item) => isOlderThan(item.stamp, retentionDays, now))
285
+ .map((item) => item.pathname)
286
+ if (expired.length === 0) return { deleted: [] }
287
+ const mod = await blob()
288
+ for (let i = 0; i < expired.length; i += DEL_BATCH_SIZE) {
289
+ await mod.del(expired.slice(i, i + DEL_BATCH_SIZE), { ...auth })
290
+ }
291
+ return { deleted: expired }
292
+ },
293
+ }
294
+ }
@@ -0,0 +1,153 @@
1
+ /**
2
+ * Small pure helpers shared by `db:backup` and `db:restore`: env resolution,
3
+ * local-host detection, same-database comparison and human formatting.
4
+ */
5
+
6
+ /** Shared exit codes: 0 ok · 1 the operation failed · 2 preconditions (tools, env, safety). */
7
+ export const EXIT_OK = 0
8
+ export const EXIT_FAILED = 1
9
+ export const EXIT_PRECONDITION = 2
10
+
11
+ export interface ResolvedDatabaseUrl {
12
+ url: string
13
+ source: 'DIRECT_DATABASE_URL' | 'DATABASE_URL'
14
+ }
15
+
16
+ /** `DIRECT_DATABASE_URL` first (non-pooled), else `DATABASE_URL`. */
17
+ export function resolveDatabaseUrl(env: NodeJS.ProcessEnv): ResolvedDatabaseUrl | null {
18
+ if (env.DIRECT_DATABASE_URL)
19
+ return { url: env.DIRECT_DATABASE_URL, source: 'DIRECT_DATABASE_URL' }
20
+ if (env.DATABASE_URL) return { url: env.DATABASE_URL, source: 'DATABASE_URL' }
21
+ return null
22
+ }
23
+
24
+ /**
25
+ * How the CLI can authenticate to Vercel Blob. `{ token }` when
26
+ * `BLOB_READ_WRITE_TOKEN` is set; `{}` when only the Marketplace OIDC pair
27
+ * (`VERCEL_OIDC_TOKEN` + `BLOB_STORE_ID`) is present, in which case
28
+ * `@vercel/blob` resolves the credentials from the environment itself and
29
+ * the CLI must not pass `token` at all. `null` when neither mode is available.
30
+ * Mirrors `resolveBlobClientAuthOptions` in `@prenta/platform-vercel`.
31
+ */
32
+ export function resolveBlobAuth(env: NodeJS.ProcessEnv): { token?: string } | null {
33
+ const token = env.BLOB_READ_WRITE_TOKEN?.trim()
34
+ if (token) return { token }
35
+ if (env.VERCEL_OIDC_TOKEN?.trim() && env.BLOB_STORE_ID?.trim()) return {}
36
+ return null
37
+ }
38
+
39
+ /** Names both Blob auth modes, for precondition errors. */
40
+ export const BLOB_AUTH_HINT =
41
+ 'BLOB_READ_WRITE_TOKEN (Vercel Blob read-write token), or VERCEL_OIDC_TOKEN together with BLOB_STORE_ID (Marketplace Blob store on Vercel)'
42
+
43
+ const LOCAL_HOSTS = new Set(['localhost', '127.0.0.1', '::1', '[::1]'])
44
+
45
+ /** True for URLs pointing at the developer's own machine. */
46
+ export function isLocalDatabaseUrl(url: string): boolean {
47
+ try {
48
+ return LOCAL_HOSTS.has(new URL(url).hostname.toLowerCase())
49
+ } catch {
50
+ return false
51
+ }
52
+ }
53
+
54
+ /**
55
+ * What identifies "one database" for the production guard.
56
+ *
57
+ * Prisma Postgres direct URLs are `postgres://USER:PASSWORD@db.prisma.io:5432/postgres`
58
+ * for every database in a project — the username is the per-database
59
+ * discriminator, so host + database name alone would call a fresh scratch
60
+ * database "production". Host is lowercased with a leading `pooled.` label
61
+ * stripped (pooled and direct strings of one database compare equal); the
62
+ * database path loses trailing slashes and an empty path means `postgres`
63
+ * (libpq's default). Password, port and query string are ignored.
64
+ */
65
+ export interface DatabaseIdentity {
66
+ user: string
67
+ host: string
68
+ name: string
69
+ }
70
+
71
+ function safeDecode(value: string): string {
72
+ try {
73
+ return decodeURIComponent(value)
74
+ } catch {
75
+ return value
76
+ }
77
+ }
78
+
79
+ /**
80
+ * The database a URL path names, normalized the way libpq resolves it:
81
+ * surrounding slashes stripped, percent-escapes decoded, and an empty path
82
+ * meaning `postgres`. Every place that shows or compares a database name
83
+ * (the production guard, the typed confirmation, the manifest) must use this
84
+ * so they agree.
85
+ */
86
+ export function normalizeDatabaseName(pathname: string): string {
87
+ const path = safeDecode(pathname.replace(/^\/+|\/+$/g, ''))
88
+ return path === '' ? 'postgres' : path
89
+ }
90
+
91
+ /** True when the URL path names a database explicitly (`/db`), not `` or `/`. */
92
+ export function namesDatabase(url: string): boolean {
93
+ try {
94
+ return new URL(url).pathname.replace(/^\/+|\/+$/g, '') !== ''
95
+ } catch {
96
+ return false
97
+ }
98
+ }
99
+
100
+ /** `DatabaseIdentity` for a parseable postgres:// URL, else `null`. */
101
+ export function databaseIdentity(url: string): DatabaseIdentity | null {
102
+ if (!isPostgresUrl(url)) return null
103
+ const parsed = new URL(url)
104
+ return {
105
+ user: safeDecode(parsed.username),
106
+ host: parsed.hostname.toLowerCase().replace(/^pooled\./, ''),
107
+ name: normalizeDatabaseName(parsed.pathname),
108
+ }
109
+ }
110
+
111
+ /**
112
+ * True when both URLs name the same database (see `DatabaseIdentity`).
113
+ * Unparseable input is never "the same" — callers that need to know whether
114
+ * the comparison was possible at all use `databaseIdentity` directly.
115
+ */
116
+ export function isSameDatabase(a: string, b: string): boolean {
117
+ const da = databaseIdentity(a)
118
+ const db = databaseIdentity(b)
119
+ if (!da || !db) return false
120
+ return da.user === db.user && da.host === db.host && da.name === db.name
121
+ }
122
+
123
+ /** Validate a connection URL is parseable and uses a postgres scheme. */
124
+ export function isPostgresUrl(url: string): boolean {
125
+ try {
126
+ const parsed = new URL(url)
127
+ return (
128
+ (parsed.protocol === 'postgres:' || parsed.protocol === 'postgresql:') && !!parsed.hostname
129
+ )
130
+ } catch {
131
+ return false
132
+ }
133
+ }
134
+
135
+ export function formatBytes(bytes: number): string {
136
+ if (bytes < 1024) return `${bytes} B`
137
+ const units = ['KB', 'MB', 'GB', 'TB']
138
+ let value = bytes / 1024
139
+ let unit = 0
140
+ while (value >= 1024 && unit < units.length - 1) {
141
+ value /= 1024
142
+ unit++
143
+ }
144
+ return `${value.toFixed(value >= 100 ? 0 : 1)} ${units[unit]}`
145
+ }
146
+
147
+ export function formatDuration(ms: number): string {
148
+ if (ms < 1000) return `${Math.round(ms)}ms`
149
+ const seconds = ms / 1000
150
+ if (seconds < 60) return `${seconds.toFixed(1)}s`
151
+ const minutes = Math.floor(seconds / 60)
152
+ return `${minutes}m ${Math.round(seconds - minutes * 60)}s`
153
+ }
@@ -0,0 +1,192 @@
1
+ /**
2
+ * AES-256-GCM file envelope for encrypted database dumps.
3
+ *
4
+ * Layout (spec 2026-09-18-db-backups-and-dr-design.md §1 step 4):
5
+ *
6
+ * `PRENTA1` magic (7 bytes) | IV (12 bytes) | ciphertext | auth tag (16 bytes)
7
+ *
8
+ * The key is `BACKUP_ENCRYPTION_KEY`: 32 bytes as 64 hex characters, distinct
9
+ * from `CMS_ENCRYPTION_KEY`. Encryption and decryption stream through Node's
10
+ * `crypto` so a multi-gigabyte dump never has to fit in memory. Decryption
11
+ * verifies the GCM tag before the output is considered valid; on any failure
12
+ * the partial output file is removed so a corrupt plaintext can never be
13
+ * mistaken for a good restore source.
14
+ */
15
+ import { createCipheriv, createDecipheriv, randomBytes, type CipherGCM } from 'node:crypto'
16
+ import { createReadStream, createWriteStream } from 'node:fs'
17
+ import { open, rm, stat } from 'node:fs/promises'
18
+ import { Readable, Transform, type TransformCallback } from 'node:stream'
19
+ import { pipeline } from 'node:stream/promises'
20
+
21
+ export const BACKUP_MAGIC: Buffer = Buffer.from('PRENTA1', 'ascii')
22
+ export const IV_LENGTH = 12
23
+ export const TAG_LENGTH = 16
24
+ export const KEY_LENGTH = 32
25
+ const ALGORITHM = 'aes-256-gcm'
26
+ const HEADER_LENGTH = BACKUP_MAGIC.length + IV_LENGTH
27
+
28
+ export class BackupKeyError extends Error {
29
+ constructor(message: string) {
30
+ super(message)
31
+ this.name = 'BackupKeyError'
32
+ }
33
+ }
34
+
35
+ /**
36
+ * Parse `BACKUP_ENCRYPTION_KEY`. Throws `BackupKeyError` with an actionable
37
+ * message when the value is missing or is not exactly 64 hex characters.
38
+ */
39
+ export function parseBackupKey(hex: string | undefined): Buffer {
40
+ const value = hex?.trim() ?? ''
41
+ if (!value) {
42
+ throw new BackupKeyError(
43
+ 'BACKUP_ENCRYPTION_KEY is not set. Generate one with `openssl rand -hex 32` and escrow it — backups cannot be decrypted without it.',
44
+ )
45
+ }
46
+ if (!/^[0-9a-fA-F]{64}$/.test(value)) {
47
+ throw new BackupKeyError(
48
+ `BACKUP_ENCRYPTION_KEY must be exactly 64 hex characters (32 bytes); got ${value.length} characters.`,
49
+ )
50
+ }
51
+ return Buffer.from(value, 'hex')
52
+ }
53
+
54
+ function assertKey(key: Buffer): void {
55
+ if (key.length !== KEY_LENGTH) {
56
+ throw new BackupKeyError(`Backup key must be ${KEY_LENGTH} bytes; got ${key.length}.`)
57
+ }
58
+ }
59
+
60
+ /** Emits header + ciphertext, then the auth tag on flush. */
61
+ class GcmEncryptStream extends Transform {
62
+ private headerSent = false
63
+
64
+ constructor(
65
+ private readonly cipher: CipherGCM,
66
+ private readonly header: Buffer,
67
+ ) {
68
+ super()
69
+ }
70
+
71
+ private sendHeader(): void {
72
+ if (!this.headerSent) {
73
+ this.headerSent = true
74
+ this.push(this.header)
75
+ }
76
+ }
77
+
78
+ override _transform(chunk: Buffer, _encoding: BufferEncoding, cb: TransformCallback): void {
79
+ this.sendHeader()
80
+ cb(null, this.cipher.update(chunk))
81
+ }
82
+
83
+ override _flush(cb: TransformCallback): void {
84
+ this.sendHeader()
85
+ try {
86
+ const last = this.cipher.final()
87
+ if (last.length > 0) this.push(last)
88
+ this.push(this.cipher.getAuthTag())
89
+ cb()
90
+ } catch (err) {
91
+ cb(err instanceof Error ? err : new Error(String(err)))
92
+ }
93
+ }
94
+ }
95
+
96
+ /**
97
+ * Encrypt `src` into `dest`. Returns the number of bytes written (header +
98
+ * ciphertext + tag). `dest` is truncated if it already exists.
99
+ */
100
+ export async function encryptFile(
101
+ src: string,
102
+ dest: string,
103
+ key: Buffer,
104
+ ): Promise<{ bytesWritten: number }> {
105
+ assertKey(key)
106
+ const iv = randomBytes(IV_LENGTH)
107
+ const cipher = createCipheriv(ALGORITHM, key, iv, { authTagLength: TAG_LENGTH })
108
+ const header = Buffer.concat([BACKUP_MAGIC, iv])
109
+ const out = createWriteStream(dest)
110
+ try {
111
+ await pipeline(createReadStream(src), new GcmEncryptStream(cipher, header), out)
112
+ } catch (err) {
113
+ await rm(dest, { force: true })
114
+ throw err
115
+ }
116
+ return { bytesWritten: out.bytesWritten }
117
+ }
118
+
119
+ class BackupFormatError extends Error {
120
+ constructor(message: string) {
121
+ super(message)
122
+ this.name = 'BackupFormatError'
123
+ }
124
+ }
125
+
126
+ async function readEnvelope(src: string): Promise<{ iv: Buffer; tag: Buffer; size: number }> {
127
+ const { size } = await stat(src)
128
+ if (size < HEADER_LENGTH + TAG_LENGTH) {
129
+ throw new BackupFormatError(`${src} is not a Prenta backup (file too short).`)
130
+ }
131
+ const handle = await open(src, 'r')
132
+ try {
133
+ const header = Buffer.alloc(HEADER_LENGTH)
134
+ await handle.read(header, 0, HEADER_LENGTH, 0)
135
+ if (!header.subarray(0, BACKUP_MAGIC.length).equals(BACKUP_MAGIC)) {
136
+ throw new BackupFormatError(`${src} is not a Prenta backup (missing PRENTA1 magic).`)
137
+ }
138
+ const tag = Buffer.alloc(TAG_LENGTH)
139
+ await handle.read(tag, 0, TAG_LENGTH, size - TAG_LENGTH)
140
+ return { iv: header.subarray(BACKUP_MAGIC.length), tag, size }
141
+ } finally {
142
+ await handle.close()
143
+ }
144
+ }
145
+
146
+ /**
147
+ * Decrypt `src` into `dest`, verifying the GCM auth tag. Throws when the
148
+ * file is not a Prenta envelope, or when the key is wrong / the ciphertext or
149
+ * tag were modified ("authentication failed"). On failure `dest` is removed.
150
+ */
151
+ export async function decryptFile(src: string, dest: string, key: Buffer): Promise<void> {
152
+ assertKey(key)
153
+ const { iv, tag, size } = await readEnvelope(src)
154
+ const decipher = createDecipheriv(ALGORITHM, key, iv, { authTagLength: TAG_LENGTH })
155
+ decipher.setAuthTag(tag)
156
+
157
+ // `end` is inclusive; an empty plaintext has no ciphertext bytes at all.
158
+ const ciphertextEnd = size - TAG_LENGTH - 1
159
+ const input =
160
+ ciphertextEnd < HEADER_LENGTH
161
+ ? Readable.from([])
162
+ : createReadStream(src, { start: HEADER_LENGTH, end: ciphertextEnd })
163
+
164
+ try {
165
+ await pipeline(input, decipher, createWriteStream(dest))
166
+ } catch (err) {
167
+ try {
168
+ await rm(dest, { force: true })
169
+ } catch {
170
+ // The original error is what the operator needs; a failed cleanup must not mask it.
171
+ }
172
+ if (isGcmAuthError(err)) {
173
+ throw new Error(
174
+ `Backup authentication failed for ${src}: wrong BACKUP_ENCRYPTION_KEY or the file was modified.`,
175
+ )
176
+ }
177
+ throw err
178
+ }
179
+ }
180
+
181
+ /**
182
+ * Node reports a GCM tag mismatch as "Unsupported state or unable to
183
+ * authenticate data" (OpenSSL codes `ERR_OSSL_*` on newer releases). Matched
184
+ * precisely so an unrelated error whose text happens to contain "auth" (a
185
+ * path, an ENOENT) is not reported as a wrong key.
186
+ */
187
+ function isGcmAuthError(err: unknown): boolean {
188
+ if (!(err instanceof Error)) return false
189
+ const code = (err as NodeJS.ErrnoException).code
190
+ if (typeof code === 'string' && code.startsWith('ERR_OSSL_')) return true
191
+ return /Unsupported state or unable to authenticate data/i.test(err.message)
192
+ }