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/schemas/parse.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/schemas/parse.ts')
| -rw-r--r-- | src/schemas/parse.ts | 23 |
1 files changed, 23 insertions, 0 deletions
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 = <S extends TSchema>( + raw: string, + validator: Validator<{}, S>, +): Result<Static<S>, 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); +}; |
