burrow-cli 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +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 +131 -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
|
@@ -0,0 +1,390 @@
|
|
|
1
|
+
import { createServer } from 'node:http';
|
|
2
|
+
import { spawn } from 'node:child_process';
|
|
3
|
+
import { existsSync, statSync, openSync, readSync, closeSync, readFileSync } from 'node:fs';
|
|
4
|
+
import { fileURLToPath } from 'node:url';
|
|
5
|
+
import { createRequire } from 'node:module';
|
|
6
|
+
import { loadConfig } from '../config.js';
|
|
7
|
+
import { assertLabel } from '../naming.js';
|
|
8
|
+
import { logFile } from '../process.js';
|
|
9
|
+
import { collect, invalidateCloudflare } from './data.js';
|
|
10
|
+
import { readTail, combinedText, downloadName, streamAll } from './logs.js';
|
|
11
|
+
import {
|
|
12
|
+
passwordMatches, sessionKey, signSession, verifySession, RateLimiter, parseCookies, newSecret, MIN_PASSWORD_LENGTH,
|
|
13
|
+
} from './auth.js';
|
|
14
|
+
import { LOGIN_HTML, renderApp, APP_CSS, APP_JS, LOGIN_JS } from './ui.js';
|
|
15
|
+
import { totpEnabled, verifyCode } from './totp.js';
|
|
16
|
+
import { openSessionStore } from './session-store.js';
|
|
17
|
+
import { loadPanels, sortPanels, panelJs, panelCss, panelVendor, events } from './panels.js';
|
|
18
|
+
|
|
19
|
+
// Vendored front-end libraries, served from node_modules (no CDN, works offline).
|
|
20
|
+
const require = createRequire(import.meta.url);
|
|
21
|
+
export const VENDOR = {
|
|
22
|
+
'/vendor/alpine.min.js': { pkg: '@alpinejs/csp/dist/cdn.min.js', type: 'text/javascript; charset=utf-8' },
|
|
23
|
+
'/vendor/pico.min.css': { pkg: '@picocss/pico/css/pico.min.css', type: 'text/css; charset=utf-8' },
|
|
24
|
+
};
|
|
25
|
+
const vendorCache = new Map();
|
|
26
|
+
function vendorAsset(path, entry = VENDOR[path]) {
|
|
27
|
+
if (!vendorCache.has(path)) vendorCache.set(path, readFileSync(require.resolve(entry.pkg)));
|
|
28
|
+
return vendorCache.get(path);
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const BIN = fileURLToPath(new URL('../../bin/burrow.js', import.meta.url));
|
|
32
|
+
const COOKIE = 'burrow_session';
|
|
33
|
+
const SESSION_TTL = 12 * 60 * 60 * 1000;
|
|
34
|
+
const BLOCKED_LOG_MS = 60 * 1000;
|
|
35
|
+
|
|
36
|
+
const SECURITY_HEADERS = {
|
|
37
|
+
'Content-Security-Policy':
|
|
38
|
+
"default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; " +
|
|
39
|
+
"object-src 'none'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
|
|
40
|
+
'X-Content-Type-Options': 'nosniff',
|
|
41
|
+
'X-Frame-Options': 'DENY',
|
|
42
|
+
'Referrer-Policy': 'no-referrer',
|
|
43
|
+
'Cache-Control': 'no-store',
|
|
44
|
+
};
|
|
45
|
+
|
|
46
|
+
function send(res, status, body, type = 'text/plain; charset=utf-8', extra = {}) {
|
|
47
|
+
res.writeHead(status, { ...SECURITY_HEADERS, 'Content-Type': type, ...extra });
|
|
48
|
+
res.end(body);
|
|
49
|
+
}
|
|
50
|
+
const json = (res, status, obj, extra) => send(res, status, JSON.stringify(obj), 'application/json', extra);
|
|
51
|
+
|
|
52
|
+
function readBody(req, limit = 4096) {
|
|
53
|
+
return new Promise((resolve, reject) => {
|
|
54
|
+
let size = 0;
|
|
55
|
+
const chunks = [];
|
|
56
|
+
req.on('data', (c) => {
|
|
57
|
+
size += c.length;
|
|
58
|
+
if (size > limit) { reject(new Error('body too large')); req.destroy(); return; }
|
|
59
|
+
chunks.push(c);
|
|
60
|
+
});
|
|
61
|
+
req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
|
|
62
|
+
req.on('error', reject);
|
|
63
|
+
});
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
// cloudflared connects from loopback; only then trust CF-Connecting-IP.
|
|
67
|
+
export function clientIp(req) {
|
|
68
|
+
const remote = req.socket.remoteAddress || '';
|
|
69
|
+
const loopback = remote === '127.0.0.1' || remote === '::1' || remote === '::ffff:127.0.0.1';
|
|
70
|
+
const cf = req.headers['cf-connecting-ip'];
|
|
71
|
+
return loopback && typeof cf === 'string' && cf ? cf : remote;
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
// BURROW_SOURCE tells the CLI (e.g. the event history) that the dashboard ran it.
|
|
75
|
+
export function runCli(args, timeoutMs = 90000) {
|
|
76
|
+
return new Promise((resolve) => {
|
|
77
|
+
const child = spawn(process.execPath, [BIN, ...args], {
|
|
78
|
+
stdio: ['ignore', 'pipe', 'pipe'], env: { ...process.env, BURROW_SOURCE: 'dashboard' },
|
|
79
|
+
});
|
|
80
|
+
let out = '';
|
|
81
|
+
child.stdout.on('data', (d) => { out += d; });
|
|
82
|
+
child.stderr.on('data', (d) => { out += d; });
|
|
83
|
+
const timer = setTimeout(() => child.kill('SIGTERM'), timeoutMs);
|
|
84
|
+
child.on('close', (code) => { clearTimeout(timer); resolve({ ok: code === 0, output: out.slice(-20000) }); });
|
|
85
|
+
child.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, output: e.message }); });
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function streamLog(req, res, project) {
|
|
90
|
+
const file = logFile(project);
|
|
91
|
+
res.writeHead(200, {
|
|
92
|
+
...SECURITY_HEADERS, 'Content-Type': 'text/event-stream', Connection: 'keep-alive', 'X-Accel-Buffering': 'no',
|
|
93
|
+
});
|
|
94
|
+
let pos = 0;
|
|
95
|
+
let partial = '';
|
|
96
|
+
const emit = (text) => {
|
|
97
|
+
const lines = (partial + text).split('\n');
|
|
98
|
+
partial = lines.pop();
|
|
99
|
+
for (const line of lines) res.write(`data: ${line.replace(/\r/g, '')}\n\n`);
|
|
100
|
+
};
|
|
101
|
+
const readRange = (from, to) => {
|
|
102
|
+
const fd = openSync(file, 'r');
|
|
103
|
+
try {
|
|
104
|
+
const buf = Buffer.alloc(to - from);
|
|
105
|
+
readSync(fd, buf, 0, buf.length, from);
|
|
106
|
+
return buf.toString('utf8');
|
|
107
|
+
} finally { closeSync(fd); }
|
|
108
|
+
};
|
|
109
|
+
if (existsSync(file)) {
|
|
110
|
+
const size = statSync(file).size;
|
|
111
|
+
const start = Math.max(0, size - 64 * 1024);
|
|
112
|
+
let text = readRange(start, size);
|
|
113
|
+
if (start > 0) text = text.slice(text.indexOf('\n') + 1);
|
|
114
|
+
emit(text);
|
|
115
|
+
pos = size;
|
|
116
|
+
} else {
|
|
117
|
+
res.write(`data: (no log yet at ${file})\n\n`);
|
|
118
|
+
}
|
|
119
|
+
const poll = setInterval(() => {
|
|
120
|
+
try {
|
|
121
|
+
if (!existsSync(file)) return;
|
|
122
|
+
const size = statSync(file).size;
|
|
123
|
+
if (size < pos) { pos = 0; partial = ''; res.write('data: (log truncated)\n\n'); }
|
|
124
|
+
if (size > pos) {
|
|
125
|
+
const to = Math.min(size, pos + 256 * 1024);
|
|
126
|
+
emit(readRange(pos, to));
|
|
127
|
+
pos = to;
|
|
128
|
+
}
|
|
129
|
+
} catch {}
|
|
130
|
+
}, 1000);
|
|
131
|
+
const ping = setInterval(() => res.write(': ping\n\n'), 15000);
|
|
132
|
+
req.on('close', () => { clearInterval(poll); clearInterval(ping); });
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
// Panels (see ./panels/README.md) are loaded from ./panels/*.js, or passed in (tests).
|
|
136
|
+
function buildPanels(list) {
|
|
137
|
+
return { list, html: renderApp(list), js: panelJs(list), css: panelCss(list), vendor: panelVendor(list) };
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// persistSessions: keep sessions (and their signing secret) in the state dir so they survive
|
|
141
|
+
// a restart (see session-store.js). On for `burrow dashboard`; off by default (tests).
|
|
142
|
+
export function createDashboard({ password, log = console.log, panels, persistSessions = false } = {}) {
|
|
143
|
+
if (typeof password !== 'string' || password.length < MIN_PASSWORD_LENGTH) {
|
|
144
|
+
throw new Error(`Set BURROW_DASHBOARD_PASSWORD (at least ${MIN_PASSWORD_LENGTH} characters) in the burrow config.`);
|
|
145
|
+
}
|
|
146
|
+
let store = null;
|
|
147
|
+
if (persistSessions) {
|
|
148
|
+
try { store = openSessionStore(); } catch (e) { log(`warning: sessions are kept in memory only (${e.message})`); }
|
|
149
|
+
}
|
|
150
|
+
const key = sessionKey(store ? store.secret : newSecret(), password);
|
|
151
|
+
const sessions = new Map(); // id -> exp (server-side, so logout really ends a session)
|
|
152
|
+
const sessionInfo = new Map(); // id -> { createdAt, lastSeen, ip, agent } (for the Sessions panel)
|
|
153
|
+
if (store) for (const [id, s] of store.sessions) { sessions.set(id, s.exp); sessionInfo.set(id, s.info); }
|
|
154
|
+
const saveSessions = (touchOnly = false) => {
|
|
155
|
+
if (!store) return;
|
|
156
|
+
try { (touchOnly ? store.touch : store.save)(sessions, sessionInfo); } catch (e) { log(`warning: could not save sessions: ${e.message}`); }
|
|
157
|
+
};
|
|
158
|
+
const limiter = new RateLimiter({ max: 5, windowMs: 15 * 60 * 1000 });
|
|
159
|
+
// Sign-ins refused by the rate limit go to the event history, at most one entry per IP per
|
|
160
|
+
// minute (with how many were left out), so a flood of attempts can't flood the history.
|
|
161
|
+
const blockedSeen = new Map(); // ip -> { at, suppressed }
|
|
162
|
+
const recordBlocked = (ip, retryAfter, now = Date.now()) => {
|
|
163
|
+
const b = blockedSeen.get(ip);
|
|
164
|
+
if (b && now - b.at < BLOCKED_LOG_MS) { b.suppressed++; return; }
|
|
165
|
+
const more = b?.suppressed ? ` (${b.suppressed} more since the last entry)` : '';
|
|
166
|
+
events.emit('event', { action: 'sign-in', ok: false, detail: `blocked by the rate limit from ${ip}${more}; retry in ${retryAfter}s` });
|
|
167
|
+
blockedSeen.set(ip, { at: now, suppressed: 0 });
|
|
168
|
+
if (blockedSeen.size > 10000) for (const [k, v] of blockedSeen) if (now - v.at >= BLOCKED_LOG_MS) blockedSeen.delete(k);
|
|
169
|
+
};
|
|
170
|
+
const busy = new Set();
|
|
171
|
+
const ready = (panels ? Promise.resolve(sortPanels(panels)) : loadPanels()).then(buildPanels);
|
|
172
|
+
ready.catch((e) => log(`error: dashboard panels failed to load: ${e.message}`));
|
|
173
|
+
// Run fn while holding the per-project lock; null when the project is busy.
|
|
174
|
+
const withBusy = async (project, fn) => {
|
|
175
|
+
if (busy.has(project)) return null;
|
|
176
|
+
busy.add(project);
|
|
177
|
+
try { return await fn(); } finally { busy.delete(project); }
|
|
178
|
+
};
|
|
179
|
+
const panelCtx = (req, res, url) => ({
|
|
180
|
+
req, res, url, method: req.method, path: url.pathname, log, events, withBusy, runCli, loadConfig,
|
|
181
|
+
invalidate: invalidateCloudflare,
|
|
182
|
+
// The /api/tunnels payload (with every panel's enrich), for panels that push updates.
|
|
183
|
+
async snapshot() {
|
|
184
|
+
const data = await collect(loadConfig());
|
|
185
|
+
for (const p of (await ready).list) {
|
|
186
|
+
if (!p.enrich) continue;
|
|
187
|
+
try { await p.enrich(data.projects, this); } catch (e) { log(`error: panel ${p.id}: ${e.message}`); }
|
|
188
|
+
}
|
|
189
|
+
return data;
|
|
190
|
+
},
|
|
191
|
+
clientIp: clientIp(req),
|
|
192
|
+
json: (status, obj, extra) => json(res, status, obj, extra),
|
|
193
|
+
send: (status, body, type, extra) => send(res, status, body, type, extra),
|
|
194
|
+
readJson: async (limit = 16384) => {
|
|
195
|
+
const text = await readBody(req, limit);
|
|
196
|
+
try { return text ? JSON.parse(text) : {}; } catch { return null; }
|
|
197
|
+
},
|
|
198
|
+
// Signed-in sessions (ids never leave the server; panels see opaque handles).
|
|
199
|
+
sessions: {
|
|
200
|
+
current: () => authed(req) || null,
|
|
201
|
+
list: () => [...sessions].filter(([, exp]) => exp > Date.now()).map(([id, exp]) => ({ id, exp, ...(sessionInfo.get(id) || {}) })),
|
|
202
|
+
revoke: (id) => { sessionInfo.delete(id); const had = sessions.delete(id); saveSessions(); return had; },
|
|
203
|
+
clearCookie: () => cookie('', 0),
|
|
204
|
+
},
|
|
205
|
+
});
|
|
206
|
+
|
|
207
|
+
const authed = (req) => {
|
|
208
|
+
const id = verifySession(key, parseCookies(req.headers.cookie)[COOKIE]);
|
|
209
|
+
if (!id) return false;
|
|
210
|
+
const exp = sessions.get(id);
|
|
211
|
+
if (!exp || exp < Date.now()) { sessions.delete(id); sessionInfo.delete(id); saveSessions(); return false; }
|
|
212
|
+
const info = sessionInfo.get(id) || { createdAt: Date.now(), ip: clientIp(req), agent: String(req.headers['user-agent'] || '').slice(0, 200) };
|
|
213
|
+
info.lastSeen = Date.now();
|
|
214
|
+
info.ip = clientIp(req);
|
|
215
|
+
sessionInfo.set(id, info);
|
|
216
|
+
saveSessions(true);
|
|
217
|
+
return id;
|
|
218
|
+
};
|
|
219
|
+
const cookie = (value, maxAge) =>
|
|
220
|
+
`${COOKIE}=${value}; Path=/; HttpOnly; Secure; SameSite=Strict; Max-Age=${maxAge}`;
|
|
221
|
+
|
|
222
|
+
async function handle(req, res) {
|
|
223
|
+
const url = new URL(req.url, 'http://local');
|
|
224
|
+
const path = url.pathname;
|
|
225
|
+
const P = await ready;
|
|
226
|
+
|
|
227
|
+
if (req.method === 'GET' && path === '/app.css') return send(res, 200, APP_CSS, 'text/css; charset=utf-8');
|
|
228
|
+
if (req.method === 'GET' && path === '/healthz') return send(res, 200, 'ok');
|
|
229
|
+
if (req.method === 'GET' && path === '/favicon.ico') return send(res, 204, '');
|
|
230
|
+
if (req.method === 'GET' && path === '/login.js') return send(res, 200, LOGIN_JS, 'text/javascript; charset=utf-8');
|
|
231
|
+
const vendor = VENDOR[path] || P.vendor[path];
|
|
232
|
+
if (req.method === 'GET' && vendor) {
|
|
233
|
+
return send(res, 200, vendorAsset(path, vendor), vendor.type, { 'Cache-Control': 'public, max-age=86400' });
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
if (path === '/login') {
|
|
237
|
+
if (req.method === 'GET') return send(res, 200, LOGIN_HTML(''), 'text/html; charset=utf-8');
|
|
238
|
+
if (req.method !== 'POST') return send(res, 405, 'Method not allowed');
|
|
239
|
+
const ip = clientIp(req);
|
|
240
|
+
const wantsJson = String(req.headers.accept || '').includes('application/json');
|
|
241
|
+
const lim = limiter.check(ip);
|
|
242
|
+
if (!lim.allowed) {
|
|
243
|
+
log(`login rate-limited for ${ip}`);
|
|
244
|
+
recordBlocked(ip, lim.retryAfter);
|
|
245
|
+
const msg = `Too many attempts. Try again in ${Math.ceil(lim.retryAfter / 60)} min.`;
|
|
246
|
+
if (wantsJson) return json(res, 429, { error: msg, retryAfter: lim.retryAfter }, { 'Retry-After': String(lim.retryAfter) });
|
|
247
|
+
return send(res, 429, LOGIN_HTML(`Too many attempts. Try again in ${Math.ceil(lim.retryAfter / 60)} min.`),
|
|
248
|
+
'text/html; charset=utf-8', { 'Retry-After': String(lim.retryAfter) });
|
|
249
|
+
}
|
|
250
|
+
let given = '';
|
|
251
|
+
let code = '';
|
|
252
|
+
try {
|
|
253
|
+
const form = new URLSearchParams(await readBody(req));
|
|
254
|
+
given = form.get('password') || '';
|
|
255
|
+
code = form.get('code') || '';
|
|
256
|
+
} catch { return send(res, 413, 'Too large'); }
|
|
257
|
+
if (!passwordMatches(given, password)) {
|
|
258
|
+
limiter.fail(ip);
|
|
259
|
+
log(`login failed from ${ip}`);
|
|
260
|
+
events.emit('event', { action: 'sign-in', ok: false, detail: `wrong password from ${ip}` });
|
|
261
|
+
if (wantsJson) return json(res, 401, { error: 'Wrong password.' });
|
|
262
|
+
return send(res, 401, LOGIN_HTML('Wrong password.'), 'text/html; charset=utf-8');
|
|
263
|
+
}
|
|
264
|
+
// Optional second factor (see totp.js): counts against the same rate limit.
|
|
265
|
+
if (totpEnabled() && !verifyCode(code)) {
|
|
266
|
+
limiter.fail(ip);
|
|
267
|
+
log(`login failed from ${ip}: two-factor code`);
|
|
268
|
+
events.emit('event', { action: 'sign-in', ok: false, detail: `${code ? 'wrong' : 'missing'} two-factor code from ${ip}` });
|
|
269
|
+
const msg = code ? 'Wrong two-factor code.' : 'Enter the code from your authenticator app.';
|
|
270
|
+
if (wantsJson) return json(res, 401, { error: msg, twoFactor: true });
|
|
271
|
+
return send(res, 401, LOGIN_HTML(msg), 'text/html; charset=utf-8');
|
|
272
|
+
}
|
|
273
|
+
limiter.reset(ip);
|
|
274
|
+
const s = signSession(key, SESSION_TTL);
|
|
275
|
+
sessions.set(s.id, s.exp);
|
|
276
|
+
saveSessions();
|
|
277
|
+
log(`login ok from ${ip}`);
|
|
278
|
+
events.emit('event', { action: 'sign-in', detail: `from ${ip}` });
|
|
279
|
+
if (wantsJson) return json(res, 200, { ok: true }, { 'Set-Cookie': cookie(s.value, SESSION_TTL / 1000) });
|
|
280
|
+
return send(res, 303, '', 'text/plain', { Location: '/', 'Set-Cookie': cookie(s.value, SESSION_TTL / 1000) });
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
const sid = authed(req);
|
|
284
|
+
if (!sid) {
|
|
285
|
+
if (path.startsWith('/api/')) return json(res, 401, { error: 'login required' });
|
|
286
|
+
return send(res, 303, '', 'text/plain', { Location: '/login' });
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
// State-changing requests need a custom header: browsers can't send it
|
|
290
|
+
// cross-site without a CORS preflight, which this server never allows.
|
|
291
|
+
if (req.method === 'POST' && req.headers['x-burrow'] !== '1') return json(res, 403, { error: 'missing X-Burrow header' });
|
|
292
|
+
|
|
293
|
+
if (req.method === 'POST' && path === '/logout') {
|
|
294
|
+
sessions.delete(sid);
|
|
295
|
+
sessionInfo.delete(sid);
|
|
296
|
+
saveSessions();
|
|
297
|
+
events.emit('event', { action: 'sign-out', detail: `from ${clientIp(req)}` });
|
|
298
|
+
return json(res, 200, { ok: true }, { 'Set-Cookie': cookie('', 0) });
|
|
299
|
+
}
|
|
300
|
+
if (req.method === 'GET' && path === '/') return send(res, 200, P.html, 'text/html; charset=utf-8');
|
|
301
|
+
if (req.method === 'GET' && path === '/app.js') return send(res, 200, APP_JS, 'text/javascript; charset=utf-8');
|
|
302
|
+
if (req.method === 'GET' && path === '/panels.js') return send(res, 200, P.js, 'text/javascript; charset=utf-8');
|
|
303
|
+
if (req.method === 'GET' && path === '/panels.css') return send(res, 200, P.css, 'text/css; charset=utf-8');
|
|
304
|
+
if (req.method === 'GET' && path === '/api/tunnels') {
|
|
305
|
+
const data = await collect(loadConfig());
|
|
306
|
+
const ctx = panelCtx(req, res, url);
|
|
307
|
+
for (const p of P.list) {
|
|
308
|
+
if (!p.enrich) continue;
|
|
309
|
+
try { await p.enrich(data.projects, ctx); } catch (e) { log(`error: panel ${p.id}: ${e.message}`); }
|
|
310
|
+
}
|
|
311
|
+
return json(res, 200, data);
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
let m = path.match(/^\/api\/logs\/([^/]+)$/);
|
|
315
|
+
if (req.method === 'GET' && m) {
|
|
316
|
+
try { assertLabel(m[1], 'project'); } catch { return json(res, 400, { error: 'bad project' }); }
|
|
317
|
+
return streamLog(req, res, m[1]);
|
|
318
|
+
}
|
|
319
|
+
if (req.method === 'GET' && path === '/api/logs-all') return streamAll(req, res, SECURITY_HEADERS);
|
|
320
|
+
if (req.method === 'GET' && path === '/api/logs-all/download') {
|
|
321
|
+
return send(res, 200, combinedText(), 'text/plain; charset=utf-8',
|
|
322
|
+
{ 'Content-Disposition': `attachment; filename="${downloadName('all')}"` });
|
|
323
|
+
}
|
|
324
|
+
m = path.match(/^\/api\/logs\/([^/]+)\/download$/);
|
|
325
|
+
if (req.method === 'GET' && m) {
|
|
326
|
+
try { assertLabel(m[1], 'project'); } catch { return json(res, 400, { error: 'bad project' }); }
|
|
327
|
+
if (!existsSync(logFile(m[1]))) return json(res, 404, { error: 'no log yet' });
|
|
328
|
+
return send(res, 200, readTail(logFile(m[1]), 10 * 1024 * 1024), 'text/plain; charset=utf-8',
|
|
329
|
+
{ 'Content-Disposition': `attachment; filename="${downloadName(m[1])}"` });
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
m = path.match(/^\/api\/tunnels\/([^/]+)\/(up|down|destroy)$/);
|
|
333
|
+
if (req.method === 'POST' && m) {
|
|
334
|
+
const [, project, action] = m;
|
|
335
|
+
try { assertLabel(project, 'project'); } catch { return json(res, 400, { error: 'bad project' }); }
|
|
336
|
+
if (action === 'destroy') {
|
|
337
|
+
let body = {};
|
|
338
|
+
try { body = JSON.parse((await readBody(req)) || '{}'); } catch {}
|
|
339
|
+
if (body.confirm !== project) return json(res, 400, { error: 'type the project name to confirm' });
|
|
340
|
+
}
|
|
341
|
+
if (busy.has(project)) return json(res, 409, { error: `${project} is busy` });
|
|
342
|
+
busy.add(project);
|
|
343
|
+
log(`${action} ${project} (requested from ${clientIp(req)})`);
|
|
344
|
+
try {
|
|
345
|
+
const r = await runCli([action, project]);
|
|
346
|
+
invalidateCloudflare();
|
|
347
|
+
return json(res, r.ok ? 200 : 500, r);
|
|
348
|
+
} finally { busy.delete(project); }
|
|
349
|
+
}
|
|
350
|
+
for (const p of P.list) {
|
|
351
|
+
if (p.route && (await p.route(panelCtx(req, res, url)))) return;
|
|
352
|
+
}
|
|
353
|
+
return json(res, 404, { error: 'not found' });
|
|
354
|
+
}
|
|
355
|
+
|
|
356
|
+
const server = createServer((req, res) => {
|
|
357
|
+
handle(req, res).catch((e) => {
|
|
358
|
+
log(`error: ${e.message}`);
|
|
359
|
+
if (!res.headersSent) json(res, 500, { error: 'internal error' });
|
|
360
|
+
else res.end();
|
|
361
|
+
});
|
|
362
|
+
});
|
|
363
|
+
// Background work of panels (export function start(ctx) -> stop function), for things that
|
|
364
|
+
// should happen with no browser open. Started once the server listens, stopped when it closes.
|
|
365
|
+
const stops = [];
|
|
366
|
+
server.once('listening', () => {
|
|
367
|
+
ready.then((P) => {
|
|
368
|
+
if (!server.listening) return;
|
|
369
|
+
const ctx = { log, events, loadConfig, invalidate: invalidateCloudflare, runCli, collect: () => collect(loadConfig()) };
|
|
370
|
+
for (const p of P.list) {
|
|
371
|
+
if (typeof p.start !== 'function') continue;
|
|
372
|
+
try { const stop = p.start(ctx); if (typeof stop === 'function') stops.push(stop); } catch (e) { log(`error: panel ${p.id}: ${e.message}`); }
|
|
373
|
+
}
|
|
374
|
+
}).catch(() => {});
|
|
375
|
+
});
|
|
376
|
+
server.once('close', () => { for (const stop of stops.splice(0)) { try { stop(); } catch {} } });
|
|
377
|
+
return server;
|
|
378
|
+
}
|
|
379
|
+
|
|
380
|
+
export function runDashboard({ port, host = '127.0.0.1' }) {
|
|
381
|
+
const cfg = loadConfig();
|
|
382
|
+
const server = createDashboard({ password: cfg.dashboardPassword, persistSessions: true });
|
|
383
|
+
return new Promise((resolve, reject) => {
|
|
384
|
+
server.once('error', reject);
|
|
385
|
+
server.listen(port, host, () => {
|
|
386
|
+
console.log(`burrow dashboard on http://${host}:${port} (pid ${process.pid})`);
|
|
387
|
+
resolve(server);
|
|
388
|
+
});
|
|
389
|
+
});
|
|
390
|
+
}
|
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
// Dashboard sessions that survive a restart: the signing secret and the server-side session
|
|
2
|
+
// list are kept in <state>/dashboard/sessions.json (mode 600, directory 700). Cookies are still
|
|
3
|
+
// signed with HMAC(secret, password), so changing the password ends every session; expired
|
|
4
|
+
// sessions are dropped on load and on save; signing out (one, others, everywhere) is saved
|
|
5
|
+
// straight away. Deleting the file ends every session at the next restart.
|
|
6
|
+
import { randomBytes } from 'node:crypto';
|
|
7
|
+
import { chmodSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
|
|
8
|
+
import { dirname, join } from 'node:path';
|
|
9
|
+
import { stateDir } from '../config.js';
|
|
10
|
+
|
|
11
|
+
export const sessionsFile = () => join(stateDir(), 'dashboard', 'sessions.json');
|
|
12
|
+
const TOUCH_MS = 5 * 60 * 1000; // lastSeen changes are saved at most this often
|
|
13
|
+
|
|
14
|
+
export function openSessionStore({ file = sessionsFile(), now = Date.now } = {}) {
|
|
15
|
+
let data = null;
|
|
16
|
+
try { data = JSON.parse(readFileSync(file, 'utf8')); } catch {}
|
|
17
|
+
let secret = null;
|
|
18
|
+
try { secret = Buffer.from(String(data?.secret || ''), 'base64'); } catch {}
|
|
19
|
+
const fresh = !secret || secret.length < 32;
|
|
20
|
+
if (fresh) secret = randomBytes(32);
|
|
21
|
+
const loaded = new Map();
|
|
22
|
+
if (!fresh && data?.sessions && typeof data.sessions === 'object') {
|
|
23
|
+
for (const [id, s] of Object.entries(data.sessions)) {
|
|
24
|
+
if (/^[A-Za-z0-9_-]+$/.test(id) && Number(s?.exp) > now()) loaded.set(id, { exp: Number(s.exp), info: s.info && typeof s.info === 'object' ? s.info : {} });
|
|
25
|
+
}
|
|
26
|
+
}
|
|
27
|
+
let savedAt = 0;
|
|
28
|
+
const save = (sessions, info) => {
|
|
29
|
+
const t = now();
|
|
30
|
+
const out = {};
|
|
31
|
+
for (const [id, exp] of sessions) if (exp > t) out[id] = { exp, info: info.get(id) || {} };
|
|
32
|
+
mkdirSync(dirname(file), { recursive: true, mode: 0o700 });
|
|
33
|
+
const tmp = `${file}.${process.pid}.tmp`;
|
|
34
|
+
writeFileSync(tmp, JSON.stringify({ secret: secret.toString('base64'), sessions: out }) + '\n', { mode: 0o600 });
|
|
35
|
+
chmodSync(tmp, 0o600);
|
|
36
|
+
renameSync(tmp, file);
|
|
37
|
+
savedAt = t;
|
|
38
|
+
};
|
|
39
|
+
if (fresh) save(new Map(), new Map()); // keep the new secret, so the next restart reuses it
|
|
40
|
+
return {
|
|
41
|
+
secret,
|
|
42
|
+
sessions: loaded,
|
|
43
|
+
save,
|
|
44
|
+
// For lastSeen updates: save only when the last save is old enough.
|
|
45
|
+
touch: (sessions, info) => { if (now() - savedAt >= TOUCH_MS) save(sessions, info); },
|
|
46
|
+
};
|
|
47
|
+
}
|
|
@@ -0,0 +1,103 @@
|
|
|
1
|
+
// Optional two-factor sign-in for the dashboard: TOTP (RFC 6238; SHA-1, 30 s, 6 digits, the
|
|
2
|
+
// defaults every authenticator app uses). Off unless you enroll from the Sessions panel.
|
|
3
|
+
// The secret lives in the state dir (mode 600) and is only ever shown during setup.
|
|
4
|
+
// A code is accepted once (replay protection) and within one step either side of now.
|
|
5
|
+
import { createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
6
|
+
import { mkdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
|
|
7
|
+
import { dirname, join } from 'node:path';
|
|
8
|
+
import { stateDir } from '../config.js';
|
|
9
|
+
|
|
10
|
+
export const STEP = 30;
|
|
11
|
+
export const DIGITS = 6;
|
|
12
|
+
export const totpFile = () => join(stateDir(), 'dashboard', 'totp.json');
|
|
13
|
+
const B32 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ234567';
|
|
14
|
+
|
|
15
|
+
export function base32Encode(buf) {
|
|
16
|
+
let bits = 0, value = 0, out = '';
|
|
17
|
+
for (const b of buf) {
|
|
18
|
+
value = (value << 8) | b; bits += 8;
|
|
19
|
+
while (bits >= 5) { out += B32[(value >>> (bits - 5)) & 31]; bits -= 5; }
|
|
20
|
+
}
|
|
21
|
+
if (bits > 0) out += B32[(value << (5 - bits)) & 31];
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
export function base32Decode(s) {
|
|
25
|
+
const clean = String(s).toUpperCase().replace(/[\s=]/g, '');
|
|
26
|
+
let bits = 0, value = 0;
|
|
27
|
+
const out = [];
|
|
28
|
+
for (const c of clean) {
|
|
29
|
+
const i = B32.indexOf(c);
|
|
30
|
+
if (i < 0) throw new Error('invalid base32');
|
|
31
|
+
value = (value << 5) | i; bits += 5;
|
|
32
|
+
if (bits >= 8) { out.push((value >>> (bits - 8)) & 255); bits -= 8; }
|
|
33
|
+
}
|
|
34
|
+
return Buffer.from(out);
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
export const newSecret = () => base32Encode(randomBytes(20));
|
|
38
|
+
|
|
39
|
+
// RFC 4226 HOTP for counter `step`.
|
|
40
|
+
export function hotp(secret, step) {
|
|
41
|
+
const msg = Buffer.alloc(8);
|
|
42
|
+
msg.writeBigUInt64BE(BigInt(step));
|
|
43
|
+
const h = createHmac('sha1', base32Decode(secret)).update(msg).digest();
|
|
44
|
+
const o = h[h.length - 1] & 15;
|
|
45
|
+
const n = ((h[o] & 127) << 24) | (h[o + 1] << 16) | (h[o + 2] << 8) | h[o + 3];
|
|
46
|
+
return String(n % 10 ** DIGITS).padStart(DIGITS, '0');
|
|
47
|
+
}
|
|
48
|
+
export const stepAt = (ms = Date.now()) => Math.floor(ms / 1000 / STEP);
|
|
49
|
+
export const totp = (secret, ms = Date.now()) => hotp(secret, stepAt(ms));
|
|
50
|
+
|
|
51
|
+
// The matching step for code (window ±1) that is newer than lastStep, or null.
|
|
52
|
+
export function matchStep(secret, code, { now = Date.now(), lastStep = -1, window = 1 } = {}) {
|
|
53
|
+
const c = String(code ?? '').replace(/\s/g, '');
|
|
54
|
+
if (!/^\d{6}$/.test(c)) return null;
|
|
55
|
+
const cur = stepAt(now);
|
|
56
|
+
let found = null;
|
|
57
|
+
for (let s = cur - window; s <= cur + window; s++) {
|
|
58
|
+
const ok = timingSafeEqual(Buffer.from(hotp(secret, s)), Buffer.from(c));
|
|
59
|
+
if (ok && s > lastStep && found === null) found = s;
|
|
60
|
+
}
|
|
61
|
+
return found;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export const otpauthUri = (secret, label = 'dashboard') =>
|
|
65
|
+
`otpauth://totp/${encodeURIComponent(`burrow:${label}`)}?secret=${secret}&issuer=burrow&algorithm=SHA1&digits=${DIGITS}&period=${STEP}`;
|
|
66
|
+
|
|
67
|
+
export function readTotp() {
|
|
68
|
+
try { return JSON.parse(readFileSync(totpFile(), 'utf8')); } catch { return {}; }
|
|
69
|
+
}
|
|
70
|
+
function writeTotp(st) {
|
|
71
|
+
if (!st.secret && !st.pending) { rmSync(totpFile(), { force: true }); return; }
|
|
72
|
+
mkdirSync(dirname(totpFile()), { recursive: true, mode: 0o700 });
|
|
73
|
+
writeFileSync(totpFile(), JSON.stringify(st, null, 2) + '\n', { mode: 0o600 });
|
|
74
|
+
}
|
|
75
|
+
export const totpEnabled = () => !!readTotp().enabled;
|
|
76
|
+
|
|
77
|
+
// Setup: a new pending secret (not active until confirmed with a code). Refused while enabled.
|
|
78
|
+
export function beginSetup(label) {
|
|
79
|
+
const st = readTotp();
|
|
80
|
+
if (st.enabled) throw new Error('two-factor sign-in is already on; turn it off first');
|
|
81
|
+
const secret = newSecret();
|
|
82
|
+
writeTotp({ pending: { secret, createdAt: Date.now() } });
|
|
83
|
+
return { secret, uri: otpauthUri(secret, label) };
|
|
84
|
+
}
|
|
85
|
+
export function confirmSetup(code, now = Date.now()) {
|
|
86
|
+
const st = readTotp();
|
|
87
|
+
if (st.enabled) throw new Error('two-factor sign-in is already on');
|
|
88
|
+
if (!st.pending?.secret || now - st.pending.createdAt > 15 * 60 * 1000) throw new Error('start the setup again (it expires after 15 minutes)');
|
|
89
|
+
const step = matchStep(st.pending.secret, code, { now });
|
|
90
|
+
if (step === null) return false;
|
|
91
|
+
writeTotp({ enabled: true, secret: st.pending.secret, lastStep: step, enabledAt: now });
|
|
92
|
+
return true;
|
|
93
|
+
}
|
|
94
|
+
// Sign-in and turning it off: a current code that wasn't used before.
|
|
95
|
+
export function verifyCode(code, now = Date.now()) {
|
|
96
|
+
const st = readTotp();
|
|
97
|
+
if (!st.enabled) return true;
|
|
98
|
+
const step = matchStep(st.secret, code, { now, lastStep: st.lastStep ?? -1 });
|
|
99
|
+
if (step === null) return false;
|
|
100
|
+
writeTotp({ ...st, lastStep: step });
|
|
101
|
+
return true;
|
|
102
|
+
}
|
|
103
|
+
export function disable() { writeTotp({}); }
|