forked from unimatrix/web
Expand public tariffs with tax rules, reserve instruments and economic formulas; add complete PDF and audited direct publisher
This commit is contained in:
parent
857cdf5d6f
commit
8eca3945ba
5 changed files with 189 additions and 10 deletions
|
|
@ -15,7 +15,7 @@ export function createDevKeyAuthority({secret,environment,authorize,clock=Date.n
|
|||
return Object.freeze({
|
||||
async issue(actor,manifest,{ttlMs=600000}={}){
|
||||
await allowed(actor);
|
||||
if(!Number.isSafeInteger(ttlMs)||ttlMs<1||ttlMs>900000||manifest?.action!=='clan-reset'||manifest.state!=='planned')throw TypeError('Invalid developer batch');
|
||||
if(!Number.isSafeInteger(ttlMs)||ttlMs<1||ttlMs>900000||!['clan-reset','tariff-publication'].includes(manifest?.action)||manifest.state!=='planned')throw TypeError('Invalid developer batch');
|
||||
const now=clock(),record={id:randomUUID(),environment,actorId:actor.id,issuedAt:now,expiresAt:now+ttlMs,manifestHash:hash(canonical(manifest)),manifest:JSON.parse(canonical(manifest))};
|
||||
const payload=Buffer.from(canonical(record)).toString('base64url');
|
||||
const key='DEV-BATCH.'+payload+'.'+sign(payload);
|
||||
|
|
|
|||
26
tools/jarvis-dev-tariff-receipt.mjs
Normal file
26
tools/jarvis-dev-tariff-receipt.mjs
Normal file
|
|
@ -0,0 +1,26 @@
|
|||
// Root-only companion to the fixed-file publication script, never a web route.
|
||||
import {createDevKeyAuthority} from './jarvis-dev-key.mjs';
|
||||
import {randomBytes,randomUUID} from 'node:crypto';
|
||||
import {createRequire} from 'node:module';
|
||||
let raw='';for await(const part of process.stdin)raw+=part;
|
||||
if(process.getuid?.()!==0||raw.length>65536||!['--issue','--complete','--failed'].includes(process.argv[2]))throw Error('Fixed developer publication command required');
|
||||
const data=JSON.parse(raw),mode=process.argv[2],actor={id:'server-root'};
|
||||
process.loadEnvFile('/home/dunerealms/.config/dunerealms.env');
|
||||
const require=createRequire('/home/dunerealms/apps/dunerealms/current/node/mysql.mjs'),mysql=require('mysql2/promise');
|
||||
const db=await mysql.createConnection({host:process.env.DB_HOST||'127.0.0.1',port:Number(process.env.DB_PORT||3306),user:process.env.DB_USER,password:process.env.DB_PASSWORD,database:process.env.DB_NAME,multipleStatements:false});
|
||||
try{
|
||||
let details,action;
|
||||
if(mode==='--issue'){
|
||||
if(data.action!=='tariff-publication'||data.batchId!=='tariff-guide-20261118-v1'||!Array.isArray(data.files)||data.files.length!==5)throw Error('Unexpected tariff manifest');
|
||||
const authority=createDevKeyAuthority({secret:randomBytes(32).toString('hex'),environment:'production',authorize:async who=>who.id===actor.id&&process.getuid()===0});
|
||||
const issued=await authority.issue(actor,data),record=await authority.verify(actor,issued.key,data);
|
||||
details={...issued.audit,batchId:data.batchId,manifest:data};action='dev-key-issued';
|
||||
await db.execute('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[record.id,'f3ffda37-01e4-41ea-b89d-fbeda82e453e',action,JSON.stringify(details),Date.now()]);
|
||||
console.log(JSON.stringify({record,audit:issued.audit}));
|
||||
}else{
|
||||
if(data.record?.manifest?.batchId!=='tariff-guide-20261118-v1'||typeof data.record?.id!=='string')throw Error('Publication receipt required');
|
||||
action=mode==='--complete'?'dev-tariff-published':'dev-tariff-failed';details={keyId:data.record.id,batchId:data.record.manifest.batchId,manifestHash:data.record.manifestHash,files:data.record.manifest.files};
|
||||
await db.execute('INSERT INTO account_audit(id,actor_id,action,details,created_at) VALUES(?,?,?,?,?)',[randomUUID(),'f3ffda37-01e4-41ea-b89d-fbeda82e453e',action,JSON.stringify(details),Date.now()]);
|
||||
console.log(JSON.stringify({keyId:data.record.id,state:mode==='--complete'?'completed':'failed'}));
|
||||
}
|
||||
}finally{await db.end();}
|
||||
12
tools/package-tariff-hotfix.mjs
Normal file
12
tools/package-tariff-hotfix.mjs
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import {readFileSync,writeFileSync,readdirSync} from 'node:fs';
|
||||
import {createHash} from 'node:crypto';
|
||||
const root=new URL('../',import.meta.url),read=p=>readFileSync(new URL(p,root)),hash=b=>createHash('sha256').update(b).digest('hex');
|
||||
const names=['rates-and-charges.html','bank-rates.css','bank-rates.js','downloads/rates-guide-manifest.json','downloads/dunerealms-rates-guide-20261118.pdf'];
|
||||
const files=Object.fromEntries(names.map(name=>{
|
||||
let bytes=read('website/web/'+name);const mime=name.endsWith('.html')?'text/html; charset=utf-8':name.endsWith('.css')?'text/css; charset=utf-8':name.endsWith('.js')?'text/javascript; charset=utf-8':name.endsWith('.json')?'application/json; charset=utf-8':'application/pdf';
|
||||
if(name.endsWith('.html')){const key=JSON.stringify('/'+name)+':';let prepared=null;for(const shard of [...read('website/dist/server/index.js').toString().matchAll(/from "\.\/(assets-[a-f0-9]+\.mjs)"/g)].map(m=>m[1])){const source=read('website/dist/server/'+shard).toString();const start=source.indexOf(key);if(start>=0){const end=source.indexOf('],',start);prepared=JSON.parse(source.slice(start+key.length,end+1));break;}}if(!prepared)throw Error('Build prepared tariff HTML first');bytes=Buffer.from(prepared[1],'base64');}
|
||||
return[name,{mime,data:bytes.toString('base64'),sha256:hash(bytes)}];
|
||||
}));
|
||||
const helpers=Object.fromEntries(['jarvis-dev-key.mjs','jarvis-dev-tariff-receipt.mjs'].map(name=>{const b=read('tools/'+name);return[name,{data:b.toString('base64'),sha256:hash(b)}];}));
|
||||
const template=read('tools/tariff-hotfix-template.py').toString().replace('__FILES_JSON__',JSON.stringify(JSON.stringify(files))).replace('__HELPERS_JSON__',JSON.stringify(JSON.stringify(helpers)));
|
||||
if(!process.argv[2])throw Error('Specify staged script path');writeFileSync(process.argv[2],template);console.log(JSON.stringify({files:names,script:process.argv[2],containsSecrets:false}));
|
||||
94
tools/tariff-hotfix-template.py
Normal file
94
tools/tariff-hotfix-template.py
Normal file
|
|
@ -0,0 +1,94 @@
|
|||
"""Fixed, manifest-bound publication of five public tariff assets. No policy edits."""
|
||||
import base64, hashlib, json, os, pathlib, re, subprocess, sys, fcntl
|
||||
FILES=json.loads(__FILES_JSON__)
|
||||
HELPERS=json.loads(__HELPERS_JSON__)
|
||||
APP=pathlib.Path('/home/dunerealms/apps/dunerealms')
|
||||
STATE=pathlib.Path('/mnt/HC_Volume_107481500/dunegit/ci/promotion')
|
||||
NODE='/home/dunerealms/.nvm/versions/node/v22.23.3/bin/node'
|
||||
EXPECTED='ci-27d3bef1b60f01e6ddebfb644144002773a3de52'
|
||||
INSTALL=pathlib.Path('/usr/local/libexec/dunerealms-dev/tariff-guide-20261118')
|
||||
def digest(data):return hashlib.sha256(data).hexdigest()
|
||||
def run(args,**kwargs):return subprocess.run(args,check=True,capture_output=True,**kwargs)
|
||||
def atomic(path,data):
|
||||
metadata=path.stat() if path.exists() else None
|
||||
path.parent.mkdir(parents=True,exist_ok=True)
|
||||
tmp=path.with_name(path.name+'.tariff-new')
|
||||
if tmp.exists() or tmp.is_symlink():raise RuntimeError('Unexpected staged publication file')
|
||||
with tmp.open('xb') as out:out.write(data);out.flush();os.fsync(out.fileno())
|
||||
os.chmod(tmp,metadata.st_mode & 0o777 if metadata else 0o644)
|
||||
if metadata:os.chown(tmp,metadata.st_uid,metadata.st_gid)
|
||||
os.replace(tmp,path)
|
||||
def main():
|
||||
if os.geteuid()!=0:raise RuntimeError('Server administrator required')
|
||||
if len(sys.argv)!=2 or sys.argv[1] not in ('--plan','--apply'):raise RuntimeError('Choose --plan or --apply')
|
||||
release=(APP/'current').resolve(strict=True)
|
||||
if release.parent!=APP/'releases' or release.name!=EXPECTED:raise RuntimeError('Live release changed; regenerate this fixed publication package')
|
||||
payload={name:base64.b64decode(item['data']) for name,item in FILES.items()}
|
||||
if any(digest(payload[n])!=v['sha256'] for n,v in FILES.items()):raise RuntimeError('Publication package integrity failure')
|
||||
source=json.loads(run(['curl','--noproxy','*','-fsS','--max-time','15','--resolve','cp.dunerealms.com:443:127.0.0.1','https://cp.dunerealms.com/api/bank/public/rates']).stdout)
|
||||
guide=json.loads(payload['downloads/rates-guide-manifest.json'])
|
||||
if source['version']!=guide['sourcePublicationVersion']:raise RuntimeError('Financial policy changed; regenerate the guide from its current public snapshot')
|
||||
manifest={'action':'tariff-publication','state':'planned','batchId':'tariff-guide-20261118-v1','release':release.name,'files':[{'path':'/'+n,'sha256':FILES[n]['sha256']} for n in sorted(FILES)],'changesFinancialPolicy':False,'changesBalances':False}
|
||||
if sys.argv[1]=='--plan':print(json.dumps(manifest));return
|
||||
lock=os.fdopen(os.open(STATE/'tariff-guide-20261118.lock',os.O_CREAT|os.O_RDWR|os.O_NOFOLLOW,0o600),'w')
|
||||
fcntl.flock(lock,fcntl.LOCK_EX|fcntl.LOCK_NB)
|
||||
receipt_path=STATE/'tariff-guide-20261118-v1.json'
|
||||
if receipt_path.exists():
|
||||
receipt=json.loads(receipt_path.read_text())
|
||||
if receipt.get('state')=='completed':print(json.dumps({'state':'already-completed','keyId':receipt['record']['id']}));return
|
||||
raise RuntimeError('Previous incomplete publication needs inspection before retry')
|
||||
for directory in (INSTALL.parent,INSTALL):
|
||||
if directory.is_symlink():raise RuntimeError('Unsafe developer installation path')
|
||||
directory.mkdir(parents=True,exist_ok=True)
|
||||
st=directory.stat()
|
||||
if st.st_uid!=0 or st.st_mode & 0o022:raise RuntimeError('Developer installation must be root-owned and not writable by others')
|
||||
for name,item in HELPERS.items():
|
||||
data=base64.b64decode(item['data'])
|
||||
if digest(data)!=item['sha256']:raise RuntimeError('Developer helper integrity failure')
|
||||
atomic(INSTALL/name,data)
|
||||
run([NODE,'--check',str(INSTALL/name)])
|
||||
def audit(mode,value):return json.loads(run([NODE,str(INSTALL/'jarvis-dev-tariff-receipt.mjs'),mode],input=json.dumps(value).encode()).stdout)
|
||||
originals={};changes={};shards=[release/'dist/server'/name for name in re.findall(r'from "\./(assets-[a-f0-9]+\.mjs)"',(release/'dist/server/index.js').read_text())]
|
||||
if not shards:raise RuntimeError('Compiled public assets unavailable')
|
||||
for name,item in FILES.items():
|
||||
key=json.dumps('/'+name,separators=(',',':'))
|
||||
entry=key+':'+json.dumps([item['mime'],item['data']],separators=(',',':'))+','
|
||||
matches=[]
|
||||
pattern=re.compile(re.escape(key)+r':\["[^"]+","[A-Za-z0-9+/=]*"\],')
|
||||
for shard in shards:
|
||||
text=changes.get(shard,shard.read_bytes()).decode()
|
||||
if pattern.search(text):matches.append((shard,pattern.sub(lambda _:entry,text,count=1).encode()))
|
||||
if len(matches)>1:raise RuntimeError('Ambiguous compiled publication asset')
|
||||
if matches:changes[matches[0][0]]=matches[0][1]
|
||||
else:
|
||||
shard=shards[0];text=changes.get(shard,shard.read_bytes()).decode()
|
||||
if not text.rstrip().endswith('};'):raise RuntimeError('Unexpected compiled asset format')
|
||||
end=text.rfind('};');changes[shard]=(text[:end]+entry+text[end:]).encode()
|
||||
changes[release/'web'/name]=payload[name]
|
||||
if name in ('rates-and-charges.html','bank-rates.css'):
|
||||
changes[release/'dist/shared-chrome'/name]=payload[name]
|
||||
changes[pathlib.Path('/var/lib/dunerealms-public-rates')/name]=payload[name]
|
||||
slot=(STATE/'active-slot').read_text().strip()
|
||||
if slot not in ('blue','green'):raise RuntimeError('Unknown active website slot')
|
||||
pm2=['runuser','-u','dunerealms','--','env','PM2_HOME='+str(STATE.parent/'pm2'),NODE,'/home/dunerealms/.local/node_modules/pm2/bin/pm2']
|
||||
run(pm2+['describe','dunerealms-web-'+slot])
|
||||
for path in changes:originals[path]=path.read_bytes() if path.exists() else None
|
||||
receipt=audit('--issue',manifest)
|
||||
if receipt['record']['manifest']!=manifest:raise RuntimeError('Developer manifest verification failed')
|
||||
receipt['state']='executing';atomic(receipt_path,json.dumps(receipt).encode())
|
||||
try:
|
||||
for path,data in changes.items():atomic(path,data)
|
||||
run(pm2+['reload','dunerealms-web-'+slot])
|
||||
for name,item in FILES.items():
|
||||
actual=run(['curl','--noproxy','*','-fsS','--retry','5','--retry-delay','1','--max-time','15','--resolve','www.dunerealms.com:443:127.0.0.1','https://www.dunerealms.com/'+name]).stdout
|
||||
if digest(actual)!=item['sha256']:raise RuntimeError('Public tariff verification failed: '+name)
|
||||
audit('--complete',receipt);receipt['state']='completed';atomic(receipt_path,json.dumps(receipt).encode())
|
||||
print(json.dumps({'state':'completed','keyId':receipt['record']['id'],'publishedAssets':len(FILES),'balancesChanged':False,'financialPoliciesChanged':False}))
|
||||
except Exception:
|
||||
for path,data in originals.items():
|
||||
if data is None:path.unlink(missing_ok=True)
|
||||
else:atomic(path,data)
|
||||
run(pm2+['reload','dunerealms-web-'+slot])
|
||||
audit('--failed',receipt);receipt['state']='failed';atomic(receipt_path,json.dumps(receipt).encode())
|
||||
raise
|
||||
if __name__=='__main__':main()
|
||||
|
|
@ -17,3 +17,9 @@ test('expiry, tampering and unavailable developer privileges reject before execu
|
|||
now=10100;await assert.rejects(service.verify(dev,issued.key,manifest),/unavailable/);
|
||||
await assert.rejects(setup({authorize:async()=>false}).issue(dev,manifest),/Developer access/);
|
||||
});
|
||||
test('tariff publication keys bind exact public file hashes and reject unrelated developer actions',async()=>{
|
||||
const service=setup(),publication={action:'tariff-publication',state:'planned',files:[{path:'/rates-and-charges.html',sha256:'ab'.repeat(32)}],changesBalances:false};
|
||||
const issued=await service.issue(dev,publication);assert.equal((await service.verify(dev,issued.key,publication)).manifest.changesBalances,false);
|
||||
await assert.rejects(service.verify(dev,issued.key,{...publication,files:[{path:'/other.html',sha256:'ab'.repeat(32)}]}),/manifest/);
|
||||
await assert.rejects(service.issue(dev,{action:'arbitrary-sql',state:'planned'}),/Invalid developer batch/);
|
||||
});
|
||||
|
|
|
|||
Loading…
Reference in a new issue

Staff