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.
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 +131 -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,134 @@
1
+ // tunnel.yml <-> the dashboard's project form. New files are rendered by add.js;
2
+ // existing files are edited in place with the YAML document API, so comments and
3
+ // keys the form doesn't know about (hooks, domain, private, originRequest…) are kept.
4
+ import YAML from 'yaml';
5
+ import { assertDomain, assertLabel } from './naming.js';
6
+ import { parseProject } from './project.js';
7
+ import { buildDoc, renderYaml, toUrl, slug } from './add.js';
8
+
9
+ const str = (v) => String(v ?? '').trim();
10
+
11
+ // Form shape: { project, domain, app, paths: [{ path, target }], services: [{ name, target }], autostart }
12
+ // domain: '' = BURROW_DOMAIN (no `domain:` key); undefined = leave the file's `domain:` alone.
13
+ export function normalizeDomain(v) {
14
+ if (v === undefined || v === null) return undefined;
15
+ const d = str(v).toLowerCase().replace(/\.$/, '');
16
+ if (!d) return '';
17
+ try { assertDomain(d); } catch { throw new Error(`invalid domain "${str(v)}" (e.g. example.org)`); }
18
+ return d;
19
+ }
20
+
21
+ export function normalizeForm(raw) {
22
+ if (!raw || typeof raw !== 'object') throw new Error('form must be an object');
23
+ const project = str(raw.project);
24
+ assertLabel(project, 'project name');
25
+ const rows = (v, what) => {
26
+ if (v === undefined) return [];
27
+ if (!Array.isArray(v) || v.length > 50) throw new Error(`${what} must be a list (at most 50)`);
28
+ return v;
29
+ };
30
+ const paths = rows(raw.paths, 'paths')
31
+ .map((p) => ({ path: str(p?.path), target: str(p?.target) }))
32
+ .filter((p) => p.path || p.target);
33
+ for (const p of paths) {
34
+ if (!p.path || !p.target) throw new Error('every path needs a path and a port or URL');
35
+ if (!p.path.startsWith('/') && !p.path.startsWith('^')) throw new Error(`path "${p.path}" must start with /`);
36
+ }
37
+ const services = rows(raw.services, 'services')
38
+ .map((s) => ({ name: slug(s?.name), target: str(s?.target) }))
39
+ .filter((s) => s.name || s.target);
40
+ for (const s of services) {
41
+ if (!s.name || !s.target) throw new Error('every sub-service needs a name and a port or URL');
42
+ if (s.name === 'app') throw new Error('"app" is the root service; use the App field');
43
+ }
44
+ const app = str(raw.app);
45
+ if (!app && !services.length) throw new Error('add an app port or at least one sub-service');
46
+ if (!app && paths.length) throw new Error('paths need an app port or URL');
47
+ const domain = normalizeDomain(raw.domain);
48
+ return { project, ...(domain === undefined ? {} : { domain }), app, paths, services, autostart: raw.autostart === true };
49
+ }
50
+
51
+ const target = (url) => {
52
+ const m = String(url).match(/^http:\/\/localhost:(\d+)$/);
53
+ return m ? m[1] : String(url);
54
+ };
55
+
56
+ // Read a tunnel.yml into the form. The root service is the form's "app".
57
+ export function formFromText(text, source = 'tunnel.yml') {
58
+ const proj = parseProject(text, source);
59
+ const root = proj.services.find((s) => s.root);
60
+ const raw = YAML.parse(text) || {};
61
+ const list = (raw.services || []).filter((s) => s && typeof s === 'object');
62
+ const explicit = list.some((s) => s.root === true);
63
+ const rawRoot = list.find((s) => (explicit ? s.root === true : s.name === 'app'));
64
+ return {
65
+ project: proj.project,
66
+ domain: proj.domain || '',
67
+ app: root ? target(root.url) : '',
68
+ paths: (rawRoot?.paths || []).map((p) => ({ path: String(p.path), target: target(p.url) })),
69
+ services: proj.services.filter((s) => !s.root).map((s) => ({ name: s.name, target: target(s.url) })),
70
+ autostart: proj.autostart,
71
+ };
72
+ }
73
+
74
+ // New file: same output as `burrow add`, plus autostart.
75
+ export function renderNew(form) {
76
+ const f = normalizeForm(form);
77
+ const doc = buildDoc({
78
+ project: f.project, app: f.app, paths: f.paths.map((p) => [p.path, p.target]),
79
+ services: f.services.map((s) => [s.name, s.target]),
80
+ });
81
+ if (f.autostart) doc.autostart = true;
82
+ return renderYaml(f.domain ? { project: doc.project, domain: f.domain, ...doc } : doc);
83
+ }
84
+
85
+ // Existing file: replace services/autostart, keep everything else. Extra keys on a
86
+ // service (originRequest, private, …) survive when the service keeps its name.
87
+ export function renderEdit(text, form, source = 'tunnel.yml') {
88
+ const f = normalizeForm(form);
89
+ const before = parseProject(text, source);
90
+ if (f.project !== before.project) throw new Error(`renaming is not supported here (${before.project} -> ${f.project})`);
91
+ const doc = YAML.parseDocument(text);
92
+ const old = (doc.toJS().services || []).filter((s) => s && typeof s === 'object');
93
+ const oldRoot = old.find((s) => s.root === true) || old.find((s) => s.name === 'app');
94
+ const keep = (prev, fields) => {
95
+ const out = { ...(prev || {}) };
96
+ for (const k of ['name', 'url', 'paths', 'root']) delete out[k];
97
+ return { ...fields, ...out };
98
+ };
99
+ const services = [];
100
+ if (f.app) {
101
+ const svc = { name: oldRoot?.name || 'app', url: toUrl(f.app) };
102
+ if (oldRoot && oldRoot.name !== 'app') svc.root = true;
103
+ if (f.paths.length) {
104
+ svc.paths = f.paths.map((p) => {
105
+ const prev = (oldRoot?.paths || []).find((x) => String(x.path) === p.path);
106
+ return { ...(prev || {}), path: p.path, url: toUrl(p.target) };
107
+ });
108
+ }
109
+ services.push(keep(oldRoot, svc));
110
+ }
111
+ for (const s of f.services) {
112
+ services.push(keep(old.find((o) => o !== oldRoot && o.name === s.name), { name: s.name, url: toUrl(s.target) }));
113
+ }
114
+ doc.set('services', doc.createNode(services));
115
+ if (f.autostart) doc.set('autostart', true);
116
+ else doc.delete('autostart');
117
+ if (f.domain) doc.set('domain', f.domain);
118
+ else if (f.domain === '') doc.delete('domain');
119
+ const out = doc.toString({ lineWidth: 0 });
120
+ parseProject(out, source); // same errors as `burrow up`
121
+ return out;
122
+ }
123
+
124
+ // Rename: only the `project:` key changes; comments, services and other keys stay.
125
+ export function renameText(text, to, source = 'tunnel.yml') {
126
+ assertLabel(to, 'new project name');
127
+ const before = parseProject(text, source);
128
+ if (before.project === to) throw new Error(`${source} is already called ${to}`);
129
+ const doc = YAML.parseDocument(text);
130
+ doc.set('project', to);
131
+ const out = doc.toString({ lineWidth: 0 });
132
+ parseProject(out, source);
133
+ return out;
134
+ }
package/src/project.js ADDED
@@ -0,0 +1,114 @@
1
+ import { readFileSync, existsSync } from 'node:fs';
2
+ import { resolve } from 'node:path';
3
+ import YAML from 'yaml';
4
+ import { assertDomain, assertLabel, hostnameFor } from './naming.js';
5
+
6
+ export const DEFAULT_FILE = 'tunnel.yml';
7
+
8
+ // The dashboard's own tunnel: burrow.<domain> -> the local dashboard port.
9
+ export const DASHBOARD_PROJECT = 'burrow';
10
+ export function dashboardProject(port = 7070) {
11
+ return {
12
+ project: DASHBOARD_PROJECT,
13
+ services: [{ name: 'app', root: true, url: `http://localhost:${port}`, paths: [] }],
14
+ source: '(built-in dashboard)',
15
+ };
16
+ }
17
+
18
+ export function findProjectFile(file) {
19
+ const p = resolve(file || DEFAULT_FILE);
20
+ return existsSync(p) ? p : null;
21
+ }
22
+
23
+ export function loadProjectFile(path) {
24
+ return parseProject(readFileSync(path, 'utf8'), path);
25
+ }
26
+
27
+ function assertUrl(url, where) {
28
+ if (typeof url !== 'string') throw new Error(`${where}: "url" is required`);
29
+ if (/^(http_status:\d{3}|hello_world)$/.test(url)) return;
30
+ let u;
31
+ try { u = new URL(url); } catch { throw new Error(`${where}: invalid url "${url}"`); }
32
+ if (!['http:', 'https:', 'tcp:', 'ssh:', 'unix:', 'ws:', 'wss:'].includes(u.protocol)) {
33
+ throw new Error(`${where}: unsupported url scheme in "${url}"`);
34
+ }
35
+ }
36
+
37
+ // Plain prefixes like /auth/v1 become an anchored regex matching the prefix
38
+ // and anything under it. Values starting with ^ are passed through as regex.
39
+ export function pathRegex(path) {
40
+ if (typeof path !== 'string' || !path) throw new Error('path must be a non-empty string');
41
+ if (path.startsWith('^')) return path;
42
+ const clean = '/' + path.replace(/^\/+|\/+$/g, '');
43
+ const escaped = clean.replace(/[.*+?()[\]{}|\\$]/g, '\\$&');
44
+ return `^${escaped}(/.*)?$`;
45
+ }
46
+
47
+ export function parseProject(text, source = 'tunnel.yml') {
48
+ const doc = YAML.parse(text) || {};
49
+ const project = String(doc.project ?? '').trim();
50
+ assertLabel(project, `project name in ${source}`);
51
+ if (project === DASHBOARD_PROJECT) throw new Error(`${source}: "${DASHBOARD_PROJECT}" is reserved for the dashboard`);
52
+ let domain;
53
+ if (doc.domain !== undefined && doc.domain !== null && doc.domain !== '') {
54
+ domain = String(doc.domain).trim().toLowerCase().replace(/\.$/, '');
55
+ try { assertDomain(domain); } catch { throw new Error(`${source}: invalid domain "${doc.domain}" (e.g. domain: example.org)`); }
56
+ }
57
+ if (!Array.isArray(doc.services) || doc.services.length === 0) {
58
+ throw new Error(`${source}: "services" must be a non-empty list`);
59
+ }
60
+ const hasExplicitRoot = doc.services.some((s) => s && s.root === true);
61
+ const seen = new Set();
62
+ const services = doc.services.map((s, i) => {
63
+ const where = `${source}: services[${i}]`;
64
+ if (!s || typeof s !== 'object') throw new Error(`${where} must be a mapping`);
65
+ const name = String(s.name ?? '').trim();
66
+ assertLabel(name, `service name (${where})`);
67
+ const root = hasExplicitRoot ? s.root === true : name === 'app';
68
+ assertUrl(s.url, where);
69
+ const paths = (s.paths || []).map((p, j) => {
70
+ const pw = `${where}.paths[${j}]`;
71
+ if (!p || typeof p !== 'object') throw new Error(`${pw} must be {path, url}`);
72
+ assertUrl(p.url, pw);
73
+ return { path: pathRegex(p.path), url: p.url, ...(p.originRequest ? { originRequest: p.originRequest } : {}) };
74
+ });
75
+ const svc = { name, root, url: s.url, paths };
76
+ if (s.originRequest) svc.originRequest = s.originRequest;
77
+ if (s.private !== undefined && typeof s.private !== 'boolean') throw new Error(`${where}: "private" must be true or false`);
78
+ if (s.private) svc.private = true;
79
+ if (s.allow !== undefined) {
80
+ if (!s.private) throw new Error(`${where}: "allow" only applies with private: true`);
81
+ const allow = (Array.isArray(s.allow) ? s.allow : String(s.allow).split(',')).map((e) => String(e).trim().toLowerCase()).filter(Boolean);
82
+ const bad = allow.filter((e) => !/^[^@\s,]+@[a-z0-9.-]+\.[a-z]{2,}$/.test(e) && !/^@[a-z0-9.-]+\.[a-z]{2,}$/.test(e));
83
+ if (bad.length) throw new Error(`${where}: invalid "allow" entries ${bad.join(', ')} (use emails or @domain)`);
84
+ svc.allow = allow;
85
+ }
86
+ const key = root ? '@root' : name;
87
+ if (seen.has(key)) throw new Error(`${where}: duplicate ${root ? 'root service' : `service "${name}"`}`);
88
+ seen.add(key);
89
+ return svc;
90
+ });
91
+ return { project, services, source, autostart: doc.autostart === true, ...(domain ? { domain } : {}) };
92
+ }
93
+
94
+ export function hostnames(proj, domain) {
95
+ return proj.services.map((s) => ({ service: s.name, hostname: hostnameFor(proj.project, s, domain) }));
96
+ }
97
+
98
+ export function buildIngress(proj, domain) {
99
+ const ingress = [];
100
+ for (const s of proj.services) {
101
+ const hostname = hostnameFor(proj.project, s, domain);
102
+ for (const p of s.paths) {
103
+ const rule = { hostname, path: p.path, service: p.url };
104
+ const origin = p.originRequest || s.originRequest;
105
+ if (origin) rule.originRequest = origin;
106
+ ingress.push(rule);
107
+ }
108
+ const rule = { hostname, service: s.url };
109
+ if (s.originRequest) rule.originRequest = s.originRequest;
110
+ ingress.push(rule);
111
+ }
112
+ ingress.push({ service: 'http_status:404' });
113
+ return ingress;
114
+ }
package/src/prune.js ADDED
@@ -0,0 +1,99 @@
1
+ import { readdirSync } from 'node:fs';
2
+ import { createInterface } from 'node:readline/promises';
3
+ import { loadConfig, requireConfig, stateDir } from './config.js';
4
+ import { Cloudflare } from './cloudflare.js';
5
+ import { tunnelTarget } from './naming.js';
6
+ import { recordsEverywhere, inZone } from './zones.js';
7
+ import { listPending, retryPending } from './pending.js';
8
+
9
+ const TUNNEL_PREFIX = 'burrow-';
10
+ const COMMENT_PREFIX = 'burrow:';
11
+ const log = (...a) => console.log(...a);
12
+
13
+ // Names of projects this machine knows about (state files).
14
+ export function localProjectNames(dir = stateDir()) {
15
+ try {
16
+ return new Set(readdirSync(dir).filter((f) => /\.(json|pid)$/.test(f)).map((f) => f.replace(/\.(json|pid)$/, '')));
17
+ } catch {
18
+ return new Set();
19
+ }
20
+ }
21
+
22
+ // Pure planning step, easy to test.
23
+ // - orphan tunnel: burrow-<p> with no local state for <p> and no live connections
24
+ // - orphan record: burrow:<p> record whose tunnel is missing, points elsewhere,
25
+ // or belongs to an orphan tunnel
26
+ export function findOrphans({ tunnels, records, local, includeActive = false }) {
27
+ const byProject = new Map();
28
+ for (const t of tunnels) if (t.name.startsWith(TUNNEL_PREFIX)) byProject.set(t.name.slice(TUNNEL_PREFIX.length), t);
29
+ const orphanTunnels = [];
30
+ const skipped = [];
31
+ for (const [project, t] of byProject) {
32
+ if (local.has(project)) continue;
33
+ if ((t.connections || []).length && !includeActive) skipped.push(t);
34
+ else orphanTunnels.push(t);
35
+ }
36
+ const doomed = new Set(orphanTunnels.map((t) => t.id));
37
+ const orphanRecords = records.filter((r) => {
38
+ if (!String(r.comment || '').startsWith(COMMENT_PREFIX)) return false;
39
+ const t = byProject.get(r.comment.slice(COMMENT_PREFIX.length));
40
+ return !t || doomed.has(t.id) || r.content !== tunnelTarget(t.id);
41
+ });
42
+ return { orphanTunnels, orphanRecords, skipped };
43
+ }
44
+
45
+ async function confirm(question) {
46
+ if (!process.stdin.isTTY) return false;
47
+ const rl = createInterface({ input: process.stdin, output: process.stdout });
48
+ try { return /^y(es)?$/i.test((await rl.question(`${question} [y/N] `)).trim()); } finally { rl.close(); }
49
+ }
50
+
51
+ export async function prune(opts = {}) {
52
+ const cfg = loadConfig();
53
+ requireConfig(cfg, ['token', 'accountId', 'domain']);
54
+ const cf = new Cloudflare({ token: cfg.token, accountId: cfg.accountId, zoneId: cfg.zoneId });
55
+ // DNS deletions queued by an earlier destroy that couldn't read a zone. They were already
56
+ // asked for, so they're retried without another confirmation.
57
+ const pending = listPending();
58
+ if (pending.length && opts.dryRun) {
59
+ log(`[dry-run] would retry ${pending.length} queued DNS cleanup(s):`);
60
+ for (const e of pending) log(` ${e.project}: records tagged "${e.comment}" in ${e.domain} (queued ${e.at}: ${e.error})`);
61
+ } else if (pending.length) {
62
+ log(`Retrying ${pending.length} queued DNS cleanup(s):`);
63
+ const r = await retryPending(cf, { log: (l) => log(` ${l}`) });
64
+ if (r.left.length) process.exitCode = 1;
65
+ }
66
+ const tunnels = (await cf.listTunnels()).filter((t) => t.name.startsWith(TUNNEL_PREFIX));
67
+ const records = await recordsEverywhere(cf, cfg, {
68
+ prefix: COMMENT_PREFIX,
69
+ onError: (z, e) => console.error(`burrow: warning: couldn't read DNS in ${z.domain} (${e.message}); skipped it.`),
70
+ });
71
+ const { orphanTunnels, orphanRecords, skipped } = findOrphans({
72
+ tunnels, records, local: localProjectNames(), includeActive: !!opts.includeActive,
73
+ });
74
+ const access = await import('./access.js');
75
+ const orphanApps = await access.orphanAccessApps(cf, localProjectNames());
76
+
77
+ for (const t of skipped) {
78
+ log(`Skipping ${t.name}: no local state, but it has ${t.connections.length} live connection(s) (another machine?). Use --include-active to prune it.`);
79
+ }
80
+ if (!orphanTunnels.length && !orphanRecords.length && !orphanApps.length) { log('Nothing to prune.'); return; }
81
+ log('Orphans:');
82
+ for (const t of orphanTunnels) log(` tunnel ${t.name} (${t.id})`);
83
+ for (const r of orphanRecords) log(` DNS ${r.type} ${r.name} -> ${r.content} (${r.comment})`);
84
+ for (const a of orphanApps) log(` Access app ${a.name} (${a.domain})`);
85
+ const apps = orphanApps.length ? ` and ${orphanApps.length} Access app(s)` : '';
86
+ if (opts.dryRun) { log(`[dry-run] would delete ${orphanTunnels.length} tunnel(s) and ${orphanRecords.length} DNS record(s)${apps}`); return; }
87
+ if (!opts.yes && !(await confirm(`Delete ${orphanTunnels.length} tunnel(s) and ${orphanRecords.length} DNS record(s)${apps}?`))) {
88
+ log('Aborted. (Non-interactive shells need --yes.)');
89
+ process.exitCode = 1;
90
+ return;
91
+ }
92
+ for (const r of orphanRecords) { await inZone(cf, r.zoneId).deleteRecord(r.id); log(`Deleted DNS ${r.name}`); }
93
+ for (const t of orphanTunnels) {
94
+ await cf.deleteTunnelConnections(t.id);
95
+ await cf.deleteTunnel(t.id);
96
+ log(`Deleted tunnel ${t.name}`);
97
+ }
98
+ for (const a of orphanApps) { await access.deleteAccessApp(cf, a); log(`Deleted Access app ${a.name}`); }
99
+ }
@@ -0,0 +1,39 @@
1
+ // After a project is renamed (see the dashboard's Rename…), its local files follow it:
2
+ // the cloudflared log, the background pre_up log, and its `burrow watch` state entry.
3
+ // The event history and hook results keep the old name: they describe the past.
4
+ import { appendFileSync, existsSync, mkdirSync, readFileSync, renameSync, rmSync, writeFileSync } from 'node:fs';
5
+ import { dirname } from 'node:path';
6
+ import { logFile } from './process.js';
7
+ import { backgroundLogFile } from './hooks.js';
8
+ import { watchStateFile } from './watch.js';
9
+
10
+ // Move one file. When the target already exists (a log left by an earlier project with the
11
+ // new name), the old file is appended to it, so no line is lost. Returns true when moved.
12
+ function moveFile(from, to) {
13
+ if (!existsSync(from)) return false;
14
+ mkdirSync(dirname(to), { recursive: true, mode: 0o700 });
15
+ if (existsSync(to)) {
16
+ appendFileSync(to, readFileSync(from));
17
+ rmSync(from, { force: true });
18
+ } else renameSync(from, to);
19
+ return true;
20
+ }
21
+
22
+ export function moveProjectState(from, to) {
23
+ if (!from || !to || from === to) return [];
24
+ const moved = [];
25
+ for (const [a, b] of [[logFile(from), logFile(to)], [backgroundLogFile(from), backgroundLogFile(to)]]) {
26
+ if (moveFile(a, b)) moved.push(b);
27
+ }
28
+ try {
29
+ const file = watchStateFile();
30
+ const st = JSON.parse(readFileSync(file, 'utf8'));
31
+ if (st && typeof st === 'object' && st[from]) {
32
+ st[to] = st[from];
33
+ delete st[from];
34
+ writeFileSync(file, JSON.stringify(st, null, 2) + '\n', { mode: 0o600 });
35
+ moved.push(file);
36
+ }
37
+ } catch {}
38
+ return moved;
39
+ }
package/src/restart.js ADDED
@@ -0,0 +1,35 @@
1
+ import * as cmd from './commands.js';
2
+ import { localProjects, runningPid } from './process.js';
3
+ import { isShare, restartShare } from './share.js';
4
+
5
+ // `burrow restart [project]`: re-sync and restart one project's connector.
6
+ // Without a project: every connector that is currently running, shares included
7
+ // (see restartShare for how a share is restarted). `--no-hooks` (opts.hooks === false)
8
+ // skips pre_up/post_up, as with `burrow up --no-hooks`.
9
+ export async function restart(projectArg, opts = {}) {
10
+ if (projectArg && !opts.file && isShare(projectArg)) {
11
+ await restartShare(projectArg, opts);
12
+ return;
13
+ }
14
+ if (projectArg || opts.file) {
15
+ await cmd.up(projectArg, opts);
16
+ return;
17
+ }
18
+ const running = localProjects().filter((p) => runningPid(p));
19
+ if (!running.length) {
20
+ console.log('No running burrow connectors to restart.');
21
+ return;
22
+ }
23
+ let failed = 0;
24
+ for (const project of running) {
25
+ console.log(`== ${project}`);
26
+ try {
27
+ if (isShare(project)) await restartShare(project, { dryRun: opts.dryRun });
28
+ else await cmd.up(project, { dryRun: opts.dryRun, hooks: opts.hooks });
29
+ } catch (e) {
30
+ failed++;
31
+ console.error(`burrow: ${project}: ${e.message}`);
32
+ }
33
+ }
34
+ if (failed) process.exitCode = 1;
35
+ }
package/src/service.js ADDED
@@ -0,0 +1,173 @@
1
+ import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from 'node:fs';
2
+ import { spawnSync } from 'node:child_process';
3
+ import { homedir, userInfo } from 'node:os';
4
+ import { join } from 'node:path';
5
+ import { fileURLToPath } from 'node:url';
6
+ import { loadConfig, stateDir } from './config.js';
7
+ import { loadProjectFile, DASHBOARD_PROJECT } from './project.js';
8
+ import { readMeta } from './process.js';
9
+
10
+ export const UNIT_NAME = 'burrow.service';
11
+ const BIN = fileURLToPath(new URL('../bin/burrow.js', import.meta.url));
12
+ const log = (...a) => console.log(...a);
13
+
14
+ export const unitDir = () =>
15
+ process.env.BURROW_SYSTEMD_DIR || join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'systemd', 'user');
16
+ export const unitPath = () => join(unitDir(), UNIT_NAME);
17
+ const systemctlBin = () => process.env.BURROW_SYSTEMCTL || 'systemctl';
18
+
19
+ function systemctl(...args) {
20
+ const r = spawnSync(systemctlBin(), ['--user', ...args], { encoding: 'utf8' });
21
+ return { ok: !r.error && r.status === 0, out: `${r.stdout || ''}${r.stderr || ''}`.trim(), error: r.error };
22
+ }
23
+
24
+ // systemd-run (to start the boot command in its own transient scope), or null. BURROW_SYSTEMD_RUN
25
+ // overrides the binary; "none" turns it off. Without it the unit behaves as before.
26
+ export function findSystemdRun(env = process.env) {
27
+ const v = env.BURROW_SYSTEMD_RUN;
28
+ if (v === 'none') return null;
29
+ if (v) return v;
30
+ for (const dir of (env.PATH || '').split(':').filter(Boolean)) {
31
+ const f = join(dir, 'systemd-run');
32
+ if (existsSync(f)) return f;
33
+ }
34
+ return null;
35
+ }
36
+
37
+ // systemd quoting for Environment= and Exec lines.
38
+ const q = (s) => (/^[A-Za-z0-9_@%+=:,./-]+$/.test(s) ? s : `"${String(s).replace(/(["\\])/g, '\\$1')}"`);
39
+
40
+ export function renderUnit({ node = process.execPath, bin = BIN, projects = [], env = process.env, systemdRun = findSystemdRun(env) } = {}) {
41
+ const keep = ['PATH', 'BURROW_CONFIG', 'BURROW_STATE_DIR', 'XDG_CONFIG_HOME', 'XDG_STATE_HOME'];
42
+ const envLines = keep.filter((k) => env[k]).map((k) => `Environment=${q(`${k}=${env[k]}`)}`);
43
+ // Run the boot command in its own transient scope so the connectors, dashboard, shares and
44
+ // expiry watchers it starts live outside this unit's cgroup: systemd then has nothing left
45
+ // over to warn about when the unit stops or restarts.
46
+ const scope = systemdRun ? [systemdRun, '--user', '--scope', '--quiet', '--description=burrow: tunnels, dashboard and shares'] : [];
47
+ const start = [...scope, node, bin, 'autostart', ...projects].map(q).join(' ');
48
+ const stop = [node, bin, 'down', '--keep-shares'].map(q).join(' ');
49
+ return `# Generated by "burrow service install". Remove with "burrow service uninstall".
50
+ [Unit]
51
+ Description=burrow: Cloudflare Tunnels for local projects
52
+ Wants=network-online.target
53
+ After=network-online.target
54
+
55
+ [Service]
56
+ Type=oneshot
57
+ RemainAfterExit=yes
58
+ ${envLines.join('\n')}
59
+ ExecStart=${start}
60
+ ExecStop=${stop}
61
+ TimeoutStartSec=300
62
+ # Connectors, the dashboard, shares and their expiry watchers are detached children of the boot
63
+ # command${systemdRun ? ', which runs in its own systemd scope (systemd-run --scope), outside this unit' : ''}.
64
+ # Stopping or restarting the unit runs ExecStop (which stops the projects but keeps shares)
65
+ # and then kills only the main process, not the whole control group.
66
+ KillMode=process
67
+
68
+ [Install]
69
+ WantedBy=default.target
70
+ `;
71
+ }
72
+
73
+ // A unit written by an older burrow, without KillMode=process: stopping or restarting it
74
+ // kills every process it started (including shares). "burrow service install" rewrites it.
75
+ export function unitOutdated(path = unitPath(), systemdRun = findSystemdRun()) {
76
+ return unitProblem(path, systemdRun) !== null;
77
+ }
78
+ // null, 'killmode' (no KillMode=process) or 'scope' (systemd-run is available but the unit
79
+ // doesn't start its boot command in a scope, so systemd warns about leftover processes).
80
+ export function unitProblem(path = unitPath(), systemdRun = findSystemdRun()) {
81
+ let text;
82
+ try { text = readFileSync(path, 'utf8'); } catch { return null; }
83
+ if (!/^KillMode=process$/m.test(text)) return 'killmode';
84
+ if (systemdRun && !/^ExecStart=.*\s--scope\s/m.test(text)) return 'scope';
85
+ return null;
86
+ }
87
+ export const OUTDATED_HINT = 'written by an older burrow: stopping or restarting it also kills shares and the dashboard. Run "burrow service install" to update it.';
88
+ export const SCOPE_HINT = 'its boot command is not started in a systemd scope, so systemd warns about leftover processes (shares, dashboard) when it stops or restarts. Run "burrow service install" to update it.';
89
+ export const outdatedHint = (path = unitPath(), systemdRun = findSystemdRun()) => (unitProblem(path, systemdRun) === 'scope' ? SCOPE_HINT : OUTDATED_HINT);
90
+
91
+ // Projects to bring up at boot: BURROW_AUTOSTART in the config plus every
92
+ // remembered project whose tunnel.yml has `autostart: true`.
93
+ export function autostartProjects(cfg = loadConfig()) {
94
+ const list = (cfg.autostart || '').split(',').map((s) => s.trim()).filter(Boolean);
95
+ let metas = [];
96
+ try { metas = readdirSync(stateDir()).filter((f) => f.endsWith('.json')).map((f) => f.slice(0, -5)); } catch {}
97
+ for (const name of metas.sort()) {
98
+ const file = readMeta(name)?.file;
99
+ if (!file || !existsSync(file)) continue;
100
+ try { if (loadProjectFile(file).autostart) list.push(name); } catch {}
101
+ }
102
+ return [...new Set(list)];
103
+ }
104
+
105
+ export async function autostart(projectArgs = [], opts = {}) {
106
+ const projects = projectArgs.length ? projectArgs : autostartProjects();
107
+ if (!projects.length) {
108
+ log('No autostart projects. Set "autostart: true" in a tunnel.yml or BURROW_AUTOSTART in the config.');
109
+ return;
110
+ }
111
+ if (opts.dryRun) { log(`[dry-run] would bring up: ${projects.join(', ')}`); return; }
112
+ const cmd = await import('./commands.js');
113
+ let failed = 0;
114
+ for (const p of projects) {
115
+ try {
116
+ if (p === DASHBOARD_PROJECT) await (await import('./dashboard/manage.js')).up({});
117
+ else await cmd.up(p, {});
118
+ } catch (e) {
119
+ failed++;
120
+ console.error(`burrow: ${p}: ${e.message}`);
121
+ }
122
+ }
123
+ if (failed) process.exitCode = 1;
124
+ }
125
+
126
+ function lingerHint() {
127
+ const user = userInfo().username;
128
+ const r = spawnSync('loginctl', ['show-user', user, '-p', 'Linger', '--value'], { encoding: 'utf8' });
129
+ if (r.error || r.status !== 0) return null;
130
+ return r.stdout.trim() === 'yes' ? 'yes' : `no (run "loginctl enable-linger ${user}" so it starts at boot without logging in)`;
131
+ }
132
+
133
+ export async function service(action, opts = {}) {
134
+ const projects = (opts.projects || '').split(',').map((s) => s.trim()).filter(Boolean);
135
+ if (action === 'install') {
136
+ const unit = renderUnit({ projects });
137
+ if (opts.dryRun) { log(`[dry-run] would write ${unitPath()}:\n`); log(unit); return; }
138
+ const upgraded = unitOutdated();
139
+ mkdirSync(unitDir(), { recursive: true });
140
+ writeFileSync(unitPath(), unit);
141
+ log(`Wrote ${unitPath()}${upgraded ? ' (replaced an older unit; stopping the service now leaves shares and the dashboard running)' : ''}`);
142
+ for (const args of [['daemon-reload'], ['enable', ...(opts.now ? ['--now'] : []), UNIT_NAME]]) {
143
+ const r = systemctl(...args);
144
+ if (!r.ok) throw new Error(`systemctl --user ${args.join(' ')} failed: ${r.error?.message || r.out}`);
145
+ }
146
+ log(`Enabled ${UNIT_NAME}${opts.now ? ' and started it' : ''}.`);
147
+ const list = projects.length ? projects : autostartProjects();
148
+ log(`Projects at boot: ${list.length ? list.join(', ') : '(none yet; add autostart: true or BURROW_AUTOSTART)'}${projects.length ? '' : ' (re-read at every boot)'}`);
149
+ const linger = lingerHint();
150
+ if (linger && linger !== 'yes') log(`Linger: ${linger}`);
151
+ return;
152
+ }
153
+ if (action === 'uninstall') {
154
+ if (opts.dryRun) { log(`[dry-run] would disable ${UNIT_NAME} and remove ${unitPath()}`); return; }
155
+ systemctl('disable', '--now', UNIT_NAME);
156
+ rmSync(unitPath(), { force: true });
157
+ systemctl('daemon-reload');
158
+ log(`Removed ${UNIT_NAME}. Its stop command stopped the running connectors (shares were kept); start them again with burrow up.`);
159
+ return;
160
+ }
161
+ if (action === 'status') {
162
+ log(`Unit: ${existsSync(unitPath()) ? unitPath() : 'not installed'}`);
163
+ if (unitOutdated()) log(`Outdated: ${outdatedHint()}`);
164
+ log(`Enabled: ${systemctl('is-enabled', UNIT_NAME).out || 'unknown'}`);
165
+ log(`Active: ${systemctl('is-active', UNIT_NAME).out || 'unknown'}`);
166
+ const list = autostartProjects();
167
+ log(`Autostart projects: ${list.length ? list.join(', ') : 'none'}`);
168
+ const linger = lingerHint();
169
+ if (linger) log(`Linger: ${linger}`);
170
+ return;
171
+ }
172
+ throw new Error(`Unknown service action "${action}" (use install, uninstall or status)`);
173
+ }
@@ -0,0 +1,55 @@
1
+ import { spawn } from 'node:child_process';
2
+ import { fileURLToPath } from 'node:url';
3
+ import { readMeta, saveMeta, isAlive } from './process.js';
4
+ import { recordEvent } from './history.js';
5
+
6
+ // Expiry for detached shares that doesn't need the dashboard. Each detached share with an
7
+ // expiresAt gets a tiny watcher process (`burrow _share-expire share-<label>`, detached, no
8
+ // terminal). It sleeps until the expiry, re-reading the share's state file at least every
9
+ // 15 s so an extend, a "never" or a removal is picked up, then removes the share like
10
+ // `burrow down share-<label>` and records "share expired" in the history. A foreground
11
+ // `burrow share` enforces its own expiry instead, and the dashboard's sweeper stays as a
12
+ // second line. After a reboot, `burrow restart` (or autostart) starts the watcher again.
13
+ const BIN = fileURLToPath(new URL('../bin/burrow.js', import.meta.url));
14
+ export const WATCHER_COMMAND = '_share-expire';
15
+
16
+ const pidAlive = (pid) => {
17
+ try { process.kill(pid, 0); return true; } catch (e) { return e.code === 'EPERM'; }
18
+ };
19
+ const ownerRunning = (meta) => !!meta.ownerPid && meta.ownerPid !== process.pid && pidAlive(meta.ownerPid);
20
+ export const watcherAlive = (meta) => !!meta?.expiryPid && isAlive(meta.expiryPid, WATCHER_COMMAND);
21
+
22
+ // Start the watcher for a detached share with an expiry, unless one is already running.
23
+ // Returns its pid, or null when none is needed.
24
+ export function ensureExpiryWatcher(project, { env = process.env } = {}) {
25
+ const meta = readMeta(project);
26
+ if (!meta?.share || !meta.expiresAt || ownerRunning(meta)) return null;
27
+ if (watcherAlive(meta)) return meta.expiryPid;
28
+ const child = spawn(process.execPath, [BIN, WATCHER_COMMAND, project], { detached: true, stdio: 'ignore', env });
29
+ child.unref();
30
+ const now = readMeta(project);
31
+ if (now) saveMeta(project, { ...now, expiryPid: child.pid });
32
+ return child.pid;
33
+ }
34
+
35
+ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
36
+
37
+ // The watcher's loop. `remove(project)` deletes the share (bin uses `burrow down`).
38
+ export async function watchExpiry(project, { remove, poll = Number(process.env.BURROW_SHARE_EXPIRY_POLL_MS) || 15000 } = {}) {
39
+ for (;;) {
40
+ const meta = readMeta(project);
41
+ if (!meta?.share) return 'gone';
42
+ if (meta.expiryPid && meta.expiryPid !== process.pid) return 'superseded';
43
+ const done = (why) => { const { expiryPid, ...rest } = meta; saveMeta(project, rest); return why; };
44
+ if (!meta.expiresAt) return done('no expiry');
45
+ if (ownerRunning(meta)) return done('foreground');
46
+ const left = Date.parse(meta.expiresAt) - Date.now();
47
+ if (!(left > 0)) {
48
+ let ok = true;
49
+ try { await remove(project); } catch { ok = false; }
50
+ recordEvent({ action: 'share expired', project, source: 'cli', ok, detail: `${meta.hostname || project} (expiry watcher)` });
51
+ return ok ? 'expired' : 'failed';
52
+ }
53
+ await sleep(Math.min(poll, left));
54
+ }
55
+ }