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