openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
9 lines • 14.7 kB
JavaScript
import{l as normalizeOptionalString,o as normalizeLowercaseStringOrEmpty}from"./string-coerce-CpTFcSwY.mjs";import{a as resolveGlobalSet}from"./global-singleton-DolL9xGt.mjs";import{t as createSubsystemLogger}from"./subsystem-DLCDFvCH.mjs";import{n as rememberBoundedKey}from"./dedupe-CsfmSvUH.mjs";import{n as GATEWAY_CLIENT_IDS,r as GATEWAY_CLIENT_MODES}from"./client-info-Dr3-kuD1.mjs";import{a as isLoopbackAddress,c as isPrivateOrLoopbackAddress,l as isPrivateOrLoopbackHost,s as isLoopbackHost,y as resolveHostName}from"./net-Bu4cO5Pq.mjs";import{n as PROXY_ATTRIBUTION_REQUIRED_REASON}from"./ingress-attribution-Ct_hJMPU.mjs";import{t as GATEWAY_DELEGATION_DENIED}from"./trusted-proxy-delegation-Cn2wiXdt.mjs";import{r as parseComputerUseCapabilityDescriptor}from"./computer-use-contract-CaYMDN7U.mjs";import{n as normalizeNodeApprovalSurfaceList,t as intersectNodePermissionSurface}from"./node-pairing-surface-COC5mZ4f.mjs";import{o as AUTH_RATE_LIMIT_SCOPE_DEVICE_TOKEN,t as AUTH_RATE_LIMIT_SCOPE_BOOTSTRAP_TOKEN,u as AUTH_RATE_LIMIT_SCOPE_SHARED_SECRET}from"./auth-rate-limit-CJ17nIGS.mjs";import{n as withSerializedRateLimitAttempt}from"./rate-limit-attempt-serialization-CLMEob1y.mjs";import{i as authorizeWsControlUiGatewayConnect,r as authorizeHttpGatewayConnect}from"./auth-BwgQGI6W.mjs";import{i as verifyDeviceSignature}from"./device-identity-Dwje1Nh0.mjs";import{n as buildDeviceAuthPayloadV3,t as buildDeviceAuthPayload}from"./device-auth-DG7mDK4P.mjs";import{d as resolveNodePairingCommandAllowlist,l as normalizeDeclaredNodeCommands,p as retainFulfilledNodeCapabilities}from"./node-command-policy-Qm4E-4M-.mjs";import{n as confirmDevicePairSetupCompletionDelivery,r as consumeDeviceBootstrapTokenWithSetupCompletion}from"./device-bootstrap-CKmEWen4.mjs";
//!src/gateway/server/ws-connection/auth-context.ts
async function resolveConnectAuthState(e){const t=normalizeOptionalString(e.connectAuth?.token);const n=normalizeOptionalString(e.connectAuth?.password);const r=t||n?{token:t,password:n}:void 0;const i=e.hasDeviceIdentity?normalizeOptionalString(e.connectAuth?.bootstrapToken):void 0;const a=e.hasDeviceIdentity?normalizeOptionalString(e.connectAuth?.deviceToken):void 0;const o=e.hasDeviceIdentity?a??t:void 0;const s=Boolean(o);const c=await authorizeWsControlUiGatewayConnect({auth:e.resolvedAuth,connectAuth:r,req:e.req,trustedProxies:e.trustedProxies,allowRealIpFallback:e.allowRealIpFallback,rateLimiter:r?e.rateLimiter:void 0,clientIp:e.clientIp,rateLimitScope:AUTH_RATE_LIMIT_SCOPE_SHARED_SECRET,deferRateLimitFailure:s});const l=r&&await authorizeHttpGatewayConnect({auth:{...e.resolvedAuth,allowTailscale:false},connectAuth:r,req:e.req,trustedProxies:e.trustedProxies,allowRealIpFallback:e.allowRealIpFallback,rateLimitScope:`shared-secret`});const u=l?.ok===true&&(l.method===`token`||l.method===`password`)||c.ok&&c.method===`trusted-proxy`;const d=s&&(c.reason===`token_mismatch`||c.reason===`password_mismatch`);return{authResult:c,authOk:c.ok,authMethod:c.method??(e.resolvedAuth.mode===`password`?`password`:`token`),sharedAuthOk:u,pendingSharedAuthFailure:d,bootstrapTokenCandidate:i,deviceTokenCandidate:o,deviceTokenCandidateSource:a?`explicit-device-token`:o?`shared-token-fallback`:void 0}}async function resolveConnectAuthDecision(e){if(!Boolean(e.rateLimiter&&e.hasDeviceIdentity&&e.deviceId&&e.publicKey&&e.state.bootstrapTokenCandidate))return await resolveConnectAuthDecisionCore(e);return await withSerializedRateLimitAttempt({ip:e.clientIp,scope:AUTH_RATE_LIMIT_SCOPE_BOOTSTRAP_TOKEN,run:async()=>await resolveConnectAuthDecisionCore(e)})}async function resolveConnectAuthDecisionCore(e){let t=e.state.authResult;let n=e.state.authOk;let r=e.state.authMethod;let i;let a=false;async function finish(){if(e.state.pendingSharedAuthFailure&&!n)await e.rateLimiter?.recordFailureAndDelay(e.clientIp,AUTH_RATE_LIMIT_SCOPE_SHARED_SECRET);if(a&&!n)e.rateLimiter?.recordFailure(e.clientIp,AUTH_RATE_LIMIT_SCOPE_BOOTSTRAP_TOKEN);return{authResult:t,authOk:n,authMethod:r,deviceTokenSharedGatewaySessionGeneration:i}}if(t.openclawId||t.delegation||t.reason===`trusted_proxy_delegation_denied`||t.reason===`openclaw_id_not_admitted`||t.reason===`proxy_attribution_required`||t.reason===`token_redacted_config`||t.reason===`password_redacted_config`)return await finish();const o=e.state.bootstrapTokenCandidate;if(e.hasDeviceIdentity&&e.deviceId&&e.publicKey&&o){let i=false;if(e.rateLimiter){const r=e.rateLimiter.check(e.clientIp,AUTH_RATE_LIMIT_SCOPE_BOOTSTRAP_TOKEN);if(!r.allowed){i=true;if(!n||e.requireBootstrapToken){n=false;t={ok:false,reason:`rate_limited`,rateLimited:true,retryAfterMs:r.retryAfterMs}}}}if(!i){const i=await e.verifyBootstrapToken({deviceId:e.deviceId,publicKey:e.publicKey,token:o,role:e.role,scopes:e.scopes});if(i.ok){n=true;r=`bootstrap-token`;e.rateLimiter?.reset(e.clientIp,AUTH_RATE_LIMIT_SCOPE_BOOTSTRAP_TOKEN)}else{a=true;if(!n||e.requireBootstrapToken){n=false;t={ok:false,reason:i.reason??`bootstrap_token_invalid`}}}}}const s=e.state.deviceTokenCandidate;if(!e.hasDeviceIdentity||!e.deviceId||n||!s)return await finish();const c=e.rateLimiter?.check(e.clientIp,AUTH_RATE_LIMIT_SCOPE_DEVICE_TOKEN);if(c&&!c.allowed){t={ok:false,reason:`rate_limited`,rateLimited:true,retryAfterMs:c.retryAfterMs};return await finish()}const l=await e.verifyDeviceToken({deviceId:e.deviceId,token:s,role:e.role,scopes:e.scopes});if(l.ok){n=true;r=`device-token`;if(l.issuer?.kind===`shared-gateway-auth`)i=l.issuer.generation;e.rateLimiter?.reset(e.clientIp,AUTH_RATE_LIMIT_SCOPE_DEVICE_TOKEN)}else{t={ok:false,reason:l.reason===`scope-mismatch`||l.reason===`scope_mismatch`?`scope_mismatch`:e.state.deviceTokenCandidateSource===`explicit-device-token`?`device_token_mismatch`:t.reason??`device_token_mismatch`};e.rateLimiter?.recordFailure(e.clientIp,AUTH_RATE_LIMIT_SCOPE_DEVICE_TOKEN)}return await finish()}
//!src/gateway/server/ws-connection/handshake-auth-helpers.ts
const BROWSER_ORIGIN_LOOPBACK_RATE_LIMIT_IP=`198.18.0.1`;const BROWSER_ORIGIN_RATE_LIMIT_KEY_PREFIX=`browser-origin:`;function resolveBrowserOriginRateLimitKey(e){const t=URL.parse(e?.trim()??``)?.origin;return t?`${BROWSER_ORIGIN_RATE_LIMIT_KEY_PREFIX}${normalizeLowercaseStringOrEmpty(t)}`:BROWSER_ORIGIN_LOOPBACK_RATE_LIMIT_IP}function resolveHandshakeBrowserSecurityContext(e){const t=Boolean(e.requestOrigin&&e.requestOrigin.trim()!==``);return{hasBrowserOriginHeader:t,enforceOriginCheckForAnyClient:t,rateLimitClientIp:t&&isLoopbackAddress(e.clientIp)?resolveBrowserOriginRateLimitKey(e.requestOrigin):e.clientIp,authRateLimiter:t&&e.browserRateLimiter?e.browserRateLimiter:e.rateLimiter}}function shouldAllowSilentLocalPairing(e){if(e.locality===`remote`)return false;if(e.hasBrowserOriginHeader&&!e.isControlUi&&!e.isWebchat)return false;if(e.reason===`metadata-upgrade`)return!e.hasBrowserOriginHeader&&!e.isControlUi&&!e.isWebchat&&(e.locality===`direct_local`&&e.isNativeAppUi===true||e.locality===`cli_container_local`||e.locality===`shared_secret_loopback_local`);if(e.autoApproveLocal===false)return false;if(e.reason===`scope-upgrade`)return e.authMethod===`none`||e.authMethod===`token`||e.authMethod===`password`;return true}function isCliCliClient(e){return e.id===GATEWAY_CLIENT_IDS.CLI&&e.mode===GATEWAY_CLIENT_MODES.CLI}function isSharedSecretAuthMethod(e){return e===`token`||e===`password`}function resolvePairingLocality(e){if(e.isLocalClient)return`direct_local`;if(e.connectParams.client.id===GATEWAY_CLIENT_IDS.CONTROL_UI&&e.connectParams.client.mode===GATEWAY_CLIENT_MODES.WEBCHAT&&e.sharedAuthOk&&isSharedSecretAuthMethod(e.authMethod)&&!e.hasProxyHeaders&&e.hasBrowserOriginHeader&&isPrivateOrLoopbackAddress(e.remoteAddress)&&isLoopbackHost(resolveHostName(e.requestHost))&&isLoopbackHost(URL.parse(e.requestOrigin?.trim()??``)?.hostname??``))return`browser_container_local`;if(e.sharedAuthOk&&isSharedSecretAuthMethod(e.authMethod)&&!e.hasProxyHeaders&&!e.hasBrowserOriginHeader&&isLoopbackAddress(e.remoteAddress)&&isPrivateOrLoopbackHost(resolveHostName(e.requestHost)))return isCliCliClient(e.connectParams.client)?`cli_container_local`:`shared_secret_loopback_local`;return`remote`}function shouldSkipLocalBackendSelfPairing(e){const t=e.connectParams.client.id===GATEWAY_CLIENT_IDS.GATEWAY_CLIENT&&e.connectParams.client.mode===GATEWAY_CLIENT_MODES.BACKEND;const n=e.locality===`direct_local`||e.locality===`shared_secret_loopback_local`;if(!t||!n||e.hasBrowserOriginHeader)return false;return e.authMethod===`none`||e.authMethod===`device-token`||e.sharedAuthOk&&isSharedSecretAuthMethod(e.authMethod)}function shouldPreserveLocalCliSharedAuthScopes(e){return isCliCliClient(e.connectParams.client)&&(e.locality===`direct_local`||e.locality===`cli_container_local`)&&!e.hasBrowserOriginHeader&&e.sharedAuthOk&&isSharedSecretAuthMethod(e.authMethod)}function resolveDeviceSignaturePayloadVersion(e){const t={deviceId:e.device.id,clientId:e.connectParams.client.id,clientMode:e.connectParams.client.mode,role:e.role,scopes:e.scopes,signedAtMs:e.signedAtMs,token:e.connectParams.auth?.token??e.connectParams.auth?.deviceToken??e.connectParams.auth?.bootstrapToken??null,nonce:e.nonce};const n=buildDeviceAuthPayloadV3({...t,platform:e.connectParams.client.platform,deviceFamily:e.connectParams.client.deviceFamily});if(verifyDeviceSignature(e.device.publicKey,n,e.device.signature))return`v3`;const r=buildDeviceAuthPayload(t);if(verifyDeviceSignature(e.device.publicKey,r,e.device.signature))return`v2`;return null}function resolveUnauthorizedHandshakeContext(e){const t=e.connectAuth?.password?`password`:e.connectAuth?.token?`token`:e.connectAuth?.bootstrapToken?`bootstrap-token`:e.connectAuth?.deviceToken?`device-token`:`none`;const n=e.failedAuth.reason===`token_mismatch`&&e.hasDeviceIdentity&&t===`token`&&!e.connectAuth?.deviceToken;if(n)return{authProvided:t,canRetryWithDeviceToken:n,recommendedNextStep:`retry_with_device_token`};let r;switch(e.failedAuth.reason){case`token_missing`:case`token_missing_config`:case`token_redacted_config`:case`password_redacted_config`:case`password_missing`:case`password_missing_config`:r=`update_auth_configuration`;break;case`token_mismatch`:case`password_mismatch`:case`device_token_mismatch`:r=`update_auth_credentials`;break;case`rate_limited`:r=`wait_then_retry`;break;default:r=`review_auth_configuration`}return{authProvided:t,canRetryWithDeviceToken:n,recommendedNextStep:r}}
//!src/gateway/device-pair-setup-completion.ts
async function consumeSetupHandoff(e){const t=e.ts??Date.now();return consumeDeviceBootstrapTokenWithSetupCompletion({token:e.token,deviceId:e.deviceId,completedAtMs:t,admitsCloudWorkerSetup:e.admitsCloudWorkerSetup,...e.pairedDeviceMatches?{pairedDeviceMatches:e.pairedDeviceMatches}:{},...e.baseDir?{baseDir:e.baseDir}:{}})}async function confirmSetupHandoffDelivery(e){const t=e.handoff.completion;if(!t)return e.handoff;const n=await confirmDevicePairSetupCompletionDelivery({setupId:t.setupId,deviceId:t.deviceId,...e.baseDir?{baseDir:e.baseDir}:{}});return n?{record:e.handoff.record,completion:n}:null}function broadcastSetupHandoff({handoff:e,broadcast:t},n){const r=e.completion;if(r?.deliveryState!==n)return;const i={setupId:r.setupId,deviceId:r.deviceId,...r.deviceName?{deviceName:r.deviceName}:{},access:r.access,ts:r.completedAtMs};t(n===`confirmed`?`device.pair.setup.completed`:`device.pair.setup.deliveryUncertain`,i,{dropIfSlow:true})}function broadcastSetupHandoffCompletion(e){broadcastSetupHandoff(e,`confirmed`)}function broadcastSetupHandoffDeliveryUncertain(e){broadcastSetupHandoff(e,`uncertain`)}
//!src/gateway/node-connect-reconcile.ts
const log=createSubsystemLogger(`gateway/node-connect`);const warnedWithheldSets=resolveGlobalSet(Symbol.for(`openclaw.nodeConnectWithheldWarnings`),`close-and-restart`);function normalizePermissionMap(e){if(!e)return;const t=Object.entries(e).toSorted(([e],[t])=>e.localeCompare(t));return t.length>0?Object.fromEntries(t):void 0}async function reconcileNodePairingOnConnect(e){const t=e.connectParams.device?.id??e.connectParams.client.id;const n={platform:e.connectParams.client.platform,deviceFamily:e.connectParams.client.deviceFamily,caps:e.connectParams.caps,commands:e.connectParams.commands};const r=resolveNodePairingCommandAllowlist(e.cfg,n);const i=normalizeNodeApprovalSurfaceList(e.connectParams.commands);const a=normalizeDeclaredNodeCommands({declaredCommands:i,allowlist:r});const o=i.filter(e=>!a.includes(e));const s=retainFulfilledNodeCapabilities({caps:normalizeNodeApprovalSurfaceList(e.connectParams.caps),admittedCommands:a,withheldCommands:o});if(o.length>0){const e=JSON.stringify([t,[...new Set(o)].toSorted()]);const n=rememberBoundedKey(warnedWithheldSets,e,1024)?`warn`:`debug`;log[n](`node command surface withheld node=${t} commands=${o.join(`,`)}`)}const c=normalizePermissionMap(e.connectParams.permissions);const l=e.connectParams.computerUse===void 0?void 0:parseComputerUseCapabilityDescriptor(e.connectParams.computerUse);const u={nodeId:t,declaredCaps:s,declaredCommands:a,withheldCommands:o,...l?{declaredComputerUse:l}:{},declaredPermissions:c};const{pairedNode:d}=e;const f=new Set(normalizeDeclaredNodeCommands({declaredCommands:d?.commands,allowlist:r}));const p=new Set(normalizeNodeApprovalSurfaceList(d?.caps));const m=normalizePermissionMap(d?.permissions);if(d&&a.every(e=>f.has(e))&&s.every(e=>p.has(e))&&!Object.entries(c??{}).some(([e,t])=>t&&m?.[e]!==true))return{...u,effectiveCaps:s,effectiveCommands:a,effectivePermissions:c,shouldClearPendingPairings:true};const h=s.filter(e=>p.has(e));const g=a.filter(e=>f.has(e));const _=d?intersectNodePermissionSurface({approved:m,declared:c}):void 0;const{client:v}=e.connectParams;const y=await e.requestPairing({nodeId:t,displayName:v.displayName,platform:v.platform,version:v.version,deviceFamily:v.deviceFamily,modelIdentifier:v.modelIdentifier,caps:s,commands:a,permissions:c,remoteIp:e.reportedClientIp,...!d&&e.initialSurfaceSilent?{silent:true}:{}});if(!d&&!y)throw new Error(`node pairing request required`);return{...u,effectiveCaps:h,effectiveCommands:g,effectivePermissions:_,...y?{pendingPairing:y}:{}}}export{consumeSetupHandoff as a,resolvePairingLocality as c,shouldPreserveLocalCliSharedAuthScopes as d,shouldSkipLocalBackendSelfPairing as f,confirmSetupHandoffDelivery as i,resolveUnauthorizedHandshakeContext as l,resolveConnectAuthState as m,broadcastSetupHandoffCompletion as n,resolveDeviceSignaturePayloadVersion as o,resolveConnectAuthDecision as p,broadcastSetupHandoffDeliveryUncertain as r,resolveHandshakeBrowserSecurityContext as s,reconcileNodePairingOnConnect as t,shouldAllowSilentLocalPairing as u};