@pi-chamber/web 1.0.4 → 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 (205) hide show
  1. package/README.md +1 -1
  2. package/bin/cli.js +21 -2
  3. package/bin/cli.test.js +164 -4
  4. package/bin/lib/DOCUMENTATION.md +3 -3
  5. package/bin/lib/cli-args.js +96 -13
  6. package/bin/lib/commands-connect-url-tailscale.test.js +136 -0
  7. package/bin/lib/commands-connect-url.js +146 -39
  8. package/bin/lib/commands-connect-url.test.js +126 -0
  9. package/bin/lib/commands-serve.js +45 -2
  10. package/bin/lib/commands-status.js +28 -5
  11. package/bin/lib/commands-status.test.js +107 -0
  12. package/bin/lib/commands-tunnel.js +36 -10
  13. package/dist/assets/{DiagramView-BpG1c3Hi.js → DiagramView-BWG8peHt.js} +1 -1
  14. package/dist/assets/DiffView-C_uRNQMT.js +18 -0
  15. package/dist/assets/{FileSaveConflictDialog-DP7k9a-i.js → FileSaveConflictDialog-DlH8IWDL.js} +2 -2
  16. package/dist/assets/FilesView-RnF9JBPu.js +6 -0
  17. package/dist/assets/{GitHubDetailScaffold-UxLAMAOl.js → GitHubDetailScaffold-BTRvUnwh.js} +2 -2
  18. package/dist/assets/{GitHubLinkPicker-Bh9RO1yK.js → GitHubLinkPicker-CGi8p2zF.js} +1 -1
  19. package/dist/assets/{GitHubListPrimitives-DQyhT5wG.js → GitHubListPrimitives-XckcmdeA.js} +1 -1
  20. package/dist/assets/{GitView-XBBheKRM.js → GitView-DyPJ8Oay.js} +4 -4
  21. package/dist/assets/{IssuesSurface-BA1kpvAJ.js → IssuesSurface-rQ78ziEu.js} +3 -3
  22. package/dist/assets/{JsonTreeView-BAaEPL4O.js → JsonTreeView-Cy5NKUzx.js} +1 -1
  23. package/dist/assets/{MarkdownRendererImpl-DzgDmUsL.js → MarkdownRendererImpl-C5AlnAbG.js} +1 -1
  24. package/dist/assets/{PatchDiff-BMEUsgXH.js → PatchDiff-D6048My1.js} +1 -1
  25. package/dist/assets/PierreDiffViewer-_000TWrM.js +135 -0
  26. package/dist/assets/PullRequestsSurface-eACi4Yxm.js +2 -0
  27. package/dist/assets/SessionSwitcherContent-CFMjBIfH.js +1 -0
  28. package/dist/assets/SessionSwitcherDropdown-CINW_ydZ.js +2 -0
  29. package/dist/assets/SessionUnreadDot-YZJi4IFP.js +1 -0
  30. package/dist/assets/SettingsView-DBiQXIji.js +6 -0
  31. package/dist/assets/{SettingsWindow-j0e99YI0.js → SettingsWindow-Wvd56oG1.js} +1 -1
  32. package/dist/assets/StickyHorizontalScrollbar-BMITjK4e.js +8 -0
  33. package/dist/assets/{ToolOutputDialog-VlS12Xyq.js → ToolOutputDialog-DeDXQNWw.js} +4 -4
  34. package/dist/assets/{ToolPartDiffPreview-DdSneZws.js → ToolPartDiffPreview-DuN8fldE.js} +1 -1
  35. package/dist/assets/{VirtualizedFileDiff-BqiXjvP6.js → VirtualizedFileDiff-BYVjUxk9.js} +4 -4
  36. package/dist/assets/{Virtualizer-Cp_cJWbI.js → Virtualizer-DP6HbEeC.js} +1 -1
  37. package/dist/assets/{collapsible-C7oyikVm.js → collapsible-BOcd0lzY.js} +1 -1
  38. package/dist/assets/{computeVirtualFileMetrics-BJjC-tXV.js → computeVirtualFileMetrics-E4gJTgVF.js} +1 -1
  39. package/dist/assets/{contextFileOpenGuard-BBzqKGei.js → contextFileOpenGuard-CcGZtZsz.js} +1 -1
  40. package/dist/assets/{gitStatusPredicates-Dq-E5DaH.js → gitStatusPredicates-C2H7tf7t.js} +1 -1
  41. package/dist/assets/{githubLink-Cryd7GkG.js → githubLink-DTEEkgAl.js} +5 -5
  42. package/dist/assets/{index-BbhXFTId.js → index-BKc_DF05.js} +1 -1
  43. package/dist/assets/index-DWSrsQWl.js +11 -0
  44. package/dist/assets/index-DsQIBAWK.css +1 -0
  45. package/dist/assets/main-BNoO2jRw.js +136 -0
  46. package/dist/assets/main-DnCR4Jva.js +2 -0
  47. package/dist/assets/{markdownCore-B9AuEyYi.js → markdownCore-CP1hsIRw.js} +2 -2
  48. package/dist/assets/{miniChat-CgOaJfD8.js → miniChat-BBI_B4OS.js} +2 -2
  49. package/dist/assets/mobile-dRWyYBgl.js +2 -0
  50. package/dist/assets/{nativeFileSave-BzhtrDoD.js → nativeFileSave-CFuugNKV.js} +1 -1
  51. package/dist/assets/pi-session-focus-preference-Cw78V7mw.js +9 -0
  52. package/dist/assets/{renderDiffWithHighlighter-CVLsdtQ5.js → renderDiffWithHighlighter-kdzNWs8-.js} +1 -1
  53. package/dist/assets/renderElectronMiniChatApp-uVOQvccp.js +2 -0
  54. package/dist/assets/{renderFileWithHighlighter-DJ9mk2bZ.js → renderFileWithHighlighter-BdeYSXwS.js} +1 -1
  55. package/dist/assets/renderMobileApp-Cdg1IAhJ.js +11 -0
  56. package/dist/assets/runtimeEndpointReset-thviM404.js +62 -0
  57. package/dist/assets/{runtimeSurface-DBiUWYK2.js → runtimeSurface-Der4qUnI.js} +1 -1
  58. package/dist/assets/useAppFontEffects-Bd0btzjJ.js +212 -0
  59. package/dist/assets/{useFilesViewSearch-D2Au5Xgt.js → useFilesViewSearch-Yvk43YOy.js} +3 -3
  60. package/dist/assets/useGitHubRemoteSearch-BUjSEnXC.js +1 -0
  61. package/dist/assets/{useSwitcherItems-Dej8BzXI.js → useSwitcherItems-D2opwbRZ.js} +1 -1
  62. package/dist/assets/{vendor-aparajita-capacitor-secure-storage-BYohCVY0.js → vendor-aparajita-capacitor-secure-storage-BDrMx_CE.js} +1 -1
  63. package/dist/assets/{vendor-base-ui-BscvGUFt.js → vendor-base-ui-CKRUCG-f.js} +1 -1
  64. package/dist/assets/{vendor-boot-Dgb9NVFe.js → vendor-boot-EC6IyLt1.js} +13 -13
  65. package/dist/assets/{vendor-capacitor-app-BjdQVib9.js → vendor-capacitor-app-BaupizkW.js} +1 -1
  66. package/dist/assets/{vendor-capacitor-keyboard-eTtI5go3.js → vendor-capacitor-keyboard-9BVxykO7.js} +1 -1
  67. package/dist/assets/{vendor-capacitor-status-bar-9rNIGxlO.js → vendor-capacitor-status-bar-BsrUwiaA.js} +1 -1
  68. package/dist/assets/{vendor-codemirror-autocomplete-DxS3jwvE.js → vendor-codemirror-autocomplete-CGpAsPWp.js} +1 -1
  69. package/dist/assets/{vendor-codemirror-lang-angular-DdjXl9e2.js → vendor-codemirror-lang-angular-CDJoHJSY.js} +1 -1
  70. package/dist/assets/{vendor-codemirror-lang-cpp--aMr7NVt.js → vendor-codemirror-lang-cpp-BmHofQls.js} +1 -1
  71. package/dist/assets/{vendor-codemirror-lang-css-CZ_qxZY9.js → vendor-codemirror-lang-css-RM2HqXZ0.js} +1 -1
  72. package/dist/assets/{vendor-codemirror-lang-go-Ca-y2Alu.js → vendor-codemirror-lang-go-Crwca_X7.js} +1 -1
  73. package/dist/assets/{vendor-codemirror-lang-html-COZ0L5wT.js → vendor-codemirror-lang-html-CHSHUpwq.js} +1 -1
  74. package/dist/assets/{vendor-codemirror-lang-java-D3Rf3QNJ.js → vendor-codemirror-lang-java-lhQXgWu0.js} +1 -1
  75. package/dist/assets/{vendor-codemirror-lang-javascript-DwJ-IvCs.js → vendor-codemirror-lang-javascript-Dw4kFO4e.js} +1 -1
  76. package/dist/assets/{vendor-codemirror-lang-jinja-D_5lod6k.js → vendor-codemirror-lang-jinja-_pAC3UTN.js} +1 -1
  77. package/dist/assets/{vendor-codemirror-lang-json-BG8C7OpC.js → vendor-codemirror-lang-json-B-b1vAv-.js} +1 -1
  78. package/dist/assets/{vendor-codemirror-lang-less-CVEkoaTw.js → vendor-codemirror-lang-less-xIgOi1ze.js} +1 -1
  79. package/dist/assets/{vendor-codemirror-lang-liquid-U9vj0m8w.js → vendor-codemirror-lang-liquid-CP49m5dB.js} +1 -1
  80. package/dist/assets/{vendor-codemirror-lang-markdown-DqlYH9gY.js → vendor-codemirror-lang-markdown-BTht2ATe.js} +1 -1
  81. package/dist/assets/{vendor-codemirror-lang-php-BFEiEVA1.js → vendor-codemirror-lang-php-BguZDhaO.js} +1 -1
  82. package/dist/assets/{vendor-codemirror-lang-python-Cz1dQXQd.js → vendor-codemirror-lang-python-CH6_em9L.js} +1 -1
  83. package/dist/assets/{vendor-codemirror-lang-rust-C_CoD9mj.js → vendor-codemirror-lang-rust-EG_DtGyi.js} +1 -1
  84. package/dist/assets/{vendor-codemirror-lang-sass-BuR0aKh5.js → vendor-codemirror-lang-sass-BknY5Qpo.js} +1 -1
  85. package/dist/assets/{vendor-codemirror-lang-sql-DggNUjdM.js → vendor-codemirror-lang-sql-B0f-qCZo.js} +1 -1
  86. package/dist/assets/{vendor-codemirror-lang-vue-DFZHi2J3.js → vendor-codemirror-lang-vue-CyGn9snv.js} +1 -1
  87. package/dist/assets/{vendor-codemirror-lang-wast-zuTN3SHT.js → vendor-codemirror-lang-wast-CsFfSyyB.js} +1 -1
  88. package/dist/assets/{vendor-codemirror-lang-xml-CrcvhI-k.js → vendor-codemirror-lang-xml-Cdan_Jp1.js} +1 -1
  89. package/dist/assets/{vendor-codemirror-lang-yaml-DcVWsakb.js → vendor-codemirror-lang-yaml-COI5hck8.js} +1 -1
  90. package/dist/assets/{vendor-codemirror-language-data-CCLITgCF.js → vendor-codemirror-language-data-CqU7kHmg.js} +2 -2
  91. package/dist/assets/{vendor-codemirror-search-H7NOEdbX.js → vendor-codemirror-search-DUfSCF9S.js} +1 -1
  92. package/dist/assets/{vendor-lezer-cpp-C8aD2KAr.js → vendor-lezer-cpp-DMZOJzBa.js} +1 -1
  93. package/dist/assets/{vendor-lezer-css-2lbTJF-Y.js → vendor-lezer-css-DUkkbMp7.js} +1 -1
  94. package/dist/assets/{vendor-lezer-go-Bw6LFTrZ.js → vendor-lezer-go-CHIhCNY6.js} +1 -1
  95. package/dist/assets/{vendor-lezer-html-D7ym2z7S.js → vendor-lezer-html-B3h0MOrG.js} +1 -1
  96. package/dist/assets/{vendor-lezer-java-CZhK7w21.js → vendor-lezer-java-tMazV_6X.js} +1 -1
  97. package/dist/assets/{vendor-lezer-javascript-rpKeTHZp.js → vendor-lezer-javascript-ctwLWf4v.js} +1 -1
  98. package/dist/assets/{vendor-lezer-json-C7jwsd2G.js → vendor-lezer-json-BP_UAzLL.js} +1 -1
  99. package/dist/assets/{vendor-lezer-lr-DR-ylqNN.js → vendor-lezer-lr-B8TQctNw.js} +1 -1
  100. package/dist/assets/{vendor-lezer-markdown-Bir0m5nB.js → vendor-lezer-markdown-aGLZf_3h.js} +1 -1
  101. package/dist/assets/{vendor-lezer-php-y0hIEfo1.js → vendor-lezer-php-D5zCNzlt.js} +1 -1
  102. package/dist/assets/{vendor-lezer-python-D64A9lNV.js → vendor-lezer-python-EJ4Im4y2.js} +1 -1
  103. package/dist/assets/{vendor-lezer-rust-E3ZA9T2L.js → vendor-lezer-rust-DO5c7OtA.js} +1 -1
  104. package/dist/assets/{vendor-lezer-sass-C5UFI9SP.js → vendor-lezer-sass-CMi6zfXI.js} +1 -1
  105. package/dist/assets/{vendor-lezer-xml-DOy7FzCR.js → vendor-lezer-xml-0MHMeZDp.js} +1 -1
  106. package/dist/assets/{vendor-lezer-yaml-kEjaSCvZ.js → vendor-lezer-yaml-BE2EFjpA.js} +1 -1
  107. package/dist/assets/{vendor-replit-codemirror-vim-BLfh0LPy.js → vendor-replit-codemirror-vim-AnOuN8yJ.js} +1 -1
  108. package/dist/assets/{web-components-C7CmoFxi.js → web-components-BeROQeen.js} +3 -3
  109. package/dist/index.html +4 -4
  110. package/dist/mini-chat.html +3 -3
  111. package/dist/mobile.html +3 -3
  112. package/dist/sw.js +1 -1
  113. package/package.json +1 -2
  114. package/server/index.js +72 -30
  115. package/server/lib/client-auth/DOCUMENTATION.md +15 -1
  116. package/server/lib/client-auth/pairing.js +2 -12
  117. package/server/lib/client-auth/remote-clients.js +2 -12
  118. package/server/lib/cloudflare-tunnel.js +0 -132
  119. package/server/lib/fs/DOCUMENTATION.md +8 -0
  120. package/server/lib/fs/atomic-write.js +111 -0
  121. package/server/lib/fs/atomic-write.test.js +133 -0
  122. package/server/lib/notifications/DOCUMENTATION.md +43 -32
  123. package/server/lib/notifications/pi-notification-watcher.js +8 -7
  124. package/server/lib/notifications/pi-notification-watcher.test.js +88 -2
  125. package/server/lib/pi/routes-extension-events.test.js +231 -0
  126. package/server/lib/pi/routes.js +137 -4
  127. package/server/lib/pi/routes.test.js +248 -2
  128. package/server/lib/pi/session-daemon/DOCUMENTATION.md +17 -4
  129. package/server/lib/pi/session-daemon/daemon-process.js +2 -0
  130. package/server/lib/pi/session-daemon/engines/index.js +6 -0
  131. package/server/lib/pi/session-daemon/extension-bridge-draft.test.js +1 -1
  132. package/server/lib/pi/session-daemon/extension-bridge.js +24 -0
  133. package/server/lib/pi/session-daemon/extension-message-render.js +74 -0
  134. package/server/lib/pi/session-daemon/extension-message-render.test.js +164 -0
  135. package/server/lib/pi/session-daemon/extension-tool-render.js +13 -6
  136. package/server/lib/pi/session-daemon/pending-input.js +188 -0
  137. package/server/lib/pi/session-daemon/pending-input.test.js +202 -0
  138. package/server/lib/pi/session-daemon/session-daemon-engines.test.js +828 -0
  139. package/server/lib/pi/session-daemon/session-daemon-extensions.test.js +296 -6
  140. package/server/lib/pi/session-daemon/session-daemon-turn.e2e.test.js +9 -0
  141. package/server/lib/pi/session-daemon/session-daemon.js +219 -19
  142. package/server/lib/pi/session-daemon/session-daemon.test.js +30 -2
  143. package/server/lib/pi/session-daemon/session-engine-router.js +390 -0
  144. package/server/lib/pi/session-daemon/session-engine-router.test.js +515 -0
  145. package/server/lib/pi/session-daemon/session-engines.js +467 -0
  146. package/server/lib/pi/session-daemon/session-engines.test.js +383 -0
  147. package/server/lib/pi/snippets-store.js +8 -17
  148. package/server/lib/pi/ui-settings-store.js +6 -10
  149. package/server/lib/pi/ui-settings-store.test.js +37 -1
  150. package/server/lib/relay/DOCUMENTATION.md +6 -4
  151. package/server/lib/relay/identity-store.js +116 -0
  152. package/server/lib/relay/identity-store.test.js +169 -0
  153. package/server/lib/relay/identity.js +6 -4
  154. package/server/lib/relay/server-id.js +63 -0
  155. package/server/lib/relay/server-id.test.js +132 -0
  156. package/server/lib/relay/signing-key.js +14 -11
  157. package/server/lib/security/bind-host.js +6 -2
  158. package/server/lib/security/bind-host.test.js +17 -0
  159. package/server/lib/server/core-routes.js +27 -1
  160. package/server/lib/server/lan-addresses.js +18 -6
  161. package/server/lib/server/lan-addresses.test.js +28 -0
  162. package/server/lib/server/tunnel-auth.js +47 -7
  163. package/server/lib/server/tunnel-auth.rate-limit.test.js +164 -0
  164. package/server/lib/server/tunnel-service.DOCUMENTATION.md +3 -4
  165. package/server/lib/server/tunnel-service.js +23 -20
  166. package/server/lib/server/tunnel-service.test.js +19 -2
  167. package/server/lib/stt/config-store.js +5 -15
  168. package/server/lib/tailscale/DOCUMENTATION.md +285 -0
  169. package/server/lib/tailscale/nc-probe.js +220 -0
  170. package/server/lib/tailscale/routes.js +45 -0
  171. package/server/lib/tailscale/service.js +1012 -0
  172. package/server/lib/tailscale/tailscale.js +302 -0
  173. package/server/lib/tailscale/tailscale.test.js +2080 -0
  174. package/server/lib/tunnels/DOCUMENTATION.md +3 -4
  175. package/server/lib/tunnels/providers/cloudflare.js +1 -22
  176. package/server/lib/tunnels/types.js +0 -2
  177. package/server/lib/ui-auth/DOCUMENTATION.md +31 -0
  178. package/server/lib/ui-auth/ui-auth.js +80 -6
  179. package/server/lib/ui-auth/ui-auth.test.js +136 -0
  180. package/server/lib/ui-auth/ui-passkeys.js +2 -13
  181. package/server/lib/update-job-store.js +4 -6
  182. package/dist/assets/DiffView-BxwoRCYx.js +0 -18
  183. package/dist/assets/FilesView-D_2QcdUt.js +0 -6
  184. package/dist/assets/PierreDiffViewer-BW8MO-O6.js +0 -134
  185. package/dist/assets/PullRequestsSurface-B3ictm4I.js +0 -2
  186. package/dist/assets/SessionSwitcherContent-rLoyVqgs.js +0 -1
  187. package/dist/assets/SessionSwitcherDropdown-CfySKnUu.js +0 -2
  188. package/dist/assets/SessionUnreadDot-CmEF9sxM.js +0 -1
  189. package/dist/assets/SettingsView-BiwlwnTK.js +0 -6
  190. package/dist/assets/index-BnZVqcki.js +0 -11
  191. package/dist/assets/index-BnieExes.css +0 -1
  192. package/dist/assets/main-9O5IAtT_.js +0 -136
  193. package/dist/assets/main-DWGwALIw.js +0 -2
  194. package/dist/assets/mobile-BbJcYVym.js +0 -2
  195. package/dist/assets/pi-session-focus-preference-Bmk1iOvn.js +0 -10
  196. package/dist/assets/renderElectronMiniChatApp-R5o9NwFC.js +0 -2
  197. package/dist/assets/renderMobileApp-CQ9tWYIj.js +0 -11
  198. package/dist/assets/runtimeEndpointReset-CtK4C_5h.js +0 -62
  199. package/dist/assets/useAppFontEffects-DviRbaCJ.js +0 -212
  200. package/dist/assets/useGitHubRemoteSearch-D-K7aolk.js +0 -1
  201. package/dist/assets/vendor-capacitor-push-notifications-CBKq2Arn.js +0 -1
  202. package/server/lib/notifications/delivery-runtime.js +0 -314
  203. package/server/lib/notifications/delivery-runtime.test.js +0 -85
  204. package/server/lib/notifications/routes.js +0 -74
  205. package/server/lib/relay/service.js +0 -9
@@ -0,0 +1,1012 @@
1
+ /**
2
+ * Tailscale remote-access lifecycle owner.
3
+ *
4
+ * Applies `tailscale serve` (private, tailnet-only) or `tailscale funnel`
5
+ * (public) mappings to `http://127.0.0.1:<boundPort>` while PiChamber runs,
6
+ * and removes them on graceful shutdown. Applying/removing failures log a
7
+ * warning and never block startup or shutdown (bounded timeouts).
8
+ *
9
+ * Crash safety: the mapping PiChamber created is recorded in
10
+ * `tailscale-mapping.json` in the PiChamber data dir. On the next start a
11
+ * stale record is removed/repointed. A mapping PiChamber did not create is
12
+ * NEVER removed or overwritten: `tailscale serve status --json` is inspected
13
+ * first, and a foreign mapping on the target port reports `conflict`.
14
+ *
15
+ * All process execution goes through the injected `runner` (argument arrays,
16
+ * no shell, bounded timeouts) so unit tests can inject a fake. The default
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.
21
+ */
22
+
23
+ import { spawn } from 'node:child_process';
24
+ import fs from 'node:fs';
25
+ import path from 'node:path';
26
+
27
+ import {
28
+ TAILSCALE_APPLY_TIMEOUT_MS,
29
+ TAILSCALE_APPROVAL_WAIT_MS,
30
+ TAILSCALE_DEFAULT_HTTPS_PORT,
31
+ TAILSCALE_DEFAULT_MODE,
32
+ TAILSCALE_PROBE_TIMEOUT_MS,
33
+ TAILSCALE_REMOVE_TIMEOUT_MS,
34
+ TAILSCALE_STATUS_TIMEOUT_MS,
35
+ buildTailscaleRemoveArgs,
36
+ buildTailscaleServeArgs,
37
+ buildTailscaleUrl,
38
+ checkTailscaleAuthGate,
39
+ classifyApplyFailure,
40
+ classifyServeMapping,
41
+ conflictMessageForPort,
42
+ extractApprovalUrl,
43
+ findServeMappingForPort,
44
+ normalizeTailscaleConfig,
45
+ parseTailscaleStatus,
46
+ resolveTailscaleExecutable,
47
+ validateTailscaleConfig,
48
+ } from './tailscale.js';
49
+ import { createTailscaleNcHealthFetch } from './nc-probe.js';
50
+
51
+ const TAILSCALE_CONFIG_FILE = 'tailscale-config.json';
52
+ const TAILSCALE_MAPPING_FILE = 'tailscale-mapping.json';
53
+
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.
56
+ const PROBE_RETRY_BUDGET_MS = 10 * 60 * 1000;
57
+ 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
+
59
+ // Config/retry HTTP responses wait for reconcile only up to this grace, then
60
+ // return the current (possibly transitional) status while reconcile
61
+ // continues in the background. The apply can block for minutes waiting for
62
+ // tailnet approval, and callers (CLI `pair --tailscale`, the UI hook) poll
63
+ // `GET /status` until a terminal state.
64
+ const CONFIG_RESPONSE_GRACE_MS = 3_000;
65
+ // Shutdown runs its status query and removal under tighter bounds than
66
+ // reconcile: together they must finish inside Electron's quit timeout
67
+ // (`QUIT_SERVER_STOP_TIMEOUT_MS`, 8s, packages/electron/quit-server-stop.mjs),
68
+ // or the app exits mid-removal and orphans the mapping. A timeout keeps the
69
+ // record, so the next start's cleanup retries.
70
+ const SHUTDOWN_STATUS_TIMEOUT_MS = 3_000;
71
+ const SHUTDOWN_REMOVE_TIMEOUT_MS = 4_000;
72
+
73
+ /**
74
+ * Default command runner. Never rejects: spawn errors and timeouts are
75
+ * reported in the result so the service can classify them. `onOutput` gets
76
+ * each stdout/stderr chunk for approval-URL extraction while waiting.
77
+ */
78
+ export const createDefaultTailscaleRunner = ({ spawnFn = spawn, platform = process.platform } = {}) => {
79
+ const runTailscale = (args, { timeoutMs, onOutput, signal } = {}) => new Promise((resolve) => {
80
+ let stdout = '';
81
+ let stderr = '';
82
+ let timedOut = false;
83
+ let aborted = false;
84
+ let settled = false;
85
+ const finish = (result) => {
86
+ if (settled) return;
87
+ settled = true;
88
+ if (timer) clearTimeout(timer);
89
+ signal?.removeEventListener?.('abort', onAbort);
90
+ resolve(result);
91
+ };
92
+ const onAbort = () => {
93
+ aborted = true;
94
+ try {
95
+ child.kill('SIGKILL');
96
+ } catch {
97
+ }
98
+ finish({ ok: false, code: null, stdout, stderr, spawnError: 'aborted', timedOut: false, aborted: true });
99
+ };
100
+ let child;
101
+ try {
102
+ child = spawnFn(args[0], args.slice(1), {
103
+ windowsHide: true,
104
+ stdio: ['ignore', 'pipe', 'pipe'],
105
+ });
106
+ } catch (error) {
107
+ finish({ ok: false, code: null, stdout: '', stderr: '', spawnError: error?.message || String(error), timedOut: false });
108
+ return;
109
+ }
110
+ if (signal?.aborted) {
111
+ onAbort();
112
+ return;
113
+ }
114
+ signal?.addEventListener?.('abort', onAbort, { once: true });
115
+ const timer = Number.isFinite(timeoutMs) && timeoutMs > 0
116
+ ? setTimeout(() => {
117
+ timedOut = true;
118
+ try {
119
+ child.kill('SIGKILL');
120
+ } catch {
121
+ }
122
+ finish({ ok: false, code: null, stdout, stderr, spawnError: null, timedOut: true });
123
+ }, timeoutMs)
124
+ : null;
125
+ if (timer?.unref) timer.unref();
126
+ child.stdout?.on('data', (chunk) => {
127
+ const text = String(chunk);
128
+ stdout += text;
129
+ try {
130
+ onOutput?.(text);
131
+ } catch {
132
+ }
133
+ });
134
+ child.stderr?.on('data', (chunk) => {
135
+ const text = String(chunk);
136
+ stderr += text;
137
+ try {
138
+ onOutput?.(text);
139
+ } catch {
140
+ }
141
+ });
142
+ child.on('error', (error) => {
143
+ finish({ ok: false, code: null, stdout, stderr, spawnError: error?.message || String(error), timedOut: false });
144
+ });
145
+ child.on('close', (code) => {
146
+ finish({ ok: code === 0, code, stdout, stderr, spawnError: null, timedOut });
147
+ });
148
+ });
149
+ return { runTailscale, platform };
150
+ };
151
+
152
+ const readJsonFile = async (fsPromises, filePath) => {
153
+ try {
154
+ return JSON.parse(await fsPromises.readFile(filePath, 'utf8'));
155
+ } catch {
156
+ return null;
157
+ }
158
+ };
159
+
160
+ const writeJsonFileAtomic = async (fsPromises, filePath, value) => {
161
+ const serialized = `${JSON.stringify(value, null, 2)}\n`;
162
+ const tmpPath = `${filePath}.tmp-${process.pid}`;
163
+ await fsPromises.mkdir(path.dirname(filePath), { recursive: true });
164
+ await fsPromises.writeFile(tmpPath, serialized, 'utf8');
165
+ await fsPromises.rename(tmpPath, filePath);
166
+ };
167
+
168
+ export const createTailscaleService = ({
169
+ dataDir,
170
+ getPort = () => null,
171
+ isUiAuthEnabled = () => false,
172
+ isUnsafeUnauthenticatedLanAllowed = () => false,
173
+ runner = null,
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,
180
+ fsPromises = fs.promises,
181
+ existsSync = fs.existsSync,
182
+ // Stable server identity (hash of the public relay signing key — not a
183
+ // secret). Injected so the probe compares against the same id `/health`,
184
+ // `/api/version`, and relay pairing candidates report. A null/throwing id
185
+ // fails the probe (the URL stays `starting`, never `active`).
186
+ getServerId = async () => null,
187
+ platform = process.platform,
188
+ env = process.env,
189
+ logWarn = (message) => console.warn(message),
190
+ configResponseGraceMs = CONFIG_RESPONSE_GRACE_MS,
191
+ } = {}) => {
192
+ const effectiveRunner = runner || createDefaultTailscaleRunner({ platform });
193
+ const executable = resolveTailscaleExecutable({ platform, env, existsSync });
194
+ const effectiveTailnetHealthFetch = tailnetHealthFetch
195
+ || createTailscaleNcHealthFetch({ executable: executable.command });
196
+ const configPath = path.join(dataDir, TAILSCALE_CONFIG_FILE);
197
+ const mappingPath = path.join(dataDir, TAILSCALE_MAPPING_FILE);
198
+
199
+ let config = { enabled: false, mode: TAILSCALE_DEFAULT_MODE, httpsPort: TAILSCALE_DEFAULT_HTTPS_PORT };
200
+ let status = {
201
+ installed: false,
202
+ running: false,
203
+ loggedIn: false,
204
+ magicDnsName: null,
205
+ httpsCertsAvailable: null,
206
+ state: 'off',
207
+ url: null,
208
+ approvalUrl: null,
209
+ errorCode: null,
210
+ errorMessage: null,
211
+ };
212
+ let generation = 0;
213
+ let probeTimer = null;
214
+ // Serializes reconciles: each reconcile starts only after the previous
215
+ // one settles, so a superseded Off can never remove a mapping after the
216
+ // newer Private reconcile verified it. The tail swallows rejection so one
217
+ // failure never wedges the chain; the returned promise still rejects
218
+ // for the caller (`reconcileWithGrace` logs it).
219
+ let reconcileTail = Promise.resolve();
220
+ // Abort for the in-flight apply (F6): a generation bump aborts it so a
221
+ // stale apply cannot create a mapping nobody owns.
222
+ let applyAbort = null;
223
+ // Whether our mapping record is on disk (F13): a starting/needs-approval
224
+ // mapping that is already written is quit-risky, like an active one.
225
+ let mappingRecordPresent = false;
226
+
227
+ // Every generation bump cancels the in-flight apply first.
228
+ const bumpGeneration = () => {
229
+ generation += 1;
230
+ try {
231
+ applyAbort?.abort();
232
+ } catch {
233
+ }
234
+ applyAbort = null;
235
+ };
236
+
237
+ const clearProbeTimer = () => {
238
+ if (probeTimer) {
239
+ clearTimeout(probeTimer);
240
+ probeTimer = null;
241
+ }
242
+ };
243
+
244
+ const setRuntime = (patch) => {
245
+ status = { ...status, ...patch };
246
+ };
247
+
248
+ /**
249
+ * Records host prerequisites from `tailscale status --json` (queried via
250
+ * `queryStatus`). Shared by the enabled/disabled/blocked reconcile paths
251
+ * so all of them report installed/running/loggedIn accurately. Never sets
252
+ * a state or error code: callers own those.
253
+ */
254
+ const applyHostInfo = (hostInfo) => {
255
+ if (!hostInfo || hostInfo.installed !== true) {
256
+ setRuntime({ installed: false, running: false, loggedIn: false, magicDnsName: null, httpsCertsAvailable: null });
257
+ return;
258
+ }
259
+ setRuntime({
260
+ installed: true,
261
+ running: hostInfo.running === true,
262
+ loggedIn: hostInfo.loggedIn === true,
263
+ magicDnsName: hostInfo.magicDnsName ?? null,
264
+ httpsCertsAvailable: hostInfo.httpsCertsAvailable ?? null,
265
+ });
266
+ };
267
+
268
+ const loadConfig = async () => {
269
+ const raw = await readJsonFile(fsPromises, configPath);
270
+ config = normalizeTailscaleConfig(raw);
271
+ try {
272
+ mappingRecordPresent = (await readMappingRecord()) !== null;
273
+ } catch {
274
+ mappingRecordPresent = false;
275
+ }
276
+ return config;
277
+ };
278
+
279
+ const persistConfig = async (next) => {
280
+ config = next;
281
+ await writeJsonFileAtomic(fsPromises, configPath, next);
282
+ };
283
+
284
+ const readMappingRecord = async () => {
285
+ const raw = await readJsonFile(fsPromises, mappingPath);
286
+ if (!raw || typeof raw !== 'object') return null;
287
+ if (!Number.isInteger(raw.httpsPort) || typeof raw.mode !== 'string' || !Number.isInteger(raw.localPort)) {
288
+ return null;
289
+ }
290
+ return { httpsPort: raw.httpsPort, mode: raw.mode, localPort: raw.localPort };
291
+ };
292
+
293
+ const writeMappingRecord = async (record) => {
294
+ await writeJsonFileAtomic(fsPromises, mappingPath, record);
295
+ mappingRecordPresent = true;
296
+ };
297
+
298
+ const clearMappingRecord = async () => {
299
+ try {
300
+ await fsPromises.unlink(mappingPath);
301
+ } catch {
302
+ }
303
+ mappingRecordPresent = false;
304
+ };
305
+
306
+ // The resolved install location when it exists, otherwise the PATH
307
+ // command (spawn reports ENOENT, which we classify as not-installed).
308
+ const withExecutable = (args) => [executable.command, ...args];
309
+
310
+ const queryStatus = async () => {
311
+ const result = await effectiveRunner.runTailscale(
312
+ withExecutable(['status', '--json']),
313
+ { timeoutMs: TAILSCALE_STATUS_TIMEOUT_MS },
314
+ );
315
+ if (result.spawnError && /ENOENT/i.test(result.spawnError)) {
316
+ return { installed: false };
317
+ }
318
+ if (!result.ok) {
319
+ // `status` exits non-zero when logged out on some builds, but still
320
+ // prints JSON — parse whatever it emitted before giving up.
321
+ const parsed = parseTailscaleStatus(result.stdout);
322
+ if (parsed.loggedIn || parsed.magicDnsName) return { installed: true, ...parsed };
323
+ return { installed: true, running: false, loggedIn: false, magicDnsName: null, httpsCertsAvailable: null };
324
+ }
325
+ return { installed: true, ...parseTailscaleStatus(result.stdout) };
326
+ };
327
+
328
+ const queryServeMapping = async (mode, timeoutMs = TAILSCALE_STATUS_TIMEOUT_MS) => {
329
+ // Funnel mappings are listed by `tailscale funnel status`; serve mappings
330
+ // by `tailscale serve status`. A query failure is UNKNOWN (ok: false),
331
+ // never "absent": callers must refuse to apply/remove/clear without
332
+ // positive ownership instead of overwriting a foreign mapping.
333
+ const subcommand = mode === 'public' ? 'funnel' : 'serve';
334
+ const result = await effectiveRunner.runTailscale(
335
+ withExecutable([subcommand, 'status', '--json']),
336
+ { timeoutMs },
337
+ );
338
+ if (!result.ok || result.spawnError) return { ok: false, status: null };
339
+ try {
340
+ return { ok: true, status: JSON.parse(result.stdout) };
341
+ } catch {
342
+ return { ok: false, status: null };
343
+ }
344
+ };
345
+
346
+ const STATUS_QUERY_FAILED_MESSAGE =
347
+ 'Could not read the current Tailscale serve status, so nothing was changed. Try again.';
348
+
349
+ // Message for a verified own mapping whose `off` removal failed: the
350
+ // mapping may still be live, so never suggest `tailscale serve reset`
351
+ // (that would wipe mappings PiChamber does not own).
352
+ const removeFailedMessageFor = (record) => {
353
+ const surface = record.mode === 'public' ? 'Funnel' : 'serve';
354
+ return `Could not remove PiChamber's Tailscale ${surface} mapping on HTTPS port ${record.httpsPort}, so it may still be reachable. Try again.`;
355
+ };
356
+
357
+ // Maps a `removeVerifiedOwnMapping` result to the status error to report,
358
+ // or null when the stale mapping is verifiably gone (or there was none).
359
+ const removalFailure = (removal, record) => {
360
+ if (!removal) return null;
361
+ if (!removal.verified) return { errorCode: 'status_query_failed', errorMessage: STATUS_QUERY_FAILED_MESSAGE };
362
+ if (removal.removed === false) return { errorCode: 'remove_failed', errorMessage: removeFailedMessageFor(record) };
363
+ return null;
364
+ };
365
+
366
+ /**
367
+ * Verified own-mapping removal shared by the disabled/blocked/stale paths:
368
+ * classify the live mapping against our record and remove ONLY when it is
369
+ * ours, then clear the record. On a query failure nothing is removed and
370
+ * the record is kept so a later reconcile can retry with verification. A
371
+ * failed removal (`removed: false`) also keeps the record — the mapping
372
+ * may still be live — so callers must report `remove_failed` instead of
373
+ * success. Absent/foreign mappings clear the record as before.
374
+ */
375
+ const removeVerifiedOwnMapping = async (record, myGeneration) => {
376
+ const queried = await queryServeMapping(record.mode);
377
+ if (myGeneration !== generation) {
378
+ // Superseded while the serve-status query was in flight: the newer
379
+ // generation may have just verified this same mapping as its own.
380
+ // Remove and clear nothing; the caller returns on its own
381
+ // generation check before interpreting this result.
382
+ return { verified: false, superseded: true };
383
+ }
384
+ if (!queried.ok) return { verified: false };
385
+ const mapping = queried.status ? findServeMappingForPort(queried.status, record.httpsPort) : null;
386
+ const classification = classifyServeMapping({ mapping, httpsPort: record.httpsPort, boundPort: record.localPort });
387
+ if (classification.kind === 'ours') {
388
+ const { removed } = await removeMapping({ mode: record.mode, httpsPort: record.httpsPort });
389
+ if (!removed) {
390
+ return { verified: true, removed: false, classification };
391
+ }
392
+ }
393
+ await clearMappingRecord();
394
+ return { verified: true, removed: true, classification };
395
+ };
396
+
397
+ /**
398
+ * Stale-apply cleanup (F6): an apply that resolved after its generation
399
+ * was superseded may still have created a mapping. Remove it when it
400
+ * verifiably points at the stale local port — unless the current record
401
+ * already claims the same mapping for the live generation (pure retry),
402
+ * in which case the new generation owns it.
403
+ */
404
+ const cleanupStaleApply = async ({ mode, httpsPort, localPort }) => {
405
+ try {
406
+ const current = await readMappingRecord();
407
+ if (current && current.httpsPort === httpsPort && current.mode === mode && current.localPort === localPort) {
408
+ return;
409
+ }
410
+ const queried = await queryServeMapping(mode);
411
+ if (!queried.ok) {
412
+ logWarn(`[tailscale] Stale apply for ${mode} port ${httpsPort} could not be verified; leaving it for the next reconcile.`);
413
+ return;
414
+ }
415
+ const mapping = queried.status ? findServeMappingForPort(queried.status, httpsPort) : null;
416
+ const classification = classifyServeMapping({ mapping, httpsPort, boundPort: localPort });
417
+ if (classification.kind === 'ours') {
418
+ await removeMapping({ mode, httpsPort });
419
+ }
420
+ } catch (error) {
421
+ logWarn(`[tailscale] Stale apply cleanup failed: ${error?.message || error}`);
422
+ }
423
+ };
424
+
425
+ const removeMapping = async ({ mode, httpsPort, timeoutMs = TAILSCALE_REMOVE_TIMEOUT_MS }) => {
426
+ const result = await effectiveRunner.runTailscale(
427
+ withExecutable(buildTailscaleRemoveArgs({ mode, httpsPort })),
428
+ { timeoutMs },
429
+ );
430
+ if (!result.ok && !result.spawnError) {
431
+ // Removing a port with no mapping exits non-zero ("no handler"); that
432
+ // is the desired end state, not a failure.
433
+ if (/handler does not exist|no .* handler|not configured|no such/i.test(`${result.stdout}\n${result.stderr}`)) {
434
+ return { removed: true };
435
+ }
436
+ logWarn(`[tailscale] Failed to remove ${mode} mapping on https port ${httpsPort} (exit ${result.code}).`);
437
+ return { removed: false, output: `${result.stdout}\n${result.stderr}` };
438
+ }
439
+ if (!result.ok) {
440
+ logWarn(`[tailscale] Failed to remove ${mode} mapping on https port ${httpsPort}: ${result.spawnError || 'spawn failed'}.`);
441
+ return { removed: false, output: result.spawnError || '' };
442
+ }
443
+ return { removed: true };
444
+ };
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
+
486
+ const probeUrl = async (url) => {
487
+ // A null/throwing identity fails the probe: the URL stays `starting`
488
+ // and is never advertised as `active`.
489
+ let expectedServerId = null;
490
+ try {
491
+ expectedServerId = await getServerId();
492
+ } catch {
493
+ return false;
494
+ }
495
+ if (typeof expectedServerId !== 'string' || !expectedServerId) return false;
496
+ try {
497
+ const controller = new AbortController();
498
+ const timer = setTimeout(() => controller.abort(), TAILSCALE_PROBE_TIMEOUT_MS);
499
+ if (timer?.unref) timer.unref();
500
+ // Credential-free by construction: no Authorization header, no cookie.
501
+ // Only advertised once the body proves THIS server answered.
502
+ const response = await fetchImpl(`${url.replace(/\/+$/, '')}/health`, {
503
+ method: 'GET',
504
+ headers: { Accept: 'application/json' },
505
+ signal: controller.signal,
506
+ });
507
+ clearTimeout(timer);
508
+ if (!response || !response.ok) return false;
509
+ const body = await response.json().catch(() => null);
510
+ return checkHealthBody(body, expectedServerId);
511
+ } catch {
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);
516
+ }
517
+ };
518
+
519
+ const scheduleProbeRetries = (myGeneration, url, delays, elapsed = 0) => {
520
+ clearProbeTimer();
521
+ if (myGeneration !== generation) return;
522
+ if (elapsed >= PROBE_RETRY_BUDGET_MS || delays.length === 0) {
523
+ if (myGeneration === generation && status.state === 'starting') {
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.' });
525
+ }
526
+ return;
527
+ }
528
+ const [delay, ...rest] = delays;
529
+ probeTimer = setTimeout(async () => {
530
+ probeTimer = null;
531
+ if (myGeneration !== generation) return;
532
+ const ok = await probeUrl(url);
533
+ if (myGeneration !== generation) return;
534
+ if (ok) {
535
+ setRuntime({ state: 'active', url, approvalUrl: null, errorCode: null, errorMessage: null });
536
+ return;
537
+ }
538
+ scheduleProbeRetries(myGeneration, url, rest, elapsed + delay);
539
+ }, delay);
540
+ if (probeTimer?.unref) probeTimer.unref();
541
+ };
542
+
543
+ const applyMapping = async (myGeneration, { mode, httpsPort, localPort }) => {
544
+ let approvalUrl = null;
545
+ if (myGeneration !== generation) {
546
+ // Superseded before the apply even started: never assign the shared
547
+ // abort handle (it belongs to the live generation), just sweep a
548
+ // possibly orphaned mapping for these params.
549
+ await cleanupStaleApply({ mode, httpsPort, localPort });
550
+ return { applied: false, stale: true };
551
+ }
552
+ const controller = typeof AbortController !== 'undefined' ? new AbortController() : null;
553
+ applyAbort = controller;
554
+ const result = await effectiveRunner.runTailscale(
555
+ withExecutable(buildTailscaleServeArgs({ mode, httpsPort, localPort })),
556
+ {
557
+ timeoutMs: TAILSCALE_APPROVAL_WAIT_MS,
558
+ ...(controller ? { signal: controller.signal } : {}),
559
+ onOutput: (chunk) => {
560
+ if (approvalUrl || myGeneration !== generation) return;
561
+ const found = extractApprovalUrl(chunk);
562
+ if (found) {
563
+ approvalUrl = found;
564
+ if (status.state === 'starting') {
565
+ setRuntime({ state: 'needs-approval', approvalUrl, errorCode: 'needs_approval', errorMessage: 'Tailscale needs tailnet approval before the mapping goes live.' });
566
+ }
567
+ }
568
+ },
569
+ },
570
+ );
571
+ if (applyAbort === controller) applyAbort = null;
572
+ if (myGeneration !== generation) {
573
+ // Superseded while applying: a mapping may still have been created, so
574
+ // verify and remove it rather than orphaning it.
575
+ await cleanupStaleApply({ mode, httpsPort, localPort });
576
+ return { applied: false, stale: true };
577
+ }
578
+ if (result.timedOut) {
579
+ if (approvalUrl) {
580
+ setRuntime({ state: 'needs-approval', approvalUrl, errorCode: 'needs_approval', errorMessage: 'Tailscale is still waiting for tailnet approval. Approve, then retry.' });
581
+ return { applied: false, approvalUrl };
582
+ }
583
+ setRuntime({ state: 'error', errorCode: 'timeout', errorMessage: 'Applying the Tailscale mapping timed out.' });
584
+ return { applied: false };
585
+ }
586
+ if (result.spawnError) {
587
+ if (/ENOENT/i.test(result.spawnError)) {
588
+ setRuntime({ installed: false, state: 'unavailable', errorCode: 'not_installed', errorMessage: 'The tailscale executable was not found. Install Tailscale to use remote access.' });
589
+ return { applied: false };
590
+ }
591
+ setRuntime({ state: 'error', errorCode: 'apply_failed', errorMessage: 'Failed to start the Tailscale process.' });
592
+ return { applied: false };
593
+ }
594
+ if (!result.ok) {
595
+ const output = `${result.stdout}\n${result.stderr}`;
596
+ const found = extractApprovalUrl(output);
597
+ if (found) {
598
+ setRuntime({ state: 'needs-approval', approvalUrl: found, errorCode: 'needs_approval', errorMessage: 'Tailscale needs tailnet approval before the mapping goes live. Approve, then retry.' });
599
+ return { applied: false, approvalUrl: found };
600
+ }
601
+ const classified = classifyApplyFailure(output);
602
+ if (classified) {
603
+ setRuntime({ state: 'error', errorCode: classified.code, errorMessage: classified.message });
604
+ return { applied: false };
605
+ }
606
+ setRuntime({ state: 'error', errorCode: 'apply_failed', errorMessage: `tailscale ${mode} exited with code ${result.code}.` });
607
+ return { applied: false };
608
+ }
609
+ return { applied: true };
610
+ };
611
+
612
+ /**
613
+ * Reconcile desired (config) vs actual (serve status) state. Never throws:
614
+ * every failure is captured in the status model with a stable error code.
615
+ * Runs serialized via `reconcile()`: `myGeneration` is the generation this
616
+ * run was scheduled under.
617
+ */
618
+ const runReconcile = async (myGeneration) => {
619
+ clearProbeTimer();
620
+ setRuntime({ approvalUrl: null, errorCode: null, errorMessage: null });
621
+ const boundPort = getPort();
622
+ if (!Number.isInteger(boundPort) || boundPort <= 0) {
623
+ setRuntime({ state: 'error', errorCode: 'unknown', errorMessage: 'Server port is not bound yet.' });
624
+ return getStatus();
625
+ }
626
+
627
+ if (!config.enabled) {
628
+ // Disabled: remove any stale mapping PiChamber created, leave foreign
629
+ // mappings untouched, and report off. Without a successful status
630
+ // query there is no positive ownership, so the record is kept for the
631
+ // next reconcile to retry with verification.
632
+ const record = await readMappingRecord();
633
+ if (myGeneration !== generation) return getStatus();
634
+ const removal = record ? await removeVerifiedOwnMapping(record, myGeneration) : null;
635
+ if (myGeneration !== generation) return getStatus();
636
+ // Still report host prerequisites (`status --json` only, no
637
+ // serve/funnel commands) so the UI shows Not installed / Not signed
638
+ // in accurately instead of a blanket Off; retry re-checks them.
639
+ const hostInfo = await queryStatus();
640
+ if (myGeneration !== generation) return getStatus();
641
+ applyHostInfo(hostInfo);
642
+ const failure = removalFailure(removal, record);
643
+ if (failure) {
644
+ setRuntime({ state: 'error', url: null, ...failure });
645
+ return getStatus();
646
+ }
647
+ setRuntime({ state: 'off', url: null });
648
+ return getStatus();
649
+ }
650
+
651
+ const gate = checkTailscaleAuthGate({
652
+ enabled: true,
653
+ mode: config.mode,
654
+ uiPasswordConfigured: isUiAuthEnabled(),
655
+ unsafeUnauthenticatedLanAllowed: isUnsafeUnauthenticatedLanAllowed(),
656
+ });
657
+ if (!gate.allowed) {
658
+ // Blocked (e.g. the desktop password was cleared and the app
659
+ // restarted): tailscaled persists serve config, so an existing mapping
660
+ // PiChamber created would stay reachable without auth. Remove it with
661
+ // the same verified ownership check as the disabled path, then report
662
+ // blocked. A query failure or a failed removal keeps the record and
663
+ // reports `error` instead: a surviving mapping here is reachable
664
+ // without auth, so it must never be reported as `blocked`.
665
+ const record = await readMappingRecord();
666
+ if (myGeneration !== generation) return getStatus();
667
+ const removal = record ? await removeVerifiedOwnMapping(record, myGeneration) : null;
668
+ if (myGeneration !== generation) return getStatus();
669
+ // Same host-prerequisite refresh as the disabled path.
670
+ const hostInfo = await queryStatus();
671
+ if (myGeneration !== generation) return getStatus();
672
+ applyHostInfo(hostInfo);
673
+ const failure = removalFailure(removal, record);
674
+ if (failure) {
675
+ setRuntime({ state: 'error', url: null, ...failure });
676
+ return getStatus();
677
+ }
678
+ setRuntime({ state: 'blocked', url: null, errorCode: gate.code, errorMessage: gate.message });
679
+ return getStatus();
680
+ }
681
+
682
+ setRuntime({ state: 'starting', url: null });
683
+ const hostInfo = await queryStatus();
684
+ if (myGeneration !== generation) return getStatus();
685
+ applyHostInfo(hostInfo);
686
+ if (!hostInfo.installed) {
687
+ setRuntime({ state: 'unavailable', errorCode: 'not_installed', errorMessage: 'The tailscale executable was not found. Install Tailscale to use remote access.' });
688
+ return getStatus();
689
+ }
690
+ if (!hostInfo.running) {
691
+ setRuntime({ state: 'unavailable', errorCode: 'not_running', errorMessage: 'The Tailscale daemon is not running. Start it, then retry.' });
692
+ return getStatus();
693
+ }
694
+ if (!hostInfo.loggedIn || !hostInfo.magicDnsName) {
695
+ setRuntime({ state: 'unavailable', errorCode: 'not_logged_in', errorMessage: 'Tailscale is not logged in. Run: tailscale up' });
696
+ return getStatus();
697
+ }
698
+
699
+ // Crash safety: a stale record for a different port/mode must be removed
700
+ // (when it is ours) before the new mapping is applied. A failed status
701
+ // query leaves the old record in place and ends in error/retry — in
702
+ // particular a public→private switch never leaves a live Funnel behind
703
+ // while claiming success.
704
+ const stale = await readMappingRecord();
705
+ if (stale && (stale.httpsPort !== config.httpsPort || stale.mode !== config.mode)) {
706
+ // A failed removal keeps the old record: never apply the new mapping
707
+ // while the old one may still be live, so retry can remove it first.
708
+ // The generation is checked before interpreting the result, so a
709
+ // superseded removal (which removed nothing) never reports an error.
710
+ const removal = await removeVerifiedOwnMapping(stale, myGeneration);
711
+ if (myGeneration !== generation) return getStatus();
712
+ const failure = removalFailure(removal, stale);
713
+ if (failure) {
714
+ setRuntime({ state: 'error', url: null, ...failure });
715
+ return getStatus();
716
+ }
717
+ }
718
+
719
+ const queried = await queryServeMapping(config.mode);
720
+ if (myGeneration !== generation) return getStatus();
721
+ if (!queried.ok) {
722
+ // Unknown, not absent: refuse to apply rather than overwriting a
723
+ // mapping we cannot see. The stale record (if any) is kept for
724
+ // cleanup once the query succeeds.
725
+ setRuntime({ state: 'error', url: null, errorCode: 'status_query_failed', errorMessage: STATUS_QUERY_FAILED_MESSAGE });
726
+ return getStatus();
727
+ }
728
+ const mapping = queried.status ? findServeMappingForPort(queried.status, config.httpsPort) : null;
729
+ const classification = classifyServeMapping({ mapping, httpsPort: config.httpsPort, boundPort });
730
+ if (classification.kind === 'foreign') {
731
+ // Crash-restart on a new local port: the live mapping points at the
732
+ // recorded port instead of this bound port. The record (same
733
+ // port+mode) proves PiChamber created it, so re-verify the live
734
+ // targets against the recorded port and repoint instead of conflict.
735
+ // (When the stale cleanup above cleared the record it no longer
736
+ // applies, so fall back to a fresh read.) Ownership still needs BOTH
737
+ // the record and the live targets — never repoint on the record alone.
738
+ const record = stale && stale.httpsPort === config.httpsPort && stale.mode === config.mode
739
+ ? stale
740
+ : await readMappingRecord();
741
+ const recordedOurs = record
742
+ && record.httpsPort === config.httpsPort
743
+ && record.mode === config.mode
744
+ && record.localPort !== boundPort
745
+ && classifyServeMapping({ mapping, httpsPort: config.httpsPort, boundPort: record.localPort }).kind === 'ours';
746
+ if (!recordedOurs) {
747
+ setRuntime({ state: 'conflict', url: null, errorCode: 'conflict', errorMessage: conflictMessageForPort(config.httpsPort) });
748
+ return getStatus();
749
+ }
750
+ // Ours by record, still pointing at the previous local port: fall
751
+ // through and repoint it at this bound port.
752
+ }
753
+ if (classification.kind === 'ours') {
754
+ const record = await readMappingRecord();
755
+ const sameTarget = record && record.httpsPort === config.httpsPort && record.mode === config.mode && record.localPort === boundPort;
756
+ if (sameTarget) {
757
+ // Mapping already fronts this server: verify it answers as us.
758
+ const url = buildTailscaleUrl({ magicDnsName: hostInfo.magicDnsName, httpsPort: config.httpsPort });
759
+ const ok = await probeUrl(url);
760
+ if (myGeneration !== generation) return getStatus();
761
+ if (ok) {
762
+ setRuntime({ state: 'active', url, approvalUrl: null });
763
+ } else {
764
+ setRuntime({ state: 'starting', url: null });
765
+ scheduleProbeRetries(myGeneration, url, PROBE_RETRY_DELAYS_MS);
766
+ }
767
+ return getStatus();
768
+ }
769
+ // Ours and already pointing at this bound port, but the record is
770
+ // missing or names a different port: fall through and re-apply it so
771
+ // the record is rewritten.
772
+ }
773
+
774
+ const applied = await applyMapping(myGeneration, { mode: config.mode, httpsPort: config.httpsPort, localPort: boundPort });
775
+ if (myGeneration !== generation) return getStatus();
776
+ if (!applied.applied) return getStatus();
777
+ await writeMappingRecord({ httpsPort: config.httpsPort, mode: config.mode, localPort: boundPort });
778
+ const url = buildTailscaleUrl({ magicDnsName: hostInfo.magicDnsName, httpsPort: config.httpsPort });
779
+ const ok = await probeUrl(url);
780
+ if (myGeneration !== generation) return getStatus();
781
+ if (ok) {
782
+ setRuntime({ state: 'active', url, approvalUrl: null });
783
+ } else {
784
+ // First-use HTTPS/DNS provisioning can take minutes: report starting
785
+ // and keep re-probing in the background with backoff.
786
+ setRuntime({ state: 'starting', url: null });
787
+ scheduleProbeRetries(myGeneration, url, PROBE_RETRY_DELAYS_MS);
788
+ }
789
+ return getStatus();
790
+ };
791
+
792
+ const getStatus = () => {
793
+ const authGateFor = (mode) => {
794
+ try {
795
+ return checkTailscaleAuthGate({
796
+ enabled: true,
797
+ mode,
798
+ uiPasswordConfigured: isUiAuthEnabled(),
799
+ unsafeUnauthenticatedLanAllowed: isUnsafeUnauthenticatedLanAllowed(),
800
+ }).allowed === true;
801
+ } catch {
802
+ return false;
803
+ }
804
+ };
805
+ return {
806
+ installed: status.installed,
807
+ running: status.running,
808
+ loggedIn: status.loggedIn,
809
+ magicDnsName: status.magicDnsName,
810
+ httpsCertsAvailable: status.httpsCertsAvailable,
811
+ config: { ...config },
812
+ state: status.state,
813
+ url: status.state === 'active' ? status.url : null,
814
+ approvalUrl: status.approvalUrl,
815
+ errorCode: status.errorCode,
816
+ errorMessage: status.errorMessage,
817
+ authGate: { privateAllowed: authGateFor('private'), publicAllowed: authGateFor('public') },
818
+ };
819
+ };
820
+
821
+ // Serialized entry point: reconciles run one at a time in call order. A
822
+ // run superseded while queued is skipped; a superseded in-flight run
823
+ // finishes quickly (`bumpGeneration()` aborts its apply) and never
824
+ // removes a mapping after the newer run starts (generation re-checked
825
+ // after the serve-status query and before every state write).
826
+ const reconcile = () => {
827
+ const myGeneration = generation;
828
+ const pending = reconcileTail.catch(() => {}).then(() => {
829
+ if (myGeneration !== generation) return getStatus();
830
+ return runReconcile(myGeneration);
831
+ });
832
+ reconcileTail = pending.catch(() => {});
833
+ return pending;
834
+ };
835
+
836
+ // Config/retry responses wait for reconcile only up to a short grace,
837
+ // then return the current (possibly transitional) status while
838
+ // reconcile continues in the background. Callers poll `GET /status`
839
+ // until a terminal state. Validation/auth-gate errors still throw
840
+ // synchronously before kickoff via `setConfig` above.
841
+ const reconcileWithGrace = () => {
842
+ const myGeneration = generation;
843
+ const pending = reconcile();
844
+ // Background safety net (same precedent as the startup reconcile in
845
+ // `server/index.js`): never an unhandled rejection. Only records when
846
+ // still current so a superseded generation cannot clobber live state.
847
+ pending.catch((error) => {
848
+ logWarn(`[tailscale] Background reconcile failed: ${error?.message || error}`);
849
+ if (myGeneration === generation) {
850
+ setRuntime({ state: 'error', errorCode: 'unknown', errorMessage: 'Tailscale reconcile failed unexpectedly.' });
851
+ }
852
+ });
853
+ const graceMs = Number.isFinite(configResponseGraceMs) && configResponseGraceMs >= 0
854
+ ? configResponseGraceMs
855
+ : CONFIG_RESPONSE_GRACE_MS;
856
+ let timer = null;
857
+ const graceElapsed = new Promise((resolve) => {
858
+ timer = setTimeout(() => resolve(null), graceMs);
859
+ if (timer?.unref) timer.unref();
860
+ });
861
+ const settled = pending.then(
862
+ (result) => {
863
+ if (timer) clearTimeout(timer);
864
+ return result;
865
+ },
866
+ () => {
867
+ if (timer) clearTimeout(timer);
868
+ return getStatus();
869
+ },
870
+ );
871
+ return Promise.race([settled, graceElapsed.then(() => getStatus())]);
872
+ };
873
+
874
+ const setConfig = async (patch) => {
875
+ const merged = normalizeTailscaleConfig({ ...config, ...(patch || {}) });
876
+ const validation = validateTailscaleConfig({ ...config, ...(patch || {}) });
877
+ if (!validation.ok) {
878
+ const error = new Error(validation.errors.join('; '));
879
+ error.code = 'invalid_config';
880
+ throw error;
881
+ }
882
+ if (merged.enabled) {
883
+ const gate = checkTailscaleAuthGate({
884
+ enabled: true,
885
+ mode: merged.mode,
886
+ uiPasswordConfigured: isUiAuthEnabled(),
887
+ unsafeUnauthenticatedLanAllowed: isUnsafeUnauthenticatedLanAllowed(),
888
+ });
889
+ if (!gate.allowed) {
890
+ const error = new Error(gate.message);
891
+ error.code = gate.code;
892
+ throw error;
893
+ }
894
+ }
895
+ bumpGeneration();
896
+ await persistConfig(merged);
897
+ return reconcileWithGrace();
898
+ };
899
+
900
+ const shutdown = async () => {
901
+ bumpGeneration();
902
+ clearProbeTimer();
903
+ try {
904
+ // Verify ownership before removing: a failed status query leaves the
905
+ // mapping (and the record) untouched so the next start's stale
906
+ // cleanup can retry with verification. Each step is bounded by the
907
+ // shutdown timeouts, which fit inside Electron's quit timeout.
908
+ const record = await readMappingRecord();
909
+ if (record) {
910
+ const queried = await queryServeMapping(record.mode, SHUTDOWN_STATUS_TIMEOUT_MS);
911
+ if (!queried.ok) {
912
+ logWarn('[tailscale] Shutdown: serve status query failed; leaving the mapping for next-start cleanup.');
913
+ } else {
914
+ const mapping = queried.status ? findServeMappingForPort(queried.status, record.httpsPort) : null;
915
+ const classification = classifyServeMapping({ mapping, httpsPort: record.httpsPort, boundPort: record.localPort });
916
+ if (classification.kind === 'ours') {
917
+ const { removed } = await removeMapping({ mode: record.mode, httpsPort: record.httpsPort, timeoutMs: SHUTDOWN_REMOVE_TIMEOUT_MS });
918
+ if (!removed) {
919
+ logWarn(`[tailscale] Shutdown: could not remove ${record.mode} mapping on https port ${record.httpsPort}; leaving it for next-start cleanup.`);
920
+ } else {
921
+ await clearMappingRecord();
922
+ }
923
+ } else if (classification.kind === 'foreign') {
924
+ logWarn(`[tailscale] Shutdown: mapping on port ${record.httpsPort} is not ours; leaving it alone.`);
925
+ await clearMappingRecord();
926
+ } else {
927
+ await clearMappingRecord();
928
+ }
929
+ }
930
+ }
931
+ } catch (error) {
932
+ logWarn(`[tailscale] Shutdown cleanup failed: ${error?.message || error}`);
933
+ }
934
+ setRuntime({ state: config.enabled ? status.state : 'off', url: null, approvalUrl: null });
935
+ };
936
+
937
+ const dispose = () => {
938
+ bumpGeneration();
939
+ clearProbeTimer();
940
+ };
941
+
942
+ const getPairingCandidate = () => {
943
+ if (status.state !== 'active' || !status.url) return null;
944
+ return { type: 'tailscale', url: status.url, mode: config.mode, priority: 20 };
945
+ };
946
+
947
+ const getTransports = () => {
948
+ const active = status.state === 'active';
949
+ // A starting/needs-approval mapping that is already written still
950
+ // fronts this server (or is about to), so quitting without the
951
+ // removal step orphans it — treat it as quit-risky like active.
952
+ const pendingRisky = (status.state === 'starting' || status.state === 'needs-approval') && mappingRecordPresent;
953
+ const available = active || pendingRisky;
954
+ return {
955
+ available,
956
+ url: active ? status.url : null,
957
+ mode: config.mode,
958
+ };
959
+ };
960
+
961
+ return {
962
+ loadConfig,
963
+ getConfig: () => ({ ...config }),
964
+ setConfig,
965
+ getStatus,
966
+ reconcile,
967
+ retry: () => {
968
+ bumpGeneration();
969
+ return reconcileWithGrace();
970
+ },
971
+ shutdown,
972
+ dispose,
973
+ getPairingCandidate,
974
+ getTransports,
975
+ validateTailscaleConfig,
976
+ };
977
+ };
978
+
979
+ /**
980
+ * CLI/serve startup helper: persist config without starting the service.
981
+ * Enforces the auth gate itself (core-enforced, never CLI-only): enabling
982
+ * without a UI password rejects with `auth_required`.
983
+ */
984
+ export const persistTailscaleConfigForStartup = async ({
985
+ dataDir,
986
+ patch,
987
+ fsPromises = fs.promises,
988
+ uiPasswordConfigured = false,
989
+ unsafeUnauthenticatedLanAllowed = false,
990
+ }) => {
991
+ const current = normalizeTailscaleConfig(await readJsonFile(fsPromises, path.join(dataDir, TAILSCALE_CONFIG_FILE)));
992
+ const merged = normalizeTailscaleConfig({ ...current, ...(patch || {}) });
993
+ const validation = validateTailscaleConfig({ ...current, ...(patch || {}) });
994
+ if (!validation.ok) {
995
+ throw new Error(validation.errors.join('; '));
996
+ }
997
+ if (merged.enabled) {
998
+ const gate = checkTailscaleAuthGate({
999
+ enabled: true,
1000
+ mode: merged.mode,
1001
+ uiPasswordConfigured,
1002
+ unsafeUnauthenticatedLanAllowed,
1003
+ });
1004
+ if (!gate.allowed) {
1005
+ const error = new Error(gate.message);
1006
+ error.code = gate.code;
1007
+ throw error;
1008
+ }
1009
+ }
1010
+ await writeJsonFileAtomic(fsPromises, path.join(dataDir, TAILSCALE_CONFIG_FILE), merged);
1011
+ return merged;
1012
+ };