@basaltkit/deploy 0.6.1 → 0.8.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 +34 -2
- package/dist/bootstrap.d.ts +13 -4
- package/dist/bootstrap.js +20 -3
- package/dist/cli.js +32 -5
- package/dist/commits.d.ts +39 -0
- package/dist/commits.js +188 -0
- package/dist/config.d.ts +16 -0
- package/dist/config.js +4 -0
- package/dist/host.d.ts +6 -0
- package/dist/host.js +38 -3
- package/dist/index.d.ts +1 -1
- package/dist/install-plan.js +48 -2
- package/dist/pipeline.d.ts +19 -0
- package/dist/pipeline.js +87 -3
- package/dist/protocol.d.ts +68 -1
- package/dist/protocol.js +7 -0
- package/dist/state.d.ts +6 -0
- package/dist/state.js +8 -0
- package/dist/system.d.ts +50 -0
- package/dist/system.js +95 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -109,7 +109,8 @@ Node at `engines.node` (NodeSource), the pnpm the lockfile records — gives the
|
|
|
109
109
|
checkout and the `docker` group to the user (said plainly: that group is root on
|
|
110
110
|
the machine; rootless Docker is a later step), then, **as the user, in the
|
|
111
111
|
checkout**: `pnpm install`, `env` (it asks what it cannot generate) and
|
|
112
|
-
`install-plan`. From that plan (data, validated) it
|
|
112
|
+
`install-plan`. From that plan (data, validated) it installs the app's
|
|
113
|
+
[system packages](#system-packages), adds swap when RAM is under
|
|
113
114
|
6 GB (`bootstrap.swapGb`), ufw with SSH and 80/443 (turned on only when nothing
|
|
114
115
|
else listens; `--no-firewall`), Caddy when the proxy is `caddy()`, and runs
|
|
115
116
|
`install`. It never loads `deploy.config.ts` itself. A step that fails stops it;
|
|
@@ -167,6 +168,34 @@ import line. `caddy validate` runs before the reload; a failure puts every file
|
|
|
167
168
|
back. Deploys diff the site and never rewrite it; C1, C2 (not imported) and C8
|
|
168
169
|
(no `ask`) are checked as for Apache.
|
|
169
170
|
|
|
171
|
+
### System packages
|
|
172
|
+
|
|
173
|
+
What the app runs from the operating system — binaries it spawns, libraries
|
|
174
|
+
it loads — is declared with the app, as Debian/Ubuntu apt package names:
|
|
175
|
+
|
|
176
|
+
```ts
|
|
177
|
+
system: { packages: ['tesseract-ocr', 'poppler-utils', 'unzip'] },
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
Each name matches `[a-z0-9][a-z0-9.+-]{1,62}` (no option, no version, no shell
|
|
181
|
+
syntax) and appears once. Every deploy checks them as the app user
|
|
182
|
+
(`dpkg-query -W -f='${Status}' <pkg>`, no shell): a missing one is a **C12**
|
|
183
|
+
error that stops the run before anything is built and prints the fix,
|
|
184
|
+
`sudo apt-get install -y <missing>` — not the first user who reaches the
|
|
185
|
+
feature. Without `dpkg-query` (not Debian/Ubuntu) it is a warning: nothing
|
|
186
|
+
could be checked. `plan` prints `system: tesseract-ocr, poppler-utils, unzip
|
|
187
|
+
(installed)` or `(missing: …)`.
|
|
188
|
+
|
|
189
|
+
A deploy never installs them (it is not root). Root does, from the install
|
|
190
|
+
plan, which carries the names as data: `bootstrap` (after the user's
|
|
191
|
+
`install-plan`) and `install` run `apt-get update` and `apt-get install -y
|
|
192
|
+
--no-install-recommends` for the missing ones, non-interactively, from the
|
|
193
|
+
server's own apt sources. The app user chose the names and a package's install
|
|
194
|
+
scripts run as root, so the list is shown and needs a "yes" at the terminal;
|
|
195
|
+
when nothing is missing nothing is asked. Adding a package later: commit it,
|
|
196
|
+
then `install-plan` and `install` once (or the `apt-get` line the deploy
|
|
197
|
+
printed).
|
|
198
|
+
|
|
170
199
|
## Commands
|
|
171
200
|
|
|
172
201
|
As the app user, in the checkout (`node node_modules/@basaltkit/deploy/dist/bin.js <command>`):
|
|
@@ -175,11 +204,13 @@ As the app user, in the checkout (`node node_modules/@basaltkit/deploy/dist/bin.
|
|
|
175
204
|
|---|---|
|
|
176
205
|
| `init --domain=<host>` | writes `deploy.config.ts` from the project (`--server`: also from this server), then `check` |
|
|
177
206
|
| `check` | the config is valid and types check (your `tsc`). No server needed — for CI. |
|
|
178
|
-
| `plan` | every check, then what `run` would do.
|
|
207
|
+
| `plan` | every check, then what `run` would do, and the commits it would deploy. Asks nothing, and changes nothing `run` uses: the commits are fetched into a private ref it deletes again. |
|
|
179
208
|
| `run` | preflight → fetch → env → infra → build → validate → backup → migrate → release → health → record |
|
|
180
209
|
| `env` | the `.env` and the containers only |
|
|
181
210
|
| `rollback [--to=<sha>]` | the last healthy release. Code only — the database keeps its migrations. Holds the commit it left. |
|
|
182
211
|
| `status` | the last releases (who, from where), the process, the deploy lock, a hold |
|
|
212
|
+
| `commits --from=<sha> --to=<sha>` | the commits between two releases. Read-only: no lock, no fetch. |
|
|
213
|
+
| `commits --rollback [--to=<sha>]` | what `rollback` would take out of production, to the commit it would choose |
|
|
183
214
|
| `install-plan [--out=<file>\|-]` | what `install` needs, as JSON (default `<state dir>/install-plan.json`, 0600), and the root command to run |
|
|
184
215
|
| `attach <runId> --json [--from-seq=<n>] [--follow]` | the events of a run, from any point (machine mode, below) |
|
|
185
216
|
| `cancel <runId> [--first-only]` | SIGTERM to a detached run; a second `cancel` stops it at once (`--first-only` refuses instead) |
|
|
@@ -556,6 +587,7 @@ incident (RFC 0006 §5):
|
|
|
556
587
|
- **C9** run with a package manager major other than the one `packageManager` declares;
|
|
557
588
|
- **C10** keep a forbidden key, or a fixed key with another value.
|
|
558
589
|
- **C11** build a commit whose `packageManager` (pnpm ≥ 12) the lockfile does not record — checked in preflight and again on the commit the fetch brings, before any install. A lockfile the package manager rewrites during the deploy is put back to the committed version (with a warning), so the next deploy is not blocked; and no check runs the package manager inside the checkout.
|
|
590
|
+
- **C12** build when a `system.packages` entry is not installed (the fix is printed; a deploy never runs apt).
|
|
559
591
|
|
|
560
592
|
Secrets never reach a command line, the compose file, or the terminal: the
|
|
561
593
|
summary names keys, passwords travel in child-process environments only.
|
package/dist/bootstrap.d.ts
CHANGED
|
@@ -11,11 +11,13 @@ import type { Host } from './host.js';
|
|
|
11
11
|
* the user;
|
|
12
12
|
* 2. as the user, in the checkout: `pnpm install`, `env` (it may ask), then
|
|
13
13
|
* `install-plan`, whose JSON comes back as data;
|
|
14
|
-
* 3. as root, from that plan: swap (< 6 GB
|
|
15
|
-
* SSH listens), Caddy (proxy: caddy),
|
|
14
|
+
* 3. as root, from that plan: the app's `system.packages`, swap (< 6 GB
|
|
15
|
+
* RAM), ufw (only when nothing but SSH listens), Caddy (proxy: caddy),
|
|
16
|
+
* then `install`.
|
|
16
17
|
*
|
|
17
18
|
* `--dry-run` prints every command and runs none (phase 3 then assumes
|
|
18
|
-
* `--proxy`, or none
|
|
19
|
+
* `--proxy`, or none, and shows the system packages as a placeholder: the
|
|
20
|
+
* plan is not written in a dry run).
|
|
19
21
|
*/
|
|
20
22
|
export interface BootstrapOptions {
|
|
21
23
|
user: string | undefined;
|
|
@@ -36,6 +38,8 @@ export interface Action {
|
|
|
36
38
|
interactive?: boolean;
|
|
37
39
|
/** Asked at the terminal before a real run runs it; a "no" (or no terminal) stops bootstrap. */
|
|
38
40
|
confirm?: string;
|
|
41
|
+
/** With `confirm`: what the operator can do instead of answering, said when the answer is not "yes". */
|
|
42
|
+
otherwise?: string;
|
|
39
43
|
/** Runs as the app user: its output reaches root's terminal only through a pipe, line by line, sanitized. */
|
|
40
44
|
user?: boolean;
|
|
41
45
|
}
|
|
@@ -77,11 +81,16 @@ export declare function planSystem(host: Host, dir: string, user: string): Promi
|
|
|
77
81
|
export declare function userSteps(user: string, dir: string, tty: boolean): Action[];
|
|
78
82
|
/** The phase-2 command whose stdout is the install plan (JSON) — in its own session, like the other steps. */
|
|
79
83
|
export declare const planCommand: (user: string) => string[];
|
|
80
|
-
/**
|
|
84
|
+
/**
|
|
85
|
+
* Phase 3 — the app's system packages, swap, ufw, Caddy, from the plan (or
|
|
86
|
+
* the flags). `packages` undefined: a dry run, which has no plan — the
|
|
87
|
+
* install is shown with a placeholder for the names.
|
|
88
|
+
*/
|
|
81
89
|
export declare function planServer(host: Host, options: {
|
|
82
90
|
proxy: 'apache' | 'caddy' | 'none';
|
|
83
91
|
swapGb: number;
|
|
84
92
|
firewall: boolean;
|
|
93
|
+
packages?: string[];
|
|
85
94
|
}): Promise<{
|
|
86
95
|
actions: Action[];
|
|
87
96
|
notes: string[];
|
package/dist/bootstrap.js
CHANGED
|
@@ -3,8 +3,8 @@ import { below, lockedPnpm, minimumVersion } from './checks.js';
|
|
|
3
3
|
import { DeployError } from './context.js';
|
|
4
4
|
import { LineSplitter, sanitize } from './events.js';
|
|
5
5
|
import { install, parseInstallPlan } from './install-plan.js';
|
|
6
|
+
import { APT, aptInstall, fixCommand, packageStatus } from './system.js';
|
|
6
7
|
import { CHECKOUT_PATH, USER_NAME } from './trust.js';
|
|
7
|
-
const APT = ['env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get'];
|
|
8
8
|
/** The oldest pnpm root installs globally (lockfile v9; the app user chooses the version, root sets the floor). */
|
|
9
9
|
export const MIN_PNPM = [9, 0, 0];
|
|
10
10
|
// `/`, never a world-writable directory: a tool that reads project config from its working directory finds none there.
|
|
@@ -107,6 +107,7 @@ export async function planSystem(host, dir, user) {
|
|
|
107
107
|
what: `${dir} owned by ${user}`,
|
|
108
108
|
commands: [['chown', '-R', `${user}:`, dir]],
|
|
109
109
|
confirm: `${dir} is ${owner || 'unknown'}'s: give it and everything in it to ${user} (chown -R)?`,
|
|
110
|
+
otherwise: `make ${dir} the user's first`,
|
|
110
111
|
});
|
|
111
112
|
}
|
|
112
113
|
const groups = (await host.exec('id', ['-nG', user], OUTSIDE)).stdout.split(/\s+/);
|
|
@@ -151,10 +152,25 @@ export function userSteps(user, dir, tty) {
|
|
|
151
152
|
}
|
|
152
153
|
/** The phase-2 command whose stdout is the install plan (JSON) — in its own session, like the other steps. */
|
|
153
154
|
export const planCommand = (user) => ['setsid', '-w', 'sudo', '-u', user, '-H', '--', 'node', BIN, 'install-plan', '--out=-'];
|
|
154
|
-
/**
|
|
155
|
+
/**
|
|
156
|
+
* Phase 3 — the app's system packages, swap, ufw, Caddy, from the plan (or
|
|
157
|
+
* the flags). `packages` undefined: a dry run, which has no plan — the
|
|
158
|
+
* install is shown with a placeholder for the names.
|
|
159
|
+
*/
|
|
155
160
|
export async function planServer(host, options) {
|
|
156
161
|
const actions = [];
|
|
157
162
|
const notes = [];
|
|
163
|
+
if (options.packages === undefined) {
|
|
164
|
+
actions.push({ what: 'system packages: those of system.packages not installed (from the install plan)', commands: aptInstall(['<system.packages>']) });
|
|
165
|
+
}
|
|
166
|
+
else if (options.packages.length > 0) {
|
|
167
|
+
// Names the plan carries, validated by parseInstallPlan; apt only checked for (planSystem refused a server without it).
|
|
168
|
+
const { missing, unverified } = await packageStatus(host, options.packages, OUTSIDE.cwd);
|
|
169
|
+
const install = unverified ? options.packages : missing;
|
|
170
|
+
// The app user chose them and their install scripts run as root: asked, as install asks.
|
|
171
|
+
if (install.length)
|
|
172
|
+
actions.push({ what: `system packages: ${install.join(', ')}`, commands: aptInstall(install), confirm: `Install ${install.join(', ')} (system.packages) as root?`, otherwise: `install them first: ${fixCommand(install)}` });
|
|
173
|
+
}
|
|
158
174
|
const meminfo = (await host.readFile('/proc/meminfo')) ?? '';
|
|
159
175
|
const memGb = Number(/MemTotal:\s+(\d+)/.exec(meminfo)?.[1] ?? 0) / 1024 / 1024;
|
|
160
176
|
const swapKb = Number(/SwapTotal:\s+(\d+)/.exec(meminfo)?.[1] ?? 0);
|
|
@@ -237,7 +253,7 @@ async function runActions(host, actions, dryRun) {
|
|
|
237
253
|
for (const action of actions) {
|
|
238
254
|
host.out.info(action.what);
|
|
239
255
|
if (action.confirm && !dryRun && !(await host.confirm(action.confirm))) {
|
|
240
|
-
throw new DeployError(`${action.what}: not confirmed — nothing more was done (a terminal must answer
|
|
256
|
+
throw new DeployError(`${action.what}: not confirmed — nothing more was done (a terminal must answer${action.otherwise ? `; or ${action.otherwise}` : ''})`);
|
|
241
257
|
}
|
|
242
258
|
for (const command of action.commands) {
|
|
243
259
|
host.out.info(` + ${command.join(' ')}${action.cwd ? ` (in ${action.cwd})` : ''}`);
|
|
@@ -297,6 +313,7 @@ export async function bootstrap(host, dir, options, tool) {
|
|
|
297
313
|
proxy: options.proxy ?? plan.proxy.kind,
|
|
298
314
|
swapGb: options.swapGb ?? plan.bootstrap?.swapGb ?? 4,
|
|
299
315
|
firewall: options.firewall ?? plan.bootstrap?.firewall ?? true,
|
|
316
|
+
packages: plan.system?.packages ?? [],
|
|
300
317
|
});
|
|
301
318
|
await runActions(host, server.actions, false);
|
|
302
319
|
await install(host, plan, user);
|
package/dist/cli.js
CHANGED
|
@@ -18,7 +18,7 @@ import { VERSION } from './version.js';
|
|
|
18
18
|
import { DeployLockedError } from './lock.js';
|
|
19
19
|
import { envValues, parseEnv } from './dotenv.js';
|
|
20
20
|
import { nodeHost } from './host.js';
|
|
21
|
-
import { envCommand, plan, refuseRoot, rollback, run, SKIPPABLE, status } from './pipeline.js';
|
|
21
|
+
import { commitsCommand, envCommand, plan, refuseRoot, rollback, run, SKIPPABLE, status } from './pipeline.js';
|
|
22
22
|
export const USAGE = `basalt-deploy — deploy this Basalt app on this server (RFC 0006)
|
|
23
23
|
|
|
24
24
|
As the app user, in the checkout (node node_modules/@basaltkit/deploy/dist/bin.js <command>):
|
|
@@ -31,6 +31,9 @@ As the app user, in the checkout (node node_modules/@basaltkit/deploy/dist/bin.j
|
|
|
31
31
|
env the .env and the dedicated infra only (first setup)
|
|
32
32
|
rollback [--to=<sha>] back to the last healthy release (code only); holds the commit it left
|
|
33
33
|
status the last releases, the process, the lock
|
|
34
|
+
commits --from=<sha> --to=<sha> | --rollback [--to=<sha>]
|
|
35
|
+
the commits between two releases, or what a rollback would take out
|
|
36
|
+
of production; read-only (no lock, no fetch)
|
|
34
37
|
install-plan [--out=<file>|-]
|
|
35
38
|
what install needs, as data (default <state dir>/install-plan.json);
|
|
36
39
|
prints the root command for install
|
|
@@ -45,9 +48,10 @@ As root, with a copy of the tool root owns — never the checkout's node_modules
|
|
|
45
48
|
cd / && sudo -H npx --yes --package=@basaltkit/deploy@<exact version> -- basalt-deploy <command>
|
|
46
49
|
bootstrap --user=<name> --dir=<checkout> [--dry-run] [--proxy=…] [--swap-gb=<n>] [--no-firewall]
|
|
47
50
|
a fresh Ubuntu/Debian server, once: Docker, Node, pnpm; as the user
|
|
48
|
-
pnpm install, env, install-plan; then swap, ufw, Caddy and install
|
|
51
|
+
pnpm install, env, install-plan; then system packages, swap, ufw, Caddy and install
|
|
49
52
|
install --plan=<file> --user=<name>
|
|
50
|
-
once per server: state directory, proxy site, env file ownership
|
|
53
|
+
once per server: state directory, proxy site, env file ownership,
|
|
54
|
+
the app's missing system packages (apt, after a yes)
|
|
51
55
|
|
|
52
56
|
Run the app user's commands with \`node\`, not \`pnpm exec\`: pnpm ≥ 12 may rewrite
|
|
53
57
|
pnpm-lock.yaml on any command it runs. As root, nothing loads deploy.config.ts.
|
|
@@ -56,7 +60,7 @@ Exit codes: 0 done · 1 failed (or refused) · 3 another deploy holds the lock
|
|
|
56
60
|
(a second signal ends the process at once: 130/129/143)
|
|
57
61
|
|
|
58
62
|
Machine mode (RFC 0008): stdout carries NDJSON events only
|
|
59
|
-
--json[=1] status, check, plan, run, env, rollback, install-plan, attach, cancel
|
|
63
|
+
--json[=1] status, check, plan, run, env, rollback, commits, install-plan, attach, cancel
|
|
60
64
|
--answers=stdin run/env: answer lines {"v":1,"type":"answer","id":"env.KEY","value":"…"} on stdin
|
|
61
65
|
--answer-timeout=<s> how long a prompt waits for its answer (1–3600, default 600)
|
|
62
66
|
--detach run/rollback: in their own session; returns the runId once the lock is held
|
|
@@ -117,7 +121,7 @@ function parse(argv) {
|
|
|
117
121
|
}
|
|
118
122
|
return { command, args, values, switches };
|
|
119
123
|
}
|
|
120
|
-
const COMMANDS = ['init', 'check', 'plan', 'run', 'env', 'rollback', 'status', 'install-plan', 'install', 'bootstrap', 'attach', 'cancel', 'ui'];
|
|
124
|
+
const COMMANDS = ['init', 'check', 'plan', 'run', 'env', 'rollback', 'status', 'commits', 'install-plan', 'install', 'bootstrap', 'attach', 'cancel', 'ui'];
|
|
121
125
|
/** The commands that take the deploy lock, and so write a run log under --json. */
|
|
122
126
|
const LOCKED = new Set(['run', 'env', 'rollback']);
|
|
123
127
|
const usage = (message, hint) => new DeployError(message, [], 'usage', hint);
|
|
@@ -406,6 +410,28 @@ function checkFlags(flags, json, env) {
|
|
|
406
410
|
if ((command === 'attach' || command === 'cancel') && !flags.args[0])
|
|
407
411
|
throw usage(`${command} <runId>`);
|
|
408
412
|
}
|
|
413
|
+
const SHA = /^[0-9a-f]{7,40}$/;
|
|
414
|
+
/** `commits`: two shas, or `--rollback` with the `--to` a rollback would take. */
|
|
415
|
+
function commitsRequest(flags) {
|
|
416
|
+
const sha = (name) => {
|
|
417
|
+
const value = flags.values.get(name);
|
|
418
|
+
if (value !== undefined && !SHA.test(value))
|
|
419
|
+
throw usage(`--${name}=${value}: a commit sha (7 to 40 lowercase hex digits)`);
|
|
420
|
+
return value;
|
|
421
|
+
};
|
|
422
|
+
const from = sha('from');
|
|
423
|
+
const to = sha('to');
|
|
424
|
+
if (flags.values.has('rollback'))
|
|
425
|
+
throw usage('--rollback is a switch: commits --rollback [--to=<sha>]');
|
|
426
|
+
if (flags.switches.has('rollback')) {
|
|
427
|
+
if (from !== undefined)
|
|
428
|
+
throw usage('commits --rollback takes no --from: it starts from what is deployed');
|
|
429
|
+
return { rollback: true, ...(to === undefined ? {} : { to }) };
|
|
430
|
+
}
|
|
431
|
+
if (from === undefined || to === undefined)
|
|
432
|
+
throw usage('commits --from=<sha> --to=<sha>, or commits --rollback [--to=<sha>]');
|
|
433
|
+
return { from, to };
|
|
434
|
+
}
|
|
409
435
|
/** The flags a detached child gets again — never an answer. */
|
|
410
436
|
function forwarded(flags) {
|
|
411
437
|
const out = [];
|
|
@@ -519,6 +545,7 @@ async function session(flags, host, cwd, reporter, machine) {
|
|
|
519
545
|
return await detach(ctx, detachRequest('rollback'), reporter);
|
|
520
546
|
return await rollback(ctx, flags.values.get('to'), options);
|
|
521
547
|
case 'status': return await status(ctx);
|
|
548
|
+
case 'commits': return await commitsCommand(ctx, commitsRequest(flags));
|
|
522
549
|
case 'install-plan': return await writeInstallPlan(host, ctx, cwd, flags.values.get('out'));
|
|
523
550
|
case 'attach': {
|
|
524
551
|
const runId = flags.args[0];
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
import type { DeployContext } from './context.js';
|
|
2
|
+
import { type CommitInfo, type Commits } from './protocol.js';
|
|
3
|
+
export declare const MAX_SUBJECT = 200;
|
|
4
|
+
export declare const MAX_AUTHOR = 100;
|
|
5
|
+
/** Per git call: a list of 50 capped commits is far below this; a huge one is cut, never read. */
|
|
6
|
+
export declare const MAX_GIT_OUTPUT_BYTES: number;
|
|
7
|
+
export declare const GIT_TIMEOUT_MS = 5000;
|
|
8
|
+
/** The plan's fetch reaches the network. */
|
|
9
|
+
export declare const FETCH_TIMEOUT_MS = 30000;
|
|
10
|
+
/** Where `plan` fetches the branch: never the tracking ref `run` merges from. Deleted after use. */
|
|
11
|
+
export declare const PREVIEW_REF = "refs/basalt-deploy/preview";
|
|
12
|
+
/** One line of the author's text: no escapes, controls, newlines or bidi overrides, at most `max` characters. */
|
|
13
|
+
export declare function cleanText(text: string, max: number): string;
|
|
14
|
+
/**
|
|
15
|
+
* `git log -z` with {@link FORMAT}: five fields per commit. A bad sha or a
|
|
16
|
+
* wrong field count is a parse that went wrong — the whole list is refused.
|
|
17
|
+
* A bad date is the author's to forge: only that date is dropped.
|
|
18
|
+
*/
|
|
19
|
+
export declare function parseLog(stdout: string): CommitInfo[] | undefined;
|
|
20
|
+
/**
|
|
21
|
+
* What changes when the code goes from `from` to `to` (both full shas). The
|
|
22
|
+
* whole ancestry, never `--first-parent`: the commits a merge brings in go
|
|
23
|
+
* out too. Two lists, so a rewritten branch shows what it drops as well.
|
|
24
|
+
*/
|
|
25
|
+
export declare function commitRange(ctx: DeployContext, from: string, to: string): Promise<Commits>;
|
|
26
|
+
/** The subject of each commit, by sha, in one git call; undefined when git could not say. Missing commits are left out. */
|
|
27
|
+
export declare function commitSubjects(ctx: DeployContext, shas: string[]): Promise<Record<string, string> | undefined>;
|
|
28
|
+
/** The full sha of `rev`, a commit in this checkout; undefined when it is not one. */
|
|
29
|
+
export declare function resolveCommit(ctx: DeployContext, rev: string): Promise<string | undefined>;
|
|
30
|
+
/**
|
|
31
|
+
* What `run` would deploy, for `plan`: HEAD to the branch's tip on the
|
|
32
|
+
* remote. The tip is fetched into {@link PREVIEW_REF} — never into the
|
|
33
|
+
* tracking ref `run` merges from (`--refmap=` also stops git's
|
|
34
|
+
* opportunistic update of it) — and that ref is deleted again.
|
|
35
|
+
*/
|
|
36
|
+
export declare function incomingCommits(ctx: DeployContext, target: {
|
|
37
|
+
remote: string;
|
|
38
|
+
head: string;
|
|
39
|
+
}, skipFetch: boolean): Promise<Commits>;
|
package/dist/commits.js
ADDED
|
@@ -0,0 +1,188 @@
|
|
|
1
|
+
import { sanitize } from './events.js';
|
|
2
|
+
import { COMMITS_LIMIT } from './protocol.js';
|
|
3
|
+
/**
|
|
4
|
+
* The commits between two releases, for the plan, the history and a rollback
|
|
5
|
+
* (RFC 0008 §4.3). Read-only and best effort: every function here returns
|
|
6
|
+
* "unavailable" with a reason instead of throwing, so a git that fails, hangs
|
|
7
|
+
* or prints too much never stops a deploy, a plan or a status.
|
|
8
|
+
*
|
|
9
|
+
* The text of a commit is the author's: data, never instructions. It is
|
|
10
|
+
* sanitised (escapes, controls, bidi) and capped here, and only ever rendered
|
|
11
|
+
* as plain text. git's own messages are never passed on: they can carry a
|
|
12
|
+
* remote URL with credentials.
|
|
13
|
+
*/
|
|
14
|
+
const FULL_SHA = /^[0-9a-f]{40}$/;
|
|
15
|
+
/** `%aI`: strict ISO-8601 with an offset. */
|
|
16
|
+
const ISO_DATE = /^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:[+-]\d{2}:\d{2}|Z)$/;
|
|
17
|
+
const BIDI = /[--]/g;
|
|
18
|
+
export const MAX_SUBJECT = 200;
|
|
19
|
+
export const MAX_AUTHOR = 100;
|
|
20
|
+
/** Per git call: a list of 50 capped commits is far below this; a huge one is cut, never read. */
|
|
21
|
+
export const MAX_GIT_OUTPUT_BYTES = 256 * 1024;
|
|
22
|
+
export const GIT_TIMEOUT_MS = 5_000;
|
|
23
|
+
/** The plan's fetch reaches the network. */
|
|
24
|
+
export const FETCH_TIMEOUT_MS = 30_000;
|
|
25
|
+
/** Where `plan` fetches the branch: never the tracking ref `run` merges from. Deleted after use. */
|
|
26
|
+
export const PREVIEW_REF = 'refs/basalt-deploy/preview';
|
|
27
|
+
/** No pager, colour, signature check, notes, mailmap or replace refs: the same plain output on every server. */
|
|
28
|
+
const GIT_CONFIG = ['-c', 'core.pager=cat', '-c', 'color.ui=false', '-c', 'log.showSignature=false', '-c', 'i18n.logOutputEncoding=UTF-8'];
|
|
29
|
+
const GIT_ENV = { GIT_OPTIONAL_LOCKS: '0', GIT_NO_REPLACE_OBJECTS: '1', GIT_PAGER: 'cat', GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never', GIT_SSH_COMMAND: 'ssh -o BatchMode=yes' };
|
|
30
|
+
/** NUL between fields and (with `-z`) after each commit: no text of a commit can forge the framing. */
|
|
31
|
+
const FORMAT = '--format=%H%x00%P%x00%an%x00%aI%x00%s';
|
|
32
|
+
const LOG_FLAGS = ['--no-show-signature', '--no-notes', '--no-mailmap', '--no-decorate', '--no-color', '--topo-order', '-z', FORMAT];
|
|
33
|
+
async function git(ctx, args, timeoutMs = GIT_TIMEOUT_MS) {
|
|
34
|
+
let result;
|
|
35
|
+
try {
|
|
36
|
+
result = await ctx.host.exec('git', [...GIT_CONFIG, ...args], { cwd: ctx.dir, env: GIT_ENV, timeoutMs, maxOutputBytes: MAX_GIT_OUTPUT_BYTES });
|
|
37
|
+
}
|
|
38
|
+
catch {
|
|
39
|
+
return { ok: false, reason: 'git-failed' };
|
|
40
|
+
}
|
|
41
|
+
if (result.limit)
|
|
42
|
+
return { ok: false, reason: result.limit };
|
|
43
|
+
return { ok: true, stdout: result.stdout, code: result.code };
|
|
44
|
+
}
|
|
45
|
+
/** One line of the author's text: no escapes, controls, newlines or bidi overrides, at most `max` characters. */
|
|
46
|
+
export function cleanText(text, max) {
|
|
47
|
+
const plain = sanitize(text).replace(BIDI, '').trim();
|
|
48
|
+
const chars = [...plain];
|
|
49
|
+
return chars.length <= max ? plain : `${chars.slice(0, max - 1).join('')}…`;
|
|
50
|
+
}
|
|
51
|
+
/**
|
|
52
|
+
* `git log -z` with {@link FORMAT}: five fields per commit. A bad sha or a
|
|
53
|
+
* wrong field count is a parse that went wrong — the whole list is refused.
|
|
54
|
+
* A bad date is the author's to forge: only that date is dropped.
|
|
55
|
+
*/
|
|
56
|
+
export function parseLog(stdout) {
|
|
57
|
+
const fields = stdout.split('\u0000');
|
|
58
|
+
if (fields.at(-1) === '')
|
|
59
|
+
fields.pop();
|
|
60
|
+
if (fields.length % 5 !== 0)
|
|
61
|
+
return undefined;
|
|
62
|
+
const commits = [];
|
|
63
|
+
for (let i = 0; i < fields.length; i += 5) {
|
|
64
|
+
const [sha, parents, author, at, subject] = fields.slice(i, i + 5);
|
|
65
|
+
const parentList = parents === '' ? [] : parents.split(' ');
|
|
66
|
+
if (!FULL_SHA.test(sha) || !parentList.every((p) => FULL_SHA.test(p)))
|
|
67
|
+
return undefined;
|
|
68
|
+
commits.push({
|
|
69
|
+
sha,
|
|
70
|
+
subject: cleanText(subject, MAX_SUBJECT),
|
|
71
|
+
author: cleanText(author, MAX_AUTHOR),
|
|
72
|
+
...(ISO_DATE.test(at) ? { at } : {}),
|
|
73
|
+
...(parentList.length > 1 ? { merge: true } : {}),
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
return commits;
|
|
77
|
+
}
|
|
78
|
+
async function list(ctx, include, exclude) {
|
|
79
|
+
const out = await git(ctx, ['log', ...LOG_FLAGS, `--max-count=${COMMITS_LIMIT}`, '--end-of-options', include, `^${exclude}`, '--']);
|
|
80
|
+
if (!out.ok)
|
|
81
|
+
return out.reason;
|
|
82
|
+
if (out.code !== 0)
|
|
83
|
+
return 'git-failed';
|
|
84
|
+
return parseLog(out.stdout) ?? 'malformed';
|
|
85
|
+
}
|
|
86
|
+
/**
|
|
87
|
+
* What changes when the code goes from `from` to `to` (both full shas). The
|
|
88
|
+
* whole ancestry, never `--first-parent`: the commits a merge brings in go
|
|
89
|
+
* out too. Two lists, so a rewritten branch shows what it drops as well.
|
|
90
|
+
*/
|
|
91
|
+
export async function commitRange(ctx, from, to) {
|
|
92
|
+
const unavailable = (reason) => ({ ok: false, reason });
|
|
93
|
+
if (!FULL_SHA.test(from) || !FULL_SHA.test(to))
|
|
94
|
+
return unavailable('malformed');
|
|
95
|
+
if (from === to)
|
|
96
|
+
return { ok: true, range: { from, to, relation: 'same', mergeBase: from, added: [], addedTotal: 0, removed: [], removedTotal: 0, truncated: false } };
|
|
97
|
+
// Below a shallow boundary the merge base and the counts are silently wrong.
|
|
98
|
+
const shallow = await git(ctx, ['rev-parse', '--is-shallow-repository']);
|
|
99
|
+
if (!shallow.ok)
|
|
100
|
+
return unavailable(shallow.reason);
|
|
101
|
+
if (shallow.code !== 0)
|
|
102
|
+
return unavailable('git-failed');
|
|
103
|
+
if (shallow.stdout.trim() === 'true')
|
|
104
|
+
return unavailable('shallow');
|
|
105
|
+
for (const sha of [from, to]) {
|
|
106
|
+
const exists = await git(ctx, ['cat-file', '-e', `${sha}^{commit}`]);
|
|
107
|
+
if (!exists.ok)
|
|
108
|
+
return unavailable(exists.reason);
|
|
109
|
+
// A sha a force-push and a gc took away, or never fetched here.
|
|
110
|
+
if (exists.code !== 0)
|
|
111
|
+
return unavailable('missing-commit');
|
|
112
|
+
}
|
|
113
|
+
const base = await git(ctx, ['merge-base', from, to]);
|
|
114
|
+
if (!base.ok)
|
|
115
|
+
return unavailable(base.reason);
|
|
116
|
+
if (base.code === 1)
|
|
117
|
+
return unavailable('unrelated');
|
|
118
|
+
const mergeBase = base.stdout.trim();
|
|
119
|
+
if (base.code !== 0 || !FULL_SHA.test(mergeBase))
|
|
120
|
+
return unavailable('git-failed');
|
|
121
|
+
const counts = await git(ctx, ['rev-list', '--left-right', '--count', '--end-of-options', `${from}...${to}`, '--']);
|
|
122
|
+
if (!counts.ok)
|
|
123
|
+
return unavailable(counts.reason);
|
|
124
|
+
const match = /^(\d+)\s+(\d+)$/.exec(counts.stdout.trim());
|
|
125
|
+
if (counts.code !== 0 || !match)
|
|
126
|
+
return unavailable('git-failed');
|
|
127
|
+
const removedTotal = Number(match[1]);
|
|
128
|
+
const addedTotal = Number(match[2]);
|
|
129
|
+
const added = addedTotal > 0 ? await list(ctx, to, from) : [];
|
|
130
|
+
if (typeof added === 'string')
|
|
131
|
+
return unavailable(added);
|
|
132
|
+
const removed = removedTotal > 0 ? await list(ctx, from, to) : [];
|
|
133
|
+
if (typeof removed === 'string')
|
|
134
|
+
return unavailable(removed);
|
|
135
|
+
const relation = addedTotal > 0 && removedTotal > 0 ? 'diverged' : addedTotal > 0 ? 'ahead' : removedTotal > 0 ? 'behind' : 'same';
|
|
136
|
+
return {
|
|
137
|
+
ok: true,
|
|
138
|
+
range: { from, to, relation, mergeBase, added, addedTotal, removed, removedTotal, truncated: added.length < addedTotal || removed.length < removedTotal },
|
|
139
|
+
};
|
|
140
|
+
}
|
|
141
|
+
/** The subject of each commit, by sha, in one git call; undefined when git could not say. Missing commits are left out. */
|
|
142
|
+
export async function commitSubjects(ctx, shas) {
|
|
143
|
+
const wanted = [...new Set(shas.filter((sha) => FULL_SHA.test(sha)))];
|
|
144
|
+
if (wanted.length === 0)
|
|
145
|
+
return {};
|
|
146
|
+
const out = await git(ctx, ['log', '--no-walk=unsorted', '--ignore-missing', ...LOG_FLAGS, '--end-of-options', ...wanted, '--']);
|
|
147
|
+
if (!out.ok || out.code !== 0)
|
|
148
|
+
return undefined;
|
|
149
|
+
const commits = parseLog(out.stdout);
|
|
150
|
+
if (!commits)
|
|
151
|
+
return undefined;
|
|
152
|
+
return Object.fromEntries(commits.map((c) => [c.sha, c.subject]));
|
|
153
|
+
}
|
|
154
|
+
/** The full sha of `rev`, a commit in this checkout; undefined when it is not one. */
|
|
155
|
+
export async function resolveCommit(ctx, rev) {
|
|
156
|
+
const out = await git(ctx, ['rev-parse', '--verify', '--quiet', '--end-of-options', `${rev}^{commit}`]);
|
|
157
|
+
if (!out.ok || out.code !== 0)
|
|
158
|
+
return undefined;
|
|
159
|
+
const sha = out.stdout.trim();
|
|
160
|
+
return FULL_SHA.test(sha) ? sha : undefined;
|
|
161
|
+
}
|
|
162
|
+
/**
|
|
163
|
+
* What `run` would deploy, for `plan`: HEAD to the branch's tip on the
|
|
164
|
+
* remote. The tip is fetched into {@link PREVIEW_REF} — never into the
|
|
165
|
+
* tracking ref `run` merges from (`--refmap=` also stops git's
|
|
166
|
+
* opportunistic update of it) — and that ref is deleted again.
|
|
167
|
+
*/
|
|
168
|
+
export async function incomingCommits(ctx, target, skipFetch) {
|
|
169
|
+
if (skipFetch)
|
|
170
|
+
return { ok: false, reason: 'skipped' };
|
|
171
|
+
const head = await resolveCommit(ctx, 'HEAD');
|
|
172
|
+
if (!head)
|
|
173
|
+
return { ok: false, reason: 'git-failed' };
|
|
174
|
+
const fetched = await git(ctx, ['fetch', '--quiet', '--no-tags', '--no-recurse-submodules', '--refmap=', '--', target.remote, `+${target.head}:${PREVIEW_REF}`], FETCH_TIMEOUT_MS);
|
|
175
|
+
try {
|
|
176
|
+
if (!fetched.ok)
|
|
177
|
+
return { ok: false, reason: fetched.reason === 'timeout' ? 'timeout' : 'not-fetched' };
|
|
178
|
+
if (fetched.code !== 0)
|
|
179
|
+
return { ok: false, reason: 'not-fetched' };
|
|
180
|
+
const tip = await resolveCommit(ctx, PREVIEW_REF);
|
|
181
|
+
if (!tip)
|
|
182
|
+
return { ok: false, reason: 'not-fetched' };
|
|
183
|
+
return await commitRange(ctx, head, tip);
|
|
184
|
+
}
|
|
185
|
+
finally {
|
|
186
|
+
await git(ctx, ['update-ref', '-d', PREVIEW_REF]);
|
|
187
|
+
}
|
|
188
|
+
}
|
package/dist/config.d.ts
CHANGED
|
@@ -81,6 +81,13 @@ export interface DeployConfig<E extends object = EnvShape> {
|
|
|
81
81
|
audit?: {
|
|
82
82
|
syslog?: boolean;
|
|
83
83
|
};
|
|
84
|
+
/**
|
|
85
|
+
* What the app needs from the operating system, outside node_modules
|
|
86
|
+
* (RFC 0007 §12, system packages). Checked on every deploy (C12, before
|
|
87
|
+
* anything is built); installed by root — `bootstrap` and `install` — from
|
|
88
|
+
* the install plan, never by a deploy.
|
|
89
|
+
*/
|
|
90
|
+
system?: SystemConfig;
|
|
84
91
|
/** What `basalt-deploy bootstrap` sets up on a fresh server (RFC 0007 §7). */
|
|
85
92
|
bootstrap?: {
|
|
86
93
|
/** Swap created when RAM is under 6 GB and there is none; 0 = never. @default 4 */
|
|
@@ -89,6 +96,15 @@ export interface DeployConfig<E extends object = EnvShape> {
|
|
|
89
96
|
firewall?: boolean;
|
|
90
97
|
};
|
|
91
98
|
}
|
|
99
|
+
export interface SystemConfig {
|
|
100
|
+
/**
|
|
101
|
+
* Debian/Ubuntu apt package names the app runs (binaries it spawns, shared
|
|
102
|
+
* libraries it loads): `[a-z0-9][a-z0-9.+-]{1,62}`, each once — names only,
|
|
103
|
+
* no version, no release.
|
|
104
|
+
* @example ['tesseract-ocr', 'tesseract-ocr-por', 'poppler-utils', 'unzip']
|
|
105
|
+
*/
|
|
106
|
+
packages?: string[];
|
|
107
|
+
}
|
|
92
108
|
export interface VerifyConfig {
|
|
93
109
|
/**
|
|
94
110
|
* Per compose service, text that must not appear in its logs since the
|
package/dist/config.js
CHANGED
|
@@ -5,6 +5,7 @@
|
|
|
5
5
|
* its own module. A config can therefore be printed, diffed and validated
|
|
6
6
|
* without running anything.
|
|
7
7
|
*/
|
|
8
|
+
import { systemPackageProblems } from './system.js';
|
|
8
9
|
import { API_PREFIX, ASK_PATH, caddyExtraProblem, CERT_NAME, envLocationProblem, isConfigRoot, isWebRoot, vhostFileProblem } from './trust.js';
|
|
9
10
|
/** The entries of an env record, without the keys a mapped type left `undefined`. */
|
|
10
11
|
export function definedEntries(record) {
|
|
@@ -291,6 +292,9 @@ export function validateConfig(typed) {
|
|
|
291
292
|
if (problem)
|
|
292
293
|
problems.push(`env file ${problem}`);
|
|
293
294
|
}
|
|
295
|
+
// Root installs these from the plan: a name is never an option, never shell syntax.
|
|
296
|
+
if (config.system?.packages !== undefined)
|
|
297
|
+
problems.push(...systemPackageProblems(config.system.packages, 'system.packages'));
|
|
294
298
|
if (config.proxy?.kind === 'caddy' && config.tenants === 'subdomain' && !config.proxy.onDemandTls) {
|
|
295
299
|
problems.push(`tenants: 'subdomain' behind caddy() needs onDemandTls: { ask: '/…' } — a certificate per tenant host, issued only for hosts the app vouches for`);
|
|
296
300
|
}
|
package/dist/host.d.ts
CHANGED
|
@@ -198,11 +198,17 @@ export interface ExecOptions {
|
|
|
198
198
|
* here as decoded text, instead of going to the terminal (RFC 0008 §5.3).
|
|
199
199
|
*/
|
|
200
200
|
onOutput?: (text: string, stream: 'stdout' | 'stderr') => void;
|
|
201
|
+
/** Captured output only: the child is killed after this long (`limit: 'timeout'`). */
|
|
202
|
+
timeoutMs?: number;
|
|
203
|
+
/** Captured output only: the child is killed once stdout + stderr pass this many bytes (`limit: 'too-large'`). */
|
|
204
|
+
maxOutputBytes?: number;
|
|
201
205
|
}
|
|
202
206
|
export interface ExecResult {
|
|
203
207
|
code: number;
|
|
204
208
|
stdout: string;
|
|
205
209
|
stderr: string;
|
|
210
|
+
/** Set when `timeoutMs` or `maxOutputBytes` stopped the child: its output is partial. */
|
|
211
|
+
limit?: 'timeout' | 'too-large';
|
|
206
212
|
}
|
|
207
213
|
export interface TlsCertificate {
|
|
208
214
|
/** `subjectAltName` DNS names, lowercased (`*.example.com` included as written). */
|
package/dist/host.js
CHANGED
|
@@ -147,14 +147,42 @@ export function nodeHost(output = consoleOutput()) {
|
|
|
147
147
|
child.stderr?.on('data', (chunk) => sink(decoders.stderr.write(chunk), 'stderr'));
|
|
148
148
|
}
|
|
149
149
|
else {
|
|
150
|
-
|
|
151
|
-
|
|
150
|
+
const max = options.maxOutputBytes;
|
|
151
|
+
let bytes = 0;
|
|
152
|
+
const capture = (key) => (chunk) => {
|
|
153
|
+
if (limit)
|
|
154
|
+
return;
|
|
155
|
+
bytes += chunk.length;
|
|
156
|
+
if (max !== undefined && bytes > max) {
|
|
157
|
+
stop('too-large');
|
|
158
|
+
return;
|
|
159
|
+
}
|
|
160
|
+
const text = max === undefined ? chunk.toString() : decoders[key].write(chunk);
|
|
161
|
+
if (key === 'stdout')
|
|
162
|
+
stdout += text;
|
|
163
|
+
else
|
|
164
|
+
stderr += text;
|
|
165
|
+
};
|
|
166
|
+
child.stdout?.on('data', capture('stdout'));
|
|
167
|
+
child.stderr?.on('data', capture('stderr'));
|
|
152
168
|
}
|
|
169
|
+
let limit;
|
|
170
|
+
const stop = (why) => {
|
|
171
|
+
if (limit)
|
|
172
|
+
return;
|
|
173
|
+
limit = why;
|
|
174
|
+
child.kill('SIGKILL');
|
|
175
|
+
};
|
|
176
|
+
const timer = options.timeoutMs !== undefined && !sink && !options.stream && !options.interactive
|
|
177
|
+
? setTimeout(() => stop('timeout'), options.timeoutMs)
|
|
178
|
+
: undefined;
|
|
153
179
|
let finished = false;
|
|
154
180
|
const done = (code) => {
|
|
155
181
|
if (finished)
|
|
156
182
|
return;
|
|
157
183
|
finished = true;
|
|
184
|
+
if (timer)
|
|
185
|
+
clearTimeout(timer);
|
|
158
186
|
if (fd !== undefined)
|
|
159
187
|
closeSync(fd);
|
|
160
188
|
if (sink) {
|
|
@@ -164,7 +192,14 @@ export function nodeHost(output = consoleOutput()) {
|
|
|
164
192
|
sink(decoders.stdout.end(), 'stdout');
|
|
165
193
|
sink(decoders.stderr.end(), 'stderr');
|
|
166
194
|
}
|
|
167
|
-
|
|
195
|
+
if (!sink && options.maxOutputBytes !== undefined && !limit) {
|
|
196
|
+
stdout += decoders.stdout.end();
|
|
197
|
+
stderr += decoders.stderr.end();
|
|
198
|
+
}
|
|
199
|
+
if (limit)
|
|
200
|
+
resolve({ code: code === 0 ? 1 : code, stdout, stderr, limit });
|
|
201
|
+
else
|
|
202
|
+
resolve({ code, stdout, stderr });
|
|
168
203
|
};
|
|
169
204
|
child.on('error', (error) => { stderr += error.message; done(127); });
|
|
170
205
|
child.on('close', (code) => done(code ?? 1));
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export { defineDeploy, secret, ask, pm2, compose, apache, caddy, none, external, bucketName, dockerInfra, validateConfig, applyOverrides, parseOverrides, processName, DeployConfigError, SEAWEEDFS_IMAGE, type DeployConfig, type EnvShape, type EnvKey, type EnvValue, type EnvConfig, type DeriveContext, type SecretSpec, type Question, type InfraConfig, type DockerInfra, type DockerInfraOptions, type ExternalInfra, type ExternalPostgres, type AppRole, type Bucket, type VerifyConfig, type ComposeJob, type PostgresService, type RedisService, type SeaweedfsService, type ExternalS3, type S3Keys, type BuildConfig, type MigrateConfig, type BackupConfig, type RuntimeConfig, type Pm2Runtime, type ComposeRuntime, type ComposeImage, type HooksConfig, type ProxyConfig, type ApacheProxy, type CaddyProxy, type NoProxy, type HealthConfig, type ServerOverrides, } from './config.js';
|
|
1
|
+
export { defineDeploy, secret, ask, pm2, compose, apache, caddy, none, external, bucketName, dockerInfra, validateConfig, applyOverrides, parseOverrides, processName, DeployConfigError, SEAWEEDFS_IMAGE, type DeployConfig, type EnvShape, type EnvKey, type EnvValue, type EnvConfig, type DeriveContext, type SecretSpec, type Question, type InfraConfig, type DockerInfra, type DockerInfraOptions, type ExternalInfra, type ExternalPostgres, type AppRole, type Bucket, type SystemConfig, type VerifyConfig, type ComposeJob, type PostgresService, type RedisService, type SeaweedfsService, type ExternalS3, type S3Keys, type BuildConfig, type MigrateConfig, type BackupConfig, type RuntimeConfig, type Pm2Runtime, type ComposeRuntime, type ComposeImage, type HooksConfig, type ProxyConfig, type ApacheProxy, type CaddyProxy, type NoProxy, type HealthConfig, type ServerOverrides, } from './config.js';
|
|
2
2
|
export { main, loadConfig, createContext, processIO, USAGE, type CliIO } from './cli.js';
|
|
3
3
|
export { nodeHost, consoleOutput, type Host, type ExecOptions, type ExecResult, type FileStat, type Output, type TlsCertificate, type PromptMeta, type LogHandle, type FileRange } from './host.js';
|
|
4
4
|
export { DeployAbortedError, DeployError, INSTALL_COMMAND, RUN_COMMAND, rootInstallCommand, type DeployContext, type Finding } from './context.js';
|
package/dist/install-plan.js
CHANGED
|
@@ -7,6 +7,7 @@ import { envValues } from './dotenv.js';
|
|
|
7
7
|
import { envFile, envMirrors, readEnv } from './env-step.js';
|
|
8
8
|
import { acquireLock } from './lock.js';
|
|
9
9
|
import { covers } from './checks.js';
|
|
10
|
+
import { aptInstall, fixCommand, packageStatus, systemPackageProblems } from './system.js';
|
|
10
11
|
import { API_PREFIX, ASK_PATH, assertRootOwnedDir, caddyExtraProblem, CERT_NAME, CHECKOUT_PATH, envLocationProblem, isConfigRoot, isWebRoot, untrustedAncestor, USER_NAME, vhostFileProblem } from './trust.js';
|
|
11
12
|
/**
|
|
12
13
|
* `install` in two halves (RFC 0006 §11.4), so that root never runs code the
|
|
@@ -46,6 +47,8 @@ export async function buildInstallPlan(ctx, tool) {
|
|
|
46
47
|
envFiles: [envFile(ctx), ...envMirrors(ctx)].filter((f) => !f.startsWith(`${ctx.dir}/`)),
|
|
47
48
|
docker: config.infra?.kind === 'docker' || config.runtime.kind === 'compose',
|
|
48
49
|
...(config.bootstrap ? { bootstrap: { ...config.bootstrap } } : {}),
|
|
50
|
+
// Names only: root installs them from this list, validated again, never from the config.
|
|
51
|
+
...(config.system?.packages?.length ? { system: { packages: [...config.system.packages] } } : {}),
|
|
49
52
|
tool,
|
|
50
53
|
};
|
|
51
54
|
// Root will run exactly these checks: refuse now, where the fix is.
|
|
@@ -89,7 +92,7 @@ export function parseInstallPlan(text, source) {
|
|
|
89
92
|
if (!keys.includes(key))
|
|
90
93
|
problems.push(`${where}: unknown key "${key}"`);
|
|
91
94
|
};
|
|
92
|
-
known(plan, ['kind', 'version', 'app', 'domain', 'tenants', 'dir', 'port', 'proxy', 'envFiles', 'docker', 'bootstrap', 'tool'], 'plan');
|
|
95
|
+
known(plan, ['kind', 'version', 'app', 'domain', 'tenants', 'dir', 'port', 'proxy', 'envFiles', 'docker', 'bootstrap', 'system', 'tool'], 'plan');
|
|
93
96
|
if (plan['kind'] !== PLAN_KIND || plan['version'] !== 1)
|
|
94
97
|
problems.push(`not a version-1 ${PLAN_KIND}`);
|
|
95
98
|
const app = typeof plan['app'] === 'string' && APP_NAME.test(plan['app']) ? plan['app'] : undefined;
|
|
@@ -133,6 +136,16 @@ export function parseInstallPlan(text, source) {
|
|
|
133
136
|
problems.push('bootstrap.firewall must be true or false');
|
|
134
137
|
}
|
|
135
138
|
}
|
|
139
|
+
const system = plan['system'];
|
|
140
|
+
if (system !== undefined) {
|
|
141
|
+
if (typeof system !== 'object' || system === null || Array.isArray(system))
|
|
142
|
+
problems.push('system must be an object');
|
|
143
|
+
else {
|
|
144
|
+
known(system, ['packages'], 'system');
|
|
145
|
+
// What root hands to apt-get as arguments: names only, never an option.
|
|
146
|
+
problems.push(...systemPackageProblems(system['packages'], 'system.packages'));
|
|
147
|
+
}
|
|
148
|
+
}
|
|
136
149
|
const proxy = (typeof plan['proxy'] === 'object' && plan['proxy'] !== null ? plan['proxy'] : {});
|
|
137
150
|
const kind = proxy['kind'];
|
|
138
151
|
if (kind === 'none')
|
|
@@ -263,6 +276,7 @@ export async function install(host, plan, user, options = {}) {
|
|
|
263
276
|
}
|
|
264
277
|
const ctx = contextOf(host, plan, stateDir);
|
|
265
278
|
summary(host, plan, user, stateDir, ctx);
|
|
279
|
+
await systemPackages(host, plan.system?.packages ?? []);
|
|
266
280
|
await envOwnership(host, plan, owner);
|
|
267
281
|
if (plan.proxy.kind === 'apache' && plan.proxy.managed) {
|
|
268
282
|
const root = plan.proxy.root ?? '/etc/apache2';
|
|
@@ -315,7 +329,39 @@ function summary(host, plan, user, stateDir, ctx) {
|
|
|
315
329
|
? `Caddy ${caddyPaths(ctx).site} for ${names} → 127.0.0.1:${plan.port}, ${join(plan.dir, plan.proxy.webRoot)} served`
|
|
316
330
|
: 'no proxy site';
|
|
317
331
|
host.out.info(`install for "${plan.app}" (plan by @basaltkit/deploy ${plan.tool}), for ${user}, checkout ${plan.dir}:`);
|
|
318
|
-
host.out.info(` state ${stateDir} · ${site}${plan.envFiles.length ? ` · env ${plan.envFiles.join(', ')}` : ''}`);
|
|
332
|
+
host.out.info(` state ${stateDir} · ${site}${plan.envFiles.length ? ` · env ${plan.envFiles.join(', ')}` : ''}${plan.system?.packages.length ? ` · system packages ${plan.system.packages.join(', ')}` : ''}`);
|
|
333
|
+
}
|
|
334
|
+
/**
|
|
335
|
+
* `system.packages`: the missing ones, installed with apt — names the plan
|
|
336
|
+
* carries (validated: never an option), as argv, from this server's own apt
|
|
337
|
+
* sources. The app user chose them, and a package's install scripts run as
|
|
338
|
+
* root: the list is shown and needs a "yes", as Caddy `extra` does. Already
|
|
339
|
+
* installed, nothing is asked. Not Debian/Ubuntu: said, and left to the
|
|
340
|
+
* administrator.
|
|
341
|
+
*/
|
|
342
|
+
async function systemPackages(host, packages) {
|
|
343
|
+
if (packages.length === 0)
|
|
344
|
+
return;
|
|
345
|
+
host.out.step('system packages');
|
|
346
|
+
const { missing, unverified } = await packageStatus(host, packages, '/');
|
|
347
|
+
if (unverified) {
|
|
348
|
+
host.out.warn(`no dpkg-query here (not Debian/Ubuntu): ${packages.join(', ')} not checked nor installed — install them by hand`);
|
|
349
|
+
return;
|
|
350
|
+
}
|
|
351
|
+
if (missing.length === 0) {
|
|
352
|
+
host.out.ok(`${packages.join(', ')} installed`);
|
|
353
|
+
return;
|
|
354
|
+
}
|
|
355
|
+
host.out.info(`not installed: ${missing.join(', ')} — apt-get install, as root, from this server's apt sources`);
|
|
356
|
+
if (!(await host.confirm(`Install ${missing.join(', ')} as root?`)))
|
|
357
|
+
throw new DeployError(`system packages not confirmed — nothing installed (a terminal must answer; or, by hand: ${fixCommand(missing)})`);
|
|
358
|
+
for (const command of aptInstall(missing)) {
|
|
359
|
+
host.out.info(` + ${command.join(' ')}`);
|
|
360
|
+
const result = await host.exec(command[0], command.slice(1), { cwd: '/', stream: true });
|
|
361
|
+
if (result.code !== 0)
|
|
362
|
+
throw new DeployError(`system packages: \`${command.join(' ')}\` failed (exit ${result.code})`);
|
|
363
|
+
}
|
|
364
|
+
host.out.ok(`${missing.join(', ')} installed`);
|
|
319
365
|
}
|
|
320
366
|
/** The host names a proxy config file serves: Apache ServerName/ServerAlias, Caddy site addresses. */
|
|
321
367
|
export function servedNames(text, kind) {
|
package/dist/pipeline.d.ts
CHANGED
|
@@ -1,4 +1,6 @@
|
|
|
1
1
|
import { type DeployContext, type Finding } from './context.js';
|
|
2
|
+
import type { Commits } from './protocol.js';
|
|
3
|
+
import { type PackageStatus } from './system.js';
|
|
2
4
|
/**
|
|
3
5
|
* The pipeline (RFC 0006 §4): preflight → fetch → env → infra → build →
|
|
4
6
|
* validate → backup → migrate → release → proxy → health → record.
|
|
@@ -65,6 +67,8 @@ export interface Preflight {
|
|
|
65
67
|
findings: Finding[];
|
|
66
68
|
port: number;
|
|
67
69
|
values: Map<string, string>;
|
|
70
|
+
/** `system.packages` as this server has them; undefined when none are declared. */
|
|
71
|
+
system?: PackageStatus;
|
|
68
72
|
}
|
|
69
73
|
export declare function preflight(ctx: DeployContext, options?: RunOptions): Promise<Preflight>;
|
|
70
74
|
/** `prisma migrate deploy` runs when asked to, or — unsaid — when the app generates a Prisma client. */
|
|
@@ -88,9 +92,24 @@ export declare function backupDecision(config: DeployContext['config'], values:
|
|
|
88
92
|
why: string;
|
|
89
93
|
};
|
|
90
94
|
export declare function plan(ctx: DeployContext, options?: RunOptions): Promise<number>;
|
|
95
|
+
/** One line for the terminal; the list itself is in the result (--json). */
|
|
96
|
+
export declare function describeCommits(commits: Commits): string;
|
|
91
97
|
/** `basalt-deploy env` — the .env and the infra only (first setup, before `install`). */
|
|
92
98
|
export declare function envCommand(ctx: DeployContext, options?: RunOptions): Promise<number>;
|
|
93
99
|
export declare function run(ctx: DeployContext, options?: RunOptions): Promise<number>;
|
|
94
100
|
/** `basalt-deploy rollback [--to=<sha>]` — code only; the database stays as it is. */
|
|
95
101
|
export declare function rollback(ctx: DeployContext, to?: string, options?: RunOptions): Promise<number>;
|
|
96
102
|
export declare function status(ctx: DeployContext): Promise<number>;
|
|
103
|
+
/**
|
|
104
|
+
* `basalt-deploy commits --from=<sha> --to=<sha>` — what changed between two
|
|
105
|
+
* commits; `commits --rollback [--to=<sha>]` — what `rollback` would take
|
|
106
|
+
* out of production, to the commit it would choose. Read-only: no lock, no
|
|
107
|
+
* fetch. A list it cannot get is an answer (`unavailable`), not a failure.
|
|
108
|
+
*/
|
|
109
|
+
export declare function commitsCommand(ctx: DeployContext, request: {
|
|
110
|
+
from: string;
|
|
111
|
+
to: string;
|
|
112
|
+
} | {
|
|
113
|
+
rollback: true;
|
|
114
|
+
to?: string;
|
|
115
|
+
}): Promise<number>;
|
package/dist/pipeline.js
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { tmpdir } from 'node:os';
|
|
1
2
|
import { apachePreflight } from './apache.js';
|
|
2
3
|
import { caddyPreflight } from './caddy.js';
|
|
3
4
|
import { backupDatabase, backupDir, backupPlaceFindings, restoreCommand } from './backup.js';
|
|
@@ -11,11 +12,13 @@ import { envValues } from './dotenv.js';
|
|
|
11
12
|
import { applyInfra, describeInfra, dockerPostgres, maintainServices, planInfra } from './infra.js';
|
|
12
13
|
import { appRoleOf, describeServices, dumpContainer, dumpUrlKey, externalOf, externalPostgres, grantTenantSchemas } from './services.js';
|
|
13
14
|
import { pm2List, pm2Preflight, pm2Release, resolvePort } from './pm2.js';
|
|
14
|
-
import { clearHold,
|
|
15
|
+
import { clearHold, migrationNames, readHold, readReleases, recordRelease, rollbackTarget, writeHold } from './state.js';
|
|
16
|
+
import { commitRange, commitSubjects, incomingCommits, resolveCommit } from './commits.js';
|
|
15
17
|
import { acquireLock, describeHolder, readLock } from './lock.js';
|
|
16
18
|
import { auditOf } from './audit.js';
|
|
17
19
|
import { questionDescriptors } from './env-step.js';
|
|
18
20
|
import { activeRun, lastRun } from './runs.js';
|
|
21
|
+
import { describeSystem, packageStatus, systemFindings } from './system.js';
|
|
19
22
|
export const SKIPPABLE = ['fetch', 'backup', 'tls'];
|
|
20
23
|
/** run, env and rollback are the app user's (RFC 0006 §11.4): never root unless asked. */
|
|
21
24
|
export function refuseRoot(host, command, allowRoot = false) {
|
|
@@ -166,6 +169,9 @@ export async function preflight(ctx, options = {}) {
|
|
|
166
169
|
const port = await resolvePort(ctx, values);
|
|
167
170
|
findings.push(...await toolingFindings(ctx));
|
|
168
171
|
findings.push(...await lockfileFindings(ctx));
|
|
172
|
+
const system = await systemStatus(ctx);
|
|
173
|
+
if (system)
|
|
174
|
+
findings.push(...systemFindings(ctx.config.system?.packages ?? [], system));
|
|
169
175
|
const head = (await ctx.host.exec('git', ['rev-parse', 'HEAD'], { cwd: ctx.dir })).stdout.trim();
|
|
170
176
|
findings.push(...await runtimePreflight(ctx, port, head));
|
|
171
177
|
findings.push(...await mirrorFindings(ctx));
|
|
@@ -176,7 +182,18 @@ export async function preflight(ctx, options = {}) {
|
|
|
176
182
|
if (!options.skip?.includes('tls'))
|
|
177
183
|
findings.push(...await tlsFindings(ctx));
|
|
178
184
|
findings.push(...await backupFindings(ctx, values, options));
|
|
179
|
-
return { findings, port, values };
|
|
185
|
+
return { findings, port, values, ...(system ? { system } : {}) };
|
|
186
|
+
}
|
|
187
|
+
/**
|
|
188
|
+
* C12's probe, as the app user: read-only, outside the checkout. Installing
|
|
189
|
+
* needs root, so a deploy never does — it stops before the build and prints
|
|
190
|
+
* the command an administrator runs.
|
|
191
|
+
*/
|
|
192
|
+
async function systemStatus(ctx) {
|
|
193
|
+
const packages = ctx.config.system?.packages ?? [];
|
|
194
|
+
if (packages.length === 0)
|
|
195
|
+
return undefined;
|
|
196
|
+
return packageStatus(ctx.host, packages, tmpdir());
|
|
180
197
|
}
|
|
181
198
|
/** The dump's container running — found now, not after the build, minutes later. */
|
|
182
199
|
async function backupFindings(ctx, values, options) {
|
|
@@ -518,6 +535,8 @@ export async function plan(ctx, options = {}) {
|
|
|
518
535
|
const { host, config, pm } = ctx;
|
|
519
536
|
const blocking = errors([...checked.findings, ...infra.findings]).length > 0;
|
|
520
537
|
const lines = await stepped(ctx, 'plan', async () => planLines(ctx, options, checked, env, infra), 'plan — nothing below has run');
|
|
538
|
+
const commits = await planCommits(ctx, options);
|
|
539
|
+
host.out.info(describeCommits(commits));
|
|
521
540
|
host.out.result?.('plan', {
|
|
522
541
|
findings: [...checked.findings, ...infra.findings],
|
|
523
542
|
lines: lines.map((line) => {
|
|
@@ -527,15 +546,38 @@ export async function plan(ctx, options = {}) {
|
|
|
527
546
|
// What env/run would ask now — the deploy's own environment answers first, as it does there.
|
|
528
547
|
questions: questionDescriptors(config, env.questions.filter((key) => host.env[key] === undefined)),
|
|
529
548
|
blocking,
|
|
549
|
+
commits,
|
|
530
550
|
});
|
|
531
551
|
return blocking ? 1 : 0;
|
|
532
552
|
}
|
|
553
|
+
/** What a run would deploy, marked when a rollback held that commit. Never a finding: a list it cannot get stops nothing. */
|
|
554
|
+
async function planCommits(ctx, options) {
|
|
555
|
+
const commits = await incomingCommits(ctx, gitTarget(ctx), options.skip?.includes('fetch') ?? false);
|
|
556
|
+
if (!commits.ok)
|
|
557
|
+
return commits;
|
|
558
|
+
const hold = await readHold(ctx);
|
|
559
|
+
return hold?.sha === commits.range.to && commits.range.relation !== 'same' ? { ok: true, range: { ...commits.range, held: true } } : commits;
|
|
560
|
+
}
|
|
561
|
+
/** One line for the terminal; the list itself is in the result (--json). */
|
|
562
|
+
export function describeCommits(commits) {
|
|
563
|
+
if (!commits.ok)
|
|
564
|
+
return `commits: the list is unavailable (${commits.reason})`;
|
|
565
|
+
const { range } = commits;
|
|
566
|
+
const span = `${range.from.slice(0, 7)} → ${range.to.slice(0, 7)}`;
|
|
567
|
+
switch (range.relation) {
|
|
568
|
+
case 'same': return `commits: nothing new (${range.to.slice(0, 7)})`;
|
|
569
|
+
case 'ahead': return `commits: ${range.addedTotal} to go out (${span})${range.held ? ' — held by a rollback' : ''}`;
|
|
570
|
+
case 'behind': return `commits: ${range.removedTotal} would leave (${span})`;
|
|
571
|
+
case 'diverged': return `commits: the branch was rewritten — ${range.addedTotal} new, ${range.removedTotal} only here (${span}); run refuses it (--ff-only)`;
|
|
572
|
+
}
|
|
573
|
+
}
|
|
533
574
|
/** What `plan` prints, one line per thing a run would do. */
|
|
534
575
|
function planLines(ctx, options, checked, env, infra) {
|
|
535
576
|
const { host, config, pm } = ctx;
|
|
536
577
|
const lines = [
|
|
537
578
|
options.skip?.includes('fetch') ? 'fetch: skipped' : ((t) => `fetch: git ${fetchArgs(t).filter((a) => a !== '--quiet').join(' ')} && git merge --ff-only ${t.tracking}`)(gitTarget(ctx)),
|
|
538
579
|
...describeEnv(env).map((l) => `env: ${l}`),
|
|
580
|
+
...describeSystem(config.system?.packages ?? [], checked.system).map((l) => `system: ${l}`),
|
|
539
581
|
...describeInfra(infra).map((l) => `infra: ${l}`),
|
|
540
582
|
...describeServices(config).map((l) => `infra: ${l}`),
|
|
541
583
|
`build: ${pm} install (frozen), ${(config.build?.prisma ?? []).map((c) => `prisma generate --config ${c}`).join(', ') || 'no prisma'}${config.build?.script ? `, ${pm} run ${config.build.script}` : ''}${config.build?.web ? `, ${config.build.web} build` : ''}${isCompose(ctx) ? `, docker build ${composeOf(ctx).images.map((i) => i.tag).join(', ')} (skipped when the commit's tag exists)` : ''}`,
|
|
@@ -810,7 +852,7 @@ async function rollbackLocked(ctx, to, options) {
|
|
|
810
852
|
}
|
|
811
853
|
// The last healthy release before this one; on the first recorded deploy,
|
|
812
854
|
// the commit it was deployed over.
|
|
813
|
-
const target =
|
|
855
|
+
const target = rollbackTarget(releases, current, wanted);
|
|
814
856
|
if (!target || target === current)
|
|
815
857
|
throw new DeployError('no earlier release to go back to; pass --to=<sha>');
|
|
816
858
|
const document = await readEnv(ctx);
|
|
@@ -888,7 +930,49 @@ export async function status(ctx) {
|
|
|
888
930
|
hold: hold ?? null,
|
|
889
931
|
releases,
|
|
890
932
|
process: running,
|
|
933
|
+
...await subjectsOf(ctx, releases),
|
|
891
934
|
});
|
|
892
935
|
}
|
|
893
936
|
return 0;
|
|
894
937
|
}
|
|
938
|
+
async function subjectsOf(ctx, releases) {
|
|
939
|
+
const subjects = await commitSubjects(ctx, releases.map((r) => r.sha));
|
|
940
|
+
return subjects ? { subjects } : {};
|
|
941
|
+
}
|
|
942
|
+
/**
|
|
943
|
+
* `basalt-deploy commits --from=<sha> --to=<sha>` — what changed between two
|
|
944
|
+
* commits; `commits --rollback [--to=<sha>]` — what `rollback` would take
|
|
945
|
+
* out of production, to the commit it would choose. Read-only: no lock, no
|
|
946
|
+
* fetch. A list it cannot get is an answer (`unavailable`), not a failure.
|
|
947
|
+
*/
|
|
948
|
+
export async function commitsCommand(ctx, request) {
|
|
949
|
+
const { host } = ctx;
|
|
950
|
+
let result;
|
|
951
|
+
if ('rollback' in request) {
|
|
952
|
+
const current = await resolveCommit(ctx, 'HEAD');
|
|
953
|
+
const wanted = request.to === undefined ? undefined : await resolveCommit(ctx, request.to);
|
|
954
|
+
const target = current && (request.to === undefined || wanted) ? rollbackTarget(await readReleases(ctx), current, wanted) : undefined;
|
|
955
|
+
result = {
|
|
956
|
+
purpose: 'rollback',
|
|
957
|
+
...(current ? { from: current } : {}),
|
|
958
|
+
...(target ? { to: target } : {}),
|
|
959
|
+
commits: !current ? { ok: false, reason: 'git-failed' }
|
|
960
|
+
: request.to !== undefined && !wanted ? { ok: false, reason: 'missing-commit' }
|
|
961
|
+
: !target || target === current ? { ok: false, reason: 'no-previous' }
|
|
962
|
+
: await commitRange(ctx, current, target),
|
|
963
|
+
};
|
|
964
|
+
}
|
|
965
|
+
else {
|
|
966
|
+
const [from, to] = [await resolveCommit(ctx, request.from), await resolveCommit(ctx, request.to)];
|
|
967
|
+
result = { purpose: 'range', ...(from ? { from } : {}), ...(to ? { to } : {}), commits: from && to ? await commitRange(ctx, from, to) : { ok: false, reason: 'missing-commit' } };
|
|
968
|
+
}
|
|
969
|
+
host.out.info(describeCommits(result.commits));
|
|
970
|
+
if (result.commits.ok) {
|
|
971
|
+
for (const [label, list] of [['+', result.commits.range.added], ['-', result.commits.range.removed]]) {
|
|
972
|
+
for (const c of list)
|
|
973
|
+
host.out.info(`${label} ${c.sha.slice(0, 7)} ${c.subject} (${c.author}${c.at ? `, ${c.at}` : ''})${c.merge ? ' [merge]' : ''}`);
|
|
974
|
+
}
|
|
975
|
+
}
|
|
976
|
+
host.out.result?.('commits', result);
|
|
977
|
+
return 0;
|
|
978
|
+
}
|
package/dist/protocol.d.ts
CHANGED
|
@@ -8,7 +8,7 @@
|
|
|
8
8
|
* imports it as `@basaltkit/deploy/protocol` without loading the CLI.
|
|
9
9
|
*/
|
|
10
10
|
export interface Finding {
|
|
11
|
-
/** The RFC 0006 §5 check id (`C1`…`
|
|
11
|
+
/** The RFC 0006 §5 check id (`C1`…`C12`) or a step name. */
|
|
12
12
|
id: string;
|
|
13
13
|
level: 'error' | 'warning';
|
|
14
14
|
message: string;
|
|
@@ -61,6 +61,56 @@ export interface Hold {
|
|
|
61
61
|
actor: string;
|
|
62
62
|
note: string;
|
|
63
63
|
}
|
|
64
|
+
/** The most commits a list carries; the totals say how many there were. */
|
|
65
|
+
export declare const COMMITS_LIMIT = 50;
|
|
66
|
+
/**
|
|
67
|
+
* One commit, as the server read it from git. Every string is the author's
|
|
68
|
+
* text: data, never instructions — sanitised and capped by the deploy, and
|
|
69
|
+
* rendered as plain text.
|
|
70
|
+
*/
|
|
71
|
+
export interface CommitInfo {
|
|
72
|
+
sha: string;
|
|
73
|
+
subject: string;
|
|
74
|
+
author: string;
|
|
75
|
+
/** ISO-8601, as the author's commit states it (absent when it does not parse). */
|
|
76
|
+
at?: string;
|
|
77
|
+
/** A merge commit (more than one parent). */
|
|
78
|
+
merge?: true;
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* `same`: nothing changes. `ahead`: `to` only adds commits (a fast-forward).
|
|
82
|
+
* `behind`: `to` only removes commits (a rollback). `diverged`: both — the
|
|
83
|
+
* branch was rewritten (`run` refuses it: its merge is `--ff-only`).
|
|
84
|
+
*/
|
|
85
|
+
export type CommitRelation = 'same' | 'ahead' | 'behind' | 'diverged';
|
|
86
|
+
/** What changes when the code goes from `from` to `to`. */
|
|
87
|
+
export interface CommitRange {
|
|
88
|
+
from: string;
|
|
89
|
+
to: string;
|
|
90
|
+
relation: CommitRelation;
|
|
91
|
+
mergeBase?: string;
|
|
92
|
+
/** In `to`, not in `from` (`git log to ^from`): what goes out. Newest first, at most {@link COMMITS_LIMIT}. */
|
|
93
|
+
added: CommitInfo[];
|
|
94
|
+
addedTotal: number;
|
|
95
|
+
/** In `from`, not in `to`: what leaves. Newest first, at most {@link COMMITS_LIMIT}. */
|
|
96
|
+
removed: CommitInfo[];
|
|
97
|
+
removedTotal: number;
|
|
98
|
+
/** A list holds fewer commits than its total. */
|
|
99
|
+
truncated: boolean;
|
|
100
|
+
/** Plan only: `to` is the commit a rollback held — `run` refuses it without `--unhold`. */
|
|
101
|
+
held?: true;
|
|
102
|
+
}
|
|
103
|
+
/** Why there is no list. Never git's own message: it can carry a URL with credentials. */
|
|
104
|
+
export declare const COMMITS_UNAVAILABLE: readonly ['skipped', 'not-fetched', 'no-previous', 'missing-commit', 'shallow', 'unrelated', 'timeout', 'too-large', 'malformed', 'git-failed'];
|
|
105
|
+
export type CommitsUnavailable = typeof COMMITS_UNAVAILABLE[number];
|
|
106
|
+
/** A list of commits, or why there is none: getting it never stops a command. */
|
|
107
|
+
export type Commits = {
|
|
108
|
+
ok: true;
|
|
109
|
+
range: CommitRange;
|
|
110
|
+
} | {
|
|
111
|
+
ok: false;
|
|
112
|
+
reason: CommitsUnavailable;
|
|
113
|
+
};
|
|
64
114
|
export type PlanProxy = {
|
|
65
115
|
kind: 'none';
|
|
66
116
|
} | {
|
|
@@ -103,6 +153,10 @@ export interface InstallPlan {
|
|
|
103
153
|
swapGb?: number;
|
|
104
154
|
firewall?: boolean;
|
|
105
155
|
};
|
|
156
|
+
/** `system.packages`: apt package names root installs when missing (bootstrap, install). */
|
|
157
|
+
system?: {
|
|
158
|
+
packages: string[];
|
|
159
|
+
};
|
|
106
160
|
/** The @basaltkit/deploy version that wrote the plan (informational). */
|
|
107
161
|
tool: string;
|
|
108
162
|
}
|
|
@@ -212,6 +266,8 @@ export interface StatusResult {
|
|
|
212
266
|
hold: Hold | null;
|
|
213
267
|
/** The last 10, newest first. */
|
|
214
268
|
releases: Release[];
|
|
269
|
+
/** The subject of each release's commit, by sha (`--json` only; absent when git could not say). */
|
|
270
|
+
subjects?: Record<string, string>;
|
|
215
271
|
process: {
|
|
216
272
|
kind: 'pm2';
|
|
217
273
|
name: string;
|
|
@@ -241,6 +297,16 @@ export interface PlanResult {
|
|
|
241
297
|
questions: PromptDescriptor[];
|
|
242
298
|
/** `plan` exits 1. */
|
|
243
299
|
blocking: boolean;
|
|
300
|
+
/** What a run would deploy: from the checkout's HEAD to the branch's tip on the remote. */
|
|
301
|
+
commits?: Commits;
|
|
302
|
+
}
|
|
303
|
+
/** `commits`: the commits between two releases, or what a rollback would take out of production. */
|
|
304
|
+
export interface CommitsResult {
|
|
305
|
+
/** `range`: `--from`/`--to`. `rollback`: from HEAD to the commit `rollback` would go back to. */
|
|
306
|
+
purpose: 'range' | 'rollback';
|
|
307
|
+
from?: string;
|
|
308
|
+
to?: string;
|
|
309
|
+
commits: Commits;
|
|
244
310
|
}
|
|
245
311
|
export interface RunResult {
|
|
246
312
|
sha: string;
|
|
@@ -293,6 +359,7 @@ export interface ResultPayloads {
|
|
|
293
359
|
env: EnvResult;
|
|
294
360
|
cancel: CancelResult;
|
|
295
361
|
'install-plan': InstallPlanResult;
|
|
362
|
+
commits: CommitsResult;
|
|
296
363
|
}
|
|
297
364
|
export type ResultCommand = keyof ResultPayloads;
|
|
298
365
|
export type ResultEvent = Envelope & {
|
package/dist/protocol.js
CHANGED
|
@@ -7,6 +7,13 @@
|
|
|
7
7
|
* import that runs code. A program that drives the CLI (the phase-2 local UI)
|
|
8
8
|
* imports it as `@basaltkit/deploy/protocol` without loading the CLI.
|
|
9
9
|
*/
|
|
10
|
+
/** The most commits a list carries; the totals say how many there were. */
|
|
11
|
+
export const COMMITS_LIMIT = 50;
|
|
12
|
+
/** Why there is no list. Never git's own message: it can carry a URL with credentials. */
|
|
13
|
+
export const COMMITS_UNAVAILABLE = [
|
|
14
|
+
'skipped', 'not-fetched', 'no-previous', 'missing-commit', 'shallow', 'unrelated',
|
|
15
|
+
'timeout', 'too-large', 'malformed', 'git-failed',
|
|
16
|
+
];
|
|
10
17
|
/** The protocol version: `--json` and `--json=1`. */
|
|
11
18
|
export const PROTOCOL_VERSION = 1;
|
|
12
19
|
/** The steps a command reports, a closed set (`step-start`/`step-end`). */
|
package/dist/state.d.ts
CHANGED
|
@@ -24,6 +24,12 @@ export declare function lastGood(releases: Release[], except: string): Release |
|
|
|
24
24
|
* unhealthy. `undefined` when there is none: the caller asks for `--to`.
|
|
25
25
|
*/
|
|
26
26
|
export declare function deployedOver(releases: Release[], current: string): string | undefined;
|
|
27
|
+
/**
|
|
28
|
+
* The commit `rollback` goes back to: the one asked for, else the last
|
|
29
|
+
* healthy release before `current`, else the commit `current` was deployed
|
|
30
|
+
* over. What `rollback` does and what `commits --rollback` previews.
|
|
31
|
+
*/
|
|
32
|
+
export declare function rollbackTarget(releases: Release[], current: string, wanted?: string): string | undefined;
|
|
27
33
|
export declare const holdFile: (ctx: DeployContext) => string;
|
|
28
34
|
/** The hold — from `<stateDir>/hold.json`, else (after `install`) the checkout's `.basalt/hold.json`, like the release history. */
|
|
29
35
|
export declare function readHold(ctx: DeployContext): Promise<Hold | undefined>;
|
package/dist/state.js
CHANGED
|
@@ -61,6 +61,14 @@ export function deployedOver(releases, current) {
|
|
|
61
61
|
return undefined;
|
|
62
62
|
return target;
|
|
63
63
|
}
|
|
64
|
+
/**
|
|
65
|
+
* The commit `rollback` goes back to: the one asked for, else the last
|
|
66
|
+
* healthy release before `current`, else the commit `current` was deployed
|
|
67
|
+
* over. What `rollback` does and what `commits --rollback` previews.
|
|
68
|
+
*/
|
|
69
|
+
export function rollbackTarget(releases, current, wanted) {
|
|
70
|
+
return wanted ?? lastGood(releases, current)?.sha ?? deployedOver(releases, current);
|
|
71
|
+
}
|
|
64
72
|
export const holdFile = (ctx) => join(ctx.stateDir, 'hold.json');
|
|
65
73
|
/** Where the hold was kept before `install` moved the state out of the checkout. */
|
|
66
74
|
const legacyHold = (ctx) => join(ctx.dir, '.basalt', 'hold.json');
|
package/dist/system.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import type { Finding } from './context.js';
|
|
2
|
+
import type { Host } from './host.js';
|
|
3
|
+
/**
|
|
4
|
+
* `system.packages` — the OS binaries the app runs (OCR, PDF tools, `unzip`):
|
|
5
|
+
* Debian/Ubuntu apt package names, declared in deploy.config.ts so that a
|
|
6
|
+
* server without them fails the preflight, not the first user who reaches the
|
|
7
|
+
* feature.
|
|
8
|
+
*
|
|
9
|
+
* Two sides, as everywhere else (RFC 0006 §11.4): the app user only checks
|
|
10
|
+
* (`dpkg-query`, C12) and prints the fix; root installs — `bootstrap` and
|
|
11
|
+
* `install` — from the install plan's list, a field it validates again. The
|
|
12
|
+
* names reach apt as arguments, never through a shell.
|
|
13
|
+
*/
|
|
14
|
+
/**
|
|
15
|
+
* An apt package name (Debian Policy §5.6.1, lowercase only): never an option
|
|
16
|
+
* (`-…`), never a path, a version (`=`), a release (`/`), a glob or shell syntax.
|
|
17
|
+
*/
|
|
18
|
+
export declare const SYSTEM_PACKAGE: RegExp;
|
|
19
|
+
/** More than any app needs; a cap on what root is asked to install. */
|
|
20
|
+
export declare const MAX_SYSTEM_PACKAGES = 64;
|
|
21
|
+
/** apt as root: no question can block it (there may be no terminal). */
|
|
22
|
+
export declare const APT: string[];
|
|
23
|
+
/** Every problem with a package list, as `where` names it (`system.packages`); none → []. */
|
|
24
|
+
export declare function systemPackageProblems(value: unknown, where: string): string[];
|
|
25
|
+
export interface PackageStatus {
|
|
26
|
+
/** Declared and not installed. */
|
|
27
|
+
missing: string[];
|
|
28
|
+
/** No `dpkg-query` here (not Debian/Ubuntu): nothing could be checked. */
|
|
29
|
+
unverified: boolean;
|
|
30
|
+
}
|
|
31
|
+
/**
|
|
32
|
+
* Which declared packages are not installed: `dpkg-query -W -f=${Status} <pkg>`,
|
|
33
|
+
* one argv per package. The status is "<want> <flag> <status>"; installed is
|
|
34
|
+
* the third word (`install ok installed`, or `hold ok installed`). An unknown
|
|
35
|
+
* package exits non-zero: missing. A package of several architectures prints
|
|
36
|
+
* one status each, run together: installed when one of them is.
|
|
37
|
+
*/
|
|
38
|
+
export declare function packageStatus(host: Host, packages: readonly string[], cwd: string): Promise<PackageStatus>;
|
|
39
|
+
/** The command an administrator runs for the missing packages — printed, never run by the app user. */
|
|
40
|
+
export declare const fixCommand: (missing: readonly string[]) => string;
|
|
41
|
+
/**
|
|
42
|
+
* C12 — the declared OS packages are installed. Missing is an error: the
|
|
43
|
+
* release would build and start, then fail on the first request that needs
|
|
44
|
+
* one. No `dpkg-query` is a warning: the deploy cannot tell, and cannot fix it.
|
|
45
|
+
*/
|
|
46
|
+
export declare function systemFindings(packages: readonly string[], status: PackageStatus): Finding[];
|
|
47
|
+
/** What `plan` prints for the packages. */
|
|
48
|
+
export declare function describeSystem(packages: readonly string[], status: PackageStatus | undefined): string[];
|
|
49
|
+
/** Root's commands: the index refreshed once, then the packages — argv, no shell, no recommends. */
|
|
50
|
+
export declare const aptInstall: (packages: readonly string[]) => string[][];
|
package/dist/system.js
ADDED
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `system.packages` — the OS binaries the app runs (OCR, PDF tools, `unzip`):
|
|
3
|
+
* Debian/Ubuntu apt package names, declared in deploy.config.ts so that a
|
|
4
|
+
* server without them fails the preflight, not the first user who reaches the
|
|
5
|
+
* feature.
|
|
6
|
+
*
|
|
7
|
+
* Two sides, as everywhere else (RFC 0006 §11.4): the app user only checks
|
|
8
|
+
* (`dpkg-query`, C12) and prints the fix; root installs — `bootstrap` and
|
|
9
|
+
* `install` — from the install plan's list, a field it validates again. The
|
|
10
|
+
* names reach apt as arguments, never through a shell.
|
|
11
|
+
*/
|
|
12
|
+
/**
|
|
13
|
+
* An apt package name (Debian Policy §5.6.1, lowercase only): never an option
|
|
14
|
+
* (`-…`), never a path, a version (`=`), a release (`/`), a glob or shell syntax.
|
|
15
|
+
*/
|
|
16
|
+
export const SYSTEM_PACKAGE = /^[a-z0-9][a-z0-9.+-]{1,62}$/;
|
|
17
|
+
/** More than any app needs; a cap on what root is asked to install. */
|
|
18
|
+
export const MAX_SYSTEM_PACKAGES = 64;
|
|
19
|
+
/** apt as root: no question can block it (there may be no terminal). */
|
|
20
|
+
export const APT = ['env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get'];
|
|
21
|
+
/** Every problem with a package list, as `where` names it (`system.packages`); none → []. */
|
|
22
|
+
export function systemPackageProblems(value, where) {
|
|
23
|
+
if (!Array.isArray(value))
|
|
24
|
+
return [`${where} must be a list of apt package names`];
|
|
25
|
+
const problems = [];
|
|
26
|
+
if (value.length > MAX_SYSTEM_PACKAGES)
|
|
27
|
+
problems.push(`${where}: at most ${MAX_SYSTEM_PACKAGES} packages`);
|
|
28
|
+
for (const name of value) {
|
|
29
|
+
if (typeof name !== 'string' || !SYSTEM_PACKAGE.test(name))
|
|
30
|
+
problems.push(`${where}: "${String(name)}" is not an apt package name (${SYSTEM_PACKAGE})`);
|
|
31
|
+
}
|
|
32
|
+
if (new Set(value).size !== value.length)
|
|
33
|
+
problems.push(`${where}: each package once`);
|
|
34
|
+
return problems;
|
|
35
|
+
}
|
|
36
|
+
/**
|
|
37
|
+
* dpkg's "<want> <error> <status>", matched by its closed vocabularies: with
|
|
38
|
+
* no separator in the format, two architectures' statuses run together
|
|
39
|
+
* (`hold ok installedinstall ok installed`), and `\S+` would read one word.
|
|
40
|
+
*/
|
|
41
|
+
const STATUS = /(unknown|install|hold|deinstall|purge) (ok|reinstreq) (not-installed|config-files|half-installed|unpacked|half-configured|triggers-awaited|triggers-pending|installed)/g;
|
|
42
|
+
/**
|
|
43
|
+
* Which declared packages are not installed: `dpkg-query -W -f=${Status} <pkg>`,
|
|
44
|
+
* one argv per package. The status is "<want> <flag> <status>"; installed is
|
|
45
|
+
* the third word (`install ok installed`, or `hold ok installed`). An unknown
|
|
46
|
+
* package exits non-zero: missing. A package of several architectures prints
|
|
47
|
+
* one status each, run together: installed when one of them is.
|
|
48
|
+
*/
|
|
49
|
+
export async function packageStatus(host, packages, cwd) {
|
|
50
|
+
const missing = [];
|
|
51
|
+
for (const name of packages) {
|
|
52
|
+
const result = await host.exec('dpkg-query', ['-W', '-f=${Status}', name], { cwd });
|
|
53
|
+
// 127: the command itself is absent (spawn failed) — not a Debian system.
|
|
54
|
+
if (result.code === 127)
|
|
55
|
+
return { missing: [], unverified: true };
|
|
56
|
+
const statuses = [...result.stdout.matchAll(STATUS)].map((m) => m[3]);
|
|
57
|
+
if (result.code !== 0 || statuses.length === 0 || !statuses.includes('installed'))
|
|
58
|
+
missing.push(name);
|
|
59
|
+
}
|
|
60
|
+
return { missing, unverified: false };
|
|
61
|
+
}
|
|
62
|
+
/** The command an administrator runs for the missing packages — printed, never run by the app user. */
|
|
63
|
+
export const fixCommand = (missing) => `sudo apt-get install -y ${missing.join(' ')}`;
|
|
64
|
+
/**
|
|
65
|
+
* C12 — the declared OS packages are installed. Missing is an error: the
|
|
66
|
+
* release would build and start, then fail on the first request that needs
|
|
67
|
+
* one. No `dpkg-query` is a warning: the deploy cannot tell, and cannot fix it.
|
|
68
|
+
*/
|
|
69
|
+
export function systemFindings(packages, status) {
|
|
70
|
+
if (packages.length === 0)
|
|
71
|
+
return [];
|
|
72
|
+
if (status.unverified) {
|
|
73
|
+
return [{ id: 'C12', level: 'warning', message: `system.packages (${packages.join(', ')}) cannot be verified: no dpkg-query on this server (Debian/Ubuntu only)` }];
|
|
74
|
+
}
|
|
75
|
+
if (status.missing.length === 0)
|
|
76
|
+
return [];
|
|
77
|
+
return [{
|
|
78
|
+
id: 'C12',
|
|
79
|
+
level: 'error',
|
|
80
|
+
message: `system package${status.missing.length > 1 ? 's' : ''} not installed: ${status.missing.join(', ')}`,
|
|
81
|
+
fix: fixCommand(status.missing),
|
|
82
|
+
}];
|
|
83
|
+
}
|
|
84
|
+
/** What `plan` prints for the packages. */
|
|
85
|
+
export function describeSystem(packages, status) {
|
|
86
|
+
if (packages.length === 0)
|
|
87
|
+
return [];
|
|
88
|
+
const state = !status || status.unverified ? 'not verified: no dpkg-query' : status.missing.length ? `missing: ${status.missing.join(', ')}` : 'installed';
|
|
89
|
+
return [`${packages.join(', ')} (${state})`];
|
|
90
|
+
}
|
|
91
|
+
/** Root's commands: the index refreshed once, then the packages — argv, no shell, no recommends. */
|
|
92
|
+
export const aptInstall = (packages) => [
|
|
93
|
+
[...APT, 'update', '-qq'],
|
|
94
|
+
[...APT, 'install', '-y', '-qq', '--no-install-recommends', ...packages],
|
|
95
|
+
];
|