UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

233 lines (232 loc) • 8.16 kB
import { m as readNonBlankString } from "./string-coerce-CCIiB4H7.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { t as hasErrnoCode } from "./errno-DFcoqIT9.mjs"; import { o as registerSecretValueForRedaction } from "./secret-redaction-registry-Cy0acctn.mjs"; import { i as resolveEnvironmentValue, n as mergeProcessEnv } from "./process-env-DVJdcOcM.mjs"; import { o as resolveExecutablePath } from "./executable-path-D8oWZRS5.mjs"; import { n as sha256Hex } from "./node-crypto-B6yuTjmm.mjs"; import { a as withGitProcessOperation } from "./spawn-diagnostics-DBVI9KzR.mjs"; import { t as runCommandBuffered } from "./exec-aRIvS9s4.mjs"; import { t as createStaleWhileRevalidateCache } from "./stale-while-revalidate-cache-BRZEfv_f.mjs"; import { n as resolveGitHubHost } from "./github-host-runtime-CMm44VF1.mjs"; import path from "node:path"; import fs from "node:fs/promises"; //#region src/agents/github-read-identity.ts const GITHUB_IDENTITY_COMMAND_TIMEOUT_MS = 15e3; const GITHUB_IDENTITY_OUTPUT_LIMIT_BYTES = 32768; const nativeTokens = createStaleWhileRevalidateCache({ maxEntries: 32, ttlMs: 6e4, cacheable: (e) => e !== void 0 }); const githubIdentityChanges = {}; function clearNativeGitHubTokenCache() { nativeTokens.clear(); try { githubIdentityChanges.onChange?.(); } catch {} } function ambientGitHubCredential(e, t = resolveGitHubHost()) { const n = t === "github.com" ? ["GH_TOKEN", "GITHUB_TOKEN"] : ["GH_ENTERPRISE_TOKEN", "GITHUB_ENTERPRISE_TOKEN"]; const r = resolveEnvironmentValue(e, n[0]) || resolveEnvironmentValue(e, n[1]); if (r && t !== "github.com" && resolveEnvironmentValue(e, "GH_HOST")?.trim().toLowerCase() !== t) throw new GitHubIdentityError("unverified"); return { host: t, token: r }; } async function readCachedNativeGitHubToken(e, t = false, n = resolveGitHubHost(), r) { const i = mergeProcessEnv([process.env, e]); const { host: a, token: o } = ambientGitHubCredential(i, n); if (o) return normalizeGitHubToken(o); const s = sha256Hex(JSON.stringify([ a, process.cwd(), Object.entries(i).toSorted(([e], [t]) => e.localeCompare(t)), t ])); const { value: c, stale: l } = await nativeTokens.read(s, () => readNativeGitHubToken(e, t, a), { allowStale: r !== void 0 }); if (l) r?.onStale(); return c; } async function runGitHubIdentityCommand(e, t, n, r = GITHUB_IDENTITY_COMMAND_TIMEOUT_MS) { return await withGitProcessOperation("github.identity", () => runCommandBuffered(e, { env: t ? { ...t } : {}, cwd: n, timeoutMs: r, maxOutputBytes: GITHUB_IDENTITY_OUTPUT_LIMIT_BYTES }), "default"); } function normalizeGitHubToken(e) { const t = e.trim(); if (!t || t.length > 2048 || /\s/u.test(t)) throw new Error("Managed GitHub credential must be one non-empty line."); registerSecretValueForRedaction(t); return t; } async function assertNoNativeGitHubConfiguration(e, t) { const value = (t) => resolveEnvironmentValue(e, t); const n = process.platform === "win32"; const r = n ? path.win32 : path.posix; const i = value(n ? "USERPROFILE" : "HOME"); const a = value("XDG_CONFIG_HOME"); const o = value("APPDATA"); const s = value("GH_CONFIG_DIR") || (a ? r.join(a, "gh") : void 0) || (n && o ? r.join(o, "GitHub CLI") : void 0) || (i ? r.join(i, ".config", "gh") : void 0); if (!s) throw new GitHubIdentityError("unverified"); const c = r.resolve(t, s); for (const e of [ c, r.join(c, "config.yml"), r.join(c, "hosts.yml") ]) try { const t = await fs.lstat(e); if (e !== c || !t.isDirectory() || t.isSymbolicLink()) throw new GitHubIdentityError("unavailable"); } catch (e) { if (e instanceof GitHubIdentityError) throw e; if (!hasErrnoCode(e, "ENOENT")) throw new GitHubIdentityError("unverified"); } } async function readNativeGitHubToken(e, t = false, n = resolveGitHubHost()) { const r = mergeProcessEnv([process.env, e]); const { token: i } = ambientGitHubCredential(r, n); if (i) return normalizeGitHubToken(i); const a = { ...e, GH_HOST: n, GH_TOKEN: void 0, GITHUB_TOKEN: void 0, GH_ENTERPRISE_TOKEN: void 0, GITHUB_ENTERPRISE_TOKEN: void 0 }; const o = performance.now(); const s = await runGitHubIdentityCommand([ "gh", "auth", "token", "--hostname", n ], a); try { if (s.code === 0) return normalizeGitHubToken(s.stdout.toString("utf8")); } finally { s.stdout.fill(0); s.stderr.fill(0); } if (!t) return; if (s.termination === "error") try { const e = process.cwd(); if (!hasErrnoCode(s.error, "ENOENT") || !(await fs.stat(e)).isDirectory() || resolveExecutablePath("gh", { env: r, cwd: e, useCache: false })) throw new GitHubIdentityError("unverified"); await assertNoNativeGitHubConfiguration(r, e); return; } catch (e) { throw e instanceof GitHubIdentityError ? e : new GitHubIdentityError("unverified"); } if (s.termination !== "exit") throw new GitHubIdentityError("unverified"); const c = GITHUB_IDENTITY_COMMAND_TIMEOUT_MS - Math.ceil(performance.now() - o); if (c <= 0) throw new GitHubIdentityError("unverified"); const l = await runGitHubIdentityCommand([ "gh", "auth", "status", "--active", "--hostname", n, "--json", "hosts" ], a, void 0, c); try { if (l.code !== 0) throw new GitHubIdentityError("unverified"); let e; try { e = JSON.parse(l.stdout.toString("utf8")); } catch { throw new GitHubIdentityError("unverified"); } if (!isRecord(e) || !isRecord(e.hosts) || Object.keys(e).length !== 1) throw new GitHubIdentityError("unverified"); if (Object.keys(e.hosts).length !== 0) throw new GitHubIdentityError("unavailable"); return; } finally { l.stdout.fill(0); l.stderr.fill(0); } } /** The caller's owner admits the operation; selection is checked inside that admission. */ function startGitHubIdentityOperation(e, t) { t.assertCurrent?.(); return t.startCurrent ? t.startCurrent(() => { t.assertCurrent?.(); return e(); }) : e(); } var GitHubIdentityError = class extends Error { constructor(e) { super(e === "changed" ? "GitHub identity changed; reload the dashboard and retry." : e === "rate_limited" ? "GitHub identity verification is rate limited; wait and retry." : e === "unverified" ? "The effective GitHub identity could not be verified; retry or reconnect the agent's GitHub identity." : "The selected GitHub credential is unavailable; reconnect the agent's GitHub identity in Settings."); this.reason = e; } }; function createGitHubReadIdentity(e) { const { token: t, selection: n, assertSelected: r, startActive: i, readToken: a } = e; const o = { assertCurrent: r, startCurrent: i }; const start = async (e) => { const n = await startGitHubIdentityOperation(a, o); return await startGitHubIdentityOperation(() => { if (n !== t) throw new GitHubIdentityError("changed"); return e(); }, o); }; const s = { ...e.stale ? { stale: true } : {}, cacheScope: n.source === "anonymous" ? "anonymous" : sha256Hex(JSON.stringify([ n.source, n.profileId, n.accountId, t ])), assertSelected: r, revalidate: () => start(() => void 0), start }; return e.token === void 0 ? { ...s, token: void 0, selection: Object.freeze(e.selection) } : { ...s, token: e.token, selection: Object.freeze(e.selection) }; } async function readGitAuthor(e, t) { const n = await runGitHubIdentityCommand([ "git", "config", "--null", "--get-regexp", "^user\\.(name|email)$" ], { ...e, GIT_NO_LAZY_FETCH: "1" }, t); const r = { name: null, email: null }; if (n.code !== 0) return r; for (const e of n.stdout.toString("utf8").split("\0")) { const t = e.indexOf("\n"); if (t < 0) continue; const n = e.slice(0, t); const i = readNonBlankString(e.slice(t + 1))?.trim() ?? null; if (n === "user.name") r.name = i; else if (n === "user.email") r.email = i; } return r; } //#endregion export { githubIdentityChanges as a, readGitAuthor as c, createGitHubReadIdentity as i, readNativeGitHubToken as l, GitHubIdentityError as n, normalizeGitHubToken as o, clearNativeGitHubTokenCache as r, readCachedNativeGitHubToken as s, GITHUB_IDENTITY_OUTPUT_LIMIT_BYTES as t, startGitHubIdentityOperation as u };