@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.
- package/LICENSE +21 -0
- package/README.md +125 -2
- package/dist/apache.d.ts +13 -0
- package/dist/apache.js +179 -0
- package/dist/backup.d.ts +13 -0
- package/dist/backup.js +51 -0
- package/dist/bin.d.ts +2 -0
- package/dist/bin.js +3 -0
- package/dist/checks.d.ts +13 -0
- package/dist/checks.js +99 -0
- package/dist/cli.d.ts +8 -0
- package/dist/cli.js +134 -0
- package/dist/config.d.ts +231 -0
- package/dist/config.js +163 -0
- package/dist/context.d.ts +34 -0
- package/dist/context.js +49 -0
- package/dist/diff.d.ts +2 -0
- package/dist/diff.js +33 -0
- package/dist/dotenv.d.ts +47 -0
- package/dist/dotenv.js +145 -0
- package/dist/env-check.d.ts +18 -0
- package/dist/env-check.js +95 -0
- package/dist/env-step.d.ts +29 -0
- package/dist/env-step.js +126 -0
- package/dist/host.d.ts +87 -0
- package/dist/host.js +199 -0
- package/dist/index.d.ts +11 -0
- package/dist/index.js +10 -0
- package/dist/infra.d.ts +42 -0
- package/dist/infra.js +242 -0
- package/dist/pipeline.d.ts +49 -0
- package/dist/pipeline.js +432 -0
- package/dist/pm2.d.ts +23 -0
- package/dist/pm2.js +110 -0
- package/dist/ports.d.ts +10 -0
- package/dist/ports.js +27 -0
- package/dist/state.d.ts +20 -0
- package/dist/state.js +34 -0
- package/package.json +48 -3
package/dist/host.js
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { randomBytes } from 'node:crypto';
|
|
3
|
+
import { constants, openSync, closeSync } from 'node:fs';
|
|
4
|
+
import { chmod, copyFile, lstat, mkdir, readFile, readdir, readlink, rename, rm, symlink, writeFile } from 'node:fs/promises';
|
|
5
|
+
import http from 'node:http';
|
|
6
|
+
import https from 'node:https';
|
|
7
|
+
import { dirname } from 'node:path';
|
|
8
|
+
import { createInterface } from 'node:readline';
|
|
9
|
+
import tls from 'node:tls';
|
|
10
|
+
export function consoleOutput(stream = process.stderr) {
|
|
11
|
+
const color = stream.isTTY && !process.env['NO_COLOR'];
|
|
12
|
+
const paint = (code, text) => (color ? `\u001b[${code}m${text}\u001b[0m` : text);
|
|
13
|
+
return {
|
|
14
|
+
step: (title) => stream.write(`\n${paint('1', `==> ${title}`)}\n`),
|
|
15
|
+
info: (message) => stream.write(` ${message}\n`),
|
|
16
|
+
ok: (message) => stream.write(` ${paint('32', 'ok')} ${message}\n`),
|
|
17
|
+
warn: (message) => stream.write(` ${paint('33', 'warning')} ${message}\n`),
|
|
18
|
+
error: (message) => stream.write(` ${paint('31', 'error')} ${message}\n`),
|
|
19
|
+
};
|
|
20
|
+
}
|
|
21
|
+
export function nodeHost(output = consoleOutput()) {
|
|
22
|
+
return {
|
|
23
|
+
out: output,
|
|
24
|
+
env: process.env,
|
|
25
|
+
uid: () => (typeof process.getuid === 'function' ? process.getuid() : -1),
|
|
26
|
+
interactive: () => Boolean(process.stdin.isTTY) && !process.env['CI'],
|
|
27
|
+
now: () => new Date(),
|
|
28
|
+
randomHex: (bytes) => randomBytes(bytes).toString('hex'),
|
|
29
|
+
sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
|
|
30
|
+
exec(command, args, options = {}) {
|
|
31
|
+
const base = options.inheritEnv === false
|
|
32
|
+
? { PATH: process.env['PATH'], HOME: process.env['HOME'] }
|
|
33
|
+
: { ...process.env };
|
|
34
|
+
for (const key of options.unset ?? [])
|
|
35
|
+
delete base[key];
|
|
36
|
+
const env = { ...base, ...options.env };
|
|
37
|
+
let fd;
|
|
38
|
+
if (options.stdoutFile) {
|
|
39
|
+
fd = openSync(options.stdoutFile, constants.O_WRONLY | constants.O_CREAT | constants.O_TRUNC, 0o600);
|
|
40
|
+
}
|
|
41
|
+
return new Promise((resolve) => {
|
|
42
|
+
let stdout = '';
|
|
43
|
+
let stderr = '';
|
|
44
|
+
const child = spawn(command, args, {
|
|
45
|
+
cwd: options.cwd,
|
|
46
|
+
env,
|
|
47
|
+
stdio: options.stream ? ['ignore', 'inherit', 'inherit'] : ['ignore', fd ?? 'pipe', 'pipe'],
|
|
48
|
+
});
|
|
49
|
+
child.stdout?.on('data', (chunk) => { stdout += chunk.toString(); });
|
|
50
|
+
child.stderr?.on('data', (chunk) => { stderr += chunk.toString(); });
|
|
51
|
+
const done = (code) => {
|
|
52
|
+
if (fd !== undefined)
|
|
53
|
+
closeSync(fd);
|
|
54
|
+
resolve({ code, stdout, stderr });
|
|
55
|
+
};
|
|
56
|
+
child.on('error', (error) => { stderr += error.message; done(127); });
|
|
57
|
+
child.on('close', (code) => done(code ?? 1));
|
|
58
|
+
});
|
|
59
|
+
},
|
|
60
|
+
async readFile(path) {
|
|
61
|
+
try {
|
|
62
|
+
return await readFile(path, 'utf8');
|
|
63
|
+
}
|
|
64
|
+
catch {
|
|
65
|
+
return undefined;
|
|
66
|
+
}
|
|
67
|
+
},
|
|
68
|
+
async writeFile(path, content, mode = 0o644) {
|
|
69
|
+
const temp = `${path}.basalt-${randomBytes(4).toString('hex')}`;
|
|
70
|
+
await writeFile(temp, content, { mode, flag: 'wx' });
|
|
71
|
+
await chmod(temp, mode);
|
|
72
|
+
await rename(temp, path);
|
|
73
|
+
},
|
|
74
|
+
async copyFile(from, to, mode) {
|
|
75
|
+
await copyFile(from, to);
|
|
76
|
+
if (mode !== undefined)
|
|
77
|
+
await chmod(to, mode);
|
|
78
|
+
},
|
|
79
|
+
async exists(path) {
|
|
80
|
+
try {
|
|
81
|
+
await lstat(path);
|
|
82
|
+
return true;
|
|
83
|
+
}
|
|
84
|
+
catch {
|
|
85
|
+
return false;
|
|
86
|
+
}
|
|
87
|
+
},
|
|
88
|
+
async stat(path) {
|
|
89
|
+
try {
|
|
90
|
+
const s = await lstat(path);
|
|
91
|
+
const kind = s.isSymbolicLink() ? 'symlink' : s.isFile() ? 'file' : s.isDirectory() ? 'dir' : 'other';
|
|
92
|
+
return { kind, size: s.size };
|
|
93
|
+
}
|
|
94
|
+
catch {
|
|
95
|
+
return undefined;
|
|
96
|
+
}
|
|
97
|
+
},
|
|
98
|
+
async readlink(path) {
|
|
99
|
+
try {
|
|
100
|
+
return await readlink(path);
|
|
101
|
+
}
|
|
102
|
+
catch {
|
|
103
|
+
return undefined;
|
|
104
|
+
}
|
|
105
|
+
},
|
|
106
|
+
symlink: (target, path) => symlink(target, path),
|
|
107
|
+
async mkdir(path, mode) {
|
|
108
|
+
await mkdir(path, { recursive: true, ...(mode === undefined ? {} : { mode }) });
|
|
109
|
+
},
|
|
110
|
+
remove: (path) => rm(path, { force: true, recursive: true }),
|
|
111
|
+
async list(dir) {
|
|
112
|
+
try {
|
|
113
|
+
return await readdir(dir);
|
|
114
|
+
}
|
|
115
|
+
catch {
|
|
116
|
+
return [];
|
|
117
|
+
}
|
|
118
|
+
},
|
|
119
|
+
async prompt(question, { secret }) {
|
|
120
|
+
if (!process.stdin.isTTY || process.env['CI'])
|
|
121
|
+
return undefined;
|
|
122
|
+
// The question and the echo go to stderr: anything a prompt writes to
|
|
123
|
+
// stdout can end up inside a captured value (RFC 0006 §A, incident 5).
|
|
124
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr, terminal: true });
|
|
125
|
+
if (secret) {
|
|
126
|
+
const writer = rl;
|
|
127
|
+
let asked = false;
|
|
128
|
+
writer._writeToOutput = (s) => {
|
|
129
|
+
if (!asked) {
|
|
130
|
+
process.stderr.write(s);
|
|
131
|
+
asked = true;
|
|
132
|
+
}
|
|
133
|
+
};
|
|
134
|
+
}
|
|
135
|
+
const answer = await new Promise((resolve) => rl.question(` ${question}: `, resolve));
|
|
136
|
+
rl.close();
|
|
137
|
+
if (secret)
|
|
138
|
+
process.stderr.write('\n');
|
|
139
|
+
return answer.trim();
|
|
140
|
+
},
|
|
141
|
+
async confirm(question) {
|
|
142
|
+
if (!process.stdin.isTTY || process.env['CI'])
|
|
143
|
+
return false;
|
|
144
|
+
const rl = createInterface({ input: process.stdin, output: process.stderr });
|
|
145
|
+
const answer = await new Promise((resolve) => rl.question(` ${question} [y/N] `, resolve));
|
|
146
|
+
rl.close();
|
|
147
|
+
return /^y(es)?$/i.test(answer.trim());
|
|
148
|
+
},
|
|
149
|
+
tlsCertificate(servername) {
|
|
150
|
+
return new Promise((resolve) => {
|
|
151
|
+
// The chain is verified as for any client: an untrusted or expired
|
|
152
|
+
// certificate fails the handshake and is reported by its code. Only
|
|
153
|
+
// the NAME check is ours — it records the certificate instead of
|
|
154
|
+
// refusing it, because which names it covers is what we report (C8).
|
|
155
|
+
// Nothing is sent over the connection either way.
|
|
156
|
+
let names = [];
|
|
157
|
+
const socket = tls.connect({
|
|
158
|
+
host: servername, port: 443, servername, timeout: 10_000,
|
|
159
|
+
checkServerIdentity: (_host, cert) => {
|
|
160
|
+
names = (cert.subjectaltname ?? '')
|
|
161
|
+
.split(',')
|
|
162
|
+
.map((entry) => entry.trim())
|
|
163
|
+
.filter((entry) => entry.startsWith('DNS:'))
|
|
164
|
+
.map((entry) => entry.slice(4).toLowerCase());
|
|
165
|
+
return undefined;
|
|
166
|
+
},
|
|
167
|
+
});
|
|
168
|
+
const finish = (value) => { socket.destroy(); resolve(value); };
|
|
169
|
+
socket.once('secureConnect', () => {
|
|
170
|
+
finish({ names, validTo: new Date(socket.getPeerCertificate().valid_to), trusted: true });
|
|
171
|
+
});
|
|
172
|
+
socket.once('timeout', () => finish({ error: 'timed out' }));
|
|
173
|
+
socket.once('error', (error) => {
|
|
174
|
+
const code = error.code ?? '';
|
|
175
|
+
finish({ error: /CERT|SELF_SIGNED|UNABLE_TO|VERIFY/.test(code) ? `certificate not trusted by browsers (${code})` : error.message });
|
|
176
|
+
});
|
|
177
|
+
});
|
|
178
|
+
},
|
|
179
|
+
httpGet(url, options = {}) {
|
|
180
|
+
return new Promise((resolve) => {
|
|
181
|
+
const target = new URL(url);
|
|
182
|
+
const client = target.protocol === 'https:' ? https : http;
|
|
183
|
+
const request = client.request(target, {
|
|
184
|
+
method: 'GET',
|
|
185
|
+
headers: options.host ? { host: options.host } : {},
|
|
186
|
+
timeout: options.timeoutMs ?? 5_000,
|
|
187
|
+
}, (response) => {
|
|
188
|
+
response.resume();
|
|
189
|
+
resolve({ status: response.statusCode ?? 0 });
|
|
190
|
+
});
|
|
191
|
+
request.on('timeout', () => request.destroy(new Error('timed out')));
|
|
192
|
+
request.on('error', (error) => resolve({ error: error.message }));
|
|
193
|
+
request.end();
|
|
194
|
+
});
|
|
195
|
+
},
|
|
196
|
+
};
|
|
197
|
+
}
|
|
198
|
+
/** `mkdir -p` of the parent, for writers that create a file in a directory that may not exist. */
|
|
199
|
+
export const parentOf = (path) => dirname(path);
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
export { defineDeploy, secret, ask, pm2, apache, none, external, dockerInfra, validateConfig, applyOverrides, parseOverrides, processName, DeployConfigError, MINIO_IMAGE, type DeployConfig, type EnvConfig, type DeriveContext, type SecretSpec, type Question, type InfraConfig, type DockerInfra, type DockerInfraOptions, type ExternalInfra, type PostgresService, type RedisService, type MinioService, type BuildConfig, type MigrateConfig, type BackupConfig, type RuntimeConfig, type Pm2Runtime, type ProxyConfig, type ApacheProxy, type NoProxy, type HealthConfig, type ServerOverrides, } from './config.js';
|
|
2
|
+
export { main, loadConfig, createContext, USAGE } from './cli.js';
|
|
3
|
+
export { nodeHost, consoleOutput, type Host, type ExecOptions, type ExecResult, type Output, type TlsCertificate } from './host.js';
|
|
4
|
+
export { DeployError, type DeployContext, type Finding } from './context.js';
|
|
5
|
+
export { parseEnv, applyEnvChanges, formatValue, envValues, UnwritableValueError, type EnvDocument, type EnvChange } from './dotenv.js';
|
|
6
|
+
export { renderVhost, proxiedPorts } from './apache.js';
|
|
7
|
+
export { renderCompose } from './infra.js';
|
|
8
|
+
export { coercionFindings } from './env-check.js';
|
|
9
|
+
export { covers } from './checks.js';
|
|
10
|
+
export { plan, run, envCommand, rollback, status, install, preflight, SKIPPABLE, type Skippable, type RunOptions } from './pipeline.js';
|
|
11
|
+
export type { Release } from './state.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export { defineDeploy, secret, ask, pm2, apache, none, external, dockerInfra, validateConfig, applyOverrides, parseOverrides, processName, DeployConfigError, MINIO_IMAGE, } from './config.js';
|
|
2
|
+
export { main, loadConfig, createContext, USAGE } from './cli.js';
|
|
3
|
+
export { nodeHost, consoleOutput } from './host.js';
|
|
4
|
+
export { DeployError } from './context.js';
|
|
5
|
+
export { parseEnv, applyEnvChanges, formatValue, envValues, UnwritableValueError } from './dotenv.js';
|
|
6
|
+
export { renderVhost, proxiedPorts } from './apache.js';
|
|
7
|
+
export { renderCompose } from './infra.js';
|
|
8
|
+
export { coercionFindings } from './env-check.js';
|
|
9
|
+
export { covers } from './checks.js';
|
|
10
|
+
export { plan, run, envCommand, rollback, status, install, preflight, SKIPPABLE } from './pipeline.js';
|
package/dist/infra.d.ts
ADDED
|
@@ -0,0 +1,42 @@
|
|
|
1
|
+
import type { DockerInfra } from './config.js';
|
|
2
|
+
import type { DeployContext, Finding } from './context.js';
|
|
3
|
+
import type { EnvChange } from './dotenv.js';
|
|
4
|
+
/**
|
|
5
|
+
* Dedicated containers, adopted or created (RFC 0006 §6.3).
|
|
6
|
+
*
|
|
7
|
+
* The running container is the truth: its credentials are read back and the
|
|
8
|
+
* `.env` follows them, never the other way round. A fresh password written over
|
|
9
|
+
* an initialised volume is exactly the `P1000` that cost a production deploy
|
|
10
|
+
* (incident 7) — Postgres and MinIO keep the first credentials in the data.
|
|
11
|
+
*
|
|
12
|
+
* Passwords never reach a command line (visible in `ps`) or the generated
|
|
13
|
+
* compose file: compose reads them from its own environment, and `docker exec
|
|
14
|
+
* -e NAME` (no value) copies them from the CLI's environment.
|
|
15
|
+
*/
|
|
16
|
+
export type ServiceName = 'postgres' | 'redis' | 'minio';
|
|
17
|
+
export interface ServicePlan {
|
|
18
|
+
service: ServiceName;
|
|
19
|
+
container: string;
|
|
20
|
+
volume: string;
|
|
21
|
+
action: 'adopt' | 'create';
|
|
22
|
+
port: number;
|
|
23
|
+
consolePort?: number;
|
|
24
|
+
user?: string;
|
|
25
|
+
database?: string;
|
|
26
|
+
/** Where the password came from — printed; the password itself never is. */
|
|
27
|
+
source: 'container' | 'env' | 'generated';
|
|
28
|
+
}
|
|
29
|
+
export interface InfraPlan {
|
|
30
|
+
services: ServicePlan[];
|
|
31
|
+
env: EnvChange[];
|
|
32
|
+
findings: Finding[];
|
|
33
|
+
/** Values compose interpolates (`${BASALT_PG_PASSWORD}`); passed in its environment only. */
|
|
34
|
+
secrets: Record<string, string>;
|
|
35
|
+
}
|
|
36
|
+
export declare function planInfra(ctx: DeployContext, values: Map<string, string>): Promise<InfraPlan>;
|
|
37
|
+
/** The compose file, with no secret in it: compose interpolates them from its environment. */
|
|
38
|
+
export declare function renderCompose(app: string, infra: DockerInfra, plan: InfraPlan): string;
|
|
39
|
+
export declare const composeFile: (ctx: DeployContext) => string;
|
|
40
|
+
/** Starts (or reconciles) the containers, waits for health, proves the credentials, creates the buckets. */
|
|
41
|
+
export declare function applyInfra(ctx: DeployContext, plan: InfraPlan): Promise<Finding[]>;
|
|
42
|
+
export declare function describeInfra(plan: InfraPlan): string[];
|
package/dist/infra.js
ADDED
|
@@ -0,0 +1,242 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { freePort } from './ports.js';
|
|
3
|
+
async function inspect(ctx, container) {
|
|
4
|
+
const result = await ctx.host.exec('docker', ['inspect', container, '--format', '{{json .Config.Env}}\t{{json .HostConfig.PortBindings}}']);
|
|
5
|
+
if (result.code !== 0)
|
|
6
|
+
return undefined;
|
|
7
|
+
const [envJson = '[]', portsJson = '{}'] = result.stdout.trim().split('\t');
|
|
8
|
+
const env = new Map();
|
|
9
|
+
for (const entry of JSON.parse(envJson)) {
|
|
10
|
+
const eq = entry.indexOf('=');
|
|
11
|
+
if (eq > 0)
|
|
12
|
+
env.set(entry.slice(0, eq), entry.slice(eq + 1));
|
|
13
|
+
}
|
|
14
|
+
const ports = new Map();
|
|
15
|
+
const bindings = (JSON.parse(portsJson) ?? {});
|
|
16
|
+
for (const [containerPort, hostPorts] of Object.entries(bindings)) {
|
|
17
|
+
const hostPort = Number(hostPorts?.[0]?.HostPort);
|
|
18
|
+
if (Number.isInteger(hostPort) && hostPort > 0)
|
|
19
|
+
ports.set(containerPort, hostPort);
|
|
20
|
+
}
|
|
21
|
+
return { env, ports };
|
|
22
|
+
}
|
|
23
|
+
async function volumeExists(ctx, volume) {
|
|
24
|
+
return (await ctx.host.exec('docker', ['volume', 'inspect', volume])).code === 0;
|
|
25
|
+
}
|
|
26
|
+
function urlParts(value) {
|
|
27
|
+
if (!value)
|
|
28
|
+
return undefined;
|
|
29
|
+
try {
|
|
30
|
+
const url = new URL(value);
|
|
31
|
+
if (url.hostname !== 'localhost' && url.hostname !== '127.0.0.1')
|
|
32
|
+
return undefined;
|
|
33
|
+
return {
|
|
34
|
+
user: decodeURIComponent(url.username),
|
|
35
|
+
password: decodeURIComponent(url.password),
|
|
36
|
+
port: Number(url.port),
|
|
37
|
+
database: url.pathname.replace(/^\//, ''),
|
|
38
|
+
};
|
|
39
|
+
}
|
|
40
|
+
catch {
|
|
41
|
+
return undefined;
|
|
42
|
+
}
|
|
43
|
+
}
|
|
44
|
+
const names = (app, service) => {
|
|
45
|
+
const suffix = service === 'postgres' ? 'pg' : service;
|
|
46
|
+
// Compose prefixes volumes with the project name — the app — so this is
|
|
47
|
+
// what an older compose file with the same project name already created.
|
|
48
|
+
return { container: `${app}-${suffix}`, volumeKey: `${app}-${suffix}-data`, volume: `${app}_${app}-${suffix}-data` };
|
|
49
|
+
};
|
|
50
|
+
export async function planInfra(ctx, values) {
|
|
51
|
+
const infra = ctx.config.infra;
|
|
52
|
+
const plan = { services: [], env: [], findings: [], secrets: {} };
|
|
53
|
+
if (infra?.kind !== 'docker')
|
|
54
|
+
return plan;
|
|
55
|
+
const { app } = ctx.config;
|
|
56
|
+
const picked = [];
|
|
57
|
+
const pick = async (wanted, existing, from) => {
|
|
58
|
+
const port = typeof wanted === 'number' ? wanted : existing ?? await freePort(ctx.host, from, [], picked);
|
|
59
|
+
picked.push(port);
|
|
60
|
+
return port;
|
|
61
|
+
};
|
|
62
|
+
const setEnv = (key, value, reason) => {
|
|
63
|
+
if (values.get(key) !== value)
|
|
64
|
+
plan.env.push({ kind: 'set', key, value, reason });
|
|
65
|
+
};
|
|
66
|
+
const unknownPassword = (service, volume) => ({
|
|
67
|
+
id: 'C7',
|
|
68
|
+
level: 'error',
|
|
69
|
+
message: `${service}: the volume ${volume} exists but no container and no .env value says which password it was initialised with`,
|
|
70
|
+
fix: `put the original credentials back in ${ctx.config.env.file ?? '.env'}, or — destroying that data — docker volume rm ${volume}`,
|
|
71
|
+
});
|
|
72
|
+
if (infra.postgres) {
|
|
73
|
+
const pg = infra.postgres;
|
|
74
|
+
const { container, volume } = names(app, 'postgres');
|
|
75
|
+
const running = await inspect(ctx, container);
|
|
76
|
+
const fromEnv = urlParts(values.get(pg.urlKey));
|
|
77
|
+
let password = running?.env.get('POSTGRES_PASSWORD');
|
|
78
|
+
let source = 'container';
|
|
79
|
+
if (password === undefined && fromEnv?.password) {
|
|
80
|
+
password = fromEnv.password;
|
|
81
|
+
source = 'env';
|
|
82
|
+
}
|
|
83
|
+
if (password === undefined) {
|
|
84
|
+
if (await volumeExists(ctx, volume))
|
|
85
|
+
plan.findings.push(unknownPassword('postgres', volume));
|
|
86
|
+
password = ctx.host.randomHex(24);
|
|
87
|
+
source = 'generated';
|
|
88
|
+
}
|
|
89
|
+
const user = running?.env.get('POSTGRES_USER') ?? fromEnv?.user ?? pg.user;
|
|
90
|
+
const database = running?.env.get('POSTGRES_DB') ?? fromEnv?.database ?? pg.database;
|
|
91
|
+
const port = await pick(pg.port, running?.ports.get('5432/tcp') ?? fromEnv?.port, 5433);
|
|
92
|
+
const params = new URLSearchParams(pg.urlParams).toString();
|
|
93
|
+
setEnv(pg.urlKey, `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(password)}@127.0.0.1:${port}/${database}${params ? `?${params}` : ''}`, source === 'container' ? `from the running ${container}` : source === 'generated' ? 'new database' : 'port or parameters');
|
|
94
|
+
plan.secrets['BASALT_PG_PASSWORD'] = password;
|
|
95
|
+
plan.services.push({ service: 'postgres', container, volume, action: running ? 'adopt' : 'create', port, user, database, source });
|
|
96
|
+
}
|
|
97
|
+
if (infra.redis) {
|
|
98
|
+
const redis = infra.redis;
|
|
99
|
+
const { container, volume } = names(app, 'redis');
|
|
100
|
+
const running = await inspect(ctx, container);
|
|
101
|
+
const fromEnv = urlParts(values.get(redis.urlKey));
|
|
102
|
+
let password = running?.env.get('REDIS_PASSWORD');
|
|
103
|
+
let source = 'container';
|
|
104
|
+
if (password === undefined && fromEnv?.password) {
|
|
105
|
+
password = fromEnv.password;
|
|
106
|
+
source = 'env';
|
|
107
|
+
}
|
|
108
|
+
// Redis keeps no credentials in its data: a new password is always safe.
|
|
109
|
+
if (password === undefined) {
|
|
110
|
+
password = ctx.host.randomHex(24);
|
|
111
|
+
source = 'generated';
|
|
112
|
+
}
|
|
113
|
+
const port = await pick(redis.port, running?.ports.get('6379/tcp') ?? fromEnv?.port, 6380);
|
|
114
|
+
setEnv(redis.urlKey, `redis://:${encodeURIComponent(password)}@127.0.0.1:${port}`, source === 'container' ? `from the running ${container}` : source === 'generated' ? 'new redis' : 'port');
|
|
115
|
+
plan.secrets['BASALT_REDIS_PASSWORD'] = password;
|
|
116
|
+
plan.services.push({ service: 'redis', container, volume, action: running ? 'adopt' : 'create', port, source });
|
|
117
|
+
}
|
|
118
|
+
if (infra.minio) {
|
|
119
|
+
const minio = infra.minio;
|
|
120
|
+
const { container, volume } = names(app, 'minio');
|
|
121
|
+
const running = await inspect(ctx, container);
|
|
122
|
+
let user = running?.env.get('MINIO_ROOT_USER');
|
|
123
|
+
let password = running?.env.get('MINIO_ROOT_PASSWORD');
|
|
124
|
+
let source = 'container';
|
|
125
|
+
if ((user === undefined || password === undefined) && values.get(minio.keys.secretKey)) {
|
|
126
|
+
user = values.get(minio.keys.accessKey) ?? minio.user;
|
|
127
|
+
password = values.get(minio.keys.secretKey);
|
|
128
|
+
source = 'env';
|
|
129
|
+
}
|
|
130
|
+
if (user === undefined || password === undefined) {
|
|
131
|
+
if (await volumeExists(ctx, volume))
|
|
132
|
+
plan.findings.push(unknownPassword('minio', volume));
|
|
133
|
+
user = minio.user;
|
|
134
|
+
password = ctx.host.randomHex(24);
|
|
135
|
+
source = 'generated';
|
|
136
|
+
}
|
|
137
|
+
let endpointPort;
|
|
138
|
+
try {
|
|
139
|
+
const endpoint = values.get(minio.keys.endpoint);
|
|
140
|
+
endpointPort = endpoint ? Number(new URL(endpoint).port) || undefined : undefined;
|
|
141
|
+
}
|
|
142
|
+
catch {
|
|
143
|
+
endpointPort = undefined;
|
|
144
|
+
}
|
|
145
|
+
const port = await pick(minio.port, running?.ports.get('9000/tcp') ?? endpointPort, 9100);
|
|
146
|
+
const consolePort = await pick(minio.consolePort, running?.ports.get('9001/tcp'), port + 1);
|
|
147
|
+
const reason = source === 'container' ? `from the running ${container}` : source === 'generated' ? 'new minio' : 'port';
|
|
148
|
+
setEnv(minio.keys.endpoint, `http://127.0.0.1:${port}`, reason);
|
|
149
|
+
setEnv(minio.keys.accessKey, user, reason);
|
|
150
|
+
setEnv(minio.keys.secretKey, password, reason);
|
|
151
|
+
plan.secrets['BASALT_MINIO_USER'] = user;
|
|
152
|
+
plan.secrets['BASALT_MINIO_PASSWORD'] = password;
|
|
153
|
+
plan.services.push({ service: 'minio', container, volume, action: running ? 'adopt' : 'create', port, consolePort, user, source });
|
|
154
|
+
}
|
|
155
|
+
return plan;
|
|
156
|
+
}
|
|
157
|
+
/** The compose file, with no secret in it: compose interpolates them from its environment. */
|
|
158
|
+
export function renderCompose(app, infra, plan) {
|
|
159
|
+
for (const service of plan.services) {
|
|
160
|
+
for (const value of [service.user, service.database]) {
|
|
161
|
+
// These go into the YAML as written: anything outside an identifier
|
|
162
|
+
// could change its meaning.
|
|
163
|
+
if (value !== undefined && !/^[A-Za-z_][A-Za-z0-9_-]{0,62}$/.test(value)) {
|
|
164
|
+
throw new Error(`${service.service}: "${value}" is not a plain user/database name; rename it in deploy.config.ts`);
|
|
165
|
+
}
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
const lines = [
|
|
169
|
+
`# Generated by basalt-deploy for "${app}". Do not edit — change deploy.config.ts.`,
|
|
170
|
+
'# Every port is bound to 127.0.0.1: Docker writes its own iptables rules and',
|
|
171
|
+
'# ignores ufw, so a port published without an address is open to the internet.',
|
|
172
|
+
`name: ${app}`,
|
|
173
|
+
'',
|
|
174
|
+
'services:',
|
|
175
|
+
];
|
|
176
|
+
const volumes = [];
|
|
177
|
+
for (const service of plan.services) {
|
|
178
|
+
const key = service.volume.slice(app.length + 1);
|
|
179
|
+
volumes.push(key);
|
|
180
|
+
if (service.service === 'postgres' && infra.postgres) {
|
|
181
|
+
lines.push(' postgres:', ` image: ${infra.postgres.image}`, ` container_name: ${service.container}`, ' restart: unless-stopped', ` labels: { basalt.app: ${app} }`, ` ports: ['127.0.0.1:${service.port}:5432']`, ' environment:', ` POSTGRES_USER: ${service.user}`, ' POSTGRES_PASSWORD: ${BASALT_PG_PASSWORD:?missing}', ` POSTGRES_DB: ${service.database}`, ` volumes: ['${key}:/var/lib/postgresql/data']`, ' healthcheck:', ` test: ['CMD-SHELL', 'pg_isready -U ${service.user} -d ${service.database}']`, ' interval: 10s', ' timeout: 5s', ' retries: 10');
|
|
182
|
+
}
|
|
183
|
+
if (service.service === 'redis' && infra.redis) {
|
|
184
|
+
lines.push(' redis:', ` image: ${infra.redis.image}`, ` container_name: ${service.container}`, ' restart: unless-stopped', ` labels: { basalt.app: ${app} }`, " command: ['sh', '-c', 'exec redis-server --requirepass \"$$REDIS_PASSWORD\" --appendonly yes']", ` ports: ['127.0.0.1:${service.port}:6379']`, ' environment:', ' REDIS_PASSWORD: ${BASALT_REDIS_PASSWORD:?missing}', ` volumes: ['${key}:/data']`, ' healthcheck:', ` test: ['CMD-SHELL', 'REDISCLI_AUTH="$$REDIS_PASSWORD" redis-cli ping | grep -q PONG']`, ' interval: 10s', ' timeout: 5s', ' retries: 10');
|
|
185
|
+
}
|
|
186
|
+
if (service.service === 'minio' && infra.minio) {
|
|
187
|
+
lines.push(' minio:', ` image: ${infra.minio.image}`, ` container_name: ${service.container}`, ' restart: unless-stopped', ` labels: { basalt.app: ${app} }`, " command: ['server', '/data', '--console-address', ':9001']", ` ports: ['127.0.0.1:${service.port}:9000', '127.0.0.1:${service.consolePort}:9001']`, ' environment:', ' MINIO_ROOT_USER: ${BASALT_MINIO_USER:?missing}', ' MINIO_ROOT_PASSWORD: ${BASALT_MINIO_PASSWORD:?missing}', ` volumes: ['${key}:/data']`, ' healthcheck:', " test: ['CMD', 'mc', 'ready', 'local']", ' interval: 10s', ' timeout: 5s', ' retries: 10');
|
|
188
|
+
}
|
|
189
|
+
}
|
|
190
|
+
lines.push('', 'volumes:', ...volumes.map((v) => ` ${v}:`));
|
|
191
|
+
return `${lines.join('\n')}\n`;
|
|
192
|
+
}
|
|
193
|
+
export const composeFile = (ctx) => join(ctx.stateDir, 'infra.compose.yml');
|
|
194
|
+
/** Starts (or reconciles) the containers, waits for health, proves the credentials, creates the buckets. */
|
|
195
|
+
export async function applyInfra(ctx, plan) {
|
|
196
|
+
const infra = ctx.config.infra;
|
|
197
|
+
if (infra?.kind !== 'docker' || plan.services.length === 0)
|
|
198
|
+
return [];
|
|
199
|
+
const { host } = ctx;
|
|
200
|
+
const { app } = ctx.config;
|
|
201
|
+
await host.mkdir(ctx.stateDir, 0o700);
|
|
202
|
+
await host.writeFile(composeFile(ctx), renderCompose(app, infra, plan), 0o600);
|
|
203
|
+
const up = await host.exec('docker', ['compose', '-p', app, '-f', composeFile(ctx), 'up', '-d', '--wait', '--wait-timeout', '180'], { env: plan.secrets });
|
|
204
|
+
if (up.code !== 0) {
|
|
205
|
+
return [{ id: 'infra', level: 'error', message: `docker compose up failed:\n${up.stderr.trim()}`, fix: `docker compose -p ${app} ps; docker logs ${app}-pg` }];
|
|
206
|
+
}
|
|
207
|
+
const findings = [];
|
|
208
|
+
for (const service of plan.services) {
|
|
209
|
+
if (service.service === 'postgres') {
|
|
210
|
+
// Over TCP with the password: the local socket would trust anyone and
|
|
211
|
+
// prove nothing about the credentials the app will use.
|
|
212
|
+
const check = await host.exec('docker', ['exec', '-e', 'PGPASSWORD', service.container, 'psql', '-h', '127.0.0.1', '-U', service.user ?? app, '-d', service.database ?? app, '-tAc', 'select 1'], { env: { PGPASSWORD: plan.secrets['BASALT_PG_PASSWORD'] ?? '' } });
|
|
213
|
+
if (check.code !== 0 || check.stdout.trim() !== '1') {
|
|
214
|
+
findings.push({
|
|
215
|
+
id: 'C7',
|
|
216
|
+
level: 'error',
|
|
217
|
+
message: `postgres refuses the password in ${ctx.config.env.file ?? '.env'} — the volume ${service.volume} was initialised with another one`,
|
|
218
|
+
fix: 'put the original password back in the .env URL (it is the one the data was created with); never re-create the volume to "fix" this',
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
}
|
|
222
|
+
if (service.service === 'redis') {
|
|
223
|
+
const check = await host.exec('docker', ['exec', '-e', 'REDISCLI_AUTH', service.container, 'redis-cli', 'ping'], { env: { REDISCLI_AUTH: plan.secrets['BASALT_REDIS_PASSWORD'] ?? '' } });
|
|
224
|
+
if (!check.stdout.includes('PONG'))
|
|
225
|
+
findings.push({ id: 'C7', level: 'error', message: `redis refuses the password in ${ctx.config.env.file ?? '.env'}` });
|
|
226
|
+
}
|
|
227
|
+
if (service.service === 'minio' && infra.minio && infra.minio.buckets.length > 0) {
|
|
228
|
+
const alias = `http://${encodeURIComponent(plan.secrets['BASALT_MINIO_USER'] ?? '')}:${encodeURIComponent(plan.secrets['BASALT_MINIO_PASSWORD'] ?? '')}@127.0.0.1:9000`;
|
|
229
|
+
const made = await host.exec('docker', ['exec', '-e', 'MC_HOST_local', service.container, 'mc', 'mb', '-p', ...infra.minio.buckets.map((b) => `local/${b}`)], { env: { MC_HOST_local: alias } });
|
|
230
|
+
if (made.code !== 0)
|
|
231
|
+
findings.push({ id: 'C7', level: 'error', message: `minio refused to create the buckets: ${made.stderr.trim().split('\n')[0] ?? ''}` });
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
return findings;
|
|
235
|
+
}
|
|
236
|
+
export function describeInfra(plan) {
|
|
237
|
+
return plan.services.map((s) => {
|
|
238
|
+
const ports = s.consolePort === undefined ? `127.0.0.1:${s.port}` : `127.0.0.1:${s.port} (console ${s.consolePort})`;
|
|
239
|
+
const credentials = s.source === 'container' ? 'credentials from the container' : s.source === 'env' ? 'credentials from .env' : 'new credentials';
|
|
240
|
+
return `${s.service}: ${s.action} ${s.container} on ${ports}, ${credentials}`;
|
|
241
|
+
});
|
|
242
|
+
}
|
|
@@ -0,0 +1,49 @@
|
|
|
1
|
+
import { type DeployContext, type Finding } from './context.js';
|
|
2
|
+
/**
|
|
3
|
+
* The pipeline (RFC 0006 §4): preflight → fetch → env → infra → build →
|
|
4
|
+
* validate → backup → migrate → release → proxy → health → record.
|
|
5
|
+
*
|
|
6
|
+
* Nothing that runs changes before `release`. A failure up to `migrate` puts
|
|
7
|
+
* the code on disk back (a PM2 crash-restart must not pick up half a deploy);
|
|
8
|
+
* a failure at `release`/`health` rolls the code back and restarts it.
|
|
9
|
+
*/
|
|
10
|
+
export type Skippable = 'fetch' | 'backup' | 'tls';
|
|
11
|
+
export declare const SKIPPABLE: readonly Skippable[];
|
|
12
|
+
export interface RunOptions {
|
|
13
|
+
skip?: Skippable[];
|
|
14
|
+
}
|
|
15
|
+
export interface Preflight {
|
|
16
|
+
findings: Finding[];
|
|
17
|
+
port: number;
|
|
18
|
+
values: Map<string, string>;
|
|
19
|
+
}
|
|
20
|
+
export declare function preflight(ctx: DeployContext, options?: RunOptions): Promise<Preflight>;
|
|
21
|
+
/** `prisma migrate deploy` runs when asked to, or — unsaid — when the app generates a Prisma client. */
|
|
22
|
+
export declare function migratesCentral(config: DeployContext['config']): boolean;
|
|
23
|
+
/**
|
|
24
|
+
* Whether the pre-migration dump runs, and why not when it does not. Unsaid,
|
|
25
|
+
* it runs when there is something to migrate AND a Postgres to dump: the
|
|
26
|
+
* dedicated one, or a `postgres…` URL in the `.env`. Explicitly on, a missing
|
|
27
|
+
* database is the backup step's error to report.
|
|
28
|
+
*/
|
|
29
|
+
export declare function backupDecision(config: DeployContext['config'], values: Map<string, string>, skip?: Iterable<string>): {
|
|
30
|
+
run: true;
|
|
31
|
+
} | {
|
|
32
|
+
run: false;
|
|
33
|
+
why: string;
|
|
34
|
+
};
|
|
35
|
+
export declare function plan(ctx: DeployContext, options?: RunOptions): Promise<number>;
|
|
36
|
+
/** `basalt-deploy env` — the .env and the infra only (first setup, before `install`). */
|
|
37
|
+
export declare function envCommand(ctx: DeployContext): Promise<number>;
|
|
38
|
+
export declare function run(ctx: DeployContext, options?: RunOptions): Promise<number>;
|
|
39
|
+
/** `basalt-deploy rollback [--to=<sha>]` — code only; the database stays as it is. */
|
|
40
|
+
export declare function rollback(ctx: DeployContext, to?: string): Promise<number>;
|
|
41
|
+
export declare function status(ctx: DeployContext): Promise<number>;
|
|
42
|
+
/**
|
|
43
|
+
* `sudo basalt-deploy install` — once per server, by an administrator (RFC
|
|
44
|
+
* 0006 §11.4). Everything that needs root and nothing else: the vhost, the
|
|
45
|
+
* state directory owned by the app user. The app user is never added to the
|
|
46
|
+
* `docker` group (root-equivalent); with dedicated infra it needs rootless
|
|
47
|
+
* Docker, and this says so.
|
|
48
|
+
*/
|
|
49
|
+
export declare function install(ctx: DeployContext, user: string | undefined): Promise<number>;
|