MC/website/ops/publish-cp-v2-preview.mjs
2026-11-27 23:43:05 +00:00

61 lines
5.2 KiB
JavaScript

import {constants} from 'node:fs';
import {lstat,realpath,readFile,readdir,mkdir,mkdtemp,writeFile,chmod,rename,symlink,readlink,rm} from 'node:fs/promises';
import {createHash,randomUUID} from 'node:crypto';
import path from 'node:path';
import {fileURLToPath} from 'node:url';
const markerPattern=/^[0-9a-f]{40}$/;
const assetPattern=/^[a-z0-9][a-z0-9-]*\.(?:html|css|js|mjs|json)$/;
const required=['index.html','v2.js','v2.css','cp-v2-page-template.mjs','cp-v2-bureau-pages.mjs'];
const digest=bytes=>createHash('sha256').update(bytes).digest('hex');
async function readRegular(file){const stat=await lstat(file);if(!stat.isFile()||stat.isSymbolicLink())throw Error('Regular file required: '+file);if(stat.size>1048576)throw Error('Preview asset bound exceeded');return readFile(file,{flag:constants.O_RDONLY|(constants.O_NOFOLLOW||0)});}
async function optionalLink(file){try{const stat=await lstat(file);if(!stat.isSymbolicLink())throw Error('Refusing to replace a non-symlink: '+file);return await readlink(file);}catch(error){if(error.code==='ENOENT')return null;throw error;}}
// Publishes static V2 assets only. No shell, PM2, application restart, database
// connection, nginx reconfiguration or source-code execution occurs here.
export async function publishPreview({ciRoot='/home/dunedeploy/ci-deploy',previewRoot='/var/lib/dunerealms-cp-v2',requireRoot=true}={}){
if(requireRoot&&process.getuid?.()!==0)throw Error('Root-owned publication service required');
ciRoot=path.resolve(ciRoot);previewRoot=path.resolve(previewRoot);
const marker=async name=>(await readRegular(path.join(ciRoot,name))).toString('utf8').trim();
const revision=await marker('built-commit');if(!markerPattern.test(revision)||revision!==await marker('pending-commit'))throw Error('No matching CI-approved build');
const source=path.join(ciRoot,'artifacts',revision,'website','control-panel','public','cp-v2');
if(await realpath(source)!==source)throw Error('Symlinked artifact paths are refused');
const entries=await readdir(source,{withFileTypes:true});if(entries.length>80)throw Error('Too many preview assets');
const files=new Map();let total=0;
for(const entry of entries){
if(!entry.isFile()||!assetPattern.test(entry.name)||/git/i.test(entry.name)||entry.name==='revision.json')throw Error('Unsupported preview asset: '+entry.name);
const bytes=await readRegular(path.join(source,entry.name));total+=bytes.length;if(bytes.length>1048576||total>5242880)throw Error('Preview asset bound exceeded');files.set(entry.name,bytes);
}
for(const name of required)if(!files.has(name))throw Error('Missing preview asset: '+name);
for(const [name,bytes]of files)if(/\.(?:mjs|js)$/.test(name)){
const pattern=/(?:from\s*|import\s*\(\s*)['"](?:\.\/|\/v2\/)([a-z0-9-]+\.(?:mjs|js))(?:\?[^'"]*)?['"]/g;
for(const match of bytes.toString('utf8').matchAll(pattern))if(!files.has(match[1]))throw Error('Missing preview import: '+match[1]);
}
const hashes=Object.fromEntries([...files].sort(([a],[b])=>a.localeCompare(b)).map(([name,bytes])=>[name,digest(bytes)]));
await mkdir(path.join(previewRoot,'releases'),{recursive:true,mode:0o755});
if(await realpath(previewRoot)!==previewRoot)throw Error('Symlinked preview root refused');
const release=path.join(previewRoot,'releases',revision),current=path.join(previewRoot,'current');
const prior=await optionalLink(current);
let existing=false;try{await lstat(release);existing=true;}catch(error){if(error.code!=='ENOENT')throw error;}
if(existing){
if(await realpath(release)!==release)throw Error('Symlinked release refused');
const manifest=JSON.parse((await readRegular(path.join(release,'revision.json'))).toString('utf8'));
if(manifest.revision!==revision||JSON.stringify(manifest.files)!==JSON.stringify(hashes))throw Error('Immutable preview release differs');
for(const [name,hash]of Object.entries(hashes))if(digest(await readRegular(path.join(release,name)))!==hash)throw Error('Preview release hash mismatch');
}else{
const staging=await mkdtemp(path.join(previewRoot,'releases','.pending-'));
try{
for(const [name,bytes]of files)await writeFile(path.join(staging,name),bytes,{flag:'wx',mode:0o644});
await writeFile(path.join(staging,'revision.json'),JSON.stringify({revision,files:hashes})+'\n',{flag:'wx',mode:0o644});await chmod(staging,0o755);await rename(staging,release);
}finally{if(path.dirname(staging)!==path.join(previewRoot,'releases'))throw Error('Unsafe staging cleanup');await rm(staging,{recursive:true,force:true});}
}
if(revision!==await marker('pending-commit')||revision!==await marker('built-commit'))throw Error('Approved revision changed during publication');
if(prior===release)return {revision,changed:false,files:files.size};
if(prior){const previous=path.join(previewRoot,'previous.next-'+randomUUID());await symlink(prior,previous,'dir');await rename(previous,path.join(previewRoot,'previous'));}
const next=path.join(previewRoot,'current.next-'+randomUUID());await symlink(release,next,'dir');await rename(next,current);
return {revision,changed:true,files:files.size};
}
if(process.argv[1]&&path.resolve(process.argv[1])===fileURLToPath(import.meta.url)){
if(process.argv.length!==2)throw Error('Publication arguments are not accepted');
console.log(JSON.stringify(await publishPreview()));
}