openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
204 lines (203 loc) • 6.42 kB
JavaScript
import { d as asPositiveFiniteNumber } from "./number-coercion-D6u-4YD8.mjs";
import { t as FsSafeError, w as root } from "./fs-safe-BbWvmdVn.mjs";
import { n as detectMime } from "./mime-D2wVBzpa.mjs";
import { o as readFileHandleBounded } from "./file-access-runtime-BD2Fjfbw.mjs";
import { a as createDeferred } from "./extension-shared-CJ4teJ7p.mjs";
import "./security-runtime-C-zE_Zy_.mjs";
import "./number-runtime-W4chuk8B.mjs";
import "./media-mime-8fD2xhws.mjs";
import { n as matchesFileIdentity, r as readPathBinding, t as fileIdentity } from "./path-binding-CgKQ8yCF.mjs";
import { a as resolveCanonicalReadPath, n as readAbsolutePath, r as rejectCanonicalPathChange, t as createReadErrorClassifier } from "./path-errors-Bc8by22e.mjs";
import { i as readFileFetchBinaryMaxBytes, n as FILE_FETCH_DEFAULT_MAX_BYTES, r as FILE_FETCH_HARD_MAX_BYTES, t as FILE_FETCH_CHUNK_BYTES } from "./file-fetch-protocol-BkzCnMYL.mjs";
import path from "node:path";
import crypto from "node:crypto";
//#region extensions/file-transfer/src/node-host/file-fetch.ts
const TEXT_SNIFF_MAX_BYTES = 8192;
const classifyReadError = createReadErrorClassifier({
FILE_TOO_LARGE: "FILE_TOO_LARGE",
"not-file": "IS_DIRECTORY",
ENOENT: "NOT_FOUND",
EACCES: "PERMISSION_DENIED",
EPERM: "PERMISSION_DENIED",
EISDIR: "IS_DIRECTORY"
});
function classifyFsError(e) {
return e instanceof FsSafeError && e.code === "too-large" ? "FILE_TOO_LARGE" : classifyReadError(e);
}
function isLikelyPlainText(e) {
if (e.byteLength === 0) return true;
const t = e.subarray(0, TEXT_SNIFF_MAX_BYTES);
if (t.includes(0)) return false;
try {
new TextDecoder("utf-8", { fatal: true }).decode(t);
} catch {
return false;
}
let n = 0;
for (const e of t) if (e < 32 && e !== 9 && e !== 10 && e !== 13) n += 1;
return n / t.byteLength < .01;
}
async function handleFileFetch(e, t) {
const n = readAbsolutePath(e.path);
if (typeof n !== "string") return n;
let r;
try {
r = readFileFetchBinaryMaxBytes(e);
} catch (e) {
return {
ok: false,
code: "INVALID_PARAMS",
message: String(e)
};
}
const i = r ?? Math.min(Math.floor(asPositiveFiniteNumber(e.maxBytes) ?? 8388608), 16777216);
const a = e.followSymlinks === true;
const o = e.preflightOnly === true;
const s = e.rootPath === void 0 ? void 0 : readAbsolutePath(e.rootPath);
if (s !== void 0 && typeof s !== "string") return s;
const c = await resolveCanonicalReadPath({
requestedPath: s ?? n,
followSymlinks: s === void 0 && a,
classifyError: classifyFsError,
notFoundMessage: "file not found"
});
if (typeof c !== "string") return c;
let l;
try {
if (s !== void 0) l = await (await root(c)).open(path.relative(c, n), { symlinks: a ? "follow-parents-within-root" : "reject" });
else l = await (await root(path.dirname(c))).open(path.basename(c));
} catch (e) {
const t = classifyFsError(e);
return {
ok: false,
code: t,
message: t === "IS_DIRECTORY" ? "path is a directory" : `open failed: ${String(e)}`,
canonicalPath: c
};
}
try {
const n = rejectCanonicalPathChange(e.expectedCanonicalPath, l.realPath);
if (n) return n;
const a = l.stat;
const s = await l.handle.stat({ bigint: true });
const c = fileIdentity(s);
const u = readPathBinding(e.expectedBinding);
if (e.expectedBinding !== void 0 && u?.kind !== "existing" || u?.kind === "existing" && !matchesFileIdentity(s, u)) return {
ok: false,
code: "CANONICAL_PATH_CHANGED",
message: "filesystem identity differs from the authorized target",
canonicalPath: l.realPath
};
if (a.size > i) return {
ok: false,
code: "FILE_TOO_LARGE",
message: `file size ${a.size} exceeds limit ${i}`,
canonicalPath: l.realPath
};
if (o) return {
ok: true,
path: l.realPath,
size: a.size,
mimeType: "",
base64: "",
sha256: "",
preflightOnly: true,
binding: {
kind: "existing",
...c
}
};
if (r !== void 0) {
if (!t?.frames || u?.kind !== "existing") return {
ok: false,
code: "INVALID_PARAMS",
message: "binary file.fetch requires duplex IO and an authorized filesystem binding"
};
const e = t.frames;
if (!e) throw new Error("binary file.fetch requires framed duplex IO");
t.signal.throwIfAborted();
let n = "start";
let r = createDeferred();
r.promise.catch(() => {});
const onAbort = () => r.reject(t.signal.reason);
t.signal.addEventListener("abort", onAbort, { once: true });
let a;
try {
a = e.onMessage((e) => {
if (!n || Buffer.from(e).toString("utf8") !== n) {
const e = /* @__PURE__ */ new Error("Unexpected file.fetch stream control");
r.reject(e);
throw e;
}
n = void 0;
r.resolve();
});
t.signal.throwIfAborted();
await r.promise;
const o = Buffer.allocUnsafe(FILE_FETCH_CHUNK_BYTES);
const s = crypto.createHash("sha256");
let u = 0;
while (true) {
t.signal.throwIfAborted();
const { bytesRead: a } = await l.handle.read(o, 0, Math.min(o.length, i - u + 1));
t.signal.throwIfAborted();
if (!a) return {
ok: true,
path: l.realPath,
size: u,
sha256: s.digest("hex"),
transport: "binary",
mimeType: "",
base64: "",
binding: {
kind: "existing",
...c
}
};
u += a;
if (u > i) throw Object.assign(/* @__PURE__ */ new Error("file grew beyond the authorized byte limit"), { code: "FILE_TOO_LARGE" });
const d = o.subarray(0, a);
s.update(d);
r = createDeferred();
r.promise.catch(() => {});
n = "ack";
await e.send(d);
await r.promise;
}
} finally {
a?.();
t.signal.removeEventListener("abort", onAbort);
}
}
const d = await readFileHandleBounded(l.handle, i);
const f = crypto.createHash("sha256").update(d).digest("hex");
const p = d.toString("base64");
const m = await detectMime({
buffer: d,
filePath: l.realPath
}) || (isLikelyPlainText(d) ? "text/plain" : "application/octet-stream");
return {
ok: true,
path: l.realPath,
size: d.byteLength,
mimeType: m,
base64: p,
sha256: f,
binding: {
kind: "existing",
...c
}
};
} catch (e) {
return {
ok: false,
code: classifyFsError(e),
message: `read failed: ${String(e)}`,
canonicalPath: l.realPath
};
} finally {
await l.handle.close().catch(() => void 0);
}
}
//#endregion
export { handleFileFetch };