Files
vHost/deploy/package-release.mjs
T

61 lines
6.3 KiB
JavaScript

// Package only declared project inputs. Never recursively copy the workspace.
import fs from 'node:fs';
import path from 'node:path';
import crypto from 'node:crypto';
import {fileURLToPath} from 'node:url';
import {execFileSync} from 'node:child_process';
const root=path.resolve(path.dirname(fileURLToPath(import.meta.url)),'..');
const build=path.join(root,'build');
const config=JSON.parse(fs.readFileSync(path.join(root,'deploy/release-files.json'),'utf8'));
const requiredBinaries=['sea-vhost-api','sea-vhost-agent','sea-vhost-panel-broker','sea-vhost-node','sea-vhost-run','sea-vhost-scheduler'];
const skip=new Set(['node_modules','__pycache__','.git','.cache','.npm-cache']);
const hash=b=>crypto.createHash('sha256').update(b).digest('hex');
const slash=p=>p.split(path.sep).join('/');
function inside(base,name){const target=path.resolve(base,name),relative=path.relative(base,target);if(!relative||relative.startsWith('..')||path.isAbsolute(relative))throw Error('Path outside allowed output directory');return target}
function validateName(name){if(!name||name.includes('\\')||name.includes('\n')||path.posix.isAbsolute(name)||name.split('/').some(v=>v==='..'||v===''))throw Error('Unsafe package path');return name}
function collect(files,dirs){
const found=new Set();
function visit(name){validateName(name);const full=inside(root,name),s=fs.lstatSync(full);if(s.isSymbolicLink())throw Error('Refusing package symlink: '+name);if(s.isDirectory()){for(const item of fs.readdirSync(full).sort()){if(skip.has(item)||item.startsWith('.tmp')||item.endsWith('.pyc')||item.endsWith('.tsbuildinfo'))continue;visit(name+'/'+item)}}else if(s.isFile()){if(path.basename(name)==='.env')throw Error('Live environment file in package');found.add(name)}else throw Error('Non-regular package input: '+name)}
for(const name of [...files,...dirs])visit(name);
return [...found].sort();
}
function scanSecrets(files){
// Certificate forms contain PEM header placeholders. Reject actual key
// material, including escaped newlines, rather than the header text alone.
const patterns=[[/-----BEGIN (?:RSA |EC |OPENSSH |ENCRYPTED )?PRIVATE KEY-----(?:\s|\\[rn])*(?:[A-Za-z0-9+/=](?:\s|\\[rn])*){80,}/,'private-key'],[/\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/,'aws-access-key'],[/\bgh[pousr]_[A-Za-z0-9]{30,}\b/,'github-token']];
const actualSecret=process.env.SEA_PANEL_API_KEY;
for(const name of files){const data=fs.readFileSync(path.join(root,name));if(actualSecret&&data.includes(Buffer.from(actualSecret)))throw Error('Live panel credential detected in '+name);if(!/\.(?:go|mjs|js|ts|tsx|py|sh|md|json|example|conf|service|sql)$/.test(name)||name.endsWith('_test.go')||/\.test\.(?:ts|tsx|mjs)$/.test(name)||name==='deploy/package-release.mjs')continue;const value=data.toString('utf8');for(const [pattern,kind] of patterns)if(pattern.test(value))throw Error('Potential '+kind+' in '+name)}
}
function checkBuild(){
for(const name of requiredBinaries){const file=path.join(build,'bin',name),s=fs.lstatSync(file);if(!s.isFile()||s.isSymbolicLink()||!fs.readFileSync(file).subarray(0,4).equals(Buffer.from([127,69,76,70])))throw Error('Missing Linux ELF: '+name)}
if(!fs.statSync(path.join(build,'web/index.html')).isFile())throw Error('Frontend build missing');
const actual=fs.readdirSync(path.join(build,'bin')).sort();if(JSON.stringify(actual)!==JSON.stringify([...requiredBinaries].sort()))throw Error('Unexpected file in build/bin');
}
function writePackage(kind,files){
const archiveName=kind==='runtime'?'sea-vhost-linux-amd64.tar.gz':'sea-vhost-source.tar.gz';
const output=inside(build,archiveName),stage=fs.mkdtempSync(path.join(build,'release-stage-'));
try{
const entries=files.map(name=>{const source=path.join(root,name),target=inside(stage,name);fs.mkdirSync(path.dirname(target),{recursive:true});fs.copyFileSync(source,target);const executable=name.startsWith('build/bin/')||name.endsWith('.sh');fs.chmodSync(target,executable?0o755:0o644);return {path:name,bytes:fs.statSync(source).size,sha256:hash(fs.readFileSync(source))}});
const manifest={format:'sea-vhost.release',version:1,kind,createdAt:new Date().toISOString(),platform:'linux/amd64',databaseMigrations:fs.readdirSync(path.join(root,'backend/internal/migrations')).filter(n=>/^\d{3}_.+\.sql$/.test(n)).length,files:entries};
fs.writeFileSync(path.join(stage,'RELEASE-MANIFEST.json'),JSON.stringify(manifest,null,2)+'\n');
const names=[...files,'RELEASE-MANIFEST.json'].sort();
const listing=path.join(stage,'package-list.txt');fs.writeFileSync(listing,names.join('\n')+'\n');
const temporary=inside(build,archiveName+'.pending');
execFileSync('tar',['-czf',temporary,'-C',stage,'-T',listing],{stdio:'pipe'});
const actual=execFileSync('tar',['-tzf',temporary],{encoding:'utf8'}).split(/\r?\n/).filter(Boolean).sort();
if(JSON.stringify(actual)!==JSON.stringify(names))throw Error('Archive content verification failed');
if(fs.existsSync(output)){const prior=hash(fs.readFileSync(output)),history=inside(build,'archive');fs.mkdirSync(history,{recursive:true});const archived=inside(history,archiveName.replace('.tar.gz','-'+prior.slice(0,12)+'.tar.gz'));if(!fs.existsSync(archived))fs.copyFileSync(output,archived)}
fs.renameSync(temporary,output);
const digest=hash(fs.readFileSync(output));fs.writeFileSync(output+'.sha256',digest+' '+archiveName+'\n');
fs.writeFileSync(inside(build,kind+'-manifest.json'),JSON.stringify(manifest,null,2)+'\n');
return {name:archiveName,sha256:digest,bytes:fs.statSync(output).size,files:entries.length};
}finally{const safe=inside(build,path.basename(stage));if(safe!==stage||!path.basename(safe).startsWith('release-stage-'))throw Error('Unsafe staging cleanup');fs.rmSync(safe,{recursive:true,force:true})}
}
checkBuild();fs.mkdirSync(build,{recursive:true});
const runtime=collect(config.runtimeFiles,config.runtimeDirectories),source=collect(config.sourceFiles,config.sourceDirectories);
scanSecrets([...new Set([...runtime,...source])]);
const report={format:'sea-vhost.package-verification',createdAt:new Date().toISOString(),curatedInputs:true,knownLivePanelCredentialChecked:Boolean(process.env.SEA_PANEL_API_KEY),secretScan:'passed (private keys, common token patterns, and supplied live credential; not a complete secret audit)',packages:[writePackage('runtime',runtime),writePackage('source',source)]};
fs.writeFileSync(inside(build,'release-verification.json'),JSON.stringify(report,null,2)+'\n');
console.log(JSON.stringify(report));