Skip to content

armgit / rea

Public Imported from GitHub
0

Reverse engineer anything with agents, from app behavior down to native binaries.

fix(browser): preserve command failures and reject malformed replies

morluto6b92002597d3
diff --git a/docs/browser-observation.md b/docs/browser-observation.md
index 0d9bd8a35..e1ce74fd1 100644
--- a/docs/browser-observation.md
+++ b/docs/browser-observation.md
@@ -157,7 +157,7 @@ coverage. It reports excluded items and any values omitted or truncated by
validation; it does not drop records to meet an internal collection quota.
Disallowed-origin entries are filtered before retention.
-CDP discovery, WebSocket connection, and commands continue until the peer responds or the caller cancels the operation; REA has no internal byte, message-count, or pending-command quota for these exchanges. Without caller cancellation, a stalled peer can leave an operation waiting. On cancellation, REA closes only its own WebSocket, waiting up to one second before terminating it. Malformed unsolicited protocol events poison the connection so later commands fail closed.
+CDP discovery, WebSocket connection, and commands continue until the peer responds or the caller cancels the operation; REA has no internal byte, message-count, or pending-command quota for these exchanges. Without caller cancellation, a stalled peer can leave an operation waiting. On cancellation, REA closes only its own WebSocket, waiting up to one second before terminating it. Malformed unsolicited events and malformed replies to pending commands poison the connection so later commands fail closed. An optional method is reported unavailable only when the browser rejects it as unknown; other command rejections retain their reported failure.
Network and console coverage starts only after REA attaches and enables the relevant CDP domains. `prior_activity_available` is always `false`; absence from these arrays is not evidence that an event never occurred. If CDP reuses a request ID without supplying redirect metadata, REA retains the predecessor observation and marks network coverage incomplete.
diff --git a/src/browser/CdpConnection.ts b/src/browser/CdpConnection.ts
index cbf6bae44..c547e20ba 100644
--- a/src/browser/CdpConnection.ts
+++ b/src/browser/CdpConnection.ts
@@ -211,24 +211,43 @@ export class CdpConnection {
#receiveResponse(message: Record<string, unknown>, id: number): void {
const pending = this.#pending.get(id);
if (pending === undefined) return;
- this.#complete(id, pending);
- if ("error" in message) {
- const reported = message.error;
- pending.reject(
- new CdpCommandRejection(
- this.operation,
- pending.method,
- isRecord(reported) && typeof reported.code === "number"
- ? reported.code
- : null,
- isRecord(reported) && typeof reported.message === "string"
- ? reported.message
- : null,
- ),
- );
+ const hasResult = "result" in message;
+ const hasError = "error" in message;
+ if (
+ ("sessionId" in message && typeof message.sessionId !== "string") ||
+ hasResult === hasError
+ ) {
+ this.#failPending("protocol_error");
+ return;
+ }
+ if (hasResult) {
+ if (!isRecord(message.result)) {
+ this.#failPending("protocol_error");
+ return;
+ }
+ this.#complete(id, pending);
+ pending.resolve(message.result);
+ return;
+ }
+ const reported = message.error;
+ if (
+ !isRecord(reported) ||
+ typeof reported.code !== "number" ||
+ !Number.isSafeInteger(reported.code) ||
+ typeof reported.message !== "string"
+ ) {
+ this.#failPending("protocol_error");
return;
}
- pending.resolve("result" in message ? message.result : {});
+ this.#complete(id, pending);
+ pending.reject(
+ new CdpCommandRejection(
+ this.operation,
+ pending.method,
+ reported.code,
+ reported.message,
+ ),
+ );
}
#complete(id: number, pending: PendingCommand): void {
diff --git a/src/browser/CdpOptionalCommand.ts b/src/browser/CdpOptionalCommand.ts
index b02b2f78f..8939ce904 100644
--- a/src/browser/CdpOptionalCommand.ts
+++ b/src/browser/CdpOptionalCommand.ts
@@ -1,4 +1,4 @@
-import { BrowserObservationError } from "../domain/browserObservationError.js";
+import { CdpCommandRejection } from "./CdpCommandRejection.js";
import { CdpConnection } from "./CdpConnection.js";
/** Execute an optional CDP method while preserving transport and cancellation failures. */
@@ -20,10 +20,7 @@ export const optionalCdpCommand = async (
context.signal,
);
} catch (cause: unknown) {
- if (
- !(cause instanceof BrowserObservationError) ||
- cause.reason !== "protocol_error"
- )
+ if (!(cause instanceof CdpCommandRejection) || cause.code !== -32_601)
throw cause;
limitations.push(`${method} was unavailable from this browser target.`);
return undefined;
diff --git a/tests/boundary/browser/cdpBrowserProvider.lifecycle_failures.test.ts b/tests/boundary/browser/cdpBrowserProvider.lifecycle_failures.test.ts
index 3d5fc7a6f..3109e9d00 100644
--- a/tests/boundary/browser/cdpBrowserProvider.lifecycle_failures.test.ts
+++ b/tests/boundary/browser/cdpBrowserProvider.lifecycle_failures.test.ts
@@ -269,6 +269,32 @@ describe("CdpBrowserProvider: protocol failures and cancellation cleanup", () =>
"Accessibility.getFullAXTree was unavailable from this browser target.",
);
+ const invalidAccessibilityParams = await startFakeCdpBrowser({
+ commandError: (command) =>
+ command.method === "Accessibility.getFullAXTree"
+ ? { code: -32_602, message: "Invalid params" }
+ : undefined,
+ });
+ trackBrowser(invalidAccessibilityParams);
+ const invalidParamsResult = await new CdpBrowserProvider().inspectPage(
+ inspectWebPageInputSchema.parse({
+ cdp_endpoint: invalidAccessibilityParams.endpoint,
+ allowed_origins: [invalidAccessibilityParams.allowedOrigin],
+ target_id: "allowed-page",
+ observation_ms: 0,
+ }),
+ );
+ expect(invalidParamsResult).toMatchObject({
+ ok: false,
+ error: {
+ _tag: "BrowserObservationError",
+ reason: "protocol_error",
+ command: "Accessibility.getFullAXTree",
+ code: -32_602,
+ reportedMessage: "Invalid params",
+ },
+ });
+
for (const [options, reason] of [
[{ oversizedDiscovery: true }, "invalid_endpoint_response"],
[{ invalidBrowserWebSocket: true }, "invalid_endpoint_response"],
diff --git a/tests/boundary/browser/cdpConnection.test.ts b/tests/boundary/browser/cdpConnection.test.ts
index 5df64c46b..2b2bb0c08 100644
--- a/tests/boundary/browser/cdpConnection.test.ts
+++ b/tests/boundary/browser/cdpConnection.test.ts
@@ -32,6 +32,8 @@ describe("CDP connection", () => {
expect(frames).toMatchObject({
frameTree: { frame: { id: "frame-main" } },
});
+ browser.emitRawMessage(JSON.stringify({ id: 999 }));
+ await expect(connection.send("Runtime.enable")).resolves.toEqual({});
} finally {
await connection.close();
}
@@ -84,6 +86,57 @@ describe("CDP connection", () => {
}
});
+ it.each([
+ ["missing result and error", (id: number) => ({ id })],
+ [
+ "both result and error",
+ (id: number) => ({
+ id,
+ result: {},
+ error: { code: -32_602, message: "Invalid params" },
+ }),
+ ],
+ [
+ "malformed error",
+ (id: number) => ({
+ id,
+ error: { code: "bad", message: "Invalid params" },
+ }),
+ ],
+ ["invalid result", (id: number) => ({ id, result: [] })],
+ ["invalid session id", (id: number) => ({ id, result: {}, sessionId: 7 })],
+ ])(
+ "fails the connection for a correlated reply with %s",
+ async (_case, reply) => {
+ const browser = await startFakeCdpBrowser({
+ hangOnMethod: "Page.enable",
+ });
+ browsers.push(browser);
+ const connection = await CdpConnection.connect(
+ browser.browserWebSocketUrl,
+ "observe_web_session",
+ );
+ try {
+ const pending = connection.send("Page.enable");
+ const rejection = expect(pending).rejects.toMatchObject({
+ _tag: "BrowserObservationError",
+ reason: "protocol_error",
+ });
+ await vi.waitFor(() => expect(browser.commands).toHaveLength(1));
+ const command = browser.commands[0];
+ if (command === undefined)
+ throw new Error("Fake browser received no command");
+ browser.emitRawMessage(JSON.stringify(reply(command.id)));
+ await rejection;
+ await expect(connection.send("Runtime.enable")).rejects.toMatchObject({
+ reason: "protocol_error",
+ });
+ } finally {
+ await connection.close();
+ }
+ },
+ );
+
it("preserves the selected payload limit reason for pending and subsequent commands", async () => {
const browser = await startFakeCdpBrowser({
commandResult: () => ({ oversized: "x".repeat(2_048) }),