@reclaimprotocol/agent 0.1.23 → 0.1.25

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 (149) hide show
  1. package/README.md +56 -20
  2. package/lib/authoring/backend.d.ts +5 -4
  3. package/lib/authoring/tools.js +30 -30
  4. package/lib/cdp/capture-engine.js +8 -7
  5. package/lib/cdp/claims.d.ts +21 -0
  6. package/lib/cdp/claims.js +129 -0
  7. package/lib/cdp/container.d.ts +85 -0
  8. package/lib/cdp/container.js +481 -0
  9. package/lib/cdp/geo.d.ts +10 -0
  10. package/lib/cdp/geo.js +36 -0
  11. package/lib/cdp/index.d.ts +1 -0
  12. package/lib/cdp/index.js +1 -0
  13. package/lib/live/cloudflared.d.ts +15 -0
  14. package/lib/live/cloudflared.js +268 -0
  15. package/lib/live/tunnel.d.ts +26 -0
  16. package/lib/live/tunnel.js +160 -0
  17. package/lib/mcp/api/operations.gen.js +34 -26
  18. package/lib/mcp/api/to-zod.d.ts +1 -1
  19. package/lib/mcp/api/to-zod.js +1 -1
  20. package/lib/mcp/api/tools.js +1 -1
  21. package/lib/mcp/instructions.d.ts +15 -2
  22. package/lib/mcp/instructions.js +102 -38
  23. package/lib/mcp/start.js +62 -6
  24. package/lib/mcp/tools/agent/analyze.js +5 -1
  25. package/lib/mcp/tools/agent/attach.d.ts +29 -2
  26. package/lib/mcp/tools/agent/attach.js +310 -24
  27. package/lib/mcp/tools/agent/build.d.ts +18 -8
  28. package/lib/mcp/tools/agent/build.js +30 -12
  29. package/lib/mcp/tools/agent/capture.js +5 -1
  30. package/lib/mcp/tools/agent/eval.js +3 -1
  31. package/lib/mcp/tools/agent/find.js +6 -5
  32. package/lib/mcp/tools/agent/how-it-works.d.ts +15 -7
  33. package/lib/mcp/tools/agent/how-it-works.js +57 -17
  34. package/lib/mcp/tools/agent/index.d.ts +1 -2
  35. package/lib/mcp/tools/agent/index.js +1 -1
  36. package/lib/mcp/tools/agent/live-view.d.ts +17 -0
  37. package/lib/mcp/tools/agent/live-view.js +146 -0
  38. package/lib/mcp/tools/agent/pod-proof.d.ts +8 -0
  39. package/lib/mcp/tools/agent/pod-proof.js +64 -0
  40. package/lib/mcp/tools/agent/propose.js +4 -2
  41. package/lib/mcp/tools/agent/publish.js +47 -77
  42. package/lib/mcp/tools/agent/session.d.ts +16 -1
  43. package/lib/mcp/tools/agent/session.js +32 -7
  44. package/lib/mcp/tools/authenticate/authenticate.js +26 -13
  45. package/lib/mcp/tools/mode/mode.d.ts +1 -1
  46. package/lib/mcp/tools/mode/mode.js +10 -22
  47. package/lib/old/client.d.ts +1 -1
  48. package/lib/old/client.js +1 -1
  49. package/lib/old/instructions.d.ts +9 -1
  50. package/lib/old/instructions.js +4 -6
  51. package/lib/old/login-cdp.d.ts +2 -2
  52. package/lib/old/login-cdp.js +46 -6
  53. package/lib/old/to-register.d.ts +3 -2
  54. package/lib/old/to-register.js +1 -1
  55. package/lib/old/tools/authenticate.js +9 -1
  56. package/lib/old/tools/get-provider-info.js +6 -5
  57. package/lib/old/tools/issue-app-credentials.js +3 -2
  58. package/lib/old/tools/publish.d.ts +1 -1
  59. package/lib/old/tools/publish.js +90 -131
  60. package/lib/old/tools/update-provider-metadata.d.ts +1 -1
  61. package/lib/old/tools/update-provider-metadata.js +1 -1
  62. package/lib/old/tools/verify-sdk-setup.js +1 -1
  63. package/lib/proof/attestor.d.ts +3 -3
  64. package/lib/proof/debug-response-dump.js +4 -4
  65. package/lib/proof/index.d.ts +1 -0
  66. package/lib/proof/index.js +1 -0
  67. package/lib/proof/page-replay.d.ts +1 -1
  68. package/lib/proof/page-replay.js +1 -1
  69. package/lib/proof/pod-prover.d.ts +47 -0
  70. package/lib/proof/pod-prover.js +155 -0
  71. package/lib/provider/dom-xpath.js +11 -9
  72. package/lib/provider/draft.d.ts +10 -7
  73. package/lib/provider/draft.js +11 -9
  74. package/lib/provider/injection-doc.d.ts +23 -1
  75. package/lib/provider/injection-doc.js +34 -21
  76. package/lib/provider/match-redaction-warning.d.ts +2 -2
  77. package/lib/provider/match-redaction-warning.js +3 -3
  78. package/lib/provider/matcher.js +13 -12
  79. package/lib/provider/secrets.d.ts +3 -3
  80. package/lib/provider/secrets.js +3 -3
  81. package/lib/provider/to-version.d.ts +7 -6
  82. package/lib/provider/to-version.js +3 -3
  83. package/lib/tools/registry.d.ts +5 -5
  84. package/lib/tools/registry.js +5 -5
  85. package/package.json +3 -3
  86. package/samples/demo-server/README.md +7 -6
  87. package/skill/SKILL.builder.md +356 -189
  88. package/skill/SKILL.common.md +400 -97
  89. package/skill/SKILL.old.md +340 -155
  90. package/skill/builder-mode.md +60 -17
  91. package/skill/hash-validation.md +170 -0
  92. package/skill/interception.md +236 -0
  93. package/skill/js-sdk-integration.md +13 -7
  94. package/skill/old-mode.md +62 -21
  95. package/skill/user-script.md +61 -0
  96. package/src/authoring/backend.ts +5 -4
  97. package/src/authoring/tools.ts +31 -30
  98. package/src/cdp/capture-engine.ts +8 -7
  99. package/src/cdp/claims.ts +153 -0
  100. package/src/cdp/container.ts +593 -0
  101. package/src/cdp/geo.ts +52 -0
  102. package/src/cdp/index.ts +1 -0
  103. package/src/consts.ts +1 -0
  104. package/src/live/cloudflared.ts +348 -0
  105. package/src/live/tunnel.ts +208 -0
  106. package/src/mcp/api/operations.gen.ts +34 -26
  107. package/src/mcp/api/to-zod.ts +1 -1
  108. package/src/mcp/api/tools.ts +1 -1
  109. package/src/mcp/instructions.ts +122 -48
  110. package/src/mcp/start.ts +69 -5
  111. package/src/mcp/tools/agent/analyze.ts +5 -1
  112. package/src/mcp/tools/agent/attach.ts +367 -26
  113. package/src/mcp/tools/agent/build.ts +35 -16
  114. package/src/mcp/tools/agent/capture.ts +5 -1
  115. package/src/mcp/tools/agent/eval.ts +4 -1
  116. package/src/mcp/tools/agent/find.ts +6 -5
  117. package/src/mcp/tools/agent/how-it-works.ts +62 -21
  118. package/src/mcp/tools/agent/index.ts +6 -2
  119. package/src/mcp/tools/agent/live-view.ts +182 -0
  120. package/src/mcp/tools/agent/pod-proof.ts +90 -0
  121. package/src/mcp/tools/agent/propose.ts +4 -2
  122. package/src/mcp/tools/agent/publish.ts +52 -77
  123. package/src/mcp/tools/agent/session.ts +33 -6
  124. package/src/mcp/tools/authenticate/authenticate.ts +28 -13
  125. package/src/mcp/tools/mode/mode.ts +10 -22
  126. package/src/old/client.ts +2 -2
  127. package/src/old/instructions.ts +4 -10
  128. package/src/old/login-cdp.ts +50 -6
  129. package/src/old/to-register.ts +3 -2
  130. package/src/old/tools/authenticate.ts +9 -1
  131. package/src/old/tools/get-provider-info.ts +6 -5
  132. package/src/old/tools/issue-app-credentials.ts +3 -2
  133. package/src/old/tools/publish.ts +95 -131
  134. package/src/old/tools/update-provider-metadata.ts +1 -1
  135. package/src/old/tools/verify-sdk-setup.ts +1 -1
  136. package/src/proof/attestor.ts +3 -3
  137. package/src/proof/debug-response-dump.ts +4 -4
  138. package/src/proof/index.ts +8 -0
  139. package/src/proof/page-replay.ts +1 -1
  140. package/src/proof/pod-prover.ts +231 -0
  141. package/src/provider/dom-xpath.ts +11 -9
  142. package/src/provider/draft.ts +13 -10
  143. package/src/provider/injection-doc.ts +37 -24
  144. package/src/provider/match-redaction-warning.ts +3 -3
  145. package/src/provider/matcher.ts +13 -12
  146. package/src/provider/secrets.ts +3 -3
  147. package/src/provider/to-version.ts +11 -9
  148. package/src/tools/registry.ts +5 -5
  149. package/skill/injection-api.md +0 -364
@@ -0,0 +1,268 @@
1
+ /**
2
+ * Finding — and if necessary fetching — the `cloudflared` binary the live view
3
+ * tunnels through.
4
+ *
5
+ * Resolution order, first hit wins:
6
+ * 1. `RECLAIM_CLOUDFLARED_PATH`, for an air-gapped box or a corporate mirror.
7
+ * 2. `cloudflared` on PATH — someone who installed it with a package manager
8
+ * keeps their own copy, updated their way.
9
+ * 3. `~/.reclaim/bin/cloudflared`, ours from a previous run.
10
+ * 4. Download it from Cloudflare's GitHub releases into `~/.reclaim/bin`.
11
+ *
12
+ * Step 4 happens on FIRST USE, never at install time. The npm `cloudflared`
13
+ * package would have done this for us, but its postinstall pulls a ~38 MB
14
+ * binary on every `npm install` of this package — a cost paid by everyone who
15
+ * never shares a live view. `run_proof`'s ZK circuits are deferred for exactly
16
+ * the same reason.
17
+ *
18
+ * Every download is SHA-256 verified. Cloudflare publishes a checksum table in
19
+ * the release notes (not as a release asset), so we read the release metadata
20
+ * first, take the digest for our asset, and refuse to install anything that
21
+ * doesn't match. The release TAG from that same response is used to build the
22
+ * download URL, so the checksum and the bytes always come from one release —
23
+ * `/latest/download/` could otherwise hand us a newer build than the table we
24
+ * just read.
25
+ *
26
+ * Verification is not optional: this writes an executable to the developer's
27
+ * machine. If the checksum can't be established, we fail rather than install.
28
+ * The escape hatch is to install cloudflared yourself — step 2 then wins and
29
+ * nothing is downloaded.
30
+ */
31
+ import { execFile } from 'node:child_process';
32
+ import { createHash } from 'node:crypto';
33
+ import { chmod, mkdir, rename, rm, stat, writeFile } from 'node:fs/promises';
34
+ import { arch, platform } from 'node:os';
35
+ import { join } from 'node:path';
36
+ import { promisify } from 'node:util';
37
+ import { gunzipSync } from 'node:zlib';
38
+ import { LOGGER } from "../logger.js";
39
+ import { reclaimHomeDirPath } from "../paths.js";
40
+ const execFileAsync = promisify(execFile);
41
+ /** Release metadata: the tag to pin to, and the checksum table in its notes. */
42
+ const LATEST_RELEASE_API = 'https://api.github.com/repos/cloudflare/cloudflared/releases/latest';
43
+ /** Asset downloads, keyed by the tag we read the checksums from. */
44
+ function releaseDownloadUrl(tag, asset) {
45
+ return 'https://github.com/cloudflare/cloudflared/releases/download'
46
+ + `/${tag}/${asset}`;
47
+ }
48
+ /** Give up on a slow or stalled download rather than hanging the tool. */
49
+ const DOWNLOAD_TIMEOUT_MS = 180000;
50
+ /**
51
+ * The release asset for this machine, or `undefined` when Cloudflare ships no
52
+ * build for it. macOS assets are gzipped tarballs; everything else is the bare
53
+ * executable.
54
+ */
55
+ function assetFor(os, cpu) {
56
+ if (os === 'darwin') {
57
+ const suffix = cpu === 'arm64' ? 'arm64' : 'amd64';
58
+ return { name: `cloudflared-darwin-${suffix}.tgz`, tarball: true };
59
+ }
60
+ if (os === 'linux') {
61
+ const map = {
62
+ x64: 'amd64',
63
+ arm64: 'arm64',
64
+ arm: 'arm',
65
+ ia32: '386',
66
+ };
67
+ const suffix = map[cpu];
68
+ return suffix
69
+ ? { name: `cloudflared-linux-${suffix}`, tarball: false }
70
+ : undefined;
71
+ }
72
+ if (os === 'win32') {
73
+ const suffix = cpu === 'ia32' ? '386' : 'amd64';
74
+ return { name: `cloudflared-windows-${suffix}.exe`, tarball: false };
75
+ }
76
+ return undefined;
77
+ }
78
+ /** Our install location. Kept beside the other `~/.reclaim` caches. */
79
+ function cachedBinaryPath() {
80
+ const name = platform() === 'win32' ? 'cloudflared.exe' : 'cloudflared';
81
+ return join(reclaimHomeDirPath(), 'bin', name);
82
+ }
83
+ /** Whether `command` runs. Used both for a PATH probe and to smoke-test a
84
+ * freshly downloaded binary before we hand it back. */
85
+ async function runsOk(command) {
86
+ try {
87
+ await execFileAsync(command, ['--version'], { timeout: 15000 });
88
+ return true;
89
+ }
90
+ catch {
91
+ return false;
92
+ }
93
+ }
94
+ async function exists(path) {
95
+ try {
96
+ await stat(path);
97
+ return true;
98
+ }
99
+ catch {
100
+ return false;
101
+ }
102
+ }
103
+ /**
104
+ * Resolve a runnable cloudflared, downloading one only if `autoInstall` allows
105
+ * it and nothing else turned up. Throws with an actionable message when this
106
+ * platform has no build, or the download fails.
107
+ */
108
+ export async function resolveCloudflared({ autoInstall = true } = {}) {
109
+ const override = process.env.RECLAIM_CLOUDFLARED_PATH?.trim();
110
+ if (override) {
111
+ if (!await runsOk(override)) {
112
+ throw new Error(`RECLAIM_CLOUDFLARED_PATH is set to "${override}", but that did not `
113
+ + 'run. Point it at a working cloudflared binary, or unset it to let '
114
+ + 'the agent find one.');
115
+ }
116
+ return { path: override, source: 'env' };
117
+ }
118
+ if (await runsOk('cloudflared')) {
119
+ return { path: 'cloudflared', source: 'path' };
120
+ }
121
+ const cached = cachedBinaryPath();
122
+ if (await exists(cached) && await runsOk(cached)) {
123
+ return { path: cached, source: 'cached' };
124
+ }
125
+ if (!autoInstall) {
126
+ throw new Error('cloudflared is not installed. Install it (macOS: `brew install '
127
+ + 'cloudflared`; other platforms: https://developers.cloudflare.com/'
128
+ + 'cloudflare-one/connections/connect-networks/downloads/), or allow '
129
+ + 'the agent to fetch it.');
130
+ }
131
+ await install(cached);
132
+ return { path: cached, source: 'downloaded' };
133
+ }
134
+ /** `cloudflared-linux-amd64: <64 hex>` lines inside the notes' fenced block. */
135
+ const CHECKSUM_LINE = /^\s*(\S+):\s*([a-f0-9]{64})\s*$/gim;
136
+ /**
137
+ * The current release's tag and its published SHA-256 table.
138
+ *
139
+ * Both come from one response on purpose: pinning the download to this tag is
140
+ * what makes the digest meaningful.
141
+ */
142
+ async function fetchRelease() {
143
+ const res = await fetch(LATEST_RELEASE_API, {
144
+ headers: {
145
+ accept: 'application/vnd.github+json',
146
+ 'user-agent': '@reclaimprotocol/agent',
147
+ },
148
+ signal: AbortSignal.timeout(30000),
149
+ });
150
+ if (!res.ok) {
151
+ throw new Error(`Could not read cloudflared release metadata: ${res.status} `
152
+ + `${res.statusText}. Needed to verify the download's checksum. `
153
+ + 'Install cloudflared yourself, or set RECLAIM_CLOUDFLARED_PATH.');
154
+ }
155
+ const release = await res.json();
156
+ const tag = release.tag_name;
157
+ if (!tag) {
158
+ throw new Error('cloudflared release metadata carried no tag.');
159
+ }
160
+ const checksums = new Map();
161
+ for (const match of (release.body ?? '').matchAll(CHECKSUM_LINE)) {
162
+ checksums.set(match[1], match[2].toLowerCase());
163
+ }
164
+ return { tag, checksums };
165
+ }
166
+ /** Download the release asset for this machine to `target`, verified. */
167
+ async function install(target) {
168
+ const asset = assetFor(platform(), arch());
169
+ if (!asset) {
170
+ throw new Error(`Cloudflare publishes no cloudflared build for ${platform()}/${arch()}. `
171
+ + 'Install it another way and set RECLAIM_CLOUDFLARED_PATH, or use '
172
+ + '`attach_browser` in builder mode, whose Popcorn browser returns a '
173
+ + 'hosted liveViewUrl and needs no tunnel.');
174
+ }
175
+ // Read the checksum table BEFORE downloading, and pin the download to the
176
+ // tag it came from.
177
+ const { tag, checksums } = await fetchRelease();
178
+ const expected = checksums.get(asset.name);
179
+ if (!expected) {
180
+ throw new Error(`cloudflared release ${tag} publishes no SHA-256 for ${asset.name}, so `
181
+ + 'the download cannot be verified. Refusing to install an unverified '
182
+ + 'binary. Install cloudflared yourself, or set '
183
+ + 'RECLAIM_CLOUDFLARED_PATH.');
184
+ }
185
+ const url = releaseDownloadUrl(tag, asset.name);
186
+ LOGGER.info({ url, target, tag }, 'cloudflared: downloading (first use)');
187
+ const res = await fetch(url, {
188
+ redirect: 'follow',
189
+ signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),
190
+ });
191
+ if (!res.ok) {
192
+ throw new Error(`Downloading cloudflared failed: ${res.status} ${res.statusText} `
193
+ + `from ${url}. Install it manually and retry, or set `
194
+ + 'RECLAIM_CLOUDFLARED_PATH.');
195
+ }
196
+ const downloaded = Buffer.from(await res.arrayBuffer());
197
+ // The macOS assets are tarballs, so unpack before hashing. Unpacked
198
+ // in-process rather than by shelling out to `tar`: that would add a
199
+ // dependency on something being on PATH, which is exactly the assumption
200
+ // this module exists to stop making.
201
+ //
202
+ // This ordering is not incidental. Cloudflare's table lists a digest for
203
+ // `cloudflared-darwin-arm64.tgz`, but that digest is of the BINARY INSIDE,
204
+ // not of the tarball (verified against a real release: the tarball hashes
205
+ // to something else entirely, and the binary self-reports the published
206
+ // value as its own checksum). The linux and windows entries, which ship a
207
+ // bare executable, do match the downloaded file. Hashing the payload we are
208
+ // about to write covers both, and is the stronger invariant anyway: what
209
+ // gets verified is what gets executed.
210
+ const payload = asset.tarball
211
+ ? readTarEntry(gunzipSync(downloaded), 'cloudflared')
212
+ : downloaded;
213
+ const actual = createHash('sha256').update(payload).digest('hex');
214
+ if (actual !== expected) {
215
+ // Nothing is written to disk on a mismatch — not even a partial file.
216
+ throw new Error(`cloudflared checksum mismatch for ${asset.name} (release ${tag}). `
217
+ + `Expected ${expected}, got ${actual}. The download was discarded. `
218
+ + 'Retry; if it persists, install cloudflared yourself and set '
219
+ + 'RECLAIM_CLOUDFLARED_PATH.');
220
+ }
221
+ LOGGER.info({ asset: asset.name, tag }, 'cloudflared: checksum verified');
222
+ // Write beside the target, then rename: a half-written or unverified
223
+ // binary is never left at a path a later run would trust.
224
+ await mkdir(join(target, '..'), { recursive: true });
225
+ const partial = `${target}.download`;
226
+ await writeFile(partial, payload);
227
+ await rename(partial, target);
228
+ if (platform() !== 'win32') {
229
+ await chmod(target, 0o755);
230
+ }
231
+ if (!await runsOk(target)) {
232
+ await rm(target, { force: true });
233
+ throw new Error('Downloaded cloudflared, but it did not run. Removed it. Install '
234
+ + 'cloudflared manually and retry.');
235
+ }
236
+ LOGGER.info({ target }, 'cloudflared: installed');
237
+ }
238
+ /** A tar header block is 512 bytes, and so is every data block. */
239
+ const TAR_BLOCK = 512;
240
+ /**
241
+ * Pull one file out of an uncompressed tar archive.
242
+ *
243
+ * Only as much of the format as this needs: walk the 512-byte headers, read
244
+ * each entry's name and octal size, and return the payload of the first
245
+ * regular file whose basename matches. Cloudflare's macOS tarball holds a
246
+ * single binary, so there is nothing more to handle.
247
+ */
248
+ function readTarEntry(tar, wanted) {
249
+ let offset = 0;
250
+ while (offset + TAR_BLOCK <= tar.length) {
251
+ const header = tar.subarray(offset, offset + TAR_BLOCK);
252
+ const name = header.subarray(0, 100).toString('utf8').replace(/\0.*$/, '');
253
+ if (!name) {
254
+ break; // two zero blocks mark the end of the archive
255
+ }
256
+ const size = parseInt(header.subarray(124, 136).toString('utf8').replace(/\0.*$/, '').trim(), 8) || 0;
257
+ const type = header.subarray(156, 157).toString('utf8');
258
+ const dataStart = offset + TAR_BLOCK;
259
+ if ((type === '0' || type === '\0') && name.split('/').pop() === wanted) {
260
+ return tar.subarray(dataStart, dataStart + size);
261
+ }
262
+ // Data is padded up to the next block boundary.
263
+ offset = dataStart + Math.ceil(size / TAR_BLOCK) * TAR_BLOCK;
264
+ }
265
+ throw new Error(`The cloudflared archive did not contain "${wanted}". Cloudflare may `
266
+ + 'have changed its release layout — install cloudflared manually and '
267
+ + 'set RECLAIM_CLOUDFLARED_PATH.');
268
+ }
@@ -0,0 +1,26 @@
1
+ import { type CloudflaredBinary } from './cloudflared.ts';
2
+ export interface Tunnel {
3
+ /** The public HTTPS origin Cloudflare assigned. */
4
+ url: string;
5
+ /** Whether the tunnel was carrying traffic before {@link READY_TIMEOUT_MS}
6
+ * elapsed. False means it may still be propagating rather than broken — say
7
+ * so rather than treating the share as failed. */
8
+ ready: boolean;
9
+ /** cloudflared's own last words, for when `ready` is false and someone has
10
+ * to work out why. Absent when the tunnel came up normally. */
11
+ diagnostics?: string;
12
+ /** Terminate the tunnel. Safe to call more than once. */
13
+ stop: () => Promise<void>;
14
+ /** Which cloudflared ran, and whether we had to fetch it. */
15
+ binary: CloudflaredBinary;
16
+ }
17
+ /**
18
+ * Open a quick tunnel to `http://127.0.0.1:<port>` and resolve once
19
+ * Cloudflare has assigned a hostname.
20
+ *
21
+ * Rejects with an actionable message when `cloudflared` is not installed,
22
+ * exits early, or never reports a hostname.
23
+ */
24
+ export declare function startTunnel(port: number, { autoInstall }?: {
25
+ autoInstall?: boolean;
26
+ }): Promise<Tunnel>;
@@ -0,0 +1,160 @@
1
+ /**
2
+ * Public HTTPS front door for a local port, via a `cloudflared` quick tunnel.
3
+ *
4
+ * A quick tunnel needs no Cloudflare account and no DNS: `cloudflared` dials
5
+ * out, Cloudflare hands back a throwaway `*.trycloudflare.com` hostname, and
6
+ * traffic arrives on the loopback port we pass in. That is the whole reason it
7
+ * is used here — the developer's machine keeps no inbound port open.
8
+ *
9
+ * **The hostname IS the secret, and it is the only one.** The tunnel carries no
10
+ * authorization of its own, and the browser runtime's viewer behind it has no
11
+ * login either — so whoever learns the URL has the browser. Cloudflare's
12
+ * hostnames are randomly generated, which is what makes that tolerable for a
13
+ * short, deliberate hand-off, and `stop_browser_view` is how it ends.
14
+ *
15
+ * That is weaker than what this file used to front. The agent's own screencast
16
+ * viewer added a 24-byte token to every path, so the hostname alone was not
17
+ * enough; the container's viewer has no equivalent. Callers must say plainly
18
+ * what the URL grants, and it must never front the container's CDP port, which
19
+ * is unauthenticated total control of the browser.
20
+ */
21
+ import { spawn } from 'node:child_process';
22
+ import { LOGGER } from "../logger.js";
23
+ import { resolveCloudflared } from "./cloudflared.js";
24
+ /** How long to wait for cloudflared to report its hostname before giving up. */
25
+ const URL_TIMEOUT_MS = 30000;
26
+ /** After the hostname is printed, Cloudflare needs a moment before the edge
27
+ * routes to it — measured at ~3s. Wait for it so the caller never hands out a
28
+ * URL that errors, but don't fail the share if it's slow. */
29
+ const READY_TIMEOUT_MS = 20000;
30
+ const READY_POLL_MS = 1000;
31
+ /** `https://<something>.trycloudflare.com`, as printed on cloudflared's log
32
+ * stream. Anchored to the scheme so a hostname inside prose can't match. */
33
+ const QUICK_TUNNEL_URL = /https:\/\/[a-z0-9-]+\.trycloudflare\.com/i;
34
+ /**
35
+ * cloudflared says this once per edge connection it establishes, and until it
36
+ * does, the hostname resolves but routes nowhere.
37
+ *
38
+ * This is the signal to trust, because it is LOCAL. Asking whether we can fetch
39
+ * the public URL ourselves conflates two questions — is the tunnel up, and does
40
+ * this machine have egress to Cloudflare's edge — and reports "not ready" when
41
+ * only the second fails. Observed: a tunnel printed its hostname and registered
42
+ * nothing for 12s, which is indistinguishable from a blocked fetch unless you
43
+ * read cloudflared's own account of it.
44
+ */
45
+ const REGISTERED = /Registered tunnel connection|connIndex=/i;
46
+ /** Tail of cloudflared's log kept for error messages. */
47
+ const LOG_TAIL_BYTES = 4096;
48
+ /**
49
+ * Wait until the tunnel is actually carrying traffic.
50
+ *
51
+ * Two independent signals, either of which is proof:
52
+ * - cloudflared reported an edge registration (see {@link REGISTERED}). Local,
53
+ * so it works regardless of this machine's own egress.
54
+ * - the public origin answered. ANY HTTP response counts, including a 404:
55
+ * the live-view server 404s unknown paths, so a status code at all proves
56
+ * the hop is live. Kept as a second opinion in case a cloudflared release
57
+ * rewords its log.
58
+ */
59
+ async function waitUntilRouted(url, isRegistered) {
60
+ const deadline = Date.now() + READY_TIMEOUT_MS;
61
+ while (Date.now() < deadline) {
62
+ if (isRegistered()) {
63
+ return true;
64
+ }
65
+ try {
66
+ await fetch(url, {
67
+ method: 'GET',
68
+ redirect: 'manual',
69
+ signal: AbortSignal.timeout(READY_POLL_MS * 2),
70
+ });
71
+ return true;
72
+ }
73
+ catch {
74
+ await new Promise((r) => setTimeout(r, READY_POLL_MS));
75
+ }
76
+ }
77
+ return isRegistered();
78
+ }
79
+ /**
80
+ * Open a quick tunnel to `http://127.0.0.1:<port>` and resolve once
81
+ * Cloudflare has assigned a hostname.
82
+ *
83
+ * Rejects with an actionable message when `cloudflared` is not installed,
84
+ * exits early, or never reports a hostname.
85
+ */
86
+ export async function startTunnel(port, { autoInstall = true } = {}) {
87
+ // Resolves an existing cloudflared, or fetches one on first use. Throws
88
+ // with an actionable message when neither is possible.
89
+ const binary = await resolveCloudflared({ autoInstall });
90
+ const child = spawn(binary.path, [
91
+ 'tunnel',
92
+ '--no-autoupdate',
93
+ '--url', `http://127.0.0.1:${port}`,
94
+ ], { stdio: ['ignore', 'pipe', 'pipe'] });
95
+ const stop = async () => {
96
+ if (!child.killed) {
97
+ child.kill('SIGTERM');
98
+ }
99
+ };
100
+ return new Promise((resolve, reject) => {
101
+ const timer = setTimeout(() => {
102
+ void stop();
103
+ reject(new Error('cloudflared did not report a tunnel hostname within '
104
+ + `${URL_TIMEOUT_MS / 1000}s. Check network egress to Cloudflare, `
105
+ + 'or run `cloudflared tunnel --url http://127.0.0.1:'
106
+ + `${port}` + '` by hand to see its output.'));
107
+ }, URL_TIMEOUT_MS);
108
+ let registered = false;
109
+ let tail = '';
110
+ let settled = false;
111
+ const finish = (fn) => {
112
+ if (settled) {
113
+ return;
114
+ }
115
+ settled = true;
116
+ clearTimeout(timer);
117
+ fn();
118
+ };
119
+ // cloudflared logs the assigned hostname to stderr, not stdout. Watch
120
+ // both so a future version that switches streams still works.
121
+ const onChunk = (chunk) => {
122
+ const text = chunk.toString();
123
+ // Keep watching after the hostname: registration lands a beat later, and
124
+ // on a bad run it never lands at all, which is the case worth reporting.
125
+ tail = (tail + text).slice(-LOG_TAIL_BYTES);
126
+ if (REGISTERED.test(text)) {
127
+ registered = true;
128
+ }
129
+ const match = QUICK_TUNNEL_URL.exec(text);
130
+ if (match) {
131
+ const url = match[0];
132
+ finish(() => {
133
+ void waitUntilRouted(url, () => registered).then((ready) => {
134
+ if (ready) {
135
+ resolve({ url, ready, stop, binary });
136
+ return;
137
+ }
138
+ LOGGER.warn({ url, tail }, 'tunnel never registered with an edge; returning anyway');
139
+ resolve({ url, ready, stop, binary, diagnostics: tail });
140
+ });
141
+ });
142
+ }
143
+ };
144
+ child.stdout?.on('data', onChunk);
145
+ child.stderr?.on('data', onChunk);
146
+ child.on('error', (err) => {
147
+ // `resolveCloudflared` already proved the binary runs, so an ENOENT
148
+ // here means it vanished between resolving and spawning.
149
+ finish(() => reject(err.code === 'ENOENT'
150
+ ? new Error(`cloudflared disappeared from ${binary.path} before it could `
151
+ + 'start. Retry — the agent will fetch it again if needed.')
152
+ : err));
153
+ });
154
+ child.on('exit', (code) => {
155
+ LOGGER.debug({ code }, 'cloudflared exited');
156
+ finish(() => reject(new Error(`cloudflared exited with code ${code} before reporting a `
157
+ + 'hostname.')));
158
+ });
159
+ });
160
+ }