@reclaimprotocol/agent 0.1.22 → 0.1.24

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 (163) hide show
  1. package/README.md +55 -20
  2. package/lib/authoring/backend.d.ts +13 -10
  3. package/lib/authoring/tools.js +106 -9
  4. package/lib/cdp/browser-proxy.d.ts +78 -0
  5. package/lib/cdp/browser-proxy.js +186 -0
  6. package/lib/cdp/capture-engine.js +8 -7
  7. package/lib/cdp/client.d.ts +10 -0
  8. package/lib/cdp/geo.d.ts +10 -0
  9. package/lib/cdp/geo.js +36 -0
  10. package/lib/cdp/index.d.ts +1 -0
  11. package/lib/cdp/index.js +1 -0
  12. package/lib/live/cloudflared.d.ts +15 -0
  13. package/lib/live/cloudflared.js +268 -0
  14. package/lib/live/page.d.ts +20 -0
  15. package/lib/live/page.js +134 -0
  16. package/lib/live/tunnel.d.ts +23 -0
  17. package/lib/live/tunnel.js +120 -0
  18. package/lib/live/viewer.d.ts +28 -0
  19. package/lib/live/viewer.js +232 -0
  20. package/lib/mcp/api/operations.gen.js +34 -26
  21. package/lib/mcp/api/to-zod.d.ts +1 -1
  22. package/lib/mcp/api/to-zod.js +1 -1
  23. package/lib/mcp/api/tools.js +1 -1
  24. package/lib/mcp/instructions.d.ts +15 -2
  25. package/lib/mcp/instructions.js +101 -38
  26. package/lib/mcp/start.js +4 -3
  27. package/lib/mcp/tools/agent/analyze.js +5 -1
  28. package/lib/mcp/tools/agent/attach.d.ts +8 -1
  29. package/lib/mcp/tools/agent/attach.js +166 -22
  30. package/lib/mcp/tools/agent/build.d.ts +13 -8
  31. package/lib/mcp/tools/agent/build.js +22 -11
  32. package/lib/mcp/tools/agent/capture.js +5 -1
  33. package/lib/mcp/tools/agent/eval.js +3 -1
  34. package/lib/mcp/tools/agent/find.js +6 -5
  35. package/lib/mcp/tools/agent/how-it-works.d.ts +15 -7
  36. package/lib/mcp/tools/agent/how-it-works.js +57 -17
  37. package/lib/mcp/tools/agent/live-view.d.ts +21 -0
  38. package/lib/mcp/tools/agent/live-view.js +153 -0
  39. package/lib/mcp/tools/agent/pod-proof.d.ts +8 -0
  40. package/lib/mcp/tools/agent/pod-proof.js +64 -0
  41. package/lib/mcp/tools/agent/propose.js +29 -3
  42. package/lib/mcp/tools/agent/proxy.d.ts +3 -0
  43. package/lib/mcp/tools/agent/proxy.js +199 -0
  44. package/lib/mcp/tools/agent/publish.js +49 -77
  45. package/lib/mcp/tools/agent/session.d.ts +2 -1
  46. package/lib/mcp/tools/agent/session.js +26 -7
  47. package/lib/mcp/tools/agent/shared.js +17 -8
  48. package/lib/mcp/tools/authenticate/authenticate.d.ts +11 -0
  49. package/lib/mcp/tools/authenticate/authenticate.js +143 -121
  50. package/lib/mcp/tools/authenticate/builder-access.d.ts +8 -3
  51. package/lib/mcp/tools/authenticate/builder-access.js +8 -3
  52. package/lib/mcp/tools/mode/mode.d.ts +1 -1
  53. package/lib/mcp/tools/mode/mode.js +26 -7
  54. package/lib/old/client.d.ts +9 -0
  55. package/lib/old/client.js +19 -1
  56. package/lib/old/instructions.d.ts +9 -1
  57. package/lib/old/instructions.js +4 -6
  58. package/lib/old/login-cdp.d.ts +2 -2
  59. package/lib/old/login-cdp.js +46 -6
  60. package/lib/old/to-register.d.ts +20 -8
  61. package/lib/old/to-register.js +7 -1
  62. package/lib/old/tools/authenticate.js +9 -1
  63. package/lib/old/tools/get-provider-info.js +6 -5
  64. package/lib/old/tools/issue-app-credentials.js +3 -2
  65. package/lib/old/tools/me-providers.js +3 -1
  66. package/lib/old/tools/publish.d.ts +1 -1
  67. package/lib/old/tools/publish.js +132 -129
  68. package/lib/old/tools/update-provider-metadata.d.ts +1 -1
  69. package/lib/old/tools/update-provider-metadata.js +1 -1
  70. package/lib/old/tools/verify-sdk-setup.js +1 -1
  71. package/lib/proof/attestor.d.ts +3 -3
  72. package/lib/proof/debug-response-dump.js +4 -4
  73. package/lib/proof/index.d.ts +1 -0
  74. package/lib/proof/index.js +1 -0
  75. package/lib/proof/page-replay.d.ts +36 -0
  76. package/lib/proof/page-replay.js +76 -0
  77. package/lib/proof/pod-prover.d.ts +47 -0
  78. package/lib/proof/pod-prover.js +155 -0
  79. package/lib/proof/replay.d.ts +28 -0
  80. package/lib/proof/replay.js +39 -18
  81. package/lib/provider/dom-xpath.js +11 -9
  82. package/lib/provider/draft.d.ts +13 -8
  83. package/lib/provider/draft.js +47 -13
  84. package/lib/provider/injection-doc.d.ts +23 -1
  85. package/lib/provider/injection-doc.js +34 -21
  86. package/lib/provider/match-redaction-warning.d.ts +2 -2
  87. package/lib/provider/match-redaction-warning.js +3 -3
  88. package/lib/provider/matcher.js +122 -12
  89. package/lib/provider/secrets.d.ts +3 -3
  90. package/lib/provider/secrets.js +3 -3
  91. package/lib/provider/to-version.d.ts +12 -9
  92. package/lib/provider/to-version.js +16 -4
  93. package/lib/tools/registry.d.ts +5 -5
  94. package/lib/tools/registry.js +5 -5
  95. package/package.json +4 -3
  96. package/samples/demo-server/README.md +7 -6
  97. package/skill/SKILL.builder.md +356 -189
  98. package/skill/SKILL.common.md +314 -79
  99. package/skill/SKILL.old.md +340 -155
  100. package/skill/builder-mode.md +58 -17
  101. package/skill/hash-validation.md +170 -0
  102. package/skill/interception.md +235 -0
  103. package/skill/js-sdk-integration.md +13 -7
  104. package/skill/old-mode.md +53 -12
  105. package/skill/user-script.md +61 -0
  106. package/src/authoring/backend.ts +13 -10
  107. package/src/authoring/tools.ts +128 -9
  108. package/src/cdp/capture-engine.ts +8 -7
  109. package/src/cdp/client.ts +8 -0
  110. package/src/cdp/geo.ts +52 -0
  111. package/src/cdp/index.ts +1 -0
  112. package/src/consts.ts +1 -0
  113. package/src/live/cloudflared.ts +348 -0
  114. package/src/live/page.ts +145 -0
  115. package/src/live/tunnel.ts +157 -0
  116. package/src/live/viewer.ts +293 -0
  117. package/src/mcp/api/operations.gen.ts +34 -26
  118. package/src/mcp/api/to-zod.ts +1 -1
  119. package/src/mcp/api/tools.ts +1 -1
  120. package/src/mcp/instructions.ts +121 -48
  121. package/src/mcp/start.ts +4 -3
  122. package/src/mcp/tools/agent/analyze.ts +5 -1
  123. package/src/mcp/tools/agent/attach.ts +194 -22
  124. package/src/mcp/tools/agent/build.ts +26 -15
  125. package/src/mcp/tools/agent/capture.ts +5 -1
  126. package/src/mcp/tools/agent/eval.ts +4 -1
  127. package/src/mcp/tools/agent/find.ts +6 -5
  128. package/src/mcp/tools/agent/how-it-works.ts +62 -21
  129. package/src/mcp/tools/agent/live-view.ts +198 -0
  130. package/src/mcp/tools/agent/pod-proof.ts +90 -0
  131. package/src/mcp/tools/agent/propose.ts +31 -3
  132. package/src/mcp/tools/agent/publish.ts +54 -78
  133. package/src/mcp/tools/agent/session.ts +26 -5
  134. package/src/mcp/tools/agent/shared.ts +19 -8
  135. package/src/mcp/tools/authenticate/authenticate.ts +167 -165
  136. package/src/mcp/tools/authenticate/builder-access.ts +8 -3
  137. package/src/mcp/tools/mode/mode.ts +28 -7
  138. package/src/old/client.ts +30 -1
  139. package/src/old/instructions.ts +4 -10
  140. package/src/old/login-cdp.ts +50 -6
  141. package/src/old/to-register.ts +28 -8
  142. package/src/old/tools/authenticate.ts +9 -1
  143. package/src/old/tools/get-provider-info.ts +6 -5
  144. package/src/old/tools/issue-app-credentials.ts +3 -2
  145. package/src/old/tools/me-providers.ts +3 -1
  146. package/src/old/tools/publish.ts +140 -130
  147. package/src/old/tools/update-provider-metadata.ts +1 -1
  148. package/src/old/tools/verify-sdk-setup.ts +1 -1
  149. package/src/proof/attestor.ts +3 -3
  150. package/src/proof/debug-response-dump.ts +4 -4
  151. package/src/proof/index.ts +8 -0
  152. package/src/proof/page-replay.ts +131 -0
  153. package/src/proof/pod-prover.ts +231 -0
  154. package/src/proof/replay.ts +60 -19
  155. package/src/provider/dom-xpath.ts +11 -9
  156. package/src/provider/draft.ts +56 -13
  157. package/src/provider/injection-doc.ts +37 -24
  158. package/src/provider/match-redaction-warning.ts +3 -3
  159. package/src/provider/matcher.ts +151 -10
  160. package/src/provider/secrets.ts +3 -3
  161. package/src/provider/to-version.ts +30 -13
  162. package/src/tools/registry.ts +5 -5
  163. package/skill/injection-api.md +0 -335
@@ -0,0 +1,348 @@
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 {
34
+ chmod,
35
+ mkdir,
36
+ rename,
37
+ rm,
38
+ stat,
39
+ writeFile
40
+ } from 'node:fs/promises'
41
+ import { arch, platform } from 'node:os'
42
+ import { join } from 'node:path'
43
+ import { promisify } from 'node:util'
44
+ import { gunzipSync } from 'node:zlib'
45
+ import { LOGGER } from '../logger.ts'
46
+ import { reclaimHomeDirPath } from '../paths.ts'
47
+
48
+ const execFileAsync = promisify(execFile)
49
+
50
+ /** Release metadata: the tag to pin to, and the checksum table in its notes. */
51
+ const LATEST_RELEASE_API =
52
+ 'https://api.github.com/repos/cloudflare/cloudflared/releases/latest'
53
+ /** Asset downloads, keyed by the tag we read the checksums from. */
54
+ function releaseDownloadUrl(tag: string, asset: string): string {
55
+ return 'https://github.com/cloudflare/cloudflared/releases/download'
56
+ + `/${tag}/${asset}`
57
+ }
58
+
59
+ /** Give up on a slow or stalled download rather than hanging the tool. */
60
+ const DOWNLOAD_TIMEOUT_MS = 180_000
61
+
62
+ export interface CloudflaredBinary {
63
+ /** Path to run. */
64
+ path: string
65
+ /** How it was found — surfaced so the caller can tell the developer when a
66
+ * download just happened on their machine. */
67
+ source: 'env' | 'path' | 'cached' | 'downloaded'
68
+ }
69
+
70
+ /**
71
+ * The release asset for this machine, or `undefined` when Cloudflare ships no
72
+ * build for it. macOS assets are gzipped tarballs; everything else is the bare
73
+ * executable.
74
+ */
75
+ function assetFor(
76
+ os: string,
77
+ cpu: string,
78
+ ): { name: string, tarball: boolean } | undefined {
79
+ if(os === 'darwin') {
80
+ const suffix = cpu === 'arm64' ? 'arm64' : 'amd64'
81
+ return { name: `cloudflared-darwin-${suffix}.tgz`, tarball: true }
82
+ }
83
+
84
+ if(os === 'linux') {
85
+ const map: Record<string, string> = {
86
+ x64: 'amd64',
87
+ arm64: 'arm64',
88
+ arm: 'arm',
89
+ ia32: '386',
90
+ }
91
+ const suffix = map[cpu]
92
+ return suffix
93
+ ? { name: `cloudflared-linux-${suffix}`, tarball: false }
94
+ : undefined
95
+ }
96
+
97
+ if(os === 'win32') {
98
+ const suffix = cpu === 'ia32' ? '386' : 'amd64'
99
+ return { name: `cloudflared-windows-${suffix}.exe`, tarball: false }
100
+ }
101
+
102
+ return undefined
103
+ }
104
+
105
+ /** Our install location. Kept beside the other `~/.reclaim` caches. */
106
+ function cachedBinaryPath(): string {
107
+ const name = platform() === 'win32' ? 'cloudflared.exe' : 'cloudflared'
108
+ return join(reclaimHomeDirPath(), 'bin', name)
109
+ }
110
+
111
+ /** Whether `command` runs. Used both for a PATH probe and to smoke-test a
112
+ * freshly downloaded binary before we hand it back. */
113
+ async function runsOk(command: string): Promise<boolean> {
114
+ try {
115
+ await execFileAsync(command, ['--version'], { timeout: 15_000 })
116
+ return true
117
+ } catch{
118
+ return false
119
+ }
120
+ }
121
+
122
+ async function exists(path: string): Promise<boolean> {
123
+ try {
124
+ await stat(path)
125
+ return true
126
+ } catch{
127
+ return false
128
+ }
129
+ }
130
+
131
+ /**
132
+ * Resolve a runnable cloudflared, downloading one only if `autoInstall` allows
133
+ * it and nothing else turned up. Throws with an actionable message when this
134
+ * platform has no build, or the download fails.
135
+ */
136
+ export async function resolveCloudflared(
137
+ { autoInstall = true }: { autoInstall?: boolean } = {},
138
+ ): Promise<CloudflaredBinary> {
139
+ const override = process.env.RECLAIM_CLOUDFLARED_PATH?.trim()
140
+ if(override) {
141
+ if(!await runsOk(override)) {
142
+ throw new Error(
143
+ `RECLAIM_CLOUDFLARED_PATH is set to "${override}", but that did not `
144
+ + 'run. Point it at a working cloudflared binary, or unset it to let '
145
+ + 'the agent find one.',
146
+ )
147
+ }
148
+
149
+ return { path: override, source: 'env' }
150
+ }
151
+
152
+ if(await runsOk('cloudflared')) {
153
+ return { path: 'cloudflared', source: 'path' }
154
+ }
155
+
156
+ const cached = cachedBinaryPath()
157
+ if(await exists(cached) && await runsOk(cached)) {
158
+ return { path: cached, source: 'cached' }
159
+ }
160
+
161
+ if(!autoInstall) {
162
+ throw new Error(
163
+ 'cloudflared is not installed. Install it (macOS: `brew install '
164
+ + 'cloudflared`; other platforms: https://developers.cloudflare.com/'
165
+ + 'cloudflare-one/connections/connect-networks/downloads/), or allow '
166
+ + 'the agent to fetch it.',
167
+ )
168
+ }
169
+
170
+ await install(cached)
171
+ return { path: cached, source: 'downloaded' }
172
+ }
173
+
174
+ /** `cloudflared-linux-amd64: <64 hex>` lines inside the notes' fenced block. */
175
+ const CHECKSUM_LINE = /^\s*(\S+):\s*([a-f0-9]{64})\s*$/gim
176
+
177
+ /**
178
+ * The current release's tag and its published SHA-256 table.
179
+ *
180
+ * Both come from one response on purpose: pinning the download to this tag is
181
+ * what makes the digest meaningful.
182
+ */
183
+ async function fetchRelease(): Promise<{
184
+ tag: string
185
+ checksums: Map<string, string>
186
+ }> {
187
+ const res = await fetch(LATEST_RELEASE_API, {
188
+ headers: {
189
+ accept: 'application/vnd.github+json',
190
+ 'user-agent': '@reclaimprotocol/agent',
191
+ },
192
+ signal: AbortSignal.timeout(30_000),
193
+ })
194
+ if(!res.ok) {
195
+ throw new Error(
196
+ `Could not read cloudflared release metadata: ${res.status} `
197
+ + `${res.statusText}. Needed to verify the download's checksum. `
198
+ + 'Install cloudflared yourself, or set RECLAIM_CLOUDFLARED_PATH.',
199
+ )
200
+ }
201
+
202
+ const release = await res.json() as { tag_name?: string, body?: string }
203
+ const tag = release.tag_name
204
+ if(!tag) {
205
+ throw new Error('cloudflared release metadata carried no tag.')
206
+ }
207
+
208
+ const checksums = new Map<string, string>()
209
+ for(const match of (release.body ?? '').matchAll(CHECKSUM_LINE)) {
210
+ checksums.set(match[1], match[2].toLowerCase())
211
+ }
212
+
213
+ return { tag, checksums }
214
+ }
215
+
216
+ /** Download the release asset for this machine to `target`, verified. */
217
+ async function install(target: string): Promise<void> {
218
+ const asset = assetFor(platform(), arch())
219
+ if(!asset) {
220
+ throw new Error(
221
+ `Cloudflare publishes no cloudflared build for ${platform()}/${arch()}. `
222
+ + 'Install it another way and set RECLAIM_CLOUDFLARED_PATH, or use '
223
+ + '`attach_browser` in builder mode, whose Popcorn browser returns a '
224
+ + 'hosted liveViewUrl and needs no tunnel.',
225
+ )
226
+ }
227
+
228
+ // Read the checksum table BEFORE downloading, and pin the download to the
229
+ // tag it came from.
230
+ const { tag, checksums } = await fetchRelease()
231
+ const expected = checksums.get(asset.name)
232
+ if(!expected) {
233
+ throw new Error(
234
+ `cloudflared release ${tag} publishes no SHA-256 for ${asset.name}, so `
235
+ + 'the download cannot be verified. Refusing to install an unverified '
236
+ + 'binary. Install cloudflared yourself, or set '
237
+ + 'RECLAIM_CLOUDFLARED_PATH.',
238
+ )
239
+ }
240
+
241
+ const url = releaseDownloadUrl(tag, asset.name)
242
+ LOGGER.info({ url, target, tag }, 'cloudflared: downloading (first use)')
243
+ const res = await fetch(url, {
244
+ redirect: 'follow',
245
+ signal: AbortSignal.timeout(DOWNLOAD_TIMEOUT_MS),
246
+ })
247
+ if(!res.ok) {
248
+ throw new Error(
249
+ `Downloading cloudflared failed: ${res.status} ${res.statusText} `
250
+ + `from ${url}. Install it manually and retry, or set `
251
+ + 'RECLAIM_CLOUDFLARED_PATH.',
252
+ )
253
+ }
254
+
255
+ const downloaded = Buffer.from(await res.arrayBuffer())
256
+
257
+ // The macOS assets are tarballs, so unpack before hashing. Unpacked
258
+ // in-process rather than by shelling out to `tar`: that would add a
259
+ // dependency on something being on PATH, which is exactly the assumption
260
+ // this module exists to stop making.
261
+ //
262
+ // This ordering is not incidental. Cloudflare's table lists a digest for
263
+ // `cloudflared-darwin-arm64.tgz`, but that digest is of the BINARY INSIDE,
264
+ // not of the tarball (verified against a real release: the tarball hashes
265
+ // to something else entirely, and the binary self-reports the published
266
+ // value as its own checksum). The linux and windows entries, which ship a
267
+ // bare executable, do match the downloaded file. Hashing the payload we are
268
+ // about to write covers both, and is the stronger invariant anyway: what
269
+ // gets verified is what gets executed.
270
+ const payload = asset.tarball
271
+ ? readTarEntry(gunzipSync(downloaded), 'cloudflared')
272
+ : downloaded
273
+
274
+ const actual = createHash('sha256').update(payload).digest('hex')
275
+ if(actual !== expected) {
276
+ // Nothing is written to disk on a mismatch — not even a partial file.
277
+ throw new Error(
278
+ `cloudflared checksum mismatch for ${asset.name} (release ${tag}). `
279
+ + `Expected ${expected}, got ${actual}. The download was discarded. `
280
+ + 'Retry; if it persists, install cloudflared yourself and set '
281
+ + 'RECLAIM_CLOUDFLARED_PATH.',
282
+ )
283
+ }
284
+
285
+ LOGGER.info({ asset: asset.name, tag }, 'cloudflared: checksum verified')
286
+
287
+ // Write beside the target, then rename: a half-written or unverified
288
+ // binary is never left at a path a later run would trust.
289
+ await mkdir(join(target, '..'), { recursive: true })
290
+ const partial = `${target}.download`
291
+ await writeFile(partial, payload)
292
+ await rename(partial, target)
293
+
294
+ if(platform() !== 'win32') {
295
+ await chmod(target, 0o755)
296
+ }
297
+
298
+ if(!await runsOk(target)) {
299
+ await rm(target, { force: true })
300
+ throw new Error(
301
+ 'Downloaded cloudflared, but it did not run. Removed it. Install '
302
+ + 'cloudflared manually and retry.',
303
+ )
304
+ }
305
+
306
+ LOGGER.info({ target }, 'cloudflared: installed')
307
+ }
308
+
309
+ /** A tar header block is 512 bytes, and so is every data block. */
310
+ const TAR_BLOCK = 512
311
+
312
+ /**
313
+ * Pull one file out of an uncompressed tar archive.
314
+ *
315
+ * Only as much of the format as this needs: walk the 512-byte headers, read
316
+ * each entry's name and octal size, and return the payload of the first
317
+ * regular file whose basename matches. Cloudflare's macOS tarball holds a
318
+ * single binary, so there is nothing more to handle.
319
+ */
320
+ function readTarEntry(tar: Buffer, wanted: string): Buffer {
321
+ let offset = 0
322
+ while(offset + TAR_BLOCK <= tar.length) {
323
+ const header = tar.subarray(offset, offset + TAR_BLOCK)
324
+ const name = header.subarray(0, 100).toString('utf8').replace(/\0.*$/, '')
325
+ if(!name) {
326
+ break // two zero blocks mark the end of the archive
327
+ }
328
+
329
+ const size = parseInt(
330
+ header.subarray(124, 136).toString('utf8').replace(/\0.*$/, '').trim(),
331
+ 8,
332
+ ) || 0
333
+ const type = header.subarray(156, 157).toString('utf8')
334
+ const dataStart = offset + TAR_BLOCK
335
+ if((type === '0' || type === '\0') && name.split('/').pop() === wanted) {
336
+ return tar.subarray(dataStart, dataStart + size)
337
+ }
338
+
339
+ // Data is padded up to the next block boundary.
340
+ offset = dataStart + Math.ceil(size / TAR_BLOCK) * TAR_BLOCK
341
+ }
342
+
343
+ throw new Error(
344
+ `The cloudflared archive did not contain "${wanted}". Cloudflare may `
345
+ + 'have changed its release layout — install cloudflared manually and '
346
+ + 'set RECLAIM_CLOUDFLARED_PATH.',
347
+ )
348
+ }
@@ -0,0 +1,145 @@
1
+ /**
2
+ * The live-view page served to whoever opens the tunnel URL.
3
+ *
4
+ * Deliberately dependency-free and inline: it is delivered through a throwaway
5
+ * tunnel, so it cannot rely on a CDN, a bundler, or anything cached.
6
+ *
7
+ * Frames arrive as base64 JPEG over Server-Sent Events rather than a
8
+ * WebSocket. SSE is one plain GET, so it survives tunnels and proxies that
9
+ * mishandle upgrades, and it reconnects on its own. Input goes the other way
10
+ * as small POSTs.
11
+ */
12
+
13
+ /** Escape a value for embedding in a single-quoted JS string literal. */
14
+ function js(value: string): string {
15
+ return value
16
+ .replace(/\\/g, '\\\\')
17
+ .replace(/'/g, "\\'")
18
+ .replace(/</g, '\\x3c')
19
+ }
20
+
21
+ export interface PageOptions {
22
+ /** Path prefix that carries the access token, for example `/v/<token>`. */
23
+ base: string
24
+ /** Whether to wire up mouse and keyboard forwarding. */
25
+ interactive: boolean
26
+ /** Shown in the header so a viewer knows which tab they are watching. */
27
+ title: string
28
+ }
29
+
30
+ export function renderViewerPage(opts: PageOptions): string {
31
+ return `<!doctype html>
32
+ <html lang="en">
33
+ <head>
34
+ <meta charset="utf-8">
35
+ <meta name="viewport" content="width=device-width, initial-scale=1">
36
+ <meta name="robots" content="noindex, nofollow">
37
+ <title>Reclaim live view</title>
38
+ <style>
39
+ :root { color-scheme: dark; }
40
+ * { box-sizing: border-box; }
41
+ body { margin: 0; background: #0b0b0c; color: #e7e7ea; display: flex;
42
+ flex-direction: column; height: 100vh;
43
+ font: 14px/1.4 ui-sans-serif, system-ui, sans-serif; }
44
+ header { display: flex; align-items: center; gap: .75rem;
45
+ padding: .5rem .75rem; border-bottom: 1px solid #26262b; }
46
+ .dot { width: .5rem; height: .5rem; border-radius: 50%; background: #f5a524; }
47
+ .dot.live { background: #17c964; }
48
+ .title { color: #9a9aa4; overflow: hidden; text-overflow: ellipsis;
49
+ white-space: nowrap; }
50
+ .badge { margin-left: auto; font-size: 12px; padding: .15rem .4rem;
51
+ border: 1px solid #26262b; border-radius: .25rem; color: #9a9aa4; }
52
+ main { flex: 1; min-height: 0; display: grid; place-items: center;
53
+ padding: .75rem; }
54
+ img { max-width: 100%; max-height: 100%; display: block;
55
+ background: #fff; border-radius: .25rem; }
56
+ img.interactive { cursor: crosshair; }
57
+ .msg { color: #9a9aa4; }
58
+ </style>
59
+ </head>
60
+ <body>
61
+ <header>
62
+ <span class="dot" id="dot"></span>
63
+ <span class="title" id="title">${js(opts.title)}</span>
64
+ <span class="badge">${opts.interactive ? 'interactive' : 'view only'}</span>
65
+ </header>
66
+ <main><img id="screen" alt="Live view of the browser tab"><p class="msg"
67
+ id="msg">Connecting…</p></main>
68
+ <script>
69
+ (function () {
70
+ var BASE = '${js(opts.base)}';
71
+ var INTERACTIVE = ${opts.interactive ? 'true' : 'false'};
72
+ var screen = document.getElementById('screen');
73
+ var msg = document.getElementById('msg');
74
+ var dot = document.getElementById('dot');
75
+ var title = document.getElementById('title');
76
+
77
+ var es = new EventSource(BASE + '/stream');
78
+ es.addEventListener('frame', function (e) {
79
+ var payload = JSON.parse(e.data);
80
+ screen.src = 'data:image/jpeg;base64,' + payload.data;
81
+ if (payload.title) { title.textContent = payload.title; }
82
+ msg.style.display = 'none';
83
+ dot.className = 'dot live';
84
+ });
85
+ es.onerror = function () {
86
+ dot.className = 'dot';
87
+ msg.style.display = '';
88
+ msg.textContent = 'Reconnecting…';
89
+ };
90
+
91
+ if (!INTERACTIVE) { return; }
92
+ screen.className = 'interactive';
93
+
94
+ // The <img> is letterboxed by object-fit, so a click at some point in the
95
+ // element maps to page coordinates by the ratio of natural to rendered size.
96
+ function toPage(ev) {
97
+ var r = screen.getBoundingClientRect();
98
+ if (!screen.naturalWidth || !r.width) { return null; }
99
+ return {
100
+ x: Math.round((ev.clientX - r.left) * (screen.naturalWidth / r.width)),
101
+ y: Math.round((ev.clientY - r.top) * (screen.naturalHeight / r.height))
102
+ };
103
+ }
104
+
105
+ function post(body) {
106
+ return fetch(BASE + '/input', {
107
+ method: 'POST',
108
+ headers: { 'content-type': 'application/json' },
109
+ body: JSON.stringify(body)
110
+ }).catch(function () {});
111
+ }
112
+
113
+ screen.addEventListener('mousedown', function (ev) {
114
+ var p = toPage(ev); if (!p) { return; }
115
+ ev.preventDefault();
116
+ post({ kind: 'mouse', type: 'mousePressed', x: p.x, y: p.y,
117
+ button: 'left', clickCount: 1 });
118
+ });
119
+ screen.addEventListener('mouseup', function (ev) {
120
+ var p = toPage(ev); if (!p) { return; }
121
+ post({ kind: 'mouse', type: 'mouseReleased', x: p.x, y: p.y,
122
+ button: 'left', clickCount: 1 });
123
+ });
124
+ screen.addEventListener('wheel', function (ev) {
125
+ var p = toPage(ev); if (!p) { return; }
126
+ ev.preventDefault();
127
+ post({ kind: 'mouse', type: 'mouseWheel', x: p.x, y: p.y,
128
+ deltaX: ev.deltaX, deltaY: ev.deltaY });
129
+ }, { passive: false });
130
+
131
+ // Typing goes to the page, so the viewer never needs to focus anything.
132
+ window.addEventListener('keydown', function (ev) {
133
+ if (ev.metaKey || ev.ctrlKey) { return; }
134
+ ev.preventDefault();
135
+ post({ kind: 'key', type: 'keyDown', key: ev.key, code: ev.code });
136
+ });
137
+ window.addEventListener('keyup', function (ev) {
138
+ if (ev.metaKey || ev.ctrlKey) { return; }
139
+ post({ kind: 'key', type: 'keyUp', key: ev.key, code: ev.code });
140
+ });
141
+ })();
142
+ </script>
143
+ </body>
144
+ </html>`
145
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Public HTTPS front door for the local live-view server, via a `cloudflared`
3
+ * quick tunnel.
4
+ *
5
+ * A quick tunnel needs no Cloudflare account and no DNS: `cloudflared` dials
6
+ * out, Cloudflare hands back a throwaway `*.trycloudflare.com` hostname, and
7
+ * traffic arrives on the loopback port we pass in. That is the whole reason it
8
+ * is used here — the developer's machine keeps no inbound port open.
9
+ *
10
+ * The tunnel itself carries NO authorization. Anyone holding the hostname can
11
+ * reach the local server, so the server is the thing that must authenticate
12
+ * (see `viewer.ts`, which puts an unguessable token in every path).
13
+ */
14
+ import { spawn } from 'node:child_process'
15
+ import { LOGGER } from '../logger.ts'
16
+ import { type CloudflaredBinary, resolveCloudflared } from './cloudflared.ts'
17
+
18
+ /** How long to wait for cloudflared to report its hostname before giving up. */
19
+ const URL_TIMEOUT_MS = 30_000
20
+ /** After the hostname is printed, Cloudflare needs a moment before the edge
21
+ * routes to it — measured at ~3s. Poll until it answers so the caller never
22
+ * hands out a URL that errors, but don't fail the share if it's slow. */
23
+ const READY_TIMEOUT_MS = 20_000
24
+ const READY_POLL_MS = 1_000
25
+
26
+ /** `https://<something>.trycloudflare.com`, as printed on cloudflared's log
27
+ * stream. Anchored to the scheme so a hostname inside prose can't match. */
28
+ const QUICK_TUNNEL_URL = /https:\/\/[a-z0-9-]+\.trycloudflare\.com/i
29
+
30
+ export interface Tunnel {
31
+ /** The public HTTPS origin Cloudflare assigned. */
32
+ url: string
33
+ /** Whether the edge answered before {@link READY_TIMEOUT_MS} elapsed. False
34
+ * means the tunnel is probably still propagating rather than broken — tell
35
+ * the viewer to retry rather than treating the share as failed. */
36
+ ready: boolean
37
+ /** Terminate the tunnel. Safe to call more than once. */
38
+ stop: () => Promise<void>
39
+ /** Which cloudflared ran, and whether we had to fetch it. */
40
+ binary: CloudflaredBinary
41
+ }
42
+
43
+ /**
44
+ * Poll the public origin until Cloudflare's edge routes to it. ANY HTTP
45
+ * response counts, including a 404: the live-view server 404s unknown paths,
46
+ * so a status code at all proves the hop is live.
47
+ */
48
+ async function waitUntilRouted(url: string): Promise<boolean> {
49
+ const deadline = Date.now() + READY_TIMEOUT_MS
50
+ while(Date.now() < deadline) {
51
+ try {
52
+ await fetch(url, {
53
+ method: 'GET',
54
+ redirect: 'manual',
55
+ signal: AbortSignal.timeout(READY_POLL_MS * 4),
56
+ })
57
+ return true
58
+ } catch{
59
+ await new Promise((r) => setTimeout(r, READY_POLL_MS))
60
+ }
61
+ }
62
+
63
+ return false
64
+ }
65
+
66
+ /**
67
+ * Open a quick tunnel to `http://127.0.0.1:<port>` and resolve once
68
+ * Cloudflare has assigned a hostname.
69
+ *
70
+ * Rejects with an actionable message when `cloudflared` is not installed,
71
+ * exits early, or never reports a hostname.
72
+ */
73
+ export async function startTunnel(
74
+ port: number,
75
+ { autoInstall = true }: { autoInstall?: boolean } = {},
76
+ ): Promise<Tunnel> {
77
+ // Resolves an existing cloudflared, or fetches one on first use. Throws
78
+ // with an actionable message when neither is possible.
79
+ const binary = await resolveCloudflared({ autoInstall })
80
+ const child = spawn(binary.path, [
81
+ 'tunnel',
82
+ '--no-autoupdate',
83
+ '--url', `http://127.0.0.1:${port}`,
84
+ ], { stdio: ['ignore', 'pipe', 'pipe'] })
85
+
86
+ const stop = async() => {
87
+ if(!child.killed) {
88
+ child.kill('SIGTERM')
89
+ }
90
+ }
91
+
92
+ return new Promise<Tunnel>((resolve, reject) => {
93
+ const timer = setTimeout(() => {
94
+ void stop()
95
+ reject(new Error(
96
+ 'cloudflared did not report a tunnel hostname within '
97
+ + `${URL_TIMEOUT_MS / 1000}s. Check network egress to Cloudflare, `
98
+ + 'or run `cloudflared tunnel --url http://127.0.0.1:'
99
+ + `${port}` + '` by hand to see its output.',
100
+ ))
101
+ }, URL_TIMEOUT_MS)
102
+
103
+ let settled = false
104
+ const finish = (fn: () => void) => {
105
+ if(settled) {
106
+ return
107
+ }
108
+
109
+ settled = true
110
+ clearTimeout(timer)
111
+ fn()
112
+ }
113
+
114
+ // cloudflared logs the assigned hostname to stderr, not stdout. Watch
115
+ // both so a future version that switches streams still works.
116
+ const onChunk = (chunk: Buffer) => {
117
+ const text = chunk.toString()
118
+ const match = QUICK_TUNNEL_URL.exec(text)
119
+ if(match) {
120
+ const url = match[0]
121
+ finish(() => {
122
+ void waitUntilRouted(url).then((ready) => {
123
+ if(!ready) {
124
+ LOGGER.warn({ url }, 'tunnel not routed yet; returning anyway')
125
+ }
126
+
127
+ resolve({ url, ready, stop, binary })
128
+ })
129
+ })
130
+ }
131
+ }
132
+
133
+ child.stdout?.on('data', onChunk)
134
+ child.stderr?.on('data', onChunk)
135
+
136
+ child.on('error', (err: NodeJS.ErrnoException) => {
137
+ // `resolveCloudflared` already proved the binary runs, so an ENOENT
138
+ // here means it vanished between resolving and spawning.
139
+ finish(() => reject(
140
+ err.code === 'ENOENT'
141
+ ? new Error(
142
+ `cloudflared disappeared from ${binary.path} before it could `
143
+ + 'start. Retry — the agent will fetch it again if needed.',
144
+ )
145
+ : err,
146
+ ))
147
+ })
148
+
149
+ child.on('exit', (code) => {
150
+ LOGGER.debug({ code }, 'cloudflared exited')
151
+ finish(() => reject(new Error(
152
+ `cloudflared exited with code ${code} before reporting a `
153
+ + 'hostname.',
154
+ )))
155
+ })
156
+ })
157
+ }