From ba308b3ee5e49a22680a1ee82a6439758ae7d2eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jos=C3=A9=20Costa?= Date: Wed, 2 Dec 2026 18:40:26 +0100 Subject: [PATCH] feat(lint): require validation before casting parsed JSON --- .changeset/checked-json-boundaries.md | 9 + .../eslint-config-basic/eslint.config.mjs | 1 + packages/eslint-plugin/index.mjs | 2 + packages/eslint-plugin/package.json | 3 +- .../rules/no-unchecked-json-cast.mjs | 202 ++++++++++++++++++ .../rules/no-unchecked-json-cast.test.mjs | 71 ++++++ packages/oxlint-config-basic/index.mjs | 1 + 7 files changed, 288 insertions(+), 1 deletion(-) create mode 100644 .changeset/checked-json-boundaries.md create mode 100644 packages/eslint-plugin/rules/no-unchecked-json-cast.mjs create mode 100644 packages/eslint-plugin/rules/no-unchecked-json-cast.test.mjs diff --git a/.changeset/checked-json-boundaries.md b/.changeset/checked-json-boundaries.md new file mode 100644 index 0000000..28b723c --- /dev/null +++ b/.changeset/checked-json-boundaries.md @@ -0,0 +1,9 @@ +--- +'@frontify/eslint-config-basic': minor +'@frontify/eslint-config-react': minor +'@frontify/eslint-plugin': patch +'@frontify/oxlint-config-basic': minor +'@frontify/oxlint-config-react': minor +--- + +ESLint and Oxlint report direct TypeScript casts on `JSON.parse()` and known web response `.json()` calls. Assign the result to `unknown` and validate it with a schema before using it. diff --git a/packages/eslint-config-basic/eslint.config.mjs b/packages/eslint-config-basic/eslint.config.mjs index 997f299..083862d 100644 --- a/packages/eslint-config-basic/eslint.config.mjs +++ b/packages/eslint-config-basic/eslint.config.mjs @@ -346,6 +346,7 @@ export default defineConfig( files: ['**/*.ts', '**/*.tsx', '**/*.mts', '**/*.cts'], rules: { '@frontify/no-inline-param-type': 'error', + '@frontify/no-unchecked-json-cast': 'error', // As we're using @typescript-eslint it's recommended to turn off // the standard eslint rule for unused variables and use the @typescript-eslint rule instead. diff --git a/packages/eslint-plugin/index.mjs b/packages/eslint-plugin/index.mjs index b80ce44..4a28851 100644 --- a/packages/eslint-plugin/index.mjs +++ b/packages/eslint-plugin/index.mjs @@ -4,6 +4,7 @@ import jsxShorthandBoolean from './rules/jsx-shorthand-boolean.mjs'; import noConditionalObjectSpread from './rules/no-conditional-object-spread.mjs'; import noInlineParamType from './rules/no-inline-param-type.mjs'; import noPositionalBooleanFlags from './rules/no-positional-boolean-flags.mjs'; +import noUncheckedJsonCast from './rules/no-unchecked-json-cast.mjs'; export default { meta: { @@ -14,5 +15,6 @@ export default { 'no-conditional-object-spread': noConditionalObjectSpread, 'no-inline-param-type': noInlineParamType, 'no-positional-boolean-flags': noPositionalBooleanFlags, + 'no-unchecked-json-cast': noUncheckedJsonCast, }, }; diff --git a/packages/eslint-plugin/package.json b/packages/eslint-plugin/package.json index 4c7f5fa..f34cb40 100644 --- a/packages/eslint-plugin/package.json +++ b/packages/eslint-plugin/package.json @@ -18,7 +18,8 @@ "rules/jsx-shorthand-boolean.mjs", "rules/no-conditional-object-spread.mjs", "rules/no-inline-param-type.mjs", - "rules/no-positional-boolean-flags.mjs" + "rules/no-positional-boolean-flags.mjs", + "rules/no-unchecked-json-cast.mjs" ], "scripts": { "test": "node --test 'rules/**/*.test.mjs'" diff --git a/packages/eslint-plugin/rules/no-unchecked-json-cast.mjs b/packages/eslint-plugin/rules/no-unchecked-json-cast.mjs new file mode 100644 index 0000000..1c10565 --- /dev/null +++ b/packages/eslint-plugin/rules/no-unchecked-json-cast.mjs @@ -0,0 +1,202 @@ +/* (c) Copyright Frontify Ltd., all rights reserved. */ + +// @ts-check + +/** @import { SourceCode, JSSyntaxElement } from 'eslint' */ +/** @import { TSESTree } from '@typescript-eslint/types' */ + +const ASSERTION_TYPES = /** @type {const} */ (['TSAsExpression', 'TSTypeAssertion']); +const ASSERTION_SELECTOR = ASSERTION_TYPES.join(', '); +const EXPRESSION_WRAPPERS = new Set([ + 'ChainExpression', + 'ParenthesizedExpression', + 'TSNonNullExpression', + 'TSSatisfiesExpression', +]); +const JSON_GLOBAL = 'JSON'; +const JSON_PARSE = 'parse'; +const FETCH_GLOBAL = 'fetch'; +const RESPONSE_GLOBAL = 'Response'; +const RESPONSE_JSON = 'json'; +const VALIDATE_JSON_MESSAGE_ID = 'validateJson'; + +/** @typedef {Extract} TypeAssertion */ + +/** + * Follows wrappers that do not validate the value. + * @param {TSESTree.Node | null | undefined} node - The expression under inspection. + */ +function unwrapValue(node) { + let value = node; + + while (value) { + if (value.type === 'AwaitExpression') { + value = value.argument; + continue; + } + + if (value.type === 'TSAsExpression' || value.type === 'TSTypeAssertion') { + if (value.typeAnnotation.type !== 'TSUnknownKeyword') { + break; + } + + value = value.expression; + continue; + } + + if ('expression' in value && typeof value.expression === 'object' && EXPRESSION_WRAPPERS.has(value.type)) { + value = value.expression; + continue; + } + + break; + } + + return value; +} + +/** + * Resolves a name at its use site so a local definition can shadow a global. + * @param {SourceCode} sourceCode - The scope API shared by ESLint and Oxlint. + * @param {TSESTree.Identifier} identifier - The identifier to resolve. + */ +function findBinding(sourceCode, identifier) { + /** @type {import('eslint').Scope.Scope | null} */ + let scope = sourceCode.getScope(identifier); + + while (scope) { + const binding = scope.set.get(identifier.name); + + if (binding) { + return binding; + } + + scope = scope.upper; + } +} + +/** + * Checks that the expected built-in name has no local definition. + * @param {SourceCode} sourceCode - The rule's source code. + * @param {TSESTree.Node} node - The expression or type name to check. + * @param {string} name - The built-in identifier. + */ +function isGlobal(sourceCode, node, name) { + return node.type === 'Identifier' && node.name === name && !findBinding(sourceCode, node)?.defs.length; +} + +/** + * Identifies a call to the built-in fetch API. + * @param {SourceCode} sourceCode - The rule's source code. + * @param {TSESTree.Node | null | undefined} node - A possible call to fetch. + */ +function isFetch(sourceCode, node) { + const call = unwrapValue(node); + + return call?.type === 'CallExpression' && isGlobal(sourceCode, call.callee, FETCH_GLOBAL); +} + +/** + * Identifies browser responses from a Response annotation or a direct fetch result. + * @param {SourceCode} sourceCode - The rule's source code. + * @param {TSESTree.Node} node - The receiver of the JSON read. + */ +function isResponse(sourceCode, node) { + if (isFetch(sourceCode, node)) { + return true; + } + + const receiver = unwrapValue(node); + + if (receiver?.type !== 'Identifier') { + return false; + } + + const [definition, another] = findBinding(sourceCode, receiver)?.defs ?? []; + + if (!definition || another) { + return false; + } + + // The TypeScript parser adds annotations to scope identifiers. + const name = /** @type {TSESTree.Identifier} */ (definition.name); + const annotation = name.typeAnnotation?.typeAnnotation; + + if (annotation?.type === 'TSTypeReference' && isGlobal(sourceCode, annotation.typeName, RESPONSE_GLOBAL)) { + return true; + } + + if ( + definition.type !== 'Variable' || + definition.parent.kind !== 'const' || + definition.node.id.type !== 'Identifier' + ) { + return false; + } + + // Scope definitions use ESTree types, but the initializer can contain TypeScript wrappers. + const declaration = /** @type {TSESTree.VariableDeclarator} */ (definition.node); + + return isFetch(sourceCode, declaration.init); +} + +/** + * Recognizes direct reads from JSON.parse or a known web response. + * @param {SourceCode} sourceCode - The rule's source code. + * @param {TSESTree.Node} node - The operand of an assertion. + */ +function isJsonRead(sourceCode, node) { + const call = unwrapValue(node); + + if (call?.type !== 'CallExpression' || call.callee.type !== 'MemberExpression') { + return false; + } + + const { computed, object, property } = call.callee; + let method; + + if (!computed && property.type === 'Identifier') { + method = property.name; + } + + if (computed && property.type === 'Literal') { + method = property.value; + } + + return ( + (method === JSON_PARSE && isGlobal(sourceCode, object, JSON_GLOBAL)) || + (method === RESPONSE_JSON && isResponse(sourceCode, object)) + ); +} + +/** @satisfies {import('eslint').Rule.RuleModule} */ +const noUncheckedJsonCast = { + meta: { + type: 'problem', + schema: [], + messages: { + [VALIDATE_JSON_MESSAGE_ID]: 'Keep parsed JSON unknown until a runtime check validates its shape.', + }, + }, + create(context) { + return { + /** + * Reports an assertion that assigns a type to unchecked JSON. + * @param {JSSyntaxElement} node - The assertion matched by the selector. + */ + [ASSERTION_SELECTOR](node) { + // The selector matches only TypeScript nodes with an assertion operand and type. + const assertion = /** @type {TypeAssertion} */ (node); + + if ( + assertion.typeAnnotation.type !== 'TSUnknownKeyword' && + isJsonRead(context.sourceCode, assertion.expression) + ) { + context.report({ node, messageId: VALIDATE_JSON_MESSAGE_ID }); + } + }, + }; + }, +}; + +export default noUncheckedJsonCast; diff --git a/packages/eslint-plugin/rules/no-unchecked-json-cast.test.mjs b/packages/eslint-plugin/rules/no-unchecked-json-cast.test.mjs new file mode 100644 index 0000000..07381de --- /dev/null +++ b/packages/eslint-plugin/rules/no-unchecked-json-cast.test.mjs @@ -0,0 +1,71 @@ +/* (c) Copyright Frontify Ltd., all rights reserved. */ + +import * as parser from '@typescript-eslint/parser'; +import { RuleTester } from 'eslint'; + +import plugin from '../index.mjs'; + +const rule = plugin.rules['no-unchecked-json-cast']; +const ruleTester = new RuleTester({ languageOptions: { parser } }); +const validateJsonError = { messageId: 'validateJson' }; + +const uncheckedJsonCasts = [ + { + name: 'reports a direct cast of JSON.parse', + code: 'const settings = JSON.parse(text) as Settings;', + }, + { + name: 'reports an angle-bracket cast of a computed JSON.parse call', + filename: 'example.ts', + code: 'const settings = JSON["parse"](text);', + }, + { + name: 'reports the concrete type in a double assertion through unknown', + code: 'const settings = JSON.parse(text) as unknown as Settings;', + }, + { + name: 'reports a cast through satisfies and a non-null assertion', + code: 'const settings = (JSON.parse(text) satisfies unknown)! as Settings;', + }, + { + name: 'reports an any cast of parsed JSON', + code: 'const settings = JSON.parse(text) as any;', + }, + { + name: 'reports a cast of the JSON result from an awaited fetch', + code: 'async function read() { return (await (await fetch(url)).json()) as Settings; }', + }, + { + name: 'follows a const initialized from fetch', + code: 'async function read() { const response = await fetch(url); return (await response.json()) as Settings; }', + }, + { + name: 'follows a Response parameter and a computed json call', + code: 'async function read(response: Response) { return (await response["json"]()) as Settings; }', + }, + { + name: 'follows a Response variable annotation', + code: 'async function read() { const response: Response = getResponse(); return (await response.json()) as Settings; }', + }, +]; + +ruleTester.run('no-unchecked-json-cast', rule, { + valid: [ + 'const value: unknown = JSON.parse(text); const settings = settingsSchema.parse(value);', + 'const value = JSON.parse(text) as unknown;', + 'async function read(response: Response) { return (await response.json()) as unknown; }', + 'const settings = settingsSchema.parse(JSON.parse(text)) as Settings;', + 'const parse = JSON.parse; const settings = parse(text) as Settings;', + 'const settings = JSON[method](text) as Settings;', + 'const settings = object as Settings;', + 'function read(JSON: LocalParser) { return JSON.parse(text) as Settings; }', + 'import JSON from "./parser"; const settings = JSON.parse(text) as Settings;', + 'async function read(response: LocalCache) { return (await response.json()) as Settings; }', + 'async function read(response) { return (await response.json()) as Settings; }', + 'async function read(fetch: LocalReader) { const response = await fetch(key); return (await response.json()) as Settings; }', + 'import type { Response } from "./cache"; async function read(response: Response) { return (await response.json()) as Settings; }', + 'async function read() { let response = await fetch(url); response = getCache(); return (await response.json()) as Settings; }', + 'async function read() { const { body } = await fetch(url); return (await body.json()) as Settings; }', + ], + invalid: uncheckedJsonCasts.map((testCase) => ({ ...testCase, errors: [validateJsonError] })), +}); diff --git a/packages/oxlint-config-basic/index.mjs b/packages/oxlint-config-basic/index.mjs index 724dd42..ab45414 100644 --- a/packages/oxlint-config-basic/index.mjs +++ b/packages/oxlint-config-basic/index.mjs @@ -579,6 +579,7 @@ export default defineConfig({ files: ['**/*.ts', '**/*.tsx', '**/*.mts', '**/*.cts'], rules: { '@frontify/no-inline-param-type': 'error', + '@frontify/no-unchecked-json-cast': 'error', 'no-unused-vars': [ 'error', { argsIgnorePattern: '^_', varsIgnorePattern: '^_' },