guard-scanner 3.3.0 → 3.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/src/scanner.js ADDED
@@ -0,0 +1,1024 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * guard-scanner v2.1.0 — Agent Skill Security Scanner šŸ›”ļø
4
+ *
5
+ * @security-manifest
6
+ * env-read: []
7
+ * env-write: []
8
+ * network: none
9
+ * fs-read: [scan target directory (user-specified)]
10
+ * fs-write: [JSON/SARIF/HTML reports to scan directory]
11
+ * exec: none
12
+ * purpose: Static analysis of agent skill files for threat patterns
13
+ *
14
+ * Based on GuavaGuard v9.0.0 (OSS extraction)
15
+ * 20 threat categories • Snyk ToxicSkills + OWASP MCP Top 10
16
+ * Zero dependencies • CLI + JSON + SARIF + HTML output
17
+ * Plugin API for custom detection rules
18
+ *
19
+ * Born from a real 3-day agent identity hijack (2026-02-12)
20
+ *
21
+ * License: MIT
22
+ */
23
+
24
+ const fs = require('fs');
25
+ const path = require('path');
26
+ const os = require('os');
27
+ const crypto = require('crypto');
28
+
29
+ const { PATTERNS } = require('./patterns.js');
30
+ const { KNOWN_MALICIOUS } = require('./ioc-db.js');
31
+ const { generateHTML } = require('./html-template.js');
32
+
33
+ // ===== CONFIGURATION =====
34
+ const VERSION = '3.4.0';
35
+
36
+ const THRESHOLDS = {
37
+ normal: { suspicious: 30, malicious: 80 },
38
+ strict: { suspicious: 20, malicious: 60 },
39
+ };
40
+
41
+ // File classification
42
+ const CODE_EXTENSIONS = new Set(['.js', '.ts', '.mjs', '.cjs', '.py', '.sh', '.bash', '.ps1', '.rb', '.go', '.rs', '.php', '.pl']);
43
+ const DOC_EXTENSIONS = new Set(['.md', '.txt', '.rst', '.adoc']);
44
+ const DATA_EXTENSIONS = new Set(['.json', '.yaml', '.yml', '.toml', '.xml', '.csv']);
45
+ const BINARY_EXTENSIONS = new Set(['.png', '.jpg', '.jpeg', '.gif', '.ico', '.woff', '.woff2', '.ttf', '.eot', '.wasm', '.wav', '.mp3', '.mp4', '.webm', '.ogg', '.pdf', '.zip', '.tar', '.gz', '.bz2', '.7z', '.exe', '.dll', '.so', '.dylib']);
46
+ const GENERATED_REPORT_FILES = new Set(['guard-scanner-report.json', 'guard-scanner-report.html', 'guard-scanner.sarif']);
47
+
48
+ // Severity weights for risk scoring
49
+ const SEVERITY_WEIGHTS = { CRITICAL: 40, HIGH: 15, MEDIUM: 5, LOW: 2 };
50
+
51
+ class GuardScanner {
52
+ constructor(options = {}) {
53
+ this.verbose = options.verbose || false;
54
+ this.selfExclude = options.selfExclude || false;
55
+ this.strict = options.strict || false;
56
+ this.summaryOnly = options.summaryOnly || false;
57
+ this.quiet = options.quiet || false;
58
+ this.checkDeps = options.checkDeps || false;
59
+ this.scannerDir = path.resolve(__dirname);
60
+ this.thresholds = this.strict ? THRESHOLDS.strict : THRESHOLDS.normal;
61
+ this.findings = [];
62
+ this.stats = { scanned: 0, clean: 0, low: 0, suspicious: 0, malicious: 0 };
63
+ this.ignoredSkills = new Set();
64
+ this.ignoredPatterns = new Set();
65
+ this.customRules = [];
66
+
67
+ // Plugin API: load plugins
68
+ if (options.plugins && Array.isArray(options.plugins)) {
69
+ for (const plugin of options.plugins) {
70
+ this.loadPlugin(plugin);
71
+ }
72
+ }
73
+
74
+ // Custom rules file (legacy compat)
75
+ if (options.rulesFile) {
76
+ this.loadCustomRules(options.rulesFile);
77
+ }
78
+ }
79
+
80
+ // Plugin API: load a plugin module
81
+ loadPlugin(pluginPath) {
82
+ try {
83
+ const plugin = require(path.resolve(pluginPath));
84
+ if (plugin.patterns && Array.isArray(plugin.patterns)) {
85
+ for (const p of plugin.patterns) {
86
+ if (p.id && p.regex && p.severity && p.cat && p.desc) {
87
+ this.customRules.push(p);
88
+ }
89
+ }
90
+ if (!this.summaryOnly) {
91
+ console.log(`šŸ”Œ Plugin loaded: ${plugin.name || pluginPath} (${plugin.patterns.length} rule(s))`);
92
+ }
93
+ }
94
+ } catch (e) {
95
+ console.error(`āš ļø Failed to load plugin ${pluginPath}: ${e.message}`);
96
+ }
97
+ }
98
+
99
+ // Custom rules from JSON file
100
+ loadCustomRules(rulesFile) {
101
+ try {
102
+ const content = fs.readFileSync(rulesFile, 'utf-8');
103
+ const rules = JSON.parse(content);
104
+ if (!Array.isArray(rules)) {
105
+ console.error(`āš ļø Custom rules file must be a JSON array`);
106
+ return;
107
+ }
108
+ for (const rule of rules) {
109
+ if (!rule.id || !rule.pattern || !rule.severity || !rule.cat || !rule.desc) {
110
+ console.error(`āš ļø Skipping invalid rule: ${JSON.stringify(rule).substring(0, 80)}`);
111
+ continue;
112
+ }
113
+ try {
114
+ const flags = rule.flags || 'gi';
115
+ this.customRules.push({
116
+ id: rule.id,
117
+ cat: rule.cat,
118
+ regex: new RegExp(rule.pattern, flags),
119
+ severity: rule.severity,
120
+ desc: rule.desc,
121
+ codeOnly: rule.codeOnly || false,
122
+ docOnly: rule.docOnly || false,
123
+ all: !rule.codeOnly && !rule.docOnly
124
+ });
125
+ } catch (e) {
126
+ console.error(`āš ļø Invalid regex in rule ${rule.id}: ${e.message}`);
127
+ }
128
+ }
129
+ if (!this.summaryOnly && this.customRules.length > 0) {
130
+ console.log(`šŸ“ Loaded ${this.customRules.length} custom rule(s) from ${rulesFile}`);
131
+ }
132
+ } catch (e) {
133
+ console.error(`āš ļø Failed to load custom rules: ${e.message}`);
134
+ }
135
+ }
136
+
137
+ // Load .guava-guard-ignore / .guard-scanner-ignore from scan directory
138
+ loadIgnoreFile(scanDir) {
139
+ const ignorePaths = [
140
+ path.join(scanDir, '.guard-scanner-ignore'),
141
+ path.join(scanDir, '.guava-guard-ignore'),
142
+ ];
143
+ for (const ignorePath of ignorePaths) {
144
+ if (!fs.existsSync(ignorePath)) continue;
145
+ const lines = fs.readFileSync(ignorePath, 'utf-8').split('\n');
146
+ for (const line of lines) {
147
+ const trimmed = line.trim();
148
+ if (!trimmed || trimmed.startsWith('#')) continue;
149
+ if (trimmed.startsWith('pattern:')) {
150
+ this.ignoredPatterns.add(trimmed.replace('pattern:', '').trim());
151
+ } else {
152
+ this.ignoredSkills.add(trimmed);
153
+ }
154
+ }
155
+ if (this.verbose && (this.ignoredSkills.size || this.ignoredPatterns.size)) {
156
+ console.log(`šŸ“‹ Loaded ignore file: ${this.ignoredSkills.size} skills, ${this.ignoredPatterns.size} patterns`);
157
+ }
158
+ break; // use first found
159
+ }
160
+ }
161
+
162
+ scanDirectory(dir) {
163
+ if (!fs.existsSync(dir)) {
164
+ console.error(`āŒ Directory not found: ${dir}`);
165
+ process.exit(2);
166
+ }
167
+
168
+ this.loadIgnoreFile(dir);
169
+
170
+ const skills = fs.readdirSync(dir).filter(f => {
171
+ const p = path.join(dir, f);
172
+ return fs.statSync(p).isDirectory();
173
+ });
174
+
175
+ if (!this.quiet) {
176
+ console.log(`\nšŸ›”ļø guard-scanner v${VERSION}`);
177
+ console.log(`${'═'.repeat(54)}`);
178
+ console.log(`šŸ“‚ Scanning: ${dir}`);
179
+ console.log(`šŸ“¦ Skills found: ${skills.length}`);
180
+ if (this.strict) console.log(`⚔ Strict mode enabled`);
181
+ console.log();
182
+ }
183
+
184
+ for (const skill of skills) {
185
+ const skillPath = path.join(dir, skill);
186
+
187
+ // Self-exclusion
188
+ if (this.selfExclude && path.resolve(skillPath) === this.scannerDir) {
189
+ if (!this.summaryOnly && !this.quiet) console.log(`ā­ļø ${skill} — SELF (excluded)`);
190
+ continue;
191
+ }
192
+
193
+ // Ignore list
194
+ if (this.ignoredSkills.has(skill)) {
195
+ if (!this.summaryOnly && !this.quiet) console.log(`ā­ļø ${skill} — IGNORED`);
196
+ continue;
197
+ }
198
+
199
+ this.scanSkill(skillPath, skill);
200
+ }
201
+
202
+ if (!this.quiet) this.printSummary();
203
+ return this.findings;
204
+ }
205
+
206
+ scanSkill(skillPath, skillName) {
207
+ this.stats.scanned++;
208
+ const skillFindings = [];
209
+
210
+ // Check 1: Known malicious skill name
211
+ if (KNOWN_MALICIOUS.typosquats.includes(skillName.toLowerCase())) {
212
+ skillFindings.push({
213
+ severity: 'CRITICAL', id: 'KNOWN_TYPOSQUAT', cat: 'malicious-code',
214
+ desc: `Known malicious/typosquat skill name`,
215
+ file: 'SKILL NAME', line: 0
216
+ });
217
+ }
218
+
219
+ // Check 2: Scan all files
220
+ const files = this.getFiles(skillPath);
221
+ for (const file of files) {
222
+ const ext = path.extname(file).toLowerCase();
223
+ const relFile = path.relative(skillPath, file);
224
+
225
+ if (relFile.includes('node_modules/') || relFile.includes('node_modules\\')) continue;
226
+ if (relFile.startsWith('.git/') || relFile.startsWith('.git\\')) continue;
227
+ if (BINARY_EXTENSIONS.has(ext)) continue;
228
+
229
+ let content;
230
+ try { content = fs.readFileSync(file, 'utf-8'); } catch { continue; }
231
+ if (content.length > 500000) continue;
232
+
233
+ const fileType = this.classifyFile(ext, relFile);
234
+
235
+ // IoC checks
236
+ this.checkIoCs(content, relFile, skillFindings);
237
+
238
+ // Pattern checks (context-aware)
239
+ this.checkPatterns(content, relFile, fileType, skillFindings);
240
+
241
+ // Custom rules / plugins
242
+ if (this.customRules.length > 0) {
243
+ this.checkPatterns(content, relFile, fileType, skillFindings, this.customRules);
244
+ }
245
+
246
+ // Hardcoded secret detection
247
+ const baseName = path.basename(relFile).toLowerCase();
248
+ const skipSecretCheck = baseName.endsWith('-lock.json') || baseName === 'package-lock.json' ||
249
+ baseName === 'yarn.lock' || baseName === 'pnpm-lock.yaml' ||
250
+ baseName === '_meta.json' || baseName === '.package-lock.json';
251
+ if (fileType === 'code' && !skipSecretCheck) {
252
+ this.checkHardcodedSecrets(content, relFile, skillFindings);
253
+ }
254
+
255
+ // Lightweight JS data flow analysis
256
+ if ((ext === '.js' || ext === '.mjs' || ext === '.cjs' || ext === '.ts') && content.length < 200000) {
257
+ this.checkJSDataFlow(content, relFile, skillFindings);
258
+ }
259
+ }
260
+
261
+ // Check 3: Structural checks
262
+ this.checkStructure(skillPath, skillName, skillFindings);
263
+
264
+ // Check 4: Dependency chain scanning
265
+ if (this.checkDeps) {
266
+ this.checkDependencies(skillPath, skillName, skillFindings);
267
+ }
268
+
269
+ // Check 5: Hidden files detection
270
+ this.checkHiddenFiles(skillPath, skillName, skillFindings);
271
+
272
+ // Check 6: Cross-file analysis
273
+ this.checkCrossFile(skillPath, skillName, skillFindings);
274
+
275
+ // Check 7: Skill manifest validation (v1.1)
276
+ this.checkSkillManifest(skillPath, skillName, skillFindings);
277
+
278
+ // Check 8: Code complexity metrics (v1.1)
279
+ this.checkComplexity(skillPath, skillName, skillFindings);
280
+
281
+ // Check 9: Config impact analysis (v1.1)
282
+ this.checkConfigImpact(skillPath, skillName, skillFindings);
283
+
284
+ // Filter ignored patterns
285
+ const filteredFindings = skillFindings.filter(f => !this.ignoredPatterns.has(f.id));
286
+
287
+ // Calculate risk
288
+ const risk = this.calculateRisk(filteredFindings);
289
+ const verdict = this.getVerdict(risk);
290
+
291
+ this.stats[verdict.stat]++;
292
+
293
+ if (!this.summaryOnly && !this.quiet) {
294
+ console.log(`${verdict.icon} ${skillName} — ${verdict.label} (risk: ${risk})`);
295
+
296
+ if (this.verbose && filteredFindings.length > 0) {
297
+ const byCat = {};
298
+ for (const f of filteredFindings) {
299
+ (byCat[f.cat] = byCat[f.cat] || []).push(f);
300
+ }
301
+ for (const [cat, findings] of Object.entries(byCat)) {
302
+ console.log(` šŸ“ ${cat}`);
303
+ for (const f of findings) {
304
+ const icon = f.severity === 'CRITICAL' ? 'šŸ’€' : f.severity === 'HIGH' ? 'šŸ”“' : f.severity === 'MEDIUM' ? '🟔' : '⚪';
305
+ const loc = f.line ? `${f.file}:${f.line}` : f.file;
306
+ console.log(` ${icon} [${f.severity}] ${f.desc} — ${loc}`);
307
+ if (f.sample) console.log(` └─ "${f.sample}"`);
308
+ }
309
+ }
310
+ }
311
+ }
312
+
313
+ if (filteredFindings.length > 0) {
314
+ this.findings.push({ skill: skillName, risk, verdict: verdict.label, findings: filteredFindings });
315
+ }
316
+ }
317
+
318
+ classifyFile(ext, relFile) {
319
+ if (CODE_EXTENSIONS.has(ext)) return 'code';
320
+ if (DOC_EXTENSIONS.has(ext)) return 'doc';
321
+ if (DATA_EXTENSIONS.has(ext)) return 'data';
322
+ const base = path.basename(relFile).toLowerCase();
323
+ if (base === 'skill.md' || base === 'readme.md') return 'skill-doc';
324
+ return 'other';
325
+ }
326
+
327
+ checkIoCs(content, relFile, findings) {
328
+ const contentLower = content.toLowerCase();
329
+
330
+ for (const ip of KNOWN_MALICIOUS.ips) {
331
+ if (content.includes(ip)) {
332
+ findings.push({ severity: 'CRITICAL', id: 'IOC_IP', cat: 'malicious-code', desc: `Known malicious IP: ${ip}`, file: relFile });
333
+ }
334
+ }
335
+
336
+ for (const url of KNOWN_MALICIOUS.urls) {
337
+ if (contentLower.includes(url.toLowerCase())) {
338
+ findings.push({ severity: 'CRITICAL', id: 'IOC_URL', cat: 'malicious-code', desc: `Known malicious URL: ${url}`, file: relFile });
339
+ }
340
+ }
341
+
342
+ for (const domain of KNOWN_MALICIOUS.domains) {
343
+ const domainRegex = new RegExp(`(?:https?://|[\\s'"\`(]|^)${domain.replace(/\./g, '\\.')}`, 'gi');
344
+ if (domainRegex.test(content)) {
345
+ findings.push({ severity: 'HIGH', id: 'IOC_DOMAIN', cat: 'exfiltration', desc: `Suspicious domain: ${domain}`, file: relFile });
346
+ }
347
+ }
348
+
349
+ for (const fname of KNOWN_MALICIOUS.filenames) {
350
+ if (contentLower.includes(fname.toLowerCase())) {
351
+ findings.push({ severity: 'CRITICAL', id: 'IOC_FILE', cat: 'suspicious-download', desc: `Known malicious filename: ${fname}`, file: relFile });
352
+ }
353
+ }
354
+
355
+ for (const user of KNOWN_MALICIOUS.usernames) {
356
+ if (contentLower.includes(user.toLowerCase())) {
357
+ findings.push({ severity: 'HIGH', id: 'IOC_USER', cat: 'malicious-code', desc: `Known malicious username: ${user}`, file: relFile });
358
+ }
359
+ }
360
+ }
361
+
362
+ checkPatterns(content, relFile, fileType, findings, patterns = PATTERNS) {
363
+ for (const pattern of patterns) {
364
+ if (pattern.codeOnly && fileType !== 'code') continue;
365
+ if (pattern.docOnly && fileType !== 'doc' && fileType !== 'skill-doc') continue;
366
+ if (!pattern.all && !pattern.codeOnly && !pattern.docOnly) continue;
367
+
368
+ pattern.regex.lastIndex = 0;
369
+ const matches = content.match(pattern.regex);
370
+ if (!matches) continue;
371
+
372
+ pattern.regex.lastIndex = 0;
373
+ const idx = content.search(pattern.regex);
374
+ const lineNum = idx >= 0 ? content.substring(0, idx).split('\n').length : null;
375
+
376
+ let adjustedSeverity = pattern.severity;
377
+ if ((fileType === 'doc' || fileType === 'skill-doc') && pattern.all && !pattern.docOnly) {
378
+ if (adjustedSeverity === 'HIGH') adjustedSeverity = 'MEDIUM';
379
+ else if (adjustedSeverity === 'MEDIUM') adjustedSeverity = 'LOW';
380
+ }
381
+
382
+ findings.push({
383
+ severity: adjustedSeverity,
384
+ id: pattern.id,
385
+ cat: pattern.cat,
386
+ desc: pattern.desc,
387
+ file: relFile,
388
+ line: lineNum,
389
+ matchCount: matches.length,
390
+ sample: matches[0].substring(0, 80)
391
+ });
392
+ }
393
+ }
394
+
395
+ // Entropy-based secret detection
396
+ checkHardcodedSecrets(content, relFile, findings) {
397
+ const assignmentRegex = /(?:api[_-]?key|secret|token|password|credential|auth)\s*[:=]\s*['"]([a-zA-Z0-9_\-+/=]{16,})['"]|['"]([a-zA-Z0-9_\-+/=]{32,})['"]/gi;
398
+ let match;
399
+ while ((match = assignmentRegex.exec(content)) !== null) {
400
+ const value = match[1] || match[2];
401
+ if (!value) continue;
402
+
403
+ if (/^[A-Z_]+$/.test(value)) continue;
404
+ if (/^(true|false|null|undefined|none|default|example|test|placeholder|your[_-])/i.test(value)) continue;
405
+ if (/^x{4,}|\.{4,}|_{4,}|0{8,}$/i.test(value)) continue;
406
+ if (/^projects\/|^gs:\/\/|^https?:\/\//i.test(value)) continue;
407
+ if (/^[a-z]+-[a-z]+-[a-z0-9]+$/i.test(value)) continue;
408
+
409
+ const entropy = this.shannonEntropy(value);
410
+ if (entropy > 3.5 && value.length >= 20) {
411
+ const lineNum = content.substring(0, match.index).split('\n').length;
412
+ findings.push({
413
+ severity: 'HIGH', id: 'SECRET_ENTROPY', cat: 'secret-detection',
414
+ desc: `High-entropy string (possible leaked secret, entropy=${entropy.toFixed(1)})`,
415
+ file: relFile, line: lineNum,
416
+ sample: value.substring(0, 8) + '...' + value.substring(value.length - 4)
417
+ });
418
+ }
419
+ }
420
+ }
421
+
422
+ shannonEntropy(str) {
423
+ const freq = {};
424
+ for (const c of str) freq[c] = (freq[c] || 0) + 1;
425
+ const len = str.length;
426
+ let entropy = 0;
427
+ for (const count of Object.values(freq)) {
428
+ const p = count / len;
429
+ if (p > 0) entropy -= p * Math.log2(p);
430
+ }
431
+ return entropy;
432
+ }
433
+
434
+ checkStructure(skillPath, skillName, findings) {
435
+ const skillMd = path.join(skillPath, 'SKILL.md');
436
+ if (!fs.existsSync(skillMd)) {
437
+ findings.push({ severity: 'LOW', id: 'STRUCT_NO_SKILLMD', cat: 'structural', desc: 'No SKILL.md found', file: skillName });
438
+ return;
439
+ }
440
+ const content = fs.readFileSync(skillMd, 'utf-8');
441
+ if (content.length < 50) {
442
+ findings.push({ severity: 'MEDIUM', id: 'STRUCT_TINY_SKILLMD', cat: 'structural', desc: 'Suspiciously short SKILL.md (< 50 chars)', file: 'SKILL.md' });
443
+ }
444
+ const scriptsDir = path.join(skillPath, 'scripts');
445
+ if (fs.existsSync(scriptsDir)) {
446
+ const scripts = fs.readdirSync(scriptsDir).filter(f => CODE_EXTENSIONS.has(path.extname(f).toLowerCase()));
447
+ if (scripts.length > 0 && !content.includes('scripts/')) {
448
+ findings.push({ severity: 'MEDIUM', id: 'STRUCT_UNDOCUMENTED_SCRIPTS', cat: 'structural', desc: `${scripts.length} script(s) in scripts/ not referenced in SKILL.md`, file: 'scripts/' });
449
+ }
450
+ }
451
+ }
452
+
453
+ checkDependencies(skillPath, skillName, findings) {
454
+ const pkgPath = path.join(skillPath, 'package.json');
455
+ if (!fs.existsSync(pkgPath)) return;
456
+
457
+ let pkg;
458
+ try { pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf-8')); } catch { return; }
459
+
460
+ const allDeps = { ...pkg.dependencies, ...pkg.devDependencies, ...pkg.optionalDependencies };
461
+
462
+ const RISKY_PACKAGES = new Set([
463
+ 'node-ipc', 'colors', 'faker', 'event-stream', 'ua-parser-js', 'coa', 'rc',
464
+ ]);
465
+
466
+ for (const [dep, version] of Object.entries(allDeps)) {
467
+ if (RISKY_PACKAGES.has(dep)) {
468
+ findings.push({ severity: 'HIGH', id: 'DEP_RISKY', cat: 'dependency-chain', desc: `Known risky dependency: ${dep}@${version}`, file: 'package.json' });
469
+ }
470
+ if (typeof version === 'string' && (version.startsWith('git+') || version.startsWith('http') || version.startsWith('github:') || version.includes('.tar.gz'))) {
471
+ findings.push({ severity: 'HIGH', id: 'DEP_REMOTE', cat: 'dependency-chain', desc: `Remote/git dependency: ${dep}@${version}`, file: 'package.json' });
472
+ }
473
+ if (version === '*' || version === 'latest') {
474
+ findings.push({ severity: 'MEDIUM', id: 'DEP_WILDCARD', cat: 'dependency-chain', desc: `Wildcard version: ${dep}@${version}`, file: 'package.json' });
475
+ }
476
+ }
477
+
478
+ const RISKY_SCRIPTS = ['preinstall', 'postinstall', 'preuninstall', 'postuninstall', 'prepare'];
479
+ if (pkg.scripts) {
480
+ for (const scriptName of RISKY_SCRIPTS) {
481
+ if (pkg.scripts[scriptName]) {
482
+ const cmd = pkg.scripts[scriptName];
483
+ findings.push({ severity: 'HIGH', id: 'DEP_LIFECYCLE', cat: 'dependency-chain', desc: `Lifecycle script "${scriptName}": ${cmd.substring(0, 80)}`, file: 'package.json' });
484
+ if (/curl|wget|node\s+-e|eval|exec|bash\s+-c/i.test(cmd)) {
485
+ findings.push({ severity: 'CRITICAL', id: 'DEP_LIFECYCLE_EXEC', cat: 'dependency-chain', desc: `Lifecycle script "${scriptName}" downloads/executes code`, file: 'package.json', sample: cmd.substring(0, 80) });
486
+ }
487
+ }
488
+ }
489
+ }
490
+ }
491
+
492
+ // ── v1.1: Skill Manifest Validation ──
493
+ // Checks SKILL.md frontmatter for dangerous tool declarations,
494
+ // overly broad file scope, and sensitive env requirements
495
+ checkSkillManifest(skillPath, skillName, findings) {
496
+ const skillMd = path.join(skillPath, 'SKILL.md');
497
+ if (!fs.existsSync(skillMd)) return;
498
+
499
+ let content;
500
+ try { content = fs.readFileSync(skillMd, 'utf-8'); } catch { return; }
501
+
502
+ // Parse YAML frontmatter (lightweight, no dependency)
503
+ const fmMatch = content.match(/^---\n([\s\S]*?)\n---/);
504
+ if (!fmMatch) return;
505
+ const fm = fmMatch[1];
506
+
507
+ // Check 1: Dangerous binary requirements
508
+ const DANGEROUS_BINS = new Set([
509
+ 'sudo', 'rm', 'rmdir', 'chmod', 'chown', 'kill', 'pkill',
510
+ 'curl', 'wget', 'nc', 'ncat', 'socat', 'ssh', 'scp',
511
+ 'dd', 'mkfs', 'fdisk', 'mount', 'umount',
512
+ 'iptables', 'ufw', 'firewall-cmd',
513
+ 'docker', 'kubectl', 'systemctl',
514
+ ]);
515
+ const binsMatch = fm.match(/bins:\s*\n((?:\s+-\s+[^\n]+\n?)*)/i);
516
+ if (binsMatch) {
517
+ const bins = binsMatch[1].match(/- ([^\n]+)/g) || [];
518
+ for (const binLine of bins) {
519
+ const bin = binLine.replace(/^-\s*/, '').trim().toLowerCase();
520
+ if (DANGEROUS_BINS.has(bin)) {
521
+ findings.push({
522
+ severity: 'HIGH', id: 'MANIFEST_DANGEROUS_BIN',
523
+ cat: 'sandbox-validation',
524
+ desc: `SKILL.md requires dangerous binary: ${bin}`,
525
+ file: 'SKILL.md'
526
+ });
527
+ }
528
+ }
529
+ }
530
+
531
+ // Check 2: Overly broad file scope
532
+ const filesMatch = fm.match(/files:\s*\[([^\]]+)\]/i) || fm.match(/files:\s*\n((?:\s+-\s+[^\n]+\n?)*)/i);
533
+ if (filesMatch) {
534
+ const filesStr = filesMatch[1];
535
+ if (/\*\*\/\*|\*\.\*|\"\*\"/i.test(filesStr)) {
536
+ findings.push({
537
+ severity: 'HIGH', id: 'MANIFEST_BROAD_FILES',
538
+ cat: 'sandbox-validation',
539
+ desc: 'SKILL.md declares overly broad file scope (e.g. **/*)',
540
+ file: 'SKILL.md'
541
+ });
542
+ }
543
+ }
544
+
545
+ // Check 3: Sensitive env requirements
546
+ const SENSITIVE_ENV_PATTERNS = /(?:SECRET|PASSWORD|CREDENTIAL|PRIVATE_KEY|AWS_SECRET|GITHUB_TOKEN)/i;
547
+ const envMatch = fm.match(/env:\s*\n((?:\s+-\s+[^\n]+\n?)*)/i);
548
+ if (envMatch) {
549
+ const envVars = envMatch[1].match(/- ([^\n]+)/g) || [];
550
+ for (const envLine of envVars) {
551
+ const envVar = envLine.replace(/^-\s*/, '').trim();
552
+ if (SENSITIVE_ENV_PATTERNS.test(envVar)) {
553
+ findings.push({
554
+ severity: 'HIGH', id: 'MANIFEST_SENSITIVE_ENV',
555
+ cat: 'sandbox-validation',
556
+ desc: `SKILL.md requires sensitive env var: ${envVar}`,
557
+ file: 'SKILL.md'
558
+ });
559
+ }
560
+ }
561
+ }
562
+
563
+ // Check 4: exec or network declared without justification
564
+ if (/exec:\s*(?:true|yes|enabled|'\*'|"\*")/i.test(fm)) {
565
+ findings.push({
566
+ severity: 'MEDIUM', id: 'MANIFEST_EXEC_DECLARED',
567
+ cat: 'sandbox-validation',
568
+ desc: 'SKILL.md declares exec capability',
569
+ file: 'SKILL.md'
570
+ });
571
+ }
572
+ if (/network:\s*(?:true|yes|enabled|'\*'|"\*"|all|any)/i.test(fm)) {
573
+ findings.push({
574
+ severity: 'MEDIUM', id: 'MANIFEST_NETWORK_DECLARED',
575
+ cat: 'sandbox-validation',
576
+ desc: 'SKILL.md declares unrestricted network access',
577
+ file: 'SKILL.md'
578
+ });
579
+ }
580
+ }
581
+
582
+ // ── v1.1: Code Complexity Metrics ──
583
+ // Detects excessive file length, deep nesting, and eval/exec density
584
+ checkComplexity(skillPath, skillName, findings) {
585
+ const files = this.getFiles(skillPath);
586
+ const MAX_LINES = 1000;
587
+ const MAX_NESTING = 5;
588
+ const MAX_EVAL_DENSITY = 0.02; // 2% of lines
589
+
590
+ for (const file of files) {
591
+ const ext = path.extname(file).toLowerCase();
592
+ if (!CODE_EXTENSIONS.has(ext)) continue;
593
+
594
+ const relFile = path.relative(skillPath, file);
595
+ if (relFile.includes('node_modules') || relFile.startsWith('.git')) continue;
596
+
597
+ let content;
598
+ try { content = fs.readFileSync(file, 'utf-8'); } catch { continue; }
599
+
600
+ const lines = content.split('\n');
601
+
602
+ // Check 1: Excessive file length
603
+ if (lines.length > MAX_LINES) {
604
+ findings.push({
605
+ severity: 'MEDIUM', id: 'COMPLEXITY_LONG_FILE',
606
+ cat: 'complexity',
607
+ desc: `File exceeds ${MAX_LINES} lines (${lines.length} lines)`,
608
+ file: relFile
609
+ });
610
+ }
611
+
612
+ // Check 2: Deep nesting (brace tracking)
613
+ let maxDepth = 0;
614
+ let currentDepth = 0;
615
+ let deepestLine = 0;
616
+ for (let i = 0; i < lines.length; i++) {
617
+ const line = lines[i];
618
+ // Count opening/closing braces outside strings (simplified)
619
+ for (const ch of line) {
620
+ if (ch === '{') currentDepth++;
621
+ if (ch === '}') currentDepth = Math.max(0, currentDepth - 1);
622
+ }
623
+ if (currentDepth > maxDepth) {
624
+ maxDepth = currentDepth;
625
+ deepestLine = i + 1;
626
+ }
627
+ }
628
+ if (maxDepth > MAX_NESTING) {
629
+ findings.push({
630
+ severity: 'MEDIUM', id: 'COMPLEXITY_DEEP_NESTING',
631
+ cat: 'complexity',
632
+ desc: `Deep nesting detected: ${maxDepth} levels (max recommended: ${MAX_NESTING})`,
633
+ file: relFile, line: deepestLine
634
+ });
635
+ }
636
+
637
+ // Check 3: eval/exec density
638
+ const evalPattern = /\b(?:eval|exec|execSync|spawn|Function)\s*\(/g;
639
+ const evalMatches = content.match(evalPattern) || [];
640
+ const density = lines.length > 0 ? evalMatches.length / lines.length : 0;
641
+ if (density > MAX_EVAL_DENSITY && evalMatches.length >= 3) {
642
+ findings.push({
643
+ severity: 'HIGH', id: 'COMPLEXITY_EVAL_DENSITY',
644
+ cat: 'complexity',
645
+ desc: `High eval/exec density: ${evalMatches.length} calls in ${lines.length} lines (${(density * 100).toFixed(1)}%)`,
646
+ file: relFile
647
+ });
648
+ }
649
+ }
650
+ }
651
+
652
+ // ── v1.1: Config Impact Analysis ──
653
+ // Detects modifications to openclaw.json and dangerous configuration changes
654
+ checkConfigImpact(skillPath, skillName, findings) {
655
+ const files = this.getFiles(skillPath);
656
+
657
+ for (const file of files) {
658
+ const ext = path.extname(file).toLowerCase();
659
+ if (!CODE_EXTENSIONS.has(ext) && ext !== '.json') continue;
660
+
661
+ const relFile = path.relative(skillPath, file);
662
+ if (relFile.includes('node_modules') || relFile.startsWith('.git')) continue;
663
+
664
+ let content;
665
+ try { content = fs.readFileSync(file, 'utf-8'); } catch { continue; }
666
+
667
+ // Check 1: openclaw.json reference + write operation in same file
668
+ // Handles both direct and variable-based patterns (e.g. writeFileSync(configPath))
669
+ const hasConfigRef = /openclaw\.json/i.test(content);
670
+ const hasWriteOp = /(?:writeFileSync|writeFile|fs\.write)\s*\(/i.test(content);
671
+ if (hasConfigRef && hasWriteOp) {
672
+ // Find the write line for location info
673
+ const clines = content.split('\n');
674
+ let writeLine = 0;
675
+ for (let i = 0; i < clines.length; i++) {
676
+ if (/(?:writeFileSync|writeFile|fs\.write)\s*\(/i.test(clines[i])) {
677
+ writeLine = i + 1;
678
+ break;
679
+ }
680
+ }
681
+ findings.push({
682
+ severity: 'CRITICAL', id: 'CFG_WRITE_DETECTED',
683
+ cat: 'config-impact',
684
+ desc: 'Code writes to openclaw.json',
685
+ file: relFile, line: writeLine,
686
+ sample: writeLine > 0 ? clines[writeLine - 1].trim().substring(0, 80) : ''
687
+ });
688
+ }
689
+
690
+ // Check 2: Dangerous config key modifications
691
+ const DANGEROUS_CONFIG_KEYS = [
692
+ { regex: /exec\.approvals?\s*[:=]\s*['"]?(off|false|disabled|none)/gi, id: 'CFG_EXEC_APPROVAL_OFF', desc: 'Disables exec approval requirement', severity: 'CRITICAL' },
693
+ { regex: /tools\.exec\.host\s*[:=]\s*['"]gateway['"]/gi, id: 'CFG_EXEC_HOST_GATEWAY', desc: 'Sets exec host to gateway (bypasses sandbox)', severity: 'CRITICAL' },
694
+ { regex: /hooks\s*\.\s*internal\s*\.\s*entries\s*[:=]/gi, id: 'CFG_HOOKS_INTERNAL', desc: 'Modifies internal hook entries', severity: 'HIGH' },
695
+ { regex: /network\.allowedDomains\s*[:=]\s*\[?\s*['"]\*['"]/gi, id: 'CFG_NET_WILDCARD', desc: 'Sets network allowedDomains to wildcard', severity: 'HIGH' },
696
+ ];
697
+
698
+ for (const check of DANGEROUS_CONFIG_KEYS) {
699
+ check.regex.lastIndex = 0;
700
+ if (check.regex.test(content)) {
701
+ findings.push({
702
+ severity: check.severity, id: check.id,
703
+ cat: 'config-impact',
704
+ desc: check.desc,
705
+ file: relFile
706
+ });
707
+ }
708
+ }
709
+ }
710
+ }
711
+
712
+ checkHiddenFiles(skillPath, skillName, findings) {
713
+ try {
714
+ const entries = fs.readdirSync(skillPath);
715
+ for (const entry of entries) {
716
+ if (entry.startsWith('.') && entry !== '.guard-scanner-ignore' && entry !== '.guava-guard-ignore' && entry !== '.gitignore' && entry !== '.git') {
717
+ const fullPath = path.join(skillPath, entry);
718
+ const stat = fs.statSync(fullPath);
719
+ if (stat.isFile()) {
720
+ const ext = path.extname(entry).toLowerCase();
721
+ if (CODE_EXTENSIONS.has(ext) || ext === '' || ext === '.sh') {
722
+ findings.push({ severity: 'MEDIUM', id: 'STRUCT_HIDDEN_EXEC', cat: 'structural', desc: `Hidden executable file: ${entry}`, file: entry });
723
+ }
724
+ } else if (stat.isDirectory() && entry !== '.git') {
725
+ findings.push({ severity: 'LOW', id: 'STRUCT_HIDDEN_DIR', cat: 'structural', desc: `Hidden directory: ${entry}/`, file: entry });
726
+ }
727
+ }
728
+ }
729
+ } catch { }
730
+ }
731
+
732
+ checkJSDataFlow(content, relFile, findings) {
733
+ const lines = content.split('\n');
734
+ const imports = new Map();
735
+ const sensitiveReads = [];
736
+ const networkCalls = [];
737
+ const execCalls = [];
738
+
739
+ for (let i = 0; i < lines.length; i++) {
740
+ const line = lines[i];
741
+ const lineNum = i + 1;
742
+
743
+ const reqMatch = line.match(/(?:const|let|var)\s+(?:{[^}]+}|\w+)\s*=\s*require\s*\(\s*['"]([^'"]+)['"]\s*\)/);
744
+ if (reqMatch) {
745
+ const varMatch = line.match(/(?:const|let|var)\s+({[^}]+}|\w+)/);
746
+ if (varMatch) imports.set(varMatch[1].trim(), reqMatch[1]);
747
+ }
748
+
749
+ if (/(?:readFileSync|readFile)\s*\([^)]*(?:\.env|\.ssh|id_rsa|\.clawdbot|\.openclaw(?!\/workspace))/i.test(line)) {
750
+ sensitiveReads.push({ line: lineNum, text: line.trim() });
751
+ }
752
+ if (/process\.env\.[A-Z_]*(?:KEY|SECRET|TOKEN|PASSWORD|CREDENTIAL)/i.test(line)) {
753
+ sensitiveReads.push({ line: lineNum, text: line.trim() });
754
+ }
755
+
756
+ if (/(?:fetch|axios|request|http\.request|https\.request|got)\s*\(/i.test(line) ||
757
+ /\.post\s*\(|\.put\s*\(|\.patch\s*\(/i.test(line)) {
758
+ networkCalls.push({ line: lineNum, text: line.trim() });
759
+ }
760
+
761
+ if (/(?:exec|execSync|spawn|spawnSync|execFile)\s*\(/i.test(line)) {
762
+ execCalls.push({ line: lineNum, text: line.trim() });
763
+ }
764
+ }
765
+
766
+ if (sensitiveReads.length > 0 && networkCalls.length > 0) {
767
+ findings.push({
768
+ severity: 'CRITICAL', id: 'AST_CRED_TO_NET', cat: 'data-flow',
769
+ desc: `Data flow: secret read (L${sensitiveReads[0].line}) → network call (L${networkCalls[0].line})`,
770
+ file: relFile, line: sensitiveReads[0].line,
771
+ sample: sensitiveReads[0].text.substring(0, 60)
772
+ });
773
+ }
774
+
775
+ if (sensitiveReads.length > 0 && execCalls.length > 0) {
776
+ findings.push({
777
+ severity: 'HIGH', id: 'AST_CRED_TO_EXEC', cat: 'data-flow',
778
+ desc: `Data flow: secret read (L${sensitiveReads[0].line}) → command exec (L${execCalls[0].line})`,
779
+ file: relFile, line: sensitiveReads[0].line,
780
+ sample: sensitiveReads[0].text.substring(0, 60)
781
+ });
782
+ }
783
+
784
+ const importedModules = new Set([...imports.values()]);
785
+ if (importedModules.has('child_process') && (importedModules.has('https') || importedModules.has('http') || importedModules.has('node-fetch'))) {
786
+ findings.push({ severity: 'HIGH', id: 'AST_SUSPICIOUS_IMPORTS', cat: 'data-flow', desc: 'Suspicious import combination: child_process + network module', file: relFile });
787
+ }
788
+ if (importedModules.has('fs') && importedModules.has('child_process') && (importedModules.has('https') || importedModules.has('http'))) {
789
+ findings.push({ severity: 'CRITICAL', id: 'AST_EXFIL_TRIFECTA', cat: 'data-flow', desc: 'Exfiltration trifecta: fs + child_process + network', file: relFile });
790
+ }
791
+
792
+ for (let i = 0; i < lines.length; i++) {
793
+ const line = lines[i];
794
+ if (/`[^`]*\$\{.*(?:env|key|token|secret|password).*\}[^`]*`\s*(?:\)|,)/i.test(line) &&
795
+ /(?:fetch|request|axios|http|url)/i.test(line)) {
796
+ findings.push({ severity: 'CRITICAL', id: 'AST_SECRET_IN_URL', cat: 'data-flow', desc: 'Secret interpolated into URL/request', file: relFile, line: i + 1, sample: line.trim().substring(0, 80) });
797
+ }
798
+ }
799
+ }
800
+
801
+ checkCrossFile(skillPath, skillName, findings) {
802
+ const files = this.getFiles(skillPath);
803
+ const allContent = {};
804
+
805
+ for (const file of files) {
806
+ const ext = path.extname(file).toLowerCase();
807
+ if (BINARY_EXTENSIONS.has(ext)) continue;
808
+ const relFile = path.relative(skillPath, file);
809
+ if (relFile.includes('node_modules') || relFile.startsWith('.git')) continue;
810
+ try {
811
+ const content = fs.readFileSync(file, 'utf-8');
812
+ if (content.length < 500000) allContent[relFile] = content;
813
+ } catch { }
814
+ }
815
+
816
+ const skillMd = allContent['SKILL.md'] || '';
817
+ const codeFileRefs = skillMd.match(/(?:scripts?\/|\.\/)[a-zA-Z0-9_\-./]+\.(js|py|sh|ts)/gi) || [];
818
+ for (const ref of codeFileRefs) {
819
+ const cleanRef = ref.replace(/^\.\//, '');
820
+ if (!allContent[cleanRef] && !files.some(f => path.relative(skillPath, f) === cleanRef)) {
821
+ findings.push({ severity: 'MEDIUM', id: 'XFILE_PHANTOM_REF', cat: 'structural', desc: `SKILL.md references non-existent file: ${cleanRef}`, file: 'SKILL.md' });
822
+ }
823
+ }
824
+
825
+ const base64Fragments = [];
826
+ for (const [file, content] of Object.entries(allContent)) {
827
+ const matches = content.match(/[A-Za-z0-9+/]{20,}={0,2}/g) || [];
828
+ for (const m of matches) {
829
+ if (m.length > 40) base64Fragments.push({ file, fragment: m.substring(0, 30) });
830
+ }
831
+ }
832
+ if (base64Fragments.length > 3 && new Set(base64Fragments.map(f => f.file)).size > 1) {
833
+ findings.push({ severity: 'HIGH', id: 'XFILE_FRAGMENT_B64', cat: 'obfuscation', desc: `Base64 fragments across ${new Set(base64Fragments.map(f => f.file)).size} files`, file: skillName });
834
+ }
835
+
836
+ if (/(?:read|load|source|import)\s+(?:the\s+)?(?:script|file|code)\s+(?:from|at|in)\s+(?:scripts?\/)/gi.test(skillMd)) {
837
+ const hasExec = Object.values(allContent).some(c => /(?:eval|exec|spawn)\s*\(/i.test(c));
838
+ if (hasExec) {
839
+ findings.push({ severity: 'MEDIUM', id: 'XFILE_LOAD_EXEC', cat: 'data-flow', desc: 'SKILL.md references script files that contain exec/eval', file: 'SKILL.md' });
840
+ }
841
+ }
842
+ }
843
+
844
+ calculateRisk(findings) {
845
+ if (findings.length === 0) return 0;
846
+
847
+ let score = 0;
848
+ for (const f of findings) {
849
+ score += SEVERITY_WEIGHTS[f.severity] || 0;
850
+ }
851
+
852
+ const ids = new Set(findings.map(f => f.id));
853
+ const cats = new Set(findings.map(f => f.cat));
854
+
855
+ if (cats.has('credential-handling') && cats.has('exfiltration')) score = Math.round(score * 2);
856
+ if (cats.has('credential-handling') && findings.some(f => f.id === 'MAL_CHILD' || f.id === 'MAL_EXEC')) score = Math.round(score * 1.5);
857
+ if (cats.has('obfuscation') && (cats.has('malicious-code') || cats.has('credential-handling'))) score = Math.round(score * 2);
858
+ if (ids.has('DEP_LIFECYCLE_EXEC')) score = Math.round(score * 2);
859
+ if (ids.has('PI_BIDI') && findings.length > 1) score = Math.round(score * 1.5);
860
+ if (cats.has('leaky-skills') && (cats.has('exfiltration') || cats.has('malicious-code'))) score = Math.round(score * 2);
861
+ if (cats.has('memory-poisoning')) score = Math.round(score * 1.5);
862
+ if (cats.has('prompt-worm')) score = Math.round(score * 2);
863
+ if (cats.has('cve-patterns')) score = Math.max(score, 70);
864
+ if (cats.has('persistence') && (cats.has('malicious-code') || cats.has('credential-handling') || cats.has('memory-poisoning'))) score = Math.round(score * 1.5);
865
+ if (cats.has('identity-hijack')) score = Math.round(score * 2);
866
+ if (cats.has('identity-hijack') && (cats.has('persistence') || cats.has('memory-poisoning'))) score = Math.max(score, 90);
867
+ if (ids.has('IOC_IP') || ids.has('IOC_URL') || ids.has('KNOWN_TYPOSQUAT')) score = 100;
868
+
869
+ // v1.1 categories
870
+ if (cats.has('config-impact')) score = Math.round(score * 2);
871
+ if (cats.has('config-impact') && cats.has('sandbox-validation')) score = Math.max(score, 70);
872
+ if (cats.has('complexity') && (cats.has('malicious-code') || cats.has('obfuscation'))) score = Math.round(score * 1.5);
873
+
874
+ // v2.1 PII exposure amplifiers
875
+ if (cats.has('pii-exposure') && cats.has('exfiltration')) score = Math.round(score * 3);
876
+ if (cats.has('pii-exposure') && (ids.has('SHADOW_AI_OPENAI') || ids.has('SHADOW_AI_ANTHROPIC') || ids.has('SHADOW_AI_GENERIC'))) score = Math.round(score * 2.5);
877
+ if (cats.has('pii-exposure') && cats.has('credential-handling')) score = Math.round(score * 2);
878
+
879
+ return Math.min(100, score);
880
+ }
881
+
882
+ getVerdict(risk) {
883
+ if (risk >= this.thresholds.malicious) return { icon: 'šŸ”“', label: 'MALICIOUS', stat: 'malicious' };
884
+ if (risk >= this.thresholds.suspicious) return { icon: '🟔', label: 'SUSPICIOUS', stat: 'suspicious' };
885
+ if (risk > 0) return { icon: '🟢', label: 'LOW RISK', stat: 'low' };
886
+ return { icon: '🟢', label: 'CLEAN', stat: 'clean' };
887
+ }
888
+
889
+ getFiles(dir) {
890
+ const results = [];
891
+ try {
892
+ const entries = fs.readdirSync(dir, { withFileTypes: true });
893
+ for (const entry of entries) {
894
+ const fullPath = path.join(dir, entry.name);
895
+ if (entry.isDirectory()) {
896
+ if (entry.name === '.git' || entry.name === 'node_modules') continue;
897
+ results.push(...this.getFiles(fullPath));
898
+ } else {
899
+ const baseName = entry.name.toLowerCase();
900
+ if (GENERATED_REPORT_FILES.has(baseName)) continue;
901
+ results.push(fullPath);
902
+ }
903
+ }
904
+ } catch { }
905
+ return results;
906
+ }
907
+
908
+ printSummary() {
909
+ const total = this.stats.scanned;
910
+ const safe = this.stats.clean + this.stats.low;
911
+ console.log(`\n${'═'.repeat(54)}`);
912
+ console.log(`šŸ“Š guard-scanner v${VERSION} Scan Summary`);
913
+ console.log(`${'─'.repeat(54)}`);
914
+ console.log(` Scanned: ${total}`);
915
+ console.log(` 🟢 Clean: ${this.stats.clean}`);
916
+ console.log(` 🟢 Low Risk: ${this.stats.low}`);
917
+ console.log(` 🟔 Suspicious: ${this.stats.suspicious}`);
918
+ console.log(` šŸ”“ Malicious: ${this.stats.malicious}`);
919
+ console.log(` Safety Rate: ${total ? Math.round(safe / total * 100) : 0}%`);
920
+ console.log(`${'═'.repeat(54)}`);
921
+
922
+ if (this.stats.malicious > 0) {
923
+ console.log(`\nāš ļø CRITICAL: ${this.stats.malicious} malicious skill(s) detected!`);
924
+ console.log(` Review findings with --verbose and remove if confirmed.`);
925
+ } else if (this.stats.suspicious > 0) {
926
+ console.log(`\n⚔ ${this.stats.suspicious} suspicious skill(s) found — review recommended.`);
927
+ } else {
928
+ console.log(`\nāœ… All clear! No threats detected.`);
929
+ }
930
+ }
931
+
932
+ toJSON() {
933
+ const recommendations = [];
934
+ for (const skillResult of this.findings) {
935
+ const skillRecs = [];
936
+ const cats = new Set(skillResult.findings.map(f => f.cat));
937
+
938
+ if (cats.has('prompt-injection')) skillRecs.push('šŸ›‘ Contains prompt injection patterns.');
939
+ if (cats.has('malicious-code')) skillRecs.push('šŸ›‘ Contains potentially malicious code.');
940
+ if (cats.has('credential-handling') && cats.has('exfiltration')) skillRecs.push('šŸ’€ CRITICAL: Credential access + exfiltration. DO NOT INSTALL.');
941
+ if (cats.has('dependency-chain')) skillRecs.push('šŸ“¦ Suspicious dependency chain.');
942
+ if (cats.has('obfuscation')) skillRecs.push('šŸ” Code obfuscation detected.');
943
+ if (cats.has('secret-detection')) skillRecs.push('šŸ”‘ Possible hardcoded secrets.');
944
+ if (cats.has('leaky-skills')) skillRecs.push('šŸ’§ LEAKY SKILL: Secrets pass through LLM context.');
945
+ if (cats.has('memory-poisoning')) skillRecs.push('🧠 MEMORY POISONING: Agent memory modification attempt.');
946
+ if (cats.has('prompt-worm')) skillRecs.push('🪱 PROMPT WORM: Self-replicating instructions.');
947
+ if (cats.has('data-flow')) skillRecs.push('šŸ”€ Suspicious data flow patterns.');
948
+ if (cats.has('persistence')) skillRecs.push('ā° PERSISTENCE: Creates scheduled tasks.');
949
+ if (cats.has('cve-patterns')) skillRecs.push('🚨 CVE PATTERN: Matches known exploits.');
950
+ if (cats.has('identity-hijack')) skillRecs.push('šŸ”’ IDENTITY HIJACK: Agent soul file tampering. DO NOT INSTALL.');
951
+ if (cats.has('sandbox-validation')) skillRecs.push('šŸ”’ SANDBOX: Skill requests dangerous capabilities.');
952
+ if (cats.has('complexity')) skillRecs.push('🧩 COMPLEXITY: Excessive code complexity may hide malicious behavior.');
953
+ if (cats.has('config-impact')) skillRecs.push('āš™ļø CONFIG IMPACT: Modifies OpenClaw configuration. DO NOT INSTALL.');
954
+ if (cats.has('pii-exposure')) skillRecs.push('šŸ†” PII EXPOSURE: Handles personally identifiable information. Review data handling.');
955
+
956
+ if (skillRecs.length > 0) recommendations.push({ skill: skillResult.skill, actions: skillRecs });
957
+ }
958
+
959
+ return {
960
+ timestamp: new Date().toISOString(),
961
+ scanner: `guard-scanner v${VERSION}`,
962
+ mode: this.strict ? 'strict' : 'normal',
963
+ stats: this.stats,
964
+ thresholds: this.thresholds,
965
+ findings: this.findings,
966
+ recommendations,
967
+ iocVersion: '2026-02-12',
968
+ };
969
+ }
970
+
971
+ toSARIF(scanDir) {
972
+ const rules = [];
973
+ const ruleIndex = {};
974
+ const results = [];
975
+
976
+ for (const skillResult of this.findings) {
977
+ for (const f of skillResult.findings) {
978
+ if (!ruleIndex[f.id]) {
979
+ ruleIndex[f.id] = rules.length;
980
+ rules.push({
981
+ id: f.id, name: f.id,
982
+ shortDescription: { text: f.desc },
983
+ defaultConfiguration: { level: f.severity === 'CRITICAL' ? 'error' : f.severity === 'HIGH' ? 'error' : f.severity === 'MEDIUM' ? 'warning' : 'note' },
984
+ properties: { tags: ['security', f.cat], 'security-severity': f.severity === 'CRITICAL' ? '9.0' : f.severity === 'HIGH' ? '7.0' : f.severity === 'MEDIUM' ? '4.0' : '1.0' }
985
+ });
986
+ }
987
+ const normalizedFile = String(f.file || '')
988
+ .replaceAll('\\', '/')
989
+ .replace(/^\/+/, '');
990
+ const artifactUri = `${skillResult.skill}/${normalizedFile}`;
991
+ const fingerprintSeed = `${f.id}|${artifactUri}|${f.line || 0}|${(f.sample || '').slice(0, 200)}`;
992
+ const lineHash = crypto.createHash('sha256').update(fingerprintSeed).digest('hex').slice(0, 24);
993
+
994
+ results.push({
995
+ ruleId: f.id, ruleIndex: ruleIndex[f.id],
996
+ level: f.severity === 'CRITICAL' ? 'error' : f.severity === 'HIGH' ? 'error' : f.severity === 'MEDIUM' ? 'warning' : 'note',
997
+ message: { text: `[${skillResult.skill}] ${f.desc}${f.sample ? ` — "${f.sample}"` : ''}` },
998
+ partialFingerprints: {
999
+ primaryLocationLineHash: lineHash
1000
+ },
1001
+ locations: [{ physicalLocation: { artifactLocation: { uri: artifactUri, uriBaseId: '%SRCROOT%' }, region: f.line ? { startLine: f.line } : undefined } }]
1002
+ });
1003
+ }
1004
+ }
1005
+
1006
+ return {
1007
+ version: '2.1.0',
1008
+ $schema: 'https://json.schemastore.org/sarif-2.1.0.json',
1009
+ runs: [{
1010
+ tool: { driver: { name: 'guard-scanner', version: VERSION, informationUri: 'https://github.com/koatora20/guard-scanner', rules } },
1011
+ results,
1012
+ invocations: [{ executionSuccessful: true, endTimeUtc: new Date().toISOString() }]
1013
+ }]
1014
+ };
1015
+ }
1016
+
1017
+ toHTML() {
1018
+ return generateHTML(VERSION, this.stats, this.findings);
1019
+ }
1020
+ }
1021
+
1022
+ const { scanToolCall, RUNTIME_CHECKS, getCheckStats, LAYER_NAMES } = require('./runtime-guard.js');
1023
+
1024
+ module.exports = { GuardScanner, VERSION, THRESHOLDS, SEVERITY_WEIGHTS, scanToolCall, RUNTIME_CHECKS, getCheckStats, LAYER_NAMES };