@pi-chamber/web 1.0.5-rc.1 → 1.0.5-rc.2

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.
Files changed (52) hide show
  1. package/dist/assets/{DiagramView-D-OSWTbO.js → DiagramView-BWG8peHt.js} +1 -1
  2. package/dist/assets/{DiffView-BKT-MIH4.js → DiffView-C_uRNQMT.js} +1 -1
  3. package/dist/assets/{FileSaveConflictDialog-DBkVFssC.js → FileSaveConflictDialog-DlH8IWDL.js} +1 -1
  4. package/dist/assets/{FilesView-B7GIuRlh.js → FilesView-RnF9JBPu.js} +1 -1
  5. package/dist/assets/{GitHubDetailScaffold-C9rCZMUT.js → GitHubDetailScaffold-BTRvUnwh.js} +1 -1
  6. package/dist/assets/{GitHubLinkPicker-Bm09hvhJ.js → GitHubLinkPicker-CGi8p2zF.js} +1 -1
  7. package/dist/assets/{GitHubListPrimitives-DlhAlxI6.js → GitHubListPrimitives-XckcmdeA.js} +1 -1
  8. package/dist/assets/{GitView-BgqdMb0m.js → GitView-DyPJ8Oay.js} +3 -3
  9. package/dist/assets/{IssuesSurface-BZXAvt49.js → IssuesSurface-rQ78ziEu.js} +1 -1
  10. package/dist/assets/{JsonTreeView-BKgCQjh_.js → JsonTreeView-Cy5NKUzx.js} +1 -1
  11. package/dist/assets/{MarkdownRendererImpl-BdcyMPw-.js → MarkdownRendererImpl-C5AlnAbG.js} +1 -1
  12. package/dist/assets/{PatchDiff-2MmWXcGe.js → PatchDiff-D6048My1.js} +1 -1
  13. package/dist/assets/{PierreDiffViewer-D1F2WvD0.js → PierreDiffViewer-_000TWrM.js} +1 -1
  14. package/dist/assets/{PullRequestsSurface-CN2z3DFv.js → PullRequestsSurface-eACi4Yxm.js} +2 -2
  15. package/dist/assets/{SessionSwitcherContent-CCljxAZb.js → SessionSwitcherContent-CFMjBIfH.js} +1 -1
  16. package/dist/assets/{SessionSwitcherDropdown-DtNt3qw4.js → SessionSwitcherDropdown-CINW_ydZ.js} +2 -2
  17. package/dist/assets/{SessionUnreadDot-B9bHMy5q.js → SessionUnreadDot-YZJi4IFP.js} +1 -1
  18. package/dist/assets/{SettingsView-DaZVCInW.js → SettingsView-DBiQXIji.js} +3 -3
  19. package/dist/assets/{SettingsWindow-C-ydfopH.js → SettingsWindow-Wvd56oG1.js} +1 -1
  20. package/dist/assets/{ToolOutputDialog-DJUAx_Oj.js → ToolOutputDialog-DeDXQNWw.js} +1 -1
  21. package/dist/assets/{ToolPartDiffPreview-DFyuJM4c.js → ToolPartDiffPreview-DuN8fldE.js} +1 -1
  22. package/dist/assets/{VirtualizedFileDiff-BS-af6rn.js → VirtualizedFileDiff-BYVjUxk9.js} +1 -1
  23. package/dist/assets/{computeVirtualFileMetrics-BI6wORhM.js → computeVirtualFileMetrics-E4gJTgVF.js} +1 -1
  24. package/dist/assets/{contextFileOpenGuard-DUMSGR4M.js → contextFileOpenGuard-CcGZtZsz.js} +1 -1
  25. package/dist/assets/{gitStatusPredicates-FdKYDZe3.js → gitStatusPredicates-C2H7tf7t.js} +1 -1
  26. package/dist/assets/{githubLink-B3-BaGpb.js → githubLink-DTEEkgAl.js} +1 -1
  27. package/dist/assets/{index-Df-vmvzu.js → index-BKc_DF05.js} +1 -1
  28. package/dist/assets/{main-q43jqZ2I.js → main-BNoO2jRw.js} +4 -4
  29. package/dist/assets/{main-61_cd7S7.js → main-DnCR4Jva.js} +2 -2
  30. package/dist/assets/{markdownCore-CqHYlXi_.js → markdownCore-CP1hsIRw.js} +1 -1
  31. package/dist/assets/{miniChat-vOuWN5pV.js → miniChat-BBI_B4OS.js} +2 -2
  32. package/dist/assets/{mobile-mrXWV5ky.js → mobile-dRWyYBgl.js} +2 -2
  33. package/dist/assets/{pi-session-focus-preference-BEufpwC6.js → pi-session-focus-preference-Cw78V7mw.js} +1 -1
  34. package/dist/assets/{renderDiffWithHighlighter-BD9CAhZU.js → renderDiffWithHighlighter-kdzNWs8-.js} +1 -1
  35. package/dist/assets/{renderElectronMiniChatApp-QQFXkY5Y.js → renderElectronMiniChatApp-uVOQvccp.js} +2 -2
  36. package/dist/assets/{renderFileWithHighlighter-KiEWMtzI.js → renderFileWithHighlighter-BdeYSXwS.js} +1 -1
  37. package/dist/assets/{renderMobileApp-DIZYvrhi.js → renderMobileApp-Cdg1IAhJ.js} +3 -3
  38. package/dist/assets/{runtimeEndpointReset-BA2uP2rj.js → runtimeEndpointReset-thviM404.js} +4 -4
  39. package/dist/assets/{useAppFontEffects-Bfw_d5eB.js → useAppFontEffects-Bd0btzjJ.js} +6 -6
  40. package/dist/assets/{useFilesViewSearch-Budwejnx.js → useFilesViewSearch-Yvk43YOy.js} +1 -1
  41. package/dist/assets/{useGitHubRemoteSearch-gUdylYy3.js → useGitHubRemoteSearch-BUjSEnXC.js} +1 -1
  42. package/dist/assets/{useSwitcherItems-yHSMduoo.js → useSwitcherItems-D2opwbRZ.js} +1 -1
  43. package/dist/assets/{web-components-CeHLxvED.js → web-components-BeROQeen.js} +1 -1
  44. package/dist/index.html +1 -1
  45. package/dist/mini-chat.html +1 -1
  46. package/dist/mobile.html +1 -1
  47. package/package.json +1 -1
  48. package/server/index.js +4 -1
  49. package/server/lib/tailscale/DOCUMENTATION.md +26 -5
  50. package/server/lib/tailscale/nc-probe.js +220 -0
  51. package/server/lib/tailscale/service.js +57 -4
  52. package/server/lib/tailscale/tailscale.test.js +219 -0
@@ -0,0 +1,220 @@
1
+ /**
2
+ * Tailnet-path health probe for the Tailscale self-check.
3
+ *
4
+ * Some hosts cannot reach their own MagicDNS name over the normal network
5
+ * path — containers/LXC running tailscaled with `--tun=userspace-networking`
6
+ * have no `tailscale0` interface, and host resolvers may not use MagicDNS —
7
+ * so a direct `fetch()` of `<url>/health` throws (DNS/connect error) even
8
+ * though the `tailscale serve`/`funnel` mapping works fine for tailnet
9
+ * peers. The state would sit at `starting` for the full retry budget and
10
+ * then report `probe_failed` for a mapping that was fine all along.
11
+ *
12
+ * This module tunnels the same credential-free `GET /health` check through
13
+ * the tailscale CLI instead: it spawns `tailscale nc <host> <port>` and runs
14
+ * a real TLS handshake over the child's stdio (wrapped as a Duplex via
15
+ * `stream.Duplex.from`) and sends the request with `node:http` over that
16
+ * TLS socket, so Node parses HTTP (including chunked encoding)
17
+ * and verifies the serve certificate exactly like a normal HTTPS request.
18
+ * Certificate verification stays ON — the serve cert is a valid Let's
19
+ * Encrypt cert for the ts.net name — and no Authorization header or cookie
20
+ * is ever sent.
21
+ *
22
+ * Factory: `createTailscaleNcHealthFetch({ executable, spawnFn })` returns
23
+ * `fetchHealth({ host, port, timeoutMs, signal })`, which never throws: every
24
+ * failure (spawn error, timeout, abort, TLS/HTTP error, oversized or
25
+ * non-JSON body) resolves to `{ ok: false, status: null, body: null,
26
+ * error }`. Success resolves to `{ ok: true, status, body }` where `status`
27
+ * is the HTTP status code and `body` is the parsed JSON (or null when the
28
+ * body is not JSON — callers must still check the status and the server
29
+ * identity themselves). Completion, timeout, abort, and error paths always
30
+ * kill the child and destroy the sockets. Response bodies are capped at
31
+ * 64 KiB (the remainder is drained and dropped).
32
+ */
33
+
34
+ import { spawn } from 'node:child_process';
35
+ import { request as httpRequest } from 'node:http';
36
+ import tls from 'node:tls';
37
+ import { Duplex } from 'node:stream';
38
+
39
+ import { TAILSCALE_PROBE_TIMEOUT_MS } from './tailscale.js';
40
+
41
+ // `/health` is a few hundred bytes; cap well above that so a rogue handler
42
+ // piping unbounded output through the serve mapping cannot grow memory.
43
+ const NC_PROBE_MAX_BODY_BYTES = 64 * 1024;
44
+
45
+ export const createTailscaleNcHealthFetch = ({ executable, spawnFn = spawn } = {}) => {
46
+ if (typeof executable !== 'string' || executable.length === 0) {
47
+ throw new Error('createTailscaleNcHealthFetch requires an executable path or command');
48
+ }
49
+ if (typeof spawnFn !== 'function') {
50
+ throw new Error('createTailscaleNcHealthFetch requires a spawn function');
51
+ }
52
+
53
+ const fail = (error) => ({ ok: false, status: null, body: null, error });
54
+
55
+ return async ({ host, port, timeoutMs = TAILSCALE_PROBE_TIMEOUT_MS, signal } = {}) => {
56
+ if (typeof host !== 'string' || host.length === 0 || !Number.isInteger(port) || port <= 0 || port > 65535) {
57
+ return fail('invalid-target');
58
+ }
59
+ if (signal?.aborted) return fail('aborted');
60
+ const effectiveTimeoutMs = Number.isFinite(timeoutMs) && timeoutMs > 0 ? timeoutMs : TAILSCALE_PROBE_TIMEOUT_MS;
61
+
62
+ let child = null;
63
+ try {
64
+ child = spawnFn(executable, ['nc', host, String(port)], {
65
+ windowsHide: true,
66
+ stdio: ['pipe', 'pipe', 'ignore'],
67
+ shell: false,
68
+ });
69
+ } catch {
70
+ return fail('spawn');
71
+ }
72
+ if (!child || !child.stdout || !child.stdin) {
73
+ try {
74
+ child?.kill?.('SIGKILL');
75
+ } catch {
76
+ }
77
+ return fail('spawn');
78
+ }
79
+
80
+ let tunnel = null;
81
+ try {
82
+ tunnel = Duplex.from({ readable: child.stdout, writable: child.stdin });
83
+ } catch {
84
+ try {
85
+ child.kill('SIGKILL');
86
+ } catch {
87
+ }
88
+ return fail('spawn');
89
+ }
90
+ // Stray stream errors after teardown are expected (e.g. destroying the
91
+ // tunnel aborts the in-flight handshake): every outcome is reported via
92
+ // `done`, never via unhandled stream errors.
93
+ tunnel.on('error', () => {});
94
+
95
+ try {
96
+ return await new Promise((resolve) => {
97
+ let settled = false;
98
+ let timer = null;
99
+ let tlsSocket = null;
100
+ let req = null;
101
+ const done = (value) => {
102
+ if (settled) return;
103
+ settled = true;
104
+ cleanup();
105
+ resolve(value);
106
+ };
107
+ const onAbort = () => done(fail('aborted'));
108
+ const cleanup = () => {
109
+ if (timer) {
110
+ clearTimeout(timer);
111
+ timer = null;
112
+ }
113
+ try {
114
+ signal?.removeEventListener?.('abort', onAbort);
115
+ } catch {
116
+ }
117
+ try {
118
+ req?.destroy?.();
119
+ } catch {
120
+ }
121
+ try {
122
+ tlsSocket?.destroy?.();
123
+ } catch {
124
+ }
125
+ try {
126
+ tunnel?.destroy?.();
127
+ } catch {
128
+ }
129
+ try {
130
+ child.kill?.('SIGKILL');
131
+ } catch {
132
+ }
133
+ };
134
+
135
+ timer = setTimeout(() => done(fail('timeout')), effectiveTimeoutMs);
136
+ if (timer?.unref) timer.unref();
137
+ try {
138
+ signal?.addEventListener?.('abort', onAbort, { once: true });
139
+ } catch {
140
+ }
141
+ try {
142
+ child.on?.('error', () => done(fail('spawn')));
143
+ } catch {
144
+ }
145
+
146
+ let secureSocket = null;
147
+ try {
148
+ secureSocket = tls.connect({ socket: tunnel, servername: host });
149
+ } catch {
150
+ done(fail('tls'));
151
+ return;
152
+ }
153
+ tlsSocket = secureSocket;
154
+ tlsSocket.on('error', () => done(fail('tls')));
155
+
156
+ let clientReq = null;
157
+ try {
158
+ clientReq = httpRequest(
159
+ {
160
+ host,
161
+ port,
162
+ path: '/health',
163
+ method: 'GET',
164
+ // Credential-free by construction: no Authorization header, no
165
+ // cookie. The Host header comes from `host` as usual.
166
+ headers: { Accept: 'application/json' },
167
+ // HTTP/1.1 over the already-verified TLS socket. No `agent`:
168
+ // any Agent (including `agent: false`) ignores
169
+ // `createConnection` and would resolve `host` via DNS again.
170
+ createConnection: () => tlsSocket,
171
+ },
172
+ (res) => {
173
+ const chunks = [];
174
+ let bytes = 0;
175
+ res.on('data', (chunk) => {
176
+ if (bytes + chunk.length <= NC_PROBE_MAX_BODY_BYTES) {
177
+ chunks.push(chunk);
178
+ bytes += chunk.length;
179
+ }
180
+ // Beyond the cap the rest is drained and dropped.
181
+ });
182
+ res.on('end', () => {
183
+ let body = null;
184
+ try {
185
+ body = JSON.parse(Buffer.concat(chunks).toString('utf8'));
186
+ } catch {
187
+ body = null;
188
+ }
189
+ done({ ok: true, status: res.statusCode ?? null, body });
190
+ });
191
+ res.on('error', () => done(fail('http')));
192
+ },
193
+ );
194
+ } catch {
195
+ done(fail('request'));
196
+ return;
197
+ }
198
+ req = clientReq;
199
+ req.on('error', () => done(fail('request')));
200
+ try {
201
+ req.end();
202
+ } catch {
203
+ done(fail('request'));
204
+ }
205
+ });
206
+ } catch {
207
+ // Belt and braces: the contract is never-throw, so a synchronous
208
+ // surprise above still resolves to a failure result.
209
+ try {
210
+ child?.kill?.('SIGKILL');
211
+ } catch {
212
+ }
213
+ try {
214
+ tunnel?.destroy?.();
215
+ } catch {
216
+ }
217
+ return fail('internal');
218
+ }
219
+ };
220
+ };
@@ -15,6 +15,9 @@
15
15
  * All process execution goes through the injected `runner` (argument arrays,
16
16
  * no shell, bounded timeouts) so unit tests can inject a fake. The default
17
17
  * runner spawns the resolved executable directly with `windowsHide: true`.
18
+ * The tailnet-path health-probe fallback goes through the injected
19
+ * `tailnetHealthFetch` (a `tailscale nc` + TLS fetch built from the resolved
20
+ * executable by default); tests inject a fake.
18
21
  */
19
22
 
20
23
  import { spawn } from 'node:child_process';
@@ -43,6 +46,7 @@ import {
43
46
  resolveTailscaleExecutable,
44
47
  validateTailscaleConfig,
45
48
  } from './tailscale.js';
49
+ import { createTailscaleNcHealthFetch } from './nc-probe.js';
46
50
 
47
51
  const TAILSCALE_CONFIG_FILE = 'tailscale-config.json';
48
52
  const TAILSCALE_MAPPING_FILE = 'tailscale-mapping.json';
@@ -168,6 +172,11 @@ export const createTailscaleService = ({
168
172
  isUnsafeUnauthenticatedLanAllowed = () => false,
169
173
  runner = null,
170
174
  fetchImpl = globalThis.fetch,
175
+ // Tailnet-path fallback for the self-probe (`tailscale nc` + TLS, see
176
+ // `nc-probe.js`). Defaults to the real implementation built from the
177
+ // resolved executable; tests inject a fake. Only used when the direct
178
+ // fetch throws without an HTTP response.
179
+ tailnetHealthFetch = null,
171
180
  fsPromises = fs.promises,
172
181
  existsSync = fs.existsSync,
173
182
  // Stable server identity (hash of the public relay signing key — not a
@@ -182,6 +191,8 @@ export const createTailscaleService = ({
182
191
  } = {}) => {
183
192
  const effectiveRunner = runner || createDefaultTailscaleRunner({ platform });
184
193
  const executable = resolveTailscaleExecutable({ platform, env, existsSync });
194
+ const effectiveTailnetHealthFetch = tailnetHealthFetch
195
+ || createTailscaleNcHealthFetch({ executable: executable.command });
185
196
  const configPath = path.join(dataDir, TAILSCALE_CONFIG_FILE);
186
197
  const mappingPath = path.join(dataDir, TAILSCALE_MAPPING_FILE);
187
198
 
@@ -432,6 +443,46 @@ export const createTailscaleService = ({
432
443
  return { removed: true };
433
444
  };
434
445
 
446
+ /**
447
+ * Shared identity check for both probe paths: the body must be a JSON
448
+ * object whose `serverId` equals this server's stable id.
449
+ */
450
+ const checkHealthBody = (body, expectedServerId) => {
451
+ const reported = body && typeof body === 'object' ? body.serverId : null;
452
+ return typeof reported === 'string' && reported.length > 0 && reported === expectedServerId;
453
+ };
454
+
455
+ /**
456
+ * Tailnet-path fallback: re-runs the same credential-free `/health`
457
+ * check through `tailscale nc` when the direct fetch threw without an
458
+ * HTTP response (host cannot resolve/reach its own MagicDNS name —
459
+ * userspace networking, non-MagicDNS resolver). A direct HTTP response,
460
+ * even non-OK or mismatched, never reaches here: something answered, so
461
+ * the tailnet path must not override it. Returns true only on a 2xx
462
+ * response whose JSON body carries this server's id.
463
+ */
464
+ const probeUrlOverTailnet = async (url, expectedServerId) => {
465
+ let host = null;
466
+ let port = 443;
467
+ try {
468
+ const parsed = new URL(url);
469
+ host = parsed.hostname || null;
470
+ port = parsed.port ? Number.parseInt(parsed.port, 10) : 443;
471
+ } catch {
472
+ return false;
473
+ }
474
+ if (!host || !Number.isInteger(port) || port <= 0) return false;
475
+ let result = null;
476
+ try {
477
+ result = await effectiveTailnetHealthFetch({ host, port, timeoutMs: TAILSCALE_PROBE_TIMEOUT_MS });
478
+ } catch {
479
+ return false;
480
+ }
481
+ if (!result || result.ok !== true) return false;
482
+ if (!Number.isInteger(result.status) || result.status < 200 || result.status >= 300) return false;
483
+ return checkHealthBody(result.body, expectedServerId);
484
+ };
485
+
435
486
  const probeUrl = async (url) => {
436
487
  // A null/throwing identity fails the probe: the URL stays `starting`
437
488
  // and is never advertised as `active`.
@@ -456,10 +507,12 @@ export const createTailscaleService = ({
456
507
  clearTimeout(timer);
457
508
  if (!response || !response.ok) return false;
458
509
  const body = await response.json().catch(() => null);
459
- const reported = body && typeof body === 'object' ? body.serverId : null;
460
- return typeof reported === 'string' && reported.length > 0 && reported === expectedServerId;
510
+ return checkHealthBody(body, expectedServerId);
461
511
  } catch {
462
- return false;
512
+ // No HTTP response (DNS/connect/abort on hosts that cannot resolve
513
+ // or reach their own MagicDNS name): retry the identical check over
514
+ // the tailnet path instead of failing the probe.
515
+ return probeUrlOverTailnet(url, expectedServerId);
463
516
  }
464
517
  };
465
518
 
@@ -468,7 +521,7 @@ export const createTailscaleService = ({
468
521
  if (myGeneration !== generation) return;
469
522
  if (elapsed >= PROBE_RETRY_BUDGET_MS || delays.length === 0) {
470
523
  if (myGeneration === generation && status.state === 'starting') {
471
- setRuntime({ state: 'error', errorCode: 'probe_failed', errorMessage: 'The Tailscale URL never answered as this server.' });
524
+ setRuntime({ state: 'error', errorCode: 'probe_failed', errorMessage: 'The Tailscale URL never answered as this server. Check that MagicDNS and HTTPS certificates are enabled for your tailnet, then retry.' });
472
525
  }
473
526
  return;
474
527
  }
@@ -17,6 +17,7 @@ import {
17
17
  validateTailscaleConfig,
18
18
  } from './tailscale.js';
19
19
  import { createTailscaleService } from './service.js';
20
+ import { createTailscaleNcHealthFetch } from './nc-probe.js';
20
21
 
21
22
  describe('tailscale status parsing', () => {
22
23
  it('strips the trailing dot from DNSName and reports login state', () => {
@@ -253,6 +254,9 @@ const createHarness = ({ handlers, port = 3000, uiPassword = 'secret' } = {}) =>
253
254
  fsPromises,
254
255
  existsSync: () => false,
255
256
  fetchImpl: async () => ({ ok: false, status: 404, json: async () => null }),
257
+ // Fail closed by default: no existing test exercises the tailnet path,
258
+ // and the real `tailscale nc` implementation must never spawn here.
259
+ tailnetHealthFetch: async () => ({ ok: false, status: null, body: null, error: 'disabled-in-test' }),
256
260
  logWarn: () => {},
257
261
  });
258
262
  return { service, calls, files, fsPromises };
@@ -1859,3 +1863,218 @@ describe('tailscale reconcile serialization (Off/Private overlap)', () => {
1859
1863
  }
1860
1864
  });
1861
1865
  });
1866
+
1867
+ describe('tailscale tailnet-path probe fallback (nc)', () => {
1868
+ const memFsFor = () => {
1869
+ const memFs = new Map();
1870
+ return {
1871
+ memFs,
1872
+ fsPromises: {
1873
+ readFile: async (p) => {
1874
+ if (!memFs.has(p)) { const e = new Error('x'); e.code = 'ENOENT'; throw e; }
1875
+ return memFs.get(p);
1876
+ },
1877
+ writeFile: async (p, c) => { memFs.set(p, String(c)); },
1878
+ mkdir: async () => {},
1879
+ rename: async (a, b) => { memFs.set(b, memFs.get(a)); memFs.delete(a); },
1880
+ unlink: async (p) => { memFs.delete(p); },
1881
+ },
1882
+ };
1883
+ };
1884
+ const createProbeService = ({ fetchImpl, tailnetHealthFetch }) => {
1885
+ const { fsPromises } = memFsFor();
1886
+ const fallbackCalls = [];
1887
+ const service = createTailscaleService({
1888
+ existsSync: () => false,
1889
+ dataDir: '/data',
1890
+ getPort: () => 3000,
1891
+ isUiAuthEnabled: () => true,
1892
+ isUnsafeUnauthenticatedLanAllowed: () => false,
1893
+ runner: {
1894
+ runTailscale: async (args) => {
1895
+ if (args.includes('serve') && args.includes('status')) {
1896
+ return { ok: true, code: 0, stdout: JSON.stringify({ Web: {} }), stderr: '', spawnError: null, timedOut: false };
1897
+ }
1898
+ return { ok: true, code: 0, stdout: STATUS_JSON, stderr: '', spawnError: null, timedOut: false };
1899
+ },
1900
+ },
1901
+ fsPromises,
1902
+ getServerId: async () => TEST_SERVER_ID,
1903
+ fetchImpl,
1904
+ tailnetHealthFetch: async (args) => {
1905
+ fallbackCalls.push(args);
1906
+ return tailnetHealthFetch(args);
1907
+ },
1908
+ logWarn: () => {},
1909
+ });
1910
+ return { service, fallbackCalls };
1911
+ };
1912
+ const directDnsFailure = async () => {
1913
+ throw new Error('getaddrinfo ENOTFOUND mymachine.tailabc.ts.net');
1914
+ };
1915
+
1916
+ it('goes active when the direct fetch throws but the tailnet path answers', async () => {
1917
+ const { service, fallbackCalls } = createProbeService({
1918
+ fetchImpl: directDnsFailure,
1919
+ tailnetHealthFetch: async () => ({ ok: true, status: 200, body: { serverId: TEST_SERVER_ID } }),
1920
+ });
1921
+ await service.loadConfig();
1922
+ const result = await service.setConfig({ enabled: true, mode: 'private', httpsPort: 443 });
1923
+ expect(result.state).toBe('active');
1924
+ expect(result.url).toBe('https://mymachine.tailabc.ts.net');
1925
+ expect(fallbackCalls).toHaveLength(1);
1926
+ expect(fallbackCalls[0]).toMatchObject({ host: 'mymachine.tailabc.ts.net', port: 443 });
1927
+ service.dispose();
1928
+ });
1929
+
1930
+ it('stays starting when the tailnet path reports a different server', async () => {
1931
+ const { service, fallbackCalls } = createProbeService({
1932
+ fetchImpl: directDnsFailure,
1933
+ tailnetHealthFetch: async () => ({ ok: true, status: 200, body: { serverId: 'some-other-server' } }),
1934
+ });
1935
+ await service.loadConfig();
1936
+ const result = await service.setConfig({ enabled: true, mode: 'private', httpsPort: 443 });
1937
+ expect(result.state).toBe('starting');
1938
+ expect(result.url).toBeNull();
1939
+ expect(fallbackCalls).toHaveLength(1);
1940
+ service.dispose();
1941
+ });
1942
+
1943
+ it('never uses the tailnet path when the direct path answers', async () => {
1944
+ // Non-OK direct response.
1945
+ const nonOk = createProbeService({
1946
+ fetchImpl: async () => ({ ok: false, status: 404, json: async () => null }),
1947
+ tailnetHealthFetch: async () => ({ ok: true, status: 200, body: { serverId: TEST_SERVER_ID } }),
1948
+ });
1949
+ await nonOk.service.loadConfig();
1950
+ const nonOkResult = await nonOk.service.setConfig({ enabled: true, mode: 'private', httpsPort: 443 });
1951
+ expect(nonOkResult.state).toBe('starting');
1952
+ expect(nonOkResult.url).toBeNull();
1953
+ expect(nonOk.fallbackCalls).toEqual([]);
1954
+ nonOk.service.dispose();
1955
+ // Mismatching serverId direct response.
1956
+ const mismatch = createProbeService({
1957
+ fetchImpl: async () => ({ ok: true, status: 200, json: async () => ({ serverId: 'some-other-server' }) }),
1958
+ tailnetHealthFetch: async () => ({ ok: true, status: 200, body: { serverId: TEST_SERVER_ID } }),
1959
+ });
1960
+ await mismatch.service.loadConfig();
1961
+ const mismatchResult = await mismatch.service.setConfig({ enabled: true, mode: 'private', httpsPort: 443 });
1962
+ expect(mismatchResult.state).toBe('starting');
1963
+ expect(mismatchResult.url).toBeNull();
1964
+ expect(mismatch.fallbackCalls).toEqual([]);
1965
+ mismatch.service.dispose();
1966
+ });
1967
+
1968
+ it('stays starting when the tailnet path fails, without an unhandled rejection', async () => {
1969
+ const unhandled = [];
1970
+ const onUnhandled = (reason) => unhandled.push(reason);
1971
+ process.on('unhandledRejection', onUnhandled);
1972
+ const services = [];
1973
+ try {
1974
+ // Throwing fallback.
1975
+ const throwing = createProbeService({
1976
+ fetchImpl: directDnsFailure,
1977
+ tailnetHealthFetch: async () => { throw new Error('nc exploded'); },
1978
+ });
1979
+ services.push(throwing.service);
1980
+ await throwing.service.loadConfig();
1981
+ const throwingResult = await throwing.service.setConfig({ enabled: true, mode: 'private', httpsPort: 443 });
1982
+ expect(throwingResult.state).toBe('starting');
1983
+ expect(throwingResult.url).toBeNull();
1984
+ expect(throwing.fallbackCalls).toHaveLength(1);
1985
+ // Failing (non-throwing) fallback.
1986
+ const failing = createProbeService({
1987
+ fetchImpl: directDnsFailure,
1988
+ tailnetHealthFetch: async () => ({ ok: false, status: null, body: null, error: 'timeout' }),
1989
+ });
1990
+ services.push(failing.service);
1991
+ await failing.service.loadConfig();
1992
+ const failingResult = await failing.service.setConfig({ enabled: true, mode: 'private', httpsPort: 443 });
1993
+ expect(failingResult.state).toBe('starting');
1994
+ expect(failingResult.url).toBeNull();
1995
+ expect(failing.fallbackCalls).toHaveLength(1);
1996
+ await new Promise((resolve) => setTimeout(resolve, 20));
1997
+ expect(unhandled).toEqual([]);
1998
+ } finally {
1999
+ process.removeListener('unhandledRejection', onUnhandled);
2000
+ for (const service of services) service.dispose();
2001
+ }
2002
+ });
2003
+ });
2004
+
2005
+ describe('tailscale nc health fetch', () => {
2006
+ it('reports a spawn failure instead of throwing', async () => {
2007
+ const fetch = createTailscaleNcHealthFetch({
2008
+ executable: 'tailscale',
2009
+ spawnFn: () => { throw new Error('spawn tailscale ENOENT'); },
2010
+ });
2011
+ const result = await fetch({ host: 'mymachine.tailabc.ts.net', port: 443, timeoutMs: 100 });
2012
+ expect(result).toEqual({ ok: false, status: null, body: null, error: 'spawn' });
2013
+ });
2014
+
2015
+ it('rejects an invalid target without spawning', async () => {
2016
+ const spawnFn = vi.fn();
2017
+ const fetch = createTailscaleNcHealthFetch({ executable: 'tailscale', spawnFn });
2018
+ const result = await fetch({ host: '', port: 443, timeoutMs: 100 });
2019
+ expect(result).toEqual({ ok: false, status: null, body: null, error: 'invalid-target' });
2020
+ expect(spawnFn).not.toHaveBeenCalled();
2021
+ });
2022
+
2023
+ it('kills the child when the probe times out', async () => {
2024
+ const { PassThrough } = await import('node:stream');
2025
+ const { EventEmitter } = await import('node:events');
2026
+ const children = [];
2027
+ const spawnFn = (command, args, options) => {
2028
+ expect(command).toBe('tailscale');
2029
+ expect(args).toEqual(['nc', 'mymachine.tailabc.ts.net', '443']);
2030
+ expect(options).toMatchObject({ windowsHide: true, shell: false });
2031
+ const child = new EventEmitter();
2032
+ child.stdout = new PassThrough();
2033
+ child.stdin = new PassThrough();
2034
+ child.kill = vi.fn();
2035
+ child.stdout.on('error', () => {});
2036
+ child.stdin.on('error', () => {});
2037
+ children.push(child);
2038
+ return child;
2039
+ };
2040
+ const fetch = createTailscaleNcHealthFetch({ executable: 'tailscale', spawnFn });
2041
+ // No handshake bytes ever arrive, so the probe must time out.
2042
+ const result = await fetch({ host: 'mymachine.tailabc.ts.net', port: 443, timeoutMs: 50 });
2043
+ expect(result.ok).toBe(false);
2044
+ expect(result.error).toBe('timeout');
2045
+ expect(children).toHaveLength(1);
2046
+ expect(children[0].kill).toHaveBeenCalledWith('SIGKILL');
2047
+ children[0].stdout.destroy();
2048
+ children[0].stdin.destroy();
2049
+ });
2050
+
2051
+ it('aborts on signal and kills the child', async () => {
2052
+ const { PassThrough } = await import('node:stream');
2053
+ const { EventEmitter } = await import('node:events');
2054
+ const children = [];
2055
+ const spawnFn = () => {
2056
+ const child = new EventEmitter();
2057
+ child.stdout = new PassThrough();
2058
+ child.stdin = new PassThrough();
2059
+ child.kill = vi.fn();
2060
+ child.stdout.on('error', () => {});
2061
+ child.stdin.on('error', () => {});
2062
+ children.push(child);
2063
+ return child;
2064
+ };
2065
+ const fetch = createTailscaleNcHealthFetch({ executable: 'tailscale', spawnFn });
2066
+ const controller = new AbortController();
2067
+ setTimeout(() => controller.abort(), 10);
2068
+ const result = await fetch({
2069
+ host: 'mymachine.tailabc.ts.net',
2070
+ port: 443,
2071
+ timeoutMs: 5_000,
2072
+ signal: controller.signal,
2073
+ });
2074
+ expect(result).toEqual({ ok: false, status: null, body: null, error: 'aborted' });
2075
+ expect(children).toHaveLength(1);
2076
+ expect(children[0].kill).toHaveBeenCalledWith('SIGKILL');
2077
+ children[0].stdout.destroy();
2078
+ children[0].stdin.destroy();
2079
+ });
2080
+ });