recovery-probe 1.0.0 → 1.0.1

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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,14 @@ All notable changes to Recovery Probe are documented here. The project follows [
4
4
 
5
5
  Version 0.2.0 is the first npm release. Earlier 0.1.x revisions were repository-only prototypes.
6
6
 
7
+ ## 1.0.1 (2026-10-28)
8
+
9
+ - Reject browser-origin WebSocket connections and untrusted Host headers on the Android CDP bridge before opening an upstream connection. Validate the network proxy control API's Host header to block DNS rebinding.
10
+ - Bound complete inbound CDP WebSocket messages, including continuation frames, and close oversized messages with code 1009.
11
+ - Suppress MCP tool responses after cancellation and emit `structuredContent` only for object results.
12
+ - Match network host names with or without a final DNS dot. Document wildcard apex behavior, unrestricted local CONNECT tunneling, and the `webContents.send` scope of IPC push counting.
13
+
14
+
7
15
  ## 1.0.0 (2026-10-27)
8
16
 
9
17
  The first release with an explicit 1.x compatibility commitment. It removes the old command spellings and brings in everything since 0.6.0: the 0.7.0 and 0.8.0 previews below. The README defines the supported interfaces and experimental exceptions, and explains that failed checks can save unredacted screen-text quotes of up to 200 characters.
@@ -1,4 +1,6 @@
1
- import type { Server } from 'node:http';
1
+ import type { IncomingMessage, Server } from 'node:http';
2
+ /** Reject DNS aliases and ambiguous authorities before exposing local controls. */
3
+ export declare function hasLoopbackHost(request: IncomingMessage): boolean;
2
4
  /** Listens on 127.0.0.1 and returns the port; port 0 picks a free one. */
3
5
  export declare function listenOnLoopback(server: Server, port: number): Promise<number>;
4
6
  /** Closes the server and the connections it still holds. */
@@ -1,3 +1,11 @@
1
+ /** Reject DNS aliases and ambiguous authorities before exposing local controls. */
2
+ export function hasLoopbackHost(request) {
3
+ const hosts = request.headersDistinct.host;
4
+ if (hosts?.length !== 1 || !request.socket.localPort)
5
+ return false;
6
+ const port = request.socket.localPort;
7
+ return hosts[0] === `127.0.0.1:${port}` || hosts[0] === `localhost:${port}`;
8
+ }
1
9
  /** Listens on 127.0.0.1 and returns the port; port 0 picks a free one. */
2
10
  export async function listenOnLoopback(server, port) {
3
11
  await new Promise((resolve, reject) => {
@@ -1,5 +1,5 @@
1
1
  import { createServer, } from 'node:http';
2
- import { closeServer, listenOnLoopback } from '../../core/server.mjs';
2
+ import { closeServer, hasLoopbackHost, listenOnLoopback, } from '../../core/server.mjs';
3
3
  import { BRIDGE_ID_BASE, TargetFilter } from './filter.mjs';
4
4
  import { acceptWebSocket } from './websocket.mjs';
5
5
  /** A page with nothing loaded, as Android keeps for a WebView that has no window yet. */
@@ -30,6 +30,10 @@ export async function startCdpBridge({ upstream, hide = isBlankPage, port = 0, }
30
30
  };
31
31
  }
32
32
  async function answer(context, request, response) {
33
+ if (!hasLoopbackHost(request)) {
34
+ response.writeHead(403).end('Forbidden');
35
+ return;
36
+ }
33
37
  try {
34
38
  // Clients ask for both /json/version and /json/version/.
35
39
  const path = new URL(request.url ?? '/', 'http://bridge').pathname.replace(/\/$/, '');
@@ -64,6 +68,11 @@ async function visibleTargets(context) {
64
68
  }
65
69
  /** Connects one client to the device's browser endpoint, through a target filter. */
66
70
  function bridgeClient(context, peers, request, socket) {
71
+ // Native CDP clients send no Origin. Even an empty or null browser origin is denied.
72
+ if (!hasLoopbackHost(request) || request.headers.origin !== undefined) {
73
+ socket.end('HTTP/1.1 403 Forbidden\r\nConnection: close\r\n\r\n');
74
+ return;
75
+ }
67
76
  if (new URL(request.url ?? '/', 'http://bridge').pathname !==
68
77
  '/devtools/browser') {
69
78
  socket.end('HTTP/1.1 404 Not Found\r\n\r\n');
@@ -6,3 +6,9 @@ export interface WebSocketPeer {
6
6
  }
7
7
  /** Accepts a WebSocket upgrade (RFC 6455) and delivers its text messages. */
8
8
  export declare function acceptWebSocket(request: IncomingMessage, socket: Duplex, onMessage: (text: string) => void, onClose: () => void): WebSocketPeer;
9
+ export declare class ServerWebSocket implements WebSocketPeer {
10
+ #private;
11
+ constructor(socket: Duplex, onMessage: (text: string) => void, onClose: () => void, maxMessage?: number);
12
+ readonly send: (text: string) => void;
13
+ readonly close: (code?: number) => void;
14
+ }
@@ -27,13 +27,15 @@ function payloadLength(buffered) {
27
27
  return { length, offset: 2 };
28
28
  }
29
29
  /** The first whole frame and its size in bytes, or undefined until it has all arrived. */
30
- function readFrame(buffered) {
30
+ function readFrame(buffered, remaining) {
31
31
  if (buffered.length < 2)
32
32
  return undefined;
33
33
  const header = payloadLength(buffered);
34
34
  if (!header)
35
35
  return undefined;
36
- if (header.length > MAX_MESSAGE)
36
+ const opcode = buffered[0] & 0x0f;
37
+ const limit = opcode < 0x8 ? remaining : 125;
38
+ if (header.length > limit)
37
39
  return 'too-large';
38
40
  const masked = (buffered[1] & 0x80) !== 0;
39
41
  const start = header.offset + (masked ? 4 : 0);
@@ -57,22 +59,26 @@ export function acceptWebSocket(request, socket, onMessage, onClose) {
57
59
  `Sec-WebSocket-Accept: ${accept}\r\n\r\n`);
58
60
  return new ServerWebSocket(socket, onMessage, onClose);
59
61
  }
60
- class ServerWebSocket {
62
+ export class ServerWebSocket {
61
63
  #socket;
62
64
  #onMessage;
63
65
  #onClose;
66
+ #maxMessage;
64
67
  #closed = false;
65
68
  #buffered = Buffer.alloc(0);
66
69
  #message = [];
67
- constructor(socket, onMessage, onClose) {
70
+ #messageBytes = 0;
71
+ constructor(socket, onMessage, onClose, maxMessage = MAX_MESSAGE) {
68
72
  this.#socket = socket;
69
73
  this.#onMessage = onMessage;
70
74
  this.#onClose = onClose;
75
+ this.#maxMessage = maxMessage;
71
76
  socket.on('data', (chunk) => this.#receive(chunk));
72
77
  socket.on('close', () => {
73
78
  if (this.#closed)
74
79
  return;
75
80
  this.#closed = true;
81
+ this.#clear();
76
82
  this.#onClose();
77
83
  });
78
84
  socket.on('error', () => socket.destroy());
@@ -81,11 +87,14 @@ class ServerWebSocket {
81
87
  if (!this.#closed)
82
88
  this.#frame(0x1, Buffer.from(text));
83
89
  };
84
- close = () => {
90
+ close = (code = 1000) => {
85
91
  if (this.#closed)
86
92
  return;
87
93
  this.#closed = true;
88
- this.#frame(0x8, Buffer.from([0x03, 0xe8])); // 1000: normal closure
94
+ const payload = Buffer.alloc(2);
95
+ payload.writeUInt16BE(code);
96
+ this.#frame(0x8, payload);
97
+ this.#clear();
89
98
  this.#socket.end();
90
99
  this.#onClose();
91
100
  };
@@ -93,27 +102,37 @@ class ServerWebSocket {
93
102
  this.#socket.write(Buffer.concat([frameHeader(opcode, payload.length), payload]));
94
103
  }
95
104
  #receive(chunk) {
105
+ if (this.#closed)
106
+ return;
96
107
  this.#buffered = Buffer.concat([this.#buffered, chunk]);
97
- for (;;) {
98
- const read = readFrame(this.#buffered);
108
+ while (!this.#closed) {
109
+ const read = readFrame(this.#buffered, this.#maxMessage - this.#messageBytes);
99
110
  if (read === undefined)
100
111
  return;
101
112
  if (read === 'too-large')
102
- return this.close();
113
+ return this.close(1009);
103
114
  this.#buffered = this.#buffered.subarray(read.size);
104
115
  if (read.frame.opcode === 0x8)
105
116
  return this.close();
106
117
  this.#handle(read.frame);
107
118
  }
108
119
  }
120
+ #clear() {
121
+ this.#buffered = Buffer.alloc(0);
122
+ this.#message = [];
123
+ this.#messageBytes = 0;
124
+ }
109
125
  #handle({ fin, opcode, payload }) {
110
126
  if (opcode === 0x9)
111
127
  this.#frame(0xa, payload);
112
128
  else if (opcode === 0x1 || opcode === 0x2 || opcode === 0x0) {
113
- this.#message.push(payload);
129
+ if (payload.length)
130
+ this.#message.push(payload);
131
+ this.#messageBytes += payload.length;
114
132
  if (fin) {
115
133
  const text = Buffer.concat(this.#message).toString('utf8');
116
134
  this.#message = [];
135
+ this.#messageBytes = 0;
117
136
  this.#onMessage(text);
118
137
  }
119
138
  }
@@ -121,13 +121,23 @@ class McpServer {
121
121
  this.#running.set(id, controller);
122
122
  try {
123
123
  const result = await tool.run((params.arguments ?? {}), { signal: controller.signal });
124
+ if (controller.signal.aborted)
125
+ return undefined;
124
126
  return reply(id, {
125
- content: [{ type: 'text', text: JSON.stringify(result, null, 2) }],
126
- structuredContent: result,
127
+ content: [
128
+ { type: 'text', text: JSON.stringify(result, null, 2) ?? 'null' },
129
+ ],
130
+ ...(result !== null &&
131
+ typeof result === 'object' &&
132
+ !Array.isArray(result)
133
+ ? { structuredContent: result }
134
+ : {}),
127
135
  isError: false,
128
136
  });
129
137
  }
130
138
  catch (error) {
139
+ if (controller.signal.aborted)
140
+ return undefined;
131
141
  // A tool failure is a result the model can read and act on, not a protocol error.
132
142
  return reply(id, {
133
143
  content: [{ type: 'text', text: error.message }],
@@ -1,3 +1,4 @@
1
+ import { hasLoopbackHost } from '../../core/server.mjs';
1
2
  import { CONTROL_HEADER, CONTROL_PATH } from './client.mjs';
2
3
  const MAX_CONTROL_BODY = 64 * 1024;
3
4
  const failure = (message, status) => Object.assign(new Error(message), { status });
@@ -23,7 +24,12 @@ export function controlListener(handle) {
23
24
  response.writeHead(501).end('Recovery Probe tunnels HTTPS (CONNECT) only');
24
25
  return;
25
26
  }
26
- // A web page cannot send this header without a preflight, which is never answered.
27
+ // A same-origin page after DNS rebinding can send the control header too.
28
+ if (!hasLoopbackHost(request)) {
29
+ reply(403, { error: 'Use the proxy loopback host and port' });
30
+ return;
31
+ }
32
+ // Other web pages cannot send this header without a preflight, never answered here.
27
33
  if (request.headers[CONTROL_HEADER] !== 'network') {
28
34
  reply(403, { error: `Send the ${CONTROL_HEADER}: network header` });
29
35
  return;
@@ -3,7 +3,8 @@ import { ensure, isNonEmptyString } from '../../core/validate.mjs';
3
3
  const FAULTS = new Set(['refuse', 'reset', 'stall', 'delay']);
4
4
  const isWholeNumber = (value) => Number.isInteger(value) && value >= 0;
5
5
  export function hostMatches(pattern, host) {
6
- const name = host.toLowerCase();
6
+ const name = host.toLowerCase().replace(/\.$/, '');
7
+ pattern = pattern.toLowerCase().replace(/\.$/, '');
7
8
  if (pattern === '*')
8
9
  return true;
9
10
  if (pattern.startsWith('*.'))
package/docs/android.md CHANGED
@@ -34,6 +34,7 @@ npx recovery-probe android --package com.example.app --keep-awake
34
34
  - **Page reads:** fetch and XHR made by the WebView can be observed and faulted, as in a desktop page.
35
35
  - **Native reads are outside the page.** That covers requests made in Java or Kotlin code or an SDK, and calls through JavaScript bridges (`addJavascriptInterface`). Android apps do not read `HTTPS_PROXY`, so `recovery-probe net` does not reach them either.
36
36
  - **Blank WebViews are hidden.** Apps often keep WebViews with nothing loaded and no window yet, for example to warm one up. Android pauses those, and they never answer DevTools, so a client that attaches to every page waits forever. The URL serves the app's DevTools through a small bridge that leaves out pages that were blank when it first saw them, and lets them run if they were waiting for a debugger. Everything else passes through unchanged.
37
+ - **The bridge accepts native CDP clients only.** WebSocket requests carrying any `Origin` header are rejected. Discovery and WebSocket requests must use `127.0.0.1:<port>` or `localhost:<port>` for the bridge's actual port; DNS aliases are rejected. Inbound WebSocket messages, including fragmented messages, are limited to 256 MiB.
37
38
  - **Leftover forwards:** a forward is removed when the command stops. If the process is killed instead, remove it with `adb forward --remove tcp:PORT`.
38
39
 
39
40
  ## Keep the app drawing
package/docs/ipc.md CHANGED
@@ -42,7 +42,7 @@ Replace channel names with the exact existing read channels. Include the second
42
42
 
43
43
  Set `RECOVERY_PROBE_IPC=1` and `RECOVERY_PROBE_IPC_MODULE` to the absolute `.cjs` path from step 1 when starting the development app. No company application's production dependency needs changing. Do not expose controls through preload or contextBridge.
44
44
 
45
- For fault-free observation the hook also accepts optional `classify`, `pushChannels` and `classifyPush` options, which count calls per method label on shared channels and main-to-renderer pushes without storing arguments or payloads. See [Actions, tracked rows and delayed UI updates](observe.md#actions-tracked-rows-and-delayed-ui-updates).
45
+ For fault-free observation the hook also accepts optional `classify`, `pushChannels` and `classifyPush` options, which count calls per method label on shared channels and main-to-renderer pushes through `webContents.send` without storing arguments or payloads. Pushes through `mainFrame.send` or `postMessage` are not counted. See [Actions, tracked rows and delayed UI updates](observe.md#actions-tracked-rows-and-delayed-ui-updates).
46
46
 
47
47
  Registration is captured using the public `ipcMain.handle` API. Install before registration, once per process. Unaffected calls keep their original arguments, receiver and return value/Promise. The adapter observes completion without recording arguments, results or full errors. Calling `dispose()` disarms and restores the registration function; existing dispatchers become transparent. Restart the development app to remove them entirely.
48
48
 
package/docs/net.md CHANGED
@@ -7,6 +7,7 @@ Some apps make their own HTTPS requests outside the page: an SDK, the Electron m
7
7
  - **Whole connections only.** HTTPS stays end to end, so the proxy sees each connection's host and port and nothing else. It cannot return an HTTP status, change a response or fail one path on a host.
8
8
  - **The app has to use the proxy.** Clients that read `HTTPS_PROXY` include Rust's reqwest (by default), Go's `net/http`, curl and Python's requests. Node's built-in `fetch` reads it only with `NODE_USE_ENV_PROXY=1` (Node 24 or later). Chromium and Electron renderers ignore it; use the [page's HTTP faults](desktop.md) for those.
9
9
  - **Open connections are reused.** A rule that starts mid-session reaches a client only once it connects again. Set `dropOpen` to close the open connections to the host when the rule starts.
10
+ - **Local processes can tunnel to any host and port**, including other loopback services. The proxy binds only to `127.0.0.1`; it is a development proxy, not a destination allowlist or a security boundary between local processes.
10
11
  - It reports what it did to connections, not whether the app recovered. Check the screen with `observe`, discovery or your own assertions.
11
12
 
12
13
  Use it only with development or test targets you control.
@@ -53,7 +54,7 @@ Rule windows count from the first connection through the proxy, so they line up
53
54
  | `fromMs`, `untilMs` | When the rule applies |
54
55
  | `dropOpen` | Close the open connections to the host when the rule starts |
55
56
 
56
- The first rule that matches a connection applies.
57
+ The first rule that matches a connection applies. Host matching ignores case and a final DNS dot: `api.example.com.` matches `api.example.com`. `*.example.com` matches subdomains at any depth but never the apex `example.com`; add a separate rule for the apex if needed.
57
58
 
58
59
  ## Results
59
60
 
@@ -65,7 +66,7 @@ The first rule that matches a connection applies.
65
66
 
66
67
  Without `--rules`, `net` only passes connections through until something arms faults through its control. [`observe --network URL`](observe.md#network-steps) does that from network steps, so the screen is sampled while hosts are away and after they come back. Code can use the same control with `connectNetworkFaults(url)`.
67
68
 
68
- The control listens on the proxy's own loopback address and answers only requests with the `x-recovery-probe: network` header. A web page cannot send that header without a preflight, which the proxy never answers.
69
+ The control listens on the proxy's own loopback address and requires both the `x-recovery-probe: network` header and a `Host` of `127.0.0.1:<port>` or `localhost:<port>` using the proxy's actual port. The Host check rejects DNS rebinding; other web pages cannot send the control header without a preflight, which the proxy never answers.
69
70
 
70
71
  ## Use it from code
71
72
 
package/docs/observe.md CHANGED
@@ -145,6 +145,8 @@ When one IPC channel carries many kinds of calls (for example an SDK bridge), co
145
145
 
146
146
  Main-to-renderer pushes can be observed as data-change events. List their channels in the hook's `pushChannels`, optionally with `classifyPush(channel, args)`, and select them with `dataEvents`. The hook wraps `send` on the target window's WebContents only while an observation lease is active, counts sends and their times, never stores payloads, and removes the wrapper at the end of the lease. Fault plans never observe pushes.
147
147
 
148
+ These counts cover calls through `webContents.send` only. Calls through `webContents.mainFrame.send`, `postMessage`, other frames, or a reference to `send` saved before the wrapper was installed are not counted. A zero push count does not prove that no message was sent through those paths.
149
+
148
150
  ```js
149
151
  installIpcProbe(ipcMain, {
150
152
  enabled: true, channels: ['app:invoke'], sender: () => mainWindow?.webContents,
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "recovery-probe",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "type": "module",
5
5
  "description": "Test whether web and Electron desktop apps show the right data when a read fails, from the command line, your tests or an AI coding agent.",
6
6
  "license": "MIT",