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

This commit is contained in:
morluto
2026-10-09 04:12:48 +08:00
parent bc4aa46d7c
commit 6b92002597
5 changed files with 117 additions and 22 deletions
+35 -16
View File
@@ -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;
}
pending.resolve("result" in message ? message.result : {});
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;
}
this.#complete(id, pending);
pending.reject(
new CdpCommandRejection(
this.operation,
pending.method,
reported.code,
reported.message,
),
);
}
#complete(id: number, pending: PendingCommand): void {
+2 -5
View File
@@ -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;