@basaltkit/deploy 0.1.2 → 0.1.4

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 CHANGED
@@ -51,15 +51,21 @@ What is true of one server only (a port taken there, another branch) goes in
51
51
  ```sh
52
52
  # as the app user (never root), in the checkout:
53
53
  pnpm install
54
- pnpm exec basalt-deploy env # writes the .env (asks once), starts the containers, validates
54
+ node node_modules/@basaltkit/deploy/dist/bin.js env # writes the .env (asks once), starts the containers, validates
55
55
 
56
- # once, as an administrator (node on the file: root often has no pnpm on its PATH):
57
- sudo node node_modules/@basaltkit/deploy/dist/bin.js install --user=<app user> # Apache vhost, /var/lib/basalt/<app>
56
+ # once, as an administrator — the node path is resolved by YOUR shell, because
57
+ # with a per-user Node (nvm) root has none on its PATH:
58
+ sudo "$(command -v node)" node_modules/@basaltkit/deploy/dist/bin.js install --user="$USER"
58
59
 
59
60
  # then, every deploy, as the app user:
60
- pnpm exec basalt-deploy run
61
+ node node_modules/@basaltkit/deploy/dist/bin.js run
61
62
  ```
62
63
 
64
+ Wrap it in a two-line `deploy.sh` if you like. Run it with `node`, not
65
+ `pnpm exec basalt-deploy`: pnpm ≥ 12 rewrites `pnpm-lock.yaml` on any command
66
+ in the checkout when the lockfile came from another pnpm, and the deploy
67
+ refuses a modified tree.
68
+
63
69
  `run` pulls the code itself. Store the git credentials once
64
70
  (`git config credential.helper store && git fetch`, or a read-only deploy key):
65
71
  preflight probes the remote with prompts disabled, warns at a terminal and
@@ -104,7 +110,7 @@ incident (RFC 0006 §5):
104
110
  - **C8** stay silent about a certificate that does not cover the apex or a tenant host;
105
111
  - **C9** run with a package manager major other than the one `packageManager` declares;
106
112
  - **C10** keep a forbidden key, or a fixed key with another value.
107
- - **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.
113
+ - **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.
108
114
 
109
115
  Secrets never reach a command line, the compose file, or the terminal: the
110
116
  summary names keys, passwords travel in child-process environments only.
package/dist/checks.js CHANGED
@@ -1,3 +1,4 @@
1
+ import { tmpdir } from 'node:os';
1
2
  import { join } from 'node:path';
2
3
  /** Whether a certificate name (`*.example.com` or exact) covers `host`. Wildcards cover one label only. */
3
4
  export function covers(name, host) {
@@ -59,6 +60,14 @@ const below = (version, minimum) => {
59
60
  }
60
61
  return false;
61
62
  };
63
+ /**
64
+ * Version probes run OUTSIDE the checkout. Inside it, pnpm ≥ 12 reads
65
+ * `packageManager` and may rewrite `pnpm-lock.yaml` on any command — a
66
+ * check must never change the repository it checks (it then failed the
67
+ * deploy's own dirty check). Outside it, the answer is also the right one:
68
+ * the pnpm actually installed, not the one `packageManager` would fetch.
69
+ */
70
+ const OUTSIDE = { cwd: tmpdir() };
62
71
  /** C9 — the toolchain the pipeline will call, before it calls it. */
63
72
  export async function toolingFindings(ctx) {
64
73
  const { host } = ctx;
@@ -70,7 +79,7 @@ export async function toolingFindings(ctx) {
70
79
  catch {
71
80
  findings.push({ id: 'C9', level: 'error', message: 'package.json is not valid JSON' });
72
81
  }
73
- const node = await host.exec('node', ['--version']);
82
+ const node = await host.exec('node', ['--version'], OUTSIDE);
74
83
  const nodeVersion = minimumVersion(node.stdout);
75
84
  const nodeMinimum = minimumVersion(pkg.engines?.node);
76
85
  if (!nodeVersion)
@@ -78,7 +87,7 @@ export async function toolingFindings(ctx) {
78
87
  else if (nodeMinimum && below(nodeVersion, nodeMinimum)) {
79
88
  findings.push({ id: 'C9', level: 'error', message: `node ${node.stdout.trim()} is older than engines.node (${pkg.engines?.node})` });
80
89
  }
81
- const pm = await host.exec(ctx.pm, ['--version']);
90
+ const pm = await host.exec(ctx.pm, ['--version'], OUTSIDE);
82
91
  if (pm.code !== 0) {
83
92
  findings.push({ id: 'C9', level: 'error', message: `${ctx.pm} is not on PATH`, fix: 'corepack enable' });
84
93
  }
@@ -91,7 +100,7 @@ export async function toolingFindings(ctx) {
91
100
  }
92
101
  }
93
102
  if (ctx.config.infra?.kind === 'docker') {
94
- const docker = await host.exec('docker', ['compose', 'version']);
103
+ const docker = await host.exec('docker', ['compose', 'version'], OUTSIDE);
95
104
  if (docker.code !== 0)
96
105
  findings.push({ id: 'C9', level: 'error', message: 'docker compose is not available to this user' });
97
106
  }
package/dist/cli.js CHANGED
@@ -12,9 +12,12 @@ export const USAGE = `basalt-deploy — deploy this Basalt app on this server (R
12
12
  basalt-deploy env the .env and the dedicated infra only (first setup)
13
13
  basalt-deploy rollback [--to=<sha>] back to the last healthy release (code only)
14
14
  basalt-deploy status the last releases and the process
15
- sudo node node_modules/@basaltkit/deploy/dist/bin.js install --user=<name>
15
+ sudo "$(command -v node)" node_modules/@basaltkit/deploy/dist/bin.js install --user=<name>
16
16
  once per server, as root: vhost, state directory
17
17
 
18
+ Run it as \`node node_modules/@basaltkit/deploy/dist/bin.js <command>\`, not
19
+ \`pnpm exec\`: pnpm ≥ 12 may rewrite pnpm-lock.yaml on any command it runs.
20
+
18
21
  Options:
19
22
  --config=<file> default deploy.config.ts
20
23
  --overrides=<file> server-local values, default /etc/basalt/<app>.json
package/dist/context.d.ts CHANGED
@@ -20,10 +20,18 @@ export interface Finding {
20
20
  fix?: string;
21
21
  }
22
22
  /**
23
- * How an administrator runs `install`. `node` on the file, not `pnpm exec`:
24
- * root often has no pnpm on its PATH (a per-user install, corepack).
23
+ * How the app user runs the deploy. Not `pnpm exec`: pnpm ≥ 12 rewrites
24
+ * `pnpm-lock.yaml` on any command in the checkout when the lockfile came from
25
+ * another pnpm, and the deploy then refuses its own dirty tree.
25
26
  */
26
- export declare const INSTALL_COMMAND = "sudo node node_modules/@basaltkit/deploy/dist/bin.js install --user=\"$USER\"";
27
+ export declare const RUN_COMMAND = "node node_modules/@basaltkit/deploy/dist/bin.js run";
28
+ /**
29
+ * How an administrator runs `install`. The node binary is resolved by the
30
+ * operator's shell BEFORE sudo: with a per-user Node (nvm, fnm, volta) root
31
+ * has no `node` on its PATH — `sudo node` failed with "command not found" on
32
+ * the first server. Not `pnpm exec` either: root often has no pnpm.
33
+ */
34
+ export declare const INSTALL_COMMAND = "sudo \"$(command -v node)\" node_modules/@basaltkit/deploy/dist/bin.js install --user=\"$USER\"";
27
35
  export declare const errors: (findings: Finding[]) => Finding[];
28
36
  export declare function report(host: Host, findings: Finding[]): void;
29
37
  export declare function detectPackageManager(host: Host, dir: string): Promise<DeployContext['pm']>;
package/dist/context.js CHANGED
@@ -1,9 +1,19 @@
1
1
  import { join } from 'node:path';
2
+ /** The tool, run by `node` on its file — never `pnpm exec` (see {@link RUN_COMMAND}). */
3
+ const BIN = 'node_modules/@basaltkit/deploy/dist/bin.js';
2
4
  /**
3
- * How an administrator runs `install`. `node` on the file, not `pnpm exec`:
4
- * root often has no pnpm on its PATH (a per-user install, corepack).
5
+ * How the app user runs the deploy. Not `pnpm exec`: pnpm ≥ 12 rewrites
6
+ * `pnpm-lock.yaml` on any command in the checkout when the lockfile came from
7
+ * another pnpm, and the deploy then refuses its own dirty tree.
5
8
  */
6
- export const INSTALL_COMMAND = 'sudo node node_modules/@basaltkit/deploy/dist/bin.js install --user="$USER"';
9
+ export const RUN_COMMAND = `node ${BIN} run`;
10
+ /**
11
+ * How an administrator runs `install`. The node binary is resolved by the
12
+ * operator's shell BEFORE sudo: with a per-user Node (nvm, fnm, volta) root
13
+ * has no `node` on its PATH — `sudo node` failed with "command not found" on
14
+ * the first server. Not `pnpm exec` either: root often has no pnpm.
15
+ */
16
+ export const INSTALL_COMMAND = `sudo "$(command -v node)" ${BIN} install --user="$USER"`;
7
17
  export const errors = (findings) => findings.filter((f) => f.level === 'error');
8
18
  export function report(host, findings) {
9
19
  for (const finding of findings) {
package/dist/pipeline.js CHANGED
@@ -3,7 +3,7 @@ import { apacheInstall, apachePreflight, vhostPaths } from './apache.js';
3
3
  import { backupDatabase, restoreCommand } from './backup.js';
4
4
  import { lockfileFindings, tlsFindings, toolingFindings } from './checks.js';
5
5
  import { processName } from './config.js';
6
- import { DeployError, errors, INSTALL_COMMAND, report } from './context.js';
6
+ import { DeployError, errors, INSTALL_COMMAND, report, RUN_COMMAND } from './context.js';
7
7
  import { checkSchema, coercionFindings, policyFindings } from './env-check.js';
8
8
  import { answerQuestions, describeEnv, planEnv, readEnv, syntaxFindings, writeEnv } from './env-step.js';
9
9
  import { envValues } from './dotenv.js';
@@ -27,9 +27,12 @@ async function step(ctx, title, run) {
27
27
  return run();
28
28
  }
29
29
  export async function preflight(ctx, options = {}) {
30
+ // First, before any command runs: the tree as the operator left it. A
31
+ // later probe that writes to the checkout would otherwise be blamed on them.
32
+ const findings = [...await gitFindings(ctx, options)];
30
33
  const document = await readEnv(ctx);
31
34
  const values = envValues(document);
32
- const findings = [...syntaxFindings(document, ctx.config.env.file ?? '.env')];
35
+ findings.push(...syntaxFindings(document, ctx.config.env.file ?? '.env'));
33
36
  const port = await resolvePort(ctx, values);
34
37
  findings.push(...await toolingFindings(ctx));
35
38
  findings.push(...await lockfileFindings(ctx));
@@ -38,22 +41,33 @@ export async function preflight(ctx, options = {}) {
38
41
  findings.push(...await apachePreflight(ctx, port));
39
42
  if (!options.skip?.includes('tls'))
40
43
  findings.push(...await tlsFindings(ctx));
44
+ return { findings, port, values };
45
+ }
46
+ const LOCKFILES = ['pnpm-lock.yaml', 'package-lock.json', 'yarn.lock', 'bun.lock'];
47
+ async function gitFindings(ctx, options) {
48
+ const findings = [];
41
49
  const dirty = await ctx.host.exec('git', ['status', '--porcelain', '--untracked-files=no'], { cwd: ctx.dir });
42
- if (dirty.code !== 0) {
43
- findings.push({ id: 'git', level: 'error', message: `${ctx.dir} is not a git checkout` });
44
- }
45
- else {
46
- if (dirty.stdout.trim()) {
47
- findings.push({ id: 'git', level: 'error', message: `tracked files are modified on the server:\n${dirty.stdout.trimEnd().split('\n').map((l) => ` ${l}`).join('\n')}`, fix: 'git stash (or commit them where they belong); a deploy builds what is committed' });
48
- }
49
- const branch = (await ctx.host.exec('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: ctx.dir })).stdout.trim();
50
- const wanted = ctx.config.branch ?? 'main';
51
- if (branch !== wanted)
52
- findings.push({ id: 'git', level: 'error', message: `the checkout is on "${branch}", the deploy tracks "${wanted}"`, fix: `git checkout ${wanted}` });
53
- if (!options.skip?.includes('fetch'))
54
- findings.push(...await remoteFindings(ctx));
50
+ if (dirty.code !== 0)
51
+ return [{ id: 'git', level: 'error', message: `${ctx.dir} is not a git checkout` }];
52
+ const changed = dirty.stdout.split('\n').map((l) => l.trimEnd()).filter(Boolean);
53
+ if (changed.length > 0) {
54
+ const onlyLockfile = changed.every((l) => LOCKFILES.includes(l.slice(3)));
55
+ findings.push({
56
+ id: 'git',
57
+ level: 'error',
58
+ message: `tracked files are modified on the server:\n${changed.map((l) => ` ${l}`).join('\n')}`,
59
+ fix: onlyLockfile
60
+ ? 'only the lockfile — most likely rewritten by the package manager, not by a person: git checkout -- ' + changed.map((l) => l.slice(3)).join(' ') + ', and commit a lockfile written by the same pnpm as this server'
61
+ : 'git stash (or commit them where they belong); a deploy builds what is committed',
62
+ });
55
63
  }
56
- return { findings, port, values };
64
+ const branch = (await ctx.host.exec('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: ctx.dir })).stdout.trim();
65
+ const wanted = ctx.config.branch ?? 'main';
66
+ if (branch !== wanted)
67
+ findings.push({ id: 'git', level: 'error', message: `the checkout is on "${branch}", the deploy tracks "${wanted}"`, fix: `git checkout ${wanted}` });
68
+ if (!options.skip?.includes('fetch'))
69
+ findings.push(...await remoteFindings(ctx));
70
+ return findings;
57
71
  }
58
72
  const CREDENTIALS = /terminal prompts disabled|could not read (Username|Password)|Authentication failed|Permission denied \(publickey|Host key verification failed|Invalid username or (password|token)/i;
59
73
  /** Can the fetch reach the branch without asking anyone for anything? */
@@ -135,6 +149,30 @@ async function build(ctx, values) {
135
149
  if (ctx.config.build?.web)
136
150
  await run(['--dir', ctx.config.build.web, 'run', 'build'], { env: values });
137
151
  }
152
+ /**
153
+ * The deploy leaves the checkout as committed. pnpm ≥ 12 may rewrite the
154
+ * lockfile's `packageManagerDependencies` during `exec`/`run` when the
155
+ * committed one was written by another pnpm; left there, it blocked the
156
+ * NEXT deploy's dirty check. Put back, and said — the fix belongs in the
157
+ * repository, not on the server.
158
+ */
159
+ async function settleLockfile(ctx, said) {
160
+ const status = await ctx.host.exec('git', ['status', '--porcelain', '--untracked-files=no', '--', ...LOCKFILES], { cwd: ctx.dir });
161
+ const rewritten = status.stdout.split('\n').map((l) => l.slice(3).trim()).filter(Boolean);
162
+ if (status.code !== 0 || rewritten.length === 0)
163
+ return;
164
+ await git(ctx, ['checkout', '--', ...rewritten]);
165
+ if (said?.warned)
166
+ return;
167
+ if (said)
168
+ said.warned = true;
169
+ report(ctx.host, [{
170
+ id: 'C11',
171
+ level: 'warning',
172
+ message: `${ctx.pm} rewrote ${rewritten.join(', ')} during the deploy; put back to the committed version`,
173
+ fix: `regenerate it with the ${ctx.pm} this server runs (${ctx.pm} install --lockfile-only) and commit it, or every deploy rewrites it`,
174
+ }]);
175
+ }
138
176
  async function validate(ctx, values) {
139
177
  const schema = await checkSchema(ctx, values);
140
178
  return [...schema.findings, ...coercionFindings(values, schema.trueKeys), ...policyFindings(ctx, values)];
@@ -191,6 +229,7 @@ async function restoreCode(ctx, sha, values) {
191
229
  ctx.host.out.step(`restoring the code to ${sha.slice(0, 7)}`);
192
230
  await git(ctx, ['reset', '--hard', sha]);
193
231
  await build(ctx, values);
232
+ await settleLockfile(ctx);
194
233
  }
195
234
  /** The env step's summary: what changed, or that nothing did. */
196
235
  function reportEnv(ctx, plan) {
@@ -272,6 +311,7 @@ export async function run(ctx, options = {}) {
272
311
  const applied = sha === previous ? [] : migrationNames((await git(ctx, ['diff', '--name-only', previous, sha])).split('\n'));
273
312
  const release = { sha, previous, at: host.now().toISOString(), user: host.env['USER'] ?? String(host.uid()), status: 'failed', migrations: applied };
274
313
  // From here a failure puts the code on disk back before it is reported.
314
+ const lockfileSaid = { warned: false };
275
315
  let values = checked.values;
276
316
  let infra = { services: [], env: [], findings: [], secrets: {} };
277
317
  try {
@@ -288,7 +328,7 @@ export async function run(ctx, options = {}) {
288
328
  await writeEnv(ctx, prepared.env);
289
329
  values = prepared.env.values;
290
330
  await step(ctx, 'infra', () => infraStep(ctx, infra));
291
- await step(ctx, 'build', () => build(ctx, values));
331
+ await step(ctx, 'build', async () => { await build(ctx, values); await settleLockfile(ctx, lockfileSaid); });
292
332
  await step(ctx, 'validate', () => validateStep(ctx, values));
293
333
  const backup = backupDecision(config, values, skip);
294
334
  if (backup.run) {
@@ -299,7 +339,7 @@ export async function run(ctx, options = {}) {
299
339
  host.out.step('backup');
300
340
  host.out.info(`skipped: ${backup.why}`);
301
341
  }
302
- await step(ctx, 'migrate', () => migrate(ctx, values));
342
+ await step(ctx, 'migrate', async () => { await migrate(ctx, values); await settleLockfile(ctx, lockfileSaid); });
303
343
  }
304
344
  catch (error) {
305
345
  if (sha !== previous)
@@ -338,6 +378,8 @@ export async function run(ctx, options = {}) {
338
378
  host.out.ok(`http://127.0.0.1:${port}${config.health?.path ?? '/health'}`);
339
379
  const publicProblem = await publicHealthy(ctx);
340
380
  release.status = publicProblem ? 'public-unreachable' : 'ok';
381
+ // `pnpm run start`, launched by PM2 in the checkout, may rewrite it too.
382
+ await settleLockfile(ctx, lockfileSaid);
341
383
  await step(ctx, 'record', () => recordRelease(ctx, release));
342
384
  if (publicProblem) {
343
385
  report(host, [publicProblem]);
@@ -403,20 +445,37 @@ export async function install(ctx, user) {
403
445
  throw new DeployError('install needs the unprivileged user the deploys run as: --user=<name> (never root)');
404
446
  const port = Number(envValues(await readEnv(ctx)).get('PORT'));
405
447
  if (!Number.isInteger(port) || port <= 0)
406
- throw new DeployError('no PORT in the .env yet: run `pnpm exec basalt-deploy env` as the app user first');
448
+ throw new DeployError(`no PORT in the .env yet: run \`${RUN_COMMAND.replace(/ run$/, ' env')}\` as the app user first`);
407
449
  const stateDir = `/var/lib/basalt/${config.app}`;
408
450
  await step(ctx, `state directory ${stateDir}`, async () => {
409
451
  await host.mkdir(stateDir, 0o700);
410
452
  await host.mkdir(join(stateDir, 'install-backups'), 0o700);
411
453
  const local = await host.readFile(join(ctx.dir, '.basalt', 'releases.json'));
412
- if (local && !(await host.exists(join(stateDir, 'releases.json'))))
413
- await host.writeFile(join(stateDir, 'releases.json'), local, 0o600);
454
+ const target = join(stateDir, 'releases.json');
455
+ let history = 'no release history yet';
456
+ if (await host.exists(target)) {
457
+ history = 'release history kept as it was';
458
+ }
459
+ else if (local) {
460
+ await host.writeFile(target, local, 0o600);
461
+ const count = (() => { try {
462
+ const v = JSON.parse(local);
463
+ return Array.isArray(v) ? v.length : 0;
464
+ }
465
+ catch {
466
+ return 0;
467
+ } })();
468
+ history = `${count} release(s) copied from ${join(ctx.dir, '.basalt', 'releases.json')}`;
469
+ }
414
470
  const chown = await host.exec('chown', ['-R', `${user}:`, stateDir]);
415
471
  if (chown.code !== 0)
416
472
  throw new DeployError(`chown ${user} ${stateDir}: ${chown.stderr.trim()}`);
417
- if (!(await host.exists(`/etc/basalt/${config.app}.json`))) {
473
+ host.out.ok(`${stateDir} (0700, owned by ${user}); ${history}`);
474
+ const overrides = `/etc/basalt/${config.app}.json`;
475
+ if (!(await host.exists(overrides))) {
418
476
  await host.mkdir('/etc/basalt', 0o755);
419
- await host.writeFile(`/etc/basalt/${config.app}.json`, '{}\n', 0o644);
477
+ await host.writeFile(overrides, '{}\n', 0o644);
478
+ host.out.ok(`${overrides} created (server-local overrides, no secrets)`);
420
479
  }
421
480
  });
422
481
  if (config.proxy?.kind === 'apache') {
@@ -431,6 +490,6 @@ export async function install(ctx, user) {
431
490
  host.out.info(`dedicated infra runs under ${user}'s rootless Docker: dockerd-rootless-setuptool.sh install (as ${user}), then loginctl enable-linger ${user}`);
432
491
  }
433
492
  }
434
- host.out.ok(`installed — from now on, as ${user}: pnpm exec basalt-deploy run`);
493
+ host.out.ok(`installed — from now on, as ${user} (not root), in ${ctx.dir}: ${RUN_COMMAND}`);
435
494
  return 0;
436
495
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/deploy",
3
- "version": "0.1.2",
3
+ "version": "0.1.4",
4
4
  "engines": {
5
5
  "node": ">=22.5.0"
6
6
  },