@basaltkit/deploy 0.4.0 → 0.5.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +276 -23
  2. package/dist/answers.d.ts +70 -0
  3. package/dist/answers.js +196 -0
  4. package/dist/apache.js +11 -2
  5. package/dist/audit.d.ts +20 -0
  6. package/dist/audit.js +26 -0
  7. package/dist/backup.d.ts +17 -1
  8. package/dist/backup.js +49 -1
  9. package/dist/bin.js +9 -1
  10. package/dist/bootstrap.d.ts +68 -18
  11. package/dist/bootstrap.js +177 -45
  12. package/dist/caddy.js +2 -1
  13. package/dist/check.js +18 -5
  14. package/dist/checks.js +1 -1
  15. package/dist/cli.d.ts +22 -1
  16. package/dist/cli.js +498 -57
  17. package/dist/compose.d.ts +1 -1
  18. package/dist/compose.js +18 -1
  19. package/dist/config.d.ts +25 -2
  20. package/dist/config.js +65 -3
  21. package/dist/context.d.ts +43 -13
  22. package/dist/context.js +50 -7
  23. package/dist/detach.d.ts +23 -0
  24. package/dist/detach.js +105 -0
  25. package/dist/env-step.d.ts +16 -1
  26. package/dist/env-step.js +58 -5
  27. package/dist/events.d.ts +168 -0
  28. package/dist/events.js +477 -0
  29. package/dist/host.d.ts +171 -7
  30. package/dist/host.js +302 -41
  31. package/dist/index.d.ts +10 -5
  32. package/dist/index.js +7 -3
  33. package/dist/init.d.ts +2 -0
  34. package/dist/init.js +2 -1
  35. package/dist/install-plan.d.ts +40 -0
  36. package/dist/install-plan.js +433 -0
  37. package/dist/json-host.d.ts +32 -0
  38. package/dist/json-host.js +106 -0
  39. package/dist/lock.d.ts +45 -0
  40. package/dist/lock.js +128 -0
  41. package/dist/pipeline.d.ts +51 -3
  42. package/dist/pipeline.js +339 -173
  43. package/dist/protocol.d.ts +364 -0
  44. package/dist/protocol.js +134 -0
  45. package/dist/runs.d.ts +75 -0
  46. package/dist/runs.js +287 -0
  47. package/dist/state.d.ts +26 -13
  48. package/dist/state.js +68 -4
  49. package/dist/trust.d.ts +63 -0
  50. package/dist/trust.js +159 -0
  51. package/dist/version.d.ts +2 -0
  52. package/dist/version.js +10 -0
  53. package/package.json +5 -1
@@ -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,58 @@ 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
+ if (!ctx.config.backup?.dir) {
51
+ const legacy = join(ctx.dir, 'backups', 'predeploy');
52
+ const left = (await host.list(legacy)).filter((name) => name.endsWith('.dump'));
53
+ if (left.length > 0) {
54
+ 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 (mv ${legacy}/*.dump ${dir}/) or delete them` });
55
+ }
56
+ }
57
+ return findings;
58
+ }
15
59
  export async function backupDatabase(ctx, values, infra, sha) {
16
60
  const { host, config } = ctx;
17
- const dir = join(ctx.dir, config.backup?.dir ?? 'backups/predeploy');
61
+ const dir = backupDir(ctx);
18
62
  await host.mkdir(dir, 0o700);
63
+ // A directory made earlier with a looser mode: every dump is the whole database.
64
+ const made = await host.stat(dir);
65
+ if (made?.kind === 'dir' && made.uid === host.uid() && made.mode !== undefined && (made.mode & 0o077) !== 0)
66
+ await host.chmod(dir, 0o700);
19
67
  const stamp = host.now().toISOString().replace(/[-:]/g, '').replace(/\..+$/, '');
20
68
  const file = join(dir, `${stamp}-${sha.slice(0, 7)}.dump`);
21
69
  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
- process.exit(await main(process.argv.slice(2)));
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);
@@ -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. Installs only what is missing, then hands over to the app user:
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 · the pnpm the
7
- * lockfile records · swap (< 6 GB RAM) · ufw (only when nothing but SSH
8
- * listens) · Caddy (proxy: caddy) · the checkout and the docker group for
9
- * the user · then, as the user, `pnpm install` and `env`, and as root,
10
- * `install`.
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
- * It needs no node_modules and no loaded config: it runs before either exists
13
- * (`sudo npx -y -p @basaltkit/deploy basalt-deploy bootstrap --user=<u>`), so it
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
- proxy: 'apache' | 'caddy' | 'none';
21
- swapGb: number;
22
- firewall: boolean;
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
- /** What a fresh server needs, given what is already there. Pure planning: it runs probes, never changes anything. */
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
- export declare function bootstrap(host: Host, dir: string, options: BootstrapOptions): Promise<number>;
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
- /** What a fresh server needs, given what is already there. Pure planning: it runs probes, never changes anything. */
8
- export async function planBootstrap(host, dir, options) {
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
- const sh = (script) => ['sh', '-c', script];
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.readFile(join(dir, 'package.json'))) ?? '{}');
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.readFile(join(dir, 'pnpm-lock.yaml'));
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 owner = (await host.exec('stat', ['-c', '%U', dir], OUTSIDE)).stdout.trim();
101
- if (owner !== user)
102
- actions.push({ what: `${dir} owned by ${user}`, commands: [['chown', '-R', `${user}:`, dir]] });
103
- const groups = (await host.exec('id', ['-nG', user], OUTSIDE)).stdout.split(/\s+/);
104
- if (!groups.includes('docker')) {
105
- // §11.2: the docker group, said plainly — rootless Docker is its own phase.
106
- actions.push({ what: `${user} in the docker group`, commands: [['usermod', '-aG', 'docker', user]] });
107
- 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.`);
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
- actions.push({ what: 'install (root): state directory, the proxy site, env ownership', commands: [['sh', '-c', `cd '${dir}' && node node_modules/@basaltkit/deploy/dist/bin.js install --user=${user}`]] });
119
- return { actions, notes };
204
+ notes: [...system.notes, ...server.notes],
205
+ };
120
206
  }
121
- export async function bootstrap(host, dir, options) {
122
- if (!options.user || options.user === 'root')
123
- throw new DeployError('bootstrap needs the unprivileged user the deploys will run as: --user=<name> (never root)');
124
- if (!options.dryRun && host.uid() !== 0)
125
- throw new DeployError('bootstrap installs packages: run it with sudo (or --dry-run to see what it would do)');
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 (options.dryRun)
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), { stream: true });
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 (!options.dryRun)
228
+ if (!dryRun && action.commands.length)
141
229
  host.out.ok(action.what);
142
230
  }
143
- for (const note of notes)
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
- if (!options.dryRun)
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, then sudo basalt-deploy install.
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
package/dist/check.js CHANGED
@@ -9,17 +9,30 @@ import { isAbsolute, join, resolve } from 'node:path';
9
9
  * `src/` only still gets its deploy config checked.
10
10
  */
11
11
  export async function check(host, dir, file, config) {
12
- host.out.step('check');
12
+ const started = host.now().getTime();
13
+ let types;
14
+ try {
15
+ types = await checkTypes(host, dir, file, config);
16
+ }
17
+ finally {
18
+ // Every step that starts ends, also when checkTypes throws (a read-only checkout).
19
+ host.out.stepEnd?.('check', types === undefined || types === 'failed' ? 'failed' : 'ok', host.now().getTime() - started);
20
+ }
21
+ host.out.result?.('check', { file, app: config.app, runtime: config.runtime.kind, ...(config.proxy ? { proxy: config.proxy.kind } : {}), types });
22
+ return types === 'failed' ? 1 : 0;
23
+ }
24
+ async function checkTypes(host, dir, file, config) {
25
+ host.out.step('check', 'check');
13
26
  host.out.ok(`${file}: valid for ${config.app} (${config.runtime.kind}${config.proxy ? `, ${config.proxy.kind}` : ''})`);
14
27
  const path = isAbsolute(file) ? file : resolve(dir, file);
15
28
  if (!/\.[cm]?ts$/.test(path)) {
16
29
  host.out.info('not TypeScript: no types to check');
17
- return 0;
30
+ return 'not-typescript';
18
31
  }
19
32
  const tsc = join(dir, 'node_modules', '.bin', 'tsc');
20
33
  if (!(await host.stat(tsc))) {
21
34
  host.out.warn(`types not checked: no ${tsc} (add typescript to the app's devDependencies)`);
22
- return 0;
35
+ return 'no-tsc';
23
36
  }
24
37
  const base = join(dir, 'tsconfig.json');
25
38
  const project = {
@@ -41,12 +54,12 @@ export async function check(host, dir, file, config) {
41
54
  const result = await host.exec(tsc, ['-p', tsconfig, '--pretty', 'false'], { cwd: dir });
42
55
  if (result.code === 0) {
43
56
  host.out.ok(`${file}: types check`);
44
- return 0;
57
+ return 'ok';
45
58
  }
46
59
  const errors = `${result.stdout}${result.stderr}`.trim().split('\n').filter(Boolean);
47
60
  for (const line of errors)
48
61
  host.out.error(line.startsWith(dir) ? line.slice(dir.length + 1) : line);
49
- return 1;
62
+ return 'failed';
50
63
  }
51
64
  finally {
52
65
  await host.remove(tsconfig);
package/dist/checks.js CHANGED
@@ -40,7 +40,7 @@ export async function tlsFindings(ctx) {
40
40
  ...(name === config.domain ? {} : { fix: `issue a wildcard: certbot certonly --dns-cloudflare -d ${config.domain} -d '*.${config.domain}', and make *.${config.domain} DNS-only` }),
41
41
  });
42
42
  }
43
- else if (!cert.trusted) {
43
+ if (!cert.trusted) {
44
44
  findings.push({ id: 'C8', level: 'warning', message: `the certificate served for ${label} is not trusted by browsers (${cert.trustError ?? 'unknown reason'}) — a Cloudflare Origin certificate behind a DNS-only record?` });
45
45
  }
46
46
  const days = Math.floor((cert.validTo.getTime() - host.now().getTime()) / 86_400_000);