@interlace/eslint-devkit 1.10.0 → 1.12.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +1 -1
- package/package.json +2 -2
- package/src/rule-creation/index.d.ts +1 -0
- package/src/rule-creation/index.js +1 -1
- package/src/rule-creation/message-source.d.ts +95 -0
- package/src/rule-creation/message-source.js +1 -0
- package/src/rule-creation/sql-injection-rule.d.ts +20 -0
- package/src/rule-creation/sql-injection-rule.js +1 -1
package/README.md
CHANGED
|
@@ -504,7 +504,7 @@ const rule = createRule<[], 'messageId'>({
|
|
|
504
504
|
|
|
505
505
|
| Package | Version |
|
|
506
506
|
| ------------------------- | ----------------------------- |
|
|
507
|
-
| ESLint | ^8.
|
|
507
|
+
| ESLint | ^8.40.0 \|\| ^9.0.0 \|\| ^10.0.0 |
|
|
508
508
|
| TypeScript | >=4.0.0 |
|
|
509
509
|
| @typescript-eslint/parser | >=6.0.0 |
|
|
510
510
|
| @typescript-eslint/utils | ^8.0.0 |
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@interlace/eslint-devkit",
|
|
3
|
-
"version": "1.
|
|
3
|
+
"version": "1.12.0",
|
|
4
4
|
"description": "Toolkit for building ESLint plugins in TypeScript — AST helpers, type utilities, rule-creation scaffolding, security benchmarks, and SARIF output.",
|
|
5
5
|
"type": "commonjs",
|
|
6
6
|
"main": "./src/index.js",
|
|
@@ -66,7 +66,7 @@
|
|
|
66
66
|
},
|
|
67
67
|
"peerDependencies": {
|
|
68
68
|
"@typescript-eslint/utils": "^7.0.0 || ^8.0.0",
|
|
69
|
-
"eslint": "^8.
|
|
69
|
+
"eslint": "^8.40.0 || ^9.0.0 || ^10.0.0",
|
|
70
70
|
"oxc-resolver": "^11.24.2",
|
|
71
71
|
"typescript": ">=4.8.4"
|
|
72
72
|
},
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";var __createBinding=this&&this.__createBinding||(Object.create?(function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:function(){return m[k]}}}Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]}));var __exportStar=this&&this.__exportStar||function(m,exports2){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./rule-creator"),exports);__exportStar(require("./mock-context"),exports);__exportStar(require("./sql-injection-rule"),exports);__exportStar(require("./unscoped-mutation-rule"),exports);__exportStar(require("./require-tls-rule"),exports);__exportStar(require("./mass-assignment-rule"),exports);__exportStar(require("./hardcoded-credentials-rule"),exports);__exportStar(require("./sdk-api-key-rule"),exports);__exportStar(require("./browser-escape-hatch-rule"),exports);__exportStar(require("./system-prompt-injection-rule"),exports);__exportStar(require("./raw-identifier-rule"),exports);
|
|
1
|
+
"use strict";var __createBinding=this&&this.__createBinding||(Object.create?(function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:function(){return m[k]}}}Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]}));var __exportStar=this&&this.__exportStar||function(m,exports2){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./rule-creator"),exports);__exportStar(require("./mock-context"),exports);__exportStar(require("./sql-injection-rule"),exports);__exportStar(require("./unscoped-mutation-rule"),exports);__exportStar(require("./require-tls-rule"),exports);__exportStar(require("./mass-assignment-rule"),exports);__exportStar(require("./hardcoded-credentials-rule"),exports);__exportStar(require("./sdk-api-key-rule"),exports);__exportStar(require("./browser-escape-hatch-rule"),exports);__exportStar(require("./system-prompt-injection-rule"),exports);__exportStar(require("./message-source"),exports);__exportStar(require("./raw-identifier-rule"),exports);
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Copyright (c) 2025 Ofri Peretz
|
|
3
|
+
* Licensed under the MIT License. Use of this source code is governed by the
|
|
4
|
+
* MIT license that can be found in the LICENSE file.
|
|
5
|
+
*/
|
|
6
|
+
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
|
|
7
|
+
/** A source whose messages are attacker-influenced, and which owns its own rule. */
|
|
8
|
+
export type MessageSource = 'websocket' | 'worker' | 'filereader' | 'postmessage';
|
|
9
|
+
/**
|
|
10
|
+
* Resolve a receiver identifier to the source it was constructed from.
|
|
11
|
+
*
|
|
12
|
+
* Lexical, not name-keyed. A file-wide name map cannot see shadowing: with
|
|
13
|
+
* `const ws = new WebSocket()` at module scope, an inner `const ws = payload`
|
|
14
|
+
* was still resolved as a WebSocket — so an attacker-controlled `payload`
|
|
15
|
+
* got reported as "WebSocket message data" while the generic rule, believing
|
|
16
|
+
* the line was owned, said nothing. Measured before this change.
|
|
17
|
+
*
|
|
18
|
+
* Resolution walks the scope chain from the reference itself, so the binding
|
|
19
|
+
* that is actually in scope is the one that decides.
|
|
20
|
+
*/
|
|
21
|
+
/**
|
|
22
|
+
* `SHADOWED` — the name resolves to a binding that is not a known source.
|
|
23
|
+
*
|
|
24
|
+
* Distinct from `undefined`, which means no binding at all, i.e. a genuine
|
|
25
|
+
* global. The difference matters for `window` / `self` / `parent`: those are
|
|
26
|
+
* the postMessage receivers only when nothing shadows them, and
|
|
27
|
+
* `function f(window) { window.addEventListener('message', …) }` is a
|
|
28
|
+
* parameter, not the global.
|
|
29
|
+
*/
|
|
30
|
+
export declare const SHADOWED: unique symbol;
|
|
31
|
+
export type ReceiverResolver = (node: TSESTree.Identifier) => MessageSource | typeof SHADOWED | undefined;
|
|
32
|
+
/**
|
|
33
|
+
* Build the resolver for a file from its scope manager.
|
|
34
|
+
*
|
|
35
|
+
* A variable with more than one definition is not resolved: `let ws` reassigned
|
|
36
|
+
* later could be anything at the point of use, and guessing is what this module
|
|
37
|
+
* exists to stop.
|
|
38
|
+
*/
|
|
39
|
+
export declare function createReceiverResolver(sourceCode: TSESLint.SourceCode): ReceiverResolver;
|
|
40
|
+
/** The source a `new X()` expression constructs, if X is one we own a rule for. */
|
|
41
|
+
export declare function constructedSource(node: TSESTree.Node | null | undefined): MessageSource | undefined;
|
|
42
|
+
/**
|
|
43
|
+
* The source of a receiver expression — `ws` in `ws.onmessage = …`.
|
|
44
|
+
*
|
|
45
|
+
* Resolves an identifier through the scope chain, and an inline
|
|
46
|
+
* `new WebSocket().onmessage = …` directly. Anything else is unknown.
|
|
47
|
+
*/
|
|
48
|
+
export declare function receiverSource(receiver: TSESTree.Node, resolve: ReceiverResolver): MessageSource | undefined;
|
|
49
|
+
/**
|
|
50
|
+
* The source whose handler this node is, if it is a message-handler attachment.
|
|
51
|
+
*
|
|
52
|
+
* Covers both attachment shapes:
|
|
53
|
+
* `ws.onmessage = (e) => …` (AssignmentExpression)
|
|
54
|
+
* `ws.addEventListener('message', fn)` (CallExpression)
|
|
55
|
+
* `reader.onload = (e) => …` (FileReader's event name)
|
|
56
|
+
*
|
|
57
|
+
* Returns the source, the handler's first parameter name (what the sink rules
|
|
58
|
+
* match `event.data` against) and the handler function itself, whose range is
|
|
59
|
+
* the region the payload is in scope for. `undefined` means "not a handler, or
|
|
60
|
+
* a handler on a receiver this file cannot identify".
|
|
61
|
+
*/
|
|
62
|
+
export declare function handlerSource(node: TSESTree.Node, resolve: ReceiverResolver): {
|
|
63
|
+
source: MessageSource;
|
|
64
|
+
eventParam: string;
|
|
65
|
+
handler: TSESTree.Node;
|
|
66
|
+
} | undefined;
|
|
67
|
+
/**
|
|
68
|
+
* Does this expression read the payload off `eventParam`?
|
|
69
|
+
*
|
|
70
|
+
* Matches `event.data`, `event.target.result` and deeper reads such as
|
|
71
|
+
* `event.data.html`, so that a sink fed a *property of* the payload is still
|
|
72
|
+
* attributed to the source rather than falling through to the generic rule.
|
|
73
|
+
*/
|
|
74
|
+
export declare function readsEventPayload(node: TSESTree.Node, eventParam: string): boolean;
|
|
75
|
+
/**
|
|
76
|
+
* The identifier a member chain is rooted at — `event` in `event.target.result`.
|
|
77
|
+
*
|
|
78
|
+
* Exposed so callers can resolve that identifier to a *binding*. Matching on the
|
|
79
|
+
* name alone is not enough: a nested function whose parameter shares the
|
|
80
|
+
* handler's parameter name reads an entirely different value.
|
|
81
|
+
*/
|
|
82
|
+
export declare function payloadRoot(node: TSESTree.Node): TSESTree.Identifier | undefined;
|
|
83
|
+
/**
|
|
84
|
+
* Build the file's payload resolver: "which source does this value come from?"
|
|
85
|
+
*
|
|
86
|
+
* This is the single question every sink rule in the family needs, asked from
|
|
87
|
+
* both directions:
|
|
88
|
+
*
|
|
89
|
+
* source rule `payloadSource(value) === 'websocket'` — mine, report it
|
|
90
|
+
* generic rule `payloadSource(value) === undefined` — nobody's, report it
|
|
91
|
+
*
|
|
92
|
+
* Because the two tests are complements, exactly one rule reports any given
|
|
93
|
+
* value. That is the whole fix.
|
|
94
|
+
*/
|
|
95
|
+
export declare function createPayloadResolver(sourceCode: TSESLint.SourceCode): (node: TSESTree.Node) => MessageSource | undefined;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.SHADOWED=void 0;exports.createReceiverResolver=createReceiverResolver;exports.constructedSource=constructedSource;exports.receiverSource=receiverSource;exports.handlerSource=handlerSource;exports.readsEventPayload=readsEventPayload;exports.payloadRoot=payloadRoot;exports.createPayloadResolver=createPayloadResolver;const ast_node_types_1=require("../ast-node-types");const CONSTRUCTORS=new Map([["WebSocket","websocket"],["Worker","worker"],["SharedWorker","worker"],["FileReader","filereader"]]);const POSTMESSAGE_RECEIVERS=new Set(["window","self","globalThis","parent","top"]);exports.SHADOWED=Symbol("shadowed");function findVariable(scope,name){for(let current=scope;current!==null;current=current.upper){const found=current.variables.find(variable=>variable.name===name);if(found!==void 0)return found}return void 0}function createReceiverResolver(sourceCode){return node=>{const scope=sourceCode.getScope(node);const variable=findVariable(scope,node.name);if(variable===void 0||variable.defs.length===0)return void 0;if(variable.defs.length!==1)return exports.SHADOWED;if(variable.references.filter(reference=>reference.isWrite()).length>1){return exports.SHADOWED}const declarator=variable.defs.find(definition=>definition.node.type===ast_node_types_1.AST_NODE_TYPES.VariableDeclarator);if(declarator===void 0)return exports.SHADOWED;return constructedSource(declarator.node.init)??exports.SHADOWED}}function constructedSource(node){if(node==null||node.type!==ast_node_types_1.AST_NODE_TYPES.NewExpression)return void 0;if(node.callee.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return void 0;return CONSTRUCTORS.get(node.callee.name)}function receiverSource(receiver,resolve){if(receiver.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const resolved=resolve(receiver);if(resolved===void 0){return POSTMESSAGE_RECEIVERS.has(receiver.name)?"postmessage":void 0}return resolved===exports.SHADOWED?void 0:resolved}return constructedSource(receiver)}function handlerSource(node,resolve){if(node.type===ast_node_types_1.AST_NODE_TYPES.AssignmentExpression){if(node.left.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression)return void 0;if(node.left.property.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return void 0;const source=receiverSource(node.left.object,resolve);if(source===void 0)return void 0;if(!HANDLER_PROPS[source].has(node.left.property.name))return void 0;return withHandler(source,node.right)}if(node.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){if(node.callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression)return void 0;if(node.callee.property.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return void 0;if(node.callee.property.name!=="addEventListener")return void 0;const[eventType,handler]=node.arguments;if(eventType?.type!==ast_node_types_1.AST_NODE_TYPES.Literal)return void 0;if(typeof eventType.value!=="string")return void 0;const source=receiverSource(node.callee.object,resolve);if(source===void 0)return void 0;if(!HANDLER_EVENTS[source].has(eventType.value))return void 0;return withHandler(source,handler)}return void 0}function withHandler(source,handler){if(handler===void 0)return void 0;if(handler.type!==ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression&&handler.type!==ast_node_types_1.AST_NODE_TYPES.FunctionExpression){return void 0}const first=handler.params[0];if(first?.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return void 0;return{source,eventParam:first.name,handler}}const HANDLER_PROPS={websocket:new Set(["onmessage"]),worker:new Set(["onmessage"]),filereader:new Set(["onload","onloadend"]),postmessage:new Set(["onmessage"])};const HANDLER_EVENTS={websocket:new Set(["message"]),worker:new Set(["message"]),filereader:new Set(["load","loadend"]),postmessage:new Set(["message"])};function readsEventPayload(node,eventParam){const root=payloadRoot(node);return root!==void 0&&root.name===eventParam}function payloadRoot(node){let current=node;while(current.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){current=current.object}return current.type===ast_node_types_1.AST_NODE_TYPES.Identifier?current:void 0}function createPayloadResolver(sourceCode){const resolve=createReceiverResolver(sourceCode);const program=sourceCode.ast;const scopes=[];walk(program,node=>{const handler=handlerSource(node,resolve);if(handler===void 0)return;scopes.push({source:handler.source,handler:handler.handler,range:handler.handler.range})});scopes.sort((a,b)=>a.range[1]-a.range[0]-(b.range[1]-b.range[0]));return node=>scopes.find(scope=>node.range[0]>=scope.range[0]&&node.range[1]<=scope.range[1]&&readsPayloadOf(node,scope.handler,sourceCode))?.source}function readsPayloadOf(node,handler,sourceCode){const root=payloadRoot(node);if(root===void 0)return false;const variable=findVariable(sourceCode.getScope(root),root.name);if(variable===void 0)return false;return variable.defs.some(definition=>definition.type==="Parameter"&&definition.node===handler)}function walk(node,visit){visit(node);for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];if(Array.isArray(value)){for(const child of value){if(isNode(child))walk(child,visit)}}else if(isNode(value)){walk(value,visit)}}}function isNode(value){return typeof value==="object"&&value!==null&&typeof value.type==="string"}
|
|
@@ -28,6 +28,26 @@ export interface SqlInjectionRuleConfig {
|
|
|
28
28
|
};
|
|
29
29
|
/** Method names treated as raw-SQL sinks, e.g. `['query']` or `['query', 'raw', 'execute']`. */
|
|
30
30
|
readonly methods: readonly string[];
|
|
31
|
+
/**
|
|
32
|
+
* Modules whose API these sinks belong to. **The rule stays silent in a file
|
|
33
|
+
* that imports none of them.**
|
|
34
|
+
*
|
|
35
|
+
* Method names are not evidence of an SDK. `['raw']` is knex *and* drizzle;
|
|
36
|
+
* `['query']` is typeorm *and* pg *and* mysql2; `['get','all','run']` is
|
|
37
|
+
* better-sqlite3 *and* an Express router *and* `Promise.all`. Measured over
|
|
38
|
+
* 73,364 files, that produced 1,142 lines where two or more plugins reported
|
|
39
|
+
* the *same* CWE — 616 for postgres×typeorm, 503 for mysql×typeorm, 347 for
|
|
40
|
+
* drizzle×knex, all from this one factory.
|
|
41
|
+
*
|
|
42
|
+
* Requiring the import makes the collision impossible by construction rather
|
|
43
|
+
* than deduplicated after the fact, and it is *local* evidence: no project
|
|
44
|
+
* scan, nothing to go stale, and a file that does not import the driver is
|
|
45
|
+
* one this rule genuinely has nothing to say about.
|
|
46
|
+
*
|
|
47
|
+
* Matched against the import specifier's package root, so `'mysql2/promise'`
|
|
48
|
+
* matches `'mysql2'` and `'@prisma/client/edge'` matches `'@prisma/client'`.
|
|
49
|
+
*/
|
|
50
|
+
readonly modules: readonly string[];
|
|
31
51
|
/**
|
|
32
52
|
* Require SQL keywords in the *static* part of the string before reporting.
|
|
33
53
|
* Precision guard for broad sink lists (`.raw()`, `.execute()` are not
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createSqlInjectionRule=createSqlInjectionRule;const ast_node_types_1=require("../ast-node-types");const messaging_1=require("../messaging");const SQL_KEYWORDS=/\b(?:select|insert|update|delete|drop|alter|truncate|union|from|where|values|set)\b/i;const FUNCTION_TYPES=new Set([ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration,ast_node_types_1.AST_NODE_TYPES.FunctionExpression,ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression]);function enclosingFunction(node){for(let n=node.parent;n;n=n.parent){if(FUNCTION_TYPES.has(n.type))return n}return void 0}function callableName(fn){if(fn.type===ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration&&fn.id)return fn.id.name;const parent=fn.parent;if(parent.type===ast_node_types_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return parent.id.name}if((parent.type===ast_node_types_1.AST_NODE_TYPES.MethodDefinition||parent.type===ast_node_types_1.AST_NODE_TYPES.PropertyDefinition||parent.type===ast_node_types_1.AST_NODE_TYPES.Property)&&parent.key.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return parent.key.name}return void 0}function staticText(node){if(node.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join(" ")}if(node.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression){return`${staticText(node.left)} ${staticText(node.right)}`}if(node.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}return""}function classify(node,requireSqlKeywords){let kind=false;if(node.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){kind="concat"}if(node.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral&&node.expressions.length>0){kind="template"}if(kind===false)return false;if(kind==="concat"&&staticText(node).trim()==="")return false;if(requireSqlKeywords&&!SQL_KEYWORDS.test(staticText(node)))return false;return kind}function createSqlInjectionRule(config){const sinks=new Set(config.methods);return{meta:{type:config.meta.type,docs:{...config.meta.docs},messages:{noUnsafeQuery:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"Unsafe SQL query detected. Variable interpolation found.",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:config.fix,documentationLink:config.documentationLink}),unsafeTemplateLiteral:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"Unsafe SQL query construction detected (template literal).",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:config.fix,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){const tainted=new Map;const sqlish=new Set;const wrappers=new Map;const definitions=new Map;const wrapperFns=new Map;const pending=[];const report=(node,kind)=>{context.report({node,messageId:kind==="template"?"unsafeTemplateLiteral":"noUnsafeQuery"})};return{"FunctionDeclaration, FunctionExpression, ArrowFunctionExpression"(node){const name=callableName(node);if(name!==void 0)definitions.set(name,(definitions.get(name)??0)+1)},VariableDeclarator(node){if(node.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&node.init){const kind=classify(node.init,config.requireSqlKeywords);if(kind)tainted.set(node.id.name,kind);if(SQL_KEYWORDS.test(staticText(node.init)))sqlish.add(node.id.name)}},AssignmentExpression(node){if(node.operator==="+="&&node.left.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const gate=config.requireSqlKeywords&&!sqlish.has(node.left.name);const kind=classify(node.right,gate);if(kind)tainted.set(node.left.name,kind);if(SQL_KEYWORDS.test(staticText(node.right)))sqlish.add(node.left.name)}},CallExpression(node){const isMember=node.callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier;const calleeName=isMember?node.callee.property.name:node.callee.type===ast_node_types_1.AST_NODE_TYPES.Identifier?node.callee.name:void 0;if(calleeName===void 0)return;if(!isMember||!sinks.has(calleeName)){for(const[index,arg]of node.arguments.entries()){if(arg.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;const kind=classify(arg,true);if(kind)pending.push({name:calleeName,index,arg,kind});else if(arg.type===ast_node_types_1.AST_NODE_TYPES.Identifier)pending.push({name:calleeName,index,arg,kind:void 0})}return}const queryArg=node.arguments[0];if(!queryArg)return;if(queryArg.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const fn=enclosingFunction(node);const index=fn?.params.findIndex(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&p.name===queryArg.name)??-1;const name=fn&&index>=0?callableName(fn):void 0;if(name!==void 0&&fn){wrappers.set(name,index);wrapperFns.set(fn,name)}}const direct=classify(queryArg,config.requireSqlKeywords);if(direct){report(queryArg,direct);return}if(queryArg.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const taint=tainted.get(queryArg.name);if(taint)report(queryArg,taint)}},"Program:exit"(){const proven=new Map;for(const name of wrapperFns.values())proven.set(name,(proven.get(name)??0)+1);for(const{name,index,arg,kind}of pending){if(wrappers.get(name)!==index)continue;if(definitions.get(name)!==proven.get(name))continue;if(kind){report(arg,kind);continue}const varName=arg.name;const taint=tainted.get(varName);if(taint&&sqlish.has(varName))report(arg,taint)}}}}}}
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createSqlInjectionRule=createSqlInjectionRule;const ast_node_types_1=require("../ast-node-types");const messaging_1=require("../messaging");const SQL_KEYWORDS=/\b(?:select|insert|update|delete|drop|alter|truncate|union|from|where|values|set)\b/i;const FUNCTION_TYPES=new Set([ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration,ast_node_types_1.AST_NODE_TYPES.FunctionExpression,ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression]);function enclosingFunction(node){for(let n=node.parent;n;n=n.parent){if(FUNCTION_TYPES.has(n.type))return n}return void 0}function callableName(fn){if(fn.type===ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration&&fn.id)return fn.id.name;const parent=fn.parent;if(parent.type===ast_node_types_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return parent.id.name}if((parent.type===ast_node_types_1.AST_NODE_TYPES.MethodDefinition||parent.type===ast_node_types_1.AST_NODE_TYPES.PropertyDefinition||parent.type===ast_node_types_1.AST_NODE_TYPES.Property)&&parent.key.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return parent.key.name}return void 0}function staticText(node){if(node.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join(" ")}if(node.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression){return`${staticText(node.left)} ${staticText(node.right)}`}if(node.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}return""}function classify(node,requireSqlKeywords){let kind=false;if(node.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){kind="concat"}if(node.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral&&node.expressions.length>0){kind="template"}if(kind===false)return false;if(kind==="concat"&&staticText(node).trim()==="")return false;if(requireSqlKeywords&&!SQL_KEYWORDS.test(staticText(node)))return false;return kind}function createSqlInjectionRule(config){const sinks=new Set(config.methods);const owned=new Set(config.modules);const owns=specifier=>{if(specifier.startsWith(".")||specifier.startsWith("/"))return false;const parts=specifier.split("/");const root=specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0];return owned.has(root)};return{meta:{type:config.meta.type,docs:{...config.meta.docs},messages:{noUnsafeQuery:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"Unsafe SQL query detected. Variable interpolation found.",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:config.fix,documentationLink:config.documentationLink}),unsafeTemplateLiteral:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"Unsafe SQL query construction detected (template literal).",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:config.fix,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){const tainted=new Map;const sqlish=new Set;const wrappers=new Map;const definitions=new Map;const wrapperFns=new Map;const pending=[];let ownsFile=false;const report=(node,kind)=>{if(!ownsFile)return;context.report({node,messageId:kind==="template"?"unsafeTemplateLiteral":"noUnsafeQuery"})};return{Program(program){ownsFile=program.body.some(stmt=>stmt.type===ast_node_types_1.AST_NODE_TYPES.ImportDeclaration&&owns(stmt.source.value))},"FunctionDeclaration, FunctionExpression, ArrowFunctionExpression"(node){const name=callableName(node);if(name!==void 0)definitions.set(name,(definitions.get(name)??0)+1)},VariableDeclarator(node){if(node.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&node.init){const kind=classify(node.init,config.requireSqlKeywords);if(kind)tainted.set(node.id.name,kind);if(SQL_KEYWORDS.test(staticText(node.init)))sqlish.add(node.id.name)}},AssignmentExpression(node){if(node.operator==="+="&&node.left.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const gate=config.requireSqlKeywords&&!sqlish.has(node.left.name);const kind=classify(node.right,gate);if(kind)tainted.set(node.left.name,kind);if(SQL_KEYWORDS.test(staticText(node.right)))sqlish.add(node.left.name)}},CallExpression(node){const isMember=node.callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier;const calleeName=isMember?node.callee.property.name:node.callee.type===ast_node_types_1.AST_NODE_TYPES.Identifier?node.callee.name:void 0;if(calleeName===void 0)return;if(!isMember||!sinks.has(calleeName)){for(const[index,arg]of node.arguments.entries()){if(arg.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;const kind=classify(arg,true);if(kind)pending.push({name:calleeName,index,arg,kind});else if(arg.type===ast_node_types_1.AST_NODE_TYPES.Identifier)pending.push({name:calleeName,index,arg,kind:void 0})}return}const queryArg=node.arguments[0];if(!queryArg)return;if(queryArg.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const fn=enclosingFunction(node);const index=fn?.params.findIndex(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&p.name===queryArg.name)??-1;const name=fn&&index>=0?callableName(fn):void 0;if(name!==void 0&&fn){wrappers.set(name,index);wrapperFns.set(fn,name)}}const direct=classify(queryArg,config.requireSqlKeywords);if(direct){report(queryArg,direct);return}if(queryArg.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const taint=tainted.get(queryArg.name);if(taint)report(queryArg,taint)}},"Program:exit"(){const proven=new Map;for(const name of wrapperFns.values())proven.set(name,(proven.get(name)??0)+1);for(const{name,index,arg,kind}of pending){if(wrappers.get(name)!==index)continue;if(definitions.get(name)!==proven.get(name))continue;if(kind){report(arg,kind);continue}const varName=arg.name;const taint=tainted.get(varName);if(taint&&sqlish.has(varName))report(arg,taint)}}}}}}
|