import fs from 'node:fs'; import path from 'node:path'; import http from 'node:http'; import {createHash,randomUUID,timingSafeEqual} from 'node:crypto'; import {pathToFileURL} from 'node:url'; import {engineCanonicalDigest as digest,engineError} from '../../shared/contracts/engines.mjs'; import {engineFileIdentity} from './deepseek-installation.mjs'; import {assertOriginalPurgeStrategy} from './original-purge-source.mjs'; const sha=bytes=>createHash('sha256').update(bytes).digest('hex'); const equal=(left,right)=>typeof left==='string'&&Buffer.byteLength(left)===Buffer.byteLength(right)&&timingSafeEqual(Buffer.from(left),Buffer.from(right)); export function originalPurgeReadRoots(directories,metadata=[]){ const inside=(base,file)=>{const relative=path.relative(base,file);return relative===''||relative!=='..'&&!relative.startsWith('..'+path.sep)&&!path.isAbsolute(relative);}; const roots=[...new Set(directories.map(root=>fs.realpathSync.native(root)))]; // Node 24's Windows permission trie can deny an allowed ancestor when both // it and a descendant are supplied. Keep only the encompassing read grant. const minimal=roots.filter(root=>!roots.some(other=>other!==root&&inside(other,root))); return [...minimal,...new Set(metadata.filter(file=>!minimal.some(root=>inside(root,file))))]; } export const ORIGINAL_PURGE_WRAPPER=String.raw`import fs from 'node:fs'; export const name='workbench-original-purge-restricted'; export const inject=['systemPrompt','tools','appReady']; export async function apply(ctx,config){ const blockedTools=[]; const tools=new Proxy(ctx.tools,{get(target,key){if(key==='register')return definition=>{ if(!['purge_status','purge_apply','purge_revert'].includes(definition.name))throw new Error('Unexpected original tool registration.'); blockedTools.push(definition.name);return ()=>{}; };const value=Reflect.get(target,key,target);return typeof value==='function'?value.bind(target):value;}}); const facade=new Proxy(ctx,{get(target,key){if(key==='tools')return tools;if(key==='get')return name=>name==='tools'?tools:target.get(name); const value=Reflect.get(target,key,target);return typeof value==='function'?value.bind(target):value;}}); const original=await import(config.entry);await original.apply(facade,config.originalConfig); fs.writeFileSync(config.marker,JSON.stringify({schemaVersion:1,pid:process.pid,strategySha256:config.strategySha256, originalEntryLoaded:true,originalApplyCalled:true,blockedTools,originalConfig:config.originalConfig,upstreamPatchInstalled:false}),{flag:'wx'}); } `; // The only executable inputs allowed after this preload are the frozen original // files, pinned Harness JS/JSON and the two generated, hashed host adapters. // Node permissions are defense in depth for this trusted-source profile, not an // OS sandbox. Native builtins belong to the pinned Node executable. Only the // fixed require-builtin addon may use dlopen; it is recorded separately. export const ORIGINAL_PURGE_PRELOAD=String.raw`import fs from 'node:fs'; import path from 'node:path'; import {fileURLToPath,pathToFileURL} from 'node:url'; import {registerHooks,syncBuiltinESMExports,createRequire} from 'node:module'; import {createHash} from 'node:crypto'; const policy=JSON.parse(fs.readFileSync(process.env.AWB_ORIGINAL_PURGE_POLICY,'utf8')); const originalRead=fs.readFileSync.bind(fs),inputs=new Map(policy.inputs.map(input=>[input.path,input])),seen=new Set(); const hash=bytes=>createHash('sha256').update(bytes).digest('hex'); const fileInput=url=>{if(!url.startsWith('file:'))throw new Error('Unsealed module protocol.'); let file;try{file=fs.realpathSync.native(fileURLToPath(url));}catch(error){process.stderr.write('AWB_MODULE_LOOKUP_REFUSED '+url+'\n'+error.stack+'\n');throw error;}const input=inputs.get(file); if(!input||hash(originalRead(file))!==input.sha256){process.stderr.write('AWB_MODULE_REFUSED '+file+'\n');throw new Error('Unsealed or changed module: '+file);}return input;}; const originalDlopen=process.dlopen; process.dlopen=function(module,file,...args){const input=fileInput(pathToFileURL(String(file)).href); if(!policy.nativeAddons.some(native=>native.path===input.path&&native.sha256===input.sha256))throw Object.assign(new Error('Unsealed native addon.'),{code:'ERR_ACCESS_DENIED'}); const result=originalDlopen.call(this,module,file,...args); fs.appendFileSync(policy.nativeModules,JSON.stringify({...input,operation:'actual-process-dlopen'})+'\n');return result;}; registerHooks({resolve(specifier,context,next){ if(context.parentURL?.startsWith(policy.originalUrl)&&specifier==='@deepseek-ai/dsh-llm')return {url:policy.llmModule,shortCircuit:true}; const result=next(specifier,context);if(!result.url.startsWith('node:'))fileInput(result.url);return result; },load(url,context,next){ if(url.startsWith('node:'))return next(url,context); const input=fileInput(url),result=next(url,context),source=result.source==null?null:Buffer.from(result.source); if(source&&hash(source)!==input.sha256)throw new Error('Loaded source differs from sealed bytes.'); if(!seen.has(input.path)){ if(seen.size>=1024)throw new Error('Loaded module count exceeded.');seen.add(input.path); fs.appendFileSync(policy.modules,JSON.stringify({...input,format:result.format??null,sourceSha256:source?hash(source):null})+'\n'); }return result; }}); const koffiModule=createRequire(import.meta.url)(policy.koffiEntry),koffi=koffiModule.default??koffiModule,originalLibraryLoad=koffi.load.bind(koffi); koffi.load=function(name,...args){const library=policy.platformLibraries.find(input=>name.toLowerCase()===input.name||name===input.path); if(!library||hash(originalRead(library.path))!==library.sha256)throw new Error('Unsealed native library.'); const result=originalLibraryLoad(library.path,...args); fs.appendFileSync(policy.nativeLibraries,JSON.stringify({...library,operation:'actual-koffi-load'})+'\n');return result;}; const delegatedStat=(file,options)=>{if(options?.bigint)return null;const item=policy.directoryMetadata[path.resolve(String(file))]; if(!item)return null;const value=Object.assign(Object.create(fs.Stats.prototype),item); for(const key of ['atime','mtime','ctime','birthtime'])value[key]=new Date(value[key]);return value;}; let deniedCount=0;const logDenied=(name,file,error)=>{if(error?.code==='ERR_ACCESS_DENIED'&&deniedCount++<24)process.stderr.write('AWB_ACCESS_REFUSED '+name+' '+String(file)+' resource='+String(error.resource)+'\n'+error.stack+'\n');}; for(const name of ['statSync','lstatSync','readFileSync','realpathSync','readdirSync','accessSync']){const original=fs[name]; const wrapped=function(file,...args){try{return original.call(this,file,...args);}catch(error){logDenied(name,file,error);throw error;}}; Object.assign(wrapped,original);fs[name]=wrapped;} for(const name of ['readFile','stat','lstat','realpath','readdir','access','open']){const original=fs[name]; const wrap=fn=>function(file,...args){const callback=args.at(-1);if(typeof callback==='function')args[args.length-1]=function(error,...values){logDenied(name,file,error);return callback.call(this,error,...values);}; try{return fn.call(this,file,...args);}catch(error){logDenied(name,file,error);throw error;}}; const wrapped=wrap(original);Object.assign(wrapped,original);if(original.native)wrapped.native=wrap(original.native);fs[name]=wrapped;} const stat=fs.promises.stat;fs.promises.stat=async function(file,options){try{return await stat.call(this,file,options);}catch(error){ const value=error.code==='ERR_ACCESS_DENIED'&&delegatedStat(file,options);if(value)return value;logDenied('promises.stat',file,error);throw error;}}; for(const name of ['lstat','readFile','realpath','readdir','access','mkdir','opendir']){const original=fs.promises[name];fs.promises[name]=async function(file,...args){ try{return await original.call(this,file,...args);}catch(error){logDenied('promises.'+name,file,error);throw error;}};} const open=fs.promises.open;fs.promises.open=async function(file,...args){let handle;try{handle=await open.call(this,file,...args);}catch(error){logDenied('promises.open',file,error);throw error;}const sync=handle.sync.bind(handle); handle.sync=async()=>{try{return await sync();}catch(error){if(error.code!=='ERR_ACCESS_DENIED')throw error; const stat=await handle.stat({bigint:true}),response=await fetch(policy.durabilityEndpoint,{method:'POST',signal:AbortSignal.timeout(10000), headers:{'Content-Type':'application/json',Authorization:'Bearer '+process.env.AWB_ORIGINAL_PURGE_DURABILITY_NONCE}, body:JSON.stringify({path:String(file),dev:String(stat.dev),ino:String(stat.ino),size:String(stat.size)})}); if(!response.ok)throw new Error('Owned durability synchronization refused.');await response.json(); }};return handle;}; syncBuiltinESMExports(); `; export class OriginalPurgeRuntime { constructor(strategy,directory){ assertOriginalPurgeStrategy(strategy);this.strategy=strategy;this.directory=fs.realpathSync.native(directory);this.inputs=[]; this.report={schemaVersion:1,kind:strategy.kind,strategySha256:strategy.sha256,runtimeSha256:strategy.runtime.sha256, isolation:strategy.isolation,originalConfig:strategy.originalConfig,upstreamPatchInstalled:false, durabilityReceipts:[],durabilityRejections:[],loadedModules:[],nativeLoads:[],nativeLibraries:[],readiness:null}; } async prepare(launch,installation){ const directory=this.directory,source=path.join(directory,'original-purge');fs.mkdirSync(source); for(const input of this.strategy.source.inputs){ const raw=fs.readFileSync(input.path);if(sha(raw)!==input.sha256)throw engineError('复制前原版输入已变化。'); const target=path.join(source,input.relative);fs.mkdirSync(path.dirname(target),{recursive:true});fs.writeFileSync(target,raw,{flag:'wx'}); this.inputs.push({...engineFileIdentity(target),relative:input.relative}); } this.marker=path.join(directory,'original-purge-ready.json');this.modules=path.join(directory,'original-purge-modules.jsonl');this.nativeModules=path.join(directory,'original-purge-native-modules.jsonl'); this.nativeLibraries=path.join(directory,'original-purge-native-libraries.jsonl'); const wrapper=path.join(directory,'original-purge-wrapper.mjs'),preload=path.join(directory,'original-purge-preload.mjs'),policyFile=path.join(directory,'original-purge-policy.json'); fs.writeFileSync(wrapper,ORIGINAL_PURGE_WRAPPER,{flag:'wx'});fs.writeFileSync(preload,ORIGINAL_PURGE_PRELOAD,{flag:'wx'}); const nonce=randomUUID();this.server=http.createServer((request,response)=>this.handleDurability(request,response,nonce)); await new Promise((resolve,reject)=>{this.server.once('error',reject);this.server.listen(0,'127.0.0.1',resolve);}); const directoryMetadata={}; for(let ancestor=path.dirname(directory);;ancestor=path.dirname(ancestor)){ if(fs.lstatSync(ancestor).isSymbolicLink())throw engineError('所属运行目录祖先不能是链接。'); const stat=fs.statSync(ancestor);directoryMetadata[ancestor]=stat;directoryMetadata[path.toNamespacedPath(ancestor)]=stat; if(path.dirname(ancestor)===ancestor)break; } const patchFile=launch.args.at(-1),patch=JSON.parse(fs.readFileSync(patchFile)); patch.push({insert:[{id:'workbench-original-purge-restricted',name:wrapper,config:{entry:pathToFileURL(path.join(source,'lib/index.js')).href, originalConfig:this.strategy.originalConfig,strategySha256:this.strategy.sha256,marker:this.marker}}]});fs.writeFileSync(patchFile,JSON.stringify(patch)); const executableInputs=[...this.strategy.runtime.inputs,...this.inputs,engineFileIdentity(wrapper),engineFileIdentity(path.join(directory,'bridge.mjs'))]; this.expectedModules=new Map(executableInputs.map(input=>[input.path,input])); const policy={schemaVersion:1,inputs:executableInputs,modules:this.modules,nativeModules:this.nativeModules,nativeLibraries:this.nativeLibraries, platformLibraries:this.strategy.runtime.platformLibraries,koffiEntry:path.join(installation.root,'node_modules/.pnpm/koffi@3.1.1/node_modules/koffi/index.js'), nativeAddons:this.strategy.runtime.nativeAddons,directoryMetadata, originalUrl:pathToFileURL(source+path.sep).href,llmModule:installation.llmModule,durabilityEndpoint:'http://127.0.0.1:'+this.server.address().port+'/fsync'}; fs.writeFileSync(policyFile,JSON.stringify(policy),{flag:'wx'}); this.launchInputs=[engineFileIdentity(wrapper),engineFileIdentity(preload),engineFileIdentity(policyFile),...this.inputs]; const metadataReads=[]; for(const anchor of [installation.root,launch.cwd,source])for(let ancestor=path.dirname(anchor);;ancestor=path.dirname(ancestor)){ metadataReads.push(path.join(ancestor,'node_modules','*'),path.join(ancestor,'package.json'));if(path.dirname(ancestor)===ancestor)break; } const readRoots=originalPurgeReadRoots([installation.root,path.dirname(installation.node.path),directory,launch.cwd], [...metadataReads,...this.strategy.runtime.platformLibraries.map(input=>input.path)]); launch.args=['--permission','--allow-addons',...[...new Set(readRoots)].flatMap(root=>['--allow-fs-read='+root,'--allow-fs-read='+path.toNamespacedPath(root)]), '--allow-fs-write='+directory,'--allow-fs-write='+path.toNamespacedPath(directory),'--import',pathToFileURL(preload).href,...launch.args]; Object.assign(launch.env,{USERPROFILE:path.join(directory,'home'),APPDATA:path.join(directory,'home'),LOCALAPPDATA:path.join(directory,'home'), NARB_DISABLE_NATIVE_CACHE:'1',AWB_ORIGINAL_PURGE_POLICY:policyFile,AWB_ORIGINAL_PURGE_DURABILITY_NONCE:nonce}); this.report.launchInputs=this.launchInputs;this.report.originalCopies=this.inputs; this.report.permissionPolicy={readRoots,writeRoot:directory,arguments:launch.args,cwd:launch.cwd,nativeCache:false}; return launch; } async handleDurability(request,response,nonce){ try{ if(this.closed||request.method!=='POST'||request.url!=='/fsync'||request.headers.origin!==undefined||request.headers['content-type']!=='application/json' ||!equal(request.headers.authorization,'Bearer '+nonce))throw engineError('同步请求不属于当前运行。'); const chunks=[];let size=0;for await(const chunk of request){size+=chunk.length;if(size>4096)throw engineError('同步输入超限。');chunks.push(chunk);} const value=JSON.parse(Buffer.concat(chunks)),file=path.resolve(value.path); if(Object.keys(value).sort().join(',')!=='dev,ino,path,size'||!file.startsWith(this.directory+path.sep)||fs.realpathSync.native(file)!==file)throw engineError('同步路径不属于运行目录。'); for(let current=file;current!==this.directory;current=path.dirname(current))if(fs.lstatSync(current).isSymbolicLink())throw engineError('同步路径不能经过链接。'); const fd=fs.openSync(file,'r+');try{ const stat=fs.fstatSync(fd,{bigint:true});if(!stat.isFile()||stat.size>64n*1024n*1024n)throw engineError('同步文件超限。'); for(const key of ['dev','ino','size'])if(String(stat[key])!==value[key])throw engineError('同步文件身份已变化。'); fs.fsyncSync(fd);const bytes=fs.readFileSync(fd); if(BigInt(bytes.length)!==stat.size)throw engineError('同步期间文件发生变化。'); this.report.durabilityReceipts.push({path:path.relative(this.directory,file),dev:value.dev,ino:value.ino,size:value.size,sha256:sha(bytes),operation:'actual-parent-fsync'}); }finally{fs.closeSync(fd);} response.writeHead(200,{'Content-Type':'application/json',Connection:'close'});response.end('{"flushed":true}'); }catch(error){this.report.durabilityRejections.push({at:new Date().toISOString(),reason:error.message}); if(!response.destroyed){response.writeHead(409,{'Content-Type':'application/json',Connection:'close'});response.end('{"error":"Owned durability request refused"}');}} } verify({ready=false,pid=null}={}){ assertOriginalPurgeStrategy(this.strategy); for(const input of this.launchInputs??[])if(engineFileIdentity(input.path).sha256!==input.sha256)throw engineError('所属原版运行副本或适配输入已变化。',409,'ENGINE_INPUT_CHANGED'); if(ready||this.report.readiness){ const marker=JSON.parse(fs.readFileSync(this.marker)); if(marker.schemaVersion!==1||marker.pid!==(pid??this.report.readiness?.pid)||marker.strategySha256!==this.strategy.sha256 ||marker.originalEntryLoaded!==true||marker.originalApplyCalled!==true||marker.upstreamPatchInstalled!==false ||digest(marker.originalConfig)!==digest(this.strategy.originalConfig) ||digest([...marker.blockedTools].sort())!==digest(['purge_apply','purge_revert','purge_status']))throw engineError('原版入口、受限配置或外部工具门控不符合封存策略。'); this.report.readiness=marker; } if(fs.existsSync(this.modules)){ if(fs.statSync(this.modules).size>4*1024*1024)throw engineError('原版模块收据超限。'); const lines=fs.readFileSync(this.modules,'utf8').trimEnd().split('\n'); this.report.loadedModules=lines.filter(Boolean).map(line=>{const item=JSON.parse(line),expected=this.expectedModules.get(item.path); if(!expected||item.sha256!==expected.sha256||item.bytes!==expected.bytes||item.sourceSha256!==null&&item.sourceSha256!==expected.sha256)throw engineError('实际加载模块与封存输入不符。');return item;}); if(this.report.loadedModules.length>1024)throw engineError('原版模块收据数量超限。'); } if(fs.existsSync(this.nativeModules)){ if(fs.statSync(this.nativeModules).size>65536)throw engineError('原生加载收据超限。'); this.report.nativeLoads=fs.readFileSync(this.nativeModules,'utf8').trimEnd().split('\n').filter(Boolean).map(line=>{const item=JSON.parse(line); if(!this.strategy.runtime.nativeAddons.some(expected=>expected.path===item.path&&expected.sha256===item.sha256&&expected.bytes===item.bytes) ||item.operation!=='actual-process-dlopen')throw engineError('实际原生加载不属于固定清单。');return item;}); } if(fs.existsSync(this.nativeLibraries)){ if(fs.statSync(this.nativeLibraries).size>65536)throw engineError('原生库加载收据超限。'); this.report.nativeLibraries=fs.readFileSync(this.nativeLibraries,'utf8').trimEnd().split('\n').filter(Boolean).map(line=>{const item=JSON.parse(line); if(!this.strategy.runtime.platformLibraries.some(expected=>expected.path===item.path&&expected.sha256===item.sha256&&expected.bytes===item.bytes) ||item.operation!=='actual-koffi-load')throw engineError('实际原生库加载不属于固定清单。');return item;}); } if(ready&&this.report.nativeLoads.length!==this.strategy.runtime.nativeAddons.length)throw engineError('未核对固定原生模块的实际加载。'); return this.report; } async close(){if(this.closed)return;this.closed=true;if(this.server){this.server.closeAllConnections();await new Promise(resolve=>this.server.close(resolve));}} }