openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3 lines • 13.5 kB
JavaScript
import{l as normalizeOptionalString,o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{n as isRedactedSecretValue}from"./redact-sentinel-BwYTpV-q.mjs";import{t as safeEqualSecret}from"./secret-equal-BtEZdDeQ.mjs";import{r as getHeader}from"./http-header-value-D4bOEsPJ.mjs";import{a as isLoopbackAddress,b as resolveLocalInterfaceAddressMatch,d as isTrustedProxyAddress,r as isLocalDirectRequest,x as resolveRequestClientIpFromHeaders}from"./net-Bu4cO5Pq.mjs";import{f as openclawIdTunnelUser,g as resolveOpenClawIdTunnelPrincipal}from"./tunnel-principal-CmwEB_uz.mjs";import{t as isNamedOperatorRoleEnforcementEnabled}from"./operator-role-enforcement-FsaRvImR.mjs";import"./auth-resolve-UwT9_UjV.mjs";import{l as prepareGatewayIngressAttribution,n as PROXY_ATTRIBUTION_REQUIRED_REASON,u as readGatewayIngressTransport}from"./ingress-attribution-Ct_hJMPU.mjs";import{t as checkBrowserOrigin}from"./origin-check-CngtffS_.mjs";import{i as hasGatewayDelegationClaim,n as authorizeGatewayDelegation,t as GATEWAY_DELEGATION_DENIED}from"./trusted-proxy-delegation-Cn2wiXdt.mjs";import{u as AUTH_RATE_LIMIT_SCOPE_SHARED_SECRET}from"./auth-rate-limit-CJ17nIGS.mjs";import{r as isInvalidGatewaySecret,t as assertGatewayAuthNotKnownWeak}from"./known-weak-gateway-secrets-CjFHNxY3.mjs";import{n as withSerializedRateLimitAttempt}from"./rate-limit-attempt-serialization-CLMEob1y.mjs";
//!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 gatewayIngressPrincipalAuthError(e,t,n){if(n.kind===`delegated-person`)return;if(n.kind===`person`)return gatewayPersonPrincipalAuthError(e,t);if(isNamedOperatorRoleEnforcementEnabled(t))return`Owner ingress does not support gateway.roles. Use a person-bound grant approved in the Gateway Control UI.`;if(e.mode!==`token`&&e.mode!==`password`)return`Owner ingress requires gateway.auth.mode token or password without gateway.roles. Trusted-proxy Gateways require a person-bound grant.`;if(isRedactedSecretValue(e[e.mode]))return`Remote Control UI ingress cannot use a redacted Gateway credential. Replace the configured token or password with its real value locally before opening ingress.`}function gatewayPersonPrincipalAuthError(e,t,n){const r=e.trustedProxy;if(e.mode!==`trusted-proxy`||!isNamedOperatorRoleEnforcementEnabled(t)||r?.userHeader.trim().toLowerCase()!==`cf-access-authenticated-user-email`||!r.requiredHeaders?.some(e=>e.trim().toLowerCase()===`cf-access-jwt-assertion`))return`Person ingress requires trusted-proxy authentication with verified Cloudflare Access profiles and gateway.roles. Approve the grant from the person's authenticated Gateway Control UI.`;if(n&&!isTrustedProxyUserAllowed(r,n))return`Person principal is no longer permitted by gateway.auth.trustedProxy.allowUsers.`}function isTrustedProxyUserAllowed(e,t){const n=e?.allowUsers;return!n?.length||t.some(e=>n.includes(e))}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();if(hasGatewayDelegationClaim(t,r.userHeader)){const e=authorizeGatewayDelegation(t,r,c);return e?{user:c,delegation:e}:{reason:GATEWAY_DELEGATION_DENIED}}if(!isTrustedProxyUserAllowed(r,[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;const n=hasGatewayDelegationClaim(e.req,t.trustedProxy?.userHeader);const finish=e=>(n||e.user?.startsWith(`${`oce`}:`))&&!e.delegation?{ok:false,reason:GATEWAY_DELEGATION_DENIED}:e;if(n&&t.mode!==`trusted-proxy`)return{ok:false,reason:GATEWAY_DELEGATION_DENIED};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 r=e.ingressAttribution??(e.req?prepareGatewayIngressAttribution({req:e.req,trustedProxies:e.trustedProxies,trustedProxy:t.trustedProxy,allowRealIpFallback:e.allowRealIpFallback,tailscaleWhois:e.tailscaleWhois}):void 0);if(r?.kind===`unattributable-proxy`)return{ok:false,reason:PROXY_ATTRIBUTION_REQUIRED_REASON};const i=r?{...e,ingressAttribution:r}:e;const{authSurface:a,limiter:o,subject:s,rateLimitScope:c}=resolveGatewayAuthRequestContext(i);if(o&&shouldAllowTailscaleHeaderAuth(a)&&t.allowTailscale&&r?.kind===`tailscale-serve`)return await withSerializedRateLimitAttempt({ip:s,scope:c,run:async()=>finish(await authorizeGatewayConnectCore(i))});return finish(await authorizeGatewayConnectCore(i))}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(d?.kind===`openclaw-id-tunnel`)return await authorizeOpenClawIdTunnel(d.peerKey,a===`ws-control-ui`);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,...f.delegation?{delegation:f.delegation}:{}}}if(!hasGatewayDelegationClaim(r,t.trustedProxy.userHeader)&&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`}}async function authorizeOpenClawIdTunnel(e,t){const n=await resolveOpenClawIdTunnelPrincipal(e);if(!n)return{ok:false,reason:`openclaw_id_not_admitted`};if(n.kind===`node`&&!t)return{ok:false,reason:`openclaw_id_node_role_required`};const r=openclawIdTunnelUser(n);return{ok:true,method:`trusted-proxy`,...r?{user:r}:{},openclawId:n}}async function authorizeHttpGatewayConnect(e){return authorizeGatewayConnect({...e,authSurface:`http`})}async function authorizeControlUiReadHttpGatewayConnect(e){return authorizeGatewayConnect({...e,authSurface:`http-control-ui-read`})}async function authorizeWsControlUiGatewayConnect(e){return authorizeGatewayConnect({...e,authSurface:`ws-control-ui`})}export{gatewayIngressPrincipalAuthError as a,authorizeWsControlUiGatewayConnect as i,authorizeControlUiReadHttpGatewayConnect as n,gatewayPersonPrincipalAuthError as o,authorizeHttpGatewayConnect as r,assertGatewayAuthConfigured as t};