#!/usr/bin/env node import {readFileSync} from 'node:fs'; import {createHash} from 'node:crypto'; const VERSION='openlab-value-sharing-v1'; const ID=/^[a-z0-9][a-z0-9-]{1,63}$/; const PARTICIPANT=/^[0-9a-f]{32}$/; const HASH=/^[0-9a-f]{64}$/; const die=m=>{throw new Error(m)}; const exact=(v,required,label)=>{if(!v||typeof v!=='object'||Array.isArray(v))die(`${label} must be an object`);for(const k of required)if(!Object.hasOwn(v,k))die(`${label} missing ${k}`);for(const k of Object.keys(v))if(!required.includes(k))die(`${label} has unknown field ${k}`)}; const text=(v,label,min,max)=>{if(typeof v!=='string'||v.trim().lengthmax)die(`${label} must be ${min}-${max} nonblank characters`);return v.trim()}; const timestamp=(v,label)=>{const p=typeof v==='string'?Date.parse(v):NaN;if(typeof v!=='string'||!/^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$/.test(v)||!Number.isFinite(p)||new Date(p).toISOString()!==v.replace('Z','.000Z'))die(`${label} must be an RFC 3339 UTC timestamp to whole seconds`);return v}; const canonical=v=>v===null||typeof v!=='object'?JSON.stringify(v):Array.isArray(v)?`[${v.map(canonical).join(',')}]`:`{${Object.keys(v).sort().map(k=>`${JSON.stringify(k)}:${canonical(v[k])}`).join(',')}}`; export function validateAgreement(v){ const top=['schema_version','project_id','currency','signed_before_work','agreement_effective_at','compensated_work_not_before','amendment','pool_bps','rounding_rule','participants','permitted_deductions','accounting_frequency','objection_days','tax_handling','payment_method','zero_revenue_rule','mandatory_claims_preserved','patent_rights_unaffected'];exact(v,top,'value sharing agreement'); if(v.schema_version!==VERSION)die(`schema_version must be ${VERSION}`);if(typeof v.project_id!=='string'||!ID.test(v.project_id))die('project_id must be a lowercase slug');if(v.currency!=='EUR')die('currency must be EUR');if(v.signed_before_work!==true)die('every agreement must be signed before compensated work'); const effective=timestamp(v.agreement_effective_at,'agreement_effective_at'),work=timestamp(v.compensated_work_not_before,'compensated_work_not_before');if(Date.parse(work)10000)die('pool_bps must be 0-10000');if(v.rounding_rule!=='largest_remainder_cents_participant_id_tiebreak')die('invalid rounding_rule');if(!Array.isArray(v.participants)||v.participants.length<1||v.participants.length>100)die('participants must contain 1-100 entries'); const ids=new Set();const participants=v.participants.map(x=>{const f=['participant_id','eligible_contribution_scope','weight_basis','weight','signed','signed_at'];exact(x,f,'value sharing participant');if(typeof x.participant_id!=='string'||!PARTICIPANT.test(x.participant_id)||ids.has(x.participant_id))die('participant IDs must be distinct 32 lowercase hex values');ids.add(x.participant_id);if(!Number.isSafeInteger(x.weight)||x.weight<1||x.weight>1000000)die('participant weight must be 1-1000000');if(x.signed!==true)die('every participant must sign before work');const signed=timestamp(x.signed_at,'participant signed_at');if(Date.parse(signed)>Date.parse(effective))die('every participant must sign no later than agreement_effective_at');return {participant_id:x.participant_id,eligible_contribution_scope:text(x.eligible_contribution_scope,'eligible contribution scope',10,500),weight_basis:text(x.weight_basis,'weight basis',10,500),weight:x.weight,signed:true,signed_at:signed}}).sort((a,b)=>a.participant_id.localeCompare(b.participant_id)); if(!Array.isArray(v.permitted_deductions)||v.permitted_deductions.length>30)die('permitted_deductions must contain at most 30 entries');const codes=new Set();const deductions=v.permitted_deductions.map(x=>{exact(x,['code','description','cap_cents'],'permitted deduction');const code=text(x.code,'deduction code',2,40);if(!ID.test(code)||codes.has(code))die('deduction codes must be distinct lowercase slugs');codes.add(code);if(!Number.isSafeInteger(x.cap_cents)||x.cap_cents<0||x.cap_cents>1000000000000)die('deduction cap must be nonnegative safe integer cents');return {code,description:text(x.description,'deduction description',5,300),cap_cents:x.cap_cents}}).sort((a,b)=>a.code.localeCompare(b.code)); if(!Number.isInteger(v.objection_days)||v.objection_days<7||v.objection_days>365)die('objection_days must be 7-365');if(v.mandatory_claims_preserved!==true||v.patent_rights_unaffected!==true)die('mandatory claims and patent rights must remain unaffected'); const result={schema_version:VERSION,project_id:v.project_id,currency:'EUR',signed_before_work:true,agreement_effective_at:effective,compensated_work_not_before:work,amendment,pool_bps:v.pool_bps,rounding_rule:'largest_remainder_cents_participant_id_tiebreak',participants,permitted_deductions:deductions,accounting_frequency:text(v.accounting_frequency,'accounting frequency',3,100),objection_days:v.objection_days,tax_handling:text(v.tax_handling,'tax handling',10,500),payment_method:text(v.payment_method,'payment method',5,300),zero_revenue_rule:text(v.zero_revenue_rule,'zero revenue rule',10,300),mandatory_claims_preserved:true,patent_rights_unaffected:true}; return {...result,agreement_sha256:createHash('sha256').update(canonical(result)).digest('hex')}; } export function validateAmendment(previousValue,currentValue){ const previous=validateAgreement(previousValue),current=validateAgreement(currentValue); if(current.amendment===null)die('current agreement must declare an amendment'); if(current.amendment.supersedes_agreement_sha256!==previous.agreement_sha256)die('amendment does not match exact superseded agreement'); if(current.project_id!==previous.project_id||current.currency!==previous.currency)die('amendment cannot change project or currency identity'); if(Date.parse(current.agreement_effective_at)<=Date.parse(previous.agreement_effective_at))die('amendment must become effective after the superseded agreement'); if(Date.parse(current.compensated_work_not_before)2)die('usage: node validate-value-sharing-agreement.mjs AGREEMENT.json [CURRENT-AMENDMENT.json]');const first=JSON.parse(readFileSync(paths[0],'utf8'));const result=paths.length===2?validateAmendment(first,JSON.parse(readFileSync(paths[1],'utf8'))):validateAgreement(first);process.stdout.write(JSON.stringify({ok:true,status:paths.length===2?'prospective_amendment_chain_valid_not_contract_authentication':'structurally_and_cross_field_valid_not_contract_authentication',agreement_sha256:result.agreement_sha256,previous_agreement_sha256:paths.length===2?validateAgreement(first).agreement_sha256:null,network_requests:0,files_written:0,adopted_contract:false,payment_promised:false,signature_authenticity_verified:false,actual_work_timing_verified:false,legal_or_tax_clearance:false},null,2)+'\n')}catch(e){process.stderr.write(JSON.stringify({ok:false,error:e.message,network_requests:0,files_written:0})+'\n');process.exitCode=1}}