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

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 (59) 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-BWG8peHt.js → DiagramView-CiAfS52a.js} +1 -1
  5. package/dist/assets/{DiffView-C_uRNQMT.js → DiffView-CEAAlJ4b.js} +1 -1
  6. package/dist/assets/{FileSaveConflictDialog-DlH8IWDL.js → FileSaveConflictDialog-yvhJRLj7.js} +1 -1
  7. package/dist/assets/{FilesView-RnF9JBPu.js → FilesView-DAEtByHZ.js} +1 -1
  8. package/dist/assets/{GitHubDetailScaffold-BTRvUnwh.js → GitHubDetailScaffold-CtFeWl_3.js} +1 -1
  9. package/dist/assets/{GitHubLinkPicker-CGi8p2zF.js → GitHubLinkPicker-BEB6WkNO.js} +1 -1
  10. package/dist/assets/{GitHubListPrimitives-XckcmdeA.js → GitHubListPrimitives-BilsEUSt.js} +1 -1
  11. package/dist/assets/{GitView-DyPJ8Oay.js → GitView-C19-aC7A.js} +3 -3
  12. package/dist/assets/{IssuesSurface-rQ78ziEu.js → IssuesSurface-zvICpciG.js} +2 -2
  13. package/dist/assets/{JsonTreeView-Cy5NKUzx.js → JsonTreeView-D99tzKTq.js} +1 -1
  14. package/dist/assets/{MarkdownRendererImpl-C5AlnAbG.js → MarkdownRendererImpl-CRfobHRu.js} +1 -1
  15. package/dist/assets/{PatchDiff-D6048My1.js → PatchDiff-Fbf3Mt_o.js} +1 -1
  16. package/dist/assets/{PierreDiffViewer-_000TWrM.js → PierreDiffViewer-C2nEOax_.js} +1 -1
  17. package/dist/assets/{PullRequestsSurface-eACi4Yxm.js → PullRequestsSurface-DMWgrwmP.js} +2 -2
  18. package/dist/assets/{SessionSwitcherContent-CFMjBIfH.js → SessionSwitcherContent-DByH7H41.js} +1 -1
  19. package/dist/assets/{SessionSwitcherDropdown-CINW_ydZ.js → SessionSwitcherDropdown-D-kE5IJ_.js} +2 -2
  20. package/dist/assets/{SessionUnreadDot-YZJi4IFP.js → SessionUnreadDot-DNbvtMOd.js} +1 -1
  21. package/dist/assets/{SettingsView-DBiQXIji.js → SettingsView-BhXkRsZT.js} +4 -4
  22. package/dist/assets/{SettingsWindow-Wvd56oG1.js → SettingsWindow-B1_mMQyb.js} +1 -1
  23. package/dist/assets/{ToolOutputDialog-DeDXQNWw.js → ToolOutputDialog-BO3d88qF.js} +1 -1
  24. package/dist/assets/{ToolPartDiffPreview-DuN8fldE.js → ToolPartDiffPreview-BgbLfmmd.js} +1 -1
  25. package/dist/assets/{VirtualizedFileDiff-BYVjUxk9.js → VirtualizedFileDiff-D7kxYBDG.js} +1 -1
  26. package/dist/assets/{collapsible-BOcd0lzY.js → collapsible-9MJx4VhA.js} +1 -1
  27. package/dist/assets/{computeVirtualFileMetrics-E4gJTgVF.js → computeVirtualFileMetrics-8pZIB8G2.js} +1 -1
  28. package/dist/assets/{contextFileOpenGuard-CcGZtZsz.js → contextFileOpenGuard-BNtzRA7B.js} +1 -1
  29. package/dist/assets/{gitStatusPredicates-C2H7tf7t.js → gitStatusPredicates-B7adeDSu.js} +1 -1
  30. package/dist/assets/{githubLink-DTEEkgAl.js → githubLink-DVRaj2ms.js} +1 -1
  31. package/dist/assets/{index-BKc_DF05.js → index-B7HgGIB0.js} +1 -1
  32. package/dist/assets/{index-DsQIBAWK.css → index-BwoW_-vk.css} +1 -1
  33. package/dist/assets/{index-DWSrsQWl.js → index-D4n3TVp2.js} +2 -2
  34. package/dist/assets/{main-BNoO2jRw.js → main-BWWBkkNK.js} +4 -4
  35. package/dist/assets/{main-DnCR4Jva.js → main-C-nlfc4f.js} +2 -2
  36. package/dist/assets/{markdownCore-CP1hsIRw.js → markdownCore-B6YzRefV.js} +1 -1
  37. package/dist/assets/{miniChat-BBI_B4OS.js → miniChat-b8DbqBHL.js} +2 -2
  38. package/dist/assets/{mobile-dRWyYBgl.js → mobile-BDDUPrDt.js} +2 -2
  39. package/dist/assets/{nativeFileSave-CFuugNKV.js → nativeFileSave-BJsGPh58.js} +1 -1
  40. package/dist/assets/{pi-session-focus-preference-Cw78V7mw.js → pi-session-focus-preference-gLalTsQo.js} +1 -1
  41. package/dist/assets/{renderDiffWithHighlighter-kdzNWs8-.js → renderDiffWithHighlighter-BamhejwM.js} +1 -1
  42. package/dist/assets/{renderElectronMiniChatApp-uVOQvccp.js → renderElectronMiniChatApp-CiWui-Wg.js} +2 -2
  43. package/dist/assets/{renderFileWithHighlighter-BdeYSXwS.js → renderFileWithHighlighter-CFlqKZg7.js} +1 -1
  44. package/dist/assets/{renderMobileApp-Cdg1IAhJ.js → renderMobileApp-C27Xb0G7.js} +3 -3
  45. package/dist/assets/{runtimeEndpointReset-thviM404.js → runtimeEndpointReset-O-OHpVl7.js} +6 -6
  46. package/dist/assets/{runtimeSurface-Der4qUnI.js → runtimeSurface-k1Eit61v.js} +1 -1
  47. package/dist/assets/{useAppFontEffects-Bd0btzjJ.js → useAppFontEffects-B6Bro-YP.js} +77 -77
  48. package/dist/assets/{useFilesViewSearch-Yvk43YOy.js → useFilesViewSearch-jAAdikwo.js} +1 -1
  49. package/dist/assets/{useGitHubRemoteSearch-BUjSEnXC.js → useGitHubRemoteSearch-BoCzq4zs.js} +1 -1
  50. package/dist/assets/{useSwitcherItems-D2opwbRZ.js → useSwitcherItems-C8IKoSTL.js} +1 -1
  51. package/dist/assets/{web-components-BeROQeen.js → web-components-DTteDmIQ.js} +1 -1
  52. package/dist/index.html +4 -4
  53. package/dist/mini-chat.html +3 -3
  54. package/dist/mobile.html +3 -3
  55. package/package.json +1 -1
  56. package/server/lib/tailscale/DOCUMENTATION.md +34 -5
  57. package/server/lib/tailscale/public-dns.js +72 -0
  58. package/server/lib/tailscale/service.js +126 -3
  59. package/server/lib/tailscale/tailscale.test.js +318 -1
@@ -47,15 +47,25 @@ import {
47
47
  validateTailscaleConfig,
48
48
  } from './tailscale.js';
49
49
  import { createTailscaleNcHealthFetch } from './nc-probe.js';
50
+ import { defaultResolvePublicDns } from './public-dns.js';
50
51
 
51
52
  const TAILSCALE_CONFIG_FILE = 'tailscale-config.json';
52
53
  const TAILSCALE_MAPPING_FILE = 'tailscale-mapping.json';
53
54
 
54
- // Funnel public DNS can take minutes on first use: keep re-probing with
55
- // 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).
56
59
  const PROBE_RETRY_BUDGET_MS = 10 * 60 * 1000;
57
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];
58
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
+
59
69
  // Config/retry HTTP responses wait for reconcile only up to this grace, then
60
70
  // return the current (possibly transitional) status while reconcile
61
71
  // continues in the background. The apply can block for minutes waiting for
@@ -188,6 +198,11 @@ export const createTailscaleService = ({
188
198
  env = process.env,
189
199
  logWarn = (message) => console.warn(message),
190
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,
191
206
  } = {}) => {
192
207
  const effectiveRunner = runner || createDefaultTailscaleRunner({ platform });
193
208
  const executable = resolveTailscaleExecutable({ platform, env, existsSync });
@@ -211,6 +226,12 @@ export const createTailscaleService = ({
211
226
  };
212
227
  let generation = 0;
213
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;
214
235
  // Serializes reconciles: each reconcile starts only after the previous
215
236
  // one settles, so a superseded Off can never remove a mapping after the
216
237
  // newer Private reconcile verified it. The tail swallows rejection so one
@@ -224,7 +245,8 @@ export const createTailscaleService = ({
224
245
  // mapping that is already written is quit-risky, like an active one.
225
246
  let mappingRecordPresent = false;
226
247
 
227
- // 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`).
228
250
  const bumpGeneration = () => {
229
251
  generation += 1;
230
252
  try {
@@ -232,6 +254,10 @@ export const createTailscaleService = ({
232
254
  } catch {
233
255
  }
234
256
  applyAbort = null;
257
+ if (publicDnsTimer) {
258
+ clearTimeout(publicDnsTimer);
259
+ publicDnsTimer = null;
260
+ }
235
261
  };
236
262
 
237
263
  const clearProbeTimer = () => {
@@ -241,6 +267,79 @@ export const createTailscaleService = ({
241
267
  }
242
268
  };
243
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
+
244
343
  const setRuntime = (patch) => {
245
344
  status = { ...status, ...patch };
246
345
  };
@@ -533,6 +632,11 @@ export const createTailscaleService = ({
533
632
  if (myGeneration !== generation) return;
534
633
  if (ok) {
535
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
+ }
536
640
  return;
537
641
  }
538
642
  scheduleProbeRetries(myGeneration, url, rest, elapsed + delay);
@@ -617,6 +721,7 @@ export const createTailscaleService = ({
617
721
  */
618
722
  const runReconcile = async (myGeneration) => {
619
723
  clearProbeTimer();
724
+ stopPublicDnsWatcher();
620
725
  setRuntime({ approvalUrl: null, errorCode: null, errorMessage: null });
621
726
  const boundPort = getPort();
622
727
  if (!Number.isInteger(boundPort) || boundPort <= 0) {
@@ -760,6 +865,11 @@ export const createTailscaleService = ({
760
865
  if (myGeneration !== generation) return getStatus();
761
866
  if (ok) {
762
867
  setRuntime({ state: 'active', url, approvalUrl: null });
868
+ if (config.mode === 'public') {
869
+ startPublicDnsWatcher(myGeneration, hostInfo.magicDnsName);
870
+ } else {
871
+ stopPublicDnsWatcher();
872
+ }
763
873
  } else {
764
874
  setRuntime({ state: 'starting', url: null });
765
875
  scheduleProbeRetries(myGeneration, url, PROBE_RETRY_DELAYS_MS);
@@ -780,6 +890,11 @@ export const createTailscaleService = ({
780
890
  if (myGeneration !== generation) return getStatus();
781
891
  if (ok) {
782
892
  setRuntime({ state: 'active', url, approvalUrl: null });
893
+ if (config.mode === 'public') {
894
+ startPublicDnsWatcher(myGeneration, hostInfo.magicDnsName);
895
+ } else {
896
+ stopPublicDnsWatcher();
897
+ }
783
898
  } else {
784
899
  // First-use HTTPS/DNS provisioning can take minutes: report starting
785
900
  // and keep re-probing in the background with backoff.
@@ -811,6 +926,12 @@ export const createTailscaleService = ({
811
926
  config: { ...config },
812
927
  state: status.state,
813
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,
814
935
  approvalUrl: status.approvalUrl,
815
936
  errorCode: status.errorCode,
816
937
  errorMessage: status.errorMessage,
@@ -900,6 +1021,7 @@ export const createTailscaleService = ({
900
1021
  const shutdown = async () => {
901
1022
  bumpGeneration();
902
1023
  clearProbeTimer();
1024
+ clearPublicDnsTimer();
903
1025
  try {
904
1026
  // Verify ownership before removing: a failed status query leaves the
905
1027
  // mapping (and the record) untouched so the next start's stale
@@ -937,6 +1059,7 @@ export const createTailscaleService = ({
937
1059
  const dispose = () => {
938
1060
  bumpGeneration();
939
1061
  clearProbeTimer();
1062
+ clearPublicDnsTimer();
940
1063
  };
941
1064
 
942
1065
  const getPairingCandidate = () => {
@@ -206,7 +206,7 @@ const TEST_SERVER_ID = 'test-server-id';
206
206
  const matchingFetchImpl = async () => ({ ok: true, status: 200, json: async () => ({ serverId: TEST_SERVER_ID }) });
207
207
 
208
208
  /** In-memory fs + scripted command runner for lifecycle tests. */
209
- const createHarness = ({ handlers, port = 3000, uiPassword = 'secret' } = {}) => {
209
+ const createHarness = ({ handlers, port = 3000, uiPassword = 'secret', resolvePublicDns } = {}) => {
210
210
  const files = new Map();
211
211
  const calls = [];
212
212
  const fsPromises = {
@@ -257,6 +257,9 @@ const createHarness = ({ handlers, port = 3000, uiPassword = 'secret' } = {}) =>
257
257
  // Fail closed by default: no existing test exercises the tailnet path,
258
258
  // and the real `tailscale nc` implementation must never spawn here.
259
259
  tailnetHealthFetch: async () => ({ ok: false, status: null, body: null, error: 'disabled-in-test' }),
260
+ // Never touch real DNS in tests: default to not-found (keeps existing
261
+ // tests unchanged); public-DNS tests inject their own sequence.
262
+ resolvePublicDns: resolvePublicDns || (async () => 'not-found'),
260
263
  logWarn: () => {},
261
264
  });
262
265
  return { service, calls, files, fsPromises };
@@ -1155,6 +1158,7 @@ describe('tailscale crash-restart repoint (record-owned mapping on a new port)',
1155
1158
  fsPromises,
1156
1159
  getServerId: async () => TEST_SERVER_ID,
1157
1160
  fetchImpl: matchingFetchImpl,
1161
+ resolvePublicDns: async () => 'not-found',
1158
1162
  logWarn: () => {},
1159
1163
  });
1160
1164
  await service.loadConfig();
@@ -1905,6 +1909,7 @@ describe('tailscale tailnet-path probe fallback (nc)', () => {
1905
1909
  fallbackCalls.push(args);
1906
1910
  return tailnetHealthFetch(args);
1907
1911
  },
1912
+ resolvePublicDns: async () => 'not-found',
1908
1913
  logWarn: () => {},
1909
1914
  });
1910
1915
  return { service, fallbackCalls };
@@ -2078,3 +2083,315 @@ describe('tailscale nc health fetch', () => {
2078
2083
  children[0].stdin.destroy();
2079
2084
  });
2080
2085
  });
2086
+
2087
+ describe('tailscale public DNS readiness (funnel)', () => {
2088
+ const memFsFor = () => {
2089
+ const memFs = new Map();
2090
+ return {
2091
+ memFs,
2092
+ fsPromises: {
2093
+ readFile: async (p) => {
2094
+ if (!memFs.has(p)) { const e = new Error('x'); e.code = 'ENOENT'; throw e; }
2095
+ return memFs.get(p);
2096
+ },
2097
+ writeFile: async (p, c) => { memFs.set(p, String(c)); },
2098
+ mkdir: async () => {},
2099
+ rename: async (a, b) => { memFs.set(b, memFs.get(a)); memFs.delete(a); },
2100
+ unlink: async (p) => { memFs.delete(p); },
2101
+ },
2102
+ };
2103
+ };
2104
+ const flush = async (rounds = 5) => {
2105
+ for (let i = 0; i < rounds; i += 1) {
2106
+ await Promise.resolve();
2107
+ await new Promise((resolve) => setTimeout(resolve, 0));
2108
+ }
2109
+ };
2110
+ const createPublicService = ({ dnsImpl, mode = 'public' } = {}) => {
2111
+ const { fsPromises } = memFsFor();
2112
+ const dnsCalls = [];
2113
+ const resolvePublicDns = async (hostname) => {
2114
+ dnsCalls.push(hostname);
2115
+ return dnsImpl(hostname);
2116
+ };
2117
+ const service = createTailscaleService({
2118
+ existsSync: () => false,
2119
+ dataDir: '/data',
2120
+ getPort: () => 3000,
2121
+ isUiAuthEnabled: () => true,
2122
+ isUnsafeUnauthenticatedLanAllowed: () => false,
2123
+ runner: {
2124
+ runTailscale: async (args) => {
2125
+ const sub = mode === 'public' ? 'funnel' : 'serve';
2126
+ if (args.includes(sub) && args.includes('status')) {
2127
+ return { ok: true, code: 0, stdout: JSON.stringify({ Web: {} }), stderr: '', spawnError: null, timedOut: false };
2128
+ }
2129
+ if (args.includes('serve') && args.includes('status')) {
2130
+ return { ok: true, code: 0, stdout: JSON.stringify({ Web: {} }), stderr: '', spawnError: null, timedOut: false };
2131
+ }
2132
+ if (args.includes('funnel') && args.includes('status')) {
2133
+ return { ok: true, code: 0, stdout: JSON.stringify({ Web: {} }), stderr: '', spawnError: null, timedOut: false };
2134
+ }
2135
+ return { ok: true, code: 0, stdout: STATUS_JSON, stderr: '', spawnError: null, timedOut: false };
2136
+ },
2137
+ },
2138
+ fsPromises,
2139
+ getServerId: async () => TEST_SERVER_ID,
2140
+ fetchImpl: matchingFetchImpl,
2141
+ resolvePublicDns,
2142
+ logWarn: () => {},
2143
+ });
2144
+ return { service, dnsCalls };
2145
+ };
2146
+
2147
+ it('public active pending -> ready via interval with fake timers, then stops polling', async () => {
2148
+ vi.useFakeTimers();
2149
+ let dnsResult = 'not-found';
2150
+ const { service, dnsCalls } = createPublicService({ dnsImpl: async () => dnsResult });
2151
+ try {
2152
+ await service.loadConfig();
2153
+ const result = await service.setConfig({ enabled: true, mode: 'public', httpsPort: 443 });
2154
+ expect(result.state).toBe('active');
2155
+ // Immediate check runs async: flush it.
2156
+ await vi.advanceTimersByTimeAsync(0);
2157
+ expect(service.getStatus().publicDns).toBe('pending');
2158
+ expect(dnsCalls.length).toBe(1);
2159
+ // Still not found after one interval.
2160
+ await vi.advanceTimersByTimeAsync(30_000);
2161
+ expect(service.getStatus().publicDns).toBe('pending');
2162
+ expect(dnsCalls.length).toBe(2);
2163
+ // Record appears: next interval flips to ready and stops.
2164
+ dnsResult = 'found';
2165
+ await vi.advanceTimersByTimeAsync(30_000);
2166
+ expect(service.getStatus().publicDns).toBe('ready');
2167
+ const callsAtReady = dnsCalls.length;
2168
+ await vi.advanceTimersByTimeAsync(10 * 60_000);
2169
+ expect(dnsCalls.length).toBe(callsAtReady);
2170
+ expect(service.getStatus().publicDns).toBe('ready');
2171
+ } finally {
2172
+ service.dispose();
2173
+ vi.useRealTimers();
2174
+ }
2175
+ });
2176
+
2177
+ it('error maps to unknown and recovers to pending then ready', async () => {
2178
+ vi.useFakeTimers();
2179
+ let dnsResult = 'error';
2180
+ const { service, dnsCalls } = createPublicService({ dnsImpl: async () => dnsResult });
2181
+ try {
2182
+ await service.loadConfig();
2183
+ await service.setConfig({ enabled: true, mode: 'public', httpsPort: 443 });
2184
+ await vi.advanceTimersByTimeAsync(0);
2185
+ expect(service.getStatus().publicDns).toBe('unknown');
2186
+ dnsResult = 'not-found';
2187
+ await vi.advanceTimersByTimeAsync(30_000);
2188
+ expect(service.getStatus().publicDns).toBe('pending');
2189
+ dnsResult = 'found';
2190
+ await vi.advanceTimersByTimeAsync(30_000);
2191
+ expect(service.getStatus().publicDns).toBe('ready');
2192
+ expect(dnsCalls.length).toBeGreaterThanOrEqual(3);
2193
+ } finally {
2194
+ service.dispose();
2195
+ vi.useRealTimers();
2196
+ }
2197
+ });
2198
+
2199
+ it('private active never queries DNS and reports null', async () => {
2200
+ const { service, dnsCalls } = createPublicService({ dnsImpl: async () => 'found', mode: 'private' });
2201
+ try {
2202
+ await service.loadConfig();
2203
+ const result = await service.setConfig({ enabled: true, mode: 'private', httpsPort: 443 });
2204
+ expect(result.state).toBe('active');
2205
+ expect(result.publicDns).toBeNull();
2206
+ await flush();
2207
+ expect(dnsCalls).toEqual([]);
2208
+ expect(service.getStatus().publicDns).toBeNull();
2209
+ } finally {
2210
+ service.dispose();
2211
+ }
2212
+ });
2213
+
2214
+ it('non-active states report null (off)', async () => {
2215
+ const { service } = createHarness({
2216
+ handlers: {
2217
+ 'status --json': { ok: true, code: 0, stdout: STATUS_JSON, stderr: '', spawnError: null, timedOut: false },
2218
+ },
2219
+ });
2220
+ try {
2221
+ await service.loadConfig();
2222
+ expect(service.getStatus().publicDns).toBeNull();
2223
+ const off = await service.reconcile();
2224
+ expect(off.state).toBe('off');
2225
+ expect(off.publicDns).toBeNull();
2226
+ } finally {
2227
+ service.dispose();
2228
+ }
2229
+ });
2230
+
2231
+ it('mode switch public->private stops the watcher and reports null', async () => {
2232
+ vi.useFakeTimers();
2233
+ let dnsResult = 'not-found';
2234
+ const { service, dnsCalls } = createPublicService({ dnsImpl: async () => dnsResult });
2235
+ try {
2236
+ await service.loadConfig();
2237
+ await service.setConfig({ enabled: true, mode: 'public', httpsPort: 443 });
2238
+ await vi.advanceTimersByTimeAsync(0);
2239
+ expect(service.getStatus().publicDns).toBe('pending');
2240
+ const callsBefore = dnsCalls.length;
2241
+ await service.setConfig({ enabled: true, mode: 'private', httpsPort: 443 });
2242
+ expect(service.getStatus().publicDns).toBeNull();
2243
+ await vi.advanceTimersByTimeAsync(5 * 60_000);
2244
+ expect(dnsCalls.length).toBe(callsBefore);
2245
+ expect(service.getStatus().publicDns).toBeNull();
2246
+ } finally {
2247
+ service.dispose();
2248
+ vi.useRealTimers();
2249
+ }
2250
+ });
2251
+
2252
+ it('disable stops the watcher; a stale resolve never writes after the generation bump', async () => {
2253
+ let releaseDns = null;
2254
+ const gate = new Promise((resolve) => { releaseDns = resolve; });
2255
+ const { fsPromises } = memFsFor();
2256
+ const dnsCalls = [];
2257
+ const service = createTailscaleService({
2258
+ existsSync: () => false,
2259
+ dataDir: '/data',
2260
+ getPort: () => 3000,
2261
+ isUiAuthEnabled: () => true,
2262
+ isUnsafeUnauthenticatedLanAllowed: () => false,
2263
+ runner: {
2264
+ runTailscale: async (args) => {
2265
+ if (args.includes('funnel') && args.includes('status')) {
2266
+ return { ok: true, code: 0, stdout: JSON.stringify({ Web: {} }), stderr: '', spawnError: null, timedOut: false };
2267
+ }
2268
+ if (args.includes('serve') && args.includes('status')) {
2269
+ return { ok: true, code: 0, stdout: JSON.stringify({ Web: {} }), stderr: '', spawnError: null, timedOut: false };
2270
+ }
2271
+ return { ok: true, code: 0, stdout: STATUS_JSON, stderr: '', spawnError: null, timedOut: false };
2272
+ },
2273
+ },
2274
+ fsPromises,
2275
+ getServerId: async () => TEST_SERVER_ID,
2276
+ fetchImpl: matchingFetchImpl,
2277
+ resolvePublicDns: async (hostname) => {
2278
+ dnsCalls.push(hostname);
2279
+ await gate;
2280
+ return 'found';
2281
+ },
2282
+ logWarn: () => {},
2283
+ });
2284
+ try {
2285
+ await service.loadConfig();
2286
+ const active = await service.setConfig({ enabled: true, mode: 'public', httpsPort: 443 });
2287
+ expect(active.state).toBe('active');
2288
+ expect(active.publicDns).toBe('pending');
2289
+ // Bump the generation while the immediate DNS check is in flight.
2290
+ const disabled = await service.setConfig({ enabled: false });
2291
+ expect(disabled.state).toBe('off');
2292
+ expect(disabled.publicDns).toBeNull();
2293
+ // Late DNS success must not resurrect publicDns.
2294
+ releaseDns();
2295
+ await flush(10);
2296
+ expect(service.getStatus().state).toBe('off');
2297
+ expect(service.getStatus().publicDns).toBeNull();
2298
+ } finally {
2299
+ try { releaseDns?.(); } catch {}
2300
+ service.dispose();
2301
+ }
2302
+ });
2303
+
2304
+ it('shutdown stops the watcher: no further resolver calls', async () => {
2305
+ vi.useFakeTimers();
2306
+ let dnsResult = 'not-found';
2307
+ const { service, dnsCalls } = createPublicService({ dnsImpl: async () => dnsResult });
2308
+ try {
2309
+ await service.loadConfig();
2310
+ await service.setConfig({ enabled: true, mode: 'public', httpsPort: 443 });
2311
+ await vi.advanceTimersByTimeAsync(0);
2312
+ expect(service.getStatus().publicDns).toBe('pending');
2313
+ const callsBefore = dnsCalls.length;
2314
+ await service.shutdown();
2315
+ await vi.advanceTimersByTimeAsync(5 * 60_000);
2316
+ expect(dnsCalls.length).toBe(callsBefore);
2317
+ } finally {
2318
+ service.dispose();
2319
+ vi.useRealTimers();
2320
+ }
2321
+ });
2322
+
2323
+ it('interval backs off to 2 minutes after 20 minutes', async () => {
2324
+ vi.useFakeTimers();
2325
+ const { service, dnsCalls } = createPublicService({ dnsImpl: async () => 'not-found' });
2326
+ try {
2327
+ await service.loadConfig();
2328
+ await service.setConfig({ enabled: true, mode: 'public', httpsPort: 443 });
2329
+ await vi.advanceTimersByTimeAsync(0);
2330
+ expect(dnsCalls.length).toBe(1);
2331
+ // 30s cadence for the first 20 minutes: 40 intervals reach t=20min.
2332
+ for (let i = 0; i < 40; i += 1) {
2333
+ await vi.advanceTimersByTimeAsync(30_000);
2334
+ }
2335
+ const callsAt20min = dnsCalls.length;
2336
+ expect(callsAt20min).toBe(1 + 40);
2337
+ // After 20 minutes the cadence is 2 minutes: +30s is not enough.
2338
+ await vi.advanceTimersByTimeAsync(30_000);
2339
+ expect(dnsCalls.length).toBe(callsAt20min);
2340
+ await vi.advanceTimersByTimeAsync(90_000);
2341
+ expect(dnsCalls.length).toBe(callsAt20min + 1);
2342
+ } finally {
2343
+ service.dispose();
2344
+ vi.useRealTimers();
2345
+ }
2346
+ });
2347
+ });
2348
+
2349
+ describe('public-dns resolver mapping', () => {
2350
+ it('maps answers, NXDOMAIN/NODATA, and failures without touching the network', async () => {
2351
+ const { createResolvePublicDns } = await import('./public-dns.js');
2352
+ const scripted = ({ v4, v6 }) => {
2353
+ const calls = [];
2354
+ const resolve = createResolvePublicDns({
2355
+ createResolver: () => ({
2356
+ setServers: () => {},
2357
+ cancel: () => {},
2358
+ resolve4: async () => {
2359
+ calls.push('v4');
2360
+ if (v4 instanceof Error) throw v4;
2361
+ return v4;
2362
+ },
2363
+ resolve6: async () => {
2364
+ calls.push('v6');
2365
+ if (v6 instanceof Error) throw v6;
2366
+ return v6;
2367
+ },
2368
+ }),
2369
+ });
2370
+ return { resolve, calls };
2371
+ };
2372
+ const notFound4 = Object.assign(new Error('queryA ENOTFOUND m.ts.net'), { code: 'ENOTFOUND' });
2373
+ const noData6 = Object.assign(new Error('queryAaaa ENODATA m.ts.net'), { code: 'ENODATA' });
2374
+ // Any address -> found.
2375
+ {
2376
+ const { resolve: resolveFound } = scripted({ v4: ['93.184.216.34'], v6: noData6 });
2377
+ expect(await resolveFound('m.ts.net')).toBe('found');
2378
+ }
2379
+ // All NXDOMAIN/NODATA -> not-found.
2380
+ {
2381
+ const { resolve: resolveNotFound } = scripted({ v4: notFound4, v6: noData6 });
2382
+ expect(await resolveNotFound('m.ts.net')).toBe('not-found');
2383
+ }
2384
+ // Timeout/refused -> error.
2385
+ {
2386
+ const timeout = Object.assign(new Error('queryA ETIMEOUT m.ts.net'), { code: 'ETIMEOUT' });
2387
+ const { resolve: resolveError } = scripted({ v4: timeout, v6: noData6 });
2388
+ expect(await resolveError('m.ts.net')).toBe('error');
2389
+ }
2390
+ // Never throws on bad input.
2391
+ {
2392
+ const { resolve: resolveBad } = scripted({ v4: ['1.1.1.1'], v6: ['::1'] });
2393
+ expect(await resolveBad('')).toBe('error');
2394
+ expect(await resolveBad(null)).toBe('error');
2395
+ }
2396
+ });
2397
+ });