@dokebi/cli 0.4.29 → 0.4.31

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.
@@ -12,7 +12,10 @@ interface Layer {
12
12
  readonly kind: 'app' | 'module' | 'shared';
13
13
  readonly name: string;
14
14
  readonly folder: string;
15
+ /** By canonical locale (`en-US` for a folder `en-us`), as @dokebi/i18n reads the folders. */
15
16
  readonly files: ReadonlyMap<string, ReadonlyMap<string, CatalogFile>>;
17
+ /** The folder name of each canonical locale, as it is spelled on disk. */
18
+ readonly folders: ReadonlyMap<string, string>;
16
19
  }
17
20
  /** i18n-layer-override: a key of one language in two layers, unless the overriding file lists it. */
18
21
  export declare function overrideProblems(shared: Layer | undefined, modules: readonly Layer[], apps: readonly Layer[]): Problem[];
@@ -21,7 +24,9 @@ export declare function layerMissingProblems(layers: readonly Layer[], locales:
21
24
  /** The problems of one file's text against the catalogs (the path is project-relative). */
22
25
  export declare function missingKeyProblems(path: string, text: string, catalogs: ReadonlyMap<string, ReadonlySet<string>>,
23
26
  /** dokebi-i18n defaultLocale: the end of every fallback chain. */
24
- defaultLocale?: string): Problem[];
27
+ defaultLocale?: string,
28
+ /** The shared catalogs' folder of the default locale as spelled on disk (`en-us`). */
29
+ defaultFolder?: string): Problem[];
25
30
  /** The translation rules over the catalogs and the files under `src/` (only with @dokebi/i18n). */
26
31
  export declare function missingKeysProblems(root: string, skip: (path: string) => boolean): Promise<Problem[]>;
27
32
  export {};
@@ -56,6 +56,23 @@ function flatten(value, prefix, keys, top = true) {
56
56
  flatten(child, `${prefix}.${key}`, keys, false);
57
57
  }
58
58
  }
59
+ /**
60
+ * A locale as @dokebi/i18n reads a folder name or defaultLocale (`Intl.Locale(name).baseName`:
61
+ * `en-us` is `en-US`), or undefined when it is none (audit R8-g5b-2: `en-us` folders with
62
+ * `defaultLocale: en-US` made every key "missing in the default locale").
63
+ */
64
+ function canonicalLocale(name) {
65
+ if (name.length < 2 || name.length > 128)
66
+ return undefined;
67
+ try {
68
+ return new Intl.Locale(name).baseName;
69
+ }
70
+ catch (error) {
71
+ if (error instanceof RangeError)
72
+ return undefined;
73
+ throw error;
74
+ }
75
+ }
59
76
  /** The files of one locales folder (`<locale>/<namespace>.json`); unreadable JSON is reported. */
60
77
  async function readLayer(root, kind, name, folder, broken) {
61
78
  let locales;
@@ -69,9 +86,23 @@ async function readLayer(root, kind, name, folder, broken) {
69
86
  throw error;
70
87
  }
71
88
  const files = new Map();
89
+ const folders = new Map();
72
90
  for (const locale of locales) {
73
91
  if (!locale.isDirectory())
74
92
  continue;
93
+ const canonical = canonicalLocale(locale.name);
94
+ if (canonical === undefined || folders.has(canonical)) {
95
+ broken.push({
96
+ rule: RULE,
97
+ severity: 'warning',
98
+ file: `${folder}/${locale.name}`,
99
+ line: 1,
100
+ message: `${folder}/${locale.name} is ${canonical === undefined ? 'not a BCP 47 locale' : `a second folder of the locale ${canonical} (${folders.get(canonical)})`}: its keys are not compared, and @dokebi/i18n refuses it at start`,
101
+ fix: 'name each locales folder by one BCP 47 locale (en, en-US, ko-KR)',
102
+ });
103
+ continue;
104
+ }
105
+ folders.set(canonical, locale.name);
75
106
  const byNamespace = new Map();
76
107
  for (const file of await readdir(join(root, folder, locale.name), { withFileTypes: true })) {
77
108
  if (!file.isFile() || !file.name.endsWith('.json'))
@@ -105,9 +136,9 @@ async function readLayer(root, kind, name, folder, broken) {
105
136
  : []);
106
137
  byNamespace.set(namespace, { path, text, keys, overrides });
107
138
  }
108
- files.set(locale.name, byNamespace);
139
+ files.set(canonical, byNamespace);
109
140
  }
110
- return files.size ? { kind, name, folder, files } : undefined;
141
+ return files.size ? { kind, name, folder, files, folders } : undefined;
111
142
  }
112
143
  /** The named folders of `parent` that have a locales folder, as layers in name order. */
113
144
  async function namedLayers(root, parent, kind, broken) {
@@ -234,7 +265,7 @@ export function layerMissingProblems(layers, locales) {
234
265
  const missing = [...keys].filter((key) => !has.has(key)).sort();
235
266
  if (!missing.length)
236
267
  continue;
237
- const path = `${layer.folder}/${locale}/${namespace}.json`;
268
+ const path = `${layer.folder}/${layer.folders.get(locale) ?? locale}/${namespace}.json`;
238
269
  const named = missing.slice(0, NAMED).join(', ');
239
270
  problems.push({
240
271
  rule: MISSING,
@@ -251,7 +282,9 @@ export function layerMissingProblems(layers, locales) {
251
282
  /** The problems of one file's text against the catalogs (the path is project-relative). */
252
283
  export function missingKeyProblems(path, text, catalogs,
253
284
  /** dokebi-i18n defaultLocale: the end of every fallback chain. */
254
- defaultLocale = 'en') {
285
+ defaultLocale = 'en',
286
+ /** The shared catalogs' folder of the default locale as spelled on disk (`en-us`). */
287
+ defaultFolder = defaultLocale) {
255
288
  // A key the default locale has never throws (every lookup chain ends there); one it lacks
256
289
  // throws in every locale that lacks it too.
257
290
  const fallback = catalogs.get(defaultLocale);
@@ -286,7 +319,7 @@ defaultLocale = 'en') {
286
319
  file: path,
287
320
  line,
288
321
  message: `${path} asks for the translation ${key}, which ${having.length ? `only the ${having.join(', ')} catalog${having.length > 1 ? 's have' : ' has'}, not the default locale ${defaultLocale}` : 'no catalog has'}: @dokebi/i18n throws MISSING_MESSAGE for it${having.length ? ' in the other locales' : ''} (under npx dokebi dev the page shows the key)${marker ? ' (the dokebi-check marker has no reason, so it does not count)' : ''}`,
289
- fix: `add ${key.slice(namespace.length + 1)} to ${LOCALES}/${defaultLocale}/${namespace}.json (the fallback of every locale; or to the locales folder of its app or module), or correct the key`,
322
+ fix: `add ${key.slice(namespace.length + 1)} to ${LOCALES}/${defaultFolder}/${namespace}.json (the fallback of every locale; or to the locales folder of its app or module), or correct the key`,
290
323
  });
291
324
  }
292
325
  }
@@ -306,7 +339,9 @@ async function defaultLocaleOf(root) {
306
339
  try {
307
340
  const options = parseProjectConfig(source).options;
308
341
  const section = options['dokebi-i18n'];
309
- return typeof section?.defaultLocale === 'string' ? section.defaultLocale : 'en';
342
+ return typeof section?.defaultLocale === 'string'
343
+ ? (canonicalLocale(section.defaultLocale) ?? section.defaultLocale)
344
+ : 'en';
310
345
  }
311
346
  catch (error) {
312
347
  debug('check: i18n default locale not read, en assumed', { error: error.message });
@@ -340,7 +375,7 @@ export async function missingKeysProblems(root, skip) {
340
375
  files++;
341
376
  const app = /^src\/apps\/([^/]+)\//.exec(path)?.[1];
342
377
  const catalogs = (app !== undefined && scoped.get(app)) || scoped.get('');
343
- problems.push(...missingKeyProblems(path, text, catalogs, fallback));
378
+ problems.push(...missingKeyProblems(path, text, catalogs, fallback, shared?.folders.get(fallback)));
344
379
  }
345
380
  debug('check: translation keys', {
346
381
  files,
@@ -19,10 +19,14 @@ const FORMS = '/dokebi/seal/forms.mjs';
19
19
  /** Files larger than this are not read (generated bundles, data). */
20
20
  const MAX_BYTES = 1024 * 1024;
21
21
  export const SEAL_HEAD_FIX = "write <%- data.seal?.head ?? '' %> in the <head> of the layout of an app page; a page rendered outside an app route (an oauth consent page) takes context.getDependency(apps).seal(request).head (AppGroupApi of @dokebi/app ^0.4.5, empty on a plain host). A page that is no app page at all takes // dokebi-check: allow seal-head-copied <reason>";
22
- /** True when the text before `index` on its line opens a comment. */
22
+ /**
23
+ * True when the text before `index` on its line opens a comment. The `//` of a URL
24
+ * (`https://host/…`, a scheme-relative `"//host/…"`) opens none (audit R8-g5b-3: a copy with the
25
+ * app's origin was not reported).
26
+ */
23
27
  function inComment(line, column) {
24
28
  const before = line.slice(0, column);
25
- return /^\s*(?:\*|\/\*)/.test(line) || before.includes('//') || before.includes('<%#');
29
+ return (/^\s*(?:\*|\/\*)/.test(line) || /(?:^|[^:'"`=/])\/\//.test(before) || before.includes('<%#'));
26
30
  }
27
31
  /** The seal head problems of one file's text (the path is project-relative, with `/`). */
28
32
  export function sealHeadProblems(path, text) {
package/dist/commands.js CHANGED
@@ -45,7 +45,7 @@ export const COMMANDS = [
45
45
  },
46
46
  {
47
47
  name: 'add',
48
- usage: 'dokebi add <package|local.tgz> [--set <path>=<value>]... [--adapter <pg|mysql2|mariadb|mongodb>] [--startup <required|optional>] [--no-first-app] [--dry-run] [--json]',
48
+ usage: 'dokebi add <package|local.tgz> [--set <path>=<value>]... [--adapter <id>] [--startup <required|optional>] [--no-first-app] [--dry-run] [--json]',
49
49
  summary: 'Install and register a plugin (and the plugins it requires); no version picks the newest one for this core',
50
50
  },
51
51
  {
@@ -369,7 +369,7 @@ export const COMMAND_DETAILS = {
369
369
  ],
370
370
  [
371
371
  '--adapter <id>',
372
- '@dokebi/db: pg | mysql2 | mariadb | mongodb (adapter file, connection main, driver, @types/pg)',
372
+ '@dokebi/db: pg | mysql2 | mariadb | mongodb (adapter file, connection main, driver, @types/pg); @dokebi/ai: anthropic | openai | gemini (the provider SDK)',
373
373
  ],
374
374
  [
375
375
  '--startup <required|optional>',
@@ -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.31";
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.31';
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)