UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

391 lines (390 loc) • 15 kB
import { r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs"; import { a as extractErrorCode } from "./error-coercion-hDrHOSGy.mjs"; import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs"; import { t as createSubsystemLogger } from "./subsystem-BHJiy01V.mjs"; import { t as truncateUtf8Prefix } from "./utf8-truncate-BH7Ecfuh.mjs"; import "./string-coerce-runtime-BwAZZDf5.mjs"; import { o as sanitizeUntrustedFileName } from "./security-runtime-C-zE_Zy_.mjs"; import "./text-utility-runtime-Ds8jsG0J.mjs"; import { m as parseBrowserErrorPayload } from "./errors-C9QQGqVs.mjs"; import "./time-runtime-DoAwjF0T.mjs"; import "./error-runtime-BM740gJj.mjs"; import "./runtime-env-D-Pa5lD6.mjs"; import { i as resolveExistingUploadPaths, r as DEFAULT_UPLOAD_DIR } from "./paths-YzGx8hkK.mjs"; import path from "node:path"; import fs from "node:fs/promises"; //#region extensions/browser/src/browser-proxy-envelope.ts /** Additive opt-in for structured browser route errors over node.invoke. */ const BROWSER_PROXY_ERROR_ENVELOPE = "browser-v1"; /** Additive request envelope for Gateway-owned files sent to a browser node. */ const BROWSER_PROXY_UPLOAD_ENVELOPE = "browser-upload-v1"; /** Private node-host operation; unknown older nodes reject it before closing anything. */ const BROWSER_PROXY_OWNED_TAB_CLOSE_PATH = "/__openclaw/session-tab/close-owned"; const BROWSER_PROXY_MAX_FILE_BYTES = 10485760; const BROWSER_PROXY_MAX_TOTAL_FILE_BYTES = 16777216; const BROWSER_PROXY_MAX_FILES = 256; /** Bound filesystem work even when one action emits many tiny downloads. */ function assertBrowserProxyFileCountWithinLimit(e, t = "response") { if (e > BROWSER_PROXY_MAX_FILES) throw new Error(`browser proxy ${t} exceeds 256 file limit`); } function assertBrowserProxyFileBytesWithinLimits(e, t) { if (e > 10485760) throw new Error("browser proxy file exceeds 10 MiB limit"); if (t > BROWSER_PROXY_MAX_TOTAL_FILE_BYTES) throw new Error("browser proxy files exceed 16 MiB aggregate limit"); } /** Visit the route-owned file paths that may cross the Browser node boundary. */ function visitBrowserProxyFilePaths(e, t) { const n = asNullableRecord(e); if (!n) return; const visitPath = (e, n) => { if (!e) return; const r = e[n]; if (typeof r !== "string" || !r.trim()) return; const i = t(r); if (typeof i === "string") e[n] = i; }; visitPath(n, "path"); visitPath(n, "imagePath"); visitPath(asNullableRecord(n.download), "path"); if (Array.isArray(n.downloads)) for (const e of n.downloads) visitPath(asNullableRecord(e), "path"); } /** Build a route-failure envelope while allowing only closed Browser metadata. */ function createBrowserProxyFailure(e, t, n) { return { error: { status: e, body: parseBrowserErrorPayload(t) ?? { error: `HTTP ${e}` } }, ...n ? { route: n } : {} }; } function parseBrowserProxyRoute(e) { const t = asNullableRecord(asNullableRecord(e)?.route); if (!t) return; if (t.status === "unavailable") return { status: "unavailable" }; if (t.status !== "resolved" || typeof t.profile !== "string" || !t.profile || t.profile.trim() !== t.profile || t.driver !== "openclaw" && t.driver !== "existing-session" && t.driver !== "extension") return; return { status: "resolved", profile: t.profile, driver: t.driver }; } /** Parse an untrusted node response without forwarding arbitrary metadata. */ function parseBrowserProxyFailure(e) { const t = asNullableRecord(asNullableRecord(e)?.error); if (!t) return null; if (typeof t.status !== "number" || !Number.isInteger(t.status) || t.status < 400 || t.status > 599) return null; const n = parseBrowserErrorPayload(t.body); if (!n) return null; const r = parseBrowserProxyRoute(e); return { error: { status: t.status, body: n }, ...r ? { route: r } : {} }; } //#endregion //#region extensions/browser/src/browser-proxy-upload.ts /** * Existing Browser upload paths are Gateway-owned. Proxied requests carry * bounded bytes to the node, which stages private copies under its upload root. */ const logger = createSubsystemLogger("browser"); const BROWSER_PROXY_UPLOAD_ROOT_NAME = ".proxy-uploads"; const BROWSER_PROXY_UPLOAD_PREFIX = "upload-"; const BROWSER_PROXY_UPLOAD_MARKER_NAME = ".openclaw-browser-proxy-upload-v1"; const BROWSER_PROXY_UPLOAD_MARKER_CONTENT = "openclaw-browser-proxy-upload-v1\n"; const BROWSER_PROXY_UPLOAD_RETENTION_MS = 864e5; const BROWSER_PROXY_UPLOAD_MAX_RETAINED_BYTES = 268435456; const BROWSER_PROXY_UPLOAD_MAX_RETAINED_DIRECTORIES = 64; const BROWSER_PROXY_MAX_ENCODED_FILE_LENGTH = Math.ceil(BROWSER_PROXY_MAX_FILE_BYTES / 3) * 4; const MAX_STAGED_NAME_BYTES = 180; const cleanupTimers = /* @__PURE__ */ new Map(); let recoveryPromise; let recoveryFailed = false; let stagingTail; let activeCleanup = 0; let activeRecovery = 0; function hasBrowserProxyUploadWork() { return activeCleanup > 0 || activeRecovery > 0 || stagingTail !== void 0; } function isFileChooserRequest(e, t) { return e.toUpperCase() === "POST" && `/${t.trim().replace(/^\/+/u, "")}` === "/hooks/file-chooser"; } /** Identify upload requests before reading files or applying transport-only limits. */ function isBrowserProxyUploadRequest(e) { if (!isFileChooserRequest(e.method, e.path)) return false; const t = asNullableRecord(e.body); return Boolean(t && Array.isArray(t.paths) && t.paths.length > 0); } function readUploadPaths(e) { if (!Array.isArray(e.paths) || e.paths.length === 0) return null; if (!e.paths.every((e) => typeof e === "string")) throw new Error("browser proxy upload paths must contain only strings"); return e.paths; } async function readBrowserProxyUploadFiles(e, t) { const n = []; let r = 0; for (const i of e) { t?.throwIfAborted(); const e = await fs.stat(i).catch(() => null); if (!e?.isFile()) throw new Error(`browser proxy upload file not found: ${i}`); assertBrowserProxyFileBytesWithinLimits(e.size, r + e.size); const a = await fs.readFile(i, t ? { signal: t } : void 0); assertBrowserProxyFileBytesWithinLimits(a.byteLength, r + a.byteLength); r += a.byteLength; n.push({ name: path.basename(i), contentBase64: a.toString("base64") }); } return n; } /** Build a node-only upload envelope while retaining the original body for host fallback. */ async function prepareBrowserProxyUploadRequest(e) { e.signal?.throwIfAborted(); const t = isFileChooserRequest(e.method, e.path) ? asNullableRecord(e.body) : null; const n = t && readUploadPaths(t); if (!t || !n) return { body: e.body }; assertBrowserProxyFileCountWithinLimit(n.length, "request"); const r = await resolveExistingUploadPaths({ requestedPaths: n }); if (!r.ok) throw new Error(r.error); const i = { envelope: BROWSER_PROXY_UPLOAD_ENVELOPE, files: await readBrowserProxyUploadFiles(r.paths, e.signal) }; const { paths: a, ...o } = t; return { body: o, upload: i }; } function sanitizeUploadName(e) { const t = sanitizeUntrustedFileName(e, "upload").replace(/[!%]/gu, "_"); const n = truncateUtf8Prefix(t, MAX_STAGED_NAME_BYTES).replace(/[.\s]+$/u, ""); return sanitizeUntrustedFileName(n, "upload"); } function decodedBase64Size(e) { if (e.length % 4 !== 0) throw new Error("INVALID_REQUEST: invalid browser proxy upload encoding"); const t = e.endsWith("==") ? 2 : e.endsWith("=") ? 1 : 0; return e.length / 4 * 3 - t; } function decodeUploadFile(e, t) { if (!e || typeof e.name !== "string" || !e.name.trim() || typeof e.contentBase64 !== "string" || e.contentBase64.length > BROWSER_PROXY_MAX_ENCODED_FILE_LENGTH) throw new Error("INVALID_REQUEST: invalid browser proxy upload file"); const n = decodedBase64Size(e.contentBase64); assertBrowserProxyFileBytesWithinLimits(n, t + n); const r = Buffer.from(e.contentBase64, "base64"); if (r.toString("base64") !== e.contentBase64) throw new Error("INVALID_REQUEST: invalid browser proxy upload encoding"); return r; } async function removeStagedUpload(e) { activeCleanup += 1; const t = cleanupTimers.get(e); if (t) { clearTimeout(t); cleanupTimers.delete(e); } try { if ((await fs.lstat(e)).isDirectory()) { for (const t of await fs.readdir(e)) if (t !== BROWSER_PROXY_UPLOAD_MARKER_NAME) await fs.rm(path.join(e, t), { recursive: true, force: true }); } await fs.rm(e, { recursive: true, force: true }); } catch (e) { if (extractErrorCode(e) === "ENOENT") return; logger.warn(`browser proxy upload cleanup failed; retained for recovery: ${String(e)}`); } finally { activeCleanup -= 1; } } async function readUploadDirectoryEntries(e, t) { t?.throwIfAborted(); try { return await fs.readdir(e, { withFileTypes: true }); } catch (e) { if (e.code === "ENOENT") return []; throw e; } } async function readDirectoryBytes(e, t) { const n = await readUploadDirectoryEntries(e, t); let r = 0; for (const i of n) { t?.throwIfAborted(); const n = path.join(e, i.name); if (i.isDirectory()) { r += await readDirectoryBytes(n, t); continue; } if (!i.isFile()) continue; const a = await fs.stat(n).catch(() => null); r += a?.isFile() ? a.size : 0; } return r; } async function readOwnedStagedUploads(e, t) { const n = await readUploadDirectoryEntries(e, t); return (await Promise.all(n.filter((e) => e.isDirectory() && e.name.startsWith(BROWSER_PROXY_UPLOAD_PREFIX)).map(async (n) => { t?.throwIfAborted(); const r = path.join(e, n.name); const i = await fs.stat(r).catch(() => null); if (!i?.isDirectory()) return null; if (typeof process.getuid === "function" && i.uid !== process.getuid()) return null; if (await fs.readFile(path.join(r, BROWSER_PROXY_UPLOAD_MARKER_NAME), "utf8").catch(() => null) !== BROWSER_PROXY_UPLOAD_MARKER_CONTENT) return null; return { bytes: await readDirectoryBytes(r, t), directory: r, mtimeMs: i.mtimeMs }; }))).filter((e) => e !== null); } function scheduleCleanup(e, t) { if (cleanupTimers.has(e)) return; const n = setTimeout(() => { cleanupTimers.delete(e); removeStagedUpload(e); }, Math.max(0, t)); cleanupTimers.set(e, n); n.unref?.(); } async function recoverStagedUploads() { const e = Date.now(); const t = path.join(DEFAULT_UPLOAD_DIR, BROWSER_PROXY_UPLOAD_ROOT_NAME); const n = []; for (const r of await readOwnedStagedUploads(t)) if (BROWSER_PROXY_UPLOAD_RETENTION_MS - Math.max(0, e - r.mtimeMs) <= 0) await removeStagedUpload(r.directory); else n.push(r); n.sort((e, t) => e.mtimeMs - t.mtimeMs); let r = n.reduce((e, t) => e + t.bytes, 0); while (n.length > BROWSER_PROXY_UPLOAD_MAX_RETAINED_DIRECTORIES || r > BROWSER_PROXY_UPLOAD_MAX_RETAINED_BYTES) { const e = n.shift(); if (!e) break; r -= e.bytes; await removeStagedUpload(e.directory); } for (const t of n) { const n = BROWSER_PROXY_UPLOAD_RETENTION_MS - Math.max(0, e - t.mtimeMs); scheduleCleanup(t.directory, n); } } async function runRecovery() { activeRecovery += 1; try { await recoverStagedUploads(); recoveryFailed = false; } catch (e) { recoveryFailed = true; logger.warn(`browser proxy upload recovery failed; retry on the next upload: ${String(e)}`); } finally { activeRecovery -= 1; } } /** Restores cleanup timers for staged uploads left by a previous node process. */ function ensureBrowserProxyUploadCleanup() { return recoveryPromise ??= runRecovery(); } async function withStagingLock(e, t) { const n = stagingTail ?? Promise.resolve(); let release = () => {}; const r = new Promise((e) => { release = e; }); const i = n.then(() => r); stagingTail = i; i.then(() => { if (stagingTail === i) stagingTail = void 0; }); try { t?.throwIfAborted(); await racePromiseWithAbortSignal(n, t, ({ reason: e }) => e instanceof Error ? e : new Error(String(e))); return await e(); } finally { release(); } } function validateUploadEnvelope(e) { if (!e || e.envelope !== "browser-upload-v1" || !Array.isArray(e.files) || e.files.length === 0) throw new Error("INVALID_REQUEST: invalid browser proxy upload envelope"); assertBrowserProxyFileCountWithinLimit(e.files.length, "request"); return e.files; } async function stageBrowserProxyUploadRequest(e) { e.signal?.throwIfAborted(); if (e.upload === void 0) return { body: e.body }; if (!isFileChooserRequest(e.method, e.path)) throw new Error("INVALID_REQUEST: browser proxy upload requires the file chooser route"); const t = asNullableRecord(e.body); if (!t || Object.hasOwn(t, "paths")) throw new Error("INVALID_REQUEST: browser proxy upload body must omit paths"); const n = validateUploadEnvelope(e.upload); const r = path.join(DEFAULT_UPLOAD_DIR, BROWSER_PROXY_UPLOAD_ROOT_NAME); await fs.mkdir(r, { recursive: true, mode: 448 }); e.signal?.throwIfAborted(); if (recoveryFailed) { recoveryFailed = false; recoveryPromise = void 0; } await ensureBrowserProxyUploadCleanup(); e.signal?.throwIfAborted(); const i = []; let a = 0; for (const e of n) { const t = decodeUploadFile(e, a); a += t.byteLength; i.push({ buffer: t, name: e.name }); } const o = a + Buffer.byteLength(BROWSER_PROXY_UPLOAD_MARKER_CONTENT); return await withStagingLock(async () => { e.signal?.throwIfAborted(); const n = await readOwnedStagedUploads(r, e.signal); const a = n.reduce((e, t) => e + t.bytes, 0); if (n.length >= BROWSER_PROXY_UPLOAD_MAX_RETAINED_DIRECTORIES || a + o > BROWSER_PROXY_UPLOAD_MAX_RETAINED_BYTES) throw new Error("RESOURCE_EXHAUSTED: browser proxy upload staging limit reached"); const s = await fs.mkdtemp(path.join(r, BROWSER_PROXY_UPLOAD_PREFIX)); const c = []; try { await fs.writeFile(path.join(s, BROWSER_PROXY_UPLOAD_MARKER_NAME), BROWSER_PROXY_UPLOAD_MARKER_CONTENT, { flag: "wx", mode: 384, signal: e.signal }); for (const [t, n] of i.entries()) { e.signal?.throwIfAborted(); const r = path.join(s, String(t)); await fs.mkdir(r, { mode: 448 }); e.signal?.throwIfAborted(); const i = path.join(r, sanitizeUploadName(n.name)); await fs.writeFile(i, n.buffer, { flag: "wx", mode: 384, signal: e.signal }); c.push(i); } } catch (e) { await removeStagedUpload(s); throw e; } scheduleCleanup(s, BROWSER_PROXY_UPLOAD_RETENTION_MS); return { body: { ...t, paths: c }, directory: s }; }, e.signal); } /** Remove staged copies after a request fails before Browser ownership is established. */ async function discardStagedBrowserProxyUpload(e) { if (e.directory) await removeStagedUpload(e.directory); } //#endregion export { prepareBrowserProxyUploadRequest as a, BROWSER_PROXY_MAX_FILE_BYTES as c, assertBrowserProxyFileCountWithinLimit as d, createBrowserProxyFailure as f, visitBrowserProxyFilePaths as h, isBrowserProxyUploadRequest as i, BROWSER_PROXY_OWNED_TAB_CLOSE_PATH as l, parseBrowserProxyRoute as m, ensureBrowserProxyUploadCleanup as n, stageBrowserProxyUploadRequest as o, parseBrowserProxyFailure as p, hasBrowserProxyUploadWork as r, BROWSER_PROXY_ERROR_ENVELOPE as s, discardStagedBrowserProxyUpload as t, assertBrowserProxyFileBytesWithinLimits as u };