@basaltkit/deploy 0.0.0-stage → 0.1.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.
@@ -0,0 +1,432 @@
1
+ import { join } from 'node:path';
2
+ import { apacheInstall, apachePreflight, vhostPaths } from './apache.js';
3
+ import { backupDatabase, restoreCommand } from './backup.js';
4
+ import { tlsFindings, toolingFindings } from './checks.js';
5
+ import { processName } from './config.js';
6
+ import { DeployError, errors, INSTALL_COMMAND, report } from './context.js';
7
+ import { checkSchema, coercionFindings, policyFindings } from './env-check.js';
8
+ import { answerQuestions, describeEnv, planEnv, readEnv, syntaxFindings, writeEnv } from './env-step.js';
9
+ import { envValues } from './dotenv.js';
10
+ import { applyInfra, describeInfra, planInfra } from './infra.js';
11
+ import { pm2List, pm2Preflight, pm2Release, resolvePort } from './pm2.js';
12
+ import { lastGood, migrationNames, readReleases, recordRelease } from './state.js';
13
+ export const SKIPPABLE = ['fetch', 'backup', 'tls'];
14
+ /**
15
+ * Never a credential prompt: one in the middle of a deploy hangs cron and CI,
16
+ * and interrupts a person half-way. With nobody to answer, git fails instead.
17
+ */
18
+ const NO_PROMPT = { GIT_TERMINAL_PROMPT: '0', GCM_INTERACTIVE: 'never', GIT_SSH_COMMAND: 'ssh -o BatchMode=yes' };
19
+ async function git(ctx, args, options = {}) {
20
+ const result = await ctx.host.exec('git', args, { cwd: ctx.dir, ...(options.noPrompt ? { env: NO_PROMPT } : {}) });
21
+ if (result.code !== 0)
22
+ throw new DeployError(`git ${args[0]} failed: ${result.stderr.trim()}`);
23
+ return result.stdout.trim();
24
+ }
25
+ async function step(ctx, title, run) {
26
+ ctx.host.out.step(title);
27
+ return run();
28
+ }
29
+ export async function preflight(ctx, options = {}) {
30
+ const document = await readEnv(ctx);
31
+ const values = envValues(document);
32
+ const findings = [...syntaxFindings(document, ctx.config.env.file ?? '.env')];
33
+ const port = await resolvePort(ctx, values);
34
+ findings.push(...await toolingFindings(ctx));
35
+ findings.push(...await pm2Preflight(ctx, port));
36
+ if (ctx.config.proxy?.kind === 'apache')
37
+ findings.push(...await apachePreflight(ctx, port));
38
+ if (!options.skip?.includes('tls'))
39
+ findings.push(...await tlsFindings(ctx));
40
+ 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));
54
+ }
55
+ return { findings, port, values };
56
+ }
57
+ 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
+ /** Can the fetch reach the branch without asking anyone for anything? */
59
+ async function remoteFindings(ctx) {
60
+ const remote = ctx.config.remote ?? 'origin';
61
+ const branch = ctx.config.branch ?? 'main';
62
+ const probe = await ctx.host.exec('git', ['ls-remote', '--exit-code', remote, `refs/heads/${branch}`], { cwd: ctx.dir, env: NO_PROMPT });
63
+ if (probe.code === 0)
64
+ return [];
65
+ if (probe.code === 2)
66
+ return [{ id: 'git', level: 'error', message: `the branch "${branch}" does not exist on ${remote}` }];
67
+ const reason = probe.stderr.trim().split('\n').find((l) => l.trim()) ?? `exit ${probe.code}`;
68
+ if (CREDENTIALS.test(probe.stderr)) {
69
+ const fix = 'store them once: git config credential.helper store && git fetch (or a read-only deploy key and an ssh remote)';
70
+ return ctx.host.interactive()
71
+ ? [{ id: 'git', level: 'warning', message: `${remote} needs credentials: the fetch will ask for them`, fix }]
72
+ : [{ id: 'git', level: 'error', message: `${remote} needs credentials and nobody can type them here (no terminal)`, fix }];
73
+ }
74
+ return [{ id: 'git', level: 'warning', message: `could not reach ${remote}: ${reason}`, fix: '--skip=fetch deploys the code already in the checkout' }];
75
+ }
76
+ function stopOnErrors(ctx, findings, what) {
77
+ report(ctx.host, findings);
78
+ const blocking = errors(findings);
79
+ if (blocking.length > 0)
80
+ throw new DeployError(`${what}: ${blocking.length} problem(s) above — nothing was changed`, blocking);
81
+ }
82
+ // ── what runs by default ───────────────────────────────────────────────────
83
+ /** `prisma migrate deploy` runs when asked to, or — unsaid — when the app generates a Prisma client. */
84
+ export function migratesCentral(config) {
85
+ return config.migrate?.central ?? (config.build?.prisma?.length ?? 0) > 0;
86
+ }
87
+ const migratesAnything = (config) => migratesCentral(config) || Boolean(config.migrate?.tenants);
88
+ /**
89
+ * Whether the pre-migration dump runs, and why not when it does not. Unsaid,
90
+ * it runs when there is something to migrate AND a Postgres to dump: the
91
+ * dedicated one, or a `postgres…` URL in the `.env`. Explicitly on, a missing
92
+ * database is the backup step's error to report.
93
+ */
94
+ export function backupDecision(config, values, skip = []) {
95
+ if ([...skip].includes('backup'))
96
+ return { run: false, why: '--skip=backup' };
97
+ const wanted = config.backup?.beforeMigrate;
98
+ if (wanted === false)
99
+ return { run: false, why: 'backup.beforeMigrate is false' };
100
+ if (wanted === true)
101
+ return { run: true };
102
+ if (!migratesAnything(config))
103
+ return { run: false, why: 'nothing to migrate' };
104
+ if (config.infra?.kind === 'docker' && config.infra.postgres)
105
+ return { run: true };
106
+ const url = values.get(config.backup?.urlKey ?? 'DATABASE_URL') ?? '';
107
+ return /^postgres(ql)?:\/\//.test(url) ? { run: true } : { run: false, why: 'no Postgres database in the .env' };
108
+ }
109
+ // ── the building blocks ────────────────────────────────────────────────────
110
+ async function prepareEnv(ctx, port) {
111
+ const document = await readEnv(ctx);
112
+ const infra = await planInfra(ctx, envValues(document));
113
+ const env = planEnv(ctx, document, port, infra.env);
114
+ return { env, infra };
115
+ }
116
+ async function build(ctx, values) {
117
+ const { host, pm } = ctx;
118
+ const run = async (args, options = {}) => {
119
+ host.out.info(`${pm} ${args.join(' ')}`);
120
+ const result = await host.exec(pm, args, {
121
+ cwd: ctx.dir, stream: true,
122
+ ...(options.env ? { env: Object.fromEntries(options.env) } : {}),
123
+ ...(options.unset ? { unset: options.unset } : {}),
124
+ });
125
+ if (result.code !== 0)
126
+ throw new DeployError(`${pm} ${args.join(' ')} failed (exit ${result.code})`);
127
+ };
128
+ // NODE_ENV unset: the build needs devDependencies (tsc, prisma, vite).
129
+ // Never a flag for it — they change between majors (pnpm 11 refused --prod=false).
130
+ const frozen = pm === 'npm' ? ['ci'] : pm === 'yarn' ? ['install', '--immutable'] : ['install', '--frozen-lockfile'];
131
+ await run(frozen, { unset: ['NODE_ENV'] });
132
+ for (const config of ctx.config.build?.prisma ?? [])
133
+ await run(['exec', 'prisma', 'generate', '--config', config], { env: values });
134
+ if (ctx.config.build?.web)
135
+ await run(['--dir', ctx.config.build.web, 'run', 'build'], { env: values });
136
+ }
137
+ async function validate(ctx, values) {
138
+ const schema = await checkSchema(ctx, values);
139
+ return [...schema.findings, ...coercionFindings(values, schema.trueKeys), ...policyFindings(ctx, values)];
140
+ }
141
+ async function migrate(ctx, values) {
142
+ const { host, pm } = ctx;
143
+ const env = { cwd: ctx.dir, stream: true, env: Object.fromEntries(values) };
144
+ if (migratesCentral(ctx.config)) {
145
+ host.out.info(`${pm} exec prisma migrate deploy`);
146
+ const central = await host.exec(pm, ['exec', 'prisma', 'migrate', 'deploy'], env);
147
+ if (central.code !== 0)
148
+ throw new DeployError('prisma migrate deploy failed');
149
+ }
150
+ const tenants = ctx.config.migrate?.tenants;
151
+ if (tenants) {
152
+ const args = Array.isArray(tenants) ? ['run', ...tenants] : ['run', 'basalt', ...(pm === 'npm' ? ['--'] : []), 'tenant:migrate'];
153
+ host.out.info(`${pm} ${args.join(' ')}`);
154
+ const result = await host.exec(pm, args, env);
155
+ if (result.code !== 0)
156
+ throw new DeployError('the tenant migrations failed');
157
+ }
158
+ if (!migratesAnything(ctx.config))
159
+ host.out.info('nothing to migrate (no build.prisma, no migrate.tenants)');
160
+ }
161
+ async function healthy(ctx, port) {
162
+ const { host, config } = ctx;
163
+ const path = config.health?.path ?? '/health';
164
+ const deadline = host.now().getTime() + (config.health?.timeoutSeconds ?? 60) * 1000;
165
+ do {
166
+ const answer = await host.httpGet(`http://127.0.0.1:${port}${path}`, { host: config.domain });
167
+ if ('status' in answer && answer.status >= 200 && answer.status < 400)
168
+ return true;
169
+ await host.sleep(2000);
170
+ } while (host.now().getTime() < deadline);
171
+ return false;
172
+ }
173
+ async function publicHealthy(ctx) {
174
+ const { config } = ctx;
175
+ if (config.health?.public === false || config.proxy?.kind !== 'apache')
176
+ return undefined;
177
+ const url = `https://${config.domain}${config.proxy.apiPrefix.replace(/\/$/, '')}${config.health?.path ?? '/health'}`;
178
+ const answer = await ctx.host.httpGet(url, { timeoutMs: 10_000 });
179
+ if ('status' in answer && answer.status >= 200 && answer.status < 400)
180
+ return undefined;
181
+ return {
182
+ id: 'health',
183
+ level: 'error',
184
+ message: `the app answers on 127.0.0.1 but not at ${url} (${'status' in answer ? `HTTP ${answer.status}` : answer.error}) — the proxy, DNS or TLS, not the code`,
185
+ fix: 'the [C1]/[C2]/[vhost] findings above, then: apachectl -S',
186
+ };
187
+ }
188
+ /** Puts the code on disk back to `sha` and rebuilds it. Does not restart anything. */
189
+ async function restoreCode(ctx, sha, values) {
190
+ ctx.host.out.step(`restoring the code to ${sha.slice(0, 7)}`);
191
+ await git(ctx, ['reset', '--hard', sha]);
192
+ await build(ctx, values);
193
+ }
194
+ /** The env step's summary: what changed, or that nothing did. */
195
+ function reportEnv(ctx, plan) {
196
+ const lines = describeEnv(plan);
197
+ if (lines.length === 0)
198
+ ctx.host.out.ok(`${ctx.config.env.file ?? '.env'} unchanged`);
199
+ for (const line of lines)
200
+ ctx.host.out.info(line);
201
+ }
202
+ async function infraStep(ctx, infra) {
203
+ stopOnErrors(ctx, await applyInfra(ctx, infra), 'infra');
204
+ if (infra.services.length === 0)
205
+ ctx.host.out.ok('nothing to start (external infra)');
206
+ else
207
+ ctx.host.out.ok(`${infra.services.map((s) => s.container).join(', ')} healthy; credentials accepted${ctx.config.infra?.kind === 'docker' && ctx.config.infra.minio?.buckets.length ? '; buckets in place' : ''}`);
208
+ }
209
+ async function validateStep(ctx, values) {
210
+ stopOnErrors(ctx, await validate(ctx, values), 'validate');
211
+ const schema = ctx.config.env.schema;
212
+ ctx.host.out.ok(schema ? `${ctx.config.env.file ?? '.env'} is valid for ${schema}` : `${ctx.config.env.file ?? '.env'}: syntax and policy only (no env.schema configured)`);
213
+ }
214
+ // ── commands ───────────────────────────────────────────────────────────────
215
+ export async function plan(ctx, options = {}) {
216
+ const checked = await step(ctx, 'preflight', () => preflight(ctx, options));
217
+ report(ctx.host, checked.findings);
218
+ const { env, infra } = await prepareEnv(ctx, checked.port);
219
+ report(ctx.host, infra.findings);
220
+ const { host, config, pm } = ctx;
221
+ host.out.step('plan — nothing below has run');
222
+ const lines = [
223
+ options.skip?.includes('fetch') ? 'fetch: skipped' : `fetch: git fetch ${config.remote ?? 'origin'} ${config.branch ?? 'main'} && git merge --ff-only`,
224
+ ...describeEnv(env).map((l) => `env: ${l}`),
225
+ ...describeInfra(infra).map((l) => `infra: ${l}`),
226
+ `build: ${pm} install (frozen), ${(config.build?.prisma ?? []).map((c) => `prisma generate --config ${c}`).join(', ') || 'no prisma'}${config.build?.web ? `, ${config.build.web} build` : ''}`,
227
+ `validate: ${config.env.schema ?? '(no schema configured)'} against the new .env`,
228
+ ((decision) => decision.run
229
+ ? `backup: pg_dump → ${config.backup?.dir ?? 'backups/predeploy'} (keep ${config.backup?.keep ?? 10})`
230
+ : `backup: skipped (${decision.why})`)(backupDecision(config, checked.values, options.skip ?? [])),
231
+ `migrate: ${[migratesCentral(config) ? 'prisma migrate deploy' : '', config.migrate?.tenants ? 'tenant:migrate' : ''].filter(Boolean).join(' + ') || 'nothing configured'}`,
232
+ `release: pm2 ${processName(config)} on 127.0.0.1:${checked.port}`,
233
+ `health: http://127.0.0.1:${checked.port}${config.health?.path ?? '/health'} (Host: ${config.domain})${config.proxy?.kind === 'apache' && config.health?.public !== false ? `, then https://${config.domain}${config.proxy.apiPrefix}${config.health?.path ?? '/health'}` : ''}`,
234
+ ];
235
+ for (const line of lines)
236
+ host.out.info(line);
237
+ return errors([...checked.findings, ...infra.findings]).length > 0 ? 1 : 0;
238
+ }
239
+ /** `basalt-deploy env` — the .env and the infra only (first setup, before `install`). */
240
+ export async function envCommand(ctx) {
241
+ const document = await readEnv(ctx);
242
+ stopOnErrors(ctx, syntaxFindings(document, ctx.config.env.file ?? '.env'), '.env');
243
+ const port = await resolvePort(ctx, envValues(document));
244
+ const { env, infra } = await step(ctx, 'env', () => prepareEnv(ctx, port));
245
+ stopOnErrors(ctx, infra.findings, 'infra');
246
+ const missing = await answerQuestions(ctx, env);
247
+ if (missing.length > 0)
248
+ throw new DeployError(`no answer for ${missing.join(', ')} (no terminal to ask): set them in the environment of this command`);
249
+ reportEnv(ctx, env);
250
+ await writeEnv(ctx, env);
251
+ await step(ctx, 'infra', () => infraStep(ctx, infra));
252
+ await step(ctx, 'validate', () => validateStep(ctx, env.values));
253
+ ctx.host.out.ok(`.env ready (PORT=${port})`);
254
+ return 0;
255
+ }
256
+ export async function run(ctx, options = {}) {
257
+ const { host, config } = ctx;
258
+ const skip = new Set(options.skip ?? []);
259
+ const checked = await step(ctx, 'preflight', () => preflight(ctx, options));
260
+ stopOnErrors(ctx, checked.findings, 'preflight');
261
+ const { port } = checked;
262
+ const previous = await git(ctx, ['rev-parse', 'HEAD']);
263
+ if (!skip.has('fetch')) {
264
+ await step(ctx, 'fetch', async () => {
265
+ await git(ctx, ['fetch', '--quiet', config.remote ?? 'origin', config.branch ?? 'main'], { noPrompt: !host.interactive() });
266
+ await git(ctx, ['merge', '--ff-only', `${config.remote ?? 'origin'}/${config.branch ?? 'main'}`]);
267
+ });
268
+ }
269
+ const sha = await git(ctx, ['rev-parse', 'HEAD']);
270
+ host.out.info(sha === previous ? `already at ${sha.slice(0, 7)}` : `${previous.slice(0, 7)} → ${sha.slice(0, 7)}`);
271
+ const applied = sha === previous ? [] : migrationNames((await git(ctx, ['diff', '--name-only', previous, sha])).split('\n'));
272
+ const release = { sha, previous, at: host.now().toISOString(), user: host.env['USER'] ?? String(host.uid()), status: 'failed', migrations: applied };
273
+ // From here a failure puts the code on disk back before it is reported.
274
+ let values = checked.values;
275
+ let infra = { services: [], env: [], findings: [], secrets: {} };
276
+ try {
277
+ const prepared = await step(ctx, 'env', () => prepareEnv(ctx, port));
278
+ infra = prepared.infra;
279
+ stopOnErrors(ctx, infra.findings, 'infra');
280
+ const missing = await answerQuestions(ctx, prepared.env);
281
+ if (missing.length > 0)
282
+ throw new DeployError(`no answer for ${missing.join(', ')} (no terminal to ask): set them in the environment of this command`);
283
+ reportEnv(ctx, prepared.env);
284
+ await writeEnv(ctx, prepared.env);
285
+ values = prepared.env.values;
286
+ await step(ctx, 'infra', () => infraStep(ctx, infra));
287
+ await step(ctx, 'build', () => build(ctx, values));
288
+ await step(ctx, 'validate', () => validateStep(ctx, values));
289
+ const backup = backupDecision(config, values, skip);
290
+ if (backup.run) {
291
+ release.backup = await step(ctx, 'backup', () => backupDatabase(ctx, values, infra, sha));
292
+ host.out.ok(release.backup);
293
+ }
294
+ else {
295
+ host.out.step('backup');
296
+ host.out.info(`skipped: ${backup.why}`);
297
+ }
298
+ await step(ctx, 'migrate', () => migrate(ctx, values));
299
+ }
300
+ catch (error) {
301
+ if (sha !== previous)
302
+ await restoreCode(ctx, previous, values).catch((e) => host.out.error(`could not restore the code: ${e.message}`));
303
+ release.note = error.message;
304
+ await recordRelease(ctx, release).catch(() => undefined);
305
+ throw error;
306
+ }
307
+ const destructive = applied.filter((name) => config.destructive?.includes(name));
308
+ const recover = async (why) => {
309
+ host.out.error(why);
310
+ if (destructive.length > 0 || sha === previous) {
311
+ if (destructive.length > 0)
312
+ host.out.error(`not rolled back automatically: ${destructive.join(', ')} ${destructive.length === 1 ? 'is' : 'are'} marked destructive`);
313
+ if (release.backup)
314
+ host.out.info(`database before this release: ${restoreCommand(ctx, infra, release.backup)}`);
315
+ release.note = why;
316
+ await recordRelease(ctx, release);
317
+ return 1;
318
+ }
319
+ await rollbackTo(ctx, previous, values, port);
320
+ release.status = 'rolled-back';
321
+ release.note = why;
322
+ await recordRelease(ctx, release);
323
+ return 1;
324
+ };
325
+ try {
326
+ host.out.ok(await step(ctx, 'release', () => pm2Release(ctx, values)));
327
+ }
328
+ catch (error) {
329
+ return recover(error.message);
330
+ }
331
+ const ok = await step(ctx, 'health', () => healthy(ctx, port));
332
+ if (!ok)
333
+ return recover(`the app does not answer on http://127.0.0.1:${port}${config.health?.path ?? '/health'}`);
334
+ host.out.ok(`http://127.0.0.1:${port}${config.health?.path ?? '/health'}`);
335
+ const publicProblem = await publicHealthy(ctx);
336
+ release.status = publicProblem ? 'public-unreachable' : 'ok';
337
+ await step(ctx, 'record', () => recordRelease(ctx, release));
338
+ if (publicProblem) {
339
+ report(host, [publicProblem]);
340
+ return 1;
341
+ }
342
+ host.out.ok(`${config.app} ${sha.slice(0, 7)} is live at https://${config.domain}`);
343
+ return 0;
344
+ }
345
+ async function rollbackTo(ctx, sha, values, port) {
346
+ await restoreCode(ctx, sha, values);
347
+ ctx.host.out.step(`release ${sha.slice(0, 7)}`);
348
+ ctx.host.out.ok(await pm2Release(ctx, values));
349
+ if (await healthy(ctx, port))
350
+ ctx.host.out.ok(`back on ${sha.slice(0, 7)}`);
351
+ else
352
+ ctx.host.out.error(`${sha.slice(0, 7)} does not answer either — pm2 logs ${processName(ctx.config)}`);
353
+ }
354
+ /** `basalt-deploy rollback [--to=<sha>]` — code only; the database stays as it is. */
355
+ export async function rollback(ctx, to) {
356
+ const current = await git(ctx, ['rev-parse', 'HEAD']);
357
+ const releases = await readReleases(ctx);
358
+ // The last healthy release before this one; on the first recorded deploy,
359
+ // the commit it was deployed over.
360
+ const target = to ?? lastGood(releases, current)?.sha ?? [...releases].reverse().find((r) => r.sha === current)?.previous;
361
+ if (!target || target === current)
362
+ throw new DeployError('no earlier release to go back to; pass --to=<sha>');
363
+ const document = await readEnv(ctx);
364
+ const values = envValues(document);
365
+ const port = await resolvePort(ctx, values);
366
+ const since = migrationNames((await git(ctx, ['diff', '--name-only', target, current])).split('\n'));
367
+ if (since.length > 0) {
368
+ ctx.host.out.warn(`the database keeps the migrations applied since ${target.slice(0, 7)}: ${since.join(', ')}`);
369
+ const destructive = since.filter((name) => ctx.config.destructive?.includes(name));
370
+ if (destructive.length > 0)
371
+ throw new DeployError(`refused: ${destructive.join(', ')} marked destructive — ${target.slice(0, 7)} cannot run on this schema`);
372
+ }
373
+ await rollbackTo(ctx, target, values, port);
374
+ await recordRelease(ctx, { sha: target, previous: current, at: ctx.host.now().toISOString(), user: ctx.host.env['USER'] ?? '', status: 'ok', migrations: [], note: `manual rollback from ${current.slice(0, 7)}` });
375
+ return 0;
376
+ }
377
+ export async function status(ctx) {
378
+ const { host } = ctx;
379
+ const releases = (await readReleases(ctx)).slice(-10).reverse();
380
+ host.out.step(`${ctx.config.app} — last ${releases.length} release(s)`);
381
+ for (const r of releases)
382
+ host.out.info(`${r.at} ${r.sha.slice(0, 7)} ${r.status.padEnd(18)} ${r.user}${r.migrations.length ? ` +${r.migrations.length} migration(s)` : ''}${r.note ? ` — ${r.note}` : ''}`);
383
+ const process = (await pm2List(ctx))?.find((p) => p.name === processName(ctx.config));
384
+ host.out.info(process ? `pm2 ${process.name}: ${process.status} (pid ${process.pid}, ${process.cwd})` : `pm2 ${processName(ctx.config)}: not running`);
385
+ return 0;
386
+ }
387
+ /**
388
+ * `sudo basalt-deploy install` — once per server, by an administrator (RFC
389
+ * 0006 §11.4). Everything that needs root and nothing else: the vhost, the
390
+ * state directory owned by the app user. The app user is never added to the
391
+ * `docker` group (root-equivalent); with dedicated infra it needs rootless
392
+ * Docker, and this says so.
393
+ */
394
+ export async function install(ctx, user) {
395
+ const { host, config } = ctx;
396
+ if (host.uid() !== 0)
397
+ throw new DeployError(`install needs root: ${INSTALL_COMMAND}`);
398
+ if (!user || user === 'root')
399
+ throw new DeployError('install needs the unprivileged user the deploys run as: --user=<name> (never root)');
400
+ const port = Number(envValues(await readEnv(ctx)).get('PORT'));
401
+ if (!Number.isInteger(port) || port <= 0)
402
+ throw new DeployError('no PORT in the .env yet: run `pnpm exec basalt-deploy env` as the app user first');
403
+ const stateDir = `/var/lib/basalt/${config.app}`;
404
+ await step(ctx, `state directory ${stateDir}`, async () => {
405
+ await host.mkdir(stateDir, 0o700);
406
+ await host.mkdir(join(stateDir, 'install-backups'), 0o700);
407
+ const local = await host.readFile(join(ctx.dir, '.basalt', 'releases.json'));
408
+ if (local && !(await host.exists(join(stateDir, 'releases.json'))))
409
+ await host.writeFile(join(stateDir, 'releases.json'), local, 0o600);
410
+ const chown = await host.exec('chown', ['-R', `${user}:`, stateDir]);
411
+ if (chown.code !== 0)
412
+ throw new DeployError(`chown ${user} ${stateDir}: ${chown.stderr.trim()}`);
413
+ if (!(await host.exists(`/etc/basalt/${config.app}.json`))) {
414
+ await host.mkdir('/etc/basalt', 0o755);
415
+ await host.writeFile(`/etc/basalt/${config.app}.json`, '{}\n', 0o644);
416
+ }
417
+ });
418
+ if (config.proxy?.kind === 'apache') {
419
+ await step(ctx, `Apache vhost ${vhostPaths(ctx).file}`, () => apacheInstall(ctx, port, join(stateDir, 'install-backups')));
420
+ }
421
+ if (config.infra?.kind === 'docker') {
422
+ const groups = (await host.exec('id', ['-nG', user])).stdout.split(/\s+/);
423
+ if (groups.includes('docker')) {
424
+ host.out.warn(`${user} is in the docker group: that is root on this machine (a container can mount /). Plan the move to rootless Docker for ${user} (dockerd-rootless-setuptool.sh install); this command will not do it for a server with data in rootful volumes.`);
425
+ }
426
+ else {
427
+ host.out.info(`dedicated infra runs under ${user}'s rootless Docker: dockerd-rootless-setuptool.sh install (as ${user}), then loginctl enable-linger ${user}`);
428
+ }
429
+ }
430
+ host.out.ok(`installed — from now on, as ${user}: pnpm exec basalt-deploy run`);
431
+ return 0;
432
+ }
package/dist/pm2.d.ts ADDED
@@ -0,0 +1,23 @@
1
+ import { type DeployContext, type Finding } from './context.js';
2
+ /**
3
+ * The PM2 runtime. It only ever names `<app>-…` (C4) — there is no `all`.
4
+ */
5
+ export interface Pm2Process {
6
+ name: string;
7
+ pid: number;
8
+ cwd: string;
9
+ status: string;
10
+ }
11
+ export declare function pm2List(ctx: DeployContext): Promise<Pm2Process[] | undefined>;
12
+ export declare function resolvePort(ctx: DeployContext, values: Map<string, string>): Promise<number>;
13
+ export declare function pm2Preflight(ctx: DeployContext, port: number): Promise<Finding[]>;
14
+ /**
15
+ * What the process is started with: a minimal environment, never the
16
+ * operator's shell (a stray variable there would override the `.env` — dotenv
17
+ * and `--env-file` never overwrite) and never the `.env`'s secrets (`pm2 save`
18
+ * writes the process environment to `~/.pm2/dump.pm2`). The app reads its own
19
+ * `.env`, as it does in development; only what PM2 itself must know is passed.
20
+ */
21
+ export declare function processEnv(host: DeployContext['host'], env: Map<string, string>): Record<string, string>;
22
+ /** Starts, restarts or re-creates the process; says which. */
23
+ export declare function pm2Release(ctx: DeployContext, env: Map<string, string>): Promise<string>;
package/dist/pm2.js ADDED
@@ -0,0 +1,110 @@
1
+ import { processName } from './config.js';
2
+ import { DeployError } from './context.js';
3
+ import { freePort, listeners } from './ports.js';
4
+ export async function pm2List(ctx) {
5
+ const result = await ctx.host.exec('pm2', ['jlist']);
6
+ if (result.code !== 0)
7
+ return undefined;
8
+ // pm2 may print a banner or an update notice before the JSON.
9
+ const start = result.stdout.indexOf('[');
10
+ if (start === -1)
11
+ return [];
12
+ try {
13
+ const raw = JSON.parse(result.stdout.slice(start));
14
+ return raw.map((p) => ({ name: String(p.name ?? ''), pid: Number(p.pid ?? 0), cwd: String(p.pm2_env?.pm_cwd ?? ''), status: String(p.pm2_env?.status ?? '') }));
15
+ }
16
+ catch {
17
+ return [];
18
+ }
19
+ }
20
+ const PORT_FROM = 3000;
21
+ export async function resolvePort(ctx, values) {
22
+ const runtime = ctx.config.runtime;
23
+ if (typeof runtime.port === 'number')
24
+ return runtime.port;
25
+ const current = Number(values.get('PORT'));
26
+ if (Number.isInteger(current) && current > 0)
27
+ return current;
28
+ return freePort(ctx.host, PORT_FROM, runtime.avoid);
29
+ }
30
+ export async function pm2Preflight(ctx, port) {
31
+ const findings = [];
32
+ const name = processName(ctx.config);
33
+ const processes = await pm2List(ctx);
34
+ if (processes === undefined) {
35
+ return [{ id: 'C9', level: 'error', message: 'pm2 is not available to this user', fix: 'npm i -g pm2 (as the app user), then pm2 startup' }];
36
+ }
37
+ const ours = processes.find((p) => p.name === name);
38
+ // C3 — `pm2 restart` reuses the directory the process was started in. One
39
+ // started from an old clone kept running old code after every deploy.
40
+ if (ours && ours.cwd !== ctx.dir) {
41
+ findings.push({ id: 'C3', level: 'warning', message: `${name} runs from ${ours.cwd}, not ${ctx.dir}: it will be re-created here, not restarted` });
42
+ }
43
+ // C1 — the port must be free or ours. "Ours" includes the process above
44
+ // even from its old directory: it is about to be replaced.
45
+ const ourDirs = new Set([ctx.dir, ...(ours ? [ours.cwd] : [])]);
46
+ for (const listener of (await listeners(ctx.host)).filter((l) => l.port === port)) {
47
+ let foreign = listener.pids.length === 0;
48
+ for (const pid of listener.pids) {
49
+ const cwd = await ctx.host.readlink(`/proc/${pid}/cwd`);
50
+ if (cwd === undefined || !ourDirs.has(cwd))
51
+ foreign = true;
52
+ }
53
+ if (foreign) {
54
+ findings.push({
55
+ id: 'C1',
56
+ level: 'error',
57
+ message: `port ${port} (PORT in .env) is already taken by a process that is not ${name} (on ${listener.address})`,
58
+ fix: 'pick another: put "port": <n> in /etc/basalt/<app>.json, or remove PORT from .env to pick a free one',
59
+ });
60
+ break;
61
+ }
62
+ }
63
+ return findings;
64
+ }
65
+ /**
66
+ * What the process is started with: a minimal environment, never the
67
+ * operator's shell (a stray variable there would override the `.env` — dotenv
68
+ * and `--env-file` never overwrite) and never the `.env`'s secrets (`pm2 save`
69
+ * writes the process environment to `~/.pm2/dump.pm2`). The app reads its own
70
+ * `.env`, as it does in development; only what PM2 itself must know is passed.
71
+ */
72
+ export function processEnv(host, env) {
73
+ const out = {};
74
+ for (const key of ['NODE_ENV', 'PORT', 'HOST']) {
75
+ const value = env.get(key);
76
+ if (value !== undefined)
77
+ out[key] = value;
78
+ }
79
+ const pm2Home = host.env['PM2_HOME'];
80
+ if (pm2Home)
81
+ out['PM2_HOME'] = pm2Home;
82
+ return out;
83
+ }
84
+ /** Starts, restarts or re-creates the process; says which. */
85
+ export async function pm2Release(ctx, env) {
86
+ const { host } = ctx;
87
+ const name = processName(ctx.config);
88
+ const options = { cwd: ctx.dir, env: processEnv(host, env), inheritEnv: false };
89
+ const ours = (await pm2List(ctx))?.find((p) => p.name === name);
90
+ if (ours && ours.cwd !== ctx.dir) {
91
+ host.out.info(`pm2 delete ${name} (it ran from ${ours.cwd})`);
92
+ await must(ctx, ['delete', name], options);
93
+ }
94
+ let done;
95
+ if (ours && ours.cwd === ctx.dir) {
96
+ await must(ctx, ['restart', name, '--update-env'], options);
97
+ done = `${name} restarted`;
98
+ }
99
+ else {
100
+ await must(ctx, ['start', ctx.pm, '--name', name, '--cwd', ctx.dir, '--', 'run', ctx.config.runtime.script], options);
101
+ done = ours ? `${name} re-created in ${ctx.dir}` : `${name} started`;
102
+ }
103
+ await must(ctx, ['save'], options);
104
+ return `${done} (${ctx.pm} run ${ctx.config.runtime.script}, port ${env.get('PORT') ?? '?'})`;
105
+ }
106
+ async function must(ctx, args, options) {
107
+ const result = await ctx.host.exec('pm2', args, options);
108
+ if (result.code !== 0)
109
+ throw new DeployError(`pm2 ${args.slice(0, 2).join(' ')} failed: ${result.stderr.trim() || result.stdout.trim()}`);
110
+ }
@@ -0,0 +1,10 @@
1
+ import type { Host } from './host.js';
2
+ export interface Listener {
3
+ port: number;
4
+ address: string;
5
+ /** Empty when the socket belongs to another user (ss shows no process then). */
6
+ pids: number[];
7
+ }
8
+ /** TCP listeners on this machine, from `ss -ltnpH`. */
9
+ export declare function listeners(host: Host): Promise<Listener[]>;
10
+ export declare function freePort(host: Host, from: number, avoid?: number[], taken?: number[]): Promise<number>;
package/dist/ports.js ADDED
@@ -0,0 +1,27 @@
1
+ /** TCP listeners on this machine, from `ss -ltnpH`. */
2
+ export async function listeners(host) {
3
+ const result = await host.exec('ss', ['-ltnpH']);
4
+ if (result.code !== 0)
5
+ return [];
6
+ const out = [];
7
+ for (const line of result.stdout.split('\n')) {
8
+ const fields = line.trim().split(/\s+/);
9
+ const local = fields[3];
10
+ if (!local)
11
+ continue;
12
+ const colon = local.lastIndexOf(':');
13
+ const port = Number(local.slice(colon + 1));
14
+ if (!Number.isInteger(port))
15
+ continue;
16
+ const pids = [...line.matchAll(/pid=(\d+)/g)].map((m) => Number(m[1]));
17
+ out.push({ port, address: local.slice(0, colon), pids });
18
+ }
19
+ return out;
20
+ }
21
+ export async function freePort(host, from, avoid = [], taken = []) {
22
+ const busy = new Set([...(await listeners(host)).map((l) => l.port), ...avoid, ...taken]);
23
+ for (let port = from; port < from + 1000; port++)
24
+ if (!busy.has(port))
25
+ return port;
26
+ throw new Error(`no free port between ${from} and ${from + 999}`);
27
+ }
@@ -0,0 +1,20 @@
1
+ import type { DeployContext } from './context.js';
2
+ /** One line per release in `<stateDir>/releases.json` (RFC 0006 §8). */
3
+ export interface Release {
4
+ sha: string;
5
+ previous?: string;
6
+ at: string;
7
+ user: string;
8
+ status: 'ok' | 'rolled-back' | 'failed' | 'public-unreachable';
9
+ /** Migration directories this release applied for the first time. */
10
+ migrations: string[];
11
+ backup?: string;
12
+ note?: string;
13
+ }
14
+ export declare const releasesFile: (ctx: DeployContext) => string;
15
+ export declare function readReleases(ctx: DeployContext): Promise<Release[]>;
16
+ export declare function recordRelease(ctx: DeployContext, release: Release): Promise<void>;
17
+ /** The last release that ended healthy, other than `sha`. */
18
+ export declare function lastGood(releases: Release[], except: string): Release | undefined;
19
+ /** Migration directory names among changed paths (`…/migrations/<name>/migration.sql`). */
20
+ export declare function migrationNames(paths: string[]): string[];
package/dist/state.js ADDED
@@ -0,0 +1,34 @@
1
+ import { join } from 'node:path';
2
+ const KEEP = 100;
3
+ export const releasesFile = (ctx) => join(ctx.stateDir, 'releases.json');
4
+ export async function readReleases(ctx) {
5
+ const text = await ctx.host.readFile(releasesFile(ctx));
6
+ if (!text)
7
+ return [];
8
+ try {
9
+ const parsed = JSON.parse(text);
10
+ return Array.isArray(parsed) ? parsed : [];
11
+ }
12
+ catch {
13
+ return [];
14
+ }
15
+ }
16
+ export async function recordRelease(ctx, release) {
17
+ const releases = [...(await readReleases(ctx)), release].slice(-KEEP);
18
+ await ctx.host.mkdir(ctx.stateDir, 0o700);
19
+ await ctx.host.writeFile(releasesFile(ctx), `${JSON.stringify(releases, null, 2)}\n`, 0o600);
20
+ }
21
+ /** The last release that ended healthy, other than `sha`. */
22
+ export function lastGood(releases, except) {
23
+ return [...releases].reverse().find((r) => r.status === 'ok' && r.sha !== except);
24
+ }
25
+ /** Migration directory names among changed paths (`…/migrations/<name>/migration.sql`). */
26
+ export function migrationNames(paths) {
27
+ const names = new Set();
28
+ for (const path of paths) {
29
+ const match = /(?:^|\/)migrations\/([^/]+)\/[^/]+\.sql$/.exec(path);
30
+ if (match)
31
+ names.add(match[1]);
32
+ }
33
+ return [...names].sort();
34
+ }