@basaltkit/deploy 0.4.1 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +276 -23
  2. package/dist/answers.d.ts +70 -0
  3. package/dist/answers.js +196 -0
  4. package/dist/apache.js +11 -2
  5. package/dist/audit.d.ts +20 -0
  6. package/dist/audit.js +26 -0
  7. package/dist/backup.d.ts +17 -1
  8. package/dist/backup.js +49 -1
  9. package/dist/bin.js +9 -1
  10. package/dist/bootstrap.d.ts +68 -18
  11. package/dist/bootstrap.js +177 -45
  12. package/dist/caddy.js +2 -1
  13. package/dist/check.js +18 -5
  14. package/dist/checks.js +1 -1
  15. package/dist/cli.d.ts +22 -1
  16. package/dist/cli.js +498 -57
  17. package/dist/compose.d.ts +1 -1
  18. package/dist/compose.js +6 -1
  19. package/dist/config.d.ts +25 -2
  20. package/dist/config.js +65 -3
  21. package/dist/context.d.ts +43 -13
  22. package/dist/context.js +50 -7
  23. package/dist/detach.d.ts +23 -0
  24. package/dist/detach.js +105 -0
  25. package/dist/env-step.d.ts +16 -1
  26. package/dist/env-step.js +58 -5
  27. package/dist/events.d.ts +168 -0
  28. package/dist/events.js +477 -0
  29. package/dist/host.d.ts +171 -7
  30. package/dist/host.js +302 -41
  31. package/dist/index.d.ts +10 -5
  32. package/dist/index.js +7 -3
  33. package/dist/init.d.ts +2 -0
  34. package/dist/init.js +2 -1
  35. package/dist/install-plan.d.ts +40 -0
  36. package/dist/install-plan.js +433 -0
  37. package/dist/json-host.d.ts +32 -0
  38. package/dist/json-host.js +106 -0
  39. package/dist/lock.d.ts +45 -0
  40. package/dist/lock.js +128 -0
  41. package/dist/pipeline.d.ts +51 -3
  42. package/dist/pipeline.js +339 -173
  43. package/dist/protocol.d.ts +364 -0
  44. package/dist/protocol.js +134 -0
  45. package/dist/runs.d.ts +75 -0
  46. package/dist/runs.js +287 -0
  47. package/dist/state.d.ts +26 -13
  48. package/dist/state.js +68 -4
  49. package/dist/trust.d.ts +63 -0
  50. package/dist/trust.js +159 -0
  51. package/dist/version.d.ts +2 -0
  52. package/dist/version.js +10 -0
  53. package/package.json +5 -1
package/dist/cli.js CHANGED
@@ -1,43 +1,102 @@
1
1
  import { createRequire } from 'node:module';
2
- import { isAbsolute, join, resolve } from 'node:path';
3
- import { pathToFileURL } from 'node:url';
2
+ import { dirname, isAbsolute, join, resolve } from 'node:path';
3
+ import { fileURLToPath, pathToFileURL } from 'node:url';
4
+ import { AnswerChannel, askedQuestions, ANSWER_TIMEOUT_SECONDS } from './answers.js';
4
5
  import { bootstrap } from './bootstrap.js';
6
+ import { DETACHED_CHILD_ENV, detach } from './detach.js';
7
+ import { EventWriter, foreignSink, humanReporter, Redactor } from './events.js';
8
+ import { jsonHost } from './json-host.js';
9
+ import { isErrorCode, RUN_ID } from './protocol.js';
10
+ import { attach, cancel, createRunLog, newRunId, pruneRunLogs } from './runs.js';
5
11
  import { check } from './check.js';
6
12
  import { init } from './init.js';
7
13
  import { applyOverrides, DeployConfigError, parseOverrides, validateConfig } from './config.js';
8
- import { DeployError, detectPackageManager, resolveStateDir } from './context.js';
14
+ import { DeployAbortedError, DeployError, detectPackageManager, INSTALL_COMMAND, resolveStateDir, rootInstallCommand } from './context.js';
15
+ import { buildInstallPlan, install, readInstallPlan } from './install-plan.js';
16
+ import { untrustedToolPaths, USER_NAME } from './trust.js';
17
+ import { VERSION } from './version.js';
18
+ import { DeployLockedError } from './lock.js';
9
19
  import { envValues, parseEnv } from './dotenv.js';
10
20
  import { nodeHost } from './host.js';
11
- import { envCommand, install, plan, rollback, run, SKIPPABLE, status } from './pipeline.js';
21
+ import { envCommand, plan, refuseRoot, rollback, run, SKIPPABLE, status } from './pipeline.js';
12
22
  export const USAGE = `basalt-deploy — deploy this Basalt app on this server (RFC 0006)
13
23
 
14
- basalt-deploy init --domain=<host> [--tenants=subdomain|none] [--branch=<b>] [--proxy=apache|caddy|none] [--server]
15
- writes deploy.config.ts from the project (and, with --server, this server)
16
- sudo "$(command -v node)" node_modules/@basaltkit/deploy/dist/bin.js bootstrap --user=<name> [--dry-run]
17
- a fresh Ubuntu/Debian server, once: Docker, Node, pnpm, swap, ufw,
18
- Caddy; then pnpm install, env and install for that user
19
- basalt-deploy check the config is valid and types check; no server needed
20
- basalt-deploy plan what a run would do; changes nothing
21
- basalt-deploy run fetch, .env, infra, build, backup, migrate, restart, health
22
- basalt-deploy env the .env and the dedicated infra only (first setup)
23
- basalt-deploy rollback [--to=<sha>] back to the last healthy release (code only)
24
- basalt-deploy status the last releases and the process
25
- sudo "$(command -v node)" node_modules/@basaltkit/deploy/dist/bin.js install --user=<name>
26
- once per server, as root: vhost, state directory
24
+ As the app user, in the checkout (node node_modules/@basaltkit/deploy/dist/bin.js <command>):
25
+ init --domain=<host> [--tenants=subdomain|none] [--branch=<b>] [--proxy=apache|caddy|none] [--server]
26
+ writes deploy.config.ts from the project (and, with --server, this server)
27
+ check the config is valid and types check; no server needed
28
+ plan what a run would do; changes nothing
29
+ run [--unhold] fetch, .env, infra, build, backup, migrate, restart, health
30
+ (--unhold: deploy the commit a rollback held, deliberately)
31
+ env the .env and the dedicated infra only (first setup)
32
+ rollback [--to=<sha>] back to the last healthy release (code only); holds the commit it left
33
+ status the last releases, the process, the lock
34
+ install-plan [--out=<file>|-]
35
+ what install needs, as data (default <state dir>/install-plan.json);
36
+ prints the root command for install
37
+ attach <runId> --json [--from-seq=<n>] [--follow]
38
+ the events of a run (run/env/rollback --json), from any seq
39
+ cancel <runId> [--first-only]
40
+ SIGTERM to a detached run (a second cancel stops it at once;
41
+ --first-only refuses when the run was already cancelled)
42
+ ui how to start the local UI — on YOUR machine, never on the server
27
43
 
28
- Run it as \`node node_modules/@basaltkit/deploy/dist/bin.js <command>\`, not
29
- \`pnpm exec\`: pnpm ≥ 12 may rewrite pnpm-lock.yaml on any command it runs.
44
+ As root, with a copy of the tool root owns — never the checkout's node_modules:
45
+ cd / && sudo -H npx --yes --package=@basaltkit/deploy@<exact version> -- basalt-deploy <command>
46
+ bootstrap --user=<name> --dir=<checkout> [--dry-run] [--proxy=…] [--swap-gb=<n>] [--no-firewall]
47
+ a fresh Ubuntu/Debian server, once: Docker, Node, pnpm; as the user
48
+ pnpm install, env, install-plan; then swap, ufw, Caddy and install
49
+ install --plan=<file> --user=<name>
50
+ once per server: state directory, proxy site, env file ownership
51
+
52
+ Run the app user's commands with \`node\`, not \`pnpm exec\`: pnpm ≥ 12 may rewrite
53
+ pnpm-lock.yaml on any command it runs. As root, nothing loads deploy.config.ts.
54
+
55
+ Exit codes: 0 done · 1 failed (or refused) · 3 another deploy holds the lock · 130 stopped by a signal
56
+ (a second signal ends the process at once: 130/129/143)
57
+
58
+ Machine mode (RFC 0008): stdout carries NDJSON events only
59
+ --json[=1] status, check, plan, run, env, rollback, install-plan, attach, cancel
60
+ --answers=stdin run/env: answer lines {"v":1,"type":"answer","id":"env.KEY","value":"…"} on stdin
61
+ --answer-timeout=<s> how long a prompt waits for its answer (1–3600, default 600)
62
+ --detach run/rollback: in their own session; returns the runId once the lock is held
63
+ --via=ui recorded as the release's via
30
64
 
31
65
  Options:
32
66
  --config=<file> default deploy.config.ts
33
67
  --overrides=<file> server-local values, default /etc/basalt/<app>.json
68
+ --allow-root run an app-user command as root anyway (refused by default)
69
+ --unsafe-tool let install/bootstrap run from files another user can change (refused by default)
70
+ --actor=<name> who deploys, recorded with the release (default $BASALT_DEPLOY_ACTOR, else $USER)
34
71
  --skip=<steps> ${SKIPPABLE.join(', ')} (comma-separated); --no-fetch = --skip=fetch
35
72
  -h, --help
36
73
  `;
74
+ /**
75
+ * `basalt-deploy ui` (RFC 0009 §3.4): a hint, nothing else. The UI is a
76
+ * separate package that runs on the operator's machine and drives this CLI
77
+ * over ssh; this package gains no listener and no dependency for it.
78
+ */
79
+ export const UI_HINT = `The deploy UI runs on YOUR machine, never on the server: it listens on
80
+ 127.0.0.1 only and drives this server over your own ssh, as the app user.
81
+
82
+ On your machine (not here, and not in the app's package.json — the deploy
83
+ installs devDependencies on the server):
84
+
85
+ npx @basaltkit/deploy-ui@<exact version>
86
+
87
+ It opens your browser. Add a target (ssh destination and this checkout's
88
+ directory), check the connection, plan, deploy. See the @basaltkit/deploy-ui
89
+ README for its security model.
90
+ `;
91
+ /** Another deploy holds the lock: nothing was done. */
92
+ export const EXIT_LOCKED = 3;
93
+ /** A signal stopped the command at a step boundary. */
94
+ export const EXIT_ABORTED = 130;
37
95
  function parse(argv) {
38
96
  const values = new Map();
39
97
  const switches = new Set();
40
98
  let command = '';
99
+ const args = [];
41
100
  for (const arg of argv) {
42
101
  if (arg === '-h' || arg === '--help') {
43
102
  switches.add('help');
@@ -53,8 +112,45 @@ function parse(argv) {
53
112
  }
54
113
  if (!command)
55
114
  command = arg;
115
+ else
116
+ args.push(arg);
56
117
  }
57
- return { command, values, switches };
118
+ return { command, args, values, switches };
119
+ }
120
+ const COMMANDS = ['init', 'check', 'plan', 'run', 'env', 'rollback', 'status', 'install-plan', 'install', 'bootstrap', 'attach', 'cancel', 'ui'];
121
+ /** The commands that take the deploy lock, and so write a run log under --json. */
122
+ const LOCKED = new Set(['run', 'env', 'rollback']);
123
+ const usage = (message, hint) => new DeployError(message, [], 'usage', hint);
124
+ /** The files root is about to run: node, and this package's own (its directory and modules). */
125
+ async function assertTrustedTool(host, unsafe) {
126
+ const dir = dirname(fileURLToPath(import.meta.url));
127
+ const modules = (await host.list(dir)).filter((name) => name.endsWith('.js')).map((name) => join(dir, name));
128
+ const problems = await untrustedToolPaths(host, [process.execPath, dir, ...modules]);
129
+ if (problems.length === 0)
130
+ return;
131
+ const message = `root would run files another user can change:\n${problems.map((p) => ` - ${p}`).join('\n')}\n run a copy root owns: ${rootInstallCommand(VERSION, '<plan>', '<user>').replace(/ install --plan=.*$/, ' <command>')}, or a root-owned global install (sudo npm install -g @basaltkit/deploy@${VERSION}) and a root-owned node`;
132
+ if (!unsafe)
133
+ throw new DeployError(message);
134
+ host.out.warn(`--unsafe-tool: ${message}`);
135
+ }
136
+ /** `install-plan`: the plan as JSON — to stdout (`--out=-`) or a 0600 file — and the root command that reads it. */
137
+ async function writeInstallPlan(host, ctx, cwd, out) {
138
+ const plan = await buildInstallPlan(ctx, VERSION);
139
+ const text = `${JSON.stringify(plan, null, 2)}\n`;
140
+ if (out === '-') {
141
+ process.stdout.write(text);
142
+ return 0;
143
+ }
144
+ const path = out ? resolve(cwd, out) : join(ctx.stateDir, 'install-plan.json');
145
+ await host.mkdir(dirname(path), 0o700);
146
+ await host.writeFile(path, text, 0o600);
147
+ host.out.ok(`install plan written to ${path} (data only: root validates it, never runs your code)`);
148
+ host.out.info(`root will: give ${ctx.stateDir.startsWith('/var/lib/basalt/') ? ctx.stateDir : `/var/lib/basalt/${plan.app}`} to you (0700)${plan.envFiles.length ? `, give ${plan.envFiles.join(', ')} to you (0600)` : ''}${plan.proxy.kind !== 'none' && plan.proxy.managed ? `, write the ${plan.proxy.kind} site for ${plan.domain} → 127.0.0.1:${plan.port}` : ''}`);
149
+ const user = host.env['USER'] && USER_NAME.test(host.env['USER']) ? host.env['USER'] : '<this user>';
150
+ host.out.info('then, as an administrator (a pinned copy root owns, never this checkout\'s):');
151
+ host.out.info(` ${rootInstallCommand(VERSION, path, user)}`);
152
+ host.out.result?.('install-plan', { plan, path, rootCommand: rootInstallCommand(VERSION, path, user) });
153
+ return 0;
58
154
  }
59
155
  /** Loads deploy.config.ts with the app's own tsx when it has one, else Node's type stripping. */
60
156
  export async function loadConfig(dir, file) {
@@ -95,38 +191,284 @@ export async function createContext(host, dir, config) {
95
191
  ...(text === undefined ? {} : { values: envValues(parseEnv(text)) }),
96
192
  };
97
193
  }
98
- export async function main(argv, host = nodeHost(), cwd = process.cwd()) {
194
+ /** Streams whose reader is gone (EPIPE): written to no more. */
195
+ const broken = new WeakSet();
196
+ const watched = new WeakSet();
197
+ export function processIO(stream = process.stdout, input = process.stdin, errors = process.stderr) {
198
+ const original = stream.write.bind(stream);
199
+ const originalErrors = errors.write.bind(errors);
200
+ if (!watched.has(stream)) {
201
+ watched.add(stream);
202
+ // The SSH client gone: never a crash mid-migration; the run log keeps every event.
203
+ stream.on('error', (error) => { if (error.code === 'EPIPE')
204
+ broken.add(stream); });
205
+ }
206
+ return {
207
+ write(text) {
208
+ if (broken.has(stream))
209
+ return;
210
+ try {
211
+ original(text);
212
+ }
213
+ catch (error) {
214
+ if (error.code !== 'EPIPE')
215
+ throw error;
216
+ broken.add(stream);
217
+ }
218
+ },
219
+ stdin: () => input,
220
+ capture(sink) {
221
+ // stderr too: a UI may show it, and the config's console.error is as foreign as its console.log.
222
+ const targets = stream === errors ? [stream] : [stream, errors];
223
+ const previous = targets.map((target) => target.write);
224
+ for (const target of targets) {
225
+ target.write = ((chunk, encoding, callback) => {
226
+ sink(typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8'));
227
+ const done = typeof encoding === 'function' ? encoding : callback;
228
+ if (typeof done === 'function')
229
+ queueMicrotask(() => done());
230
+ return true;
231
+ });
232
+ }
233
+ return () => { targets.forEach((target, i) => { target.write = previous[i]; }); };
234
+ },
235
+ // The stream as it was before capture: the writer's own failure is never a foreign event.
236
+ stderr: (text) => {
237
+ try {
238
+ originalErrors(text);
239
+ }
240
+ catch {
241
+ // Nobody reads stderr any more: nothing else to tell.
242
+ }
243
+ },
244
+ };
245
+ }
246
+ export async function main(argv, host = nodeHost(), cwd = process.cwd(), io = processIO()) {
99
247
  const flags = parse(argv);
248
+ if (flags.switches.has('json') || flags.values.has('json'))
249
+ return machine(flags, host, cwd, io);
100
250
  if (flags.switches.has('help') || !flags.command || flags.command === 'help') {
101
251
  process.stdout.write(USAGE);
102
252
  return flags.command && flags.command !== 'help' ? 1 : 0;
103
253
  }
104
- const skip = [];
105
- for (const name of (flags.values.get('skip') ?? '').split(',').filter(Boolean)) {
106
- if (!SKIPPABLE.includes(name)) {
107
- host.out.error(`--skip=${name}: only ${SKIPPABLE.join(', ')} can be skipped`);
108
- return 1;
109
- }
110
- skip.push(name);
254
+ return session(flags, host, cwd, humanReporter(host.out));
255
+ }
256
+ /** The largest `.env` the redactor reads before the config's own read (createContext). */
257
+ const MAX_ENV_BYTES = 1024 * 1024;
258
+ /** `--json`: hello first, done last, nothing else on stdout. */
259
+ async function machine(flags, base, cwd, io) {
260
+ const redactor = new Redactor();
261
+ const given = flags.values.get('run-id');
262
+ const child = given !== undefined && RUN_ID.test(given) && base.env[DETACHED_CHILD_ENV] === '1' && (flags.command === 'run' || flags.command === 'rollback');
263
+ const runId = child ? given : LOCKED.has(flags.command) && !flags.switches.has('detach') ? newRunId(base) : undefined;
264
+ const writer = new EventWriter({
265
+ now: () => base.now(),
266
+ stdout: (line) => io.write(line),
267
+ redactor,
268
+ ...(runId ? { runId } : {}),
269
+ stdoutIsRunLog: child,
270
+ expectRunLog: Boolean(runId) && !child,
271
+ onFailure: (message) => io.stderr(`${message}\n`),
272
+ });
273
+ writer.emit({
274
+ type: 'hello', tool: '@basaltkit/deploy', version: VERSION, protocol: 1, command: flags.command, pid: base.pid(), host: base.hostname(),
275
+ ...(child || flags.switches.has('detach') ? { detached: true } : {}),
276
+ });
277
+ const timeout = Number(flags.values.get('answer-timeout'));
278
+ const json = jsonHost(base, writer, redactor, { answerTimeoutMs: (Number.isInteger(timeout) && timeout >= 1 && timeout <= 3600 ? timeout : ANSWER_TIMEOUT_SECONDS) * 1000 });
279
+ // The secrets the deploy was started with (a token in its environment), known before anything runs.
280
+ json.learn(Object.entries(base.env).filter((pair) => typeof pair[1] === 'string'));
281
+ // deploy.config.ts runs in this process: what it prints is data, never an event —
282
+ // and held until the redactor knows the .env it may print from.
283
+ const foreign = foreignSink(writer, () => json.output.current);
284
+ const restore = io.capture((text) => foreign.write(text));
285
+ const learnt = new Set();
286
+ const state = {
287
+ json, writer, io, child,
288
+ async secretsKnown(config) {
289
+ for (const path of envFilesOf(config, cwd)) {
290
+ if (learnt.has(path))
291
+ continue;
292
+ learnt.add(path);
293
+ const text = await readEnvForRedactor(base, path);
294
+ if (text !== undefined)
295
+ json.learn(envValues(parseEnv(text)), config);
296
+ }
297
+ foreign.release();
298
+ },
299
+ };
300
+ let code;
301
+ try {
302
+ code = await session(flags, json.host, cwd, writer, state);
303
+ }
304
+ finally {
305
+ foreign.end();
306
+ // No answer is read once the command is over: a late one never becomes an event after `done`.
307
+ state.channel?.finish();
308
+ restore();
111
309
  }
112
- if (flags.switches.has('no-fetch'))
113
- skip.push('fetch');
310
+ // attach ends with the run's own exit code; the run's error is in what it replayed.
311
+ if (code !== 0 && !writer.last.error && flags.command !== 'attach')
312
+ writer.emit(outcomeError(flags.command, writer));
313
+ writer.emit({ type: 'done', exitCode: code });
314
+ writer.close();
315
+ return code;
316
+ }
317
+ /** The `.env` files a config names (`.env` while none is known, or one that does not validate). */
318
+ function envFilesOf(config, cwd) {
319
+ const env = config?.env;
320
+ const file = typeof env?.file === 'string' ? env.file : '.env';
321
+ const mirrors = Array.isArray(env?.mirror) ? env.mirror.filter((m) => typeof m === 'string') : [];
322
+ return [file, ...mirrors].map((f) => resolve(cwd, f));
323
+ }
324
+ /** A `.env` for the redactor only: through its links, a regular file, at most 1 MiB; never an error. */
325
+ async function readEnvForRedactor(host, path) {
114
326
  try {
327
+ const real = await host.realpath(path);
328
+ return real === undefined ? undefined : await host.readPlainFile(real, MAX_ENV_BYTES);
329
+ }
330
+ catch {
331
+ return undefined;
332
+ }
333
+ }
334
+ /** A command that ended non-zero without throwing says why, with a code (the terminal already read it). */
335
+ function outcomeError(command, writer) {
336
+ const result = writer.last.result;
337
+ switch (command) {
338
+ case 'run':
339
+ case 'rollback':
340
+ return { type: 'error', code: 'release-failed', message: result?.data?.note ?? `${command} did not end with a healthy release` };
341
+ case 'plan':
342
+ return { type: 'error', code: 'preflight', message: 'plan: the problems above would stop a run' };
343
+ default:
344
+ return { type: 'error', code: 'failed', message: `${command} failed` };
345
+ }
346
+ }
347
+ /** The flags that only make sense together (RFC 0008 §3.2); refused before anything runs. */
348
+ function checkFlags(flags, json, env) {
349
+ const via = flags.values.get('via');
350
+ if (via !== undefined && via !== 'ui')
351
+ throw usage('--via takes only ui');
352
+ if ((flags.switches.has('first-only') || flags.values.has('first-only')) && (flags.command !== 'cancel' || flags.values.has('first-only')))
353
+ throw usage('--first-only is a switch of cancel');
354
+ const protocolOnly = ['answers', 'answer-timeout', 'detach', 'from-seq', 'follow', 'run-id'];
355
+ if (!json) {
356
+ for (const name of protocolOnly)
357
+ if (flags.values.has(name) || flags.switches.has(name))
358
+ throw usage(`--${name} needs --json`);
359
+ if (flags.command === 'attach')
360
+ throw usage('attach speaks only --json: its output is the run\'s events');
361
+ if (flags.command === 'cancel' && !flags.args[0])
362
+ throw usage('cancel <runId>');
363
+ return;
364
+ }
365
+ const version = flags.values.get('json');
366
+ if (version !== undefined && version !== '1')
367
+ throw new DeployError(`--json=${version}: this basalt-deploy ${VERSION} speaks protocol 1`, [], 'protocol-version');
368
+ const { command } = flags;
369
+ if (command === 'init' || command === 'install' || command === 'bootstrap' || command === 'ui') {
370
+ const why = command === 'init' ? 'it writes code into the checkout' : command === 'ui' ? 'it only prints how to start the local UI, which runs on the operator\'s machine' : 'root\'s confirmations are the control, never a pipe';
371
+ throw new DeployError(`${command} does not speak --json: ${why}`, [], 'unsupported');
372
+ }
373
+ if (flags.switches.has('help') || !command || !COMMANDS.includes(command))
374
+ throw usage(command && !flags.switches.has('help') ? `unknown command "${command}"` : 'a command is needed', 'basalt-deploy --help lists them');
375
+ if (flags.switches.has('answers') || (flags.values.has('answers') && flags.values.get('answers') !== 'stdin'))
376
+ throw usage('--answers takes only stdin');
377
+ if (flags.values.has('answers') && command !== 'run' && command !== 'env')
378
+ throw usage(`${command} asks nothing: --answers is for run and env`);
379
+ if (flags.values.has('answer-timeout') || flags.switches.has('answer-timeout')) {
380
+ if (!flags.values.has('answers'))
381
+ throw usage('--answer-timeout needs --answers=stdin');
382
+ if (!/^\d{1,4}$/.test(flags.values.get('answer-timeout') ?? '') || Number(flags.values.get('answer-timeout')) < 1 || Number(flags.values.get('answer-timeout')) > 3600)
383
+ throw usage('--answer-timeout takes 1 to 3600 seconds');
384
+ }
385
+ if ((flags.switches.has('detach') || flags.values.has('detach')) && command !== 'run' && command !== 'rollback')
386
+ throw usage(`${command} does not detach: only run and rollback`);
387
+ if ((flags.values.has('from-seq') || flags.switches.has('follow')) && command !== 'attach')
388
+ throw usage('--from-seq and --follow are for attach');
389
+ if (flags.values.has('from-seq') && !/^\d{1,15}$/.test(flags.values.get('from-seq') ?? ''))
390
+ throw usage('--from-seq takes a whole number');
391
+ if (flags.values.has('run-id') || flags.switches.has('run-id')) {
392
+ if (env[DETACHED_CHILD_ENV] !== '1')
393
+ throw usage('--run-id is set by run --detach, never by hand');
394
+ if (!RUN_ID.test(flags.values.get('run-id') ?? '') || (command !== 'run' && command !== 'rollback') || flags.switches.has('detach'))
395
+ throw usage('--run-id is malformed or misplaced');
396
+ }
397
+ if (command === 'install-plan' && flags.values.get('out') === '-')
398
+ throw usage('install-plan --json: the plan is in the result event, not on stdout (--out=- is refused)');
399
+ if ((command === 'attach' || command === 'cancel') && !flags.args[0])
400
+ throw usage(`${command} <runId>`);
401
+ }
402
+ /** The flags a detached child gets again — never an answer. */
403
+ function forwarded(flags) {
404
+ const out = [];
405
+ for (const name of ['actor', 'via', 'skip', 'to', 'config', 'overrides']) {
406
+ const value = flags.values.get(name);
407
+ if (value !== undefined)
408
+ out.push(`--${name}=${value}`);
409
+ }
410
+ for (const name of ['unhold', 'no-fetch', 'allow-root'])
411
+ if (flags.switches.has(name))
412
+ out.push(`--${name}`);
413
+ if (flags.values.has('answers'))
414
+ out.push('--answers=stdin');
415
+ return out;
416
+ }
417
+ /** One command, as the terminal and the protocol both run it; `reporter` says how it ended. */
418
+ async function session(flags, host, cwd, reporter, machine) {
419
+ /** The config as far as it loaded: which `.env` the redactor reads before an error is reported. */
420
+ let loaded;
421
+ try {
422
+ checkFlags(flags, machine !== undefined, host.env);
423
+ const skip = [];
424
+ for (const name of (flags.values.get('skip') ?? '').split(',').filter(Boolean)) {
425
+ if (!SKIPPABLE.includes(name))
426
+ throw usage(`--skip=${name}: only ${SKIPPABLE.join(', ')} can be skipped`);
427
+ skip.push(name);
428
+ }
429
+ if (flags.switches.has('no-fetch'))
430
+ skip.push('fetch');
431
+ // A hint: no config, no server state, nothing spawned.
432
+ if (flags.command === 'ui') {
433
+ process.stderr.write(UI_HINT);
434
+ return 0;
435
+ }
115
436
  const file = flags.values.get('config') ?? 'deploy.config.ts';
116
- if (flags.command === 'bootstrap') {
117
- // Runs before node_modules exist: the config only when it loads.
118
- const config = await loadConfig(cwd, file).catch(() => undefined);
119
- const proxy = flags.values.get('proxy') ?? config?.proxy?.kind ?? 'none';
120
- if (proxy !== 'apache' && proxy !== 'caddy' && proxy !== 'none')
437
+ // Root's commands: never deploy.config.ts, never the checkout's code.
438
+ if (flags.command === 'bootstrap' || flags.command === 'install') {
439
+ if (host.uid() === 0)
440
+ await assertTrustedTool(host, flags.switches.has('unsafe-tool'));
441
+ if (flags.command === 'install') {
442
+ const planPath = flags.values.get('plan');
443
+ if (!planPath) {
444
+ throw new DeployError(`install reads a plan, never deploy.config.ts: as the app user, in the checkout, run \`${INSTALL_COMMAND}\` — it writes the plan and prints the root command`);
445
+ }
446
+ if (!isAbsolute(planPath))
447
+ throw new DeployError('--plan takes an absolute path');
448
+ return await install(host, await readInstallPlan(host, planPath), flags.values.get('user') ?? host.env['SUDO_USER']);
449
+ }
450
+ const proxy = flags.values.get('proxy');
451
+ if (proxy !== undefined && proxy !== 'apache' && proxy !== 'caddy' && proxy !== 'none')
121
452
  throw new DeployError('--proxy is apache, caddy or none');
122
- return await bootstrap(host, cwd, {
453
+ const swap = flags.values.get('swap-gb');
454
+ if (swap !== undefined && !/^\d{1,2}$/.test(swap))
455
+ throw new DeployError('--swap-gb takes a whole number of GB');
456
+ // Never the working directory: root's commands run from `cd /`, and bootstrap may chown -R it.
457
+ const dirFlag = flags.values.get('dir');
458
+ if (!dirFlag || !isAbsolute(dirFlag))
459
+ throw new DeployError('bootstrap needs --dir=<checkout>, an absolute path (the app user\'s clone of the app) — it is never taken from the working directory');
460
+ return await bootstrap(host, dirFlag, {
123
461
  user: flags.values.get('user') ?? host.env['SUDO_USER'],
124
- proxy,
125
- swapGb: Number(flags.values.get('swap-gb') ?? config?.bootstrap?.swapGb ?? 4),
126
- firewall: !flags.switches.has('no-firewall') && config?.bootstrap?.firewall !== false,
462
+ ...(proxy ? { proxy } : {}),
463
+ ...(swap === undefined ? {} : { swapGb: Number(swap) }),
464
+ ...(flags.switches.has('no-firewall') ? { firewall: false } : {}),
127
465
  dryRun: flags.switches.has('dry-run'),
128
- });
466
+ }, VERSION);
129
467
  }
468
+ // Every command below loads deploy.config.ts — code the app user can
469
+ // change. As root that would be the app user's code running as root.
470
+ const allowRoot = flags.switches.has('allow-root');
471
+ refuseRoot(host, flags.command, allowRoot);
130
472
  if (flags.command === 'init') {
131
473
  const written = await init(host, cwd, flags.values, flags.switches);
132
474
  if (written !== 0)
@@ -135,21 +477,61 @@ export async function main(argv, host = nodeHost(), cwd = process.cwd()) {
135
477
  return await check(host, cwd, file, created);
136
478
  }
137
479
  let config = await loadConfig(cwd, file);
480
+ loaded = config;
138
481
  validateConfig(config);
482
+ await machine?.secretsKnown(config);
139
483
  if (flags.command === 'check')
140
484
  return await check(host, cwd, file, config);
141
485
  const overridesPath = flags.values.get('overrides') ?? `/etc/basalt/${config.app}.json`;
142
486
  const overrides = await host.readFile(overridesPath);
143
487
  if (overrides !== undefined)
144
488
  config = validateConfig(applyOverrides(config, parseOverrides(overrides, overridesPath)));
489
+ loaded = config;
490
+ if (machine) {
491
+ await machine.secretsKnown(config);
492
+ prepareMachine(machine, flags, config, cwd);
493
+ }
145
494
  const ctx = await createContext(host, cwd, config);
495
+ const via = flags.values.get('via') === 'ui' ? { via: 'ui' } : {};
496
+ const actor = { ...(flags.values.has('actor') ? { actor: flags.values.get('actor') } : {}), allowRoot, ...via };
497
+ const detaching = machine !== undefined && flags.switches.has('detach');
498
+ const options = { ...actor, ...(machine && LOCKED.has(flags.command) && !detaching ? { protocol: await protocolHooks(machine, ctx) } : {}) };
499
+ const detachRequest = (command) => ({
500
+ command, forward: forwarded(flags), ...(machine?.channel ? { answers: machine.channel } : {}),
501
+ execPath: process.execPath, binPath: fileURLToPath(new URL('./bin.js', import.meta.url)),
502
+ });
146
503
  switch (flags.command) {
147
504
  case 'plan': return await plan(ctx, { skip });
148
- case 'run': return await run(ctx, { skip });
149
- case 'env': return await envCommand(ctx);
150
- case 'rollback': return await rollback(ctx, flags.values.get('to'));
505
+ case 'run':
506
+ if (detaching)
507
+ return await detach(ctx, detachRequest('run'), reporter);
508
+ return await run(ctx, { ...options, skip, unhold: flags.switches.has('unhold') });
509
+ case 'env': return await envCommand(ctx, options);
510
+ case 'rollback':
511
+ if (detaching)
512
+ return await detach(ctx, detachRequest('rollback'), reporter);
513
+ return await rollback(ctx, flags.values.get('to'), options);
151
514
  case 'status': return await status(ctx);
152
- case 'install': return await install(ctx, flags.values.get('user') ?? host.env['SUDO_USER']);
515
+ case 'install-plan': return await writeInstallPlan(host, ctx, cwd, flags.values.get('out'));
516
+ case 'attach': {
517
+ const runId = flags.args[0];
518
+ const exit = await attach(host, ctx.stateDir, runId, {
519
+ fromSeq: Number(flags.values.get('from-seq') ?? 0),
520
+ follow: flags.switches.has('follow'),
521
+ emit: (event) => reporter.emit({ type: 'event', event }),
522
+ });
523
+ if (exit !== undefined)
524
+ return exit;
525
+ host.out.info(`run ${runId} is still running: attach --follow waits for its end`);
526
+ return 0;
527
+ }
528
+ case 'cancel': {
529
+ const runId = flags.args[0];
530
+ const sent = await cancel(host, ctx.stateDir, runId, { firstOnly: flags.switches.has('first-only') });
531
+ host.out.ok(`SIGTERM sent to run ${runId} (pid ${sent.pid})${sent.second ? ' — the second one: it stops at once, mid-step, and leaves a stale lock' : ' — it stops at the next safe point'}`);
532
+ host.out.result?.('cancel', { runId, pid: sent.pid, signal: 'SIGTERM', second: sent.second });
533
+ return 0;
534
+ }
153
535
  default:
154
536
  host.out.error(`unknown command "${flags.command}"`);
155
537
  process.stdout.write(USAGE);
@@ -157,19 +539,78 @@ export async function main(argv, host = nodeHost(), cwd = process.cwd()) {
157
539
  }
158
540
  }
159
541
  catch (error) {
160
- if (error instanceof DeployError) {
161
- host.out.error(error.message);
162
- return 1;
163
- }
164
- if (error instanceof DeployConfigError) {
165
- host.out.error(error.message);
166
- return 1;
167
- }
168
- // Anything else is a bug or an environment we did not foresee: say what
169
- // failed, keep the stack for BASALT_DEBUG=1.
170
- host.out.error(`unexpected: ${error.message ?? String(error)}`);
171
- if (host.env['BASALT_DEBUG'])
172
- host.out.info(error.stack ?? '');
542
+ // A config that failed to load may quote a .env value in its error: the redactor reads the .env first.
543
+ await machine?.secretsKnown(loaded);
544
+ return reportError(error, reporter, host.env['BASALT_DEBUG'] !== undefined && host.env['BASALT_DEBUG'] !== '');
545
+ }
546
+ }
547
+ /** The config is known: the redactor learns its secret keys, the answers start being read. */
548
+ function prepareMachine(machine, flags, config, cwd) {
549
+ machine.json.watchEnv(config, cwd);
550
+ if (!flags.values.has('answers') || machine.channel)
551
+ return;
552
+ const channel = new AnswerChannel(askedQuestions(config.env.ask), (key, value) => machine.json.secret(key, value));
553
+ channel.start(machine.io.stdin());
554
+ machine.json.useAnswers(channel);
555
+ machine.channel = channel;
556
+ }
557
+ /** A locked command under --json: its run log, the answers checked before the lock, retention after it. */
558
+ async function protocolHooks(machine, ctx) {
559
+ const { writer, channel, child } = machine;
560
+ const runId = writer.runId;
561
+ if (runId && !child) {
562
+ if (ctx.host.createLog)
563
+ machine.writer.attachLog((await createRunLog(ctx.host, ctx.stateDir, runId)).handle);
564
+ else
565
+ writer.dropBacklog();
566
+ }
567
+ return {
568
+ ...(runId ? { runId } : {}),
569
+ beforeLock: async () => {
570
+ // A detached child's answers are complete (the parent closed its stdin); an attended run's may still come.
571
+ if (channel)
572
+ await (child ? channel.drain() : channel.settle());
573
+ },
574
+ afterLock: async () => {
575
+ if (runId && ctx.host.readFileRange)
576
+ await pruneRunLogs(ctx.host, ctx.stateDir, runId);
577
+ },
578
+ afterAnswers: () => {
579
+ // A bad line that arrived after the lock and found no prompt still fails, before the .env is written.
580
+ channel?.throwIfFatal();
581
+ for (const key of channel?.finish() ?? [])
582
+ ctx.host.out.warn(`the answer for ${key} was not needed (already in the .env, or given by the environment): dropped`);
583
+ },
584
+ };
585
+ }
586
+ /** Every failure, as an `error` event and its exit code — the terminal shows the message, as it always did. */
587
+ function reportError(error, reporter, debug) {
588
+ // Distinct codes a wrapper (cron, CI) can act on: 3 = another deploy holds the lock.
589
+ if (error instanceof DeployLockedError) {
590
+ reporter.emit({ type: 'error', code: 'locked', message: error.message, ...(error.holder ? { holder: error.holder } : {}) });
591
+ return EXIT_LOCKED;
592
+ }
593
+ if (error instanceof DeployAbortedError) {
594
+ reporter.emit({ type: 'error', code: 'aborted', message: error.message });
595
+ return EXIT_ABORTED;
596
+ }
597
+ if (error instanceof DeployError) {
598
+ const code = error.code && isErrorCode(error.code) ? error.code : 'failed';
599
+ reporter.emit({
600
+ type: 'error', code, message: error.message,
601
+ ...(error.hint ? { hint: error.hint } : {}),
602
+ ...(error.findings.length ? { findings: error.findings } : {}),
603
+ });
604
+ return 1;
605
+ }
606
+ if (error instanceof DeployConfigError) {
607
+ reporter.emit({ type: 'error', code: 'config', message: error.message });
173
608
  return 1;
174
609
  }
610
+ // Anything else is a bug or an environment we did not foresee: say what
611
+ // failed, keep the stack for BASALT_DEBUG=1.
612
+ reporter.emit({ type: 'error', code: 'unexpected', message: `unexpected: ${error.message ?? String(error)}` });
613
+ if (debug)
614
+ reporter.emit({ type: 'log', stream: 'tool', level: 'info', text: error.stack ?? '', redacted: false });
615
+ return 1;
175
616
  }
package/dist/compose.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import type { ComposeRuntime } from './config.js';
1
+ import { type ComposeRuntime } from './config.js';
2
2
  import { type DeployContext, type Finding } from './context.js';
3
3
  /**
4
4
  * The Docker Compose runtime (RFC 0006 §13.2): images built once per commit