diff --git a/README.md b/README.md index cc155d3..7b314f7 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ This writes a `.claude/settings.json` with a `PostToolUse` hook that runs after ### Configuring Rules -By default, all 41 rules run. To customize, create a `laint.config.json` in your project root: +By default, all 42 rules run. To customize, create a `laint.config.json` in your project root: ```json // Only run these specific rules (include mode) @@ -88,7 +88,7 @@ const results = lintJsxCode(code, { exclude: true, }); -// Run all 40 rules +// Run all 42 rules const allResults = lintJsxCode(code, { rules: [], exclude: true, @@ -117,7 +117,7 @@ const webRules = getRulesForPlatform('web'); const backendRules = getRulesForPlatform('backend'); ``` -## Available Rules (41 total) +## Available Rules (42 total) ### Expo Router Rules @@ -185,6 +185,12 @@ const backendRules = getRulesForPlatform('backend'); | `no-response-json-lowercase` | warning | backend | Use Response.json() instead of new Response(JSON.stringify()) | | `sql-no-nested-calls` | error | backend | Don't nest sql template tags | +### URL Rules + +| Rule | Severity | Description | +| ------------------------ | -------- | -------------------------------------------------------------- | +| `url-params-must-encode` | warning | URL query param values must be wrapped in encodeURIComponent() | + ### Error Handling Rules | Rule | Severity | Description | @@ -459,6 +465,16 @@ if (typeof data === 'string') { const user: User = response.data; ``` +### `url-params-must-encode` + +```typescript +// Bad - unencoded query param +const url = `https://api.example.com?q=${query}`; + +// Good - encoded query param +const url = `https://api.example.com?q=${encodeURIComponent(query)}`; +``` + ### `catch-must-log-to-sentry` ```typescript diff --git a/src/rules/index.ts b/src/rules/index.ts index 7a608b8..9bf2ab8 100644 --- a/src/rules/index.ts +++ b/src/rules/index.ts @@ -32,6 +32,7 @@ import { transitionSharedTagMismatch } from './transition-shared-tag-mismatch'; import { transitionPreferBlankStack } from './transition-prefer-blank-stack'; import { preferGuardClauses } from './prefer-guard-clauses'; import { noTypeAssertion } from './no-type-assertion'; +import { urlParamsMustEncode } from './url-params-must-encode'; import { catchMustLogToSentry } from './catch-must-log-to-sentry'; import { noNestedTryCatch } from './no-nested-try-catch'; import { noInlineStyles } from './no-inline-styles'; @@ -75,6 +76,7 @@ export const rules: Record = { 'transition-prefer-blank-stack': transitionPreferBlankStack, 'prefer-guard-clauses': preferGuardClauses, 'no-type-assertion': noTypeAssertion, + 'url-params-must-encode': urlParamsMustEncode, 'catch-must-log-to-sentry': catchMustLogToSentry, 'no-nested-try-catch': noNestedTryCatch, 'no-inline-styles': noInlineStyles, diff --git a/src/rules/url-params-must-encode.ts b/src/rules/url-params-must-encode.ts new file mode 100644 index 0000000..5c5d426 --- /dev/null +++ b/src/rules/url-params-must-encode.ts @@ -0,0 +1,57 @@ +import traverse from '@babel/traverse'; +import * as t from '@babel/types'; +import type { File } from '@babel/types'; +import type { LintResult } from '../types'; + +const RULE_NAME = 'url-params-must-encode'; + +export function urlParamsMustEncode(ast: File, _code: string): LintResult[] { + const results: LintResult[] = []; + + traverse(ast, { + TemplateLiteral(path) { + const { quasis, expressions } = path.node; + + for (let i = 0; i < expressions.length; i++) { + const expr = expressions[i]; + const precedingQuasi = quasis[i]; + const rawBefore = precedingQuasi.value.raw; + + // Check if the preceding text ends with a URL query param pattern: ?key= or &key= + if (!/[?&][a-zA-Z_][a-zA-Z0-9_]*=$/.test(rawBefore)) continue; + + // Check if the expression is wrapped in encodeURIComponent() + if ( + t.isCallExpression(expr) && + t.isIdentifier(expr.callee, { name: 'encodeURIComponent' }) + ) { + continue; + } + + // Also allow function calls wrapping encodeURIComponent, e.g. String(encodeURIComponent(...)) + if (t.isCallExpression(expr)) { + const arg = expr.arguments[0]; + if ( + arg && + t.isCallExpression(arg) && + t.isIdentifier(arg.callee, { name: 'encodeURIComponent' }) + ) { + continue; + } + } + + const { loc } = expr; + results.push({ + rule: RULE_NAME, + message: + 'URL query parameter value should be wrapped in encodeURIComponent() to prevent malformed URLs.', + line: loc?.start.line ?? 0, + column: loc?.start.column ?? 0, + severity: 'warning', + }); + } + }, + }); + + return results; +} diff --git a/tests/config-modes.test.ts b/tests/config-modes.test.ts index d7567d7..2158b60 100644 --- a/tests/config-modes.test.ts +++ b/tests/config-modes.test.ts @@ -124,7 +124,7 @@ describe('config modes', () => { expect(ruleNames).toContain('expo-image-import'); expect(ruleNames).toContain('no-stylesheet-create'); - expect(ruleNames.length).toBe(41); + expect(ruleNames.length).toBe(42); }); }); }); diff --git a/tests/url-params-must-encode.test.ts b/tests/url-params-must-encode.test.ts new file mode 100644 index 0000000..7399486 --- /dev/null +++ b/tests/url-params-must-encode.test.ts @@ -0,0 +1,60 @@ +import { describe, it, expect } from 'vitest'; +import { lintJsxCode } from '../src'; + +const RULE = 'url-params-must-encode'; + +function lint(code: string) { + return lintJsxCode(code, { rules: [RULE] }); +} + +describe(RULE, () => { + it('flags unencoded value after ?key=', () => { + const code = 'const url = `https://api.example.com/search?q=${query}`;'; + const results = lint(code); + expect(results).toHaveLength(1); + expect(results[0].rule).toBe(RULE); + expect(results[0].message).toContain('encodeURIComponent'); + }); + + it('flags unencoded value after &key=', () => { + const code = 'const url = `https://api.example.com/search?q=test&page=${page}`;'; + const results = lint(code); + expect(results).toHaveLength(1); + }); + + it('flags multiple unencoded params', () => { + const code = 'const url = `https://api.example.com?q=${query}&page=${page}`;'; + const results = lint(code); + expect(results).toHaveLength(2); + }); + + it('allows encodeURIComponent wrapped values', () => { + const code = 'const url = `https://api.example.com?q=${encodeURIComponent(query)}`;'; + const results = lint(code); + expect(results).toHaveLength(0); + }); + + it('allows template literals without URL params', () => { + const code = 'const msg = `Hello ${name}, welcome!`;'; + const results = lint(code); + expect(results).toHaveLength(0); + }); + + it('allows path segments (no query params)', () => { + const code = 'const url = `https://api.example.com/users/${userId}`;'; + const results = lint(code); + expect(results).toHaveLength(0); + }); + + it('allows String(encodeURIComponent(...)) wrapped values', () => { + const code = 'const url = `https://api.example.com?q=${String(encodeURIComponent(query))}`;'; + const results = lint(code); + expect(results).toHaveLength(0); + }); + + it('does not flag non-template string concatenation', () => { + const code = 'const url = "https://api.example.com?q=" + query;'; + const results = lint(code); + expect(results).toHaveLength(0); + }); +});