@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,267 @@
1
+ /**
2
+ * Thin wrappers around the PostgreSQL client tools used by `db:backup` /
3
+ * `db:restore`: `pg_dump`, `pg_restore` and `psql`.
4
+ *
5
+ * Credentials: the connection URL is always handed over via `--dbname=` and
6
+ * never as free-standing argv, and the password is stripped from that URL and
7
+ * passed through `PGPASSWORD` in the child's environment so it does not show
8
+ * up in process listings or in the tool's own error output. Captured stderr
9
+ * is redacted again before it reaches an error message.
10
+ *
11
+ * Row counts: `@prenta/cli` has no Postgres client dependency (see
12
+ * package.json) and the backup commands should not add one for two queries.
13
+ * The pre-dump estimate (`pg_class.reltuples`) and the post-restore exact
14
+ * `count(*)` therefore run through `psql --tuples-only --no-align`, which
15
+ * ships with the same `postgresql-client` package as `pg_dump`.
16
+ *
17
+ * Every function takes an injectable `spawnImpl` so unit tests never run a
18
+ * real binary.
19
+ */
20
+ import { spawn } from 'node:child_process';
21
+ /** Real `child_process.spawn` adapted to `SpawnImpl` (stdin closed, stdout/stderr piped). */
22
+ export const nodeSpawn = (command, args, options) => spawn(command, [...args], { ...options, stdio: ['ignore', 'pipe', 'pipe'] });
23
+ const defaultSpawn = nodeSpawn;
24
+ export class PgToolError extends Error {
25
+ tool;
26
+ exitCode;
27
+ constructor(message, tool, exitCode) {
28
+ super(message);
29
+ this.tool = tool;
30
+ this.exitCode = exitCode;
31
+ this.name = 'PgToolError';
32
+ }
33
+ }
34
+ /**
35
+ * Split the password out of a connection URL (decoded, ready for PGPASSWORD).
36
+ *
37
+ * WHATWG `URL.password` is still percent-encoded (`p%40ss`, not `p@ss`), so
38
+ * exactly one `decodeURIComponent` is right. A literal `%` that is not a
39
+ * valid escape (`100%legit`) throws `URIError`; libpq would have used the
40
+ * raw bytes, so the raw value is passed through unchanged.
41
+ */
42
+ export function splitCredentials(url) {
43
+ const parsed = new URL(url);
44
+ if (!parsed.password)
45
+ return { url };
46
+ const password = decodePasswordComponent(parsed.password);
47
+ parsed.password = '';
48
+ return { url: parsed.toString(), password };
49
+ }
50
+ function decodePasswordComponent(encoded) {
51
+ try {
52
+ return decodeURIComponent(encoded);
53
+ }
54
+ catch (err) {
55
+ if (err instanceof URIError)
56
+ return encoded;
57
+ throw err;
58
+ }
59
+ }
60
+ /** Connection URL safe to print: password replaced by `***`. */
61
+ export function redactUrl(url) {
62
+ try {
63
+ const parsed = new URL(url);
64
+ if (parsed.password)
65
+ parsed.password = '***';
66
+ return parsed.toString();
67
+ }
68
+ catch {
69
+ return '<invalid database url>';
70
+ }
71
+ }
72
+ /** Secrets shorter than this are not redacted: replacing every "ab" would shred the message. */
73
+ const MIN_REDACT_LENGTH = 4;
74
+ function redactText(text, secrets) {
75
+ let out = text;
76
+ for (const secret of secrets) {
77
+ if (!secret || secret.length < MIN_REDACT_LENGTH)
78
+ continue;
79
+ out = out.split(secret).join('***');
80
+ const encoded = encodeURIComponent(secret);
81
+ if (encoded !== secret)
82
+ out = out.split(encoded).join('***');
83
+ }
84
+ return out;
85
+ }
86
+ function collect(stream) {
87
+ return new Promise((resolve) => {
88
+ if (!stream)
89
+ return resolve('');
90
+ let out = '';
91
+ stream.on('data', (chunk) => {
92
+ out += String(chunk);
93
+ });
94
+ stream.on('end', () => resolve(out));
95
+ stream.on('error', () => resolve(out));
96
+ });
97
+ }
98
+ function run(spawnImpl, command, args, env) {
99
+ return new Promise((resolve, reject) => {
100
+ const child = spawnImpl(command, args, { env });
101
+ const stdout = collect(child.stdout);
102
+ const stderr = collect(child.stderr);
103
+ child.on('error', (err) => reject(err));
104
+ child.on('close', (code) => {
105
+ void Promise.all([stdout, stderr]).then(([out, errText]) => resolve({ code, stdout: out, stderr: errText }));
106
+ });
107
+ });
108
+ }
109
+ function installHint(name, minMajor) {
110
+ const versioned = minMajor > 0;
111
+ return (`Install PostgreSQL ${versioned ? `${minMajor} ` : ''}client tools (provides ${name}): ` +
112
+ `Debian/Ubuntu \`apt-get install postgresql-client${versioned ? `-${minMajor}` : ''}\` (apt.postgresql.org), ` +
113
+ `macOS \`brew install libpq && brew link --force libpq\`, ` +
114
+ `Windows: https://www.postgresql.org/download/windows/ (command-line tools only).`);
115
+ }
116
+ /** Probe `<name> --version` and require `major >= minMajor` (`0` = any version). */
117
+ export async function checkPgTool(name, minMajor = 17, spawnImpl = defaultSpawn) {
118
+ let result;
119
+ try {
120
+ result = await run(spawnImpl, name, ['--version'], process.env);
121
+ }
122
+ catch (err) {
123
+ const detail = err instanceof Error ? err.message : String(err);
124
+ return {
125
+ ok: false,
126
+ reason: 'missing',
127
+ detail: `${name} not found on PATH (${detail}). ${installHint(name, minMajor)}`,
128
+ };
129
+ }
130
+ if (result.code !== 0) {
131
+ return {
132
+ ok: false,
133
+ reason: 'missing',
134
+ detail: `${name} --version exited with ${result.code ?? 'signal'}: ${result.stderr.trim()}. ${installHint(name, minMajor)}`,
135
+ };
136
+ }
137
+ const match = result.stdout.match(/(\d+)(?:\.(\d+))?(?:\.(\d+))?/);
138
+ if (!match?.[1]) {
139
+ return {
140
+ ok: false,
141
+ reason: 'unparseable',
142
+ detail: `Could not parse a version from \`${name} --version\` output: ${result.stdout.trim()}`,
143
+ };
144
+ }
145
+ const major = Number(match[1]);
146
+ const version = match[0];
147
+ if (major < minMajor) {
148
+ return {
149
+ ok: false,
150
+ reason: 'too-old',
151
+ detail: `${name} ${version} is too old; version ${minMajor} or newer is required (Prisma Postgres runs PostgreSQL ${minMajor}). ${installHint(name, minMajor)}`,
152
+ };
153
+ }
154
+ return { ok: true, version, major };
155
+ }
156
+ async function runWithUrl(spawnImpl, tool, buildArgs, databaseUrl, baseEnv) {
157
+ const { url: safeUrl, password } = splitCredentials(databaseUrl);
158
+ const env = password === undefined ? baseEnv : { ...baseEnv, PGPASSWORD: password };
159
+ let result;
160
+ try {
161
+ result = await run(spawnImpl, tool, buildArgs(safeUrl), env);
162
+ }
163
+ catch (err) {
164
+ const detail = err instanceof Error ? err.message : String(err);
165
+ throw new PgToolError(`${tool} could not be started: ${redactText(detail, [password])}`, tool, null);
166
+ }
167
+ if (result.code !== 0) {
168
+ const stderr = redactText(result.stderr.trim(), [password]);
169
+ throw new PgToolError(`${tool} exited with code ${result.code ?? 'signal'}${stderr ? `:\n${stderr}` : ''}`, tool, result.code);
170
+ }
171
+ return { ...result, stderr: redactText(result.stderr, [password]) };
172
+ }
173
+ /** `pg_dump --format=custom --no-owner --no-privileges --file=<out> --dbname=<url>` */
174
+ export async function runPgDump(databaseUrl, outPath, spawnImpl = defaultSpawn, baseEnv = process.env) {
175
+ const result = await runWithUrl(spawnImpl, 'pg_dump', (safeUrl) => [
176
+ '--format=custom',
177
+ '--no-owner',
178
+ '--no-privileges',
179
+ `--file=${outPath}`,
180
+ `--dbname=${safeUrl}`,
181
+ ], databaseUrl, baseEnv);
182
+ return { stderr: result.stderr };
183
+ }
184
+ /**
185
+ * `pg_restore --clean --if-exists --no-owner --no-privileges --no-comments --single-transaction --exit-on-error --dbname=<url> <in>`
186
+ *
187
+ * `--clean` only drops objects that are present in the dump; anything else
188
+ * in the target is left alone. `--single-transaction --exit-on-error` makes
189
+ * the restore atomic: the first error rolls the whole thing back and the
190
+ * target is exactly as it was (DR-sized dumps fit one transaction fine).
191
+ * `--no-comments` drops `COMMENT ON EXTENSION …` statements: pg_dump emits
192
+ * them for `plpgsql` / `pg_trgm`, they need extension ownership that a managed
193
+ * Postgres app role does not have, and under `--exit-on-error` that single
194
+ * harmless failure would otherwise abort the whole restore. The schema
195
+ * carries no comments of its own.
196
+ */
197
+ export async function runPgRestore(databaseUrl, inPath, spawnImpl = defaultSpawn, baseEnv = process.env) {
198
+ const result = await runWithUrl(spawnImpl, 'pg_restore', (safeUrl) => [
199
+ '--clean',
200
+ '--if-exists',
201
+ '--no-owner',
202
+ '--no-privileges',
203
+ '--no-comments',
204
+ '--single-transaction',
205
+ '--exit-on-error',
206
+ `--dbname=${safeUrl}`,
207
+ inPath,
208
+ ], databaseUrl, baseEnv);
209
+ return { stderr: result.stderr };
210
+ }
211
+ const FIELD_SEPARATOR = '\t';
212
+ async function runPsql(databaseUrl, sql, spawnImpl, baseEnv) {
213
+ const result = await runWithUrl(spawnImpl, 'psql', (safeUrl) => [
214
+ '--no-psqlrc',
215
+ '--quiet',
216
+ '--tuples-only',
217
+ '--no-align',
218
+ `--field-separator=${FIELD_SEPARATOR}`,
219
+ '--set=ON_ERROR_STOP=1',
220
+ `--command=${sql}`,
221
+ `--dbname=${safeUrl}`,
222
+ ], databaseUrl, baseEnv);
223
+ return result.stdout
224
+ .split(/\r?\n/)
225
+ .filter((line) => line.trim().length > 0)
226
+ .map((line) => line.split(FIELD_SEPARATOR));
227
+ }
228
+ function parseCount(raw) {
229
+ const n = Number(raw);
230
+ return Number.isFinite(n) && n > 0 ? Math.trunc(n) : 0;
231
+ }
232
+ const ESTIMATE_SQL = 'SELECT n.nspname, c.relname, GREATEST(c.reltuples, 0)::bigint ' +
233
+ 'FROM pg_class c JOIN pg_namespace n ON n.oid = c.relnamespace ' +
234
+ "WHERE c.relkind IN ('r', 'p') " +
235
+ "AND n.nspname NOT IN ('pg_catalog', 'information_schema') " +
236
+ "AND n.nspname NOT LIKE 'pg_toast%' " +
237
+ 'ORDER BY 1, 2';
238
+ /**
239
+ * Planner row estimates for every user table (`pg_class.reltuples`; no table
240
+ * scans). Never-analyzed tables report -1 in PostgreSQL 14+; clamped to 0.
241
+ */
242
+ export async function estimateTableRows(databaseUrl, spawnImpl = defaultSpawn, baseEnv = process.env) {
243
+ const rows = await runPsql(databaseUrl, ESTIMATE_SQL, spawnImpl, baseEnv);
244
+ return rows
245
+ .filter((cols) => cols.length >= 3)
246
+ .map((cols) => ({ schema: cols[0], name: cols[1], rows: parseCount(cols[2]) }));
247
+ }
248
+ function quoteIdent(name) {
249
+ return `"${name.replace(/"/g, '""')}"`;
250
+ }
251
+ function quoteLiteral(value) {
252
+ return `'${value.replace(/'/g, "''")}'`;
253
+ }
254
+ /** Exact `count(*)` for each table, in one round-trip (post-restore report). */
255
+ export async function countTableRows(databaseUrl, tables, spawnImpl = defaultSpawn, baseEnv = process.env) {
256
+ if (tables.length === 0)
257
+ return [];
258
+ const sql = tables
259
+ .map((t) => `SELECT ${quoteLiteral(t.schema)}, ${quoteLiteral(t.name)}, count(*) ` +
260
+ `FROM ${quoteIdent(t.schema)}.${quoteIdent(t.name)}`)
261
+ .join(' UNION ALL ');
262
+ const rows = await runPsql(databaseUrl, sql, spawnImpl, baseEnv);
263
+ return rows
264
+ .filter((cols) => cols.length >= 3)
265
+ .map((cols) => ({ schema: cols[0], name: cols[1], rows: parseCount(cols[2]) }));
266
+ }
267
+ //# sourceMappingURL=pg-tools.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"pg-tools.js","sourceRoot":"","sources":["../../src/backup/pg-tools.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;GAkBG;AACH,OAAO,EAAE,KAAK,EAAE,MAAM,oBAAoB,CAAA;AAsB1C,6FAA6F;AAC7F,MAAM,CAAC,MAAM,SAAS,GAAc,CAAC,OAAO,EAAE,IAAI,EAAE,OAAO,EAAE,EAAE,CAC7D,KAAK,CAAC,OAAO,EAAE,CAAC,GAAG,IAAI,CAAC,EAAE,EAAE,GAAG,OAAO,EAAE,KAAK,EAAE,CAAC,QAAQ,EAAE,MAAM,EAAE,MAAM,CAAC,EAAE,CAAC,CAAA;AAE9E,MAAM,YAAY,GAAG,SAAS,CAAA;AAI9B,MAAM,OAAO,WAAY,SAAQ,KAAK;IAGzB;IACA;IAHX,YACE,OAAe,EACN,IAAgB,EAChB,QAAuB;QAEhC,KAAK,CAAC,OAAO,CAAC,CAAA;QAHL,SAAI,GAAJ,IAAI,CAAY;QAChB,aAAQ,GAAR,QAAQ,CAAe;QAGhC,IAAI,CAAC,IAAI,GAAG,aAAa,CAAA;IAC3B,CAAC;CACF;AAED;;;;;;;GAOG;AACH,MAAM,UAAU,gBAAgB,CAAC,GAAW;IAC1C,MAAM,MAAM,GAAG,IAAI,GAAG,CAAC,GAAG,CAAC,CAAA;IAC3B,IAAI,CAAC,MAAM,CAAC,QAAQ;QAAE,OAAO,EAAE,GAAG,EAAE,CAAA;IACpC,MAAM,QAAQ,GAAG,uBAAuB,CAAC,MAAM,CAAC,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C,OAAO,CAAC,IAAI,EAAE,IAAI,CAAC,GAAG,CAAA;AACzC,CAAC;AAED,gFAAgF;AAChF,MAAM,CAAC,KAAK,UAAU,cAAc,CAClC,WAAmB,EACnB,MAA+D,EAC/D,YAAuB,YAAY,EACnC,UAA6B,OAAO,CAAC,GAAG;IAExC,IAAI,MAAM,CAAC,MAAM,KAAK,CAAC;QAAE,OAAO,EAAE,CAAA;IAClC,MAAM,GAAG,GAAG,MAAM;SACf,GAAG,CACF,CAAC,CAAC,EAAE,EAAE,CACJ,UAAU,YAAY,CAAC,CAAC,CAAC,MAAM,CAAC,KAAK,YAAY,CAAC,CAAC,CAAC,IAAI,CAAC,aAAa;QACtE,QAAQ,UAAU,CAAC,CAAC,CAAC,MAAM,CAAC,IAAI,UAAU,CAAC,CAAC,CAAC,IAAI,CAAC,EAAE,CACvD;SACA,IAAI,CAAC,aAAa,CAAC,CAAA;IACtB,MAAM,IAAI,GAAG,MAAM,OAAO,CAAC,WAAW,EAAE,GAAG,EAAE,SAAS,EAAE,OAAO,CAAC,CAAA;IAChE,OAAO,IAAI;SACR,MAAM,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,IAAI,CAAC,MAAM,IAAI,CAAC,CAAC;SAClC,GAAG,CAAC,CAAC,IAAI,EAAE,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,IAAI,CAAC,CAAC,CAAE,EAAE,IAAI,EAAE,IAAI,CAAC,CAAC,CAAE,EAAE,IAAI,EAAE,UAAU,CAAC,IAAI,CAAC,CAAC,CAAC,CAAC,EAAE,CAAC,CAAC,CAAA;AACrF,CAAC"}
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The scheduled GitHub Actions workflow `prenta db:backup --init-workflow`
3
+ * writes (and `create-prenta` scaffolds). Content is the template from
4
+ * docs/superpowers/specs/2026-09-18-db-backups-and-dr-design.md §2, verbatim;
5
+ * keep the two in sync.
6
+ *
7
+ * The install step is `pnpm install --no-frozen-lockfile` because the file is
8
+ * scaffolded into projects that have not committed a lockfile yet (same as
9
+ * the scaffolded ci.yml). The Prenta repo's own `.github/workflows/db-backup.yml`
10
+ * is hand-maintained and keeps `--frozen-lockfile`.
11
+ */
12
+ export declare const DB_BACKUP_WORKFLOW_PATH = ".github/workflows/db-backup.yml";
13
+ export declare const DB_BACKUP_WORKFLOW_YAML = "name: Database backup\non:\n schedule:\n - cron: '30 3 * * *' # nightly 03:30 UTC\n workflow_dispatch:\npermissions:\n contents: read\nconcurrency: { group: db-backup, cancel-in-progress: false }\njobs:\n backup:\n runs-on: ubuntu-latest\n timeout-minutes: 30\n steps:\n - uses: actions/checkout@v6\n - uses: pnpm/action-setup@v6\n - uses: actions/setup-node@v6\n with: { node-version: 22, cache: pnpm }\n - name: Install PostgreSQL 17 client\n run: |\n sudo install -d /usr/share/postgresql-common/pgdg\n sudo curl -fsSL -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc https://www.postgresql.org/media/keys/ACCC4CF8.asc\n echo \"deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main\" | sudo tee /etc/apt/sources.list.d/pgdg.list\n sudo apt-get update -qq && sudo apt-get install -y -qq postgresql-client-17\n # Bypass pg_wrapper: hosted runners ship an older PostgreSQL cluster\n # that /usr/bin/pg_dump would otherwise select over the 17 binaries.\n echo \"/usr/lib/postgresql/17/bin\" >> \"$GITHUB_PATH\"\n # Fresh scaffolds ship no lockfile yet; switch to --frozen-lockfile once\n # pnpm-lock.yaml is committed.\n - run: pnpm install --no-frozen-lockfile\n - name: Dump, encrypt, upload, prune\n run: pnpm exec prenta db:backup --upload --retention-days 30 --json\n env:\n DIRECT_DATABASE_URL: ${{ secrets.DIRECT_DATABASE_URL }}\n BLOB_READ_WRITE_TOKEN: ${{ secrets.BLOB_READ_WRITE_TOKEN }}\n BACKUP_ENCRYPTION_KEY: ${{ secrets.BACKUP_ENCRYPTION_KEY }}\n";
14
+ //# sourceMappingURL=workflow-template.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow-template.d.ts","sourceRoot":"","sources":["../../src/backup/workflow-template.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,eAAO,MAAM,uBAAuB,oCAAoC,CAAA;AAExE,eAAO,MAAM,uBAAuB,2sDAmCnC,CAAA"}
@@ -0,0 +1,49 @@
1
+ /**
2
+ * The scheduled GitHub Actions workflow `prenta db:backup --init-workflow`
3
+ * writes (and `create-prenta` scaffolds). Content is the template from
4
+ * docs/superpowers/specs/2026-09-18-db-backups-and-dr-design.md §2, verbatim;
5
+ * keep the two in sync.
6
+ *
7
+ * The install step is `pnpm install --no-frozen-lockfile` because the file is
8
+ * scaffolded into projects that have not committed a lockfile yet (same as
9
+ * the scaffolded ci.yml). The Prenta repo's own `.github/workflows/db-backup.yml`
10
+ * is hand-maintained and keeps `--frozen-lockfile`.
11
+ */
12
+ export const DB_BACKUP_WORKFLOW_PATH = '.github/workflows/db-backup.yml';
13
+ export const DB_BACKUP_WORKFLOW_YAML = `name: Database backup
14
+ on:
15
+ schedule:
16
+ - cron: '30 3 * * *' # nightly 03:30 UTC
17
+ workflow_dispatch:
18
+ permissions:
19
+ contents: read
20
+ concurrency: { group: db-backup, cancel-in-progress: false }
21
+ jobs:
22
+ backup:
23
+ runs-on: ubuntu-latest
24
+ timeout-minutes: 30
25
+ steps:
26
+ - uses: actions/checkout@v6
27
+ - uses: pnpm/action-setup@v6
28
+ - uses: actions/setup-node@v6
29
+ with: { node-version: 22, cache: pnpm }
30
+ - name: Install PostgreSQL 17 client
31
+ run: |
32
+ sudo install -d /usr/share/postgresql-common/pgdg
33
+ sudo curl -fsSL -o /usr/share/postgresql-common/pgdg/apt.postgresql.org.asc https://www.postgresql.org/media/keys/ACCC4CF8.asc
34
+ echo "deb [signed-by=/usr/share/postgresql-common/pgdg/apt.postgresql.org.asc] https://apt.postgresql.org/pub/repos/apt $(lsb_release -cs)-pgdg main" | sudo tee /etc/apt/sources.list.d/pgdg.list
35
+ sudo apt-get update -qq && sudo apt-get install -y -qq postgresql-client-17
36
+ # Bypass pg_wrapper: hosted runners ship an older PostgreSQL cluster
37
+ # that /usr/bin/pg_dump would otherwise select over the 17 binaries.
38
+ echo "/usr/lib/postgresql/17/bin" >> "$GITHUB_PATH"
39
+ # Fresh scaffolds ship no lockfile yet; switch to --frozen-lockfile once
40
+ # pnpm-lock.yaml is committed.
41
+ - run: pnpm install --no-frozen-lockfile
42
+ - name: Dump, encrypt, upload, prune
43
+ run: pnpm exec prenta db:backup --upload --retention-days 30 --json
44
+ env:
45
+ DIRECT_DATABASE_URL: \${{ secrets.DIRECT_DATABASE_URL }}
46
+ BLOB_READ_WRITE_TOKEN: \${{ secrets.BLOB_READ_WRITE_TOKEN }}
47
+ BACKUP_ENCRYPTION_KEY: \${{ secrets.BACKUP_ENCRYPTION_KEY }}
48
+ `;
49
+ //# sourceMappingURL=workflow-template.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"workflow-template.js","sourceRoot":"","sources":["../../src/backup/workflow-template.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AACH,MAAM,CAAC,MAAM,uBAAuB,GAAG,iCAAiC,CAAA;AAExE,MAAM,CAAC,MAAM,uBAAuB,GAAG;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;CAmCtC,CAAA"}
@@ -0,0 +1,56 @@
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 { type BlobModule } from '../backup/blob-store.js';
16
+ import { type SpawnImpl } from '../backup/pg-tools.js';
17
+ import { type Logger } from '../utils/logger.js';
18
+ export declare const DEFAULT_RETENTION_DAYS = 30;
19
+ export interface DbBackupOptions {
20
+ out?: string;
21
+ upload?: boolean;
22
+ retentionDays?: number;
23
+ prefix?: string;
24
+ json?: boolean;
25
+ initWorkflow?: boolean;
26
+ force?: boolean;
27
+ allowLocal?: boolean;
28
+ }
29
+ export interface DbBackupDeps {
30
+ spawnImpl: SpawnImpl;
31
+ /** Injected `@vercel/blob`; `undefined` loads the real module on demand. */
32
+ blobModule?: BlobModule;
33
+ env: NodeJS.ProcessEnv;
34
+ cwd: string;
35
+ now: () => Date;
36
+ log: Logger;
37
+ /** Machine-readable / summary output (stdout). */
38
+ print: (line: string) => void;
39
+ }
40
+ export interface DbBackupSummary {
41
+ stamp: string;
42
+ dumpPath: string;
43
+ manifestPath: string;
44
+ sizeBytes: number;
45
+ tableCount: number;
46
+ uploaded: boolean;
47
+ blobPathname?: string;
48
+ dumpUrl?: string;
49
+ manifestUrl?: string;
50
+ pruned: string[];
51
+ durationMs: number;
52
+ }
53
+ export declare function runDbBackup(opts: DbBackupOptions, deps: DbBackupDeps): Promise<number>;
54
+ export declare function defaultDbBackupDeps(): DbBackupDeps;
55
+ export declare function registerDbBackupCommand(program: Command, deps?: DbBackupDeps): void;
56
+ //# sourceMappingURL=db-backup.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"db-backup.d.ts","sourceRoot":"","sources":["../../src/commands/db-backup.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;GAYG;AACH,OAAO,EAAE,OAAO,EAAE,MAAM,WAAW,CAAA;AAKnC,OAAO,EAA0C,KAAK,UAAU,EAAE,MAAM,yBAAyB,CAAA;AAsBjG,OAAO,EAML,KAAK,SAAS,EACf,MAAM,uBAAuB,CAAA;AAG9B,OAAO,EAAU,KA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,IAAI,YAAY,CASlD;AAED,wBAAgB,uBAAuB,CAAC,OAAO,EAAE,OAAO,EAAE,IAAI,CAAC,EAAE,YAAY,GAAG,IAAI,CAwBnF"}
@@ -0,0 +1,226 @@
1
+ import { existsSync } from 'node:fs';
2
+ import { mkdir, mkdtemp, rm, stat, writeFile } from 'node:fs/promises';
3
+ import { tmpdir } from 'node:os';
4
+ import { dirname, join, resolve } from 'node:path';
5
+ import { createBlobStore, DEFAULT_BACKUP_PREFIX } from '../backup/blob-store.js';
6
+ import { BLOB_AUTH_HINT, EXIT_FAILED, EXIT_OK, EXIT_PRECONDITION, formatBytes, formatDuration, isLocalDatabaseUrl, isPostgresUrl, resolveBlobAuth, resolveDatabaseUrl, } from '../backup/common.js';
7
+ import { BackupKeyError, encryptFile, parseBackupKey } from '../backup/crypto.js';
8
+ import { buildManifest, DUMP_EXTENSION, MANIFEST_EXTENSION, sha256File, stampFor, } from '../backup/manifest.js';
9
+ import { checkPgTool, estimateTableRows, nodeSpawn, redactUrl, runPgDump, } from '../backup/pg-tools.js';
10
+ import { DB_BACKUP_WORKFLOW_PATH, DB_BACKUP_WORKFLOW_YAML } from '../backup/workflow-template.js';
11
+ import { loadProjectEnv } from '../utils/load-dotenv.js';
12
+ import { logger } from '../utils/logger.js';
13
+ import { findRepoRoot } from '../utils/repo-root.js';
14
+ export const DEFAULT_RETENTION_DAYS = 30;
15
+ const MIN_PG_MAJOR = 17;
16
+ async function writeWorkflow(opts, deps) {
17
+ // GitHub only reads workflows from the repository root, so resolve against
18
+ // the git top-level even when the CMS app lives in `apps/cms`.
19
+ const root = findRepoRoot(deps.cwd);
20
+ const target = resolve(root, DB_BACKUP_WORKFLOW_PATH);
21
+ const shown = root === resolve(deps.cwd) ? DB_BACKUP_WORKFLOW_PATH : target;
22
+ if (existsSync(target) && !opts.force) {
23
+ deps.log.error(`${shown} already exists. Re-run with --force to overwrite it.`);
24
+ return EXIT_FAILED;
25
+ }
26
+ await mkdir(dirname(target), { recursive: true });
27
+ await writeFile(target, DB_BACKUP_WORKFLOW_YAML);
28
+ deps.log.success(`Wrote ${shown}.`);
29
+ deps.log.info('Add the repository secrets DIRECT_DATABASE_URL, BLOB_READ_WRITE_TOKEN and BACKUP_ENCRYPTION_KEY, then trigger the workflow once via workflow_dispatch.');
30
+ return EXIT_OK;
31
+ }
32
+ export async function runDbBackup(opts, deps) {
33
+ if (opts.initWorkflow)
34
+ return writeWorkflow(opts, deps);
35
+ const startedAt = deps.now();
36
+ const started = Date.now();
37
+ const env = await loadProjectEnv(deps.cwd, deps.env);
38
+ // 1. Database URL.
39
+ const resolved = resolveDatabaseUrl(env);
40
+ if (!resolved) {
41
+ deps.log.error('No database URL found. Set DIRECT_DATABASE_URL (preferred, non-pooled) or DATABASE_URL.');
42
+ return EXIT_PRECONDITION;
43
+ }
44
+ if (!isPostgresUrl(resolved.url)) {
45
+ deps.log.error(`${resolved.source} is not a valid postgres:// URL.`);
46
+ return EXIT_PRECONDITION;
47
+ }
48
+ if (resolved.source === 'DATABASE_URL') {
49
+ deps.log.warn('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.');
50
+ }
51
+ if (isLocalDatabaseUrl(resolved.url) && !opts.allowLocal) {
52
+ deps.log.error(`${resolved.source} points at a local database (${redactUrl(resolved.url)}). Pass --allow-local if that is intended.`);
53
+ return EXIT_PRECONDITION;
54
+ }
55
+ // 2. Encryption key.
56
+ let key;
57
+ try {
58
+ key = parseBackupKey(env.BACKUP_ENCRYPTION_KEY);
59
+ }
60
+ catch (err) {
61
+ deps.log.error(err instanceof BackupKeyError ? err.message : String(err));
62
+ return EXIT_PRECONDITION;
63
+ }
64
+ // 3. Upload preconditions (checked before any expensive work).
65
+ const retentionDays = opts.retentionDays ?? DEFAULT_RETENTION_DAYS;
66
+ const prefix = opts.prefix ?? DEFAULT_BACKUP_PREFIX;
67
+ const blobAuth = resolveBlobAuth(env);
68
+ if (opts.upload) {
69
+ if (!blobAuth) {
70
+ deps.log.error(`--upload requires Vercel Blob credentials: ${BLOB_AUTH_HINT}.`);
71
+ return EXIT_PRECONDITION;
72
+ }
73
+ if (!Number.isFinite(retentionDays) || retentionDays <= 0) {
74
+ deps.log.error('--retention-days must be a positive number of days.');
75
+ return EXIT_PRECONDITION;
76
+ }
77
+ }
78
+ // 4. Tools.
79
+ const pgDump = await checkPgTool('pg_dump', MIN_PG_MAJOR, deps.spawnImpl);
80
+ if (!pgDump.ok) {
81
+ deps.log.error(pgDump.detail);
82
+ return EXIT_PRECONDITION;
83
+ }
84
+ // 5. Row estimates (before the dump; psql is optional).
85
+ let tables = [];
86
+ const psql = await checkPgTool('psql', 0, deps.spawnImpl);
87
+ if (psql.ok) {
88
+ try {
89
+ tables = await estimateTableRows(resolved.url, deps.spawnImpl, env);
90
+ }
91
+ catch (err) {
92
+ deps.log.warn(`Could not read table row estimates via psql; the manifest will list no tables. ${err instanceof Error ? err.message : String(err)}`);
93
+ }
94
+ }
95
+ else {
96
+ deps.log.warn('psql is not available; the manifest will list no tables and db:restore cannot print per-table counts.');
97
+ }
98
+ // 6. Dump → encrypt → manifest.
99
+ const stamp = stampFor(startedAt);
100
+ const outDir = resolve(deps.cwd, opts.out ?? join(tmpdir(), 'prenta-backups'));
101
+ await mkdir(outDir, { recursive: true });
102
+ const dumpPath = join(outDir, `${stamp}${DUMP_EXTENSION}`);
103
+ const manifestPath = join(outDir, `${stamp}${MANIFEST_EXTENSION}`);
104
+ const scratch = await mkdtemp(join(tmpdir(), 'prenta-db-backup-'));
105
+ const rawDump = join(scratch, `${stamp}.dump`);
106
+ let sizeBytes;
107
+ try {
108
+ deps.log.info(`Dumping ${redactUrl(resolved.url)} with pg_dump ${pgDump.version}…`);
109
+ await runPgDump(resolved.url, rawDump, deps.spawnImpl, env);
110
+ await encryptFile(rawDump, dumpPath, key);
111
+ sizeBytes = (await stat(dumpPath)).size;
112
+ const sha256 = await sha256File(dumpPath);
113
+ const manifest = buildManifest({
114
+ createdAt: startedAt,
115
+ databaseUrl: resolved.url,
116
+ pgDumpVersion: pgDump.version,
117
+ sizeBytes,
118
+ sha256,
119
+ tables,
120
+ });
121
+ await writeFile(manifestPath, `${JSON.stringify(manifest, null, 2)}\n`);
122
+ }
123
+ catch (err) {
124
+ await rm(dumpPath, { force: true });
125
+ await rm(manifestPath, { force: true });
126
+ deps.log.error(`Backup failed: ${err instanceof Error ? err.message : String(err)}`);
127
+ return EXIT_FAILED;
128
+ }
129
+ finally {
130
+ await rm(scratch, { recursive: true, force: true });
131
+ }
132
+ const summary = {
133
+ stamp,
134
+ dumpPath,
135
+ manifestPath,
136
+ sizeBytes,
137
+ tableCount: tables.length,
138
+ uploaded: false,
139
+ pruned: [],
140
+ durationMs: 0,
141
+ };
142
+ // 7. Upload + prune. Manifest first: `--list` / `latest` only consider
143
+ // `.dump.enc` objects, so a stray manifest is invisible whereas a stray
144
+ // dump would be offered as restorable without its manifest.
145
+ if (opts.upload && blobAuth) {
146
+ const store = createBlobStore({ ...blobAuth, prefix, blobModule: deps.blobModule });
147
+ const manifestName = `${stamp}${MANIFEST_EXTENSION}`;
148
+ let manifestUploaded = false;
149
+ try {
150
+ const manifest = await store.upload(manifestPath, manifestName);
151
+ manifestUploaded = true;
152
+ const dump = await store.upload(dumpPath, `${stamp}${DUMP_EXTENSION}`);
153
+ summary.uploaded = true;
154
+ summary.blobPathname = dump.pathname;
155
+ summary.dumpUrl = dump.url;
156
+ summary.manifestUrl = manifest.url;
157
+ }
158
+ catch (err) {
159
+ deps.log.error(`Upload to Vercel Blob failed: ${err instanceof Error ? err.message : String(err)}. Local files were kept at ${outDir}; nothing was pruned.`);
160
+ if (manifestUploaded) {
161
+ try {
162
+ await store.remove(manifestName);
163
+ }
164
+ catch (cleanupErr) {
165
+ deps.log.warn(`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.`);
166
+ }
167
+ }
168
+ return EXIT_FAILED;
169
+ }
170
+ try {
171
+ // Relative to the run start: a slow dump must not widen the window.
172
+ summary.pruned = (await store.prune(retentionDays, startedAt)).deleted;
173
+ }
174
+ catch (err) {
175
+ // The backup itself succeeded; a prune hiccup must not fail the run.
176
+ deps.log.warn(`Backup uploaded but pruning old backups failed: ${err instanceof Error ? err.message : String(err)}`);
177
+ }
178
+ }
179
+ summary.durationMs = Date.now() - started;
180
+ if (opts.json) {
181
+ deps.print(JSON.stringify(summary));
182
+ }
183
+ else {
184
+ const where = summary.uploaded ? `${dumpPath} → ${summary.blobPathname}` : dumpPath;
185
+ deps.print(`Backup ${stamp}: ${formatBytes(sizeBytes)}, ${tables.length} table(s), ${where}, pruned ${summary.pruned.length}, ${formatDuration(summary.durationMs)}`);
186
+ if (!summary.uploaded) {
187
+ deps.log.info('Run with --upload to store this backup in Vercel Blob.');
188
+ }
189
+ }
190
+ return EXIT_OK;
191
+ }
192
+ function parseRetention(value) {
193
+ const n = Number(value);
194
+ if (!Number.isFinite(n))
195
+ throw new Error(`--retention-days expects a number, got "${value}".`);
196
+ return n;
197
+ }
198
+ export function defaultDbBackupDeps() {
199
+ return {
200
+ spawnImpl: nodeSpawn,
201
+ env: process.env,
202
+ cwd: process.cwd(),
203
+ now: () => new Date(),
204
+ log: logger,
205
+ print: (line) => console.log(line),
206
+ };
207
+ }
208
+ export function registerDbBackupCommand(program, deps) {
209
+ program
210
+ .command('db:backup')
211
+ .description('Dump, encrypt and (optionally) upload the database to Vercel Blob')
212
+ .option('--out <dir>', 'Directory for <stamp>.dump.enc + <stamp>.manifest.json')
213
+ .option('--upload', 'Upload both files to Vercel Blob (BLOB_READ_WRITE_TOKEN); never overwrites - a rerun within the same second fails')
214
+ .option('--retention-days <n>', 'Prune uploaded backups older than n days (with --upload)', parseRetention, DEFAULT_RETENTION_DAYS)
215
+ .option('--prefix <path>', 'Blob pathname prefix', DEFAULT_BACKUP_PREFIX)
216
+ .option('--allow-local', 'Allow a localhost / 127.0.0.1 database URL')
217
+ .option('--json', 'Print a machine-readable JSON summary')
218
+ .option('--init-workflow', `Write ${DB_BACKUP_WORKFLOW_PATH} into this repo and exit`)
219
+ .option('--force', 'Overwrite an existing workflow file (with --init-workflow)')
220
+ .action(async (opts) => {
221
+ const code = await runDbBackup(opts, deps ?? defaultDbBackupDeps());
222
+ if (code !== EXIT_OK)
223
+ process.exitCode = code;
224
+ });
225
+ }
226
+ //# sourceMappingURL=db-backup.js.map