buildproof 3.12.1 → 3.12.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/bin/buildproof.js CHANGED
@@ -205,14 +205,25 @@ async function main() {
205
205
  const r = await require('../core/bug-hunter/engine').repro(path.resolve(positional[1] || process.cwd()), f);
206
206
  out(`${r.reproduced ? 'REPRODUCED' : 'NOT_REPRODUCED'} ${f.oracle} ${f.file} ${f.export}(${f.inputPreview}) -> ${r.outcome}`, r.reproduced ? 0 : 1);
207
207
  }
208
+ if (['license', 'activate', 'status', 'open'].includes(cmd)) { // these need the local service: start it if it is not running
209
+ const sv = await require('../core/service').ensure({ autostart: false });
210
+ if (!sv.ok) out(`DOWN BuildProof could not start on port ${sv.port} (if another program uses it, pick a free port: set MGR_PORT=38711)`, 1);
211
+ }
208
212
  if (cmd === 'license' || cmd === 'activate') {
209
213
  if (cmd === 'activate') {
210
214
  let key = positional[0] || '';
211
215
  if (!key) { // no key typed: take it from the clipboard (copied on the thank-you page)
212
216
  const { spawnSync } = require('child_process');
213
- 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' });
214
- key = ((c.stdout || '').match(/BP1\.[\w-]+\.[\w-]+/) || [''])[0];
215
- if (!key) out('ACTIVATE_FAIL no key - copy it from the thank-you page, or: buildproof activate <key>', 1);
217
+ const tries = process.platform === 'win32' ? [['powershell', ['-NoProfile', '-Command', 'Get-Clipboard']]] : process.platform === 'darwin' ? [['pbpaste', []]] : [['wl-paste', ['-n']], ['xclip', ['-o', '-selection', 'clipboard']], ['xsel', ['-b', '-o']]];
218
+ let readable = false;
219
+ for (const [bin, a] of tries) {
220
+ const c = spawnSync(bin, a, { encoding: 'utf8', windowsHide: true });
221
+ if (c.error || c.status !== 0) continue;
222
+ readable = true;
223
+ key = ((c.stdout || '').match(/BP1\.[\w-]+\.[\w-]+/) || [''])[0];
224
+ if (key) break;
225
+ }
226
+ if (!key) out(readable ? 'ACTIVATE_FAIL no key in the clipboard - copy it from the thank-you page, or: buildproof activate <key>' : 'ACTIVATE_FAIL cannot read the clipboard here - run: buildproof activate <key>', 1);
216
227
  }
217
228
  const r = await api('POST', '/api/license', { key });
218
229
  out(r.ok ? `ACTIVATED ${r.license.label} until ${String(r.license.expires).slice(0, 10)}` : `ACTIVATE_FAIL ${r.error}`, r.ok ? 0 : 1);
@@ -224,7 +235,7 @@ async function main() {
224
235
  if (cmd === 'init') {
225
236
  const service = require('../core/service');
226
237
  const sv = await service.ensure({ autostart: !process.env.MGR_NO_AUTOSTART });
227
- if (!sv.ok) out(`INIT_FAIL BuildProof could not start on port ${sv.port}`, 1);
238
+ if (!sv.ok) out(`INIT_FAIL BuildProof could not start on port ${sv.port} (if another program uses it, pick a free port: set MGR_PORT=38711)`, 1);
228
239
  const dir = path.resolve(positional[0] || process.cwd());
229
240
  const pr = await api('POST', '/api/projects', { root: dir });
230
241
  if (!pr.ok) out(`INIT_FAIL ${pr.error}${pr.limit ? ' (limit ' + pr.limit + ' projects in this plan)' : ''}`, 1);
@@ -245,10 +256,10 @@ async function main() {
245
256
  if (!process.env.MGR_NO_AUTOSTART && !process.env.MGR_NO_OPEN) openUrl(`http://127.0.0.1:${sv.port}/connect`);
246
257
  out(`OPEN http://127.0.0.1:${sv.port}/connect (BuildProof on this computer + add your phone)`, 0);
247
258
  }
248
- if (cmd === 'try') { // 30-second demo on a throw-away sample project, never on your code
259
+ if (cmd === 'try') { // 30-second demo on a throw-away sample project, never on your code (installs nothing that starts at login)
249
260
  const service = require('../core/service');
250
- const sv = await service.ensure({ autostart: !process.env.MGR_NO_AUTOSTART });
251
- if (!sv.ok) out(`TRY_FAIL BuildProof could not start on port ${sv.port}`, 1);
261
+ const sv = await service.ensure({ autostart: false });
262
+ if (!sv.ok) out(`TRY_FAIL BuildProof could not start on port ${sv.port} (if another program uses it, pick a free port: set MGR_PORT=38711)`, 1);
252
263
  const r = await require('../core/try-demo').run({ api, sleep, say: (t) => console.log(t) });
253
264
  if (!r.ok) out(`TRY_FAIL ${r.error}${r.error === 'license_required' ? ' (start the free trial: buildproof init)' : ''}${r.limit ? ' (limit ' + r.limit + ' projects in this plan)' : ''}`, 1);
254
265
  const good = !r.round1.proven && r.round2.proven;
package/core/license.js CHANGED
@@ -89,18 +89,40 @@ function deviceId(){
89
89
  if(!identity)identity=os.hostname()+'|'+Object.values(os.networkInterfaces()).flat().filter(x=>x&&!x.internal&&x.mac&&x.mac!=='00:00:00:00:00:00').map(x=>x.mac).sort().join('|');
90
90
  return crypto.createHash('sha256').update('BuildProof-trial-v4:'+identity).digest('hex');
91
91
  }
92
+ const OFFLINE_FILE = () => path.join(DATA_DIR, 'trial-offline.json');
93
+ /** Remember the server's trial start locally, so going offline later can never give more days than the server allows. */
94
+ function recordServerStart(online){
95
+ try{
96
+ let t=Date.parse(online.started||'');
97
+ if(!Number.isFinite(t))t=Date.now()-(TRIAL_DAYS-Math.max(0,online.daysLeft))*DAY-(online.status==='expired'?DAY:0);
98
+ const st=readJson(FILE())||{}; const prev=Date.parse(st.trialStart||'');
99
+ if(Number.isFinite(prev)&&prev<=t)return;
100
+ const iso=new Date(t).toISOString();
101
+ fs.mkdirSync(DATA_DIR,{recursive:true}); fs.writeFileSync(FILE(),JSON.stringify({...st,trialStart:iso},null,2));
102
+ try{fs.writeFileSync(MARKER(),iso)}catch{}
103
+ }catch{}
104
+ }
92
105
  function onlineTrial(){
93
106
  if(global.__bpTrialCache && Date.now()-global.__bpTrialCacheAt<30000)return global.__bpTrialCache;
94
107
  const cp=require('child_process');
95
108
  const cfg=require('./config').load();
96
109
  const base=process.env.MGR_TRIAL_SERVER||cfg.licenseServer;
97
110
  if(!base)return null; // developer test installations without a configured server
111
+ // the server did not answer recently: do not wait for it again for 10 minutes (firewalls, proxies, no internet)
112
+ try{const o=JSON.parse(fs.readFileSync(OFFLINE_FILE(),'utf8'));if(o.base===base&&Date.now()<o.until&&o.until<=Date.now()+10*60*1000)return null;}catch{}
98
113
  const device=deviceId();
99
114
  const url=new URL('/api/trial/start',base).href;
100
- const childCode="const u=process.argv[1],d=process.argv[2],m=u.startsWith('https:')?require('https'):require('http');const r=m.request(u,{method:'POST',headers:{'content-type':'application/json'},timeout:3000},s=>{let b='';s.on('data',x=>b+=x);s.on('end',()=>{if(s.statusCode!==200)process.exit(4);try{const v=JSON.parse(b);if(!v.ok||!['trial','expired'].includes(v.status)||!Number.isInteger(v.daysLeft))process.exit(5);process.stdout.write(JSON.stringify(v))}catch{process.exit(6)}})});r.on('timeout',()=>r.destroy());r.on('error',()=>process.exit(7));r.end(JSON.stringify({device:d}))";
101
- const r=cp.spawnSync(process.execPath,['-e',childCode,url,device],{encoding:'utf8',timeout:4500,windowsHide:true});
102
- if(r.status!==0||r.error)return null; // server unreachable: use the local trial clock, never lock a user out because of the network
103
- try{const result=JSON.parse(r.stdout);global.__bpTrialCache=result;global.__bpTrialCacheAt=Date.now();return result}catch{return null}
115
+ const childCode="const u=process.argv[1],d=process.argv[2],m=u.startsWith('https:')?require('https'):require('http');const r=m.request(u,{method:'POST',headers:{'content-type':'application/json'},timeout:2500},s=>{let b='';s.on('data',x=>b+=x);s.on('end',()=>{if(s.statusCode!==200)process.exit(4);try{const v=JSON.parse(b);if(!v.ok||!['trial','expired'].includes(v.status)||!Number.isInteger(v.daysLeft))process.exit(5);process.stdout.write(JSON.stringify(v))}catch{process.exit(6)}})});r.on('timeout',()=>r.destroy());r.on('error',()=>process.exit(7));r.end(JSON.stringify({device:d}))";
116
+ const r=cp.spawnSync(process.execPath,['-e',childCode,url,device],{encoding:'utf8',timeout:3500,windowsHide:true});
117
+ let result=null;
118
+ if(r.status===0&&!r.error){try{result=JSON.parse(r.stdout)}catch{result=null}}
119
+ if(!result){ // server unreachable: use the local trial clock, never lock a user out because of the network
120
+ try{fs.mkdirSync(DATA_DIR,{recursive:true});fs.writeFileSync(OFFLINE_FILE(),JSON.stringify({base,until:Date.now()+10*60*1000}))}catch{}
121
+ return null;
122
+ }
123
+ try{fs.unlinkSync(OFFLINE_FILE())}catch{}
124
+ recordServerStart(result);
125
+ global.__bpTrialCache=result;global.__bpTrialCacheAt=Date.now();return result;
104
126
  }
105
127
  function status() {
106
128
  const now = Date.now();
@@ -124,7 +146,7 @@ function status() {
124
146
  return { status:online.status, plan:'trial',label:'Trial',daysLeft:left,trialStarted:online.started||null,projects:PLANS.trial.projects,features:online.status==='trial'?PLANS.trial.features:[], ...(online.reason?{reason:online.reason}:{}) };
125
147
  }
126
148
  const start = trialStart();
127
- const left = Math.max(0, Math.ceil((start + TRIAL_DAYS * DAY - now) / DAY));
149
+ const left = Math.max(0, Math.ceil((start + TRIAL_DAYS * DAY - Math.max(now, start)) / DAY));
128
150
  return { status: left > 0 ? 'trial' : 'expired', plan: 'trial', label: 'Trial', daysLeft: left, trialStarted: new Date(start).toISOString(), projects: PLANS.trial.projects, features: left > 0 ? PLANS.trial.features : [] };
129
151
  }
130
152
 
package/core/procs.js ADDED
@@ -0,0 +1,37 @@
1
+ 'use strict';
2
+ /** Who is that process? Used before BuildProof ever stops one: only its own guard / server may be stopped. */
3
+ const fs = require('fs');
4
+ const path = require('path');
5
+ const { execSync } = require('child_process');
6
+ const ROOT = path.resolve(__dirname, '..');
7
+ const IS_WIN = process.platform === 'win32';
8
+ const cache = new Map(); // pid -> { at, cmd }
9
+
10
+ /** Command line of a process, or null when it cannot be read (cached 5 minutes per pid). */
11
+ function cmdLine(pid, fresh) {
12
+ pid = Number(pid);
13
+ if (!Number.isInteger(pid) || pid <= 0) return null;
14
+ const hit = cache.get(pid);
15
+ if (!fresh && hit && Date.now() - hit.at < 5 * 60 * 1000) return hit.cmd;
16
+ let cmd = null;
17
+ try {
18
+ if (process.platform === 'linux') cmd = fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8').split('\0').join(' ').trim() || null;
19
+ else if (IS_WIN) cmd = execSync(`powershell -NoProfile -Command "(Get-CimInstance Win32_Process -Filter 'ProcessId=${pid}').CommandLine"`, { encoding: 'utf8', windowsHide: true, timeout: 8000 }).trim() || null;
20
+ else cmd = execSync(`ps -o command= -p ${pid}`, { encoding: 'utf8', timeout: 3000 }).trim() || null;
21
+ } catch { cmd = null; }
22
+ cache.set(pid, { at: Date.now(), cmd });
23
+ return cmd;
24
+ }
25
+
26
+ /** true = a BuildProof process of this kind ('guard' | 'server'), false = something else, null = unknown. */
27
+ /** fresh = re-read now (always used right before stopping a process). */
28
+ function isOurs(pid, kind, fresh) {
29
+ const c = cmdLine(pid, fresh);
30
+ if (c == null) return null;
31
+ const n = c.replace(/\\/g, '/');
32
+ const script = kind === 'guard' ? /scripts\/guard\.js/i : /core\/server\.js/i;
33
+ const home = n.toLowerCase().includes(ROOT.replace(/\\/g, '/').toLowerCase()) || /node_modules\/buildproof\//i.test(n);
34
+ return script.test(n) && home;
35
+ }
36
+
37
+ module.exports = { cmdLine, isOurs, ROOT };
package/core/service.js CHANGED
@@ -16,13 +16,31 @@ const config = require('./config');
16
16
  const GUARD = path.join(config.ROOT, 'scripts', 'guard.js');
17
17
  const NODE = process.execPath;
18
18
 
19
- function health(port, timeoutMs = 1500) {
19
+ function healthInfo(port, timeoutMs = 1500) {
20
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); });
21
+ const req = http.get({ host: '127.0.0.1', port, path: '/healthz', timeout: timeoutMs }, (res) => {
22
+ let b = ''; res.on('data', (d) => { b += d; });
23
+ res.on('end', () => { if (res.statusCode !== 200) return resolve(null); try { resolve(JSON.parse(b)); } catch { resolve({}); } });
24
+ });
25
+ req.on('error', () => resolve(null));
26
+ req.on('timeout', () => { req.destroy(); resolve(null); });
24
27
  });
25
28
  }
29
+ async function health(port, timeoutMs) { return !!(await healthInfo(port, timeoutMs)); }
30
+
31
+ /** An older BuildProof is still answering after an update: stop it (its guard first, so it is not restarted). */
32
+ // Only processes whose command line shows they ARE BuildProof are ever stopped: never trust a PID from a file or an HTTP reply alone.
33
+ function stopOld(info) {
34
+ const { isOurs } = require('./procs');
35
+ let stopped = false;
36
+ try {
37
+ const pidFile = path.join(config.LOG_DIR, 'server_guard.pid');
38
+ const g = Number(String(fs.readFileSync(pidFile, 'utf8')).trim());
39
+ if (g > 0 && g !== process.pid && isOurs(g, 'guard', true) === true) { try { process.kill(g); } catch { /* gone */ } }
40
+ } catch { /* no guard */ }
41
+ if (info && info.pid > 0 && info.pid !== process.pid && isOurs(info.pid, 'server', true) === true) { try { process.kill(info.pid); stopped = true; } catch { /* gone */ } }
42
+ return stopped;
43
+ }
26
44
 
27
45
  function startDetached() {
28
46
  const child = spawn(NODE, [GUARD], { detached: true, stdio: 'ignore', windowsHide: true, cwd: config.ROOT, env: process.env });
@@ -74,9 +92,19 @@ function installAutostart() {
74
92
  async function ensure({ autostart = true } = {}) {
75
93
  const cfg = config.load();
76
94
  let how = 'already-running';
77
- if (!(await health(cfg.port))) {
95
+ const VERSION = require('../package.json').version;
96
+ let info = await healthInfo(cfg.port);
97
+ const older = (a, b) => { const x = String(a).split('.').map(Number), y = String(b).split('.').map(Number); for (let i = 0; i < 3; i++) { if ((x[i] || 0) !== (y[i] || 0)) return (x[i] || 0) < (y[i] || 0); } return false; };
98
+ if (info && info.ok && info.version && older(info.version, VERSION)) { // updated: replace the older service
99
+ if (stopOld(info)) {
100
+ for (let i = 0; i < 20 && info; i++) { await new Promise((r) => setTimeout(r, 300)); info = await healthInfo(cfg.port, 800); }
101
+ }
102
+ if (info) return { ok: true, how: `old-version-running(${info.version})`, autostart: null, port: cfg.port }; // could not replace it safely: keep using it
103
+ how = 'updated';
104
+ }
105
+ if (!info) {
78
106
  startDetached();
79
- how = 'started';
107
+ if (how !== 'updated') how = 'started';
80
108
  let ok = false;
81
109
  for (let i = 0; i < 40 && !ok; i++) { await new Promise((r) => setTimeout(r, 500)); ok = await health(cfg.port); }
82
110
  if (!ok) return { ok: false, how: 'start_failed', port: cfg.port };
@@ -86,4 +114,4 @@ async function ensure({ autostart = true } = {}) {
86
114
  return { ok: true, how, autostart: auto, port: cfg.port };
87
115
  }
88
116
 
89
- module.exports = { ensure, health, installAutostart, startDetached };
117
+ module.exports = { ensure, health, healthInfo, installAutostart, startDetached };
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "buildproof",
3
- "version": "3.12.1",
3
+ "version": "3.12.2",
4
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
5
  "main": "core/server.js",
6
6
  "scripts": {
package/scripts/guard.js CHANGED
@@ -28,7 +28,8 @@ const ERR_LOG = path.join(LOG_DIR, 'backend.err.log');
28
28
  const PID_FILE = path.join(LOG_DIR, 'server_guard.pid');
29
29
  const STATUS_FILE = path.join(LOG_DIR, 'server_guard.status.json');
30
30
 
31
- const PORT = parseInt(process.env.MGR_PORT || process.env.PORT || '38700', 10);
31
+ // Same port as the CLI and the server: MGR_PORT, else config.json, else 38700. Never the generic PORT variable (that is the customer's own app).
32
+ const PORT = parseInt(process.env.MGR_PORT || (() => { try { return require('../core/config').load().port; } catch { return 0; } })() || '38700', 10);
32
33
  const HEALTH_PATH = process.env.MGR_HEALTH_PATH || '/healthz';
33
34
  const CHECK_MS = parseInt(process.env.MGR_GUARD_CHECK_MS || '10000', 10);
34
35
  const HEALTH_TIMEOUT_MS = parseInt(process.env.MGR_GUARD_HEALTH_TIMEOUT_MS || '5000', 10);
@@ -49,6 +50,7 @@ let restarting = false;
49
50
  let stopping = false;
50
51
  let errTail = [];
51
52
  let lastHealthOkAt = 0;
53
+ let foreignWarned = false;
52
54
 
53
55
  function ensureLogDir() { fs.mkdirSync(LOG_DIR, { recursive: true }); }
54
56
 
@@ -91,13 +93,20 @@ function isPidAlive(pid) {
91
93
  try { process.kill(pid, 0); return true; } catch (e) { return !!(e && e.code === 'EPERM'); }
92
94
  }
93
95
 
96
+ const { cmdLine, isOurs } = require('../core/procs');
97
+ function statusFresh() {
98
+ try { return Date.now() - Date.parse(JSON.parse(fs.readFileSync(STATUS_FILE, 'utf8')).updatedAt) < 90000; } catch { return false; }
99
+ }
100
+
94
101
  function acquireLock() {
95
102
  ensureLogDir();
96
103
  try {
97
104
  if (fs.existsSync(PID_FILE)) {
98
105
  const existing = Number(String(fs.readFileSync(PID_FILE, 'utf8')).trim());
99
106
  if (existing !== process.pid && isPidAlive(existing)) {
100
- process.exit(0); // another guard is already running
107
+ // the PID may have been reused by an unrelated process after a reboot or crash: only a real BuildProof guard counts
108
+ const ours = isOurs(existing, 'guard', true);
109
+ if (ours === true || (ours === null && statusFresh())) process.exit(0); // another guard is already running
101
110
  }
102
111
  }
103
112
  } catch { /* stale lock */ }
@@ -146,9 +155,15 @@ function pidListeningOnPort(port) {
146
155
  }
147
156
  return null;
148
157
  }
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;
158
+ if (process.platform === 'linux') {
159
+ const out = execSync(`ss -ltnp 2>/dev/null | grep ':${port} ' || true`, { encoding: 'utf8' });
160
+ const m = out.match(/pid=(\d+)/);
161
+ if (m) return Number(m[1]);
162
+ }
163
+ // macOS (no ss), or Linux without ss
164
+ const out = execSync(`lsof -nP -iTCP:${Number(port)} -sTCP:LISTEN -t 2>/dev/null || true`, { encoding: 'utf8', timeout: 5000 });
165
+ const pid = Number(String(out).trim().split(/\s+/)[0]);
166
+ return pid > 0 ? pid : null;
152
167
  } catch { return null; }
153
168
  }
154
169
 
@@ -241,8 +256,8 @@ function hardRestart(reason) {
241
256
  killTree(pid);
242
257
  const holder = pidListeningOnPort(PORT);
243
258
  if (holder && holder !== process.pid) {
244
- log(`FREE-PORT killing pid=${holder} holding :${PORT}`);
245
- killTree(holder);
259
+ if (isOurs(holder, 'server', true) === true) { log(`FREE-PORT killing hung BuildProof backend pid=${holder} on :${PORT}`); killTree(holder); }
260
+ else log(`PORT-BUSY :${PORT} is held by pid=${holder}, which is not BuildProof - left alone`);
246
261
  }
247
262
  scheduleRestart(reason);
248
263
  }
@@ -268,9 +283,14 @@ async function tick() {
268
283
  if (!child) {
269
284
  const holder = pidListeningOnPort(PORT);
270
285
  if (!holder) { startBackend('not-running'); return; }
286
+ if (isOurs(holder, 'server') !== true) { // another program owns this port: never touch it
287
+ if (!foreignWarned) { log(`PORT-BUSY :${PORT} is used by pid=${holder} (not BuildProof) - waiting, nothing is killed. Set another port: MGR_PORT or "port" in config.json`); foreignWarned = true; }
288
+ writeStatus({ portBusy: true });
289
+ return;
290
+ }
271
291
  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');
292
+ log(`HEALTH-FAIL own backend pid=${holder} on :${PORT} (${consecutiveFails}/${FAILS_BEFORE_RESTART})`);
293
+ if (consecutiveFails >= FAILS_BEFORE_RESTART) hardRestart('orphan backend unhealthy');
274
294
  writeStatus();
275
295
  return;
276
296
  }
@@ -308,4 +328,4 @@ async function main() {
308
328
 
309
329
  if (require.main === module) main();
310
330
 
311
- module.exports = { checkHealth, pidListeningOnPort, memoryMb, PORT };
331
+ module.exports = { checkHealth, pidListeningOnPort, memoryMb, isOurs, cmdLine, PORT };