@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
package/dist/sw.js CHANGED
@@ -1 +1 @@
1
- (function(){"use strict";self.addEventListener("install",t=>{t.waitUntil(self.skipWaiting())}),self.addEventListener("activate",t=>{t.waitUntil(self.clients.claim())}),self.addEventListener("push",t=>{t.waitUntil((async()=>{const i=t.data?.json()??null;if(!i||(await self.clients.matchAll({type:"window",includeUncontrolled:!0})).some(l=>l.visibilityState==="visible"||l.focused))return;const s=i.title||"PiChamber",a=i.body??"",o=i.icon??"/apple-touch-icon-180x180.png",c=i.badge??"/favicon-32.png";await self.registration.showNotification(s,{body:a,icon:o,badge:c,tag:i.tag,data:i.data})})())}),self.addEventListener("notificationclick",t=>{t.notification.close();const i=t.notification.data??null,n=typeof i?.url=="string"?i.url:"",e=n.startsWith("/")&&!n.startsWith("//");let s="/";if(e)s=n;else try{const a=new URL(n);(a.protocol==="http:"||a.protocol==="https:")&&(s=n)}catch{}t.waitUntil(self.clients.openWindow(s))})})();
1
+ (function(){"use strict";self.addEventListener("install",t=>{t.waitUntil(self.skipWaiting())}),self.addEventListener("activate",t=>{t.waitUntil(self.clients.claim())}),self.addEventListener("notificationclick",t=>{t.notification.close();const n=t.notification.data??null,i=typeof n?.url=="string"?n.url:"",e=i.startsWith("/")&&!i.startsWith("//");let s="/";if(e)s=i;else try{const l=new URL(i);(l.protocol==="http:"||l.protocol==="https:")&&(s=i)}catch{}t.waitUntil(self.clients.openWindow(s))})})();
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@pi-chamber/web",
3
- "version": "1.0.4",
3
+ "version": "1.0.5-rc.2",
4
4
  "private": false,
5
5
  "type": "module",
6
6
  "engines": {
@@ -49,7 +49,6 @@
49
49
  "reflect-metadata": "^0.2.2",
50
50
  "sherpa-onnx-node": "1.12.28",
51
51
  "simple-git": "^3.36.0",
52
- "web-push": "^3.6.7",
53
52
  "ws": "^8.18.3",
54
53
  "yaml": "^2.8.1"
55
54
  },
package/server/index.js CHANGED
@@ -1,11 +1,10 @@
1
1
  import 'reflect-metadata';
2
2
  import compression from 'compression';
3
3
  import express from 'express';
4
+ import crypto from 'node:crypto';
4
5
  import fs from 'node:fs';
5
6
  import http from 'node:http';
6
- import crypto from 'node:crypto';
7
7
  import os from 'node:os';
8
- import webPush from 'web-push';
9
8
  import path from 'node:path';
10
9
  import { fileURLToPath } from 'node:url';
11
10
 
@@ -14,12 +13,13 @@ import { createRemoteClientAuthRuntime } from './lib/client-auth/remote-clients.
14
13
  import { createRevocationCoordinator } from './lib/client-auth/principal-tracker.js';
15
14
  import { resolvePiChamberDataDir } from './lib/pichamber-data-dir.js';
16
15
  import { createTunnelService } from './lib/server/tunnel-service.js';
16
+ import { createTailscaleService } from './lib/tailscale/service.js';
17
+ import { createServerIdResolver } from './lib/relay/server-id.js';
18
+ import { registerTailscaleRoutes } from './lib/tailscale/routes.js';
17
19
  import { registerPiRuntimeRoutes } from './lib/pi/routes.js';
18
20
  import { createDockerInitialLocalSettings, createPiUiSettingsStore } from './lib/pi/ui-settings-store.js';
19
21
  import { detectLinuxDistribution } from './lib/server/linux-distribution.js';
20
- import { createNotificationDeliveryRuntime } from './lib/notifications/delivery-runtime.js';
21
22
  import { createPiNotificationWatcher } from './lib/notifications/pi-notification-watcher.js';
22
- import { registerNotificationRoutes } from './lib/notifications/routes.js';
23
23
  import { registerWorkspaceIntegrations } from './lib/workspace/host.js';
24
24
  import { createPiSessionDaemonSupervisor } from './lib/pi/session-daemon/supervisor.js';
25
25
  import {
@@ -129,13 +129,6 @@ export async function startWebUiServer(options = {}) {
129
129
  const apiOnly = options.apiOnly === true || isEnvFlagEnabled(process.env.PICHAMBER_API_ONLY);
130
130
  const app = express();
131
131
  const server = http.createServer(app);
132
- const pairingTransports = createPairingTransportResolvers({
133
- getPort: () => {
134
- const address = server.address();
135
- return typeof address === 'object' && address ? address.port : null;
136
- },
137
- bindHost: host,
138
- });
139
132
  const serverStartedAt = new Date().toISOString();
140
133
  const dataPath = (name) => path.join(PICHAMBER_DATA_DIR, name);
141
134
  const remoteClientAuthRuntime = createRemoteClientAuthRuntime({ fsPromises: fs.promises, path, crypto: await import('node:crypto'), storePath: dataPath('remote-clients.json') });
@@ -160,12 +153,6 @@ export async function startWebUiServer(options = {}) {
160
153
  ? createDockerInitialLocalSettings()
161
154
  : {},
162
155
  });
163
- const notificationDelivery = createNotificationDeliveryRuntime({
164
- dataDir: PICHAMBER_DATA_DIR,
165
- webPush,
166
- crypto,
167
- onDesktopNotification: options.onDesktopNotification,
168
- });
169
156
  const tunnelService = createTunnelService({
170
157
  dataDir: PICHAMBER_DATA_DIR,
171
158
  getPort: () => {
@@ -175,6 +162,44 @@ export async function startWebUiServer(options = {}) {
175
162
  tunnelAuthController,
176
163
  getServerLabel: () => os.hostname() || 'PiChamber',
177
164
  });
165
+ const hasUiPasswordConfigured = () => typeof uiPassword === 'string' && uiPassword.trim().length > 0;
166
+ // One stable server identity: the relay signing-key serverId, shared by
167
+ // /health, /api/version, connection candidates, and the Tailscale probe.
168
+ const serverIdResolver = createServerIdResolver({ dataDir: PICHAMBER_DATA_DIR, crypto });
169
+ // Resolve the identity before anything can rewrite settings.json: the UI
170
+ // settings store drops keys it does not own, so a legacy install's key must
171
+ // be copied into relay-identity.json first. Failure is not fatal here; the
172
+ // routes retry on demand.
173
+ await serverIdResolver.getServerId().catch((error) => {
174
+ console.warn(`[relay-identity] Failed to resolve serverId at startup: ${error?.message || error}`);
175
+ });
176
+ // Tailscale remote access (tailnet-only serve / public funnel). Off by
177
+ // default; enabled only via its settings API or CLI flags. The service
178
+ // owns its persisted config, lifecycle and conflict rules — see
179
+ // `packages/web/server/lib/tailscale/DOCUMENTATION.md`.
180
+ const tailscaleService = createTailscaleService({
181
+ dataDir: PICHAMBER_DATA_DIR,
182
+ getServerId: serverIdResolver.getServerId,
183
+ getPort: () => {
184
+ const address = server.address();
185
+ return typeof address === 'object' && address ? address.port : null;
186
+ },
187
+ isUiAuthEnabled: hasUiPasswordConfigured,
188
+ isUnsafeUnauthenticatedLanAllowed: () => isUnsafeUnauthenticatedLanAllowed(process.env),
189
+ });
190
+ try {
191
+ await tailscaleService.loadConfig();
192
+ } catch (error) {
193
+ console.warn(`[tailscale] Failed to load persisted config: ${error?.message || error}`);
194
+ }
195
+ const pairingTransports = createPairingTransportResolvers({
196
+ getPort: () => {
197
+ const address = server.address();
198
+ return typeof address === 'object' && address ? address.port : null;
199
+ },
200
+ bindHost: host,
201
+ getTailscaleCandidate: () => tailscaleService.getPairingCandidate(),
202
+ });
178
203
  let stopped = false;
179
204
 
180
205
  // trust proxy = true is intentional for PiChamber's deployment model:
@@ -212,7 +237,7 @@ export async function startWebUiServer(options = {}) {
212
237
  return typeof address === 'object' && address ? address.port : null;
213
238
  },
214
239
  getTunnelUrl: () => null,
215
- getServerId: async () => null,
240
+ getServerId: serverIdResolver.getServerId,
216
241
  tunnelAuthController,
217
242
  uiAuthController,
218
243
  });
@@ -228,15 +253,15 @@ export async function startWebUiServer(options = {}) {
228
253
  normalizeTunnelSessionTtlMs: () => 8 * 60 * 60 * 1000,
229
254
  getPairingTransports: () => pairingTransports.getPairingTransports(),
230
255
  getDirectCandidateUrls: () => pairingTransports.getDirectCandidateUrls(),
231
- getServerId: async () => null,
256
+ getTailscalePairingCandidate: () => tailscaleService.getPairingCandidate(),
257
+ getServerId: serverIdResolver.getServerId,
232
258
  getServerLabel: () => os.hostname() || 'PiChamber',
233
259
  });
234
260
  const piRuntimeRoutes = registerPiRuntimeRoutes(app, {
235
261
  getPiSessionDaemonRuntime: () => piSessionDaemonRuntime,
236
262
  uiSettingsStore,
237
263
  });
238
- registerNotificationRoutes(app, { uiAuthController, delivery: notificationDelivery });
239
- // Cloudflare Tunnel external access (manual token + quick modes).
264
+ // Cloudflare Tunnel external access (managed-remote and managed-local modes).
240
265
  const requireTunnelAuth = (req, res, next) => uiAuthController.requireAuth(req, res, next);
241
266
  app.get('/api/pichamber/tunnel/status', requireTunnelAuth, async (_req, res) => {
242
267
  try { res.json(await tunnelService.getStatus()); } catch (error) { res.status(500).json({ error: error?.message || 'Failed to get tunnel status' }); }
@@ -245,10 +270,10 @@ export async function startWebUiServer(options = {}) {
245
270
  try { res.json(await tunnelService.check(req.query?.provider)); } catch (error) { res.status(500).json({ error: error?.message || 'Tunnel check failed' }); }
246
271
  });
247
272
  app.get('/api/pichamber/tunnel/providers', requireTunnelAuth, async (_req, res) => {
248
- res.json({ providers: [{ provider: 'cloudflare', modes: [{ key: 'quick' }, { key: 'managed-remote' }, { key: 'managed-local' }] }] });
273
+ res.json({ providers: [{ provider: 'cloudflare', modes: [{ key: 'managed-remote' }, { key: 'managed-local' }] }] });
249
274
  });
250
275
  app.post('/api/pichamber/tunnel/start', express.json({ limit: '64kb' }), requireTunnelAuth, async (req, res) => {
251
- try { const result = await tunnelService.start(req.body ?? {}); res.json(result); } catch (error) { const code = error?.code === 'missing_dependency' ? 400 : error?.code === 'validation_error' ? 422 : 500; res.status(code).json({ ok: false, error: error?.message || 'Failed to start tunnel', code: error?.code }); }
276
+ try { const result = await tunnelService.start(req.body ?? {}); res.json(result); } catch (error) { const code = error?.code === 'missing_dependency' ? 400 : error?.code === 'quick_tunnel_removed' ? 410 : error?.code === 'validation_error' ? 422 : 500; res.status(code).json({ ok: false, error: error?.message || 'Failed to start tunnel', code: error?.code }); }
252
277
  });
253
278
  app.post('/api/pichamber/tunnel/stop', requireTunnelAuth, async (_req, res) => {
254
279
  try { res.json(await tunnelService.stop()); } catch (error) { res.status(500).json({ error: error?.message || 'Failed to stop tunnel' }); }
@@ -259,10 +284,21 @@ export async function startWebUiServer(options = {}) {
259
284
  app.get('/api/pichamber/tunnel/doctor', requireTunnelAuth, async (req, res) => {
260
285
  try { const status = await tunnelService.getStatus(); const checkResult = await tunnelService.check(); res.json({ ok: true, status, check: checkResult, query: req.query }); } catch (error) { res.status(500).json({ ok: false, error: error?.message || 'Doctor failed' }); }
261
286
  });
287
+ registerTailscaleRoutes(app, { express, tailscaleService, uiAuthController });
262
288
  const workspaceRuntime = registerWorkspaceIntegrations({ app, server, express, uiAuthController, dataDir: PICHAMBER_DATA_DIR, liveRevocation });
263
289
  registerStaticRoutes(app, { apiOnly });
264
290
 
265
291
  await listen(server, port, host);
292
+ // Tailscale mappings apply only after the server is listening (they front
293
+ // the bound loopback port). Reconcile runs in the background so an
294
+ // approval wait (up to 5 minutes) never blocks server-ready; status
295
+ // reports starting/needs-approval meanwhile. A failure never stops
296
+ // startup: the status model carries the error and
297
+ // `POST /api/pichamber/tailscale/retry` (or a config change) reconciles
298
+ // again. Rejections are caught and logged — never unhandled.
299
+ void tailscaleService.reconcile().catch((error) => {
300
+ console.warn(`[tailscale] Failed to apply mapping on startup: ${error?.message || error}`);
301
+ });
266
302
  const resolvedPort = typeof server.address() === 'object' && server.address() ? server.address().port : null;
267
303
  piSessionDaemonRuntime = createPiSessionDaemonSupervisor({
268
304
  dataDir: PICHAMBER_DATA_DIR,
@@ -278,12 +314,16 @@ export async function startWebUiServer(options = {}) {
278
314
  }
279
315
  // Warm startup creates the daemon credential before subscriptions can read
280
316
  // it. The watcher then owns transport retries independently of browsers so
281
- // native background push keeps working after reconnects.
282
- notificationWatcher = createPiNotificationWatcher({
283
- supervisor: piSessionDaemonRuntime,
284
- uiSettingsStore,
285
- delivery: notificationDelivery,
286
- });
317
+ // the local desktop notification still fires after reconnects. Web/CLI
318
+ // servers have no local delivery, so the watcher only runs when Electron
319
+ // supplies its native notification callback.
320
+ if (typeof options.onDesktopNotification === 'function') {
321
+ notificationWatcher = createPiNotificationWatcher({
322
+ supervisor: piSessionDaemonRuntime,
323
+ uiSettingsStore,
324
+ notify: options.onDesktopNotification,
325
+ });
326
+ }
287
327
  void piSessionDaemonRuntime.start()
288
328
  .catch((error) => {
289
329
  console.warn(`[PiSessionDaemon] unavailable: ${error?.code ?? 'DAEMON_UNAVAILABLE'}`);
@@ -300,7 +340,8 @@ export async function startWebUiServer(options = {}) {
300
340
  },
301
341
  getTunnelUrl: () => null,
302
342
  getDaemonProfileKey: () => piSessionDaemonRuntime?.paths?.profileKey ?? null,
303
- getQuitRiskStatus: () => ({ tunnel: { active: false } }),
343
+ getTailscaleStatus: () => tailscaleService.getStatus(),
344
+ getQuitRiskStatus: () => ({ tunnel: { active: false }, tailscale: tailscaleService.getTransports() }),
304
345
  isReady: () => !stopped,
305
346
  stop: async ({ exitProcess = false } = {}) => {
306
347
  if (stopped) return;
@@ -314,6 +355,7 @@ export async function startWebUiServer(options = {}) {
314
355
  notificationWatcher?.stop(),
315
356
  workspaceRuntime.shutdown(),
316
357
  piSessionDaemonRuntime ? piSessionDaemonRuntime.stop() : Promise.resolve(),
358
+ tailscaleService.shutdown(),
317
359
  close(server),
318
360
  ]);
319
361
  uiAuthController.dispose?.();
@@ -87,7 +87,7 @@ closed when their mint token ages out.
87
87
  response reports `closedConnections`.
88
88
  - **Cross-process propagation**: the credential store is a file shared by
89
89
  processes using the data directory (one server plus the
90
- `pichamber connect-url` pairing CLI, which shares only
90
+ `pichamber pair` pairing CLI, which shares only
91
91
  `remote-clients.json`). No cross-process revocation emitter exists, and none
92
92
  is claimed. Propagation is a **bounded poll** of `listRevokedClientIds()`
93
93
  (default every 15 seconds, timer unref'd); a revocation committed by another
@@ -163,6 +163,20 @@ never happened.
163
163
  enforced at the core route; the tracker keys off the store-derived
164
164
  principal only and never trusts a caller-supplied ID.
165
165
 
166
+ ## Pairing candidates (routes in `../server/core-routes.js`)
167
+
168
+ Pairing v2 payloads (`POST /api/client-auth/pairing/sessions`) and the
169
+ refresh endpoint (`GET /api/client-auth/connection/candidates`) advertise
170
+ transport candidates ordered by priority: direct LAN (`lan`, 10), Tailscale
171
+ (`tailscale`, 20, only while the mapping is `active` — see
172
+ `../tailscale/DOCUMENTATION.md`), relay (`relay`, 30). The Tailscale
173
+ candidate is `{ type: 'tailscale', url, mode, priority }` and is redeemed
174
+ over its `url` like any direct URL. `tailscale` is a distinct type so new
175
+ clients can label it; old parsers drop unknown candidate types, so old
176
+ clients ignore it and use the rest. `GET
177
+ /api/client-auth/pairing/transports` additionally reports
178
+ `tailscale: { available, url, mode }` for the create-device dialog.
179
+
166
180
  ## Verification
167
181
 
168
182
  ```sh
@@ -1,3 +1,4 @@
1
+ import { writeFileAtomic } from '../fs/atomic-write.js';
1
2
  import { withCrossProcessLock } from '../server/cross-process-lock.js';
2
3
 
3
4
  const STORE_VERSION = 1;
@@ -158,18 +159,7 @@ export const createClientPairingRuntime = ({
158
159
  };
159
160
 
160
161
  const writeStore = async (store) => {
161
- await fsPromises.mkdir(path.dirname(storePath), { recursive: true, mode: 0o700 });
162
- const temporary = `${storePath}.tmp-${process.pid}-${crypto.randomBytes(8).toString('hex')}`;
163
- try {
164
- await fsPromises.writeFile(temporary, JSON.stringify(normalizeStore(store), null, 2), { mode: 0o600 });
165
- await fsPromises.rename(temporary, storePath);
166
- } catch (error) {
167
- await fsPromises.rm?.(temporary, { force: true }).catch(() => {});
168
- throw error;
169
- }
170
- if (typeof fsPromises.chmod === 'function') {
171
- await fsPromises.chmod(storePath, 0o600).catch(() => {});
172
- }
162
+ await writeFileAtomic(storePath, JSON.stringify(normalizeStore(store), null, 2), { fs: fsPromises });
173
163
  };
174
164
 
175
165
  const sweepExpiredSessionsFromStore = (store) => {
@@ -1,3 +1,4 @@
1
+ import { writeFileAtomic } from '../fs/atomic-write.js';
1
2
  import { withCrossProcessLock } from '../server/cross-process-lock.js';
2
3
 
3
4
  const STORE_VERSION = 1;
@@ -109,18 +110,7 @@ export const createRemoteClientAuthRuntime = ({ fsPromises, path, crypto, storeP
109
110
  };
110
111
 
111
112
  const writeStore = async (store) => {
112
- await fsPromises.mkdir(path.dirname(storePath), { recursive: true, mode: 0o700 });
113
- const temporary = `${storePath}.tmp-${process.pid}-${crypto.randomBytes(8).toString('hex')}`;
114
- try {
115
- await fsPromises.writeFile(temporary, JSON.stringify(normalizeStore(store), null, 2), { mode: 0o600 });
116
- await fsPromises.rename(temporary, storePath);
117
- } catch (error) {
118
- await fsPromises.rm?.(temporary, { force: true }).catch(() => {});
119
- throw error;
120
- }
121
- if (typeof fsPromises.chmod === 'function') {
122
- await fsPromises.chmod(storePath, 0o600).catch(() => {});
123
- }
113
+ await writeFileAtomic(storePath, JSON.stringify(normalizeStore(store), null, 2), { fs: fsPromises });
124
114
  };
125
115
 
126
116
  const publicClient = (client) => ({
@@ -12,12 +12,8 @@ import {
12
12
  const __filename = fileURLToPath(import.meta.url);
13
13
  const __dirname = path.dirname(__filename);
14
14
 
15
- const TRY_CF_URL_REGEX = /https:\/\/[a-z0-9-]+\.trycloudflare\.com/i;
16
-
17
- const DEFAULT_STARTUP_TIMEOUT_MS = 30000;
18
15
  const MANAGED_TUNNEL_STARTUP_TIMEOUT_MS = 20000;
19
16
  const MANAGED_TUNNEL_LIVENESS_FALLBACK_MS = 6000;
20
- const TUNNEL_MODE_QUICK = 'quick';
21
17
  const TUNNEL_MODE_MANAGED_REMOTE = 'managed-remote';
22
18
  const TUNNEL_MODE_MANAGED_LOCAL = 'managed-local';
23
19
 
@@ -103,39 +99,6 @@ export function normalizeCloudflareTunnelHostname(value) {
103
99
  return normalizeHostname(value);
104
100
  }
105
101
 
106
- export async function checkCloudflareApiReachability({ fetchImpl = globalThis.fetch, timeoutMs = 5000 } = {}) {
107
- if (typeof fetchImpl !== 'function') {
108
- return {
109
- reachable: false,
110
- status: null,
111
- error: 'Fetch API is unavailable in this runtime.',
112
- };
113
- }
114
-
115
- const controller = new AbortController();
116
- const timeout = setTimeout(() => controller.abort(), timeoutMs);
117
- try {
118
- const response = await fetchImpl('https://api.trycloudflare.com/', {
119
- method: 'GET',
120
- signal: controller.signal,
121
- });
122
- return {
123
- reachable: true,
124
- status: response.status,
125
- error: null,
126
- };
127
- } catch (error) {
128
- const message = error instanceof Error ? error.message : String(error);
129
- return {
130
- reachable: false,
131
- status: null,
132
- error: message,
133
- };
134
- } finally {
135
- clearTimeout(timeout);
136
- }
137
- }
138
-
139
102
  const READY_LOG_PATTERNS = [
140
103
  /registered tunnel connection/i,
141
104
  /connection[^\n]*registered/i,
@@ -353,96 +316,6 @@ async function waitForManagedTunnelReady(child, { modeLabel }) {
353
316
  });
354
317
  }
355
318
 
356
- export async function startCloudflareQuickTunnel({ originUrl }) {
357
- const cfCheck = await checkCloudflaredAvailable();
358
-
359
- if (!cfCheck.available) {
360
- printCloudflareTunnelInstallHelp();
361
- throw new Error('cloudflared is not installed');
362
- }
363
-
364
- console.log(`Using cloudflared: ${cfCheck.path} (${cfCheck.version})`);
365
-
366
- const tempDir = fs.mkdtempSync(path.join(os.tmpdir(), 'pichamber-cf-'));
367
-
368
- const child = spawnCloudflared(['tunnel', '--url', originUrl], { HOME: tempDir }, cfCheck.path);
369
-
370
- let publicUrl = null;
371
- let tunnelReady = false;
372
-
373
- const onData = (chunk, isStderr) => {
374
- const text = chunk.toString('utf8');
375
-
376
- if (!tunnelReady) {
377
- const match = text.match(TRY_CF_URL_REGEX);
378
- if (match) {
379
- publicUrl = match[0];
380
- tunnelReady = true;
381
- }
382
- }
383
-
384
- process.stderr.write(isStderr ? text : '');
385
- };
386
-
387
- child.stdout.on('data', (chunk) => onData(chunk, false));
388
- child.stderr.on('data', (chunk) => onData(chunk, true));
389
-
390
- child.on('error', (error) => {
391
- console.error(`Cloudflared error: ${error.message}`);
392
- cleanupTempDir();
393
- });
394
-
395
- const cleanupTempDir = () => {
396
- try {
397
- if (fs.existsSync(tempDir)) {
398
- fs.rmSync(tempDir, { recursive: true, force: true });
399
- }
400
- } catch {
401
- // Ignore cleanup errors
402
- }
403
- };
404
-
405
- await new Promise((resolve, reject) => {
406
- const timeout = setTimeout(() => {
407
- if (!publicUrl) {
408
- try { child.kill('SIGINT'); } catch { /* ignore */ }
409
- cleanupTempDir();
410
- reject(new Error('Tunnel URL not received within 30 seconds'));
411
- }
412
- }, DEFAULT_STARTUP_TIMEOUT_MS);
413
-
414
- const checkReady = setInterval(() => {
415
- if (publicUrl) {
416
- clearTimeout(timeout);
417
- clearInterval(checkReady);
418
- resolve(null);
419
- }
420
- }, 100);
421
-
422
- child.on('exit', (code) => {
423
- clearTimeout(timeout);
424
- clearInterval(checkReady);
425
- cleanupTempDir();
426
- if (code !== null && code !== 0) {
427
- reject(new Error(`Cloudflared exited with code ${code}`));
428
- }
429
- });
430
- });
431
-
432
- return {
433
- mode: TUNNEL_MODE_QUICK,
434
- stop: () => {
435
- try {
436
- child.kill('SIGINT');
437
- } catch {
438
- // Ignore
439
- }
440
- },
441
- process: child,
442
- getPublicUrl: () => publicUrl,
443
- };
444
- }
445
-
446
319
  export async function startCloudflareManagedRemoteTunnel({ token, hostname, tokenFilePath }) {
447
320
  const cfCheck = await checkCloudflaredAvailable();
448
321
 
@@ -599,8 +472,3 @@ export async function startCloudflareManagedLocalTunnel({ configPath, hostname }
599
472
  getEffectiveConfigPath: () => effectiveConfigPath,
600
473
  };
601
474
  }
602
-
603
- async function startCloudflareTunnel({ originUrl, port }) {
604
- void port;
605
- return startCloudflareQuickTunnel({ originUrl });
606
- }
@@ -6,6 +6,14 @@ Own filesystem API behavior for the web server runtime, including workspace-boun
6
6
  ## Entrypoints and structure
7
7
  - `packages/web/server/lib/fs/routes.js`: route registration and runtime-owned state for `/api/fs/*` endpoints.
8
8
  - `packages/web/server/lib/fs/search.js`: bounded-concurrency fuzzy filesystem search runtime used by `GET /api/fs/find`.
9
+ - `packages/web/server/lib/fs/atomic-write.js`: shared symlink-preserving atomic write for server-owned config and state files.
10
+
11
+ ## Atomic config/state writes
12
+ - `writeFileAtomic(file, data, { fs, encoding, mode = 0o600, dirMode = 0o700 })` and `writeFileAtomicSync(...)` write a temp file and rename it over the file's real target, then chmod that target (best effort, skipped on Windows; a chmod failure does not fail the write because the content is already in place). They return the written target path.
13
+ - Symlinks are preserved so user-managed links (for example GNU Stow dotfiles for `settings.json`, `pi/snippets.json`, `stt/config.json`) keep receiving changes. Existing paths resolve through `realpath`. A missing path is written in place. A dangling link writes to its target path, resolved relative to the link's directory, and creates the target's parent directory.
14
+ - The temp file lives in the real target's directory so the rename stays on one filesystem. It is removed when the write or rename fails, and the previous content is left untouched.
15
+ - Cross-process locking stays with callers, keyed on the caller-facing path (`${file}.lock`), so locking semantics do not change when a file becomes a symlink.
16
+ - Injected `fs` objects must provide `realpath`, `readlink`, `mkdir`, `writeFile`, `rename`, `rm`, and `chmod` (or the `*Sync` equivalents).
9
17
 
10
18
  ## Public exports
11
19
  - `registerFsRoutes(app, dependencies)` from `routes.js`
@@ -0,0 +1,111 @@
1
+ import { randomUUID } from 'node:crypto';
2
+ import fsSync from 'node:fs';
3
+ import fsPromises from 'node:fs/promises';
4
+ import path from 'node:path';
5
+
6
+ const MAX_SYMLINK_HOPS = 40;
7
+
8
+ const symlinkLoopError = (file) => {
9
+ const error = new Error(`Too many symbolic links while resolving ${file}`);
10
+ error.code = 'ELOOP';
11
+ return error;
12
+ };
13
+
14
+ const isMissingOrNotLink = (error) => error?.code === 'ENOENT' || error?.code === 'EINVAL' || error?.code === 'UNKNOWN';
15
+
16
+ const temporaryPathFor = (target) => `${target}.tmp-${process.pid}-${randomUUID()}`;
17
+
18
+ /**
19
+ * Resolve the path an atomic write must replace so a symlinked file (for
20
+ * example a GNU Stow-managed config) keeps its link. Existing targets resolve
21
+ * through realpath. A missing file resolves to itself. A dangling link resolves
22
+ * to the path it points at, relative to the link's directory.
23
+ */
24
+ const resolveAtomicWriteTarget = async (file, fs = fsPromises) => {
25
+ try {
26
+ return await fs.realpath(file);
27
+ } catch (error) {
28
+ if (error?.code !== 'ENOENT') throw error;
29
+ }
30
+ let current = file;
31
+ for (let hop = 0; hop < MAX_SYMLINK_HOPS; hop += 1) {
32
+ let link;
33
+ try {
34
+ link = await fs.readlink(current);
35
+ } catch (error) {
36
+ if (isMissingOrNotLink(error)) return current;
37
+ throw error;
38
+ }
39
+ current = path.resolve(path.dirname(current), link);
40
+ }
41
+ throw symlinkLoopError(file);
42
+ };
43
+
44
+ const resolveAtomicWriteTargetSync = (file, fs = fsSync) => {
45
+ try {
46
+ return fs.realpathSync(file);
47
+ } catch (error) {
48
+ if (error?.code !== 'ENOENT') throw error;
49
+ }
50
+ let current = file;
51
+ for (let hop = 0; hop < MAX_SYMLINK_HOPS; hop += 1) {
52
+ let link;
53
+ try {
54
+ link = fs.readlinkSync(current);
55
+ } catch (error) {
56
+ if (isMissingOrNotLink(error)) return current;
57
+ throw error;
58
+ }
59
+ current = path.resolve(path.dirname(current), link);
60
+ }
61
+ throw symlinkLoopError(file);
62
+ };
63
+
64
+ /**
65
+ * Atomically replace `file` with `data` (temp file + rename in the real
66
+ * target's directory) without replacing a symlink at `file`. Returns the path
67
+ * that was written. Callers own any cross-process locking; keep lock keys on
68
+ * the caller-facing `file` path.
69
+ */
70
+ export const writeFileAtomic = async (file, data, {
71
+ fs = fsPromises,
72
+ encoding = 'utf8',
73
+ mode = 0o600,
74
+ dirMode = 0o700,
75
+ } = {}) => {
76
+ const target = await resolveAtomicWriteTarget(file, fs);
77
+ await fs.mkdir(path.dirname(target), { recursive: true, mode: dirMode });
78
+ const temporary = temporaryPathFor(target);
79
+ try {
80
+ await fs.writeFile(temporary, data, { encoding, mode });
81
+ await fs.rename(temporary, target);
82
+ } catch (error) {
83
+ await fs.rm(temporary, { force: true }).catch(() => {});
84
+ throw error;
85
+ }
86
+ // Best effort: the new content is already in place, so a chmod failure must not fail the save.
87
+ if (process.platform !== 'win32') await fs.chmod(target, mode).catch(() => {});
88
+ return target;
89
+ };
90
+
91
+ export const writeFileAtomicSync = (file, data, {
92
+ fs = fsSync,
93
+ encoding = 'utf8',
94
+ mode = 0o600,
95
+ dirMode = 0o700,
96
+ } = {}) => {
97
+ const target = resolveAtomicWriteTargetSync(file, fs);
98
+ fs.mkdirSync(path.dirname(target), { recursive: true, mode: dirMode });
99
+ const temporary = temporaryPathFor(target);
100
+ try {
101
+ fs.writeFileSync(temporary, data, { encoding, mode });
102
+ fs.renameSync(temporary, target);
103
+ } catch (error) {
104
+ try { fs.rmSync(temporary, { force: true }); } catch {}
105
+ throw error;
106
+ }
107
+ if (process.platform !== 'win32') {
108
+ try { fs.chmodSync(target, mode); } catch {}
109
+ }
110
+ return target;
111
+ };