burrow-cli 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +594 -2
- package/bin/burrow.js +200 -0
- package/examples/acme-shop.tunnel.yml +18 -0
- package/package.json +45 -4
- package/src/access.js +163 -0
- package/src/add.js +106 -0
- package/src/cloudflare.js +118 -0
- package/src/commands.js +386 -0
- package/src/completion.js +127 -0
- package/src/config-file.js +31 -0
- package/src/config.js +82 -0
- package/src/dashboard/auth.js +79 -0
- package/src/dashboard/data.js +70 -0
- package/src/dashboard/logs.js +95 -0
- package/src/dashboard/manage.js +102 -0
- package/src/dashboard/panels/README.md +50 -0
- package/src/dashboard/panels/access.js +218 -0
- package/src/dashboard/panels/alerts.js +244 -0
- package/src/dashboard/panels/backup.js +193 -0
- package/src/dashboard/panels/bulk.js +246 -0
- package/src/dashboard/panels/cleanup.js +237 -0
- package/src/dashboard/panels/doctor.js +119 -0
- package/src/dashboard/panels/health.js +146 -0
- package/src/dashboard/panels/history.js +104 -0
- package/src/dashboard/panels/hooks.js +86 -0
- package/src/dashboard/panels/live.js +153 -0
- package/src/dashboard/panels/project-form.js +463 -0
- package/src/dashboard/panels/quick-actions.js +133 -0
- package/src/dashboard/panels/sessions.js +267 -0
- package/src/dashboard/panels/shares.js +280 -0
- package/src/dashboard/panels/stats.js +165 -0
- package/src/dashboard/panels/updates.js +156 -0
- package/src/dashboard/panels/uptime.js +115 -0
- package/src/dashboard/panels.js +53 -0
- package/src/dashboard/server.js +390 -0
- package/src/dashboard/session-store.js +47 -0
- package/src/dashboard/totp.js +103 -0
- package/src/dashboard/ui.js +454 -0
- package/src/doctor.js +342 -0
- package/src/edit.js +135 -0
- package/src/health-observer.js +81 -0
- package/src/history.js +145 -0
- package/src/hooks.js +256 -0
- package/src/naming.js +38 -0
- package/src/open.js +67 -0
- package/src/pending.js +72 -0
- package/src/process.js +95 -0
- package/src/project-form.js +134 -0
- package/src/project.js +114 -0
- package/src/prune.js +99 -0
- package/src/rename-state.js +39 -0
- package/src/restart.js +35 -0
- package/src/service.js +173 -0
- package/src/share-expiry.js +55 -0
- package/src/share.js +275 -0
- package/src/shell-words.js +284 -0
- package/src/stats.js +180 -0
- package/src/transfer.js +124 -0
- package/src/update.js +254 -0
- package/src/uptime.js +91 -0
- package/src/watch.js +263 -0
- package/src/zones.js +102 -0
package/src/doctor.js
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
1
|
+
import { existsSync, statSync, readdirSync, accessSync, constants, readFileSync } from 'node:fs';
|
|
2
|
+
import { spawnSync } from 'node:child_process';
|
|
3
|
+
import { delimiter, dirname, isAbsolute, join } from 'node:path';
|
|
4
|
+
import { connect } from 'node:net';
|
|
5
|
+
import { loadConfig, stateDir } from './config.js';
|
|
6
|
+
import { Cloudflare } from './cloudflare.js';
|
|
7
|
+
import { assertDomain } from './naming.js';
|
|
8
|
+
import { findProjectFile, loadProjectFile } from './project.js';
|
|
9
|
+
import { readMeta } from './process.js';
|
|
10
|
+
import { loadHooks } from './hooks.js';
|
|
11
|
+
import { parseCommands, isAssignment } from './shell-words.js';
|
|
12
|
+
import { zoneIdFor } from './zones.js';
|
|
13
|
+
|
|
14
|
+
// Shell builtins and keywords that need no file; cd is followed so later commands are checked
|
|
15
|
+
// in the right directory.
|
|
16
|
+
const SHELL_BUILTINS = new Set(['cd', 'export', 'set', 'unset', 'test', '[', 'true', 'false', ':', '.', 'source', 'echo', 'printf',
|
|
17
|
+
'exit', 'trap', 'wait', 'read', 'shift', 'umask', 'ulimit', 'alias', 'eval', 'return', 'local', 'readonly', 'type', 'hash', 'kill', 'pwd']);
|
|
18
|
+
// Prefixes that run the command after them.
|
|
19
|
+
const WRAPPERS = new Set(['exec', 'nohup', 'command', 'time', 'env', 'nice', 'setsid']);
|
|
20
|
+
const executable = (p) => { try { accessSync(p, constants.X_OK); return statSync(p).isFile(); } catch { return false; } };
|
|
21
|
+
const onPath = (word, path) => {
|
|
22
|
+
for (const dir of path.split(delimiter)) if (dir && executable(join(dir, word))) return join(dir, word);
|
|
23
|
+
return null;
|
|
24
|
+
};
|
|
25
|
+
|
|
26
|
+
function packageScripts(dir) {
|
|
27
|
+
try { return JSON.parse(readFileSync(join(dir, 'package.json'), 'utf8')).scripts || {}; } catch { return null; }
|
|
28
|
+
}
|
|
29
|
+
|
|
30
|
+
// `npm run x`, `npm start|test|stop|restart`, `yarn [run] x`, `pnpm [run] x`: is script x in
|
|
31
|
+
// package.json? Returns a problem string or null.
|
|
32
|
+
function scriptProblem(tool, args, cwd) {
|
|
33
|
+
const rest = args.filter((a) => !a.startsWith('-'));
|
|
34
|
+
let script = null;
|
|
35
|
+
if (tool === 'npm') {
|
|
36
|
+
if (['run', 'run-script', 'rum', 'urn'].includes(rest[0])) script = rest[1];
|
|
37
|
+
else if (['start', 'test', 't', 'stop', 'restart'].includes(rest[0])) script = rest[0] === 't' ? 'test' : rest[0];
|
|
38
|
+
if (!script) return null;
|
|
39
|
+
} else {
|
|
40
|
+
const builtin = ['install', 'add', 'remove', 'i', 'exec', 'dlx', 'create', 'init', 'why', 'list', 'ls', 'outdated', 'upgrade', 'up', 'update', 'link', 'unlink', 'config', 'cache', 'store', 'audit', 'info', 'publish', 'pack'];
|
|
41
|
+
if (rest[0] === 'run') script = rest[1];
|
|
42
|
+
else if (rest[0] && !builtin.includes(rest[0])) script = rest[0];
|
|
43
|
+
if (!script) return null;
|
|
44
|
+
}
|
|
45
|
+
const scripts = packageScripts(cwd);
|
|
46
|
+
if (!scripts) return { problem: `${tool} ${rest.join(' ')}: no package.json in ${cwd}` };
|
|
47
|
+
if (script in scripts) return null;
|
|
48
|
+
// npm's default: with no start script, `npm start` runs `node server.js`.
|
|
49
|
+
if (tool === 'npm' && script === 'start' && rest[0] === 'start' && existsSync(join(cwd, 'server.js'))) {
|
|
50
|
+
return { note: `npm start: no "start" script, so npm runs "node server.js" (${join(cwd, 'server.js')})` };
|
|
51
|
+
}
|
|
52
|
+
return { problem: `${tool}: no "${script}" script in ${join(cwd, 'package.json')}` };
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// Check a hook command without running it: for every simple command (each part of a
|
|
56
|
+
// pipeline, && / || / ; list), skip VAR=value prefixes and wrappers (env, exec, nohup, …),
|
|
57
|
+
// follow `cd <dir>`, and look the command up (builtin, ./script relative to the current
|
|
58
|
+
// directory, or PATH); `npm run x` and friends also need script x in package.json.
|
|
59
|
+
// Commands inside $(…), backticks, ( … ), { …; }, if/while/until/for/case are checked too
|
|
60
|
+
// (see shell-words.js): a cd in a subshell or $(…) stays there, and a cd inside an if/loop/case
|
|
61
|
+
// body makes the directory unknown after the block. A cd in an if/elif/while/until condition is
|
|
62
|
+
// tracked: the then/do body runs where the condition succeeded, the else/elif where it failed
|
|
63
|
+
// (a failing cd changes nothing); if those differ (cd … || cd …, a cd before a ';'), the
|
|
64
|
+
// directory is unknown there. Nothing is ever executed.
|
|
65
|
+
// -> { ok, detail, problems: [...], checked: [...], unchecked: [...], notes: [...] }
|
|
66
|
+
export function checkHookCommand(run, cwd, path = process.env.PATH || '') {
|
|
67
|
+
const problems = [];
|
|
68
|
+
const checked = [];
|
|
69
|
+
const unchecked = [];
|
|
70
|
+
const notes = [];
|
|
71
|
+
// Current directory per scope (a subshell or $(…) starts in its parent's directory).
|
|
72
|
+
const dirs = new Map([['', cwd]]);
|
|
73
|
+
const cdInBlock = new Set();
|
|
74
|
+
const lastDepth = new Map(); // scope -> depth of its previous command
|
|
75
|
+
const entryDirs = new Map(); // scope -> [directory when each block depth was entered]
|
|
76
|
+
const parentOf = (s) => s.slice(0, s.lastIndexOf('/'));
|
|
77
|
+
const conds = new Map(); // `${scope}|${depth}` -> { S, F, thenUsed }: possible directories after a condition succeeded / failed
|
|
78
|
+
const single = (set) => (set.size === 1 ? [...set][0] : null);
|
|
79
|
+
const union = (...sets) => new Set(sets.flatMap((x) => [...x]));
|
|
80
|
+
for (const cmd of parseCommands(run)) {
|
|
81
|
+
const scope = cmd.scope || '';
|
|
82
|
+
if (!dirs.has(scope)) dirs.set(scope, dirs.get(parentOf(scope)) ?? null);
|
|
83
|
+
if (cmd.depth === 0 && cdInBlock.has(scope)) { cdInBlock.delete(scope); dirs.set(scope, null); }
|
|
84
|
+
const entry = entryDirs.get(scope) || [];
|
|
85
|
+
entryDirs.set(scope, entry);
|
|
86
|
+
for (let d = (lastDepth.get(scope) ?? 0) + 1; d <= cmd.depth; d++) entry[d] = dirs.get(scope);
|
|
87
|
+
lastDepth.set(scope, cmd.depth);
|
|
88
|
+
// A then/else/case-arm body starts where the block began, not where the last branch cd'd to.
|
|
89
|
+
if (cmd.branchStart && cmd.depth > 0 && entry[cmd.depth] !== undefined) dirs.set(scope, entry[cmd.depth]);
|
|
90
|
+
const ckey = `${scope}|${cmd.depth}`;
|
|
91
|
+
const prior = conds.get(ckey);
|
|
92
|
+
if (cmd.branchStart && cmd.depth > 0 && prior) {
|
|
93
|
+
const k = cmd.branchKind;
|
|
94
|
+
if ((k === 'then' || k === 'do') && !prior.thenUsed) { prior.thenUsed = true; dirs.set(scope, single(prior.S)); }
|
|
95
|
+
else if (k === 'else' || k === 'elif') dirs.set(scope, single(prior.F));
|
|
96
|
+
}
|
|
97
|
+
// A condition: track where it can leave us when it succeeds (S) and when it fails (F).
|
|
98
|
+
let rec = null;
|
|
99
|
+
let runSet = null;
|
|
100
|
+
if (cmd.cond) {
|
|
101
|
+
const pre = dirs.get(scope) ?? null;
|
|
102
|
+
if (cmd.cond === 'start' || !prior) {
|
|
103
|
+
rec = { S: new Set([pre]), F: new Set([pre]), thenUsed: false, first: true };
|
|
104
|
+
conds.set(ckey, rec);
|
|
105
|
+
runSet = new Set([pre]);
|
|
106
|
+
} else {
|
|
107
|
+
rec = prior;
|
|
108
|
+
runSet = cmd.op === '&&' ? rec.S : cmd.op === '||' ? rec.F : union(rec.S, rec.F);
|
|
109
|
+
}
|
|
110
|
+
dirs.set(scope, single(runSet));
|
|
111
|
+
}
|
|
112
|
+
let condDone = false;
|
|
113
|
+
// nextFn: how this command changes the directory (a static cd), or null.
|
|
114
|
+
const finishCond = (nextFn) => {
|
|
115
|
+
if (!rec || condDone) return;
|
|
116
|
+
condDone = true;
|
|
117
|
+
const apply = (set) => (nextFn ? new Set([...set].map(nextFn)) : set);
|
|
118
|
+
if (rec.first) { rec.first = false; rec.S = apply(runSet); rec.F = new Set(runSet); }
|
|
119
|
+
else if (cmd.op === '&&') { const S = apply(rec.S); rec.F = union(rec.F, rec.S); rec.S = S; }
|
|
120
|
+
else if (cmd.op === '||') { rec.S = union(rec.S, apply(rec.F)); }
|
|
121
|
+
else { const all = union(rec.S, rec.F); rec.S = apply(all); rec.F = all; }
|
|
122
|
+
if (nextFn) cdInBlock.add(scope);
|
|
123
|
+
};
|
|
124
|
+
let dir = dirs.get(scope);
|
|
125
|
+
const setDir = (d) => { dir = d; dirs.set(scope, d); if (cmd.depth > 0) cdInBlock.add(scope); };
|
|
126
|
+
if (cmd.unsupported) { finishCond(null); unchecked.push(cmd.unsupported); continue; }
|
|
127
|
+
let words = cmd.words.slice();
|
|
128
|
+
while (words.length && isAssignment(words[0])) words.shift();
|
|
129
|
+
while (words.length && !words[0].quoted && WRAPPERS.has(words[0].text)) {
|
|
130
|
+
const w = words.shift().text;
|
|
131
|
+
while (words.length && (words[0].text.startsWith('-') || (w === 'env' && isAssignment(words[0])))) {
|
|
132
|
+
const opt = words.shift().text;
|
|
133
|
+
if (w === 'nice' && opt === '-n') words.shift();
|
|
134
|
+
}
|
|
135
|
+
}
|
|
136
|
+
if (!words.length) { finishCond(null); continue; }
|
|
137
|
+
const [head, ...args] = words;
|
|
138
|
+
if (!(head.text === 'cd' && !head.expands)) finishCond(null);
|
|
139
|
+
if (head.expands) { unchecked.push(`${head.text} (${/[`(]/.test(head.text) ? 'command output' : 'variable'})`); continue; }
|
|
140
|
+
const name = head.text;
|
|
141
|
+
if (name === 'cd' && rec) {
|
|
142
|
+
// cd in a condition: the new directory depends on how the condition ends.
|
|
143
|
+
const target = args[0];
|
|
144
|
+
const isolated = ['|', '&'].includes(cmd.op); // a pipeline stage or background job: a subshell
|
|
145
|
+
const resolve = (d) => {
|
|
146
|
+
if (!target) return process.env.HOME || d;
|
|
147
|
+
if (target.expands || target.text === '-') return null;
|
|
148
|
+
if (isAbsolute(target.text)) return target.text;
|
|
149
|
+
return d === null ? null : join(d, target.text);
|
|
150
|
+
};
|
|
151
|
+
if (!isolated) {
|
|
152
|
+
if (!target || (!target.expands && target.text !== '-' && (isAbsolute(target.text) || dir !== null))) {
|
|
153
|
+
const next = resolve(dir);
|
|
154
|
+
if (target && dir !== null && !existsSync(next)) problems.push(`cd ${target.text}: no such directory in ${dir}`);
|
|
155
|
+
} else unchecked.push(`cd ${target.text}`);
|
|
156
|
+
}
|
|
157
|
+
finishCond(isolated ? null : resolve);
|
|
158
|
+
continue;
|
|
159
|
+
}
|
|
160
|
+
if (name === 'cd') {
|
|
161
|
+
const target = args[0];
|
|
162
|
+
if (!target) { setDir(process.env.HOME || dir); continue; }
|
|
163
|
+
if (target.expands || target.text === '-') { unchecked.push(`cd ${target.text}`); setDir(null); continue; }
|
|
164
|
+
if (dir === null && !isAbsolute(target.text)) { unchecked.push(`cd ${target.text}`); continue; }
|
|
165
|
+
const next = isAbsolute(target.text) ? target.text : join(dir, target.text);
|
|
166
|
+
if (!existsSync(next)) problems.push(`cd ${target.text}: no such directory in ${dir}`);
|
|
167
|
+
setDir(next);
|
|
168
|
+
continue;
|
|
169
|
+
}
|
|
170
|
+
if (SHELL_BUILTINS.has(name)) { checked.push(name); continue; }
|
|
171
|
+
if (name.includes('/')) {
|
|
172
|
+
if (dir === null && !isAbsolute(name)) { unchecked.push(name); continue; }
|
|
173
|
+
const p = isAbsolute(name) ? name : join(dir, name);
|
|
174
|
+
if (executable(p)) checked.push(name); else problems.push(`${name} not found or not executable in ${dir}`);
|
|
175
|
+
continue;
|
|
176
|
+
}
|
|
177
|
+
if (!onPath(name, path)) { problems.push(`${name} not found on PATH`); continue; }
|
|
178
|
+
checked.push(name);
|
|
179
|
+
if (['npm', 'yarn', 'pnpm'].includes(name) && dir !== null) {
|
|
180
|
+
const p = scriptProblem(name, args.map((a) => a.text), dir);
|
|
181
|
+
if (p?.problem) problems.push(p.problem);
|
|
182
|
+
if (p?.note) notes.push(p.note);
|
|
183
|
+
}
|
|
184
|
+
}
|
|
185
|
+
const ok = problems.length === 0;
|
|
186
|
+
const parts = ok ? [checked.length ? `found: ${[...new Set(checked)].join(', ')}` : ''] : [...problems];
|
|
187
|
+
if (notes.length) parts.push(`note: ${[...new Set(notes)].join(', ')}`);
|
|
188
|
+
if (unchecked.length) parts.push(`not checked: ${[...new Set(unchecked)].join(', ')}`);
|
|
189
|
+
return { ok, detail: parts.filter(Boolean).join('; ') || 'nothing to check', problems, checked, unchecked, notes };
|
|
190
|
+
}
|
|
191
|
+
|
|
192
|
+
// Kept for callers of the first version: the result of checkHookCommand.
|
|
193
|
+
export const hookCommandFound = (run, cwd, path) => checkHookCommand(run, cwd, path);
|
|
194
|
+
|
|
195
|
+
const MARK = { pass: '✓', warn: '!', fail: '✗', skip: '-' };
|
|
196
|
+
|
|
197
|
+
// Can we open a TCP connection to the service behind a tunnel ingress URL?
|
|
198
|
+
export function checkTarget(url, timeoutMs = 1500) {
|
|
199
|
+
if (/^(http_status:\d+|hello_world)$/.test(url)) return Promise.resolve({ ok: true, detail: 'built-in' });
|
|
200
|
+
let u;
|
|
201
|
+
try { u = new URL(url); } catch { return Promise.resolve({ ok: false, detail: 'invalid URL' }); }
|
|
202
|
+
if (u.protocol === 'unix:') {
|
|
203
|
+
const ok = existsSync(u.pathname);
|
|
204
|
+
return Promise.resolve({ ok, detail: ok ? 'socket exists' : 'socket missing' });
|
|
205
|
+
}
|
|
206
|
+
const defaults = { 'http:': 80, 'ws:': 80, 'https:': 443, 'wss:': 443, 'ssh:': 22 };
|
|
207
|
+
const port = Number(u.port || defaults[u.protocol]);
|
|
208
|
+
const host = u.hostname.replace(/^\[|\]$/g, '');
|
|
209
|
+
return new Promise((resolve) => {
|
|
210
|
+
const sock = connect({ host, port });
|
|
211
|
+
const finish = (ok, detail) => { sock.destroy(); resolve({ ok, detail }); };
|
|
212
|
+
sock.setTimeout(timeoutMs, () => finish(false, 'timed out'));
|
|
213
|
+
sock.once('connect', () => finish(true, 'reachable'));
|
|
214
|
+
sock.once('error', (e) => finish(false, e.code === 'ECONNREFUSED' ? 'connection refused' : e.code || e.message));
|
|
215
|
+
});
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function projectsToCheck(projectArg, opts) {
|
|
219
|
+
const file = opts.all ? null : findProjectFile(opts.file);
|
|
220
|
+
if (file && (!projectArg || loadProjectFile(file).project === projectArg)) return [file];
|
|
221
|
+
if (projectArg) {
|
|
222
|
+
const meta = readMeta(projectArg);
|
|
223
|
+
if (meta?.file && existsSync(meta.file)) return [meta.file];
|
|
224
|
+
throw new Error(`No tunnel.yml known for "${projectArg}". Run burrow up -f <file> once, or pass -f.`);
|
|
225
|
+
}
|
|
226
|
+
// No project given and no ./tunnel.yml: every remembered project.
|
|
227
|
+
let names = [];
|
|
228
|
+
try { names = readdirSync(stateDir()).filter((f) => f.endsWith('.json')).map((f) => f.slice(0, -5)); } catch {}
|
|
229
|
+
return [...new Set(names.map((n) => readMeta(n)?.file).filter((f) => f && existsSync(f)))];
|
|
230
|
+
}
|
|
231
|
+
|
|
232
|
+
// opts.json: print one JSON line { counts, checks: [{ section, status, label, detail, fix }] }
|
|
233
|
+
// instead of the text report (the dashboard's Doctor panel reads it). opts.all: check every
|
|
234
|
+
// remembered project and ignore ./tunnel.yml.
|
|
235
|
+
export async function doctor(projectArg, opts = {}) {
|
|
236
|
+
const counts = { pass: 0, warn: 0, fail: 0, skip: 0 };
|
|
237
|
+
const checks = [];
|
|
238
|
+
let current = '';
|
|
239
|
+
const out = opts.json ? () => {} : (...a) => console.log(...a);
|
|
240
|
+
const report = (status, label, detail = '', fix = '') => {
|
|
241
|
+
counts[status]++;
|
|
242
|
+
checks.push({ section: current, status, label, detail, ...(fix && (status === 'fail' || status === 'warn') ? { fix } : {}) });
|
|
243
|
+
out(` ${MARK[status]} ${label}${detail ? ` - ${detail}` : ''}`);
|
|
244
|
+
};
|
|
245
|
+
const section = (title) => { current = title; out(`\n${title}`); };
|
|
246
|
+
const cfg = loadConfig();
|
|
247
|
+
|
|
248
|
+
section('Config');
|
|
249
|
+
if (cfg.exists) {
|
|
250
|
+
report('pass', 'config file', cfg.path);
|
|
251
|
+
const mode = statSync(cfg.path).mode & 0o777;
|
|
252
|
+
if (mode & 0o077) report('warn', 'config permissions', `${mode.toString(8)}; run chmod 600 ${cfg.path}`, `Run: chmod 600 ${cfg.path}`);
|
|
253
|
+
else report('pass', 'config permissions', mode.toString(8));
|
|
254
|
+
} else {
|
|
255
|
+
report('fail', 'config file', `${cfg.path} missing; run burrow init`, 'Run "burrow init" on the server, then fill in the token, account ID and domain.');
|
|
256
|
+
}
|
|
257
|
+
report(cfg.token ? 'pass' : 'fail', 'CF_API_TOKEN', cfg.token ? 'set' : 'missing', 'Create an API token (Account > Cloudflare Tunnel > Edit, Zone > DNS > Edit) and set CF_API_TOKEN in the config.');
|
|
258
|
+
report(cfg.accountId ? 'pass' : 'fail', 'CF_ACCOUNT_ID', cfg.accountId ? 'set' : 'missing', 'Copy the account ID from the Cloudflare dashboard into CF_ACCOUNT_ID.');
|
|
259
|
+
try {
|
|
260
|
+
assertDomain(cfg.domain);
|
|
261
|
+
report('pass', 'BURROW_DOMAIN', cfg.domain);
|
|
262
|
+
} catch {
|
|
263
|
+
report('fail', 'BURROW_DOMAIN', cfg.domain ? `invalid: ${cfg.domain}` : 'missing', 'Set BURROW_DOMAIN to a domain (zone) on your Cloudflare account, e.g. example.dev.');
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
section('Cloudflare API');
|
|
267
|
+
if (opts.offline) {
|
|
268
|
+
report('skip', 'API checks', '--offline');
|
|
269
|
+
} else if (!cfg.token || !cfg.accountId || !cfg.domain) {
|
|
270
|
+
report('skip', 'API checks', 'config incomplete');
|
|
271
|
+
} else {
|
|
272
|
+
const cf = new Cloudflare({ token: cfg.token, accountId: cfg.accountId, zoneId: cfg.zoneId });
|
|
273
|
+
const tryCheck = async (label, fn, fix) => {
|
|
274
|
+
try { report('pass', label, await fn()); return true; } catch (e) { report('fail', label, e.message, fix); return false; }
|
|
275
|
+
};
|
|
276
|
+
await tryCheck('token', async () => {
|
|
277
|
+
const v = await cf.verifyToken();
|
|
278
|
+
if (v?.status && v.status !== 'active') throw new Error(`status ${v.status}`);
|
|
279
|
+
return `${v?.status || 'ok'}${v?.expires_on ? `, expires ${v.expires_on}` : ''}`;
|
|
280
|
+
}, 'The token is wrong, expired or disabled: create a new one and update CF_API_TOKEN.');
|
|
281
|
+
if (await tryCheck('zone', async () => `${cfg.domain} (${await cf.resolveZoneId(cfg.domain)})`,
|
|
282
|
+
`Add ${cfg.domain} to the account in CF_ACCOUNT_ID, or give the token Zone > Zone > Read for it.`)) {
|
|
283
|
+
await tryCheck('tunnel access', async () => `${(await cf.listTunnels()).length} tunnel(s) in the account`,
|
|
284
|
+
'Give the token Account > Cloudflare Tunnel > Edit.');
|
|
285
|
+
await tryCheck('DNS access', async () => `${(await cf.recordsByCommentPrefix('burrow:')).length} burrow record(s)`,
|
|
286
|
+
`Give the token Zone > DNS > Edit for ${cfg.domain}.`);
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
section('cloudflared');
|
|
291
|
+
const v = spawnSync(cfg.cloudflared, ['--version'], { encoding: 'utf8', timeout: 10000 });
|
|
292
|
+
if (v.error || v.status !== 0) report('fail', 'cloudflared', `${cfg.cloudflared} not runnable (${v.error?.code || `exit ${v.status}`})`, 'Install cloudflared (https://developers.cloudflare.com/cloudflare-one/connections/connect-networks/downloads/) or set CLOUDFLARED_BIN to its path.');
|
|
293
|
+
else report('pass', 'cloudflared', (v.stdout || v.stderr).trim().split('\n')[0]);
|
|
294
|
+
|
|
295
|
+
const files = projectsToCheck(projectArg, opts);
|
|
296
|
+
for (const file of files) {
|
|
297
|
+
let proj;
|
|
298
|
+
try { proj = loadProjectFile(file); } catch (e) {
|
|
299
|
+
section(`Project file ${file}`);
|
|
300
|
+
report('fail', 'tunnel.yml', e.message, `Fix ${file} (burrow up prints the same error).`);
|
|
301
|
+
continue;
|
|
302
|
+
}
|
|
303
|
+
section(`Project ${proj.project} (${file})`);
|
|
304
|
+
// The project's own domain: is a separate zone; the API section only checked BURROW_DOMAIN's.
|
|
305
|
+
if (proj.domain && proj.domain !== cfg.domain) {
|
|
306
|
+
if (opts.offline) report('skip', `domain ${proj.domain}`, '--offline');
|
|
307
|
+
else if (!cfg.token || !cfg.accountId) report('skip', `domain ${proj.domain}`, 'config incomplete');
|
|
308
|
+
else {
|
|
309
|
+
try {
|
|
310
|
+
const cf = new Cloudflare({ token: cfg.token, accountId: cfg.accountId });
|
|
311
|
+
report('pass', `domain ${proj.domain}`, `zone ${await zoneIdFor(cf, cfg, proj.domain, { refresh: true })}`);
|
|
312
|
+
} catch (e) {
|
|
313
|
+
report('fail', `domain ${proj.domain}`, e.message, `Add ${proj.domain} to the account in CF_ACCOUNT_ID and give the token Zone > Zone > Read and Zone > DNS > Edit for it, or remove domain: from ${file}.`);
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
let hooks = {};
|
|
318
|
+
try { hooks = loadHooks(file); } catch (e) {
|
|
319
|
+
report('fail', 'hooks', e.message, `Fix the hooks: section of ${file} (burrow up stops on the same error).`);
|
|
320
|
+
}
|
|
321
|
+
for (const [name, h] of Object.entries(hooks)) {
|
|
322
|
+
const cwd = dirname(file);
|
|
323
|
+
const r = checkHookCommand(h.run, cwd);
|
|
324
|
+
report(r.ok ? 'pass' : 'warn', `hook ${name}${h.background ? ' (background)' : ''}`, r.detail,
|
|
325
|
+
`Install the command or fix hooks.${name} in ${file}; hooks run with /bin/sh in ${cwd}.`);
|
|
326
|
+
}
|
|
327
|
+
for (const s of proj.services) {
|
|
328
|
+
for (const p of s.paths) {
|
|
329
|
+
const r = await checkTarget(p.url);
|
|
330
|
+
report(r.ok ? 'pass' : 'fail', `${s.name} ${p.path} -> ${p.url}`, r.detail, `Start the app behind ${p.url}, or fix the URL in tunnel.yml.`);
|
|
331
|
+
}
|
|
332
|
+
const r = await checkTarget(s.url);
|
|
333
|
+
report(r.ok ? 'pass' : 'fail', `${s.name} -> ${s.url}`, r.detail, `Start the app behind ${s.url}, or fix the URL in tunnel.yml.`);
|
|
334
|
+
}
|
|
335
|
+
}
|
|
336
|
+
if (!files.length) { section('Projects'); report('skip', 'local services', 'no tunnel.yml here and no remembered projects'); }
|
|
337
|
+
|
|
338
|
+
out(`\n${counts.pass} passed, ${counts.warn} warning(s), ${counts.fail} failed${counts.skip ? `, ${counts.skip} skipped` : ''}`);
|
|
339
|
+
if (opts.json) console.log(JSON.stringify({ counts, checks }));
|
|
340
|
+
if (counts.fail) process.exitCode = 1;
|
|
341
|
+
return counts;
|
|
342
|
+
}
|
package/src/edit.js
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
import { spawnSync } from 'node:child_process';
|
|
2
|
+
import { accessSync, constants, existsSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { tmpdir } from 'node:os';
|
|
4
|
+
import { basename, delimiter, join } from 'node:path';
|
|
5
|
+
import { createInterface } from 'node:readline/promises';
|
|
6
|
+
import YAML from 'yaml';
|
|
7
|
+
import { assertLabel } from './naming.js';
|
|
8
|
+
import { parseHooks } from './hooks.js';
|
|
9
|
+
import { findProjectFile, parseProject } from './project.js';
|
|
10
|
+
import { readMeta, runningPid } from './process.js';
|
|
11
|
+
|
|
12
|
+
const log = (...a) => console.log(...a);
|
|
13
|
+
|
|
14
|
+
export function findOnPath(bin, path = process.env.PATH || '') {
|
|
15
|
+
for (const dir of path.split(delimiter)) {
|
|
16
|
+
if (!dir) continue;
|
|
17
|
+
try { accessSync(join(dir, bin), constants.X_OK); return join(dir, bin); } catch {}
|
|
18
|
+
}
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
// $VISUAL, then $EDITOR (may carry arguments, e.g. "code --wait"), then vi, then nano.
|
|
23
|
+
export function pickEditor(env = process.env) {
|
|
24
|
+
for (const v of [env.VISUAL, env.EDITOR]) if (v && v.trim()) return v.trim();
|
|
25
|
+
for (const bin of ['vi', 'nano']) if (findOnPath(bin, env.PATH)) return bin;
|
|
26
|
+
return null;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
// -f, ./tunnel.yml (when it is this project's), or the file remembered by `burrow up`.
|
|
30
|
+
// The file is not validated here, so a broken tunnel.yml can still be opened and fixed.
|
|
31
|
+
export function resolveEditFile(projectArg, opts = {}) {
|
|
32
|
+
if (projectArg) assertLabel(projectArg, 'project name');
|
|
33
|
+
let file = findProjectFile(opts.file);
|
|
34
|
+
if (file && projectArg) {
|
|
35
|
+
let name = null;
|
|
36
|
+
try { name = parseProject(readFileSync(file, 'utf8'), file).project; } catch {}
|
|
37
|
+
if (name && name !== projectArg) {
|
|
38
|
+
if (opts.file) throw new Error(`${file} is for project "${name}", not "${projectArg}".`);
|
|
39
|
+
file = null;
|
|
40
|
+
}
|
|
41
|
+
}
|
|
42
|
+
if (!file && projectArg) {
|
|
43
|
+
const meta = readMeta(projectArg);
|
|
44
|
+
if (meta?.file && existsSync(meta.file)) file = meta.file;
|
|
45
|
+
}
|
|
46
|
+
if (!file) {
|
|
47
|
+
throw new Error(
|
|
48
|
+
`No tunnel.yml found${opts.file ? ` at ${opts.file}` : ' in the current directory'}` +
|
|
49
|
+
(projectArg ? ` and no remembered file for "${projectArg}"` : '') + '. Use -f <path>.'
|
|
50
|
+
);
|
|
51
|
+
}
|
|
52
|
+
return file;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
// y/N question. Returns null when stdin is not a terminal.
|
|
56
|
+
async function ask(question, defaultYes) {
|
|
57
|
+
if (!process.stdin.isTTY) return null;
|
|
58
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
59
|
+
try {
|
|
60
|
+
const a = (await rl.question(`${question} ${defaultYes ? '[Y/n]' : '[y/N]'} `)).trim();
|
|
61
|
+
return a ? /^y(es)?$/i.test(a) : defaultYes;
|
|
62
|
+
} finally { rl.close(); }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function runEditor(editor, file) {
|
|
66
|
+
// Through sh so EDITOR may contain arguments; the file name is passed as $1, never interpolated.
|
|
67
|
+
const r = spawnSync('/bin/sh', ['-c', `${editor} "$1"`, 'sh', file], { stdio: 'inherit' });
|
|
68
|
+
if (r.error) throw new Error(`Could not start editor "${editor}": ${r.error.message}`);
|
|
69
|
+
return r.status;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export async function edit(projectArg, opts = {}) {
|
|
73
|
+
const file = resolveEditFile(projectArg, opts);
|
|
74
|
+
const editor = pickEditor();
|
|
75
|
+
if (!editor) throw new Error('No editor found. Set $EDITOR (for example: export EDITOR=nano).');
|
|
76
|
+
const original = readFileSync(file, 'utf8');
|
|
77
|
+
let before = null;
|
|
78
|
+
try { before = parseProject(original, file); } catch {}
|
|
79
|
+
|
|
80
|
+
// Edit a private copy; tunnel.yml is only replaced once the new text is valid.
|
|
81
|
+
const dir = mkdtempSync(join(tmpdir(), 'burrow-edit-'));
|
|
82
|
+
const tmp = join(dir, basename(file));
|
|
83
|
+
writeFileSync(tmp, original, { mode: 0o600 });
|
|
84
|
+
let text;
|
|
85
|
+
let proj;
|
|
86
|
+
for (;;) {
|
|
87
|
+
const status = runEditor(editor, tmp);
|
|
88
|
+
if (status !== 0) {
|
|
89
|
+
console.error(`Editor exited with ${status === null ? 'a signal' : `code ${status}`}; ${file} is unchanged. Your edits are in ${tmp}`);
|
|
90
|
+
process.exitCode = 1;
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
text = readFileSync(tmp, 'utf8');
|
|
94
|
+
if (text === original) {
|
|
95
|
+
rmSync(dir, { recursive: true, force: true });
|
|
96
|
+
log(`No changes to ${file}.`);
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
try {
|
|
100
|
+
proj = parseProject(text, file);
|
|
101
|
+
// hooks: is read by up/down, not by parseProject; check it here so a typo in a hook
|
|
102
|
+
// name or option is caught on save instead of on the next start.
|
|
103
|
+
parseHooks(YAML.parse(text) || {}, file);
|
|
104
|
+
break;
|
|
105
|
+
} catch (e) {
|
|
106
|
+
console.error(`burrow: ${e.message}`);
|
|
107
|
+
if (!(await ask('Re-open the editor to fix it?', true))) {
|
|
108
|
+
console.error(`Not saved: ${file} is unchanged. Your edits are in ${tmp}`);
|
|
109
|
+
process.exitCode = 1;
|
|
110
|
+
return;
|
|
111
|
+
}
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
writeFileSync(file, text);
|
|
115
|
+
rmSync(dir, { recursive: true, force: true });
|
|
116
|
+
log(`Saved ${file} (project ${proj.project}, ${proj.services.length} service(s)).`);
|
|
117
|
+
if (before && before.project !== proj.project) {
|
|
118
|
+
log(`Note: the project was renamed from ${before.project} to ${proj.project}. ` +
|
|
119
|
+
`Tunnel burrow-${before.project} is kept; remove it with "burrow destroy ${before.project}".`);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const pid = runningPid(proj.project);
|
|
123
|
+
const later = `burrow up -f ${file}`;
|
|
124
|
+
if (!pid) { log(`${proj.project} is not running. Start it with: ${later}`); return; }
|
|
125
|
+
if (opts.apply === false) { log(`Not applied (--no-apply). Apply it with: ${later}`); return; }
|
|
126
|
+
let go = !!opts.yes;
|
|
127
|
+
if (!go) {
|
|
128
|
+
const answer = await ask(`${proj.project} is running (pid ${pid}). Apply the change now (burrow up)?`, true);
|
|
129
|
+
if (answer === null) { log(`${proj.project} is running, but this is not a terminal. Pass --yes to apply, or run: ${later}`); return; }
|
|
130
|
+
go = answer;
|
|
131
|
+
}
|
|
132
|
+
if (!go) { log(`Not applied. Apply it later with: ${later}`); return; }
|
|
133
|
+
const cmd = await import('./commands.js');
|
|
134
|
+
await cmd.up(undefined, { file, dryRun: opts.dryRun });
|
|
135
|
+
}
|
|
@@ -0,0 +1,81 @@
|
|
|
1
|
+
// Health changes seen by the dashboard, for when `burrow watch` isn't running.
|
|
2
|
+
// Every refresh of the project list (and a timer in the dashboard, so it works with no browser
|
|
3
|
+
// open) compares what each project is doing with the last observation and records a change in
|
|
4
|
+
// the event history as action `health`, source `dashboard`, e.g.
|
|
5
|
+
// `down: cloudflared is not running (it exited or crashed) (was ok)`. The uptime timeline reads
|
|
6
|
+
// these like the ones `burrow watch` writes. While `burrow watch` is active (its state file was
|
|
7
|
+
// written in the last WATCH_FRESH_MS) it owns health changes and the dashboard records nothing.
|
|
8
|
+
// No port probes here: only the connector process and the tunnel status from Cloudflare.
|
|
9
|
+
import { mkdirSync, readFileSync, statSync, writeFileSync } from 'node:fs';
|
|
10
|
+
import { dirname, join } from 'node:path';
|
|
11
|
+
import { stateDir } from './config.js';
|
|
12
|
+
import { recordEvent } from './history.js';
|
|
13
|
+
import { readPid } from './process.js';
|
|
14
|
+
import { isShare } from './share.js';
|
|
15
|
+
import { watchStateFile } from './watch.js';
|
|
16
|
+
|
|
17
|
+
export const observedFile = () => join(stateDir(), 'watch', 'observed.json');
|
|
18
|
+
export const WATCH_FRESH_MS = 5 * 60 * 1000;
|
|
19
|
+
// A new status must be seen twice, at least this far apart, before it counts (a restart briefly
|
|
20
|
+
// looks like a crash).
|
|
21
|
+
export const CONFIRM_MS = 15 * 1000;
|
|
22
|
+
|
|
23
|
+
export function watchActive(now = Date.now()) {
|
|
24
|
+
try { return now - statSync(watchStateFile()).mtimeMs < WATCH_FRESH_MS; } catch { return false; }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
// { status: ok|degraded|down, reason } for a /api/tunnels project row, or null when the project
|
|
28
|
+
// is stopped on purpose (no pid file) or is the dashboard itself.
|
|
29
|
+
export function observedStatus(p, { pidFileExists = (name) => !!readPid(name) } = {}) {
|
|
30
|
+
if (!p || p.builtIn || isShare(p.project)) return null;
|
|
31
|
+
if (!p.running) {
|
|
32
|
+
return pidFileExists(p.project) ? { status: 'down', reason: 'cloudflared is not running (it exited or crashed)' } : null;
|
|
33
|
+
}
|
|
34
|
+
const t = p.tunnel?.status;
|
|
35
|
+
if (t === 'down' || t === 'inactive') return { status: 'down', reason: `tunnel is ${t} (no connections)` };
|
|
36
|
+
if (t === 'degraded') return { status: 'degraded', reason: `tunnel is degraded (${(p.tunnel.connections || []).length} connection(s))` };
|
|
37
|
+
return { status: 'ok', reason: '' };
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
export function readObserved() {
|
|
41
|
+
try { return JSON.parse(readFileSync(observedFile(), 'utf8')) || {}; } catch { return {}; }
|
|
42
|
+
}
|
|
43
|
+
function writeObserved(st) {
|
|
44
|
+
mkdirSync(dirname(observedFile()), { recursive: true, mode: 0o700 });
|
|
45
|
+
writeFileSync(observedFile(), JSON.stringify(st, null, 2) + '\n', { mode: 0o600 });
|
|
46
|
+
}
|
|
47
|
+
|
|
48
|
+
// projects: /api/tunnels rows. Returns the changes recorded ([{ project, from, to }]).
|
|
49
|
+
export function observe(projects, { now = Date.now(), record = recordEvent, pidFileExists } = {}) {
|
|
50
|
+
if (watchActive(now)) return [];
|
|
51
|
+
const prev = readObserved();
|
|
52
|
+
const next = {};
|
|
53
|
+
const changes = [];
|
|
54
|
+
for (const p of projects || []) {
|
|
55
|
+
const s = observedStatus(p, pidFileExists ? { pidFileExists } : undefined);
|
|
56
|
+
if (!s) continue; // stopped on purpose: not tracked (a later start is an `up` event)
|
|
57
|
+
// First sighting counts as coming from ok, like `burrow watch`, so an already broken project shows.
|
|
58
|
+
const cur = prev[p.project] || { status: 'ok', since: now, pending: null, pendingAt: null };
|
|
59
|
+
if (s.status === cur.status) { next[p.project] = { ...cur, pending: null, pendingAt: null }; continue; }
|
|
60
|
+
if (cur.pending !== s.status) { next[p.project] = { ...cur, pending: s.status, pendingAt: now }; continue; }
|
|
61
|
+
if (now - cur.pendingAt < CONFIRM_MS) { next[p.project] = cur; continue; }
|
|
62
|
+
next[p.project] = { status: s.status, since: cur.pendingAt, pending: null, pendingAt: null };
|
|
63
|
+
changes.push({ project: p.project, from: cur.status, to: s.status });
|
|
64
|
+
record({
|
|
65
|
+
action: 'health', project: p.project, source: 'dashboard', ok: s.status === 'ok',
|
|
66
|
+
detail: `${s.status}${s.reason ? `: ${s.reason}` : ''} (was ${cur.status})`,
|
|
67
|
+
});
|
|
68
|
+
}
|
|
69
|
+
// Only write when something changed, so a quiet dashboard doesn't touch the disk every refresh.
|
|
70
|
+
if (JSON.stringify(next) !== JSON.stringify(prev)) writeObserved(next);
|
|
71
|
+
return changes;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// The per-project health state the uptime timeline uses for "now": the watch state while
|
|
75
|
+
// `burrow watch` is active, else what the dashboard observed.
|
|
76
|
+
export function healthState(now = Date.now()) {
|
|
77
|
+
if (watchActive(now)) {
|
|
78
|
+
try { return JSON.parse(readFileSync(watchStateFile(), 'utf8')); } catch { return {}; }
|
|
79
|
+
}
|
|
80
|
+
return readObserved();
|
|
81
|
+
}
|