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/profile/list.ts | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) (limited to 'src/profile/list.ts') diff --git a/src/profile/list.ts b/src/profile/list.ts index 5a83654..3915a98 100644 --- a/src/profile/list.ts +++ b/src/profile/list.ts @@ -21,6 +21,9 @@ import { readdir, readFile } from "node:fs/promises"; import { join } from "node:path"; +import { Type } from "typebox"; +import { Compile } from "typebox/compile"; +import { parseJson } from "../schemas/parse"; export type BrowserProfile = { /** Profile subdirectory name, e.g. "Default" or "Profile 1". */ @@ -48,21 +51,23 @@ const NON_PROFILE_DIRS: ReadonlySet = new Set([ export const formatProfileLabel = (name: string, email: string | undefined, dir: string): string => `${name} (${email && email.length > 0 ? email : dir})`; +const JsonObject = Type.Record(Type.String(), Type.Unknown()); + +const jsonObjectValidator = Compile(JsonObject); + const readJsonFile = async (path: string): Promise | null> => { + let raw: string; try { - const raw = await readFile(path, "utf8"); - const parsed: unknown = JSON.parse(raw); - if (typeof parsed !== "object" || parsed === null || Array.isArray(parsed)) return null; - return parsed as Record; + raw = await readFile(path, "utf8"); } catch { - // Missing file, permission error, or malformed JSON — the caller falls - // back to the next tier, and ultimately to an empty list. return null; } + const parsed = parseJson(raw, jsonObjectValidator); + return parsed.success ? parsed.data : null; }; const asRecord = (v: unknown): Record | null => - typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Record) : null; + jsonObjectValidator.Check(v) ? v : null; const asString = (v: unknown): string | undefined => typeof v === "string" && v.length > 0 ? v : undefined; -- cgit v1.2.3