UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

547 lines (546 loc) • 22.4 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { s as asFiniteNumber } from "./number-coercion-D6u-4YD8.mjs"; import { a as asOptionalRecord } from "./record-coerce-CVPuDqcc.mjs"; import { c as visibleWidth, i as stripAnsi } from "./ansi-CZa2t0Hf.mjs"; import { n as sanitizeTerminalText, r as terminalText } from "./safe-text-C80HAQ2e.mjs"; import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs"; import { t as normalizeClawHubSha256Hex } from "./clawhub-integrity-DTNmm7ZL.mjs"; import { r as theme } from "./theme-BOI0xyRZ.mjs"; import { v as resolveClawHubBaseUrl } from "./clawhub-client-BLg-dsn2.mjs"; import { r as fetchClawHubPackageSecurity } from "./clawhub-packages-BkEmBO-h.mjs"; import { c as fetchClawHubSkillSecurityVerdicts, l as fetchClawHubSkillVerification } from "./clawhub-skills-C1KFinHC.mjs"; import pLimit from "p-limit"; //#region src/infra/clawhub-display.ts function encodeClawHubPackagePath(e) { return e.split("/").map((e) => encodeURIComponent(e).replaceAll("%40", "@")).join("/"); } function formatClawHubReleaseLabel(e, t) { return `${sanitizeTerminalText(e)}@${sanitizeTerminalText(t)}`; } //#endregion //#region src/infra/clawhub-skill-security.ts const MAX_SECURITY_VERDICT_BATCH_SIZE = 100; const OWNER_QUALIFIED_FALLBACK_CONCURRENCY = 6; const NON_SECURITY_VERIFY_REASONS = /* @__PURE__ */ new Set(["card.missing", "card_missing"]); function normalizeOwnerHandle(e) { return normalizeOptionalString(e)?.replace(/^@+/, "").toLowerCase() || void 0; } function normalizeTarget(e) { const t = e.slug.trim(); const n = normalizeOwnerHandle(e.ownerHandle); const r = e.version.trim(); return { slug: t, ...n ? { ownerHandle: n } : {}, version: r }; } function normalizeSlug(e) { return e.trim().toLowerCase(); } function targetKey(e) { return `${e.ownerHandle ?? ""}\0${normalizeSlug(e.slug)}\0${e.version}`; } function legacyTargetKey(e) { return `${normalizeSlug(e.slug)}\0${e.version}`; } function partitionCompatibleBatches(e) { const t = []; for (const n of e) { const e = legacyTargetKey(n); let r = t.find((t) => t.items.length < MAX_SECURITY_VERDICT_BATCH_SIZE && !t.legacyKeys.has(e)); if (!r) { r = { items: [], legacyKeys: /* @__PURE__ */ new Set() }; t.push(r); } r.items.push(n); r.legacyKeys.add(e); } return t.map((e) => e.items); } function normalizeReason(e) { return normalizeOptionalString(e)?.toLowerCase() ?? ""; } function hasOnlyNonSecurityVerifyReasons(e) { return e.length > 0 && e.every((e) => NON_SECURITY_VERIFY_REASONS.has(normalizeReason(e))); } function mapVerificationSecurity(e, t) { const n = asOptionalRecord(e.security); if (!n || Object.hasOwn(n, "passed")) return e.security; const r = normalizeOptionalString(n.status) ?? normalizeOptionalString(n.rawStatus); const i = e.ok && normalizeReason(e.decision) === "pass"; if (!r || !i && !t) return e.security; return { ...n, passed: true }; } function identityFailure(e, t) { return { ok: false, decision: "fail", reasons: ["security.identity_mismatch"], requestedSlug: e.slug, ...e.ownerHandle ? { requestedOwnerHandle: e.ownerHandle } : {}, requestedVersion: e.version, slug: null, version: null, publisherHandle: null, security: null, error: { code: "identity_mismatch", message: t } }; } function validateVerdictIdentity(e, t) { const n = normalizeOptionalString(t.requestedSlug)?.toLowerCase(); if (n !== normalizeSlug(e.slug)) return identityFailure(e, `ClawHub returned requested slug ${n ?? "unknown"}.`); if (normalizeOptionalString(t.requestedVersion) !== e.version) return identityFailure(e, "ClawHub returned a different requested version."); const r = normalizeOwnerHandle(t.requestedOwnerHandle); if (r && r !== e.ownerHandle) return identityFailure(e, `ClawHub returned requested owner ${r}.`); const i = normalizeOptionalString(t.slug)?.toLowerCase(); if (i && i !== normalizeSlug(e.slug)) return identityFailure(e, `ClawHub resolved skill ${i}.`); const a = normalizeOptionalString(t.version); if (a && a !== e.version) return identityFailure(e, `ClawHub resolved version ${a}.`); if (t.ok && a !== e.version) return identityFailure(e, "ClawHub did not return the exact requested version."); const o = normalizeOwnerHandle(t.publisherHandle); if (e.ownerHandle && t.version !== null && o !== e.ownerHandle) return identityFailure(e, `ClawHub resolved publisher ${o ?? "unknown"}.`); return t; } function correlateBatchItems(e, t) { if (t.length !== e.length) throw new Error(`ClawHub skill security verdict request returned ${t.length} verdicts for ${e.length} targets.`); const n = new Map(e.map((e) => [targetKey(e), e])); const r = new Map(e.map((e) => [legacyTargetKey(e), e])); const i = /* @__PURE__ */ new Map(); for (const e of t) { const t = normalizeOptionalString(e.requestedSlug)?.toLowerCase(); const a = normalizeOptionalString(e.requestedVersion); const o = normalizeOwnerHandle(e.requestedOwnerHandle); if (!t || !a) throw new Error("ClawHub skill security verdict response omitted request identity."); const s = o ? n.get(targetKey({ slug: t, ownerHandle: o, version: a })) : r.get(legacyTargetKey({ slug: t, version: a })); if (!s || i.has(targetKey(s))) throw new Error("ClawHub skill security verdict response could not be correlated safely."); i.set(targetKey(s), e); } return i; } async function fetchExactClawHubSkillSecurityVerdicts(e) { const t = e.items.map(normalizeTarget); const n = { baseUrl: e.baseUrl, token: e.token, ...e.skipAuth !== void 0 ? { skipAuth: e.skipAuth } : {}, timeoutMs: e.timeoutMs }; const r = /* @__PURE__ */ new Set(); for (const e of t) { const t = targetKey(e); if (r.has(t)) throw new Error("ClawHub skill security verdict request contains duplicate targets."); r.add(t); } const i = /* @__PURE__ */ new Map(); for (const e of partitionCompatibleBatches(t)) { const t = correlateBatchItems(e, (await fetchClawHubSkillSecurityVerdicts({ ...n, items: e })).items); const r = pLimit(OWNER_QUALIFIED_FALLBACK_CONCURRENCY); const a = await Promise.all(e.map(async (e) => { const i = targetKey(e); const a = t.get(i); if (!a) throw new Error("ClawHub skill security verdict response omitted a target."); const o = e.ownerHandle; return [i, validateVerdictIdentity(e, o && a.error?.code === "skill_not_found" ? await r(async () => { const t = await fetchClawHubSkillVerification({ ...n, slug: e.slug, ownerHandle: o, version: e.version }); const r = asOptionalRecord(t.skill); const i = asOptionalRecord(t.publisher); const a = asOptionalRecord(t.version); const s = asOptionalRecord(t.security); const c = normalizeOptionalString(t.pageUrl); const l = t.reasons.map((e) => normalizeOptionalString(e)).filter((e) => Boolean(e)); const u = normalizeReason(normalizeOptionalString(s?.status) ?? normalizeOptionalString(s?.rawStatus)); const d = !t.ok && u === "clean" && hasOnlyNonSecurityVerifyReasons(l); const f = normalizeOptionalString(t.version) ?? normalizeOptionalString(a?.version); return { ok: d ? true : t.ok, decision: d ? "pass" : t.decision, reasons: d ? [] : l, requestedSlug: e.slug, requestedOwnerHandle: o, requestedVersion: e.version, slug: normalizeOptionalString(t.slug) ?? normalizeOptionalString(r?.slug), version: f ?? (d ? e.version : null), displayName: normalizeOptionalString(t.displayName) ?? normalizeOptionalString(r?.displayName), publisherHandle: normalizeOptionalString(t.publisherHandle) ?? normalizeOptionalString(i?.handle), publisherDisplayName: normalizeOptionalString(t.publisherDisplayName) ?? normalizeOptionalString(i?.displayName), createdAt: t.createdAt ?? asFiniteNumber(a?.createdAt) ?? null, checkedAt: asFiniteNumber(s?.checkedAt) ?? null, ...c ? { skillUrl: c } : {}, ...c ? { securityAuditUrl: `${c}/security-audit?version=${encodeURIComponent(e.version)}` } : {}, security: mapVerificationSecurity(t, d) }; }) : a)]; })); for (const [e, t] of a) i.set(e, t); } return t.map((e) => { const t = i.get(targetKey(e)); if (!t) throw new Error("ClawHub skill security verdict resolution omitted a target."); return t; }); } //#endregion //#region src/infra/clawhub-install-trust.ts const CLAWHUB_TRUST_ERROR_CODE = { CLAWHUB_SECURITY_UNAVAILABLE: "clawhub_security_unavailable", CLAWHUB_DOWNLOAD_BLOCKED: "clawhub_download_blocked" }; const CLAWHUB_BLOCKING_MODERATION_STATES = /* @__PURE__ */ new Set([ "blocked", "quarantined", "revoked" ]); const CLAWHUB_SAFE_MODERATION_STATES = /* @__PURE__ */ new Set(["", "approved"]); const CLAWHUB_SAFE_SECURITY_VERDICTS = /* @__PURE__ */ new Set(["clean", "benign"]); const CLAWHUB_BLOCKING_SECURITY_VERDICTS = /* @__PURE__ */ new Set(["malicious", "blocked"]); const CLAWHUB_NON_RISK_SCAN_STATUSES = /* @__PURE__ */ new Set([ "pending", "scan_pending", "stale", "stale_scan" ]); const CLAWHUB_NON_RISK_REASONS = /* @__PURE__ */ new Set([ "pending", "pending_scan", "scan:pending", "scan_pending", "stale", "scan:stale", "stale_scan" ]); function normalizeClawHubTrustToken(e) { return normalizeOptionalString(e)?.toLowerCase() ?? ""; } function hasClawHubRiskReasons(e) { const t = normalizeClawHubTrustToken(e.scanStatus); const n = e.pending || e.stale; const r = normalizeClawHubTrustToken(e.moderationState); return e.blockedFromDownload || t !== "clean" && !(n && CLAWHUB_NON_RISK_SCAN_STATUSES.has(t)) || !CLAWHUB_SAFE_MODERATION_STATES.has(r) || e.reasons.some((e) => { const t = normalizeClawHubTrustToken(e); return Boolean(t) && !(n && CLAWHUB_NON_RISK_REASONS.has(t)); }); } function isBlockingClawHubTrust(e) { if (e.blockedFromDownload) return true; if (normalizeClawHubTrustToken(e.scanStatus) === "malicious") return true; if (CLAWHUB_BLOCKING_MODERATION_STATES.has(normalizeClawHubTrustToken(e.moderationState))) return true; return e.reasons.some((e) => { const t = normalizeClawHubTrustToken(e); return t === "scan:malicious" || t === "static:malicious"; }); } function assessClawHubTrust(e) { const t = e.trust; const n = normalizeClawHubTrustToken(e.verdict); if (isBlockingClawHubTrust(t) || CLAWHUB_BLOCKING_SECURITY_VERDICTS.has(n)) return "blocked"; if (!CLAWHUB_SAFE_SECURITY_VERDICTS.has(n)) return "review-required"; const r = hasClawHubRiskReasons(t); if (!r && !t.pending && !t.stale) return "clean"; return r ? "review-required" : "review-recommended"; } function resolveClawHubSubjectUrl(e) { if (e.subject.kind === "skill" && e.subject.ownerHandle) return `${resolveClawHubBaseUrl(e.baseUrl)}/${encodeURIComponent(e.subject.ownerHandle)}/skills/${encodeURIComponent(e.subject.packageName)}`; const t = e.subject.kind === "skill" ? "skills" : e.subject.kind === "template" ? "templates" : "plugins"; return `${resolveClawHubBaseUrl(e.baseUrl)}/${t}/${encodeClawHubPackagePath(e.subject.packageName)}`; } function wrapClawHubAuditLine(e, t) { if (visibleWidth(e) <= t) return [e]; const n = e.split(/\s+/u).filter(Boolean); const r = []; let i = ""; for (const e of n) { const n = i ? `${i} ${e}` : e; if (i && visibleWidth(n) > t) { r.push(i); i = e; } else i = n; } return i ? [...r, i] : r; } function renderClawHubAuditBox(e) { const t = Math.max(72, Math.min(process.stdout.columns ?? 88, 104)); const n = Math.max(54, Math.min(t - 4, 88)); const r = "─ ClawHub Security Audit "; const i = n + 2; return [ `╭${r}${"─".repeat(Math.max(0, i - visibleWidth(r)))}╮`, ...e.flatMap((e) => { if (!e) return [`│ ${" ".repeat(n)} │`]; return wrapClawHubAuditLine(e, n).map((e) => `│ ${e}${" ".repeat(Math.max(0, n - visibleWidth(e)))} │`); }), `╰${"─".repeat(i)}╯` ].join("\n"); } function formatClawHubSubjectPackageName(e) { return e.kind === "skill" && e.ownerHandle ? `@${e.ownerHandle}/${e.packageName}` : e.packageName; } function formatClawHubSubjectReleaseLabel(e, t) { return formatClawHubReleaseLabel(formatClawHubSubjectPackageName(e), t); } function readSkillVerdictSecurityStatus(e) { if (!e.security || typeof e.security !== "object") return; const t = e.security; if (typeof t.status === "string") return t.status; return typeof t.rawStatus === "string" ? t.rawStatus : void 0; } function readSkillVerdictSecurityPassed(e) { if (!e.security || typeof e.security !== "object") return; const t = e.security.passed; return typeof t === "boolean" ? t : void 0; } function hasUsablePassingSkillVerdictSecurity(e) { return Boolean(readSkillVerdictSecurityStatus(e)) && readSkillVerdictSecurityPassed(e) === true; } function hasSkillVerdictSecurityError(e) { return Boolean(e.error?.code || e.error?.message || e.version === null); } function isSkillVerdictPendingReason(e) { const t = normalizeClawHubTrustToken(e); return t === "pending" || t === "pending_scan" || t === "scan_pending"; } function isSkillVerdictStaleReason(e) { const t = normalizeClawHubTrustToken(e); return t === "stale" || t === "scan:stale" || t === "stale_scan"; } function isSkillVerdictBlockingReason(e) { const t = normalizeClawHubTrustToken(e); return t.includes("malicious") || t.includes("malware") || t.endsWith("_blocked") || t.endsWith(".blocked") || t === "blocked"; } function mapSkillSecurityVerdictToPackageSecurity(e) { const t = normalizeOptionalString(e.item.slug ?? e.item.requestedSlug); if (t !== e.packageName) throw new Error(terminalText`ClawHub skill trust check for "${formatClawHubReleaseLabel(e.packageName, e.version)}" returned skill "${t ?? "unknown"}".`); const n = normalizeOptionalString(e.item.publisherHandle); if (e.ownerHandle && n !== e.ownerHandle) throw new Error(terminalText`ClawHub skill trust check for "${formatClawHubReleaseLabel(e.packageName, e.version)}" returned publisher "${n ?? "unknown"}", expected "${e.ownerHandle}".`); const r = normalizeOptionalString(e.item.version); if (r !== e.version) { const t = e.item.error?.message ? `: ${e.item.error.message}` : ""; throw new Error(terminalText`ClawHub skill trust check for "${formatClawHubReleaseLabel(e.packageName, e.version)}" returned version "${r ?? "unknown"}"${t}.`); } if (hasSkillVerdictSecurityError(e.item)) { const t = e.item.error?.message ? `: ${e.item.error.message}` : ""; throw new Error(terminalText`ClawHub skill trust check for "${formatClawHubReleaseLabel(e.packageName, e.version)}" did not return a usable security verdict${t}.`); } const i = normalizeClawHubTrustToken(e.item.decision); if (e.item.ok && i === "pass" && !hasUsablePassingSkillVerdictSecurity(e.item)) throw new Error(`ClawHub skill trust check for "${formatClawHubReleaseLabel(e.packageName, e.version)}" did not return a usable security verdict.`); const a = normalizeClawHubTrustToken(readSkillVerdictSecurityStatus(e.item)); const o = readSkillVerdictSecurityPassed(e.item); const s = e.item.reasons.map((e) => normalizeOptionalString(e)).filter((e) => Boolean(e)); const c = o ?? true; const l = e.item.ok && i === "pass" && c; const u = l ? a || "clean" : a && a !== "clean" ? a : "suspicious"; if (!l && s.length === 0) s.push(i ? `decision:${i}` : "decision:fail"); const d = s.some(isSkillVerdictBlockingReason); const f = i === "blocked" || a === "malicious" || d; const p = normalizeOptionalString(e.item.displayName); const m = e.item.overview; if (typeof m !== "string" || !m.trim()) throw new Error(`ClawHub skill trust check for "${formatClawHubReleaseLabel(e.packageName, e.version)}" did not return an audit overview.`); const h = normalizeOptionalString(e.item.securityAuditUrl); if (!h) throw new Error(`ClawHub skill trust check for "${formatClawHubReleaseLabel(e.packageName, e.version)}" did not return a security audit URL.`); return { package: { name: e.packageName, family: "skill", ...p ? { displayName: p } : {} }, release: { version: e.version }, overview: m, verdict: f ? "blocked" : l && a === "clean" && s.length === 0 ? "benign" : "review", securityAuditUrl: h, trust: { scanStatus: u, moderationState: null, blockedFromDownload: f, reasons: s, pending: a === "pending" || s.some(isSkillVerdictPendingReason), stale: a === "stale" || s.some(isSkillVerdictStaleReason) } }; } function resolveSkillSecurityLinks(e) { const t = normalizeOptionalString(e.skillUrl); const n = normalizeOptionalString(e.securityAuditUrl); return { ...t ? { subject: t } : {}, ...n ? { security: n } : {} }; } async function fetchClawHubSubjectSecurity(e) { if (e.subject.kind === "plugin" || e.subject.kind === "template") { const t = await fetchClawHubPackageSecurity({ name: e.subject.packageName, version: e.version, baseUrl: e.baseUrl, token: e.token, timeoutMs: e.timeoutMs }); return { security: t, links: { security: t.securityAuditUrl } }; } const [t] = await fetchExactClawHubSkillSecurityVerdicts({ items: [{ slug: e.subject.packageName, ...e.subject.ownerHandle ? { ownerHandle: e.subject.ownerHandle } : {}, version: e.version }], baseUrl: e.baseUrl, token: e.token, timeoutMs: e.timeoutMs }); if (!t) throw new Error(`ClawHub skill trust check for "${formatClawHubReleaseLabel(e.subject.packageName, e.version)}" returned no verdict.`); return { security: mapSkillSecurityVerdictToPackageSecurity({ item: t, packageName: e.subject.packageName, ...e.subject.ownerHandle ? { ownerHandle: e.subject.ownerHandle } : {}, version: e.version }), links: resolveSkillSecurityLinks(t) }; } async function checkClawHubPackageTrust(e) { let t; let n; const r = formatClawHubSubjectPackageName(e.subject); const i = formatClawHubSubjectReleaseLabel(e.subject, e.version); try { const i = await fetchClawHubSubjectSecurity({ subject: e.subject, version: e.version, baseUrl: e.baseUrl, token: e.token, timeoutMs: e.timeoutMs }); const a = e.subject.kind === "template" ? "template" : void 0; const o = a ? e.expectedTemplateArtifact : void 0; const s = normalizeOptionalString(i.security.package?.name); if (s !== e.subject.packageName) return { ok: false, error: terminalText`ClawHub release trust check for "${formatClawHubReleaseLabel(r, e.version)}" returned package "${s ?? "unknown"}".`, code: CLAWHUB_TRUST_ERROR_CODE.CLAWHUB_SECURITY_UNAVAILABLE, version: e.version }; if (a && i.security.package?.family !== a) return { ok: false, error: `ClawHub release trust check for "${formatClawHubReleaseLabel(r, e.version)}" returned a different package family.`, code: CLAWHUB_TRUST_ERROR_CODE.CLAWHUB_SECURITY_UNAVAILABLE, version: e.version }; const c = normalizeOptionalString(i.security.release?.version); if (c !== e.version) return { ok: false, error: terminalText`ClawHub release trust check for "${formatClawHubReleaseLabel(r, e.version)}" returned version "${c ?? "unknown"}".`, code: CLAWHUB_TRUST_ERROR_CODE.CLAWHUB_SECURITY_UNAVAILABLE, version: e.version }; if (a === "template" && !o) return { ok: false, error: `ClawHub release trust check for "${formatClawHubReleaseLabel(r, e.version)}" has no selected artifact identity.`, code: CLAWHUB_TRUST_ERROR_CODE.CLAWHUB_SECURITY_UNAVAILABLE, version: e.version }; if (o) { const t = i.security.release; if (t?.artifactKind !== "npm-pack" || normalizeClawHubSha256Hex(t.artifactSha256 ?? "") !== o.sha256 || t.npmIntegrity !== o.npmIntegrity || o.npmShasum !== void 0 && t.npmShasum !== o.npmShasum) return { ok: false, error: `ClawHub release trust check for "${formatClawHubReleaseLabel(r, e.version)}" returned a different artifact identity.`, code: CLAWHUB_TRUST_ERROR_CODE.CLAWHUB_SECURITY_UNAVAILABLE, version: e.version }; } t = i.security; n = i.links; } catch (t) { return { ok: false, error: terminalText`ClawHub release trust check failed for "${i}": ${formatErrorMessage(t)}`, code: CLAWHUB_TRUST_ERROR_CODE.CLAWHUB_SECURITY_UNAVAILABLE, version: e.version }; } const a = assessClawHubTrust(t); const o = e.subject.kind === "template" && a === "review-recommended" ? "review-required" : a; const s = (/* @__PURE__ */ new Date()).toISOString(); const c = e.baseUrl; const l = e.subject; const u = e.version; const d = t.overview; const f = l.kind === "skill" && normalizeOptionalString(n?.subject) || resolveClawHubSubjectUrl({ baseUrl: c, subject: l }); const p = normalizeOptionalString(n?.security) ?? `${f}/security-audit?version=${encodeURIComponent(u)}`; const m = formatClawHubSubjectReleaseLabel(l, u); const h = o === "blocked" ? theme.error("Blocked") : o === "clean" ? theme.success("Safe") : theme.warn("Review"); const g = renderClawHubAuditBox([ terminalText`${m}`, "", `Outcome: ${h}`, "", "Overview:", ...d.split("\n").map((e) => terminalText`${e}`), "", terminalText`Details: ${p}` ]); const _ = stripAnsi(g); if (o === "clean") e.logger?.info?.(g); else e.logger?.warn?.(g); if (o === "blocked") return { ok: false, error: `ClawHub blocked this release; ${e.mode === "update" ? "update" : "install"} was not started.`, code: CLAWHUB_TRUST_ERROR_CODE.CLAWHUB_DOWNLOAD_BLOCKED, warning: _, version: e.version }; if ((e.mode !== "update" || e.confirmOnUpdate) && e.confirmInstall && !await e.confirmInstall(o === "clean" ? void 0 : _)) return { ok: false, error: "Install cancelled.", warning: _, version: e.version }; const v = t.trust; const y = normalizeClawHubTrustToken(v.scanStatus); const b = normalizeClawHubTrustToken(v.moderationState); const x = v.reasons.map((e) => normalizeOptionalString(e)).filter((e) => Boolean(e)); return { ok: true, trustInstallRecordFields: { clawhubTrustDisposition: o, ...y ? { clawhubTrustScanStatus: y } : {}, ...b ? { clawhubTrustModerationState: b } : {}, ...x.length > 0 ? { clawhubTrustReasons: x } : {}, ...v.pending ? { clawhubTrustPending: true } : {}, ...v.stale ? { clawhubTrustStale: true } : {}, clawhubTrustCheckedAt: s }, ...o === "clean" ? {} : { warning: _ } }; } //#endregion export { encodeClawHubPackagePath as a, fetchExactClawHubSkillSecurityVerdicts as i, assessClawHubTrust as n, formatClawHubReleaseLabel as o, checkClawHubPackageTrust as r, CLAWHUB_TRUST_ERROR_CODE as t };