-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserver.js
More file actions
649 lines (564 loc) · 22.5 KB
/
server.js
File metadata and controls
649 lines (564 loc) · 22.5 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
const crypto = require('crypto');
const express = require('express');
const http = require('http');
const { WebSocketServer } = require('ws');
const pty = require('node-pty');
const path = require('path');
const fs = require('fs');
const { execFileSync, spawn } = require('child_process');
const auth = require('./auth');
const projects = require('./projects');
const { findAuthUrl } = require('./auth-url-scanner');
// --- CLI flags ---
const args = process.argv.slice(2);
const NO_AUTH = args.includes('--no-auth');
const portFlagIndex = args.indexOf('--port');
const PORT = (portFlagIndex !== -1 && args[portFlagIndex + 1])
? parseInt(args[portFlagIndex + 1], 10)
: (parseInt(process.env.PORT, 10) || 3000);
if (!Number.isInteger(PORT) || PORT < 1 || PORT > 65535) {
console.error(`[server] invalid port: ${PORT} (must be 1-65535)`);
process.exit(1);
}
const REMOTE = args.includes('--remote');
if (NO_AUTH && REMOTE) {
console.error('[server] --no-auth and --remote cannot be used together (would expose unauthenticated terminal to the internet)');
process.exit(1);
}
const BIND_HOST = (NO_AUTH && !REMOTE) ? '127.0.0.1' : '0.0.0.0';
const SETUP_TOKEN = crypto.randomBytes(16).toString('hex');
const REPLAY_BUFFER_SIZE = 100 * 1024; // 100KB
const MAX_SESSIONS = 50;
// --- Mode definitions ---
const MODES = {
claude: { cmd: 'claude', label: 'Claude Code' },
copilot: { cmd: 'copilot', label: 'GitHub Copilot' },
terminal: { cmd: null, label: 'Terminal' }, // null = plain bash -l
};
const VALID_MODES = new Set(Object.keys(MODES));
// --- Detect which CLIs are installed (cached at startup) ---
const modeAvailability = {};
for (const [mode, config] of Object.entries(MODES)) {
if (!config.cmd) {
// terminal mode — always available
modeAvailability[mode] = true;
} else {
try {
execFileSync('which', [config.cmd], { timeout: 3000, stdio: 'ignore' });
modeAvailability[mode] = true;
} catch {
modeAvailability[mode] = false;
console.log(`[server] ${config.label} (${config.cmd}) not found — mode disabled`);
}
}
}
const app = express();
const server = http.createServer(app);
// Trust proxy so req.protocol detects HTTPS behind tunnels
app.set('trust proxy', 1);
// --- Body parsing ---
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
// --- Security headers ---
app.use((req, res, next) => {
res.setHeader('Content-Security-Policy',
"default-src 'self'; " +
"script-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; " +
"style-src 'self' 'unsafe-inline' https://cdn.jsdelivr.net; " +
"connect-src 'self' ws: wss:; " +
"img-src 'self' data:;"
);
res.setHeader('X-Content-Type-Options', 'nosniff');
res.setHeader('X-Frame-Options', 'DENY');
next();
});
// --- PtySession class ---
const BROWSER_BRIDGE_PATH = path.join(__dirname, 'browser-bridge.sh');
class PtySession {
constructor(mode, sessionKey, cwd) {
this.mode = mode;
this.sessionKey = sessionKey;
this.cwd = cwd || process.env.HOME || process.cwd();
this.ptyProcess = null;
this.replayBuffer = '';
this.clients = new Set();
this.authPipePath = null;
this.authPipeWatcher = null;
this.authPipeSize = 0;
this.seenAuthUrls = new Set(); // dedup across $BROWSER and PTY scan
}
spawn(cols = 120, rows = 30) {
if (this.ptyProcess) {
try { this.ptyProcess.kill(); } catch (e) { console.warn(`[pty:${this.sessionKey}] kill error on respawn:`, e.message); }
}
this.replayBuffer = '';
// Validate cwd exists — fall back to HOME if it doesn't
const home = process.env.HOME || process.cwd();
if (!fs.existsSync(this.cwd)) {
console.warn(`[pty:${this.sessionKey}] cwd does not exist (${this.cwd}), falling back to ${home}`);
this.cwd = home;
}
const shell = process.env.SHELL || '/bin/bash';
const env = { ...process.env, TERM: 'xterm-256color' };
// Remove nested-session guard so claude can launch from within this server
delete env.CLAUDECODE;
delete env.CLAUDE_CODE;
// $BROWSER interception for auth URL capture
this.cleanupAuthPipe();
this.authPipePath = `/tmp/.pocketshell-auth-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
env.BROWSER = BROWSER_BRIDGE_PATH;
env.POCKETSHELL_AUTH_PIPE = this.authPipePath;
this.seenAuthUrls.clear();
this.authPipeSize = 0;
const modeConfig = MODES[this.mode];
// For commands (claude, copilot): spawn the binary directly to avoid
// any bash profile/rc noise. For terminal: use login shell.
const spawnCmd = modeConfig.cmd || shell;
const spawnArgs = modeConfig.cmd ? [] : ['-l'];
this.ptyProcess = pty.spawn(spawnCmd, spawnArgs, {
name: 'xterm-256color',
cols,
rows,
cwd: this.cwd,
env,
});
// Watch auth pipe file for $BROWSER-intercepted URLs
this.watchAuthPipe();
console.log(`[pty:${this.sessionKey}] spawned (pid ${this.ptyProcess.pid}), cols=${cols} rows=${rows}, cwd=${this.cwd}`);
this.ptyProcess.onData((data) => {
this.replayBuffer += data;
if (this.replayBuffer.length > REPLAY_BUFFER_SIZE) {
this.replayBuffer = this.replayBuffer.slice(-REPLAY_BUFFER_SIZE);
}
const msg = JSON.stringify({ type: 'output', data });
for (const ws of this.clients) {
if (ws.readyState === 1) { // WebSocket.OPEN
ws.send(msg);
}
}
// PTY output scanning for auth URLs (fallback)
const authMatch = findAuthUrl(data);
if (authMatch && !this.seenAuthUrls.has(authMatch.url)) {
this.seenAuthUrls.add(authMatch.url);
this.broadcastAuthUrl(authMatch.url, authMatch.provider);
}
});
this.ptyProcess.onExit(({ exitCode, signal }) => {
console.log(`[pty:${this.sessionKey}] exited (code=${exitCode}, signal=${signal})`);
const msg = JSON.stringify({ type: 'exit', exitCode, signal });
for (const ws of this.clients) {
if (ws.readyState === 1) {
ws.send(msg);
}
}
this.ptyProcess = null;
this.cleanupAuthPipe();
});
}
/** Watch the auth pipe file for URLs written by browser-bridge.sh */
watchAuthPipe() {
if (!this.authPipePath) return;
try {
// Ensure file exists for watchFile
fs.writeFileSync(this.authPipePath, '', { flag: 'a' });
this.authPipeWatcher = fs.watchFile(this.authPipePath, { interval: 500 }, (curr) => {
if (curr.size <= this.authPipeSize) return;
try {
const content = fs.readFileSync(this.authPipePath, 'utf8');
const lines = content.split('\n').filter(l => l.trim());
// Process only new lines
const newLines = lines.slice(this.authPipeSize === 0 ? 0 : undefined);
this.authPipeSize = curr.size;
for (const url of newLines) {
const trimmed = url.trim();
if (trimmed && !this.seenAuthUrls.has(trimmed)) {
this.seenAuthUrls.add(trimmed);
const provider = guessProviderFromUrl(trimmed);
this.broadcastAuthUrl(trimmed, provider);
}
}
} catch (e) {
// File may have been deleted
}
});
} catch (e) {
console.warn(`[pty:${this.sessionKey}] auth pipe setup error:`, e.message);
}
}
/** Clean up auth pipe file and watcher */
cleanupAuthPipe() {
if (this.authPipeWatcher) {
try { fs.unwatchFile(this.authPipePath); } catch (e) { /* ignore */ }
this.authPipeWatcher = null;
}
if (this.authPipePath) {
try { fs.unlinkSync(this.authPipePath); } catch (e) { /* ignore */ }
this.authPipePath = null;
}
}
/** Broadcast auth URL to all connected clients */
broadcastAuthUrl(url, provider) {
console.log(`[pty:${this.sessionKey}] auth URL detected: ${url} (${provider})`);
const msg = JSON.stringify({ type: 'auth-url', url, provider });
for (const ws of this.clients) {
if (ws.readyState === 1) {
ws.send(msg);
}
}
}
kill() {
if (this.ptyProcess) {
try { this.ptyProcess.kill(); } catch (e) { console.warn(`[pty:${this.sessionKey}] kill error:`, e.message); }
this.ptyProcess = null;
}
this.cleanupAuthPipe();
}
}
/** Guess auth provider from a URL (for $BROWSER interception path) */
function guessProviderFromUrl(url) {
const lower = url.toLowerCase();
if (lower.includes('github.com')) return 'GitHub';
if (lower.includes('microsoftonline.com') || lower.includes('microsoft.com') || lower.includes('login.live.com')) return 'Microsoft';
if (lower.includes('anthropic.com')) return 'Anthropic';
if (lower.includes('google.com')) return 'Google';
return 'Auth';
}
// --- Sessions Map ---
// Key format: "projectId:mode" (e.g. "home:claude", "L2hvbWUv...:terminal")
const sessions = new Map();
function resolveProjectCwd(projectId, cwd) {
const home = process.env.HOME || process.cwd();
if (cwd) return cwd;
if (projectId === 'home') return home;
try {
const decoded = projects.projectIdToPath(projectId);
return fs.existsSync(decoded) ? decoded : home;
} catch (e) {
return home;
}
}
function getOrCreateSession(mode, projectId = 'home', cwd = null) {
const sessionKey = `${projectId}:${mode}`;
let session = sessions.get(sessionKey);
if (!session) {
if (sessions.size >= MAX_SESSIONS) {
console.warn(`[server] session limit reached (${MAX_SESSIONS}), reusing home:${mode}`);
return getOrCreateSession(mode, 'home');
}
const sessionCwd = resolveProjectCwd(projectId, cwd);
session = new PtySession(mode, sessionKey, sessionCwd);
sessions.set(sessionKey, session);
session.spawn();
} else if (!session.ptyProcess) {
// PTY exited; respawn
session.spawn();
}
return session;
}
// Eagerly spawn PTYs for the last-used project (or home) at startup
// Only spawn modes whose CLI is actually installed
const lastProject = projects.getLastProject();
for (const mode of Object.keys(MODES)) {
if (modeAvailability[mode]) {
getOrCreateSession(mode, lastProject);
}
}
// --- Redirect old direct-access URLs to landing page ---
app.get('/desktop.html', (req, res) => res.redirect('/'));
app.get('/mobile.html', (req, res) => res.redirect('/'));
// --- Auth setup ---
if (NO_AUTH) {
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Debug: serve test fixtures for reader-test.html (only in --no-auth mode)
app.use('/tests/fixtures', express.static(path.join(__dirname, 'tests', 'fixtures')));
// Debug: replay buffer capture (only in --no-auth mode)
app.get('/api/debug/replay', (req, res) => {
const mode = req.query.mode || 'claude';
const project = req.query.project || 'home';
const sessionKey = `${project}:${mode}`;
const session = sessions.get(sessionKey);
if (!session) {
return res.status(404).json({ error: 'Session not found' });
}
res.type('text').send(session.replayBuffer);
});
// Project API routes (before static middleware)
setupProjectRoutes(app);
app.use(express.static(path.join(__dirname, 'public')));
} else {
// Auth API routes (public, no auth required)
auth.setupRoutes(app, SETUP_TOKEN);
// Serve login page without auth — must come before authMiddleware
app.get('/login.html', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'login.html'));
});
// Auth middleware (everything below requires login)
app.use(auth.authMiddleware);
app.get('/', (req, res) => {
res.sendFile(path.join(__dirname, 'public', 'index.html'));
});
// Project API routes (after auth middleware)
setupProjectRoutes(app);
// Static files (protected)
app.use(express.static(path.join(__dirname, 'public')));
}
// --- Project API routes ---
function setupProjectRoutes(app) {
// Which modes are available
app.get('/api/modes', (req, res) => {
res.json(modeAvailability);
});
// Bootstrap data: last project, recents, repos
app.get('/api/projects', (req, res) => {
res.json(projects.getBootstrapData());
});
// Discover repos on the filesystem
app.get('/api/projects/discover', async (req, res) => {
try {
const repos = await projects.discoverRepos();
res.json({ repos });
} catch (e) {
console.error('[api] discover error:', e.message);
res.status(500).json({ error: 'Failed to scan for repos' });
}
});
// Register a repo
app.post('/api/projects/repos', (req, res) => {
try {
const { repoPath } = req.body;
if (!repoPath || typeof repoPath !== 'string') {
return res.status(400).json({ error: 'repoPath is required' });
}
const resolved = projects.registerRepo(repoPath);
res.json({ ok: true, repoPath: resolved });
} catch (e) {
res.status(400).json({ error: e.message });
}
});
// Unregister a repo
app.delete('/api/projects/repos', (req, res) => {
const { repoPath } = req.body;
if (!repoPath || typeof repoPath !== 'string') {
return res.status(400).json({ error: 'repoPath is required' });
}
projects.removeRepo(repoPath);
res.json({ ok: true });
});
// List branches for a repo (must be a registered repo)
app.get('/api/projects/branches', async (req, res) => {
try {
const repo = req.query.repo;
if (!repo) return res.status(400).json({ error: 'repo query param required' });
if (!projects.isRegisteredRepo(repo)) {
return res.status(403).json({ error: 'Repository not registered' });
}
const branches = await projects.listBranches(repo);
res.json({ branches });
} catch (e) {
console.error('[api] branches error:', e.message);
res.status(400).json({ error: 'Failed to list branches' });
}
});
// List worktrees for a repo (must be a registered repo)
app.get('/api/projects/worktrees', async (req, res) => {
try {
const repo = req.query.repo;
if (!repo) return res.status(400).json({ error: 'repo query param required' });
if (!projects.isRegisteredRepo(repo)) {
return res.status(403).json({ error: 'Repository not registered' });
}
const worktrees = await projects.listWorktrees(repo);
res.json({ worktrees });
} catch (e) {
console.error('[api] worktrees error:', e.message);
res.status(400).json({ error: 'Failed to list worktrees' });
}
});
// Create a worktree (must be a registered repo)
app.post('/api/projects/worktrees', async (req, res) => {
try {
const { repoPath, branch, newBranch } = req.body;
if (!repoPath || !branch) {
return res.status(400).json({ error: 'repoPath and branch are required' });
}
if (!projects.isRegisteredRepo(repoPath)) {
return res.status(403).json({ error: 'Repository not registered' });
}
const worktreeDir = await projects.createWorktree(repoPath, branch, newBranch);
const projectId = projects.pathToProjectId(worktreeDir);
res.json({ ok: true, worktreePath: worktreeDir, projectId });
} catch (e) {
console.error('[api] create worktree error:', e.message);
// Show git's error message (strip "fatal:" prefix) — it's useful context
const userMsg = e.message.replace(/^fatal:\s*/i, '').trim() || 'Failed to create worktree';
res.status(400).json({ error: userMsg });
}
});
// Select / activate a project
app.post('/api/projects/select', (req, res) => {
const { projectId, repoPath, branch, worktreePath } = req.body;
if (!projectId) {
return res.status(400).json({ error: 'projectId is required' });
}
// Validate: 'home' always allowed, otherwise must be a valid project path
if (projectId !== 'home' && !projects.validateProjectPath(projectId)) {
return res.status(400).json({ error: 'Invalid project path' });
}
projects.setLastProject(projectId);
if (projectId !== 'home' && repoPath && branch && worktreePath) {
projects.touchRecent(projectId, repoPath, branch, worktreePath);
}
res.json({ ok: true });
});
}
// --- Cache HTML templates ---
const desktopHtml = fs.readFileSync(path.join(__dirname, 'public', 'desktop.html'), 'utf8');
const mobileHtml = fs.readFileSync(path.join(__dirname, 'public', 'mobile.html'), 'utf8');
// --- View + mode routes: /desktop/:mode and /mobile/:mode ---
// Pre-spawn PTY on page load so bash profile noise clears before WS connects.
// Cache-bust asset URLs so phones don't serve stale broken files.
const startupTs = Date.now();
function serveModeHtml(template, mode, projectId, res) {
// Pre-spawn the PTY session so it's ready by the time WebSocket connects
getOrCreateSession(mode, projectId);
const modeScript = `<script>window.POCKETSHELL_MODE=${JSON.stringify(mode)};window.POCKETSHELL_PROJECT=${JSON.stringify(projectId)};</script>`;
let html = template.replace('</head>', modeScript + '\n</head>');
// Cache-bust local assets to avoid stale cached 404s
html = html.replace(/((?:src|href)="\/[^"]+\.(?:js|css))(")/g, `$1?v=${startupTs}$2`);
res.set('Cache-Control', 'no-cache, no-store, must-revalidate');
res.type('html').send(html);
}
app.get('/desktop/:mode(claude|copilot|terminal)', (req, res) => {
const projectId = req.query.project || 'home';
if (projectId !== 'home' && !projects.validateProjectPath(projectId)) {
return res.redirect('/');
}
serveModeHtml(desktopHtml, req.params.mode, projectId, res);
});
app.get('/mobile/:mode(claude|copilot|terminal)', (req, res) => {
const projectId = req.query.project || 'home';
if (projectId !== 'home' && !projects.validateProjectPath(projectId)) {
return res.redirect('/');
}
serveModeHtml(mobileHtml, req.params.mode, projectId, res);
});
// --- WebSocket Server (with auth + path routing) ---
const wss = new WebSocketServer({
server,
maxPayload: 64 * 1024, // 64KB
verifyClient: (info) => {
// Validate WebSocket path: must be /ws/{mode} with optional ?project= query
const parsed = new URL(info.req.url, 'http://localhost');
const match = parsed.pathname.match(/^\/ws\/(claude|copilot|terminal)$/);
if (!match) return false;
// Stash mode and project on request for later use
info.req._pocketshellMode = match[1];
const projectId = parsed.searchParams.get('project') || 'home';
info.req._pocketshellProject = projectId;
// Validate project ID (home is always allowed)
if (projectId !== 'home' && !projects.validateProjectPath(projectId)) {
return false;
}
if (NO_AUTH) return true;
return auth.authenticateWs(info.req);
},
});
// --- WebSocket connections ---
wss.on('connection', (ws, req) => {
const mode = req._pocketshellMode;
const projectId = req._pocketshellProject || 'home';
if (!mode || !VALID_MODES.has(mode)) {
ws.close();
return;
}
const session = getOrCreateSession(mode, projectId);
session.clients.add(ws);
console.log(`[ws:${projectId}:${mode}] client connected (total: ${session.clients.size})`);
// Send replay buffer so new client sees current terminal state
if (session.replayBuffer.length > 0) {
ws.send(JSON.stringify({ type: 'output', data: session.replayBuffer }));
}
ws.on('message', (raw) => {
let msg;
try {
msg = JSON.parse(raw);
} catch (e) {
console.warn(`[ws:${projectId}:${mode}] invalid JSON from client:`, e.message);
return;
}
switch (msg.type) {
case 'input':
if (session.ptyProcess && typeof msg.data === 'string') {
session.ptyProcess.write(msg.data);
}
break;
case 'resize':
if (session.ptyProcess && msg.cols && msg.rows) {
const cols = Math.min(500, Math.max(1, Math.floor(msg.cols)));
const rows = Math.min(200, Math.max(1, Math.floor(msg.rows)));
try {
session.ptyProcess.resize(cols, rows);
} catch (e) {
console.warn(`[ws:${projectId}:${mode}] resize error:`, e.message);
}
}
break;
case 'restart':
console.log(`[ws:${projectId}:${mode}] restart requested`);
session.spawn(msg.cols || 120, msg.rows || 30);
break;
default:
break;
}
});
ws.on('close', () => {
session.clients.delete(ws);
console.log(`[ws:${projectId}:${mode}] client disconnected (total: ${session.clients.size})`);
});
});
// --- Graceful shutdown ---
function shutdown() {
console.log('\n[server] shutting down...');
for (const session of sessions.values()) {
session.kill();
}
wss.close();
server.close(() => process.exit(0));
// Force exit after 3 seconds
setTimeout(() => process.exit(1), 3000);
}
process.on('SIGINT', shutdown);
process.on('SIGTERM', shutdown);
// --- Start ---
server.listen(PORT, BIND_HOST, () => {
console.log('');
console.log(' ┌────────────────────────────────────────────────────────────┐');
console.log(' │ PocketShell is running │');
console.log(' ├────────────────────────────────────────────────────────────┤');
console.log(` │ Landing: http://localhost:${PORT} │`);
console.log(` │ Claude: http://localhost:${PORT}/desktop/claude │`);
console.log(` │ Copilot: http://localhost:${PORT}/desktop/copilot │`);
console.log(` │ Terminal: http://localhost:${PORT}/desktop/terminal │`);
console.log(` │ Bind: ${BIND_HOST.padEnd(46)}│`);
if (NO_AUTH) {
console.log(' │ Auth: DISABLED (--no-auth) │');
} else if (!auth.isSetupComplete()) {
console.log(` │ Setup: http://localhost:${PORT}/login.html?token=${SETUP_TOKEN} │`);
console.log(` │ Token: ${SETUP_TOKEN} │`);
}
console.log(' └────────────────────────────────────────────────────────────┘');
console.log('');
// Auto-open browser for first-time setup
if (!NO_AUTH && !auth.isSetupComplete()) {
const setupUrl = `http://localhost:${PORT}/login.html?token=${SETUP_TOKEN}`;
const openCmd = ['wslview', 'xdg-open', 'open'].find(cmd => {
try { execFileSync('which', [cmd], { stdio: 'ignore', timeout: 1000 }); return true; } catch { return false; }
});
if (openCmd) {
spawn(openCmd, [setupUrl], { detached: true, stdio: 'ignore' }).unref();
console.log(` [server] Opening setup page in browser: ${setupUrl}\n`);
}
}
});