feat: integrate pinned original Purge with host execution gates
This commit is contained in:
@@ -9,7 +9,8 @@ import { isId } from '../../shared/contracts/execution.mjs';
|
||||
import { readOwnedProcessTree } from '../owned-process-tree.mjs';
|
||||
import { CONTROLLED_BRIDGE_PLUGIN } from './controlled-plugin.mjs';
|
||||
import { assertControlledInstallation, controlledDigest, controlledPatch, controlledToolCatalogue, CONTROLLED_ENGINE_SCOPE } from './controlled-installation.mjs';
|
||||
import { assertPurgeStrategy } from './purge-strategy.mjs';
|
||||
import { assertPurgeStrategy, PURGE_PROMPT_KIND, ORIGINAL_PURGE_KIND } from './purge-strategy.mjs';
|
||||
import { OriginalPurgeRuntime } from './original-purge-runtime.mjs';
|
||||
|
||||
const allowedEnvironment = /^(path|pathext|systemroot|systemdrive|windir|comspec|temp|tmp|userprofile|appdata|localappdata|programfiles(?:\(x86\))?|homedrive|homepath)$/i;
|
||||
const at = () => new Date().toISOString();
|
||||
@@ -51,7 +52,7 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
|
||||
const pluginConfig = { owner: this.owner, sdkSessionId, tools: catalogue, catalogueSha256, nonce, marker,
|
||||
llmModule: this.installation.llmModule, endpoint: 'http://127.0.0.1:' + this.guard.address().port,
|
||||
maximumFrameBytes: this.maximumFrameBytes, model: config.model, maxOutputTokens: config.maxOutputTokens, contextLimit: config.contextLimit,
|
||||
...(strategy ? { promptExperiment: { sha256: strategy.sha256, section: strategy.section } } : {}) };
|
||||
...(strategy?.kind===PURGE_PROMPT_KIND ? { promptExperiment: { sha256: strategy.sha256, section: strategy.section } } : {}) };
|
||||
fs.writeFileSync(plugin, CONTROLLED_BRIDGE_PLUGIN, { flag: 'wx' }); fs.writeFileSync(patch, JSON.stringify(controlledPatch(plugin, pluginConfig)), { flag: 'wx' });
|
||||
this.report.launchInputs = { plugin: engineFileIdentity(plugin), patch: engineFileIdentity(patch), cwd: fs.realpathSync.native(cwd),
|
||||
disabledPlugins: this.installation.disabledPlugins, catalogue, catalogueSha256 };
|
||||
@@ -59,8 +60,12 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
|
||||
for (const name of Object.keys(process.env)) if (allowedEnvironment.test(name)) env[name] = process.env[name];
|
||||
Object.assign(env, { DSH_HOME: home, DSH_AGENTS_HOME: agents, DSH_TELEMETRY_DISABLED: 'true' });
|
||||
signal?.throwIfAborted(); assertControlledInstallation(this.installation);
|
||||
this.client = this.clientFactory({ executable: this.installation.node.path,
|
||||
args: [this.installation.entry, '--profile', this.installation.profile, '--patch', patch], cwd, env },
|
||||
let launch={executable:this.installation.node.path,args:[this.installation.entry,'--profile',this.installation.profile,'--patch',patch],cwd,env};
|
||||
if(strategy?.kind===ORIGINAL_PURGE_KIND){
|
||||
this.originalPurge=new OriginalPurgeRuntime(strategy,directory);this.report.originalPurge=this.originalPurge.report;
|
||||
launch=await this.originalPurge.prepare(launch,this.installation);this.report.launchInputs.patch=engineFileIdentity(patch);
|
||||
}
|
||||
this.client = this.clientFactory(launch,
|
||||
{ timeoutMs: this.timeoutMs, maximumFrameBytes: this.maximumFrameBytes, cancellationMethod: null });
|
||||
this.report.process = { pid: this.client.pid, connectionId: this.client.id, startedAt: this.client.startedAt, ownership: 'one-process-per-engine-run' };
|
||||
onState('starting', this.report.process);
|
||||
@@ -95,7 +100,8 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
|
||||
if (controlledDigest(ready.owner) !== controlledDigest(this.owner) || ready.sdkSessionId !== sdkSessionId
|
||||
|| ready.catalogueSha256 !== catalogueSha256 || controlledDigest(ready.catalogue) !== catalogueSha256
|
||||
|| JSON.stringify(ready.providers) !== JSON.stringify(['agent-workbench'])
|
||||
|| (ready.promptExperimentSha256 ?? null) !== (strategy?.sha256 ?? null)) throw engineError('启动后工具、模型、实验提示或Run目录不符合封存契约。');
|
||||
|| (ready.promptExperimentSha256 ?? null) !== (strategy?.kind===PURGE_PROMPT_KIND?strategy.sha256:null)) throw engineError('启动后工具、模型、实验提示或Run目录不符合封存契约。');
|
||||
this.originalPurge?.verify({ready:true,pid:this.client.pid});
|
||||
this.verifyLaunch(); onState('initializing', { readiness: ready });
|
||||
const initialized = await this.request('initialize', { cwd, provider: 'agent-workbench', model: config.model, maxTokens: config.maxOutputTokens });
|
||||
if (controlledDigest(initialized.serverInfo) !== controlledDigest(this.installation.serverInfo)) throw engineError('受控SDK返回身份不符合固定发行。');
|
||||
@@ -109,6 +115,7 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
|
||||
for (const input of [this.report.launchInputs.plugin, this.report.launchInputs.patch]) {
|
||||
if (engineFileIdentity(input.path).sha256 !== input.sha256) throw engineError('所属叠加插件或启动输入发生变化。');
|
||||
}
|
||||
this.originalPurge?.verify();
|
||||
}
|
||||
async captureTree(publish = true) {
|
||||
const info = this.report.process, tree = await this.processTreeReader(info);
|
||||
@@ -211,6 +218,7 @@ export class ControlledDeepSeekSession extends DeepSeekAdapter {
|
||||
}
|
||||
if (this.guard) { this.guard.closeAllConnections(); await new Promise(resolve => this.guard.close(resolve)); }
|
||||
await Promise.allSettled([...this.pending]);
|
||||
if(this.originalPurge){try{this.originalPurge.verify();}catch(error){failure??=error;}finally{await this.originalPurge.close();}}
|
||||
if (!interrupted && this.report.launchInputs) { try { this.verifyLaunch(); } catch (error) { failure ??= error; } }
|
||||
if (!interrupted && this.report.cleanup?.exit?.code !== 0) failure ??= engineError('所属引擎未正常退出。');
|
||||
this.report.finishedAt = at(); this.report.status = this.client && (!this.report.cleanup?.rootExited || !this.report.cleanup?.treeConfirmed)
|
||||
|
||||
@@ -32,7 +32,7 @@ export class EngineRunner {
|
||||
if (installation.controlledStatus !== 'available' || installation.controlledSha256 !== input.controlledSha256) {
|
||||
throw engineError('受控引擎与刚才检测的程序/插件身份不一致,请重新检测后制定新计划。');
|
||||
}
|
||||
return { ...installation, ...(input.strategy === undefined ? {} : { strategy: selectPurgeStrategy(input.strategy, this.appDirectory) }) };
|
||||
return { ...installation, ...(input.strategy === undefined ? {} : { strategy: selectPurgeStrategy(input.strategy, this.appDirectory, installation) }) };
|
||||
}
|
||||
assertCurrent(session, run) {
|
||||
const driver = this.drivers.get(run.id);
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,205 @@
|
||||
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));}}
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
import fs from 'node:fs';
|
||||
import path from 'node:path';
|
||||
import {createHash} from 'node:crypto';
|
||||
import lock from './original-purge-lock.json' with {type:'json'};
|
||||
import {engineCanonicalDigest as digest,engineError} from '../../shared/contracts/engines.mjs';
|
||||
import {engineFileIdentity} from './deepseek-installation.mjs';
|
||||
|
||||
export const ORIGINAL_PURGE_KIND='purge-original-restricted-v1';
|
||||
export const ORIGINAL_PURGE_LOCK_SHA256=digest(lock);
|
||||
const hash=bytes=>createHash('sha256').update(bytes).digest('hex');
|
||||
const changed=message=>engineError(message,409,'ENGINE_INPUT_CHANGED');
|
||||
function directory(root){
|
||||
if(typeof root!=='string'||!path.isAbsolute(root)||!fs.lstatSync(root).isDirectory()||fs.lstatSync(root).isSymbolicLink())throw changed('原版来源需要普通绝对目录。');
|
||||
return fs.realpathSync.native(root);
|
||||
}
|
||||
function pinnedInputs(root,expected,{original=false}={}){
|
||||
const inputs=expected.map(input=>{
|
||||
const file=path.join(root,input.relative),identity=engineFileIdentity(file,8*1024*1024);
|
||||
if(!identity.path.startsWith(root+path.sep)||identity.bytes!==input.bytes||identity.sha256!==input.sha256)throw changed('固定原版输入已变化:'+input.relative);
|
||||
if(original){
|
||||
for(let current=file;current!==root;current=path.dirname(current))if(fs.lstatSync(current).isSymbolicLink())throw changed('原版输入不能经过链接。');
|
||||
}
|
||||
return {...identity,relative:input.relative};
|
||||
});
|
||||
if(original){
|
||||
const found=[];function walk(relative){const file=path.join(root,relative),stat=fs.lstatSync(file);
|
||||
if(stat.isSymbolicLink())throw changed('原版 lib 不能包含链接。');
|
||||
if(stat.isDirectory()){for(const name of fs.readdirSync(file))walk(path.join(relative,name));}
|
||||
else if(stat.isFile())found.push(relative.replaceAll('\\','/'));else throw changed('原版 lib 包含非普通文件。');
|
||||
if(found.length>128)throw changed('原版 lib 文件数量超出固定版本。');
|
||||
}walk('lib');
|
||||
if(digest(found.sort())!==digest(expected.filter(item=>item.relative.startsWith('lib/')).map(item=>item.relative).sort()))throw changed('原版 lib 文件集合已变化。');
|
||||
}
|
||||
return inputs;
|
||||
}
|
||||
export function originalPurgeSource(root){
|
||||
root=directory(root);const inputs=pinnedInputs(root,lock.original,{original:true});
|
||||
const source={name:'dsh-purge',version:lock.purgeVersion,dshTarget:lock.harnessVersion,license:'Apache-2.0',attribution:'YuJunZhiXue / dsh-purge',root,inputs,lockSha256:ORIGINAL_PURGE_LOCK_SHA256};
|
||||
return {...source,sourceSha256:digest(source)};
|
||||
}
|
||||
export function originalPurgeRuntime(installation){
|
||||
if(process.platform!=='win32'||process.arch!=='x64')throw changed('当前原版受限配置仅核验 Windows x64。');
|
||||
if(installation?.controlledStatus!=='available'||installation.version!==lock.harnessVersion)throw changed('原版受限模式需要已检测的 Harness 0.2.1-rc.2。');
|
||||
const root=directory(installation.root),inputs=pinnedInputs(root,lock.harness);
|
||||
const platformLibraries=['kernel32.dll','advapi32.dll'].map(name=>({...engineFileIdentity(path.join(process.env.SystemRoot,'System32',name)),name}));
|
||||
const runtime={root,inputs,node:installation.node,lockSha256:ORIGINAL_PURGE_LOCK_SHA256,platformLibraries,
|
||||
nativeAddons:lock.nativeAddons.map(input=>({...input,path:path.join(root,input.relative)}))};
|
||||
return {...runtime,sha256:digest(runtime)};
|
||||
}
|
||||
export function originalPurgeStrategy(source,runtime,prompt){
|
||||
const postPrompt='[Agent Workbench original Purge '+source.sourceSha256+' / '+hash(Buffer.from(prompt))+']\n'+prompt+'\n[/Agent Workbench original Purge]';
|
||||
const config={enabled:true,autoApplyOnStart:false,autoUpdateOnStart:false,autoRevertOnMissing:false,injectOnce:false,stripMnemon:true,verbose:false,
|
||||
autoRetry:false,retryMax:0,autoContinue:false,continueMax:0,capabilityProtocol:true,hooksDenyBypass:false,postPromptOrder:5100,postPrompt};
|
||||
const strategy={schemaVersion:1,kind:ORIGINAL_PURGE_KIND,enabled:true,source,runtime,prompt,promptSha256:hash(Buffer.from(prompt)),originalConfig:config,
|
||||
implementation:'workbench-original-entry-restricted-v1',upstreamPluginLoaded:true,automaticRetry:false,hostModification:false,
|
||||
isolation:{profile:'fixed-trusted-source-node-permissions-v1',osSandbox:false,pinnedNativeAddons:true,arbitraryNativeAddons:false,originalTools:false,credentials:false}};
|
||||
return {...strategy,sha256:digest(strategy)};
|
||||
}
|
||||
export function assertOriginalPurgeStrategy(strategy){
|
||||
const source=originalPurgeSource(strategy.source?.root),runtime=originalPurgeRuntime({controlledStatus:'available',version:lock.harnessVersion,...strategy.runtime});
|
||||
const node=engineFileIdentity(strategy.runtime.node.path,256*1024*1024);
|
||||
if(node.sha256!==strategy.runtime.node.sha256||node.bytes!==strategy.runtime.node.bytes||strategy.runtime.node.version!==process.versions.node
|
||||
||digest(originalPurgeStrategy(source,runtime,strategy.prompt))!==digest(strategy))throw changed('原版策略、运行器或固定加载输入已变化,请保留原记录并封存新计划。');
|
||||
}
|
||||
@@ -4,6 +4,8 @@ import { createHash } from 'node:crypto';
|
||||
import { engineError, engineCanonicalDigest } from '../../shared/contracts/engines.mjs';
|
||||
import { engineFileIdentity } from './deepseek-installation.mjs';
|
||||
import { registeredSourceRoots } from './registered-sources.mjs';
|
||||
import { ORIGINAL_PURGE_KIND, originalPurgeSource, originalPurgeRuntime, originalPurgeStrategy, assertOriginalPurgeStrategy } from './original-purge-source.mjs';
|
||||
export { ORIGINAL_PURGE_KIND } from './original-purge-source.mjs';
|
||||
|
||||
export const PURGE_SOURCE_FILES = Object.freeze(['package.json', 'lib/index.js', 'lib/identity.js', 'lib/core.js',
|
||||
'lib/continue-retry.js', 'lib/capability-protocol.js', 'cordis.patch.yml', 'LICENSE', 'NOTICE']);
|
||||
@@ -69,7 +71,22 @@ function strategyFor(source, prompt) {
|
||||
implementation: 'workbench-independent-prompt-v1', upstreamPluginLoaded: false, automaticRetry: false, hostModification: false };
|
||||
return { ...strategy, sha256: engineCanonicalDigest(strategy) };
|
||||
}
|
||||
export function selectPurgeStrategy(input, appDirectory = process.cwd()) {
|
||||
export function resolveOriginalPurgeSource(appDirectory=process.cwd(),root,installation) {
|
||||
const detected=resolvePurgeSource(appDirectory,root),base={...detected,kind:ORIGINAL_PURGE_KIND,supportedVersions:['1.1.78']};
|
||||
try {
|
||||
const source=originalPurgeSource(detected.root),runtime=originalPurgeRuntime(installation);
|
||||
return {...base,...source,status:'available',runtimeSha256:runtime.sha256,runtimeInputs:runtime.inputs.length,
|
||||
message:'原版 1.1.78 完整文件与固定 Harness 依赖已核对。使用独立运行副本;自动重试、继续和原版修改工具关闭。'};
|
||||
}catch(error){return {...base,status:'unavailable',sourceSha256:undefined,message:'原版受限模式尚不可用:'+error.message};}
|
||||
}
|
||||
export function selectPurgeStrategy(input, appDirectory = process.cwd(), installation) {
|
||||
if(input?.kind===ORIGINAL_PURGE_KIND){
|
||||
if(Object.keys(input).some(key=>!['kind','root','sourceSha256','runtimeSha256','prompt'].includes(key)))throw engineError('原版受限模式不接受权限或自动重试参数。',400);
|
||||
promptText(input.prompt);
|
||||
const source=resolveOriginalPurgeSource(appDirectory,input.root,installation);
|
||||
if(source.status!=='available'||source.sourceSha256!==input.sourceSha256||source.runtimeSha256!==input.runtimeSha256)throw engineError('原版来源或运行依赖与刚才的检测不一致,请重新检测并封存新计划。');
|
||||
return originalPurgeStrategy(originalPurgeSource(source.root),originalPurgeRuntime(installation),input.prompt);
|
||||
}
|
||||
if (!input || typeof input !== 'object' || Array.isArray(input) || Object.keys(input).some(key => !['kind', 'root', 'sourceSha256', 'prompt'].includes(key))
|
||||
|| input.kind !== PURGE_PROMPT_KIND || typeof input.root !== 'string' || !/^[a-f0-9]{64}$/.test(input.sourceSha256 ?? '')) {
|
||||
throw engineError('实验策略只接受已检测来源与完整工程提示。', 400);
|
||||
@@ -81,6 +98,7 @@ export function selectPurgeStrategy(input, appDirectory = process.cwd()) {
|
||||
}
|
||||
export function assertPurgeStrategy(strategy) {
|
||||
if (strategy === undefined) return;
|
||||
if(strategy?.kind===ORIGINAL_PURGE_KIND){promptText(strategy.prompt);return assertOriginalPurgeStrategy(strategy);}
|
||||
if (!strategy || strategy.kind !== PURGE_PROMPT_KIND || strategy.enabled !== true || !strategy.source) throw engineError('原提示实验策略无效。');
|
||||
const source = resolvePurgeSource(process.cwd(), strategy.source.root);
|
||||
if (source.status !== 'available' || source.sourceSha256 !== strategy.source.sourceSha256) throw engineError('Purge 来源已变化,原提示实验不能继续;请保留记录并封存新计划。', 409, 'ENGINE_INPUT_CHANGED');
|
||||
@@ -93,7 +111,8 @@ export function nativeSystemTexts(input) {
|
||||
}
|
||||
export function assertPurgeModelInput(input, strategy) {
|
||||
if (!strategy) return;
|
||||
if (nativeSystemTexts(input).reduce((count, text) => count + text.split(strategy.section.text).length - 1, 0) !== 1) {
|
||||
const expected=strategy.kind===ORIGINAL_PURGE_KIND?strategy.originalConfig.postPrompt:strategy.section.text;
|
||||
if (nativeSystemTexts(input).reduce((count, text) => count + text.split(expected).length - 1, 0) !== 1) {
|
||||
throw engineError('实际模型输入缺少唯一完整的封存提示实验段,未发送请求。');
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user