web/tools/tariff-hotfix-template.py
2026-11-21 20:22:37 +01:00

94 lines
6.8 KiB
Python

"""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()