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.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +594 -2
  3. package/bin/burrow.js +200 -0
  4. package/examples/acme-shop.tunnel.yml +18 -0
  5. package/package.json +45 -4
  6. package/src/access.js +163 -0
  7. package/src/add.js +106 -0
  8. package/src/cloudflare.js +118 -0
  9. package/src/commands.js +386 -0
  10. package/src/completion.js +127 -0
  11. package/src/config-file.js +31 -0
  12. package/src/config.js +82 -0
  13. package/src/dashboard/auth.js +79 -0
  14. package/src/dashboard/data.js +70 -0
  15. package/src/dashboard/logs.js +95 -0
  16. package/src/dashboard/manage.js +102 -0
  17. package/src/dashboard/panels/README.md +50 -0
  18. package/src/dashboard/panels/access.js +218 -0
  19. package/src/dashboard/panels/alerts.js +244 -0
  20. package/src/dashboard/panels/backup.js +193 -0
  21. package/src/dashboard/panels/bulk.js +246 -0
  22. package/src/dashboard/panels/cleanup.js +237 -0
  23. package/src/dashboard/panels/doctor.js +119 -0
  24. package/src/dashboard/panels/health.js +146 -0
  25. package/src/dashboard/panels/history.js +104 -0
  26. package/src/dashboard/panels/hooks.js +86 -0
  27. package/src/dashboard/panels/live.js +153 -0
  28. package/src/dashboard/panels/project-form.js +463 -0
  29. package/src/dashboard/panels/quick-actions.js +133 -0
  30. package/src/dashboard/panels/sessions.js +267 -0
  31. package/src/dashboard/panels/shares.js +280 -0
  32. package/src/dashboard/panels/stats.js +165 -0
  33. package/src/dashboard/panels/updates.js +156 -0
  34. package/src/dashboard/panels/uptime.js +115 -0
  35. package/src/dashboard/panels.js +53 -0
  36. package/src/dashboard/server.js +390 -0
  37. package/src/dashboard/session-store.js +47 -0
  38. package/src/dashboard/totp.js +103 -0
  39. package/src/dashboard/ui.js +454 -0
  40. package/src/doctor.js +342 -0
  41. package/src/edit.js +135 -0
  42. package/src/health-observer.js +81 -0
  43. package/src/history.js +145 -0
  44. package/src/hooks.js +256 -0
  45. package/src/naming.js +38 -0
  46. package/src/open.js +67 -0
  47. package/src/pending.js +72 -0
  48. package/src/process.js +95 -0
  49. package/src/project-form.js +134 -0
  50. package/src/project.js +114 -0
  51. package/src/prune.js +99 -0
  52. package/src/rename-state.js +39 -0
  53. package/src/restart.js +35 -0
  54. package/src/service.js +173 -0
  55. package/src/share-expiry.js +55 -0
  56. package/src/share.js +275 -0
  57. package/src/shell-words.js +284 -0
  58. package/src/stats.js +180 -0
  59. package/src/transfer.js +124 -0
  60. package/src/update.js +254 -0
  61. package/src/uptime.js +91 -0
  62. package/src/watch.js +263 -0
  63. package/src/zones.js +102 -0
@@ -0,0 +1,79 @@
1
+ import { createHash, createHmac, randomBytes, timingSafeEqual } from 'node:crypto';
2
+
3
+ export const MIN_PASSWORD_LENGTH = 12;
4
+
5
+ // Constant-time password check. Both sides are hashed first so the compare
6
+ // never leaks length and timingSafeEqual always gets equal-sized buffers.
7
+ export function passwordMatches(given, expected) {
8
+ if (typeof expected !== 'string' || expected.length === 0) return false;
9
+ const a = createHash('sha256').update(String(given ?? ''), 'utf8').digest();
10
+ const b = createHash('sha256').update(expected, 'utf8').digest();
11
+ return timingSafeEqual(a, b);
12
+ }
13
+
14
+ // Signing key = HMAC(per-process secret, password): restarting the server or
15
+ // changing the password invalidates every session.
16
+ export function sessionKey(secret, password) {
17
+ return createHmac('sha256', secret).update(`burrow-session\0${password}`).digest();
18
+ }
19
+
20
+ const mac = (key, body) => createHmac('sha256', key).update(body).digest();
21
+
22
+ export function signSession(key, ttlMs, now = Date.now()) {
23
+ const exp = now + ttlMs;
24
+ const id = randomBytes(18).toString('base64url');
25
+ const body = `${exp}.${id}`;
26
+ return { value: `${body}.${mac(key, body).toString('base64url')}`, id, exp };
27
+ }
28
+
29
+ // Returns the session id when the cookie is authentic and unexpired, else null.
30
+ export function verifySession(key, value, now = Date.now()) {
31
+ if (typeof value !== 'string') return null;
32
+ const parts = value.split('.');
33
+ if (parts.length !== 3) return null;
34
+ const [exp, id, sig] = parts;
35
+ if (!/^\d+$/.test(exp) || !/^[A-Za-z0-9_-]+$/.test(id) || !/^[A-Za-z0-9_-]+$/.test(sig)) return null;
36
+ const expected = mac(key, `${exp}.${id}`);
37
+ const got = Buffer.from(sig, 'base64url');
38
+ if (got.length !== expected.length || !timingSafeEqual(got, expected)) return null;
39
+ return Number(exp) > now ? id : null;
40
+ }
41
+
42
+ // Fixed-window limiter for login attempts, keyed by client IP.
43
+ export class RateLimiter {
44
+ constructor({ max = 5, windowMs = 15 * 60 * 1000 } = {}) {
45
+ this.max = max;
46
+ this.windowMs = windowMs;
47
+ this.hits = new Map();
48
+ }
49
+ check(key, now = Date.now()) {
50
+ const e = this.hits.get(key);
51
+ if (!e || now - e.start >= this.windowMs) return { allowed: true, retryAfter: 0 };
52
+ if (e.count >= this.max) return { allowed: false, retryAfter: Math.ceil((e.start + this.windowMs - now) / 1000) };
53
+ return { allowed: true, retryAfter: 0 };
54
+ }
55
+ fail(key, now = Date.now()) {
56
+ const e = this.hits.get(key);
57
+ if (!e || now - e.start >= this.windowMs) this.hits.set(key, { start: now, count: 1 });
58
+ else e.count++;
59
+ if (this.hits.size > 10000) {
60
+ for (const [k, v] of this.hits) if (now - v.start >= this.windowMs) this.hits.delete(k);
61
+ }
62
+ }
63
+ reset(key) {
64
+ this.hits.delete(key);
65
+ }
66
+ }
67
+
68
+ export function parseCookies(header = '') {
69
+ const out = {};
70
+ for (const part of header.split(';')) {
71
+ const i = part.indexOf('=');
72
+ if (i < 0) continue;
73
+ const k = part.slice(0, i).trim();
74
+ if (k) out[k] = decodeURIComponent(part.slice(i + 1).trim());
75
+ }
76
+ return out;
77
+ }
78
+
79
+ export const newSecret = () => randomBytes(32);
@@ -0,0 +1,70 @@
1
+ import { readdirSync, statSync, existsSync } from 'node:fs';
2
+ import { stateDir } from '../config.js';
3
+ import { Cloudflare } from '../cloudflare.js';
4
+ import { recordComment, tunnelName } from '../naming.js';
5
+ import { localProjects, runningPid, pidFile, readMeta } from '../process.js';
6
+ import { DASHBOARD_PROJECT } from '../project.js';
7
+ import { recordsEverywhere, zoneErrorCollector, zoneErrorFor } from '../zones.js';
8
+
9
+ function metaProjects() {
10
+ try {
11
+ return readdirSync(stateDir()).filter((f) => f.endsWith('.json')).map((f) => f.slice(0, -5));
12
+ } catch {
13
+ return [];
14
+ }
15
+ }
16
+
17
+ let cache = { at: 0, data: null, error: null };
18
+ export function invalidateCloudflare() {
19
+ cache = { at: 0, data: null, error: null };
20
+ }
21
+
22
+ async function cloudflareState(cfg) {
23
+ if (!(cfg.token && cfg.accountId && cfg.domain)) return { data: null, error: 'Cloudflare not configured' };
24
+ if (Date.now() - cache.at < 10000) return cache;
25
+ try {
26
+ const cf = new Cloudflare({ token: cfg.token, accountId: cfg.accountId, zoneId: cfg.zoneId });
27
+ // One unreadable zone doesn't blank the table: its projects get zoneError instead.
28
+ const zones = zoneErrorCollector();
29
+ const [tunnels, records] = await Promise.all([cf.listTunnels(), recordsEverywhere(cf, cfg, { prefix: 'burrow:', onError: zones.onError })]);
30
+ cache = { at: Date.now(), data: { tunnels: tunnels.filter((t) => t.name.startsWith('burrow-')), records, zoneErrors: zones.list }, error: null };
31
+ } catch (e) {
32
+ cache = { at: Date.now(), data: null, error: e.message };
33
+ }
34
+ return cache;
35
+ }
36
+
37
+ export async function collect(cfg) {
38
+ const cf = await cloudflareState(cfg);
39
+ const names = new Set([...localProjects(), ...metaProjects()]);
40
+ for (const t of cf.data?.tunnels || []) names.add(t.name.slice('burrow-'.length));
41
+ for (const r of cf.data?.records || []) names.add(String(r.comment).slice('burrow:'.length));
42
+ const projects = [...names].sort().map((project) => {
43
+ const meta = readMeta(project);
44
+ const pid = runningPid(project);
45
+ let startedAt = null;
46
+ if (pid) { try { startedAt = statSync(pidFile(project)).mtimeMs; } catch {} }
47
+ const tunnel = cf.data?.tunnels.find((t) => t.name === tunnelName(project)) || null;
48
+ const recs = (cf.data?.records || []).filter((r) => r.comment === recordComment(project)).map((r) => r.name);
49
+ const zoneError = project === DASHBOARD_PROJECT ? null : zoneErrorFor(project, cf.data?.zoneErrors, cfg);
50
+ return {
51
+ project,
52
+ builtIn: project === DASHBOARD_PROJECT,
53
+ hostnames: recs.length ? recs.sort() : meta?.hostnames || [],
54
+ zoneError,
55
+ running: !!pid,
56
+ pid,
57
+ startedAt,
58
+ canUp: project === DASHBOARD_PROJECT || !!(meta?.file && existsSync(meta.file)),
59
+ tunnel: tunnel && {
60
+ id: tunnel.id,
61
+ status: tunnel.status || 'unknown',
62
+ connections: (tunnel.connections || []).map((c) => ({
63
+ colo: c.colo_name, openedAt: c.opened_at, version: c.client_version,
64
+ })),
65
+ },
66
+ };
67
+ });
68
+ const zoneErrors = (cf.data?.zoneErrors || []).map(({ zone, error }) => ({ zone, error }));
69
+ return { projects, cloudflare: { configured: !!cf.data || cf.error !== 'Cloudflare not configured', error: cf.error, zoneErrors }, now: Date.now() };
70
+ }
@@ -0,0 +1,95 @@
1
+ // Log helpers for the dashboard: tails, downloads and a combined stream of every
2
+ // project's cloudflared log (~/.local/state/burrow/<project>.log).
3
+ import { existsSync, statSync, openSync, readSync, closeSync, readdirSync } from 'node:fs';
4
+ import { stateDir } from '../config.js';
5
+ import { logFile } from '../process.js';
6
+
7
+ const TS = /^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(?:\.\d+)?(?:Z|[+-]\d{2}:?\d{2}))/;
8
+
9
+ export function readRange(file, from, to) {
10
+ const fd = openSync(file, 'r');
11
+ try {
12
+ const buf = Buffer.alloc(to - from);
13
+ readSync(fd, buf, 0, buf.length, from);
14
+ return buf.toString('utf8');
15
+ } finally { closeSync(fd); }
16
+ }
17
+
18
+ // The last `bytes` of a file, starting at a line boundary.
19
+ export function readTail(file, bytes) {
20
+ if (!existsSync(file)) return '';
21
+ const size = statSync(file).size;
22
+ const start = Math.max(0, size - bytes);
23
+ let text = readRange(file, start, size);
24
+ if (start > 0) text = text.slice(text.indexOf('\n') + 1);
25
+ return text;
26
+ }
27
+
28
+ // Projects with a log file in the state dir.
29
+ export function logProjects(dir = stateDir()) {
30
+ try {
31
+ return readdirSync(dir).filter((f) => /^[a-z0-9-]+\.log$/.test(f)).map((f) => f.slice(0, -4)).sort();
32
+ } catch {
33
+ return [];
34
+ }
35
+ }
36
+
37
+ // Interleave lines from several logs by their leading timestamp (lines without one
38
+ // stay right after the line before them).
39
+ export function mergeByTime(perProject) {
40
+ const out = [];
41
+ for (const [project, lines] of perProject) {
42
+ let last = 0;
43
+ lines.forEach((line, i) => {
44
+ const m = line.match(TS);
45
+ if (m) last = Date.parse(m[1]) || last;
46
+ out.push({ project, line, t: last, i });
47
+ });
48
+ }
49
+ return out.sort((a, b) => a.t - b.t || (a.project === b.project ? a.i - b.i : a.project.localeCompare(b.project)));
50
+ }
51
+
52
+ const lines = (text) => text.split('\n').map((l) => l.replace(/\r/g, '')).filter((l) => l.length);
53
+
54
+ export function combinedText(projects = logProjects(), bytesEach = 2 * 1024 * 1024) {
55
+ const merged = mergeByTime(projects.map((p) => [p, lines(readTail(logFile(p), bytesEach))]));
56
+ return merged.map((e) => `[${e.project}] ${e.line}`).join('\n') + (merged.length ? '\n' : '');
57
+ }
58
+
59
+ const stamp = () => new Date().toISOString().replace(/[-:]/g, '').replace(/\..*$/, '').replace('T', '-');
60
+ export const downloadName = (what) => `burrow-${what}-${stamp()}.log`;
61
+
62
+ // SSE: `data: {"p": project, "l": line}` for every project's log, backlog first.
63
+ export function streamAll(req, res, headers, { backlogBytes = 16 * 1024, intervalMs = 1000 } = {}) {
64
+ res.writeHead(200, { ...headers, 'Content-Type': 'text/event-stream', Connection: 'keep-alive', 'X-Accel-Buffering': 'no' });
65
+ const send = (project, line) => res.write(`data: ${JSON.stringify({ p: project, l: line })}\n\n`);
66
+ const files = new Map(); // project -> { pos, partial }
67
+ const backlog = [];
68
+ for (const p of logProjects()) {
69
+ const file = logFile(p);
70
+ backlog.push([p, lines(readTail(file, backlogBytes))]);
71
+ files.set(p, { pos: statSync(file).size, partial: '' });
72
+ }
73
+ for (const e of mergeByTime(backlog)) send(e.project, e.line);
74
+ if (!files.size) res.write(`data: ${JSON.stringify({ p: '', l: '(no logs yet)' })}\n\n`);
75
+ const poll = setInterval(() => {
76
+ for (const p of logProjects()) {
77
+ try {
78
+ const file = logFile(p);
79
+ const st = files.get(p) || { pos: 0, partial: '' };
80
+ files.set(p, st);
81
+ const size = statSync(file).size;
82
+ if (size < st.pos) { st.pos = 0; st.partial = ''; send(p, '(log truncated)'); }
83
+ if (size > st.pos) {
84
+ const to = Math.min(size, st.pos + 256 * 1024);
85
+ const parts = (st.partial + readRange(file, st.pos, to)).split('\n');
86
+ st.partial = parts.pop();
87
+ st.pos = to;
88
+ for (const l of parts) send(p, l.replace(/\r/g, ''));
89
+ }
90
+ } catch {}
91
+ }
92
+ }, intervalMs);
93
+ const ping = setInterval(() => res.write(': ping\n\n'), 15000);
94
+ req.on('close', () => { clearInterval(poll); clearInterval(ping); });
95
+ }
@@ -0,0 +1,102 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { openSync, closeSync, readFileSync, writeFileSync, rmSync, mkdirSync, existsSync } from 'node:fs';
3
+ import { join } from 'node:path';
4
+ import { fileURLToPath } from 'node:url';
5
+ import { loadConfig, stateDir } from '../config.js';
6
+ import { isAlive, runningPid, stopConnector } from '../process.js';
7
+ import { DASHBOARD_PROJECT, dashboardProject } from '../project.js';
8
+ import { hostnameFor } from '../naming.js';
9
+ import { MIN_PASSWORD_LENGTH } from './auth.js';
10
+ import { runDashboard } from './server.js';
11
+ import * as commands from '../commands.js';
12
+
13
+ const BIN = fileURLToPath(new URL('../../bin/burrow.js', import.meta.url));
14
+ // Lives in a subdirectory so it is never mistaken for a project pid file.
15
+ const dir = () => join(stateDir(), 'dashboard');
16
+ export const serverPidFile = () => join(dir(), 'server.pid');
17
+ export const serverLogFile = () => join(dir(), 'server.log');
18
+
19
+ const log = (...a) => console.log(...a);
20
+ const portOf = (opts, cfg) => {
21
+ const port = parseInt(opts.port || cfg.dashboardPort, 10);
22
+ if (!(port > 0 && port < 65536)) throw new Error(`Invalid dashboard port "${opts.port || cfg.dashboardPort}"`);
23
+ return port;
24
+ };
25
+
26
+ export function serverPid() {
27
+ try {
28
+ const pid = parseInt(readFileSync(serverPidFile(), 'utf8'), 10);
29
+ return isAlive(pid, 'burrow') ? pid : null;
30
+ } catch {
31
+ return null;
32
+ }
33
+ }
34
+
35
+ function requirePassword(cfg) {
36
+ if (!cfg.dashboardPassword || cfg.dashboardPassword.length < MIN_PASSWORD_LENGTH) {
37
+ throw new Error(
38
+ `Set BURROW_DASHBOARD_PASSWORD (at least ${MIN_PASSWORD_LENGTH} characters) in ${cfg.path} first.`
39
+ );
40
+ }
41
+ }
42
+
43
+ export async function foreground(opts) {
44
+ const cfg = loadConfig();
45
+ requirePassword(cfg);
46
+ await runDashboard({ port: portOf(opts, cfg), host: opts.host || '127.0.0.1' });
47
+ }
48
+
49
+ export async function up(opts) {
50
+ const cfg = loadConfig();
51
+ const port = portOf(opts, cfg);
52
+ const host = opts.host || '127.0.0.1';
53
+ const dry = !!opts.dryRun;
54
+ if (!dry) requirePassword(cfg);
55
+ const pid = serverPid();
56
+ if (dry) {
57
+ log(`[dry-run] ${pid ? `dashboard already running (pid ${pid})` : `would start dashboard on http://${host}:${port}, log ${serverLogFile()}`}`);
58
+ } else if (pid) {
59
+ log(`Dashboard already running (pid ${pid})`);
60
+ } else {
61
+ mkdirSync(dir(), { recursive: true, mode: 0o700 });
62
+ const out = openSync(serverLogFile(), 'a', 0o600);
63
+ const child = spawn(process.execPath, [BIN, 'dashboard', '--port', String(port), '--host', host], {
64
+ detached: true, stdio: ['ignore', out, out], env: process.env,
65
+ });
66
+ closeSync(out);
67
+ child.unref();
68
+ writeFileSync(serverPidFile(), String(child.pid), { mode: 0o600 });
69
+ await new Promise((r) => setTimeout(r, 800));
70
+ if (!isAlive(child.pid, 'burrow')) {
71
+ rmSync(serverPidFile(), { force: true });
72
+ throw new Error(`Dashboard exited right away; see ${serverLogFile()}`);
73
+ }
74
+ log(`Dashboard started on http://${host}:${port} (pid ${child.pid}), log ${serverLogFile()}`);
75
+ }
76
+ if (opts.tunnel === false) return;
77
+ await commands.up(DASHBOARD_PROJECT, { dryRun: dry });
78
+ }
79
+
80
+ export async function down() {
81
+ const pid = serverPid();
82
+ if (pid) {
83
+ process.kill(pid, 'SIGTERM');
84
+ for (let i = 0; i < 25 && isAlive(pid, 'burrow'); i++) await new Promise((r) => setTimeout(r, 200));
85
+ if (isAlive(pid, 'burrow')) process.kill(pid, 'SIGKILL');
86
+ log(`Dashboard stopped (pid ${pid})`);
87
+ } else log('Dashboard was not running');
88
+ rmSync(serverPidFile(), { force: true });
89
+ const c = await stopConnector(DASHBOARD_PROJECT);
90
+ log(c ? `Dashboard tunnel connector stopped (pid ${c})` : 'Dashboard tunnel connector was not running');
91
+ }
92
+
93
+ export function status() {
94
+ const cfg = loadConfig();
95
+ const pid = serverPid();
96
+ log(`Server: ${pid ? `running (pid ${pid}) on port ${cfg.dashboardPort}` : 'stopped'}`);
97
+ const c = runningPid(DASHBOARD_PROJECT);
98
+ log(`Tunnel connector: ${c ? `running (pid ${c})` : 'stopped'}`);
99
+ if (cfg.domain) log(`URL: https://${hostnameFor(DASHBOARD_PROJECT, dashboardProject(cfg.dashboardPort).services[0], cfg.domain)}`);
100
+ log(`Password: ${cfg.dashboardPassword ? 'set' : 'NOT set (BURROW_DASHBOARD_PASSWORD)'}`);
101
+ if (existsSync(serverLogFile())) log(`Log: ${serverLogFile()}`);
102
+ }
@@ -0,0 +1,50 @@
1
+ # Dashboard panels
2
+
3
+ Every `*.js` file in this directory is loaded by the dashboard at start-up (sorted by
4
+ `order`, then file name). A panel adds a feature without editing the core files, so
5
+ features can be developed and merged independently. All exports are optional:
6
+
7
+ ```js
8
+ export const order = 50;
9
+
10
+ // HTML added to the page. Slot names: see SLOTS in ../panels.js.
11
+ // rowActions are plain <button>s shown as items of the row's "⋯" menu (above Destroy), so
12
+ // a panel never makes the table wider; keep labels short ("Edit", "Stats", "Restart").
13
+ // rowCols cells should carry data-label="…": it's shown in front of the cell when rows
14
+ // become cards on small screens (where the table header is hidden).
15
+ // toolbar items are <li><button>…</button></li> listed in the top bar's "More" menu (one
16
+ // per panel that opens a section). toolbarMain is for the few items that must stay visible
17
+ // in the top bar (a status, "New project", buttons that only show in some states); keep it
18
+ // small so the top bar fits on one row at 1280px.
19
+ // rowBadges wrap under the project name, so keep them to one short word.
20
+ export const html = { toolbar: '<li>…</li>', sections: '<article>…</article>' };
21
+
22
+ // Browser JS, served in /panels.js after /app.js. It registers a mixin that is merged
23
+ // into the Alpine "dashboard" component. init() runs once; onLoad(data) runs after
24
+ // every /api/tunnels refresh. Helpers from app.js: post(url, body), getJson(url), ago(ms).
25
+ export const js = `burrowPanel(function () { return { … }; });`;
26
+
27
+ export const css = '.my-panel{…}';
28
+
29
+ // Extra vendored files: URL -> { pkg: '<npm package path>', type }.
30
+ export const vendor = { '/vendor/thing.js': { pkg: 'thing/dist/thing.min.js', type: 'text/javascript; charset=utf-8' } };
31
+
32
+ // Add fields to each project row of GET /api/tunnels.
33
+ export async function enrich(projects, ctx) {}
34
+
35
+ // Handle a request. Runs only for signed-in sessions, and POSTs already carry the
36
+ // X-Burrow CSRF header. Return true when the request was answered.
37
+ export async function route(ctx) { return false; }
38
+
39
+ // Background work that should run with no browser open (e.g. timers). Called once when the
40
+ // server starts listening, with { log, events, loadConfig, invalidate, runCli, collect };
41
+ // return a function that stops it (called when the server closes). unref() your timers.
42
+ export function start(ctx) { return () => {}; }
43
+ ```
44
+
45
+ `ctx` has `req`, `res`, `method`, `path`, `url` (URL), `json(status, obj)`, `send(status, body, type, headers)`,
46
+ `readJson(limit)`, `runCli(args)`, `withBusy(project, fn)` (409 when the project is busy), `clientIp`,
47
+ `loadConfig()`, `invalidate()` (drop the cached Cloudflare state), `events`, `log`.
48
+
49
+ Every panel uses the same CSP-safe Alpine build: no inline scripts, no `eval`, and
50
+ expressions in the HTML stay simple (property reads and method calls).
@@ -0,0 +1,218 @@
1
+ // Panel: Cloudflare Access per service. Shows which services are private (behind Access),
2
+ // whether that's applied in Cloudflare yet, and toggles `private:` / `allow:` in the
3
+ // project's tunnel.yml (edited in place, so comments and other keys stay). Access apps are
4
+ // created or removed by `burrow up`, which the panel can run right away. Services stay
5
+ // public unless you opt in; making a service public again needs an explicit confirmation.
6
+ import { existsSync, readFileSync, writeFileSync } from 'node:fs';
7
+ import YAML from 'yaml';
8
+ import { assertLabel } from '../../naming.js';
9
+ import { parseProject, hostnames, DASHBOARD_PROJECT } from '../../project.js';
10
+ import { readMeta, runningPid } from '../../process.js';
11
+ import { isShare } from '../../share.js';
12
+ import { accessStateFile, parseEmails, privateHosts, validAllow } from '../../access.js';
13
+
14
+ export const order = 45;
15
+
16
+ function projectFile(project) {
17
+ if (project === DASHBOARD_PROJECT || isShare(project)) return null;
18
+ const file = readMeta(project)?.file;
19
+ return file && existsSync(file) ? file : null;
20
+ }
21
+ function appliedApps(project) {
22
+ try { return JSON.parse(readFileSync(accessStateFile(project), 'utf8')).apps || []; } catch { return []; }
23
+ }
24
+ const domainOf = (proj, cfg) => proj.domain || cfg.domain;
25
+
26
+ // [{ service, hostname, private, allow, effective, applied }] for a project's tunnel.yml.
27
+ export function accessView(project, cfg) {
28
+ const file = projectFile(project);
29
+ if (!file) return null;
30
+ const proj = parseProject(readFileSync(file, 'utf8'), file);
31
+ const domain = domainOf(proj, cfg);
32
+ const hosts = domain ? hostnames(proj, domain) : proj.services.map(() => ({ hostname: null }));
33
+ const applied = appliedApps(project);
34
+ const defaults = parseEmails(cfg.accessEmails);
35
+ const services = proj.services.map((s, i) => ({
36
+ service: s.name,
37
+ hostname: hosts[i].hostname,
38
+ private: !!s.private,
39
+ allow: s.allow || [],
40
+ effective: s.private ? (s.allow?.length ? s.allow : defaults) : [],
41
+ applied: applied.some((a) => a.name === `burrow:${project}:${s.name}`),
42
+ }));
43
+ return { project, file, services, defaults, pending: services.some((s) => s.private !== s.applied) };
44
+ }
45
+
46
+ // Apply [{ service, private, allow? }] to the tunnel.yml text. Returns { text, toPublic }.
47
+ export function applyAccess(text, changes, cfg, source = 'tunnel.yml') {
48
+ const before = parseProject(text, source);
49
+ const doc = YAML.parseDocument(text);
50
+ const seq = doc.get('services');
51
+ const items = seq?.items || [];
52
+ const toPublic = [];
53
+ for (const c of changes) {
54
+ const name = String(c?.service ?? '');
55
+ const node = items.find((it) => YAML.isMap(it) && String(it.get('name')) === name);
56
+ if (!node) throw new Error(`no service "${name}" in ${source}`);
57
+ const was = before.services.find((s) => s.name === name);
58
+ if (c.private === true) {
59
+ node.set('private', true);
60
+ const allow = parseEmails(c.allow);
61
+ const bad = allow.filter((e) => !validAllow(e));
62
+ if (bad.length) throw new Error(`invalid allow entries ${bad.join(', ')} (use emails or @domain)`);
63
+ if (allow.length) node.set('allow', doc.createNode(allow, { flow: true }));
64
+ else node.delete('allow');
65
+ } else if (c.private === false) {
66
+ if (was?.private) toPublic.push(name);
67
+ node.delete('private');
68
+ node.delete('allow');
69
+ } else throw new Error('private must be true or false');
70
+ }
71
+ const out = doc.toString({ lineWidth: 0 });
72
+ const proj = parseProject(out, source); // same rules as `burrow up`
73
+ const domain = domainOf(proj, cfg);
74
+ privateHosts(proj, domain ? hostnames(proj, domain) : proj.services.map(() => ({ hostname: '' })), cfg);
75
+ return { text: out, toPublic };
76
+ }
77
+
78
+ export async function enrich(projects, ctx) {
79
+ const cfg = ctx.loadConfig();
80
+ for (const p of projects) {
81
+ try {
82
+ const v = accessView(p.project, cfg);
83
+ if (!v) continue;
84
+ p.accessEditable = true;
85
+ p.privateCount = v.services.filter((s) => s.private).length;
86
+ p.accessPending = v.pending;
87
+ } catch { /* invalid tunnel.yml: the row shows other errors */ }
88
+ }
89
+ }
90
+
91
+ export async function route(ctx) {
92
+ const m = ctx.path.match(/^\/api\/access\/([^/]+)$/);
93
+ if (!m) return false;
94
+ const project = m[1];
95
+ try { assertLabel(project, 'project'); } catch { return ctx.json(400, { error: 'bad project' }) ?? true; }
96
+ const cfg = ctx.loadConfig();
97
+ let view;
98
+ try { view = accessView(project, cfg); } catch (e) { return ctx.json(422, { error: e.message }) ?? true; }
99
+ if (!view) return ctx.json(404, { error: `${project} has no remembered tunnel.yml` }) ?? true;
100
+ if (ctx.method === 'GET') return ctx.json(200, { ...view, running: !!runningPid(project) }) ?? true;
101
+ if (ctx.method !== 'POST') return false;
102
+ const body = await ctx.readJson();
103
+ if (!body) return ctx.json(400, { error: 'invalid JSON' }) ?? true;
104
+ if (!Array.isArray(body.services) || !body.services.length || body.services.length > 50) {
105
+ return ctx.json(400, { error: 'services must be a non-empty list' }) ?? true;
106
+ }
107
+ let next;
108
+ try { next = applyAccess(readFileSync(view.file, 'utf8'), body.services, cfg, view.file); } catch (e) {
109
+ return ctx.json(400, { error: e.message }) ?? true;
110
+ }
111
+ if (next.toPublic.length && body.confirmPublic !== true) {
112
+ return ctx.json(400, { error: `confirm making ${next.toPublic.join(', ')} public (confirmPublic: true)`, toPublic: next.toPublic }) ?? true;
113
+ }
114
+ const r = await ctx.withBusy(project, async () => {
115
+ writeFileSync(view.file, next.text);
116
+ ctx.log(`access ${project}: ${body.services.map((s) => `${s.service}=${s.private ? 'private' : 'public'}`).join(' ')} (requested from ${ctx.clientIp})`);
117
+ ctx.events.emit('event', { action: 'access', project, ok: true, source: 'dashboard', detail: next.toPublic.length ? `public: ${next.toPublic.join(', ')}` : 'saved' });
118
+ const out = { ok: true, saved: true, file: view.file, toPublic: next.toPublic };
119
+ if (body.up !== true) return { ...out, ...accessView(project, cfg) };
120
+ const run = await ctx.runCli(['up', project]);
121
+ ctx.invalidate();
122
+ return { ...out, ...accessView(project, cfg), ok: run.ok, output: run.output };
123
+ });
124
+ if (!r) return ctx.json(409, { error: `${project} is busy` }) ?? true;
125
+ ctx.json(r.ok ? 200 : 500, r);
126
+ return true;
127
+ }
128
+
129
+ export const html = {
130
+ rowBadges: '<span class="badge" x-show="hasPrivate(p)" :class="accessBadgeClass(p)" :title="accessBadgeTitle(p)" x-text="accessBadge(p)"></span>',
131
+ rowActions: '<button class="secondary outline" x-show="canAccess(p)" @click="openAccess(p)">Access</button>',
132
+ dialogs: `
133
+ <dialog :open="accessOpen" class="access-dialog">
134
+ <article>
135
+ <header><strong>Cloudflare Access: <span x-text="accessProject"></span></strong></header>
136
+ <p><small class="muted">Private services ask visitors to sign in with an allowed email (Cloudflare one-time PIN) before the request reaches your app. Public is the default.</small></p>
137
+ <template x-for="s in accessRows" :key="s.service">
138
+ <div class="access-row">
139
+ <label><input type="checkbox" role="switch" x-model="s.private"> <code x-text="s.hostname"></code></label>
140
+ <small class="badge" :class="appliedClass(s)" x-text="appliedText(s)"></small>
141
+ <input type="text" x-show="s.private" x-model="s.allowText" :placeholder="allowPlaceholder" aria-label="Allowed emails or @domains" autocomplete="off">
142
+ </div>
143
+ </template>
144
+ <label><input type="checkbox" x-model="accessUp"> Apply now (<code>burrow up</code>)</label>
145
+ <p class="error" x-show="hasAccessError" x-text="accessError"></p>
146
+ <div x-show="hasToPublic" class="access-confirm">
147
+ <p><strong>These become public:</strong> anyone with the link can reach them.</p>
148
+ <ul><template x-for="h in toPublicHosts" :key="h"><li><code x-text="h"></code></li></template></ul>
149
+ <label><input type="checkbox" x-model="accessConfirm"> I understand, make them public</label>
150
+ </div>
151
+ <footer>
152
+ <button class="secondary" @click="closeAccess">Cancel</button>
153
+ <button :class="saveAccessClass" :disabled="cannotSaveAccess" :aria-busy="accessBusy" @click="saveAccess">Save</button>
154
+ </footer>
155
+ </article>
156
+ </dialog>`,
157
+ };
158
+
159
+ export const css = `
160
+ .access-dialog article{width:min(620px,100%)}
161
+ .access-row{display:grid;grid-template-columns:1fr auto;gap:.2rem .6rem;align-items:center;margin-bottom:.6rem}
162
+ .access-row label{margin:0}.access-row input[type=text]{grid-column:1/-1;margin:0}
163
+ .access-confirm{border-left:3px solid #dc2626;padding-left:.75rem;margin:.5rem 0}
164
+ `;
165
+
166
+ export const js = `
167
+ burrowPanel(function () {
168
+ return {
169
+ accessOpen: false, accessProject: '', accessRows: [], accessDefaults: [], accessUp: false, accessBusy: false,
170
+ accessError: '', accessConfirm: false,
171
+ get hasAccessError() { return this.accessError.length > 0; },
172
+ get allowPlaceholder() { return this.accessDefaults.length ? 'Default: ' + this.accessDefaults.join(', ') : 'ana@example.dev, @example.dev'; },
173
+ get toPublicHosts() { return this.accessRows.filter(function (s) { return s.wasPrivate && !s.private; }).map(function (s) { return s.hostname || s.service; }); },
174
+ get hasToPublic() { return this.toPublicHosts.length > 0; },
175
+ get cannotSaveAccess() { return this.accessBusy || (this.hasToPublic && !this.accessConfirm); },
176
+ get saveAccessClass() { return this.hasToPublic ? 'danger' : ''; },
177
+ canAccess: function (p) { return !!p.accessEditable; },
178
+ hasPrivate: function (p) { return p.privateCount > 0; },
179
+ accessBadge: function (p) { return p.accessPending ? 'access: pending' : 'private ' + p.privateCount; },
180
+ accessBadgeClass: function (p) { return p.accessPending ? 'warn' : 'ok'; },
181
+ accessBadgeTitle: function (p) { return p.accessPending ? 'Access changes apply on the next burrow up' : 'Behind Cloudflare Access'; },
182
+ appliedText: function (s) {
183
+ if (s.private === s.applied) return s.applied ? 'protected' : 'public';
184
+ return s.private ? 'not applied yet' : 'still protected';
185
+ },
186
+ appliedClass: function (s) { return s.private === s.applied ? (s.applied ? 'ok' : '') : 'warn'; },
187
+ openAccess: async function (p) {
188
+ this.accessError = ''; this.accessConfirm = false;
189
+ try {
190
+ var j = await getJson('/api/access/' + encodeURIComponent(p.project));
191
+ this.accessProject = p.project; this.accessDefaults = j.defaults; this.accessUp = !!j.running;
192
+ this.accessRows = j.services.map(function (s) {
193
+ return { service: s.service, hostname: s.hostname, private: s.private, wasPrivate: s.private, applied: s.applied, allowText: s.allow.join(', ') };
194
+ });
195
+ this.accessOpen = true;
196
+ } catch (e) { this.showToast('✗ ' + e.message, false); }
197
+ },
198
+ closeAccess: function () { this.accessOpen = false; },
199
+ saveAccess: async function () {
200
+ if (this.cannotSaveAccess) return;
201
+ this.accessBusy = true; this.accessError = '';
202
+ try {
203
+ var r = await post('/api/access/' + encodeURIComponent(this.accessProject), {
204
+ services: this.accessRows.map(function (s) { return { service: s.service, private: !!s.private, allow: s.allowText }; }),
205
+ up: this.accessUp, confirmPublic: this.accessConfirm,
206
+ });
207
+ if (r.status === 401) { location.assign('/login'); return; }
208
+ var j = await r.json().catch(function () { return {}; });
209
+ if (j.saved) {
210
+ this.accessOpen = false;
211
+ this.showToast((j.ok ? '✓ ' : '✗ ') + 'Access saved for ' + this.accessProject + (this.accessUp ? '' : ' (applies on the next up)') + (j.output ? '\\n' + j.output : ''), !!j.ok, 12000);
212
+ this.load();
213
+ } else this.accessError = j.error || ('HTTP ' + r.status);
214
+ } catch (e) { this.accessError = 'Network error'; } finally { this.accessBusy = false; }
215
+ },
216
+ };
217
+ });
218
+ `;