buildproof 0.0.0-stage → 3.7.2
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/LICENSE.txt +2 -0
- package/README.md +23 -2
- package/bin/buildproof.js +253 -0
- package/core/ai.js +193 -0
- package/core/av-scan.js +66 -0
- package/core/bug-hunter/engine.js +4 -0
- package/core/certs.js +194 -0
- package/core/claims.js +53 -0
- package/core/config.js +57 -0
- package/core/deps-guard.js +49 -0
- package/core/edits.js +97 -0
- package/core/fixlib.js +93 -0
- package/core/flow.js +852 -0
- package/core/gate.js +193 -0
- package/core/hooks.js +120 -0
- package/core/integrity.js +321 -0
- package/core/keep-corrupt.js +17 -0
- package/core/license.js +165 -0
- package/core/machine-proof.js +27 -0
- package/core/project-lock.js +31 -0
- package/core/projects.js +180 -0
- package/core/proof-score.js +11 -0
- package/core/runner.js +46 -0
- package/core/scope.js +153 -0
- package/core/security-scan.js +68 -0
- package/core/server.js +322 -0
- package/core/service.js +89 -0
- package/core/snapshot.js +90 -0
- package/core/store.js +45 -0
- package/core/vault.js +77 -0
- package/license/.keep +0 -0
- package/license/vendor.pub.pem +3 -0
- package/package.json +39 -4
- package/scripts/guard.js +311 -0
- package/web/apple-touch-icon.png +0 -0
- package/web/favicon-32.png +0 -0
- package/web/html2canvas.min.js +20 -0
- package/web/icon-192.png +0 -0
- package/web/icon-512.png +0 -0
- package/web/index.html +834 -0
- package/web/manifest.webmanifest +12 -0
package/LICENSE.txt
ADDED
package/README.md
CHANGED
|
@@ -1,3 +1,24 @@
|
|
|
1
|
-
#
|
|
1
|
+
# BuildProof v3 - proof gate for AI-written code
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Works two ways, same guarantees:
|
|
4
|
+
|
|
5
|
+
**A. BuildProof fixes it** - task from phone / tablet / PC -> diagnose (baseline build/test) -> scope proposal (tests locked) -> your approval -> fix library or local AI (Ollama) under supervision -> proof -> signed certificate.
|
|
6
|
+
|
|
7
|
+
**B. Guard my AI tool** - keep using Cursor, Claude Code, Copilot... Start guard (full copy + baseline), work, then Check:
|
|
8
|
+
- Test-integrity guard (10 rules): deleted / skipped / removed tests, changed expected values, new mocks, sleeps, silent catches, silenced checkers, changed test scripts or test config.
|
|
9
|
+
- Fail-closed gate: a check that did not really run (timeout, "no tests found", fewer tests than before) = NOT proven.
|
|
10
|
+
- Hardcoded answers (code that special-cases the test's values) and code that detects the test environment.
|
|
11
|
+
- Revert check: the original code is put back for a moment - the tests must FAIL without the change (covered), otherwise flaky / not covered.
|
|
12
|
+
- Claim vs reality: what the AI said it did ("all tests pass", "added tests", "didn't touch tests", "fixed") is checked against what really happened.
|
|
13
|
+
- Removing the BuildProof hook is itself detected (guard_disabled).
|
|
14
|
+
- Accept -> ed25519-signed certificate (self-verifying HTML). Rollback -> project byte-for-byte as at guard start.
|
|
15
|
+
|
|
16
|
+
One-tap hooks (Projects -> AI tools, or `buildproof connect git,claude,cursor`): Claude Code (UserPromptSubmit starts the guard, Stop checks - exit 2 sends the reason back to Claude), Cursor (beforeSubmitPrompt / stop with followup_message), git pre-commit. Existing files are backed up and merged.
|
|
17
|
+
|
|
18
|
+
Projects: Node / Web (npm scripts typecheck, lint, build, test) and Python (syntax check of every file without writing .pyc, ruff and mypy when configured, pytest or unittest).
|
|
19
|
+
Also (3.7.1): Go (go build, go vet, go test), Rust (cargo build, cargo test - also tests inside the source file), Java with Maven or Gradle (JUnit results), .NET (dotnet build, dotnet test), Ruby (syntax check, RSpec or Minitest), PHP (syntax check, PHPUnit). Each uses its own toolchain on your computer; a missing toolchain or unreadable test results is reported, never counted as proven.
|
|
20
|
+
|
|
21
|
+
CLI: `buildproof start | check [--claim "..."] | accept [--force] | rollback | connect | verify <cert.html> | status`. `buildproof check` exits 0 only when proven.
|
|
22
|
+
|
|
23
|
+
Run: `node scripts/guard.js` (keeps core/server.js alive on port 38700). Test: `node test/run-all.js`.
|
|
24
|
+
Data (config, token, signing key, tasks, backups, certificates, learned fixes): `data/` - never shipped, kept on reinstall.
|
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
'use strict';
|
|
3
|
+
/**
|
|
4
|
+
* BuildProof CLI - use the guard from a terminal, a git hook or an AI tool hook.
|
|
5
|
+
*
|
|
6
|
+
* buildproof start [folder] start guarding (copy + baseline), then work with any AI tool
|
|
7
|
+
* buildproof check [folder] [--claim "what the AI said"] exit 0 = proven, 1 = not proven
|
|
8
|
+
* buildproof accept [folder] [--force] accept and sign a certificate
|
|
9
|
+
* buildproof rollback [folder] restore the project exactly as at guard start
|
|
10
|
+
* buildproof connect [folder] git,claude,cursor install the hooks in one go
|
|
11
|
+
* buildproof status service and AI status
|
|
12
|
+
* buildproof verify <certificate.html|.json> [--rerun folder] verify a certificate (and re-run its checks)
|
|
13
|
+
* buildproof repro <evidence.json> [folder] replay one hidden-bug finding (isolated copy)
|
|
14
|
+
* buildproof init [folder] one-time setup: background service, project, AI tool hooks
|
|
15
|
+
* buildproof activate <key> activate a license key buildproof license show the plan
|
|
16
|
+
* buildproof open open BuildProof in the browser
|
|
17
|
+
*
|
|
18
|
+
* Hook mode (installed by "connect"): --hook=claude | --hook=cursor | --hook=git
|
|
19
|
+
*/
|
|
20
|
+
const fs = require('fs');
|
|
21
|
+
const path = require('path');
|
|
22
|
+
const http = require('http');
|
|
23
|
+
function openUrl(u) { // best effort: the default browser
|
|
24
|
+
try { const { spawn } = require('child_process'); const c = process.platform === 'win32' ? spawn('cmd', ['/c', 'start', '', u], { detached: true, stdio: 'ignore', windowsHide: true }) : spawn(process.platform === 'darwin' ? 'open' : 'xdg-open', [u], { detached: true, stdio: 'ignore' }); c.on('error', () => {}); c.unref(); return true; } catch { return false; }
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const ROOT = path.resolve(__dirname, '..');
|
|
28
|
+
const config = require('../core/config');
|
|
29
|
+
|
|
30
|
+
const args = process.argv.slice(2);
|
|
31
|
+
const cmd = args[0] || 'help';
|
|
32
|
+
const flag = (n) => { const a = args.find((x) => x === `--${n}` || x.startsWith(`--${n}=`)); return a == null ? null : a.includes('=') ? a.split('=').slice(1).join('=') : true; };
|
|
33
|
+
const hook = flag('hook');
|
|
34
|
+
const force = !!flag('force');
|
|
35
|
+
let claimArg = null;
|
|
36
|
+
{ const i = args.indexOf('--claim'); if (i >= 0) claimArg = args[i + 1] || ''; }
|
|
37
|
+
const positional = args.slice(1).filter((a, i, all) => !a.startsWith('--') && all[i - 1] !== '--claim');
|
|
38
|
+
|
|
39
|
+
function readStdin() {
|
|
40
|
+
if (!hook || process.stdin.isTTY) return Promise.resolve({});
|
|
41
|
+
return new Promise((resolve) => {
|
|
42
|
+
let raw = ''; const t = setTimeout(() => resolve(parse(raw)), 1500);
|
|
43
|
+
process.stdin.on('data', (d) => { raw += d; });
|
|
44
|
+
process.stdin.on('end', () => { clearTimeout(t); resolve(parse(raw)); });
|
|
45
|
+
process.stdin.on('error', () => { clearTimeout(t); resolve({}); });
|
|
46
|
+
});
|
|
47
|
+
function parse(s) { try { return JSON.parse(s); } catch { return {}; } }
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function api(method, p, body) {
|
|
51
|
+
const c = config.load();
|
|
52
|
+
return new Promise((resolve) => {
|
|
53
|
+
const data = body ? JSON.stringify(body) : null;
|
|
54
|
+
const req = http.request({ host: '127.0.0.1', port: c.port, path: p, method, headers: { authorization: `Bearer ${c.token}`, ...(data ? { 'content-type': 'application/json', 'content-length': Buffer.byteLength(data) } : {}) }, timeout: 30 * 60 * 1000 }, (res) => {
|
|
55
|
+
let raw = ''; res.on('data', (d) => { raw += d; }); res.on('end', () => { try { resolve(JSON.parse(raw)); } catch { resolve({ ok: false, error: 'bad_response' }); } });
|
|
56
|
+
});
|
|
57
|
+
req.on('error', () => resolve({ ok: false, error: 'service_not_running', down: true }));
|
|
58
|
+
if (data) req.write(data);
|
|
59
|
+
req.end();
|
|
60
|
+
});
|
|
61
|
+
}
|
|
62
|
+
const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
|
|
63
|
+
const same = (a, b) => path.resolve(a).toLowerCase() === path.resolve(b).toLowerCase();
|
|
64
|
+
|
|
65
|
+
function out(line, code) { if (line) console.log(line); process.exit(code); }
|
|
66
|
+
|
|
67
|
+
/** Hook replies in the format each tool understands. Hooks never block when BuildProof itself is not in use. */
|
|
68
|
+
function hookPass() {
|
|
69
|
+
if (hook === 'cursor') console.log(cmd === 'start' ? '{"continue":true}' : '{}');
|
|
70
|
+
process.exit(0);
|
|
71
|
+
}
|
|
72
|
+
function hookBlock(msg) {
|
|
73
|
+
if (hook === 'claude') { process.stderr.write(msg + '\n'); process.exit(2); }
|
|
74
|
+
if (hook === 'cursor') { console.log(JSON.stringify({ followup_message: msg })); process.exit(0); }
|
|
75
|
+
console.log(msg); process.exit(1); // git
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
function steps(after) { return Object.entries(after || {}).map(([s, r]) => `${s}=${r.pass ? 'PASS' : r.ran === false ? 'NOTRUN' : 'FAIL'}`).join(' '); }
|
|
79
|
+
|
|
80
|
+
async function findProject(dir, create) {
|
|
81
|
+
if (create) { const r = await api('POST', '/api/projects', { root: dir }); return r.ok ? r.project : (r.down ? { down: true } : null); }
|
|
82
|
+
const r = await api('GET', '/api/projects');
|
|
83
|
+
if (r.down) return { down: true };
|
|
84
|
+
return (r.projects || []).filter((p) => same(p.root, dir) || path.resolve(dir).toLowerCase().startsWith(path.resolve(p.root).toLowerCase() + path.sep)).sort((a, b) => b.root.length - a.root.length)[0] || null;
|
|
85
|
+
}
|
|
86
|
+
async function activeGuard(projectId) {
|
|
87
|
+
const r = await api('GET', '/api/tasks');
|
|
88
|
+
return (r.tasks || []).find((t) => t.kind === 'guard' && t.projectId === projectId && ['baselining', 'watching', 'checking'].includes(t.state));
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
async function main() {
|
|
92
|
+
if (cmd === 'verify') {
|
|
93
|
+
const certs = require('../core/certs');
|
|
94
|
+
const file = positional[0];
|
|
95
|
+
if (!file || !fs.existsSync(file)) out('usage: buildproof verify <certificate.html|.json>', 1);
|
|
96
|
+
const raw = fs.readFileSync(file, 'utf8');
|
|
97
|
+
const m = raw.match(/<script id="cert" type="application\/json">([\s\S]*?)<\/script>/);
|
|
98
|
+
const cert = JSON.parse(m ? m[1] : raw);
|
|
99
|
+
const ok = certs.verify(cert);
|
|
100
|
+
if (!ok) out('INVALID signature - the certificate was modified (or names a key it was not signed with)', 1);
|
|
101
|
+
if (!flag('rerun')) out(`VALID ${cert.payload.id} ${cert.payload.result} project=${cert.payload.project}`, 0);
|
|
102
|
+
// --rerun: is this exactly the certified code, and do the checks really pass here?
|
|
103
|
+
const rr = cert.payload.rerun;
|
|
104
|
+
if (!rr) out(`VALID ${cert.payload.id} - this certificate is too old for --rerun`, 1);
|
|
105
|
+
const dir = path.resolve(positional[1] || process.cwd());
|
|
106
|
+
const tree = certs.treeOf(dir, { legacy: !rr.walk }); // certificates from before 3.7.1 used the old folder rules
|
|
107
|
+
const problems = [];
|
|
108
|
+
if (tree.treeHash !== rr.treeHash) {
|
|
109
|
+
let detail = '';
|
|
110
|
+
if (rr.files && tree.files) {
|
|
111
|
+
const want = new Map(rr.files.map((f) => [f.file, f.sha256])); const have = new Map(tree.files.map((f) => [f.file, f.sha256]));
|
|
112
|
+
const diff = [...new Set([...want.keys(), ...have.keys()])].filter((f) => want.get(f) !== have.get(f));
|
|
113
|
+
detail = ` (${diff.length} file(s) differ: ${diff.slice(0, 5).join(', ')}${diff.length > 5 ? ', ...' : ''})`;
|
|
114
|
+
}
|
|
115
|
+
problems.push('the code is NOT the certified version' + detail);
|
|
116
|
+
}
|
|
117
|
+
const projects = require('../core/projects');
|
|
118
|
+
const { run } = require('../core/runner');
|
|
119
|
+
const gate = require('../core/gate');
|
|
120
|
+
const info = projects.detect(dir);
|
|
121
|
+
const results = [];
|
|
122
|
+
for (const step of rr.steps) {
|
|
123
|
+
const { cmd, args } = projects.commandFor(info, step);
|
|
124
|
+
process.stdout.write(`running ${step}...\r`);
|
|
125
|
+
const r = await run(cmd, args, { cwd: dir, timeoutMs: 10 * 60 * 1000 });
|
|
126
|
+
const g = gate.evaluate(step, r);
|
|
127
|
+
const was = (cert.payload.checks || []).find((c) => c.step === step);
|
|
128
|
+
results.push(`${step}=${g.pass ? 'PASS' : 'FAIL'}${g.tests ? '(' + g.tests.passed + '/' + g.tests.total + ')' : ''}`);
|
|
129
|
+
if (!g.pass) problems.push(`${step} fails here`);
|
|
130
|
+
else if (was && was.tests && g.tests && g.tests.total < was.tests.total) problems.push(`${step}: fewer tests ran here (${g.tests.total}) than certified (${was.tests.total})`);
|
|
131
|
+
}
|
|
132
|
+
out(problems.length ? `RERUN_MISMATCH ${cert.payload.id} | ${problems.join('; ')} | ${results.join(' ')}` : `RERUN_VERIFIED ${cert.payload.id} code=identical(${tree.count} files) ${results.join(' ')}`, problems.length ? 1 : 0);
|
|
133
|
+
}
|
|
134
|
+
if (cmd === 'repro') {
|
|
135
|
+
// replay one hidden-bug finding: buildproof repro <evidence.json> [project folder]
|
|
136
|
+
const file = positional[0];
|
|
137
|
+
if (!file || !fs.existsSync(file)) out('usage: buildproof repro <evidence.json> [project folder]', 1);
|
|
138
|
+
const f = JSON.parse(fs.readFileSync(file, 'utf8'));
|
|
139
|
+
const r = await require('../core/bug-hunter/engine').repro(path.resolve(positional[1] || process.cwd()), f);
|
|
140
|
+
out(`${r.reproduced ? 'REPRODUCED' : 'NOT_REPRODUCED'} ${f.oracle} ${f.file} ${f.export}(${f.inputPreview}) -> ${r.outcome}`, r.reproduced ? 0 : 1);
|
|
141
|
+
}
|
|
142
|
+
if (cmd === 'license' || cmd === 'activate') {
|
|
143
|
+
if (cmd === 'activate') {
|
|
144
|
+
let key = positional[0] || '';
|
|
145
|
+
if (!key) { // no key typed: take it from the clipboard (copied on the thank-you page)
|
|
146
|
+
const { spawnSync } = require('child_process');
|
|
147
|
+
const c = process.platform === 'win32' ? spawnSync('powershell', ['-NoProfile', '-Command', 'Get-Clipboard'], { encoding: 'utf8', windowsHide: true }) : spawnSync(process.platform === 'darwin' ? 'pbpaste' : 'xclip', process.platform === 'darwin' ? [] : ['-o', '-selection', 'clipboard'], { encoding: 'utf8' });
|
|
148
|
+
key = ((c.stdout || '').match(/BP1\.[\w-]+\.[\w-]+/) || [''])[0];
|
|
149
|
+
if (!key) out('ACTIVATE_FAIL no key - copy it from the thank-you page, or: buildproof activate <key>', 1);
|
|
150
|
+
}
|
|
151
|
+
const r = await api('POST', '/api/license', { key });
|
|
152
|
+
out(r.ok ? `ACTIVATED ${r.license.label} until ${String(r.license.expires).slice(0, 10)}` : `ACTIVATE_FAIL ${r.error}`, r.ok ? 0 : 1);
|
|
153
|
+
}
|
|
154
|
+
const r = await api('GET', '/api/license');
|
|
155
|
+
if (!r.ok) out(`DOWN ${r.error}`, 1);
|
|
156
|
+
out(`LICENSE ${r.label} ${r.status}${r.daysLeft != null ? ' days_left=' + r.daysLeft : ''}${r.projects ? ' projects_max=' + r.projects : ''}`, r.status === 'expired' ? 1 : 0);
|
|
157
|
+
}
|
|
158
|
+
if (cmd === 'init') {
|
|
159
|
+
const service = require('../core/service');
|
|
160
|
+
const sv = await service.ensure({ autostart: !process.env.MGR_NO_AUTOSTART });
|
|
161
|
+
if (!sv.ok) out(`INIT_FAIL BuildProof could not start on port ${sv.port}`, 1);
|
|
162
|
+
const dir = path.resolve(positional[0] || process.cwd());
|
|
163
|
+
const pr = await api('POST', '/api/projects', { root: dir });
|
|
164
|
+
if (!pr.ok) out(`INIT_FAIL ${pr.error}${pr.limit ? ' (limit ' + pr.limit + ' projects in this plan)' : ''}`, 1);
|
|
165
|
+
const { spawnSync } = require('child_process');
|
|
166
|
+
const onPath = (c) => { try { return spawnSync(process.platform === 'win32' ? 'where' : 'which', [c], { stdio: 'ignore' }).status === 0; } catch { return false; } };
|
|
167
|
+
const tools = [];
|
|
168
|
+
if (fs.existsSync(path.join(dir, '.claude')) || onPath('claude')) tools.push('claude');
|
|
169
|
+
if (fs.existsSync(path.join(dir, '.cursor')) || onPath('cursor')) tools.push('cursor');
|
|
170
|
+
if (fs.existsSync(path.join(dir, '.git'))) tools.push('git');
|
|
171
|
+
let hk = { ok: true, hooks: {} };
|
|
172
|
+
if (tools.length) hk = await api('POST', `/api/projects/${pr.project.id}/hooks`, { tools });
|
|
173
|
+
const lic = await api('GET', '/api/license');
|
|
174
|
+
const connected = Object.entries(hk.hooks || {}).filter(([, v]) => v.connected).map(([k]) => k);
|
|
175
|
+
console.log(`INIT project=${pr.project.name} type=${pr.project.type} proof=${pr.project.verify.join(',') || 'none'} tools=${connected.join(',') || 'none'} service=${sv.how}${sv.autostart ? '/' + sv.autostart : ''} license=${lic.label}:${lic.status}${lic.daysLeft != null ? '(' + lic.daysLeft + 'd)' : ''}`);
|
|
176
|
+
if (!process.env.MGR_NO_AUTOSTART && !process.env.MGR_NO_OPEN) openUrl(`http://127.0.0.1:${sv.port}/connect`);
|
|
177
|
+
out(`OPEN http://127.0.0.1:${sv.port}/connect (BuildProof on this computer + add your phone)`, 0);
|
|
178
|
+
}
|
|
179
|
+
if (cmd === 'open') { const u = `http://127.0.0.1:${config.load().port || 38700}/connect`; openUrl(u); out('OPEN ' + u, 0); }
|
|
180
|
+
if (cmd === 'status') {
|
|
181
|
+
const r = await api('GET', '/api/status');
|
|
182
|
+
out(r.ok ? `BUILDPROOF v${r.version} AI=${r.ai.ok ? 'OK' : 'DOWN'} fixes=${r.fixes} key=${r.fingerprint}` : `DOWN ${r.error}`, r.ok ? 0 : 1);
|
|
183
|
+
}
|
|
184
|
+
if (!['start', 'check', 'accept', 'rollback', 'connect'].includes(cmd)) {
|
|
185
|
+
out(fs.readFileSync(__filename, 'utf8').split('\n').slice(3, 17).map((l) => l.replace(/^ \* ?/, '')).join('\n'), cmd === 'help' ? 0 : 1);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
const input = await readStdin();
|
|
189
|
+
const folder = path.resolve(positional[0] && cmd !== 'connect' ? positional[0] : (cmd === 'connect' && positional.length > 1 ? positional[0] : (input.cwd || (input.workspace_roots && input.workspace_roots[0]) || process.cwd())));
|
|
190
|
+
// only start / connect register a new project; check, accept and rollback must work on a known project even when the licence has ended
|
|
191
|
+
const p = await findProject(folder, !hook && ['start', 'connect'].includes(cmd));
|
|
192
|
+
if (!p || p.down) {
|
|
193
|
+
// service down while a guard is active for this folder: a hook must NOT let the work through unchecked
|
|
194
|
+
if (hook && p && p.down && cmd === 'check') {
|
|
195
|
+
const crypto = require('crypto'); const { DATA_DIR } = require('../core/config');
|
|
196
|
+
for (let d = folder; ; d = path.dirname(d)) {
|
|
197
|
+
if (fs.existsSync(path.join(DATA_DIR, 'active-guards', crypto.createHash('sha256').update(path.resolve(d).toLowerCase()).digest('hex').slice(0, 24) + '.json'))) hookBlock('BuildProof: a guard is active for this project, but the BuildProof service is not running, so nothing can be checked. Start it (buildproof open), then check again.');
|
|
198
|
+
if (path.dirname(d) === d) break;
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
if (hook) hookPass();
|
|
202
|
+
out(p && p.down ? 'DOWN service_not_running (start BuildProof first)' : `NOT_A_PROJECT ${folder}`, 1);
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (cmd === 'connect') {
|
|
206
|
+
const tools = (positional[positional.length - 1] || 'git,claude,cursor').split(',').map((s) => s.trim());
|
|
207
|
+
const r = await api('POST', `/api/projects/${p.id}/hooks`, { tools });
|
|
208
|
+
out(r.ok ? `CONNECTED ${Object.entries(r.hooks).filter(([, v]) => v.connected).map(([k]) => k).join(',')}` : `FAIL ${r.error || JSON.stringify(r.result)}`, r.ok ? 0 : 1);
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
let g = await activeGuard(p.id);
|
|
212
|
+
if (cmd === 'start') {
|
|
213
|
+
if (!g) { const r = await api('POST', '/api/guards', { projectId: p.id, source: hook ? hook : 'cli' }); if (!r.ok) { if (hook) hookPass(); out(`FAIL ${r.error}`, 1); } g = r.task; }
|
|
214
|
+
if (hook) hookPass(); // do not make the developer wait for the baseline
|
|
215
|
+
while (g && g.state === 'baselining') { await sleep(1000); g = (await api('GET', `/api/tasks/${g.id}`)).task; }
|
|
216
|
+
if (!g || g.state !== 'watching') out(`FAIL ${g ? g.resultText : 'guard not started'}`, 1);
|
|
217
|
+
const full = (await api('GET', `/api/tasks/${g.id}`)).task;
|
|
218
|
+
out(`GUARD_ON ${p.name} baseline: ${steps(full.baseline) || 'no build/test scripts'}`, 0);
|
|
219
|
+
}
|
|
220
|
+
if (!g) { if (hook) hookPass(); out(`NO_GUARD for ${p.name}. Run: buildproof start`, 1); }
|
|
221
|
+
while (g.state === 'baselining' || g.state === 'checking') { await sleep(1000); g = (await api('GET', `/api/tasks/${g.id}`)).task; }
|
|
222
|
+
|
|
223
|
+
if (cmd === 'check') {
|
|
224
|
+
const claim = claimArg != null ? claimArg : (input.last_assistant_message || input.text || '');
|
|
225
|
+
const r = await api('POST', `/api/guards/${g.id}/check`, { claim });
|
|
226
|
+
if (!r.ok) { if (hook) hookPass(); out(`FAIL ${r.error}`, 1); }
|
|
227
|
+
const full = (await api('GET', `/api/tasks/${g.id}`)).task;
|
|
228
|
+
const files = (full.changedFiles || []).length;
|
|
229
|
+
const integ = full.integrity && !full.integrity.clean ? full.integrity.findings.map((f) => `${f.text} (${f.file}: ${f.detail})`) : [];
|
|
230
|
+
const falseClaims = (full.claims || []).filter((c) => c.truth === false).map((c) => `You said "${c.text}" but that is not true: ${c.why}`);
|
|
231
|
+
if (hook) {
|
|
232
|
+
if (files === 0) hookPass();
|
|
233
|
+
if (r.proven) {
|
|
234
|
+
if (falseClaims.length && hook === 'claude' && !input.stop_hook_active) { process.stderr.write(`BuildProof: the change is proven, but correct your summary. ${falseClaims.join('. ')}.\n`); process.exit(2); }
|
|
235
|
+
hookPass();
|
|
236
|
+
}
|
|
237
|
+
hookBlock(['BuildProof: NOT PROVEN. ' + full.resultText, ...integ.map((x) => '- ' + x), ...falseClaims.map((x) => '- ' + x),
|
|
238
|
+
'Fix the real cause in the source code. Do not delete, skip or weaken tests, do not special-case test values, do not swallow errors.'].join('\n'));
|
|
239
|
+
}
|
|
240
|
+
const extra = [integ.length ? 'integrity: ' + integ.join('; ') : '', falseClaims.length ? 'claims: ' + falseClaims.join('; ') : '', full.revertCheck ? 'revert: ' + full.revertCheck.verdict : ''].filter(Boolean).join(' | ');
|
|
241
|
+
out(`${r.proven ? 'PROVEN' : 'NOT_PROVEN'} files=${files} ${steps(full.after)}${extra ? ' | ' + extra : ''} | ${full.resultText}`, r.proven ? 0 : 1);
|
|
242
|
+
}
|
|
243
|
+
if (cmd === 'accept') {
|
|
244
|
+
const r = await api('POST', `/api/guards/${g.id}/accept`, { force });
|
|
245
|
+
out(r.ok ? (r.cert ? `CERTIFICATE ${r.cert.id}${force ? ' (with warnings)' : ''}` : 'ACCEPTED (certificates are not in this plan)') : `FAIL ${r.error}`, r.ok ? 0 : 1);
|
|
246
|
+
}
|
|
247
|
+
if (cmd === 'rollback') {
|
|
248
|
+
const r = await api('POST', `/api/guards/${g.id}/rollback`, {});
|
|
249
|
+
out(r.ok ? `ROLLED_BACK restored=${r.restored.length}${r.packagesEdited ? ` packages_edited=${r.packagesEdited} (reinstall them: npm ci)` : ''}` : `FAIL ${r.error}`, r.ok ? 0 : 1);
|
|
250
|
+
}
|
|
251
|
+
}
|
|
252
|
+
|
|
253
|
+
main();
|
package/core/ai.js
ADDED
|
@@ -0,0 +1,193 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* AI worker for "BuildProof fixes it". The AI only PROPOSES full-file edits; the supervisor decides.
|
|
4
|
+
* Providers: ollama (local, default) | openai (or any OpenAI-compatible server) | anthropic | claude-code (the developer's own CLI).
|
|
5
|
+
* API keys live only in data/secrets.json on this computer, encrypted (or in env vars) - never in the config or the UI.
|
|
6
|
+
*/
|
|
7
|
+
const fs = require('fs');
|
|
8
|
+
const os = require('os');
|
|
9
|
+
const path = require('path');
|
|
10
|
+
const http = require('http');
|
|
11
|
+
const https = require('https');
|
|
12
|
+
const { spawn } = require('child_process');
|
|
13
|
+
|
|
14
|
+
const SECRETS = () => path.join(require('./config').DATA_DIR, 'secrets.json');
|
|
15
|
+
// encrypted at rest (AES-256-GCM, key protected by Windows DPAPI) - see vault.js
|
|
16
|
+
function secrets() { try { return require('./vault').readFile(SECRETS()); } catch { return {}; } }
|
|
17
|
+
function saveSecret(name, value) {
|
|
18
|
+
const s = secrets();
|
|
19
|
+
if (value) s[name] = String(value).trim(); else delete s[name];
|
|
20
|
+
require('./vault').writeFile(SECRETS(), s);
|
|
21
|
+
}
|
|
22
|
+
function keyFor(provider) {
|
|
23
|
+
if (provider === 'openai') return process.env.OPENAI_API_KEY || secrets().openaiKey || '';
|
|
24
|
+
if (provider === 'anthropic') return process.env.ANTHROPIC_API_KEY || secrets().anthropicKey || '';
|
|
25
|
+
return '';
|
|
26
|
+
}
|
|
27
|
+
const isLocalUrl = (u) => { try { return /^(localhost|127\.\d+\.\d+\.\d+|\[?::1\]?)$/i.test(new URL(u).hostname); } catch { return false; } };
|
|
28
|
+
|
|
29
|
+
/** Which AI is in use, in one place. */
|
|
30
|
+
function describe(cfg) {
|
|
31
|
+
const a = cfg.ai || {};
|
|
32
|
+
const provider = a.provider || 'ollama';
|
|
33
|
+
if (provider === 'openai') { const endpoint = a.endpoint || 'https://api.openai.com/v1'; return { provider, model: a.model || '', endpoint, local: isLocalUrl(endpoint), label: `${a.model || '(no model)'} via ${isLocalUrl(endpoint) ? 'local OpenAI-compatible server' : new URL(endpoint).hostname}` }; }
|
|
34
|
+
if (provider === 'anthropic') return { provider, model: a.model || 'claude-sonnet-5-5', endpoint: a.endpoint || 'https://api.anthropic.com', local: false, label: `${a.model || 'claude-sonnet-5-5'} (Anthropic API)` };
|
|
35
|
+
if (provider === 'claude-code') return { provider, model: a.model || '', local: false, label: `Claude Code${a.model ? ' · ' + a.model : ''}` };
|
|
36
|
+
return { provider: 'ollama', model: cfg.ollama.model, endpoint: cfg.ollama.endpoint, local: isLocalUrl(cfg.ollama.endpoint), label: cfg.ollama.model };
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function request(urlStr, body, timeoutMs, headers = {}) {
|
|
40
|
+
return new Promise((resolve) => {
|
|
41
|
+
const url = new URL(urlStr);
|
|
42
|
+
const lib = url.protocol === 'https:' ? https : http;
|
|
43
|
+
const data = body ? JSON.stringify(body) : null;
|
|
44
|
+
const req = lib.request({
|
|
45
|
+
method: body ? 'POST' : 'GET',
|
|
46
|
+
hostname: url.hostname, port: url.port, path: url.pathname + url.search,
|
|
47
|
+
headers: { ...(data ? { 'content-type': 'application/json', 'content-length': Buffer.byteLength(data) } : {}), ...headers },
|
|
48
|
+
timeout: timeoutMs,
|
|
49
|
+
}, (res) => {
|
|
50
|
+
let raw = '';
|
|
51
|
+
res.on('data', (d) => { raw += d; });
|
|
52
|
+
res.on('end', () => {
|
|
53
|
+
try { resolve({ ok: res.statusCode === 200, status: res.statusCode, json: JSON.parse(raw) }); }
|
|
54
|
+
catch { resolve({ ok: false, status: res.statusCode, raw }); }
|
|
55
|
+
});
|
|
56
|
+
});
|
|
57
|
+
req.on('timeout', () => { req.destroy(); resolve({ ok: false, error: 'timeout' }); });
|
|
58
|
+
req.on('error', (e) => resolve({ ok: false, error: e.message }));
|
|
59
|
+
if (data) req.write(data);
|
|
60
|
+
req.end();
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
function claudeBin() { const b = process.env.MGR_CLAUDE_BIN || 'claude'; return process.platform === 'win32' && /\s/.test(b) ? `"${b}"` : b; }
|
|
65
|
+
// Windows needs the shell for claude.cmd - and the shell drops empty args (--tools "") unless they are quoted
|
|
66
|
+
const WIN = process.platform === 'win32';
|
|
67
|
+
const winArgs = (args) => (WIN ? args.map((a) => (a === '' ? '""' : /[\s"&|<>^]/.test(a) ? '"' + a.replace(/"/g, '\\"') + '"' : a)) : args);
|
|
68
|
+
|
|
69
|
+
async function health(cfg) {
|
|
70
|
+
const d = describe(cfg);
|
|
71
|
+
if (d.provider === 'openai') {
|
|
72
|
+
if (!d.model) return { ok: false, model: d.label, reason: 'no_model_set' };
|
|
73
|
+
if (!keyFor('openai') && !d.local) return { ok: false, model: d.label, reason: 'no_api_key' };
|
|
74
|
+
return { ok: true, model: d.label, provider: d.provider };
|
|
75
|
+
}
|
|
76
|
+
if (d.provider === 'anthropic') return keyFor('anthropic') ? { ok: true, model: d.label, provider: d.provider } : { ok: false, model: d.label, reason: 'no_api_key' };
|
|
77
|
+
if (d.provider === 'claude-code') {
|
|
78
|
+
const ok = await new Promise((resolve) => { try { const c = spawn(claudeBin(), ['--version'], { windowsHide: true, shell: process.platform === 'win32' }); c.on('error', () => resolve(false)); c.on('close', (code) => resolve(code === 0)); } catch { resolve(false); } });
|
|
79
|
+
return ok ? { ok: true, model: d.label, provider: d.provider } : { ok: false, model: d.label, reason: 'claude_not_installed' };
|
|
80
|
+
}
|
|
81
|
+
const r = await request(`${cfg.ollama.endpoint}/api/tags`, null, 4000);
|
|
82
|
+
if (!r.ok) return { ok: false, reason: r.error || `http_${r.status}` };
|
|
83
|
+
const models = (r.json.models || []).map((m) => m.name);
|
|
84
|
+
return { ok: models.includes(cfg.ollama.model), models, model: cfg.ollama.model, reason: models.includes(cfg.ollama.model) ? null : 'model_not_installed' };
|
|
85
|
+
}
|
|
86
|
+
|
|
87
|
+
function buildPrompt({ instruction, files, context, failure, attempt }) {
|
|
88
|
+
const fileBlocks = files.map((f) => `### FILE: ${f.path}\n${f.content == null ? '(new file - does not exist yet)' : f.content}`).join('\n\n');
|
|
89
|
+
const ctxBlocks = (context || []).map((f) => `### READ-ONLY TEST: ${f.path}\n${f.content}`).join('\n\n');
|
|
90
|
+
return [
|
|
91
|
+
'You are a careful senior software engineer. Make the SMALLEST correct change.',
|
|
92
|
+
'Rules:',
|
|
93
|
+
'- You may ONLY edit the files listed below. Never invent other files.',
|
|
94
|
+
'- Return the COMPLETE new content of each file you change (not a diff).',
|
|
95
|
+
'- Do not change behavior that was not requested. Do not delete or weaken tests.',
|
|
96
|
+
'- Tests are CORRECT. Never say a test is wrong; fix the code. Never special-case test values.',
|
|
97
|
+
'- If the task is impossible with these files, return no edits and explain in "summary".',
|
|
98
|
+
'Respond with JSON only: {"summary": "<one short sentence>", "edits": [{"path": "<file>", "content": "<full new content>"}]}',
|
|
99
|
+
'',
|
|
100
|
+
`TASK: ${instruction}`,
|
|
101
|
+
failure ? `\nCURRENT FAILURE (attempt ${attempt}) - fix this:\n${failure.slice(-6000)}` : '',
|
|
102
|
+
ctxBlocks ? '\nThe tests below are READ-ONLY. Use them to see the expected behavior and the exact names they use. Never edit them.\n\n' + ctxBlocks : '',
|
|
103
|
+
'\nFILES YOU MAY EDIT:\n',
|
|
104
|
+
fileBlocks,
|
|
105
|
+
].join('\n');
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/** Pull the JSON answer out of a model reply (it may wrap it in text or ``` fences). */
|
|
109
|
+
function parseAnswer(text) {
|
|
110
|
+
const t = String(text || '');
|
|
111
|
+
try { return JSON.parse(t); } catch { /* look inside */ }
|
|
112
|
+
const a = t.indexOf('{'); const b = t.lastIndexOf('}');
|
|
113
|
+
if (a >= 0 && b > a) { try { return JSON.parse(t.slice(a, b + 1)); } catch { /* invalid */ } }
|
|
114
|
+
return null;
|
|
115
|
+
}
|
|
116
|
+
function result(parsed, tokens, ms) {
|
|
117
|
+
if (!parsed) return { ok: false, error: 'invalid_json_from_model' };
|
|
118
|
+
const edits = Array.isArray(parsed.edits) ? parsed.edits.filter((e) => e && typeof e.path === 'string' && typeof e.content === 'string') : [];
|
|
119
|
+
return { ok: true, summary: String(parsed.summary || '').slice(0, 500), edits, tokens: tokens || { prompt: 0, output: 0 }, ms: ms || 0 };
|
|
120
|
+
}
|
|
121
|
+
const temperature = (input) => [0.1, 0.5, 0.8][Math.min((input.attempt || 1) - 1, 2)];
|
|
122
|
+
|
|
123
|
+
async function proposeOpenAI(cfg, d, prompt, input) {
|
|
124
|
+
const t0 = Date.now();
|
|
125
|
+
const r = await request(`${d.endpoint.replace(/\/$/, '')}/chat/completions`, { model: d.model, temperature: temperature(input), response_format: { type: 'json_object' }, messages: [{ role: 'user', content: prompt }] }, cfg.ollama.timeoutMs, keyFor('openai') ? { authorization: `Bearer ${keyFor('openai')}` } : {});
|
|
126
|
+
if (!r.ok) return { ok: false, error: r.error || `http_${r.status}${r.json && r.json.error ? ': ' + (r.json.error.message || '').slice(0, 120) : ''}` };
|
|
127
|
+
const msg = r.json.choices && r.json.choices[0] && r.json.choices[0].message;
|
|
128
|
+
const u = r.json.usage || {};
|
|
129
|
+
return result(parseAnswer(msg && msg.content), { prompt: u.prompt_tokens || 0, output: u.completion_tokens || 0 }, Date.now() - t0);
|
|
130
|
+
}
|
|
131
|
+
|
|
132
|
+
async function proposeAnthropic(cfg, d, prompt, input) {
|
|
133
|
+
const t0 = Date.now();
|
|
134
|
+
const r = await request(`${d.endpoint.replace(/\/$/, '')}/v1/messages`, { model: d.model, max_tokens: 16000, temperature: temperature(input), messages: [{ role: 'user', content: prompt }] }, cfg.ollama.timeoutMs, { 'x-api-key': keyFor('anthropic'), 'anthropic-version': '2023-06-01' });
|
|
135
|
+
if (!r.ok) return { ok: false, error: r.error || `http_${r.status}${r.json && r.json.error ? ': ' + (r.json.error.message || '').slice(0, 120) : ''}` };
|
|
136
|
+
const text = (r.json.content || []).filter((c) => c.type === 'text').map((c) => c.text).join('');
|
|
137
|
+
const u = r.json.usage || {};
|
|
138
|
+
return result(parseAnswer(text), { prompt: u.input_tokens || 0, output: u.output_tokens || 0 }, Date.now() - t0);
|
|
139
|
+
}
|
|
140
|
+
|
|
141
|
+
/** The developer's own Claude Code, with every tool switched off: it can only answer, never touch files. */
|
|
142
|
+
function proposeClaudeCode(cfg, d, prompt) {
|
|
143
|
+
const t0 = Date.now();
|
|
144
|
+
return new Promise((resolve) => {
|
|
145
|
+
const cwd = fs.mkdtempSync(path.join(os.tmpdir(), 'bp-claude-'));
|
|
146
|
+
const args = ['-p', '--output-format', 'json', '--tools', ''];
|
|
147
|
+
if (d.model) args.push('--model', d.model);
|
|
148
|
+
let out = ''; let err = '';
|
|
149
|
+
let child;
|
|
150
|
+
try { child = spawn(claudeBin(), winArgs(args), { cwd, windowsHide: true, shell: process.platform === 'win32' }); } catch (e) { resolve({ ok: false, error: e.message }); return; }
|
|
151
|
+
const timer = setTimeout(() => { try { child.kill(); } catch { /* gone */ } }, cfg.ollama.timeoutMs);
|
|
152
|
+
child.stdout.on('data', (x) => { out += x; });
|
|
153
|
+
child.stderr.on('data', (x) => { err += x; });
|
|
154
|
+
child.on('error', (e) => { clearTimeout(timer); resolve({ ok: false, error: e.message }); });
|
|
155
|
+
child.on('close', (code) => {
|
|
156
|
+
clearTimeout(timer);
|
|
157
|
+
try { fs.rmSync(cwd, { recursive: true, force: true }); } catch { /* temp */ }
|
|
158
|
+
if (code !== 0) { resolve({ ok: false, error: `claude exited ${code}: ${err.slice(-200)}` }); return; }
|
|
159
|
+
let text = out; let usage = {};
|
|
160
|
+
try { const j = JSON.parse(out); text = j.result || ''; usage = j.usage || {}; } catch { /* plain text */ }
|
|
161
|
+
resolve(result(parseAnswer(text), { prompt: usage.input_tokens || 0, output: usage.output_tokens || 0 }, Date.now() - t0));
|
|
162
|
+
});
|
|
163
|
+
child.stdin.end(prompt);
|
|
164
|
+
});
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
async function proposeEdits(cfg, input) {
|
|
168
|
+
const prompt = buildPrompt(input);
|
|
169
|
+
const d = describe(cfg);
|
|
170
|
+
if (d.provider === 'openai') return proposeOpenAI(cfg, d, prompt, input);
|
|
171
|
+
if (d.provider === 'anthropic') return proposeAnthropic(cfg, d, prompt, input);
|
|
172
|
+
if (d.provider === 'claude-code') return proposeClaudeCode(cfg, d, prompt);
|
|
173
|
+
const r = await request(`${cfg.ollama.endpoint}/api/generate`, {
|
|
174
|
+
model: cfg.ollama.model,
|
|
175
|
+
prompt,
|
|
176
|
+
stream: false,
|
|
177
|
+
format: 'json',
|
|
178
|
+
options: { temperature: [0.1, 0.5, 0.8][Math.min((input.attempt || 1) - 1, 2)], num_ctx: 16384 },
|
|
179
|
+
}, cfg.ollama.timeoutMs);
|
|
180
|
+
if (!r.ok) return { ok: false, error: r.error || `http_${r.status}` };
|
|
181
|
+
let parsed;
|
|
182
|
+
try { parsed = JSON.parse(r.json.response || '{}'); } catch { return { ok: false, error: 'invalid_json_from_model', raw: String(r.json.response || '').slice(0, 500) }; }
|
|
183
|
+
const edits = Array.isArray(parsed.edits) ? parsed.edits.filter((e) => e && typeof e.path === 'string' && typeof e.content === 'string') : [];
|
|
184
|
+
return {
|
|
185
|
+
ok: true,
|
|
186
|
+
summary: String(parsed.summary || '').slice(0, 500),
|
|
187
|
+
edits,
|
|
188
|
+
tokens: { prompt: r.json.prompt_eval_count || 0, output: r.json.eval_count || 0 },
|
|
189
|
+
ms: Math.round((r.json.total_duration || 0) / 1e6),
|
|
190
|
+
};
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
module.exports = { health, proposeEdits, buildPrompt, request, describe, saveSecret, secrets, parseAnswer };
|
package/core/av-scan.js
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* Antivirus scan (ClamAV) of the files the AI changed since guard start.
|
|
4
|
+
* scan(root, files) -> { engine, status, hits:[{file, sig}], scanned, detail }
|
|
5
|
+
* status: 'clean' | 'infected' | 'not_installed' | 'error'
|
|
6
|
+
* Engine: env MGR_CLAMSCAN_BIN, else clamscan on PATH, else the default Windows install folder.
|
|
7
|
+
* Never throws. Missing ClamAV = 'not_installed' (the check goes on). Only 'infected' blocks approval.
|
|
8
|
+
*/
|
|
9
|
+
const fs = require('fs'), path = require('path'), { spawnSync } = require('child_process');
|
|
10
|
+
const IS_WIN = process.platform === 'win32';
|
|
11
|
+
const MAX_FILES = 500;
|
|
12
|
+
|
|
13
|
+
function onPath(name) {
|
|
14
|
+
const exts = IS_WIN ? ['.exe', '.cmd', '.bat', ''] : [''];
|
|
15
|
+
for (const d of String(process.env.PATH || '').split(path.delimiter)) {
|
|
16
|
+
if (!d) continue;
|
|
17
|
+
for (const e of exts) { const f = path.join(d, name + e); try { if (fs.statSync(f).isFile()) return f; } catch { /* next */ } }
|
|
18
|
+
}
|
|
19
|
+
return null;
|
|
20
|
+
}
|
|
21
|
+
|
|
22
|
+
function engine() {
|
|
23
|
+
if (process.env.MGR_CLAMSCAN_BIN !== undefined) {
|
|
24
|
+
const b = process.env.MGR_CLAMSCAN_BIN;
|
|
25
|
+
return b && fs.existsSync(b) ? b : null; // set but empty / missing = "not installed" (used by tests)
|
|
26
|
+
}
|
|
27
|
+
const found = onPath('clamscan'); // clamdscan needs a running clamd - only used when set in MGR_CLAMSCAN_BIN
|
|
28
|
+
if (found) return found;
|
|
29
|
+
if (IS_WIN) for (const f of ['C:\\Program Files\\ClamAV\\clamscan.exe', 'C:\\Program Files (x86)\\ClamAV\\clamscan.exe']) if (fs.existsSync(f)) return f;
|
|
30
|
+
return null;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function run(bin, args) {
|
|
34
|
+
// a .js engine (used by tests) runs with this node
|
|
35
|
+
const [cmd, a] = /\.js$/i.test(bin) ? [process.execPath, [bin, ...args]] : [bin, args];
|
|
36
|
+
return spawnSync(cmd, a, { encoding: 'utf8', windowsHide: true, timeout: 5 * 60e3, maxBuffer: 16 * 1024 * 1024 });
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
function scan(root, files) {
|
|
40
|
+
const bin = engine();
|
|
41
|
+
if (!bin) return { engine: null, status: 'not_installed', hits: [], scanned: 0, detail: 'ClamAV not found' };
|
|
42
|
+
const base = path.resolve(root);
|
|
43
|
+
const abs = [];
|
|
44
|
+
for (const f of files || []) {
|
|
45
|
+
const p = path.resolve(base, f);
|
|
46
|
+
if (!p.startsWith(base + path.sep)) continue; // never outside the project
|
|
47
|
+
try { if (fs.lstatSync(p).isFile()) abs.push(p); } catch { /* deleted */ }
|
|
48
|
+
}
|
|
49
|
+
if (!abs.length) return { engine: bin, status: 'clean', hits: [], scanned: 0, detail: 'no files to scan' };
|
|
50
|
+
const hits = []; let scanned = 0;
|
|
51
|
+
for (let i = 0; i < Math.min(abs.length, MAX_FILES); i += 50) {
|
|
52
|
+
const batch = abs.slice(i, i + 50);
|
|
53
|
+
const r = run(bin, ['--no-summary', '--infected', ...batch]);
|
|
54
|
+
if (r.error) return { engine: bin, status: 'error', hits, scanned, detail: r.error.message };
|
|
55
|
+
// clamscan: 0 = clean, 1 = virus found, 2 = error
|
|
56
|
+
for (const line of String(r.stdout || '').split(/\r?\n/)) {
|
|
57
|
+
const m = line.match(/^(.*): (.+) FOUND$/);
|
|
58
|
+
if (m) hits.push({ file: path.relative(base, path.resolve(m[1].trim())).split(path.sep).join('/'), sig: m[2].trim() });
|
|
59
|
+
}
|
|
60
|
+
if (r.status === 2 || (r.status === 1 && !hits.length) || r.status === null) return { engine: bin, status: 'error', hits, scanned, detail: String(r.stderr || '').trim().slice(0, 300) || `exit ${r.status}` };
|
|
61
|
+
scanned += batch.length;
|
|
62
|
+
}
|
|
63
|
+
return { engine: bin, status: hits.length ? 'infected' : 'clean', hits, scanned, detail: abs.length > MAX_FILES ? `only first ${MAX_FILES} files scanned` : '' };
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
module.exports = { scan, engine };
|
|
@@ -0,0 +1,4 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
// the hidden bug hunt runs on the BuildProof server (isolated sandbox, signed results); it is not shipped
|
|
3
|
+
const msg='the hidden bug hunt runs on the BuildProof server';
|
|
4
|
+
module.exports={hunt:async()=>({error:msg,findings:[],regressions:[],stats:{}}),repro:async()=>({reproduced:false,outcome:msg})};
|