readingroom 0.2.0 → 0.4.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/README.md +35 -7
- package/dist/assets/index-BRMmjGIp.js +190 -0
- package/dist/assets/index-C2oluWMZ.css +2 -0
- package/dist/index.html +2 -2
- package/package.json +1 -1
- package/src/git.js +216 -0
- package/src/server.js +521 -12
- package/src/tunnel.js +294 -0
- package/dist/assets/index-87varIK4.js +0 -190
- package/dist/assets/index-jgmgco4r.css +0 -2
package/src/server.js
CHANGED
|
@@ -1,8 +1,12 @@
|
|
|
1
1
|
import http from 'node:http';
|
|
2
|
+
import { createHash, randomBytes, timingSafeEqual } from 'node:crypto';
|
|
2
3
|
import { createReadStream, existsSync, readFileSync, statSync, watch } from 'node:fs';
|
|
4
|
+
import { networkInterfaces } from 'node:os';
|
|
3
5
|
import path from 'node:path';
|
|
4
6
|
import { scanTree, fileKind, DEFAULT_IGNORED_DIRS } from './scanner.js';
|
|
5
7
|
import { openExternal } from './openBrowser.js';
|
|
8
|
+
import { repoStatus, lastCommitFor, fileHistory, fileVersion, VersionNotFound } from './git.js';
|
|
9
|
+
import { startQuickTunnel } from './tunnel.js';
|
|
6
10
|
|
|
7
11
|
const MIME = {
|
|
8
12
|
'.md': 'text/markdown; charset=utf-8',
|
|
@@ -32,6 +36,15 @@ function mimeType(file) {
|
|
|
32
36
|
return MIME[path.extname(file).toLowerCase()] || 'application/octet-stream';
|
|
33
37
|
}
|
|
34
38
|
|
|
39
|
+
/**
|
|
40
|
+
* RFC 6266 Content-Disposition for a download filename: an ASCII-only
|
|
41
|
+
* `filename` fallback plus an RFC 5987 `filename*` carrying the real name.
|
|
42
|
+
*/
|
|
43
|
+
function contentDisposition(name) {
|
|
44
|
+
const fallback = name.replace(/[^\x20-\x7e]/g, '_').replace(/["\\]/g, '_');
|
|
45
|
+
return `attachment; filename="${fallback}"; filename*=UTF-8''${encodeURIComponent(name)}`;
|
|
46
|
+
}
|
|
47
|
+
|
|
35
48
|
function sendJson(res, status, body) {
|
|
36
49
|
const data = JSON.stringify(body);
|
|
37
50
|
res.writeHead(status, {
|
|
@@ -41,17 +54,17 @@ function sendJson(res, status, body) {
|
|
|
41
54
|
res.end(data);
|
|
42
55
|
}
|
|
43
56
|
|
|
44
|
-
function
|
|
57
|
+
function loopbackHost(header) {
|
|
45
58
|
if (!header) return false;
|
|
46
59
|
try {
|
|
47
|
-
const hostname = new URL('http://' + header).hostname;
|
|
48
|
-
return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1'
|
|
60
|
+
const hostname = new URL('http://' + header).hostname.replace(/^\[|\]$/g, '');
|
|
61
|
+
return hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1';
|
|
49
62
|
} catch {
|
|
50
63
|
return false;
|
|
51
64
|
}
|
|
52
65
|
}
|
|
53
66
|
|
|
54
|
-
function listen(server, port, limit) {
|
|
67
|
+
function listen(server, port, limit, host = '127.0.0.1') {
|
|
55
68
|
return new Promise((resolve, reject) => {
|
|
56
69
|
let tries = 0;
|
|
57
70
|
const attempt = (p) => {
|
|
@@ -63,7 +76,7 @@ function listen(server, port, limit) {
|
|
|
63
76
|
reject(err);
|
|
64
77
|
}
|
|
65
78
|
});
|
|
66
|
-
server.listen(p,
|
|
79
|
+
server.listen(p, host, () => resolve(server.address().port));
|
|
67
80
|
};
|
|
68
81
|
attempt(port);
|
|
69
82
|
});
|
|
@@ -77,13 +90,93 @@ const NOT_BUILT_PAGE = `<!doctype html>
|
|
|
77
90
|
<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>
|
|
78
91
|
</body></html>`;
|
|
79
92
|
|
|
93
|
+
const PAIR_COOKIE = 'rr_pair';
|
|
94
|
+
|
|
95
|
+
// Served to unauthenticated visitors on the mobile listener. Deliberately
|
|
96
|
+
// does not echo the token — only the paired desktop and QR URL know it.
|
|
97
|
+
const PAIR_REQUIRED_PAGE = `<!doctype html>
|
|
98
|
+
<html><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
99
|
+
<title>readingroom</title></head>
|
|
100
|
+
<body style="font-family: ui-monospace, monospace; background:#0a0a0a; color:#e5e5e5; padding:3rem; line-height:1.6">
|
|
101
|
+
<h1 style="font-size:1.2rem">Pairing required</h1>
|
|
102
|
+
<p>This readingroom is private. Scan the QR code in the desktop sidebar again,</p>
|
|
103
|
+
<p>or open <code>/pair?t=YOUR_ACCESS_CODE</code> with the code shown on the desktop.</p>
|
|
104
|
+
</body></html>`;
|
|
105
|
+
|
|
106
|
+
/** Read a small JSON body from a POST request. */
|
|
107
|
+
function readJsonBody(req, limit = 2048) {
|
|
108
|
+
return new Promise((resolve, reject) => {
|
|
109
|
+
const chunks = [];
|
|
110
|
+
let size = 0;
|
|
111
|
+
req.on('data', (chunk) => {
|
|
112
|
+
size += chunk.length;
|
|
113
|
+
if (size > limit) {
|
|
114
|
+
reject(new Error('body too large'));
|
|
115
|
+
req.destroy();
|
|
116
|
+
return;
|
|
117
|
+
}
|
|
118
|
+
chunks.push(chunk);
|
|
119
|
+
});
|
|
120
|
+
req.on('end', () => {
|
|
121
|
+
try {
|
|
122
|
+
resolve(chunks.length ? JSON.parse(Buffer.concat(chunks).toString('utf8')) : {});
|
|
123
|
+
} catch {
|
|
124
|
+
reject(new Error('invalid JSON body'));
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
req.on('error', reject);
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
|
|
131
|
+
function lanIpv4Addresses() {
|
|
132
|
+
const out = new Set();
|
|
133
|
+
for (const addrs of Object.values(networkInterfaces())) {
|
|
134
|
+
for (const addr of addrs || []) {
|
|
135
|
+
if (addr.family === 'IPv4' && !addr.internal) out.add(addr.address);
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
return [...out];
|
|
139
|
+
}
|
|
140
|
+
|
|
80
141
|
/**
|
|
81
142
|
* Start the readingroom server.
|
|
82
143
|
*
|
|
83
|
-
* Returns { server, port, url, root, tree(), close() }.
|
|
144
|
+
* Returns { server, port, url, root, tree(), liveReload, mobile, close() }.
|
|
145
|
+
* `mobile` exposes the phone-access feature: { status(), enableLan(),
|
|
146
|
+
* disableLan(), startTunnel(), stopTunnel() }. `startTunnelImpl` is
|
|
147
|
+
* injectable for tests.
|
|
84
148
|
*/
|
|
85
|
-
export async function startServer({
|
|
149
|
+
export async function startServer({
|
|
150
|
+
root,
|
|
151
|
+
port = 9345,
|
|
152
|
+
mobilePort = 9346,
|
|
153
|
+
distDir,
|
|
154
|
+
autoIncrementLimit = 100,
|
|
155
|
+
openFile = openExternal,
|
|
156
|
+
startTunnelImpl = startQuickTunnel,
|
|
157
|
+
}) {
|
|
86
158
|
const rootAbs = path.resolve(root);
|
|
159
|
+
|
|
160
|
+
// Per-run pairing token. Anything arriving on the mobile listener must
|
|
161
|
+
// present it (as ?t= on /pair, or as the cookie /pair sets) to get in.
|
|
162
|
+
const token = randomBytes(18).toString('base64url');
|
|
163
|
+
const tokenHash = createHash('sha256').update(token).digest();
|
|
164
|
+
const tokenEquals = (candidate) => {
|
|
165
|
+
if (typeof candidate !== 'string') return false;
|
|
166
|
+
const digest = createHash('sha256').update(candidate).digest();
|
|
167
|
+
return timingSafeEqual(digest, tokenHash);
|
|
168
|
+
};
|
|
169
|
+
const hasPairCookie = (req) => {
|
|
170
|
+
const cookies = req.headers.cookie;
|
|
171
|
+
if (!cookies) return false;
|
|
172
|
+
for (const part of cookies.split(';')) {
|
|
173
|
+
const eq = part.indexOf('=');
|
|
174
|
+
if (eq !== -1 && part.slice(0, eq).trim() === PAIR_COOKIE) {
|
|
175
|
+
return tokenEquals(part.slice(eq + 1).trim());
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
return false;
|
|
179
|
+
};
|
|
87
180
|
let cachedTree = scanTree(rootAbs);
|
|
88
181
|
let lastTreeJson = JSON.stringify(cachedTree);
|
|
89
182
|
const sseClients = new Set();
|
|
@@ -170,12 +263,8 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
|
|
|
170
263
|
createReadStream(indexPath).pipe(res);
|
|
171
264
|
}
|
|
172
265
|
|
|
173
|
-
const
|
|
266
|
+
const handle = async (req, res, channel) => {
|
|
174
267
|
try {
|
|
175
|
-
if (!hostAllowed(req.headers.host)) {
|
|
176
|
-
sendJson(res, 403, { error: 'forbidden host' });
|
|
177
|
-
return;
|
|
178
|
-
}
|
|
179
268
|
const url = new URL(req.url, 'http://127.0.0.1');
|
|
180
269
|
const pathname = url.pathname;
|
|
181
270
|
|
|
@@ -220,6 +309,146 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
|
|
|
220
309
|
return;
|
|
221
310
|
}
|
|
222
311
|
|
|
312
|
+
if (pathname === '/api/repo') {
|
|
313
|
+
sendJson(res, 200, await repoStatus(rootAbs));
|
|
314
|
+
return;
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
if (pathname === '/api/meta') {
|
|
318
|
+
const rel = url.searchParams.get('p');
|
|
319
|
+
const abs = safeResolve(rel);
|
|
320
|
+
if (!abs) {
|
|
321
|
+
sendJson(res, 403, { error: 'path outside root' });
|
|
322
|
+
return;
|
|
323
|
+
}
|
|
324
|
+
let st;
|
|
325
|
+
try {
|
|
326
|
+
st = statSync(abs);
|
|
327
|
+
} catch {
|
|
328
|
+
sendJson(res, 404, { error: 'not found' });
|
|
329
|
+
return;
|
|
330
|
+
}
|
|
331
|
+
if (!st.isFile()) {
|
|
332
|
+
sendJson(res, 400, { error: 'not a file' });
|
|
333
|
+
return;
|
|
334
|
+
}
|
|
335
|
+
const cleanRel = rel.replace(/\\/g, '/');
|
|
336
|
+
const name = path.basename(abs);
|
|
337
|
+
const kind = fileKind(name);
|
|
338
|
+
let words = null;
|
|
339
|
+
let chars = null;
|
|
340
|
+
if (kind === 'md' || kind === 'txt') {
|
|
341
|
+
try {
|
|
342
|
+
const content = readFileSync(abs, 'utf8');
|
|
343
|
+
words = (content.match(/\S+/g) || []).length;
|
|
344
|
+
chars = content.length;
|
|
345
|
+
} catch {
|
|
346
|
+
/* unreadable right now — reading stats stay null */
|
|
347
|
+
}
|
|
348
|
+
}
|
|
349
|
+
const lastCommit = await lastCommitFor(rootAbs, cleanRel);
|
|
350
|
+
sendJson(res, 200, {
|
|
351
|
+
path: cleanRel,
|
|
352
|
+
name,
|
|
353
|
+
ext: path.extname(abs).toLowerCase(),
|
|
354
|
+
kind,
|
|
355
|
+
size: st.size,
|
|
356
|
+
mtime: st.mtimeMs,
|
|
357
|
+
words,
|
|
358
|
+
chars,
|
|
359
|
+
lastCommit,
|
|
360
|
+
});
|
|
361
|
+
return;
|
|
362
|
+
}
|
|
363
|
+
|
|
364
|
+
if (pathname === '/api/history') {
|
|
365
|
+
const rel = url.searchParams.get('p');
|
|
366
|
+
const abs = safeResolve(rel);
|
|
367
|
+
if (!abs) {
|
|
368
|
+
sendJson(res, 403, { error: 'path outside root' });
|
|
369
|
+
return;
|
|
370
|
+
}
|
|
371
|
+
let history;
|
|
372
|
+
try {
|
|
373
|
+
history = await fileHistory(rootAbs, rel.replace(/\\/g, '/'));
|
|
374
|
+
} catch {
|
|
375
|
+
sendJson(res, 500, { error: 'git failed' });
|
|
376
|
+
return;
|
|
377
|
+
}
|
|
378
|
+
if (!history) {
|
|
379
|
+
sendJson(res, 200, { git: false, commits: [], truncated: false });
|
|
380
|
+
return;
|
|
381
|
+
}
|
|
382
|
+
sendJson(res, 200, { git: true, commits: history.commits, truncated: history.truncated });
|
|
383
|
+
return;
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
if (pathname === '/api/version') {
|
|
387
|
+
const rel = url.searchParams.get('p');
|
|
388
|
+
const abs = safeResolve(rel);
|
|
389
|
+
if (!abs) {
|
|
390
|
+
sendJson(res, 403, { error: 'path outside root' });
|
|
391
|
+
return;
|
|
392
|
+
}
|
|
393
|
+
const ref = url.searchParams.get('ref');
|
|
394
|
+
if (!ref || !/^[0-9a-f]{7,40}$/i.test(ref)) {
|
|
395
|
+
sendJson(res, 400, { error: 'bad ref' });
|
|
396
|
+
return;
|
|
397
|
+
}
|
|
398
|
+
let version;
|
|
399
|
+
try {
|
|
400
|
+
version = await fileVersion(rootAbs, rel.replace(/\\/g, '/'), ref);
|
|
401
|
+
} catch (err) {
|
|
402
|
+
if (err instanceof VersionNotFound) {
|
|
403
|
+
sendJson(res, 404, { error: 'version not found' });
|
|
404
|
+
} else {
|
|
405
|
+
sendJson(res, 500, { error: 'git failed' });
|
|
406
|
+
}
|
|
407
|
+
return;
|
|
408
|
+
}
|
|
409
|
+
if (!version) {
|
|
410
|
+
sendJson(res, 404, { error: 'not a git repository' });
|
|
411
|
+
return;
|
|
412
|
+
}
|
|
413
|
+
const name = path.basename(abs);
|
|
414
|
+
const kind = fileKind(name);
|
|
415
|
+
if (url.searchParams.get('raw') === '1') {
|
|
416
|
+
const type = mimeType(abs);
|
|
417
|
+
res.writeHead(200, {
|
|
418
|
+
'Content-Type': type,
|
|
419
|
+
'Content-Length': version.buffer.length,
|
|
420
|
+
'Cache-Control': 'no-store',
|
|
421
|
+
'X-Content-Type-Options': 'nosniff',
|
|
422
|
+
...(type === 'application/pdf' ? {} : { 'Content-Security-Policy': 'sandbox' }),
|
|
423
|
+
...(url.searchParams.get('download') === '1'
|
|
424
|
+
// entry.path is the rename-aware name at this commit; refs hit
|
|
425
|
+
// outside the walked history have no entry and fall back to the
|
|
426
|
+
// current name.
|
|
427
|
+
? { 'Content-Disposition': contentDisposition(path.basename(version.entry?.path || rel)) }
|
|
428
|
+
: {}),
|
|
429
|
+
});
|
|
430
|
+
res.end(version.buffer);
|
|
431
|
+
return;
|
|
432
|
+
}
|
|
433
|
+
const isText = kind === 'md' || kind === 'txt';
|
|
434
|
+
const entry = version.entry;
|
|
435
|
+
sendJson(res, 200, {
|
|
436
|
+
path: rel.replace(/\\/g, '/'),
|
|
437
|
+
name,
|
|
438
|
+
ext: path.extname(abs).toLowerCase(),
|
|
439
|
+
kind,
|
|
440
|
+
size: version.buffer.length,
|
|
441
|
+
binary: !isText,
|
|
442
|
+
content: isText ? version.buffer.toString('utf8') : null,
|
|
443
|
+
ref: entry ? entry.sha : ref,
|
|
444
|
+
author: entry ? entry.author : null,
|
|
445
|
+
date: entry ? entry.date : null,
|
|
446
|
+
subject: entry ? entry.subject : null,
|
|
447
|
+
deleted: entry ? entry.status === 'D' : false,
|
|
448
|
+
});
|
|
449
|
+
return;
|
|
450
|
+
}
|
|
451
|
+
|
|
223
452
|
if (pathname === '/api/raw') {
|
|
224
453
|
const abs = safeResolve(url.searchParams.get('p'));
|
|
225
454
|
if (!abs) {
|
|
@@ -247,12 +476,20 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
|
|
|
247
476
|
// exempt: some browsers refuse to run their built-in PDF viewer on
|
|
248
477
|
// a response delivered under CSP sandbox.
|
|
249
478
|
...(type === 'application/pdf' ? {} : { 'Content-Security-Policy': 'sandbox' }),
|
|
479
|
+
...(url.searchParams.get('download') === '1'
|
|
480
|
+
? { 'Content-Disposition': contentDisposition(path.basename(abs)) }
|
|
481
|
+
: {}),
|
|
250
482
|
});
|
|
251
483
|
createReadStream(abs).pipe(res);
|
|
252
484
|
return;
|
|
253
485
|
}
|
|
254
486
|
|
|
255
487
|
if (pathname === '/api/open') {
|
|
488
|
+
if (channel === 'mobile') {
|
|
489
|
+
// Launching a system app is a desktop-only action.
|
|
490
|
+
sendJson(res, 403, { error: 'not available from a paired device' });
|
|
491
|
+
return;
|
|
492
|
+
}
|
|
256
493
|
if (req.method !== 'POST') {
|
|
257
494
|
sendJson(res, 405, { error: 'method not allowed' });
|
|
258
495
|
return;
|
|
@@ -287,6 +524,48 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
|
|
|
287
524
|
return;
|
|
288
525
|
}
|
|
289
526
|
|
|
527
|
+
if (pathname === '/api/mobile' || pathname === '/api/mobile/lan' || pathname === '/api/mobile/tunnel') {
|
|
528
|
+
// The phone-access controls manage the host machine; loopback only.
|
|
529
|
+
if (channel !== 'local') {
|
|
530
|
+
sendJson(res, 403, { error: 'desktop only' });
|
|
531
|
+
return;
|
|
532
|
+
}
|
|
533
|
+
if (pathname === '/api/mobile') {
|
|
534
|
+
if (req.method !== 'GET') {
|
|
535
|
+
sendJson(res, 405, { error: 'method not allowed' });
|
|
536
|
+
return;
|
|
537
|
+
}
|
|
538
|
+
sendJson(res, 200, mobileStatus());
|
|
539
|
+
return;
|
|
540
|
+
}
|
|
541
|
+
if (req.method !== 'POST') {
|
|
542
|
+
sendJson(res, 405, { error: 'method not allowed' });
|
|
543
|
+
return;
|
|
544
|
+
}
|
|
545
|
+
let body;
|
|
546
|
+
try {
|
|
547
|
+
body = await readJsonBody(req);
|
|
548
|
+
} catch (err) {
|
|
549
|
+
sendJson(res, 400, { error: err.message });
|
|
550
|
+
return;
|
|
551
|
+
}
|
|
552
|
+
const enable = body.enabled === true;
|
|
553
|
+
try {
|
|
554
|
+
if (pathname === '/api/mobile/lan') {
|
|
555
|
+
if (enable) await enableLan();
|
|
556
|
+
else await disableLan();
|
|
557
|
+
} else {
|
|
558
|
+
if (enable) await startTunnel();
|
|
559
|
+
else await stopTunnel();
|
|
560
|
+
}
|
|
561
|
+
} catch (err) {
|
|
562
|
+
sendJson(res, 500, { error: err.message });
|
|
563
|
+
return;
|
|
564
|
+
}
|
|
565
|
+
sendJson(res, 200, mobileStatus());
|
|
566
|
+
return;
|
|
567
|
+
}
|
|
568
|
+
|
|
290
569
|
if (pathname === '/api/events') {
|
|
291
570
|
res.writeHead(200, {
|
|
292
571
|
'Content-Type': 'text/event-stream',
|
|
@@ -314,6 +593,222 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
|
|
|
314
593
|
if (!res.headersSent) sendJson(res, 500, { error: 'internal error' });
|
|
315
594
|
else res.end();
|
|
316
595
|
}
|
|
596
|
+
};
|
|
597
|
+
|
|
598
|
+
// ---- phone access --------------------------------------------------------
|
|
599
|
+
//
|
|
600
|
+
// A second listener (0.0.0.0, default port 9346) serves phones. Every
|
|
601
|
+
// request on it needs the pairing token; there is deliberately no loopback
|
|
602
|
+
// exemption because cloudflared's proxy also connects from 127.0.0.1.
|
|
603
|
+
let lanServer = null;
|
|
604
|
+
let lanHosts = new Set();
|
|
605
|
+
// The mobile listener may run for the tunnel alone. `lanAdvertised` tracks
|
|
606
|
+
// what the user actually asked for: Wi-Fi sharing (and its QR) is only
|
|
607
|
+
// reported when started explicitly, never as a side effect of the tunnel.
|
|
608
|
+
let lanAdvertised = false;
|
|
609
|
+
let listener = { running: false, port: null, urls: [] };
|
|
610
|
+
let tunnelState = { state: 'off', url: null, bytes: 0, total: null, error: null };
|
|
611
|
+
let tunnelStop = null;
|
|
612
|
+
let tunnelHost = null;
|
|
613
|
+
let tunnelGen = 0;
|
|
614
|
+
|
|
615
|
+
function mobileAllowedHost(header) {
|
|
616
|
+
if (!header) return false;
|
|
617
|
+
try {
|
|
618
|
+
const hostname = new URL('http://' + header).hostname.replace(/^\[|\]$/g, '').toLowerCase();
|
|
619
|
+
if (hostname === 'localhost' || hostname === '127.0.0.1' || hostname === '::1') return true;
|
|
620
|
+
if (tunnelHost && hostname === tunnelHost) return true;
|
|
621
|
+
return lanHosts.has(hostname);
|
|
622
|
+
} catch {
|
|
623
|
+
return false;
|
|
624
|
+
}
|
|
625
|
+
}
|
|
626
|
+
|
|
627
|
+
function handlePair(req, res, url) {
|
|
628
|
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
|
|
629
|
+
sendJson(res, 405, { error: 'method not allowed' });
|
|
630
|
+
return;
|
|
631
|
+
}
|
|
632
|
+
if (!tokenEquals(url.searchParams.get('t'))) {
|
|
633
|
+
sendJson(res, 403, { error: 'invalid access code' });
|
|
634
|
+
return;
|
|
635
|
+
}
|
|
636
|
+
res.writeHead(302, {
|
|
637
|
+
Location: '/',
|
|
638
|
+
'Set-Cookie': `${PAIR_COOKIE}=${token}; Path=/; HttpOnly; SameSite=Lax`,
|
|
639
|
+
'Cache-Control': 'no-store',
|
|
640
|
+
});
|
|
641
|
+
res.end();
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
function unauthenticated(res, pathname) {
|
|
645
|
+
if (pathname.startsWith('/api/')) {
|
|
646
|
+
sendJson(res, 401, { error: 'pairing required' });
|
|
647
|
+
} else {
|
|
648
|
+
res.writeHead(401, {
|
|
649
|
+
'Content-Type': 'text/html; charset=utf-8',
|
|
650
|
+
'Cache-Control': 'no-store',
|
|
651
|
+
});
|
|
652
|
+
res.end(PAIR_REQUIRED_PAGE);
|
|
653
|
+
}
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
const mobileGuard = (req, res) => {
|
|
657
|
+
if (!mobileAllowedHost(req.headers.host)) {
|
|
658
|
+
sendJson(res, 403, { error: 'forbidden host' });
|
|
659
|
+
return;
|
|
660
|
+
}
|
|
661
|
+
let url;
|
|
662
|
+
try {
|
|
663
|
+
url = new URL(req.url, 'http://127.0.0.1');
|
|
664
|
+
} catch {
|
|
665
|
+
sendJson(res, 400, { error: 'bad request' });
|
|
666
|
+
return;
|
|
667
|
+
}
|
|
668
|
+
if (url.pathname === '/pair') {
|
|
669
|
+
handlePair(req, res, url);
|
|
670
|
+
return;
|
|
671
|
+
}
|
|
672
|
+
if (!hasPairCookie(req)) {
|
|
673
|
+
unauthenticated(res, url.pathname);
|
|
674
|
+
return;
|
|
675
|
+
}
|
|
676
|
+
handle(req, res, 'mobile').catch(() => {
|
|
677
|
+
if (!res.headersSent) res.destroy();
|
|
678
|
+
});
|
|
679
|
+
};
|
|
680
|
+
|
|
681
|
+
function mobileStatus() {
|
|
682
|
+
const pair = (u) => `${u}/pair?t=${token}`;
|
|
683
|
+
return {
|
|
684
|
+
token,
|
|
685
|
+
lan: {
|
|
686
|
+
enabled: lanAdvertised,
|
|
687
|
+
port: listener.running ? listener.port : null,
|
|
688
|
+
urls: lanAdvertised ? listener.urls.map(pair) : [],
|
|
689
|
+
},
|
|
690
|
+
tunnel: {
|
|
691
|
+
state: tunnelState.state,
|
|
692
|
+
url: tunnelState.url ? pair(tunnelState.url) : null,
|
|
693
|
+
bytes: tunnelState.bytes,
|
|
694
|
+
total: tunnelState.total,
|
|
695
|
+
error: tunnelState.error,
|
|
696
|
+
},
|
|
697
|
+
};
|
|
698
|
+
}
|
|
699
|
+
|
|
700
|
+
// Bring the mobile listener up (idempotent). Silent by design: it is an
|
|
701
|
+
// implementation detail shared by Wi-Fi sharing and the tunnel.
|
|
702
|
+
async function startListener() {
|
|
703
|
+
if (listener.running) return;
|
|
704
|
+
const server = http.createServer(mobileGuard);
|
|
705
|
+
const actualPort = await listen(server, mobilePort, autoIncrementLimit, '0.0.0.0');
|
|
706
|
+
const addresses = lanIpv4Addresses();
|
|
707
|
+
lanServer = server;
|
|
708
|
+
lanHosts = new Set(addresses);
|
|
709
|
+
listener = {
|
|
710
|
+
running: true,
|
|
711
|
+
port: actualPort,
|
|
712
|
+
urls: addresses.map((ip) => `http://${ip}:${actualPort}`),
|
|
713
|
+
};
|
|
714
|
+
}
|
|
715
|
+
|
|
716
|
+
async function stopListener() {
|
|
717
|
+
listener = { running: false, port: null, urls: [] };
|
|
718
|
+
lanHosts = new Set();
|
|
719
|
+
const server = lanServer;
|
|
720
|
+
lanServer = null;
|
|
721
|
+
if (server) {
|
|
722
|
+
// Mobile clients may hold SSE streams open; end them so close() returns.
|
|
723
|
+
// Desktop clients transparently reconnect.
|
|
724
|
+
for (const res of sseClients) res.end();
|
|
725
|
+
server.close();
|
|
726
|
+
server.closeAllConnections?.();
|
|
727
|
+
}
|
|
728
|
+
}
|
|
729
|
+
|
|
730
|
+
async function enableLan() {
|
|
731
|
+
if (lanAdvertised) return;
|
|
732
|
+
await startListener();
|
|
733
|
+
lanAdvertised = true;
|
|
734
|
+
if (listener.urls.length === 0) {
|
|
735
|
+
console.warn('readingroom: no network address found — phones must use the tunnel');
|
|
736
|
+
} else {
|
|
737
|
+
console.log(`readingroom: phone access on — ${listener.urls[0]}/pair?t=${token}`);
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
async function disableLan() {
|
|
742
|
+
const wasAdvertised = lanAdvertised;
|
|
743
|
+
lanAdvertised = false;
|
|
744
|
+
// stopTunnel tears the listener down too when nothing else needs it.
|
|
745
|
+
await stopTunnel();
|
|
746
|
+
if (listener.running) await stopListener();
|
|
747
|
+
if (wasAdvertised) console.log('readingroom: phone access off');
|
|
748
|
+
}
|
|
749
|
+
|
|
750
|
+
function setTunnel(patch) {
|
|
751
|
+
tunnelState = { ...tunnelState, ...patch };
|
|
752
|
+
}
|
|
753
|
+
|
|
754
|
+
// Kicks the work off and returns; progress and errors land in the tunnel
|
|
755
|
+
// state that GET /api/mobile reports. The listener it needs comes up
|
|
756
|
+
// silently — Wi-Fi sharing is only reported when started explicitly.
|
|
757
|
+
async function startTunnel() {
|
|
758
|
+
await startListener();
|
|
759
|
+
if (tunnelState.state === 'on' || tunnelState.state === 'downloading' || tunnelState.state === 'starting') {
|
|
760
|
+
return;
|
|
761
|
+
}
|
|
762
|
+
const gen = ++tunnelGen;
|
|
763
|
+
setTunnel({ state: 'downloading', url: null, bytes: 0, total: null, error: null });
|
|
764
|
+
startTunnelImpl({
|
|
765
|
+
targetPort: listener.port,
|
|
766
|
+
onProgress: (p) => {
|
|
767
|
+
if (gen !== tunnelGen) return;
|
|
768
|
+
if (p.phase === 'downloading') setTunnel({ state: 'downloading', bytes: p.bytes, total: p.total });
|
|
769
|
+
else if (p.phase === 'starting') setTunnel({ state: 'starting' });
|
|
770
|
+
},
|
|
771
|
+
onUnexpectedExit: (message) => {
|
|
772
|
+
if (gen !== tunnelGen) return;
|
|
773
|
+
setTunnel({ state: 'error', url: null, error: message });
|
|
774
|
+
},
|
|
775
|
+
}).then(
|
|
776
|
+
({ url, host, stop }) => {
|
|
777
|
+
if (gen !== tunnelGen) {
|
|
778
|
+
stop();
|
|
779
|
+
return;
|
|
780
|
+
}
|
|
781
|
+
tunnelStop = stop;
|
|
782
|
+
tunnelHost = host;
|
|
783
|
+
setTunnel({ state: 'on', url, error: null });
|
|
784
|
+
console.log(`readingroom: tunnel ready — ${url}/pair?t=${token}`);
|
|
785
|
+
},
|
|
786
|
+
(err) => {
|
|
787
|
+
if (gen !== tunnelGen) return;
|
|
788
|
+
setTunnel({ state: 'error', error: err.message });
|
|
789
|
+
},
|
|
790
|
+
);
|
|
791
|
+
}
|
|
792
|
+
|
|
793
|
+
async function stopTunnel() {
|
|
794
|
+
tunnelGen += 1; // invalidate any in-flight start
|
|
795
|
+
tunnelHost = null;
|
|
796
|
+
const stop = tunnelStop;
|
|
797
|
+
tunnelStop = null;
|
|
798
|
+
setTunnel({ state: 'off', url: null, error: null, bytes: 0, total: null });
|
|
799
|
+
if (stop) await stop();
|
|
800
|
+
// If the listener only existed for the tunnel, bring the whole thing down.
|
|
801
|
+
if (!lanAdvertised && listener.running) await stopListener();
|
|
802
|
+
}
|
|
803
|
+
|
|
804
|
+
const server = http.createServer((req, res) => {
|
|
805
|
+
if (!loopbackHost(req.headers.host)) {
|
|
806
|
+
sendJson(res, 403, { error: 'forbidden host' });
|
|
807
|
+
return;
|
|
808
|
+
}
|
|
809
|
+
handle(req, res, 'local').catch(() => {
|
|
810
|
+
if (!res.headersSent) res.destroy();
|
|
811
|
+
});
|
|
317
812
|
});
|
|
318
813
|
|
|
319
814
|
const actualPort = await listen(server, port, autoIncrementLimit);
|
|
@@ -325,11 +820,25 @@ export async function startServer({ root, port = 9345, distDir, autoIncrementLim
|
|
|
325
820
|
root: rootAbs,
|
|
326
821
|
tree: () => cachedTree,
|
|
327
822
|
liveReload: watcher !== null,
|
|
823
|
+
mobile: {
|
|
824
|
+
status: mobileStatus,
|
|
825
|
+
enableLan,
|
|
826
|
+
disableLan,
|
|
827
|
+
startTunnel,
|
|
828
|
+
stopTunnel,
|
|
829
|
+
},
|
|
328
830
|
close() {
|
|
329
831
|
clearTimeout(rescanTimer);
|
|
330
832
|
clearInterval(heartbeat);
|
|
331
833
|
watcher?.close();
|
|
332
834
|
for (const res of sseClients) res.end();
|
|
835
|
+
if (lanServer) {
|
|
836
|
+
lanServer.close();
|
|
837
|
+
lanServer.closeAllConnections?.();
|
|
838
|
+
}
|
|
839
|
+
// stop() dispatches SIGTERM synchronously, so the child dies even if
|
|
840
|
+
// the process exits immediately after close().
|
|
841
|
+
tunnelStop?.();
|
|
333
842
|
server.close();
|
|
334
843
|
},
|
|
335
844
|
};
|