@basaltkit/deploy 0.10.0 → 0.11.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.
- package/README.md +7 -1
- package/dist/apache.d.ts +11 -0
- package/dist/apache.js +45 -0
- package/dist/bootstrap.js +17 -5
- package/dist/checks.d.ts +9 -0
- package/dist/checks.js +27 -0
- package/dist/cli.js +38 -4
- package/dist/config.d.ts +6 -2
- package/dist/config.js +1 -1
- package/dist/env-check.d.ts +8 -0
- package/dist/env-check.js +24 -0
- package/dist/env-step.js +10 -1
- package/dist/events.d.ts +12 -2
- package/dist/events.js +21 -1
- package/dist/infra.js +2 -2
- package/dist/init.d.ts +5 -0
- package/dist/init.js +44 -10
- package/dist/json-host.js +2 -0
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -34,6 +34,10 @@ It asks the domain, the tenancy and the branch (or takes `--domain`,
|
|
|
34
34
|
`--tenants`, `--branch`, `--proxy`), never overwrites a config (`--force`),
|
|
35
35
|
and runs `check` on what it wrote.
|
|
36
36
|
|
|
37
|
+
Every option, its default and an example: the
|
|
38
|
+
[`deploy.config.ts` reference](https://basaltkit-docs.pages.dev/guide/deploy-config)
|
|
39
|
+
([Português](https://basaltkit-docs.pages.dev/pt/guide/deploy-config)).
|
|
40
|
+
|
|
37
41
|
```ts
|
|
38
42
|
import { apache, ask, defineDeploy, dockerInfra, pm2, secret } from '@basaltkit/deploy'
|
|
39
43
|
|
|
@@ -548,7 +552,9 @@ They run in the checkout as the deploy user with the `.env` values, the image
|
|
|
548
552
|
variables, `DEPLOY_SHA` and `DEPLOY_APP`. They run on every deploy: idempotent.
|
|
549
553
|
|
|
550
554
|
**Apache you write yourself:** `apache({ managed: false, vhosts: ['myapp.conf'] })`
|
|
551
|
-
checks C2 and C1 on each vhost on every deploy and never writes them.
|
|
555
|
+
checks C2 and C1 on each vhost on every deploy and never writes them. Start one
|
|
556
|
+
with `basalt-deploy vhost > myapp.conf`: the managed vhost, rendered for this
|
|
557
|
+
checkout and the app's port.
|
|
552
558
|
|
|
553
559
|
## What runs by default
|
|
554
560
|
|
package/dist/apache.d.ts
CHANGED
|
@@ -9,5 +9,16 @@ export declare function renderVhost(ctx: DeployContext, port: number): string;
|
|
|
9
9
|
/** The ports a vhost proxies to on this machine. */
|
|
10
10
|
export declare function proxiedPorts(vhost: string): number[];
|
|
11
11
|
export declare function apachePreflight(ctx: DeployContext, port: number): Promise<Finding[]>;
|
|
12
|
+
/**
|
|
13
|
+
* Root only. The certificate the vhost names, before the vhost is written: a
|
|
14
|
+
* vhost pointing at a missing `/etc/letsencrypt/live/<name>` fails
|
|
15
|
+
* `apachectl configtest`, and install then puts every file back and stops.
|
|
16
|
+
* When it is missing, install offers to get one from Let's Encrypt (HTTP-01
|
|
17
|
+
* through the Apache plugin, `certonly`: certbot never edits the vhost), and
|
|
18
|
+
* installs certbot first if it is not there, all after asking. A wildcard
|
|
19
|
+
* (tenants on subdomains) needs a DNS challenge, which install cannot answer.
|
|
20
|
+
* It says how, and stops.
|
|
21
|
+
*/
|
|
22
|
+
export declare function ensureCertificate(ctx: DeployContext): Promise<void>;
|
|
12
23
|
/** Root only. Writes the vhost (after showing the diff and asking), links it, configtest, reload. */
|
|
13
24
|
export declare function apacheInstall(ctx: DeployContext, port: number, backupDir: string): Promise<void>;
|
package/dist/apache.js
CHANGED
|
@@ -2,6 +2,7 @@ import { dirname, join } from 'node:path';
|
|
|
2
2
|
import { vhostName } from './config.js';
|
|
3
3
|
import { DeployError, INSTALL_COMMAND } from './context.js';
|
|
4
4
|
import { lineDiff } from './diff.js';
|
|
5
|
+
import { APT } from './system.js';
|
|
5
6
|
/**
|
|
6
7
|
* The Apache target (RFC 0006 §11.3): the vhost is written ONLY by `install`,
|
|
7
8
|
* as root, once. Every deploy compares what is installed with what `install`
|
|
@@ -193,9 +194,53 @@ export async function apachePreflight(ctx, port) {
|
|
|
193
194
|
}
|
|
194
195
|
return findings;
|
|
195
196
|
}
|
|
197
|
+
/**
|
|
198
|
+
* Root only. The certificate the vhost names, before the vhost is written: a
|
|
199
|
+
* vhost pointing at a missing `/etc/letsencrypt/live/<name>` fails
|
|
200
|
+
* `apachectl configtest`, and install then puts every file back and stops.
|
|
201
|
+
* When it is missing, install offers to get one from Let's Encrypt (HTTP-01
|
|
202
|
+
* through the Apache plugin, `certonly`: certbot never edits the vhost), and
|
|
203
|
+
* installs certbot first if it is not there, all after asking. A wildcard
|
|
204
|
+
* (tenants on subdomains) needs a DNS challenge, which install cannot answer.
|
|
205
|
+
* It says how, and stops.
|
|
206
|
+
*/
|
|
207
|
+
export async function ensureCertificate(ctx) {
|
|
208
|
+
const { host } = ctx;
|
|
209
|
+
const { domain } = ctx.config;
|
|
210
|
+
const name = apacheOf(ctx).certName ?? domain;
|
|
211
|
+
const live = `/etc/letsencrypt/live/${name}`;
|
|
212
|
+
if ((await host.stat(join(live, 'fullchain.pem'))) !== undefined)
|
|
213
|
+
return;
|
|
214
|
+
if (ctx.config.tenants === 'subdomain') {
|
|
215
|
+
throw new DeployError(`no TLS certificate at ${live}, and tenants on subdomains need a wildcard (*.${domain}), which Let's Encrypt issues only over DNS. ` +
|
|
216
|
+
`Get it with your DNS provider's certbot plugin, or by hand: certbot certonly --manual --preferred-challenges dns --cert-name ${name} -d ${domain} -d '*.${domain}'. Then run install again`);
|
|
217
|
+
}
|
|
218
|
+
const certbot = (await host.exec('sh', ['-c', 'command -v certbot'])).code === 0;
|
|
219
|
+
const steps = [
|
|
220
|
+
...(certbot ? [] : [[...APT, 'install', '-y', '-qq', 'certbot', 'python3-certbot-apache']]),
|
|
221
|
+
['certbot', 'certonly', '--apache', '--non-interactive', '--agree-tos', '--register-unsafely-without-email', '--cert-name', name, '-d', domain],
|
|
222
|
+
];
|
|
223
|
+
const byHand = steps.map((step) => step.join(' ')).join(' && ');
|
|
224
|
+
host.out.info(`no TLS certificate for ${domain} at ${live}: the vhost would not load without one.`);
|
|
225
|
+
host.out.info(`install can get one from Let's Encrypt (${domain} must already point at this server, and port 80 be open):`);
|
|
226
|
+
for (const step of steps)
|
|
227
|
+
host.out.info(` + ${step.join(' ')}`);
|
|
228
|
+
if (!(await host.confirm(`Get a certificate for ${domain} from Let's Encrypt (you accept its terms, https://letsencrypt.org/repository/)?`))) {
|
|
229
|
+
throw new DeployError(`no TLS certificate at ${live}: get one, then run install again:\n ${byHand}`);
|
|
230
|
+
}
|
|
231
|
+
for (const step of steps) {
|
|
232
|
+
const result = await host.exec(step[0], step.slice(1));
|
|
233
|
+
if (result.code !== 0) {
|
|
234
|
+
const tail = (result.stderr || result.stdout).trim().split('\n').slice(-4).join('\n');
|
|
235
|
+
throw new DeployError(`${step.slice(0, 2).join(' ')} failed (exit ${result.code}); nothing was written:\n${tail}`);
|
|
236
|
+
}
|
|
237
|
+
}
|
|
238
|
+
host.out.ok(`certificate for ${domain} in ${live} (certbot renews it on its own timer)`);
|
|
239
|
+
}
|
|
196
240
|
/** Root only. Writes the vhost (after showing the diff and asking), links it, configtest, reload. */
|
|
197
241
|
export async function apacheInstall(ctx, port, backupDir) {
|
|
198
242
|
const { host } = ctx;
|
|
243
|
+
await ensureCertificate(ctx);
|
|
199
244
|
const paths = vhostPaths(ctx);
|
|
200
245
|
const wanted = renderVhost(ctx, port);
|
|
201
246
|
const stamp = host.now().toISOString().replace(/[-:]/g, '').replace(/\..+$/, '');
|
package/dist/bootstrap.js
CHANGED
|
@@ -88,19 +88,31 @@ export async function planSystem(host, dir, user) {
|
|
|
88
88
|
const major = Math.max(24, wanted?.[0] ?? 0);
|
|
89
89
|
actions.push({ what: `Node ${major} (NodeSource; engines.node ${pkg.engines?.node ?? 'unset'})`, commands: [sh(`curl -fsSL https://deb.nodesource.com/setup_${major}.x | bash -`), [...APT, 'install', '-y', '-qq', 'nodejs']] });
|
|
90
90
|
}
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
91
|
+
// Phase 2 runs `pnpm install` whatever package.json says, so a pnpm must be
|
|
92
|
+
// there: the lockfile's own when it records one (C11), else packageManager's.
|
|
93
|
+
const lockfile = await readCheckoutFile(host, join(dir, 'pnpm-lock.yaml'), LOCKFILE_BYTES);
|
|
94
|
+
const declared = pkg.packageManager?.startsWith('pnpm@') ? pkg.packageManager.slice('pnpm@'.length).split('+')[0] : undefined;
|
|
95
|
+
const version = (lockfile && lockedPnpm(lockfile)) ?? declared;
|
|
96
|
+
const current = (await host.exec('pnpm', ['--version'], OUTSIDE)).stdout.trim();
|
|
97
|
+
if (version !== undefined) {
|
|
95
98
|
if (!/^\d+\.\d+\.\d+(-[0-9A-Za-z.-]+)?$/.test(version))
|
|
96
99
|
throw new DeployError(`the pnpm version the project records ("${version}") is not a version`);
|
|
97
100
|
// The app user picks the version root installs globally: never one older than the floor.
|
|
98
101
|
if (below(minimumVersion(version), MIN_PNPM))
|
|
99
102
|
throw new DeployError(`the project records pnpm ${version}; bootstrap installs pnpm ${MIN_PNPM.join('.')} or newer globally, as root — update packageManager and the lockfile`);
|
|
100
|
-
const current = (await host.exec('pnpm', ['--version'], OUTSIDE)).stdout.trim();
|
|
101
103
|
if (current !== version)
|
|
102
104
|
actions.push({ what: `pnpm ${version}${current ? ` (this server has ${current})` : ''}`, commands: [['npm', 'install', '-g', `pnpm@${version}`]] });
|
|
103
105
|
}
|
|
106
|
+
else {
|
|
107
|
+
// Nothing says which pnpm: say so now, in the dry run too, rather than
|
|
108
|
+
// plan nothing and die at `pnpm install` (exit 127) in phase 2.
|
|
109
|
+
const usable = minimumVersion(current);
|
|
110
|
+
if (!usable || below(usable, MIN_PNPM)) {
|
|
111
|
+
throw new DeployError(`package.json has no "packageManager": "pnpm@<version>" and pnpm-lock.yaml records no pnpm, so bootstrap cannot tell which pnpm to install` +
|
|
112
|
+
(current ? ` (this server has pnpm ${current}, older than ${MIN_PNPM.join('.')})` : ' (and this server has none)') +
|
|
113
|
+
'; phase 2 runs pnpm install. Run `corepack use pnpm@<version>` in the project (it writes packageManager), commit, and run bootstrap again', [], undefined, 'run `corepack use pnpm@<version>` in the project (it writes packageManager), commit, and run bootstrap again');
|
|
114
|
+
}
|
|
115
|
+
}
|
|
104
116
|
const owner = (await host.exec('stat', ['-c', '%U', dir], OUTSIDE)).stdout.trim();
|
|
105
117
|
if (owner !== user) {
|
|
106
118
|
actions.push({
|
package/dist/checks.d.ts
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import type { DeployContext, Finding } from './context.js';
|
|
2
|
+
import type { Host } from './host.js';
|
|
2
3
|
/** Whether a certificate name (`*.example.com` or exact) covers `host`. Wildcards cover one label only. */
|
|
3
4
|
export declare function covers(name: string, host: string): boolean;
|
|
4
5
|
/**
|
|
@@ -13,6 +14,14 @@ export declare function minimumVersion(range: string | undefined): number[] | un
|
|
|
13
14
|
export declare const below: (version: number[], minimum: number[]) => boolean;
|
|
14
15
|
/** C9 — the toolchain the pipeline will call, before it calls it. */
|
|
15
16
|
export declare function toolingFindings(ctx: DeployContext): Promise<Finding[]>;
|
|
17
|
+
/**
|
|
18
|
+
* Why root's commands (`bootstrap`, `install`) would not start here, if they
|
|
19
|
+
* would not: they run as `sudo -H npx …`, and `sudo` resolves `npx` on its
|
|
20
|
+
* secure_path, so a `node` that only nvm (or fnm, volta, asdf) installed for
|
|
21
|
+
* this user is not there. Said when the user is about to need root — the
|
|
22
|
+
* app's own runs are fine on nvm's node.
|
|
23
|
+
*/
|
|
24
|
+
export declare function rootNodeProblem(host: Host): Promise<string | undefined>;
|
|
16
25
|
/** The pnpm version the lockfile records for `packageManager` (`packageManagerDependencies`), if any. */
|
|
17
26
|
export declare function lockedPnpm(lockfile: string): string | undefined;
|
|
18
27
|
/**
|
package/dist/checks.js
CHANGED
|
@@ -106,6 +106,33 @@ export async function toolingFindings(ctx) {
|
|
|
106
106
|
}
|
|
107
107
|
return findings;
|
|
108
108
|
}
|
|
109
|
+
/** Where nvm, fnm, volta and asdf put a user's own `node`: invisible to root and to `sudo`'s secure_path. */
|
|
110
|
+
const HOME_PREFIX = /^\/(?:home|root)\//;
|
|
111
|
+
const MANAGER_DIR = /\/\.(?:nvm|fnm|volta|asdf)\/|\/\.local\/share\/fnm\//;
|
|
112
|
+
const isUserNode = (path) => HOME_PREFIX.test(path) || MANAGER_DIR.test(path);
|
|
113
|
+
/** The places a system `node` lives (NodeSource and distro packages, a manual install). */
|
|
114
|
+
const SYSTEM_NODES = ['/usr/bin/node', '/usr/local/bin/node'];
|
|
115
|
+
/**
|
|
116
|
+
* Why root's commands (`bootstrap`, `install`) would not start here, if they
|
|
117
|
+
* would not: they run as `sudo -H npx …`, and `sudo` resolves `npx` on its
|
|
118
|
+
* secure_path, so a `node` that only nvm (or fnm, volta, asdf) installed for
|
|
119
|
+
* this user is not there. Said when the user is about to need root — the
|
|
120
|
+
* app's own runs are fine on nvm's node.
|
|
121
|
+
*/
|
|
122
|
+
export async function rootNodeProblem(host) {
|
|
123
|
+
const found = (await host.exec('sh', ['-c', 'command -v node'], OUTSIDE)).stdout.trim();
|
|
124
|
+
if (!found || !isUserNode(found))
|
|
125
|
+
return undefined;
|
|
126
|
+
for (const path of SYSTEM_NODES) {
|
|
127
|
+
const stat = await host.stat(path);
|
|
128
|
+
if (stat?.kind === 'file' || stat?.kind === 'symlink')
|
|
129
|
+
return undefined;
|
|
130
|
+
}
|
|
131
|
+
return (`node here is ${found}, a per-user install (nvm, fnm, volta or asdf): root's command runs \`sudo -H npx …\`, ` +
|
|
132
|
+
'and sudo does not see it ("npx: command not found"). Install a system Node first, once, as an administrator: ' +
|
|
133
|
+
'curl -fsSL https://deb.nodesource.com/setup_24.x | sudo -E bash - && sudo apt-get install -y nodejs ' +
|
|
134
|
+
'(your nvm node keeps running the app)');
|
|
135
|
+
}
|
|
109
136
|
/** The pnpm version the lockfile records for `packageManager` (`packageManagerDependencies`), if any. */
|
|
110
137
|
export function lockedPnpm(lockfile) {
|
|
111
138
|
const at = lockfile.indexOf('packageManagerDependencies:');
|
package/dist/cli.js
CHANGED
|
@@ -9,8 +9,12 @@ import { jsonHost } from './json-host.js';
|
|
|
9
9
|
import { isErrorCode, RUN_ID } from './protocol.js';
|
|
10
10
|
import { attach, cancel, createRunLog, newRunId, pruneRunLogs } from './runs.js';
|
|
11
11
|
import { check } from './check.js';
|
|
12
|
+
import { rootNodeProblem } from './checks.js';
|
|
13
|
+
import { renderVhost } from './apache.js';
|
|
14
|
+
import { readEnv } from './env-step.js';
|
|
12
15
|
import { init } from './init.js';
|
|
13
|
-
import {
|
|
16
|
+
import { resolvePort } from './pm2.js';
|
|
17
|
+
import { applyOverrides, DeployConfigError, parseOverrides, validateConfig, vhostName } from './config.js';
|
|
14
18
|
import { DeployAbortedError, DeployError, detectPackageManager, INSTALL_COMMAND, resolveStateDir, rootInstallCommand } from './context.js';
|
|
15
19
|
import { buildInstallPlan, install, readInstallPlan } from './install-plan.js';
|
|
16
20
|
import { untrustedToolPaths, USER_NAME } from './trust.js';
|
|
@@ -37,6 +41,8 @@ As the app user, in the checkout (node node_modules/@basaltkit/deploy/dist/bin.j
|
|
|
37
41
|
install-plan [--out=<file>|-]
|
|
38
42
|
what install needs, as data (default <state dir>/install-plan.json);
|
|
39
43
|
prints the root command for install
|
|
44
|
+
vhost [--port=<n>] the Apache vhost install would write, for this checkout and the app's
|
|
45
|
+
port (stdout): a starting point for apache({ managed: false })
|
|
40
46
|
attach <runId> --json [--from-seq=<n>] [--follow]
|
|
41
47
|
the events of a run (run/env/rollback --json), from any seq
|
|
42
48
|
cancel <runId> [--first-only]
|
|
@@ -121,7 +127,7 @@ function parse(argv) {
|
|
|
121
127
|
}
|
|
122
128
|
return { command, args, values, switches };
|
|
123
129
|
}
|
|
124
|
-
const COMMANDS = ['init', 'check', 'plan', 'run', 'env', 'rollback', 'status', 'commits', 'install-plan', 'install', 'bootstrap', 'attach', 'cancel', 'ui'];
|
|
130
|
+
const COMMANDS = ['init', 'check', 'plan', 'run', 'env', 'rollback', 'status', 'commits', 'install-plan', 'vhost', 'install', 'bootstrap', 'attach', 'cancel', 'ui'];
|
|
125
131
|
/** The commands that take the deploy lock, and so write a run log under --json. */
|
|
126
132
|
const LOCKED = new Set(['run', 'env', 'rollback']);
|
|
127
133
|
const usage = (message, hint) => new DeployError(message, [], 'usage', hint);
|
|
@@ -158,11 +164,38 @@ async function writeInstallPlan(host, ctx, cwd, out) {
|
|
|
158
164
|
host.out.ok(`install plan written to ${path} (data only: root validates it, never runs your code)`);
|
|
159
165
|
host.out.info(`root will: give ${ctx.stateDir.startsWith('/var/lib/basalt/') ? ctx.stateDir : `/var/lib/basalt/${plan.app}`} to you (0700)${plan.envFiles.length ? `, give ${plan.envFiles.join(', ')} to you (0600)` : ''}${plan.proxy.kind !== 'none' && plan.proxy.managed ? `, write the ${plan.proxy.kind} site for ${plan.domain} → 127.0.0.1:${plan.port}` : ''}`);
|
|
160
166
|
const user = host.env['USER'] && USER_NAME.test(host.env['USER']) ? host.env['USER'] : '<this user>';
|
|
167
|
+
const rootNode = await rootNodeProblem(host);
|
|
168
|
+
if (rootNode)
|
|
169
|
+
host.out.warn(rootNode);
|
|
161
170
|
host.out.info('then, as an administrator (a pinned copy root owns, never this checkout\'s):');
|
|
162
171
|
host.out.info(` ${rootInstallCommand(VERSION, path, user)}`);
|
|
163
172
|
host.out.result?.('install-plan', { plan, path, rootCommand: rootInstallCommand(VERSION, path, user) });
|
|
164
173
|
return 0;
|
|
165
174
|
}
|
|
175
|
+
/**
|
|
176
|
+
* `vhost`: the Apache vhost install would write, rendered for this checkout's
|
|
177
|
+
* path and the app's port, on stdout. For an app that keeps its own vhost
|
|
178
|
+
* (`managed: false`): a vhost copied from an example names someone else's
|
|
179
|
+
* checkout (/var/www/…) and port, and the preflight then reports the mismatch
|
|
180
|
+
* only at the first deploy.
|
|
181
|
+
*/
|
|
182
|
+
async function printVhost(ctx, given) {
|
|
183
|
+
if (ctx.config.proxy?.kind !== 'apache') {
|
|
184
|
+
throw usage(`vhost renders an Apache vhost; this config's proxy is ${ctx.config.proxy?.kind ?? 'none'}`);
|
|
185
|
+
}
|
|
186
|
+
let port;
|
|
187
|
+
if (given !== undefined) {
|
|
188
|
+
port = Number(given);
|
|
189
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
190
|
+
throw usage(`--port=${given} is not a port`);
|
|
191
|
+
}
|
|
192
|
+
else {
|
|
193
|
+
port = await resolvePort(ctx, envValues(await readEnv(ctx)));
|
|
194
|
+
}
|
|
195
|
+
process.stdout.write(renderVhost(ctx, port));
|
|
196
|
+
ctx.host.out.info(`rendered for ${ctx.dir}, port ${port}, ${ctx.config.domain}: save it as /etc/apache2/sites-available/${vhostName(ctx.config) ?? `${ctx.config.app}.conf`}, then a2ensite and reload`);
|
|
197
|
+
return 0;
|
|
198
|
+
}
|
|
166
199
|
/** Loads deploy.config.ts with the app's own tsx when it has one, else Node's type stripping. */
|
|
167
200
|
export async function loadConfig(dir, file) {
|
|
168
201
|
const path = isAbsolute(file) ? file : resolve(dir, file);
|
|
@@ -377,8 +410,8 @@ function checkFlags(flags, json, env) {
|
|
|
377
410
|
if (version !== undefined && version !== '1')
|
|
378
411
|
throw new DeployError(`--json=${version}: this basalt-deploy ${VERSION} speaks protocol 1`, [], 'protocol-version');
|
|
379
412
|
const { command } = flags;
|
|
380
|
-
if (command === 'init' || command === 'install' || command === 'bootstrap' || command === 'ui') {
|
|
381
|
-
const why = command === 'init' ? 'it writes code into the checkout' : command === 'ui' ? 'it only prints how to start the local UI, which runs on the operator\'s machine' : 'root\'s confirmations are the control, never a pipe';
|
|
413
|
+
if (command === 'init' || command === 'install' || command === 'bootstrap' || command === 'ui' || command === 'vhost') {
|
|
414
|
+
const why = command === 'init' ? 'it writes code into the checkout' : command === 'ui' ? 'it only prints how to start the local UI, which runs on the operator\'s machine' : command === 'vhost' ? 'its output is the vhost file itself' : 'root\'s confirmations are the control, never a pipe';
|
|
382
415
|
throw new DeployError(`${command} does not speak --json: ${why}`, [], 'unsupported');
|
|
383
416
|
}
|
|
384
417
|
if (flags.switches.has('help') || !command || !COMMANDS.includes(command))
|
|
@@ -547,6 +580,7 @@ async function session(flags, host, cwd, reporter, machine) {
|
|
|
547
580
|
case 'status': return await status(ctx);
|
|
548
581
|
case 'commits': return await commitsCommand(ctx, commitsRequest(flags));
|
|
549
582
|
case 'install-plan': return await writeInstallPlan(host, ctx, cwd, flags.values.get('out'));
|
|
583
|
+
case 'vhost': return await printVhost(ctx, flags.values.get('port'));
|
|
550
584
|
case 'attach': {
|
|
551
585
|
const runId = flags.args[0];
|
|
552
586
|
const exit = await attach(host, ctx.stateDir, runId, {
|
package/dist/config.d.ts
CHANGED
|
@@ -311,8 +311,12 @@ export interface SeaweedfsService<E extends object = EnvShape> {
|
|
|
311
311
|
image: string;
|
|
312
312
|
/** Host port on 127.0.0.1 for the S3 API; `auto` keeps the running container's, else the `.env` endpoint's, else the first free from 8333. */
|
|
313
313
|
port: number | 'auto';
|
|
314
|
-
/**
|
|
315
|
-
|
|
314
|
+
/**
|
|
315
|
+
* The access key a new store gets. @default a random 20-character key,
|
|
316
|
+
* generated with the store (it used to be the app's name, which then
|
|
317
|
+
* looked like a secret wherever the name appeared).
|
|
318
|
+
*/
|
|
319
|
+
accessKey?: string;
|
|
316
320
|
buckets: Bucket[];
|
|
317
321
|
/** The `.env` keys that receive the endpoint and the credentials. */
|
|
318
322
|
keys: S3Keys<E>;
|
package/dist/config.js
CHANGED
|
@@ -103,7 +103,7 @@ export function dockerInfra(app, options = {}) {
|
|
|
103
103
|
}
|
|
104
104
|
if (options.seaweedfs !== false && options.seaweedfs !== undefined) {
|
|
105
105
|
infra.seaweedfs = {
|
|
106
|
-
image: SEAWEEDFS_IMAGE, port: 'auto',
|
|
106
|
+
image: SEAWEEDFS_IMAGE, port: 'auto', buckets: [],
|
|
107
107
|
keys: { ...DEFAULT_S3_KEYS },
|
|
108
108
|
...options.seaweedfs,
|
|
109
109
|
};
|
package/dist/env-check.d.ts
CHANGED
|
@@ -5,6 +5,14 @@ export interface SchemaResult {
|
|
|
5
5
|
trueKeys: string[];
|
|
6
6
|
}
|
|
7
7
|
export declare function checkSchema(ctx: DeployContext, values: Map<string, string>): Promise<SchemaResult>;
|
|
8
|
+
/**
|
|
9
|
+
* What the app's own schema says about one answer, while it can still be
|
|
10
|
+
* asked again: a 31-character token the schema wants at 32 used to pass the
|
|
11
|
+
* question and fail only at validate, after everything else was answered.
|
|
12
|
+
* Only the issues of `key` count (the other keys may not be set yet), and a
|
|
13
|
+
* schema that cannot be loaded says nothing here: validate reports it.
|
|
14
|
+
*/
|
|
15
|
+
export declare function answerProblem(ctx: DeployContext, key: string, value: string, values: Map<string, string>): Promise<string | undefined>;
|
|
8
16
|
/**
|
|
9
17
|
* C6 — a value written to turn something OFF that the schema reads as ON.
|
|
10
18
|
* `z.coerce.boolean()` is `Boolean(string)`: every non-empty string is true,
|
package/dist/env-check.js
CHANGED
|
@@ -55,6 +55,30 @@ export async function checkSchema(ctx, values) {
|
|
|
55
55
|
})),
|
|
56
56
|
};
|
|
57
57
|
}
|
|
58
|
+
/**
|
|
59
|
+
* What the app's own schema says about one answer, while it can still be
|
|
60
|
+
* asked again: a 31-character token the schema wants at 32 used to pass the
|
|
61
|
+
* question and fail only at validate, after everything else was answered.
|
|
62
|
+
* Only the issues of `key` count (the other keys may not be set yet), and a
|
|
63
|
+
* schema that cannot be loaded says nothing here: validate reports it.
|
|
64
|
+
*/
|
|
65
|
+
export async function answerProblem(ctx, key, value, values) {
|
|
66
|
+
const schema = ctx.config.env.schema;
|
|
67
|
+
if (!schema)
|
|
68
|
+
return undefined;
|
|
69
|
+
const result = await checkSchema(ctx, new Map([...values, [key, value]]));
|
|
70
|
+
const prefix = `${schema}: `;
|
|
71
|
+
for (const finding of result.findings) {
|
|
72
|
+
if (!finding.message.startsWith(prefix))
|
|
73
|
+
continue;
|
|
74
|
+
const issue = finding.message.slice(prefix.length);
|
|
75
|
+
if (issue.startsWith(`${key}: `))
|
|
76
|
+
return issue.slice(key.length + 2);
|
|
77
|
+
if (issue.startsWith(`${key}.`))
|
|
78
|
+
return issue.slice(key.length + 1);
|
|
79
|
+
}
|
|
80
|
+
return undefined;
|
|
81
|
+
}
|
|
58
82
|
const FALSY = new Set(['0', 'false', 'no', 'off']);
|
|
59
83
|
/**
|
|
60
84
|
* C6 — a value written to turn something OFF that the schema reads as ON.
|
package/dist/env-step.js
CHANGED
|
@@ -1,6 +1,7 @@
|
|
|
1
1
|
import { basename, dirname, join, resolve } from 'node:path';
|
|
2
2
|
import { definedEntries } from './config.js';
|
|
3
3
|
import { applyEnvChanges, envValues, formatValue, parseEnv, UnwritableValueError } from './dotenv.js';
|
|
4
|
+
import { answerProblem } from './env-check.js';
|
|
4
5
|
/** The `.env`: relative to the checkout, or absolute (`/etc/<app>/api.env`). */
|
|
5
6
|
export const envFile = (ctx) => resolve(ctx.dir, ctx.config.env.file ?? '.env');
|
|
6
7
|
/** Its exact copies (`env.mirror`), resolved the same way. */
|
|
@@ -82,13 +83,21 @@ export async function answerQuestions(ctx, plan, options = {}) {
|
|
|
82
83
|
}
|
|
83
84
|
try {
|
|
84
85
|
formatValue(value, key);
|
|
85
|
-
answer = value;
|
|
86
86
|
}
|
|
87
87
|
catch (error) {
|
|
88
88
|
if (!(error instanceof UnwritableValueError))
|
|
89
89
|
throw error;
|
|
90
90
|
ctx.host.out.warn(error.message);
|
|
91
|
+
continue;
|
|
92
|
+
}
|
|
93
|
+
// An optional question left empty is the app's own choice to run without it.
|
|
94
|
+
const problem = value === '' ? undefined : await answerProblem(ctx, key, value, plan.values);
|
|
95
|
+
if (problem !== undefined) {
|
|
96
|
+
// The schema's message names the rule, never the value (a secret stays unechoed).
|
|
97
|
+
ctx.host.out.warn(`${key}: ${problem} — try again`);
|
|
98
|
+
continue;
|
|
91
99
|
}
|
|
100
|
+
answer = value;
|
|
92
101
|
}
|
|
93
102
|
if (answer === undefined) {
|
|
94
103
|
if (!question.optional) {
|
package/dist/events.d.ts
CHANGED
|
@@ -62,8 +62,18 @@ export declare class Redactor {
|
|
|
62
62
|
private sorted;
|
|
63
63
|
/** Keys whose value is too short to be matched. */
|
|
64
64
|
readonly short: Set<string>;
|
|
65
|
-
/**
|
|
66
|
-
|
|
65
|
+
/** Values known to be public: never learnt, whatever key holds them. */
|
|
66
|
+
private readonly allowed;
|
|
67
|
+
/**
|
|
68
|
+
* Marks a value as public: the app's name, which the container, the
|
|
69
|
+
* database user and the state path all carry. A key that happens to hold
|
|
70
|
+
* it (an S3 access key that defaulted to the app name, `BASALT_PG_USER`)
|
|
71
|
+
* would otherwise make every line that names the app unreadable. Forgets
|
|
72
|
+
* the value if it was learnt before the config was known.
|
|
73
|
+
*/
|
|
74
|
+
allow(value: string): void;
|
|
75
|
+
/** `short` when the value is too short to match; `public` when {@link allow}ed; `added` or `known` otherwise. */
|
|
76
|
+
add(key: string, value: string): 'added' | 'known' | 'short' | 'empty' | 'public';
|
|
67
77
|
get size(): number;
|
|
68
78
|
/** The length of the longest needle: a cut can split at most `longest - 1` characters of one. */
|
|
69
79
|
get longest(): number;
|
package/dist/events.js
CHANGED
|
@@ -138,10 +138,30 @@ export class Redactor {
|
|
|
138
138
|
sorted;
|
|
139
139
|
/** Keys whose value is too short to be matched. */
|
|
140
140
|
short = new Set();
|
|
141
|
-
/**
|
|
141
|
+
/** Values known to be public: never learnt, whatever key holds them. */
|
|
142
|
+
allowed = new Set();
|
|
143
|
+
/**
|
|
144
|
+
* Marks a value as public: the app's name, which the container, the
|
|
145
|
+
* database user and the state path all carry. A key that happens to hold
|
|
146
|
+
* it (an S3 access key that defaulted to the app name, `BASALT_PG_USER`)
|
|
147
|
+
* would otherwise make every line that names the app unreadable. Forgets
|
|
148
|
+
* the value if it was learnt before the config was known.
|
|
149
|
+
*/
|
|
150
|
+
allow(value) {
|
|
151
|
+
if (value === '')
|
|
152
|
+
return;
|
|
153
|
+
this.allowed.add(value);
|
|
154
|
+
for (const form of [value, encodeURIComponent(value)]) {
|
|
155
|
+
if (this.needles.delete(form))
|
|
156
|
+
this.sorted = undefined;
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
/** `short` when the value is too short to match; `public` when {@link allow}ed; `added` or `known` otherwise. */
|
|
142
160
|
add(key, value) {
|
|
143
161
|
if (value === '')
|
|
144
162
|
return 'empty';
|
|
163
|
+
if (this.allowed.has(value))
|
|
164
|
+
return 'public';
|
|
145
165
|
if (value.length < MIN_REDACTED_LENGTH) {
|
|
146
166
|
if (this.short.has(key))
|
|
147
167
|
return 'known';
|
package/dist/infra.js
CHANGED
|
@@ -153,14 +153,14 @@ export async function planInfra(ctx, values) {
|
|
|
153
153
|
let secretKey = running?.env.get('AWS_SECRET_ACCESS_KEY');
|
|
154
154
|
let source = 'container';
|
|
155
155
|
if ((!accessKey || !secretKey) && values.get(sw.keys.secretKey)) {
|
|
156
|
-
accessKey = values.get(sw.keys.accessKey) || sw.accessKey;
|
|
156
|
+
accessKey = values.get(sw.keys.accessKey) || sw.accessKey || ctx.host.randomHex(10);
|
|
157
157
|
secretKey = values.get(sw.keys.secretKey);
|
|
158
158
|
source = 'env';
|
|
159
159
|
}
|
|
160
160
|
// Not kept in the data (unlike Postgres): an old volume opens with new
|
|
161
161
|
// credentials, and the objects stay readable — verified, RFC 0010 §2.
|
|
162
162
|
if (!accessKey || !secretKey) {
|
|
163
|
-
accessKey = sw.accessKey;
|
|
163
|
+
accessKey = sw.accessKey ?? ctx.host.randomHex(10);
|
|
164
164
|
secretKey = ctx.host.randomHex(24);
|
|
165
165
|
source = 'generated';
|
|
166
166
|
}
|
package/dist/init.d.ts
CHANGED
|
@@ -48,9 +48,14 @@ export interface ProjectFacts {
|
|
|
48
48
|
buildScript: string | undefined;
|
|
49
49
|
web: string | undefined;
|
|
50
50
|
compose: ComposeFact | undefined;
|
|
51
|
+
/**
|
|
52
|
+
* With `--server`: the Apache vhosts serving the domain, the ports taken
|
|
53
|
+
* (3000–3099), and the loopback port those vhosts already proxy to.
|
|
54
|
+
*/
|
|
51
55
|
server: {
|
|
52
56
|
vhosts: string[];
|
|
53
57
|
busyPorts: number[];
|
|
58
|
+
proxyPort?: number;
|
|
54
59
|
} | undefined;
|
|
55
60
|
/** `/readyz` when the app declares one (readiness: database and dependencies), else `/health`. */
|
|
56
61
|
health: '/readyz' | '/health';
|
package/dist/init.js
CHANGED
|
@@ -261,17 +261,30 @@ async function detectCompose(host, dir, file, app) {
|
|
|
261
261
|
}
|
|
262
262
|
async function detectServer(host, domain) {
|
|
263
263
|
const vhosts = [];
|
|
264
|
+
const proxied = new Set();
|
|
264
265
|
for (const name of (await host.list('/etc/apache2/sites-available').catch(() => [])).sort()) {
|
|
265
266
|
if (!name.endsWith('.conf'))
|
|
266
267
|
continue;
|
|
267
268
|
const text = await host.readFile(`/etc/apache2/sites-available/${name}`);
|
|
268
269
|
const served = [...(text ?? '').matchAll(/^\s*Server(?:Name|Alias)\s+(.+)$/gim)].flatMap((m) => m[1].trim().split(/\s+/));
|
|
269
|
-
if (served.some((h) => h === domain || h === `*.${domain}`))
|
|
270
|
-
|
|
270
|
+
if (!served.some((h) => h === domain || h === `*.${domain}`))
|
|
271
|
+
continue;
|
|
272
|
+
vhosts.push(name);
|
|
273
|
+
for (const m of (text ?? '').matchAll(/^\s*ProxyPass(?:Reverse)?\s+\S+\s+(?:https?|ws):\/\/(?:127\.0\.0\.1|localhost):(\d+)/gim))
|
|
274
|
+
proxied.add(Number(m[1]));
|
|
271
275
|
}
|
|
272
276
|
const ss = await host.exec('ss', ['-ltnH'], {});
|
|
273
277
|
const busyPorts = [...new Set([...ss.stdout.matchAll(/:(\d+)\s/g)].map((m) => Number(m[1])).filter((p) => p >= 3000 && p < 3100))].sort((a, b) => a - b);
|
|
274
|
-
|
|
278
|
+
// One port across the vhosts is the app's; several (an API and a share
|
|
279
|
+
// service) is not a guess init makes.
|
|
280
|
+
return { vhosts, busyPorts, ...(proxied.size === 1 ? { proxyPort: [...proxied][0] } : {}) };
|
|
281
|
+
}
|
|
282
|
+
/** The first port from 3000 that nothing listens on (3000–3099, as `ss` saw it). */
|
|
283
|
+
function firstFreePort(busy) {
|
|
284
|
+
for (let port = 3000; port < 3100; port++)
|
|
285
|
+
if (!busy.includes(port))
|
|
286
|
+
return port;
|
|
287
|
+
return undefined;
|
|
275
288
|
}
|
|
276
289
|
function parseJson(text) {
|
|
277
290
|
if (text === undefined)
|
|
@@ -381,8 +394,21 @@ export function renderConfig(facts, answers) {
|
|
|
381
394
|
}
|
|
382
395
|
else {
|
|
383
396
|
helpers.add('pm2');
|
|
384
|
-
const
|
|
385
|
-
|
|
397
|
+
const server = facts.server;
|
|
398
|
+
const avoid = server?.busyPorts ?? [];
|
|
399
|
+
// Behind Apache the vhost names the port, and it is written before the
|
|
400
|
+
// first deploy: an `auto` port picked then may not be the one it says.
|
|
401
|
+
// So pin it: the one the vhost already proxies to, else one free now.
|
|
402
|
+
const pinned = answers.proxy === 'apache' && server ? (server.proxyPort ?? firstFreePort(avoid)) : undefined;
|
|
403
|
+
if (pinned !== undefined) {
|
|
404
|
+
const note = server?.proxyPort !== undefined
|
|
405
|
+
? `the port ${server.vhosts.join(', ')} proxies to`
|
|
406
|
+
: `free on this server now: your vhost proxies to 127.0.0.1:${pinned}`;
|
|
407
|
+
lines.push(` runtime: pm2({ port: ${pinned} }), // ${note}`);
|
|
408
|
+
}
|
|
409
|
+
else {
|
|
410
|
+
lines.push(` runtime: pm2(${avoid.length ? `{ avoid: [${avoid.join(', ')}] }` : ''}),${avoid.length ? ' // ports already taken on this server' : ''}`);
|
|
411
|
+
}
|
|
386
412
|
}
|
|
387
413
|
if (answers.proxy === 'caddy') {
|
|
388
414
|
helpers.add('caddy');
|
|
@@ -444,27 +470,35 @@ export async function init(host, dir, flags, switches) {
|
|
|
444
470
|
host.out.error(`${file} already exists — init never overwrites it (--force to replace it)`);
|
|
445
471
|
return 1;
|
|
446
472
|
}
|
|
447
|
-
|
|
473
|
+
// host.prompt adds the ": " itself. With `choices`, a terminal answer outside
|
|
474
|
+
// them is asked again (a typo must not abort init); a flag is never re-asked.
|
|
475
|
+
const answer = async (key, question, fallback, choices) => {
|
|
448
476
|
const given = flags.get(key);
|
|
449
477
|
if (given !== undefined)
|
|
450
478
|
return given;
|
|
451
479
|
if (!host.interactive())
|
|
452
480
|
return fallback;
|
|
453
|
-
|
|
454
|
-
|
|
481
|
+
for (let attempt = 0; attempt < 3; attempt += 1) {
|
|
482
|
+
const typed = (await host.prompt(`${question}${fallback ? ` [${fallback}]` : ''}`, { secret: false }))?.trim();
|
|
483
|
+
const value = typed || fallback;
|
|
484
|
+
if (!choices || value === undefined || choices.includes(value))
|
|
485
|
+
return value;
|
|
486
|
+
host.out.warn(`"${value}" is not one of: ${choices.join(', ')}`);
|
|
487
|
+
}
|
|
488
|
+
return undefined;
|
|
455
489
|
};
|
|
456
490
|
const domain = await answer('domain', 'Domain the app answers on (e.g. acme.example.ao)');
|
|
457
491
|
if (!domain || !/^[a-z0-9.-]+\.[a-z]{2,}$/.test(domain)) {
|
|
458
492
|
host.out.error(`--domain=<host> is required${domain ? `: "${domain}" is not a host name` : ''}`);
|
|
459
493
|
return 1;
|
|
460
494
|
}
|
|
461
|
-
const tenants = await answer('tenants',
|
|
495
|
+
const tenants = await answer('tenants', `Multi-tenant, each tenant on its own subdomain (<tenant>.${domain})? subdomain | none`, 'none', ['subdomain', 'none']);
|
|
462
496
|
if (tenants !== 'subdomain' && tenants !== 'none') {
|
|
463
497
|
host.out.error('--tenants is subdomain or none');
|
|
464
498
|
return 1;
|
|
465
499
|
}
|
|
466
500
|
const branch = (await answer('branch', 'Branch deployed', 'main')) ?? 'main';
|
|
467
|
-
const proxy = (await answer('proxy', 'Proxy on this server: apache | caddy | none', 'apache')) ?? 'apache';
|
|
501
|
+
const proxy = (await answer('proxy', 'Proxy on this server: apache | caddy | none', 'apache', ['apache', 'caddy', 'none'])) ?? 'apache';
|
|
468
502
|
if (proxy !== 'apache' && proxy !== 'caddy' && proxy !== 'none') {
|
|
469
503
|
host.out.error('--proxy is apache, caddy or none');
|
|
470
504
|
return 1;
|
package/dist/json-host.js
CHANGED
|
@@ -93,6 +93,8 @@ export function jsonHost(base, writer, redactor, options = {}) {
|
|
|
93
93
|
learn(pairs, given) { warnShort(learnSecrets(redactor, pairs, given ?? config)); },
|
|
94
94
|
watchEnv(next, dir) {
|
|
95
95
|
config = next;
|
|
96
|
+
// The app's name is everywhere in the output and never a secret.
|
|
97
|
+
redactor.allow(next.app);
|
|
96
98
|
envFiles.add(resolve(dir, next.env.file ?? '.env'));
|
|
97
99
|
for (const mirror of next.env.mirror ?? [])
|
|
98
100
|
envFiles.add(resolve(dir, mirror));
|