openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
5 lines • 10.3 kB
JavaScript
import"./src-0ci69Prg.mjs";import{t as expectDefined}from"./expect-DkJCbmLj.mjs";import{t as parseJsonWithJson5Fallback}from"./parse-json-compat-BEbcOl-a.mjs";import"./utils-Dlk0IYAa.mjs";import{t as isPlainObject}from"./plain-object-CHrMoU5Q.mjs";import{o as openRootFileSync,t as canUseRootFileOpen}from"./boundary-file-read-bB9An35K.mjs";import{t as mergeDeep}from"./deep-merge-BcazJ3mu.mjs";import{i as isMissingPathError}from"./errno-DUBt6SQQ.mjs";import{a as realpathViaExistingPrefixSync,n as canonicalizeContainmentRootSync}from"./path-containment-Drv7Ulmz.mjs";import fs from"node:fs";import path from"node:path";import crypto from"node:crypto";import{isPathInside as isPathInside$1,isPathInsideWithRealpath as isPathInsideWithRealpath$1}from"@openclaw/fs-safe/path";
//!src/security/scan-paths.ts
function extensionUsesSkippedScannerPath(e){return e.split(/[\\/]+/).filter(Boolean).some(e=>e===`node_modules`||e.startsWith(`.`)&&e!==`.`&&e!==`..`)}
//!src/config/includes.ts
const INCLUDE_KEY=`$include`;const MAX_INCLUDE_DEPTH=10;const MAX_INCLUDE_FILE_BYTES=2097152;const MAX_INCLUDE_PATH_LENGTH=4096;function hashConfigIncludeRaw(e){const t=crypto.createHash(`sha256`);if(e===null)t.update(`missing`);else{t.update(`present\0`);t.update(e,`utf-8`)}return t.digest(`hex`)}function resolveConfigIncludeWritePath(e){const t=path.normalize(path.resolve(e.includePath));const n=[path.dirname(e.configPath),...e.allowedRoots??[]].filter(e=>path.isAbsolute(e)).map(e=>path.normalize(e));const r=realpathViaExistingPrefixSync(t);const i=r?path.normalize(r):void 0;const a=n.map(e=>path.normalize(canonicalizeContainmentRootSync(e)));const o=i!==void 0&&a.some(e=>isPathInside$1(e,i));if(!o&&!n.some(e=>isPathInside$1(e,t)))throw new ConfigIncludeError(`Include write path escapes config directory: ${e.includePath}`,e.includePath);if(!o||i===void 0)throw new ConfigIncludeError(`Include write path resolves outside config directory (symlink): ${e.includePath}`,e.includePath);return i}function isInternalIncludeWriteTarget(e){const t=path.normalize(path.resolve(e.includePath));const n=path.normalize(path.dirname(path.resolve(e.configPath)));const r=realpathViaExistingPrefixSync(t);return r!==void 0&&isPathInside$1(path.normalize(canonicalizeContainmentRootSync(n)),path.normalize(r))}function isConfigContainer(e){return Array.isArray(e)||isPlainObject(e)}function includeLogicalPath(e){const t=[];for(let n=e;n;n=n.parent)t.push(n.key);return t.toReversed()}var ConfigIncludeError=class extends Error{constructor(e,t,n){super(e);this.includePath=t;this.cause=n;this.name=`ConfigIncludeError`}};var ConfigIncludeReadError=class extends ConfigIncludeError{constructor(...e){super(...e);this.name=`ConfigIncludeReadError`}};var CircularIncludeError=class extends ConfigIncludeError{constructor(e){super(`Circular include detected: ${e.join(` -> `)}`,expectDefined(e[e.length-1],`chain entry at chain.length 1`));this.chain=e;this.name=`CircularIncludeError`}};function deepMerge(e,t){return mergeDeep(e,t,{arrays:`concat`,undefinedValues:`replace`})}var IncludeProcessor=class{constructor(e,t,n,r){this.basePath=e;this.resolver=t;this.boundary=n;this.rootProjectionKeys=r}get rootDir(){return this.boundary.configRoot.rootDir}process(e){const t=[];let n=this.traverseValue(e,null,false,{basePath:this.basePath,visited:/* @__PURE__ */ new Set([path.normalize(this.basePath)]),depth:0});let r=void 0;for(;;){const e=n.next(r);if(e.done){const i=t.pop();if(!i)return e.value;r=e.value;n=i;continue}t.push(n);n=this.traverseValue(e.value.value,e.value.pathLink,e.value.hasArrayAncestor,e.value.context)}}*traverseValue(e,t,n,r){if(Array.isArray(e)){const n=[];for(const[i,a]of e.entries())n.push(isConfigContainer(a)?yield{value:a,pathLink:{parent:t,key:String(i)},hasArrayAncestor:true,context:r}:a);return n}if(!isPlainObject(e))return e;if(!(`$include`in e)){const i=t===null;const a={};for(const[o,s]of Object.entries(e)){if(i&&this.rootProjectionKeys&&!this.rootProjectionKeys.has(o))continue;a[o]=isConfigContainer(s)?yield{value:s,pathLink:{parent:t,key:o},hasArrayAncestor:n,context:r}:s}return a}return yield*this.traverseInclude(e,t,n,r)}*traverseInclude(e,t,n,r){const i=e[INCLUDE_KEY];const a=t===null;const o=Object.keys(e).filter(e=>e!==`$include`&&(!a||!this.rootProjectionKeys||this.rootProjectionKeys.has(e)));const s=Array.isArray(i);if(!s&&typeof i!==`string`)throw new ConfigIncludeError(`Invalid $include value: expected string or array of strings, got ${typeof i}`,String(i));const c=[];for(const e of s?i:[i]){if(typeof e!==`string`)throw new ConfigIncludeError(`Invalid $include array item: expected string, got ${typeof e}`,String(e));const i=this.loadFileSync(e,r);c.push({value:yield{value:i.parsed,pathLink:t,hasArrayAncestor:n,context:i.nestedContext},targetPath:i.resolvedPath})}const l=s?c.reduce((e,t)=>deepMerge(e,t.value),{}):c[0].value;this.resolver.onIncludeResolved?.({path:includeLogicalPath(t),value:l,kind:s?`multiple`:`single`,hasSiblingOverrides:o.length>0,hasArrayAncestor:n,...s?{targetPaths:c.map(e=>e.targetPath)}:{targetPath:c[0].targetPath}});if(o.length===0)return l;if(!isPlainObject(l))throw new ConfigIncludeError(`Sibling keys require included content to be an object`,typeof i===`string`?i:INCLUDE_KEY);const u={};for(const i of o){const a=e[i];u[i]=isConfigContainer(a)?yield{value:a,pathLink:{parent:t,key:i},hasArrayAncestor:n,context:r}:a}return deepMerge(l,u)}loadFileSync(e,t){const{resolvedPath:n,root:r}=this.resolvePath(e,t);if(t.visited.has(n))throw new CircularIncludeError([...t.visited,n]);if(t.depth>=10)throw new ConfigIncludeError(`Maximum include depth (${10}) exceeded at: ${e}`,e);const i=this.readFile(e,n,r);return{parsed:this.parseFile(e,n,i),resolvedPath:n,nestedContext:{basePath:n,visited:/* @__PURE__ */ new Set([...t.visited,n]),depth:t.depth+1}}}resolvePath(e,t){if(e.includes(`\0`))throw new ConfigIncludeError(`Include path must not contain null bytes`,e);if(e.length>=MAX_INCLUDE_PATH_LENGTH)throw new ConfigIncludeError(`Include path exceeds maximum length (${MAX_INCLUDE_PATH_LENGTH} characters)`,e);const n=path.dirname(t.basePath);const r=path.isAbsolute(e)?e:path.resolve(n,e);const i=path.normalize(this.resolver.mapPath?.(r)??r);if(i.length>=MAX_INCLUDE_PATH_LENGTH)throw new ConfigIncludeError(`Resolved include path exceeds maximum length (${MAX_INCLUDE_PATH_LENGTH} characters)`,e);const a=realpathViaExistingPrefixSync(i);const o=this.findContainingRoot(i,`rootDir`)??(a?this.findContainingRoot(path.normalize(a),`rootRealDir`):null);if(!o)throw new ConfigIncludeError(`Include path escapes config directory: ${e} (root: ${this.rootDir})`,e);this.resolver.onLexicalPath?.(i);try{const t=fs.realpathSync(i);const n=this.findContainingRoot(t,`rootRealDir`);if(!n)throw new ConfigIncludeError(`Include path resolves outside config directory (symlink): ${e} (root: ${this.rootDir})`,e);return{resolvedPath:i,root:n}}catch(t){if(t instanceof ConfigIncludeError)throw t;if(isMissingPathError(t))return{resolvedPath:i,root:o};throw new ConfigIncludeReadError(`Failed to resolve include file realpath: ${e} (resolved: ${i})`,e,t instanceof Error?t:void 0)}}findContainingRoot(e,t){if(isPathInside$1(this.boundary.configRoot[t],e))return this.boundary.configRoot;for(const n of this.boundary.allowedRoots)if(isPathInside$1(n[t],e))return n;return null}readFile(e,t,n){try{if(this.resolver.readFileWithGuards)return this.resolver.readFileWithGuards({includePath:e,resolvedPath:t,rootRealDir:n.rootRealDir});return this.resolver.readFile(t)}catch(n){if(n instanceof ConfigIncludeError)throw n;throw new ConfigIncludeReadError(`Failed to read include file: ${e} (resolved: ${t})`,e,n instanceof Error?n:void 0)}}parseFile(e,t,n){try{return this.resolver.parseJson(n)}catch(n){throw new ConfigIncludeError(`Failed to parse include file: ${e} (resolved: ${t})`,e,n instanceof Error?n:void 0)}}};function safeRealpath(e){return canonicalizeContainmentRootSync(e)}function createConfigIncludeBoundary(e,t=[]){const n=path.normalize(path.dirname(e));return{configRoot:{rootDir:n,rootRealDir:path.normalize(safeRealpath(n))},allowedRoots:t.filter(e=>typeof e===`string`&&e.length>0&&path.isAbsolute(e)).map(e=>{const t=path.normalize(e);return{rootDir:t,rootRealDir:path.normalize(safeRealpath(t))}})}}function readConfigIncludeFileWithGuards(e){const t=e.ioFs??fs;const n=e.maxBytes??MAX_INCLUDE_FILE_BYTES;if(!canUseRootFileOpen(t)){const n=t.readFileSync(e.resolvedPath,`utf-8`);try{e.onResolvedPath?.(path.normalize(t.realpathSync(e.resolvedPath)))}catch{}return n}const r=openRootFileSync({absolutePath:e.resolvedPath,rootPath:e.rootRealDir,rootRealPath:e.rootRealDir,boundaryLabel:`config directory`,skipLexicalRootCheck:true,rejectSymlinks:false,maxBytes:n,ioFs:t});if(!r.ok){if(r.reason===`validation`)throw new ConfigIncludeError(`Include file failed security checks (regular file, max ${n} bytes, no hardlinks): ${e.includePath}`,e.includePath);throw new ConfigIncludeReadError(`Failed to read include file: ${e.includePath} (resolved: ${e.resolvedPath})`,e.includePath,r.error instanceof Error?r.error:void 0)}try{const n=t.readFileSync(r.fd,`utf-8`);e.onResolvedPath?.(path.normalize(r.path));return n}finally{t.closeSync(r.fd)}}const defaultResolver={readFile:e=>fs.readFileSync(e,`utf-8`),readFileWithGuards:readConfigIncludeFileWithGuards,parseJson:parseJsonWithJson5Fallback};function createConfigIncludeResolutionSession(e,t=[]){const n=createConfigIncludeBoundary(e,t);return(e,t,r=defaultResolver)=>new IncludeProcessor(t,r,n).process(e)}function resolveConfigIncludes(e,t,n=defaultResolver,r={}){const i=createConfigIncludeBoundary(t,r.allowedRoots??[]);return new IncludeProcessor(t,n,i).process(e)}function resolveConfigIncludesForTopLevelKey(e,t,n,r=defaultResolver,i={}){const a=createConfigIncludeBoundary(t,i.allowedRoots??[]);return new IncludeProcessor(t,r,a,/* @__PURE__ */ new Set([n])).process(e)}export{createConfigIncludeResolutionSession as a,readConfigIncludeFileWithGuards as c,resolveConfigIncludesForTopLevelKey as d,extensionUsesSkippedScannerPath as f,INCLUDE_KEY as i,resolveConfigIncludeWritePath as l,isPathInsideWithRealpath$1 as m,ConfigIncludeError as n,hashConfigIncludeRaw as o,isPathInside$1 as p,ConfigIncludeReadError as r,isInternalIncludeWriteTarget as s,CircularIncludeError as t,resolveConfigIncludes as u};