diff --git a/recipes/openai-bridge/SECURITY.md b/recipes/openai-bridge/SECURITY.md index 893cfc5..43815df 100644 --- a/recipes/openai-bridge/SECURITY.md +++ b/recipes/openai-bridge/SECURITY.md @@ -76,7 +76,7 @@ Current App streamfix addresses contain only an opaque HMAC route ID; their orig Runtime execution requires the fixed component source, manifest hash and private file to agree. The published r11 stale-file mode also allows non-executing retirement and interrupted in-place upgrades when each private file still matches its recorded hash or the current fixed source; this mode never executes the old private file. As the manifest is not a signature trust root, this is not proof that the old bytes were an authentic historical release. Upgrades replace stale runtime files with current verified source before any later execution, while retirement may safely remove Hooks/registration without executing the private content. The stop protocol is implemented in the fixed installer and never sources or executes a private `bridge-common.sh`, even for its explicit manual cleanup path. Lock opens use directory descriptors, `O_NOFOLLOW` and no truncation, reject hard links/special files, and recheck identity under the shared registration lock. Before TERM/KILL, the installer checks the expected Node/watchdog command, runtime path, PID start time and registration again; settings writes similarly recheck the snapshot rather than overwrite a concurrent edit. These checks do not make the private manifest a signature trust root or authorize deleting unverified data. Successor-registration retention assumes writers use the shared registration flock. It is not an atomic compare-and-unlink guarantee against arbitrary noncooperating same-UID code rewriting the pathname between the final check and unlink; directory descriptors prevent parent redirection, not that same-UID mutation. -The sole path alias normalization is `fs.realpathSync(os.homedir())` at the trusted HOME root, before deriving default targets and forwarding HOME to child processes; explicit target paths and links below that root remain subject to strict identity/no-follow checks. The watchdog treats explicit disabled as an immediate stop without creating a new fault. Only a missing fixed component entry receives one bounded ten-second confirmation, with unchanged manifest hash/inode and a canonical regular entry required to continue. No patch/stop/spawn occurs while it waits, and the service lock is released instead of blocking other operations. The old transaction is abandoned; the main loop reacquires nonblocking, revalidates manifest and PID/starttime identity, rereads the durable attempt count and gives a concurrently started replacement only a bounded readiness grace. Unobserved confirmation time is not credited as stable health. A persistent absence still locks recovery and exits. Existing locks are never cleared by an update or save. This addresses the confirmed update-transient failure, not the still-unknown earlier first midnight health failure. +Path normalization is confined to caller-trusted HOME/component roots and the verified Android app-root spellings `/data/data/` and `/data/user/0/`. The app-root directories must have matching device/inode identities; their canonical `/data/data` spelling is preferred when available, including bind-mount layouts whose realpaths retain both spellings. Only that prefix is projected, never the complete input path: symlinks below HOME, inside an instance, in state/registration directories or below the component root remain subject to the existing strict realpath, lstat and no-follow checks. The installer, fixed entry, registration and shell lifecycle code share this policy. Equivalent recorded target/settings/component/home paths and explicit `--dir` aliases no longer require rewriting the manifest or registration. Hook merge/removal recognizes only exact generated Hook objects for the verified aliases, not arbitrary shell commands. Identity, source/hash and recovery gates are unchanged. The watchdog treats explicit disabled as an immediate stop without creating a new fault. Only a missing fixed component entry receives one bounded ten-second confirmation, with unchanged manifest hash/inode and a canonical regular entry required to continue. No patch/stop/spawn occurs while it waits, and the service lock is released instead of blocking other operations. The old transaction is abandoned; the main loop reacquires nonblocking, revalidates manifest and PID/starttime identity, rereads the durable attempt count and gives a concurrently started replacement only a bounded readiness grace. Unobserved confirmation time is not credited as stable health. A persistent absence still locks recovery and exits. Existing locks are never cleared by an update or save. This addresses the confirmed update-transient failure, not the still-unknown earlier first midnight health failure. Release presence follows the official App/component release records, not a permanent "unpublished" label in this contract. Publish an App supporting the new schema while retaining the old one first, then the component; migration remains explicit. Unknown future schemas fail closed for startup but must not prevent fixed-path/owned-file uninstall cleanup. These source changes do not by themselves prove a signed release or native-App acceptance. The installed App, installed signed component and current daily bridge are not modified by this source revision. Genuine package-update recovery, final signature installation and all eight native UI delivery gates remain separate verification requirements. diff --git a/recipes/openai-bridge/component.cjs b/recipes/openai-bridge/component.cjs index 6c5a7db..838b186 100644 --- a/recipes/openai-bridge/component.cjs +++ b/recipes/openai-bridge/component.cjs @@ -11,7 +11,7 @@ function run(file,argv){ process.exitCode=result.status??1; } try{ - // 仅 HOME 信任根允许 realpath(应用 HOME 可是 Android 路径别名);显式 --dir 不规范化。 + // 只归并可信根的别名;--dir 以下的链接仍由当前安装器逐项拒绝。 const home=api.trustedHome();process.env.HOME=home; if(command==='--selftest'){ if(args.length)throw new Error('selftest 不接受额外参数。'); @@ -32,19 +32,19 @@ try{ if(command==='configure'){ run(path.join(__dirname,'installer.cjs'),['install',...args,'--bundled-runtime',__dirname]); }else if(command==='ensure'||(command==='uninstall'&&scoped)){ - const target=options.dir===undefined?path.join(home,'.local/share/ccr-bridge-kit'):path.resolve(options.dir); + const target=options.dir===undefined?path.join(home,'.local/share/ccr-bridge-kit'):api.normalizedPath(path.resolve(options.dir)); // 固定入口必须保留实例核对,不能将新参数交给可能不认识它们的旧 manage.cjs。 // 当前安装器验证既有 manifest/注册/运行文件后管理它;绝不覆盖私有运行副本。 - const forwarded=options.dir===undefined?[...args,'--dir',target]:args; + const forwarded=options.dir===undefined?[...args,'--dir',target]:args.map((value,i)=>args[i-1]==='--dir'?target:value); run(path.join(__dirname,'installer.cjs'),[command,...forwarded]); }else{ - const target=options.dir===undefined?path.join(home,'.local/share/ccr-bridge-kit'):path.resolve(options.dir); + const target=options.dir===undefined?path.join(home,'.local/share/ccr-bridge-kit'):api.normalizedPath(path.resolve(options.dir)); const marker=path.join(target,'.ccr-bridge-kit.json'); if(!fs.existsSync(marker))throw new Error('尚未配置此安装。请用户在终端运行 openai-bridge configure。'); const manifest=JSON.parse(fs.readFileSync(marker,'utf8')); - if(manifest.id!=='ccr-bridge-kit'||!api.sameDir(path.resolve(manifest.target),target))throw new Error('不是受管理的桥安装。'); + if(manifest.id!=='ccr-bridge-kit'||api.normalizedPath(manifest.target)!==target)throw new Error('不是受管理的桥安装。'); // 手动清理不要求新实例协议;保留旧运行副本自带管理器,不擅自覆盖它。 - const forwarded=options.dir===undefined?[...args,'--dir',target]:args; + const forwarded=options.dir===undefined?[...args,'--dir',target]:args.map((value,i)=>args[i-1]==='--dir'?target:value); run(path.join(target,'manage.cjs'),[command,...forwarded]); } }else throw new Error('未知操作;运行 openai-bridge --help 查看用法。'); diff --git a/recipes/openai-bridge/installer.cjs b/recipes/openai-bridge/installer.cjs index bc5023d..9306a64 100644 --- a/recipes/openai-bridge/installer.cjs +++ b/recipes/openai-bridge/installer.cjs @@ -20,9 +20,11 @@ const registration = require(exists(path.join(SOURCE,'service-registration.cjs') const COMMANDS = new Set(['install','status','start','ensure','stop','uninstall','connection']); const sha = data => crypto.createHash('sha256').update(data).digest('hex'); const quote = value => "'" + value.replaceAll("'", "'\\''") + "'"; -// HOME 是唯一可规范化的信任根(Android 的应用 HOME 可经 /data/data 别名进入)。 -// 只在构造默认路径前 realpath;显式 target 及 HOME 以下的链接仍须逐项拒绝。 -function trustedHome() { const home=fs.realpathSync(os.homedir());instanceDirectory(home);return home; } +// 可信 HOME 与组件根只归并系统前缀/调用者的根别名;子目录链接仍逐项拒绝。 +const pathRoots=[os.homedir(),SOURCE]; +const normalizedPath=file=>registration.normalizedPath(file,pathRoots); +const samePath=(a,b)=>{try{return normalizedPath(a)===normalizedPath(b);}catch{return false;}}; +function trustedHome() { const home=normalizedPath(fs.realpathSync(os.homedir()));instanceDirectory(home);return home; } function atomic(file, content, mode=0o600) { fs.mkdirSync(path.dirname(file),{recursive:true,mode:0o700}); @@ -58,10 +60,11 @@ function checkTools(bundled) { if(!fs.existsSync('/proc/self/cmdline'))throw new Error('当前安装包只支持具有 /proc 的 Android/Linux,不支持 Windows/macOS。'); } function safeTarget(input,settings) { - const target=path.resolve(input); + const target=normalizedPath(path.resolve(input)); + settings=normalizedPath(path.resolve(settings)); const home=trustedHome(); - if(target==='/'||sameDir(target,home)||path.basename(target)==='.claude')throw new Error('安装目录必须是专用子目录,不能是根目录、HOME 或 .claude。'); - if(insideOrSame(settings,target))throw new Error('Claude 设置不能放进安装目录,避免卸载误删。'); + if(target==='/'||target===home||sameDir(target,home)||path.basename(target)==='.claude')throw new Error('安装目录必须是专用子目录,不能是根目录、HOME 或 .claude。'); + if(settings===target || settings.startsWith(target+path.sep)||insideOrSame(settings,target))throw new Error('Claude 设置不能放进安装目录,避免卸载误删。'); let p=target; while(!exists(p))p=path.dirname(p); const resolved=path.join(fs.realpathSync(p),path.relative(p,target)); @@ -88,15 +91,17 @@ function mergeHook(settings,target) { const result=structuredClone(settings); result.hooks??={}; result.hooks.SessionStart??=[]; - const entry=hookEntry(target), expected=entry.hooks[0], legacy=legacyHookEntry(target).hooks[0]; + const entry=hookEntry(target),aliases=registration.pathAliases(target); + const expected=aliases.map(alias=>hookEntry(alias).hooks[0]),legacy=aliases.map(alias=>legacyHookEntry(alias).hooks[0]); let current=false, old=false; for(const group of result.hooks.SessionStart){ for(const hook of Array.isArray(group?.hooks)?group.hooks:[]){ - if(hook?.command===expected.command){ - if(!same(hook,expected)||group?.matcher!==entry.matcher)throw new Error('已有同路径 hook 被定制,拒绝覆盖。'); + const matched=expected.find(h=>h.command===hook?.command),prior=legacy.find(h=>h.command===hook?.command); + if(matched){ + if(!same(hook,matched)||group?.matcher!==entry.matcher)throw new Error('已有同路径 hook 被定制,拒绝覆盖。'); current=true; - }else if(hook?.command===legacy.command){ - if(!same(hook,legacy))throw new Error('已有同路径 hook 被定制,拒绝覆盖。'); + }else if(prior){ + if(!same(hook,prior))throw new Error('已有同路径 hook 被定制,拒绝覆盖。'); old=true; } } @@ -104,7 +109,7 @@ function mergeHook(settings,target) { if(old || current){ result.hooks.SessionStart=result.hooks.SessionStart.flatMap(g=>{ if(!Array.isArray(g?.hooks))return [g]; - const hooks=g.hooks.filter(h=>h?.command!==legacy.command&&h?.command!==expected.command); + const hooks=g.hooks.filter(h=>![...legacy,...expected].some(entry=>h?.command===entry.command)); if(hooks.length===g.hooks.length)return [g]; return hooks.length?[{...g,hooks}]:[]; }); @@ -115,10 +120,10 @@ function mergeHook(settings,target) { function removeHook(settings,target) { const result=structuredClone(settings); if(!result.hooks?.SessionStart)return result; - const expected=hookEntry(target).hooks[0], legacy=legacyHookEntry(target).hooks[0]; + const expected=registration.pathAliases(target).flatMap(alias=>[hookEntry(alias).hooks[0],legacyHookEntry(alias).hooks[0]]); result.hooks.SessionStart=result.hooks.SessionStart.flatMap(g=>{ if(!Array.isArray(g?.hooks))return [g]; - const hooks=g.hooks.filter(h=>!same(h,expected)&&!same(h,legacy)); + const hooks=g.hooks.filter(h=>!expected.some(entry=>same(h,entry))); if(hooks.length===g.hooks.length)return [g]; return hooks.length?[{...g,hooks}]:[]; }); @@ -414,7 +419,7 @@ function loadManifest(target) { const p=path.join(target,MARKER); if(!exists(p))throw new Error('该目录不是由本安装器管理的安装:'+target); const m=JSON.parse(instanceFile(p,65536).data); - if(!object(m)||m.id!=='ccr-bridge-kit'||m.version!==VERSION||typeof m.target!=='string'||!sameDir(path.resolve(m.target),target))throw new Error('安装标记不匹配,拒绝操作。'); + if(!object(m)||m.id!=='ccr-bridge-kit'||m.version!==VERSION||!samePath(m.target,target))throw new Error('安装标记不匹配,拒绝操作。'); return m; } function managedIntact(target,m) { @@ -437,29 +442,20 @@ function regularFile(file) { return st; } function sameFile(a,b) { return a.dev===b.dev&&a.ino===b.ino; } -// 两个路径是不是同一个目录(按 dev:ino,不按字符串):安卓上 /data/data/<包名> 与 /data/user/0/<包名> 是 -// 同一目录的两种写法(绑定挂载,realpath 不归并)。配置时记一种写法、卸载时敲另一种,字符串比较就对不上(06-路径别名卸载走不通) -function sameDir(a,b) { - try { return sameFile(fs.lstatSync(a),fs.lstatSync(b)); } catch { return false; } -} -/** p 就是 root、或位于 root 之下(逐级向上按 dev:ino 比,别名写法也认) */ +// 保留 r20 的目录身份包含关系;不存在的路径仍逐级检查其已存在父目录。 +function sameDir(a,b) { try{return sameFile(fs.lstatSync(a),fs.lstatSync(b));}catch{return false;} } function insideOrSame(p,root) { - let q=p; - for(;;){ - if(sameDir(q,root))return true; - const d=path.dirname(q); - if(d===q)return false; - q=d; - } + for(let q=p;;q=path.dirname(q)){if(sameDir(q,root))return true;if(path.dirname(q)===q)return false;} } -/** p 严格位于 root 之下(p 自己就是 root 不算) */ -function underDir(p,root) { return !sameDir(p,root) && insideOrSame(p,root); } +function underDir(p,root) { return !sameDir(p,root)&&insideOrSame(p,root); } function instanceDirectory(dir) { + dir=normalizedPath(dir); const st=fs.lstatSync(dir); if(!st.isDirectory()||fs.realpathSync(dir)!==dir)throw new Error('实例目录或父路径不规范,拒绝操作。'); return st; } function openInstanceDirectory(dir) { + dir=normalizedPath(dir); const st=instanceDirectory(dir),fd=fs.openSync(dir,fs.constants.O_RDONLY|fs.constants.O_DIRECTORY|fs.constants.O_NOFOLLOW); const check=()=>{ if(!sameFile(st,fs.fstatSync(fd))||!sameFile(st,instanceDirectory(dir)))throw new Error('操作期间实例目录已变更。'); @@ -514,7 +510,7 @@ function checkInstance(target,options,previous=null,registered=true,stale=null) // 与当前组件不一致的文件名记进 stale,不再当冲突。 const targetStat=instanceDirectory(target),m=JSON.parse(instanceFile(path.join(target,MARKER),65536).data),home=trustedHome(); const service=m?.service; - if(m?.id!=='ccr-bridge-kit'||m.version!==VERSION||!sameDir(m.target,target)||!object(service)||service.schema!==1||!sameDir(service.home,home)||fs.realpathSync(home)!==home||service.instanceId!==options.instance)throw new Error('本地桥实例注册不匹配。'); + if(m?.id!=='ccr-bridge-kit'||m.version!==VERSION||!samePath(m.target,target)||!object(service)||service.schema!==1||!samePath(service.home,home)||fs.realpathSync(home)!==home||service.instanceId!==options.instance)throw new Error('本地桥实例注册不匹配。'); const port=instancePort(target); if(options.endpoint!=='http://127.0.0.1:'+port)throw new Error('本地桥 endpoint 与实例端口不匹配。'); if(typeof m.settings!=='string'||!path.isAbsolute(m.settings)||path.resolve(m.settings)!==m.settings)throw new Error('实例设置路径不规范。'); @@ -523,8 +519,7 @@ function checkInstance(target,options,previous=null,registered=true,stale=null) instanceDirectory(registryDir); const current=exists(registryFile)?JSON.parse(instanceFile(registryFile,4096).data):null; const expected=registration.value(target,port,service.instanceId); - // runtimeDir 按目录身份(dev:ino)比:注册记的是配置时的路径写法,卸载换一种别名写法(/data/data 与 /data/user/0)不该算「已变更」 - const regSame=(a,b)=>!!a&&object(a)&&Object.keys(a).length===5&&['schema','id','endpoint','instanceId'].every(k=>a[k]===b[k])&&sameDir(a.runtimeDir,b.runtimeDir); + const regSame=(a,b)=>object(a)&&Object.keys(a).length===5&&['schema','id','endpoint','instanceId'].every(k=>a[k]===b[k])&&samePath(a.runtimeDir,b.runtimeDir); if(registered?!regSame(current,expected):current!==null)throw new Error('本地桥服务注册已变更,拒绝操作。'); const allowed=new Set([...RUNTIME_FILES,'manage.cjs','stop.sh','uninstall.sh','status.sh','package.json','package-lock.json','port']); if(!object(m.files)||[...RUNTIME_FILES,'port'].some(name=>!Object.hasOwn(m.files,name)))throw new Error('实例缺少受管理的运行文件。'); @@ -610,13 +605,13 @@ async function install(options) { const bundled=options['bundled-runtime']?path.resolve(options['bundled-runtime']):null; checkTools(bundled); const home=trustedHome(); - const settings=path.resolve(options.settings||path.join(home,'.claude','settings.json')); + const settings=normalizedPath(path.resolve(options.settings||path.join(home,'.claude','settings.json'))); const target=safeTarget(options.dir||path.join(home,'.local','share','ccr-bridge-kit'),settings); if(exists(target)){ if(options.guiConfig)throw guiError('RUNTIME_CONFLICT'); const m=loadManifest(target); managedIntact(target,m); - if(m.settings!==settings)throw new Error('重复安装不能更换 settings 路径。'); + if(!samePath(m.settings,settings))throw new Error('重复安装不能更换 settings 路径。'); if(options.config||options.port)throw new Error('重复安装不会覆盖现有密钥/端口;如需重配,请先卸载并备份自己的配置。'); const original=readSettings(settings),merged=mergeHook(original,target); if(m.service){registration.register(m.service.home,target,Number(fs.readFileSync(path.join(target,'port'),'utf8').trim()),m.service.instanceId);} @@ -803,7 +798,7 @@ function checkGuiRuntime(paths,previous=null,allowConfiguring=false,readOnly=fal instanceOptions('ensure',options); const stale=readOnly?[]:null,instance=checkInstance(target,options,previous?.instance,true,stale); const disabled=path.join(target,'disabled'); - if(!paths.cli&&m.guiManaged!==true||m.settings!==settings||m.componentEntry!==path.join(SOURCE,'component.cjs'))throw guiError('RUNTIME_CONFLICT'); + if(!paths.cli&&m.guiManaged!==true||!samePath(m.settings,settings)||!samePath(m.componentEntry,path.join(SOURCE,'component.cjs')))throw guiError('RUNTIME_CONFLICT'); // disabled 是生命周期状态,不是实例冲突;stopMetadata 已有界拒绝链接/非普通文件。 // allowConfiguring 只豁免本次事务自己的临时标记,不能豁免其他 disabled。 const disabledText=exists(disabled)?instanceFile(disabled,32).data.toString('utf8'):null; @@ -1044,8 +1039,8 @@ function guiRetired(paths){ // 不用 loadManifest:它要求版本号与当前组件一致,组件升了版本(比如 1.0.6)后旧版卸载留下的目录就认不出了,又回到配不上。 // 只在这里放宽到同系列的任意版本号,其余身份字段照旧严格;认出来也只是改名让位,不读不执行 let m;try{m=JSON.parse(instanceFile(path.join(target,MARKER),65536).data);}catch{return false;} - if(!object(m)||m.id!=='ccr-bridge-kit'||typeof m.version!=='string'||!/^[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,4}$/.test(m.version)||m.target!==target)return false; - if(m.guiManaged!==true||m.settings!==settings||m.componentEntry!==path.join(SOURCE,'component.cjs'))return false; + if(!object(m)||m.id!=='ccr-bridge-kit'||typeof m.version!=='string'||!/^[0-9]{1,4}\.[0-9]{1,4}\.[0-9]{1,4}$/.test(m.version)||!samePath(m.target,target))return false; + if(m.guiManaged!==true||!samePath(m.settings,settings)||!samePath(m.componentEntry,path.join(SOURCE,'component.cjs')))return false; if(instanceFile(path.join(target,'disabled'),32).data.toString('utf8')!==RETIRED)return false; return registration.read(home)===null; } @@ -1091,9 +1086,9 @@ async function gui(command,args){ } } function purgeTarget(target) { + target=normalizedPath(target); if(fs.lstatSync(target).isSymbolicLink() || fs.realpathSync(target)!==target)throw new Error('清理目标或父路径有符号链接,拒绝删除。'); - // 按 dev:ino 逐级向上比,不按字符串前缀:路径别名(/data/data 与 /data/user/0 是同一目录的两种写法)前缀对不上 - if(!underDir(target,trustedHome()) && !underDir(target,path.resolve(os.tmpdir())))throw new Error('清理目标必须位于私有 HOME 或临时目录的专用子目录。'); + if(!underDir(target,trustedHome())&&!underDir(target,normalizedPath(fs.realpathSync(os.tmpdir()))))throw new Error('清理目标必须位于私有 HOME 或临时目录的专用子目录。'); const manifest=loadManifest(target); safeTarget(target,path.resolve(manifest.settings)); return target; @@ -1107,7 +1102,7 @@ async function confirmStop(target,options) { function stopManaged(target,context=null) { // 固定组件内联的停止协议。无论 manifest 如何自报 hash,绝不 source/exec 私有代码。 const baseline=stopMetadata(target),manifest=JSON.parse(instanceFile(path.join(target,MARKER),65536).data),port=instancePort(target); - if(manifest?.id!=='ccr-bridge-kit'||manifest.version!==VERSION||!sameDir(manifest.target,target))throw new Error('停止目标不是规范的受管理实例。'); + if(manifest?.id!=='ccr-bridge-kit'||manifest.version!==VERSION||!samePath(manifest.target,target))throw new Error('停止目标不是规范的受管理实例。'); const registryFile=registration.fileOf(trustedHome()); const registry=exists(registryFile)?instanceFile(registryFile,4096).data:null; let startLock,serviceLock; @@ -1158,10 +1153,10 @@ function stopManaged(target,context=null) { let exeReal='';try{exeReal=fs.realpathSync('/proc/'+pid+'/exe');}catch(error){if(!['ENOENT','ESRCH','EACCES'].includes(error.code))throw error;} const viaLinker=isSystemLinker(exeReal)&&args.length>=2;if(viaLinker)args.shift(); let matches; - if(kind==='watchdog')matches=args.length===2&&path.basename(args[0])==='bash'&&args[1]===path.join(target,'watchdog.sh'); + if(kind==='watchdog')matches=args.length===2&&path.basename(args[0])==='bash'&&samePath(args[1],path.join(target,'watchdog.sh')); else{ const cli='node_modules/@musistudio/claude-code-router/dist/cli.js'; - matches=args.length===3&&path.basename(args[0])==='node'&&args[2]==='start'&&(args[1]===path.join(target,cli)||args[1]===cli&&fs.readlinkSync('/proc/'+pid+'/cwd')===target); + matches=args.length===3&&path.basename(args[0])==='node'&&args[2]==='start'&&(samePath(args[1],path.join(target,cli))||args[1]===cli&&samePath(fs.readlinkSync('/proc/'+pid+'/cwd'),target)); } if(!matches)return null; // argv[0] 可任意伪装;真实 /proc/PID/exe 必须属于固定解析的解释器。 @@ -1307,7 +1302,7 @@ function upgradeInstance(target,options,preserveDisabled=false) { // 只把本组件自己发过、未被改动的文件换成当前组件那份:先用内联协议停桥(不执行私有代码), // 逐个原子替换,最后才改 manifest;中途断掉时每个文件仍是新旧之一,下次接着做。 const m=loadManifest(target); - if(m.componentEntry!==path.join(SOURCE,'component.cjs')||!exists(path.join(SOURCE,'runtime')))return false; + if(!samePath(m.componentEntry,path.join(SOURCE,'component.cjs'))||!exists(path.join(SOURCE,'runtime')))return false; const marker=path.join(target,'disabled'); const leftover=()=>exists(marker)&&instanceFile(marker,32).data.toString('utf8')===UPGRADING; const probe=[];checkInstance(target,options,null,true,probe); @@ -1344,7 +1339,7 @@ function upgradeInstance(target,options,preserveDisabled=false) { } async function manage(command,options) { const scoped=instanceOptions(command,options); - const target=path.resolve(options.dir||SOURCE); + const target=normalizedPath(path.resolve(options.dir||SOURCE)); const m=loadManifest(target); if(scoped&&command==='ensure')upgradeInstance(target,options); // 卸载不执行私有代码,旧版运行文件只要未被改动就放行,免得组件升级后卸不掉 @@ -1488,4 +1483,4 @@ async function main() { if(cmd==='install')await install(options);else await manage(cmd,options); } if(require.main===module)main().catch(e=>{console.error('错误:'+e.message);process.exitCode=1;}); -module.exports={atomic,mergeHook,removeHook,validateConfig,routerConfig,connectionConfig,readSettings,safeTarget,hookEntry,legacyHookEntry,parse,quote,copyBundledRuntime,purgeTarget,instanceOptions,trustedHome,sameDir,underDir,insideOrSame,VERSION,loadManifest}; +module.exports={atomic,mergeHook,removeHook,validateConfig,routerConfig,connectionConfig,readSettings,safeTarget,hookEntry,legacyHookEntry,parse,quote,copyBundledRuntime,purgeTarget,instanceOptions,trustedHome,normalizedPath,loadManifest,sameDir,underDir,insideOrSame,VERSION}; diff --git a/recipes/openai-bridge/package.json b/recipes/openai-bridge/package.json index a0506f2..5745675 100644 --- a/recipes/openai-bridge/package.json +++ b/recipes/openai-bridge/package.json @@ -29,7 +29,9 @@ "scripts": { "test:app": "node tests/test-app-lifecycle.cjs", "test:models-app": "node tests/test-gui-models-app.cjs", + "test:paths": "node tests/test-path-aliases.cjs", + "test:aliases-e2e": "node tests/test-install-e2e.cjs --bundled --aliases", "test:watchdog": "node tests/test-health.cjs && node tests/test-hooks.cjs && python3 tests/test-watchdog-transient.py", - "test": "node tests/test-registration.cjs && node tests/test-installer.cjs && node tests/test-multi-provider.cjs && node tests/test-uninstall-instance.cjs && node tests/test-gui-config.cjs && node tests/test-gui-models.cjs && node tests/test-hooks.cjs && node tests/test-install-e2e.cjs && node tests/test-install-e2e.cjs --bundled && node tests/test-response.cjs && node tests/test-security.cjs && python3 tests/test-integration.py && node tests/test-health.cjs && node runtime/selftest.cjs" + "test": "node tests/test-registration.cjs && node tests/test-path-aliases.cjs && node tests/test-installer.cjs && node tests/test-multi-provider.cjs && node tests/test-uninstall-instance.cjs && node tests/test-gui-config.cjs && node tests/test-gui-models.cjs && node tests/test-hooks.cjs && node tests/test-install-e2e.cjs && node tests/test-install-e2e.cjs --bundled && node tests/test-response.cjs && node tests/test-security.cjs && python3 tests/test-integration.py && node tests/test-health.cjs && node runtime/selftest.cjs" } } diff --git a/recipes/openai-bridge/recipe.json b/recipes/openai-bridge/recipe.json index 29c2ba3..9b69dfc 100644 --- a/recipes/openai-bridge/recipe.json +++ b/recipes/openai-bridge/recipe.json @@ -2,43 +2,97 @@ "schema": 1, "id": "openai-bridge", "kind": "termux", - "revision": 21, + "revision": 22, "version": "1.0.5", - "name": { "zh": "OpenAI API 本地协议桥(预览)", "en": "Local OpenAI API bridge (preview)" }, + "name": { + "zh": "OpenAI API 本地协议桥(预览)", + "en": "Local OpenAI API bridge (preview)" + }, "desc": { "zh": "将用户自有的 OpenAI Chat Completions API 转为本机 Anthropic Messages 接口。含 CCR 1.0.73 修复、多模型路由、多个 OpenAI 兼容上游及在线增删改、有限恢复与安全探活;图形多API、多模型和独立窗口需配套 App。预览组件,不提供模型或额度,约 105 MiB。", "en": "Adapt authorized Chat Completions APIs to local Anthropic Messages, using the user's remote services. Includes CCR 1.0.73 fixes, multi-model routing, multiple OpenAI-compatible upstreams with online add/edit/remove, bounded recovery and safe diagnostics. GUI APIs, models and individual context windows need a paired App. Preview; no model or quota, about 105 MiB." }, - "roots": ["nodejs", "bash", "util-linux", "coreutils"], - "bin": ["openai-bridge"], + "roots": [ + "nodejs", + "bash", + "util-linux", + "coreutils" + ], + "bin": [ + "openai-bridge" + ], "selftest": "openai-bridge --selftest", - "needs": { "shizuku": false, "display": false, "gpu": false }, + "needs": { + "shizuku": false, + "display": false, + "gpu": false + }, "category": "ai", "license": "MIT", "homepage": "https://github.com/chenshi723/cccodroid-openai-bridge", - "maintainers": ["chenshi723"], + "maintainers": [ + "chenshi723" + ], "npm": { "dir": "usr/lib/openai-bridge", "why": "CCR 只在 npm 发布,Termux 官方仓库无 claude-code-router 包;固定为 1.0.73,CI 按锁文件校验完整性并禁用安装脚本。" }, "files": { - "usr/bin/openai-bridge": { "src": "openai-bridge", "mode": "755" }, - "usr/lib/openai-bridge/component.cjs": { "src": "component.cjs" }, - "usr/lib/openai-bridge/installer.cjs": { "src": "installer.cjs" }, - "usr/lib/openai-bridge/gui-models.cjs": { "src": "gui-models.cjs" }, - "usr/lib/openai-bridge/package.json": { "src": "package.json" }, - "usr/lib/openai-bridge/package-lock.json": { "src": "package-lock.json" }, - "usr/lib/openai-bridge/LICENSE": { "src": "LICENSE" }, - "usr/lib/openai-bridge/NOTICE": { "src": "NOTICE" }, - "usr/lib/openai-bridge/LICENSE-CCR.txt": { "src": "LICENSE-CCR.txt" }, - "usr/lib/openai-bridge/SECURITY.md": { "src": "SECURITY.md" }, - "usr/lib/openai-bridge/runtime/patch-ccr.js": { "src": "runtime/patch-ccr.js" }, - "usr/lib/openai-bridge/runtime/bridge-common.sh": { "src": "runtime/bridge-common.sh", "mode": "755" }, - "usr/lib/openai-bridge/runtime/start-bridge.sh": { "src": "runtime/start-bridge.sh", "mode": "755" }, - "usr/lib/openai-bridge/runtime/watchdog.sh": { "src": "runtime/watchdog.sh", "mode": "755" }, - "usr/lib/openai-bridge/runtime/selftest.cjs": { "src": "runtime/selftest.cjs" }, - "usr/lib/openai-bridge/runtime/health.cjs": { "src": "runtime/health.cjs" }, - "usr/lib/openai-bridge/runtime/service-registration.cjs": { "src": "runtime/service-registration.cjs" } + "usr/bin/openai-bridge": { + "src": "openai-bridge", + "mode": "755" + }, + "usr/lib/openai-bridge/component.cjs": { + "src": "component.cjs" + }, + "usr/lib/openai-bridge/installer.cjs": { + "src": "installer.cjs" + }, + "usr/lib/openai-bridge/gui-models.cjs": { + "src": "gui-models.cjs" + }, + "usr/lib/openai-bridge/package.json": { + "src": "package.json" + }, + "usr/lib/openai-bridge/package-lock.json": { + "src": "package-lock.json" + }, + "usr/lib/openai-bridge/LICENSE": { + "src": "LICENSE" + }, + "usr/lib/openai-bridge/NOTICE": { + "src": "NOTICE" + }, + "usr/lib/openai-bridge/LICENSE-CCR.txt": { + "src": "LICENSE-CCR.txt" + }, + "usr/lib/openai-bridge/SECURITY.md": { + "src": "SECURITY.md" + }, + "usr/lib/openai-bridge/runtime/patch-ccr.js": { + "src": "runtime/patch-ccr.js" + }, + "usr/lib/openai-bridge/runtime/bridge-common.sh": { + "src": "runtime/bridge-common.sh", + "mode": "755" + }, + "usr/lib/openai-bridge/runtime/start-bridge.sh": { + "src": "runtime/start-bridge.sh", + "mode": "755" + }, + "usr/lib/openai-bridge/runtime/watchdog.sh": { + "src": "runtime/watchdog.sh", + "mode": "755" + }, + "usr/lib/openai-bridge/runtime/selftest.cjs": { + "src": "runtime/selftest.cjs" + }, + "usr/lib/openai-bridge/runtime/health.cjs": { + "src": "runtime/health.cjs" + }, + "usr/lib/openai-bridge/runtime/service-registration.cjs": { + "src": "runtime/service-registration.cjs" + } }, - "notes": "r21:OpenAI 兼容端点(/v1/chat/completions)裸模型名按 MODEL_ROUTES / 唯一声明上游路由,不再一律 404 Provider not found(cccodroid 主仓 #217);selftest 增加裸名路由与未知名保持 404 的功能断言。r20:安装标记、实例注册、停止与清理的路径比较全部按目录身份(dev:ino)识别,/data/data 与 /data/user/0 两种拼写不再误拒(路径别名卸载);HOME 与设置包含关系、清理范围同样按目录身份判断。同机回归:旧代码按别名卸载复现拒绝,新代码卸载+purge+注册清理通过;selftest 增加别名块(无 /data/data 环境自动跳过)。r19源码候选:已就绪实例采用独立300秒健康宽限;故障探活增加随机回环对照,仅对照也失败时等待本机传输恢复,不重启、不消费预算、不报告就绪。真正退出、持续服务/补丁失败仍有限恢复。调度长空窗不计连续健康或失败。原有恢复锁/停用/实例校验保留,不代表首次午夜诱因已查明。保留r17的Gemini 3工具调用thought signature回传兼容。含r15/r16审查后的配置崩溃续配和看护并发修正,保留正式r14的Android执行层、受管升级/卸载和推理参数回退。配套App可保存至多100个模型及逐模型窗口:有效元数据优先,缺失200000,保留手动值。清单先由用户同意,只GET同源/models,不推理/不切会话/不跟重定向;固定组件以stdin接Key,不回显。组件只接模型ID,窗口由App管理。恢复故障固定码优先于残存health;状态/保存/Hook/普通ensure不清恢复锁,不实现GUI重置。只有精确configuring临时事务残留可在用户明确保存、身份核对和完整提交后清除,其他停用标记/恢复次数不清。探活仅时间/固定码,有绝对截止和有界日志,不记正文/头/对话;入口缺失有界重确认不替代恢复预算。可信HOME根统一真实路径,实例以下链接/身份/完整性检查不放宽。需要配套App和v1注册/ensure;先发布兼容App,再发布组件并经用户确认配置或迁移。仅改专用私有副本,不改Claude Code、签名根或其他服务。源码隔离测试不等于真机界面/签名安装验收,不伪造verified.json。首次午夜探活失败诱因仍未知,恢复运行不等于全部根因修复。修改上游后由recipe/sync.sh同步,依赖仍按锁文件和指纹验证。 多上游:可选 providers 数组(附加上游)生成多个 CCR Providers 与 MODEL_ROUTES;可见模型全局去重,重名显示为 /,合计 1–100;connection.json 仍保持 schema 1,上游 Key 只在私有 CCR 配置。同批配套App可新增/编辑/移除多个API,组件以capabilities.multiUpstream标记能力;upstreams全量保存模型显式别名,留空Key按名称和origin复用;旧单表单保留附加上游。CLI add/edit/remove-provider无需卸载,确认后原子更新同一实例;清单按provider选择单endpoint不跨源发Key。签名缓存绑定session/provider/model/toolCallId,身份缺失不复用。" + "notes": "r22源码候选:补齐Android可信根别名处理;固定入口显式--dir、shell启动/看护、旧清单/注册、升级/停止/Hook/卸载统一投影已核对身份的系统前缀;不跟随实例/状态/组件根下链接,不清恢复锁,不需手改清单。保留r20目录身份范围保护和r21裸模型路由补丁;增加实际别名冷启动、双本地假上游全生命周期、安装后别名自检及负对照。仅源码验证,未签名发布、未修改真实安装。 r21:OpenAI 兼容端点(/v1/chat/completions)裸模型名按 MODEL_ROUTES / 唯一声明上游路由,不再一律 404 Provider not found(cccodroid 主仓 #217);selftest 增加裸名路由与未知名保持 404 的功能断言。r20:安装标记、实例注册、停止与清理的路径比较全部按目录身份(dev:ino)识别,/data/data 与 /data/user/0 两种拼写不再误拒(路径别名卸载);HOME 与设置包含关系、清理范围同样按目录身份判断。同机回归:旧代码按别名卸载复现拒绝,新代码卸载+purge+注册清理通过;selftest 增加别名块(无 /data/data 环境自动跳过)。r19源码候选:已就绪实例采用独立300秒健康宽限;故障探活增加随机回环对照,仅对照也失败时等待本机传输恢复,不重启、不消费预算、不报告就绪。真正退出、持续服务/补丁失败仍有限恢复。调度长空窗不计连续健康或失败。原有恢复锁/停用/实例校验保留,不代表首次午夜诱因已查明。保留r17的Gemini 3工具调用thought signature回传兼容。含r15/r16审查后的配置崩溃续配和看护并发修正,保留正式r14的Android执行层、受管升级/卸载和推理参数回退。配套App可保存至多100个模型及逐模型窗口:有效元数据优先,缺失200000,保留手动值。清单先由用户同意,只GET同源/models,不推理/不切会话/不跟重定向;固定组件以stdin接Key,不回显。组件只接模型ID,窗口由App管理。恢复故障固定码优先于残存health;状态/保存/Hook/普通ensure不清恢复锁,不实现GUI重置。只有精确configuring临时事务残留可在用户明确保存、身份核对和完整提交后清除,其他停用标记/恢复次数不清。探活仅时间/固定码,有绝对截止和有界日志,不记正文/头/对话;入口缺失有界重确认不替代恢复预算。可信HOME根统一真实路径,实例以下链接/身份/完整性检查不放宽。需要配套App和v1注册/ensure;先发布兼容App,再发布组件并经用户确认配置或迁移。仅改专用私有副本,不改Claude Code、签名根或其他服务。源码隔离测试不等于真机界面/签名安装验收,不伪造verified.json。首次午夜探活失败诱因仍未知,恢复运行不等于全部根因修复。修改上游后由recipe/sync.sh同步,依赖仍按锁文件和指纹验证。 多上游:可选 providers 数组(附加上游)生成多个 CCR Providers 与 MODEL_ROUTES;可见模型全局去重,重名显示为 /,合计 1–100;connection.json 仍保持 schema 1,上游 Key 只在私有 CCR 配置。同批配套App可新增/编辑/移除多个API,组件以capabilities.multiUpstream标记能力;upstreams全量保存模型显式别名,留空Key按名称和origin复用;旧单表单保留附加上游。CLI add/edit/remove-provider无需卸载,确认后原子更新同一实例;清单按provider选择单endpoint不跨源发Key。签名缓存绑定session/provider/model/toolCallId,身份缺失不复用。" } diff --git a/recipes/openai-bridge/runtime/bridge-common.sh b/recipes/openai-bridge/runtime/bridge-common.sh index 1bcb10f..144c1bc 100644 --- a/recipes/openai-bridge/runtime/bridge-common.sh +++ b/recipes/openai-bridge/runtime/bridge-common.sh @@ -35,12 +35,17 @@ bridge_component_state() { const root=process.argv[1],file=path.join(root,".ccr-bridge-kit.json"),st=fs.lstatSync(file); if(!st.isFile()||st.nlink!==1||st.size>65536||fs.realpathSync(root)!==root)process.exit(1); const text=fs.readFileSync(file),m=JSON.parse(text); - if(m.id!=="ccr-bridge-kit"||m.target!==root||typeof m.componentEntry!=="string"||!path.isAbsolute(m.componentEntry)||path.resolve(m.componentEntry)!==m.componentEntry)process.exit(1); + const helper=path.join(root,"service-registration.cjs"),helperStat=fs.lstatSync(helper); + if(!helperStat.isFile()||helperStat.nlink!==1||fs.realpathSync(helper)!==helper)process.exit(1); + const {normalizedPath}=require(helper); + const roots=[root,process.env.PREFIX].filter(Boolean),normalize=p=>normalizedPath(p,roots); + if(m.id!=="ccr-bridge-kit"||normalize(m.target)!==normalize(root))process.exit(1); + const component=normalize(m.componentEntry); const stamp=crypto.createHash("sha256").update(text).update(String(st.dev)+":"+st.ino).digest("hex"); if(process.argv[2]&&process.argv[2]!==stamp)process.exit(1); console.log(stamp); - let entry;try{entry=fs.lstatSync(m.componentEntry);}catch(error){if(error.code==="ENOENT")process.exit(3);throw error;} - if(!entry.isFile()||entry.nlink!==1||fs.realpathSync(m.componentEntry)!==m.componentEntry)process.exit(1); + let entry;try{entry=fs.lstatSync(component);}catch(error){if(error.code==="ENOENT")process.exit(3);throw error;} + if(!entry.isFile()||entry.nlink!==1||fs.realpathSync(component)!==component)process.exit(1); } catch { process.exit(1); } ' "$BR" "${1:-}" 2>/dev/null } @@ -76,6 +81,15 @@ strip_linker() { return 0 } +# 先作便宜的精确比较;不同写法只接受已验证的根别名,不跟脚本/状态子路径的链接。 +bridge_path_same() { + [[ "$1" = "$2" ]] && return 0 + node -e ' + const path=require("node:path"),{samePath}=require(path.join(process.argv[1],"service-registration.cjs")); + process.exit(samePath(process.argv[2],process.argv[3],[process.argv[1],process.env.PREFIX].filter(Boolean))?0:1); + ' "$BR" "$1" "$2" 2>/dev/null +} + # 不凭 PID 文件就杀进程:同时校验 Node、完整脚本路径(或原看护的相对路径 + cwd)。 bridge_process() { local pid=$1 @@ -85,9 +99,9 @@ bridge_process() { { mapfile -d '' -t args < "/proc/$pid/cmdline"; } 2>/dev/null || return 1 strip_linker [[ ${#args[@]} -ge 3 && ${args[0]##*/} = node && ${args[2]} = start ]] || return 1 - [[ ${args[1]} = "$CLI" ]] && return 0 + bridge_path_same "${args[1]}" "$CLI" && return 0 [[ ${args[1]} = node_modules/@musistudio/claude-code-router/dist/cli.js ]] && - [[ $(readlink "/proc/$pid/cwd" 2>/dev/null) = "$BR" ]] + bridge_path_same "$(readlink "/proc/$pid/cwd" 2>/dev/null)" "$BR" } bridge_pid() { @@ -156,7 +170,7 @@ watchdog_running() { kill -0 "$pid" 2>/dev/null || return 1 { mapfile -d '' -t args < "/proc/$pid/cmdline"; } 2>/dev/null || return 1 strip_linker - [[ ${#args[@]} -ge 2 && ${args[0]##*/} = bash && ${args[1]} = "$BR/watchdog.sh" ]] || return 1 + [[ ${#args[@]} -ge 2 && ${args[0]##*/} = bash ]] && bridge_path_same "${args[1]}" "$BR/watchdog.sh" || return 1 # PID 仍在但锁已释放,也不能算一个有效的看护。 ! flock -n "$STATE/watchdog.lock" true } diff --git a/recipes/openai-bridge/runtime/selftest.cjs b/recipes/openai-bridge/runtime/selftest.cjs index 502d021..8f8afa3 100644 --- a/recipes/openai-bridge/runtime/selftest.cjs +++ b/recipes/openai-bridge/runtime/selftest.cjs @@ -6,6 +6,7 @@ const os = require("node:os"); const path = require("node:path"); const http = require("node:http"); const { spawn, spawnSync } = require("node:child_process"); +const registration = require("./service-registration.cjs"); const root = path.resolve(__dirname, ".."); const listen = (server) => new Promise((resolve, reject) => { @@ -15,9 +16,31 @@ const listen = (server) => new Promise((resolve, reject) => { const sleep = (ms) => new Promise((resolve) => setTimeout(resolve, ms)); async function main() { - const temp = fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), "openai-bridge-selftest-")); + const temp = fs.realpathSync(fs.mkdtempSync(path.join(process.env.TMPDIR || os.tmpdir(), "openai-bridge-selftest-"))); let child, upstream, output = "", passed = 0; try { + // 安装后的自检也走真实 shell 判定和固定卸载入口,不只测协议转换。 + const fixture=path.join(temp,"alias-fixture"),fixtureState=path.join(fixture,"runtime-home/.claude-code-router"); + fs.mkdirSync(fixtureState,{recursive:true}); + const files={},hash=data=>require("node:crypto").createHash("sha256").update(data).digest("hex"); + for(const name of ["bridge-common.sh","start-bridge.sh","watchdog.sh","patch-ccr.js","health.cjs","service-registration.cjs"]){ + const data=fs.readFileSync(path.join(__dirname,name));fs.writeFileSync(path.join(fixture,name),data);files[name]=hash(data); + } + fs.writeFileSync(path.join(fixture,"port"),"34591\n");files.port=hash("34591\n"); + const alias=file=>file.startsWith("/data/data/")?file.replace("/data/data/","/data/user/0/"):file.startsWith("/data/user/0/")?file.replace("/data/user/0/","/data/data/"):file; + const alternate=fs.existsSync(alias(temp))?alias:x=>x; + const settings=path.join(temp,"settings.json"),instanceId="1".repeat(32); + fs.writeFileSync(settings,"{}"); + const marker=path.join(fixture,".ccr-bridge-kit.json"); + fs.writeFileSync(marker,JSON.stringify({id:"ccr-bridge-kit",version:"1.0.5",target:alternate(fixture),settings:alternate(settings),componentEntry:alternate(path.join(root,"component.cjs")),service:{schema:1,home:alternate(temp),instanceId},files})); + const check=spawnSync("bash",["-c",'source "$1/bridge-common.sh" && bridge_component_state',"selftest",alternate(fixture)],{encoding:"utf8",timeout:5000}); + assert.equal(check.status,0,"alias shell component check: "+check.stderr); + registration.register(temp,alternate(fixture),34591,instanceId); + const retired=spawnSync(process.execPath,[path.join(root,"component.cjs"),"uninstall","--dir",fixture,"--endpoint","http://127.0.0.1:34591","--instance",instanceId,"--yes"],{env:{...process.env,HOME:temp},encoding:"utf8",timeout:20000}); + assert.equal(retired.status,0,"alias fixed uninstall: "+retired.stderr); + assert.equal(fs.existsSync(registration.fileOf(temp)),false); + assert.equal(fs.readFileSync(path.join(fixture,"disabled"),"utf8"),"uninstalled\n"); + console.log("PASS trusted path aliases; shell/start metadata + fixed uninstall; private data preserved"); const dist = path.join(temp, "node_modules/@musistudio/claude-code-router/dist"); fs.mkdirSync(dist, { recursive: true }); for (const name of ["@fastify", "@isaacs", "fastify", "ajv", "fast-uri", "find-my-way", "undici", "minimatch", "glob", "shell-quote"]) { @@ -117,22 +140,16 @@ async function main() { console.log(`PASS ${model} stream=${stream}; text + effort preserved`); } assert.equal(seen.length, 3); - // OpenAI 兼容端点:裸模型名按唯一声明上游路由,不再一律 404(cccodroid 主仓 #217) - const openai = async (model) => { - const response = await fetch(`http://127.0.0.1:${port}/v1/chat/completions`, { - method: "POST", signal: AbortSignal.timeout(5000), headers: { "content-type": "application/json", "x-api-key": "local-test-only" }, - body: JSON.stringify({ model, max_tokens: 16, stream: false, messages: [{ role: "user", content: "local selftest" }] }) + for(const [model,status] of [["json",200],["unknown-selftest-model",404]]){ + const before=seen.length; + const response=await fetch(`http://127.0.0.1:${port}/v1/chat/completions`,{ + method:"POST",signal:AbortSignal.timeout(5000),headers:{"content-type":"application/json","x-api-key":"local-test-only"}, + body:JSON.stringify({model,max_tokens:16,stream:false,messages:[{role:"user",content:"local route selftest"}]}) }); - return [response.status, await response.text()]; - }; - let [st, text] = await openai("json"); - assert.equal(st, 200, text); - assert.match(text, /LOCAL_OK/); - assert.equal(seen.at(-1).model, "json"); - [st, text] = await openai("nope"); - assert.equal(st, 404, text); - assert.match(text, /not found/i); - passed += 2; + const text=await response.text();assert.equal(response.status,status,text); + assert.equal(seen.length-before,status===200?1:0); + if(status===200){assert.match(text,/LOCAL_OK/);assert.equal(seen.at(-1).model,model);} + } console.log("PASS openai bare model routed / unknown stays 404"); // 上游不认推理参数:第一次 400 后去掉重发并记住,第二次直接不带(#84) for (const round of [1, 2]) { @@ -161,24 +178,6 @@ async function main() { } passed++; console.log("PASS strict upstream; reasoning params dropped after 400, remembered; real errors kept"); - // 06-路径别名:安卓上 /data/data/<包名> 与 /data/user/N/<包名> 是同一目录的两种写法(绑定挂载,realpath 不归并)。 - // 配置时记一种写法、卸载时敲另一种,卸载不能因为字符串对不上被拒(installer.cjs 的 sameDir)。 - { - const api = require(path.join(root, "installer.cjs")); - const aliasDir = fs.mkdtempSync(path.join(temp, "alias-")); - const u = aliasDir.match(/^\/data\/user(?:_de)?\/\d+\//); - const other = u ? "/data/data/" + aliasDir.slice(u[0].length) : null; - if (other && api.sameDir(aliasDir, other)) { - assert.ok(api.insideOrSame(aliasDir, temp)); - assert.ok(api.underDir(aliasDir, temp)); - assert.ok(!api.underDir(temp, temp), "自己不算位于自己之下"); - fs.writeFileSync(path.join(aliasDir, ".ccr-bridge-kit.json"), JSON.stringify({ id: "ccr-bridge-kit", version: api.VERSION, target: other })); - assert.doesNotThrow(() => api.loadManifest(aliasDir), "manifest 记 /data/data 写法、用 /data/user/0 写法卸载:要认同一目录"); - console.log("PASS path alias: /data/data 与 /data/user/N 两种写法认作同一目录"); - } else { - console.log("SKIP path alias: 本机没有 /data/data 别名(CI 或非安卓),无法实测"); - } - } } finally { if (child && child.exitCode === null) { child.kill("SIGTERM"); diff --git a/recipes/openai-bridge/runtime/service-registration.cjs b/recipes/openai-bridge/runtime/service-registration.cjs index 3bfeec0..e8572a7 100644 --- a/recipes/openai-bridge/runtime/service-registration.cjs +++ b/recipes/openai-bridge/runtime/service-registration.cjs @@ -3,6 +3,36 @@ const fs=require('node:fs'); const path=require('node:path'); const crypto=require('node:crypto'); const {spawnSync}=require('node:child_process'); +const os=require('node:os'); + +// 只折叠调用者信任的根,以及同一 Android 应用的两种系统前缀。 +// 不 realpath 整条输入:HOME/组件根以下的链接必须留给无链接校验拒绝。 +function normalizedPath(file,roots=[os.homedir()]){ + if(typeof file!=='string'||file.includes('\0')||!path.isAbsolute(file)||path.resolve(file)!==file)throw new Error('路径不是规范绝对路径。'); + const under=(value,root)=>value===root||value.startsWith(root+path.sep); + for(const root of roots){ + let real;try{real=fs.realpathSync(root);}catch{continue;} + if(root!==real&&under(file,root))file=path.join(real,path.relative(root,file)); + const match=/^\/data\/(?:data|user\/0)\/[^/]+(?=\/|$)/.exec(real); + if(!match)continue; + const app=match[0],identity=fs.lstatSync(fs.realpathSync(app)); + const primary=app.replace(/^\/data\/user\/0\//,'/data/data/'); + let canonical=fs.realpathSync(app); + try{const st=fs.lstatSync(primary);if(st.isDirectory()&&st.dev===identity.dev&&st.ino===identity.ino)canonical=fs.realpathSync(primary);}catch{} + for(const alias of [primary,app.replace(/^\/data\/data\//,'/data/user/0/')]){ + if(!under(file,alias))continue; + let st;try{st=fs.lstatSync(alias);}catch{continue;} + if(st.isDirectory()&&st.dev===identity.dev&&st.ino===identity.ino)return path.join(canonical,path.relative(alias,file)); + } + } + return file; +} +function samePath(a,b,roots){try{return normalizedPath(a,roots)===normalizedPath(b,roots);}catch{return false;}} +function pathAliases(file){ + const canonical=normalizedPath(file),variants=[file,canonical]; + if(/^\/data\/(?:data|user\/0)\//.test(canonical))variants.push(canonical.replace(/^\/data\/data\//,'/data/user/0/'),canonical.replace(/^\/data\/user\/0\//,'/data/data/')); + return [...new Set(variants)].filter(value=>samePath(value,canonical)); +} const ID='openai-bridge'; const fileOf=home=>path.join(home,'.cccodroid','services',ID+'.json'); @@ -18,9 +48,7 @@ function value(target,port,instanceId){ if(!path.isAbsolute(target)||path.resolve(target)!==target||!Number.isInteger(port)||port<1024||port>65535||!/^[0-9a-f]{32}$/.test(instanceId))throw new Error('服务注册参数不合法。'); return {schema:1,id:ID,endpoint:'http://127.0.0.1:'+port,runtimeDir:target,instanceId}; } -function sameDir(a,b){try{const sa=fs.lstatSync(a),sb=fs.lstatSync(b);return sa.dev===sb.dev&&sa.ino===sb.ino;}catch{return false;}} -// runtimeDir 按目录身份(dev:ino)比:注册记的是配置时的路径写法,卸载换一种别名写法(/data/data 与 /data/user/0)不该算「另一项注册」 -function same(a,b){return !!a&&Object.keys(a).length===5&&!!b&&['schema','id','endpoint','instanceId'].every(k=>a[k]===b[k])&&sameDir(a.runtimeDir,b.runtimeDir);} +function same(a,b){return !!a&&Object.keys(a).length===5&&!!b&&['schema','id','endpoint','instanceId'].every(k=>a[k]===b[k])&&samePath(a.runtimeDir,b.runtimeDir);} function check(home,target,port,instanceId){return same(read(home),value(target,port,instanceId));} function lock(home,fn){ const dir=path.dirname(fileOf(home)); @@ -49,8 +77,8 @@ function registerLocked(home,target,port,instanceId){ } function unregister(home,target,instanceId){return lock(home,()=>{ const current=read(home); - if(!current||current.id!==ID||current.schema!==1||!sameDir(current.runtimeDir,target)||current.instanceId!==instanceId)return false; + if(!current||current.id!==ID||current.schema!==1||!samePath(current.runtimeDir,target)||current.instanceId!==instanceId)return false; fs.unlinkSync(fileOf(home)); return true; });} -module.exports={fileOf,read,value,check,register,unregister}; +module.exports={fileOf,read,value,check,register,unregister,normalizedPath,samePath,pathAliases}; diff --git a/recipes/openai-bridge/runtime/start-bridge.sh b/recipes/openai-bridge/runtime/start-bridge.sh index 5e88d83..c2edff0 100755 --- a/recipes/openai-bridge/runtime/start-bridge.sh +++ b/recipes/openai-bridge/runtime/start-bridge.sh @@ -87,7 +87,7 @@ if ! watchdog_running; then EXE=$(readlink "${PROC%/cmdline}/exe" 2>/dev/null) || EXE= EXE=${EXE% (deleted)} [[ ( $EXE = /system/bin/linker64 || $EXE =~ ^/apex/com\.android\.runtime(@[^/]*)?/bin/linker64$ ) && ${#ARGS[@]} -ge 2 ]] && ARGS=("${ARGS[@]:1}") - if [[ ${#ARGS[@]} -ge 2 && ${ARGS[0]##*/} = bash && ${ARGS[1]} = "$BR/watchdog.sh" ]]; then + if [[ ${#ARGS[@]} -ge 2 && ${ARGS[0]##*/} = bash ]] && bridge_path_same "${ARGS[1]}" "$BR/watchdog.sh"; then sleep 0.2 watchdog_running || fail "发现尚未迁移的看护(${PROC%/cmdline}),需先确认并替换旧看护" break diff --git a/recipes/openai-bridge/skill/SKILL.md b/recipes/openai-bridge/skill/SKILL.md index 59e03ad..d7b1f68 100644 --- a/recipes/openai-bridge/skill/SKILL.md +++ b/recipes/openai-bridge/skill/SKILL.md @@ -30,7 +30,7 @@ openai-bridge → 本组件的 component.cjs / installer.cjs($PREFIX/lib/opena - SessionStart Hook 只匹配 `startup|resume`。仅当会话的 `ANTHROPIC_BASE_URL` 直接指向本桥 `http://127.0.0.1:` 或其下方路径,或经 App 本机 streamfix 包装且解码后严格指向本桥时投递后台看护。只解开一层合法回环包装;其他端口/主机、错误编码、嵌套包装、未设端点、compact/clear 不触发启动。即使是定时任务,是否运行也取决于该会话端点,不按任务类别一概跳过。Hook 不等补丁、服务锁或就绪;异步错误看私有日志,手动 start 会检查就绪,不会静默切模型。 - manifest 记录组件包入口,App 移除后残留 Hook 只写清理日志并退出;已有看护也会退出、不再重启 CCR。不强杀已运行请求,不自动删数据;若入口已删除,请在私有安装目录运行 `bash uninstall.sh --yes` 清理。 - 本地 `/health` 正常只说明有本地服务响应,不代表远端可用,也不能覆盖恢复耗尽、补丁校验失败或停用等故障。配置页与启动按同一固定错误码阻断;保存配置不解除恢复故障。若只是上次配置崩溃留下精确 `configuring` 临时标记,用户下一次明确保存可在实例核对、停止旧进程和完整提交后完成事务并清掉它;只读页面不清,其他停用及恢复锁/次数不清。上游失败不会通过反复重启本地服务修好。 -- 可信 HOME 根先统一真实路径,再生成默认实例目录并传给子进程;实例目录以下仍拒绝符号链接、不匹配的实例身份与运行文件修改。更新时组件入口短暂缺失会有界重新确认,不在缺失期间启动;确认等待释放服务锁、放弃旧事务,重取锁后重新核对实例及恢复预算,不能覆盖并发启动。真正停用立即阻断,永久缺失最终停止,不无限等待或自动清恢复锁。 +- 可信 HOME/组件根及同一 Android 应用的 `/data/data/<包名>`、`/data/user/0/<包名>` 别名先核对根目录身份再归并;显式 `--dir`、旧清单/注册、启动/升级/卸载统一使用这一规则,无需手改清单。只投影信任根前缀,实例目录以下仍拒绝符号链接、不匹配的实例身份与运行文件修改。更新时组件入口短暂缺失会有界重新确认,不在缺失期间启动;确认等待释放服务锁、放弃旧事务,重取锁后重新核对实例及恢复预算,不能覆盖并发启动。真正停用立即阻断,永久缺失最终停止,不无限等待或自动清恢复锁。 - 服务只监听回环地址。它是用户自有 API 的协议适配,不共享、转售或转发 Claude 订阅账户,不读取 Claude 登录凭据、不改 Claude Code 本体、不绕过模型安全限制。 ## 配置