harnery 0.41.0 → 0.43.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 (269) hide show
  1. package/dist/commander.d.ts +16 -0
  2. package/dist/commander.d.ts.map +1 -1
  3. package/dist/commander.js +21 -0
  4. package/dist/commands/agents.d.ts.map +1 -1
  5. package/dist/commands/agents.js +63 -5
  6. package/dist/commands/artifacts.d.ts.map +1 -1
  7. package/dist/commands/artifacts.js +113 -12
  8. package/dist/commands/browse.d.ts +164 -0
  9. package/dist/commands/browse.d.ts.map +1 -1
  10. package/dist/commands/browse.js +263 -51
  11. package/dist/commands/claude-desktop.d.ts.map +1 -1
  12. package/dist/commands/claude-desktop.js +52 -0
  13. package/dist/commands/disk.d.ts +6 -0
  14. package/dist/commands/disk.d.ts.map +1 -0
  15. package/dist/commands/disk.js +80 -0
  16. package/dist/commands/doctor.d.ts +8 -0
  17. package/dist/commands/doctor.d.ts.map +1 -1
  18. package/dist/commands/doctor.js +48 -1
  19. package/dist/commands/files.d.ts +16 -0
  20. package/dist/commands/files.d.ts.map +1 -1
  21. package/dist/commands/files.js +54 -2
  22. package/dist/commands/init.d.ts +2 -2
  23. package/dist/commands/init.d.ts.map +1 -1
  24. package/dist/commands/init.js +43 -9
  25. package/dist/commands/rm.d.ts +4 -0
  26. package/dist/commands/rm.d.ts.map +1 -0
  27. package/dist/commands/rm.js +87 -0
  28. package/dist/commands/servers.d.ts +7 -0
  29. package/dist/commands/servers.d.ts.map +1 -0
  30. package/dist/commands/servers.js +394 -0
  31. package/dist/commands/tunnel.d.ts +65 -0
  32. package/dist/commands/tunnel.d.ts.map +1 -1
  33. package/dist/commands/tunnel.js +372 -103
  34. package/dist/commands/web-fetch.d.ts +3 -2
  35. package/dist/commands/web-fetch.d.ts.map +1 -1
  36. package/dist/commands/web-fetch.js +25 -19
  37. package/dist/commands/web.d.ts +7 -1
  38. package/dist/commands/web.d.ts.map +1 -1
  39. package/dist/commands/web.js +9 -3
  40. package/dist/core/adapters/profiles.d.ts +9 -0
  41. package/dist/core/adapters/profiles.d.ts.map +1 -1
  42. package/dist/core/adapters/profiles.js +22 -1
  43. package/dist/core/adapters/types.d.ts +9 -0
  44. package/dist/core/adapters/types.d.ts.map +1 -1
  45. package/dist/core/agents/cli.js +13 -6
  46. package/dist/core/agents/render/prompt-context.d.ts.map +1 -1
  47. package/dist/core/agents/render/prompt-context.js +11 -5
  48. package/dist/core/agents/render/session-context.d.ts.map +1 -1
  49. package/dist/core/agents/render/session-context.js +59 -13
  50. package/dist/core/agents/state/live-coordination-view.d.ts +20 -0
  51. package/dist/core/agents/state/live-coordination-view.d.ts.map +1 -1
  52. package/dist/core/agents/state/live-coordination-view.js +60 -0
  53. package/dist/core/agents/state/names.d.ts +43 -3
  54. package/dist/core/agents/state/names.d.ts.map +1 -1
  55. package/dist/core/agents/state/names.js +87 -3
  56. package/dist/core/artifacts/delivery-card.js +9 -2
  57. package/dist/core/artifacts/index.d.ts +140 -4
  58. package/dist/core/artifacts/index.d.ts.map +1 -1
  59. package/dist/core/artifacts/index.js +522 -49
  60. package/dist/core/config.d.ts +68 -11
  61. package/dist/core/config.d.ts.map +1 -1
  62. package/dist/core/config.js +128 -3
  63. package/dist/core/diagnostics/bundle.d.ts.map +1 -1
  64. package/dist/core/diagnostics/bundle.js +2 -2
  65. package/dist/core/events/v3/producers/recorder.d.ts.map +1 -1
  66. package/dist/core/events/v3/producers/recorder.js +16 -0
  67. package/dist/core/events/v3/projection.js +9 -1
  68. package/dist/core/events/v3/support-storage/pack-reader.d.ts.map +1 -1
  69. package/dist/core/events/v3/support-storage/pack-reader.js +42 -16
  70. package/dist/core/hooks/adapter/events.d.ts +17 -0
  71. package/dist/core/hooks/adapter/events.d.ts.map +1 -1
  72. package/dist/core/hooks/adapter/events.js +5 -0
  73. package/dist/core/hooks/adapter/runtime-telemetry.js +3 -1
  74. package/dist/core/hooks/adapter/wiring.d.ts +37 -7
  75. package/dist/core/hooks/adapter/wiring.d.ts.map +1 -1
  76. package/dist/core/hooks/adapter/wiring.js +62 -4
  77. package/dist/core/hooks/cli.js +131 -23
  78. package/dist/core/hooks/fork-lineage.d.ts +40 -0
  79. package/dist/core/hooks/fork-lineage.d.ts.map +1 -0
  80. package/dist/core/hooks/fork-lineage.js +62 -0
  81. package/dist/core/hooks/resolve/transcript.d.ts +16 -0
  82. package/dist/core/hooks/resolve/transcript.d.ts.map +1 -1
  83. package/dist/core/hooks/resolve/transcript.js +84 -0
  84. package/dist/core/hooks/run-markers.d.ts +37 -0
  85. package/dist/core/hooks/run-markers.d.ts.map +1 -0
  86. package/dist/core/hooks/run-markers.js +109 -0
  87. package/dist/core/hooks/shell-rm.d.ts +2 -0
  88. package/dist/core/hooks/shell-rm.d.ts.map +1 -0
  89. package/dist/core/hooks/shell-rm.js +105 -0
  90. package/dist/core/hooks/shell-tokens.d.ts +12 -0
  91. package/dist/core/hooks/shell-tokens.d.ts.map +1 -0
  92. package/dist/core/hooks/shell-tokens.js +97 -0
  93. package/dist/core/hooks/shell-waiter.d.ts.map +1 -1
  94. package/dist/core/hooks/shell-waiter.js +3 -93
  95. package/dist/core/semantic/contract.d.ts +5 -5
  96. package/dist/core/servers/index.d.ts +211 -0
  97. package/dist/core/servers/index.d.ts.map +1 -0
  98. package/dist/core/servers/index.js +560 -0
  99. package/dist/core/servers/net.d.ts +58 -0
  100. package/dist/core/servers/net.d.ts.map +1 -0
  101. package/dist/core/servers/net.js +270 -0
  102. package/dist/core/servers/tunnels.d.ts +14 -0
  103. package/dist/core/servers/tunnels.d.ts.map +1 -0
  104. package/dist/core/servers/tunnels.js +33 -0
  105. package/dist/core/storage/builtins.js +1 -0
  106. package/dist/core/storage/process-log.d.ts +12 -0
  107. package/dist/core/storage/process-log.d.ts.map +1 -1
  108. package/dist/core/storage/process-log.js +10 -2
  109. package/dist/core/workflow/engine.d.ts.map +1 -1
  110. package/dist/core/workflow/engine.js +30 -1
  111. package/dist/core/workflow/sandbox-projection.d.ts +13 -2
  112. package/dist/core/workflow/sandbox-projection.d.ts.map +1 -1
  113. package/dist/core/workflow/sandbox-projection.js +23 -0
  114. package/dist/core/workflow/spawn-claude.d.ts.map +1 -1
  115. package/dist/core/workflow/spawn-claude.js +6 -1
  116. package/dist/core/workflow/spawn-codex.d.ts +2 -0
  117. package/dist/core/workflow/spawn-codex.d.ts.map +1 -1
  118. package/dist/core/workflow/spawn-codex.js +20 -1
  119. package/dist/core/workflow/spawn-cursor.d.ts.map +1 -1
  120. package/dist/core/workflow/spawn-cursor.js +6 -1
  121. package/dist/core/workflow/spawn-opencode.d.ts.map +1 -1
  122. package/dist/core/workflow/spawn-opencode.js +4 -1
  123. package/dist/core/workflow/types.d.ts +47 -2
  124. package/dist/core/workflow/types.d.ts.map +1 -1
  125. package/dist/core/workflow/worker-access.d.ts +92 -0
  126. package/dist/core/workflow/worker-access.d.ts.map +1 -0
  127. package/dist/core/workflow/worker-access.js +450 -0
  128. package/dist/lib/browser/batch-steps.d.ts +18 -0
  129. package/dist/lib/browser/batch-steps.d.ts.map +1 -0
  130. package/dist/lib/browser/batch-steps.js +82 -0
  131. package/dist/lib/browser/collect/collector.d.ts +99 -0
  132. package/dist/lib/browser/collect/collector.d.ts.map +1 -0
  133. package/dist/lib/browser/collect/collector.js +202 -0
  134. package/dist/lib/browser/collect/fields.d.ts +31 -0
  135. package/dist/lib/browser/collect/fields.d.ts.map +1 -0
  136. package/dist/lib/browser/collect/fields.js +75 -0
  137. package/dist/lib/browser/collect/index.d.ts +6 -0
  138. package/dist/lib/browser/collect/index.d.ts.map +1 -0
  139. package/dist/lib/browser/collect/index.js +5 -0
  140. package/dist/lib/browser/collect/page-driver.d.ts +14 -0
  141. package/dist/lib/browser/collect/page-driver.d.ts.map +1 -0
  142. package/dist/lib/browser/collect/page-driver.js +306 -0
  143. package/dist/lib/browser/collect/presets.d.ts +52 -0
  144. package/dist/lib/browser/collect/presets.d.ts.map +1 -0
  145. package/dist/lib/browser/collect/presets.js +176 -0
  146. package/dist/lib/browser/collect/scroll-plan.d.ts +85 -0
  147. package/dist/lib/browser/collect/scroll-plan.d.ts.map +1 -0
  148. package/dist/lib/browser/collect/scroll-plan.js +118 -0
  149. package/dist/lib/browser/index.d.ts +1 -1
  150. package/dist/lib/browser/index.d.ts.map +1 -1
  151. package/dist/lib/browser/page-review-judge.d.ts +2 -0
  152. package/dist/lib/browser/page-review-judge.d.ts.map +1 -1
  153. package/dist/lib/browser/page-review-judge.js +13 -0
  154. package/dist/lib/browser/qa-run-contracts.d.ts +10 -0
  155. package/dist/lib/browser/qa-run-contracts.d.ts.map +1 -1
  156. package/dist/lib/browser/qa-run.d.ts.map +1 -1
  157. package/dist/lib/browser/qa-run.js +1 -0
  158. package/dist/lib/browser/windows-chrome.d.ts +59 -0
  159. package/dist/lib/browser/windows-chrome.d.ts.map +1 -0
  160. package/dist/lib/browser/windows-chrome.js +179 -0
  161. package/dist/lib/claude-desktop-share.d.ts +136 -0
  162. package/dist/lib/claude-desktop-share.d.ts.map +1 -0
  163. package/dist/lib/claude-desktop-share.js +394 -0
  164. package/dist/lib/disk-usage.d.ts +50 -0
  165. package/dist/lib/disk-usage.d.ts.map +1 -0
  166. package/dist/lib/disk-usage.js +303 -0
  167. package/dist/lib/docs-lint.d.ts +6 -0
  168. package/dist/lib/docs-lint.d.ts.map +1 -1
  169. package/dist/lib/docs-lint.js +8 -3
  170. package/dist/lib/guarded-remove.d.ts +34 -0
  171. package/dist/lib/guarded-remove.d.ts.map +1 -0
  172. package/dist/lib/guarded-remove.js +310 -0
  173. package/dist/lib/instructions/templates.js +8 -8
  174. package/dist/lib/tunnel/allowlist.d.ts +44 -0
  175. package/dist/lib/tunnel/allowlist.d.ts.map +1 -0
  176. package/dist/lib/tunnel/allowlist.js +204 -0
  177. package/dist/lib/tunnel/current-address.d.ts +41 -0
  178. package/dist/lib/tunnel/current-address.d.ts.map +1 -0
  179. package/dist/lib/tunnel/current-address.js +123 -0
  180. package/dist/lib/tunnel/error-page.d.ts +1 -1
  181. package/dist/lib/tunnel/error-page.d.ts.map +1 -1
  182. package/dist/lib/tunnel/error-page.js +19 -8
  183. package/dist/lib/tunnel/gate.js +33 -7
  184. package/dist/lib/tunnel/path-scope.d.ts +22 -0
  185. package/dist/lib/tunnel/path-scope.d.ts.map +1 -0
  186. package/dist/lib/tunnel/path-scope.js +62 -0
  187. package/dist/lib/tunnel/processes.d.ts +39 -0
  188. package/dist/lib/tunnel/processes.d.ts.map +1 -0
  189. package/dist/lib/tunnel/processes.js +121 -0
  190. package/dist/lib/tunnel/state.d.ts +33 -3
  191. package/dist/lib/tunnel/state.d.ts.map +1 -1
  192. package/dist/lib/tunnel/state.js +115 -30
  193. package/package.json +7 -1
  194. package/schemas/config.schema.json +91 -0
  195. package/src/commander.ts +51 -0
  196. package/src/commands/agents.ts +111 -11
  197. package/src/commands/artifacts.ts +171 -19
  198. package/src/commands/browse.ts +400 -57
  199. package/src/commands/claude-desktop.ts +61 -0
  200. package/src/commands/disk.ts +114 -0
  201. package/src/commands/doctor.ts +52 -1
  202. package/src/commands/files.ts +93 -2
  203. package/src/commands/init.ts +55 -5
  204. package/src/commands/rm.ts +115 -0
  205. package/src/commands/servers.ts +506 -0
  206. package/src/commands/tunnel.ts +494 -116
  207. package/src/commands/web-fetch.ts +30 -19
  208. package/src/commands/web.ts +9 -3
  209. package/src/core/adapters/profiles.ts +22 -1
  210. package/src/core/adapters/types.ts +10 -0
  211. package/src/core/agents/cli.ts +14 -6
  212. package/src/core/agents/render/prompt-context.ts +25 -8
  213. package/src/core/agents/render/session-context.ts +84 -16
  214. package/src/core/agents/state/live-coordination-view.ts +73 -0
  215. package/src/core/agents/state/names.ts +117 -6
  216. package/src/core/artifacts/delivery-card.ts +10 -2
  217. package/src/core/artifacts/index.ts +697 -44
  218. package/src/core/config.ts +183 -4
  219. package/src/core/diagnostics/bundle.ts +2 -1
  220. package/src/core/events/v3/producers/recorder.ts +16 -0
  221. package/src/core/events/v3/projection.ts +11 -1
  222. package/src/core/events/v3/support-storage/pack-reader.ts +45 -19
  223. package/src/core/hooks/adapter/events.ts +19 -0
  224. package/src/core/hooks/adapter/runtime-telemetry.ts +3 -1
  225. package/src/core/hooks/adapter/wiring.ts +116 -8
  226. package/src/core/hooks/cli.ts +152 -22
  227. package/src/core/hooks/fork-lineage.ts +82 -0
  228. package/src/core/hooks/resolve/transcript.ts +88 -0
  229. package/src/core/hooks/run-markers.ts +132 -0
  230. package/src/core/hooks/shell-rm.ts +103 -0
  231. package/src/core/hooks/shell-tokens.ts +96 -0
  232. package/src/core/hooks/shell-waiter.ts +4 -91
  233. package/src/core/servers/index.ts +712 -0
  234. package/src/core/servers/net.ts +283 -0
  235. package/src/core/servers/tunnels.ts +39 -0
  236. package/src/core/storage/builtins.ts +1 -0
  237. package/src/core/storage/process-log.ts +17 -2
  238. package/src/core/workflow/engine.ts +38 -1
  239. package/src/core/workflow/sandbox-projection.ts +38 -2
  240. package/src/core/workflow/spawn-claude.ts +5 -1
  241. package/src/core/workflow/spawn-codex.ts +18 -1
  242. package/src/core/workflow/spawn-cursor.ts +5 -1
  243. package/src/core/workflow/spawn-opencode.ts +4 -1
  244. package/src/core/workflow/types.ts +62 -2
  245. package/src/core/workflow/worker-access.ts +525 -0
  246. package/src/lib/browser/batch-steps.ts +79 -0
  247. package/src/lib/browser/collect/collector.ts +306 -0
  248. package/src/lib/browser/collect/fields.ts +87 -0
  249. package/src/lib/browser/collect/index.ts +47 -0
  250. package/src/lib/browser/collect/page-driver.ts +327 -0
  251. package/src/lib/browser/collect/presets.ts +237 -0
  252. package/src/lib/browser/collect/scroll-plan.ts +179 -0
  253. package/src/lib/browser/index.ts +1 -0
  254. package/src/lib/browser/page-review-judge.ts +16 -0
  255. package/src/lib/browser/qa-run-contracts.ts +11 -0
  256. package/src/lib/browser/qa-run.ts +1 -0
  257. package/src/lib/browser/windows-chrome.ts +227 -0
  258. package/src/lib/claude-desktop-share.ts +511 -0
  259. package/src/lib/disk-usage.ts +347 -0
  260. package/src/lib/docs-lint.ts +8 -3
  261. package/src/lib/guarded-remove.ts +376 -0
  262. package/src/lib/instructions/templates.ts +8 -8
  263. package/src/lib/tunnel/allowlist.ts +208 -0
  264. package/src/lib/tunnel/current-address.ts +158 -0
  265. package/src/lib/tunnel/error-page.ts +25 -9
  266. package/src/lib/tunnel/gate.ts +38 -9
  267. package/src/lib/tunnel/path-scope.ts +73 -0
  268. package/src/lib/tunnel/processes.ts +149 -0
  269. package/src/lib/tunnel/state.ts +143 -30
@@ -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
+ }
@@ -1,5 +1,5 @@
1
1
  export interface TunnelErrorPageOptions {
2
- kind: "access-denied" | "upstream-unavailable";
2
+ kind: "access-denied" | "path-denied" | "upstream-unavailable";
3
3
  incidentId: string;
4
4
  timestamp: string;
5
5
  tunnelName: string;
@@ -40,14 +40,30 @@ function diagnosticText(options: TunnelErrorPageOptions): string {
40
40
  }
41
41
 
42
42
  export function renderTunnelErrorPage(options: TunnelErrorPageOptions): string {
43
- const denied = options.kind === "access-denied";
44
- const title = denied ? "This device is not allowed yet" : "The preview is temporarily offline";
45
- const summary = denied
46
- ? "The tunnel is running, but this device's public IP is not on its access list."
47
- : "The public tunnel and access check are working, but the local preview server is not responding.";
48
- const nextStep = denied
49
- ? "Copy the diagnostic below and send it to the person running the tunnel. It includes the public IP that needs to be allowed."
50
- : "Copy the diagnostic below and send it to the person running the tunnel. The incident ID can be matched to the server log.";
43
+ const copy = {
44
+ "access-denied": {
45
+ title: "This device is not allowed yet",
46
+ summary: "The tunnel is running, but this device's public IP is not on its access list.",
47
+ nextStep:
48
+ "Copy the diagnostic below and send it to the person running the tunnel. It includes the public IP that needs to be allowed.",
49
+ },
50
+ "path-denied": {
51
+ title: "This page is not shared",
52
+ summary:
53
+ "The tunnel is running, but it shares only part of the site, and this address is outside it.",
54
+ nextStep:
55
+ "If you expected to see this page, copy the diagnostic below and send it to the person running the tunnel.",
56
+ },
57
+ "upstream-unavailable": {
58
+ title: "The preview is temporarily offline",
59
+ summary:
60
+ "The public tunnel and access check are working, but the local preview server is not responding.",
61
+ nextStep:
62
+ "Copy the diagnostic below and send it to the person running the tunnel. The incident ID can be matched to the server log.",
63
+ },
64
+ }[options.kind];
65
+ const { title, summary, nextStep } = copy;
66
+ const denied = options.kind !== "upstream-unavailable";
51
67
  const diagnostic = diagnosticText(options);
52
68
  const safeDiagnosticForScript = JSON.stringify(diagnostic).replaceAll("<", "\\u003c");
53
69
 
@@ -4,14 +4,18 @@
4
4
  // stripped (Bun's fetch auto-decompresses the body but retains the encoding
5
5
  // header, which breaks browser decoding downstream). Cloudflare provider mode
6
6
  // checks CF-Connecting-IP against an allowlist; trusted local proxy mode lets
7
- // the local exposer own access.
7
+ // the local exposer own access. In every mode the gate then refuses any path
8
+ // outside the tunnel's path scope (see path-scope.ts); an empty scope refuses
9
+ // everything.
8
10
  //
9
11
  // Runs detached, outside the CLI command framework; no command context is
10
12
  // available; stdout/stderr is captured into .cache/tunnel/gate.log by the
11
13
  // spawner.
12
14
 
15
+ import { allowlistMatches, compileAllowlist } from "./allowlist.ts";
13
16
  import { renderTunnelErrorPage } from "./error-page";
14
17
  import { applyUpstreamHeaders } from "./forward-headers";
18
+ import { ALLOW_PATHS_ENV, isPathAllowed, parseAllowPathsEnv } from "./path-scope.ts";
15
19
 
16
20
  // `--port`/`--name` are also passed on argv (not just env) so the gate's port
17
21
  // and instance name show up in its process command line. That's what lets
@@ -24,16 +28,13 @@ function argvFlag(flag: string): string | undefined {
24
28
  return i !== -1 ? process.argv[i + 1] : undefined;
25
29
  }
26
30
 
27
- const ALLOW = new Set(
28
- (process.env.HARNERY_TUNNEL_ALLOW ?? "")
29
- .split(",")
30
- .map((s) => s.trim())
31
- .filter(Boolean),
32
- );
31
+ // Entries are exact addresses or CIDR ranges (`203.0.113.0/24`, `2601:db8:1:2::/64`).
32
+ const ALLOW = compileAllowlist((process.env.HARNERY_TUNNEL_ALLOW ?? "").split(","));
33
33
  const TARGET = process.env.HARNERY_TUNNEL_TARGET ?? "127.0.0.1:8001";
34
34
  const VHOST = process.env.HARNERY_TUNNEL_VHOST ?? "localhost";
35
35
  const PORT = Number(process.env.HARNERY_TUNNEL_PORT ?? argvFlag("--port") ?? "9001");
36
36
  const ACCESS = process.env.HARNERY_TUNNEL_ACCESS ?? "cloudflare-allowlist";
37
+ const ALLOW_PATHS = parseAllowPathsEnv(process.env[ALLOW_PATHS_ENV]);
37
38
  const NAME = argvFlag("--name") ?? "default";
38
39
 
39
40
  const UPSTREAM_HTTP = `http://${TARGET}`;
@@ -77,7 +78,7 @@ const server = Bun.serve<WsData, never>({
77
78
  const url = new URL(req.url);
78
79
  if (ACCESS === "cloudflare-allowlist") {
79
80
  const ip = req.headers.get("cf-connecting-ip") ?? "";
80
- if (!ALLOW.has(ip)) {
81
+ if (!allowlistMatches(ALLOW, ip)) {
81
82
  const details = requestDetails(req, url);
82
83
  // Log denials so operators can whitelist a phone/laptop that just
83
84
  // hit 403 without asking the human to dig up their public IP.
@@ -96,6 +97,22 @@ const server = Bun.serve<WsData, never>({
96
97
  }
97
98
  }
98
99
 
100
+ if (!isPathAllowed(url.pathname, ALLOW_PATHS)) {
101
+ const details = requestDetails(req, url);
102
+ console.log(
103
+ // lint-ok-emission: detached worker, see file note above
104
+ `path-deny: incident=${details.incidentId} ip=${details.clientIp || "(missing-cf-connecting-ip)"} ray=${details.cloudflareRay || "(missing)"} ${req.method} ${details.path}`,
105
+ );
106
+ return new Response(renderTunnelErrorPage({ ...details, kind: "path-denied" }), {
107
+ status: 403,
108
+ headers: {
109
+ "cache-control": "no-store",
110
+ "content-type": "text/html; charset=utf-8",
111
+ "x-harnery-tunnel-incident": details.incidentId,
112
+ },
113
+ });
114
+ }
115
+
99
116
  if (req.headers.get("upgrade")?.toLowerCase() === "websocket") {
100
117
  if (
101
118
  server.upgrade(req, {
@@ -192,4 +209,16 @@ const server = Bun.serve<WsData, never>({
192
209
  // captured into .cache/tunnel/gate.log by the spawning command.
193
210
  console.log(`harn-tunnel-gate :${server.port} -> ${UPSTREAM_HTTP} (Host: ${VHOST})`); // lint-ok-emission: detached worker, see file note above
194
211
  console.log(`access: ${ACCESS}`); // lint-ok-emission: detached worker, see file note above
195
- console.log(`allow: ${[...ALLOW].join(", ") || "(empty, not used outside allowlist mode)"}`); // lint-ok-emission: detached worker, see file note above
212
+ console.log(`paths: ${ALLOW_PATHS.join(", ") || "(empty, every path refused)"}`); // lint-ok-emission: detached worker, see file note above
213
+ console.log(
214
+ // lint-ok-emission: detached worker, see file note above
215
+ `allow: ${
216
+ process.env.HARNERY_TUNNEL_ALLOW?.split(",")
217
+ .filter((s) => s.trim())
218
+ .join(", ") || "(empty, not used outside allowlist mode)"
219
+ }`,
220
+ );
221
+ if (ALLOW.invalid.length > 0) {
222
+ // lint-ok-emission: detached worker, see file note above
223
+ console.log(`allow: ignoring unreadable entries: ${ALLOW.invalid.join(", ")}`);
224
+ }
@@ -0,0 +1,73 @@
1
+ // Path scope for the tunnel gate: the URL path prefixes a tunnel publishes.
2
+ //
3
+ // A tunnel forwards to a whole local app, but the person starting it usually
4
+ // means to share one surface of that app. The gate therefore refuses every
5
+ // request whose path is outside the scope the operator named at `tunnel up`,
6
+ // and an empty scope refuses everything. `/` is the explicit way to publish
7
+ // the whole upstream.
8
+
9
+ /** Env var that carries the scope from `tunnel up` to the detached gate. */
10
+ export const ALLOW_PATHS_ENV = "HARNERY_TUNNEL_ALLOW_PATHS";
11
+
12
+ /**
13
+ * Normalize one `--allow-path` value to a canonical prefix: a leading slash,
14
+ * no trailing slash (except `/` itself), no query or fragment, and no dot,
15
+ * empty, or percent-encoded segment. Throws on anything the gate could not
16
+ * match unambiguously, so a typo fails at `tunnel up` instead of publishing
17
+ * more or less than intended.
18
+ */
19
+ export function normalizeAllowPath(raw: string): string {
20
+ const value = raw.trim();
21
+ if (!value.startsWith("/")) {
22
+ throw new Error(`allow-path must start with "/": ${JSON.stringify(raw)}`);
23
+ }
24
+ if (/[?#%\\]/.test(value)) {
25
+ throw new Error(
26
+ `allow-path must be a plain path prefix without ?, #, %, or \\: ${JSON.stringify(raw)}`,
27
+ );
28
+ }
29
+ if (value === "/") return "/";
30
+ const trimmed = value.replace(/\/+$/, "");
31
+ const segments = trimmed.slice(1).split("/");
32
+ if (segments.some((s) => s === "" || s === "." || s === "..")) {
33
+ throw new Error(
34
+ `allow-path must not contain empty, "." or ".." segments: ${JSON.stringify(raw)}`,
35
+ );
36
+ }
37
+ return trimmed;
38
+ }
39
+
40
+ /** Normalize and de-duplicate a list of `--allow-path` values. */
41
+ export function normalizeAllowPaths(raw: readonly string[]): string[] {
42
+ return [...new Set(raw.map(normalizeAllowPath))];
43
+ }
44
+
45
+ /** Parse the gate's env value (comma-separated, already normalized by `up`). */
46
+ export function parseAllowPathsEnv(value: string | undefined): string[] {
47
+ return normalizeAllowPaths(
48
+ (value ?? "")
49
+ .split(",")
50
+ .map((s) => s.trim())
51
+ .filter(Boolean),
52
+ );
53
+ }
54
+
55
+ // Encoded slash, backslash, dot, or percent. A request path carrying one of
56
+ // these can be decoded differently by the gate and the upstream router (for
57
+ // example `/share%2F..%2Fprivate`), so the gate refuses it outright rather than
58
+ // guess which reading the upstream will use.
59
+ const AMBIGUOUS_PATH = /%(2f|5c|2e|25)|\\/i;
60
+
61
+ /**
62
+ * True when `pathname` (a WHATWG-parsed URL pathname, so `.` and `..` segments
63
+ * are already resolved) falls inside one of the allowed prefixes. A prefix
64
+ * matches itself and anything below it on a segment boundary: `/share` allows
65
+ * `/share` and `/share/x`, never `/shared`.
66
+ */
67
+ export function isPathAllowed(pathname: string, allowPaths: readonly string[]): boolean {
68
+ if (allowPaths.length === 0) return false;
69
+ if (!pathname.startsWith("/") || AMBIGUOUS_PATH.test(pathname)) return false;
70
+ return allowPaths.some(
71
+ (prefix) => prefix === "/" || pathname === prefix || pathname.startsWith(`${prefix}/`),
72
+ );
73
+ }
@@ -0,0 +1,149 @@
1
+ // Process and port discovery for the tunnel commands, per platform.
2
+ //
3
+ // Linux and macOS have `pgrep`/`ps`; Linux has `ss`; both have `lsof`. Windows
4
+ // has none of these, so it uses PowerShell for command lines and `netstat` for
5
+ // listening sockets. Every probe is best effort: a missing tool yields "no
6
+ // answer" (null or an empty list), never a thrown error, and the callers fall
7
+ // back to checks that need no tool (a TCP connect probe, a PID check).
8
+
9
+ import { spawnSync } from "node:child_process";
10
+ import { connect } from "node:net";
11
+
12
+ type Run = (
13
+ command: string,
14
+ args: string[],
15
+ ) => { status: number | null; stdout: string; missing: boolean };
16
+
17
+ const runTool: Run = (command, args) => {
18
+ const r = spawnSync(command, args, { encoding: "utf-8", windowsHide: true, timeout: 15_000 });
19
+ const missing = (r.error as NodeJS.ErrnoException | undefined)?.code === "ENOENT";
20
+ return { status: r.status, stdout: typeof r.stdout === "string" ? r.stdout : "", missing };
21
+ };
22
+
23
+ export interface ProcessRow {
24
+ pid: number;
25
+ command: string;
26
+ }
27
+
28
+ /** Parse `ps -axo pid=,command=` output (also the shape the PowerShell probe emits). */
29
+ export function parseProcessRows(output: string): ProcessRow[] {
30
+ const rows: ProcessRow[] = [];
31
+ for (const line of output.split(/\r?\n/)) {
32
+ const m = line.match(/^\s*(\d+)\s+(.*\S)\s*$/);
33
+ if (m) rows.push({ pid: Number(m[1]), command: m[2] as string });
34
+ }
35
+ return rows;
36
+ }
37
+
38
+ const POWERSHELL_PROCESS_LIST =
39
+ "Get-CimInstance Win32_Process | Where-Object { $_.CommandLine } | " +
40
+ 'ForEach-Object { "$($_.ProcessId) $($_.CommandLine)" }';
41
+
42
+ /** Every process with a command line, or null when the platform gives no way to list them. */
43
+ export function listProcesses(
44
+ platform: NodeJS.Platform = process.platform,
45
+ run: Run = runTool,
46
+ ): ProcessRow[] | null {
47
+ if (platform === "win32") {
48
+ for (const shell of ["powershell.exe", "pwsh.exe", "pwsh"]) {
49
+ const r = run(shell, ["-NoProfile", "-NonInteractive", "-Command", POWERSHELL_PROCESS_LIST]);
50
+ if (r.missing) continue;
51
+ if (r.status === 0) return parseProcessRows(r.stdout);
52
+ }
53
+ return null;
54
+ }
55
+ const ps = run("ps", ["-axo", "pid=,command="]);
56
+ return ps.status === 0 ? parseProcessRows(ps.stdout) : null;
57
+ }
58
+
59
+ /**
60
+ * PIDs whose command line matches `pattern`, an extended regular expression
61
+ * (the intersection of `pgrep -f` and JavaScript syntax). Returns [] when
62
+ * nothing matches or no listing tool works.
63
+ */
64
+ export function findPidsByCommandLine(
65
+ pattern: string,
66
+ platform: NodeJS.Platform = process.platform,
67
+ run: Run = runTool,
68
+ ): number[] {
69
+ if (platform !== "win32") {
70
+ // `--` ends options: the provider pattern starts with `--url`, which pgrep
71
+ // would otherwise reject as an unknown flag and report as "no match".
72
+ const r = run("pgrep", ["-f", "--", pattern]);
73
+ if (!r.missing) {
74
+ if (r.status !== 0) return [];
75
+ return r.stdout
76
+ .split("\n")
77
+ .map((line) => Number(line.trim()))
78
+ .filter((pid) => Number.isInteger(pid) && pid > 0);
79
+ }
80
+ }
81
+ const rows = listProcesses(platform, run);
82
+ if (!rows) return [];
83
+ const re = new RegExp(pattern);
84
+ return rows.filter((row) => re.test(row.command)).map((row) => row.pid);
85
+ }
86
+
87
+ /** Ports from `ss -tlnH`: `LISTEN 0 4096 127.0.0.1:9001 0.0.0.0:*`. */
88
+ export function parseSsPorts(output: string): number[] {
89
+ return [...output.matchAll(/:(\d+)\s/g)].map((m) => Number(m[1]));
90
+ }
91
+
92
+ /** Ports from `lsof -nP -iTCP -sTCP:LISTEN` rows ending `127.0.0.1:58055 (LISTEN)`. */
93
+ export function parseLsofPorts(output: string): number[] {
94
+ return [...output.matchAll(/:(\d+) \(LISTEN\)\s*$/gm)].map((m) => Number(m[1]));
95
+ }
96
+
97
+ /** Ports from `netstat -ano -p TCP` rows: `TCP 0.0.0.0:9001 0.0.0.0:0 LISTENING 4`. */
98
+ export function parseNetstatPorts(output: string): number[] {
99
+ return [...output.matchAll(/^\s*TCP\s+\S*:(\d+)\s+\S+\s+LISTENING\b/gim)].map((m) =>
100
+ Number(m[1]),
101
+ );
102
+ }
103
+
104
+ /**
105
+ * Ports with a LISTEN socket, or null when no discovery tool answered.
106
+ *
107
+ * Null is not "no ports": reporting every port as free would let a caller hand
108
+ * out an occupied port, so callers that need a real answer use `portListening`,
109
+ * which falls back to connecting.
110
+ */
111
+ export function listeningPorts(
112
+ platform: NodeJS.Platform = process.platform,
113
+ run: Run = runTool,
114
+ ): Set<number> | null {
115
+ if (platform === "win32") {
116
+ const r = run("netstat", ["-ano", "-p", "TCP"]);
117
+ return !r.missing && r.status === 0 ? new Set(parseNetstatPorts(r.stdout)) : null;
118
+ }
119
+ if (platform === "linux") {
120
+ const ss = run("ss", ["-tlnH"]);
121
+ if (!ss.missing && ss.status === 0) return new Set(parseSsPorts(ss.stdout));
122
+ }
123
+ // macOS and BSD, or Linux without iproute2. lsof reports a failure when any
124
+ // single process is unreadable while stdout still holds usable rows, so
125
+ // judge it on the output.
126
+ const lsof = run("lsof", ["-nP", "-iTCP", "-sTCP:LISTEN"]);
127
+ if (!lsof.missing && lsof.stdout.trim()) return new Set(parseLsofPorts(lsof.stdout));
128
+ return null;
129
+ }
130
+
131
+ /** True when something accepts a TCP connection on 127.0.0.1:<port>. */
132
+ export function connectProbe(port: number, timeoutMs = 400): Promise<boolean> {
133
+ return new Promise((resolve) => {
134
+ const socket = connect({ port, host: "127.0.0.1" });
135
+ const done = (result: boolean) => {
136
+ socket.destroy();
137
+ resolve(result);
138
+ };
139
+ socket.setTimeout(timeoutMs, () => done(false));
140
+ socket.once("connect", () => done(true));
141
+ socket.once("error", () => done(false));
142
+ });
143
+ }
144
+
145
+ /** Whether `port` has a listener, by the platform tool when there is one, else by connecting. */
146
+ export async function portListening(port: number): Promise<boolean> {
147
+ const ports = listeningPorts();
148
+ return ports ? ports.has(port) : connectProbe(port);
149
+ }