@basaltkit/deploy 0.4.1 → 0.5.1
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 +284 -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 +56 -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 +61 -5
- package/dist/events.d.ts +168 -0
- package/dist/events.js +477 -0
- package/dist/host.d.ts +179 -7
- package/dist/host.js +317 -42
- 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 +437 -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/apache.js
CHANGED
|
@@ -29,7 +29,8 @@ export function renderVhost(ctx, port) {
|
|
|
29
29
|
const cert = `/etc/letsencrypt/live/${proxy.certName ?? domain}`;
|
|
30
30
|
return `# Written by basalt-deploy install for "${app}". Deploys compare this file with
|
|
31
31
|
# what install would write and print the difference; they never rewrite it.
|
|
32
|
-
# To change it: edit deploy.config.ts,
|
|
32
|
+
# To change it: edit deploy.config.ts, run ${INSTALL_COMMAND}
|
|
33
|
+
# as the app user, then the root command it prints.
|
|
33
34
|
|
|
34
35
|
<VirtualHost *:80>
|
|
35
36
|
ServerName ${domain}
|
|
@@ -42,9 +43,17 @@ ${alias} RewriteEngine On
|
|
|
42
43
|
ServerName ${domain}
|
|
43
44
|
${alias}
|
|
44
45
|
DocumentRoot ${webRoot}
|
|
46
|
+
# The checkout is the app user's: a link it plants is followed only to a
|
|
47
|
+
# file it owns too (never to /, nor to another site's files), and no
|
|
48
|
+
# .htaccess turns that back on.
|
|
49
|
+
<Directory ${ctx.dir}>
|
|
50
|
+
Options -Indexes -FollowSymLinks +SymLinksIfOwnerMatch
|
|
51
|
+
AllowOverride None
|
|
52
|
+
</Directory>
|
|
45
53
|
<Directory ${webRoot}>
|
|
46
54
|
Require all granted
|
|
47
|
-
Options -Indexes
|
|
55
|
+
Options -Indexes -FollowSymLinks +SymLinksIfOwnerMatch
|
|
56
|
+
AllowOverride None
|
|
48
57
|
FallbackResource /index.html
|
|
49
58
|
</Directory>
|
|
50
59
|
|
package/dist/audit.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { type DeployContext } from './context.js';
|
|
2
|
+
import type { Host } from './host.js';
|
|
3
|
+
import type { Release } from './state.js';
|
|
4
|
+
/**
|
|
5
|
+
* Who deployed, from where, how — kept with every release record (and, with
|
|
6
|
+
* `audit: { syslog: true }`, sent to the system log). Facts the process can
|
|
7
|
+
* see, never secrets: `$SSH_CONNECTION`'s client address, not a key.
|
|
8
|
+
*/
|
|
9
|
+
export interface Audit {
|
|
10
|
+
/** `--actor`, else `$BASALT_DEPLOY_ACTOR`, else `$USER` (a shared account names a person this way). */
|
|
11
|
+
actor: string;
|
|
12
|
+
/** The SSH client address, when the deploy runs over SSH. */
|
|
13
|
+
client?: string;
|
|
14
|
+
/** `ssh`, `ci`, `terminal`, `batch` (cron, a pipe) or `ui` (`--via=ui`: a program drove the CLI over SSH). */
|
|
15
|
+
via: string;
|
|
16
|
+
}
|
|
17
|
+
/** `via` is self-declared, like `--actor`: it attributes, it does not authenticate (RFC 0008 §8.6). */
|
|
18
|
+
export declare function auditOf(host: Host, declared?: string, declaredVia?: 'ui'): Audit;
|
|
19
|
+
/** One line per recorded release in the system log (`logger -t basalt-deploy`), best effort. */
|
|
20
|
+
export declare function syslogRelease(ctx: DeployContext, release: Release): Promise<void>;
|
package/dist/audit.js
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { DeployError } from './context.js';
|
|
2
|
+
const ACTOR = /^[A-Za-z0-9._@+-]{1,64}$/;
|
|
3
|
+
/** `via` is self-declared, like `--actor`: it attributes, it does not authenticate (RFC 0008 §8.6). */
|
|
4
|
+
export function auditOf(host, declared, declaredVia) {
|
|
5
|
+
const named = declared ?? host.env['BASALT_DEPLOY_ACTOR'];
|
|
6
|
+
if (named !== undefined && !ACTOR.test(named))
|
|
7
|
+
throw new DeployError(`--actor "${named}": 1–64 of letters, digits and . _ @ + -`);
|
|
8
|
+
const actor = named ?? host.env['USER'] ?? String(host.uid());
|
|
9
|
+
// "client-ip client-port server-ip server-port": split, never a regex over the whole input.
|
|
10
|
+
const ip = (host.env['SSH_CONNECTION'] ?? '').trim().split(/\s+/)[0] ?? '';
|
|
11
|
+
const client = /^[0-9A-Fa-f:.]{2,45}$/.test(ip) ? ip : undefined;
|
|
12
|
+
const via = declaredVia ?? (client ? 'ssh' : host.env['CI'] ? 'ci' : host.interactive() ? 'terminal' : 'batch');
|
|
13
|
+
return { actor, ...(client ? { client } : {}), via };
|
|
14
|
+
}
|
|
15
|
+
/** One line per recorded release in the system log (`logger -t basalt-deploy`), best effort. */
|
|
16
|
+
export async function syslogRelease(ctx, release) {
|
|
17
|
+
if (!ctx.config.audit?.syslog)
|
|
18
|
+
return;
|
|
19
|
+
const fields = [
|
|
20
|
+
`app=${ctx.config.app}`, `sha=${release.sha.slice(0, 12)}`, `status=${release.status}`,
|
|
21
|
+
`actor=${release.actor ?? release.user}`, ...(release.client ? [`client=${release.client}`] : []), ...(release.via ? [`via=${release.via}`] : []),
|
|
22
|
+
];
|
|
23
|
+
const result = await ctx.host.exec('logger', ['-t', 'basalt-deploy', '--', fields.join(' ')]);
|
|
24
|
+
if (result.code !== 0)
|
|
25
|
+
ctx.host.out.warn(`audit.syslog: logger failed (${result.stderr.trim() || `exit ${result.code}`}) — the release is recorded in releases.json`);
|
|
26
|
+
}
|
package/dist/backup.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type DeployContext } from './context.js';
|
|
1
|
+
import { type DeployContext, type Finding } from './context.js';
|
|
2
2
|
import type { InfraPlan } from './infra.js';
|
|
3
3
|
/**
|
|
4
4
|
* `pg_dump -Fc` of the central database before migrating — migrations do not
|
|
@@ -11,5 +11,21 @@ import type { InfraPlan } from './infra.js';
|
|
|
11
11
|
* when there is one, travels in the environment (`docker exec -e PGPASSWORD`,
|
|
12
12
|
* no value), never on a command line.
|
|
13
13
|
*/
|
|
14
|
+
/**
|
|
15
|
+
* Where the dumps go: `<stateDir>/backups` (0700). Once `install` ran that is
|
|
16
|
+
* `/var/lib/basalt/<app>/backups`, outside the checkout — never in a
|
|
17
|
+
* `COPY . .` image, a commit or a served directory. Before, it is
|
|
18
|
+
* `<checkout>/.basalt/backups`, and {@link backupPlaceFindings} says when
|
|
19
|
+
* git or the Docker build context would take it. `backup.dir` (relative to
|
|
20
|
+
* the checkout) keeps the old place for those who chose it.
|
|
21
|
+
*/
|
|
22
|
+
export declare const backupDir: (ctx: DeployContext) => string;
|
|
23
|
+
/**
|
|
24
|
+
* Dumps of the whole database inside the checkout: said before the deploy
|
|
25
|
+
* writes one, when git does not ignore them or a Docker build would copy
|
|
26
|
+
* them into an image. And dumps left in the pre-0.6 place
|
|
27
|
+
* (`backups/predeploy`), which nothing prunes any more.
|
|
28
|
+
*/
|
|
29
|
+
export declare function backupPlaceFindings(ctx: DeployContext): Promise<Finding[]>;
|
|
14
30
|
export declare function backupDatabase(ctx: DeployContext, values: Map<string, string>, infra: InfraPlan, sha: string): Promise<string>;
|
|
15
31
|
export declare function restoreCommand(ctx: DeployContext, infra: InfraPlan, file: string, values?: Map<string, string>): string;
|
package/dist/backup.js
CHANGED
|
@@ -12,10 +12,65 @@ import { dumpContainer, dumpUrlKey } from './services.js';
|
|
|
12
12
|
* when there is one, travels in the environment (`docker exec -e PGPASSWORD`,
|
|
13
13
|
* no value), never on a command line.
|
|
14
14
|
*/
|
|
15
|
+
/**
|
|
16
|
+
* Where the dumps go: `<stateDir>/backups` (0700). Once `install` ran that is
|
|
17
|
+
* `/var/lib/basalt/<app>/backups`, outside the checkout — never in a
|
|
18
|
+
* `COPY . .` image, a commit or a served directory. Before, it is
|
|
19
|
+
* `<checkout>/.basalt/backups`, and {@link backupPlaceFindings} says when
|
|
20
|
+
* git or the Docker build context would take it. `backup.dir` (relative to
|
|
21
|
+
* the checkout) keeps the old place for those who chose it.
|
|
22
|
+
*/
|
|
23
|
+
export const backupDir = (ctx) => (ctx.config.backup?.dir ? join(ctx.dir, ctx.config.backup.dir) : join(ctx.stateDir, 'backups'));
|
|
24
|
+
/** A .dockerignore line that keeps `top` (a top-level directory) out of the build context. */
|
|
25
|
+
const ignoresTop = (dockerignore, top) => dockerignore.split('\n').map((l) => l.trim().replace(/\/+$/, '')).some((l) => [top, `/${top}`, `${top}/**`, `/${top}/**`, `**/${top}`].includes(l));
|
|
26
|
+
/**
|
|
27
|
+
* Dumps of the whole database inside the checkout: said before the deploy
|
|
28
|
+
* writes one, when git does not ignore them or a Docker build would copy
|
|
29
|
+
* them into an image. And dumps left in the pre-0.6 place
|
|
30
|
+
* (`backups/predeploy`), which nothing prunes any more.
|
|
31
|
+
*/
|
|
32
|
+
export async function backupPlaceFindings(ctx) {
|
|
33
|
+
const { host } = ctx;
|
|
34
|
+
const findings = [];
|
|
35
|
+
const dir = backupDir(ctx);
|
|
36
|
+
const fix = `run install once (dumps then go to /var/lib/basalt/${ctx.config.app}/backups, outside the checkout)`;
|
|
37
|
+
if (dir.startsWith(`${ctx.dir}/`)) {
|
|
38
|
+
const relative = dir.slice(ctx.dir.length + 1);
|
|
39
|
+
const top = relative.split('/')[0];
|
|
40
|
+
const ignored = await host.exec('git', ['check-ignore', '-q', '--no-index', '--', `${relative}/x.dump`], { cwd: ctx.dir });
|
|
41
|
+
if (ignored.code !== 0) {
|
|
42
|
+
findings.push({ id: 'dumps', level: 'warning', message: `database dumps go to ${dir}, inside the checkout, and git does not ignore them`, fix: `add /${top}/ to .gitignore, or ${fix}` });
|
|
43
|
+
}
|
|
44
|
+
const dockerBuild = ctx.config.runtime.kind === 'compose' || (await host.exists(join(ctx.dir, 'Dockerfile')));
|
|
45
|
+
const dockerignore = await host.readFile(join(ctx.dir, '.dockerignore'));
|
|
46
|
+
if (dockerBuild && !ignoresTop(dockerignore ?? '', top)) {
|
|
47
|
+
findings.push({ id: 'dumps', level: 'warning', message: `database dumps go to ${dir}, inside the Docker build context: a COPY . . puts them in the image`, fix: `add ${top} to .dockerignore, or ${fix}` });
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
// /var/lib/basalt is there (another app's install, or this one's with a
|
|
51
|
+
// parent the app user cannot enter) but this app's state is not: the deploy
|
|
52
|
+
// falls back to the checkout, which is easy to miss.
|
|
53
|
+
const system = `/var/lib/basalt/${ctx.config.app}`;
|
|
54
|
+
if (ctx.stateDir !== system && (await host.stat('/var/lib/basalt'))?.kind === 'dir') {
|
|
55
|
+
findings.push({ id: 'state-dir', level: 'warning', message: `${system} is missing or not reachable by this user: the deploy's state (release history, lock, dumps) stays in ${ctx.stateDir}, inside the checkout`, fix: 'run install-plan, then the root command it prints: install makes it yours (0700) and its parent enterable' });
|
|
56
|
+
}
|
|
57
|
+
if (!ctx.config.backup?.dir) {
|
|
58
|
+
const legacy = join(ctx.dir, 'backups', 'predeploy');
|
|
59
|
+
const left = (await host.list(legacy)).filter((name) => name.endsWith('.dump'));
|
|
60
|
+
if (left.length > 0) {
|
|
61
|
+
findings.push({ id: 'dumps', level: 'warning', message: `${left.length} dump(s) left in ${legacy} (the old place): new dumps go to ${dir}, and nothing prunes these`, fix: `move them next to the new ones (install -d -m 700 ${dir} && mv ${legacy}/*.dump ${dir}/) or delete them` });
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
return findings;
|
|
65
|
+
}
|
|
15
66
|
export async function backupDatabase(ctx, values, infra, sha) {
|
|
16
67
|
const { host, config } = ctx;
|
|
17
|
-
const dir =
|
|
68
|
+
const dir = backupDir(ctx);
|
|
18
69
|
await host.mkdir(dir, 0o700);
|
|
70
|
+
// A directory made earlier with a looser mode: every dump is the whole database.
|
|
71
|
+
const made = await host.stat(dir);
|
|
72
|
+
if (made?.kind === 'dir' && made.uid === host.uid() && made.mode !== undefined && (made.mode & 0o077) !== 0)
|
|
73
|
+
await host.chmod(dir, 0o700);
|
|
19
74
|
const stamp = host.now().toISOString().replace(/[-:]/g, '').replace(/\..+$/, '');
|
|
20
75
|
const file = join(dir, `${stamp}-${sha.slice(0, 7)}.dump`);
|
|
21
76
|
const pg = infra.services.find((s) => s.service === 'postgres');
|
package/dist/bin.js
CHANGED
|
@@ -1,3 +1,11 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
2
|
import { main } from './cli.js';
|
|
3
|
-
|
|
3
|
+
const code = await main(process.argv.slice(2));
|
|
4
|
+
// Events still queued for a pipe reach it before the process ends (a reader gone: at most 2 s).
|
|
5
|
+
if (process.stdout.writableLength > 0) {
|
|
6
|
+
await new Promise((resolve) => {
|
|
7
|
+
process.stdout.once('drain', resolve);
|
|
8
|
+
setTimeout(resolve, 2000).unref();
|
|
9
|
+
});
|
|
10
|
+
}
|
|
11
|
+
process.exit(code);
|
package/dist/bootstrap.d.ts
CHANGED
|
@@ -1,35 +1,85 @@
|
|
|
1
1
|
import type { Host } from './host.js';
|
|
2
2
|
/**
|
|
3
3
|
* `basalt-deploy bootstrap` — a fresh Ubuntu/Debian server, once (RFC 0007 §7).
|
|
4
|
-
* Root
|
|
4
|
+
* Root, with a copy of this tool root owns (`sudo -H npx --yes
|
|
5
|
+
* --package=@basaltkit/deploy@<exact version> -- basalt-deploy bootstrap
|
|
6
|
+
* --dir=<checkout>`, run from outside the checkout): it never loads deploy.config.ts nor runs the
|
|
7
|
+
* checkout's node_modules — both are the app user's to change. Three phases:
|
|
5
8
|
*
|
|
6
|
-
* base packages · Docker + compose · Node at engines.node ·
|
|
7
|
-
*
|
|
8
|
-
*
|
|
9
|
-
* the user
|
|
10
|
-
*
|
|
9
|
+
* 1. the system: base packages · Docker + compose · Node at engines.node ·
|
|
10
|
+
* the pnpm the lockfile records · the checkout and the docker group for
|
|
11
|
+
* the user;
|
|
12
|
+
* 2. as the user, in the checkout: `pnpm install`, `env` (it may ask), then
|
|
13
|
+
* `install-plan`, whose JSON comes back as data;
|
|
14
|
+
* 3. as root, from that plan: swap (< 6 GB RAM), ufw (only when nothing but
|
|
15
|
+
* SSH listens), Caddy (proxy: caddy), then `install`.
|
|
11
16
|
*
|
|
12
|
-
*
|
|
13
|
-
*
|
|
14
|
-
* reads package.json and takes the proxy and swap from flags.
|
|
15
|
-
*
|
|
16
|
-
* `--dry-run` prints every command and runs none.
|
|
17
|
+
* `--dry-run` prints every command and runs none (phase 3 then assumes
|
|
18
|
+
* `--proxy`, or none: the plan is not written in a dry run).
|
|
17
19
|
*/
|
|
18
20
|
export interface BootstrapOptions {
|
|
19
21
|
user: string | undefined;
|
|
20
|
-
|
|
21
|
-
|
|
22
|
-
|
|
22
|
+
/** Overrides the plan's proxy (and decides phase 3 of a dry run). */
|
|
23
|
+
proxy?: 'apache' | 'caddy' | 'none';
|
|
24
|
+
/** Overrides the plan's `bootstrap.swapGb` (default 4). */
|
|
25
|
+
swapGb?: number;
|
|
26
|
+
/** Overrides the plan's `bootstrap.firewall` (default on). */
|
|
27
|
+
firewall?: boolean;
|
|
23
28
|
dryRun: boolean;
|
|
24
29
|
}
|
|
25
|
-
interface Action {
|
|
30
|
+
export interface Action {
|
|
26
31
|
what: string;
|
|
27
32
|
commands: string[][];
|
|
33
|
+
/** Run in this directory (the checkout, for the user's steps); default outside it. */
|
|
34
|
+
cwd?: string;
|
|
35
|
+
/** The command may ask at the terminal (`env`). */
|
|
36
|
+
interactive?: boolean;
|
|
37
|
+
/** Asked at the terminal before a real run runs it; a "no" (or no terminal) stops bootstrap. */
|
|
38
|
+
confirm?: string;
|
|
28
39
|
}
|
|
29
|
-
/**
|
|
40
|
+
/**
|
|
41
|
+
* The checkout bootstrap works on — and may `chown -R` to the user — named
|
|
42
|
+
* with `--dir`, never taken from the working directory (root's commands run
|
|
43
|
+
* from `cd /`). It must be an app checkout: an absolute, normalized path with
|
|
44
|
+
* no link in it, not a system directory, holding package.json and .git.
|
|
45
|
+
*/
|
|
46
|
+
export declare function checkoutProblem(host: Host, dir: string): Promise<string | undefined>;
|
|
47
|
+
/** Phase 1 — what the system lacks. Pure planning: probes only. */
|
|
48
|
+
export declare function planSystem(host: Host, dir: string, user: string): Promise<{
|
|
49
|
+
actions: Action[];
|
|
50
|
+
notes: string[];
|
|
51
|
+
}>;
|
|
52
|
+
/**
|
|
53
|
+
* Phase 2 — as the user, in the checkout: argv only (no shell), the directory
|
|
54
|
+
* as the working directory — and never on root's terminal. Without
|
|
55
|
+
* `use_pty` (sudo < 1.9.14: Debian 12, Ubuntu 22.04) the user's command would
|
|
56
|
+
* share root's controlling terminal, and on a kernel that still allows
|
|
57
|
+
* TIOCSTI (< 6.2) a postinstall script could type a command into root's
|
|
58
|
+
* shell. So: the plain steps run in a new session (`setsid -w`: no
|
|
59
|
+
* controlling terminal, stdin closed); `env`, which may ask, gets a terminal
|
|
60
|
+
* of its own (`script`, run by root, relays the keys) — or, with no terminal
|
|
61
|
+
* to relay, runs like the others and fails closed on a missing answer.
|
|
62
|
+
*
|
|
63
|
+
* A Ctrl-C does not reach a step in its own session: bootstrap stops, the
|
|
64
|
+
* step finishes on its own.
|
|
65
|
+
*/
|
|
66
|
+
export declare function userSteps(user: string, dir: string, tty: boolean): Action[];
|
|
67
|
+
/** The phase-2 command whose stdout is the install plan (JSON) — in its own session, like the other steps. */
|
|
68
|
+
export declare const planCommand: (user: string) => string[];
|
|
69
|
+
/** Phase 3 — swap, ufw, Caddy, from the plan (or the flags). */
|
|
70
|
+
export declare function planServer(host: Host, options: {
|
|
71
|
+
proxy: 'apache' | 'caddy' | 'none';
|
|
72
|
+
swapGb: number;
|
|
73
|
+
firewall: boolean;
|
|
74
|
+
}): Promise<{
|
|
75
|
+
actions: Action[];
|
|
76
|
+
notes: string[];
|
|
77
|
+
}>;
|
|
78
|
+
/** Every phase as a dry run shows it: phase 3 with the flags (the plan does not exist yet). */
|
|
30
79
|
export declare function planBootstrap(host: Host, dir: string, options: BootstrapOptions): Promise<{
|
|
31
80
|
actions: Action[];
|
|
32
81
|
notes: string[];
|
|
33
82
|
}>;
|
|
34
|
-
|
|
35
|
-
export
|
|
83
|
+
/** The @basaltkit/deploy version the lockfile records — what root should be running. */
|
|
84
|
+
export declare function lockedDeployVersion(lockfile: string): string | undefined;
|
|
85
|
+
export declare function bootstrap(host: Host, dir: string, options: BootstrapOptions, tool?: string): Promise<number>;
|
package/dist/bootstrap.js
CHANGED
|
@@ -1,16 +1,56 @@
|
|
|
1
1
|
import { tmpdir } from 'node:os';
|
|
2
|
-
import { join } from 'node:path';
|
|
2
|
+
import { join, normalize } from 'node:path';
|
|
3
3
|
import { below, lockedPnpm, minimumVersion } from './checks.js';
|
|
4
4
|
import { DeployError } from './context.js';
|
|
5
|
+
import { install, parseInstallPlan } from './install-plan.js';
|
|
6
|
+
import { USER_NAME } from './trust.js';
|
|
5
7
|
const APT = ['env', 'DEBIAN_FRONTEND=noninteractive', 'apt-get'];
|
|
6
8
|
const OUTSIDE = { cwd: tmpdir() };
|
|
7
|
-
|
|
8
|
-
|
|
9
|
+
const BIN = 'node_modules/@basaltkit/deploy/dist/bin.js';
|
|
10
|
+
const sh = (script) => ['sh', '-c', script];
|
|
11
|
+
/** Read as data, as root, from the app user's checkout: no link followed, a size cap (a FIFO or /dev/zero must not hang root). */
|
|
12
|
+
const PACKAGE_JSON_BYTES = 1024 * 1024;
|
|
13
|
+
const LOCKFILE_BYTES = 32 * 1024 * 1024;
|
|
14
|
+
async function readCheckoutFile(host, path, maxBytes) {
|
|
15
|
+
try {
|
|
16
|
+
return await host.readPlainFile(path, maxBytes);
|
|
17
|
+
}
|
|
18
|
+
catch {
|
|
19
|
+
return undefined;
|
|
20
|
+
}
|
|
21
|
+
}
|
|
22
|
+
/** Directories that are never a checkout: bootstrap would `chown -R` them to the app user. */
|
|
23
|
+
const SYSTEM_DIRS = new Set(['/', '/bin', '/boot', '/dev', '/etc', '/home', '/lib', '/lib32', '/lib64', '/media', '/mnt', '/opt', '/proc', '/root', '/run', '/sbin', '/snap', '/srv', '/sys', '/tmp', '/usr', '/usr/local', '/var', '/var/lib', '/var/www']);
|
|
24
|
+
const SYSTEM_TREES = ['/bin/', '/boot/', '/dev/', '/etc/', '/lib/', '/lib32/', '/lib64/', '/proc/', '/root/', '/run/', '/sbin/', '/sys/', '/usr/', '/var/lib/'];
|
|
25
|
+
/**
|
|
26
|
+
* The checkout bootstrap works on — and may `chown -R` to the user — named
|
|
27
|
+
* with `--dir`, never taken from the working directory (root's commands run
|
|
28
|
+
* from `cd /`). It must be an app checkout: an absolute, normalized path with
|
|
29
|
+
* no link in it, not a system directory, holding package.json and .git.
|
|
30
|
+
*/
|
|
31
|
+
export async function checkoutProblem(host, dir) {
|
|
32
|
+
if (!dir.startsWith('/') || normalize(dir) !== dir || (dir !== '/' && dir.endsWith('/')) || /[\0\n\r"'\\$`\s]/.test(dir))
|
|
33
|
+
return `${dir} must be an absolute, normalized path without quotes, spaces or shell characters`;
|
|
34
|
+
if (SYSTEM_DIRS.has(dir) || SYSTEM_TREES.some((tree) => dir.startsWith(tree)))
|
|
35
|
+
return `${dir} is a system directory, not an app checkout`;
|
|
36
|
+
const stat = await host.stat(dir);
|
|
37
|
+
if (stat?.kind !== 'dir')
|
|
38
|
+
return `${dir} is not a directory${stat?.kind === 'symlink' ? ' (a symbolic link is refused)' : ''}`;
|
|
39
|
+
const real = await host.realpath(dir);
|
|
40
|
+
if (real !== dir)
|
|
41
|
+
return `${dir} goes through a symbolic link (it is ${real ?? 'unreadable'}): name the real directory`;
|
|
42
|
+
if ((await host.stat(join(dir, 'package.json')))?.kind !== 'file')
|
|
43
|
+
return `${dir} has no package.json: not an app checkout`;
|
|
44
|
+
if (!(await host.exists(join(dir, '.git'))))
|
|
45
|
+
return `${dir} has no .git: not a git checkout`;
|
|
46
|
+
return undefined;
|
|
47
|
+
}
|
|
48
|
+
const has = async (host, command) => (await host.exec('sh', ['-c', `command -v ${command}`], OUTSIDE)).code === 0;
|
|
49
|
+
/** Phase 1 — what the system lacks. Pure planning: probes only. */
|
|
50
|
+
export async function planSystem(host, dir, user) {
|
|
9
51
|
const actions = [];
|
|
10
52
|
const notes = [];
|
|
11
|
-
|
|
12
|
-
const has = async (command) => (await host.exec('sh', ['-c', `command -v ${command}`], OUTSIDE)).code === 0;
|
|
13
|
-
if (!(await has('apt-get')))
|
|
53
|
+
if (!(await has(host, 'apt-get')))
|
|
14
54
|
throw new DeployError('bootstrap installs with apt: Ubuntu or Debian only');
|
|
15
55
|
const packages = [];
|
|
16
56
|
for (const name of ['ca-certificates', 'curl', 'git', 'openssl', 'gnupg']) {
|
|
@@ -32,9 +72,10 @@ export async function planBootstrap(host, dir, options) {
|
|
|
32
72
|
],
|
|
33
73
|
});
|
|
34
74
|
}
|
|
75
|
+
// package.json and the lockfile as data: versions matched by pattern, nothing evaluated.
|
|
35
76
|
let pkg = {};
|
|
36
77
|
try {
|
|
37
|
-
pkg = JSON.parse((await host
|
|
78
|
+
pkg = JSON.parse((await readCheckoutFile(host, join(dir, 'package.json'), PACKAGE_JSON_BYTES)) ?? '{}');
|
|
38
79
|
}
|
|
39
80
|
catch { /* reported by run's C9 */ }
|
|
40
81
|
const wanted = minimumVersion(pkg.engines?.node);
|
|
@@ -46,12 +87,61 @@ export async function planBootstrap(host, dir, options) {
|
|
|
46
87
|
}
|
|
47
88
|
if (pkg.packageManager?.startsWith('pnpm@')) {
|
|
48
89
|
// The lockfile's own pnpm when it records one (C11), else packageManager's.
|
|
49
|
-
const lockfile = await host
|
|
90
|
+
const lockfile = await readCheckoutFile(host, join(dir, 'pnpm-lock.yaml'), LOCKFILE_BYTES);
|
|
50
91
|
const version = (lockfile && lockedPnpm(lockfile)) ?? pkg.packageManager.slice('pnpm@'.length).split('+')[0];
|
|
92
|
+
if (!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(version))
|
|
93
|
+
throw new DeployError(`the pnpm version the project records ("${version}") is not a version`);
|
|
51
94
|
const current = (await host.exec('pnpm', ['--version'], OUTSIDE)).stdout.trim();
|
|
52
95
|
if (current !== version)
|
|
53
96
|
actions.push({ what: `pnpm ${version}${current ? ` (this server has ${current})` : ''}`, commands: [['npm', 'install', '-g', `pnpm@${version}`]] });
|
|
54
97
|
}
|
|
98
|
+
const owner = (await host.exec('stat', ['-c', '%U', dir], OUTSIDE)).stdout.trim();
|
|
99
|
+
if (owner !== user) {
|
|
100
|
+
actions.push({
|
|
101
|
+
what: `${dir} owned by ${user}`,
|
|
102
|
+
commands: [['chown', '-R', `${user}:`, dir]],
|
|
103
|
+
confirm: `${dir} is ${owner || 'unknown'}'s: give it and everything in it to ${user} (chown -R)?`,
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
const groups = (await host.exec('id', ['-nG', user], OUTSIDE)).stdout.split(/\s+/);
|
|
107
|
+
if (!groups.includes('docker')) {
|
|
108
|
+
// §11.2: the docker group, said plainly — rootless Docker is its own phase.
|
|
109
|
+
actions.push({ what: `${user} in the docker group`, commands: [['usermod', '-aG', 'docker', user]] });
|
|
110
|
+
notes.push(`${user} is now in the docker group — that is root on this machine (a container can mount /). Rootless Docker is a later step; it moves every volume.`);
|
|
111
|
+
}
|
|
112
|
+
return { actions, notes };
|
|
113
|
+
}
|
|
114
|
+
/**
|
|
115
|
+
* Phase 2 — as the user, in the checkout: argv only (no shell), the directory
|
|
116
|
+
* as the working directory — and never on root's terminal. Without
|
|
117
|
+
* `use_pty` (sudo < 1.9.14: Debian 12, Ubuntu 22.04) the user's command would
|
|
118
|
+
* share root's controlling terminal, and on a kernel that still allows
|
|
119
|
+
* TIOCSTI (< 6.2) a postinstall script could type a command into root's
|
|
120
|
+
* shell. So: the plain steps run in a new session (`setsid -w`: no
|
|
121
|
+
* controlling terminal, stdin closed); `env`, which may ask, gets a terminal
|
|
122
|
+
* of its own (`script`, run by root, relays the keys) — or, with no terminal
|
|
123
|
+
* to relay, runs like the others and fails closed on a missing answer.
|
|
124
|
+
*
|
|
125
|
+
* A Ctrl-C does not reach a step in its own session: bootstrap stops, the
|
|
126
|
+
* step finishes on its own.
|
|
127
|
+
*/
|
|
128
|
+
export function userSteps(user, dir, tty) {
|
|
129
|
+
const asUser = (...command) => ['sudo', '-u', user, '-H', '--', ...command];
|
|
130
|
+
const env = tty
|
|
131
|
+
// `user` matched USER_NAME and BIN is fixed: nothing in this line needs quoting.
|
|
132
|
+
? ['script', '--quiet', '--return', '--command', asUser('node', BIN, 'env').join(' '), '/dev/null']
|
|
133
|
+
: ['setsid', '-w', ...asUser('node', BIN, 'env')];
|
|
134
|
+
return [
|
|
135
|
+
{ what: `as ${user}: dependencies`, cwd: dir, commands: [['setsid', '-w', ...asUser('env', '-u', 'NODE_ENV', 'pnpm', 'install', '--frozen-lockfile')]] },
|
|
136
|
+
{ what: `as ${user}: the .env (asks what it cannot generate)`, cwd: dir, ...(tty ? { interactive: true } : {}), commands: [env] },
|
|
137
|
+
];
|
|
138
|
+
}
|
|
139
|
+
/** The phase-2 command whose stdout is the install plan (JSON) — in its own session, like the other steps. */
|
|
140
|
+
export const planCommand = (user) => ['setsid', '-w', 'sudo', '-u', user, '-H', '--', 'node', BIN, 'install-plan', '--out=-'];
|
|
141
|
+
/** Phase 3 — swap, ufw, Caddy, from the plan (or the flags). */
|
|
142
|
+
export async function planServer(host, options) {
|
|
143
|
+
const actions = [];
|
|
144
|
+
const notes = [];
|
|
55
145
|
const meminfo = (await host.readFile('/proc/meminfo')) ?? '';
|
|
56
146
|
const memGb = Number(/MemTotal:\s+(\d+)/.exec(meminfo)?.[1] ?? 0) / 1024 / 1024;
|
|
57
147
|
const swapKb = Number(/SwapTotal:\s+(\d+)/.exec(meminfo)?.[1] ?? 0);
|
|
@@ -61,7 +151,7 @@ export async function planBootstrap(host, dir, options) {
|
|
|
61
151
|
commands: [['fallocate', '-l', `${options.swapGb}G`, '/swapfile'], ['chmod', '600', '/swapfile'], ['mkswap', '/swapfile'], ['swapon', '/swapfile'], sh("grep -q '^/swapfile ' /etc/fstab || echo '/swapfile none swap sw 0 0' >> /etc/fstab")],
|
|
62
152
|
});
|
|
63
153
|
}
|
|
64
|
-
if (options.firewall && (await has('ufw'))) {
|
|
154
|
+
if (options.firewall && (await has(host, 'ufw'))) {
|
|
65
155
|
// SSH_CONNECTION = "client-ip client-port server-ip server-port": split, not a regex over input.
|
|
66
156
|
const sshPort = (host.env['SSH_CONNECTION'] ?? '').trim().split(/\s+/)[3];
|
|
67
157
|
const ssh = sshPort && /^\d+$/.test(sshPort) ? sshPort : '22';
|
|
@@ -84,7 +174,7 @@ export async function planBootstrap(host, dir, options) {
|
|
|
84
174
|
actions.push({ what: `ufw on: SSH (${ssh})${web.length ? ', 80, 443' : ''} only`, commands: [['ufw', 'allow', `${ssh}/tcp`], ...web, ['ufw', '--force', 'enable']] });
|
|
85
175
|
}
|
|
86
176
|
}
|
|
87
|
-
if (options.proxy === 'caddy' && !(await has('caddy'))) {
|
|
177
|
+
if (options.proxy === 'caddy' && !(await has(host, 'caddy'))) {
|
|
88
178
|
actions.push({
|
|
89
179
|
what: 'Caddy (cloudsmith)',
|
|
90
180
|
commands: [
|
|
@@ -96,53 +186,95 @@ export async function planBootstrap(host, dir, options) {
|
|
|
96
186
|
],
|
|
97
187
|
});
|
|
98
188
|
}
|
|
189
|
+
return { actions, notes };
|
|
190
|
+
}
|
|
191
|
+
/** Every phase as a dry run shows it: phase 3 with the flags (the plan does not exist yet). */
|
|
192
|
+
export async function planBootstrap(host, dir, options) {
|
|
99
193
|
const user = options.user;
|
|
100
|
-
const
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
// As the user, from the checkout: the project's own tools from here on.
|
|
110
|
-
const asUser = (...command) => ['sudo', '-u', user, '-H', '--', ...command];
|
|
111
|
-
actions.push({
|
|
112
|
-
what: `as ${user}: dependencies, then the .env (asks what it cannot generate)`,
|
|
113
|
-
commands: [
|
|
114
|
-
asUser('env', '-u', 'NODE_ENV', 'sh', '-c', `cd '${dir}' && pnpm install --frozen-lockfile`),
|
|
115
|
-
asUser('sh', '-c', `cd '${dir}' && node node_modules/@basaltkit/deploy/dist/bin.js env`),
|
|
194
|
+
const system = await planSystem(host, dir, user);
|
|
195
|
+
const server = await planServer(host, { proxy: options.proxy ?? 'none', swapGb: options.swapGb ?? 4, firewall: options.firewall ?? true });
|
|
196
|
+
return {
|
|
197
|
+
actions: [
|
|
198
|
+
...system.actions,
|
|
199
|
+
...userSteps(user, dir, host.interactive()),
|
|
200
|
+
{ what: `as ${user}: the install plan (data only)`, cwd: dir, commands: [planCommand(user)] },
|
|
201
|
+
...server.actions,
|
|
202
|
+
{ what: 'install (root, from the plan): state directory, the proxy site, env ownership', commands: [] },
|
|
116
203
|
],
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
return { actions, notes };
|
|
204
|
+
notes: [...system.notes, ...server.notes],
|
|
205
|
+
};
|
|
120
206
|
}
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
if ((await host.exec('id', ['-u', options.user], OUTSIDE)).code !== 0)
|
|
127
|
-
throw new DeployError(`no user ${options.user} on this server: adduser ${options.user} first`);
|
|
128
|
-
host.out.step(`bootstrap${options.dryRun ? ' — dry run, nothing below runs' : ''}`);
|
|
129
|
-
const { actions, notes } = await planBootstrap(host, dir, options);
|
|
207
|
+
/** The @basaltkit/deploy version the lockfile records — what root should be running. */
|
|
208
|
+
export function lockedDeployVersion(lockfile) {
|
|
209
|
+
return /['"]?@basaltkit\/deploy@(\d+\.\d+\.\d+(?:-[0-9A-Za-z.-]+)?)['"]?:/.exec(lockfile)?.[1];
|
|
210
|
+
}
|
|
211
|
+
async function runActions(host, actions, dryRun) {
|
|
130
212
|
for (const action of actions) {
|
|
131
213
|
host.out.info(action.what);
|
|
214
|
+
if (action.confirm && !dryRun && !(await host.confirm(action.confirm))) {
|
|
215
|
+
throw new DeployError(`${action.what}: not confirmed — nothing more was done (a terminal must answer; or make ${action.what.split(' ')[0]} the user's first)`);
|
|
216
|
+
}
|
|
132
217
|
for (const command of action.commands) {
|
|
133
|
-
host.out.info(` + ${command.join(' ')}`);
|
|
134
|
-
if (
|
|
218
|
+
host.out.info(` + ${command.join(' ')}${action.cwd ? ` (in ${action.cwd})` : ''}`);
|
|
219
|
+
if (dryRun)
|
|
135
220
|
continue;
|
|
136
|
-
const result = await host.exec(command[0], command.slice(1), {
|
|
221
|
+
const result = await host.exec(command[0], command.slice(1), {
|
|
222
|
+
cwd: action.cwd ?? OUTSIDE.cwd,
|
|
223
|
+
...(action.interactive ? { interactive: true } : { stream: true }),
|
|
224
|
+
});
|
|
137
225
|
if (result.code !== 0)
|
|
138
226
|
throw new DeployError(`${action.what}: \`${command.join(' ')}\` failed (exit ${result.code}) — re-run bootstrap after fixing it; what is done is not redone`);
|
|
139
227
|
}
|
|
140
|
-
if (!
|
|
228
|
+
if (!dryRun && action.commands.length)
|
|
141
229
|
host.out.ok(action.what);
|
|
142
230
|
}
|
|
143
|
-
|
|
231
|
+
}
|
|
232
|
+
export async function bootstrap(host, dir, options, tool) {
|
|
233
|
+
const user = options.user;
|
|
234
|
+
if (!user || user === 'root')
|
|
235
|
+
throw new DeployError('bootstrap needs the unprivileged user the deploys will run as: --user=<name> (never root)');
|
|
236
|
+
if (!USER_NAME.test(user))
|
|
237
|
+
throw new DeployError(`--user=${user} is not a login name`);
|
|
238
|
+
if (!options.dryRun && host.uid() !== 0)
|
|
239
|
+
throw new DeployError('bootstrap installs packages: run it with sudo (or --dry-run to see what it would do)');
|
|
240
|
+
if ((await host.exec('id', ['-u', user], OUTSIDE)).code !== 0)
|
|
241
|
+
throw new DeployError(`no user ${user} on this server: adduser ${user} first`);
|
|
242
|
+
const problem = await checkoutProblem(host, dir);
|
|
243
|
+
if (problem)
|
|
244
|
+
throw new DeployError(`--dir: ${problem} — refused, nothing was done`);
|
|
245
|
+
host.out.step(`bootstrap${options.dryRun ? ' — dry run, nothing below runs' : ''}`);
|
|
246
|
+
const locked = lockedDeployVersion((await readCheckoutFile(host, join(dir, 'pnpm-lock.yaml'), LOCKFILE_BYTES)) ?? '');
|
|
247
|
+
if (tool && locked && locked !== tool)
|
|
248
|
+
host.out.warn(`this is @basaltkit/deploy ${tool}; the lockfile records ${locked} — run the version the app deploys with (npx --package=@basaltkit/deploy@${locked})`);
|
|
249
|
+
const system = await planSystem(host, dir, user);
|
|
250
|
+
const steps = userSteps(user, dir, host.interactive());
|
|
251
|
+
await runActions(host, [...system.actions, ...steps], options.dryRun);
|
|
252
|
+
if (options.dryRun) {
|
|
253
|
+
const { actions, notes } = await planBootstrap(host, dir, options);
|
|
254
|
+
await runActions(host, actions.slice(system.actions.length + steps.length), true);
|
|
255
|
+
host.out.info(`(phase 3 above assumes proxy ${options.proxy ?? 'none'}: a real run takes it from the install plan)`);
|
|
256
|
+
for (const note of notes)
|
|
257
|
+
host.out.warn(note);
|
|
258
|
+
return 0;
|
|
259
|
+
}
|
|
260
|
+
// The plan comes back as data; root parses and validates it, never runs it.
|
|
261
|
+
const command = planCommand(user);
|
|
262
|
+
host.out.info(`as ${user}: the install plan\n + ${command.join(' ')}`);
|
|
263
|
+
const written = await host.exec(command[0], command.slice(1), { cwd: dir });
|
|
264
|
+
if (written.code !== 0)
|
|
265
|
+
throw new DeployError(`install-plan as ${user} failed (exit ${written.code}): ${written.stderr.trim().split('\n').slice(-3).join(' ')}`);
|
|
266
|
+
const plan = parseInstallPlan(written.stdout, `the install plan from ${user}`);
|
|
267
|
+
if (plan.dir !== dir)
|
|
268
|
+
throw new DeployError(`the install plan names ${plan.dir}, not ${dir} — refused`);
|
|
269
|
+
const server = await planServer(host, {
|
|
270
|
+
proxy: options.proxy ?? plan.proxy.kind,
|
|
271
|
+
swapGb: options.swapGb ?? plan.bootstrap?.swapGb ?? 4,
|
|
272
|
+
firewall: options.firewall ?? plan.bootstrap?.firewall ?? true,
|
|
273
|
+
});
|
|
274
|
+
await runActions(host, server.actions, false);
|
|
275
|
+
await install(host, plan, user);
|
|
276
|
+
for (const note of [...system.notes, ...server.notes])
|
|
144
277
|
host.out.warn(note);
|
|
145
|
-
|
|
146
|
-
host.out.ok(`server ready — from now on, as ${options.user} in ${dir}: node node_modules/@basaltkit/deploy/dist/bin.js run`);
|
|
278
|
+
host.out.ok(`server ready — from now on, as ${user} in ${dir}: node ${BIN} run`);
|
|
147
279
|
return 0;
|
|
148
280
|
}
|
package/dist/caddy.js
CHANGED
|
@@ -24,7 +24,8 @@ export function renderSite(ctx, port) {
|
|
|
24
24
|
const tls = proxy.onDemandTls ? '\n\ttls {\n\t\ton_demand\n\t}\n' : '';
|
|
25
25
|
return `# Written by basalt-deploy install for "${app}". Deploys compare this file with
|
|
26
26
|
# what install would write and print the difference; they never rewrite it.
|
|
27
|
-
# To change it: edit deploy.config.ts,
|
|
27
|
+
# To change it: edit deploy.config.ts, run ${INSTALL_COMMAND}
|
|
28
|
+
# as the app user, then the root command it prints.
|
|
28
29
|
|
|
29
30
|
${hosts} {${tls}
|
|
30
31
|
\tencode gzip
|