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/bin/burrow.js
ADDED
|
@@ -0,0 +1,200 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
// node-guard:start
|
|
3
|
+
if (Number(process.versions.node.split('.')[0]) < 18) {
|
|
4
|
+
console.error(`burrow needs Node.js 18 or newer (found ${process.versions.node}).`);
|
|
5
|
+
process.exit(1);
|
|
6
|
+
}
|
|
7
|
+
// node-guard:end
|
|
8
|
+
import { Command } from 'commander';
|
|
9
|
+
import { readFileSync } from 'node:fs';
|
|
10
|
+
import * as cmd from '../src/commands.js';
|
|
11
|
+
import * as dash from '../src/dashboard/manage.js';
|
|
12
|
+
|
|
13
|
+
const pkg = JSON.parse(readFileSync(new URL('../package.json', import.meta.url), 'utf8'));
|
|
14
|
+
const program = new Command();
|
|
15
|
+
program.name('burrow').description('Manage Cloudflare Tunnels for local projects').version(pkg.version);
|
|
16
|
+
// Event history: state-changing commands are recorded with their source (src/history.js),
|
|
17
|
+
// also when the run is cut short by Ctrl+C, SIGTERM or process.exit().
|
|
18
|
+
let tracked = null;
|
|
19
|
+
program.hook('preAction', async (_, command) => {
|
|
20
|
+
try { tracked = (await import('../src/history.js')).trackCommand(command); } catch {}
|
|
21
|
+
});
|
|
22
|
+
program.hook('postAction', () => {
|
|
23
|
+
try { tracked?.finish(); } catch {}
|
|
24
|
+
tracked = null;
|
|
25
|
+
});
|
|
26
|
+
program.command('completion <shell>')
|
|
27
|
+
.description('print a shell completion script: bash | zsh')
|
|
28
|
+
.action(async (shell) => {
|
|
29
|
+
try { (await import('../src/completion.js')).completion(shell, program); } catch (e) {
|
|
30
|
+
console.error(`burrow: ${e.message}`);
|
|
31
|
+
process.exitCode = 1;
|
|
32
|
+
}
|
|
33
|
+
});
|
|
34
|
+
program.command('__complete <what>', { hidden: true })
|
|
35
|
+
.action(async (what) => (await import('../src/completion.js')).complete(what));
|
|
36
|
+
|
|
37
|
+
const wrap = (fn) => async (...args) => {
|
|
38
|
+
try { await fn(...args); } catch (e) {
|
|
39
|
+
console.error(`burrow: ${e.message}`);
|
|
40
|
+
process.exitCode = 1;
|
|
41
|
+
}
|
|
42
|
+
};
|
|
43
|
+
program.command('update')
|
|
44
|
+
.description('update burrow from GitHub (git checkout: git pull --ff-only + npm install; global install: npm i -g)')
|
|
45
|
+
.option('--check', 'only report whether a newer commit or version exists')
|
|
46
|
+
.option('--json', 'with --check: print one JSON object (for the dashboard)')
|
|
47
|
+
.option('--dry-run', 'print what would run')
|
|
48
|
+
.option('--force', 'global install: reinstall even when up to date')
|
|
49
|
+
.action(wrap(async (o) => (await import('../src/update.js')).update(o)));
|
|
50
|
+
program.command('url [project]')
|
|
51
|
+
.description("print a project's public URLs")
|
|
52
|
+
.option('-f, --file <path>', 'path to tunnel.yml')
|
|
53
|
+
.option('--plain', 'URLs only, one per line')
|
|
54
|
+
.action(wrap(async (p, o) => (await import('../src/open.js')).url(p, o)));
|
|
55
|
+
program.command('open [project] [service]')
|
|
56
|
+
.description('open a project URL in the browser (the app, or the given service)')
|
|
57
|
+
.option('-f, --file <path>', 'path to tunnel.yml')
|
|
58
|
+
.option('--print', 'print the URL instead of opening it')
|
|
59
|
+
.action(wrap(async (p, s, o) => (await import('../src/open.js')).open(p, s, o)));
|
|
60
|
+
|
|
61
|
+
program.command('export [file]')
|
|
62
|
+
.description('export remembered project configs (no secrets) to a file or stdout')
|
|
63
|
+
.option('--project <list>', 'comma-separated projects (default: all)')
|
|
64
|
+
.option('--json', 'JSON instead of YAML')
|
|
65
|
+
.action(wrap(async (f, o) => (await import('../src/transfer.js')).exportProjects(f, o)));
|
|
66
|
+
program.command('import <file>')
|
|
67
|
+
.description('import project configs from a burrow export')
|
|
68
|
+
.option('--dir <dir>', 'where to write the tunnel.yml files (default ~/.config/burrow/projects)')
|
|
69
|
+
.option('--force', 'replace existing files and remembered paths')
|
|
70
|
+
.option('--dry-run', 'print what would be written')
|
|
71
|
+
.action(wrap(async (f, o) => (await import('../src/transfer.js')).importProjects(f, o)));
|
|
72
|
+
program.command('init').description('write the config template, or verify the API token').action(wrap(() => cmd.init({})));
|
|
73
|
+
program.command('add [project]')
|
|
74
|
+
.description('create a tunnel.yml (prompts, or use flags)')
|
|
75
|
+
.option('-f, --file <path>', 'where to write', 'tunnel.yml')
|
|
76
|
+
.option('--app <target>', 'root service: port or URL')
|
|
77
|
+
.option('--path <prefix=target>', 'extra path on the app (repeatable)', (v, a) => a.concat(v), [])
|
|
78
|
+
.option('--service <name=target>', 'sub-service (repeatable)', (v, a) => a.concat(v), [])
|
|
79
|
+
.option('--force', 'overwrite an existing file')
|
|
80
|
+
.option('-y, --yes', 'never prompt')
|
|
81
|
+
.action(wrap(async (p, o) => (await import('../src/add.js')).add(p, o)));
|
|
82
|
+
program.command('edit [project]')
|
|
83
|
+
.description('open tunnel.yml in $EDITOR, validate it on save, and offer to apply it if the project is running')
|
|
84
|
+
.option('-f, --file <path>', 'path to tunnel.yml')
|
|
85
|
+
.option('--no-apply', 'only save, never re-run up')
|
|
86
|
+
.option('-y, --yes', 'apply without asking when the project is running')
|
|
87
|
+
.option('--dry-run', 'apply as "up --dry-run"')
|
|
88
|
+
.action(wrap(async (p, o) => (await import('../src/edit.js')).edit(p, o)));
|
|
89
|
+
program.command('up [project]')
|
|
90
|
+
.description('create/reuse tunnel, set ingress and DNS, start cloudflared')
|
|
91
|
+
.option('-f, --file <path>', 'path to tunnel.yml')
|
|
92
|
+
.option('--dry-run', 'print the plan without calling Cloudflare or starting anything')
|
|
93
|
+
.option('--force', 'replace DNS records not managed by burrow on the same hostnames')
|
|
94
|
+
.option('--no-hooks', 'skip the hooks in tunnel.yml')
|
|
95
|
+
.action(wrap((p, o) => cmd.up(p, o)));
|
|
96
|
+
program.command('share <target>')
|
|
97
|
+
.description('share a local port or URL on a temporary <random>.<domain> hostname')
|
|
98
|
+
.option('--name <label>', 'pick the hostname label instead of a random one')
|
|
99
|
+
.option('--domain <domain>', 'share on this domain (a zone on the account) instead of BURROW_DOMAIN')
|
|
100
|
+
.option('-f, --file <path>', "share for this tunnel.yml: use its domain: and run its hooks")
|
|
101
|
+
.option('--project <name>', 'like -f, with the tunnel.yml remembered for that project')
|
|
102
|
+
.option('--no-hooks', 'with -f/--project: skip its hooks')
|
|
103
|
+
.option('--detach', 'keep running in the background (remove with burrow down)')
|
|
104
|
+
.option('--expires <duration>', 'remove the share after 30m, 2h, 1d, … (1 minute to 30 days)')
|
|
105
|
+
.option('--dry-run', 'print the plan only')
|
|
106
|
+
.action(wrap(async (t, o) => (await import('../src/share.js')).share(t, o)));
|
|
107
|
+
// Internal: the per-share expiry watcher started by `share --detach --expires` (src/share-expiry.js).
|
|
108
|
+
program.command('_share-expire <project>', { hidden: true })
|
|
109
|
+
.action(wrap(async (project) => {
|
|
110
|
+
const { watchExpiry } = await import('../src/share-expiry.js');
|
|
111
|
+
await watchExpiry(project, { remove: (p) => cmd.down(p, {}) });
|
|
112
|
+
}));
|
|
113
|
+
program.command('down [project]')
|
|
114
|
+
.description('stop cloudflared (all running projects when none is given); keeps tunnel and DNS')
|
|
115
|
+
.option('-f, --file <path>', 'path to tunnel.yml')
|
|
116
|
+
.option('--purge', 'same as "burrow destroy"')
|
|
117
|
+
.option('--all', 'with --purge and no project: every burrow tunnel')
|
|
118
|
+
.option('-y, --yes', 'with --purge --all: skip the confirmation')
|
|
119
|
+
.option('--dry-run', 'print what would happen')
|
|
120
|
+
.option('--no-hooks', 'skip pre_down/post_down (a background pre_up process is still stopped)')
|
|
121
|
+
.option('--keep-shares', 'with no project: leave temporary shares running (used by the boot service)')
|
|
122
|
+
.action(wrap((p, o) => cmd.down(p, o)));
|
|
123
|
+
program.command('restart [project]')
|
|
124
|
+
.description('re-sync and restart a project (all running projects when none is given)')
|
|
125
|
+
.option('-f, --file <path>', 'path to tunnel.yml')
|
|
126
|
+
.option('--dry-run', 'print the plan only')
|
|
127
|
+
.option('--no-hooks', 'skip the pre_up/post_up hooks in tunnel.yml')
|
|
128
|
+
.action(wrap(async (p, o) => (await import('../src/restart.js')).restart(p, o)));
|
|
129
|
+
program.command('destroy [project]')
|
|
130
|
+
.description('stop cloudflared and delete the tunnel and its DNS records')
|
|
131
|
+
.option('-f, --file <path>', 'path to tunnel.yml')
|
|
132
|
+
.option('--all', 'every burrow-* tunnel and burrow:* DNS record (asks first)')
|
|
133
|
+
.option('-y, --yes', 'skip the confirmation for --all')
|
|
134
|
+
.option('--dry-run', 'print what would be deleted')
|
|
135
|
+
.action(wrap((p, o) => cmd.destroy(p, o)));
|
|
136
|
+
program.command('prune')
|
|
137
|
+
.description('delete orphaned burrow-* tunnels and burrow:* DNS records (asks first)')
|
|
138
|
+
.option('--dry-run', 'list orphans only')
|
|
139
|
+
.option('-y, --yes', 'skip the confirmation')
|
|
140
|
+
.option('--include-active', 'also prune tunnels that still have live connections')
|
|
141
|
+
.action(wrap(async (o) => (await import('../src/prune.js')).prune(o)));
|
|
142
|
+
program.command('dashboard [action]')
|
|
143
|
+
.description('web dashboard: no action = run in foreground; up | down | status to manage it in the background')
|
|
144
|
+
.option('--port <port>', 'port (default BURROW_DASHBOARD_PORT or 7070)')
|
|
145
|
+
.option('--host <host>', 'bind address', '127.0.0.1')
|
|
146
|
+
.option('--no-tunnel', 'with "up": do not expose it on burrow.<domain>')
|
|
147
|
+
.option('--dry-run', 'with "up": print the plan only')
|
|
148
|
+
.action(wrap(async (action, o) => {
|
|
149
|
+
if (!action) return dash.foreground(o);
|
|
150
|
+
if (action === 'up') return dash.up(o);
|
|
151
|
+
if (action === 'down') return dash.down(o);
|
|
152
|
+
if (action === 'status') return dash.status(o);
|
|
153
|
+
throw new Error(`Unknown dashboard action "${action}" (use up, down or status)`);
|
|
154
|
+
}));
|
|
155
|
+
program.command('ls').description('list burrow tunnels, hostnames and running state')
|
|
156
|
+
.option('--json', 'machine-readable output')
|
|
157
|
+
.action(wrap((o) => cmd.ls(o)));
|
|
158
|
+
program.command('status [project]').description('show one project')
|
|
159
|
+
.option('-f, --file <path>', 'path to tunnel.yml')
|
|
160
|
+
.option('--json', 'machine-readable output')
|
|
161
|
+
.action(wrap((p, o) => cmd.status(p, o)));
|
|
162
|
+
program.command('service <action>')
|
|
163
|
+
.description('systemd user unit that brings projects up at boot: install | uninstall | status')
|
|
164
|
+
.option('--projects <list>', 'install: comma-separated projects (default: autostart projects, re-read at boot)')
|
|
165
|
+
.option('--now', 'install: also start it now')
|
|
166
|
+
.option('--dry-run', 'print what would happen')
|
|
167
|
+
.action(wrap(async (a, o) => (await import('../src/service.js')).service(a, o)));
|
|
168
|
+
program.command('autostart [projects...]')
|
|
169
|
+
.description('bring up autostart projects (what the systemd unit runs)')
|
|
170
|
+
.option('--dry-run', 'print the list only')
|
|
171
|
+
.action(wrap(async (p, o) => (await import('../src/service.js')).autostart(p, o)));
|
|
172
|
+
program.command('watch [projects...]')
|
|
173
|
+
.description('watch connectors, tunnels and local ports; alert on changes (webhook, ntfy)')
|
|
174
|
+
.option('--interval <seconds>', 'seconds between checks', '60')
|
|
175
|
+
.option('--debounce <n>', 'checks in a row before a change alerts', '2')
|
|
176
|
+
.option('--once', 'check once and exit (for cron)')
|
|
177
|
+
.option('--dry-run', 'print alerts instead of sending them')
|
|
178
|
+
.option('--install-service', 'install a systemd user unit that runs burrow watch')
|
|
179
|
+
.option('--uninstall-service', 'remove that unit')
|
|
180
|
+
.action(wrap(async (p, o) => (await import('../src/watch.js')).watch(p, o)));
|
|
181
|
+
program.command('logs [project]').description('show cloudflared logs')
|
|
182
|
+
.option('-f, --file <path>', 'path to tunnel.yml')
|
|
183
|
+
.option('-n, --lines <n>', 'number of lines', '100')
|
|
184
|
+
.option('--follow', 'follow the log')
|
|
185
|
+
.action(wrap((p, o) => cmd.logs(p, o)));
|
|
186
|
+
program.command('doctor [project]')
|
|
187
|
+
.description('check config, token, zone, cloudflared and local service ports')
|
|
188
|
+
.option('-f, --file <path>', 'path to tunnel.yml')
|
|
189
|
+
.option('--offline', 'skip the Cloudflare API checks')
|
|
190
|
+
.option('--all', 'check every remembered project (ignore ./tunnel.yml)')
|
|
191
|
+
.option('--json', 'print the checks as one line of JSON')
|
|
192
|
+
.action(wrap(async (p, o) => (await import('../src/doctor.js')).doctor(p, o)));
|
|
193
|
+
program.command('stats [project]')
|
|
194
|
+
.description('requests, bandwidth and status codes per hostname (Cloudflare GraphQL Analytics)')
|
|
195
|
+
.option('-f, --file <path>', 'path to tunnel.yml')
|
|
196
|
+
.option('--since <window>', 'time window: 30m, 24h, 7d or an ISO date', '24h')
|
|
197
|
+
.option('--json', 'machine-readable output')
|
|
198
|
+
.action(wrap(async (p, o) => (await import('../src/stats.js')).stats(p, o)));
|
|
199
|
+
|
|
200
|
+
await program.parseAsync();
|
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
# Example tunnel.yml for a fictional "acme-shop" app with a local Supabase stack.
|
|
2
|
+
# Copy it into your project as tunnel.yml. With BURROW_DOMAIN=example.dev this gives:
|
|
3
|
+
# app -> https://acme-shop.example.dev
|
|
4
|
+
# mail -> https://mail-acme-shop.example.dev (Mailpit)
|
|
5
|
+
# studio -> https://studio-acme-shop.example.dev (Supabase Studio)
|
|
6
|
+
project: acme-shop
|
|
7
|
+
services:
|
|
8
|
+
- name: app # "app" is the root service: <project>.<domain>
|
|
9
|
+
url: http://localhost:3100
|
|
10
|
+
paths: # local Supabase API on the same origin
|
|
11
|
+
- { path: /auth/v1, url: http://localhost:54321 }
|
|
12
|
+
- { path: /rest/v1, url: http://localhost:54321 }
|
|
13
|
+
- { path: /storage/v1, url: http://localhost:54321 }
|
|
14
|
+
- { path: /realtime/v1, url: http://localhost:54321 }
|
|
15
|
+
- name: mail
|
|
16
|
+
url: http://localhost:54324
|
|
17
|
+
- name: studio
|
|
18
|
+
url: http://localhost:54323
|
package/package.json
CHANGED
|
@@ -1,6 +1,47 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "burrow-cli",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"description": "burrow: manage Cloudflare Tunnels, DNS and cloudflared for local projects",
|
|
5
|
+
"keywords": [
|
|
6
|
+
"cloudflare",
|
|
7
|
+
"cloudflare-tunnel",
|
|
8
|
+
"cloudflared",
|
|
9
|
+
"dns",
|
|
10
|
+
"cli"
|
|
11
|
+
],
|
|
12
|
+
"repository": {
|
|
13
|
+
"type": "git",
|
|
14
|
+
"url": "git+https://github.com/zfir-dev/burrow-cli.git"
|
|
15
|
+
},
|
|
16
|
+
"type": "module",
|
|
17
|
+
"bin": {
|
|
18
|
+
"burrow": "bin/burrow.js"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"bin",
|
|
22
|
+
"src",
|
|
23
|
+
"examples",
|
|
24
|
+
"README.md"
|
|
25
|
+
],
|
|
26
|
+
"engines": {
|
|
27
|
+
"node": ">=18"
|
|
28
|
+
},
|
|
29
|
+
"scripts": {
|
|
30
|
+
"test": "node --test"
|
|
31
|
+
},
|
|
32
|
+
"license": "MIT",
|
|
33
|
+
"dependencies": {
|
|
34
|
+
"@alpinejs/csp": "3.17.5",
|
|
35
|
+
"@picocss/pico": "2.1.1",
|
|
36
|
+
"commander": "^12.1.0",
|
|
37
|
+
"qrcode-generator": "2.0.4",
|
|
38
|
+
"yaml": "^2.9.1"
|
|
39
|
+
},
|
|
40
|
+
"homepage": "https://github.com/zfir-dev/burrow-cli#readme",
|
|
41
|
+
"bugs": {
|
|
42
|
+
"url": "https://github.com/zfir-dev/burrow-cli/issues"
|
|
43
|
+
},
|
|
44
|
+
"publishConfig": {
|
|
45
|
+
"access": "public"
|
|
46
|
+
}
|
|
47
|
+
}
|
package/src/access.js
ADDED
|
@@ -0,0 +1,163 @@
|
|
|
1
|
+
import { mkdirSync, readFileSync, readdirSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { dirname, join } from 'node:path';
|
|
3
|
+
import { stateDir } from './config.js';
|
|
4
|
+
|
|
5
|
+
// Cloudflare Access for services marked `private: true`: one self-hosted Access app per
|
|
6
|
+
// hostname, with one allow policy. burrow owns an app when it carries the Access tag
|
|
7
|
+
// "burrow" and is named burrow:<project>:<service>. Anything else is never touched.
|
|
8
|
+
export const ACCESS_TAG = 'burrow';
|
|
9
|
+
export const POLICY_NAME = 'burrow:allow';
|
|
10
|
+
export const PERMISSION_HINT = 'The API token needs Account > Access: Apps and Policies > Edit for private: true services.';
|
|
11
|
+
export const appName = (project, service) => `burrow:${project}:${service}`;
|
|
12
|
+
const log = (...a) => console.log(...a);
|
|
13
|
+
|
|
14
|
+
export function ownedBy(app, project) {
|
|
15
|
+
const prefix = project ? `burrow:${project}:` : 'burrow:';
|
|
16
|
+
return String(app?.name || '').startsWith(prefix) && (app.tags || []).includes(ACCESS_TAG);
|
|
17
|
+
}
|
|
18
|
+
|
|
19
|
+
// Which apps exist for a project is remembered locally, so projects that never used
|
|
20
|
+
// private: true never call the Access API (and tokens without Access permission keep working).
|
|
21
|
+
export const accessStateFile = (project) => join(stateDir(), 'access', `${project}.json`);
|
|
22
|
+
function readState(project) {
|
|
23
|
+
try { return JSON.parse(readFileSync(accessStateFile(project), 'utf8')).apps || []; } catch { return []; }
|
|
24
|
+
}
|
|
25
|
+
function writeState(project, apps) {
|
|
26
|
+
if (!apps.length) { rmSync(accessStateFile(project), { force: true }); return; }
|
|
27
|
+
mkdirSync(dirname(accessStateFile(project)), { recursive: true, mode: 0o700 });
|
|
28
|
+
writeFileSync(accessStateFile(project), JSON.stringify({ apps }, null, 2) + '\n', { mode: 0o600 });
|
|
29
|
+
}
|
|
30
|
+
export function accessProjects() {
|
|
31
|
+
try { return readdirSync(join(stateDir(), 'access')).filter((f) => f.endsWith('.json')).map((f) => f.slice(0, -5)); } catch { return []; }
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
export function parseEmails(value) {
|
|
35
|
+
const list = Array.isArray(value) ? value : String(value || '').split(',');
|
|
36
|
+
return list.map((e) => String(e).trim().toLowerCase()).filter(Boolean);
|
|
37
|
+
}
|
|
38
|
+
export const validAllow = (e) => /^[^@\s,]+@[a-z0-9.-]+\.[a-z]{2,}$/.test(e) || /^@[a-z0-9.-]+\.[a-z]{2,}$/.test(e);
|
|
39
|
+
|
|
40
|
+
export function includeRules(allow) {
|
|
41
|
+
return allow.map((e) => (e.startsWith('@') ? { email_domain: { domain: e.slice(1) } } : { email: { email: e } }));
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
// [{ service, hostname, allow, name }] for the project's private services.
|
|
45
|
+
// hosts is hostnames(proj, domain), in the same order as proj.services.
|
|
46
|
+
export function privateHosts(proj, hosts, cfg) {
|
|
47
|
+
const out = [];
|
|
48
|
+
proj.services.forEach((s, i) => {
|
|
49
|
+
if (!s.private) return;
|
|
50
|
+
const allow = s.allow?.length ? s.allow : parseEmails(cfg.accessEmails);
|
|
51
|
+
if (!allow.length) {
|
|
52
|
+
throw new Error(`${proj.project}: service "${s.name}" is private but has no "allow" list, and BURROW_ACCESS_EMAILS is empty.`);
|
|
53
|
+
}
|
|
54
|
+
const bad = allow.filter((e) => !validAllow(e));
|
|
55
|
+
if (bad.length) throw new Error(`BURROW_ACCESS_EMAILS: invalid entries ${bad.join(', ')} (use emails or @domain)`);
|
|
56
|
+
out.push({ service: s.name, hostname: hosts[i].hostname, allow, name: appName(proj.project, s.name) });
|
|
57
|
+
});
|
|
58
|
+
return out;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
const isAuthError = (e) => /HTTP 40[13]\b/.test(e.message) || /\b10000: /.test(e.message);
|
|
62
|
+
async function guard(fn) {
|
|
63
|
+
try { return await fn(); } catch (e) {
|
|
64
|
+
if (isAuthError(e)) throw new Error(`Cloudflare Access: ${e.message}. ${PERMISSION_HINT}`);
|
|
65
|
+
throw e;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
const appsPath = (cf) => `/accounts/${cf.accountId}/access/apps`;
|
|
70
|
+
const listApps = (cf) => cf.all(appsPath(cf));
|
|
71
|
+
|
|
72
|
+
async function ensureTag(cf) {
|
|
73
|
+
const tag = await cf.req('GET', `/accounts/${cf.accountId}/access/tags/${ACCESS_TAG}`, { allow404: true });
|
|
74
|
+
if (!tag) await cf.req('POST', `/accounts/${cf.accountId}/access/tags`, { body: { name: ACCESS_TAG } });
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
const sortRules = (rules) => JSON.stringify((rules || []).map((r) => JSON.stringify(r)).sort());
|
|
78
|
+
|
|
79
|
+
async function syncPolicy(cf, app, w) {
|
|
80
|
+
const base = `${appsPath(cf)}/${app.id}/policies`;
|
|
81
|
+
const include = includeRules(w.allow);
|
|
82
|
+
const body = { name: POLICY_NAME, decision: 'allow', include, precedence: 1 };
|
|
83
|
+
const ours = (await cf.all(base)).find((p) => p.name === POLICY_NAME);
|
|
84
|
+
if (!ours) {
|
|
85
|
+
await cf.req('POST', base, { body });
|
|
86
|
+
log(`Access: ${w.hostname} allows ${w.allow.join(', ')}`);
|
|
87
|
+
} else if (sortRules(ours.include) !== sortRules(include) || ours.decision !== 'allow') {
|
|
88
|
+
await cf.req('PUT', `${base}/${ours.id}`, { body });
|
|
89
|
+
log(`Access: ${w.hostname} now allows ${w.allow.join(', ')}`);
|
|
90
|
+
}
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
// Called by `burrow up` after DNS: create/update apps for private services and delete
|
|
94
|
+
// burrow's apps for services that are no longer private.
|
|
95
|
+
export async function syncAccess(cf, cfg, proj, hosts, { dry = false } = {}) {
|
|
96
|
+
const wanted = privateHosts(proj, hosts, cfg);
|
|
97
|
+
if (dry) {
|
|
98
|
+
for (const w of wanted) log(`[dry-run] would protect https://${w.hostname} with Cloudflare Access (allow: ${w.allow.join(', ')})`);
|
|
99
|
+
return;
|
|
100
|
+
}
|
|
101
|
+
if (!wanted.length && !readState(proj.project).length) return;
|
|
102
|
+
await guard(async () => {
|
|
103
|
+
const all = await listApps(cf);
|
|
104
|
+
const ours = all.filter((a) => ownedBy(a, proj.project));
|
|
105
|
+
const kept = [];
|
|
106
|
+
if (wanted.length) await ensureTag(cf);
|
|
107
|
+
for (const w of wanted) {
|
|
108
|
+
const foreign = all.find((a) => a.domain === w.hostname && !ownedBy(a));
|
|
109
|
+
if (foreign) {
|
|
110
|
+
log(`Access: https://${w.hostname} already has an Access app not managed by burrow ("${foreign.name}"); leaving it alone.`);
|
|
111
|
+
continue;
|
|
112
|
+
}
|
|
113
|
+
const body = { name: w.name, domain: w.hostname, type: 'self_hosted', session_duration: '24h', app_launcher_visible: false, tags: [ACCESS_TAG] };
|
|
114
|
+
let app = ours.find((a) => a.name === w.name);
|
|
115
|
+
if (!app) {
|
|
116
|
+
app = (await cf.req('POST', appsPath(cf), { body })).result;
|
|
117
|
+
log(`Access: protected https://${w.hostname} (app ${app.id})`);
|
|
118
|
+
} else if (app.domain !== w.hostname || app.type !== 'self_hosted') {
|
|
119
|
+
app = (await cf.req('PUT', `${appsPath(cf)}/${app.id}`, { body: { ...body, id: app.id } })).result;
|
|
120
|
+
log(`Access: updated the app for https://${w.hostname}`);
|
|
121
|
+
}
|
|
122
|
+
await syncPolicy(cf, app, w);
|
|
123
|
+
kept.push({ id: app.id, name: w.name, hostname: w.hostname });
|
|
124
|
+
}
|
|
125
|
+
for (const a of ours) {
|
|
126
|
+
if (kept.some((k) => k.id === a.id)) continue;
|
|
127
|
+
await cf.req('DELETE', `${appsPath(cf)}/${a.id}`, { allow404: true });
|
|
128
|
+
log(`Access: removed ${a.name}; https://${a.domain} is public again`);
|
|
129
|
+
}
|
|
130
|
+
writeState(proj.project, kept);
|
|
131
|
+
});
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
// Called by `burrow destroy`: delete every Access app burrow made for the project.
|
|
135
|
+
export async function removeAccessApps(cf, project) {
|
|
136
|
+
if (!readState(project).length) return 0;
|
|
137
|
+
return guard(async () => {
|
|
138
|
+
let n = 0;
|
|
139
|
+
for (const a of (await listApps(cf)).filter((x) => ownedBy(x, project))) {
|
|
140
|
+
await cf.req('DELETE', `${appsPath(cf)}/${a.id}`, { allow404: true });
|
|
141
|
+
log(`${project}: deleted Access app ${a.name} (${a.domain})`);
|
|
142
|
+
n++;
|
|
143
|
+
}
|
|
144
|
+
writeState(project, []);
|
|
145
|
+
return n;
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
// For `burrow prune`: burrow-owned apps whose project has no local state. A token without
|
|
150
|
+
// Access permission (or an account without Access) simply has no orphan apps.
|
|
151
|
+
export async function orphanAccessApps(cf, local) {
|
|
152
|
+
try {
|
|
153
|
+
return (await listApps(cf)).filter((a) => ownedBy(a) && !local.has(String(a.name).split(':')[1]));
|
|
154
|
+
} catch (e) {
|
|
155
|
+
if (isAuthError(e)) log(`Skipping Access apps: ${PERMISSION_HINT}`);
|
|
156
|
+
return [];
|
|
157
|
+
}
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
export async function deleteAccessApp(cf, app) {
|
|
161
|
+
await cf.req('DELETE', `${appsPath(cf)}/${app.id}`, { allow404: true });
|
|
162
|
+
rmSync(accessStateFile(String(app.name).split(':')[1]), { force: true });
|
|
163
|
+
}
|
package/src/add.js
ADDED
|
@@ -0,0 +1,106 @@
|
|
|
1
|
+
import { existsSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { basename, dirname, resolve } from 'node:path';
|
|
3
|
+
import { createInterface } from 'node:readline/promises';
|
|
4
|
+
import YAML from 'yaml';
|
|
5
|
+
import { loadConfig } from './config.js';
|
|
6
|
+
import { parseProject, hostnames } from './project.js';
|
|
7
|
+
|
|
8
|
+
// "3100" -> http://localhost:3100, "host:8080" -> http://host:8080, URLs unchanged.
|
|
9
|
+
export function toUrl(value) {
|
|
10
|
+
const v = String(value ?? '').trim();
|
|
11
|
+
if (/^\d+$/.test(v)) return `http://localhost:${v}`;
|
|
12
|
+
if (/^[a-z0-9.-]+:\d+$/i.test(v)) return `http://${v}`;
|
|
13
|
+
return v;
|
|
14
|
+
}
|
|
15
|
+
|
|
16
|
+
export function slug(value) {
|
|
17
|
+
return String(value ?? '').toLowerCase().replace(/[^a-z0-9-]+/g, '-').replace(/^-+|-+$/g, '').slice(0, 40);
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
// "name=target" -> [name, url]
|
|
21
|
+
export function parsePair(spec, flag) {
|
|
22
|
+
const i = String(spec).indexOf('=');
|
|
23
|
+
if (i <= 0 || i === spec.length - 1) throw new Error(`${flag} must look like name=port-or-url, got "${spec}"`);
|
|
24
|
+
return [spec.slice(0, i).trim(), toUrl(spec.slice(i + 1))];
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
export function buildDoc({ project, app, paths = [], services = [] }) {
|
|
28
|
+
const doc = { project, services: [] };
|
|
29
|
+
if (app) {
|
|
30
|
+
const svc = { name: 'app', url: toUrl(app) };
|
|
31
|
+
if (paths.length) svc.paths = paths.map(([path, url]) => ({ path, url: toUrl(url) }));
|
|
32
|
+
doc.services.push(svc);
|
|
33
|
+
} else if (paths.length) {
|
|
34
|
+
throw new Error('Paths need an app service (--app).');
|
|
35
|
+
}
|
|
36
|
+
for (const [name, url] of services) doc.services.push({ name: slug(name), url: toUrl(url) });
|
|
37
|
+
return doc;
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
// Render and validate; throws with the same errors `burrow up` would give.
|
|
41
|
+
export function renderYaml(doc) {
|
|
42
|
+
const text = '# burrow tunnel config (see the burrow README for the format)\n' + YAML.stringify(doc, { lineWidth: 0 });
|
|
43
|
+
parseProject(text, 'generated tunnel.yml');
|
|
44
|
+
return text;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function readlineAsk(rl) {
|
|
48
|
+
return async (question, def = '') => {
|
|
49
|
+
const answer = (await rl.question(def ? `${question} [${def}]: ` : `${question}: `)).trim();
|
|
50
|
+
return answer || def;
|
|
51
|
+
};
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
export async function promptDoc(ask, defaults) {
|
|
55
|
+
const project = slug(await ask('Project name', defaults.project));
|
|
56
|
+
const app = await ask('App port or URL (root hostname, empty for none)', defaults.app);
|
|
57
|
+
const paths = [];
|
|
58
|
+
if (app) {
|
|
59
|
+
for (;;) {
|
|
60
|
+
const path = await ask(' Extra path on the app, e.g. /api (empty to finish)');
|
|
61
|
+
if (!path) break;
|
|
62
|
+
paths.push([path, await ask(` Port or URL for ${path}`)]);
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
const services = [];
|
|
66
|
+
for (;;) {
|
|
67
|
+
const name = await ask('Sub-service name, e.g. mail (empty to finish)');
|
|
68
|
+
if (!name) break;
|
|
69
|
+
services.push([name, await ask(` Port or URL for ${slug(name)}`)]);
|
|
70
|
+
}
|
|
71
|
+
return buildDoc({ project, app, paths, services });
|
|
72
|
+
}
|
|
73
|
+
|
|
74
|
+
export async function add(projectArg, opts = {}, ask) {
|
|
75
|
+
const file = resolve(opts.file || 'tunnel.yml');
|
|
76
|
+
if (existsSync(file) && !opts.force) throw new Error(`${file} already exists. Use --force to overwrite it.`);
|
|
77
|
+
const services = (opts.service || []).map((s) => parsePair(s, '--service'));
|
|
78
|
+
const paths = (opts.path || []).map((s) => parsePair(s, '--path'));
|
|
79
|
+
const project = slug(projectArg || basename(dirname(file)));
|
|
80
|
+
const hasFlags = !!opts.app || services.length > 0;
|
|
81
|
+
|
|
82
|
+
let doc;
|
|
83
|
+
if (hasFlags || opts.yes) {
|
|
84
|
+
if (!hasFlags) throw new Error('Pass --app and/or --service (or run without --yes to be prompted).');
|
|
85
|
+
doc = buildDoc({ project, app: opts.app, paths, services });
|
|
86
|
+
} else if (ask || process.stdin.isTTY) {
|
|
87
|
+
let rl;
|
|
88
|
+
if (!ask) {
|
|
89
|
+
rl = createInterface({ input: process.stdin, output: process.stdout });
|
|
90
|
+
ask = readlineAsk(rl);
|
|
91
|
+
}
|
|
92
|
+
try { doc = await promptDoc(ask, { project, app: '' }); } finally { rl?.close(); }
|
|
93
|
+
} else {
|
|
94
|
+
throw new Error('Not a terminal: pass --app and/or --service to create tunnel.yml without prompts.');
|
|
95
|
+
}
|
|
96
|
+
|
|
97
|
+
const text = renderYaml(doc);
|
|
98
|
+
writeFileSync(file, text);
|
|
99
|
+
console.log(`Wrote ${file}`);
|
|
100
|
+
const cfg = loadConfig();
|
|
101
|
+
if (cfg.domain) {
|
|
102
|
+
for (const h of hostnames(parseProject(text), cfg.domain)) console.log(` ${h.service.padEnd(10)} https://${h.hostname}`);
|
|
103
|
+
}
|
|
104
|
+
console.log(`Next: burrow up${opts.file ? ` -f ${opts.file}` : ''}`);
|
|
105
|
+
return { file, doc };
|
|
106
|
+
}
|
|
@@ -0,0 +1,131 @@
|
|
|
1
|
+
// Minimal Cloudflare API v4 client. Never logs the token.
|
|
2
|
+
const DEFAULT_BASE = 'https://api.cloudflare.com/client/v4';
|
|
3
|
+
// BURROW_CF_API_BASE (environment only) points burrow at a mock API for tests
|
|
4
|
+
// and the README screenshots. Never set it in normal use.
|
|
5
|
+
// Under `node --test` (NODE_TEST_CONTEXT is set, also in spawned CLIs) the real
|
|
6
|
+
// API is refused outright, so a test can never touch a real account.
|
|
7
|
+
export function apiBase(env = process.env) {
|
|
8
|
+
const b = env.BURROW_CF_API_BASE || DEFAULT_BASE;
|
|
9
|
+
if (env.NODE_TEST_CONTEXT) {
|
|
10
|
+
let host = '';
|
|
11
|
+
try { host = new URL(b).hostname; } catch {}
|
|
12
|
+
if (host === 'cloudflare.com' || host.endsWith('.cloudflare.com')) {
|
|
13
|
+
throw new CloudflareError(`Refusing to call the real Cloudflare API (${host}) from a test: set BURROW_CF_API_BASE to a mock`);
|
|
14
|
+
}
|
|
15
|
+
}
|
|
16
|
+
return b;
|
|
17
|
+
}
|
|
18
|
+
const base = () => apiBase();
|
|
19
|
+
|
|
20
|
+
export class CloudflareError extends Error {}
|
|
21
|
+
|
|
22
|
+
export class Cloudflare {
|
|
23
|
+
constructor({ token, accountId, zoneId }) {
|
|
24
|
+
this.token = token;
|
|
25
|
+
this.accountId = accountId;
|
|
26
|
+
this.zoneId = zoneId;
|
|
27
|
+
}
|
|
28
|
+
|
|
29
|
+
async req(method, path, { query, body, allow404 = false } = {}) {
|
|
30
|
+
const url = new URL(base() + path);
|
|
31
|
+
for (const [k, v] of Object.entries(query || {})) if (v !== undefined && v !== '') url.searchParams.set(k, String(v));
|
|
32
|
+
const res = await fetch(url, {
|
|
33
|
+
method,
|
|
34
|
+
headers: { Authorization: `Bearer ${this.token}`, 'Content-Type': 'application/json' },
|
|
35
|
+
body: body === undefined ? undefined : JSON.stringify(body),
|
|
36
|
+
});
|
|
37
|
+
if (allow404 && res.status === 404) return null;
|
|
38
|
+
let json;
|
|
39
|
+
try { json = await res.json(); } catch { json = null; }
|
|
40
|
+
if (!res.ok || !json || json.success === false) {
|
|
41
|
+
const errs = (json?.errors || []).map((e) => `${e.code}: ${e.message}`).join('; ');
|
|
42
|
+
throw new CloudflareError(`${method} ${path} failed (HTTP ${res.status})${errs ? ` - ${errs}` : ''}`);
|
|
43
|
+
}
|
|
44
|
+
return json;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
async all(path, query = {}) {
|
|
48
|
+
const out = [];
|
|
49
|
+
for (let page = 1; ; page++) {
|
|
50
|
+
const j = await this.req('GET', path, { query: { ...query, page, per_page: query.per_page || 100 } });
|
|
51
|
+
out.push(...(j.result || []));
|
|
52
|
+
const info = j.result_info;
|
|
53
|
+
if (!info || !info.total_pages || page >= info.total_pages) break;
|
|
54
|
+
}
|
|
55
|
+
return out;
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
// Tokens
|
|
59
|
+
async verifyToken() {
|
|
60
|
+
try {
|
|
61
|
+
return (await this.req('GET', '/user/tokens/verify')).result;
|
|
62
|
+
} catch (e) {
|
|
63
|
+
if (!this.accountId) throw e;
|
|
64
|
+
// Account-owned tokens verify on the account endpoint.
|
|
65
|
+
return (await this.req('GET', `/accounts/${this.accountId}/tokens/verify`)).result;
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
// Zones
|
|
70
|
+
async resolveZoneId(domain) {
|
|
71
|
+
if (this.zoneId) return this.zoneId;
|
|
72
|
+
const zones = await this.all('/zones', { name: domain });
|
|
73
|
+
if (!zones.length) {
|
|
74
|
+
throw new CloudflareError(`Zone ${domain} not found. Set CF_ZONE_ID or grant the token Zone > Zone > Read.`);
|
|
75
|
+
}
|
|
76
|
+
this.zoneId = zones[0].id;
|
|
77
|
+
return this.zoneId;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
// Tunnels
|
|
81
|
+
async findTunnel(name) {
|
|
82
|
+
const list = await this.all(`/accounts/${this.accountId}/cfd_tunnel`, { name, is_deleted: false });
|
|
83
|
+
return list.find((t) => t.name === name) || null;
|
|
84
|
+
}
|
|
85
|
+
listTunnels() {
|
|
86
|
+
return this.all(`/accounts/${this.accountId}/cfd_tunnel`, { is_deleted: false });
|
|
87
|
+
}
|
|
88
|
+
async createTunnel(name, secret) {
|
|
89
|
+
const j = await this.req('POST', `/accounts/${this.accountId}/cfd_tunnel`, {
|
|
90
|
+
body: { name, config_src: 'cloudflare', tunnel_secret: secret },
|
|
91
|
+
});
|
|
92
|
+
return j.result;
|
|
93
|
+
}
|
|
94
|
+
async getTunnelToken(id) {
|
|
95
|
+
return (await this.req('GET', `/accounts/${this.accountId}/cfd_tunnel/${id}/token`)).result;
|
|
96
|
+
}
|
|
97
|
+
async putTunnelConfig(id, ingress) {
|
|
98
|
+
return (await this.req('PUT', `/accounts/${this.accountId}/cfd_tunnel/${id}/configurations`, {
|
|
99
|
+
body: { config: { ingress } },
|
|
100
|
+
})).result;
|
|
101
|
+
}
|
|
102
|
+
async getTunnelConfig(id) {
|
|
103
|
+
return (await this.req('GET', `/accounts/${this.accountId}/cfd_tunnel/${id}/configurations`)).result;
|
|
104
|
+
}
|
|
105
|
+
deleteTunnelConnections(id) {
|
|
106
|
+
return this.req('DELETE', `/accounts/${this.accountId}/cfd_tunnel/${id}/connections`, { allow404: true });
|
|
107
|
+
}
|
|
108
|
+
deleteTunnel(id) {
|
|
109
|
+
return this.req('DELETE', `/accounts/${this.accountId}/cfd_tunnel/${id}`, { allow404: true });
|
|
110
|
+
}
|
|
111
|
+
|
|
112
|
+
// DNS
|
|
113
|
+
recordsByName(name) {
|
|
114
|
+
return this.all(`/zones/${this.zoneId}/dns_records`, { name });
|
|
115
|
+
}
|
|
116
|
+
recordsByComment(comment) {
|
|
117
|
+
return this.all(`/zones/${this.zoneId}/dns_records`, { 'comment.exact': comment });
|
|
118
|
+
}
|
|
119
|
+
recordsByCommentPrefix(prefix) {
|
|
120
|
+
return this.all(`/zones/${this.zoneId}/dns_records`, { 'comment.startswith': prefix });
|
|
121
|
+
}
|
|
122
|
+
async createRecord(rec) {
|
|
123
|
+
return (await this.req('POST', `/zones/${this.zoneId}/dns_records`, { body: rec })).result;
|
|
124
|
+
}
|
|
125
|
+
async updateRecord(id, rec) {
|
|
126
|
+
return (await this.req('PUT', `/zones/${this.zoneId}/dns_records/${id}`, { body: rec })).result;
|
|
127
|
+
}
|
|
128
|
+
deleteRecord(id) {
|
|
129
|
+
return this.req('DELETE', `/zones/${this.zoneId}/dns_records/${id}`, { allow404: true });
|
|
130
|
+
}
|
|
131
|
+
}
|