openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
8 lines • 18.6 kB
JavaScript
import{c as normalizeOptionalLowercaseString}from"./string-coerce-CpTFcSwY.mjs";import{r as isPathInside}from"./path-guards-DGttsOJI.mjs";import{t as FsSafeError}from"./fs-safe-Bxzu1j4h.mjs";import{a as openRootFile,s as readFileDescriptorBounded}from"./boundary-file-read-bB9An35K.mjs";import{i as isMissingPathError}from"./errno-DUBt6SQQ.mjs";import"./errors-D37BJTfI.mjs";import{f as resolveIdentityPathViaExistingAncestorSync}from"./path-existence-BR9MXlgL.mjs";import{i as resolveSandboxHostPathViaExistingAncestor,r as normalizeSandboxHostPath,t as getSandboxHostPathPolicyKey}from"./host-paths-CmrZGmeh.mjs";import{n as normalizeContainerPathCore,r as relativePathEscapesContainerRoot,t as isPathInsideContainerRoot}from"./path-utils-C1CmrIel.mjs";import{c as resolveSandboxTmpfsMounts}from"./workspace-mounts-DefzGu84.mjs";import{a as resolveSandboxFsPathWithMounts,i as resolveSandboxFsMount,t as buildSandboxFsMounts}from"./fs-paths-Djl1qCxq.mjs";import{c as buildPinnedMutationPlan,i as PINNED_MUTATION_ACTION_LABELS,l as parseDirectoryEntries,n as parseSandboxStatMtimeMs,r as parseSandboxStatSize}from"./fs-bridge-stat-parse-DmQs0gu9.mjs";import{t as SANDBOX_FILE_IDENTITY}from"./file-mutation-identity-nZwlS4qx.mjs";import fs from"node:fs";import path from"node:path";import{promisify}from"node:util";import{GUEST_FILESYSTEM_CREATE_EXISTS_EXIT_CODE}from"@openclaw/fs-safe/guest";
//!src/agents/sandbox/fs-bridge-path-safety.ts
function sandboxBoundaryError(e,t,n){if(n instanceof Error&&!(n instanceof FsSafeError&&n.code===`not-file`))return n;return new Error(`Sandbox boundary checks failed; cannot ${e}: ${t}`,{cause:n})}var SandboxFsPathGuard=class{constructor(e){this.mountsByContainer=e.mountsByContainer.map(e=>({hostRoot:e.hostRoot,containerRoot:e.containerRoot,writable:e.writable,source:e.source,canonicalHostRoot:e.canonicalHostRoot??resolveSandboxHostPathViaExistingAncestor(e.hostRoot)}));this.runCommand=e.runCommand;this.containerOnlyMounts=e.containerOnlyMounts??[]}async assertPathChecks(e,t){for(const n of e)await this.assertPathSafety(n.target,{...n.options,signal:t})}async assertPathSafety(e,t){const n=t.allowedType===`file-or-directory`?this.pathIsExistingDirectory(e.hostPath)?`directory`:`file`:t.allowedType;const r=await this.openBoundaryWithinRequiredMount(e,t.action,{aliasPolicy:t.aliasPolicy,allowedType:n,signal:t.signal});await this.assertGuardedPathSafety(e,{...t,allowedType:n},r)}async openReadableFile(e,t,n,r){const i=await this.resolveCanonicalReadTarget(e,`read files`,t);const a=await this.openBoundaryWithinRequiredMount(i.target,`read files`,{signal:t,allowedType:r===`file-or-directory`?this.pathIsExistingDirectory(i.target.hostPath)?`directory`:`file`:r});if(!a.ok)throw sandboxBoundaryError(`read files`,e.containerPath,a.error);try{this.assertExpectedPolicyPath(i.target,a.path,n);if(getSandboxHostPathPolicyKey(i.canonicalHostPath)!==getSandboxHostPathPolicyKey(a.path))throw new Error(`Sandbox path is hidden by another mount: ${e.containerPath}. Use the mounted container path directly.`)}catch(e){fs.closeSync(a.fd);throw e}return{...a,containerPath:i.target.containerPath}}async resolveCanonicalEndpoint(e,t){const n=await this.resolveCanonicalContainerPath({containerPath:e,allowFinalSymlinkForUnlink:false,resolveIdentity:t?.identity,signal:t?.signal});const r=resolveSandboxFsMount(this.mountsByContainer,n,this.containerOnlyMounts,{containerOnlyAsUnmapped:t?.identity});const i=r?path.posix.relative(r.containerRoot,n).split(`/`):[];return{containerPath:n,mount:r,hostPath:r?path.resolve(r.hostRoot,...i):void 0,canonicalHostPath:r?path.resolve(r.canonicalHostRoot,...i):void 0}}async resolveFileIdentity(e,t){const n=await this.resolveCanonicalEndpoint(e.containerPath,{identity:true,signal:t});return n.canonicalHostPath??`container:${n.containerPath}`}async resolveReadPolicyPath(e,t){const n=await this.resolveCanonicalReadTarget(e,`authorize file reads`,t);return this.policyPathForCanonicalHostIdentity(n.target,resolveIdentityPathViaExistingAncestorSync(n.canonicalHostPath))}policyPathForCanonicalHostIdentity(e,t){const n=normalizeSandboxHostPath(t);const r=this.resolveMountByContainerPath(e.containerPath);const i=r&&isPathInside(r.canonicalHostRoot,n)?r:this.mountsByContainer.toSorted((e,t)=>t.canonicalHostRoot.length-e.canonicalHostRoot.length).find(e=>isPathInside(e.canonicalHostRoot,n));if(!i)throw new Error(`Sandbox path escapes allowed mounts: ${e.containerPath}`);const a=path.relative(i.canonicalHostRoot,n);return normalizeContainerPathCore(a?path.posix.join(i.containerRoot,...a.split(path.sep)):i.containerRoot)}async resolveCanonicalReadTarget(e,t,n){const r=await this.resolveCanonicalEndpoint(e.containerPath,{signal:n});if(!r.mount||!r.hostPath||!r.canonicalHostPath)throw new Error(`Sandbox path escapes allowed mounts; cannot ${t}: ${r.containerPath}`);return{target:{...e,containerPath:r.containerPath,hostPath:r.hostPath,writable:r.mount.writable},canonicalHostPath:r.canonicalHostPath}}resolveRequiredMount(e,t){const n=this.resolveMountByContainerPath(e);if(!n)throw new Error(`Sandbox path escapes allowed mounts; cannot ${t}: ${e}`);return n}async assertGuardedPathSafety(e,t,n){if(!n.ok){if(n.reason!==`path`){if(!(n.reason===`io`&&t.allowedType===`directory`&&this.pathIsExistingDirectory(e.hostPath)))throw sandboxBoundaryError(t.action,e.containerPath,n.error)}}else fs.closeSync(n.fd);const r=await this.resolveCanonicalContainerPath({containerPath:e.containerPath,allowFinalSymlinkForUnlink:t.aliasPolicy?.allowFinalSymlinkForUnlink===true,signal:t.signal});const i=this.resolveRequiredMount(r,t.action);if(t.requireWritable===`subtree`&&this.containerOnlyMounts.some(e=>isPathInsideContainerRoot(r,e)))throw new Error(`Sandbox subtree contains a container-only mount; cannot ${t.action}: ${e.containerPath}. Use exec to access this mount.`);if(t.requireWritable&&(!i.writable||t.requireWritable===`subtree`&&this.mountsByContainer.some(e=>!e.writable&&isPathInsideContainerRoot(r,e.containerRoot))))throw new Error(`Sandbox path is read-only; cannot ${t.action}: ${e.containerPath}`)}async openBoundaryWithinRequiredMount(e,t,n){const r=this.resolveRequiredMount(e.containerPath,t);n?.signal?.throwIfAborted();const i=await openRootFile({absolutePath:e.hostPath,rootPath:r.hostRoot,boundaryLabel:`sandbox mount root`,rejectSymlinks:false,aliasPolicy:n?.aliasPolicy,allowedType:n?.allowedType});if(n?.signal?.aborted){if(i.ok)fs.closeSync(i.fd);n.signal.throwIfAborted()}return i}resolvePinnedEntry(e,t){const n=path.posix.basename(e.containerPath);if(!n||n===`.`||n===`/`)throw new Error(`Invalid sandbox entry target: ${e.containerPath}`);const r=normalizeContainerPathCore(path.posix.dirname(e.containerPath));const{mountRootPath:i,relativePath:a}=this.resolvePinnedDirectory(r,t,e.containerPath);return{mountRootPath:i,relativeParentPath:a,basename:n}}async resolveAnchoredSandboxEntry(e,t,n){const r=path.posix.basename(e.containerPath);if(!r||r===`.`||r===`/`)throw new Error(`Invalid sandbox entry target: ${e.containerPath}`);const i=normalizeContainerPathCore(path.posix.dirname(e.containerPath));const a=await this.resolveCanonicalContainerPath({containerPath:i,allowFinalSymlinkForUnlink:false,signal:n});this.resolveRequiredMount(a,t);return{canonicalParentPath:a,basename:r}}async resolveAnchoredPinnedEntry(e,t,n){const r=await this.resolveAnchoredSandboxEntry(e,t,n);const{mountRootPath:i,relativePath:a}=this.resolvePinnedDirectory(r.canonicalParentPath,t,e.containerPath);return{mountRootPath:i,relativeParentPath:a,basename:r.basename}}async resolveCanonicalMutationTarget(e,t,n){if(n?.directory){const r=await this.resolveCanonicalContainerPath({containerPath:e.containerPath,allowFinalSymlinkForUnlink:false,signal:n?.signal});this.resolveRequiredMount(r,t);return r}const r=await this.resolveAnchoredSandboxEntry(e,t,n?.signal);this.resolveRequiredMount(r.canonicalParentPath,t);return r.canonicalParentPath===`/`?`/${r.basename}`:`${r.canonicalParentPath}/${r.basename}`}async resolveAnchoredPinnedDirectoryEntry(e,t,n){const r=await this.resolveCanonicalContainerPath({containerPath:e.containerPath,allowFinalSymlinkForUnlink:false,signal:n});return this.resolvePinnedDirectoryEntry({...e,containerPath:r},t)}resolvePinnedDirectoryEntry(e,t){return this.resolvePinnedDirectory(e.containerPath,t)}resolvePinnedDirectory(e,t,n=e){const r=this.resolveRequiredMount(e,t);const i=path.posix.relative(r.containerRoot,e);if(relativePathEscapesContainerRoot(i))throw new Error(`Sandbox path escapes allowed mounts; cannot ${t}: ${n}`);return{mountRootPath:r.containerRoot,relativePath:i===`.`?``:i}}pathIsExistingDirectory(e){try{return fs.statSync(e).isDirectory()}catch{return false}}assertExpectedPolicyPath(e,t,n){if(n!==void 0&&this.policyPathForCanonicalHostIdentity(e,t)!==normalizeContainerPathCore(n))throw new Error(`Sandbox file changed after authorization: ${e.containerPath}`)}resolveMountByContainerPath(e){const t=normalizeContainerPathCore(e);return resolveSandboxFsMount(this.mountsByContainer,t,this.containerOnlyMounts)}async resolveCanonicalContainerPath(e){const t=[`set -eu`,`target="$1"`,`allow_final="$2"`,`identity="$3"`,`suffix=""`,`read_canonical() {`,` canonical=$(readlink -n -f -- "$cursor" && printf .) || return`," canonical=${canonical%.}",`}`,`probe="$target"`,'if [ "$allow_final" = "1" ] && [ -L "$target" ]; then probe=${target%/*}; probe=${probe:-/}; fi',`cursor="$probe"`,`while [ ! -e "$cursor" ] && [ ! -L "$cursor" ]; do`," parent=${cursor%/*}; parent=${parent:-/}",` if [ "$parent" = "$cursor" ]; then break; fi`," base=${cursor##*/}",` suffix="/$base$suffix"`,` cursor="$parent"`,`done`,`if [ "$identity" = "1" ]; then`,` while ! read_canonical; do`," parent=${cursor%/*}; parent=${parent:-/}",` if [ "$parent" = "$cursor" ]; then canonical="$target"; suffix=""; break; fi`," base=${cursor##*/}",` suffix="/$base$suffix"`,` cursor="$parent"`,` done`,`else`,` read_canonical`,`fi`,`printf "%s%s\\n" "$canonical" "$suffix"`].join(`
`);const n=(await this.runCommand(t,{args:[e.containerPath,e.allowFinalSymlinkForUnlink?`1`:`0`,e.resolveIdentity?`1`:`0`],signal:e.signal})).stdout.toString(`utf8`).replace(/\n$/,``);if(!n.startsWith(`/`))throw new Error(`Failed to resolve sandbox path: ${e.containerPath}`);return normalizeContainerPathCore(n)}};
//!src/agents/sandbox/fs-bridge.ts
const readFileAsync=promisify(fs.readFile);function createSandboxFsBridge(e){return new SandboxFsBridgeImpl(e.sandbox,e.containerOnlyMounts)}async function resolveSandboxReferencePath(e,t){return e instanceof SandboxFsBridgeImpl?e.resolvePathInWorker(t):e.resolvePath(t)}var SandboxFsBridgeImpl=class{constructor(e,t){this.sandbox=e;this.mounts=e.fsPreparation?.mounts??buildSandboxFsMounts(e);this.containerOnlyMounts=t??resolveSandboxTmpfsMounts(e.docker.tmpfs).map(e=>e.containerPath);const n=this.mounts.toSorted((e,t)=>t.containerRoot.length-e.containerRoot.length);this.pathGuard=new SandboxFsPathGuard({mountsByContainer:n,containerOnlyMounts:this.containerOnlyMounts,runCommand:(t,n)=>e.backend.runShellCommand({script:t,...n})})}resolvePath(e){const t=this.resolveResolvedPath(e);return{hostPath:t.hostPath,relativePath:t.relativePath,containerPath:t.containerPath}}async resolvePathInWorker(e){const t=this.pathInput(e);const{prepareSandboxFsPath:n}=await import(`./refresh-DDFbJ_aI.mjs`);return n(t)}get pathMappings(){return this.mounts}async[SANDBOX_FILE_IDENTITY](e){return this.pathGuard.resolveFileIdentity(this.resolveResolvedPath(e),e.signal)}async resolveReadPolicyPath(e){return await this.pathGuard.resolveReadPolicyPath(this.resolveResolvedPath(e),e.signal)}async resolvePinnedMutationTarget(e){const t=this.resolveResolvedPath(e);const n=await this.pathGuard.resolveCanonicalMutationTarget(t,PINNED_MUTATION_ACTION_LABELS[e.action],{directory:e.action===`mkdir`,signal:e.signal});return{policyPath:n,pinnedPath:n}}async readFile(e){return(await this.readFileWithSource(e)).data}async readFileWithSource(e){const t=this.resolveResolvedPath(e);return this.readPinnedFile(t,e.maxBytes,e.signal,e.expectedPolicyPath)}async readDirectory(e){const t=this.resolveResolvedPath(e);const n=await this.runCheckedCommand({...buildPinnedMutationPlan({kind:`readdir`,target:t,pinned:await this.pathGuard.resolveAnchoredPinnedDirectoryEntry(t,`list directories`,e.signal)}),signal:e.signal});return parseDirectoryEntries(n.stdout.toString(`utf8`))}async copyFile(e){const t=this.resolveResolvedPath({filePath:e.sourcePath,cwd:e.cwd});const n=this.resolveResolvedPath({filePath:e.destinationPath,cwd:e.cwd});this.ensureWriteAccess(n,`copy files`);await this.runCheckedCommand({...buildPinnedMutationPlan({kind:`copy`,sourceTarget:t,destinationTarget:n,source:await this.pathGuard.resolveAnchoredPinnedEntry(t,`copy files`,e.signal),destination:await this.resolveMutationPin(n,e.pinnedPath,`copy files`,e.signal),mkdir:e.mkdir!==false}),signal:e.signal})}async writeFile(e){await this.writeFileContents(e,`write`)}async createFileExclusive(e){const{result:t,containerPath:n}=await this.writeFileContents(e,`create`);if(t.code===GUEST_FILESYSTEM_CREATE_EXISTS_EXIT_CODE)return`exists`;if(t.code!==0)throw new Error(`sandbox create failed for ${n}: ${t.stderr.toString(`utf8`).trim()}`);return`created`}async writeFileContents(e,t){const n=PINNED_MUTATION_ACTION_LABELS[t];const r=this.resolveResolvedPath(e);this.ensureWriteAccess(r,n);await this.pathGuard.assertPathSafety(r,{action:n,requireWritable:true,signal:e.signal});const i=Buffer.isBuffer(e.data)?e.data:Buffer.from(e.data,e.encoding??`utf8`);const a=await this.resolveMutationPin(r,e.pinnedPath,n,e.signal);return{result:await this.runCheckedCommand({...buildPinnedMutationPlan({kind:t,target:r,pinned:a,mkdir:e.mkdir!==false}),allowFailure:t===`create`?true:void 0,stdin:i,signal:e.signal}),containerPath:r.containerPath}}async mkdirp(e){const t=this.resolveResolvedPath(e);this.ensureWriteAccess(t,`create directories`);await this.runCheckedCommand({...buildPinnedMutationPlan({kind:`mkdirp`,target:t,pinned:this.pathGuard.resolvePinnedDirectoryEntry(e.pinnedPath===void 0?t:this.authorizedPinnedTarget(t,e.pinnedPath,`create directories`,{directory:true}),`create directories`)}),signal:e.signal})}async remove(e){const t=this.resolveResolvedPath(e);this.ensureWriteAccess(t,`remove files`);await this.runCheckedCommand({...buildPinnedMutationPlan({kind:`remove`,target:t,pinned:this.pathGuard.resolvePinnedEntry(e.pinnedPath===void 0?t:this.authorizedPinnedTarget(t,e.pinnedPath,`remove files`),`remove files`),recursive:e.recursive,force:e.force}),signal:e.signal})}async rename(e){const t=this.resolveResolvedPath({filePath:e.from,cwd:e.cwd});const n=this.resolveResolvedPath({filePath:e.to,cwd:e.cwd});this.ensureWriteAccess(t,`rename files`);this.ensureWriteAccess(n,`rename files`);await this.runCheckedCommand({...buildPinnedMutationPlan({kind:`rename`,sourceTarget:t,destinationTarget:n,source:this.pathGuard.resolvePinnedEntry(t,`rename files`),destination:this.pathGuard.resolvePinnedEntry(n,`rename files`)}),signal:e.signal})}async stat(e){const t=this.resolveResolvedPath(e);if(e.expectedPolicyPath!==void 0){let n;try{n=await this.pathGuard.openReadableFile(t,e.signal,e.expectedPolicyPath,`file-or-directory`)}catch(e){if(isMissingPathError(e))return null;throw e}try{return{type:n.stat.isDirectory()?`directory`:`file`,size:parseSandboxStatSize(String(n.stat.size)),mtimeMs:Math.trunc(n.stat.mtimeMs)}}finally{fs.closeSync(n.fd)}}const n=await this.pathGuard.resolveCanonicalReadTarget(t,`stat files`,e.signal);const r=await this.pathGuard.resolveAnchoredSandboxEntry(t,`stat files`,e.signal);const i=await this.runCheckedCommand({checks:[{target:n.target,options:{action:`stat files`}}],script:`set -eu
cd -- "$1"
LC_ALL=C stat -c "%F|%s|%y" -- "$2"`,args:[r.canonicalParentPath,r.basename],allowFailure:true,signal:e.signal});if(i.code!==0){const e=i.stderr.toString(`utf8`);if(e.includes(`No such file or directory`))return null;const n=e.trim()||`stat failed with code ${i.code}`;throw new Error(`stat failed for ${t.containerPath}: ${n}`)}const[a,o,s]=i.stdout.toString(`utf8`).trim().split(`|`);return{type:coerceStatType(a),size:parseSandboxStatSize(o),mtimeMs:parseSandboxStatMtimeMs(s)}}async readPinnedFile(e,t,n,r){const i=await this.pathGuard.openReadableFile(e,n,r);try{n?.throwIfAborted();let r;if(t===void 0){const e={signal:n,encoding:null};r=await readFileAsync(i.fd,e)}else{if(!Number.isSafeInteger(t)||t<0)throw new RangeError(`maxBytes must be a non-negative safe integer`);const a=fs.fstatSync(i.fd);if(!a.isFile())throw new Error(`Sandbox read requires a regular file: ${e.containerPath}`);if(a.size>t)throw new RangeError(`File exceeds ${t} bytes`);r=await readFileDescriptorBounded(i.fd,t);n?.throwIfAborted();const o=fs.fstatSync(i.fd);if(!o.isFile()||o.size>t)throw new RangeError(`File exceeds ${t} bytes`)}const a=resolveSandboxFsMount(this.mounts,i.containerPath,this.containerOnlyMounts);return{data:r,canonicalPath:i.containerPath,...a?.source===`workspace`?{workspaceRelativePath:path.posix.relative(a.containerRoot,i.containerPath)}:{}}}finally{fs.closeSync(i.fd)}}async runCheckedCommand(e){await this.pathGuard.assertPathChecks(e.checks,e.signal);return await this.sandbox.backend.runShellCommand({script:e.script,args:e.args,stdin:e.stdin,allowFailure:e.allowFailure,signal:e.signal})}ensureWriteAccess(e,t){if(this.sandbox.workspaceAccess===`ro`||!e.writable)throw new Error(`Sandbox path is read-only; cannot ${t}: ${e.containerPath}`)}resolveResolvedPath(e){return resolveSandboxFsPathWithMounts(this.pathInput(e))}pathInput(e){return{filePath:e.filePath,cwd:e.cwd??this.sandbox.workspaceDir,defaultWorkspaceRoot:this.sandbox.workspaceDir,defaultContainerRoot:this.sandbox.containerWorkdir,mounts:this.mounts,containerOnlyMounts:this.containerOnlyMounts}}async resolveMutationPin(e,t,n,r){if(t===void 0)return await this.pathGuard.resolveAnchoredPinnedEntry(e,n,r);return this.pathGuard.resolvePinnedEntry(this.authorizedPinnedTarget(e,t,n),n)}authorizedPinnedTarget(e,t,n,r){const i=normalizeContainerPathCore(t);if(!r?.directory&&path.posix.basename(i)!==path.posix.basename(e.containerPath))throw new Error(`Pinned sandbox destination does not match the requested path; cannot ${n}: ${e.containerPath}`);return{...e,containerPath:i}}};function coerceStatType(e){const t=normalizeOptionalLowercaseString(e)??``;if(t.includes(`directory`))return`directory`;if(t.includes(`file`))return`file`;return`other`}export{resolveSandboxReferencePath as n,createSandboxFsBridge as t};