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
package/src/commands.js
ADDED
|
@@ -0,0 +1,386 @@
|
|
|
1
|
+
import { randomBytes } from 'node:crypto';
|
|
2
|
+
import { existsSync, readFileSync } from 'node:fs';
|
|
3
|
+
import { spawn } from 'node:child_process';
|
|
4
|
+
import { createInterface } from 'node:readline/promises';
|
|
5
|
+
import { projectDomain, zoneIdFor, recordsEverywhere, inZone, zoneErrorCollector, zoneErrorFor } from './zones.js';
|
|
6
|
+
import { loadConfig, requireConfig, writeTemplate, configPath } from './config.js';
|
|
7
|
+
import { Cloudflare } from './cloudflare.js';
|
|
8
|
+
import { syncAccess, removeAccessApps, privateHosts } from './access.js';
|
|
9
|
+
import { tunnelName, recordComment, tunnelTarget, assertLabel } from './naming.js';
|
|
10
|
+
import {
|
|
11
|
+
findProjectFile, loadProjectFile, buildIngress, hostnames, DASHBOARD_PROJECT, dashboardProject,
|
|
12
|
+
} from './project.js';
|
|
13
|
+
import {
|
|
14
|
+
runningPid, startConnector, stopConnector, logFile, pidFile, saveMeta, readMeta, removeMeta, localProjects,
|
|
15
|
+
} from './process.js';
|
|
16
|
+
import { runHook, hookContext, beforeDown, afterDown, stopBackground } from './hooks.js';
|
|
17
|
+
import { isShare, removeShare } from './share.js';
|
|
18
|
+
import { addPending } from './pending.js';
|
|
19
|
+
|
|
20
|
+
const log = (...a) => console.log(...a);
|
|
21
|
+
const step = (dry, msg) => log(`${dry ? '[dry-run] ' : ''}${msg}`);
|
|
22
|
+
|
|
23
|
+
// Resolve the project file: -f, ./tunnel.yml, or the path remembered from a
|
|
24
|
+
// previous `burrow up <project>`.
|
|
25
|
+
function resolveProject(projectArg, opts) {
|
|
26
|
+
if (projectArg === DASHBOARD_PROJECT && !opts.file) {
|
|
27
|
+
return { proj: dashboardProject(loadConfig().dashboardPort), file: '(built-in dashboard)' };
|
|
28
|
+
}
|
|
29
|
+
let file = findProjectFile(opts.file);
|
|
30
|
+
if (!file && projectArg) {
|
|
31
|
+
const meta = readMeta(projectArg);
|
|
32
|
+
if (meta?.file && existsSync(meta.file)) file = meta.file;
|
|
33
|
+
}
|
|
34
|
+
if (!file) {
|
|
35
|
+
throw new Error(
|
|
36
|
+
`No tunnel.yml found${opts.file ? ` at ${opts.file}` : ' in the current directory'}` +
|
|
37
|
+
(projectArg ? ` and no remembered file for "${projectArg}"` : '') + '. Use -f <path>.'
|
|
38
|
+
);
|
|
39
|
+
}
|
|
40
|
+
const proj = loadProjectFile(file);
|
|
41
|
+
if (projectArg && projectArg !== proj.project) {
|
|
42
|
+
throw new Error(`${file} is for project "${proj.project}", not "${projectArg}".`);
|
|
43
|
+
}
|
|
44
|
+
return { proj, file };
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
// For commands that only need a name (down/status/logs).
|
|
48
|
+
function resolveName(projectArg, opts) {
|
|
49
|
+
if (projectArg) { assertLabel(projectArg, 'project name'); return projectArg; }
|
|
50
|
+
const file = findProjectFile(opts.file);
|
|
51
|
+
if (!file) throw new Error('Pass a project name or run inside a directory with tunnel.yml.');
|
|
52
|
+
return loadProjectFile(file).project;
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function client(cfg) {
|
|
56
|
+
return new Cloudflare({ token: cfg.token, accountId: cfg.accountId, zoneId: cfg.zoneId });
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
export async function init(opts) {
|
|
60
|
+
const path = configPath();
|
|
61
|
+
if (!existsSync(path)) {
|
|
62
|
+
writeTemplate(path);
|
|
63
|
+
log(`Wrote config template to ${path} (mode 600). Fill it in, then run "burrow init" again to verify.`);
|
|
64
|
+
return;
|
|
65
|
+
}
|
|
66
|
+
const cfg = loadConfig();
|
|
67
|
+
log(`Config: ${path}`);
|
|
68
|
+
requireConfig(cfg, ['token', 'accountId', 'domain']);
|
|
69
|
+
const cf = client(cfg);
|
|
70
|
+
const v = await cf.verifyToken();
|
|
71
|
+
log(`Token: ${v?.status || 'unknown'}${v?.expires_on ? ` (expires ${v.expires_on})` : ''}`);
|
|
72
|
+
const zoneId = await cf.resolveZoneId(cfg.domain);
|
|
73
|
+
log(`Domain: ${cfg.domain} (zone ${zoneId})`);
|
|
74
|
+
await cf.listTunnels();
|
|
75
|
+
log('Tunnel API access: ok');
|
|
76
|
+
await cf.recordsByCommentPrefix('burrow:');
|
|
77
|
+
log('DNS API access: ok');
|
|
78
|
+
if (opts.quiet) return;
|
|
79
|
+
}
|
|
80
|
+
|
|
81
|
+
export async function up(projectArg, opts) {
|
|
82
|
+
const dry = !!opts.dryRun;
|
|
83
|
+
const cfg = loadConfig();
|
|
84
|
+
const { proj, file } = resolveProject(projectArg, opts);
|
|
85
|
+
requireConfig(cfg, (dry ? [] : ['token', 'accountId']).concat(proj.domain ? [] : ['domain']));
|
|
86
|
+
const name = tunnelName(proj.project);
|
|
87
|
+
const comment = recordComment(proj.project);
|
|
88
|
+
const domain = projectDomain(proj, cfg);
|
|
89
|
+
const hosts = hostnames(proj, domain);
|
|
90
|
+
const ingress = buildIngress(proj, domain);
|
|
91
|
+
|
|
92
|
+
log(`Project ${proj.project} (${file})`);
|
|
93
|
+
await runHook('pre_up', hookContext(proj, file, hosts), { dry, enabled: opts.hooks !== false });
|
|
94
|
+
if (dry) {
|
|
95
|
+
step(dry, `would create or reuse remotely-managed tunnel ${name}`);
|
|
96
|
+
if (proj.domain) step(dry, `would use domain ${domain} from ${file} (checking its zone is on the account)`);
|
|
97
|
+
step(dry, 'would PUT ingress config:');
|
|
98
|
+
log(JSON.stringify({ config: { ingress } }, null, 2));
|
|
99
|
+
for (const h of hosts) {
|
|
100
|
+
step(dry, `would upsert DNS CNAME ${h.hostname} -> <tunnel-id>.cfargotunnel.com (proxied, comment "${comment}")`);
|
|
101
|
+
}
|
|
102
|
+
step(dry, `would delete other DNS records tagged "${comment}" not listed above`);
|
|
103
|
+
await syncAccess(null, cfg, proj, hosts, { dry });
|
|
104
|
+
const pid = runningPid(proj.project);
|
|
105
|
+
step(dry, pid ? `cloudflared already running (pid ${pid}); would restart it` : `would start cloudflared, pid ${pidFile(proj.project)}, log ${logFile(proj.project)}`);
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
const cf = client(cfg);
|
|
110
|
+
cf.zoneId = await zoneIdFor(cf, cfg, domain);
|
|
111
|
+
|
|
112
|
+
privateHosts(proj, hosts, cfg); // fail before changing anything if an allow list is missing
|
|
113
|
+
let tunnel = await cf.findTunnel(name);
|
|
114
|
+
if (tunnel) log(`Tunnel ${name} exists (${tunnel.id})`);
|
|
115
|
+
else {
|
|
116
|
+
tunnel = await cf.createTunnel(name, randomBytes(32).toString('base64'));
|
|
117
|
+
log(`Created tunnel ${name} (${tunnel.id})`);
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
await cf.putTunnelConfig(tunnel.id, ingress);
|
|
121
|
+
log(`Ingress config set (${ingress.length} rules)`);
|
|
122
|
+
|
|
123
|
+
const target = tunnelTarget(tunnel.id);
|
|
124
|
+
const wanted = new Set(hosts.map((h) => h.hostname));
|
|
125
|
+
for (const h of hosts) {
|
|
126
|
+
const existing = await cf.recordsByName(h.hostname);
|
|
127
|
+
const rec = { type: 'CNAME', name: h.hostname, content: target, proxied: true, ttl: 1, comment };
|
|
128
|
+
const ours = existing.find((r) => r.comment === comment);
|
|
129
|
+
const foreign = existing.filter((r) => r.comment !== comment);
|
|
130
|
+
if (foreign.length && !opts.force) {
|
|
131
|
+
throw new Error(
|
|
132
|
+
`${h.hostname} already has a DNS record not managed by burrow (${foreign.map((r) => r.type).join(', ')}). ` +
|
|
133
|
+
'Remove it or rerun with --force to replace it.'
|
|
134
|
+
);
|
|
135
|
+
}
|
|
136
|
+
for (const r of foreign) { await cf.deleteRecord(r.id); log(`Removed foreign ${r.type} record ${r.name}`); }
|
|
137
|
+
if (ours && ours.type === 'CNAME') {
|
|
138
|
+
if (ours.content !== target || !ours.proxied) { await cf.updateRecord(ours.id, rec); log(`Updated DNS ${h.hostname}`); }
|
|
139
|
+
else log(`DNS ${h.hostname} ok`);
|
|
140
|
+
} else {
|
|
141
|
+
if (ours) await cf.deleteRecord(ours.id);
|
|
142
|
+
await cf.createRecord(rec);
|
|
143
|
+
log(`Created DNS ${h.hostname}`);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
// The domain changed since the last up: clear this project's records in the old zone.
|
|
147
|
+
const prev = readMeta(proj.project);
|
|
148
|
+
const prevZone = prev ? prev.zoneId || (cfg.domain ? await zoneIdFor(cf, cfg, cfg.domain) : null) : null;
|
|
149
|
+
if (prevZone && prevZone !== cf.zoneId) {
|
|
150
|
+
const old = inZone(cf, prevZone);
|
|
151
|
+
for (const r of await old.recordsByComment(comment)) { await old.deleteRecord(r.id); log(`Removed DNS ${r.name} (previous domain)`); }
|
|
152
|
+
}
|
|
153
|
+
for (const r of await cf.recordsByComment(comment)) {
|
|
154
|
+
if (!wanted.has(r.name)) { await cf.deleteRecord(r.id); log(`Removed stale DNS ${r.name}`); }
|
|
155
|
+
}
|
|
156
|
+
await syncAccess(cf, cfg, proj, hosts);
|
|
157
|
+
|
|
158
|
+
const old = await stopConnector(proj.project);
|
|
159
|
+
if (old) log(`Stopped previous cloudflared (pid ${old})`);
|
|
160
|
+
const token = await cf.getTunnelToken(tunnel.id);
|
|
161
|
+
const pid = startConnector(proj.project, token, cfg.cloudflared);
|
|
162
|
+
saveMeta(proj.project, { project: proj.project, file, tunnelId: tunnel.id, tunnelName: name, hostnames: [...wanted], domain, zoneId: cf.zoneId });
|
|
163
|
+
log(`cloudflared started (pid ${pid}), log ${logFile(proj.project)}`);
|
|
164
|
+
for (const h of hosts) log(` ${h.service.padEnd(10)} https://${h.hostname}`);
|
|
165
|
+
await runHook('post_up', hookContext(proj, file, hosts, { BURROW_TUNNEL_ID: tunnel.id }), { enabled: opts.hooks !== false, soft: true });
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
// Stop cloudflared only. Tunnel and DNS stay, so the next `burrow up` is fast.
|
|
169
|
+
// With no project (and no -f), stops every running burrow connector.
|
|
170
|
+
export async function down(projectArg, opts) {
|
|
171
|
+
const dry = !!opts.dryRun;
|
|
172
|
+
if (opts.purge) return destroy(projectArg, opts);
|
|
173
|
+
// --keep-shares (the boot service's stop command): leave temporary shares running.
|
|
174
|
+
const projects = projectArg || opts.file ? [resolveName(projectArg, opts)] : localProjects().filter((p) => !(opts.keepShares && isShare(p)));
|
|
175
|
+
if (!projects.length) { log('No burrow connectors found.'); return; }
|
|
176
|
+
for (const project of projects) {
|
|
177
|
+
const pid = runningPid(project);
|
|
178
|
+
const temp = isShare(project);
|
|
179
|
+
if (dry) {
|
|
180
|
+
step(dry, pid ? `would stop ${project} cloudflared (pid ${pid})` : `${project}: not running`);
|
|
181
|
+
if (temp) step(dry, `would delete share ${project} (tunnel and DNS)`);
|
|
182
|
+
await beforeDown(project, opts);
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
const hookCtx = await beforeDown(project, opts);
|
|
186
|
+
const stopped = await stopConnector(project);
|
|
187
|
+
log(stopped ? `${project}: stopped cloudflared (pid ${stopped})` : `${project}: not running`);
|
|
188
|
+
await afterDown(project, hookCtx, opts);
|
|
189
|
+
if (temp) {
|
|
190
|
+
await removeShare(project);
|
|
191
|
+
log(`${project}: share removed (tunnel and DNS deleted)`);
|
|
192
|
+
}
|
|
193
|
+
}
|
|
194
|
+
if (!dry) log('Tunnels and DNS records are kept. Use "burrow destroy" to delete them.');
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
export function isYes(answer) {
|
|
198
|
+
return /^y(es)?$/i.test(String(answer || '').trim());
|
|
199
|
+
}
|
|
200
|
+
|
|
201
|
+
async function confirm(question) {
|
|
202
|
+
if (!process.stdin.isTTY) return false;
|
|
203
|
+
const rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
204
|
+
try { return isYes(await rl.question(`${question} [y/N] `)); } finally { rl.close(); }
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async function destroyOne(cf, project, dry) {
|
|
208
|
+
const name = tunnelName(project);
|
|
209
|
+
const comment = recordComment(project);
|
|
210
|
+
if (dry) {
|
|
211
|
+
const pid = runningPid(project);
|
|
212
|
+
step(dry, pid ? `would stop cloudflared (pid ${pid})` : `${project}: cloudflared not running locally`);
|
|
213
|
+
step(dry, `would delete DNS records tagged "${comment}"`);
|
|
214
|
+
step(dry, `would delete connections and tunnel ${name}`);
|
|
215
|
+
return;
|
|
216
|
+
}
|
|
217
|
+
const stopped = await stopConnector(project);
|
|
218
|
+
const bg = await stopBackground(project);
|
|
219
|
+
if (bg) log(`${project}: stopped pre_up background process (pid ${bg})`);
|
|
220
|
+
log(stopped ? `${project}: stopped cloudflared (pid ${stopped})` : `${project}: cloudflared was not running`);
|
|
221
|
+
// A zone that can't be read now (token lost access, Cloudflare error) doesn't stop the
|
|
222
|
+
// rest: the deletion is queued and retried by `burrow prune` or the dashboard's Cleanup.
|
|
223
|
+
const unread = (z, e) => {
|
|
224
|
+
addPending({ zoneId: z.id, domain: z.domain, comment, project, error: e.message });
|
|
225
|
+
console.error(`burrow: warning: ${project}: couldn't read DNS in ${z.domain} (${e.message}); ` +
|
|
226
|
+
`its records there are queued for deletion. Run "burrow prune" to retry.`);
|
|
227
|
+
};
|
|
228
|
+
for (const r of await recordsEverywhere(cf, loadConfig(), { comment, onError: unread })) {
|
|
229
|
+
await inZone(cf, r.zoneId).deleteRecord(r.id);
|
|
230
|
+
log(`${project}: deleted DNS ${r.type} ${r.name}`);
|
|
231
|
+
}
|
|
232
|
+
const tunnel = await cf.findTunnel(name);
|
|
233
|
+
if (tunnel) {
|
|
234
|
+
await cf.deleteTunnelConnections(tunnel.id);
|
|
235
|
+
await cf.deleteTunnel(tunnel.id);
|
|
236
|
+
log(`${project}: deleted tunnel ${name} (${tunnel.id})`);
|
|
237
|
+
} else log(`${project}: tunnel ${name} not found`);
|
|
238
|
+
await removeAccessApps(cf, project);
|
|
239
|
+
removeMeta(project);
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// Stop cloudflared AND delete the tunnel and its DNS records.
|
|
243
|
+
// No project needs --all, and asks for confirmation unless --yes.
|
|
244
|
+
export async function destroy(projectArg, opts) {
|
|
245
|
+
const dry = !!opts.dryRun;
|
|
246
|
+
const cfg = loadConfig();
|
|
247
|
+
const single = projectArg || opts.file;
|
|
248
|
+
if (!single && !opts.all) {
|
|
249
|
+
throw new Error('Pass a project, -f <tunnel.yml>, or --all to destroy every burrow tunnel.');
|
|
250
|
+
}
|
|
251
|
+
if (single) {
|
|
252
|
+
const project = resolveName(projectArg, opts);
|
|
253
|
+
if (dry) return destroyOne(null, project, true);
|
|
254
|
+
requireConfig(cfg, ['token', 'accountId']);
|
|
255
|
+
return destroyOne(client(cfg), project, false);
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
// --all
|
|
259
|
+
if (dry && !(cfg.token && cfg.accountId && cfg.domain)) {
|
|
260
|
+
for (const p of localProjects()) step(dry, `would stop ${p} cloudflared (pid ${runningPid(p) || '-'})`);
|
|
261
|
+
step(dry, 'would delete every burrow-* tunnel and every DNS record tagged burrow:*');
|
|
262
|
+
return;
|
|
263
|
+
}
|
|
264
|
+
requireConfig(cfg, ['token', 'accountId']);
|
|
265
|
+
const cf = client(cfg);
|
|
266
|
+
const tunnels = (await cf.listTunnels()).filter((t) => t.name.startsWith('burrow-'));
|
|
267
|
+
const unreadable = [];
|
|
268
|
+
const records = await recordsEverywhere(cf, cfg, { prefix: 'burrow:', onError: (z) => unreadable.push(z.domain) });
|
|
269
|
+
if (unreadable.length) console.error(`burrow: warning: couldn't read DNS in ${unreadable.join(', ')}; records there are queued per project.`);
|
|
270
|
+
const projects = new Set([
|
|
271
|
+
...tunnels.map((t) => t.name.slice('burrow-'.length)),
|
|
272
|
+
...records.map((r) => r.comment.slice('burrow:'.length)),
|
|
273
|
+
...localProjects(),
|
|
274
|
+
]);
|
|
275
|
+
if (!projects.size) { log('Nothing to destroy.'); return; }
|
|
276
|
+
log(`This deletes ${tunnels.length} tunnel(s) and ${records.length} DNS record(s) for: ${[...projects].join(', ')}`);
|
|
277
|
+
if (dry) { for (const p of projects) await destroyOne(cf, p, true); return; }
|
|
278
|
+
if (!opts.yes && !(await confirm('Destroy all of them?'))) {
|
|
279
|
+
log('Aborted. (Non-interactive shells need --yes.)');
|
|
280
|
+
process.exitCode = 1;
|
|
281
|
+
return;
|
|
282
|
+
}
|
|
283
|
+
for (const p of projects) await destroyOne(cf, p, false);
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
export async function ls(opts = {}) {
|
|
287
|
+
const cfg = loadConfig();
|
|
288
|
+
requireConfig(cfg, ['token', 'accountId']);
|
|
289
|
+
const cf = client(cfg);
|
|
290
|
+
const tunnels = (await cf.listTunnels()).filter((t) => t.name.startsWith('burrow-'));
|
|
291
|
+
// A zone whose DNS can't be read doesn't stop the listing: its projects are shown with
|
|
292
|
+
// their hostnames unknown, a warning goes to stderr and the exit code is 1.
|
|
293
|
+
const zones = zoneErrorCollector();
|
|
294
|
+
const records = await recordsEverywhere(cf, cfg, { prefix: 'burrow:', onError: zones.onError });
|
|
295
|
+
warnZones(zones.list);
|
|
296
|
+
const zoneError = (t) => zoneErrorFor(t.name.slice('burrow-'.length), zones.list, cfg);
|
|
297
|
+
if (tunnels.some(zoneError)) process.exitCode = 1;
|
|
298
|
+
if (opts.json) {
|
|
299
|
+
log(JSON.stringify(tunnels.map((t) => tunnelJson(t, records, zoneError(t))), null, 2));
|
|
300
|
+
return;
|
|
301
|
+
}
|
|
302
|
+
if (!tunnels.length) { log('No burrow tunnels.'); return; }
|
|
303
|
+
for (const t of tunnels) {
|
|
304
|
+
const project = t.name.slice('burrow-'.length);
|
|
305
|
+
const pid = runningPid(project);
|
|
306
|
+
const hosts = records.filter((r) => r.comment === recordComment(project)).map((r) => r.name);
|
|
307
|
+
log(`${project} tunnel=${t.status || 'unknown'} local=${pid ? `running (pid ${pid})` : 'stopped'}`);
|
|
308
|
+
for (const h of hosts) log(` https://${h}`);
|
|
309
|
+
const ze = zoneError(t);
|
|
310
|
+
if (ze) log(` hostnames unknown: zone ${ze.zone} unreadable`);
|
|
311
|
+
}
|
|
312
|
+
}
|
|
313
|
+
|
|
314
|
+
function warnZones(list) {
|
|
315
|
+
for (const z of list) console.error(`burrow: warning: couldn't read DNS in ${z.zone} (${z.error}); hostnames there are unknown.`);
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
// JSON shape shared by `ls --json` and `status --json`. No secrets, no origin IPs.
|
|
319
|
+
// zoneError ({ zone, error }) is set, and hostnames may be incomplete, when the zone holding
|
|
320
|
+
// the project's DNS couldn't be read.
|
|
321
|
+
function tunnelJson(t, records, zoneError = null) {
|
|
322
|
+
const project = t.name.slice('burrow-'.length);
|
|
323
|
+
const pid = runningPid(project);
|
|
324
|
+
return {
|
|
325
|
+
project,
|
|
326
|
+
running: !!pid,
|
|
327
|
+
pid: pid || null,
|
|
328
|
+
hostnames: records.filter((r) => r.comment === recordComment(project)).map((r) => r.name).sort(),
|
|
329
|
+
hostnamesKnown: !zoneError,
|
|
330
|
+
zoneError,
|
|
331
|
+
tunnel: {
|
|
332
|
+
id: t.id,
|
|
333
|
+
name: t.name,
|
|
334
|
+
status: t.status || 'unknown',
|
|
335
|
+
connections: (t.connections || []).map((c) => ({ colo: c.colo_name, openedAt: c.opened_at, version: c.client_version })),
|
|
336
|
+
},
|
|
337
|
+
};
|
|
338
|
+
}
|
|
339
|
+
|
|
340
|
+
export async function status(projectArg, opts = {}) {
|
|
341
|
+
const project = resolveName(projectArg, opts);
|
|
342
|
+
const cfg = loadConfig();
|
|
343
|
+
const pid = runningPid(project);
|
|
344
|
+
const configured = !!(cfg.token && cfg.accountId && cfg.domain);
|
|
345
|
+
let t = null;
|
|
346
|
+
let records = [];
|
|
347
|
+
const zones = zoneErrorCollector();
|
|
348
|
+
if (configured) {
|
|
349
|
+
const cf = client(cfg);
|
|
350
|
+
t = await cf.findTunnel(tunnelName(project));
|
|
351
|
+
if (t) records = await recordsEverywhere(cf, cfg, { comment: recordComment(project), onError: zones.onError });
|
|
352
|
+
}
|
|
353
|
+
warnZones(zones.list);
|
|
354
|
+
const zoneError = zoneErrorFor(project, zones.list, cfg);
|
|
355
|
+
if (zoneError) process.exitCode = 1;
|
|
356
|
+
if (opts.json) {
|
|
357
|
+
log(JSON.stringify({
|
|
358
|
+
project, running: !!pid, pid: pid || null, log: logFile(project), cloudflare: configured,
|
|
359
|
+
tunnel: t && { id: t.id, name: t.name, status: t.status || 'unknown', connections: tunnelJson(t, []).tunnel.connections },
|
|
360
|
+
records: records.map((r) => ({ type: r.type, name: r.name, content: r.content, proxied: !!r.proxied })),
|
|
361
|
+
recordsKnown: !zoneError, zoneError, zoneErrors: zones.list.map(({ zone, error }) => ({ zone, error })),
|
|
362
|
+
}, null, 2));
|
|
363
|
+
return;
|
|
364
|
+
}
|
|
365
|
+
log(`Project: ${project}`);
|
|
366
|
+
log(`Local cloudflared: ${pid ? `running (pid ${pid})` : 'stopped'}`);
|
|
367
|
+
log(`Log: ${logFile(project)}`);
|
|
368
|
+
if (!configured) { log('Cloudflare: not configured (run "burrow init")'); return; }
|
|
369
|
+
if (!t) { log(`Tunnel ${tunnelName(project)}: not found`); return; }
|
|
370
|
+
log(`Tunnel ${t.name}: ${t.status} (${t.id}), ${t.connections?.length || 0} connection(s)`);
|
|
371
|
+
for (const r of records) log(` ${r.type} https://${r.name} -> ${r.content}${r.proxied ? ' (proxied)' : ''}`);
|
|
372
|
+
if (zoneError) log(` DNS: unknown, zone ${zoneError.zone} unreadable (${zoneError.error})`);
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
export async function logs(projectArg, opts) {
|
|
376
|
+
const project = resolveName(projectArg, opts);
|
|
377
|
+
const file = logFile(project);
|
|
378
|
+
if (!existsSync(file)) throw new Error(`No log at ${file}`);
|
|
379
|
+
const n = String(parseInt(opts.lines, 10) || 100);
|
|
380
|
+
if (opts.follow) {
|
|
381
|
+
await new Promise((res) => spawn('tail', ['-n', n, '-f', file], { stdio: 'inherit' }).on('exit', res));
|
|
382
|
+
} else {
|
|
383
|
+
const lines = readFileSync(file, 'utf8').split('\n');
|
|
384
|
+
process.stdout.write(lines.slice(-Number(n) - 1).join('\n'));
|
|
385
|
+
}
|
|
386
|
+
}
|
|
@@ -0,0 +1,127 @@
|
|
|
1
|
+
import { readdirSync } from 'node:fs';
|
|
2
|
+
import { stateDir } from './config.js';
|
|
3
|
+
import { findProjectFile, loadProjectFile, DASHBOARD_PROJECT } from './project.js';
|
|
4
|
+
import { isShare } from './share.js';
|
|
5
|
+
|
|
6
|
+
// Project names for completion: remembered/running projects, ./tunnel.yml, the dashboard.
|
|
7
|
+
// Shares (share-<label>) are only offered where they work: see SHARE_COMMANDS.
|
|
8
|
+
export function projectNames({ shares = false } = {}) {
|
|
9
|
+
const names = new Set();
|
|
10
|
+
try {
|
|
11
|
+
for (const f of readdirSync(stateDir())) {
|
|
12
|
+
const m = f.match(/^([a-z0-9][a-z0-9-]*)\.(json|pid)$/);
|
|
13
|
+
if (m) names.add(m[1]);
|
|
14
|
+
}
|
|
15
|
+
} catch {}
|
|
16
|
+
try {
|
|
17
|
+
const file = findProjectFile();
|
|
18
|
+
if (file) names.add(loadProjectFile(file).project);
|
|
19
|
+
} catch {}
|
|
20
|
+
names.add(DASHBOARD_PROJECT);
|
|
21
|
+
return [...names].filter((n) => shares || !isShare(n)).sort();
|
|
22
|
+
}
|
|
23
|
+
|
|
24
|
+
export const shareNamesForCompletion = () => projectNames({ shares: true }).filter((n) => isShare(n));
|
|
25
|
+
|
|
26
|
+
// Commands that accept a share name as their project argument.
|
|
27
|
+
export const SHARE_COMMANDS = new Set(['down', 'destroy', 'restart', 'status', 'logs']);
|
|
28
|
+
|
|
29
|
+
const ACTIONS = { dashboard: ['up', 'down', 'status'], service: ['install', 'uninstall', 'status'], completion: ['bash', 'zsh'] };
|
|
30
|
+
|
|
31
|
+
// Describe the commander program: name, description, options, first-argument kind.
|
|
32
|
+
export function describe(program) {
|
|
33
|
+
return program.commands
|
|
34
|
+
.filter((c) => !c._hidden)
|
|
35
|
+
.map((c) => {
|
|
36
|
+
const args = c.registeredArguments || c._args || [];
|
|
37
|
+
const first = args[0] ? args[0].name() : '';
|
|
38
|
+
return {
|
|
39
|
+
name: c.name(),
|
|
40
|
+
description: c.description(),
|
|
41
|
+
options: c.options.map((o) => o.long).filter(Boolean).concat('--help'),
|
|
42
|
+
projectArg: first === 'project',
|
|
43
|
+
shares: first === 'project' && SHARE_COMMANDS.has(c.name()),
|
|
44
|
+
actions: ACTIONS[c.name()] || [],
|
|
45
|
+
};
|
|
46
|
+
});
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
export function bashScript(cmds) {
|
|
50
|
+
const cases = cmds.map((c) => {
|
|
51
|
+
const opts = c.options.join(' ');
|
|
52
|
+
let words = '';
|
|
53
|
+
if (c.projectArg) words = `$(burrow __complete ${c.shares ? 'targets' : 'projects'} 2>/dev/null)`;
|
|
54
|
+
else if (c.actions.length) words = c.actions.join(' ');
|
|
55
|
+
return ` ${c.name})
|
|
56
|
+
if [[ "$cur" == -* ]]; then COMPREPLY=( $(compgen -W "${opts}" -- "$cur") )
|
|
57
|
+
elif [[ $COMP_CWORD -eq 2 ]]; then COMPREPLY=( $(compgen -W "${words}" -- "$cur") )
|
|
58
|
+
fi ;;`;
|
|
59
|
+
}).join('\n');
|
|
60
|
+
return `# burrow bash completion. Load it with: source <(burrow completion bash)
|
|
61
|
+
_burrow() {
|
|
62
|
+
local cur="\${COMP_WORDS[COMP_CWORD]}"
|
|
63
|
+
COMPREPLY=()
|
|
64
|
+
if [[ $COMP_CWORD -eq 1 ]]; then
|
|
65
|
+
COMPREPLY=( $(compgen -W "${cmds.map((c) => c.name).join(' ')} --help --version" -- "$cur") )
|
|
66
|
+
return 0
|
|
67
|
+
fi
|
|
68
|
+
case "\${COMP_WORDS[1]}" in
|
|
69
|
+
${cases}
|
|
70
|
+
esac
|
|
71
|
+
return 0
|
|
72
|
+
}
|
|
73
|
+
complete -F _burrow burrow
|
|
74
|
+
`;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const zq = (s) => `'${String(s).replace(/'/g, `'\\''`)}'`;
|
|
78
|
+
|
|
79
|
+
export function zshScript(cmds) {
|
|
80
|
+
const list = cmds.map((c) => ` ${zq(`${c.name}:${c.description.replace(/:/g, '\\:')}`)}`).join('\n');
|
|
81
|
+
const cases = cmds.map((c) => {
|
|
82
|
+
const opts = c.options.map(zq).join(' ');
|
|
83
|
+
let words = '';
|
|
84
|
+
if (c.projectArg) words = `compadd -- \${(f)"$(burrow __complete ${c.shares ? 'targets' : 'projects'} 2>/dev/null)"}`;
|
|
85
|
+
else if (c.actions.length) words = `compadd -- ${c.actions.join(' ')}`;
|
|
86
|
+
return ` ${c.name})
|
|
87
|
+
if [[ $words[CURRENT] == -* ]]; then compadd -- ${opts}
|
|
88
|
+
elif (( CURRENT == 3 )); then ${words || ':'}
|
|
89
|
+
fi ;;`;
|
|
90
|
+
}).join('\n');
|
|
91
|
+
return `#compdef burrow
|
|
92
|
+
# burrow zsh completion. Load it with: source <(burrow completion zsh)
|
|
93
|
+
# or save it as _burrow in a directory on your $fpath.
|
|
94
|
+
_burrow() {
|
|
95
|
+
local -a cmds
|
|
96
|
+
cmds=(
|
|
97
|
+
${list}
|
|
98
|
+
)
|
|
99
|
+
if (( CURRENT == 2 )); then
|
|
100
|
+
_describe 'burrow command' cmds
|
|
101
|
+
return
|
|
102
|
+
fi
|
|
103
|
+
case $words[2] in
|
|
104
|
+
${cases}
|
|
105
|
+
esac
|
|
106
|
+
}
|
|
107
|
+
if [[ $zsh_eval_context[-1] == loadautofunc ]]; then
|
|
108
|
+
_burrow "$@"
|
|
109
|
+
else
|
|
110
|
+
compdef _burrow burrow
|
|
111
|
+
fi
|
|
112
|
+
`;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
export function completion(shell, program) {
|
|
116
|
+
const cmds = describe(program);
|
|
117
|
+
if (shell === 'bash') return process.stdout.write(bashScript(cmds));
|
|
118
|
+
if (shell === 'zsh') return process.stdout.write(zshScript(cmds));
|
|
119
|
+
throw new Error(`Unsupported shell "${shell}" (use bash or zsh)`);
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
export function complete(what) {
|
|
123
|
+
// projects: tunnel.yml projects only; targets: projects and shares; shares: shares only.
|
|
124
|
+
if (what === 'projects') for (const p of projectNames()) console.log(p);
|
|
125
|
+
if (what === 'targets') for (const p of projectNames({ shares: true })) console.log(p);
|
|
126
|
+
if (what === 'shares') for (const p of shareNamesForCompletion()) console.log(p);
|
|
127
|
+
}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
// Update KEY=value lines in the burrow config file, keeping comments, order and mode 600.
|
|
2
|
+
import { chmodSync, existsSync, mkdirSync, readFileSync, writeFileSync } from 'node:fs';
|
|
3
|
+
import { dirname } from 'node:path';
|
|
4
|
+
import { configPath } from './config.js';
|
|
5
|
+
|
|
6
|
+
const KEY_RE = /^[A-Z][A-Z0-9_]*$/;
|
|
7
|
+
|
|
8
|
+
// updates: { KEY: 'value' | '' (clear) }. Values are single-line and unquoted.
|
|
9
|
+
export function setConfigValues(updates, path = configPath()) {
|
|
10
|
+
for (const [k, v] of Object.entries(updates)) {
|
|
11
|
+
if (!KEY_RE.test(k)) throw new Error(`bad config key ${k}`);
|
|
12
|
+
if (typeof v !== 'string' || /[\r\n\0]/.test(v)) throw new Error(`${k}: value must be a single line`);
|
|
13
|
+
}
|
|
14
|
+
const lines = existsSync(path) ? readFileSync(path, 'utf8').split(/\r?\n/) : [];
|
|
15
|
+
if (lines.length && lines[lines.length - 1] === '') lines.pop();
|
|
16
|
+
const done = new Set();
|
|
17
|
+
const out = [];
|
|
18
|
+
for (const line of lines) {
|
|
19
|
+
const m = line.match(/^\s*(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=/);
|
|
20
|
+
if (m && m[1] in updates) {
|
|
21
|
+
if (done.has(m[1])) continue; // drop duplicates, the first one wins in parseEnv
|
|
22
|
+
out.push(`${m[1]}=${updates[m[1]]}`);
|
|
23
|
+
done.add(m[1]);
|
|
24
|
+
} else out.push(line);
|
|
25
|
+
}
|
|
26
|
+
for (const [k, v] of Object.entries(updates)) if (!done.has(k)) out.push(`${k}=${v}`);
|
|
27
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
28
|
+
writeFileSync(path, out.join('\n') + '\n', { mode: 0o600 });
|
|
29
|
+
chmodSync(path, 0o600);
|
|
30
|
+
return path;
|
|
31
|
+
}
|
package/src/config.js
ADDED
|
@@ -0,0 +1,82 @@
|
|
|
1
|
+
import { readFileSync, writeFileSync, existsSync, mkdirSync, chmodSync } from 'node:fs';
|
|
2
|
+
import { homedir } from 'node:os';
|
|
3
|
+
import { join, dirname } from 'node:path';
|
|
4
|
+
|
|
5
|
+
export const configPath = () =>
|
|
6
|
+
process.env.BURROW_CONFIG || join(process.env.XDG_CONFIG_HOME || join(homedir(), '.config'), 'burrow', 'config.env');
|
|
7
|
+
|
|
8
|
+
export const stateDir = () =>
|
|
9
|
+
process.env.BURROW_STATE_DIR || join(process.env.XDG_STATE_HOME || join(homedir(), '.local', 'state'), 'burrow');
|
|
10
|
+
|
|
11
|
+
export const TEMPLATE = `# burrow config. Keep this file private (chmod 600). Never commit it.
|
|
12
|
+
# API token: dash.cloudflare.com/profile/api-tokens -> Create Custom Token
|
|
13
|
+
# Account > Cloudflare Tunnel > Edit
|
|
14
|
+
# Zone > DNS > Edit (zone: your tunnel domain)
|
|
15
|
+
# Zone > Analytics > Read (optional, only for burrow stats)
|
|
16
|
+
# Zone > Zone > Read (optional, only if CF_ZONE_ID is empty)
|
|
17
|
+
# Account > Access: Apps and Policies > Edit (optional, only for private: true)
|
|
18
|
+
CF_API_TOKEN=
|
|
19
|
+
# Account ID: dashboard -> domain overview -> right sidebar
|
|
20
|
+
CF_ACCOUNT_ID=
|
|
21
|
+
# Zone ID of BURROW_DOMAIN (optional; resolved from BURROW_DOMAIN when empty)
|
|
22
|
+
CF_ZONE_ID=
|
|
23
|
+
# Tunnel domain. Hostnames: <project>.<domain>, <service>-<project>.<domain>
|
|
24
|
+
BURROW_DOMAIN=
|
|
25
|
+
# Default allow list for services with private: true (comma-separated emails or @domains)
|
|
26
|
+
BURROW_ACCESS_EMAILS=
|
|
27
|
+
# Dashboard login (burrow dashboard). At least 12 characters.
|
|
28
|
+
BURROW_DASHBOARD_PASSWORD=
|
|
29
|
+
BURROW_DASHBOARD_PORT=7070
|
|
30
|
+
# Projects "burrow service" brings up at boot (comma-separated), besides autostart: true
|
|
31
|
+
BURROW_AUTOSTART=
|
|
32
|
+
# Optional path to the cloudflared binary
|
|
33
|
+
CLOUDFLARED_BIN=cloudflared
|
|
34
|
+
`;
|
|
35
|
+
|
|
36
|
+
export function parseEnv(text) {
|
|
37
|
+
const out = {};
|
|
38
|
+
for (const raw of text.split(/\r?\n/)) {
|
|
39
|
+
const line = raw.trim();
|
|
40
|
+
if (!line || line.startsWith('#')) continue;
|
|
41
|
+
const m = line.match(/^(?:export\s+)?([A-Za-z_][A-Za-z0-9_]*)\s*=\s*(.*)$/);
|
|
42
|
+
if (!m) continue;
|
|
43
|
+
let v = m[2].trim();
|
|
44
|
+
if ((v.startsWith('"') && v.endsWith('"')) || (v.startsWith("'") && v.endsWith("'"))) v = v.slice(1, -1);
|
|
45
|
+
out[m[1]] = v;
|
|
46
|
+
}
|
|
47
|
+
return out;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
export function loadConfig() {
|
|
51
|
+
const path = configPath();
|
|
52
|
+
const file = existsSync(path) ? parseEnv(readFileSync(path, 'utf8')) : {};
|
|
53
|
+
const pick = (k) => process.env[k] || file[k] || '';
|
|
54
|
+
return {
|
|
55
|
+
path,
|
|
56
|
+
exists: existsSync(path),
|
|
57
|
+
token: pick('CF_API_TOKEN'),
|
|
58
|
+
accountId: pick('CF_ACCOUNT_ID'),
|
|
59
|
+
zoneId: pick('CF_ZONE_ID'),
|
|
60
|
+
domain: pick('BURROW_DOMAIN').toLowerCase().replace(/\.$/, ''),
|
|
61
|
+
accessEmails: pick('BURROW_ACCESS_EMAILS'),
|
|
62
|
+
cloudflared: pick('CLOUDFLARED_BIN') || 'cloudflared',
|
|
63
|
+
dashboardPassword: pick('BURROW_DASHBOARD_PASSWORD'),
|
|
64
|
+
dashboardPort: pick('BURROW_DASHBOARD_PORT') || '7070',
|
|
65
|
+
autostart: pick('BURROW_AUTOSTART'),
|
|
66
|
+
};
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function requireConfig(cfg, keys) {
|
|
70
|
+
const map = { token: 'CF_API_TOKEN', accountId: 'CF_ACCOUNT_ID', domain: 'BURROW_DOMAIN' };
|
|
71
|
+
const missing = keys.filter((k) => !cfg[k]).map((k) => map[k] || k);
|
|
72
|
+
if (missing.length) {
|
|
73
|
+
throw new Error(`Missing ${missing.join(', ')} in ${cfg.path}. Run "burrow init" and fill it in.`);
|
|
74
|
+
}
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
export function writeTemplate(path = configPath()) {
|
|
78
|
+
mkdirSync(dirname(path), { recursive: true, mode: 0o700 });
|
|
79
|
+
writeFileSync(path, TEMPLATE, { mode: 0o600, flag: 'wx' });
|
|
80
|
+
chmodSync(path, 0o600);
|
|
81
|
+
return path;
|
|
82
|
+
}
|