-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.ts
More file actions
653 lines (572 loc) · 27.3 KB
/
server.ts
File metadata and controls
653 lines (572 loc) · 27.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
import { Client, type ConnectConfig } from 'ssh2';
import { readdirSync, statSync, readFileSync, writeFileSync, unlinkSync, createWriteStream, mkdirSync } from 'fs';
import { join, dirname, basename } from 'path';
import { homedir, tmpdir } from 'os';
import { spawn } from 'child_process';
import { randomUUID } from 'crypto';
import { createServer as createNetServer } from 'net';
// ─── Types ─────────────────────────────────────────────────────────
interface FileEntry {
name: string;
type: 'directory' | 'file';
size: number;
modified: string;
}
interface ConnInfo {
host: string;
username: string;
port: number;
}
interface TransferState {
status: 'running' | 'cancelled';
process?: ReturnType<typeof spawn>;
}
interface SavedConnection {
id: string;
name: string;
host: string;
port: number;
username: string;
authMode: 'password' | 'key' | 'default';
privateKeyPath?: string;
}
interface Snippet {
id: string;
label: string;
command: string;
}
interface PortForward {
id: string;
localPort: number;
remoteHost: string;
remotePort: number;
server: ReturnType<typeof createNetServer>;
connCount: number;
}
// ─── Module state ──────────────────────────────────────────────────
let sshClient: Client | null = null;
let connInfo: ConnInfo | null = null;
const transferMap = new Map<string, TransferState>();
const forwardMap = new Map<string, PortForward>();
const wsSet = new Set<import('bun').ServerWebSocket<unknown>>();
const CONNECTIONS_FILE = join(homedir(), '.serverbrdg.json');
// ─── Exported utilities ─────────────────────────────────────────────
export function formatBytes(bytes: number): string {
if (!bytes) return '—';
const units = ['B', 'KB', 'MB', 'GB', 'TB'];
const i = Math.floor(Math.log(bytes) / Math.log(1024));
return `${(bytes / 1024 ** i).toFixed(1)} ${units[i]}`;
}
export function parseRsyncProgress(line: string): { percent: number; speed: string; eta: string } | null {
const m = line.match(/[\d,]+\s+(\d+)%\s+([\d.]+[kMGT]?B\/s)\s+([\d:]+)/);
if (!m) return null;
return { percent: parseInt(m[1]), speed: m[2], eta: m[3] };
}
// ─── Saved connections & snippets ──────────────────────────────────
function loadDataFile(): { connections: SavedConnection[]; snippets: Snippet[] } {
try {
const d = JSON.parse(readFileSync(CONNECTIONS_FILE, 'utf8'));
return { connections: d.connections ?? [], snippets: d.snippets ?? [] };
} catch { return { connections: [], snippets: [] }; }
}
function loadConnections(): SavedConnection[] { return loadDataFile().connections; }
function loadSnippets(): Snippet[] { return loadDataFile().snippets; }
function saveConnections(conns: SavedConnection[]) {
const d = loadDataFile();
writeFileSync(CONNECTIONS_FILE, JSON.stringify({ ...d, connections: conns }, null, 2));
}
function saveSnippets(snippets: Snippet[]) {
const d = loadDataFile();
writeFileSync(CONNECTIONS_FILE, JSON.stringify({ ...d, snippets }, null, 2));
}
// ─── Internal helpers ──────────────────────────────────────────────
function jsonResp(data: object, status = 200): Response {
return new Response(JSON.stringify(data), {
status,
headers: { 'Content-Type': 'application/json' }
});
}
function broadcast(data: object) {
const msg = JSON.stringify(data);
for (const ws of wsSet) ws.send(msg);
}
// ─── Request router ────────────────────────────────────────────────
async function handleRequest(req: Request, server: import('bun').Server): Promise<Response> {
const url = new URL(req.url);
const { method } = req;
const p = url.pathname;
if (p === '/ws') {
return server.upgrade(req, { data: { type: 'progress' } }) ? (undefined as any) : new Response('Upgrade failed', { status: 400 });
}
if (p === '/ws/terminal') {
if (!sshClient) return new Response('Not connected', { status: 400 });
return server.upgrade(req, { data: { type: 'terminal', channel: null as any } }) ? (undefined as any) : new Response('Upgrade failed', { status: 400 });
}
if (p === '/' || p === '/index.html') {
return new Response(Bun.file('public/index.html'), { headers: { 'Content-Type': 'text/html' } });
}
if (p === '/api/status' && method === 'GET') return handleStatus();
if (p === '/api/connect' && method === 'POST') return handleConnect(req);
if (p === '/api/disconnect' && method === 'POST') return handleDisconnect();
if (p === '/api/browse/remote' && method === 'GET') return handleBrowseRemote(url);
if (p === '/api/browse/local' && method === 'GET') return handleBrowseLocal(url);
if (p === '/api/transfer' && method === 'POST') return handleTransfer(req);
if (p === '/api/upload' && method === 'POST') return handleUpload(req);
if (p === '/api/connections' && method === 'GET') return handleGetConnections();
if (p === '/api/connections' && method === 'POST') return handleSaveConnection(req);
if (p === '/api/snippets' && method === 'GET') return handleGetSnippets();
if (p === '/api/snippets' && method === 'POST') return handleSaveSnippet(req);
if (p === '/api/forwards' && method === 'GET') return handleListForwards();
if (p === '/api/forwards' && method === 'POST') return handleCreateForward(req);
const cancelMatch = p.match(/^\/api\/transfer\/([^/]+)\/cancel$/);
if (cancelMatch && method === 'POST') return handleCancel(cancelMatch[1]);
const delConnMatch = p.match(/^\/api\/connections\/([^/]+)$/);
if (delConnMatch && method === 'DELETE') return handleDeleteConnection(delConnMatch[1]);
const delSnipMatch = p.match(/^\/api\/snippets\/([^/]+)$/);
if (delSnipMatch && method === 'DELETE') return handleDeleteSnippet(delSnipMatch[1]);
const delFwdMatch = p.match(/^\/api\/forwards\/([^/]+)$/);
if (delFwdMatch && method === 'DELETE') return handleDeleteForward(delFwdMatch[1]);
return new Response('Not found', { status: 404 });
}
// ─── Saved connections handlers ────────────────────────────────────
function handleGetConnections(): Response {
return jsonResp({ connections: loadConnections() });
}
async function handleSaveConnection(req: Request): Promise<Response> {
const body = await req.json() as Omit<SavedConnection, 'id'>;
const conns = loadConnections();
const idx = conns.findIndex(c => c.host === body.host && c.username === body.username && c.port === body.port);
const conn: SavedConnection = { ...body, id: idx >= 0 ? conns[idx].id : randomUUID() };
if (idx >= 0) conns[idx] = conn;
else conns.push(conn);
saveConnections(conns);
return jsonResp({ connection: conn });
}
function handleDeleteConnection(id: string): Response {
saveConnections(loadConnections().filter(c => c.id !== id));
return jsonResp({ success: true });
}
// ─── SSH connection handlers ───────────────────────────────────────
function handleStatus(): Response {
if (!connInfo) return jsonResp({ connected: false });
return jsonResp({ connected: true, ...connInfo });
}
async function handleConnect(req: Request): Promise<Response> {
const body = await req.json() as {
host: string; port?: number; username: string;
password?: string; privateKeyPath?: string;
authMode: 'password' | 'key' | 'default';
};
if (sshClient) { sshClient.end(); sshClient = null; connInfo = null; }
return new Promise(resolve => {
const conn = new Client();
const config: ConnectConfig = {
host: body.host,
port: body.port ?? 22,
username: body.username,
readyTimeout: 10000
};
if (body.authMode === 'password') {
if (!body.password) return resolve(jsonResp({ error: 'Password required' }, 400));
config.password = body.password;
} else if (body.authMode === 'key') {
const keyPath = body.privateKeyPath ?? join(homedir(), '.ssh', 'id_rsa');
try { config.privateKey = readFileSync(keyPath); }
catch { return resolve(jsonResp({ error: `Cannot read key: ${keyPath}` }, 400)); }
} else {
const candidates = ['.ssh/id_rsa', '.ssh/id_ed25519', '.ssh/id_ecdsa'].map(p => join(homedir(), p));
for (const p of candidates) { try { config.privateKey = readFileSync(p); break; } catch {} }
if (!config.privateKey) {
return resolve(jsonResp({ error: 'No default SSH key found. Try Password or Key Path auth.' }, 400));
}
}
conn.on('ready', () => {
sshClient = conn;
connInfo = { host: body.host, username: body.username, port: body.port ?? 22 };
broadcast({ type: 'connected', host: body.host, username: body.username });
resolve(jsonResp({ success: true }));
});
conn.on('error', err => resolve(jsonResp({ error: err.message }, 500)));
conn.connect(config);
});
}
function handleDisconnect(): Response {
for (const [id, fwd] of forwardMap) { try { fwd.server.close(); } catch {} forwardMap.delete(id); }
if (sshClient) { sshClient.end(); sshClient = null; connInfo = null; }
broadcast({ type: 'disconnected' });
return jsonResp({ success: true });
}
// ─── Terminal shell ────────────────────────────────────────────────
// Opens an interactive PTY via ssh2 shell() and wires it to a WebSocket.
function openTerminalShell(ws: import('bun').ServerWebSocket<any>) {
if (!sshClient) { ws.close(1011, 'Not connected'); return; }
sshClient.shell({ term: 'xterm-256color', cols: 220, rows: 50 }, (err, channel) => {
if (err) { ws.close(1011, err.message); return; }
ws.data.channel = channel;
channel.on('data', (data: Buffer) => { try { ws.send(data); } catch {} });
channel.stderr.on('data', (data: Buffer) => { try { ws.send(data); } catch {} });
channel.on('close', () => { try { ws.close(); } catch {} });
});
}
// ─── Snippet handlers ──────────────────────────────────────────────
function handleGetSnippets(): Response {
return jsonResp({ snippets: loadSnippets() });
}
async function handleSaveSnippet(req: Request): Promise<Response> {
const body = await req.json() as { label: string; command: string };
const snippet: Snippet = { id: randomUUID(), label: body.label.trim(), command: body.command };
saveSnippets([...loadSnippets(), snippet]);
return jsonResp({ snippet });
}
function handleDeleteSnippet(id: string): Response {
saveSnippets(loadSnippets().filter(s => s.id !== id));
return jsonResp({ success: true });
}
// ─── Upload handler ────────────────────────────────────────────────
async function handleUpload(req: Request): Promise<Response> {
if (!sshClient) return jsonResp({ error: 'Not connected' }, 400);
const form = await req.formData();
const file = form.get('file') as File;
const remotePath = ((form.get('remotePath') as string) || '/tmp').replace(/\/$/, '') + '/' + file.name;
const buf = Buffer.from(await file.arrayBuffer());
return new Promise(resolve => {
sshClient!.sftp((err, sftp) => {
if (err) return resolve(jsonResp({ error: err.message }, 500));
const ws = sftp.createWriteStream(remotePath);
ws.on('close', () => { sftp.end(); resolve(jsonResp({ success: true, remotePath })); });
ws.on('error', (e: Error) => { sftp.end(); resolve(jsonResp({ error: e.message }, 500)); });
ws.end(buf);
});
});
}
// ─── Port forward handlers ─────────────────────────────────────────
async function handleCreateForward(req: Request): Promise<Response> {
if (!sshClient) return jsonResp({ error: 'Not connected' }, 400);
const { localPort, remoteHost, remotePort } = await req.json() as {
localPort: number; remoteHost: string; remotePort: number;
};
return new Promise(resolve => {
const id = randomUUID();
const netServer = createNetServer(sock => {
const fwd = forwardMap.get(id);
if (fwd) fwd.connCount++;
sshClient!.forwardOut('127.0.0.1', localPort, remoteHost, remotePort, (err, stream) => {
if (err) { sock.destroy(); return; }
sock.pipe(stream as any); (stream as any).pipe(sock);
sock.on('close', () => { try { (stream as any).destroy(); } catch {} });
(stream as any).on('close', () => { try { sock.destroy(); } catch {} });
});
});
netServer.on('error', (err: Error) => resolve(jsonResp({ error: err.message }, 500)));
netServer.listen(localPort, '127.0.0.1', () => {
forwardMap.set(id, { id, localPort, remoteHost, remotePort, server: netServer, connCount: 0 });
resolve(jsonResp({ success: true, forward: { id, localPort, remoteHost, remotePort, connCount: 0 } }));
});
});
}
function handleDeleteForward(id: string): Response {
const fwd = forwardMap.get(id);
if (fwd) { try { fwd.server.close(); } catch {} forwardMap.delete(id); }
return jsonResp({ success: true });
}
function handleListForwards(): Response {
const forwards = [...forwardMap.values()].map(({ id, localPort, remoteHost, remotePort, connCount }) =>
({ id, localPort, remoteHost, remotePort, connCount }));
return jsonResp({ forwards });
}
// ─── File browser handlers ─────────────────────────────────────────
function handleBrowseRemote(url: URL): Promise<Response> {
if (!sshClient) return Promise.resolve(jsonResp({ error: 'Not connected to server' }, 400));
const remotePath = url.searchParams.get('path') || '/';
return new Promise(resolve => {
sshClient!.sftp((err, sftp) => {
if (err) return resolve(jsonResp({ error: err.message }, 500));
sftp.readdir(remotePath, (err, list) => {
sftp.end();
if (err) return resolve(jsonResp({ error: err.message }, 500));
const files: FileEntry[] = list
.filter(item => !item.filename.startsWith('.'))
.map(item => ({
name: item.filename,
type: item.longname.startsWith('d') ? 'directory' : 'file',
size: item.attrs.size ?? 0,
modified: new Date((item.attrs.mtime ?? 0) * 1000).toISOString()
}))
.sort((a, b) => {
if (a.type !== b.type) return a.type === 'directory' ? -1 : 1;
return a.name.localeCompare(b.name);
});
resolve(jsonResp({ path: remotePath, parent: dirname(remotePath), files }));
});
});
});
}
function handleBrowseLocal(url: URL): Response {
const localPath = url.searchParams.get('path') || join(homedir(), 'Desktop');
try {
const entries = readdirSync(localPath, { withFileTypes: true });
const files: FileEntry[] = entries
.filter(e => !e.name.startsWith('.'))
.map(e => {
const full = join(localPath, e.name);
let size = 0, modified = new Date().toISOString();
try { const s = statSync(full); size = s.size; modified = s.mtime.toISOString(); } catch {}
return { name: e.name, type: e.isDirectory() ? 'directory' : 'file', size, modified };
})
.sort((a, b) => {
if (a.type !== b.type) return a.type === 'directory' ? -1 : 1;
return a.name.localeCompare(b.name);
});
return jsonResp({ path: localPath, parent: dirname(localPath), files });
} catch (err: any) {
return jsonResp({ error: err.message }, 500);
}
}
// ─── SSH remote execution helper ──────────────────────────────────
// sshClient.exec() runs commands on the remote server via SSH2 — not locally.
// Paths originate from SFTP directory listings, not from user text input.
function sshRemoteExec(cmd: string): Promise<string> {
return new Promise((resolve, reject) => {
if (!sshClient) return reject(new Error('Not connected'));
sshClient.exec(cmd, (err, stream) => {
if (err) return reject(err);
let out = '';
stream.on('data', (d: Buffer) => out += d.toString());
stream.stderr.on('data', (d: Buffer) => console.error('[remote]', d.toString()));
stream.on('close', (code: number) => {
code === 0 ? resolve(out) : reject(new Error(`Remote command exited ${code}`));
});
});
});
}
function checkRemoteIsDir(remotePath: string): Promise<boolean> {
return sshRemoteExec(`test -d "${remotePath}" && echo yes || echo no`)
.then(out => out.trim() === 'yes')
.catch(() => false);
}
// ─── Transfer functions ────────────────────────────────────────────
// Bun.spawn with array args — no shell interpolation, safe
function rsyncTransfer(transferId: string, src: string, destDir: string): Promise<void> {
return new Promise((resolve, reject) => {
const args = ['-avz', '--progress', '-e', 'ssh -o StrictHostKeyChecking=no -o BatchMode=yes', src, destDir + '/'];
const proc = spawn('rsync', args);
transferMap.set(transferId, { status: 'running', process: proc });
let buffer = '';
proc.stdout.on('data', (chunk: Buffer) => {
buffer += chunk.toString();
const parts = buffer.split('\r'); buffer = parts.pop()!;
for (const line of parts) {
const p = parseRsyncProgress(line);
if (p) broadcast({ type: 'progress', transferId, ...p, status: 'Downloading' });
}
});
proc.stderr.on('data', (d: Buffer) => console.error('[rsync]', d.toString()));
proc.on('close', code => {
const state = transferMap.get(transferId); transferMap.delete(transferId);
if (state?.status === 'cancelled') return resolve();
if (code === 0 || code === 23) resolve();
else reject(new Error(`rsync exited with code ${code}`));
});
proc.on('error', (err: NodeJS.ErrnoException) => {
if (err.code === 'ENOENT') reject(Object.assign(new Error('rsync not found — install it with your package manager'), { isRsyncMissing: true }));
else reject(err);
});
});
}
// SFTP single-file download — used when rsync is unavailable
function sftpDownloadFile(transferId: string, remotePath: string, localFilePath: string): Promise<void> {
return new Promise((resolve, reject) => {
if (!sshClient) return reject(new Error('Not connected'));
sshClient.sftp((err, sftp) => {
if (err) return reject(err);
sftp.stat(remotePath, (statErr, stats) => {
if (statErr) { sftp.end(); return reject(statErr); }
const total = stats.size;
let transferred = 0;
const reader = sftp.createReadStream(remotePath);
const writer = createWriteStream(localFilePath);
reader.on('data', (chunk: Buffer) => {
transferred += chunk.length;
const percent = total ? Math.floor(transferred / total * 100) : 0;
broadcast({ type: 'progress', transferId, percent, speed: '—', eta: '—', status: 'Downloading' });
});
reader.pipe(writer);
writer.on('finish', () => { sftp.end(); resolve(); });
reader.on('error', (e: Error) => { sftp.end(); writer.destroy(); reject(e); });
writer.on('error', (e: Error) => { sftp.end(); reject(e); });
});
});
});
}
// SFTP recursive directory download — used when rsync is unavailable
async function sftpDownloadDir(transferId: string, remotePath: string, localDest: string): Promise<void> {
if (!sshClient) throw new Error('Not connected');
const list = await new Promise<FileEntry[]>((resolve, reject) => {
sshClient!.sftp((err, sftp) => {
if (err) return reject(err);
sftp.readdir(remotePath, (err, items) => {
sftp.end();
if (err) return reject(err);
resolve(items
.filter(i => i.filename !== '.' && i.filename !== '..')
.map(i => ({
name: i.filename,
type: i.longname.startsWith('d') ? 'directory' : 'file',
size: i.attrs.size ?? 0,
modified: new Date((i.attrs.mtime ?? 0) * 1000).toISOString()
})));
});
});
});
const localDir = join(localDest, basename(remotePath));
mkdirSync(localDir, { recursive: true });
for (const f of list) {
const remoteChild = remotePath.replace(/\/$/, '') + '/' + f.name;
if (f.type === 'directory') await sftpDownloadDir(transferId, remoteChild, localDir);
else await sftpDownloadFile(transferId, remoteChild, join(localDir, f.name));
}
}
async function compressAndTransfer(transferId: string, remotePath: string, localDest: string): Promise<void> {
const { host, username } = connInfo!;
const uid = randomUUID().slice(0, 8);
const archiveName = `sbrdg_${uid}.tar.gz`;
const remoteTmp = `/tmp/${archiveName}`;
const localTmp = join(tmpdir(), archiveName);
broadcast({ type: 'progress', transferId, percent: 0, speed: '—', eta: '—', status: 'Compressing on server...' });
await sshRemoteExec(`tar -czf "${remoteTmp}" -C "${dirname(remotePath)}" "${basename(remotePath)}"`);
let sizeLabel = '';
try {
const out = await sshRemoteExec(`stat -c%s "${remoteTmp}" 2>/dev/null || wc -c < "${remoteTmp}"`);
const bytes = parseInt(out.trim());
if (!isNaN(bytes)) sizeLabel = ` (${formatBytes(bytes)})`;
} catch {}
broadcast({ type: 'progress', transferId, percent: 5, speed: '—', eta: '—', status: `Downloading archive${sizeLabel}...` });
// Transfer archive — try rsync, fall back to SFTP if not installed
let rsyncFailed = false;
try {
await new Promise<void>((resolve, reject) => {
const args = ['-az', '--progress', '-e', 'ssh -o StrictHostKeyChecking=no', `${username}@${host}:${remoteTmp}`, localTmp];
const proc = spawn('rsync', args);
transferMap.set(transferId, { status: 'running', process: proc });
let buffer = '';
proc.stdout.on('data', (chunk: Buffer) => {
buffer += chunk.toString();
const parts = buffer.split('\r'); buffer = parts.pop()!;
for (const line of parts) {
const p = parseRsyncProgress(line);
if (p) {
const pct = 5 + Math.floor(p.percent * 0.85);
broadcast({ type: 'progress', transferId, percent: pct, speed: p.speed, eta: p.eta, status: 'Downloading...' });
}
}
});
proc.on('close', code => {
const state = transferMap.get(transferId); transferMap.delete(transferId);
if (state?.status === 'cancelled') return resolve();
code === 0 ? resolve() : reject(new Error(`Archive transfer failed (code ${code})`));
});
proc.on('error', (err: NodeJS.ErrnoException) => {
if (err.code === 'ENOENT') reject(Object.assign(err, { isRsyncMissing: true }));
else reject(err);
});
});
} catch (err: any) {
if (!err.isRsyncMissing) throw err;
rsyncFailed = true;
broadcast({ type: 'progress', transferId, percent: 5, speed: '—', eta: '—', status: 'Downloading via SFTP...' });
await sftpDownloadFile(transferId, remoteTmp, localTmp);
}
broadcast({ type: 'progress', transferId, percent: 92, speed: '—', eta: '—', status: 'Extracting...' });
const result = Bun.spawnSync(['tar', '-xzf', localTmp, '-C', localDest]);
if (result.exitCode !== 0) throw new Error(`Extraction failed: ${new TextDecoder().decode(result.stderr)}`);
broadcast({ type: 'progress', transferId, percent: 98, speed: '—', eta: '—', status: 'Cleaning up...' });
try { unlinkSync(localTmp); } catch {}
sshRemoteExec(`rm -f "${remoteTmp}"`).catch(() => {});
}
// ─── Transfer handlers ─────────────────────────────────────────────
async function handleTransfer(req: Request): Promise<Response> {
if (!sshClient || !connInfo) return jsonResp({ error: 'Not connected' }, 400);
const { remotePath, compress = true, localDest } = await req.json() as {
remotePath: string;
compress: boolean;
localDest: string;
};
const dest = localDest || join(homedir(), 'Desktop');
const transferId = randomUUID();
broadcast({ type: 'transfer_start', transferId, name: basename(remotePath), remotePath, localPath: dest });
(async () => {
try {
const isDir = await checkRemoteIsDir(remotePath);
if (compress && isDir) {
await compressAndTransfer(transferId, remotePath, dest);
} else {
const src = `${connInfo!.username}@${connInfo!.host}:${remotePath}`;
try {
await rsyncTransfer(transferId, src, dest);
} catch (err: any) {
if (err.isRsyncMissing) {
broadcast({ type: 'progress', transferId, percent: 0, speed: '—', eta: '—', status: 'Downloading via SFTP...' });
if (isDir) await sftpDownloadDir(transferId, remotePath, dest);
else await sftpDownloadFile(transferId, remotePath, join(dest, basename(remotePath)));
} else throw err;
}
}
broadcast({ type: 'transfer_complete', transferId });
} catch (err: any) {
broadcast({ type: 'transfer_error', transferId, error: err.message });
}
})();
return jsonResp({ success: true, transferId });
}
function handleCancel(transferId: string): Response {
const t = transferMap.get(transferId);
if (t?.process) {
t.process.kill('SIGTERM');
transferMap.set(transferId, { status: 'cancelled' });
broadcast({ type: 'transfer_cancelled', transferId });
}
return jsonResp({ success: true });
}
// ─── Server start ──────────────────────────────────────────────────
const PORT = 3847;
Bun.serve({
port: PORT,
fetch: handleRequest,
websocket: {
open(ws) {
const d = ws.data as any;
if (d?.type === 'terminal') {
openTerminalShell(ws);
} else {
wsSet.add(ws);
if (connInfo) ws.send(JSON.stringify({ type: 'connected', ...connInfo }));
}
},
close(ws) {
const d = ws.data as any;
if (d?.type === 'terminal') {
try { d.channel?.destroy(); } catch {}
} else {
wsSet.delete(ws);
}
},
message(ws, msg) {
const d = ws.data as any;
if (d?.type === 'terminal' && d.channel) {
if (typeof msg === 'string') {
try {
const parsed = JSON.parse(msg);
if (parsed.type === 'resize') { d.channel.setWindow(parsed.rows, parsed.cols, 0, 0); return; }
} catch {}
d.channel.stdin.write(msg);
} else {
d.channel.stdin.write(Buffer.from(msg as ArrayBuffer));
}
}
}
}
});
console.log(`\n ┌──────────────────────────────┐`);
console.log(` │ SERVERBRDG │`);
console.log(` │ http://localhost:${PORT} │`);
console.log(` └──────────────────────────────┘\n`);