import assert from 'node:assert/strict';import {createHash}from'node:crypto';import {readFileSync,readdirSync,existsSync,mkdirSync,copyFileSync,writeFileSync}from'node:fs';import{homedir}from'node:os';import{join,dirname,relative}from'node:path'; const hash=bytes=>createHash('sha256').update(bytes).digest('hex'); export function snapshotCryptoDependencies(root,directory,lockPath){ const packageRows=readFileSync(lockPath,'utf8').split('[[package]]').slice(1).filter(s=>s.includes('source = "registry+https://github.com/rust-lang/crates.io-index"')).map(s=>Object.fromEntries(['name','version','checksum'].map(k=>[k,s.match(new RegExp('^'+k+' = "([^\"]+)"','m'))?.[1]]))); assert.ok(packageRows.length>0&&packageRows.length<=16);const roots=readdirSync(join(homedir(),'.cargo/registry/src')),packages=[]; for(const pkg of packageRows){const name=pkg.name+'-'+pkg.version,registry=roots.filter(r=>existsSync(join(homedir(),'.cargo/registry/src',r,name)));assert.equal(registry.length,1,name);const source=join(homedir(),'.cargo/registry/src',registry[0],name),checksums=JSON.parse(readFileSync(join(source,'.cargo-checksum.json')));assert.equal(checksums.package,pkg.checksum);const archive=join(homedir(),'.cargo/registry/cache',registry[0],name+'.crate');assert.equal(hash(readFileSync(archive)),pkg.checksum);const files=[]; for(const[path,checksum]of Object.entries(checksums.files)){assert.ok(!path.startsWith('/')&&!path.split('/').includes('..'));const input=join(source,path),bytes=readFileSync(input);assert.equal(hash(bytes),checksum,name+'/'+path);const target=join(directory,'dependencies',name,path);mkdirSync(dirname(target),{recursive:true});copyFileSync(input,target);files.push({path:relative(root,target),sha256:checksum});} const manifest=join(directory,'dependencies',name,'.cargo-checksum.json');copyFileSync(join(source,'.cargo-checksum.json'),manifest);packages.push({...pkg,archiveVerified:true,checksumManifest:{path:relative(root,manifest),sha256:hash(readFileSync(manifest))},files}); } const report={schema:'turkos-crypto-provider-dependency-snapshot/v1',status:'CHECKSUMS_AND_SOURCES_VERIFIED',lock:{path:relative(root,lockPath),sha256:hash(readFileSync(lockPath))},packages};const path=join(directory,'dependency-sources.json');writeFileSync(path,JSON.stringify(report,null,2)+'\n');return{path:relative(root,path),sha256:hash(readFileSync(path))}; }