@dokebi/cli 0.4.28 → 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.
@@ -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) {
@@ -108,8 +108,15 @@ function ensureMap(document, path, code) {
108
108
  continue;
109
109
  if (!document.hasIn(current) || (isScalar(node) && node.value === null))
110
110
  document.setIn(current, document.createNode({}));
111
- else if (!isMap(node))
112
- throw new CliError(code, 'Configuration path crosses a non-mapping value');
111
+ else if (!isMap(node)) {
112
+ const at = current.slice(1).join('.');
113
+ throw new CliError(code, `Configuration path crosses a non-mapping value at ${at}`, {
114
+ details: {
115
+ path: at,
116
+ fix: `${at} holds a value that is not a mapping (a text, number or list): set the whole value instead (a JSON value, such as a list of objects), or unset it first (npx dokebi config unset ${at})`,
117
+ },
118
+ });
119
+ }
113
120
  }
114
121
  }
115
122
  /** Applies an edit inside options.<id> and proves no other plugin section changed. */
@@ -36,6 +36,17 @@ export interface ConfigSecretsResult {
36
36
  why: string;
37
37
  }>;
38
38
  }
39
+ /** The option at `path`, list items found by index or by name (`itemIndex`). */
40
+ export declare function valueAt(options: unknown, path: readonly string[]): unknown;
41
+ /** `path` with each list item it names (`itemIndex`) as its index; the keys after a miss as given. */
42
+ export declare function indexedPath(options: unknown, path: readonly string[]): string[];
43
+ /**
44
+ * `path` with each list index named by its item (its `name`, else the `type` of an item without
45
+ * a name) when that names exactly this item: the key a secrets file fills the item with, whatever
46
+ * the order of the list (`logging.targets.2.token` → `logging.targets.studio.token`). An item
47
+ * that cannot be named so keeps its index.
48
+ */
49
+ export declare function namedPath(options: unknown, path: readonly string[]): string[];
39
50
  /** The JSON Schema types the option at `keys` may have (properties, records, anyOf/oneOf). */
40
51
  export declare function schemaTypes(schema: unknown, keys: readonly string[]): Set<string>;
41
52
  /**
@@ -14,18 +14,81 @@ import { dependencyMap } from './npm-client.js';
14
14
  import { planLifecycle } from './plugin-lifecycle.js';
15
15
  import { readState } from './project-state.js';
16
16
  import { reloadSchemas } from './reloadable.js';
17
- function valueAt(options, path) {
17
+ const ITEM_INDEX = /^(?:0|[1-9][0-9]{0,5})$/;
18
+ function isRecord(value) {
19
+ return value !== null && typeof value === 'object' && !Array.isArray(value);
20
+ }
21
+ /**
22
+ * The item of `list` that `key` names, the way @dokebi/config merges a secrets file into a list:
23
+ * an index, else the one item whose `name` is `key`, else the one item without a name whose
24
+ * `type` is. `undefined` when no item, or more than one, matches.
25
+ */
26
+ function itemIndex(list, key) {
27
+ if (ITEM_INDEX.test(key))
28
+ return Number(key) < list.length ? Number(key) : undefined;
29
+ const only = (match) => {
30
+ const found = list.flatMap((item, index) => (isRecord(item) && match(item) ? [index] : []));
31
+ return found.length === 1 ? found[0] : found.length ? -1 : undefined;
32
+ };
33
+ const named = only((item) => item.name === key);
34
+ if (named !== undefined)
35
+ return named < 0 ? undefined : named;
36
+ const typed = only((item) => !Object.hasOwn(item, 'name') && item.type === key);
37
+ return typed === undefined || typed < 0 ? undefined : typed;
38
+ }
39
+ /** The option at `path`, list items found by index or by name (`itemIndex`). */
40
+ export function valueAt(options, path) {
18
41
  let value = options;
19
42
  for (const key of path) {
20
- if (Array.isArray(value) && /^\d+$/.test(key))
21
- value = value[Number(key)];
22
- else if (value && typeof value === 'object' && Object.hasOwn(value, key))
43
+ const index = Array.isArray(value) ? itemIndex(value, key) : undefined;
44
+ if (index !== undefined)
45
+ value = value[index];
46
+ else if (isRecord(value) && Object.hasOwn(value, key))
23
47
  value = value[key];
24
48
  else
25
49
  return undefined;
26
50
  }
27
51
  return value;
28
52
  }
53
+ /** `path` with each list item it names (`itemIndex`) as its index; the keys after a miss as given. */
54
+ export function indexedPath(options, path) {
55
+ const indexed = [];
56
+ let value = options;
57
+ for (const key of path) {
58
+ const index = Array.isArray(value) ? itemIndex(value, key) : undefined;
59
+ indexed.push(index === undefined ? key : String(index));
60
+ value = valueAt(value, [key]);
61
+ }
62
+ return indexed;
63
+ }
64
+ /**
65
+ * `path` with each list index named by its item (its `name`, else the `type` of an item without
66
+ * a name) when that names exactly this item: the key a secrets file fills the item with, whatever
67
+ * the order of the list (`logging.targets.2.token` → `logging.targets.studio.token`). An item
68
+ * that cannot be named so keeps its index.
69
+ */
70
+ export function namedPath(options, path) {
71
+ const named = [];
72
+ let value = options;
73
+ for (const key of path) {
74
+ if (Array.isArray(value) && ITEM_INDEX.test(key)) {
75
+ const item = value[Number(key)];
76
+ const name = !isRecord(item)
77
+ ? undefined
78
+ : Object.hasOwn(item, 'name')
79
+ ? item.name
80
+ : item.type;
81
+ named.push(typeof name === 'string' && !ITEM_INDEX.test(name) && itemIndex(value, name) === Number(key)
82
+ ? name
83
+ : key);
84
+ value = item;
85
+ continue;
86
+ }
87
+ named.push(key);
88
+ value = isRecord(value) && Object.hasOwn(value, key) ? value[key] : undefined;
89
+ }
90
+ return named;
91
+ }
29
92
  function empty(value) {
30
93
  return (value === undefined ||
31
94
  value === null ||
@@ -56,7 +119,8 @@ export function schemaTypes(schema, keys) {
56
119
  walk(properties[key], tail, depth + 1);
57
120
  else if (value.additionalProperties && typeof value.additionalProperties === 'object')
58
121
  walk(value.additionalProperties, tail, depth + 1);
59
- else if (/^\d+$/.test(key) && value.items)
122
+ // A list item, by index or by name (`logging.targets.studio.token`).
123
+ else if (value.items)
60
124
  walk(value.items, tail, depth + 1);
61
125
  };
62
126
  walk(schema, keys, 0);
@@ -141,13 +205,11 @@ export async function configSecrets(root, env = process.env) {
141
205
  // below, so a missing listed secret is reported instead of thrown.
142
206
  let merged = document.options;
143
207
  let secretsText;
144
- let secretOptions;
145
208
  if (secretsFile !== undefined) {
146
209
  try {
147
210
  merged = (await applySecrets({ schemaVersion: 1, options: document.options }, secretsFile))
148
211
  .options;
149
212
  secretsText = await readConfigFile(secretsFile);
150
- secretOptions = parseConfig(secretsText).options;
151
213
  }
152
214
  catch (error) {
153
215
  if (error instanceof ConfigError)
@@ -155,23 +217,31 @@ export async function configSecrets(root, env = process.env) {
155
217
  throw error;
156
218
  }
157
219
  }
158
- const fromConfig = new Set((await configShow(root, undefined, { source, file: target.file })).secrets);
220
+ // One path per secret: a list item by its name where the settings name it, the key a secrets
221
+ // file fills that item with (Studio v2, 11-02).
222
+ const canonical = (path) => namedPath(document.options, path.split('.')).join('.');
223
+ const fromConfig = new Set((await configShow(root, undefined, { source, file: target.file })).secrets.map(canonical));
159
224
  const fromSecrets = new Set(secretsText === undefined
160
225
  ? []
161
- : (await configShow(root, undefined, { source: secretsText, file: secretsFile }))
162
- .secrets);
226
+ : (await configShow(root, undefined, { source: secretsText, file: secretsFile })).secrets.map(canonical));
163
227
  const planned = await requiredSecretPaths(root, document.options);
164
228
  const state = readState(parseObject(await readFile(join(root, '.dokebi/state.json'), 'utf8'), 'state'));
165
229
  // The types tell a tool that writes the secrets file a list from a text (Studio v2, 11-01).
166
230
  const schemas = await reloadSchemas(root, state.plugins, state.settings ?? []);
167
- const required = new Set(planned.paths);
168
- const listed = document.secrets ?? [];
231
+ const required = new Set(planned.paths.map(canonical));
232
+ const listed = (document.secrets ?? []).map(canonical);
169
233
  const paths = [...new Set([...fromConfig, ...fromSecrets, ...listed, ...required])].sort();
170
234
  const secrets = paths.map((path) => {
171
235
  const set = !empty(valueAt(merged, path.split('.')));
172
236
  return {
173
237
  path,
174
- source: !set ? null : !empty(valueAt(secretOptions, path.split('.'))) ? 'secrets' : 'config',
238
+ // Both files never hold one option (CONFIG_SECRETS_CONFLICT): what the settings lack came
239
+ // from the secrets file.
240
+ source: !set
241
+ ? null
242
+ : empty(valueAt(document.options, path.split('.')))
243
+ ? 'secrets'
244
+ : 'config',
175
245
  listed: listed.includes(path),
176
246
  required: required.has(path),
177
247
  type: typeOf(schemas, path),
@@ -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 = [];
@@ -2,7 +2,7 @@
2
2
  export interface InstanceLayout {
3
3
  readonly app: string;
4
4
  readonly instance: string;
5
- /** Local port of the app (127.0.0.1). */
5
+ /** Local port of the app (127.0.0.1); 0 without @dokebi/web (nothing listens). */
6
6
  readonly port: number;
7
7
  /** systemd unit, system user and journald identifier; compose project name. */
8
8
  readonly unit: string;
@@ -104,8 +104,10 @@ WantedBy=timers.target
104
104
  }
105
105
  export function composeFile(at) {
106
106
  return `# ${at.app} (${at.instance}): docker compose -f deploy/compose/${at.instance}.yaml up -d --build
107
- # The container uses the host network, as the systemd unit would: the app listens on
108
- # 127.0.0.1:${at.port} (settings) behind the reverse proxy of the host, and reaches databases
107
+ # The container uses the host network, as the systemd unit would: ${at.port
108
+ ? `the app listens on
109
+ # 127.0.0.1:${at.port} (settings) behind the reverse proxy of the host, and`
110
+ : 'the app'} reaches databases
109
111
  # on the host at 127.0.0.1. Settings and secrets are mounted read-only from /etc.
110
112
  name: ${at.unit}
111
113
  services:
@@ -156,7 +158,7 @@ export function deployGuide(input) {
156
158
  const storage = input.plugins.includes('dokebi-storage');
157
159
  const first = input.instances[0];
158
160
  const rows = input.instances
159
- .map((at) => `| ${at.instance} | \`${at.unit}\` | 127.0.0.1:${at.port} | \`${at.settings}\` | \`${at.secrets}\` | \`${at.code}/current\` | \`${at.data}\` | \`${at.logs}\` | \`${at.backups}\` | \`${at.database}\` |`)
161
+ .map((at) => `| ${at.instance} | \`${at.unit}\` | ${at.port ? `127.0.0.1:${at.port}` : '— (no web server)'} | \`${at.settings}\` | \`${at.secrets}\` | \`${at.code}/current\` | \`${at.data}\` | \`${at.logs}\` | \`${at.backups}\` | \`${at.database}\` |`)
160
162
  .join('\n');
161
163
  const env = (at) => `DOKEBI_CONFIG=${at.settings} DOKEBI_SECRETS=${at.secrets}`;
162
164
  return `# Deploying ${app}
@@ -174,8 +176,10 @@ The repository keeps, per instance, \`deploy/<instance>/dokebi.example.yaml\` (t
174
176
  without secrets: copy it to the settings path) and \`deploy/<instance>/secrets.example.yaml\`
175
177
  (the secret paths with placeholders: the values live only in your secret store). The app refuses
176
178
  to start while a path of the settings' \`secrets:\` list is empty (CONFIG_SECRETS_MISSING), the
177
- secrets file is readable by others (CONFIG_SECRETS_UNSAFE) or both files set the same option
178
- (CONFIG_SECRETS_CONFLICT).${input.secrets.length ? `\n\nSecrets of this app: ${input.secrets.map((path) => `\`${path}\``).join(', ')}.` : ''}
179
+ secrets file is readable by others (CONFIG_SECRETS_UNSAFE), both files set the same option
180
+ (CONFIG_SECRETS_CONFLICT) or the secrets file names a list item the settings lack
181
+ (CONFIG_SECRETS_UNMATCHED: a secret inside a list item, such as logging.targets.studio.token,
182
+ fills that field of the item the settings name studio).${input.secrets.length ? `\n\nSecrets of this app: ${input.secrets.map((path) => `\`${path}\``).join(', ')}.` : ''}
179
183
 
180
184
  ## 1. Prepare the server (once per instance)
181
185
 
@@ -255,7 +259,8 @@ never reach a command line.
255
259
  - **Restore drill, every month** (and after a database upgrade): create an empty scratch database
256
260
  (e.g. \`${first.database}_drill\`), then
257
261
  \`${env(first)} DOKEBI_BACKUP_DIR=${first.backups} DOKEBI_RESTORE_URL=<scratch database URL> node deploy/restore-drill.mjs\`.
258
- 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
259
264
  collections) and the migration history with the live one, and prints one JSON line. Drop the
260
265
  scratch database afterwards.
261
266
  - **A real restore:** stop the instance, restore the chosen backup into a new database
@@ -296,9 +301,16 @@ ${input.domains.join(', ')} {
296
301
  }
297
302
  }
298
303
  # ${input.live} and ${input.ready} answer as the app answers them (never cached):
299
- # what an uptime monitor and dokebi verify --remote read.
300
- header ${input.live} Cache-Control no-store
301
- 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
+ }
302
314
  log {
303
315
  output file /var/log/caddy/${at.unit}.access.log
304
316
  }
@@ -310,28 +322,40 @@ export function nginxConf(input) {
310
322
  const names = input.domains.join(' ');
311
323
  const main = input.domains[0];
312
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; }`;
313
331
  return `# ${at.app} (${at.instance}): nginx terminates TLS for these names and passes requests to the
314
332
  # app on 127.0.0.1:${at.port}. The app trusts X-Forwarded-* only from dokebi-web.trustProxy
315
333
  # (127.0.0.1 and ::1 here). Certificates: certbot certonly --webroot -w /var/www/letsencrypt -d ${main}
316
334
  # Install: copy to /etc/nginx/conf.d/${at.unit}.conf, then nginx -t && systemctl reload nginx.
317
335
 
318
336
  ${input.streams
319
- ? `# 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.
320
340
  map $http_upgrade $${upstream}_connection {
321
341
  default upgrade;
322
- '' close;
342
+ '' '';
323
343
  }
324
344
 
325
345
  `
326
346
  : ''}upstream ${upstream} {
327
347
  server 127.0.0.1:${at.port};
328
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;
329
352
  }
330
353
 
331
354
  server {
332
355
  listen 80;
333
356
  listen [::]:80;
334
357
  server_name ${names};
358
+ ${only}
335
359
  location /.well-known/acme-challenge/ { root /var/www/letsencrypt; }
336
360
  location / { return 308 https://$host$request_uri; }
337
361
  }
@@ -341,6 +365,7 @@ server {
341
365
  listen 443 ssl http2;
342
366
  listen [::]:443 ssl http2;
343
367
  server_name ${names};
368
+ ${only}
344
369
 
345
370
  ssl_certificate /etc/letsencrypt/live/${main}/fullchain.pem;
346
371
  ssl_certificate_key /etc/letsencrypt/live/${main}/privkey.pem;
@@ -365,8 +390,9 @@ server {
365
390
  proxy_send_timeout ${input.readTimeoutSeconds}s;
366
391
 
367
392
  # Health routes as the app answers them, never cached (monitoring, dokebi verify --remote).
368
- location = ${input.live} { proxy_pass http://${upstream}; add_header Cache-Control no-store always; }
369
- 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; }
370
396
 
371
397
  location / {
372
398
  proxy_pass http://${upstream};
package/dist/deploy.d.ts CHANGED
@@ -28,6 +28,13 @@ export interface DeployProxyResult extends DeployResult {
28
28
  readonly file: string;
29
29
  readonly domains: readonly string[];
30
30
  }
31
+ /**
32
+ * The port of each instance asked for. An instance's port lives in its settings sample
33
+ * (`dokebi-web.port`); without @dokebi/web nothing listens, so no instance has one (0) and
34
+ * `--port` is refused. With it a new instance other than production (3000) and staging (3001)
35
+ * needs `--port`, and two instances of the server never share one.
36
+ */
37
+ export declare function instancePorts(names: readonly string[], known: ReadonlyMap<string, number>, port: number | undefined, web: boolean): Map<string, number>;
31
38
  export interface DeployInitOptions {
32
39
  readonly target: 'systemd' | 'compose';
33
40
  readonly instances: readonly string[];