UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

315 lines (314 loc) • 11.9 kB
import { g as readStringValue } from "./string-coerce-CCIiB4H7.mjs"; import { s as asFiniteNumber } from "./number-coercion-D6u-4YD8.mjs"; import { t as asBoolean } from "./boolean-2vRuVafy.mjs"; import { o as asRecord } from "./record-coerce-CVPuDqcc.mjs"; import { p as toErrorObject } from "./error-coercion-hDrHOSGy.mjs"; import "./errors-BKzCeTYb.mjs"; import { n as resolvePreferredOpenClawTmpDir } from "./tmp-openclaw-dir-Bf0oU1Cn.mjs"; import { n as estimateBase64DecodedBytes, t as canonicalizeBase64 } from "./base64-CnKpkbff.mjs"; import { n as extnameFromAnyPath } from "./file-name-PRG-HeBL.mjs"; import "./http-body-B9w7rzPz.mjs"; import { t as cancelUnreadResponseBody } from "./http-response-body-B-i_0116.mjs"; import { n as normalizeHostname } from "./hostname-DQVb2xzD.mjs"; import { r as fetchWithSsrFGuard } from "./fetch-guard-BLMw2n18.mjs"; import { t as publishOutputFileAtomically } from "./output-file.runtime.js"; import { t as CLI_NAME } from "./cli-name-Dp_huZBR.mjs"; import { t as parseMediaContentLength } from "./content-length-CEI2r5C4.mjs"; import fs from "node:fs"; import * as path$1 from "node:path"; import { randomUUID } from "node:crypto"; import * as fs$2 from "node:fs/promises"; //#region src/cli/nodes-media-utils.ts function normalizeMediaExtension(e) { const t = (e.startsWith(".") ? e.slice(1) : e).toLowerCase(); if (!/^[a-z0-9][a-z0-9_-]{0,15}$/u.test(t)) return; return t === "jpeg" ? ".jpg" : `.${t}`; } /** * True when `filePath` does not contradict media encoded as `format`. * * Callers choose an output path before the node reports how it encoded the * media, so the name can end up describing bytes it never received. Everything * that dispatches on extension — viewers, uploads, content-type headers, * channel attachment handling — is misled when that happens. A path with no * extension claims nothing and is therefore accepted. * * This only compares; it never rewrites the path. Output paths reach the media * writers already workspace-guarded, and that guard alias-checks the exact * final segment, so swapping the extension afterwards would write to a name * nothing validated. */ function mediaPathMatchesFormat(e, t) { const n = extnameFromAnyPath(e); if (!n) return true; const r = normalizeMediaExtension(t); return !r || normalizeMediaExtension(n) === r; } function resolveTempPathParts(e) { const t = e.tmpDir ?? resolvePreferredOpenClawTmpDir(); const n = e.ext.startsWith(".") ? e.ext : `.${e.ext}`; if (!/^\.[A-Za-z0-9][A-Za-z0-9_-]{0,15}$/u.test(n)) throw new Error("invalid media format"); if (!e.tmpDir) fs.mkdirSync(t, { recursive: true, mode: 448 }); return { tmpDir: t, id: e.id ?? randomUUID(), ext: n }; } //#endregion //#region src/cli/nodes-camera.ts const MAX_CAMERA_URL_DOWNLOAD_BYTES = 262144e3; const MAX_CAMERA_BASE64_BYTES = MAX_CAMERA_URL_DOWNLOAD_BYTES; const CAMERA_URL_DOWNLOAD_TIMEOUT_MS = 9e5; /** Resolve snap requests without inventing a facing when the CLI or node cannot select one. */ function resolveCameraSnapTargets(e) { if (e.platform?.toLowerCase() === "linux") return [{ artifactFacing: "unknown" }]; if (!e.facing) return [{ artifactFacing: "unknown" }]; const t = e.facing === "both" ? ["front", "back"] : [e.facing]; if (e.deviceId && t.length > 1) throw new Error("facing=both is not allowed when deviceId is set"); return t.map((e) => ({ requestFacing: e, artifactFacing: e })); } /** Keep Linux clip requests and artifact labels honest when V4L2 position is unknown. */ function resolveCameraClipTarget(e) { return e.platform?.toLowerCase() === "linux" ? { artifactFacing: "unknown" } : { requestFacing: e.facing, artifactFacing: e.facing }; } /** Validate a complete still-image payload before any capture can be published. */ function parseCameraSnapPayload(e, t = {}) { const n = asRecord(e); const r = readStringValue(n.format); const i = readStringValue(n.base64); const a = readStringValue(n.url); const o = asFiniteNumber(n.width); const s = asFiniteNumber(n.height); if (!r || !i && !a || o === void 0 || s === void 0) throw new Error("invalid camera.snap payload"); if (a) validateCameraPayloadUrl(a, requireNodeRemoteIp(t.expectedHost)); if (i) validateCameraPayloadBase64(i); return { format: r, ...i ? { base64: i } : {}, ...a ? { url: a } : {}, width: o, height: s }; } function parseCameraClipPayload(e) { const t = asRecord(e); const n = readStringValue(t.format); const r = readStringValue(t.base64); const i = readStringValue(t.url); const a = asFiniteNumber(t.durationMs); const o = asBoolean(t.hasAudio); if (!n || !r && !i || a === void 0 || o === void 0) throw new Error("invalid camera.clip payload"); return { format: n, ...r ? { base64: r } : {}, ...i ? { url: i } : {}, durationMs: a, hasAudio: o }; } function cameraTempPath(e) { const { tmpDir: t, id: n, ext: r } = resolveTempPathParts(e); const i = e.facing ? `-${e.facing}` : ""; return path$1.join(t, `${CLI_NAME}-camera-${e.kind}${i}-${n}${r}`); } /** * Own generated batch paths until the complete result is published. * * A fresh directory proves these destinations were not preexisting files. * Rollback names only the batch's paths; never sweep other directory entries. */ async function withCameraArtifactBatch(e, t) { const n = e[0]; if (n === void 0) return await t([]); const r = await fs$2.mkdtemp(path$1.join(path$1.dirname(n), ".openclaw-camera-batch-")); const i = e.map((e) => path$1.join(r, path$1.basename(e))); try { return await t(i); } catch (e) { await Promise.allSettled(i.map((e) => fs$2.rm(e, { force: true }))); await fs$2.rmdir(r).catch(() => {}); throw e; } } function validateCameraPayloadUrl(e, t) { const n = new URL(e); if (n.protocol !== "https:") throw new Error(`writeUrlToFile: only https URLs are allowed, got ${n.protocol}`); const r = normalizeHostname(t); if (!r) throw new Error("writeUrlToFile: expectedHost is required"); if (normalizeHostname(n.hostname) !== r) throw new Error(`writeUrlToFile: url host ${n.hostname} must match node host ${t}`); return r; } /** Download a node-hosted media URL to disk after HTTPS, host, redirect, and size checks. */ async function writeUrlToFile(e, t, n) { const r = validateCameraPayloadUrl(t, n.expectedHost); const i = { allowPrivateNetwork: true, allowedHostnames: [r], hostnameAllowlist: [r] }; let release = async () => {}; let a = 0; try { const o = await fetchWithSsrFGuard({ url: t, auditContext: "writeUrlToFile", policy: i, requireHttps: true, timeoutMs: CAMERA_URL_DOWNLOAD_TIMEOUT_MS }); release = o.release; const s = o.response; const c = new URL(o.finalUrl); if (normalizeHostname(c.hostname) !== r) { await cancelUnreadResponseBody(s); throw new Error(`writeUrlToFile: redirect host ${c.hostname} must match node host ${n.expectedHost}`); } if (!s.ok) { await cancelUnreadResponseBody(s); throw new Error(`failed to download ${t}: ${s.status} ${s.statusText}`); } let l; try { l = parseMediaContentLength(s.headers.get("content-length")); } catch (e) { await cancelUnreadResponseBody(s); throw e; } if (l !== null && l > MAX_CAMERA_URL_DOWNLOAD_BYTES) { await cancelUnreadResponseBody(s); throw new Error(`writeUrlToFile: content-length ${l} exceeds max ${MAX_CAMERA_URL_DOWNLOAD_BYTES}`); } const u = s.body; if (!u) { await cancelUnreadResponseBody(s); throw new Error(`failed to download ${t}: empty response body`); } await publishOutputFileAtomically({ filePath: e, writeTemp: async (e) => { const n = await fs$2.open(e, "wx"); const r = u.getReader(); try { while (true) { const { done: e, value: t } = await r.read(); if (e) break; a += t.byteLength; if (a > MAX_CAMERA_URL_DOWNLOAD_BYTES) { await r.cancel().catch(() => void 0); throw new Error(`writeUrlToFile: downloaded ${a} bytes, exceeds max ${MAX_CAMERA_URL_DOWNLOAD_BYTES}`); } await n.writeFile(t); } } catch (e) { await r.cancel().catch(() => void 0); throw toErrorObject(e, "Non-Error thrown"); } finally { r.releaseLock(); await n.close(); } if (a === 0) throw new Error(`writeUrlToFile: empty download from ${t}`); } }); } finally { await release(); } } function validateCameraPayloadBase64(e) { if (estimateBase64DecodedBytes(e) > MAX_CAMERA_BASE64_BYTES) throw new Error(`writeBase64ToFile: decoded payload exceeds max ${MAX_CAMERA_BASE64_BYTES}`); const t = canonicalizeBase64(e); if (!t) throw new Error("writeBase64ToFile: invalid base64 payload"); return t; } /** Decode a base64 media payload to disk with preflight and post-decode size checks. */ async function writeBase64ToFile(e, t) { const n = validateCameraPayloadBase64(t); const r = Buffer.from(n, "base64"); if (r.length > MAX_CAMERA_BASE64_BYTES) throw new Error(`writeBase64ToFile: decoded ${r.length} bytes, exceeds max ${MAX_CAMERA_BASE64_BYTES}`); await fs$2.stat(path$1.dirname(e)); await publishOutputFileAtomically({ filePath: e, writeTemp: async (e) => { await fs$2.writeFile(e, r, { flag: "wx" }); } }); return { path: e }; } function requireNodeRemoteIp(e) { const t = e?.trim(); if (!t) throw new Error("camera URL payload requires node remoteIp"); return t; } async function writeCameraPayloadToFile(e) { if (e.payload.url) { await writeUrlToFile(e.filePath, e.payload.url, { expectedHost: requireNodeRemoteIp(e.expectedHost) }); return; } if (e.payload.base64) { await writeBase64ToFile(e.filePath, e.payload.base64); return; } throw new Error(e.invalidPayloadMessage ?? "invalid camera payload"); } async function writeCameraClipPayloadToFile(e) { const t = cameraTempPath({ kind: "clip", facing: e.facing, ext: e.payload.format }); await writeCameraPayloadToFile({ filePath: t, payload: e.payload, expectedHost: e.expectedHost, invalidPayloadMessage: "invalid camera.clip payload" }); return t; } //#endregion //#region src/cli/nodes-screen.ts function parseScreenRecordPayload(e) { const t = asRecord(e); const n = readStringValue(t.format); const r = readStringValue(t.base64); if (!n || !r) throw new Error("invalid screen.record payload"); return { format: n, base64: r, durationMs: typeof t.durationMs === "number" ? t.durationMs : void 0, fps: typeof t.fps === "number" ? t.fps : void 0, screenIndex: typeof t.screenIndex === "number" ? t.screenIndex : void 0, hasAudio: typeof t.hasAudio === "boolean" ? t.hasAudio : void 0 }; } function screenRecordTempPath(e) { const { tmpDir: t, id: n, ext: r } = resolveTempPathParts(e); return path$1.join(t, `openclaw-screen-record-${n}${r}`); } /** * Maps a caller-chosen snapshot path to the encoding the node should produce. * * `screen.snapshot` lets the node pick its encoding, so asking for the one the * filename already promises is what keeps the name and the bytes in agreement. * Returns undefined when the path claims nothing recognizable and the node's * own default should stand. */ function screenSnapshotFormatForPath(e) { const t = extnameFromAnyPath(e).toLowerCase(); if (t === ".png") return "png"; return t === ".jpg" || t === ".jpeg" ? "jpeg" : void 0; } function screenSnapshotTempPath(e) { const { tmpDir: t, id: n, ext: r } = resolveTempPathParts(e); return path$1.join(t, `openclaw-screen-snapshot-${n}${r}`); } //#endregion export { cameraTempPath as a, resolveCameraClipTarget as c, writeBase64ToFile as d, writeCameraClipPayloadToFile as f, screenSnapshotTempPath as i, resolveCameraSnapTargets as l, mediaPathMatchesFormat as m, screenRecordTempPath as n, parseCameraClipPayload as o, writeCameraPayloadToFile as p, screenSnapshotFormatForPath as r, parseCameraSnapPayload as s, parseScreenRecordPayload as t, withCameraArtifactBatch as u };