@prenta/cli 0.16.5 → 0.17.1

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 +36 -27
  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 +73 -0
  9. package/dist/backup/common.d.ts.map +1 -0
  10. package/dist/backup/common.js +134 -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 +125 -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 +159 -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,125 @@
1
+ import { describe, expect, it } from 'vitest'
2
+
3
+ import { databaseIdentity, isSameDatabase, resolveDatabaseUrl } from '../backup/common.js'
4
+ import { FAKE_PASSWORD_2, pgUrl } from './fixtures/pg-url.js'
5
+
6
+ // Real Prisma Postgres direct URLs share the host `db.prisma.io` and the
7
+ // database name `postgres` across every database in a project; the
8
+ // per-database discriminator is the username. The guard is host-agnostic, so
9
+ // fixtures use `example.net` hosts to keep secret scanners quiet.
10
+ const PROD_USER = 'a1b2c3d4e5f6'
11
+ const SCRATCH_USER = 'f6e5d4c3b2a1'
12
+ const PROD = pgUrl({ user: PROD_USER, password: 'password', query: 'sslmode=require' })
13
+ const SCRATCH = pgUrl({ user: SCRATCH_USER, password: 'password', query: 'sslmode=require' })
14
+
15
+ describe('backup common: production guard URL comparison', () => {
16
+ describe('databaseIdentity', () => {
17
+ it('returns user + normalized host + database name for a postgres URL', () => {
18
+ expect(databaseIdentity(PROD)).toEqual({
19
+ user: PROD_USER,
20
+ host: 'db.example.net',
21
+ name: 'postgres',
22
+ })
23
+ })
24
+
25
+ it('decodes the username, lowercases the host and strips a pooled. label', () => {
26
+ expect(
27
+ databaseIdentity(
28
+ pgUrl({ user: 'us%40er', password: 'password', host: 'Pooled.DB.EXAMPLE.NET' }),
29
+ ),
30
+ ).toEqual({
31
+ user: 'us@er',
32
+ host: 'db.example.net',
33
+ name: 'postgres',
34
+ })
35
+ })
36
+
37
+ it('treats an empty path (or a bare slash) as the postgres database', () => {
38
+ const u = { user: 'u', password: 'password' }
39
+ expect(databaseIdentity(pgUrl({ ...u, database: null }))?.name).toBe('postgres')
40
+ expect(databaseIdentity(pgUrl({ ...u, database: '' }))?.name).toBe('postgres')
41
+ expect(databaseIdentity(pgUrl({ ...u, database: 'prod/' }))?.name).toBe('prod')
42
+ })
43
+
44
+ it('returns null for URLs it cannot parse or non-postgres schemes', () => {
45
+ expect(databaseIdentity('prisma+postgres://accelerate.prisma-data.net/?api_key=x')).toBeNull()
46
+ expect(databaseIdentity('not a url')).toBeNull()
47
+ expect(
48
+ databaseIdentity(
49
+ pgUrl({
50
+ protocol: 'mysql',
51
+ user: 'u',
52
+ password: 'password',
53
+ host: 'host',
54
+ port: null,
55
+ database: 'db',
56
+ }),
57
+ ),
58
+ ).toBeNull()
59
+ })
60
+ })
61
+
62
+ describe('isSameDatabase', () => {
63
+ it('prod direct vs scratch direct (different Prisma user, same host + db) → different', () => {
64
+ expect(isSameDatabase(PROD, SCRATCH)).toBe(false)
65
+ })
66
+
67
+ it('same database with a trailing slash, empty path, pooled. host, other password or query string → same', () => {
68
+ const other = { user: PROD_USER, password: FAKE_PASSWORD_2 }
69
+ const variants = [
70
+ pgUrl({ ...other, database: 'postgres/' }),
71
+ pgUrl({ ...other, database: '' }),
72
+ pgUrl({ ...other, database: null }),
73
+ pgUrl({ ...other, host: 'pooled.db.example.net' }),
74
+ pgUrl({ ...other, host: 'DB.EXAMPLE.NET', query: 'sslmode=require&x=1' }),
75
+ pgUrl({ user: PROD_USER, port: null }),
76
+ pgUrl({ user: PROD_USER, password: 'password', protocol: 'postgresql', port: 6543 }),
77
+ ]
78
+ for (const variant of variants) {
79
+ expect(isSameDatabase(PROD, variant), variant).toBe(true)
80
+ expect(isSameDatabase(variant, PROD), variant).toBe(true)
81
+ }
82
+ })
83
+
84
+ it('different host → different; different database name → different', () => {
85
+ expect(
86
+ isSameDatabase(
87
+ PROD,
88
+ pgUrl({ user: PROD_USER, password: 'password', host: 'db.example.com' }),
89
+ ),
90
+ ).toBe(false)
91
+ expect(
92
+ isSameDatabase(PROD, pgUrl({ user: PROD_USER, password: 'password', database: 'other' })),
93
+ ).toBe(false)
94
+ })
95
+
96
+ it('is false (never a false positive) when either URL is unparseable', () => {
97
+ expect(isSameDatabase(PROD, 'prisma+postgres://accelerate.prisma-data.net/?api_key=x')).toBe(
98
+ false,
99
+ )
100
+ expect(isSameDatabase('garbage', PROD)).toBe(false)
101
+ })
102
+ })
103
+ })
104
+
105
+ describe('resolveDatabaseUrl', () => {
106
+ // The first production run failed with invalid sslmode value: "require\r\n":
107
+ // the Vercel env value had been pasted with a trailing newline. Secrets are
108
+ // opaque to the operator, so the CLI must not let stray whitespace through.
109
+ it('trims surrounding whitespace, including CR LF, from env URLs', () => {
110
+ const url = pgUrl({ password: 'password', query: 'sslmode=require' })
111
+ const direct = resolveDatabaseUrl({ DIRECT_DATABASE_URL: `${url}\r\n` })
112
+ expect(direct).toEqual({ url, source: 'DIRECT_DATABASE_URL' })
113
+ const pooled = resolveDatabaseUrl({ DATABASE_URL: ` ${url}\n` })
114
+ expect(pooled).toEqual({ url, source: 'DATABASE_URL' })
115
+ })
116
+
117
+ it('treats a whitespace-only value as unset', () => {
118
+ const url = pgUrl({ password: 'password' })
119
+ expect(resolveDatabaseUrl({ DIRECT_DATABASE_URL: ' \r\n', DATABASE_URL: url })).toEqual({
120
+ url,
121
+ source: 'DATABASE_URL',
122
+ })
123
+ expect(resolveDatabaseUrl({ DIRECT_DATABASE_URL: '\n' })).toBeNull()
124
+ })
125
+ })
@@ -0,0 +1,197 @@
1
+ import { randomBytes } from 'node:crypto'
2
+ import { mkdtemp, readFile, rm, stat, writeFile } from 'node:fs/promises'
3
+ import { existsSync } from 'node:fs'
4
+ import { tmpdir } from 'node:os'
5
+ import path from 'node:path'
6
+ import { afterEach, beforeEach, describe, expect, it } from 'vitest'
7
+
8
+ import {
9
+ BACKUP_MAGIC,
10
+ decryptFile,
11
+ encryptFile,
12
+ IV_LENGTH,
13
+ parseBackupKey,
14
+ TAG_LENGTH,
15
+ } from '../backup/crypto.js'
16
+
17
+ const KEY_HEX = 'a'.repeat(64)
18
+ const OTHER_KEY_HEX = 'b'.repeat(64)
19
+
20
+ describe('backup crypto (AES-256-GCM file envelope)', () => {
21
+ let dir: string
22
+
23
+ beforeEach(async () => {
24
+ dir = await mkdtemp(path.join(tmpdir(), 'prenta-backup-crypto-'))
25
+ })
26
+
27
+ afterEach(async () => {
28
+ await rm(dir, { recursive: true, force: true })
29
+ })
30
+
31
+ describe('parseBackupKey', () => {
32
+ it('accepts a 64-char hex string (32 bytes) in either case', () => {
33
+ expect(parseBackupKey(KEY_HEX)).toHaveLength(32)
34
+ expect(parseBackupKey('AbCd'.repeat(16))).toHaveLength(32)
35
+ })
36
+
37
+ it('rejects a missing key with a hint naming the env var', () => {
38
+ expect(() => parseBackupKey(undefined)).toThrow(/BACKUP_ENCRYPTION_KEY/)
39
+ expect(() => parseBackupKey('')).toThrow(/BACKUP_ENCRYPTION_KEY/)
40
+ })
41
+
42
+ it('rejects wrong length and non-hex input', () => {
43
+ expect(() => parseBackupKey('a'.repeat(63))).toThrow(/64 hex/)
44
+ expect(() => parseBackupKey('a'.repeat(66))).toThrow(/64 hex/)
45
+ expect(() => parseBackupKey('z'.repeat(64))).toThrow(/64 hex/)
46
+ })
47
+ })
48
+
49
+ describe('encryptFile / decryptFile', () => {
50
+ it('round-trips arbitrary bytes, including multi-chunk inputs', async () => {
51
+ const src = path.join(dir, 'plain.bin')
52
+ const enc = path.join(dir, 'plain.bin.enc')
53
+ const out = path.join(dir, 'plain.out')
54
+ // > 64 KiB so the stream path sees several chunks.
55
+ const payload = randomBytes(200_000)
56
+ await writeFile(src, payload)
57
+
58
+ await encryptFile(src, enc, parseBackupKey(KEY_HEX))
59
+ await decryptFile(enc, out, parseBackupKey(KEY_HEX))
60
+
61
+ expect(Buffer.compare(await readFile(out), payload)).toBe(0)
62
+ })
63
+
64
+ it('round-trips an empty file', async () => {
65
+ const src = path.join(dir, 'empty')
66
+ const enc = path.join(dir, 'empty.enc')
67
+ const out = path.join(dir, 'empty.out')
68
+ await writeFile(src, Buffer.alloc(0))
69
+
70
+ await encryptFile(src, enc, parseBackupKey(KEY_HEX))
71
+ const encSize = (await stat(enc)).size
72
+ expect(encSize).toBe(BACKUP_MAGIC.length + IV_LENGTH + TAG_LENGTH)
73
+
74
+ await decryptFile(enc, out, parseBackupKey(KEY_HEX))
75
+ expect((await readFile(out)).length).toBe(0)
76
+ })
77
+
78
+ it('writes the documented layout: PRENTA1 magic + 12-byte IV + ciphertext + 16-byte tag', async () => {
79
+ const src = path.join(dir, 'layout')
80
+ const enc = path.join(dir, 'layout.enc')
81
+ const payload = Buffer.from('hello backups')
82
+ await writeFile(src, payload)
83
+
84
+ await encryptFile(src, enc, parseBackupKey(KEY_HEX))
85
+ const bytes = await readFile(enc)
86
+
87
+ expect(BACKUP_MAGIC.toString('ascii')).toBe('PRENTA1')
88
+ expect(BACKUP_MAGIC.length).toBe(7)
89
+ expect(IV_LENGTH).toBe(12)
90
+ expect(TAG_LENGTH).toBe(16)
91
+ expect(bytes.subarray(0, 7).toString('ascii')).toBe('PRENTA1')
92
+ expect(bytes.length).toBe(7 + 12 + payload.length + 16)
93
+ // Ciphertext must not be the plaintext.
94
+ expect(bytes.subarray(19, 19 + payload.length).equals(payload)).toBe(false)
95
+ })
96
+
97
+ it('uses a fresh random IV per call', async () => {
98
+ const src = path.join(dir, 'iv')
99
+ await writeFile(src, 'same input')
100
+ const a = path.join(dir, 'a.enc')
101
+ const b = path.join(dir, 'b.enc')
102
+ await encryptFile(src, a, parseBackupKey(KEY_HEX))
103
+ await encryptFile(src, b, parseBackupKey(KEY_HEX))
104
+ const ivA = (await readFile(a)).subarray(7, 19)
105
+ const ivB = (await readFile(b)).subarray(7, 19)
106
+ expect(ivA.equals(ivB)).toBe(false)
107
+ })
108
+
109
+ it('detects a flipped ciphertext byte (auth failure) and leaves no partial output', async () => {
110
+ const src = path.join(dir, 'tamper')
111
+ const enc = path.join(dir, 'tamper.enc')
112
+ const out = path.join(dir, 'tamper.out')
113
+ await writeFile(src, randomBytes(4096))
114
+ await encryptFile(src, enc, parseBackupKey(KEY_HEX))
115
+
116
+ const bytes = await readFile(enc)
117
+ bytes[100] = bytes[100]! ^ 0xff
118
+ await writeFile(enc, bytes)
119
+
120
+ await expect(decryptFile(enc, out, parseBackupKey(KEY_HEX))).rejects.toThrow(
121
+ /authentication failed/i,
122
+ )
123
+ expect(existsSync(out)).toBe(false)
124
+ })
125
+
126
+ it('detects a flipped auth-tag byte', async () => {
127
+ const src = path.join(dir, 'tag')
128
+ const enc = path.join(dir, 'tag.enc')
129
+ const out = path.join(dir, 'tag.out')
130
+ await writeFile(src, 'payload')
131
+ await encryptFile(src, enc, parseBackupKey(KEY_HEX))
132
+
133
+ const bytes = await readFile(enc)
134
+ const last = bytes.length - 1
135
+ bytes[last] = bytes[last]! ^ 0x01
136
+ await writeFile(enc, bytes)
137
+
138
+ await expect(decryptFile(enc, out, parseBackupKey(KEY_HEX))).rejects.toThrow(
139
+ /authentication failed/i,
140
+ )
141
+ })
142
+
143
+ it('treats a truncated envelope as an authentication failure and leaves no partial file', async () => {
144
+ const src = path.join(dir, 'trunc')
145
+ const enc = path.join(dir, 'trunc.enc')
146
+ const out = path.join(dir, 'trunc.out')
147
+ await writeFile(src, randomBytes(50_000))
148
+ await encryptFile(src, enc, parseBackupKey(KEY_HEX))
149
+
150
+ // Lose the last 1000 bytes (tag + ciphertext tail), as an interrupted download would.
151
+ const bytes = await readFile(enc)
152
+ await writeFile(enc, bytes.subarray(0, bytes.length - 1000))
153
+
154
+ await expect(decryptFile(enc, out, parseBackupKey(KEY_HEX))).rejects.toThrow(
155
+ /authentication failed/i,
156
+ )
157
+ expect(existsSync(out)).toBe(false)
158
+ })
159
+
160
+ it('does not mistake an ordinary error mentioning "auth" for a GCM failure', async () => {
161
+ const src = path.join(dir, 'authword')
162
+ const enc = path.join(dir, 'authword.enc')
163
+ await writeFile(src, 'payload')
164
+ await encryptFile(src, enc, parseBackupKey(KEY_HEX))
165
+ // Destination inside a path that does not exist → ENOENT from the write stream.
166
+ const out = path.join(dir, 'no-such-author-dir', 'x.out')
167
+ await expect(decryptFile(enc, out, parseBackupKey(KEY_HEX))).rejects.toThrow(/ENOENT/)
168
+ })
169
+
170
+ it('fails with the wrong key', async () => {
171
+ const src = path.join(dir, 'wrongkey')
172
+ const enc = path.join(dir, 'wrongkey.enc')
173
+ const out = path.join(dir, 'wrongkey.out')
174
+ await writeFile(src, 'secret')
175
+ await encryptFile(src, enc, parseBackupKey(KEY_HEX))
176
+
177
+ await expect(decryptFile(enc, out, parseBackupKey(OTHER_KEY_HEX))).rejects.toThrow(
178
+ /authentication failed/i,
179
+ )
180
+ })
181
+
182
+ it('rejects files without the PRENTA1 magic or that are too short', async () => {
183
+ const bogus = path.join(dir, 'bogus.enc')
184
+ const out = path.join(dir, 'bogus.out')
185
+ await writeFile(bogus, Buffer.concat([Buffer.from('NOTPREN'), randomBytes(40)]))
186
+ await expect(decryptFile(bogus, out, parseBackupKey(KEY_HEX))).rejects.toThrow(
187
+ /not a Prenta backup/i,
188
+ )
189
+
190
+ const short = path.join(dir, 'short.enc')
191
+ await writeFile(short, Buffer.from('PRENTA1'))
192
+ await expect(decryptFile(short, out, parseBackupKey(KEY_HEX))).rejects.toThrow(
193
+ /not a Prenta backup/i,
194
+ )
195
+ })
196
+ })
197
+ })
@@ -0,0 +1,189 @@
1
+ import { createHash } from 'node:crypto'
2
+ import { mkdtemp, rm, writeFile } from 'node:fs/promises'
3
+ import { tmpdir } from 'node:os'
4
+ import path from 'node:path'
5
+ import { afterEach, describe, expect, it } from 'vitest'
6
+
7
+ import {
8
+ buildManifest,
9
+ compareStamps,
10
+ describeDatabase,
11
+ DUMP_EXTENSION,
12
+ isOlderThan,
13
+ MANIFEST_EXTENSION,
14
+ MANIFEST_VERSION,
15
+ manifestPathnameFor,
16
+ parseManifest,
17
+ parseStamp,
18
+ sha256File,
19
+ stampFor,
20
+ stampToDate,
21
+ } from '../backup/manifest.js'
22
+ import { FAKE_PASSWORD_1, pgUrl } from './fixtures/pg-url.js'
23
+
24
+ describe('backup manifest', () => {
25
+ const temps: string[] = []
26
+ afterEach(async () => {
27
+ await Promise.all(temps.map((t) => rm(t, { recursive: true, force: true })))
28
+ temps.length = 0
29
+ })
30
+
31
+ describe('stampFor / parseStamp / stampToDate', () => {
32
+ it('formats UTC as YYYY-MM-DDTHHmmssZ with zero padding', () => {
33
+ expect(stampFor(new Date('2026-09-18T03:30:00.000Z'))).toBe('2026-09-18T033000Z')
34
+ expect(stampFor(new Date('2026-01-05T00:00:09.999Z'))).toBe('2026-01-05T000009Z')
35
+ })
36
+
37
+ it('extracts the stamp from dump and manifest pathnames (any prefix)', () => {
38
+ expect(parseStamp('backups/db/2026-09-18T033000Z.dump.enc')).toBe('2026-09-18T033000Z')
39
+ expect(parseStamp('backups/db/2026-09-18T033000Z.manifest.json')).toBe('2026-09-18T033000Z')
40
+ expect(parseStamp('C:\\tmp\\2026-09-18T033000Z.dump.enc')).toBe('2026-09-18T033000Z')
41
+ expect(parseStamp('2026-09-18T033000Z')).toBe('2026-09-18T033000Z')
42
+ })
43
+
44
+ it('returns null for non-backup pathnames', () => {
45
+ expect(parseStamp('backups/db/readme.txt')).toBeNull()
46
+ expect(parseStamp('backups/db/2026-09-18.dump.enc')).toBeNull()
47
+ expect(parseStamp('')).toBeNull()
48
+ })
49
+
50
+ it('round-trips a stamp back to the UTC instant', () => {
51
+ const date = new Date('2026-09-18T03:30:00.000Z')
52
+ expect(stampToDate(stampFor(date)).getTime()).toBe(date.getTime())
53
+ })
54
+
55
+ it('sorts stamps chronologically', () => {
56
+ const stamps = ['2026-09-18T033000Z', '2025-12-31T235959Z', '2026-09-18T033001Z']
57
+ expect([...stamps].sort(compareStamps)).toEqual([
58
+ '2025-12-31T235959Z',
59
+ '2026-09-18T033000Z',
60
+ '2026-09-18T033001Z',
61
+ ])
62
+ })
63
+ })
64
+
65
+ describe('isOlderThan (retention cut-off)', () => {
66
+ const now = new Date('2026-09-30T03:30:00.000Z')
67
+
68
+ it('keeps a backup exactly on the boundary day', () => {
69
+ expect(isOlderThan('2026-08-31T033000Z', 30, now)).toBe(false)
70
+ })
71
+
72
+ it('keeps everything newer than the cut-off', () => {
73
+ expect(isOlderThan('2026-09-29T033000Z', 30, now)).toBe(false)
74
+ expect(isOlderThan('2026-08-31T033001Z', 30, now)).toBe(false)
75
+ })
76
+
77
+ it('prunes day 31 (one second past the boundary and older)', () => {
78
+ expect(isOlderThan('2026-08-31T032959Z', 30, now)).toBe(true)
79
+ expect(isOlderThan('2026-08-30T033000Z', 30, now)).toBe(true)
80
+ expect(isOlderThan('2020-01-01T000000Z', 30, now)).toBe(true)
81
+ })
82
+
83
+ it('never prunes when retention is not a positive number', () => {
84
+ expect(isOlderThan('2020-01-01T000000Z', 0, now)).toBe(false)
85
+ expect(isOlderThan('2020-01-01T000000Z', -5, now)).toBe(false)
86
+ expect(isOlderThan('2020-01-01T000000Z', Number.NaN, now)).toBe(false)
87
+ })
88
+ })
89
+
90
+ describe('pathnames', () => {
91
+ it('derives the manifest pathname from a dump pathname', () => {
92
+ expect(manifestPathnameFor('backups/db/2026-09-18T033000Z.dump.enc')).toBe(
93
+ 'backups/db/2026-09-18T033000Z.manifest.json',
94
+ )
95
+ expect(DUMP_EXTENSION).toBe('.dump.enc')
96
+ expect(MANIFEST_EXTENSION).toBe('.manifest.json')
97
+ })
98
+ })
99
+
100
+ describe('describeDatabase', () => {
101
+ it('extracts host + database name and never the password', () => {
102
+ const described = describeDatabase(
103
+ pgUrl({
104
+ user: 'user',
105
+ password: FAKE_PASSWORD_1,
106
+ database: 'prod_db',
107
+ query: 'sslmode=require',
108
+ }),
109
+ )
110
+ expect(described).toEqual({ host: 'db.example.net', name: 'prod_db' })
111
+ expect(JSON.stringify(described)).not.toContain(FAKE_PASSWORD_1)
112
+ })
113
+
114
+ it('accepts postgresql:// and normalizes a missing database name to postgres (libpq default)', () => {
115
+ const base = { protocol: 'postgresql', user: 'u', password: 'password', host: 'localhost' }
116
+ expect(describeDatabase(pgUrl({ ...base, port: null, database: '' }))).toEqual({
117
+ host: 'localhost',
118
+ name: 'postgres',
119
+ })
120
+ expect(describeDatabase(pgUrl({ ...base, database: null })).name).toBe('postgres')
121
+ // Same normalization as the production guard: trailing slash dropped, escapes decoded.
122
+ expect(describeDatabase(pgUrl({ ...base, database: 'prod/' })).name).toBe('prod')
123
+ expect(describeDatabase(pgUrl({ ...base, database: 'my%20db' })).name).toBe('my db')
124
+ })
125
+ })
126
+
127
+ describe('sha256File', () => {
128
+ it('hashes file contents as lowercase hex', async () => {
129
+ const dir = await mkdtemp(path.join(tmpdir(), 'prenta-manifest-'))
130
+ temps.push(dir)
131
+ const file = path.join(dir, 'x.bin')
132
+ const payload = Buffer.from('hash me')
133
+ await writeFile(file, payload)
134
+ const expected = createHash('sha256').update(payload).digest('hex')
135
+ expect(await sha256File(file)).toBe(expected)
136
+ expect(await sha256File(file)).toMatch(/^[0-9a-f]{64}$/)
137
+ })
138
+ })
139
+
140
+ describe('buildManifest / parseManifest', () => {
141
+ const input = {
142
+ createdAt: new Date('2026-09-18T03:30:00.000Z'),
143
+ databaseUrl: pgUrl({
144
+ user: 'user',
145
+ password: 'password',
146
+ database: 'prod',
147
+ query: 'sslmode=require',
148
+ }),
149
+ pgDumpVersion: '17.2',
150
+ sizeBytes: 12345,
151
+ sha256: 'ab'.repeat(32),
152
+ tables: [
153
+ { schema: 'public', name: 'prenta_documents', rows: 120 },
154
+ { schema: 'public', name: 'prenta_users', rows: 3 },
155
+ ],
156
+ }
157
+
158
+ it('produces the documented shape and records row counts as estimates', () => {
159
+ const manifest = buildManifest(input)
160
+ expect(manifest).toEqual({
161
+ version: MANIFEST_VERSION,
162
+ createdAt: '2026-09-18T03:30:00.000Z',
163
+ stamp: '2026-09-18T033000Z',
164
+ database: { host: 'db.example.net', name: 'prod' },
165
+ pgDumpVersion: '17.2',
166
+ sizeBytes: 12345,
167
+ sha256: 'ab'.repeat(32),
168
+ rowCounts: 'estimate',
169
+ tables: input.tables,
170
+ })
171
+ expect(MANIFEST_VERSION).toBe(1)
172
+ expect(JSON.stringify(manifest)).not.toContain('password')
173
+ })
174
+
175
+ it('parses its own JSON output', () => {
176
+ const manifest = buildManifest(input)
177
+ expect(parseManifest(JSON.parse(JSON.stringify(manifest)))).toEqual(manifest)
178
+ })
179
+
180
+ it('rejects malformed manifests with a clear reason', () => {
181
+ expect(() => parseManifest(null)).toThrow(/manifest/i)
182
+ expect(() => parseManifest({ version: 2 })).toThrow(/version/i)
183
+ expect(() => parseManifest({ ...buildManifest(input), sha256: 'nope' })).toThrow(/sha256/i)
184
+ expect(() =>
185
+ parseManifest({ ...buildManifest(input), tables: [{ schema: 'public' }] }),
186
+ ).toThrow(/tables/i)
187
+ })
188
+ })
189
+ })