@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,136 @@
1
+ import fs from 'fs';
2
+ import os from 'os';
3
+ import path from 'path';
4
+ import { beforeEach, describe, expect, it, vi } from 'vitest';
5
+
6
+ vi.mock('./cli-lifecycle.js', () => ({
7
+ discoverRunningInstances: vi.fn(),
8
+ }));
9
+
10
+ vi.mock('./cli-http.js', () => ({
11
+ requestJson: vi.fn(),
12
+ }));
13
+
14
+ import { discoverRunningInstances } from './cli-lifecycle.js';
15
+ import { requestJson } from './cli-http.js';
16
+ import { createConnectUrlCommand } from './commands-connect-url.js';
17
+
18
+ async function withTempPiChamberDataDir(fn) {
19
+ const previous = process.env.PICHAMBER_DATA_DIR;
20
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pichamber-pair-test-'));
21
+ process.env.PICHAMBER_DATA_DIR = dir;
22
+ try {
23
+ return await fn(dir);
24
+ } finally {
25
+ if (typeof previous === 'string') {
26
+ process.env.PICHAMBER_DATA_DIR = previous;
27
+ } else {
28
+ delete process.env.PICHAMBER_DATA_DIR;
29
+ }
30
+ fs.rmSync(dir, { recursive: true, force: true });
31
+ }
32
+ }
33
+
34
+ async function captureOutput(fn) {
35
+ const originalStdoutWrite = process.stdout.write;
36
+ const originalStderrWrite = process.stderr.write;
37
+ const stdoutTarget = { value: '' };
38
+ const stderrTarget = { value: '' };
39
+ const capture = (target) => (chunk, encoding, callback) => {
40
+ target.value += Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk);
41
+ if (typeof encoding === 'function') encoding();
42
+ if (typeof callback === 'function') callback();
43
+ return true;
44
+ };
45
+ process.stdout.write = capture(stdoutTarget);
46
+ process.stderr.write = capture(stderrTarget);
47
+ try {
48
+ await fn();
49
+ return { stdout: stdoutTarget.value, stderr: stderrTarget.value };
50
+ } finally {
51
+ process.stdout.write = originalStdoutWrite;
52
+ process.stderr.write = originalStderrWrite;
53
+ }
54
+ }
55
+
56
+ function stubRunningServer() {
57
+ vi.mocked(discoverRunningInstances).mockResolvedValue([{ port: 3000 }]);
58
+ }
59
+
60
+ function stubTailscaleStatus(body) {
61
+ vi.mocked(requestJson).mockResolvedValue({
62
+ response: { status: 200, ok: true },
63
+ body,
64
+ });
65
+ }
66
+
67
+ describe('pair --tailscale --quiet', () => {
68
+ beforeEach(() => {
69
+ vi.resetAllMocks();
70
+ stubRunningServer();
71
+ });
72
+
73
+ it('prints only the link on stdout and the approval url on stderr for needs-approval', async () => {
74
+ await withTempPiChamberDataDir(async () => {
75
+ const approvalUrl = 'https://login.tailscale.com/a/abc123';
76
+ stubTailscaleStatus({ state: 'needs-approval', approvalUrl, mode: 'private' });
77
+ const serveCommand = vi.fn();
78
+ const pair = createConnectUrlCommand({ serveCommand });
79
+
80
+ const { stdout, stderr } = await captureOutput(() => pair({
81
+ port: 3000,
82
+ tailscale: true,
83
+ quiet: true,
84
+ server: 'http://127.0.0.1:3000',
85
+ }));
86
+
87
+ const stdoutLines = stdout.trim().split('\n');
88
+ expect(stdoutLines).toHaveLength(1);
89
+ expect(stdoutLines[0].startsWith('pichamber://connect')).toBe(true);
90
+ expect(stderr).toContain('[TAILSCALE_APPROVAL]');
91
+ expect(stderr).toContain(approvalUrl);
92
+ expect(stderr.trim().split('\n')).toHaveLength(1);
93
+ expect(stderr).not.toContain('pichamber://connect');
94
+ expect(serveCommand).not.toHaveBeenCalled();
95
+ });
96
+ });
97
+
98
+ it('prints nothing extra on stderr when tailscale is active', async () => {
99
+ await withTempPiChamberDataDir(async () => {
100
+ stubTailscaleStatus({ state: 'active', url: 'https://host.ts.net', mode: 'private' });
101
+ const pair = createConnectUrlCommand({ serveCommand: vi.fn() });
102
+
103
+ const { stdout, stderr } = await captureOutput(() => pair({
104
+ port: 3000,
105
+ tailscale: true,
106
+ quiet: true,
107
+ server: 'http://127.0.0.1:3000',
108
+ }));
109
+
110
+ const stdoutLines = stdout.trim().split('\n');
111
+ expect(stdoutLines).toHaveLength(1);
112
+ expect(stdoutLines[0].startsWith('pichamber://connect')).toBe(true);
113
+ expect(stderr).toBe('');
114
+ });
115
+ });
116
+
117
+ it('reports non-approval states with state and error message on stderr', async () => {
118
+ await withTempPiChamberDataDir(async () => {
119
+ stubTailscaleStatus({ state: 'error', errorMessage: 'daemon unreachable', mode: 'private' });
120
+ const pair = createConnectUrlCommand({ serveCommand: vi.fn() });
121
+
122
+ const { stdout, stderr } = await captureOutput(() => pair({
123
+ port: 3000,
124
+ tailscale: true,
125
+ quiet: true,
126
+ server: 'http://127.0.0.1:3000',
127
+ }));
128
+
129
+ expect(stdout.trim().split('\n')).toHaveLength(1);
130
+ expect(stderr).toContain('[TAILSCALE_NOT_ACTIVE]');
131
+ expect(stderr).toContain('error');
132
+ expect(stderr).toContain('daemon unreachable');
133
+ expect(stderr).not.toContain('pichamber://connect');
134
+ });
135
+ });
136
+ });
@@ -11,12 +11,13 @@ import {
11
11
  formatHostForUrl,
12
12
  } from './cli-network.js';
13
13
  import { discoverRunningInstances } from './cli-lifecycle.js';
14
+ import { requestJson } from './cli-http.js';
14
15
  import { getInstanceFilePath, readInstanceOptions } from './cli-process.js';
15
16
  import { resolvePiChamberDataDir } from '../../server/lib/pichamber-data-dir.js';
16
17
  import { createRemoteClientAuthRuntime } from '../../server/lib/client-auth/remote-clients.js';
17
18
  import { createClientPairingRuntime } from '../../server/lib/client-auth/pairing.js';
18
19
  import { createRelayIdentityRuntime } from '../../server/lib/relay/identity.js';
19
- import { DEFAULT_RELAY_URL } from '../../server/lib/relay/service.js';
20
+ import { createRelayIdentityStore } from '../../server/lib/relay/identity-store.js';
20
21
  import { bytesToBase64Url } from '../../server/lib/relay/e2ee.js';
21
22
  import {
22
23
  intro as clackIntro,
@@ -25,6 +26,7 @@ import {
25
26
  isJsonMode,
26
27
  isQuietMode,
27
28
  canPrompt,
29
+ createSpinner,
28
30
  printJson,
29
31
  logStatus,
30
32
  } from '../cli-output.js';
@@ -33,6 +35,74 @@ const REMOTE_CLIENTS_FILE_NAME = 'remote-clients.json';
33
35
  const SETTINGS_FILE_NAME = 'settings.json';
34
36
  const PAIRING_SESSIONS_FILE_NAME = 'client-pairing-sessions.json';
35
37
 
38
+ // How long `pair --tailscale` waits for the server to reach a terminal
39
+ // Tailscale state (the approval flow alone may block up to 5 minutes).
40
+ const TAILSCALE_PAIR_WAIT_MS = 6 * 60 * 1000;
41
+ const TAILSCALE_PAIR_POLL_MS = 2000;
42
+ const TAILSCALE_TERMINAL_STATES = new Set(['active', 'needs-approval', 'conflict', 'blocked', 'error', 'unavailable']);
43
+
44
+ function assertTailscaleFlagCombination(options) {
45
+ if ((options.public === true || options.httpsPort !== undefined) && options.tailscale !== true) {
46
+ throw new TunnelCliError('Use --tailscale with --public / --https-port.', EXIT_CODE.USAGE_ERROR);
47
+ }
48
+ }
49
+
50
+ // Asks the RUNNING server to enable Tailscale (persisted server-side), then
51
+ // waits for a terminal state. Returns the status body. Throws TunnelCliError
52
+ // on auth/validation failures; terminal non-active states are returned (not
53
+ // thrown) so the caller can still print the pairing link with whatever
54
+ // candidates exist.
55
+ async function enableTailscaleForPairing(options) {
56
+ const mode = options.public === true ? 'public' : 'private';
57
+ const httpsPort = options.httpsPort ?? 443;
58
+ const spin = createSpinner(options);
59
+ spin?.start(`Enabling Tailscale ${mode === 'public' ? 'Funnel (public)' : 'serve (tailnet-only)'} on port ${options.port}...`);
60
+ try {
61
+ const putResult = await requestJson(options.port, '/api/pichamber/tailscale/config', {
62
+ ...options,
63
+ method: 'PUT',
64
+ body: JSON.stringify({ enabled: true, mode, httpsPort }),
65
+ timeoutMs: 15000,
66
+ });
67
+ if (putResult.response.status === 403 || putResult.response.status === 422) {
68
+ throw new TunnelCliError(
69
+ typeof putResult.body?.error === 'string' ? putResult.body.error : 'Tailscale config rejected.',
70
+ EXIT_CODE.AUTH_CONFIG_ERROR,
71
+ );
72
+ }
73
+ if (!putResult.response.ok) {
74
+ throw new TunnelCliError(
75
+ typeof putResult.body?.error === 'string' ? putResult.body.error : 'Failed to enable Tailscale.',
76
+ EXIT_CODE.GENERAL_ERROR,
77
+ );
78
+ }
79
+ const deadline = Date.now() + TAILSCALE_PAIR_WAIT_MS;
80
+ let status = putResult.body;
81
+ while (!TAILSCALE_TERMINAL_STATES.has(status?.state) && Date.now() < deadline) {
82
+ await new Promise((resolve) => setTimeout(resolve, TAILSCALE_PAIR_POLL_MS));
83
+ const polled = await requestJson(options.port, '/api/pichamber/tailscale/status', {
84
+ ...options,
85
+ timeoutMs: 8000,
86
+ });
87
+ if (polled.response.ok && polled.body) status = polled.body;
88
+ }
89
+ if (!TAILSCALE_TERMINAL_STATES.has(status?.state)) {
90
+ throw new TunnelCliError('Timed out waiting for Tailscale to become active.', EXIT_CODE.GENERAL_ERROR);
91
+ }
92
+ spin?.stop(`Tailscale state: ${status.state}`);
93
+ return status;
94
+ } catch (error) {
95
+ spin?.stop('Tailscale setup failed');
96
+ throw error;
97
+ }
98
+ }
99
+
100
+ function appendTailscaleCandidate(candidates, tailscaleStatus) {
101
+ const url = typeof tailscaleStatus?.url === 'string' ? tailscaleStatus.url : null;
102
+ if (!url || candidates.some((candidate) => candidate?.url === url)) return candidates;
103
+ return [...candidates, { type: 'tailscale', url, mode: tailscaleStatus.mode || 'private', priority: 20 }];
104
+ }
105
+
36
106
  function isValidRelayUrl(value) {
37
107
  if (typeof value !== 'string') return false;
38
108
  try {
@@ -43,50 +113,52 @@ function isValidRelayUrl(value) {
43
113
  }
44
114
  }
45
115
 
46
- // Resolve the relay endpoint the same way the running host does (service.js):
47
- // PICHAMBER_RELAY_URL env override, then the stored setting, then the default —
48
- // so the pairing link points at the same relay the host connects out to.
116
+ // Relay candidates require an explicitly configured relay endpoint: the
117
+ // PICHAMBER_RELAY_URL env override or the stored setting. There is no hosted
118
+ // default — without one there is nothing for the client to dial out to, so no
119
+ // relay candidate is emitted and no relay identity keys are generated.
49
120
  function resolveRelayUrl(settings) {
50
121
  const envUrl = process.env.PICHAMBER_RELAY_URL;
51
122
  if (isValidRelayUrl(envUrl)) return envUrl.trim();
52
123
  const stored = settings?.privateRelay?.relayUrl;
53
124
  if (isValidRelayUrl(stored)) return stored.trim();
54
- return DEFAULT_RELAY_URL;
125
+ return null;
55
126
  }
56
127
 
57
- // Minimal settings.json read/write for the relay identity runtime. It reads the
58
- // whole object and writes it back with the relay keys added, so other settings
59
- // are preserved. Enough for the CLI without wiring the full settings runtime.
60
- function createSettingsAccessors() {
128
+ // Minimal settings.json read for non-identity relay config (privateRelay
129
+ // relayUrl/enabled). Host identity keys live in the host-local
130
+ // relay-identity.json (see server/lib/relay/identity-store.js) — never in
131
+ // settings.json, which is portable between hosts and rewritten by the UI
132
+ // settings store.
133
+ async function readPairingRelaySettings() {
61
134
  const settingsPath = path.join(getPiChamberDataDir(), SETTINGS_FILE_NAME);
62
- const readSettingsFromDiskMigrated = async () => {
63
- try {
64
- return JSON.parse(await fs.promises.readFile(settingsPath, 'utf8'));
65
- } catch {
66
- return {};
67
- }
68
- };
69
- const writeSettingsToDisk = async (settings) => {
70
- await fs.promises.mkdir(path.dirname(settingsPath), { recursive: true });
71
- await fs.promises.writeFile(settingsPath, JSON.stringify(settings, null, 2), 'utf8');
72
- };
73
- return { readSettingsFromDiskMigrated, writeSettingsToDisk };
135
+ try {
136
+ return JSON.parse(await fs.promises.readFile(settingsPath, 'utf8'));
137
+ } catch {
138
+ return {};
139
+ }
74
140
  }
75
141
 
76
142
  // Resolves the instance's relay identity (serverId + encryption public key,
77
143
  // generating it if the relay was never enabled) into a pairing-v2 relay
78
144
  // candidate. Relay is a transport, not a separate link format: the candidate
79
145
  // carries no token — the client redeems the one-time pairing secret over the
80
- // E2EE tunnel like any other candidate. `enabled` reports whether the host relay
81
- // is actually on (a relay candidate only connects when the host is relaying).
146
+ // E2EE tunnel like any other candidate. `enabled` reports whether the relay is
147
+ // enabled in settings; `candidate` is null when no relay URL is configured, in
148
+ // which case no identity keys are generated. A relay candidate only connects
149
+ // when the host is relaying.
82
150
  async function buildRelayPairingCandidate() {
83
- const accessors = createSettingsAccessors();
84
- const settings = await accessors.readSettingsFromDiskMigrated();
151
+ const settings = await readPairingRelaySettings();
85
152
  const relayUrl = resolveRelayUrl(settings);
86
- const identityRuntime = createRelayIdentityRuntime({ crypto, ...accessors });
153
+ const enabled = settings?.privateRelay?.enabled === true;
154
+ if (!relayUrl) return { enabled, relayUrl: null, candidate: null };
155
+ const identityRuntime = createRelayIdentityRuntime({
156
+ crypto,
157
+ ...createRelayIdentityStore({ dataDir: getPiChamberDataDir() }),
158
+ });
87
159
  const identity = await identityRuntime.getRelayIdentity();
88
160
  return {
89
- enabled: settings?.privateRelay?.enabled === true,
161
+ enabled,
90
162
  relayUrl,
91
163
  serverId: identity.serverId,
92
164
  candidate: {
@@ -225,7 +297,8 @@ async function displayTunnelQrCode(url) {
225
297
 
226
298
  function createConnectUrlCommand({ serveCommand }) {
227
299
  return async function connectUrlCommand(options = {}) {
228
- assertSafeBrowserPort(options.port, { context: 'PiChamber connect-url' });
300
+ assertSafeBrowserPort(options.port, { context: 'PiChamber pair' });
301
+ assertTailscaleFlagCombination(options);
229
302
  const explicitServerUrl = options.server ? normalizeServerUrlForConnection(options.server) : null;
230
303
  if (options.server && !explicitServerUrl) {
231
304
  throw new TunnelCliError('Invalid --server URL. Use an http:// or https:// URL.', EXIT_CODE.USAGE_ERROR);
@@ -261,18 +334,33 @@ function createConnectUrlCommand({ serveCommand }) {
261
334
  const label = options.name || os.hostname();
262
335
 
263
336
  // Direct candidate for the reachable server URL, plus the relay transport as
264
- // a fallback candidate — one link that works both on the LAN and off-network.
265
- // Candidate priorities make the client prefer the direct route and try the
266
- // relay last, mirroring the UI's "Anywhere" pairing. `--relay` opts in even
267
- // when the host relay is not up yet (the demand-driven lifecycle starts it);
268
- // otherwise the relay rides along only when it is already enabled.
337
+ // a fallback candidate when a relay URL is configured — one link that works
338
+ // both on the LAN and off-network. Candidate priorities make the client
339
+ // prefer the direct route and try the relay last. `--relay` opts in when the
340
+ // relay is enabled in settings; without a configured relay URL there is no
341
+ // relay candidate.
269
342
  const candidates = [{ type: serverUrl.startsWith('https://') ? 'tunnel' : 'lan', url: serverUrl, priority: 10 }];
270
343
  const relay = await buildRelayPairingCandidate();
271
- if (options.relay || relay.enabled) candidates.push(relay.candidate);
344
+ if (options.relay && !relay.relayUrl) {
345
+ throw new TunnelCliError(
346
+ 'Relay requested but no relay URL is configured. Set PICHAMBER_RELAY_URL to a ws:// or wss:// relay URL (self-hosted relay) and try again.',
347
+ EXIT_CODE.USAGE_ERROR,
348
+ );
349
+ }
350
+ if (relay.candidate && (options.relay || relay.enabled)) candidates.push(relay.candidate);
351
+
352
+ // Tailscale: persist the config on the RUNNING server and wait for a
353
+ // terminal state, then append the ts.net URL (when live) as a candidate.
354
+ let tailscale = null;
355
+ if (options.tailscale === true) {
356
+ tailscale = await enableTailscaleForPairing(options);
357
+ const withTailscale = appendTailscaleCandidate(candidates, tailscale);
358
+ candidates.length = 0;
359
+ candidates.push(...withTailscale);
360
+ }
272
361
 
273
362
  const pairingRuntime = createCliPairingRuntime();
274
- // Mark relay-carrying sessions like the server route does, so the host's
275
- // demand-driven relay lifecycle keeps the relay up while the link is pending.
363
+ // The pairing record reflects the transports carried by the link.
276
364
  const usesRelay = candidates.some((candidate) => candidate.type === 'relay');
277
365
  const { pairing } = await pairingRuntime.createPairingSession({ label, usesRelay });
278
366
  const connectUrl = encodePairingConnectUrl(buildPairingPayload({ pairing, label, candidates }));
@@ -286,12 +374,22 @@ function createConnectUrlCommand({ serveCommand }) {
286
374
  expiresAt: pairing.expiresAt,
287
375
  candidates,
288
376
  autoStarted: serverState.autoStarted,
377
+ ...(tailscale ? { tailscale } : {}),
289
378
  });
290
379
  return;
291
380
  }
292
381
 
293
382
  if (isQuietMode(options)) {
294
383
  process.stdout.write(`${connectUrl}\n`);
384
+ // Quiet stdout stays link-only so scripts capturing it do not break;
385
+ // surface a non-active Tailscale outcome on stderr instead.
386
+ if (options.tailscale === true && tailscale && tailscale.state !== 'active') {
387
+ if (tailscale.state === 'needs-approval' && tailscale.approvalUrl) {
388
+ process.stderr.write(`[TAILSCALE_APPROVAL] Approve Tailscale access: ${tailscale.approvalUrl}\n`);
389
+ } else {
390
+ process.stderr.write(`[TAILSCALE_NOT_ACTIVE] Tailscale state is ${tailscale.state ?? 'unknown'}${tailscale.errorMessage ? `: ${tailscale.errorMessage}` : ''}.\n`);
391
+ }
392
+ }
295
393
  return;
296
394
  }
297
395
 
@@ -301,11 +399,20 @@ function createConnectUrlCommand({ serveCommand }) {
301
399
  }
302
400
  logStatus('success', connectUrl);
303
401
  clackLog.info(`Server URL: ${serverUrl}`);
304
- if (options.relay || relay.enabled) {
402
+ if (tailscale) {
403
+ if (tailscale.state === 'active' && tailscale.url) {
404
+ clackLog.info(`Tailscale URL: ${tailscale.url}`);
405
+ } else if (tailscale.state === 'needs-approval' && tailscale.approvalUrl) {
406
+ logStatus('warn', '[TAILSCALE_APPROVAL]', `Approve Tailscale access: ${tailscale.approvalUrl}`);
407
+ } else {
408
+ logStatus('warn', '[TAILSCALE_NOT_ACTIVE]', `Tailscale state is ${tailscale.state ?? 'unknown'}${tailscale.errorMessage ? `: ${tailscale.errorMessage}` : ''}. The link below carries the remaining candidates.`);
409
+ }
410
+ }
411
+ if (relay.candidate && (options.relay || relay.enabled)) {
305
412
  clackLog.info(`Relay fallback: ${relay.relayUrl}`);
306
413
  }
307
- if (options.relay && !relay.enabled) {
308
- logStatus('info', '[RELAY_STARTING]', 'Relay is not up yet. A running instance starts it within a minute; a stopped instance starts it on next launch.');
414
+ if (!relay.candidate && relay.enabled) {
415
+ logStatus('warn', '[RELAY_NO_URL]', 'Relay is enabled in settings but no relay URL is configured (PICHAMBER_RELAY_URL). The link has no relay fallback.');
309
416
  }
310
417
  if (pairing.fingerprint) {
311
418
  clackLog.info(`Fingerprint: ${pairing.fingerprint}`);
@@ -0,0 +1,126 @@
1
+ import { describe, expect, it } from 'vitest';
2
+ import fs from 'node:fs';
3
+ import os from 'node:os';
4
+ import path from 'node:path';
5
+
6
+ import { createConnectUrlCommand } from './commands-connect-url.js';
7
+ import { EXIT_CODE, TunnelCliError } from './cli-errors.js';
8
+
9
+ async function withTempPiChamberDataDir(fn) {
10
+ const previous = process.env.PICHAMBER_DATA_DIR;
11
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'pichamber-connect-url-test-'));
12
+ process.env.PICHAMBER_DATA_DIR = dir;
13
+ try {
14
+ return await fn(dir);
15
+ } finally {
16
+ if (typeof previous === 'string') {
17
+ process.env.PICHAMBER_DATA_DIR = previous;
18
+ } else {
19
+ delete process.env.PICHAMBER_DATA_DIR;
20
+ }
21
+ fs.rmSync(dir, { recursive: true, force: true });
22
+ }
23
+ }
24
+
25
+ async function captureStdout(fn) {
26
+ const originalWrite = process.stdout.write;
27
+ let output = '';
28
+ process.stdout.write = (chunk, encoding, callback) => {
29
+ output += Buffer.isBuffer(chunk) ? chunk.toString('utf8') : String(chunk);
30
+ if (typeof encoding === 'function') encoding();
31
+ if (typeof callback === 'function') callback();
32
+ return true;
33
+ };
34
+ try {
35
+ await fn();
36
+ return output;
37
+ } finally {
38
+ process.stdout.write = originalWrite;
39
+ }
40
+ }
41
+
42
+ const withRelayEnv = async (value, fn) => {
43
+ const previous = process.env.PICHAMBER_RELAY_URL;
44
+ if (value === undefined) {
45
+ delete process.env.PICHAMBER_RELAY_URL;
46
+ } else {
47
+ process.env.PICHAMBER_RELAY_URL = value;
48
+ }
49
+ try {
50
+ return await fn();
51
+ } finally {
52
+ if (typeof previous === 'string') {
53
+ process.env.PICHAMBER_RELAY_URL = previous;
54
+ } else {
55
+ delete process.env.PICHAMBER_RELAY_URL;
56
+ }
57
+ }
58
+ };
59
+
60
+ const runConnectUrl = (options) => {
61
+ const command = createConnectUrlCommand({ serveCommand: async () => {} });
62
+ // Loopback bind keeps server-URL resolution local: no LAN detection, no
63
+ // network. The temp data dir has no registry, so the serve mock auto-starts.
64
+ return command({ port: 45671, host: '127.0.0.1', ...options });
65
+ };
66
+
67
+ describe('connect-url relay candidate', () => {
68
+ it('emits a direct-only link without generating relay identity keys when no relay URL is configured', async () => {
69
+ await withTempPiChamberDataDir(async (dir) => {
70
+ await withRelayEnv(undefined, async () => {
71
+ const output = await captureStdout(() => runConnectUrl({ json: true }));
72
+ const body = JSON.parse(output);
73
+
74
+ expect(body.candidates).toHaveLength(1);
75
+ expect(body.candidates[0].type).not.toBe('relay');
76
+ // No relay URL configured: identity key generation must not run, so
77
+ // the settings file stays untouched.
78
+ expect(fs.existsSync(path.join(dir, 'settings.json'))).toBe(false);
79
+ });
80
+ });
81
+ });
82
+
83
+ it('fails deterministically when --relay has no relay URL configured', async () => {
84
+ for (const mode of [{}, { json: true }, { quiet: true }]) {
85
+ await withTempPiChamberDataDir(async () => {
86
+ await withRelayEnv(undefined, async () => {
87
+ const error = await runConnectUrl({ relay: true, ...mode }).then(
88
+ () => null,
89
+ (caught) => caught,
90
+ );
91
+
92
+ expect(error).toBeInstanceOf(TunnelCliError);
93
+ expect(error.exitCode).toBe(EXIT_CODE.USAGE_ERROR);
94
+ expect(error.message).toContain('PICHAMBER_RELAY_URL');
95
+ });
96
+ });
97
+ }
98
+ });
99
+
100
+ it('uses PICHAMBER_RELAY_URL for the relay candidate when set', async () => {
101
+ await withTempPiChamberDataDir(async () => {
102
+ await withRelayEnv('wss://relay.example.test/ws', async () => {
103
+ const output = await captureStdout(() => runConnectUrl({ json: true, relay: true }));
104
+ const body = JSON.parse(output);
105
+ const relay = body.candidates.find((candidate) => candidate.type === 'relay');
106
+
107
+ expect(relay).toMatchObject({
108
+ relayUrl: 'wss://relay.example.test/ws',
109
+ priority: 30,
110
+ });
111
+ expect(typeof relay.serverId).toBe('string');
112
+ });
113
+ });
114
+ });
115
+
116
+ it('ignores an invalid PICHAMBER_RELAY_URL instead of emitting a relay candidate', async () => {
117
+ await withTempPiChamberDataDir(async () => {
118
+ await withRelayEnv('https://relay.example.test/ws', async () => {
119
+ const output = await captureStdout(() => runConnectUrl({ json: true }));
120
+ const body = JSON.parse(output);
121
+
122
+ expect(body.candidates.some((candidate) => candidate.type === 'relay')).toBe(false);
123
+ });
124
+ });
125
+ });
126
+ });
@@ -2,7 +2,7 @@ import fs from 'fs';
2
2
  import { pathToFileURL } from 'url';
3
3
  import { spawn } from 'child_process';
4
4
  import { EXIT_CODE, TunnelCliError } from './cli-errors.js';
5
- import { buildLocalUrl, resolveServeHost, assertSafeBrowserPort, resolveServeUiPassword, assertAuthenticatedNetworkExposure } from './cli-network.js';
5
+ import { buildLocalUrl, resolveServeHost, assertSafeBrowserPort, hasUiPasswordConfigured, resolveServeUiPassword, assertAuthenticatedNetworkExposure } from './cli-network.js';
6
6
  import { fetchSystemInfoFromPort } from './cli-http.js';
7
7
  import { isPortAvailable, resolveAvailablePort } from './cli-ports.js';
8
8
  import { ensureLogsDir, getLogFilePath } from './cli-paths.js';
@@ -10,7 +10,10 @@ import { rotateLogFile } from './cli-log-files.js';
10
10
  import { discoverPiChamberInstanceOnPort, isDesktopRuntimeForPort } from './cli-lifecycle.js';
11
11
  import { getPidFilePath, getInstanceFilePath, writePidFile, writeInstanceOptions, removePidFile, removeInstanceFile, isProcessRunning, terminateProcessTree } from './cli-process.js';
12
12
  import { resolveServerExecutable as defaultResolveServerExecutable, assertCurrentRuntimeSupported as defaultAssertCurrentRuntimeSupported } from './server-runtime.js';
13
- import { isNetworkExposedBindHost } from '../../server/lib/security/bind-host.js';
13
+ import { isNetworkExposedBindHost, isUnsafeUnauthenticatedLanAllowed } from '../../server/lib/security/bind-host.js';
14
+ import { checkTailscaleAuthGate } from '../../server/lib/tailscale/tailscale.js';
15
+ import { persistTailscaleConfigForStartup } from '../../server/lib/tailscale/service.js';
16
+ import { resolvePiChamberDataDir } from '../../server/lib/pichamber-data-dir.js';
14
17
  import {
15
18
  intro as clackIntro,
16
19
  outro as clackOutro,
@@ -278,6 +281,45 @@ async function serveCommand(options) {
278
281
  host: effectiveHost,
279
282
  uiPassword: effectiveUiPassword,
280
283
  });
284
+ // Tailscale remote access persists server-side and is applied by the
285
+ // server after listen (loopback mapping, so no LAN bind is required).
286
+ // The auth gate is enforced here for a fast deterministic failure AND in
287
+ // the service itself (core-enforced, never UI-only).
288
+ let tailscaleConfig = null;
289
+ if (options.tailscale === true || options.public === true || options.httpsPort !== undefined) {
290
+ if (options.tailscale !== true) {
291
+ throw new TunnelCliError('Use --tailscale with --public / --https-port.', EXIT_CODE.USAGE_ERROR);
292
+ }
293
+ const tailscaleMode = options.public === true ? 'public' : 'private';
294
+ const tailscaleHttpsPort = options.httpsPort ?? 443;
295
+ const gate = checkTailscaleAuthGate({
296
+ enabled: true,
297
+ mode: tailscaleMode,
298
+ uiPasswordConfigured: hasUiPasswordConfigured(effectiveUiPassword),
299
+ unsafeUnauthenticatedLanAllowed: isUnsafeUnauthenticatedLanAllowed(process.env),
300
+ });
301
+ if (!gate.allowed) {
302
+ throw new TunnelCliError(gate.message, EXIT_CODE.AUTH_CONFIG_ERROR);
303
+ }
304
+ tailscaleConfig = await persistTailscaleConfigForStartup({
305
+ dataDir: resolvePiChamberDataDir(),
306
+ patch: { enabled: true, mode: tailscaleMode, httpsPort: tailscaleHttpsPort },
307
+ uiPasswordConfigured: hasUiPasswordConfigured(effectiveUiPassword),
308
+ unsafeUnauthenticatedLanAllowed: isUnsafeUnauthenticatedLanAllowed(process.env),
309
+ });
310
+ emitNotice({
311
+ level: 'info',
312
+ code: 'TAILSCALE_ENABLED',
313
+ message: `Tailscale ${tailscaleMode === 'public' ? 'Funnel (public)' : 'serve (tailnet-only)'} enabled on HTTPS port ${tailscaleConfig.httpsPort}.`,
314
+ });
315
+ // Startup reconcile runs in the background (approval may take
316
+ // minutes), so the mapping may not be active yet when serve returns.
317
+ emitNotice({
318
+ level: 'info',
319
+ code: 'TAILSCALE_STARTING',
320
+ message: 'Tailscale applies in the background; check `pichamber status` or Settings → Remote Access for the live state.',
321
+ });
322
+ }
281
323
  if (!effectiveUiPassword && !options.suppressUiPasswordWarning) {
282
324
  const bindHost = effectiveHost;
283
325
  const networkExposed = isNetworkExposedBindHost(bindHost);
@@ -553,6 +595,7 @@ async function serveCommand(options) {
553
595
  ...serveResult,
554
596
  messages: jsonMessages,
555
597
  ...(autoGeneratedUiPassword ? { password: effectiveUiPassword } : {}),
598
+ ...(tailscaleConfig ? { tailscale: tailscaleConfig } : {}),
556
599
  });
557
600
  return resolvedPort;
558
601
  }