@basaltkit/deploy 0.1.1 → 0.1.3

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
@@ -104,6 +104,7 @@ incident (RFC 0006 §5):
104
104
  - **C8** stay silent about a certificate that does not cover the apex or a tenant host;
105
105
  - **C9** run with a package manager major other than the one `packageManager` declares;
106
106
  - **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. 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.
107
108
 
108
109
  Secrets never reach a command line, the compose file, or the terminal: the
109
110
  summary names keys, passwords travel in child-process environments only.
package/dist/checks.d.ts CHANGED
@@ -11,3 +11,17 @@ export declare function covers(name: string, host: string): boolean;
11
11
  export declare function tlsFindings(ctx: DeployContext): Promise<Finding[]>;
12
12
  /** C9 — the toolchain the pipeline will call, before it calls it. */
13
13
  export declare function toolingFindings(ctx: DeployContext): Promise<Finding[]>;
14
+ /** The pnpm version the lockfile records for `packageManager` (`packageManagerDependencies`), if any. */
15
+ export declare function lockedPnpm(lockfile: string): string | undefined;
16
+ /**
17
+ * C11 — a `packageManager` the lockfile does not record. pnpm 12 writes the
18
+ * pnpm it runs as into the lockfile (`packageManagerDependencies`) and its
19
+ * frozen install refuses a lockfile without it, or with another version:
20
+ * ERR_PNPM_FROZEN_LOCKFILE_WITH_OUTDATED_LOCKFILE, half-way through a deploy.
21
+ * It happened twice on the first day: `packageManager: pnpm@12.3.4` was
22
+ * committed with a lockfile written by pnpm 11.
23
+ *
24
+ * Checked when it can bite: pnpm declared at 12 or later, or a lockfile that
25
+ * already records a version (which must then be the declared one).
26
+ */
27
+ export declare function lockfileFindings(ctx: DeployContext): Promise<Finding[]>;
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,9 +100,59 @@ 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
  }
98
107
  return findings;
99
108
  }
109
+ /** The pnpm version the lockfile records for `packageManager` (`packageManagerDependencies`), if any. */
110
+ export function lockedPnpm(lockfile) {
111
+ const at = lockfile.indexOf('packageManagerDependencies:');
112
+ if (at === -1)
113
+ return undefined;
114
+ const match = /\n\s+pnpm:\s*\n\s+specifier:\s*['"]?([^\s'"]+)/.exec(lockfile.slice(at, at + 2000));
115
+ return match?.[1];
116
+ }
117
+ /**
118
+ * C11 — a `packageManager` the lockfile does not record. pnpm 12 writes the
119
+ * pnpm it runs as into the lockfile (`packageManagerDependencies`) and its
120
+ * frozen install refuses a lockfile without it, or with another version:
121
+ * ERR_PNPM_FROZEN_LOCKFILE_WITH_OUTDATED_LOCKFILE, half-way through a deploy.
122
+ * It happened twice on the first day: `packageManager: pnpm@12.3.4` was
123
+ * committed with a lockfile written by pnpm 11.
124
+ *
125
+ * Checked when it can bite: pnpm declared at 12 or later, or a lockfile that
126
+ * already records a version (which must then be the declared one).
127
+ */
128
+ export async function lockfileFindings(ctx) {
129
+ if (ctx.pm !== 'pnpm')
130
+ return [];
131
+ let declared;
132
+ try {
133
+ const pkg = JSON.parse((await ctx.host.readFile(join(ctx.dir, 'package.json'))) ?? '{}');
134
+ const match = /^pnpm@(\d+[^+\s]*)/.exec(pkg.packageManager ?? '');
135
+ declared = match?.[1];
136
+ }
137
+ catch {
138
+ return [];
139
+ }
140
+ if (!declared)
141
+ return [];
142
+ const lockfile = await ctx.host.readFile(join(ctx.dir, 'pnpm-lock.yaml'));
143
+ if (lockfile === undefined)
144
+ return [];
145
+ const locked = lockedPnpm(lockfile);
146
+ if (locked === undefined && Number(declared.split('.')[0]) < 12)
147
+ return [];
148
+ if (locked === declared)
149
+ return [];
150
+ return [{
151
+ id: 'C11',
152
+ level: 'error',
153
+ message: locked === undefined
154
+ ? `package.json declares pnpm@${declared}, but pnpm-lock.yaml does not record it (packageManagerDependencies): pnpm's frozen install will refuse the lockfile`
155
+ : `package.json declares pnpm@${declared}, but pnpm-lock.yaml records pnpm ${locked}: pnpm's frozen install will refuse the lockfile`,
156
+ fix: `run pnpm install --lockfile-only with pnpm ${declared} and commit pnpm-lock.yaml`,
157
+ }];
158
+ }
package/dist/pipeline.js CHANGED
@@ -1,7 +1,7 @@
1
1
  import { join } from 'node:path';
2
2
  import { apacheInstall, apachePreflight, vhostPaths } from './apache.js';
3
3
  import { backupDatabase, restoreCommand } from './backup.js';
4
- import { tlsFindings, toolingFindings } from './checks.js';
4
+ import { lockfileFindings, tlsFindings, toolingFindings } from './checks.js';
5
5
  import { processName } from './config.js';
6
6
  import { DeployError, errors, INSTALL_COMMAND, report } from './context.js';
7
7
  import { checkSchema, coercionFindings, policyFindings } from './env-check.js';
@@ -27,32 +27,47 @@ 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));
38
+ findings.push(...await lockfileFindings(ctx));
35
39
  findings.push(...await pm2Preflight(ctx, port));
36
40
  if (ctx.config.proxy?.kind === 'apache')
37
41
  findings.push(...await apachePreflight(ctx, port));
38
42
  if (!options.skip?.includes('tls'))
39
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 = [];
40
49
  const dirty = await ctx.host.exec('git', ['status', '--porcelain', '--untracked-files=no'], { cwd: ctx.dir });
41
- if (dirty.code !== 0) {
42
- findings.push({ id: 'git', level: 'error', message: `${ctx.dir} is not a git checkout` });
43
- }
44
- else {
45
- if (dirty.stdout.trim()) {
46
- 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' });
47
- }
48
- const branch = (await ctx.host.exec('git', ['rev-parse', '--abbrev-ref', 'HEAD'], { cwd: ctx.dir })).stdout.trim();
49
- const wanted = ctx.config.branch ?? 'main';
50
- if (branch !== wanted)
51
- findings.push({ id: 'git', level: 'error', message: `the checkout is on "${branch}", the deploy tracks "${wanted}"`, fix: `git checkout ${wanted}` });
52
- if (!options.skip?.includes('fetch'))
53
- 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
+ });
54
63
  }
55
- 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;
56
71
  }
57
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;
58
73
  /** Can the fetch reach the branch without asking anyone for anything? */
@@ -134,6 +149,30 @@ async function build(ctx, values) {
134
149
  if (ctx.config.build?.web)
135
150
  await run(['--dir', ctx.config.build.web, 'run', 'build'], { env: values });
136
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
+ }
137
176
  async function validate(ctx, values) {
138
177
  const schema = await checkSchema(ctx, values);
139
178
  return [...schema.findings, ...coercionFindings(values, schema.trueKeys), ...policyFindings(ctx, values)];
@@ -190,6 +229,7 @@ async function restoreCode(ctx, sha, values) {
190
229
  ctx.host.out.step(`restoring the code to ${sha.slice(0, 7)}`);
191
230
  await git(ctx, ['reset', '--hard', sha]);
192
231
  await build(ctx, values);
232
+ await settleLockfile(ctx);
193
233
  }
194
234
  /** The env step's summary: what changed, or that nothing did. */
195
235
  function reportEnv(ctx, plan) {
@@ -271,9 +311,13 @@ export async function run(ctx, options = {}) {
271
311
  const applied = sha === previous ? [] : migrationNames((await git(ctx, ['diff', '--name-only', previous, sha])).split('\n'));
272
312
  const release = { sha, previous, at: host.now().toISOString(), user: host.env['USER'] ?? String(host.uid()), status: 'failed', migrations: applied };
273
313
  // From here a failure puts the code on disk back before it is reported.
314
+ const lockfileSaid = { warned: false };
274
315
  let values = checked.values;
275
316
  let infra = { services: [], env: [], findings: [], secrets: {} };
276
317
  try {
318
+ // Again on the code the fetch brought: preflight saw the commit before it.
319
+ if (sha !== previous)
320
+ stopOnErrors(ctx, await lockfileFindings(ctx), `the incoming commit ${sha.slice(0, 7)}`);
277
321
  const prepared = await step(ctx, 'env', () => prepareEnv(ctx, port));
278
322
  infra = prepared.infra;
279
323
  stopOnErrors(ctx, infra.findings, 'infra');
@@ -284,7 +328,7 @@ export async function run(ctx, options = {}) {
284
328
  await writeEnv(ctx, prepared.env);
285
329
  values = prepared.env.values;
286
330
  await step(ctx, 'infra', () => infraStep(ctx, infra));
287
- await step(ctx, 'build', () => build(ctx, values));
331
+ await step(ctx, 'build', async () => { await build(ctx, values); await settleLockfile(ctx, lockfileSaid); });
288
332
  await step(ctx, 'validate', () => validateStep(ctx, values));
289
333
  const backup = backupDecision(config, values, skip);
290
334
  if (backup.run) {
@@ -295,7 +339,7 @@ export async function run(ctx, options = {}) {
295
339
  host.out.step('backup');
296
340
  host.out.info(`skipped: ${backup.why}`);
297
341
  }
298
- await step(ctx, 'migrate', () => migrate(ctx, values));
342
+ await step(ctx, 'migrate', async () => { await migrate(ctx, values); await settleLockfile(ctx, lockfileSaid); });
299
343
  }
300
344
  catch (error) {
301
345
  if (sha !== previous)
@@ -334,6 +378,8 @@ export async function run(ctx, options = {}) {
334
378
  host.out.ok(`http://127.0.0.1:${port}${config.health?.path ?? '/health'}`);
335
379
  const publicProblem = await publicHealthy(ctx);
336
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);
337
383
  await step(ctx, 'record', () => recordRelease(ctx, release));
338
384
  if (publicProblem) {
339
385
  report(host, [publicProblem]);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@basaltkit/deploy",
3
- "version": "0.1.1",
3
+ "version": "0.1.3",
4
4
  "engines": {
5
5
  "node": ">=22.5.0"
6
6
  },