easy-devops 1.3.5 → 1.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -0
- package/dist/ui/assets/index-Bu7af-Kj.css +1 -0
- package/dist/ui/assets/index-gndgYe3K.js +532 -0
- package/dist/ui/assets/socket-Bv0wCEgi.js +65 -0
- package/dist/ui/index.html +2 -2
- package/package.json +2 -2
- package/src/cli/index.js +8 -0
- package/src/cli/managers/domain-manager.js +37 -6
- package/src/cli/managers/nginx-manager.js +14 -5
- package/src/cli/managers/node-manager.js +19 -13
- package/src/cli/managers/ssl-manager.js +89 -26
- package/src/cli/menu.js +8 -2
- package/src/cli/menus/cleanup.js +4 -2
- package/src/cli/menus/dashboard.js +22 -15
- package/src/cli/menus/hub.js +381 -0
- package/src/cli/menus/runtime.js +12 -0
- package/src/cli/menus/service.js +28 -10
- package/src/cli/menus/settings.js +46 -12
- package/src/cli/menus/uninstall.js +13 -5
- package/src/cli/menus/update.js +24 -14
- package/src/cli/ui/page.js +123 -0
- package/src/core/cert-operations.js +34 -4
- package/src/core/cert-reader.js +67 -22
- package/src/core/cert-renewal.js +65 -9
- package/src/core/cert-suggest.js +120 -0
- package/src/core/cleanup.js +221 -1
- package/src/core/cloudflare-ips.js +161 -0
- package/src/core/daemon/ipc.js +1 -1
- package/src/core/daemon/lock.js +296 -9
- package/src/core/dashboardProcess.js +134 -6
- package/src/core/deploy/apps.js +36 -62
- package/src/core/deploy/deployKey.js +331 -0
- package/src/core/deploy/domainLink.js +280 -23
- package/src/core/deploy/engine.js +382 -63
- package/src/core/deploy/ezfile.js +496 -29
- package/src/core/deploy/githubApi.js +100 -13
- package/src/core/deploy/hubCommands.js +158 -18
- package/src/core/deploy/status.js +28 -1
- package/src/core/domains-db.js +1 -0
- package/src/core/hub/agent.js +238 -32
- package/src/core/hub/deployProgress.js +411 -0
- package/src/core/hubConnect.js +205 -0
- package/src/core/hubPermissions.js +48 -10
- package/src/core/jobs/bus.js +1 -1
- package/src/core/jobs/owner.js +268 -6
- package/src/core/nginx-conf-generator.js +124 -19
- package/src/core/notifications/claim.js +26 -3
- package/src/core/permissions.js +277 -59
- package/src/core/platform.js +48 -2
- package/src/core/runner.js +96 -40
- package/src/core/ssl/preflight.js +548 -0
- package/src/core/ssl/progress.js +196 -0
- package/src/core/ssl-issuer.js +502 -148
- package/src/core/validators.js +24 -0
- package/src/dashboard/controllers/authController.js +12 -5
- package/src/dashboard/controllers/deploymentsController.js +76 -11
- package/src/dashboard/controllers/domainsController.js +35 -1
- package/src/dashboard/controllers/hubController.js +4 -3
- package/src/dashboard/controllers/settingsController.js +73 -68
- package/src/dashboard/controllers/sslController.js +135 -15
- package/src/dashboard/public/js/app.js +42 -7
- package/src/dashboard/routes/deployments.js +2 -0
- package/src/dashboard/routes/domains.js +1 -0
- package/src/dashboard/server.js +73 -8
- package/src/dashboard/socketManager.js +19 -25
- package/src/dashboard/views/partials/settings-panel.ejs +29 -10
- package/dist/ui/assets/index-BUpPxWmp.css +0 -1
- package/dist/ui/assets/index-DD0JjK0Q.js +0 -475
- package/dist/ui/assets/socket-4tfdap-e.js +0 -65
|
@@ -0,0 +1,411 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* core/hub/deployProgress.js
|
|
3
|
+
*
|
|
4
|
+
* Live deployment progress for the Hub, read from the files the engine already
|
|
5
|
+
* writes.
|
|
6
|
+
*
|
|
7
|
+
* A deployment can be started by this process (the Hub), by an open dashboard
|
|
8
|
+
* in another process, by `ezz daemon`, or by a CI hook. The in-process job bus
|
|
9
|
+
* therefore cannot be the source: two of those run somewhere else. What every
|
|
10
|
+
* one of them leaves behind is the same pair of files —
|
|
11
|
+
*
|
|
12
|
+
* deploy/<app>/deploy.lock who is deploying, and which run
|
|
13
|
+
* deploy/<app>/runs/<id>.json the run record, rewritten as steps change
|
|
14
|
+
* deploy/<app>/logs/<id>.log the run output, appended by the engine
|
|
15
|
+
*
|
|
16
|
+
* so the agent watches those with cheap fs reads. It never spawns a process,
|
|
17
|
+
* never reads the deploy key, and never sends a run's log unless the Hub has
|
|
18
|
+
* `deploy.logs`.
|
|
19
|
+
*
|
|
20
|
+
* Detection runs every two seconds because a lock file appearing is the only
|
|
21
|
+
* cross-process "a deployment started" signal there is. Once a run is found it
|
|
22
|
+
* is polled every second, and the log is read from the last byte offset, so a
|
|
23
|
+
* long build is not re-sent line after line. Only whole lines are emitted; a
|
|
24
|
+
* partial last line waits for its newline.
|
|
25
|
+
*/
|
|
26
|
+
|
|
27
|
+
import fs from 'fs';
|
|
28
|
+
|
|
29
|
+
import { getDataDir } from '../platform.js';
|
|
30
|
+
import { listApps } from '../deploy/apps.js';
|
|
31
|
+
import { logFile, lockHolder, listRuns, readRun } from '../deploy/store.js';
|
|
32
|
+
import { RUN_STATUS, redactSecrets } from '../deploy/engine.js';
|
|
33
|
+
import { getHubPermissions } from '../hubLink.js';
|
|
34
|
+
|
|
35
|
+
/** How often apps and their locks are scanned for a new run. */
|
|
36
|
+
export const DETECT_INTERVAL_MS = 2_000;
|
|
37
|
+
/** How often a run already under way is read. */
|
|
38
|
+
export const POLL_INTERVAL_MS = 1_000;
|
|
39
|
+
/** At most one `deploy:progress` per run per second. */
|
|
40
|
+
export const EMIT_INTERVAL_MS = 1_000;
|
|
41
|
+
|
|
42
|
+
/** Limits of one event's `lines` array. */
|
|
43
|
+
export const MAX_LINES = 200;
|
|
44
|
+
export const MAX_LINE_CHARS = 2_000;
|
|
45
|
+
export const MAX_LINES_BYTES = 32 * 1024;
|
|
46
|
+
|
|
47
|
+
/** A deploy key must never travel, not even as part of a log line. */
|
|
48
|
+
const PRIVATE_KEY_LINE = /PRIVATE KEY-----/;
|
|
49
|
+
/** The edges of a PEM private key block: everything between them is the key itself. */
|
|
50
|
+
const KEY_BLOCK_BEGIN = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----/;
|
|
51
|
+
const KEY_BLOCK_END = /-----END [A-Z0-9 ]*PRIVATE KEY-----/;
|
|
52
|
+
|
|
53
|
+
const RUNNING = RUN_STATUS.RUNNING;
|
|
54
|
+
|
|
55
|
+
/**
|
|
56
|
+
* What the run record says about the current step.
|
|
57
|
+
*
|
|
58
|
+
* The record has a single real field for this — `step` — not a `steps` array.
|
|
59
|
+
* The event's array shape is kept for the Hub, but it is built from that field
|
|
60
|
+
* only, so nothing here can disagree with the record the dashboard shows.
|
|
61
|
+
*
|
|
62
|
+
* @param {Object|null} run
|
|
63
|
+
* @returns {Array<{ name: string, status: string }>}
|
|
64
|
+
*/
|
|
65
|
+
export function stepsFromRun(run) {
|
|
66
|
+
if (!run || typeof run.step !== 'string' || run.step === '') return [];
|
|
67
|
+
const status = typeof run.status === 'string' ? run.status : RUNNING;
|
|
68
|
+
return [{ name: run.step, status }];
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Applies the two rules a log line must pass before it can leave this machine:
|
|
73
|
+
* drop anything that looks like a private key, and redact the app's own secret
|
|
74
|
+
* values. The length cap is applied after redaction, so a long secret cannot
|
|
75
|
+
* make the cap hide the `***` that replaced it.
|
|
76
|
+
*
|
|
77
|
+
* @param {string} line
|
|
78
|
+
* @param {Object|null} app
|
|
79
|
+
* @returns {string|null} null when the line must be dropped entirely
|
|
80
|
+
*/
|
|
81
|
+
export function safeLogLine(line, app) {
|
|
82
|
+
if (PRIVATE_KEY_LINE.test(line)) return null;
|
|
83
|
+
const redacted = redactSecrets(line, app?.env ?? {}, app?.auth?.token ?? null);
|
|
84
|
+
return redacted.length > MAX_LINE_CHARS ? redacted.slice(0, MAX_LINE_CHARS) : redacted;
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
/**
|
|
88
|
+
* The same rules for a whole log text (the Hub's `run` action): redaction
|
|
89
|
+
* per line, and every PEM private key block dropped from BEGIN to END.
|
|
90
|
+
*
|
|
91
|
+
* @param {string} text
|
|
92
|
+
* @param {Object|null} app
|
|
93
|
+
* @returns {string}
|
|
94
|
+
*/
|
|
95
|
+
export function safeLogText(text, app) {
|
|
96
|
+
const out = [];
|
|
97
|
+
let inKeyBlock = false;
|
|
98
|
+
for (const line of String(text ?? '').split('\n')) {
|
|
99
|
+
if (inKeyBlock) {
|
|
100
|
+
if (KEY_BLOCK_END.test(line)) inKeyBlock = false;
|
|
101
|
+
continue;
|
|
102
|
+
}
|
|
103
|
+
if (KEY_BLOCK_BEGIN.test(line) && !KEY_BLOCK_END.test(line)) {
|
|
104
|
+
inKeyBlock = true;
|
|
105
|
+
continue;
|
|
106
|
+
}
|
|
107
|
+
const safeLine = safeLogLine(line, app);
|
|
108
|
+
if (safeLine !== null) out.push(safeLine);
|
|
109
|
+
}
|
|
110
|
+
return out.join('\n');
|
|
111
|
+
}
|
|
112
|
+
|
|
113
|
+
/**
|
|
114
|
+
* Takes the newest lines that fit in one event.
|
|
115
|
+
*
|
|
116
|
+
* When more arrived than fit, the newest are kept and `skipped` says how many
|
|
117
|
+
* of the oldest were dropped. Sending the newest matters: a build's last lines
|
|
118
|
+
* are the ones that explain where it stopped.
|
|
119
|
+
*
|
|
120
|
+
* @param {string[]} lines
|
|
121
|
+
* @returns {{ lines: string[], skipped: number }}
|
|
122
|
+
*/
|
|
123
|
+
export function batchLines(lines) {
|
|
124
|
+
const selected = [];
|
|
125
|
+
let bytes = 0;
|
|
126
|
+
|
|
127
|
+
for (let i = lines.length - 1; i >= 0; i--) {
|
|
128
|
+
if (selected.length >= MAX_LINES) break;
|
|
129
|
+
const line = lines[i].length > MAX_LINE_CHARS ? lines[i].slice(0, MAX_LINE_CHARS) : lines[i];
|
|
130
|
+
// Measure what the Hub will actually receive: JSON escaping can double a
|
|
131
|
+
// line of quotes or backslashes, and that is part of the payload budget.
|
|
132
|
+
const size = Buffer.byteLength(JSON.stringify(line), 'utf8') + 1; // + the comma
|
|
133
|
+
if (selected.length > 0 && bytes + size > MAX_LINES_BYTES) break;
|
|
134
|
+
selected.push(line);
|
|
135
|
+
bytes += size;
|
|
136
|
+
}
|
|
137
|
+
|
|
138
|
+
selected.reverse();
|
|
139
|
+
return { lines: selected, skipped: lines.length - selected.length };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
/**
|
|
143
|
+
* Creates one poller. Exported for tests; the agent uses the singleton below.
|
|
144
|
+
*
|
|
145
|
+
* @param {Object} options
|
|
146
|
+
* @param {(event: string, payload: Object) => void} options.emit
|
|
147
|
+
* @param {() => void} [options.onAppsChanged] Send a fresh deploy:apps
|
|
148
|
+
* @param {string} [options.dataDir]
|
|
149
|
+
* @param {number} [options.detectMs]
|
|
150
|
+
* @param {number} [options.pollMs]
|
|
151
|
+
* @param {number} [options.emitMs]
|
|
152
|
+
* @param {Object} [options.deps] Injected store/app functions (tests only)
|
|
153
|
+
*/
|
|
154
|
+
export function createDeployProgress({
|
|
155
|
+
emit,
|
|
156
|
+
onAppsChanged = () => {},
|
|
157
|
+
dataDir = getDataDir(),
|
|
158
|
+
detectMs = DETECT_INTERVAL_MS,
|
|
159
|
+
pollMs = POLL_INTERVAL_MS,
|
|
160
|
+
emitMs = EMIT_INTERVAL_MS,
|
|
161
|
+
deps = {},
|
|
162
|
+
} = {}) {
|
|
163
|
+
if (typeof emit !== 'function') throw new TypeError('deployProgress: emit must be a function');
|
|
164
|
+
|
|
165
|
+
const listAppsFn = deps.listApps ?? listApps;
|
|
166
|
+
const lockHolderFn = deps.lockHolder ?? lockHolder;
|
|
167
|
+
const listRunsFn = deps.listRuns ?? listRuns;
|
|
168
|
+
const readRunFn = deps.readRun ?? readRun;
|
|
169
|
+
const logFileFn = deps.logFile ?? logFile;
|
|
170
|
+
const getPermissionsFn = deps.getPermissions ?? getHubPermissions;
|
|
171
|
+
const nowFn = deps.now ?? (() => Date.now());
|
|
172
|
+
|
|
173
|
+
/** runId → per-run cursor state */
|
|
174
|
+
const active = new Map();
|
|
175
|
+
/** Runs already watched, so an interrupted run is not picked up twice. */
|
|
176
|
+
const seen = new Set();
|
|
177
|
+
|
|
178
|
+
let detectTimer = null;
|
|
179
|
+
let pollTimer = null;
|
|
180
|
+
let stopped = true;
|
|
181
|
+
|
|
182
|
+
const safe = (fn, fallback = null) => {
|
|
183
|
+
try { return fn(); } catch { return fallback; }
|
|
184
|
+
};
|
|
185
|
+
|
|
186
|
+
function startRun(app, runId) {
|
|
187
|
+
if (stopped || seen.has(runId) || active.has(runId)) return;
|
|
188
|
+
seen.add(runId);
|
|
189
|
+
|
|
190
|
+
const state = {
|
|
191
|
+
appId: app.id,
|
|
192
|
+
app,
|
|
193
|
+
runId,
|
|
194
|
+
offset: 0,
|
|
195
|
+
partial: '',
|
|
196
|
+
inKeyBlock: false,
|
|
197
|
+
pending: [],
|
|
198
|
+
lastEmitAt: 0,
|
|
199
|
+
lastFingerprint: null,
|
|
200
|
+
};
|
|
201
|
+
active.set(runId, state);
|
|
202
|
+
|
|
203
|
+
try { onAppsChanged(); } catch { /* the list push is not the poller's job */ }
|
|
204
|
+
poll(state); // do not wait a second for the first sign of life
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function detect() {
|
|
208
|
+
if (stopped) return;
|
|
209
|
+
const apps = safe(() => listAppsFn()) ?? [];
|
|
210
|
+
if (!Array.isArray(apps)) return;
|
|
211
|
+
|
|
212
|
+
for (const app of apps) {
|
|
213
|
+
const appId = app?.id;
|
|
214
|
+
if (typeof appId !== 'string' || appId === '') continue;
|
|
215
|
+
|
|
216
|
+
// A lock is the strongest signal. The newest run record is the fallback
|
|
217
|
+
// only when no lock is held at all — a lock with no runId belongs to
|
|
218
|
+
// another operation (a move or a delete), not to a deployment.
|
|
219
|
+
const holder = safe(() => lockHolderFn(appId, dataDir));
|
|
220
|
+
let runId = null;
|
|
221
|
+
if (holder) {
|
|
222
|
+
if (typeof holder.runId === 'string') runId = holder.runId;
|
|
223
|
+
} else {
|
|
224
|
+
const newest = safe(() => listRunsFn(appId, { limit: 1, dataDir }))?.[0];
|
|
225
|
+
if (newest?.status === RUNNING && typeof newest.id === 'string') runId = newest.id;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
if (typeof runId !== 'string' || runId === '' || seen.has(runId)) continue;
|
|
229
|
+
startRun(app, runId);
|
|
230
|
+
}
|
|
231
|
+
}
|
|
232
|
+
|
|
233
|
+
/**
|
|
234
|
+
* Reads bytes added since the last read.
|
|
235
|
+
*
|
|
236
|
+
* Three cases that would otherwise corrupt the stream: the file does not
|
|
237
|
+
* exist yet (nothing to read), it was truncated while a run was live (start
|
|
238
|
+
* again from zero), and the last chunk ends mid-line (hold the fragment until
|
|
239
|
+
* its newline arrives).
|
|
240
|
+
*
|
|
241
|
+
* @returns {string[]} Whole lines, without their line endings
|
|
242
|
+
*/
|
|
243
|
+
function readNewLines(state) {
|
|
244
|
+
let file;
|
|
245
|
+
try { file = logFileFn(state.appId, state.runId, dataDir); } catch { return []; }
|
|
246
|
+
|
|
247
|
+
let size;
|
|
248
|
+
try { size = fs.statSync(file).size; } catch { return []; }
|
|
249
|
+
|
|
250
|
+
if (size < state.offset) {
|
|
251
|
+
state.offset = 0;
|
|
252
|
+
state.partial = '';
|
|
253
|
+
}
|
|
254
|
+
if (size === state.offset) return [];
|
|
255
|
+
|
|
256
|
+
const length = size - state.offset;
|
|
257
|
+
const buffer = Buffer.alloc(length);
|
|
258
|
+
let fd;
|
|
259
|
+
let bytesRead = 0;
|
|
260
|
+
try {
|
|
261
|
+
fd = fs.openSync(file, 'r');
|
|
262
|
+
bytesRead = fs.readSync(fd, buffer, 0, length, state.offset);
|
|
263
|
+
} catch {
|
|
264
|
+
return [];
|
|
265
|
+
} finally {
|
|
266
|
+
if (fd !== undefined) { try { fs.closeSync(fd); } catch { /* ignore */ } }
|
|
267
|
+
}
|
|
268
|
+
|
|
269
|
+
state.offset += bytesRead;
|
|
270
|
+
const text = state.partial + buffer.subarray(0, bytesRead).toString('utf8');
|
|
271
|
+
const parts = text.split('\n');
|
|
272
|
+
state.partial = parts.pop() ?? '';
|
|
273
|
+
|
|
274
|
+
return parts.map((line) => (line.endsWith('\r') ? line.slice(0, -1) : line));
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
function emitProgress(state, { status, steps, done, now }) {
|
|
278
|
+
const pending = state.pending;
|
|
279
|
+
state.pending = [];
|
|
280
|
+
|
|
281
|
+
let lines = [];
|
|
282
|
+
let skipped = 0;
|
|
283
|
+
const permissions = safe(() => getPermissionsFn(), {}) ?? {};
|
|
284
|
+
if (permissions['deploy.logs'] === true) {
|
|
285
|
+
({ lines, skipped } = batchLines(pending));
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const payload = {
|
|
289
|
+
appId: state.appId,
|
|
290
|
+
runId: state.runId,
|
|
291
|
+
status,
|
|
292
|
+
steps,
|
|
293
|
+
lines,
|
|
294
|
+
done,
|
|
295
|
+
at: new Date(now).toISOString(),
|
|
296
|
+
};
|
|
297
|
+
if (skipped > 0) payload.skipped = skipped;
|
|
298
|
+
|
|
299
|
+
try { emit('deploy:progress', payload); } catch { /* a closed socket is not a poller error */ }
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
function finish(state) {
|
|
303
|
+
if (active.get(state.runId) !== state) return;
|
|
304
|
+
active.delete(state.runId);
|
|
305
|
+
try { onAppsChanged(); } catch { /* non-fatal */ }
|
|
306
|
+
}
|
|
307
|
+
|
|
308
|
+
function poll(state) {
|
|
309
|
+
if (stopped || active.get(state.runId) !== state) return;
|
|
310
|
+
|
|
311
|
+
const run = safe(() => readRunFn(state.appId, state.runId, dataDir));
|
|
312
|
+
const holder = safe(() => lockHolderFn(state.appId, dataDir));
|
|
313
|
+
const lockHeld = Boolean(holder && holder.runId === state.runId);
|
|
314
|
+
|
|
315
|
+
if (!run) {
|
|
316
|
+
// The lock is taken before the record is written, so a missing record
|
|
317
|
+
// while the lock is ours is just "not yet". Otherwise this run is over
|
|
318
|
+
// without a record to report.
|
|
319
|
+
if (!lockHeld) finish(state);
|
|
320
|
+
return;
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
const app = state.app;
|
|
324
|
+
for (const line of readNewLines(state)) {
|
|
325
|
+
// Dropping only the BEGIN/END lines would still send the base64 between
|
|
326
|
+
// them. A block that never ends drops the rest of the run's log.
|
|
327
|
+
if (state.inKeyBlock) {
|
|
328
|
+
if (KEY_BLOCK_END.test(line)) state.inKeyBlock = false;
|
|
329
|
+
continue;
|
|
330
|
+
}
|
|
331
|
+
if (KEY_BLOCK_BEGIN.test(line) && !KEY_BLOCK_END.test(line)) {
|
|
332
|
+
state.inKeyBlock = true;
|
|
333
|
+
continue;
|
|
334
|
+
}
|
|
335
|
+
const safeLine = safeLogLine(line, app);
|
|
336
|
+
if (safeLine !== null) state.pending.push(safeLine);
|
|
337
|
+
}
|
|
338
|
+
|
|
339
|
+
const status = typeof run.status === 'string' ? run.status : RUNNING;
|
|
340
|
+
const steps = stepsFromRun(run);
|
|
341
|
+
const done = status !== RUNNING || !lockHeld;
|
|
342
|
+
const fingerprint = `${status}|${done}|${steps.map((s) => `${s.name}:${s.status}`).join(',')}`;
|
|
343
|
+
const now = nowFn();
|
|
344
|
+
|
|
345
|
+
const changed = done || state.pending.length > 0 || fingerprint !== state.lastFingerprint;
|
|
346
|
+
if (changed && (done || now - state.lastEmitAt >= emitMs)) {
|
|
347
|
+
emitProgress(state, { status, steps, done, now });
|
|
348
|
+
state.lastEmitAt = now;
|
|
349
|
+
state.lastFingerprint = fingerprint;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
if (done) finish(state);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
return {
|
|
356
|
+
start() {
|
|
357
|
+
if (!stopped) return this;
|
|
358
|
+
stopped = false;
|
|
359
|
+
detect();
|
|
360
|
+
detectTimer = setInterval(detect, detectMs);
|
|
361
|
+
pollTimer = setInterval(() => {
|
|
362
|
+
for (const state of [...active.values()]) poll(state);
|
|
363
|
+
}, pollMs);
|
|
364
|
+
detectTimer.unref?.();
|
|
365
|
+
pollTimer.unref?.();
|
|
366
|
+
return this;
|
|
367
|
+
},
|
|
368
|
+
|
|
369
|
+
stop() {
|
|
370
|
+
stopped = true;
|
|
371
|
+
if (detectTimer) { clearInterval(detectTimer); detectTimer = null; }
|
|
372
|
+
if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
|
|
373
|
+
active.clear();
|
|
374
|
+
},
|
|
375
|
+
|
|
376
|
+
isRunning() {
|
|
377
|
+
return !stopped;
|
|
378
|
+
},
|
|
379
|
+
|
|
380
|
+
activeRunIds() {
|
|
381
|
+
return [...active.keys()];
|
|
382
|
+
},
|
|
383
|
+
};
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
// ─── The agent's singleton ───────────────────────────────────────────────────
|
|
387
|
+
|
|
388
|
+
let singleton = null;
|
|
389
|
+
|
|
390
|
+
/**
|
|
391
|
+
* Starts progress observation for the current agent socket. Idempotent: a
|
|
392
|
+
* reconnect replaces the old poller rather than leaving two reading one log.
|
|
393
|
+
*/
|
|
394
|
+
export function startDeployProgress(options) {
|
|
395
|
+
stopDeployProgress();
|
|
396
|
+
singleton = createDeployProgress(options);
|
|
397
|
+
singleton.start();
|
|
398
|
+
return singleton;
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
/** Stops observation and forgets every cursor. Called with the socket. */
|
|
402
|
+
export function stopDeployProgress() {
|
|
403
|
+
if (!singleton) return;
|
|
404
|
+
singleton.stop();
|
|
405
|
+
singleton = null;
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
/** @returns {boolean} */
|
|
409
|
+
export function isDeployProgressRunning() {
|
|
410
|
+
return singleton?.isRunning() === true;
|
|
411
|
+
}
|
|
@@ -0,0 +1,205 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* core/hubConnect.js — turns what the operator typed after `ezz hub connect`
|
|
3
|
+
* into a connection string, without ever printing it.
|
|
4
|
+
*
|
|
5
|
+
* Two inputs are accepted:
|
|
6
|
+
* - a one-time link from the Hub, https://<hub>/api/v1/connect/cli/<token>,
|
|
7
|
+
* fetched exactly once (the Hub deletes it on the first successful fetch);
|
|
8
|
+
* - a raw `ezops://…` connection string, as pasted into the dashboard.
|
|
9
|
+
*
|
|
10
|
+
* The link's path IS the credential, so it is treated like a password here:
|
|
11
|
+
* https only (plain http only for localhost, where there is no network to
|
|
12
|
+
* cross), redirects are refused rather than followed (a redirect would carry
|
|
13
|
+
* the token to wherever it points), a timeout bounds the request, and no
|
|
14
|
+
* message this module produces contains the token or the connection string.
|
|
15
|
+
*
|
|
16
|
+
* Nothing here persists anything or touches the database: the caller saves
|
|
17
|
+
* the result through core/hubLink.js, which is what tells a running daemon.
|
|
18
|
+
*/
|
|
19
|
+
|
|
20
|
+
import { parseConnectionString } from './hubLink.js';
|
|
21
|
+
|
|
22
|
+
export const CONNECT_TIMEOUT_MS = 15_000;
|
|
23
|
+
/** A real answer is ~200 bytes; anything far larger is not the Hub. */
|
|
24
|
+
const MAX_BODY_BYTES = 16 * 1024;
|
|
25
|
+
|
|
26
|
+
const LINK_PATH = /^\/api\/v1\/connect\/cli\/([A-Za-z0-9_-]{43})$/;
|
|
27
|
+
const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]', '::1']);
|
|
28
|
+
|
|
29
|
+
/** Failure reasons the CLI turns into a sentence; stable for tests. */
|
|
30
|
+
export const CONNECT_ERRORS = Object.freeze({
|
|
31
|
+
INVALID_INPUT: 'invalid_input',
|
|
32
|
+
INSECURE: 'insecure',
|
|
33
|
+
EXPIRED: 'expired',
|
|
34
|
+
USED: 'used',
|
|
35
|
+
REPLACED: 'replaced',
|
|
36
|
+
REVOKED: 'revoked',
|
|
37
|
+
UNKNOWN_LINK: 'unknown_link',
|
|
38
|
+
RATE_LIMITED: 'rate_limited',
|
|
39
|
+
UNREACHABLE: 'unreachable',
|
|
40
|
+
TIMEOUT: 'timeout',
|
|
41
|
+
REJECTED: 'rejected',
|
|
42
|
+
});
|
|
43
|
+
|
|
44
|
+
const MESSAGES = {
|
|
45
|
+
invalid_input:
|
|
46
|
+
'That is neither a Hub pairing link nor an ezops:// connection string. ' +
|
|
47
|
+
'Copy the full `ezz hub connect …` command from the Hub\'s "From the CLI" pairing option.',
|
|
48
|
+
insecure:
|
|
49
|
+
'The pairing link must use https (plain http is accepted only for localhost). ' +
|
|
50
|
+
'Set PUBLIC_HUB_URL on the Hub to its https address and create a new link.',
|
|
51
|
+
expired: 'This pairing link has expired (links last 5 minutes). Create a new one in the Hub and run the new command.',
|
|
52
|
+
used: 'This pairing link was already used. A link works once — create a new one in the Hub.',
|
|
53
|
+
replaced: 'A newer pairing link was created for this server, which cancels this one. Use the newest link.',
|
|
54
|
+
revoked: 'This pairing link was cancelled on the Hub (the server was deleted or its secret changed). Create a new link.',
|
|
55
|
+
unknown_link: 'The Hub does not recognise this pairing link. Check it was copied completely, or create a new one.',
|
|
56
|
+
rate_limited: 'Too many pairing attempts from this address. Wait a few minutes and try again.',
|
|
57
|
+
unreachable: 'Could not reach the Hub. Check the server can open an https connection to it, then try again.',
|
|
58
|
+
timeout: 'The Hub did not answer in time. Check the server can reach it, then try again.',
|
|
59
|
+
rejected: 'The Hub refused the request. Create a new pairing link and try again.',
|
|
60
|
+
};
|
|
61
|
+
|
|
62
|
+
function fail(code, extra = {}) {
|
|
63
|
+
return { ok: false, code, error: MESSAGES[code], ...extra };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
/**
|
|
67
|
+
* Classifies the operator's input. Never echoes it back in an error.
|
|
68
|
+
*
|
|
69
|
+
* @param {string} input
|
|
70
|
+
* @returns {{ ok: true, kind: 'link', url: string }
|
|
71
|
+
* | { ok: true, kind: 'string', connectionString: string }
|
|
72
|
+
* | { ok: false, code: string, error: string }}
|
|
73
|
+
*/
|
|
74
|
+
export function parseConnectTarget(input) {
|
|
75
|
+
const raw = String(input ?? '').trim();
|
|
76
|
+
if (!raw) return fail(CONNECT_ERRORS.INVALID_INPUT);
|
|
77
|
+
|
|
78
|
+
if (raw.toLowerCase().startsWith('ezops://')) {
|
|
79
|
+
const parsed = parseConnectionString(raw);
|
|
80
|
+
// parseConnectionString's errors describe shape only, never the value.
|
|
81
|
+
return parsed.ok
|
|
82
|
+
? { ok: true, kind: 'string', connectionString: raw }
|
|
83
|
+
: { ok: false, code: CONNECT_ERRORS.INVALID_INPUT, error: parsed.error };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
let url;
|
|
87
|
+
try {
|
|
88
|
+
url = new URL(raw);
|
|
89
|
+
} catch {
|
|
90
|
+
return fail(CONNECT_ERRORS.INVALID_INPUT);
|
|
91
|
+
}
|
|
92
|
+
if (url.username || url.password || url.search || url.hash) return fail(CONNECT_ERRORS.INVALID_INPUT);
|
|
93
|
+
if (!LINK_PATH.test(url.pathname.replace(/\/+$/, ''))) return fail(CONNECT_ERRORS.INVALID_INPUT);
|
|
94
|
+
|
|
95
|
+
if (url.protocol === 'http:') {
|
|
96
|
+
if (!LOOPBACK_HOSTS.has(url.hostname)) return fail(CONNECT_ERRORS.INSECURE);
|
|
97
|
+
} else if (url.protocol !== 'https:') {
|
|
98
|
+
return fail(CONNECT_ERRORS.INVALID_INPUT);
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
url.pathname = url.pathname.replace(/\/+$/, '');
|
|
102
|
+
return { ok: true, kind: 'link', url: url.toString() };
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
/** The Hub's origin for display, e.g. "https://hub.example.com" — no token. */
|
|
106
|
+
export function linkOrigin(linkUrl) {
|
|
107
|
+
try {
|
|
108
|
+
return new URL(linkUrl).origin;
|
|
109
|
+
} catch {
|
|
110
|
+
return null;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
/**
|
|
115
|
+
* Fetches a one-time link once.
|
|
116
|
+
*
|
|
117
|
+
* @param {string} linkUrl a URL accepted by parseConnectTarget()
|
|
118
|
+
* @param {{ fetch?: typeof fetch, timeoutMs?: number }} [deps]
|
|
119
|
+
* @returns {Promise<{ ok: true, connectionString: string }
|
|
120
|
+
* | { ok: false, code: string, error: string, retryAfterSeconds?: number }>}
|
|
121
|
+
*/
|
|
122
|
+
export async function fetchConnectionString(linkUrl, deps = {}) {
|
|
123
|
+
const target = parseConnectTarget(linkUrl);
|
|
124
|
+
if (!target.ok) return target;
|
|
125
|
+
if (target.kind !== 'link') return fail(CONNECT_ERRORS.INVALID_INPUT);
|
|
126
|
+
|
|
127
|
+
const doFetch = deps.fetch ?? globalThis.fetch;
|
|
128
|
+
const timeoutMs = deps.timeoutMs ?? CONNECT_TIMEOUT_MS;
|
|
129
|
+
|
|
130
|
+
let res;
|
|
131
|
+
try {
|
|
132
|
+
res = await doFetch(target.url, {
|
|
133
|
+
method: 'GET',
|
|
134
|
+
redirect: 'error',
|
|
135
|
+
headers: { Accept: 'application/json' },
|
|
136
|
+
signal: AbortSignal.timeout(timeoutMs),
|
|
137
|
+
});
|
|
138
|
+
} catch (err) {
|
|
139
|
+
const name = err?.name ?? '';
|
|
140
|
+
if (name === 'TimeoutError' || name === 'AbortError') return fail(CONNECT_ERRORS.TIMEOUT);
|
|
141
|
+
// `fetch failed` hides the cause; neither carries the URL's token, but only
|
|
142
|
+
// the error CODE is passed on, never a message that might quote the URL.
|
|
143
|
+
const cause = typeof err?.cause?.code === 'string' ? err.cause.code : null;
|
|
144
|
+
return fail(CONNECT_ERRORS.UNREACHABLE, cause ? { cause } : {});
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
if (res.status === 200) {
|
|
148
|
+
let body;
|
|
149
|
+
try {
|
|
150
|
+
const text = await readLimited(res, MAX_BODY_BYTES);
|
|
151
|
+
body = JSON.parse(text);
|
|
152
|
+
} catch {
|
|
153
|
+
return fail(CONNECT_ERRORS.REJECTED);
|
|
154
|
+
}
|
|
155
|
+
const connectionString = typeof body?.connectionString === 'string' ? body.connectionString.trim() : '';
|
|
156
|
+
if (!parseConnectionString(connectionString).ok) return fail(CONNECT_ERRORS.REJECTED);
|
|
157
|
+
return { ok: true, connectionString };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
// Drain without reading into memory beyond the limit; the body is only a code.
|
|
161
|
+
let code = null;
|
|
162
|
+
try {
|
|
163
|
+
const text = await readLimited(res, MAX_BODY_BYTES);
|
|
164
|
+
code = JSON.parse(text)?.code ?? null;
|
|
165
|
+
} catch {
|
|
166
|
+
/* no usable body */
|
|
167
|
+
}
|
|
168
|
+
|
|
169
|
+
if (res.status === 410) {
|
|
170
|
+
if (code === 'LINK_EXPIRED') return fail(CONNECT_ERRORS.EXPIRED);
|
|
171
|
+
if (code === 'LINK_REPLACED') return fail(CONNECT_ERRORS.REPLACED);
|
|
172
|
+
if (code === 'LINK_REVOKED') return fail(CONNECT_ERRORS.REVOKED);
|
|
173
|
+
return fail(CONNECT_ERRORS.USED);
|
|
174
|
+
}
|
|
175
|
+
if (res.status === 404) return fail(CONNECT_ERRORS.UNKNOWN_LINK);
|
|
176
|
+
if (res.status === 429) {
|
|
177
|
+
const retry = Number(res.headers?.get?.('retry-after'));
|
|
178
|
+
return fail(CONNECT_ERRORS.RATE_LIMITED, Number.isFinite(retry) && retry > 0 ? { retryAfterSeconds: retry } : {});
|
|
179
|
+
}
|
|
180
|
+
if (res.status >= 500) return fail(CONNECT_ERRORS.UNREACHABLE, { status: res.status });
|
|
181
|
+
return fail(CONNECT_ERRORS.REJECTED, { status: res.status });
|
|
182
|
+
}
|
|
183
|
+
|
|
184
|
+
async function readLimited(res, limit) {
|
|
185
|
+
const declared = Number(res.headers?.get?.('content-length'));
|
|
186
|
+
if (Number.isFinite(declared) && declared > limit) throw new Error('response too large');
|
|
187
|
+
const text = await res.text();
|
|
188
|
+
if (text.length > limit) throw new Error('response too large');
|
|
189
|
+
return text;
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* Resolves the operator's input to a connection string: a raw string is used
|
|
194
|
+
* as-is, a link is fetched once.
|
|
195
|
+
*
|
|
196
|
+
* @returns {Promise<{ ok: true, connectionString: string, source: 'link'|'string' }
|
|
197
|
+
* | { ok: false, code: string, error: string }>}
|
|
198
|
+
*/
|
|
199
|
+
export async function resolveConnectInput(input, deps = {}) {
|
|
200
|
+
const target = parseConnectTarget(input);
|
|
201
|
+
if (!target.ok) return target;
|
|
202
|
+
if (target.kind === 'string') return { ok: true, connectionString: target.connectionString, source: 'string' };
|
|
203
|
+
const fetched = await fetchConnectionString(target.url, deps);
|
|
204
|
+
return fetched.ok ? { ...fetched, source: 'link' } : fetched;
|
|
205
|
+
}
|