readingroom 0.3.0 → 0.5.0

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/src/server.js CHANGED
@@ -1,9 +1,13 @@
1
1
  import http from 'node:http';
2
- import { createReadStream, existsSync, readFileSync, statSync, watch } from 'node:fs';
2
+ import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
3
+ import { closeSync, createReadStream, existsSync, openSync, readFileSync, readSync, statSync, watch } from 'node:fs';
4
+ import { networkInterfaces } from 'node:os';
3
5
  import path from 'node:path';
4
- import { scanTree, fileKind, DEFAULT_IGNORED_DIRS } from './scanner.js';
6
+ import { scanAllTree, fileCategory, fileKind, filePreview, DEFAULT_IGNORED_DIRS } from './scanner.js';
5
7
  import { openExternal } from './openBrowser.js';
6
8
  import { repoStatus, lastCommitFor, fileHistory, fileVersion, VersionNotFound } from './git.js';
9
+ import { buildDashboard } from './dashboard.js';
10
+ import { startQuickTunnel } from './tunnel.js';
7
11
 
8
12
  const MIME = {
9
13
  '.md': 'text/markdown; charset=utf-8',
@@ -33,6 +37,15 @@ function mimeType(file) {
33
37
  return MIME[path.extname(file).toLowerCase()] || 'application/octet-stream';
34
38
  }
35
39
 
40
+ /**
41
+ * RFC 6266 Content-Disposition for a download filename: an ASCII-only
42
+ * `filename` fallback plus an RFC 5987 `filename*` carrying the real name.
43
+ */
44
+ function contentDisposition(name) {
45
+ const fallback = name.replace(/[^\x20-\x7e]/g, '_').replace(/["\\]/g, '_');
46
+ return `attachment; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(name)}`;
47
+ }
48
+
36
49
  function sendJson(res, status, body) {
37
50
  const data = JSON.stringify(body);
38
51
  res.writeHead(status, {
@@ -42,17 +55,17 @@ function sendJson(res, status, body) {
42
55
  res.end(data);
43
56
  }
44
57
 
45
- function hostAllowed(header) {
58
+ function loopbackHost(header) {
46
59
  if (!header) return false;
47
60
  try {
48
- const hostname = new URL('http://' + header).hostname;
49
- return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1' || hostname === '[::1]';
61
+ const hostname = new URL('http://' + header).hostname.replace(/^\[|\]$/g, '');
62
+ return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1';
50
63
  } catch {
51
64
  return false;
52
65
  }
53
66
  }
54
67
 
55
- function listen(server, port, limit) {
68
+ function listen(server, port, limit, host = '127.0.0.1') {
56
69
  return new Promise((resolve, reject) => {
57
70
  let tries = 0;
58
71
  const attempt = (p) => {
@@ -64,7 +77,7 @@ function listen(server, port, limit) {
64
77
  reject(err);
65
78
  }
66
79
  });
67
- server.listen(p, '127.0.0.1', () => resolve(server.address().port));
80
+ server.listen(p, host, () => resolve(server.address().port));
68
81
  };
69
82
  attempt(port);
70
83
  });
@@ -78,15 +91,126 @@ const NOT_BUILT_PAGE = `<!doctype html>
78
91
  <p>If you are hacking on readingroom itself, run <code>npm run build</code> (or use <code>npm run dev:web</code>) and reload.</p>
79
92
  </body></html>`;
80
93
 
94
+ const PAIR_COOKIE = 'rr_pair';
95
+ const MAX_TEXT_PREVIEW_BYTES = 2 * 1024 * 1024;
96
+ const MAX_CODE_PREVIEW_BYTES = 512 * 1024;
97
+
98
+ function readTextPreview(abs, maxBytes = MAX_TEXT_PREVIEW_BYTES) {
99
+ let fd;
100
+ try {
101
+ fd = openSync(abs, 'r');
102
+ const buffer = Buffer.allocUnsafe(maxBytes);
103
+ const bytes = readSync(fd, buffer, 0, maxBytes, 0);
104
+ return { content: buffer.subarray(0, bytes).toString('utf8'), truncated: bytes < statSync(abs).size };
105
+ } finally {
106
+ if (fd !== undefined) closeSync(fd);
107
+ }
108
+ }
109
+
110
+ function readFileSample(abs, maxBytes = 4096) {
111
+ let fd;
112
+ try {
113
+ fd = openSync(abs, 'r');
114
+ const buffer = Buffer.allocUnsafe(maxBytes);
115
+ const bytes = readSync(fd, buffer, 0, maxBytes, 0);
116
+ return buffer.subarray(0, bytes);
117
+ } catch {
118
+ return null;
119
+ } finally {
120
+ if (fd !== undefined) closeSync(fd);
121
+ }
122
+ }
123
+
124
+ // Served to unauthenticated visitors on the mobile listener. Deliberately
125
+ // does not echo the token — only the paired desktop and QR URL know it.
126
+ const PAIR_REQUIRED_PAGE = `<!doctype html>
127
+ <html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
128
+ <title>readingroom</title></head>
129
+ <body style="font-family: ui-monospace, monospace; background:#0a0a0a; color:#e5e5e5; padding:3rem; line-height:1.6">
130
+ <h1 style="font-size:1.2rem">Pairing required</h1>
131
+ <p>This readingroom is private. Scan the QR code in the desktop sidebar again,</p>
132
+ <p>or open <code>/pair?t=YOUR_ACCESS_CODE</code> with the code shown on the desktop.</p>
133
+ </body></html>`;
134
+
135
+ /** Read a small JSON body from a POST request. */
136
+ function readJsonBody(req, limit = 2048) {
137
+ return new Promise((resolve, reject) => {
138
+ const chunks = [];
139
+ let size = 0;
140
+ req.on('data', (chunk) => {
141
+ size += chunk.length;
142
+ if (size > limit) {
143
+ reject(new Error('body too large'));
144
+ req.destroy();
145
+ return;
146
+ }
147
+ chunks.push(chunk);
148
+ });
149
+ req.on('end', () => {
150
+ try {
151
+ resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {});
152
+ } catch {
153
+ reject(new Error('invalid JSON body'));
154
+ }
155
+ });
156
+ req.on('error', reject);
157
+ });
158
+ }
159
+
160
+ function lanIpv4Addresses() {
161
+ const out = new Set();
162
+ for (const addrs of Object.values(networkInterfaces())) {
163
+ for (const addr of addrs || []) {
164
+ if (addr.family === 'IPv4' && !addr.internal) out.add(addr.address);
165
+ }
166
+ }
167
+ return [...out];
168
+ }
169
+
81
170
  /**
82
171
  * Start the readingroom server.
83
172
  *
84
- * Returns { server, port, url, root, tree(), close() }.
173
+ * Returns { server, port, url, root, tree(), liveReload, mobile, close() }.
174
+ * `mobile` exposes the phone-access feature: { status(), enableLan(),
175
+ * disableLan(), startTunnel(), stopTunnel() }. `startTunnelImpl` is
176
+ * injectable for tests.
85
177
  */
86
- export async function startServer({ root, port = 9345, distDir, autoIncrementLimit = 100, openFile = openExternal }) {
178
+ export async function startServer({
179
+ root,
180
+ port = 9345,
181
+ mobilePort = 9346,
182
+ distDir,
183
+ autoIncrementLimit = 100,
184
+ openFile = openExternal,
185
+ startTunnelImpl = startQuickTunnel,
186
+ }) {
87
187
  const rootAbs = path.resolve(root);
88
- let cachedTree = scanTree(rootAbs);
188
+
189
+ // Per-run pairing token. Anything arriving on the mobile listener must
190
+ // present it (as ?t= on /pair, or as the cookie /pair sets) to get in.
191
+ const token = randomBytes(18).toString('base64url');
192
+ const tokenHash = createHash('sha256').update(token).digest();
193
+ const tokenEquals = (candidate) => {
194
+ if (typeof candidate !== 'string') return false;
195
+ const digest = createHash('sha256').update(candidate).digest();
196
+ return timingSafeEqual(digest, tokenHash);
197
+ };
198
+ const hasPairCookie = (req) => {
199
+ const cookies = req.headers.cookie;
200
+ if (!cookies) return false;
201
+ for (const part of cookies.split(';')) {
202
+ const eq = part.indexOf('=');
203
+ if (eq !== -1 && part.slice(0, eq).trim() === PAIR_COOKIE) {
204
+ return tokenEquals(part.slice(eq + 1).trim());
205
+ }
206
+ }
207
+ return false;
208
+ };
209
+ let cachedTree = scanAllTree(rootAbs);
210
+ let cachedInventory = cachedTree;
89
211
  let lastTreeJson = JSON.stringify(cachedTree);
212
+ let lastInventoryJson = JSON.stringify(cachedInventory);
213
+ let dashboardCache = { inventoryJson: null, promise: null };
90
214
  const sseClients = new Set();
91
215
 
92
216
  // Only serve files that resolve inside the scanned root.
@@ -102,16 +226,40 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
102
226
  for (const res of sseClients) res.write(payload);
103
227
  }
104
228
 
229
+ function dashboardData() {
230
+ if (dashboardCache.inventoryJson === lastInventoryJson && dashboardCache.promise) {
231
+ return dashboardCache.promise;
232
+ }
233
+ dashboardCache = {
234
+ inventoryJson: lastInventoryJson,
235
+ promise: buildDashboard(cachedInventory, rootAbs),
236
+ };
237
+ return dashboardCache.promise;
238
+ }
239
+
105
240
  let rescanTimer = null;
106
241
  function scheduleRescan() {
107
242
  clearTimeout(rescanTimer);
108
243
  rescanTimer = setTimeout(() => {
109
244
  try {
110
- const next = scanTree(rootAbs);
111
- const json = JSON.stringify(next);
112
- if (json !== lastTreeJson) {
113
- cachedTree = next;
114
- lastTreeJson = json;
245
+ const next = scanAllTree(rootAbs);
246
+ const nextInventory = next;
247
+ const treeJson = JSON.stringify(next);
248
+ const inventoryJson = JSON.stringify(nextInventory);
249
+ const treeChanged = treeJson !== lastTreeJson;
250
+ const inventoryChanged = inventoryJson !== lastInventoryJson;
251
+ if (treeChanged || inventoryChanged) {
252
+ if (treeChanged) {
253
+ cachedTree = next;
254
+ lastTreeJson = treeJson;
255
+ }
256
+ if (inventoryChanged) {
257
+ cachedInventory = nextInventory;
258
+ lastInventoryJson = inventoryJson;
259
+ }
260
+ dashboardCache = { inventoryJson: null, promise: null };
261
+ // An inventory-only change still needs to wake the dashboard, while
262
+ // keeping the sidebar tree payload stable for its subscribers.
115
263
  broadcastTree();
116
264
  }
117
265
  } catch {
@@ -171,12 +319,8 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
171
319
  createReadStream(indexPath).pipe(res);
172
320
  }
173
321
 
174
- const server = http.createServer(async (req, res) => {
322
+ const handle = async (req, res, channel) => {
175
323
  try {
176
- if (!hostAllowed(req.headers.host)) {
177
- sendJson(res, 403, { error: 'forbidden host' });
178
- return;
179
- }
180
324
  const url = new URL(req.url, 'http://127.0.0.1');
181
325
  const pathname = url.pathname;
182
326
 
@@ -185,6 +329,11 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
185
329
  return;
186
330
  }
187
331
 
332
+ if (pathname === '/api/dashboard') {
333
+ sendJson(res, 200, await dashboardData());
334
+ return;
335
+ }
336
+
188
337
  if (pathname === '/api/file') {
189
338
  const rel = url.searchParams.get('p');
190
339
  const abs = safeResolve(rel);
@@ -192,11 +341,6 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
192
341
  sendJson(res, 403, { error: 'path outside root' });
193
342
  return;
194
343
  }
195
- const kind = fileKind(path.basename(abs));
196
- if (kind !== 'md' && kind !== 'txt') {
197
- sendJson(res, 400, { error: 'only .md and .txt files can be opened as text' });
198
- return;
199
- }
200
344
  let st;
201
345
  try {
202
346
  st = statSync(abs);
@@ -208,14 +352,40 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
208
352
  sendJson(res, 400, { error: 'not a file' });
209
353
  return;
210
354
  }
211
- const content = readFileSync(abs, 'utf8');
355
+ const name = path.basename(abs);
356
+ const kind = fileKind(name);
357
+ const category = fileCategory(name, readFileSample(abs));
358
+ const preview = filePreview(name, category);
359
+ if (preview !== 'text') {
360
+ sendJson(res, 200, {
361
+ path: rel.replace(/\\/g, '/'),
362
+ name,
363
+ ext: path.extname(abs).toLowerCase(),
364
+ size: st.size,
365
+ mtime: st.mtimeMs,
366
+ kind: kind || 'other',
367
+ category,
368
+ preview,
369
+ previewable: false,
370
+ content: null,
371
+ });
372
+ return;
373
+ }
374
+ const previewLimit = category === 'code' || category === 'json' ? MAX_CODE_PREVIEW_BYTES : MAX_TEXT_PREVIEW_BYTES;
375
+ const { content, truncated } = readTextPreview(abs, previewLimit);
212
376
  sendJson(res, 200, {
213
377
  path: rel.replace(/\\/g, '/'),
214
- name: path.basename(abs),
378
+ name,
215
379
  ext: path.extname(abs).toLowerCase(),
216
380
  size: st.size,
217
381
  mtime: st.mtimeMs,
218
- kind,
382
+ kind: kind || 'other',
383
+ category,
384
+ preview,
385
+ previewable: true,
386
+ truncated,
387
+ previewBytes: Buffer.byteLength(content),
388
+ previewLimit,
219
389
  content,
220
390
  });
221
391
  return;
@@ -247,11 +417,12 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
247
417
  const cleanRel = rel.replace(/\\/g, '/');
248
418
  const name = path.basename(abs);
249
419
  const kind = fileKind(name);
420
+ const category = fileCategory(name, readFileSample(abs));
250
421
  let words = null;
251
422
  let chars = null;
252
- if (kind === 'md' || kind === 'txt') {
423
+ if (filePreview(name, category) === 'text' && st.size <= MAX_TEXT_PREVIEW_BYTES) {
253
424
  try {
254
- const content = readFileSync(abs, 'utf8');
425
+ const content = readTextPreview(abs).content;
255
426
  words = (content.match(/\S+/g) || []).length;
256
427
  chars = content.length;
257
428
  } catch {
@@ -264,6 +435,9 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
264
435
  name,
265
436
  ext: path.extname(abs).toLowerCase(),
266
437
  kind,
438
+ category,
439
+ preview: filePreview(name, category),
440
+ previewable: filePreview(name, category) === 'text' && st.size <= MAX_TEXT_PREVIEW_BYTES,
267
441
  size: st.size,
268
442
  mtime: st.mtimeMs,
269
443
  words,
@@ -324,6 +498,8 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
324
498
  }
325
499
  const name = path.basename(abs);
326
500
  const kind = fileKind(name);
501
+ const category = fileCategory(name, version.buffer.subarray(0, 4096));
502
+ const preview = filePreview(name, category);
327
503
  if (url.searchParams.get('raw') === '1') {
328
504
  const type = mimeType(abs);
329
505
  res.writeHead(200, {
@@ -332,20 +508,31 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
332
508
  'Cache-Control': 'no-store',
333
509
  'X-Content-Type-Options': 'nosniff',
334
510
  ...(type === 'application/pdf' ? {} : { 'Content-Security-Policy': 'sandbox' }),
511
+ ...(url.searchParams.get('download') === '1'
512
+ // entry.path is the rename-aware name at this commit; refs hit
513
+ // outside the walked history have no entry and fall back to the
514
+ // current name.
515
+ ? { 'Content-Disposition': contentDisposition(path.basename(version.entry?.path || rel)) }
516
+ : {}),
335
517
  });
336
518
  res.end(version.buffer);
337
519
  return;
338
520
  }
339
- const isText = kind === 'md' || kind === 'txt';
521
+ const isText = preview === 'text';
340
522
  const entry = version.entry;
523
+ const contentLimit = category === 'code' || category === 'json' ? MAX_CODE_PREVIEW_BYTES : MAX_TEXT_PREVIEW_BYTES;
524
+ const contentBuffer = isText ? version.buffer.subarray(0, contentLimit) : null;
341
525
  sendJson(res, 200, {
342
526
  path: rel.replace(/\\/g, '/'),
343
527
  name,
344
528
  ext: path.extname(abs).toLowerCase(),
345
529
  kind,
530
+ category,
531
+ preview,
346
532
  size: version.buffer.length,
347
533
  binary: !isText,
348
- content: isText ? version.buffer.toString('utf8') : null,
534
+ content: contentBuffer ? contentBuffer.toString('utf8') : null,
535
+ truncated: Boolean(contentBuffer && contentBuffer.length < version.buffer.length),
349
536
  ref: entry ? entry.sha : ref,
350
537
  author: entry ? entry.author : null,
351
538
  date: entry ? entry.date : null,
@@ -382,12 +569,20 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
382
569
  // exempt: some browsers refuse to run their built-in PDF viewer on
383
570
  // a response delivered under CSP sandbox.
384
571
  ...(type === 'application/pdf' ? {} : { 'Content-Security-Policy': 'sandbox' }),
572
+ ...(url.searchParams.get('download') === '1'
573
+ ? { 'Content-Disposition': contentDisposition(path.basename(abs)) }
574
+ : {}),
385
575
  });
386
576
  createReadStream(abs).pipe(res);
387
577
  return;
388
578
  }
389
579
 
390
580
  if (pathname === '/api/open') {
581
+ if (channel === 'mobile') {
582
+ // Launching a system app is a desktop-only action.
583
+ sendJson(res, 403, { error: 'not available from a paired device' });
584
+ return;
585
+ }
391
586
  if (req.method !== 'POST') {
392
587
  sendJson(res, 405, { error: 'method not allowed' });
393
588
  return;
@@ -422,6 +617,48 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
422
617
  return;
423
618
  }
424
619
 
620
+ if (pathname === '/api/mobile' || pathname === '/api/mobile/lan' || pathname === '/api/mobile/tunnel') {
621
+ // The phone-access controls manage the host machine; loopback only.
622
+ if (channel !== 'local') {
623
+ sendJson(res, 403, { error: 'desktop only' });
624
+ return;
625
+ }
626
+ if (pathname === '/api/mobile') {
627
+ if (req.method !== 'GET') {
628
+ sendJson(res, 405, { error: 'method not allowed' });
629
+ return;
630
+ }
631
+ sendJson(res, 200, mobileStatus());
632
+ return;
633
+ }
634
+ if (req.method !== 'POST') {
635
+ sendJson(res, 405, { error: 'method not allowed' });
636
+ return;
637
+ }
638
+ let body;
639
+ try {
640
+ body = await readJsonBody(req);
641
+ } catch (err) {
642
+ sendJson(res, 400, { error: err.message });
643
+ return;
644
+ }
645
+ const enable = body.enabled === true;
646
+ try {
647
+ if (pathname === '/api/mobile/lan') {
648
+ if (enable) await enableLan();
649
+ else await disableLan();
650
+ } else {
651
+ if (enable) await startTunnel();
652
+ else await stopTunnel();
653
+ }
654
+ } catch (err) {
655
+ sendJson(res, 500, { error: err.message });
656
+ return;
657
+ }
658
+ sendJson(res, 200, mobileStatus());
659
+ return;
660
+ }
661
+
425
662
  if (pathname === '/api/events') {
426
663
  res.writeHead(200, {
427
664
  'Content-Type': 'text/event-stream',
@@ -449,6 +686,222 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
449
686
  if (!res.headersSent) sendJson(res, 500, { error: 'internal error' });
450
687
  else res.end();
451
688
  }
689
+ };
690
+
691
+ // ---- phone access --------------------------------------------------------
692
+ //
693
+ // A second listener (0.0.0.0, default port 9346) serves phones. Every
694
+ // request on it needs the pairing token; there is deliberately no loopback
695
+ // exemption because cloudflared's proxy also connects from 127.0.0.1.
696
+ let lanServer = null;
697
+ let lanHosts = new Set();
698
+ // The mobile listener may run for the tunnel alone. `lanAdvertised` tracks
699
+ // what the user actually asked for: Wi-Fi sharing (and its QR) is only
700
+ // reported when started explicitly, never as a side effect of the tunnel.
701
+ let lanAdvertised = false;
702
+ let listener = { running: false, port: null, urls: [] };
703
+ let tunnelState = { state: 'off', url: null, bytes: 0, total: null, error: null };
704
+ let tunnelStop = null;
705
+ let tunnelHost = null;
706
+ let tunnelGen = 0;
707
+
708
+ function mobileAllowedHost(header) {
709
+ if (!header) return false;
710
+ try {
711
+ const hostname = new URL('http://' + header).hostname.replace(/^\[|\]$/g, '').toLowerCase();
712
+ if (hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1') return true;
713
+ if (tunnelHost && hostname === tunnelHost) return true;
714
+ return lanHosts.has(hostname);
715
+ } catch {
716
+ return false;
717
+ }
718
+ }
719
+
720
+ function handlePair(req, res, url) {
721
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
722
+ sendJson(res, 405, { error: 'method not allowed' });
723
+ return;
724
+ }
725
+ if (!tokenEquals(url.searchParams.get('t'))) {
726
+ sendJson(res, 403, { error: 'invalid access code' });
727
+ return;
728
+ }
729
+ res.writeHead(302, {
730
+ Location: '/',
731
+ 'Set-Cookie': `${PAIR_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax`,
732
+ 'Cache-Control': 'no-store',
733
+ });
734
+ res.end();
735
+ }
736
+
737
+ function unauthenticated(res, pathname) {
738
+ if (pathname.startsWith('/api/')) {
739
+ sendJson(res, 401, { error: 'pairing required' });
740
+ } else {
741
+ res.writeHead(401, {
742
+ 'Content-Type': 'text/html; charset=utf-8',
743
+ 'Cache-Control': 'no-store',
744
+ });
745
+ res.end(PAIR_REQUIRED_PAGE);
746
+ }
747
+ }
748
+
749
+ const mobileGuard = (req, res) => {
750
+ if (!mobileAllowedHost(req.headers.host)) {
751
+ sendJson(res, 403, { error: 'forbidden host' });
752
+ return;
753
+ }
754
+ let url;
755
+ try {
756
+ url = new URL(req.url, 'http://127.0.0.1');
757
+ } catch {
758
+ sendJson(res, 400, { error: 'bad request' });
759
+ return;
760
+ }
761
+ if (url.pathname === '/pair') {
762
+ handlePair(req, res, url);
763
+ return;
764
+ }
765
+ if (!hasPairCookie(req)) {
766
+ unauthenticated(res, url.pathname);
767
+ return;
768
+ }
769
+ handle(req, res, 'mobile').catch(() => {
770
+ if (!res.headersSent) res.destroy();
771
+ });
772
+ };
773
+
774
+ function mobileStatus() {
775
+ const pair = (u) => `${u}/pair?t=${token}`;
776
+ return {
777
+ token,
778
+ lan: {
779
+ enabled: lanAdvertised,
780
+ port: listener.running ? listener.port : null,
781
+ urls: lanAdvertised ? listener.urls.map(pair) : [],
782
+ },
783
+ tunnel: {
784
+ state: tunnelState.state,
785
+ url: tunnelState.url ? pair(tunnelState.url) : null,
786
+ bytes: tunnelState.bytes,
787
+ total: tunnelState.total,
788
+ error: tunnelState.error,
789
+ },
790
+ };
791
+ }
792
+
793
+ // Bring the mobile listener up (idempotent). Silent by design: it is an
794
+ // implementation detail shared by Wi-Fi sharing and the tunnel.
795
+ async function startListener() {
796
+ if (listener.running) return;
797
+ const server = http.createServer(mobileGuard);
798
+ const actualPort = await listen(server, mobilePort, autoIncrementLimit, '0.0.0.0');
799
+ const addresses = lanIpv4Addresses();
800
+ lanServer = server;
801
+ lanHosts = new Set(addresses);
802
+ listener = {
803
+ running: true,
804
+ port: actualPort,
805
+ urls: addresses.map((ip) => `http://${ip}:${actualPort}`),
806
+ };
807
+ }
808
+
809
+ async function stopListener() {
810
+ listener = { running: false, port: null, urls: [] };
811
+ lanHosts = new Set();
812
+ const server = lanServer;
813
+ lanServer = null;
814
+ if (server) {
815
+ // Mobile clients may hold SSE streams open; end them so close() returns.
816
+ // Desktop clients transparently reconnect.
817
+ for (const res of sseClients) res.end();
818
+ server.close();
819
+ server.closeAllConnections?.();
820
+ }
821
+ }
822
+
823
+ async function enableLan() {
824
+ if (lanAdvertised) return;
825
+ await startListener();
826
+ lanAdvertised = true;
827
+ if (listener.urls.length === 0) {
828
+ console.warn('readingroom: no network address found — phones must use the tunnel');
829
+ } else {
830
+ console.log(`readingroom: phone access on — ${listener.urls[0]}/pair?t=${token}`);
831
+ }
832
+ }
833
+
834
+ async function disableLan() {
835
+ const wasAdvertised = lanAdvertised;
836
+ lanAdvertised = false;
837
+ // stopTunnel tears the listener down too when nothing else needs it.
838
+ await stopTunnel();
839
+ if (listener.running) await stopListener();
840
+ if (wasAdvertised) console.log('readingroom: phone access off');
841
+ }
842
+
843
+ function setTunnel(patch) {
844
+ tunnelState = { ...tunnelState, ...patch };
845
+ }
846
+
847
+ // Kicks the work off and returns; progress and errors land in the tunnel
848
+ // state that GET /api/mobile reports. The listener it needs comes up
849
+ // silently — Wi-Fi sharing is only reported when started explicitly.
850
+ async function startTunnel() {
851
+ await startListener();
852
+ if (tunnelState.state === 'on' || tunnelState.state === 'downloading' || tunnelState.state === 'starting') {
853
+ return;
854
+ }
855
+ const gen = ++tunnelGen;
856
+ setTunnel({ state: 'downloading', url: null, bytes: 0, total: null, error: null });
857
+ startTunnelImpl({
858
+ targetPort: listener.port,
859
+ onProgress: (p) => {
860
+ if (gen !== tunnelGen) return;
861
+ if (p.phase === 'downloading') setTunnel({ state: 'downloading', bytes: p.bytes, total: p.total });
862
+ else if (p.phase === 'starting') setTunnel({ state: 'starting' });
863
+ },
864
+ onUnexpectedExit: (message) => {
865
+ if (gen !== tunnelGen) return;
866
+ setTunnel({ state: 'error', url: null, error: message });
867
+ },
868
+ }).then(
869
+ ({ url, host, stop }) => {
870
+ if (gen !== tunnelGen) {
871
+ stop();
872
+ return;
873
+ }
874
+ tunnelStop = stop;
875
+ tunnelHost = host;
876
+ setTunnel({ state: 'on', url, error: null });
877
+ console.log(`readingroom: tunnel ready — ${url}/pair?t=${token}`);
878
+ },
879
+ (err) => {
880
+ if (gen !== tunnelGen) return;
881
+ setTunnel({ state: 'error', error: err.message });
882
+ },
883
+ );
884
+ }
885
+
886
+ async function stopTunnel() {
887
+ tunnelGen += 1; // invalidate any in-flight start
888
+ tunnelHost = null;
889
+ const stop = tunnelStop;
890
+ tunnelStop = null;
891
+ setTunnel({ state: 'off', url: null, error: null, bytes: 0, total: null });
892
+ if (stop) await stop();
893
+ // If the listener only existed for the tunnel, bring the whole thing down.
894
+ if (!lanAdvertised && listener.running) await stopListener();
895
+ }
896
+
897
+ const server = http.createServer((req, res) => {
898
+ if (!loopbackHost(req.headers.host)) {
899
+ sendJson(res, 403, { error: 'forbidden host' });
900
+ return;
901
+ }
902
+ handle(req, res, 'local').catch(() => {
903
+ if (!res.headersSent) res.destroy();
904
+ });
452
905
  });
453
906
 
454
907
  const actualPort = await listen(server, port, autoIncrementLimit);
@@ -460,11 +913,25 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
460
913
  root: rootAbs,
461
914
  tree: () => cachedTree,
462
915
  liveReload: watcher !== null,
916
+ mobile: {
917
+ status: mobileStatus,
918
+ enableLan,
919
+ disableLan,
920
+ startTunnel,
921
+ stopTunnel,
922
+ },
463
923
  close() {
464
924
  clearTimeout(rescanTimer);
465
925
  clearInterval(heartbeat);
466
926
  watcher?.close();
467
927
  for (const res of sseClients) res.end();
928
+ if (lanServer) {
929
+ lanServer.close();
930
+ lanServer.closeAllConnections?.();
931
+ }
932
+ // stop() dispatches SIGTERM synchronously, so the child dies even if
933
+ // the process exits immediately after close().
934
+ tunnelStop?.();
468
935
  server.close();
469
936
  },
470
937
  };