@interlace/eslint-devkit 1.20.3 → 1.21.1

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 CHANGED
@@ -552,7 +552,6 @@ Part of the **Interlace ESLint ecosystem** — AI-native rules with LLM-optimize
552
552
 
553
553
  | Plugin | Downloads | Description |
554
554
  | :--- | :---: | :--- |
555
- | [`eslint-plugin-cli-floor`](https://www.npmjs.com/package/eslint-plugin-cli-floor) | [![downloads](https://img.shields.io/npm/dt/eslint-plugin-cli-floor.svg?style=flat-square)](https://www.npmjs.com/package/eslint-plugin-cli-floor) | CLI floor for commander, yargs and burgee. |
556
555
  | [`eslint-plugin-conventions`](https://www.npmjs.com/package/eslint-plugin-conventions) | [![downloads](https://img.shields.io/npm/dt/eslint-plugin-conventions.svg?style=flat-square)](https://www.npmjs.com/package/eslint-plugin-conventions) | Team-specific habits and styles. |
557
556
  | [`eslint-plugin-import-next`](https://www.npmjs.com/package/eslint-plugin-import-next) | [![downloads](https://img.shields.io/npm/dt/eslint-plugin-import-next.svg?style=flat-square)](https://www.npmjs.com/package/eslint-plugin-import-next) | Fast cycle + import-graph analysis. |
558
557
  | [`eslint-plugin-maintainability`](https://www.npmjs.com/package/eslint-plugin-maintainability) | [![downloads](https://img.shields.io/npm/dt/eslint-plugin-maintainability.svg?style=flat-square)](https://www.npmjs.com/package/eslint-plugin-maintainability) | Cognitive load and clean-code patterns. |
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@interlace/eslint-devkit",
3
- "version": "1.20.3",
3
+ "version": "1.21.1",
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",
@@ -71,6 +71,9 @@
71
71
  "typescript": ">=4.8.4"
72
72
  },
73
73
  "peerDependenciesMeta": {
74
+ "eslint": {
75
+ "optional": true
76
+ },
74
77
  "@typescript-eslint/utils": {
75
78
  "optional": true
76
79
  },
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.resolveModuleBinding=resolveModuleBinding;exports.isModuleBinding=isModuleBinding;const spellings_1=require("./spellings");const ast_node_types_1=require("../ast-node-types");function normalize(specifier,options){const bare=specifier.startsWith("node:")?specifier.slice("node:".length):specifier;return options.equivalents?.[bare]??bare}function requireTarget(node,options){if(node.type!==ast_node_types_1.AST_NODE_TYPES.CallExpression)return void 0;if(node.callee.type!==ast_node_types_1.AST_NODE_TYPES.Identifier||node.callee.name!=="require")return void 0;const[arg]=node.arguments;if(arg?.type!==ast_node_types_1.AST_NODE_TYPES.Literal)return void 0;return typeof arg.value==="string"?normalize(arg.value,options):void 0}function destructuredKey(pattern,boundName){if(pattern.type!==ast_node_types_1.AST_NODE_TYPES.ObjectPattern)return void 0;for(const property of pattern.properties){if(property.type!==ast_node_types_1.AST_NODE_TYPES.Property)continue;if(property.value.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)continue;if(property.value.name!==boundName)continue;return(0,spellings_1.objectKeyName)(property)??void 0}return void 0}function lookup(name,scope){for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable}return void 0}function resolveModuleBinding(node,scope,options={}){return resolve(node,scope,options,new Set)}function resolve(node,scope,options,seen){if(seen.has(node))return void 0;seen.add(node);const required=requireTarget(node,options);if(required!==void 0)return{module:required,path:[]};if(node.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){const property=(0,spellings_1.propertyName)(node);if(property===null)return void 0;const base2=resolve(node.object,scope,options,seen);return base2&&{module:base2.module,path:[...base2.path,property]}}if(node.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return void 0;const variable=lookup(node.name,scope);const def=variable?.defs[0];if(!def)return void 0;if(def.type==="ImportBinding"){const declaration=def.parent;if(declaration?.type!==ast_node_types_1.AST_NODE_TYPES.ImportDeclaration)return void 0;const module=normalize(String(declaration.source.value),options);if(def.node.type===ast_node_types_1.AST_NODE_TYPES.ImportSpecifier){const imported=def.node.imported;const name=imported.type===ast_node_types_1.AST_NODE_TYPES.Identifier?imported.name:String(imported.value);return{module,path:[name]}}return{module,path:[]}}if(def.type!=="Variable"||!def.node.init)return void 0;if(variable&&variable.references.filter(ref=>ref.isWrite()).length!==1)return void 0;const base=resolve(def.node.init,scope,options,seen);if(!base)return void 0;if(def.node.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return base;const key=destructuredKey(def.node.id,node.name);return key===void 0?void 0:{module:base.module,path:[...base.path,key]}}function isModuleBinding(node,scope,module,exportPath,options={}){const binding=resolveModuleBinding(node,scope,options);if(!binding||binding.module!==module)return false;if(!exportPath)return true;return binding.path.length===exportPath.length&&exportPath.every((part,i)=>binding.path[i]===part)}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.resolveModuleBinding=resolveModuleBinding;exports.isModuleBinding=isModuleBinding;const spellings_1=require("./spellings");const ast_node_types_1=require("../ast-node-types");function normalize(specifier,options){const bare=specifier.startsWith("node:")?specifier.slice("node:".length):specifier;return options.equivalents?.[bare]??bare}function requireTarget(node,options){if(node.type!==ast_node_types_1.AST_NODE_TYPES.CallExpression)return void 0;if(node.callee.type!==ast_node_types_1.AST_NODE_TYPES.Identifier||node.callee.name!=="require")return void 0;const[arg]=node.arguments;if(arg?.type!==ast_node_types_1.AST_NODE_TYPES.Literal)return void 0;return typeof arg.value==="string"?normalize(arg.value,options):void 0}function destructuredPath(pattern,boundName){if(pattern.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return pattern.name===boundName?[]:void 0;if(pattern.type===ast_node_types_1.AST_NODE_TYPES.AssignmentPattern)return destructuredPath(pattern.left,boundName);if(pattern.type!==ast_node_types_1.AST_NODE_TYPES.ObjectPattern)return void 0;for(const property of pattern.properties){const value=property.type===ast_node_types_1.AST_NODE_TYPES.RestElement?property.argument:property.value;const inner=destructuredPath(value,boundName);if(inner===void 0)continue;if(property.type===ast_node_types_1.AST_NODE_TYPES.RestElement)return inner;const key=(0,spellings_1.objectKeyName)(property);return key===null?void 0:[key,...inner]}return void 0}function lookup(name,scope){for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable}return void 0}function resolveModuleBinding(node,scope,options={}){return resolve(node,scope,options,new Set)}function resolve(node,scope,options,seen){if(seen.has(node))return void 0;seen.add(node);const required=requireTarget(node,options);if(required!==void 0){const declared=(lookup("require",scope)?.defs.length??0)>0;return declared?void 0:{module:required,path:[]}}if(node.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){const property=(0,spellings_1.propertyName)(node);if(property===null)return void 0;const base2=resolve(node.object,scope,options,seen);return base2&&{module:base2.module,path:[...base2.path,property]}}if(node.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return void 0;const variable=lookup(node.name,scope);const def=variable?.defs[0];if(!variable||!def)return void 0;if(def.type==="ImportBinding"){const declaration=def.parent;if(declaration.type===ast_node_types_1.AST_NODE_TYPES.TSImportEqualsDeclaration){const reference=declaration.moduleReference;if(reference.type!==ast_node_types_1.AST_NODE_TYPES.TSExternalModuleReference)return void 0;return{module:normalize(reference.expression.value,options),path:[]}}const module=normalize(String(declaration.source.value),options);if(def.node.type===ast_node_types_1.AST_NODE_TYPES.ImportSpecifier){const imported=def.node.imported;const name=imported.type===ast_node_types_1.AST_NODE_TYPES.Identifier?imported.name:String(imported.value);return{module,path:[name]}}return{module,path:[]}}if(def.type!=="Variable"||!def.node.init)return void 0;if(variable.defs.length!==1||variable.references.some(ref=>ref.isWrite()&&!ref.init)){return void 0}const base=resolve(def.node.init,scope,options,seen);if(!base)return void 0;const keys=destructuredPath(def.node.id,node.name);return keys&&{module:base.module,path:[...base.path,...keys]}}function isModuleBinding(node,scope,module,exportPath,options={}){const binding=resolveModuleBinding(node,scope,options);if(!binding||binding.module!==module)return false;if(!exportPath)return true;return binding.path.length===exportPath.length&&exportPath.every((part,i)=>binding.path[i]===part)}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isStaticExpression=isStaticExpression;const ast_node_types_1=require("../ast-node-types");const PATH_MODULES=new Set(["path","node:path","path/posix","path/win32","node:path/posix","node:path/win32"]);const PATH_METHODS=new Set(["basename","dirname","extname","join","normalize","relative","resolve","format","toNamespacedPath"]);const PATH_CONSTANTS=new Set(["sep","delimiter"]);const IMPORT_META_STATIC=new Set(["url","dirname","filename"]);const cache=new WeakMap;function resolveConstInit(name,scope){for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(!variable)continue;const writes=variable.references.filter(ref=>ref.isWrite());if(writes.length!==1)return void 0;const[def]=variable.defs;if(!def||def.type!=="Variable")return void 0;if(!def.node.init)return void 0;return{init:def.node.init,scope:current}}return void 0}const MODULE_LOCATION_GLOBALS=new Set(["__dirname","__filename"]);const MODULE_LOADER_GLOBALS=new Set(["require"]);function isModuleLocationGlobal(name,scope,allowed=MODULE_LOCATION_GLOBALS){if(!allowed.has(name))return false;for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable.defs.length===0}return true}function isPathModuleReference(object,scope){if(object.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return false;for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===object.name);if(!variable)continue;const[def]=variable.defs;if(!def)return false;if(def.type==="ImportBinding"){const declaration=def.parent;if(declaration?.type!==ast_node_types_1.AST_NODE_TYPES.ImportDeclaration)return false;const source=declaration.source.value;return typeof source==="string"&&PATH_MODULES.has(source)}if(def.type==="Variable"&&def.node.init?.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){const call=def.node.init;if(call.callee.type!==ast_node_types_1.AST_NODE_TYPES.Identifier||call.callee.name!=="require")return false;const[arg]=call.arguments;return arg?.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof arg.value==="string"&&PATH_MODULES.has(arg.value)}return false}return false}function isStaticExpression({node,scope,treatConstAsStatic=true}){const cacheable=treatConstAsStatic;if(cacheable){const hit=cache.get(node);if(hit!==void 0)return hit}const result=evaluate(node,scope,treatConstAsStatic,new Set);if(cacheable)cache.set(node,result);return result}function evaluate(node,scope,treatConstAsStatic,seen){if(seen.has(node))return false;seen.add(node);try{return evaluateNode(node,scope,treatConstAsStatic,seen)}finally{seen.delete(node)}}function evaluateNode(node,scope,treatConstAsStatic,seen){switch(node.type){case ast_node_types_1.AST_NODE_TYPES.Literal:return true;case ast_node_types_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.every(expression=>evaluate(expression,scope,treatConstAsStatic,seen));case ast_node_types_1.AST_NODE_TYPES.BinaryExpression:if(node.operator==="in"||node.operator==="instanceof")return false;return evaluate(node.left,scope,treatConstAsStatic,seen)&&evaluate(node.right,scope,treatConstAsStatic,seen);case ast_node_types_1.AST_NODE_TYPES.UnaryExpression:return evaluate(node.argument,scope,treatConstAsStatic,seen);case ast_node_types_1.AST_NODE_TYPES.ConditionalExpression:return evaluate(node.consequent,scope,treatConstAsStatic,seen)&&evaluate(node.alternate,scope,treatConstAsStatic,seen);case ast_node_types_1.AST_NODE_TYPES.TSAsExpression:case ast_node_types_1.AST_NODE_TYPES.TSSatisfiesExpression:case ast_node_types_1.AST_NODE_TYPES.TSNonNullExpression:return evaluate(node.expression,scope,treatConstAsStatic,seen);case ast_node_types_1.AST_NODE_TYPES.Identifier:{if(isModuleLocationGlobal(node.name,scope))return true;if(!treatConstAsStatic)return false;const resolved=resolveConstInit(node.name,scope);if(!resolved)return false;return evaluate(resolved.init,resolved.scope,treatConstAsStatic,seen)}case ast_node_types_1.AST_NODE_TYPES.MemberExpression:{if(node.computed)return false;if(node.property.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return false;if(node.object.type===ast_node_types_1.AST_NODE_TYPES.MetaProperty&&node.object.meta.name==="import"&&node.object.property.name==="meta"){return IMPORT_META_STATIC.has(node.property.name)}return PATH_CONSTANTS.has(node.property.name)&&isPathModuleReference(node.object,scope)}case ast_node_types_1.AST_NODE_TYPES.CallExpression:{const{callee}=node;if(callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression||callee.computed)return false;if(callee.property.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return false;if(callee.object.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&callee.object.name==="require"&&callee.property.name==="resolve"&&isModuleLocationGlobal("require",scope,MODULE_LOADER_GLOBALS)){return node.arguments.every(argument=>argument.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement&&evaluate(argument,scope,treatConstAsStatic,seen))}if(!PATH_METHODS.has(callee.property.name))return false;if(!isPathModuleReference(callee.object,scope))return false;return node.arguments.every(argument=>argument.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement&&evaluate(argument,scope,treatConstAsStatic,seen))}default:return false}}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isStaticExpression=isStaticExpression;const ast_node_types_1=require("../ast-node-types");const module_binding_1=require("./module-binding");const spellings_1=require("./spellings");const PATH_MODULES=new Set(["path","path/posix","path/win32"]);const PATH_NAMESPACES=new Set(["posix","win32"]);const PATH_METHODS=new Set(["basename","dirname","extname","join","normalize","relative","resolve","format","toNamespacedPath"]);const PATH_CONSTANTS=new Set(["sep","delimiter"]);const IMPORT_META_STATIC=new Set(["url","dirname","filename"]);const cache=new WeakMap;function resolveConstInit(name,scope){for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(!variable)continue;const writes=variable.references.filter(ref=>ref.isWrite());if(writes.length!==1)return void 0;const[def]=variable.defs;if(!def||def.type!=="Variable")return void 0;if(!def.node.init)return void 0;return{init:def.node.init,scope:current}}return void 0}const MODULE_LOCATION_GLOBALS=new Set(["__dirname","__filename"]);const MODULE_LOADER_GLOBALS=new Set(["require"]);function isModuleLocationGlobal(name,scope,allowed=MODULE_LOCATION_GLOBALS){if(!allowed.has(name))return false;for(let current=scope;current;current=current.upper){const variable=current.variables.find(v=>v.name===name);if(variable)return variable.defs.length===0}return true}function isPathMember(node,scope,members){const binding=(0,module_binding_1.resolveModuleBinding)(node,scope);if(!binding||!PATH_MODULES.has(binding.module))return false;const[first,...rest]=binding.path;const[member,...extra]=first!==void 0&&PATH_NAMESPACES.has(first)?rest:binding.path;return member!==void 0&&extra.length===0&&members.has(member)}function isStaticExpression({node,scope,treatConstAsStatic=true}){const cacheable=treatConstAsStatic;if(cacheable){const hit=cache.get(node);if(hit!==void 0)return hit}const result=evaluate(node,scope,treatConstAsStatic,new Set);if(cacheable)cache.set(node,result);return result}function evaluate(node,scope,treatConstAsStatic,seen){if(seen.has(node))return false;seen.add(node);try{return evaluateNode(node,scope,treatConstAsStatic,seen)}finally{seen.delete(node)}}function evaluateNode(node,scope,treatConstAsStatic,seen){switch(node.type){case ast_node_types_1.AST_NODE_TYPES.Literal:return true;case ast_node_types_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.every(expression=>evaluate(expression,scope,treatConstAsStatic,seen));case ast_node_types_1.AST_NODE_TYPES.BinaryExpression:if(node.operator==="in"||node.operator==="instanceof")return false;return evaluate(node.left,scope,treatConstAsStatic,seen)&&evaluate(node.right,scope,treatConstAsStatic,seen);case ast_node_types_1.AST_NODE_TYPES.UnaryExpression:return evaluate(node.argument,scope,treatConstAsStatic,seen);case ast_node_types_1.AST_NODE_TYPES.ConditionalExpression:return evaluate(node.consequent,scope,treatConstAsStatic,seen)&&evaluate(node.alternate,scope,treatConstAsStatic,seen);case ast_node_types_1.AST_NODE_TYPES.TSAsExpression:case ast_node_types_1.AST_NODE_TYPES.TSSatisfiesExpression:case ast_node_types_1.AST_NODE_TYPES.TSNonNullExpression:return evaluate(node.expression,scope,treatConstAsStatic,seen);case ast_node_types_1.AST_NODE_TYPES.Identifier:{if(isModuleLocationGlobal(node.name,scope))return true;if(!treatConstAsStatic)return false;const resolved=resolveConstInit(node.name,scope);if(!resolved)return false;return evaluate(resolved.init,resolved.scope,treatConstAsStatic,seen)}case ast_node_types_1.AST_NODE_TYPES.MemberExpression:{if(node.object.type===ast_node_types_1.AST_NODE_TYPES.MetaProperty&&node.object.meta.name==="import"&&node.object.property.name==="meta"){const name=(0,spellings_1.propertyName)(node);return name!==null&&IMPORT_META_STATIC.has(name)}return isPathMember(node,scope,PATH_CONSTANTS)}case ast_node_types_1.AST_NODE_TYPES.CallExpression:{const{callee}=node;const isRequireResolve=callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&callee.object.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&callee.object.name==="require"&&(0,spellings_1.propertyName)(callee)==="resolve"&&isModuleLocationGlobal("require",scope,MODULE_LOADER_GLOBALS);if(!isRequireResolve&&!isPathMember(callee,scope,PATH_METHODS))return false;return node.arguments.every(argument=>argument.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement&&evaluate(argument,scope,treatConstAsStatic,seen))}default:return false}}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BROWSER_ESCAPE_FLAG=void 0;exports.credentialOrigin=credentialOrigin;exports.readFlag=readFlag;exports.createBrowserEscapeHatchRule=createBrowserEscapeHatchRule;const rule_creator_1=require("./rule-creator");const messaging_1=require("../messaging");const module_evidence_1=require("./module-evidence");const ast_node_types_1=require("../ast-node-types");const type_syntax_1=require("../ast/type-syntax");const sdk_flow_1=require("./sdk-flow");exports.BROWSER_ESCAPE_FLAG="dangerouslyAllowBrowser";function credentialOrigin(node,sourceCode,hops=sdk_flow_1.MAX_FOLLOW_HOPS){const current=(0,type_syntax_1.unwrapTypeSyntax)(node);if(hops<=0)return"shipped";const either=(a,b)=>credentialOrigin(a,sourceCode,hops-1)==="shipped"||credentialOrigin(b,sourceCode,hops-1)==="shipped"?"shipped":"runtime";switch(current.type){case ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression:case ast_node_types_1.AST_NODE_TYPES.FunctionExpression:case ast_node_types_1.AST_NODE_TYPES.AwaitExpression:case ast_node_types_1.AST_NODE_TYPES.CallExpression:case ast_node_types_1.AST_NODE_TYPES.NewExpression:return"runtime";case ast_node_types_1.AST_NODE_TYPES.ConditionalExpression:return either(current.consequent,current.alternate);case ast_node_types_1.AST_NODE_TYPES.LogicalExpression:return either(current.left,current.right);case ast_node_types_1.AST_NODE_TYPES.MemberExpression:return(0,sdk_flow_1.isEnvironmentRead)(current,sourceCode)?"shipped":credentialOrigin(current.object,sourceCode,hops-1);case ast_node_types_1.AST_NODE_TYPES.Identifier:{const variable=(0,sdk_flow_1.variableOf)(current,sourceCode);const definition=variable?.defs[0];if(definition===void 0)return"shipped";if(definition.type==="Parameter"||definition.type==="FunctionName"){return"runtime"}const init=definition.type==="Variable"?definition.node.init:null;return init===null?"shipped":credentialOrigin(init,sourceCode,hops-1)}default:return"shipped"}}function isFlagProperty(prop){return prop.type!=="SpreadElement"&&!prop.computed&&(prop.key.type==="Identifier"&&prop.key.name===exports.BROWSER_ESCAPE_FLAG||prop.key.type==="Literal"&&prop.key.value===exports.BROWSER_ESCAPE_FLAG)}function readFlag(options){const props=options.properties;const index=props.findIndex(isFlagProperty);if(index===-1){return props.some(prop=>prop.type==="SpreadElement")?"unreadable":"absent"}for(let i=index+1;i<props.length;i++){if(props[i].type==="SpreadElement")return"unreadable"}const value=props[index].value;if(value.type==="Literal"&&value.value===true)return"enabled";if(value.type==="Literal")return"absent";return"unreadable"}function createBrowserEscapeHatchRule(config){const usesSdk=(0,module_evidence_1.createModuleListEvidence)(config.modules);const matcher=(0,sdk_flow_1.createSdkClientMatcher)((0,module_evidence_1.createModuleListMatcher)(config.modules));const credentialProps=config.credentialProps??["apiKey"];const tokenProviderProps=config.tokenProviderProps??["azureADTokenProvider"];return(0,rule_creator_1.createRule)({name:config.ruleName,meta:{type:"problem",docs:{url:config.docsUrl,description:`Forbid ${exports.BROWSER_ESCAPE_FLAG}, which exposes the ${config.vendor} API key to the client`,cwe:"CWE-522",cvss:8.6},messages:{browserKeyExposure:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:`${config.vendor} API Key Exposed to the Browser`,cwe:"CWE-522",owasp:"A07:2021",cvss:8.6,description:"dangerouslyAllowBrowser lets the SDK run client-side, which ships the API key to every visitor",severity:"HIGH",compliance:["SOC2","PCI-DSS"],fix:`Call ${config.vendor} from a server route and forward the result, so the key never leaves the server`,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){if(!usesSdk(context.sourceCode.ast))return{};const sourceCode=context.sourceCode;function flagEnabled(options){const read=(0,sdk_flow_1.readObjectProperty)(options,exports.BROWSER_ESCAPE_FLAG,sourceCode);if(read.kind!=="value")return false;const value=(0,sdk_flow_1.followConst)(read.node,sourceCode);return value.type===ast_node_types_1.AST_NODE_TYPES.Literal&&value.value===true}function hasTokenProvider(options){return tokenProviderProps.some(prop=>{const read=(0,sdk_flow_1.readObjectProperty)(options,prop,sourceCode);if(read.kind!=="value")return false;const value=(0,sdk_flow_1.followConst)(read.node,sourceCode);return!(value.type===ast_node_types_1.AST_NODE_TYPES.Literal||value.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&value.name==="undefined")})}function credentialIsRuntime(options){const values=credentialProps.map(prop=>(0,sdk_flow_1.readObjectProperty)(options,prop,sourceCode)).flatMap(read=>read.kind==="value"?[read.node]:[]);return values.length>0&&values.every(value=>credentialOrigin(value,sourceCode)==="runtime")}function inspect(node){for(const index of matcher.optionArguments(node,sourceCode)){const argument=node.arguments[index];if(argument===void 0||argument.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;const options=(0,sdk_flow_1.resolveObjectLiteral)(argument,sourceCode);if(options===void 0||!flagEnabled(options))continue;if(hasTokenProvider(options)||credentialIsRuntime(options)){continue}context.report({node,messageId:"browserKeyExposure"});return}}return{NewExpression:inspect,CallExpression:inspect}}})}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BROWSER_ESCAPE_FLAG=void 0;exports.credentialOrigin=credentialOrigin;exports.readFlag=readFlag;exports.createBrowserEscapeHatchRule=createBrowserEscapeHatchRule;const rule_creator_1=require("./rule-creator");const messaging_1=require("../messaging");const module_evidence_1=require("./module-evidence");const ast_node_types_1=require("../ast-node-types");const type_syntax_1=require("../ast/type-syntax");const sdk_flow_1=require("./sdk-flow");exports.BROWSER_ESCAPE_FLAG="dangerouslyAllowBrowser";function credentialOrigin(node,sourceCode,hops=sdk_flow_1.MAX_FOLLOW_HOPS){const current=(0,type_syntax_1.unwrapTypeSyntax)(node);if(hops<=0)return"shipped";const either=(a,b)=>credentialOrigin(a,sourceCode,hops-1)==="shipped"||credentialOrigin(b,sourceCode,hops-1)==="shipped"?"shipped":"runtime";switch(current.type){case ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression:case ast_node_types_1.AST_NODE_TYPES.FunctionExpression:case ast_node_types_1.AST_NODE_TYPES.AwaitExpression:case ast_node_types_1.AST_NODE_TYPES.CallExpression:case ast_node_types_1.AST_NODE_TYPES.NewExpression:return"runtime";case ast_node_types_1.AST_NODE_TYPES.ConditionalExpression:return either(current.consequent,current.alternate);case ast_node_types_1.AST_NODE_TYPES.LogicalExpression:return either(current.left,current.right);case ast_node_types_1.AST_NODE_TYPES.MemberExpression:return(0,sdk_flow_1.isEnvironmentRead)(current,sourceCode)?"shipped":credentialOrigin(current.object,sourceCode,hops-1);case ast_node_types_1.AST_NODE_TYPES.Identifier:{const variable=(0,sdk_flow_1.variableOf)(current,sourceCode);const definition=variable?.defs[0];if(definition===void 0)return"shipped";if(definition.type==="Parameter"||definition.type==="FunctionName"){return"runtime"}const init=definition.type==="Variable"?definition.node.init:null;return init===null?"shipped":credentialOrigin(init,sourceCode,hops-1)}default:return"shipped"}}function isFlagProperty(prop){return prop.type!=="SpreadElement"&&!prop.computed&&(prop.key.type==="Identifier"&&prop.key.name===exports.BROWSER_ESCAPE_FLAG||prop.key.type==="Literal"&&prop.key.value===exports.BROWSER_ESCAPE_FLAG)}function readFlag(options){const props=options.properties;const index=props.findIndex(isFlagProperty);if(index===-1){return props.some(prop=>prop.type==="SpreadElement")?"unreadable":"absent"}for(let i=index+1;i<props.length;i++){if(props[i].type==="SpreadElement")return"unreadable"}const value=props[index].value;if(value.type==="Literal"&&value.value===true)return"enabled";if(value.type==="Literal")return"absent";return"unreadable"}function createBrowserEscapeHatchRule(config){const usesSdk=(0,module_evidence_1.createModuleListEvidence)(config.modules);const matcher=(0,sdk_flow_1.createSdkClientMatcher)((0,module_evidence_1.createModuleListMatcher)(config.modules));const credentialProps=config.credentialProps??["apiKey"];const tokenProviderProps=config.tokenProviderProps??["azureADTokenProvider"];return(0,rule_creator_1.createRule)({name:config.ruleName,meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:config.docsUrl,description:`Forbid ${exports.BROWSER_ESCAPE_FLAG}, which exposes the ${config.vendor} API key to the client`,cwe:"CWE-522",cvss:8.6},messages:{browserKeyExposure:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:`${config.vendor} API Key Exposed to the Browser`,cwe:"CWE-522",owasp:"A07:2021",cvss:8.6,description:"dangerouslyAllowBrowser lets the SDK run client-side, which ships the API key to every visitor",severity:"HIGH",compliance:["SOC2","PCI-DSS"],fix:`Call ${config.vendor} from a server route and forward the result, so the key never leaves the server`,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],createOnce(context){let sourceCode;function flagEnabled(options){const read=(0,sdk_flow_1.readObjectProperty)(options,exports.BROWSER_ESCAPE_FLAG,sourceCode);if(read.kind!=="value")return false;const value=(0,sdk_flow_1.followConst)(read.node,sourceCode);return value.type===ast_node_types_1.AST_NODE_TYPES.Literal&&value.value===true}function hasTokenProvider(options){return tokenProviderProps.some(prop=>{const read=(0,sdk_flow_1.readObjectProperty)(options,prop,sourceCode);if(read.kind!=="value")return false;const value=(0,sdk_flow_1.followConst)(read.node,sourceCode);return!(value.type===ast_node_types_1.AST_NODE_TYPES.Literal||value.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&value.name==="undefined")})}function credentialIsRuntime(options){const values=credentialProps.map(prop=>(0,sdk_flow_1.readObjectProperty)(options,prop,sourceCode)).flatMap(read=>read.kind==="value"?[read.node]:[]);return values.length>0&&values.every(value=>credentialOrigin(value,sourceCode)==="runtime")}function inspect(node){for(const index of matcher.optionArguments(node,sourceCode)){const argument=node.arguments[index];if(argument===void 0||argument.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;const options=(0,sdk_flow_1.resolveObjectLiteral)(argument,sourceCode);if(options===void 0||!flagEnabled(options))continue;if(hasTokenProvider(options)||credentialIsRuntime(options)){continue}context.report({node,messageId:"browserKeyExposure"});return}}return{before(){if(!usesSdk(context.sourceCode.ast))return false;sourceCode=context.sourceCode;return true},NewExpression:inspect,CallExpression:inspect}}})}
@@ -1,8 +1,3 @@
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
1
  import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
7
2
  import { type ConfigShape } from './connection-config';
8
3
  /**
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.urlEmbedsCredentials=urlEmbedsCredentials;exports.staticStringValue=staticStringValue;exports.isLiteralSecret=isLiteralSecret;exports.createHardcodedCredentialsRule=createHardcodedCredentialsRule;exports.urlPrefix=urlPrefix;const ast_node_types_1=require("../ast-node-types");const messaging_1=require("../messaging");const unscoped_mutation_rule_1=require("./unscoped-mutation-rule");const module_evidence_1=require("./module-evidence");const rule_creator_1=require("./rule-creator");const driver_origin_1=require("./driver-origin");const connection_config_1=require("./connection-config");const value_follow_1=require("./value-follow");const require_tls_rule_1=require("./require-tls-rule");const CREDENTIAL_KEYS=["password","pass","pwd","secret","passwd","auth"];const DEFAULT_CONNECTION_KEYS=["host","hostname","port","database","connectionString","socketPath","uri","url","connection","pool","schema"];function urlEmbedsCredentials(value,schemes){const match=/^([a-z][a-z0-9+.-]*):\/\/([^/@\s:]*:[^/@\s]+)@/i.exec(value);if(match===null)return false;return schemes.some(scheme=>scheme.toLowerCase()===match[1].toLowerCase())}function staticStringValue(node){if(node.type===ast_node_types_1.AST_NODE_TYPES.Literal){return typeof node.value==="string"?node.value:void 0}if(node.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral&&node.expressions.length===0){const[{value}]=node.quasis;return value.cooked??value.raw}return void 0}function isLiteralSecret(node){const value=staticStringValue(node);return value!==void 0&&value.length>0}function createHardcodedCredentialsRule(config){const connectionKeys=[...DEFAULT_CONNECTION_KEYS,...config.connectionKeys??[]];const isConfigShape=(0,connection_config_1.configShapeEvidence)(config.configShapes??[]);const usesModule=(0,module_evidence_1.createModuleEvidence)({packages:config.modules,extraEvidence:isConfigShape});const importsModule=(0,module_evidence_1.createModuleEvidence)({packages:config.modules});const withinConfigShape=node=>{for(let at=node;at;at=at.parent){if(at.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&isConfigShape?.(at))return true}return false};const originOf=(0,driver_origin_1.createOriginClassifier)(config.modules);return{meta:{type:config.meta.type,docs:{...config.meta.docs},messages:{hardcodedPassword:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Hardcoded Credentials",description:"A database password is written as a literal. It is in git history, every fork, and the built image \u2014 rotating it means rewriting history, so it never gets rotated.",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A07:2021",compliance:["SOC2","PCI-DSS","ISO27001","NIST-CSF"],effort:"low",fix:config.fix,documentationLink:config.documentationLink}),credentialsInUrl:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Hardcoded Credentials",description:"A connection URL embeds a password in its userinfo section, so the secret is committed with the string.",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A07:2021",compliance:["SOC2","PCI-DSS","ISO27001","NIST-CSF"],effort:"low",fix:config.urlFix,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){if((0,rule_creator_1.isTestFilePath)(context.filename))return{};const env=(0,value_follow_1.envOf)(context);let ownsFile=false;let ownsShapeOnly=false;const reported=new WeakSet;const scanned=new WeakSet;const report=(node,messageId)=>{if(reported.has(node))return;reported.add(node);context.report({node,messageId})};const reportSecrets=node=>{for(const value of(0,connection_config_1.possibleValues)((0,value_follow_1.valueAt)(node,env))){if(!isLiteralSecret(value.node))continue;report(value.env===env&&(0,require_tls_rule_1.within)(value.node,node)?value.node:node,"hardcodedPassword")}};const reportUrl=node=>{for(const value of(0,connection_config_1.possibleValues)((0,value_follow_1.valueAt)(node,env))){const url=urlPrefix(value.node);if(url===void 0||!urlEmbedsCredentials(url,config.urlSchemes))continue;report(value.env===env&&(0,require_tls_rule_1.within)(value.node,node)?value.node:node,"credentialsInUrl");return true}return false};const scanConfig=obj=>{if(scanned.has(obj))return;scanned.add(obj);for(const prop of obj.properties){if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property)continue;const name=(0,unscoped_mutation_rule_1.propertyKeyName)(prop);if(name===void 0)continue;if(CREDENTIAL_KEYS.includes(name.toLowerCase())){reportSecrets(prop.value);continue}if(reportUrl(prop.value))continue;if(connectionKeys.includes(name)){for(const value of(0,connection_config_1.possibleValues)((0,value_follow_1.valueAt)(prop.value,env))){if(value.env===env&&value.node.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression){scanConfig(value.node)}}}}};return{Program(program){ownsFile=usesModule(program);ownsShapeOnly=ownsFile&&!importsModule(program)},ObjectExpression(node){if(!ownsFile)return;if(ownsShapeOnly&&!withinConfigShape(node))return;if(!(0,require_tls_rule_1.looksLikeConnectionConfig)(node,connectionKeys))return;if((0,connection_config_1.passedToForeign)(node,originOf,env))return;scanConfig(node)},"CallExpression, NewExpression"(node){if(!ownsFile)return;if(originOf((0,value_follow_1.valueAt)(node.callee,env))!=="ours")return;for(const argument of node.arguments){if(argument.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement)reportUrl(argument)}const index=config.positionalPassword;if(index!==void 0&&node.type===ast_node_types_1.AST_NODE_TYPES.NewExpression&&node.arguments.length>index){reportSecrets(node.arguments[index])}},"Literal, TemplateLiteral"(node){if(!ownsFile)return;const value=urlPrefix(node);if(value===void 0)return;if(!urlEmbedsCredentials(value,config.urlSchemes))return;if(!(0,require_tls_rule_1.inConnectionPosition)(node,connectionKeys,callee=>originOf((0,value_follow_1.valueAt)(callee,env))==="ours")){return}report(node,"credentialsInUrl")}}}}}function urlPrefix(node){const value=staticStringValue(node);if(value!==void 0)return value;if(node.type!==ast_node_types_1.AST_NODE_TYPES.TemplateLiteral)return void 0;const[head]=node.quasis;return head.value.raw}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.urlEmbedsCredentials=urlEmbedsCredentials;exports.staticStringValue=staticStringValue;exports.isLiteralSecret=isLiteralSecret;exports.createHardcodedCredentialsRule=createHardcodedCredentialsRule;exports.urlPrefix=urlPrefix;const rule_creator_1=require("./rule-creator");const ast_node_types_1=require("../ast-node-types");const messaging_1=require("../messaging");const unscoped_mutation_rule_1=require("./unscoped-mutation-rule");const module_evidence_1=require("./module-evidence");const rule_creator_2=require("./rule-creator");const driver_origin_1=require("./driver-origin");const connection_config_1=require("./connection-config");const value_follow_1=require("./value-follow");const require_tls_rule_1=require("./require-tls-rule");const CREDENTIAL_KEYS=["password","pass","pwd","secret","passwd","auth"];const DEFAULT_CONNECTION_KEYS=["host","hostname","port","database","connectionString","socketPath","uri","url","connection","pool","schema"];function urlEmbedsCredentials(value,schemes){const match=/^([a-z][a-z0-9+.-]*):\/\/([^/@\s:]*:[^/@\s]+)@/i.exec(value);if(match===null)return false;return schemes.some(scheme=>scheme.toLowerCase()===match[1].toLowerCase())}function staticStringValue(node){if(node.type===ast_node_types_1.AST_NODE_TYPES.Literal){return typeof node.value==="string"?node.value:void 0}if(node.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral&&node.expressions.length===0){const[{value}]=node.quasis;return value.cooked??value.raw}return void 0}function isLiteralSecret(node){const value=staticStringValue(node);return value!==void 0&&value.length>0}function createHardcodedCredentialsRule(config){const connectionKeys=[...DEFAULT_CONNECTION_KEYS,...config.connectionKeys??[]];const isConfigShape=(0,connection_config_1.configShapeEvidence)(config.configShapes??[]);const usesModule=(0,module_evidence_1.createModuleEvidence)({packages:config.modules,extraEvidence:isConfigShape});const importsModule=(0,module_evidence_1.createModuleEvidence)({packages:config.modules});const withinConfigShape=node=>{for(let at=node;at;at=at.parent){if(at.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&isConfigShape?.(at))return true}return false};const originOf=(0,driver_origin_1.createOriginClassifier)(config.modules);return rule_creator_1.RuleCreator.withoutDocs({meta:{interop:{runtimes:["eslint","oxlint"]},type:config.meta.type,docs:{...config.meta.docs},messages:{hardcodedPassword:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Hardcoded Credentials",description:"A database password is written as a literal. It is in git history, every fork, and the built image \u2014 rotating it means rewriting history, so it never gets rotated.",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A07:2021",compliance:["SOC2","PCI-DSS","ISO27001","NIST-CSF"],effort:"low",fix:config.fix,documentationLink:config.documentationLink}),credentialsInUrl:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Hardcoded Credentials",description:"A connection URL embeds a password in its userinfo section, so the secret is committed with the string.",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A07:2021",compliance:["SOC2","PCI-DSS","ISO27001","NIST-CSF"],effort:"low",fix:config.urlFix,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],createOnce(context){let env;let ownsFile;let ownsShapeOnly;let reported;let scanned;const report=(node,messageId)=>{if(reported.has(node))return;reported.add(node);context.report({node,messageId})};const reportSecrets=node=>{for(const value of(0,connection_config_1.possibleValues)((0,value_follow_1.valueAt)(node,env))){if(!isLiteralSecret(value.node))continue;report(value.env===env&&(0,require_tls_rule_1.within)(value.node,node)?value.node:node,"hardcodedPassword")}};const reportUrl=node=>{for(const value of(0,connection_config_1.possibleValues)((0,value_follow_1.valueAt)(node,env))){const url=urlPrefix(value.node);if(url===void 0||!urlEmbedsCredentials(url,config.urlSchemes))continue;report(value.env===env&&(0,require_tls_rule_1.within)(value.node,node)?value.node:node,"credentialsInUrl");return true}return false};const scanConfig=obj=>{if(scanned.has(obj))return;scanned.add(obj);for(const prop of obj.properties){if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property)continue;const name=(0,unscoped_mutation_rule_1.propertyKeyName)(prop);if(name===void 0)continue;if(CREDENTIAL_KEYS.includes(name.toLowerCase())){reportSecrets(prop.value);continue}if(reportUrl(prop.value))continue;if(connectionKeys.includes(name)){for(const value of(0,connection_config_1.possibleValues)((0,value_follow_1.valueAt)(prop.value,env))){if(value.env===env&&value.node.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression){scanConfig(value.node)}}}}};return{before(){if((0,rule_creator_2.isTestFilePath)(context.filename))return false;env=(0,value_follow_1.envOf)(context);ownsFile=false;ownsShapeOnly=false;reported=new WeakSet;scanned=new WeakSet;return true},Program(program){ownsFile=usesModule(program);ownsShapeOnly=ownsFile&&!importsModule(program)},ObjectExpression(node){if(!ownsFile)return;if(ownsShapeOnly&&!withinConfigShape(node))return;if(!(0,require_tls_rule_1.looksLikeConnectionConfig)(node,connectionKeys))return;if((0,connection_config_1.passedToForeign)(node,originOf,env))return;scanConfig(node)},"CallExpression, NewExpression"(node){if(!ownsFile)return;if(originOf((0,value_follow_1.valueAt)(node.callee,env))!=="ours")return;for(const argument of node.arguments){if(argument.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement)reportUrl(argument)}const index=config.positionalPassword;if(index!==void 0&&node.type===ast_node_types_1.AST_NODE_TYPES.NewExpression&&node.arguments.length>index){reportSecrets(node.arguments[index])}},"Literal, TemplateLiteral"(node){if(!ownsFile)return;const value=urlPrefix(node);if(value===void 0)return;if(!urlEmbedsCredentials(value,config.urlSchemes))return;if(!(0,require_tls_rule_1.inConnectionPosition)(node,connectionKeys,callee=>originOf((0,value_follow_1.valueAt)(callee,env))==="ours")){return}report(node,"credentialsInUrl")}}}})}function urlPrefix(node){const value=staticStringValue(node);if(value!==void 0)return value;if(node.type!==ast_node_types_1.AST_NODE_TYPES.TemplateLiteral)return void 0;const[head]=node.quasis;return head.value.raw}
@@ -1,8 +1,3 @@
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
1
  import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
7
2
  import { type Env } from './value-follow';
8
3
  /**
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.classifyPayload=classifyPayload;exports.createMassAssignmentRule=createMassAssignmentRule;const ast_node_types_1=require("../ast-node-types");const messaging_1=require("../messaging");const module_evidence_1=require("./module-evidence");const rule_creator_1=require("./rule-creator");const driver_origin_1=require("./driver-origin");const request_source_1=require("./request-source");const unscoped_mutation_rule_1=require("./unscoped-mutation-rule");const value_follow_1=require("./value-follow");function classifyPayload(node,env,isOurs=()=>false){if((0,request_source_1.isRequestPayload)(node,env))return"untrustedPayload";if(node.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const variable=(0,value_follow_1.lookup)(node.name,env.scopeOf(node));const filled=variable?.references.some(reference=>{const call=reference.identifier.parent;if(call===void 0||!isObjectAssign(call))return false;const args=call.arguments;return args[0]===reference.identifier&&!isOurs(reference.identifier)&&args.slice(1).some(source=>(0,request_source_1.isRequestPayload)(source,env))});if(filled===true)return"untrustedPayload"}if(node.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression){for(const prop of node.properties){if(prop.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;if((0,request_source_1.isRequestPayload)(prop.argument,env))return"untrustedSpread"}}return false}function isObjectAssign(node){return node.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&node.callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&node.callee.object.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&node.callee.object.name==="Object"&&!node.callee.computed&&node.callee.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&node.callee.property.name==="assign"}const WRITE_VERBS=new Set(["insert","update"]);function createMassAssignmentRule(config){const methods=new Set(config.methods);const payloadKeys=new Set(config.payloadKeys??[]);const usesModule=(0,module_evidence_1.createModuleEvidence)({packages:config.modules});const originOf=(0,driver_origin_1.createOriginClassifier)(config.modules);return{meta:{type:config.meta.type,docs:{...config.meta.docs},messages:{untrustedPayload:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Mass Assignment",description:"The request object is written straight to the database, so every column the model exposes is settable by the caller \u2014 including ones this code never mentions.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A04:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"medium",fix:config.fix,documentationLink:config.documentationLink}),untrustedSpread:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Mass Assignment",description:"Spreading the request into the payload carries every key it happens to hold, not just the ones written beside it.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A04:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"medium",fix:config.fix,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){if((0,rule_creator_1.isTestFilePath)(context.filename))return{};const env=(0,value_follow_1.envOf)(context);let ownsFile=false;const isOurs=node=>originOf((0,value_follow_1.valueAt)(node,env))==="ours";const hasDistinctiveShape=node=>{const callee=node.callee;switch(config.distinctiveShape){case"model-accessor":return callee.object.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression;case"table-call":{const chained=(0,unscoped_mutation_rule_1.chainMethodNames)(node);return(0,unscoped_mutation_rule_1.startsWithTable)(callee.object)||["into","table","from"].some(m=>chained.has(m))}case"builder-chain":{const object=callee.object;return object.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&object.callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&WRITE_VERBS.has(object.callee.property.name)}default:return false}};return{Program(program){ownsFile=usesModule(program)},CallExpression(node){if(isObjectAssign(node)){const[target,...sources]=node.arguments;if(target===void 0||!isOurs(target))return;for(const source of sources){if((0,request_source_1.isRequestPayload)(source,env))context.report({node:source,messageId:"untrustedPayload"})}return}if(node.callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression||node.callee.property.type!==ast_node_types_1.AST_NODE_TYPES.Identifier||!methods.has(node.callee.property.name)){return}const origin=originOf((0,value_follow_1.valueAt)(node.callee.object,env));if(origin==="foreign")return;if(origin==="unknown"&&!(ownsFile&&hasDistinctiveShape(node))){return}if(config.allowlistOption!==void 0&&node.arguments.some(arg=>arg.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&arg.properties.some(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Property&&(0,unscoped_mutation_rule_1.propertyKeyName)(p)===config.allowlistOption))){return}for(const arg of node.arguments){if(arg.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;const direct=classifyPayload(arg,env,isOurs);if(direct){context.report({node:arg,messageId:direct});continue}if(arg.type!==ast_node_types_1.AST_NODE_TYPES.ObjectExpression)continue;for(const prop of arg.properties){if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property)continue;const name=(0,unscoped_mutation_rule_1.propertyKeyName)(prop);if(name===void 0||!payloadKeys.has(name))continue;const nested=classifyPayload(prop.value,env,isOurs);if(nested)context.report({node:prop.value,messageId:nested})}}}}}}}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.classifyPayload=classifyPayload;exports.createMassAssignmentRule=createMassAssignmentRule;const rule_creator_1=require("./rule-creator");const ast_node_types_1=require("../ast-node-types");const messaging_1=require("../messaging");const module_evidence_1=require("./module-evidence");const rule_creator_2=require("./rule-creator");const driver_origin_1=require("./driver-origin");const request_source_1=require("./request-source");const unscoped_mutation_rule_1=require("./unscoped-mutation-rule");const value_follow_1=require("./value-follow");function classifyPayload(node,env,isOurs=()=>false){if((0,request_source_1.isRequestPayload)(node,env))return"untrustedPayload";if(node.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const variable=(0,value_follow_1.lookup)(node.name,env.scopeOf(node));const filled=variable?.references.some(reference=>{const call=reference.identifier.parent;if(call===void 0||!isObjectAssign(call))return false;const args=call.arguments;return args[0]===reference.identifier&&!isOurs(reference.identifier)&&args.slice(1).some(source=>(0,request_source_1.isRequestPayload)(source,env))});if(filled===true)return"untrustedPayload"}if(node.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression){for(const prop of node.properties){if(prop.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;if((0,request_source_1.isRequestPayload)(prop.argument,env))return"untrustedSpread"}}return false}function isObjectAssign(node){return node.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&node.callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&node.callee.object.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&node.callee.object.name==="Object"&&!node.callee.computed&&node.callee.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&node.callee.property.name==="assign"}const WRITE_VERBS=new Set(["insert","update"]);function createMassAssignmentRule(config){const methods=new Set(config.methods);const payloadKeys=new Set(config.payloadKeys??[]);const usesModule=(0,module_evidence_1.createModuleEvidence)({packages:config.modules});const originOf=(0,driver_origin_1.createOriginClassifier)(config.modules);return rule_creator_1.RuleCreator.withoutDocs({meta:{interop:{runtimes:["eslint","oxlint"]},type:config.meta.type,docs:{...config.meta.docs},messages:{untrustedPayload:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Mass Assignment",description:"The request object is written straight to the database, so every column the model exposes is settable by the caller \u2014 including ones this code never mentions.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A04:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"medium",fix:config.fix,documentationLink:config.documentationLink}),untrustedSpread:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Mass Assignment",description:"Spreading the request into the payload carries every key it happens to hold, not just the ones written beside it.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A04:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"medium",fix:config.fix,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],createOnce(context){let env;let ownsFile;const isOurs=node=>originOf((0,value_follow_1.valueAt)(node,env))==="ours";const hasDistinctiveShape=node=>{const callee=node.callee;switch(config.distinctiveShape){case"model-accessor":return callee.object.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression;case"table-call":{const chained=(0,unscoped_mutation_rule_1.chainMethodNames)(node);return(0,unscoped_mutation_rule_1.startsWithTable)(callee.object)||["into","table","from"].some(m=>chained.has(m))}case"builder-chain":{const object=callee.object;return object.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&object.callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&WRITE_VERBS.has(object.callee.property.name)}default:return false}};return{before(){if((0,rule_creator_2.isTestFilePath)(context.filename))return false;env=(0,value_follow_1.envOf)(context);ownsFile=false;return true},Program(program){ownsFile=usesModule(program)},CallExpression(node){if(isObjectAssign(node)){const[target,...sources]=node.arguments;if(target===void 0||!isOurs(target))return;for(const source of sources){if((0,request_source_1.isRequestPayload)(source,env))context.report({node:source,messageId:"untrustedPayload"})}return}if(node.callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression||node.callee.property.type!==ast_node_types_1.AST_NODE_TYPES.Identifier||!methods.has(node.callee.property.name)){return}const origin=originOf((0,value_follow_1.valueAt)(node.callee.object,env));if(origin==="foreign")return;if(origin==="unknown"&&!(ownsFile&&hasDistinctiveShape(node))){return}if(config.allowlistOption!==void 0&&node.arguments.some(arg=>arg.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&arg.properties.some(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Property&&(0,unscoped_mutation_rule_1.propertyKeyName)(p)===config.allowlistOption))){return}for(const arg of node.arguments){if(arg.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;const direct=classifyPayload(arg,env,isOurs);if(direct){context.report({node:arg,messageId:direct});continue}if(arg.type!==ast_node_types_1.AST_NODE_TYPES.ObjectExpression)continue;for(const prop of arg.properties){if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property)continue;const name=(0,unscoped_mutation_rule_1.propertyKeyName)(prop);if(name===void 0||!payloadKeys.has(name))continue;const nested=classifyPayload(prop.value,env,isOurs);if(nested)context.report({node:prop.value,messageId:nested})}}}}}})}
@@ -1,8 +1,3 @@
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
1
  import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
7
2
  /**
8
3
  * Two ids because the remediations are genuinely different.
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.stripIdentifierGap=stripIdentifierGap;exports.lastClause=lastClause;exports.identifierPosition=identifierPosition;exports.calleeText=calleeText;exports.isExemptExpression=isExemptExpression;exports.tagName=tagName;exports.createRawIdentifierRule=createRawIdentifierRule;const ast_node_types_1=require("../ast-node-types");const spellings_1=require("../ast/spellings");const messaging_1=require("../messaging");const type_syntax_1=require("../ast/type-syntax");const rule_creator_1=require("./rule-creator");const driver_origin_1=require("./driver-origin");const sql_safety_1=require("./sql-safety");const value_follow_1=require("./value-follow");const IDENTIFIER_KEYWORDS=/\b(?:from|join|into|update|table|order\s+by|group\s+by|select|distinct\s+on)$/i;const GAP_CHAR=/[\s"'`[]/;function stripIdentifierGap(text){let end=text.length;while(end>0&&GAP_CHAR.test(text[end-1]))end--;return text.slice(0,end)}const CLAUSE_KEYWORDS=/\b(select|from|where|group\s+by|having|order\s+by|limit|offset|union|returning|values|set)\b/gi;function lastClause(text){const matches=[...text.matchAll(CLAUSE_KEYWORDS)];const last=matches.at(-1);return last?last[1].toLowerCase().replace(/\s+/g," "):""}function identifierPosition(precedingText){if(IDENTIFIER_KEYWORDS.test(stripIdentifierGap(precedingText)))return"identifier";if(lastClause(precedingText)==="order by")return"sortDirection";return false}function calleeText(node){if(node.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return node.name;if(node.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){const object=calleeText(node.object);const property=(0,spellings_1.propertyName)(node);return object&&property?`${object}.${property}`:""}return""}function isExemptExpression(expr,identifierHelpers,tags){if(expr.type===ast_node_types_1.AST_NODE_TYPES.Literal)return true;if(expr.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){if(identifierHelpers.includes(calleeText(expr.callee)))return true}if(expr.type===ast_node_types_1.AST_NODE_TYPES.TaggedTemplateExpression){const nested=tagName(expr.tag);return nested!==void 0&&tags.includes(nested)}return false}function tagName(tag){if(tag.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return tag.name;if(tag.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){return(0,spellings_1.propertyName)(tag)??void 0}return void 0}function createRawIdentifierRule(config){const tags=new Set([...config.tags,...config.driverTags??[]]);const driverTags=new Set(config.driverTags??[]);return{meta:{type:config.meta.type,docs:{...config.meta.docs},messages:{identifierInterpolation:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"A table or column name is interpolated into a parameterized query. Bind parameters only ever substitute values, so this identifier is spliced into the SQL as text.",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"medium",fix:config.fix,documentationLink:config.documentationLink}),sortDirectionInterpolation:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"A value is interpolated inside an ORDER BY clause, where a bind parameter cannot reach.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"low",fix:config.sortDirectionFix,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){if((0,rule_creator_1.isTestFilePath)(context.filename))return{};const env=(0,value_follow_1.envOf)(context);const originOf=(0,driver_origin_1.createOriginClassifier)(config.modules);const safety=(0,sql_safety_1.createSqlSafety)({origin:originOf,escapers:new Set,fragmentFactories:new Set,modules:config.modules});const tagKey=tag=>{if(tag.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const variable=(0,value_follow_1.lookup)(tag.name,env.scopeOf(tag));const specifier=variable===null?null:(0,value_follow_1.importSpecifierOf)(variable);if(specifier!==null&&(0,driver_origin_1.sourceMatches)(specifier.source,config.modules))return{name:specifier.name,driver:true};return{name:tag.name,driver:false}}const name=tagName(tag);if(name===void 0)return void 0;const object=tag.object;return{name,driver:originOf((0,value_follow_1.valueAt)(object,env))==="ours"}};const isDriverObject=(node,depth=0)=>{if(depth>8)return false;const value=(0,type_syntax_1.unwrapTypeSyntax)(node);switch(value.type){case ast_node_types_1.AST_NODE_TYPES.Identifier:{const variable=(0,value_follow_1.lookup)(value.name,env.scopeOf(value));if(variable===null)return false;const specifier=(0,value_follow_1.importSpecifierOf)(variable);if(specifier!==null){if((0,driver_origin_1.sourceMatches)(specifier.source,config.modules))return true;const followed=(0,value_follow_1.follow)((0,value_follow_1.valueAt)(value,env));return followed.node!==value&&followed.env!==env&&isExportedDriverObject(followed.node,followed.env)}const def=variable.defs[0];if(def?.type!=="Variable"||def.node.id.type!==ast_node_types_1.AST_NODE_TYPES.Identifier){return false}const written=(0,value_follow_1.singleWrite)(variable);return written!==null&&isDriverObject(written,depth+1)}case ast_node_types_1.AST_NODE_TYPES.MemberExpression:return isDriverObject(value.object,depth+1);case ast_node_types_1.AST_NODE_TYPES.ConditionalExpression:return isDriverObject(value.consequent,depth+1)&&isDriverObject(value.alternate,depth+1);case ast_node_types_1.AST_NODE_TYPES.TaggedTemplateExpression:return isDriverObject(value.tag,depth+1);case ast_node_types_1.AST_NODE_TYPES.NewExpression:return isDriverObject(value.callee,depth+1);case ast_node_types_1.AST_NODE_TYPES.CallExpression:{const callee=value.callee;if(callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&(0,spellings_1.propertyName)(callee)==="raw"){const[text]=value.arguments;return text!==void 0&&safety.isSafe((0,value_follow_1.valueAt)(text,env))}if(callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&(0,spellings_1.propertyName)(callee)==="as"){return originOf((0,value_follow_1.valueAt)(callee.object,env))==="ours"}return isDriverObject(callee,depth+1)}default:return false}};const isExportedDriverObject=(node,moduleEnv)=>{const value=(0,type_syntax_1.unwrapTypeSyntax)(node);if(value.type!==ast_node_types_1.AST_NODE_TYPES.CallExpression)return false;let root=value.callee;while(root.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression)root=root.object;if(root.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,value_follow_1.lookup)(root.name,moduleEnv.scopeOf(root));const specifier=variable===null?null:(0,value_follow_1.importSpecifierOf)(variable);return specifier!==null&&(0,driver_origin_1.sourceMatches)(specifier.source,config.modules)};const isUsedAsObject=node=>{const value=(0,type_syntax_1.unwrapTypeSyntax)(node);if(value.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,value_follow_1.lookup)(value.name,env.scopeOf(value));return variable!==null&&variable.references.some(reference=>{const use=reference.identifier.parent;return use?.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&use.object===reference.identifier&&!use.computed&&use.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&!(use.property.name in String.prototype)})};return{TaggedTemplateExpression(node){const key=tagKey(node.tag);if(key===void 0||!tags.has(key.name))return;if((config.requireImport||driverTags.has(key.name))&&!key.driver){return}if(node.tag.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&originOf((0,value_follow_1.valueAt)(node.tag.object,env))==="foreign"){return}const{quasis,expressions}=node.quasi;expressions.forEach((expr,index)=>{if(isExemptExpression(expr,config.identifierHelpers,config.tags))return;if(isDriverObject(expr)||isUsedAsObject(expr))return;if(safety.isSafe((0,value_follow_1.valueAt)(expr,env)))return;const preceding=quasis.slice(0,index+1).map(q=>q.value.raw).join(" ");const position=identifierPosition(preceding);if(position===false)return;context.report({node:expr,messageId:position==="identifier"?"identifierInterpolation":"sortDirectionInterpolation"})})}}}}}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.stripIdentifierGap=stripIdentifierGap;exports.lastClause=lastClause;exports.identifierPosition=identifierPosition;exports.calleeText=calleeText;exports.isExemptExpression=isExemptExpression;exports.tagName=tagName;exports.createRawIdentifierRule=createRawIdentifierRule;const rule_creator_1=require("./rule-creator");const ast_node_types_1=require("../ast-node-types");const spellings_1=require("../ast/spellings");const messaging_1=require("../messaging");const type_syntax_1=require("../ast/type-syntax");const rule_creator_2=require("./rule-creator");const driver_origin_1=require("./driver-origin");const sql_safety_1=require("./sql-safety");const value_follow_1=require("./value-follow");const IDENTIFIER_KEYWORDS=/\b(?:from|join|into|update|table|order\s+by|group\s+by|select|distinct\s+on)$/i;const GAP_CHAR=/[\s"'`[]/;function stripIdentifierGap(text){let end=text.length;while(end>0&&GAP_CHAR.test(text[end-1]))end--;return text.slice(0,end)}const CLAUSE_KEYWORDS=/\b(select|from|where|group\s+by|having|order\s+by|limit|offset|union|returning|values|set)\b/gi;function lastClause(text){const matches=[...text.matchAll(CLAUSE_KEYWORDS)];const last=matches.at(-1);return last?last[1].toLowerCase().replace(/\s+/g," "):""}function identifierPosition(precedingText){if(IDENTIFIER_KEYWORDS.test(stripIdentifierGap(precedingText)))return"identifier";if(lastClause(precedingText)==="order by")return"sortDirection";return false}function calleeText(node){if(node.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return node.name;if(node.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){const object=calleeText(node.object);const property=(0,spellings_1.propertyName)(node);return object&&property?`${object}.${property}`:""}return""}function isExemptExpression(expr,identifierHelpers,tags){if(expr.type===ast_node_types_1.AST_NODE_TYPES.Literal)return true;if(expr.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){if(identifierHelpers.includes(calleeText(expr.callee)))return true}if(expr.type===ast_node_types_1.AST_NODE_TYPES.TaggedTemplateExpression){const nested=tagName(expr.tag);return nested!==void 0&&tags.includes(nested)}return false}function tagName(tag){if(tag.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return tag.name;if(tag.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){return(0,spellings_1.propertyName)(tag)??void 0}return void 0}function createRawIdentifierRule(config){const tags=new Set([...config.tags,...config.driverTags??[]]);const driverTags=new Set(config.driverTags??[]);return rule_creator_1.RuleCreator.withoutDocs({meta:{interop:{runtimes:["eslint","oxlint"]},type:config.meta.type,docs:{...config.meta.docs},messages:{identifierInterpolation:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"A table or column name is interpolated into a parameterized query. Bind parameters only ever substitute values, so this identifier is spliced into the SQL as text.",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"medium",fix:config.fix,documentationLink:config.documentationLink}),sortDirectionInterpolation:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"A value is interpolated inside an ORDER BY clause, where a bind parameter cannot reach.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"low",fix:config.sortDirectionFix,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],createOnce(context){let env;let originOf;let safety;const tagKey=tag=>{if(tag.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const variable=(0,value_follow_1.lookup)(tag.name,env.scopeOf(tag));const specifier=variable===null?null:(0,value_follow_1.importSpecifierOf)(variable);if(specifier!==null&&(0,driver_origin_1.sourceMatches)(specifier.source,config.modules))return{name:specifier.name,driver:true};return{name:tag.name,driver:false}}const name=tagName(tag);if(name===void 0)return void 0;const object=tag.object;return{name,driver:originOf((0,value_follow_1.valueAt)(object,env))==="ours"}};const isDriverObject=(node,depth=0)=>{if(depth>8)return false;const value=(0,type_syntax_1.unwrapTypeSyntax)(node);switch(value.type){case ast_node_types_1.AST_NODE_TYPES.Identifier:{const variable=(0,value_follow_1.lookup)(value.name,env.scopeOf(value));if(variable===null)return false;const specifier=(0,value_follow_1.importSpecifierOf)(variable);if(specifier!==null){if((0,driver_origin_1.sourceMatches)(specifier.source,config.modules))return true;const followed=(0,value_follow_1.follow)((0,value_follow_1.valueAt)(value,env));return followed.node!==value&&followed.env!==env&&isExportedDriverObject(followed.node,followed.env)}const def=variable.defs[0];if(def?.type!=="Variable"||def.node.id.type!==ast_node_types_1.AST_NODE_TYPES.Identifier){return false}const written=(0,value_follow_1.singleWrite)(variable);return written!==null&&isDriverObject(written,depth+1)}case ast_node_types_1.AST_NODE_TYPES.MemberExpression:return isDriverObject(value.object,depth+1);case ast_node_types_1.AST_NODE_TYPES.ConditionalExpression:return isDriverObject(value.consequent,depth+1)&&isDriverObject(value.alternate,depth+1);case ast_node_types_1.AST_NODE_TYPES.TaggedTemplateExpression:return isDriverObject(value.tag,depth+1);case ast_node_types_1.AST_NODE_TYPES.NewExpression:return isDriverObject(value.callee,depth+1);case ast_node_types_1.AST_NODE_TYPES.CallExpression:{const callee=value.callee;if(callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&(0,spellings_1.propertyName)(callee)==="raw"){const[text]=value.arguments;return text!==void 0&&safety.isSafe((0,value_follow_1.valueAt)(text,env))}if(callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&(0,spellings_1.propertyName)(callee)==="as"){return originOf((0,value_follow_1.valueAt)(callee.object,env))==="ours"}return isDriverObject(callee,depth+1)}default:return false}};const isExportedDriverObject=(node,moduleEnv)=>{const value=(0,type_syntax_1.unwrapTypeSyntax)(node);if(value.type!==ast_node_types_1.AST_NODE_TYPES.CallExpression)return false;let root=value.callee;while(root.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression)root=root.object;if(root.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,value_follow_1.lookup)(root.name,moduleEnv.scopeOf(root));const specifier=variable===null?null:(0,value_follow_1.importSpecifierOf)(variable);return specifier!==null&&(0,driver_origin_1.sourceMatches)(specifier.source,config.modules)};const isUsedAsObject=node=>{const value=(0,type_syntax_1.unwrapTypeSyntax)(node);if(value.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,value_follow_1.lookup)(value.name,env.scopeOf(value));return variable!==null&&variable.references.some(reference=>{const use=reference.identifier.parent;return use?.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&use.object===reference.identifier&&!use.computed&&use.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&!(use.property.name in String.prototype)})};return{before(){if((0,rule_creator_2.isTestFilePath)(context.filename))return false;env=(0,value_follow_1.envOf)(context);originOf=(0,driver_origin_1.createOriginClassifier)(config.modules);safety=(0,sql_safety_1.createSqlSafety)({origin:originOf,escapers:new Set,fragmentFactories:new Set,modules:config.modules});return true},TaggedTemplateExpression(node){const key=tagKey(node.tag);if(key===void 0||!tags.has(key.name))return;if((config.requireImport||driverTags.has(key.name))&&!key.driver){return}if(node.tag.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&originOf((0,value_follow_1.valueAt)(node.tag.object,env))==="foreign"){return}const{quasis,expressions}=node.quasi;expressions.forEach((expr,index)=>{if(isExemptExpression(expr,config.identifierHelpers,config.tags))return;if(isDriverObject(expr)||isUsedAsObject(expr))return;if(safety.isSafe((0,value_follow_1.valueAt)(expr,env)))return;const preceding=quasis.slice(0,index+1).map(q=>q.value.raw).join(" ");const position=identifierPosition(preceding);if(position===false)return;context.report({node:expr,messageId:position==="identifier"?"identifierInterpolation":"sortDirectionInterpolation"})})}}}})}
@@ -1,8 +1,3 @@
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
1
  import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
7
2
  import { type ConfigShape } from './connection-config';
8
3
  /** Message ids every rule built by this factory reports. */
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isLiteralBoolean=isLiteralBoolean;exports.looksLikeConnectionConfig=looksLikeConnectionConfig;exports.urlDisablesTls=urlDisablesTls;exports.within=within;exports.inConnectionPosition=inConnectionPosition;exports.createRequireTlsRule=createRequireTlsRule;const ast_node_types_1=require("../ast-node-types");const messaging_1=require("../messaging");const unscoped_mutation_rule_1=require("./unscoped-mutation-rule");const module_evidence_1=require("./module-evidence");const rule_creator_1=require("./rule-creator");const driver_origin_1=require("./driver-origin");const connection_config_1=require("./connection-config");const value_follow_1=require("./value-follow");const DEFAULT_CONNECTION_KEYS=["host","hostname","port","user","username","password","database","connectionString","socketPath","uri","url","connection","pool","schema"];const TLS_OFF_KEYS=["ssl","secure","tls","encrypt","useSSL","requireSSL"];const VERIFY_OFF_KEYS=["rejectUnauthorized","verifyServerCertificate","checkServerIdentity","trustServerCertificate"];function isLiteralBoolean(value,expect){if(value.type!==ast_node_types_1.AST_NODE_TYPES.Literal)return false;if(typeof value.value!=="boolean"){return expect===false&&!value.value}return value.value===expect}function looksLikeConnectionConfig(obj,connectionKeys){return obj.properties.some(prop=>{const name=(0,unscoped_mutation_rule_1.propertyKeyName)(prop);return name!==void 0&&connectionKeys.includes(name)})}function urlDisablesTls(value,schemes){if(!schemes.some(scheme=>value.startsWith(`${scheme}://`)))return false;const query=value.split("#")[0];return/[?&](?:sslmode=disable|ssl=(?:false|0))(?:&|$)/i.test(query)}function within(inner,outer){return outer.range[0]<=inner.range[0]&&inner.range[1]<=outer.range[1]}function inConnectionPosition(node,connectionKeys,isDriverCallee){const parent=node.parent;if(!parent)return false;if(parent.type===ast_node_types_1.AST_NODE_TYPES.Property&&parent.value===node){const name=(0,unscoped_mutation_rule_1.propertyKeyName)(parent);return name!==void 0&&connectionKeys.includes(name)}if(parent.type===ast_node_types_1.AST_NODE_TYPES.CallExpression||parent.type===ast_node_types_1.AST_NODE_TYPES.NewExpression){if(!parent.arguments.includes(node))return false;return isDriverCallee(parent.callee)}return false}function createRequireTlsRule(config){const connectionKeys=[...DEFAULT_CONNECTION_KEYS,...config.connectionKeys??[]];const urlSchemes=config.urlSchemes??[];const usesModule=(0,module_evidence_1.createModuleEvidence)({packages:config.modules,extraEvidence:(0,connection_config_1.configShapeEvidence)(config.configShapes??[])});const originOf=(0,driver_origin_1.createOriginClassifier)(config.modules);return{meta:{type:config.meta.type,docs:{...config.meta.docs},messages:{tlsDisabled:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Cleartext Database Connection",description:"TLS is explicitly disabled on this database connection. Queries, result rows and the credentials that open the session all cross the network in cleartext.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A02:2021",compliance:["SOC2","PCI-DSS","HIPAA","NIST-CSF"],effort:"low",fix:config.fix,documentationLink:config.documentationLink}),certificateValidationDisabled:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Unverified Database TLS Peer",description:"Certificate validation is disabled on this database connection. The traffic is encrypted but the server is never authenticated, so it encrypts just as willingly to whoever answered in its place.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A02:2021",compliance:["SOC2","PCI-DSS","HIPAA","NIST-CSF"],effort:"medium",fix:"Supply the server CA instead of switching verification off \u2014 `ssl: { ca: fs.readFileSync(caPath) }`. If the certificate is self-signed, add that CA to the trust store rather than trusting everything.",documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){if((0,rule_creator_1.isTestFilePath)(context.filename))return{};const env=(0,value_follow_1.envOf)(context);let ownsFile=false;const reported=new WeakSet;const report=(node,messageId)=>{if(reported.has(node))return;reported.add(node);context.report({node,messageId})};const judgeProperty=(prop,name,depth)=>{const tlsKey=TLS_OFF_KEYS.includes(name);const verifyKey=VERIFY_OFF_KEYS.includes(name);const inverted=name==="trustServerCertificate";for(const value of(0,connection_config_1.possibleValues)((0,value_follow_1.valueAt)(prop.value,env))){const inline=value.env===env&&within(value.node,prop.value);if(tlsKey&&isLiteralBoolean(value.node,false)){report(prop,"tlsDisabled");return}if(verifyKey&&isLiteralBoolean(value.node,inverted)){report(prop,"certificateValidationDisabled");return}if(value.node.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&(tlsKey||connectionKeys.includes(name))){if(inline)scanTlsKeys(value.node,depth+1);else if(disablesTls(value.node))report(prop,"certificateValidationDisabled")}}};const disablesTls=obj=>obj.properties.some(prop=>prop.type===ast_node_types_1.AST_NODE_TYPES.Property&&VERIFY_OFF_KEYS.includes((0,unscoped_mutation_rule_1.propertyKeyName)(prop))&&isLiteralBoolean(prop.value,(0,unscoped_mutation_rule_1.propertyKeyName)(prop)==="trustServerCertificate"));const scanTlsKeys=(obj,depth=0)=>{if(depth>4)return;for(const prop of obj.properties){if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property)continue;const name=(0,unscoped_mutation_rule_1.propertyKeyName)(prop);if(name===void 0)continue;judgeProperty(prop,name,depth)}};return{Program(program){ownsFile=usesModule(program)},ObjectExpression(node){if(!ownsFile)return;if(!looksLikeConnectionConfig(node,connectionKeys))return;if((0,connection_config_1.passedToForeign)(node,originOf,env))return;scanTlsKeys(node)},Literal(node){if(!ownsFile)return;if(typeof node.value!=="string")return;if(!urlDisablesTls(node.value,urlSchemes))return;if(!inConnectionPosition(node,connectionKeys,isDriverCallee))return;context.report({node,messageId:"tlsDisabled"})}};function isDriverCallee(callee){return originOf((0,value_follow_1.valueAt)(callee,env))==="ours"}}}}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isLiteralBoolean=isLiteralBoolean;exports.looksLikeConnectionConfig=looksLikeConnectionConfig;exports.urlDisablesTls=urlDisablesTls;exports.within=within;exports.inConnectionPosition=inConnectionPosition;exports.createRequireTlsRule=createRequireTlsRule;const rule_creator_1=require("./rule-creator");const ast_node_types_1=require("../ast-node-types");const messaging_1=require("../messaging");const unscoped_mutation_rule_1=require("./unscoped-mutation-rule");const module_evidence_1=require("./module-evidence");const rule_creator_2=require("./rule-creator");const driver_origin_1=require("./driver-origin");const connection_config_1=require("./connection-config");const value_follow_1=require("./value-follow");const DEFAULT_CONNECTION_KEYS=["host","hostname","port","user","username","password","database","connectionString","socketPath","uri","url","connection","pool","schema"];const TLS_OFF_KEYS=["ssl","secure","tls","encrypt","useSSL","requireSSL"];const VERIFY_OFF_KEYS=["rejectUnauthorized","verifyServerCertificate","checkServerIdentity","trustServerCertificate"];function isLiteralBoolean(value,expect){if(value.type!==ast_node_types_1.AST_NODE_TYPES.Literal)return false;if(typeof value.value!=="boolean"){return expect===false&&!value.value}return value.value===expect}function looksLikeConnectionConfig(obj,connectionKeys){return obj.properties.some(prop=>{const name=(0,unscoped_mutation_rule_1.propertyKeyName)(prop);return name!==void 0&&connectionKeys.includes(name)})}function urlDisablesTls(value,schemes){if(!schemes.some(scheme=>value.startsWith(`${scheme}://`)))return false;const query=value.split("#")[0];return/[?&](?:sslmode=disable|ssl=(?:false|0))(?:&|$)/i.test(query)}function within(inner,outer){return outer.range[0]<=inner.range[0]&&inner.range[1]<=outer.range[1]}function inConnectionPosition(node,connectionKeys,isDriverCallee){const parent=node.parent;if(!parent)return false;if(parent.type===ast_node_types_1.AST_NODE_TYPES.Property&&parent.value===node){const name=(0,unscoped_mutation_rule_1.propertyKeyName)(parent);return name!==void 0&&connectionKeys.includes(name)}if(parent.type===ast_node_types_1.AST_NODE_TYPES.CallExpression||parent.type===ast_node_types_1.AST_NODE_TYPES.NewExpression){if(!parent.arguments.includes(node))return false;return isDriverCallee(parent.callee)}return false}function createRequireTlsRule(config){const connectionKeys=[...DEFAULT_CONNECTION_KEYS,...config.connectionKeys??[]];const urlSchemes=config.urlSchemes??[];const usesModule=(0,module_evidence_1.createModuleEvidence)({packages:config.modules,extraEvidence:(0,connection_config_1.configShapeEvidence)(config.configShapes??[])});const originOf=(0,driver_origin_1.createOriginClassifier)(config.modules);return rule_creator_1.RuleCreator.withoutDocs({meta:{interop:{runtimes:["eslint","oxlint"]},type:config.meta.type,docs:{...config.meta.docs},messages:{tlsDisabled:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Cleartext Database Connection",description:"TLS is explicitly disabled on this database connection. Queries, result rows and the credentials that open the session all cross the network in cleartext.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A02:2021",compliance:["SOC2","PCI-DSS","HIPAA","NIST-CSF"],effort:"low",fix:config.fix,documentationLink:config.documentationLink}),certificateValidationDisabled:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Unverified Database TLS Peer",description:"Certificate validation is disabled on this database connection. The traffic is encrypted but the server is never authenticated, so it encrypts just as willingly to whoever answered in its place.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A02:2021",compliance:["SOC2","PCI-DSS","HIPAA","NIST-CSF"],effort:"medium",fix:"Supply the server CA instead of switching verification off \u2014 `ssl: { ca: fs.readFileSync(caPath) }`. If the certificate is self-signed, add that CA to the trust store rather than trusting everything.",documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],createOnce(context){let env;let ownsFile;let reported;function isDriverCallee(callee){return originOf((0,value_follow_1.valueAt)(callee,env))==="ours"}const report=(node,messageId)=>{if(reported.has(node))return;reported.add(node);context.report({node,messageId})};const judgeProperty=(prop,name,depth)=>{const tlsKey=TLS_OFF_KEYS.includes(name);const verifyKey=VERIFY_OFF_KEYS.includes(name);const inverted=name==="trustServerCertificate";for(const value of(0,connection_config_1.possibleValues)((0,value_follow_1.valueAt)(prop.value,env))){const inline=value.env===env&&within(value.node,prop.value);if(tlsKey&&isLiteralBoolean(value.node,false)){report(prop,"tlsDisabled");return}if(verifyKey&&isLiteralBoolean(value.node,inverted)){report(prop,"certificateValidationDisabled");return}if(value.node.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&(tlsKey||connectionKeys.includes(name))){if(inline)scanTlsKeys(value.node,depth+1);else if(disablesTls(value.node))report(prop,"certificateValidationDisabled")}}};const disablesTls=obj=>obj.properties.some(prop=>prop.type===ast_node_types_1.AST_NODE_TYPES.Property&&VERIFY_OFF_KEYS.includes((0,unscoped_mutation_rule_1.propertyKeyName)(prop))&&isLiteralBoolean(prop.value,(0,unscoped_mutation_rule_1.propertyKeyName)(prop)==="trustServerCertificate"));const scanTlsKeys=(obj,depth=0)=>{if(depth>4)return;for(const prop of obj.properties){if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property)continue;const name=(0,unscoped_mutation_rule_1.propertyKeyName)(prop);if(name===void 0)continue;judgeProperty(prop,name,depth)}};return{before(){if((0,rule_creator_2.isTestFilePath)(context.filename))return false;env=(0,value_follow_1.envOf)(context);ownsFile=false;reported=new WeakSet;return true},Program(program){ownsFile=usesModule(program)},ObjectExpression(node){if(!ownsFile)return;if(!looksLikeConnectionConfig(node,connectionKeys))return;if((0,connection_config_1.passedToForeign)(node,originOf,env))return;scanTlsKeys(node)},Literal(node){if(!ownsFile)return;if(typeof node.value!=="string")return;if(!urlDisablesTls(node.value,urlSchemes))return;if(!inConnectionPosition(node,connectionKeys,isDriverCallee))return;context.report({node,messageId:"tlsDisabled"})}}}})}
@@ -21,8 +21,37 @@ export declare function applyDefault<Options extends readonly unknown[]>(default
21
21
  export type NamedCreateRuleMeta<MessageIds extends string, PluginDocs = unknown, Options extends readonly unknown[] = []> = {
22
22
  docs: PluginDocs & TSESLint.RuleMetaDataDocs;
23
23
  } & Omit<TSESLint.RuleMetaData<MessageIds, PluginDocs, Options>, 'docs'>;
24
- export interface RuleCreateAndOptions<Options extends readonly unknown[], MessageIds extends string> {
25
- create: (context: Readonly<TSESLint.RuleContext<MessageIds, Options>>, optionsWithDefault: Readonly<Options>) => TSESLint.RuleListener;
24
+ /**
25
+ * oxlint's rule shape: a visitor built ONCE per lint run, with per-file hooks.
26
+ *
27
+ * `before` runs before each file and is where per-file state is (re)set;
28
+ * returning `false` skips the file. `after` runs once the file is walked.
29
+ * The context's file-scoped members (`filename`, `sourceCode`, `options`,
30
+ * `report`) are only valid inside `before`, `after` and the visitors — oxlint
31
+ * throws if `createOnce`'s own body reads them.
32
+ */
33
+ export type RuleVisitorWithHooks = TSESLint.RuleListener & {
34
+ before?: () => boolean | void;
35
+ after?: () => void;
36
+ };
37
+ export type RuleCreateOnce<Options extends readonly unknown[], MessageIds extends string> = (context: Readonly<TSESLint.RuleContext<MessageIds, Options>>,
38
+ /** The current file's options, defaults applied. Call it in `before` or a visitor. */
39
+ options: () => Readonly<Options>) => RuleVisitorWithHooks;
40
+ export type RuleCreate<Options extends readonly unknown[], MessageIds extends string> = (context: Readonly<TSESLint.RuleContext<MessageIds, Options>>, optionsWithDefault: Readonly<Options>) => TSESLint.RuleListener;
41
+ /**
42
+ * A rule supplies exactly one of `createOnce` (oxlint's shape, preferred) or
43
+ * `create` (ESLint's). A `createOnce` rule still runs on ESLint: the creator
44
+ * derives `create` from it. New rules use `createOnce`; `create` survives only
45
+ * for rules on `.agent/create-rule-allowlist.json`.
46
+ */
47
+ export type RuleCreateAndOptions<Options extends readonly unknown[], MessageIds extends string> = RuleOptionsAndSkips<Options> & ({
48
+ create: RuleCreate<Options, MessageIds>;
49
+ createOnce?: never;
50
+ } | {
51
+ createOnce: RuleCreateOnce<Options, MessageIds>;
52
+ create?: never;
53
+ });
54
+ interface RuleOptionsAndSkips<Options extends readonly unknown[]> {
26
55
  defaultOptions?: Readonly<Options>;
27
56
  /**
28
57
  * BENCHMARK-CRITERIA.md §B1: "self-skips test files — by path and by filename
@@ -73,14 +102,14 @@ export interface RuleCreateAndOptions<Options extends readonly unknown[], Messag
73
102
  */
74
103
  skipMinifiedFiles?: boolean;
75
104
  }
76
- export interface RuleWithMeta<Options extends readonly unknown[], MessageIds extends string, Docs = unknown> extends RuleCreateAndOptions<Options, MessageIds> {
105
+ export type RuleWithMeta<Options extends readonly unknown[], MessageIds extends string, Docs = unknown> = RuleCreateAndOptions<Options, MessageIds> & {
77
106
  meta: TSESLint.RuleMetaData<MessageIds, Docs, Options>;
78
107
  name?: string;
79
- }
80
- export interface RuleWithMetaAndName<Options extends readonly unknown[], MessageIds extends string, Docs = unknown> extends RuleCreateAndOptions<Options, MessageIds> {
108
+ };
109
+ export type RuleWithMetaAndName<Options extends readonly unknown[], MessageIds extends string, Docs = unknown> = RuleCreateAndOptions<Options, MessageIds> & {
81
110
  meta: NamedCreateRuleMeta<MessageIds, Docs, Options>;
82
111
  name: string;
83
- }
112
+ };
84
113
  export type RuleModuleWithName<MessageIds extends string, Options extends readonly unknown[] = [], Docs = unknown> = TSESLint.RuleModule<MessageIds, Options, Docs> & {
85
114
  name: string;
86
115
  };
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.docsUrlFor=exports.ESLintUtils=exports.createRule=void 0;exports.applyDefault=applyDefault;exports.isTestFilePath=isTestFilePath;exports.RuleCreator=RuleCreator;exports.createRuleCreator=createRuleCreator;exports.withCanonicalDocsUrls=withCanonicalDocsUrls;const generated_file_1=require("./generated-file");const minified_file_1=require("./minified-file");function isObjectNotArray(obj){return typeof obj==="object"&&obj!=null&&!Array.isArray(obj)}function deepMerge(first,second){const keys=new Set([...Object.keys(first),...Object.keys(second)]);return Object.fromEntries([...keys].map(key=>{const firstHasKey=key in first;const secondHasKey=key in second;const firstValue=first[key];const secondValue=second[key];if(firstHasKey&&secondHasKey){return[key,isObjectNotArray(firstValue)&&isObjectNotArray(secondValue)?deepMerge(firstValue,secondValue):secondValue]}return[key,firstHasKey?firstValue:secondValue]}))}function applyDefault(defaultOptions,userOptions){const options=structuredClone(defaultOptions);if(userOptions==null){return options}options.forEach((opt,i)=>{if(userOptions[i]!==void 0){const userOpt=userOptions[i];options[i]=isObjectNotArray(userOpt)&&isObjectNotArray(opt)?deepMerge(opt,userOpt):userOpt}});return options}const TEST_DIR_SEGMENTS=new Set(["__tests__","__test__","test","tests","spec","specs","e2e","__mocks__","mocks","fixtures","__fixtures__"]);const TEST_BASENAME=/\.(test|spec|fixture|mock|e2e-spec|stories|story)\.[cm]?[jt]sx?$/;const TEST_DIR_SUFFIX=/[-_](tests?|specs?)$/;const TEST_SUPPORT_DIR=/^test(?:[-_]?(?:utils?|helpers?|support|data|doubles?|factories|fixtures?|setup))$|^testing$/i;function isTestFilePath(filename){if(!filename||filename==="<input>"||filename==="<text>")return false;const slash=Math.max(filename.lastIndexOf("/"),filename.lastIndexOf("\\"));if(TEST_BASENAME.test(filename.slice(slash+1)))return true;if(slash<0)return false;return filename.slice(0,slash).split(/[\\/]/).some(segment=>TEST_DIR_SEGMENTS.has(segment)||TEST_DIR_SUFFIX.test(segment)||TEST_SUPPORT_DIR.test(segment))}function createRuleInternal({create,defaultOptions,meta,name,skipTestFiles,skipGeneratedFiles,skipMinifiedFiles}){const resolvedDefaultOptions=defaultOptions??[];return{create(context){if(skipTestFiles&&isTestFilePath(context.filename))return{};if(skipGeneratedFiles&&(0,generated_file_1.isGeneratedFile)(context.sourceCode))return{};if(skipMinifiedFiles&&(0,minified_file_1.isMinifiedFile)(context.sourceCode))return{};return create(context,applyDefault(resolvedDefaultOptions,context.options))},defaultOptions:resolvedDefaultOptions,meta,name}}function RuleCreator(urlCreator){return({meta,name,...rule})=>createRuleInternal({meta:{...meta,docs:{...meta.docs,url:urlCreator(name)}},name,...rule})}RuleCreator.withoutDocs=args=>createRuleInternal(args);function createRuleCreator(urlCreator){return RuleCreator(urlCreator)}exports.createRule=RuleCreator(()=>void 0);exports.ESLintUtils={RuleCreator,applyDefault};const PLUGIN_DOCS_CATEGORY={"plugin-anthropic-security":"security","plugin-gemini-security":"security","plugin-mcp-sdk-security":"security","plugin-supabase-security":"security","plugin-openai-security":"security","plugin-browser-security":"security","plugin-drizzle-security":"security","plugin-express-security":"security","plugin-jwt-security":"security","plugin-knex-security":"security","plugin-lambda-security":"security","plugin-mongodb-security":"security","plugin-mysql-security":"security","plugin-nestjs-security":"security","plugin-node-security":"security","plugin-postgresql-security":"security","plugin-prisma-security":"security","plugin-secure-coding":"security","plugin-sequelize-security":"security","plugin-sqlite-security":"security","plugin-typeorm-security":"security","plugin-vercel-ai-security":"security","plugin-cli-floor":"quality","plugin-conventions":"quality","plugin-import-next":"quality","plugin-maintainability":"quality","plugin-modernization":"quality","plugin-modularity":"quality","plugin-operability":"quality","plugin-react-a11y":"quality","plugin-react-features":"quality","plugin-reliability":"quality"};const docsUrlFor=(pluginSlug,ruleName)=>{const category=PLUGIN_DOCS_CATEGORY[pluginSlug];return category?`https://eslint.interlace.tools/docs/${category}/${pluginSlug}/rules/${ruleName}`:null};exports.docsUrlFor=docsUrlFor;function withCanonicalDocsUrls(pluginSlug,rules){if(!PLUGIN_DOCS_CATEGORY[pluginSlug]){console.warn(`[eslint-devkit] withCanonicalDocsUrls('${pluginSlug}'): slug is not registered in PLUGIN_DOCS_CATEGORY, so no rule in this plugin gets a meta.docs.url. Register it in packages/eslint-devkit/src/rule-creation/rule-creator.ts.`)}for(const name of Object.keys(rules)){const descriptor=Object.getOwnPropertyDescriptor(rules,name);const{get}=descriptor;if(get){Object.defineProperty(rules,name,{...descriptor,get(){const rule=get.call(this);stampDocsUrl(pluginSlug,name,rule);return rule}});continue}stampDocsUrl(pluginSlug,name,descriptor.value)}return rules}function stampDocsUrl(pluginSlug,name,rule){const docs=rule?.meta?.docs;if(!docs)return;const url=(0,exports.docsUrlFor)(pluginSlug,name);if(url)docs.url=url}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.docsUrlFor=exports.ESLintUtils=exports.createRule=void 0;exports.applyDefault=applyDefault;exports.isTestFilePath=isTestFilePath;exports.RuleCreator=RuleCreator;exports.createRuleCreator=createRuleCreator;exports.withCanonicalDocsUrls=withCanonicalDocsUrls;const generated_file_1=require("./generated-file");const minified_file_1=require("./minified-file");function isObjectNotArray(obj){return typeof obj==="object"&&obj!=null&&!Array.isArray(obj)}function deepMerge(first,second){const keys=new Set([...Object.keys(first),...Object.keys(second)]);return Object.fromEntries([...keys].map(key=>{const firstHasKey=key in first;const secondHasKey=key in second;const firstValue=first[key];const secondValue=second[key];if(firstHasKey&&secondHasKey){return[key,isObjectNotArray(firstValue)&&isObjectNotArray(secondValue)?deepMerge(firstValue,secondValue):secondValue]}return[key,firstHasKey?firstValue:secondValue]}))}function applyDefault(defaultOptions,userOptions){const options=structuredClone(defaultOptions);if(userOptions==null){return options}options.forEach((opt,i)=>{if(userOptions[i]!==void 0){const userOpt=userOptions[i];options[i]=isObjectNotArray(userOpt)&&isObjectNotArray(opt)?deepMerge(opt,userOpt):userOpt}});return options}const TEST_DIR_SEGMENTS=new Set(["__tests__","__test__","test","tests","spec","specs","e2e","__mocks__","mocks","fixtures","__fixtures__"]);const TEST_BASENAME=/\.(test|spec|fixture|mock|e2e-spec|stories|story)\.[cm]?[jt]sx?$/;const TEST_DIR_SUFFIX=/[-_](tests?|specs?)$/;const TEST_SUPPORT_DIR=/^test(?:[-_]?(?:utils?|helpers?|support|data|doubles?|factories|fixtures?|setup))$|^testing$/i;function isTestFilePath(filename){if(!filename||filename==="<input>"||filename==="<text>")return false;const slash=Math.max(filename.lastIndexOf("/"),filename.lastIndexOf("\\"));if(TEST_BASENAME.test(filename.slice(slash+1)))return true;if(slash<0)return false;return filename.slice(0,slash).split(/[\\/]/).some(segment=>TEST_DIR_SEGMENTS.has(segment)||TEST_DIR_SUFFIX.test(segment)||TEST_SUPPORT_DIR.test(segment))}function createRuleInternal(rule){const{defaultOptions,meta,name}=rule;const{skipTestFiles,skipGeneratedFiles,skipMinifiedFiles}=rule;const resolvedDefaultOptions=defaultOptions??[];const skipsFile=context=>skipTestFiles&&isTestFilePath(context.filename)||skipGeneratedFiles&&(0,generated_file_1.isGeneratedFile)(context.sourceCode)||skipMinifiedFiles&&(0,minified_file_1.isMinifiedFile)(context.sourceCode);const module={defaultOptions:resolvedDefaultOptions,meta,name};const{createOnce}=rule;if(!createOnce){const{create}=rule;module.create=context=>skipsFile(context)?{}:create(context,applyDefault(resolvedDefaultOptions,context.options));return module}module.createOnce=raw=>{const context=raw;let options=resolvedDefaultOptions;const{before,...visitor}=createOnce(context,()=>options);return{...visitor,before(){if(skipsFile(context))return false;options=applyDefault(resolvedDefaultOptions,context.options);return before?.()}}};module.create=context=>{if(skipsFile(context))return{};const options=applyDefault(resolvedDefaultOptions,context.options);const{before,after,...visitor}=createOnce(context,()=>options);if(before?.()===false)return{};if(!after)return visitor;const exit=visitor["Program:exit"];return{...visitor,"Program:exit"(node){exit?.(node);after()}}};return module}function RuleCreator(urlCreator){return({meta,name,...rule})=>createRuleInternal({meta:{...meta,docs:{...meta.docs,url:urlCreator(name)}},name,...rule})}RuleCreator.withoutDocs=args=>createRuleInternal(args);function createRuleCreator(urlCreator){return RuleCreator(urlCreator)}exports.createRule=RuleCreator(()=>void 0);exports.ESLintUtils={RuleCreator,applyDefault};const PLUGIN_DOCS_CATEGORY={"plugin-anthropic-security":"security","plugin-gemini-security":"security","plugin-mcp-sdk-security":"security","plugin-supabase-security":"security","plugin-openai-security":"security","plugin-browser-security":"security","plugin-drizzle-security":"security","plugin-express-security":"security","plugin-jwt-security":"security","plugin-knex-security":"security","plugin-lambda-security":"security","plugin-mongodb-security":"security","plugin-mysql-security":"security","plugin-nestjs-security":"security","plugin-node-security":"security","plugin-postgresql-security":"security","plugin-prisma-security":"security","plugin-secure-coding":"security","plugin-sequelize-security":"security","plugin-sqlite-security":"security","plugin-typeorm-security":"security","plugin-vercel-ai-security":"security","plugin-cli-floor":"quality","plugin-conventions":"quality","plugin-import-next":"quality","plugin-maintainability":"quality","plugin-modernization":"quality","plugin-modularity":"quality","plugin-operability":"quality","plugin-react-a11y":"quality","plugin-react-features":"quality","plugin-reliability":"quality"};const docsUrlFor=(pluginSlug,ruleName)=>{const category=PLUGIN_DOCS_CATEGORY[pluginSlug];return category?`https://eslint.interlace.tools/docs/${category}/${pluginSlug}/rules/${ruleName}`:null};exports.docsUrlFor=docsUrlFor;function withCanonicalDocsUrls(pluginSlug,rules){if(!PLUGIN_DOCS_CATEGORY[pluginSlug]){console.warn(`[eslint-devkit] withCanonicalDocsUrls('${pluginSlug}'): slug is not registered in PLUGIN_DOCS_CATEGORY, so no rule in this plugin gets a meta.docs.url. Register it in packages/eslint-devkit/src/rule-creation/rule-creator.ts.`)}for(const name of Object.keys(rules)){const descriptor=Object.getOwnPropertyDescriptor(rules,name);const{get}=descriptor;if(get){Object.defineProperty(rules,name,{...descriptor,get(){const rule=get.call(this);stampDocsUrl(pluginSlug,name,rule);return rule}});continue}stampDocsUrl(pluginSlug,name,descriptor.value)}return rules}function stampDocsUrl(pluginSlug,name,rule){const docs=rule?.meta?.docs;if(!docs)return;const url=(0,exports.docsUrlFor)(pluginSlug,name);if(url)docs.url=url}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.POSITIONAL_KEY_LABEL=void 0;exports.readCredential=readCredential;exports.calleeName=calleeName;exports.createSdkApiKeyRule=createSdkApiKeyRule;const rule_creator_1=require("./rule-creator");const module_evidence_1=require("./module-evidence");const messaging_1=require("../messaging");const sdk_flow_1=require("./sdk-flow");exports.POSITIONAL_KEY_LABEL="The first argument";function readCredential(options,keyProps){for(const prop of options.properties){if(prop.type==="SpreadElement")return{kind:"unreadable"};if(prop.computed)continue;const name=prop.key.type==="Identifier"?prop.key.name:String(prop.key.value);if(!keyProps.has(name))continue;if(prop.value.type!=="Literal")continue;if(typeof prop.value.value==="string"&&prop.value.value.length>0){return{kind:"literal",prop:name}}}return{kind:"safe"}}function calleeName(node){if(node.type==="Identifier")return node.name;if(node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"){return node.property.name}return void 0}function createSdkApiKeyRule(config){const positional=new Set(config.positionalKeyConstructors??[]);const usesSdk=(0,module_evidence_1.createModuleListEvidence)(config.modules);const matcher=(0,sdk_flow_1.createSdkClientMatcher)((0,module_evidence_1.createModuleListMatcher)(config.modules));return(0,rule_creator_1.createRule)({name:config.ruleName,meta:{type:"problem",docs:{url:config.docsUrl,description:`Forbid a literal API key in the ${config.vendor} client options`,cwe:"CWE-798",cvss:9.1},messages:{hardcodedApiKey:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:`Hardcoded ${config.vendor} Credential`,cwe:"CWE-798",owasp:"A07:2021",cvss:9.1,description:"{{prop}} is a string literal, so the credential is committed to source control and readable by anyone with repository access",severity:"CRITICAL",compliance:["SOC2","PCI-DSS"],fix:`Read it from the environment: ${config.fixTemplate}`,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){if(!usesSdk(context.sourceCode.ast))return{};const sourceCode=context.sourceCode;const isHardcodedKey=node=>(0,sdk_flow_1.committedStrings)(node,sourceCode).some(sdk_flow_1.isCredentialShaped);function credentialProp(options){return config.keyProps.find(prop=>{const read=(0,sdk_flow_1.readObjectProperty)(options,prop,sourceCode);return read.kind==="value"&&isHardcodedKey(read.node)})}function inspect(node){const indices=matcher.optionArguments(node,sourceCode);if(indices.length===0)return;const first=node.arguments[0];if(positional.size>0&&first!==void 0&&indices.includes(0)){const binding=matcher.exportOf(node.callee,sourceCode);if(binding!==void 0&&positional.has((0,sdk_flow_1.sdkExportName)(binding))&&isHardcodedKey(first)){context.report({node,messageId:"hardcodedApiKey",data:{prop:exports.POSITIONAL_KEY_LABEL}});return}}for(const index of indices){const argument=node.arguments[index];if(argument===void 0||argument.type==="SpreadElement")continue;const options=(0,sdk_flow_1.resolveObjectLiteral)(argument,sourceCode);const prop=options&&credentialProp(options);if(prop!==void 0){context.report({node,messageId:"hardcodedApiKey",data:{prop}});return}}}return{NewExpression:inspect,CallExpression:inspect}}})}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.POSITIONAL_KEY_LABEL=void 0;exports.readCredential=readCredential;exports.calleeName=calleeName;exports.createSdkApiKeyRule=createSdkApiKeyRule;const rule_creator_1=require("./rule-creator");const module_evidence_1=require("./module-evidence");const messaging_1=require("../messaging");const sdk_flow_1=require("./sdk-flow");exports.POSITIONAL_KEY_LABEL="The first argument";function readCredential(options,keyProps){for(const prop of options.properties){if(prop.type==="SpreadElement")return{kind:"unreadable"};if(prop.computed)continue;const name=prop.key.type==="Identifier"?prop.key.name:String(prop.key.value);if(!keyProps.has(name))continue;if(prop.value.type!=="Literal")continue;if(typeof prop.value.value==="string"&&prop.value.value.length>0){return{kind:"literal",prop:name}}}return{kind:"safe"}}function calleeName(node){if(node.type==="Identifier")return node.name;if(node.type==="MemberExpression"&&!node.computed&&node.property.type==="Identifier"){return node.property.name}return void 0}function createSdkApiKeyRule(config){const positional=new Set(config.positionalKeyConstructors??[]);const usesSdk=(0,module_evidence_1.createModuleListEvidence)(config.modules);const matcher=(0,sdk_flow_1.createSdkClientMatcher)((0,module_evidence_1.createModuleListMatcher)(config.modules));return(0,rule_creator_1.createRule)({name:config.ruleName,meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:config.docsUrl,description:`Forbid a literal API key in the ${config.vendor} client options`,cwe:"CWE-798",cvss:9.1},messages:{hardcodedApiKey:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:`Hardcoded ${config.vendor} Credential`,cwe:"CWE-798",owasp:"A07:2021",cvss:9.1,description:"{{prop}} is a string literal, so the credential is committed to source control and readable by anyone with repository access",severity:"CRITICAL",compliance:["SOC2","PCI-DSS"],fix:`Read it from the environment: ${config.fixTemplate}`,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],createOnce(context){let sourceCode;const isHardcodedKey=node=>(0,sdk_flow_1.committedStrings)(node,sourceCode).some(sdk_flow_1.isCredentialShaped);function credentialProp(options){return config.keyProps.find(prop=>{const read=(0,sdk_flow_1.readObjectProperty)(options,prop,sourceCode);return read.kind==="value"&&isHardcodedKey(read.node)})}function inspect(node){const indices=matcher.optionArguments(node,sourceCode);if(indices.length===0)return;const first=node.arguments[0];if(positional.size>0&&first!==void 0&&indices.includes(0)){const binding=matcher.exportOf(node.callee,sourceCode);if(binding!==void 0&&positional.has((0,sdk_flow_1.sdkExportName)(binding))&&isHardcodedKey(first)){context.report({node,messageId:"hardcodedApiKey",data:{prop:exports.POSITIONAL_KEY_LABEL}});return}}for(const index of indices){const argument=node.arguments[index];if(argument===void 0||argument.type==="SpreadElement")continue;const options=(0,sdk_flow_1.resolveObjectLiteral)(argument,sourceCode);const prop=options&&credentialProp(options);if(prop!==void 0){context.report({node,messageId:"hardcodedApiKey",data:{prop}});return}}}return{before(){if(!usesSdk(context.sourceCode.ast))return false;sourceCode=context.sourceCode;return true},NewExpression:inspect,CallExpression:inspect}}})}
@@ -1,8 +1,3 @@
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
1
  import type { TSESLint } from '@typescript-eslint/utils';
7
2
  /** Message ids every rule built by this factory reports. */
8
3
  export type SqlInjectionMessageIds = 'noUnsafeQuery' | 'unsafeTemplateLiteral';
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.looksLikeSqlStatement=looksLikeSqlStatement;exports.createSqlInjectionRule=createSqlInjectionRule;const ast_node_types_1=require("../ast-node-types");const spellings_1=require("../ast/spellings");const type_syntax_1=require("../ast/type-syntax");const messaging_1=require("../messaging");const module_evidence_1=require("./module-evidence");const rule_creator_1=require("./rule-creator");const driver_origin_1=require("./driver-origin");const request_source_1=require("./request-source");const sql_safety_1=require("./sql-safety");const sql_position_1=require("./sql-position");const value_follow_1=require("./value-follow");const SQL_STATEMENTS=[/^[\s(]*select\b[\s\S]*\bfrom\b/i,/^[\s(]*select\s/i,/^\s*insert\s+(?:or\s+\w+\s+|ignore\s+)?into\b/i,/^\s*update\b[\s\S]*\bset\b/i,/^\s*delete\s+from\b/i,/^\s*(?:replace|merge)\s+into\b/i,/^\s*with\b[\s\S]*\bas\s*\(/i,/^\s*(?:create|drop|alter|truncate)\s+(?:unique\s+|temp(?:orary)?\s+|or\s+replace\s+)*(?:table|index|view|schema|database|sequence|trigger|function|procedure|user|role)\b/i,/^\s*(?:pragma|attach|detach|vacuum|analyze|reindex|show|describe|explain)\b/i,/^\s*call\s+[\w".`]+\s*\(/i];const PARTITION_SHARED_SINKS=new Set(["query","execute"]);function looksLikeSqlStatement(text){return SQL_STATEMENTS.some(pattern=>pattern.test(text))}function enclosingFunction(node){for(let n=node.parent;n;n=n.parent){if((0,driver_origin_1.isFunctionNode)(n))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 createSqlInjectionRule(config){const statementSinks=new Set(config.methods);const fragmentSinks=new Map;for(const sink of config.fragmentMethods??[]){const spec=typeof sink==="string"?{name:sink}:sink;fragmentSinks.set(spec.name,{name:spec.name,arg:spec.arg??0,requireDriverReceiver:spec.requireDriverReceiver??false})}const fragmentFunctions=new Set(config.fragmentFunctions??[]);const aliasCallbacks=new Set(config.aliasCallbacks??[]);const sqlTextProperties=new Set(config.sqlTextProperties??[]);const statementFactories=new Set(config.statementFactories??[]);const usesModule=(0,module_evidence_1.createModuleEvidence)({packages:config.modules});const originOf=(0,driver_origin_1.createOriginClassifier)(config.modules);const safety=(0,sql_safety_1.createSqlSafety)({origin:originOf,escapers:new Set(config.escapers??[]),fragmentFactories:new Set(config.fragmentFactories??[]),modules:config.modules,escaperModules:config.escaperModules});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){if((0,rule_creator_1.isTestFilePath)(context.filename))return{};const env=(0,value_follow_1.envOf)(context);const wrappers=new Map;const definitions=new Map;const wrapperFns=new Map;const pending=[];let ownsFile=false;const judge=(node,gate,depth=0)=>{const arg=(0,type_syntax_1.unwrapTypeSyntax)(node);if(arg.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral||arg.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression&&arg.operator==="+"){if(arg.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral&&arg.expressions.length===0){return false}const kind=arg.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral?"template":"concat";const text=(0,sql_safety_1.sqlStaticText)(arg);if(kind==="concat"&&text.trim()==="")return false;if(gate&&!looksLikeSqlStatement(text))return false;return(0,sql_position_1.sqlHoles)(arg).some(isUnsafeHole)?kind:false}if(depth>2)return false;if(arg.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return judgeBinding(arg,gate,depth)}if(arg.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){const target=(0,value_follow_1.follow)((0,value_follow_1.valueAt)(arg.callee,env));if(target.env!==env||!(0,driver_origin_1.isFunctionNode)(target.node))return false;for(const result of(0,value_follow_1.returnedValues)(target.node)??[]){const kind=judge(result,gate,depth+1);if(kind)return kind}}return false};const isUnsafeHole=({expression,preceding})=>!safety.isSafe((0,value_follow_1.valueAt)(expression,env),(0,sql_position_1.isQuoted)(preceding))&&((0,sql_position_1.isValuePosition)(preceding,config.doubleQuotedStrings)||(0,sql_position_1.isRequestDerived)(expression,env));const judgeBinding=(node,gate,depth)=>{const variable=(0,value_follow_1.lookup)(node.name,env.scopeOf(node));if(variable===null||!variable.defs.some(def=>def.type==="Variable")||variable.defs.some(def=>def.type==="Parameter")){return false}const writes=variable.references.filter(r=>r.isWrite()&&r.writeExpr).map(r=>r.writeExpr);const text=writes.map(sql_safety_1.sqlStaticText).join(" ");if(gate&&!looksLikeSqlStatement(text))return false;for(const write of writes){const kind=judge(write,false,depth+1);if(kind)return kind}return false};const isRequestText=node=>{let cursor=(0,type_syntax_1.unwrapTypeSyntax)(node);while(cursor.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&cursor.callee.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&cursor.callee.name==="String"&&cursor.arguments.length===1){cursor=(0,type_syntax_1.unwrapTypeSyntax)(cursor.arguments[0])}for(let link=cursor;;link=link.object){if((0,request_source_1.isRequestPayload)(link,env))return true;if(link.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression)return false}};const report=(node,kind)=>{context.report({node,messageId:kind==="template"?"unsafeTemplateLiteral":"noUnsafeQuery"})};let requestTextSink=true;const isStatementObject=receiver=>{const value=(0,type_syntax_1.unwrapTypeSyntax)((0,value_follow_1.follow)((0,value_follow_1.valueAt)(receiver,env)).node);return value.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&value.callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&statementFactories.has((0,spellings_1.propertyName)(value.callee)??"")};const check=(arg,gate)=>{let text=(0,type_syntax_1.unwrapTypeSyntax)(arg);if(text.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&sqlTextProperties.size>0){const property=text.properties.find(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Property&&sqlTextProperties.has((0,spellings_1.objectKeyName)(p)??""));if(property===void 0)return;text=property.value}const kind=judge(text,gate);if(kind){report(text,kind);return}if(requestTextSink&&isRequestText(text))report(text,"concat")};const importedName=callee=>{const variable=(0,value_follow_1.lookup)(callee.name,env.scopeOf(callee));const specifier=variable===null?null:(0,value_follow_1.importSpecifierOf)(variable);return specifier!==null&&config.modules.some(m=>specifier.source===m||specifier.source.startsWith(`${m}/`))?specifier.name:null};const checkAliasCallback=node=>{const callback=node.arguments[0];if(!callback||!(0,driver_origin_1.isFunctionNode)(callback))return;const alias=callback.params[0];for(const result of(0,value_follow_1.returnedValues)(callback)??[]){const text=(0,type_syntax_1.unwrapTypeSyntax)(result);if(text.type!==ast_node_types_1.AST_NODE_TYPES.TemplateLiteral)continue;const unsafe=(0,sql_position_1.sqlHoles)(text).some(hole=>!(hole.expression.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&alias?.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&hole.expression.name===alias.name)&&isUnsafeHole(hole));if(unsafe)report(text,"template")}};return{Program(program){ownsFile=usesModule(program)},"FunctionDeclaration, FunctionExpression, ArrowFunctionExpression"(node){const name=callableName(node);if(name!==void 0)definitions.set(name,(definitions.get(name)??0)+1)},CallExpression(node){const callee=node.callee;const isMember=callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression;const calleeName=isMember?(0,spellings_1.propertyName)(callee)??void 0:callee.type===ast_node_types_1.AST_NODE_TYPES.Identifier?callee.name:void 0;if(calleeName===void 0)return;if(!isMember&&ownsFile){const imported=importedName(callee);if(imported!==null&&fragmentFunctions.has(imported)){requestTextSink=true;if(node.arguments[0])check(node.arguments[0],false);return}if(imported!==null&&aliasCallbacks.has(imported)){checkAliasCallback(node);return}}const fragment=isMember?fragmentSinks.get(calleeName):void 0;if(!isMember||!statementSinks.has(calleeName)&&!fragment){for(const[index,arg]of node.arguments.entries()){if(arg.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;pending.push({name:calleeName,index,arg})}return}const receiver=originOf((0,value_follow_1.valueAt)(callee.object,env));if(receiver==="foreign")return;if(fragment?.requireDriverReceiver&&receiver!=="ours")return;if(!ownsFile&&!(receiver==="ours"&&!PARTITION_SHARED_SINKS.has(calleeName))){return}const queryArg=node.arguments[fragment?.arg??0];if(!queryArg||queryArg.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)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 gate=fragment===void 0&&config.requireSqlKeywords&&receiver!=="ours";requestTextSink=!isStatementObject(callee.object);check(queryArg,gate)},"Program:exit"(){if(!ownsFile)return;const proven=new Map;for(const name of wrapperFns.values())proven.set(name,(proven.get(name)??0)+1);for(const{name,index,arg}of pending){if(wrappers.get(name)!==index)continue;if(definitions.get(name)!==proven.get(name))continue;const kind=judge(arg,true);if(kind)report((0,type_syntax_1.unwrapTypeSyntax)(arg),kind)}}}}}}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.looksLikeSqlStatement=looksLikeSqlStatement;exports.createSqlInjectionRule=createSqlInjectionRule;const rule_creator_1=require("./rule-creator");const ast_node_types_1=require("../ast-node-types");const spellings_1=require("../ast/spellings");const type_syntax_1=require("../ast/type-syntax");const messaging_1=require("../messaging");const module_evidence_1=require("./module-evidence");const rule_creator_2=require("./rule-creator");const driver_origin_1=require("./driver-origin");const request_source_1=require("./request-source");const sql_safety_1=require("./sql-safety");const sql_position_1=require("./sql-position");const value_follow_1=require("./value-follow");const SQL_STATEMENTS=[/^[\s(]*select\b[\s\S]*\bfrom\b/i,/^[\s(]*select\s/i,/^\s*insert\s+(?:or\s+\w+\s+|ignore\s+)?into\b/i,/^\s*update\b[\s\S]*\bset\b/i,/^\s*delete\s+from\b/i,/^\s*(?:replace|merge)\s+into\b/i,/^\s*with\b[\s\S]*\bas\s*\(/i,/^\s*(?:create|drop|alter|truncate)\s+(?:unique\s+|temp(?:orary)?\s+|or\s+replace\s+)*(?:table|index|view|schema|database|sequence|trigger|function|procedure|user|role)\b/i,/^\s*(?:pragma|attach|detach|vacuum|analyze|reindex|show|describe|explain)\b/i,/^\s*call\s+[\w".`]+\s*\(/i];const PARTITION_SHARED_SINKS=new Set(["query","execute"]);function looksLikeSqlStatement(text){return SQL_STATEMENTS.some(pattern=>pattern.test(text))}function enclosingFunction(node){for(let n=node.parent;n;n=n.parent){if((0,driver_origin_1.isFunctionNode)(n))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 createSqlInjectionRule(config){const statementSinks=new Set(config.methods);const fragmentSinks=new Map;for(const sink of config.fragmentMethods??[]){const spec=typeof sink==="string"?{name:sink}:sink;fragmentSinks.set(spec.name,{name:spec.name,arg:spec.arg??0,requireDriverReceiver:spec.requireDriverReceiver??false})}const fragmentFunctions=new Set(config.fragmentFunctions??[]);const aliasCallbacks=new Set(config.aliasCallbacks??[]);const sqlTextProperties=new Set(config.sqlTextProperties??[]);const statementFactories=new Set(config.statementFactories??[]);const usesModule=(0,module_evidence_1.createModuleEvidence)({packages:config.modules});const originOf=(0,driver_origin_1.createOriginClassifier)(config.modules);const safety=(0,sql_safety_1.createSqlSafety)({origin:originOf,escapers:new Set(config.escapers??[]),fragmentFactories:new Set(config.fragmentFactories??[]),modules:config.modules,escaperModules:config.escaperModules});return rule_creator_1.RuleCreator.withoutDocs({meta:{interop:{runtimes:["eslint","oxlint"]},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:[],createOnce(context){let env;let wrappers;let definitions;let wrapperFns;let pending;let ownsFile;let requestTextSink;const judge=(node,gate,depth=0)=>{const arg=(0,type_syntax_1.unwrapTypeSyntax)(node);if(arg.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral||arg.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression&&arg.operator==="+"){if(arg.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral&&arg.expressions.length===0){return false}const kind=arg.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral?"template":"concat";const text=(0,sql_safety_1.sqlStaticText)(arg);if(kind==="concat"&&text.trim()==="")return false;if(gate&&!looksLikeSqlStatement(text))return false;return(0,sql_position_1.sqlHoles)(arg).some(isUnsafeHole)?kind:false}if(depth>2)return false;if(arg.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return judgeBinding(arg,gate,depth)}if(arg.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){const target=(0,value_follow_1.follow)((0,value_follow_1.valueAt)(arg.callee,env));if(target.env!==env||!(0,driver_origin_1.isFunctionNode)(target.node))return false;for(const result of(0,value_follow_1.returnedValues)(target.node)??[]){const kind=judge(result,gate,depth+1);if(kind)return kind}}return false};const isUnsafeHole=({expression,preceding})=>!safety.isSafe((0,value_follow_1.valueAt)(expression,env),(0,sql_position_1.isQuoted)(preceding))&&((0,sql_position_1.isValuePosition)(preceding,config.doubleQuotedStrings)||(0,sql_position_1.isRequestDerived)(expression,env));const judgeBinding=(node,gate,depth)=>{const variable=(0,value_follow_1.lookup)(node.name,env.scopeOf(node));if(variable===null||!variable.defs.some(def=>def.type==="Variable")||variable.defs.some(def=>def.type==="Parameter")){return false}const writes=variable.references.filter(r=>r.isWrite()&&r.writeExpr).map(r=>r.writeExpr);const text=writes.map(sql_safety_1.sqlStaticText).join(" ");if(gate&&!looksLikeSqlStatement(text))return false;for(const write of writes){const kind=judge(write,false,depth+1);if(kind)return kind}return false};const isRequestText=node=>{let cursor=(0,type_syntax_1.unwrapTypeSyntax)(node);while(cursor.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&cursor.callee.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&cursor.callee.name==="String"&&cursor.arguments.length===1){cursor=(0,type_syntax_1.unwrapTypeSyntax)(cursor.arguments[0])}for(let link=cursor;;link=link.object){if((0,request_source_1.isRequestPayload)(link,env))return true;if(link.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression)return false}};const report=(node,kind)=>{context.report({node,messageId:kind==="template"?"unsafeTemplateLiteral":"noUnsafeQuery"})};const isStatementObject=receiver=>{const value=(0,type_syntax_1.unwrapTypeSyntax)((0,value_follow_1.follow)((0,value_follow_1.valueAt)(receiver,env)).node);return value.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&value.callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&statementFactories.has((0,spellings_1.propertyName)(value.callee)??"")};const check=(arg,gate)=>{let text=(0,type_syntax_1.unwrapTypeSyntax)(arg);if(text.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&sqlTextProperties.size>0){const property=text.properties.find(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Property&&sqlTextProperties.has((0,spellings_1.objectKeyName)(p)??""));if(property===void 0)return;text=property.value}const kind=judge(text,gate);if(kind){report(text,kind);return}if(requestTextSink&&isRequestText(text))report(text,"concat")};const importedName=callee=>{const variable=(0,value_follow_1.lookup)(callee.name,env.scopeOf(callee));const specifier=variable===null?null:(0,value_follow_1.importSpecifierOf)(variable);return specifier!==null&&config.modules.some(m=>specifier.source===m||specifier.source.startsWith(`${m}/`))?specifier.name:null};const checkAliasCallback=node=>{const callback=node.arguments[0];if(!callback||!(0,driver_origin_1.isFunctionNode)(callback))return;const alias=callback.params[0];for(const result of(0,value_follow_1.returnedValues)(callback)??[]){const text=(0,type_syntax_1.unwrapTypeSyntax)(result);if(text.type!==ast_node_types_1.AST_NODE_TYPES.TemplateLiteral)continue;const unsafe=(0,sql_position_1.sqlHoles)(text).some(hole=>!(hole.expression.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&alias?.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&hole.expression.name===alias.name)&&isUnsafeHole(hole));if(unsafe)report(text,"template")}};return{before(){if((0,rule_creator_2.isTestFilePath)(context.filename))return false;env=(0,value_follow_1.envOf)(context);wrappers=new Map;definitions=new Map;wrapperFns=new Map;pending=[];ownsFile=false;requestTextSink=true;return true},Program(program){ownsFile=usesModule(program)},"FunctionDeclaration, FunctionExpression, ArrowFunctionExpression"(node){const name=callableName(node);if(name!==void 0)definitions.set(name,(definitions.get(name)??0)+1)},CallExpression(node){const callee=node.callee;const isMember=callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression;const calleeName=isMember?(0,spellings_1.propertyName)(callee)??void 0:callee.type===ast_node_types_1.AST_NODE_TYPES.Identifier?callee.name:void 0;if(calleeName===void 0)return;if(!isMember&&ownsFile){const imported=importedName(callee);if(imported!==null&&fragmentFunctions.has(imported)){requestTextSink=true;if(node.arguments[0])check(node.arguments[0],false);return}if(imported!==null&&aliasCallbacks.has(imported)){checkAliasCallback(node);return}}const fragment=isMember?fragmentSinks.get(calleeName):void 0;if(!isMember||!statementSinks.has(calleeName)&&!fragment){for(const[index,arg]of node.arguments.entries()){if(arg.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;pending.push({name:calleeName,index,arg})}return}const receiver=originOf((0,value_follow_1.valueAt)(callee.object,env));if(receiver==="foreign")return;if(fragment?.requireDriverReceiver&&receiver!=="ours")return;if(!ownsFile&&!(receiver==="ours"&&!PARTITION_SHARED_SINKS.has(calleeName))){return}const queryArg=node.arguments[fragment?.arg??0];if(!queryArg||queryArg.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)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 gate=fragment===void 0&&config.requireSqlKeywords&&receiver!=="ours";requestTextSink=!isStatementObject(callee.object);check(queryArg,gate)},"Program:exit"(){if(!ownsFile)return;const proven=new Map;for(const name of wrapperFns.values())proven.set(name,(proven.get(name)??0)+1);for(const{name,index,arg}of pending){if(wrappers.get(name)!==index)continue;if(definitions.get(name)!==proven.get(name))continue;const kind=judge(arg,true);if(kind)report((0,type_syntax_1.unwrapTypeSyntax)(arg),kind)}}}}})}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isStaticInstruction=isStaticInstruction;exports.staticKey=staticKey;exports.isSystemMessage=isSystemMessage;exports.classifyInstruction=classifyInstruction;exports.messageContent=messageContent;exports.calleePath=calleePath;exports.createSystemPromptInjectionRule=createSystemPromptInjectionRule;const ast_node_types_1=require("../ast-node-types");const rule_creator_1=require("./rule-creator");const messaging_1=require("../messaging");const module_evidence_1=require("./module-evidence");const type_syntax_1=require("../ast/type-syntax");const spellings_1=require("../ast/spellings");const module_binding_1=require("../ast/module-binding");const sdk_flow_1=require("./sdk-flow");function isStaticInstruction(node){if(node.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return true;return isStaticText(node)}function isStaticText(node){if(node.type===ast_node_types_1.AST_NODE_TYPES.Literal)return typeof node.value==="string";if(node.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral)return node.expressions.length===0;if(node.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return isStaticText(node.left)&&isStaticText(node.right)}return false}function staticKey(prop){if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property||prop.computed)return void 0;if(prop.key.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return prop.key.name;if(prop.key.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"){return prop.key.value}return void 0}function isSystemMessage(node){if(node.type!==ast_node_types_1.AST_NODE_TYPES.ObjectExpression)return false;return node.properties.some(prop=>{if(staticKey(prop)!=="role")return false;const value=(0,type_syntax_1.unwrapTypeSyntax)(prop.value);return value.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof value.value==="string"&&INSTRUCTION_ROLES.has(value.value)})}const INSTRUCTION_ROLES=new Set(["system","developer"]);const MESSAGE_LIST_KEYS=["messages","input"];const NON_TEXT_TYPE_KEYWORDS=new Set([ast_node_types_1.AST_NODE_TYPES.TSNumberKeyword,ast_node_types_1.AST_NODE_TYPES.TSBooleanKeyword,ast_node_types_1.AST_NODE_TYPES.TSBigIntKeyword]);const NUMERIC_GLOBAL_CALLS=new Set(["Number","parseInt","parseFloat","Boolean"]);const NUMERIC_GLOBAL_NAMESPACES=new Set(["Math","Date"]);const NUMBER_FORMAT_METHODS=new Set(["toFixed","toPrecision","toExponential"]);const isGlobalNamed=(node,names,sourceCode)=>node.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&names.has(node.name)&&(0,sdk_flow_1.isGlobalReference)(node,sourceCode);const DATE=new Set(["Date"]);function isDateValue(node,sourceCode){const resolved=(0,sdk_flow_1.followConst)(node,sourceCode);return resolved.type===ast_node_types_1.AST_NODE_TYPES.NewExpression&&isGlobalNamed(resolved.callee,DATE,sourceCode)}function isNonTextParameter(id,sourceCode){const definition=(0,sdk_flow_1.variableOf)(id,sourceCode)?.defs[0];if(definition?.type!=="Parameter")return false;const annotation=definition.name.typeAnnotation?.typeAnnotation;if(annotation===void 0)return false;const members=annotation.type===ast_node_types_1.AST_NODE_TYPES.TSUnionType?annotation.types:[annotation];return members.every(member=>NON_TEXT_TYPE_KEYWORDS.has(member.type))}function isNonText(node,sourceCode,hops){if(hops<=0)return false;const current=(0,type_syntax_1.unwrapTypeSyntax)(node);switch(current.type){case ast_node_types_1.AST_NODE_TYPES.Literal:return typeof current.value!=="string";case ast_node_types_1.AST_NODE_TYPES.UnaryExpression:return true;case ast_node_types_1.AST_NODE_TYPES.BinaryExpression:return current.operator!=="+"||isNonText(current.left,sourceCode,hops-1)&&isNonText(current.right,sourceCode,hops-1);case ast_node_types_1.AST_NODE_TYPES.NewExpression:return isGlobalNamed(current.callee,DATE,sourceCode);case ast_node_types_1.AST_NODE_TYPES.MemberExpression:return(0,spellings_1.propertyName)(current)==="length";case ast_node_types_1.AST_NODE_TYPES.CallExpression:{const callee=(0,type_syntax_1.unwrapTypeSyntax)(current.callee);if(isGlobalNamed(callee,NUMERIC_GLOBAL_CALLS,sourceCode))return true;if(callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression)return false;const method=(0,spellings_1.propertyName)(callee);return isGlobalNamed((0,type_syntax_1.unwrapTypeSyntax)(callee.object),NUMERIC_GLOBAL_NAMESPACES,sourceCode)||method!==null&&NUMBER_FORMAT_METHODS.has(method)||isDateValue(callee.object,sourceCode)}case ast_node_types_1.AST_NODE_TYPES.Identifier:{if(isNonTextParameter(current,sourceCode))return true;const resolved=(0,sdk_flow_1.followConst)(current,sourceCode);return resolved!==current&&isNonText(resolved,sourceCode,hops-1)}default:return false}}function isFunctionNode(node){return node.type===ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration||node.type===ast_node_types_1.AST_NODE_TYPES.FunctionExpression||node.type===ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression}function returnedValues(fn){if(fn.body.type!==ast_node_types_1.AST_NODE_TYPES.BlockStatement)return[fn.body];const values=[];const stack=[fn.body];while(stack.length>0){const node=stack.pop();if(node.type===ast_node_types_1.AST_NODE_TYPES.ReturnStatement&&node.argument){values.push(node.argument)}for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];for(const child of Array.isArray(value)?value:[value]){if(child!==null&&typeof child==="object"&&typeof child.type==="string"&&!isFunctionNode(child)){stack.push(child)}}}}return values}function calledFunction(callee,sourceCode){const target=(0,type_syntax_1.unwrapTypeSyntax)(callee);if(target.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return void 0;const resolved=(0,sdk_flow_1.followConst)(target,sourceCode);if(isFunctionNode(resolved))return resolved;const definition=(0,sdk_flow_1.variableOf)(target,sourceCode)?.defs[0];return definition?.type==="FunctionName"?definition.node:void 0}function memberRoot(node){let current=node;while(current.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){current=(0,type_syntax_1.unwrapTypeSyntax)(current.object)}return current}function isImported(node,sourceCode){return node.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&(0,sdk_flow_1.variableOf)(node,sourceCode)?.defs[0]?.type==="ImportBinding"}const PATH_BUILTINS=new Set(["fs","fs/promises","os","path","path/posix","path/win32"]);const PATH_HELPERS=new Set(["mkdtemp","mkdtempSync","tmpdir","homedir","join","resolve","dirname","basename","relative","normalize"]);function isPathHelper(callee,sourceCode){const binding=(0,module_binding_1.resolveModuleBinding)(callee,sourceCode.getScope(callee));const method=binding?.path[binding.path.length-1];return binding!==void 0&&PATH_BUILTINS.has(binding.module)&&method!==void 0&&PATH_HELPERS.has(method)}function classifyInstruction(node,sourceCode,whole,hops=sdk_flow_1.MAX_FOLLOW_HOPS){const current=(0,type_syntax_1.unwrapTypeSyntax)(node);if(hops<=0)return"dynamic";if(isNonText(current,sourceCode,hops))return"static";const part=child=>classifyInstruction(child,sourceCode,false,hops-1);const allStatic=children=>children.every(child=>part(child)==="static")?"static":"dynamic";const branches=(a,b)=>{const verdicts=new Set([a,b].map(branch=>classifyInstruction(branch,sourceCode,whole,hops-1)));if(verdicts.has("dynamic"))return"dynamic";return verdicts.has("unknown")?"unknown":"static"};switch(current.type){case ast_node_types_1.AST_NODE_TYPES.Literal:return"static";case ast_node_types_1.AST_NODE_TYPES.TemplateLiteral:return allStatic(current.expressions);case ast_node_types_1.AST_NODE_TYPES.TaggedTemplateExpression:return allStatic(current.quasi.expressions);case ast_node_types_1.AST_NODE_TYPES.BinaryExpression:return allStatic([current.left,current.right]);case ast_node_types_1.AST_NODE_TYPES.ConditionalExpression:return branches(current.consequent,current.alternate);case ast_node_types_1.AST_NODE_TYPES.LogicalExpression:return branches(current.left,current.right);case ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression:case ast_node_types_1.AST_NODE_TYPES.FunctionExpression:return allStatic(returnedValues(current));case ast_node_types_1.AST_NODE_TYPES.CallExpression:return classifyCall(current,sourceCode,hops);case ast_node_types_1.AST_NODE_TYPES.AwaitExpression:return classifyInstruction(current.argument,sourceCode,whole,hops-1);case ast_node_types_1.AST_NODE_TYPES.Identifier:{const resolved=(0,sdk_flow_1.followConst)(current,sourceCode);if(resolved!==current){return classifyInstruction(resolved,sourceCode,whole,hops-1)}if(isImported(current,sourceCode))return"static";return whole?"unknown":"dynamic"}case ast_node_types_1.AST_NODE_TYPES.MemberExpression:{if((0,sdk_flow_1.isEnvironmentRead)(current,sourceCode))return"static";const object=(0,sdk_flow_1.resolveObjectLiteral)(current.object,sourceCode);if(object!==void 0){const key=(0,spellings_1.propertyName)(current);if(key===null){return allStatic(object.properties.map(property=>property.type===ast_node_types_1.AST_NODE_TYPES.Property?property.value:property))}const read=(0,sdk_flow_1.readObjectProperty)(object,key,sourceCode);if(read.kind==="value"){return classifyInstruction(read.node,sourceCode,whole,hops-1)}}const root=memberRoot(current);if(isImported(root,sourceCode))return"static";return whole&&root.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&(0,sdk_flow_1.isGlobalReference)(root,sourceCode)?"unknown":"dynamic"}default:return"dynamic"}}function classifyCall(call,sourceCode,hops){const part=child=>classifyInstruction(child,sourceCode,false,hops-1);const isStatic=child=>child.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement&&part(child)==="static";const callee=(0,type_syntax_1.unwrapTypeSyntax)(call.callee);if(isPathHelper(callee,sourceCode)){return call.arguments.every(isStatic)?"static":"dynamic"}if(callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){const array=(0,sdk_flow_1.resolveArrayLiteral)(callee.object,sourceCode);if(array!==void 0&&(0,spellings_1.propertyName)(callee)==="join"){const elements=array.elements.filter(element=>element!==null);return elements.every(isStatic)&&call.arguments.every(isStatic)?"static":"dynamic"}if(isImported(memberRoot(callee),sourceCode))return"dynamic";return part(callee.object)==="static"&&call.arguments.every(isStatic)?"static":"dynamic"}const fn=calledFunction(callee,sourceCode);if(fn===void 0)return"dynamic";return returnedValues(fn).every(isStatic)?"static":"dynamic"}function messageContent(node){for(const prop of node.properties){if(staticKey(prop)==="content")return prop.value}return void 0}function calleePath(callee){const parts=[];let node=callee;while(node.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){const name=(0,spellings_1.propertyName)(node);if(name===null)return void 0;parts.unshift(name);node=node.object}return parts.length>0?parts.join("."):void 0}function createSystemPromptInjectionRule(config){const promptProps=new Set(config.systemPromptProps);const paths=config.requestPaths;const usesSdk=(0,module_evidence_1.createModuleListEvidence)(config.modules);const owns=(0,module_evidence_1.createModuleListMatcher)(config.modules);const nestedKeys=config.nestedOptionKeys??[];const constructors=new Set(config.promptConstructors??[]);const batchPaths=config.batchRequestPaths??[];return(0,rule_creator_1.createRule)({name:config.ruleName,meta:{type:"problem",docs:{url:config.docsUrl,description:`Disallow untrusted content built into the ${config.vendor} system prompt`,cwe:"CWE-1427",cvss:8.1},messages:{untrustedSystemPrompt:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:`Untrusted Content in ${config.vendor} System Prompt`,cwe:"CWE-1427",owasp:"A03:2021",cvss:8.1,description:"The system prompt is built at runtime, so whatever is spliced in is read by the model as instructions rather than as data \u2014 anyone controlling that value controls the agent",severity:"HIGH",compliance:["SOC2"],fix:"Keep the system prompt a static string. Pass runtime values as a separate user message, where the model treats them as data \u2014 never interpolate them into the instructions.",documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){if(!usesSdk(context.sourceCode.ast))return{};const sourceCode=context.sourceCode;const reported=new Set;function inspectRequest(options,nested){for(const key of promptProps){const read=(0,sdk_flow_1.readObjectProperty)(options,key,sourceCode);if(read.kind==="value")collect(read.node)}for(const key of MESSAGE_LIST_KEYS){const read=(0,sdk_flow_1.readObjectProperty)(options,key,sourceCode);if(read.kind!=="value")continue;const list=(0,sdk_flow_1.resolveArrayLiteral)(read.node,sourceCode);for(const element of list?.elements??[]){if(element===null||element.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;const message=(0,sdk_flow_1.resolveObjectLiteral)(element,sourceCode);if(message===void 0||!isInstructionTurn(message))continue;const content=(0,sdk_flow_1.readObjectProperty)(message,"content",sourceCode);if(content.kind==="value")collect(content.node)}}if(nested)return;for(const key of nestedKeys){const read=(0,sdk_flow_1.readObjectProperty)(options,key,sourceCode);const inner=read.kind==="value"?(0,sdk_flow_1.resolveObjectLiteral)(read.node,sourceCode):void 0;if(inner!==void 0)inspectRequest(inner,true)}}function isInstructionTurn(message){const read=(0,sdk_flow_1.readObjectProperty)(message,"role",sourceCode);if(read.kind!=="value")return false;const role=(0,sdk_flow_1.followConst)(read.node,sourceCode);return role.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof role.value==="string"&&INSTRUCTION_ROLES.has(role.value)}function collect(value){const resolved=(0,sdk_flow_1.followConst)(value,sourceCode);if(resolved.type===ast_node_types_1.AST_NODE_TYPES.ArrayExpression){for(const element of resolved.elements){if(element!==null&&element.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement)collect(element)}return}if(resolved.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression){for(const key of["text","parts"]){const read=(0,sdk_flow_1.readObjectProperty)(resolved,key,sourceCode);if(read.kind==="value")collect(read.node)}return}if(classifyInstruction(value,sourceCode,true)==="dynamic"&&!reported.has(value)){reported.add(value);context.report({node:value,messageId:"untrustedSystemPrompt"})}}function receiverIsForeign(callee){const root=memberRoot(callee);const value=(0,sdk_flow_1.followConst)(root,sourceCode);if(value===root)return false;if(value.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression)return true;if(value.type!==ast_node_types_1.AST_NODE_TYPES.NewExpression)return false;if((0,sdk_flow_1.resolveSdkExport)(value.callee,sourceCode,owns)!==void 0)return false;const constructor=(0,type_syntax_1.unwrapTypeSyntax)(value.callee);if(constructor.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return false;const definition=(0,sdk_flow_1.variableOf)(constructor,sourceCode)?.defs[0];if(definition?.type==="ImportBinding"){const source=definition.parent.source.value;return!source.startsWith(".")}if(definition?.type==="ClassName"){const superClass=definition.node.superClass;return superClass===null||(0,sdk_flow_1.resolveSdkExport)(superClass,sourceCode,owns)===void 0}return false}function requestOf(node){if(node===void 0||node.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)return;const options=(0,sdk_flow_1.resolveObjectLiteral)(node,sourceCode);if(options!==void 0)inspectRequest(options,false)}function batchEntries(node){const list=(0,sdk_flow_1.resolveArrayLiteral)(node,sourceCode);if(list!==void 0){return list.elements.filter(element=>element!==null&&element.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement)}const call=(0,sdk_flow_1.followConst)(node,sourceCode);if(call.type!==ast_node_types_1.AST_NODE_TYPES.CallExpression||call.callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression||(0,spellings_1.propertyName)(call.callee)!=="map")return[];const callback=call.arguments[0];return callback!==void 0&&isFunctionNode(callback)?returnedValues(callback):[]}function batchOf(node){if(node===void 0||node.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)return;const batch=(0,sdk_flow_1.resolveObjectLiteral)(node,sourceCode);const read=batch===void 0?void 0:(0,sdk_flow_1.readObjectProperty)(batch,"requests",sourceCode);if(read?.kind!=="value")return;for(const element of batchEntries(read.node)){const entry=(0,sdk_flow_1.resolveObjectLiteral)(element,sourceCode);const params=entry===void 0?void 0:(0,sdk_flow_1.readObjectProperty)(entry,"params",sourceCode);if(params?.kind==="value")requestOf(params.node)}}const matches=(path,list)=>list.some(p=>path===p||path.endsWith(`.${p}`));return{CallExpression(node){const path=calleePath(node.callee);if(path===void 0)return;if(matches(path,batchPaths)){if(!receiverIsForeign(node.callee))batchOf(node.arguments[0]);return}if(!matches(path,paths))return;if(receiverIsForeign(node.callee))return;for(const argument of node.arguments)requestOf(argument)},NewExpression(node){if(constructors.size===0)return;const binding=(0,sdk_flow_1.resolveSdkExport)(node.callee,sourceCode,owns);if(binding===void 0)return;if(!constructors.has((0,sdk_flow_1.sdkExportName)(binding)))return;requestOf(node.arguments[0])}}}})}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isStaticInstruction=isStaticInstruction;exports.staticKey=staticKey;exports.isSystemMessage=isSystemMessage;exports.classifyInstruction=classifyInstruction;exports.messageContent=messageContent;exports.calleePath=calleePath;exports.createSystemPromptInjectionRule=createSystemPromptInjectionRule;const ast_node_types_1=require("../ast-node-types");const rule_creator_1=require("./rule-creator");const messaging_1=require("../messaging");const module_evidence_1=require("./module-evidence");const type_syntax_1=require("../ast/type-syntax");const spellings_1=require("../ast/spellings");const module_binding_1=require("../ast/module-binding");const sdk_flow_1=require("./sdk-flow");function isStaticInstruction(node){if(node.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return true;return isStaticText(node)}function isStaticText(node){if(node.type===ast_node_types_1.AST_NODE_TYPES.Literal)return typeof node.value==="string";if(node.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral)return node.expressions.length===0;if(node.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return isStaticText(node.left)&&isStaticText(node.right)}return false}function staticKey(prop){if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property||prop.computed)return void 0;if(prop.key.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return prop.key.name;if(prop.key.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"){return prop.key.value}return void 0}function isSystemMessage(node){if(node.type!==ast_node_types_1.AST_NODE_TYPES.ObjectExpression)return false;return node.properties.some(prop=>{if(staticKey(prop)!=="role")return false;const value=(0,type_syntax_1.unwrapTypeSyntax)(prop.value);return value.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof value.value==="string"&&INSTRUCTION_ROLES.has(value.value)})}const INSTRUCTION_ROLES=new Set(["system","developer"]);const MESSAGE_LIST_KEYS=["messages","input"];const NON_TEXT_TYPE_KEYWORDS=new Set([ast_node_types_1.AST_NODE_TYPES.TSNumberKeyword,ast_node_types_1.AST_NODE_TYPES.TSBooleanKeyword,ast_node_types_1.AST_NODE_TYPES.TSBigIntKeyword]);const NUMERIC_GLOBAL_CALLS=new Set(["Number","parseInt","parseFloat","Boolean"]);const NUMERIC_GLOBAL_NAMESPACES=new Set(["Math","Date"]);const NUMBER_FORMAT_METHODS=new Set(["toFixed","toPrecision","toExponential"]);const isGlobalNamed=(node,names,sourceCode)=>node.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&names.has(node.name)&&(0,sdk_flow_1.isGlobalReference)(node,sourceCode);const DATE=new Set(["Date"]);function isDateValue(node,sourceCode){const resolved=(0,sdk_flow_1.followConst)(node,sourceCode);return resolved.type===ast_node_types_1.AST_NODE_TYPES.NewExpression&&isGlobalNamed(resolved.callee,DATE,sourceCode)}function isNonTextParameter(id,sourceCode){const definition=(0,sdk_flow_1.variableOf)(id,sourceCode)?.defs[0];if(definition?.type!=="Parameter")return false;const annotation=definition.name.typeAnnotation?.typeAnnotation;if(annotation===void 0)return false;const members=annotation.type===ast_node_types_1.AST_NODE_TYPES.TSUnionType?annotation.types:[annotation];return members.every(member=>NON_TEXT_TYPE_KEYWORDS.has(member.type))}function isNonText(node,sourceCode,hops){if(hops<=0)return false;const current=(0,type_syntax_1.unwrapTypeSyntax)(node);switch(current.type){case ast_node_types_1.AST_NODE_TYPES.Literal:return typeof current.value!=="string";case ast_node_types_1.AST_NODE_TYPES.UnaryExpression:return true;case ast_node_types_1.AST_NODE_TYPES.BinaryExpression:return current.operator!=="+"||isNonText(current.left,sourceCode,hops-1)&&isNonText(current.right,sourceCode,hops-1);case ast_node_types_1.AST_NODE_TYPES.NewExpression:return isGlobalNamed(current.callee,DATE,sourceCode);case ast_node_types_1.AST_NODE_TYPES.MemberExpression:return(0,spellings_1.propertyName)(current)==="length";case ast_node_types_1.AST_NODE_TYPES.CallExpression:{const callee=(0,type_syntax_1.unwrapTypeSyntax)(current.callee);if(isGlobalNamed(callee,NUMERIC_GLOBAL_CALLS,sourceCode))return true;if(callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression)return false;const method=(0,spellings_1.propertyName)(callee);return isGlobalNamed((0,type_syntax_1.unwrapTypeSyntax)(callee.object),NUMERIC_GLOBAL_NAMESPACES,sourceCode)||method!==null&&NUMBER_FORMAT_METHODS.has(method)||isDateValue(callee.object,sourceCode)}case ast_node_types_1.AST_NODE_TYPES.Identifier:{if(isNonTextParameter(current,sourceCode))return true;const resolved=(0,sdk_flow_1.followConst)(current,sourceCode);return resolved!==current&&isNonText(resolved,sourceCode,hops-1)}default:return false}}function isFunctionNode(node){return node.type===ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration||node.type===ast_node_types_1.AST_NODE_TYPES.FunctionExpression||node.type===ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression}function returnedValues(fn){if(fn.body.type!==ast_node_types_1.AST_NODE_TYPES.BlockStatement)return[fn.body];const values=[];const stack=[fn.body];while(stack.length>0){const node=stack.pop();if(node.type===ast_node_types_1.AST_NODE_TYPES.ReturnStatement&&node.argument){values.push(node.argument)}for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];for(const child of Array.isArray(value)?value:[value]){if(child!==null&&typeof child==="object"&&typeof child.type==="string"&&!isFunctionNode(child)){stack.push(child)}}}}return values}function calledFunction(callee,sourceCode){const target=(0,type_syntax_1.unwrapTypeSyntax)(callee);if(target.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return void 0;const resolved=(0,sdk_flow_1.followConst)(target,sourceCode);if(isFunctionNode(resolved))return resolved;const definition=(0,sdk_flow_1.variableOf)(target,sourceCode)?.defs[0];return definition?.type==="FunctionName"?definition.node:void 0}function memberRoot(node){let current=node;while(current.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){current=(0,type_syntax_1.unwrapTypeSyntax)(current.object)}return current}function isImported(node,sourceCode){return node.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&(0,sdk_flow_1.variableOf)(node,sourceCode)?.defs[0]?.type==="ImportBinding"}const PATH_BUILTINS=new Set(["fs","fs/promises","os","path","path/posix","path/win32"]);const PATH_HELPERS=new Set(["mkdtemp","mkdtempSync","tmpdir","homedir","join","resolve","dirname","basename","relative","normalize"]);function isPathHelper(callee,sourceCode){const binding=(0,module_binding_1.resolveModuleBinding)(callee,sourceCode.getScope(callee));const method=binding?.path[binding.path.length-1];return binding!==void 0&&PATH_BUILTINS.has(binding.module)&&method!==void 0&&PATH_HELPERS.has(method)}function classifyInstruction(node,sourceCode,whole,hops=sdk_flow_1.MAX_FOLLOW_HOPS){const current=(0,type_syntax_1.unwrapTypeSyntax)(node);if(hops<=0)return"dynamic";if(isNonText(current,sourceCode,hops))return"static";const part=child=>classifyInstruction(child,sourceCode,false,hops-1);const allStatic=children=>children.every(child=>part(child)==="static")?"static":"dynamic";const branches=(a,b)=>{const verdicts=new Set([a,b].map(branch=>classifyInstruction(branch,sourceCode,whole,hops-1)));if(verdicts.has("dynamic"))return"dynamic";return verdicts.has("unknown")?"unknown":"static"};switch(current.type){case ast_node_types_1.AST_NODE_TYPES.Literal:return"static";case ast_node_types_1.AST_NODE_TYPES.TemplateLiteral:return allStatic(current.expressions);case ast_node_types_1.AST_NODE_TYPES.TaggedTemplateExpression:return allStatic(current.quasi.expressions);case ast_node_types_1.AST_NODE_TYPES.BinaryExpression:return allStatic([current.left,current.right]);case ast_node_types_1.AST_NODE_TYPES.ConditionalExpression:return branches(current.consequent,current.alternate);case ast_node_types_1.AST_NODE_TYPES.LogicalExpression:return branches(current.left,current.right);case ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression:case ast_node_types_1.AST_NODE_TYPES.FunctionExpression:return allStatic(returnedValues(current));case ast_node_types_1.AST_NODE_TYPES.CallExpression:return classifyCall(current,sourceCode,hops);case ast_node_types_1.AST_NODE_TYPES.AwaitExpression:return classifyInstruction(current.argument,sourceCode,whole,hops-1);case ast_node_types_1.AST_NODE_TYPES.Identifier:{const resolved=(0,sdk_flow_1.followConst)(current,sourceCode);if(resolved!==current){return classifyInstruction(resolved,sourceCode,whole,hops-1)}if(isImported(current,sourceCode))return"static";return whole?"unknown":"dynamic"}case ast_node_types_1.AST_NODE_TYPES.MemberExpression:{if((0,sdk_flow_1.isEnvironmentRead)(current,sourceCode))return"static";const object=(0,sdk_flow_1.resolveObjectLiteral)(current.object,sourceCode);if(object!==void 0){const key=(0,spellings_1.propertyName)(current);if(key===null){return allStatic(object.properties.map(property=>property.type===ast_node_types_1.AST_NODE_TYPES.Property?property.value:property))}const read=(0,sdk_flow_1.readObjectProperty)(object,key,sourceCode);if(read.kind==="value"){return classifyInstruction(read.node,sourceCode,whole,hops-1)}}const root=memberRoot(current);if(isImported(root,sourceCode))return"static";return whole&&root.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&(0,sdk_flow_1.isGlobalReference)(root,sourceCode)?"unknown":"dynamic"}default:return"dynamic"}}function classifyCall(call,sourceCode,hops){const part=child=>classifyInstruction(child,sourceCode,false,hops-1);const isStatic=child=>child.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement&&part(child)==="static";const callee=(0,type_syntax_1.unwrapTypeSyntax)(call.callee);if(isPathHelper(callee,sourceCode)){return call.arguments.every(isStatic)?"static":"dynamic"}if(callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){const array=(0,sdk_flow_1.resolveArrayLiteral)(callee.object,sourceCode);if(array!==void 0&&(0,spellings_1.propertyName)(callee)==="join"){const elements=array.elements.filter(element=>element!==null);return elements.every(isStatic)&&call.arguments.every(isStatic)?"static":"dynamic"}if(isImported(memberRoot(callee),sourceCode))return"dynamic";return part(callee.object)==="static"&&call.arguments.every(isStatic)?"static":"dynamic"}const fn=calledFunction(callee,sourceCode);if(fn===void 0)return"dynamic";return returnedValues(fn).every(isStatic)?"static":"dynamic"}function messageContent(node){for(const prop of node.properties){if(staticKey(prop)==="content")return prop.value}return void 0}function calleePath(callee){const parts=[];let node=callee;while(node.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){const name=(0,spellings_1.propertyName)(node);if(name===null)return void 0;parts.unshift(name);node=node.object}return parts.length>0?parts.join("."):void 0}function createSystemPromptInjectionRule(config){const promptProps=new Set(config.systemPromptProps);const paths=config.requestPaths;const usesSdk=(0,module_evidence_1.createModuleListEvidence)(config.modules);const owns=(0,module_evidence_1.createModuleListMatcher)(config.modules);const nestedKeys=config.nestedOptionKeys??[];const constructors=new Set(config.promptConstructors??[]);const batchPaths=config.batchRequestPaths??[];return(0,rule_creator_1.createRule)({name:config.ruleName,meta:{interop:{runtimes:["eslint","oxlint"]},type:"problem",docs:{url:config.docsUrl,description:`Disallow untrusted content built into the ${config.vendor} system prompt`,cwe:"CWE-1427",cvss:8.1},messages:{untrustedSystemPrompt:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:`Untrusted Content in ${config.vendor} System Prompt`,cwe:"CWE-1427",owasp:"A03:2021",cvss:8.1,description:"The system prompt is built at runtime, so whatever is spliced in is read by the model as instructions rather than as data \u2014 anyone controlling that value controls the agent",severity:"HIGH",compliance:["SOC2"],fix:"Keep the system prompt a static string. Pass runtime values as a separate user message, where the model treats them as data \u2014 never interpolate them into the instructions.",documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],createOnce(context){let sourceCode;let reported;function inspectRequest(options,nested){for(const key of promptProps){const read=(0,sdk_flow_1.readObjectProperty)(options,key,sourceCode);if(read.kind==="value")collect(read.node)}for(const key of MESSAGE_LIST_KEYS){const read=(0,sdk_flow_1.readObjectProperty)(options,key,sourceCode);if(read.kind!=="value")continue;const list=(0,sdk_flow_1.resolveArrayLiteral)(read.node,sourceCode);for(const element of list?.elements??[]){if(element===null||element.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;const message=(0,sdk_flow_1.resolveObjectLiteral)(element,sourceCode);if(message===void 0||!isInstructionTurn(message))continue;const content=(0,sdk_flow_1.readObjectProperty)(message,"content",sourceCode);if(content.kind==="value")collect(content.node)}}if(nested)return;for(const key of nestedKeys){const read=(0,sdk_flow_1.readObjectProperty)(options,key,sourceCode);const inner=read.kind==="value"?(0,sdk_flow_1.resolveObjectLiteral)(read.node,sourceCode):void 0;if(inner!==void 0)inspectRequest(inner,true)}}function isInstructionTurn(message){const read=(0,sdk_flow_1.readObjectProperty)(message,"role",sourceCode);if(read.kind!=="value")return false;const role=(0,sdk_flow_1.followConst)(read.node,sourceCode);return role.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof role.value==="string"&&INSTRUCTION_ROLES.has(role.value)}function collect(value){const resolved=(0,sdk_flow_1.followConst)(value,sourceCode);if(resolved.type===ast_node_types_1.AST_NODE_TYPES.ArrayExpression){for(const element of resolved.elements){if(element!==null&&element.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement)collect(element)}return}if(resolved.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression){for(const key of["text","parts"]){const read=(0,sdk_flow_1.readObjectProperty)(resolved,key,sourceCode);if(read.kind==="value")collect(read.node)}return}if(classifyInstruction(value,sourceCode,true)==="dynamic"&&!reported.has(value)){reported.add(value);context.report({node:value,messageId:"untrustedSystemPrompt"})}}function receiverIsForeign(callee){const root=memberRoot(callee);const value=(0,sdk_flow_1.followConst)(root,sourceCode);if(value===root)return false;if(value.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression)return true;if(value.type!==ast_node_types_1.AST_NODE_TYPES.NewExpression)return false;if((0,sdk_flow_1.resolveSdkExport)(value.callee,sourceCode,owns)!==void 0)return false;const constructor=(0,type_syntax_1.unwrapTypeSyntax)(value.callee);if(constructor.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return false;const definition=(0,sdk_flow_1.variableOf)(constructor,sourceCode)?.defs[0];if(definition?.type==="ImportBinding"){const source=definition.parent.source.value;return!source.startsWith(".")}if(definition?.type==="ClassName"){const superClass=definition.node.superClass;return superClass===null||(0,sdk_flow_1.resolveSdkExport)(superClass,sourceCode,owns)===void 0}return false}function requestOf(node){if(node===void 0||node.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)return;const options=(0,sdk_flow_1.resolveObjectLiteral)(node,sourceCode);if(options!==void 0)inspectRequest(options,false)}function batchEntries(node){const list=(0,sdk_flow_1.resolveArrayLiteral)(node,sourceCode);if(list!==void 0){return list.elements.filter(element=>element!==null&&element.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement)}const call=(0,sdk_flow_1.followConst)(node,sourceCode);if(call.type!==ast_node_types_1.AST_NODE_TYPES.CallExpression||call.callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression||(0,spellings_1.propertyName)(call.callee)!=="map")return[];const callback=call.arguments[0];return callback!==void 0&&isFunctionNode(callback)?returnedValues(callback):[]}function batchOf(node){if(node===void 0||node.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)return;const batch=(0,sdk_flow_1.resolveObjectLiteral)(node,sourceCode);const read=batch===void 0?void 0:(0,sdk_flow_1.readObjectProperty)(batch,"requests",sourceCode);if(read?.kind!=="value")return;for(const element of batchEntries(read.node)){const entry=(0,sdk_flow_1.resolveObjectLiteral)(element,sourceCode);const params=entry===void 0?void 0:(0,sdk_flow_1.readObjectProperty)(entry,"params",sourceCode);if(params?.kind==="value")requestOf(params.node)}}const matches=(path,list)=>list.some(p=>path===p||path.endsWith(`.${p}`));return{before(){if(!usesSdk(context.sourceCode.ast))return false;sourceCode=context.sourceCode;reported=new Set;return true},CallExpression(node){const path=calleePath(node.callee);if(path===void 0)return;if(matches(path,batchPaths)){if(!receiverIsForeign(node.callee))batchOf(node.arguments[0]);return}if(!matches(path,paths))return;if(receiverIsForeign(node.callee))return;for(const argument of node.arguments)requestOf(argument)},NewExpression(node){if(constructors.size===0)return;const binding=(0,sdk_flow_1.resolveSdkExport)(node.callee,sourceCode,owns);if(binding===void 0)return;if(!constructors.has((0,sdk_flow_1.sdkExportName)(binding)))return;requestOf(node.arguments[0])}}}})}
@@ -1,8 +1,3 @@
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
1
  import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
7
2
  import { type Env } from './value-follow';
8
3
  /** Message ids every rule built by this factory reports. */
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.propertyKeyName=propertyKeyName;exports.hasTruthyKey=hasTruthyKey;exports.hasArgumentScope=hasArgumentScope;exports.chainMethodNames=chainMethodNames;exports.driverBindings=driverBindings;exports.receiverBaseName=receiverBaseName;exports.createUnscopedMutationRule=createUnscopedMutationRule;exports.startsWithTable=startsWithTable;exports.insideAny=insideAny;exports.exportedFunctions=exportedFunctions;exports.scopedElsewhere=scopedElsewhere;const ast_node_types_1=require("../ast-node-types");const spellings_1=require("../ast/spellings");const messaging_1=require("../messaging");const module_evidence_1=require("./module-evidence");const rule_creator_1=require("./rule-creator");const driver_origin_1=require("./driver-origin");const value_follow_1=require("./value-follow");const DEFAULT_SCOPE_KEYS=["where"];const DEFAULT_SCOPE_METHODS=["where"];function propertyKeyName(prop){if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property)return void 0;if(prop.computed)return void 0;if(prop.key.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return prop.key.name;if(prop.key.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"){return prop.key.value}return void 0}function hasTruthyKey(obj,keys){return obj.properties.some(prop=>{if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property)return false;const name=propertyKeyName(prop);if(name===void 0||!keys.includes(name))return false;return!(prop.value.type===ast_node_types_1.AST_NODE_TYPES.Literal&&!prop.value.value)})}function hasArgumentScope(args,scopeKeys){return args.some(arg=>{if(arg.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression){return arg.properties.some(prop=>{if(prop.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)return true;const name=propertyKeyName(prop);if(name===void 0)return true;if(!scopeKeys.includes(name))return false;if(prop.type===ast_node_types_1.AST_NODE_TYPES.Property&&prop.value.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&prop.value.properties.length===0){return false}return true})}return arg.type!==ast_node_types_1.AST_NODE_TYPES.Literal})}function chainMethodNames(node){let root=node;for(;;){const parent=root.parent;if(!parent)break;if(parent.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&parent.object===root){root=parent;continue}if(parent.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&parent.callee===root){root=parent;continue}break}const names=new Set;let cursor=root;for(;;){if(cursor.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){cursor=cursor.callee;continue}if(cursor.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){if(!cursor.computed&&cursor.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier){names.add(cursor.property.name)}cursor=cursor.object;continue}break}return names}function driverBindings(program,modules){const names=new Set;const isDriver=source=>modules.some(m=>source===m||source.startsWith(`${m}/`));for(const stmt of program.body){if(stmt.type===ast_node_types_1.AST_NODE_TYPES.ImportDeclaration){if(typeof stmt.source.value!=="string"||!isDriver(stmt.source.value))continue;for(const spec of stmt.specifiers)names.add(spec.local.name);continue}if(stmt.type!==ast_node_types_1.AST_NODE_TYPES.VariableDeclaration)continue;for(const decl of stmt.declarations){const init=decl.init;if(!init||init.type!==ast_node_types_1.AST_NODE_TYPES.CallExpression||init.callee.type!==ast_node_types_1.AST_NODE_TYPES.Identifier||init.callee.name!=="require"){continue}const arg=init.arguments[0];if(!arg||arg.type!==ast_node_types_1.AST_NODE_TYPES.Literal||typeof arg.value!=="string"||!isDriver(arg.value)){continue}if(decl.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier)names.add(decl.id.name);if(decl.id.type===ast_node_types_1.AST_NODE_TYPES.ObjectPattern){for(const prop of decl.id.properties){if(prop.type===ast_node_types_1.AST_NODE_TYPES.Property&&prop.value.type===ast_node_types_1.AST_NODE_TYPES.Identifier){names.add(prop.value.name)}}}}}return names}function receiverBaseName(node){let cursor=node.object;for(;;){if(cursor.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){if(cursor.object.type===ast_node_types_1.AST_NODE_TYPES.ThisExpression&&!cursor.computed&&cursor.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return cursor.property.name}cursor=cursor.object;continue}if(cursor.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){cursor=cursor.callee;continue}return cursor.type===ast_node_types_1.AST_NODE_TYPES.Identifier?cursor.name:void 0}}function createUnscopedMutationRule(config){const sinks=new Set(config.methods);const scopeKeys=config.scopeKeys??DEFAULT_SCOPE_KEYS;const scopeMethods=config.scopeMethods??DEFAULT_SCOPE_METHODS;const truncateKeys=config.truncateKeys??[];const argumentRole=config.argumentRole??"options";const usesModule=(0,module_evidence_1.createModuleEvidence)({packages:config.modules});const originOf=(0,driver_origin_1.createOriginClassifier)(config.modules);return{meta:{type:config.meta.type,docs:{...config.meta.docs},messages:{unscopedMutation:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Unscoped Bulk Mutation",description:"Bulk mutation with no filter detected. This rewrites or deletes every row in the table.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A01:2021",compliance:["SOC2","NIST-CSF"],effort:"low",fix:config.fix,documentationLink:config.documentationLink}),explicitTruncate:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Unscoped Bulk Mutation",description:"Table truncation detected. This ignores any filter and empties the whole table.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A01:2021",compliance:["SOC2","NIST-CSF"],effort:"low",fix:"Remove the truncate flag and delete by filter, or move the truncation to an explicit maintenance script.",documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){if((0,rule_creator_1.isTestFilePath)(context.filename))return{};const env=(0,value_follow_1.envOf)(context);let ownsFile=false;let migrations=new Set;return{Program(program){ownsFile=usesModule(program);migrations=exportedFunctions(program,config.migrationExports??[],context)},CallExpression(node){if(node.callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression||node.callee.computed||node.callee.property.type!==ast_node_types_1.AST_NODE_TYPES.Identifier||!sinks.has(node.callee.property.name)){return}const origin=originOf((0,value_follow_1.valueAt)(node.callee.object,env));if(origin==="foreign")return;if(origin==="unknown"&&!(ownsFile&&hasDistinctiveShape(node))){return}if(insideAny(node,migrations))return;if(truncateKeys.length>0){const truncating=node.arguments.some(arg=>arg.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&hasTruthyKey(arg,truncateKeys));if(truncating){context.report({node,messageId:"explicitTruncate"});return}}if(argumentRole==="options"){if(config.requireOptionsObject===true&&!node.arguments.some(arg=>arg.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression)){return}if(hasArgumentScope(node.arguments,scopeKeys))return}const chained=chainMethodNames(node);if(scopeMethods.some(name=>chained.has(name)))return;if(scopedElsewhere(node,scopeMethods,env))return;context.report({node,messageId:"unscopedMutation"})}};function hasDistinctiveShape(node){const callee=node.callee;switch(config.distinctiveShape){case"model-accessor":return callee.object.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression;case"table-call":return startsWithTable(callee.object);case"table-argument":{const[table]=node.arguments;return table!==void 0&&table.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement&&originOf((0,value_follow_1.valueAt)(table,env))==="ours"}default:return false}}}}}const TABLE_STARTERS=new Set(["table","from","into","queryBuilder","withSchema"]);function startsWithTable(receiver){let cursor=receiver;for(;;){if(cursor.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){if(cursor.callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression)return true;if(TABLE_STARTERS.has((0,spellings_1.propertyName)(cursor.callee)??""))return true;cursor=cursor.callee.object;continue}if(cursor.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){cursor=cursor.object;continue}return false}}function insideAny(node,functions){for(let n=node.parent;n;n=n.parent){if(functions.has(n))return true}return false}function exportedFunctions(program,names,context){const found=new Set;const scopeManager=context.sourceCode.scopeManager;if(names.length===0||scopeManager===null)return found;const module={file:context.physicalFilename,ast:program,scopeManager};for(const name of names){const exported=(0,value_follow_1.exportedValue)(module,name,context.languageOptions?.parser);if(exported===null)continue;const target=(0,value_follow_1.follow)(exported);if((0,driver_origin_1.isFunctionNode)(target.node))found.add(target.node)}return found}function scopedElsewhere(node,scopeMethods,env){let root=node.callee;while(root.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression||root.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){root=root.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression?root.object:root.callee}if(root.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,value_follow_1.lookup)(root.name,env.scopeOf(root));if(variable===null||variable.defs[0]?.type!=="Variable")return false;return variable.references.some(reference=>{const use=reference.identifier.parent;if(use?.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&use.object===reference.identifier){return scopeMethods.includes((0,spellings_1.propertyName)(use)??"")}return(use?.type===ast_node_types_1.AST_NODE_TYPES.CallExpression||use?.type===ast_node_types_1.AST_NODE_TYPES.NewExpression)&&use.arguments.some(argument=>argument===reference.identifier)})}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.propertyKeyName=propertyKeyName;exports.hasTruthyKey=hasTruthyKey;exports.hasArgumentScope=hasArgumentScope;exports.chainMethodNames=chainMethodNames;exports.driverBindings=driverBindings;exports.receiverBaseName=receiverBaseName;exports.createUnscopedMutationRule=createUnscopedMutationRule;exports.startsWithTable=startsWithTable;exports.insideAny=insideAny;exports.exportedFunctions=exportedFunctions;exports.scopedElsewhere=scopedElsewhere;const rule_creator_1=require("./rule-creator");const ast_node_types_1=require("../ast-node-types");const spellings_1=require("../ast/spellings");const messaging_1=require("../messaging");const module_evidence_1=require("./module-evidence");const rule_creator_2=require("./rule-creator");const driver_origin_1=require("./driver-origin");const value_follow_1=require("./value-follow");const DEFAULT_SCOPE_KEYS=["where"];const DEFAULT_SCOPE_METHODS=["where"];function propertyKeyName(prop){if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property)return void 0;if(prop.computed)return void 0;if(prop.key.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return prop.key.name;if(prop.key.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"){return prop.key.value}return void 0}function hasTruthyKey(obj,keys){return obj.properties.some(prop=>{if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property)return false;const name=propertyKeyName(prop);if(name===void 0||!keys.includes(name))return false;return!(prop.value.type===ast_node_types_1.AST_NODE_TYPES.Literal&&!prop.value.value)})}function hasArgumentScope(args,scopeKeys){return args.some(arg=>{if(arg.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression){return arg.properties.some(prop=>{if(prop.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)return true;const name=propertyKeyName(prop);if(name===void 0)return true;if(!scopeKeys.includes(name))return false;if(prop.type===ast_node_types_1.AST_NODE_TYPES.Property&&prop.value.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&prop.value.properties.length===0){return false}return true})}return arg.type!==ast_node_types_1.AST_NODE_TYPES.Literal})}function chainMethodNames(node){let root=node;for(;;){const parent=root.parent;if(!parent)break;if(parent.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&parent.object===root){root=parent;continue}if(parent.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&parent.callee===root){root=parent;continue}break}const names=new Set;let cursor=root;for(;;){if(cursor.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){cursor=cursor.callee;continue}if(cursor.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){if(!cursor.computed&&cursor.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier){names.add(cursor.property.name)}cursor=cursor.object;continue}break}return names}function driverBindings(program,modules){const names=new Set;const isDriver=source=>modules.some(m=>source===m||source.startsWith(`${m}/`));for(const stmt of program.body){if(stmt.type===ast_node_types_1.AST_NODE_TYPES.ImportDeclaration){if(typeof stmt.source.value!=="string"||!isDriver(stmt.source.value))continue;for(const spec of stmt.specifiers)names.add(spec.local.name);continue}if(stmt.type!==ast_node_types_1.AST_NODE_TYPES.VariableDeclaration)continue;for(const decl of stmt.declarations){const init=decl.init;if(!init||init.type!==ast_node_types_1.AST_NODE_TYPES.CallExpression||init.callee.type!==ast_node_types_1.AST_NODE_TYPES.Identifier||init.callee.name!=="require"){continue}const arg=init.arguments[0];if(!arg||arg.type!==ast_node_types_1.AST_NODE_TYPES.Literal||typeof arg.value!=="string"||!isDriver(arg.value)){continue}if(decl.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier)names.add(decl.id.name);if(decl.id.type===ast_node_types_1.AST_NODE_TYPES.ObjectPattern){for(const prop of decl.id.properties){if(prop.type===ast_node_types_1.AST_NODE_TYPES.Property&&prop.value.type===ast_node_types_1.AST_NODE_TYPES.Identifier){names.add(prop.value.name)}}}}}return names}function receiverBaseName(node){let cursor=node.object;for(;;){if(cursor.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){if(cursor.object.type===ast_node_types_1.AST_NODE_TYPES.ThisExpression&&!cursor.computed&&cursor.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return cursor.property.name}cursor=cursor.object;continue}if(cursor.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){cursor=cursor.callee;continue}return cursor.type===ast_node_types_1.AST_NODE_TYPES.Identifier?cursor.name:void 0}}function createUnscopedMutationRule(config){const sinks=new Set(config.methods);const scopeKeys=config.scopeKeys??DEFAULT_SCOPE_KEYS;const scopeMethods=config.scopeMethods??DEFAULT_SCOPE_METHODS;const truncateKeys=config.truncateKeys??[];const argumentRole=config.argumentRole??"options";const usesModule=(0,module_evidence_1.createModuleEvidence)({packages:config.modules});const originOf=(0,driver_origin_1.createOriginClassifier)(config.modules);return rule_creator_1.RuleCreator.withoutDocs({meta:{interop:{runtimes:["eslint","oxlint"]},type:config.meta.type,docs:{...config.meta.docs},messages:{unscopedMutation:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Unscoped Bulk Mutation",description:"Bulk mutation with no filter detected. This rewrites or deletes every row in the table.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A01:2021",compliance:["SOC2","NIST-CSF"],effort:"low",fix:config.fix,documentationLink:config.documentationLink}),explicitTruncate:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Unscoped Bulk Mutation",description:"Table truncation detected. This ignores any filter and empties the whole table.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A01:2021",compliance:["SOC2","NIST-CSF"],effort:"low",fix:"Remove the truncate flag and delete by filter, or move the truncation to an explicit maintenance script.",documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],createOnce(context){let env;let ownsFile;let migrations;function hasDistinctiveShape(node){const callee=node.callee;switch(config.distinctiveShape){case"model-accessor":return callee.object.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression;case"table-call":return startsWithTable(callee.object);case"table-argument":{const[table]=node.arguments;return table!==void 0&&table.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement&&originOf((0,value_follow_1.valueAt)(table,env))==="ours"}default:return false}}return{before(){if((0,rule_creator_2.isTestFilePath)(context.filename))return false;env=(0,value_follow_1.envOf)(context);ownsFile=false;migrations=new Set;return true},Program(program){ownsFile=usesModule(program);migrations=exportedFunctions(program,config.migrationExports??[],context)},CallExpression(node){if(node.callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression||node.callee.computed||node.callee.property.type!==ast_node_types_1.AST_NODE_TYPES.Identifier||!sinks.has(node.callee.property.name)){return}const origin=originOf((0,value_follow_1.valueAt)(node.callee.object,env));if(origin==="foreign")return;if(origin==="unknown"&&!(ownsFile&&hasDistinctiveShape(node))){return}if(insideAny(node,migrations))return;if(truncateKeys.length>0){const truncating=node.arguments.some(arg=>arg.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&hasTruthyKey(arg,truncateKeys));if(truncating){context.report({node,messageId:"explicitTruncate"});return}}if(argumentRole==="options"){if(config.requireOptionsObject===true&&!node.arguments.some(arg=>arg.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression)){return}if(hasArgumentScope(node.arguments,scopeKeys))return}const chained=chainMethodNames(node);if(scopeMethods.some(name=>chained.has(name)))return;if(scopedElsewhere(node,scopeMethods,env))return;context.report({node,messageId:"unscopedMutation"})}}}})}const TABLE_STARTERS=new Set(["table","from","into","queryBuilder","withSchema"]);function startsWithTable(receiver){let cursor=receiver;for(;;){if(cursor.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){if(cursor.callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression)return true;if(TABLE_STARTERS.has((0,spellings_1.propertyName)(cursor.callee)??""))return true;cursor=cursor.callee.object;continue}if(cursor.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){cursor=cursor.object;continue}return false}}function insideAny(node,functions){for(let n=node.parent;n;n=n.parent){if(functions.has(n))return true}return false}function exportedFunctions(program,names,context){const found=new Set;const scopeManager=context.sourceCode.scopeManager;if(names.length===0||scopeManager===null)return found;const module={file:context.physicalFilename,ast:program,scopeManager};for(const name of names){const exported=(0,value_follow_1.exportedValue)(module,name,context.languageOptions?.parser);if(exported===null)continue;const target=(0,value_follow_1.follow)(exported);if((0,driver_origin_1.isFunctionNode)(target.node))found.add(target.node)}return found}function scopedElsewhere(node,scopeMethods,env){let root=node.callee;while(root.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression||root.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){root=root.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression?root.object:root.callee}if(root.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,value_follow_1.lookup)(root.name,env.scopeOf(root));if(variable===null||variable.defs[0]?.type!=="Variable")return false;return variable.references.some(reference=>{const use=reference.identifier.parent;if(use?.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&use.object===reference.identifier){return scopeMethods.includes((0,spellings_1.propertyName)(use)??"")}return(use?.type===ast_node_types_1.AST_NODE_TYPES.CallExpression||use?.type===ast_node_types_1.AST_NODE_TYPES.NewExpression)&&use.arguments.some(argument=>argument===reference.identifier)})}
@@ -22,6 +22,25 @@
22
22
  * project-wide.
23
23
  */
24
24
  declare module '@typescript-eslint/utils/ts-eslint' {
25
+ interface RuleMetaData<MessageIds extends string, PluginDocs = unknown, Options extends readonly unknown[] = []> {
26
+ /**
27
+ * Where this rule is known to behave identically (INTEROP_PHILOSOPHY.md).
28
+ * `oxlint` is claimed only when the rule's own test suite passes on
29
+ * oxlint's RuleTester too (vitest.dual-rule-tester.ts runs it there);
30
+ * type-aware rules stay `['eslint']` — oxlint has no parser services.
31
+ * ESLint is the floor and is always listed.
32
+ */
33
+ interop?: {
34
+ runtimes: readonly ['eslint'] | readonly ['eslint', 'oxlint'];
35
+ /**
36
+ * The oxlint built-in that does the same job (`import/no-cycle`),
37
+ * from docs/oxlint-builtin-overlap.json verdicts of `equivalent`. An
38
+ * oxlint user enables that native rule instead of this one: same
39
+ * finding, no double report.
40
+ */
41
+ nativeEquivalent?: string;
42
+ };
43
+ }
25
44
  interface RuleMetaDataDocs {
26
45
  /** CWE identifier (e.g. "CWE-89"). Rendered inline by @interlace/eslint-formatter. */
27
46
  cwe?: string;