UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

254 lines (253 loc) • 7.95 kB
import { r as truncateUtf16Safe } from "./utf16-slice-CuDyEXgS.mjs"; import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs"; import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs"; import "./abort-signal-D4Q6SEw7.mjs"; import { r as withResponseBodyTimeout } from "./http-response-body-timeout-BomM6jjh.mjs"; import { i as readResponseWithLimit } from "./http-response-body-B-i_0116.mjs"; import { n as normalizeHostname } from "./hostname-DQVb2xzD.mjs"; import { o as isBlockedHostnameOrIp } from "./ssrf-DHBNJw0c.mjs"; import { a as withStrictGuardedFetchMode, r as fetchWithSsrFGuard } from "./fetch-guard-BLMw2n18.mjs"; import { f as readImageMetadataFromHeader, h as createImageProcessor } from "./image-ops-zeupBxnN.mjs"; import { isIP } from "node:net"; import pLimit from "p-limit"; import { Parser } from "htmlparser2"; //#region src/gateway/control-ui-link-preview.ts const HTML_MAX_BYTES = 65536; const IMAGE_MAX_BYTES = 2097152; const ICON_MAX_BYTES = 65536; const IMAGE_OUTPUT_MAX_BYTES = 262144; const REQUEST_TIMEOUT_MS = 5e3; const PREVIEW_TIMEOUT_MS = 15e3; const CACHE_MAX_ENTRIES = 64; const SUCCESS_TTL_MS = 36e5; const FAILURE_TTL_MS = 3e5; const loads = pLimit(4); const processor = createImageProcessor(); const principals = /* @__PURE__ */ new WeakMap(); let nextPrincipal = 0; const cache = /* @__PURE__ */ new Map(); /** Public presentation only: never reuse browser credentials or private-network policy. */ function parseControlUiLinkPreviewUrl(e, t) { if (typeof e !== "string" || !e.trim() || e.length > 2048) return null; const n = URL.parse(e, t); if (!n || !["http:", "https:"].includes(n.protocol) || n.username || n.password || isIP(normalizeHostname(n.hostname)) || isBlockedHostnameOrIp(n.hostname)) return null; n.hash = ""; return n; } async function readPageMetadata(e, t, n) { const r = /* @__PURE__ */ new Map(); const i = []; let a; let o; let s = false; let c = false; const l = new Parser({ onopentag(e, t) { if (e === "body") { c = true; l.pause(); } else if (e === "base") a ??= t.href; else if (e === "title" && o === void 0) { o = ""; s = true; } else if (e === "meta") { const e = (t.property ?? t.name)?.toLowerCase(); const n = t.content?.trim(); if (e && n && !r.has(e)) r.set(e, n); } else if (e === "link") i.push(t); }, ontext(e) { if (s) o += e; }, onclosetag(e) { if (e === "title") s = false; else if (e === "head") { c = true; l.pause(); } } }); const u = e.body?.getReader(); if (u) try { await withResponseBodyTimeout({ signal: n, timeoutMs: REQUEST_TIMEOUT_MS, onTimeout: void 0, cancel: (e) => u.cancel(e), read: async (e) => { const t = new TextDecoder(); let n = HTML_MAX_BYTES; while (n > 0) { e?.(); const { done: r, value: i } = await u.read(); if (r) { l.end(t.decode()); return; } const a = i.subarray(0, n); n -= a.byteLength; l.write(t.decode(a, { stream: true })); if (c) return; } l.end(); } }); } finally { u.cancel().catch(() => void 0); u.releaseLock(); } const d = URL.parse(a ?? "", t)?.href ?? t; const f = r.get("og:title") ?? r.get("twitter:title") ?? o; const p = r.get("og:description") ?? r.get("twitter:description") ?? r.get("description"); const m = [ "og:image:secure_url", "og:image", "og:image:url", "twitter:image", "twitter:image:src" ].map((e) => parseControlUiLinkPreviewUrl(r.get(e), d)?.href).find(Boolean); const h = []; for (const e of i) { const t = e.rel?.toLowerCase().split(/\s+/u) ?? []; if (!t.includes("icon") && !t.includes("apple-touch-icon")) continue; const n = parseControlUiLinkPreviewUrl(e.href, d)?.href; if (n && e.type !== "image/svg+xml" && !h.includes(n)) { h.push(n); if (h.length === 2) break; } } return { title: f ? truncateUtf16Safe(f.replace(/\s+/gu, " ").trim(), 180) : void 0, description: p ? truncateUtf16Safe(p.replace(/\s+/gu, " ").trim(), 400) : void 0, image: m, icons: h }; } async function fetchPreviewResource(e, t, n, r, i) { try { const { response: a, finalUrl: o, release: s } = await fetchWithSsrFGuard(withStrictGuardedFetchMode({ url: e, maxRedirects: 3, timeoutMs: REQUEST_TIMEOUT_MS, signal: n, init: { headers: { Accept: t }, credentials: "omit" }, beforeRequest: () => { n.throwIfAborted(); if (!r()) throw new Error("Link previews disabled"); }, resolveDispatcherPolicy: (e) => { if (!parseControlUiLinkPreviewUrl(e.href)) throw new Error("Not a public preview URL"); } })); try { return a.ok ? await i(a, o) : void 0; } finally { await s(); } } catch { return; } } async function loadImage(e, t, n) { try { if (!e || e.length > (t ? ICON_MAX_BYTES : IMAGE_MAX_BYTES)) return; const { fileTypeFromBuffer: r } = await import("file-type"); const i = await r(e); if (t && i?.mime === "image/x-icon") return `data:image/x-icon;base64,${e.toString("base64")}`; if (!i || ![ "image/png", "image/apng", "image/jpeg", "image/webp", "image/gif", "image/avif" ].includes(i.mime)) return; const a = readImageMetadataFromHeader(e); if (!a || a.width <= 0 || a.height <= 0 || a.width > 16e6 / a.height) return; const o = await processor.encode(e, { format: "png", resize: { maxSide: t ? 64 : 640, fit: "inside", enlarge: false }, signal: n }); return o.data.length <= (t ? ICON_MAX_BYTES : IMAGE_OUTPUT_MAX_BYTES) ? `data:image/png;base64,${o.data.toString("base64")}` : void 0; } catch { return; } } async function loadPreview(e, t, n) { if (n.aborted || !t()) return {}; const r = await fetchPreviewResource(e.href, "text/html,application/xhtml+xml", n, t, async (e, t) => { const r = e.headers.get("content-type")?.split(";", 1)[0]?.trim().toLowerCase(); if (r !== "text/html" && r !== "application/xhtml+xml") return; return { ...await readPageMetadata(e, t, n), finalUrl: t }; }); const i = /* @__PURE__ */ new Set([...r?.icons ?? [], new URL("/favicon.ico", r?.finalUrl ?? e.href).href]); const a = /* @__PURE__ */ new Map(); const imageBytes = (e) => { let i = a.get(e); if (!i) { i = fetchPreviewResource(e, "image/*", n, t, (t) => readResponseWithLimit(t, e === r?.image ? IMAGE_MAX_BYTES : ICON_MAX_BYTES, { signal: n, chunkTimeoutMs: REQUEST_TIMEOUT_MS })); a.set(e, i); } return i; }; const [o, s] = await Promise.all([r?.image ? imageBytes(r.image).then((e) => loadImage(e, false, n)) : void 0, (async () => { for (const e of i) { const t = await loadImage(await imageBytes(e), true, n); if (t) return t; } })()]); return t() ? { ...r?.title ? { title: r.title } : {}, ...r?.description ? { description: r.description } : {}, ...o ? { imageDataUrl: o } : {}, ...s ? { faviconDataUrl: s } : {} } : {}; } /** Anonymous requests, isolated to the requesting principal and owner revision. */ async function loadControlUiLinkPreview(e, t, n) { if (!t()) return {}; let r = principals.get(n.principal); if (r === void 0) { r = ++nextPrincipal; principals.set(n.principal, r); } const i = JSON.stringify([ r, n.revision, e.href ]); const a = Date.now(); const o = cache.get(i); if (o && o.expiresAt > a) { const e = await o.promise; return t() ? e : {}; } if (loads.activeCount + loads.pendingCount >= 32) return {}; const s = AbortSignal.timeout(PREVIEW_TIMEOUT_MS); const c = { expiresAt: Number.POSITIVE_INFINITY, promise: racePromiseWithAbortSignal(loads(() => loadPreview(e, t, s)), s).catch(() => ({})) }; cache.delete(i); cache.set(i, c); pruneMapToMaxSize(cache, CACHE_MAX_ENTRIES); const l = await c.promise; c.expiresAt = Date.now() + (Object.keys(l).length ? SUCCESS_TTL_MS : FAILURE_TTL_MS); return t() ? l : {}; } //#endregion export { loadControlUiLinkPreview, parseControlUiLinkPreviewUrl };