@interlace/eslint-devkit 1.8.0 → 1.10.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/package.json +1 -1
- package/src/aria-definitions.js +1 -990
- package/src/ast/ast-utils.js +1 -133
- package/src/ast/index.js +1 -17
- package/src/ast-node-types.js +1 -174
- package/src/index.js +1 -43
- package/src/messaging/config.js +1 -98
- package/src/messaging/constants.js +1 -678
- package/src/messaging/formatters-ai.js +2 -176
- package/src/messaging/formatters-v2.js +10 -212
- package/src/messaging/formatters.js +3 -186
- package/src/messaging/index.js +1 -21
- package/src/messaging/types-v2.js +1 -2
- package/src/messaging/types.js +1 -2
- package/src/node/fs.js +1 -104
- package/src/node/index.js +1 -19
- package/src/node/os.js +1 -52
- package/src/node/path.js +1 -143
- package/src/resolver/dependency-analysis.js +1 -740
- package/src/resolver/index.js +1 -20
- package/src/resolver/resolver-adapter.js +1 -92
- package/src/resolver/resolver-detection.js +1 -189
- package/src/resolver/resolver.js +1 -206
- package/src/resolver.js +1 -17
- package/src/rule-creation/browser-escape-hatch-rule.d.ts +72 -0
- package/src/rule-creation/browser-escape-hatch-rule.js +1 -0
- package/src/rule-creation/hardcoded-credentials-rule.d.ts +81 -0
- package/src/rule-creation/hardcoded-credentials-rule.js +1 -0
- package/src/rule-creation/index.d.ts +6 -0
- package/src/rule-creation/index.js +1 -21
- package/src/rule-creation/mass-assignment-rule.d.ts +79 -0
- package/src/rule-creation/mass-assignment-rule.js +1 -0
- package/src/rule-creation/mock-context.js +1 -39
- package/src/rule-creation/raw-identifier-rule.d.ts +127 -0
- package/src/rule-creation/raw-identifier-rule.js +1 -0
- package/src/rule-creation/require-tls-rule.d.ts +1 -1
- package/src/rule-creation/require-tls-rule.js +1 -190
- package/src/rule-creation/rule-creator.js +1 -70
- package/src/rule-creation/sdk-api-key-rule.d.ts +108 -0
- package/src/rule-creation/sdk-api-key-rule.js +1 -0
- package/src/rule-creation/sql-injection-rule.js +1 -207
- package/src/rule-creation/system-prompt-injection-rule.d.ts +78 -0
- package/src/rule-creation/system-prompt-injection-rule.js +1 -0
- package/src/rule-creation/unscoped-mutation-rule.js +1 -234
- package/src/security/index.js +1 -17
- package/src/security/security-utils.js +1 -461
- package/src/types/index.js +1 -18
- package/src/types/meta-augmentation.js +1 -2
- package/src/types/type-utils.js +1 -222
|
@@ -1,70 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.ESLintUtils = exports.createRule = void 0;
|
|
4
|
-
exports.applyDefault = applyDefault;
|
|
5
|
-
exports.RuleCreator = RuleCreator;
|
|
6
|
-
exports.createRuleCreator = createRuleCreator;
|
|
7
|
-
function isObjectNotArray(obj) {
|
|
8
|
-
return typeof obj === 'object' && obj != null && !Array.isArray(obj);
|
|
9
|
-
}
|
|
10
|
-
function deepMerge(first, second) {
|
|
11
|
-
const keys = new Set([...Object.keys(first), ...Object.keys(second)]);
|
|
12
|
-
return Object.fromEntries([...keys].map((key) => {
|
|
13
|
-
const firstHasKey = key in first;
|
|
14
|
-
const secondHasKey = key in second;
|
|
15
|
-
const firstValue = first[key];
|
|
16
|
-
const secondValue = second[key];
|
|
17
|
-
if (firstHasKey && secondHasKey) {
|
|
18
|
-
return [
|
|
19
|
-
key,
|
|
20
|
-
isObjectNotArray(firstValue) && isObjectNotArray(secondValue)
|
|
21
|
-
? deepMerge(firstValue, secondValue)
|
|
22
|
-
: secondValue,
|
|
23
|
-
];
|
|
24
|
-
}
|
|
25
|
-
return [key, firstHasKey ? firstValue : secondValue];
|
|
26
|
-
}));
|
|
27
|
-
}
|
|
28
|
-
function applyDefault(defaultOptions, userOptions) {
|
|
29
|
-
const options = structuredClone(defaultOptions);
|
|
30
|
-
if (userOptions == null) {
|
|
31
|
-
return options;
|
|
32
|
-
}
|
|
33
|
-
options.forEach((opt, i) => {
|
|
34
|
-
if (userOptions[i] !== undefined) {
|
|
35
|
-
const userOpt = userOptions[i];
|
|
36
|
-
options[i] =
|
|
37
|
-
isObjectNotArray(userOpt) && isObjectNotArray(opt)
|
|
38
|
-
? deepMerge(opt, userOpt)
|
|
39
|
-
: userOpt;
|
|
40
|
-
}
|
|
41
|
-
});
|
|
42
|
-
return options;
|
|
43
|
-
}
|
|
44
|
-
function createRuleInternal({ create, defaultOptions, meta, name, }) {
|
|
45
|
-
const resolvedDefaultOptions = (defaultOptions ?? []);
|
|
46
|
-
return {
|
|
47
|
-
create(context) {
|
|
48
|
-
return create(context, applyDefault(resolvedDefaultOptions, context.options));
|
|
49
|
-
},
|
|
50
|
-
defaultOptions: resolvedDefaultOptions,
|
|
51
|
-
meta,
|
|
52
|
-
name: name,
|
|
53
|
-
};
|
|
54
|
-
}
|
|
55
|
-
function RuleCreator(urlCreator) {
|
|
56
|
-
return ({ meta, name, ...rule }) => createRuleInternal({
|
|
57
|
-
meta: {
|
|
58
|
-
...meta,
|
|
59
|
-
docs: { ...meta.docs, url: urlCreator(name) },
|
|
60
|
-
},
|
|
61
|
-
name,
|
|
62
|
-
...rule,
|
|
63
|
-
});
|
|
64
|
-
}
|
|
65
|
-
RuleCreator.withoutDocs = (args) => createRuleInternal(args);
|
|
66
|
-
function createRuleCreator(urlCreator) {
|
|
67
|
-
return RuleCreator(urlCreator);
|
|
68
|
-
}
|
|
69
|
-
exports.createRule = RuleCreator((name) => `https://github.com/ofri-peretz/eslint/blob/main/packages/eslint-plugin/docs/rules/${name}.md`);
|
|
70
|
-
exports.ESLintUtils = { RuleCreator, applyDefault };
|
|
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};
|
|
@@ -0,0 +1,108 @@
|
|
|
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
|
+
* @fileoverview Shared CWE-798 detector — a literal API key in an inference
|
|
8
|
+
* SDK's client construction.
|
|
9
|
+
*
|
|
10
|
+
* ## Why this is not `secure-coding/no-hardcoded-credentials`
|
|
11
|
+
*
|
|
12
|
+
* Measured, not assumed: every rule in `eslint-plugin-secure-coding` reports
|
|
13
|
+
* *nothing* on `new OpenAI({ apiKey: 'sk-proj-…' })`,
|
|
14
|
+
* `new GoogleGenerativeAI('AIza…')` or the Anthropic equivalent. The generic
|
|
15
|
+
* credential rules look for password-shaped names and connection strings; an
|
|
16
|
+
* SDK's client options are a different shape and no rule in the ecosystem
|
|
17
|
+
* covers them.
|
|
18
|
+
*
|
|
19
|
+
* The gate here compares against an exact SDK module specifier, which by the
|
|
20
|
+
* taxonomy contract puts it in that SDK's plugin — not in `secure-coding`.
|
|
21
|
+
* The logic is shared because the three SDKs differ only in the module name,
|
|
22
|
+
* the option names, and the remediation copy.
|
|
23
|
+
*/
|
|
24
|
+
import type { TSESTree } from '@typescript-eslint/utils';
|
|
25
|
+
export interface SdkApiKeyRuleConfig {
|
|
26
|
+
/** Rule id, e.g. `no-hardcoded-api-key`. */
|
|
27
|
+
ruleName: string;
|
|
28
|
+
/** Vendor name for the message, e.g. `OpenAI`. */
|
|
29
|
+
vendor: string;
|
|
30
|
+
/**
|
|
31
|
+
* Module names that open the gate. Matched as the exact specifier or a
|
|
32
|
+
* subpath of it (`openai` matches `openai` and `openai/resources`, but not
|
|
33
|
+
* `openai-edge`, which is a different package with a different client).
|
|
34
|
+
* A bare scope (`@anthropic-ai`) matches every package under it.
|
|
35
|
+
*/
|
|
36
|
+
modules: readonly string[];
|
|
37
|
+
/** Client-option names that hold the credential, e.g. `apiKey`. */
|
|
38
|
+
keyProps: readonly string[];
|
|
39
|
+
/**
|
|
40
|
+
* The corrected construction shown in the fix.
|
|
41
|
+
*
|
|
42
|
+
* A template, not a computed string: `{{prop}}` here is resolved by ESLint
|
|
43
|
+
* from the same report data as the description, so a consumer's RuleTester
|
|
44
|
+
* cases only ever declare `prop`. Passing a pre-computed string instead
|
|
45
|
+
* leaves an unhydrated placeholder in every expected message.
|
|
46
|
+
*
|
|
47
|
+
* SDKs whose key can be positional should keep this static — `{{prop}}`
|
|
48
|
+
* reads as "The first argument" there and would render nonsense inside an
|
|
49
|
+
* options literal.
|
|
50
|
+
*/
|
|
51
|
+
fixTemplate: string;
|
|
52
|
+
/** Rule documentation URL. */
|
|
53
|
+
docsUrl: string;
|
|
54
|
+
/** Vendor documentation link carried in the message. */
|
|
55
|
+
documentationLink: string;
|
|
56
|
+
/**
|
|
57
|
+
* Constructors whose *first positional argument* is the key itself, e.g.
|
|
58
|
+
* `new GoogleGenerativeAI('AIza…')`. Empty for SDKs that only take options.
|
|
59
|
+
*/
|
|
60
|
+
positionalKeyConstructors?: readonly string[];
|
|
61
|
+
}
|
|
62
|
+
/**
|
|
63
|
+
* What `{{prop}}` reads as when the credential is a positional argument rather
|
|
64
|
+
* than a named option. Exported so a test can pin the string the
|
|
65
|
+
* description renders, without duplicating the literal.
|
|
66
|
+
*/
|
|
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
|
+
/**
|
|
76
|
+
* `literal` carries the property name that actually held the credential.
|
|
77
|
+
* A bare verdict left the caller guessing, and it guessed the first configured
|
|
78
|
+
* prop — naming the wrong option whenever a later one was the offender.
|
|
79
|
+
*/
|
|
80
|
+
export type KeyVerdict = {
|
|
81
|
+
kind: 'literal';
|
|
82
|
+
prop: string;
|
|
83
|
+
} | {
|
|
84
|
+
kind: 'safe';
|
|
85
|
+
} | {
|
|
86
|
+
kind: 'unreadable';
|
|
87
|
+
};
|
|
88
|
+
/**
|
|
89
|
+
* Whether the client options literal carries an inline credential.
|
|
90
|
+
*
|
|
91
|
+
* `process.env.OPENAI_API_KEY` and any other non-literal expression are `safe`
|
|
92
|
+
* — reading a key from the environment is the correct pattern. A spread is
|
|
93
|
+
* `unreadable`: the key may be in the spread source, and guessing there would
|
|
94
|
+
* flag correct code.
|
|
95
|
+
*
|
|
96
|
+
* A safe credential prop `continue`s rather than returning, because a config
|
|
97
|
+
* can carry more than one: Anthropic's `{ apiKey, authToken }` meant an
|
|
98
|
+
* environment-read `apiKey` returned early and a hardcoded `authToken` right
|
|
99
|
+
* after it was never inspected. `safe` is only the verdict once every property
|
|
100
|
+
* has been looked at.
|
|
101
|
+
*/
|
|
102
|
+
export declare function readCredential(options: TSESTree.ObjectExpression, keyProps: ReadonlySet<string>): KeyVerdict;
|
|
103
|
+
/**
|
|
104
|
+
* The callee name of a `new X(...)` / `X(...)`, if it is statically known.
|
|
105
|
+
* `new pkg.Client()` counts as `Client` — the namespace is not the identity.
|
|
106
|
+
*/
|
|
107
|
+
export declare function calleeName(node: TSESTree.Node): string | undefined;
|
|
108
|
+
export declare function createSdkApiKeyRule(config: SdkApiKeyRuleConfig): import("./rule-creator").RuleModuleWithName<"hardcodedApiKey", [], unknown>;
|
|
@@ -0,0 +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,207 +1 @@
|
|
|
1
|
-
"use strict";
|
|
2
|
-
Object.defineProperty(exports, "__esModule", { value: true });
|
|
3
|
-
exports.createSqlInjectionRule = createSqlInjectionRule;
|
|
4
|
-
const ast_node_types_1 = require("../ast-node-types");
|
|
5
|
-
const messaging_1 = require("../messaging");
|
|
6
|
-
const SQL_KEYWORDS = /\b(?:select|insert|update|delete|drop|alter|truncate|union|from|where|values|set)\b/i;
|
|
7
|
-
const FUNCTION_TYPES = new Set([
|
|
8
|
-
ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration,
|
|
9
|
-
ast_node_types_1.AST_NODE_TYPES.FunctionExpression,
|
|
10
|
-
ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression,
|
|
11
|
-
]);
|
|
12
|
-
function enclosingFunction(node) {
|
|
13
|
-
for (let n = node.parent; n; n = n.parent) {
|
|
14
|
-
if (FUNCTION_TYPES.has(n.type))
|
|
15
|
-
return n;
|
|
16
|
-
}
|
|
17
|
-
return undefined;
|
|
18
|
-
}
|
|
19
|
-
function callableName(fn) {
|
|
20
|
-
if (fn.type === ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration && fn.id)
|
|
21
|
-
return fn.id.name;
|
|
22
|
-
const parent = fn.parent;
|
|
23
|
-
if (parent.type === ast_node_types_1.AST_NODE_TYPES.VariableDeclarator &&
|
|
24
|
-
parent.id.type === ast_node_types_1.AST_NODE_TYPES.Identifier) {
|
|
25
|
-
return parent.id.name;
|
|
26
|
-
}
|
|
27
|
-
if ((parent.type === ast_node_types_1.AST_NODE_TYPES.MethodDefinition ||
|
|
28
|
-
parent.type === ast_node_types_1.AST_NODE_TYPES.PropertyDefinition ||
|
|
29
|
-
parent.type === ast_node_types_1.AST_NODE_TYPES.Property) &&
|
|
30
|
-
parent.key.type === ast_node_types_1.AST_NODE_TYPES.Identifier) {
|
|
31
|
-
return parent.key.name;
|
|
32
|
-
}
|
|
33
|
-
return undefined;
|
|
34
|
-
}
|
|
35
|
-
function staticText(node) {
|
|
36
|
-
if (node.type === ast_node_types_1.AST_NODE_TYPES.TemplateLiteral) {
|
|
37
|
-
return node.quasis.map((q) => q.value.raw).join(' ');
|
|
38
|
-
}
|
|
39
|
-
if (node.type === ast_node_types_1.AST_NODE_TYPES.BinaryExpression) {
|
|
40
|
-
return `${staticText(node.left)} ${staticText(node.right)}`;
|
|
41
|
-
}
|
|
42
|
-
if (node.type === ast_node_types_1.AST_NODE_TYPES.Literal && typeof node.value === 'string') {
|
|
43
|
-
return node.value;
|
|
44
|
-
}
|
|
45
|
-
return '';
|
|
46
|
-
}
|
|
47
|
-
function classify(node, requireSqlKeywords) {
|
|
48
|
-
let kind = false;
|
|
49
|
-
if (node.type === ast_node_types_1.AST_NODE_TYPES.BinaryExpression && node.operator === '+') {
|
|
50
|
-
kind = 'concat';
|
|
51
|
-
}
|
|
52
|
-
if (node.type === ast_node_types_1.AST_NODE_TYPES.TemplateLiteral &&
|
|
53
|
-
node.expressions.length > 0) {
|
|
54
|
-
kind = 'template';
|
|
55
|
-
}
|
|
56
|
-
if (kind === false)
|
|
57
|
-
return false;
|
|
58
|
-
if (kind === 'concat' && staticText(node).trim() === '')
|
|
59
|
-
return false;
|
|
60
|
-
if (requireSqlKeywords && !SQL_KEYWORDS.test(staticText(node)))
|
|
61
|
-
return false;
|
|
62
|
-
return kind;
|
|
63
|
-
}
|
|
64
|
-
function createSqlInjectionRule(config) {
|
|
65
|
-
const sinks = new Set(config.methods);
|
|
66
|
-
return {
|
|
67
|
-
meta: {
|
|
68
|
-
type: config.meta.type,
|
|
69
|
-
docs: { ...config.meta.docs },
|
|
70
|
-
messages: {
|
|
71
|
-
noUnsafeQuery: (0, messaging_1.formatLLMMessage)({
|
|
72
|
-
icon: messaging_1.MessageIcons.SECURITY,
|
|
73
|
-
issueName: 'SQL Injection Risk',
|
|
74
|
-
description: 'Unsafe SQL query detected. Variable interpolation found.',
|
|
75
|
-
severity: 'CRITICAL',
|
|
76
|
-
cwe: config.meta.docs.cwe,
|
|
77
|
-
owasp: 'A03:2021',
|
|
78
|
-
compliance: ['SOC2', 'PCI-DSS', 'NIST-CSF'],
|
|
79
|
-
effort: 'high',
|
|
80
|
-
fix: config.fix,
|
|
81
|
-
documentationLink: config.documentationLink,
|
|
82
|
-
}),
|
|
83
|
-
unsafeTemplateLiteral: (0, messaging_1.formatLLMMessage)({
|
|
84
|
-
icon: messaging_1.MessageIcons.SECURITY,
|
|
85
|
-
issueName: 'SQL Injection Risk',
|
|
86
|
-
description: 'Unsafe SQL query construction detected (template literal).',
|
|
87
|
-
severity: 'CRITICAL',
|
|
88
|
-
cwe: config.meta.docs.cwe,
|
|
89
|
-
owasp: 'A03:2021',
|
|
90
|
-
compliance: ['SOC2', 'PCI-DSS', 'NIST-CSF'],
|
|
91
|
-
effort: 'high',
|
|
92
|
-
fix: config.fix,
|
|
93
|
-
documentationLink: config.documentationLink,
|
|
94
|
-
}),
|
|
95
|
-
},
|
|
96
|
-
schema: [],
|
|
97
|
-
},
|
|
98
|
-
defaultOptions: [],
|
|
99
|
-
create(context) {
|
|
100
|
-
const tainted = new Map();
|
|
101
|
-
const sqlish = new Set();
|
|
102
|
-
const wrappers = new Map();
|
|
103
|
-
const definitions = new Map();
|
|
104
|
-
const wrapperFns = new Map();
|
|
105
|
-
const pending = [];
|
|
106
|
-
const report = (node, kind) => {
|
|
107
|
-
context.report({
|
|
108
|
-
node,
|
|
109
|
-
messageId: kind === 'template' ? 'unsafeTemplateLiteral' : 'noUnsafeQuery',
|
|
110
|
-
});
|
|
111
|
-
};
|
|
112
|
-
return {
|
|
113
|
-
'FunctionDeclaration, FunctionExpression, ArrowFunctionExpression'(node) {
|
|
114
|
-
const name = callableName(node);
|
|
115
|
-
if (name !== undefined)
|
|
116
|
-
definitions.set(name, (definitions.get(name) ?? 0) + 1);
|
|
117
|
-
},
|
|
118
|
-
VariableDeclarator(node) {
|
|
119
|
-
if (node.id.type === ast_node_types_1.AST_NODE_TYPES.Identifier && node.init) {
|
|
120
|
-
const kind = classify(node.init, config.requireSqlKeywords);
|
|
121
|
-
if (kind)
|
|
122
|
-
tainted.set(node.id.name, kind);
|
|
123
|
-
if (SQL_KEYWORDS.test(staticText(node.init)))
|
|
124
|
-
sqlish.add(node.id.name);
|
|
125
|
-
}
|
|
126
|
-
},
|
|
127
|
-
AssignmentExpression(node) {
|
|
128
|
-
if (node.operator === '+=' &&
|
|
129
|
-
node.left.type === ast_node_types_1.AST_NODE_TYPES.Identifier) {
|
|
130
|
-
const gate = config.requireSqlKeywords && !sqlish.has(node.left.name);
|
|
131
|
-
const kind = classify(node.right, gate);
|
|
132
|
-
if (kind)
|
|
133
|
-
tainted.set(node.left.name, kind);
|
|
134
|
-
if (SQL_KEYWORDS.test(staticText(node.right)))
|
|
135
|
-
sqlish.add(node.left.name);
|
|
136
|
-
}
|
|
137
|
-
},
|
|
138
|
-
CallExpression(node) {
|
|
139
|
-
const isMember = node.callee.type === ast_node_types_1.AST_NODE_TYPES.MemberExpression &&
|
|
140
|
-
node.callee.property.type === ast_node_types_1.AST_NODE_TYPES.Identifier;
|
|
141
|
-
const calleeName = isMember
|
|
142
|
-
? node.callee
|
|
143
|
-
.property.name
|
|
144
|
-
: node.callee.type === ast_node_types_1.AST_NODE_TYPES.Identifier
|
|
145
|
-
? node.callee.name
|
|
146
|
-
: undefined;
|
|
147
|
-
if (calleeName === undefined)
|
|
148
|
-
return;
|
|
149
|
-
if (!isMember || !sinks.has(calleeName)) {
|
|
150
|
-
for (const [index, arg] of node.arguments.entries()) {
|
|
151
|
-
if (arg.type === ast_node_types_1.AST_NODE_TYPES.SpreadElement)
|
|
152
|
-
continue;
|
|
153
|
-
const kind = classify(arg, true);
|
|
154
|
-
if (kind)
|
|
155
|
-
pending.push({ name: calleeName, index, arg, kind });
|
|
156
|
-
else if (arg.type === ast_node_types_1.AST_NODE_TYPES.Identifier)
|
|
157
|
-
pending.push({ name: calleeName, index, arg, kind: undefined });
|
|
158
|
-
}
|
|
159
|
-
return;
|
|
160
|
-
}
|
|
161
|
-
const queryArg = node.arguments[0];
|
|
162
|
-
if (!queryArg)
|
|
163
|
-
return;
|
|
164
|
-
if (queryArg.type === ast_node_types_1.AST_NODE_TYPES.Identifier) {
|
|
165
|
-
const fn = enclosingFunction(node);
|
|
166
|
-
const index = fn?.params.findIndex((p) => p.type === ast_node_types_1.AST_NODE_TYPES.Identifier &&
|
|
167
|
-
p.name === queryArg.name) ?? -1;
|
|
168
|
-
const name = fn && index >= 0 ? callableName(fn) : undefined;
|
|
169
|
-
if (name !== undefined && fn) {
|
|
170
|
-
wrappers.set(name, index);
|
|
171
|
-
wrapperFns.set(fn, name);
|
|
172
|
-
}
|
|
173
|
-
}
|
|
174
|
-
const direct = classify(queryArg, config.requireSqlKeywords);
|
|
175
|
-
if (direct) {
|
|
176
|
-
report(queryArg, direct);
|
|
177
|
-
return;
|
|
178
|
-
}
|
|
179
|
-
if (queryArg.type === ast_node_types_1.AST_NODE_TYPES.Identifier) {
|
|
180
|
-
const taint = tainted.get(queryArg.name);
|
|
181
|
-
if (taint)
|
|
182
|
-
report(queryArg, taint);
|
|
183
|
-
}
|
|
184
|
-
},
|
|
185
|
-
'Program:exit'() {
|
|
186
|
-
const proven = new Map();
|
|
187
|
-
for (const name of wrapperFns.values())
|
|
188
|
-
proven.set(name, (proven.get(name) ?? 0) + 1);
|
|
189
|
-
for (const { name, index, arg, kind } of pending) {
|
|
190
|
-
if (wrappers.get(name) !== index)
|
|
191
|
-
continue;
|
|
192
|
-
if (definitions.get(name) !== proven.get(name))
|
|
193
|
-
continue;
|
|
194
|
-
if (kind) {
|
|
195
|
-
report(arg, kind);
|
|
196
|
-
continue;
|
|
197
|
-
}
|
|
198
|
-
const varName = arg.name;
|
|
199
|
-
const taint = tainted.get(varName);
|
|
200
|
-
if (taint && sqlish.has(varName))
|
|
201
|
-
report(arg, taint);
|
|
202
|
-
}
|
|
203
|
-
},
|
|
204
|
-
};
|
|
205
|
-
},
|
|
206
|
-
};
|
|
207
|
-
}
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createSqlInjectionRule=createSqlInjectionRule;const ast_node_types_1=require("../ast-node-types");const messaging_1=require("../messaging");const SQL_KEYWORDS=/\b(?:select|insert|update|delete|drop|alter|truncate|union|from|where|values|set)\b/i;const FUNCTION_TYPES=new Set([ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration,ast_node_types_1.AST_NODE_TYPES.FunctionExpression,ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression]);function enclosingFunction(node){for(let n=node.parent;n;n=n.parent){if(FUNCTION_TYPES.has(n.type))return n}return void 0}function callableName(fn){if(fn.type===ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration&&fn.id)return fn.id.name;const parent=fn.parent;if(parent.type===ast_node_types_1.AST_NODE_TYPES.VariableDeclarator&&parent.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return parent.id.name}if((parent.type===ast_node_types_1.AST_NODE_TYPES.MethodDefinition||parent.type===ast_node_types_1.AST_NODE_TYPES.PropertyDefinition||parent.type===ast_node_types_1.AST_NODE_TYPES.Property)&&parent.key.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return parent.key.name}return void 0}function staticText(node){if(node.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral){return node.quasis.map(q=>q.value.raw).join(" ")}if(node.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression){return`${staticText(node.left)} ${staticText(node.right)}`}if(node.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof node.value==="string"){return node.value}return""}function classify(node,requireSqlKeywords){let kind=false;if(node.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){kind="concat"}if(node.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral&&node.expressions.length>0){kind="template"}if(kind===false)return false;if(kind==="concat"&&staticText(node).trim()==="")return false;if(requireSqlKeywords&&!SQL_KEYWORDS.test(staticText(node)))return false;return kind}function createSqlInjectionRule(config){const sinks=new Set(config.methods);return{meta:{type:config.meta.type,docs:{...config.meta.docs},messages:{noUnsafeQuery:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"Unsafe SQL query detected. Variable interpolation found.",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:config.fix,documentationLink:config.documentationLink}),unsafeTemplateLiteral:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"SQL Injection Risk",description:"Unsafe SQL query construction detected (template literal).",severity:"CRITICAL",cwe:config.meta.docs.cwe,owasp:"A03:2021",compliance:["SOC2","PCI-DSS","NIST-CSF"],effort:"high",fix:config.fix,documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){const tainted=new Map;const sqlish=new Set;const wrappers=new Map;const definitions=new Map;const wrapperFns=new Map;const pending=[];const report=(node,kind)=>{context.report({node,messageId:kind==="template"?"unsafeTemplateLiteral":"noUnsafeQuery"})};return{"FunctionDeclaration, FunctionExpression, ArrowFunctionExpression"(node){const name=callableName(node);if(name!==void 0)definitions.set(name,(definitions.get(name)??0)+1)},VariableDeclarator(node){if(node.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&node.init){const kind=classify(node.init,config.requireSqlKeywords);if(kind)tainted.set(node.id.name,kind);if(SQL_KEYWORDS.test(staticText(node.init)))sqlish.add(node.id.name)}},AssignmentExpression(node){if(node.operator==="+="&&node.left.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const gate=config.requireSqlKeywords&&!sqlish.has(node.left.name);const kind=classify(node.right,gate);if(kind)tainted.set(node.left.name,kind);if(SQL_KEYWORDS.test(staticText(node.right)))sqlish.add(node.left.name)}},CallExpression(node){const isMember=node.callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&node.callee.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier;const calleeName=isMember?node.callee.property.name:node.callee.type===ast_node_types_1.AST_NODE_TYPES.Identifier?node.callee.name:void 0;if(calleeName===void 0)return;if(!isMember||!sinks.has(calleeName)){for(const[index,arg]of node.arguments.entries()){if(arg.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;const kind=classify(arg,true);if(kind)pending.push({name:calleeName,index,arg,kind});else if(arg.type===ast_node_types_1.AST_NODE_TYPES.Identifier)pending.push({name:calleeName,index,arg,kind:void 0})}return}const queryArg=node.arguments[0];if(!queryArg)return;if(queryArg.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const fn=enclosingFunction(node);const index=fn?.params.findIndex(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&p.name===queryArg.name)??-1;const name=fn&&index>=0?callableName(fn):void 0;if(name!==void 0&&fn){wrappers.set(name,index);wrapperFns.set(fn,name)}}const direct=classify(queryArg,config.requireSqlKeywords);if(direct){report(queryArg,direct);return}if(queryArg.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const taint=tainted.get(queryArg.name);if(taint)report(queryArg,taint)}},"Program:exit"(){const proven=new Map;for(const name of wrapperFns.values())proven.set(name,(proven.get(name)??0)+1);for(const{name,index,arg,kind}of pending){if(wrappers.get(name)!==index)continue;if(definitions.get(name)!==proven.get(name))continue;if(kind){report(arg,kind);continue}const varName=arg.name;const taint=tainted.get(varName);if(taint&&sqlish.has(varName))report(arg,taint)}}}}}}
|
|
@@ -0,0 +1,78 @@
|
|
|
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
|
+
* Configuration for one vendor's instantiation of the CWE-1427 detector.
|
|
9
|
+
*
|
|
10
|
+
* The contract is: `modules` decides *whether* the rule is armed in a file,
|
|
11
|
+
* `requestPaths` decides *which calls* it looks at, and `systemPromptProps`
|
|
12
|
+
* decides *which option* inside those calls holds the instruction text. The
|
|
13
|
+
* `messages: [{ role: 'system' }]` array form is read for every vendor and is
|
|
14
|
+
* not configurable — every SDK in this family spells it the same way.
|
|
15
|
+
*
|
|
16
|
+
* `requestPaths` is what keeps two vendors' instantiations off the same line;
|
|
17
|
+
* see the note on that field before adding a path.
|
|
18
|
+
*/
|
|
19
|
+
export interface SystemPromptInjectionRuleConfig {
|
|
20
|
+
ruleName: string;
|
|
21
|
+
/** Vendor name for the message, e.g. `OpenAI`. */
|
|
22
|
+
vendor: string;
|
|
23
|
+
/** Module names that open the gate — exact specifier or subpath. */
|
|
24
|
+
modules: readonly string[];
|
|
25
|
+
/**
|
|
26
|
+
* Qualified member paths whose first argument carries the request, e.g.
|
|
27
|
+
* `messages.create` or `completions.create`. Matched as a suffix of the
|
|
28
|
+
* callee's member path.
|
|
29
|
+
*
|
|
30
|
+
* The *path*, not the leaf method: `create` alone is not SDK-specific, and
|
|
31
|
+
* matching on it meant a file importing two SDKs reported one line twice —
|
|
32
|
+
* measured, and exactly what the taxonomy contract forbids. Anthropic's
|
|
33
|
+
* `messages.create` and OpenAI's `completions.create` are distinct; a bare
|
|
34
|
+
* `generateText(...)` has no member path at all, which is what keeps
|
|
35
|
+
* vercel-ai-security's shape out.
|
|
36
|
+
*/
|
|
37
|
+
requestPaths: readonly string[];
|
|
38
|
+
/** Option names that hold the system prompt directly, e.g. `system`. */
|
|
39
|
+
systemPromptProps: readonly string[];
|
|
40
|
+
docsUrl: string;
|
|
41
|
+
documentationLink: string;
|
|
42
|
+
}
|
|
43
|
+
/**
|
|
44
|
+
* Is this expression static instruction text?
|
|
45
|
+
*
|
|
46
|
+
* Static means: a string literal, a template with no interpolations, or a
|
|
47
|
+
* concatenation of those. An interpolation, a call, an await or a member
|
|
48
|
+
* expression can all carry content this file cannot see.
|
|
49
|
+
*
|
|
50
|
+
* A bare identifier is the one deliberate exception, and only as the WHOLE
|
|
51
|
+
* value: `const SYSTEM = '…'` above the call is the correct pattern and by far
|
|
52
|
+
* the most common one. Following it is the data-flow analysis these rules exist
|
|
53
|
+
* to avoid, and reporting every `system: SYSTEM_PROMPT` would make the rule
|
|
54
|
+
* unusable. Inside a concatenation the same identifier is the dynamic half, so
|
|
55
|
+
* the exception does not apply there — see isStaticText.
|
|
56
|
+
*/
|
|
57
|
+
export declare function isStaticInstruction(node: TSESTree.Node): boolean;
|
|
58
|
+
/** Static name of a property key, or undefined when it isn't statically known. */
|
|
59
|
+
export declare function staticKey(prop: TSESTree.Node): string | undefined;
|
|
60
|
+
/**
|
|
61
|
+
* Is this object a chat message whose role is the system role?
|
|
62
|
+
*
|
|
63
|
+
* Only a literal `'system'` counts. `{ role: someRole }` is not knowably the
|
|
64
|
+
* system turn, and guessing would report user turns — which are *supposed* to
|
|
65
|
+
* carry untrusted content.
|
|
66
|
+
*/
|
|
67
|
+
export declare function isSystemMessage(node: TSESTree.Node): boolean;
|
|
68
|
+
/** The `content` value of a message object, if it has a static `content` key. */
|
|
69
|
+
export declare function messageContent(node: TSESTree.ObjectExpression): TSESTree.Node | undefined;
|
|
70
|
+
/**
|
|
71
|
+
* Dot-joined member path of a callee, root object excluded.
|
|
72
|
+
*
|
|
73
|
+
* `client.chat.completions.create` -> `chat.completions.create`.
|
|
74
|
+
* A bare `generateText` -> undefined: no member path, so no raw-SDK rule can
|
|
75
|
+
* match it and the Vercel AI SDK's form stays with its own plugin.
|
|
76
|
+
*/
|
|
77
|
+
export declare function calleePath(callee: TSESTree.Node): string | undefined;
|
|
78
|
+
export declare function createSystemPromptInjectionRule(config: SystemPromptInjectionRuleConfig): import("./rule-creator").RuleModuleWithName<"untrustedSystemPrompt", [], unknown>;
|
|
@@ -0,0 +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"})}}}}})}
|