harnery 0.42.0 → 0.44.0

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 (343) hide show
  1. package/README.md +3 -3
  2. package/dist/commander.d.ts +16 -0
  3. package/dist/commander.d.ts.map +1 -1
  4. package/dist/commander.js +18 -0
  5. package/dist/commands/agents.d.ts.map +1 -1
  6. package/dist/commands/agents.js +95 -52
  7. package/dist/commands/browse.d.ts.map +1 -1
  8. package/dist/commands/browse.js +38 -11
  9. package/dist/commands/diagnostics.d.ts.map +1 -1
  10. package/dist/commands/diagnostics.js +10 -0
  11. package/dist/commands/doctor.d.ts +12 -0
  12. package/dist/commands/doctor.d.ts.map +1 -1
  13. package/dist/commands/doctor.js +22 -7
  14. package/dist/commands/governor.js +22 -10
  15. package/dist/commands/inbox.d.ts +1 -1
  16. package/dist/commands/inbox.d.ts.map +1 -1
  17. package/dist/commands/inbox.js +55 -2
  18. package/dist/commands/rm.d.ts.map +1 -1
  19. package/dist/commands/rm.js +28 -4
  20. package/dist/commands/servers.d.ts.map +1 -1
  21. package/dist/commands/servers.js +16 -1
  22. package/dist/commands/supervisor.d.ts.map +1 -1
  23. package/dist/commands/supervisor.js +7 -2
  24. package/dist/commands/toc.d.ts +14 -0
  25. package/dist/commands/toc.d.ts.map +1 -1
  26. package/dist/commands/toc.js +7 -4
  27. package/dist/commands/tunnel.d.ts +65 -0
  28. package/dist/commands/tunnel.d.ts.map +1 -1
  29. package/dist/commands/tunnel.js +290 -101
  30. package/dist/commands/web-fetch.d.ts +3 -2
  31. package/dist/commands/web-fetch.d.ts.map +1 -1
  32. package/dist/commands/web-fetch.js +25 -19
  33. package/dist/commands/web.d.ts +7 -1
  34. package/dist/commands/web.d.ts.map +1 -1
  35. package/dist/commands/web.js +9 -3
  36. package/dist/commands/workflow.js +24 -30
  37. package/dist/core/agents/live-authority-v3.d.ts +1 -0
  38. package/dist/core/agents/live-authority-v3.d.ts.map +1 -1
  39. package/dist/core/agents/live-authority-v3.js +11 -0
  40. package/dist/core/agents/live-lifecycle-v3.d.ts +4 -2
  41. package/dist/core/agents/live-lifecycle-v3.d.ts.map +1 -1
  42. package/dist/core/agents/live-lifecycle-v3.js +28 -7
  43. package/dist/core/agents/mailbox.d.ts +9 -8
  44. package/dist/core/agents/mailbox.d.ts.map +1 -1
  45. package/dist/core/agents/mailbox.js +24 -17
  46. package/dist/core/agents/render/prompt-context.d.ts +2 -0
  47. package/dist/core/agents/render/prompt-context.d.ts.map +1 -1
  48. package/dist/core/agents/render/prompt-context.js +19 -17
  49. package/dist/core/agents/render/session-context.d.ts +2 -8
  50. package/dist/core/agents/render/session-context.d.ts.map +1 -1
  51. package/dist/core/agents/render/session-context.js +64 -43
  52. package/dist/core/agents/rules/stop-hook.js +3 -3
  53. package/dist/core/agents/state/heartbeat-writer.d.ts.map +1 -1
  54. package/dist/core/agents/state/heartbeat-writer.js +25 -14
  55. package/dist/core/agents/state/live-coordination-writer.d.ts.map +1 -1
  56. package/dist/core/agents/state/live-coordination-writer.js +5 -0
  57. package/dist/core/agents/state/names.d.ts +43 -3
  58. package/dist/core/agents/state/names.d.ts.map +1 -1
  59. package/dist/core/agents/state/names.js +87 -3
  60. package/dist/core/agents/state/pidmap.d.ts.map +1 -1
  61. package/dist/core/agents/state/pidmap.js +5 -0
  62. package/dist/core/agents/state/proc-start.d.ts +19 -0
  63. package/dist/core/agents/state/proc-start.d.ts.map +1 -1
  64. package/dist/core/agents/state/proc-start.js +41 -0
  65. package/dist/core/agents/state/stale-sweep.d.ts.map +1 -1
  66. package/dist/core/agents/state/stale-sweep.js +180 -70
  67. package/dist/core/agents/state/unchanged-file.d.ts +44 -0
  68. package/dist/core/agents/state/unchanged-file.d.ts.map +1 -0
  69. package/dist/core/agents/state/unchanged-file.js +390 -0
  70. package/dist/core/context/index.d.ts +22 -10
  71. package/dist/core/context/index.d.ts.map +1 -1
  72. package/dist/core/context/index.js +381 -119
  73. package/dist/core/context/observation.d.ts +26 -0
  74. package/dist/core/context/observation.d.ts.map +1 -0
  75. package/dist/core/context/observation.js +11 -0
  76. package/dist/core/diagnostics/bundle.d.ts.map +1 -1
  77. package/dist/core/diagnostics/bundle.js +25 -14
  78. package/dist/core/diagnostics/path-identity.d.ts +3 -0
  79. package/dist/core/diagnostics/path-identity.d.ts.map +1 -0
  80. package/dist/core/diagnostics/path-identity.js +12 -0
  81. package/dist/core/diagnostics/sanitize.d.ts.map +1 -1
  82. package/dist/core/diagnostics/sanitize.js +4 -3
  83. package/dist/core/events/v3/authority-outbox.d.ts.map +1 -1
  84. package/dist/core/events/v3/authority-outbox.js +29 -0
  85. package/dist/core/events/v3/generation-custody.d.ts +5 -0
  86. package/dist/core/events/v3/generation-custody.d.ts.map +1 -0
  87. package/dist/core/events/v3/generation-custody.js +50 -0
  88. package/dist/core/events/v3/producers/coordination-recorder.d.ts +1 -0
  89. package/dist/core/events/v3/producers/coordination-recorder.d.ts.map +1 -1
  90. package/dist/core/events/v3/producers/coordination-recorder.js +7 -0
  91. package/dist/core/events/v3/producers/recorder.d.ts.map +1 -1
  92. package/dist/core/events/v3/producers/recorder.js +77 -64
  93. package/dist/core/events/v3/support-storage/pack-reader.d.ts.map +1 -1
  94. package/dist/core/events/v3/support-storage/pack-reader.js +42 -16
  95. package/dist/core/governor/planning.d.ts.map +1 -1
  96. package/dist/core/governor/planning.js +14 -1
  97. package/dist/core/governor/service-read.d.ts +10 -2
  98. package/dist/core/governor/service-read.d.ts.map +1 -1
  99. package/dist/core/governor/service-read.js +105 -22
  100. package/dist/core/governor/service.d.ts +20 -2
  101. package/dist/core/governor/service.d.ts.map +1 -1
  102. package/dist/core/governor/service.js +72 -47
  103. package/dist/core/hooks/cli.js +120 -23
  104. package/dist/core/hooks/fork-lineage.d.ts +40 -0
  105. package/dist/core/hooks/fork-lineage.d.ts.map +1 -0
  106. package/dist/core/hooks/fork-lineage.js +62 -0
  107. package/dist/core/hooks/resolve/transcript.d.ts +16 -0
  108. package/dist/core/hooks/resolve/transcript.d.ts.map +1 -1
  109. package/dist/core/hooks/resolve/transcript.js +84 -0
  110. package/dist/core/hooks/shell-rm.d.ts +2 -0
  111. package/dist/core/hooks/shell-rm.d.ts.map +1 -0
  112. package/dist/core/hooks/shell-rm.js +105 -0
  113. package/dist/core/hooks/shell-tokens.d.ts +12 -0
  114. package/dist/core/hooks/shell-tokens.d.ts.map +1 -0
  115. package/dist/core/hooks/shell-tokens.js +97 -0
  116. package/dist/core/hooks/shell-waiter.d.ts.map +1 -1
  117. package/dist/core/hooks/shell-waiter.js +3 -93
  118. package/dist/core/inbox/contract.d.ts +2 -1
  119. package/dist/core/inbox/contract.d.ts.map +1 -1
  120. package/dist/core/inbox/index.d.ts +2 -0
  121. package/dist/core/inbox/index.d.ts.map +1 -1
  122. package/dist/core/inbox/index.js +2 -0
  123. package/dist/core/inbox/peer-messages.d.ts +37 -0
  124. package/dist/core/inbox/peer-messages.d.ts.map +1 -0
  125. package/dist/core/inbox/peer-messages.js +72 -0
  126. package/dist/core/inbox/service.d.ts +8 -1
  127. package/dist/core/inbox/service.d.ts.map +1 -1
  128. package/dist/core/inbox/service.js +67 -21
  129. package/dist/core/inbox/targets.d.ts +22 -0
  130. package/dist/core/inbox/targets.d.ts.map +1 -0
  131. package/dist/core/inbox/targets.js +108 -0
  132. package/dist/core/inbox/watcher.js +7 -3
  133. package/dist/core/journal/index.d.ts.map +1 -1
  134. package/dist/core/journal/index.js +17 -2
  135. package/dist/core/resources/contract.d.ts +3 -0
  136. package/dist/core/resources/contract.d.ts.map +1 -1
  137. package/dist/core/resources/service-status.d.ts +14 -1
  138. package/dist/core/resources/service-status.d.ts.map +1 -1
  139. package/dist/core/resources/service-status.js +23 -13
  140. package/dist/core/resources/service.d.ts +9 -1
  141. package/dist/core/resources/service.d.ts.map +1 -1
  142. package/dist/core/resources/service.js +47 -27
  143. package/dist/core/resources/status.d.ts +2 -5
  144. package/dist/core/resources/status.d.ts.map +1 -1
  145. package/dist/core/resources/status.js +36 -7
  146. package/dist/core/semantic/contract.d.ts +5 -5
  147. package/dist/core/servers/index.d.ts +24 -13
  148. package/dist/core/servers/index.d.ts.map +1 -1
  149. package/dist/core/servers/index.js +132 -92
  150. package/dist/core/servers/tunnels.d.ts +3 -5
  151. package/dist/core/servers/tunnels.d.ts.map +1 -1
  152. package/dist/core/servers/tunnels.js +3 -9
  153. package/dist/core/storage/process-log.d.ts +12 -0
  154. package/dist/core/storage/process-log.d.ts.map +1 -1
  155. package/dist/core/storage/process-log.js +10 -2
  156. package/dist/core/supervisor/contract.d.ts +12 -0
  157. package/dist/core/supervisor/contract.d.ts.map +1 -1
  158. package/dist/core/supervisor/explanations.d.ts.map +1 -1
  159. package/dist/core/supervisor/explanations.js +2 -1
  160. package/dist/core/supervisor/findings.d.ts.map +1 -1
  161. package/dist/core/supervisor/findings.js +54 -9
  162. package/dist/core/supervisor/service.d.ts +9 -1
  163. package/dist/core/supervisor/service.d.ts.map +1 -1
  164. package/dist/core/supervisor/service.js +59 -29
  165. package/dist/core/supervisor/services.d.ts.map +1 -1
  166. package/dist/core/supervisor/services.js +22 -1
  167. package/dist/core/supervisor/status.d.ts +17 -2
  168. package/dist/core/supervisor/status.d.ts.map +1 -1
  169. package/dist/core/supervisor/status.js +70 -12
  170. package/dist/core/supervisor/timeline.d.ts.map +1 -1
  171. package/dist/core/supervisor/timeline.js +2 -1
  172. package/dist/core/work/state.js +7 -7
  173. package/dist/core/workflow/engine.d.ts.map +1 -1
  174. package/dist/core/workflow/engine.js +105 -32
  175. package/dist/core/workflow/failure-evidence.d.ts +16 -0
  176. package/dist/core/workflow/failure-evidence.d.ts.map +1 -0
  177. package/dist/core/workflow/failure-evidence.js +114 -0
  178. package/dist/core/workflow/index.d.ts +1 -1
  179. package/dist/core/workflow/index.d.ts.map +1 -1
  180. package/dist/core/workflow/index.js +1 -1
  181. package/dist/core/workflow/live-session-v3.d.ts +6 -0
  182. package/dist/core/workflow/live-session-v3.d.ts.map +1 -1
  183. package/dist/core/workflow/live-session-v3.js +126 -5
  184. package/dist/core/workflow/proof.d.ts +5 -5
  185. package/dist/core/workflow/proof.d.ts.map +1 -1
  186. package/dist/core/workflow/proof.js +115 -20
  187. package/dist/core/workflow/run-state.d.ts +3 -1
  188. package/dist/core/workflow/run-state.d.ts.map +1 -1
  189. package/dist/core/workflow/run-state.js +31 -27
  190. package/dist/core/workflow/spawn-claude.d.ts.map +1 -1
  191. package/dist/core/workflow/spawn-claude.js +19 -0
  192. package/dist/core/workflow/spawn-codex.d.ts.map +1 -1
  193. package/dist/core/workflow/spawn-codex.js +13 -0
  194. package/dist/core/workflow/spawn-cursor.d.ts.map +1 -1
  195. package/dist/core/workflow/spawn-cursor.js +19 -0
  196. package/dist/core/workflow/spawn-opencode.d.ts.map +1 -1
  197. package/dist/core/workflow/spawn-opencode.js +14 -0
  198. package/dist/core/workflow/types.d.ts +64 -17
  199. package/dist/core/workflow/types.d.ts.map +1 -1
  200. package/dist/core/workflow/workspaces/index.d.ts +0 -1
  201. package/dist/core/workflow/workspaces/index.d.ts.map +1 -1
  202. package/dist/core/workflow/workspaces/index.js +0 -1
  203. package/dist/core/workflow/workspaces/leases.d.ts +3 -1
  204. package/dist/core/workflow/workspaces/leases.d.ts.map +1 -1
  205. package/dist/core/workflow/workspaces/leases.js +30 -16
  206. package/dist/core/workflow/workspaces/local-git.d.ts +6 -2
  207. package/dist/core/workflow/workspaces/local-git.d.ts.map +1 -1
  208. package/dist/core/workflow/workspaces/local-git.js +270 -6
  209. package/dist/core/workflow/workspaces/ownership.d.ts +11 -0
  210. package/dist/core/workflow/workspaces/ownership.d.ts.map +1 -0
  211. package/dist/core/workflow/workspaces/ownership.js +194 -0
  212. package/dist/core/workflow/workspaces/reclaim.d.ts +35 -0
  213. package/dist/core/workflow/workspaces/reclaim.d.ts.map +1 -1
  214. package/dist/core/workflow/workspaces/reclaim.js +14 -0
  215. package/dist/core/workflow/workspaces/recovery.d.ts.map +1 -1
  216. package/dist/core/workflow/workspaces/recovery.js +21 -13
  217. package/dist/core/workflow/workspaces/state.d.ts +1 -0
  218. package/dist/core/workflow/workspaces/state.d.ts.map +1 -1
  219. package/dist/core/workflow/workspaces/state.js +21 -1
  220. package/dist/lib/browser/windows-chrome.d.ts +100 -12
  221. package/dist/lib/browser/windows-chrome.d.ts.map +1 -1
  222. package/dist/lib/browser/windows-chrome.js +262 -73
  223. package/dist/lib/docs-links.d.ts.map +1 -1
  224. package/dist/lib/docs-links.js +45 -2
  225. package/dist/lib/guarded-remove.d.ts +7 -0
  226. package/dist/lib/guarded-remove.d.ts.map +1 -1
  227. package/dist/lib/guarded-remove.js +106 -12
  228. package/dist/lib/identities/assume.d.ts.map +1 -1
  229. package/dist/lib/identities/assume.js +4 -0
  230. package/dist/lib/tunnel/allowlist.d.ts +44 -0
  231. package/dist/lib/tunnel/allowlist.d.ts.map +1 -0
  232. package/dist/lib/tunnel/allowlist.js +204 -0
  233. package/dist/lib/tunnel/current-address.d.ts +41 -0
  234. package/dist/lib/tunnel/current-address.d.ts.map +1 -0
  235. package/dist/lib/tunnel/current-address.js +123 -0
  236. package/dist/lib/tunnel/gate.js +13 -6
  237. package/dist/lib/tunnel/processes.d.ts +39 -0
  238. package/dist/lib/tunnel/processes.d.ts.map +1 -0
  239. package/dist/lib/tunnel/processes.js +121 -0
  240. package/dist/lib/tunnel/state.d.ts +28 -3
  241. package/dist/lib/tunnel/state.d.ts.map +1 -1
  242. package/dist/lib/tunnel/state.js +98 -27
  243. package/dist/lib/zip/index.d.ts +41 -0
  244. package/dist/lib/zip/index.d.ts.map +1 -0
  245. package/dist/lib/zip/index.js +398 -0
  246. package/package.json +8 -1
  247. package/src/commander.ts +32 -0
  248. package/src/commands/agents.ts +151 -74
  249. package/src/commands/browse.ts +50 -14
  250. package/src/commands/diagnostics.ts +10 -0
  251. package/src/commands/doctor.ts +26 -7
  252. package/src/commands/governor.ts +23 -10
  253. package/src/commands/inbox.ts +52 -2
  254. package/src/commands/rm.ts +43 -4
  255. package/src/commands/servers.ts +16 -4
  256. package/src/commands/supervisor.ts +7 -2
  257. package/src/commands/toc.ts +14 -6
  258. package/src/commands/tunnel.ts +394 -116
  259. package/src/commands/web-fetch.ts +30 -19
  260. package/src/commands/web.ts +9 -3
  261. package/src/commands/workflow.ts +30 -30
  262. package/src/core/agents/live-authority-v3.ts +17 -0
  263. package/src/core/agents/live-lifecycle-v3.ts +52 -14
  264. package/src/core/agents/mailbox.ts +26 -17
  265. package/src/core/agents/render/prompt-context.ts +35 -20
  266. package/src/core/agents/render/session-context.ts +92 -48
  267. package/src/core/agents/rules/stop-hook.ts +3 -3
  268. package/src/core/agents/state/heartbeat-writer.ts +29 -12
  269. package/src/core/agents/state/live-coordination-writer.ts +29 -0
  270. package/src/core/agents/state/names.ts +117 -6
  271. package/src/core/agents/state/pidmap.ts +13 -0
  272. package/src/core/agents/state/proc-start.ts +57 -0
  273. package/src/core/agents/state/stale-sweep.ts +247 -82
  274. package/src/core/agents/state/unchanged-file.ts +456 -0
  275. package/src/core/context/index.ts +446 -136
  276. package/src/core/context/observation.ts +29 -0
  277. package/src/core/diagnostics/bundle.ts +23 -18
  278. package/src/core/diagnostics/path-identity.ts +15 -0
  279. package/src/core/diagnostics/sanitize.ts +4 -3
  280. package/src/core/events/v3/authority-outbox.ts +56 -0
  281. package/src/core/events/v3/generation-custody.ts +59 -0
  282. package/src/core/events/v3/producers/coordination-recorder.ts +15 -0
  283. package/src/core/events/v3/producers/recorder.ts +94 -68
  284. package/src/core/events/v3/support-storage/pack-reader.ts +45 -19
  285. package/src/core/governor/planning.ts +20 -8
  286. package/src/core/governor/service-read.ts +128 -20
  287. package/src/core/governor/service.ts +119 -42
  288. package/src/core/hooks/cli.ts +139 -22
  289. package/src/core/hooks/fork-lineage.ts +82 -0
  290. package/src/core/hooks/resolve/transcript.ts +88 -0
  291. package/src/core/hooks/shell-rm.ts +103 -0
  292. package/src/core/hooks/shell-tokens.ts +96 -0
  293. package/src/core/hooks/shell-waiter.ts +4 -91
  294. package/src/core/inbox/contract.ts +2 -1
  295. package/src/core/inbox/index.ts +2 -0
  296. package/src/core/inbox/peer-messages.ts +94 -0
  297. package/src/core/inbox/service.ts +88 -22
  298. package/src/core/inbox/targets.ts +148 -0
  299. package/src/core/inbox/watcher.ts +8 -9
  300. package/src/core/journal/index.ts +19 -2
  301. package/src/core/resources/contract.ts +4 -0
  302. package/src/core/resources/service-status.ts +35 -12
  303. package/src/core/resources/service.ts +71 -24
  304. package/src/core/resources/status.ts +57 -8
  305. package/src/core/servers/index.ts +177 -91
  306. package/src/core/servers/tunnels.ts +3 -11
  307. package/src/core/storage/process-log.ts +17 -2
  308. package/src/core/supervisor/contract.ts +13 -0
  309. package/src/core/supervisor/explanations.ts +4 -1
  310. package/src/core/supervisor/findings.ts +68 -10
  311. package/src/core/supervisor/service.ts +88 -26
  312. package/src/core/supervisor/services.ts +26 -8
  313. package/src/core/supervisor/status.ts +89 -12
  314. package/src/core/supervisor/timeline.ts +2 -1
  315. package/src/core/work/state.ts +7 -7
  316. package/src/core/workflow/engine.ts +131 -49
  317. package/src/core/workflow/failure-evidence.ts +141 -0
  318. package/src/core/workflow/index.ts +0 -1
  319. package/src/core/workflow/live-session-v3.ts +146 -5
  320. package/src/core/workflow/proof.ts +134 -26
  321. package/src/core/workflow/run-state.ts +31 -29
  322. package/src/core/workflow/spawn-claude.ts +18 -0
  323. package/src/core/workflow/spawn-codex.ts +13 -0
  324. package/src/core/workflow/spawn-cursor.ts +18 -0
  325. package/src/core/workflow/spawn-opencode.ts +14 -0
  326. package/src/core/workflow/types.ts +51 -17
  327. package/src/core/workflow/workspaces/index.ts +0 -1
  328. package/src/core/workflow/workspaces/leases.ts +48 -17
  329. package/src/core/workflow/workspaces/local-git.ts +315 -5
  330. package/src/core/workflow/workspaces/ownership.ts +232 -0
  331. package/src/core/workflow/workspaces/reclaim.ts +58 -0
  332. package/src/core/workflow/workspaces/recovery.ts +25 -13
  333. package/src/core/workflow/workspaces/state.ts +20 -0
  334. package/src/lib/browser/windows-chrome.ts +346 -86
  335. package/src/lib/docs-links.ts +49 -2
  336. package/src/lib/guarded-remove.ts +132 -14
  337. package/src/lib/identities/assume.ts +4 -0
  338. package/src/lib/tunnel/allowlist.ts +208 -0
  339. package/src/lib/tunnel/current-address.ts +158 -0
  340. package/src/lib/tunnel/gate.ts +16 -8
  341. package/src/lib/tunnel/processes.ts +149 -0
  342. package/src/lib/tunnel/state.ts +123 -27
  343. package/src/lib/zip/index.ts +483 -0
@@ -1,7 +1,7 @@
1
1
  import { spawnSync } from "node:child_process";
2
2
  import { lstatSync, readdirSync, readlinkSync, realpathSync, rmSync, type Stats } from "node:fs";
3
3
  import { homedir } from "node:os";
4
- import { basename, dirname, isAbsolute, parse, relative, resolve, sep } from "node:path";
4
+ import { basename, dirname, isAbsolute, join, parse, relative, resolve, sep } from "node:path";
5
5
 
6
6
  export interface RemoveOptions {
7
7
  root: string;
@@ -16,6 +16,12 @@ export interface RemoveOptions {
16
16
  allowProtected?: string[];
17
17
  /** Directories whose own Git metadata and Harnery state may never be allowed (the live workspace). */
18
18
  liveRoots?: string[];
19
+ /** Command-layer validation of the current caller's ownership of this exact managed artifact root. */
20
+ assertOwnedArtifact?: (root: string) => void;
21
+ /** Inspection bound; values above 10,000 require verified ownership of the exact artifact root. */
22
+ entryLimit?: number;
23
+ /** Remove only verified-clean standalone clones inside the caller's owned artifact. */
24
+ cleanClone?: boolean;
19
25
  }
20
26
 
21
27
  export interface RemovalLink {
@@ -30,6 +36,7 @@ export interface RemovalReport {
30
36
  root: string;
31
37
  targets: string[];
32
38
  entries: number;
39
+ entry_limit: number;
33
40
  bytes: number;
34
41
  /** Protected paths removed because the caller named them with allowProtected. */
35
42
  protected: string[];
@@ -39,6 +46,7 @@ export interface RemovalReport {
39
46
 
40
47
  const protectedNames = new Set([".git", ".harnery", ".credentials", ".ssh", ".gnupg"]);
41
48
  const MAX_ENTRIES = 10_000;
49
+ const MAX_OWNED_ARTIFACT_ENTRIES = 100_000;
42
50
 
43
51
  /** Permanent removal is deliberately limited to inspected, untracked local outputs. */
44
52
  export function guardedRemove(
@@ -48,18 +56,48 @@ export function guardedRemove(
48
56
  ): RemovalReport {
49
57
  const cwd = realpathSync(process.cwd());
50
58
  const root = checkedPath(options.root, new Set(), true);
51
- const allowed = allowedProtected(options.allowProtected ?? [], root, options.liveRoots ?? []);
59
+ if (options.cleanClone) {
60
+ if (!options.recursive) throw new Error("Clean clone removal requires --recursive");
61
+ if (options.allowProtected?.length)
62
+ throw new Error("Clean clone removal cannot be combined with --allow-protected");
63
+ if (!options.assertOwnedArtifact)
64
+ throw new Error("Clean clone removal requires one current caller-owned managed artifact");
65
+ options.assertOwnedArtifact(root);
66
+ }
67
+ const entryLimit = options.entryLimit ?? MAX_ENTRIES;
68
+ if (
69
+ !Number.isSafeInteger(entryLimit) ||
70
+ entryLimit < 1 ||
71
+ entryLimit > MAX_OWNED_ARTIFACT_ENTRIES
72
+ )
73
+ throw new Error(`The entry limit must be an integer from 1 to ${MAX_OWNED_ARTIFACT_ENTRIES}`);
74
+ const assertEntryLimitAuthority = () => {
75
+ if (entryLimit <= MAX_ENTRIES) return;
76
+ if (!options.assertOwnedArtifact)
77
+ throw new Error(
78
+ "An entry limit above 10000 requires one current caller-owned managed artifact",
79
+ );
80
+ options.assertOwnedArtifact(root);
81
+ };
82
+ const allowed = allowedProtected(
83
+ options.allowProtected ?? [],
84
+ root,
85
+ options.liveRoots ?? [],
86
+ options.assertOwnedArtifact,
87
+ );
52
88
  const rootStat = lstatSync(root);
53
89
  const rootFingerprint = fingerprint(rootStat);
54
90
  if (!rootStat.isDirectory()) throw new Error("--root must be a directory");
55
91
  if (root === parse(root).root || root === realpathSync(homedir()))
56
92
  throw new Error("--root cannot be a filesystem root or home directory");
93
+ assertEntryLimitAuthority();
57
94
  if (paths.length === 0 || paths.length > 100) throw new Error("Supply 1-100 explicit targets");
58
95
  const targets = paths.map((path) => checkedPath(path, allowed));
59
96
  const snapshots = new Map<string, string>();
60
97
  const removedProtected = new Set<string>();
61
98
  const links: RemovalLink[] = [];
62
99
  const gitDirs = new Set<string>();
100
+ const cleanClones = new Set<string>();
63
101
  let bytes = 0;
64
102
  const devices = new Set<number>();
65
103
 
@@ -110,6 +148,10 @@ export function guardedRemove(
110
148
  if (stat.isDirectory() && !options.recursive)
111
149
  throw new Error(`Directory removal requires --recursive: ${target}`);
112
150
  const device = stat.dev;
151
+ if (options.cleanClone) {
152
+ assertCleanClone(target);
153
+ cleanClones.add(target);
154
+ }
113
155
  devices.add(device);
114
156
  const pending = [target];
115
157
  while (pending.length) {
@@ -118,6 +160,12 @@ export function guardedRemove(
118
160
  if (basename(path) === ARTIFACT_RECORD && insideArtifactWorkspace(path, null))
119
161
  throw new Error(`An artifact's record is managed by the artifact commands: ${path}`);
120
162
  if (protectedNames.has(basename(path).toLowerCase())) {
163
+ if (options.cleanClone && basename(path) === ".git") {
164
+ const clone = dirname(path);
165
+ assertCleanClone(clone);
166
+ cleanClones.add(clone);
167
+ allowed.add(path);
168
+ }
121
169
  if (!allowed.has(path)) throw new Error(protectedMessage(path));
122
170
  removedProtected.add(path);
123
171
  }
@@ -126,9 +174,9 @@ export function guardedRemove(
126
174
  // read, followed, or counted. (The target itself and its ancestors
127
175
  // were already refused if they were links, in checkedPath.)
128
176
  if (path === target) throw new Error(`Path contains a symlink: ${path}`);
129
- if (snapshots.size >= MAX_ENTRIES)
177
+ if (snapshots.size >= entryLimit)
130
178
  throw new Error(
131
- `Removal exceeds the ${MAX_ENTRIES}-entry limit; use the owning cleanup command`,
179
+ `Removal exceeds the ${entryLimit}-entry limit; use the owning cleanup command`,
132
180
  );
133
181
  snapshots.set(path, fingerprint(info));
134
182
  links.push({ path, target: readlinkSync(path) });
@@ -136,9 +184,9 @@ export function guardedRemove(
136
184
  }
137
185
  if (info.dev !== device || (!info.isDirectory() && !info.isFile()))
138
186
  throw new Error(`Mount boundary or special file cannot be removed: ${path}`);
139
- if (snapshots.size >= MAX_ENTRIES)
187
+ if (snapshots.size >= entryLimit)
140
188
  throw new Error(
141
- `Removal exceeds the ${MAX_ENTRIES}-entry limit; use the owning cleanup command`,
189
+ `Removal exceeds the ${entryLimit}-entry limit; use the owning cleanup command`,
142
190
  );
143
191
  snapshots.set(path, fingerprint(info));
144
192
  if (info.isFile()) bytes += info.size;
@@ -172,6 +220,7 @@ export function guardedRemove(
172
220
  root,
173
221
  targets,
174
222
  entries: snapshots.size,
223
+ entry_limit: entryLimit,
175
224
  bytes,
176
225
  protected: [...removedProtected].sort(),
177
226
  links,
@@ -185,11 +234,21 @@ export function guardedRemove(
185
234
  fingerprint(lstatSync(root)) !== rootFingerprint
186
235
  )
187
236
  throw new Error("Allowed root changed during inspection");
237
+ assertEntryLimitAuthority();
238
+ if (options.cleanClone) options.assertOwnedArtifact!(root);
239
+ // Ownership may have been released or changed while the contents were inspected.
240
+ allowedProtected(
241
+ options.allowProtected ?? [],
242
+ root,
243
+ options.liveRoots ?? [],
244
+ options.assertOwnedArtifact,
245
+ );
188
246
  for (const target of targets) {
189
247
  checkedPath(target, allowed);
190
248
  assertUntracked(target);
191
249
  }
192
250
  for (const dir of gitDirs) assertNoUnpushedHistory(dir);
251
+ for (const clone of cleanClones) assertCleanClone(clone);
193
252
  checkClaims(targets);
194
253
  for (const [path, previous] of snapshots) {
195
254
  if (fingerprint(lstatSync(path)) !== previous)
@@ -200,6 +259,47 @@ export function guardedRemove(
200
259
  return { ...report, applied: true };
201
260
  }
202
261
 
262
+ /** A disposable clone must not be the only copy of work or a registered worktree. */
263
+ function assertCleanClone(clone: string): void {
264
+ const metadata = join(clone, ".git");
265
+ const stat = lstatSync(metadata);
266
+ if (!stat.isDirectory() || stat.isSymbolicLink())
267
+ throw new Error(`Clean clone removal requires a standalone .git directory: ${clone}`);
268
+ const git = (args: string[]) => {
269
+ const result = spawnSync("git", ["-c", "core.fsmonitor=false", "-C", clone, ...args], {
270
+ encoding: "utf8",
271
+ timeout: 10_000,
272
+ maxBuffer: 4 * 1024 * 1024,
273
+ env: {
274
+ ...process.env,
275
+ LC_ALL: "C",
276
+ GIT_DIR: undefined,
277
+ GIT_COMMON_DIR: undefined,
278
+ GIT_WORK_TREE: undefined,
279
+ GIT_INDEX_FILE: undefined,
280
+ GIT_OPTIONAL_LOCKS: "0",
281
+ },
282
+ });
283
+ if (result.error || result.status !== 0)
284
+ throw new Error(`Cannot verify clean clone ${clone}: git ${args[0]} failed`);
285
+ return result.stdout;
286
+ };
287
+ if (
288
+ realpathSync(git(["rev-parse", "--show-toplevel"]).trim()) !== clone ||
289
+ realpathSync(resolve(clone, git(["rev-parse", "--git-common-dir"]).trim())) !== metadata
290
+ )
291
+ throw new Error(`Clean clone removal refuses shared repository metadata: ${clone}`);
292
+ const worktrees = git(["worktree", "list", "--porcelain", "-z"])
293
+ .split("\0")
294
+ .filter((entry) => entry.startsWith("worktree "));
295
+ if (worktrees.length !== 1 || worktrees[0] !== `worktree ${clone}`)
296
+ throw new Error(`Clean clone removal refuses registered or linked worktrees: ${clone}`);
297
+ if (git(["status", "--porcelain=v1", "--untracked-files=all"]).trim())
298
+ throw new Error(`Clean clone has uncommitted or untracked work: ${clone}`);
299
+ if (git(["rev-list", "--max-count=1", "HEAD", "--all", "--reflog", "--not", "--remotes"]).trim())
300
+ throw new Error(`Clean clone has HEAD, ref or reflog commits not on any remote: ${clone}`);
301
+ }
302
+
203
303
  /** The metadata file the artifact commands keep in each artifact workspace. */
204
304
  const ARTIFACT_RECORD = ".harnery-artifact.json";
205
305
 
@@ -238,9 +338,14 @@ function insideAllowed(path: string, allowed: ReadonlySet<string>): boolean {
238
338
  * protected path strictly inside the root, reached without symlinks, and
239
339
  * never the Git metadata or Harnery state of a live workspace root.
240
340
  */
241
- function allowedProtected(paths: string[], root: string, liveRoots: string[]): Set<string> {
341
+ function allowedProtected(
342
+ paths: string[],
343
+ root: string,
344
+ liveRoots: string[],
345
+ assertOwnedArtifact?: (root: string) => void,
346
+ ): Set<string> {
242
347
  const allowed = new Set<string>();
243
- const live = liveRoots.map((dir) => resolve(dir));
348
+ const live = liveRoots.map((dir) => realpathSync(dir));
244
349
  for (const input of paths) {
245
350
  if (!input?.trim() || /[\0\r\n*?[\]$]/.test(input))
246
351
  throw new Error("Use a nonempty explicit --allow-protected path without wildcards");
@@ -261,13 +366,26 @@ function allowedProtected(paths: string[], root: string, liveRoots: string[]): S
261
366
  if (!named && !(info.isDirectory() && isRepositoryMetadata(path)))
262
367
  throw new Error(`--allow-protected must name a protected path itself: ${path}`);
263
368
  for (const dir of live) {
264
- const own = [".git", ".harnery"].map((name) => resolve(dir, name));
265
- if (
266
- path === dir ||
267
- strictlyInside(path, dir) ||
268
- own.some((state) => path === state || strictlyInside(state, path))
269
- )
369
+ if (path === dir || strictlyInside(path, dir))
370
+ throw new Error(`The live workspace's own state cannot be allowed: ${path}`);
371
+ for (const name of [".git", ".harnery"]) {
372
+ const state = resolve(dir, name);
373
+ if (path !== state && !strictlyInside(state, path)) continue;
374
+ // Only an explicitly named copied state directory inside one owned
375
+ // artifact may cross the outer live-state ancestor. Other live roots
376
+ // (including a checkout inside that artifact) still veto the path.
377
+ if (
378
+ name === ".harnery" &&
379
+ basename(path) === ".harnery" &&
380
+ info.isDirectory() &&
381
+ dirname(root) === resolve(state, "artifacts") &&
382
+ assertOwnedArtifact
383
+ ) {
384
+ assertOwnedArtifact(root);
385
+ continue;
386
+ }
270
387
  throw new Error(`The live workspace's own state cannot be allowed: ${path}`);
388
+ }
271
389
  }
272
390
  allowed.add(realpathSync(path));
273
391
  }
@@ -140,6 +140,7 @@ export function reclaimAbandonedLocalConflict(
140
140
  let sessionId = conflict.instance_id;
141
141
  let ageSecs: number | undefined;
142
142
  const liveRow = readLiveCoordinationRow(coordRoot, conflict.instance_id);
143
+ let expectedGenerationId = liveRow?.v3_generation_id ?? null;
143
144
  if (liveRow) {
144
145
  adapter = adapterOf(liveRow.platform);
145
146
  sessionId = liveRow.session_id || conflict.instance_id;
@@ -153,7 +154,9 @@ export function reclaimAbandonedLocalConflict(
153
154
  // It is required to join the exact producer state when recording the sweep.
154
155
  adapter = adapterOf(hb.platform);
155
156
  sessionId = hb.session_id || conflict.instance_id;
157
+ expectedGenerationId = hb.v3_generation_id ?? null;
156
158
  } catch {
159
+ expectedGenerationId = null;
157
160
  /* content unreadable — still reclaim the file */
158
161
  }
159
162
  try {
@@ -168,6 +171,7 @@ export function reclaimAbandonedLocalConflict(
168
171
  owner: conflict.instance_id,
169
172
  nativeSessionId: sessionId,
170
173
  adapter,
174
+ expectedGenerationId,
171
175
  observation: "stale_heartbeat",
172
176
  ageMs: Math.max(0, (ageSecs ?? 0) * 1_000),
173
177
  });
@@ -0,0 +1,208 @@
1
+ // Address allowlist for the tunnel gate: exact addresses and CIDR ranges, IPv4
2
+ // and IPv6. Pure functions with no I/O, shared by the gate worker (matching)
3
+ // and the `tunnel allow` commands (validation + canonical spelling).
4
+ //
5
+ // An IPv6 phone and laptop on one Wi-Fi network have different addresses but
6
+ // share a /64 prefix, so a range entry such as `2601:db8:1:2::/64` admits both.
7
+ // An entry without a prefix length is a single address (/32 or /128).
8
+ //
9
+ // IPv4-mapped IPv6 addresses (`::ffff:203.0.113.8`) are IPv4 addresses reached
10
+ // through a dual-stack socket, so they parse and match as IPv4.
11
+
12
+ import { isIPv4, isIPv6 } from "node:net";
13
+
14
+ export type IpFamily = 4 | 6;
15
+
16
+ export interface ParsedIp {
17
+ family: IpFamily;
18
+ value: bigint;
19
+ }
20
+
21
+ export interface AllowEntry extends ParsedIp {
22
+ /** Prefix length in bits (32 or 128 for a single address). */
23
+ prefix: number;
24
+ }
25
+
26
+ const FULL_BITS: Record<IpFamily, number> = { 4: 32, 6: 128 };
27
+
28
+ function parseIpv4(text: string): bigint | null {
29
+ if (!isIPv4(text)) return null;
30
+ let value = 0n;
31
+ for (const part of text.split(".")) value = (value << 8n) | BigInt(Number(part));
32
+ return value;
33
+ }
34
+
35
+ function parseIpv6(text: string): bigint | null {
36
+ if (!isIPv6(text)) return null;
37
+ let rest = text;
38
+ // A trailing dotted quad (`::ffff:1.2.3.4`, `64:ff9b::1.2.3.4`) is two groups.
39
+ const dotted = rest.match(/^(.*:)(\d+\.\d+\.\d+\.\d+)$/);
40
+ if (dotted) {
41
+ const v4 = parseIpv4(dotted[2] as string);
42
+ if (v4 === null) return null;
43
+ rest = `${dotted[1]}${(v4 >> 16n).toString(16)}:${(v4 & 0xffffn).toString(16)}`;
44
+ }
45
+ const halves = rest.split("::");
46
+ if (halves.length > 2) return null;
47
+ const head = halves[0] ? (halves[0] as string).split(":") : [];
48
+ const tail = halves.length === 2 && halves[1] ? (halves[1] as string).split(":") : [];
49
+ const missing = 8 - head.length - tail.length;
50
+ if (halves.length === 1 ? missing !== 0 : missing < 1) return null;
51
+ const groups = [
52
+ ...head,
53
+ ...Array.from({ length: halves.length === 2 ? missing : 0 }, () => "0"),
54
+ ...tail,
55
+ ];
56
+ if (groups.length !== 8) return null;
57
+ let value = 0n;
58
+ for (const group of groups) {
59
+ if (!/^[0-9a-f]{1,4}$/i.test(group)) return null;
60
+ value = (value << 16n) | BigInt(Number.parseInt(group, 16));
61
+ }
62
+ return value;
63
+ }
64
+
65
+ /**
66
+ * Parse one address. Returns null for anything that is not an IP literal. A
67
+ * zone id (`fe80::1%en0`) is dropped, and an IPv4-mapped IPv6 address is
68
+ * reported as the IPv4 address it carries.
69
+ */
70
+ export function parseIp(raw: string): ParsedIp | null {
71
+ let text = raw.trim();
72
+ if (text.startsWith("[") && text.endsWith("]")) text = text.slice(1, -1);
73
+ const zone = text.indexOf("%");
74
+ if (zone !== -1) text = text.slice(0, zone);
75
+ if (!text) return null;
76
+ const v4 = parseIpv4(text);
77
+ if (v4 !== null) return { family: 4, value: v4 };
78
+ const v6 = parseIpv6(text);
79
+ if (v6 === null) return null;
80
+ if (v6 >> 32n === 0xffffn) return { family: 4, value: v6 & 0xffffffffn };
81
+ return { family: 6, value: v6 };
82
+ }
83
+
84
+ function maskFor(family: IpFamily, prefix: number): bigint {
85
+ const bits = BigInt(FULL_BITS[family]);
86
+ const host = bits - BigInt(prefix);
87
+ return ((1n << bits) - 1n) ^ ((1n << host) - 1n);
88
+ }
89
+
90
+ /**
91
+ * Parse an allowlist entry: `203.0.113.8`, `203.0.113.0/24`, `2601:db8::1`, or
92
+ * `2601:db8:1:2::/64`. Host bits below the prefix are cleared, so
93
+ * `203.0.113.77/24` means the network `203.0.113.0/24`. Returns null when the
94
+ * entry is not a valid address or its prefix length is out of range.
95
+ */
96
+ export function parseAllowEntry(raw: string): AllowEntry | null {
97
+ const text = raw.trim();
98
+ const slash = text.indexOf("/");
99
+ const address = parseIp(slash === -1 ? text : text.slice(0, slash));
100
+ if (!address) return null;
101
+ let prefix = FULL_BITS[address.family];
102
+ if (slash !== -1) {
103
+ const lengthText = text.slice(slash + 1);
104
+ if (!/^\d{1,3}$/.test(lengthText)) return null;
105
+ prefix = Number(lengthText);
106
+ // A prefix on an IPv4-mapped IPv6 entry counts from the IPv6 start, so
107
+ // `::ffff:1.2.3.0/120` is the IPv4 /24. Anything shorter is not an IPv4 range.
108
+ if (address.family === 4 && /:/.test(text.slice(0, slash))) {
109
+ if (prefix < 96 || prefix > 128) return null;
110
+ prefix -= 96;
111
+ }
112
+ if (prefix > FULL_BITS[address.family]) return null;
113
+ }
114
+ return { ...address, prefix, value: address.value & maskFor(address.family, prefix) };
115
+ }
116
+
117
+ function compress(groups: number[]): string {
118
+ // RFC 5952: collapse the longest run of two or more zero groups (first wins).
119
+ let bestStart = -1;
120
+ let bestLen = 0;
121
+ for (let i = 0; i < 8; ) {
122
+ if (groups[i] !== 0) {
123
+ i++;
124
+ continue;
125
+ }
126
+ let j = i;
127
+ while (j < 8 && groups[j] === 0) j++;
128
+ if (j - i > bestLen) {
129
+ bestStart = i;
130
+ bestLen = j - i;
131
+ }
132
+ i = j;
133
+ }
134
+ if (bestLen < 2) return groups.map((g) => g.toString(16)).join(":");
135
+ const left = groups.slice(0, bestStart).map((g) => g.toString(16));
136
+ const right = groups.slice(bestStart + bestLen).map((g) => g.toString(16));
137
+ return `${left.join(":")}::${right.join(":")}`;
138
+ }
139
+
140
+ /** Canonical text of an address (dotted quad, or compressed lowercase IPv6). */
141
+ export function formatIp(ip: ParsedIp): string {
142
+ if (ip.family === 4) {
143
+ return [24n, 16n, 8n, 0n].map((shift) => Number((ip.value >> shift) & 0xffn)).join(".");
144
+ }
145
+ const groups: number[] = [];
146
+ for (let i = 7; i >= 0; i--) groups.push(Number((ip.value >> BigInt(i * 16)) & 0xffffn));
147
+ return compress(groups);
148
+ }
149
+
150
+ /** Canonical text of an entry; a single address carries no `/len` suffix. */
151
+ export function formatAllowEntry(entry: AllowEntry): string {
152
+ const address = formatIp(entry);
153
+ return entry.prefix === FULL_BITS[entry.family] ? address : `${address}/${entry.prefix}`;
154
+ }
155
+
156
+ /**
157
+ * Canonical spelling of an allowlist entry, or null when invalid. Two spellings
158
+ * of one address or range (`2601:DB8:0:0::1`, `2601:db8::1`) normalize equal.
159
+ */
160
+ export function normalizeAllowEntry(raw: string): string | null {
161
+ const entry = parseAllowEntry(raw);
162
+ return entry ? formatAllowEntry(entry) : null;
163
+ }
164
+
165
+ export interface Allowlist {
166
+ entries: AllowEntry[];
167
+ /** Entries that could not be parsed; they never match anything. */
168
+ invalid: string[];
169
+ }
170
+
171
+ export function compileAllowlist(rawEntries: readonly string[]): Allowlist {
172
+ const entries: AllowEntry[] = [];
173
+ const invalid: string[] = [];
174
+ for (const raw of rawEntries) {
175
+ const text = raw.trim();
176
+ if (!text) continue;
177
+ const entry = parseAllowEntry(text);
178
+ if (entry) entries.push(entry);
179
+ else invalid.push(text);
180
+ }
181
+ return { entries, invalid };
182
+ }
183
+
184
+ /** True when `ip` lies inside any entry. A missing or malformed address never matches. */
185
+ export function allowlistMatches(list: Allowlist, ip: string): boolean {
186
+ const address = parseIp(ip);
187
+ if (!address) return false;
188
+ for (const entry of list.entries) {
189
+ if (entry.family !== address.family) continue;
190
+ const mask = maskFor(entry.family, entry.prefix);
191
+ if ((address.value & mask) === entry.value) return true;
192
+ }
193
+ return false;
194
+ }
195
+
196
+ /** The IPv6 /64 network prefix of an address, as a canonical `…/64` entry. */
197
+ export function ipv6Slash64(address: string): string | null {
198
+ const ip = parseIp(address);
199
+ if (!ip || ip.family !== 6) return null;
200
+ return formatAllowEntry({ ...ip, prefix: 64, value: ip.value & maskFor(6, 64) });
201
+ }
202
+
203
+ /** A single IPv4 address as a `/32` entry. */
204
+ export function ipv4Slash32(address: string): string | null {
205
+ const ip = parseIp(address);
206
+ if (!ip || ip.family !== 4) return null;
207
+ return `${formatIp(ip)}/32`;
208
+ }
@@ -0,0 +1,158 @@
1
+ // This machine's public addresses as Cloudflare sees them, and the allowlist
2
+ // bookkeeping around them (`tunnel allow add --current`).
3
+ //
4
+ // The tunnel gate admits a visitor by the `CF-Connecting-IP` header, which is
5
+ // the address Cloudflare saw. Asking Cloudflare's own trace endpoint therefore
6
+ // returns the same address the gate will later compare, with no third party and
7
+ // no guess about NAT. The IPv4 and IPv6 probes use address literals, so each
8
+ // travels over the family it is named for and needs no DNS.
9
+ //
10
+ // Entries the refresh adds are recorded in `auto_allowed`. The next refresh
11
+ // replaces exactly those, so a machine that changes network does not pile up
12
+ // stale addresses, and an entry added by hand is never removed.
13
+
14
+ import { ipv4Slash32, ipv6Slash64, normalizeAllowEntry } from "./allowlist.ts";
15
+ import type { TunnelConfig } from "./state.ts";
16
+
17
+ export const TRACE_URL_V4 = "https://1.1.1.1/cdn-cgi/trace";
18
+ export const TRACE_URL_V6 = "https://[2606:4700:4700::1111]/cdn-cgi/trace";
19
+
20
+ export interface DetectedAddresses {
21
+ v4?: string;
22
+ v6?: string;
23
+ /** One note per family that could not be read. */
24
+ failures: string[];
25
+ }
26
+
27
+ export interface DetectOptions {
28
+ fetch?: typeof fetch;
29
+ timeoutMs?: number;
30
+ /** Tries per family; a transient failure on a flaky network should not drop an address. */
31
+ attempts?: number;
32
+ }
33
+
34
+ /** The `ip=` value of a Cloudflare trace body, or null. */
35
+ export function parseTraceIp(body: string): string | null {
36
+ const m = body.match(/^ip=(\S+)\s*$/m);
37
+ return m ? (m[1] as string) : null;
38
+ }
39
+
40
+ async function probe(url: string, family: 4 | 6, opts: Required<DetectOptions>): Promise<string> {
41
+ let last = "no answer";
42
+ for (let attempt = 0; attempt < opts.attempts; attempt++) {
43
+ try {
44
+ const res = await opts.fetch(url, { signal: AbortSignal.timeout(opts.timeoutMs) });
45
+ if (!res.ok) throw new Error(`HTTP ${res.status}`);
46
+ const ip = parseTraceIp(await res.text());
47
+ if (!ip) throw new Error("the trace had no ip= line");
48
+ const entry = family === 4 ? ipv4Slash32(ip) : ipv6Slash64(ip);
49
+ if (!entry) throw new Error(`expected an IPv${family} address, got ${ip}`);
50
+ return ip;
51
+ } catch (error) {
52
+ last = error instanceof Error ? error.message : String(error);
53
+ }
54
+ }
55
+ throw new Error(last);
56
+ }
57
+
58
+ /** Both families in parallel. A family that fails is reported, not thrown. */
59
+ export async function detectPublicAddresses(
60
+ options: DetectOptions = {},
61
+ ): Promise<DetectedAddresses> {
62
+ const opts: Required<DetectOptions> = {
63
+ fetch: options.fetch ?? fetch,
64
+ timeoutMs: options.timeoutMs ?? 4_000,
65
+ attempts: options.attempts ?? 2,
66
+ };
67
+ const [v4, v6] = await Promise.allSettled([
68
+ probe(TRACE_URL_V4, 4, opts),
69
+ probe(TRACE_URL_V6, 6, opts),
70
+ ]);
71
+ const out: DetectedAddresses = { failures: [] };
72
+ if (v4.status === "fulfilled") out.v4 = v4.value;
73
+ else out.failures.push(`IPv4: ${(v4.reason as Error).message}`);
74
+ if (v6.status === "fulfilled") out.v6 = v6.value;
75
+ else out.failures.push(`IPv6: ${(v6.reason as Error).message}`);
76
+ return out;
77
+ }
78
+
79
+ export interface CurrentAddressPlan {
80
+ config: TunnelConfig;
81
+ /** Entries newly present in the allowlist. */
82
+ added: string[];
83
+ /** Automatic entries from an earlier refresh that are now gone. */
84
+ removed: string[];
85
+ /** The automatic entries after this refresh (the detected, not already listed by hand). */
86
+ automatic: string[];
87
+ changed: boolean;
88
+ warnings: string[];
89
+ }
90
+
91
+ const sameEntry = (a: string, b: string) =>
92
+ (normalizeAllowEntry(a) ?? a) === (normalizeAllowEntry(b) ?? b);
93
+ const includesEntry = (list: readonly string[], entry: string) =>
94
+ list.some((e) => sameEntry(e, entry));
95
+
96
+ /**
97
+ * Fold freshly detected addresses into the allowlist.
98
+ *
99
+ * When nothing was detected the config comes back untouched with a warning:
100
+ * a failed lookup must never empty the list. When at least one family was
101
+ * detected, a family that was not is treated as absent from this network, so
102
+ * its old automatic entry goes. The entries for the detected families replace
103
+ * every previous automatic entry; manual entries are kept in place.
104
+ */
105
+ export function planCurrentAddresses(
106
+ config: TunnelConfig,
107
+ detected: DetectedAddresses,
108
+ ): CurrentAddressPlan {
109
+ const previousAuto = config.auto_allowed ?? [];
110
+ const wanted: string[] = [];
111
+ if (detected.v4) {
112
+ const entry = ipv4Slash32(detected.v4);
113
+ if (entry) wanted.push(entry);
114
+ }
115
+ if (detected.v6) {
116
+ const entry = ipv6Slash64(detected.v6);
117
+ if (entry) wanted.push(entry);
118
+ }
119
+
120
+ if (wanted.length === 0) {
121
+ return {
122
+ config,
123
+ added: [],
124
+ removed: [],
125
+ automatic: previousAuto,
126
+ changed: false,
127
+ warnings: [
128
+ `Could not detect this machine's public address (${detected.failures.join("; ") || "no answer"}). ` +
129
+ `The allowlist is unchanged${previousAuto.length ? `; the previous automatic entries stay: ${previousAuto.join(", ")}` : ""}.`,
130
+ ],
131
+ };
132
+ }
133
+
134
+ const manual = config.allowed_ips.filter((e) => !includesEntry(previousAuto, e));
135
+ // An address already listed by hand stays manual, so a later refresh keeps it.
136
+ const automatic = wanted.filter((e) => !includesEntry(manual, e));
137
+ const allowed = [...manual, ...automatic];
138
+ const before = config.allowed_ips;
139
+ const added = allowed.filter((e) => !includesEntry(before, e));
140
+ const removed = before.filter((e) => !includesEntry(allowed, e));
141
+ const warnings: string[] = [];
142
+ const missing = [detected.v4 ? null : "IPv4", detected.v6 ? null : "IPv6"].filter(Boolean);
143
+ if (missing.length > 0) {
144
+ warnings.push(
145
+ `${missing.join(" and ")} was not detected, so this network is treated as having none` +
146
+ (detected.failures.length ? ` (${detected.failures.join("; ")})` : "") +
147
+ ".",
148
+ );
149
+ }
150
+ return {
151
+ config: { ...config, allowed_ips: allowed, auto_allowed: automatic },
152
+ added,
153
+ removed,
154
+ automatic,
155
+ changed: added.length > 0 || removed.length > 0,
156
+ warnings,
157
+ };
158
+ }