UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

332 lines (331 loc) • 14.3 kB
import { m as readNonBlankString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs"; import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs"; import { i as getOrCreatePromise, n as createLazyPromise } from "./lazy-promise-DiCvjz9w.mjs"; import { t as normalizeGitHubLogin } from "./github-login-BtE4eIcv.mjs"; import { t as firstHeaderValue } from "./http-header-value-BTQlMYRm.mjs"; import { S as parseEnterpriseGitHubPrincipal, x as normalizeVerifiedEmail } from "./user-profile-identity.read-DZIwS_8H.mjs"; import { a as resolveConfiguredGitHubHost } from "./github-host-CjR25cOO.mjs"; import { n as gitHubPublicApi, r as githubApiToken } from "./github-public-api-C47tI7vQ.mjs"; import { t as classifyTailscaleLogin } from "./user-profiles-tailscale-login-DtoF4wFU.mjs"; import { a as resolveCanonicalCachedGitHubIdentity } from "./user-profile-reads-B8FZQ8ed.mjs"; import { r as ensureCanonicalUserProfileForEmail, t as ensureCanonicalEnterpriseGitHubProfile, u as syncCanonicalGitHubIdentity } from "./user-profile-writes-Coep_BY9.mjs"; import { createHash } from "node:crypto"; //#region src/gateway/github-user-identity.ts const CLOUDFLARE_ACCESS_USER_HEADER = "cf-access-authenticated-user-email"; const CLOUDFLARE_ACCESS_ASSERTION_HEADER = "cf-access-jwt-assertion"; const CLOUDFLARE_ACCESS_HOST_SUFFIX = ".cloudflareaccess.com"; const CLOUDFLARE_ACCESS_IDENTITY_PATH = "/cdn-cgi/access/get-identity"; const ACCESS_ASSERTION_MAX_BYTES = 16384; const ACCESS_IDENTITY_MAX_BYTES = 65536; const ACCESS_IDENTITY_CACHE_MS = 3e5; const ACCESS_IDENTITY_CACHE_LIMIT = 200; const JWT_SEGMENT_PATTERN = /^[A-Za-z0-9_-]+$/u; const GITHUB_IDENTITY_CACHE_MS = 9e5; const GITHUB_IDENTITY_CACHE_LIMIT = 200; const GITHUB_ETAG_MAX_LENGTH = 1024; const identityMetadataCaches = /* @__PURE__ */ new WeakMap(); const accessIdentityCaches = /* @__PURE__ */ new WeakMap(); function cloudflareAccessAssertionClaims(e) { if (Buffer.byteLength(e, "utf8") > ACCESS_ASSERTION_MAX_BYTES) throw new Error("Cloudflare Access assertion is invalid"); const t = e.split("."); if (t.length !== 3 || t.some((e) => !JWT_SEGMENT_PATTERN.test(e))) throw new Error("Cloudflare Access assertion is invalid"); let n; try { n = JSON.parse(Buffer.from(t[1], "base64url").toString("utf8")); } catch { throw new Error("Cloudflare Access assertion is invalid"); } if (!isRecord(n) || typeof n.iss !== "string") throw new Error("Cloudflare Access assertion issuer is invalid"); const r = URL.parse(n.iss); if (!r || r.protocol !== "https:" || r.username || r.password || r.port || r.pathname !== "/" || r.search || r.hash || !r.hostname.endsWith(CLOUDFLARE_ACCESS_HOST_SUFFIX)) throw new Error("Cloudflare Access assertion issuer is invalid"); return { issuer: r, expiresAt: typeof n.exp === "number" && Number.isFinite(n.exp) ? Math.min(n.exp * 1e3, Date.now() + ACCESS_IDENTITY_CACHE_MS) : 0 }; } async function resolveCloudflareAccessIdentity(e, t, n) { const { issuer: r, expiresAt: i } = cloudflareAccessAssertionClaims(e); const a = n && { ...n }; const o = fetch; const load = () => fetchCloudflareAccessIdentity(o, r, e, t, a); if (i <= Date.now()) return load(); const s = createHash("sha256").update(JSON.stringify([ e, t.trim().toLowerCase(), a ])).digest("hex"); const c = accessIdentityCaches.get(o) ?? /* @__PURE__ */ new Map(); accessIdentityCaches.set(o, c); const l = c.get(s); if (l && l.expiresAt > Date.now()) return l.identity; const u = load(); c.set(s, { identity: u, expiresAt: i }); pruneMapToMaxSize(c, ACCESS_IDENTITY_CACHE_LIMIT); u.catch(() => { if (c.get(s)?.identity === u) c.delete(s); }); return u; } async function fetchCloudflareAccessIdentity(e, t, n, r, i) { let a; try { const r = await e(`${t.origin}${CLOUDFLARE_ACCESS_IDENTITY_PATH}`, { headers: { Cookie: `CF_Authorization=${n}` }, redirect: "manual", signal: AbortSignal.timeout(gitHubPublicApi.GITHUB_REQUEST_TIMEOUT_MS) }); if (!r.ok) { await r.body?.cancel().catch(() => {}); throw new Error("identity response was not successful"); } const i = await gitHubPublicApi.readBoundedResponse(r, ACCESS_IDENTITY_MAX_BYTES); a = JSON.parse(i.toString("utf8")); } catch { throw new Error("Cloudflare Access identity lookup failed"); } if (!isRecord(a)) throw new Error("Cloudflare Access identity response is invalid"); const o = typeof a.email === "string" ? a.email.trim() : ""; if (!o || o.toLowerCase() !== r.trim().toLowerCase()) throw new Error("Cloudflare Access identity principal did not match"); if (!isRecord(a.idp)) throw new Error("Cloudflare Access identity provider is invalid"); if (a.idp.type === "oidc") { const e = Object.hasOwn(a, "oidc_fields") ? a.oidc_fields : a.custom; if (!i || t.origin !== i.issuer || a.idp.id !== i.providerId || !isRecord(e) || !Object.hasOwn(e, i.githubAccountIdClaim)) return { provider: "oidc" }; const n = e[i.githubAccountIdClaim]; if (typeof n !== "string" || !/^[1-9][0-9]*$/u.test(n) || !Number.isSafeInteger(Number(n))) return { provider: "oidc" }; return { provider: "oidc", accountId: Number(n) }; } if (a.idp.type !== "github") throw new Error("Cloudflare Access identity provider is unsupported"); if (typeof a.id !== "number" || !Number.isSafeInteger(a.id) || a.id <= 0) throw new Error("Cloudflare Access GitHub account id is invalid"); const s = typeof a.name === "string" && a.name.trim() ? a.name : void 0; return { provider: "github", accountId: a.id, ...s ? { initialDisplayName: s } : {} }; } async function resolveGitHubUserIdentityByLogin(e, t) { const n = normalizeGitHubLogin(e); if (!n) throw new TypeError("GitHub username is invalid"); const r = githubApiToken(process.env, void 0, "github.com"); let i; try { const request = async (e) => { const { value: r } = await gitHubPublicApi.fetchGitHubJsonPage(`${gitHubPublicApi.GITHUB_API_ORIGIN}/users/${encodeURIComponent(n)}`, fetch, e, { signal: t?.signal, apiBaseUrl: gitHubPublicApi.GITHUB_API_ORIGIN }); return r; }; i = t?.allowAnonymousRetry === false ? await request(r) : await gitHubPublicApi.withOptionalGitHubAuth(r, request); } catch (e) { if (e instanceof gitHubPublicApi.ControlUiGitHubError) throw e; throw new gitHubPublicApi.ControlUiGitHubError(502, "GitHub request failed"); } if (!isRecord(i)) throw new gitHubPublicApi.ControlUiGitHubError(502, "GitHub response was not an object"); const a = i.id; if (!Number.isSafeInteger(a) || typeof a !== "number" || a <= 0) throw new gitHubPublicApi.ControlUiGitHubError(502, "GitHub response omitted a valid account id"); return parseGitHubUserIdentity(a, i); } function parseGitHubUserIdentity(e, t) { if (!isRecord(t) || t.id !== e) throw new gitHubPublicApi.ControlUiGitHubError(502, "GitHub account id did not match"); const n = typeof t.login === "string" ? normalizeGitHubLogin(t.login) : void 0; if (!n) throw new gitHubPublicApi.ControlUiGitHubError(502, "GitHub response omitted a valid login"); return { accountId: e, login: n, name: readNonBlankString(t.name) }; } function resolveGitHubUserIdentityById(e, t, n) { const r = identityMetadataCaches.get(n) ?? { values: /* @__PURE__ */ new Map(), pending: /* @__PURE__ */ new Map() }; identityMetadataCaches.set(n, r); const i = `${e}:${gitHubPublicApi.githubApiCredentialCacheScope(t)}`; const a = r.values.get(i); if (a && a.expiresAt > Date.now()) return Promise.resolve({ identity: a.identity, refreshed: false }); const o = getOrCreatePromise(r.pending, i, async () => { try { const s = await gitHubPublicApi.fetchGitHubApi(`${gitHubPublicApi.GITHUB_API_ORIGIN}/user/${e}`, n, t, void 0, void 0, a?.etag, void 0, void 0, gitHubPublicApi.GITHUB_API_ORIGIN); let c; if (s.status === 304 && a?.etag) { await gitHubPublicApi.discardResponse(s); c = a.identity; } else c = parseGitHubUserIdentity(e, await gitHubPublicApi.readGitHubJsonResponse(s)); const l = s.headers.get("etag") ?? (s.status === 304 ? a?.etag : void 0); const u = l && l.length <= GITHUB_ETAG_MAX_LENGTH ? l : void 0; if (r.pending.get(i) === o) { r.values.set(i, { identity: c, etag: u, expiresAt: Date.now() + GITHUB_IDENTITY_CACHE_MS }); pruneMapToMaxSize(r.values, GITHUB_IDENTITY_CACHE_LIMIT); } return c; } catch (e) { if (r.pending.get(i) === o && e instanceof gitHubPublicApi.ControlUiGitHubError && !e.retryable) r.values.delete(i); throw e; } }, { evictOnSettled: true }); pruneMapToMaxSize(r.pending, GITHUB_IDENTITY_CACHE_LIMIT); return o.then((e) => ({ identity: e, refreshed: true })); } /** An Enterprise GitHub principal is authoritative only after trusted-proxy admission. */ function resolveTrustedEnterpriseGitHubAccountId(e) { if (!e.authResult.ok || e.authResult.method !== "trusted-proxy" || e.authConfig?.mode !== "trusted-proxy" || normalizeLowercaseStringOrEmpty(e.authConfig.trustedProxy?.userHeader) !== "x-factory-principal") return; const t = parseEnterpriseGitHubPrincipal(e.authResult.user ?? ""); return t?.host === resolveConfiguredGitHubHost(e.config) ? t.accountId : void 0; } function createAuthenticatedGitHubIdentitySync(e) { const t = { assertCurrent: e.assertCurrent }; const measure = (t, n) => { if (!e.recordTiming) return n(); const r = performance.now(); return n().finally(() => e.recordTiming?.(t, r)); }; const reuseVerifiedBinding = async (t, n) => { if (!(t instanceof gitHubPublicApi.ControlUiGitHubError && t.retryable)) return; e.assertCurrent?.(); const r = await measure("profileBindingReadMs", () => resolveCanonicalCachedGitHubIdentity(n)); e.assertCurrent?.(); return r; }; const n = resolveTrustedEnterpriseGitHubAccountId(e); if (n) { const r = firstHeaderValue(e.requestHeaders?.["x-factory-github-login"]); const i = r && r.length <= 39 ? normalizeGitHubLogin(r) : void 0; const a = firstHeaderValue(e.requestHeaders?.["x-factory-github-name"]); const o = a && a.length <= 128 && !/[\p{Cc}\p{Cf}]/u.test(a) ? a.trim() : void 0; const s = firstHeaderValue(e.requestHeaders?.["x-factory-github-avatar-url"]); const c = normalizeVerifiedEmail(e.requestHeaders?.["x-factory-github-email"]); let l; if (s && s.length <= 512) try { const t = new URL(s); if (t.origin === `https://${resolveConfiguredGitHubHost(e.config)}` && t.pathname === `/avatars/u/${n}` && !t.username && !t.password && !t.hash) l = t.href; } catch {} if (i) return createLazyPromise(async () => { e.assertCurrent?.(); const r = await measure("profileWriteMs", () => ensureCanonicalEnterpriseGitHubProfile(e.authResult.user, o || i, t, { login: i, email: c })); e.assertCurrent?.(); return { profileId: r.id, updatedAt: r.updatedAt, enterprise: { accountId: n, login: i, ...l ? { avatarUrl: l } : {} } }; }); } const r = e.authResult.tailscaleIdentity ? classifyTailscaleLogin(e.authResult.tailscaleIdentity.login) : void 0; if (r?.kind === "provider" && r.provider === "github") return createLazyPromise(async () => { e.assertCurrent?.(); let n; try { n = await measure("profileGitHubMetadataMs", () => resolveGitHubUserIdentityByLogin(r.subject)); } catch (e) { const t = await reuseVerifiedBinding(e, { login: r.subject }); if (t) return t; throw e; } e.assertCurrent?.(); const i = await measure("profileWriteMs", () => syncCanonicalGitHubIdentity({ identity: n, authenticationAlias: { kind: "github-login", login: r.subject }, initialDisplayName: e.authResult.tailscaleIdentity?.name }, t)); e.assertCurrent?.(); return { profileId: i.id, updatedAt: i.updatedAt }; }); const i = e.authConfig?.trustedProxy; if (!e.authResult.ok || e.authResult.method !== "trusted-proxy" || e.authConfig?.mode !== "trusted-proxy" || normalizeLowercaseStringOrEmpty(i?.userHeader) !== CLOUDFLARE_ACCESS_USER_HEADER || !i?.requiredHeaders?.some((e) => normalizeLowercaseStringOrEmpty(e) === CLOUDFLARE_ACCESS_ASSERTION_HEADER)) return; const a = e.authResult.user?.trim(); const o = firstHeaderValue(e.requestHeaders?.[CLOUDFLARE_ACCESS_ASSERTION_HEADER])?.trim(); if (!a || !o) return; return createLazyPromise(async () => { e.assertCurrent?.(); const n = await measure("profileAccessIdentityMs", () => resolveCloudflareAccessIdentity(o, a, e.authConfig?.trustedProxy?.cloudflareAccessOidc)); e.assertCurrent?.(); const r = n.accountId; if (r === void 0) { const n = await measure("profileWriteMs", () => ensureCanonicalUserProfileForEmail(a, t)); e.assertCurrent?.(); return { profileId: n.id, updatedAt: n.updatedAt }; } const i = { accountId: r, email: a }; const s = githubApiToken(process.env, void 0, "github.com"); let c; try { c = await measure("profileGitHubMetadataMs", () => gitHubPublicApi.withOptionalGitHubAuth(s, (e) => resolveGitHubUserIdentityById(r, e, fetch))); } catch (o) { const s = await reuseVerifiedBinding(o, i); if (s) return s; if (n.provider === "oidc") { e.assertCurrent?.(); const n = await measure("profileWriteMs", () => ensureCanonicalUserProfileForEmail(a, { ...t, expectedGitHubAccountId: r })); e.assertCurrent?.(); return { profileId: n.id, updatedAt: n.updatedAt }; } throw o instanceof gitHubPublicApi.ControlUiGitHubError ? o : new gitHubPublicApi.ControlUiGitHubError(502, "GitHub request failed"); } e.assertCurrent?.(); if (!c.refreshed) { const t = await measure("profileBindingReadMs", () => resolveCanonicalCachedGitHubIdentity(i)); e.assertCurrent?.(); if (t) return t; } const l = await measure("profileWriteMs", () => syncCanonicalGitHubIdentity({ identity: c.identity, authenticationAlias: { kind: "email", email: a }, initialDisplayName: n.provider === "github" ? n.initialDisplayName : void 0, preserveEmailProfile: n.provider === "oidc" }, t)); e.assertCurrent?.(); return { profileId: l.id, updatedAt: l.updatedAt }; }); } //#endregion export { resolveGitHubUserIdentityByLogin as n, resolveTrustedEnterpriseGitHubAccountId as r, createAuthenticatedGitHubIdentitySync as t };