openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
5 lines • 17.6 kB
JavaScript
import{Q as validateDevicePairApproveParams,aa as validateScopeUpgradeRequest,et as validateDevicePairListParams,nt as validateDevicePairRemoveParams,oa as validateScopeUpgradeWait,ot as validateDeviceTokenRevokeParams,rt as validateDevicePairRenameParams,st as validateDeviceTokenRotateParams,tt as validateDevicePairRejectParams}from"./src-BDZMFmKa.mjs";import{n as GATEWAY_CLIENT_IDS}from"./client-info-Dr3-kuD1.mjs";import{p as isOperatorScope}from"./operator-scopes-bEvB7E5X.mjs";import{o as roleScopesAllow}from"./operator-scope-compat-TmgAKmD2.mjs";import{i as ErrorCodes}from"./missing-scope-error-CkgBgh6d.mjs";import{p as errorShape}from"./error-codes-CQNGhXT-.mjs";import{m as resolveOperatorRolePolicy}from"./operator-role-policy-g-dxw0h4.mjs";import{t as ConnectErrorDetailCodes}from"./connect-error-details-CJ6aH8Ny.mjs";import{n as GATEWAY_EVENT_DEVICE_PAIR_CHANGED}from"./events-Cmrg6oec.mjs";import{n as holdGatewayPolicyResponse}from"./ws-policy-close-piWBcH1L.mjs";import{n as normalizeDeviceAuthScopes}from"./device-auth-BxeuYK8r.mjs";import{i as listApprovedPairedDeviceRoles}from"./device-pairing-identity-B-BktV6a.mjs";import{a as invalidateNodeWakeState}from"./node-wake-state-CFYzfbEQ.mjs";import{n as forgetDeviceTokenBindings,r as hasOpenClawIdOperatorBinding}from"./device-token-binding-DqxswR4K.mjs";import{c as rejectDevicePairing,d as requestDevicePairing,f as updatePairedDeviceMetadata,i as listDevicePairing,l as removePairedDevice,n as getPendingDevicePairing,t as getPairedDevice}from"./device-pairing-DUQvqwi7.mjs";import{t as respondError}from"./response-BYbuAh7a.mjs";import{n as defineValidatedGatewayHandler,t as assertValidParams}from"./validation-CM41YclJ.mjs";import{r as summarizeDeviceTokens}from"./device-pairing-token-utils-_qLMx5_V.mjs";import{n as revokeDeviceToken,r as rotateDeviceToken}from"./device-pairing-tokens-Cyh6YQaS.mjs";import{n as approveDevicePairing,r as formatDevicePairingForbiddenMessage}from"./device-pairing-approval-CY-aWOPZ.mjs";import{n as clearRemovedNodeRuntimeState,s as reconcileRevokedDeviceWorker}from"./node-runtime-state-Cz4bb8pA.mjs";import{t as broadcastRejectedDevicePairing}from"./pairing-events-BXsG23Nv.mjs";import{a as resolveDeviceManagementAuthz,i as requestsNonOperatorDeviceRole,n as deniesDeviceTokenRoleManagement,o as resolveDeviceSessionAuthz,r as pairedDeviceHasNonOperatorRole,t as deniesCrossDeviceManagement}from"./device-management-authz-CCyFphnk.mjs";import{t as emitDeviceManagementSecurityEvent}from"./device-management-security-DbMePVRI.mjs";
//!src/gateway/server-methods/device-scope-upgrade.ts
const DEVICE_REQUIRED_MESSAGE=`device scope upgrade requires a paired browser identity; reopen OpenClaw over HTTPS or localhost, then retry`;function readUpgradeOwner(e){const t=e?.connect.device?.id.trim();const n=e?.connect.device?.publicKey.trim();return e?.connId&&e.connect.role===`operator`&&t&&n?{deviceId:t,publicKey:n}:null}function respondDeviceRequired(e){respondError(e,ErrorCodes.INVALID_REQUEST,DEVICE_REQUIRED_MESSAGE,{details:{code:ConnectErrorDetailCodes.DEVICE_IDENTITY_REQUIRED,recommendedNextStep:`reopen_control_ui_securely`}})}const scopeUpgradeHandlers={"device.scopes.requestUpgrade":defineValidatedGatewayHandler(`device.scopes.requestUpgrade`,validateScopeUpgradeRequest,async({params:e,respond:t,context:n,client:r})=>{const i=readUpgradeOwner(r);if(!i){respondDeviceRequired(t);return}const a=await getPairedDevice(i.deviceId);if(!a||a.publicKey!==i.publicKey){respondDeviceRequired(t);return}const o=normalizeDeviceAuthScopes(e.scopes);if(!o.every(isOperatorScope)){respondError(t,ErrorCodes.INVALID_REQUEST,`requested scopes contain an unknown operator scope`);return}const s=resolveOperatorRolePolicy(r,n.getRuntimeConfig());if(s&&!roleScopesAllow({role:`operator`,requestedScopes:o,allowedScopes:s.scopes})){respondError(t,ErrorCodes.INVALID_REQUEST,`requested scopes exceed your assigned operator role; ask a gateway administrator to change your role`);return}const c=r?.connect.scopes??[];if(!roleScopesAllow({role:`operator`,requestedScopes:c,allowedScopes:o})){respondError(t,ErrorCodes.INVALID_REQUEST,`requested scopes must include the connection's current scopes`);return}const l=await requestDevicePairing({deviceId:i.deviceId,publicKey:i.publicKey,displayName:r?.connect.client.displayName,platform:r?.connect.client.platform,deviceFamily:r?.connect.client.deviceFamily,clientId:r?.connect.client.id,clientMode:r?.connect.client.mode,browserOrigin:a.browserOrigin,role:`operator`,scopes:o,remoteIp:r?.clientIp,silent:false});const u=n.scopeUpgradeCoordinator;if(!u?.register({requestId:l.request.requestId,expiresAtMs:l.expiresAtMs,owner:i,requestedScopes:o,initialToken:a.tokens?.operator?.token,initialApprovedAtMs:a.approvedAtMs})){respondError(t,ErrorCodes.UNAVAILABLE,`device scope upgrade is temporarily unavailable`,{retryable:true});return}const d=Date.now();for(const e of l.superseded??[]){u.notify(e.requestId,`rejected`);broadcastRejectedDevicePairing(n.broadcast,e,d)}if(l.created)n.broadcast(`device.pair.requested`,l.request,{dropIfSlow:true});n.logGateway.warn(`security audit: live device scope upgrade requested device=${i.deviceId} scopesFrom=${c.join(`,`)} scopesTo=${o.join(`,`)}`);t(true,{requestId:l.request.requestId},void 0)}),"device.scopes.waitUpgrade":defineValidatedGatewayHandler(`device.scopes.waitUpgrade`,validateScopeUpgradeWait,async({params:e,respond:t,context:n,client:r})=>{const i=readUpgradeOwner(r);if(!i){respondDeviceRequired(t);return}const a=await n.scopeUpgradeCoordinator?.wait(e.requestId,i);if(!a){respondError(t,ErrorCodes.INVALID_REQUEST,`scope upgrade expired or not found`);return}if(a.status===`insufficient-scopes`){respondError(t,ErrorCodes.INVALID_REQUEST,`Pairing was approved, but this browser's previously narrowed token still lacks the requested access. Run openclaw dashboard --json on the Gateway host for a fresh one-time owner pairing link. Open its browserUrl in this browser using the same web app address and Gateway URL to restore administrator access.`);return}if(a.status===`approved`){const e=resolveOperatorRolePolicy(r,n.getRuntimeConfig());if(e&&!roleScopesAllow({role:`operator`,requestedScopes:a.scopes,allowedScopes:e.scopes})){respondError(t,ErrorCodes.INVALID_REQUEST,`approved scopes exceed your assigned operator role; ask a gateway administrator to change your role`);return}}t(true,a,void 0)})};
//!src/gateway/server-methods/devices.ts
const MANAGED_BY_ACCESS_MESSAGE=`This browser connects through OpenClaw ID. Manage access on the Access page.`;function isManagedByOpenClawId(e,t){return t!=null&&t.clientId===GATEWAY_CLIENT_IDS.CONTROL_UI&&!listApprovedPairedDeviceRoles(t).includes(`node`)&&hasOpenClawIdOperatorBinding(t.deviceId.trim())&&e.getRuntimeConfig().gateway?.openclawId?.enabled===true}function redactPairedDevice(e,t,n=false){const{tokens:r,approvedScopes:i,...a}=e;return{...a,...t!==void 0?{connected:t}:{},...n?{managedBy:`openclaw-id`}:{},tokens:summarizeDeviceTokens(r)}}function refuseOpenClawIdManaged(e){e.context.logGateway.warn(`${e.controlId} denied device=${e.deviceId} reason=openclaw-id-managed`);emitDevicePairingDeniedSecurityEvent({authz:e.authz,targetDeviceId:e.deviceId,controlId:e.controlId,reason:`openclaw-id-managed`,severity:`low`});e.respond(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,MANAGED_BY_ACCESS_MESSAGE))}function createDeviceTokenHandler(e){const t=`device.token.${e}`;const n=e===`rotate`?validateDeviceTokenRotateParams:validateDeviceTokenRevokeParams;return async({params:r,client:i,context:a,respond:o})=>{if(!assertValidParams(r,n,t,o))return;const{deviceId:s,role:c}=r;const l=resolveDeviceManagementAuthz(i,s);const deny=(t,n)=>{const r=e===`rotate`?`rotation`:`revocation`;const i=`device token ${r} denied`;const u=n?` scope=${n}`:``;a.logGateway.warn(`${i} device=${s} role=${c} reason=${t}${u}`);emitDeviceManagementSecurityEvent({outcome:`denied`,severity:`medium`,policyId:`gateway.device-token`,decision:`deny`,action:`device.token.${r}_denied`,authz:l,targetDeviceId:s,controlId:`device.token.${e}`,reason:t,attributes:{role:c.trim()}});o(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,i))};const u=deniesCrossDeviceManagement(l)?`device-ownership-mismatch`:deniesDeviceTokenRoleManagement(l,c)?`role-management-requires-admin`:void 0;if(u){deny(u);return}if(e===`revoke`&&isManagedByOpenClawId(a,await getPairedDevice(s.trim()))){refuseOpenClawIdManaged({authz:l,deviceId:s,controlId:`device.token.revoke`,context:a,respond:o});return}const d=c.trim()===`operator`?l.callerScopes:void 0;const f=e===`rotate`?await rotateDeviceToken({deviceId:s,role:c,scopes:r.scopes,callerScopes:d}):await revokeDeviceToken({deviceId:s,role:c,callerScopes:d});if(!f.ok){deny(f.reason,f.scope);return}const p=f.entry;const m=s.trim();if(e===`rotate`){a.logGateway.info(`device token rotated device=${s} role=${p.role} scopes=${p.scopes.join(`,`)}`);emitDeviceTokenLifecycleSecurityEvent({action:`device.token.rotated`,severity:`medium`,authz:l,targetDeviceId:s,controlId:`device.token.rotate`,role:p.role,scopeCount:p.scopes.length});if(p.role===`node`)invalidateNodeWakeState(m);try{holdGatewayPolicyResponse(o)}finally{a.invalidateClientsForDevice?.(m,{role:p.role,reason:`device-token-rotated`});queueMicrotask(()=>{a.disconnectClientsForDevice?.(m,{role:p.role})})}const e=Boolean(l.callerDeviceId&&l.callerDeviceId===l.normalizedTargetDeviceId);o(true,{deviceId:s,role:p.role,...e?{token:p.token}:{},scopes:p.scopes,rotatedAtMs:p.rotatedAtMs??p.createdAtMs,tokenDelivery:e?`in-band`:`withheld-cross-device`},void 0);return}a.logGateway.info(`device token revoked device=${m} role=${p.role}`);emitDeviceTokenLifecycleSecurityEvent({action:`device.token.revoked`,severity:`high`,authz:l,targetDeviceId:m,controlId:`device.token.revoke`,role:p.role});try{try{holdGatewayPolicyResponse(o)}finally{a.invalidateClientsForDevice?.(m,{role:p.role,reason:`device-token-revoked`});if(p.role===`node`){clearRemovedNodeRuntimeState({nodeId:m,context:a});await reconcileRevokedDeviceWorker(a,m)}}}finally{queueMicrotask(()=>{a.disconnectClientsForDevice?.(m,{role:p.role})})}o(true,{deviceId:m,role:p.role,revokedAtMs:p.revokedAtMs??Date.now()},void 0)}}async function runDevicePairingMutation(e){const t=resolveDeviceManagementAuthz(e.client,e.deviceId);let n;if(deniesCrossDeviceManagement(t))n=`device-ownership-mismatch`;else if(t.callerDeviceId&&!t.isAdminCaller){const e=await getPairedDevice(t.normalizedTargetDeviceId);if(e&&pairedDeviceHasNonOperatorRole(e))n=`role-management-requires-admin`}if(!n)return e.run(t);const r=`device pairing ${e.operation===`remove`?`removal`:`rename`} denied`;e.context.logGateway.warn(`${r} device=${e.deviceId} reason=${n}`);emitDevicePairingDeniedSecurityEvent({authz:t,targetDeviceId:e.deviceId,controlId:`device.pair.${e.operation}`,reason:n});e.respond(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,r))}function emitDevicePairingDeniedSecurityEvent(e){emitDeviceManagementSecurityEvent({action:`device.pairing.denied`,outcome:`denied`,severity:e.severity??`medium`,authz:e.authz,targetDeviceId:e.targetDeviceId,policyId:`gateway.device-pairing`,decision:`deny`,controlId:e.controlId,reason:e.reason})}function authorizePairingDecision(e,t,n,r,{respond:i,context:a}){const o=n?r.callerDeviceId&&n.deviceId.trim()!==r.callerDeviceId?`device-ownership-mismatch`:e===`approve`&&requestsNonOperatorDeviceRole(n)?`role-management-requires-admin`:void 0:void 0;if(n&&!o)return true;const s=`device pairing ${e===`approve`?`approval`:`rejection`} denied`;if(n&&o){a.logGateway.warn(`${s} request=${t} reason=${o}`);emitDevicePairingDeniedSecurityEvent({authz:r,targetDeviceId:n.deviceId,controlId:`device.pair.${e}`,reason:o})}i(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,s));return false}function emitDevicePairingLifecycleSecurityEvent(e){emitDeviceManagementSecurityEvent({...e,outcome:`success`,policyId:`gateway.device-pairing`,decision:`allow`})}function emitDeviceTokenLifecycleSecurityEvent(e){emitDeviceManagementSecurityEvent({...e,outcome:`success`,policyId:`gateway.device-token`,decision:`allow`,attributes:{role:e.role,...e.scopeCount!==void 0?{scope_count:e.scopeCount}:{}}})}const deviceHandlers={...scopeUpgradeHandlers,"device.pair.list":async({params:e,respond:t,context:n,client:r})=>{if(!assertValidParams(e,validateDevicePairListParams,`device.pair.list`,t))return;const i=await listDevicePairing();const a=resolveDeviceSessionAuthz(r);let o=i;if(a.callerDeviceId&&!a.isAdminCaller)o={pending:i.pending.filter(e=>e.deviceId.trim()===a.callerDeviceId),paired:i.paired.filter(e=>e.deviceId.trim()===a.callerDeviceId)};t(true,{pending:o.pending,paired:o.paired.map(e=>redactPairedDevice(e,n.hasConnectedClientsForDevice?.(e.deviceId.trim())??false,isManagedByOpenClawId(n,e)))},void 0)},"device.pair.approve":async({params:e,respond:t,context:n,client:r})=>{if(!assertValidParams(e,validateDevicePairApproveParams,`device.pair.approve`,t))return;const i=e.requestId.trim();const a=resolveDeviceSessionAuthz(r);if(!a.isAdminCaller){if(!authorizePairingDecision(`approve`,i,await getPendingDevicePairing(i),a,{respond:t,context:n}))return}const o=await approveDevicePairing(i,{callerScopes:a.callerScopes});if(!o){t(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,`unknown requestId`));return}if(o.status===`forbidden`){emitDevicePairingDeniedSecurityEvent({authz:a,controlId:`device.pair.approve`,reason:o.reason});t(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,formatDevicePairingForbiddenMessage(o)));return}const s=o.device.deviceId.trim();n.scopeUpgradeCoordinator?.notify(i,`approved`);if(o.nodePairingGenerationChanged){invalidateNodeWakeState(s);n.invalidateClientsForDevice?.(s,{role:`node`,reason:`device-pairing-reapproved`})}n.logGateway.info(`device pairing approved device=${o.device.deviceId} role=${o.device.role??`unknown`}`);emitDevicePairingLifecycleSecurityEvent({action:`device.pairing.approved`,severity:`low`,authz:a,targetDeviceId:o.device.deviceId,controlId:`device.pair.approve`,attributes:{role_count:o.device.roles?.length??(o.device.role?1:0),scope_count:o.device.approvedScopes?.length??o.device.scopes?.length??0}});n.broadcast(`device.pair.resolved`,{requestId:i,deviceId:o.device.deviceId,decision:`approved`,ts:Date.now()},{dropIfSlow:true});t(true,{requestId:i,device:redactPairedDevice(o.device)},void 0);if(o.nodePairingGenerationChanged)queueMicrotask(()=>{n.disconnectClientsForDevice?.(s,{role:`node`})})},"device.pair.reject":async({params:e,respond:t,context:n,client:r})=>{if(!assertValidParams(e,validateDevicePairRejectParams,`device.pair.reject`,t))return;const i=e.requestId.trim();const a=resolveDeviceSessionAuthz(r);if(a.callerDeviceId&&!a.isAdminCaller){if(!authorizePairingDecision(`reject`,i,await getPendingDevicePairing(i),a,{respond:t,context:n}))return}const o=await rejectDevicePairing(i);if(!o){t(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,`unknown requestId`));return}n.scopeUpgradeCoordinator?.notify(i,`rejected`);emitDevicePairingLifecycleSecurityEvent({action:`device.pairing.rejected`,authz:a,targetDeviceId:o.deviceId,controlId:`device.pair.reject`,severity:`low`});broadcastRejectedDevicePairing(n.broadcast,{requestId:i,deviceId:o.deviceId},Date.now());t(true,o,void 0)},"device.pair.remove":async({params:e,respond:t,context:n,client:r})=>{if(!assertValidParams(e,validateDevicePairRemoveParams,`device.pair.remove`,t))return;const{deviceId:i}=e;await runDevicePairingMutation({operation:`remove`,client:r,context:n,respond:t,deviceId:i,run:async e=>{const r=await getPairedDevice(i.trim());if(isManagedByOpenClawId(n,r)){refuseOpenClawIdManaged({authz:e,deviceId:i,controlId:`device.pair.remove`,context:n,respond:t});return}const a=await removePairedDevice(i);if(!a){t(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,`unknown deviceId`));return}clearRemovedNodeRuntimeState({nodeId:a.deviceId,context:n});try{try{holdGatewayPolicyResponse(t)}finally{n.invalidateClientsForDevice?.(a.deviceId,{reason:`device-pair-removed`});await forgetDeviceTokenBindings(a.deviceId,r?listApprovedPairedDeviceRoles(r):[]).catch(e=>{n.logGateway.warn(`device pairing removed device=${a.deviceId} but its OpenClaw ID token bindings were not cleared: ${String(e)}`)});await reconcileRevokedDeviceWorker(n,a.deviceId)}n.logGateway.info(`device pairing removed device=${a.deviceId}`);emitDevicePairingLifecycleSecurityEvent({action:`device.pairing.removed`,severity:`medium`,authz:e,targetDeviceId:a.deviceId,controlId:`device.pair.remove`});t(true,a,void 0)}finally{queueMicrotask(()=>{n.disconnectClientsForDevice?.(a.deviceId)})}}})},"device.pair.rename":async({params:e,respond:t,context:n,client:r})=>{if(!assertValidParams(e,validateDevicePairRenameParams,`device.pair.rename`,t))return;const{deviceId:i,label:a}=e;const o=a.trim();if(!o){t(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,`label required`));return}await runDevicePairingMutation({operation:`rename`,client:r,context:n,respond:t,deviceId:i,run:async e=>{if(!await updatePairedDeviceMetadata(i,{operatorLabel:o})){t(false,void 0,errorShape(ErrorCodes.INVALID_REQUEST,`unknown deviceId`));return}n.logGateway.info(`device pairing renamed device=${i} label=${o}`);emitDevicePairingLifecycleSecurityEvent({action:`device.pairing.renamed`,severity:`low`,authz:e,targetDeviceId:i,controlId:`device.pair.rename`});n.broadcast(GATEWAY_EVENT_DEVICE_PAIR_CHANGED,{},{dropIfSlow:true});t(true,{deviceId:i,label:o},void 0)}})},"device.token.rotate":createDeviceTokenHandler(`rotate`),"device.token.revoke":createDeviceTokenHandler(`revoke`)};export{deviceHandlers};