/** * HeavenCoin — independent local service-receipt signature verification v1. * Node.js 20+ only. NO npm packages, Floot login, internet, wallets or banks. * * Save this direct Jesus OS .txt source as local-receipt-verify.mjs. * Then run: * node local-receipt-verify.mjs private-receipt.json provider-proof.json * node local-receipt-verify.mjs private-receipt.json provider-proof.json recipient-proof.json * Optional independently obtained key pins: * --pin-provider=<64 hex SHA256> --pin-recipient=<64 hex SHA256> * * KEEP ALL LOCAL RECEIPTS PRIVATE. They may include names and work details. * Mathematically valid key signatures do NOT establish two real individuals, * lawful consent, completed work, any value, settlement or decentralization. */ import {createHash,createPublicKey,verify} from "node:crypto"; import {readFileSync,lstatSync} from "node:fs"; import {resolve} from "node:path"; import {fileURLToPath} from "node:url"; const FORMAT="heavencoin.local-service-receipt-key-proof.v1"; const MAX_RECEIPT=262144,MAX_PROOF=2500; const hash=text=>createHash("sha256").update(text,"utf8").digest("hex"); const hex64=/^[a-f0-9]{64}$/; const b43=/^[A-Za-z0-9_-]{43}$/; const b86=/^[A-Za-z0-9_-]{86}$/; const roles=new Set(["provider","recipient"]); const AG_FIELDS=[ "receiptId","title","providerAlias","recipientAlias","kind","description", "quantity","unit","requestedInReturn","timing","completionCriteria", "consentAndAuthority","correctionRoute" ]; function assert(ok,message){if(!ok)throw Error(message);} function keysExact(value,names){ return !!value&&typeof value==="object"&&!Array.isArray(value)&& Object.keys(value).sort().join("|")===names.slice().sort().join("|"); } function read(path,limit){ const stat=lstatSync(path); assert(stat.isFile()&&!stat.isSymbolicLink()&& stat.size>0&&stat.size<=limit,"File must be a bounded, nonempty regular file"); const bytes=readFileSync(path); assert(bytes.byteLength<=limit,"File exceeds allowed byte length"); return JSON.parse(new TextDecoder("utf-8",{fatal:true}).decode(bytes)); } function string(x,min,max){ assert(typeof x==="string","Expected text in receipt"); const s=x.trim(); assert(s.length>=min&&s.length<=max,"Receipt text field length invalid"); return s; } function date(x){ assert(typeof x==="string"&&x.length<=42&& /^\d{4}-\d\d-\d\dT\d\d:\d\d/.test(x)&& /(?:Z|[+-]\d\d:\d\d)$/.test(x)&& Number.isFinite(Date.parse(x)),"Invalid date with timezone"); return Date.parse(x); } function canonicalReceipt(receipt){ assert(keysExact(receipt,[ "format","version","signed","verification","agreementRecordedAt", "exportedAt","agreement","events","notice" ]),"Unsupported receipt fields"); assert(receipt.format==="heavencoin-voluntary-service-receipt"&& receipt.version===1&&receipt.signed===false&& receipt.verification==="participant-statements-unverified", "Not an unsigned Jesus OS service receipt v1"); string(receipt.notice,20,2000); const start=date(receipt.agreementRecordedAt),end=date(receipt.exportedAt); assert(end>=start,"Receipt timestamps out of order"); const a=receipt.agreement; assert(keysExact(a,AG_FIELDS),"Unexpected agreement fields"); const constrained={ receiptId:[3,80],title:[5,200],providerAlias:[2,80], recipientAlias:[2,80],description:[20,3000], requestedInReturn:[10,2000],timing:[5,1000], completionCriteria:[10,2000],consentAndAuthority:[10,1500], correctionRoute:[10,1500] }; const clean={}; for(const field of AG_FIELDS){ if(field in constrained)clean[field]=string(a[field],...constrained[field]); else clean[field]=a[field]; } assert(/^[A-Za-z0-9][A-Za-z0-9._-]*$/.test(clean.receiptId), "Invalid receipt reference"); assert(clean.providerAlias.toLowerCase()!==clean.recipientAlias.toLowerCase(), "Use different aliases"); assert(["service","goods"].includes(clean.kind)&& ["hours","items","projects","bundles"].includes(clean.unit), "Unsupported work type or quantity unit"); assert(typeof clean.quantity==="string"&& /^(?:0|[1-9]\d{0,8})(?:\.\d{1,8})?$/.test(clean.quantity)&& Number(clean.quantity)>0,"Invalid quantity"); assert(Array.isArray(receipt.events)&&receipt.events.length<=50, "Too many statements"); let last=start; const completed=new Set(); const events=receipt.events.map((raw,index)=>{ assert(keysExact(raw,["sequence","kind","role","statement", "evidenceReference","recordedAt"]),"Unexpected statement fields"); assert(raw.sequence===index+1,"Event history must be contiguous"); assert(["completion","concern","correction","repair"].includes(raw.kind)&& ["provider","recipient","recorder"].includes(raw.role), "Unsupported statement type or role"); const statement=string(raw.statement,10,2000); const evidenceReference=string(raw.evidenceReference,0,1000); const at=date(raw.recordedAt); assert(at>=last&&at<=end,"Event chronology does not match export"); last=at; if(raw.kind==="completion"){ assert(raw.role!=="recorder"&&!completed.has(raw.role), "Duplicate or unauthorized completion role"); completed.add(raw.role); } return [raw.sequence,raw.kind,raw.role,statement,evidenceReference,raw.recordedAt]; }); return JSON.stringify([ "heavencoin.service-receipt-snapshot.v1", receipt.agreementRecordedAt,AG_FIELDS.map(field=>clean[field]),events ]); } function loadProof(file){ const proof=read(file,MAX_PROOF); assert(keysExact(proof,["format","receiptSha256","role","signedAt", "publicKey","signature"]),"Unrecognized signed-proof fields"); assert(proof.format===FORMAT&&hex64.test(proof.receiptSha256)&& roles.has(proof.role),"Unsupported signed receipt proof"); assert(date(proof.signedAt)<=Date.now()+300000, "Future signed timestamp"); const key=proof.publicKey; assert(keysExact(key,["kty","crv","x","y"])&& key.kty==="EC"&&key.crv==="P-256"&& b43.test(key.x)&&b43.test(key.y), "Invalid or secret-bearing public key"); assert(typeof proof.signature==="string"&&b86.test(proof.signature), "Invalid signature encoding"); const raw=Buffer.from(proof.signature,"base64url"); assert(raw.byteLength===64&&raw.toString("base64url")===proof.signature, "Noncanonical signature bytes"); return proof; } function checkProof(proof,sourceHash){ const message=JSON.stringify([FORMAT,proof.receiptSha256,proof.role, proof.signedAt]); const key=createPublicKey({key:{...proof.publicKey},format:"jwk"}); const good=verify("sha256",Buffer.from(message,"utf8"), {key,dsaEncoding:"ieee-p1363"}, Buffer.from(proof.signature,"base64url")); const keyHash=hash(JSON.stringify([ "heavencoin.service-receipt-key.v1", proof.publicKey.kty,proof.publicKey.crv,proof.publicKey.x,proof.publicKey.y ])); return {claimedRole:proof.role,validSignature:good, matchesExactReceipt:proof.receiptSha256===sourceHash, publicKeySha256:keyHash}; } export function verifySavedReceipt(receiptPath,proofOnePath,proofTwoPath,options={}){ const sourceHash=hash(canonicalReceipt(read(receiptPath,MAX_RECEIPT))); const a=checkProof(loadProof(proofOnePath),sourceHash); const b=proofTwoPath?checkProof(loadProof(proofTwoPath),sourceHash):null; const pins={provider:options.pinProvider??null, recipient:options.pinRecipient??null}; for(const [role,pin] of Object.entries(pins)) if(pin!==null)assert(hex64.test(pin),"Bad pinned key fingerprint: "+role); const verified=[a,...(b?[b]:[])]; const pinChecks=verified.map(v=> pins[v.claimedRole]===null?null:v.publicKeySha256===pins[v.claimedRole]); return { format:"heavencoin.local-receipt-node-check.v1", sourceSha256:sourceHash, first:a, second:b, rolesOpposite:b?a.claimedRole!==b.claimedRole:null, distinctPublicKeys:b?a.publicKeySha256!==b.publicKeySha256:null, pinnedKeyChecks:pinChecks, verified:a.validSignature&&a.matchesExactReceipt&& (!b||(b.validSignature&&b.matchesExactReceipt&& a.claimedRole!==b.claimedRole&& a.publicKeySha256!==b.publicKeySha256))&& pinChecks.every(v=>v!==false), twoHumanIdentitiesIndependentlyVerified:false, consentOrPerformanceVerified:false, paymentsOrTokenIssuanceVerified:false, independentBlockchainConsensusVerified:false }; } async function main(){ const params=process.argv.slice(2); const flags=params.filter(x=>x.startsWith("--")); const paths=params.filter(x=>!x.startsWith("--")); if(paths.length<2||paths.length>3|| flags.some(x=>!/^--pin-(provider|recipient)=[a-f0-9]{64}$/.test(x))|| new Set(flags.map(x=>x.slice(0,x.indexOf("=")))).size!==flags.length){ process.stderr.write("Usage: node local-receipt-verify.mjs receipt.json first-proof.json [second-proof.json] [--pin-provider=SHA256] [--pin-recipient=SHA256]\n"); process.exitCode=2;return; } const map=Object.fromEntries(flags.map(x=>x.slice(2).split("="))); try{ const result=verifySavedReceipt(paths[0],paths[1],paths[2],{ pinProvider:map["pin-provider"],pinRecipient:map["pin-recipient"] }); process.stdout.write(JSON.stringify(result,null,2)+"\n"); if(!result.verified)process.exitCode=1; }catch(error){ process.stderr.write("Receipt verification REFUSED: "+ (error instanceof Error?error.message:"Invalid input")+"\n"); process.exitCode=1; } } if(process.argv[1]&&resolve(process.argv[1])===fileURLToPath(import.meta.url)) void main();