diff options
| author | amankumarsingh77 <amankumarsingh7702@gmail.com> | 2026-07-28 00:53:19 +0530 |
|---|---|---|
| committer | Aman Kumar <145339995+amankumarsingh77@users.noreply.github.com> | 2026-08-02 19:12:46 +0530 |
| commit | b9c77bb6f9b8b83574489344ef6efd207a611e98 (patch) | |
| tree | 3c59bf53bcce3ac5c6bbf9a22884b6e6f787dc91 /src/profile/list.ts | |
| parent | 1c73f4af643aa60ca554a3770264791d299e64e2 (diff) | |
refactor: validate JSON at every parse boundary
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) <noreply@anthropic.com>
Diffstat (limited to 'src/profile/list.ts')
| -rw-r--r-- | src/profile/list.ts | 19 |
1 files changed, 12 insertions, 7 deletions
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<string> = 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<Record<string, unknown> | 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<string, unknown>; + 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<string, unknown> | null => - typeof v === "object" && v !== null && !Array.isArray(v) ? (v as Record<string, unknown>) : null; + jsonObjectValidator.Check(v) ? v : null; const asString = (v: unknown): string | undefined => typeof v === "string" && v.length > 0 ? v : undefined; |
