burrow-cli 0.0.0-stage → 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (63) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +594 -2
  3. package/bin/burrow.js +200 -0
  4. package/examples/acme-shop.tunnel.yml +18 -0
  5. package/package.json +45 -4
  6. package/src/access.js +163 -0
  7. package/src/add.js +106 -0
  8. package/src/cloudflare.js +131 -0
  9. package/src/commands.js +386 -0
  10. package/src/completion.js +127 -0
  11. package/src/config-file.js +31 -0
  12. package/src/config.js +82 -0
  13. package/src/dashboard/auth.js +79 -0
  14. package/src/dashboard/data.js +70 -0
  15. package/src/dashboard/logs.js +95 -0
  16. package/src/dashboard/manage.js +102 -0
  17. package/src/dashboard/panels/README.md +50 -0
  18. package/src/dashboard/panels/access.js +218 -0
  19. package/src/dashboard/panels/alerts.js +244 -0
  20. package/src/dashboard/panels/backup.js +193 -0
  21. package/src/dashboard/panels/bulk.js +246 -0
  22. package/src/dashboard/panels/cleanup.js +237 -0
  23. package/src/dashboard/panels/doctor.js +119 -0
  24. package/src/dashboard/panels/health.js +146 -0
  25. package/src/dashboard/panels/history.js +104 -0
  26. package/src/dashboard/panels/hooks.js +86 -0
  27. package/src/dashboard/panels/live.js +153 -0
  28. package/src/dashboard/panels/project-form.js +463 -0
  29. package/src/dashboard/panels/quick-actions.js +133 -0
  30. package/src/dashboard/panels/sessions.js +267 -0
  31. package/src/dashboard/panels/shares.js +280 -0
  32. package/src/dashboard/panels/stats.js +165 -0
  33. package/src/dashboard/panels/updates.js +156 -0
  34. package/src/dashboard/panels/uptime.js +115 -0
  35. package/src/dashboard/panels.js +53 -0
  36. package/src/dashboard/server.js +390 -0
  37. package/src/dashboard/session-store.js +47 -0
  38. package/src/dashboard/totp.js +103 -0
  39. package/src/dashboard/ui.js +454 -0
  40. package/src/doctor.js +342 -0
  41. package/src/edit.js +135 -0
  42. package/src/health-observer.js +81 -0
  43. package/src/history.js +145 -0
  44. package/src/hooks.js +256 -0
  45. package/src/naming.js +38 -0
  46. package/src/open.js +67 -0
  47. package/src/pending.js +72 -0
  48. package/src/process.js +95 -0
  49. package/src/project-form.js +134 -0
  50. package/src/project.js +114 -0
  51. package/src/prune.js +99 -0
  52. package/src/rename-state.js +39 -0
  53. package/src/restart.js +35 -0
  54. package/src/service.js +173 -0
  55. package/src/share-expiry.js +55 -0
  56. package/src/share.js +275 -0
  57. package/src/shell-words.js +284 -0
  58. package/src/stats.js +180 -0
  59. package/src/transfer.js +124 -0
  60. package/src/update.js +254 -0
  61. package/src/uptime.js +91 -0
  62. package/src/watch.js +263 -0
  63. package/src/zones.js +102 -0
@@ -0,0 +1,244 @@
1
+ // Panel: alerts. Shows and configures `burrow watch`: the alert channels (webhook,
2
+ // ntfy), its systemd unit, a test alert, and the last state it saw per project.
3
+ // Channel values are secrets: they're written to the config file but never sent back.
4
+ import { spawnSync } from 'node:child_process';
5
+ import { existsSync, readFileSync } from 'node:fs';
6
+ import { join } from 'node:path';
7
+ import { settings, sendAlert, watchStateFile, WATCH_UNIT } from '../../watch.js';
8
+ import { unitDir } from '../../service.js';
9
+ import { setConfigValues } from '../../config-file.js';
10
+
11
+ export const order = 70;
12
+ const KEYS = { webhook: 'BURROW_ALERT_WEBHOOK', ntfy: 'BURROW_ALERT_NTFY', ntfyToken: 'BURROW_ALERT_NTFY_TOKEN' };
13
+
14
+ const hostOf = (url) => { try { return new URL(url).hostname; } catch { return ''; } };
15
+ export function webhookKind(url) {
16
+ const host = hostOf(url);
17
+ if (host === 'hooks.slack.com') return 'Slack';
18
+ if (/(^|\.)discord(app)?\.com$/.test(host)) return 'Discord';
19
+ return 'JSON';
20
+ }
21
+
22
+ export function validate(field, value) {
23
+ if (value === '') return;
24
+ if (value.length > 500 || /\s/.test(value)) throw new Error(`${field}: no spaces, at most 500 characters`);
25
+ if (field === 'webhook' && !/^https?:\/\/[^/]+/.test(value)) throw new Error('webhook must be an http(s) URL');
26
+ if (field === 'ntfy' && !/^https?:\/\/[^/]+\/[^/]+/.test(value) && !/^[A-Za-z0-9_-]{1,64}$/.test(value)) {
27
+ throw new Error('ntfy must be a topic name (letters, digits, - and _) or a full topic URL');
28
+ }
29
+ }
30
+
31
+ function unitState() {
32
+ const installed = existsSync(join(unitDir(), WATCH_UNIT));
33
+ const r = spawnSync(process.env.BURROW_SYSTEMCTL || 'systemctl', ['--user', 'is-active', WATCH_UNIT], { encoding: 'utf8', timeout: 5000, killSignal: 'SIGKILL' });
34
+ const active = r.error ? 'unknown' : (r.stdout || '').trim() || 'unknown';
35
+ return { installed, active };
36
+ }
37
+
38
+ function readWatchState() { try { return JSON.parse(readFileSync(watchStateFile(), 'utf8')); } catch { return {}; } }
39
+
40
+ export function overview(env = process.env) {
41
+ const s = settings(env);
42
+ const ntfyServer = !s.ntfy ? '' : /^https?:\/\//.test(s.ntfy) ? hostOf(s.ntfy) : 'ntfy.sh';
43
+ return {
44
+ channels: {
45
+ webhook: { set: !!s.webhook, kind: s.webhook ? webhookKind(s.webhook) : '', host: hostOf(s.webhook), fromEnv: !!env[KEYS.webhook] },
46
+ ntfy: { set: !!s.ntfy, server: ntfyServer, fromEnv: !!env[KEYS.ntfy] },
47
+ ntfyToken: { set: !!s.ntfyToken, fromEnv: !!env[KEYS.ntfyToken] },
48
+ },
49
+ service: unitState(),
50
+ watch: Object.entries(readWatchState()).map(([project, st]) => ({ project, ...st })).sort((a, b) => a.project.localeCompare(b.project)),
51
+ };
52
+ }
53
+
54
+ export async function route(ctx) {
55
+ const { method, path } = ctx;
56
+ if (method === 'GET' && path === '/api/alerts') return ctx.json(200, overview()) ?? true;
57
+ if (method !== 'POST' || !path.startsWith('/api/alerts/')) return false;
58
+ const body = await ctx.readJson(4096);
59
+ if (!body) return ctx.json(400, { error: 'invalid JSON' }) ?? true;
60
+
61
+ if (path === '/api/alerts/config') {
62
+ const updates = {};
63
+ try {
64
+ for (const [field, key] of Object.entries(KEYS)) {
65
+ if (body[field] === undefined) continue;
66
+ const value = body[field] === null ? '' : String(body[field]).trim();
67
+ validate(field, value);
68
+ updates[key] = value;
69
+ }
70
+ if (!Object.keys(updates).length) throw new Error('nothing to change');
71
+ setConfigValues(updates);
72
+ } catch (e) { return ctx.json(400, { error: e.message }) ?? true; }
73
+ // Log which settings changed, never their values.
74
+ ctx.log(`alert settings changed: ${Object.keys(updates).join(', ')} (requested from ${ctx.clientIp})`);
75
+ ctx.events.emit('event', { action: 'alerts config', ok: true, detail: Object.keys(updates).join(', ') });
76
+ return ctx.json(200, { ok: true, ...overview() }) ?? true;
77
+ }
78
+
79
+ if (path === '/api/alerts/test') {
80
+ const s = settings();
81
+ if (!s.webhook && !s.ntfy) return ctx.json(400, { error: 'No alert channel set yet' }) ?? true;
82
+ const errors = [];
83
+ const failed = await sendAlert({
84
+ project: 'burrow-test', from: 'ok', to: 'degraded', at: Date.now(), hostnames: [],
85
+ problems: ['this is a test alert from the burrow dashboard'],
86
+ }, s, { report: (m) => errors.push(m) });
87
+ return ctx.json(failed ? 502 : 200, { ok: !failed, errors }) ?? true;
88
+ }
89
+
90
+ if (path === '/api/alerts/service') {
91
+ let args;
92
+ if (body.action === 'install') {
93
+ const interval = parseInt(body.interval ?? 60, 10);
94
+ const debounce = parseInt(body.debounce ?? 2, 10);
95
+ if (!(interval >= 10 && interval <= 86400)) return ctx.json(400, { error: 'interval: 10 to 86400 seconds' }) ?? true;
96
+ if (!(debounce >= 1 && debounce <= 20)) return ctx.json(400, { error: 'debounce: 1 to 20 checks' }) ?? true;
97
+ args = ['watch', '--install-service', '--interval', String(interval), '--debounce', String(debounce)];
98
+ } else if (body.action === 'uninstall') {
99
+ if (body.confirm !== true) return ctx.json(400, { error: 'confirm the uninstall' }) ?? true;
100
+ args = ['watch', '--uninstall-service'];
101
+ } else return ctx.json(400, { error: 'action must be install or uninstall' }) ?? true;
102
+ const r = await ctx.runCli(args, 60000);
103
+ return ctx.json(r.ok ? 200 : 500, { ...r, ...overview() }) ?? true;
104
+ }
105
+ return false;
106
+ }
107
+
108
+ export const html = {
109
+ toolbar: '<li><button class="secondary outline" @click="openAlerts">Alerts</button></li>',
110
+ sections: `
111
+ <article x-show="alertsOpen" class="alerts">
112
+ <header class="logs-head">
113
+ <strong>Alerts</strong><small class="muted">burrow watch</small>
114
+ <span class="spacer"></span>
115
+ <button class="secondary outline" @click="loadAlerts">Refresh</button>
116
+ <button class="secondary outline" @click="closeAlerts">Close</button>
117
+ </header>
118
+ <p class="error" x-show="hasAlertsError" x-text="alertsError"></p>
119
+ <div class="grid alerts-grid">
120
+ <section>
121
+ <h6>Watcher</h6>
122
+ <p>systemd unit <code>burrow-watch.service</code>:
123
+ <span class="badge" :class="unitClass" x-text="unitText"></span></p>
124
+ <div class="grid">
125
+ <label>Check every (s)<input type="number" min="10" max="86400" x-model="watchInterval"></label>
126
+ <label>Alert after (checks)<input type="number" min="1" max="20" x-model="watchDebounce"></label>
127
+ </div>
128
+ <div class="row-buttons">
129
+ <button :aria-busy="alertsBusy" :disabled="alertsBusy" @click="installWatch" x-text="installLabel"></button>
130
+ <button class="danger outline" x-show="unitInstalled" :disabled="alertsBusy" @click="askUninstall">Uninstall</button>
131
+ </div>
132
+ <h6>Last seen by the watcher</h6>
133
+ <p x-show="noWatchState"><small class="muted">Nothing yet. The watcher records a state per running project.</small></p>
134
+ <table class="striped" x-show="hasWatchState">
135
+ <thead><tr><th>Project</th><th>Status</th><th>Since</th><th>Pending</th></tr></thead>
136
+ <tbody><template x-for="w in alertsData.watch" :key="w.project">
137
+ <tr><td x-text="w.project"></td><td><span class="badge" :class="watchClass(w)" x-text="w.status"></span></td>
138
+ <td x-text="watchSince(w)"></td><td><small x-text="watchPending(w)"></small></td></tr>
139
+ </template></tbody>
140
+ </table>
141
+ </section>
142
+ <section>
143
+ <h6>Channels</h6>
144
+ <p class="channel"><strong>Webhook</strong> <span class="badge" :class="chanClass('webhook')" x-text="webhookText"></span>
145
+ <button type="button" x-show="canClear('webhook')" @click="clearChannel('webhook')" title="Remove">remove</button></p>
146
+ <input type="password" x-model="newWebhook" placeholder="https://hooks.slack.com/services/…" aria-label="Webhook URL" autocomplete="off">
147
+ <p class="channel"><strong>ntfy</strong> <span class="badge" :class="chanClass('ntfy')" x-text="ntfyText"></span>
148
+ <button type="button" x-show="canClear('ntfy')" @click="clearChannel('ntfy')" title="Remove">remove</button></p>
149
+ <input type="password" x-model="newNtfy" placeholder="topic or https://ntfy.example.dev/topic" aria-label="ntfy topic" autocomplete="off">
150
+ <p class="channel"><strong>ntfy token</strong> <span class="badge" :class="chanClass('ntfyToken')" x-text="tokenText"></span>
151
+ <button type="button" x-show="canClear('ntfyToken')" @click="clearChannel('ntfyToken')" title="Remove">remove</button></p>
152
+ <input type="password" x-model="newNtfyToken" placeholder="optional access token" aria-label="ntfy token" autocomplete="off">
153
+ <small class="muted">Saved to the burrow config file (mode 600). Values are never shown again. Settings from the
154
+ environment win over the file.</small>
155
+ <div class="row-buttons">
156
+ <button :disabled="cannotSaveChannels" @click="saveChannels">Save</button>
157
+ <button class="secondary outline" :disabled="noChannels" @click="testAlert">Send test alert</button>
158
+ </div>
159
+ </section>
160
+ </div>
161
+ </article>
162
+ <dialog :open="uninstallOpen">
163
+ <article>
164
+ <header><strong>Uninstall burrow-watch.service?</strong></header>
165
+ <p>This stops the watcher and removes its systemd unit. No more alerts are sent until you install it again.</p>
166
+ <footer>
167
+ <button class="secondary" @click="closeUninstall">Cancel</button>
168
+ <button class="danger" @click="uninstallWatch">Uninstall</button>
169
+ </footer>
170
+ </article>
171
+ </dialog>`,
172
+ };
173
+
174
+ export const css = `
175
+ .alerts-grid{align-items:start}.alerts h6{margin:.5rem 0}
176
+ .alerts input{margin-bottom:.5rem}.alerts .channel{margin:.4rem 0 .2rem}
177
+ .alerts .channel button{all:unset;cursor:pointer;font-size:.8rem;color:var(--pico-del-color);margin-left:.4rem}
178
+ .alerts .channel button:hover{text-decoration:underline}
179
+ .row-buttons{display:flex;gap:.5rem;margin:.5rem 0 1rem}.row-buttons button{width:auto;margin:0}
180
+ `;
181
+
182
+ export const js = `
183
+ burrowPanel(function () {
184
+ function empty() {
185
+ return { channels: { webhook: {}, ntfy: {}, ntfyToken: {} }, service: { installed: false, active: 'unknown' }, watch: [] };
186
+ }
187
+ return {
188
+ alertsOpen: false, alertsData: empty(), alertsError: '', alertsBusy: false, uninstallOpen: false,
189
+ watchInterval: 60, watchDebounce: 2, newWebhook: '', newNtfy: '', newNtfyToken: '',
190
+
191
+ get hasAlertsError() { return this.alertsError.length > 0; },
192
+ get unitInstalled() { return this.alertsData.service.installed; },
193
+ get unitText() { var s = this.alertsData.service; return s.installed ? s.active : 'not installed'; },
194
+ get unitClass() { var s = this.alertsData.service; return !s.installed ? '' : s.active === 'active' ? 'ok' : 'bad'; },
195
+ get installLabel() { return this.unitInstalled ? 'Reinstall with these settings' : 'Install and start'; },
196
+ get hasWatchState() { return this.alertsData.watch.length > 0; },
197
+ get noWatchState() { return this.alertsData.watch.length === 0; },
198
+ get noChannels() { var c = this.alertsData.channels; return !c.webhook.set && !c.ntfy.set; },
199
+ get cannotSaveChannels() { return this.alertsBusy || !(this.newWebhook || this.newNtfy || this.newNtfyToken); },
200
+ get webhookText() { var c = this.alertsData.channels.webhook; return c.set ? c.kind + ' · ' + c.host + (c.fromEnv ? ' (env)' : '') : 'not set'; },
201
+ get ntfyText() { var c = this.alertsData.channels.ntfy; return c.set ? c.server + (c.fromEnv ? ' (env)' : '') : 'not set'; },
202
+ get tokenText() { var c = this.alertsData.channels.ntfyToken; return c.set ? 'set' + (c.fromEnv ? ' (env)' : '') : 'not set'; },
203
+ chanClass: function (k) { return this.alertsData.channels[k].set ? 'ok' : ''; },
204
+ canClear: function (k) { var c = this.alertsData.channels[k]; return c.set && !c.fromEnv; },
205
+ watchClass: function (w) { return w.status === 'ok' ? 'ok' : w.status === 'down' ? 'bad' : 'warn'; },
206
+ watchSince: function (w) { return w.since ? ago(Date.now() - w.since) + ' ago' : ''; },
207
+ watchPending: function (w) { return w.pending ? w.pending + ' (' + w.count + ' check' + (w.count === 1 ? '' : 's') + ')' : ''; },
208
+
209
+ openAlerts: function () { this.alertsOpen = true; this.loadAlerts(); },
210
+ closeAlerts: function () { this.alertsOpen = false; },
211
+ loadAlerts: async function () {
212
+ this.alertsError = '';
213
+ try { this.alertsData = await getJson('/api/alerts'); } catch (e) { this.alertsError = e.message; }
214
+ },
215
+ alertsPost: async function (url, body, okText) {
216
+ this.alertsBusy = true; this.alertsError = '';
217
+ try {
218
+ var r = await post(url, body);
219
+ if (r.status === 401) { location.assign('/login'); return null; }
220
+ var j = await r.json().catch(function () { return {}; });
221
+ if (j.channels) this.alertsData = { channels: j.channels, service: j.service, watch: j.watch };
222
+ if (r.ok) this.showToast('✓ ' + okText + (j.output ? '\\n' + j.output : ''), true, 6000);
223
+ else this.alertsError = j.error || (j.errors || []).join('; ') || j.output || ('HTTP ' + r.status);
224
+ return r.ok ? j : null;
225
+ } catch (e) { this.alertsError = 'Network error'; return null; } finally { this.alertsBusy = false; }
226
+ },
227
+ saveChannels: async function () {
228
+ var body = {};
229
+ if (this.newWebhook) body.webhook = this.newWebhook;
230
+ if (this.newNtfy) body.ntfy = this.newNtfy;
231
+ if (this.newNtfyToken) body.ntfyToken = this.newNtfyToken;
232
+ if (await this.alertsPost('/api/alerts/config', body, 'Alert channels saved')) { this.newWebhook = ''; this.newNtfy = ''; this.newNtfyToken = ''; }
233
+ },
234
+ clearChannel: function (k) { var body = {}; body[k] = null; this.alertsPost('/api/alerts/config', body, 'Removed'); },
235
+ testAlert: function () { this.alertsPost('/api/alerts/test', {}, 'Test alert sent'); },
236
+ installWatch: function () {
237
+ this.alertsPost('/api/alerts/service', { action: 'install', interval: Number(this.watchInterval), debounce: Number(this.watchDebounce) }, 'Watcher installed');
238
+ },
239
+ askUninstall: function () { this.uninstallOpen = true; },
240
+ closeUninstall: function () { this.uninstallOpen = false; },
241
+ uninstallWatch: function () { this.uninstallOpen = false; this.alertsPost('/api/alerts/service', { action: 'uninstall', confirm: true }, 'Watcher removed'); },
242
+ };
243
+ });
244
+ `;
@@ -0,0 +1,193 @@
1
+ // Panel: backup and restore. Download a `burrow export` bundle of every remembered project
2
+ // (tunnel.yml settings only: no tokens, passwords or hooks), and restore one: the server
3
+ // previews what each project would do first, and writing needs a typed confirmation.
4
+ // Restoring only writes tunnel.yml files and remembers them; nothing is started.
5
+ import YAML from 'yaml';
6
+ import { buildBundle, parseBundle, planImport, writeImported } from '../../transfer.js';
7
+ import { hostnames, parseProject } from '../../project.js';
8
+
9
+ export const order = 88;
10
+ export const CONFIRM_WORD = 'restore';
11
+ const MAX_BYTES = 1024 * 1024;
12
+
13
+ export function exportText(bundle = buildBundle()) {
14
+ return '# burrow project export. Contains tunnel.yml settings only, no tokens or passwords.\n' + YAML.stringify(bundle, { lineWidth: 0 });
15
+ }
16
+
17
+ function preview(text, cfg) {
18
+ const plan = planImport(parseBundle(text, 'The backup'));
19
+ return plan.map((p) => ({
20
+ project: p.project, status: p.status, dest: p.dest || null, knownAt: p.knownAt || null, error: p.error || null,
21
+ services: p.proj ? p.proj.services.length : 0,
22
+ hostnames: p.proj && cfg.domain ? hostnames(parseProject(YAML.stringify(p.proj)), cfg.domain).map((h) => h.hostname) : [],
23
+ }));
24
+ }
25
+
26
+ export async function route(ctx) {
27
+ const { method, path } = ctx;
28
+ if (method === 'GET' && path === '/api/backup/export') {
29
+ let text;
30
+ try { text = exportText(); } catch (e) { return ctx.json(500, { error: e.message }) ?? true; }
31
+ const name = `burrow-projects-${new Date().toISOString().slice(0, 10)}.yml`;
32
+ ctx.log(`backup exported (requested from ${ctx.clientIp})`);
33
+ ctx.send(200, text, 'application/yaml; charset=utf-8', { 'Content-Disposition': `attachment; filename="${name}"` });
34
+ return true;
35
+ }
36
+ if (method !== 'POST' || !['/api/backup/preview', '/api/backup/restore'].includes(path)) return false;
37
+ const body = await ctx.readJson(MAX_BYTES + 4096);
38
+ if (!body || typeof body.text !== 'string') return ctx.json(400, { error: 'send the backup as { text }' }) ?? true;
39
+ if (Buffer.byteLength(body.text) > MAX_BYTES) return ctx.json(413, { error: 'backup larger than 1 MB' }) ?? true;
40
+ const cfg = ctx.loadConfig();
41
+ let items;
42
+ try { items = preview(body.text, cfg); } catch (e) { return ctx.json(400, { error: e.message }) ?? true; }
43
+ if (path === '/api/backup/preview') return ctx.json(200, { projects: items }) ?? true;
44
+
45
+ if (body.confirm !== CONFIRM_WORD) return ctx.json(400, { error: `type "${CONFIRM_WORD}" to confirm` }) ?? true;
46
+ const pick = new Set(Array.isArray(body.projects) ? body.projects.filter((x) => typeof x === 'string') : []);
47
+ if (!pick.size) return ctx.json(400, { error: 'nothing selected' }) ?? true;
48
+ const replace = body.replace === true;
49
+ const r = await ctx.withBusy('(backup)', async () => {
50
+ // Planned again here, so the result matches the files as they are now.
51
+ const plan = planImport(parseBundle(body.text, 'The backup'));
52
+ const written = [];
53
+ const skipped = [];
54
+ for (const p of plan) {
55
+ if (!pick.has(p.project)) continue;
56
+ if (p.status === 'invalid') { skipped.push({ project: p.project, reason: p.error }); continue; }
57
+ if (p.status !== 'new' && !replace) { skipped.push({ project: p.project, reason: p.status === 'known' ? `already remembered at ${p.knownAt}` : `${p.dest} exists` }); continue; }
58
+ try { writeImported(p); written.push({ project: p.project, file: p.dest, replaced: p.status !== 'new' }); } catch (e) {
59
+ skipped.push({ project: p.project, reason: e.message });
60
+ }
61
+ }
62
+ ctx.log(`backup restored: ${written.length} written, ${skipped.length} skipped (requested from ${ctx.clientIp})`);
63
+ ctx.events.emit('event', { action: 'restore', ok: true, detail: `${written.length} written, ${skipped.length} skipped` });
64
+ ctx.invalidate();
65
+ return { ok: true, written, skipped };
66
+ });
67
+ if (!r) return ctx.json(409, { error: 'a restore is already running' }) ?? true;
68
+ ctx.json(200, r);
69
+ return true;
70
+ }
71
+
72
+ export const html = {
73
+ toolbar: '<li><button class="secondary outline" @click="openBackup">Backup</button></li>',
74
+ sections: `
75
+ <article x-show="backupOpen" class="backup">
76
+ <header class="logs-head">
77
+ <strong>Backup and restore</strong><small class="muted">tunnel.yml settings only, no secrets</small>
78
+ <span class="spacer"></span>
79
+ <a class="secondary outline" role="button" href="/api/backup/export" download>Download backup</a>
80
+ <button class="secondary outline" @click="closeBackup">Close</button>
81
+ </header>
82
+ <label>Restore from a backup file
83
+ <input type="file" accept=".yml,.yaml,.json,application/yaml,application/json" @change="pickBackupFile" aria-label="Backup file">
84
+ </label>
85
+ <p class="error" x-show="hasBackupError" x-text="backupError"></p>
86
+ <div x-show="hasRestorePlan">
87
+ <table class="restore-plan">
88
+ <thead><tr><th></th><th>Project</th><th>What happens</th><th>Hostnames</th></tr></thead>
89
+ <tbody>
90
+ <template x-for="p in restorePlan" :key="p.project">
91
+ <tr>
92
+ <td><input type="checkbox" :value="p.project" x-model="restorePick" :disabled="restoreDisabled(p)" :aria-label="p.project"></td>
93
+ <td><strong x-text="p.project"></strong></td>
94
+ <td><span class="badge" :class="restoreClass(p)" x-text="restoreText(p)"></span> <small class="muted" x-text="restoreDetail(p)"></small></td>
95
+ <td><small x-text="restoreHosts(p)"></small></td>
96
+ </tr>
97
+ </template>
98
+ </tbody>
99
+ </table>
100
+ <label><input type="checkbox" role="switch" x-model="restoreReplace"> Replace projects that already exist</label>
101
+ <div class="row-buttons"><button class="danger" :disabled="nothingToRestore" @click="askRestore" x-text="restoreLabel"></button></div>
102
+ </div>
103
+ </article>
104
+ <dialog :open="restoreConfirmOpen">
105
+ <article>
106
+ <header><strong>Restore from the backup?</strong></header>
107
+ <p>This writes <strong x-text="restoreSummary"></strong> on the server and remembers them, so <strong>Up</strong> works.
108
+ <span x-show="restoreReplace">Existing files of picked projects are <strong>overwritten</strong>.</span>
109
+ Nothing is started. Type <strong>restore</strong> to confirm.</p>
110
+ <input type="text" x-model="restoreConfirmText" placeholder="restore" aria-label="Type restore to confirm" autocomplete="off">
111
+ <footer>
112
+ <button class="secondary" @click="closeRestoreConfirm">Cancel</button>
113
+ <button class="danger" :disabled="cannotRestore" :aria-busy="restoreBusy" @click="runRestore">Restore</button>
114
+ </footer>
115
+ </article>
116
+ </dialog>`,
117
+ };
118
+
119
+ export const css = `
120
+ .backup .restore-plan{font-size:.875rem;margin:.5rem 0}
121
+ .backup .row-buttons{display:flex;gap:.5rem;margin:.75rem 0}.backup .row-buttons button{width:auto;margin:0}
122
+ .backup a[role=button]{width:auto;margin:0;padding:.3rem .7rem;font-size:.85rem}
123
+ `;
124
+
125
+ export const js = `
126
+ burrowPanel(function () {
127
+ var TEXT = { new: 'new', exists: 'file exists', known: 'already remembered', invalid: 'invalid' };
128
+ var CLASS = { new: 'ok', exists: 'warn', known: 'warn', invalid: 'bad' };
129
+ return {
130
+ backupOpen: false, backupError: '', backupText: '', restorePlan: [], restorePick: [], restoreReplace: false,
131
+ restoreConfirmOpen: false, restoreConfirmText: '', restoreBusy: false,
132
+ get hasBackupError() { return this.backupError.length > 0; },
133
+ get hasRestorePlan() { return this.restorePlan.length > 0; },
134
+ get restoreCount() {
135
+ var self = this;
136
+ return this.restorePlan.filter(function (p) { return self.restorePick.indexOf(p.project) >= 0 && !self.restoreDisabled(p); }).length;
137
+ },
138
+ get restoreSummary() { return this.restoreCount + ' project file(s)'; },
139
+ get restoreLabel() { return 'Restore ' + this.restoreSummary; },
140
+ get nothingToRestore() { return this.restoreCount === 0; },
141
+ get cannotRestore() { return this.restoreConfirmText !== 'restore' || this.restoreBusy; },
142
+ restoreDisabled: function (p) { return p.status === 'invalid' || (p.status !== 'new' && !this.restoreReplace); },
143
+ restoreText: function (p) { return p.status === 'new' ? 'new' : this.restoreReplace && p.status !== 'invalid' ? 'replace' : TEXT[p.status]; },
144
+ restoreClass: function (p) { return p.status !== 'new' && p.status !== 'invalid' && this.restoreReplace ? 'bad' : CLASS[p.status]; },
145
+ restoreDetail: function (p) { return p.error || (p.status === 'known' ? p.knownAt : p.dest) || ''; },
146
+ restoreHosts: function (p) { return p.hostnames.join(', '); },
147
+ openBackup: function () { this.backupOpen = true; },
148
+ closeBackup: function () { this.backupOpen = false; },
149
+ pickBackupFile: function (e) {
150
+ var self = this;
151
+ var f = e.target.files && e.target.files[0];
152
+ this.backupError = ''; this.restorePlan = []; this.restorePick = [];
153
+ if (!f) return;
154
+ if (f.size > 1024 * 1024) { this.backupError = 'That file is larger than 1 MB.'; return; }
155
+ var reader = new FileReader();
156
+ reader.onload = function () { self.backupText = String(reader.result); self.previewRestore(); };
157
+ reader.onerror = function () { self.backupError = 'Could not read the file.'; };
158
+ reader.readAsText(f);
159
+ },
160
+ previewRestore: async function () {
161
+ try {
162
+ var r = await post('/api/backup/preview', { text: this.backupText });
163
+ if (r.status === 401) { location.assign('/login'); return; }
164
+ var j = await r.json().catch(function () { return {}; });
165
+ if (!r.ok) { this.backupError = j.error || ('HTTP ' + r.status); return; }
166
+ this.restorePlan = j.projects;
167
+ this.restorePick = j.projects.filter(function (p) { return p.status === 'new'; }).map(function (p) { return p.project; });
168
+ } catch (e) { this.backupError = 'Network error'; }
169
+ },
170
+ askRestore: function () { this.restoreConfirmText = ''; this.restoreConfirmOpen = true; },
171
+ closeRestoreConfirm: function () { this.restoreConfirmOpen = false; },
172
+ runRestore: async function () {
173
+ if (this.cannotRestore) return;
174
+ var self = this;
175
+ var picks = this.restorePlan.filter(function (p) { return self.restorePick.indexOf(p.project) >= 0 && !self.restoreDisabled(p); }).map(function (p) { return p.project; });
176
+ this.restoreBusy = true;
177
+ try {
178
+ var r = await post('/api/backup/restore', { text: this.backupText, projects: picks, replace: this.restoreReplace, confirm: 'restore' });
179
+ if (r.status === 401) { location.assign('/login'); return; }
180
+ var j = await r.json().catch(function () { return {}; });
181
+ if (r.ok) {
182
+ var lines = j.written.map(function (w) { return (w.replaced ? 'replaced ' : 'restored ') + w.project + ' -> ' + w.file; })
183
+ .concat(j.skipped.map(function (s) { return 'skipped ' + s.project + ': ' + s.reason; }));
184
+ this.showToast('✓ restore\\n' + lines.join('\\n'), true, 12000);
185
+ this.restoreConfirmOpen = false;
186
+ this.previewRestore();
187
+ this.load();
188
+ } else this.backupError = j.error || ('HTTP ' + r.status);
189
+ } catch (e) { this.backupError = 'Network error'; } finally { this.restoreBusy = false; }
190
+ },
191
+ };
192
+ });
193
+ `;