depkill 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +179 -3
- package/data/module-replacements.LICENSE +21 -0
- package/data/module-replacements.json +947 -0
- package/dist/src/anticheat/constants.js +105 -0
- package/dist/src/anticheat/imports.js +419 -0
- package/dist/src/anticheat/tokens.js +177 -0
- package/dist/src/anticheat.js +189 -0
- package/dist/src/card/format.js +113 -0
- package/dist/src/card/svg.js +137 -0
- package/dist/src/card.js +364 -0
- package/dist/src/check.js +139 -0
- package/dist/src/cli.js +333 -0
- package/dist/src/gate/holdout.js +78 -0
- package/dist/src/gate/process.js +78 -0
- package/dist/src/gate.js +532 -0
- package/dist/src/graph.js +148 -0
- package/dist/src/holdout/perturb.js +108 -0
- package/dist/src/holdout/snapshot.js +113 -0
- package/dist/src/init.js +76 -0
- package/dist/src/inputs/generate.js +282 -0
- package/dist/src/inputs.js +273 -0
- package/dist/src/measure.js +149 -0
- package/dist/src/project.js +72 -0
- package/dist/src/record.js +180 -0
- package/dist/src/registry.js +78 -0
- package/dist/src/replacement.js +146 -0
- package/dist/src/runner.js +227 -0
- package/dist/src/runtime/agent-inputs.js +36 -0
- package/dist/src/runtime/child.js +260 -0
- package/dist/src/runtime/esm-hooks.js +44 -0
- package/dist/src/runtime/fsguard.js +264 -0
- package/dist/src/runtime/inspect.js +115 -0
- package/dist/src/runtime/lockdown.js +157 -0
- package/dist/src/runtime/protocol.js +16 -0
- package/dist/src/scan.js +210 -0
- package/dist/src/serialize.js +399 -0
- package/dist/src/tooling.js +88 -0
- package/dist/src/types.js +9 -0
- package/dist/src/usage/common.js +36 -0
- package/dist/src/usage/fallback.js +227 -0
- package/dist/src/usage/ts.js +142 -0
- package/dist/src/usage.js +97 -0
- package/dist/src/util/exports.js +86 -0
- package/dist/src/util/fs.js +64 -0
- package/dist/src/util/term.js +61 -0
- package/package.json +54 -6
- package/skills/AGENTS.section.md +52 -0
- package/skills/depkill/SKILL.md +148 -0
|
@@ -0,0 +1,105 @@
|
|
|
1
|
+
import { scriptKind } from '../usage/ts.js';
|
|
2
|
+
import { tokenize } from './tokens.js';
|
|
3
|
+
/** Joins each run of consecutive literal pieces (null = a non-literal operand breaks the run). */
|
|
4
|
+
function foldRuns(pieces, into) {
|
|
5
|
+
let run = [];
|
|
6
|
+
const flush = () => {
|
|
7
|
+
if (run.length > 1)
|
|
8
|
+
into.add(run.join(''));
|
|
9
|
+
run = [];
|
|
10
|
+
};
|
|
11
|
+
for (const piece of pieces) {
|
|
12
|
+
if (piece === null)
|
|
13
|
+
flush();
|
|
14
|
+
else
|
|
15
|
+
run.push(piece);
|
|
16
|
+
}
|
|
17
|
+
flush();
|
|
18
|
+
}
|
|
19
|
+
function withTs(ts, src, fileName) {
|
|
20
|
+
const sf = ts.createSourceFile(fileName, src, ts.ScriptTarget.Latest, true, scriptKind(ts, fileName));
|
|
21
|
+
const out = { strings: new Set(), numbers: new Set() };
|
|
22
|
+
const isPlus = (node) => ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken;
|
|
23
|
+
const strip = (node) => (ts.isParenthesizedExpression(node) ? strip(node.expression) : node);
|
|
24
|
+
/** Operands of a `+` chain, left to right (parentheses removed). */
|
|
25
|
+
const operands = (node) => {
|
|
26
|
+
const inner = strip(node);
|
|
27
|
+
return isPlus(inner) ? [...operands(inner.left), ...operands(inner.right)] : [inner];
|
|
28
|
+
};
|
|
29
|
+
const visit = (node) => {
|
|
30
|
+
if (ts.isStringLiteralLike(node))
|
|
31
|
+
out.strings.add(node.text);
|
|
32
|
+
else if (ts.isNumericLiteral(node)) {
|
|
33
|
+
const value = Number(node.text.replaceAll('_', ''));
|
|
34
|
+
out.numbers.add(value);
|
|
35
|
+
if (ts.isPrefixUnaryExpression(node.parent) && node.parent.operator === ts.SyntaxKind.MinusToken)
|
|
36
|
+
out.numbers.add(-value);
|
|
37
|
+
}
|
|
38
|
+
else if (isPlus(node)) {
|
|
39
|
+
// Top of a `+` chain only (parentheses included): fold every run of adjacent literal operands.
|
|
40
|
+
let top = node;
|
|
41
|
+
while (ts.isParenthesizedExpression(top.parent) || isPlus(top.parent))
|
|
42
|
+
top = top.parent;
|
|
43
|
+
if (top === node)
|
|
44
|
+
foldRuns(operands(node).map((o) => (ts.isStringLiteralLike(o) ? o.text : null)), out.strings);
|
|
45
|
+
}
|
|
46
|
+
ts.forEachChild(node, visit);
|
|
47
|
+
};
|
|
48
|
+
visit(sf);
|
|
49
|
+
return out;
|
|
50
|
+
}
|
|
51
|
+
const SIMPLE_ESCAPES = { n: '\n', t: '\t', r: '\r', b: '\b', f: '\f', v: '\v', 0: '\0' };
|
|
52
|
+
/** The value of a string literal token (`'…'`, `"…"`, or a whole no-substitution template). */
|
|
53
|
+
function cook(raw) {
|
|
54
|
+
return raw.slice(1, -1).replace(/\\(u\{[0-9a-fA-F]+\}|u[0-9a-fA-F]{4}|x[0-9a-fA-F]{2}|\r?\n|[\s\S])/g, (_, esc) => {
|
|
55
|
+
if (esc.startsWith('u{'))
|
|
56
|
+
return String.fromCodePoint(parseInt(esc.slice(2, -1), 16));
|
|
57
|
+
if (esc.length > 1 && (esc[0] === 'u' || esc[0] === 'x'))
|
|
58
|
+
return String.fromCharCode(parseInt(esc.slice(1), 16));
|
|
59
|
+
if (esc === '\n' || esc === '\r\n')
|
|
60
|
+
return '';
|
|
61
|
+
return SIMPLE_ESCAPES[esc] ?? esc;
|
|
62
|
+
});
|
|
63
|
+
}
|
|
64
|
+
function literalOf(token) {
|
|
65
|
+
if (token.type === 'string' && token.value.length >= 2)
|
|
66
|
+
return cook(token.value);
|
|
67
|
+
if (token.type === 'template' && token.value.startsWith('`') && token.value.endsWith('`') && token.value.length >= 2)
|
|
68
|
+
return cook(token.value);
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
function withTokens(src) {
|
|
72
|
+
const tokens = tokenize(src);
|
|
73
|
+
const out = { strings: new Set(), numbers: new Set() };
|
|
74
|
+
const pieces = [];
|
|
75
|
+
tokens.forEach((token, i) => {
|
|
76
|
+
const literal = literalOf(token);
|
|
77
|
+
if (literal !== null)
|
|
78
|
+
out.strings.add(literal);
|
|
79
|
+
if (token.type === 'number' && !token.value.endsWith('n')) {
|
|
80
|
+
const value = Number(token.value.replaceAll('_', ''));
|
|
81
|
+
if (!Number.isNaN(value)) {
|
|
82
|
+
out.numbers.add(value);
|
|
83
|
+
if (tokens[i - 1]?.value === '-')
|
|
84
|
+
out.numbers.add(-value);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
// A `+` between two literals keeps the run going; anything else breaks it.
|
|
88
|
+
if (token.type === 'punct' && token.value === '+')
|
|
89
|
+
return;
|
|
90
|
+
pieces.push(literal);
|
|
91
|
+
});
|
|
92
|
+
foldRuns(pieces, out.strings);
|
|
93
|
+
return out;
|
|
94
|
+
}
|
|
95
|
+
export function collectConstants(src, opts = {}) {
|
|
96
|
+
if (opts.ts) {
|
|
97
|
+
try {
|
|
98
|
+
return withTs(opts.ts, src, opts.fileName ?? 'replacement.ts');
|
|
99
|
+
}
|
|
100
|
+
catch {
|
|
101
|
+
// fall back to the tokenizer
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
return withTokens(src);
|
|
105
|
+
}
|
|
@@ -0,0 +1,419 @@
|
|
|
1
|
+
import { lineIndex } from '../usage/common.js';
|
|
2
|
+
import { scriptKind } from '../usage/ts.js';
|
|
3
|
+
const NON_LITERAL = 'dynamic import/require of a non-literal specifier';
|
|
4
|
+
const REQUIRE_VALUE = '`require` used other than as a direct call on a string literal';
|
|
5
|
+
const EVAL = 'suspicious capability: eval (runs code built at runtime)';
|
|
6
|
+
const FUNCTION_CTOR = 'suspicious capability: the Function constructor (runs code built at runtime)';
|
|
7
|
+
const CONSTRUCTOR = 'suspicious capability: .constructor used outside a comparison (it reaches the Function constructor)';
|
|
8
|
+
const PROCESS_PROPS = new Set(['binding', '_linkedBinding', 'dlopen', 'mainModule']);
|
|
9
|
+
/** Objects whose members may only be read by literal name: `globalThis[x]` can reach eval, `module[x]` require. */
|
|
10
|
+
const COMPUTED_TARGETS = ['globalThis', 'global', 'window', 'self', 'process', 'module'];
|
|
11
|
+
const COMPUTED_SET = new Set(COMPUTED_TARGETS);
|
|
12
|
+
const computedProblem = (name) => `suspicious capability: computed property access on ${name} (use a literal member name)`;
|
|
13
|
+
/** Objects that may only be used through direct member access: an alias would hide what is read from them. */
|
|
14
|
+
const ALIASED_NAMES = ['globalThis', 'global', 'process', 'module'];
|
|
15
|
+
const ALIASED = new Set(ALIASED_NAMES);
|
|
16
|
+
const aliasProblem = (name) => `suspicious capability: ${name} used as a value (use direct member access such as ${name === 'process' ? 'process.env' : name === 'module' ? 'module.exports' : `${name}.Symbol`})`;
|
|
17
|
+
const EQUALITY = new Set(['===', '!==', '==', '!=']);
|
|
18
|
+
/** Property names that reach code loading or evaluation; naming them in a string or destructuring is a problem. */
|
|
19
|
+
const DANGEROUS_NAMES = ['constructor', 'eval', 'Function', 'require', 'createRequire', 'getBuiltinModule', 'mainModule', '_linkedBinding', 'dlopen', 'binding'];
|
|
20
|
+
const DANGEROUS = new Set(DANGEROUS_NAMES);
|
|
21
|
+
const namedProblem = (name) => `suspicious capability: indirect access to "${name}" (string or destructuring)`;
|
|
22
|
+
const processProblem = (name) => `suspicious capability: process.${name}`;
|
|
23
|
+
const ARGUMENTS = 'suspicious capability: module-wrapper escape (`arguments` outside a function reaches require)';
|
|
24
|
+
const THIS_ESCAPE = 'suspicious capability: function returning `this` (in sloppy mode that is the global object)';
|
|
25
|
+
const OPAQUE = 'suspicious capability: opaque blob (a long base64/hex/char-code string can hide code)';
|
|
26
|
+
const NETWORK_GLOBALS = new Set(['fetch', 'WebSocket', 'EventSource']);
|
|
27
|
+
const networkProblem = (name) => `network or code-loading capability: ${name}`;
|
|
28
|
+
const MIN_BLOB = 256;
|
|
29
|
+
/** A string of ≥ 256 characters that is mostly base64/hex/char codes: data, not text — possibly code in disguise. */
|
|
30
|
+
export function isOpaque(text) {
|
|
31
|
+
const length = text.length;
|
|
32
|
+
if (length < MIN_BLOB)
|
|
33
|
+
return false;
|
|
34
|
+
const count = (pattern) => text.match(pattern)?.length ?? 0;
|
|
35
|
+
const space = count(/\s/g);
|
|
36
|
+
const base64 = count(/[A-Za-z0-9+/=_-]/g);
|
|
37
|
+
const hex = count(/[0-9a-fA-F]/g);
|
|
38
|
+
const charCodes = count(/[0-9,\s]/g);
|
|
39
|
+
const digits = count(/[0-9]/g);
|
|
40
|
+
return (base64 / length >= 0.9 && space / length < 0.02) || hex / length >= 0.9 || (charCodes / length >= 0.9 && digits / length >= 0.5);
|
|
41
|
+
}
|
|
42
|
+
/** `.depkill` (recorded cases) and `node_modules` (the original package) may not appear anywhere in the source. */
|
|
43
|
+
export function stateReferences(src) {
|
|
44
|
+
const line = lineIndex(src);
|
|
45
|
+
const out = [];
|
|
46
|
+
for (const [pattern, what] of [[/\.depkill/gi, '.depkill (depkill state: recorded cases and the original)'], [/node_modules/gi, 'node_modules (installed packages)']]) {
|
|
47
|
+
for (const m of src.matchAll(pattern))
|
|
48
|
+
out.push({ line: line(m.index), problem: `suspicious capability: reference to ${what}` });
|
|
49
|
+
}
|
|
50
|
+
return out;
|
|
51
|
+
}
|
|
52
|
+
// --- TypeScript AST ---------------------------------------------------------------------------------
|
|
53
|
+
/** Findings from the TypeScript AST, plus whether the parser reported syntax errors. */
|
|
54
|
+
export function scanWithTs(ts, src, fileName) {
|
|
55
|
+
const sf = ts.createSourceFile(fileName, src, ts.ScriptTarget.Latest, true, scriptKind(ts, fileName));
|
|
56
|
+
const findings = [];
|
|
57
|
+
const lineOf = (node) => sf.getLineAndCharacterOfPosition(node.getStart(sf)).line + 1;
|
|
58
|
+
const add = (node, finding) => {
|
|
59
|
+
findings.push({ line: lineOf(node), ...finding });
|
|
60
|
+
};
|
|
61
|
+
const literal = (node) => (node !== undefined && ts.isStringLiteralLike(node) ? node.text : null);
|
|
62
|
+
const loads = (at, arg, typeOnly = false) => {
|
|
63
|
+
const spec = literal(arg);
|
|
64
|
+
add(at, spec === null ? { problem: NON_LITERAL } : { specifier: spec, typeOnly });
|
|
65
|
+
};
|
|
66
|
+
const unparen = (node) => (ts.isParenthesizedExpression(node.parent) ? unparen(node.parent) : node);
|
|
67
|
+
const unparenExpr = (node) => (ts.isParenthesizedExpression(node) ? unparenExpr(node.expression) : node);
|
|
68
|
+
const isIdent = (node, name) => ts.isIdentifier(node) && node.text === name;
|
|
69
|
+
const isCallee = (node) => {
|
|
70
|
+
const outer = unparen(node);
|
|
71
|
+
return ts.isCallExpression(outer.parent) && outer.parent.expression === outer;
|
|
72
|
+
};
|
|
73
|
+
const propName = (node) => {
|
|
74
|
+
if (ts.isPropertyAccessExpression(node))
|
|
75
|
+
return node.name.text;
|
|
76
|
+
if (ts.isElementAccessExpression(node))
|
|
77
|
+
return literal(node.argumentExpression);
|
|
78
|
+
return null;
|
|
79
|
+
};
|
|
80
|
+
/** Is this identifier a value reference (not a declaration name, property name or type)? */
|
|
81
|
+
const isReference = (id) => {
|
|
82
|
+
const p = id.parent;
|
|
83
|
+
if (ts.isShorthandPropertyAssignment(p))
|
|
84
|
+
return true;
|
|
85
|
+
if (ts.isQualifiedName(p) || ts.isTypeReferenceNode(p) || ts.isTypeQueryNode(p))
|
|
86
|
+
return false;
|
|
87
|
+
if (ts.isPropertyAccessExpression(p))
|
|
88
|
+
return p.expression === id;
|
|
89
|
+
const named = p;
|
|
90
|
+
return named.name !== id && named.propertyName !== id;
|
|
91
|
+
};
|
|
92
|
+
/** Nearest enclosing function that has its own `this` / `arguments` (arrow functions do not), or null at module level. */
|
|
93
|
+
const ownFunction = (node) => {
|
|
94
|
+
for (let p = node.parent; p !== undefined; p = p.parent) {
|
|
95
|
+
if (ts.isFunctionLike(p) && !ts.isArrowFunction(p))
|
|
96
|
+
return p;
|
|
97
|
+
if (ts.isClassStaticBlockDeclaration(p))
|
|
98
|
+
return null;
|
|
99
|
+
}
|
|
100
|
+
return null;
|
|
101
|
+
};
|
|
102
|
+
/** Root of a member chain: `a` in `a.b[c].d`. */
|
|
103
|
+
const chainRoot = (node) => {
|
|
104
|
+
let n = node;
|
|
105
|
+
while (ts.isPropertyAccessExpression(n) || ts.isElementAccessExpression(n) || ts.isParenthesizedExpression(n) || ts.isNonNullExpression(n))
|
|
106
|
+
n = n.expression;
|
|
107
|
+
return n;
|
|
108
|
+
};
|
|
109
|
+
/** A function expression called on the spot or through .call/.apply/.bind, or any function declaration. */
|
|
110
|
+
const calledLoose = (fn) => {
|
|
111
|
+
if (ts.isFunctionDeclaration(fn))
|
|
112
|
+
return true;
|
|
113
|
+
if (!ts.isFunctionExpression(fn))
|
|
114
|
+
return false;
|
|
115
|
+
const outer = unparen(fn);
|
|
116
|
+
if (isCallee(fn))
|
|
117
|
+
return true;
|
|
118
|
+
return ts.isPropertyAccessExpression(outer.parent) && outer.parent.expression === outer && ['call', 'apply', 'bind'].includes(outer.parent.name.text);
|
|
119
|
+
};
|
|
120
|
+
/** Text of a `'a' + 'b' + …` chain made only of string literals, or null. */
|
|
121
|
+
const literalConcat = (node) => {
|
|
122
|
+
if (ts.isParenthesizedExpression(node))
|
|
123
|
+
return literalConcat(node.expression);
|
|
124
|
+
if (ts.isStringLiteralLike(node))
|
|
125
|
+
return node.text;
|
|
126
|
+
if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken) {
|
|
127
|
+
const left = literalConcat(node.left);
|
|
128
|
+
const right = left === null ? null : literalConcat(node.right);
|
|
129
|
+
return left === null || right === null ? null : left + right;
|
|
130
|
+
}
|
|
131
|
+
return null;
|
|
132
|
+
};
|
|
133
|
+
/** A call that loads or resolves a module: import(), require(), x.require(), require.resolve(), … */
|
|
134
|
+
const isLoaderCall = (call) => {
|
|
135
|
+
const callee = call.expression;
|
|
136
|
+
if (callee.kind === ts.SyntaxKind.ImportKeyword || isIdent(callee, 'require'))
|
|
137
|
+
return true;
|
|
138
|
+
if (ts.isCallExpression(callee) && (isIdent(callee.expression, 'createRequire') || propName(callee.expression) === 'createRequire'))
|
|
139
|
+
return true;
|
|
140
|
+
const name = propName(callee);
|
|
141
|
+
if (name === 'require' || name === 'getBuiltinModule')
|
|
142
|
+
return true;
|
|
143
|
+
if (name !== 'resolve' || !(ts.isPropertyAccessExpression(callee) || ts.isElementAccessExpression(callee)))
|
|
144
|
+
return false;
|
|
145
|
+
const target = callee.expression;
|
|
146
|
+
const createRequireCall = ts.isCallExpression(target)
|
|
147
|
+
&& (isIdent(target.expression, 'createRequire') || propName(target.expression) === 'createRequire');
|
|
148
|
+
return isIdent(target, 'require') || createRequireCall
|
|
149
|
+
|| (ts.isMetaProperty(target) && target.keywordToken === ts.SyntaxKind.ImportKeyword);
|
|
150
|
+
};
|
|
151
|
+
const visitIdentifier = (node) => {
|
|
152
|
+
if (!isReference(node))
|
|
153
|
+
return;
|
|
154
|
+
const outer = unparen(node);
|
|
155
|
+
const p = outer.parent;
|
|
156
|
+
const typeofOperand = ts.isTypeOfExpression(p);
|
|
157
|
+
if (node.text === 'require' && !typeofOperand && !isCallee(node)) {
|
|
158
|
+
const resolveCall = ts.isPropertyAccessExpression(p) && p.name.text === 'resolve' && isCallee(p);
|
|
159
|
+
if (!resolveCall)
|
|
160
|
+
add(node, { problem: REQUIRE_VALUE });
|
|
161
|
+
}
|
|
162
|
+
else if (node.text === 'eval' && !typeofOperand) {
|
|
163
|
+
add(node, { problem: EVAL });
|
|
164
|
+
}
|
|
165
|
+
else if (node.text === 'Function') {
|
|
166
|
+
const instanceOf = ts.isBinaryExpression(p) && p.operatorToken.kind === ts.SyntaxKind.InstanceOfKeyword && p.right === outer;
|
|
167
|
+
const prototype = ts.isPropertyAccessExpression(p) && p.name.text === 'prototype';
|
|
168
|
+
if (!instanceOf && !prototype && !typeofOperand)
|
|
169
|
+
add(node, { problem: FUNCTION_CTOR });
|
|
170
|
+
}
|
|
171
|
+
else if (node.text === 'arguments' && ownFunction(node) === null) {
|
|
172
|
+
add(node, { problem: ARGUMENTS });
|
|
173
|
+
}
|
|
174
|
+
else if (NETWORK_GLOBALS.has(node.text) && !typeofOperand) {
|
|
175
|
+
add(node, { problem: networkProblem(node.text) });
|
|
176
|
+
}
|
|
177
|
+
else if (ALIASED.has(node.text) && !typeofOperand) {
|
|
178
|
+
// `process.env.X` / `globalThis.Symbol` are fine; `const g = globalThis` hides later member names.
|
|
179
|
+
const member = (ts.isPropertyAccessExpression(p) || ts.isElementAccessExpression(p)) && p.expression === outer;
|
|
180
|
+
if (!member)
|
|
181
|
+
add(node, { problem: aliasProblem(node.text) });
|
|
182
|
+
}
|
|
183
|
+
};
|
|
184
|
+
const visitMember = (node) => {
|
|
185
|
+
const name = propName(node);
|
|
186
|
+
const target = node.expression;
|
|
187
|
+
if (name === null && ts.isElementAccessExpression(node)) {
|
|
188
|
+
const root = chainRoot(target);
|
|
189
|
+
if (ts.isIdentifier(root) && (COMPUTED_SET.has(root.text) || root.text === 'require'))
|
|
190
|
+
add(node, { problem: computedProblem(root.text) });
|
|
191
|
+
else if (root.kind === ts.SyntaxKind.ThisKeyword && ownFunction(root) === null)
|
|
192
|
+
add(node, { problem: computedProblem('this') });
|
|
193
|
+
return;
|
|
194
|
+
}
|
|
195
|
+
const root = chainRoot(target);
|
|
196
|
+
if (name !== null && NETWORK_GLOBALS.has(name) && ts.isIdentifier(root) && COMPUTED_SET.has(root.text) && root.text !== 'process' && root.text !== 'module') {
|
|
197
|
+
add(node, { problem: networkProblem(name) });
|
|
198
|
+
}
|
|
199
|
+
// `globalThis.process` / `global.module` are the same objects: only direct member access on them too.
|
|
200
|
+
if (name !== null && ALIASED.has(name) && ts.isIdentifier(target) && (target.text === 'globalThis' || target.text === 'global')) {
|
|
201
|
+
const outer = unparen(node);
|
|
202
|
+
const p = outer.parent;
|
|
203
|
+
const member = (ts.isPropertyAccessExpression(p) || ts.isElementAccessExpression(p)) && p.expression === outer;
|
|
204
|
+
if (!member && !ts.isTypeOfExpression(p))
|
|
205
|
+
add(node, { problem: aliasProblem(name) });
|
|
206
|
+
}
|
|
207
|
+
if (name === 'constructor') {
|
|
208
|
+
const outer = unparen(node);
|
|
209
|
+
const p = outer.parent;
|
|
210
|
+
const compared = ts.isBinaryExpression(p) && EQUALITY.has(ts.tokenToString(p.operatorToken.kind) ?? '');
|
|
211
|
+
const harmless = ts.isPropertyAccessExpression(p) && p.expression === outer && (p.name.text === 'name' || p.name.text === 'prototype');
|
|
212
|
+
if (!compared && !harmless)
|
|
213
|
+
add(node, { problem: CONSTRUCTOR });
|
|
214
|
+
}
|
|
215
|
+
else if (name === 'eval')
|
|
216
|
+
add(node, { problem: EVAL });
|
|
217
|
+
else if (name === 'Function' && !(ts.isPropertyAccessExpression(unparen(node).parent) && propName(unparen(node).parent) === 'prototype')) {
|
|
218
|
+
add(node, { problem: FUNCTION_CTOR });
|
|
219
|
+
}
|
|
220
|
+
else if (name === 'binding' && isCallee(node))
|
|
221
|
+
add(node, { problem: processProblem('binding') });
|
|
222
|
+
else if (name !== null && PROCESS_PROPS.has(name) && name !== 'binding')
|
|
223
|
+
add(node, { problem: processProblem(name) });
|
|
224
|
+
else if ((name === 'require' || name === 'getBuiltinModule') && !isCallee(node))
|
|
225
|
+
add(node, { problem: REQUIRE_VALUE });
|
|
226
|
+
};
|
|
227
|
+
/** Numeric literals among call arguments, counting the elements of array-literal (or spread array) arguments. */
|
|
228
|
+
const numericArgs = (args) => args.reduce((n, arg) => {
|
|
229
|
+
const inner = ts.isSpreadElement(arg) ? arg.expression : arg;
|
|
230
|
+
if (ts.isNumericLiteral(inner))
|
|
231
|
+
return n + 1;
|
|
232
|
+
return ts.isArrayLiteralExpression(inner) ? n + inner.elements.filter((e) => ts.isNumericLiteral(e)).length : n;
|
|
233
|
+
}, 0);
|
|
234
|
+
/** `String.fromCharCode(…64+ numbers)`, `Buffer.from([…])`, `new Uint8Array([…])`: bytes of hidden source. */
|
|
235
|
+
const byteBlob = (node) => {
|
|
236
|
+
if (!ts.isCallExpression(node) && !ts.isNewExpression(node))
|
|
237
|
+
return false;
|
|
238
|
+
const callee = propName(node.expression) ?? (ts.isIdentifier(node.expression) ? node.expression.text : '');
|
|
239
|
+
return /^(fromCharCode|fromCodePoint|from|of|Uint8Array|Uint16Array|Int8Array|Buffer)$/.test(callee) && numericArgs(node.arguments ?? []) >= MIN_BLOB / 4;
|
|
240
|
+
};
|
|
241
|
+
const visit = (node) => {
|
|
242
|
+
if (byteBlob(node))
|
|
243
|
+
add(node, { problem: OPAQUE });
|
|
244
|
+
if (ts.isImportDeclaration(node)) {
|
|
245
|
+
loads(node, node.moduleSpecifier, node.importClause?.isTypeOnly === true);
|
|
246
|
+
}
|
|
247
|
+
else if (ts.isExportDeclaration(node) && node.moduleSpecifier !== undefined) {
|
|
248
|
+
loads(node, node.moduleSpecifier, node.isTypeOnly);
|
|
249
|
+
}
|
|
250
|
+
else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
|
|
251
|
+
loads(node, node.moduleReference.expression, node.isTypeOnly);
|
|
252
|
+
}
|
|
253
|
+
else if (ts.isImportTypeNode(node)) {
|
|
254
|
+
const arg = node.argument;
|
|
255
|
+
loads(node, ts.isLiteralTypeNode(arg) ? arg.literal : undefined, true);
|
|
256
|
+
}
|
|
257
|
+
else if (ts.isCallExpression(node) && isLoaderCall(node)) {
|
|
258
|
+
loads(node, node.arguments[0]);
|
|
259
|
+
}
|
|
260
|
+
else if (ts.isIdentifier(node)) {
|
|
261
|
+
visitIdentifier(node);
|
|
262
|
+
}
|
|
263
|
+
else if (ts.isPropertyAccessExpression(node) || ts.isElementAccessExpression(node)) {
|
|
264
|
+
visitMember(node);
|
|
265
|
+
}
|
|
266
|
+
else if (ts.isBindingElement(node)) {
|
|
267
|
+
const key = node.propertyName ?? node.name;
|
|
268
|
+
const name = ts.isIdentifier(key) || ts.isStringLiteralLike(key) ? key.text : null;
|
|
269
|
+
if (name !== null && DANGEROUS.has(name))
|
|
270
|
+
add(node, { problem: namedProblem(name) });
|
|
271
|
+
}
|
|
272
|
+
else if (ts.isReturnStatement(node) && node.expression !== undefined && unparenExpr(node.expression).kind === ts.SyntaxKind.ThisKeyword) {
|
|
273
|
+
const fn = ownFunction(node);
|
|
274
|
+
if (fn !== null && calledLoose(fn))
|
|
275
|
+
add(node, { problem: THIS_ESCAPE });
|
|
276
|
+
}
|
|
277
|
+
else if (ts.isBinaryExpression(node) && node.operatorToken.kind === ts.SyntaxKind.PlusToken && !(ts.isBinaryExpression(unparen(node).parent))) {
|
|
278
|
+
const text = literalConcat(node);
|
|
279
|
+
if (text !== null && isOpaque(text))
|
|
280
|
+
add(node, { problem: OPAQUE });
|
|
281
|
+
}
|
|
282
|
+
else if ((ts.isTemplateHead(node) || ts.isTemplateMiddle(node) || ts.isTemplateTail(node)) && isOpaque(node.text)) {
|
|
283
|
+
add(node, { problem: OPAQUE });
|
|
284
|
+
}
|
|
285
|
+
else if (ts.isStringLiteralLike(node) && isOpaque(node.text)) {
|
|
286
|
+
add(node, { problem: OPAQUE });
|
|
287
|
+
}
|
|
288
|
+
else if (ts.isStringLiteralLike(node) && DANGEROUS.has(node.text)) {
|
|
289
|
+
// Element-access arguments are judged by visitMember (x['constructor'] === Object is fine).
|
|
290
|
+
const indexed = ts.isElementAccessExpression(node.parent) && node.parent.argumentExpression === node;
|
|
291
|
+
if (!indexed)
|
|
292
|
+
add(node, { problem: namedProblem(node.text) });
|
|
293
|
+
}
|
|
294
|
+
ts.forEachChild(node, visit);
|
|
295
|
+
};
|
|
296
|
+
visit(sf);
|
|
297
|
+
const parseDiagnostics = sf.parseDiagnostics;
|
|
298
|
+
return { findings, parseErrors: Array.isArray(parseDiagnostics) && parseDiagnostics.length > 0 };
|
|
299
|
+
}
|
|
300
|
+
// --- conservative raw-text scan ---------------------------------------------------------------------
|
|
301
|
+
// Whitespace and comments between tokens (R20: webpack-style `import(/* magic */ 'x')`).
|
|
302
|
+
// A block comment is matched exactly (it cannot contain `*/`), so a gap never swallows code between two comments.
|
|
303
|
+
const GAP = String.raw `(?:\s|/\*(?:[^*]|\*(?!/))*\*/|//[^\n]*(?:\n|$))*`;
|
|
304
|
+
const LITERAL_ARG = new RegExp(String.raw `^${GAP}\(${GAP}(?:'([^'\\\n]*)'|"([^"\\\n]*)"|\x60([^\x60\\$]*)\x60)${GAP}[,)]`);
|
|
305
|
+
const STATIC = new RegExp(String.raw `\b(?:from|import)${GAP}(['"])([^'"\n]*)\1`, 'g');
|
|
306
|
+
const CALL = new RegExp(String.raw `^${GAP}\(`);
|
|
307
|
+
const RESOLVE_CALL = new RegExp(String.raw `^${GAP}\.${GAP}resolve${GAP}\(`);
|
|
308
|
+
const META_RESOLVE = new RegExp(String.raw `^${GAP}\.${GAP}meta${GAP}\.${GAP}resolve${GAP}(?=\()`);
|
|
309
|
+
const CREATE_REQUIRE_CALL = new RegExp(String.raw `^${GAP}\([^()]*\)${GAP}(?=\()`);
|
|
310
|
+
const CONSTRUCTOR_OK_AFTER = new RegExp(String.raw `^${GAP}(?:===?|!==?|\.${GAP}(?:name|prototype)\b)`);
|
|
311
|
+
const CONSTRUCTOR_END = new RegExp(String.raw `^${GAP}(?:[)\]};,:?&|]|$)`);
|
|
312
|
+
const PROTOTYPE_AFTER = new RegExp(String.raw `^${GAP}\.${GAP}prototype\b`);
|
|
313
|
+
const PROCESS_MEMBER = new RegExp(String.raw `\bprocess${GAP}\.${GAP}([\w$]+)`, 'g');
|
|
314
|
+
const LITERAL_INDEX = String.raw `\[${GAP}['"][\w$]*['"]${GAP}\]`;
|
|
315
|
+
/** `root(.a|['a'])*[expr]`: a computed member anywhere along a chain that starts at a sensitive root. */
|
|
316
|
+
const COMPUTED_INDEX = new RegExp(String.raw `\b(${[...COMPUTED_TARGETS, 'require', 'this'].join('|')})(?:${GAP}(?:\??\.${GAP}[\w$]+|${LITERAL_INDEX}))*${GAP}\[(?!${GAP}['"][\w$]*['"]${GAP}\])`, 'g');
|
|
317
|
+
const RETURN_THIS = new RegExp(String.raw `\breturn${GAP}this\b`, 'g');
|
|
318
|
+
const NETWORK_WORD = new RegExp(String.raw `(?<![.\w$])(fetch|WebSocket|EventSource)\b|\b(?:globalThis|global|self|window)${GAP}\.${GAP}(fetch|WebSocket|EventSource)\b`, 'g');
|
|
319
|
+
const BLOB_RUN = /[A-Za-z0-9+/=_-]{256,}|(?:\d{1,3}\s*,\s*){64,}\d/g;
|
|
320
|
+
const BINDING_CALL = new RegExp(String.raw `\.${GAP}binding${GAP}\(`, 'g');
|
|
321
|
+
const QUOTED_NAME = new RegExp(String.raw `(['"\x60])(${DANGEROUS_NAMES.join('|')})\1`, 'g');
|
|
322
|
+
const INDEX_OPEN = new RegExp(String.raw `\[${GAP}$`);
|
|
323
|
+
const BARE_CONSTRUCTOR = /\bconstructor\b/g;
|
|
324
|
+
const ALIAS_WORD = new RegExp(String.raw `(?<![\w$])(${ALIASED_NAMES.join('|')})\b`, 'g');
|
|
325
|
+
const MEMBER_AFTER = new RegExp(String.raw `^${GAP}(?:\?\.|\.|\[)`);
|
|
326
|
+
const CONSTRUCTOR_ACCESS = new RegExp(String.raw `(?:\.${GAP}constructor\b|\[${GAP}['"]constructor['"]${GAP}\])`, 'g');
|
|
327
|
+
/** Specifier finding (or non-literal problem) for the argument list that starts right after `end`. */
|
|
328
|
+
function literalArgument(src, end, line) {
|
|
329
|
+
const m = LITERAL_ARG.exec(src.slice(end));
|
|
330
|
+
if (m === null)
|
|
331
|
+
return { line, problem: NON_LITERAL };
|
|
332
|
+
return { line, specifier: m[1] ?? m[2] ?? m[3] ?? '' };
|
|
333
|
+
}
|
|
334
|
+
/** Raw-text scan: every keyword occurrence counts, including in comments and strings. */
|
|
335
|
+
export function scanWithRegex(src) {
|
|
336
|
+
const lineOf = lineIndex(src);
|
|
337
|
+
const out = [];
|
|
338
|
+
for (const m of src.matchAll(STATIC))
|
|
339
|
+
out.push({ line: lineOf(m.index), specifier: m[2] });
|
|
340
|
+
for (const m of src.matchAll(/\b(require|import|getBuiltinModule|createRequire|eval|Function)\b/g)) {
|
|
341
|
+
const word = m[1];
|
|
342
|
+
const end = m.index + word.length;
|
|
343
|
+
const after = src.slice(end);
|
|
344
|
+
const line = lineOf(m.index);
|
|
345
|
+
const before = src.slice(Math.max(0, m.index - 40), m.index);
|
|
346
|
+
if (word === 'require' || word === 'getBuiltinModule') {
|
|
347
|
+
const resolve = RESOLVE_CALL.exec(after);
|
|
348
|
+
if (CALL.test(after))
|
|
349
|
+
out.push(literalArgument(src, end, line));
|
|
350
|
+
else if (word === 'require' && resolve !== null)
|
|
351
|
+
out.push(literalArgument(src, end + resolve[0].length - 1, line));
|
|
352
|
+
else if (!/\btypeof\s*$/.test(before))
|
|
353
|
+
out.push({ line, problem: REQUIRE_VALUE });
|
|
354
|
+
}
|
|
355
|
+
else if (word === 'import') {
|
|
356
|
+
const meta = META_RESOLVE.exec(after);
|
|
357
|
+
if (CALL.test(after))
|
|
358
|
+
out.push(literalArgument(src, end, line));
|
|
359
|
+
else if (meta !== null)
|
|
360
|
+
out.push(literalArgument(src, end + meta[0].length, line));
|
|
361
|
+
}
|
|
362
|
+
else if (word === 'createRequire') {
|
|
363
|
+
const call = CREATE_REQUIRE_CALL.exec(after);
|
|
364
|
+
out.push(call === null ? { line, problem: REQUIRE_VALUE } : literalArgument(src, end + call[0].length, line));
|
|
365
|
+
}
|
|
366
|
+
else if (word === 'eval') {
|
|
367
|
+
if (!/\btypeof\s*$/.test(before))
|
|
368
|
+
out.push({ line, problem: EVAL });
|
|
369
|
+
}
|
|
370
|
+
else if (!/\binstanceof\s*$/.test(before) && !PROTOTYPE_AFTER.test(after)) {
|
|
371
|
+
out.push({ line, problem: FUNCTION_CTOR });
|
|
372
|
+
}
|
|
373
|
+
}
|
|
374
|
+
for (const m of src.matchAll(CONSTRUCTOR_ACCESS)) {
|
|
375
|
+
const after = src.slice(m.index + m[0].length);
|
|
376
|
+
const before = src.slice(Math.max(0, m.index - 200), m.index);
|
|
377
|
+
const compared = CONSTRUCTOR_OK_AFTER.test(after) || (/(?:===?|!==?)[\s\w$.]*$/.test(before) && CONSTRUCTOR_END.test(after));
|
|
378
|
+
if (!compared)
|
|
379
|
+
out.push({ line: lineOf(m.index), problem: CONSTRUCTOR });
|
|
380
|
+
}
|
|
381
|
+
for (const m of src.matchAll(PROCESS_MEMBER)) {
|
|
382
|
+
if (PROCESS_PROPS.has(m[1]))
|
|
383
|
+
out.push({ line: lineOf(m.index), problem: processProblem(m[1]) });
|
|
384
|
+
}
|
|
385
|
+
for (const m of src.matchAll(QUOTED_NAME)) {
|
|
386
|
+
if (!INDEX_OPEN.test(src.slice(Math.max(0, m.index - 40), m.index)))
|
|
387
|
+
out.push({ line: lineOf(m.index), problem: namedProblem(m[2]) });
|
|
388
|
+
}
|
|
389
|
+
for (const m of src.matchAll(COMPUTED_INDEX))
|
|
390
|
+
out.push({ line: lineOf(m.index), problem: computedProblem(m[1]) });
|
|
391
|
+
for (const m of src.matchAll(BINDING_CALL))
|
|
392
|
+
out.push({ line: lineOf(m.index), problem: processProblem('binding') });
|
|
393
|
+
for (const m of src.matchAll(/\b(_linkedBinding|dlopen|mainModule)\b/g))
|
|
394
|
+
out.push({ line: lineOf(m.index), problem: processProblem(m[1]) });
|
|
395
|
+
for (const m of src.matchAll(BARE_CONSTRUCTOR)) {
|
|
396
|
+
// `.constructor` and quoted forms are judged above; a class's `constructor(` method is fine.
|
|
397
|
+
const before = src.slice(Math.max(0, m.index - 40), m.index);
|
|
398
|
+
if (!/[.'"\x60]\s*$/.test(before) && !CALL.test(src.slice(m.index + m[0].length)))
|
|
399
|
+
out.push({ line: lineOf(m.index), problem: namedProblem('constructor') });
|
|
400
|
+
}
|
|
401
|
+
for (const m of src.matchAll(ALIAS_WORD)) {
|
|
402
|
+
const after = src.slice(m.index + m[0].length);
|
|
403
|
+
const before = src.slice(Math.max(0, m.index - 40), m.index);
|
|
404
|
+
if (!MEMBER_AFTER.test(after) && !/\btypeof\s*$/.test(before))
|
|
405
|
+
out.push({ line: lineOf(m.index), problem: aliasProblem(m[1]) });
|
|
406
|
+
}
|
|
407
|
+
for (const m of src.matchAll(/\barguments\b/g))
|
|
408
|
+
out.push({ line: lineOf(m.index), problem: ARGUMENTS });
|
|
409
|
+
for (const m of src.matchAll(RETURN_THIS))
|
|
410
|
+
out.push({ line: lineOf(m.index), problem: THIS_ESCAPE });
|
|
411
|
+
for (const m of src.matchAll(NETWORK_WORD))
|
|
412
|
+
out.push({ line: lineOf(m.index), problem: networkProblem((m[1] ?? m[2])) });
|
|
413
|
+
// Literal pieces joined with `+` count as one blob.
|
|
414
|
+
const joined = src.replace(/(['"\x60])\s*\+\s*\1/g, '');
|
|
415
|
+
const joinedLine = lineIndex(joined);
|
|
416
|
+
for (const m of joined.matchAll(BLOB_RUN))
|
|
417
|
+
out.push({ line: joinedLine(m.index), problem: OPAQUE });
|
|
418
|
+
return out;
|
|
419
|
+
}
|