@interlace/eslint-devkit 1.19.8 → 1.20.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/rule-creation/browser-escape-hatch-rule.d.ts +35 -1
- package/src/rule-creation/browser-escape-hatch-rule.js +1 -1
- package/src/rule-creation/connection-config.d.ts +49 -0
- package/src/rule-creation/connection-config.js +1 -0
- package/src/rule-creation/driver-origin.d.ts +52 -0
- package/src/rule-creation/driver-origin.js +1 -0
- package/src/rule-creation/hardcoded-credentials-rule.d.ts +18 -0
- package/src/rule-creation/hardcoded-credentials-rule.js +1 -1
- package/src/rule-creation/index.d.ts +1 -0
- package/src/rule-creation/index.js +1 -1
- package/src/rule-creation/mass-assignment-rule.d.ts +31 -26
- package/src/rule-creation/mass-assignment-rule.js +1 -1
- package/src/rule-creation/module-evidence.d.ts +7 -34
- package/src/rule-creation/module-evidence.js +1 -1
- package/src/rule-creation/raw-identifier-rule.d.ts +8 -0
- package/src/rule-creation/raw-identifier-rule.js +1 -1
- package/src/rule-creation/request-source.d.ts +36 -0
- package/src/rule-creation/request-source.js +1 -0
- package/src/rule-creation/require-tls-rule.d.ts +9 -1
- package/src/rule-creation/require-tls-rule.js +1 -1
- package/src/rule-creation/sdk-api-key-rule.d.ts +13 -2
- package/src/rule-creation/sdk-api-key-rule.js +1 -1
- package/src/rule-creation/sdk-flow.d.ts +161 -0
- package/src/rule-creation/sdk-flow.js +1 -0
- package/src/rule-creation/sql-injection-rule.d.ts +86 -9
- package/src/rule-creation/sql-injection-rule.js +1 -1
- package/src/rule-creation/sql-position.d.ts +51 -0
- package/src/rule-creation/sql-position.js +1 -0
- package/src/rule-creation/sql-safety.d.ts +75 -0
- package/src/rule-creation/sql-safety.js +1 -0
- package/src/rule-creation/system-prompt-injection-rule.d.ts +42 -1
- package/src/rule-creation/system-prompt-injection-rule.js +1 -1
- package/src/rule-creation/unscoped-mutation-rule.d.ts +52 -7
- package/src/rule-creation/unscoped-mutation-rule.js +1 -1
- package/src/rule-creation/value-follow.d.ts +108 -0
- package/src/rule-creation/value-follow.js +1 -0
|
@@ -0,0 +1,75 @@
|
|
|
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
|
+
* Can a value spliced into SQL text change the statement? Decided from where
|
|
8
|
+
* the value is written, never from what it is called.
|
|
9
|
+
*
|
|
10
|
+
* The shared CWE-89 detector used to report EVERY interpolation into a raw
|
|
11
|
+
* sink: `${TABLE}` bound to a literal three lines up, `${ids.map(() => '?').join()}`
|
|
12
|
+
* (the placeholder list the rule's own fix asks for), `${isUnique ? 'UNIQUE ' : ''}`,
|
|
13
|
+
* `${mysql.escapeId(col)}`. A value is SAFE here when the file proves it can
|
|
14
|
+
* only be fixed text, a number, or text the driver itself escaped or
|
|
15
|
+
* parameterised:
|
|
16
|
+
*
|
|
17
|
+
* - literals, and templates / `+` chains / ternaries / `??` / `||` built only
|
|
18
|
+
* of safe parts;
|
|
19
|
+
* - numbers: arithmetic, `.length`, `Number()` / `parseInt()` / `Math.*`, a
|
|
20
|
+
* parameter typed `number`, the index argument of an array callback;
|
|
21
|
+
* - a binding every write of which is safe — including a `let sql` builder
|
|
22
|
+
* whose every `+=` appends fixed text — an enum member, a `const` object
|
|
23
|
+
* member, a class field initialised with a literal, and a lookup into a
|
|
24
|
+
* `const` map whose every value is safe (the allowlist idiom);
|
|
25
|
+
* - a list joined from fixed elements: an array literal, `.map(cb)` whose
|
|
26
|
+
* callback returns only fixed text (`() => '?'`), `Array(n).fill('?')`;
|
|
27
|
+
* - the driver's own escapers (`mysql.escape`, `escapeId`, `format`,
|
|
28
|
+
* `sequelize.escape`) and parameterised fragments (a tagged template whose
|
|
29
|
+
* tag the driver exports, `Prisma.join`, `sql.identifier`);
|
|
30
|
+
* - a call to a function written in this file (or a relative import) every
|
|
31
|
+
* `return` of which is safe.
|
|
32
|
+
*
|
|
33
|
+
* Anything else — a parameter, request data, an unknown call — is unproven,
|
|
34
|
+
* and an unproven value in a raw SQL string is the finding.
|
|
35
|
+
*/
|
|
36
|
+
import type { TSESTree } from '@typescript-eslint/utils';
|
|
37
|
+
import { type OriginClassifier } from './driver-origin';
|
|
38
|
+
import { type Value } from './value-follow';
|
|
39
|
+
export interface SqlSafetyOptions {
|
|
40
|
+
/** Classifies a receiver (and a written type) against the driver modules. */
|
|
41
|
+
readonly origin: OriginClassifier;
|
|
42
|
+
/**
|
|
43
|
+
* Driver functions whose result is escaped SQL text: a member call on a
|
|
44
|
+
* receiver that is not provably foreign, or a binding imported under that
|
|
45
|
+
* name from the driver (`mysql.escapeId(col)`, `pool.escape(v)`,
|
|
46
|
+
* `sequelize.escape(v)`).
|
|
47
|
+
*/
|
|
48
|
+
readonly escapers: ReadonlySet<string>;
|
|
49
|
+
/**
|
|
50
|
+
* Driver members whose result is a parameterised fragment, never text:
|
|
51
|
+
* `Prisma.join(ids)`, `sql.identifier(name)`, `knex.ref(col)`. Only on a
|
|
52
|
+
* receiver proven to be the driver.
|
|
53
|
+
*/
|
|
54
|
+
readonly fragmentFactories: ReadonlySet<string>;
|
|
55
|
+
/** Modules escapers may be imported from by name. */
|
|
56
|
+
readonly modules: readonly string[];
|
|
57
|
+
/**
|
|
58
|
+
* Standalone escaping libraries for this driver — `sqlstring` for mysql —
|
|
59
|
+
* whose `escape` / `escapeId` / `format` are as good as the driver's own.
|
|
60
|
+
*/
|
|
61
|
+
readonly escaperModules?: readonly string[];
|
|
62
|
+
}
|
|
63
|
+
/** Build the safety judge for one plugin. */
|
|
64
|
+
export declare function createSqlSafety(options: SqlSafetyOptions): {
|
|
65
|
+
/**
|
|
66
|
+
* Can `value`, spliced into SQL text, only ever be fixed text or a number?
|
|
67
|
+
*
|
|
68
|
+
* @param quoted the hole sits inside a quoted token (`'…'`, `` `…` ``). An
|
|
69
|
+
* escaper's output brings its own quotes, which close that token — so
|
|
70
|
+
* there an escaped value is only as safe as what was escaped.
|
|
71
|
+
*/
|
|
72
|
+
isSafe(value: Value, quoted?: boolean): boolean;
|
|
73
|
+
};
|
|
74
|
+
/** The literal text of a string expression, ignoring every interpolated value. */
|
|
75
|
+
export declare function sqlStaticText(node: TSESTree.Node): string;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.createSqlSafety=createSqlSafety;exports.sqlStaticText=sqlStaticText;const ast_node_types_1=require("../ast-node-types");const spellings_1=require("../ast/spellings");const type_syntax_1=require("../ast/type-syntax");const driver_origin_1=require("./driver-origin");const request_source_1=require("./request-source");const value_follow_1=require("./value-follow");const NUMBER_FUNCTIONS=new Set(["Number","parseInt","parseFloat","Boolean","isNaN","isFinite"]);const NUMBER_NAMESPACES=new Set(["Math","Number"]);const FIXED_GLOBALS=new Set(["undefined","NaN","Infinity"]);const STRING_TRANSFORMS=new Set(["slice","substring","substr","trim","trimStart","trimEnd","toUpperCase","toLowerCase","padStart","padEnd","repeat","at","charAt","concat","replace","replaceAll","toString","toFixed","valueOf"]);const LIST_SUBSETS=new Set(["filter","slice","sort","reverse","concat"]);const LIST_MAPPERS=new Set(["map","flatMap"]);const ELEMENT_CALLBACKS=new Set(["map","flatMap","forEach","filter","some","every","find"]);function isFixedType(type,value){switch(type.type){case ast_node_types_1.AST_NODE_TYPES.TSNumberKeyword:case ast_node_types_1.AST_NODE_TYPES.TSBooleanKeyword:case ast_node_types_1.AST_NODE_TYPES.TSBigIntKeyword:case ast_node_types_1.AST_NODE_TYPES.TSLiteralType:case ast_node_types_1.AST_NODE_TYPES.TSUndefinedKeyword:case ast_node_types_1.AST_NODE_TYPES.TSNullKeyword:return true;case ast_node_types_1.AST_NODE_TYPES.TSUnionType:return type.types.every(t=>isFixedType(t,value));case ast_node_types_1.AST_NODE_TYPES.TSTypeReference:{if(type.typeName.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,value_follow_1.lookup)(type.typeName.name,value.env.scopeOf(type.typeName));return variable?.defs[0]?.type==="TSEnumName"}default:return false}}function enumMember(object,key,value){if(object.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return null;const variable=(0,value_follow_1.lookup)(object.name,value.env.scopeOf(object));const def=variable?.defs[0];if(def?.type!=="TSEnumName")return null;const declaration=def.node;return declaration.body.members.find(m=>(m.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier?m.id.name:m.id.value)===key)??null}function sameExpression(a,b){const x=(0,type_syntax_1.unwrapTypeSyntax)(a);const y=(0,type_syntax_1.unwrapTypeSyntax)(b);if(x.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&y.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return x.name===y.name;return x.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&y.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&(0,spellings_1.propertyName)(x)!==null&&(0,spellings_1.propertyName)(x)===(0,spellings_1.propertyName)(y)&&sameExpression(x.object,y.object)}function contains(outer,inner){return outer.range[0]<=inner.range[0]&&inner.range[1]<=outer.range[1]}function exits(statement){if(statement.type===ast_node_types_1.AST_NODE_TYPES.BlockStatement){const last=statement.body.at(-1);return last!==void 0&&exits(last)}return statement.type===ast_node_types_1.AST_NODE_TYPES.ThrowStatement||statement.type===ast_node_types_1.AST_NODE_TYPES.ReturnStatement||statement.type===ast_node_types_1.AST_NODE_TYPES.ContinueStatement||statement.type===ast_node_types_1.AST_NODE_TYPES.BreakStatement}function createSqlSafety(options){const{origin,escapers,fragmentFactories,modules}=options;let quoted=false;const escaped=(call,value,depth,seen)=>!quoted||call.arguments.every(a=>isSafe(at(a,value),depth+1,seen));const escaperOrigin=(0,driver_origin_1.createOriginClassifier)([...modules,...options.escaperModules??[]]);const escaperSources=[...modules,...options.escaperModules??[]];const at=(node,value)=>(0,value_follow_1.valueAt)(node,value.env);const isFixedOrDriverType=(type,value)=>isFixedType(type,value)||origin.ofType(at(type,value))==="ours";function isSafeList(value,depth,seen){if(depth>value_follow_1.MAX_FOLLOW_DEPTH)return false;const node=(0,type_syntax_1.unwrapTypeSyntax)(value.node);if(node.type===ast_node_types_1.AST_NODE_TYPES.ArrayExpression){return node.elements.every(element=>element===null||isSafe(at(element,value),depth+1,seen))}if(node.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const variable=(0,value_follow_1.lookup)(node.name,value.env.scopeOf(node));if(variable===null||variable.defs[0]?.type!=="Variable")return false;return variable.references.every(reference=>{if(reference.isWrite()){return reference.writeExpr!=null&&isSafeList(at(reference.writeExpr,value),depth+1,seen)}const use=reference.identifier.parent;if(use?.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&use.object===reference.identifier&&use.parent?.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&use.parent.callee===use){const method2=(0,spellings_1.propertyName)(use);if(method2==="push"||method2==="unshift"){return use.parent.arguments.every(argument=>isSafe(at(argument,value),depth+1,seen))}return true}return!(use?.type===ast_node_types_1.AST_NODE_TYPES.CallExpression||use?.type===ast_node_types_1.AST_NODE_TYPES.NewExpression)})}if(node.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){const followed=(0,value_follow_1.follow)(at(node,value));return followed.node!==node&&isSafeList(followed,depth+1,seen)}if(node.type!==ast_node_types_1.AST_NODE_TYPES.CallExpression&&node.type!==ast_node_types_1.AST_NODE_TYPES.NewExpression){return false}const callee=node.callee;if(callee.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&callee.name==="Array"&&(0,request_source_1.isGlobal)(callee,value.env)){return node.arguments.every(a=>isSafe(at(a,value),depth+1,seen))}if(callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression)return false;const method=(0,spellings_1.propertyName)(callee);const object=callee.object;const[first,second]=node.arguments;if(object.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&(object.name==="Array"||object.name==="Object")&&(0,request_source_1.isGlobal)(object,value.env)){if(object.name==="Array"&&method==="from"){if(second!==void 0)return callbackReturnsSafe(second,value,depth,seen);return first!==void 0&&isSafeList(at(first,value),depth+1,seen)}if(object.name==="Object"&&(method==="keys"||method==="values")){const target=first===void 0?null:(0,value_follow_1.follow)(at(first,value));return target!==null&&target.node.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&target.node.properties.every(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Property&&!p.computed&&(method==="keys"||isSafe(at(p.value,target),depth+1,seen)))}return false}if(method==="fill")return first!==void 0&&isSafe(at(first,value),depth+1,seen)&&(node.arguments.length===1||isSafeList(at(object,value),depth+1,seen));if(method!==null&&LIST_MAPPERS.has(method))return first!==void 0&&callbackReturnsSafe(first,value,depth,seen);if(method!==null&&LIST_SUBSETS.has(method))return isSafeList(at(object,value),depth+1,seen)&&(method!=="concat"||node.arguments.every(a=>isSafeList(at(a,value),depth+1,seen)));return false}function callbackReturnsSafe(callback,value,depth,seen){const fn=(0,type_syntax_1.unwrapTypeSyntax)(callback);if(!(0,driver_origin_1.isFunctionNode)(fn))return false;const results=(0,value_follow_1.returnedValues)(fn);return results!==null&&results.every(r=>isSafe(at(r,value),depth+1,seen))}function isSafeParameter(identifier,fn,value,depth,seen){const annotation=(0,driver_origin_1.writtenAnnotation)(identifier);if(annotation!==void 0&&isFixedOrDriverType(annotation,value))return true;const index=fn.params.findIndex(p=>p===identifier);const call=fn.parent;if(call?.type!==ast_node_types_1.AST_NODE_TYPES.CallExpression||call.arguments[0]!==fn&&call.arguments[1]!==fn||call.callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression){return false}const method=(0,spellings_1.propertyName)(call.callee);const receiver=call.callee.object;const isArrayFrom=receiver.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&receiver.name==="Array"&&method==="from"&&call.arguments[1]===fn;if(!isArrayFrom&&(method===null||!ELEMENT_CALLBACKS.has(method)||call.arguments[0]!==fn))return false;if(index===1)return true;if(index!==0)return false;if(isArrayFrom){const source=call.arguments[0];return source.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression||isSafeList(at(source,value),depth+1,seen)}return isSafeList(at(receiver,value),depth+1,seen)}function isAllowlisted(variable,use,value,depth,seen){return variable.references.some(reference=>{const call=reference.identifier.parent;if(call?.type!==ast_node_types_1.AST_NODE_TYPES.CallExpression||call.arguments[0]!==reference.identifier||call.callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression){return false}const method=(0,spellings_1.propertyName)(call.callee);const checker=at(call.callee.object,value);const fixed=method==="test"?isAnchoredPattern(checker):(method==="includes"||method==="has")&&isSafeList(checker,depth+1,seen);if(!fixed)return false;const negated=call.parent?.type===ast_node_types_1.AST_NODE_TYPES.UnaryExpression&&call.parent.operator==="!";const test=negated?call.parent:call;const guard=test?.parent;if(guard?.type!==ast_node_types_1.AST_NODE_TYPES.IfStatement||guard.test!==test)return false;if(!negated)return contains(guard.consequent,use);return exits(guard.consequent)&&guard.range[1]<=use.range[0]&&contains(guard.parent,use)})}function allowlistedBy(test,value,depth,seen){const call=test.type===ast_node_types_1.AST_NODE_TYPES.UnaryExpression&&test.operator==="!"?test.argument:test;if(call.type!==ast_node_types_1.AST_NODE_TYPES.CallExpression||call.callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression||call.arguments.length!==1){return null}const method=(0,spellings_1.propertyName)(call.callee);const checker=at(call.callee.object,value);const fixed=method==="test"?isAnchoredPattern(checker):(method==="includes"||method==="has")&&isSafeList(checker,depth+1,seen);return fixed?call.arguments[0]:null}function isAnchoredPattern(value){const target=(0,value_follow_1.follow)(value).node;const pattern=target.regex?.pattern;return pattern!==void 0&&pattern.startsWith("^")&&pattern.endsWith("$")}function isSafeIdentifier(node,value,depth,seen){const variable=(0,value_follow_1.lookup)(node.name,value.env.scopeOf(node));if(variable===null||variable.defs.length===0)return FIXED_GLOBALS.has(node.name);if(isAllowlisted(variable,node,value,depth,seen))return true;const def=variable.defs[0];if(def.type==="Parameter")return isSafeParameter(variable.identifiers[0],def.node,value,depth,seen);const specifier=(0,value_follow_1.importSpecifierOf)(variable);if(specifier!==null){if(!(0,value_follow_1.isRelativeSpecifier)(specifier.source))return false;const followed=(0,value_follow_1.follow)(at(node,value));return followed.node!==node&&followed.node.type!==ast_node_types_1.AST_NODE_TYPES.Program&&isSafe(followed,depth+1,seen)}if(def.type!=="Variable")return false;const annotation=(0,driver_origin_1.writtenAnnotation)(def.node.id);if(annotation!==void 0&&isFixedOrDriverType(annotation,value))return true;const loop=def.node.parent.parent;if(loop?.type===ast_node_types_1.AST_NODE_TYPES.ForOfStatement&&loop.left===def.node.parent){return isSafeList(at(loop.right,value),depth+1,seen)}if(def.node.id.type!==ast_node_types_1.AST_NODE_TYPES.Identifier){const followed=(0,value_follow_1.follow)(at(node,value));return followed.node!==node&&isSafe(followed,depth+1,seen)}const writes=variable.references.filter(r=>r.isWrite());return writes.length>0&&writes.every(r=>r.writeExpr!=null&&isSafe(at(r.writeExpr,value),depth+1,seen))}function isSafeMember(node,value,depth,seen){const key=(0,spellings_1.propertyName)(node);if(key==="length")return true;if(key!==null){const member=enumMember(node.object,key,value);if(member!==null)return member.initializer===void 0||isSafe(at(member.initializer,value),depth+1,seen)}const followed=(0,value_follow_1.follow)(at(node,value));if(followed.node!==node)return isSafe(followed,depth+1,seen);const owner=node.object.type===ast_node_types_1.AST_NODE_TYPES.ThisExpression?enclosingClassOf(node):classOf(node.object,value);if(owner!==null&&key!==null){const field=owner.body.body.find(e=>e.type===ast_node_types_1.AST_NODE_TYPES.PropertyDefinition&&!e.computed&&e.key.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&e.key.name===key);return field?.value!=null&&isSafe(at(field.value,value),depth+1,seen)}if(node.computed){const object=(0,value_follow_1.follow)(at(node.object,value));if(object.node.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression){return object.node.properties.every(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Property&&isSafe(at(p.value,object),depth+1,seen))}return isSafeList(object,depth+1,seen)}return false}function enclosingClassOf(node){for(let n=node.parent;n;n=n.parent){if(n.type===ast_node_types_1.AST_NODE_TYPES.ClassDeclaration||n.type===ast_node_types_1.AST_NODE_TYPES.ClassExpression){return n}}return null}function classOf(node,value){if(node.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return null;const def=(0,value_follow_1.lookup)(node.name,value.env.scopeOf(node))?.defs[0];return def?.type==="ClassName"?def.node:null}function isSafeCall(node,value,depth,seen){const callee=(0,type_syntax_1.unwrapTypeSyntax)(node.callee);const[first]=node.arguments;if(callee.type===ast_node_types_1.AST_NODE_TYPES.Identifier){if((0,request_source_1.isGlobal)(callee,value.env)){if(NUMBER_FUNCTIONS.has(callee.name))return true;return callee.name==="String"&&first!==void 0&&isSafe(at(first,value),depth+1,seen)}const specifier=(0,value_follow_1.importSpecifierOf)((0,value_follow_1.lookup)(callee.name,value.env.scopeOf(callee)));if(specifier!==null&&(0,driver_origin_1.sourceMatches)(specifier.source,escaperSources)){return escapers.has(specifier.name)&&escaped(node,value,depth,seen)}}if(callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){const method=(0,spellings_1.propertyName)(callee);const object=callee.object;if(object.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&NUMBER_NAMESPACES.has(object.name)&&(0,request_source_1.isGlobal)(object,value.env)){return true}if(method!==null){if(escapers.has(method)&&escaperOrigin(at(object,value))!=="foreign"){return escaped(node,value,depth,seen)}if(fragmentFactories.has(method)&&origin(at(object,value))==="ours")return true;if(method==="join"){return isSafeList(at(object,value),depth+1,seen)&&(first===void 0||isSafe(at(first,value),depth+1,seen))}if(STRING_TRANSFORMS.has(method)){return isSafe(at(object,value),depth+1,seen)&&node.arguments.every(a=>isSafe(at(a,value),depth+1,seen))}}}const target=(0,value_follow_1.follow)(at(callee,value));if(!(0,driver_origin_1.isFunctionNode)(target.node))return false;const results=(0,value_follow_1.returnedValues)(target.node);return results!==null&&results.every(r=>isSafe((0,value_follow_1.valueAt)(r,target.env),depth+1,seen))}function isSafe(value,depth=0,seen=new Set){if(depth>value_follow_1.MAX_FOLLOW_DEPTH||seen.has(value.node))return false;seen.add(value.node);try{if((value.node.type===ast_node_types_1.AST_NODE_TYPES.TSAsExpression||value.node.type===ast_node_types_1.AST_NODE_TYPES.TSSatisfiesExpression)&&origin.ofType(at(value.node.typeAnnotation,value))==="ours"){return true}const node=(0,type_syntax_1.unwrapTypeSyntax)(value.node);switch(node.type){case ast_node_types_1.AST_NODE_TYPES.Literal:case ast_node_types_1.AST_NODE_TYPES.UnaryExpression:case ast_node_types_1.AST_NODE_TYPES.UpdateExpression:return true;case ast_node_types_1.AST_NODE_TYPES.TemplateLiteral:return node.expressions.every(e=>isSafe(at(e,value),depth+1,seen));case ast_node_types_1.AST_NODE_TYPES.TaggedTemplateExpression:return origin(at(node.tag,value))==="ours";case ast_node_types_1.AST_NODE_TYPES.BinaryExpression:return node.operator!=="+"||isSafe(at(node.left,value),depth+1,seen)&&isSafe(at(node.right,value),depth+1,seen);case ast_node_types_1.AST_NODE_TYPES.LogicalExpression:return isSafe(at(node.left,value),depth+1,seen)&&isSafe(at(node.right,value),depth+1,seen);case ast_node_types_1.AST_NODE_TYPES.ConditionalExpression:{const checked=allowlistedBy(node.test,value,depth,seen);const armSafe=(arm,guarded)=>guarded&&checked!==null&&sameExpression(arm,checked)||isSafe(at(arm,value),depth+1,seen);const negated=node.test.type===ast_node_types_1.AST_NODE_TYPES.UnaryExpression&&node.test.operator==="!";return armSafe(node.consequent,!negated)&&armSafe(node.alternate,negated)}case ast_node_types_1.AST_NODE_TYPES.ArrayExpression:return isSafeList(at(node,value),depth+1,seen);case ast_node_types_1.AST_NODE_TYPES.AwaitExpression:return isSafe(at(node.argument,value),depth+1,seen);case ast_node_types_1.AST_NODE_TYPES.ChainExpression:return isSafe(at(node.expression,value),depth+1,seen);case ast_node_types_1.AST_NODE_TYPES.Identifier:return isSafeIdentifier(node,value,depth,seen);case ast_node_types_1.AST_NODE_TYPES.MemberExpression:return isSafeMember(node,value,depth,seen);case ast_node_types_1.AST_NODE_TYPES.CallExpression:return isSafeCall(node,value,depth,seen);default:return false}}finally{seen.delete(value.node)}}return{isSafe:(value,inQuotes=false)=>{quoted=inQuotes;try{return isSafe(value)}finally{quoted=false}}}}function sqlStaticText(node){const value=(0,type_syntax_1.unwrapTypeSyntax)(node);if(value.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral){return value.quasis.map(q=>q.value.raw).join("")}if(value.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression&&value.operator==="+"){return`${sqlStaticText(value.left)}${sqlStaticText(value.right)}`}return(0,spellings_1.staticString)(value)??""}
|
|
@@ -3,7 +3,8 @@
|
|
|
3
3
|
* Licensed under the MIT License. Use of this source code is governed by the
|
|
4
4
|
* MIT license that can be found in the LICENSE file.
|
|
5
5
|
*/
|
|
6
|
-
import type { TSESTree } from '@typescript-eslint/utils';
|
|
6
|
+
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
|
|
7
|
+
type SourceCode = Readonly<TSESLint.SourceCode>;
|
|
7
8
|
/**
|
|
8
9
|
* Configuration for one vendor's instantiation of the CWE-1427 detector.
|
|
9
10
|
*
|
|
@@ -37,6 +38,22 @@ export interface SystemPromptInjectionRuleConfig {
|
|
|
37
38
|
requestPaths: readonly string[];
|
|
38
39
|
/** Option names that hold the system prompt directly, e.g. `system`. */
|
|
39
40
|
systemPromptProps: readonly string[];
|
|
41
|
+
/**
|
|
42
|
+
* Option names whose object value holds more request options, read one level
|
|
43
|
+
* deep — `@google/genai` puts `systemInstruction` under `config`.
|
|
44
|
+
*/
|
|
45
|
+
nestedOptionKeys?: readonly string[];
|
|
46
|
+
/**
|
|
47
|
+
* SDK exports constructed with the prompt in their first argument, e.g. the
|
|
48
|
+
* OpenAI Agents SDK's `new Agent({ instructions })`. Matched against the
|
|
49
|
+
* export the callee resolves to through its import, never its local name.
|
|
50
|
+
*/
|
|
51
|
+
promptConstructors?: readonly string[];
|
|
52
|
+
/**
|
|
53
|
+
* Request paths whose argument is a *batch*: `requests: [{ params }]`, each
|
|
54
|
+
* `params` a full request body — Anthropic's `messages.batches.create`.
|
|
55
|
+
*/
|
|
56
|
+
batchRequestPaths?: readonly string[];
|
|
40
57
|
docsUrl: string;
|
|
41
58
|
documentationLink: string;
|
|
42
59
|
}
|
|
@@ -65,6 +82,29 @@ export declare function staticKey(prop: TSESTree.Node): string | undefined;
|
|
|
65
82
|
* carry untrusted content.
|
|
66
83
|
*/
|
|
67
84
|
export declare function isSystemMessage(node: TSESTree.Node): boolean;
|
|
85
|
+
/**
|
|
86
|
+
* `static` — fixed in this file. `dynamic` — built from something that can
|
|
87
|
+
* carry text this file does not fix. `unknown` — a whole value this file cannot
|
|
88
|
+
* see into (a parameter, an import, a global): the caller abstains, which is the
|
|
89
|
+
* old `system: SYSTEM_PROMPT` exception, kept.
|
|
90
|
+
*/
|
|
91
|
+
export type InstructionVerdict = 'static' | 'dynamic' | 'unknown';
|
|
92
|
+
/**
|
|
93
|
+
* Is this system-prompt value fixed in this file?
|
|
94
|
+
*
|
|
95
|
+
* `whole` is true for the value of the prompt option itself and false for a
|
|
96
|
+
* part of it. A whole value this file cannot see into (a parameter, an import,
|
|
97
|
+
* a global) is `unknown` — reporting every `system: SYSTEM_PROMPT` would make
|
|
98
|
+
* the rule unusable. The same value spliced into a template is the dynamic half
|
|
99
|
+
* of it, so it is `dynamic` there.
|
|
100
|
+
*
|
|
101
|
+
* Followed within the file: consts, `[…].join()`, string methods on static
|
|
102
|
+
* text, conditionals between static branches, same-file helpers whose every
|
|
103
|
+
* return is static, members of same-file object literals, and interpolation-free
|
|
104
|
+
* tagged templates (`dedent\`…\``). Values that cannot print text (dates,
|
|
105
|
+
* numbers, comparisons) are static wherever they appear.
|
|
106
|
+
*/
|
|
107
|
+
export declare function classifyInstruction(node: TSESTree.Node, sourceCode: SourceCode, whole: boolean, hops?: number): InstructionVerdict;
|
|
68
108
|
/** The `content` value of a message object, if it has a static `content` key. */
|
|
69
109
|
export declare function messageContent(node: TSESTree.ObjectExpression): TSESTree.Node | undefined;
|
|
70
110
|
/**
|
|
@@ -76,3 +116,4 @@ export declare function messageContent(node: TSESTree.ObjectExpression): TSESTre
|
|
|
76
116
|
*/
|
|
77
117
|
export declare function calleePath(callee: TSESTree.Node): string | undefined;
|
|
78
118
|
export declare function createSystemPromptInjectionRule(config: SystemPromptInjectionRuleConfig): import("./rule-creator").RuleModuleWithName<"untrustedSystemPrompt", [], unknown>;
|
|
119
|
+
export {};
|
|
@@ -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 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)}}}})}
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.isStaticInstruction=isStaticInstruction;exports.staticKey=staticKey;exports.isSystemMessage=isSystemMessage;exports.classifyInstruction=classifyInstruction;exports.messageContent=messageContent;exports.calleePath=calleePath;exports.createSystemPromptInjectionRule=createSystemPromptInjectionRule;const ast_node_types_1=require("../ast-node-types");const rule_creator_1=require("./rule-creator");const messaging_1=require("../messaging");const module_evidence_1=require("./module-evidence");const type_syntax_1=require("../ast/type-syntax");const spellings_1=require("../ast/spellings");const module_binding_1=require("../ast/module-binding");const sdk_flow_1=require("./sdk-flow");function isStaticInstruction(node){if(node.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return true;return isStaticText(node)}function isStaticText(node){if(node.type===ast_node_types_1.AST_NODE_TYPES.Literal)return typeof node.value==="string";if(node.type===ast_node_types_1.AST_NODE_TYPES.TemplateLiteral)return node.expressions.length===0;if(node.type===ast_node_types_1.AST_NODE_TYPES.BinaryExpression&&node.operator==="+"){return isStaticText(node.left)&&isStaticText(node.right)}return false}function staticKey(prop){if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property||prop.computed)return void 0;if(prop.key.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return prop.key.name;if(prop.key.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"){return prop.key.value}return void 0}function isSystemMessage(node){if(node.type!==ast_node_types_1.AST_NODE_TYPES.ObjectExpression)return false;return node.properties.some(prop=>{if(staticKey(prop)!=="role")return false;const value=(0,type_syntax_1.unwrapTypeSyntax)(prop.value);return value.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof value.value==="string"&&INSTRUCTION_ROLES.has(value.value)})}const INSTRUCTION_ROLES=new Set(["system","developer"]);const MESSAGE_LIST_KEYS=["messages","input"];const NON_TEXT_TYPE_KEYWORDS=new Set([ast_node_types_1.AST_NODE_TYPES.TSNumberKeyword,ast_node_types_1.AST_NODE_TYPES.TSBooleanKeyword,ast_node_types_1.AST_NODE_TYPES.TSBigIntKeyword]);const NUMERIC_GLOBAL_CALLS=new Set(["Number","parseInt","parseFloat","Boolean"]);const NUMERIC_GLOBAL_NAMESPACES=new Set(["Math","Date"]);const NUMBER_FORMAT_METHODS=new Set(["toFixed","toPrecision","toExponential"]);const isGlobalNamed=(node,names,sourceCode)=>node.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&names.has(node.name)&&(0,sdk_flow_1.isGlobalReference)(node,sourceCode);const DATE=new Set(["Date"]);function isDateValue(node,sourceCode){const resolved=(0,sdk_flow_1.followConst)(node,sourceCode);return resolved.type===ast_node_types_1.AST_NODE_TYPES.NewExpression&&isGlobalNamed(resolved.callee,DATE,sourceCode)}function isNonTextParameter(id,sourceCode){const definition=(0,sdk_flow_1.variableOf)(id,sourceCode)?.defs[0];if(definition?.type!=="Parameter")return false;const annotation=definition.name.typeAnnotation?.typeAnnotation;if(annotation===void 0)return false;const members=annotation.type===ast_node_types_1.AST_NODE_TYPES.TSUnionType?annotation.types:[annotation];return members.every(member=>NON_TEXT_TYPE_KEYWORDS.has(member.type))}function isNonText(node,sourceCode,hops){if(hops<=0)return false;const current=(0,type_syntax_1.unwrapTypeSyntax)(node);switch(current.type){case ast_node_types_1.AST_NODE_TYPES.Literal:return typeof current.value!=="string";case ast_node_types_1.AST_NODE_TYPES.UnaryExpression:return true;case ast_node_types_1.AST_NODE_TYPES.BinaryExpression:return current.operator!=="+"||isNonText(current.left,sourceCode,hops-1)&&isNonText(current.right,sourceCode,hops-1);case ast_node_types_1.AST_NODE_TYPES.NewExpression:return isGlobalNamed(current.callee,DATE,sourceCode);case ast_node_types_1.AST_NODE_TYPES.MemberExpression:return(0,spellings_1.propertyName)(current)==="length";case ast_node_types_1.AST_NODE_TYPES.CallExpression:{const callee=(0,type_syntax_1.unwrapTypeSyntax)(current.callee);if(isGlobalNamed(callee,NUMERIC_GLOBAL_CALLS,sourceCode))return true;if(callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression)return false;const method=(0,spellings_1.propertyName)(callee);return isGlobalNamed((0,type_syntax_1.unwrapTypeSyntax)(callee.object),NUMERIC_GLOBAL_NAMESPACES,sourceCode)||method!==null&&NUMBER_FORMAT_METHODS.has(method)||isDateValue(callee.object,sourceCode)}case ast_node_types_1.AST_NODE_TYPES.Identifier:{if(isNonTextParameter(current,sourceCode))return true;const resolved=(0,sdk_flow_1.followConst)(current,sourceCode);return resolved!==current&&isNonText(resolved,sourceCode,hops-1)}default:return false}}function isFunctionNode(node){return node.type===ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration||node.type===ast_node_types_1.AST_NODE_TYPES.FunctionExpression||node.type===ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression}function returnedValues(fn){if(fn.body.type!==ast_node_types_1.AST_NODE_TYPES.BlockStatement)return[fn.body];const values=[];const stack=[fn.body];while(stack.length>0){const node=stack.pop();if(node.type===ast_node_types_1.AST_NODE_TYPES.ReturnStatement&&node.argument){values.push(node.argument)}for(const key of Object.keys(node)){if(key==="parent")continue;const value=node[key];for(const child of Array.isArray(value)?value:[value]){if(child!==null&&typeof child==="object"&&typeof child.type==="string"&&!isFunctionNode(child)){stack.push(child)}}}}return values}function calledFunction(callee,sourceCode){const target=(0,type_syntax_1.unwrapTypeSyntax)(callee);if(target.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return void 0;const resolved=(0,sdk_flow_1.followConst)(target,sourceCode);if(isFunctionNode(resolved))return resolved;const definition=(0,sdk_flow_1.variableOf)(target,sourceCode)?.defs[0];return definition?.type==="FunctionName"?definition.node:void 0}function memberRoot(node){let current=node;while(current.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){current=(0,type_syntax_1.unwrapTypeSyntax)(current.object)}return current}function isImported(node,sourceCode){return node.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&(0,sdk_flow_1.variableOf)(node,sourceCode)?.defs[0]?.type==="ImportBinding"}const PATH_BUILTINS=new Set(["fs","fs/promises","os","path","path/posix","path/win32"]);const PATH_HELPERS=new Set(["mkdtemp","mkdtempSync","tmpdir","homedir","join","resolve","dirname","basename","relative","normalize"]);function isPathHelper(callee,sourceCode){const binding=(0,module_binding_1.resolveModuleBinding)(callee,sourceCode.getScope(callee));const method=binding?.path[binding.path.length-1];return binding!==void 0&&PATH_BUILTINS.has(binding.module)&&method!==void 0&&PATH_HELPERS.has(method)}function classifyInstruction(node,sourceCode,whole,hops=sdk_flow_1.MAX_FOLLOW_HOPS){const current=(0,type_syntax_1.unwrapTypeSyntax)(node);if(hops<=0)return"dynamic";if(isNonText(current,sourceCode,hops))return"static";const part=child=>classifyInstruction(child,sourceCode,false,hops-1);const allStatic=children=>children.every(child=>part(child)==="static")?"static":"dynamic";const branches=(a,b)=>{const verdicts=new Set([a,b].map(branch=>classifyInstruction(branch,sourceCode,whole,hops-1)));if(verdicts.has("dynamic"))return"dynamic";return verdicts.has("unknown")?"unknown":"static"};switch(current.type){case ast_node_types_1.AST_NODE_TYPES.Literal:return"static";case ast_node_types_1.AST_NODE_TYPES.TemplateLiteral:return allStatic(current.expressions);case ast_node_types_1.AST_NODE_TYPES.TaggedTemplateExpression:return allStatic(current.quasi.expressions);case ast_node_types_1.AST_NODE_TYPES.BinaryExpression:return allStatic([current.left,current.right]);case ast_node_types_1.AST_NODE_TYPES.ConditionalExpression:return branches(current.consequent,current.alternate);case ast_node_types_1.AST_NODE_TYPES.LogicalExpression:return branches(current.left,current.right);case ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression:case ast_node_types_1.AST_NODE_TYPES.FunctionExpression:return allStatic(returnedValues(current));case ast_node_types_1.AST_NODE_TYPES.CallExpression:return classifyCall(current,sourceCode,hops);case ast_node_types_1.AST_NODE_TYPES.AwaitExpression:return classifyInstruction(current.argument,sourceCode,whole,hops-1);case ast_node_types_1.AST_NODE_TYPES.Identifier:{const resolved=(0,sdk_flow_1.followConst)(current,sourceCode);if(resolved!==current){return classifyInstruction(resolved,sourceCode,whole,hops-1)}if(isImported(current,sourceCode))return"static";return whole?"unknown":"dynamic"}case ast_node_types_1.AST_NODE_TYPES.MemberExpression:{if((0,sdk_flow_1.isEnvironmentRead)(current,sourceCode))return"static";const object=(0,sdk_flow_1.resolveObjectLiteral)(current.object,sourceCode);if(object!==void 0){const key=(0,spellings_1.propertyName)(current);if(key===null){return allStatic(object.properties.map(property=>property.type===ast_node_types_1.AST_NODE_TYPES.Property?property.value:property))}const read=(0,sdk_flow_1.readObjectProperty)(object,key,sourceCode);if(read.kind==="value"){return classifyInstruction(read.node,sourceCode,whole,hops-1)}}const root=memberRoot(current);if(isImported(root,sourceCode))return"static";return whole&&root.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&(0,sdk_flow_1.isGlobalReference)(root,sourceCode)?"unknown":"dynamic"}default:return"dynamic"}}function classifyCall(call,sourceCode,hops){const part=child=>classifyInstruction(child,sourceCode,false,hops-1);const isStatic=child=>child.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement&&part(child)==="static";const callee=(0,type_syntax_1.unwrapTypeSyntax)(call.callee);if(isPathHelper(callee,sourceCode)){return call.arguments.every(isStatic)?"static":"dynamic"}if(callee.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){const array=(0,sdk_flow_1.resolveArrayLiteral)(callee.object,sourceCode);if(array!==void 0&&(0,spellings_1.propertyName)(callee)==="join"){const elements=array.elements.filter(element=>element!==null);return elements.every(isStatic)&&call.arguments.every(isStatic)?"static":"dynamic"}if(isImported(memberRoot(callee),sourceCode))return"dynamic";return part(callee.object)==="static"&&call.arguments.every(isStatic)?"static":"dynamic"}const fn=calledFunction(callee,sourceCode);if(fn===void 0)return"dynamic";return returnedValues(fn).every(isStatic)?"static":"dynamic"}function messageContent(node){for(const prop of node.properties){if(staticKey(prop)==="content")return prop.value}return void 0}function calleePath(callee){const parts=[];let node=callee;while(node.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){const name=(0,spellings_1.propertyName)(node);if(name===null)return void 0;parts.unshift(name);node=node.object}return parts.length>0?parts.join("."):void 0}function createSystemPromptInjectionRule(config){const promptProps=new Set(config.systemPromptProps);const paths=config.requestPaths;const usesSdk=(0,module_evidence_1.createModuleListEvidence)(config.modules);const owns=(0,module_evidence_1.createModuleListMatcher)(config.modules);const nestedKeys=config.nestedOptionKeys??[];const constructors=new Set(config.promptConstructors??[]);const batchPaths=config.batchRequestPaths??[];return(0,rule_creator_1.createRule)({name:config.ruleName,meta:{type:"problem",docs:{url:config.docsUrl,description:`Disallow untrusted content built into the ${config.vendor} system prompt`,cwe:"CWE-1427",cvss:8.1},messages:{untrustedSystemPrompt:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:`Untrusted Content in ${config.vendor} System Prompt`,cwe:"CWE-1427",owasp:"A03:2021",cvss:8.1,description:"The system prompt is built at runtime, so whatever is spliced in is read by the model as instructions rather than as data \u2014 anyone controlling that value controls the agent",severity:"HIGH",compliance:["SOC2"],fix:"Keep the system prompt a static string. Pass runtime values as a separate user message, where the model treats them as data \u2014 never interpolate them into the instructions.",documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){if(!usesSdk(context.sourceCode.ast))return{};const sourceCode=context.sourceCode;const reported=new Set;function inspectRequest(options,nested){for(const key of promptProps){const read=(0,sdk_flow_1.readObjectProperty)(options,key,sourceCode);if(read.kind==="value")collect(read.node)}for(const key of MESSAGE_LIST_KEYS){const read=(0,sdk_flow_1.readObjectProperty)(options,key,sourceCode);if(read.kind!=="value")continue;const list=(0,sdk_flow_1.resolveArrayLiteral)(read.node,sourceCode);for(const element of list?.elements??[]){if(element===null||element.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)continue;const message=(0,sdk_flow_1.resolveObjectLiteral)(element,sourceCode);if(message===void 0||!isInstructionTurn(message))continue;const content=(0,sdk_flow_1.readObjectProperty)(message,"content",sourceCode);if(content.kind==="value")collect(content.node)}}if(nested)return;for(const key of nestedKeys){const read=(0,sdk_flow_1.readObjectProperty)(options,key,sourceCode);const inner=read.kind==="value"?(0,sdk_flow_1.resolveObjectLiteral)(read.node,sourceCode):void 0;if(inner!==void 0)inspectRequest(inner,true)}}function isInstructionTurn(message){const read=(0,sdk_flow_1.readObjectProperty)(message,"role",sourceCode);if(read.kind!=="value")return false;const role=(0,sdk_flow_1.followConst)(read.node,sourceCode);return role.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof role.value==="string"&&INSTRUCTION_ROLES.has(role.value)}function collect(value){const resolved=(0,sdk_flow_1.followConst)(value,sourceCode);if(resolved.type===ast_node_types_1.AST_NODE_TYPES.ArrayExpression){for(const element of resolved.elements){if(element!==null&&element.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement)collect(element)}return}if(resolved.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression){for(const key of["text","parts"]){const read=(0,sdk_flow_1.readObjectProperty)(resolved,key,sourceCode);if(read.kind==="value")collect(read.node)}return}if(classifyInstruction(value,sourceCode,true)==="dynamic"&&!reported.has(value)){reported.add(value);context.report({node:value,messageId:"untrustedSystemPrompt"})}}function receiverIsForeign(callee){const root=memberRoot(callee);const value=(0,sdk_flow_1.followConst)(root,sourceCode);if(value===root)return false;if(value.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression)return true;if(value.type!==ast_node_types_1.AST_NODE_TYPES.NewExpression)return false;if((0,sdk_flow_1.resolveSdkExport)(value.callee,sourceCode,owns)!==void 0)return false;const constructor=(0,type_syntax_1.unwrapTypeSyntax)(value.callee);if(constructor.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return false;const definition=(0,sdk_flow_1.variableOf)(constructor,sourceCode)?.defs[0];if(definition?.type==="ImportBinding"){const source=definition.parent.source.value;return!source.startsWith(".")}if(definition?.type==="ClassName"){const superClass=definition.node.superClass;return superClass===null||(0,sdk_flow_1.resolveSdkExport)(superClass,sourceCode,owns)===void 0}return false}function requestOf(node){if(node===void 0||node.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)return;const options=(0,sdk_flow_1.resolveObjectLiteral)(node,sourceCode);if(options!==void 0)inspectRequest(options,false)}function batchEntries(node){const list=(0,sdk_flow_1.resolveArrayLiteral)(node,sourceCode);if(list!==void 0){return list.elements.filter(element=>element!==null&&element.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement)}const call=(0,sdk_flow_1.followConst)(node,sourceCode);if(call.type!==ast_node_types_1.AST_NODE_TYPES.CallExpression||call.callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression||(0,spellings_1.propertyName)(call.callee)!=="map")return[];const callback=call.arguments[0];return callback!==void 0&&isFunctionNode(callback)?returnedValues(callback):[]}function batchOf(node){if(node===void 0||node.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)return;const batch=(0,sdk_flow_1.resolveObjectLiteral)(node,sourceCode);const read=batch===void 0?void 0:(0,sdk_flow_1.readObjectProperty)(batch,"requests",sourceCode);if(read?.kind!=="value")return;for(const element of batchEntries(read.node)){const entry=(0,sdk_flow_1.resolveObjectLiteral)(element,sourceCode);const params=entry===void 0?void 0:(0,sdk_flow_1.readObjectProperty)(entry,"params",sourceCode);if(params?.kind==="value")requestOf(params.node)}}const matches=(path,list)=>list.some(p=>path===p||path.endsWith(`.${p}`));return{CallExpression(node){const path=calleePath(node.callee);if(path===void 0)return;if(matches(path,batchPaths)){if(!receiverIsForeign(node.callee))batchOf(node.arguments[0]);return}if(!matches(path,paths))return;if(receiverIsForeign(node.callee))return;for(const argument of node.arguments)requestOf(argument)},NewExpression(node){if(constructors.size===0)return;const binding=(0,sdk_flow_1.resolveSdkExport)(node.callee,sourceCode,owns);if(binding===void 0)return;if(!constructors.has((0,sdk_flow_1.sdkExportName)(binding)))return;requestOf(node.arguments[0])}}}})}
|
|
@@ -4,6 +4,7 @@
|
|
|
4
4
|
* MIT license that can be found in the LICENSE file.
|
|
5
5
|
*/
|
|
6
6
|
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
|
|
7
|
+
import { type Env } from './value-follow';
|
|
7
8
|
/** Message ids every rule built by this factory reports. */
|
|
8
9
|
export type UnscopedMutationMessageIds = 'unscopedMutation' | 'explicitTruncate';
|
|
9
10
|
export interface UnscopedMutationRuleConfig {
|
|
@@ -40,15 +41,35 @@ export interface UnscopedMutationRuleConfig {
|
|
|
40
41
|
*/
|
|
41
42
|
readonly modules: readonly string[];
|
|
42
43
|
/**
|
|
43
|
-
*
|
|
44
|
-
*
|
|
45
|
-
*
|
|
44
|
+
* @deprecated Ignored. The receiver was once matched by NAME against this
|
|
45
|
+
* pattern; it is now classified by where it is written (`driver-origin.ts`),
|
|
46
|
+
* so renaming a handle can neither silence nor create a finding. Kept so an
|
|
47
|
+
* existing caller still type-checks.
|
|
48
|
+
*/
|
|
49
|
+
readonly receiverPattern?: RegExp;
|
|
50
|
+
/**
|
|
51
|
+
* What a call must look like to be reported when its receiver cannot be
|
|
52
|
+
* traced to the driver (an undeclared name, an untyped parameter, a path
|
|
53
|
+
* alias the linter cannot read). A receiver PROVEN to be the driver's is
|
|
54
|
+
* always enough; one proven to be another library's never is.
|
|
55
|
+
*
|
|
56
|
+
* - `'model-accessor'` — Prisma's `<client>.<model>.deleteMany()`: a
|
|
57
|
+
* method read off a property of the receiver.
|
|
58
|
+
* - `'table-call'` — Knex's `<knex>('users').del()` /
|
|
59
|
+
* `<knex>.from('users').del()`: the chain starts by naming a table.
|
|
60
|
+
* - `'table-argument'` — Drizzle's `<db>.delete(users)`: the argument is
|
|
61
|
+
* a table the driver's schema helpers built.
|
|
46
62
|
*
|
|
47
|
-
*
|
|
48
|
-
*
|
|
49
|
-
* imported binding is accepted regardless of its name.
|
|
63
|
+
* Without one, an untraceable receiver is not reported: `store.delete(key)`
|
|
64
|
+
* and `db.delete(users)` are the same program when neither name resolves.
|
|
50
65
|
*/
|
|
51
|
-
readonly
|
|
66
|
+
readonly distinctiveShape?: 'model-accessor' | 'table-call' | 'table-argument';
|
|
67
|
+
/**
|
|
68
|
+
* Exported function names that make a module a migration or seed for this
|
|
69
|
+
* driver — Knex's `up` / `down` / `seed`. A full-table backfill inside one
|
|
70
|
+
* is the migration's whole purpose, not a forgotten clause.
|
|
71
|
+
*/
|
|
72
|
+
readonly migrationExports?: readonly string[];
|
|
52
73
|
/**
|
|
53
74
|
* What the sink's arguments mean for this driver. The same AST — a lone
|
|
54
75
|
* identifier argument — means opposite things per driver, so it cannot be
|
|
@@ -156,3 +177,27 @@ export declare function driverBindings(program: TSESTree.Program, modules: reado
|
|
|
156
177
|
*/
|
|
157
178
|
export declare function receiverBaseName(node: TSESTree.MemberExpression): string | undefined;
|
|
158
179
|
export declare function createUnscopedMutationRule(config: UnscopedMutationRuleConfig): TSESLint.RuleModule<UnscopedMutationMessageIds, []>;
|
|
180
|
+
/** Does this receiver chain begin by naming a table (`x('t')`, `x.from('t')`)? */
|
|
181
|
+
export declare function startsWithTable(receiver: TSESTree.Node): boolean;
|
|
182
|
+
/** Is `node` inside any of `functions`? */
|
|
183
|
+
export declare function insideAny(node: TSESTree.Node, functions: ReadonlySet<TSESTree.Node>): boolean;
|
|
184
|
+
/**
|
|
185
|
+
* The functions this module exports under any of `names` — ESM, CommonJS,
|
|
186
|
+
* `module.exports = { up, down }` — resolved through the same export reader
|
|
187
|
+
* the cross-file walk uses.
|
|
188
|
+
*/
|
|
189
|
+
export declare function exportedFunctions(program: TSESTree.Program, names: readonly string[], context: {
|
|
190
|
+
readonly physicalFilename: string;
|
|
191
|
+
readonly languageOptions?: {
|
|
192
|
+
readonly parser?: unknown;
|
|
193
|
+
};
|
|
194
|
+
readonly sourceCode: {
|
|
195
|
+
readonly scopeManager: TSESLint.Scope.ScopeManager | null;
|
|
196
|
+
};
|
|
197
|
+
}): Set<TSESTree.Node>;
|
|
198
|
+
/**
|
|
199
|
+
* Is the builder this chain starts from scoped by another statement — a
|
|
200
|
+
* `.where…()` on the same binding, or the binding handed to a function that
|
|
201
|
+
* may add one?
|
|
202
|
+
*/
|
|
203
|
+
export declare function scopedElsewhere(node: TSESTree.CallExpression, scopeMethods: readonly string[], env: Env): boolean;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.propertyKeyName=propertyKeyName;exports.hasTruthyKey=hasTruthyKey;exports.hasArgumentScope=hasArgumentScope;exports.chainMethodNames=chainMethodNames;exports.driverBindings=driverBindings;exports.receiverBaseName=receiverBaseName;exports.createUnscopedMutationRule=createUnscopedMutationRule;const ast_node_types_1=require("../ast-node-types");const messaging_1=require("../messaging");const DEFAULT_SCOPE_KEYS=["where"];const DEFAULT_SCOPE_METHODS=["where"];function propertyKeyName(prop){if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property)return void 0;if(prop.computed)return void 0;if(prop.key.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return prop.key.name;if(prop.key.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"){return prop.key.value}return void 0}function hasTruthyKey(obj,keys){return obj.properties.some(prop=>{if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property)return false;const name=propertyKeyName(prop);if(name===void 0||!keys.includes(name))return false;return!(prop.value.type===ast_node_types_1.AST_NODE_TYPES.Literal&&!prop.value.value)})}function hasArgumentScope(args,scopeKeys){return args.some(arg=>{if(arg.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression){return arg.properties.some(prop=>{if(prop.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)return true;const name=propertyKeyName(prop);if(name===void 0)return true;if(!scopeKeys.includes(name))return false;if(prop.type===ast_node_types_1.AST_NODE_TYPES.Property&&prop.value.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&prop.value.properties.length===0){return false}return true})}return arg.type!==ast_node_types_1.AST_NODE_TYPES.Literal})}function chainMethodNames(node){let root=node;for(;;){const parent=root.parent;if(!parent)break;if(parent.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&parent.object===root){root=parent;continue}if(parent.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&parent.callee===root){root=parent;continue}break}const names=new Set;let cursor=root;for(;;){if(cursor.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){cursor=cursor.callee;continue}if(cursor.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){if(!cursor.computed&&cursor.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier){names.add(cursor.property.name)}cursor=cursor.object;continue}break}return names}function driverBindings(program,modules){const names=new Set;const isDriver=source=>modules.some(m=>source===m||source.startsWith(`${m}/`));for(const stmt of program.body){if(stmt.type===ast_node_types_1.AST_NODE_TYPES.ImportDeclaration){if(typeof stmt.source.value!=="string"||!isDriver(stmt.source.value))continue;for(const spec of stmt.specifiers)names.add(spec.local.name);continue}if(stmt.type!==ast_node_types_1.AST_NODE_TYPES.VariableDeclaration)continue;for(const decl of stmt.declarations){const init=decl.init;if(!init||init.type!==ast_node_types_1.AST_NODE_TYPES.CallExpression||init.callee.type!==ast_node_types_1.AST_NODE_TYPES.Identifier||init.callee.name!=="require"){continue}const arg=init.arguments[0];if(!arg||arg.type!==ast_node_types_1.AST_NODE_TYPES.Literal||typeof arg.value!=="string"||!isDriver(arg.value)){continue}if(decl.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier)names.add(decl.id.name);if(decl.id.type===ast_node_types_1.AST_NODE_TYPES.ObjectPattern){for(const prop of decl.id.properties){if(prop.type===ast_node_types_1.AST_NODE_TYPES.Property&&prop.value.type===ast_node_types_1.AST_NODE_TYPES.Identifier){names.add(prop.value.name)}}}}}return names}function receiverBaseName(node){let cursor=node.object;for(;;){if(cursor.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){if(cursor.object.type===ast_node_types_1.AST_NODE_TYPES.ThisExpression&&!cursor.computed&&cursor.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return cursor.property.name}cursor=cursor.object;continue}if(cursor.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){cursor=cursor.callee;continue}return cursor.type===ast_node_types_1.AST_NODE_TYPES.Identifier?cursor.name:void 0}}function createUnscopedMutationRule(config){const sinks=new Set(config.methods);const scopeKeys=config.scopeKeys??DEFAULT_SCOPE_KEYS;const scopeMethods=config.scopeMethods??DEFAULT_SCOPE_METHODS;const truncateKeys=config.truncateKeys??[];const argumentRole=config.argumentRole??"options";return{meta:{type:config.meta.type,docs:{...config.meta.docs},messages:{unscopedMutation:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Unscoped Bulk Mutation",description:"Bulk mutation with no filter detected. This rewrites or deletes every row in the table.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A01:2021",compliance:["SOC2","NIST-CSF"],effort:"low",fix:config.fix,documentationLink:config.documentationLink}),explicitTruncate:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Unscoped Bulk Mutation",description:"Table truncation detected. This ignores any filter and empties the whole table.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A01:2021",compliance:["SOC2","NIST-CSF"],effort:"low",fix:"Remove the truncate flag and delete by filter, or move the truncation to an explicit maintenance script.",documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){let
|
|
1
|
+
"use strict";Object.defineProperty(exports,"__esModule",{value:true});exports.propertyKeyName=propertyKeyName;exports.hasTruthyKey=hasTruthyKey;exports.hasArgumentScope=hasArgumentScope;exports.chainMethodNames=chainMethodNames;exports.driverBindings=driverBindings;exports.receiverBaseName=receiverBaseName;exports.createUnscopedMutationRule=createUnscopedMutationRule;exports.startsWithTable=startsWithTable;exports.insideAny=insideAny;exports.exportedFunctions=exportedFunctions;exports.scopedElsewhere=scopedElsewhere;const ast_node_types_1=require("../ast-node-types");const spellings_1=require("../ast/spellings");const messaging_1=require("../messaging");const module_evidence_1=require("./module-evidence");const rule_creator_1=require("./rule-creator");const driver_origin_1=require("./driver-origin");const value_follow_1=require("./value-follow");const DEFAULT_SCOPE_KEYS=["where"];const DEFAULT_SCOPE_METHODS=["where"];function propertyKeyName(prop){if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property)return void 0;if(prop.computed)return void 0;if(prop.key.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return prop.key.name;if(prop.key.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof prop.key.value==="string"){return prop.key.value}return void 0}function hasTruthyKey(obj,keys){return obj.properties.some(prop=>{if(prop.type!==ast_node_types_1.AST_NODE_TYPES.Property)return false;const name=propertyKeyName(prop);if(name===void 0||!keys.includes(name))return false;return!(prop.value.type===ast_node_types_1.AST_NODE_TYPES.Literal&&!prop.value.value)})}function hasArgumentScope(args,scopeKeys){return args.some(arg=>{if(arg.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression){return arg.properties.some(prop=>{if(prop.type===ast_node_types_1.AST_NODE_TYPES.SpreadElement)return true;const name=propertyKeyName(prop);if(name===void 0)return true;if(!scopeKeys.includes(name))return false;if(prop.type===ast_node_types_1.AST_NODE_TYPES.Property&&prop.value.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&prop.value.properties.length===0){return false}return true})}return arg.type!==ast_node_types_1.AST_NODE_TYPES.Literal})}function chainMethodNames(node){let root=node;for(;;){const parent=root.parent;if(!parent)break;if(parent.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&parent.object===root){root=parent;continue}if(parent.type===ast_node_types_1.AST_NODE_TYPES.CallExpression&&parent.callee===root){root=parent;continue}break}const names=new Set;let cursor=root;for(;;){if(cursor.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){cursor=cursor.callee;continue}if(cursor.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){if(!cursor.computed&&cursor.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier){names.add(cursor.property.name)}cursor=cursor.object;continue}break}return names}function driverBindings(program,modules){const names=new Set;const isDriver=source=>modules.some(m=>source===m||source.startsWith(`${m}/`));for(const stmt of program.body){if(stmt.type===ast_node_types_1.AST_NODE_TYPES.ImportDeclaration){if(typeof stmt.source.value!=="string"||!isDriver(stmt.source.value))continue;for(const spec of stmt.specifiers)names.add(spec.local.name);continue}if(stmt.type!==ast_node_types_1.AST_NODE_TYPES.VariableDeclaration)continue;for(const decl of stmt.declarations){const init=decl.init;if(!init||init.type!==ast_node_types_1.AST_NODE_TYPES.CallExpression||init.callee.type!==ast_node_types_1.AST_NODE_TYPES.Identifier||init.callee.name!=="require"){continue}const arg=init.arguments[0];if(!arg||arg.type!==ast_node_types_1.AST_NODE_TYPES.Literal||typeof arg.value!=="string"||!isDriver(arg.value)){continue}if(decl.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier)names.add(decl.id.name);if(decl.id.type===ast_node_types_1.AST_NODE_TYPES.ObjectPattern){for(const prop of decl.id.properties){if(prop.type===ast_node_types_1.AST_NODE_TYPES.Property&&prop.value.type===ast_node_types_1.AST_NODE_TYPES.Identifier){names.add(prop.value.name)}}}}}return names}function receiverBaseName(node){let cursor=node.object;for(;;){if(cursor.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){if(cursor.object.type===ast_node_types_1.AST_NODE_TYPES.ThisExpression&&!cursor.computed&&cursor.property.type===ast_node_types_1.AST_NODE_TYPES.Identifier){return cursor.property.name}cursor=cursor.object;continue}if(cursor.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){cursor=cursor.callee;continue}return cursor.type===ast_node_types_1.AST_NODE_TYPES.Identifier?cursor.name:void 0}}function createUnscopedMutationRule(config){const sinks=new Set(config.methods);const scopeKeys=config.scopeKeys??DEFAULT_SCOPE_KEYS;const scopeMethods=config.scopeMethods??DEFAULT_SCOPE_METHODS;const truncateKeys=config.truncateKeys??[];const argumentRole=config.argumentRole??"options";const usesModule=(0,module_evidence_1.createModuleEvidence)({packages:config.modules});const originOf=(0,driver_origin_1.createOriginClassifier)(config.modules);return{meta:{type:config.meta.type,docs:{...config.meta.docs},messages:{unscopedMutation:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Unscoped Bulk Mutation",description:"Bulk mutation with no filter detected. This rewrites or deletes every row in the table.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A01:2021",compliance:["SOC2","NIST-CSF"],effort:"low",fix:config.fix,documentationLink:config.documentationLink}),explicitTruncate:(0,messaging_1.formatLLMMessage)({icon:messaging_1.MessageIcons.SECURITY,issueName:"Unscoped Bulk Mutation",description:"Table truncation detected. This ignores any filter and empties the whole table.",severity:"HIGH",cwe:config.meta.docs.cwe,owasp:"A01:2021",compliance:["SOC2","NIST-CSF"],effort:"low",fix:"Remove the truncate flag and delete by filter, or move the truncation to an explicit maintenance script.",documentationLink:config.documentationLink})},schema:[]},defaultOptions:[],create(context){if((0,rule_creator_1.isTestFilePath)(context.filename))return{};const env=(0,value_follow_1.envOf)(context);let ownsFile=false;let migrations=new Set;return{Program(program){ownsFile=usesModule(program);migrations=exportedFunctions(program,config.migrationExports??[],context)},CallExpression(node){if(node.callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression||node.callee.computed||node.callee.property.type!==ast_node_types_1.AST_NODE_TYPES.Identifier||!sinks.has(node.callee.property.name)){return}const origin=originOf((0,value_follow_1.valueAt)(node.callee.object,env));if(origin==="foreign")return;if(origin==="unknown"&&!(ownsFile&&hasDistinctiveShape(node))){return}if(insideAny(node,migrations))return;if(truncateKeys.length>0){const truncating=node.arguments.some(arg=>arg.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression&&hasTruthyKey(arg,truncateKeys));if(truncating){context.report({node,messageId:"explicitTruncate"});return}}if(argumentRole==="options"){if(config.requireOptionsObject===true&&!node.arguments.some(arg=>arg.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression)){return}if(hasArgumentScope(node.arguments,scopeKeys))return}const chained=chainMethodNames(node);if(scopeMethods.some(name=>chained.has(name)))return;if(scopedElsewhere(node,scopeMethods,env))return;context.report({node,messageId:"unscopedMutation"})}};function hasDistinctiveShape(node){const callee=node.callee;switch(config.distinctiveShape){case"model-accessor":return callee.object.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression;case"table-call":return startsWithTable(callee.object);case"table-argument":{const[table]=node.arguments;return table!==void 0&&table.type!==ast_node_types_1.AST_NODE_TYPES.SpreadElement&&originOf((0,value_follow_1.valueAt)(table,env))==="ours"}default:return false}}}}}const TABLE_STARTERS=new Set(["table","from","into","queryBuilder","withSchema"]);function startsWithTable(receiver){let cursor=receiver;for(;;){if(cursor.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){if(cursor.callee.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression)return true;if(TABLE_STARTERS.has((0,spellings_1.propertyName)(cursor.callee)??""))return true;cursor=cursor.callee.object;continue}if(cursor.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){cursor=cursor.object;continue}return false}}function insideAny(node,functions){for(let n=node.parent;n;n=n.parent){if(functions.has(n))return true}return false}function exportedFunctions(program,names,context){const found=new Set;const scopeManager=context.sourceCode.scopeManager;if(names.length===0||scopeManager===null)return found;const module={file:context.physicalFilename,ast:program,scopeManager};for(const name of names){const exported=(0,value_follow_1.exportedValue)(module,name,context.languageOptions?.parser);if(exported===null)continue;const target=(0,value_follow_1.follow)(exported);if((0,driver_origin_1.isFunctionNode)(target.node))found.add(target.node)}return found}function scopedElsewhere(node,scopeMethods,env){let root=node.callee;while(root.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression||root.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){root=root.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression?root.object:root.callee}if(root.type!==ast_node_types_1.AST_NODE_TYPES.Identifier)return false;const variable=(0,value_follow_1.lookup)(root.name,env.scopeOf(root));if(variable===null||variable.defs[0]?.type!=="Variable")return false;return variable.references.some(reference=>{const use=reference.identifier.parent;if(use?.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression&&use.object===reference.identifier){return scopeMethods.includes((0,spellings_1.propertyName)(use)??"")}return(use?.type===ast_node_types_1.AST_NODE_TYPES.CallExpression||use?.type===ast_node_types_1.AST_NODE_TYPES.NewExpression)&&use.arguments.some(argument=>argument===reference.identifier)})}
|
|
@@ -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
|
+
import type { TSESLint, TSESTree } from '@typescript-eslint/utils';
|
|
7
|
+
/** A parsed module on disk, with the scope analysis its own parser produced. */
|
|
8
|
+
export interface ModuleInfo {
|
|
9
|
+
readonly file: string;
|
|
10
|
+
readonly ast: TSESTree.Program;
|
|
11
|
+
readonly scopeManager: TSESLint.Scope.ScopeManager;
|
|
12
|
+
}
|
|
13
|
+
/** Where a value is being read: the file it sits in, and how to parse others. */
|
|
14
|
+
export interface Env {
|
|
15
|
+
/** Absolute path of the file the node belongs to. */
|
|
16
|
+
readonly file: string;
|
|
17
|
+
/** The parser the lint run uses — reused for every module it opens. */
|
|
18
|
+
readonly parser: unknown;
|
|
19
|
+
/** The module the node belongs to, or `null` for the file being linted. */
|
|
20
|
+
readonly module: ModuleInfo | null;
|
|
21
|
+
/** The innermost scope of a node in this file. */
|
|
22
|
+
readonly scopeOf: (node: TSESTree.Node) => TSESLint.Scope.Scope;
|
|
23
|
+
}
|
|
24
|
+
/** A node, together with the scope and environment it must be read in. */
|
|
25
|
+
export interface Value {
|
|
26
|
+
readonly node: TSESTree.Node;
|
|
27
|
+
readonly scope: TSESLint.Scope.Scope;
|
|
28
|
+
readonly env: Env;
|
|
29
|
+
}
|
|
30
|
+
/** How far a value is followed before giving up. */
|
|
31
|
+
export declare const MAX_FOLLOW_DEPTH = 8;
|
|
32
|
+
/** The slice of a rule context this module reads. */
|
|
33
|
+
export interface FollowContextLike {
|
|
34
|
+
readonly physicalFilename: string;
|
|
35
|
+
readonly languageOptions?: {
|
|
36
|
+
readonly parser?: unknown;
|
|
37
|
+
};
|
|
38
|
+
readonly sourceCode: {
|
|
39
|
+
getScope(node: TSESTree.Node): TSESLint.Scope.Scope;
|
|
40
|
+
};
|
|
41
|
+
}
|
|
42
|
+
/** Is `specifier` relative — a file in this project rather than a package? */
|
|
43
|
+
export declare function isRelativeSpecifier(specifier: string): boolean;
|
|
44
|
+
/** The environment of the file a rule is linting. */
|
|
45
|
+
export declare function envOf(context: FollowContextLike): Env;
|
|
46
|
+
/** A node read in the scope of the environment it sits in. */
|
|
47
|
+
export declare function valueAt(node: TSESTree.Node, env: Env): Value;
|
|
48
|
+
/**
|
|
49
|
+
* The file a RELATIVE specifier names, or `null`. A bare package specifier,
|
|
50
|
+
* a path alias, or a path with nothing on disk behind it is not resolved.
|
|
51
|
+
*/
|
|
52
|
+
export declare function resolveRelative(fromFile: string, specifier: string): string | null;
|
|
53
|
+
/** Parse source text with the first parser that also produces scope analysis. */
|
|
54
|
+
export declare function parseModule(text: string, file: string, parser: unknown): ModuleInfo | null;
|
|
55
|
+
/**
|
|
56
|
+
* The module at `file`, parsed and cached. JSON is read as the default export
|
|
57
|
+
* of a module whose value is the JSON text, so every AST check applies to it.
|
|
58
|
+
*/
|
|
59
|
+
export declare function loadModule(file: string, parser: unknown): ModuleInfo | null;
|
|
60
|
+
/** The innermost scope that contains `node`, inside a module opened from disk. */
|
|
61
|
+
export declare function scopeIn(module: ModuleInfo, node: TSESTree.Node): TSESLint.Scope.Scope;
|
|
62
|
+
/** The environment of a module opened from disk. */
|
|
63
|
+
export declare function moduleEnv(module: ModuleInfo, parser: unknown): Env;
|
|
64
|
+
/** The variable a name resolves to, walking outward from `scope`. */
|
|
65
|
+
export declare function lookup(name: string, scope: TSESLint.Scope.Scope): TSESLint.Scope.Variable | null;
|
|
66
|
+
/** `require('x')` — the specifier a CommonJS load names, or `null`. */
|
|
67
|
+
export declare function requiredSpecifier(node: TSESTree.Node | null | undefined): string | null;
|
|
68
|
+
/** The value of a plainly keyed property of an object literal, or `null`. */
|
|
69
|
+
export declare function findProperty(object: TSESTree.ObjectExpression, key: string): TSESTree.Node | null;
|
|
70
|
+
/** The value `name` is exported as from `module` — `'default'` for the default export. */
|
|
71
|
+
export declare function exportedValue(module: ModuleInfo, name: string, parser: unknown, depth?: number): Value | null;
|
|
72
|
+
/**
|
|
73
|
+
* Where an imported binding comes from: the module on disk and the name it
|
|
74
|
+
* is exported under (`'default'`, a named export, or `'*'` for a namespace).
|
|
75
|
+
*/
|
|
76
|
+
export declare function importOrigin(variable: TSESLint.Scope.Variable, env: Env): {
|
|
77
|
+
readonly module: ModuleInfo;
|
|
78
|
+
readonly name: string;
|
|
79
|
+
} | null;
|
|
80
|
+
/**
|
|
81
|
+
* The module specifier a binding is loaded from, and the export it names —
|
|
82
|
+
* for `import`, `import * as`, `const x = require()` and
|
|
83
|
+
* `const { a } = require()`. `null` for any other binding.
|
|
84
|
+
*/
|
|
85
|
+
export declare function importSpecifierOf(variable: TSESLint.Scope.Variable): {
|
|
86
|
+
readonly source: string;
|
|
87
|
+
readonly name: string;
|
|
88
|
+
} | null;
|
|
89
|
+
/** The expression a function returns: a concise body, or its trailing `return`. */
|
|
90
|
+
export declare function returnedValue(fn: TSESTree.Node): TSESTree.Node | null;
|
|
91
|
+
/**
|
|
92
|
+
* Every value a function can return: a concise body, or the argument of each
|
|
93
|
+
* `return` in its own body (nested functions excluded). `null` when the body
|
|
94
|
+
* can also fall off its end without a `return`, or when one `return` carries
|
|
95
|
+
* no value — then not every result is known.
|
|
96
|
+
*/
|
|
97
|
+
export declare function returnedValues(fn: TSESTree.FunctionLike): TSESTree.Node[] | null;
|
|
98
|
+
/** The single write a binding receives — its declaration or its only assignment. */
|
|
99
|
+
export declare function singleWrite(variable: TSESLint.Scope.Variable): TSESTree.Node | null;
|
|
100
|
+
/**
|
|
101
|
+
* Follow a value to where it is written.
|
|
102
|
+
*
|
|
103
|
+
* Bounded at {@link MAX_FOLLOW_DEPTH} hops and guarded against cycles: a
|
|
104
|
+
* binding that leads back to itself stops where it is. A parameter, an
|
|
105
|
+
* undeclared name, or a binding written more than once stops the walk — the
|
|
106
|
+
* caller then judges the node it was left with.
|
|
107
|
+
*/
|
|
108
|
+
export declare function follow(start: Value, depth?: number, seen?: Set<TSESTree.Node>): Value;
|
|
@@ -0,0 +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 __setModuleDefault=this&&this.__setModuleDefault||(Object.create?(function(o,v){Object.defineProperty(o,"default",{enumerable:true,value:v})}):function(o,v){o["default"]=v});var __importStar=this&&this.__importStar||(function(){var ownKeys=function(o){ownKeys=Object.getOwnPropertyNames||function(o2){var ar=[];for(var k in o2)if(Object.prototype.hasOwnProperty.call(o2,k))ar[ar.length]=k;return ar};return ownKeys(o)};return function(mod){if(mod&&mod.__esModule)return mod;var result={};if(mod!=null){for(var k=ownKeys(mod),i=0;i<k.length;i++)if(k[i]!=="default")__createBinding(result,mod,k[i])}__setModuleDefault(result,mod);return result}})();Object.defineProperty(exports,"__esModule",{value:true});exports.MAX_FOLLOW_DEPTH=void 0;exports.isRelativeSpecifier=isRelativeSpecifier;exports.envOf=envOf;exports.valueAt=valueAt;exports.resolveRelative=resolveRelative;exports.parseModule=parseModule;exports.loadModule=loadModule;exports.scopeIn=scopeIn;exports.moduleEnv=moduleEnv;exports.lookup=lookup;exports.requiredSpecifier=requiredSpecifier;exports.findProperty=findProperty;exports.exportedValue=exportedValue;exports.importOrigin=importOrigin;exports.importSpecifierOf=importSpecifierOf;exports.returnedValue=returnedValue;exports.returnedValues=returnedValues;exports.singleWrite=singleWrite;exports.follow=follow;const fs=__importStar(require("node:fs"));const path=__importStar(require("node:path"));const node_module_1=require("node:module");const ast_node_types_1=require("../ast-node-types");const spellings_1=require("../ast/spellings");const type_syntax_1=require("../ast/type-syntax");exports.MAX_FOLLOW_DEPTH=8;const EXTENSIONS=[".ts",".tsx",".js",".mjs",".cjs",".json"];const RELATIVE=/^\.{1,2}(?:\/|$)/;const JS_EXTENSION=/\.[cm]?js$/;const modules=new Map;function isRelativeSpecifier(specifier){return RELATIVE.test(specifier)}function envOf(context){return{file:path.resolve(context.physicalFilename),parser:context.languageOptions?.parser,module:null,scopeOf:node=>context.sourceCode.getScope(node)}}function valueAt(node,env){return{node,scope:env.scopeOf(node),env}}function isFile(candidate){return fs.statSync(candidate,{throwIfNoEntry:false})?.isFile()===true}function resolveRelative(fromFile,specifier){if(!isRelativeSpecifier(specifier))return null;const base=path.resolve(path.dirname(fromFile),specifier);const candidates=[base,...EXTENSIONS.map(extension=>`${base}${extension}`),...EXTENSIONS.map(extension=>path.join(base,`index${extension}`))];if(JS_EXTENSION.test(base)){const stem=base.replace(JS_EXTENSION,"");candidates.push(`${stem}.ts`,`${stem}.tsx`)}return candidates.find(isFile)??null}function fallbackParser(){try{return(0,node_module_1.createRequire)(path.join(process.cwd(),"package.json"))("@typescript-eslint/parser")}catch{return null}}function linkParents(node,parent){node.parent=parent;for(const[key,value]of Object.entries(node)){if(key==="parent")continue;const children=Array.isArray(value)?value:[value];for(const child of children){if(typeof child==="object"&&child!==null&&typeof child.type==="string"){linkParents(child,node)}}}}function parseModule(text,file,parser){for(const candidate of[parser,fallbackParser()]){const parseForESLint=candidate?.parseForESLint;if(typeof parseForESLint!=="function")continue;try{const result=parseForESLint(text,{filePath:file,sourceType:"module",ecmaVersion:"latest",range:true,loc:true});if(!result.scopeManager)continue;linkParents(result.ast,void 0);return{file,ast:result.ast,scopeManager:result.scopeManager}}catch{}}return null}function loadModule(file,parser){const stat=fs.statSync(file,{throwIfNoEntry:false});if(stat===void 0||!stat.isFile())return null;const cached=modules.get(file);if(cached!==void 0&&cached.mtimeMs===stat.mtimeMs)return cached.info;let info=null;try{const text=fs.readFileSync(file,"utf8");if(path.extname(file)===".json"){JSON.parse(text);info=parseModule(`export default (${text});`,`${file}.ts`,parser)}else{info=parseModule(text,file,parser)}}catch{info=null}modules.set(file,{mtimeMs:stat.mtimeMs,info});return info}function scopeIn(module,node){let current=node;for(;current.parent;current=current.parent){const scope=module.scopeManager.acquire(current,true);if(scope!==null)return scope}return module.scopeManager.acquire(current,true)}function moduleEnv(module,parser){return{file:module.file,parser,module,scopeOf:node=>scopeIn(module,node)}}function lookup(name,scope){for(let current=scope;current;current=current.upper){const variable=current.set.get(name);if(variable!==void 0)return variable}return null}function requiredSpecifier(node){if(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"){return null}const[argument]=node.arguments;return argument?.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof argument.value==="string"?argument.value:null}function moduleExportName(node){return node.type===ast_node_types_1.AST_NODE_TYPES.Identifier?node.name:node.value}function memberChain(node){if(node.type===ast_node_types_1.AST_NODE_TYPES.Identifier)return node.name;if(node.type!==ast_node_types_1.AST_NODE_TYPES.MemberExpression)return null;const key=(0,spellings_1.propertyName)(node);const head=memberChain(node.object);return key===null||head===null?null:`${head}.${key}`}function findProperty(object,key){for(const property of object.properties){if(property.type===ast_node_types_1.AST_NODE_TYPES.Property&&(0,spellings_1.objectKeyName)(property)===key){return property.value}}return null}function exportedValue(module,name,parser,depth=0){if(depth>exports.MAX_FOLLOW_DEPTH)return null;const env=moduleEnv(module,parser);for(const statement of module.ast.body){if(statement.type===ast_node_types_1.AST_NODE_TYPES.ExportDefaultDeclaration){if(name==="default")return valueAt(statement.declaration,env);continue}if(statement.type===ast_node_types_1.AST_NODE_TYPES.ExportNamedDeclaration){const declaration=statement.declaration;if(declaration?.type===ast_node_types_1.AST_NODE_TYPES.VariableDeclaration){const declarator=declaration.declarations.find(d=>d.id.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&d.id.name===name);if(declarator?.init)return valueAt(declarator.init,env)}else if((declaration?.type===ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration||declaration?.type===ast_node_types_1.AST_NODE_TYPES.ClassDeclaration||declaration?.type===ast_node_types_1.AST_NODE_TYPES.TSTypeAliasDeclaration||declaration?.type===ast_node_types_1.AST_NODE_TYPES.TSInterfaceDeclaration)&&declaration.id?.name===name){return valueAt(declaration,env)}for(const specifier of statement.specifiers){if(moduleExportName(specifier.exported)!==name)continue;const local=moduleExportName(specifier.local);if(statement.source!==null){const target=resolveRelative(module.file,String(statement.source.value));const next=target===null?null:loadModule(target,parser);return next===null?null:exportedValue(next,local,parser,depth+1)}const variable=lookup(local,env.scopeOf(module.ast));return variable===null?null:follow(valueAt(variable.identifiers[0],env),depth+1)}continue}if(statement.type===ast_node_types_1.AST_NODE_TYPES.ExpressionStatement&&statement.expression.type===ast_node_types_1.AST_NODE_TYPES.AssignmentExpression&&statement.expression.operator==="="){const{left,right}=statement.expression;const target=memberChain(left);if(target==="module.exports"){if(name==="default")return valueAt(right,env);const object=follow(valueAt(right,env),depth+1);if(object.node.type===ast_node_types_1.AST_NODE_TYPES.ObjectExpression){const property=findProperty(object.node,name);if(property!==null)return valueAt(property,object.env)}}else if(target===`module.exports.${name}`||target===`exports.${name}`){return valueAt(right,env)}}}return null}function importOrigin(variable,env){const specifier=importSpecifierOf(variable);if(specifier===null)return null;const file=resolveRelative(env.file,specifier.source);const module=file===null?null:loadModule(file,env.parser);return module===null?null:{module,name:specifier.name}}function importSpecifierOf(variable){const def=variable.defs[0];if(def===void 0)return null;if(def.type==="ImportBinding"){if(def.node.type===ast_node_types_1.AST_NODE_TYPES.TSImportEqualsDeclaration){const reference=def.node.moduleReference;return reference.type===ast_node_types_1.AST_NODE_TYPES.TSExternalModuleReference&&reference.expression.type===ast_node_types_1.AST_NODE_TYPES.Literal?{source:String(reference.expression.value),name:"*"}:null}const declaration=def.parent;const source2=String(declaration.source.value);if(def.node.type===ast_node_types_1.AST_NODE_TYPES.ImportSpecifier)return{source:source2,name:moduleExportName(def.node.imported)};if(def.node.type===ast_node_types_1.AST_NODE_TYPES.ImportNamespaceSpecifier)return{source:source2,name:"*"};return{source:source2,name:"default"}}if(def.type!=="Variable")return null;const declarator=def.node;const init=declarator.init?.type===ast_node_types_1.AST_NODE_TYPES.AwaitExpression?declarator.init.argument:declarator.init;const source=requiredSpecifier(init)??(init?.type===ast_node_types_1.AST_NODE_TYPES.ImportExpression&&init.source.type===ast_node_types_1.AST_NODE_TYPES.Literal&&typeof init.source.value==="string"?init.source.value:null);if(source===null)return null;if(declarator.id.type!==ast_node_types_1.AST_NODE_TYPES.ObjectPattern)return{source,name:"*"};const property=declarator.id.properties.find(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Property&&p.value.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&p.value.name===variable.name);const name=property===void 0?null:(0,spellings_1.objectKeyName)(property);return name===null?null:{source,name}}function returnedValue(fn){if(fn.type!==ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration&&fn.type!==ast_node_types_1.AST_NODE_TYPES.FunctionExpression&&fn.type!==ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression){return null}if(fn.body.type!==ast_node_types_1.AST_NODE_TYPES.BlockStatement)return fn.body;const last=fn.body.body.at(-1);return last?.type===ast_node_types_1.AST_NODE_TYPES.ReturnStatement?last.argument:null}function returnedValues(fn){if(fn.body===null||fn.body===void 0)return null;if(fn.body.type!==ast_node_types_1.AST_NODE_TYPES.BlockStatement)return[fn.body];const found=[];let bare=false;const visit=node=>{if(node.type===ast_node_types_1.AST_NODE_TYPES.ReturnStatement){if(node.argument===null)bare=true;else found.push(node.argument);return}for(const[key,value]of Object.entries(node)){if(key==="parent")continue;const children=Array.isArray(value)?value:[value];for(const child of children){if(typeof child!=="object"||child===null||typeof child.type!=="string")continue;const type=child.type;if(type===ast_node_types_1.AST_NODE_TYPES.FunctionDeclaration||type===ast_node_types_1.AST_NODE_TYPES.FunctionExpression||type===ast_node_types_1.AST_NODE_TYPES.ArrowFunctionExpression)continue;visit(child)}}};visit(fn.body);if(bare||!alwaysLeaves(fn.body)||found.length===0)return null;return found}function alwaysLeaves(statement){switch(statement.type){case ast_node_types_1.AST_NODE_TYPES.ReturnStatement:case ast_node_types_1.AST_NODE_TYPES.ThrowStatement:return true;case ast_node_types_1.AST_NODE_TYPES.BlockStatement:{const last=statement.body.at(-1);return last!==void 0&&alwaysLeaves(last)}case ast_node_types_1.AST_NODE_TYPES.IfStatement:return statement.alternate!==null&&alwaysLeaves(statement.consequent)&&alwaysLeaves(statement.alternate);default:return false}}function singleWrite(variable){if(variable.defs.some(def=>def.type==="Parameter"))return null;const writes=variable.references.filter(reference=>reference.isWrite());if(writes.length!==1)return null;return writes[0].writeExpr??null}function follow(start,depth=0,seen=new Set){if(depth>exports.MAX_FOLLOW_DEPTH||seen.has(start.node))return start;seen.add(start.node);const{scope,env}=start;const node=(0,type_syntax_1.unwrapTypeSyntax)(start.node);const next=(target,nextEnv=env)=>follow(valueAt(target,nextEnv),depth+1,seen);if(node!==start.node)return next(node);if(node.type===ast_node_types_1.AST_NODE_TYPES.AwaitExpression)return next(node.argument);if(node.type===ast_node_types_1.AST_NODE_TYPES.ChainExpression)return next(node.expression);if(node.type===ast_node_types_1.AST_NODE_TYPES.Identifier){const variable=lookup(node.name,scope);if(variable===null)return start;const def=variable.defs[0];if(def?.type==="FunctionName"||def?.type==="ClassName")return next(def.node);const origin=importOrigin(variable,env);if(origin!==null){const commonJs=origin.name==="*"&&def?.type==="Variable"?exportedValue(origin.module,"default",env.parser,depth+1):null;if(commonJs!==null)return follow(commonJs,depth+1,seen);if(origin.name==="*"){return valueAt(origin.module.ast,moduleEnv(origin.module,env.parser))}const exported=exportedValue(origin.module,origin.name,env.parser,depth+1);return exported===null?start:follow(exported,depth+1,seen)}if(def?.type==="Variable"&&def.node.id.type===ast_node_types_1.AST_NODE_TYPES.ObjectPattern){const property=def.node.id.properties.find(p=>p.type===ast_node_types_1.AST_NODE_TYPES.Property&&p.value.type===ast_node_types_1.AST_NODE_TYPES.Identifier&&p.value.name===node.name);const key=property===void 0?null:(0,spellings_1.objectKeyName)(property);if(key===null||def.node.init===null)return start;const object=next(def.node.init);if(object.node.type!==ast_node_types_1.AST_NODE_TYPES.ObjectExpression)return start;const value=findProperty(object.node,key);return value===null?start:next(value,object.env)}const written=singleWrite(variable);return written===null?start:next(written)}if(node.type===ast_node_types_1.AST_NODE_TYPES.MemberExpression){const key=(0,spellings_1.propertyName)(node);if(key===null)return start;const object=next(node.object);if(object.node.type===ast_node_types_1.AST_NODE_TYPES.Program&&object.env.module!==null){const exported=exportedValue(object.env.module,key,env.parser,depth+1);return exported===null?start:follow(exported,depth+1,seen)}if(object.node.type!==ast_node_types_1.AST_NODE_TYPES.ObjectExpression)return start;const value=findProperty(object.node,key);return value===null?start:next(value,object.env)}if(node.type===ast_node_types_1.AST_NODE_TYPES.CallExpression){const callee=next(node.callee);const returned=returnedValue(callee.node);return returned===null?start:next(returned,callee.env)}return start}
|