Audit a delivery package for missing, extra and changed files
Run a Node.js SHA-256 audit over an original three-file handoff and reject missing files, extras, same-size byte edits, unsafe paths and symlinks.
Establish whether a received package has exactly the expected local regular files and byte contents. A checksum manifest detects change relative to a trusted copy; it is not an authenticity signature or media-quality check.
Previously recorded numerical observations below describe the original local fixture runs. For a reproduction, use the new receipt and its actual tool versions and hashes; an old observation is not a guaranteed result on every installation.
Preparation
- Save each complete code block below under its displayed filename in one empty local folder. Run commands from that folder. The scripts create their synthetic inputs and manifests in the chosen output directory; inspect those files after running. Use an output directory that does not already exist. All relative paths below refer to this working folder.
- Use Node.js with built-in filesystem and crypto modules. The original delivery folder contains delivery-notes.txt, shots.json and captions.srt.
- Inspect delivery-manifest.json outside the delivery/ folder. Its three rows bind basename, byte count and SHA-256; excluding the manifest itself avoids a circular self-hash.
- Choose a new output directory and preserve the expected manifest separately from any editable received files. The generated fixture totals 171 bytes before receipts and documentation.
Run
node run-recipe.mjs --out ./my-run
01. Freeze the expected file inventory
The script writes an original miniature handoff and captures its sorted filename list, byte sizes and SHA-256 values. The expected set is exact: an additional file is reviewable evidence of a mismatch rather than something silently skipped.
02. Require safe regular files
Validate unique safe basenames, compare expected and actual inventories, then use lstat to reject a symlink before reading contents. This fixture audits one flat directory, not an arbitrary nested archive or a concurrent untrusted filesystem.
03. Check sizes and full byte hashes
For each expected file, compare both size and SHA-256. The same-size mutation flips one byte of delivery-notes.txt, proving that size alone is insufficient. SHA-256 proves equality to this expected manifest, not that its author is trusted.
04. Restore and rerun the handoff audit
The suite temporarily removes a file, adds an extra file, changes bytes and replaces a file with a symlink, always restoring originals in finally. It also rejects duplicate manifest paths and ../outside.txt. The restored package passes again, with nine checks retained.
Acceptance
- The clean delivery folder contains exactly the three declared regular files.
- Every expected SHA-256 is a 64-character lowercase hexadecimal digest.
- A missing file and an unexpected extra file are separately rejected.
- A one-byte change that preserves file size fails its checksum comparison.
- Duplicate manifest paths, a parent path and a symlink are rejected.
- After the negative fixtures are restored, the complete package passes again; all nine checks pass.
Troubleshooting
All byte sizes match but the audit fails.
Compare the actual SHA-256 of the named file with its expected row; restore the correct bytes instead of removing the hash check.
An extra export appears in the package.
Decide whether that file belongs in the handoff. Remove only the accidental file, or deliberately revise the expected manifest and have it reviewed.
A shortcut or symlink is rejected.
Replace only that entry with a real local regular file, then capture the intended file’s bytes and rerun inventory plus SHA-256 checks.
Keep with the result
Keep a trusted manifest and the actual audit receipt with the handoff. The audit does not decode video, establish authorship or protect a manifest that was itself replaced by an attacker.
Complete source and input construction
Save every file below with its exact filename in the same folder. The source includes the input definitions and construction logic; code blocks are complete, including all companion modules.
common.mjs
import fs from 'node:fs';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
import { createHash } from 'node:crypto';
import { deflateSync } from 'node:zlib';
import { spawnSync } from 'node:child_process';
import http from 'node:http';
export { fs, path, http };
export const sha = b => createHash('sha256').update(b).digest('hex');
export const ensure = (v,m) => { if (!v) throw new Error(m); };
export const json = (p,v) => fs.writeFileSync(p,JSON.stringify(v,null,2)+'\n');
export function png(w,h,colour) {
const raw=Buffer.alloc(h*(w*3+1));
for(let y=0;y<h;y++) for(let x=0;x<w;x++) { const c=typeof colour==='function'?colour(x,y):colour; for(let k=0;k<3;k++) raw[y*(w*3+1)+1+x*3+k]=c[k]; }
const crc=b=>{let c=0xffffffff;for(const n of b){c^=n;for(let j=0;j<8;j++)c=(c>>>1)^((c&1)?0xedb88320:0);}return(c^0xffffffff)>>>0;};
const chunk=(t,b)=>{const n=Buffer.alloc(4),s=Buffer.from(t),c=Buffer.alloc(4);n.writeUInt32BE(b.length);c.writeUInt32BE(crc(Buffer.concat([s,b])));return Buffer.concat([n,s,b,c]);};
const head=Buffer.alloc(13);head.writeUInt32BE(w);head.writeUInt32BE(h,4);head[8]=8;head[9]=2;
return Buffer.concat([Buffer.from([137,80,78,71,13,10,26,10]),chunk('IHDR',head),chunk('IDAT',deflateSync(raw)),chunk('IEND',Buffer.alloc(0))]);
}
export function dimensions(b){ensure(b.subarray(0,8).equals(Buffer.from([137,80,78,71,13,10,26,10])),'PNG_SIGNATURE');return[b.readUInt32BE(16),b.readUInt32BE(20)];}
export const maxDelta=(a,b)=>{ensure(a.length===b.length,'BYTE_LENGTH');let d=0;for(let i=0;i<a.length;i++)d=Math.max(d,Math.abs(a[i]-b[i]));return d;};
export const safeName=s=>typeof s==='string'&&/^[a-zA-Z0-9][a-zA-Z0-9_.-]*$/.test(s);
export async function request(url,method='GET',body){
const u=new URL(url);ensure(u.hostname==='127.0.0.1'&&u.protocol==='http:','LOOPBACK_ONLY');
return await new Promise((resolve,reject)=>{const q=http.request(u,{method,agent:false,headers:body?{'content-type':'application/json'}:{}},r=>{let size=0;const a=[];r.on('data',b=>{size+=b.length;if(size>2*1024*1024){r.destroy(new Error('RESPONSE_LIMIT'));return;}a.push(b);});r.on('error',reject);r.on('end',()=>resolve({status:r.statusCode,body:Buffer.concat(a)}));});q.setTimeout(3000,()=>q.destroy(new Error('HTTP_TIMEOUT')));q.on('error',reject);q.end(body===undefined?undefined:JSON.stringify(body));});
}
export async function closeServer(server){await new Promise((resolve,reject)=>{server.close(e=>e?reject(e):resolve());server.closeAllConnections();});}
export async function run(task,fn,media=false){
const here=path.dirname(fileURLToPath(import.meta.url));const args=process.argv.slice(2);ensure(args.length===0||(args.length===2&&args[0]==='--out'),'USAGE: node run-recipe.mjs --out NEW_DIRECTORY');
const out=path.resolve(args[1]||path.join(here,'my-run'));ensure(!fs.existsSync(out),'REFUSE_OVERWRITE');fs.mkdirSync(out,{recursive:true});
const tmp=path.join(out,'.tmp');fs.mkdirSync(tmp);const tests=[],failures=[],commands=[];const scripts=Object.fromEntries(['run-recipe.mjs','common.mjs'].map(n=>[n,sha(fs.readFileSync(path.join(here,n)))]));
const h={out,tmp,info:{},p:n=>path.join(out,n),check:(name,v,detail={})=>{ensure(v,`CHECK_FAILED:${name}`);tests.push({name,passed:true,...detail});},reject:(name,fn,pattern)=>{let e;try{fn();}catch(x){e=x;}ensure(e&&(!pattern||pattern.test(e.message)),`EXPECTED_REJECTION_MISSING:${name}`);const r={name,passed:true,expectedRejection:true,error:String(e.message).slice(0,900)};tests.push(r);failures.push(r);}};
const bin=process.env.FFMPEG_BIN||'ffmpeg';
h.ff=(args,allowFailure=false)=>{const all=['-hide_banner','-nostdin','-loglevel','error','-threads','1','-filter_threads','1',...args];const r=spawnSync(bin,all,{shell:false,timeout:15000,killSignal:'SIGKILL',maxBuffer:8*1024*1024});commands.push({args:all,status:r.status,signal:r.signal,stdoutBytes:r.stdout?.length||0,stderrTail:r.stderr?.toString().slice(-1800)||'',error:r.error?.message||null});if(!allowFailure)ensure(!r.error&&r.status===0,`FFMPEG:${r.error?.message||r.stderr?.toString().slice(-900)}`);return r;};
h.decode=(file,w,hgt)=>{const r=h.ff(['-xerror','-err_detect','explode','-i',file,'-map','0:v:0','-an','-pix_fmt','rgb24','-f','rawvideo','pipe:1']);ensure(r.stdout.length>0&&r.stdout.length%(w*hgt*3)===0,'DECODE_GEOMETRY');return r.stdout;};
let fatal=null;let ffmpeg=null;
try{if(media){const r=h.ff(['-version']);ffmpeg={version:r.stdout.toString().split('\n')[0],binarySha256:path.isAbsolute(bin)?sha(fs.readFileSync(bin)):null};}await fn(h);ensure(tests.length>=6,'AT_LEAST_SIX_CHECKS');}
catch(e){fatal=e.stack||String(e);process.exitCode=1;}
finally{fs.rmSync(tmp,{recursive:true,force:true});const scriptsAfter=Object.fromEntries(Object.keys(scripts).map(n=>[n,sha(fs.readFileSync(path.join(here,n)))]));if(JSON.stringify(scriptsAfter)!==JSON.stringify(scripts)){fatal='SCRIPT_CHANGED_DURING_RUN';process.exitCode=1;}
const receipt={task,recordedAt:new Date().toISOString(),nodeVersion:process.version,ffmpeg,scriptHashes:scripts,scriptBindingVerified:JSON.stringify(scriptsAfter)===JSON.stringify(scripts),fixtureOnly:true,providerModelTest:false,productionTaskRun:false,networkScope:'loopback-only or no network',passed:!fatal,checks:tests,observations:h.info,commands,fatal};json(h.p('execution-receipt.json'),receipt);json(h.p('failure-receipt.json'),{task,expectedFailureChecks:failures});fs.writeFileSync(h.p('checks.csv'),'check,result,expected_rejection\n'+tests.map(t=>`${t.name},${t.passed?'pass':'fail'},${Boolean(t.expectedRejection)}`).join('\n')+'\n');console.log(JSON.stringify({task,passed:!fatal,checks:tests.length,expectedRejections:failures.length,out}));if(fatal)console.error(fatal);}
}
run-recipe.mjs
import {fs,path,sha,json,ensure,safeName,run} from './common.mjs';
await run('output-package-checksum-audit',async h=>{
const dir=h.p('delivery');fs.mkdirSync(dir);fs.writeFileSync(path.join(dir,'delivery-notes.txt'),'Original fixture delivery package. No generated model media.\n');json(path.join(dir,'shots.json'),{shots:['opening','hinge','hold']});fs.writeFileSync(path.join(dir,'captions.srt'),'1\n00:00:00,000 --> 00:00:01,000\nReview the hinge.\n');const manifest=fs.readdirSync(dir).sort().map(file=>({file,bytes:fs.statSync(path.join(dir,file)).size,sha256:sha(fs.readFileSync(path.join(dir,file)))}));json(h.p('delivery-manifest.json'),{algorithm:'sha256',files:manifest});
const audit=rows=>{ensure(new Set(rows.map(r=>r.file)).size===rows.length,'DUPLICATE_MANIFEST_PATH');for(const r of rows)ensure(safeName(r.file),'UNSAFE_PATH');const actual=fs.readdirSync(dir).sort(),expected=rows.map(r=>r.file).sort();ensure(expected.every(f=>actual.includes(f)),'MISSING_FILE');ensure(actual.every(f=>expected.includes(f)),'EXTRA_FILE');for(const r of rows){const p=path.join(dir,r.file);ensure(fs.lstatSync(p).isFile()&&!fs.lstatSync(p).isSymbolicLink(),'REGULAR_FILE_REQUIRED');const b=fs.readFileSync(p);ensure(b.length===r.bytes,'SIZE_CHANGED');ensure(sha(b)===r.sha256,'CHECKSUM_CHANGED');}return true;};h.check('clean-delivery-package-accepted',audit(manifest));h.check('sha256-has-sixty-four-hex-digits',manifest.every(r=>/^[a-f0-9]{64}$/.test(r.sha256)));const victim=path.join(dir,'delivery-notes.txt'),original=fs.readFileSync(victim);fs.unlinkSync(victim);try{h.reject('missing-delivery-file-rejected',()=>audit(manifest),/MISSING_FILE/);}finally{fs.writeFileSync(victim,original);}fs.writeFileSync(path.join(dir,'extra.txt'),'unexpected');try{h.reject('extra-delivery-file-rejected',()=>audit(manifest),/EXTRA_FILE/);}finally{fs.unlinkSync(path.join(dir,'extra.txt'));}const changed=Buffer.from(original);changed[0]^=1;fs.writeFileSync(victim,changed);try{h.reject('same-size-byte-change-rejected',()=>audit(manifest),/CHECKSUM_CHANGED/);}finally{fs.writeFileSync(victim,original);}h.reject('duplicate-manifest-path-rejected',()=>audit([...manifest,manifest[0]]),/DUPLICATE_MANIFEST_PATH/);h.reject('parent-path-rejected',()=>audit([{...manifest[0],file:'../outside.txt'}]),/UNSAFE_PATH/);fs.renameSync(victim,h.tmp+'/original.txt');fs.symlinkSync(h.tmp+'/original.txt',victim);try{h.reject('symlink-file-rejected',()=>audit(manifest),/REGULAR_FILE_REQUIRED/);}finally{fs.unlinkSync(victim);fs.renameSync(h.tmp+'/original.txt',victim);}h.check('restored-delivery-package-accepted',audit(manifest));h.info={files:manifest.length,totalBytes:manifest.reduce((n,r)=>n+r.bytes,0),algorithm:'SHA-256',selfManifestExcluded:true,authenticitySignature:false,mediaDecodeTest:false};
});