@fabioplunser/epd 0.5.15 → 0.5.16
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 +71 -3
- package/bin/epd.js +0 -0
- package/dist/cli.js +1641 -330
- package/docs/.vitepress/config.mts +2 -0
- package/docs/agents.md +16 -1
- package/docs/guide/dashboard-validation.md +181 -0
- package/docs/guide/private-repositories.md +44 -0
- package/docs/guide/server-baseline.md +104 -0
- package/docs/guide/storage-validation.md +40 -0
- package/docs/reference/cli.md +95 -0
- package/docs/reference/config.md +14 -0
- package/package.json +17 -6
package/dist/cli.js
CHANGED
|
@@ -13,9 +13,9 @@ var __esm = (fn, res, err) => () => {
|
|
|
13
13
|
var __require = import.meta.require;
|
|
14
14
|
|
|
15
15
|
// src/util/log.ts
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
}
|
|
16
|
+
import { closeSync, mkdirSync, openSync, readdirSync, unlinkSync, writeSync } from "fs";
|
|
17
|
+
import { homedir } from "os";
|
|
18
|
+
import { join } from "path";
|
|
19
19
|
function registerSecret(value) {
|
|
20
20
|
if (value && value.length >= 4)
|
|
21
21
|
knownSecrets.add(value);
|
|
@@ -29,13 +29,162 @@ function redact(text) {
|
|
|
29
29
|
out = out.replace(re, replacement);
|
|
30
30
|
return out;
|
|
31
31
|
}
|
|
32
|
-
function
|
|
33
|
-
|
|
34
|
-
|
|
32
|
+
function setVerbose(v) {
|
|
33
|
+
verbose = v;
|
|
34
|
+
}
|
|
35
|
+
function logFormat() {
|
|
36
|
+
return format;
|
|
37
|
+
}
|
|
38
|
+
function logDir() {
|
|
39
|
+
if (process.env.EPD_LOG_DIR)
|
|
40
|
+
return process.env.EPD_LOG_DIR;
|
|
41
|
+
const state = process.env.XDG_STATE_HOME || join(homedir(), ".local", "state");
|
|
42
|
+
return join(state, "epd", "logs");
|
|
43
|
+
}
|
|
44
|
+
function openRunLog(command, argv, version, keep = 200) {
|
|
45
|
+
if (fileFd !== null)
|
|
46
|
+
return filePath;
|
|
47
|
+
const dir = logDir();
|
|
48
|
+
if (dir === "off")
|
|
49
|
+
return null;
|
|
50
|
+
try {
|
|
51
|
+
mkdirSync(dir, { recursive: true, mode: 448 });
|
|
52
|
+
const stamp = new Date().toISOString().replace(/[:.]/g, "-").replace("T", "_").slice(0, 19);
|
|
53
|
+
filePath = join(dir, `${stamp}-${command.replace(/[^\w-]/g, "_")}-${process.pid}.log`);
|
|
54
|
+
fileFd = openSync(filePath, "a", 384);
|
|
55
|
+
writeFile(`# epd ${version} \u2014 ${command}`);
|
|
56
|
+
writeFile(`# argv: ${redactArgv(argv).join(" ")}`);
|
|
57
|
+
writeFile(`# cwd: ${process.cwd()}`);
|
|
58
|
+
writeFile(`# started: ${new Date(started).toISOString()}`);
|
|
59
|
+
pruneLogs(dir, keep);
|
|
60
|
+
} catch {
|
|
61
|
+
fileFd = null;
|
|
62
|
+
filePath = null;
|
|
63
|
+
}
|
|
64
|
+
return filePath;
|
|
65
|
+
}
|
|
66
|
+
function runLogPath() {
|
|
67
|
+
return filePath;
|
|
68
|
+
}
|
|
69
|
+
function closeRunLog() {
|
|
70
|
+
if (fileFd === null)
|
|
71
|
+
return;
|
|
72
|
+
try {
|
|
73
|
+
closeSync(fileFd);
|
|
74
|
+
} catch {}
|
|
75
|
+
fileFd = null;
|
|
76
|
+
}
|
|
77
|
+
function writeFile(line) {
|
|
78
|
+
if (fileFd === null)
|
|
79
|
+
return;
|
|
80
|
+
try {
|
|
81
|
+
writeSync(fileFd, `${line}
|
|
82
|
+
`);
|
|
83
|
+
} catch {}
|
|
84
|
+
}
|
|
85
|
+
function pruneLogs(dir, keep) {
|
|
86
|
+
try {
|
|
87
|
+
const files = readdirSync(dir).filter((f) => f.endsWith(".log")).sort();
|
|
88
|
+
for (const f of files.slice(0, Math.max(0, files.length - keep)))
|
|
89
|
+
unlinkSync(join(dir, f));
|
|
90
|
+
} catch {}
|
|
91
|
+
}
|
|
92
|
+
function redactArgv(argv) {
|
|
93
|
+
return argv.map((a, i) => /password|token|secret|key/i.test(argv[i - 1] ?? "") ? "***" : a);
|
|
94
|
+
}
|
|
95
|
+
function stamp(t) {
|
|
96
|
+
return c.gray(`${(t / 1000).toFixed(1).padStart(5, " ")}s`);
|
|
97
|
+
}
|
|
98
|
+
function render(e) {
|
|
99
|
+
const s = stamp(e.t);
|
|
100
|
+
switch (e.level) {
|
|
101
|
+
case "step":
|
|
102
|
+
return `${s} ${c.blue("\u203A")} ${c.bold(e.msg)}`;
|
|
103
|
+
case "ok":
|
|
104
|
+
return `${s} ${c.green("\u2713")} ${e.msg}`;
|
|
105
|
+
case "warn":
|
|
106
|
+
return `${s} ${c.yellow("!")} ${e.msg}`;
|
|
107
|
+
case "error":
|
|
108
|
+
return `${s} ${c.red("\u2717")} ${e.msg}${e.hint ? `
|
|
109
|
+
|
|
110
|
+
${c.gray(e.hint)}` : ""}`;
|
|
111
|
+
case "debug":
|
|
112
|
+
return `${s} ${c.gray("\xB7")} ${c.gray(e.msg)}`;
|
|
113
|
+
case "host":
|
|
114
|
+
return `${s} ${c.magenta((e.host ?? "").padEnd(15).slice(0, 15))} ${e.msg}`;
|
|
115
|
+
case "output":
|
|
116
|
+
return e.msg;
|
|
117
|
+
case "plain":
|
|
118
|
+
case "result":
|
|
119
|
+
return e.msg;
|
|
120
|
+
default:
|
|
121
|
+
return `${s} ${e.msg}`;
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
function fileLine(e) {
|
|
125
|
+
const where = e.host ? ` [${e.host}]` : "";
|
|
126
|
+
const src = e.level === "output" ? ` ${e.stream === "stderr" ? "err" : "out"}${e.label ? ` (${e.label})` : ""}` : "";
|
|
127
|
+
const extra = e.hint ? `
|
|
128
|
+
${e.hint.split(`
|
|
129
|
+
`).map((l) => ` ${l}`).join(`
|
|
130
|
+
`)}` : "";
|
|
131
|
+
return `${e.ts} ${e.level.padEnd(6)}${where}${src} ${stripAnsi(e.msg)}${extra}`;
|
|
132
|
+
}
|
|
133
|
+
function emit(partial) {
|
|
134
|
+
partial = { ...partial, msg: redact(partial.msg), ...partial.hint === undefined ? {} : { hint: redact(partial.hint) } };
|
|
135
|
+
const now = Date.now();
|
|
136
|
+
const e = { ts: new Date(now).toISOString(), t: now - started, ...partial };
|
|
137
|
+
writeFile(fileLine(e));
|
|
138
|
+
if (e.level !== "debug" && e.level !== "result") {
|
|
139
|
+
tail.push(stripAnsi(e.host ? `[${e.host}] ${e.msg}` : e.msg));
|
|
140
|
+
if (tail.length > TAIL_MAX)
|
|
141
|
+
tail.shift();
|
|
142
|
+
}
|
|
143
|
+
for (const fn of listeners)
|
|
144
|
+
fn(e);
|
|
145
|
+
if (e.level === "debug" && !verbose)
|
|
146
|
+
return;
|
|
147
|
+
if (e.level === "result" && format === "pretty")
|
|
148
|
+
return;
|
|
149
|
+
if (format === "json") {
|
|
150
|
+
realLog(JSON.stringify({ ...e, msg: stripAnsi(e.msg) }));
|
|
151
|
+
return;
|
|
152
|
+
}
|
|
153
|
+
const toStderr = e.level === "error" || e.level === "output" && e.stream === "stderr";
|
|
154
|
+
(toStderr ? console.error : console.log)(render(e));
|
|
155
|
+
}
|
|
156
|
+
function setLogFormat(f) {
|
|
157
|
+
format = f;
|
|
158
|
+
colorOn = process.stdout.isTTY && process.env.NO_COLOR === undefined && f === "pretty";
|
|
159
|
+
if (f === "json") {
|
|
160
|
+
console.log = (...args) => emitLines("plain", args);
|
|
161
|
+
console.info = console.log;
|
|
162
|
+
console.warn = (...args) => emitLines("warn", args);
|
|
163
|
+
console.error = (...args) => emitLines("error", args);
|
|
164
|
+
} else {
|
|
165
|
+
console.log = realLog;
|
|
166
|
+
console.error = realError;
|
|
167
|
+
}
|
|
168
|
+
}
|
|
169
|
+
function emitLines(level, args) {
|
|
170
|
+
const text = args.map((a) => typeof a === "string" ? a : a instanceof Error ? a.message : JSON.stringify(a)).join(" ");
|
|
171
|
+
for (const line of text.split(`
|
|
172
|
+
`))
|
|
173
|
+
emit({ level, msg: line });
|
|
35
174
|
}
|
|
36
|
-
var
|
|
175
|
+
var knownSecrets, REDACTED = "[REDACTED]", SECRET_PATTERNS, format, colorOn, wrap = (code) => (s) => colorOn ? `\x1B[${code}m${s}\x1B[0m` : s, c, verbose = false, started, ANSI, stripAnsi = (s) => s.replace(ANSI, ""), fileFd = null, filePath = null, TAIL_MAX = 60, tail, listeners, realLog, realError, log, EpdError;
|
|
37
176
|
var init_log = __esm(() => {
|
|
38
|
-
|
|
177
|
+
knownSecrets = new Set;
|
|
178
|
+
SECRET_PATTERNS = [
|
|
179
|
+
[/(-----BEGIN [A-Z ]*PRIVATE KEY-----)[\s\S]*?(-----END [A-Z ]*PRIVATE KEY-----)/g, `$1${REDACTED}$2`],
|
|
180
|
+
[/(\bBearer\s+)[A-Za-z0-9._~+/=-]+/gi, `$1${REDACTED}`],
|
|
181
|
+
[/\b(gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/g, REDACTED],
|
|
182
|
+
[/("(?:apiToken|api_token|password|passwd|secret|token)"\s*:\s*")[^"]*"/gi, `$1${REDACTED}"`],
|
|
183
|
+
[/(?<![.\w])((?:password|passwd|secret|token|api_token)\s*[:=]\s*)\S+/gi, `$1${REDACTED}`],
|
|
184
|
+
[/\b([A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY)[A-Za-z0-9_]*=)\S+/g, `$1${REDACTED}`]
|
|
185
|
+
];
|
|
186
|
+
format = process.env.EPD_LOG_FORMAT === "json" ? "json" : "pretty";
|
|
187
|
+
colorOn = process.stdout.isTTY && process.env.NO_COLOR === undefined && format === "pretty";
|
|
39
188
|
c = {
|
|
40
189
|
dim: wrap("2"),
|
|
41
190
|
bold: wrap("1"),
|
|
@@ -47,48 +196,50 @@ var init_log = __esm(() => {
|
|
|
47
196
|
cyan: wrap("36"),
|
|
48
197
|
gray: wrap("90")
|
|
49
198
|
};
|
|
50
|
-
knownSecrets = new Set;
|
|
51
|
-
SECRET_PATTERNS = [
|
|
52
|
-
[/(-----BEGIN [A-Z ]*PRIVATE KEY-----)[\s\S]*?(-----END [A-Z ]*PRIVATE KEY-----)/g, `$1${REDACTED}$2`],
|
|
53
|
-
[/(\bBearer\s+)[A-Za-z0-9._~+/=-]+/gi, `$1${REDACTED}`],
|
|
54
|
-
[/\b(gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{20,})\b/g, REDACTED],
|
|
55
|
-
[/("(?:apiToken|api_token|password|passwd|secret|token)"\s*:\s*")[^"]*"/gi, `$1${REDACTED}"`],
|
|
56
|
-
[/(?<![.\w])((?:password|passwd|secret|token|api_token)\s*[:=]\s*)\S+/gi, `$1${REDACTED}`],
|
|
57
|
-
[/\b([A-Za-z0-9_]*(?:TOKEN|SECRET|PASSWORD|PASSWD|API_KEY|PRIVATE_KEY)[A-Za-z0-9_]*=)\S+/g, `$1${REDACTED}`]
|
|
58
|
-
];
|
|
59
199
|
started = Date.now();
|
|
200
|
+
ANSI = /\x1b\[[0-9;?]*[A-Za-z]/g;
|
|
201
|
+
tail = [];
|
|
202
|
+
listeners = new Set;
|
|
203
|
+
realLog = console.log.bind(console);
|
|
204
|
+
realError = console.error.bind(console);
|
|
60
205
|
log = {
|
|
61
|
-
|
|
62
|
-
console.log(
|
|
206
|
+
template(msg) {
|
|
207
|
+
console.log(msg);
|
|
208
|
+
},
|
|
209
|
+
step(msg, phase) {
|
|
210
|
+
emit({ level: "step", msg, phase });
|
|
63
211
|
},
|
|
64
212
|
info(msg) {
|
|
65
|
-
|
|
213
|
+
emit({ level: "info", msg });
|
|
66
214
|
},
|
|
67
215
|
ok(msg) {
|
|
68
|
-
|
|
216
|
+
emit({ level: "ok", msg });
|
|
69
217
|
},
|
|
70
218
|
warn(msg) {
|
|
71
|
-
|
|
219
|
+
emit({ level: "warn", msg });
|
|
72
220
|
},
|
|
73
|
-
error(msg) {
|
|
74
|
-
|
|
221
|
+
error(msg, hint) {
|
|
222
|
+
emit({ level: "error", msg, hint });
|
|
75
223
|
},
|
|
76
224
|
debug(msg) {
|
|
77
|
-
|
|
78
|
-
console.log(`${stamp()} ${c.gray("\xB7")} ${c.gray(redact(msg))}`);
|
|
225
|
+
emit({ level: "debug", msg });
|
|
79
226
|
},
|
|
80
227
|
plain(msg) {
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
console.log(msg);
|
|
228
|
+
for (const line of msg.split(`
|
|
229
|
+
`))
|
|
230
|
+
emit({ level: "plain", msg: line });
|
|
85
231
|
},
|
|
86
|
-
host(host, msg) {
|
|
87
|
-
const
|
|
88
|
-
for (const line of redact(msg).split(`
|
|
232
|
+
host(host, msg, phase) {
|
|
233
|
+
for (const line of msg.split(`
|
|
89
234
|
`))
|
|
90
235
|
if (line.length)
|
|
91
|
-
|
|
236
|
+
emit({ level: "host", host, msg: line, phase });
|
|
237
|
+
},
|
|
238
|
+
output(line, stream, label, host) {
|
|
239
|
+
emit({ level: "output", msg: line, stream, label, host });
|
|
240
|
+
},
|
|
241
|
+
result(ok, code, msg, hint) {
|
|
242
|
+
emit({ level: "result", ok, code, msg, hint, logFile: filePath ?? undefined });
|
|
92
243
|
}
|
|
93
244
|
};
|
|
94
245
|
EpdError = class EpdError extends Error {
|
|
@@ -101,6 +252,28 @@ var init_log = __esm(() => {
|
|
|
101
252
|
};
|
|
102
253
|
});
|
|
103
254
|
|
|
255
|
+
// src/util/interrupt.ts
|
|
256
|
+
function onInterrupt(fn) {
|
|
257
|
+
handlers.add(fn);
|
|
258
|
+
return () => handlers.delete(fn);
|
|
259
|
+
}
|
|
260
|
+
async function runInterruptHandlers(timeoutMs = 20000) {
|
|
261
|
+
const all = [...handlers].reverse();
|
|
262
|
+
handlers.clear();
|
|
263
|
+
const work = (async () => {
|
|
264
|
+
for (const fn of all) {
|
|
265
|
+
try {
|
|
266
|
+
await fn();
|
|
267
|
+
} catch {}
|
|
268
|
+
}
|
|
269
|
+
})();
|
|
270
|
+
await Promise.race([work, new Promise((r) => setTimeout(r, timeoutMs))]);
|
|
271
|
+
}
|
|
272
|
+
var handlers;
|
|
273
|
+
var init_interrupt = __esm(() => {
|
|
274
|
+
handlers = new Set;
|
|
275
|
+
});
|
|
276
|
+
|
|
104
277
|
// src/util/misc.ts
|
|
105
278
|
function hash32(s) {
|
|
106
279
|
let h = 2166136261;
|
|
@@ -173,7 +346,7 @@ var init_misc = __esm(() => {
|
|
|
173
346
|
|
|
174
347
|
// src/util/prompt.ts
|
|
175
348
|
function interactive() {
|
|
176
|
-
return Boolean(process.stdin.isTTY && process.stdout.isTTY);
|
|
349
|
+
return Boolean(process.stdin.isTTY && process.stdout.isTTY) && logFormat() !== "json" && !process.env.CI;
|
|
177
350
|
}
|
|
178
351
|
async function readLine() {
|
|
179
352
|
for await (const line of console)
|
|
@@ -243,6 +416,170 @@ var init_prompt = __esm(() => {
|
|
|
243
416
|
init_log();
|
|
244
417
|
});
|
|
245
418
|
|
|
419
|
+
// src/util/proc.ts
|
|
420
|
+
import { existsSync } from "fs";
|
|
421
|
+
import { dirname, join as join2 } from "path";
|
|
422
|
+
async function run(cmd, opts = {}) {
|
|
423
|
+
const label = opts.label ?? cmd.join(" ");
|
|
424
|
+
log.debug(`local: ${cmd.join(" ")}`);
|
|
425
|
+
const startedAt = Date.now();
|
|
426
|
+
const proc = Bun.spawn(cmd, {
|
|
427
|
+
cwd: opts.cwd,
|
|
428
|
+
env: opts.env ? { ...process.env, ...opts.env } : process.env,
|
|
429
|
+
stdin: typeof opts.input === "string" ? new TextEncoder().encode(opts.input) : opts.input ?? "inherit",
|
|
430
|
+
stdout: "pipe",
|
|
431
|
+
stderr: "pipe"
|
|
432
|
+
});
|
|
433
|
+
let lastOutput = Date.now();
|
|
434
|
+
const heartbeat = setInterval(() => {
|
|
435
|
+
if (Date.now() - lastOutput < HEARTBEAT_MS)
|
|
436
|
+
return;
|
|
437
|
+
lastOutput = Date.now();
|
|
438
|
+
log.info(`\u2026 still running: ${label} (${Math.round((Date.now() - startedAt) / 1000)}s)`);
|
|
439
|
+
}, Math.min(HEARTBEAT_MS, 5000));
|
|
440
|
+
const onLine = opts.stream ? (stream) => (line) => {
|
|
441
|
+
lastOutput = Date.now();
|
|
442
|
+
log.output(line, stream, label);
|
|
443
|
+
} : () => () => {
|
|
444
|
+
lastOutput = Date.now();
|
|
445
|
+
};
|
|
446
|
+
let stdout;
|
|
447
|
+
let stderr;
|
|
448
|
+
let code;
|
|
449
|
+
try {
|
|
450
|
+
[stdout, stderr, code] = await Promise.all([
|
|
451
|
+
collect(proc.stdout, onLine("stdout"), !opts.stream),
|
|
452
|
+
collect(proc.stderr, onLine("stderr"), !opts.stream),
|
|
453
|
+
proc.exited
|
|
454
|
+
]);
|
|
455
|
+
} finally {
|
|
456
|
+
clearInterval(heartbeat);
|
|
457
|
+
}
|
|
458
|
+
log.debug(`exit ${code} after ${Date.now() - startedAt}ms: ${label}`);
|
|
459
|
+
const result = { code, stdout: stdout.trim(), stderr: stderr.trim() };
|
|
460
|
+
if (code !== 0 && !opts.allowFailure) {
|
|
461
|
+
throw new EpdError(`command failed (exit ${code}): ${label}`, result.stderr || result.stdout || undefined);
|
|
462
|
+
}
|
|
463
|
+
return result;
|
|
464
|
+
}
|
|
465
|
+
async function collect(stream, onLine, full) {
|
|
466
|
+
const reader = stream.getReader();
|
|
467
|
+
const decoder = new TextDecoder;
|
|
468
|
+
let captured = "";
|
|
469
|
+
let pending = "";
|
|
470
|
+
const push = (text) => {
|
|
471
|
+
captured += text;
|
|
472
|
+
if (!full && captured.length > TAIL_BYTES * 2)
|
|
473
|
+
captured = captured.slice(-TAIL_BYTES);
|
|
474
|
+
pending += text;
|
|
475
|
+
const lines = pending.split(/\r\n|\n|\r/);
|
|
476
|
+
pending = lines.pop() ?? "";
|
|
477
|
+
for (const line of lines)
|
|
478
|
+
if (line.trim())
|
|
479
|
+
onLine(line);
|
|
480
|
+
};
|
|
481
|
+
try {
|
|
482
|
+
while (true) {
|
|
483
|
+
const { done, value } = await reader.read();
|
|
484
|
+
if (done)
|
|
485
|
+
break;
|
|
486
|
+
push(decoder.decode(value, { stream: true }));
|
|
487
|
+
}
|
|
488
|
+
push(decoder.decode());
|
|
489
|
+
if (pending.trim())
|
|
490
|
+
onLine(pending);
|
|
491
|
+
} finally {
|
|
492
|
+
reader.releaseLock();
|
|
493
|
+
}
|
|
494
|
+
return full ? captured : captured.slice(-TAIL_BYTES);
|
|
495
|
+
}
|
|
496
|
+
function localShell(kind = "sh") {
|
|
497
|
+
if (process.platform !== "win32")
|
|
498
|
+
return kind === "sh" ? "/bin/sh" : "bash";
|
|
499
|
+
if (windowsBash)
|
|
500
|
+
return windowsBash;
|
|
501
|
+
const candidates = [];
|
|
502
|
+
const git = Bun.which("git");
|
|
503
|
+
if (git)
|
|
504
|
+
candidates.push(join2(dirname(git), "..", "bin", "bash.exe"), join2(dirname(git), "..", "usr", "bin", "bash.exe"));
|
|
505
|
+
for (const root of [process.env.ProgramFiles, process.env["ProgramFiles(x86)"], process.env.LOCALAPPDATA && join2(process.env.LOCALAPPDATA, "Programs")]) {
|
|
506
|
+
if (root)
|
|
507
|
+
candidates.push(join2(root, "Git", "bin", "bash.exe"));
|
|
508
|
+
}
|
|
509
|
+
const onPath = Bun.which("bash");
|
|
510
|
+
if (onPath && !/\\system32\\/i.test(onPath))
|
|
511
|
+
candidates.push(onPath);
|
|
512
|
+
const found = candidates.find((c) => existsSync(c));
|
|
513
|
+
if (!found) {
|
|
514
|
+
throw new EpdError("no POSIX shell found on this machine", "On Windows epd runs shell steps through Git Bash. Install Git for Windows (https://git-scm.com/download/win) and open a new terminal.");
|
|
515
|
+
}
|
|
516
|
+
return windowsBash = found;
|
|
517
|
+
}
|
|
518
|
+
async function runShell(script, opts = {}) {
|
|
519
|
+
return run([localShell(), "-c", script], { ...opts, label: opts.label ?? script });
|
|
520
|
+
}
|
|
521
|
+
async function which(bin) {
|
|
522
|
+
return Bun.which(bin);
|
|
523
|
+
}
|
|
524
|
+
async function requireLocal(bin, hint) {
|
|
525
|
+
if (!await which(bin))
|
|
526
|
+
throw new EpdError(`\`${bin}\` was not found on this machine`, hint);
|
|
527
|
+
}
|
|
528
|
+
var HEARTBEAT_MS, TAIL_BYTES = 65536, windowsBash;
|
|
529
|
+
var init_proc = __esm(() => {
|
|
530
|
+
init_log();
|
|
531
|
+
HEARTBEAT_MS = Number(process.env.EPD_HEARTBEAT_MS ?? 20000);
|
|
532
|
+
});
|
|
533
|
+
|
|
534
|
+
// src/util/container-engine.ts
|
|
535
|
+
import { basename } from "path";
|
|
536
|
+
function validateContainerEngine(value) {
|
|
537
|
+
if (!value.trim() || value.startsWith("-") || /[\s\x00-\x1f;&|`$<>]/.test(value)) {
|
|
538
|
+
throw new EpdError("container_engine must be auto or a single Docker-compatible executable name or path");
|
|
539
|
+
}
|
|
540
|
+
return value;
|
|
541
|
+
}
|
|
542
|
+
function engineKind(engine) {
|
|
543
|
+
return basename(engine).replace(/\.exe$/i, "");
|
|
544
|
+
}
|
|
545
|
+
async function containerEngine(configured = "auto", prompt = true) {
|
|
546
|
+
const requested = validateContainerEngine(process.env.EPD_CONTAINER_ENGINE || configured);
|
|
547
|
+
const candidates = requested === "auto" ? CONTAINER_ENGINES : [requested];
|
|
548
|
+
const probe = async (engine) => {
|
|
549
|
+
const executable = Bun.which(engine, { PATH: process.env.PATH });
|
|
550
|
+
if (!executable)
|
|
551
|
+
return false;
|
|
552
|
+
try {
|
|
553
|
+
const child = Bun.spawn([executable, "info"], { stdout: "ignore", stderr: "ignore", timeout: 1e4 });
|
|
554
|
+
return await child.exited === 0;
|
|
555
|
+
} catch {
|
|
556
|
+
return false;
|
|
557
|
+
}
|
|
558
|
+
};
|
|
559
|
+
for (const engine of candidates)
|
|
560
|
+
if (await probe(engine))
|
|
561
|
+
return engine;
|
|
562
|
+
if (prompt && interactive()) {
|
|
563
|
+
for (;; ) {
|
|
564
|
+
const answer = await ask(`No usable container engine found. Start one and enter its executable, or enter cancel`, requested === "auto" ? "podman" : requested);
|
|
565
|
+
if (answer === "cancel")
|
|
566
|
+
break;
|
|
567
|
+
const engine = validateContainerEngine(answer);
|
|
568
|
+
if (engine !== "auto" && await probe(engine))
|
|
569
|
+
return engine;
|
|
570
|
+
console.error(`Cannot connect with ${engine}. Start its service or VM and try again.`);
|
|
571
|
+
}
|
|
572
|
+
}
|
|
573
|
+
throw new EpdError("No usable local container engine", "Start Docker, Podman or nerdctl, or set container_engine in epd.yml to a Docker-compatible executable. EPD_CONTAINER_ENGINE overrides YAML. On macOS, start your Podman machine.");
|
|
574
|
+
}
|
|
575
|
+
var CONTAINER_ENGINES;
|
|
576
|
+
var init_container_engine = __esm(() => {
|
|
577
|
+
init_log();
|
|
578
|
+
init_proc();
|
|
579
|
+
init_prompt();
|
|
580
|
+
CONTAINER_ENGINES = ["docker", "podman", "nerdctl"];
|
|
581
|
+
});
|
|
582
|
+
|
|
246
583
|
// src/core/names.ts
|
|
247
584
|
function paths(cfg) {
|
|
248
585
|
const root = cfg.remoteRoot;
|
|
@@ -343,19 +680,19 @@ var init_names = __esm(() => {
|
|
|
343
680
|
});
|
|
344
681
|
|
|
345
682
|
// src/config/load.ts
|
|
346
|
-
import { existsSync, readFileSync } from "fs";
|
|
683
|
+
import { existsSync as existsSync2, readFileSync } from "fs";
|
|
347
684
|
import { isIPv6 } from "net";
|
|
348
|
-
import { dirname, join, resolve } from "path";
|
|
349
|
-
import { homedir } from "os";
|
|
685
|
+
import { dirname as dirname2, join as join3, resolve } from "path";
|
|
686
|
+
import { homedir as homedir2 } from "os";
|
|
350
687
|
function findConfigFile(startDir) {
|
|
351
688
|
let dir = resolve(startDir);
|
|
352
689
|
for (;; ) {
|
|
353
690
|
for (const name of CONFIG_NAMES) {
|
|
354
|
-
const p =
|
|
355
|
-
if (
|
|
691
|
+
const p = join3(dir, name);
|
|
692
|
+
if (existsSync2(p))
|
|
356
693
|
return p;
|
|
357
694
|
}
|
|
358
|
-
const parent =
|
|
695
|
+
const parent = dirname2(dir);
|
|
359
696
|
if (parent === dir)
|
|
360
697
|
return null;
|
|
361
698
|
dir = parent;
|
|
@@ -399,8 +736,8 @@ function loadEnvironment(root, destination) {
|
|
|
399
736
|
if (v !== undefined)
|
|
400
737
|
env[k] = v;
|
|
401
738
|
for (const f of files) {
|
|
402
|
-
const p =
|
|
403
|
-
if (!
|
|
739
|
+
const p = join3(root, f);
|
|
740
|
+
if (!existsSync2(p))
|
|
404
741
|
continue;
|
|
405
742
|
for (const [k, v] of Object.entries(parseDotenv(readFileSync(p, "utf8")))) {
|
|
406
743
|
if (process.env[k] === undefined)
|
|
@@ -410,7 +747,7 @@ function loadEnvironment(root, destination) {
|
|
|
410
747
|
return env;
|
|
411
748
|
}
|
|
412
749
|
function interpolateText(text, env, file) {
|
|
413
|
-
|
|
750
|
+
const substitute = (value) => value.replace(/\$(\$?)\{([A-Za-z_][A-Za-z0-9_]*)(?::-([^}]*))?\}/g, (_m, escape, name, dflt) => {
|
|
414
751
|
if (escape)
|
|
415
752
|
return `\${${name}${dflt !== undefined ? `:-${dflt}` : ""}}`;
|
|
416
753
|
const v = env[name];
|
|
@@ -420,6 +757,83 @@ function interpolateText(text, env, file) {
|
|
|
420
757
|
return dflt;
|
|
421
758
|
throw new EpdError(`${file}: environment variable \${${name}} is not set`, `Export it, add it to .env, or write \${${name}:-fallback}.`);
|
|
422
759
|
});
|
|
760
|
+
let quote = null;
|
|
761
|
+
let flowDepth = 0;
|
|
762
|
+
let blockIndent = null;
|
|
763
|
+
let blockContentIndent = null;
|
|
764
|
+
return text.split(`
|
|
765
|
+
`).map((line) => {
|
|
766
|
+
const indent = line.match(/^ */)[0].length;
|
|
767
|
+
if (blockIndent !== null) {
|
|
768
|
+
if (!line.trim() || indent > blockIndent) {
|
|
769
|
+
blockContentIndent ??= line.trim() ? indent : null;
|
|
770
|
+
if (blockContentIndent === null || indent >= blockContentIndent)
|
|
771
|
+
return substitute(line);
|
|
772
|
+
}
|
|
773
|
+
blockIndent = blockContentIndent = null;
|
|
774
|
+
}
|
|
775
|
+
let comment = line.length;
|
|
776
|
+
let scalarStart = quote === null;
|
|
777
|
+
for (let i = 0;i < line.length; i++) {
|
|
778
|
+
const char = line[i];
|
|
779
|
+
if (quote) {
|
|
780
|
+
if (quote === '"' && char === "\\") {
|
|
781
|
+
i++;
|
|
782
|
+
continue;
|
|
783
|
+
}
|
|
784
|
+
if (char === quote) {
|
|
785
|
+
if (quote === "'" && line[i + 1] === "'") {
|
|
786
|
+
i++;
|
|
787
|
+
continue;
|
|
788
|
+
}
|
|
789
|
+
quote = null;
|
|
790
|
+
}
|
|
791
|
+
continue;
|
|
792
|
+
}
|
|
793
|
+
if (char === "#" && (i === 0 || /\s/.test(line[i - 1]))) {
|
|
794
|
+
comment = i;
|
|
795
|
+
break;
|
|
796
|
+
}
|
|
797
|
+
if (char === "$" && /^\$\$?\{/.test(line.slice(i))) {
|
|
798
|
+
const end = line.indexOf("}", i);
|
|
799
|
+
if (end !== -1) {
|
|
800
|
+
i = end;
|
|
801
|
+
scalarStart = false;
|
|
802
|
+
continue;
|
|
803
|
+
}
|
|
804
|
+
}
|
|
805
|
+
if (scalarStart && (char === "'" || char === '"')) {
|
|
806
|
+
quote = char;
|
|
807
|
+
scalarStart = false;
|
|
808
|
+
continue;
|
|
809
|
+
}
|
|
810
|
+
if (/\s/.test(char))
|
|
811
|
+
continue;
|
|
812
|
+
if (scalarStart && (char === "&" || char === "!")) {
|
|
813
|
+
while (i + 1 < line.length && !/\s/.test(line[i + 1]))
|
|
814
|
+
i++;
|
|
815
|
+
continue;
|
|
816
|
+
}
|
|
817
|
+
if (scalarStart && (char === "[" || char === "{")) {
|
|
818
|
+
flowDepth++;
|
|
819
|
+
} else if (flowDepth && (char === "]" || char === "}")) {
|
|
820
|
+
flowDepth--;
|
|
821
|
+
scalarStart = false;
|
|
822
|
+
} else if (flowDepth && (char === "," || char === ":") || (char === ":" || char === "-" || char === "?") && /\s/.test(line[i + 1] || " ")) {
|
|
823
|
+
scalarStart = true;
|
|
824
|
+
} else {
|
|
825
|
+
scalarStart = false;
|
|
826
|
+
}
|
|
827
|
+
}
|
|
828
|
+
const content = line.slice(0, comment);
|
|
829
|
+
if (!quote && /(?:^|:\s+|-\s+)[|>](?:[1-9][+-]?|[+-][1-9]?)?\s*$/.test(content)) {
|
|
830
|
+
blockIndent = indent;
|
|
831
|
+
const explicitIndent = content.match(/[|>][+-]?([1-9])/);
|
|
832
|
+
blockContentIndent = explicitIndent ? indent + Number(explicitIndent[1]) : null;
|
|
833
|
+
}
|
|
834
|
+
return substitute(content) + line.slice(comment);
|
|
835
|
+
}).join(`
|
|
836
|
+
`);
|
|
423
837
|
}
|
|
424
838
|
function bareRegistryPassword(text) {
|
|
425
839
|
let inRegistry = false;
|
|
@@ -566,7 +980,7 @@ function levenshtein2(a, b) {
|
|
|
566
980
|
return m[a.length][b.length];
|
|
567
981
|
}
|
|
568
982
|
function expandHome(p) {
|
|
569
|
-
return p.startsWith("~/") ?
|
|
983
|
+
return p.startsWith("~/") ? join3(homedir2(), p.slice(2)) : p;
|
|
570
984
|
}
|
|
571
985
|
function hostnameProblem(h) {
|
|
572
986
|
const port = HOST_PORT.exec(h);
|
|
@@ -755,21 +1169,21 @@ function parseHealth(raw, path, dflt) {
|
|
|
755
1169
|
function loadConfig(opts = {}) {
|
|
756
1170
|
const cwd = opts.cwd ?? process.cwd();
|
|
757
1171
|
const configPath = opts.file ? resolve(cwd, opts.file) : findConfigFile(cwd) ?? fail("epd.yml", "not found", "Run `epd init` to create one.");
|
|
758
|
-
if (!
|
|
1172
|
+
if (!existsSync2(configPath))
|
|
759
1173
|
throw new EpdError(`config file not found: ${configPath}`);
|
|
760
|
-
const root =
|
|
1174
|
+
const root = dirname2(configPath);
|
|
761
1175
|
const destination = opts.destination;
|
|
762
1176
|
const env = loadEnvironment(root, destination);
|
|
763
1177
|
let raw = parseYaml(configPath, env);
|
|
764
1178
|
let overlay;
|
|
765
1179
|
if (destination) {
|
|
766
1180
|
const overlays = [
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
].filter(
|
|
1181
|
+
join3(root, `epd.${destination}.yml`),
|
|
1182
|
+
join3(root, `epd.${destination}.yaml`),
|
|
1183
|
+
join3(root, "config", `epd.${destination}.yml`)
|
|
1184
|
+
].filter(existsSync2);
|
|
771
1185
|
if (!overlays.length) {
|
|
772
|
-
throw new EpdError(`no config found for destination "${destination}"`, `Create ${
|
|
1186
|
+
throw new EpdError(`no config found for destination "${destination}"`, `Create ${join3(root, `epd.${destination}.yml`)} with the values that differ.`);
|
|
773
1187
|
}
|
|
774
1188
|
overlay = { file: overlays[0], raw: parseYaml(overlays[0], env) };
|
|
775
1189
|
raw = deepMerge(raw, overlay.raw);
|
|
@@ -1070,6 +1484,20 @@ function normalize(raw, configPath, root, destination) {
|
|
|
1070
1484
|
const image = check(asString(raw.image, "epd.yml.image", registry ? `${registry.server ? registry.server + "/" : ""}${registry.username}/${name}` : name).toLowerCase(), "epd.yml.image", imageProblem, IMAGE_HINT);
|
|
1071
1485
|
const buildRaw = asMap(raw.build, "epd.yml.build");
|
|
1072
1486
|
checkKeys(buildRaw, ["dockerfile", "context", "platform", "target", "args", "secrets", "cache", "remote"], "epd.yml.build");
|
|
1487
|
+
const serverRaw = raw.server ?? {};
|
|
1488
|
+
if (typeof serverRaw !== "object" || Array.isArray(serverRaw))
|
|
1489
|
+
fail("epd.yml.server", "expected a mapping");
|
|
1490
|
+
const baseline = serverRaw;
|
|
1491
|
+
checkKeys(baseline, ["auto_updates", "firewall", "allow", "ssh_hardening", "log_rotation", "reboot_window"], "epd.yml.server");
|
|
1492
|
+
const allow = asList(baseline.allow, "epd.yml.server.allow").map((value) => {
|
|
1493
|
+
const port = Number(value);
|
|
1494
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
1495
|
+
fail("epd.yml.server.allow", "ports must be integers between 1 and 65535");
|
|
1496
|
+
return port;
|
|
1497
|
+
});
|
|
1498
|
+
const rebootWindow = baseline.reboot_window === false ? false : asString(baseline.reboot_window, "epd.yml.server.reboot_window", "03:00");
|
|
1499
|
+
if (rebootWindow !== false && !/^([01][0-9]|2[0-3]):[0-5][0-9]$/.test(rebootWindow))
|
|
1500
|
+
fail("epd.yml.server.reboot_window", "expected HH:MM or false");
|
|
1073
1501
|
const sshRaw = asMap(raw.ssh, "epd.yml.ssh");
|
|
1074
1502
|
checkKeys(sshRaw, ["user", "port", "key", "options", "proxy_jump", "control_persist", "sudo_password"], "epd.yml.ssh");
|
|
1075
1503
|
const procRaw = asMap(raw.process, "epd.yml.process");
|
|
@@ -1169,11 +1597,20 @@ function normalize(raw, configPath, root, destination) {
|
|
|
1169
1597
|
const cfg = {
|
|
1170
1598
|
name,
|
|
1171
1599
|
mode,
|
|
1600
|
+
containerEngine: validateContainerEngine(asString(raw.container_engine, "epd.yml.container_engine", "auto")),
|
|
1172
1601
|
destination,
|
|
1173
1602
|
configPath,
|
|
1174
1603
|
root,
|
|
1175
1604
|
image,
|
|
1176
1605
|
registry,
|
|
1606
|
+
server: {
|
|
1607
|
+
autoUpdates: asBool(baseline.auto_updates, "epd.yml.server.auto_updates", true),
|
|
1608
|
+
firewall: asBool(baseline.firewall, "epd.yml.server.firewall", true),
|
|
1609
|
+
allow: [...new Set(allow)],
|
|
1610
|
+
sshHardening: asBool(baseline.ssh_hardening, "epd.yml.server.ssh_hardening", true),
|
|
1611
|
+
logRotation: asBool(baseline.log_rotation, "epd.yml.server.log_rotation", true),
|
|
1612
|
+
rebootWindow
|
|
1613
|
+
},
|
|
1177
1614
|
build: {
|
|
1178
1615
|
dockerfile: asString(buildRaw.dockerfile, "epd.yml.build.dockerfile", "Dockerfile"),
|
|
1179
1616
|
context: asString(buildRaw.context, "epd.yml.build.context", "."),
|
|
@@ -1263,6 +1700,7 @@ function validateCrossReferences(cfg) {
|
|
|
1263
1700
|
}
|
|
1264
1701
|
var CONFIG_NAMES, nameProblem, HOST_LABEL, HOST_HINT = 'Use a DNS name such as "example.com", "*.example.com" or an IP address.', PATH_HINT = 'Write a path such as "/health" or "/api".', HOST_PORT, BRACKETED_IPV6, asPort = (v, path, dflt) => asInt(v, path, dflt, 1, 65535), IMAGE_REF, IMAGE_HINT = 'Write an image such as "ghcr.io/acme/api:1.2" or "postgres:17". The repository name must be lower case.', SSH_HOST, SSH_USER, ENV_NAME, ENV_NAME_HINT = "Use letters, digits and underscores, starting with a letter or underscore.", TOP_LEVEL_KEYS;
|
|
1265
1702
|
var init_load = __esm(() => {
|
|
1703
|
+
init_container_engine();
|
|
1266
1704
|
init_log();
|
|
1267
1705
|
init_misc();
|
|
1268
1706
|
init_names();
|
|
@@ -1310,85 +1748,265 @@ var init_load = __esm(() => {
|
|
|
1310
1748
|
"docker_options",
|
|
1311
1749
|
"cloudflare",
|
|
1312
1750
|
"dns",
|
|
1313
|
-
"hetzner"
|
|
1751
|
+
"hetzner",
|
|
1752
|
+
"server",
|
|
1753
|
+
"container_engine"
|
|
1314
1754
|
];
|
|
1315
1755
|
});
|
|
1316
1756
|
|
|
1317
|
-
// src/
|
|
1318
|
-
|
|
1319
|
-
|
|
1320
|
-
|
|
1321
|
-
|
|
1322
|
-
|
|
1323
|
-
|
|
1324
|
-
|
|
1325
|
-
|
|
1326
|
-
|
|
1327
|
-
|
|
1328
|
-
|
|
1329
|
-
|
|
1330
|
-
|
|
1331
|
-
|
|
1332
|
-
|
|
1333
|
-
|
|
1334
|
-
|
|
1335
|
-
|
|
1336
|
-
|
|
1337
|
-
|
|
1338
|
-
|
|
1339
|
-
|
|
1340
|
-
|
|
1341
|
-
|
|
1342
|
-
|
|
1343
|
-
|
|
1344
|
-
|
|
1345
|
-
|
|
1346
|
-
|
|
1347
|
-
|
|
1348
|
-
|
|
1349
|
-
|
|
1350
|
-
|
|
1351
|
-
|
|
1757
|
+
// src/agent/agent.md
|
|
1758
|
+
var agent_default = `# EPD agent guide
|
|
1759
|
+
|
|
1760
|
+
EPD deploys projects over SSH. Both epd and edp are CLI names. This guide ships
|
|
1761
|
+
inside the CLI. Print it with epd agent --guide, or export it with
|
|
1762
|
+
epd agent --write-guide EPD_AGENT.md. Read the project's AGENTS.md too.
|
|
1763
|
+
|
|
1764
|
+
## Setup task
|
|
1765
|
+
|
|
1766
|
+
Inspect the repository and existing epd.yml first. Determine the application's
|
|
1767
|
+
build and start commands, internal port, health endpoint and required secrets.
|
|
1768
|
+
Ask the user for target server addresses, SSH login, domains and TLS email when
|
|
1769
|
+
these are missing. Do not invent infrastructure, credentials or production URLs.
|
|
1770
|
+
|
|
1771
|
+
Prepare configuration and supporting files. Do not provision servers, change DNS
|
|
1772
|
+
or deploy until the user requests those actions. Keep the AI CLI's normal
|
|
1773
|
+
approval and sandbox settings. Do not install software or bypass permissions.
|
|
1774
|
+
|
|
1775
|
+
Run epd --help and the relevant command's --help for the installed version.
|
|
1776
|
+
For unattended initialization, provide explicit values rather than starter defaults:
|
|
1777
|
+
|
|
1778
|
+
epd init --yes --name my-app --mode docker --container-engine auto --host 203.0.113.10 --domain app.example.com --port 3000 --email ops@example.com
|
|
1779
|
+
|
|
1780
|
+
Do not use --force unless replacing the existing file is authorized. Interactive
|
|
1781
|
+
users can run epd init or epd init --interactive for the full setup wizard.
|
|
1782
|
+
The wizard accepts JSON objects for maps such as hooks, build arguments,
|
|
1783
|
+
accessories and advanced sections. JSON strings must be quoted.
|
|
1784
|
+
|
|
1785
|
+
## Container engines
|
|
1786
|
+
|
|
1787
|
+
The top-level YAML setting container_engine defaults to auto. Detection probes
|
|
1788
|
+
Docker, Podman and nerdctl in that order with info. Docker-compatible tools such
|
|
1789
|
+
as OrbStack, Colima and Rancher Desktop can supply the docker CLI or nerdctl.
|
|
1790
|
+
A custom executable name or path is also accepted. It must implement the needed
|
|
1791
|
+
Docker CLI commands. Do not claim that every OCI runtime is compatible.
|
|
1792
|
+
|
|
1793
|
+
container_engine: podman
|
|
1794
|
+
|
|
1795
|
+
EPD_CONTAINER_ENGINE overrides YAML. A configured executable is checked directly;
|
|
1796
|
+
it does not silently fall back. When no engine works, an interactive terminal
|
|
1797
|
+
asks for another executable. CI and JSON logging fail with instructions instead.
|
|
1798
|
+
An executable path must not contain spaces or shell syntax. Extra arguments
|
|
1799
|
+
belong in an executable wrapper, not in container_engine.
|
|
1800
|
+
|
|
1801
|
+
This setting selects the local builder and image exporter. Remote deployment,
|
|
1802
|
+
provisioning and monitoring still use Docker. Keep mode: docker for local
|
|
1803
|
+
Podman or nerdctl builds. Process mode uploads source and runs it with PM2.
|
|
1804
|
+
Podman Compose needs a Compose provider. nerdctl build needs BuildKit.
|
|
1805
|
+
Cross-platform RUN instructions may need emulation on the selected engine.
|
|
1806
|
+
|
|
1807
|
+
## Configuration
|
|
1808
|
+
|
|
1809
|
+
Use epd config to inspect the resolved config, epd config --raw for merged input,
|
|
1810
|
+
and epd config --json for structured output. These outputs can contain clear
|
|
1811
|
+
configuration values. Do not publish them without checking for secrets.
|
|
1812
|
+
|
|
1813
|
+
Common fields in epd.yml:
|
|
1814
|
+
|
|
1815
|
+
- name, mode, image, container_engine and registry define the app and image delivery.
|
|
1816
|
+
- build has dockerfile, context, platform, target, args, secrets and cache.
|
|
1817
|
+
- ssh has user, port, key, options, proxy_jump and control_persist.
|
|
1818
|
+
- servers maps service names to hosts, replicas, port, domains, routes, command,
|
|
1819
|
+
healthcheck, volumes, labels, cpus, memory and docker_options.
|
|
1820
|
+
- process has install, build, start, exclude, path_prepend and source.
|
|
1821
|
+
- proxy controls TLS, email, entrypoints, cross_host and private_ips.
|
|
1822
|
+
- env.clear holds non-secret values. env.secret lists environment variable names.
|
|
1823
|
+
- accessories maps dependency names to image, host, env, volumes and ports.
|
|
1824
|
+
- hooks has pre_build, pre_deploy, post_deploy and on_failure commands.
|
|
1825
|
+
- server controls firewall, auto_updates, ssh_hardening and log_rotation.
|
|
1826
|
+
- port_base, strategy, keep_releases and remote_root control deployment storage
|
|
1827
|
+
and rollout. Destination overlays use epd.<destination>.yml with -d.
|
|
1828
|
+
|
|
1829
|
+
Use environment variable names for secrets and registry.password. Keep values in
|
|
1830
|
+
the user's shell or a gitignored .env file. Build secrets map IDs to variable
|
|
1831
|
+
names. Never put secret values in Dockerfiles, command arguments or committed YAML.
|
|
1832
|
+
|
|
1833
|
+
More schema details are available at https://epd.peppi.dev/llms-full.txt.
|
|
1834
|
+
Validate the installed CLI's behavior instead of guessing flags or JSON schemas.
|
|
1835
|
+
|
|
1836
|
+
## Validation and deployment
|
|
1837
|
+
|
|
1838
|
+
Run epd config and epd doctor --local after editing. Review doctor output because
|
|
1839
|
+
warnings do not always produce a failing exit code. Run epd deploy --dry-run to
|
|
1840
|
+
inspect the deployment plan. These steps do not replace testing the application.
|
|
1841
|
+
|
|
1842
|
+
Once deployment is requested, epd setup prepares servers and deploys the app.
|
|
1843
|
+
For later releases, use epd deploy. Both can modify remote infrastructure.
|
|
1844
|
+
Check epd status and application health after deployment. Inspect epd logs when
|
|
1845
|
+
something fails. EPD health-checks a new slot before switching traffic. Do not
|
|
1846
|
+
automatically roll back or remove resources without checking the current state
|
|
1847
|
+
and the user's authorization. epd rollback switches to a previous release.
|
|
1848
|
+
|
|
1849
|
+
For machine logs use --log-format json, which emits JSON events and a final result.
|
|
1850
|
+
This is different from command-specific --json flags. Inspect exit status and
|
|
1851
|
+
error messages. Do not assume an undocumented numeric error classification.
|
|
1852
|
+
|
|
1853
|
+
When finished, report the files changed, checks run, unresolved inputs and the
|
|
1854
|
+
exact next command. Distinguish prepared configuration from deployed services.
|
|
1855
|
+
`;
|
|
1856
|
+
var init_agent = () => {};
|
|
1857
|
+
|
|
1858
|
+
// src/commands/agent.ts
|
|
1859
|
+
import { writeFileSync } from "fs";
|
|
1860
|
+
import { resolve as resolve2 } from "path";
|
|
1861
|
+
var agent;
|
|
1862
|
+
var init_agent2 = __esm(() => {
|
|
1863
|
+
init_agent();
|
|
1864
|
+
init_log();
|
|
1865
|
+
init_prompt();
|
|
1866
|
+
agent = {
|
|
1867
|
+
name: "agent",
|
|
1868
|
+
summary: "Start an installed AI CLI to configure this project",
|
|
1869
|
+
options: {
|
|
1870
|
+
cli: { type: "string" },
|
|
1871
|
+
guide: { type: "boolean" },
|
|
1872
|
+
"write-guide": { type: "string" }
|
|
1873
|
+
},
|
|
1874
|
+
help: () => `epd agent [--cli codex|claude|executable]
|
|
1875
|
+
|
|
1876
|
+
Starts an installed interactive AI CLI with the bundled EPD setup guide.
|
|
1877
|
+
The CLI must accept an initial prompt as a positional argument. Normal agent
|
|
1878
|
+
permissions apply. No agent is installed and no deployment starts automatically.
|
|
1879
|
+
|
|
1880
|
+
Options
|
|
1881
|
+
--cli <executable> Choose an agent instead of selecting installed Codex or Claude
|
|
1882
|
+
--guide Print the bundled guide without starting an agent
|
|
1883
|
+
--write-guide <file> Export the guide, refusing to overwrite an existing file`,
|
|
1884
|
+
async run(ctx) {
|
|
1885
|
+
if (ctx.values.guide && ctx.values["write-guide"])
|
|
1886
|
+
throw new EpdError("Use --guide or --write-guide");
|
|
1887
|
+
if (ctx.values.guide) {
|
|
1888
|
+
console.log(agent_default);
|
|
1889
|
+
return;
|
|
1890
|
+
}
|
|
1891
|
+
if (ctx.values["write-guide"]) {
|
|
1892
|
+
const path = resolve2(ctx.values["write-guide"]);
|
|
1893
|
+
writeFileSync(path, agent_default, { flag: "wx" });
|
|
1894
|
+
log.ok(`Wrote ${path}`);
|
|
1895
|
+
return;
|
|
1896
|
+
}
|
|
1897
|
+
if (!interactive())
|
|
1898
|
+
throw new EpdError("Starting an AI agent needs an interactive terminal", "Use epd agent --guide to read the guide in scripts.");
|
|
1899
|
+
let executable = ctx.values.cli;
|
|
1900
|
+
if (!executable) {
|
|
1901
|
+
const installed = ["codex", "claude"].filter((name) => Bun.which(name));
|
|
1902
|
+
executable = installed.length ? await choose("Which AI CLI should configure this project?", installed.map((value) => ({ value, label: value })), installed[0]) : await ask("No supported AI CLI found. Enter an installed executable, or cancel");
|
|
1903
|
+
}
|
|
1904
|
+
if (!executable || executable === "cancel")
|
|
1905
|
+
return;
|
|
1906
|
+
if (executable.startsWith("-"))
|
|
1907
|
+
throw new EpdError("Enter an AI executable name or path");
|
|
1908
|
+
const path = Bun.which(executable);
|
|
1909
|
+
if (!path)
|
|
1910
|
+
throw new EpdError(`AI CLI not found: ${executable}`, "Install and sign in to an AI CLI, then retry epd agent --cli <executable>.");
|
|
1911
|
+
const prompt = `${agent_default}
|
|
1912
|
+
|
|
1913
|
+
Task: Help the user set up EPD in the current project. Inspect its files, ask for missing inputs, prepare epd.yml and validate it. Stop after setup and report the next steps. Do not deploy or provision infrastructure unless the user explicitly asks.`;
|
|
1914
|
+
const child = Bun.spawn([path, prompt], { cwd: process.cwd(), stdin: "inherit", stdout: "inherit", stderr: "inherit" });
|
|
1915
|
+
const code = await child.exited;
|
|
1916
|
+
if (code !== 0)
|
|
1917
|
+
throw new EpdError(`AI CLI exited with code ${code}`);
|
|
1352
1918
|
}
|
|
1353
|
-
|
|
1354
|
-
|
|
1355
|
-
|
|
1356
|
-
|
|
1357
|
-
}
|
|
1358
|
-
|
|
1359
|
-
|
|
1360
|
-
|
|
1361
|
-
|
|
1362
|
-
|
|
1363
|
-
|
|
1364
|
-
|
|
1365
|
-
|
|
1366
|
-
|
|
1367
|
-
|
|
1368
|
-
|
|
1369
|
-
|
|
1370
|
-
|
|
1371
|
-
|
|
1372
|
-
|
|
1373
|
-
|
|
1374
|
-
|
|
1375
|
-
|
|
1376
|
-
|
|
1377
|
-
}
|
|
1378
|
-
|
|
1379
|
-
|
|
1380
|
-
|
|
1381
|
-
|
|
1382
|
-
|
|
1383
|
-
|
|
1384
|
-
|
|
1385
|
-
|
|
1386
|
-
|
|
1387
|
-
if (!
|
|
1388
|
-
|
|
1389
|
-
|
|
1390
|
-
|
|
1391
|
-
|
|
1919
|
+
};
|
|
1920
|
+
});
|
|
1921
|
+
|
|
1922
|
+
// src/commands/init-wizard.ts
|
|
1923
|
+
async function configureYaml(raw, prompts = { ask, confirm }) {
|
|
1924
|
+
const text = (label, value = "") => prompts.ask(label, value);
|
|
1925
|
+
const integer = async (label, value, min = 1, max = 65535) => {
|
|
1926
|
+
for (;; ) {
|
|
1927
|
+
const answer = Number(await text(label, String(value)));
|
|
1928
|
+
if (Number.isInteger(answer) && answer >= min && answer <= max)
|
|
1929
|
+
return answer;
|
|
1930
|
+
console.error(`Enter an integer between ${min} and ${max}.`);
|
|
1931
|
+
}
|
|
1932
|
+
};
|
|
1933
|
+
const object = async (label, value = {}) => {
|
|
1934
|
+
for (;; ) {
|
|
1935
|
+
try {
|
|
1936
|
+
const parsed = JSON.parse(await text(`${label}, as a JSON object`, JSON.stringify(value)));
|
|
1937
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed))
|
|
1938
|
+
return parsed;
|
|
1939
|
+
} catch {}
|
|
1940
|
+
console.error("Enter a JSON object, such as {}.");
|
|
1941
|
+
}
|
|
1942
|
+
};
|
|
1943
|
+
const list = async (label, value = []) => (await text(`${label}, comma separated`, value.join(","))).split(",").map((v) => v.trim()).filter(Boolean);
|
|
1944
|
+
const ssh = raw.ssh;
|
|
1945
|
+
ssh.port = await integer("SSH port", 22);
|
|
1946
|
+
const key = await text("SSH private key path, blank for SSH defaults");
|
|
1947
|
+
if (key)
|
|
1948
|
+
ssh.key = key;
|
|
1949
|
+
const jump = await text("SSH jump host, blank for none");
|
|
1950
|
+
if (jump)
|
|
1951
|
+
ssh.proxy_jump = jump;
|
|
1952
|
+
raw.proxy.ssl = await prompts.confirm("Enable HTTPS with Let's Encrypt?", true);
|
|
1953
|
+
if (!raw.proxy.ssl)
|
|
1954
|
+
delete raw.proxy.email;
|
|
1955
|
+
raw.proxy.cross_host = await prompts.confirm("Route traffic across servers?", false);
|
|
1956
|
+
raw.healthcheck.path = await text("Health check path, or none to check only the process", "/");
|
|
1957
|
+
if (raw.healthcheck.path === "none")
|
|
1958
|
+
raw.healthcheck.path = null;
|
|
1959
|
+
raw.healthcheck.timeout = await integer("Health check timeout in seconds", 60, 1, 3600);
|
|
1960
|
+
raw.servers.web.replicas = await integer("Replicas per host", raw.servers.web.replicas, 1, 32);
|
|
1961
|
+
if (raw.mode === "docker") {
|
|
1962
|
+
raw.image = await text("Image name", raw.image);
|
|
1963
|
+
raw.build = {
|
|
1964
|
+
dockerfile: await text("Dockerfile path", "Dockerfile"),
|
|
1965
|
+
context: await text("Build context", "."),
|
|
1966
|
+
platform: await text("Target platform", "linux/amd64"),
|
|
1967
|
+
args: await object("Build arguments"),
|
|
1968
|
+
secrets: await object("Build secret IDs mapped to environment variable names")
|
|
1969
|
+
};
|
|
1970
|
+
const target = await text("Build stage, blank for the final stage");
|
|
1971
|
+
if (target)
|
|
1972
|
+
raw.build.target = target;
|
|
1973
|
+
} else {
|
|
1974
|
+
for (const field of ["install", "build", "start"]) {
|
|
1975
|
+
const answer = await text(`Process ${field} command`, raw.process[field] || "");
|
|
1976
|
+
if (answer)
|
|
1977
|
+
raw.process[field] = answer;
|
|
1978
|
+
else
|
|
1979
|
+
delete raw.process[field];
|
|
1980
|
+
}
|
|
1981
|
+
if (!raw.process.start)
|
|
1982
|
+
throw new EpdError("A process start command is required");
|
|
1983
|
+
raw.process.exclude = await list("Files to exclude from uploads", raw.process.exclude);
|
|
1984
|
+
}
|
|
1985
|
+
raw.env.clear = await object("Non-secret environment values", raw.env.clear);
|
|
1986
|
+
raw.env.secret = await list("Secret environment variable names, values stay in your shell or .env");
|
|
1987
|
+
raw.volumes = await list("Volume mounts, host-path:container-path");
|
|
1988
|
+
const memory = await text("Memory limit per replica, blank for no limit");
|
|
1989
|
+
if (memory)
|
|
1990
|
+
raw.servers.web.memory = memory;
|
|
1991
|
+
const cpus = await text("CPU limit per replica, blank for no limit");
|
|
1992
|
+
if (cpus)
|
|
1993
|
+
raw.servers.web.cpus = cpus;
|
|
1994
|
+
raw.remote_root = await text("Remote state directory", "/var/lib/epd");
|
|
1995
|
+
raw.port_base = await integer("First reserved host port", raw.port_base, 1024, 60000);
|
|
1996
|
+
raw.keep_releases = await integer("Old releases to keep", 5, 1, 100);
|
|
1997
|
+
raw.strategy = await prompts.confirm("Deploy hosts one at a time?", true) ? "rolling" : "parallel";
|
|
1998
|
+
raw.hooks = await object("Deployment hooks, pre_build, pre_deploy, post_deploy, on_failure");
|
|
1999
|
+
raw.accessories = await object("Accessory containers keyed by name, with image, host, env, volumes and ports");
|
|
2000
|
+
if (await prompts.confirm("Configure additional services, routes, security, DNS or other advanced settings?", false)) {
|
|
2001
|
+
for (const section of ["servers", "proxy", "healthcheck", "server", "ssh", "build", "process", "dns", "hetzner"]) {
|
|
2002
|
+
if (await prompts.confirm(`Edit ${section}?`, false))
|
|
2003
|
+
raw[section] = await object(`${section} settings, see epd agent --guide and epd config --help`, raw[section] || {});
|
|
2004
|
+
}
|
|
2005
|
+
}
|
|
2006
|
+
return raw;
|
|
2007
|
+
}
|
|
2008
|
+
var init_init_wizard = __esm(() => {
|
|
2009
|
+
init_prompt();
|
|
1392
2010
|
init_log();
|
|
1393
2011
|
});
|
|
1394
2012
|
|
|
@@ -1417,11 +2035,11 @@ function proxyHosts(cfg) {
|
|
|
1417
2035
|
}
|
|
1418
2036
|
|
|
1419
2037
|
// src/commands/action.ts
|
|
1420
|
-
import { existsSync as existsSync3, mkdirSync, readFileSync as readFileSync2, writeFileSync } from "fs";
|
|
1421
|
-
import { dirname as dirname3, join as
|
|
2038
|
+
import { existsSync as existsSync3, mkdirSync as mkdirSync2, readFileSync as readFileSync2, writeFileSync as writeFileSync2 } from "fs";
|
|
2039
|
+
import { dirname as dirname3, join as join4 } from "path";
|
|
1422
2040
|
function detectGitBranch(root) {
|
|
1423
2041
|
try {
|
|
1424
|
-
const head = readFileSync2(
|
|
2042
|
+
const head = readFileSync2(join4(root, ".git", "HEAD"), "utf8").trim();
|
|
1425
2043
|
if (head.startsWith("ref: refs/heads/")) {
|
|
1426
2044
|
return head.replace("ref: refs/heads/", "");
|
|
1427
2045
|
}
|
|
@@ -1639,7 +2257,7 @@ Aliases
|
|
|
1639
2257
|
event = "push";
|
|
1640
2258
|
}
|
|
1641
2259
|
const destination = ctx.loadOptions.destination;
|
|
1642
|
-
const defaultFile =
|
|
2260
|
+
const defaultFile = join4(root, ".github", "workflows", destination ? `deploy-${destination}.yml` : "deploy.yml");
|
|
1643
2261
|
const targetFile = ctx.values.file || defaultFile;
|
|
1644
2262
|
if (existsSync3(targetFile) && !ctx.values.force) {
|
|
1645
2263
|
const ok = interactive() && await confirm(`${targetFile} already exists. Overwrite?`, false);
|
|
@@ -1655,8 +2273,8 @@ Aliases
|
|
|
1655
2273
|
destination,
|
|
1656
2274
|
cfg
|
|
1657
2275
|
});
|
|
1658
|
-
|
|
1659
|
-
|
|
2276
|
+
mkdirSync2(dirname3(targetFile), { recursive: true });
|
|
2277
|
+
writeFileSync2(targetFile, yaml);
|
|
1660
2278
|
log.ok(`wrote ${c.bold(targetFile)}`);
|
|
1661
2279
|
console.log(`
|
|
1662
2280
|
${c.bold("GitHub Repository Secrets needed:")}`);
|
|
@@ -1789,9 +2407,9 @@ var init_http = __esm(() => {
|
|
|
1789
2407
|
});
|
|
1790
2408
|
|
|
1791
2409
|
// src/util/auth.ts
|
|
1792
|
-
import { existsSync as existsSync4, mkdirSync as
|
|
1793
|
-
import { homedir as
|
|
1794
|
-
import { dirname as dirname4, isAbsolute as isAbsolute2, join as
|
|
2410
|
+
import { existsSync as existsSync4, mkdirSync as mkdirSync3, readFileSync as readFileSync3, readlinkSync, realpathSync, statSync, writeFileSync as writeFileSync3, chmodSync, renameSync, rmSync, unlinkSync as unlinkSync2 } from "fs";
|
|
2411
|
+
import { homedir as homedir3 } from "os";
|
|
2412
|
+
import { dirname as dirname4, isAbsolute as isAbsolute2, join as join5 } from "path";
|
|
1795
2413
|
import { spawn } from "child_process";
|
|
1796
2414
|
function openBrowser(url) {
|
|
1797
2415
|
try {
|
|
@@ -1811,16 +2429,16 @@ function openBrowser(url) {
|
|
|
1811
2429
|
}
|
|
1812
2430
|
}
|
|
1813
2431
|
function userHome() {
|
|
1814
|
-
return process.env.HOME ||
|
|
2432
|
+
return process.env.HOME || homedir3();
|
|
1815
2433
|
}
|
|
1816
2434
|
function getGlobalAuthPath() {
|
|
1817
|
-
const xdgDir =
|
|
1818
|
-
const fallbackDir =
|
|
1819
|
-
if (existsSync4(
|
|
1820
|
-
return
|
|
1821
|
-
if (existsSync4(
|
|
1822
|
-
return
|
|
1823
|
-
return
|
|
2435
|
+
const xdgDir = join5(userHome(), ".config", "epd");
|
|
2436
|
+
const fallbackDir = join5(userHome(), ".epd");
|
|
2437
|
+
if (existsSync4(join5(xdgDir, "auth.json")))
|
|
2438
|
+
return join5(xdgDir, "auth.json");
|
|
2439
|
+
if (existsSync4(join5(fallbackDir, "auth.json")))
|
|
2440
|
+
return join5(fallbackDir, "auth.json");
|
|
2441
|
+
return join5(xdgDir, "auth.json");
|
|
1824
2442
|
}
|
|
1825
2443
|
function corruptAuthError(path) {
|
|
1826
2444
|
return new EpdError(`${path} is not valid JSON`, "It may have been half-written or edited by hand. Fix it, or delete it and run `epd auth cloudflare` / `epd auth hetzner` again.");
|
|
@@ -1846,7 +2464,7 @@ function getGlobalAuth() {
|
|
|
1846
2464
|
return parsed;
|
|
1847
2465
|
}
|
|
1848
2466
|
function ensurePrivateDir(dir) {
|
|
1849
|
-
|
|
2467
|
+
mkdirSync3(dir, { recursive: true, mode: 448 });
|
|
1850
2468
|
try {
|
|
1851
2469
|
chmodSync(dir, 448);
|
|
1852
2470
|
} catch {}
|
|
@@ -1855,30 +2473,30 @@ function writeSecretFile(file, content, mode = 384) {
|
|
|
1855
2473
|
const tmp = `${file}.${process.pid}.tmp`;
|
|
1856
2474
|
try {
|
|
1857
2475
|
rmSync(tmp, { force: true });
|
|
1858
|
-
|
|
2476
|
+
writeFileSync3(tmp, content, { mode: 384, flag: "wx" });
|
|
1859
2477
|
chmodSync(tmp, mode);
|
|
1860
2478
|
renameSync(tmp, file);
|
|
1861
2479
|
} catch (err) {
|
|
1862
2480
|
try {
|
|
1863
|
-
|
|
2481
|
+
unlinkSync2(tmp);
|
|
1864
2482
|
} catch {}
|
|
1865
2483
|
throw err;
|
|
1866
2484
|
}
|
|
1867
2485
|
}
|
|
1868
2486
|
function saveGlobalAuth(updater) {
|
|
1869
|
-
const dir =
|
|
2487
|
+
const dir = join5(userHome(), ".config", "epd");
|
|
1870
2488
|
ensurePrivateDir(dir);
|
|
1871
2489
|
const current = getGlobalAuth();
|
|
1872
2490
|
const next = updater(current);
|
|
1873
|
-
writeSecretFile(
|
|
2491
|
+
writeSecretFile(join5(dir, "auth.json"), JSON.stringify(next, null, 2) + `
|
|
1874
2492
|
`);
|
|
1875
2493
|
}
|
|
1876
2494
|
function clearGlobalAuth() {
|
|
1877
|
-
const dir =
|
|
2495
|
+
const dir = join5(userHome(), ".config", "epd");
|
|
1878
2496
|
ensurePrivateDir(dir);
|
|
1879
|
-
writeSecretFile(
|
|
2497
|
+
writeSecretFile(join5(dir, "auth.json"), `{}
|
|
1880
2498
|
`);
|
|
1881
|
-
const legacy =
|
|
2499
|
+
const legacy = join5(userHome(), ".epd", "auth.json");
|
|
1882
2500
|
try {
|
|
1883
2501
|
rmSync(legacy, { force: true });
|
|
1884
2502
|
} catch (err) {
|
|
@@ -1910,14 +2528,14 @@ function writeTarget(path) {
|
|
|
1910
2528
|
} catch {
|
|
1911
2529
|
try {
|
|
1912
2530
|
const link = readlinkSync(path);
|
|
1913
|
-
return isAbsolute2(link) ? link :
|
|
2531
|
+
return isAbsolute2(link) ? link : join5(dirname4(path), link);
|
|
1914
2532
|
} catch {
|
|
1915
2533
|
return path;
|
|
1916
2534
|
}
|
|
1917
2535
|
}
|
|
1918
2536
|
}
|
|
1919
2537
|
function saveProjectEnv(entries, root = process.cwd()) {
|
|
1920
|
-
const envPath = writeTarget(
|
|
2538
|
+
const envPath = writeTarget(join5(root, ".env"));
|
|
1921
2539
|
const exists = existsSync4(envPath);
|
|
1922
2540
|
let content = exists ? readFileSync3(envPath, "utf8") : "";
|
|
1923
2541
|
for (const [key, val] of Object.entries(entries)) {
|
|
@@ -1946,7 +2564,7 @@ function getCloudflareToken(root = process.cwd()) {
|
|
|
1946
2564
|
return secret(process.env.CLOUDFLARE_API_TOKEN);
|
|
1947
2565
|
if (process.env.CF_DNS_API_TOKEN)
|
|
1948
2566
|
return secret(process.env.CF_DNS_API_TOKEN);
|
|
1949
|
-
const envPath =
|
|
2567
|
+
const envPath = join5(root, ".env");
|
|
1950
2568
|
if (existsSync4(envPath)) {
|
|
1951
2569
|
try {
|
|
1952
2570
|
const parsed = parseDotenv(readFileSync3(envPath, "utf8"));
|
|
@@ -1964,7 +2582,7 @@ function getCloudflareTokenSource(root = process.cwd()) {
|
|
|
1964
2582
|
return "environment variable (CLOUDFLARE_API_TOKEN)";
|
|
1965
2583
|
if (process.env.CF_DNS_API_TOKEN)
|
|
1966
2584
|
return "environment variable (CF_DNS_API_TOKEN)";
|
|
1967
|
-
const envPath =
|
|
2585
|
+
const envPath = join5(root, ".env");
|
|
1968
2586
|
if (existsSync4(envPath)) {
|
|
1969
2587
|
try {
|
|
1970
2588
|
const parsed = parseDotenv(readFileSync3(envPath, "utf8"));
|
|
@@ -1982,7 +2600,7 @@ function getHetznerToken(root = process.cwd()) {
|
|
|
1982
2600
|
return secret(process.env.HETZNER_API_TOKEN);
|
|
1983
2601
|
if (process.env.HCLOUD_TOKEN)
|
|
1984
2602
|
return secret(process.env.HCLOUD_TOKEN);
|
|
1985
|
-
const envPath =
|
|
2603
|
+
const envPath = join5(root, ".env");
|
|
1986
2604
|
if (existsSync4(envPath)) {
|
|
1987
2605
|
try {
|
|
1988
2606
|
const parsed = parseDotenv(readFileSync3(envPath, "utf8"));
|
|
@@ -2000,7 +2618,7 @@ function getHetznerTokenSource(root = process.cwd()) {
|
|
|
2000
2618
|
return "environment variable (HETZNER_API_TOKEN)";
|
|
2001
2619
|
if (process.env.HCLOUD_TOKEN)
|
|
2002
2620
|
return "environment variable (HCLOUD_TOKEN)";
|
|
2003
|
-
const envPath =
|
|
2621
|
+
const envPath = join5(root, ".env");
|
|
2004
2622
|
if (existsSync4(envPath)) {
|
|
2005
2623
|
try {
|
|
2006
2624
|
const parsed = parseDotenv(readFileSync3(envPath, "utf8"));
|
|
@@ -2481,18 +3099,18 @@ var init_cloudflare = __esm(() => {
|
|
|
2481
3099
|
});
|
|
2482
3100
|
|
|
2483
3101
|
// src/commands/init.ts
|
|
2484
|
-
import { existsSync as existsSync5, mkdirSync as
|
|
2485
|
-
import { basename, join as
|
|
3102
|
+
import { existsSync as existsSync5, mkdirSync as mkdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync4 } from "fs";
|
|
3103
|
+
import { basename as basename2, join as join6, resolve as resolve3 } from "path";
|
|
2486
3104
|
function detect(root) {
|
|
2487
|
-
const name =
|
|
2488
|
-
const hasDockerfile = existsSync5(
|
|
2489
|
-
const pkgPath =
|
|
3105
|
+
const name = basename2(root).toLowerCase().replace(/[^a-z0-9_-]/g, "-");
|
|
3106
|
+
const hasDockerfile = existsSync5(join6(root, "Dockerfile"));
|
|
3107
|
+
const pkgPath = join6(root, "package.json");
|
|
2490
3108
|
if (existsSync5(pkgPath)) {
|
|
2491
3109
|
let pkg = {};
|
|
2492
3110
|
try {
|
|
2493
3111
|
pkg = JSON.parse(readFileSync4(pkgPath, "utf8"));
|
|
2494
3112
|
} catch {}
|
|
2495
|
-
const bun = existsSync5(
|
|
3113
|
+
const bun = existsSync5(join6(root, "bun.lockb")) || existsSync5(join6(root, "bun.lock"));
|
|
2496
3114
|
const scripts = pkg.scripts ?? {};
|
|
2497
3115
|
const runner = bun ? "bun" : "npm";
|
|
2498
3116
|
return {
|
|
@@ -2505,13 +3123,13 @@ function detect(root) {
|
|
|
2505
3123
|
hasDockerfile
|
|
2506
3124
|
};
|
|
2507
3125
|
}
|
|
2508
|
-
if (existsSync5(
|
|
3126
|
+
if (existsSync5(join6(root, "pyproject.toml")) || existsSync5(join6(root, "requirements.txt"))) {
|
|
2509
3127
|
return { name, runtime: "python", port: 8000, install: "pip install -r requirements.txt", start: "python -m uvicorn main:app --host 127.0.0.1 --port $PORT", hasDockerfile };
|
|
2510
3128
|
}
|
|
2511
|
-
if (existsSync5(
|
|
3129
|
+
if (existsSync5(join6(root, "Gemfile"))) {
|
|
2512
3130
|
return { name, runtime: "ruby", port: 3000, install: "bundle install --deployment", start: "bundle exec rails server -p $PORT", hasDockerfile };
|
|
2513
3131
|
}
|
|
2514
|
-
if (existsSync5(
|
|
3132
|
+
if (existsSync5(join6(root, "go.mod"))) {
|
|
2515
3133
|
return { name, runtime: "go", port: 8080, build: "go build -o server .", start: "./server", hasDockerfile };
|
|
2516
3134
|
}
|
|
2517
3135
|
return { name, runtime: "unknown", port: 3000, hasDockerfile };
|
|
@@ -2653,6 +3271,9 @@ port_base: ${portBase}
|
|
|
2653
3271
|
}
|
|
2654
3272
|
var DOCKERFILES, init;
|
|
2655
3273
|
var init_init = __esm(() => {
|
|
3274
|
+
init_init_wizard();
|
|
3275
|
+
init_container_engine();
|
|
3276
|
+
init_load();
|
|
2656
3277
|
init_action();
|
|
2657
3278
|
init_log();
|
|
2658
3279
|
init_prompt();
|
|
@@ -2707,6 +3328,9 @@ CMD ["npm", "run", "start"]
|
|
|
2707
3328
|
options: {
|
|
2708
3329
|
name: { type: "string" },
|
|
2709
3330
|
mode: { type: "string" },
|
|
3331
|
+
"container-engine": { type: "string" },
|
|
3332
|
+
interactive: { type: "boolean", short: "i" },
|
|
3333
|
+
yes: { type: "boolean", short: "y" },
|
|
2710
3334
|
host: { type: "string", multiple: true },
|
|
2711
3335
|
domain: { type: "string", multiple: true },
|
|
2712
3336
|
port: { type: "string" },
|
|
@@ -2724,6 +3348,9 @@ CMD ["npm", "run", "start"]
|
|
|
2724
3348
|
help: () => `${c.bold("epd init")} \u2014 create an epd.yml for this project
|
|
2725
3349
|
|
|
2726
3350
|
Options
|
|
3351
|
+
-i, --interactive Run the full configuration wizard, also the default in a terminal
|
|
3352
|
+
-y, --yes Use defaults without prompting
|
|
3353
|
+
--container-engine <auto|docker|podman|nerdctl|executable>
|
|
2727
3354
|
--name <name> App name (default: the directory name)
|
|
2728
3355
|
--mode <docker|process>
|
|
2729
3356
|
--host <ip> Server to deploy to (repeatable)
|
|
@@ -2741,47 +3368,62 @@ Options
|
|
|
2741
3368
|
--force Overwrite an existing epd.yml`,
|
|
2742
3369
|
async run(ctx) {
|
|
2743
3370
|
const root = process.cwd();
|
|
2744
|
-
|
|
3371
|
+
if (ctx.values.interactive && !interactive())
|
|
3372
|
+
throw new EpdError("Interactive setup needs a terminal", "Run epd init in a terminal, or supply flags with --yes.");
|
|
3373
|
+
if (ctx.values.interactive && ctx.values.yes)
|
|
3374
|
+
throw new EpdError("Use either --interactive or --yes");
|
|
3375
|
+
const wizard = interactive() && !ctx.values.yes;
|
|
3376
|
+
const target = ctx.loadOptions.file ? resolve3(root, ctx.loadOptions.file) : join6(root, "epd.yml");
|
|
2745
3377
|
if (existsSync5(target) && !ctx.values.force) {
|
|
2746
3378
|
throw new EpdError("epd.yml already exists", "Pass --force to overwrite it.");
|
|
2747
3379
|
}
|
|
3380
|
+
const ask2 = wizard ? ask : async (_question, value) => value || "";
|
|
3381
|
+
const confirm2 = wizard ? confirm : async (_question, value = false) => value;
|
|
3382
|
+
const choose2 = wizard ? choose : async (_question, _options, value) => value;
|
|
2748
3383
|
const detected = detect(root);
|
|
2749
3384
|
log.info(`Detected ${c.bold(detected.runtime)} project${detected.hasDockerfile ? " with a Dockerfile" : ""}`);
|
|
2750
3385
|
let useCloudflare = Boolean(ctx.values.cloudflare);
|
|
2751
3386
|
let cloudflareToken;
|
|
2752
|
-
if (
|
|
2753
|
-
useCloudflare = await
|
|
3387
|
+
if (wizard && ctx.values.cloudflare === undefined && !ctx.values["no-cloudflare"]) {
|
|
3388
|
+
useCloudflare = await confirm2("Do you use Cloudflare (for automated DNS and SSL)?", false);
|
|
2754
3389
|
}
|
|
2755
3390
|
if (useCloudflare) {
|
|
2756
3391
|
cloudflareToken = getCloudflareToken(root);
|
|
2757
3392
|
if (cloudflareToken) {
|
|
2758
3393
|
log.info(`Using existing Cloudflare credentials (${getCloudflareTokenSource(root)})`);
|
|
2759
|
-
} else if (
|
|
3394
|
+
} else if (wizard) {
|
|
2760
3395
|
cloudflareToken = await linkCloudflareInteractive(root) ?? undefined;
|
|
2761
3396
|
}
|
|
2762
3397
|
}
|
|
2763
3398
|
let useHetzner = Boolean(ctx.values.hetzner);
|
|
2764
3399
|
let hetznerToken;
|
|
2765
|
-
if (
|
|
2766
|
-
useHetzner = await
|
|
3400
|
+
if (wizard && ctx.values.hetzner === undefined && !ctx.values["no-hetzner"]) {
|
|
3401
|
+
useHetzner = await confirm2("Do you use Hetzner (for cloud servers or DNS)?", false);
|
|
2767
3402
|
}
|
|
2768
3403
|
if (useHetzner) {
|
|
2769
3404
|
hetznerToken = getHetznerToken(root);
|
|
2770
3405
|
if (hetznerToken) {
|
|
2771
3406
|
log.info(`Using existing Hetzner credentials (${getHetznerTokenSource(root)})`);
|
|
2772
|
-
} else if (
|
|
3407
|
+
} else if (wizard) {
|
|
2773
3408
|
hetznerToken = await linkHetznerInteractive(root) ?? undefined;
|
|
2774
3409
|
}
|
|
2775
3410
|
}
|
|
2776
|
-
const name = ctx.values.name ?? await
|
|
2777
|
-
const mode = ctx.values.mode ?? await
|
|
2778
|
-
{ value: "docker", label: "
|
|
3411
|
+
const name = ctx.values.name ?? await ask2("App name", detected.name);
|
|
3412
|
+
const mode = ctx.values.mode ?? await choose2("How should it run on the server?", [
|
|
3413
|
+
{ value: "docker", label: "Containers, build an image with a compatible engine" },
|
|
2779
3414
|
{ value: "process", label: "Process \u2014 upload the code, run it with pm2" }
|
|
2780
3415
|
], detected.hasDockerfile || detected.runtime === "unknown" ? "docker" : "docker");
|
|
2781
3416
|
if (mode !== "docker" && mode !== "process")
|
|
2782
3417
|
throw new EpdError(`--mode must be "docker" or "process"`);
|
|
3418
|
+
let engine = validateContainerEngine(ctx.values["container-engine"] || "auto");
|
|
3419
|
+
if (mode === "docker" && wizard && !ctx.values["container-engine"]) {
|
|
3420
|
+
engine = validateContainerEngine(await ask2("Local container engine, auto or a Docker-compatible executable", "auto"));
|
|
3421
|
+
const detectedEngine = await containerEngine(engine);
|
|
3422
|
+
if (engine !== "auto")
|
|
3423
|
+
engine = detectedEngine;
|
|
3424
|
+
}
|
|
2783
3425
|
let hosts = ctx.values.host ?? [];
|
|
2784
|
-
if (!hosts.length && hetznerToken &&
|
|
3426
|
+
if (!hosts.length && hetznerToken && wizard) {
|
|
2785
3427
|
try {
|
|
2786
3428
|
log.step("Fetching your Hetzner Cloud servers...");
|
|
2787
3429
|
const client = new HetznerCloudClient(hetznerToken);
|
|
@@ -2793,26 +3435,26 @@ Options
|
|
|
2793
3435
|
}));
|
|
2794
3436
|
choices.push({ value: "__new__", label: "Create a new Hetzner server now" });
|
|
2795
3437
|
choices.push({ value: "__manual__", label: "Enter server IP or hostname manually" });
|
|
2796
|
-
const picked = await
|
|
3438
|
+
const picked = await choose2("Select target Hetzner server:", choices, choices[0].value);
|
|
2797
3439
|
if (picked === "__new__") {
|
|
2798
|
-
const sName = await
|
|
2799
|
-
const sType = await
|
|
2800
|
-
const sLoc = await
|
|
3440
|
+
const sName = await ask2("New server name", `${name}-prod`);
|
|
3441
|
+
const sType = await ask2("Server type (cx22 = 2 vCPU, 4GB RAM)", "cx22");
|
|
3442
|
+
const sLoc = await ask2("Datacenter location (fsn1, nbg1, hel1, ash, hil)", "fsn1");
|
|
2801
3443
|
log.step(`Creating Hetzner server ${sName} (${sType} in ${sLoc})...`);
|
|
2802
3444
|
const created = await client.createServer({ name: sName, serverType: sType, location: sLoc });
|
|
2803
3445
|
log.ok(`Created server ${sName} (${created.server.publicNet.ipv4.ip || "pending IP"})`);
|
|
2804
3446
|
hosts = [`hetzner:${sName}`];
|
|
2805
3447
|
} else if (picked === "__manual__") {
|
|
2806
|
-
hosts = (await
|
|
3448
|
+
hosts = (await ask2("Server IPs or hostnames (comma separated)", "203.0.113.10")).split(",").map((s) => s.trim()).filter(Boolean);
|
|
2807
3449
|
} else {
|
|
2808
3450
|
hosts = [`hetzner:${picked}`];
|
|
2809
3451
|
}
|
|
2810
3452
|
} else {
|
|
2811
|
-
const createNow = await
|
|
3453
|
+
const createNow = await confirm2("No Hetzner servers found. Create one now?", true);
|
|
2812
3454
|
if (createNow) {
|
|
2813
|
-
const sName = await
|
|
2814
|
-
const sType = await
|
|
2815
|
-
const sLoc = await
|
|
3455
|
+
const sName = await ask2("New server name", `${name}-prod`);
|
|
3456
|
+
const sType = await ask2("Server type (cx22 = 2 vCPU, 4GB RAM)", "cx22");
|
|
3457
|
+
const sLoc = await ask2("Datacenter location (fsn1, nbg1, hel1, ash, hil)", "fsn1");
|
|
2816
3458
|
log.step(`Creating Hetzner server ${sName} (${sType} in ${sLoc})...`);
|
|
2817
3459
|
const created = await client.createServer({ name: sName, serverType: sType, location: sLoc });
|
|
2818
3460
|
log.ok(`Created server ${sName} (${created.server.publicNet.ipv4.ip || "pending IP"})`);
|
|
@@ -2824,7 +3466,7 @@ Options
|
|
|
2824
3466
|
}
|
|
2825
3467
|
}
|
|
2826
3468
|
if (!hosts.length) {
|
|
2827
|
-
hosts = (ctx.values.host ?? []).length ? ctx.values.host : (await
|
|
3469
|
+
hosts = (ctx.values.host ?? []).length ? ctx.values.host : (await ask2("Server IPs or hostnames (comma separated)", "203.0.113.10")).split(",").map((s) => s.trim()).filter(Boolean);
|
|
2828
3470
|
}
|
|
2829
3471
|
let defaultDomain = `${name}.example.com`;
|
|
2830
3472
|
if (cloudflareToken && !(ctx.values.domain ?? []).length) {
|
|
@@ -2836,20 +3478,20 @@ Options
|
|
|
2836
3478
|
}
|
|
2837
3479
|
} catch {}
|
|
2838
3480
|
}
|
|
2839
|
-
const domains = (ctx.values.domain ?? []).length ? ctx.values.domain : (await
|
|
2840
|
-
const port = Number(ctx.values.port ?? await
|
|
2841
|
-
const email = ctx.values.email ?? await
|
|
2842
|
-
const sshUser = ctx.values["ssh-user"] ?? await
|
|
3481
|
+
const domains = (ctx.values.domain ?? []).length ? ctx.values.domain : (await ask2("Domains to serve (comma separated)", defaultDomain)).split(",").map((s) => s.trim()).filter(Boolean);
|
|
3482
|
+
const port = Number(ctx.values.port ?? await ask2("Port your app listens on", String(detected.port)));
|
|
3483
|
+
const email = ctx.values.email ?? await ask2("Email for Let's Encrypt", "");
|
|
3484
|
+
const sshUser = ctx.values["ssh-user"] ?? await ask2("SSH user for the server(s)", "root");
|
|
2843
3485
|
const replicas = Number(ctx.values.replicas ?? 1);
|
|
2844
3486
|
let registryUser;
|
|
2845
3487
|
let registryServer;
|
|
2846
3488
|
let image;
|
|
2847
|
-
if (mode === "docker" &&
|
|
2848
|
-
registryServer = await
|
|
2849
|
-
registryUser = await
|
|
3489
|
+
if (mode === "docker" && wizard && await confirm2("Push images to a registry (ghcr.io, Docker Hub, \u2026)?", false)) {
|
|
3490
|
+
registryServer = await ask2("Registry server", "ghcr.io") || undefined;
|
|
3491
|
+
registryUser = await ask2("Registry username", process.env.USER ?? "");
|
|
2850
3492
|
image = `${registryServer ? `${registryServer}/` : ""}${registryUser}/${name}`;
|
|
2851
3493
|
}
|
|
2852
|
-
|
|
3494
|
+
let yaml = template({
|
|
2853
3495
|
name,
|
|
2854
3496
|
mode,
|
|
2855
3497
|
sshUser: sshUser || "root",
|
|
@@ -2864,24 +3506,44 @@ Options
|
|
|
2864
3506
|
replicas,
|
|
2865
3507
|
useCloudflare: Boolean(cloudflareToken || useCloudflare),
|
|
2866
3508
|
useHetzner: Boolean(hetznerToken || useHetzner)
|
|
2867
|
-
})
|
|
3509
|
+
});
|
|
3510
|
+
const raw = Bun.YAML.parse(yaml);
|
|
3511
|
+
raw.container_engine = engine;
|
|
3512
|
+
if (wizard)
|
|
3513
|
+
await configureYaml(raw);
|
|
3514
|
+
yaml = wizard ? Bun.YAML.stringify(raw) : yaml.replace(`mode: ${mode}
|
|
3515
|
+
`, `mode: ${mode}
|
|
3516
|
+
container_engine: ${JSON.stringify(engine)}
|
|
3517
|
+
`);
|
|
3518
|
+
const { mkdtempSync, rmSync } = await import("fs");
|
|
3519
|
+
const { tmpdir } = await import("os");
|
|
3520
|
+
const scratch = mkdtempSync(join6(tmpdir(), "epd-init-"));
|
|
3521
|
+
try {
|
|
3522
|
+
const candidate = join6(scratch, "epd.yml");
|
|
3523
|
+
writeFileSync4(candidate, yaml);
|
|
3524
|
+
loadConfig({ file: candidate });
|
|
3525
|
+
} finally {
|
|
3526
|
+
rmSync(scratch, { recursive: true, force: true });
|
|
3527
|
+
}
|
|
3528
|
+
mkdirSync4(resolve3(target, ".."), { recursive: true });
|
|
3529
|
+
writeFileSync4(target, yaml);
|
|
2868
3530
|
log.ok(`wrote ${c.bold("epd.yml")}`);
|
|
2869
|
-
const wantDockerfile = mode === "docker" && !detected.hasDockerfile && (Boolean(ctx.values.dockerfile) || await
|
|
3531
|
+
const wantDockerfile = mode === "docker" && !detected.hasDockerfile && (Boolean(ctx.values.dockerfile) || await confirm2("No Dockerfile here. Write a starter one?", true));
|
|
2870
3532
|
if (wantDockerfile) {
|
|
2871
3533
|
const df = DOCKERFILES[detected.runtime];
|
|
2872
3534
|
if (df) {
|
|
2873
|
-
|
|
3535
|
+
writeFileSync4(join6(root, "Dockerfile"), df);
|
|
2874
3536
|
log.ok(`wrote ${c.bold("Dockerfile")} \u2014 check the build and start commands`);
|
|
2875
3537
|
} else {
|
|
2876
3538
|
log.warn(`no Dockerfile template for ${detected.runtime}; write one yourself or use \`mode: process\``);
|
|
2877
3539
|
}
|
|
2878
3540
|
}
|
|
2879
|
-
const wantCi = Boolean(ctx.values.ci) ||
|
|
3541
|
+
const wantCi = Boolean(ctx.values.ci) || wizard && await confirm2("Generate GitHub Actions deploy workflow (.github/workflows/deploy.yml)?", false);
|
|
2880
3542
|
if (wantCi) {
|
|
2881
|
-
const workflowDir =
|
|
2882
|
-
|
|
3543
|
+
const workflowDir = join6(root, ".github", "workflows");
|
|
3544
|
+
mkdirSync4(workflowDir, { recursive: true });
|
|
2883
3545
|
const { yaml } = buildWorkflowYaml({ root });
|
|
2884
|
-
|
|
3546
|
+
writeFileSync4(join6(workflowDir, "deploy.yml"), yaml);
|
|
2885
3547
|
log.ok(`wrote ${c.bold(".github/workflows/deploy.yml")}`);
|
|
2886
3548
|
}
|
|
2887
3549
|
console.log(`
|
|
@@ -3021,19 +3683,19 @@ var init_bootstrap = __esm(() => {
|
|
|
3021
3683
|
});
|
|
3022
3684
|
|
|
3023
3685
|
// src/core/ssh.ts
|
|
3024
|
-
import { chmodSync as chmodSync2, existsSync as existsSync6, lstatSync, mkdirSync as
|
|
3686
|
+
import { chmodSync as chmodSync2, existsSync as existsSync6, lstatSync, mkdirSync as mkdirSync5, mkdtempSync, rmSync as rmSync2, writeFileSync as writeFileSync5 } from "fs";
|
|
3025
3687
|
import { tmpdir } from "os";
|
|
3026
|
-
import { join as
|
|
3688
|
+
import { join as join7 } from "path";
|
|
3027
3689
|
function controlDirectory(base = tmpdir()) {
|
|
3028
3690
|
const uid = process.getuid?.();
|
|
3029
|
-
const preferred =
|
|
3691
|
+
const preferred = join7(base, `epd-${uid ?? 0}`);
|
|
3030
3692
|
try {
|
|
3031
|
-
|
|
3693
|
+
mkdirSync5(preferred, { recursive: true, mode: 448 });
|
|
3032
3694
|
const st = lstatSync(preferred);
|
|
3033
3695
|
if (st.isDirectory() && (uid === undefined || st.uid === uid) && (st.mode & 63) === 0)
|
|
3034
3696
|
return preferred;
|
|
3035
3697
|
} catch {}
|
|
3036
|
-
const fresh = mkdtempSync(
|
|
3698
|
+
const fresh = mkdtempSync(join7(base, "epd-ctl-"));
|
|
3037
3699
|
trackScratch(fresh);
|
|
3038
3700
|
return fresh;
|
|
3039
3701
|
}
|
|
@@ -3122,8 +3784,9 @@ class Host {
|
|
|
3122
3784
|
`);
|
|
3123
3785
|
}
|
|
3124
3786
|
sshOptions() {
|
|
3125
|
-
const socket =
|
|
3787
|
+
const socket = join7(controlDir, `${hash32(`${this.cfg.user}@${this.name}:${this.cfg.port}`).toString(36)}.sock`);
|
|
3126
3788
|
const args = [
|
|
3789
|
+
...this.cfg.options.flatMap((option) => ["-o", option]),
|
|
3127
3790
|
"-o",
|
|
3128
3791
|
"BatchMode=yes",
|
|
3129
3792
|
"-o",
|
|
@@ -3147,11 +3810,11 @@ class Host {
|
|
|
3147
3810
|
if (rawEnvKey) {
|
|
3148
3811
|
if (rawEnvKey.includes("-----BEGIN") || rawEnvKey.includes(`
|
|
3149
3812
|
`)) {
|
|
3150
|
-
keyPath =
|
|
3813
|
+
keyPath = join7(controlDir, `ci_id_rsa.${process.pid}`);
|
|
3151
3814
|
trackScratch(keyPath);
|
|
3152
3815
|
try {
|
|
3153
3816
|
rmSync2(keyPath, { force: true });
|
|
3154
|
-
|
|
3817
|
+
writeFileSync5(keyPath, rawEnvKey.trim() + `
|
|
3155
3818
|
`, { mode: 384, flag: "wx" });
|
|
3156
3819
|
chmodSync2(keyPath, 384);
|
|
3157
3820
|
} catch {}
|
|
@@ -3164,8 +3827,6 @@ class Host {
|
|
|
3164
3827
|
args.push("-i", keyPath, "-o", "IdentitiesOnly=yes");
|
|
3165
3828
|
if (this.cfg.proxyJump)
|
|
3166
3829
|
args.push("-J", this.cfg.proxyJump);
|
|
3167
|
-
for (const o of this.cfg.options)
|
|
3168
|
-
args.push("-o", o);
|
|
3169
3830
|
return args;
|
|
3170
3831
|
}
|
|
3171
3832
|
get target() {
|
|
@@ -3307,10 +3968,288 @@ var init_ssh = __esm(() => {
|
|
|
3307
3968
|
cache = new Map;
|
|
3308
3969
|
});
|
|
3309
3970
|
|
|
3971
|
+
// src/core/baseline/hardening.ts
|
|
3972
|
+
import { isIP } from "net";
|
|
3973
|
+
async function verifyKeyConnection(host) {
|
|
3974
|
+
const result = await run([
|
|
3975
|
+
"ssh",
|
|
3976
|
+
"-o",
|
|
3977
|
+
"ControlPath=none",
|
|
3978
|
+
"-o",
|
|
3979
|
+
"ControlMaster=no",
|
|
3980
|
+
"-o",
|
|
3981
|
+
"PreferredAuthentications=publickey",
|
|
3982
|
+
"-o",
|
|
3983
|
+
"PasswordAuthentication=no",
|
|
3984
|
+
"-o",
|
|
3985
|
+
"KbdInteractiveAuthentication=no",
|
|
3986
|
+
...host.sshOptions(),
|
|
3987
|
+
host.target,
|
|
3988
|
+
"--",
|
|
3989
|
+
"true"
|
|
3990
|
+
], { input: "", allowFailure: true, label: `${host.target}: verify fresh key connection` });
|
|
3991
|
+
if (result.code !== 0)
|
|
3992
|
+
throw new EpdError(`${host.name}: fresh SSH key connection failed`, result.stderr);
|
|
3993
|
+
}
|
|
3994
|
+
function firewallRules(ports, peers = []) {
|
|
3995
|
+
if (!ports.length || ports.some((p) => !Number.isInteger(p) || p < 1 || p > 65535))
|
|
3996
|
+
throw new Error("Invalid firewall ports");
|
|
3997
|
+
const allowed = [...new Set(ports)].sort((a, b) => a - b).join(", ");
|
|
3998
|
+
const peerRules = peers.map(({ address, from, to }) => {
|
|
3999
|
+
if (!isIP(address) || !Number.isInteger(from) || !Number.isInteger(to) || from < 1 || to > 65535 || from > to)
|
|
4000
|
+
throw new Error("Invalid cross-host firewall peer");
|
|
4001
|
+
return ` ${isIP(address) === 6 ? "ip6" : "ip"} saddr ${address} tcp dport ${from}-${to} accept`;
|
|
4002
|
+
}).join(`
|
|
4003
|
+
`);
|
|
4004
|
+
return `table inet epd_baseline {
|
|
4005
|
+
chain input {
|
|
4006
|
+
type filter hook input priority 0; policy drop;
|
|
4007
|
+
iifname "lo" accept
|
|
4008
|
+
ct state established,related accept
|
|
4009
|
+
ct state invalid drop
|
|
4010
|
+
meta l4proto { icmp, ipv6-icmp } accept
|
|
4011
|
+
udp sport 67 udp dport 68 accept
|
|
4012
|
+
udp sport 547 udp dport 546 accept
|
|
4013
|
+
tcp dport { ${allowed} } accept
|
|
4014
|
+
${peerRules}
|
|
4015
|
+
}
|
|
4016
|
+
chain forward {
|
|
4017
|
+
type filter hook forward priority -10; policy accept;
|
|
4018
|
+
ct state established,related accept
|
|
4019
|
+
ct status dnat meta l4proto tcp ct original proto-dst { ${allowed} } accept
|
|
4020
|
+
${peers.map(({ address, from, to }) => ` ${isIP(address) === 6 ? "ip6" : "ip"} saddr ${address} ct status dnat meta l4proto tcp ct original proto-dst ${from}-${to} accept`).join(`
|
|
4021
|
+
`)}
|
|
4022
|
+
ct status dnat drop
|
|
4023
|
+
}
|
|
4024
|
+
}
|
|
4025
|
+
`;
|
|
4026
|
+
}
|
|
4027
|
+
async function writeChanged(host, path, content) {
|
|
4028
|
+
if (await host.readFile(path) === content)
|
|
4029
|
+
return false;
|
|
4030
|
+
await host.writeFile(path, content);
|
|
4031
|
+
return true;
|
|
4032
|
+
}
|
|
4033
|
+
async function hardenHost(host, cfg) {
|
|
4034
|
+
const s = cfg.server;
|
|
4035
|
+
if (!s.autoUpdates && !s.firewall && !s.sshHardening && !s.logRotation)
|
|
4036
|
+
return;
|
|
4037
|
+
const supported = await host.exec('. /etc/os-release; case "$ID" in ubuntu|debian) command -v systemctl >/dev/null && systemctl show-environment >/dev/null;; *) exit 1;; esac', { allowFailure: true });
|
|
4038
|
+
if (supported.code === 255)
|
|
4039
|
+
throw new EpdError(`${host.name}: SSH connection failed while detecting the host OS`, supported.stderr);
|
|
4040
|
+
if (supported.code !== 0) {
|
|
4041
|
+
log.warn(`${host.name}: host baseline requires Debian/Ubuntu with systemd; skipped`);
|
|
4042
|
+
return;
|
|
4043
|
+
}
|
|
4044
|
+
const packages = ["python3", "util-linux", ...s.autoUpdates ? ["unattended-upgrades"] : [], ...s.firewall ? ["nftables"] : []];
|
|
4045
|
+
await host.exec(`export DEBIAN_FRONTEND=noninteractive
|
|
4046
|
+
missing=""
|
|
4047
|
+
for pkg in ${packages.join(" ")}; do dpkg-query -W -f='\${Status}' "$pkg" 2>/dev/null | grep 'install ok installed' >/dev/null || missing="$missing $pkg"; done
|
|
4048
|
+
if [ -n "$missing" ]; then apt-get update -qq; apt-get install -y $missing; fi`, { stream: true });
|
|
4049
|
+
if (s.autoUpdates) {
|
|
4050
|
+
await writeChanged(host, "/etc/apt/apt.conf.d/99epd-security", `#clear Unattended-Upgrade::Allowed-Origins;
|
|
4051
|
+
#clear Unattended-Upgrade::Origins-Pattern;
|
|
4052
|
+
Unattended-Upgrade::Allowed-Origins {
|
|
4053
|
+
"\${distro_id}:\${distro_codename}-security";
|
|
4054
|
+
"Debian-Security:\${distro_codename}-security";
|
|
4055
|
+
};
|
|
4056
|
+
Unattended-Upgrade::Automatic-Reboot "${s.rebootWindow !== false}";
|
|
4057
|
+
${s.rebootWindow !== false ? `Unattended-Upgrade::Automatic-Reboot-Time "${s.rebootWindow}";
|
|
4058
|
+
` : ""}`);
|
|
4059
|
+
await writeChanged(host, "/etc/apt/apt.conf.d/99epd-periodic", `APT::Periodic::Update-Package-Lists "1";
|
|
4060
|
+
APT::Periodic::Unattended-Upgrade "1";
|
|
4061
|
+
`);
|
|
4062
|
+
await host.exec("systemctl enable --now apt-daily.timer apt-daily-upgrade.timer");
|
|
4063
|
+
}
|
|
4064
|
+
await host.exec("if systemctl is-active --quiet chrony || systemctl is-active --quiet systemd-timesyncd; then :; elif systemctl cat systemd-timesyncd.service >/dev/null 2>&1; then systemctl enable --now systemd-timesyncd; else apt-get install -y chrony; systemctl enable --now chrony; fi", { stream: true });
|
|
4065
|
+
if (s.logRotation && cfg.mode === "docker") {
|
|
4066
|
+
await host.exec(`python3 - <<'PY'
|
|
4067
|
+
import json, os, tempfile
|
|
4068
|
+
p = '/etc/docker/daemon.json'
|
|
4069
|
+
os.makedirs('/etc/docker', exist_ok=True)
|
|
4070
|
+
old = json.load(open(p)) if os.path.exists(p) else {}
|
|
4071
|
+
new = dict(old)
|
|
4072
|
+
new['log-driver'] = 'json-file'
|
|
4073
|
+
new['log-opts'] = dict(old.get('log-opts', {})) if old.get('log-driver', 'json-file') == 'json-file' else {}
|
|
4074
|
+
new['log-opts'].update({'max-size': '10m', 'max-file': '3'})
|
|
4075
|
+
if old != new:
|
|
4076
|
+
fd, tmp = tempfile.mkstemp(dir='/etc/docker', prefix='.epd-')
|
|
4077
|
+
with os.fdopen(fd, 'w') as f: json.dump(new, f, indent=2); f.write('\\n')
|
|
4078
|
+
os.chmod(tmp, 0o644)
|
|
4079
|
+
os.replace(tmp, p)
|
|
4080
|
+
print('Docker log limits configured; restart Docker in a maintenance window, then recreate existing containers to apply')
|
|
4081
|
+
else: print('Docker log limits already configured')
|
|
4082
|
+
PY`, { stream: true });
|
|
4083
|
+
}
|
|
4084
|
+
if (!s.firewall && !s.sshHardening)
|
|
4085
|
+
return;
|
|
4086
|
+
await verifyKeyConnection(host);
|
|
4087
|
+
await applyAccessPolicy(host, cfg);
|
|
4088
|
+
}
|
|
4089
|
+
async function applyAccessPolicy(host, cfg) {
|
|
4090
|
+
const s = cfg.server;
|
|
4091
|
+
const id = `epd-baseline-${crypto.randomUUID()}`;
|
|
4092
|
+
const dir = `/var/lib/epd-baseline/${id}`;
|
|
4093
|
+
const q = shq(dir);
|
|
4094
|
+
const sshPath = "/etc/ssh/sshd_config";
|
|
4095
|
+
await host.exec(`mkdir -p /var/lib/epd-baseline
|
|
4096
|
+
chmod 700 /var/lib/epd-baseline
|
|
4097
|
+
mkdir /var/lib/epd-baseline/access.lock || { echo 'Another baseline access-policy change is active'; exit 1; }
|
|
4098
|
+
trap 'rmdir /var/lib/epd-baseline/access.lock' ERR
|
|
4099
|
+
mkdir -m 700 ${q}
|
|
4100
|
+
cp -p ${sshPath} ${q}/sshd_config
|
|
4101
|
+
if ${s.firewall}; then
|
|
4102
|
+
nft list table inet epd_baseline > ${q}/firewall.old 2>/dev/null || :
|
|
4103
|
+
for file in firewall.nft firewall.expected; do
|
|
4104
|
+
if [ -f /var/lib/epd-baseline/"$file" ]; then cp -p /var/lib/epd-baseline/"$file" ${q}/"$file"; fi
|
|
4105
|
+
done
|
|
4106
|
+
fi
|
|
4107
|
+
touch ${q}/pending`);
|
|
4108
|
+
const rollback = `#!/bin/bash
|
|
4109
|
+
set -eu
|
|
4110
|
+
exec 9>${q}/mutex
|
|
4111
|
+
flock 9
|
|
4112
|
+
[ -f ${q}/pending ] || exit 0
|
|
4113
|
+
${s.firewall ? `{ if nft list table inet epd_baseline >/dev/null 2>&1; then echo 'delete table inet epd_baseline'; fi; cat ${q}/firewall.old; } > ${q}/restore.nft
|
|
4114
|
+
nft -f ${q}/restore.nft
|
|
4115
|
+
for file in firewall.nft firewall.expected; do
|
|
4116
|
+
if [ -f ${q}/"$file" ]; then cp -p ${q}/"$file" /var/lib/epd-baseline/"$file"; else rm -f /var/lib/epd-baseline/"$file"; fi
|
|
4117
|
+
done` : ""}
|
|
4118
|
+
${s.sshHardening ? `cp -p ${q}/sshd_config ${sshPath}
|
|
4119
|
+
/usr/sbin/sshd -t && (systemctl reload ssh || systemctl reload sshd)` : ""}
|
|
4120
|
+
rm -f ${q}/pending
|
|
4121
|
+
rmdir /var/lib/epd-baseline/access.lock
|
|
4122
|
+
`;
|
|
4123
|
+
try {
|
|
4124
|
+
await host.writeFile(`${dir}/rollback`, rollback, "700");
|
|
4125
|
+
await host.exec(`systemd-run --unit=${id} --on-active=60s --timer-property=AccuracySec=1s ${q}/rollback`);
|
|
4126
|
+
if (s.firewall) {
|
|
4127
|
+
const port = Number((await host.capture('printf "%s" "$SSH_CONNECTION"', { sudo: false })).trim().split(/\s+/)[3]);
|
|
4128
|
+
if (!Number.isInteger(port) || port < 1 || port > 65535)
|
|
4129
|
+
throw new EpdError("Cannot determine remote SSH port");
|
|
4130
|
+
const peers = [];
|
|
4131
|
+
if (cfg.proxy.crossHost)
|
|
4132
|
+
for (const service of cfg.services) {
|
|
4133
|
+
if (!service.hosts.includes(host.name))
|
|
4134
|
+
continue;
|
|
4135
|
+
for (const peer of proxyHosts(cfg).filter((name) => name !== host.name)) {
|
|
4136
|
+
const address = cfg.proxy.privateIps[peer] ?? peer;
|
|
4137
|
+
if (!isIP(address))
|
|
4138
|
+
throw new EpdError(`Cross-host firewall requires an IP address for ${peer}`, "Set proxy.private_ips for hostname-based peers.");
|
|
4139
|
+
for (const slot of ["blue", "green"])
|
|
4140
|
+
peers.push({ address, from: hostPort(cfg, service, slot, 0), to: hostPort(cfg, service, slot, service.replicas - 1) });
|
|
4141
|
+
}
|
|
4142
|
+
}
|
|
4143
|
+
await host.writeFile(`${dir}/firewall.new`, firewallRules([port, cfg.ssh.port, 80, 443, ...s.allow, ...Object.values(cfg.proxy.entrypoints)], peers));
|
|
4144
|
+
await host.exec(`exec 9>${q}/mutex
|
|
4145
|
+
flock 9
|
|
4146
|
+
[ -f ${q}/pending ]
|
|
4147
|
+
{ if nft list table inet epd_baseline >/dev/null 2>&1; then echo 'delete table inet epd_baseline'; fi; cat ${q}/firewall.new; } > ${q}/apply.nft
|
|
4148
|
+
nft --check -f ${q}/apply.nft
|
|
4149
|
+
nft -s list table inet epd_baseline > ${q}/firewall.live 2>/dev/null || :
|
|
4150
|
+
if cmp -s ${q}/firewall.new /var/lib/epd-baseline/firewall.nft && cmp -s ${q}/firewall.live /var/lib/epd-baseline/firewall.expected; then
|
|
4151
|
+
echo 'Firewall already configured'
|
|
4152
|
+
else
|
|
4153
|
+
nft -f ${q}/apply.nft
|
|
4154
|
+
fi`, { stream: true });
|
|
4155
|
+
}
|
|
4156
|
+
if (s.sshHardening) {
|
|
4157
|
+
await host.exec(`exec 9>${q}/mutex
|
|
4158
|
+
flock 9
|
|
4159
|
+
[ -f ${q}/pending ]
|
|
4160
|
+
python3 - <<'PY'
|
|
4161
|
+
import os, stat, subprocess, tempfile
|
|
4162
|
+
p = '${sshPath}'
|
|
4163
|
+
s = open(p).read()
|
|
4164
|
+
start, end = '# BEGIN EPD BASELINE\\n', '# END EPD BASELINE\\n'
|
|
4165
|
+
if start in s:
|
|
4166
|
+
a, rest = s.split(start, 1)
|
|
4167
|
+
_, b = rest.split(end, 1)
|
|
4168
|
+
s = a + b
|
|
4169
|
+
root = 'no' if 'permitrootlogin no' in subprocess.check_output(['/usr/sbin/sshd', '-T'], text=True).splitlines() else 'prohibit-password'
|
|
4170
|
+
policy = 'PasswordAuthentication no\\nKbdInteractiveAuthentication no\\nPermitRootLogin ' + root + '\\nPubkeyAuthentication yes\\n'
|
|
4171
|
+
new = start + policy + end + s
|
|
4172
|
+
if open(p).read() != new:
|
|
4173
|
+
st = os.stat(p)
|
|
4174
|
+
fd, tmp = tempfile.mkstemp(dir='/etc/ssh', prefix='.epd-')
|
|
4175
|
+
with os.fdopen(fd, 'w') as f: f.write(new)
|
|
4176
|
+
os.chmod(tmp, stat.S_IMODE(st.st_mode))
|
|
4177
|
+
os.chown(tmp, st.st_uid, st.st_gid)
|
|
4178
|
+
os.replace(tmp, p)
|
|
4179
|
+
PY
|
|
4180
|
+
/usr/sbin/sshd -t
|
|
4181
|
+
if cmp -s ${sshPath} ${q}/sshd_config; then echo 'SSH hardening already configured'; else systemctl reload ssh || systemctl reload sshd; fi`, { stream: true });
|
|
4182
|
+
}
|
|
4183
|
+
await verifyKeyConnection(host);
|
|
4184
|
+
await host.exec(`exec 9>${q}/mutex
|
|
4185
|
+
flock 9
|
|
4186
|
+
[ -f ${q}/pending ] || { echo 'Baseline policy already reverted'; exit 1; }
|
|
4187
|
+
${s.firewall ? `install -m 600 ${q}/firewall.new /var/lib/epd-baseline/firewall.nft
|
|
4188
|
+
nft -s list table inet epd_baseline > /var/lib/epd-baseline/firewall.expected` : ""}
|
|
4189
|
+
rm ${q}/pending
|
|
4190
|
+
rmdir /var/lib/epd-baseline/access.lock`);
|
|
4191
|
+
if (s.firewall) {
|
|
4192
|
+
await writeChanged(host, "/etc/systemd/system/epd-firewall.service", `[Unit]
|
|
4193
|
+
Description=EPD host input firewall
|
|
4194
|
+
After=nftables.service
|
|
4195
|
+
Before=docker.service
|
|
4196
|
+
[Service]
|
|
4197
|
+
Type=oneshot
|
|
4198
|
+
RemainAfterExit=yes
|
|
4199
|
+
ExecStart=/bin/bash -ec 'if /usr/sbin/nft list table inet epd_baseline >/dev/null 2>&1; then /usr/sbin/nft delete table inet epd_baseline; fi; /usr/sbin/nft -f /var/lib/epd-baseline/firewall.nft'
|
|
4200
|
+
[Install]
|
|
4201
|
+
WantedBy=multi-user.target
|
|
4202
|
+
`);
|
|
4203
|
+
await host.exec("systemctl daemon-reload; systemctl enable epd-firewall.service");
|
|
4204
|
+
}
|
|
4205
|
+
log.host(host.name, "host access policy applied; fresh SSH key connection verified", "baseline");
|
|
4206
|
+
} catch (error) {
|
|
4207
|
+
await host.exec(`${q}/rollback`, { allowFailure: true }).catch(() => {
|
|
4208
|
+
return;
|
|
4209
|
+
});
|
|
4210
|
+
throw error;
|
|
4211
|
+
} finally {
|
|
4212
|
+
log.debug(`${host.name}: access-policy recovery files: ${dir}`);
|
|
4213
|
+
}
|
|
4214
|
+
}
|
|
4215
|
+
var init_hardening = __esm(() => {
|
|
4216
|
+
init_names();
|
|
4217
|
+
init_log();
|
|
4218
|
+
init_misc();
|
|
4219
|
+
init_proc();
|
|
4220
|
+
});
|
|
4221
|
+
|
|
4222
|
+
// src/core/baseline/index.ts
|
|
4223
|
+
async function applyBaseline(host, cfg) {
|
|
4224
|
+
log.host(host.name, "applying secure host baseline", "baseline");
|
|
4225
|
+
await hardenHost(host, cfg);
|
|
4226
|
+
}
|
|
4227
|
+
async function checkBaseline(host, cfg) {
|
|
4228
|
+
const checks = [];
|
|
4229
|
+
const commands = [];
|
|
4230
|
+
if (cfg.server.firewall)
|
|
4231
|
+
commands.push(["Host firewall", "nft -s list table inet epd_baseline | cmp - /var/lib/epd-baseline/firewall.expected && systemctl is-enabled --quiet epd-firewall.service"]);
|
|
4232
|
+
if (cfg.server.autoUpdates)
|
|
4233
|
+
commands.push(["Security updates", `apt-config dump | grep 'APT::Periodic::Unattended-Upgrade "1"' && systemctl is-active --quiet apt-daily-upgrade.timer`]);
|
|
4234
|
+
if (cfg.server.sshHardening)
|
|
4235
|
+
commands.push(["SSH hardening", "/usr/sbin/sshd -T | grep -x 'passwordauthentication no' && /usr/sbin/sshd -T | grep -x 'kbdinteractiveauthentication no' && /usr/sbin/sshd -T | grep -E '^permitrootlogin (prohibit-password|without-password|no)$'"]);
|
|
4236
|
+
if (cfg.server.logRotation && cfg.mode === "docker")
|
|
4237
|
+
commands.push(["Docker log limits", `python3 -c 'import json; d=json.load(open("/etc/docker/daemon.json")); assert d.get("log-driver")=="json-file" and d.get("log-opts",{}).get("max-size")=="10m" and d.get("log-opts",{}).get("max-file")=="3"'`]);
|
|
4238
|
+
for (const [name, command] of commands) {
|
|
4239
|
+
const result = await host.exec(command, { allowFailure: true });
|
|
4240
|
+
checks.push({ name, status: result.code === 0 ? "ok" : "warn", message: result.code === 0 ? "Configured" : "Missing or changed since setup", ...result.code === 0 ? {} : { hint: "Run epd setup --skip-deploy to apply the host baseline." } });
|
|
4241
|
+
}
|
|
4242
|
+
return checks;
|
|
4243
|
+
}
|
|
4244
|
+
var init_baseline = __esm(() => {
|
|
4245
|
+
init_log();
|
|
4246
|
+
init_hardening();
|
|
4247
|
+
});
|
|
4248
|
+
|
|
3310
4249
|
// src/core/ssh-setup.ts
|
|
3311
|
-
import { existsSync as existsSync7, mkdirSync as
|
|
3312
|
-
import { homedir as
|
|
3313
|
-
import { join as
|
|
4250
|
+
import { existsSync as existsSync7, mkdirSync as mkdirSync6, readFileSync as readFileSync5, unlinkSync as unlinkSync3, writeFileSync as writeFileSync6 } from "fs";
|
|
4251
|
+
import { homedir as homedir4, tmpdir as tmpdir2 } from "os";
|
|
4252
|
+
import { join as join8 } from "path";
|
|
3314
4253
|
function askpassBody(password) {
|
|
3315
4254
|
return `#!/bin/sh
|
|
3316
4255
|
printf '%s\\n' ${shq(password)}
|
|
@@ -3351,9 +4290,9 @@ chmod 600 "$HOME/.ssh/authorized_keys"
|
|
|
3351
4290
|
grep -qxF -- ${shq(key)} "$HOME/.ssh/authorized_keys" || printf '\\n%s\\n' ${shq(key)} >> "$HOME/.ssh/authorized_keys"`;
|
|
3352
4291
|
let installedCode = 1;
|
|
3353
4292
|
if (password) {
|
|
3354
|
-
const askpassScript =
|
|
4293
|
+
const askpassScript = join8(tmpdir2(), `epd-askpass-${Date.now()}-${Math.random().toString(36).slice(2)}.sh`);
|
|
3355
4294
|
try {
|
|
3356
|
-
|
|
4295
|
+
writeFileSync6(askpassScript, askpassBody(password), { mode: 448 });
|
|
3357
4296
|
const res = await run([
|
|
3358
4297
|
"ssh",
|
|
3359
4298
|
"-o",
|
|
@@ -3383,7 +4322,7 @@ grep -qxF -- ${shq(key)} "$HOME/.ssh/authorized_keys" || printf '\\n%s\\n' ${shq
|
|
|
3383
4322
|
}
|
|
3384
4323
|
} finally {
|
|
3385
4324
|
if (existsSync7(askpassScript))
|
|
3386
|
-
|
|
4325
|
+
unlinkSync3(askpassScript);
|
|
3387
4326
|
}
|
|
3388
4327
|
}
|
|
3389
4328
|
if (installedCode !== 0) {
|
|
@@ -3445,17 +4384,17 @@ async function publicKeyFor(host) {
|
|
|
3445
4384
|
const selected = keys.length === 1 ? "0" : await choose("Which SSH agent key should EPD authorize?", keys.map((key, index) => ({ value: String(index), label: key.split(/\s+/).slice(2).join(" ") || `Agent key ${index + 1}` })), "0");
|
|
3446
4385
|
return validateKey(keys[Number(selected)]);
|
|
3447
4386
|
}
|
|
3448
|
-
const sshDir =
|
|
4387
|
+
const sshDir = join8(homedir4(), ".ssh");
|
|
3449
4388
|
for (const name of ["id_ed25519", "gh_deploy", "id_ecdsa", "id_rsa"]) {
|
|
3450
|
-
const path =
|
|
4389
|
+
const path = join8(sshDir, `${name}.pub`);
|
|
3451
4390
|
if (existsSync7(path))
|
|
3452
4391
|
return validateKey(readFileSync5(path, "utf8"));
|
|
3453
4392
|
}
|
|
3454
|
-
const keyPath =
|
|
4393
|
+
const keyPath = join8(sshDir, "id_ed25519");
|
|
3455
4394
|
if (existsSync7(keyPath)) {
|
|
3456
4395
|
throw new EpdError(`Missing public key for ${keyPath}`, "Load it with ssh-add, or set ssh.key to its path, then retry.");
|
|
3457
4396
|
}
|
|
3458
|
-
|
|
4397
|
+
mkdirSync6(sshDir, { recursive: true, mode: 448 });
|
|
3459
4398
|
log.info(`Creating ${keyPath} with ed25519 algorithm...`);
|
|
3460
4399
|
const generated = await run(["ssh-keygen", "-t", "ed25519", "-f", keyPath, "-N", "", "-C", "epd"], { stream: true, allowFailure: true });
|
|
3461
4400
|
if (generated.code !== 0)
|
|
@@ -3483,8 +4422,8 @@ var init_ssh_setup = __esm(() => {
|
|
|
3483
4422
|
});
|
|
3484
4423
|
|
|
3485
4424
|
// src/proxy/detect.ts
|
|
3486
|
-
import { existsSync as existsSync8, readFileSync as readFileSync6, writeFileSync as
|
|
3487
|
-
import { basename as
|
|
4425
|
+
import { existsSync as existsSync8, readFileSync as readFileSync6, writeFileSync as writeFileSync7 } from "fs";
|
|
4426
|
+
import { basename as basename3, resolve as resolve4 } from "path";
|
|
3488
4427
|
async function detectExistingProxy(host, checkPorts = [80, 443]) {
|
|
3489
4428
|
const portsSet = new Set(checkPorts);
|
|
3490
4429
|
const filter = `( ${[...portsSet].map((p) => `sport = :${p}`).join(" or ")} )`;
|
|
@@ -3696,7 +4635,7 @@ http:
|
|
|
3696
4635
|
`;
|
|
3697
4636
|
}
|
|
3698
4637
|
function updateLocalConfigDisableProxy(configPath = "epd.yml") {
|
|
3699
|
-
const configFile =
|
|
4638
|
+
const configFile = resolve4(configPath);
|
|
3700
4639
|
if (!existsSync8(configFile))
|
|
3701
4640
|
return;
|
|
3702
4641
|
try {
|
|
@@ -3712,7 +4651,7 @@ function updateLocalConfigDisableProxy(configPath = "epd.yml") {
|
|
|
3712
4651
|
`);
|
|
3713
4652
|
}
|
|
3714
4653
|
if (updated !== raw) {
|
|
3715
|
-
|
|
4654
|
+
writeFileSync7(configFile, updated, "utf8");
|
|
3716
4655
|
log.ok("Updated epd.yml: set proxy: false");
|
|
3717
4656
|
}
|
|
3718
4657
|
} catch (err) {
|
|
@@ -3801,7 +4740,7 @@ ${c.yellow("!")} Unrecognized reverse proxy detected (${detected.details}).`);
|
|
|
3801
4740
|
const customConfig = await ask("Provide path to your custom proxy configuration file to deploy (or leave empty to configure manually):");
|
|
3802
4741
|
if (customConfig && existsSync8(customConfig)) {
|
|
3803
4742
|
const content = readFileSync6(customConfig, "utf8");
|
|
3804
|
-
const defaultRemote = `/etc/proxy/${
|
|
4743
|
+
const defaultRemote = `/etc/proxy/${basename3(customConfig)}`;
|
|
3805
4744
|
const remotePath = await ask(`Remote destination path on ${host.name}:`, defaultRemote);
|
|
3806
4745
|
await host.writeFile(remotePath, content);
|
|
3807
4746
|
log.ok(`${host.name}: uploaded proxy configuration to ${remotePath}`);
|
|
@@ -4646,15 +5585,21 @@ async function withLock(cfg, hosts, what, skip, fn) {
|
|
|
4646
5585
|
return fn();
|
|
4647
5586
|
const lock = new DeployLock(cfg, hosts);
|
|
4648
5587
|
await lock.acquire(what);
|
|
5588
|
+
const off = onInterrupt(async () => {
|
|
5589
|
+
log.warn("interrupted: releasing the deploy lock");
|
|
5590
|
+
await lock.release();
|
|
5591
|
+
});
|
|
4649
5592
|
try {
|
|
4650
5593
|
return await fn();
|
|
4651
5594
|
} finally {
|
|
5595
|
+
off();
|
|
4652
5596
|
await lock.release();
|
|
4653
5597
|
}
|
|
4654
5598
|
}
|
|
4655
5599
|
var STALE_AFTER_MS, activeLocks, SIGNALS, SIGNAL_EXIT, SIGNAL_RELEASE_MS, releasingOnSignal = false, signalHandlers;
|
|
4656
5600
|
var init_lock = __esm(() => {
|
|
4657
5601
|
init_log();
|
|
5602
|
+
init_interrupt();
|
|
4658
5603
|
init_misc();
|
|
4659
5604
|
init_names();
|
|
4660
5605
|
init_ssh();
|
|
@@ -4837,11 +5782,11 @@ var init_state = __esm(() => {
|
|
|
4837
5782
|
|
|
4838
5783
|
// src/deploy/image.ts
|
|
4839
5784
|
import { existsSync as existsSync9 } from "fs";
|
|
4840
|
-
import { join as
|
|
5785
|
+
import { join as join9 } from "path";
|
|
4841
5786
|
async function resolveVersion(cfg, explicit) {
|
|
4842
5787
|
if (explicit)
|
|
4843
5788
|
return { id: explicit, source: "explicit", dirty: false };
|
|
4844
|
-
if (existsSync9(
|
|
5789
|
+
if (existsSync9(join9(cfg.root, ".git")) && await which("git")) {
|
|
4845
5790
|
const sha = await run(["git", "-C", cfg.root, "rev-parse", "--short=12", "HEAD"], { allowFailure: true });
|
|
4846
5791
|
if (sha.code === 0 && sha.stdout) {
|
|
4847
5792
|
const status = await run(["git", "-C", cfg.root, "status", "--porcelain"], { allowFailure: true });
|
|
@@ -4851,25 +5796,30 @@ async function resolveVersion(cfg, explicit) {
|
|
|
4851
5796
|
}
|
|
4852
5797
|
return { id: timestamp(), source: "timestamp", dirty: false };
|
|
4853
5798
|
}
|
|
4854
|
-
async function hasBuildx() {
|
|
4855
|
-
|
|
5799
|
+
async function hasBuildx(configured) {
|
|
5800
|
+
const engine = await containerEngine(configured);
|
|
5801
|
+
if (engineKind(engine) !== "docker")
|
|
5802
|
+
return false;
|
|
5803
|
+
return (await run([engine, "buildx", "version"], { allowFailure: true })).code === 0;
|
|
4856
5804
|
}
|
|
4857
5805
|
async function buildImage(cfg, version, env) {
|
|
4858
|
-
const dockerfile =
|
|
5806
|
+
const dockerfile = join9(cfg.root, cfg.build.dockerfile);
|
|
4859
5807
|
if (!existsSync9(dockerfile)) {
|
|
4860
5808
|
throw new EpdError(`${cfg.build.dockerfile} not found`, "Add a Dockerfile, point build.dockerfile at yours, or switch to `mode: process`.");
|
|
4861
5809
|
}
|
|
5810
|
+
cfg.containerEngine = await containerEngine(cfg.containerEngine);
|
|
4862
5811
|
const ref = imageRef(cfg, version);
|
|
4863
|
-
log.step(`Building ${ref}
|
|
4864
|
-
if (await hasBuildx())
|
|
5812
|
+
log.step(`Building ${ref}`, "build");
|
|
5813
|
+
if (await hasBuildx(cfg.containerEngine))
|
|
4865
5814
|
await buildWithBuildx(cfg, ref, version, env);
|
|
4866
5815
|
else
|
|
4867
5816
|
await buildWithLegacyDocker(cfg, ref, version, env);
|
|
4868
5817
|
}
|
|
4869
5818
|
async function buildWithBuildx(cfg, ref, version, env) {
|
|
4870
|
-
const
|
|
5819
|
+
const engine = await containerEngine(cfg.containerEngine);
|
|
5820
|
+
const args = [engine, "buildx", "build"];
|
|
4871
5821
|
args.push("--platform", cfg.build.platform);
|
|
4872
|
-
args.push("--file",
|
|
5822
|
+
args.push("--file", join9(cfg.root, cfg.build.dockerfile));
|
|
4873
5823
|
args.push("--tag", ref, "--tag", `${cfg.image}:latest`);
|
|
4874
5824
|
if (cfg.build.target)
|
|
4875
5825
|
args.push("--target", cfg.build.target);
|
|
@@ -4891,39 +5841,51 @@ async function buildWithBuildx(cfg, ref, version, env) {
|
|
|
4891
5841
|
args.push("--load");
|
|
4892
5842
|
}
|
|
4893
5843
|
args.push(cfg.build.context);
|
|
4894
|
-
await ensureBuilder();
|
|
5844
|
+
await ensureBuilder(engine);
|
|
4895
5845
|
await run(args, { cwd: cfg.root, stream: true, env, label: "docker buildx build" });
|
|
4896
5846
|
}
|
|
4897
5847
|
async function buildWithLegacyDocker(cfg, ref, version, env) {
|
|
4898
|
-
|
|
5848
|
+
const engine = await containerEngine(cfg.containerEngine);
|
|
5849
|
+
const kind = engineKind(engine);
|
|
5850
|
+
if (kind !== "podman" && kind !== "nerdctl" && Object.keys(cfg.build.secrets).length) {
|
|
4899
5851
|
throw new EpdError("build.secrets needs BuildKit", "Install the docker buildx plugin: https://docs.docker.com/go/buildx/");
|
|
4900
5852
|
}
|
|
4901
5853
|
const localPlatform = `linux/${process.arch === "arm64" ? "arm64" : "amd64"}`;
|
|
4902
|
-
if (cfg.build.platform !== localPlatform) {
|
|
5854
|
+
if (kind === "docker" && cfg.build.platform !== localPlatform) {
|
|
4903
5855
|
log.warn(`buildx is not installed, so the image is built for ${localPlatform} rather than ${cfg.build.platform}. ` + `Install buildx to cross-build, or set build.platform: ${localPlatform}.`);
|
|
4904
5856
|
}
|
|
4905
|
-
const args = [
|
|
5857
|
+
const args = [engine, "build", "--file", join9(cfg.root, cfg.build.dockerfile), "--tag", ref, "--tag", `${cfg.image}:latest`];
|
|
5858
|
+
if (kind !== "docker") {
|
|
5859
|
+
args.push("--platform", cfg.build.platform);
|
|
5860
|
+
if (kind === "podman")
|
|
5861
|
+
args.push("--format", "docker");
|
|
5862
|
+
for (const [id, envName] of Object.entries(cfg.build.secrets)) {
|
|
5863
|
+
if (env[envName] === undefined)
|
|
5864
|
+
throw new EpdError(`build.secrets: ${envName} is not set`);
|
|
5865
|
+
args.push("--secret", `id=${id},env=${envName}`);
|
|
5866
|
+
}
|
|
5867
|
+
}
|
|
4906
5868
|
if (cfg.build.target)
|
|
4907
5869
|
args.push("--target", cfg.build.target);
|
|
4908
5870
|
for (const [k, v] of Object.entries(cfg.build.args))
|
|
4909
5871
|
args.push("--build-arg", `${k}=${v}`);
|
|
4910
5872
|
args.push("--label", `epd.app=${cfg.name}`, "--label", `epd.version=${version}`);
|
|
4911
5873
|
args.push(cfg.build.context);
|
|
4912
|
-
await run(args, { cwd: cfg.root, stream: true, env, label:
|
|
5874
|
+
await run(args, { cwd: cfg.root, stream: true, env, label: `${engine} build` });
|
|
4913
5875
|
if (cfg.registry) {
|
|
4914
|
-
log.step(`Pushing ${ref}
|
|
4915
|
-
await run([
|
|
4916
|
-
await run([
|
|
5876
|
+
log.step(`Pushing ${ref}`, "push");
|
|
5877
|
+
await run([engine, "push", ref], { stream: true });
|
|
5878
|
+
await run([engine, "push", `${cfg.image}:latest`], { stream: true, allowFailure: true });
|
|
4917
5879
|
}
|
|
4918
5880
|
}
|
|
4919
|
-
async function ensureBuilder() {
|
|
4920
|
-
const res = await run([
|
|
5881
|
+
async function ensureBuilder(engine = "docker") {
|
|
5882
|
+
const res = await run([engine, "buildx", "inspect", "epd"], { allowFailure: true });
|
|
4921
5883
|
if (res.code === 0) {
|
|
4922
|
-
await run([
|
|
5884
|
+
await run([engine, "buildx", "use", "epd"], { allowFailure: true });
|
|
4923
5885
|
return;
|
|
4924
5886
|
}
|
|
4925
5887
|
log.info('creating buildx builder "epd"');
|
|
4926
|
-
await run([
|
|
5888
|
+
await run([engine, "buildx", "create", "--name", "epd", "--use", "--bootstrap"], { stream: true });
|
|
4927
5889
|
}
|
|
4928
5890
|
function checkRegistryPassword(cfg, env) {
|
|
4929
5891
|
if (!cfg.registry)
|
|
@@ -4951,7 +5913,7 @@ async function ensureImage(host, cfg, version) {
|
|
|
4951
5913
|
await host.exec(`docker pull ${shq(ref)} >/dev/null`, { label: `${host.name}: docker pull` });
|
|
4952
5914
|
} else {
|
|
4953
5915
|
log.host(host.name, `shipping ${ref} over ssh (no registry configured)`);
|
|
4954
|
-
await host.pipeInto("gunzip | docker load", [localShell("bash"), "-c",
|
|
5916
|
+
await host.pipeInto("gunzip | docker load", [localShell("bash"), "-c", `${shq(await containerEngine(cfg.containerEngine))} save ${shq(ref)} | gzip -1`]);
|
|
4955
5917
|
}
|
|
4956
5918
|
}
|
|
4957
5919
|
async function pruneImages(host, cfg, keep, inUse) {
|
|
@@ -4967,6 +5929,7 @@ docker image prune -f --filter ${shq(`label=epd.app=${cfg.name}`)} >/dev/null 2>
|
|
|
4967
5929
|
}
|
|
4968
5930
|
var imageRef = (cfg, version) => `${cfg.image}:${version}`;
|
|
4969
5931
|
var init_image = __esm(() => {
|
|
5932
|
+
init_container_engine();
|
|
4970
5933
|
init_log();
|
|
4971
5934
|
init_misc();
|
|
4972
5935
|
init_proc();
|
|
@@ -5161,7 +6124,7 @@ var init_docker = __esm(() => {
|
|
|
5161
6124
|
|
|
5162
6125
|
// src/deploy/process.ts
|
|
5163
6126
|
import { existsSync as existsSync10 } from "fs";
|
|
5164
|
-
import { join as
|
|
6127
|
+
import { join as join10 } from "path";
|
|
5165
6128
|
function releaseDir(cfg, version) {
|
|
5166
6129
|
return `${paths(cfg).releases}/${version}`;
|
|
5167
6130
|
}
|
|
@@ -5170,14 +6133,14 @@ async function uploadSource(host, cfg, version) {
|
|
|
5170
6133
|
const p = paths(cfg);
|
|
5171
6134
|
await host.exec(`mkdir -p ${shq(p.releases)} ${shq(p.shared)}`, asUser);
|
|
5172
6135
|
if (cfg.process.source === "git") {
|
|
5173
|
-
if (!existsSync10(
|
|
6136
|
+
if (!existsSync10(join10(cfg.root, ".git")))
|
|
5174
6137
|
throw new EpdError('process.source is "git" but this is not a git repository');
|
|
5175
6138
|
log.host(host.name, `uploading HEAD as ${version}`);
|
|
5176
|
-
await host.pipeInto(`mkdir -p ${shq(dest)} && tar -x -C ${shq(dest)}`, ["
|
|
6139
|
+
await host.pipeInto(`mkdir -p ${shq(dest)} && tar -x -C ${shq(dest)}`, ["git", "-C", cfg.root, "archive", "--format=tar", "HEAD"]);
|
|
5177
6140
|
return;
|
|
5178
6141
|
}
|
|
5179
6142
|
const previous = await host.capture(`ls -1dt ${shq(p.releases)}/*/ 2>/dev/null | head -n 1 || true`, { ...asUser, allowFailure: true });
|
|
5180
|
-
const args = ["rsync", "-az", "--delete", "--human-readable", "--
|
|
6143
|
+
const args = ["rsync", "-az", "--delete", "--human-readable", "--stats"];
|
|
5181
6144
|
for (const ex of cfg.process.exclude)
|
|
5182
6145
|
args.push("--exclude", ex);
|
|
5183
6146
|
if (previous)
|
|
@@ -5799,7 +6762,7 @@ async function deploy(loaded, opts = {}) {
|
|
|
5799
6762
|
const targetHosts = selectHosts(cfg, services, opts.onlyHosts);
|
|
5800
6763
|
const hosts = targetHosts.map((h) => host(h, cfg.ssh));
|
|
5801
6764
|
const version = (await resolveVersion(cfg, opts.version)).id;
|
|
5802
|
-
log.step(`Deploying ${c.bold(cfg.name)} ${c.cyan(version)}${cfg.destination ? ` \u2192 ${cfg.destination}` : ""} to ${targetHosts.length} host(s)
|
|
6765
|
+
log.step(`Deploying ${c.bold(cfg.name)} ${c.cyan(version)}${cfg.destination ? ` \u2192 ${cfg.destination}` : ""} to ${targetHosts.length} host(s)`, "plan");
|
|
5803
6766
|
if (opts.dryRun) {
|
|
5804
6767
|
log.step(`[dry-run] Simulating deployment plan for ${c.bold(cfg.name)} ${c.cyan(version)}`);
|
|
5805
6768
|
log.plain(`
|
|
@@ -5855,6 +6818,7 @@ ${c.bold("DNS Synchronization")}`);
|
|
|
5855
6818
|
${c.green("\u2713")} [dry-run] Plan validated successfully. No changes were made.`);
|
|
5856
6819
|
return;
|
|
5857
6820
|
}
|
|
6821
|
+
log.step(`Connecting to ${hosts.map((h) => h.target).join(", ")}`, "connect");
|
|
5858
6822
|
for (const host of hosts) {
|
|
5859
6823
|
await host.ping();
|
|
5860
6824
|
if (host.user !== "root") {
|
|
@@ -5972,6 +6936,9 @@ async function rollout(cfg, hosts, services, version, opts, fx, snapshot) {
|
|
|
5972
6936
|
}
|
|
5973
6937
|
};
|
|
5974
6938
|
const stopNew = async (host, started) => {
|
|
6939
|
+
await fx.diagnose?.(host, started).catch(() => {
|
|
6940
|
+
return;
|
|
6941
|
+
});
|
|
5975
6942
|
for (const { svc, slot } of started)
|
|
5976
6943
|
await fx.stop(host, svc, slot, { drain: 0 }).catch(() => {
|
|
5977
6944
|
return;
|
|
@@ -6146,6 +7113,10 @@ async function rollout(cfg, hosts, services, version, opts, fx, snapshot) {
|
|
|
6146
7113
|
}
|
|
6147
7114
|
function liveEffects(cfg, env) {
|
|
6148
7115
|
return {
|
|
7116
|
+
async diagnose(host, started) {
|
|
7117
|
+
if (cfg.mode === "docker")
|
|
7118
|
+
await reportFailedContainers(host, cfg, started);
|
|
7119
|
+
},
|
|
6149
7120
|
async prepare(host, version, reuse) {
|
|
6150
7121
|
if (cfg.mode === "docker") {
|
|
6151
7122
|
await loginRegistry(host, cfg, env);
|
|
@@ -6214,6 +7185,26 @@ function liveEffects(cfg, env) {
|
|
|
6214
7185
|
}
|
|
6215
7186
|
};
|
|
6216
7187
|
}
|
|
7188
|
+
async function reportFailedContainers(host, cfg, started) {
|
|
7189
|
+
const containers = await listContainers(host, cfg);
|
|
7190
|
+
const failed = containers.filter((ct) => started.some((s) => s.svc.name === ct.service && s.slot === ct.slot));
|
|
7191
|
+
for (const ct of failed) {
|
|
7192
|
+
const res = await host.exec(`docker inspect --format '{{.State.Status}} exit={{.State.ExitCode}} oom={{.State.OOMKilled}} restarts={{.RestartCount}}' ${shq(ct.name)} 2>&1 || true
|
|
7193
|
+
echo EPD_DIAG_LOGS
|
|
7194
|
+
docker logs --tail 40 ${shq(ct.name)} 2>&1 || true`, { allowFailure: true, label: `${host.name}: diagnose ${ct.name}` });
|
|
7195
|
+
const [state = "", logs = ""] = res.stdout.split("EPD_DIAG_LOGS");
|
|
7196
|
+
log.host(host.name, `${ct.name}: ${state.trim() || ct.status}`, "diagnose");
|
|
7197
|
+
const lines = logs.split(`
|
|
7198
|
+
`).filter((l) => l.trim());
|
|
7199
|
+
if (lines.length) {
|
|
7200
|
+
log.host(host.name, `${ct.name}: last ${lines.length} log line(s):`, "diagnose");
|
|
7201
|
+
for (const line of lines)
|
|
7202
|
+
log.output(line, "stdout", ct.name, host.name);
|
|
7203
|
+
} else {
|
|
7204
|
+
log.host(host.name, `${ct.name}: produced no output`, "diagnose");
|
|
7205
|
+
}
|
|
7206
|
+
}
|
|
7207
|
+
}
|
|
6217
7208
|
async function confirmUp(host, cfg, svc, slot) {
|
|
6218
7209
|
if (cfg.mode === "docker") {
|
|
6219
7210
|
const containers = await listContainers(host, cfg);
|
|
@@ -6277,7 +7268,7 @@ function buildAccessoryEndpoints(cfg, targetHost) {
|
|
|
6277
7268
|
async function deployAccessories(cfg, env, recreate) {
|
|
6278
7269
|
if (!cfg.accessories.length)
|
|
6279
7270
|
return;
|
|
6280
|
-
log.step("Accessories");
|
|
7271
|
+
log.step("Accessories", "accessories");
|
|
6281
7272
|
for (const acc of cfg.accessories) {
|
|
6282
7273
|
const host2 = host(acc.host, cfg.ssh);
|
|
6283
7274
|
if (cfg.mode === "process" && !await hasDocker(host2)) {
|
|
@@ -6313,7 +7304,7 @@ function selectHosts(cfg, services, only) {
|
|
|
6313
7304
|
return all.filter((h) => only.includes(h));
|
|
6314
7305
|
}
|
|
6315
7306
|
async function hook(cfg, name, script, version) {
|
|
6316
|
-
log.step(`Hook ${name}
|
|
7307
|
+
log.step(`Hook ${name}`, "hooks");
|
|
6317
7308
|
await runShell(script, {
|
|
6318
7309
|
cwd: cfg.root,
|
|
6319
7310
|
stream: true,
|
|
@@ -6374,6 +7365,7 @@ var init_setup = __esm(() => {
|
|
|
6374
7365
|
init_auth();
|
|
6375
7366
|
init_bootstrap();
|
|
6376
7367
|
init_ssh();
|
|
7368
|
+
init_baseline();
|
|
6377
7369
|
init_ssh_setup();
|
|
6378
7370
|
init_traefik();
|
|
6379
7371
|
init_detect();
|
|
@@ -6391,7 +7383,8 @@ var init_setup = __esm(() => {
|
|
|
6391
7383
|
help: () => `${c.bold("epd setup")} \u2014 get servers ready and run the first deploy
|
|
6392
7384
|
|
|
6393
7385
|
Installs Docker (or rsync + pm2 in process mode), creates the shared network,
|
|
6394
|
-
starts Traefik and then deploys.
|
|
7386
|
+
starts Traefik and then deploys. On Debian/Ubuntu with systemd, also applies
|
|
7387
|
+
the secure host baseline configured in server:. Safe to run again at any time.
|
|
6395
7388
|
|
|
6396
7389
|
Options
|
|
6397
7390
|
--skip-deploy Only prepare the servers
|
|
@@ -6442,9 +7435,6 @@ Options
|
|
|
6442
7435
|
await prepareSsh(host);
|
|
6443
7436
|
log.host(host.name, "SSH key authentication succeeded");
|
|
6444
7437
|
await host.exec("true", { label: `${host.target}: sudo authorization` });
|
|
6445
|
-
if (host.user !== "root") {
|
|
6446
|
-
await host.exec(`echo ${shq(`${host.user} ALL=(ALL) NOPASSWD:ALL`)} > /etc/sudoers.d/epd && chmod 440 /etc/sudoers.d/epd`, { allowFailure: true, label: `${host.target}: configure passwordless sudo` });
|
|
6447
|
-
}
|
|
6448
7438
|
}
|
|
6449
7439
|
await pool(hosts, 4, async (host) => {
|
|
6450
7440
|
await host.ping();
|
|
@@ -6456,6 +7446,7 @@ Options
|
|
|
6456
7446
|
await installSystemPackages(host);
|
|
6457
7447
|
await installProcessRuntime(host, cfg);
|
|
6458
7448
|
}
|
|
7449
|
+
await applyBaseline(host, cfg);
|
|
6459
7450
|
await ensureDirs(host, cfg);
|
|
6460
7451
|
await reservePorts(host, cfg);
|
|
6461
7452
|
});
|
|
@@ -6626,12 +7617,12 @@ Options
|
|
|
6626
7617
|
// src/commands/status.ts
|
|
6627
7618
|
function table(rows, head) {
|
|
6628
7619
|
const all = [head, ...rows];
|
|
6629
|
-
const widths = head.map((_, i) => Math.max(...all.map((r) =>
|
|
6630
|
-
const line = (r) => r.map((cell, i) => cell + " ".repeat(Math.max(0, widths[i] -
|
|
7620
|
+
const widths = head.map((_, i) => Math.max(...all.map((r) => stripAnsi2(r[i] ?? "").length)));
|
|
7621
|
+
const line = (r) => r.map((cell, i) => cell + " ".repeat(Math.max(0, widths[i] - stripAnsi2(cell).length))).join(" ").trimEnd();
|
|
6631
7622
|
return [c.gray(line(head)), ...rows.map(line)].join(`
|
|
6632
7623
|
`);
|
|
6633
7624
|
}
|
|
6634
|
-
function
|
|
7625
|
+
function stripAnsi2(s) {
|
|
6635
7626
|
return s.replace(/\x1b\[[0-9;]*m/g, "");
|
|
6636
7627
|
}
|
|
6637
7628
|
var status;
|
|
@@ -7188,6 +8179,8 @@ Options
|
|
|
7188
8179
|
}
|
|
7189
8180
|
log.plain(`${c.bold(cfg.name)} ${c.gray(cfg.configPath)}`);
|
|
7190
8181
|
log.plain(` mode ${cfg.mode}${cfg.destination ? c.gray(` (${cfg.destination})`) : ""}`);
|
|
8182
|
+
if (cfg.mode === "docker")
|
|
8183
|
+
log.plain(` engine ${cfg.containerEngine ?? "auto"} (local)`);
|
|
7191
8184
|
if (cfg.mode === "docker")
|
|
7192
8185
|
log.plain(` image ${cfg.image}${cfg.registry ? c.gray(` via ${cfg.registry.server ?? "docker.io"}`) : c.gray(" shipped over ssh")}`);
|
|
7193
8186
|
else
|
|
@@ -8217,15 +9210,15 @@ var init_api2 = __esm(() => {
|
|
|
8217
9210
|
|
|
8218
9211
|
// src/commands/sevalla.ts
|
|
8219
9212
|
function formatTable(headers, rows) {
|
|
8220
|
-
const colWidths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) =>
|
|
8221
|
-
const pad = (s, len) => s + " ".repeat(Math.max(0, len -
|
|
9213
|
+
const colWidths = headers.map((h, i) => Math.max(h.length, ...rows.map((r) => stripAnsi3(r[i] ?? "").length)));
|
|
9214
|
+
const pad = (s, len) => s + " ".repeat(Math.max(0, len - stripAnsi3(s).length));
|
|
8222
9215
|
const headerLine = headers.map((h, i) => c.bold(pad(h, colWidths[i]))).join(" ");
|
|
8223
9216
|
const sepLine = colWidths.map((w) => "\u2500".repeat(w)).join(" ");
|
|
8224
9217
|
const dataLines = rows.map((r) => r.map((cell, i) => pad(cell ?? "", colWidths[i])).join(" "));
|
|
8225
9218
|
return [headerLine, c.gray(sepLine), ...dataLines].join(`
|
|
8226
9219
|
`);
|
|
8227
9220
|
}
|
|
8228
|
-
function
|
|
9221
|
+
function stripAnsi3(str) {
|
|
8229
9222
|
return str.replace(/\x1B\[[0-9;]*[a-zA-Z]/g, "");
|
|
8230
9223
|
}
|
|
8231
9224
|
var sevalla;
|
|
@@ -8372,9 +9365,9 @@ ${c.bold("SEVALLA MANAGED DATABASES")} (${dbs.length})
|
|
|
8372
9365
|
|
|
8373
9366
|
// src/core/update.ts
|
|
8374
9367
|
import { createHash } from "crypto";
|
|
8375
|
-
import { chmodSync as chmodSync3, existsSync as existsSync11, mkdirSync as
|
|
8376
|
-
import { homedir as
|
|
8377
|
-
import { basename as
|
|
9368
|
+
import { chmodSync as chmodSync3, existsSync as existsSync11, mkdirSync as mkdirSync7, readFileSync as readFileSync7, renameSync as renameSync2, unlinkSync as unlinkSync4, writeFileSync as writeFileSync8 } from "fs";
|
|
9369
|
+
import { homedir as homedir5 } from "os";
|
|
9370
|
+
import { basename as basename4, dirname as dirname5, join as join11 } from "path";
|
|
8378
9371
|
function isValidVersion(version) {
|
|
8379
9372
|
return VERSION_RE.test(version);
|
|
8380
9373
|
}
|
|
@@ -8434,18 +9427,18 @@ async function downloadBytes(url, timeoutMs) {
|
|
|
8434
9427
|
function replaceExecutable(path, data) {
|
|
8435
9428
|
const tmpPath = `${path}.tmp.${process.pid}.${Date.now()}`;
|
|
8436
9429
|
try {
|
|
8437
|
-
|
|
9430
|
+
writeFileSync8(tmpPath, data);
|
|
8438
9431
|
chmodSync3(tmpPath, 493);
|
|
8439
9432
|
renameSync2(tmpPath, path);
|
|
8440
9433
|
} catch (e) {
|
|
8441
9434
|
try {
|
|
8442
|
-
|
|
9435
|
+
unlinkSync4(tmpPath);
|
|
8443
9436
|
} catch {}
|
|
8444
9437
|
throw e;
|
|
8445
9438
|
}
|
|
8446
9439
|
}
|
|
8447
9440
|
function isCompiledExecutable(execPath, isBun) {
|
|
8448
|
-
return isBun && !["bun", "bun.exe"].includes(
|
|
9441
|
+
return isBun && !["bun", "bun.exe"].includes(basename4(execPath).toLowerCase());
|
|
8449
9442
|
}
|
|
8450
9443
|
function packageUpdateCommand(manager, pkgSpec, platform = process.platform) {
|
|
8451
9444
|
return platform === "win32" && manager === "npm" ? [process.env.ComSpec || "cmd.exe", "/d", "/s", "/c", `npm install -g ${pkgSpec}`] : [manager, "install", "-g", pkgSpec];
|
|
@@ -8469,7 +9462,7 @@ function isNewer(current, latest) {
|
|
|
8469
9462
|
return lPatch > cPatch;
|
|
8470
9463
|
}
|
|
8471
9464
|
function getCachePath() {
|
|
8472
|
-
return
|
|
9465
|
+
return join11(homedir5(), ".epd", "update-check.json");
|
|
8473
9466
|
}
|
|
8474
9467
|
function readCache() {
|
|
8475
9468
|
try {
|
|
@@ -8483,9 +9476,9 @@ function readCache() {
|
|
|
8483
9476
|
function writeCache(latestVersion) {
|
|
8484
9477
|
try {
|
|
8485
9478
|
const p = getCachePath();
|
|
8486
|
-
|
|
9479
|
+
mkdirSync7(dirname5(p), { recursive: true });
|
|
8487
9480
|
const data = { lastChecked: Date.now(), latestVersion };
|
|
8488
|
-
|
|
9481
|
+
writeFileSync8(p, JSON.stringify(data));
|
|
8489
9482
|
} catch {}
|
|
8490
9483
|
}
|
|
8491
9484
|
async function fetchLatestNpmVersion() {
|
|
@@ -8613,7 +9606,7 @@ var init_update = __esm(() => {
|
|
|
8613
9606
|
});
|
|
8614
9607
|
|
|
8615
9608
|
// package.json
|
|
8616
|
-
var version = "0.5.
|
|
9609
|
+
var version = "0.5.16";
|
|
8617
9610
|
var init_package = () => {};
|
|
8618
9611
|
|
|
8619
9612
|
// src/version.ts
|
|
@@ -9384,9 +10377,282 @@ Options
|
|
|
9384
10377
|
};
|
|
9385
10378
|
});
|
|
9386
10379
|
|
|
10380
|
+
// src/commands/archive.ts
|
|
10381
|
+
import { spawn as spawn2 } from "child_process";
|
|
10382
|
+
import { createReadStream, createWriteStream } from "fs";
|
|
10383
|
+
import { pipeline } from "stream/promises";
|
|
10384
|
+
import { createHash as createHash2 } from "crypto";
|
|
10385
|
+
function archiveVolume(value) {
|
|
10386
|
+
const parts = value.split(":");
|
|
10387
|
+
if (parts.length < 2 || parts.length > 3 || !/^[A-Za-z0-9][A-Za-z0-9_.-]*$/.test(parts[0] || "") || !parts[1]?.startsWith("/") || /(^|\/)\.\.($|\/)/.test(parts[1]) || parts[2] && !["ro", "rw"].includes(parts[2]))
|
|
10388
|
+
throw new EpdError("Archive supports declared Docker named volumes only, with an absolute container destination. Bind mounts are unavailable.");
|
|
10389
|
+
return { source: parts[0], destination: parts[1] };
|
|
10390
|
+
}
|
|
10391
|
+
function archiveTargetFingerprint(host, container, volume) {
|
|
10392
|
+
return createHash2("sha256").update(JSON.stringify({ host, container, ...volume })).digest("hex");
|
|
10393
|
+
}
|
|
10394
|
+
function volumeRestoreScript() {
|
|
10395
|
+
return `set -eu
|
|
10396
|
+
cd /data
|
|
10397
|
+
for reserved in /data/.epd-archive-*; do
|
|
10398
|
+
if test -e "$reserved" || test -L "$reserved"; then echo 'Reserved recovery files exist; inspect them before retrying' >&2; exit 1; fi
|
|
10399
|
+
done
|
|
10400
|
+
mkdir .epd-archive-new .epd-archive-old
|
|
10401
|
+
remove_current() {
|
|
10402
|
+
for item in /data/* /data/.[!.]* /data/..?*; do
|
|
10403
|
+
if ! test -e "$item" && ! test -L "$item"; then continue; fi
|
|
10404
|
+
case "$item" in /data/.epd-archive-*) continue;; esac
|
|
10405
|
+
rm -rf "$item" || return 1
|
|
10406
|
+
done
|
|
10407
|
+
}
|
|
10408
|
+
rollback() {
|
|
10409
|
+
result=$?
|
|
10410
|
+
trap - EXIT
|
|
10411
|
+
if test "$result" != 0 && test -f /data/.epd-archive-committing; then
|
|
10412
|
+
if ! remove_current; then echo 'Rollback failed; recovery data retained in .epd-archive-old' >&2; exit "$result"; fi
|
|
10413
|
+
for item in /data/.epd-archive-old/* /data/.epd-archive-old/.[!.]* /data/.epd-archive-old/..?*; do
|
|
10414
|
+
if ! test -e "$item" && ! test -L "$item"; then continue; fi
|
|
10415
|
+
if ! mv "$item" /data/; then echo 'Rollback failed; recovery data retained in .epd-archive-old' >&2; exit "$result"; fi
|
|
10416
|
+
done
|
|
10417
|
+
fi
|
|
10418
|
+
rm -rf /data/.epd-archive-new /data/.epd-archive-old /data/.epd-archive-committing
|
|
10419
|
+
exit "$result"
|
|
10420
|
+
}
|
|
10421
|
+
trap rollback EXIT
|
|
10422
|
+
cat > /data/.epd-archive-new/archive.tar.gz
|
|
10423
|
+
tar -tzf /data/.epd-archive-new/archive.tar.gz > /data/.epd-archive-new/list
|
|
10424
|
+
if grep -E '(^/|(^|/)\\.\\.(/|$)|(^|/)\\.epd-archive-)' /data/.epd-archive-new/list; then echo 'Unsafe archive path' >&2; exit 1; fi
|
|
10425
|
+
if tar -tvzf /data/.epd-archive-new/archive.tar.gz | grep -E '^[^d-]'; then echo 'Archive links and special files are unsupported for safe restore' >&2; exit 1; fi
|
|
10426
|
+
mkdir /data/.epd-archive-new/extracted
|
|
10427
|
+
tar -xzf /data/.epd-archive-new/archive.tar.gz -C /data/.epd-archive-new/extracted
|
|
10428
|
+
for item in /data/* /data/.[!.]* /data/..?*; do
|
|
10429
|
+
if ! test -e "$item" && ! test -L "$item"; then continue; fi
|
|
10430
|
+
case "$item" in /data/.epd-archive-*) continue;; esac
|
|
10431
|
+
cp -a "$item" /data/.epd-archive-old/
|
|
10432
|
+
done
|
|
10433
|
+
touch /data/.epd-archive-committing
|
|
10434
|
+
remove_current
|
|
10435
|
+
for item in /data/.epd-archive-new/extracted/* /data/.epd-archive-new/extracted/.[!.]* /data/.epd-archive-new/extracted/..?*; do
|
|
10436
|
+
if ! test -e "$item" && ! test -L "$item"; then continue; fi
|
|
10437
|
+
mv "$item" /data/
|
|
10438
|
+
done
|
|
10439
|
+
rm /data/.epd-archive-committing
|
|
10440
|
+
`;
|
|
10441
|
+
}
|
|
10442
|
+
var archive;
|
|
10443
|
+
var init_archive = __esm(() => {
|
|
10444
|
+
init_log();
|
|
10445
|
+
init_misc();
|
|
10446
|
+
init_names();
|
|
10447
|
+
init_ssh();
|
|
10448
|
+
archive = {
|
|
10449
|
+
name: "archive",
|
|
10450
|
+
summary: "Back up and restore a project accessory named volume",
|
|
10451
|
+
options: { accessory: { type: "string" }, "volume-index": { type: "string" }, file: { type: "string" }, yes: { type: "boolean" }, "expected-target": { type: "string" }, "expected-host": { type: "string" }, "ssh-user": { type: "string" }, "ssh-port": { type: "string" }, "ssh-key": { type: "string" }, "known-hosts": { type: "string" } },
|
|
10452
|
+
help: () => `epd archive backup|restore --accessory NAME --volume-index 0 --file archive.tar.gz
|
|
10453
|
+
Consistent Docker named-volume archive: stops the owning accessory and restarts it afterward. Database images and bind mounts are unsupported. Restore requires --yes and --expected-target from the backup result. Untrusted archive paths and links are rejected.`,
|
|
10454
|
+
async run(ctx) {
|
|
10455
|
+
const verb = ctx.positionals[0];
|
|
10456
|
+
if (!["backup", "restore"].includes(verb || ""))
|
|
10457
|
+
throw new EpdError("Choose archive backup or restore.");
|
|
10458
|
+
const cfg = ctx.load().config;
|
|
10459
|
+
const name = String(ctx.values.accessory || "");
|
|
10460
|
+
const accessory = cfg.accessories.find((item) => item.name === name);
|
|
10461
|
+
if (!accessory || /postgres|mysql|mariadb|mongo|redis|timescale|postgis/i.test(accessory.image))
|
|
10462
|
+
throw new EpdError("Choose a non-database accessory for volume archives. Use logical database backups for database images.");
|
|
10463
|
+
const index = Number(ctx.values["volume-index"] || 0);
|
|
10464
|
+
if (!Number.isInteger(index) || index < 0 || !accessory.volumes[index])
|
|
10465
|
+
throw new EpdError("Choose a declared accessory volume index.");
|
|
10466
|
+
const volume = archiveVolume(accessory.volumes[index]);
|
|
10467
|
+
const file = String(ctx.values.file || "");
|
|
10468
|
+
if (!file)
|
|
10469
|
+
throw new EpdError("Provide a local --file archive path.");
|
|
10470
|
+
const container = accessoryContainer(cfg.name, name);
|
|
10471
|
+
const target = archiveTargetFingerprint(accessory.host, container, volume);
|
|
10472
|
+
if (verb === "restore" && (!ctx.values.yes || ctx.values["expected-target"] !== target))
|
|
10473
|
+
throw new EpdError("Restore requires confirmation and the exact target fingerprint recorded by backup.");
|
|
10474
|
+
if (ctx.values["expected-host"]) {
|
|
10475
|
+
if (accessory.host !== ctx.values["expected-host"])
|
|
10476
|
+
throw new EpdError("Accessory host differs from the organization-owned project server.");
|
|
10477
|
+
if (!ctx.values["ssh-key"] || !ctx.values["known-hosts"])
|
|
10478
|
+
throw new EpdError("Pinned dashboard SSH credentials are required.");
|
|
10479
|
+
cfg.ssh = { ...cfg.ssh, user: String(ctx.values["ssh-user"] || "root"), hostUsers: {}, port: Number(ctx.values["ssh-port"] || 22), key: String(ctx.values["ssh-key"]), proxyJump: undefined, sudoPassword: undefined, options: ["StrictHostKeyChecking=yes", `UserKnownHostsFile=${ctx.values["known-hosts"]}`, "GlobalKnownHostsFile=/dev/null", "IdentityAgent=none", "ControlMaster=no", "ControlPath=none"] };
|
|
10480
|
+
}
|
|
10481
|
+
const remote = host(accessory.host, cfg.ssh);
|
|
10482
|
+
const helper = "alpine:3.22";
|
|
10483
|
+
const inner = verb === "backup" ? `set -eu
|
|
10484
|
+
for reserved in /data/.epd-archive-*; do
|
|
10485
|
+
if test -e "$reserved" || test -L "$reserved"; then echo 'Reserved recovery files exist; inspect them before retrying' >&2; exit 1; fi
|
|
10486
|
+
done
|
|
10487
|
+
tar -czf - -C /data .` : volumeRestoreScript();
|
|
10488
|
+
const operation = `docker run --rm -i --network none --mount ${shq(`type=volume,src=${volume.source},dst=/data${verb === "backup" ? ",readonly" : ""}`)} ${shq(helper)} sh -c ${shq(inner)}`;
|
|
10489
|
+
const script = `set -eu
|
|
10490
|
+
if ! docker container inspect ${shq(container)} >/dev/null 2>&1; then echo 'Accessory container is missing' >&2; exit 1; fi
|
|
10491
|
+
docker inspect --format '{{range .Mounts}}{{println .Name}}{{end}}' ${shq(container)} | grep -Fx ${shq(volume.source)} >/dev/null || { echo 'Configured volume is not mounted by this accessory' >&2; exit 1; }
|
|
10492
|
+
others=$(docker ps --filter ${shq(`volume=${volume.source}`)} --format '{{.Names}}' | grep -vx ${shq(container)} || true)
|
|
10493
|
+
[ -z "$others" ] || { echo 'Another running container shares this volume; stop its writers first' >&2; exit 1; }
|
|
10494
|
+
docker image inspect ${shq(helper)} >/dev/null 2>&1 || docker pull ${shq(helper)} >/dev/null
|
|
10495
|
+
running=$(docker inspect --format '{{.State.Running}}' ${shq(container)})
|
|
10496
|
+
cleanup() { result=$?; trap - EXIT; if test "$running" = true; then docker start ${shq(container)} >/dev/null || result=1; if ! docker inspect --format '{{.State.Running}}' ${shq(container)} | grep -qx true; then result=1; fi; fi; exit "$result"; }
|
|
10497
|
+
trap cleanup EXIT
|
|
10498
|
+
if test "$running" = true; then docker stop ${shq(container)} >/dev/null; fi
|
|
10499
|
+
${operation}`;
|
|
10500
|
+
log.info("ARCHIVE_TARGET " + target);
|
|
10501
|
+
log.step(`${verb} named volume for accessory ${name}; the accessory is paused during streaming.`);
|
|
10502
|
+
const command = `${remote.user === "root" ? "" : "sudo -n "}bash -o pipefail -c ${shq(script)}`;
|
|
10503
|
+
const child = spawn2("ssh", [...remote.sshOptions(), remote.target, command], { stdio: ["pipe", "pipe", "pipe"] });
|
|
10504
|
+
let stderr = "";
|
|
10505
|
+
child.stderr.on("data", (chunk) => {
|
|
10506
|
+
stderr = (stderr + chunk.toString()).slice(-2000);
|
|
10507
|
+
});
|
|
10508
|
+
const done = new Promise((resolve, reject) => {
|
|
10509
|
+
child.on("error", reject);
|
|
10510
|
+
child.on("close", (code) => code === 0 ? resolve() : reject(new EpdError(`Volume ${verb} failed (exit ${code}).`, stderr)));
|
|
10511
|
+
});
|
|
10512
|
+
if (verb === "backup")
|
|
10513
|
+
child.stdin.end();
|
|
10514
|
+
else
|
|
10515
|
+
child.stdout.resume();
|
|
10516
|
+
await Promise.all([done, verb === "backup" ? pipeline(child.stdout, createWriteStream(file, { mode: 384 })) : pipeline(createReadStream(file), child.stdin)]);
|
|
10517
|
+
log.ok(`Volume ${verb} verified; original container running state restored.`);
|
|
10518
|
+
}
|
|
10519
|
+
};
|
|
10520
|
+
});
|
|
10521
|
+
|
|
10522
|
+
// src/commands/database.ts
|
|
10523
|
+
import { spawn as spawn3 } from "child_process";
|
|
10524
|
+
import { createReadStream as createReadStream2, createWriteStream as createWriteStream2 } from "fs";
|
|
10525
|
+
import { pipeline as pipeline2 } from "stream/promises";
|
|
10526
|
+
function postgresProvisionScript(options) {
|
|
10527
|
+
const o = options;
|
|
10528
|
+
if (!/^[a-zA-Z][a-zA-Z0-9_]{0,62}$/.test(o.database) || !/^[a-zA-Z][a-zA-Z0-9_]{0,62}$/.test(o.user))
|
|
10529
|
+
throw new EpdError("Database and user must be SQL identifiers (letters, digits and underscore, at most 63 characters).");
|
|
10530
|
+
if (!Number.isInteger(o.port) || o.port < 1024 || o.port > 65535 || !Number.isInteger(o.memoryMb) || o.memoryMb < 256 || o.memoryMb > 65536)
|
|
10531
|
+
throw new EpdError("Invalid database port or memory limit.");
|
|
10532
|
+
if (!o.password || o.password.length < 20 || /[\r\n\0]/.test(o.password))
|
|
10533
|
+
throw new EpdError("Database passwords must contain at least 20 characters.");
|
|
10534
|
+
if (!/^postgres:(16|17)(\.\d+)?-alpine$/.test(o.image))
|
|
10535
|
+
throw new EpdError("Choose a supported PostgreSQL alpine image.");
|
|
10536
|
+
return `set -eu
|
|
10537
|
+
command -v docker >/dev/null || { echo 'Docker is required; enroll or prepare the host first.' >&2; exit 1; }
|
|
10538
|
+
if docker container inspect ${shq(o.container)} >/dev/null 2>&1; then echo 'Container already exists; inspect it before retrying.' >&2; exit 1; fi
|
|
10539
|
+
if docker volume inspect ${shq(o.volume)} >/dev/null 2>&1; then echo 'Data volume already exists; use restore or inspect before retrying.' >&2; exit 1; fi
|
|
10540
|
+
docker pull ${shq(o.image)} >/dev/null
|
|
10541
|
+
docker volume create ${shq(o.volume)} >/dev/null
|
|
10542
|
+
DB_ENV=$(mktemp)
|
|
10543
|
+
trap 'rm -f "$DB_ENV"' EXIT
|
|
10544
|
+
chmod 600 "$DB_ENV"
|
|
10545
|
+
printf '%s\\n' ${shq(`POSTGRES_DB=${o.database}`)} ${shq(`POSTGRES_USER=${o.user}`)} ${shq(`POSTGRES_PASSWORD=${o.password}`)} > "$DB_ENV"
|
|
10546
|
+
docker run -d --name ${shq(o.container)} --restart unless-stopped --memory ${shq(`${o.memoryMb}m`)} --publish ${shq(`127.0.0.1:${o.port}:5432`)} --mount ${shq(`type=volume,src=${o.volume},dst=/var/lib/postgresql/data`)} --env-file "$DB_ENV" ${shq(o.image)} >/dev/null
|
|
10547
|
+
${postgresCheckScript(o.container, o.user, o.database)}
|
|
10548
|
+
`;
|
|
10549
|
+
}
|
|
10550
|
+
function postgresCheckScript(container, user, database) {
|
|
10551
|
+
return `verified=0
|
|
10552
|
+
for attempt in $(seq 1 60); do
|
|
10553
|
+
if docker exec ${shq(container)} psql -v ON_ERROR_STOP=1 -U ${shq(user)} -d ${shq(database)} -tAc 'SELECT 1' 2>/dev/null | grep -qx '1'; then verified=1; break; fi
|
|
10554
|
+
sleep 2
|
|
10555
|
+
done
|
|
10556
|
+
[ "$verified" = 1 ] || { echo 'PostgreSQL query verification failed; data volume retained for inspection.' >&2; exit 1; }
|
|
10557
|
+
echo 'PostgreSQL SELECT 1 verified.'`;
|
|
10558
|
+
}
|
|
10559
|
+
function postgresRestoreScript(container, user, database) {
|
|
10560
|
+
return `set -euo pipefail
|
|
10561
|
+
umask 077
|
|
10562
|
+
WORK=$(mktemp -d)
|
|
10563
|
+
trap 'rm -f "$WORK/archive.gz" "$WORK/archive.sql" "$WORK/reset.sql"; rmdir "$WORK"' EXIT
|
|
10564
|
+
cat > "$WORK/archive.gz"
|
|
10565
|
+
gzip -t "$WORK/archive.gz"
|
|
10566
|
+
gunzip -c "$WORK/archive.gz" > "$WORK/archive.sql"
|
|
10567
|
+
grep -q '^-- PostgreSQL database dump complete' "$WORK/archive.sql" || { echo 'Archive has no complete pg_dump footer; no restore was attempted.' >&2; exit 1; }
|
|
10568
|
+
cat > "$WORK/reset.sql" <<'EPD_RESET_SQL'
|
|
10569
|
+
SET LOCAL lock_timeout = '30s';
|
|
10570
|
+
SELECT pg_advisory_xact_lock(hashtext('epd-database-restore'));
|
|
10571
|
+
DO $epd$
|
|
10572
|
+
DECLARE item record;
|
|
10573
|
+
BEGIN
|
|
10574
|
+
IF EXISTS (SELECT 1 FROM pg_extension WHERE extname <> 'plpgsql')
|
|
10575
|
+
OR EXISTS (SELECT 1 FROM pg_largeobject_metadata)
|
|
10576
|
+
OR EXISTS (SELECT 1 FROM pg_publication)
|
|
10577
|
+
OR EXISTS (SELECT 1 FROM pg_subscription)
|
|
10578
|
+
OR EXISTS (SELECT 1 FROM pg_event_trigger)
|
|
10579
|
+
OR EXISTS (SELECT 1 FROM pg_foreign_server)
|
|
10580
|
+
OR EXISTS (SELECT 1 FROM pg_default_acl) THEN
|
|
10581
|
+
RAISE EXCEPTION 'Automatic schema replacement does not support extensions, large objects, replication, event triggers, foreign servers or custom default privileges. Use an operator-managed restore.';
|
|
10582
|
+
END IF;
|
|
10583
|
+
FOR item IN SELECT nspname FROM pg_namespace WHERE nspname !~ '^pg_' AND nspname <> 'information_schema' LOOP
|
|
10584
|
+
EXECUTE format('DROP SCHEMA %I CASCADE', item.nspname);
|
|
10585
|
+
END LOOP;
|
|
10586
|
+
END $epd$;
|
|
10587
|
+
CREATE SCHEMA public AUTHORIZATION pg_database_owner;
|
|
10588
|
+
GRANT USAGE ON SCHEMA public TO PUBLIC;
|
|
10589
|
+
EPD_RESET_SQL
|
|
10590
|
+
cat "$WORK/reset.sql" "$WORK/archive.sql" | docker exec -i ${shq(container)} psql -X --single-transaction -v ON_ERROR_STOP=1 -U ${shq(user)} -d ${shq(database)} -f -
|
|
10591
|
+
`;
|
|
10592
|
+
}
|
|
10593
|
+
var database;
|
|
10594
|
+
var init_database = __esm(() => {
|
|
10595
|
+
init_log();
|
|
10596
|
+
init_misc();
|
|
10597
|
+
init_names();
|
|
10598
|
+
init_ssh();
|
|
10599
|
+
database = {
|
|
10600
|
+
name: "database",
|
|
10601
|
+
summary: "Provision and verify a private PostgreSQL accessory",
|
|
10602
|
+
options: { file: { type: "string" }, yes: { type: "boolean" }, accessory: { type: "string" }, port: { type: "string" }, memory: { type: "string" } },
|
|
10603
|
+
help: () => `epd database provision|check|backup|restore --accessory <name> [--port 5432] [--memory 1024]
|
|
10604
|
+
Uses a PostgreSQL accessory in epd.yml. Publishes only to host loopback; use an SSH tunnel for external clients. Docker must already be installed. backup/restore require --file; restore also requires --yes. Existing containers or data volumes are never overwritten.`,
|
|
10605
|
+
async run(ctx) {
|
|
10606
|
+
const verb = ctx.positionals[0];
|
|
10607
|
+
if (!["provision", "check", "backup", "restore"].includes(verb || ""))
|
|
10608
|
+
throw new EpdError("Use epd database provision or epd database check.");
|
|
10609
|
+
const cfg = ctx.load().config;
|
|
10610
|
+
const name = String(ctx.values.accessory || "database");
|
|
10611
|
+
const accessory = cfg.accessories.find((item) => item.name === name);
|
|
10612
|
+
if (!accessory || !accessory.image.startsWith("postgres:"))
|
|
10613
|
+
throw new EpdError("Configure a supported PostgreSQL accessory first.");
|
|
10614
|
+
const container = accessoryContainer(cfg.name, name);
|
|
10615
|
+
const user = accessory.env.POSTGRES_USER || "postgres";
|
|
10616
|
+
const dbName = accessory.env.POSTGRES_DB || cfg.name;
|
|
10617
|
+
const host2 = host(accessory.host, cfg.ssh);
|
|
10618
|
+
if (verb === "backup" || verb === "restore") {
|
|
10619
|
+
const file = String(ctx.values.file || "");
|
|
10620
|
+
if (!file)
|
|
10621
|
+
throw new EpdError("Provide --file for the backup archive.");
|
|
10622
|
+
if (verb === "restore" && !ctx.values.yes)
|
|
10623
|
+
throw new EpdError("Restore replaces database objects. Supply --yes after confirming the exact target.");
|
|
10624
|
+
const sqlCommand = verb === "backup" ? `docker exec ${shq(container)} pg_dump --clean --if-exists -U ${shq(user)} ${shq(dbName)} | gzip -9` : postgresRestoreScript(container, user, dbName);
|
|
10625
|
+
const remote = `${host2.user === "root" ? "" : "sudo -n "}bash -o pipefail -c ${shq(sqlCommand)}`;
|
|
10626
|
+
const process2 = spawn3("ssh", [...host2.sshOptions(), host2.target, remote], { stdio: ["pipe", "pipe", "pipe"] });
|
|
10627
|
+
let stderr = "";
|
|
10628
|
+
process2.stderr.on("data", (chunk) => {
|
|
10629
|
+
stderr = (stderr + chunk.toString()).slice(-4000);
|
|
10630
|
+
});
|
|
10631
|
+
const completed = new Promise((resolve, reject) => {
|
|
10632
|
+
process2.on("error", reject);
|
|
10633
|
+
process2.on("close", (code) => code === 0 ? resolve() : reject(new EpdError(`Database ${verb} failed (exit ${code}).`, stderr)));
|
|
10634
|
+
});
|
|
10635
|
+
if (verb === "backup")
|
|
10636
|
+
process2.stdin.end();
|
|
10637
|
+
else
|
|
10638
|
+
process2.stdout.resume();
|
|
10639
|
+
await Promise.all([completed, verb === "backup" ? pipeline2(process2.stdout, createWriteStream2(file, { mode: 384 })) : pipeline2(createReadStream2(file), process2.stdin)]);
|
|
10640
|
+
if (verb === "restore")
|
|
10641
|
+
await host2.exec(postgresCheckScript(container, user, dbName), { label: "Verify restored database" });
|
|
10642
|
+
log.ok(`PostgreSQL ${verb} completed.`);
|
|
10643
|
+
return;
|
|
10644
|
+
}
|
|
10645
|
+
log.step(`${verb === "provision" ? "Provisioning" : "Verifying"} PostgreSQL on ${host2.name}`);
|
|
10646
|
+
const script = verb === "check" ? postgresCheckScript(container, user, dbName) : postgresProvisionScript({ container, volume: `${container}-data`, image: accessory.image, database: dbName, user, password: accessory.env.POSTGRES_PASSWORD || "", port: Number(ctx.values.port || 5432), memoryMb: Number(ctx.values.memory || 1024) });
|
|
10647
|
+
await host2.exec(script, { label: "PostgreSQL database operation" });
|
|
10648
|
+
log.ok("PostgreSQL SELECT 1 verified.");
|
|
10649
|
+
}
|
|
10650
|
+
};
|
|
10651
|
+
});
|
|
10652
|
+
|
|
9387
10653
|
// src/commands/backup.ts
|
|
9388
|
-
import { createWriteStream, mkdirSync as
|
|
9389
|
-
import { dirname as dirname6, join as
|
|
10654
|
+
import { createWriteStream as createWriteStream3, mkdirSync as mkdirSync8, statSync as statSync2 } from "fs";
|
|
10655
|
+
import { dirname as dirname6, join as join12, resolve as resolve5 } from "path";
|
|
9390
10656
|
function detectAccessoryType(decl, cfg) {
|
|
9391
10657
|
const name = decl.name;
|
|
9392
10658
|
const img = (decl.image || "").toLowerCase();
|
|
@@ -9482,8 +10748,8 @@ Options
|
|
|
9482
10748
|
} else {
|
|
9483
10749
|
targets = accessories.map((a) => detectAccessoryType(a, cfg));
|
|
9484
10750
|
}
|
|
9485
|
-
const outBaseDir =
|
|
9486
|
-
|
|
10751
|
+
const outBaseDir = resolve5(process.cwd(), "backups");
|
|
10752
|
+
mkdirSync8(outBaseDir, { recursive: true });
|
|
9487
10753
|
for (const target of targets) {
|
|
9488
10754
|
const host2 = host(target.hostName, cfg.ssh);
|
|
9489
10755
|
const isRunning = await host2.test(`docker ps -q -f name=${shq(`^${target.containerName}$`)} | grep -q .`);
|
|
@@ -9494,8 +10760,8 @@ Options
|
|
|
9494
10760
|
const timestamp = new Date().toISOString().replace(/[:.]/g, "-").replace("T", "_").slice(0, 19);
|
|
9495
10761
|
const ext = target.type === "volume" ? "tar.gz" : "sql.gz";
|
|
9496
10762
|
const filename = `${cfg.name}-${target.name}-${timestamp}.${ext}`;
|
|
9497
|
-
const localFile = ctx.values.output ?
|
|
9498
|
-
|
|
10763
|
+
const localFile = ctx.values.output ? resolve5(String(ctx.values.output)) : join12(outBaseDir, filename);
|
|
10764
|
+
mkdirSync8(dirname6(localFile), { recursive: true });
|
|
9499
10765
|
let dumpCmd = "";
|
|
9500
10766
|
if (target.type === "postgres") {
|
|
9501
10767
|
dumpCmd = `docker exec ${shq(target.containerName)} pg_dump -U ${shq(target.dbUser)} ${shq(target.dbName)} | gzip -9`;
|
|
@@ -9514,7 +10780,7 @@ Options
|
|
|
9514
10780
|
log.step(`Streaming ${c.bold(target.type)} backup of ${c.magenta(target.name)} from ${host2.name}...`);
|
|
9515
10781
|
const t0 = Date.now();
|
|
9516
10782
|
const sshArgs = [...host2.sshOptions(), host2.target, dumpCmd];
|
|
9517
|
-
const writeStream =
|
|
10783
|
+
const writeStream = createWriteStream3(localFile);
|
|
9518
10784
|
await new Promise((res, rej) => {
|
|
9519
10785
|
const proc = typeof process.isBun !== "undefined" ? Bun.spawn(["ssh", ...sshArgs], { stdout: "pipe", stderr: "pipe" }) : __require("child_process").spawn("ssh", sshArgs, { stdio: ["ignore", "pipe", "pipe"] });
|
|
9520
10786
|
const stream = proc.stdout;
|
|
@@ -9543,8 +10809,8 @@ Options
|
|
|
9543
10809
|
});
|
|
9544
10810
|
|
|
9545
10811
|
// src/commands/restore.ts
|
|
9546
|
-
import { createReadStream, existsSync as existsSync12 } from "fs";
|
|
9547
|
-
import { basename as
|
|
10812
|
+
import { createReadStream as createReadStream3, existsSync as existsSync12 } from "fs";
|
|
10813
|
+
import { basename as basename5, resolve as resolve6 } from "path";
|
|
9548
10814
|
var restore;
|
|
9549
10815
|
var init_restore = __esm(() => {
|
|
9550
10816
|
init_log();
|
|
@@ -9570,12 +10836,12 @@ Options
|
|
|
9570
10836
|
const backupPath = ctx.positionals[0];
|
|
9571
10837
|
if (!backupPath)
|
|
9572
10838
|
throw new EpdError("Please provide a path to the backup file to restore.");
|
|
9573
|
-
const absPath =
|
|
10839
|
+
const absPath = resolve6(backupPath);
|
|
9574
10840
|
if (!existsSync12(absPath))
|
|
9575
10841
|
throw new EpdError(`Backup file not found: ${absPath}`);
|
|
9576
10842
|
const loaded = ctx.load();
|
|
9577
10843
|
const cfg = loaded.config;
|
|
9578
|
-
const fileBase =
|
|
10844
|
+
const fileBase = basename5(absPath);
|
|
9579
10845
|
const accessories = cfg.accessories;
|
|
9580
10846
|
if (!accessories.length)
|
|
9581
10847
|
throw new EpdError("No accessories configured in epd.yml.");
|
|
@@ -9644,7 +10910,7 @@ Options
|
|
|
9644
10910
|
log.step(`Streaming restore into ${c.bold(targetAccessoryName)} on ${host2.name}...`);
|
|
9645
10911
|
const t0 = Date.now();
|
|
9646
10912
|
const sshArgs = [...host2.sshOptions(), host2.target, restoreCmd];
|
|
9647
|
-
const readStream =
|
|
10913
|
+
const readStream = createReadStream3(absPath);
|
|
9648
10914
|
await new Promise((res, rej) => {
|
|
9649
10915
|
const proc = typeof process.isBun !== "undefined" ? Bun.spawn(["ssh", ...sshArgs], { stdin: "pipe", stdout: "inherit", stderr: "inherit" }) : __require("child_process").spawn("ssh", sshArgs, { stdio: ["pipe", "inherit", "inherit"] });
|
|
9650
10916
|
const stdinStream = proc.stdin;
|
|
@@ -9673,9 +10939,9 @@ Options
|
|
|
9673
10939
|
});
|
|
9674
10940
|
|
|
9675
10941
|
// src/commands/doctor.ts
|
|
9676
|
-
import { existsSync as existsSync13, readdirSync, statSync as statSync3 } from "fs";
|
|
9677
|
-
import { homedir as
|
|
9678
|
-
import { join as
|
|
10942
|
+
import { existsSync as existsSync13, readdirSync as readdirSync2, statSync as statSync3 } from "fs";
|
|
10943
|
+
import { homedir as homedir6 } from "os";
|
|
10944
|
+
import { join as join13 } from "path";
|
|
9679
10945
|
function printResults(results, prefix = " ") {
|
|
9680
10946
|
for (const r of results) {
|
|
9681
10947
|
const symbol = r.status === "ok" ? c.green("\u2713") : r.status === "warn" ? c.yellow("!") : c.red("\u2717");
|
|
@@ -9687,10 +10953,12 @@ function printResults(results, prefix = " ") {
|
|
|
9687
10953
|
}
|
|
9688
10954
|
var doctor;
|
|
9689
10955
|
var init_doctor = __esm(() => {
|
|
10956
|
+
init_container_engine();
|
|
9690
10957
|
init_log();
|
|
9691
10958
|
init_proc();
|
|
9692
10959
|
init_ssh();
|
|
9693
10960
|
init_misc();
|
|
10961
|
+
init_baseline();
|
|
9694
10962
|
init_names();
|
|
9695
10963
|
init_resolve();
|
|
9696
10964
|
doctor = {
|
|
@@ -9749,31 +11017,6 @@ Options
|
|
|
9749
11017
|
hint: "Run `git init` to enable git SHA-based image tagging and version tracking."
|
|
9750
11018
|
});
|
|
9751
11019
|
}
|
|
9752
|
-
const dockerVer = await run(["docker", "--version"], { allowFailure: true });
|
|
9753
|
-
if (dockerVer.code === 0) {
|
|
9754
|
-
const daemonCheck = await run(["docker", "info"], { allowFailure: true });
|
|
9755
|
-
if (daemonCheck.code === 0) {
|
|
9756
|
-
results.push({
|
|
9757
|
-
name: "Docker",
|
|
9758
|
-
status: "ok",
|
|
9759
|
-
message: `${dockerVer.stdout.trim()} (daemon running)`
|
|
9760
|
-
});
|
|
9761
|
-
} else {
|
|
9762
|
-
results.push({
|
|
9763
|
-
name: "Docker",
|
|
9764
|
-
status: "warn",
|
|
9765
|
-
message: `${dockerVer.stdout.trim()} installed, but daemon is not running`,
|
|
9766
|
-
hint: "Start Docker with `systemctl start docker` or launch Docker Desktop."
|
|
9767
|
-
});
|
|
9768
|
-
}
|
|
9769
|
-
} else {
|
|
9770
|
-
results.push({
|
|
9771
|
-
name: "Docker",
|
|
9772
|
-
status: "warn",
|
|
9773
|
-
message: "Docker is not installed locally",
|
|
9774
|
-
hint: "Docker is required locally to build images. (Not required if using mode: process)."
|
|
9775
|
-
});
|
|
9776
|
-
}
|
|
9777
11020
|
const sshVer = await run(["ssh", "-V"], { allowFailure: true, captureStderr: true });
|
|
9778
11021
|
const sshText = (sshVer.stderr || sshVer.stdout || "").trim();
|
|
9779
11022
|
if (sshVer.code === 0 || sshText.includes("OpenSSH")) {
|
|
@@ -9790,7 +11033,7 @@ Options
|
|
|
9790
11033
|
hint: "Install OpenSSH client via your package manager."
|
|
9791
11034
|
});
|
|
9792
11035
|
}
|
|
9793
|
-
const sshDir =
|
|
11036
|
+
const sshDir = join13(homedir6(), ".ssh");
|
|
9794
11037
|
if (process.env.SSH_PRIVATE_KEY || process.env.EPD_SSH_KEY) {
|
|
9795
11038
|
results.push({
|
|
9796
11039
|
name: "SSH Key (Environment)",
|
|
@@ -9798,11 +11041,11 @@ Options
|
|
|
9798
11041
|
message: "SSH_PRIVATE_KEY is set in the environment (ideal for CI)"
|
|
9799
11042
|
});
|
|
9800
11043
|
} else if (existsSync13(sshDir)) {
|
|
9801
|
-
const keys =
|
|
11044
|
+
const keys = readdirSync2(sshDir).filter((f) => ["id_ed25519", "id_rsa", "gh_deploy"].includes(f));
|
|
9802
11045
|
if (keys.length > 0) {
|
|
9803
11046
|
const keyIssues = [];
|
|
9804
11047
|
for (const k of keys) {
|
|
9805
|
-
const p =
|
|
11048
|
+
const p = join13(sshDir, k);
|
|
9806
11049
|
try {
|
|
9807
11050
|
const st = statSync3(p);
|
|
9808
11051
|
const mode = st.mode & 511;
|
|
@@ -9857,6 +11100,14 @@ ${c.bold("Configuration & Secrets")}`);
|
|
|
9857
11100
|
return;
|
|
9858
11101
|
}
|
|
9859
11102
|
const { config: cfg, env } = loadedConfig;
|
|
11103
|
+
if (cfg.mode === "docker") {
|
|
11104
|
+
try {
|
|
11105
|
+
const engine = await containerEngine(cfg.containerEngine, false);
|
|
11106
|
+
results.push({ name: "Local container engine", status: "ok", message: `${engine} is reachable` });
|
|
11107
|
+
} catch (error) {
|
|
11108
|
+
results.push({ name: "Local container engine", status: "warn", message: error instanceof Error ? error.message : String(error), hint: "Start a compatible engine or set container_engine in epd.yml." });
|
|
11109
|
+
}
|
|
11110
|
+
}
|
|
9860
11111
|
const requiredSecrets = [];
|
|
9861
11112
|
if (cfg.env && Array.isArray(cfg.env.secret)) {
|
|
9862
11113
|
requiredSecrets.push(...cfg.env.secret);
|
|
@@ -9986,6 +11237,7 @@ ${c.bold("Remote Servers")}`);
|
|
|
9986
11237
|
});
|
|
9987
11238
|
}
|
|
9988
11239
|
}
|
|
11240
|
+
results.push(...await checkBaseline(h, cfg));
|
|
9989
11241
|
const diskCheck = await h.exec('df -h / | awk "NR==2 {print \\$4, \\$5}"', { allowFailure: true, sudo: false });
|
|
9990
11242
|
if (diskCheck.code === 0 && diskCheck.stdout.trim()) {
|
|
9991
11243
|
const [avail, usedPct] = diskCheck.stdout.trim().split(" ");
|
|
@@ -10226,6 +11478,7 @@ Setup Instructions
|
|
|
10226
11478
|
// src/commands/index.ts
|
|
10227
11479
|
var commands;
|
|
10228
11480
|
var init_commands = __esm(() => {
|
|
11481
|
+
init_agent2();
|
|
10229
11482
|
init_init();
|
|
10230
11483
|
init_setup();
|
|
10231
11484
|
init_deploy2();
|
|
@@ -10247,6 +11500,8 @@ var init_commands = __esm(() => {
|
|
|
10247
11500
|
init_maintenance();
|
|
10248
11501
|
init_ssl();
|
|
10249
11502
|
init_top();
|
|
11503
|
+
init_archive();
|
|
11504
|
+
init_database();
|
|
10250
11505
|
init_backup();
|
|
10251
11506
|
init_restore();
|
|
10252
11507
|
init_action();
|
|
@@ -10254,6 +11509,7 @@ var init_commands = __esm(() => {
|
|
|
10254
11509
|
init_completion();
|
|
10255
11510
|
commands = [
|
|
10256
11511
|
init,
|
|
11512
|
+
agent,
|
|
10257
11513
|
setup,
|
|
10258
11514
|
deploy2,
|
|
10259
11515
|
redeploy,
|
|
@@ -10276,6 +11532,8 @@ var init_commands = __esm(() => {
|
|
|
10276
11532
|
maintenance,
|
|
10277
11533
|
ssl,
|
|
10278
11534
|
top,
|
|
11535
|
+
archive,
|
|
11536
|
+
database,
|
|
10279
11537
|
backup,
|
|
10280
11538
|
restore,
|
|
10281
11539
|
ghAction,
|
|
@@ -10286,6 +11544,7 @@ var init_commands = __esm(() => {
|
|
|
10286
11544
|
|
|
10287
11545
|
// src/cli.ts
|
|
10288
11546
|
init_log();
|
|
11547
|
+
init_interrupt();
|
|
10289
11548
|
init_misc();
|
|
10290
11549
|
init_prompt();
|
|
10291
11550
|
init_load();
|
|
@@ -10296,7 +11555,7 @@ import { parseArgs } from "util";
|
|
|
10296
11555
|
var CATEGORIES = [
|
|
10297
11556
|
{
|
|
10298
11557
|
title: "Deploy & Lifecycle",
|
|
10299
|
-
commands: ["init", "setup", "deploy", "redeploy", "rollback", "remove"]
|
|
11558
|
+
commands: ["init", "agent", "setup", "deploy", "redeploy", "rollback", "remove"]
|
|
10300
11559
|
},
|
|
10301
11560
|
{
|
|
10302
11561
|
title: "Observability & Metrics",
|
|
@@ -10304,7 +11563,7 @@ var CATEGORIES = [
|
|
|
10304
11563
|
},
|
|
10305
11564
|
{
|
|
10306
11565
|
title: "Server Management",
|
|
10307
|
-
commands: ["exec", "shell", "lock", "proxy", "maintenance", "backup", "restore"]
|
|
11566
|
+
commands: ["exec", "shell", "lock", "proxy", "maintenance", "database", "archive", "backup", "restore"]
|
|
10308
11567
|
},
|
|
10309
11568
|
{
|
|
10310
11569
|
title: "Cloud & Automation",
|
|
@@ -10336,6 +11595,8 @@ ${c.bold("Global options")}
|
|
|
10336
11595
|
-c, --config <file> Path to epd.yml
|
|
10337
11596
|
-d, --destination <d> Overlay epd.<d>.yml (staging, production, \u2026)
|
|
10338
11597
|
-v, --verbose Show every command epd runs
|
|
11598
|
+
--log-format <f> pretty (default) or json: one JSON event per line on
|
|
11599
|
+
stdout, ending with a "result" event (EPD_LOG_FORMAT)
|
|
10339
11600
|
-h, --help Show help for a command
|
|
10340
11601
|
--version Print the epd version
|
|
10341
11602
|
|
|
@@ -10424,6 +11685,11 @@ ${command.help()}`);
|
|
|
10424
11685
|
return 0;
|
|
10425
11686
|
}
|
|
10426
11687
|
setVerbose(Boolean(parsed.values.verbose));
|
|
11688
|
+
if (!NO_RUN_LOG.has(command.name)) {
|
|
11689
|
+
const file = openRunLog(command.name, argv, VERSION);
|
|
11690
|
+
if (file)
|
|
11691
|
+
log.debug(`run log: ${file}`);
|
|
11692
|
+
}
|
|
10427
11693
|
const loadOptions = {
|
|
10428
11694
|
file: parsed.values.config,
|
|
10429
11695
|
destination: parsed.values.destination
|
|
@@ -10434,24 +11700,69 @@ ${command.help()}`);
|
|
|
10434
11700
|
loadOptions,
|
|
10435
11701
|
load: () => loadConfig(loadOptions)
|
|
10436
11702
|
};
|
|
10437
|
-
if (command.name !== "update") {
|
|
11703
|
+
if (command.name !== "update" && command.name !== "agent") {
|
|
10438
11704
|
await promptAutoUpdate(VERSION);
|
|
10439
11705
|
}
|
|
10440
11706
|
await command.run(ctx);
|
|
10441
11707
|
return 0;
|
|
10442
11708
|
}
|
|
11709
|
+
var NO_RUN_LOG = new Set(["completion", "help", "shell", "agent"]);
|
|
11710
|
+
function preParseLogFormat(argv) {
|
|
11711
|
+
let value;
|
|
11712
|
+
const rest = [];
|
|
11713
|
+
for (let i = 0;i < argv.length; i++) {
|
|
11714
|
+
const a = argv[i];
|
|
11715
|
+
if (a === "--log-format")
|
|
11716
|
+
value = argv[++i];
|
|
11717
|
+
else if (a.startsWith("--log-format="))
|
|
11718
|
+
value = a.slice("--log-format=".length);
|
|
11719
|
+
else
|
|
11720
|
+
rest.push(a);
|
|
11721
|
+
}
|
|
11722
|
+
value ??= process.env.EPD_LOG_FORMAT;
|
|
11723
|
+
if (value === undefined)
|
|
11724
|
+
return rest;
|
|
11725
|
+
if (value !== "json" && value !== "pretty") {
|
|
11726
|
+
console.error(`--log-format must be "pretty" or "json", got "${value}"`);
|
|
11727
|
+
process.exit(2);
|
|
11728
|
+
}
|
|
11729
|
+
setLogFormat(value);
|
|
11730
|
+
return rest;
|
|
11731
|
+
}
|
|
11732
|
+
function finish(ok, code, msg, hint) {
|
|
11733
|
+
log.result(ok, code, msg, hint);
|
|
11734
|
+
const file = runLogPath();
|
|
11735
|
+
if (!ok && file && logFormat() === "pretty")
|
|
11736
|
+
console.error(c.gray(`
|
|
11737
|
+
Full log: ${file}`));
|
|
11738
|
+
closeRunLog();
|
|
11739
|
+
}
|
|
11740
|
+
var interrupted = false;
|
|
11741
|
+
for (const [signal, n] of [["SIGINT", 2], ["SIGTERM", 15], ["SIGHUP", 1]]) {
|
|
11742
|
+
process.on(signal, () => {
|
|
11743
|
+
if (interrupted)
|
|
11744
|
+
process.exit(128 + n);
|
|
11745
|
+
interrupted = true;
|
|
11746
|
+
log.error(`received ${signal}, cleaning up (send again to force quit)`);
|
|
11747
|
+
runInterruptHandlers().finally(() => {
|
|
11748
|
+
finish(false, 128 + n, `interrupted by ${signal}`, "The deploy may be partially applied. Run `epd status` to check, then deploy again.");
|
|
11749
|
+
process.exit(128 + n);
|
|
11750
|
+
});
|
|
11751
|
+
});
|
|
11752
|
+
}
|
|
11753
|
+
var argv = preParseLogFormat(process.argv.slice(2));
|
|
10443
11754
|
try {
|
|
10444
|
-
|
|
11755
|
+
const code = await main(argv);
|
|
11756
|
+
process.exitCode = code;
|
|
11757
|
+
finish(code === 0, code, code === 0 ? "ok" : "failed");
|
|
10445
11758
|
} catch (error) {
|
|
10446
11759
|
if (error instanceof EpdError) {
|
|
10447
|
-
log.error(
|
|
10448
|
-
if (error.hint)
|
|
10449
|
-
console.error(`
|
|
10450
|
-
${c.gray(redact(error.hint))}`);
|
|
11760
|
+
log.error(error.message, error.hint);
|
|
10451
11761
|
} else {
|
|
10452
11762
|
log.error(error instanceof Error ? error.message : String(error));
|
|
10453
|
-
if (
|
|
10454
|
-
|
|
11763
|
+
if (error instanceof Error && error.stack)
|
|
11764
|
+
log.debug(error.stack);
|
|
10455
11765
|
}
|
|
10456
11766
|
process.exitCode = 1;
|
|
11767
|
+
finish(false, 1, error instanceof Error ? error.message : String(error), error instanceof EpdError ? error.hint : undefined);
|
|
10457
11768
|
}
|