crossexamdev 0.2.0 → 0.4.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +7 -2
- package/bin/crossexam.js +253 -5
- package/package.json +1 -1
- package/src/claims.js +138 -120
- package/src/evidence.js +3 -1
- package/src/findings.js +194 -0
- package/src/github.js +93 -69
- package/src/mcp.js +155 -5
- package/src/mutate.js +582 -0
- package/src/redact.js +59 -0
- package/src/reliability.js +154 -0
- package/src/report.js +195 -99
- package/src/sandbox.js +627 -0
- package/src/strength.js +637 -0
- package/src/upload.js +212 -0
package/src/mutate.js
ADDED
|
@@ -0,0 +1,582 @@
|
|
|
1
|
+
// Mutation operators: plant small, deterministic defects in changed code.
|
|
2
|
+
//
|
|
3
|
+
// Pure functions, no I/O. The engine works on a "masked" copy of the source
|
|
4
|
+
// in which strings, template literals, comments and regex literals are blanked
|
|
5
|
+
// out (same length, newlines kept), so an operator never fires inside text and
|
|
6
|
+
// every offset in the masked copy is also an offset in the original.
|
|
7
|
+
|
|
8
|
+
import { createHash } from 'node:crypto';
|
|
9
|
+
|
|
10
|
+
export const CODE_EXT = /\.(?:py|go|rs|java|kt|kts|rb|swift|cs|php|c|cc|cpp|h|hpp|scala|ex|exs|dart|vue|svelte|lua|r|jl)$/i;
|
|
11
|
+
export const JS_EXT = /\.(?:[cm]?jsx?|[cm]?tsx?)$/i;
|
|
12
|
+
export const TEST_FILE = /(?:^|[\\/])(?:__tests__|__mocks__|tests?|spec|e2e|fixtures?)[\\/]|[._-](?:test|spec)\.[cm]?[jt]sx?$/i;
|
|
13
|
+
const SKIP_FILE = /(?:^|[\\/])(?:node_modules|dist|build|out|coverage|\.next|\.nuxt|vendor)[\\/]|\.d\.[cm]?ts$|\.min\.js$|(?:^|[\\/])(?:vite|vitest|jest|webpack|rollup|babel|eslint|prettier|tailwind|postcss|next|svelte)\.config\.[cm]?[jt]s$/i;
|
|
14
|
+
|
|
15
|
+
/** Why a file is or isn't mutated. */
|
|
16
|
+
export function classifyFile(file) {
|
|
17
|
+
if (TEST_FILE.test(file)) return { ok: false, reason: 'test file' };
|
|
18
|
+
if (SKIP_FILE.test(file)) return { ok: false, reason: 'generated, vendored or config' };
|
|
19
|
+
if (!JS_EXT.test(file)) return CODE_EXT.test(file) ? { ok: false, reason: 'language not supported yet' } : { ok: false, reason: 'not source code', quiet: true };
|
|
20
|
+
return { ok: true, language: /tsx?$/i.test(file) ? 'typescript' : 'javascript' };
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
// ---------- masking ----------
|
|
24
|
+
|
|
25
|
+
const REGEX_BEFORE = /[(,=:[!&|?{};+\-*%<>~^]$/;
|
|
26
|
+
const REGEX_KEYWORD = /\b(?:return|typeof|case|in|of|new|delete|void|throw|yield|await|else|do)$/;
|
|
27
|
+
|
|
28
|
+
/** Blank out strings, templates, comments and regex literals (JS/TS). */
|
|
29
|
+
export function maskJs(src) {
|
|
30
|
+
const out = src.split('');
|
|
31
|
+
const n = src.length;
|
|
32
|
+
const blank = (a, b) => {
|
|
33
|
+
for (let k = a; k < b && k < n; k++) if (out[k] !== '\n') out[k] = ' ';
|
|
34
|
+
};
|
|
35
|
+
let i = 0;
|
|
36
|
+
// Last significant (unmasked, non-space) text, to tell regex from division.
|
|
37
|
+
const prevSig = (at) => {
|
|
38
|
+
let k = at - 1;
|
|
39
|
+
while (k >= 0 && /\s/.test(out[k])) k--;
|
|
40
|
+
return out.slice(Math.max(0, k - 12), k + 1).join('');
|
|
41
|
+
};
|
|
42
|
+
|
|
43
|
+
const skipTemplate = (start) => {
|
|
44
|
+
// start is at the opening backtick; returns index after the closing one.
|
|
45
|
+
let k = start + 1;
|
|
46
|
+
while (k < n) {
|
|
47
|
+
const ch = src[k];
|
|
48
|
+
if (ch === '\\') k += 2;
|
|
49
|
+
else if (ch === '`') return k + 1;
|
|
50
|
+
else if (ch === '$' && src[k + 1] === '{') {
|
|
51
|
+
k = skipExpr(k + 2);
|
|
52
|
+
} else k++;
|
|
53
|
+
}
|
|
54
|
+
return n;
|
|
55
|
+
};
|
|
56
|
+
const skipQuoted = (start, q) => {
|
|
57
|
+
let k = start + 1;
|
|
58
|
+
while (k < n && src[k] !== q && src[k] !== '\n') k += src[k] === '\\' ? 2 : 1;
|
|
59
|
+
return Math.min(n, k + 1);
|
|
60
|
+
};
|
|
61
|
+
const skipExpr = (start) => {
|
|
62
|
+
// inside ${ … }: balance braces, honouring nested strings and templates.
|
|
63
|
+
let depth = 1;
|
|
64
|
+
let k = start;
|
|
65
|
+
while (k < n && depth > 0) {
|
|
66
|
+
const ch = src[k];
|
|
67
|
+
if (ch === '{') depth++;
|
|
68
|
+
else if (ch === '}') depth--;
|
|
69
|
+
else if (ch === '`') {
|
|
70
|
+
k = skipTemplate(k);
|
|
71
|
+
continue;
|
|
72
|
+
} else if (ch === '"' || ch === "'") {
|
|
73
|
+
k = skipQuoted(k, ch);
|
|
74
|
+
continue;
|
|
75
|
+
}
|
|
76
|
+
k++;
|
|
77
|
+
}
|
|
78
|
+
return k;
|
|
79
|
+
};
|
|
80
|
+
|
|
81
|
+
while (i < n) {
|
|
82
|
+
const ch = src[i];
|
|
83
|
+
const nx = src[i + 1];
|
|
84
|
+
if (ch === '/' && nx === '/') {
|
|
85
|
+
const e = src.indexOf('\n', i);
|
|
86
|
+
const end = e < 0 ? n : e;
|
|
87
|
+
blank(i, end);
|
|
88
|
+
i = end;
|
|
89
|
+
} else if (ch === '/' && nx === '*') {
|
|
90
|
+
const e = src.indexOf('*/', i + 2);
|
|
91
|
+
const end = e < 0 ? n : e + 2;
|
|
92
|
+
blank(i, end);
|
|
93
|
+
i = end;
|
|
94
|
+
} else if (ch === '"' || ch === "'") {
|
|
95
|
+
const end = skipQuoted(i, ch);
|
|
96
|
+
blank(i, end);
|
|
97
|
+
i = end;
|
|
98
|
+
} else if (ch === '`') {
|
|
99
|
+
const end = skipTemplate(i);
|
|
100
|
+
blank(i, end);
|
|
101
|
+
i = end;
|
|
102
|
+
} else if (ch === '/') {
|
|
103
|
+
const before = prevSig(i);
|
|
104
|
+
if (before === '' || REGEX_BEFORE.test(before) || REGEX_KEYWORD.test(before)) {
|
|
105
|
+
let k = i + 1;
|
|
106
|
+
let cls = false;
|
|
107
|
+
while (k < n && src[k] !== '\n') {
|
|
108
|
+
if (src[k] === '\\') k += 2;
|
|
109
|
+
else if (src[k] === '[') (cls = true), k++;
|
|
110
|
+
else if (src[k] === ']') (cls = false), k++;
|
|
111
|
+
else if (src[k] === '/' && !cls) break;
|
|
112
|
+
else k++;
|
|
113
|
+
}
|
|
114
|
+
if (src[k] === '/') {
|
|
115
|
+
k++;
|
|
116
|
+
while (k < n && /[a-z]/i.test(src[k])) k++;
|
|
117
|
+
blank(i, k);
|
|
118
|
+
i = k;
|
|
119
|
+
} else i++;
|
|
120
|
+
} else i++;
|
|
121
|
+
} else i++;
|
|
122
|
+
}
|
|
123
|
+
return out.join('');
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
// ---------- lines ----------
|
|
127
|
+
|
|
128
|
+
export function lineStarts(src) {
|
|
129
|
+
const starts = [0];
|
|
130
|
+
for (let i = 0; i < src.length; i++) if (src[i] === '\n') starts.push(i + 1);
|
|
131
|
+
return starts;
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
export function lineOf(starts, offset) {
|
|
135
|
+
let lo = 0;
|
|
136
|
+
let hi = starts.length - 1;
|
|
137
|
+
while (lo < hi) {
|
|
138
|
+
const mid = (lo + hi + 1) >> 1;
|
|
139
|
+
if (starts[mid] <= offset) lo = mid;
|
|
140
|
+
else hi = mid - 1;
|
|
141
|
+
}
|
|
142
|
+
return lo + 1;
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
// ---------- functions ----------
|
|
146
|
+
|
|
147
|
+
const NOT_A_NAME = new Set(['if', 'for', 'while', 'switch', 'catch', 'function', 'return', 'with', 'constructor', 'super', 'typeof', 'new', 'await', 'import', 'export']);
|
|
148
|
+
|
|
149
|
+
function matchClose(masked, open) {
|
|
150
|
+
const pair = { '(': ')', '{': '}', '[': ']' }[masked[open]];
|
|
151
|
+
let depth = 0;
|
|
152
|
+
for (let k = open; k < masked.length; k++) {
|
|
153
|
+
const ch = masked[k];
|
|
154
|
+
if (ch === masked[open]) depth++;
|
|
155
|
+
else if (ch === pair && --depth === 0) return k;
|
|
156
|
+
}
|
|
157
|
+
return -1;
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
/**
|
|
161
|
+
* Named function-like ranges in JS/TS. Lexical, not a full parser: good enough
|
|
162
|
+
* to say which function a changed line belongs to.
|
|
163
|
+
* @returns {{name: string, line: number, start: number, end: number}[]}
|
|
164
|
+
*/
|
|
165
|
+
export function findFunctions(masked) {
|
|
166
|
+
const starts = lineStarts(masked);
|
|
167
|
+
const found = [];
|
|
168
|
+
const add = (name, at, bodyFrom) => {
|
|
169
|
+
if (!name || NOT_A_NAME.has(name)) return;
|
|
170
|
+
const range = bodyRange(masked, bodyFrom);
|
|
171
|
+
if (range) found.push({ name, line: lineOf(starts, at), start: at, end: range });
|
|
172
|
+
};
|
|
173
|
+
|
|
174
|
+
// function foo(…) { async function* foo<T>(…) {
|
|
175
|
+
for (const m of masked.matchAll(/\b(?:async\s+)?function\s*\*?\s*([A-Za-z_$][\w$]*)\s*(?:<[^>{]*>)?\s*\(/g)) {
|
|
176
|
+
add(m[1], m.index, m.index + m[0].length - 1);
|
|
177
|
+
}
|
|
178
|
+
// const foo = (…) => … const foo = async x => … const foo = function (…) {
|
|
179
|
+
for (const m of masked.matchAll(/\b(?:const|let|var)\s+([A-Za-z_$][\w$]*)\s*(?::[^=;]+)?=\s*(?:async\s+)?(?=function\b|\(|[A-Za-z_$][\w$]*\s*=>|<)/g)) {
|
|
180
|
+
add(m[1], m.index, m.index + m[0].length);
|
|
181
|
+
}
|
|
182
|
+
// foo: (…) => … foo: function (…) {
|
|
183
|
+
for (const m of masked.matchAll(/(?<![\w$.?])([A-Za-z_$][\w$]*)\s*:\s*(?:async\s+)?(?=function\b|\([^()]*\)\s*(?::[^=]+)?=>|[A-Za-z_$][\w$]*\s*=>)/g)) {
|
|
184
|
+
add(m[1], m.index, m.index + m[0].length);
|
|
185
|
+
}
|
|
186
|
+
// class / object methods: async foo(…) { static get bar() { foo<T>(…): Type {
|
|
187
|
+
for (const m of masked.matchAll(/^[ \t]*(?:(?:public|private|protected|static|async|override|readonly|get|set|abstract)\s+)*\*?\s*([A-Za-z_$#][\w$]*)\s*(?:<[^>\n]*>)?\s*\(/gm)) {
|
|
188
|
+
const open = m.index + m[0].length - 1;
|
|
189
|
+
const close = matchClose(masked, open);
|
|
190
|
+
if (close < 0) continue;
|
|
191
|
+
// Only a method if a body brace follows the parameter list (allowing a return type).
|
|
192
|
+
const tail = masked.slice(close + 1, close + 200).match(/^\s*(?::\s*[^{;]+?)?\s*\{/);
|
|
193
|
+
if (tail) add(m[1], m.index + m[0].indexOf(m[1]), open);
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// Dedupe by start, innermost-first lookups come from sorting by size.
|
|
197
|
+
const byStart = new Map();
|
|
198
|
+
for (const f of found) if (!byStart.has(f.start) || byStart.get(f.start).end < f.end) byStart.set(f.start, f);
|
|
199
|
+
return [...byStart.values()].sort((a, b) => a.start - b.start);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
/** From somewhere in a function header, find where its body ends. */
|
|
203
|
+
function bodyRange(masked, from) {
|
|
204
|
+
let k = from;
|
|
205
|
+
// Skip a parameter list if we're on one.
|
|
206
|
+
while (k < masked.length && /\s/.test(masked[k])) k++;
|
|
207
|
+
if (masked.startsWith('function', k)) {
|
|
208
|
+
const p = masked.indexOf('(', k);
|
|
209
|
+
if (p < 0) return null;
|
|
210
|
+
k = p;
|
|
211
|
+
}
|
|
212
|
+
if (masked[k] === '<') {
|
|
213
|
+
// generic arrow: <T,>(…) =>
|
|
214
|
+
const p = masked.indexOf('(', k);
|
|
215
|
+
if (p < 0) return null;
|
|
216
|
+
k = p;
|
|
217
|
+
}
|
|
218
|
+
if (masked[k] === '(') {
|
|
219
|
+
const close = matchClose(masked, k);
|
|
220
|
+
if (close < 0) return null;
|
|
221
|
+
k = close + 1;
|
|
222
|
+
} else {
|
|
223
|
+
// single-parameter arrow: x => …
|
|
224
|
+
const m = masked.slice(k).match(/^[A-Za-z_$][\w$]*\s*/);
|
|
225
|
+
if (m) k += m[0].length;
|
|
226
|
+
}
|
|
227
|
+
// Return type annotation, arrow, then the body.
|
|
228
|
+
const rest = masked.slice(k, k + 400);
|
|
229
|
+
const arrow = rest.match(/^\s*(?::\s*[^={;]+?)?\s*=>\s*/);
|
|
230
|
+
if (arrow) {
|
|
231
|
+
k += arrow[0].length;
|
|
232
|
+
if (masked[k] === '{') return matchClose(masked, k);
|
|
233
|
+
return expressionEnd(masked, k);
|
|
234
|
+
}
|
|
235
|
+
const brace = rest.match(/^\s*(?::\s*[^{;]+?)?\s*\{/);
|
|
236
|
+
if (brace) {
|
|
237
|
+
const open = k + brace[0].length - 1;
|
|
238
|
+
return matchClose(masked, open);
|
|
239
|
+
}
|
|
240
|
+
return null;
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
function expressionEnd(masked, from) {
|
|
244
|
+
let depth = 0;
|
|
245
|
+
for (let k = from; k < masked.length; k++) {
|
|
246
|
+
const ch = masked[k];
|
|
247
|
+
if ('([{'.includes(ch)) depth++;
|
|
248
|
+
else if (')]}'.includes(ch)) {
|
|
249
|
+
if (depth === 0) return k;
|
|
250
|
+
depth--;
|
|
251
|
+
} else if (depth === 0 && (ch === ';' || ch === ',')) return k;
|
|
252
|
+
else if (depth === 0 && ch === '\n' && !/^\s*[.?:+\-*/&|]/.test(masked.slice(k + 1, k + 40))) {
|
|
253
|
+
// a newline ends the expression unless the next line continues it
|
|
254
|
+
const before = masked.slice(from, k).trim();
|
|
255
|
+
if (before && !/[=(,:?+\-*/&|]$/.test(before)) return k;
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
return masked.length;
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
export function enclosingFunction(fns, offset) {
|
|
262
|
+
let best = null;
|
|
263
|
+
for (const f of fns) if (f.start <= offset && offset <= f.end && (!best || f.end - f.start < best.end - best.start)) best = f;
|
|
264
|
+
return best;
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// ---------- operators ----------
|
|
268
|
+
|
|
269
|
+
const SWAP = (map) => (s) => map[s];
|
|
270
|
+
|
|
271
|
+
export const OPERATORS = [
|
|
272
|
+
{
|
|
273
|
+
id: 'boundary',
|
|
274
|
+
label: 'boundary',
|
|
275
|
+
re: /(?<=\s)(<=|>=|<|>)(?=\s)/g,
|
|
276
|
+
swap: SWAP({ '<': '<=', '<=': '<', '>': '>=', '>=': '>' }),
|
|
277
|
+
why: 'no test sits exactly on the boundary',
|
|
278
|
+
},
|
|
279
|
+
{
|
|
280
|
+
id: 'equality',
|
|
281
|
+
label: 'equality',
|
|
282
|
+
re: /(?<=\s)(===|!==|==|!=)(?=\s)/g,
|
|
283
|
+
swap: SWAP({ '===': '!==', '!==': '===', '==': '!=', '!=': '==' }),
|
|
284
|
+
why: 'the outcome of this comparison is never asserted',
|
|
285
|
+
},
|
|
286
|
+
{
|
|
287
|
+
id: 'logical',
|
|
288
|
+
label: 'logical',
|
|
289
|
+
re: /(?<=\s)(&&|\|\|)(?=\s)/g,
|
|
290
|
+
swap: SWAP({ '&&': '||', '||': '&&' }),
|
|
291
|
+
why: 'the two conditions are never tested apart',
|
|
292
|
+
},
|
|
293
|
+
{
|
|
294
|
+
id: 'remove-not',
|
|
295
|
+
label: 'negation',
|
|
296
|
+
re: /(?<![!=\w$)\]])(!)(?=[\w$(])/g,
|
|
297
|
+
swap: () => '',
|
|
298
|
+
why: 'the negated case is not tested',
|
|
299
|
+
},
|
|
300
|
+
{
|
|
301
|
+
id: 'boolean',
|
|
302
|
+
label: 'boolean',
|
|
303
|
+
re: /(?<![.\w$])(true|false)(?![\w$])/g,
|
|
304
|
+
swap: SWAP({ true: 'false', false: 'true' }),
|
|
305
|
+
why: 'this flag or return value is never asserted',
|
|
306
|
+
},
|
|
307
|
+
{
|
|
308
|
+
id: 'arithmetic',
|
|
309
|
+
label: 'arithmetic',
|
|
310
|
+
re: /(?<=\s)([+\-*/%])(?=\s)/g,
|
|
311
|
+
swap: SWAP({ '+': '-', '-': '+', '*': '/', '/': '*', '%': '*' }),
|
|
312
|
+
why: 'the computed value is not checked exactly',
|
|
313
|
+
},
|
|
314
|
+
{
|
|
315
|
+
id: 'update',
|
|
316
|
+
label: 'update',
|
|
317
|
+
re: /(?<![+\-])(\+\+|--)(?![+\-=])|(?<=\s)(\+=|-=)(?=\s)/g,
|
|
318
|
+
swap: SWAP({ '++': '--', '--': '++', '+=': '-=', '-=': '+=' }),
|
|
319
|
+
why: 'the counter or running total is not checked',
|
|
320
|
+
},
|
|
321
|
+
];
|
|
322
|
+
|
|
323
|
+
const NEGATE = { id: 'negate-condition', label: 'condition', why: 'neither branch of this condition is pinned down by a test' };
|
|
324
|
+
|
|
325
|
+
/*
|
|
326
|
+
* Behavioural defects: the ways real changes go wrong, not just a flipped
|
|
327
|
+
* token. Found by pattern on the masked source (so never inside strings or
|
|
328
|
+
* comments), and labelled as such: a name like `requireAdmin` or `retries`
|
|
329
|
+
* is what marks the code, not a type checker.
|
|
330
|
+
*/
|
|
331
|
+
export const BEHAVIOURS = [
|
|
332
|
+
{ id: 'commit-to-rollback', category: 'transactions', why: 'nothing checks that the work is actually committed' },
|
|
333
|
+
{ id: 'drop-rollback', category: 'transactions', why: 'nothing checks that a failure undoes the partial writes' },
|
|
334
|
+
{ id: 'bypass-auth', category: 'authorization', why: 'no test proves that a caller without permission is turned away' },
|
|
335
|
+
{ id: 'drop-auth-check', category: 'authorization', why: 'no test proves that a caller without permission is turned away' },
|
|
336
|
+
{ id: 'retry-once', category: 'retries', why: 'nothing tests what happens when the first attempt fails' },
|
|
337
|
+
{ id: 'no-backoff', category: 'retries', why: 'nothing checks the wait between attempts' },
|
|
338
|
+
{ id: 'off-by-one', category: 'boundaries', why: 'no test checks the first or the last item' },
|
|
339
|
+
{ id: 'drop-await', category: 'concurrency', why: 'nothing checks that this finishes before the code moves on' },
|
|
340
|
+
{ id: 'drop-lock', category: 'concurrency', why: 'nothing exercises two of these running at the same time' },
|
|
341
|
+
{ id: 'all-settled', category: 'concurrency', why: 'nothing checks that one failed task fails the whole batch' },
|
|
342
|
+
];
|
|
343
|
+
|
|
344
|
+
export const OPERATOR_WHY = Object.fromEntries([...OPERATORS, NEGATE, ...BEHAVIOURS].map((o) => [o.id, o.why]));
|
|
345
|
+
|
|
346
|
+
/** What kind of defect an operator plants. */
|
|
347
|
+
export const CATEGORY = {
|
|
348
|
+
boundary: 'boundaries',
|
|
349
|
+
equality: 'logic',
|
|
350
|
+
logical: 'logic',
|
|
351
|
+
'remove-not': 'logic',
|
|
352
|
+
'negate-condition': 'logic',
|
|
353
|
+
boolean: 'logic',
|
|
354
|
+
arithmetic: 'arithmetic',
|
|
355
|
+
update: 'arithmetic',
|
|
356
|
+
...Object.fromEntries(BEHAVIOURS.map((b) => [b.id, b.category])),
|
|
357
|
+
};
|
|
358
|
+
/** Categories that describe behaviour rather than syntax. */
|
|
359
|
+
export const BEHAVIOURAL_CATEGORIES = new Set(['transactions', 'authorization', 'retries', 'concurrency']);
|
|
360
|
+
export const isBehavioural = (op) => BEHAVIOURAL_CATEGORIES.has(CATEGORY[op]) || op === 'off-by-one';
|
|
361
|
+
|
|
362
|
+
// Names that mark code as being about access, retries or array positions.
|
|
363
|
+
const AUTH_WORDS = /\b(?:auth\w*|Auth\w*|authori[sz]\w*|permi\w*|can[A-Z]\w*|isAdmin|is[A-Z]\w*(?:Admin|Owner|Member|Allowed|Authori[sz]ed)|admin\w*|owner\w*|roles?|scopes?|allowed\w*|forbidden|unauthori[sz]ed|session|currentUser|acl|policy|access\w*)\b/;
|
|
364
|
+
const AUTH_CALL = /^(?:require|assert|ensure|check|verify|enforce|authori[sz]e|guard|can|must)\w*$/i;
|
|
365
|
+
const AUTH_NAME = /auth|perm|role|admin|owner|access|scope|login|session|can[A-Z]|allowed|policy|acl/i;
|
|
366
|
+
const RETRY_WORDS = /\b(?:[a-z]*[Rr]etr(?:y|ies|ied)[A-Za-z]*|[a-z]*[Aa]ttempts?[A-Za-z]*|(?:max|num)?[Tt]ries|[a-z]*[Bb]ackoff[A-Za-z]*)\b/;
|
|
367
|
+
const INDEX_WORDS = /\b(?:length|index|idx|count|size|limit|offset|page|end|start|last|first|len|total|cursor)\b/i;
|
|
368
|
+
const DELAY_CALL = /\b(sleep|delay|wait|pause|backoff\w*|setTimeout)\s*\(/g;
|
|
369
|
+
|
|
370
|
+
/** The whole line as one statement (no block, no control flow), or null. */
|
|
371
|
+
function lineStatement(mline) {
|
|
372
|
+
const lead = mline.match(/^\s*/)[0].length;
|
|
373
|
+
const body = mline.slice(lead).replace(/\s+$/, '');
|
|
374
|
+
if (!body || /[{}]/.test(body) || /^(?:if|for|while|switch|return|throw|else|case|default|const|let|var|function|class|try|catch|finally|do)\b/.test(body)) return null;
|
|
375
|
+
return [lead, lead + body.length];
|
|
376
|
+
}
|
|
377
|
+
|
|
378
|
+
// Lines where an operator-looking token isn't an operator.
|
|
379
|
+
const NOT_CODE_LINE = /^\s*(?:import\b|export\s+(?:\*|\{[^}]*\}\s+from)|\/\/|\*|type\s+\w+\s*=|interface\b|@)/;
|
|
380
|
+
|
|
381
|
+
/**
|
|
382
|
+
* Every mutant on the given lines of one file.
|
|
383
|
+
* @param {string} file
|
|
384
|
+
* @param {string} src
|
|
385
|
+
* @param {Set<number>|null} lines 1-based line numbers to mutate (null = all)
|
|
386
|
+
*/
|
|
387
|
+
export function generateMutants(file, src, lines) {
|
|
388
|
+
const masked = maskJs(src);
|
|
389
|
+
const starts = lineStarts(src);
|
|
390
|
+
const fns = findFunctions(masked);
|
|
391
|
+
const srcLines = src.split('\n');
|
|
392
|
+
const mutants = [];
|
|
393
|
+
const seen = new Set();
|
|
394
|
+
|
|
395
|
+
const push = (operator, start, end, replacement) => {
|
|
396
|
+
const original = src.slice(start, end);
|
|
397
|
+
if (original === replacement) return;
|
|
398
|
+
const line = lineOf(starts, start);
|
|
399
|
+
const col = start - starts[line - 1] + 1;
|
|
400
|
+
const id = `${file}:${line}:${col}:${operator}`;
|
|
401
|
+
if (seen.has(id)) return;
|
|
402
|
+
seen.add(id);
|
|
403
|
+
const mutated = src.slice(0, start) + replacement + src.slice(end);
|
|
404
|
+
const fn = enclosingFunction(fns, start);
|
|
405
|
+
const lineEnd = (n) => {
|
|
406
|
+
const s = mutated.split('\n');
|
|
407
|
+
return s.slice(line - 1, line - 1 + n).join('\n');
|
|
408
|
+
};
|
|
409
|
+
const spanLines = src.slice(start, end).split('\n').length;
|
|
410
|
+
mutants.push({
|
|
411
|
+
id,
|
|
412
|
+
file,
|
|
413
|
+
line,
|
|
414
|
+
col,
|
|
415
|
+
operator,
|
|
416
|
+
original,
|
|
417
|
+
replacement,
|
|
418
|
+
start,
|
|
419
|
+
end,
|
|
420
|
+
function: fn ? fn.name : null,
|
|
421
|
+
functionLine: fn ? fn.line : null,
|
|
422
|
+
before: srcLines.slice(line - 1, line - 1 + spanLines).join('\n').trim(),
|
|
423
|
+
after: lineEnd(spanLines + (replacement.split('\n').length - spanLines)).trim(),
|
|
424
|
+
});
|
|
425
|
+
};
|
|
426
|
+
|
|
427
|
+
for (let ln = 1; ln <= starts.length; ln++) {
|
|
428
|
+
if (lines && !lines.has(ln)) continue;
|
|
429
|
+
const a = starts[ln - 1];
|
|
430
|
+
const b = ln < starts.length ? starts[ln] - 1 : src.length;
|
|
431
|
+
const mline = masked.slice(a, b);
|
|
432
|
+
if (!mline.trim() || NOT_CODE_LINE.test(mline)) continue;
|
|
433
|
+
|
|
434
|
+
for (const op of OPERATORS) {
|
|
435
|
+
op.re.lastIndex = 0;
|
|
436
|
+
for (const m of mline.matchAll(op.re)) {
|
|
437
|
+
const tok = m[1] ?? m[2];
|
|
438
|
+
const at = a + m.index;
|
|
439
|
+
const rep = op.swap(tok);
|
|
440
|
+
if (rep === undefined) continue;
|
|
441
|
+
push(op.id, at, at + tok.length, rep);
|
|
442
|
+
}
|
|
443
|
+
}
|
|
444
|
+
// if (cond) → if (!(cond))
|
|
445
|
+
for (const m of mline.matchAll(/\b(?:if|while)\s*\(/g)) {
|
|
446
|
+
const open = a + m.index + m[0].length - 1;
|
|
447
|
+
const close = matchClose(masked, open);
|
|
448
|
+
if (close < 0) continue;
|
|
449
|
+
const cond = src.slice(open + 1, close);
|
|
450
|
+
// `if (!x)` is already covered by remove-not; `!(!x)` would be the same mutant twice.
|
|
451
|
+
if (!cond.trim() || /^\s*!\s*(?:[\w$.]+|\([^()]*\))\s*$/.test(cond)) continue;
|
|
452
|
+
push(NEGATE.id, open + 1, close, `!(${cond})`);
|
|
453
|
+
}
|
|
454
|
+
behaviouralMutants(mline, a, masked, src, push);
|
|
455
|
+
}
|
|
456
|
+
return mutants;
|
|
457
|
+
}
|
|
458
|
+
|
|
459
|
+
/** Realistic defects on one line: transactions, access checks, retries, positions, concurrency. */
|
|
460
|
+
function behaviouralMutants(mline, a, masked, src, push) {
|
|
461
|
+
const stmt = lineStatement(mline);
|
|
462
|
+
|
|
463
|
+
// transactions: commit becomes rollback; a rollback disappears
|
|
464
|
+
for (const m of mline.matchAll(/\.(commit)\s*\(/g)) push('commit-to-rollback', a + m.index + 1, a + m.index + 1 + 6, 'rollback');
|
|
465
|
+
if (stmt && /\.\s*rollback\s*\(/.test(mline)) push('drop-rollback', a + stmt[0], a + stmt[1], 'void 0;');
|
|
466
|
+
|
|
467
|
+
// authorization: a guard that turns callers away never fires
|
|
468
|
+
for (const m of mline.matchAll(/\bif\s*\(/g)) {
|
|
469
|
+
const open = a + m.index + m[0].length - 1;
|
|
470
|
+
const close = matchClose(masked, open);
|
|
471
|
+
if (close < 0) continue;
|
|
472
|
+
const cond = masked.slice(open + 1, close);
|
|
473
|
+
if (!AUTH_WORDS.test(cond)) continue;
|
|
474
|
+
// only guards: the branch leaves (throw, return, a 4xx response, next(err))
|
|
475
|
+
if (!/^\s*(?:\{\s*)?(?:throw\b|return\b|res(?:ponse)?\.status\s*\(\s*4\d\d|next\s*\(\s*[\w$])/.test(masked.slice(close + 1, close + 200))) continue;
|
|
476
|
+
push('bypass-auth', open + 1, close, 'false');
|
|
477
|
+
}
|
|
478
|
+
// ...or a guard call (`await requireAdmin(user)`) is dropped
|
|
479
|
+
if (stmt) {
|
|
480
|
+
const call = mline.slice(stmt[0], stmt[1]).match(/^(?:await\s+)?(?:[\w$]+\.)*([\w$]+)\s*\(/);
|
|
481
|
+
if (call && AUTH_CALL.test(call[1]) && AUTH_NAME.test(call[1])) push('drop-auth-check', a + stmt[0], a + stmt[1], 'void 0;');
|
|
482
|
+
}
|
|
483
|
+
|
|
484
|
+
// retries: only one attempt, or no wait between attempts
|
|
485
|
+
if (RETRY_WORDS.test(mline)) {
|
|
486
|
+
for (const m of mline.matchAll(/(?<=\s)(<=?)\s+([\w$.]+)/g)) {
|
|
487
|
+
if (m[2] === '1' || m[2] === '0') continue;
|
|
488
|
+
const at = a + m.index + m[0].length - m[2].length;
|
|
489
|
+
push('retry-once', at, at + m[2].length, m[1] === '<=' ? '0' : '1');
|
|
490
|
+
}
|
|
491
|
+
}
|
|
492
|
+
for (const m of mline.matchAll(DELAY_CALL)) {
|
|
493
|
+
const open = a + m.index + m[0].length - 1;
|
|
494
|
+
const close = matchClose(masked, open);
|
|
495
|
+
if (close < 0) continue;
|
|
496
|
+
const inner = src.slice(open + 1, close);
|
|
497
|
+
// setTimeout(fn, ms): the delay is the last argument; sleep(ms): the only one
|
|
498
|
+
let from = open + 1;
|
|
499
|
+
if (m[1] === 'setTimeout') {
|
|
500
|
+
const comma = masked.slice(open + 1, close).lastIndexOf(',');
|
|
501
|
+
if (comma < 0) continue;
|
|
502
|
+
from = open + 1 + comma + 1;
|
|
503
|
+
}
|
|
504
|
+
const arg = src.slice(from, close);
|
|
505
|
+
if (!arg.trim() || /^\s*0\s*$/.test(arg) || (m[1] !== 'setTimeout' && inner.includes(','))) continue;
|
|
506
|
+
const lead = arg.match(/^\s*/)[0].length;
|
|
507
|
+
push('no-backoff', from + lead, close, '0');
|
|
508
|
+
}
|
|
509
|
+
|
|
510
|
+
// positions: an index or length loses its -1 / +1
|
|
511
|
+
if (INDEX_WORDS.test(mline)) {
|
|
512
|
+
for (const m of mline.matchAll(/(?<=[\w$\])])(\s[+-]\s1)(?![\w$.])/g)) push('off-by-one', a + m.index, a + m.index + m[1].length, '');
|
|
513
|
+
}
|
|
514
|
+
|
|
515
|
+
// concurrency: an await is dropped, a lock is skipped, Promise.all stops failing fast
|
|
516
|
+
for (const m of mline.matchAll(/(?<!for\s)\bawait\s+(?=[\w$([])/g)) push('drop-await', a + m.index, a + m.index + m[0].length, '');
|
|
517
|
+
if (stmt && /\.(?:acquire|lock|runExclusive|waitForUnlock)\s*\(|\b(?:acquireLock|lock)\s*\(/.test(mline) && !/\.release\s*\(|\bunlock\s*\(/.test(mline)) push('drop-lock', a + stmt[0], a + stmt[1], 'void 0;');
|
|
518
|
+
for (const m of mline.matchAll(/\bPromise\.(all)\s*\(/g)) {
|
|
519
|
+
const at = a + m.index + 'Promise.'.length;
|
|
520
|
+
push('all-settled', at, at + 3, 'allSettled');
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
/**
|
|
525
|
+
* A stable id for a mutant that outlives line shifts: the same change to the
|
|
526
|
+
* same code in the same function gets the same fingerprint, so a triage
|
|
527
|
+
* decision, or an agent's fix, carries over between runs.
|
|
528
|
+
*/
|
|
529
|
+
export function mutantFingerprint(m) {
|
|
530
|
+
const firstLine = String(m.before ?? '').split('\n')[0].replace(/\s+/g, ' ').trim();
|
|
531
|
+
return createHash('sha256').update([m.file, m.function ?? '', m.operator, m.original ?? '', m.replacement ?? '', firstLine].join('\u0000')).digest('hex').slice(0, 32);
|
|
532
|
+
}
|
|
533
|
+
|
|
534
|
+
/**
|
|
535
|
+
* Pick which mutants to run: spread across functions first, then operators,
|
|
536
|
+
* so a cap still touches every changed function. Deterministic.
|
|
537
|
+
*/
|
|
538
|
+
export function prioritize(mutants) {
|
|
539
|
+
const byFn = new Map();
|
|
540
|
+
for (const m of [...mutants].sort((x, y) => x.file.localeCompare(y.file) || x.line - y.line || x.col - y.col)) {
|
|
541
|
+
const k = `${m.file}#${m.function ?? '(top level)'}`;
|
|
542
|
+
if (!byFn.has(k)) byFn.set(k, new Map());
|
|
543
|
+
const ops = byFn.get(k);
|
|
544
|
+
if (!ops.has(m.operator)) ops.set(m.operator, []);
|
|
545
|
+
ops.get(m.operator).push(m);
|
|
546
|
+
}
|
|
547
|
+
// Within a function: round-robin across operators.
|
|
548
|
+
const queues = [...byFn.values()].map((ops) => {
|
|
549
|
+
// behavioural defects first, so a capped run still reaches them
|
|
550
|
+
const lists = [...ops.entries()].sort((x, y) => Number(isBehavioural(y[0])) - Number(isBehavioural(x[0]))).map(([, l]) => l);
|
|
551
|
+
const q = [];
|
|
552
|
+
for (let i = 0; lists.some((l) => l.length > i); i++) for (const l of lists) if (l[i]) q.push(l[i]);
|
|
553
|
+
return q;
|
|
554
|
+
});
|
|
555
|
+
const out = [];
|
|
556
|
+
for (let i = 0; queues.some((q) => q.length > i); i++) for (const q of queues) if (q[i]) out.push(q[i]);
|
|
557
|
+
return out;
|
|
558
|
+
}
|
|
559
|
+
|
|
560
|
+
export function applyMutant(src, m) {
|
|
561
|
+
return src.slice(0, m.start) + m.replacement + src.slice(m.end);
|
|
562
|
+
}
|
|
563
|
+
|
|
564
|
+
/** One sentence on what a surviving mutant says about the tests. */
|
|
565
|
+
export function explain(m) {
|
|
566
|
+
const where = m.function ? `\`${m.function}\`` : 'top-level code';
|
|
567
|
+
const change =
|
|
568
|
+
m.operator === 'negate-condition' ? `inverting \`${clip(m.original)}\``
|
|
569
|
+
: m.operator === 'remove-not' ? 'dropping the `!`'
|
|
570
|
+
: m.replacement === 'void 0;' ? `removing \`${clip(m.original)}\``
|
|
571
|
+
: m.operator === 'bypass-auth' ? `skipping the check \`${clip(m.original)}\``
|
|
572
|
+
: m.operator === 'drop-await' ? `dropping the \`await\` in \`${clip(m.before)}\``
|
|
573
|
+
: m.operator === 'off-by-one' ? `dropping \`${m.original.trim()}\``
|
|
574
|
+
: m.operator === 'no-backoff' ? `waiting 0 instead of \`${clip(m.original)}\``
|
|
575
|
+
: `\`${m.original}\` → \`${m.replacement}\``;
|
|
576
|
+
return `In ${where}, ${change} still passed every test: ${OPERATOR_WHY[m.operator]}.`;
|
|
577
|
+
}
|
|
578
|
+
|
|
579
|
+
const clip = (s) => {
|
|
580
|
+
const one = s.replace(/\s+/g, ' ').trim();
|
|
581
|
+
return one.length > 48 ? one.slice(0, 45) + '…' : one;
|
|
582
|
+
};
|
package/src/redact.js
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
1
|
+
// Keeping secrets and local paths out of anything crossexam writes or shares.
|
|
2
|
+
import os from 'node:os';
|
|
3
|
+
|
|
4
|
+
// Values that look like secrets never leave in a report.
|
|
5
|
+
const SECRET_PATTERNS = [
|
|
6
|
+
/\b(?:sk|pk|rk)_(?:live|test)_[0-9A-Za-z]{10,}/g,
|
|
7
|
+
/\bsk-[A-Za-z0-9_-]{20,}/g,
|
|
8
|
+
/\bgh[pousr]_[A-Za-z0-9]{30,}/g,
|
|
9
|
+
/\bgithub_pat_[A-Za-z0-9_]{30,}/g,
|
|
10
|
+
/\bAKIA[0-9A-Z]{16}\b/g,
|
|
11
|
+
/\bxox[baprs]-[A-Za-z0-9-]{10,}/g,
|
|
12
|
+
/\bAIza[0-9A-Za-z_-]{35}\b/g,
|
|
13
|
+
/-----BEGIN [A-Z ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z ]*PRIVATE KEY-----|$)/g,
|
|
14
|
+
/\beyJ[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}\.[A-Za-z0-9_-]{8,}/g,
|
|
15
|
+
];
|
|
16
|
+
const SECRET_ASSIGN = /((?:password|passwd|secret|token|api[_-]?key|access[_-]?key|private[_-]?key|client[_-]?secret)["']?\s*[:=]\s*)(["'`])([^"'`\n]{6,})\2/gi;
|
|
17
|
+
|
|
18
|
+
export function redact(s) {
|
|
19
|
+
if (typeof s !== 'string' || !s) return s;
|
|
20
|
+
let out = s;
|
|
21
|
+
for (const re of SECRET_PATTERNS) out = out.replace(re, '[redacted]');
|
|
22
|
+
return out.replace(SECRET_ASSIGN, (_, k, q) => `${k}${q}[redacted]${q}`);
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
/** A path under the home folder, written from `~`. */
|
|
26
|
+
export function tildify(p) {
|
|
27
|
+
const h = os.homedir();
|
|
28
|
+
return typeof p === 'string' && p.toLowerCase().startsWith(h.toLowerCase()) ? '~' + p.slice(h.length) : p;
|
|
29
|
+
}
|
|
30
|
+
|
|
31
|
+
const escapeRe = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
|
|
32
|
+
|
|
33
|
+
// Absolute paths that would say something about the machine: drive letters,
|
|
34
|
+
// home folders, temp folders, CI workspaces.
|
|
35
|
+
const ABSOLUTE = /(?:\b[A-Za-z]:[\\/]|(?<![\w.~])\/(?:home|Users|root|tmp|private|var|opt|mnt|srv|github|runner|workspace|builds)\/)[^\s'"`<>|)]*/g;
|
|
36
|
+
|
|
37
|
+
/**
|
|
38
|
+
* Make text safe to leave this machine: paths inside `root` become relative,
|
|
39
|
+
* the home folder becomes `~`, any other absolute path becomes `[path]`, and
|
|
40
|
+
* secret-looking values are redacted.
|
|
41
|
+
*/
|
|
42
|
+
export function scrubText(s, root) {
|
|
43
|
+
if (typeof s !== 'string' || !s) return s;
|
|
44
|
+
let out = s;
|
|
45
|
+
if (root) {
|
|
46
|
+
// both slash styles; Windows paths compare case-insensitively
|
|
47
|
+
const variants = new Set([root, root.replace(/\\/g, '/'), root.replace(/\//g, '\\')]);
|
|
48
|
+
for (const v of variants) {
|
|
49
|
+
if (v.length < 2) continue;
|
|
50
|
+
out = out.replace(new RegExp(escapeRe(v) + '[\\\\/]?', process.platform === 'win32' || /^[A-Za-z]:/.test(v) ? 'gi' : 'g'), '');
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const home = os.homedir();
|
|
54
|
+
for (const v of new Set([home, home.replace(/\\/g, '/')])) {
|
|
55
|
+
if (v.length > 3) out = out.replace(new RegExp(escapeRe(v), 'gi'), '~');
|
|
56
|
+
}
|
|
57
|
+
out = out.replace(ABSOLUTE, '[path]');
|
|
58
|
+
return redact(out);
|
|
59
|
+
}
|