@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.
- package/README.md +276 -23
- package/dist/answers.d.ts +70 -0
- package/dist/answers.js +196 -0
- package/dist/apache.js +11 -2
- package/dist/audit.d.ts +20 -0
- package/dist/audit.js +26 -0
- package/dist/backup.d.ts +17 -1
- package/dist/backup.js +49 -1
- package/dist/bin.js +9 -1
- package/dist/bootstrap.d.ts +68 -18
- package/dist/bootstrap.js +177 -45
- package/dist/caddy.js +2 -1
- package/dist/check.js +18 -5
- package/dist/checks.js +1 -1
- package/dist/cli.d.ts +22 -1
- package/dist/cli.js +498 -57
- package/dist/compose.d.ts +1 -1
- package/dist/compose.js +6 -1
- package/dist/config.d.ts +25 -2
- package/dist/config.js +65 -3
- package/dist/context.d.ts +43 -13
- package/dist/context.js +50 -7
- package/dist/detach.d.ts +23 -0
- package/dist/detach.js +105 -0
- package/dist/env-step.d.ts +16 -1
- package/dist/env-step.js +58 -5
- package/dist/events.d.ts +168 -0
- package/dist/events.js +477 -0
- package/dist/host.d.ts +171 -7
- package/dist/host.js +302 -41
- package/dist/index.d.ts +10 -5
- package/dist/index.js +7 -3
- package/dist/init.d.ts +2 -0
- package/dist/init.js +2 -1
- package/dist/install-plan.d.ts +40 -0
- package/dist/install-plan.js +433 -0
- package/dist/json-host.d.ts +32 -0
- package/dist/json-host.js +106 -0
- package/dist/lock.d.ts +45 -0
- package/dist/lock.js +128 -0
- package/dist/pipeline.d.ts +51 -3
- package/dist/pipeline.js +339 -173
- package/dist/protocol.d.ts +364 -0
- package/dist/protocol.js +134 -0
- package/dist/runs.d.ts +75 -0
- package/dist/runs.js +287 -0
- package/dist/state.d.ts +26 -13
- package/dist/state.js +68 -4
- package/dist/trust.d.ts +63 -0
- package/dist/trust.js +159 -0
- package/dist/version.d.ts +2 -0
- package/dist/version.js +10 -0
- 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,
|
|
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
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
|
|
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
|
-
|
|
29
|
-
|
|
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
|
-
|
|
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
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
|
|
110
|
-
|
|
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
|
-
|
|
113
|
-
|
|
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
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
if (
|
|
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
|
-
|
|
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(
|
|
126
|
-
|
|
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':
|
|
149
|
-
|
|
150
|
-
|
|
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
|
|
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
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
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