UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

383 lines (382 loc) • 14.4 kB
import { o as __toESM } from "./chunk-DORXReHP.js"; import { a as hasConfiguredSecretInput, c as normalizeResolvedSecretInputString, l as normalizeSecretInputString } from "./types.secrets-DgX397vI.js"; import { c as isPrivateIpAddress } from "./ssrf-0bPJMoZR.js"; import { i as normalizeHostnameSuffixAllowlist, n as buildHostnameAllowlistPolicyFromSuffixAllowlist, r as isHttpsUrlAllowedByHostnameSuffixAllowlist } from "./ssrf-policy-DYINyIKC.js"; import { lookup } from "node:dns/promises"; //#region extensions/msteams/src/attachments/shared.ts const IMAGE_EXT_RE = /\.(avif|bmp|gif|heic|heif|jpe?g|png|tiff?|webp)$/i; const IMG_SRC_RE = /<img[^>]+src=["']([^"']+)["'][^>]*>/gi; const ATTACHMENT_TAG_RE = /<attachment[^>]+id=["']([^"']+)["'][^>]*>/gi; const DEFAULT_MEDIA_HOST_ALLOWLIST = [ "graph.microsoft.com", "graph.microsoft.us", "graph.microsoft.de", "graph.microsoft.cn", "sharepoint.com", "sharepoint.us", "sharepoint.de", "sharepoint.cn", "sharepoint-df.com", "1drv.ms", "onedrive.com", "teams.microsoft.com", "teams.cdn.office.net", "statics.teams.cdn.office.net", "office.com", "office.net", "asm.skype.com", "ams.skype.com", "media.ams.skype.com", "trafficmanager.net", "blob.core.windows.net", "azureedge.net", "microsoft.com" ]; const DEFAULT_MEDIA_AUTH_HOST_ALLOWLIST = [ "api.botframework.com", "botframework.com", "graph.microsoft.com", "graph.microsoft.us", "graph.microsoft.de", "graph.microsoft.cn" ]; const GRAPH_ROOT = "https://graph.microsoft.com/v1.0"; function isRecord(value) { return Boolean(value) && typeof value === "object" && !Array.isArray(value); } function resolveRequestUrl(input) { if (typeof input === "string") return input; if (input instanceof URL) return input.toString(); if (typeof input === "object" && input && "url" in input && typeof input.url === "string") return input.url; return String(input); } function normalizeContentType(value) { if (typeof value !== "string") return; const trimmed = value.trim(); return trimmed ? trimmed : void 0; } function inferPlaceholder(params) { const mime = params.contentType?.toLowerCase() ?? ""; const name = params.fileName?.toLowerCase() ?? ""; const fileType = params.fileType?.toLowerCase() ?? ""; return mime.startsWith("image/") || IMAGE_EXT_RE.test(name) || IMAGE_EXT_RE.test(`x.${fileType}`) ? "<media:image>" : "<media:document>"; } function isLikelyImageAttachment(att) { const contentType = normalizeContentType(att.contentType) ?? ""; const name = typeof att.name === "string" ? att.name : ""; if (contentType.startsWith("image/")) return true; if (IMAGE_EXT_RE.test(name)) return true; if (contentType === "application/vnd.microsoft.teams.file.download.info" && isRecord(att.content)) { const fileType = typeof att.content.fileType === "string" ? att.content.fileType : ""; if (fileType && IMAGE_EXT_RE.test(`x.${fileType}`)) return true; const fileName = typeof att.content.fileName === "string" ? att.content.fileName : ""; if (fileName && IMAGE_EXT_RE.test(fileName)) return true; } return false; } /** * Returns true if the attachment can be downloaded (any file type). * Used when downloading all files, not just images. */ function isDownloadableAttachment(att) { if ((normalizeContentType(att.contentType) ?? "") === "application/vnd.microsoft.teams.file.download.info" && isRecord(att.content) && typeof att.content.downloadUrl === "string") return true; if (typeof att.contentUrl === "string" && att.contentUrl.trim()) return true; return false; } function isHtmlAttachment(att) { return (normalizeContentType(att.contentType) ?? "").startsWith("text/html"); } function extractHtmlFromAttachment(att) { if (!isHtmlAttachment(att)) return; if (typeof att.content === "string") return att.content; if (!isRecord(att.content)) return; return typeof att.content.text === "string" ? att.content.text : typeof att.content.body === "string" ? att.content.body : typeof att.content.content === "string" ? att.content.content : void 0; } function decodeDataImage(src) { const match = /^data:(image\/[a-z0-9.+-]+)?(;base64)?,(.*)$/i.exec(src); if (!match) return null; const contentType = match[1]?.toLowerCase(); if (!Boolean(match[2])) return null; const payload = match[3] ?? ""; if (!payload) return null; try { return { kind: "data", data: Buffer.from(payload, "base64"), contentType, placeholder: "<media:image>" }; } catch { return null; } } function fileHintFromUrl(src) { try { return new URL(src).pathname.split("/").pop() || void 0; } catch { return; } } function extractInlineImageCandidates(attachments) { const out = []; for (const att of attachments) { const html = extractHtmlFromAttachment(att); if (!html) continue; IMG_SRC_RE.lastIndex = 0; let match = IMG_SRC_RE.exec(html); while (match) { const src = match[1]?.trim(); if (src && !src.startsWith("cid:")) if (src.startsWith("data:")) { const decoded = decodeDataImage(src); if (decoded) out.push(decoded); } else out.push({ kind: "url", url: src, fileHint: fileHintFromUrl(src), placeholder: "<media:image>" }); match = IMG_SRC_RE.exec(html); } } return out; } function safeHostForUrl(url) { try { return new URL(url).hostname.toLowerCase(); } catch { return "invalid-url"; } } function resolveAllowedHosts(input) { return normalizeHostnameSuffixAllowlist(input, DEFAULT_MEDIA_HOST_ALLOWLIST); } function resolveAuthAllowedHosts(input) { return normalizeHostnameSuffixAllowlist(input, DEFAULT_MEDIA_AUTH_HOST_ALLOWLIST); } function resolveAttachmentFetchPolicy(params) { return { allowHosts: resolveAllowedHosts(params?.allowHosts), authAllowHosts: resolveAuthAllowedHosts(params?.authAllowHosts) }; } function isUrlAllowed(url, allowlist) { return isHttpsUrlAllowedByHostnameSuffixAllowlist(url, allowlist); } function applyAuthorizationHeaderForUrl(params) { if (!params.bearerToken) { params.headers.delete("Authorization"); return; } if (isUrlAllowed(params.url, params.authAllowHosts)) { params.headers.set("Authorization", `Bearer ${params.bearerToken}`); return; } params.headers.delete("Authorization"); } function resolveMediaSsrfPolicy(allowHosts) { return buildHostnameAllowlistPolicyFromSuffixAllowlist(allowHosts); } /** * Returns true if the given IPv4 or IPv6 address is in a private, loopback, * or link-local range that must never be reached from media downloads. * * Delegates to the SDK's `isPrivateIpAddress` which handles IPv4-mapped IPv6, * expanded notation, NAT64, 6to4, Teredo, octal IPv4, and fails closed on * parse errors. */ const isPrivateOrReservedIP = isPrivateIpAddress; /** * Resolve a hostname via DNS and reject private/reserved IPs. * Throws if the resolved IP is private or resolution fails. */ async function resolveAndValidateIP(hostname, resolveFn) { const resolve = resolveFn ?? lookup; let resolved; try { resolved = await resolve(hostname); } catch { throw new Error(`DNS resolution failed for "${hostname}"`); } if (isPrivateOrReservedIP(resolved.address)) throw new Error(`Hostname "${hostname}" resolves to private/reserved IP (${resolved.address})`); return resolved.address; } /** Maximum number of redirects to follow in safeFetch. */ const MAX_SAFE_REDIRECTS = 5; /** * Fetch a URL with redirect: "manual", validating each redirect target * against the hostname allowlist and optional DNS-resolved IP (anti-SSRF). * * This prevents: * - Auto-following redirects to non-allowlisted hosts * - DNS rebinding attacks when a lookup function is provided */ async function safeFetch(params) { const fetchFn = params.fetchFn ?? fetch; const resolveFn = params.resolveFn; const hasDispatcher = Boolean(params.requestInit && typeof params.requestInit === "object" && "dispatcher" in params.requestInit); const currentHeaders = new Headers(params.requestInit?.headers); let currentUrl = params.url; if (!isUrlAllowed(currentUrl, params.allowHosts)) throw new Error(`Initial download URL blocked: ${currentUrl}`); if (resolveFn) try { const initialHost = new URL(currentUrl).hostname; await resolveAndValidateIP(initialHost, resolveFn); } catch { throw new Error(`Initial download URL blocked: ${currentUrl}`); } for (let i = 0; i <= MAX_SAFE_REDIRECTS; i++) { const res = await fetchFn(currentUrl, { ...params.requestInit, headers: currentHeaders, redirect: "manual" }); if (![ 301, 302, 303, 307, 308 ].includes(res.status)) return res; const location = res.headers.get("location"); if (!location) return res; let redirectUrl; try { redirectUrl = new URL(location, currentUrl).toString(); } catch { throw new Error(`Invalid redirect URL: ${location}`); } if (!isUrlAllowed(redirectUrl, params.allowHosts)) throw new Error(`Media redirect target blocked by allowlist: ${redirectUrl}`); if (currentHeaders.has("authorization") && params.authorizationAllowHosts && !isUrlAllowed(redirectUrl, params.authorizationAllowHosts)) currentHeaders.delete("authorization"); if (hasDispatcher) return res; if (resolveFn) { const redirectHost = new URL(redirectUrl).hostname; await resolveAndValidateIP(redirectHost, resolveFn); } currentUrl = redirectUrl; } throw new Error(`Too many redirects (>${MAX_SAFE_REDIRECTS})`); } async function safeFetchWithPolicy(params) { return await safeFetch({ url: params.url, allowHosts: params.policy.allowHosts, authorizationAllowHosts: params.policy.authAllowHosts, fetchFn: params.fetchFn, requestInit: params.requestInit, resolveFn: params.resolveFn }); } //#endregion //#region extensions/msteams/src/sdk.ts async function loadMSTeamsSdk() { return await import("./src-CfmuZgBM.js").then((m) => /* @__PURE__ */ __toESM(m.default, 1)); } function buildMSTeamsAuthConfig(creds, sdk) { return sdk.getAuthConfigWithDefaults({ clientId: creds.appId, clientSecret: creds.appPassword, tenantId: creds.tenantId }); } function createMSTeamsAdapter(authConfig, sdk) { return new sdk.CloudAdapter(authConfig); } async function loadMSTeamsSdkWithAuth(creds) { const sdk = await loadMSTeamsSdk(); return { sdk, authConfig: buildMSTeamsAuthConfig(creds, sdk) }; } //#endregion //#region extensions/msteams/src/token-response.ts function readAccessToken(value) { if (typeof value === "string") return value; if (value && typeof value === "object") { const token = value.accessToken ?? value.token; return typeof token === "string" ? token : null; } return null; } //#endregion //#region extensions/msteams/src/token.ts function hasConfiguredMSTeamsCredentials(cfg) { return Boolean(normalizeSecretInputString(cfg?.appId) && hasConfiguredSecretInput(cfg?.appPassword) && normalizeSecretInputString(cfg?.tenantId)); } function resolveMSTeamsCredentials(cfg) { const appId = normalizeSecretInputString(cfg?.appId) || normalizeSecretInputString(process.env.MSTEAMS_APP_ID); const appPassword = normalizeResolvedSecretInputString({ value: cfg?.appPassword, path: "channels.msteams.appPassword" }) || normalizeSecretInputString(process.env.MSTEAMS_APP_PASSWORD); const tenantId = normalizeSecretInputString(cfg?.tenantId) || normalizeSecretInputString(process.env.MSTEAMS_TENANT_ID); if (!appId || !appPassword || !tenantId) return; return { appId, appPassword, tenantId }; } //#endregion //#region extensions/msteams/src/graph.ts function normalizeQuery(value) { return value?.trim() ?? ""; } function escapeOData(value) { return value.replace(/'/g, "''"); } async function fetchGraphJson(params) { const res = await fetch(`${GRAPH_ROOT}${params.path}`, { headers: { Authorization: `Bearer ${params.token}`, ...params.headers } }); if (!res.ok) { const text = await res.text().catch(() => ""); throw new Error(`Graph ${params.path} failed (${res.status}): ${text || "unknown error"}`); } return await res.json(); } async function resolveGraphToken(cfg) { const creds = resolveMSTeamsCredentials(cfg?.channels?.msteams); if (!creds) throw new Error("MS Teams credentials missing"); const { sdk, authConfig } = await loadMSTeamsSdkWithAuth(creds); const accessToken = readAccessToken(await new sdk.MsalTokenProvider(authConfig).getAccessToken("https://graph.microsoft.com")); if (!accessToken) throw new Error("MS Teams graph token unavailable"); return accessToken; } async function listTeamsByName(token, query) { const filter = `resourceProvisioningOptions/Any(x:x eq 'Team') and startsWith(displayName,'${escapeOData(query)}')`; return (await fetchGraphJson({ token, path: `/groups?$filter=${encodeURIComponent(filter)}&$select=id,displayName` })).value ?? []; } async function listChannelsForTeam(token, teamId) { return (await fetchGraphJson({ token, path: `/teams/${encodeURIComponent(teamId)}/channels?$select=id,displayName` })).value ?? []; } //#endregion //#region extensions/msteams/src/graph-users.ts async function searchGraphUsers(params) { const query = params.query.trim(); if (!query) return []; if (query.includes("@")) { const escaped = escapeOData(query); const filter = `(mail eq '${escaped}' or userPrincipalName eq '${escaped}')`; const path = `/users?$filter=${encodeURIComponent(filter)}&$select=id,displayName,mail,userPrincipalName`; return (await fetchGraphJson({ token: params.token, path })).value ?? []; } const top = typeof params.top === "number" && params.top > 0 ? params.top : 10; const path = `/users?$search=${encodeURIComponent(`"displayName:${query}"`)}&$select=id,displayName,mail,userPrincipalName&$top=${top}`; return (await fetchGraphJson({ token: params.token, path, headers: { ConsistencyLevel: "eventual" } })).value ?? []; } //#endregion export { resolveAttachmentFetchPolicy as C, safeHostForUrl as D, safeFetchWithPolicy as E, normalizeContentType as S, resolveRequestUrl as T, inferPlaceholder as _, resolveGraphToken as a, isRecord as b, readAccessToken as c, ATTACHMENT_TAG_RE as d, GRAPH_ROOT as f, extractInlineImageCandidates as g, extractHtmlFromAttachment as h, normalizeQuery as i, createMSTeamsAdapter as l, applyAuthorizationHeaderForUrl as m, listChannelsForTeam as n, hasConfiguredMSTeamsCredentials as o, IMG_SRC_RE as p, listTeamsByName as r, resolveMSTeamsCredentials as s, searchGraphUsers as t, loadMSTeamsSdkWithAuth as u, isDownloadableAttachment as v, resolveMediaSsrfPolicy as w, isUrlAllowed as x, isLikelyImageAttachment as y };