@interlace/eslint-devkit 1.12.0 → 1.14.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.12.0",
3
+ "version": "1.14.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",
@@ -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)}}}})}
@@ -15,3 +15,4 @@ export * from './browser-escape-hatch-rule';
15
15
  export * from './system-prompt-injection-rule';
16
16
  export * from './message-source';
17
17
  export * from './raw-identifier-rule';
18
+ export * from './module-evidence';
@@ -1 +1 @@
1
- "use strict";var __createBinding=this&&this.__createBinding||(Object.create?(function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:function(){return m[k]}}}Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]}));var __exportStar=this&&this.__exportStar||function(m,exports2){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./rule-creator"),exports);__exportStar(require("./mock-context"),exports);__exportStar(require("./sql-injection-rule"),exports);__exportStar(require("./unscoped-mutation-rule"),exports);__exportStar(require("./require-tls-rule"),exports);__exportStar(require("./mass-assignment-rule"),exports);__exportStar(require("./hardcoded-credentials-rule"),exports);__exportStar(require("./sdk-api-key-rule"),exports);__exportStar(require("./browser-escape-hatch-rule"),exports);__exportStar(require("./system-prompt-injection-rule"),exports);__exportStar(require("./message-source"),exports);__exportStar(require("./raw-identifier-rule"),exports);
1
+ "use strict";var __createBinding=this&&this.__createBinding||(Object.create?(function(o,m,k,k2){if(k2===void 0)k2=k;var desc=Object.getOwnPropertyDescriptor(m,k);if(!desc||("get"in desc?!m.__esModule:desc.writable||desc.configurable)){desc={enumerable:true,get:function(){return m[k]}}}Object.defineProperty(o,k2,desc)}):(function(o,m,k,k2){if(k2===void 0)k2=k;o[k2]=m[k]}));var __exportStar=this&&this.__exportStar||function(m,exports2){for(var p in m)if(p!=="default"&&!Object.prototype.hasOwnProperty.call(exports2,p))__createBinding(exports2,m,p)};Object.defineProperty(exports,"__esModule",{value:true});__exportStar(require("./rule-creator"),exports);__exportStar(require("./mock-context"),exports);__exportStar(require("./sql-injection-rule"),exports);__exportStar(require("./unscoped-mutation-rule"),exports);__exportStar(require("./require-tls-rule"),exports);__exportStar(require("./mass-assignment-rule"),exports);__exportStar(require("./hardcoded-credentials-rule"),exports);__exportStar(require("./sdk-api-key-rule"),exports);__exportStar(require("./browser-escape-hatch-rule"),exports);__exportStar(require("./system-prompt-injection-rule"),exports);__exportStar(require("./message-source"),exports);__exportStar(require("./raw-identifier-rule"),exports);__exportStar(require("./module-evidence"),exports);
@@ -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}}
@@ -0,0 +1,103 @@
1
+ /**
2
+ * Copyright (c) 2025 Ofri Peretz
3
+ * Licensed under the MIT License. Use of this source code is governed by the
4
+ * MIT license that can be found in the LICENSE file.
5
+ */
6
+ import type { TSESTree } from '@typescript-eslint/utils';
7
+ /**
8
+ * Extra evidence a plugin accepts beyond an import.
9
+ *
10
+ * Most SDKs need none: if the file does not import the package, it does not use
11
+ * the SDK. Two do, and both were established by measuring rather than guessing:
12
+ *
13
+ * - **Lambda** — 184 of 413 handler files (45%) import nothing AWS, because
14
+ * `aws-lambda` is a types package and a plain JS handler imports nothing.
15
+ * - **Express** — 68 of 114 files with a `(req, res)`-shaped function (60%)
16
+ * import no `express`, because route modules receive `app` from a caller.
17
+ *
18
+ * Anything supplied here is an *additional* way to open the gate, so a loose
19
+ * predicate re-introduces the false positives the gate exists to remove. It
20
+ * must identify the SDK's own contract — a handler export, a middleware
21
+ * signature — never a name that merely sounds related.
22
+ */
23
+ export type ExtraEvidence = (node: TSESTree.Node) => boolean;
24
+ export interface ModuleEvidenceConfig {
25
+ /** Exact package roots, e.g. `['pg', 'postgres']`. */
26
+ readonly packages?: readonly string[];
27
+ /** Whole scopes, e.g. `['@ai-sdk']` — every package under them counts. */
28
+ readonly scopes?: readonly string[];
29
+ /** Package-root prefixes, e.g. `['serverless-']`. */
30
+ readonly prefixes?: readonly string[];
31
+ /** Non-import shapes that also mean "this file uses the SDK". */
32
+ readonly extraEvidence?: ExtraEvidence;
33
+ }
34
+ /**
35
+ * Build a per-file "does this file use my SDK?" probe.
36
+ *
37
+ * Every SDK-specific plugin gates every rule on one of these. Measured over
38
+ * 107,382 files across 107 repositories, **40% of all SDK-plugin findings were
39
+ * about an SDK the file never imports** — `lambda-security` reported on any
40
+ * `try/catch`, `postgresql-security` on any `.connect()`, and the seven SQL
41
+ * plugins on each other. A rule that matches a method name is detecting a word,
42
+ * not an interface.
43
+ *
44
+ * This lives in the devkit because it previously did not: five plugins each
45
+ * carried their own copy, so the two false-negative classes the audit found —
46
+ * TypeScript's `import =` and Deno's specifiers — had to be fixed five times,
47
+ * and the next such class would have been fixed ten. One implementation, one
48
+ * fix.
49
+ *
50
+ * The returned probe caches per `Program`, because `create` runs once per rule:
51
+ * an uncached probe walks the whole AST once for every rule in the plugin, and
52
+ * the files paying that cost are mostly the ones the gate exists to skip.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * export const fileUsesPostgres = createModuleEvidence({
57
+ * packages: ['pg', 'postgres', 'slonik'],
58
+ * scopes: ['@neondatabase'],
59
+ * });
60
+ *
61
+ * // in a rule:
62
+ * create(context) {
63
+ * if (!fileUsesPostgres(context.sourceCode.ast)) return {};
64
+ * …
65
+ * }
66
+ * ```
67
+ */
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;
@@ -0,0 +1 @@
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}/`))}
@@ -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)}}}})}