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

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 (56) hide show
  1. package/bin/lib/DOCUMENTATION.md +1 -1
  2. package/bin/lib/commands-status.js +3 -2
  3. package/bin/lib/commands-status.test.js +62 -0
  4. package/dist/assets/{DiagramView-D-OSWTbO.js → DiagramView-DxLAcmg-.js} +1 -1
  5. package/dist/assets/{DiffView-BKT-MIH4.js → DiffView-BzVBoNCp.js} +1 -1
  6. package/dist/assets/{FileSaveConflictDialog-DBkVFssC.js → FileSaveConflictDialog-2KqGdUdB.js} +1 -1
  7. package/dist/assets/{FilesView-B7GIuRlh.js → FilesView-3spQTRpf.js} +1 -1
  8. package/dist/assets/{GitHubDetailScaffold-C9rCZMUT.js → GitHubDetailScaffold-C2d4WqKe.js} +1 -1
  9. package/dist/assets/{GitHubLinkPicker-Bm09hvhJ.js → GitHubLinkPicker-BDwZtk0x.js} +1 -1
  10. package/dist/assets/{GitHubListPrimitives-DlhAlxI6.js → GitHubListPrimitives-Dor_K85Y.js} +1 -1
  11. package/dist/assets/{GitView-BgqdMb0m.js → GitView-CSAJagWK.js} +3 -3
  12. package/dist/assets/{IssuesSurface-BZXAvt49.js → IssuesSurface-euZzv2L9.js} +1 -1
  13. package/dist/assets/{JsonTreeView-BKgCQjh_.js → JsonTreeView-Drmn7tIN.js} +1 -1
  14. package/dist/assets/{MarkdownRendererImpl-BdcyMPw-.js → MarkdownRendererImpl-Bq0p5v9N.js} +1 -1
  15. package/dist/assets/{PatchDiff-2MmWXcGe.js → PatchDiff-BegAimf3.js} +1 -1
  16. package/dist/assets/{PierreDiffViewer-D1F2WvD0.js → PierreDiffViewer-DgU2Zcmr.js} +1 -1
  17. package/dist/assets/{PullRequestsSurface-CN2z3DFv.js → PullRequestsSurface-CnGgmkuf.js} +2 -2
  18. package/dist/assets/{SessionSwitcherContent-CCljxAZb.js → SessionSwitcherContent-Cq5LIBuG.js} +1 -1
  19. package/dist/assets/{SessionSwitcherDropdown-DtNt3qw4.js → SessionSwitcherDropdown-Dpob2_y5.js} +2 -2
  20. package/dist/assets/{SessionUnreadDot-B9bHMy5q.js → SessionUnreadDot-BPKnpGAh.js} +1 -1
  21. package/dist/assets/{SettingsView-DaZVCInW.js → SettingsView-DcOJRyym.js} +4 -4
  22. package/dist/assets/{SettingsWindow-C-ydfopH.js → SettingsWindow-C2RB0AjV.js} +1 -1
  23. package/dist/assets/{ToolOutputDialog-DJUAx_Oj.js → ToolOutputDialog-DmzNX2QX.js} +1 -1
  24. package/dist/assets/{ToolPartDiffPreview-DFyuJM4c.js → ToolPartDiffPreview-CO5Gg17_.js} +1 -1
  25. package/dist/assets/{VirtualizedFileDiff-BS-af6rn.js → VirtualizedFileDiff-CJ1m8JE-.js} +1 -1
  26. package/dist/assets/{computeVirtualFileMetrics-BI6wORhM.js → computeVirtualFileMetrics-8mC_o5zA.js} +1 -1
  27. package/dist/assets/{contextFileOpenGuard-DUMSGR4M.js → contextFileOpenGuard-CRboGmXF.js} +1 -1
  28. package/dist/assets/{gitStatusPredicates-FdKYDZe3.js → gitStatusPredicates-BqV-kOGY.js} +1 -1
  29. package/dist/assets/{githubLink-B3-BaGpb.js → githubLink-DSgdECMr.js} +1 -1
  30. package/dist/assets/{index-Df-vmvzu.js → index-B3qmI8VW.js} +1 -1
  31. package/dist/assets/{main-61_cd7S7.js → main-Bn93XwxQ.js} +2 -2
  32. package/dist/assets/{main-q43jqZ2I.js → main-HPNu-7DG.js} +4 -4
  33. package/dist/assets/{markdownCore-CqHYlXi_.js → markdownCore-Csm6UEBe.js} +1 -1
  34. package/dist/assets/{miniChat-vOuWN5pV.js → miniChat-C3W5IvM4.js} +2 -2
  35. package/dist/assets/{mobile-mrXWV5ky.js → mobile-COEEitAQ.js} +2 -2
  36. package/dist/assets/{pi-session-focus-preference-BEufpwC6.js → pi-session-focus-preference-DQjF7Nh1.js} +1 -1
  37. package/dist/assets/{renderDiffWithHighlighter-BD9CAhZU.js → renderDiffWithHighlighter-BBwvKSDe.js} +1 -1
  38. package/dist/assets/{renderElectronMiniChatApp-QQFXkY5Y.js → renderElectronMiniChatApp-7vIiCPiK.js} +2 -2
  39. package/dist/assets/{renderFileWithHighlighter-KiEWMtzI.js → renderFileWithHighlighter-VOwWxIE1.js} +1 -1
  40. package/dist/assets/{renderMobileApp-DIZYvrhi.js → renderMobileApp-BQDG02OP.js} +3 -3
  41. package/dist/assets/{runtimeEndpointReset-BA2uP2rj.js → runtimeEndpointReset-CzwDZ_EP.js} +4 -4
  42. package/dist/assets/{useAppFontEffects-Bfw_d5eB.js → useAppFontEffects-BQ1JUauS.js} +6 -6
  43. package/dist/assets/{useFilesViewSearch-Budwejnx.js → useFilesViewSearch-BYG2TZWz.js} +1 -1
  44. package/dist/assets/{useGitHubRemoteSearch-gUdylYy3.js → useGitHubRemoteSearch-Bo1LF-x_.js} +1 -1
  45. package/dist/assets/{useSwitcherItems-yHSMduoo.js → useSwitcherItems-q0ZavMJb.js} +1 -1
  46. package/dist/assets/{web-components-CeHLxvED.js → web-components-CJ0xIy7r.js} +1 -1
  47. package/dist/index.html +1 -1
  48. package/dist/mini-chat.html +1 -1
  49. package/dist/mobile.html +1 -1
  50. package/package.json +1 -1
  51. package/server/index.js +4 -1
  52. package/server/lib/tailscale/DOCUMENTATION.md +56 -6
  53. package/server/lib/tailscale/nc-probe.js +220 -0
  54. package/server/lib/tailscale/public-dns.js +72 -0
  55. package/server/lib/tailscale/service.js +183 -7
  56. package/server/lib/tailscale/tailscale.test.js +537 -1
@@ -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
+ };
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Public DNS readiness check for Tailscale Funnel (public) mode.
3
+ *
4
+ * When Funnel is first enabled, Tailscale takes ~10-15 minutes to publish
5
+ * the public DNS record for `<machine>.<tailnet>.ts.net`. The host's own
6
+ * resolver must NOT be used to check this:
7
+ *
8
+ * - A host using MagicDNS resolves the name to the tailnet IP immediately,
9
+ * so it can never show public readiness.
10
+ * - A host resolver may also have cached the negative (NXDOMAIN) answer.
11
+ *
12
+ * Instead this module queries public resolvers (1.1.1.1, 8.8.8.8) directly.
13
+ * It sends only the hostname — no credentials, nothing else.
14
+ */
15
+
16
+ import dns from 'node:dns';
17
+
18
+ const PUBLIC_DNS_SERVERS = ['1.1.1.1', '8.8.8.8'];
19
+ const PUBLIC_DNS_TIMEOUT_MS = 3000;
20
+
21
+ const isNotFoundCode = (code) => code === 'ENOTFOUND' || code === 'ENODATA';
22
+
23
+ /**
24
+ * Create a `resolvePublicDns` function with an injectable Resolver factory
25
+ * (tests inject a fake; production uses `dns.promises.Resolver`).
26
+ *
27
+ * Returns `async (hostname) => 'found' | 'not-found' | 'error'`. Never throws.
28
+ */
29
+ export const createResolvePublicDns = ({ createResolver } = {}) => {
30
+ const newResolver = createResolver
31
+ || ((options) => new dns.promises.Resolver(options));
32
+ return async (hostname) => {
33
+ try {
34
+ if (typeof hostname !== 'string' || hostname.trim().length === 0) return 'error';
35
+ const name = hostname.trim().replace(/\.$/, '');
36
+ if (!name) return 'error';
37
+ let resolver = null;
38
+ try {
39
+ resolver = newResolver({ timeout: PUBLIC_DNS_TIMEOUT_MS, tries: 1 });
40
+ } catch {
41
+ return 'error';
42
+ }
43
+ try {
44
+ resolver.setServers(PUBLIC_DNS_SERVERS);
45
+ } catch {
46
+ return 'error';
47
+ }
48
+ const settled = await Promise.allSettled([
49
+ resolver.resolve4(name),
50
+ resolver.resolve6(name),
51
+ ]);
52
+ try {
53
+ resolver.cancel?.();
54
+ } catch {
55
+ }
56
+ const found = settled.some(
57
+ (entry) => entry.status === 'fulfilled' && Array.isArray(entry.value) && entry.value.length > 0,
58
+ );
59
+ if (found) return 'found';
60
+ const allNotFound = settled.length > 0 && settled.every(
61
+ (entry) => entry.status === 'rejected' && isNotFoundCode(entry.reason?.code),
62
+ );
63
+ if (allNotFound) return 'not-found';
64
+ return 'error';
65
+ } catch {
66
+ return 'error';
67
+ }
68
+ };
69
+ };
70
+
71
+ /** Production resolver: public resolvers, 3s timeout, single try. Never throws. */
72
+ export const defaultResolvePublicDns = createResolvePublicDns();
@@ -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,15 +46,26 @@ import {
43
46
  resolveTailscaleExecutable,
44
47
  validateTailscaleConfig,
45
48
  } from './tailscale.js';
49
+ import { createTailscaleNcHealthFetch } from './nc-probe.js';
50
+ import { defaultResolvePublicDns } from './public-dns.js';
46
51
 
47
52
  const TAILSCALE_CONFIG_FILE = 'tailscale-config.json';
48
53
  const TAILSCALE_MAPPING_FILE = 'tailscale-mapping.json';
49
54
 
50
- // Funnel public DNS can take minutes on first use: keep re-probing with
51
- // backoff while `starting`, up to this budget, without blocking anything else.
55
+ // Funnel public DNS can take minutes on first use: the mapping already
56
+ // fronts this server (probe-before-advertise passed), so `active` is
57
+ // reported immediately and public DNS readiness is tracked separately via
58
+ // `publicDns` (see the public-DNS watcher below).
52
59
  const PROBE_RETRY_BUDGET_MS = 10 * 60 * 1000;
53
60
  const PROBE_RETRY_DELAYS_MS = [5_000, 10_000, 30_000, 60_000, 60_000, 60_000, 60_000, 60_000, 60_000, 60_000];
54
61
 
62
+ // Public-DNS watcher cadence: check immediately on reaching active (public),
63
+ // then every 30s for the first 20 minutes, then every 2 minutes, until the
64
+ // public record is found.
65
+ const PUBLIC_DNS_FAST_INTERVAL_MS = 30_000;
66
+ const PUBLIC_DNS_SLOW_INTERVAL_MS = 2 * 60_000;
67
+ const PUBLIC_DNS_FAST_WINDOW_MS = 20 * 60_000;
68
+
55
69
  // Config/retry HTTP responses wait for reconcile only up to this grace, then
56
70
  // return the current (possibly transitional) status while reconcile
57
71
  // continues in the background. The apply can block for minutes waiting for
@@ -168,6 +182,11 @@ export const createTailscaleService = ({
168
182
  isUnsafeUnauthenticatedLanAllowed = () => false,
169
183
  runner = null,
170
184
  fetchImpl = globalThis.fetch,
185
+ // Tailnet-path fallback for the self-probe (`tailscale nc` + TLS, see
186
+ // `nc-probe.js`). Defaults to the real implementation built from the
187
+ // resolved executable; tests inject a fake. Only used when the direct
188
+ // fetch throws without an HTTP response.
189
+ tailnetHealthFetch = null,
171
190
  fsPromises = fs.promises,
172
191
  existsSync = fs.existsSync,
173
192
  // Stable server identity (hash of the public relay signing key — not a
@@ -179,9 +198,16 @@ export const createTailscaleService = ({
179
198
  env = process.env,
180
199
  logWarn = (message) => console.warn(message),
181
200
  configResponseGraceMs = CONFIG_RESPONSE_GRACE_MS,
201
+ // Public DNS readiness for Funnel (public) mode: async
202
+ // `(hostname) => 'found' | 'not-found' | 'error'`. Never throws.
203
+ // Defaults to the public-resolver check in `public-dns.js`; tests inject
204
+ // a fake so no real DNS is touched.
205
+ resolvePublicDns = defaultResolvePublicDns,
182
206
  } = {}) => {
183
207
  const effectiveRunner = runner || createDefaultTailscaleRunner({ platform });
184
208
  const executable = resolveTailscaleExecutable({ platform, env, existsSync });
209
+ const effectiveTailnetHealthFetch = tailnetHealthFetch
210
+ || createTailscaleNcHealthFetch({ executable: executable.command });
185
211
  const configPath = path.join(dataDir, TAILSCALE_CONFIG_FILE);
186
212
  const mappingPath = path.join(dataDir, TAILSCALE_MAPPING_FILE);
187
213
 
@@ -200,6 +226,12 @@ export const createTailscaleService = ({
200
226
  };
201
227
  let generation = 0;
202
228
  let probeTimer = null;
229
+ // Public-DNS watcher state (Funnel/public `active` only). `publicDnsState`
230
+ // is exposed via `getStatus()` gated by mode+state, so non-active states
231
+ // always observe `null` without touching every `setRuntime` call site.
232
+ let publicDnsTimer = null;
233
+ let publicDnsState = null;
234
+ let publicDnsStartedAt = 0;
203
235
  // Serializes reconciles: each reconcile starts only after the previous
204
236
  // one settles, so a superseded Off can never remove a mapping after the
205
237
  // newer Private reconcile verified it. The tail swallows rejection so one
@@ -213,7 +245,8 @@ export const createTailscaleService = ({
213
245
  // mapping that is already written is quit-risky, like an active one.
214
246
  let mappingRecordPresent = false;
215
247
 
216
- // Every generation bump cancels the in-flight apply first.
248
+ // Every generation bump cancels the in-flight apply first, and stops the
249
+ // public-DNS watcher (same generation tie as `probeTimer`).
217
250
  const bumpGeneration = () => {
218
251
  generation += 1;
219
252
  try {
@@ -221,6 +254,10 @@ export const createTailscaleService = ({
221
254
  } catch {
222
255
  }
223
256
  applyAbort = null;
257
+ if (publicDnsTimer) {
258
+ clearTimeout(publicDnsTimer);
259
+ publicDnsTimer = null;
260
+ }
224
261
  };
225
262
 
226
263
  const clearProbeTimer = () => {
@@ -230,6 +267,79 @@ export const createTailscaleService = ({
230
267
  }
231
268
  };
232
269
 
270
+ const clearPublicDnsTimer = () => {
271
+ if (publicDnsTimer) {
272
+ clearTimeout(publicDnsTimer);
273
+ publicDnsTimer = null;
274
+ }
275
+ };
276
+
277
+ const stopPublicDnsWatcher = () => {
278
+ clearPublicDnsTimer();
279
+ publicDnsState = null;
280
+ publicDnsStartedAt = 0;
281
+ };
282
+
283
+ const schedulePublicDnsCheck = (myGeneration, hostname) => {
284
+ clearPublicDnsTimer();
285
+ if (myGeneration !== generation) return;
286
+ if (publicDnsState === 'ready') return;
287
+ const elapsed = Date.now() - publicDnsStartedAt;
288
+ const delay = elapsed < PUBLIC_DNS_FAST_WINDOW_MS
289
+ ? PUBLIC_DNS_FAST_INTERVAL_MS
290
+ : PUBLIC_DNS_SLOW_INTERVAL_MS;
291
+ publicDnsTimer = setTimeout(async () => {
292
+ publicDnsTimer = null;
293
+ if (myGeneration !== generation) return;
294
+ await runPublicDnsCheck(myGeneration, hostname);
295
+ }, delay);
296
+ if (publicDnsTimer?.unref) publicDnsTimer.unref();
297
+ };
298
+
299
+ const runPublicDnsCheck = async (myGeneration, hostname) => {
300
+ if (myGeneration !== generation) return;
301
+ let result = 'error';
302
+ try {
303
+ const value = await resolvePublicDns(hostname);
304
+ if (value === 'found' || value === 'not-found' || value === 'error') {
305
+ result = value;
306
+ } else {
307
+ result = 'error';
308
+ }
309
+ } catch {
310
+ result = 'error';
311
+ }
312
+ // A stale result after a generation bump must never write status.
313
+ if (myGeneration !== generation) return;
314
+ // Only the live public/active mapping owns this watcher: a config
315
+ // change within the same generation window must not flip DNS state.
316
+ if (config.mode !== 'public' || status.state !== 'active') return;
317
+ if (result === 'found') {
318
+ publicDnsState = 'ready';
319
+ clearPublicDnsTimer();
320
+ return;
321
+ }
322
+ publicDnsState = result === 'error' ? 'unknown' : 'pending';
323
+ schedulePublicDnsCheck(myGeneration, hostname);
324
+ };
325
+
326
+ const startPublicDnsWatcher = (myGeneration, magicDnsName) => {
327
+ clearPublicDnsTimer();
328
+ const hostname = typeof magicDnsName === 'string'
329
+ ? magicDnsName.trim().replace(/\.$/, '')
330
+ : '';
331
+ if (!hostname) {
332
+ publicDnsState = null;
333
+ publicDnsStartedAt = 0;
334
+ return;
335
+ }
336
+ publicDnsState = 'pending';
337
+ publicDnsStartedAt = Date.now();
338
+ // Check immediately, then on the interval cadence. The async check
339
+ // schedules its own follow-up, so no timer is armed here.
340
+ void runPublicDnsCheck(myGeneration, hostname);
341
+ };
342
+
233
343
  const setRuntime = (patch) => {
234
344
  status = { ...status, ...patch };
235
345
  };
@@ -432,6 +542,46 @@ export const createTailscaleService = ({
432
542
  return { removed: true };
433
543
  };
434
544
 
545
+ /**
546
+ * Shared identity check for both probe paths: the body must be a JSON
547
+ * object whose `serverId` equals this server's stable id.
548
+ */
549
+ const checkHealthBody = (body, expectedServerId) => {
550
+ const reported = body && typeof body === 'object' ? body.serverId : null;
551
+ return typeof reported === 'string' && reported.length > 0 && reported === expectedServerId;
552
+ };
553
+
554
+ /**
555
+ * Tailnet-path fallback: re-runs the same credential-free `/health`
556
+ * check through `tailscale nc` when the direct fetch threw without an
557
+ * HTTP response (host cannot resolve/reach its own MagicDNS name —
558
+ * userspace networking, non-MagicDNS resolver). A direct HTTP response,
559
+ * even non-OK or mismatched, never reaches here: something answered, so
560
+ * the tailnet path must not override it. Returns true only on a 2xx
561
+ * response whose JSON body carries this server's id.
562
+ */
563
+ const probeUrlOverTailnet = async (url, expectedServerId) => {
564
+ let host = null;
565
+ let port = 443;
566
+ try {
567
+ const parsed = new URL(url);
568
+ host = parsed.hostname || null;
569
+ port = parsed.port ? Number.parseInt(parsed.port, 10) : 443;
570
+ } catch {
571
+ return false;
572
+ }
573
+ if (!host || !Number.isInteger(port) || port <= 0) return false;
574
+ let result = null;
575
+ try {
576
+ result = await effectiveTailnetHealthFetch({ host, port, timeoutMs: TAILSCALE_PROBE_TIMEOUT_MS });
577
+ } catch {
578
+ return false;
579
+ }
580
+ if (!result || result.ok !== true) return false;
581
+ if (!Number.isInteger(result.status) || result.status < 200 || result.status >= 300) return false;
582
+ return checkHealthBody(result.body, expectedServerId);
583
+ };
584
+
435
585
  const probeUrl = async (url) => {
436
586
  // A null/throwing identity fails the probe: the URL stays `starting`
437
587
  // and is never advertised as `active`.
@@ -456,10 +606,12 @@ export const createTailscaleService = ({
456
606
  clearTimeout(timer);
457
607
  if (!response || !response.ok) return false;
458
608
  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;
609
+ return checkHealthBody(body, expectedServerId);
461
610
  } catch {
462
- return false;
611
+ // No HTTP response (DNS/connect/abort on hosts that cannot resolve
612
+ // or reach their own MagicDNS name): retry the identical check over
613
+ // the tailnet path instead of failing the probe.
614
+ return probeUrlOverTailnet(url, expectedServerId);
463
615
  }
464
616
  };
465
617
 
@@ -468,7 +620,7 @@ export const createTailscaleService = ({
468
620
  if (myGeneration !== generation) return;
469
621
  if (elapsed >= PROBE_RETRY_BUDGET_MS || delays.length === 0) {
470
622
  if (myGeneration === generation && status.state === 'starting') {
471
- setRuntime({ state: 'error', errorCode: 'probe_failed', errorMessage: 'The Tailscale URL never answered as this server.' });
623
+ 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
624
  }
473
625
  return;
474
626
  }
@@ -480,6 +632,11 @@ export const createTailscaleService = ({
480
632
  if (myGeneration !== generation) return;
481
633
  if (ok) {
482
634
  setRuntime({ state: 'active', url, approvalUrl: null, errorCode: null, errorMessage: null });
635
+ if (config.mode === 'public') {
636
+ startPublicDnsWatcher(myGeneration, status.magicDnsName);
637
+ } else {
638
+ stopPublicDnsWatcher();
639
+ }
483
640
  return;
484
641
  }
485
642
  scheduleProbeRetries(myGeneration, url, rest, elapsed + delay);
@@ -564,6 +721,7 @@ export const createTailscaleService = ({
564
721
  */
565
722
  const runReconcile = async (myGeneration) => {
566
723
  clearProbeTimer();
724
+ stopPublicDnsWatcher();
567
725
  setRuntime({ approvalUrl: null, errorCode: null, errorMessage: null });
568
726
  const boundPort = getPort();
569
727
  if (!Number.isInteger(boundPort) || boundPort <= 0) {
@@ -707,6 +865,11 @@ export const createTailscaleService = ({
707
865
  if (myGeneration !== generation) return getStatus();
708
866
  if (ok) {
709
867
  setRuntime({ state: 'active', url, approvalUrl: null });
868
+ if (config.mode === 'public') {
869
+ startPublicDnsWatcher(myGeneration, hostInfo.magicDnsName);
870
+ } else {
871
+ stopPublicDnsWatcher();
872
+ }
710
873
  } else {
711
874
  setRuntime({ state: 'starting', url: null });
712
875
  scheduleProbeRetries(myGeneration, url, PROBE_RETRY_DELAYS_MS);
@@ -727,6 +890,11 @@ export const createTailscaleService = ({
727
890
  if (myGeneration !== generation) return getStatus();
728
891
  if (ok) {
729
892
  setRuntime({ state: 'active', url, approvalUrl: null });
893
+ if (config.mode === 'public') {
894
+ startPublicDnsWatcher(myGeneration, hostInfo.magicDnsName);
895
+ } else {
896
+ stopPublicDnsWatcher();
897
+ }
730
898
  } else {
731
899
  // First-use HTTPS/DNS provisioning can take minutes: report starting
732
900
  // and keep re-probing in the background with backoff.
@@ -758,6 +926,12 @@ export const createTailscaleService = ({
758
926
  config: { ...config },
759
927
  state: status.state,
760
928
  url: status.state === 'active' ? status.url : null,
929
+ // Public DNS readiness (Funnel/public `active` only): 'pending' while
930
+ // the public record is not yet visible, 'ready' once found, 'unknown'
931
+ // when the last check failed; null otherwise.
932
+ publicDns: config.mode === 'public' && status.state === 'active'
933
+ ? (publicDnsState ?? 'pending')
934
+ : null,
761
935
  approvalUrl: status.approvalUrl,
762
936
  errorCode: status.errorCode,
763
937
  errorMessage: status.errorMessage,
@@ -847,6 +1021,7 @@ export const createTailscaleService = ({
847
1021
  const shutdown = async () => {
848
1022
  bumpGeneration();
849
1023
  clearProbeTimer();
1024
+ clearPublicDnsTimer();
850
1025
  try {
851
1026
  // Verify ownership before removing: a failed status query leaves the
852
1027
  // mapping (and the record) untouched so the next start's stale
@@ -884,6 +1059,7 @@ export const createTailscaleService = ({
884
1059
  const dispose = () => {
885
1060
  bumpGeneration();
886
1061
  clearProbeTimer();
1062
+ clearPublicDnsTimer();
887
1063
  };
888
1064
 
889
1065
  const getPairingCandidate = () => {