burrow-cli 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +594 -2
- package/bin/burrow.js +200 -0
- package/examples/acme-shop.tunnel.yml +18 -0
- package/package.json +45 -4
- package/src/access.js +163 -0
- package/src/add.js +106 -0
- package/src/cloudflare.js +131 -0
- package/src/commands.js +386 -0
- package/src/completion.js +127 -0
- package/src/config-file.js +31 -0
- package/src/config.js +82 -0
- package/src/dashboard/auth.js +79 -0
- package/src/dashboard/data.js +70 -0
- package/src/dashboard/logs.js +95 -0
- package/src/dashboard/manage.js +102 -0
- package/src/dashboard/panels/README.md +50 -0
- package/src/dashboard/panels/access.js +218 -0
- package/src/dashboard/panels/alerts.js +244 -0
- package/src/dashboard/panels/backup.js +193 -0
- package/src/dashboard/panels/bulk.js +246 -0
- package/src/dashboard/panels/cleanup.js +237 -0
- package/src/dashboard/panels/doctor.js +119 -0
- package/src/dashboard/panels/health.js +146 -0
- package/src/dashboard/panels/history.js +104 -0
- package/src/dashboard/panels/hooks.js +86 -0
- package/src/dashboard/panels/live.js +153 -0
- package/src/dashboard/panels/project-form.js +463 -0
- package/src/dashboard/panels/quick-actions.js +133 -0
- package/src/dashboard/panels/sessions.js +267 -0
- package/src/dashboard/panels/shares.js +280 -0
- package/src/dashboard/panels/stats.js +165 -0
- package/src/dashboard/panels/updates.js +156 -0
- package/src/dashboard/panels/uptime.js +115 -0
- package/src/dashboard/panels.js +53 -0
- package/src/dashboard/server.js +390 -0
- package/src/dashboard/session-store.js +47 -0
- package/src/dashboard/totp.js +103 -0
- package/src/dashboard/ui.js +454 -0
- package/src/doctor.js +342 -0
- package/src/edit.js +135 -0
- package/src/health-observer.js +81 -0
- package/src/history.js +145 -0
- package/src/hooks.js +256 -0
- package/src/naming.js +38 -0
- package/src/open.js +67 -0
- package/src/pending.js +72 -0
- package/src/process.js +95 -0
- package/src/project-form.js +134 -0
- package/src/project.js +114 -0
- package/src/prune.js +99 -0
- package/src/rename-state.js +39 -0
- package/src/restart.js +35 -0
- package/src/service.js +173 -0
- package/src/share-expiry.js +55 -0
- package/src/share.js +275 -0
- package/src/shell-words.js +284 -0
- package/src/stats.js +180 -0
- package/src/transfer.js +124 -0
- package/src/update.js +254 -0
- package/src/uptime.js +91 -0
- package/src/watch.js +263 -0
- package/src/zones.js +102 -0
|
@@ -0,0 +1,267 @@
|
|
|
1
|
+
// Panel: signed-in sessions and optional two-factor sign-in (TOTP, see ../totp.js).
|
|
2
|
+
// Lists sessions by an opaque handle (a hash; session ids never leave the server), signs
|
|
3
|
+
// one out, all others, or everywhere. Two-factor setup shows the secret and QR code once;
|
|
4
|
+
// it is turned on only after a valid code, and turning it off needs a current code.
|
|
5
|
+
import { createHash } from 'node:crypto';
|
|
6
|
+
import { RateLimiter } from '../auth.js';
|
|
7
|
+
import { beginSetup, confirmSetup, disable, readTotp, totpEnabled, verifyCode } from '../totp.js';
|
|
8
|
+
|
|
9
|
+
export const order = 92;
|
|
10
|
+
const handleOf = (id) => createHash('sha256').update(`burrow-session-handle\0${id}`).digest('hex').slice(0, 16);
|
|
11
|
+
const codeLimiter = new RateLimiter({ max: 5, windowMs: 15 * 60 * 1000 });
|
|
12
|
+
|
|
13
|
+
function view(ctx) {
|
|
14
|
+
const cur = ctx.sessions.current();
|
|
15
|
+
const list = ctx.sessions.list()
|
|
16
|
+
.map((s) => ({
|
|
17
|
+
handle: handleOf(s.id), current: s.id === cur, createdAt: s.createdAt || null, lastSeen: s.lastSeen || null,
|
|
18
|
+
expiresAt: s.exp, ip: s.ip || null, agent: s.agent || '',
|
|
19
|
+
}))
|
|
20
|
+
.sort((a, b) => (b.current - a.current) || (b.lastSeen || 0) - (a.lastSeen || 0));
|
|
21
|
+
const t = readTotp();
|
|
22
|
+
return { sessions: list, twoFactor: { enabled: !!t.enabled, enabledAt: t.enabledAt || null, pending: !t.enabled && !!t.pending } };
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
export async function route(ctx) {
|
|
26
|
+
const { method, path } = ctx;
|
|
27
|
+
if (!path.startsWith('/api/sessions') && !path.startsWith('/api/two-factor')) return false;
|
|
28
|
+
if (method === 'GET' && path === '/api/sessions') return ctx.json(200, view(ctx)) ?? true;
|
|
29
|
+
if (method !== 'POST') return false;
|
|
30
|
+
const body = await ctx.readJson();
|
|
31
|
+
if (!body) return ctx.json(400, { error: 'invalid JSON' }) ?? true;
|
|
32
|
+
const cur = ctx.sessions.current();
|
|
33
|
+
|
|
34
|
+
if (path === '/api/sessions/revoke') {
|
|
35
|
+
const target = ctx.sessions.list().find((s) => handleOf(s.id) === String(body.handle || ''));
|
|
36
|
+
if (!target) return ctx.json(404, { error: 'no such session' }) ?? true;
|
|
37
|
+
ctx.sessions.revoke(target.id);
|
|
38
|
+
ctx.log(`signed out a session (requested from ${ctx.clientIp})`);
|
|
39
|
+
const self = target.id === cur;
|
|
40
|
+
return ctx.json(200, { ok: true, signedOut: self }, self ? { 'Set-Cookie': ctx.sessions.clearCookie() } : undefined) ?? true;
|
|
41
|
+
}
|
|
42
|
+
if (path === '/api/sessions/revoke-others' || path === '/api/sessions/revoke-all') {
|
|
43
|
+
const all = path.endsWith('all');
|
|
44
|
+
if (all && body.confirm !== true) return ctx.json(400, { error: 'confirm signing out everywhere (confirm: true)' }) ?? true;
|
|
45
|
+
let n = 0;
|
|
46
|
+
for (const s of ctx.sessions.list()) if (all || s.id !== cur) { ctx.sessions.revoke(s.id); n++; }
|
|
47
|
+
ctx.log(`signed out ${n} session(s)${all ? ' everywhere' : ''} (requested from ${ctx.clientIp})`);
|
|
48
|
+
ctx.events.emit('event', { action: all ? 'sign-out everywhere' : 'sign-out others', ok: true, detail: `${n} session(s)` });
|
|
49
|
+
return ctx.json(200, { ok: true, revoked: n, signedOut: all }, all ? { 'Set-Cookie': ctx.sessions.clearCookie() } : undefined) ?? true;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
// Two-factor. Code checks share a per-IP limit (5 wrong codes / 15 min).
|
|
53
|
+
const limited = () => {
|
|
54
|
+
const lim = codeLimiter.check(ctx.clientIp);
|
|
55
|
+
if (lim.allowed) return false;
|
|
56
|
+
ctx.json(429, { error: `Too many wrong codes. Try again in ${Math.ceil(lim.retryAfter / 60)} min.` }, { 'Retry-After': String(lim.retryAfter) });
|
|
57
|
+
return true;
|
|
58
|
+
};
|
|
59
|
+
if (path === '/api/two-factor/setup') {
|
|
60
|
+
try {
|
|
61
|
+
const s = beginSetup('dashboard');
|
|
62
|
+
ctx.log(`two-factor setup started (requested from ${ctx.clientIp})`);
|
|
63
|
+
// The only response that ever carries the secret.
|
|
64
|
+
return ctx.json(200, { ok: true, secret: s.secret, uri: s.uri }) ?? true;
|
|
65
|
+
} catch (e) { return ctx.json(409, { error: e.message }) ?? true; }
|
|
66
|
+
}
|
|
67
|
+
if (path === '/api/two-factor/enable') {
|
|
68
|
+
if (limited()) return true;
|
|
69
|
+
let ok;
|
|
70
|
+
try { ok = confirmSetup(body.code); } catch (e) { return ctx.json(409, { error: e.message }) ?? true; }
|
|
71
|
+
if (!ok) { codeLimiter.fail(ctx.clientIp); return ctx.json(400, { error: 'That code is not right. Check the time on your phone and try the newest code.' }) ?? true; }
|
|
72
|
+
codeLimiter.reset(ctx.clientIp);
|
|
73
|
+
let n = 0;
|
|
74
|
+
if (body.signOutOthers === true) for (const s of ctx.sessions.list()) if (s.id !== cur) { ctx.sessions.revoke(s.id); n++; }
|
|
75
|
+
ctx.log(`two-factor sign-in turned on (requested from ${ctx.clientIp})`);
|
|
76
|
+
ctx.events.emit('event', { action: 'two-factor on', ok: true, detail: n ? `signed out ${n} other session(s)` : '' });
|
|
77
|
+
return ctx.json(200, { ok: true, ...view(ctx) }) ?? true;
|
|
78
|
+
}
|
|
79
|
+
if (path === '/api/two-factor/disable') {
|
|
80
|
+
if (!totpEnabled()) return ctx.json(409, { error: 'two-factor sign-in is off' }) ?? true;
|
|
81
|
+
if (body.confirm !== true) return ctx.json(400, { error: 'confirm turning two-factor sign-in off (confirm: true)' }) ?? true;
|
|
82
|
+
if (limited()) return true;
|
|
83
|
+
if (!verifyCode(body.code)) { codeLimiter.fail(ctx.clientIp); return ctx.json(400, { error: 'That code is not right, or it was already used: wait for the next one.' }) ?? true; }
|
|
84
|
+
codeLimiter.reset(ctx.clientIp);
|
|
85
|
+
disable();
|
|
86
|
+
ctx.log(`two-factor sign-in turned off (requested from ${ctx.clientIp})`);
|
|
87
|
+
ctx.events.emit('event', { action: 'two-factor off', ok: true });
|
|
88
|
+
return ctx.json(200, { ok: true, ...view(ctx) }) ?? true;
|
|
89
|
+
}
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
|
|
93
|
+
export const html = {
|
|
94
|
+
toolbar: '<li><button class="secondary outline" @click="openSessions">Sessions</button></li>',
|
|
95
|
+
sections: `
|
|
96
|
+
<article x-show="sessionsOpen" class="sessions">
|
|
97
|
+
<header class="logs-head">
|
|
98
|
+
<strong>Sessions</strong><small class="muted">browsers signed in to this dashboard</small>
|
|
99
|
+
<span class="spacer"></span>
|
|
100
|
+
<button class="secondary outline" :disabled="noOtherSessions" @click="revokeOthers">Sign out other sessions</button>
|
|
101
|
+
<button class="danger outline" @click="askSignOutAll">Sign out everywhere</button>
|
|
102
|
+
<button class="secondary outline" @click="closeSessions">Close</button>
|
|
103
|
+
</header>
|
|
104
|
+
<table class="session-list">
|
|
105
|
+
<thead><tr><th>Browser</th><th>IP</th><th>Signed in</th><th>Last active</th><th></th></tr></thead>
|
|
106
|
+
<tbody>
|
|
107
|
+
<template x-for="s in sessionRows" :key="s.handle">
|
|
108
|
+
<tr>
|
|
109
|
+
<td><span x-text="browserName(s)"></span> <span class="badge ok" x-show="s.current">this browser</span></td>
|
|
110
|
+
<td><code x-text="s.ip"></code></td>
|
|
111
|
+
<td><small x-text="sessionAgo(s.createdAt)"></small></td>
|
|
112
|
+
<td><small x-text="sessionAgo(s.lastSeen)"></small></td>
|
|
113
|
+
<td><button class="secondary outline" @click="revokeSession(s)" x-text="revokeLabel(s)"></button></td>
|
|
114
|
+
</tr>
|
|
115
|
+
</template>
|
|
116
|
+
</tbody>
|
|
117
|
+
</table>
|
|
118
|
+
<p><small class="muted">Sessions last 12 hours. Restarting the dashboard or changing its password signs everyone out.</small></p>
|
|
119
|
+
|
|
120
|
+
<h4>Two-factor sign-in</h4>
|
|
121
|
+
<div x-show="tfaOff">
|
|
122
|
+
<p><small>Off. With it on, signing in also needs a 6-digit code from an authenticator app (any TOTP app).</small></p>
|
|
123
|
+
<button class="secondary outline" @click="startTfa" x-show="noTfaSetup">Set up two-factor sign-in</button>
|
|
124
|
+
<div x-show="hasTfaSetup" class="tfa-setup">
|
|
125
|
+
<p><small>Scan this with your authenticator app, or enter the key by hand. It is shown only now: once two-factor is on, the dashboard never shows it again.</small></p>
|
|
126
|
+
<p class="qr-img"><img :src="tfaQr" alt="Two-factor setup QR code" width="232" height="232" x-show="hasTfaQr"></p>
|
|
127
|
+
<p><small>Key: <code class="tfa-secret" x-text="tfaSecretGroups"></code></small></p>
|
|
128
|
+
<form class="tfa-form" @submit.prevent="enableTfa">
|
|
129
|
+
<input type="text" x-model="tfaCode" placeholder="6-digit code" aria-label="Code from the app" inputmode="numeric" autocomplete="one-time-code" maxlength="7" required>
|
|
130
|
+
<button type="submit" :aria-busy="tfaBusy" :disabled="tfaBusy">Turn on</button>
|
|
131
|
+
<button type="button" class="secondary" @click="cancelTfa">Cancel</button>
|
|
132
|
+
</form>
|
|
133
|
+
<label><input type="checkbox" x-model="tfaSignOutOthers"> Sign out other sessions</label>
|
|
134
|
+
</div>
|
|
135
|
+
</div>
|
|
136
|
+
<div x-show="tfaOn">
|
|
137
|
+
<p><small><span class="badge ok">on</span> Signing in needs a code from your authenticator app<span x-text="tfaSince"></span>.</small></p>
|
|
138
|
+
<form class="tfa-form" @submit.prevent="askDisableTfa">
|
|
139
|
+
<input type="text" x-model="tfaCode" placeholder="Current 6-digit code" aria-label="Current code" inputmode="numeric" autocomplete="one-time-code" maxlength="7" required>
|
|
140
|
+
<button type="submit" class="danger outline">Turn off</button>
|
|
141
|
+
</form>
|
|
142
|
+
</div>
|
|
143
|
+
<p class="error" x-show="hasSessionError" x-text="sessionError"></p>
|
|
144
|
+
</article>
|
|
145
|
+
<dialog :open="confirmSessOpen">
|
|
146
|
+
<article>
|
|
147
|
+
<header><strong x-text="confirmSessTitle"></strong></header>
|
|
148
|
+
<p x-text="confirmSessText"></p>
|
|
149
|
+
<footer>
|
|
150
|
+
<button class="secondary" @click="closeConfirmSess">Cancel</button>
|
|
151
|
+
<button class="danger" :aria-busy="tfaBusy" @click="runConfirmSess" x-text="confirmSessButton"></button>
|
|
152
|
+
</footer>
|
|
153
|
+
</article>
|
|
154
|
+
</dialog>`,
|
|
155
|
+
};
|
|
156
|
+
|
|
157
|
+
export const css = `
|
|
158
|
+
.session-list{font-size:.875rem}
|
|
159
|
+
.tfa-form{display:flex;gap:.5rem;align-items:center;max-width:520px}.tfa-form input,.tfa-form button{margin:0;width:auto}
|
|
160
|
+
.tfa-form input{flex:1}.tfa-secret{word-break:break-all;letter-spacing:.05em}
|
|
161
|
+
.sessions .qr-img img{image-rendering:pixelated;background:#fff;padding:8px;border-radius:8px}
|
|
162
|
+
`;
|
|
163
|
+
|
|
164
|
+
export const js = `
|
|
165
|
+
burrowPanel(function () {
|
|
166
|
+
var qrLoading = null;
|
|
167
|
+
function loadQr() {
|
|
168
|
+
if (window.qrcode) return Promise.resolve();
|
|
169
|
+
if (!qrLoading) {
|
|
170
|
+
qrLoading = new Promise(function (resolve, reject) {
|
|
171
|
+
var s = document.createElement('script');
|
|
172
|
+
s.src = '/vendor/qrcode.js';
|
|
173
|
+
s.onload = function () { resolve(); };
|
|
174
|
+
s.onerror = function () { qrLoading = null; reject(new Error('could not load the QR library')); };
|
|
175
|
+
document.head.appendChild(s);
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
return qrLoading;
|
|
179
|
+
}
|
|
180
|
+
return {
|
|
181
|
+
sessionsOpen: false, sessionRows: [], twoFactor: { enabled: false, enabledAt: null }, sessionError: '',
|
|
182
|
+
tfaSecret: '', tfaQr: '', tfaCode: '', tfaBusy: false, tfaSignOutOthers: true,
|
|
183
|
+
confirmSessOpen: false, confirmSessKind: '',
|
|
184
|
+
get hasSessionError() { return this.sessionError.length > 0; },
|
|
185
|
+
get noOtherSessions() { return this.sessionRows.filter(function (s) { return !s.current; }).length === 0; },
|
|
186
|
+
get tfaOn() { return !!this.twoFactor.enabled; },
|
|
187
|
+
get tfaOff() { return !this.twoFactor.enabled; },
|
|
188
|
+
get hasTfaSetup() { return this.tfaSecret.length > 0; },
|
|
189
|
+
get noTfaSetup() { return this.tfaSecret.length === 0; },
|
|
190
|
+
get hasTfaQr() { return this.tfaQr.length > 0; },
|
|
191
|
+
get tfaSecretGroups() { return this.tfaSecret.replace(/(.{4})/g, '$1 ').trim(); },
|
|
192
|
+
get tfaSince() { return this.twoFactor.enabledAt ? ' (on since ' + new Date(this.twoFactor.enabledAt).toLocaleString() + ')' : ''; },
|
|
193
|
+
get confirmSessTitle() { return this.confirmSessKind === 'all' ? 'Sign out everywhere?' : 'Turn off two-factor sign-in?'; },
|
|
194
|
+
get confirmSessText() {
|
|
195
|
+
return this.confirmSessKind === 'all'
|
|
196
|
+
? 'Every browser signed in to this dashboard, including this one, has to sign in again.'
|
|
197
|
+
: 'Signing in will only need the password. You can set it up again later with a new key.';
|
|
198
|
+
},
|
|
199
|
+
get confirmSessButton() { return this.confirmSessKind === 'all' ? 'Sign out everywhere' : 'Turn off'; },
|
|
200
|
+
browserName: function (s) {
|
|
201
|
+
var a = s.agent || '';
|
|
202
|
+
var b = /Edg\\//.test(a) ? 'Edge' : /Firefox\\//.test(a) ? 'Firefox' : /Chrome\\//.test(a) ? 'Chrome' : /Safari\\//.test(a) ? 'Safari' : (a ? a.split(' ')[0] : 'Unknown');
|
|
203
|
+
var os = /Android/.test(a) ? 'Android' : /iPhone|iPad/.test(a) ? 'iOS' : /Mac OS X/.test(a) ? 'macOS' : /Windows/.test(a) ? 'Windows' : /Linux/.test(a) ? 'Linux' : '';
|
|
204
|
+
return b + (os ? ' on ' + os : '');
|
|
205
|
+
},
|
|
206
|
+
sessionAgo: function (t) { return t ? ago(Date.now() - t) + ' ago' : '—'; },
|
|
207
|
+
revokeLabel: function (s) { return s.current ? 'Sign out' : 'Sign out this session'; },
|
|
208
|
+
openSessions: function () { this.sessionsOpen = true; this.loadSessions(); },
|
|
209
|
+
closeSessions: function () { this.sessionsOpen = false; this.cancelTfa(); },
|
|
210
|
+
loadSessions: async function () {
|
|
211
|
+
try { var j = await getJson('/api/sessions'); this.sessionRows = j.sessions; this.twoFactor = j.twoFactor; }
|
|
212
|
+
catch (e) { this.sessionError = e.message; }
|
|
213
|
+
},
|
|
214
|
+
sessPost: async function (url, body) {
|
|
215
|
+
this.sessionError = '';
|
|
216
|
+
var r = await post(url, body || {});
|
|
217
|
+
if (r.status === 401) { location.assign('/login'); throw new Error('signed out'); }
|
|
218
|
+
var j = await r.json().catch(function () { return {}; });
|
|
219
|
+
if (!r.ok) throw new Error(j.error || 'HTTP ' + r.status);
|
|
220
|
+
if (j.signedOut) { location.assign('/login'); throw new Error('signed out'); }
|
|
221
|
+
return j;
|
|
222
|
+
},
|
|
223
|
+
revokeSession: async function (s) {
|
|
224
|
+
try { await this.sessPost('/api/sessions/revoke', { handle: s.handle }); this.loadSessions(); } catch (e) { this.sessionError = e.message; }
|
|
225
|
+
},
|
|
226
|
+
revokeOthers: async function () {
|
|
227
|
+
try { var j = await this.sessPost('/api/sessions/revoke-others'); this.showToast('✓ signed out ' + j.revoked + ' session(s)', true, 4000); this.loadSessions(); }
|
|
228
|
+
catch (e) { this.sessionError = e.message; }
|
|
229
|
+
},
|
|
230
|
+
askSignOutAll: function () { this.confirmSessKind = 'all'; this.confirmSessOpen = true; },
|
|
231
|
+
askDisableTfa: function () { this.confirmSessKind = 'tfa'; this.confirmSessOpen = true; },
|
|
232
|
+
closeConfirmSess: function () { this.confirmSessOpen = false; },
|
|
233
|
+
runConfirmSess: async function () {
|
|
234
|
+
var kind = this.confirmSessKind;
|
|
235
|
+
this.confirmSessOpen = false;
|
|
236
|
+
if (kind === 'all') { try { await this.sessPost('/api/sessions/revoke-all', { confirm: true }); } catch (e) { this.sessionError = e.message; } return; }
|
|
237
|
+
this.tfaBusy = true;
|
|
238
|
+
try {
|
|
239
|
+
var j = await this.sessPost('/api/two-factor/disable', { code: this.tfaCode, confirm: true });
|
|
240
|
+
this.twoFactor = j.twoFactor; this.tfaCode = '';
|
|
241
|
+
this.showToast('✓ two-factor sign-in is off', true, 5000);
|
|
242
|
+
} catch (e) { this.sessionError = e.message; } finally { this.tfaBusy = false; }
|
|
243
|
+
},
|
|
244
|
+
startTfa: async function () {
|
|
245
|
+
try {
|
|
246
|
+
var j = await this.sessPost('/api/two-factor/setup');
|
|
247
|
+
this.tfaSecret = j.secret; this.tfaCode = ''; this.tfaQr = '';
|
|
248
|
+
await loadQr();
|
|
249
|
+
var q = window.qrcode(0, 'M');
|
|
250
|
+
q.addData(j.uri);
|
|
251
|
+
q.make();
|
|
252
|
+
this.tfaQr = q.createDataURL(4, 2);
|
|
253
|
+
} catch (e) { this.sessionError = e.message; }
|
|
254
|
+
},
|
|
255
|
+
cancelTfa: function () { this.tfaSecret = ''; this.tfaQr = ''; this.tfaCode = ''; },
|
|
256
|
+
enableTfa: async function () {
|
|
257
|
+
this.tfaBusy = true;
|
|
258
|
+
try {
|
|
259
|
+
var j = await this.sessPost('/api/two-factor/enable', { code: this.tfaCode, signOutOthers: this.tfaSignOutOthers });
|
|
260
|
+
this.twoFactor = j.twoFactor; this.sessionRows = j.sessions;
|
|
261
|
+
this.cancelTfa();
|
|
262
|
+
this.showToast('✓ two-factor sign-in is on', true, 5000);
|
|
263
|
+
} catch (e) { this.sessionError = e.message; } finally { this.tfaBusy = false; }
|
|
264
|
+
},
|
|
265
|
+
};
|
|
266
|
+
});
|
|
267
|
+
`;
|
|
@@ -0,0 +1,280 @@
|
|
|
1
|
+
// Panel: shares. Start a temporary `burrow share` link (detached) for a local port or URL,
|
|
2
|
+
// with an expiry, list the shares this machine has, extend them, or stop them (which deletes
|
|
3
|
+
// the hostname, tunnel and DNS record, like `burrow down share-<name>`). Expired shares are
|
|
4
|
+
// stopped by the dashboard; one that expired while it was off is stopped when it starts.
|
|
5
|
+
// Shares started in a terminal (`burrow share`, also with --expires) are listed too: the state
|
|
6
|
+
// file is shared, so extending one changes the expiry that process checks, and stopping one
|
|
7
|
+
// asks that process to remove it (it checks every 2 s); if it's gone, `burrow down` does it.
|
|
8
|
+
import { readdirSync } from 'node:fs';
|
|
9
|
+
import { assertLabel } from '../../naming.js';
|
|
10
|
+
import { loadConfig, stateDir } from '../../config.js';
|
|
11
|
+
import { readMeta, runningPid, saveMeta } from '../../process.js';
|
|
12
|
+
import { ensureExpiryWatcher } from '../../share-expiry.js';
|
|
13
|
+
import { SHARE_PREFIX, isShare, randomLabel, targetUrl, ownerAlive, requestStop } from '../../share.js';
|
|
14
|
+
import { runCli } from '../server.js';
|
|
15
|
+
|
|
16
|
+
export const order = 35;
|
|
17
|
+
export const EXPIRY_MINUTES = [15, 60, 240, 1440, 10080]; // 15 min … 7 days; 0 = never
|
|
18
|
+
const SWEEP_MS = 30 * 1000;
|
|
19
|
+
const HANDOFF_MS = Number(process.env.BURROW_SHARE_HANDOFF_MS) || 10 * 1000;
|
|
20
|
+
|
|
21
|
+
// Stop one share. A terminal-owned share is asked to stop itself (so its Ctrl+C cleanup and
|
|
22
|
+
// event history run there); if that process doesn't finish in time, or is gone, `burrow down`.
|
|
23
|
+
export async function stopShare(project, { run = runCli, wait = HANDOFF_MS } = {}) {
|
|
24
|
+
const meta = readMeta(project);
|
|
25
|
+
if (!meta) return { ok: true, output: `${project} is already gone` };
|
|
26
|
+
if (ownerAlive(meta)) {
|
|
27
|
+
requestStop(project);
|
|
28
|
+
const until = Date.now() + wait;
|
|
29
|
+
while (Date.now() < until) {
|
|
30
|
+
if (!readMeta(project)) return { ok: true, output: `Asked the terminal "burrow share" (pid ${meta.ownerPid}) to stop; it removed ${meta.hostname}.` };
|
|
31
|
+
await new Promise((r) => setTimeout(r, 250));
|
|
32
|
+
}
|
|
33
|
+
if (!readMeta(project)) return { ok: true, output: `Removed ${meta.hostname}` };
|
|
34
|
+
}
|
|
35
|
+
return run(['down', project]);
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
export function listShares(now = Date.now()) {
|
|
39
|
+
let names = [];
|
|
40
|
+
try { names = readdirSync(stateDir()).filter((f) => f.endsWith('.json')).map((f) => f.slice(0, -5)); } catch {}
|
|
41
|
+
return names.filter((n) => n.startsWith(SHARE_PREFIX) && isShare(n)).sort().map((project) => {
|
|
42
|
+
const m = readMeta(project);
|
|
43
|
+
const expiresAt = m.expiresAt || null;
|
|
44
|
+
return {
|
|
45
|
+
project, label: project.slice(SHARE_PREFIX.length), hostname: m.hostname, target: m.target,
|
|
46
|
+
createdAt: m.createdAt || null, expiresAt, expired: !!expiresAt && Date.parse(expiresAt) <= now,
|
|
47
|
+
running: !!runningPid(project), foreground: ownerAlive(m),
|
|
48
|
+
};
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
const expiryFrom = (minutes, now = Date.now()) => (minutes ? new Date(now + minutes * 60000).toISOString() : null);
|
|
53
|
+
function parseExpiry(v) {
|
|
54
|
+
const n = Number(v);
|
|
55
|
+
if (n === 0 || EXPIRY_MINUTES.includes(n)) return n;
|
|
56
|
+
throw new Error(`expiresIn must be one of 0 (never), ${EXPIRY_MINUTES.join(', ')} (minutes)`);
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
// Stop every expired share. `run` is runCli (injectable for tests).
|
|
60
|
+
const sweeping = new Set();
|
|
61
|
+
export async function sweepExpired({ now = Date.now(), run = runCli, onStopped = () => {} } = {}) {
|
|
62
|
+
const stopped = [];
|
|
63
|
+
for (const s of listShares(now)) {
|
|
64
|
+
// A terminal-owned share stops itself at its expiry; this only catches the rest.
|
|
65
|
+
if (!s.expired || sweeping.has(s.project)) continue;
|
|
66
|
+
sweeping.add(s.project);
|
|
67
|
+
try {
|
|
68
|
+
const r = await stopShare(s.project, { run });
|
|
69
|
+
stopped.push({ project: s.project, ok: r.ok });
|
|
70
|
+
onStopped(s, r);
|
|
71
|
+
} finally { sweeping.delete(s.project); }
|
|
72
|
+
}
|
|
73
|
+
return stopped;
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
let sweeper = null;
|
|
77
|
+
function startSweeper(ctx) {
|
|
78
|
+
if (sweeper) return;
|
|
79
|
+
const tick = () => sweepExpired({
|
|
80
|
+
onStopped: (s, r) => {
|
|
81
|
+
ctx.log(`share ${s.project} expired; stopped (${r.ok ? 'ok' : 'failed'})`);
|
|
82
|
+
ctx.events.emit('event', { action: 'share expired', project: s.project, ok: r.ok, detail: s.hostname });
|
|
83
|
+
ctx.invalidate();
|
|
84
|
+
},
|
|
85
|
+
}).catch(() => {});
|
|
86
|
+
sweeper = setInterval(tick, SWEEP_MS);
|
|
87
|
+
sweeper.unref?.();
|
|
88
|
+
setTimeout(tick, 2000).unref?.();
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
export async function enrich(projects, ctx) {
|
|
92
|
+
startSweeper(ctx);
|
|
93
|
+
for (const p of projects) {
|
|
94
|
+
if (!p.project.startsWith(SHARE_PREFIX)) continue;
|
|
95
|
+
const m = readMeta(p.project);
|
|
96
|
+
if (m?.share) p.shareExpiresAt = m.expiresAt || null;
|
|
97
|
+
}
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
export async function route(ctx) {
|
|
101
|
+
const { method, path } = ctx;
|
|
102
|
+
if (!path.startsWith('/api/shares')) return false;
|
|
103
|
+
startSweeper(ctx);
|
|
104
|
+
if (method === 'GET' && path === '/api/shares') {
|
|
105
|
+
return ctx.json(200, { shares: listShares(), domain: loadConfig().domain || null, expiry: EXPIRY_MINUTES }) ?? true;
|
|
106
|
+
}
|
|
107
|
+
if (method !== 'POST') return false;
|
|
108
|
+
const body = await ctx.readJson();
|
|
109
|
+
if (!body) return ctx.json(400, { error: 'invalid JSON' }) ?? true;
|
|
110
|
+
|
|
111
|
+
if (path === '/api/shares') {
|
|
112
|
+
let url; let label; let minutes;
|
|
113
|
+
try {
|
|
114
|
+
url = targetUrl(body.target);
|
|
115
|
+
label = String(body.name || '').trim() || randomLabel();
|
|
116
|
+
assertLabel(label, 'share name');
|
|
117
|
+
minutes = parseExpiry(body.expiresIn ?? 60);
|
|
118
|
+
if (readMeta(SHARE_PREFIX + label)) throw new Error(`a share called ${label} already exists`);
|
|
119
|
+
} catch (e) { return ctx.json(400, { error: e.message }) ?? true; }
|
|
120
|
+
const project = SHARE_PREFIX + label;
|
|
121
|
+
const r = await ctx.withBusy(project, async () => {
|
|
122
|
+
ctx.log(`share ${url} as ${label} for ${minutes || 'no'} minute(s) (requested from ${ctx.clientIp})`);
|
|
123
|
+
// --expires starts the share's expiry watcher, so it ends on time without the dashboard.
|
|
124
|
+
const run = await ctx.runCli(['share', url, '--name', label, '--detach', ...(minutes ? ['--expires', `${minutes}m`] : [])]);
|
|
125
|
+
const meta = readMeta(project);
|
|
126
|
+
ctx.invalidate();
|
|
127
|
+
return { ok: run.ok && !!meta, output: run.output, share: listShares().find((s) => s.project === project) || null };
|
|
128
|
+
});
|
|
129
|
+
if (!r) return ctx.json(409, { error: `${project} is busy` }) ?? true;
|
|
130
|
+
return ctx.json(r.ok ? 200 : 500, r) ?? true;
|
|
131
|
+
}
|
|
132
|
+
|
|
133
|
+
const m = path.match(/^\/api\/shares\/([^/]+)\/(stop|extend)$/);
|
|
134
|
+
if (!m) return false;
|
|
135
|
+
const [, project, action] = m;
|
|
136
|
+
try { assertLabel(project, 'share'); } catch { return ctx.json(400, { error: 'bad share' }) ?? true; }
|
|
137
|
+
if (!project.startsWith(SHARE_PREFIX) || !isShare(project)) return ctx.json(404, { error: `${project} is not a share` }) ?? true;
|
|
138
|
+
const meta = readMeta(project);
|
|
139
|
+
if (action === 'extend') {
|
|
140
|
+
let minutes;
|
|
141
|
+
try { minutes = parseExpiry(body.expiresIn); } catch (e) { return ctx.json(400, { error: e.message }) ?? true; }
|
|
142
|
+
saveMeta(project, { ...meta, expiresAt: expiryFrom(minutes) });
|
|
143
|
+
ensureExpiryWatcher(project); // a running watcher just re-reads the new expiry
|
|
144
|
+
return ctx.json(200, { ok: true, share: listShares().find((s) => s.project === project) }) ?? true;
|
|
145
|
+
}
|
|
146
|
+
if (body.confirm !== true) return ctx.json(400, { error: 'confirm stopping the share (confirm: true)' }) ?? true;
|
|
147
|
+
const r = await ctx.withBusy(project, async () => {
|
|
148
|
+
ctx.log(`stop share ${project} (requested from ${ctx.clientIp})`);
|
|
149
|
+
const run = await stopShare(project, { run: ctx.runCli });
|
|
150
|
+
ctx.invalidate();
|
|
151
|
+
return run;
|
|
152
|
+
});
|
|
153
|
+
if (!r) return ctx.json(409, { error: `${project} is busy` }) ?? true;
|
|
154
|
+
ctx.json(r.ok ? 200 : 500, r);
|
|
155
|
+
return true;
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
export const html = {
|
|
159
|
+
toolbar: '<li><button class="secondary outline" @click="openShares">Shares</button></li>',
|
|
160
|
+
sections: `
|
|
161
|
+
<article x-show="sharesOpen" class="shares">
|
|
162
|
+
<header class="logs-head">
|
|
163
|
+
<strong>Shares</strong><small class="muted">temporary links to a local port or URL</small>
|
|
164
|
+
<span class="spacer"></span>
|
|
165
|
+
<button class="secondary outline" @click="closeShares">Close</button>
|
|
166
|
+
</header>
|
|
167
|
+
<form class="share-form" @submit.prevent="startShare">
|
|
168
|
+
<input type="text" x-model="shareTarget" placeholder="Port or URL, e.g. 3000" aria-label="Port or URL to share" autocomplete="off" required>
|
|
169
|
+
<input type="text" x-model="shareName" placeholder="Name (optional)" aria-label="Share name" autocomplete="off">
|
|
170
|
+
<select x-model="shareExpiry" aria-label="Expires after">
|
|
171
|
+
<option value="15">15 minutes</option><option value="60">1 hour</option><option value="240">4 hours</option>
|
|
172
|
+
<option value="1440">1 day</option><option value="10080">7 days</option><option value="0">Never</option>
|
|
173
|
+
</select>
|
|
174
|
+
<button type="submit" :aria-busy="shareBusy" :disabled="shareBusy">Share</button>
|
|
175
|
+
</form>
|
|
176
|
+
<small class="muted" x-text="shareHostHint"></small>
|
|
177
|
+
<p class="error" x-show="hasShareError" x-text="shareError"></p>
|
|
178
|
+
<p x-show="noShares"><small class="muted">No shares.</small></p>
|
|
179
|
+
<table x-show="hasShares" class="share-list">
|
|
180
|
+
<thead><tr><th>Link</th><th>To</th><th>Expires</th><th></th></tr></thead>
|
|
181
|
+
<tbody>
|
|
182
|
+
<template x-for="s in shares" :key="s.project">
|
|
183
|
+
<tr>
|
|
184
|
+
<td><a :href="shareUrl(s)" target="_blank" rel="noopener noreferrer" x-text="s.hostname"></a> <span class="badge" :class="shareStateClass(s)" x-text="shareState(s)"></span></td>
|
|
185
|
+
<td><code x-text="s.target"></code></td>
|
|
186
|
+
<td><small x-text="shareExpires(s)"></small></td>
|
|
187
|
+
<td><div class="actions">
|
|
188
|
+
<button class="secondary outline" @click="extendShare(s)">+1 hour</button>
|
|
189
|
+
<button class="danger outline" :title="shareStopTitle(s)" @click="askStopShare(s)">Stop</button>
|
|
190
|
+
</div></td>
|
|
191
|
+
</tr>
|
|
192
|
+
</template>
|
|
193
|
+
</tbody>
|
|
194
|
+
</table>
|
|
195
|
+
</article>
|
|
196
|
+
<dialog :open="shareStopOpen">
|
|
197
|
+
<article>
|
|
198
|
+
<header><strong>Stop sharing <span x-text="shareStopHost"></span>?</strong></header>
|
|
199
|
+
<p>The link stops working right away: cloudflared is stopped and the share's tunnel and DNS record are deleted.</p>
|
|
200
|
+
<footer>
|
|
201
|
+
<button class="secondary" @click="closeStopShare">Cancel</button>
|
|
202
|
+
<button class="danger" :aria-busy="shareBusy" :disabled="shareBusy" @click="stopShare">Stop sharing</button>
|
|
203
|
+
</footer>
|
|
204
|
+
</article>
|
|
205
|
+
</dialog>`,
|
|
206
|
+
};
|
|
207
|
+
|
|
208
|
+
export const css = `
|
|
209
|
+
.share-form{display:grid;grid-template-columns:2fr 1.5fr 1fr auto;gap:.5rem;align-items:start;margin:.5rem 0 .2rem}
|
|
210
|
+
.share-form input,.share-form select,.share-form button{margin:0}
|
|
211
|
+
.share-list{font-size:.875rem;margin-top:.6rem}
|
|
212
|
+
@media (max-width:700px){.share-form{grid-template-columns:1fr}}
|
|
213
|
+
`;
|
|
214
|
+
|
|
215
|
+
export const js = `
|
|
216
|
+
burrowPanel(function () {
|
|
217
|
+
return {
|
|
218
|
+
sharesOpen: false, shares: [], sharesLoaded: false, shareDomain: '', shareTarget: '', shareName: '', shareExpiry: '60',
|
|
219
|
+
shareBusy: false, shareError: '', shareStopOpen: false, shareStopping: null, sharesTimer: null,
|
|
220
|
+
get hasShares() { return this.shares.length > 0; },
|
|
221
|
+
get noShares() { return this.sharesLoaded && this.shares.length === 0; },
|
|
222
|
+
get hasShareError() { return this.shareError.length > 0; },
|
|
223
|
+
get shareStopHost() { return this.shareStopping ? this.shareStopping.hostname : ''; },
|
|
224
|
+
get shareHostHint() { return this.shareDomain ? 'Link: https://' + (this.shareName.trim() || '<random>') + '.' + this.shareDomain : ''; },
|
|
225
|
+
shareUrl: function (s) { return 'https://' + s.hostname; },
|
|
226
|
+
shareState: function (s) { return s.running ? (s.foreground ? 'terminal' : 'live') : 'stopped'; },
|
|
227
|
+
shareStateClass: function (s) { return s.running ? 'ok' : 'bad'; },
|
|
228
|
+
shareStopTitle: function (s) { return s.foreground ? 'Started with "burrow share" in a terminal: that process is asked to stop and remove it' : ''; },
|
|
229
|
+
shareExpires: function (s) {
|
|
230
|
+
if (!s.expiresAt) return s.foreground ? 'when the terminal stops' : 'never';
|
|
231
|
+
var left = Date.parse(s.expiresAt) - Date.now();
|
|
232
|
+
return left > 0 ? 'in ' + ago(left) : 'now';
|
|
233
|
+
},
|
|
234
|
+
openShares: function () {
|
|
235
|
+
var self = this;
|
|
236
|
+
this.sharesOpen = true; this.loadShares();
|
|
237
|
+
clearInterval(this.sharesTimer);
|
|
238
|
+
this.sharesTimer = setInterval(function () { if (self.sharesOpen) self.loadShares(); }, 15000);
|
|
239
|
+
},
|
|
240
|
+
closeShares: function () { this.sharesOpen = false; clearInterval(this.sharesTimer); },
|
|
241
|
+
loadShares: async function () {
|
|
242
|
+
try { var j = await getJson('/api/shares'); this.shares = j.shares; this.shareDomain = j.domain || ''; this.sharesLoaded = true; }
|
|
243
|
+
catch (e) { this.shareError = e.message; }
|
|
244
|
+
},
|
|
245
|
+
sharePost: async function (url, body) {
|
|
246
|
+
var r = await post(url, body);
|
|
247
|
+
if (r.status === 401) { location.assign('/login'); throw new Error('login required'); }
|
|
248
|
+
var j = await r.json().catch(function () { return {}; });
|
|
249
|
+
if (!r.ok) throw new Error(j.error || (j.output ? j.output.trim().split('\\n').pop() : 'HTTP ' + r.status));
|
|
250
|
+
return j;
|
|
251
|
+
},
|
|
252
|
+
startShare: async function () {
|
|
253
|
+
this.shareBusy = true; this.shareError = '';
|
|
254
|
+
try {
|
|
255
|
+
var j = await this.sharePost('/api/shares', { target: this.shareTarget, name: this.shareName.trim(), expiresIn: Number(this.shareExpiry) });
|
|
256
|
+
this.showToast('✓ sharing ' + (j.share ? 'https://' + j.share.hostname : ''), true, 8000);
|
|
257
|
+
this.shareTarget = ''; this.shareName = '';
|
|
258
|
+
this.loadShares(); this.load();
|
|
259
|
+
} catch (e) { this.shareError = e.message; } finally { this.shareBusy = false; }
|
|
260
|
+
},
|
|
261
|
+
extendShare: async function (s) {
|
|
262
|
+
try { await this.sharePost('/api/shares/' + encodeURIComponent(s.project) + '/extend', { expiresIn: 60 }); this.loadShares(); }
|
|
263
|
+
catch (e) { this.shareError = e.message; }
|
|
264
|
+
},
|
|
265
|
+
askStopShare: function (s) { this.shareStopping = s; this.shareStopOpen = true; },
|
|
266
|
+
closeStopShare: function () { this.shareStopOpen = false; },
|
|
267
|
+
stopShare: async function () {
|
|
268
|
+
var s = this.shareStopping;
|
|
269
|
+
if (!s) return;
|
|
270
|
+
this.shareBusy = true;
|
|
271
|
+
try {
|
|
272
|
+
await this.sharePost('/api/shares/' + encodeURIComponent(s.project) + '/stop', { confirm: true });
|
|
273
|
+
this.showToast('✓ stopped ' + s.hostname, true, 5000);
|
|
274
|
+
} catch (e) { this.shareError = e.message; } finally {
|
|
275
|
+
this.shareBusy = false; this.shareStopOpen = false; this.loadShares(); this.load();
|
|
276
|
+
}
|
|
277
|
+
},
|
|
278
|
+
};
|
|
279
|
+
});
|
|
280
|
+
`;
|