@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/dotenv.d.ts
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `.env` as a document: read without a shell (no `$` expansion, no command
|
|
3
|
+
* substitution), edited in place (a key keeps its line, comments survive), and
|
|
4
|
+
* written in a form Node's `--env-file`, `dotenv` and `docker compose
|
|
5
|
+
* --env-file` all read the same way.
|
|
6
|
+
*
|
|
7
|
+
* Problems are reported by line number, never by value: the file holds secrets
|
|
8
|
+
* and the report ends up in terminals, CI logs and screenshots.
|
|
9
|
+
*/
|
|
10
|
+
export declare const ENV_KEY: RegExp;
|
|
11
|
+
export type EnvLine = {
|
|
12
|
+
kind: 'pair';
|
|
13
|
+
key: string;
|
|
14
|
+
value: string;
|
|
15
|
+
raw: string;
|
|
16
|
+
} | {
|
|
17
|
+
kind: 'other';
|
|
18
|
+
raw: string;
|
|
19
|
+
};
|
|
20
|
+
export interface EnvProblem {
|
|
21
|
+
line: number;
|
|
22
|
+
message: string;
|
|
23
|
+
}
|
|
24
|
+
export interface EnvDocument {
|
|
25
|
+
lines: EnvLine[];
|
|
26
|
+
problems: EnvProblem[];
|
|
27
|
+
}
|
|
28
|
+
export declare function parseEnv(text: string): EnvDocument;
|
|
29
|
+
export declare function envValues(document: EnvDocument): Map<string, string>;
|
|
30
|
+
export declare class UnwritableValueError extends Error {
|
|
31
|
+
readonly key: string;
|
|
32
|
+
constructor(key: string);
|
|
33
|
+
}
|
|
34
|
+
/** A value in the one form every reader agrees on, or {@link UnwritableValueError}. */
|
|
35
|
+
export declare function formatValue(value: string, key?: string): string;
|
|
36
|
+
export type EnvChange = {
|
|
37
|
+
kind: 'set';
|
|
38
|
+
key: string;
|
|
39
|
+
value: string;
|
|
40
|
+
reason: string;
|
|
41
|
+
} | {
|
|
42
|
+
kind: 'remove';
|
|
43
|
+
key: string;
|
|
44
|
+
reason: string;
|
|
45
|
+
};
|
|
46
|
+
/** Applies changes: a set key keeps its line, a new key is appended, a removed key's line goes. */
|
|
47
|
+
export declare function applyEnvChanges(document: EnvDocument, changes: EnvChange[]): string;
|
package/dist/dotenv.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The `.env` as a document: read without a shell (no `$` expansion, no command
|
|
3
|
+
* substitution), edited in place (a key keeps its line, comments survive), and
|
|
4
|
+
* written in a form Node's `--env-file`, `dotenv` and `docker compose
|
|
5
|
+
* --env-file` all read the same way.
|
|
6
|
+
*
|
|
7
|
+
* Problems are reported by line number, never by value: the file holds secrets
|
|
8
|
+
* and the report ends up in terminals, CI logs and screenshots.
|
|
9
|
+
*/
|
|
10
|
+
export const ENV_KEY = /^[A-Za-z_][A-Za-z0-9_]*$/;
|
|
11
|
+
export function parseEnv(text) {
|
|
12
|
+
const lines = [];
|
|
13
|
+
const problems = [];
|
|
14
|
+
const seen = new Map();
|
|
15
|
+
const rows = text.replace(/\r\n/g, '\n').split('\n');
|
|
16
|
+
if (rows.at(-1) === '')
|
|
17
|
+
rows.pop();
|
|
18
|
+
rows.forEach((raw, index) => {
|
|
19
|
+
const number = index + 1;
|
|
20
|
+
const trimmed = raw.trim();
|
|
21
|
+
if (trimmed === '' || trimmed.startsWith('#')) {
|
|
22
|
+
lines.push({ kind: 'other', raw });
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
const match = /^\s*(?:export\s+)?([^=\s]+)\s*=(.*)$/.exec(raw);
|
|
26
|
+
if (!match) {
|
|
27
|
+
// The incident that wrote this check: a prompt's echo split `KEY="…`
|
|
28
|
+
// over two lines, and Compose refused the file (`unexpected character`).
|
|
29
|
+
problems.push({ line: number, message: 'not a KEY=value line (a value split over two lines?)' });
|
|
30
|
+
lines.push({ kind: 'other', raw });
|
|
31
|
+
return;
|
|
32
|
+
}
|
|
33
|
+
const key = match[1];
|
|
34
|
+
if (!ENV_KEY.test(key)) {
|
|
35
|
+
problems.push({ line: number, message: `"${key}" is not a valid variable name` });
|
|
36
|
+
lines.push({ kind: 'other', raw });
|
|
37
|
+
return;
|
|
38
|
+
}
|
|
39
|
+
const value = parseValue(match[2].trim());
|
|
40
|
+
if (value === null) {
|
|
41
|
+
problems.push({ line: number, message: `${key}: the quoted value is not closed on the same line` });
|
|
42
|
+
lines.push({ kind: 'other', raw });
|
|
43
|
+
return;
|
|
44
|
+
}
|
|
45
|
+
const earlier = seen.get(key);
|
|
46
|
+
if (earlier !== undefined) {
|
|
47
|
+
problems.push({ line: number, message: `${key} is already set on line ${earlier}; tools disagree on which one wins` });
|
|
48
|
+
}
|
|
49
|
+
seen.set(key, number);
|
|
50
|
+
lines.push({ kind: 'pair', key, value, raw });
|
|
51
|
+
});
|
|
52
|
+
return { lines, problems };
|
|
53
|
+
}
|
|
54
|
+
/** `null` when a quote opens and does not close on the line. */
|
|
55
|
+
function parseValue(rest) {
|
|
56
|
+
if (rest.startsWith('"')) {
|
|
57
|
+
let out = '';
|
|
58
|
+
for (let i = 1; i < rest.length; i++) {
|
|
59
|
+
const c = rest[i];
|
|
60
|
+
if (c === '\\' && i + 1 < rest.length) {
|
|
61
|
+
const next = rest[++i];
|
|
62
|
+
out += next === 'n' ? '\n' : next;
|
|
63
|
+
continue;
|
|
64
|
+
}
|
|
65
|
+
if (c === '"')
|
|
66
|
+
return out;
|
|
67
|
+
out += c;
|
|
68
|
+
}
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
if (rest.startsWith("'")) {
|
|
72
|
+
const end = rest.indexOf("'", 1);
|
|
73
|
+
return end === -1 ? null : rest.slice(1, end);
|
|
74
|
+
}
|
|
75
|
+
const comment = rest.search(/\s#/);
|
|
76
|
+
return (comment === -1 ? rest : rest.slice(0, comment)).trim();
|
|
77
|
+
}
|
|
78
|
+
export function envValues(document) {
|
|
79
|
+
const values = new Map();
|
|
80
|
+
for (const line of document.lines)
|
|
81
|
+
if (line.kind === 'pair')
|
|
82
|
+
values.set(line.key, line.value);
|
|
83
|
+
return values;
|
|
84
|
+
}
|
|
85
|
+
const SAFE = /^[A-Za-z0-9_./:@%+,=?&~*-]*$/;
|
|
86
|
+
export class UnwritableValueError extends Error {
|
|
87
|
+
key;
|
|
88
|
+
constructor(key) {
|
|
89
|
+
super(`${key}: the value has both a single quote and one of " \\ $ or a line break — no quoting reads the same in Node, dotenv and Compose. Choose another value.`);
|
|
90
|
+
this.key = key;
|
|
91
|
+
this.name = 'UnwritableValueError';
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/** A value in the one form every reader agrees on, or {@link UnwritableValueError}. */
|
|
95
|
+
export function formatValue(value, key = 'value') {
|
|
96
|
+
if (SAFE.test(value))
|
|
97
|
+
return value;
|
|
98
|
+
if (value.includes('\n'))
|
|
99
|
+
throw new UnwritableValueError(key);
|
|
100
|
+
// Single quotes are literal for Node, dotenv and Compose alike (no `$` interpolation).
|
|
101
|
+
if (!value.includes("'"))
|
|
102
|
+
return `'${value}'`;
|
|
103
|
+
// Double quotes: literal everywhere only without `"`, `\` and `$` (Compose interpolates `$`, Node keeps `\`).
|
|
104
|
+
if (!/["\\$]/.test(value))
|
|
105
|
+
return `"${value}"`;
|
|
106
|
+
throw new UnwritableValueError(key);
|
|
107
|
+
}
|
|
108
|
+
/** Applies changes: a set key keeps its line, a new key is appended, a removed key's line goes. */
|
|
109
|
+
export function applyEnvChanges(document, changes) {
|
|
110
|
+
const sets = new Map();
|
|
111
|
+
const removes = new Set();
|
|
112
|
+
for (const change of changes) {
|
|
113
|
+
if (change.kind === 'set')
|
|
114
|
+
sets.set(change.key, change.value);
|
|
115
|
+
else
|
|
116
|
+
removes.add(change.key);
|
|
117
|
+
}
|
|
118
|
+
const out = [];
|
|
119
|
+
const written = new Set();
|
|
120
|
+
for (const line of document.lines) {
|
|
121
|
+
if (line.kind !== 'pair') {
|
|
122
|
+
out.push(line.raw);
|
|
123
|
+
continue;
|
|
124
|
+
}
|
|
125
|
+
if (removes.has(line.key))
|
|
126
|
+
continue;
|
|
127
|
+
if (sets.has(line.key)) {
|
|
128
|
+
if (written.has(line.key))
|
|
129
|
+
continue;
|
|
130
|
+
out.push(`${line.key}=${formatValue(sets.get(line.key), line.key)}`);
|
|
131
|
+
written.add(line.key);
|
|
132
|
+
continue;
|
|
133
|
+
}
|
|
134
|
+
out.push(line.raw);
|
|
135
|
+
}
|
|
136
|
+
const appended = [...sets].filter(([key]) => !written.has(key));
|
|
137
|
+
if (appended.length > 0) {
|
|
138
|
+
if (out.length > 0 && out.at(-1) !== '')
|
|
139
|
+
out.push('');
|
|
140
|
+
out.push(`# Added by basalt-deploy`);
|
|
141
|
+
for (const [key, value] of appended)
|
|
142
|
+
out.push(`${key}=${formatValue(value, key)}`);
|
|
143
|
+
}
|
|
144
|
+
return `${out.join('\n')}\n`;
|
|
145
|
+
}
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
import type { DeployContext, Finding } from './context.js';
|
|
2
|
+
export interface SchemaResult {
|
|
3
|
+
findings: Finding[];
|
|
4
|
+
/** Keys whose parsed value is `true` (for C6). */
|
|
5
|
+
trueKeys: string[];
|
|
6
|
+
}
|
|
7
|
+
export declare function checkSchema(ctx: DeployContext, values: Map<string, string>): Promise<SchemaResult>;
|
|
8
|
+
/**
|
|
9
|
+
* C6 — a value written to turn something OFF that the schema reads as ON.
|
|
10
|
+
* `z.coerce.boolean()` is `Boolean(string)`: every non-empty string is true,
|
|
11
|
+
* "0" and "false" included. `PROXYPAY_FAKE="0"` switched the fake payment
|
|
12
|
+
* gateway on in production. Generic on purpose: it needs no list of boolean
|
|
13
|
+
* keys, only the parsed result (prefixed names — `MY_APP_FLAG` for `FLAG` —
|
|
14
|
+
* are matched too).
|
|
15
|
+
*/
|
|
16
|
+
export declare function coercionFindings(values: Map<string, string>, trueKeys: string[]): Finding[];
|
|
17
|
+
/** C10 — forbidden keys absent, fixed keys equal. */
|
|
18
|
+
export declare function policyFindings(ctx: DeployContext, values: Map<string, string>): Finding[];
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { pathToFileURL } from 'node:url';
|
|
3
|
+
/**
|
|
4
|
+
* The `.env` against the app's own `defineEnv(...)` (RFC 0006 §6.2), before
|
|
5
|
+
* anything is touched — a bad value is a diagnosis here, a crash loop after
|
|
6
|
+
* the restart.
|
|
7
|
+
*
|
|
8
|
+
* It runs in a child process that sees ONLY the file's values (plus PATH and
|
|
9
|
+
* HOME): the operator's shell must not mask a key the server will not have.
|
|
10
|
+
* The child reports names, never values.
|
|
11
|
+
*/
|
|
12
|
+
const MARK = '@@basalt-deploy@@';
|
|
13
|
+
const PROBE = `
|
|
14
|
+
const mark = ${JSON.stringify(MARK)}
|
|
15
|
+
try {
|
|
16
|
+
const m = await import(process.env.BASALT_DEPLOY_SCHEMA)
|
|
17
|
+
const env = m.env ?? m.default
|
|
18
|
+
const trueKeys = env && typeof env === 'object' ? Object.entries(env).filter(([, v]) => v === true).map(([k]) => k) : []
|
|
19
|
+
console.log('\\n' + mark + JSON.stringify({ ok: true, trueKeys }))
|
|
20
|
+
} catch (error) {
|
|
21
|
+
const report = Array.isArray(error?.report) ? error.report : [String(error?.message ?? error).split('\\n')[0]]
|
|
22
|
+
console.log('\\n' + mark + JSON.stringify({ ok: false, name: String(error?.name ?? 'Error'), report }))
|
|
23
|
+
}
|
|
24
|
+
`;
|
|
25
|
+
export async function checkSchema(ctx, values) {
|
|
26
|
+
const schema = ctx.config.env.schema;
|
|
27
|
+
if (!schema)
|
|
28
|
+
return { findings: [], trueKeys: [] };
|
|
29
|
+
const { host } = ctx;
|
|
30
|
+
const useTsx = /\.[cm]?ts$/.test(schema) && await host.exists(join(ctx.dir, 'node_modules', 'tsx'));
|
|
31
|
+
const args = [...(useTsx ? ['--import', 'tsx'] : []), '--input-type=module', '-e', PROBE];
|
|
32
|
+
const result = await host.exec(process.execPath, args, {
|
|
33
|
+
cwd: ctx.dir,
|
|
34
|
+
inheritEnv: false,
|
|
35
|
+
env: { ...Object.fromEntries(values), BASALT_DEPLOY_SCHEMA: pathToFileURL(join(ctx.dir, schema)).href },
|
|
36
|
+
});
|
|
37
|
+
const line = result.stdout.split('\n').find((l) => l.startsWith(MARK));
|
|
38
|
+
if (!line) {
|
|
39
|
+
return {
|
|
40
|
+
trueKeys: [],
|
|
41
|
+
findings: [{ id: 'env', level: 'error', message: `could not load ${schema} (exit ${result.code}): ${result.stderr.trim().split('\n').slice(-3).join(' / ')}` }],
|
|
42
|
+
};
|
|
43
|
+
}
|
|
44
|
+
const parsed = JSON.parse(line.slice(MARK.length));
|
|
45
|
+
if (parsed.ok)
|
|
46
|
+
return { findings: [], trueKeys: parsed.trueKeys };
|
|
47
|
+
const fix = `set it in ${ctx.config.env.file ?? '.env'}, or in deploy.config.ts (fixed/ask/generate)`;
|
|
48
|
+
return {
|
|
49
|
+
trueKeys: [],
|
|
50
|
+
findings: parsed.report.map((issue) => ({
|
|
51
|
+
id: 'env',
|
|
52
|
+
level: 'error',
|
|
53
|
+
message: `${schema}: ${issue}`,
|
|
54
|
+
...(parsed.name === 'EnvValidationError' ? { fix } : {}),
|
|
55
|
+
})),
|
|
56
|
+
};
|
|
57
|
+
}
|
|
58
|
+
const FALSY = new Set(['0', 'false', 'no', 'off']);
|
|
59
|
+
/**
|
|
60
|
+
* C6 — a value written to turn something OFF that the schema reads as ON.
|
|
61
|
+
* `z.coerce.boolean()` is `Boolean(string)`: every non-empty string is true,
|
|
62
|
+
* "0" and "false" included. `PROXYPAY_FAKE="0"` switched the fake payment
|
|
63
|
+
* gateway on in production. Generic on purpose: it needs no list of boolean
|
|
64
|
+
* keys, only the parsed result (prefixed names — `MY_APP_FLAG` for `FLAG` —
|
|
65
|
+
* are matched too).
|
|
66
|
+
*/
|
|
67
|
+
export function coercionFindings(values, trueKeys) {
|
|
68
|
+
const findings = [];
|
|
69
|
+
for (const key of trueKeys) {
|
|
70
|
+
for (const [raw, value] of values) {
|
|
71
|
+
if ((raw === key || raw.endsWith(`_${key}`)) && FALSY.has(value.trim().toLowerCase())) {
|
|
72
|
+
findings.push({
|
|
73
|
+
id: 'C6',
|
|
74
|
+
level: 'error',
|
|
75
|
+
message: `${raw}="${value}" is read as TRUE by the app's schema (a coerced boolean treats every non-empty string as true)`,
|
|
76
|
+
fix: `remove ${raw} from the file to turn it off, and use z.stringbool() in the schema`,
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
return findings;
|
|
82
|
+
}
|
|
83
|
+
/** C10 — forbidden keys absent, fixed keys equal. */
|
|
84
|
+
export function policyFindings(ctx, values) {
|
|
85
|
+
const findings = [];
|
|
86
|
+
for (const key of ctx.config.env.forbid ?? []) {
|
|
87
|
+
if (values.has(key))
|
|
88
|
+
findings.push({ id: 'C10', level: 'error', message: `${key} must not exist in the production .env`, fix: `basalt-deploy env removes it` });
|
|
89
|
+
}
|
|
90
|
+
for (const [key, value] of Object.entries(ctx.config.env.fixed ?? {})) {
|
|
91
|
+
if (values.get(key) !== value)
|
|
92
|
+
findings.push({ id: 'C10', level: 'error', message: `${key} differs from deploy.config.ts`, fix: `basalt-deploy env corrects it` });
|
|
93
|
+
}
|
|
94
|
+
return findings;
|
|
95
|
+
}
|
|
@@ -0,0 +1,29 @@
|
|
|
1
|
+
import type { DeployContext, Finding } from './context.js';
|
|
2
|
+
import { type EnvChange, type EnvDocument } from './dotenv.js';
|
|
3
|
+
/**
|
|
4
|
+
* The `.env` step (RFC 0006 §6.1). Order: fixed → generated (only when absent)
|
|
5
|
+
* → derived → infra → asked (only when absent) → forbidden removed.
|
|
6
|
+
*
|
|
7
|
+
* Nothing here prints a value. The summary is keys and reasons only.
|
|
8
|
+
*/
|
|
9
|
+
export interface EnvPlan {
|
|
10
|
+
document: EnvDocument;
|
|
11
|
+
values: Map<string, string>;
|
|
12
|
+
changes: EnvChange[];
|
|
13
|
+
/** Keys still to ask — answered by {@link answerQuestions}. */
|
|
14
|
+
questions: string[];
|
|
15
|
+
findings: Finding[];
|
|
16
|
+
}
|
|
17
|
+
export declare const envFile: (ctx: DeployContext) => string;
|
|
18
|
+
export declare function readEnv(ctx: DeployContext): Promise<EnvDocument>;
|
|
19
|
+
export declare function syntaxFindings(document: EnvDocument, file: string): Finding[];
|
|
20
|
+
export declare function planEnv(ctx: DeployContext, document: EnvDocument, port: number, infra: EnvChange[]): EnvPlan;
|
|
21
|
+
/**
|
|
22
|
+
* Asks once, at the terminal (secrets with echo off), or takes the answer from
|
|
23
|
+
* the deploy's own environment under the same name — CI, or a person who
|
|
24
|
+
* prefers `MAILER_URL=… basalt-deploy run`. Returns what is still missing.
|
|
25
|
+
*/
|
|
26
|
+
export declare function answerQuestions(ctx: DeployContext, plan: EnvPlan): Promise<string[]>;
|
|
27
|
+
export declare function describeEnv(plan: EnvPlan): string[];
|
|
28
|
+
/** Backs the file up (0600, last 5 kept) and writes it atomically, 0600. */
|
|
29
|
+
export declare function writeEnv(ctx: DeployContext, plan: EnvPlan): Promise<void>;
|
package/dist/env-step.js
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { join } from 'node:path';
|
|
2
|
+
import { applyEnvChanges, envValues, formatValue, parseEnv, UnwritableValueError } from './dotenv.js';
|
|
3
|
+
export const envFile = (ctx) => join(ctx.dir, ctx.config.env.file ?? '.env');
|
|
4
|
+
export async function readEnv(ctx) {
|
|
5
|
+
return parseEnv((await ctx.host.readFile(envFile(ctx))) ?? '');
|
|
6
|
+
}
|
|
7
|
+
export function syntaxFindings(document, file) {
|
|
8
|
+
return document.problems.map((p) => ({
|
|
9
|
+
id: 'C5',
|
|
10
|
+
level: 'error',
|
|
11
|
+
message: `${file}:${p.line}: ${p.message}`,
|
|
12
|
+
fix: `edit line ${p.line} by hand (KEY=value on one line); the value is not shown here`,
|
|
13
|
+
}));
|
|
14
|
+
}
|
|
15
|
+
export function planEnv(ctx, document, port, infra) {
|
|
16
|
+
const { config } = ctx;
|
|
17
|
+
const values = envValues(document);
|
|
18
|
+
const changes = [];
|
|
19
|
+
const pending = new Map(values);
|
|
20
|
+
const set = (key, value, reason) => {
|
|
21
|
+
if (pending.get(key) === value)
|
|
22
|
+
return;
|
|
23
|
+
const existing = changes.findIndex((c) => c.key === key);
|
|
24
|
+
if (existing !== -1)
|
|
25
|
+
changes.splice(existing, 1);
|
|
26
|
+
changes.push({ kind: 'set', key, value, reason });
|
|
27
|
+
pending.set(key, value);
|
|
28
|
+
};
|
|
29
|
+
set('PORT', String(port), 'the port the process listens on');
|
|
30
|
+
for (const [key, value] of Object.entries(config.env.fixed ?? {}))
|
|
31
|
+
set(key, value, 'fixed in deploy.config.ts');
|
|
32
|
+
for (const [key, spec] of Object.entries(config.env.generate ?? {})) {
|
|
33
|
+
if (!pending.get(key))
|
|
34
|
+
set(key, ctx.host.randomHex(spec.bytes), 'generated');
|
|
35
|
+
}
|
|
36
|
+
const derived = config.env.derive?.({ app: config.app, domain: config.domain, port }) ?? {};
|
|
37
|
+
for (const [key, value] of Object.entries(derived))
|
|
38
|
+
set(key, value, 'derived from the domain/port');
|
|
39
|
+
for (const change of infra)
|
|
40
|
+
if (change.kind === 'set')
|
|
41
|
+
set(change.key, change.value, change.reason);
|
|
42
|
+
const questions = [];
|
|
43
|
+
for (const [key, question] of Object.entries(config.env.ask ?? {})) {
|
|
44
|
+
const current = pending.get(key);
|
|
45
|
+
if (current === undefined || (current === '' && !question.optional))
|
|
46
|
+
questions.push(key);
|
|
47
|
+
}
|
|
48
|
+
for (const key of config.env.forbid ?? []) {
|
|
49
|
+
if (pending.has(key))
|
|
50
|
+
changes.push({ kind: 'remove', key, reason: 'forbidden in production by deploy.config.ts' });
|
|
51
|
+
}
|
|
52
|
+
return { document, values, changes, questions, findings: syntaxFindings(document, config.env.file ?? '.env') };
|
|
53
|
+
}
|
|
54
|
+
/**
|
|
55
|
+
* Asks once, at the terminal (secrets with echo off), or takes the answer from
|
|
56
|
+
* the deploy's own environment under the same name — CI, or a person who
|
|
57
|
+
* prefers `MAILER_URL=… basalt-deploy run`. Returns what is still missing.
|
|
58
|
+
*/
|
|
59
|
+
export async function answerQuestions(ctx, plan) {
|
|
60
|
+
const missing = [];
|
|
61
|
+
for (const key of plan.questions) {
|
|
62
|
+
const question = ctx.config.env.ask?.[key];
|
|
63
|
+
if (!question)
|
|
64
|
+
continue;
|
|
65
|
+
let answer = ctx.host.env[key]?.trim();
|
|
66
|
+
for (let attempt = 0; answer === undefined && attempt < 3; attempt++) {
|
|
67
|
+
const typed = await ctx.host.prompt(`${question.prompt} [${key}]${question.optional ? ' (empty to skip)' : ''}`, { secret: question.secret });
|
|
68
|
+
if (typed === undefined)
|
|
69
|
+
break;
|
|
70
|
+
const value = typed === '' && question.default !== undefined ? question.default : typed;
|
|
71
|
+
if (value === '' && !question.optional) {
|
|
72
|
+
ctx.host.out.warn(`${key} is required`);
|
|
73
|
+
continue;
|
|
74
|
+
}
|
|
75
|
+
try {
|
|
76
|
+
formatValue(value, key);
|
|
77
|
+
answer = value;
|
|
78
|
+
}
|
|
79
|
+
catch (error) {
|
|
80
|
+
if (!(error instanceof UnwritableValueError))
|
|
81
|
+
throw error;
|
|
82
|
+
ctx.host.out.warn(error.message);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
if (answer === undefined) {
|
|
86
|
+
if (question.optional)
|
|
87
|
+
answer = question.default ?? '';
|
|
88
|
+
else {
|
|
89
|
+
missing.push(key);
|
|
90
|
+
continue;
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
plan.changes.push({ kind: 'set', key, value: answer, reason: 'answered' });
|
|
94
|
+
}
|
|
95
|
+
plan.questions = [];
|
|
96
|
+
return missing;
|
|
97
|
+
}
|
|
98
|
+
export function describeEnv(plan) {
|
|
99
|
+
return [
|
|
100
|
+
...plan.changes.map((c) => c.kind === 'remove'
|
|
101
|
+
? `remove ${c.key} (${c.reason})`
|
|
102
|
+
: `${plan.values.has(c.key) ? 'change' : 'add'} ${c.key} (${c.reason})`),
|
|
103
|
+
...plan.questions.map((key) => `ask ${key}`),
|
|
104
|
+
];
|
|
105
|
+
}
|
|
106
|
+
/** Backs the file up (0600, last 5 kept) and writes it atomically, 0600. */
|
|
107
|
+
export async function writeEnv(ctx, plan) {
|
|
108
|
+
if (plan.changes.length === 0)
|
|
109
|
+
return;
|
|
110
|
+
const { host } = ctx;
|
|
111
|
+
const file = envFile(ctx);
|
|
112
|
+
const text = applyEnvChanges(plan.document, plan.changes);
|
|
113
|
+
if (await host.exists(file)) {
|
|
114
|
+
const stamp = host.now().toISOString().replace(/[-:]/g, '').replace(/\..+$/, '');
|
|
115
|
+
await host.copyFile(file, `${file}.bak-${stamp}`, 0o600);
|
|
116
|
+
const base = file.slice(file.lastIndexOf('/') + 1);
|
|
117
|
+
const dir = file.slice(0, file.lastIndexOf('/'));
|
|
118
|
+
const backups = (await host.list(dir)).filter((name) => name.startsWith(`${base}.bak-`)).sort();
|
|
119
|
+
for (const old of backups.slice(0, -5))
|
|
120
|
+
await host.remove(join(dir, old));
|
|
121
|
+
}
|
|
122
|
+
await host.writeFile(file, text, 0o600);
|
|
123
|
+
plan.document = parseEnv(text);
|
|
124
|
+
plan.values = envValues(plan.document);
|
|
125
|
+
plan.changes = [];
|
|
126
|
+
}
|
package/dist/host.d.ts
ADDED
|
@@ -0,0 +1,87 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Every side effect the pipeline has goes through this interface: processes,
|
|
3
|
+
* files, the terminal, the network, the clock. The real one is {@link nodeHost};
|
|
4
|
+
* the tests drive the whole pipeline with a fake one, including each production
|
|
5
|
+
* incident the checks were written for (RFC 0006 §A).
|
|
6
|
+
*/
|
|
7
|
+
export interface Host {
|
|
8
|
+
exec(command: string, args: string[], options?: ExecOptions): Promise<ExecResult>;
|
|
9
|
+
readFile(path: string): Promise<string | undefined>;
|
|
10
|
+
/** Atomic (temp file + rename) and created with `mode` before any byte is written. */
|
|
11
|
+
writeFile(path: string, content: string, mode?: number): Promise<void>;
|
|
12
|
+
copyFile(from: string, to: string, mode?: number): Promise<void>;
|
|
13
|
+
exists(path: string): Promise<boolean>;
|
|
14
|
+
stat(path: string): Promise<{
|
|
15
|
+
kind: 'file' | 'dir' | 'symlink' | 'other';
|
|
16
|
+
size: number;
|
|
17
|
+
} | undefined>;
|
|
18
|
+
readlink(path: string): Promise<string | undefined>;
|
|
19
|
+
symlink(target: string, path: string): Promise<void>;
|
|
20
|
+
mkdir(path: string, mode?: number): Promise<void>;
|
|
21
|
+
remove(path: string): Promise<void>;
|
|
22
|
+
list(dir: string): Promise<string[]>;
|
|
23
|
+
/** A line typed by a person, or `undefined` when nobody can answer (no TTY). */
|
|
24
|
+
prompt(question: string, options: {
|
|
25
|
+
secret: boolean;
|
|
26
|
+
}): Promise<string | undefined>;
|
|
27
|
+
confirm(question: string): Promise<boolean>;
|
|
28
|
+
randomHex(bytes: number): string;
|
|
29
|
+
now(): Date;
|
|
30
|
+
sleep(ms: number): Promise<void>;
|
|
31
|
+
/** The certificate a TLS server presents for `servername`: its names, or why the chain is not trusted. */
|
|
32
|
+
tlsCertificate(servername: string): Promise<TlsCertificate | {
|
|
33
|
+
error: string;
|
|
34
|
+
}>;
|
|
35
|
+
/** GET with an explicit `Host` header (fetch forbids setting it). Never throws. */
|
|
36
|
+
httpGet(url: string, options?: {
|
|
37
|
+
host?: string;
|
|
38
|
+
timeoutMs?: number;
|
|
39
|
+
}): Promise<{
|
|
40
|
+
status: number;
|
|
41
|
+
} | {
|
|
42
|
+
error: string;
|
|
43
|
+
}>;
|
|
44
|
+
/** The environment the deploy itself was started with (answers for non-interactive runs). */
|
|
45
|
+
env: Readonly<Record<string, string | undefined>>;
|
|
46
|
+
/** Whether a person can answer a prompt (a terminal, not CI). */
|
|
47
|
+
interactive(): boolean;
|
|
48
|
+
uid(): number;
|
|
49
|
+
out: Output;
|
|
50
|
+
}
|
|
51
|
+
export interface ExecOptions {
|
|
52
|
+
cwd?: string;
|
|
53
|
+
/** Added to the inherited environment (or the whole environment with `inheritEnv: false`). */
|
|
54
|
+
env?: Record<string, string>;
|
|
55
|
+
/** Removed from the inherited environment (e.g. `NODE_ENV` for an install with devDependencies). */
|
|
56
|
+
unset?: string[];
|
|
57
|
+
/** `false` → the child sees `env` and `PATH`/`HOME` only. */
|
|
58
|
+
inheritEnv?: boolean;
|
|
59
|
+
/** stdout goes to this file (created 0600), not to memory. */
|
|
60
|
+
stdoutFile?: string;
|
|
61
|
+
/** stdout/stderr go to the terminal (long steps), nothing is captured. */
|
|
62
|
+
stream?: boolean;
|
|
63
|
+
}
|
|
64
|
+
export interface ExecResult {
|
|
65
|
+
code: number;
|
|
66
|
+
stdout: string;
|
|
67
|
+
stderr: string;
|
|
68
|
+
}
|
|
69
|
+
export interface TlsCertificate {
|
|
70
|
+
/** `subjectAltName` DNS names, lowercased (`*.example.com` included as written). */
|
|
71
|
+
names: string[];
|
|
72
|
+
validTo: Date;
|
|
73
|
+
/** Whether the chain verifies against the system's roots; the reason when it does not. */
|
|
74
|
+
trusted: boolean;
|
|
75
|
+
trustError?: string;
|
|
76
|
+
}
|
|
77
|
+
export interface Output {
|
|
78
|
+
step(title: string): void;
|
|
79
|
+
info(message: string): void;
|
|
80
|
+
ok(message: string): void;
|
|
81
|
+
warn(message: string): void;
|
|
82
|
+
error(message: string): void;
|
|
83
|
+
}
|
|
84
|
+
export declare function consoleOutput(stream?: NodeJS.WriteStream): Output;
|
|
85
|
+
export declare function nodeHost(output?: Output): Host;
|
|
86
|
+
/** `mkdir -p` of the parent, for writers that create a file in a directory that may not exist. */
|
|
87
|
+
export declare const parentOf: (path: string) => string;
|