From b9c77bb6f9b8b83574489344ef6efd207a611e98 Mon Sep 17 00:00:00 2001 From: amankumarsingh77 Date: Tue, 28 Jul 2026 00:53:19 +0530 Subject: refactor: validate JSON at every parse boundary MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Ten sites cast or implicitly typed JSON.parse output; JSON.parse("null") would have satisfied all of them. parseJson returns a Result and validates against a typebox schema. js.ts keeps unknown — user script output has no fixed shape. daemon/bridge.ts assigned JSON.parse straight to CdpRawMessage with no guard at all; it now uses isCdpRawMessage like the transport does. Co-Authored-By: Claude Opus 5 (1M context) --- src/schemas/parse.ts | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) create mode 100644 src/schemas/parse.ts (limited to 'src/schemas/parse.ts') diff --git a/src/schemas/parse.ts b/src/schemas/parse.ts new file mode 100644 index 0000000..5b43fd9 --- /dev/null +++ b/src/schemas/parse.ts @@ -0,0 +1,23 @@ +import type { Static, TSchema } from "typebox"; +import type { Validator } from "typebox/compile"; +import { type Result, err, ok } from "../util/result"; + +export const parseJson = ( + raw: string, + validator: Validator<{}, S>, +): Result, string> => { + let parsed: unknown; + try { + parsed = JSON.parse(raw); + } catch (e) { + return err(`JSON parse failed: ${e instanceof Error ? e.message : String(e)}`); + } + if (!validator.Check(parsed)) { + const messages = validator + .Errors(parsed) + .map((x) => x.message) + .join("; "); + return err(messages.length > 0 ? messages : "JSON did not match the expected shape"); + } + return ok(parsed); +}; -- cgit v1.2.3