openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
372 lines (371 loc) • 13.4 kB
JavaScript
import "./src-H3RMXyFL.mjs";
import { t as expectDefined } from "./expect-DDakjvvQ.mjs";
import { t as isPlainObject } from "./plain-object-CGY5w7fM.mjs";
import { t as parseJsonWithJson5Fallback } from "./parse-json-compat-DoWUfD79.mjs";
import { o as openRootFileSync, t as canUseRootFileOpen } from "./boundary-file-read-BfaFLDqt.mjs";
import { i as isMissingPathError } from "./errno-DFcoqIT9.mjs";
import { r as resolvePathViaExistingAncestorSync } from "./boundary-path-C2gXEiXe.mjs";
import { t as mergeDeep } from "./deep-merge-Wuxftp-p.mjs";
import "./utils-C8YECn2Q.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";
//#region src/security/scan-paths.ts
/** Return true for extension paths intentionally skipped by source scanners. */
function extensionUsesSkippedScannerPath(e) {
return e.split(/[\\/]+/).filter(Boolean).some((e) => e === "node_modules" || e.startsWith(".") && e !== "." && e !== "..");
}
//#endregion
//#region src/config/includes.ts
/**
* Config includes: $include directive for modular configs
*
* @example
* ```json5
* {
* "$include": "./base.json5", // single file
* "$include": ["./a.json5", "./b.json5"] // merge multiple
* }
* ```
*/
const INCLUDE_KEY = "$include";
const MAX_INCLUDE_DEPTH = 10;
const MAX_INCLUDE_FILE_BYTES = 2097152;
/** Maximum length for $include path and resolved path (CWE-22 hardening). */
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");
}
/** Resolve an include write target through its current ancestors and allowed roots. */
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));
if (!n.some((e) => isPathInside$1(e, t))) throw new ConfigIncludeError(`Include write path escapes config directory: ${e.includePath}`, e.includePath);
const r = path.normalize(resolvePathViaExistingAncestorSync(t));
if (!n.map((e) => path.normalize(safeRealpath(e))).some((e) => isPathInside$1(e, r))) throw new ConfigIncludeError(`Include write path resolves outside config directory (symlink): ${e.includePath}`, e.includePath);
return r;
}
/**
* Whether an include target canonically resolves inside the config directory.
* Write eligibility must use the canonical form: a symlink beneath the config
* directory can point at an external OPENCLAW_INCLUDE_ROOTS file that reads
* accept but the guarded include writer rejects.
*/
function isInternalIncludeWriteTarget(e) {
const t = path.normalize(path.resolve(e.includePath));
const n = path.normalize(path.dirname(path.resolve(e.configPath)));
if (!isPathInside$1(n, t)) return false;
const r = path.normalize(resolvePathViaExistingAncestorSync(t));
const i = path.normalize(resolvePathViaExistingAncestorSync(n));
return isPathInside$1(i, 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";
}
};
/** File access failed; the included configuration has not been validated. */
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";
}
};
/** Deep merge: arrays concatenate, objects merge recursively, primitives: source wins */
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 = this.findContainingRoot(i, "rootDir");
if (!a) 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: a
};
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) {
try {
return fs.realpathSync(e);
} catch {
return e;
}
}
/** Capture the lexical and canonical include roots once for a resolver traversal. */
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
};
/**
* Creates a resolver that shares one immutable root snapshot across independent
* include resolutions. Used when callers must isolate malformed sibling graphs.
*/
function createConfigIncludeResolutionSession(e, t = []) {
const n = createConfigIncludeBoundary(e, t);
return (e, t, r = defaultResolver) => new IncludeProcessor(t, r, n).process(e);
}
/**
* Resolves all $include directives in a parsed config object.
*/
function resolveConfigIncludes(e, t, n = defaultResolver, r = {}) {
const i = createConfigIncludeBoundary(t, r.allowedRoots ?? []);
return new IncludeProcessor(t, n, i).process(e);
}
/**
* Resolves one top-level config field through the canonical include graph while
* leaving unrelated top-level branches untouched. Early bootstrap readers use
* this when a malformed sibling must not hide an independently valid setting.
*/
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);
}
//#endregion
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 };