openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
9 lines • 27.1 kB
JavaScript
import{l as normalizeOptionalString}from"./string-coerce-CpTFcSwY.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{t as sha256Base64Url}from"./crypto-digest-T8X5EZni.mjs";import{h as readRuntimeConfig}from"./runtime-snapshot-Bg5K4JNu.mjs";import{t as GATEWAY_OWNER_PROFILE_ID}from"./user-profile-constants-abCq1jKI.mjs";import{r as isOperatorAuthorityUnavailable,t as GatewayOperatorAccessUnavailableError}from"./operator-authority-error-B9EU9j0W.mjs";import{m as normalizeOperatorScopeList,t as ADMIN_SCOPE}from"./operator-scopes-bEvB7E5X.mjs";import"./io-Di_yuX3t.mjs";import{n as operatorScopeSatisfied,o as roleScopesAllow,t as intersectOperatorScopes}from"./operator-scope-compat-TmgAKmD2.mjs";import{n as authorizeOperatorScopesForMethod,t as CLI_DEFAULT_OPERATOR_SCOPES}from"./method-scopes-Dalbwzsv.mjs";import{n as getBearerToken,r as getHeader}from"./http-header-value-D4bOEsPJ.mjs";import{d as openclawIdTunnelRolePolicy,i as isOpenClawIdTunnelPrincipalCurrent,u as openclawIdSubjectRolePolicy}from"./tunnel-principal-CmwEB_uz.mjs";import{c as prepareUserProfileCatalog,t as captureResidentUserProfileAccess}from"./user-profile-list-DJsakwXy.mjs";import{l as projectUserProfileDisplay}from"./user-profiles-internal-Rs7Os4Q4.mjs";import{h as resolveOperatorRolePolicyForAssignment,y as prepareSessionCreatorProfile}from"./operator-role-policy-g-dxw0h4.mjs";import{t as isNamedOperatorRoleEnforcementEnabled}from"./operator-role-enforcement-FsaRvImR.mjs";import{o as prepareUserProfileRoleAuthority}from"./user-channel-identity-operations-BbYvG0PX.mjs";import{a as resolveGatewayOperatorAccessAuthority,i as hasGatewayOperatorAccessPolicies,n as GatewayOperatorAccessDeniedError,r as hasCurrentGatewayOperatorAccess}from"./operator-access-policy-lm0chPjw.mjs";import{n as createProfileSessionEntryFilter}from"./session-sharing-read-Cm-EAfc6.mjs";import{t as shouldUseGatewayOwnerProfile}from"./gateway-owner-profile-CqplJoy-.mjs";import{a as getRemoteControlUiIngressContext,l as prepareGatewayIngressAttribution,n as PROXY_ATTRIBUTION_REQUIRED_REASON,r as assertRemoteControlUiIngressCurrent,u as readGatewayIngressTransport}from"./ingress-attribution-Ct_hJMPU.mjs";import{o as resolveBrowserOriginPolicy}from"./origin-check-CngtffS_.mjs";import{a as isGatewayDelegationCurrent,i as hasGatewayDelegationClaim,t as GATEWAY_DELEGATION_DENIED}from"./trusted-proxy-delegation-Cn2wiXdt.mjs";import{t as captureGatewayAuthPolicy}from"./auth-policy-DPmo4h9a.mjs";import{r as listControlUiPluginTabAuthGrants}from"./control-ui-plugin-tabs-DLV3mIzR.mjs";import{m as buildRateLimitIdentityKey,o as AUTH_RATE_LIMIT_SCOPE_DEVICE_TOKEN,u as AUTH_RATE_LIMIT_SCOPE_SHARED_SECRET}from"./auth-rate-limit-CJ17nIGS.mjs";import{t as withSerializedCredentialFallbackAttempt}from"./rate-limit-attempt-serialization-CLMEob1y.mjs";import{n as authorizeControlUiReadHttpGatewayConnect,r as authorizeHttpGatewayConnect}from"./auth-BwgQGI6W.mjs";import{t as checkDeviceTokenPeer}from"./device-token-binding-DqxswR4K.mjs";import{i as listDevicePairing}from"./device-pairing-DUQvqwi7.mjs";import{t as formatForLog}from"./ws-log-DRCSDKLv.mjs";import{t as resolveSharedGatewaySessionGeneration}from"./ws-shared-generation-BJ1DAER5.mjs";import{t as sendJson}from"./http-json-g_k96dZ_.mjs";import{f as sendMissingScopeForbidden,h as sendUnauthorized,l as sendGatewayAuthFailure}from"./http-common-kI7-c_LU.mjs";import{c as sendGatewayHttpAuthFailure,i as captureHttpRequestAuthority,r as bindHttpResponseAuthority,s as bindHttpOperatorAccessAuthority,t as GatewayHttpRequestAuthorityError}from"./http-request-authority-BEm1hbys.mjs";import{a as setControlUiPluginAuthCookie,r as resolveControlUiPluginAuthCookieGrants}from"./control-ui-plugin-auth-cookie-BiRoyvY_.mjs";import{t as resolveHostAccountName}from"./host-account-name-BkFUkOpX.mjs";import{a as ensureCanonicalUserProfileForOpenClawIdIdentity,i as ensureCanonicalUserProfileForEmail,o as ensureCanonicalUserProfileForTailscaleIdentity,r as ensureCanonicalGatewayOwnerProfile,t as ensureCanonicalDelegatedUserProfile}from"./user-profile-writes-C3tuxFUD.mjs";import{t as createAuthenticatedGitHubIdentitySync}from"./github-user-identity-C8exXlim.mjs";import{t as syncTrustedProxyGitCoauthor}from"./trusted-proxy-git-coauthor-ByScgXDX.mjs";import{n as verifyPairingToken}from"./pairing-token-lRcTKOil.mjs";import{i as verifyDeviceToken}from"./device-pairing-tokens-Cyh6YQaS.mjs";import{isDeepStrictEqual}from"node:util";
//!src/gateway/http-auth-user-profile.ts
const profileLog=createSubsystemLogger(`gateway/user-profiles`);function failedHttpProfileAuthentication(e){return{ok:false,authResult:{ok:false,reason:isOperatorAuthorityUnavailable(e)?`operator_access_unavailable`:e instanceof GatewayOperatorAccessDeniedError?`operator_access_denied`:`user_profile_unavailable`}}}function withOpenClawIdPrincipal(e,t){const n=openclawIdTunnelRolePolicy(t);const r=e.hasCurrentProfileAuthority;return{...e,openclawIdPrincipal:t,...n?{operatorRolePolicy:n}:{},hasCurrentProfileAuthority:()=>r?.()!==false&&isOpenClawIdTunnelPrincipalCurrent(t)}}async function checkAuthenticatedHttpUserProfile(e){try{const t=await resolveAuthenticatedHttpUserProfile(e);const n=e.authResult.method===`trusted-proxy`?e.authResult.openclawId:void 0;return{ok:true,profile:n?withOpenClawIdPrincipal(t,n):t}}catch(e){return failedHttpProfileAuthentication(e)}}function checkHttpCookieUserProfile(e,t){if(!t&&(isNamedOperatorRoleEnforcementEnabled(e)||hasGatewayOperatorAccessPolicies(e)))return failedHttpProfileAuthentication();if(!t)return{ok:true,profile:{}};try{return{ok:true,profile:resolveHttpProfile(t,e)}}catch(e){return failedHttpProfileAuthentication(e)}}async function prepareHttpUserProfileCatalog(e){if(e.writableEnded||e.destroyed)return false;let t;try{t=await prepareUserProfileCatalog()}catch{return false}const release=()=>{e.off(`finish`,release);e.off(`close`,release);t.release()};if(e.writableEnded||e.destroyed){release();return false}e.once(`finish`,release);e.once(`close`,release);return true}function usesSharedSecretGatewayMethod(e){return e===`token`||e===`password`}async function resolveAuthenticatedHttpUserProfile(e){const t=getRemoteControlUiIngressContext(e.req);if(t){assertRemoteControlUiIngressCurrent(t);const e=t.resolvePrincipal();return{authenticatedUserProfile:e.authenticatedUserProfile,openclawIdPrincipal:e.openclawIdPrincipal,preparedSessionProfile:e.preparedSessionProfile,operatorRolePolicy:e.operatorRolePolicy,operatorRoleActor:e.operatorRoleActor,operatorAccessAuthority:e.operatorAccessAuthority}}const readAdmissionPolicy=t=>({auth:{...t.gateway?.auth,identityScopes:void 0},roles:t.gateway?.roles,trustedProxies:t.gateway?.trustedProxies,allowRealIpFallback:t.gateway?.allowRealIpFallback,browserOrigin:resolveBrowserOriginPolicy({req:e.req,cfg:t})});const n=structuredClone(readAdmissionPolicy(e.cfg));const assertCurrent=()=>{if(e.authResult.delegation&&!isGatewayDelegationCurrent(e.authResult.delegation,e.getRuntimeConfig?.()??readRuntimeConfig())||e.req.aborted||e.req.socket?.destroyed||e.res?.destroyed||e.res?.writableEnded||!isDeepStrictEqual(n,readAdmissionPolicy(e.getRuntimeConfig?.()??readRuntimeConfig())))throw new Error(`HTTP profile acquisition authority expired`)};assertCurrent();const r={assertCurrent};const i=normalizeOptionalString(e.authResult.user);const a=isNamedOperatorRoleEnforcementEnabled(e.cfg);const o=e.authResult.method===`trusted-proxy`?e.authResult.openclawId:void 0;const s=hasGatewayOperatorAccessPolicies(e.cfg,{openclawIdPrincipal:o});if(!i){if(shouldUseGatewayOwnerProfile({role:`operator`,authenticatedUserId:i,authMethod:e.authResult.method,rolesConfigured:a,openclawIdOwner:e.authResult.method===`trusted-proxy`&&e.authResult.openclawId?.kind===`owner`}))try{const e=await resolveHostAccountName();assertCurrent();const t=await ensureCanonicalGatewayOwnerProfile(e,r);return await prepareHttpProfile(t.id,t.updatedAt,assertCurrent)}catch(e){assertCurrent();profileLog.warn(`owner profile resolution failed: ${formatForLog(e)}`);return{}}throw new Error(`operator role policies require a verified durable user profile`)}try{const t=createAuthenticatedGitHubIdentitySync({authResult:e.authResult,authConfig:e.cfg.gateway?.auth,config:e.cfg,requestHeaders:e.req.headers,assertCurrent});const n=e.authResult.method===`trusted-proxy`&&e.authResult.openclawId?.kind===`member`?e.authResult.openclawId:void 0;const a=e.authResult.delegation?await ensureCanonicalDelegatedUserProfile(e.authResult.delegation.identity,r):n?await ensureCanonicalUserProfileForOpenClawIdIdentity({accountId:n.accountId},r):t?await t():e.authResult.tailscaleIdentity?await ensureCanonicalUserProfileForTailscaleIdentity(e.authResult.tailscaleIdentity,r):await ensureCanonicalUserProfileForEmail(i,r);const s=`profileId`in a?a.profileId:a.id;await syncTrustedProxyGitCoauthor({authConfig:e.cfg.gateway?.auth,authResult:e.authResult,headers:e.req.headers,profileId:s,assertCurrent});const c=await prepareHttpProfile(s,a.updatedAt,assertCurrent,usesSharedSecretGatewayMethod(e.authResult.method)?void 0:e.cfg,o);const l=e.authResult.delegation;if(l){const t=c.hasCurrentProfileAuthority;return{...c,hasCurrentProfileAuthority:()=>t?.()!==false&&isGatewayDelegationCurrent(l,e.getRuntimeConfig?.()??readRuntimeConfig())}}return c}catch(t){assertCurrent();if(e.authResult.delegation||a||s)throw t;return{}}}async function prepareHttpProfile(e,t,n,r,i){n();if(r&&hasGatewayOperatorAccessPolicies(r,{openclawIdPrincipal:i})){(await prepareUserProfileCatalog()).release();n()}const a=await prepareUserProfileRoleAuthority(e);n();if(!a?.isCurrent())throw new Error(`HTTP profile authority changed during acquisition`);const o=a.display;const s=r?resolveOperatorRolePolicyForAssignment(o.id,a.role,r,a.githubLogin??null):void 0;const c=r?resolveGatewayOperatorAccessAuthority(e,r,{openclawIdPrincipal:i}):void 0;n();if(!a.isCurrent())throw new Error(`HTTP profile authority changed during acquisition`);return{...projectHttpProfile(o,t,s,c),...r?{hasCurrentProfileAuthority:a.isCurrent}:{},...r?{preparedSessionProfile:{profileId:a.profileId,aliases:new Set(a.aliases),role:a.role,githubLogin:a.githubLogin}}:{}}}function resolveHttpProfile(e,t,n){const r=captureResidentUserProfileAccess(e).assertCurrent();const i=projectUserProfileDisplay(r);const a=t?openclawIdSubjectRolePolicy(n,()=>resolveOperatorRolePolicyForAssignment(r.id,r.role??null,t,r.githubLogin??null)):void 0;const o=t&&n?.kind!==`owner`?resolveGatewayOperatorAccessAuthority(e,t,{openclawIdPrincipal:n}):void 0;return projectHttpProfile(i,r.updated_at,a,o)}function projectHttpProfile(e,t,n,r){return{authenticatedUserProfile:{profileId:e.id,displayName:e.displayName,avatarRevision:e.avatarRevision,hasAvatar:e.hasAvatar,updatedAt:t},...n?{operatorRolePolicy:n}:{},...r!==void 0?{operatorAccessAuthority:r}:{}}}function applyHttpOperatorRoleScopeCeiling(e,t){const n=t?.operatorRolePolicy?.scopes;return n?intersectOperatorScopes(e,n):e}
//!src/gateway/http-auth-plugin-cookie.ts
function resolveControlUiPluginAuthCookieGeneration(e,t){return e?sha256Base64Url(`${e}\0${captureGatewayAuthPolicy(t,null).generation}`):void 0}function readControlUiPluginCookieRequest(e,t){const n=getRemoteControlUiIngressContext(e);assertRemoteControlUiIngressCurrent(n);if(readGatewayIngressTransport(e)?.kind===`openclaw-id-tunnel`)return null;if(getBearerToken(e)||e.method!==`GET`&&e.method!==`HEAD`)return null;const r=readRuntimeConfig();if(hasGatewayDelegationClaim(e,r.gateway?.auth?.trustedProxy?.userHeader))return null;const i=resolveControlUiPluginAuthCookieGrants(e,{requestPath:t.requestPath,generation:resolveControlUiPluginAuthCookieGeneration(t.authGeneration,r)});if(i.length===0)return null;const a=i[0]?.profileId;if(i.some(e=>e.profileId!==a))return null;return{cfg:r,grants:i,profileId:a}}async function prepareControlUiPluginCookieRequest(e,t){const n=readControlUiPluginCookieRequest(e,t);if(!getRemoteControlUiIngressContext(e)&&n?.profileId&&!await prepareHttpUserProfileCatalog(t.res))return null;return authorizeControlUiPluginCookieRequest(e,t)}function authorizeControlUiPluginCookieRequest(e,t){const n=readControlUiPluginCookieRequest(e,t);if(!n)return null;const{cfg:r,grants:i,profileId:a}=n;const o=getRemoteControlUiIngressContext(e)?.resolvePrincipal();const s=o?{ok:true,profile:{authenticatedUserProfile:o.authenticatedUserProfile,openclawIdPrincipal:o.openclawIdPrincipal,operatorRolePolicy:o.operatorRolePolicy,operatorRoleActor:o.operatorRoleActor,operatorAccessAuthority:o.operatorAccessAuthority}}:checkHttpCookieUserProfile(r,a);if(!s.ok){const e=s.authResult.reason===`operator_access_unavailable`;if(e&&!t.res)throw new GatewayOperatorAccessUnavailableError;if(t.res&&(e||s.authResult.reason===`operator_access_denied`))sendGatewayHttpAuthFailure(t.res,s.authResult);return null}const c=s.profile;for(const e of i)e.scopes=normalizeOperatorScopeList(applyHttpOperatorRoleScopeCeiling(e.scopes,c))??[];if(t.res&&!bindHttpOperatorAccessAuthority(t.res,c.operatorAccessAuthority))return null;return{requestAuth:{trustDeclaredOperatorScopes:false,controlUiPluginGrants:i,...c},operatorScopes:[]}}function bindControlUiPluginCookieRequestAuthority(e,t){const n=bindHttpResponseAuthority(e.requestAuth,t.res,t.hasCurrentClientAuthority);const revalidate=async()=>{n.assertCurrent();const r=authorizeControlUiPluginCookieRequest(t.req,{requestPath:t.requestPath,authGeneration:resolveSharedGatewaySessionGeneration(t.getResolvedAuth?.()??t.auth,t.trustedProxies??readRuntimeConfig().gateway?.trustedProxies)});const i=r?.requestAuth.controlUiPluginGrants??[];n.assertCurrent();if(!isDeepStrictEqual(r?.requestAuth.operatorRolePolicy,e.requestAuth.operatorRolePolicy)||!e.requestAuth.controlUiPluginGrants.every(e=>i.some(t=>t.pluginId===e.pluginId&&t.path===e.path&&t.match===e.match&&t.profileId===e.profileId&&roleScopesAllow({role:`operator`,requestedScopes:e.scopes,allowedScopes:t.scopes})))){sendUnauthorized(t.res);throw new GatewayHttpRequestAuthorityError(`Unauthorized`)}};return{...e,requestAuth:{...n,revalidate}}}
//!src/gateway/http-operator-device-token.ts
const CONTROL_UI_OPERATOR_READ_SCOPE=`operator.read`;const CONTROL_UI_OPERATOR_ROLE=`operator`;async function verifyHttpOperatorDeviceToken(e,t,n=[]){const r=await listDevicePairing();for(const i of r.paired){const r=i.tokens?.[CONTROL_UI_OPERATOR_ROLE];if(!r||r.revokedAtMs||!verifyPairingToken(e,r.token))continue;const a=operatorScopeSatisfied(CONTROL_UI_OPERATOR_READ_SCOPE,r.scopes)?CONTROL_UI_OPERATOR_READ_SCOPE:`operator.sessions.read`;const o=await verifyDeviceToken({deviceId:i.deviceId,token:e,role:CONTROL_UI_OPERATOR_ROLE,scopes:[a,...r.scopes,...n],requiredSharedGatewaySessionGeneration:t});const s={deviceId:i.deviceId,role:CONTROL_UI_OPERATOR_ROLE};const c=await checkDeviceTokenPeer({...s,peerKey:void 0});return o.ok&&c.ok?[...r.scopes]:null}return null}
//!src/gateway/http-auth-utils.ts
function resolveHttpBrowserOriginPolicy(e,t=readRuntimeConfig()){return resolveBrowserOriginPolicy({req:e,cfg:t})}function readControlUiQueryToken(e){if(!e.url)return;try{return normalizeOptionalString(new URL(e.url,`http://localhost`).searchParams.get(`token`))}catch{return}}function resolveControlUiReadOperatorScopes(e,t,n,r){if(t===`remote-ingress`)return getRemoteControlUiIngressContext(e)?.resolvePrincipal().scopes??[];if(t===`device-token`)return applyHttpOperatorRoleScopeCeiling(n??[],r);if(t===`trusted-proxy`||t===`tailscale`)return resolveTrustedHttpOperatorScopes(e,{trustDeclaredOperatorScopes:true,...r});return t===`bootstrap-token`?[]:[...CLI_DEFAULT_OPERATOR_SCOPES]}async function checkHttpOperatorCredentials(e,t){const{auth:n,token:r}=e;const i=getRemoteControlUiIngressContext(e.req);const a=hasGatewayDelegationClaim(e.req,n.trustedProxy?.userHeader);if(a&&(i||n.mode!==`trusted-proxy`))return{authResult:{ok:false,reason:GATEWAY_DELEGATION_DENIED}};if(i){assertRemoteControlUiIngressCurrent(i);return{authResult:r?{ok:false,reason:`unauthorized`}:{ok:true,method:`remote-ingress`},authGeneration:resolveSharedGatewaySessionGeneration(n,e.trustedProxies)}}const o=prepareGatewayIngressAttribution({req:e.req,trustedProxies:e.trustedProxies,trustedProxy:n.trustedProxy,allowRealIpFallback:e.allowRealIpFallback});if(o.kind===`unattributable-proxy`)return{authResult:{ok:false,reason:o.reason}};const s=resolveHttpBrowserOriginPolicy(e.req,e.cfg);const c=o.rateLimit.subject.key;const l=Boolean(r)&&n.mode!==`trusted-proxy`&&n.mode!==`none`&&o.kind!==`openclaw-id-tunnel`;const u=e.usesQueryToken&&o.kind===`direct-local`&&n.mode!==`none`?buildRateLimitIdentityKey(s.fetchSite===`same-origin`?`control-ui-url-same-origin`:`control-ui-url`,c):void 0;const d=e.rateLimiter;const recordCredentialFailure=async e=>{if(u)d?.recordFailure(c,e);else await d?.recordFailureAndDelay(c,e)};const verify=async()=>{const i=await t({auth:n,connectAuth:r?{token:r,password:r}:null,req:e.req,browserOriginPolicy:s,trustedProxies:e.trustedProxies,allowRealIpFallback:e.allowRealIpFallback,rateLimiter:d,clientIp:c,rateLimitScope:AUTH_RATE_LIMIT_SCOPE_SHARED_SECRET,deferRateLimitFailure:l||Boolean(u)});const o=resolveSharedGatewaySessionGeneration(n,e.trustedProxies);let f=i;let p;if(!i.ok&&i.reason!==`proxy_attribution_required`&&!a&&l&&r){const recordSharedSecretFailure=async()=>{if(i.reason===`token_mismatch`||i.reason===`password_mismatch`)await recordCredentialFailure(AUTH_RATE_LIMIT_SCOPE_SHARED_SECRET)};const t=d?.check(c,AUTH_RATE_LIMIT_SCOPE_DEVICE_TOKEN);if(t&&!t.allowed){await recordSharedSecretFailure();f={ok:false,reason:`rate_limited`,rateLimited:true,retryAfterMs:t.retryAfterMs}}else{const t=await verifyHttpOperatorDeviceToken(r,o,e.requiredDeviceScopes);if(t){p=t;d?.reset(c,AUTH_RATE_LIMIT_SCOPE_DEVICE_TOKEN);f={ok:true,method:`device-token`}}else{await recordSharedSecretFailure();await recordCredentialFailure(AUTH_RATE_LIMIT_SCOPE_DEVICE_TOKEN)}}}return{authResult:f,authGeneration:o,...p?{deviceOperatorScopes:p}:{}}};const checkCredentials=()=>l&&d?withSerializedCredentialFallbackAttempt({limiter:d,ip:c,run:verify}):verify();if(!u||!e.rateLimiter)return await checkCredentials();const f=e.rateLimiter;return await withSerializedCredentialFallbackAttempt({limiter:f,ip:u,run:async()=>{const e=`control-ui-url-credential`;const t=f.check(u,e);if(!t.allowed)return{authResult:{ok:false,reason:`rate_limited`,rateLimited:true,retryAfterMs:t.retryAfterMs}};const n=await checkCredentials();if(n.authResult.ok)f.reset(u,e);else if(n.authResult.reason===`token_mismatch`||n.authResult.reason===`password_mismatch`){f.recordFailure(u,e);if(!l)f.recordFailure(c,AUTH_RATE_LIMIT_SCOPE_SHARED_SECRET)}return n}})}async function authorizeControlUiReadRequestOrReply(e){const t=e.getResolvedAuth?.()??e.auth;const n=e.cfg??readRuntimeConfig();const r=captureHttpRequestAuthority({...e,auth:t??{mode:`none`,allowTailscale:false}});if(!t){if(getRemoteControlUiIngressContext(e.req)){sendUnauthorized(e.res);return null}e.onPluginFrameGrants?.([]);return bindHttpResponseAuthority({authMethod:`none`,operatorScopes:[...CLI_DEFAULT_OPERATOR_SCOPES]},e.res,r)}const i=getBearerToken(e.req);const a=i??(e.allowQueryToken?readControlUiQueryToken(e.req):void 0);const{authResult:o,authGeneration:s,deviceOperatorScopes:c}=await checkHttpOperatorCredentials({...e,cfg:n,auth:t,token:a,usesQueryToken:Boolean(a&&!i),rateLimiter:a?e.rateLimiter:void 0},authorizeControlUiReadHttpGatewayConnect);if(!o.ok){if(e.replyOnFailure!==false)sendGatewayAuthFailure(e.res,o);return null}const l=await checkAuthenticatedHttpUserProfile({authResult:o,cfg:n,getRuntimeConfig:e.getRuntimeConfig,req:e.req,res:e.res});if(!l.ok){if(e.replyOnFailure!==false)sendGatewayHttpAuthFailure(e.res,l.authResult);return null}const u=l.profile;if(!bindHttpOperatorAccessAuthority(e.res,u.operatorAccessAuthority,e.replyOnFailure))return null;if(!r()){if(e.replyOnFailure!==false)sendUnauthorized(e.res);return null}const d=o.method??`none`;const f=resolveControlUiReadOperatorScopes(e.req,d,c,u);const p=authorizeOperatorScopesForMethod(e.requiredOperatorMethod??`assistant.media.get`,f);if(!p.allowed){if(e.replyOnFailure!==false)sendMissingScopeForbidden(e.res,p.missingScope);return null}const m=bindHttpResponseAuthority({authMethod:d,operatorScopes:f,...u},e.res,r);if(d===`device-token`&&a){const verifyCurrentDeviceToken=()=>verifyHttpOperatorDeviceToken(a,s,c);if(!await verifyCurrentDeviceToken()||!m.hasCurrentClientAuthority()){if(e.replyOnFailure!==false){m.assertCurrent();sendUnauthorized(e.res)}return null}const t=m.assertCurrent;m.revalidate=async()=>{t();const n=await verifyCurrentDeviceToken();t();if(!n){sendUnauthorized(e.res);throw new GatewayHttpRequestAuthorityError(`Unauthorized`)}}}e.onPluginFrameGrants?.(setControlUiPluginAuthCookieForRequest(e.req,e.res,s,n,f,u.authenticatedUserProfile?.profileId));return m}async function authorizeControlUiSessionOwnerReadRequestOrReply(e){const t=await authorizeControlUiReadRequestOrReply({...e,requiredOperatorMethod:`sessions.list`});if(!t)return null;if(t.operatorScopes.includes(`operator.admin`)||getRemoteControlUiIngressContext(e.req)&&t.authenticatedUserProfile?.profileId===`gateway-owner`)return{...t,canReadSession:()=>true};const n=t.preparedSessionProfile;if(!n?.profileId){sendJson(e.res,403,{ok:false,error:{message:`owner access required`,type:`forbidden`}});return null}const r=createProfileSessionEntryFilter({profileId:n.profileId,sessionCap:t.operatorRolePolicy?.sessions.others},prepareSessionCreatorProfile(n.profileId,n.aliases));return{...t,canReadSession:r}}async function authorizeGatewayHttpRequestOrReply(e,t=false){const n=await checkGatewayHttpRequestAuth(e,t);if(!n.ok){sendGatewayHttpAuthFailure(e.res,n.authResult);return null}if(!bindHttpOperatorAccessAuthority(e.res,n.requestAuth.operatorAccessAuthority))return null;return bindHttpResponseAuthority(n.requestAuth,e.res,n.requestAuth.hasCurrentClientAuthority)}function setControlUiPluginAuthCookieForRequest(e,t,n,r,i,a){if(hasGatewayDelegationClaim(e,r.gateway?.auth?.trustedProxy?.userHeader))return[];const o=listControlUiPluginTabAuthGrants(i);if(o.length>0)return setControlUiPluginAuthCookie(t,o,{generation:resolveControlUiPluginAuthCookieGeneration(n,r),basePath:r.gateway?.controlUi?.basePath,request:e,...a?{profileId:a}:{}});return[]}async function authorizePluginGatewayHttpRequestOrReply(e){const t=resolveSharedGatewaySessionGeneration(e.auth,e.trustedProxies);const n=captureHttpRequestAuthority(e);const r=await prepareControlUiPluginCookieRequest(e.req,{requestPath:e.requestPath,authGeneration:t,res:e.res});if(r){if(!n()){sendUnauthorized(e.res);return null}return bindControlUiPluginCookieRequestAuthority(r,{...e,hasCurrentClientAuthority:n})}if(e.res.writableEnded||e.res.destroyed)return null;const i=await authorizeGatewayHttpRequestOrReply(e,true);if(i?.authMethod===`device-token`){const t=getBearerToken(e.req);const n=[...i.deviceOperatorScopes??[]];const r=i.revalidate;i.revalidate=async()=>{await r();const{authResult:i}=await checkHttpOperatorCredentials({...e,auth:e.getResolvedAuth?.()??e.auth,token:t,requiredDeviceScopes:n,rateLimiter:void 0},authorizeHttpGatewayConnect);await r();if(!i.ok||i.method!==`device-token`){sendUnauthorized(e.res);throw new GatewayHttpRequestAuthorityError(`Unauthorized`)}}}return i?{requestAuth:i,operatorScopes:e.resolveOperatorScopes(e.req,i)}:null}async function checkGatewayHttpRequestAuth(e,t=false){const n=e.cfg??readRuntimeConfig();const r=captureHttpRequestAuthority(e);const i=getBearerToken(e.req);const{authResult:a,deviceOperatorScopes:o}=t||getRemoteControlUiIngressContext(e.req)?await checkHttpOperatorCredentials({...e,cfg:n,token:i},authorizeHttpGatewayConnect):{authResult:await authorizeHttpGatewayConnect({auth:e.auth,connectAuth:i?{token:i,password:i}:null,req:e.req,trustedProxies:e.trustedProxies,allowRealIpFallback:e.allowRealIpFallback,rateLimiter:e.rateLimiter,browserOriginPolicy:resolveHttpBrowserOriginPolicy(e.req,n)})};if(!a.ok)return{ok:false,authResult:a};if(!r())return{ok:false,authResult:{ok:false,reason:`unauthorized`}};const s=await checkAuthenticatedHttpUserProfile({authResult:a,cfg:n,getRuntimeConfig:e.getRuntimeConfig,req:e.req,res:e.res});if(!s.ok)return s;const c=s.profile;if(!r())return{ok:false,authResult:{ok:false,reason:`unauthorized`}};return{ok:true,requestAuth:{hasCurrentClientAuthority:()=>r()&&c.hasCurrentProfileAuthority?.()!==false&&hasCurrentGatewayOperatorAccess(c.operatorAccessAuthority),authMethod:a.method,...a.user?{user:a.user}:{},trustDeclaredOperatorScopes:a.method!==`device-token`&&!usesSharedSecretGatewayMethod(a.method),...o?{deviceOperatorScopes:applyHttpOperatorRoleScopeCeiling(o,c)}:{},...usesSharedSecretGatewayMethod(a.method)?{operatorRoleActor:{kind:`system`}}:{},...c}}}async function authorizeScopedGatewayHttpRequestOrReply(e){const t=e.cfg??readRuntimeConfig();const n=await authorizeGatewayHttpRequestOrReply({...e,cfg:t,trustedProxies:e.trustedProxies??t.gateway?.trustedProxies,allowRealIpFallback:e.allowRealIpFallback??t.gateway?.allowRealIpFallback});if(!n)return null;const r=resolveSharedSecretHttpOperatorScopes(e.req,n);const i=authorizeOperatorScopesForMethod(e.operatorMethod,r);if(!i.allowed){sendMissingScopeForbidden(e.res,i.missingScope);return null}return{cfg:t,requestAuth:n,operatorScopes:r}}function resolveTrustedHttpOperatorScopes(e,t){const n=getRemoteControlUiIngressContext(e);if(n){const t=n.resolvePrincipal().scopes;const r=getHeader(e,`x-openclaw-scopes`);return r===void 0?t:intersectOperatorScopes(t,r.split(`,`).map(e=>e.trim()).filter(Boolean))}if(!t.trustDeclaredOperatorScopes)return[];const r=getHeader(e,`x-openclaw-scopes`);const i=r===void 0?[...CLI_DEFAULT_OPERATOR_SCOPES]:r.split(`,`).map(e=>e.trim()).filter(e=>e.length>0);return applyHttpOperatorRoleScopeCeiling(i,t)}function resolveSharedSecretHttpOperatorScopes(e,t){if(usesSharedSecretGatewayMethod(t.authMethod))return[...CLI_DEFAULT_OPERATOR_SCOPES];return resolveTrustedHttpOperatorScopes(e,t)}function resolveOpenAiCompatibleHttpSenderIsOwner(e,t){return resolveSharedSecretHttpOperatorScopes(e,t).includes(ADMIN_SCOPE)}function authorizeOpenAiCompatibleHttpModelOverride(e,t){if(!normalizeOptionalString(getHeader(e,`x-openclaw-model`))||resolveOpenAiCompatibleHttpSenderIsOwner(e,t))return{allowed:true};return{allowed:false,missingScope:ADMIN_SCOPE}}export{resolveHttpProfile as _,authorizePluginGatewayHttpRequestOrReply as a,resolveHttpBrowserOriginPolicy as c,resolveTrustedHttpOperatorScopes as d,setControlUiPluginAuthCookieForRequest as f,prepareHttpUserProfileCatalog as g,applyHttpOperatorRoleScopeCeiling as h,authorizeOpenAiCompatibleHttpModelOverride as i,resolveOpenAiCompatibleHttpSenderIsOwner as l,prepareControlUiPluginCookieRequest as m,authorizeControlUiSessionOwnerReadRequestOrReply as n,authorizeScopedGatewayHttpRequestOrReply as o,authorizeControlUiPluginCookieRequest as p,authorizeGatewayHttpRequestOrReply as r,checkGatewayHttpRequestAuth as s,authorizeControlUiReadRequestOrReply as t,resolveSharedSecretHttpOperatorScopes as u};