@dokebi/cli 0.4.29 → 0.4.30

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.
@@ -1,4 +1,4 @@
1
1
  /** deploy/backup.mjs */
2
- export declare const BACKUP_SCRIPT = "// Backs up the app's databases (D-0184): every dokebi-db connection whose URL\n// (connections.<name>.options.url) is postgres or mongodb, read from the settings the app reads (DOKEBI_CONFIG and the secrets file that\n// DOKEBI_SECRETS names). Each backup is <DOKEBI_BACKUP_DIR>/<connection>/<UTC time>.<pgdump|archive.gz>\n// (mode 0600); older ones are removed except the newest per day, per week and per month\n// (DOKEBI_BACKUP_KEEP=days,weeks,months, default 7,4,6). One JSON line on stdout; exit 1 when a\n// connection failed. pg_dump (PostgreSQL client tools of the server's major version or later)\n// and mongodump (MongoDB Database Tools) must be on PATH.\n//\n// DOKEBI_CONFIG=/etc/<app>/<instance>/dokebi.yaml DOKEBI_SECRETS=/etc/<app>/<instance>/secrets.yaml \\\n// DOKEBI_BACKUP_DIR=/var/backups/<app>/<instance> node deploy/backup.mjs\n//\n// DOKEBI_BACKUP_CONNECTIONS=main,reports limits it to those connections.\nimport { spawn } from 'node:child_process';\nimport { openSync, closeSync, fsyncSync } from 'node:fs';\nimport { mkdir, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { loadConfig } from '@dokebi/core';\n\nprocess.umask(0o077);\nconst started = Date.now();\nconst NAME = /^(\\d{8}T\\d{6}Z)\\.(pgdump|archive\\.gz)$/;\n\nfunction fail(message) {\n process.stdout.write(`${JSON.stringify({ ok: false, error: message })}\\n`);\n process.exit(1);\n}\n\nconst configFile = process.env.DOKEBI_CONFIG;\nconst folder = process.env.DOKEBI_BACKUP_DIR;\nif (!configFile) fail('DOKEBI_CONFIG is not set: the settings file of the instance');\nif (!folder) fail('DOKEBI_BACKUP_DIR is not set: the folder that keeps the backups');\nconst keep = (process.env.DOKEBI_BACKUP_KEEP ?? '7,4,6').split(',').map(Number);\nif (keep.length !== 3 || keep.some((value) => !Number.isSafeInteger(value) || value < 0))\n fail('DOKEBI_BACKUP_KEEP is days,weeks,months (whole numbers), e.g. 7,4,6');\nconst only = process.env.DOKEBI_BACKUP_CONNECTIONS?.split(',').filter(Boolean);\n\n/** postgres or mongodb by the URL scheme; anything else is not backed up here. */\nfunction kindOf(url) {\n const scheme = url.slice(0, url.indexOf(':')).toLowerCase();\n if (scheme === 'postgres' || scheme === 'postgresql') return 'postgres';\n if (scheme === 'mongodb' || scheme === 'mongodb+srv') return 'mongodb';\n return undefined;\n}\n\n/** Runs a tool with stdout into `file`; stderr is kept for the error (it never holds the password). */\nfunction run(command, args, env, file) {\n return new Promise((resolve, reject) => {\n const fd = openSync(file, 'wx', 0o600);\n let stderr = '';\n const child = spawn(command, args, { env, stdio: ['ignore', fd, 'pipe'] });\n child.stderr.setEncoding('utf8');\n child.stderr.on('data', (chunk) => {\n stderr = (stderr + chunk).slice(-4000);\n });\n child.once('error', (error) => {\n closeSync(fd);\n reject(new Error(`${command} could not run: ${error.message}`));\n });\n child.once('close', (code, signal) => {\n try {\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n if (code === 0) resolve();\n else reject(new Error(`${command} exited with ${code ?? signal}: ${stderr.trim()}`));\n });\n });\n}\n\nasync function backup(name, url, target) {\n const kind = kindOf(url);\n const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\\.\\d+Z$/, 'Z');\n const directory = join(folder, name);\n await mkdir(directory, { recursive: true, mode: 0o700 });\n const file = join(directory, `${stamp}.${kind === 'postgres' ? 'pgdump' : 'archive.gz'}`);\n const partial = `${file}.partial`;\n const begun = Date.now();\n try {\n if (kind === 'postgres') {\n const parsed = new URL(url);\n const password = decodeURIComponent(parsed.password);\n parsed.password = '';\n await run(\n 'pg_dump',\n ['--format=custom', '--no-owner', '--no-privileges', `--dbname=${parsed.href}`],\n { ...process.env, PGPASSWORD: password },\n partial,\n );\n } else {\n // The URI (with its password) goes in a 0600 file, never on the command line.\n const options = join(directory, `.${stamp}.mongodump.yaml`);\n await writeFile(options, `uri: ${JSON.stringify(url)}\\n`, { mode: 0o600, flag: 'wx' });\n try {\n await run('mongodump', [`--config=${options}`, '--archive', '--gzip'], process.env, partial);\n } finally {\n await rm(options, { force: true });\n }\n }\n await rename(partial, file);\n } catch (error) {\n await rm(partial, { force: true });\n throw error;\n }\n const { size } = await stat(file);\n target.push({ connection: name, kind, file, bytes: size, ms: Date.now() - begun });\n}\n\n/** The newest backup per day, per ISO week and per month, as many of each as DOKEBI_BACKUP_KEEP says. */\nasync function prune(name) {\n const directory = join(folder, name);\n const files = (await readdir(directory)).filter((entry) => NAME.test(entry)).sort().reverse();\n const kept = new Set();\n const pick = (count, period) => {\n const seen = new Set();\n for (const file of files) {\n if (seen.size >= count) break;\n const key = period(file.slice(0, 8));\n if (seen.has(key)) continue;\n seen.add(key);\n kept.add(file);\n }\n };\n const week = (day) => {\n const date = new Date(Date.UTC(+day.slice(0, 4), +day.slice(4, 6) - 1, +day.slice(6, 8)));\n const thursday = new Date(date);\n thursday.setUTCDate(date.getUTCDate() + 3 - ((date.getUTCDay() + 6) % 7));\n const first = new Date(Date.UTC(thursday.getUTCFullYear(), 0, 4));\n return `${thursday.getUTCFullYear()}-${Math.round((thursday - first) / 604800000 + 1)}`;\n };\n pick(keep[0], (day) => day);\n pick(keep[1], week);\n pick(keep[2], (day) => day.slice(0, 6));\n const removed = files.filter((file) => !kept.has(file));\n for (const file of removed) await rm(join(directory, file));\n // A partial file of a run that died is removed after a day.\n for (const entry of await readdir(directory))\n if (entry.endsWith('.partial')) {\n const { mtimeMs } = await stat(join(directory, entry));\n if (Date.now() - mtimeMs > 86_400_000) await rm(join(directory, entry), { force: true });\n }\n return removed.length;\n}\n\nlet document;\ntry {\n document = await loadConfig(configFile);\n} catch (error) {\n fail(`settings could not be read: ${error.code ?? ''} ${error.message}`);\n}\nconst connections = document.options['dokebi-db']?.connections ?? {};\nconst done = [];\nconst failed = [];\nconst skipped = [];\nlet removed = 0;\nfor (const [name, connection] of Object.entries(connections)) {\n if (only && !only.includes(name)) continue;\n // options.dokebi-db.connections.<name> = { adapter, options: { url, \u2026 } }\n const url = typeof connection?.options?.url === 'string' ? connection.options.url : undefined;\n if (!url || !kindOf(url)) {\n skipped.push({ connection: name, reason: url ? 'not postgres or mongodb' : 'no url' });\n continue;\n }\n try {\n await backup(name, url, done);\n removed += await prune(name);\n } catch (error) {\n failed.push({ connection: name, error: error.message });\n }\n}\nconst ok = failed.length === 0 && done.length > 0;\nprocess.stdout.write(\n `${JSON.stringify({ ok, backups: done, failed, skipped, removed, ms: Date.now() - started })}\\n`,\n);\nif (!ok) process.exitCode = 1;\n";
2
+ export declare const BACKUP_SCRIPT = "// Backs up the app's databases (D-0184): every dokebi-db connection whose URL\n// (connections.<name>.options.url) is postgres or mongodb, read from the settings the app reads (DOKEBI_CONFIG and the secrets file that\n// DOKEBI_SECRETS names). Each backup is <DOKEBI_BACKUP_DIR>/<connection>/<UTC time>.<pgdump|archive.gz>\n// (mode 0600); older ones are removed except the newest per day, per week and per month\n// (DOKEBI_BACKUP_KEEP=days,weeks,months, default 7,4,6). One JSON line on stdout; exit 1 when a\n// connection failed. pg_dump (PostgreSQL client tools of the server's major version or later)\n// and mongodump (MongoDB Database Tools) must be on PATH.\n//\n// DOKEBI_CONFIG=/etc/<app>/<instance>/dokebi.yaml DOKEBI_SECRETS=/etc/<app>/<instance>/secrets.yaml \\\n// DOKEBI_BACKUP_DIR=/var/backups/<app>/<instance> node deploy/backup.mjs\n//\n// DOKEBI_BACKUP_CONNECTIONS=main,reports limits it to those connections.\nimport { spawn } from 'node:child_process';\nimport { openSync, closeSync, fsyncSync } from 'node:fs';\nimport { mkdir, readdir, rename, rm, stat, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { loadConfig } from '@dokebi/core';\n\nprocess.umask(0o077);\nconst started = Date.now();\nconst NAME = /^(\\d{8}T\\d{6}Z)\\.(pgdump|archive\\.gz)$/;\n\nfunction fail(message) {\n process.stdout.write(`${JSON.stringify({ ok: false, error: message })}\\n`);\n process.exit(1);\n}\n\nconst configFile = process.env.DOKEBI_CONFIG;\nconst folder = process.env.DOKEBI_BACKUP_DIR;\nif (!configFile) fail('DOKEBI_CONFIG is not set: the settings file of the instance');\nif (!folder) fail('DOKEBI_BACKUP_DIR is not set: the folder that keeps the backups');\nconst keep = (process.env.DOKEBI_BACKUP_KEEP ?? '7,4,6').split(',').map(Number);\nif (keep.length !== 3 || keep.some((value) => !Number.isSafeInteger(value) || value < 0))\n fail('DOKEBI_BACKUP_KEEP is days,weeks,months (whole numbers), e.g. 7,4,6');\nconst only = process.env.DOKEBI_BACKUP_CONNECTIONS?.split(',').filter(Boolean);\n\n/** postgres or mongodb by the URL scheme; anything else is not backed up here. */\nfunction kindOf(url) {\n const scheme = url.slice(0, url.indexOf(':')).toLowerCase();\n if (scheme === 'postgres' || scheme === 'postgresql') return 'postgres';\n if (scheme === 'mongodb' || scheme === 'mongodb+srv') return 'mongodb';\n return undefined;\n}\n\n/** Runs a tool with stdout into `file`; stderr is kept for the error (it never holds the password). */\nfunction run(command, args, env, file) {\n return new Promise((resolve, reject) => {\n const fd = openSync(file, 'wx', 0o600);\n let stderr = '';\n const child = spawn(command, args, { env, stdio: ['ignore', fd, 'pipe'] });\n child.stderr.setEncoding('utf8');\n child.stderr.on('data', (chunk) => {\n stderr = (stderr + chunk).slice(-4000);\n });\n child.once('error', (error) => {\n closeSync(fd);\n reject(new Error(`${command} could not run: ${error.message}`));\n });\n child.once('close', (code, signal) => {\n try {\n fsyncSync(fd);\n } finally {\n closeSync(fd);\n }\n if (code === 0) resolve();\n else reject(new Error(`${command} exited with ${code ?? signal}: ${stderr.trim()}`));\n });\n });\n}\n\nasync function backup(name, url, target) {\n const kind = kindOf(url);\n const stamp = new Date().toISOString().replace(/[-:]/g, '').replace(/\\.\\d+Z$/, 'Z');\n const directory = join(folder, name);\n await mkdir(directory, { recursive: true, mode: 0o700 });\n const file = join(directory, `${stamp}.${kind === 'postgres' ? 'pgdump' : 'archive.gz'}`);\n // Its own name per run: two runs in one second (the timer and a hand run) must not share it.\n const partial = `${file}.${process.pid}.partial`;\n const begun = Date.now();\n try {\n if (kind === 'postgres') {\n const parsed = new URL(url);\n const password = decodeURIComponent(parsed.password);\n parsed.password = '';\n await run(\n 'pg_dump',\n ['--format=custom', '--no-owner', '--no-privileges', `--dbname=${parsed.href}`],\n { ...process.env, PGPASSWORD: password },\n partial,\n );\n } else {\n // The URI (with its password) goes in a 0600 file, never on the command line.\n const options = join(directory, `.${stamp}.${process.pid}.mongodump.yaml`);\n await writeFile(options, `uri: ${JSON.stringify(url)}\\n`, { mode: 0o600, flag: 'wx' });\n try {\n await run('mongodump', [`--config=${options}`, '--archive', '--gzip'], process.env, partial);\n } finally {\n await rm(options, { force: true });\n }\n }\n await rename(partial, file);\n } catch (error) {\n await rm(partial, { force: true });\n throw error;\n }\n const { size } = await stat(file);\n target.push({ connection: name, kind, file, bytes: size, ms: Date.now() - begun });\n}\n\n/** The newest backup per day, per ISO week and per month, as many of each as DOKEBI_BACKUP_KEEP says. */\nasync function prune(name) {\n const directory = join(folder, name);\n const files = (await readdir(directory)).filter((entry) => NAME.test(entry)).sort().reverse();\n const kept = new Set();\n const pick = (count, period) => {\n const seen = new Set();\n for (const file of files) {\n if (seen.size >= count) break;\n const key = period(file.slice(0, 8));\n if (seen.has(key)) continue;\n seen.add(key);\n kept.add(file);\n }\n };\n const week = (day) => {\n const date = new Date(Date.UTC(+day.slice(0, 4), +day.slice(4, 6) - 1, +day.slice(6, 8)));\n const thursday = new Date(date);\n thursday.setUTCDate(date.getUTCDate() + 3 - ((date.getUTCDay() + 6) % 7));\n const first = new Date(Date.UTC(thursday.getUTCFullYear(), 0, 4));\n return `${thursday.getUTCFullYear()}-${Math.round((thursday - first) / 604800000 + 1)}`;\n };\n pick(keep[0], (day) => day);\n pick(keep[1], week);\n pick(keep[2], (day) => day.slice(0, 6));\n const removed = files.filter((file) => !kept.has(file));\n for (const file of removed) await rm(join(directory, file));\n // A partial file of a run that died is removed after a day.\n for (const entry of await readdir(directory))\n if (entry.endsWith('.partial')) {\n const { mtimeMs } = await stat(join(directory, entry));\n if (Date.now() - mtimeMs > 86_400_000) await rm(join(directory, entry), { force: true });\n }\n return removed.length;\n}\n\nlet document;\ntry {\n document = await loadConfig(configFile);\n} catch (error) {\n fail(`settings could not be read: ${error.code ?? ''} ${error.message}`);\n}\nconst connections = document.options['dokebi-db']?.connections ?? {};\nconst done = [];\nconst failed = [];\nconst skipped = [];\nlet removed = 0;\nfor (const [name, connection] of Object.entries(connections)) {\n if (only && !only.includes(name)) continue;\n // options.dokebi-db.connections.<name> = { adapter, options: { url, \u2026 } }\n const url = typeof connection?.options?.url === 'string' ? connection.options.url : undefined;\n if (!url || !kindOf(url)) {\n skipped.push({ connection: name, reason: url ? 'not postgres or mongodb' : 'no url' });\n continue;\n }\n try {\n await backup(name, url, done);\n removed += await prune(name);\n } catch (error) {\n failed.push({ connection: name, error: error.message });\n }\n}\nconst ok = failed.length === 0 && done.length > 0;\nprocess.stdout.write(\n `${JSON.stringify({ ok, backups: done, failed, skipped, removed, ms: Date.now() - started })}\\n`,\n);\nif (!ok) process.exitCode = 1;\n";
3
3
  /** deploy/restore-drill.mjs */
4
- export declare const RESTORE_DRILL_SCRIPT = "// Restore drill (D-0184): proves the newest backup of a connection can be restored. It restores\n// it into DOKEBI_RESTORE_URL (an empty scratch database, never the live one: refused when it is\n// the same database) and compares the restored database with the live one: tables or\n// collections, and the rows of the migration history (dokebi_migrations). One JSON line; exit 1\n// when the restore failed or the restored database is empty. Run it every month and after a\n// change of the PostgreSQL or MongoDB version.\n//\n// DOKEBI_CONFIG=/etc/<app>/<instance>/dokebi.yaml DOKEBI_SECRETS=/etc/<app>/<instance>/secrets.yaml \\\n// DOKEBI_BACKUP_DIR=/var/backups/<app>/<instance> DOKEBI_RESTORE_URL=postgres://...<scratch db> \\\n// node deploy/restore-drill.mjs\n//\n// DOKEBI_RESTORE_CONNECTION picks the connection (default main). DOKEBI_RESTORE_URL is a secret:\n// put it in the environment of this run only (a systemd-run --property=EnvironmentFile=...).\nimport { spawn } from 'node:child_process';\nimport { createReadStream } from 'node:fs';\nimport { readdir, rm, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { loadConfig } from '@dokebi/core';\n\nprocess.umask(0o077);\nconst started = Date.now();\nfunction fail(message, extra = {}) {\n process.stdout.write(`${JSON.stringify({ ok: false, error: message, ...extra })}\\n`);\n process.exit(1);\n}\nconst configFile = process.env.DOKEBI_CONFIG;\nconst folder = process.env.DOKEBI_BACKUP_DIR;\nconst target = process.env.DOKEBI_RESTORE_URL;\nconst name = process.env.DOKEBI_RESTORE_CONNECTION || 'main';\nif (!configFile || !folder || !target)\n fail('DOKEBI_CONFIG, DOKEBI_BACKUP_DIR and DOKEBI_RESTORE_URL must be set');\n\nlet document;\ntry {\n document = await loadConfig(configFile);\n} catch (error) {\n fail(`settings could not be read: ${error.code ?? ''} ${error.message}`);\n}\nconst live = document.options['dokebi-db']?.connections?.[name]?.options?.url;\nif (typeof live !== 'string') fail(`no url for the dokebi-db connection ${name}`);\nconst scheme = (url) => url.slice(0, url.indexOf(':')).toLowerCase();\nconst kind = ['postgres', 'postgresql'].includes(scheme(live))\n ? 'postgres'\n : ['mongodb', 'mongodb+srv'].includes(scheme(live))\n ? 'mongodb'\n : fail(`the connection ${name} is not postgres or mongodb`);\nif (kind !== (['postgres', 'postgresql'].includes(scheme(target)) ? 'postgres' : 'mongodb'))\n fail('DOKEBI_RESTORE_URL is not the same kind of database as the connection');\nconst where = (url) => {\n const parsed = new URL(url);\n return `${parsed.hostname}:${parsed.port}/${parsed.pathname.slice(1)}`;\n};\nif (where(live) === where(target)) fail('DOKEBI_RESTORE_URL names the live database; use a scratch one');\n\nconst extension = kind === 'postgres' ? '.pgdump' : '.archive.gz';\nlet entries = [];\ntry {\n entries = await readdir(join(folder, name));\n} catch (error) {\n if (error.code !== 'ENOENT') throw error;\n}\nconst files = entries\n .filter((file) => /^\\d{8}T\\d{6}Z/.test(file) && file.endsWith(extension))\n .sort();\nconst newest = files.at(-1);\nif (!newest) fail(`no backup of ${name} in ${join(folder, name)}`);\nconst backup = join(folder, name, newest);\n\nfunction run(command, args, env, input) {\n return new Promise((resolve, reject) => {\n let stderr = '';\n const child = spawn(command, args, { env, stdio: ['pipe', 'ignore', 'pipe'] });\n child.stderr.setEncoding('utf8');\n child.stderr.on('data', (chunk) => {\n stderr = (stderr + chunk).slice(-4000);\n });\n child.once('error', (error) => reject(new Error(`${command} could not run: ${error.message}`)));\n // A tool that stops reading (it failed) breaks the pipe: its exit code says why.\n child.stdin.on('error', (error) => {\n stderr = `${stderr}\\n(input: ${error.code ?? error.message})`.slice(-4000);\n });\n const source = createReadStream(input);\n source.once('error', (error) => {\n child.kill();\n reject(new Error(`the backup could not be read: ${error.message}`));\n });\n child.once('close', (code, signal) =>\n code === 0\n ? resolve()\n : reject(new Error(`${command} exited with ${code ?? signal}: ${stderr.trim()}`)),\n );\n source.pipe(child.stdin);\n });\n}\n\nasync function postgresCounts(url) {\n const { default: pg } = await import('pg');\n const client = new pg.Client({ connectionString: url });\n await client.connect();\n try {\n const tables = await client.query(\n \"select count(*)::int as n from information_schema.tables where table_type = 'BASE TABLE' and table_schema not in ('pg_catalog', 'information_schema')\",\n );\n const history = await client.query(\"select to_regclass('dokebi_migrations') is not null as present\");\n const migrations = history.rows[0].present\n ? (await client.query('select count(*)::int as n from dokebi_migrations')).rows[0].n\n : null;\n return { tables: tables.rows[0].n, migrations };\n } finally {\n await client.end();\n }\n}\n\nasync function mongoCounts(url) {\n const { MongoClient } = await import('mongodb');\n const client = new MongoClient(url);\n await client.connect();\n try {\n const db = client.db();\n const collections = (await db.listCollections({}, { nameOnly: true }).toArray()).filter(\n (item) => !item.name.startsWith('system.'),\n );\n const migrations = collections.some((item) => item.name === 'dokebi_migrations')\n ? await db.collection('dokebi_migrations').countDocuments()\n : null;\n return { tables: collections.length, migrations };\n } finally {\n await client.close();\n }\n}\n\ntry {\n if (kind === 'postgres') {\n const parsed = new URL(target);\n const password = decodeURIComponent(parsed.password);\n parsed.password = '';\n await run(\n 'pg_restore',\n ['--clean', '--if-exists', '--no-owner', '--no-privileges', `--dbname=${parsed.href}`],\n { ...process.env, PGPASSWORD: password },\n backup,\n );\n } else {\n const from = new URL(live).pathname.slice(1);\n const to = new URL(target).pathname.slice(1);\n // A database in the URI would act as a --db filter (nothing of the backup matches it): the\n // URI names the server only, --nsFrom/--nsTo the databases.\n const server = new URL(target);\n server.pathname = '/';\n const options = join(folder, name, '.restore-drill.mongorestore.yaml');\n await writeFile(options, `uri: ${JSON.stringify(server.href)}\\n`, { mode: 0o600 });\n try {\n await run(\n 'mongorestore',\n [`--config=${options}`, '--archive', '--gzip', '--drop', `--nsFrom=${from}.*`, `--nsTo=${to}.*`],\n process.env,\n backup,\n );\n } finally {\n await rm(options, { force: true });\n }\n }\n} catch (error) {\n fail(error.message, { backup });\n}\nconst count = kind === 'postgres' ? postgresCounts : mongoCounts;\nconst [restored, current] = await Promise.all([count(target), count(live)]);\nconst ok = restored.tables > 0;\nconst notes = [];\nif (restored.tables !== current.tables)\n notes.push(`the live database has ${current.tables} tables or collections, the backup ${restored.tables}`);\nif (restored.migrations !== current.migrations)\n notes.push('the live migration history differs from the backup (a migration ran since)');\nprocess.stdout.write(\n `${JSON.stringify({ ok, connection: name, kind, backup, restored, live: current, notes, ms: Date.now() - started })}\\n`,\n);\nif (!ok) process.exitCode = 1;\n";
4
+ export declare const RESTORE_DRILL_SCRIPT = "// Restore drill (D-0184): proves the newest backup of a connection can be restored. It restores\n// it into DOKEBI_RESTORE_URL (an empty scratch database, never the live one: refused when it\n// names the live database or holds any table or collection) and compares the restored database with the live one: tables or\n// collections, and the rows of the migration history (dokebi_migrations). One JSON line; exit 1\n// when the restore failed or the restored database is empty. Run it every month and after a\n// change of the PostgreSQL or MongoDB version.\n//\n// DOKEBI_CONFIG=/etc/<app>/<instance>/dokebi.yaml DOKEBI_SECRETS=/etc/<app>/<instance>/secrets.yaml \\\n// DOKEBI_BACKUP_DIR=/var/backups/<app>/<instance> DOKEBI_RESTORE_URL=postgres://...<scratch db> \\\n// node deploy/restore-drill.mjs\n//\n// DOKEBI_RESTORE_CONNECTION picks the connection (default main). DOKEBI_RESTORE_URL is a secret:\n// put it in the environment of this run only (a systemd-run --property=EnvironmentFile=...).\nimport { spawn } from 'node:child_process';\nimport { createReadStream } from 'node:fs';\nimport { readdir, rm, writeFile } from 'node:fs/promises';\nimport { join } from 'node:path';\nimport { loadConfig } from '@dokebi/core';\n\nprocess.umask(0o077);\nconst started = Date.now();\nfunction fail(message, extra = {}) {\n process.stdout.write(`${JSON.stringify({ ok: false, error: message, ...extra })}\\n`);\n process.exit(1);\n}\nconst configFile = process.env.DOKEBI_CONFIG;\nconst folder = process.env.DOKEBI_BACKUP_DIR;\nconst target = process.env.DOKEBI_RESTORE_URL;\nconst name = process.env.DOKEBI_RESTORE_CONNECTION || 'main';\nif (!configFile || !folder || !target)\n fail('DOKEBI_CONFIG, DOKEBI_BACKUP_DIR and DOKEBI_RESTORE_URL must be set');\n\nlet document;\ntry {\n document = await loadConfig(configFile);\n} catch (error) {\n fail(`settings could not be read: ${error.code ?? ''} ${error.message}`);\n}\nconst live = document.options['dokebi-db']?.connections?.[name]?.options?.url;\nif (typeof live !== 'string') fail(`no url for the dokebi-db connection ${name}`);\nconst scheme = (url) => url.slice(0, url.indexOf(':')).toLowerCase();\nconst kind = ['postgres', 'postgresql'].includes(scheme(live))\n ? 'postgres'\n : ['mongodb', 'mongodb+srv'].includes(scheme(live))\n ? 'mongodb'\n : fail(`the connection ${name} is not postgres or mongodb`);\nif (kind !== (['postgres', 'postgresql'].includes(scheme(target)) ? 'postgres' : 'mongodb'))\n fail('DOKEBI_RESTORE_URL is not the same kind of database as the connection');\n// The server and database a URL names, as the drivers read it: a missing port is the default\n// one, every loopback name (and a local socket) is this machine, `?host=`, `?port=` and\n// `?dbname=` win over the URL's parts, and a postgres URL without a database names the user's.\nconst LOOPBACK = /^(localhost|127(\\.\\d{1,3}){3}|::1|0:0:0:0:0:0:0:1|)$/;\nconst where = (url) => {\n const parsed = new URL(url);\n const query = (name) => parsed.searchParams.get(name) ?? undefined;\n const host = (query('host') ?? decodeURIComponent(parsed.hostname)).toLowerCase().replace(/^\\[|\\]$/g, '');\n const port = query('port') ?? (parsed.port || (kind === 'postgres' ? '5432' : '27017'));\n const database =\n query('dbname') ??\n (decodeURIComponent(parsed.pathname.slice(1)) ||\n (kind === 'postgres' ? decodeURIComponent(parsed.username) : 'test'));\n return `${LOOPBACK.test(host) || host.startsWith('/') ? 'this machine' : host}:${port}/${database}`;\n};\nif (where(live) === where(target)) fail('DOKEBI_RESTORE_URL names the live database; use a scratch one');\n\nconst extension = kind === 'postgres' ? '.pgdump' : '.archive.gz';\nlet entries = [];\ntry {\n entries = await readdir(join(folder, name));\n} catch (error) {\n if (error.code !== 'ENOENT') throw error;\n}\nconst files = entries\n .filter((file) => /^\\d{8}T\\d{6}Z/.test(file) && file.endsWith(extension))\n .sort();\nconst newest = files.at(-1);\nif (!newest) fail(`no backup of ${name} in ${join(folder, name)}`);\nconst backup = join(folder, name, newest);\n\nfunction run(command, args, env, input) {\n return new Promise((resolve, reject) => {\n let stderr = '';\n const child = spawn(command, args, { env, stdio: ['pipe', 'ignore', 'pipe'] });\n child.stderr.setEncoding('utf8');\n child.stderr.on('data', (chunk) => {\n stderr = (stderr + chunk).slice(-4000);\n });\n child.once('error', (error) => reject(new Error(`${command} could not run: ${error.message}`)));\n // A tool that stops reading (it failed) breaks the pipe: its exit code says why.\n child.stdin.on('error', (error) => {\n stderr = `${stderr}\\n(input: ${error.code ?? error.message})`.slice(-4000);\n });\n const source = createReadStream(input);\n source.once('error', (error) => {\n child.kill();\n reject(new Error(`the backup could not be read: ${error.message}`));\n });\n child.once('close', (code, signal) =>\n code === 0\n ? resolve()\n : reject(new Error(`${command} exited with ${code ?? signal}: ${stderr.trim()}`)),\n );\n source.pipe(child.stdin);\n });\n}\n\nasync function postgresCounts(url) {\n const { default: pg } = await import('pg');\n const client = new pg.Client({ connectionString: url });\n await client.connect();\n try {\n const tables = await client.query(\n \"select count(*)::int as n from information_schema.tables where table_type = 'BASE TABLE' and table_schema not in ('pg_catalog', 'information_schema')\",\n );\n const history = await client.query(\"select to_regclass('dokebi_migrations') is not null as present\");\n const migrations = history.rows[0].present\n ? (await client.query('select count(*)::int as n from dokebi_migrations')).rows[0].n\n : null;\n return { tables: tables.rows[0].n, migrations };\n } finally {\n await client.end();\n }\n}\n\nasync function mongoCounts(url) {\n const { MongoClient } = await import('mongodb');\n const client = new MongoClient(url);\n await client.connect();\n try {\n const db = client.db();\n const collections = (await db.listCollections({}, { nameOnly: true }).toArray()).filter(\n (item) => !item.name.startsWith('system.'),\n );\n const migrations = collections.some((item) => item.name === 'dokebi_migrations')\n ? await db.collection('dokebi_migrations').countDocuments()\n : null;\n return { tables: collections.length, migrations };\n } finally {\n await client.close();\n }\n}\n\nconst count = kind === 'postgres' ? postgresCounts : mongoCounts;\n// The restore replaces what the target holds (--clean, --drop): only an empty scratch database\n// is taken, whatever name reaches the live server (a DNS alias, another address of it).\nlet before;\ntry {\n before = await count(target);\n} catch (error) {\n fail(`the scratch database could not be read: ${error.message}`);\n}\nif (before.tables > 0)\n fail(`DOKEBI_RESTORE_URL is not empty (${before.tables} tables or collections): restore into a new, empty scratch database`);\ntry {\n if (kind === 'postgres') {\n const parsed = new URL(target);\n const password = decodeURIComponent(parsed.password);\n parsed.password = '';\n await run(\n 'pg_restore',\n ['--clean', '--if-exists', '--no-owner', '--no-privileges', `--dbname=${parsed.href}`],\n { ...process.env, PGPASSWORD: password },\n backup,\n );\n } else {\n const from = new URL(live).pathname.slice(1);\n const to = new URL(target).pathname.slice(1);\n // A database in the URI would act as a --db filter (nothing of the backup matches it): the\n // URI names the server only, --nsFrom/--nsTo the databases.\n const server = new URL(target);\n server.pathname = '/';\n const options = join(folder, name, '.restore-drill.mongorestore.yaml');\n await writeFile(options, `uri: ${JSON.stringify(server.href)}\\n`, { mode: 0o600 });\n try {\n await run(\n 'mongorestore',\n [`--config=${options}`, '--archive', '--gzip', '--drop', `--nsFrom=${from}.*`, `--nsTo=${to}.*`],\n process.env,\n backup,\n );\n } finally {\n await rm(options, { force: true });\n }\n }\n} catch (error) {\n fail(error.message, { backup });\n}\nconst [restored, current] = await Promise.all([count(target), count(live)]);\nconst ok = restored.tables > 0;\nconst notes = [];\nif (restored.tables !== current.tables)\n notes.push(`the live database has ${current.tables} tables or collections, the backup ${restored.tables}`);\nif (restored.migrations !== current.migrations)\n notes.push('the live migration history differs from the backup (a migration ran since)');\nprocess.stdout.write(\n `${JSON.stringify({ ok, connection: name, kind, backup, restored, live: current, notes, ms: Date.now() - started })}\\n`,\n);\nif (!ok) process.exitCode = 1;\n";
@@ -80,7 +80,8 @@ async function backup(name, url, target) {
80
80
  const directory = join(folder, name);
81
81
  await mkdir(directory, { recursive: true, mode: 0o700 });
82
82
  const file = join(directory, \`\${stamp}.\${kind === 'postgres' ? 'pgdump' : 'archive.gz'}\`);
83
- const partial = \`\${file}.partial\`;
83
+ // Its own name per run: two runs in one second (the timer and a hand run) must not share it.
84
+ const partial = \`\${file}.\${process.pid}.partial\`;
84
85
  const begun = Date.now();
85
86
  try {
86
87
  if (kind === 'postgres') {
@@ -95,7 +96,7 @@ async function backup(name, url, target) {
95
96
  );
96
97
  } else {
97
98
  // The URI (with its password) goes in a 0600 file, never on the command line.
98
- const options = join(directory, \`.\${stamp}.mongodump.yaml\`);
99
+ const options = join(directory, \`.\${stamp}.\${process.pid}.mongodump.yaml\`);
99
100
  await writeFile(options, \`uri: \${JSON.stringify(url)}\\n\`, { mode: 0o600, flag: 'wx' });
100
101
  try {
101
102
  await run('mongodump', [\`--config=\${options}\`, '--archive', '--gzip'], process.env, partial);
@@ -182,8 +183,8 @@ if (!ok) process.exitCode = 1;
182
183
  `;
183
184
  /** deploy/restore-drill.mjs */
184
185
  export const RESTORE_DRILL_SCRIPT = `// Restore drill (D-0184): proves the newest backup of a connection can be restored. It restores
185
- // it into DOKEBI_RESTORE_URL (an empty scratch database, never the live one: refused when it is
186
- // the same database) and compares the restored database with the live one: tables or
186
+ // it into DOKEBI_RESTORE_URL (an empty scratch database, never the live one: refused when it
187
+ // names the live database or holds any table or collection) and compares the restored database with the live one: tables or
187
188
  // collections, and the rows of the migration history (dokebi_migrations). One JSON line; exit 1
188
189
  // when the restore failed or the restored database is empty. Run it every month and after a
189
190
  // change of the PostgreSQL or MongoDB version.
@@ -229,9 +230,20 @@ const kind = ['postgres', 'postgresql'].includes(scheme(live))
229
230
  : fail(\`the connection \${name} is not postgres or mongodb\`);
230
231
  if (kind !== (['postgres', 'postgresql'].includes(scheme(target)) ? 'postgres' : 'mongodb'))
231
232
  fail('DOKEBI_RESTORE_URL is not the same kind of database as the connection');
233
+ // The server and database a URL names, as the drivers read it: a missing port is the default
234
+ // one, every loopback name (and a local socket) is this machine, \`?host=\`, \`?port=\` and
235
+ // \`?dbname=\` win over the URL's parts, and a postgres URL without a database names the user's.
236
+ const LOOPBACK = /^(localhost|127(\\.\\d{1,3}){3}|::1|0:0:0:0:0:0:0:1|)$/;
232
237
  const where = (url) => {
233
238
  const parsed = new URL(url);
234
- return \`\${parsed.hostname}:\${parsed.port}/\${parsed.pathname.slice(1)}\`;
239
+ const query = (name) => parsed.searchParams.get(name) ?? undefined;
240
+ const host = (query('host') ?? decodeURIComponent(parsed.hostname)).toLowerCase().replace(/^\\[|\\]$/g, '');
241
+ const port = query('port') ?? (parsed.port || (kind === 'postgres' ? '5432' : '27017'));
242
+ const database =
243
+ query('dbname') ??
244
+ (decodeURIComponent(parsed.pathname.slice(1)) ||
245
+ (kind === 'postgres' ? decodeURIComponent(parsed.username) : 'test'));
246
+ return \`\${LOOPBACK.test(host) || host.startsWith('/') ? 'this machine' : host}:\${port}/\${database}\`;
235
247
  };
236
248
  if (where(live) === where(target)) fail('DOKEBI_RESTORE_URL names the live database; use a scratch one');
237
249
 
@@ -312,6 +324,17 @@ async function mongoCounts(url) {
312
324
  }
313
325
  }
314
326
 
327
+ const count = kind === 'postgres' ? postgresCounts : mongoCounts;
328
+ // The restore replaces what the target holds (--clean, --drop): only an empty scratch database
329
+ // is taken, whatever name reaches the live server (a DNS alias, another address of it).
330
+ let before;
331
+ try {
332
+ before = await count(target);
333
+ } catch (error) {
334
+ fail(\`the scratch database could not be read: \${error.message}\`);
335
+ }
336
+ if (before.tables > 0)
337
+ fail(\`DOKEBI_RESTORE_URL is not empty (\${before.tables} tables or collections): restore into a new, empty scratch database\`);
315
338
  try {
316
339
  if (kind === 'postgres') {
317
340
  const parsed = new URL(target);
@@ -346,7 +369,6 @@ try {
346
369
  } catch (error) {
347
370
  fail(error.message, { backup });
348
371
  }
349
- const count = kind === 'postgres' ? postgresCounts : mongoCounts;
350
372
  const [restored, current] = await Promise.all([count(target), count(live)]);
351
373
  const ok = restored.tables > 0;
352
374
  const notes = [];
@@ -259,7 +259,8 @@ never reach a command line.
259
259
  - **Restore drill, every month** (and after a database upgrade): create an empty scratch database
260
260
  (e.g. \`${first.database}_drill\`), then
261
261
  \`${env(first)} DOKEBI_BACKUP_DIR=${first.backups} DOKEBI_RESTORE_URL=<scratch database URL> node deploy/restore-drill.mjs\`.
262
- It restores the newest backup there, refuses the live database, compares tables (or
262
+ It restores the newest backup there, refuses the live database and any database that is
263
+ not empty, compares tables (or
263
264
  collections) and the migration history with the live one, and prints one JSON line. Drop the
264
265
  scratch database afterwards.
265
266
  - **A real restore:** stop the instance, restore the chosen backup into a new database
@@ -300,9 +301,16 @@ ${input.domains.join(', ')} {
300
301
  }
301
302
  }
302
303
  # ${input.live} and ${input.ready} answer as the app answers them (never cached):
303
- # what an uptime monitor and dokebi verify --remote read.
304
- header ${input.live} Cache-Control no-store
305
- header ${input.ready} Cache-Control no-store
304
+ # what an uptime monitor and dokebi verify --remote read. Deferred: set when the answer is
305
+ # written, so it replaces a Cache-Control of the app instead of adding a second one.
306
+ header ${input.live} {
307
+ Cache-Control no-store
308
+ defer
309
+ }
310
+ header ${input.ready} {
311
+ Cache-Control no-store
312
+ defer
313
+ }
306
314
  log {
307
315
  output file /var/log/caddy/${at.unit}.access.log
308
316
  }
@@ -314,28 +322,40 @@ export function nginxConf(input) {
314
322
  const names = input.domains.join(' ');
315
323
  const main = input.domains[0];
316
324
  const upstream = at.unit.replaceAll('-', '_');
325
+ // Host names are letters, digits, dots and hyphens (checked by deploy proxy): only dots escape.
326
+ const hosts = input.domains.map((name) => name.replaceAll('.', '\\.')).join('|');
327
+ const only = ` # Only these names. nginx gives a request for any other host to its first server, which may
328
+ # be this one, and the app would see that host (Caddy serves only the names it lists).
329
+ # 421: the client asked the wrong server.
330
+ if ($host !~* "^(?:${hosts})$") { return 421; }`;
317
331
  return `# ${at.app} (${at.instance}): nginx terminates TLS for these names and passes requests to the
318
332
  # app on 127.0.0.1:${at.port}. The app trusts X-Forwarded-* only from dokebi-web.trustProxy
319
333
  # (127.0.0.1 and ::1 here). Certificates: certbot certonly --webroot -w /var/www/letsencrypt -d ${main}
320
334
  # Install: copy to /etc/nginx/conf.d/${at.unit}.conf, then nginx -t && systemctl reload nginx.
321
335
 
322
336
  ${input.streams
323
- ? `# WebSocket: an Upgrade request keeps its Connection header.
337
+ ? `# WebSocket: an Upgrade request keeps its Connection header; any other request sends none, so
338
+ # the connections to the app are kept and reused (keepalive below). "close" here made every
339
+ # request close its connection, and only a stream's answer kept one.
324
340
  map $http_upgrade $${upstream}_connection {
325
341
  default upgrade;
326
- '' close;
342
+ '' '';
327
343
  }
328
344
 
329
345
  `
330
346
  : ''}upstream ${upstream} {
331
347
  server 127.0.0.1:${at.port};
332
348
  keepalive 16;
349
+ # Below the app's own idle limit (Fastify keepAliveTimeout, 72 s): nginx lets an idle
350
+ # connection go first, so it never sends a request on one the app is closing.
351
+ keepalive_timeout 60s;
333
352
  }
334
353
 
335
354
  server {
336
355
  listen 80;
337
356
  listen [::]:80;
338
357
  server_name ${names};
358
+ ${only}
339
359
  location /.well-known/acme-challenge/ { root /var/www/letsencrypt; }
340
360
  location / { return 308 https://$host$request_uri; }
341
361
  }
@@ -345,6 +365,7 @@ server {
345
365
  listen 443 ssl http2;
346
366
  listen [::]:443 ssl http2;
347
367
  server_name ${names};
368
+ ${only}
348
369
 
349
370
  ssl_certificate /etc/letsencrypt/live/${main}/fullchain.pem;
350
371
  ssl_certificate_key /etc/letsencrypt/live/${main}/privkey.pem;
@@ -369,8 +390,9 @@ server {
369
390
  proxy_send_timeout ${input.readTimeoutSeconds}s;
370
391
 
371
392
  # Health routes as the app answers them, never cached (monitoring, dokebi verify --remote).
372
- location = ${input.live} { proxy_pass http://${upstream}; add_header Cache-Control no-store always; }
373
- location = ${input.ready} { proxy_pass http://${upstream}; add_header Cache-Control no-store always; }
393
+ # (the app's own Cache-Control is dropped, so the answer carries this one only).
394
+ location = ${input.live} { proxy_pass http://${upstream}; proxy_hide_header Cache-Control; add_header Cache-Control no-store always; }
395
+ location = ${input.ready} { proxy_pass http://${upstream}; proxy_hide_header Cache-Control; add_header Cache-Control no-store always; }
374
396
 
375
397
  location / {
376
398
  proxy_pass http://${upstream};
package/dist/deploy.js CHANGED
@@ -350,6 +350,9 @@ export function instancePorts(names, known, port, web) {
350
350
  }
351
351
  return ports;
352
352
  }
353
+ function instanceUsage(name) {
354
+ return new CliError('USAGE', `--instance ${name}: lowercase letters, digits and -, 1 to 24 characters, starting with a letter`, { phase: 'arguments' });
355
+ }
353
356
  /** `dokebi deploy init` (D-0184 §2). */
354
357
  export async function deployInit(input, options) {
355
358
  const root = await realpath(input);
@@ -359,9 +362,7 @@ export async function deployInit(input, options) {
359
362
  const names = [...new Set(options.instances)];
360
363
  for (const name of names)
361
364
  if (!INSTANCE.test(name))
362
- throw new CliError('USAGE', `--instance ${name}: lowercase letters, digits and -, 1 to 24 characters, starting with a letter`, {
363
- phase: 'arguments',
364
- });
365
+ throw instanceUsage(name);
365
366
  if (options.port !== undefined && names.length !== 1)
366
367
  throw new CliError('USAGE', '--port names the port of one instance; give one --instance with it', {
367
368
  phase: 'arguments',
@@ -466,6 +467,9 @@ export async function deployProxy(input, options) {
466
467
  const state = await projectState(root);
467
468
  const app = await appName(root);
468
469
  const plugins = state.plugins.map((plugin) => optionsKey(plugin));
470
+ // The name deploy init accepts: it becomes the unit, upstream and file names of the proxy.
471
+ if (!INSTANCE.test(options.instance))
472
+ throw instanceUsage(options.instance);
469
473
  const domains = [...new Set(options.domains.map((domain) => domain.toLowerCase()))];
470
474
  for (const domain of domains)
471
475
  if (!DOMAIN.test(domain))
package/dist/dev-infra.js CHANGED
@@ -7,7 +7,7 @@ import { statSync } from 'node:fs';
7
7
  import { connect, createServer } from 'node:net';
8
8
  import { delimiter, join } from 'node:path';
9
9
  import { promisify } from 'node:util';
10
- import { isMap, isScalar, parseDocument, stringify } from 'yaml';
10
+ import { isMap, isScalar, parseDocument, stringify, visit } from 'yaml';
11
11
  import { databaseEnvironment } from './dev-compose.js';
12
12
  import { debug, describeError, isMissing } from './diagnostics.js';
13
13
  const exec = promisify(execFile);
@@ -48,11 +48,7 @@ export const FALLBACK_PROJECT_NAME = 'dokebi-app';
48
48
  */
49
49
  export function composeUnsetVariables(compose, envKeys = []) {
50
50
  const provided = new Set([PASSWORD_VARIABLE, ...envKeys]);
51
- const text = compose
52
- .split('\n')
53
- .filter((line) => !line.trimStart().startsWith('#'))
54
- .join('\n')
55
- .replaceAll('$$', '');
51
+ const text = composeValues(compose).replaceAll('$$', '');
56
52
  const unset = new Set();
57
53
  for (const match of text.matchAll(/\$\{([A-Za-z_][A-Za-z0-9_]*)(?:(:?[-+?])[^}]*)?\}|\$([A-Za-z_][A-Za-z0-9_]*)/g)) {
58
54
  const name = match[1] ?? match[3];
@@ -65,6 +61,27 @@ export function composeUnsetVariables(compose, envKeys = []) {
65
61
  }
66
62
  return [...unset].sort();
67
63
  }
64
+ /**
65
+ * The text Compose interpolates: the YAML's values, so a comment after a value (`image: x # $TAG`)
66
+ * or a key is not read. A file that does not parse is read by lines without whole-line comments
67
+ * (Compose then refuses it for its own reason).
68
+ */
69
+ function composeValues(compose) {
70
+ const document = parseDocument(compose);
71
+ if (document.errors.length)
72
+ return compose
73
+ .split('\n')
74
+ .filter((line) => !line.trimStart().startsWith('#'))
75
+ .join('\n');
76
+ const values = [];
77
+ visit(document, {
78
+ Scalar(key, node) {
79
+ if (key !== 'key' && typeof node.value === 'string')
80
+ values.push(node.value);
81
+ },
82
+ });
83
+ return values.join('\n');
84
+ }
68
85
  /** The names a `.env` text sets (`NAME=` or `export NAME=`), read leniently: doctor reports an
69
86
  * invalid `.env` on its own, so a line this cannot read is simply not a name. */
70
87
  export function envKeys(text) {
@@ -72,7 +89,7 @@ export function envKeys(text) {
72
89
  }
73
90
  /** The doctor and dev-infra advice for compose variables dev-infra up does not set. */
74
91
  export function composeVariablesHint(variables) {
75
- return `compose.yaml needs ${variables.join(', ')} from the environment, which npx dokebi dev-infra up does not set, so dev-infra up fails. dev-infra up passes the passwords of dokebi.yaml: ${PASSWORD_VARIABLE}, and for every connection DOKEBI_<PLUGIN>_<CONNECTION>_PASSWORD (or _TOKEN; without the connection for main, such as DOKEBI_REDIS_PASSWORD); use those names, give a default in compose.yaml (\${NAME:-value}) or set it in .env`;
92
+ return `compose.yaml needs ${variables.join(', ')} from the environment, which npx dokebi dev-infra up does not set: \${NAME:?…} makes dev-infra up fail, and a bare \${NAME} becomes an empty value (Compose only warns), which breaks a port or a password. dev-infra up passes the passwords of dokebi.yaml: ${PASSWORD_VARIABLE}, and for every connection DOKEBI_<PLUGIN>_<CONNECTION>_PASSWORD (or _TOKEN; without the connection for main, such as DOKEBI_REDIS_PASSWORD); use those names, give a default in compose.yaml (\${NAME:-value}) or set it in .env`;
76
93
  }
77
94
  /** Compose project names: lower-case letters, digits, dashes and underscores. */
78
95
  export function composeProject(name) {
@@ -31,12 +31,6 @@ export declare const PHASE_MISSING: unique symbol;
31
31
  * the rest of `node_modules`, so `.env` files and other projects' files stay unreadable.
32
32
  */
33
33
  export declare function installReadRoots(packageDirectory: string): Promise<string[]>;
34
- /**
35
- * Runs one lifecycle phase of a plugin installation module in a child process.
36
- * The child uses the Node permission model: it may read only `readRoots`
37
- * (at their real and link paths), cannot write files or spawn processes, and receives no
38
- * parent environment variables. Node 24 does not restrict network access.
39
- */
40
34
  /**
41
35
  * The `--allow-fs-read` flags of the restricted child. Node 24.15's permission model denies a
42
36
  * granted folder when a sibling folder whose name starts with it is granted too (with
@@ -46,4 +40,10 @@ export declare function installReadRoots(packageDirectory: string): Promise<stri
46
40
  * the siblings that start with the same name.
47
41
  */
48
42
  export declare function readPermissions(roots: readonly string[]): string[];
43
+ /**
44
+ * Runs one lifecycle phase of a plugin installation module in a child process.
45
+ * The child uses the Node permission model: it may read only `readRoots`
46
+ * (at their real and link paths), cannot write files or spawn processes, and receives no
47
+ * parent environment variables. Node 24 does not restrict network access.
48
+ */
49
49
  export declare function runInstallModule(modulePath: string, phase: InstallPhase, context: InstallModuleContext, readRoots?: readonly string[]): Promise<unknown>;
@@ -116,12 +116,6 @@ export async function installReadRoots(packageDirectory) {
116
116
  debug('Install module read roots', { package: own, roots: result });
117
117
  return result;
118
118
  }
119
- /**
120
- * Runs one lifecycle phase of a plugin installation module in a child process.
121
- * The child uses the Node permission model: it may read only `readRoots`
122
- * (at their real and link paths), cannot write files or spawn processes, and receives no
123
- * parent environment variables. Node 24 does not restrict network access.
124
- */
125
119
  /**
126
120
  * The `--allow-fs-read` flags of the restricted child. Node 24.15's permission model denies a
127
121
  * granted folder when a sibling folder whose name starts with it is granted too (with
@@ -138,6 +132,12 @@ export function readPermissions(roots) {
138
132
  return `--allow-fs-read=${root}${shadowed ? '*' : ''}`;
139
133
  });
140
134
  }
135
+ /**
136
+ * Runs one lifecycle phase of a plugin installation module in a child process.
137
+ * The child uses the Node permission model: it may read only `readRoots`
138
+ * (at their real and link paths), cannot write files or spawn processes, and receives no
139
+ * parent environment variables. Node 24 does not restrict network access.
140
+ */
141
141
  export async function runInstallModule(modulePath, phase, context, readRoots = [dirname(modulePath)]) {
142
142
  const input = JSON.stringify(context);
143
143
  if (Buffer.byteLength(input) > MAX_BYTES)
package/dist/output.d.ts CHANGED
@@ -1,3 +1,3 @@
1
- export declare const CLI_VERSION = "0.4.29";
1
+ export declare const CLI_VERSION = "0.4.30";
2
2
  export declare function envelope(command: string, result: unknown, ok?: boolean): object;
3
3
  export declare function failure(command: string, error: unknown, mutationStarted: boolean): object;
package/dist/output.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { CliError } from './errors.js';
2
- export const CLI_VERSION = '0.4.29';
2
+ export const CLI_VERSION = '0.4.30';
3
3
  export function envelope(command, result, ok = true) {
4
4
  return { schemaVersion: 1, cliVersion: CLI_VERSION, command, ok, result, error: null };
5
5
  }
@@ -74,7 +74,8 @@ export type PluginOptionsVerdict = {
74
74
  * cannot say. Every listed plugin's main entry is imported in ONE permission-restricted child, as
75
75
  * install modules are (a child per plugin made `dokebi check` about a second slower on a blog
76
76
  * project), and its `createPlugin.checkOptions` gets its section. A plugin without it (a parser
77
- * function, an older core) is left out of the result; a plugin whose entry fails has `failed`.
77
+ * function, an older core) is left out of the result; a plugin whose entry fails has `failed`,
78
+ * and when the child itself fails (a time limit, no answer) every listed plugin has it.
78
79
  */
79
80
  export declare function checkPluginsOptions(base: string, plugins: readonly PluginManifest[], options: Record<string, unknown>): Promise<Map<string, PluginOptionsVerdict>>;
80
81
  export declare function checkPlugin(input: LifecycleInput): Promise<CheckResult>;
@@ -252,7 +252,8 @@ async function mainEntry(directory) {
252
252
  * cannot say. Every listed plugin's main entry is imported in ONE permission-restricted child, as
253
253
  * install modules are (a child per plugin made `dokebi check` about a second slower on a blog
254
254
  * project), and its `createPlugin.checkOptions` gets its section. A plugin without it (a parser
255
- * function, an older core) is left out of the result; a plugin whose entry fails has `failed`.
255
+ * function, an older core) is left out of the result; a plugin whose entry fails has `failed`,
256
+ * and when the child itself fails (a time limit, no answer) every listed plugin has it.
256
257
  */
257
258
  export async function checkPluginsOptions(base, plugins, options) {
258
259
  const verdicts = new Map();
@@ -296,6 +297,15 @@ export async function checkPluginsOptions(base, plugins, options) {
296
297
  ? { code: error.code, ...(error.detail ? { module: error.detail } : {}) }
297
298
  : { error: describeError(error) }),
298
299
  });
300
+ // Audit R8-g5b-5: the child itself failed (an entry that hangs until INSTALL_TIMEOUT or ends
301
+ // the process before it answers): no plugin's rules ran, so each has that verdict, which
302
+ // doctor and config set report as the warning PLUGIN_OPTIONS_CHECK_FAILED (start checks them
303
+ // too). Thrown, it made doctor an error and refused every config set of the project.
304
+ if (error instanceof InstallPlanningError && ISSUE_CODE.test(error.code)) {
305
+ for (const entry of entries)
306
+ verdicts.set(entry.id, { failed: error.code });
307
+ return verdicts;
308
+ }
299
309
  throw new CliError('PLUGIN_OPTIONS_CHECK_FAILED', `Plugin options could not be checked: ${error instanceof InstallPlanningError ? error.code : 'INSTALL_MODULE_FAILED'}`, { cause: error });
300
310
  }
301
311
  if (!Array.isArray(raw) || raw.length !== entries.length)
@@ -69,22 +69,36 @@ export async function productionDiagnostics(root, env = process.env) {
69
69
  add('NODE_ENV_NOT_PRODUCTION', 'error', 'NODE_ENV', 'NODE_ENV is not production here, so this check (and an app started like this) runs with development behaviour: run it as the service runs, NODE_ENV=production npx dokebi doctor --production (the systemd unit and compose file set it)');
70
70
  const { target, source } = await readSettings(root);
71
71
  const secretsFile = env[SECRETS_VARIABLE] || undefined;
72
- let options;
73
- try {
74
- options = (await applySecrets(parseConfig(source), secretsFile)).options;
75
- }
76
- catch (error) {
72
+ const failed = (error, file) => {
77
73
  if (!(error instanceof ConfigError))
78
74
  throw error;
79
- // The app would refuse to start with the same code; the rest is checked on the file alone.
80
- add(error.code, 'error', target.file, `${error.message}. ${error.fix}`, 'dokebi-config', {
75
+ // The app would refuse to start with the same code.
76
+ add(error.code, 'error', file, `${error.message}. ${error.fix}`, 'dokebi-config', {
81
77
  issues: error.issues,
82
78
  });
83
- // A settings file that does not parse has nothing more to check; a secrets problem leaves
84
- // the settings file itself readable.
85
- if (!error.code.startsWith('CONFIG_SECRETS') && !/secrets file/.test(error.message))
86
- return found;
87
- options = parseConfig(source).options;
79
+ };
80
+ let document;
81
+ try {
82
+ document = parseConfig(source);
83
+ }
84
+ catch (error) {
85
+ // A settings file that does not parse has nothing more to check.
86
+ failed(error, target.file);
87
+ return found;
88
+ }
89
+ let options;
90
+ let secretsFailed = false;
91
+ try {
92
+ options = (await applySecrets(document, secretsFile)).options;
93
+ }
94
+ catch (error) {
95
+ secretsFailed = true;
96
+ // A secrets problem leaves the settings file itself readable: the rest is checked on it
97
+ // alone. The list's own failures name the settings; the file's (unreadable, not YAML, a
98
+ // `secrets` list in it) name the secrets file (R8-g5a-4).
99
+ const code = error instanceof ConfigError ? error.code : '';
100
+ failed(error, code.startsWith('CONFIG_SECRETS') || secretsFile === undefined ? target.file : secretsFile);
101
+ options = document.options;
88
102
  }
89
103
  const state = readState(parseObject(await readFile(join(root, '.dokebi/state.json'), 'utf8'), 'state'));
90
104
  const installed = new Set(state.plugins.map((plugin) => optionsKey(plugin)));
@@ -127,7 +141,8 @@ export async function productionDiagnostics(root, env = process.env) {
127
141
  const placeholders = placeholderPaths(options);
128
142
  if (placeholders.length)
129
143
  add('PLACEHOLDER_LEFT', 'error', target.file, `these options still hold a <placeholder> of the sample: ${placeholders.join(', ')}; fill them in the settings (or the secrets file)`, null, { paths: placeholders });
130
- if (!found.some((item) => item.code.startsWith('CONFIG_SECRETS'))) {
144
+ // The secrets list is checked once: config secrets would refuse the same file again.
145
+ if (!secretsFailed) {
131
146
  try {
132
147
  const secrets = await configSecrets(root, env);
133
148
  for (const warning of secrets.warnings ?? [])
package/dist/project.d.ts CHANGED
@@ -78,6 +78,7 @@ export type GeneratedSecret = {
78
78
  readonly variable: string;
79
79
  readonly file: typeof ENV_FILE;
80
80
  };
81
+ /** Previous secrets `config secret --rotate` keeps after the new one in a list (AI-M05). */
81
82
  export declare const ROTATE_KEEP = 2;
82
83
  /** What `config secret` did at one option: names and counts only, never a value. */
83
84
  export interface SecretOutcome {
package/dist/project.js CHANGED
@@ -48,9 +48,9 @@ import { appViewValue, NO_VIEW, projectView } from './view-choice.js';
48
48
  import { installedPath, packageFile, workspacePackages, workspaceRootOf, } from './workspace.js';
49
49
  const GENERATED = 'src/dokebi.generated.ts';
50
50
  const EXAMPLE = 'dokebi.example.yaml';
51
- /** Previous secrets `config secret --rotate` keeps after the new one in a list (AI-M05). */
52
51
  /** An option key that holds an address (`url`, `uri`, `databaseUrl`, `endpointURI`). */
53
52
  const URL_KEY = /^(url|uri)$|(Url|URL|Uri|URI)$/;
53
+ /** Previous secrets `config secret --rotate` keeps after the new one in a list (AI-M05). */
54
54
  export const ROTATE_KEEP = 2;
55
55
  /** The generated registration differs from what the CLI wrote (D-0116: a sentence and a fix). */
56
56
  function modifiedRegistration() {
@@ -15,19 +15,25 @@ const HSTS_MIN = 15_552_000;
15
15
  function fetchOnce(url, timeoutMs, ca) {
16
16
  return new Promise((resolve, reject) => {
17
17
  const send = url.protocol === 'https:' ? httpsRequest : httpRequest;
18
+ // The whole answer, not only each pause, stays within the limit (a server that drips bytes).
19
+ const deadline = setTimeout(() => request.destroy(new Error(`no answer within ${timeoutMs} ms`)), timeoutMs);
18
20
  const request = send(url, {
19
21
  method: 'GET',
20
22
  headers: { 'user-agent': 'dokebi-verify-remote', accept: '*/*' },
21
23
  timeout: timeoutMs,
22
24
  ...(ca === undefined ? {} : { ca }),
23
25
  }, (response) => {
24
- // Only the status and headers matter; the body is read to the end and dropped.
25
- response.resume();
26
- response.once('end', () => resolve({ status: response.statusCode ?? 0, headers: response.headers }));
27
- response.once('error', reject);
26
+ // Only the status and headers matter: the body is never read (an event stream or a
27
+ // download at the URL would keep the check waiting), the connection is closed.
28
+ clearTimeout(deadline);
29
+ resolve({ status: response.statusCode ?? 0, headers: response.headers });
30
+ response.destroy();
28
31
  });
29
32
  request.once('timeout', () => request.destroy(new Error(`no answer within ${timeoutMs} ms`)));
30
- request.once('error', reject);
33
+ request.once('error', (error) => {
34
+ clearTimeout(deadline);
35
+ reject(error);
36
+ });
31
37
  request.end();
32
38
  });
33
39
  }
package/dist/server.d.ts CHANGED
@@ -108,7 +108,9 @@ export declare function checkProject(root: string): Promise<string>;
108
108
  * R1 T4 review: why a start failed, from the app log of this start only (after its last start
109
109
  * mark): the first record with an error, as `<code>: <first line>` and, when the error has
110
110
  * causes, `… <its last Caused by line>`. A START_FAILED said only "exited with code 1", and its
111
- * tail began with an earlier start's lines. Undefined when no record says.
111
+ * tail began with an earlier start's lines. A record below `error` that carries an error (a
112
+ * `warn` DB_CHECK_FAILED of a connection whose check failed) is named only when no record at
113
+ * `error` (or without a level) says (audit R8-g5b-1). Undefined when no record says.
112
114
  */
113
115
  export declare function startFailureCause(lines: readonly string[]): string | undefined;
114
116
  export interface LogOptions {
package/dist/server.js CHANGED
@@ -673,14 +673,19 @@ async function tail(file, lines, current) {
673
673
  }
674
674
  /** The line the log writer writes before each start (log-writer.ts). */
675
675
  const START_MARK = '--- dokebi start ';
676
+ /** Record levels below `error`: an error such a record carries did not stop the start. */
677
+ const LOWER_LEVELS = new Set(['trace', 'debug', 'info', 'warn']);
676
678
  /**
677
679
  * R1 T4 review: why a start failed, from the app log of this start only (after its last start
678
680
  * mark): the first record with an error, as `<code>: <first line>` and, when the error has
679
681
  * causes, `… <its last Caused by line>`. A START_FAILED said only "exited with code 1", and its
680
- * tail began with an earlier start's lines. Undefined when no record says.
682
+ * tail began with an earlier start's lines. A record below `error` that carries an error (a
683
+ * `warn` DB_CHECK_FAILED of a connection whose check failed) is named only when no record at
684
+ * `error` (or without a level) says (audit R8-g5b-1). Undefined when no record says.
681
685
  */
682
686
  export function startFailureCause(lines) {
683
687
  const from = lines.findLastIndex((line) => line.startsWith(START_MARK));
688
+ let lower;
684
689
  for (const line of lines.slice(from + 1)) {
685
690
  // Records are JSON lines; a stack line or a plain console line is not one.
686
691
  if (!line.startsWith('{'))
@@ -703,9 +708,12 @@ export function startFailureCause(lines) {
703
708
  const causes = text.split('\n').filter((each) => each.startsWith('Caused by: '));
704
709
  const deepest = causes.at(-1)?.slice('Caused by: '.length);
705
710
  const code = typeof record.code === 'string' ? `${record.code}: ` : '';
706
- return `${code}${first}${deepest ? ` … ${deepest}` : ''}`.slice(0, 600);
711
+ const said = `${code}${first}${deepest ? ` … ${deepest}` : ''}`.slice(0, 600);
712
+ if (!LOWER_LEVELS.has(String(record.level)))
713
+ return said;
714
+ lower ??= said;
707
715
  }
708
- return undefined;
716
+ return lower;
709
717
  }
710
718
  /** Rejects rotation settings outside LOG_LIMITS; bytes below 1 MB are allowed for tests. */
711
719
  function logSettings(options) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@dokebi/cli",
3
- "version": "0.4.29",
3
+ "version": "0.4.30",
4
4
  "description": "Project scaffolding, plugin catalog, recipes, install and verification CLI for Dokebi.",
5
5
  "keywords": [
6
6
  "dokebi",