@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.
- package/README.md +600 -0
- package/bin/cli.js +1640 -0
- package/ci/vibeguard.yml +41 -0
- package/ci-templates/Jenkinsfile +26 -0
- package/ci-templates/azure-pipelines.yml +29 -0
- package/ci-templates/circleci.yml +24 -0
- package/ci-templates/gitlab.yml +19 -0
- package/hooks/pre-commit +31 -0
- package/package.json +94 -0
- package/src/ai-guard.js +205 -0
- package/src/ast.js +319 -0
- package/src/audit-trail.js +154 -0
- package/src/autofix.js +524 -0
- package/src/badge.js +42 -0
- package/src/behavior.js +205 -0
- package/src/compliance.js +151 -0
- package/src/crosstaint.js +324 -0
- package/src/cve-intel.js +136 -0
- package/src/dashboard.js +279 -0
- package/src/deps.js +159 -0
- package/src/doctor.js +111 -0
- package/src/engine.js +234 -0
- package/src/external.js +160 -0
- package/src/firewall.js +517 -0
- package/src/history.js +87 -0
- package/src/hook.js +151 -0
- package/src/install.js +248 -0
- package/src/interceptor.js +476 -0
- package/src/mcp-server.js +1804 -0
- package/src/net-audit.js +208 -0
- package/src/pii.js +212 -0
- package/src/plugin.js +80 -0
- package/src/policy-gen.js +288 -0
- package/src/pre-deploy.js +282 -0
- package/src/presets.js +113 -0
- package/src/privacy-audit.js +273 -0
- package/src/repl.js +150 -0
- package/src/report.js +312 -0
- package/src/rules-pack.js +2753 -0
- package/src/rules.js +1446 -0
- package/src/sandbox.js +139 -0
- package/src/scanner.js +651 -0
- package/src/secure-prompt.js +140 -0
- package/src/slopsquat.js +144 -0
- package/src/supply-firewall.js +243 -0
- package/src/suppress.js +89 -0
- package/src/taint.js +168 -0
- package/src/trace.js +220 -0
- package/src/urlscan.js +142 -0
- package/src/vault.js +145 -0
- package/src/verify.js +98 -0
- package/src/verifykeys.js +87 -0
package/src/taint.js
ADDED
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* Lightweight intra-file taint analysis (no AST, no dependency).
|
|
5
|
+
*
|
|
6
|
+
* Regex rules only see one line. This follows user-controlled input across
|
|
7
|
+
* assignments within a file, so it catches the multi-step case a single-line
|
|
8
|
+
* regex misses:
|
|
9
|
+
*
|
|
10
|
+
* const name = req.body.name; // <- source, `name` becomes tainted
|
|
11
|
+
* const cmd = "ls " + name; // <- taint propagates to `cmd`
|
|
12
|
+
* exec(cmd); // <- tainted value reaches a shell sink
|
|
13
|
+
*
|
|
14
|
+
* It is deliberately conservative (top-down, whole-file variable set, no scopes).
|
|
15
|
+
* A dataflow-confirmed hit is HIGH confidence — we saw input actually reach the
|
|
16
|
+
* sink — which is stronger than the regex heuristics.
|
|
17
|
+
*
|
|
18
|
+
* Scope: JS/TS-family files. Best-effort, not a substitute for a real taint tool.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
const path = require('path');
|
|
22
|
+
|
|
23
|
+
const TAINT_EXT = new Set(['.js', '.jsx', '.ts', '.tsx', '.mjs', '.cjs', '.vue', '.svelte']);
|
|
24
|
+
|
|
25
|
+
// Something that introduces attacker-controlled data.
|
|
26
|
+
const SOURCE_RE =
|
|
27
|
+
/\breq\.(?:body|query|params|headers|cookies|url|originalUrl|hostname)\b|\brequest\.(?:body|query|params|headers)\b|\bctx\.request\.(?:body|query|params)\b|\bevent\.(?:body|queryStringParameters|pathParameters|headers)\b|\.searchParams\b|\bprocess\.argv\b/;
|
|
28
|
+
|
|
29
|
+
// Sinks: dangerous call -> what kind of bug if it receives tainted data.
|
|
30
|
+
const SINKS = [
|
|
31
|
+
{
|
|
32
|
+
re: /\b(?:exec|execSync|spawn|spawnSync|execFile|execFileSync)\s*\(/,
|
|
33
|
+
ruleId: 'taint.command-injection',
|
|
34
|
+
severity: 'high',
|
|
35
|
+
title: 'User input reaches a shell command (dataflow-confirmed)',
|
|
36
|
+
message: 'A value derived from user input flows into a shell command — command injection.',
|
|
37
|
+
fix: 'Pass arguments as an array (execFile("cmd",[arg])) and never build a shell string from input; validate/allowlist.',
|
|
38
|
+
},
|
|
39
|
+
{
|
|
40
|
+
re: /\.(?:query|raw|execute)\s*\(|\bsequelize\.query\s*\(/,
|
|
41
|
+
ruleId: 'taint.sql-injection',
|
|
42
|
+
severity: 'high',
|
|
43
|
+
title: 'User input reaches a SQL query (dataflow-confirmed)',
|
|
44
|
+
message: 'A value derived from user input flows into a SQL query call — SQL injection.',
|
|
45
|
+
fix: 'Use parameterized queries / prepared statements; pass input as bound parameters, not concatenated SQL.',
|
|
46
|
+
},
|
|
47
|
+
{
|
|
48
|
+
re: /\beval\s*\(|\bnew\s+Function\s*\(/,
|
|
49
|
+
ruleId: 'taint.code-injection',
|
|
50
|
+
severity: 'critical',
|
|
51
|
+
title: 'User input reaches eval()/Function() (dataflow-confirmed)',
|
|
52
|
+
message: 'A value derived from user input flows into eval()/new Function() — remote code execution.',
|
|
53
|
+
fix: 'Remove eval/Function on dynamic input. Use JSON.parse or an explicit dispatch table.',
|
|
54
|
+
},
|
|
55
|
+
{
|
|
56
|
+
re: /\b(?:fs|fsp|fse)\.(?:readFile|readFileSync|writeFile|writeFileSync|createReadStream|createWriteStream|unlink|unlinkSync|appendFile)\s*\(|\bres\.sendFile\s*\(|\bpath\.(?:join|resolve)\s*\(/,
|
|
57
|
+
ruleId: 'taint.path-traversal',
|
|
58
|
+
severity: 'high',
|
|
59
|
+
title: 'User input reaches a filesystem path (dataflow-confirmed)',
|
|
60
|
+
message: 'A value derived from user input is used to build a filesystem path — path traversal.',
|
|
61
|
+
fix: 'Sanitize with path.basename(), resolve against a fixed base, and reject paths that escape it.',
|
|
62
|
+
},
|
|
63
|
+
{
|
|
64
|
+
re: /\b(?:fetch|axios|got|superagent)\s*\(|\baxios\.(?:get|post|put|delete)\s*\(|\bhttps?\.(?:get|request)\s*\(/,
|
|
65
|
+
ruleId: 'taint.ssrf',
|
|
66
|
+
severity: 'high',
|
|
67
|
+
title: 'User input reaches an outbound request URL (dataflow-confirmed)',
|
|
68
|
+
message: 'A value derived from user input is used as an outbound request target — server-side request forgery (SSRF).',
|
|
69
|
+
fix: 'Allowlist permitted hosts/schemes; never fetch a URL built from raw user input; block internal/metadata addresses.',
|
|
70
|
+
},
|
|
71
|
+
{
|
|
72
|
+
re: /\bres\.redirect\s*\(|\bres\.location\s*\(/,
|
|
73
|
+
ruleId: 'taint.open-redirect',
|
|
74
|
+
severity: 'medium',
|
|
75
|
+
title: 'User input reaches a redirect target (dataflow-confirmed)',
|
|
76
|
+
message: 'A value derived from user input is used as a redirect target — open redirect (phishing).',
|
|
77
|
+
fix: 'Redirect only to an allowlist of internal paths; reject absolute/off-site URLs from input.',
|
|
78
|
+
},
|
|
79
|
+
];
|
|
80
|
+
|
|
81
|
+
// Extract identifier names that become tainted on this line, given the current
|
|
82
|
+
// tainted set. Returns array of new tainted names.
|
|
83
|
+
function newlyTainted(line, tainted) {
|
|
84
|
+
const names = [];
|
|
85
|
+
const rhsIsTainted = (rhs) => {
|
|
86
|
+
if (SOURCE_RE.test(rhs)) return true;
|
|
87
|
+
// references an already-tainted variable as a whole word
|
|
88
|
+
for (const t of tainted) {
|
|
89
|
+
if (new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`).test(rhs)) return true;
|
|
90
|
+
}
|
|
91
|
+
return false;
|
|
92
|
+
};
|
|
93
|
+
|
|
94
|
+
// Destructuring: const { a, b } = <src>
|
|
95
|
+
let m = /(?:const|let|var)\s*\{([^}]+)\}\s*=\s*(.+)$/.exec(line);
|
|
96
|
+
if (m && rhsIsTainted(m[2])) {
|
|
97
|
+
for (const raw of m[1].split(',')) {
|
|
98
|
+
const id = raw.split(':').pop().trim().replace(/\s.*$/, '');
|
|
99
|
+
if (/^[A-Za-z_$][\w$]*$/.test(id)) names.push(id);
|
|
100
|
+
}
|
|
101
|
+
return names;
|
|
102
|
+
}
|
|
103
|
+
|
|
104
|
+
// Simple assignment: [const|let|var] NAME = <rhs> or NAME = <rhs>
|
|
105
|
+
m = /(?:(?:const|let|var)\s+)?([A-Za-z_$][\w$]*)\s*=\s*(.+)$/.exec(line);
|
|
106
|
+
if (m && !/[=!<>]=/.test(m[0].slice(0, m.index + m[1].length + 3))) {
|
|
107
|
+
const name = m[1];
|
|
108
|
+
const rhs = m[2];
|
|
109
|
+
if (rhsIsTainted(rhs)) names.push(name);
|
|
110
|
+
}
|
|
111
|
+
return names;
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function referencesTainted(line, tainted) {
|
|
115
|
+
for (const t of tainted) {
|
|
116
|
+
if (new RegExp(`\\b${t.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}\\b`).test(line)) return t;
|
|
117
|
+
}
|
|
118
|
+
return null;
|
|
119
|
+
}
|
|
120
|
+
|
|
121
|
+
function analyzeTaint(content, lines, relPath) {
|
|
122
|
+
const ext = path.extname(relPath || '').toLowerCase();
|
|
123
|
+
if (!TAINT_EXT.has(ext)) return [];
|
|
124
|
+
|
|
125
|
+
const tainted = new Set();
|
|
126
|
+
const findings = [];
|
|
127
|
+
|
|
128
|
+
for (let i = 0; i < lines.length; i++) {
|
|
129
|
+
const line = lines[i];
|
|
130
|
+
if (line.length > 4000) continue;
|
|
131
|
+
const trimmed = line.trim();
|
|
132
|
+
const isComment = trimmed.startsWith('//') || trimmed.startsWith('*') || trimmed.startsWith('/*');
|
|
133
|
+
|
|
134
|
+
// 1) Check sinks first (a line can both use and reassign).
|
|
135
|
+
if (!isComment) {
|
|
136
|
+
for (const sink of SINKS) {
|
|
137
|
+
if (!sink.re.test(line)) continue;
|
|
138
|
+
// Skip the inline source case — the regex rules already report it; taint
|
|
139
|
+
// exists to catch the *multi-step* case where the source is elsewhere.
|
|
140
|
+
if (SOURCE_RE.test(line)) continue;
|
|
141
|
+
const via = referencesTainted(line, tainted);
|
|
142
|
+
if (via) {
|
|
143
|
+
findings.push({
|
|
144
|
+
ruleId: sink.ruleId,
|
|
145
|
+
severity: sink.severity,
|
|
146
|
+
confidence: 'high',
|
|
147
|
+
title: sink.title,
|
|
148
|
+
message: `${sink.message} (tainted via \`${via}\`)`,
|
|
149
|
+
fix: sink.fix,
|
|
150
|
+
file: relPath,
|
|
151
|
+
line: i + 1,
|
|
152
|
+
column: 1,
|
|
153
|
+
snippet: trimmed.slice(0, 120),
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
// 2) Propagate taint from assignments.
|
|
160
|
+
if (!isComment) {
|
|
161
|
+
for (const n of newlyTainted(line, tainted)) tainted.add(n);
|
|
162
|
+
}
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
return findings;
|
|
166
|
+
}
|
|
167
|
+
|
|
168
|
+
module.exports = { analyzeTaint, SOURCE_RE, SINKS };
|
package/src/trace.js
ADDED
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* Prompt tracing — link findings back to the AI prompt that generated them.
|
|
5
|
+
*
|
|
6
|
+
* Reads Cursor (.cursor/), Claude Code, and Windsurf session history files.
|
|
7
|
+
* Scans for security-relevant behavior patterns in AI agent transcripts.
|
|
8
|
+
*
|
|
9
|
+
* Two capabilities:
|
|
10
|
+
* 1. Trace a finding back to the AI prompt that likely generated the code
|
|
11
|
+
* 2. Behavior analysis: detect blind approvals, high delegation, risky patterns
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const fs = require('fs');
|
|
15
|
+
const path = require('path');
|
|
16
|
+
|
|
17
|
+
const SESSION_DIRS = [
|
|
18
|
+
'.cursor',
|
|
19
|
+
'.cursor/projects',
|
|
20
|
+
'.windsurf',
|
|
21
|
+
'.claude',
|
|
22
|
+
'.continue',
|
|
23
|
+
];
|
|
24
|
+
|
|
25
|
+
function findSessionFiles(root) {
|
|
26
|
+
const files = [];
|
|
27
|
+
for (const dir of SESSION_DIRS) {
|
|
28
|
+
const absDir = path.join(root, dir);
|
|
29
|
+
if (!fs.existsSync(absDir)) continue;
|
|
30
|
+
try {
|
|
31
|
+
walkAndCollect(absDir, files, /\.(?:json|jsonl|md|txt)$/i);
|
|
32
|
+
} catch {}
|
|
33
|
+
}
|
|
34
|
+
return files;
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
function walkAndCollect(dir, out, extRe) {
|
|
38
|
+
let entries;
|
|
39
|
+
try {
|
|
40
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
41
|
+
} catch { return; }
|
|
42
|
+
for (const e of entries) {
|
|
43
|
+
const full = path.join(dir, e.name);
|
|
44
|
+
if (e.isDirectory()) walkAndCollect(full, out, extRe);
|
|
45
|
+
else if (e.isFile() && extRe.test(e.name)) out.push(full);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
function parseSession(filepath) {
|
|
50
|
+
const content = fs.readFileSync(filepath, 'utf8');
|
|
51
|
+
const messages = [];
|
|
52
|
+
|
|
53
|
+
// Try JSONL format (one JSON object per line)
|
|
54
|
+
if (filepath.endsWith('.jsonl')) {
|
|
55
|
+
for (const line of content.split('\n')) {
|
|
56
|
+
try {
|
|
57
|
+
const obj = JSON.parse(line);
|
|
58
|
+
if (obj.role || obj.type || obj.message) messages.push(obj);
|
|
59
|
+
} catch {}
|
|
60
|
+
}
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
// Try JSON array
|
|
64
|
+
if (messages.length === 0 && filepath.endsWith('.json')) {
|
|
65
|
+
try {
|
|
66
|
+
const arr = JSON.parse(content);
|
|
67
|
+
if (Array.isArray(arr)) messages.push(...arr);
|
|
68
|
+
else messages.push(arr);
|
|
69
|
+
} catch {}
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
// Try markdown/text (split by user/assistant markers)
|
|
73
|
+
if (messages.length === 0) {
|
|
74
|
+
const parts = content.split(/^(?:User|Human|Assistant|AI|>>>)[:\s]/m);
|
|
75
|
+
parts.forEach((p, i) => {
|
|
76
|
+
if (p.trim()) messages.push({ role: i % 2 === 0 ? 'user' : 'assistant', content: p.trim() });
|
|
77
|
+
});
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
return { file: filepath, messages };
|
|
81
|
+
}
|
|
82
|
+
|
|
83
|
+
const RISKY_BEHAVIORS = [
|
|
84
|
+
{
|
|
85
|
+
id: 'behavior.blind-approval',
|
|
86
|
+
re: /(?:yes|ok|sure|go ahead|do it|approve|sounds good|perfect|great)\s*[!.?\s]*$/i,
|
|
87
|
+
risk: 'medium',
|
|
88
|
+
desc: 'Blind approval of AI suggestion without review',
|
|
89
|
+
},
|
|
90
|
+
{
|
|
91
|
+
id: 'behavior.high-delegation',
|
|
92
|
+
re: /(?:do\s+(?:all|everything|the\s+whole)|build\s+(?:the\s+entire|all)|write\s+(?:all|every|the\s+complete)|implement\s+(?:all|everything|the\s+entire))/i,
|
|
93
|
+
risk: 'medium',
|
|
94
|
+
desc: 'High delegation — asking AI to do everything at once reduces review quality',
|
|
95
|
+
},
|
|
96
|
+
{
|
|
97
|
+
id: 'behavior.skip-tests',
|
|
98
|
+
re: /(?:skip|don'?t\s+need|no\s+need\s+for)\s+(?:tests?|testing|validation)/i,
|
|
99
|
+
risk: 'high',
|
|
100
|
+
desc: 'Requesting code without tests',
|
|
101
|
+
},
|
|
102
|
+
{
|
|
103
|
+
id: 'behavior.skip-auth',
|
|
104
|
+
re: /(?:skip|don'?t\s+(?:need|worry\s+about)|no\s+need\s+for)\s+(?:auth|authentication|authorization|security)/i,
|
|
105
|
+
risk: 'high',
|
|
106
|
+
desc: 'Explicitly requesting to skip authentication/security',
|
|
107
|
+
},
|
|
108
|
+
{
|
|
109
|
+
id: 'behavior.hardcode-secrets',
|
|
110
|
+
re: /(?:just\s+)?(?:hardcode|hard-code|put\s+(?:the\s+)?(?:password|secret|token|key|api\s+key)\s+(?:directly\s+)?(?:in|here))/i,
|
|
111
|
+
risk: 'high',
|
|
112
|
+
desc: 'Asking AI to hardcode secrets',
|
|
113
|
+
},
|
|
114
|
+
{
|
|
115
|
+
id: 'behavior.disable-security',
|
|
116
|
+
re: /(?:disable|turn\s+off|remove|skip|bypass)\s+(?:security|validation|sanitization|escaping|CORS|helmet|CSRF)/i,
|
|
117
|
+
risk: 'high',
|
|
118
|
+
desc: 'Asking AI to disable security features',
|
|
119
|
+
},
|
|
120
|
+
{
|
|
121
|
+
id: 'behavior.trust-input',
|
|
122
|
+
re: /(?:trust\s+the\s+(?:user|client|input)|user\s+input\s+is\s+(?:safe|trusted|fine)|don'?t\s+validate)/i,
|
|
123
|
+
risk: 'high',
|
|
124
|
+
desc: 'Expressing trust in user/client input without validation',
|
|
125
|
+
},
|
|
126
|
+
{
|
|
127
|
+
id: 'behavior.excessive-iter',
|
|
128
|
+
re: /(?:again|redo|try\s+again|different\s+approach|start\s+over)/i,
|
|
129
|
+
risk: 'low',
|
|
130
|
+
desc: 'Excessive iteration on AI output — possible degradation of review quality',
|
|
131
|
+
threshold: 10,
|
|
132
|
+
},
|
|
133
|
+
];
|
|
134
|
+
|
|
135
|
+
function analyzeBehavior(messages) {
|
|
136
|
+
const behaviors = [];
|
|
137
|
+
let userMessages = 0;
|
|
138
|
+
let approvals = 0;
|
|
139
|
+
let iterations = 0;
|
|
140
|
+
|
|
141
|
+
for (const msg of messages) {
|
|
142
|
+
const role = msg.role || msg.type || '';
|
|
143
|
+
const content = msg.content || msg.message || msg.text || '';
|
|
144
|
+
if (typeof content !== 'string') continue;
|
|
145
|
+
if (!/user|human/i.test(role)) continue;
|
|
146
|
+
userMessages++;
|
|
147
|
+
|
|
148
|
+
for (const b of RISKY_BEHAVIORS) {
|
|
149
|
+
if (b.re.test(content)) {
|
|
150
|
+
if (b.id === 'behavior.blind-approval') approvals++;
|
|
151
|
+
if (b.id === 'behavior.excessive-iter') iterations++;
|
|
152
|
+
if (b.id === 'behavior.excessive-iter' && iterations < (b.threshold || 10)) continue;
|
|
153
|
+
behaviors.push({
|
|
154
|
+
id: b.id,
|
|
155
|
+
risk: b.risk,
|
|
156
|
+
message: b.desc,
|
|
157
|
+
snippet: content.slice(0, 200),
|
|
158
|
+
});
|
|
159
|
+
}
|
|
160
|
+
}
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
const delegationRatio = userMessages > 0 ? approvals / userMessages : 0;
|
|
164
|
+
const risk = delegationRatio > 0.6 ? 'high' : delegationRatio > 0.3 ? 'medium' : 'low';
|
|
165
|
+
|
|
166
|
+
return {
|
|
167
|
+
totalUserMessages: userMessages,
|
|
168
|
+
approvals,
|
|
169
|
+
iterations,
|
|
170
|
+
delegationRatio: Math.round(delegationRatio * 100) / 100,
|
|
171
|
+
risk,
|
|
172
|
+
behaviors,
|
|
173
|
+
recommendation:
|
|
174
|
+
risk === 'high'
|
|
175
|
+
? 'High blind-approval ratio — review AI suggestions more carefully before accepting'
|
|
176
|
+
: risk === 'medium'
|
|
177
|
+
? 'Moderate delegation — ensure each AI suggestion is reviewed'
|
|
178
|
+
: 'Good review discipline — keep validating AI output',
|
|
179
|
+
};
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
function traceFindingsToPrompts(findings, sessions) {
|
|
183
|
+
const traces = [];
|
|
184
|
+
for (const f of findings) {
|
|
185
|
+
const matching = [];
|
|
186
|
+
for (const session of sessions) {
|
|
187
|
+
for (const msg of session.messages) {
|
|
188
|
+
const content = msg.content || msg.message || '';
|
|
189
|
+
if (typeof content !== 'string') continue;
|
|
190
|
+
const snippet = f.snippet || '';
|
|
191
|
+
if (snippet && content.includes(snippet.slice(0, 30))) {
|
|
192
|
+
matching.push({ file: session.file, role: msg.role, snippet: content.slice(0, 200) });
|
|
193
|
+
}
|
|
194
|
+
const titleWords = (f.title || '').split(/\s+/).filter((w) => w.length > 4);
|
|
195
|
+
if (titleWords.length > 0 && titleWords.every((w) => content.toLowerCase().includes(w.toLowerCase()))) {
|
|
196
|
+
matching.push({ file: session.file, role: msg.role, snippet: content.slice(0, 200) });
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
if (matching.length > 0) {
|
|
201
|
+
traces.push({ finding: f.ruleId, file: f.file, line: f.line, matches: matching });
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
return traces;
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
function trace(root, findings) {
|
|
208
|
+
const sessionFiles = findSessionFiles(root);
|
|
209
|
+
if (sessionFiles.length === 0) {
|
|
210
|
+
return { sessions: 0, behavior: null, traces: [] };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
const sessions = sessionFiles.map(parseSession);
|
|
214
|
+
const behavior = analyzeBehavior(sessions.flatMap((s) => s.messages));
|
|
215
|
+
const traces = traceFindingsToPrompts(findings, sessions);
|
|
216
|
+
|
|
217
|
+
return { sessions: sessions.length, behavior, traces };
|
|
218
|
+
}
|
|
219
|
+
|
|
220
|
+
module.exports = { trace, analyzeBehavior, findSessionFiles, parseSession, RISKY_BEHAVIORS };
|
package/src/urlscan.js
ADDED
|
@@ -0,0 +1,142 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* Live-URL scan mode.
|
|
5
|
+
*
|
|
6
|
+
* Source code is only half the story — this checks what's ACTUALLY deployed by
|
|
7
|
+
* fetching a URL and inspecting the real HTTP response: missing security headers,
|
|
8
|
+
* insecure cookies, server/version leakage, and no-HTTPS. It cannot see logic
|
|
9
|
+
* bugs or backend holes; it audits the response surface only. Same honest scope.
|
|
10
|
+
*
|
|
11
|
+
* Uses global fetch (Node 18+). No dependencies.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
const REQUIRED_HEADERS = [
|
|
15
|
+
{
|
|
16
|
+
name: 'strict-transport-security',
|
|
17
|
+
severity: 'medium',
|
|
18
|
+
title: 'Missing HSTS',
|
|
19
|
+
message: 'No Strict-Transport-Security header — browsers may use http and be downgrade-attacked.',
|
|
20
|
+
fix: 'Send Strict-Transport-Security: max-age=63072000; includeSubDomains; preload (HTTPS only).',
|
|
21
|
+
},
|
|
22
|
+
{
|
|
23
|
+
name: 'content-security-policy',
|
|
24
|
+
severity: 'medium',
|
|
25
|
+
title: 'Missing Content-Security-Policy',
|
|
26
|
+
message: 'No Content-Security-Policy — weaker defense against XSS and injected resources.',
|
|
27
|
+
fix: "Add a Content-Security-Policy (start with default-src 'self' and tighten).",
|
|
28
|
+
},
|
|
29
|
+
{
|
|
30
|
+
name: 'x-content-type-options',
|
|
31
|
+
severity: 'low',
|
|
32
|
+
title: 'Missing X-Content-Type-Options',
|
|
33
|
+
message: 'No X-Content-Type-Options — browsers may MIME-sniff responses.',
|
|
34
|
+
fix: 'Add X-Content-Type-Options: nosniff.',
|
|
35
|
+
},
|
|
36
|
+
{
|
|
37
|
+
name: 'x-frame-options',
|
|
38
|
+
severity: 'low',
|
|
39
|
+
title: 'Missing X-Frame-Options',
|
|
40
|
+
message: 'No X-Frame-Options (and no frame-ancestors CSP) — page can be clickjacked in an iframe.',
|
|
41
|
+
fix: 'Add X-Frame-Options: DENY, or a Content-Security-Policy frame-ancestors directive.',
|
|
42
|
+
},
|
|
43
|
+
];
|
|
44
|
+
|
|
45
|
+
function analyzeHeaders(url, status, headers) {
|
|
46
|
+
const findings = [];
|
|
47
|
+
const get = (n) => headers.get(n);
|
|
48
|
+
const isHttps = url.startsWith('https://');
|
|
49
|
+
|
|
50
|
+
if (!isHttps) {
|
|
51
|
+
findings.push({
|
|
52
|
+
ruleId: 'url.no-https',
|
|
53
|
+
severity: 'high',
|
|
54
|
+
confidence: 'high',
|
|
55
|
+
title: 'Site served over http://',
|
|
56
|
+
message: 'The URL is not HTTPS — traffic (including credentials) is unencrypted.',
|
|
57
|
+
fix: 'Serve the site over HTTPS and redirect http to https.',
|
|
58
|
+
file: url, line: 1, column: 1, snippet: `HTTP ${status}`,
|
|
59
|
+
});
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
const cspFrameAncestors = /frame-ancestors/i.test(get('content-security-policy') || '');
|
|
63
|
+
for (const h of REQUIRED_HEADERS) {
|
|
64
|
+
if (h.name === 'strict-transport-security' && !isHttps) continue; // HSTS only meaningful on https
|
|
65
|
+
if (h.name === 'x-frame-options' && cspFrameAncestors) continue; // covered by CSP
|
|
66
|
+
if (!get(h.name)) {
|
|
67
|
+
findings.push({
|
|
68
|
+
ruleId: `url.missing-${h.name}`,
|
|
69
|
+
severity: h.severity,
|
|
70
|
+
confidence: 'high',
|
|
71
|
+
title: h.title,
|
|
72
|
+
message: h.message,
|
|
73
|
+
fix: h.fix,
|
|
74
|
+
file: url, line: 1, column: 1, snippet: `HTTP ${status}`,
|
|
75
|
+
});
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
// Server / framework version leakage.
|
|
80
|
+
for (const leak of ['server', 'x-powered-by']) {
|
|
81
|
+
const val = get(leak);
|
|
82
|
+
if (val && /\d/.test(val)) {
|
|
83
|
+
findings.push({
|
|
84
|
+
ruleId: 'url.version-leak',
|
|
85
|
+
severity: 'low',
|
|
86
|
+
confidence: 'medium',
|
|
87
|
+
title: 'Server/framework version disclosed',
|
|
88
|
+
message: `${leak}: ${val} — discloses software/version, helping attackers target known CVEs.`,
|
|
89
|
+
fix: `Remove or genericize the ${leak} header.`,
|
|
90
|
+
file: url, line: 1, column: 1, snippet: `${leak}: ${val}`,
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
|
|
95
|
+
// Insecure cookies.
|
|
96
|
+
const setCookie = headers.getSetCookie ? headers.getSetCookie() : (get('set-cookie') ? [get('set-cookie')] : []);
|
|
97
|
+
for (const cookie of setCookie) {
|
|
98
|
+
const name = (cookie.split('=')[0] || 'cookie').trim();
|
|
99
|
+
const flags = [];
|
|
100
|
+
if (isHttps && !/;\s*secure/i.test(cookie)) flags.push('Secure');
|
|
101
|
+
if (!/;\s*httponly/i.test(cookie)) flags.push('HttpOnly');
|
|
102
|
+
if (flags.length) {
|
|
103
|
+
findings.push({
|
|
104
|
+
ruleId: 'url.insecure-cookie',
|
|
105
|
+
severity: 'medium',
|
|
106
|
+
confidence: 'high',
|
|
107
|
+
title: 'Cookie missing security flags',
|
|
108
|
+
message: `Cookie "${name}" is missing ${flags.join(' and ')} — exposed to theft (XSS) or transport interception.`,
|
|
109
|
+
fix: `Set ${flags.join(' and ')} on the "${name}" cookie${flags.includes('HttpOnly') ? ' (unless JS must read it)' : ''}.`,
|
|
110
|
+
file: url, line: 1, column: 1, snippet: cookie.slice(0, 80),
|
|
111
|
+
});
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
return findings;
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
async function scanUrl(rawUrl, opts = {}) {
|
|
119
|
+
let url = rawUrl;
|
|
120
|
+
if (!/^https?:\/\//i.test(url)) url = 'https://' + url;
|
|
121
|
+
|
|
122
|
+
const controller = new AbortController();
|
|
123
|
+
const t = setTimeout(() => controller.abort(), opts.timeoutMs || 15000);
|
|
124
|
+
let res;
|
|
125
|
+
try {
|
|
126
|
+
res = await fetch(url, {
|
|
127
|
+
method: 'GET',
|
|
128
|
+
redirect: 'manual',
|
|
129
|
+
signal: controller.signal,
|
|
130
|
+
headers: { 'user-agent': 'VibeGuard/urlscan' },
|
|
131
|
+
});
|
|
132
|
+
} catch (err) {
|
|
133
|
+
clearTimeout(t);
|
|
134
|
+
throw new Error(`could not fetch ${url}: ${err && err.message ? err.message : err}`);
|
|
135
|
+
}
|
|
136
|
+
clearTimeout(t);
|
|
137
|
+
|
|
138
|
+
const findings = analyzeHeaders(url, res.status, res.headers);
|
|
139
|
+
return { url, status: res.status, findings };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
module.exports = { scanUrl, analyzeHeaders };
|
package/src/vault.js
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/*
|
|
4
|
+
* VibeGuard Secret Vault.
|
|
5
|
+
*
|
|
6
|
+
* Encrypted in-memory secret storage that AI cannot read directly.
|
|
7
|
+
* Instead of storing secrets in process.env (which AI can read),
|
|
8
|
+
* store them in the vault. AI must call vault.get('KEY') which:
|
|
9
|
+
* - Returns the secret only for the current operation
|
|
10
|
+
* - Never logs or exposes the raw value
|
|
11
|
+
* - Automatically redacts in console.log
|
|
12
|
+
* - Requires an explicit purpose for each access
|
|
13
|
+
*
|
|
14
|
+
* Usage:
|
|
15
|
+
* const vault = require('vibeguard/vault');
|
|
16
|
+
* vault.store('OPENAI_API_KEY', 'sk-proj-...');
|
|
17
|
+
* const key = vault.get('OPENAI_API_KEY', { purpose: 'chat completion' });
|
|
18
|
+
* // key is available for this call only
|
|
19
|
+
* // process.env.OPENAI_API_KEY is still undefined
|
|
20
|
+
*
|
|
21
|
+
* 100% local. Zero network. Zero dependencies.
|
|
22
|
+
*/
|
|
23
|
+
|
|
24
|
+
const crypto = require('crypto');
|
|
25
|
+
|
|
26
|
+
const VAULT_PREFIX = '__vg_vault_';
|
|
27
|
+
const secrets = new Map();
|
|
28
|
+
const accessLog = [];
|
|
29
|
+
|
|
30
|
+
// Generate a random encryption key per session
|
|
31
|
+
const SESSION_KEY = crypto.randomBytes(32);
|
|
32
|
+
|
|
33
|
+
function encrypt(text) {
|
|
34
|
+
const iv = crypto.randomBytes(16);
|
|
35
|
+
const cipher = crypto.createCipheriv('aes-256-gcm', SESSION_KEY, iv);
|
|
36
|
+
const encrypted = Buffer.concat([cipher.update(text, 'utf8'), cipher.final()]);
|
|
37
|
+
const tag = cipher.getAuthTag();
|
|
38
|
+
return Buffer.concat([iv, tag, encrypted]).toString('base64');
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
function decrypt(encStr) {
|
|
42
|
+
try {
|
|
43
|
+
const data = Buffer.from(encStr, 'base64');
|
|
44
|
+
const iv = data.slice(0, 16);
|
|
45
|
+
const tag = data.slice(16, 32);
|
|
46
|
+
const encrypted = data.slice(32);
|
|
47
|
+
const decipher = crypto.createDecipheriv('aes-256-gcm', SESSION_KEY, iv);
|
|
48
|
+
decipher.setAuthTag(tag);
|
|
49
|
+
return decipher.update(encrypted) + decipher.final('utf8');
|
|
50
|
+
} catch {
|
|
51
|
+
return null;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
|
|
55
|
+
function store(key, value, opts = {}) {
|
|
56
|
+
const encrypted = encrypt(value);
|
|
57
|
+
secrets.set(key, {
|
|
58
|
+
encrypted,
|
|
59
|
+
storedAt: Date.now(),
|
|
60
|
+
purpose: opts.purpose || 'general',
|
|
61
|
+
accessCount: 0,
|
|
62
|
+
});
|
|
63
|
+
// Also set in process.env but with a redacted marker
|
|
64
|
+
if (!opts.skipEnv) {
|
|
65
|
+
process.env[VAULT_PREFIX + key] = '[VAULT-PROTECTED]';
|
|
66
|
+
}
|
|
67
|
+
return { stored: true, key, redacted: true };
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function get(key, opts = {}) {
|
|
71
|
+
const entry = secrets.get(key);
|
|
72
|
+
if (!entry) return null;
|
|
73
|
+
|
|
74
|
+
// Log access
|
|
75
|
+
accessLog.push({
|
|
76
|
+
key,
|
|
77
|
+
purpose: opts.purpose || 'unspecified',
|
|
78
|
+
timestamp: Date.now(),
|
|
79
|
+
caller: opts.caller || 'unknown',
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
// Limit access log
|
|
83
|
+
if (accessLog.length > 1000) accessLog.shift();
|
|
84
|
+
|
|
85
|
+
// Increment access count
|
|
86
|
+
entry.accessCount++;
|
|
87
|
+
|
|
88
|
+
// Decrypt and return
|
|
89
|
+
return decrypt(entry.encrypted);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
function list() {
|
|
93
|
+
return [...secrets.keys()].map(key => ({
|
|
94
|
+
key,
|
|
95
|
+
storedAt: secrets.get(key).storedAt,
|
|
96
|
+
accessCount: secrets.get(key).accessCount,
|
|
97
|
+
purpose: secrets.get(key).purpose,
|
|
98
|
+
}));
|
|
99
|
+
}
|
|
100
|
+
|
|
101
|
+
function getAccessLog() {
|
|
102
|
+
return accessLog;
|
|
103
|
+
}
|
|
104
|
+
|
|
105
|
+
function clear() {
|
|
106
|
+
secrets.clear();
|
|
107
|
+
accessLog.length = 0;
|
|
108
|
+
return { cleared: true };
|
|
109
|
+
}
|
|
110
|
+
|
|
111
|
+
function count() {
|
|
112
|
+
return secrets.size;
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
function renderVaultReport() {
|
|
116
|
+
const C = { red: '\x1b[31m', green: '\x1b[32m', yellow: '\x1b[33m', dim: '\x1b[2m', bold: '\x1b[1m', reset: '\x1b[0m' };
|
|
117
|
+
const lines = [
|
|
118
|
+
`${C.bold}VibeGuard Secret Vault${C.reset}`,
|
|
119
|
+
`${C.dim}${'─'.repeat(60)}${C.reset}`,
|
|
120
|
+
'',
|
|
121
|
+
` Secrets stored: ${count()}`,
|
|
122
|
+
` Access attempts: ${accessLog.length}`,
|
|
123
|
+
'',
|
|
124
|
+
];
|
|
125
|
+
|
|
126
|
+
if (secrets.size > 0) {
|
|
127
|
+
lines.push(`${C.bold}Stored Secrets${C.reset}`, '');
|
|
128
|
+
for (const s of list()) {
|
|
129
|
+
lines.push(` ${C.green}[VAULT]${C.reset} ${s.key} — accessed ${s.accessCount}x, stored ${new Date(s.storedAt).toISOString().slice(0, 19)}`);
|
|
130
|
+
}
|
|
131
|
+
lines.push('');
|
|
132
|
+
}
|
|
133
|
+
|
|
134
|
+
if (accessLog.length > 0) {
|
|
135
|
+
lines.push(`${C.bold}Recent Access Log${C.reset}`, '');
|
|
136
|
+
for (const a of accessLog.slice(-10)) {
|
|
137
|
+
lines.push(` ${C.dim}${new Date(a.timestamp).toISOString().slice(11, 19)}${C.reset} ${a.key} — ${a.purpose}`);
|
|
138
|
+
}
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
lines.push('', `${C.dim}Secrets are encrypted in memory. AI cannot read them directly.${C.reset}`);
|
|
142
|
+
return lines.join('\n');
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
module.exports = { store, get, list, clear, count, getAccessLog, renderVaultReport };
|