buildproof 0.0.0-stage → 3.8.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/LICENSE.txt +2 -0
- package/README.md +25 -2
- package/bin/buildproof.js +267 -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/ci.js +254 -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
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* Secrets the AI may have written into the project.
|
|
4
|
+
* scan(root, files): only the given files (the files changed since guard start) - a key that was already in the
|
|
5
|
+
* project before the AI started is not the AI's doing and must not block the change forever.
|
|
6
|
+
* scan(root) without files walks the whole project (used by audits).
|
|
7
|
+
* Never throws: an unreadable file is skipped and reported in `skipped`.
|
|
8
|
+
*/
|
|
9
|
+
const fs = require('fs'), path = require('path');
|
|
10
|
+
const RULES = [
|
|
11
|
+
[/-----BEGIN (?:RSA |EC |DSA |OPENSSH )?PRIVATE KEY-----/, 'private_key'],
|
|
12
|
+
[/\bghp_[A-Za-z0-9]{30,}\b|\bgithub_pat_[A-Za-z0-9_]{40,}\b/, 'github_token'],
|
|
13
|
+
[/\bsk_live_[A-Za-z0-9]{16,}\b/, 'payment_key'],
|
|
14
|
+
[/\bAKIA[0-9A-Z]{16}\b/, 'aws_access_key'],
|
|
15
|
+
[/\bsk-ant-[A-Za-z0-9_-]{20,}\b/, 'anthropic_key'],
|
|
16
|
+
[/\bsk-(?:proj-)?[A-Za-z0-9_-]{32,}\b/, 'openai_key'],
|
|
17
|
+
[/\bxox[abpors]-[A-Za-z0-9-]{20,}\b/, 'slack_token'],
|
|
18
|
+
[/-----BEGIN (?:ENCRYPTED |PGP )?PRIVATE KEY(?: BLOCK)?-----/, 'private_key'],
|
|
19
|
+
[/\bgh[ousr]_[A-Za-z0-9]{36,}\b/, 'github_token'],
|
|
20
|
+
[/\bglpat-[A-Za-z0-9_-]{20,}\b/, 'gitlab_token'],
|
|
21
|
+
[/\bnpm_[A-Za-z0-9]{36}\b/, 'npm_token'],
|
|
22
|
+
[/\b[rs]k_live_[A-Za-z0-9]{16,}\b/, 'payment_key'],
|
|
23
|
+
[/\bAIza[0-9A-Za-z_-]{35}\b/, 'google_api_key'],
|
|
24
|
+
[/\bSG\.[A-Za-z0-9_-]{22}\.[A-Za-z0-9_-]{43}\b/, 'sendgrid_key'],
|
|
25
|
+
[/\bSK[0-9a-f]{32}\b/, 'twilio_key'],
|
|
26
|
+
[/https:\/\/hooks\.slack\.com\/services\/T[A-Z0-9]+\/B[A-Z0-9]+\/[A-Za-z0-9]{20,}/, 'slack_webhook'],
|
|
27
|
+
[/\bBP1\.[A-Za-z0-9_-]{40,}\.[A-Za-z0-9_-]{40,}\b/, 'buildproof_license_key'],
|
|
28
|
+
];
|
|
29
|
+
const SKIP_DIRS = new Set(['node_modules', '.git', 'backups', '.next', 'dist', 'build', 'coverage']);
|
|
30
|
+
const MAX_BYTES = 1e6;
|
|
31
|
+
function scanFile(abs, rel, hits, skipped) {
|
|
32
|
+
let st; try { st = fs.lstatSync(abs); } catch { return; }
|
|
33
|
+
if (!st.isFile() || st.size > MAX_BYTES) return;
|
|
34
|
+
let s; try { s = fs.readFileSync(abs); } catch (e) { skipped.push(rel); return; }
|
|
35
|
+
if (s.includes(0)) return; // binary
|
|
36
|
+
const text = s.toString('utf8');
|
|
37
|
+
const seen = new Set();
|
|
38
|
+
for (const [re, type] of RULES) {
|
|
39
|
+
const m = re.exec(text);
|
|
40
|
+
if (!m) continue;
|
|
41
|
+
const line = text.slice(0, m.index).split('\n').length;
|
|
42
|
+
if (seen.has(type + ':' + line)) continue; seen.add(type + ':' + line);
|
|
43
|
+
hits.push({ file: rel.split(path.sep).join('/'), type, line });
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
function scan(root, files) {
|
|
47
|
+
const hits = [], skipped = [];
|
|
48
|
+
if (Array.isArray(files)) {
|
|
49
|
+
for (const f of files) {
|
|
50
|
+
const abs = path.resolve(root, f);
|
|
51
|
+
if (!abs.startsWith(path.resolve(root) + path.sep)) continue; // never outside the project
|
|
52
|
+
scanFile(abs, f, hits, skipped);
|
|
53
|
+
}
|
|
54
|
+
} else {
|
|
55
|
+
const walk = (dir) => {
|
|
56
|
+
let list; try { list = fs.readdirSync(dir, { withFileTypes: true }); } catch { skipped.push(path.relative(root, dir)); return; }
|
|
57
|
+
for (const e of list) {
|
|
58
|
+
if (SKIP_DIRS.has(e.name)) continue;
|
|
59
|
+
const abs = path.join(dir, e.name);
|
|
60
|
+
if (e.isDirectory()) walk(abs); else if (e.isFile()) scanFile(abs, path.relative(root, abs), hits, skipped);
|
|
61
|
+
}
|
|
62
|
+
};
|
|
63
|
+
walk(root);
|
|
64
|
+
}
|
|
65
|
+
hits.skipped = skipped;
|
|
66
|
+
return hits;
|
|
67
|
+
}
|
|
68
|
+
module.exports = { scan, RULES };
|
package/core/server.js
ADDED
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/** BuildProof core service: REST API + web app (phone / tablet / PC). Zero dependencies. */
|
|
3
|
+
const http = require('http');
|
|
4
|
+
const crypto = require('crypto');
|
|
5
|
+
const fs = require('fs');
|
|
6
|
+
const path = require('path');
|
|
7
|
+
const os = require('os');
|
|
8
|
+
const config = require('./config');
|
|
9
|
+
const store = require('./store');
|
|
10
|
+
const projects = require('./projects');
|
|
11
|
+
const flow = require('./flow');
|
|
12
|
+
const ai = require('./ai');
|
|
13
|
+
const certs = require('./certs');
|
|
14
|
+
const hooks = require('./hooks');
|
|
15
|
+
const license = require('./license');
|
|
16
|
+
|
|
17
|
+
const cfg = config.load();
|
|
18
|
+
const WEB_DIR = path.join(config.ROOT, 'web');
|
|
19
|
+
const VERSION = require('../package.json').version;
|
|
20
|
+
const startedAt = Date.now();
|
|
21
|
+
|
|
22
|
+
function send(res, code, body, headers = {}) {
|
|
23
|
+
const isObj = typeof body === 'object' && !Buffer.isBuffer(body);
|
|
24
|
+
res.writeHead(code, { 'content-type': isObj ? 'application/json; charset=utf-8' : 'text/plain; charset=utf-8', 'cache-control': 'no-store', ...headers });
|
|
25
|
+
res.end(isObj ? JSON.stringify(body) : body);
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
function readBody(req) {
|
|
29
|
+
return new Promise((resolve) => {
|
|
30
|
+
let raw = '';
|
|
31
|
+
req.on('data', (d) => { raw += d; if (raw.length > 1e6) req.destroy(); });
|
|
32
|
+
req.on('end', () => { try { resolve(raw ? JSON.parse(raw) : {}); } catch { resolve({}); } });
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
function authed(req, url) {
|
|
37
|
+
const h = req.headers.authorization || '';
|
|
38
|
+
const tok = String(h.startsWith('Bearer ') ? h.slice(7) : url.searchParams.get('token') || '');
|
|
39
|
+
const a = crypto.createHash('sha256').update(tok).digest();
|
|
40
|
+
const b = crypto.createHash('sha256').update(String(cfg.token)).digest();
|
|
41
|
+
return tok.length > 0 && crypto.timingSafeEqual(a, b); // constant time
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
/* ---- browser attacks on a local server ----
|
|
45
|
+
* DNS rebinding: a web page on evil.com re-points its name to 127.0.0.1 and reads this server.
|
|
46
|
+
* Defence: only answer requests addressed to an IP, localhost, a Tailscale name or a name you allowed. */
|
|
47
|
+
function hostOk(hostHeader) {
|
|
48
|
+
const hn = String(hostHeader || '').toLowerCase().replace(/:\d+$/, '').replace(/^\[|\]$/g, '');
|
|
49
|
+
if (!hn) return false;
|
|
50
|
+
if (hn === 'localhost' || /^\d{1,3}(\.\d{1,3}){3}$/.test(hn) || hn.includes(':')) return true; // IP literal / IPv6
|
|
51
|
+
if (/\.ts\.net$/.test(hn)) return true; // Tailscale HTTPS name
|
|
52
|
+
return (cfg.allowedHosts || []).map((x) => String(x).toLowerCase()).includes(hn);
|
|
53
|
+
}
|
|
54
|
+
// a write from another web site (cross-site request) is refused even before the token check
|
|
55
|
+
function originOk(req) {
|
|
56
|
+
const o = req.headers.origin;
|
|
57
|
+
if (!o || o === 'null') return !o; // "null" origin = sandboxed frame / file - refuse
|
|
58
|
+
try { const u = new URL(o); return hostOk(u.host) && u.host.replace(/^\[|\]$/g, '') === String(req.headers.host || '').replace(/^\[|\]$/g, ''); } catch { return false; }
|
|
59
|
+
}
|
|
60
|
+
const failures = new Map(); // wrong-token attempts per address
|
|
61
|
+
function tooManyFailures(ip) { const now = Date.now(); const l = (failures.get(ip) || []).filter((t) => now - t < 600000); failures.set(ip, l); return l.length >= 30; }
|
|
62
|
+
function noteFailure(ip) { const l = failures.get(ip) || []; l.push(Date.now()); failures.set(ip, l); }
|
|
63
|
+
const SEC_HEADERS = {
|
|
64
|
+
'x-content-type-options': 'nosniff', 'x-frame-options': 'DENY', 'referrer-policy': 'no-referrer', 'cross-origin-opener-policy': 'same-origin',
|
|
65
|
+
'content-security-policy': "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdnjs.cloudflare.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; font-src 'self' data: https://fonts.gstatic.com; img-src 'self' data: blob:; media-src 'self' blob:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'self'",
|
|
66
|
+
'permissions-policy': 'camera=(self), microphone=(), geolocation=()',
|
|
67
|
+
};
|
|
68
|
+
|
|
69
|
+
function lanAddresses() {
|
|
70
|
+
const out = [];
|
|
71
|
+
for (const list of Object.values(os.networkInterfaces())) {
|
|
72
|
+
for (const a of list || []) if (a.family === 'IPv4' && !a.internal) out.push(a.address);
|
|
73
|
+
}
|
|
74
|
+
return out;
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
/** Tailscale HTTPS (tailscale serve -> this port): the camera / share / signature check need HTTPS on phones. */
|
|
78
|
+
let tsCache = { at: 0, url: null };
|
|
79
|
+
function tailscaleHttps() {
|
|
80
|
+
if (Date.now() - tsCache.at < 60000) return tsCache.url;
|
|
81
|
+
tsCache = { at: Date.now(), url: null };
|
|
82
|
+
const { spawnSync } = require('child_process');
|
|
83
|
+
for (const exe of process.platform === 'win32' ? ['C:\\Program Files\\Tailscale\\tailscale.exe', 'tailscale'] : ['tailscale', '/Applications/Tailscale.app/Contents/MacOS/Tailscale']) {
|
|
84
|
+
try {
|
|
85
|
+
const st = spawnSync(exe, ['status', '--json'], { encoding: 'utf8', windowsHide: true, timeout: 5000 });
|
|
86
|
+
if (st.status !== 0) continue;
|
|
87
|
+
const dns = String((JSON.parse(st.stdout).Self || {}).DNSName || '').replace(/\.$/, '');
|
|
88
|
+
const sv = spawnSync(exe, ['serve', 'status', '--json'], { encoding: 'utf8', windowsHide: true, timeout: 5000 });
|
|
89
|
+
if (dns && sv.status === 0 && sv.stdout.includes(`:${cfg.port}`)) tsCache.url = `https://${dns}`;
|
|
90
|
+
break;
|
|
91
|
+
} catch { /* next */ }
|
|
92
|
+
}
|
|
93
|
+
return tsCache.url;
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/** True only for a request made on this computer (not through tailscale serve or another proxy). */
|
|
97
|
+
function isLocal(req) {
|
|
98
|
+
const ra = req.socket.remoteAddress || '';
|
|
99
|
+
return /^(::1|127\.0\.0\.1|::ffff:127\.0\.0\.1)$/.test(ra) && !req.headers['x-forwarded-for'] && !req.headers['tailscale-user-login'];
|
|
100
|
+
}
|
|
101
|
+
|
|
102
|
+
function publicTask(t, full) {
|
|
103
|
+
if (!t) return null;
|
|
104
|
+
if (full) return t;
|
|
105
|
+
const { log, baseline, after, diffs, changedFiles, integrity, ...rest } = t;
|
|
106
|
+
return { ...rest, files: (changedFiles || []).length, integrityClean: integrity ? integrity.clean : null, integrityFindings: integrity ? integrity.findings.length : 0, lastLog: (log || []).slice(-1)[0] || null };
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
function stats() {
|
|
110
|
+
const since = new Date(Date.now() - 30 * 864e5).toISOString();
|
|
111
|
+
const rows = store.list('tasks', (t) => (t.createdAt || '') >= since);
|
|
112
|
+
const sum = (f) => rows.reduce((n, t) => n + (f(t) || 0), 0);
|
|
113
|
+
return {
|
|
114
|
+
days: 30,
|
|
115
|
+
proven: rows.filter((t) => t.state === 'done' && t.certId && !t.acceptedWithWarnings).length,
|
|
116
|
+
cheatsBlocked: sum((t) => t.cheatsBlocked),
|
|
117
|
+
rolledBack: rows.filter((t) => t.state === 'rolled_back').length,
|
|
118
|
+
aiCallsSaved: rows.filter((t) => t.state === 'done' && t.plan && ['learned', 'library'].includes(t.plan.kind)).length,
|
|
119
|
+
aiCalls: sum((t) => t.aiCalls),
|
|
120
|
+
bytesSentOff: sum((t) => t.bytesSentOff),
|
|
121
|
+
needsYou: rows.filter((t) => t.state === 'awaiting_approval' || (t.kind === 'guard' && t.state === 'watching')).length,
|
|
122
|
+
certificates: store.list('certs', (c) => (c.issuedAt || '') >= since).length,
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const IS_WIN = process.platform === 'win32';
|
|
127
|
+
function listDirs(p) {
|
|
128
|
+
if (!p) {
|
|
129
|
+
const roots = IS_WIN ? 'CDEFGHIJKLMNOPQRSTUVWXYZ'.split('').map((d) => `${d}:\\`).filter((d) => { try { return fs.existsSync(d); } catch { return false; } }) : ['/', os.homedir()];
|
|
130
|
+
return { ok: true, path: '', parent: null, dirs: roots.map((r) => ({ name: r, path: r, isProject: false })) };
|
|
131
|
+
}
|
|
132
|
+
const abs = path.resolve(p);
|
|
133
|
+
let entries = [];
|
|
134
|
+
try { entries = fs.readdirSync(abs, { withFileTypes: true }); } catch (e) { return { ok: false, error: 'cannot_read', path: abs }; }
|
|
135
|
+
const dirs = entries.filter((e) => e.isDirectory() && !e.name.startsWith('.') && !/^(node_modules|\$RECYCLE\.BIN|System Volume Information|Windows|ProgramData)$/i.test(e.name))
|
|
136
|
+
.slice(0, 500).map((e) => { const full = path.join(abs, e.name); return { name: e.name, path: full, isProject: fs.existsSync(path.join(full, 'package.json')) }; })
|
|
137
|
+
.sort((a, b) => (b.isProject - a.isProject) || a.name.localeCompare(b.name));
|
|
138
|
+
const parent = path.dirname(abs) === abs ? '' : path.dirname(abs);
|
|
139
|
+
return { ok: true, path: abs, parent, isProject: fs.existsSync(path.join(abs, 'package.json')), dirs };
|
|
140
|
+
}
|
|
141
|
+
|
|
142
|
+
const MIME = { '.html': 'text/html; charset=utf-8', '.js': 'text/javascript; charset=utf-8', '.css': 'text/css; charset=utf-8', '.json': 'application/json', '.png': 'image/png', '.svg': 'image/svg+xml', '.webmanifest': 'application/manifest+json' };
|
|
143
|
+
|
|
144
|
+
function serveStatic(res, pathname) {
|
|
145
|
+
const rel = pathname === '/' ? 'index.html' : pathname.replace(/^\/+/, '');
|
|
146
|
+
let abs = path.join(WEB_DIR, rel);
|
|
147
|
+
if (rel === 'html2canvas.min.js' && !fs.existsSync(abs)) { try { abs = require.resolve('html2canvas/dist/html2canvas.min.js'); } catch { /* CDN fallback in the page */ } }
|
|
148
|
+
else if (!abs.startsWith(WEB_DIR)) return send(res, 404, 'not found');
|
|
149
|
+
if (!fs.existsSync(abs) || fs.statSync(abs).isDirectory()) return send(res, 404, 'not found');
|
|
150
|
+
res.writeHead(200, { 'content-type': MIME[path.extname(abs)] || 'application/octet-stream', 'cache-control': 'no-cache' });
|
|
151
|
+
fs.createReadStream(abs).pipe(res);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
const server = http.createServer(async (req, res) => {
|
|
155
|
+
const url = new URL(req.url, 'http://x');
|
|
156
|
+
const p = url.pathname;
|
|
157
|
+
for (const [k, v] of Object.entries(SEC_HEADERS)) res.setHeader(k, v);
|
|
158
|
+
if (!hostOk(req.headers.host)) return send(res, 421, { ok: false, error: 'unknown_host' });
|
|
159
|
+
if (req.method !== 'GET' && req.method !== 'HEAD' && !originOk(req)) return send(res, 403, { ok: false, error: 'cross_site_request' });
|
|
160
|
+
try {
|
|
161
|
+
if (p === '/healthz' || p === '/api/health') return send(res, 200, { ok: true, version: VERSION, pid: process.pid, uptimeSec: Math.round((Date.now() - startedAt) / 1000) });
|
|
162
|
+
if (p === '/connect') {
|
|
163
|
+
if (!isLocal(req)) return send(res, 403, 'only from this computer');
|
|
164
|
+
if (req.headers['sec-fetch-site'] === 'cross-site' && req.headers['sec-fetch-mode'] !== 'navigate') return send(res, 403, 'open it directly in the browser'); // another site may link here, never read it
|
|
165
|
+
// One code only: HTTPS through Tailscale when available (camera share works), else Tailscale IP, else home network.
|
|
166
|
+
const addrs = lanAddresses();
|
|
167
|
+
const ts = addrs.find((a) => { const [x, y] = a.split('.').map(Number); return x === 100 && y >= 64 && y <= 127; });
|
|
168
|
+
const best = ts || addrs.find((a) => /^(10\.|192\.168\.|172\.(1[6-9]|2\d|3[01])\.)/.test(a)) || addrs[0] || '127.0.0.1';
|
|
169
|
+
const https = tailscaleHttps();
|
|
170
|
+
const links = [`${https || `http://${best}:${cfg.port}`}/?token=${encodeURIComponent(cfg.token)}`];
|
|
171
|
+
const html = `<!doctype html><html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width,initial-scale=1"><title>Connect a device - BuildProof</title><link rel="icon" href="favicon-32.png">
|
|
172
|
+
<style>*{forced-color-adjust:none;box-sizing:border-box}body{font:500 22px/1.5 "Segoe UI",system-ui,sans-serif;background:#fff;color:#0A0A0A;margin:0;padding:24px}h1{font-size:34px;margin:0 0 8px}.top{display:flex;gap:16px;align-items:center}.top img{width:64px;height:64px;border-radius:14px}.q{display:inline-block;margin:20px 20px 0 0;padding:16px;background:#fff;border:1px solid #E6E6E6;border-radius:16px}.q p{color:#000;font-size:15px;margin:8px 0 0;word-break:break-all}a{color:#1D4ED8}.ok{color:#12803F;font-weight:700}.warn{color:#B26A00;font-weight:700}</style>
|
|
173
|
+
<script src="https://cdnjs.cloudflare.com/ajax/libs/qrcodejs/1.0.0/qrcode.min.js"></script></head><body>
|
|
174
|
+
<div class="top"><img src="icon-192.png" alt=""><h1>Connect a phone or tablet</h1></div>
|
|
175
|
+
<p>Scan this code with the phone or tablet camera, then use Share, Add to Home Screen.</p>
|
|
176
|
+
<p class="${https ? 'ok' : 'warn'}">${https ? 'Secure HTTPS link - camera sharing works.' : 'Plain http link - for camera sharing turn on HTTPS: tailscale serve --bg ' + cfg.port}</p>
|
|
177
|
+
${links.map((l, i) => `<div class="q"><div id="q${i}"></div><p>${l.replace(/token=.*/, 'token=...')}</p></div>`).join('')}
|
|
178
|
+
<p><a href="/?token=${encodeURIComponent(cfg.token)}">Open BuildProof on this computer</a></p>
|
|
179
|
+
<script>const L=${JSON.stringify(links)};L.forEach((l,i)=>{try{new QRCode(document.getElementById('q'+i),{text:l,width:280,height:280})}catch(e){document.getElementById('q'+i).textContent='QR code needs internet to load.'}});</script></body></html>`;
|
|
180
|
+
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store' });
|
|
181
|
+
return res.end(html);
|
|
182
|
+
}
|
|
183
|
+
if (!p.startsWith('/api/')) return serveStatic(res, p);
|
|
184
|
+
const ip = req.socket.remoteAddress || '';
|
|
185
|
+
if (tooManyFailures(ip)) return send(res, 429, { ok: false, error: 'too_many_wrong_tokens' });
|
|
186
|
+
if (!authed(req, url)) { noteFailure(ip); return send(res, 401, { ok: false, error: 'unauthorized' }); }
|
|
187
|
+
// licence gates (history, proofs, certificates and rollback always stay available)
|
|
188
|
+
const lic = license.status();
|
|
189
|
+
const need = (f, err) => { if (lic.features.includes(f)) return false; send(res, 402, { ok: false, error: lic.status === 'expired' ? 'license_required' : err, license: lic }); return true; };
|
|
190
|
+
if (!isLocal(req) && !/^\/api\/(license|license\/renew|status)$/.test(p) && !lic.features.includes('remote')) return send(res, 402, { ok: false, error: lic.status === 'expired' ? 'license_required' : 'needs_pro_remote', license: lic });
|
|
191
|
+
if (p === '/api/license/renew' && req.method === 'POST') { const r = await license.renew(cfg, true); return send(res, r.ok ? 200 : 400, r); }
|
|
192
|
+
if (p === '/api/license') {
|
|
193
|
+
if (req.method === 'GET') return send(res, 200, { ok: true, ...license.publicInfo() });
|
|
194
|
+
if (req.method === 'POST') { const b = await readBody(req); const r = license.activate(b.key); if (r.ok) certs.registerFingerprint(cfg).catch(() => {}); return send(res, r.ok ? 200 : 400, r); }
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
const m = (re) => p.match(re);
|
|
198
|
+
if (req.method === 'GET' && p === '/api/status') {
|
|
199
|
+
const h = await ai.health(cfg);
|
|
200
|
+
return send(res, 200, { ok: true, version: VERSION, port: cfg.port, machine: os.hostname(), lan: lanAddresses(), ai: h, aiLocal: ai.describe(cfg).local, aiLabel: ai.describe(cfg).label, license: lic, budget: cfg.budget, fixes: store.list('fixes').length, fingerprint: certs.keys().fingerprint });
|
|
201
|
+
}
|
|
202
|
+
if (p === '/api/settings/ai') {
|
|
203
|
+
if (req.method === 'POST') {
|
|
204
|
+
const b = await readBody(req);
|
|
205
|
+
const provider = ['ollama', 'openai', 'anthropic', 'claude-code'].includes(b.provider) ? b.provider : null;
|
|
206
|
+
if (!provider) return send(res, 400, { ok: false, error: 'unknown_provider' });
|
|
207
|
+
const model = String(b.model || '').trim().slice(0, 120);
|
|
208
|
+
const endpoint = String(b.endpoint || '').trim().slice(0, 300);
|
|
209
|
+
if (endpoint && !/^https?:\/\//.test(endpoint)) return send(res, 400, { ok: false, error: 'bad_endpoint' });
|
|
210
|
+
let file = {};
|
|
211
|
+
try { file = JSON.parse(fs.readFileSync(config.CONFIG_FILE, 'utf8')); } catch { /* new */ }
|
|
212
|
+
if (fs.existsSync(config.CONFIG_FILE)) fs.copyFileSync(config.CONFIG_FILE, config.CONFIG_FILE + '.bak');
|
|
213
|
+
file.ai = { provider, ...(model ? { model } : {}), ...(endpoint ? { endpoint } : {}) };
|
|
214
|
+
cfg.ai = file.ai;
|
|
215
|
+
if (provider === 'ollama' && model) { file.ollama = { ...(file.ollama || {}), model }; cfg.ollama.model = model; }
|
|
216
|
+
if (provider === 'ollama' && endpoint) { file.ollama = { ...(file.ollama || {}), endpoint }; cfg.ollama.endpoint = endpoint; }
|
|
217
|
+
fs.writeFileSync(config.CONFIG_FILE, JSON.stringify(file, null, 2));
|
|
218
|
+
if (b.apiKey && (provider === 'openai' || provider === 'anthropic')) ai.saveSecret(provider === 'openai' ? 'openaiKey' : 'anthropicKey', b.apiKey);
|
|
219
|
+
}
|
|
220
|
+
const d = ai.describe(cfg); const sec = ai.secrets();
|
|
221
|
+
return send(res, 200, { ok: true, provider: d.provider, model: d.model, endpoint: d.endpoint || '', label: d.label, local: d.local, hasOpenaiKey: !!(process.env.OPENAI_API_KEY || sec.openaiKey), hasAnthropicKey: !!(process.env.ANTHROPIC_API_KEY || sec.anthropicKey), health: await ai.health(cfg) });
|
|
222
|
+
}
|
|
223
|
+
if (req.method === 'GET' && p === '/api/stats') return send(res, 200, { ok: true, ...stats() });
|
|
224
|
+
if (req.method === 'GET' && p === '/api/fs') return send(res, 200, listDirs(url.searchParams.get('path') || ''));
|
|
225
|
+
if (req.method === 'POST' && p === '/api/guards') {
|
|
226
|
+
const b = await readBody(req);
|
|
227
|
+
if (need('guard', 'license_required')) return;
|
|
228
|
+
const r = flow.guardStart({ projectId: b.projectId, source: b.source }, cfg);
|
|
229
|
+
return send(res, r.ok ? 200 : 400, { ...r, task: publicTask(r.task) });
|
|
230
|
+
}
|
|
231
|
+
let gm;
|
|
232
|
+
if (req.method === 'POST' && (gm = p.match(/^\/api\/guards\/([\w-]+)\/(check|accept|rollback)$/))) {
|
|
233
|
+
const b = await readBody(req);
|
|
234
|
+
if (gm[2] === 'check' && need('guard', 'license_required')) return;
|
|
235
|
+
const r = gm[2] === 'check' ? await flow.guardCheck(gm[1], cfg, { claim: b.claim || '' }) : gm[2] === 'accept' ? flow.guardAccept(gm[1], cfg, { force: !!b.force }) : flow.guardRollback(gm[1], cfg);
|
|
236
|
+
return send(res, r.ok ? 200 : 400, { ...r, task: publicTask(r.task) });
|
|
237
|
+
}
|
|
238
|
+
if (req.method === 'GET' && p === '/api/certs') return send(res, 200, { ok: true, certs: store.list('certs').map(({ payload, signature, publicKey, ...c }) => ({ ...c, task: payload.task.text, checks: payload.checks.length, integrityClean: payload.integrity.clean })).reverse() });
|
|
239
|
+
let cm;
|
|
240
|
+
if (req.method === 'GET' && (cm = p.match(/^\/api\/certs\/([\w-]+)(\.html)?$/))) {
|
|
241
|
+
const c = store.get('certs', cm[1]);
|
|
242
|
+
if (!c) return send(res, 404, { ok: false, error: 'not_found' });
|
|
243
|
+
if (!cm[2]) return send(res, 200, { ok: true, cert: c, valid: certs.verify(c) });
|
|
244
|
+
res.writeHead(200, { 'content-type': 'text/html; charset=utf-8', 'cache-control': 'no-store', ...(url.searchParams.get('download') === '1' ? { 'content-disposition': `attachment; filename="buildproof-${c.id}.html"` } : {}) });
|
|
245
|
+
return res.end(certs.html(c));
|
|
246
|
+
}
|
|
247
|
+
if (req.method === 'POST' && p === '/api/certs/verify') {
|
|
248
|
+
const b = await readBody(req);
|
|
249
|
+
return send(res, 200, { ok: true, valid: !!(b.cert && certs.verify(b.cert)) });
|
|
250
|
+
}
|
|
251
|
+
if (req.method === 'GET' && p === '/api/projects') return send(res, 200, { ok: true, projects: store.list('projects').map((x) => ({ ...x, hooks: hooks.status(x.root) })) });
|
|
252
|
+
let hm;
|
|
253
|
+
if ((hm = p.match(/^\/api\/projects\/([\w-]+)\/hooks$/))) {
|
|
254
|
+
const pr = store.get('projects', hm[1]);
|
|
255
|
+
if (!pr) return send(res, 404, { ok: false, error: 'not_found' });
|
|
256
|
+
if (req.method === 'GET') return send(res, 200, { ok: true, hooks: hooks.status(pr.root) });
|
|
257
|
+
const b = await readBody(req);
|
|
258
|
+
if (req.method === 'POST' && need('hooks', 'license_required')) return;
|
|
259
|
+
if (flow.activeGuard(pr.id)) return send(res, 400, { ok: false, error: 'finish_guard_first' });
|
|
260
|
+
const tools = Array.isArray(b.tools) ? b.tools : [];
|
|
261
|
+
const result = req.method === 'DELETE' ? Object.fromEntries(tools.map((t) => [t, hooks.disconnect(pr.root, t)])) : hooks.connect(pr.root, tools);
|
|
262
|
+
return send(res, 200, { ok: Object.values(result).every((r) => r.ok), result, hooks: hooks.status(pr.root) });
|
|
263
|
+
}
|
|
264
|
+
if (req.method === 'POST' && p === '/api/projects') {
|
|
265
|
+
const b = await readBody(req);
|
|
266
|
+
if (need('guard', 'license_required')) return;
|
|
267
|
+
const all = store.list('projects');
|
|
268
|
+
const known = all.some((x) => path.resolve(x.root).toLowerCase() === path.resolve(String(b.root || '')).toLowerCase());
|
|
269
|
+
if (!known && lic.projects != null && all.length >= lic.projects) return send(res, 402, { ok: false, error: 'plan_limit_projects', limit: lic.projects, license: lic });
|
|
270
|
+
const r = projects.add({ name: b.name, root: b.root });
|
|
271
|
+
return send(res, r.ok ? 200 : 400, r);
|
|
272
|
+
}
|
|
273
|
+
let mm;
|
|
274
|
+
if (req.method === 'DELETE' && (mm = m(/^\/api\/projects\/([\w-]+)$/))) return send(res, 200, { ok: store.remove('projects', mm[1]) });
|
|
275
|
+
if (req.method === 'GET' && p === '/api/tasks') {
|
|
276
|
+
const since = url.searchParams.get('since');
|
|
277
|
+
const rows = store.list('tasks', (t) => !since || (t.updatedAt || t.createdAt) > since)
|
|
278
|
+
.sort((a, b) => (b.createdAt > a.createdAt ? 1 : -1)).slice(0, 50).map((t) => publicTask(t));
|
|
279
|
+
return send(res, 200, { ok: true, tasks: rows, now: new Date().toISOString() });
|
|
280
|
+
}
|
|
281
|
+
if (req.method === 'POST' && p === '/api/tasks') {
|
|
282
|
+
const b = await readBody(req);
|
|
283
|
+
if (need('aiFix', 'needs_pro')) return;
|
|
284
|
+
const r = flow.create({ projectId: b.projectId, text: b.text, source: b.source });
|
|
285
|
+
if (!r.ok) return send(res, 400, r);
|
|
286
|
+
flow.start(r.task.id, cfg);
|
|
287
|
+
return send(res, 200, { ok: true, task: publicTask(r.task) });
|
|
288
|
+
}
|
|
289
|
+
if (req.method === 'GET' && (mm = m(/^\/api\/tasks\/([\w-]+)$/))) {
|
|
290
|
+
const t = store.get('tasks', mm[1]);
|
|
291
|
+
return t ? send(res, 200, { ok: true, task: publicTask(t, true) }) : send(res, 404, { ok: false, error: 'not_found' });
|
|
292
|
+
}
|
|
293
|
+
if (req.method === 'POST' && (mm = m(/^\/api\/tasks\/([\w-]+)\/(approve|reject|stop|undo)$/))) {
|
|
294
|
+
const b = await readBody(req);
|
|
295
|
+
const id = mm[1];
|
|
296
|
+
const r = mm[2] === 'approve' ? await flow.approve(id, cfg, Array.isArray(b.scope) ? b.scope : null)
|
|
297
|
+
: mm[2] === 'reject' ? flow.reject(id)
|
|
298
|
+
: mm[2] === 'stop' ? flow.stop(id)
|
|
299
|
+
: flow.undo(id, cfg);
|
|
300
|
+
return send(res, r.ok ? 200 : 400, r);
|
|
301
|
+
}
|
|
302
|
+
if (req.method === 'GET' && p === '/api/fixes') return send(res, 200, { ok: true, fixes: store.list('fixes').map(({ edits, ...f }) => ({ ...f, files: edits.map((e) => e.path) })) });
|
|
303
|
+
return send(res, 404, { ok: false, error: 'no_route' });
|
|
304
|
+
} catch (e) {
|
|
305
|
+
console.error(`[api] ${req.method} ${p}: ${e.stack || e.message}`);
|
|
306
|
+
if (res.headersSent) { try { res.end(); } catch { /* closed */ } return; }
|
|
307
|
+
return send(res, 500, { ok: false, error: e.message });
|
|
308
|
+
}
|
|
309
|
+
});
|
|
310
|
+
|
|
311
|
+
// Nothing may stay "running" forever after a restart; guards keep watching.
|
|
312
|
+
flow.recoverAfterRestart(cfg);
|
|
313
|
+
certs.keys();
|
|
314
|
+
// monthly plans: pick up the renewed key by itself
|
|
315
|
+
const renewNow = () => license.renew(cfg).catch(() => {});
|
|
316
|
+
setTimeout(renewNow, 20000).unref(); setInterval(renewNow, 6 * 3600e3).unref();
|
|
317
|
+
|
|
318
|
+
server.listen(cfg.port, cfg.host, () => {
|
|
319
|
+
console.log(`BuildProof v${VERSION} on http://127.0.0.1:${cfg.port} LAN: ${lanAddresses().map((a) => `http://${a}:${cfg.port}`).join(' ')}`);
|
|
320
|
+
});
|
|
321
|
+
|
|
322
|
+
module.exports = { server, cfg };
|
package/core/service.js
ADDED
|
@@ -0,0 +1,89 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* Keep BuildProof running in the background, on every OS, without admin rights.
|
|
4
|
+
* Windows: hidden launcher in the user's Startup folder
|
|
5
|
+
* macOS: LaunchAgent (~/Library/LaunchAgents)
|
|
6
|
+
* Linux: systemd --user unit, or an XDG autostart entry when systemd is not available
|
|
7
|
+
* The guard (scripts/guard.js) is single-instance, so starting it twice is harmless.
|
|
8
|
+
*/
|
|
9
|
+
const fs = require('fs');
|
|
10
|
+
const os = require('os');
|
|
11
|
+
const path = require('path');
|
|
12
|
+
const http = require('http');
|
|
13
|
+
const { spawn, spawnSync } = require('child_process');
|
|
14
|
+
const config = require('./config');
|
|
15
|
+
|
|
16
|
+
const GUARD = path.join(config.ROOT, 'scripts', 'guard.js');
|
|
17
|
+
const NODE = process.execPath;
|
|
18
|
+
|
|
19
|
+
function health(port, timeoutMs = 1500) {
|
|
20
|
+
return new Promise((resolve) => {
|
|
21
|
+
const req = http.get({ host: '127.0.0.1', port, path: '/healthz', timeout: timeoutMs }, (res) => { res.resume(); resolve(res.statusCode === 200); });
|
|
22
|
+
req.on('error', () => resolve(false));
|
|
23
|
+
req.on('timeout', () => { req.destroy(); resolve(false); });
|
|
24
|
+
});
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function startDetached() {
|
|
28
|
+
const child = spawn(NODE, [GUARD], { detached: true, stdio: 'ignore', windowsHide: true, cwd: config.ROOT, env: process.env });
|
|
29
|
+
child.unref();
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** Auto-start at login. Returns a short description of what was done. */
|
|
33
|
+
function installAutostart() {
|
|
34
|
+
const home = os.homedir();
|
|
35
|
+
if (process.platform === 'win32') {
|
|
36
|
+
if (fs.existsSync(path.join(config.ROOT, 'scripts', 'guard.vbs'))) return 'windows-installer';
|
|
37
|
+
const dir = path.join(process.env.APPDATA || path.join(home, 'AppData', 'Roaming'), 'Microsoft', 'Windows', 'Start Menu', 'Programs', 'Startup');
|
|
38
|
+
fs.mkdirSync(dir, { recursive: true });
|
|
39
|
+
const vbs = `Set sh = CreateObject("WScript.Shell")\r\nsh.CurrentDirectory = "${config.ROOT}"\r\nsh.Run """${NODE}"" ""${GUARD}""", 0, False\r\n`;
|
|
40
|
+
fs.writeFileSync(path.join(dir, 'BuildProof.vbs'), vbs);
|
|
41
|
+
return 'windows-startup';
|
|
42
|
+
}
|
|
43
|
+
if (process.platform === 'darwin') {
|
|
44
|
+
const f = path.join(home, 'Library', 'LaunchAgents', 'dev.buildproof.guard.plist');
|
|
45
|
+
fs.mkdirSync(path.dirname(f), { recursive: true });
|
|
46
|
+
fs.writeFileSync(f, `<?xml version="1.0" encoding="UTF-8"?>
|
|
47
|
+
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
|
|
48
|
+
<plist version="1.0"><dict>
|
|
49
|
+
<key>Label</key><string>dev.buildproof.guard</string>
|
|
50
|
+
<key>ProgramArguments</key><array><string>${NODE}</string><string>${GUARD}</string></array>
|
|
51
|
+
<key>RunAtLoad</key><true/><key>KeepAlive</key><false/>
|
|
52
|
+
<key>WorkingDirectory</key><string>${config.ROOT}</string>
|
|
53
|
+
</dict></plist>
|
|
54
|
+
`);
|
|
55
|
+
spawnSync('launchctl', ['load', '-w', f], { stdio: 'ignore' });
|
|
56
|
+
return 'macos-launchagent';
|
|
57
|
+
}
|
|
58
|
+
const sd = spawnSync('systemctl', ['--user', 'show-environment'], { stdio: 'ignore' });
|
|
59
|
+
if (sd.status === 0) {
|
|
60
|
+
const f = path.join(home, '.config', 'systemd', 'user', 'buildproof.service');
|
|
61
|
+
fs.mkdirSync(path.dirname(f), { recursive: true });
|
|
62
|
+
fs.writeFileSync(f, `[Unit]\nDescription=BuildProof\n\n[Service]\nExecStart=${NODE} ${GUARD}\nWorkingDirectory=${config.ROOT}\nRestart=on-failure\n\n[Install]\nWantedBy=default.target\n`);
|
|
63
|
+
spawnSync('systemctl', ['--user', 'daemon-reload'], { stdio: 'ignore' });
|
|
64
|
+
spawnSync('systemctl', ['--user', 'enable', 'buildproof.service'], { stdio: 'ignore' });
|
|
65
|
+
return 'linux-systemd';
|
|
66
|
+
}
|
|
67
|
+
const f = path.join(home, '.config', 'autostart', 'buildproof.desktop');
|
|
68
|
+
fs.mkdirSync(path.dirname(f), { recursive: true });
|
|
69
|
+
fs.writeFileSync(f, `[Desktop Entry]\nType=Application\nName=BuildProof\nExec=${NODE} ${GUARD}\nX-GNOME-Autostart-enabled=true\n`);
|
|
70
|
+
return 'linux-autostart';
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** Make sure the service answers now; install auto-start once. */
|
|
74
|
+
async function ensure({ autostart = true } = {}) {
|
|
75
|
+
const cfg = config.load();
|
|
76
|
+
let how = 'already-running';
|
|
77
|
+
if (!(await health(cfg.port))) {
|
|
78
|
+
startDetached();
|
|
79
|
+
how = 'started';
|
|
80
|
+
let ok = false;
|
|
81
|
+
for (let i = 0; i < 40 && !ok; i++) { await new Promise((r) => setTimeout(r, 500)); ok = await health(cfg.port); }
|
|
82
|
+
if (!ok) return { ok: false, how: 'start_failed', port: cfg.port };
|
|
83
|
+
}
|
|
84
|
+
let auto = null;
|
|
85
|
+
if (autostart) { try { auto = installAutostart(); } catch (e) { auto = 'failed: ' + e.message; } }
|
|
86
|
+
return { ok: true, how, autostart: auto, port: cfg.port };
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
module.exports = { ensure, health, installAutostart, startDetached };
|
package/core/snapshot.js
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* Snapshot = { relPath: sha256 } of every project file (ignored dirs skipped).
|
|
4
|
+
*
|
|
5
|
+
* Ignored folders depend on the project:
|
|
6
|
+
* bin / obj only next to a .NET project file (in a Node project bin/ is source code)
|
|
7
|
+
* Library / Temp only in a Unity project
|
|
8
|
+
* everything else in the list (node_modules, dist, ...) always
|
|
9
|
+
* Symbolic links are part of the snapshot (hash of the link itself), so a file swapped for a link is seen.
|
|
10
|
+
* legacy: true = the 3.7.0 rules (used to re-check certificates issued before 3.7.1).
|
|
11
|
+
*/
|
|
12
|
+
const fs = require('fs');
|
|
13
|
+
const path = require('path');
|
|
14
|
+
const crypto = require('crypto');
|
|
15
|
+
|
|
16
|
+
const DOTNET = /\.(csproj|fsproj|vbproj|sln)$/i;
|
|
17
|
+
const has = (names, ...f) => f.some((x) => names.includes(x));
|
|
18
|
+
const CONTEXT = {
|
|
19
|
+
// Rust / Maven build output, PHP / Ruby / Go installed packages: only where that toolchain owns the folder
|
|
20
|
+
target: (dir, names) => has(names, 'Cargo.toml', 'pom.xml', 'build.sbt'),
|
|
21
|
+
vendor: (dir, names) => has(names, 'composer.json', 'Gemfile', 'go.mod'),
|
|
22
|
+
bin: (dir, names) => names.some((n) => DOTNET.test(n)),
|
|
23
|
+
obj: (dir, names) => names.some((n) => DOTNET.test(n)),
|
|
24
|
+
Library: (dir, names) => names.includes('Assets') && names.includes('ProjectSettings'),
|
|
25
|
+
Temp: (dir, names) => names.includes('Assets') && names.includes('ProjectSettings'),
|
|
26
|
+
};
|
|
27
|
+
|
|
28
|
+
const MAX_FILES = 100000;
|
|
29
|
+
/** files.truncated = true when the project has more files than maxFiles: callers must fail closed, never guard half a project. */
|
|
30
|
+
function walk(root, ignore, maxFiles = MAX_FILES, opts = {}) {
|
|
31
|
+
const files = [];
|
|
32
|
+
const mark = () => { Object.defineProperty(files, 'truncated', { value: true, enumerable: false }); };
|
|
33
|
+
const skip = new Set(ignore);
|
|
34
|
+
(function rec(dir) {
|
|
35
|
+
let entries = [];
|
|
36
|
+
try { entries = fs.readdirSync(dir, { withFileTypes: true }); } catch { return; }
|
|
37
|
+
const names = entries.map((e) => e.name);
|
|
38
|
+
const add = (full) => { if (files.length >= maxFiles) { mark(); return false; } files.push(path.relative(root, full).split(path.sep).join('/')); return true; };
|
|
39
|
+
for (const e of entries) {
|
|
40
|
+
if (files.truncated) return;
|
|
41
|
+
if (skip.has(e.name) && (opts.legacy || !CONTEXT[e.name] || CONTEXT[e.name](dir, names))) continue;
|
|
42
|
+
const full = path.join(dir, e.name);
|
|
43
|
+
if (e.isSymbolicLink()) { if (!opts.legacy) add(full); }
|
|
44
|
+
else if (e.isDirectory()) rec(full);
|
|
45
|
+
else if (e.isFile()) add(full);
|
|
46
|
+
}
|
|
47
|
+
})(root);
|
|
48
|
+
return files;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
function isLink(abs) { try { return fs.lstatSync(abs).isSymbolicLink(); } catch { return false; } }
|
|
52
|
+
|
|
53
|
+
function hashFile(abs) {
|
|
54
|
+
try {
|
|
55
|
+
if (isLink(abs)) return crypto.createHash('sha256').update('symlink:' + fs.readlinkSync(abs)).digest('hex');
|
|
56
|
+
return crypto.createHash('sha256').update(fs.readFileSync(abs)).digest('hex');
|
|
57
|
+
} catch { return null; }
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
function take(root, ignore, maxFiles) {
|
|
61
|
+
const snap = {};
|
|
62
|
+
const files = walk(root, ignore, maxFiles);
|
|
63
|
+
for (const rel of files) snap[rel] = hashFile(path.join(root, rel));
|
|
64
|
+
if (files.truncated) Object.defineProperty(snap, 'truncated', { value: true, enumerable: false });
|
|
65
|
+
return snap;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/** Where a link really points, when that is outside the project (null = inside, or not a link). */
|
|
69
|
+
function linkOutside(root, rel) {
|
|
70
|
+
const abs = path.join(root, rel);
|
|
71
|
+
if (!isLink(abs)) return null;
|
|
72
|
+
let target;
|
|
73
|
+
try { target = fs.realpathSync(abs); } catch { target = path.resolve(path.dirname(abs), fs.readlinkSync(abs)); }
|
|
74
|
+
let base = path.resolve(root); try { base = fs.realpathSync(base); } catch { /* as is */ }
|
|
75
|
+
const r = path.relative(base, target);
|
|
76
|
+
return r && !r.startsWith('..') && !path.isAbsolute(r) ? null : target;
|
|
77
|
+
}
|
|
78
|
+
|
|
79
|
+
/** Files added / modified / deleted between two snapshots. */
|
|
80
|
+
function diff(before, after) {
|
|
81
|
+
const changed = [];
|
|
82
|
+
for (const [f, h] of Object.entries(after)) {
|
|
83
|
+
if (!(f in before)) changed.push({ file: f, kind: 'added' });
|
|
84
|
+
else if (before[f] !== h) changed.push({ file: f, kind: 'modified' });
|
|
85
|
+
}
|
|
86
|
+
for (const f of Object.keys(before)) if (!(f in after)) changed.push({ file: f, kind: 'deleted' });
|
|
87
|
+
return changed;
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
module.exports = { walk, take, diff, hashFile, isLink, linkOutside, MAX_FILES };
|
package/core/store.js
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/** Tiny JSON store with atomic writes. One file per collection. */
|
|
3
|
+
const fs = require('fs');
|
|
4
|
+
const path = require('path');
|
|
5
|
+
const { DATA_DIR } = require('./config');
|
|
6
|
+
|
|
7
|
+
const cache = new Map();
|
|
8
|
+
|
|
9
|
+
function file(name) { return path.join(DATA_DIR, `${name}.json`); }
|
|
10
|
+
|
|
11
|
+
function readAll(name) {
|
|
12
|
+
if (cache.has(name)) return cache.get(name);
|
|
13
|
+
// a damaged file is kept aside (never overwritten by the next write)
|
|
14
|
+
const got = require('./keep-corrupt').readJsonSafe(file(name));
|
|
15
|
+
const rows = Array.isArray(got) ? got : [];
|
|
16
|
+
cache.set(name, rows);
|
|
17
|
+
return rows;
|
|
18
|
+
}
|
|
19
|
+
|
|
20
|
+
function flush(name) {
|
|
21
|
+
fs.mkdirSync(DATA_DIR, { recursive: true });
|
|
22
|
+
const tmp = file(name) + '.tmp';
|
|
23
|
+
fs.writeFileSync(tmp, JSON.stringify(readAll(name), null, 2), 'utf8');
|
|
24
|
+
fs.renameSync(tmp, file(name));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
function insert(name, row) { readAll(name).push(row); flush(name); return row; }
|
|
28
|
+
function get(name, id) { return readAll(name).find((r) => r.id === id) || null; }
|
|
29
|
+
function update(name, id, patch) {
|
|
30
|
+
const row = get(name, id);
|
|
31
|
+
if (!row) return null;
|
|
32
|
+
Object.assign(row, patch, { updatedAt: new Date().toISOString() });
|
|
33
|
+
flush(name);
|
|
34
|
+
return row;
|
|
35
|
+
}
|
|
36
|
+
function remove(name, id) {
|
|
37
|
+
const rows = readAll(name);
|
|
38
|
+
const i = rows.findIndex((r) => r.id === id);
|
|
39
|
+
if (i >= 0) { rows.splice(i, 1); flush(name); return true; }
|
|
40
|
+
return false;
|
|
41
|
+
}
|
|
42
|
+
function list(name, pred) { const rows = readAll(name); return pred ? rows.filter(pred) : rows.slice(); }
|
|
43
|
+
function resetCache() { cache.clear(); }
|
|
44
|
+
|
|
45
|
+
module.exports = { insert, get, update, remove, list, flush, resetCache };
|