@yagyeshvyas/vibeguard 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (52) hide show
  1. package/README.md +600 -0
  2. package/bin/cli.js +1640 -0
  3. package/ci/vibeguard.yml +41 -0
  4. package/ci-templates/Jenkinsfile +26 -0
  5. package/ci-templates/azure-pipelines.yml +29 -0
  6. package/ci-templates/circleci.yml +24 -0
  7. package/ci-templates/gitlab.yml +19 -0
  8. package/hooks/pre-commit +31 -0
  9. package/package.json +94 -0
  10. package/src/ai-guard.js +205 -0
  11. package/src/ast.js +319 -0
  12. package/src/audit-trail.js +154 -0
  13. package/src/autofix.js +524 -0
  14. package/src/badge.js +42 -0
  15. package/src/behavior.js +205 -0
  16. package/src/compliance.js +151 -0
  17. package/src/crosstaint.js +324 -0
  18. package/src/cve-intel.js +136 -0
  19. package/src/dashboard.js +279 -0
  20. package/src/deps.js +159 -0
  21. package/src/doctor.js +111 -0
  22. package/src/engine.js +234 -0
  23. package/src/external.js +160 -0
  24. package/src/firewall.js +517 -0
  25. package/src/history.js +87 -0
  26. package/src/hook.js +151 -0
  27. package/src/install.js +248 -0
  28. package/src/interceptor.js +476 -0
  29. package/src/mcp-server.js +1804 -0
  30. package/src/net-audit.js +208 -0
  31. package/src/pii.js +212 -0
  32. package/src/plugin.js +80 -0
  33. package/src/policy-gen.js +288 -0
  34. package/src/pre-deploy.js +282 -0
  35. package/src/presets.js +113 -0
  36. package/src/privacy-audit.js +273 -0
  37. package/src/repl.js +150 -0
  38. package/src/report.js +312 -0
  39. package/src/rules-pack.js +2753 -0
  40. package/src/rules.js +1446 -0
  41. package/src/sandbox.js +139 -0
  42. package/src/scanner.js +651 -0
  43. package/src/secure-prompt.js +140 -0
  44. package/src/slopsquat.js +144 -0
  45. package/src/supply-firewall.js +243 -0
  46. package/src/suppress.js +89 -0
  47. package/src/taint.js +168 -0
  48. package/src/trace.js +220 -0
  49. package/src/urlscan.js +142 -0
  50. package/src/vault.js +145 -0
  51. package/src/verify.js +98 -0
  52. package/src/verifykeys.js +87 -0
@@ -0,0 +1,140 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * secure_prompt — analyze an AI prompt BEFORE code is generated.
5
+ *
6
+ * This is VibeGuard's unique moat: catch security issues at the prompt level,
7
+ * before any code is written. Scans for:
8
+ * - Prompt injection vectors (user input in system prompt)
9
+ * - Requested insecure patterns (eval, exec, innerHTML, SQL concatenation)
10
+ * - Missing security constraints (no auth, no input validation, no rate limiting)
11
+ * - Dangerous capability requests (shell access, file access, DB access)
12
+ * - Missing guardrails for AI-generated code
13
+ */
14
+
15
+ const INJECTION_PATTERNS = [
16
+ { re: /ignore\s+(?:all\s+)?(?:previous|prior|above)\s+instructions/i, risk: 'high', msg: 'Prompt contains instruction-override language — possible prompt injection' },
17
+ { re: /you\s+are\s+(?:now|a)\s+(?:different|new)/i, risk: 'high', msg: 'Prompt contains role-reassignment language — possible prompt injection' },
18
+ { re: /(?:disregard|forget)\s+(?:the\s+)?(?:above|previous|all)/i, risk: 'high', msg: 'Prompt contains context-discard language — possible prompt injection' },
19
+ { re: /(?:system|developer)\s+(?:prompt|message)\s*:/i, risk: 'high', msg: 'Prompt references system/developer prompt — possible injection' },
20
+ { re: /(?:jailbreak|DAN|developer\s+mode|unrestricted\s+mode)/i, risk: 'critical', msg: 'Prompt contains known jailbreak terminology' },
21
+ ];
22
+
23
+ const INSECURE_REQUEST_PATTERNS = [
24
+ { re: /\beval\b\s*\(?\s*(?:user|input|request|req|data|code)?/i, risk: 'high', msg: 'Prompt requests eval() — code injection risk' },
25
+ { re: /new\s+Function\s*\(/i, risk: 'high', msg: 'Prompt requests new Function() — code injection risk' },
26
+ { re: /\bexec(?:Sync|File)?\s*\(/i, risk: 'high', msg: 'Prompt requests exec() — command injection risk' },
27
+ { re: /\bspawn\s*\(/i, risk: 'high', msg: 'Prompt requests spawn() — command injection risk' },
28
+ { re: /innerHTML\s*=/i, risk: 'medium', msg: 'Prompt requests innerHTML assignment — XSS risk' },
29
+ { re: /dangerouslySetInnerHTML/i, risk: 'medium', msg: 'Prompt requests dangerouslySetInnerHTML — XSS risk' },
30
+ { re: /SQL.*?concatenat|string.*?SQL.*?query|SQL.*?\+/i, risk: 'high', msg: 'Prompt suggests SQL string concatenation — SQL injection risk' },
31
+ { re: /(?:disable(?:s|d)?|skip|no|without|bypass|ignore)\s+(?:auth|authentication|authorization)/i, risk: 'high', msg: 'Prompt requests disabling authentication' },
32
+ { re: /(?:disable|skip|no)\s+(?:input\s+)?validat/i, risk: 'medium', msg: 'Prompt requests skipping input validation' },
33
+ { re: /(?:disable|skip|no)\s+(?:rate\s+limit|throttl)/i, risk: 'medium', msg: 'Prompt requests disabling rate limiting' },
34
+ { re: /(?:allow|permit|enable)\s+(?:all\s+)?(?:CORS|origins|wildcard)/i, risk: 'medium', msg: 'Prompt requests wildcard CORS' },
35
+ { re: /(?:store|save|put)\s+(?:password|secret|token|key|credential)\s+(?:in\s+)?(?:localStorage|client|browser)/i, risk: 'high', msg: 'Prompt suggests storing secrets client-side' },
36
+ { re: /(?:skip|disable|no)\s+(?:TLS|SSL|HTTPS|encryption)/i, risk: 'high', msg: 'Prompt suggests disabling encryption' },
37
+ { re: /(?:hardcode|hard-code|embed)\s+(?:password|secret|token|key|credential)/i, risk: 'high', msg: 'Prompt suggests hardcoding secrets' },
38
+ { re: /(?:allow|permit)\s+(?:any|all)\s+(?:file|filesystem)\s+access/i, risk: 'high', msg: 'Prompt requests unrestricted filesystem access' },
39
+ { re: /(?:allow|permit)\s+(?:arbitrary|any|all)\s+(?:command|shell)\s+(?:execution|access)/i, risk: 'critical', msg: 'Prompt requests arbitrary command execution' },
40
+ ];
41
+
42
+ const MISSING_CONSTRAINT_PATTERNS = [
43
+ { re: /(?:create|build|write|generate|implement)\s+(?:a\s+)?(?:REST|GraphQL|API|endpoint|route)/i, missing: 'auth', msg: 'API endpoint requested — ensure authentication is mentioned' },
44
+ { re: /(?:create|build|write|generate|implement)\s+(?:a\s+)?(?:form|input|submission|upload)/i, missing: 'validation', msg: 'Form/input requested — ensure input validation is mentioned' },
45
+ { re: /(?:create|build|write|generate|implement)\s+(?:a\s+)?(?:login|auth|register|signup)/i, missing: 'rate-limit', msg: 'Auth feature requested — ensure rate limiting is mentioned' },
46
+ { re: /(?:create|build|write|generate|implement)\s+(?:a\s+)?(?:database|DB|query|migration)/i, missing: 'parameterization', msg: 'Database code requested — ensure parameterized queries are mentioned' },
47
+ { re: /(?:create|build|write|generate|implement)\s+(?:a\s+)?(?:AI|LLM|agent|chat|assistant)/i, missing: 'prompt-injection-guard', msg: 'AI feature requested — ensure prompt injection protection is mentioned' },
48
+ { re: /(?:create|build|write|generate|implement)\s+(?:a\s+)?(?:file\s+upload|download|attachment)/i, missing: 'file-validation', msg: 'File upload requested — ensure file type/size validation is mentioned' },
49
+ ];
50
+
51
+ const DANGEROUS_CAPABILITY_PATTERNS = [
52
+ { re: /(?:agent|tool|function)\s+(?:that|which|can)\s+(?:execute|run|eval)/i, risk: 'critical', msg: 'Prompt requests an agent that can execute code — RCE via prompt injection' },
53
+ { re: /(?:agent|tool)\s+(?:that|which|can)\s+(?:access|read|write|modify)\s+(?:any|all)\s+(?:file|filesystem)/i, risk: 'high', msg: 'Prompt requests unrestricted filesystem access for an agent' },
54
+ { re: /(?:agent|tool)\s+(?:that|which|can)\s+(?:access|read|query|modify)\s+(?:any|all)\s+(?:database|DB)/i, risk: 'high', msg: 'Prompt requests unrestricted database access for an agent' },
55
+ { re: /(?:agent|tool)\s+(?:that|which|can)\s+(?:install|download|fetch|pip|npm)/i, risk: 'high', msg: 'Prompt requests package installation capability for an agent — supply chain risk' },
56
+ { re: /(?:agent|tool)\s+(?:that|which|can)\s+(?:deploy|publish|release|ship)/i, risk: 'high', msg: 'Prompt requests deployment capability for an agent' },
57
+ { re: /(?:agent|tool)\s+(?:that|which)\s+(?:has|with)\s+(?:full|unrestricted|admin|root)\s+(?:access|permissions?)/i, risk: 'critical', msg: 'Prompt requests unrestricted permissions for an agent' },
58
+ ];
59
+
60
+ function analyzePrompt(promptText) {
61
+ const findings = [];
62
+ let score = 100;
63
+
64
+ for (const p of INJECTION_PATTERNS) {
65
+ if (p.re.test(promptText)) {
66
+ findings.push({
67
+ category: 'prompt-injection',
68
+ risk: p.risk,
69
+ message: p.msg,
70
+ fix: 'Remove instruction-override language. Use system role for directives, user role for data.',
71
+ });
72
+ score -= p.risk === 'critical' ? 40 : 20;
73
+ }
74
+ }
75
+
76
+ for (const p of INSECURE_REQUEST_PATTERNS) {
77
+ if (p.re.test(promptText)) {
78
+ findings.push({
79
+ category: 'insecure-pattern-request',
80
+ risk: p.risk,
81
+ message: p.msg,
82
+ fix: 'Add a security constraint: "Do not use eval/exec. Use parameterized queries. Validate all input."',
83
+ });
84
+ score -= p.risk === 'critical' ? 35 : p.risk === 'high' ? 15 : 8;
85
+ }
86
+ }
87
+
88
+ for (const p of MISSING_CONSTRAINT_PATTERNS) {
89
+ if (p.re.test(promptText)) {
90
+ const hasConstraint = checkConstraintPresent(promptText, p.missing);
91
+ if (!hasConstraint) {
92
+ findings.push({
93
+ category: 'missing-constraint',
94
+ risk: 'medium',
95
+ message: p.msg,
96
+ fix: `Add to the prompt: "Ensure ${p.missing} is implemented."`,
97
+ });
98
+ score -= 5;
99
+ }
100
+ }
101
+ }
102
+
103
+ for (const p of DANGEROUS_CAPABILITY_PATTERNS) {
104
+ if (p.re.test(promptText)) {
105
+ findings.push({
106
+ category: 'dangerous-capability',
107
+ risk: p.risk,
108
+ message: p.msg,
109
+ fix: 'Add guardrails: sandbox, allowlist, human-in-the-loop, max-steps, and input validation.',
110
+ });
111
+ score -= p.risk === 'critical' ? 40 : 20;
112
+ }
113
+ }
114
+
115
+ return {
116
+ score: Math.max(0, score),
117
+ grade: score >= 90 ? 'A' : score >= 75 ? 'B' : score >= 60 ? 'C' : score >= 40 ? 'D' : 'F',
118
+ findings,
119
+ recommendation:
120
+ score >= 90
121
+ ? 'Prompt looks safe to execute'
122
+ : score >= 60
123
+ ? 'Prompt has security concerns — add constraints before executing'
124
+ : 'Prompt is unsafe — do NOT execute without adding security constraints',
125
+ };
126
+ }
127
+
128
+ function checkConstraintPresent(text, type) {
129
+ const checks = {
130
+ auth: /(?:auth|authentication|authorization|login|session|token|middleware)/i,
131
+ validation: /(?:validat|sanitize|schema|zod|joi|express-validator)/i,
132
+ 'rate-limit': /(?:rate\s*limit|throttl|cooldown|backoff)/i,
133
+ parameterization: /(?:parameteriz|prepared|placeholder|bind|sql\`|\$\{)/i,
134
+ 'prompt-injection-guard': /(?:prompt\s*injection|sanitiz|guardrail|system\s*prompt|instruction)/i,
135
+ 'file-validation': /(?:file\s*type|mime|size\s*limit|extension|magic\s*number|fingerprint)/i,
136
+ };
137
+ return checks[type] ? checks[type].test(text) : false;
138
+ }
139
+
140
+ module.exports = { analyzePrompt, checkConstraintPresent };
@@ -0,0 +1,144 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * Slopsquat detection — detect hallucinated/fictional npm packages.
5
+ *
6
+ * AI coding assistants sometimes "invent" package names that don't exist
7
+ * on the npm registry. If a developer installs one, an attacker can register
8
+ * it and plant malicious code (dependency confusion at the slopsquat level).
9
+ *
10
+ * Strategy:
11
+ * 1. Parse imports/requires from source files
12
+ * 2. Check each package against a known-good list (top 1000 npm packages)
13
+ * 3. Query npm registry (HEAD /package-name) to verify existence
14
+ * 4. Flag packages that don't exist on the registry
15
+ */
16
+
17
+ const https = require('https');
18
+ const fs = require('fs');
19
+ const path = require('path');
20
+
21
+ const IMPORT_RE = /(?:require\s*\(\s*['"]([^'"]+)['"]\s*\)|import\s+(?:[\s\S]*?\s+from\s+)?['"]([^'"]+)['"])/g;
22
+ const SCOPED_RE = /^@([^/]+)\/([^/]+)/;
23
+
24
+ // Top npm packages that are definitely real — short-circuit registry calls
25
+ const KNOWN_PACKAGES = new Set([
26
+ 'react', 'react-dom', 'next', 'vue', 'vue-router', '@vue/server-renderer',
27
+ 'express', 'fastify', 'koa', 'hapi', '@hapi/hapi', 'polka',
28
+ 'axios', 'node-fetch', 'got', 'superagent', 'undici',
29
+ 'lodash', 'ramda', 'date-fns', 'dayjs', 'luxon', 'moment',
30
+ 'chalk', 'colorette', 'kleur', 'picocolors',
31
+ 'zod', 'joi', 'yup', 'ajv', 'io-ts',
32
+ 'prisma', '@prisma/client', 'drizzle-orm', 'kysely', 'mikro-orm',
33
+ 'hono', '@hono/node-server',
34
+ 'jsonwebtoken', 'bcrypt', 'bcryptjs', 'argon2', 'passport',
35
+ 'stripe', '@stripe/stripe-js',
36
+ 'openai', 'anthropic-ai/sdk', '@anthropic-ai/sdk',
37
+ 'dotenv', 'cross-env', 'rimraf', 'nanoid', 'uuid',
38
+ 'typescript', 'ts-node', 'tsx', 'esbuild', 'vite', 'webpack',
39
+ 'eslint', 'prettier', 'jest', 'vitest', 'mocha', 'chai',
40
+ 'tailwindcss', 'postcss', 'autoprefixer',
41
+ 'framer-motion', 'motion', '@radix-ui/react-dialog',
42
+ 'clsx', 'tailwind-merge', 'cva', 'class-variance-authority',
43
+ 'ws', 'socket.io', 'socket.io-client',
44
+ 'mongoose', 'mongodb', 'pg', 'mysql2', 'sqlite3', 'better-sqlite3',
45
+ 'redis', 'ioredis', '@upstash/redis',
46
+ 'graphql', '@apollo/server', 'urql', '@urql/core',
47
+ 'nexus', 'tRPC', '@trpc/server', '@trpc/client',
48
+ 'zustand', 'jotai', 'recoil', 'redux', '@reduxjs/toolkit', 'react-query', '@tanstack/react-query',
49
+ 'dompurify', 'sanitize-html', 'xss',
50
+ 'helmet', 'cors', 'compression', 'morgan', 'body-parser',
51
+ 'sharp', 'canvas', 'jimp',
52
+ 'resend', '@resend/resend-node',
53
+ 'convex', 'turso', '@libsql/client',
54
+ 'expo', 'expo-secure-store', 'expo-constants',
55
+ 'react-native', 'react-native-web',
56
+ 'clerk', '@clerk/nextjs', '@clerk/backend',
57
+ 'next-auth', '@auth/core',
58
+ 'better-auth',
59
+ 'firebase', 'firebase-admin',
60
+ 'pino', 'winston', 'debug',
61
+ 'glob', 'fast-glob', 'tinyglobby', 'chokidar',
62
+ 'commander', 'yargs', 'meow', 'cac',
63
+ 'ajv', 'ajv-formats',
64
+ 'seedrandom', 'nanoid-dictionary',
65
+ ]);
66
+
67
+ function extractImports(content) {
68
+ const pkgs = new Set();
69
+ let m;
70
+ while ((m = IMPORT_RE.exec(content)) !== null) {
71
+ const pkg = m[1] || m[2];
72
+ if (!pkg) continue;
73
+ if (pkg.startsWith('.')) continue;
74
+ if (pkg.startsWith('node:') || pkg.startsWith('bun:')) continue;
75
+ const bare = pkg.split('/')[0];
76
+ if (pkg.startsWith('@')) {
77
+ const sm = SCOPED_RE.exec(pkg);
78
+ if (sm) pkgs.add(`@${sm[1]}/${sm[2]}`);
79
+ } else {
80
+ pkgs.add(bare);
81
+ }
82
+ }
83
+ return [...pkgs];
84
+ }
85
+
86
+ function checkNpmExists(pkgName) {
87
+ return new Promise((resolve) => {
88
+ if (KNOWN_PACKAGES.has(pkgName)) return resolve(true);
89
+ const url = `https://registry.npmjs.org/${encodeURIComponent(pkgName).replace(/%2F/g, '/')}`;
90
+ https
91
+ .get(url, { timeout: 8000 }, (res) => {
92
+ resolve(res.statusCode === 200);
93
+ })
94
+ .on('error', () => resolve(null))
95
+ .on('timeout', function () {
96
+ this.destroy();
97
+ resolve(null);
98
+ });
99
+ });
100
+ }
101
+
102
+ async function scanSlopsquat(root, files) {
103
+ const imports = new Set();
104
+ for (const file of files) {
105
+ try {
106
+ const content = fs.readFileSync(file, 'utf8');
107
+ for (const pkg of extractImports(content)) imports.add(pkg);
108
+ } catch {}
109
+ }
110
+
111
+ const findings = [];
112
+ const batch = [...imports];
113
+ for (let i = 0; i < batch.length; i += 10) {
114
+ const chunk = batch.slice(i, i + 10);
115
+ const results = await Promise.all(
116
+ chunk.map(async (pkg) => {
117
+ const exists = await checkNpmExists(pkg);
118
+ return { pkg, exists };
119
+ })
120
+ );
121
+ for (const r of results) {
122
+ if (r.exists === false) {
123
+ findings.push({
124
+ ruleId: 'supply-chain.slopsquat',
125
+ file: 'imports',
126
+ line: 1,
127
+ column: 1,
128
+ severity: 'medium',
129
+ confidence: 'medium',
130
+ title: `Possibly hallucinated package: ${r.pkg}`,
131
+ snippet: r.pkg,
132
+ message: `Package "${r.pkg}" does not exist on the npm registry. An attacker can register it and inject malicious code. If this is a private/internal package, configure your registry correctly.`,
133
+ fix: `Verify the package name spelling. If internal, configure .npmrc scopes. If from an AI suggestion, remove it.`,
134
+ owasp: 'A08:2025 Software and Data Integrity Failures',
135
+ cwe: 'CWE-494',
136
+ });
137
+ }
138
+ }
139
+ }
140
+
141
+ return { findings, checked: batch.length };
142
+ }
143
+
144
+ module.exports = { scanSlopsquat, extractImports, checkNpmExists, KNOWN_PACKAGES };
@@ -0,0 +1,243 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * VibeGuard Supply Chain Firewall.
5
+ *
6
+ * Pre-install protection that blocks malicious packages BEFORE they reach node_modules:
7
+ * - Pre-install hook: runs before npm install, blocks dangerous packages
8
+ * - Lockfile pinning: verifies all dependencies are pinned to exact versions
9
+ * - Integrity verification: checks all packages have integrity hashes
10
+ * - License audit: flags GPL/AGPL/Copyleft licenses in production
11
+ * - Postinstall audit: blocks packages with dangerous postinstall scripts
12
+ * - Typosquat + slopsquat: checks every package name against known attacks
13
+ *
14
+ * 100% local. Zero network. Zero dependencies.
15
+ */
16
+
17
+ const fs = require('fs');
18
+ const path = require('path');
19
+ const { checkPackage } = require('./firewall');
20
+
21
+ const DANGEROUS_SCRIPTS = [
22
+ /(?:curl|wget)\s+[^|]+\|\s*(?:bash|sh|sh -c)/i,
23
+ /(?:eval|exec)\s*\(/i,
24
+ /node\s+-e\s+['"]/i,
25
+ /python\s+-c\s+['"]/i,
26
+ /rm\s+-rf/i,
27
+ /chmod\s+777/i,
28
+ /nc\s+-/i,
29
+ /\/dev\/tcp/i,
30
+ /base64\s+-d\s*\|/i,
31
+ /mkfifo/i,
32
+ ];
33
+
34
+ const LICENSE_RISKS = {
35
+ GPL: { severity: 'high', reason: 'GPL — copyleft, may require source disclosure' },
36
+ AGPL: { severity: 'critical', reason: 'AGPL — network copyleft, SaaS must disclose source' },
37
+ SSPL: { severity: 'critical', reason: 'SSPL — Server Side Public License, effectively non-open-source' },
38
+ BUSL: { severity: 'high', reason: 'BUSL — Business Source License, not OSI approved' },
39
+ 'CC-BY-NC': { severity: 'high', reason: 'Non-commercial license — cannot be used commercially' },
40
+ UNLICENSED: { severity: 'high', reason: 'Unlicensed — no usage rights granted' },
41
+ };
42
+
43
+ function preInstallCheck(dir, packages) {
44
+ const findings = [];
45
+ let blocked = false;
46
+
47
+ for (const pkg of packages) {
48
+ const name = typeof pkg === 'string' ? pkg : pkg.name;
49
+ const version = typeof pkg === 'object' ? pkg.version : null;
50
+
51
+ // Check package name against firewall
52
+ const check = checkPackage(name);
53
+ for (const risk of check.risks) {
54
+ findings.push({
55
+ package: name,
56
+ version,
57
+ severity: risk.severity,
58
+ type: risk.type,
59
+ message: risk.message,
60
+ action: risk.action,
61
+ });
62
+ if (risk.action === 'block') blocked = true;
63
+ }
64
+
65
+ // Check version
66
+ if (version) {
67
+ if (version === '*' || version === 'latest' || version === '') {
68
+ findings.push({
69
+ package: name,
70
+ version,
71
+ severity: 'high',
72
+ type: 'unpinned',
73
+ message: `Package "${name}" is not pinned to a specific version (${version})`,
74
+ action: 'warn',
75
+ });
76
+ }
77
+ if (version.startsWith('^') || version.startsWith('~')) {
78
+ findings.push({
79
+ package: name,
80
+ version,
81
+ severity: 'medium',
82
+ type: 'range',
83
+ message: `Package "${name}" uses version range (${version}) — may install different version`,
84
+ action: 'warn',
85
+ });
86
+ }
87
+ }
88
+ }
89
+
90
+ return { findings, blocked, total: packages.length };
91
+ }
92
+
93
+ function auditLockfile(dir) {
94
+ const lockPath = path.join(dir, 'package-lock.json');
95
+ let lock;
96
+ try { lock = JSON.parse(fs.readFileSync(lockPath, 'utf8')); } catch {
97
+ return { error: 'No package-lock.json found. Run npm install to generate.' };
98
+ }
99
+
100
+ const deps = lock.dependencies || lock.packages || {};
101
+ const findings = [];
102
+
103
+ for (const [name, info] of Object.entries(deps)) {
104
+ // Check integrity hash
105
+ if (!info.integrity && !info.resolved?.includes('file:')) {
106
+ findings.push({
107
+ package: name,
108
+ severity: 'high',
109
+ type: 'missing_integrity',
110
+ message: `Package "${name}" has no integrity hash — cannot verify it hasn't been tampered with`,
111
+ });
112
+ }
113
+
114
+ // Check for resolved from non-registry
115
+ if (info.resolved && !info.resolved.includes('registry.npmjs.org')) {
116
+ findings.push({
117
+ package: name,
118
+ severity: 'medium',
119
+ type: 'non_registry',
120
+ message: `Package "${name}" is resolved from non-npm registry: ${info.resolved.slice(0, 80)}`,
121
+ });
122
+ }
123
+ }
124
+
125
+ return {
126
+ total: Object.keys(deps).length,
127
+ withIntegrity: Object.values(deps).filter(d => d.integrity).length,
128
+ findings,
129
+ findingsCount: findings.length,
130
+ };
131
+ }
132
+
133
+ function auditPackageJson(dir) {
134
+ const pkgPath = path.join(dir, 'package.json');
135
+ let pkg;
136
+ try { pkg = JSON.parse(fs.readFileSync(pkgPath, 'utf8')); } catch {
137
+ return { error: 'No package.json found' };
138
+ }
139
+
140
+ const findings = [];
141
+
142
+ // Check scripts for dangerous commands
143
+ if (pkg.scripts) {
144
+ for (const [name, script] of Object.entries(pkg.scripts)) {
145
+ for (const pattern of DANGEROUS_SCRIPTS) {
146
+ if (pattern.test(script)) {
147
+ findings.push({
148
+ script: name,
149
+ command: script.slice(0, 100),
150
+ severity: name === 'postinstall' ? 'critical' : 'high',
151
+ type: 'dangerous_script',
152
+ message: `Script "${name}" contains dangerous pattern: ${script.slice(0, 100)}`,
153
+ });
154
+ }
155
+ }
156
+ }
157
+ }
158
+
159
+ // Check license
160
+ if (pkg.license) {
161
+ const lic = String(pkg.license).toUpperCase();
162
+ for (const [key, risk] of Object.entries(LICENSE_RISKS)) {
163
+ if (lic.includes(key)) {
164
+ findings.push({
165
+ severity: risk.severity,
166
+ type: 'license',
167
+ message: `License: ${pkg.license} — ${risk.reason}`,
168
+ });
169
+ }
170
+ }
171
+ } else {
172
+ findings.push({
173
+ severity: 'medium',
174
+ type: 'no_license',
175
+ message: 'No license specified — package is "all rights reserved" by default',
176
+ });
177
+ }
178
+
179
+ // Check dependencies for wildcard versions
180
+ const allDeps = { ...(pkg.dependencies || {}), ...(pkg.devDependencies || {}) };
181
+ for (const [name, version] of Object.entries(allDeps)) {
182
+ if (version === '*' || version === 'latest' || version === '') {
183
+ findings.push({
184
+ package: name,
185
+ version,
186
+ severity: 'high',
187
+ type: 'unpinned',
188
+ message: `Dependency "${name}" is not pinned (${version})`,
189
+ });
190
+ }
191
+ }
192
+
193
+ return { findings, findingsCount: findings.length, total: Object.keys(allDeps).length };
194
+ }
195
+
196
+ function renderSupplyReport(result) {
197
+ const C = { red: '\x1b[31m', green: '\x1b[32m', yellow: '\x1b[33m', dim: '\x1b[2m', bold: '\x1b[1m', reset: '\x1b[0m' };
198
+ const lines = [
199
+ `${C.bold}VibeGuard Supply Chain Firewall${C.reset}`,
200
+ `${C.dim}${'─'.repeat(60)}${C.reset}`,
201
+ '',
202
+ ];
203
+
204
+ if (result.error) {
205
+ lines.push(` ${C.yellow}${result.error}${C.reset}`);
206
+ return lines.join('\n');
207
+ }
208
+
209
+ if (result.findings && result.findings.length === 0) {
210
+ lines.push(` ${C.green}No supply chain risks detected${C.reset}`);
211
+ return lines.join('\n');
212
+ }
213
+
214
+ if (result.total !== undefined) lines.push(` Total packages: ${result.total}`);
215
+ if (result.withIntegrity !== undefined) lines.push(` With integrity: ${C.green}${result.withIntegrity}${C.reset}/${result.total}`);
216
+ lines.push('');
217
+
218
+ if (result.findings) {
219
+ const critical = result.findings.filter(f => f.severity === 'critical');
220
+ const high = result.findings.filter(f => f.severity === 'high');
221
+ const medium = result.findings.filter(f => f.severity === 'medium');
222
+
223
+ if (critical.length > 0) {
224
+ lines.push(`${C.red}${C.bold}Critical${C.reset}`);
225
+ for (const f of critical) lines.push(` ${C.red}[CRITICAL]${C.reset} ${f.message}`);
226
+ lines.push('');
227
+ }
228
+ if (high.length > 0) {
229
+ lines.push(`${C.yellow}${C.bold}High${C.reset}`);
230
+ for (const f of high) lines.push(` ${C.yellow}[HIGH]${C.reset} ${f.message}`);
231
+ lines.push('');
232
+ }
233
+ if (medium.length > 0) {
234
+ lines.push(`${C.dim}Medium${C.reset}`);
235
+ for (const f of medium) lines.push(` ${C.dim}[MEDIUM]${C.reset} ${f.message}`);
236
+ lines.push('');
237
+ }
238
+ }
239
+
240
+ return lines.join('\n');
241
+ }
242
+
243
+ module.exports = { preInstallCheck, auditLockfile, auditPackageJson, renderSupplyReport, DANGEROUS_SCRIPTS, LICENSE_RISKS };
@@ -0,0 +1,89 @@
1
+ 'use strict';
2
+
3
+ /*
4
+ * Context-aware false positive suppression.
5
+ *
6
+ * Scans nearby lines for "safe context" patterns that indicate a finding
7
+ * is a false positive. For example:
8
+ * - eval() inside a test file (test.js) → suppress
9
+ * - secret that looks like a placeholder/example → suppress
10
+ * - HTTP URL in a comment → suppress
11
+ * - Variable named "testKey" or "mockToken" → suppress
12
+ *
13
+ * This runs AFTER rule matching, BEFORE findings are returned.
14
+ */
15
+
16
+ const PLACEHOLDER_PATTERNS = [
17
+ /(?:your[_-]?(?:api[_-]?key|token|secret)|placeholder|changeme|todo|fixme|xxx+|replace[_-]?me|insert[_-]?key|redacted|redact)/i,
18
+ /^(?:test|spec|mock|fixture|__test__|__fixtures__)\//i,
19
+ ];
20
+
21
+ const SAFE_CONTEXT_LINES = 3;
22
+
23
+ const FILE_CONTEXT = {
24
+ test: /(?:^|\/)(?:test|spec|__tests__|\.test\.|\.spec\.|tests\/|_test\.)/i,
25
+ docs: /(?:\.md$|\.txt$|README|CHANGELOG|CONTRIBUTING|LICENSE)/i,
26
+ config: /(?:\.config\.|\.rc\.|config\.js$|config\.ts$)/i,
27
+ example: /(?:example|demo|sample|tutorial)/i,
28
+ };
29
+
30
+ function isPlaceholder(line) {
31
+ for (const p of PLACEHOLDER_PATTERNS) {
32
+ if (p.test(line)) return true;
33
+ }
34
+ return false;
35
+ }
36
+
37
+ function isTestFile(relPath) {
38
+ return FILE_CONTEXT.test.test(relPath) || FILE_CONTEXT.example.test(relPath);
39
+ }
40
+
41
+ function isDocsFile(relPath) {
42
+ return FILE_CONTEXT.docs.test(relPath);
43
+ }
44
+
45
+ function hasSafeContext(lines, idx, ruleId) {
46
+ const start = Math.max(0, idx - SAFE_CONTEXT_LINES);
47
+ const end = Math.min(lines.length, idx + SAFE_CONTEXT_LINES + 1);
48
+ const context = lines.slice(start, end).join('\n').toLowerCase();
49
+
50
+ // If the surrounding code has try/catch or validation, some rules can be suppressed
51
+ if (ruleId === 'injection.eval' || ruleId === 'code.eval') {
52
+ if (/\b(?:json\.parse|function\s+\w+\s*\(|safe|sanitiz|escape|validate)\b/i.test(context)) return true;
53
+ }
54
+
55
+ // If there's a comment indicating intentional use
56
+ if (/(?:eslint-disable|@vibeguard-ignore|@ts-ignore|istanbul ignore|coverage ignore)/i.test(context)) return true;
57
+
58
+ // If it's inside a typeof check
59
+ if (typeof lines[idx] === 'string' && /typeof\s+\w+\s*===?\s*['"]/.test(context)) return true;
60
+
61
+ return false;
62
+ }
63
+
64
+ function suppressFindings(findings, content, relPath) {
65
+ if (!findings || findings.length === 0) return findings;
66
+ const lines = content ? content.split(/\r?\n/) : [];
67
+ const isTest = isTestFile(relPath);
68
+ const isDocs = isDocsFile(relPath);
69
+
70
+ return findings.filter((f) => {
71
+ // Only suppress in docs files — never suppress findings in actual code
72
+ if (isDocs && !f.ruleId.startsWith('secret.')) return false;
73
+
74
+ // Only suppress placeholder secrets — check the actual line content
75
+ if (f.ruleId.startsWith('secret.')) {
76
+ const lineIdx = f.line ? f.line - 1 : -1;
77
+ const line = lineIdx >= 0 && lineIdx < lines.length ? lines[lineIdx] : '';
78
+ if (isPlaceholder(line)) return false;
79
+ }
80
+
81
+ // Do NOT suppress findings in test files — tests expect specific findings
82
+ // Do NOT suppress based on "safe context" — too many false negatives
83
+ // Do NOT suppress low confidence — let the scanner's own confidence handle it
84
+
85
+ return true;
86
+ });
87
+ }
88
+
89
+ module.exports = { suppressFindings, isPlaceholder, isTestFile, isDocsFile, hasSafeContext };