#!/usr/bin/env node /** * JesusOS ORIGINAL Android Termux → optional v14 resilient supervisor with adaptive 15-minute ceiling * * --audit: STRICTLY READ ONLY; no downloads, child processes or pool requests. * --selftest: local SHA256 / source-config sanity only. * --run: conscious owner opt-in to the original 2-hour bounded session. * --run-extended: explicit owner opt-in to an 8-hour monitored session. * --run-week: EXPLICIT local opt-in for one 168-hour session. * --report-only: credential-bound reporting recovery; NEVER authorizes mining. * --resume-authorized: local service recovery only while an existing consent * lease and server credential are both unexpired. It never extends either. * V14 stores the bearer only as AES-256-GCM ciphertext whose wrapping key is * derived from a non-exportable Android Keystore RSA signature. Persistent, * bounded local lifecycle records distinguish observed causes without guessing. * Local recovery may restart its own child at most 3 times after source, * credential, battery (execution only) and duplicate-worker preflight checks. * No hosted server can wake or restart a force-stopped Android application. * * Keeps original 3340 status reporter, auto-reporter and HeavenCoin UNTOUCHED. * Only opens 127.0.0.1:3334 (pool relay) and 127.0.0.1:3345 (status). * Uses existing exact watch-only first address and existing 0600 pool config. * Uses a SHORT 16-character, owner-issued, single-use pairing code (10 min TTL). * The code is exchanged over JesusOS HTTPS for an expiring private credential. * Plaintext is held in memory only; local persistence is Android-Keystore-wrapped. No 69-character token copied, no wallet keys, and * original 3340 reporter is never touched. Explicit owner opt-in only. * Without an active dedicated device token, launch FAILS CLOSED: no * repeated local-only CPU mining test. A read-only JesusOS HTTPS pairing * check must succeed BEFORE starting any mining process. * Local port and signed-source preflight finishes BEFORE asking for or * consuming a one-use device code. Failure preserves existing pairing. * With EXPLICIT original 15-minute device authorization, opted-in agent polls MAIN, receives at * most one bounded 90s 5000 H/s command per UTC quarter-hour, with >=15min * spacing between claimed missions. Requires a verified Termux:API battery * reading before and DURING local mining; local governor SKIPS work as the * battery warms, reduces to 30-minute spacing when warm, and applies * a cooldown after heat / low battery / sensor failures. No battery charging * control, no CPU thermal identity guarantee, and no Android auto-restart. * ORIGINAL v9 remains installed and works unchanged with one per UTC hour. * Mining stops on Ctrl+C, process failure or at 2h (default) / 8h * (explicit extended session) / 168h (separate explicit week choice). Each CPU work order stays capped at * 90 seconds, 5,000 H/s and at most one work order per UTC quarter-hour. * No plaintext token, automatic Android boot, remote shell or payout promise. * Optional runit/Termux:Boot integration is staged separately and requires the * owner to install/enable it; Android force-stop remains outside this process. */ import fs from 'node:fs'; import fsp from 'node:fs/promises'; import os from 'node:os'; import path from 'node:path'; import crypto from 'node:crypto'; import {spawn,execFile,spawnSync} from 'node:child_process'; import net from 'node:net'; const home=process.env.HOME||os.homedir(); const original=path.join(home,'jesusos-bitcoin-mining'); const watchDir=path.join(home,'jesusos-sovereign-wallet'); const cache=path.join(original,'.jesusos-live-pinned-v1'); const PINS={ proxy:{name:'jesusos-stratum-proxy-v1.txt',sha:'5fa74b2366c8ef8d4c7885c9885237fe0ea2d9db36821ce42a72edb9223c45a3'}, miner:{name:'jesusos-owner-cpu-miner-v1.txt',sha:'2cdc072de0f8915250651bca8aae2853136e244fe4373e4926455b2f16f554c4'}, agent:{name:'jesusos-mining-device-agent-v9.txt',sha:'3d2a396bfa22fa8a5482ac421e02a8924b624351344c0979cc01de2a5a219752'} }; const sha=b=>crypto.createHash('sha256').update(b).digest('hex'); const timestamp=()=>new Date().toISOString(); function redactSensitiveDiagnosticText(value){ return String(value).replace(/\bjmr1_[0-9a-f]{64}\b/gi,'[REDACTED_DEVICE_CREDENTIAL]') .replace(/\bBearer\s+[^\s,;"']+/gi,'Bearer [REDACTED]') .replace(/\b[A-HJ-NP-Z2-9]{16}\b/g,'[REDACTED_PAIR_CODE]').slice(0,180); } const log=(event,more={})=>console.log(JSON.stringify({at:timestamp(),event,...sanitizeLifecycleDetails(more)})); const tokenPattern=/^jmr1_[0-9a-f]{64}$/; const mainFile=path.join(original,'jesusos-pool-settings.env'); const watchFile=path.join(watchDir,'watch.json'); const resilienceDir=path.join(original,'.jesusos-resilience-v14'); const credentialFile=path.join(resilienceDir,'device-credential.enc.json'); const consentFile=path.join(resilienceDir,'execution-consent.json'); const lifecycleFile=path.join(resilienceDir,'lifecycle.jsonl'); const activeFile=path.join(resilienceDir,'active-session.json'); const lockFile=path.join(resilienceDir,'supervisor.lock'); const guardFile=path.join(resilienceDir,'supervisor.guard'); const keyAlias='jesusos-bitcoin-device-v14'; const sessionId=crypto.randomUUID(); const credentialAad=Buffer.from('jesusos.bitcoin.device-credential.v14','utf8'); const MAX_LIFECYCLE_RECORDS=256; let lockHeld=false,guardFd=null; const safeDirectory=(d,onlyOwner=false)=>{ const s=fs.lstatSync(d); if(!s.isDirectory()||s.isSymbolicLink()||(s.mode&(onlyOwner?0o077:0o022))!==0) throw Error('Unsafe or non-directory original workspace: '+path.basename(d)); }; function privateFile(filename,max=8192){ const s=fs.lstatSync(filename); if(!s.isFile()||s.isSymbolicLink()||(s.mode&0o077)!==0||s.size>max) throw Error('Original public-config file missing safe 0600 permissions or valid type: '+path.basename(filename)); return fs.readFileSync(filename,'utf8'); } function parsePool(text){ const fields=new Map(); for(const line of text.split(/\r?\n/)){ if(!line.trim()||line.startsWith('#'))continue; const m=line.match(/^([A-Z][A-Z0-9_]*)=([^\r\n]*)$/); if(!m||fields.has(m[1]))throw Error('Pool settings malformed or duplicated; no mining started.'); fields.set(m[1],m[2]); } const pool={ host:fields.get('STRATUM_HOST'),port:fields.get('STRATUM_PORT'), tls:fields.get('STRATUM_TLS'),worker:fields.get('STRATUM_WORKER') }; if(pool.host!=='stratum.ckpool.org'||pool.port!=='3333'||pool.tls!=='false'|| typeof pool.worker!=='string'||!/^bc1q[a-z0-9]{38,85}$/.test(pool.worker)) throw Error('Original public CKPool configuration does not meet pinned solo-mainnet requirements.'); return pool; } function validatePayout(){ safeDirectory(original); safeDirectory(watchDir,true); const settings=parsePool(privateFile(mainFile)); const data=JSON.parse(privateFile(watchFile,16384)); if(!data||data.schema!=='jesusos.btc.watchonly.bip84.v1'|| data.network!=='mainnet'||typeof data.firstAddress!=='string'|| typeof data.accountXpub!=='string'||!data.accountXpub.startsWith('xpub')) throw Error('Original watch-only manifest invalid. Original wallet never modified.'); if(settings.worker!==data.firstAddress) throw Error('Pool payout worker does NOT match original watch-only receive address. Refusing to mine.'); return settings; } async function canListen(port){ return new Promise(resolve=>{ const s=net.createServer(); s.on('error',()=>resolve(false)); s.listen(port,'127.0.0.1',()=>s.close(()=>resolve(true))); }); } function ensureResilienceDirectory(){ fs.mkdirSync(resilienceDir,{recursive:true,mode:0o700}); try{fs.chmodSync(resilienceDir,0o700)}catch{} safeDirectory(resilienceDir,true); } function atomicPrivateWrite(filename,text){ ensureResilienceDirectory(); const tmp=filename+'.tmp.'+process.pid+'.'+crypto.randomBytes(4).toString('hex'); fs.writeFileSync(tmp,text,{flag:'wx',mode:0o600}); fs.chmodSync(tmp,0o600); fs.renameSync(tmp,filename); } function readPrivateJson(filename,max=65536){return JSON.parse(privateFile(filename,max));} function sanitizeLifecycleDetails(value){ const out={}; if(!value||typeof value!=='object'||Array.isArray(value))return out; for(const [key,raw] of Object.entries(value)){ if(!/^[A-Za-z][A-Za-z0-9]{0,40}$/.test(key)||/(token|secret|pair.*code|credentialvalue)/i.test(key))continue; if(raw===null||typeof raw==='boolean'||typeof raw==='number')out[key]=raw; else if(typeof raw==='string')out[key]=redactSensitiveDiagnosticText(raw); } return out; } function appendLifecycle(event,classification,details={}){ try{ ensureResilienceDirectory(); const record=JSON.stringify({schema:'jesusos.bitcoin.lifecycle.v1',at:timestamp(), sessionId,event,classification,...sanitizeLifecycleDetails(details)}); let lines=[]; try{lines=privateFile(lifecycleFile,262144).split(/\r?\n/).filter(Boolean)} catch(e){if(e?.code!=='ENOENT')throw e} lines=lines.slice(-(MAX_LIFECYCLE_RECORDS-1));lines.push(record); atomicPrivateWrite(lifecycleFile,lines.join('\n')+'\n'); }catch(e){console.error('LOCAL DIAGNOSTIC JOURNAL UNAVAILABLE:',redactSensitiveDiagnosticText(e instanceof Error?e.message:'unknown'))} } function classifyFailure(value){ const message=String(value instanceof Error?value.message:value).toLowerCase(); if(/battery|thermal|too-warm|temperature|sensor/.test(message))return 'battery-or-thermal-safety-intervention'; if(/401|403|not authorized|invalid or revoked|expired|credential/.test(message))return 'authentication-failure'; if(/network|fetch|unavailable|timeout|timed out|econn|dns/.test(message))return 'network-failure'; if(/duplicate|already running|occupied|not-idle/.test(message))return 'duplicate-execution-prevented'; return 'unknown-termination'; } function classifyStopReason(reason){ return reason==='planned-cap'?'normal-session-expiration': reason==='operator-requested'?'operator-requested-shutdown': reason==='parent-service-signal'?'parent-process-interruption-evidence': reason==='unexpected-child-exit'?'unexpected-child-process-termination': classifyFailure(reason); } function localRecoveryWindow(now,deadline,attempts){ if(!Number.isFinite(now)||!Number.isFinite(deadline)||now>=deadline)return 'expired'; if(!Number.isSafeInteger(attempts)||attempts<0||attempts>=3)return 'exhausted'; return 'eligible'; } function recoveryOutcomeRecord(reportingRestored){ return reportingRestored? {outcome:'reporting-restored',classification:'reporting-available',reportingRestored:true}: {outcome:'failed-before-report',classification:'unexpected-child-process-termination',reportingRestored:false}; } function startTicksFromStat(stat){ const close=stat.lastIndexOf(')'); if(close<0)return null; const ticks=stat.slice(close+1).trim().split(/\s+/)[19]; return typeof ticks==='string'&&/^\d+$/.test(ticks)?ticks:null; } function supervisorIdentityMatches(prior,ticks,argv,expectedPath){ return typeof prior?.startTicks==='string'&&/^\d+$/.test(prior.startTicks)&& prior.startTicks===ticks&&Array.isArray(argv)&& ['node','nodejs'].includes(path.basename(argv[0]||''))&& argv[1]===expectedPath&& ['--run','--run-extended','--run-week','--report-only','--resume-authorized'].includes(argv[2]); } function processIsThisSupervisor(prior){ const pid=prior?.pid; if(!Number.isSafeInteger(pid)||pid<2||pid===process.pid)return false; try{ const proc='/proc/'+pid; const before=startTicksFromStat(fs.readFileSync(proc+'/stat','utf8')); const argv=fs.readFileSync(proc+'/cmdline','utf8').split('\0'); const after=startTicksFromStat(fs.readFileSync(proc+'/stat','utf8')); return before!==null&&before===after&&supervisorIdentityMatches(prior,after,argv, path.join(original,'jesusos-termux-live-agent-v14.mjs')); }catch{return false} } function supervisorIdentityHasExited(prior,inspect=(pid)=>{ const proc='/proc/'+pid; const before=startTicksFromStat(fs.readFileSync(proc+'/stat','utf8')); const argv=fs.readFileSync(proc+'/cmdline','utf8').split('\0'); const after=startTicksFromStat(fs.readFileSync(proc+'/stat','utf8')); return {before,after,argv}; },expectedPath=path.join(original,'jesusos-termux-live-agent-v14.mjs')){ if(!Number.isSafeInteger(prior?.pid)||prior.pid<2|| typeof prior?.startTicks!=='string'||!/^[0-9]+$/.test(prior.startTicks))return false; let observed; try{observed=inspect(prior.pid)}catch(e){ return e?.code==='ENOENT'||e?.code==='ESRCH'; } if(!observed||typeof observed!=='object')return false; if(typeof observed.before!=='string'||typeof observed.after!=='string')return false; if(observed.before!==prior.startTicks||observed.after!==prior.startTicks)return true; return !supervisorIdentityMatches(prior,observed.after,observed.argv,expectedPath); } async function waitForSupervisorExit(prior,timeoutMs=8000){ const deadline=Date.now()+timeoutMs; do{ if(supervisorIdentityHasExited(prior))return true; await new Promise(resolve=>setTimeout(resolve,250)); }while(Date.now()process.kill(pid,'SIGINT')){ const pid=prior?.pid; if(!Number.isSafeInteger(pid)||pid<2||!isSupervisor(prior)) return {signalDelivered:false,signalOutcome:'no-identifiable-supervisor',stopVerified:false}; try{ if(send(pid)!==true)return {signalDelivered:false,signalOutcome:'signal-request-failed',stopVerified:false}; return {signalDelivered:true,signalOutcome:'signal-request-accepted',stopVerified:false}; }catch{return {signalDelivered:false,signalOutcome:'signal-request-failed',stopVerified:false}} } function staleGuardedLockReclaimable(prior,probe=pid=>process.kill(pid,0)){ if(prior?.lockProtocol!=='flock-v1'||!Number.isSafeInteger(prior.pid)||prior.pid<2|| prior.pid===process.pid||typeof prior.startTicks!=='string'||!/^\d+$/.test(prior.startTicks)|| typeof prior.sessionId!=='string'||!/^[0-9a-f-]{36}$/i.test(prior.sessionId))return false; try{probe(prior.pid);return false}catch(e){return e?.code==='ESRCH'} } function acquireKernelGuard(){ const fd=fs.openSync(guardFile,fs.constants.O_CREAT|fs.constants.O_RDWR|fs.constants.O_NOFOLLOW,0o600); try{ const opened=fs.fstatSync(fd),named=fs.lstatSync(guardFile); if(!opened.isFile()||!named.isFile()||named.isSymbolicLink()|| (opened.mode&0o077)!==0||opened.dev!==named.dev||opened.ino!==named.ino) throw Error('Unsafe V14 supervisor guard; refusing execution.'); const result=spawnSync('flock',['-n','-E','75','-x','3'],{stdio:['ignore','ignore','ignore',fd],timeout:5000}); if(result.status!==0||result.error){ if(result.status===75)throw Error('V14 supervisor guard already held; duplicate execution refused.'); throw Error('OS-backed flock unavailable or failed; V14 recovery refused. Verify Termux util-linux locally.'); } guardFd=fd; }catch(e){fs.closeSync(fd);throw e} } function releaseSupervisorLock(){ try{ if(lockHeld){ const current=readPrivateJson(lockFile,2048); if(current?.pid===process.pid&¤t?.sessionId===sessionId)fs.unlinkSync(lockFile); } }catch{} lockHeld=false; if(guardFd!==null){try{fs.closeSync(guardFd)}catch{}guardFd=null} } function acquireSupervisorLock(){ ensureResilienceDirectory(); acquireKernelGuard(); process.once('exit',releaseSupervisorLock); const write=()=>{ const startTicks=startTicksFromStat(fs.readFileSync('/proc/self/stat','utf8')); if(startTicks===null)throw Error('Cannot establish local supervisor start identity; refusing execution.'); const fd=fs.openSync(lockFile,'wx',0o600); try{fs.writeFileSync(fd,JSON.stringify({pid:process.pid,sessionId,startTicks,lockProtocol:'flock-v1',startedAt:timestamp()}))} finally{fs.closeSync(fd)} lockHeld=true; }; try{write()}catch(e){ if(e?.code!=='EEXIST')throw e; const st=fs.lstatSync(lockFile); if(!st.isFile()||st.isSymbolicLink()||(st.mode&0o077)!==0) throw Error('Unsafe V14 supervisor lock; refusing execution.'); let prior={};try{prior=readPrivateJson(lockFile,2048)}catch{} if(processIsThisSupervisor(prior)) throw Error('V14 supervisor already running; duplicate execution refused.'); if(!staleGuardedLockReclaimable(prior)) throw Error('Ambiguous V14 supervisor lock; local inspection required before removal. Duplicate execution refused.'); fs.unlinkSync(lockFile); write(); appendLifecycle('stale-supervisor-lock-reclaimed','parent-process-interruption-evidence',{ lockProtocol:'flock-v1',priorProcessAbsent:true,causeEstablished:false }); } let previous=null;try{previous=readPrivateJson(activeFile,8192)}catch{} if(previous?.state==='running'&&previous?.sessionId!==sessionId){ appendLifecycle('prior-parent-marker-found','parent-process-interruption-evidence',{ priorSessionId:String(previous.sessionId||'unknown'),evidence:'unclean-running-marker', causeEstablished:false }); } } function writeActiveState(state,details={}){ atomicPrivateWrite(activeFile,JSON.stringify({schema:'jesusos.bitcoin.active-session.v1', sessionId,pid:process.pid,state,updatedAt:timestamp(),...sanitizeLifecycleDetails(details)})); } async function runKeystore(args,input='',timeoutMs=12000){ return new Promise((resolve,reject)=>{ const child=spawn('termux-keystore',args,{stdio:['pipe','pipe','pipe']}); let stdout='',stderr='',settled=false; const finish=(error,value)=>{if(settled)return;settled=true;clearTimeout(timer);error?reject(error):resolve(value);}; child.stdout.setEncoding('utf8');child.stderr.setEncoding('utf8'); child.stdout.on('data',d=>{stdout=(stdout+d).slice(-65536)}); child.stderr.on('data',d=>{stderr=(stderr+d).slice(-2048)}); child.on('error',()=>finish(Error('Android Keystore command unavailable'))); child.on('close',code=>code===0?finish(null,stdout.trim()): finish(Error('Android Keystore operation failed with exit '+String(code)))); const timer=setTimeout(()=>{try{child.kill('SIGTERM')}catch{} finish(Error('Android Keystore operation timed out'))},timeoutMs); child.stdin.end(input); }); } async function ensureKeystoreKey(allowCreate){ let listed; try{listed=JSON.parse(await runKeystore(['list','-d']))} catch{throw Error('Termux:API Android Keystore is unavailable or returned invalid data')} if(!Array.isArray(listed))throw Error('Android Keystore listing invalid'); const existing=listed.find(x=>x&&x.alias===keyAlias); if(existing)return; if(!allowCreate)throw Error('Android Keystore credential key missing; explicit owner pairing required'); await runKeystore(['generate',keyAlias,'-a','RSA','-s','2048']); listed=JSON.parse(await runKeystore(['list','-d'])); if(!Array.isArray(listed)||!listed.some(x=>x&&x.alias===keyAlias)) throw Error('Android Keystore key creation could not be verified'); } async function deriveCredentialWrapKey(allowCreate){ await ensureKeystoreKey(allowCreate); const context='JesusOS Bitcoin device credential wrap v14\n'+keyAlias; const signature=await runKeystore(['sign',keyAlias,'SHA256withRSA'],context); let bytes;try{bytes=Buffer.from(signature,'base64')}catch{} if(!bytes||bytes.length<128)throw Error('Android Keystore signature output invalid'); return crypto.createHash('sha256').update(bytes).update(credentialAad).digest(); } function sealCredentialPayload(payload,key,iv=crypto.randomBytes(12)){ const cipher=crypto.createCipheriv('aes-256-gcm',key,iv);cipher.setAAD(credentialAad); const encrypted=Buffer.concat([cipher.update(JSON.stringify(payload),'utf8'),cipher.final()]); return {schema:'jesusos.bitcoin.encrypted-device-credential.v14', iv:iv.toString('base64'),tag:cipher.getAuthTag().toString('base64'), ciphertext:encrypted.toString('base64'),expiresAt:payload.expiresAt, authorizationHours:payload.authorizationHours}; } function openCredentialPayload(envelope,key){ if(!envelope||envelope.schema!=='jesusos.bitcoin.encrypted-device-credential.v14')throw Error('Credential envelope schema invalid'); const iv=Buffer.from(envelope.iv,'base64'),tag=Buffer.from(envelope.tag,'base64'); const ciphertext=Buffer.from(envelope.ciphertext,'base64'); if(iv.length!==12||tag.length!==16||ciphertext.length<16||ciphertext.length>4096) throw Error('Credential envelope invalid'); const decipher=crypto.createDecipheriv('aes-256-gcm',key,iv);decipher.setAAD(credentialAad); decipher.setAuthTag(tag); return JSON.parse(Buffer.concat([decipher.update(ciphertext),decipher.final()]).toString('utf8')); } async function saveStoredCredential(data){ const key=await deriveCredentialWrapKey(true); atomicPrivateWrite(credentialFile,JSON.stringify(sealCredentialPayload({ token:data.token,expiresAt:data.expiresAt,authorizationHours:data.authorizationHours, scope:'owner-scoped-device-agent' },key))); appendLifecycle('credential-stored','authentication-continuity',{ storage:'android-keystore-wrapped-aes-gcm',expiresAt:data.expiresAt,plaintextOnDisk:false }); } async function loadStoredCredential(){ ensureResilienceDirectory(); if(!fs.existsSync(credentialFile))return null; try{ const envelope=readPrivateJson(credentialFile,8192); if(!Number.isFinite(Date.parse(envelope?.expiresAt))||Date.parse(envelope.expiresAt)<=Date.now()){ fs.unlinkSync(credentialFile); appendLifecycle('credential-expired','authentication-failure',{expiredAt:String(envelope?.expiresAt||'unknown')}); return null; } const key=await deriveCredentialWrapKey(false); const data=openCredentialPayload(envelope,key); if(!data||!tokenPattern.test(data.token)||data.scope!=='owner-scoped-device-agent'|| ![2,8,168].includes(data.authorizationHours)||data.expiresAt!==envelope.expiresAt) throw Error('Recovered credential payload invalid'); return data; }catch(e){ appendLifecycle('credential-recovery-failed',classifyFailure(e),{reason:redactSensitiveDiagnosticText(e instanceof Error?e.message:'unknown')}); return null; } } function boundedAuthorizationDeadline(nowMs,hours,serverExpiresAt){ const localDeadline=nowMs+hours*60*60*1000; const serverDeadline=Date.parse(serverExpiresAt); if(!Number.isFinite(serverDeadline)||serverDeadline<=nowMs)throw Error('Server credential authorization expired'); return new Date(Math.min(localDeadline,serverDeadline)).toISOString(); } function saveConsentLease(hours,serverExpiresAt){ const expiresAt=boundedAuthorizationDeadline(Date.now(),hours,serverExpiresAt); const lease={schema:'jesusos.bitcoin.execution-consent.v14',state:'active', sessionId,createdAt:timestamp(),expiresAt,selectedHours:hours, mayMine:true,serverCredentialExpiresAt:serverExpiresAt}; atomicPrivateWrite(consentFile,JSON.stringify(lease)); appendLifecycle('execution-consent-recorded','operator-requested-authorization',{ selectedHours:hours,expiresAt,extendedExistingAuthorization:false }); return lease; } function loadActiveConsentLease(){ let lease;try{lease=readPrivateJson(consentFile,8192)}catch{return null} if(!lease||lease.schema!=='jesusos.bitcoin.execution-consent.v14'||lease.state!=='active'|| lease.mayMine!==true||![2,8,168].includes(lease.selectedHours)|| !Number.isFinite(Date.parse(lease.expiresAt))||Date.parse(lease.expiresAt)<=Date.now()|| !Number.isFinite(Date.parse(lease.serverCredentialExpiresAt))|| Date.parse(lease.expiresAt)>Date.parse(lease.serverCredentialExpiresAt))return null; return lease; } function endConsentLease(reason){ let lease;try{lease=readPrivateJson(consentFile,8192)}catch{return} if(lease?.schema!=='jesusos.bitcoin.execution-consent.v14'||lease.state!=='active')return; atomicPrivateWrite(consentFile,JSON.stringify({...lease,state:'ended',endedAt:timestamp(),endReason:reason})); } async function secretCheck(){ const direct=process.env.JESUSOS_MINING_DEVICE_TOKEN||''; delete process.env.JESUSOS_MINING_DEVICE_TOKEN; if(direct)throw Error('V14 refuses plaintext environment credentials; use Android-Keystore recovery or explicit pairing'); return loadStoredCredential(); } /** Private original Termux short-code prompt. Accept ONLY 16 owner-issued * uppercase base32 characters. No terminal echo. No shell command can be * interpreted as a pairing code. Ctrl+C cancels all operations. */ const pairCodePattern=/^[A-HJ-NP-Z2-9]{16}$/; async function readShortDevicePairCode(){ const input=process.stdin; if(!input.isTTY||!process.stdout.isTTY||typeof input.setRawMode!=='function') return null; process.stdout.write('PASTE 16-character JesusOS pairing CODE ONLY (not command, Enter=submit, Ctrl+C=cancel): '); const previousRaw=Boolean(input.isRaw); return new Promise((resolve,reject)=>{ let code='',finished=false; function cleanup(){ if(finished)return; finished=true; input.off('data',onData); try{input.setRawMode(previousRaw)}catch{} if(!previousRaw)input.pause(); process.stdout.write('\n'); } function onData(chunk){ for(const ch of String(chunk)){ if(ch==='\r'||ch==='\n'){ cleanup(); if(!pairCodePattern.test(code))reject(Error('Expected exactly 16 pairing-code letters/digits FROM JesusOS. Do NOT paste a shell command or the 69-character token here.')); else resolve(code); return; } if(ch==='\u0003'){cleanup();reject(Error('Operator cancelled pairing; no mining started.'));return} if(ch==='\u007f'||ch==='\b'){code=code.slice(0,-1);continue} if(ch==='\u001b'){cleanup();reject(Error('Unexpected terminal escape; pairing cancelled.'));return} if(ch===' '||ch==='-')continue; if(ch>='!'&&ch<='~'){ if(code.length>=24){ cleanup();reject(Error('This prompt takes ONLY the 16-character pairing code shown in JesusOS—not a shell command. Nothing started.'));return; } code+=ch.toUpperCase(); } } } try{input.setRawMode(true);input.setEncoding('utf8');input.on('data',onData);input.resume()} catch{cleanup();reject(Error('Private terminal input unavailable. No miner started.'))} }); } /** Claim a one-use high-entropy short code; only server returns device * credential over HTTPS, in memory. Old 3340 reporter remains valid. */ async function claimShortCode(code){ const body=JSON.stringify({schema:'jesusos.bitcoin.device-short-claim.v1',code, mode:'opt-in-15m-v1'}); let response; try{ response=await fetch('https://jesusos.online/_api/bitcoin-mining-device-short-claim',{ method:'POST',redirect:'error',cache:'no-store',signal:AbortSignal.timeout(12000), headers:{'Content-Type':'application/json'},body }); }catch{throw Error('JesusOS pairing network unavailable. Nothing started. Generate a new short code and retry.')} if(!response.ok){ throw Error('Short pairing code was invalid, expired or already used (HTTP '+response.status+'). No mining started. Generate a new code in JesusOS.'); } let data; try{data=await response.json()}catch{throw Error('Unexpected pairing response; no mining started')} if(!data||data.schema!=='jesusos.bitcoin.device-short-claim.v1'|| data.authorized!==true||!tokenPattern.test(data.token)|| data.originalLegacyReporterUnchanged!==true||data.noWalletKeysUsed!==true|| data.bitcoinPayoutVerified!==false||data.scope!=='bounded-cpu-stratum'|| data.selectedDeviceCadence!=='15m'||![2,8,168].includes(data.authorizationHours)|| typeof data.expiresAt!=='string'||!Number.isFinite(Date.parse(data.expiresAt))|| Date.parse(data.expiresAt)<=Date.now()) throw Error('Unexpected or expired device authorization; no mining started'); await saveStoredCredential(data); log('owner_short_code_pairing_success',{legacyReporterPreserved:true, privateCredentialNotPrinted:true,credentialStoredEncrypted:true, expiresAt:data.expiresAt,authorizationHours:data.authorizationHours}); return {token:data.token,expiresAt:data.expiresAt,authorizationHours:data.authorizationHours}; } const mode=process.argv[2]||'--audit'; const explicitMode=mode==='--run'||mode==='--run-extended'||mode==='--run-week'; const resumeMode=mode==='--resume-authorized'; const reportOnlyMode=mode==='--report-only'; const activeMode=explicitMode||resumeMode||reportOnlyMode; const executionMode=explicitMode||resumeMode; let maxSessionHours=mode==='--run-week'?168:mode==='--run-extended'?8:mode==='--run'?2:0; if(mode==='--selftest'){ if(sha('abc')!=='ba7816bf8f01cfea414140de5dae2223b00361a396177a9cb410ff61f20015ad') throw Error('SHA256 selftest failed.'); if(Object.values(PINS).length!==3||new Set(Object.values(PINS).map(x=>x.sha)).size!==3) throw Error('Pinned sources invalid.'); const testKey=Buffer.alloc(32,7),testPayload={token:'jmr1_'+'a'.repeat(64), expiresAt:'2026-12-06T23:18:47.178Z',authorizationHours:168,scope:'owner-scoped-device-agent'}; const sealed=sealCredentialPayload(testPayload,testKey,Buffer.alloc(12,3)); const testNow=Date.parse('2026-11-29T23:18:47.178Z'); const testPairCode='ABCDEFGHJKLMNPQR'; const sensitiveText='Bearer '+testPayload.token+' pair='+testPairCode; const redactedText=redactSensitiveDiagnosticText(sensitiveText); const journalReason=sanitizeLifecycleDetails({reason:sensitiveText}).reason; if(redactedText.includes(testPayload.token)||redactedText.includes(testPairCode)|| journalReason.includes(testPayload.token)||journalReason.includes(testPairCode)) throw Error('Sensitive diagnostic redaction selftest failed.'); if(openCredentialPayload(sealed,testKey).token!==testPayload.token|| classifyFailure(Error('HTTP 401'))!=='authentication-failure'|| classifyFailure(Error('battery too warm'))!=='battery-or-thermal-safety-intervention'|| classifyFailure(Error('network timeout'))!=='network-failure'|| classifyFailure(Error('duplicate already running'))!=='duplicate-execution-prevented'|| classifyFailure(Error('child vanished without evidence'))!=='unknown-termination'|| classifyStopReason('unexpected-child-exit')!=='unexpected-child-process-termination'|| classifyStopReason('parent-service-signal')!=='parent-process-interruption-evidence'|| classifyStopReason('planned-cap')!=='normal-session-expiration'|| classifyStopReason('operator-requested')!=='operator-requested-shutdown'|| localRecoveryWindow(testNow,testNow+60000,0)!=='eligible'|| localRecoveryWindow(testNow,testNow+60000,3)!=='exhausted'|| localRecoveryWindow(testNow,testNow,0)!=='expired'|| recoveryOutcomeRecord(true).outcome!=='reporting-restored'|| recoveryOutcomeRecord(true).reportingRestored!==true|| recoveryOutcomeRecord(false).outcome!=='failed-before-report'|| recoveryOutcomeRecord(false).reportingRestored!==false|| classifyFailure(Error('device-report network timeout'))!=='network-failure'|| boundedAuthorizationDeadline(testNow,168, '2026-11-29T23:20:47.178Z')!=='2026-11-29T23:20:47.178Z') throw Error('Credential/lifecycle selftest failed.'); const noSignal=()=>{throw Error('unexpected signal attempt')}; let sent=0; const accepted=emergencySignalOutcome({pid:123},()=>true,()=>{sent++;return true}); const missing=emergencySignalOutcome(null,()=>true,noSignal); const stale=emergencySignalOutcome({pid:123},()=>false,noSignal); const refused=emergencySignalOutcome({pid:123},()=>true,()=>false); const failed=emergencySignalOutcome({pid:123},()=>true,()=>{throw Error('ESRCH')}); if(sent!==1||!accepted.signalDelivered||accepted.stopVerified|| accepted.signalOutcome!=='signal-request-accepted'|| [missing,stale,refused,failed].some(x=>x.signalDelivered||x.stopVerified)|| missing.signalOutcome!=='no-identifiable-supervisor'||stale.signalOutcome!=='no-identifiable-supervisor'|| refused.signalOutcome!=='signal-request-failed'||failed.signalOutcome!=='signal-request-failed') throw Error('Emergency stop evidence selftest failed.'); const testPath='/test/jesusos-termux-live-agent-v14.mjs'; const exitedPrior={pid:123,startTicks:'4567'}; const sameProcess=()=>({before:'4567',after:'4567',argv:['/bin/node',testPath,'--report-only']}); const replacedProcess=()=>({before:'5678',after:'5678',argv:['/bin/node',testPath,'--report-only']}); const unreadableIdentity=()=>({before:null,after:null,argv:['/bin/node',testPath,'--report-only']}); const goneProcess=()=>{throw Object.assign(Error('gone'),{code:'ENOENT'})}; const unreadableProcess=()=>{throw Object.assign(Error('denied'),{code:'EACCES'})}; if(supervisorIdentityHasExited(exitedPrior,sameProcess,testPath)|| !supervisorIdentityHasExited(exitedPrior,replacedProcess,testPath)|| !supervisorIdentityHasExited(exitedPrior,goneProcess,testPath)|| supervisorIdentityHasExited(exitedPrior,unreadableIdentity,testPath)|| supervisorIdentityHasExited(exitedPrior,unreadableProcess,testPath)) throw Error('Emergency stop exit-verification selftest failed.'); const stat='123 (name with ) parentheses) '+['S',...Array(18).fill('0'),'4567'].join(' '); const argv=['/bin/node',testPath,'--report-only']; const identity={pid:123,startTicks:'4567'}; if(startTicksFromStat(stat)!=='4567'||startTicksFromStat('invalid')!==null|| !supervisorIdentityMatches(identity,'4567',argv,testPath)|| supervisorIdentityMatches(identity,'4568',argv,testPath)|| supervisorIdentityMatches({pid:123},'4567',argv,testPath)|| supervisorIdentityMatches(identity,'4567',['/bin/node','/tmp/other.mjs',testPath],testPath)|| supervisorIdentityMatches(identity,'4567',['/bin/node',testPath,'--audit'],testPath)) throw Error('Supervisor identity selftest failed.'); const dead=()=>{throw Object.assign(Error('absent'),{code:'ESRCH'})}; const denied=()=>{throw Object.assign(Error('denied'),{code:'EPERM'})}; const guarded={pid:123,startTicks:'4567',sessionId:'12345678-1234-1234-1234-123456789abc',lockProtocol:'flock-v1'}; if(!staleGuardedLockReclaimable(guarded,dead)|| staleGuardedLockReclaimable(guarded,()=>true)|| staleGuardedLockReclaimable(guarded,denied)|| staleGuardedLockReclaimable({...guarded,lockProtocol:undefined},dead)|| staleGuardedLockReclaimable({...guarded,startTicks:undefined},dead)) throw Error('Guarded stale-lock policy selftest failed.'); log('selftest_ok',{mode:'local-only',networkRequests:0,spawnedProcesses:0, plaintextCredentialPersisted:false,boundedLifecycleDiagnostics:true}); process.exit(0); } if(mode==='--emergency-stop'){ ensureResilienceDirectory();endConsentLease('local-emergency-stop'); let prior=null;try{prior=readPrivateJson(lockFile,2048)}catch{} const outcome=emergencySignalOutcome(prior); if(outcome.signalDelivered){ outcome.stopVerified=await waitForSupervisorExit(prior); outcome.stopOutcome=outcome.stopVerified?'supervisor-exit-observed':'supervisor-exit-not-observed'; } appendLifecycle('emergency-stop-requested','operator-requested-shutdown',outcome); console.log('Emergency stop requested: '+outcome.signalOutcome+'; process termination '+ (outcome.stopVerified?'verified':'not verified')+'. Inspect locally if not verified.'); process.exit(0); } if(mode!=='--audit'&&!activeMode){ console.error('Use --audit, --selftest, --run (2h), --run-extended (8h), --run-week (168h), --report-only, --resume-authorized, or --emergency-stop.'); process.exit(2); } let settings,credential=null; try{ settings=validatePayout(); if(activeMode)acquireSupervisorLock(); credential=activeMode?await secretCheck():null; }catch(e){ if(activeMode)appendLifecycle('startup-refused',classifyFailure(e),{reason:e instanceof Error?e.message:'configuration-invalid'}); console.error('LIVE MINING REFUSED:',redactSensitiveDiagnosticText(e instanceof Error?e.message:'Configuration invalid'));process.exit(2) } const relayFree=await canListen(3334),statusFree=await canListen(3345); const report={ schema:'jesusos.bitcoin.termux-live-agent-readiness.v1', mode:mode==='--audit'?'READ_ONLY_AUDIT':'OPERATOR_OPT_IN', payoutMatchesOriginalWatchOnly:true, soloPool:'stratum.ckpool.org:3333', originalStatus3340:'UNTOUCHED', safeRelay3334Free:relayFree, safeStatus3345Free:statusFree, dedicatedDeviceCredentialProvided:!!credential, secureCredentialContinuity:'android-keystore-wrapped-aes-256-gcm', sessionMaxHours:maxSessionHours||null, deviceCadence:'explicit-v11-opt-in-15m-v1', localBatterySafety:'Termux:API adaptive local governor, pause if warm/low or unavailable', actualReporterCredentialValueNeverPrinted:true, agentMode:credential?'existing-encrypted-device-credential-recovered': explicitMode?'pairing-after-local-and-source-preflight': activeMode?'recovery-requires-existing-credential':'not-authorized-no-mining', actualMinerRunning:false, bitcoinPayoutVerified:false, heavenCoinTouched:false }; console.log('=== JesusOS ORIGINAL Bitcoin LIVE miner activation ==='); console.log(JSON.stringify(report,null,2)); if(mode==='--audit'){ console.log('READ ONLY audit completed. No mining, source downloads, process signals or wallet changes.'); process.exit(0); } async function verifyDedicatedDevicePairing(credential){ const body=JSON.stringify({schema:'jesusos.bitcoin.device-pair-check.v1',action:'verify'}); let response; try{ response=await fetch('https://jesusos.online/_api/bitcoin-mining-device-pair',{ method:'POST',redirect:'error',cache:'no-store',signal:AbortSignal.timeout(9000), headers:{'Content-Type':'application/json','Authorization':'Bearer '+credential}, body }); }catch{throw Error('Original device pairing network unavailable; no mining started')} if(!response.ok)throw Error('Dedicated device credential invalid, expired or revoked (HTTP '+response.status+'); no mining started'); let v; try{v=await response.json()}catch{throw Error('Pairing response invalid; no mining started')} if(!v||v.schema!=='jesusos.bitcoin.device-pair-check.v1'||v.authorized!==true|| v.scope!=='bounded-cpu-stratum'||v.originalLegacyReporterUnchanged!==true|| v.physicalDeviceAttested!==false||v.actualHashesVerified!==false|| v.bitcoinPayoutVerified!==false||v.heavenCoinMinted!==false|| v.selectedDeviceCadence!=='15m'||typeof v.expiresAt!=='string'|| !Number.isFinite(Date.parse(v.expiresAt))||Date.parse(v.expiresAt)<=Date.now()) throw Error('Unexpected or expired pairing response; no mining started'); log('dedicated_device_pair_authorized',{oldReporterUnchanged:true,hardwareNotAttested:true, noPayoutInferred:true,expiresAt:v.expiresAt}); return v; } if(!relayFree||!statusFree){ if(activeMode)appendLifecycle('startup-refused','duplicate-execution-prevented',{ relay3334Free:relayFree,status3345Free:statusFree}); console.error('LIVE MINING REFUSED: reserved ports 3334 or 3345 occupied. Existing V13/HeavenCoin processes remain untouched; do not start V14 beside them.'); process.exit(3); } async function pinnedFile(entry){ await fsp.mkdir(cache,{recursive:true,mode:0o700}); safeDirectory(cache,true); const dest=path.join(cache,entry.name+'.mjs'); try{ const prior=await fsp.readFile(dest); const st=fs.lstatSync(dest); if(st.isSymbolicLink()||!st.isFile()||(st.mode&0o077)!==0||sha(prior)!==entry.sha) throw Error('Pinned local cache file mismatch; original file preserved.'); return dest; }catch(e){if(e?.code!=='ENOENT')throw e} const response=await fetch('https://jesusos.online/'+entry.name,{ redirect:'error',signal:AbortSignal.timeout(12500),cache:'no-store' }); if(!response.ok)throw Error('Pinned original worker source unavailable: '+entry.name); const bytes=Buffer.from(await response.arrayBuffer()); if(bytes.length<1000||bytes.length>25000||sha(bytes)!==entry.sha) throw Error('Pinned source SHA-256 mismatch: '+entry.name+'; refusing execution.'); const tmp=dest+'.tmp.'+process.pid; await fsp.writeFile(tmp,bytes,{flag:'wx',mode:0o600}); if(sha(await fsp.readFile(tmp))!==entry.sha)throw Error('Temporary pinned source readback mismatch.'); await fsp.rename(tmp,dest); return dest; } let paths; try{ paths={ proxy:await pinnedFile(PINS.proxy), miner:await pinnedFile(PINS.miner), agent:await pinnedFile(PINS.agent) }; }catch(e){console.error('LIVE MINING REFUSED:',redactSensitiveDiagnosticText(e instanceof Error?e.message:'source validation'));process.exit(4)} /** No private pairing code is consumed unless the local battery sensor is * actually available and reports plausible safe values. This is an explicit * run-mode preflight only; --audit remains fully child-process free. */ async function requireLocalBatterySensor(){ return new Promise((resolve,reject)=>{ execFile('termux-battery-status',[],{timeout:5000,maxBuffer:4096}, (err,stdout)=>{ if(err){reject(Error('Termux:API battery sensor unavailable; install Termux:API and allow permissions BEFORE pairing.'));return;} try{ const b=JSON.parse(stdout); if(typeof b.temperature!=='number'||!Number.isFinite(b.temperature)|| !Number.isInteger(b.percentage)||b.temperature<10||b.temperature>60|| b.percentage<0||b.percentage>100||b.temperature>=38||b.percentage<30){ reject(Error('Battery temperature/charge unsafe or invalid; private pairing code not consumed.'));return; } resolve(true); }catch(e){reject(Error('Invalid battery sensor JSON; pairing code not consumed.'))} }); }); } // Local-only ports AND exact SHA-256 sources have been verified before // consuming the short code. Failed preflight must never revoke an earlier // device key or waste a one-use, ten-minute owner-issued pairing code. let serverAuthorization=null,consentLease=null,supervisorDeadline=0; if(activeMode){ try{ if(executionMode){ await requireLocalBatterySensor(); log('local_battery_sensor_preflight_passed',{thermalAndChargeGuard:'eligible-to-supervise',chargingControl:false}); } if(!credential){ if(!explicitMode)throw Error('Existing encrypted device credential unavailable; explicit owner pairing required'); const code=await readShortDevicePairCode(); if(!code)throw Error('No short pairing code entered. No mining started.'); credential=await claimShortCode(code); } serverAuthorization=await verifyDedicatedDevicePairing(credential.token); if(explicitMode){ if(credential.authorizationHours{ const proc=spawn(process.execPath,[filename,name==='agent'?'--run':'--mine'],{ env,stdio:['ignore','inherit','inherit'] }); children.add(proc); proc.on('error',e=>{log('child_error',{name,code:e.code||'unknown'});stop('child-error')}); proc.on('exit',(code,signal)=>{children.delete(proc); log('child_exited',{name,code,signal:signal||null}); if(!stopping&&name!=='miner')stop('child-exited'); }); return proc; }; function stop(reason){ if(stopping)return; stopping=true; if(recoveryTimer!==null){clearTimeout(recoveryTimer);recoveryTimer=null;} const classification=classifyStopReason(reason); if(reason==='planned-cap'||reason==='operator-requested')endConsentLease(reason); appendLifecycle('supervisor-stopping',classification,{reason,childProcesses:children.size, authorizationExtended:false}); try{writeActiveState('stopping',{reason,classification})}catch{} log('live_agent_stopping',{reason,classification,childProcesses:children.size, originalStatus3340:'preserved',heavenCoin:'preserved'}); for(const p of children){try{p.kill('SIGTERM')}catch{}} const clean=reason==='operator-requested'||reason==='planned-cap'; setTimeout(()=>{for(const p of children){try{p.kill('SIGKILL')}catch{}} try{writeActiveState('stopped',{reason,classification})}catch{} process.exit(clean?0:1) },4500).unref(); if(children.size===0){ try{writeActiveState('stopped',{reason,classification})}catch{} process.exit(clean?0:1); } } process.on('SIGINT',()=>stop('operator-requested')); process.on('SIGTERM',()=>stop('parent-service-signal')); const withoutToken={...process.env, STRATUM_HOST:settings.host,STRATUM_PORT:settings.port, STRATUM_TLS:settings.tls,STRATUM_WORKER:settings.worker, STRATUM_PASSWORD:'x', LOCAL_STRATUM_PORT:'3334',LOCAL_STRATUM_HOST:'127.0.0.1', STATUS_PORT:'3345',MAX_MINERS:'1'}; delete withoutToken.JESUSOS_MINING_REPORTER_TOKEN; delete withoutToken.JESUSOS_MINING_DEVICE_TOKEN; delete withoutToken.JESUSOS_DEVICE_ALLOW_MINING; delete withoutToken.JESUSOS_DEVICE_WORK_CADENCE; const proxy=spawn(process.execPath,[paths.proxy],{env:withoutToken, stdio:['ignore','inherit','inherit']}); children.add(proxy); proxy.on('error',e=>{log('proxy_failed',{code:e.code||'unknown'});stop('proxy-error')}); proxy.on('exit',(code,signal)=>{children.delete(proxy); if(!stopping){log('proxy_exited',{code,signal:signal||null}); appendLifecycle('proxy-departed','unknown-termination',{exitCode:code,signal:signal||null,causeEstablished:false}); stop('proxy-exited')} }); const localStatus='http://127.0.0.1:3345/status'; async function getStatus(){ const r=await fetch(localStatus,{headers:{Host:'127.0.0.1:3345'}, cache:'no-store',signal:AbortSignal.timeout(1500)}); if(!r.ok)throw Error('Original live relay status unavailable.'); const j=await r.json(); if(j.schema!=='jesusos.stratum.telemetry.v1')throw Error('Unexpected original status schema.'); return j; } let ready=false; for(let i=0;i<45&&!stopping;i++){ try{await getStatus();ready=true;break}catch{await new Promise(r=>setTimeout(r,250))} } if(!ready){ console.error('LIVE MINING REFUSED: verified relay not available; 3340 and HeavenCoin preserved.'); stop('relay-unavailable'); }else if(!stopping){ log('real_pool_relay_ready',{host:'127.0.0.1',port:3334, statusPort:3345,officialPool:'stratum.ckpool.org:3333', agentMode:'authenticated'}); const monitor=setInterval(async()=>{ if(stopping){clearInterval(monitor);return} try{ const s=await getStatus(); log('live_status',{connected:s.minersConnected,authorized:s.authorized, poolJobs:s.jobs,sharesSubmitted:s.sharesSubmitted, sharesAccepted:s.sharesAccepted,sharesRejected:s.sharesRejected, verifiedBitcoinPayout:false}); }catch{log('live_status_unavailable')} },10000); monitor.unref(); const agentEnvironment={...withoutToken, JESUSOS_VERIFIED_MINER_PATH:paths.miner, JESUSOS_MINING_REPORTER_TOKEN:credential.token, JESUSOS_DEVICE_ALLOW_MINING:executionMode?'1':'0', JESUSOS_DEVICE_WORK_CADENCE:'opt-in-15m-v1', JESUSOS_LOCAL_RECOVERY:'bounded-local-recovery-v14', JESUSOS_EXECUTION_CONSENT:executionMode?'active-unexpired-v14':'reporting-only-v14', JESUSOS_LOCAL_STATUS_URL:localStatus }; // Only the child sees the device reporter credential. The parent keeps // it in memory solely for THIS explicitly authorized local session. // A lost Android app / dead parent has no privileged remote restart path. function observeAgentLine(line,recoveryState=null){ let event;try{event=JSON.parse(line)}catch{return} const kind=event?.kind; if(kind==='report_or_command_error'){ const classification=classifyFailure(event.message||'unknown'); appendLifecycle('device-report-failure',classification,{reason:String(event.message||'unknown')}); }else if(kind==='adaptive_throttle'&&String(event.tier||'').startsWith('pause')){ appendLifecycle('device-safety-intervention','battery-or-thermal-safety-intervention',{ tier:String(event.tier||'unknown'),workAllowed:Boolean(event.workAllowed)}); }else if(kind==='bounded_session_ended'&&event.localBatteryGuardStopped===true){ appendLifecycle('owned-child-stopped-by-safety','battery-or-thermal-safety-intervention',{ workerExitReason:String(event.workerExitReason||'unknown')}); }else if(kind==='telemetry_uploaded'){ appendLifecycle('reporting-heartbeat-sent','reporting-available',{ executionAuthorized:executionMode,miners:Number(event.miners||0)}); if(recoveryState&&recoveryState.attempt>0&&!recoveryState.reported){ recoveryState.reported=true; const outcome=recoveryOutcomeRecord(true); appendLifecycle('recovery-outcome',outcome.classification,{ outcome:outcome.outcome,reportingRestored:true,attempt:recoveryState.attempt, executionAuthorized:executionMode}); } } } function pipeAgentOutput(stream,target,recoveryState){ let pending='';stream.setEncoding('utf8'); stream.on('data',chunk=>{ target.write(chunk);pending=(pending+chunk).slice(-32768); let end;while((end=pending.indexOf('\n'))>=0){ const line=pending.slice(0,end);pending=pending.slice(end+1);observeAgentLine(line,recoveryState); } }); } function startDeviceAgent(trigger){ if(stopping||agentProcess)return; if(Date.now()>=supervisorDeadline){stop('planned-cap');return} const recoveryState={attempt:trigger==='bounded-local-recovery-v14'?recoveryAttempts:0,reported:false}; const agent=spawn(process.execPath,[paths.agent,'--run'],{ env:agentEnvironment,stdio:['ignore','pipe','pipe'] }); pipeAgentOutput(agent.stdout,process.stdout,recoveryState);pipeAgentOutput(agent.stderr,process.stderr,recoveryState); agentProcess=agent;children.add(agent); log('device_agent_spawned',{trigger,sessionMaxHours:maxSessionHours||null, recoveryAttempts,credentialStorage:'android-keystore-wrapped', executionAuthorized:executionMode}); appendLifecycle('device-agent-spawned',trigger==='initial-owner-opt-in'? (executionMode?'operator-requested-execution':'reporting-recovery'):'local-recovery-attempt',{ trigger,recoveryAttempts,executionAuthorized:executionMode}); let handled=false; const departed=(reason,code=null,signal=null)=>{ if(handled)return;handled=true; children.delete(agent); if(agentProcess===agent)agentProcess=null; log('device_agent_departed',{reason,code,signal,recoveryAttempts, originalPortsUntouched:true,operatorStopped:stopping}); if(!stopping){ appendLifecycle('device-agent-departed','unexpected-child-process-termination',{ reason,exitCode:code,signal:signal||null,recoveryAttempts}); if(recoveryState.attempt>0&&!recoveryState.reported){ const outcome=recoveryOutcomeRecord(false); appendLifecycle('recovery-outcome',outcome.classification,{ outcome:outcome.outcome,reportingRestored:false,attempt:recoveryState.attempt, exitCode:code,signal:signal||null,reason}); recoveryState.reported=true; } scheduleAgentRecovery(reason); } }; agent.on('error',e=>departed('spawn-error',String(e?.code||'unknown'))); agent.on('exit',(code,signal)=>departed('unexpected-exit',code,signal||null)); } function scheduleAgentRecovery(reason){ if(stopping)return; if(agentProcess||recoveryTimer!==null)return; const recoveryWindow=localRecoveryWindow(Date.now(),supervisorDeadline,recoveryAttempts); if(recoveryWindow==='expired'){stop('planned-cap');return} if(recoveryWindow==='exhausted'){ log('device_recovery_exhausted',{reason,attempts:recoveryAttempts, nextAction:'owner-check-Termux; never remote-start'}); appendLifecycle('recovery-exhausted','unexpected-child-process-termination',{attempts:recoveryAttempts}); stop('agent-recovery-exhausted');return; } const delayMs=AGENT_BACKOFF_MS[recoveryAttempts++]; log('device_recovery_scheduled',{reason,attempt:recoveryAttempts, delaySeconds:delayMs/1000,backoffBounded:true}); appendLifecycle('recovery-scheduled','unexpected-child-process-termination',{ reason,attempt:recoveryAttempts,delaySeconds:delayMs/1000}); recoveryTimer=setTimeout(async()=>{ recoveryTimer=null; if(stopping||agentProcess)return; if(Date.now()>=supervisorDeadline){stop('planned-cap');return} try{ if(!children.has(proxy))throw Error('original-relay-not-running'); const status=await getStatus(); if(!Number.isSafeInteger(status.minersConnected)||status.minersConnected!==0) throw Error('local-miner-not-idle; refusing-duplicate'); if(executionMode){ const activeLease=loadActiveConsentLease(); if(!activeLease||Date.parse(activeLease.expiresAt)<=Date.now()) throw Error('Execution consent expired; recovery cannot extend authorization'); await requireLocalBatterySensor(); } const st=fs.lstatSync(paths.agent); if(st.isSymbolicLink()||!st.isFile()||(st.mode&0o077)!==0|| sha(await fsp.readFile(paths.agent))!==PINS.agent.sha) throw Error('pinned-device-agent-file-changed'); await verifyDedicatedDevicePairing(credential.token); log('device_recovery_preflight_passed',{attempt:recoveryAttempts, noDuplicateMiner:true,pinnedSource:true,localBatteryCheck:executionMode, ownerAuthorizationReusedWithoutExtension:true,executionAuthorized:executionMode}); appendLifecycle('recovery-preflight-passed','local-recovery-ready',{ attempt:recoveryAttempts,noDuplicateMiner:true,executionAuthorized:executionMode, authorizationExtended:false}); startDeviceAgent('bounded-local-recovery-v14'); }catch(e){ const message=String(e instanceof Error?e.message:e).slice(0,110); const classification=classifyFailure(e); log('device_recovery_preflight_failed',{attempt:recoveryAttempts, classification,reason:message}); appendLifecycle('recovery-preflight-failed',classification,{ attempt:recoveryAttempts,reason:message,authorizationExtended:false}); scheduleAgentRecovery('local-preflight-refused'); } },delayMs); } startDeviceAgent(executionMode?'initial-owner-opt-in':'initial-reporting-recovery'); log('device_agent_enabled',{heartbeatSeconds:60,commandDurationCapSeconds:executionMode?90:0, hashRateCap:executionMode?5000:0,workOrdersPerUTCExpectedHour:executionMode?4:0, requiredLocalSafety:executionMode? 'termux-battery-status; adaptive 15m cool, 30m warm, pause hot/low; abort at warming threshold': 'reporting-only; mining commands refused', reporterCredential:'encrypted-at-rest-never-displayed', executionAuthorized:executionMode,sessionMaxHours:maxSessionHours||null, authorizationExpiresAt:new Date(supervisorDeadline).toISOString()}); const markerTimer=setInterval(()=>{ if(!stopping)try{writeActiveState('running',{mode,executionAuthorized:executionMode, authorizationExpiresAt:new Date(supervisorDeadline).toISOString()})}catch{} },60000);markerTimer.unref(); const capMs=Math.max(0,supervisorDeadline-Date.now()); setTimeout(()=>stop('planned-cap'),capMs).unref(); }