UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

386 lines (385 loc) • 12.5 kB
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs"; import { c as resolveUserPath, s as resolveUserFilesystemPath } from "./home-dir-EKmgmdPG.mjs"; import { o as redactSensitiveUrlLikeString } from "./redact-sensitive-url-D-E7DGoc.mjs"; import { n as sanitizeForLog } from "./ansi-CZa2t0Hf.mjs"; import "./utils-C8YECn2Q.mjs"; import { d as pathExists } from "./fs-safe-BbWvmdVn.mjs"; import { r as sha256HexPrefixCore } from "./node-crypto-B6yuTjmm.mjs"; import "./crypto-digest-B2m8wIBj.mjs"; import { o as resolveDefaultPluginGitDir } from "./install-paths-Bwm0P5EG.mjs"; import { t as PLUGIN_INSTALL_ERROR_CODE } from "./install-types-BBbGKapR.mjs"; import { t as hasHttpUrlPrefix } from "./url-protocol-DXxSDuQZ.mjs"; import { n as runCommandWithTimeout } from "./exec-runner-Br73vG-X.mjs"; import "./exec-aRIvS9s4.mjs"; import { t as resolveNpmCommand } from "./npm-command-kcBVU3OP.mjs"; import { n as resolveInstallWorkTimeoutMs, r as resolveTimedInstallModeOptions } from "./install-mode-options-N6t-RB8t.mjs"; import { c as withInstallWorkspace } from "./install-source-utils-yGloSiaw.mjs"; import { a as resolvePackageDirInstallTransaction, i as requestDeferredPackageDirInstall, o as createSafeNpmInstallArgs, r as installPackageDir, s as createSafeNpmInstallEnv } from "./install-package-dir-_Rv9x8R0.mjs"; import { n as preflightPluginGitInstallPolicy } from "./install-security-scan-BjcurHAj.mjs"; import { B as resolvePluginInstallTransactionRequest, F as attachPluginInstallTransaction, M as emitPluginInstallSecurityEvent, N as pluginAuditOutcomeForReason, b as ensureInstallTargetAvailableForMode, j as emitPluginAuditSecurityEvent, w as loadPluginInstallRuntime } from "./npm-managed-root-BtsiBsIh.mjs"; import { o as installPluginFromInstalledPackageDir } from "./install-Xai3w73h.mjs"; import path from "node:path"; import fs from "node:fs/promises"; //#region src/infra/git-source.ts /** Acquires a tree; callers retain source policy and ownership of its staging directory. */ async function acquireGitSource(e) { const run = (t, n, r = false) => runCommandWithTimeout(t, { ...e.commandEnv?.(), ...n ? { cwd: n } : {}, timeoutMs: r ? resolveInstallWorkTimeoutMs(e.workTimeoutMs, e.timeoutMs ?? 12e4) : e.timeoutMs ?? 12e4 }); const failure = async (t) => { await e.cleanupOnFailure?.(); if (e.formatFailure) return { ok: false, error: e.formatFailure(t) }; const safe = (e) => sanitizeForLog(redactSensitiveUrlLikeString(e)); const n = safe(e.label); const r = safe(e.ref ?? ""); const i = safe(t.stderr.trim() || t.stdout.trim() || "git failed"); return { ok: false, error: t.action === "resolve ref" ? `failed to resolve ref ${r} in ${n}` : `failed to ${t.action}${t.action === "checkout" ? ` ${r}` : ""} ${n}: ${i}` }; }; const t = ["git", "clone"]; if (e.cloneNoHardlinks) t.push("--no-hardlinks"); if (!e.ref || e.refMode === "shallow-branch") t.push("--depth", "1"); if (e.ref && e.refMode === "shallow-branch") t.push("--branch", e.ref); if (e.cloneSeparator !== false) t.push("--"); t.push(e.url, e.repoDir); const n = await run(t, void 0, true); if (n.code !== 0) return await failure({ action: "clone", ...n }); if (e.ref && e.refMode !== "shallow-branch") { let t = e.ref; if (e.refMode === "resolve-remote") { const n = e.ref.startsWith("origin/") ? [e.ref] : [e.ref, `origin/${e.ref}`]; let r; for (const t of n) { const n = await run([ "git", "rev-parse", "--verify", "--quiet", `${t}^{commit}` ], e.repoDir); const i = normalizeOptionalString(n.stdout); if (n.code === 0 && i) { r = i; break; } } if (!r) return await failure({ action: "resolve ref", stdout: "", stderr: "" }); t = r; } const n = await run([ "git", "switch", "--detach", "--", t ], e.repoDir, true); if (n.code !== 0) return await failure({ action: "checkout", ...n }); } if (e.recordCommit === false) return { ok: true }; const r = await run([ "git", "rev-parse", "HEAD" ], e.repoDir); if (r.code !== 0) return await failure({ action: "resolve commit for", ...r }); return { ok: true, commit: normalizeOptionalString(r.stdout) }; } //#endregion //#region src/plugins/git-install.ts const GIT_SPEC_PREFIX = "git:"; const DEFAULT_GIT_TIMEOUT_MS = 12e4; const FULL_GIT_COMMIT_PATTERN = /^[0-9a-f]{40}$/i; /** Returns true for full commit SHAs that do not require branch/tag drift checks. */ function isImmutableGitCommitRef(e) { return FULL_GIT_COMMIT_PATTERN.test(e ?? ""); } function splitGitSpecRef(e) { const t = e.lastIndexOf("#"); if (t > 0) return { base: e.slice(0, t), ref: normalizeOptionalString(e.slice(t + 1)) }; for (let t = e.lastIndexOf("@"); t > 0; t = e.lastIndexOf("@", t - 1)) { const n = e.slice(0, t); const r = normalizeOptionalString(e.slice(t + 1)); if (r && isGitSpecBase(n)) return { base: n, ref: r }; } return { base: e }; } function isGitSpecBase(e) { return looksLikeGitHubRepoShorthand(e) || looksLikeGitHubHostPath(e) || looksLikeUrlGitSpecBase(e) || looksLikeScpGitUrl(e) || e.endsWith(".git") || e.startsWith("./") || e.startsWith("../") || e.startsWith("~/"); } function looksLikeGitHubRepoShorthand(e) { return /^[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:\.git)?$/.test(e); } function looksLikeGitHubHostPath(e) { return /^github\.com\/[A-Za-z0-9_.-]+\/[A-Za-z0-9_.-]+(?:\.git)?$/i.test(e); } function isGitUrl(e) { if (e.startsWith("-")) return false; return /^(?:ssh|git|file):\/\//i.test(e) || looksLikeScpGitUrl(e) || e.endsWith(".git"); } function looksLikeScpGitUrl(e) { return /^[^@\s]+@[^:\s]+:.+/.test(e); } function looksLikeUrlGitSpecBase(e) { try { const t = new URL(e); if (![ "http:", "https:", "ssh:", "git:", "file:" ].includes(t.protocol)) return false; if (t.protocol === "file:") return t.pathname.length > 1; return Boolean(t.hostname) && t.pathname.length > 1; } catch { return false; } } function stripGitSuffix(e) { return e.replace(/\.git$/i, ""); } function normalizeGitLabel(e) { if (hasHttpUrlPrefix(e) || /^(?:ssh|git|file):\/\//i.test(e)) try { const t = new URL(e); return stripGitSuffix(`${t.hostname}${t.pathname}`).replace(/^\/+/, ""); } catch { return stripGitSuffix(e); } return stripGitSuffix(e); } function parseGitPluginSpec(e) { const t = e.trim(); if (!t.toLowerCase().startsWith(GIT_SPEC_PREFIX)) return null; const n = t.slice(4).trim(); if (!n) return null; const r = splitGitSpecRef(n); const i = r.base.trim(); if (!i) return null; const a = i.startsWith("./") || i.startsWith("../") || i.startsWith("~/"); let o; if (looksLikeGitHubRepoShorthand(i) || looksLikeGitHubHostPath(i)) { const e = stripGitSuffix(i.replace(/^github\.com\//i, "")); o = { url: `https://github.com/${e}.git`, label: e }; } else if (hasHttpUrlPrefix(i) || isGitUrl(i) || a) { const e = a ? resolveUserFilesystemPath(i) : i; o = { url: e, label: normalizeGitLabel(e) }; } else return null; return { input: t, ...o, ref: r.ref, normalizedSpec: `${GIT_SPEC_PREFIX}${o.url}${r.ref ? `@${r.ref}` : ""}` }; } function createGitCommandEnv() { return { GIT_TERMINAL_PROMPT: "0", GIT_CONFIG_NOSYSTEM: "1", GIT_TEMPLATE_DIR: "", GIT_EDITOR: "", GIT_SEQUENCE_EDITOR: "", GIT_EXTERNAL_DIFF: "", GIT_DIR: void 0, GIT_WORK_TREE: void 0, GIT_COMMON_DIR: void 0, GIT_INDEX_FILE: void 0, GIT_OBJECT_DIRECTORY: void 0, GIT_ALTERNATE_OBJECT_DIRECTORIES: void 0, GIT_NAMESPACE: void 0, GIT_EXEC_PATH: void 0, GIT_SSL_NO_VERIFY: void 0 }; } async function installPluginFromGitSpec(e) { const t = parseGitPluginSpec(e.spec); if (!t) return { ok: false, error: `unsupported git: plugin spec: ${e.spec}` }; const { workTimeoutMs: n } = resolveTimedInstallModeOptions(e, {}); const r = e.gitDir ? resolveUserPath(e.gitDir) : resolveDefaultPluginGitDir(); const i = redactSensitiveUrlLikeString(t.normalizedSpec); const a = path.join(r, `git-${sha256HexPrefixCore(i, 16)}`, "repo"); const o = e.mode === "update" && await pathExists(a) ? "update" : "install"; const s = await ensureInstallTargetAvailableForMode({ runtime: await loadPluginInstallRuntime(), targetPath: a, mode: o }); if (!s.ok) return s; const prepare = async (r) => { e.logger?.info?.(`Cloning ${sanitizeForLog(redactSensitiveUrlLikeString(t.label))}...`); const i = await acquireGitSource({ ...t, repoDir: r, refMode: "resolve-remote", timeoutMs: e.timeoutMs, workTimeoutMs: n, commandEnv: () => ({ env: createGitCommandEnv() }), cloneNoHardlinks: !e.dryRun }); if (!i.ok) return i; const s = { kind: "plugin-git", requestedSpecifier: t.input, source: { kind: "git", authority: "third-party", mutable: !isImmutableGitCommitRef(t.ref), network: true } }; const c = await preflightPluginGitInstallPolicy({ config: e.config, onInstallPolicyWarning: e.onInstallPolicyWarning, logger: e.logger ?? {}, mode: o, pluginId: e.expectedPluginId ?? t.label, requestedSpecifier: t.input, source: s.source, sourcePath: r }); if (c?.blocked) { const t = c.blocked.code === "security_scan_failed" ? "security_scan_failed" : "security_scan_blocked"; emitPluginAuditSecurityEvent({ outcome: pluginAuditOutcomeForReason(t), reason: t, pluginId: e.expectedPluginId, mode: o, sourceFamily: "git" }); return { ok: false, error: c.blocked.reason, ...c.blocked.code === "security_scan_failed" ? { code: PLUGIN_INSTALL_ERROR_CODE.SECURITY_SCAN_FAILED } : c.blocked.code === "security_scan_blocked" ? { code: PLUGIN_INSTALL_ERROR_CODE.SECURITY_SCAN_BLOCKED } : {} }; } if (!e.dryRun) { e.logger?.info?.("Installing plugin dependencies with npm…"); const t = await runCommandWithTimeout(resolveNpmCommand(createSafeNpmInstallArgs({ noAudit: true, noFund: true })), { cwd: r, timeoutMs: resolveInstallWorkTimeoutMs(n, Math.max(e.timeoutMs ?? DEFAULT_GIT_TIMEOUT_MS, 3e5)), env: createSafeNpmInstallEnv(process.env, { npmConfigCwd: r, packageLock: true, quiet: true }) }); if (t.code !== 0) return { ok: false, error: `npm install failed: ${t.stderr.trim() || t.stdout.trim()}` }; } const l = await installPluginFromInstalledPackageDir({ onInstallPolicyWarning: e.onInstallPolicyWarning, config: e.config, packageDir: r, dryRun: e.dryRun, expectedPluginId: e.expectedPluginId, logger: e.logger, mode: o, installPolicyRequest: s }); if (!l.ok) return l; if (!e.dryRun) await e.onBeforePluginArtifactCommit?.({ pluginId: l.pluginId, ...o === "update" ? { currentArtifactDir: a } : {}, stagedArtifactDir: r, mode: o }); return { ...l, git: { url: t.url, ref: t.ref, commit: i.commit, resolvedAt: (/* @__PURE__ */ new Date()).toISOString() } }; }; if (e.dryRun) return await withInstallWorkspace("openclaw-git-plugin-", (e) => prepare(path.join(e, "repo"))); try { await fs.mkdir(path.dirname(a), { recursive: true, mode: 448 }); } catch (e) { return { ok: false, error: `failed to replace managed git plugin repository: ${String(e)}` }; } let c; const l = resolvePluginInstallTransactionRequest(e); const u = { targetDir: a, mode: o, timeoutMs: DEFAULT_GIT_TIMEOUT_MS, copyErrorPrefix: "failed to replace managed git plugin repository", hasDeps: false, depsLogMessage: "", beforePersistentApply: e.beforePersistentApply, afterInstall: (e) => c = prepare(e) }; const d = await installPackageDir(l ? requestDeferredPackageDirInstall(u, l.assertOwned, l.prepareSettlement) : u).catch((e) => ({ ok: false, error: `failed to replace managed git plugin repository: ${String(e)}` })); const f = c ? await c : void 0; if (!d.ok) return d; if (!f?.ok) throw new Error("Git repository published without a validated plugin"); const p = { ...f, targetDir: a }; emitPluginInstallSecurityEvent({ pluginId: p.pluginId, mode: o, sourceFamily: "git", extensionCount: p.extensions.length, hasVersion: Boolean(p.version), trustedSourceLinkedOfficialInstall: e.trustedSourceLinkedOfficialInstall }); const m = resolvePackageDirInstallTransaction(d); return m ? attachPluginInstallTransaction(p, m) : p; } //#endregion export { acquireGitSource as i, isImmutableGitCommitRef as n, parseGitPluginSpec as r, installPluginFromGitSpec as t };