magpie-page-token-widget 0.1.0 → 0.2.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/lib/server.mjs CHANGED
@@ -3,16 +3,44 @@ import { timingSafeEqual } from 'node:crypto';
3
3
  import { readFile } from 'node:fs/promises';
4
4
  import path from 'node:path';
5
5
 
6
- import { Collector } from './collector.mjs';
6
+ import { Collector, REFRESH_STRATEGIES, refreshStrategy } from './collector.mjs';
7
7
  import { displayOptions } from './normalize.mjs';
8
- import { ensureState, notePairing, rotatePairing, writeState } from './state.mjs';
9
- import { detect } from './tailnet.mjs';
10
- import { applyForward, publishedFor, removeForward, serveState } from './forward.mjs';
8
+ import { sweepTemporaries } from './atomic.mjs';
9
+ import {
10
+ ensureState, notePairing, rotatePairing, writeState, pairingUsable,
11
+ addDevice, verifyToken, noteAccess, revokeDevice, renameDevice, deviceList, newToken, hashToken,
12
+ } from './state.mjs';
13
+ import { detect, interfaces, lanCandidates, ping } from './tailnet.mjs';
14
+ import { applyForward, publishedFor, removeForward, serveState, forwardRecord } from './forward.mjs';
11
15
  import { dataUri } from './qr.mjs';
12
16
 
13
17
  const PLUGIN = 'magpie-page-token-widget';
14
- const TOKEN_HEADER = 'x-token-widget-token';
18
+ // The name of the header the token travels in. The console of the computer
19
+ // and the phone both use it.
20
+ export const TOKEN_HEADER = 'x-token-widget-token';
15
21
  const LOCAL_HOSTS = new Set(['127.0.0.1', 'localhost', '::1']);
22
+ // Ten wrong codes from one computer, and then the door is shut for five
23
+ // minutes. The record of the attempts is short and is cleaned up.
24
+ const PAIR_ATTEMPTS = 10;
25
+ // The page of the pairing code is opened more often than the door itself: a
26
+ // phone that scans a code that has gone stale comes back here. It may be
27
+ // tried more often before the door is shut.
28
+ const PAIR_PAGE_ATTEMPTS = 30;
29
+ const PAIR_LOCK_MS = 5 * 60 * 1000;
30
+ const ATTEMPT_IDLE_MS = 15 * 60 * 1000;
31
+ const SESSION_CAP = 200;
32
+ // The whole service shares one bag of wrong tries. Counting per code alone
33
+ // would let anybody walk through as many codes as they like, one guess each,
34
+ // and never be told to stop. This budget puts a ceiling on the number of
35
+ // wrong tries in a window, no matter which code they were aimed at.
36
+ //
37
+ // A hundred wrong tries in five minutes is far above what an honest pair
38
+ // needs: a person who scans a code that has gone stale makes one or two.
39
+ const PAIR_BUDGET = 100;
40
+ const PAIR_BUDGET_MS = 5 * 60 * 1000;
41
+ // The state of the tailnet is looked at every five minutes, not every minute:
42
+ // the command of Tailscale is not free, and nobody waits for it.
43
+ const TAILNET_INTERVAL_MS = 5 * 60 * 1000;
16
44
 
17
45
  // Another Magpie on this computer may already serve this plugin on the port.
18
46
  // The health answer says which plugin it is, so two instances of the same
@@ -136,12 +164,20 @@ export async function startServer({ root, dataDir, magpieDir, options = {} }) {
136
164
  const snapshotFile = path.join(dataDir, 'snapshot.json');
137
165
 
138
166
  const { state } = await ensureState(stateFile);
167
+ // The temporary files of a run that was killed stay behind; they are litter
168
+ // and nothing ever reads them.
169
+ await sweepTemporaries(stateFile);
170
+ await sweepTemporaries(snapshotFile);
139
171
  const pluginSettings = options.settings || {};
172
+ // The tests bring their own Tailscale, so the real command of the machine
173
+ // is never touched while the tests run.
174
+ const runner = options.tailscaleRunner || null;
140
175
  const collector = new Collector({
141
176
  upstream,
142
177
  magpieDir,
143
178
  snapshotFile,
144
179
  display: displayOptions({ ...state.settings, ...pluginSettings }),
180
+ strategy: refreshStrategy(state.settings?.refreshStrategy),
145
181
  });
146
182
  await collector.load();
147
183
  void collector.refresh();
@@ -152,11 +188,14 @@ export async function startServer({ root, dataDir, magpieDir, options = {} }) {
152
188
  backendState: '',
153
189
  tailnetIP: '',
154
190
  dnsName: '',
191
+ path: 'unknown',
155
192
  ios: [],
156
193
  error: '正在检测 Tailscale…',
157
194
  };
158
195
  let forward = { ready: false, port, phonePort, error: '正在准备尾网转发…' };
159
196
  const sessions = new Map();
197
+ // The bag of wrong tries that the whole service shares.
198
+ const budget = { count: 0, until: 0 };
160
199
  let closed = false;
161
200
  // The console of this computer must not be reachable from the tailnet. It
162
201
  // stays shut until the forwarding is known to point at the phone side.
@@ -165,6 +204,13 @@ export async function startServer({ root, dataDir, magpieDir, options = {} }) {
165
204
 
166
205
  const serviceURL = () => (tailnet.tailnetIP ? `http://${tailnet.tailnetIP}:${port}` : '');
167
206
  const pairingURL = () => (serviceURL() ? `${serviceURL()}/p/${state.pairing.code}` : '');
207
+ // How long the pairing code is still good. The code is good for ten
208
+ // minutes, and it is good only once.
209
+ const pairingExpiresIn = () => {
210
+ const until = Date.parse(state.pairing.expiresAt || '');
211
+ if (!Number.isFinite(until)) return 0;
212
+ return Math.max(0, Math.round((until - Date.now()) / 1000));
213
+ };
168
214
 
169
215
  // The Host header is only a guard against a name that points at this
170
216
  // computer by accident. It says nothing about who is asking.
@@ -184,9 +230,24 @@ export async function startServer({ root, dataDir, magpieDir, options = {} }) {
184
230
  return '';
185
231
  };
186
232
 
187
- const authorized = (request) => {
233
+ // Two doors of their own. The console of this computer is opened by its own
234
+ // token; the phone is opened by the token of its own device. The old shared
235
+ // token stays the token of the legacy device, so the phones that were
236
+ // paired before keep working.
237
+ const phoneAuthorized = (request) => {
238
+ const device = verifyToken(state, readToken(request));
239
+ if (!device) return false;
240
+ // The time of the last visit is written down at most once every five
241
+ // minutes, so that a busy phone does not make the state file grow.
242
+ if (noteAccess(device, Date.now())) {
243
+ void writeState(stateFile, state).catch(() => {});
244
+ }
245
+ return true;
246
+ };
247
+
248
+ const consoleAuthorized = (request) => {
188
249
  const given = readToken(request);
189
- return Boolean(given) && same(given, state.token);
250
+ return Boolean(given) && same(given, state.consoleToken);
190
251
  };
191
252
 
192
253
  const consoleState = () => ({
@@ -197,6 +258,10 @@ export async function startServer({ root, dataDir, magpieDir, options = {} }) {
197
258
  serviceURL: serviceURL(),
198
259
  pairingURL: pairingURL(),
199
260
  pairingCode: state.pairing.code,
261
+ pairingExpiresAt: state.pairing.expiresAt || null,
262
+ pairingExpiresIn: pairingExpiresIn(),
263
+ // How long the door is still shut after too many wrong tries.
264
+ pairingBlocked: budget.until > Date.now() ? Math.ceil((budget.until - Date.now()) / 1000) : 0,
200
265
  token: state.token,
201
266
  qr: pairingURL() ? dataUri(pairingURL()) : '',
202
267
  tailnet: {
@@ -205,41 +270,79 @@ export async function startServer({ root, dataDir, magpieDir, options = {} }) {
205
270
  backendState: tailnet.backendState,
206
271
  tailnetIP: tailnet.tailnetIP,
207
272
  dnsName: tailnet.dnsName,
273
+ path: tailnet.path || 'unknown',
208
274
  ios: tailnet.ios,
209
275
  error: tailnet.error,
276
+ // The addresses of this computer are for the eyes of the person at the
277
+ // keyboard. They never go to the phone.
278
+ interfaces: interfaces(),
279
+ lan: lanCandidates(),
210
280
  },
211
281
  paired: state.paired,
212
- forward: { ready: forward.ready, port: forward.port, phonePort: forward.phonePort, error: forward.error },
282
+ devices: deviceList(state),
283
+ forward: {
284
+ ready: forward.ready,
285
+ port: forward.port,
286
+ phonePort: forward.phonePort,
287
+ error: forward.error,
288
+ owned: state.forward || null,
289
+ },
213
290
  display: collector.display,
214
- subscriptions: collector.overviewWith({ ...collector.display, subscriptions: ['*'] }).subscriptions,
291
+ refresh: {
292
+ strategy: collector.strategy,
293
+ label: REFRESH_STRATEGIES[collector.strategy]?.label || '',
294
+ options: Object.values(REFRESH_STRATEGIES).map(entry => ({ id: entry.id, label: entry.label })),
295
+ },
296
+ subscriptions: collector.allSubscriptions(),
215
297
  });
216
298
 
217
299
  // The forwarding of the published port has to point at the phone side. A
218
300
  // forwarding of an older version of this plugin points at the console of
219
- // this computer, and it is moved to the phone side as well.
301
+ // this computer, and it is moved to the phone side as well. A forwarding
302
+ // that belongs to somebody else is left alone.
220
303
  const settleForward = async () => {
221
304
  if (options.forward === false) {
222
305
  forward = { ready: false, port, phonePort, error: '这次没有建尾网转发,手机直接连尾网地址。' };
223
- consoleOpen = true;
306
+ // Even when no forwarding is wanted, the console of this computer must
307
+ // not be reachable from the tailnet. A rule that an older version left
308
+ // behind can still point the published port at the console, so the
309
+ // console stays shut as long as that is the case.
310
+ const status = await serveState(runner);
311
+ const existing = publishedFor(status, port);
312
+ const pointsAtConsole = existing && existing.TCPForward === `127.0.0.1:${port}`;
313
+ consoleOpen = !pointsAtConsole;
314
+ if (pointsAtConsole) {
315
+ forward = {
316
+ ...forward,
317
+ error: '尾网上还留着一条指向这台电脑控制台的转发,控制台先关着。把它删掉,或者打开转发让插件自己接管。',
318
+ };
319
+ }
224
320
  return;
225
321
  }
226
- const status = await serveState();
322
+ const status = await serveState(runner);
227
323
  const existing = publishedFor(status, port);
228
324
  consoleOpen = !existing || existing.TCPForward !== `127.0.0.1:${port}`;
229
325
  if (!phoneBound) {
230
326
  forward = { ready: false, port, phonePort, error: '手机那一侧的端口没有打开,手机暂时连不上。' };
231
327
  return;
232
328
  }
233
- const result = await applyForward(port, phonePort);
329
+ const result = await applyForward(port, phonePort, runner, state.forward);
234
330
  if (result?.ok) {
235
331
  forward = { ready: true, port, phonePort, error: '' };
236
332
  consoleOpen = true;
333
+ // The forwarding of this plugin is written down, so that the next start
334
+ // knows that it may take it away again.
335
+ const record = forwardRecord(port, phonePort, { legacy: Boolean(result.legacy) });
336
+ if (!state.forward || state.forward.target !== record.target || state.forward.publishedPort !== record.publishedPort) {
337
+ state.forward = record;
338
+ await writeState(stateFile, state).catch(() => {});
339
+ }
237
340
  return;
238
341
  }
239
342
  forward = { ready: false, port, phonePort, error: result?.error || '转发没有建好。' };
240
343
  // If the tailnet still points at the console of this computer, the console
241
344
  // stays shut.
242
- const after = await serveState();
345
+ const after = await serveState(runner);
243
346
  const now = publishedFor(after, port);
244
347
  consoleOpen = !now || now.TCPForward !== `127.0.0.1:${port}`;
245
348
  };
@@ -247,22 +350,30 @@ export async function startServer({ root, dataDir, magpieDir, options = {} }) {
247
350
  // Is the published port already taken by a forwarding of Tailscale? Then
248
351
  // Tailscale itself holds the tailnet address of that port.
249
352
  const portPublished = async () => {
250
- const status = await serveState();
353
+ const status = await serveState(runner);
251
354
  return Boolean(publishedFor(status, port));
252
355
  };
253
356
 
254
- const servePairPage = async (response, code) => {
255
- const usable = Boolean(code) && code === state.pairing.code;
357
+ const servePairPage = async (response, code, request) => {
358
+ // The page of the pairing code is a door as well: it says whether a code
359
+ // is good. It goes through the same limiter, only with more room, so that
360
+ // a phone that scans a code which has gone stale is not shut out.
361
+ const guard = pairingGuard(request, code, PAIR_PAGE_ATTEMPTS, 'page');
362
+ const usable = guard.ok;
256
363
  const content = usable
257
364
  ? `<h1>装好 iPhone 额度组件</h1>
258
- <p class="lead">这个配对码只能用一次。它换来的是一台只读的令牌,手机用它去读用量。</p>
365
+ <p class="lead">这个配对码只能用一次,十分钟后也会作废。它换来的是一台只读的令牌,手机用它去读用量。</p>
259
366
  <p><a class="button" href="/scriptable/UsageWidget.js?code=${encodeURIComponent(code)}">下载组件脚本</a></p>
260
367
  <p class="note">脚本里没有你的密钥:它只带一个一次性配对码,跑一次就换成只读令牌。</p>
261
368
  <p class="note">下载完之后,在「文件」里找到它,用 Scriptable 打开,再按提示装到桌面。</p>`
262
- : `<h1>这个配对码已经失效</h1>
263
- <p class="lead">它只能用一次,而且已经用掉了。</p>
369
+ : guard.locked
370
+ ? `<h1>试得太多了</h1>
371
+ <p class="lead">这台电脑试了很多次配对码,先歇五分钟再来。</p>
372
+ <p class="note">回到电脑上的插件页面,重新生成一个配对码再扫一次。</p>`
373
+ : `<h1>这个配对码已经失效</h1>
374
+ <p class="lead">它只能用一次,十分钟后也会作废。</p>
264
375
  <p class="note">回到电脑上的插件页面,重新生成一个配对码再扫一次。</p>`;
265
- response.writeHead(usable ? 200 : 410, {
376
+ response.writeHead(usable ? 200 : (guard.locked ? 429 : 410), {
266
377
  'Content-Type': 'text/html; charset=utf-8',
267
378
  'Content-Security-Policy': "default-src 'none'; style-src 'unsafe-inline'; base-uri 'none'; form-action 'none'",
268
379
  'Cache-Control': 'no-store',
@@ -275,8 +386,19 @@ export async function startServer({ root, dataDir, magpieDir, options = {} }) {
275
386
  // pairing page. A phone that installs it by hand already knows the token,
276
387
  // so the token alone is enough to get the same script.
277
388
  const serveWidget = async (response, code, request) => {
278
- const paired = code && code === state.pairing.code;
279
- if (!paired && !authorized(request)) {
389
+ // A code that comes with the request is a door as well: the answer says
390
+ // whether it opens. It goes through the same limiter as the pairing
391
+ // itself, so nobody can ask as often as they like.
392
+ let paired = false;
393
+ if (code) {
394
+ const guard = pairingGuard(request, code, PAIR_ATTEMPTS, 'widget');
395
+ if (guard.ok) {
396
+ paired = true;
397
+ } else if (!phoneAuthorized(request)) {
398
+ return json(response, guard.status, { error: guard.error });
399
+ }
400
+ }
401
+ if (!paired && !phoneAuthorized(request)) {
280
402
  return json(response, 403, { error: '这个配对码已经失效。' });
281
403
  }
282
404
  let source;
@@ -300,6 +422,26 @@ export async function startServer({ root, dataDir, magpieDir, options = {} }) {
300
422
  response.end(body);
301
423
  };
302
424
 
425
+ // The page of the phone. It carries no token: the phone brings its own in
426
+ // the address, and the page drops it as soon as it has read it.
427
+ const phoneCsp =
428
+ "default-src 'none'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; base-uri 'none'; form-action 'none'";
429
+
430
+ const serveMobile = async (response, name, type) => {
431
+ try {
432
+ const body = await readFile(path.join(root, 'mobile', name), 'utf8');
433
+ response.writeHead(200, {
434
+ 'Content-Type': type,
435
+ 'Content-Security-Policy': phoneCsp,
436
+ 'Cache-Control': 'no-store',
437
+ 'X-Content-Type-Options': 'nosniff',
438
+ });
439
+ response.end(body);
440
+ } catch {
441
+ text(response, 404, 'Not found');
442
+ }
443
+ };
444
+
303
445
  const serveUi = async (response, name, type, port) => {
304
446
  try {
305
447
  const body = await readFile(path.join(root, 'ui', name), 'utf8');
@@ -315,6 +457,87 @@ export async function startServer({ root, dataDir, magpieDir, options = {} }) {
315
457
  }
316
458
  };
317
459
 
460
+ // The records of the failed attempts are few: the old ones are cleaned up
461
+ // and the list never grows past its cap.
462
+ const cleanSessions = () => {
463
+ const now = Date.now();
464
+ // The bag of wrong tries empties itself when its window is over.
465
+ if (budget.until && budget.until <= now) {
466
+ budget.until = 0;
467
+ budget.count = 0;
468
+ }
469
+ for (const [key, value] of sessions) {
470
+ // A record that is not locked goes away on its own after a while, so
471
+ // that a code nobody tries again does not stay in the memory.
472
+ const idle = !value.until && value.last && now - value.last > ATTEMPT_IDLE_MS;
473
+ if ((value.until && value.until <= now) || idle) sessions.delete(key);
474
+ }
475
+ while (sessions.size > SESSION_CAP) {
476
+ const oldest = sessions.keys().next();
477
+ if (oldest.done) break;
478
+ sessions.delete(oldest.value);
479
+ }
480
+ };
481
+
482
+ // Every way of trying a pairing code goes through this door.
483
+ //
484
+ // Two things keep the guessing small.
485
+ //
486
+ // The first is the bag of wrong tries that the whole service shares: a
487
+ // hundred wrong tries in five minutes and the door is shut for everybody
488
+ // until the bag is emptied. It is looked at before the code itself, so a
489
+ // wrong code cannot be tested faster than the bag allows. The person at the
490
+ // computer can empty the bag at once by asking for a new pairing code.
491
+ //
492
+ // The second is the record that follows the CODE and not the computer that
493
+ // tries it. That matters behind the forwarding of Tailscale: tailscaled
494
+ // itself dials the loopback, so every phone of the tailnet arrives as
495
+ // 127.0.0.1. Counting per address there would let one peer shut the
496
+ // pairing of everybody else.
497
+ //
498
+ // What actually makes a code hard to guess is neither of those: a code is
499
+ // ninety-six bits of randomness, it lives ten minutes and it opens the door
500
+ // once. The two doors above only keep the noise down and stop anybody from
501
+ // leaning on the service.
502
+ //
503
+ // The address in the header of the request is not believed either, anybody
504
+ // can write it.
505
+ //
506
+ // It answers with { ok: true } when the code opens the door, and with
507
+ // { ok: false, status, error } when it does not.
508
+ const pairingGuard = (request, code, limit = PAIR_ATTEMPTS, kind = 'session') => {
509
+ const address = request.socket?.remoteAddress || 'unknown';
510
+ const now = Date.now();
511
+ if (budget.until > now) {
512
+ return { ok: false, status: 429, error: 'Too many attempts. Try again later.', locked: true };
513
+ }
514
+ // The code itself is a secret, so only its hash is written down.
515
+ const key = `${kind}|${hashToken(String(code || ''))}`;
516
+ const attempts = sessions.get(key) || { count: 0, until: 0, last: 0 };
517
+ if (attempts.until > now) {
518
+ return { ok: false, status: 429, error: 'Too many attempts. Try again later.', locked: true };
519
+ }
520
+ if (pairingUsable(state, code, now)) {
521
+ sessions.delete(key);
522
+ return { ok: true, address };
523
+ }
524
+ attempts.count += 1;
525
+ attempts.last = now;
526
+ if (attempts.count >= limit) {
527
+ attempts.until = now + PAIR_LOCK_MS;
528
+ attempts.count = 0;
529
+ }
530
+ sessions.set(key, attempts);
531
+ // The wrong try also goes into the bag that the whole service shares.
532
+ budget.count += 1;
533
+ if (budget.count >= PAIR_BUDGET) {
534
+ budget.count = 0;
535
+ budget.until = now + PAIR_BUDGET_MS;
536
+ }
537
+ cleanSessions();
538
+ return { ok: false, status: 403, error: 'That pairing code is not valid.' };
539
+ };
540
+
318
541
  // The scope comes from the socket the request came in on. The console of
319
542
  // this computer listens on the loopback address of the published port, the
320
543
  // phone side listens on a port of its own.
@@ -364,14 +587,20 @@ export async function startServer({ root, dataDir, magpieDir, options = {} }) {
364
587
  });
365
588
  return response.end();
366
589
  }
367
- if (!authorized(request)) {
590
+ if (!consoleAuthorized(request)) {
368
591
  return json(response, 403, { error: 'Reopen the page to reconnect.', code: 'reconnect' }, allowOrigin);
369
592
  }
370
593
  if (pathname === '/api/v1/console/state' && method === 'GET') {
594
+ // Somebody is at the computer: the reading keeps its rhythm.
595
+ collector.noteActivity();
371
596
  return json(response, 200, consoleState(), allowOrigin);
372
597
  }
373
598
  if (pathname === '/api/v1/console/pair' && method === 'POST') {
374
599
  rotatePairing(state);
600
+ // A new code empties the bag of wrong tries as well, so the person at
601
+ // the keyboard can open the door again at once.
602
+ budget.count = 0;
603
+ budget.until = 0;
375
604
  await writeState(stateFile, state);
376
605
  return json(response, 200, consoleState(), allowOrigin);
377
606
  }
@@ -380,40 +609,87 @@ export async function startServer({ root, dataDir, magpieDir, options = {} }) {
380
609
  if (!body) return json(response, 400, { error: 'Bad request.' }, allowOrigin);
381
610
  const next = displayOptions({ ...state.settings, ...body });
382
611
  state.settings = { ...state.settings, ...next };
612
+ if (body.refreshStrategy !== undefined) {
613
+ state.settings.refreshStrategy = refreshStrategy(body.refreshStrategy);
614
+ }
383
615
  await writeState(stateFile, state);
384
- collector.display = displayOptions({ ...state.settings, ...pluginSettings });
385
- return json(response, 200, { display: collector.display }, allowOrigin);
616
+ collector.setDisplay(displayOptions({ ...state.settings, ...pluginSettings }));
617
+ // The rhythm of the reading changes at once. The service does not have
618
+ // to be started again for that.
619
+ collector.setStrategy(state.settings.refreshStrategy);
620
+ return json(response, 200, { display: collector.display, refresh: consoleState().refresh }, allowOrigin);
621
+ }
622
+ if (pathname === '/api/v1/console/device' && method === 'POST') {
623
+ const body = await jsonBody(request);
624
+ if (!body) return json(response, 400, { error: 'Bad request.' }, allowOrigin);
625
+ if (body.action === 'create') {
626
+ // A token made by hand, for a phone that cannot read the QR code.
627
+ // It is written out once, and only its hash is kept.
628
+ const token = newToken();
629
+ const device = addDevice(state, { name: body.name, token });
630
+ await writeState(stateFile, state);
631
+ return json(response, 200, { devices: deviceList(state), device: { id: device.id, name: device.name }, token }, allowOrigin);
632
+ }
633
+ if (typeof body.id !== 'string') return json(response, 400, { error: 'Bad request.' }, allowOrigin);
634
+ const changed = body.action === 'rename'
635
+ ? renameDevice(state, body.id, body.name)
636
+ : revokeDevice(state, body.id);
637
+ if (!changed) return json(response, 404, { error: 'Not found.' }, allowOrigin);
638
+ await writeState(stateFile, state);
639
+ return json(response, 200, { devices: deviceList(state) }, allowOrigin);
640
+ }
641
+ if (pathname === '/api/v1/console/diagnose' && method === 'POST') {
642
+ const body = (await jsonBody(request)) || {};
643
+ // The person at the keyboard asked for it, so Tailscale is asked now
644
+ // and not once a minute for nothing.
645
+ tailnet = await detect(runner);
646
+ const target = typeof body.target === 'string' ? body.target : (tailnet.ios?.[0]?.ips?.[0] || '');
647
+ // The target goes to the command of Tailscale. Only an address or a
648
+ // plain name is allowed, so that nothing else can ride along.
649
+ const safeTarget = /^[A-Za-z0-9.:_-]{1,64}$/.test(target) ? target : '';
650
+ const result = safeTarget
651
+ ? await ping(safeTarget, runner)
652
+ : { ok: false, stdout: '', path: 'unknown', error: safeTarget ? '没有可诊断的地址。' : '这个地址不能用来诊断。' };
653
+ return json(response, 200, {
654
+ tailnet: consoleState().tailnet,
655
+ ping: {
656
+ target: safeTarget,
657
+ ok: Boolean(result.ok),
658
+ path: result.path || 'unknown',
659
+ error: result.error || null,
660
+ output: String(result.stdout || '').slice(0, 2000),
661
+ },
662
+ }, allowOrigin);
386
663
  }
387
664
  return json(response, 404, { error: 'Not found.' }, allowOrigin);
388
665
  }
389
666
 
390
667
  if (pathname === '/api/v1/overview' && method === 'GET') {
391
- if (!authorized(request)) return json(response, 401, { error: 'Unauthorized' });
392
- return json(response, 200, collector.overview());
668
+ if (!phoneAuthorized(request)) return json(response, 401, { error: 'Unauthorized' });
669
+ // A phone that asks while the reading is being refreshed waits for it a
670
+ // little. When the wait is over the old numbers go out, marked stale.
671
+ return json(response, 200, await collector.ensureFresh());
393
672
  }
394
673
 
395
674
  if (pathname === '/api/v1/session' && method === 'POST') {
396
675
  const body = await jsonBody(request);
397
676
  if (!body || typeof body.code !== 'string') return json(response, 400, { error: 'Bad request.' });
398
- const key = `${request.socket?.remoteAddress || 'unknown'}|${body.code}`;
399
- const attempts = sessions.get(key) || { count: 0, until: 0 };
400
- if (attempts.until > Date.now()) {
401
- return json(response, 429, { error: 'Too many attempts. Try again later.' });
402
- }
403
- if (body.code !== state.pairing.code) {
404
- attempts.count += 1;
405
- if (attempts.count >= 10) {
406
- attempts.until = Date.now() + 5 * 60 * 1000;
407
- attempts.count = 0;
408
- }
409
- sessions.set(key, attempts);
410
- return json(response, 403, { error: 'That pairing code is not valid.' });
411
- }
412
- sessions.delete(key);
677
+ const guard = pairingGuard(request, body.code);
678
+ if (!guard.ok) return json(response, guard.status, { error: guard.error });
679
+ // The code is used once: it is changed at once, so it never opens the
680
+ // door a second time.
413
681
  rotatePairing(state);
414
- notePairing(state, request.socket?.remoteAddress || 'unknown');
682
+ // Every phone gets a token of its own. Only the hash of it is kept; the
683
+ // token itself goes out once, with this answer.
684
+ const token = newToken();
685
+ const device = addDevice(state, { name: body.name, token });
686
+ notePairing(state, guard.address, device.name);
415
687
  await writeState(stateFile, state);
416
- return json(response, 200, { token: state.token, baseURL: serviceURL() });
688
+ return json(response, 200, {
689
+ token,
690
+ device: { id: device.id, name: device.name },
691
+ baseURL: serviceURL(),
692
+ });
417
693
  }
418
694
 
419
695
  if (pathname === '/scriptable/UsageWidget.js' && method === 'GET') {
@@ -437,10 +713,28 @@ export async function startServer({ root, dataDir, magpieDir, options = {} }) {
437
713
  }
438
714
 
439
715
  if (pathname.startsWith('/p/') && method === 'GET') {
440
- return servePairPage(response, decodeURIComponent(pathname.slice('/p/'.length)));
716
+ let code = '';
717
+ try {
718
+ code = decodeURIComponent(pathname.slice('/p/'.length));
719
+ } catch {
720
+ return json(response, 400, { error: 'Bad request.' });
721
+ }
722
+ return servePairPage(response, code, request);
441
723
  }
442
724
 
443
725
  if (!consoleScope) {
726
+ // The phone opens the page of the phone here. It carries no token: the
727
+ // phone brings its own in the address and drops it as soon as it has
728
+ // read it.
729
+ if ((pathname === '/' || pathname === '/index.html') && method === 'GET') {
730
+ return serveMobile(response, 'index.html', 'text/html; charset=utf-8');
731
+ }
732
+ if (pathname === '/app.js' && method === 'GET') {
733
+ return serveMobile(response, 'app.js', 'text/javascript; charset=utf-8');
734
+ }
735
+ if (pathname === '/style.css' && method === 'GET') {
736
+ return serveMobile(response, 'style.css', 'text/css; charset=utf-8');
737
+ }
444
738
  return json(response, 403, { error: 'This page is only opened on the computer of the service.' });
445
739
  }
446
740
  if (!consoleOpen) {
@@ -448,8 +742,8 @@ export async function startServer({ root, dataDir, magpieDir, options = {} }) {
448
742
  }
449
743
 
450
744
  if ((pathname === '/' || pathname === '/index.html') && method === 'GET') {
451
- // The page carries the read-only token. Only a navigation may read it,
452
- // so a page on another site cannot fetch it and take the token.
745
+ // The page carries the token of the console. Only a navigation may read
746
+ // it, so a page on another site cannot fetch it and take the token.
453
747
  const mode = request.headers['sec-fetch-mode'];
454
748
  if (mode && mode !== 'navigate') {
455
749
  return json(response, 403, { error: 'Open this page by hand, not from another page.' });
@@ -460,7 +754,7 @@ export async function startServer({ root, dataDir, magpieDir, options = {} }) {
460
754
  } catch {
461
755
  return text(response, 404, 'Not found');
462
756
  }
463
- body = body.replace('__SERVICE_TOKEN__', state.token);
757
+ body = body.replace('__SERVICE_TOKEN__', state.consoleToken);
464
758
  body = body.replace('__THEME__', url.searchParams.get('theme') === 'dark' ? 'dark' : 'light');
465
759
  response.writeHead(200, {
466
760
  'Content-Type': 'text/html; charset=utf-8',
@@ -539,7 +833,7 @@ export async function startServer({ root, dataDir, magpieDir, options = {} }) {
539
833
 
540
834
  const background = async () => {
541
835
  if (closed) return;
542
- tailnet = await detect();
836
+ tailnet = await detect(runner);
543
837
  if (closed) return;
544
838
  await settleForward();
545
839
  if (closed) return;
@@ -552,30 +846,53 @@ export async function startServer({ root, dataDir, magpieDir, options = {} }) {
552
846
  };
553
847
  void background();
554
848
 
555
- timers.push(
556
- setInterval(() => {
557
- void collector.refresh();
558
- }, 60_000),
559
- );
849
+ // The rhythm of the reading is kept by the collector itself: it knows when
850
+ // somebody is looking and when nobody is.
851
+ collector.start();
560
852
 
853
+ // The state of the tailnet is looked at every five minutes, and not once a
854
+ // minute for nothing: the command of Tailscale is not free. When it fails,
855
+ // it is asked less often still.
856
+ let tailnetFailures = 0;
857
+ let tailnetPatience = 0;
561
858
  timers.push(
562
859
  setInterval(() => {
563
860
  void (async () => {
564
861
  if (closed) return;
565
- tailnet = await detect();
862
+ if (tailnetPatience > 0) {
863
+ tailnetPatience -= 1;
864
+ return;
865
+ }
866
+ const fresh = await detect(runner);
566
867
  if (closed) return;
868
+ tailnet = fresh;
869
+ if (fresh.error) {
870
+ tailnetFailures += 1;
871
+ if (tailnetFailures >= 3) tailnetPatience = 2;
872
+ return;
873
+ }
874
+ tailnetFailures = 0;
567
875
  await settleForward();
568
876
  })();
569
- }, 60_000),
877
+ }, TAILNET_INTERVAL_MS),
570
878
  );
571
879
 
572
880
  return {
573
881
  port,
574
882
  phonePort,
883
+ // The collector is handed out so that the tests may look at it. Nothing
884
+ // outside this file uses it.
885
+ collector,
575
886
  async close() {
576
887
  closed = true;
577
888
  for (const timer of timers) clearInterval(timer);
578
- await removeForward(port, phonePort);
889
+ // The timer of the reading stops at once, and the reading that is still
890
+ // on its way is waited for, so that it does not write the snapshot
891
+ // after the service has gone.
892
+ const stopping = collector.stop();
893
+ // Only the forwarding that belongs to this plugin is taken away.
894
+ await removeForward(port, phonePort, runner, state.forward);
895
+ await stopping;
579
896
  await new Promise((resolve) => server.close(resolve));
580
897
  await new Promise((resolve) => phoneServer.close(resolve));
581
898
  await new Promise((resolve) => tailnetListener.close(resolve));