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/core/vault.js
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
/**
|
|
3
|
+
* Encryption at rest for secrets on this computer (API keys).
|
|
4
|
+
* AES-256-GCM (authenticated: any change to the file is detected).
|
|
5
|
+
* The 256-bit key lives in data/vault.key:
|
|
6
|
+
* Windows - protected with Windows DPAPI (CurrentUser): only this Windows user on this computer can unlock it.
|
|
7
|
+
* macOS / Linux - file readable by this user only (mode 0600).
|
|
8
|
+
* File format: {"v":1,"alg":"aes-256-gcm","iv":"..","tag":"..","data":".."} (base64).
|
|
9
|
+
*/
|
|
10
|
+
const fs = require('fs');
|
|
11
|
+
const path = require('path');
|
|
12
|
+
const crypto = require('crypto');
|
|
13
|
+
const { spawnSync } = require('child_process');
|
|
14
|
+
|
|
15
|
+
const KEYFILE = () => path.join(require('./config').DATA_DIR, 'vault.key');
|
|
16
|
+
let cached = null;
|
|
17
|
+
|
|
18
|
+
function dpapi(op, b64) {
|
|
19
|
+
const ps = `Add-Type -AssemblyName System.Security; $b=[Convert]::FromBase64String('${b64}'); $r=[Security.Cryptography.ProtectedData]::${op}($b,$null,'CurrentUser'); [Convert]::ToBase64String($r)`;
|
|
20
|
+
const r = spawnSync('powershell', ['-NoProfile', '-NonInteractive', '-Command', ps], { encoding: 'utf8', windowsHide: true, timeout: 20000 });
|
|
21
|
+
if (r.status !== 0) throw new Error('dpapi_failed');
|
|
22
|
+
return r.stdout.trim();
|
|
23
|
+
}
|
|
24
|
+
|
|
25
|
+
function key() {
|
|
26
|
+
if (cached) return cached;
|
|
27
|
+
const f = KEYFILE();
|
|
28
|
+
let rec = null;
|
|
29
|
+
try { rec = JSON.parse(fs.readFileSync(f, 'utf8')); } catch { /* first run */ }
|
|
30
|
+
if (rec) {
|
|
31
|
+
cached = Buffer.from(rec.dpapi ? dpapi('Unprotect', rec.dpapi) : rec.raw, 'base64');
|
|
32
|
+
if (cached.length !== 32) { cached = null; throw new Error('vault_key_bad'); }
|
|
33
|
+
return cached;
|
|
34
|
+
}
|
|
35
|
+
const k = crypto.randomBytes(32);
|
|
36
|
+
let out;
|
|
37
|
+
if (process.platform === 'win32' && !process.env.MGR_VAULT_NO_DPAPI) {
|
|
38
|
+
try { out = { v: 1, dpapi: dpapi('Protect', k.toString('base64')) }; } catch { out = { v: 1, raw: k.toString('base64') }; }
|
|
39
|
+
} else out = { v: 1, raw: k.toString('base64') };
|
|
40
|
+
fs.mkdirSync(path.dirname(f), { recursive: true });
|
|
41
|
+
fs.writeFileSync(f, JSON.stringify(out), { mode: 0o600 });
|
|
42
|
+
cached = k;
|
|
43
|
+
return k;
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
function encrypt(obj) {
|
|
47
|
+
const iv = crypto.randomBytes(12);
|
|
48
|
+
const c = crypto.createCipheriv('aes-256-gcm', key(), iv);
|
|
49
|
+
const data = Buffer.concat([c.update(JSON.stringify(obj), 'utf8'), c.final()]);
|
|
50
|
+
return { v: 1, alg: 'aes-256-gcm', iv: iv.toString('base64'), tag: c.getAuthTag().toString('base64'), data: data.toString('base64') };
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
function decrypt(rec) {
|
|
54
|
+
const d = crypto.createDecipheriv('aes-256-gcm', key(), Buffer.from(rec.iv, 'base64'));
|
|
55
|
+
d.setAuthTag(Buffer.from(rec.tag, 'base64'));
|
|
56
|
+
return JSON.parse(Buffer.concat([d.update(Buffer.from(rec.data, 'base64')), d.final()]).toString('utf8'));
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
const isSealed = (rec) => rec && rec.alg === 'aes-256-gcm' && rec.iv && rec.tag && rec.data;
|
|
60
|
+
|
|
61
|
+
/** Read an encrypted JSON file. A plain (old) file is read once and re-written encrypted. */
|
|
62
|
+
function readFile(file) {
|
|
63
|
+
let rec;
|
|
64
|
+
try { rec = JSON.parse(fs.readFileSync(file, 'utf8')); } catch { return {}; }
|
|
65
|
+
if (isSealed(rec)) return decrypt(rec); // throws if the file was changed
|
|
66
|
+
writeFile(file, rec); // migrate old plain text
|
|
67
|
+
return rec;
|
|
68
|
+
}
|
|
69
|
+
|
|
70
|
+
function writeFile(file, obj) {
|
|
71
|
+
fs.mkdirSync(path.dirname(file), { recursive: true });
|
|
72
|
+
const tmp = file + '.tmp';
|
|
73
|
+
fs.writeFileSync(tmp, JSON.stringify(encrypt(obj)), { mode: 0o600 });
|
|
74
|
+
fs.renameSync(tmp, file);
|
|
75
|
+
}
|
|
76
|
+
|
|
77
|
+
module.exports = { encrypt, decrypt, readFile, writeFile, isSealed, _reset: () => { cached = null; } };
|
package/license/.keep
ADDED
|
File without changes
|
package/package.json
CHANGED
|
@@ -1,6 +1,41 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "buildproof",
|
|
3
|
-
"version": "
|
|
4
|
-
"
|
|
5
|
-
"
|
|
6
|
-
|
|
3
|
+
"version": "3.7.2",
|
|
4
|
+
"description": "BuildProof - proof gate for AI-written code: test-integrity guard, fail-closed checks, scope lock, full rollback, signed certificates, local AI under supervision.",
|
|
5
|
+
"main": "core/server.js",
|
|
6
|
+
"scripts": {
|
|
7
|
+
"start": "node core/server.js",
|
|
8
|
+
"guard": "node scripts/guard.js",
|
|
9
|
+
"test": "node test/run-all.js && npm run test:unit",
|
|
10
|
+
"test:unit": "node --test test/modules.test.js test/guard-process.test.js test/av-scan.test.js test/license-net.test.js test/guard-force.test.js test/guard-security.test.js tools/mutation-runner/acceptance.test.js",
|
|
11
|
+
"bench": "node tools/benchmark/run.js",
|
|
12
|
+
"test:hard": "node test/hardening.js"
|
|
13
|
+
},
|
|
14
|
+
"engines": {
|
|
15
|
+
"node": ">=18"
|
|
16
|
+
},
|
|
17
|
+
"bin": {
|
|
18
|
+
"buildproof": "bin/buildproof.js"
|
|
19
|
+
},
|
|
20
|
+
"files": [
|
|
21
|
+
"bin/",
|
|
22
|
+
"core/",
|
|
23
|
+
"scripts/guard.js",
|
|
24
|
+
"web/",
|
|
25
|
+
"license/",
|
|
26
|
+
"README.md",
|
|
27
|
+
"LICENSE.txt"
|
|
28
|
+
],
|
|
29
|
+
"dependencies": {
|
|
30
|
+
"html2canvas": "1.4.1"
|
|
31
|
+
},
|
|
32
|
+
"keywords": [
|
|
33
|
+
"ai",
|
|
34
|
+
"testing",
|
|
35
|
+
"claude-code",
|
|
36
|
+
"cursor",
|
|
37
|
+
"verification",
|
|
38
|
+
"ci"
|
|
39
|
+
],
|
|
40
|
+
"license": "SEE LICENSE IN LICENSE.txt"
|
|
41
|
+
}
|
package/scripts/guard.js
ADDED
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
'use strict';
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* BuildProof Server Guard — keeps the core service alive on one port (default 38700).
|
|
5
|
+
*
|
|
6
|
+
* - Starts core/server.js as a child process (hidden, no console).
|
|
7
|
+
* - Restarts it when it crashes (exponential backoff, resets after stable uptime).
|
|
8
|
+
* - Detects a HUNG backend: /healthz fails N times in a row -> kill + restart.
|
|
9
|
+
* - Frees the port if a foreign/orphan process holds it while health is failing.
|
|
10
|
+
* - Restarts on runaway memory.
|
|
11
|
+
* - Logs every event + crash tail to logs/server_guard.log and logs/backend-crash-*.log.
|
|
12
|
+
* - Single instance via logs/server_guard.pid (safe to launch repeatedly).
|
|
13
|
+
*
|
|
14
|
+
* Plain Node only (no npm deps). Windows-first, works on Linux for tests.
|
|
15
|
+
*/
|
|
16
|
+
|
|
17
|
+
const http = require('http');
|
|
18
|
+
const fs = require('fs');
|
|
19
|
+
const path = require('path');
|
|
20
|
+
const { spawn, execSync } = require('child_process');
|
|
21
|
+
|
|
22
|
+
const ROOT = path.resolve(__dirname, '..');
|
|
23
|
+
const SERVER_JS = path.join(ROOT, 'core', 'server.js');
|
|
24
|
+
const LOG_DIR = require('../core/config').LOG_DIR;
|
|
25
|
+
const GUARD_LOG = path.join(LOG_DIR, 'server_guard.log');
|
|
26
|
+
const OUT_LOG = path.join(LOG_DIR, 'backend.out.log');
|
|
27
|
+
const ERR_LOG = path.join(LOG_DIR, 'backend.err.log');
|
|
28
|
+
const PID_FILE = path.join(LOG_DIR, 'server_guard.pid');
|
|
29
|
+
const STATUS_FILE = path.join(LOG_DIR, 'server_guard.status.json');
|
|
30
|
+
|
|
31
|
+
const PORT = parseInt(process.env.MGR_PORT || process.env.PORT || '38700', 10);
|
|
32
|
+
const HEALTH_PATH = process.env.MGR_HEALTH_PATH || '/healthz';
|
|
33
|
+
const CHECK_MS = parseInt(process.env.MGR_GUARD_CHECK_MS || '10000', 10);
|
|
34
|
+
const HEALTH_TIMEOUT_MS = parseInt(process.env.MGR_GUARD_HEALTH_TIMEOUT_MS || '5000', 10);
|
|
35
|
+
const FAILS_BEFORE_RESTART = parseInt(process.env.MGR_GUARD_FAILS || '3', 10);
|
|
36
|
+
const STARTUP_GRACE_MS = parseInt(process.env.MGR_GUARD_GRACE_MS || '45000', 10);
|
|
37
|
+
const MAX_MEMORY_MB = parseInt(process.env.MGR_GUARD_MAX_MB || '1500', 10);
|
|
38
|
+
const STABLE_RESET_MS = 5 * 60 * 1000;
|
|
39
|
+
const MAX_BACKOFF_MS = 60 * 1000;
|
|
40
|
+
const LOG_ROTATE_BYTES = 20 * 1024 * 1024;
|
|
41
|
+
const IS_WIN = process.platform === 'win32';
|
|
42
|
+
|
|
43
|
+
let child = null;
|
|
44
|
+
let childStartedAt = 0;
|
|
45
|
+
let consecutiveFails = 0;
|
|
46
|
+
let restartCount = 0;
|
|
47
|
+
let backoffMs = 2000;
|
|
48
|
+
let restarting = false;
|
|
49
|
+
let stopping = false;
|
|
50
|
+
let errTail = [];
|
|
51
|
+
let lastHealthOkAt = 0;
|
|
52
|
+
|
|
53
|
+
function ensureLogDir() { fs.mkdirSync(LOG_DIR, { recursive: true }); }
|
|
54
|
+
|
|
55
|
+
function rotate(file) {
|
|
56
|
+
try {
|
|
57
|
+
if (fs.existsSync(file) && fs.statSync(file).size > LOG_ROTATE_BYTES) {
|
|
58
|
+
const old = file + '.1';
|
|
59
|
+
if (fs.existsSync(old)) fs.unlinkSync(old);
|
|
60
|
+
fs.renameSync(file, old);
|
|
61
|
+
}
|
|
62
|
+
} catch { /* ignore */ }
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function log(msg) {
|
|
66
|
+
ensureLogDir();
|
|
67
|
+
rotate(GUARD_LOG);
|
|
68
|
+
const line = `[${new Date().toISOString()}] ${msg}`;
|
|
69
|
+
try { fs.appendFileSync(GUARD_LOG, line + '\n', 'utf8'); } catch { /* ignore */ }
|
|
70
|
+
if (process.stdout.isTTY) console.log(line);
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
function writeStatus(extra = {}) {
|
|
74
|
+
try {
|
|
75
|
+
fs.writeFileSync(STATUS_FILE, JSON.stringify({
|
|
76
|
+
guardPid: process.pid,
|
|
77
|
+
port: PORT,
|
|
78
|
+
backendPid: child ? child.pid : null,
|
|
79
|
+
backendStartedAt: childStartedAt ? new Date(childStartedAt).toISOString() : null,
|
|
80
|
+
lastHealthOkAt: lastHealthOkAt ? new Date(lastHealthOkAt).toISOString() : null,
|
|
81
|
+
consecutiveFails,
|
|
82
|
+
restartCount,
|
|
83
|
+
updatedAt: new Date().toISOString(),
|
|
84
|
+
...extra,
|
|
85
|
+
}, null, 2), 'utf8');
|
|
86
|
+
} catch { /* ignore */ }
|
|
87
|
+
}
|
|
88
|
+
|
|
89
|
+
function isPidAlive(pid) {
|
|
90
|
+
if (!pid || !Number.isFinite(pid) || pid <= 0) return false;
|
|
91
|
+
try { process.kill(pid, 0); return true; } catch (e) { return !!(e && e.code === 'EPERM'); }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
function acquireLock() {
|
|
95
|
+
ensureLogDir();
|
|
96
|
+
try {
|
|
97
|
+
if (fs.existsSync(PID_FILE)) {
|
|
98
|
+
const existing = Number(String(fs.readFileSync(PID_FILE, 'utf8')).trim());
|
|
99
|
+
if (existing !== process.pid && isPidAlive(existing)) {
|
|
100
|
+
process.exit(0); // another guard is already running
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
} catch { /* stale lock */ }
|
|
104
|
+
fs.writeFileSync(PID_FILE, String(process.pid), 'utf8');
|
|
105
|
+
}
|
|
106
|
+
|
|
107
|
+
function releaseLock() {
|
|
108
|
+
try {
|
|
109
|
+
const existing = Number(String(fs.readFileSync(PID_FILE, 'utf8')).trim());
|
|
110
|
+
if (existing === process.pid) fs.unlinkSync(PID_FILE);
|
|
111
|
+
} catch { /* ignore */ }
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
function ownsLock() {
|
|
115
|
+
try { return Number(String(fs.readFileSync(PID_FILE, 'utf8')).trim()) === process.pid; } catch { return false; }
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
function checkHealth() {
|
|
119
|
+
return new Promise((resolve) => {
|
|
120
|
+
const req = http.get({ host: '127.0.0.1', port: PORT, path: HEALTH_PATH, timeout: HEALTH_TIMEOUT_MS }, (res) => {
|
|
121
|
+
res.resume();
|
|
122
|
+
resolve(res.statusCode === 200);
|
|
123
|
+
});
|
|
124
|
+
req.on('timeout', () => { req.destroy(); resolve(false); });
|
|
125
|
+
req.on('error', () => resolve(false));
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
|
|
129
|
+
function killTree(pid) {
|
|
130
|
+
if (!pid) return;
|
|
131
|
+
try {
|
|
132
|
+
if (IS_WIN) execSync(`taskkill /PID ${pid} /T /F`, { stdio: 'ignore', windowsHide: true });
|
|
133
|
+
else process.kill(pid, 'SIGKILL');
|
|
134
|
+
} catch { /* already gone */ }
|
|
135
|
+
}
|
|
136
|
+
|
|
137
|
+
function pidListeningOnPort(port) {
|
|
138
|
+
try {
|
|
139
|
+
if (IS_WIN) {
|
|
140
|
+
const out = execSync('netstat -ano -p tcp', { encoding: 'utf8', windowsHide: true });
|
|
141
|
+
for (const line of out.split(/\r?\n/)) {
|
|
142
|
+
const parts = line.trim().split(/\s+/);
|
|
143
|
+
if (parts.length >= 5 && /LISTENING/i.test(parts[3]) && parts[1].endsWith(`:${port}`)) {
|
|
144
|
+
return Number(parts[4]);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
return null;
|
|
148
|
+
}
|
|
149
|
+
const out = execSync(`ss -ltnp 2>/dev/null | grep ':${port} ' || true`, { encoding: 'utf8' });
|
|
150
|
+
const m = out.match(/pid=(\d+)/);
|
|
151
|
+
return m ? Number(m[1]) : null;
|
|
152
|
+
} catch { return null; }
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
function memoryMb(pid) {
|
|
156
|
+
try {
|
|
157
|
+
if (IS_WIN) {
|
|
158
|
+
const out = execSync(`tasklist /FI "PID eq ${pid}" /FO CSV /NH`, { encoding: 'utf8', windowsHide: true });
|
|
159
|
+
const m = out.match(/"([\d,.\s]+)\s*K"/i);
|
|
160
|
+
return m ? Math.round(Number(m[1].replace(/[^\d]/g, '')) / 1024) : 0;
|
|
161
|
+
}
|
|
162
|
+
const kb = Number(fs.readFileSync(`/proc/${pid}/status`, 'utf8').match(/VmRSS:\s+(\d+)/)[1]);
|
|
163
|
+
return Math.round(kb / 1024);
|
|
164
|
+
} catch { return 0; }
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
function dumpCrash(reason) {
|
|
168
|
+
ensureLogDir();
|
|
169
|
+
const file = path.join(LOG_DIR, `backend-crash-${new Date().toISOString().replace(/[:.]/g, '-')}.log`);
|
|
170
|
+
try {
|
|
171
|
+
fs.writeFileSync(file, `reason: ${reason}\nport: ${PORT}\nrestartCount: ${restartCount}\n\n--- last stderr ---\n${errTail.join('')}`, 'utf8');
|
|
172
|
+
} catch { /* ignore */ }
|
|
173
|
+
// keep only the newest 20 crash files
|
|
174
|
+
try {
|
|
175
|
+
const crashes = fs.readdirSync(LOG_DIR).filter((f) => f.startsWith('backend-crash-')).sort();
|
|
176
|
+
while (crashes.length > 20) fs.unlinkSync(path.join(LOG_DIR, crashes.shift()));
|
|
177
|
+
} catch { /* ignore */ }
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
function startBackend(reason) {
|
|
181
|
+
if (stopping) return;
|
|
182
|
+
if (child && isPidAlive(child.pid)) { log(`SKIP start: backend pid=${child.pid} already running`); return; }
|
|
183
|
+
if (!fs.existsSync(SERVER_JS)) { log(`FATAL server not found: ${SERVER_JS}`); return; }
|
|
184
|
+
rotate(OUT_LOG); rotate(ERR_LOG);
|
|
185
|
+
const out = fs.openSync(OUT_LOG, 'a');
|
|
186
|
+
const err = fs.openSync(ERR_LOG, 'a');
|
|
187
|
+
errTail = [];
|
|
188
|
+
child = spawn(process.execPath, [SERVER_JS], {
|
|
189
|
+
cwd: ROOT,
|
|
190
|
+
env: { ...process.env, MGR_PORT: String(PORT) },
|
|
191
|
+
stdio: ['ignore', 'pipe', 'pipe'],
|
|
192
|
+
windowsHide: true,
|
|
193
|
+
});
|
|
194
|
+
childStartedAt = Date.now();
|
|
195
|
+
consecutiveFails = 0;
|
|
196
|
+
log(`START backend pid=${child.pid} port=${PORT} reason=${reason}`);
|
|
197
|
+
child.stdout.on('data', (d) => { try { fs.writeSync(out, d); } catch { /* ignore */ } });
|
|
198
|
+
child.stderr.on('data', (d) => {
|
|
199
|
+
try { fs.writeSync(err, d); } catch { /* ignore */ }
|
|
200
|
+
errTail.push(String(d));
|
|
201
|
+
if (errTail.length > 60) errTail.shift();
|
|
202
|
+
});
|
|
203
|
+
const startedPid = child.pid;
|
|
204
|
+
child.on('exit', (code, signal) => {
|
|
205
|
+
try { fs.closeSync(out); fs.closeSync(err); } catch { /* ignore */ }
|
|
206
|
+
if (!child || child.pid !== startedPid) return;
|
|
207
|
+
const upMs = Date.now() - childStartedAt;
|
|
208
|
+
child = null;
|
|
209
|
+
if (stopping) return;
|
|
210
|
+
log(`EXIT backend pid=${startedPid} code=${code} signal=${signal} uptime=${Math.round(upMs / 1000)}s`);
|
|
211
|
+
dumpCrash(`exit code=${code} signal=${signal}`);
|
|
212
|
+
if (upMs > STABLE_RESET_MS) backoffMs = 2000;
|
|
213
|
+
scheduleRestart('crashed');
|
|
214
|
+
});
|
|
215
|
+
writeStatus();
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
function scheduleRestart(reason) {
|
|
219
|
+
if (restarting || stopping) return;
|
|
220
|
+
restarting = true;
|
|
221
|
+
restartCount += 1;
|
|
222
|
+
const wait = backoffMs;
|
|
223
|
+
backoffMs = Math.min(MAX_BACKOFF_MS, backoffMs * 2);
|
|
224
|
+
log(`RESTART in ${Math.round(wait / 1000)}s reason=${reason} total=${restartCount}`);
|
|
225
|
+
setTimeout(async () => {
|
|
226
|
+
if (await checkHealth()) { restarting = false; adopted(); return; }
|
|
227
|
+
restarting = false; startBackend(reason);
|
|
228
|
+
}, wait);
|
|
229
|
+
}
|
|
230
|
+
|
|
231
|
+
function adopted() {
|
|
232
|
+
log(`ADOPT healthy backend already on :${PORT} (pid=${pidListeningOnPort(PORT) || '?'}) - not starting a second one`);
|
|
233
|
+
lastHealthOkAt = Date.now(); consecutiveFails = 0; backoffMs = 2000; writeStatus();
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
function hardRestart(reason) {
|
|
237
|
+
log(`HARD-RESTART reason=${reason}`);
|
|
238
|
+
dumpCrash(reason);
|
|
239
|
+
const pid = child ? child.pid : null;
|
|
240
|
+
child = null;
|
|
241
|
+
killTree(pid);
|
|
242
|
+
const holder = pidListeningOnPort(PORT);
|
|
243
|
+
if (holder && holder !== process.pid) {
|
|
244
|
+
log(`FREE-PORT killing pid=${holder} holding :${PORT}`);
|
|
245
|
+
killTree(holder);
|
|
246
|
+
}
|
|
247
|
+
scheduleRestart(reason);
|
|
248
|
+
}
|
|
249
|
+
|
|
250
|
+
async function tick() {
|
|
251
|
+
if (stopping) return;
|
|
252
|
+
if (!ownsLock()) { log(`GUARD exit: lock now held by another guard`); stopping = true; process.exit(0); }
|
|
253
|
+
if (restarting) return;
|
|
254
|
+
const ok = await checkHealth();
|
|
255
|
+
if (stopping || restarting) return; // a restart was scheduled while we waited
|
|
256
|
+
if (ok) {
|
|
257
|
+
consecutiveFails = 0;
|
|
258
|
+
lastHealthOkAt = Date.now();
|
|
259
|
+
if (child && Date.now() - childStartedAt > STABLE_RESET_MS) backoffMs = 2000;
|
|
260
|
+
if (child) {
|
|
261
|
+
const mb = memoryMb(child.pid);
|
|
262
|
+
if (mb > MAX_MEMORY_MB) { hardRestart(`memory ${mb}MB > ${MAX_MEMORY_MB}MB`); return; }
|
|
263
|
+
}
|
|
264
|
+
writeStatus();
|
|
265
|
+
return;
|
|
266
|
+
}
|
|
267
|
+
// Health failed.
|
|
268
|
+
if (!child) {
|
|
269
|
+
const holder = pidListeningOnPort(PORT);
|
|
270
|
+
if (!holder) { startBackend('not-running'); return; }
|
|
271
|
+
consecutiveFails += 1;
|
|
272
|
+
log(`HEALTH-FAIL foreign pid=${holder} on :${PORT} (${consecutiveFails}/${FAILS_BEFORE_RESTART})`);
|
|
273
|
+
if (consecutiveFails >= FAILS_BEFORE_RESTART) hardRestart('foreign process unhealthy');
|
|
274
|
+
writeStatus();
|
|
275
|
+
return;
|
|
276
|
+
}
|
|
277
|
+
if (Date.now() - childStartedAt < STARTUP_GRACE_MS) return; // still booting
|
|
278
|
+
consecutiveFails += 1;
|
|
279
|
+
log(`HEALTH-FAIL pid=${child.pid} (${consecutiveFails}/${FAILS_BEFORE_RESTART})`);
|
|
280
|
+
if (consecutiveFails >= FAILS_BEFORE_RESTART) hardRestart('hung: health timeout');
|
|
281
|
+
writeStatus();
|
|
282
|
+
}
|
|
283
|
+
|
|
284
|
+
function shutdown() {
|
|
285
|
+
stopping = true;
|
|
286
|
+
log('GUARD stopping (backend left running)');
|
|
287
|
+
releaseLock();
|
|
288
|
+
process.exit(0);
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
async function main() {
|
|
292
|
+
acquireLock();
|
|
293
|
+
log(`GUARD start pid=${process.pid} port=${PORT} check=${CHECK_MS}ms fails=${FAILS_BEFORE_RESTART} maxMem=${MAX_MEMORY_MB}MB`);
|
|
294
|
+
process.on('SIGINT', shutdown);
|
|
295
|
+
process.on('SIGTERM', shutdown);
|
|
296
|
+
process.on('exit', releaseLock);
|
|
297
|
+
process.on('uncaughtException', (e) => log(`GUARD uncaught: ${e && e.stack || e}`));
|
|
298
|
+
// Adopt a healthy backend that is already running (no duplicate start).
|
|
299
|
+
if (await checkHealth()) {
|
|
300
|
+
log(`ADOPT existing healthy backend on :${PORT}`);
|
|
301
|
+
lastHealthOkAt = Date.now();
|
|
302
|
+
} else if (!pidListeningOnPort(PORT)) {
|
|
303
|
+
startBackend('guard-start');
|
|
304
|
+
}
|
|
305
|
+
writeStatus();
|
|
306
|
+
setInterval(() => { tick().catch((e) => log(`tick error ${e.message}`)); }, CHECK_MS);
|
|
307
|
+
}
|
|
308
|
+
|
|
309
|
+
if (require.main === module) main();
|
|
310
|
+
|
|
311
|
+
module.exports = { checkHealth, pidListeningOnPort, memoryMb, PORT };
|
|
Binary file
|
|
Binary file
|