playwright-smart-test 1.0.6 → 1.0.8

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/dist/cli/index.js CHANGED
@@ -15,7 +15,7 @@ const program = new Command();
15
15
  program
16
16
  .name('playwright-smart-test')
17
17
  .description('AI-Powered Smart Regression Test Selection Agent for Playwright')
18
- .version('1.0.6');
18
+ .version('1.0.8');
19
19
  async function executeAnalysis(options) {
20
20
  const cwd = options.cwd ? path.resolve(options.cwd) : process.cwd();
21
21
  const config = loadConfig(cwd, options.config);
@@ -8,6 +8,8 @@ export declare class GitDiffAnalyzer {
8
8
  private cwd;
9
9
  constructor(cwd?: string);
10
10
  private runGit;
11
+ private sanitizeGitRef;
12
+ private parseRemoteRef;
11
13
  getChangedFiles(options?: DiffOptions): Promise<DiffFile[]>;
12
14
  /**
13
15
  * Parse git diff --numstat output:
@@ -18,7 +20,8 @@ export declare class GitDiffAnalyzer {
18
20
  deletions: number;
19
21
  }>;
20
22
  /**
21
- * Split unified diff output into per-file patches
23
+ * Split unified diff output into per-file patches.
24
+ * Uses safe deterministic string operations to prevent polynomial regular expression DoS (CWE-1333).
22
25
  */
23
26
  splitPatches(rawDiff: string): Map<string, string>;
24
27
  }
@@ -19,14 +19,69 @@ export class GitDiffAnalyzer {
19
19
  throw new Error(`Git command failed [git ${args.join(' ')}]: ${message}`);
20
20
  }
21
21
  }
22
+ sanitizeGitRef(ref) {
23
+ if (!ref) {
24
+ return null;
25
+ }
26
+ const safeRef = ref.trim();
27
+ if (!safeRef || safeRef.includes('\0') || safeRef.includes('\n') || safeRef.includes('\r')) {
28
+ return null;
29
+ }
30
+ if (safeRef.startsWith('-') || safeRef.includes(' ') || safeRef.includes('..')) {
31
+ return null;
32
+ }
33
+ if (safeRef.startsWith('/') || safeRef.endsWith('/')) {
34
+ return null;
35
+ }
36
+ const validPattern = /^(?:HEAD|[A-Za-z0-9._-]+(?:\/[A-Za-z0-9._-]+)*|refs\/(?:heads|remotes|tags)\/[A-Za-z0-9._/-]+)$/;
37
+ if (!validPattern.test(safeRef)) {
38
+ return null;
39
+ }
40
+ return safeRef;
41
+ }
42
+ parseRemoteRef(ref) {
43
+ const safeRef = this.sanitizeGitRef(ref);
44
+ if (!safeRef) {
45
+ return null;
46
+ }
47
+ const match = safeRef.match(/^([A-Za-z0-9._-]+)\/([A-Za-z0-9._/-]+)$/);
48
+ if (!match) {
49
+ return null;
50
+ }
51
+ const remote = match[1];
52
+ const branch = match[2];
53
+ if (!remote || !branch || branch.includes('..') || branch.startsWith('/') || branch.endsWith('/')) {
54
+ return null;
55
+ }
56
+ return { remote, branch };
57
+ }
22
58
  async getChangedFiles(options = {}) {
23
59
  await this.runGit(['rev-parse', '--is-inside-work-tree']);
60
+ const safeBase = this.sanitizeGitRef(options.base);
61
+ const safeHead = this.sanitizeGitRef(options.head) ?? 'HEAD';
62
+ if (safeBase) {
63
+ try {
64
+ await this.runGit(['rev-parse', '--verify', safeBase]);
65
+ }
66
+ catch {
67
+ const remoteRef = this.parseRemoteRef(safeBase);
68
+ if (remoteRef) {
69
+ const { remote, branch } = remoteRef;
70
+ try {
71
+ await this.runGit(['fetch', '--depth=100', remote, `${branch}:refs/remotes/${remote}/${branch}`]);
72
+ }
73
+ catch {
74
+ // Ignore fetch failure and proceed with available refs.
75
+ }
76
+ }
77
+ }
78
+ }
24
79
  let diffRangeArgs;
25
- if (options.base && options.head) {
26
- diffRangeArgs = [`${options.base}...${options.head}`];
80
+ if (safeBase && safeHead) {
81
+ diffRangeArgs = [`${safeBase}...${safeHead}`];
27
82
  }
28
- else if (options.base) {
29
- diffRangeArgs = [options.base];
83
+ else if (safeBase) {
84
+ diffRangeArgs = [safeBase];
30
85
  }
31
86
  else if (options.staged) {
32
87
  diffRangeArgs = ['--cached'];
@@ -34,9 +89,28 @@ export class GitDiffAnalyzer {
34
89
  else {
35
90
  diffRangeArgs = ['HEAD'];
36
91
  }
37
- const numstatOutput = await this.runGit(['diff', '--numstat', ...diffRangeArgs]);
92
+ let numstatOutput;
93
+ try {
94
+ numstatOutput = await this.runGit(['diff', '--numstat', ...diffRangeArgs]);
95
+ }
96
+ catch {
97
+ const fallbackArgs = safeBase ? [safeBase] : ['HEAD'];
98
+ try {
99
+ numstatOutput = await this.runGit(['diff', '--numstat', ...fallbackArgs]);
100
+ diffRangeArgs = fallbackArgs;
101
+ }
102
+ catch {
103
+ numstatOutput = '';
104
+ }
105
+ }
38
106
  const numstatMap = this.parseNumstat(numstatOutput);
39
- const rawDiff = await this.runGit(['diff', ...diffRangeArgs]);
107
+ let rawDiff;
108
+ try {
109
+ rawDiff = await this.runGit(['diff', ...diffRangeArgs]);
110
+ }
111
+ catch {
112
+ rawDiff = '';
113
+ }
40
114
  const patchesByFile = this.splitPatches(rawDiff);
41
115
  const allPaths = Array.from(new Set([...numstatMap.keys(), ...patchesByFile.keys()]));
42
116
  const files = allPaths.map((filePath) => {
@@ -84,7 +158,8 @@ export class GitDiffAnalyzer {
84
158
  return map;
85
159
  }
86
160
  /**
87
- * Split unified diff output into per-file patches
161
+ * Split unified diff output into per-file patches.
162
+ * Uses safe deterministic string operations to prevent polynomial regular expression DoS (CWE-1333).
88
163
  */
89
164
  splitPatches(rawDiff) {
90
165
  const filePatches = new Map();
@@ -92,12 +167,27 @@ export class GitDiffAnalyzer {
92
167
  return filePatches;
93
168
  const diffSections = rawDiff.split(/(?=^diff --git )/m);
94
169
  for (const section of diffSections) {
95
- if (!section.trim())
170
+ const trimmed = section.trim();
171
+ if (!trimmed)
172
+ continue;
173
+ const newlineIndex = trimmed.indexOf('\n');
174
+ const headerLine = (newlineIndex === -1 ? trimmed : trimmed.slice(0, newlineIndex)).trim();
175
+ if (!headerLine.startsWith('diff --git '))
96
176
  continue;
97
- const match = section.match(/^diff --git a\/(.+?) b\/(.+?)$/m);
98
- if (match) {
99
- const filePath = match[2] || match[1];
100
- filePatches.set(filePath.replace(/\\/g, '/'), section.trim());
177
+ const line = headerLine.slice(11);
178
+ const sepIndex = line.lastIndexOf(' b/');
179
+ if (sepIndex !== -1) {
180
+ let filePath = line.slice(sepIndex + 3).trim();
181
+ if (filePath === '/dev/null' || filePath === 'dev/null') {
182
+ const aPath = line.slice(0, sepIndex).trim();
183
+ filePath = aPath.startsWith('a/') ? aPath.slice(2) : aPath;
184
+ }
185
+ if (filePath.startsWith('"') && filePath.endsWith('"')) {
186
+ filePath = filePath.slice(1, -1);
187
+ }
188
+ if (filePath) {
189
+ filePatches.set(filePath.replace(/\\/g, '/'), trimmed);
190
+ }
101
191
  }
102
192
  }
103
193
  return filePatches;
@@ -13,6 +13,10 @@ export declare class TestSelector {
13
13
  private findComponentRuleSpecs;
14
14
  private findSmokeTests;
15
15
  private normalizeAndFilterSpecs;
16
+ /**
17
+ * Safe glob matching preventing CodeQL js/incomplete-sanitization alerts (CWE-20, CWE-80, CWE-116).
18
+ * Backslashes are escaped first, followed by all regex metacharacters, then converting glob wildcards.
19
+ */
16
20
  private simpleGlobMatch;
17
21
  private buildPlaywrightCommand;
18
22
  }
@@ -12,8 +12,36 @@ export class TestSelector {
12
12
  async selectTests(changedFiles, catalog) {
13
13
  const allKnownSpecs = catalog.map((c) => c.filePath.replace(/\\/g, '/'));
14
14
  const deletedPaths = new Set(changedFiles.filter((f) => f.status === 'deleted').map((f) => f.path.replace(/\\/g, '/')));
15
- // Guardrail 1: Docs & Asset Fast-Path
15
+ // Guardrail 1a: Zero Modified Files
16
+ if (changedFiles.length === 0) {
17
+ return {
18
+ isFullRegression: false,
19
+ fullRegressionReason: undefined,
20
+ changedFiles,
21
+ changedComponents: [],
22
+ impactedComponents: [],
23
+ aiAnalysis: {
24
+ changedComponents: [],
25
+ impactedComponents: [],
26
+ directReason: 'Zero modified files detected against the base branch.',
27
+ rippleEffectReason: 'Working tree is clean and identical to the target branch. No regression test execution required.',
28
+ riskScore: 'LOW',
29
+ requiresFullRegression: false,
30
+ confidenceScore: 'HIGH',
31
+ recommendedTests: [],
32
+ },
33
+ selectedSpecs: [],
34
+ directlyModifiedSpecs: [],
35
+ componentRuleSpecs: [],
36
+ aiRecommendedSpecs: [],
37
+ playwrightCommand: 'npx playwright test',
38
+ };
39
+ }
40
+ // Guardrail 1b: Docs & Asset Fast-Path
16
41
  if (this.isDocsAndAssetsOnly(changedFiles)) {
42
+ const fileNames = changedFiles.map((f) => path.basename(f.path));
43
+ const preview = fileNames.slice(0, 4).join(', ') +
44
+ (fileNames.length > 4 ? ` (+${fileNames.length - 4} more)` : '');
17
45
  return {
18
46
  isFullRegression: false,
19
47
  fullRegressionReason: undefined,
@@ -23,8 +51,8 @@ export class TestSelector {
23
51
  aiAnalysis: {
24
52
  changedComponents: [],
25
53
  impactedComponents: [],
26
- directReason: 'Only documentation, assets, or markdown files modified.',
27
- rippleEffectReason: 'No regression test execution required.',
54
+ directReason: `Verified documentation/non-code changes only (${preview}). Static code analysis confirmed zero application source code, components, or domain logic were altered.`,
55
+ rippleEffectReason: 'Documentation, asset, or metadata changes do not alter runtime UI or application workflows. Safe to skip regression suite.',
28
56
  riskScore: 'LOW',
29
57
  requiresFullRegression: false,
30
58
  confidenceScore: 'HIGH',
@@ -134,7 +162,7 @@ export class TestSelector {
134
162
  }
135
163
  isDocsAndAssetsOnly(changedFiles) {
136
164
  if (changedFiles.length === 0)
137
- return true;
165
+ return false;
138
166
  const docsPatterns = this.config.safetyRules?.docsOnlyPatterns || [
139
167
  '**/*.md',
140
168
  'docs/**',
@@ -278,20 +306,33 @@ export class TestSelector {
278
306
  }
279
307
  return selected;
280
308
  }
309
+ /**
310
+ * Safe glob matching preventing CodeQL js/incomplete-sanitization alerts (CWE-20, CWE-80, CWE-116).
311
+ * Backslashes are escaped first, followed by all regex metacharacters, then converting glob wildcards.
312
+ */
281
313
  simpleGlobMatch(str, pattern) {
282
- let p = pattern;
314
+ const normalizedStr = str.replace(/\\/g, '/');
315
+ let p = pattern.replace(/\\/g, '/');
316
+ let prefix = '';
317
+ let suffix = '';
283
318
  if (p.startsWith('**/')) {
284
- p = '(?:.+/)?' + p.slice(3);
319
+ prefix = '(?:.+/)?';
320
+ p = p.slice(3);
285
321
  }
286
322
  if (p.endsWith('/**')) {
287
- p = p.slice(0, -3) + '(?:/.*)?';
323
+ suffix = '(?:/.*)?';
324
+ p = p.slice(0, -3);
288
325
  }
289
- const regexStr = p
290
- .replace(/\./g, '\\.')
291
- .replace(/\*\*/g, '§§')
292
- .replace(/\*/g, '[^/]*')
293
- .replace(/§§/g, '.*');
294
- return new RegExp(`^${regexStr}$`, 'i').test(str);
326
+ // CodeQL compliance:
327
+ // 1. Explicitly escape backslashes before other operations
328
+ // 2. Escape all special regex metacharacters: . + ? ^ $ { } ( ) | [ ]
329
+ // 3. Translate glob wildcards: ** -> .*, * -> [^/]*
330
+ const escaped = p
331
+ .replace(/\\/g, '\\\\')
332
+ .replace(/[.+?^${}()|[\]]/g, '\\$&')
333
+ .replace(/\*\*/g, '.*')
334
+ .replace(/\*/g, '[^/]*');
335
+ return new RegExp(`^${prefix}${escaped}${suffix}$`, 'i').test(normalizedStr);
295
336
  }
296
337
  buildPlaywrightCommand(selectedSpecs, isFull) {
297
338
  if (isFull || selectedSpecs.length === 0) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "playwright-smart-test",
3
- "version": "1.0.6",
3
+ "version": "1.0.8",
4
4
  "type": "module",
5
5
  "description": "AI-Powered Smart Regression Test Selection Agent for Playwright",
6
6
  "main": "dist/index.js",
@@ -69,4 +69,4 @@
69
69
  "overrides": {
70
70
  "minimatch": "^11.0.3"
71
71
  }
72
- }
72
+ }