harnery 0.42.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 (77) hide show
  1. package/dist/commander.d.ts +16 -0
  2. package/dist/commander.d.ts.map +1 -1
  3. package/dist/commander.js +18 -0
  4. package/dist/commands/agents.d.ts.map +1 -1
  5. package/dist/commands/agents.js +54 -4
  6. package/dist/commands/tunnel.d.ts +65 -0
  7. package/dist/commands/tunnel.d.ts.map +1 -1
  8. package/dist/commands/tunnel.js +290 -101
  9. package/dist/commands/web-fetch.d.ts +3 -2
  10. package/dist/commands/web-fetch.d.ts.map +1 -1
  11. package/dist/commands/web-fetch.js +25 -19
  12. package/dist/commands/web.d.ts +7 -1
  13. package/dist/commands/web.d.ts.map +1 -1
  14. package/dist/commands/web.js +9 -3
  15. package/dist/core/agents/render/prompt-context.d.ts.map +1 -1
  16. package/dist/core/agents/render/prompt-context.js +11 -5
  17. package/dist/core/agents/render/session-context.d.ts.map +1 -1
  18. package/dist/core/agents/render/session-context.js +57 -13
  19. package/dist/core/agents/state/names.d.ts +43 -3
  20. package/dist/core/agents/state/names.d.ts.map +1 -1
  21. package/dist/core/agents/state/names.js +87 -3
  22. package/dist/core/events/v3/support-storage/pack-reader.d.ts.map +1 -1
  23. package/dist/core/events/v3/support-storage/pack-reader.js +42 -16
  24. package/dist/core/hooks/cli.js +87 -18
  25. package/dist/core/hooks/fork-lineage.d.ts +40 -0
  26. package/dist/core/hooks/fork-lineage.d.ts.map +1 -0
  27. package/dist/core/hooks/fork-lineage.js +62 -0
  28. package/dist/core/hooks/resolve/transcript.d.ts +16 -0
  29. package/dist/core/hooks/resolve/transcript.d.ts.map +1 -1
  30. package/dist/core/hooks/resolve/transcript.js +84 -0
  31. package/dist/core/hooks/shell-rm.d.ts +2 -0
  32. package/dist/core/hooks/shell-rm.d.ts.map +1 -0
  33. package/dist/core/hooks/shell-rm.js +105 -0
  34. package/dist/core/hooks/shell-tokens.d.ts +12 -0
  35. package/dist/core/hooks/shell-tokens.d.ts.map +1 -0
  36. package/dist/core/hooks/shell-tokens.js +97 -0
  37. package/dist/core/hooks/shell-waiter.d.ts.map +1 -1
  38. package/dist/core/hooks/shell-waiter.js +3 -93
  39. package/dist/core/semantic/contract.d.ts +5 -5
  40. package/dist/core/storage/process-log.d.ts +12 -0
  41. package/dist/core/storage/process-log.d.ts.map +1 -1
  42. package/dist/core/storage/process-log.js +10 -2
  43. package/dist/lib/tunnel/allowlist.d.ts +44 -0
  44. package/dist/lib/tunnel/allowlist.d.ts.map +1 -0
  45. package/dist/lib/tunnel/allowlist.js +204 -0
  46. package/dist/lib/tunnel/current-address.d.ts +41 -0
  47. package/dist/lib/tunnel/current-address.d.ts.map +1 -0
  48. package/dist/lib/tunnel/current-address.js +123 -0
  49. package/dist/lib/tunnel/gate.js +13 -6
  50. package/dist/lib/tunnel/processes.d.ts +39 -0
  51. package/dist/lib/tunnel/processes.d.ts.map +1 -0
  52. package/dist/lib/tunnel/processes.js +121 -0
  53. package/dist/lib/tunnel/state.d.ts +28 -3
  54. package/dist/lib/tunnel/state.d.ts.map +1 -1
  55. package/dist/lib/tunnel/state.js +98 -27
  56. package/package.json +2 -1
  57. package/src/commander.ts +32 -0
  58. package/src/commands/agents.ts +97 -11
  59. package/src/commands/tunnel.ts +394 -116
  60. package/src/commands/web-fetch.ts +30 -19
  61. package/src/commands/web.ts +9 -3
  62. package/src/core/agents/render/prompt-context.ts +25 -8
  63. package/src/core/agents/render/session-context.ts +83 -16
  64. package/src/core/agents/state/names.ts +117 -6
  65. package/src/core/events/v3/support-storage/pack-reader.ts +45 -19
  66. package/src/core/hooks/cli.ts +106 -17
  67. package/src/core/hooks/fork-lineage.ts +82 -0
  68. package/src/core/hooks/resolve/transcript.ts +88 -0
  69. package/src/core/hooks/shell-rm.ts +103 -0
  70. package/src/core/hooks/shell-tokens.ts +96 -0
  71. package/src/core/hooks/shell-waiter.ts +4 -91
  72. package/src/core/storage/process-log.ts +17 -2
  73. package/src/lib/tunnel/allowlist.ts +208 -0
  74. package/src/lib/tunnel/current-address.ts +158 -0
  75. package/src/lib/tunnel/gate.ts +16 -8
  76. package/src/lib/tunnel/processes.ts +149 -0
  77. package/src/lib/tunnel/state.ts +123 -27
@@ -1,3 +1,5 @@
1
+ import { basename, shellCommandFromTool, tokenize } from "./shell-tokens.ts";
2
+
1
3
  /** Recognize inline waiters; this is not a proof of arbitrary shell termination. */
2
4
  const REASON =
3
5
  "Inline shell waiter blocked: polling loops and delayed log-only checks can outlive the job " +
@@ -6,82 +8,6 @@ const REASON =
6
8
  "nonzero timeout exit, and producer-exit/failure detection. Do not create another waiter " +
7
9
  "to check progress or infer completion from a broad pgrep -f pattern.";
8
10
 
9
- interface Token {
10
- value: string;
11
- quoted: boolean;
12
- operator?: boolean;
13
- }
14
-
15
- /** Keep quoted arguments opaque, including examples and heredoc bodies. */
16
- function tokenize(source: string): Token[] {
17
- const out: Token[] = [];
18
- const heredocs: { end: string; tabs: boolean }[] = [];
19
- for (let i = 0; i < source.length; ) {
20
- const ch = source[i]!;
21
- if (ch === "\\" && source[i + 1] === "\n") {
22
- i += 2;
23
- continue;
24
- }
25
- if (ch === "\n") {
26
- out.push({ value: ";", quoted: false, operator: true });
27
- i++;
28
- for (const doc of heredocs.splice(0)) {
29
- while (i < source.length) {
30
- const end = source.indexOf("\n", i);
31
- const stop = end === -1 ? source.length : end;
32
- const line = source.slice(i, stop);
33
- i = end === -1 ? source.length : end + 1;
34
- if ((doc.tabs ? line.replace(/^\t+/, "") : line) === doc.end) break;
35
- }
36
- }
37
- continue;
38
- }
39
- if (/\s/.test(ch)) {
40
- i++;
41
- continue;
42
- }
43
- if (ch === "#") {
44
- const end = source.indexOf("\n", i);
45
- i = end === -1 ? source.length : end;
46
- continue;
47
- }
48
- if (";|&(){}<>".includes(ch)) {
49
- const op = source.slice(i).match(/^(?:<<-?|>>|&&|\|\||[;|&(){}<>])/)![0];
50
- out.push({ value: op, quoted: false, operator: true });
51
- i += op.length;
52
- continue;
53
- }
54
- let value = "";
55
- let quoted = false;
56
- while (i < source.length && !/[\s;|&(){}<>]/.test(source[i]!)) {
57
- const next = source[i++]!;
58
- if (next === "'" || next === '"' || next === "`") {
59
- quoted = true;
60
- while (i < source.length && source[i] !== next) {
61
- if (source[i] === "\\" && next !== "'" && i + 1 < source.length) i++;
62
- value += source[i++]!;
63
- }
64
- if (source[i] === next) i++;
65
- } else if (next === "\\" && i < source.length) {
66
- const escaped = source[i++]!;
67
- if (escaped !== "\n") value += escaped;
68
- } else {
69
- value += next;
70
- }
71
- }
72
- const previous = out.at(-1)?.value;
73
- if (previous === "<<" || previous === "<<-") {
74
- heredocs.push({ end: value, tabs: previous === "<<-" });
75
- }
76
- out.push({ value, quoted });
77
- }
78
- return out;
79
- }
80
-
81
- function basename(value: string): string {
82
- return value.split(/[\\/]/).at(-1) ?? value;
83
- }
84
-
85
11
  function isWaiter(source: string, depth = 0): boolean {
86
12
  if (depth > 8) return false;
87
13
  const tokens = tokenize(source);
@@ -148,19 +74,6 @@ function isWaiter(source: string, depth = 0): boolean {
148
74
  }
149
75
 
150
76
  export function shellWaiterReason(toolName: unknown, toolInput: unknown): string | null {
151
- if (typeof toolName !== "string") return null;
152
- const name = toolName.toLowerCase().replace(/^functions\./, "");
153
- if (!["bash", "shell", "shell_command", "exec_command"].includes(name)) return null;
154
- let input = toolInput;
155
- if (typeof input === "string") {
156
- try {
157
- input = JSON.parse(input);
158
- } catch {
159
- return null;
160
- }
161
- }
162
- if (!input || typeof input !== "object") return null;
163
- const args = input as Record<string, unknown>;
164
- const command = args.command ?? args.cmd;
165
- return typeof command === "string" && isWaiter(command) ? REASON : null;
77
+ const command = shellCommandFromTool(toolName, toolInput);
78
+ return command !== null && isWaiter(command) ? REASON : null;
166
79
  }
@@ -38,6 +38,13 @@ export interface RotatingProcessOptions {
38
38
  env?: Readonly<Record<string, string | undefined>>;
39
39
  max_bytes?: number;
40
40
  backups?: number;
41
+ /**
42
+ * How to start the log wrapper, as an argv prefix that takes the JSON
43
+ * specification as its final argument and ends in `runProcessLogWorker`. The
44
+ * default runs this module's own file, which does not exist inside a
45
+ * single-file host bundle; such a host supplies a hidden task of its own.
46
+ */
47
+ worker?: { command: string; arguments: string[] };
41
48
  }
42
49
 
43
50
  const DEFAULT_PROCESS_LOG_BYTES = 5 * 1024 * 1024;
@@ -136,7 +143,14 @@ export function spawnRotatingProcess(options: RotatingProcessOptions): ChildProc
136
143
  command: options.command,
137
144
  arguments: options.arguments ?? [],
138
145
  });
139
- return spawn("bun", [fileURLToPath(import.meta.url), "--run", specification], {
146
+ // Run the wrapper with the Bun that is running this code: a host may carry a
147
+ // managed Bun that is not on PATH.
148
+ const bun = typeof process.versions.bun === "string" ? process.execPath : "bun";
149
+ const launcher = options.worker ?? {
150
+ command: bun,
151
+ arguments: [fileURLToPath(import.meta.url), "--run"],
152
+ };
153
+ return spawn(launcher.command, [...launcher.arguments, specification], {
140
154
  detached: true,
141
155
  stdio: "ignore",
142
156
  env: { ...(options.env ?? process.env) } as NodeJS.ProcessEnv,
@@ -162,7 +176,8 @@ export function runRotatingProcessSync(options: RotatingProcessOptions): number
162
176
  return result.status;
163
177
  }
164
178
 
165
- async function runProcessLogWorker(raw: string | undefined): Promise<void> {
179
+ /** The wrapper's body: run the specified command and rotate its output into the log. */
180
+ export async function runProcessLogWorker(raw: string | undefined): Promise<void> {
166
181
  const parsed = JSON.parse(raw ?? "null") as RotatingProcessOptions | null;
167
182
  if (!parsed || typeof parsed.command !== "string" || !Array.isArray(parsed.arguments)) {
168
183
  throw new Error("invalid process log worker specification");
@@ -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
+ }
@@ -12,6 +12,7 @@
12
12
  // available; stdout/stderr is captured into .cache/tunnel/gate.log by the
13
13
  // spawner.
14
14
 
15
+ import { allowlistMatches, compileAllowlist } from "./allowlist.ts";
15
16
  import { renderTunnelErrorPage } from "./error-page";
16
17
  import { applyUpstreamHeaders } from "./forward-headers";
17
18
  import { ALLOW_PATHS_ENV, isPathAllowed, parseAllowPathsEnv } from "./path-scope.ts";
@@ -27,12 +28,8 @@ function argvFlag(flag: string): string | undefined {
27
28
  return i !== -1 ? process.argv[i + 1] : undefined;
28
29
  }
29
30
 
30
- const ALLOW = new Set(
31
- (process.env.HARNERY_TUNNEL_ALLOW ?? "")
32
- .split(",")
33
- .map((s) => s.trim())
34
- .filter(Boolean),
35
- );
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(","));
36
33
  const TARGET = process.env.HARNERY_TUNNEL_TARGET ?? "127.0.0.1:8001";
37
34
  const VHOST = process.env.HARNERY_TUNNEL_VHOST ?? "localhost";
38
35
  const PORT = Number(process.env.HARNERY_TUNNEL_PORT ?? argvFlag("--port") ?? "9001");
@@ -81,7 +78,7 @@ const server = Bun.serve<WsData, never>({
81
78
  const url = new URL(req.url);
82
79
  if (ACCESS === "cloudflare-allowlist") {
83
80
  const ip = req.headers.get("cf-connecting-ip") ?? "";
84
- if (!ALLOW.has(ip)) {
81
+ if (!allowlistMatches(ALLOW, ip)) {
85
82
  const details = requestDetails(req, url);
86
83
  // Log denials so operators can whitelist a phone/laptop that just
87
84
  // hit 403 without asking the human to dig up their public IP.
@@ -213,4 +210,15 @@ const server = Bun.serve<WsData, never>({
213
210
  console.log(`harn-tunnel-gate :${server.port} -> ${UPSTREAM_HTTP} (Host: ${VHOST})`); // lint-ok-emission: detached worker, see file note above
214
211
  console.log(`access: ${ACCESS}`); // lint-ok-emission: detached worker, see file note above
215
212
  console.log(`paths: ${ALLOW_PATHS.join(", ") || "(empty, every path refused)"}`); // lint-ok-emission: detached worker, see file note above
216
- console.log(`allow: ${[...ALLOW].join(", ") || "(empty, not used outside allowlist mode)"}`); // 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
+ }