UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

323 lines (322 loc) • 12.5 kB
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty } from "./string-coerce-CCIiB4H7.mjs"; import { n as isRedactedSecretValue } from "./redact-sentinel-Db2p5Put.mjs"; import { t as safeEqualSecret } from "./secret-equal-BogABOFr.mjs"; import { r as getHeader } from "./http-header-value-BTQlMYRm.mjs"; import { a as isLoopbackAddress, b as resolveLocalInterfaceAddressMatch, d as isTrustedProxyAddress, r as isLocalDirectRequest, x as resolveRequestClientIpFromHeaders } from "./net-BgRayX-P.mjs"; import { c as AUTH_RATE_LIMIT_SCOPE_SHARED_SECRET } from "./auth-rate-limit-DGfPTrXr.mjs"; import { c as prepareGatewayIngressAttribution, l as readGatewayIngressTransport, n as PROXY_ATTRIBUTION_REQUIRED_REASON } from "./ingress-attribution-DAAQgd6y.mjs"; import { r as isInvalidGatewaySecret, t as assertGatewayAuthNotKnownWeak } from "./known-weak-gateway-secrets-DrP6ACfl.mjs"; import { t as checkBrowserOrigin } from "./origin-check-C_9X1y_u.mjs"; import { n as withSerializedRateLimitAttempt } from "./rate-limit-attempt-serialization-B_N04LLR.mjs"; import "./auth-resolve-C6_i-P4T.mjs"; //#region src/gateway/auth.ts const LEGACY_OPENCLAW_ENV_NOTE = " Legacy CLAWDBOT_* and MOLTBOT_* environment variables are ignored; use OPENCLAW_* names."; function resolveGatewayAuthRequestContext(e) { const { req: t, trustedProxies: n } = e; const r = e.authSurface ?? "http"; const i = e.ingressAttribution?.kind === "unattributable-proxy" ? void 0 : e.ingressAttribution; const a = i?.clientIp ?? resolveRequestClientIpFromHeaders(t, n, e.allowRealIpFallback === true) ?? t?.socket?.remoteAddress; const o = i ? i.kind === "direct-local" : isLocalDirectRequest(t); return { authSurface: r, limiter: e.rateLimiter, subject: i && !o ? i.rateLimit.subject.key : e.clientIp ?? i?.rateLimit.subject.key ?? a, rateLimitScope: e.rateLimitScope ?? "shared-secret", localDirect: o, resetOnSuccess: i?.rateLimit.resetOnSuccess ?? true, ingressAttribution: e.ingressAttribution }; } function hasExplicitSharedSecretAuth(e) { return Boolean(normalizeOptionalString(e?.token) || normalizeOptionalString(e?.password)); } function resolveConnectSecret(e, t) { return t?.[e] ?? t?.[e === "token" ? "password" : "token"]; } function assertGatewayAuthConfigured(e, t) { if ((e.mode === "token" || e.mode === "password") && isRedactedSecretValue(e[e.mode])) assertGatewayAuthNotKnownWeak(e); if (e.mode === "token" && isInvalidGatewaySecret(e.token)) throw new Error("Gateway token must not be blank or the literal string undefined/null. Run `openclaw doctor --fix --generate-gateway-token` for an inline token, or rotate its external secret source."); if (e.mode === "token" && !e.token) { if (e.allowTailscale) return; throw new Error(`gateway auth mode is token, but no token was configured (set gateway.auth.token or OPENCLAW_GATEWAY_TOKEN).${LEGACY_OPENCLAW_ENV_NOTE}`); } if (e.mode === "password" && !e.password) { if (t?.password != null && typeof t.password !== "string") throw new Error("gateway auth mode is password, but gateway.auth.password contains a provider reference object instead of a resolved string — bootstrap secrets (gateway.auth.password) must be plaintext strings or set via the OPENCLAW_GATEWAY_PASSWORD environment variable because the secrets provider system has not initialised yet at gateway startup"); throw new Error(`gateway auth mode is password, but no password was configured.${LEGACY_OPENCLAW_ENV_NOTE}`); } if (e.mode === "trusted-proxy") { if (!e.trustedProxy) throw new Error("gateway auth mode is trusted-proxy, but no trustedProxy config was provided (set gateway.auth.trustedProxy)"); if (!e.trustedProxy.userHeader || e.trustedProxy.userHeader.trim() === "") throw new Error("gateway auth mode is trusted-proxy, but trustedProxy.userHeader is empty (set gateway.auth.trustedProxy.userHeader)"); if (e.token) throw new Error("gateway auth mode is trusted-proxy, but a shared token is also configured; remove gateway.auth.token / OPENCLAW_GATEWAY_TOKEN because trusted-proxy and token auth are mutually exclusive"); } } function authorizeTrustedProxy(e) { const { req: t, trustedProxies: n, trustedProxyConfig: r } = e; if (!t) return { reason: "trusted_proxy_no_request" }; const i = t.socket?.remoteAddress; if (!i || !isTrustedProxyAddress(i, n)) return { reason: "trusted_proxy_untrusted_source" }; const a = isLoopbackAddress(i); if (a && r.allowLoopback !== true) return { reason: "trusted_proxy_loopback_source" }; if (!a) { const e = resolveLocalInterfaceAddressMatch(i); if (e === void 0) return { reason: "trusted_proxy_local_interface_check_failed" }; if (e) return { reason: "trusted_proxy_local_interface_source" }; } const o = r.requiredHeaders ?? []; for (const e of o) { const n = getHeader(t, e); if (!n || n.trim() === "") return { reason: `trusted_proxy_missing_header_${e}` }; } const s = getHeader(t, r.userHeader); if (!s || s.trim() === "") return { reason: "trusted_proxy_user_missing" }; const c = s.trim(); const l = r.allowUsers ?? []; if (l.length > 0 && !l.includes(c)) return { reason: "trusted_proxy_user_not_allowed" }; return { user: c }; } function shouldAllowTailscaleHeaderAuth(e) { return e === "ws-control-ui" || e === "http-control-ui-read"; } function authorizeHttpBrowserOrigin(e) { if (e.authSurface === "ws-control-ui") return null; const t = e.browserOriginPolicy?.origin?.trim(); if (!t) return e.requireSameOriginFetchWithoutOrigin && normalizeLowercaseStringOrEmpty(e.browserOriginPolicy?.fetchSite) !== "same-origin" ? { ok: false, reason: e.reason } : null; return checkBrowserOrigin({ requestHost: e.browserOriginPolicy?.requestHost, origin: t, allowedOrigins: e.allowWildcardOrigin === false ? e.browserOriginPolicy?.allowedOrigins?.filter((e) => normalizeLowercaseStringOrEmpty(e) !== "*") : e.browserOriginPolicy?.allowedOrigins, allowHostHeaderOriginFallback: e.browserOriginPolicy?.allowHostHeaderOriginFallback, isLocalClient: e.isLocalClient }).ok ? null : { ok: false, reason: e.reason }; } function authorizeTrustedProxyBrowserOrigin(e) { return authorizeHttpBrowserOrigin({ ...e, isLocalClient: false, reason: "trusted_proxy_origin_not_allowed" }); } async function authorizeSharedSecretAuth(e) { if (e.method === "password" && isRedactedSecretValue(e.configuredSecret)) return { ok: false, reason: "password_redacted_config" }; if (!e.configuredSecret || e.method === "token" && isInvalidGatewaySecret(e.configuredSecret)) return { ok: false, reason: `${e.method}_missing_config` }; if (!e.providedSecret) return { ok: false, reason: `${e.method}_missing` }; if (!safeEqualSecret(e.providedSecret, e.configuredSecret)) { if (!e.deferRateLimitFailure) await e.limiter?.recordFailureAndDelay(e.ip, e.rateLimitScope); return { ok: false, reason: `${e.method}_mismatch` }; } if (e.resetOnSuccess !== false) e.limiter?.reset(e.ip, e.rateLimitScope); return { ok: true, method: e.method }; } function rejectIfRateLimited(e) { if (!e.limiter) return; const t = e.limiter.check(e.ip, e.rateLimitScope); if (t.allowed) return; return { ok: false, reason: "rate_limited", rateLimited: true, retryAfterMs: t.retryAfterMs }; } async function authorizeGatewayConnect(e) { const { auth: t } = e; if ((t.mode === "token" || t.mode === "password") && isRedactedSecretValue(t[t.mode])) return { ok: false, reason: `${t.mode}_redacted_config` }; if (e.ingressAttribution?.kind === "remote-forwarded" || e.req && readGatewayIngressTransport(e.req)?.kind === "remote-forwarded") return { ok: false, reason: "remote_control_ui_device_auth_required" }; if (t.mode === "trusted-proxy") { if (!t.trustedProxy) return { ok: false, reason: "trusted_proxy_config_missing" }; if (!e.trustedProxies || e.trustedProxies.length === 0) return { ok: false, reason: "trusted_proxy_no_proxies_configured" }; } const n = e.ingressAttribution ?? (e.req ? prepareGatewayIngressAttribution({ req: e.req, trustedProxies: e.trustedProxies, allowRealIpFallback: e.allowRealIpFallback, tailscaleWhois: e.tailscaleWhois }) : void 0); if (n?.kind === "unattributable-proxy") return { ok: false, reason: PROXY_ATTRIBUTION_REQUIRED_REASON }; const r = n ? { ...e, ingressAttribution: n } : e; const { authSurface: i, limiter: a, subject: o, rateLimitScope: s } = resolveGatewayAuthRequestContext(r); if (a && shouldAllowTailscaleHeaderAuth(i) && t.allowTailscale && n?.kind === "tailscale-serve") return await withSerializedRateLimitAttempt({ ip: o, scope: s, run: async () => await authorizeGatewayConnectCore(r) }); return await authorizeGatewayConnectCore(r); } async function authorizeGatewayConnectCore(e) { const { auth: t, connectAuth: n, req: r, trustedProxies: i } = e; const { authSurface: a, limiter: o, subject: s, rateLimitScope: c, localDirect: l, resetOnSuccess: u, ingressAttribution: d } = resolveGatewayAuthRequestContext(e); const f = shouldAllowTailscaleHeaderAuth(a); const p = hasExplicitSharedSecretAuth(n); if (a === "http-control-ui-read" && t.allowTailscale && !l && !p) { const t = authorizeHttpBrowserOrigin({ authSurface: a, browserOriginPolicy: e.browserOriginPolicy, isLocalClient: l, reason: "origin_not_allowed", requireSameOriginFetchWithoutOrigin: true, allowWildcardOrigin: false }); if (t) return t; } if (t.mode === "trusted-proxy") { if (!t.trustedProxy) return { ok: false, reason: "trusted_proxy_config_missing" }; const f = authorizeTrustedProxy({ req: r, trustedProxies: i, trustedProxyConfig: t.trustedProxy }); if ("user" in f) { if (d?.kind !== "trusted-proxy") return { ok: false, reason: PROXY_ATTRIBUTION_REQUIRED_REASON }; const t = authorizeTrustedProxyBrowserOrigin({ authSurface: a, browserOriginPolicy: e.browserOriginPolicy }); if (t) return t; return { ok: true, method: "trusted-proxy", user: f.user }; } if (l && t.password && n?.password) { const r = rejectIfRateLimited({ limiter: o, ip: s, rateLimitScope: c }); if (r) return r; return await authorizeSharedSecretAuth({ method: "password", configuredSecret: t.password, providedSecret: n.password, limiter: o, ip: s, rateLimitScope: c, deferRateLimitFailure: e.deferRateLimitFailure, resetOnSuccess: u }); } return { ok: false, reason: f.reason }; } if (t.mode === "none") { if (d?.kind === "trusted-proxy" && d.externalTailscaleExposure === "funnel") return { ok: false, reason: "gateway_auth_required" }; const t = authorizeHttpBrowserOrigin({ authSurface: a, browserOriginPolicy: e.browserOriginPolicy, isLocalClient: l, reason: "origin_not_allowed" }); if (t) return t; return { ok: true, method: "none" }; } if (f && t.allowTailscale && !l && d?.kind === "tailscale-serve" && !p) { const e = await d.verifyIdentity(); if (e) { o?.reset(s, c); return { ok: true, method: "tailscale", user: e.login, tailscaleIdentity: e }; } } const m = rejectIfRateLimited({ limiter: o, ip: s, rateLimitScope: c }); if (m) return m; if (t.mode === "token" || t.mode === "password") return await authorizeSharedSecretAuth({ method: t.mode, configuredSecret: t[t.mode], providedSecret: resolveConnectSecret(t.mode, n), limiter: o, ip: s, rateLimitScope: c, deferRateLimitFailure: e.deferRateLimitFailure, resetOnSuccess: u }); await o?.recordFailureAndDelay(s, c); return { ok: false, reason: "unauthorized" }; } /** Authorize an HTTP gateway request with Tailscale forwarded-header auth disabled. */ async function authorizeHttpGatewayConnect(e) { return authorizeGatewayConnect({ ...e, authSurface: "http" }); } /** Authorize a read-only Control UI HTTP request, including verified Tailscale identity. */ async function authorizeControlUiReadHttpGatewayConnect(e) { return authorizeGatewayConnect({ ...e, authSurface: "http-control-ui-read" }); } /** Authorize a Control UI websocket request with the WS-specific auth surface. */ async function authorizeWsControlUiGatewayConnect(e) { return authorizeGatewayConnect({ ...e, authSurface: "ws-control-ui" }); } //#endregion export { authorizeWsControlUiGatewayConnect as i, authorizeControlUiReadHttpGatewayConnect as n, authorizeHttpGatewayConnect as r, assertGatewayAuthConfigured as t };