@interlace/eslint-devkit 1.13.0 → 1.15.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -549,6 +549,7 @@ See [CHANGELOG.md](./CHANGELOG.md) for a list of changes and version history.
549
549
 
550
550
  <p align="center">
551
551
  <a href="https://eslint.interlace.tools/?utm_source=github&utm_medium=referral&utm_campaign=eslint-devkit"><img src="https://eslint.interlace.tools/images/og-devkit.png" alt="ESLint Interlace" width="100%" /></a>
552
+ <a href="https://scorecard.dev/viewer/?uri=github.com/ofri-peretz/eslint" target="_blank"><img src="https://api.securityscorecards.dev/projects/github.com/ofri-peretz/eslint/badge" alt="OpenSSF Scorecard" /></a>
552
553
  </p>
553
554
 
554
555
  <p align="center">
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@interlace/eslint-devkit",
3
- "version": "1.13.0",
3
+ "version": "1.15.0",
4
4
  "description": "Toolkit for building ESLint plugins in TypeScript — AST helpers, type utilities, rule-creation scaffolding, security benchmarks, and SARIF output.",
5
5
  "type": "commonjs",
6
6
  "main": "./src/index.js",
@@ -4,3 +4,5 @@
4
4
  * MIT license that can be found in the LICENSE file.
5
5
  */
6
6
  export * from '../ast/ast-utils';
7
+ export * from './static-expression';
8
+ export * from './module-binding';
package/src/ast/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?(function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:function(){return m[k]}}}Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]}));var __exportStar=this&&this.__exportStar||function(m,exports2){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("../ast/ast-utils"),exports);
1
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?(function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:function(){return m[k]}}}Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]}));var __exportStar=this&&this.__exportStar||function(m,exports2){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("../ast/ast-utils"),exports);__exportStar(require("./static-expression"),exports);__exportStar(require("./module-binding"),exports);
@@ -0,0 +1,64 @@
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
+ /**
7
+ * Module-binding resolution — "which module did this value actually come from?"
8
+ *
9
+ * Security rules that guard a module's sinks (`child_process.exec`, `fs.readFile`) must
10
+ * follow a binding back to its source module. Matching on identifier or method names
11
+ * instead is the defect behind both of our measured failure classes:
12
+ *
13
+ * - **False negatives.** Every one of these is missed by a name matcher:
14
+ * `require('node:fs')`, `require('fs').readFile`, `const { exec } = require('child_process')`,
15
+ * `require('fs').promises.readFile`, `var { readFile: alias } = fs.promises`.
16
+ * - **False positives across plugins.** A rule keyed on the method name `query` fires on
17
+ * every ORM and on unrelated user code. Receiver identity makes those collisions
18
+ * impossible by construction.
19
+ *
20
+ * Returns the module specifier plus the export path walked from it, so a rule can ask
21
+ * "is this `fs`'s `readFile`?" without caring how the binding was spelled.
22
+ *
23
+ * @example
24
+ * ```ts
25
+ * // const { readFile: rf } = require('node:fs').promises; rf(userPath)
26
+ * resolveModuleBinding(calleeNode, scope);
27
+ * // => { module: 'fs', path: ['promises', 'readFile'] }
28
+ * ```
29
+ */
30
+ import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
31
+ export interface ModuleBinding {
32
+ /** Module specifier, `node:` stripped and equivalents applied (e.g. `fs`). */
33
+ module: string;
34
+ /** Export path walked from the module root (e.g. `['promises', 'readFile']`). */
35
+ path: string[];
36
+ }
37
+ export interface ModuleBindingOptions {
38
+ /**
39
+ * Drop-in replacements to treat as their stdlib counterpart, e.g.
40
+ * `{ 'fs-extra': 'fs', 'graceful-fs': 'fs' }`.
41
+ *
42
+ * A list rather than a hardcoded special case — `eslint-plugin-security` hardcodes
43
+ * `fs-extra`, which leaves every other drop-in undetected.
44
+ */
45
+ equivalents?: Readonly<Record<string, string>>;
46
+ }
47
+ /**
48
+ * Resolve an expression to the module and export path it originates from.
49
+ *
50
+ * @param node - the expression to resolve (an identifier, member expression, or `require(...)` call)
51
+ * @param scope - the scope the expression appears in
52
+ * @returns the binding, or `undefined` when it cannot be proven to come from a module
53
+ */
54
+ export declare function resolveModuleBinding(node: TSESTree.Node, scope: TSESLint.Scope.Scope, options?: ModuleBindingOptions): ModuleBinding | undefined;
55
+ /**
56
+ * Convenience predicate: does this expression resolve to `module`, optionally at `exportPath`?
57
+ *
58
+ * @example
59
+ * ```ts
60
+ * isModuleBinding(callee, scope, 'child_process', ['exec']); // exec from child_process
61
+ * isModuleBinding(callee, scope, 'fs'); // anything from fs
62
+ * ```
63
+ */
64
+ export declare function isModuleBinding(node: TSESTree.Node, scope: TSESLint.Scope.Scope, module: string, exportPath?: readonly string[], options?: ModuleBindingOptions): boolean;
@@ -0,0 +1 @@
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.resolveModuleBinding=resolveModuleBinding;exports.isModuleBinding=isModuleBinding;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.computed)continue;if(property.value.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)continue;if(property.value.name!==boundName)continue;const{key}=property;return key.type===ast_node_types_1.AST_NODE_TYPES.Identifier?key.name:String(key.value)}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&&!node.computed){if(node.property.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return void 0;const property=node.property.name;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)}
@@ -0,0 +1,48 @@
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
+ /**
7
+ * Static-expression analysis — "can an attacker influence this value?"
8
+ *
9
+ * Security rules that flag a non-literal argument (`exec(cmd)`, `readFile(p)`,
10
+ * `require(m)`) produce a false positive whenever the value is provably constant:
11
+ *
12
+ * ```js
13
+ * const CMD = 'ls';
14
+ * child_process.exec(CMD); // not attacker-controlled — must not report
15
+ * ```
16
+ *
17
+ * `eslint-plugin-security` solves this per-rule with its own `isStaticExpression`.
18
+ * This lives in devkit instead, so every rule in the ecosystem inherits it, and it
19
+ * exposes a `treatConstAsStatic` escape hatch for threat models where a `const` is
20
+ * still attacker-influenced (a build-time inlined value, say) — theirs has no such option.
21
+ *
22
+ * Deliberately conservative: anything not proven static is reported as dynamic, so a
23
+ * gap here costs a false positive, never a missed vulnerability.
24
+ */
25
+ import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
26
+ export interface StaticExpressionOptions {
27
+ /**
28
+ * Treat a `const` binding with a static initializer as static.
29
+ *
30
+ * Default `true`. Set `false` for threat models where a module-level constant may
31
+ * itself be attacker-influenced — then only literals and literal-only compositions
32
+ * count as static.
33
+ */
34
+ treatConstAsStatic?: boolean;
35
+ }
36
+ export interface StaticExpressionParams extends StaticExpressionOptions {
37
+ node: TSESTree.Node;
38
+ scope: TSESLint.Scope.Scope;
39
+ }
40
+ /**
41
+ * Determine whether an expression evaluates to a value no attacker can influence.
42
+ *
43
+ * @example
44
+ * ```ts
45
+ * isStaticExpression({ node: argument, scope: context.sourceCode.getScope(node) });
46
+ * ```
47
+ */
48
+ export declare function isStaticExpression({ node, scope, treatConstAsStatic, }: StaticExpressionParams): boolean;
@@ -0,0 +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}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(!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(!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}}
package/src/index.d.ts CHANGED
@@ -21,6 +21,8 @@
21
21
  import './types/meta-augmentation';
22
22
  export * from './rule-creation';
23
23
  export * from './ast/ast-utils';
24
+ export * from './ast/module-binding';
25
+ export * from './ast/static-expression';
24
26
  export * from './types/type-utils';
25
27
  export * from './messaging';
26
28
  export * from './security';
package/src/index.js CHANGED
@@ -1 +1 @@
1
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?(function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:function(){return m[k]}}}Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]}));var __exportStar=this&&this.__exportStar||function(m,exports2){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:true});exports.ESLintUtils=exports.AST_NODE_TYPES=exports.toSARIF=exports.severityToCVSS=exports.getSecurityBenchmarks=exports.MessageIcons=exports.OWASP_2021_TO_2025=exports.OWASP_SERVERLESS_DETAILS=exports.OWASP_2021_DETAILS=exports.OWASP_2025_DETAILS=exports.OWASP_DETAILS=exports.CWE_COMPLIANCE_MAPPING=exports.CWE_MAPPING=exports.CVSS_RANGES=void 0;require("./types/meta-augmentation");__exportStar(require("./rule-creation"),exports);__exportStar(require("./ast/ast-utils"),exports);__exportStar(require("./types/type-utils"),exports);__exportStar(require("./messaging"),exports);__exportStar(require("./security"),exports);__exportStar(require("./node"),exports);__exportStar(require("./resolver"),exports);__exportStar(require("./aria-definitions"),exports);var messaging_1=require("./messaging");Object.defineProperty(exports,"CVSS_RANGES",{enumerable:true,get:function(){return messaging_1.CVSS_RANGES}});Object.defineProperty(exports,"CWE_MAPPING",{enumerable:true,get:function(){return messaging_1.CWE_MAPPING}});Object.defineProperty(exports,"CWE_COMPLIANCE_MAPPING",{enumerable:true,get:function(){return messaging_1.CWE_COMPLIANCE_MAPPING}});Object.defineProperty(exports,"OWASP_DETAILS",{enumerable:true,get:function(){return messaging_1.OWASP_DETAILS}});Object.defineProperty(exports,"OWASP_2025_DETAILS",{enumerable:true,get:function(){return messaging_1.OWASP_2025_DETAILS}});Object.defineProperty(exports,"OWASP_2021_DETAILS",{enumerable:true,get:function(){return messaging_1.OWASP_2021_DETAILS}});Object.defineProperty(exports,"OWASP_SERVERLESS_DETAILS",{enumerable:true,get:function(){return messaging_1.OWASP_SERVERLESS_DETAILS}});Object.defineProperty(exports,"OWASP_2021_TO_2025",{enumerable:true,get:function(){return messaging_1.OWASP_2021_TO_2025}});Object.defineProperty(exports,"MessageIcons",{enumerable:true,get:function(){return messaging_1.MessageIcons}});Object.defineProperty(exports,"getSecurityBenchmarks",{enumerable:true,get:function(){return messaging_1.getSecurityBenchmarks}});Object.defineProperty(exports,"severityToCVSS",{enumerable:true,get:function(){return messaging_1.severityToCVSS}});Object.defineProperty(exports,"toSARIF",{enumerable:true,get:function(){return messaging_1.toSARIF}});var ast_node_types_1=require("./ast-node-types");Object.defineProperty(exports,"AST_NODE_TYPES",{enumerable:true,get:function(){return ast_node_types_1.AST_NODE_TYPES}});var rule_creator_1=require("./rule-creation/rule-creator");Object.defineProperty(exports,"ESLintUtils",{enumerable:true,get:function(){return rule_creator_1.ESLintUtils}});
1
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?(function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:function(){return m[k]}}}Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]}));var __exportStar=this&&this.__exportStar||function(m,exports2){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:true});exports.ESLintUtils=exports.AST_NODE_TYPES=exports.toSARIF=exports.severityToCVSS=exports.getSecurityBenchmarks=exports.MessageIcons=exports.OWASP_2021_TO_2025=exports.OWASP_SERVERLESS_DETAILS=exports.OWASP_2021_DETAILS=exports.OWASP_2025_DETAILS=exports.OWASP_DETAILS=exports.CWE_COMPLIANCE_MAPPING=exports.CWE_MAPPING=exports.CVSS_RANGES=void 0;require("./types/meta-augmentation");__exportStar(require("./rule-creation"),exports);__exportStar(require("./ast/ast-utils"),exports);__exportStar(require("./ast/module-binding"),exports);__exportStar(require("./ast/static-expression"),exports);__exportStar(require("./types/type-utils"),exports);__exportStar(require("./messaging"),exports);__exportStar(require("./security"),exports);__exportStar(require("./node"),exports);__exportStar(require("./resolver"),exports);__exportStar(require("./aria-definitions"),exports);var messaging_1=require("./messaging");Object.defineProperty(exports,"CVSS_RANGES",{enumerable:true,get:function(){return messaging_1.CVSS_RANGES}});Object.defineProperty(exports,"CWE_MAPPING",{enumerable:true,get:function(){return messaging_1.CWE_MAPPING}});Object.defineProperty(exports,"CWE_COMPLIANCE_MAPPING",{enumerable:true,get:function(){return messaging_1.CWE_COMPLIANCE_MAPPING}});Object.defineProperty(exports,"OWASP_DETAILS",{enumerable:true,get:function(){return messaging_1.OWASP_DETAILS}});Object.defineProperty(exports,"OWASP_2025_DETAILS",{enumerable:true,get:function(){return messaging_1.OWASP_2025_DETAILS}});Object.defineProperty(exports,"OWASP_2021_DETAILS",{enumerable:true,get:function(){return messaging_1.OWASP_2021_DETAILS}});Object.defineProperty(exports,"OWASP_SERVERLESS_DETAILS",{enumerable:true,get:function(){return messaging_1.OWASP_SERVERLESS_DETAILS}});Object.defineProperty(exports,"OWASP_2021_TO_2025",{enumerable:true,get:function(){return messaging_1.OWASP_2021_TO_2025}});Object.defineProperty(exports,"MessageIcons",{enumerable:true,get:function(){return messaging_1.MessageIcons}});Object.defineProperty(exports,"getSecurityBenchmarks",{enumerable:true,get:function(){return messaging_1.getSecurityBenchmarks}});Object.defineProperty(exports,"severityToCVSS",{enumerable:true,get:function(){return messaging_1.severityToCVSS}});Object.defineProperty(exports,"toSARIF",{enumerable:true,get:function(){return messaging_1.toSARIF}});var ast_node_types_1=require("./ast-node-types");Object.defineProperty(exports,"AST_NODE_TYPES",{enumerable:true,get:function(){return ast_node_types_1.AST_NODE_TYPES}});var rule_creator_1=require("./rule-creation/rule-creator");Object.defineProperty(exports,"ESLintUtils",{enumerable:true,get:function(){return rule_creator_1.ESLintUtils}});
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BROWSER_ESCAPE_FLAG=void 0;exports.readFlag=readFlag;exports.createBrowserEscapeHatchRule=createBrowserEscapeHatchRule;const rule_creator_1=require("./rule-creator");const messaging_1=require("../messaging");const sdk_api_key_rule_1=require("./sdk-api-key-rule");exports.BROWSER_ESCAPE_FLAG="dangerouslyAllowBrowser";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){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){let importsSdk=false;const candidates=[];function inspect(node,args){const options=args[0];if(options?.type!=="ObjectExpression")return;if(readFlag(options)==="enabled")candidates.push(node)}return{ImportDeclaration(node){if((0,sdk_api_key_rule_1.matchesModule)(String(node.source.value),config.modules))importsSdk=true},NewExpression(node){inspect(node,node.arguments)},CallExpression(node){if(node.callee.type==="Identifier"&&node.callee.name==="require"&&node.arguments[0]?.type==="Literal"&&typeof node.arguments[0].value==="string"&&(0,sdk_api_key_rule_1.matchesModule)(node.arguments[0].value,config.modules)){importsSdk=true;return}inspect(node,node.arguments)},"Program:exit"(){if(!importsSdk)return;for(const node of candidates){context.report({node,messageId:"browserKeyExposure"})}}}}})}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.BROWSER_ESCAPE_FLAG=void 0;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");exports.BROWSER_ESCAPE_FLAG="dangerouslyAllowBrowser";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);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{};function inspect(node,args){const options=args[0];if(options?.type!=="ObjectExpression")return;if(readFlag(options)==="enabled"){context.report({node,messageId:"browserKeyExposure"})}}return{NewExpression(node){inspect(node,node.arguments)},CallExpression(node){inspect(node,node.arguments)}}}})}
@@ -29,6 +29,13 @@ export interface MockContextOptions {
29
29
  * rules that pre-scan the file at `create()` time need this to exist.
30
30
  */
31
31
  ast?: unknown;
32
+ /**
33
+ * Scope returned by the `sourceCode.getScope()` stub. Defaults to an empty
34
+ * scope. Rules that ask the scope manager a question — "does this function
35
+ * bind a credential?" — see nothing without one, so their listeners return
36
+ * early and the synthetic node under test never reaches `context.report`.
37
+ */
38
+ scope?: unknown;
32
39
  }
33
40
  export interface MockContextResult {
34
41
  /** Visitor listeners returned by `rule.create(context)`. */
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createWithMockContext=createWithMockContext;function createWithMockContext(rule,opts={}){const reports=[];const filename=opts.filename??"mock.ts";const emptyScope={variables:[],references:[],childScopes:[]};const sourceCode={ast:opts.ast??{type:"Program",body:[],tokens:[],comments:[]},text:opts.sourceText??"",getText:()=>opts.sourceText??"",getScope:()=>emptyScope,getAncestors:()=>[],getCommentsBefore:()=>[],getDeclaredVariables:()=>[]};const context={id:"mock-rule",filename,physicalFilename:filename,cwd:"/",options:opts.options??rule.defaultOptions??[],settings:opts.settings??{},parserOptions:{},languageOptions:{},sourceCode,getFilename:()=>filename,getPhysicalFilename:()=>filename,getCwd:()=>"/",getSourceCode:()=>sourceCode,getScope:()=>emptyScope,getAncestors:()=>[],report:descriptor=>{reports.push(descriptor)}};const listeners=rule.create(context);return{listeners,reports,context}}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createWithMockContext=createWithMockContext;function createWithMockContext(rule,opts={}){const reports=[];const filename=opts.filename??"mock.ts";const emptyScope={variables:[],references:[],childScopes:[]};const sourceCode={ast:opts.ast??{type:"Program",body:[],tokens:[],comments:[]},text:opts.sourceText??"",getText:()=>opts.sourceText??"",getScope:()=>opts.scope??emptyScope,getAncestors:()=>[],getCommentsBefore:()=>[],getDeclaredVariables:()=>[]};const context={id:"mock-rule",filename,physicalFilename:filename,cwd:"/",options:opts.options??rule.defaultOptions??[],settings:opts.settings??{},parserOptions:{},languageOptions:{},sourceCode,getFilename:()=>filename,getPhysicalFilename:()=>filename,getCwd:()=>"/",getSourceCode:()=>sourceCode,getScope:()=>opts.scope??emptyScope,getAncestors:()=>[],report:descriptor=>{reports.push(descriptor)}};const listeners=rule.create(context);return{listeners,reports,context}}
@@ -66,3 +66,38 @@ export interface ModuleEvidenceConfig {
66
66
  * ```
67
67
  */
68
68
  export declare function createModuleEvidence(config: ModuleEvidenceConfig): (ast: TSESTree.Program) => boolean;
69
+ /**
70
+ * Build a probe from a flat `modules` list of the kind the SDK rule factories
71
+ * already take — `['openai']`, `['@anthropic-ai']`, `['@google/generative-ai',
72
+ * '@google/genai']`.
73
+ *
74
+ * The factories predate {@link createModuleEvidence} and each opened its gate
75
+ * from two visitors: `ImportDeclaration`, and a `CallExpression` whose callee is
76
+ * named `require`. That pair covers ESM and plain CommonJS and nothing else, so
77
+ * `import OpenAI = require('openai')` and `await import('openai')` left every
78
+ * rule in four plugins — anthropic, gemini, mcp-sdk and openai — silently off.
79
+ * It is the same defect that had `jwt-security` abstaining on CommonJS files,
80
+ * one layer up: the gate was not wrong about the *library*, it was wrong about
81
+ * the *spelling*.
82
+ *
83
+ * A bare scope (`'@anthropic-ai'`) becomes a scope match and anything else a
84
+ * package match, which reproduces the old `source === m || source.startsWith(m
85
+ * + '/')` test exactly while inheriting the import-equals, dynamic-import,
86
+ * re-export, Deno-specifier and `require`-shadowing handling that only exists
87
+ * in one place.
88
+ */
89
+ export declare function createModuleListEvidence(modules: readonly string[]): (ast: TSESTree.Program) => boolean;
90
+ /**
91
+ * Does a module specifier name a package, or something inside one?
92
+ *
93
+ * @deprecated Prefer {@link createModuleListEvidence}. This answers only
94
+ * *"which package is this string in?"* and knows nothing about how the module
95
+ * was brought into the file, which is where the four AI plugins went silent on
96
+ * CommonJS.
97
+ *
98
+ * Kept because it was public API: it used to be exported from
99
+ * `sdk-api-key-rule` and re-exported from the package root, so removing it
100
+ * would make devkit a major and strand every plugin on a `^1` range — the
101
+ * opposite of shipping these fixes.
102
+ */
103
+ export declare function matchesModule(source: string, modules: readonly string[]): boolean;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createModuleEvidence=createModuleEvidence;const ast_node_types_1=require("../ast-node-types");function normalizeSpecifier(specifier){if(specifier.startsWith("npm:"))return specifier.slice(4);const deno=/^https?:\/\/deno\.land\/x\/([^@/]+)/.exec(specifier);return deno?deno[1]:specifier}function importEqualsSpecifier(node){if(node.type!==ast_node_types_1.AST_NODE_TYPES.TSImportEqualsDeclaration)return null;const ref=node.moduleReference;if(ref.type!==ast_node_types_1.AST_NODE_TYPES.TSExternalModuleReference)return null;return ref.expression.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof ref.expression.value==="string"?ref.expression.value:null}function bindsRequire(node){if(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){return node.params.some(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&p.name==="require")}if(node.type===ast_node_types_1.AST_NODE_TYPES.Program||node.type===ast_node_types_1.AST_NODE_TYPES.BlockStatement){return node.body.some(stmt=>stmt.type===ast_node_types_1.AST_NODE_TYPES.VariableDeclaration&&stmt.declarations.some(d=>d.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&d.id.name==="require"))}return false}function createModuleEvidence(config){const packages=new Set(config.packages??[]);const scopes=new Set(config.scopes??[]);const prefixes=config.prefixes??[];const extra=config.extraEvidence;const owns=raw=>{const specifier=normalizeSpecifier(raw);if(specifier.startsWith(".")||specifier.startsWith("/"))return false;if(specifier.startsWith("@")){const[scope,name]=specifier.split("/");if(scopes.has(scope))return true;const root2=name===void 0?scope:`${scope}/${name}`;return packages.has(root2)||prefixes.some(p=>root2.startsWith(p))}const root=specifier.split("/")[0];return packages.has(root)||prefixes.some(p=>root.startsWith(p))};const dynamicLoadSpecifier=(node,requireIsShadowed)=>{const argument=node.type===ast_node_types_1.AST_NODE_TYPES.ImportExpression?node.source:!requireIsShadowed&&node.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&node.callee.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"?node.arguments[0]:void 0;return argument?.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof argument.value==="string"?argument.value:null};const cache=new WeakMap;const compute=ast=>{let found=false;const visit=(node,requireIsShadowed)=>{if((node.type===ast_node_types_1.AST_NODE_TYPES.ImportDeclaration||node.type===ast_node_types_1.AST_NODE_TYPES.ExportNamedDeclaration||node.type===ast_node_types_1.AST_NODE_TYPES.ExportAllDeclaration)&&node.source?.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof node.source.value==="string"&&owns(node.source.value)){found=true;return}const importEquals=importEqualsSpecifier(node);if(importEquals!==null&&owns(importEquals)){found=true;return}const dynamic=dynamicLoadSpecifier(node,requireIsShadowed);if(dynamic!==null&&owns(dynamic)){found=true;return}if(extra?.(node)){found=true;return}const shadowedHere=requireIsShadowed||bindsRequire(node);for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];if(Array.isArray(value)){for(const child of value){if(child&&typeof child.type==="string"){visit(child,shadowedHere);if(found)return}}}else if(value&&typeof value==="object"&&typeof value.type==="string"){visit(value,shadowedHere);if(found)return}}};visit(ast,false);return found};return ast=>{const cached=cache.get(ast);if(cached!==void 0)return cached;const result=compute(ast);cache.set(ast,result);return result}}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createModuleEvidence=createModuleEvidence;exports.createModuleListEvidence=createModuleListEvidence;exports.matchesModule=matchesModule;const ast_node_types_1=require("../ast-node-types");function normalizeSpecifier(specifier){if(specifier.startsWith("npm:"))return specifier.slice(4);const deno=/^https?:\/\/deno\.land\/x\/([^@/]+)/.exec(specifier);return deno?deno[1]:specifier}function importEqualsSpecifier(node){if(node.type!==ast_node_types_1.AST_NODE_TYPES.TSImportEqualsDeclaration)return null;const ref=node.moduleReference;if(ref.type!==ast_node_types_1.AST_NODE_TYPES.TSExternalModuleReference)return null;return ref.expression.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof ref.expression.value==="string"?ref.expression.value:null}function bindsRequire(node){if(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){return node.params.some(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&p.name==="require")}if(node.type===ast_node_types_1.AST_NODE_TYPES.Program||node.type===ast_node_types_1.AST_NODE_TYPES.BlockStatement){return node.body.some(stmt=>stmt.type===ast_node_types_1.AST_NODE_TYPES.VariableDeclaration&&stmt.declarations.some(d=>d.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&d.id.name==="require"))}return false}function createModuleEvidence(config){const packages=new Set(config.packages??[]);const scopes=new Set(config.scopes??[]);const prefixes=config.prefixes??[];const extra=config.extraEvidence;const owns=raw=>{const specifier=normalizeSpecifier(raw);if(specifier.startsWith(".")||specifier.startsWith("/"))return false;if(specifier.startsWith("@")){const[scope,name]=specifier.split("/");if(scopes.has(scope))return true;const root2=name===void 0?scope:`${scope}/${name}`;return packages.has(root2)||prefixes.some(p=>root2.startsWith(p))}const root=specifier.split("/")[0];return packages.has(root)||prefixes.some(p=>root.startsWith(p))};const dynamicLoadSpecifier=(node,requireIsShadowed)=>{const argument=node.type===ast_node_types_1.AST_NODE_TYPES.ImportExpression?node.source:!requireIsShadowed&&node.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&node.callee.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"?node.arguments[0]:void 0;return argument?.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof argument.value==="string"?argument.value:null};const cache=new WeakMap;const compute=ast=>{let found=false;const visit=(node,requireIsShadowed)=>{if((node.type===ast_node_types_1.AST_NODE_TYPES.ImportDeclaration||node.type===ast_node_types_1.AST_NODE_TYPES.ExportNamedDeclaration||node.type===ast_node_types_1.AST_NODE_TYPES.ExportAllDeclaration)&&node.source?.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof node.source.value==="string"&&owns(node.source.value)){found=true;return}const importEquals=importEqualsSpecifier(node);if(importEquals!==null&&owns(importEquals)){found=true;return}const dynamic=dynamicLoadSpecifier(node,requireIsShadowed);if(dynamic!==null&&owns(dynamic)){found=true;return}if(extra?.(node)){found=true;return}const shadowedHere=requireIsShadowed||bindsRequire(node);for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];if(Array.isArray(value)){for(const child of value){if(child&&typeof child.type==="string"){visit(child,shadowedHere);if(found)return}}}else if(value&&typeof value==="object"&&typeof value.type==="string"){visit(value,shadowedHere);if(found)return}}};visit(ast,false);return found};return ast=>{const cached=cache.get(ast);if(cached!==void 0)return cached;const result=compute(ast);cache.set(ast,result);return result}}function createModuleListEvidence(modules){const isBareScope=m=>m.startsWith("@")&&!m.includes("/");return createModuleEvidence({packages:modules.filter(m=>!isBareScope(m)),scopes:modules.filter(isBareScope)})}function matchesModule(source,modules){return modules.some(m=>source===m||source.startsWith(`${m}/`))}
@@ -98,3 +98,21 @@ export declare const ESLintUtils: {
98
98
  applyDefault: typeof applyDefault;
99
99
  };
100
100
  export type { TSESLint };
101
+ /**
102
+ * Canonical documentation URL for a rule on eslint.interlace.tools.
103
+ *
104
+ * The docs slug MUST equal the package suffix — `eslint-plugin-node-security`
105
+ * documents at `plugin-node-security`. Verified live: any other shape 404s.
106
+ */
107
+ export declare const docsUrlFor: (pluginSlug: string, ruleName: string) => string;
108
+ /**
109
+ * Stamp the canonical docs URL onto every rule in a plugin's export map.
110
+ *
111
+ * Rules built with the default {@link createRule} inherit a placeholder URL that does not
112
+ * resolve — every "see docs" link in every IDE, CI report and SARIF file 404s. Rather than
113
+ * rewrite the import in ~110 rule files, plugins pass their rule map through this on export.
114
+ *
115
+ * @param pluginSlug - docs slug, equal to the package suffix (e.g. `plugin-node-security`)
116
+ * @param rules - the plugin's rule map, returned with `meta.docs.url` corrected
117
+ */
118
+ export declare function withCanonicalDocsUrls<T extends Record<string, TSESLint.RuleModule<string, readonly unknown[]>>>(pluginSlug: string, rules: T): T;
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.ESLintUtils=exports.createRule=void 0;exports.applyDefault=applyDefault;exports.RuleCreator=RuleCreator;exports.createRuleCreator=createRuleCreator;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}function createRuleInternal({create,defaultOptions,meta,name}){const resolvedDefaultOptions=defaultOptions??[];return{create(context){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(name=>`https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin/docs/rules/${name}.md`);exports.ESLintUtils={RuleCreator,applyDefault};
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.docsUrlFor=exports.ESLintUtils=exports.createRule=void 0;exports.applyDefault=applyDefault;exports.RuleCreator=RuleCreator;exports.createRuleCreator=createRuleCreator;exports.withCanonicalDocsUrls=withCanonicalDocsUrls;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}function createRuleInternal({create,defaultOptions,meta,name}){const resolvedDefaultOptions=defaultOptions??[];return{create(context){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(name=>`https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin/docs/rules/${name}.md`);exports.ESLintUtils={RuleCreator,applyDefault};const docsUrlFor=(pluginSlug,ruleName)=>`https://eslint.interlace.tools/docs/security/${pluginSlug}/rules/${ruleName}`;exports.docsUrlFor=docsUrlFor;function withCanonicalDocsUrls(pluginSlug,rules){for(const[name,rule]of Object.entries(rules)){const docs=rule?.meta?.docs;if(docs)docs.url=(0,exports.docsUrlFor)(pluginSlug,name)}return rules}
@@ -65,13 +65,6 @@ export interface SdkApiKeyRuleConfig {
65
65
  * description renders, without duplicating the literal.
66
66
  */
67
67
  export declare const POSITIONAL_KEY_LABEL = "The first argument";
68
- /**
69
- * Does this import specifier belong to one of the configured modules?
70
- *
71
- * Exact match or a subpath, never a prefix match on the bare name — `openai`
72
- * must not open the gate for `openai-edge`.
73
- */
74
- export declare function matchesModule(source: string, modules: readonly string[]): boolean;
75
68
  /**
76
69
  * `literal` carries the property name that actually held the credential.
77
70
  * A bare verdict left the caller guessing, and it guessed the first configured
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.POSITIONAL_KEY_LABEL=void 0;exports.matchesModule=matchesModule;exports.readCredential=readCredential;exports.calleeName=calleeName;exports.createSdkApiKeyRule=createSdkApiKeyRule;const rule_creator_1=require("./rule-creator");const messaging_1=require("../messaging");exports.POSITIONAL_KEY_LABEL="The first argument";function matchesModule(source,modules){return modules.some(m=>source===m||source.startsWith(`${m}/`))}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 keyProps=new Set(config.keyProps);const positional=new Set(config.positionalKeyConstructors??[]);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){let importsSdk=false;const candidates=[];function inspect(node,args){const first=args[0];if(first===void 0)return;if(first.type==="Literal"){const name=calleeName(node.callee);if(name!==void 0&&positional.has(name)&&typeof first.value==="string"&&first.value.length>0){candidates.push({node,prop:exports.POSITIONAL_KEY_LABEL})}return}if(first.type!=="ObjectExpression")return;const verdict=readCredential(first,keyProps);if(verdict.kind==="literal")candidates.push({node,prop:verdict.prop})}return{ImportDeclaration(node){if(matchesModule(String(node.source.value),config.modules))importsSdk=true},NewExpression(node){inspect(node,node.arguments)},CallExpression(node){if(node.callee.type==="Identifier"&&node.callee.name==="require"&&node.arguments[0]?.type==="Literal"&&typeof node.arguments[0].value==="string"&&matchesModule(node.arguments[0].value,config.modules)){importsSdk=true;return}inspect(node,node.arguments)},"Program:exit"(){if(!importsSdk)return;for(const{node,prop}of candidates){context.report({node,messageId:"hardcodedApiKey",data:{prop}})}}}}})}
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");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 keyProps=new Set(config.keyProps);const positional=new Set(config.positionalKeyConstructors??[]);const usesSdk=(0,module_evidence_1.createModuleListEvidence)(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{};function inspect(node,args){const first=args[0];if(first===void 0)return;if(first.type==="Literal"){const name=calleeName(node.callee);if(name!==void 0&&positional.has(name)&&typeof first.value==="string"&&first.value.length>0){context.report({node,messageId:"hardcodedApiKey",data:{prop:exports.POSITIONAL_KEY_LABEL}})}return}if(first.type!=="ObjectExpression")return;const verdict=readCredential(first,keyProps);if(verdict.kind==="literal"){context.report({node,messageId:"hardcodedApiKey",data:{prop:verdict.prop}})}}return{NewExpression(node){inspect(node,node.arguments)},CallExpression(node){inspect(node,node.arguments)}}}})}
@@ -30,7 +30,8 @@ export interface SqlInjectionRuleConfig {
30
30
  readonly methods: readonly string[];
31
31
  /**
32
32
  * Modules whose API these sinks belong to. **The rule stays silent in a file
33
- * that imports none of them.**
33
+ * that loads none of them** — by `import`, `require`, `await import()` or
34
+ * `import x = require()`.
34
35
  *
35
36
  * Method names are not evidence of an SDK. `['raw']` is knex *and* drizzle;
36
37
  * `['query']` is typeorm *and* pg *and* mysql2; `['get','all','run']` is
@@ -44,7 +45,7 @@ export interface SqlInjectionRuleConfig {
44
45
  * scan, nothing to go stale, and a file that does not import the driver is
45
46
  * one this rule genuinely has nothing to say about.
46
47
  *
47
- * Matched against the import specifier's package root, so `'mysql2/promise'`
48
+ * Matched against the specifier's package root, so `'mysql2/promise'`
48
49
  * matches `'mysql2'` and `'@prisma/client/edge'` matches `'@prisma/client'`.
49
50
  */
50
51
  readonly modules: readonly string[];
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createSqlInjectionRule=createSqlInjectionRule;const ast_node_types_1=require("../ast-node-types");const messaging_1=require("../messaging");const SQL_KEYWORDS=/\b(?:select|insert|update|delete|drop|alter|truncate|union|from|where|values|set)\b/i;const FUNCTION_TYPES=new Set([ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration,ast_node_types_1.AST_NODE_TYPES.FunctionExpression,ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression]);function enclosingFunction(node){for(let n=node.parent;n;n=n.parent){if(FUNCTION_TYPES.has(n.type))return n}return void 0}function callableName(fn){if(fn.type===ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration&&fn.id)return fn.id.name;const parent=fn.parent;if(parent.type===ast_node_types_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return parent.id.name}if((parent.type===ast_node_types_1.AST_NODE_TYPES.MethodDefinition||parent.type===ast_node_types_1.AST_NODE_TYPES.PropertyDefinition||parent.type===ast_node_types_1.AST_NODE_TYPES.Property)&&parent.key.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return parent.key.name}return void 0}function staticText(node){if(node.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join(" ")}if(node.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression){return`${staticText(node.left)} ${staticText(node.right)}`}if(node.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}return""}function classify(node,requireSqlKeywords){let kind=false;if(node.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){kind="concat"}if(node.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral&&node.expressions.length>0){kind="template"}if(kind===false)return false;if(kind==="concat"&&staticText(node).trim()==="")return false;if(requireSqlKeywords&&!SQL_KEYWORDS.test(staticText(node)))return false;return kind}function createSqlInjectionRule(config){const sinks=new Set(config.methods);const owned=new Set(config.modules);const owns=specifier=>{if(specifier.startsWith(".")||specifier.startsWith("/"))return false;const parts=specifier.split("/");const root=specifier.startsWith("@")?parts.slice(0,2).join("/"):parts[0];return owned.has(root)};return{meta:{type:config.meta.type,docs:{...config.meta.docs},messages:{noUnsafeQuery:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"Unsafe SQL query detected. Variable interpolation found.",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:config.fix,documentationLink:config.documentationLink}),unsafeTemplateLiteral:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"Unsafe SQL query construction detected (template literal).",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:config.fix,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){const tainted=new Map;const sqlish=new Set;const wrappers=new Map;const definitions=new Map;const wrapperFns=new Map;const pending=[];let ownsFile=false;const report=(node,kind)=>{if(!ownsFile)return;context.report({node,messageId:kind==="template"?"unsafeTemplateLiteral":"noUnsafeQuery"})};return{Program(program){ownsFile=program.body.some(stmt=>stmt.type===ast_node_types_1.AST_NODE_TYPES.ImportDeclaration&&owns(stmt.source.value))},"FunctionDeclaration, FunctionExpression, ArrowFunctionExpression"(node){const name=callableName(node);if(name!==void 0)definitions.set(name,(definitions.get(name)??0)+1)},VariableDeclarator(node){if(node.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&node.init){const kind=classify(node.init,config.requireSqlKeywords);if(kind)tainted.set(node.id.name,kind);if(SQL_KEYWORDS.test(staticText(node.init)))sqlish.add(node.id.name)}},AssignmentExpression(node){if(node.operator==="+="&&node.left.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const gate=config.requireSqlKeywords&&!sqlish.has(node.left.name);const kind=classify(node.right,gate);if(kind)tainted.set(node.left.name,kind);if(SQL_KEYWORDS.test(staticText(node.right)))sqlish.add(node.left.name)}},CallExpression(node){const isMember=node.callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier;const calleeName=isMember?node.callee.property.name:node.callee.type===ast_node_types_1.AST_NODE_TYPES.Identifier?node.callee.name:void 0;if(calleeName===void 0)return;if(!isMember||!sinks.has(calleeName)){for(const[index,arg]of node.arguments.entries()){if(arg.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;const kind=classify(arg,true);if(kind)pending.push({name:calleeName,index,arg,kind});else if(arg.type===ast_node_types_1.AST_NODE_TYPES.Identifier)pending.push({name:calleeName,index,arg,kind:void 0})}return}const queryArg=node.arguments[0];if(!queryArg)return;if(queryArg.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const fn=enclosingFunction(node);const index=fn?.params.findIndex(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&p.name===queryArg.name)??-1;const name=fn&&index>=0?callableName(fn):void 0;if(name!==void 0&&fn){wrappers.set(name,index);wrapperFns.set(fn,name)}}const direct=classify(queryArg,config.requireSqlKeywords);if(direct){report(queryArg,direct);return}if(queryArg.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const taint=tainted.get(queryArg.name);if(taint)report(queryArg,taint)}},"Program:exit"(){const proven=new Map;for(const name of wrapperFns.values())proven.set(name,(proven.get(name)??0)+1);for(const{name,index,arg,kind}of pending){if(wrappers.get(name)!==index)continue;if(definitions.get(name)!==proven.get(name))continue;if(kind){report(arg,kind);continue}const varName=arg.name;const taint=tainted.get(varName);if(taint&&sqlish.has(varName))report(arg,taint)}}}}}}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createSqlInjectionRule=createSqlInjectionRule;const ast_node_types_1=require("../ast-node-types");const messaging_1=require("../messaging");const module_evidence_1=require("./module-evidence");const SQL_KEYWORDS=/\b(?:select|insert|update|delete|drop|alter|truncate|union|from|where|values|set)\b/i;const FUNCTION_TYPES=new Set([ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration,ast_node_types_1.AST_NODE_TYPES.FunctionExpression,ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression]);function enclosingFunction(node){for(let n=node.parent;n;n=n.parent){if(FUNCTION_TYPES.has(n.type))return n}return void 0}function callableName(fn){if(fn.type===ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration&&fn.id)return fn.id.name;const parent=fn.parent;if(parent.type===ast_node_types_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return parent.id.name}if((parent.type===ast_node_types_1.AST_NODE_TYPES.MethodDefinition||parent.type===ast_node_types_1.AST_NODE_TYPES.PropertyDefinition||parent.type===ast_node_types_1.AST_NODE_TYPES.Property)&&parent.key.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return parent.key.name}return void 0}function staticText(node){if(node.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join(" ")}if(node.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression){return`${staticText(node.left)} ${staticText(node.right)}`}if(node.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}return""}function classify(node,requireSqlKeywords){let kind=false;if(node.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){kind="concat"}if(node.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral&&node.expressions.length>0){kind="template"}if(kind===false)return false;if(kind==="concat"&&staticText(node).trim()==="")return false;if(requireSqlKeywords&&!SQL_KEYWORDS.test(staticText(node)))return false;return kind}function createSqlInjectionRule(config){const sinks=new Set(config.methods);const usesModule=(0,module_evidence_1.createModuleEvidence)({packages:config.modules});return{meta:{type:config.meta.type,docs:{...config.meta.docs},messages:{noUnsafeQuery:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"Unsafe SQL query detected. Variable interpolation found.",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:config.fix,documentationLink:config.documentationLink}),unsafeTemplateLiteral:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"Unsafe SQL query construction detected (template literal).",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:config.fix,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){const tainted=new Map;const sqlish=new Set;const wrappers=new Map;const definitions=new Map;const wrapperFns=new Map;const pending=[];let ownsFile=false;const report=(node,kind)=>{if(!ownsFile)return;context.report({node,messageId:kind==="template"?"unsafeTemplateLiteral":"noUnsafeQuery"})};return{Program(program){ownsFile=usesModule(program)},"FunctionDeclaration, FunctionExpression, ArrowFunctionExpression"(node){const name=callableName(node);if(name!==void 0)definitions.set(name,(definitions.get(name)??0)+1)},VariableDeclarator(node){if(node.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&node.init){const kind=classify(node.init,config.requireSqlKeywords);if(kind)tainted.set(node.id.name,kind);if(SQL_KEYWORDS.test(staticText(node.init)))sqlish.add(node.id.name)}},AssignmentExpression(node){if(node.operator==="+="&&node.left.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const gate=config.requireSqlKeywords&&!sqlish.has(node.left.name);const kind=classify(node.right,gate);if(kind)tainted.set(node.left.name,kind);if(SQL_KEYWORDS.test(staticText(node.right)))sqlish.add(node.left.name)}},CallExpression(node){const isMember=node.callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier;const calleeName=isMember?node.callee.property.name:node.callee.type===ast_node_types_1.AST_NODE_TYPES.Identifier?node.callee.name:void 0;if(calleeName===void 0)return;if(!isMember||!sinks.has(calleeName)){for(const[index,arg]of node.arguments.entries()){if(arg.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;const kind=classify(arg,true);if(kind)pending.push({name:calleeName,index,arg,kind});else if(arg.type===ast_node_types_1.AST_NODE_TYPES.Identifier)pending.push({name:calleeName,index,arg,kind:void 0})}return}const queryArg=node.arguments[0];if(!queryArg)return;if(queryArg.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const fn=enclosingFunction(node);const index=fn?.params.findIndex(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&p.name===queryArg.name)??-1;const name=fn&&index>=0?callableName(fn):void 0;if(name!==void 0&&fn){wrappers.set(name,index);wrapperFns.set(fn,name)}}const direct=classify(queryArg,config.requireSqlKeywords);if(direct){report(queryArg,direct);return}if(queryArg.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const taint=tainted.get(queryArg.name);if(taint)report(queryArg,taint)}},"Program:exit"(){const proven=new Map;for(const name of wrapperFns.values())proven.set(name,(proven.get(name)??0)+1);for(const{name,index,arg,kind}of pending){if(wrappers.get(name)!==index)continue;if(definitions.get(name)!==proven.get(name))continue;if(kind){report(arg,kind);continue}const varName=arg.name;const taint=tainted.get(varName);if(taint&&sqlish.has(varName))report(arg,taint)}}}}}}
@@ -1 +1 @@
1
- "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isStaticInstruction=isStaticInstruction;exports.staticKey=staticKey;exports.isSystemMessage=isSystemMessage;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 sdk_api_key_rule_1=require("./sdk-api-key-rule");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=prop.value;return value.type===ast_node_types_1.AST_NODE_TYPES.Literal&&value.value==="system"})}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){if(node.computed||node.property.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return void 0;parts.unshift(node.property.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;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){let importsSdk=false;const candidates=[];function inspectRequest(options){for(const prop of options.properties){const key=staticKey(prop);if(key===void 0)continue;const value=prop.value;if(promptProps.has(key)){collect(value);continue}if(key==="messages"&&value.type===ast_node_types_1.AST_NODE_TYPES.ArrayExpression){for(const element of value.elements){if(element===null||!isSystemMessage(element))continue;const content=messageContent(element);if(content!==void 0)collect(content)}}}}function collect(value){if(value.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression){for(const prop of value.properties){const key=staticKey(prop);if(key==="text")collect(prop.value);if(key==="parts"){const parts=prop.value;if(parts.type!==ast_node_types_1.AST_NODE_TYPES.ArrayExpression)continue;for(const part of parts.elements){if(part!==null)collect(part)}}}return}if(!isStaticInstruction(value))candidates.push(value)}return{ImportDeclaration(node){if((0,sdk_api_key_rule_1.matchesModule)(String(node.source.value),config.modules))importsSdk=true},CallExpression(node){if(node.callee.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&node.callee.name==="require"&&node.arguments[0]?.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof node.arguments[0].value==="string"&&(0,sdk_api_key_rule_1.matchesModule)(node.arguments[0].value,config.modules)){importsSdk=true;return}const path=calleePath(node.callee);if(path===void 0)return;if(!paths.some(p=>path===p||path.endsWith(`.${p}`)))return;const request=node.arguments[0];if(request?.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression)inspectRequest(request)},"Program:exit"(){if(!importsSdk)return;for(const node of candidates){context.report({node,messageId:"untrustedSystemPrompt"})}}}}})}
1
+ "use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isStaticInstruction=isStaticInstruction;exports.staticKey=staticKey;exports.isSystemMessage=isSystemMessage;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");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=prop.value;return value.type===ast_node_types_1.AST_NODE_TYPES.Literal&&value.value==="system"})}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){if(node.computed||node.property.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return void 0;parts.unshift(node.property.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);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{};function inspectRequest(options){for(const prop of options.properties){const key=staticKey(prop);if(key===void 0)continue;const value=prop.value;if(promptProps.has(key)){collect(value);continue}if(key==="messages"&&value.type===ast_node_types_1.AST_NODE_TYPES.ArrayExpression){for(const element of value.elements){if(element===null||!isSystemMessage(element))continue;const content=messageContent(element);if(content!==void 0)collect(content)}}}}function collect(value){if(value.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression){for(const prop of value.properties){const key=staticKey(prop);if(key==="text")collect(prop.value);if(key==="parts"){const parts=prop.value;if(parts.type!==ast_node_types_1.AST_NODE_TYPES.ArrayExpression)continue;for(const part of parts.elements){if(part!==null)collect(part)}}}return}if(!isStaticInstruction(value)){context.report({node:value,messageId:"untrustedSystemPrompt"})}}return{CallExpression(node){const path=calleePath(node.callee);if(path===void 0)return;if(!paths.some(p=>path===p||path.endsWith(`.${p}`)))return;const request=node.arguments[0];if(request?.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression)inspectRequest(request)}}}})}