Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/checked-json-boundaries.md
Original file line number Diff line number Diff line change
@@ -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.
1 change: 1 addition & 0 deletions packages/eslint-config-basic/eslint.config.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
2 changes: 2 additions & 0 deletions packages/eslint-plugin/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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: {
Expand All @@ -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,
},
};
3 changes: 2 additions & 1 deletion packages/eslint-plugin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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'"
Expand Down
202 changes: 202 additions & 0 deletions packages/eslint-plugin/rules/no-unchecked-json-cast.mjs
Original file line number Diff line number Diff line change
@@ -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<TSESTree.Node, { type: (typeof ASSERTION_TYPES)[number] }>} 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;
71 changes: 71 additions & 0 deletions packages/eslint-plugin/rules/no-unchecked-json-cast.test.mjs
Original file line number Diff line number Diff line change
@@ -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 = <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] })),
});
1 change: 1 addition & 0 deletions packages/oxlint-config-basic/index.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -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: '^_' },
Expand Down