kryptheon 0.1.42 → 0.1.44

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/kryptheon-code.js CHANGED
@@ -1,1353 +1,1879 @@
1
- // Reads a project's frontend code for one kind of mistake: text that may come
2
- // from outside the page - a server response, an error message, a value a user
3
- // typed - being handed to something that turns text into HTML.
4
- //
5
- // element.innerHTML = `<p>${data.name}</p>`
6
- //
7
- // If data.name holds "<img src=x onerror=...>", the browser runs it in the
8
- // page, with the page's session. Written as textContent, or escaped first, the
9
- // same value is just text.
10
- //
11
- // This is code analysis, never execution: nothing is run, nothing is sent, and
12
- // every finding is "verification required". A static read cannot see what a
13
- // value holds at run time, so it says where the risk is and how sure it is,
14
- // and leaves the verdict to a person or a later runtime check.
15
- //
16
- // Deliberately narrow, because a report that flags every innerHTML in an app
17
- // is a report nobody reads twice:
18
- // - a sink fed only literal text is safe and never reported;
19
- // - a value wrapped in an escaping or sanitising call is safe;
20
- // - a value that can only be a number is safe;
21
- // - everything else is reported, and ranked by where it came from.
22
- //
23
- // The parser is the one Playwright already ships, so this adds no dependency.
24
- // It is an internal file of Playwright's, not a public API; if a later
25
- // Playwright moves it, this says it could not run - it never says "passed".
26
-
27
- const fs = require('fs');
28
- const path = require('path');
29
- const keys = require('./kryptheon-keys.js');
30
-
31
- const SKIP_DIRS = new Set([
32
- 'node_modules', '.git', 'dist', 'build', 'out', '.next', '.nuxt', '.svelte-kit',
33
- 'coverage', 'vendor', '.vercel', '.netlify', '.turbo', '.cache', 'tests', 'test-results',
34
- ]);
35
- const CODE_EXT = /\.(js|mjs|cjs|jsx|ts|tsx)$/i;
36
- const PAGE_EXT = /\.(html|htm|vue|svelte)$/i;
37
- const MAX_BYTES = 800 * 1024;
38
-
39
- // A call whose name says it makes text safe for HTML. Matched on the called
40
- // name only - escapeHtml(x), DOMPurify.sanitize(x), he.encode(x).
41
- const MAKES_SAFE = /^(escape\w*|\w*escape|sanitize\w*|sanitise\w*|\w*sanitize|purify|encode\w*|\w*encode|htmlEncode|safeHtml|clean(Html)?|textToHtml)$/i;
42
-
43
- // Calls and properties whose result can only be a number, a boolean, or a
44
- // formatted number/date - nothing that can carry a tag.
45
- const NUMERIC_CALLS = /^(Number|parseInt|parseFloat|Boolean|isNaN|isFinite|toFixed|toPrecision|toLocaleString|toLocaleDateString|toLocaleTimeString|getTime|getFullYear|getMonth|getDate|getDay|getHours|getMinutes|getSeconds|round|floor|ceil|abs|min|max|indexOf|findIndex|size)$/;
46
- const NUMERIC_PROPS = /^(length|size|count|total|id|index|width|height|top|left|x|y)$/;
47
-
48
- /** Every file worth reading, relative paths, skipping what is not the app's source. */
49
- function listFiles(root) {
50
- const out = [];
51
- (function walk(dir) {
52
- let entries;
53
- try {
54
- entries = fs.readdirSync(dir, { withFileTypes: true });
55
- } catch (err) {
56
- return;
57
- }
58
- for (const entry of entries) {
59
- if (entry.name.startsWith('.') && entry.name !== '.') {
60
- if (entry.isDirectory()) continue;
61
- }
62
- const full = path.join(dir, entry.name);
63
- if (entry.isDirectory()) {
64
- if (!SKIP_DIRS.has(entry.name)) walk(full);
65
- } else if ((CODE_EXT.test(entry.name) || PAGE_EXT.test(entry.name)) && !/\.min\.js$/i.test(entry.name)) {
66
- out.push(full);
67
- }
68
- }
69
- })(root);
70
- return out.sort();
71
- }
72
-
73
- /** The parser, or null when this Playwright does not have it where expected. */
74
- function loadParser(packageDir) {
75
- const candidates = [];
76
- try {
77
- candidates.push(path.join(path.dirname(require.resolve('playwright/package.json', { paths: [packageDir] })), 'lib', 'transform', 'babelBundle.js'));
78
- } catch (err) {
79
- /* not resolvable from here */
80
- }
81
- candidates.push(path.join(packageDir, 'node_modules', 'playwright', 'lib', 'transform', 'babelBundle.js'));
82
- for (const file of candidates) {
83
- try {
84
- const bundle = require(file);
85
- if (typeof bundle.babelParse === 'function' && typeof bundle.traverse === 'function') return bundle;
86
- } catch (err) {
87
- /* try the next */
88
- }
89
- }
90
- return null;
91
- }
92
-
93
- /** Inline <script> blocks of a page, with the line each one starts on. */
94
- function scriptsIn(source) {
95
- const blocks = [];
96
- const re = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
97
- let m;
98
- while ((m = re.exec(source))) {
99
- const attrs = m[1] || '';
100
- if (/\bsrc\s*=/.test(attrs)) continue;
101
- if (/type\s*=\s*["']?(application\/(ld\+)?json|text\/template|importmap)/i.test(attrs)) continue;
102
- const before = source.slice(0, m.index + m[0].indexOf('>') + 1);
103
- blocks.push({ code: m[2], line: before.split('\n').length });
104
- }
105
- return blocks;
106
- }
107
-
108
- /** v-html="..." in a template: always a sink, safe only when the value is quoted text. */
109
- function vHtmlIn(source) {
110
- const found = [];
111
- const re = /\bv-html\s*=\s*"([^"]*)"/g;
112
- let m;
113
- while ((m = re.exec(source))) {
114
- const value = m[1].trim();
115
- if (/^'[^']*'$/.test(value)) continue;
116
- found.push({ line: source.slice(0, m.index).split('\n').length, expression: value });
117
- }
118
- return found;
119
- }
120
-
121
- function calleeName(node) {
122
- if (!node) return '';
123
- if (node.type === 'Identifier') return node.name;
124
- if (node.type === 'MemberExpression' && !node.computed && node.property) return node.property.name || '';
125
- return '';
126
- }
127
-
128
- /**
129
- * Where a value comes from, as far as the code shows.
130
- * 'safe' - literal text, a number, or made safe by an escaping call
131
- * 'network' - read from a response body (.json()), so a server wrote it
132
- * 'error' - an error's message, which often carries text a server sent
133
- * 'unknown' - anything else: it may be fine, the code alone cannot say
134
- */
135
- // How far one value is followed back before giving up and calling it unknown.
136
- // It only exists to stop a loop - a function that returns itself, a name that
137
- // feeds another. It was 6, which a constant-only lookup (a template, a call,
138
- // its return, a map of maps) used up before reaching the strings at the
139
- // bottom, so a harmless label came back "unknown". Giving up always errs
140
- // towards reporting, never towards silence. It was 12 until a blind test
141
- // (Northstar): a helper's parameter, back to its call inside a map() callback,
142
- // to the list, a slice of a list reassigned from a filter of the fixed one -
143
- // 13 steps. 18 leaves room for one more layer of the same.
144
- const MAX_DEPTH = 18;
145
-
146
- function classify(node, scope, code, depth, aliases) {
147
- if (!node || depth > MAX_DEPTH) return 'unknown';
148
- const again = (n) => classify(n, scope, code, depth + 1, aliases);
149
- switch (node.type) {
150
- case 'StringLiteral':
151
- case 'NumericLiteral':
152
- case 'BooleanLiteral':
153
- case 'NullLiteral':
154
- return 'safe';
155
- case 'TemplateLiteral':
156
- return worst(judgedParts(node, scope, code).map((e) => again(e)));
157
- case 'BinaryExpression':
158
- if (node.operator !== '+') return 'safe'; // - * / % comparisons: never text
159
- return worst(judgedParts(node, scope, code).map((e) => again(e)));
160
- case 'UnaryExpression':
161
- case 'UpdateExpression':
162
- return 'safe';
163
- case 'ConditionalExpression':
164
- return worst([again(node.consequent), again(node.alternate)]);
165
- case 'LogicalExpression':
166
- return worst([again(node.left), again(node.right)]);
167
- case 'CallExpression':
168
- case 'OptionalCallExpression': {
169
- const name = calleeName(node.callee);
170
- if (MAKES_SAFE.test(name)) return 'safe';
171
- if (readsResponseBody(node)) return 'network';
172
- if (NUMERIC_CALLS.test(name)) return 'safe';
173
- if (node.callee.type === 'MemberExpression' && node.callee.object && node.callee.object.name === 'Math') return 'safe';
174
- // items.map(i => `<li>${i.name}</li>`).join('') - judge what map builds.
175
- const mapped = mapCallback(node, scope, code, depth, aliases);
176
- if (mapped) {
177
- return mapped.returns.length
178
- ? worst(mapped.returns.map((r) => classify(r.node, r.scope, code, depth + 1, mapped.inner)))
179
- : 'unknown';
180
- }
181
- // An escaping helper of this file's own, known by what it does. Inside a
182
- // template, one that leaves quotes alone does not protect a value that
183
- // lands in an attribute - the template judges that case itself.
184
- if (escaperOf(node, scope, code)) return 'safe';
185
- // A function of this file's own: as dangerous as what it returns. One
186
- // that only ever returns constants - a lookup of labels, icons and
187
- // colours - cannot carry anything in; one that returns a parameter
188
- // stays unknown, because its parameters are.
189
- const local = node.callee.type === 'Identifier' ? localFunction(node.callee.name, scope) : null;
190
- if (local) {
191
- const returns = returnsOf(local);
192
- if (returns.length) return worst(returns.map((r) => classify(r.node, r.scope, code, depth + 1, aliases)));
193
- }
194
- // String methods pass through whatever they were called on, and so do
195
- // the array methods that only pick or reorder items: notes.filter(...)
196
- // holds the same notes.
197
- if (/^(trim|toUpperCase|toLowerCase|slice|substring|substr|replace|replaceAll|padStart|padEnd|concat|toString|join|filter|sort|reverse|flat|toSorted|toReversed)$/.test(name) &&
198
- node.callee.type === 'MemberExpression') {
199
- return again(node.callee.object);
200
- }
201
- return 'unknown';
202
- }
203
- case 'ObjectExpression':
204
- // Only as dangerous as what is in it. A spread brings in whatever it spreads.
205
- return worst(node.properties.map((p) => (p.type === 'SpreadElement' ? again(p.argument) : p.value && again(p.value))));
206
- case 'ArrayExpression':
207
- return worst(node.elements.map((e) => (e ? again(e.type === 'SpreadElement' ? e.argument : e) : 'safe')));
208
- case 'MemberExpression':
209
- case 'OptionalMemberExpression': {
210
- const prop = node.property && !node.computed ? node.property.name : '';
211
- // The page's own markup, read back: button.innerHTML saved and put back
212
- // adds nothing that was not already there. textContent is not this - it
213
- // is text, and a "<" in it becomes a tag when written as HTML.
214
- if (prop === 'innerHTML' || prop === 'outerHTML') return 'safe';
215
- if (NUMERIC_PROPS.test(prop || '')) return 'safe';
216
- if (prop === 'message' && isCatchParam(node.object, scope)) return 'error';
217
- // labels().title - a property of what a call returns is judged by the
218
- // call; (await res.json()).name by the body it was read from.
219
- let base = node.object;
220
- while (base && /MemberExpression$/.test(base.type)) base = base.object;
221
- if (base && (/CallExpression$/.test(base.type) || base.type === 'AwaitExpression')) return again(base);
222
- return fromBinding(rootIdentifier(node), scope, code, depth, aliases);
223
- }
224
- case 'Identifier':
225
- return fromBinding(node, scope, code, depth, aliases);
226
- case 'AwaitExpression':
227
- return again(node.argument);
228
- default:
229
- return 'unknown';
230
- }
231
- }
232
-
233
- const RANK = { safe: 0, unknown: 1, error: 2, network: 3 };
234
- function worst(list) {
235
- return (list || []).reduce((a, b) => (RANK[b] > RANK[a] ? b : a), 'safe');
236
- }
237
-
238
- function returnedBy(fn) {
239
- if (!fn || !/Function/.test(fn.type)) return null;
240
- if (fn.body.type !== 'BlockStatement') return fn.body;
241
- const ret = fn.body.body.find((s) => s.type === 'ReturnStatement');
242
- return ret ? ret.argument : null;
243
- }
244
-
245
- /** The path of a function this file declares under `name`, or null. */
246
- function localFunction(name, scope) {
247
- const binding = scope && scope.getBinding(name);
248
- if (!binding || !binding.path) return null;
249
- const p = binding.path;
250
- if (p.node.type === 'FunctionDeclaration') return p;
251
- if (p.node.type === 'VariableDeclarator' && p.node.init && /Function/.test(p.node.init.type) &&
252
- !(binding.constantViolations && binding.constantViolations.length)) {
253
- return p.get('init');
254
- }
255
- return null;
256
- }
257
-
258
- /** Every value a function returns, with the scope to judge it in; nested functions excluded. */
259
- function returnsOf(fnPath) {
260
- if (fnPath.node.body.type !== 'BlockStatement') return [{ node: fnPath.node.body, scope: fnPath.scope }];
261
- const found = [];
262
- fnPath.traverse({
263
- Function(p) {
264
- p.skip();
265
- },
266
- ReturnStatement(p) {
267
- if (p.node.argument) found.push({ node: p.node.argument, scope: p.scope });
268
- },
269
- });
270
- return found;
271
- }
272
-
273
- // Every function in the piece being read, by node, so a callback handed to
274
- // map() can be judged in its own scope - where its own `const color = ...`
275
- // lives - instead of the caller's, where that name means nothing.
276
- let FN_PATHS = new WeakMap();
277
-
278
- /**
279
- * list.map(cb).join(''): the callback's returns, each with its own scope, and
280
- * what the callback's names stand for - the item is whatever the list holds,
281
- * the index is a number. Null when node is not that shape.
282
- */
283
- function mapCallback(node, scope, code, depth, aliases) {
284
- if (calleeName(node.callee) !== 'join' || !node.callee.object || !/CallExpression$/.test(node.callee.object.type) ||
285
- calleeName(node.callee.object.callee) !== 'map') {
286
- return null;
287
- }
288
- const mapCall = node.callee.object;
289
- const fn = mapCall.arguments[0];
290
- const listOrigin = classify(mapCall.callee.object, scope, code, depth + 1, aliases);
291
- const inner = Object.assign({}, aliases || {});
292
- const params = (fn && fn.params) || [];
293
- if (params[0] && params[0].type === 'Identifier') inner[params[0].name] = listOrigin;
294
- if (params[1] && params[1].type === 'Identifier') inner[params[1].name] = 'safe';
295
- const fnPath = fn && FN_PATHS.get(fn);
296
- const returns = fnPath
297
- ? returnsOf(fnPath)
298
- : (returnedBy(fn) ? [{ node: returnedBy(fn), scope: scope }] : []);
299
- return { returns: returns, inner: inner };
300
- }
301
-
302
- /**
303
- * Whether a call escapes HTML - by name for the well-known ones, and for a
304
- * helper of this file's own, by what it does: every return is a replace()
305
- * chain, its patterns cover & < and >, and it writes &amp; &lt; &gt;. The
306
- * name decides nothing - `esc` and `clean3` count, and an "escape" that only
307
- * handles "<", or escapes and then returns the original, does not.
308
- * Returns { dq, sq }: whether " and ' are escaped too. Null when it does not escape.
309
- */
310
- function escaperOf(call, scope, code) {
311
- if (!call || !/CallExpression$/.test(call.type)) return null;
312
- const name = calleeName(call.callee);
313
- if (MAKES_SAFE.test(name)) return { dq: true, sq: true };
314
- if (call.callee.type !== 'Identifier') return null;
315
- const fnPath = localFunction(call.callee.name, scope);
316
- if (!fnPath) return null;
317
- const returns = returnsOf(fnPath);
318
- if (!returns.length || !returns.every((r) => /CallExpression$/.test(r.node.type) &&
319
- /^(replace|replaceAll)$/.test(calleeName(r.node.callee)))) {
320
- return null;
321
- }
322
- let patterns = '';
323
- const written = [];
324
- fnPath.traverse({
325
- RegExpLiteral(p) {
326
- patterns += p.node.pattern;
327
- },
328
- StringLiteral(p) {
329
- written.push(p.node.value);
330
- const parent = p.parent;
331
- if (parent && /CallExpression$/.test(parent.type) && parent.arguments[0] === p.node &&
332
- /^(replace|replaceAll)$/.test(calleeName(parent.callee))) {
333
- patterns += p.node.value;
334
- }
335
- },
336
- });
337
- const writes = (entity) => written.some((s) => s.indexOf(entity) !== -1);
338
- if (!/&/.test(patterns) || !/</.test(patterns) || !/>/.test(patterns)) return null;
339
- if (!writes('&amp;') || !writes('&lt;') || !writes('&gt;')) return null;
340
- return {
341
- dq: /"/.test(patterns) && (writes('&quot;') || writes('&#34;') || writes('&#x22;')),
342
- sq: /'/.test(patterns) && (writes('&#39;') || writes('&#x27;') || writes('&apos;')),
343
- };
344
- }
345
-
346
- /**
347
- * The quote an HTML attribute value is open in at the end of this text: '"',
348
- * "'", 'bare' for an unquoted one, '' when the text is not inside a tag at all.
349
- * Only inside a tag - after a "<" that no ">" has closed - is an "=" an
350
- * attribute; the "=" of "/go?next=" in a URL string is not one.
351
- */
352
- function openAttribute(text) {
353
- const lt = text.lastIndexOf('<');
354
- if (lt === -1 || text.lastIndexOf('>') > lt) return '';
355
- const tag = text.slice(lt);
356
- const quoted = /=\s*(["'])[^"']*$/.exec(tag);
357
- if (quoted) return quoted[1];
358
- return /\s[^\s"'<>\/=]+\s*=\s*$/.test(tag) ? 'bare' : '';
359
- }
360
-
361
- /**
362
- * The pieces of a template or a + concatenation to judge one by one. An
363
- * escaped value is judged as its escaped input when the escaping is not
364
- * enough for where it lands: inside a "..." attribute that needs " escaped,
365
- * inside '...' that needs ' escaped, and an unquoted attribute is broken by a
366
- * space no escaper touches.
367
- */
368
- function judgedParts(node, scope, code) {
369
- const pairs = [];
370
- if (node.type === 'TemplateLiteral') {
371
- // Everything written before this value, so an attribute opened in an
372
- // earlier piece - `<a title="${a}" href="${b}"` - is still seen as open.
373
- let before = '';
374
- node.expressions.forEach((e, i) => {
375
- before += node.quasis[i].value.raw;
376
- pairs.push({ before: before, value: e });
377
- before += 'x';
378
- });
379
- } else {
380
- const text = (n) => (n.type === 'StringLiteral' ? n.value
381
- : n.type === 'TemplateLiteral' ? n.quasis[n.quasis.length - 1].value.raw : '');
382
- pairs.push({ before: '', value: node.left });
383
- pairs.push({ before: text(node.left), value: node.right });
384
- }
385
- return pairs.map(({ before, value }) => {
386
- const esc = escaperOf(value, scope, code);
387
- if (!esc) return value;
388
- const quote = openAttribute(before);
389
- const enough = quote === '' || (quote === '"' && esc.dq) || (quote === "'" && esc.sq);
390
- return enough ? { type: 'StringLiteral' } : (value.arguments[0] || value);
391
- });
392
- }
393
-
394
- /**
395
- * Which parts of a value make it unsafe, in the words of the code - so a fix
396
- * prompt can say "only ${log.caller_number}" instead of quoting sixty lines of
397
- * template and leaving the reader to find it. At most five, never repeated.
398
- */
399
- function riskyParts(node, scope, code, aliases, out, depth) {
400
- if (!node || out.length >= 5 || depth > MAX_DEPTH) return;
401
- const origin = classify(node, scope, code, 0, aliases);
402
- if (origin === 'safe') return;
403
- const go = (n, s, a) => riskyParts(n, s || scope, code, a || aliases, out, depth + 1);
404
- if (node.type === 'TemplateLiteral' || (node.type === 'BinaryExpression' && node.operator === '+')) {
405
- judgedParts(node, scope, code).forEach((p) => go(p));
406
- return;
407
- }
408
- if (node.type === 'ConditionalExpression') { go(node.consequent); go(node.alternate); return; }
409
- if (node.type === 'LogicalExpression') { go(node.left); go(node.right); return; }
410
- if (/CallExpression$/.test(node.type)) {
411
- const mapped = mapCallback(node, scope, code, depth, aliases);
412
- if (mapped && mapped.returns.length) {
413
- mapped.returns.forEach((r) => go(r.node, r.scope, mapped.inner));
414
- return;
415
- }
416
- }
417
- const text = code.slice(node.start, node.end).replace(/\s+/g, ' ').slice(0, 80);
418
- if (!out.some((p) => p.text === text)) out.push({ text: text, origin: origin, line: node.loc ? node.loc.start.line : null });
419
- }
420
-
421
- function rootIdentifier(node) {
422
- let n = node;
423
- while (n && /MemberExpression$/.test(n.type)) n = n.object;
424
- return n && n.type === 'Identifier' ? n : null;
425
- }
426
-
427
- function isCatchParam(node, scope) {
428
- const id = rootIdentifier(node) || (node && node.type === 'Identifier' ? node : null);
429
- if (!id || !scope) return false;
430
- const binding = scope.getBinding(id.name);
431
- return !!(binding && binding.path && binding.path.type === 'CatchClause');
432
- }
433
-
434
- // Bindings whose values are being followed right now, so a variable assigned
435
- // from itself (count = count + 1) is not followed round in a circle.
436
- const RESOLVING = new Set();
437
-
438
- // The project being read, for a value imported from another of its files:
439
- // where each file's names lead, and which of them anything ever writes to.
440
- // Set by scanProject for the length of one read, like FN_PATHS.
441
- let IMPORTS = null;
442
- // Which file each parsed program is, so an import is resolved from the file
443
- // that wrote it - which, once a helper in another folder is being judged, is
444
- // not the file the sink is in.
445
- let PROGRAM_FILE = new WeakMap();
446
-
447
- /**
448
- * Fixed data another file of the project exports - `export const demo = {...}`
449
- * of nothing but literals - is as safe as those literals, and only while no
450
- * file writes to it. Found on a blind test (LaunchRail): mock-data.js exported
451
- * the demo workspace, ui.js rendered it through a shell() helper, and the
452
- * import was read as unknown - so a safe page was reported.
453
- *
454
- * What is followed, and what is not:
455
- * - a named import of a `const` declared at the top of a project file;
456
- * - nothing at all if any file of the project could not be read, since a
457
- * write could be in that file (IMPORTS.blind);
458
- * - a write anywhere - through the import, any other file's import of it,
459
- * a namespace import, a local name given to part of it, or the defining
460
- * file itself - makes it unknown again (IMPORTS.written).
461
- * Handing it out - `return demo.flags` - is a read, and is not followed into
462
- * whoever receives it. That is the one place a write could still be missed: a
463
- * caller that pushes into the very list it was returned. Writing into shared
464
- * fixed data that way is rare enough to accept here, and is said so.
465
- */
466
- function fromImport(binding, depth) {
467
- if (!IMPORTS || IMPORTS.blind) return 'unknown';
468
- const spec = binding.path && binding.path.node;
469
- if (!spec || spec.type !== 'ImportSpecifier') return 'unknown';
470
- const program = binding.scope && binding.scope.getProgramParent();
471
- const here = program && PROGRAM_FILE.get(program.block);
472
- if (!here) return 'unknown';
473
- const decl = binding.path.parentPath && binding.path.parentPath.node;
474
- const from = decl && decl.source && decl.source.value;
475
- const name = spec.imported && (spec.imported.name || spec.imported.value);
476
- const found = from && name ? IMPORTS.constOf(here, from, name) : null;
477
- if (!found) return 'unknown';
478
- if (IMPORTS.written.has(found.full + '::' + name) || IMPORTS.written.has(found.full + '::*')) return 'unknown';
479
- return classify(found.init, found.scope, found.code, depth + 1);
480
- }
481
-
482
- /** What a name was set to, followed one step back when that says anything. */
483
- function fromBinding(id, scope, code, depth, aliases) {
484
- if (id && aliases && Object.prototype.hasOwnProperty.call(aliases, id.name)) return aliases[id.name];
485
- if (!id || !scope) return 'unknown';
486
- const binding = scope.getBinding(id.name);
487
- if (!binding) return 'unknown';
488
- if (binding.path && binding.path.type === 'CatchClause') return 'error';
489
- if (binding.kind === 'param') return fromCallback(binding, code, depth) || fromCalls(binding, code, depth);
490
- if (binding.kind === 'module') return fromImport(binding, depth);
491
- const init = binding.path && binding.path.node && binding.path.node.init;
492
- const later = binding.constantViolations || [];
493
- if (!init && !later.length) return 'unknown';
494
- if (init && readsResponseBody(init)) return 'network';
495
- // Reassigned later: as dangerous as the worst value it is ever given. Found
496
- // on a blind test: `let notes = []`, then `notes = data` from the database,
497
- // then rendered - read as "unknown" because the first value was an empty
498
- // list. Only plain `=` and `+=` are followed; anything else - a destructure,
499
- // a for-of - stays unknown, because what it assigns is not in one place.
500
- if (later.length) {
501
- if (RESOLVING.has(binding)) return 'safe'; // x = x + 1: itself adds nothing new
502
- RESOLVING.add(binding);
503
- try {
504
- const origins = [];
505
- if (init) origins.push(classify(init, binding.path.scope, code, depth + 1, aliases));
506
- for (const v of later) {
507
- const node = v.node;
508
- if (node.type === 'UpdateExpression') continue; // x++ holds a number
509
- if (node.type !== 'AssignmentExpression' || node.left.type !== 'Identifier' ||
510
- (node.operator !== '=' && node.operator !== '+=')) return 'unknown';
511
- origins.push(classify(node.right, v.scope, code, depth + 1, aliases));
512
- }
513
- return worst(origins);
514
- } finally {
515
- RESOLVING.delete(binding);
516
- }
517
- }
518
- // Destructured from a response body: const { name } = await res.json()
519
- // Aliases carry through: inside a map() callback, `const t = r.title` is as
520
- // dangerous as the item r it was read from.
521
- return classify(init, binding.path.scope, code, depth + 1, aliases);
522
- }
523
-
524
- // Array methods that hand their callback the list's own items.
525
- const ITEM_CALLBACKS = /^(map|forEach|filter|find|findLast|findIndex|findLastIndex|some|every|flatMap|sort|toSorted)$/;
526
-
527
- /**
528
- * A parameter of a callback handed to list.map(...) and its kin: the item is
529
- * whatever the list holds, the index a number, the third the list itself.
530
- * Null when the parameter is not that.
531
- *
532
- * Found on a blind test (Northstar): pageRows.map(row => `...${severityClass(row.severity)}...`).
533
- * The helper's parameter was followed to its call, and there `row` was a
534
- * parameter of an arrow nobody names - "unknown" - though pageRows only ever
535
- * held the file's own fixed list. The map().join() reading knew what row was;
536
- * a name followed back into the same callback did not.
537
- */
538
- function fromCallback(binding, code, depth) {
539
- const fn = binding.path && binding.path.parentPath;
540
- if (!fn || !/Function/.test(fn.node.type)) return null;
541
- const call = fn.parentPath;
542
- if (!call || !/CallExpression$/.test(call.node.type) || call.node.arguments[0] !== fn.node) return null;
543
- const method = calleeName(call.node.callee);
544
- if (!/MemberExpression$/.test(call.node.callee.type) || !ITEM_CALLBACKS.test(method)) return null;
545
- const index = fn.node.params.indexOf(binding.path.node);
546
- const list = () => classify(call.node.callee.object, call.scope, code, depth + 1);
547
- if (index === 0 || (index === 1 && /^(sort|toSorted)$/.test(method))) return list();
548
- if (index === 1) return 'safe';
549
- if (index === 2) return list();
550
- return null;
551
- }
552
-
553
- /**
554
- * A parameter is as dangerous as the worst thing any call passes it. Every
555
- * use of the function has to be a call this file makes: one handed on as a
556
- * value - a callback, an export, an event handler - is called from somewhere
557
- * the code does not show, so its parameter stays unknown.
558
- */
559
- function fromCalls(binding, code, depth) {
560
- const fn = binding.path && binding.path.parentPath;
561
- if (!fn || !/Function/.test(fn.node.type)) return 'unknown';
562
- const index = fn.node.params.indexOf(binding.path.node);
563
- if (index === -1) return 'unknown';
564
- let name = fn.node.id && fn.node.id.name;
565
- if (!name && fn.parentPath && fn.parentPath.node.type === 'VariableDeclarator' && fn.parentPath.node.id.type === 'Identifier') {
566
- name = fn.parentPath.node.id.name;
567
- }
568
- const fnBinding = name && fn.parentPath && fn.parentPath.scope.getBinding(name);
569
- if (!fnBinding || (fnBinding.constantViolations && fnBinding.constantViolations.length)) return 'unknown';
570
- const refs = fnBinding.referencePaths || [];
571
- if (!refs.length) return 'unknown';
572
- const origins = [];
573
- for (const ref of refs) {
574
- const call = ref.parent;
575
- if (!call || !/CallExpression$/.test(call.type) || call.callee !== ref.node) return 'unknown';
576
- const arg = call.arguments[index];
577
- if (!arg) {
578
- origins.push('safe'); // not passed: undefined
579
- continue;
580
- }
581
- if (call.arguments.slice(0, index + 1).some((a) => a.type === 'SpreadElement')) return 'unknown';
582
- origins.push(classify(arg, ref.scope, code, depth + 1));
583
- }
584
- return worst(origins);
585
- }
586
-
587
- function readsResponseBody(node) {
588
- let n = node;
589
- if (n && n.type === 'AwaitExpression') n = n.argument;
590
- if (!n || !/CallExpression$/.test(n.type)) return false;
591
- const name = calleeName(n.callee);
592
- if (name === 'json' || name === 'text') return true;
593
- // res.json().catch(() => ({})) - the body read, with a fallback for when it
594
- // is not JSON. Still the server's words whenever it is.
595
- if ((name === 'catch' || name === 'finally') && n.callee.type === 'MemberExpression') {
596
- return readsResponseBody(n.callee.object);
597
- }
598
- // (await fetch(url)).json() and fetch(url).then(r => r.json())
599
- if (name === 'then') return (n.arguments || []).some((fn) => {
600
- const body = returnedBy(fn);
601
- return body && readsResponseBody(body);
602
- });
603
- // Found on a blind test: const { data } = await supabase.from('notes')
604
- // .select(...) is rows straight from the database, and was judged "unknown".
605
- if (queriesSupabase(n)) return true;
606
- // axios.get(url) - its .data is the server's body.
607
- const callee = n.callee;
608
- if (callee.type === 'Identifier' && callee.name === 'axios') return true;
609
- if (callee.type === 'MemberExpression' && callee.object.type === 'Identifier' && callee.object.name === 'axios' &&
610
- /^(get|post|put|patch|delete|head|request)$/.test(calleeName(callee))) return true;
611
- return false;
612
- }
613
-
614
- // What a Supabase query chain does after .from('table'). Required, so that
615
- // Array.from(x) or somebody's own .from() is not read as the database.
616
- const QUERY_STEPS = /^(select|insert|update|upsert|delete|eq|neq|gt|gte|lt|lte|like|ilike|is|in|contains|containedBy|match|filter|or|not|order|limit|range|single|maybeSingle|textSearch|csv|throwOnError|returns|abortSignal)$/;
617
-
618
- /** supabase.from('notes').select(...)... or supabase.rpc('fn', ...). */
619
- function queriesSupabase(node) {
620
- let c = node;
621
- while (c && /CallExpression$/.test(c.type) && c.callee && /MemberExpression$/.test(c.callee.type)) {
622
- const step = calleeName(c.callee);
623
- const inner = c.callee.object;
624
- if (step === 'rpc' && c.arguments[0] && /StringLiteral|TemplateLiteral/.test(c.arguments[0].type)) return true;
625
- if (QUERY_STEPS.test(step) && inner && /CallExpression$/.test(inner.type) && calleeName(inner.callee) === 'from' &&
626
- inner.callee.type === 'MemberExpression' && inner.arguments[0] &&
627
- /StringLiteral|TemplateLiteral/.test(inner.arguments[0].type)) return true;
628
- c = inner;
629
- }
630
- return false;
631
- }
632
-
633
- /**
634
- * When the value is a parameter of the function it sits in - a helper such as
635
- * setStatus(html) { box.innerHTML = html } - which function, and which place
636
- * in its argument list. Null for anything else.
637
- */
638
- function paramOf(value, scope) {
639
- if (!value || value.type !== 'Identifier' || !scope) return null;
640
- const binding = scope.getBinding(value.name);
641
- if (!binding || binding.kind !== 'param' || !binding.path) return null;
642
- const fn = binding.path.parentPath;
643
- if (!fn || !/Function/.test(fn.node.type)) return null;
644
- const index = fn.node.params.indexOf(binding.path.node);
645
- if (index === -1) return null;
646
- let name = fn.node.id && fn.node.id.name;
647
- if (!name && fn.parentPath && fn.parentPath.node.type === 'VariableDeclarator' && fn.parentPath.node.id.type === 'Identifier') {
648
- name = fn.parentPath.node.id.name;
649
- }
650
- return name ? { fn: name, index: index } : null;
651
- }
652
-
653
- /** Everything in one piece of code that turns a non-literal value into HTML. */
654
- /* -------------------------- open redirects -------------------------- */
655
- //
656
- // Found on a blind test: after signing in, the page sent the browser to
657
- // new URLSearchParams(location.search).get('next') - wherever a link said.
658
- // A phishing link then lands someone on the attacker's page straight from
659
- // the real login, and a javascript: value runs in the page. Reported only
660
- // when the address is taken from the page's own URL, and not when the code
661
- // checks it first: a redirect to a fixed page is the feature.
662
-
663
- /** location, window.location, document.location. */
664
- function isLocation(node) {
665
- if (!node) return false;
666
- if (node.type === 'Identifier') return node.name === 'location';
667
- return node.type === 'MemberExpression' && !node.computed && node.property.name === 'location' &&
668
- node.object.type === 'Identifier' && /^(window|document|self|top)$/.test(node.object.name);
669
- }
670
-
671
- /** Is this address taken from the page's own URL, from its start? */
672
- function readsUrl(node, scope, depth) {
673
- if (!node || depth > 8) return false;
674
- const again = (n) => readsUrl(n, scope, depth + 1);
675
- switch (node.type) {
676
- case 'MemberExpression':
677
- case 'OptionalMemberExpression': {
678
- const prop = !node.computed && node.property ? node.property.name : '';
679
- if ((prop === 'search' || prop === 'hash') && isLocation(node.object)) return true;
680
- if (prop === 'referrer' && node.object.type === 'Identifier' && node.object.name === 'document') return true;
681
- // Next's pages router: router.query.next
682
- let base = node.object;
683
- while (base && /MemberExpression$/.test(base.type)) {
684
- if (!base.computed && base.property.name === 'query' && base.object.type === 'Identifier' && base.object.name === 'router') return true;
685
- base = base.object;
686
- }
687
- return false;
688
- }
689
- case 'CallExpression':
690
- case 'OptionalCallExpression': {
691
- const name = calleeName(node.callee);
692
- if (name === 'get' && /MemberExpression$/.test(node.callee.type)) {
693
- const params = node.callee.object;
694
- if (params.type === 'NewExpression' && params.callee.name === 'URLSearchParams') return true;
695
- if (/MemberExpression$/.test(params.type) && !params.computed && params.property.name === 'searchParams') return true;
696
- if (params.type === 'Identifier' && scope) {
697
- const b = scope.getBinding(params.name);
698
- const init = b && b.path && b.path.node && b.path.node.init;
699
- if (init && init.type === 'NewExpression' && init.callee.name === 'URLSearchParams') return true;
700
- if (init && /MemberExpression$/.test(init.type) && !init.computed && init.property.name === 'searchParams') return true;
701
- // Next and React Router: const params = useSearchParams(), or
702
- // const [params] = useSearchParams().
703
- if (init && /CallExpression$/.test(init.type) && calleeName(init.callee) === 'useSearchParams') return true;
704
- }
705
- return false;
706
- }
707
- if (/^(decodeURIComponent|decodeURI|String)$/.test(name) && node.callee.type === 'Identifier') return again(node.arguments[0]);
708
- if (/^(trim|toString|slice|substring)$/.test(name) && /MemberExpression$/.test(node.callee.type)) return again(node.callee.object);
709
- return false; // anything else - isSafeUrl(x), sanitize(x) - is somebody's check
710
- }
711
- case 'LogicalExpression':
712
- return again(node.left) || again(node.right);
713
- case 'ConditionalExpression':
714
- return again(node.consequent) || again(node.alternate);
715
- case 'TemplateLiteral':
716
- // `login.html?next=${x}` starts somewhere fixed; `${x}` does not.
717
- return node.quasis[0].value.cooked === '' && node.expressions.length > 0 && again(node.expressions[0]);
718
- case 'BinaryExpression':
719
- return node.operator === '+' && again(node.left);
720
- case 'AwaitExpression':
721
- return again(node.argument);
722
- case 'Identifier': {
723
- const b = scope && scope.getBinding(node.name);
724
- if (!b || !b.path || b.kind === 'param') return false;
725
- const values = [];
726
- if (b.path.node && b.path.node.init) values.push(b.path.node.init);
727
- for (const v of b.constantViolations || []) if (v.node.type === 'AssignmentExpression') values.push(v.node.right);
728
- return values.some((v) => readsUrl(v, b.path.scope, depth + 1));
729
- }
730
- default:
731
- return false;
732
- }
733
- }
734
-
735
- /**
736
- * Does the code check this name before sending the browser there? Any `if`
737
- * or `? :` around the redirect, or an earlier `if` in the same block, whose
738
- * test mentions it - an allow-list, a startsWith('/'), an origin compare.
739
- */
740
- function checkedFirst(p, value, code) {
741
- if (!value || value.type !== 'Identifier') return false;
742
- const word = new RegExp('\\b' + value.name.replace(/\$/g, '\\$') + '\\b');
743
- // A test that only asks whether there is a value - if (next) - checks
744
- // nothing about where it goes. It has to compare or match something.
745
- const VALIDATES = /startsWith|endsWith|\.test\(|includes|indexOf|match|origin|===|!==|allow|safe|valid|trusted/i;
746
- const mentions = (n) => {
747
- const text = n ? code.slice(n.start, n.end) : '';
748
- return word.test(text) && VALIDATES.test(text);
749
- };
750
- let child = p;
751
- for (let at = p.parentPath; at; child = at, at = at.parentPath) {
752
- const n = at.node;
753
- if ((n.type === 'IfStatement' || n.type === 'ConditionalExpression') && mentions(n.test)) return true;
754
- if (n.type === 'LogicalExpression' && n.operator === '&&' && child.node === n.right && mentions(n.left)) return true;
755
- if (n.type === 'BlockStatement' || n.type === 'Program') {
756
- const index = n.body.indexOf(child.node);
757
- if (n.body.slice(0, Math.max(0, index)).some((s) => s.type === 'IfStatement' && mentions(s.test))) return true;
758
- }
759
- if (/Function/.test(n.type)) break;
760
- }
761
- return false;
762
- }
763
-
764
- /**
765
- * The helper a value is the result of: a call to a function this file
766
- * declares, or one it imports from a file of the project. Its returns, each
767
- * with its scope and its file's code, and the line where the first of them
768
- * that is not plain text is built. Null for anything else - an import from a
769
- * package, a default export, a function that cannot be found.
770
- */
771
- function helperOf(value, scope, code, file, lineOffset, resolver) {
772
- if (!value || !/CallExpression$/.test(value.type) || !value.callee || value.callee.type !== 'Identifier' || !scope) return null;
773
- const name = value.callee.name;
774
- let fnPath = localFunction(name, scope);
775
- let helper = { code: code, file: null, lineOffset: lineOffset };
776
- if (!fnPath) {
777
- const binding = scope.getBinding(name);
778
- const spec = binding && binding.kind === 'module' && binding.path && binding.path.node;
779
- if (!spec || spec.type !== 'ImportSpecifier' || !resolver) return null;
780
- const from = binding.path.parentPath && binding.path.parentPath.node.source && binding.path.parentPath.node.source.value;
781
- const imported = spec.imported && (spec.imported.name || spec.imported.value);
782
- const found = from && imported ? resolver(file, from, imported) : null;
783
- if (!found) return null;
784
- fnPath = found.fnPath;
785
- helper = { code: found.code, file: found.file, lineOffset: 1 };
786
- }
787
- const returns = returnsOf(fnPath);
788
- if (!returns.length) return null;
789
- const risky = returns.find((r) => classify(r.node, r.scope, helper.code, 0) !== 'safe') || returns[0];
790
- return {
791
- fn: name,
792
- file: helper.file,
793
- line: (risky.node.loc ? risky.node.loc.start.line : 1) + helper.lineOffset - 1,
794
- code: helper.code,
795
- lineOffset: helper.lineOffset,
796
- returns: returns,
797
- };
798
- }
799
-
800
- /**
801
- * Finds a function another file of the project exports, for helperOf. Parsed
802
- * once a file; its functions are handed to the map() reader each time, since
803
- * that table is rebuilt for every file read.
804
- */
805
- /** The project file a relative import names, or null for a package or nothing. */
806
- function resolveModule(fromFile, source) {
807
- if (!/^\.\.?\//.test(source)) return null;
808
- const EXTS = ['', '.js', '.mjs', '.cjs', '.jsx', '.ts', '.tsx', '/index.js', '/index.ts'];
809
- const base = path.resolve(path.dirname(fromFile), source);
810
- return EXTS.map((ext) => base + ext).find((candidate) => {
811
- try {
812
- return fs.statSync(candidate).isFile() && CODE_EXT.test(candidate);
813
- } catch (err) {
814
- return false;
815
- }
816
- }) || null;
817
- }
818
-
819
- function importResolver(parser, root) {
820
- const parsed = new Map();
821
- const entryOf = (fromFile, source) => {
822
- const full = resolveModule(fromFile, source);
823
- if (!full) return null;
824
- if (!parsed.has(full)) {
825
- let entry = null;
826
- try {
827
- if (fs.statSync(full).size <= MAX_BYTES) {
828
- const code = fs.readFileSync(full, 'utf8');
829
- const ast = parser.babelParse(code, full, true);
830
- const fns = [];
831
- let program = null;
832
- parser.traverse(ast, {
833
- Program(p) { program = p.scope; },
834
- Function(p) { fns.push(p); },
835
- });
836
- if (program) PROGRAM_FILE.set(program.block, full);
837
- entry = { code: code, program: program, fns: fns, file: path.relative(root, full).split(path.sep).join('/') };
838
- }
839
- } catch (err) {
840
- entry = null;
841
- }
842
- parsed.set(full, entry);
843
- }
844
- const entry = parsed.get(full);
845
- if (!entry || !entry.program) return null;
846
- for (const p of entry.fns) FN_PATHS.set(p.node, p);
847
- return Object.assign({ full: full }, entry);
848
- };
849
- const resolve = (fromFile, source, name) => {
850
- const entry = entryOf(fromFile, source);
851
- if (!entry) return null;
852
- const fnPath = localFunction(name, entry.program);
853
- return fnPath ? { fnPath: fnPath, code: entry.code, file: entry.file } : null;
854
- };
855
- // A `const` the file declares at its top, with the value it is given there.
856
- resolve.constOf = (fromFile, source, name) => {
857
- const entry = entryOf(fromFile, source);
858
- if (!entry) return null;
859
- const binding = entry.program.getBinding(name);
860
- const node = binding && binding.path && binding.path.node;
861
- if (!binding || binding.kind !== 'const' || !node || node.type !== 'VariableDeclarator' || !node.init) return null;
862
- if (binding.constantViolations && binding.constantViolations.length) return null;
863
- return { full: entry.full, init: node.init, scope: binding.path.scope, code: entry.code };
864
- };
865
- return resolve;
866
- }
867
-
868
- // Methods that change the array, map or set they are called on.
869
- const MUTATORS = /^(push|pop|shift|unshift|splice|sort|reverse|fill|copyWithin|set|add|delete|clear)$/;
870
- // Calls that only read what they are given.
871
- const READS_ONLY = /^(String|Number|Boolean|JSON\.stringify|console\.\w+|Array\.isArray|Object\.(keys|values|entries|freeze|isFrozen))$/;
872
- // Methods that only read their argument: list.concat(demo.changes) builds a
873
- // new list and leaves demo alone. push() and the like are not here - they put
874
- // the value somewhere it can be written through.
875
- const READS_ARGUMENT = /^(concat|includes|indexOf|lastIndexOf|startsWith|endsWith|localeCompare|has|at)$/;
876
-
877
- /**
878
- * Whether this use of a name can change what the name holds: an assignment or
879
- * delete through it, a mutating method on it, or handing it to a call that
880
- * could change it. A local name given to part of it - `const list = demo.flags`
881
- * - is followed, since writing to the list writes to demo.
882
- */
883
- function writtenThrough(ref, depth) {
884
- if ((depth || 0) > 4) return true;
885
- let p = ref;
886
- while (p.parentPath && /MemberExpression$/.test(p.parentPath.node.type) && p.parentPath.node.object === p.node) p = p.parentPath;
887
- const parentPath = p.parentPath;
888
- const parent = parentPath && parentPath.node;
889
- if (!parent) return false;
890
- if (parent.type === 'UpdateExpression') return true;
891
- if (parent.type === 'UnaryExpression' && parent.operator === 'delete') return true;
892
- // The target of an assignment, plain or inside a destructuring pattern.
893
- let up = p;
894
- while (up.parentPath && /^(ObjectProperty|ObjectPattern|ArrayPattern|AssignmentPattern|RestElement)$/.test(up.parentPath.node.type)) up = up.parentPath;
895
- const holder = up.parentPath && up.parentPath.node;
896
- if (holder && holder.type === 'AssignmentExpression' && holder.left === up.node) return true;
897
- if (holder && /^For(Of|In)Statement$/.test(holder.type) && holder.left === up.node) return true;
898
- if (/CallExpression$/.test(parent.type)) {
899
- if (parent.callee === p.node) {
900
- return /MemberExpression$/.test(p.node.type) && MUTATORS.test(calleeName(p.node));
901
- }
902
- if (parent.arguments.indexOf(p.node) !== -1) {
903
- const callee = parent.callee;
904
- const full = callee.type === 'MemberExpression' && callee.object.type === 'Identifier'
905
- ? callee.object.name + '.' + calleeName(callee) : calleeName(callee);
906
- if (/MemberExpression$/.test(callee.type) && READS_ARGUMENT.test(calleeName(callee))) return false;
907
- return !(MAKES_SAFE.test(calleeName(callee)) || READS_ONLY.test(full));
908
- }
909
- }
910
- if (parent.type === 'VariableDeclarator' && parent.init === p.node && parent.id.type === 'Identifier') {
911
- const alias = parentPath.scope.getBinding(parent.id.name);
912
- if (!alias) return true;
913
- if (alias.constantViolations && alias.constantViolations.length) return true;
914
- return (alias.referencePaths || []).some((r) => writtenThrough(r, (depth || 0) + 1));
915
- }
916
- return false;
917
- }
918
-
919
- /**
920
- * Every project name something writes to, as "<file>::<name>", read once over
921
- * the whole project before any file is judged. `blind` when a file could not
922
- * be read: a write could be in it, so no import is trusted at all.
923
- */
924
- function projectWrites(parser, files) {
925
- const written = new Set();
926
- let blind = false;
927
- for (const full of files) {
928
- let pieces;
929
- try {
930
- if (fs.statSync(full).size > MAX_BYTES) continue;
931
- const source = fs.readFileSync(full, 'utf8');
932
- pieces = PAGE_EXT.test(full) ? scriptsIn(source) : [{ code: source }];
933
- } catch (err) {
934
- blind = true;
935
- continue;
936
- }
937
- for (const piece of pieces) {
938
- let ast;
939
- try {
940
- ast = parser.babelParse(piece.code, full, true);
941
- } catch (err) {
942
- blind = true;
943
- continue;
944
- }
945
- parser.traverse(ast, {
946
- Program(p) {
947
- // This file's own top-level names, written to here.
948
- for (const name of Object.keys(p.scope.bindings)) {
949
- const b = p.scope.bindings[name];
950
- if (b.kind === 'module') continue;
951
- if ((b.constantViolations && b.constantViolations.length) ||
952
- (b.referencePaths || []).some((r) => writtenThrough(r))) {
953
- written.add(full + '::' + name);
954
- }
955
- }
956
- },
957
- ImportDeclaration(p) {
958
- const from = resolveModule(full, p.node.source.value);
959
- if (!from) return;
960
- for (const spec of p.node.specifiers) {
961
- const b = p.scope.getBinding(spec.local.name);
962
- if (!b) continue;
963
- if (spec.type === 'ImportNamespaceSpecifier') {
964
- for (const r of b.referencePaths || []) {
965
- const m = r.parentPath && r.parentPath.node;
966
- if (m && /MemberExpression$/.test(m.type) && m.object === r.node && !m.computed && m.property.type === 'Identifier') {
967
- if (writtenThrough(r.parentPath)) written.add(from + '::' + m.property.name);
968
- } else {
969
- written.add(from + '::*');
970
- }
971
- }
972
- continue;
973
- }
974
- const name = spec.type === 'ImportDefaultSpecifier' ? 'default' : (spec.imported.name || spec.imported.value);
975
- if ((b.referencePaths || []).some((r) => writtenThrough(r))) written.add(from + '::' + name);
976
- }
977
- },
978
- });
979
- }
980
- }
981
- return { written: written, blind: blind };
982
- }
983
-
984
- function sinksIn(parser, code, file, lineOffset, resolver) {
985
- const found = [];
986
- const ast = parser.babelParse(code, file, true);
987
- PROGRAM_FILE.set(ast.program, file);
988
- const lineOf = (node) => (node.loc ? node.loc.start.line : 1) + lineOffset - 1;
989
- const textOf = (node) => code.slice(node.start, node.end).replace(/\s+/g, ' ').slice(0, 160);
990
- // Calls to plain named functions, so a helper's sink can be judged by what
991
- // each call actually hands it.
992
- const calls = new Map();
993
- const viaHelper = [];
994
- const partsOf = (value, scope) => {
995
- const out = [];
996
- riskyParts(value, scope, code, undefined, out, 0);
997
- return out;
998
- };
999
- const add = (node, scope, sink, value) => {
1000
- const param = paramOf(value, scope);
1001
- if (param) {
1002
- viaHelper.push({ node: node, sink: sink, value: value, scope: scope, param: param });
1003
- return;
1004
- }
1005
- // The HTML built by a helper - root.innerHTML = renderBoard(rows) - is
1006
- // judged by what the helper returns, in its own file, and the place it
1007
- // puts a value in is named. Found on a blind test (HelixOps): appShell(),
1008
- // a fixed string in ui.js, was reported as unknown, and renderBoard() was
1009
- // reported at its call with no word of ui.js:13, where the title goes in.
1010
- const built = helperOf(value, scope, code, file, lineOffset, resolver);
1011
- if (built) {
1012
- const origin = worst(built.returns.map((r) => classify(r.node, r.scope, built.code, 0)));
1013
- if (origin === 'safe') return;
1014
- const parts = [];
1015
- for (const r of built.returns) riskyParts(r.node, r.scope, built.code, undefined, parts, 0);
1016
- // The line of the first value that goes in, not of the return around it.
1017
- const first = parts.find((p) => p.line);
1018
- found.push({
1019
- line: lineOf(node), sink: sink, expression: textOf(value), origin: origin, parts: parts,
1020
- helper: { fn: built.fn, file: built.file, line: first ? first.line + built.lineOffset - 1 : built.line },
1021
- });
1022
- return;
1023
- }
1024
- const origin = classify(value, scope, code, 0);
1025
- if (origin === 'safe') return;
1026
- found.push({ line: lineOf(node), sink: sink, expression: textOf(value), origin: origin, parts: partsOf(value, scope) });
1027
- };
1028
- FN_PATHS = new WeakMap();
1029
- parser.traverse(ast, {
1030
- Function(p) {
1031
- FN_PATHS.set(p.node, p);
1032
- },
1033
- CallExpression: {
1034
- exit(p) {
1035
- if (p.node.callee.type !== 'Identifier') return;
1036
- const list = calls.get(p.node.callee.name) || [];
1037
- list.push({ node: p.node, scope: p.scope });
1038
- calls.set(p.node.callee.name, list);
1039
- },
1040
- },
1041
- });
1042
- const redirect = (p, sink, value) => {
1043
- if (!value || !readsUrl(value, p.scope, 0) || checkedFirst(p, value, code)) return;
1044
- found.push({ kind: 'redirect', line: lineOf(p.node), sink: sink, expression: textOf(value), origin: 'url', parts: [] });
1045
- };
1046
- parser.traverse(ast, {
1047
- AssignmentExpression(p) {
1048
- const left = p.node.left;
1049
- if (isLocation(left)) return redirect(p, 'location', p.node.right);
1050
- if (left.type !== 'MemberExpression' || left.computed) return;
1051
- const prop = left.property && left.property.name;
1052
- if (prop === 'innerHTML' || prop === 'outerHTML') add(p.node, p.scope, prop, p.node.right);
1053
- else if (prop === 'href' && isLocation(left.object)) redirect(p, 'location.href', p.node.right);
1054
- },
1055
- CallExpression(p) {
1056
- const callee = p.node.callee;
1057
- const name = calleeName(callee);
1058
- const args = p.node.arguments;
1059
- if ((name === 'assign' || name === 'replace') && callee.type === 'MemberExpression' && isLocation(callee.object)) {
1060
- return redirect(p, 'location.' + name + '()', args[0]);
1061
- }
1062
- if (name === 'open' && callee.type === 'MemberExpression' && callee.object.type === 'Identifier' && callee.object.name === 'window') {
1063
- return redirect(p, 'window.open()', args[0]);
1064
- }
1065
- // Next's router follows a full URL off the site. React Router's
1066
- // navigate() does not, so it is not a sink here.
1067
- if ((name === 'push' || name === 'replace') && callee.type === 'MemberExpression' &&
1068
- callee.object.type === 'Identifier' && callee.object.name === 'router') {
1069
- return redirect(p, 'router.' + name + '()', args[0]);
1070
- }
1071
- if (name === 'insertAdjacentHTML' && args[1]) add(p.node, p.scope, 'insertAdjacentHTML', args[1]);
1072
- else if ((name === 'write' || name === 'writeln') && callee.type === 'MemberExpression' &&
1073
- callee.object && callee.object.name === 'document' && args[0]) {
1074
- add(p.node, p.scope, 'document.' + name, args[0]);
1075
- } else if (name === 'html' && callee.type === 'MemberExpression' && args.length === 1) {
1076
- add(p.node, p.scope, '.html()', args[0]);
1077
- }
1078
- },
1079
- JSXAttribute(p) {
1080
- if (!p.node.name || p.node.name.name !== 'dangerouslySetInnerHTML') return;
1081
- const expr = p.node.value && p.node.value.expression;
1082
- if (!expr || expr.type !== 'ObjectExpression') return;
1083
- const html = expr.properties.find((prop) => prop.key && (prop.key.name === '__html' || prop.key.value === '__html'));
1084
- if (html) add(p.node, p.scope, 'dangerouslySetInnerHTML', html.value);
1085
- },
1086
- });
1087
-
1088
- // A helper's sink is judged at its calls. Most calls of a helper like this
1089
- // pass HTML on purpose, so the risk is the one call that passes something
1090
- // from outside - and that is where it has to be fixed. A helper with no call
1091
- // this file can see cannot be judged that way, so its sink is reported where
1092
- // it is, as unknown, rather than dropped.
1093
- for (const h of viaHelper) {
1094
- const seen = calls.get(h.param.fn) || [];
1095
- if (!seen.length) {
1096
- found.push({ line: lineOf(h.node), sink: h.sink, expression: textOf(h.value), origin: 'unknown' });
1097
- continue;
1098
- }
1099
- for (const call of seen) {
1100
- const arg = call.node.arguments[h.param.index];
1101
- if (!arg) continue;
1102
- const origin = classify(arg, call.scope, code, 0);
1103
- if (origin === 'safe') continue;
1104
- found.push({
1105
- line: lineOf(call.node),
1106
- sink: h.sink,
1107
- expression: textOf(arg),
1108
- origin: origin,
1109
- parts: partsOf(arg, call.scope),
1110
- via: { fn: h.param.fn, line: lineOf(h.node) },
1111
- });
1112
- }
1113
- }
1114
- return found;
1115
- }
1116
-
1117
- /**
1118
- * Reads the project at `root`. Returns
1119
- * { ran, why?, filesRead, findings: [...], unreadable: [{ file, why }] }
1120
- * `ran: false` means the check did not happen - never that it passed.
1121
- */
1122
- function scanProject(root, options) {
1123
- const packageDir = (options && options.packageDir) || __dirname;
1124
- const parser = (options && options.parser) || loadParser(packageDir);
1125
- if (!parser) {
1126
- return {
1127
- ran: false,
1128
- why: 'the JavaScript parser this check uses was not found in this install of Playwright',
1129
- filesRead: 0,
1130
- findings: [],
1131
- unreadable: [],
1132
- };
1133
- }
1134
- const findings = [];
1135
- const unreadable = [];
1136
- // Secret keys, read from the same files. Kept apart from the HTML findings:
1137
- // they are already in their final shape, and they go first.
1138
- const secrets = [];
1139
- let filesRead = 0;
1140
- const files = listFiles(root);
1141
- const relOf = (full) => path.relative(root, full).split(path.sep).join('/');
1142
- // Which pages load which scripts, so a key in config.js can be said to
1143
- // reach the browser because index.html loads it - not guessed at.
1144
- const pages = [];
1145
- for (const full of files) {
1146
- if (!/\.html?$/i.test(full)) continue;
1147
- try {
1148
- if (fs.statSync(full).size <= MAX_BYTES) pages.push({ rel: relOf(full), source: fs.readFileSync(full, 'utf8') });
1149
- } catch (err) {
1150
- /* unreadable pages are reported below */
1151
- }
1152
- }
1153
- const loadedBy = keys.scriptsLoadedBy(pages);
1154
- const resolver = importResolver(parser, root);
1155
- // Before any file is judged: which of the project's own names anything
1156
- // writes to, so fixed data is only trusted while it really is fixed.
1157
- PROGRAM_FILE = new WeakMap();
1158
- IMPORTS = Object.assign({ constOf: resolver.constOf }, projectWrites(parser, files));
1159
- try {
1160
- readAll();
1161
- } finally {
1162
- IMPORTS = null;
1163
- }
1164
- return { ran: true, filesRead: filesRead, findings: secrets.concat(findings.map(describe)), unreadable: unreadable };
1165
-
1166
- function readAll() {
1167
- for (const full of files) {
1168
- let size = 0;
1169
- try {
1170
- size = fs.statSync(full).size;
1171
- } catch (err) {
1172
- continue;
1173
- }
1174
- const rel = path.relative(root, full).split(path.sep).join('/');
1175
- if (size > MAX_BYTES) {
1176
- unreadable.push({ file: rel, why: 'larger than ' + Math.round(MAX_BYTES / 1024) + ' KB, probably generated' });
1177
- continue;
1178
- }
1179
- const source = fs.readFileSync(full, 'utf8');
1180
- filesRead++;
1181
- for (const k of keys.secretsIn(rel, source, loadedBy)) secrets.push(k);
1182
- const pieces = PAGE_EXT.test(full) ? scriptsIn(source) : [{ code: source, line: 1 }];
1183
- for (const piece of pieces) {
1184
- try {
1185
- for (const f of sinksIn(parser, piece.code, full, piece.line, resolver)) findings.push(Object.assign({ file: rel }, f));
1186
- } catch (err) {
1187
- unreadable.push({ file: rel + (piece.line > 1 ? ':' + piece.line : ''), why: 'could not be parsed: ' + String(err.message).split('\n')[0].slice(0, 120) });
1188
- }
1189
- }
1190
- if (/\.(vue|html)$/i.test(full)) {
1191
- for (const v of vHtmlIn(source)) {
1192
- findings.push({ file: rel, line: v.line, sink: 'v-html', expression: v.expression, origin: 'unknown' });
1193
- }
1194
- }
1195
- }
1196
- }
1197
- }
1198
-
1199
- const ORIGIN_WORDS = {
1200
- network: 'read from a server response',
1201
- error: "an error's message, which often carries text a server sent",
1202
- unknown: 'from somewhere the code alone cannot pin down',
1203
- };
1204
-
1205
- // Wrapped here rather than by whoever prints it: this is pasted into a chat
1206
- // box as often as it is read in a terminal, and a long line is a wall in both.
1207
- // A quoted piece of code is never wrapped - breaking it would change it.
1208
- function wrap(text, width) {
1209
- const out = [];
1210
- let current = '';
1211
- for (const word of String(text).split(/\s+/)) {
1212
- if (current && (current + ' ' + word).length > width) {
1213
- out.push(current);
1214
- current = word;
1215
- } else {
1216
- current = current ? current + ' ' + word : word;
1217
- }
1218
- }
1219
- if (current) out.push(current);
1220
- return out.join('\n');
1221
- }
1222
-
1223
- /** An open redirect, in the same shape as every other finding. */
1224
- function describeRedirect(f) {
1225
- const fixPrompt = [
1226
- 'My app may have an open redirect - please check it rather than assume it.',
1227
- '',
1228
- 'In ' + f.file + ' at line ' + f.line + ', the page sends the browser to an address taken from its own URL:',
1229
- '',
1230
- ' ' + f.expression,
1231
- '',
1232
- 'Anyone can send a link to this page with that part of the URL set to their own site - for example ' +
1233
- '?next=https://attacker.example. The person uses your real page, then lands on the attacker\'s, which ' +
1234
- 'can ask for their password again. A value starting with javascript: can run script in your page.',
1235
- '',
1236
- 'Fix it so only your own pages are allowed: accept the value only if it starts with a single "/" (not ' +
1237
- '"//" and not "/\\"), or check that new URL(value, location.origin).origin equals location.origin, and ' +
1238
- 'go to your home page otherwise. Then check every other place that reads a next, redirect or returnTo ' +
1239
- 'value the same way.',
1240
- ].map((p) => (p.startsWith(' ') ? p : wrap(p, 72))).join('\n');
1241
- return {
1242
- kind: 'open-redirect',
1243
- status: 'verification required',
1244
- evidence: 'code analysis',
1245
- severity: 'HIGH',
1246
- confidence: 'medium',
1247
- file: f.file,
1248
- line: f.line,
1249
- sink: f.sink,
1250
- expression: f.expression,
1251
- origin: 'url',
1252
- parts: [],
1253
- via: null,
1254
- headline: 'A redirect in ' + f.file + ':' + f.line + ' goes wherever the page\'s URL says.',
1255
- fixPrompt: fixPrompt,
1256
- };
1257
- }
1258
-
1259
- /** One finding, in the shape every Kryptheon report uses. */
1260
- function describe(f) {
1261
- if (f.kind === 'redirect') return describeRedirect(f);
1262
- const severity = f.origin === 'unknown' ? 'MEDIUM' : 'HIGH';
1263
- const how = f.sink === 'v-html' ? 'v-html' : f.sink;
1264
- // Where the helper builds it: its own file when it is another one.
1265
- const builtAt = f.helper ? (f.helper.file ? f.helper.file + ':' : 'line ') + f.helper.line : '';
1266
- const where = f.via
1267
- ? 'In ' + f.file + ' at line ' + f.line + ', this value is passed to ' + f.via.fn + '(), which puts ' +
1268
- 'what it is given into the page as HTML with ' + how + ' at line ' + f.via.line + ':'
1269
- : f.helper
1270
- ? 'In ' + f.file + ' at line ' + f.line + ', the HTML that ' + f.helper.fn + '() builds - at ' + builtAt +
1271
- ' - is put into the page with ' + how + ':'
1272
- : 'In ' + f.file + ' at line ' + f.line + ', this value is put into the page as HTML with ' + how + ':';
1273
- // The fix for a helper is different, and getting it wrong breaks the page:
1274
- // switching the helper to textContent makes every other call - the ones
1275
- // that pass HTML on purpose - show their tags as text. Found by applying the
1276
- // plain version of this prompt to a real helper like this.
1277
- const fix = f.via
1278
- ? [
1279
- 'Do not change ' + f.via.fn + '() to use textContent: other calls pass HTML to it on purpose, ' +
1280
- 'and they would show their tags as text. Fix it here instead - escape the dynamic part of ' +
1281
- 'this value before it is joined into the HTML (replace & < > " \' with their HTML entities), ' +
1282
- 'or pass it through a sanitizer such as DOMPurify if it must keep some formatting.',
1283
- ]
1284
- : f.helper
1285
- ? [
1286
- 'Fix it inside ' + f.helper.fn + '() at ' + builtAt + ', where the values are joined into the HTML: ' +
1287
- 'escape each dynamic value there (replace & < > " \' with their HTML entities), or pass the ' +
1288
- 'result through a sanitizer such as DOMPurify if it must keep some formatting.',
1289
- ]
1290
- : [
1291
- 'Fix it so the value is always shown as text: set textContent instead of innerHTML for the ' +
1292
- 'dynamic part, or escape it before it is joined into HTML (replace & < > " \' with their ' +
1293
- 'HTML entities). If the HTML is meant to allow some formatting, pass it through a sanitizer ' +
1294
- 'such as DOMPurify first.',
1295
- ];
1296
- // A long template is mostly harmless markup. Naming the part that decides it
1297
- // keeps the fix - and the AI tool doing it - to that part alone.
1298
- const parts = (f.parts || []).filter((p) => p.text && p.text !== f.expression);
1299
- const only = parts.length
1300
- ? [''].concat(
1301
- [(parts.length === 1 ? 'Only this part' : 'Only these parts') + ' of it can carry text from outside the page, ' +
1302
- 'so only ' + (parts.length === 1 ? 'it needs' : 'they need') + ' changing:'],
1303
- parts.map((p) => ' ${' + p.text + '}'),
1304
- )
1305
- : [];
1306
- const fixPrompt = [
1307
- 'My app may have a security problem - please check it rather than assume it.',
1308
- '',
1309
- where,
1310
- '',
1311
- ' ' + f.expression,
1312
- ].concat(only, [
1313
- '',
1314
- 'The value is ' + ORIGIN_WORDS[f.origin] + '. If it can ever contain text a user or another ' +
1315
- 'account typed, a "<" in it becomes a real tag and can run script in this page with the ' +
1316
- "signed-in person's session.",
1317
- '',
1318
- ]).concat(fix, [
1319
- '',
1320
- 'Keep the page looking the same, change only how this value is inserted, and look for the ' +
1321
- 'same pattern elsewhere in this file. Afterwards, open this page and check that ordinary ' +
1322
- 'text, and text containing < and &, both display correctly.',
1323
- ]).map((p) => (p.startsWith(' ') ? p : wrap(p, 72))).join('\n');
1324
- return {
1325
- kind: 'unsafe-html',
1326
- status: 'verification required',
1327
- evidence: 'code analysis',
1328
- severity: severity,
1329
- confidence: f.origin === 'unknown' ? 'low' : 'medium',
1330
- file: f.file,
1331
- line: f.line,
1332
- sink: f.sink,
1333
- expression: f.expression,
1334
- origin: f.origin,
1335
- parts: (f.parts || []).map((p) => ({ text: p.text, origin: p.origin })),
1336
- via: f.via || null,
1337
- helper: f.helper || null,
1338
- headline: 'Text ' + (f.origin === 'unknown' ? 'of unknown origin' : ORIGIN_WORDS[f.origin].split(',')[0]) +
1339
- ' is inserted as HTML in ' + f.file + ':' + f.line +
1340
- (f.via ? ' (through ' + f.via.fn + '() at line ' + f.via.line + ')' : '') +
1341
- (f.helper ? ', built by ' + f.helper.fn + '() at ' + builtAt : '') + '.',
1342
- fixPrompt: fixPrompt,
1343
- };
1344
- }
1345
-
1346
- module.exports = {
1347
- scanProject: scanProject,
1348
- listFiles: listFiles,
1349
- loadParser: loadParser,
1350
- scriptsIn: scriptsIn,
1351
- classify: classify,
1352
- describe: describe,
1353
- };
1
+ // Reads a project's frontend code for one kind of mistake: text that may come
2
+ // from outside the page - a server response, an error message, a value a user
3
+ // typed - being handed to something that turns text into HTML.
4
+ //
5
+ // element.innerHTML = `<p>${data.name}</p>`
6
+ //
7
+ // If data.name holds "<img src=x onerror=...>", the browser runs it in the
8
+ // page, with the page's session. Written as textContent, or escaped first, the
9
+ // same value is just text.
10
+ //
11
+ // This is code analysis, never execution: nothing is run, nothing is sent, and
12
+ // every finding is "verification required". A static read cannot see what a
13
+ // value holds at run time, so it says where the risk is and how sure it is,
14
+ // and leaves the verdict to a person or a later runtime check.
15
+ //
16
+ // Deliberately narrow, because a report that flags every innerHTML in an app
17
+ // is a report nobody reads twice:
18
+ // - a sink fed only literal text is safe and never reported;
19
+ // - a value wrapped in an escaping or sanitising call is safe;
20
+ // - a value that can only be a number is safe;
21
+ // - everything else is reported, and ranked by where it came from.
22
+ //
23
+ // The parser is the one Playwright already ships, so this adds no dependency.
24
+ // It is an internal file of Playwright's, not a public API; if a later
25
+ // Playwright moves it, this says it could not run - it never says "passed".
26
+
27
+ const fs = require('fs');
28
+ const path = require('path');
29
+ const keys = require('./kryptheon-keys.js');
30
+
31
+ const SKIP_DIRS = new Set([
32
+ 'node_modules', '.git', 'dist', 'build', 'out', '.next', '.nuxt', '.svelte-kit',
33
+ 'coverage', 'vendor', '.vercel', '.netlify', '.turbo', '.cache', 'tests', 'test-results',
34
+ ]);
35
+ const CODE_EXT = /\.(js|mjs|cjs|jsx|ts|tsx)$/i;
36
+ const PAGE_EXT = /\.(html|htm|vue|svelte)$/i;
37
+ const MAX_BYTES = 800 * 1024;
38
+
39
+ // A call whose name says it makes text safe for HTML. Matched on the called
40
+ // name only - escapeHtml(x), DOMPurify.sanitize(x), he.encode(x).
41
+ const MAKES_SAFE = /^(escape\w*|\w*escape|sanitize\w*|sanitise\w*|\w*sanitize|purify|encode\w*|\w*encode|htmlEncode|safeHtml|clean(Html)?|textToHtml)$/i;
42
+
43
+ // Calls and properties whose result can only be a number, a boolean, or a
44
+ // formatted number/date - nothing that can carry a tag.
45
+ const NUMERIC_CALLS = /^(Number|parseInt|parseFloat|Boolean|isNaN|isFinite|toFixed|toPrecision|toLocaleString|toLocaleDateString|toLocaleTimeString|getTime|getFullYear|getMonth|getDate|getDay|getHours|getMinutes|getSeconds|round|floor|ceil|abs|min|max|indexOf|findIndex|size)$/;
46
+ const NUMERIC_PROPS = /^(length|size|count|total|id|index|width|height|top|left|x|y)$/;
47
+ // A field whose name says it is a quantity of something: quantity_on_hand,
48
+ // reserved_quantity, itemCount, unit_price. Found on blind round 16
49
+ // (Meridian), once rows from the database were followed into the page: the
50
+ // stock counts were written unescaped, and an integer column holds digits.
51
+ const NUMERIC_NAMES = /^(quantity|qty|count|total|amount|price|cost|balance|percent|score)(_|[A-Z]|$)|((^|_)(quantity|qty|count|total|amount|price|cost|balance|percent|score)|[a-z](Quantity|Qty|Count|Total|Amount|Price|Cost|Balance|Percent|Score))$/;
52
+
53
+ /** Every file worth reading, relative paths, skipping what is not the app's source. */
54
+ function listFiles(root) {
55
+ const out = [];
56
+ (function walk(dir) {
57
+ let entries;
58
+ try {
59
+ entries = fs.readdirSync(dir, { withFileTypes: true });
60
+ } catch (err) {
61
+ return;
62
+ }
63
+ for (const entry of entries) {
64
+ if (entry.name.startsWith('.') && entry.name !== '.') {
65
+ if (entry.isDirectory()) continue;
66
+ }
67
+ const full = path.join(dir, entry.name);
68
+ if (entry.isDirectory()) {
69
+ if (!SKIP_DIRS.has(entry.name)) walk(full);
70
+ } else if ((CODE_EXT.test(entry.name) || PAGE_EXT.test(entry.name)) && !/\.min\.js$/i.test(entry.name)) {
71
+ out.push(full);
72
+ }
73
+ }
74
+ })(root);
75
+ return out.sort();
76
+ }
77
+
78
+ // Column types that can hold no tag: numbers, yes/no, ids, dates and times.
79
+ const TAGLESS_TYPE = /^(smallint|integer|int|int2|int4|int8|bigint|smallserial|serial|bigserial|numeric|decimal|real|float4|float8|double precision|money|boolean|bool|uuid|date|time|timetz|timestamp|timestamptz|interval)\b/i;
80
+ const NOT_A_COLUMN = /^(constraint|primary|foreign|unique|check|exclude|like)$/i;
81
+
82
+ /**
83
+ * Column names the project's own SQL declares only with a type that cannot
84
+ * hold a tag - every table that has the name gives it a number, a yes/no, an
85
+ * id or a date. Read from the .sql files in the project (migrations, a schema
86
+ * dump), never guessed from the name.
87
+ *
88
+ * Found on blind round 16, once rows from the database were followed into the
89
+ * page: stock counts and ticket numbers - integer and bigint columns - were
90
+ * reported as text of unknown origin. A name declared as text anywhere, or
91
+ * not declared at all, is not on the list.
92
+ */
93
+ function taglessColumns(root) {
94
+ const types = new Map();
95
+ let read = 0;
96
+ (function walk(dir, depth) {
97
+ if (depth > 8 || read > 200) return;
98
+ let entries;
99
+ try {
100
+ entries = fs.readdirSync(dir, { withFileTypes: true });
101
+ } catch (err) {
102
+ return;
103
+ }
104
+ for (const entry of entries) {
105
+ const full = path.join(dir, entry.name);
106
+ if (entry.isDirectory()) {
107
+ if (!entry.name.startsWith('.') && !SKIP_DIRS.has(entry.name)) walk(full, depth + 1);
108
+ continue;
109
+ }
110
+ if (!/\.sql$/i.test(entry.name)) continue;
111
+ let sql;
112
+ try {
113
+ if (fs.statSync(full).size > 4 * MAX_BYTES) continue;
114
+ sql = fs.readFileSync(full, 'utf8');
115
+ } catch (err) {
116
+ continue;
117
+ }
118
+ read++;
119
+ sql = sql.replace(/--[^\n]*/g, ' ').replace(/\/\*[\s\S]*?\*\//g, ' ');
120
+ const add = (name, type) => {
121
+ const n = String(name).replace(/"/g, '');
122
+ if (!types.has(n)) types.set(n, []);
123
+ types.get(n).push(String(type).trim());
124
+ };
125
+ // CREATE TABLE name ( ... ): split at the commas outside brackets.
126
+ const table = /create\s+(?:(?:global|local)\s+)?(?:temp(?:orary)?\s+|unlogged\s+)?table\s+(?:if\s+not\s+exists\s+)?[\w."]+\s*\(/gi;
127
+ let m;
128
+ while ((m = table.exec(sql)) !== null) {
129
+ let level = 1;
130
+ let i = table.lastIndex;
131
+ let start = i;
132
+ const parts = [];
133
+ for (; i < sql.length && level > 0; i++) {
134
+ const ch = sql[i];
135
+ if (ch === '(') level++;
136
+ else if (ch === ')') { level--; if (level === 0) parts.push(sql.slice(start, i)); }
137
+ else if (ch === ',' && level === 1) { parts.push(sql.slice(start, i)); start = i + 1; }
138
+ }
139
+ for (const part of parts) {
140
+ const cm = /^\s*("[^"]+"|[A-Za-z_][\w$]*)\s+([A-Za-z][\w ]*?)(?=\s*(\(|\[|not\b|null\b|default\b|primary\b|references\b|unique\b|check\b|generated\b|constraint\b|collate\b|$))/i.exec(part);
141
+ if (!cm || NOT_A_COLUMN.test(cm[1])) continue;
142
+ add(cm[1], cm[2]);
143
+ }
144
+ }
145
+ // ALTER TABLE ... ADD COLUMN name type
146
+ const added = /add\s+column\s+(?:if\s+not\s+exists\s+)?("[^"]+"|[A-Za-z_][\w$]*)\s+([A-Za-z][\w ]*?)(?=\s*(\(|\[|not\b|null\b|default\b|references\b|unique\b|check\b|generated\b|;|,|$))/gi;
147
+ while ((m = added.exec(sql)) !== null) add(m[1], m[2]);
148
+ }
149
+ })(root, 0);
150
+ const out = new Set();
151
+ for (const [name, list] of types) {
152
+ if (list.length && list.every((t) => TAGLESS_TYPE.test(t))) out.add(name);
153
+ }
154
+ return out;
155
+ }
156
+ let TAGLESS_COLUMNS = new Set();
157
+
158
+ /** The parser, or null when this Playwright does not have it where expected. */
159
+ function loadParser(packageDir) {
160
+ const candidates = [];
161
+ try {
162
+ candidates.push(path.join(path.dirname(require.resolve('playwright/package.json', { paths: [packageDir] })), 'lib', 'transform', 'babelBundle.js'));
163
+ } catch (err) {
164
+ /* not resolvable from here */
165
+ }
166
+ candidates.push(path.join(packageDir, 'node_modules', 'playwright', 'lib', 'transform', 'babelBundle.js'));
167
+ for (const file of candidates) {
168
+ try {
169
+ const bundle = require(file);
170
+ if (typeof bundle.babelParse === 'function' && typeof bundle.traverse === 'function') return bundle;
171
+ } catch (err) {
172
+ /* try the next */
173
+ }
174
+ }
175
+ return null;
176
+ }
177
+
178
+ /** Inline <script> blocks of a page, with the line each one starts on. */
179
+ function scriptsIn(source) {
180
+ const blocks = [];
181
+ const re = /<script\b([^>]*)>([\s\S]*?)<\/script>/gi;
182
+ let m;
183
+ while ((m = re.exec(source))) {
184
+ const attrs = m[1] || '';
185
+ if (/\bsrc\s*=/.test(attrs)) continue;
186
+ if (/type\s*=\s*["']?(application\/(ld\+)?json|text\/template|importmap)/i.test(attrs)) continue;
187
+ const before = source.slice(0, m.index + m[0].indexOf('>') + 1);
188
+ blocks.push({ code: m[2], line: before.split('\n').length });
189
+ }
190
+ return blocks;
191
+ }
192
+
193
+ /** v-html="..." in a template: always a sink, safe only when the value is quoted text. */
194
+ function vHtmlIn(source) {
195
+ const found = [];
196
+ const re = /\bv-html\s*=\s*"([^"]*)"/g;
197
+ let m;
198
+ while ((m = re.exec(source))) {
199
+ const value = m[1].trim();
200
+ if (/^'[^']*'$/.test(value)) continue;
201
+ found.push({ line: source.slice(0, m.index).split('\n').length, expression: value });
202
+ }
203
+ return found;
204
+ }
205
+
206
+ function calleeName(node) {
207
+ if (!node) return '';
208
+ if (node.type === 'Identifier') return node.name;
209
+ if (node.type === 'MemberExpression' && !node.computed && node.property) return node.property.name || '';
210
+ return '';
211
+ }
212
+
213
+ /**
214
+ * Where a value comes from, as far as the code shows.
215
+ * 'safe' - literal text, a number, or made safe by an escaping call
216
+ * 'network' - read from a response body (.json()), so a server wrote it
217
+ * 'error' - an error's message, which often carries text a server sent
218
+ * 'unknown' - anything else: it may be fine, the code alone cannot say
219
+ */
220
+ // How far one value is followed back before giving up and calling it unknown.
221
+ // It only exists to stop a loop - a function that returns itself, a name that
222
+ // feeds another. It was 6, which a constant-only lookup (a template, a call,
223
+ // its return, a map of maps) used up before reaching the strings at the
224
+ // bottom, so a harmless label came back "unknown". Giving up always errs
225
+ // towards reporting, never towards silence. It was 12 until a blind test
226
+ // (Northstar): a helper's parameter, back to its call inside a map() callback,
227
+ // to the list, a slice of a list reassigned from a filter of the fixed one -
228
+ // 13 steps. 18 leaves room for one more layer of the same.
229
+ const MAX_DEPTH = 18;
230
+
231
+ function classify(node, scope, code, depth, aliases) {
232
+ if (!node || depth > MAX_DEPTH) return 'unknown';
233
+ const again = (n) => classify(n, scope, code, depth + 1, aliases);
234
+ switch (node.type) {
235
+ case 'StringLiteral':
236
+ case 'NumericLiteral':
237
+ case 'BooleanLiteral':
238
+ case 'NullLiteral':
239
+ return 'safe';
240
+ case 'TemplateLiteral':
241
+ return worst(judgedParts(node, scope, code).map((e) => again(e)));
242
+ case 'BinaryExpression':
243
+ if (node.operator !== '+') return 'safe'; // - * / % comparisons: never text
244
+ return worst(judgedParts(node, scope, code).map((e) => again(e)));
245
+ case 'UnaryExpression':
246
+ case 'UpdateExpression':
247
+ return 'safe';
248
+ case 'ConditionalExpression':
249
+ return worst([again(node.consequent), again(node.alternate)]);
250
+ case 'LogicalExpression':
251
+ return worst([again(node.left), again(node.right)]);
252
+ case 'CallExpression':
253
+ case 'OptionalCallExpression': {
254
+ const name = calleeName(node.callee);
255
+ if (MAKES_SAFE.test(name)) return 'safe';
256
+ if (readsResponseBody(node)) return 'network';
257
+ if (NUMERIC_CALLS.test(name)) return 'safe';
258
+ // new Intl.NumberFormat(...).format(x) and its date and time kin: digits,
259
+ // signs and the locale's own words - never a tag.
260
+ if (name === 'format' && node.callee.type === 'MemberExpression' && node.callee.object.type === 'NewExpression' &&
261
+ /^Intl\.(NumberFormat|DateTimeFormat|RelativeTimeFormat)$/.test(
262
+ node.callee.object.callee.type === 'MemberExpression' && node.callee.object.callee.object.type === 'Identifier'
263
+ ? node.callee.object.callee.object.name + '.' + node.callee.object.callee.property.name : '')) {
264
+ return 'safe';
265
+ }
266
+ if (node.callee.type === 'MemberExpression' && node.callee.object && node.callee.object.name === 'Math') return 'safe';
267
+ // items.map(i => `<li>${i.name}</li>`).join('') - judge what map builds.
268
+ const mapped = mapCallback(node, scope, code, depth, aliases);
269
+ if (mapped) {
270
+ return mapped.returns.length
271
+ ? worst(mapped.returns.map((r) => classify(r.node, r.scope, code, depth + 1, mapped.inner)))
272
+ : 'unknown';
273
+ }
274
+ // An escaping helper of this file's own, known by what it does. Inside a
275
+ // template, one that leaves quotes alone does not protect a value that
276
+ // lands in an attribute - the template judges that case itself.
277
+ if (escaperOf(node, scope, code)) return 'safe';
278
+ // A function of this file's own: as dangerous as what it returns. One
279
+ // that only ever returns constants - a lookup of labels, icons and
280
+ // colours - cannot carry anything in; one that returns a parameter
281
+ // stays unknown, because its parameters are.
282
+ const local = node.callee.type === 'Identifier' ? localFunction(node.callee.name, scope) : null;
283
+ if (local) {
284
+ const returns = returnsOf(local);
285
+ // Judged with what THIS call passes: field("Title", ...) is not made
286
+ // dangerous by another call of field() that passes a name from the
287
+ // database (blind round 16, Meridian). An object written out in the
288
+ // call is kept whole, so options.placeholder is that call's own.
289
+ const inner = argumentAliases(local.node, node.arguments, scope, local.scope, code, depth, aliases);
290
+ if (returns.length) return worst(returns.map((r) => classify(r.node, r.scope, code, depth + 1, inner)));
291
+ }
292
+ // String methods pass through whatever they were called on, and so do
293
+ // the array methods that only pick or reorder items: notes.filter(...)
294
+ // holds the same notes.
295
+ if (/^(trim|toUpperCase|toLowerCase|slice|substring|substr|replace|replaceAll|padStart|padEnd|concat|toString|join|filter|sort|reverse|flat|toSorted|toReversed)$/.test(name) &&
296
+ node.callee.type === 'MemberExpression') {
297
+ return again(node.callee.object);
298
+ }
299
+ return 'unknown';
300
+ }
301
+ case 'ObjectExpression':
302
+ // Only as dangerous as what is in it. A spread brings in whatever it spreads.
303
+ return worst(node.properties.map((p) => (p.type === 'SpreadElement' ? again(p.argument) : p.value && again(p.value))));
304
+ case 'ArrayExpression':
305
+ return worst(node.elements.map((e) => (e ? again(e.type === 'SpreadElement' ? e.argument : e) : 'safe')));
306
+ case 'MemberExpression':
307
+ case 'OptionalMemberExpression': {
308
+ const prop = node.property && !node.computed ? node.property.name : '';
309
+ // The page's own markup, read back: button.innerHTML saved and put back
310
+ // adds nothing that was not already there. textContent is not this - it
311
+ // is text, and a "<" in it becomes a tag when written as HTML.
312
+ if (prop === 'innerHTML' || prop === 'outerHTML') return 'safe';
313
+ if (NUMERIC_PROPS.test(prop || '') || NUMERIC_NAMES.test(prop || '') || TAGLESS_COLUMNS.has(prop || '')) return 'safe';
314
+ // The value of one of the page's own <select>s: one of its options.
315
+ if (prop === 'value' && SELECT_IDS.has(pickedId(node.object, scope) || '')) return 'safe';
316
+ if (prop === 'message' && isCatchParam(node.object, scope)) return 'error';
317
+ // labels().title - a property of what a call returns is judged by the
318
+ // call; (await res.json()).name by the body it was read from.
319
+ let base = node.object;
320
+ while (base && /MemberExpression$/.test(base.type)) base = base.object;
321
+ if (base && (/CallExpression$/.test(base.type) || base.type === 'AwaitExpression')) return again(base);
322
+ // An item's property is judged by that property in every item, even
323
+ // where the item itself is known only as a whole: inside a helper's
324
+ // map(), item.value can be an id in every item while item.label is a
325
+ // name (blind round 16, Meridian's field()).
326
+ const ofItems = itemPropertyOrigin(node, scope, code, depth);
327
+ if (ofItems) return ofItems;
328
+ const aliased = aliases && base && Object.prototype.hasOwnProperty.call(aliases, base.name);
329
+ const filled = !aliased && base && base.type === 'Identifier' ? objectPropertyOrigin(node, base, scope, code, depth, aliases) : null;
330
+ if (filled) return filled;
331
+ let first = node;
332
+ while (first.object && /MemberExpression$/.test(first.object.type)) first = first.object;
333
+ const named = first.object === base && !first.computed && first.property && first.property.type === 'Identifier';
334
+ // options.placeholder inside a call judged with its own arguments
335
+ // (argumentAliases): that call's object, that one property.
336
+ const written = aliases && base && named && Object.prototype.hasOwnProperty.call(aliases, OBJECT_ARG + base.name)
337
+ ? aliases[OBJECT_ARG + base.name] : null;
338
+ if (written) {
339
+ const p = written.node.properties.find((x) => (x.key.type === 'Identifier' ? x.key.name : x.key.value) === first.property.name);
340
+ return p ? classify(p.value, written.scope, code, depth + 1, written.aliases) : 'safe';
341
+ }
342
+ // options.placeholder, where every call of the function writes options
343
+ // out as an object: judged by what the calls give that one property.
344
+ if (!aliased && base && base.type === 'Identifier') {
345
+ if (named) {
346
+ const values = paramPropertyValues(base, first.property.name, scope);
347
+ if (values) return worst(values.map((v) => classify(v.node, v.scope, code, depth + 1, aliases)));
348
+ }
349
+ }
350
+ return fromBinding(rootIdentifier(node), scope, code, depth, aliases);
351
+ }
352
+ case 'Identifier':
353
+ return fromBinding(node, scope, code, depth, aliases);
354
+ case 'AwaitExpression':
355
+ return again(node.argument);
356
+ default:
357
+ return 'unknown';
358
+ }
359
+ }
360
+
361
+ const RANK = { safe: 0, unknown: 1, error: 2, network: 3 };
362
+ function worst(list) {
363
+ return (list || []).reduce((a, b) => (RANK[b] > RANK[a] ? b : a), 'safe');
364
+ }
365
+
366
+ function returnedBy(fn) {
367
+ if (!fn || !/Function/.test(fn.type)) return null;
368
+ if (fn.body.type !== 'BlockStatement') return fn.body;
369
+ const ret = fn.body.body.find((s) => s.type === 'ReturnStatement');
370
+ return ret ? ret.argument : null;
371
+ }
372
+
373
+ /** The path of a function this file declares under `name`, or null. */
374
+ function localFunction(name, scope) {
375
+ const binding = scope && scope.getBinding(name);
376
+ if (!binding || !binding.path) return null;
377
+ const p = binding.path;
378
+ if (p.node.type === 'FunctionDeclaration') return p;
379
+ if (p.node.type === 'VariableDeclarator' && p.node.init && /Function/.test(p.node.init.type) &&
380
+ !(binding.constantViolations && binding.constantViolations.length)) {
381
+ return p.get('init');
382
+ }
383
+ return null;
384
+ }
385
+
386
+ /** Every value a function returns, with the scope to judge it in; nested functions excluded. */
387
+ function returnsOf(fnPath) {
388
+ if (fnPath.node.body.type !== 'BlockStatement') return [{ node: fnPath.node.body, scope: fnPath.scope }];
389
+ const found = [];
390
+ fnPath.traverse({
391
+ Function(p) {
392
+ p.skip();
393
+ },
394
+ ReturnStatement(p) {
395
+ if (p.node.argument) found.push({ node: p.node.argument, scope: p.scope });
396
+ },
397
+ });
398
+ return found;
399
+ }
400
+
401
+ // Every function in the piece being read, by node, so a callback handed to
402
+ // map() can be judged in its own scope - where its own `const color = ...`
403
+ // lives - instead of the caller's, where that name means nothing.
404
+ let FN_PATHS = new WeakMap();
405
+
406
+ /**
407
+ * list.map(cb).join(''): the callback's returns, each with its own scope, and
408
+ * what the callback's names stand for - the item is whatever the list holds,
409
+ * the index is a number. Null when node is not that shape.
410
+ */
411
+ function mapCallback(node, scope, code, depth, aliases) {
412
+ if (calleeName(node.callee) !== 'join' || !node.callee.object || !/CallExpression$/.test(node.callee.object.type) ||
413
+ calleeName(node.callee.object.callee) !== 'map') {
414
+ return null;
415
+ }
416
+ const mapCall = node.callee.object;
417
+ const fn = mapCall.arguments[0];
418
+ const listOrigin = classify(mapCall.callee.object, scope, code, depth + 1, aliases);
419
+ const inner = Object.assign({}, aliases || {});
420
+ const params = (fn && fn.params) || [];
421
+ if (params[0] && params[0].type === 'Identifier') inner[params[0].name] = listOrigin;
422
+ if (params[1] && params[1].type === 'Identifier') inner[params[1].name] = 'safe';
423
+ const fnPath = fn && FN_PATHS.get(fn);
424
+ const returns = fnPath
425
+ ? returnsOf(fnPath)
426
+ : (returnedBy(fn) ? [{ node: returnedBy(fn), scope: scope }] : []);
427
+ return { returns: returns, inner: inner };
428
+ }
429
+
430
+ /**
431
+ * Whether a call escapes HTML - by name for the well-known ones, and for a
432
+ * helper of this file's own, by what it does: every return is a replace()
433
+ * chain, its patterns cover & < and >, and it writes &amp; &lt; &gt;. The
434
+ * name decides nothing - `esc` and `clean3` count, and an "escape" that only
435
+ * handles "<", or escapes and then returns the original, does not.
436
+ * Returns { dq, sq }: whether " and ' are escaped too. Null when it does not escape.
437
+ */
438
+ function escaperOf(call, scope, code) {
439
+ if (!call || !/CallExpression$/.test(call.type)) return null;
440
+ const name = calleeName(call.callee);
441
+ if (MAKES_SAFE.test(name)) return { dq: true, sq: true };
442
+ if (call.callee.type !== 'Identifier') return null;
443
+ const fnPath = localFunction(call.callee.name, scope);
444
+ if (!fnPath) return null;
445
+ const returns = returnsOf(fnPath);
446
+ if (!returns.length || !returns.every((r) => /CallExpression$/.test(r.node.type) &&
447
+ /^(replace|replaceAll)$/.test(calleeName(r.node.callee)))) {
448
+ return null;
449
+ }
450
+ let patterns = '';
451
+ const written = [];
452
+ fnPath.traverse({
453
+ RegExpLiteral(p) {
454
+ patterns += p.node.pattern;
455
+ },
456
+ StringLiteral(p) {
457
+ written.push(p.node.value);
458
+ const parent = p.parent;
459
+ if (parent && /CallExpression$/.test(parent.type) && parent.arguments[0] === p.node &&
460
+ /^(replace|replaceAll)$/.test(calleeName(parent.callee))) {
461
+ patterns += p.node.value;
462
+ }
463
+ },
464
+ });
465
+ const writes = (entity) => written.some((s) => s.indexOf(entity) !== -1);
466
+ if (!/&/.test(patterns) || !/</.test(patterns) || !/>/.test(patterns)) return null;
467
+ if (!writes('&amp;') || !writes('&lt;') || !writes('&gt;')) return null;
468
+ return {
469
+ dq: /"/.test(patterns) && (writes('&quot;') || writes('&#34;') || writes('&#x22;')),
470
+ sq: /'/.test(patterns) && (writes('&#39;') || writes('&#x27;') || writes('&apos;')),
471
+ };
472
+ }
473
+
474
+ /**
475
+ * The quote an HTML attribute value is open in at the end of this text: '"',
476
+ * "'", 'bare' for an unquoted one, '' when the text is not inside a tag at all.
477
+ * Only inside a tag - after a "<" that no ">" has closed - is an "=" an
478
+ * attribute; the "=" of "/go?next=" in a URL string is not one.
479
+ */
480
+ function openAttribute(text) {
481
+ const lt = text.lastIndexOf('<');
482
+ if (lt === -1 || text.lastIndexOf('>') > lt) return '';
483
+ const tag = text.slice(lt);
484
+ const quoted = /=\s*(["'])[^"']*$/.exec(tag);
485
+ if (quoted) return quoted[1];
486
+ return /\s[^\s"'<>\/=]+\s*=\s*$/.test(tag) ? 'bare' : '';
487
+ }
488
+
489
+ /**
490
+ * The pieces of a template or a + concatenation to judge one by one. An
491
+ * escaped value is judged as its escaped input when the escaping is not
492
+ * enough for where it lands: inside a "..." attribute that needs " escaped,
493
+ * inside '...' that needs ' escaped, and an unquoted attribute is broken by a
494
+ * space no escaper touches.
495
+ */
496
+ function judgedParts(node, scope, code) {
497
+ const pairs = [];
498
+ if (node.type === 'TemplateLiteral') {
499
+ // Everything written before this value, so an attribute opened in an
500
+ // earlier piece - `<a title="${a}" href="${b}"` - is still seen as open.
501
+ let before = '';
502
+ node.expressions.forEach((e, i) => {
503
+ before += node.quasis[i].value.raw;
504
+ pairs.push({ before: before, value: e });
505
+ before += 'x';
506
+ });
507
+ } else {
508
+ const text = (n) => (n.type === 'StringLiteral' ? n.value
509
+ : n.type === 'TemplateLiteral' ? n.quasis[n.quasis.length - 1].value.raw : '');
510
+ pairs.push({ before: '', value: node.left });
511
+ pairs.push({ before: text(node.left), value: node.right });
512
+ }
513
+ return pairs.map(({ before, value }) => {
514
+ const esc = escaperOf(value, scope, code);
515
+ if (!esc) return value;
516
+ const quote = openAttribute(before);
517
+ const enough = quote === '' || (quote === '"' && esc.dq) || (quote === "'" && esc.sq);
518
+ return enough ? { type: 'StringLiteral' } : (value.arguments[0] || value);
519
+ });
520
+ }
521
+
522
+ /**
523
+ * Which parts of a value make it unsafe, in the words of the code - so a fix
524
+ * prompt can say "only ${log.caller_number}" instead of quoting sixty lines of
525
+ * template and leaving the reader to find it. At most five, never repeated.
526
+ */
527
+ function riskyParts(node, scope, code, aliases, out, depth) {
528
+ if (!node || out.length >= 5 || depth > MAX_DEPTH) return;
529
+ const origin = classify(node, scope, code, 0, aliases);
530
+ if (origin === 'safe') return;
531
+ const go = (n, s, a) => riskyParts(n, s || scope, code, a || aliases, out, depth + 1);
532
+ if (node.type === 'TemplateLiteral' || (node.type === 'BinaryExpression' && node.operator === '+')) {
533
+ judgedParts(node, scope, code).forEach((p) => go(p));
534
+ return;
535
+ }
536
+ if (node.type === 'ConditionalExpression') { go(node.consequent); go(node.alternate); return; }
537
+ if (node.type === 'LogicalExpression') { go(node.left); go(node.right); return; }
538
+ if (/CallExpression$/.test(node.type)) {
539
+ const mapped = mapCallback(node, scope, code, depth, aliases);
540
+ if (mapped && mapped.returns.length) {
541
+ mapped.returns.forEach((r) => go(r.node, r.scope, mapped.inner));
542
+ return;
543
+ }
544
+ }
545
+ const text = code.slice(node.start, node.end).replace(/\s+/g, ' ').slice(0, 80);
546
+ if (!out.some((p) => p.text === text)) out.push({ text: text, origin: origin, line: node.loc ? node.loc.start.line : null });
547
+ }
548
+
549
+ function rootIdentifier(node) {
550
+ let n = node;
551
+ while (n && /MemberExpression$/.test(n.type)) n = n.object;
552
+ return n && n.type === 'Identifier' ? n : null;
553
+ }
554
+
555
+ function isCatchParam(node, scope) {
556
+ const id = rootIdentifier(node) || (node && node.type === 'Identifier' ? node : null);
557
+ if (!id || !scope) return false;
558
+ const binding = scope.getBinding(id.name);
559
+ return !!(binding && binding.path && binding.path.type === 'CatchClause');
560
+ }
561
+
562
+ // Bindings whose values are being followed right now, so a variable assigned
563
+ // from itself (count = count + 1) is not followed round in a circle.
564
+ const RESOLVING = new Set();
565
+
566
+ // The project being read, for a value imported from another of its files:
567
+ // where each file's names lead, and which of them anything ever writes to.
568
+ // Set by scanProject for the length of one read, like FN_PATHS.
569
+ let IMPORTS = null;
570
+
571
+ // The ids that, on every page of the project that uses them, name a <select>.
572
+ // Set for each scan by scanProject.
573
+ let SELECT_IDS = new Set();
574
+
575
+ /**
576
+ * The ids of the pages' <select> elements - and only those no page also gives
577
+ * to anything else. A select's value is one of the options the page wrote;
578
+ * the person can only choose among them.
579
+ *
580
+ * Found once the items unshifted into a list were judged (round 13's console):
581
+ * the new incident's severity came from a <select> of four fixed options, and
582
+ * was reported as text of unknown origin.
583
+ */
584
+ function selectIdsOf(pages) {
585
+ const tags = new Map();
586
+ for (const page of pages || []) {
587
+ const re = /<([a-zA-Z][\w-]*)\b[^>]*\sid\s*=\s*["']([^"']+)["'][^>]*>/g;
588
+ let m;
589
+ while ((m = re.exec(page.source))) {
590
+ if (!tags.has(m[2])) tags.set(m[2], new Set());
591
+ tags.get(m[2]).add(/contenteditable/i.test(m[0]) ? 'editable' : m[1].toLowerCase());
592
+ }
593
+ }
594
+ const out = new Set();
595
+ for (const [id, set] of tags) if (set.size === 1 && set.has('select')) out.add(id);
596
+ return out;
597
+ }
598
+
599
+ /** The id a node picks out - document.querySelector('#x'), getElementById('x'), or a const holding one - or null. */
600
+ function pickedId(node, scope, depth) {
601
+ if (!node || (depth || 0) > 4) return null;
602
+ if (node.type === 'Identifier') {
603
+ const b = scope && scope.getBinding(node.name);
604
+ if (!b || b.kind !== 'const' || (b.constantViolations && b.constantViolations.length)) return null;
605
+ return pickedId(b.path.node.init, b.path.scope, (depth || 0) + 1);
606
+ }
607
+ if (!/CallExpression$/.test(node.type) || !node.arguments[0] || node.arguments[0].type !== 'StringLiteral') return null;
608
+ const name = calleeName(node.callee);
609
+ const arg = node.arguments[0].value;
610
+ if (name === 'getElementById') return arg;
611
+ if (name === 'querySelector' && /^#[\w-]+$/.test(arg)) return arg.slice(1);
612
+ return null;
613
+ }
614
+ // Which file each parsed program is, so an import is resolved from the file
615
+ // that wrote it - which, once a helper in another folder is being judged, is
616
+ // not the file the sink is in.
617
+ let PROGRAM_FILE = new WeakMap();
618
+
619
+ /**
620
+ * Fixed data another file of the project exports - `export const demo = {...}`
621
+ * of nothing but literals - is as safe as those literals, and only while no
622
+ * file writes to it. Found on a blind test (LaunchRail): mock-data.js exported
623
+ * the demo workspace, ui.js rendered it through a shell() helper, and the
624
+ * import was read as unknown - so a safe page was reported.
625
+ *
626
+ * What is followed, and what is not:
627
+ * - a named import of a `const` declared at the top of a project file;
628
+ * - nothing at all if any file of the project could not be read, since a
629
+ * write could be in that file (IMPORTS.blind);
630
+ * - a write anywhere - through the import, any other file's import of it,
631
+ * a namespace import, a local name given to part of it, or the defining
632
+ * file itself - makes it unknown again (IMPORTS.written).
633
+ * Handing it out - `return demo.flags` - is a read, and is not followed into
634
+ * whoever receives it. That is the one place a write could still be missed: a
635
+ * caller that pushes into the very list it was returned. Writing into shared
636
+ * fixed data that way is rare enough to accept here, and is said so.
637
+ */
638
+ function fromImport(binding, depth) {
639
+ if (!IMPORTS || IMPORTS.blind) return 'unknown';
640
+ const spec = binding.path && binding.path.node;
641
+ if (!spec || spec.type !== 'ImportSpecifier') return 'unknown';
642
+ const program = binding.scope && binding.scope.getProgramParent();
643
+ const here = program && PROGRAM_FILE.get(program.block);
644
+ if (!here) return 'unknown';
645
+ const decl = binding.path.parentPath && binding.path.parentPath.node;
646
+ const from = decl && decl.source && decl.source.value;
647
+ const name = spec.imported && (spec.imported.name || spec.imported.value);
648
+ const found = from && name ? IMPORTS.constOf(here, from, name) : null;
649
+ if (!found) return 'unknown';
650
+ if (IMPORTS.written.has(found.full + '::' + name) || IMPORTS.written.has(found.full + '::*')) return 'unknown';
651
+ return classify(found.init, found.scope, found.code, depth + 1);
652
+ }
653
+
654
+ /** What a name was set to, followed one step back when that says anything. */
655
+ function fromBinding(id, scope, code, depth, aliases) {
656
+ if (id && aliases && Object.prototype.hasOwnProperty.call(aliases, id.name)) return aliases[id.name];
657
+ if (!id || !scope) return 'unknown';
658
+ const binding = scope.getBinding(id.name);
659
+ if (!binding) return 'unknown';
660
+ if (binding.path && binding.path.type === 'CatchClause') return 'error';
661
+ if (binding.kind === 'param') return fromCallback(binding, code, depth) || fromCalls(binding, code, depth);
662
+ if (binding.kind === 'module') return fromImport(binding, depth);
663
+ // for (const order of list): an item of the list.
664
+ const loop = forOfList(binding);
665
+ if (loop) return listOrigin(loop.node, loop.scope, code, depth + 1);
666
+ const init = binding.path && binding.path.node && binding.path.node.init;
667
+ const later = binding.constantViolations || [];
668
+ if (!init && !later.length) return 'unknown';
669
+ // A list the code adds to: as dangerous as what it starts with and every
670
+ // item pushed or unshifted into it. Found on blind round 14: a fixed list of
671
+ // orders, and a form that unshifted a new one built from what was typed -
672
+ // judged by its first value alone, the typed name would have read as safe.
673
+ const added = later.length ? [] : addedItems(binding);
674
+ if (added.length) {
675
+ return worst([classify(init, binding.path.scope, code, depth + 1, aliases)]
676
+ .concat(added.map((a) => classify(a.node, a.scope, code, depth + 1, aliases))));
677
+ }
678
+ if (init && readsResponseBody(init)) return 'network';
679
+ // Reassigned later: as dangerous as the worst value it is ever given. Found
680
+ // on a blind test: `let notes = []`, then `notes = data` from the database,
681
+ // then rendered - read as "unknown" because the first value was an empty
682
+ // list. Only plain `=` and `+=` are followed; anything else - a destructure,
683
+ // a for-of - stays unknown, because what it assigns is not in one place.
684
+ if (later.length) {
685
+ if (RESOLVING.has(binding)) return 'safe'; // x = x + 1: itself adds nothing new
686
+ RESOLVING.add(binding);
687
+ try {
688
+ const origins = [];
689
+ if (init) origins.push(classify(init, binding.path.scope, code, depth + 1, aliases));
690
+ for (const v of later) {
691
+ const node = v.node;
692
+ if (node.type === 'UpdateExpression') continue; // x++ holds a number
693
+ if (node.type !== 'AssignmentExpression' || node.left.type !== 'Identifier' ||
694
+ (node.operator !== '=' && node.operator !== '+=')) return 'unknown';
695
+ origins.push(classify(node.right, v.scope, code, depth + 1, aliases));
696
+ }
697
+ return worst(origins);
698
+ } finally {
699
+ RESOLVING.delete(binding);
700
+ }
701
+ }
702
+ // An object the code fills in later: as dangerous as what it starts with
703
+ // and every value written into it. Found on blind round 16 (Meridian):
704
+ // `const state = { sites: [] }`, then `state.sites = data` from Supabase,
705
+ // then a site's name rendered - judged by the empty list it started with,
706
+ // a name from the database read as safe. Only `state.x = value` is
707
+ // followed; written through any other way, what it holds is not in one
708
+ // place.
709
+ if (init && /^(ObjectExpression|ArrayExpression)$/.test(init.type)) {
710
+ const writes = (binding.referencePaths || []).filter((r) => writtenThrough(r));
711
+ if (writes.length) {
712
+ if (RESOLVING.has(binding)) return 'safe';
713
+ RESOLVING.add(binding);
714
+ try {
715
+ const origins = [classify(init, binding.path.scope, code, depth + 1, aliases)];
716
+ for (const r of writes) {
717
+ const member = r.parentPath;
718
+ const assign = member && member.parentPath;
719
+ if (!member || !/MemberExpression$/.test(member.node.type) || member.node.object !== r.node ||
720
+ !assign || assign.node.type !== 'AssignmentExpression' || assign.node.left !== member.node ||
721
+ assign.node.operator !== '=') {
722
+ return 'unknown';
723
+ }
724
+ origins.push(classify(assign.node.right, assign.scope, code, depth + 1, aliases));
725
+ }
726
+ return worst(origins);
727
+ } finally {
728
+ RESOLVING.delete(binding);
729
+ }
730
+ }
731
+ }
732
+ // Destructured from a response body: const { name } = await res.json()
733
+ // Aliases carry through: inside a map() callback, `const t = r.title` is as
734
+ // dangerous as the item r it was read from.
735
+ return classify(init, binding.path.scope, code, depth + 1, aliases);
736
+ }
737
+
738
+ /**
739
+ * state.page, where state is an object the code declared and fills in: judged
740
+ * by what it starts with under that name and every write to that name -
741
+ * state.page = 1, state.page += 1, state.page++ - and not by what is written
742
+ * under its other names. Null when the object is written any other way
743
+ * (Object.assign(state, ...), state[key] = ...), or is not that kind of name.
744
+ *
745
+ * Found on blind round 16, once filled-in objects were followed: state.page,
746
+ * a page number, read as unknown because state.tickets was filled from the
747
+ * database.
748
+ */
749
+ function objectPropertyOrigin(node, base, scope, code, depth, aliases) {
750
+ let first = node;
751
+ while (first.object && /MemberExpression$/.test(first.object.type)) first = first.object;
752
+ if (first.object !== base || first.computed || !first.property || first.property.type !== 'Identifier') return null;
753
+ const prop = first.property.name;
754
+ const binding = scope && scope.getBinding(base.name);
755
+ if (!binding || binding.kind === 'param' || binding.kind === 'module' ||
756
+ (binding.constantViolations && binding.constantViolations.length)) return null;
757
+ const init = binding.path && binding.path.node && binding.path.node.init;
758
+ if (!init || init.type !== 'ObjectExpression' ||
759
+ init.properties.some((p) => p.type !== 'ObjectProperty' || p.computed)) return null;
760
+ if (RESOLVING.has(node)) return 'safe';
761
+ RESOLVING.add(node);
762
+ try {
763
+ const own = init.properties.find((p) => (p.key.type === 'Identifier' ? p.key.name : p.key.value) === prop);
764
+ const origins = [own ? classify(own.value, binding.path.scope, code, depth + 1) : 'safe'];
765
+ for (const ref of binding.referencePaths || []) {
766
+ if (!writtenThrough(ref)) continue;
767
+ const member = ref.parentPath;
768
+ if (!member || !/MemberExpression$/.test(member.node.type) || member.node.object !== ref.node || member.node.computed) return null;
769
+ if (member.node.property.name !== prop) continue;
770
+ const holder = member.parentPath;
771
+ if (holder.node.type === 'UpdateExpression') continue; // state.page++ holds a number
772
+ if (holder.node.type === 'AssignmentExpression' && holder.node.left === member.node) {
773
+ if (holder.node.operator === '=' || holder.node.operator === '+=') {
774
+ origins.push(classify(holder.node.right, holder.scope, code, depth + 1, aliases));
775
+ continue;
776
+ }
777
+ if (/^[-*/%]=$/.test(holder.node.operator)) continue; // arithmetic: a number
778
+ }
779
+ return 'unknown'; // state.items.push(...), state.page.x = ...: not followed here
780
+ }
781
+ return worst(origins);
782
+ } finally {
783
+ RESOLVING.delete(node);
784
+ }
785
+ }
786
+
787
+ // Array methods that hand their callback the list's own items.
788
+ const ITEM_CALLBACKS = /^(map|forEach|filter|find|findLast|findIndex|findLastIndex|some|every|flatMap|sort|toSorted)$/;
789
+
790
+ /**
791
+ * A parameter of a callback handed to list.map(...) and its kin: the item is
792
+ * whatever the list holds, the index a number, the third the list itself.
793
+ * Null when the parameter is not that.
794
+ *
795
+ * Found on a blind test (Northstar): pageRows.map(row => `...${severityClass(row.severity)}...`).
796
+ * The helper's parameter was followed to its call, and there `row` was a
797
+ * parameter of an arrow nobody names - "unknown" - though pageRows only ever
798
+ * held the file's own fixed list. The map().join() reading knew what row was;
799
+ * a name followed back into the same callback did not.
800
+ */
801
+ function fromCallback(binding, code, depth) {
802
+ const fn = binding.path && binding.path.parentPath;
803
+ if (!fn || !/Function/.test(fn.node.type)) return null;
804
+ const call = fn.parentPath;
805
+ if (!call || !/CallExpression$/.test(call.node.type) || call.node.arguments[0] !== fn.node) return null;
806
+ const method = calleeName(call.node.callee);
807
+ if (!/MemberExpression$/.test(call.node.callee.type) || !ITEM_CALLBACKS.test(method)) return null;
808
+ const index = fn.node.params.indexOf(binding.path.node);
809
+ const list = () => classify(call.node.callee.object, call.scope, code, depth + 1);
810
+ if (index === 0 || (index === 1 && /^(sort|toSorted)$/.test(method))) return list();
811
+ if (index === 1) return 'safe';
812
+ if (index === 2) return list();
813
+ return null;
814
+ }
815
+
816
+ /** for (const x of list): { node, scope } of the list, or null when x is not that. */
817
+ function forOfList(binding) {
818
+ const decl = binding && binding.path;
819
+ if (!decl || decl.node.type !== 'VariableDeclarator' || decl.node.id.type !== 'Identifier') return null;
820
+ const declaration = decl.parentPath;
821
+ const loop = declaration && declaration.parentPath;
822
+ if (!loop || loop.node.type !== 'ForOfStatement' || loop.node.left !== declaration.node) return null;
823
+ return { node: loop.node.right, scope: loop.scope };
824
+ }
825
+
826
+ /**
827
+ * What the code pushes or unshifts into a list it declared, as { node, scope }
828
+ * per item. Only the two calls whose arguments become items are read; a list
829
+ * changed any other way is judged as before.
830
+ */
831
+ function addedItems(binding) {
832
+ const out = [];
833
+ if (!binding || binding.kind !== 'const') return out;
834
+ for (const ref of binding.referencePaths || []) {
835
+ const member = ref.parentPath;
836
+ if (!member || !/MemberExpression$/.test(member.node.type) || member.node.object !== ref.node) continue;
837
+ // list[i] = value
838
+ const holder = member.parentPath;
839
+ if (member.node.computed && holder && holder.node.type === 'AssignmentExpression' && holder.node.left === member.node) {
840
+ out.push({ node: holder.node.right, scope: holder.scope });
841
+ continue;
842
+ }
843
+ const call = holder;
844
+ if (member.node.computed || !call || !/CallExpression$/.test(call.node.type) || call.node.callee !== member.node) continue;
845
+ // The calls that put new values in: every argument of push / unshift /
846
+ // add / set / fill (Map.set(key, value) - both), and splice's from the third.
847
+ const name = member.node.property.name;
848
+ const from = name === 'splice' ? 2 : /^(push|unshift|add|set|fill)$/.test(name) ? 0 : -1;
849
+ if (from < 0) continue;
850
+ for (const arg of call.node.arguments.slice(from)) out.push({ node: arg.type === 'SpreadElement' ? arg.argument : arg, scope: call.scope });
851
+ }
852
+ return out;
853
+ }
854
+
855
+ const SAME_ITEMS = /^(filter|slice|sort|toSorted|reverse|toReversed)$/;
856
+
857
+ // The key under which argumentAliases keeps an object written out in a call,
858
+ // beside the parameter's own name. Not a name any code can have.
859
+ const OBJECT_ARG = '\u0000object:';
860
+
861
+ /**
862
+ * A function's parameters as one call fills them: each name judged by the
863
+ * argument this call passes (its default when left out, undefined when it has
864
+ * none), and an object literal also kept whole under OBJECT_ARG, so a
865
+ * property of it is judged alone. A parameter that is not a plain name, or
866
+ * one behind a spread, is left to be judged from every call.
867
+ */
868
+ function argumentAliases(fn, args, scope, fnScope, code, depth, aliases) {
869
+ const inner = Object.assign({}, aliases || {});
870
+ const params = (fn && fn.params) || [];
871
+ for (let i = 0; i < params.length; i++) {
872
+ if ((args || []).slice(0, i + 1).some((a) => a.type === 'SpreadElement')) break;
873
+ const param = params[i];
874
+ const id = param.type === 'AssignmentPattern' ? param.left : param;
875
+ if (id.type !== 'Identifier') continue;
876
+ delete inner[OBJECT_ARG + id.name];
877
+ const arg = args[i];
878
+ const source = arg ? { node: arg, scope: scope, aliases: aliases }
879
+ : param.type === 'AssignmentPattern' ? { node: param.right, scope: fnScope, aliases: aliases } : null;
880
+ inner[id.name] = source ? classify(source.node, source.scope, code, depth + 1, source.aliases) : 'safe';
881
+ if (source && source.node.type === 'ObjectExpression' &&
882
+ source.node.properties.every((p) => p.type === 'ObjectProperty' && !p.computed)) {
883
+ inner[OBJECT_ARG + id.name] = source;
884
+ }
885
+ }
886
+ return inner;
887
+ }
888
+
889
+ /**
890
+ * The calls of the function a parameter belongs to: what each passes in that
891
+ * place ({ arg, scope }, arg null when it is left out) and the parameter's
892
+ * own default. Null when the function is used any way but being called here.
893
+ */
894
+ function callsOfParam(binding) {
895
+ const fn = binding && binding.path && binding.path.parentPath;
896
+ if (!fn || !/Function/.test(fn.node.type)) return null;
897
+ const index = fn.node.params.indexOf(binding.path.node);
898
+ if (index === -1) return null;
899
+ let name = fn.node.id && fn.node.id.name;
900
+ if (!name && fn.parentPath && fn.parentPath.node.type === 'VariableDeclarator' && fn.parentPath.node.id.type === 'Identifier') {
901
+ name = fn.parentPath.node.id.name;
902
+ }
903
+ const fnBinding = name && fn.parentPath && fn.parentPath.scope.getBinding(name);
904
+ if (!fnBinding || (fnBinding.constantViolations && fnBinding.constantViolations.length)) return null;
905
+ const refs = fnBinding.referencePaths || [];
906
+ if (!refs.length) return null;
907
+ const calls = [];
908
+ for (const ref of refs) {
909
+ const call = ref.parent;
910
+ if (!call || !/CallExpression$/.test(call.type) || call.callee !== ref.node) return null;
911
+ if (call.arguments.slice(0, index + 1).some((a) => a.type === 'SpreadElement')) return null;
912
+ calls.push({ arg: call.arguments[index] || null, scope: ref.scope });
913
+ }
914
+ const fallback = binding.path.node.type === 'AssignmentPattern' ? { node: binding.path.node.right, scope: fn.scope } : null;
915
+ return { calls: calls, fallback: fallback };
916
+ }
917
+
918
+ /**
919
+ * options.prop, where options is a parameter: what every call gives that one
920
+ * property, as { node, scope } - nothing for a call that leaves it out. Null
921
+ * unless every call writes the argument out as an object literal right there.
922
+ *
923
+ * Found on blind round 16 (Meridian): field(label, name, type, options) built
924
+ * every form field from constant labels, a placeholder and a list of options
925
+ * whose values were ids - but one call's options also held a list read from
926
+ * the database, so the whole of options, and every field, read as unknown.
927
+ */
928
+ function paramPropertyValues(id, prop, scope) {
929
+ const binding = id && scope && scope.getBinding(id.name);
930
+ if (!binding || binding.kind !== 'param' || (binding.constantViolations && binding.constantViolations.length)) return null;
931
+ const found = callsOfParam(binding);
932
+ if (!found) return null;
933
+ const values = [];
934
+ for (const c of found.calls) {
935
+ const source = c.arg ? { node: c.arg, scope: c.scope } : found.fallback;
936
+ if (!source) continue; // left out, no default: undefined
937
+ if (source.node.type !== 'ObjectExpression' ||
938
+ source.node.properties.some((p) => p.type !== 'ObjectProperty' || p.computed)) return null;
939
+ const p = source.node.properties.find((x) => (x.key.type === 'Identifier' ? x.key.name : x.key.value) === prop);
940
+ if (p) values.push({ node: p.value, scope: source.scope });
941
+ }
942
+ return values;
943
+ }
944
+
945
+ /**
946
+ * Every item a list can hold, as { node, scope }: its literal elements and
947
+ * what is pushed into it, through filter / slice / sort and the file's own
948
+ * functions that return one of those. Null when that cannot be known - a
949
+ * spread, a list from somewhere else, a list changed by any other means.
950
+ */
951
+ function listItems(node, scope, depth) {
952
+ if (!node || !scope || depth > 8) return null;
953
+ if (node.type === 'ArrayExpression') {
954
+ if (node.elements.some((e) => !e)) return null;
955
+ // [first, ...more]: what is spread in is items too, when it can be listed.
956
+ const all = [];
957
+ for (const e of node.elements) {
958
+ if (e.type !== 'SpreadElement') {
959
+ all.push({ node: e, scope: scope });
960
+ continue;
961
+ }
962
+ const spread = listItems(e.argument, scope, depth + 1);
963
+ if (!spread) return null;
964
+ all.push(...spread);
965
+ }
966
+ return all;
967
+ }
968
+ // list || []: either one.
969
+ if (node.type === 'LogicalExpression' && (node.operator === '||' || node.operator === '??')) {
970
+ const left = listItems(node.left, scope, depth + 1);
971
+ const right = left && listItems(node.right, scope, depth + 1);
972
+ return left && right ? left.concat(right) : null;
973
+ }
974
+ // options.items, where every call writes options out (paramPropertyValues).
975
+ if (/MemberExpression$/.test(node.type) && !node.computed && node.object.type === 'Identifier' && node.property.type === 'Identifier') {
976
+ const values = paramPropertyValues(node.object, node.property.name, scope);
977
+ if (!values) return null;
978
+ const all = [];
979
+ for (const v of values) {
980
+ const items = listItems(v.node, v.scope, depth + 1);
981
+ if (!items) return null;
982
+ all.push(...items);
983
+ }
984
+ return all;
985
+ }
986
+ if (/CallExpression$/.test(node.type)) {
987
+ const callee = node.callee;
988
+ if (/MemberExpression$/.test(callee.type) && SAME_ITEMS.test(calleeName(callee))) return listItems(callee.object, scope, depth + 1);
989
+ // sites.map(site => ({ value: site.id, label: site.name })): the items
990
+ // are what the callback returns, judged where the callback runs - so
991
+ // site.id is an id of a site, whatever else a site holds.
992
+ if (/MemberExpression$/.test(callee.type) && calleeName(callee) === 'map' && node.arguments[0] &&
993
+ /Function/.test(node.arguments[0].type)) {
994
+ const fnPath = FN_PATHS.get(node.arguments[0]);
995
+ if (!fnPath) return null;
996
+ const returns = returnsOf(fnPath);
997
+ return returns.length ? returns : null;
998
+ }
999
+ const local = callee.type === 'Identifier' ? localFunction(callee.name, scope) : null;
1000
+ if (!local) return null;
1001
+ const all = [];
1002
+ for (const r of returnsOf(local)) {
1003
+ const items = listItems(r.node, r.scope, depth + 1);
1004
+ if (!items) return null;
1005
+ all.push(...items);
1006
+ }
1007
+ return all.length ? all : null;
1008
+ }
1009
+ if (node.type === 'Identifier') {
1010
+ const binding = scope.getBinding(node.name);
1011
+ if (!binding || binding.kind !== 'const' || (binding.constantViolations && binding.constantViolations.length)) return null;
1012
+ const init = binding.path && binding.path.node && binding.path.node.init;
1013
+ const items = init && listItems(init, binding.path.scope, depth + 1);
1014
+ if (!items) return null;
1015
+ // Changed some other way than push / unshift: what it holds is not in one place.
1016
+ for (const ref of binding.referencePaths || []) {
1017
+ const member = ref.parentPath;
1018
+ const isAdd = member && /MemberExpression$/.test(member.node.type) && member.node.object === ref.node &&
1019
+ !member.node.computed && /^(push|unshift)$/.test(member.node.property.name) &&
1020
+ member.parentPath && /CallExpression$/.test(member.parentPath.node.type) && member.parentPath.node.callee === member.node;
1021
+ if (!isAdd && writtenThrough(ref)) return null;
1022
+ }
1023
+ return items.concat(addedItems(binding));
1024
+ }
1025
+ return null;
1026
+ }
1027
+
1028
+ /** A list's items, judged together - or the list itself when its items cannot be listed. */
1029
+ function listOrigin(node, scope, code, depth) {
1030
+ const items = listItems(node, scope, 0);
1031
+ if (items) return worst(items.map((i) => classify(i.node, i.scope, code, depth + 1)));
1032
+ return classify(node, scope, code, depth + 1);
1033
+ }
1034
+
1035
+ /**
1036
+ * item.prop, where item is one of a list's items - a for-of variable, or the
1037
+ * item a map() / filter() / forEach() callback is handed: judged by that
1038
+ * property in every item, not by the whole item. Null when the items are not
1039
+ * all object literals that set it.
1040
+ *
1041
+ * Found on blind round 14: orders were written with order.status and
1042
+ * order.created, which every order - the fixed ones and the one the form adds
1043
+ * - sets to a fixed word; the customer's name, typed into the form, is
1044
+ * escaped. The row was reported as text of unknown origin.
1045
+ */
1046
+ function itemPropertyOrigin(node, scope, code, depth) {
1047
+ let m = node;
1048
+ while (m && /MemberExpression$/.test(m.type) && m.object && /MemberExpression$/.test(m.object.type)) m = m.object;
1049
+ if (!m || !m.object || m.object.type !== 'Identifier' || m.computed || !m.property) return null;
1050
+ const prop = m.property.name;
1051
+ const binding = scope && scope.getBinding(m.object.name);
1052
+ if (!binding) return null;
1053
+ let list = forOfList(binding);
1054
+ if (!list && binding.kind === 'param') {
1055
+ const fn = binding.path && binding.path.parentPath;
1056
+ const call = fn && fn.parentPath;
1057
+ if (fn && /Function/.test(fn.node.type) && fn.node.params[0] === binding.path.node && call &&
1058
+ /CallExpression$/.test(call.node.type) && call.node.arguments[0] === fn.node &&
1059
+ /MemberExpression$/.test(call.node.callee.type) && ITEM_CALLBACKS.test(calleeName(call.node.callee))) {
1060
+ list = { node: call.node.callee.object, scope: call.scope };
1061
+ }
1062
+ }
1063
+ if (!list) return null;
1064
+ const items = listItems(list.node, list.scope, 0);
1065
+ if (!items || !items.length) return null;
1066
+ const values = [];
1067
+ for (const item of items) {
1068
+ if (item.node.type !== 'ObjectExpression' || item.node.properties.some((p) => p.type !== 'ObjectProperty' || p.computed)) return null;
1069
+ const p = item.node.properties.find((x) => (x.key.type === 'Identifier' ? x.key.name : x.key.value) === prop);
1070
+ if (!p) return null;
1071
+ values.push(classify(p.value, item.scope, code, depth + 1));
1072
+ }
1073
+ return worst(values);
1074
+ }
1075
+
1076
+ /**
1077
+ * A parameter is as dangerous as the worst thing any call passes it. Every
1078
+ * use of the function has to be a call this file makes: one handed on as a
1079
+ * value - a callback, an export, an event handler - is called from somewhere
1080
+ * the code does not show, so its parameter stays unknown.
1081
+ */
1082
+ function fromCalls(binding, code, depth) {
1083
+ const fn = binding.path && binding.path.parentPath;
1084
+ if (!fn || !/Function/.test(fn.node.type)) return 'unknown';
1085
+ const index = fn.node.params.indexOf(binding.path.node);
1086
+ if (index === -1) return 'unknown';
1087
+ let name = fn.node.id && fn.node.id.name;
1088
+ if (!name && fn.parentPath && fn.parentPath.node.type === 'VariableDeclarator' && fn.parentPath.node.id.type === 'Identifier') {
1089
+ name = fn.parentPath.node.id.name;
1090
+ }
1091
+ const fnBinding = name && fn.parentPath && fn.parentPath.scope.getBinding(name);
1092
+ if (!fnBinding || (fnBinding.constantViolations && fnBinding.constantViolations.length)) return 'unknown';
1093
+ const refs = fnBinding.referencePaths || [];
1094
+ if (!refs.length) return 'unknown';
1095
+ const origins = [];
1096
+ for (const ref of refs) {
1097
+ const call = ref.parent;
1098
+ if (!call || !/CallExpression$/.test(call.type) || call.callee !== ref.node) return 'unknown';
1099
+ const arg = call.arguments[index];
1100
+ if (!arg) {
1101
+ origins.push('safe'); // not passed: undefined
1102
+ continue;
1103
+ }
1104
+ if (call.arguments.slice(0, index + 1).some((a) => a.type === 'SpreadElement')) return 'unknown';
1105
+ origins.push(classify(arg, ref.scope, code, depth + 1));
1106
+ }
1107
+ return worst(origins);
1108
+ }
1109
+
1110
+ function readsResponseBody(node) {
1111
+ let n = node;
1112
+ if (n && n.type === 'AwaitExpression') n = n.argument;
1113
+ if (!n || !/CallExpression$/.test(n.type)) return false;
1114
+ const name = calleeName(n.callee);
1115
+ if (name === 'json' || name === 'text') return true;
1116
+ // res.json().catch(() => ({})) - the body read, with a fallback for when it
1117
+ // is not JSON. Still the server's words whenever it is.
1118
+ if ((name === 'catch' || name === 'finally') && n.callee.type === 'MemberExpression') {
1119
+ return readsResponseBody(n.callee.object);
1120
+ }
1121
+ // (await fetch(url)).json() and fetch(url).then(r => r.json())
1122
+ if (name === 'then') return (n.arguments || []).some((fn) => {
1123
+ const body = returnedBy(fn);
1124
+ return body && readsResponseBody(body);
1125
+ });
1126
+ // Found on a blind test: const { data } = await supabase.from('notes')
1127
+ // .select(...) is rows straight from the database, and was judged "unknown".
1128
+ if (queriesSupabase(n)) return true;
1129
+ // axios.get(url) - its .data is the server's body.
1130
+ const callee = n.callee;
1131
+ if (callee.type === 'Identifier' && callee.name === 'axios') return true;
1132
+ if (callee.type === 'MemberExpression' && callee.object.type === 'Identifier' && callee.object.name === 'axios' &&
1133
+ /^(get|post|put|patch|delete|head|request)$/.test(calleeName(callee))) return true;
1134
+ return false;
1135
+ }
1136
+
1137
+ // What a Supabase query chain does after .from('table'). Required, so that
1138
+ // Array.from(x) or somebody's own .from() is not read as the database.
1139
+ const QUERY_STEPS = /^(select|insert|update|upsert|delete|eq|neq|gt|gte|lt|lte|like|ilike|is|in|contains|containedBy|match|filter|or|not|order|limit|range|single|maybeSingle|textSearch|csv|throwOnError|returns|abortSignal)$/;
1140
+
1141
+ /** supabase.from('notes').select(...)... or supabase.rpc('fn', ...). */
1142
+ function queriesSupabase(node) {
1143
+ let c = node;
1144
+ while (c && /CallExpression$/.test(c.type) && c.callee && /MemberExpression$/.test(c.callee.type)) {
1145
+ const step = calleeName(c.callee);
1146
+ const inner = c.callee.object;
1147
+ if (step === 'rpc' && c.arguments[0] && /StringLiteral|TemplateLiteral/.test(c.arguments[0].type)) return true;
1148
+ if (QUERY_STEPS.test(step) && inner && /CallExpression$/.test(inner.type) && calleeName(inner.callee) === 'from' &&
1149
+ inner.callee.type === 'MemberExpression' && inner.arguments[0] &&
1150
+ /StringLiteral|TemplateLiteral/.test(inner.arguments[0].type)) return true;
1151
+ c = inner;
1152
+ }
1153
+ return false;
1154
+ }
1155
+
1156
+ /**
1157
+ * When the value is a parameter of the function it sits in - a helper such as
1158
+ * setStatus(html) { box.innerHTML = html } - which function, and which place
1159
+ * in its argument list. Null for anything else.
1160
+ */
1161
+ function paramOf(value, scope) {
1162
+ if (!value || value.type !== 'Identifier' || !scope) return null;
1163
+ const binding = scope.getBinding(value.name);
1164
+ if (!binding || binding.kind !== 'param' || !binding.path) return null;
1165
+ const fn = binding.path.parentPath;
1166
+ if (!fn || !/Function/.test(fn.node.type)) return null;
1167
+ const index = fn.node.params.indexOf(binding.path.node);
1168
+ if (index === -1) return null;
1169
+ let name = fn.node.id && fn.node.id.name;
1170
+ if (!name && fn.parentPath && fn.parentPath.node.type === 'VariableDeclarator' && fn.parentPath.node.id.type === 'Identifier') {
1171
+ name = fn.parentPath.node.id.name;
1172
+ }
1173
+ return name ? { fn: name, index: index } : null;
1174
+ }
1175
+
1176
+ /** Everything in one piece of code that turns a non-literal value into HTML. */
1177
+ /* -------------------------- open redirects -------------------------- */
1178
+ //
1179
+ // Found on a blind test: after signing in, the page sent the browser to
1180
+ // new URLSearchParams(location.search).get('next') - wherever a link said.
1181
+ // A phishing link then lands someone on the attacker's page straight from
1182
+ // the real login, and a javascript: value runs in the page. Reported only
1183
+ // when the address is taken from the page's own URL, and not when the code
1184
+ // checks it first: a redirect to a fixed page is the feature.
1185
+
1186
+ /** location, window.location, document.location. */
1187
+ function isLocation(node) {
1188
+ if (!node) return false;
1189
+ if (node.type === 'Identifier') return node.name === 'location';
1190
+ return node.type === 'MemberExpression' && !node.computed && node.property.name === 'location' &&
1191
+ node.object.type === 'Identifier' && /^(window|document|self|top)$/.test(node.object.name);
1192
+ }
1193
+
1194
+ /** Is this address taken from the page's own URL, from its start? */
1195
+ function readsUrl(node, scope, depth) {
1196
+ if (!node || depth > 8) return false;
1197
+ const again = (n) => readsUrl(n, scope, depth + 1);
1198
+ switch (node.type) {
1199
+ case 'MemberExpression':
1200
+ case 'OptionalMemberExpression': {
1201
+ const prop = !node.computed && node.property ? node.property.name : '';
1202
+ if ((prop === 'search' || prop === 'hash') && isLocation(node.object)) return true;
1203
+ if (prop === 'referrer' && node.object.type === 'Identifier' && node.object.name === 'document') return true;
1204
+ // Next's pages router: router.query.next
1205
+ let base = node.object;
1206
+ while (base && /MemberExpression$/.test(base.type)) {
1207
+ if (!base.computed && base.property.name === 'query' && base.object.type === 'Identifier' && base.object.name === 'router') return true;
1208
+ base = base.object;
1209
+ }
1210
+ return false;
1211
+ }
1212
+ case 'CallExpression':
1213
+ case 'OptionalCallExpression': {
1214
+ const name = calleeName(node.callee);
1215
+ if (name === 'get' && /MemberExpression$/.test(node.callee.type)) {
1216
+ const params = node.callee.object;
1217
+ if (params.type === 'NewExpression' && params.callee.name === 'URLSearchParams') return true;
1218
+ if (/MemberExpression$/.test(params.type) && !params.computed && params.property.name === 'searchParams') return true;
1219
+ if (params.type === 'Identifier' && scope) {
1220
+ const b = scope.getBinding(params.name);
1221
+ const init = b && b.path && b.path.node && b.path.node.init;
1222
+ if (init && init.type === 'NewExpression' && init.callee.name === 'URLSearchParams') return true;
1223
+ if (init && /MemberExpression$/.test(init.type) && !init.computed && init.property.name === 'searchParams') return true;
1224
+ // Next and React Router: const params = useSearchParams(), or
1225
+ // const [params] = useSearchParams().
1226
+ if (init && /CallExpression$/.test(init.type) && calleeName(init.callee) === 'useSearchParams') return true;
1227
+ }
1228
+ return false;
1229
+ }
1230
+ if (/^(decodeURIComponent|decodeURI|String)$/.test(name) && node.callee.type === 'Identifier') return again(node.arguments[0]);
1231
+ if (/^(trim|toString|slice|substring)$/.test(name) && /MemberExpression$/.test(node.callee.type)) return again(node.callee.object);
1232
+ return false; // anything else - isSafeUrl(x), sanitize(x) - is somebody's check
1233
+ }
1234
+ case 'LogicalExpression':
1235
+ return again(node.left) || again(node.right);
1236
+ case 'ConditionalExpression':
1237
+ return again(node.consequent) || again(node.alternate);
1238
+ case 'TemplateLiteral':
1239
+ // `login.html?next=${x}` starts somewhere fixed; `${x}` does not.
1240
+ return node.quasis[0].value.cooked === '' && node.expressions.length > 0 && again(node.expressions[0]);
1241
+ case 'BinaryExpression':
1242
+ return node.operator === '+' && again(node.left);
1243
+ case 'AwaitExpression':
1244
+ return again(node.argument);
1245
+ case 'Identifier': {
1246
+ const b = scope && scope.getBinding(node.name);
1247
+ if (!b || !b.path || b.kind === 'param') return false;
1248
+ const values = [];
1249
+ if (b.path.node && b.path.node.init) values.push(b.path.node.init);
1250
+ for (const v of b.constantViolations || []) if (v.node.type === 'AssignmentExpression') values.push(v.node.right);
1251
+ return values.some((v) => readsUrl(v, b.path.scope, depth + 1));
1252
+ }
1253
+ default:
1254
+ return false;
1255
+ }
1256
+ }
1257
+
1258
+ /**
1259
+ * Does the code check this name before sending the browser there? Any `if`
1260
+ * or `? :` around the redirect, or an earlier `if` in the same block, whose
1261
+ * test mentions it - an allow-list, a startsWith('/'), an origin compare.
1262
+ */
1263
+ function checkedFirst(p, value, code) {
1264
+ if (!value || value.type !== 'Identifier') return false;
1265
+ const word = new RegExp('\\b' + value.name.replace(/\$/g, '\\$') + '\\b');
1266
+ // A test that only asks whether there is a value - if (next) - checks
1267
+ // nothing about where it goes. It has to compare or match something.
1268
+ const VALIDATES = /startsWith|endsWith|\.test\(|includes|indexOf|match|origin|===|!==|allow|safe|valid|trusted/i;
1269
+ const mentions = (n) => {
1270
+ const text = n ? code.slice(n.start, n.end) : '';
1271
+ return word.test(text) && VALIDATES.test(text);
1272
+ };
1273
+ let child = p;
1274
+ for (let at = p.parentPath; at; child = at, at = at.parentPath) {
1275
+ const n = at.node;
1276
+ if ((n.type === 'IfStatement' || n.type === 'ConditionalExpression') && mentions(n.test)) return true;
1277
+ if (n.type === 'LogicalExpression' && n.operator === '&&' && child.node === n.right && mentions(n.left)) return true;
1278
+ if (n.type === 'BlockStatement' || n.type === 'Program') {
1279
+ const index = n.body.indexOf(child.node);
1280
+ if (n.body.slice(0, Math.max(0, index)).some((s) => s.type === 'IfStatement' && mentions(s.test))) return true;
1281
+ }
1282
+ if (/Function/.test(n.type)) break;
1283
+ }
1284
+ return false;
1285
+ }
1286
+
1287
+ /**
1288
+ * The helper a value is the result of: a call to a function this file
1289
+ * declares, or one it imports from a file of the project. Its returns, each
1290
+ * with its scope and its file's code, and the line where the first of them
1291
+ * that is not plain text is built. Null for anything else - an import from a
1292
+ * package, a default export, a function that cannot be found.
1293
+ */
1294
+ function helperOf(value, scope, code, file, lineOffset, resolver) {
1295
+ if (!value || !/CallExpression$/.test(value.type) || !value.callee || value.callee.type !== 'Identifier' || !scope) return null;
1296
+ const name = value.callee.name;
1297
+ let fnPath = localFunction(name, scope);
1298
+ let helper = { code: code, file: null, lineOffset: lineOffset };
1299
+ if (!fnPath) {
1300
+ const binding = scope.getBinding(name);
1301
+ const spec = binding && binding.kind === 'module' && binding.path && binding.path.node;
1302
+ if (!spec || spec.type !== 'ImportSpecifier' || !resolver) return null;
1303
+ const from = binding.path.parentPath && binding.path.parentPath.node.source && binding.path.parentPath.node.source.value;
1304
+ const imported = spec.imported && (spec.imported.name || spec.imported.value);
1305
+ const found = from && imported ? resolver(file, from, imported) : null;
1306
+ if (!found) return null;
1307
+ fnPath = found.fnPath;
1308
+ helper = { code: found.code, file: found.file, lineOffset: 1 };
1309
+ }
1310
+ const returns = returnsOf(fnPath);
1311
+ if (!returns.length) return null;
1312
+ const risky = returns.find((r) => classify(r.node, r.scope, helper.code, 0) !== 'safe') || returns[0];
1313
+ return {
1314
+ fn: name,
1315
+ file: helper.file,
1316
+ line: (risky.node.loc ? risky.node.loc.start.line : 1) + helper.lineOffset - 1,
1317
+ code: helper.code,
1318
+ lineOffset: helper.lineOffset,
1319
+ returns: returns,
1320
+ };
1321
+ }
1322
+
1323
+ /**
1324
+ * Finds a function another file of the project exports, for helperOf. Parsed
1325
+ * once a file; its functions are handed to the map() reader each time, since
1326
+ * that table is rebuilt for every file read.
1327
+ */
1328
+ /** The project file a relative import names, or null for a package or nothing. */
1329
+ function resolveModule(fromFile, source) {
1330
+ if (!/^\.\.?\//.test(source)) return null;
1331
+ const EXTS = ['', '.js', '.mjs', '.cjs', '.jsx', '.ts', '.tsx', '/index.js', '/index.ts'];
1332
+ const base = path.resolve(path.dirname(fromFile), source);
1333
+ return EXTS.map((ext) => base + ext).find((candidate) => {
1334
+ try {
1335
+ return fs.statSync(candidate).isFile() && CODE_EXT.test(candidate);
1336
+ } catch (err) {
1337
+ return false;
1338
+ }
1339
+ }) || null;
1340
+ }
1341
+
1342
+ function importResolver(parser, root) {
1343
+ const parsed = new Map();
1344
+ const entryOf = (fromFile, source) => {
1345
+ const full = resolveModule(fromFile, source);
1346
+ if (!full) return null;
1347
+ if (!parsed.has(full)) {
1348
+ let entry = null;
1349
+ try {
1350
+ if (fs.statSync(full).size <= MAX_BYTES) {
1351
+ const code = fs.readFileSync(full, 'utf8');
1352
+ const ast = parser.babelParse(code, full, true);
1353
+ const fns = [];
1354
+ let program = null;
1355
+ parser.traverse(ast, {
1356
+ Program(p) { program = p.scope; },
1357
+ Function(p) { fns.push(p); },
1358
+ });
1359
+ if (program) PROGRAM_FILE.set(program.block, full);
1360
+ entry = { code: code, program: program, fns: fns, file: path.relative(root, full).split(path.sep).join('/') };
1361
+ }
1362
+ } catch (err) {
1363
+ entry = null;
1364
+ }
1365
+ parsed.set(full, entry);
1366
+ }
1367
+ const entry = parsed.get(full);
1368
+ if (!entry || !entry.program) return null;
1369
+ for (const p of entry.fns) FN_PATHS.set(p.node, p);
1370
+ return Object.assign({ full: full }, entry);
1371
+ };
1372
+ const resolve = (fromFile, source, name) => {
1373
+ const entry = entryOf(fromFile, source);
1374
+ if (!entry) return null;
1375
+ const fnPath = localFunction(name, entry.program);
1376
+ return fnPath ? { fnPath: fnPath, code: entry.code, file: entry.file } : null;
1377
+ };
1378
+ // A `const` the file declares at its top, with the value it is given there.
1379
+ resolve.constOf = (fromFile, source, name) => {
1380
+ const entry = entryOf(fromFile, source);
1381
+ if (!entry) return null;
1382
+ const binding = entry.program.getBinding(name);
1383
+ const node = binding && binding.path && binding.path.node;
1384
+ if (!binding || binding.kind !== 'const' || !node || node.type !== 'VariableDeclarator' || !node.init) return null;
1385
+ if (binding.constantViolations && binding.constantViolations.length) return null;
1386
+ return { full: entry.full, init: node.init, scope: binding.path.scope, code: entry.code };
1387
+ };
1388
+ return resolve;
1389
+ }
1390
+
1391
+ // Methods that change the array, map or set they are called on.
1392
+ const MUTATORS = /^(push|pop|shift|unshift|splice|sort|reverse|fill|copyWithin|set|add|delete|clear)$/;
1393
+ // Calls that only read what they are given.
1394
+ const READS_ONLY = /^(String|Number|Boolean|JSON\.stringify|console\.\w+|Array\.isArray|Object\.(keys|values|entries|freeze|isFrozen))$/;
1395
+ // Methods that only read their argument: list.concat(demo.changes) builds a
1396
+ // new list and leaves demo alone. push() and the like are not here - they put
1397
+ // the value somewhere it can be written through.
1398
+ const READS_ARGUMENT = /^(concat|includes|indexOf|lastIndexOf|startsWith|endsWith|localeCompare|has|at)$/;
1399
+
1400
+ /**
1401
+ * Whether this use of a name can change what the name holds: an assignment or
1402
+ * delete through it, a mutating method on it, or handing it to a call that
1403
+ * could change it. A local name given to part of it - `const list = demo.flags`
1404
+ * - is followed, since writing to the list writes to demo.
1405
+ */
1406
+ function writtenThrough(ref, depth) {
1407
+ if ((depth || 0) > 4) return true;
1408
+ let p = ref;
1409
+ while (p.parentPath && /MemberExpression$/.test(p.parentPath.node.type) && p.parentPath.node.object === p.node) p = p.parentPath;
1410
+ const parentPath = p.parentPath;
1411
+ const parent = parentPath && parentPath.node;
1412
+ if (!parent) return false;
1413
+ if (parent.type === 'UpdateExpression') return true;
1414
+ if (parent.type === 'UnaryExpression' && parent.operator === 'delete') return true;
1415
+ // The target of an assignment, plain or inside a destructuring pattern.
1416
+ let up = p;
1417
+ while (up.parentPath && /^(ObjectProperty|ObjectPattern|ArrayPattern|AssignmentPattern|RestElement)$/.test(up.parentPath.node.type)) up = up.parentPath;
1418
+ const holder = up.parentPath && up.parentPath.node;
1419
+ if (holder && holder.type === 'AssignmentExpression' && holder.left === up.node) return true;
1420
+ if (holder && /^For(Of|In)Statement$/.test(holder.type) && holder.left === up.node) return true;
1421
+ if (/CallExpression$/.test(parent.type)) {
1422
+ if (parent.callee === p.node) {
1423
+ return /MemberExpression$/.test(p.node.type) && MUTATORS.test(calleeName(p.node));
1424
+ }
1425
+ if (parent.arguments.indexOf(p.node) !== -1) {
1426
+ const callee = parent.callee;
1427
+ const full = callee.type === 'MemberExpression' && callee.object.type === 'Identifier'
1428
+ ? callee.object.name + '.' + calleeName(callee) : calleeName(callee);
1429
+ if (/MemberExpression$/.test(callee.type) && READS_ARGUMENT.test(calleeName(callee))) return false;
1430
+ return !(MAKES_SAFE.test(calleeName(callee)) || READS_ONLY.test(full));
1431
+ }
1432
+ }
1433
+ if (parent.type === 'VariableDeclarator' && parent.init === p.node && parent.id.type === 'Identifier') {
1434
+ const alias = parentPath.scope.getBinding(parent.id.name);
1435
+ if (!alias) return true;
1436
+ if (alias.constantViolations && alias.constantViolations.length) return true;
1437
+ return (alias.referencePaths || []).some((r) => writtenThrough(r, (depth || 0) + 1));
1438
+ }
1439
+ return false;
1440
+ }
1441
+
1442
+ /**
1443
+ * Every project name something writes to, as "<file>::<name>", read once over
1444
+ * the whole project before any file is judged. `blind` when a file could not
1445
+ * be read: a write could be in it, so no import is trusted at all.
1446
+ */
1447
+ function projectWrites(parser, files) {
1448
+ const written = new Set();
1449
+ let blind = false;
1450
+ for (const full of files) {
1451
+ let pieces;
1452
+ try {
1453
+ if (fs.statSync(full).size > MAX_BYTES) continue;
1454
+ const source = fs.readFileSync(full, 'utf8');
1455
+ pieces = PAGE_EXT.test(full) ? scriptsIn(source) : [{ code: source }];
1456
+ } catch (err) {
1457
+ blind = true;
1458
+ continue;
1459
+ }
1460
+ for (const piece of pieces) {
1461
+ let ast;
1462
+ try {
1463
+ ast = parser.babelParse(piece.code, full, true);
1464
+ } catch (err) {
1465
+ blind = true;
1466
+ continue;
1467
+ }
1468
+ parser.traverse(ast, {
1469
+ Program(p) {
1470
+ // This file's own top-level names, written to here.
1471
+ for (const name of Object.keys(p.scope.bindings)) {
1472
+ const b = p.scope.bindings[name];
1473
+ if (b.kind === 'module') continue;
1474
+ if ((b.constantViolations && b.constantViolations.length) ||
1475
+ (b.referencePaths || []).some((r) => writtenThrough(r))) {
1476
+ written.add(full + '::' + name);
1477
+ }
1478
+ }
1479
+ },
1480
+ ImportDeclaration(p) {
1481
+ const from = resolveModule(full, p.node.source.value);
1482
+ if (!from) return;
1483
+ for (const spec of p.node.specifiers) {
1484
+ const b = p.scope.getBinding(spec.local.name);
1485
+ if (!b) continue;
1486
+ if (spec.type === 'ImportNamespaceSpecifier') {
1487
+ for (const r of b.referencePaths || []) {
1488
+ const m = r.parentPath && r.parentPath.node;
1489
+ if (m && /MemberExpression$/.test(m.type) && m.object === r.node && !m.computed && m.property.type === 'Identifier') {
1490
+ if (writtenThrough(r.parentPath)) written.add(from + '::' + m.property.name);
1491
+ } else {
1492
+ written.add(from + '::*');
1493
+ }
1494
+ }
1495
+ continue;
1496
+ }
1497
+ const name = spec.type === 'ImportDefaultSpecifier' ? 'default' : (spec.imported.name || spec.imported.value);
1498
+ if ((b.referencePaths || []).some((r) => writtenThrough(r))) written.add(from + '::' + name);
1499
+ }
1500
+ },
1501
+ });
1502
+ }
1503
+ }
1504
+ return { written: written, blind: blind };
1505
+ }
1506
+
1507
+ function sinksIn(parser, code, file, lineOffset, resolver) {
1508
+ const found = [];
1509
+ const ast = parser.babelParse(code, file, true);
1510
+ PROGRAM_FILE.set(ast.program, file);
1511
+ const lineOf = (node) => (node.loc ? node.loc.start.line : 1) + lineOffset - 1;
1512
+ const textOf = (node) => code.slice(node.start, node.end).replace(/\s+/g, ' ').slice(0, 160);
1513
+ // Calls to plain named functions, so a helper's sink can be judged by what
1514
+ // each call actually hands it.
1515
+ const calls = new Map();
1516
+ const viaHelper = [];
1517
+ const partsOf = (value, scope) => {
1518
+ const out = [];
1519
+ riskyParts(value, scope, code, undefined, out, 0);
1520
+ return out;
1521
+ };
1522
+ const add = (node, scope, sink, value) => {
1523
+ const param = paramOf(value, scope);
1524
+ if (param) {
1525
+ viaHelper.push({ node: node, sink: sink, value: value, scope: scope, param: param });
1526
+ return;
1527
+ }
1528
+ // The HTML built by a helper - root.innerHTML = renderBoard(rows) - is
1529
+ // judged by what the helper returns, in its own file, and the place it
1530
+ // puts a value in is named. Found on a blind test (HelixOps): appShell(),
1531
+ // a fixed string in ui.js, was reported as unknown, and renderBoard() was
1532
+ // reported at its call with no word of ui.js:13, where the title goes in.
1533
+ const built = helperOf(value, scope, code, file, lineOffset, resolver);
1534
+ if (built) {
1535
+ const origin = worst(built.returns.map((r) => classify(r.node, r.scope, built.code, 0)));
1536
+ if (origin === 'safe') return;
1537
+ const parts = [];
1538
+ for (const r of built.returns) riskyParts(r.node, r.scope, built.code, undefined, parts, 0);
1539
+ // The line of the first value that goes in, not of the return around it.
1540
+ const first = parts.find((p) => p.line);
1541
+ found.push({
1542
+ line: lineOf(node), sink: sink, expression: textOf(value), origin: origin, parts: parts,
1543
+ helper: { fn: built.fn, file: built.file, line: first ? first.line + built.lineOffset - 1 : built.line },
1544
+ });
1545
+ return;
1546
+ }
1547
+ const origin = classify(value, scope, code, 0);
1548
+ if (origin === 'safe') return;
1549
+ found.push({ line: lineOf(node), sink: sink, expression: textOf(value), origin: origin, parts: partsOf(value, scope) });
1550
+ };
1551
+ FN_PATHS = new WeakMap();
1552
+ parser.traverse(ast, {
1553
+ Function(p) {
1554
+ FN_PATHS.set(p.node, p);
1555
+ },
1556
+ CallExpression: {
1557
+ exit(p) {
1558
+ if (p.node.callee.type !== 'Identifier') return;
1559
+ const list = calls.get(p.node.callee.name) || [];
1560
+ list.push({ node: p.node, scope: p.scope });
1561
+ calls.set(p.node.callee.name, list);
1562
+ },
1563
+ },
1564
+ });
1565
+ const redirect = (p, sink, value) => {
1566
+ if (!value || !readsUrl(value, p.scope, 0) || checkedFirst(p, value, code)) return;
1567
+ found.push({ kind: 'redirect', line: lineOf(p.node), sink: sink, expression: textOf(value), origin: 'url', parts: [] });
1568
+ };
1569
+ parser.traverse(ast, {
1570
+ AssignmentExpression(p) {
1571
+ const left = p.node.left;
1572
+ if (isLocation(left)) return redirect(p, 'location', p.node.right);
1573
+ if (left.type !== 'MemberExpression' || left.computed) return;
1574
+ const prop = left.property && left.property.name;
1575
+ if (prop === 'innerHTML' || prop === 'outerHTML') add(p.node, p.scope, prop, p.node.right);
1576
+ else if (prop === 'href' && isLocation(left.object)) redirect(p, 'location.href', p.node.right);
1577
+ },
1578
+ CallExpression(p) {
1579
+ const callee = p.node.callee;
1580
+ const name = calleeName(callee);
1581
+ const args = p.node.arguments;
1582
+ if ((name === 'assign' || name === 'replace') && callee.type === 'MemberExpression' && isLocation(callee.object)) {
1583
+ return redirect(p, 'location.' + name + '()', args[0]);
1584
+ }
1585
+ if (name === 'open' && callee.type === 'MemberExpression' && callee.object.type === 'Identifier' && callee.object.name === 'window') {
1586
+ return redirect(p, 'window.open()', args[0]);
1587
+ }
1588
+ // Next's router follows a full URL off the site. React Router's
1589
+ // navigate() does not, so it is not a sink here.
1590
+ if ((name === 'push' || name === 'replace') && callee.type === 'MemberExpression' &&
1591
+ callee.object.type === 'Identifier' && callee.object.name === 'router') {
1592
+ return redirect(p, 'router.' + name + '()', args[0]);
1593
+ }
1594
+ if (name === 'insertAdjacentHTML' && args[1]) add(p.node, p.scope, 'insertAdjacentHTML', args[1]);
1595
+ else if ((name === 'write' || name === 'writeln') && callee.type === 'MemberExpression' &&
1596
+ callee.object && callee.object.name === 'document' && args[0]) {
1597
+ add(p.node, p.scope, 'document.' + name, args[0]);
1598
+ } else if (name === 'html' && callee.type === 'MemberExpression' && args.length === 1) {
1599
+ add(p.node, p.scope, '.html()', args[0]);
1600
+ }
1601
+ },
1602
+ JSXAttribute(p) {
1603
+ if (!p.node.name || p.node.name.name !== 'dangerouslySetInnerHTML') return;
1604
+ const expr = p.node.value && p.node.value.expression;
1605
+ if (!expr || expr.type !== 'ObjectExpression') return;
1606
+ const html = expr.properties.find((prop) => prop.key && (prop.key.name === '__html' || prop.key.value === '__html'));
1607
+ if (html) add(p.node, p.scope, 'dangerouslySetInnerHTML', html.value);
1608
+ },
1609
+ });
1610
+
1611
+ // A helper's sink is judged at its calls. Most calls of a helper like this
1612
+ // pass HTML on purpose, so the risk is the one call that passes something
1613
+ // from outside - and that is where it has to be fixed. A helper with no call
1614
+ // this file can see cannot be judged that way, so its sink is reported where
1615
+ // it is, as unknown, rather than dropped.
1616
+ for (const h of viaHelper) {
1617
+ const seen = calls.get(h.param.fn) || [];
1618
+ if (!seen.length) {
1619
+ found.push({ line: lineOf(h.node), sink: h.sink, expression: textOf(h.value), origin: 'unknown' });
1620
+ continue;
1621
+ }
1622
+ for (const call of seen) {
1623
+ const arg = call.node.arguments[h.param.index];
1624
+ if (!arg) continue;
1625
+ const origin = classify(arg, call.scope, code, 0);
1626
+ if (origin === 'safe') continue;
1627
+ found.push({
1628
+ line: lineOf(call.node),
1629
+ sink: h.sink,
1630
+ expression: textOf(arg),
1631
+ origin: origin,
1632
+ parts: partsOf(arg, call.scope),
1633
+ via: { fn: h.param.fn, line: lineOf(h.node) },
1634
+ });
1635
+ }
1636
+ }
1637
+ return found;
1638
+ }
1639
+
1640
+ /**
1641
+ * Reads the project at `root`. Returns
1642
+ * { ran, why?, filesRead, findings: [...], unreadable: [{ file, why }] }
1643
+ * `ran: false` means the check did not happen - never that it passed.
1644
+ */
1645
+ function scanProject(root, options) {
1646
+ SELECT_IDS = new Set();
1647
+ TAGLESS_COLUMNS = taglessColumns(root);
1648
+ const packageDir = (options && options.packageDir) || __dirname;
1649
+ const parser = (options && options.parser) || loadParser(packageDir);
1650
+ if (!parser) {
1651
+ return {
1652
+ ran: false,
1653
+ why: 'the JavaScript parser this check uses was not found in this install of Playwright',
1654
+ filesRead: 0,
1655
+ findings: [],
1656
+ unreadable: [],
1657
+ };
1658
+ }
1659
+ const findings = [];
1660
+ const unreadable = [];
1661
+ // Secret keys, read from the same files. Kept apart from the HTML findings:
1662
+ // they are already in their final shape, and they go first.
1663
+ const secrets = [];
1664
+ let filesRead = 0;
1665
+ const files = listFiles(root);
1666
+ const relOf = (full) => path.relative(root, full).split(path.sep).join('/');
1667
+ // Which pages load which scripts, so a key in config.js can be said to
1668
+ // reach the browser because index.html loads it - not guessed at.
1669
+ const pages = [];
1670
+ for (const full of files) {
1671
+ if (!/\.html?$/i.test(full)) continue;
1672
+ try {
1673
+ if (fs.statSync(full).size <= MAX_BYTES) pages.push({ rel: relOf(full), source: fs.readFileSync(full, 'utf8') });
1674
+ } catch (err) {
1675
+ /* unreadable pages are reported below */
1676
+ }
1677
+ }
1678
+ const loadedBy = keys.scriptsLoadedBy(pages);
1679
+ SELECT_IDS = selectIdsOf(pages);
1680
+ const resolver = importResolver(parser, root);
1681
+ // Before any file is judged: which of the project's own names anything
1682
+ // writes to, so fixed data is only trusted while it really is fixed.
1683
+ PROGRAM_FILE = new WeakMap();
1684
+ IMPORTS = Object.assign({ constOf: resolver.constOf }, projectWrites(parser, files));
1685
+ try {
1686
+ readAll();
1687
+ } finally {
1688
+ IMPORTS = null;
1689
+ }
1690
+ return { ran: true, filesRead: filesRead, findings: secrets.concat(findings.map(describe)), unreadable: unreadable };
1691
+
1692
+ function readAll() {
1693
+ for (const full of files) {
1694
+ let size = 0;
1695
+ try {
1696
+ size = fs.statSync(full).size;
1697
+ } catch (err) {
1698
+ continue;
1699
+ }
1700
+ const rel = path.relative(root, full).split(path.sep).join('/');
1701
+ if (size > MAX_BYTES) {
1702
+ unreadable.push({ file: rel, why: 'larger than ' + Math.round(MAX_BYTES / 1024) + ' KB, probably generated' });
1703
+ continue;
1704
+ }
1705
+ const source = fs.readFileSync(full, 'utf8');
1706
+ filesRead++;
1707
+ for (const k of keys.secretsIn(rel, source, loadedBy)) secrets.push(k);
1708
+ const pieces = PAGE_EXT.test(full) ? scriptsIn(source) : [{ code: source, line: 1 }];
1709
+ for (const piece of pieces) {
1710
+ try {
1711
+ for (const f of sinksIn(parser, piece.code, full, piece.line, resolver)) findings.push(Object.assign({ file: rel }, f));
1712
+ } catch (err) {
1713
+ unreadable.push({ file: rel + (piece.line > 1 ? ':' + piece.line : ''), why: 'could not be parsed: ' + String(err.message).split('\n')[0].slice(0, 120) });
1714
+ }
1715
+ }
1716
+ if (/\.(vue|html)$/i.test(full)) {
1717
+ for (const v of vHtmlIn(source)) {
1718
+ findings.push({ file: rel, line: v.line, sink: 'v-html', expression: v.expression, origin: 'unknown' });
1719
+ }
1720
+ }
1721
+ }
1722
+ }
1723
+ }
1724
+
1725
+ const ORIGIN_WORDS = {
1726
+ network: 'read from a server response',
1727
+ error: "an error's message, which often carries text a server sent",
1728
+ unknown: 'from somewhere the code alone cannot pin down',
1729
+ };
1730
+
1731
+ // Wrapped here rather than by whoever prints it: this is pasted into a chat
1732
+ // box as often as it is read in a terminal, and a long line is a wall in both.
1733
+ // A quoted piece of code is never wrapped - breaking it would change it.
1734
+ function wrap(text, width) {
1735
+ const out = [];
1736
+ let current = '';
1737
+ for (const word of String(text).split(/\s+/)) {
1738
+ if (current && (current + ' ' + word).length > width) {
1739
+ out.push(current);
1740
+ current = word;
1741
+ } else {
1742
+ current = current ? current + ' ' + word : word;
1743
+ }
1744
+ }
1745
+ if (current) out.push(current);
1746
+ return out.join('\n');
1747
+ }
1748
+
1749
+ /** An open redirect, in the same shape as every other finding. */
1750
+ function describeRedirect(f) {
1751
+ const fixPrompt = [
1752
+ 'My app may have an open redirect - please check it rather than assume it.',
1753
+ '',
1754
+ 'In ' + f.file + ' at line ' + f.line + ', the page sends the browser to an address taken from its own URL:',
1755
+ '',
1756
+ ' ' + f.expression,
1757
+ '',
1758
+ 'Anyone can send a link to this page with that part of the URL set to their own site - for example ' +
1759
+ '?next=https://attacker.example. The person uses your real page, then lands on the attacker\'s, which ' +
1760
+ 'can ask for their password again. A value starting with javascript: can run script in your page.',
1761
+ '',
1762
+ 'Fix it so only your own pages are allowed: accept the value only if it starts with a single "/" (not ' +
1763
+ '"//" and not "/\\"), or check that new URL(value, location.origin).origin equals location.origin, and ' +
1764
+ 'go to your home page otherwise. Then check every other place that reads a next, redirect or returnTo ' +
1765
+ 'value the same way.',
1766
+ ].map((p) => (p.startsWith(' ') ? p : wrap(p, 72))).join('\n');
1767
+ return {
1768
+ kind: 'open-redirect',
1769
+ status: 'verification required',
1770
+ evidence: 'code analysis',
1771
+ severity: 'HIGH',
1772
+ confidence: 'medium',
1773
+ file: f.file,
1774
+ line: f.line,
1775
+ sink: f.sink,
1776
+ expression: f.expression,
1777
+ origin: 'url',
1778
+ parts: [],
1779
+ via: null,
1780
+ headline: 'A redirect in ' + f.file + ':' + f.line + ' goes wherever the page\'s URL says.',
1781
+ fixPrompt: fixPrompt,
1782
+ };
1783
+ }
1784
+
1785
+ /** One finding, in the shape every Kryptheon report uses. */
1786
+ function describe(f) {
1787
+ if (f.kind === 'redirect') return describeRedirect(f);
1788
+ const severity = f.origin === 'unknown' ? 'MEDIUM' : 'HIGH';
1789
+ const how = f.sink === 'v-html' ? 'v-html' : f.sink;
1790
+ // Where the helper builds it: its own file when it is another one.
1791
+ const builtAt = f.helper ? (f.helper.file ? f.helper.file + ':' : 'line ') + f.helper.line : '';
1792
+ const where = f.via
1793
+ ? 'In ' + f.file + ' at line ' + f.line + ', this value is passed to ' + f.via.fn + '(), which puts ' +
1794
+ 'what it is given into the page as HTML with ' + how + ' at line ' + f.via.line + ':'
1795
+ : f.helper
1796
+ ? 'In ' + f.file + ' at line ' + f.line + ', the HTML that ' + f.helper.fn + '() builds - at ' + builtAt +
1797
+ ' - is put into the page with ' + how + ':'
1798
+ : 'In ' + f.file + ' at line ' + f.line + ', this value is put into the page as HTML with ' + how + ':';
1799
+ // The fix for a helper is different, and getting it wrong breaks the page:
1800
+ // switching the helper to textContent makes every other call - the ones
1801
+ // that pass HTML on purpose - show their tags as text. Found by applying the
1802
+ // plain version of this prompt to a real helper like this.
1803
+ const fix = f.via
1804
+ ? [
1805
+ 'Do not change ' + f.via.fn + '() to use textContent: other calls pass HTML to it on purpose, ' +
1806
+ 'and they would show their tags as text. Fix it here instead - escape the dynamic part of ' +
1807
+ 'this value before it is joined into the HTML (replace & < > " \' with their HTML entities), ' +
1808
+ 'or pass it through a sanitizer such as DOMPurify if it must keep some formatting.',
1809
+ ]
1810
+ : f.helper
1811
+ ? [
1812
+ 'Fix it inside ' + f.helper.fn + '() at ' + builtAt + ', where the values are joined into the HTML: ' +
1813
+ 'escape each dynamic value there (replace & < > " \' with their HTML entities), or pass the ' +
1814
+ 'result through a sanitizer such as DOMPurify if it must keep some formatting.',
1815
+ ]
1816
+ : [
1817
+ 'Fix it so the value is always shown as text: set textContent instead of innerHTML for the ' +
1818
+ 'dynamic part, or escape it before it is joined into HTML (replace & < > " \' with their ' +
1819
+ 'HTML entities). If the HTML is meant to allow some formatting, pass it through a sanitizer ' +
1820
+ 'such as DOMPurify first.',
1821
+ ];
1822
+ // A long template is mostly harmless markup. Naming the part that decides it
1823
+ // keeps the fix - and the AI tool doing it - to that part alone.
1824
+ const parts = (f.parts || []).filter((p) => p.text && p.text !== f.expression);
1825
+ const only = parts.length
1826
+ ? [''].concat(
1827
+ [(parts.length === 1 ? 'Only this part' : 'Only these parts') + ' of it can carry text from outside the page, ' +
1828
+ 'so only ' + (parts.length === 1 ? 'it needs' : 'they need') + ' changing:'],
1829
+ parts.map((p) => ' ${' + p.text + '}'),
1830
+ )
1831
+ : [];
1832
+ const fixPrompt = [
1833
+ 'My app may have a security problem - please check it rather than assume it.',
1834
+ '',
1835
+ where,
1836
+ '',
1837
+ ' ' + f.expression,
1838
+ ].concat(only, [
1839
+ '',
1840
+ 'The value is ' + ORIGIN_WORDS[f.origin] + '. If it can ever contain text a user or another ' +
1841
+ 'account typed, a "<" in it becomes a real tag and can run script in this page with the ' +
1842
+ "signed-in person's session.",
1843
+ '',
1844
+ ]).concat(fix, [
1845
+ '',
1846
+ 'Keep the page looking the same, change only how this value is inserted, and look for the ' +
1847
+ 'same pattern elsewhere in this file. Afterwards, open this page and check that ordinary ' +
1848
+ 'text, and text containing < and &, both display correctly.',
1849
+ ]).map((p) => (p.startsWith(' ') ? p : wrap(p, 72))).join('\n');
1850
+ return {
1851
+ kind: 'unsafe-html',
1852
+ status: 'verification required',
1853
+ evidence: 'code analysis',
1854
+ severity: severity,
1855
+ confidence: f.origin === 'unknown' ? 'low' : 'medium',
1856
+ file: f.file,
1857
+ line: f.line,
1858
+ sink: f.sink,
1859
+ expression: f.expression,
1860
+ origin: f.origin,
1861
+ parts: (f.parts || []).map((p) => ({ text: p.text, origin: p.origin })),
1862
+ via: f.via || null,
1863
+ helper: f.helper || null,
1864
+ headline: 'Text ' + (f.origin === 'unknown' ? 'of unknown origin' : ORIGIN_WORDS[f.origin].split(',')[0]) +
1865
+ ' is inserted as HTML in ' + f.file + ':' + f.line +
1866
+ (f.via ? ' (through ' + f.via.fn + '() at line ' + f.via.line + ')' : '') +
1867
+ (f.helper ? ', built by ' + f.helper.fn + '() at ' + builtAt : '') + '.',
1868
+ fixPrompt: fixPrompt,
1869
+ };
1870
+ }
1871
+
1872
+ module.exports = {
1873
+ scanProject: scanProject,
1874
+ listFiles: listFiles,
1875
+ loadParser: loadParser,
1876
+ scriptsIn: scriptsIn,
1877
+ classify: classify,
1878
+ describe: describe,
1879
+ };