openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
3,959 lines • 156 kB
JavaScript
import { l as normalizeOptionalString, t as hasNonEmptyString } from "./string-coerce-CCIiB4H7.mjs";
import { a as asOptionalRecord, i as asOptionalObjectRecord, p as readStringField } from "./record-coerce-CVPuDqcc.mjs";
import { r as runWithMainThreadTask } from "./main-thread-stall-BhUfYJnA.mjs";
import { b as uniqueStrings, d as normalizeSortedUniqueTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs";
import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs";
import { o as racePromiseWithAbortSignal } from "./src-BPmQBLJp.mjs";
import "./abort-signal-D4Q6SEw7.mjs";
import { t as formatErrorMessage } from "./errors-BKzCeTYb.mjs";
import { t as createDeferredCore } from "./deferred-D0La5CRk.mjs";
import { t as getActivePluginGatewayNodePolicyRegistry } from "./runtime-state-DVrhXeqI.mjs";
import { n as normalizeAgentId } from "./agent-id-CQjtp2ft.mjs";
import "./session-key-CqAyZeVk.mjs";
import { i as listAgentIds } from "./agent-roster-t1ooUdXp.mjs";
import "./agent-scope-config-DmXgFGKP.mjs";
import { l as emitTrustedSecurityEvent } from "./diagnostic-events-BjAH1Kbx.mjs";
import { T as runWithDiagnosticTraceContext, g as createDiagnosticTraceContext, h as createChildDiagnosticTraceContext, w as parseDiagnosticTraceparent } from "./diagnostics-timeline-CSwiG24r.mjs";
import { l as resolveRuntimeServiceVersion, o as resolveRuntimeServiceBuildId } from "./version-GlxUMdxI.mjs";
import { r as sha256HexPrefixCore } from "./node-crypto-B6yuTjmm.mjs";
import { t as sha256Base64Url } from "./crypto-digest-B2m8wIBj.mjs";
import { i as getOrCreatePromise, n as createLazyPromise } from "./lazy-promise-DiCvjz9w.mjs";
import { n as compareOpenClawReleaseVersions } from "./npm-registry-spec-HKkAvl6N.mjs";
import { c as normalizeEd25519PublicKeyBase64Url } from "./ed25519-signature-CUaH7IDK.mjs";
import { a as getRuntimeConfigSnapshot, h as readRuntimeConfig } from "./runtime-snapshot-WbwbY5b7.mjs";
import { a as hasGatewayClientCap, n as GATEWAY_CLIENT_IDS, o as isNativeAppUiClient, r as GATEWAY_CLIENT_MODES, t as GATEWAY_CLIENT_CAPS } from "./client-info-Cm1BcrMm.mjs";
import { Pt as validateRequestFrame, Z as validateConnectParams } from "./src-BX8OAe1J.mjs";
import { n as APPROVALS_SCOPE, r as PAIRING_SCOPE, t as ADMIN_SCOPE, u as WRITE_SCOPE } from "./operator-scopes-CULmYfyY.mjs";
import "./io-4QsrsWTJ.mjs";
import { i as runUtf8CommandWithTimeout } from "./exec-runner-Br73vG-X.mjs";
import "./exec-aRIvS9s4.mjs";
import { M as tryBeginGatewayRootWorkAdmission, d as isGatewayRestartDraining, j as tryBeginGatewayRestartStartupRootWorkAdmission, l as getGatewaySuspendAdmissionPhase, w as runWithGatewayIndependentRootWorkAdmission, x as runOutsideGatewayRootWorkAdmission } from "./gateway-work-admission-79pid1hQ.mjs";
import { a as gatewayStartupUnavailableDetails, i as GATEWAY_STARTUP_PENDING_CLOSE_CAUSE, n as GATEWAY_STARTUP_CLOSE_CODE, r as GATEWAY_STARTUP_CLOSE_REASON } from "./startup-unavailable-DEGJREFb.mjs";
import { C as formatValidationErrors } from "./worker-protocol-primitives-DsbWJKRA.mjs";
import { o as roleScopesAllow, t as intersectOperatorScopes } from "./operator-scope-compat-CpFHu-FC.mjs";
import "./method-scopes-Dpyb0Ck-.mjs";
import { a as isLoopbackAddress, c as isPrivateOrLoopbackAddress, d as isTrustedProxyAddress, i as isLocalishHost } from "./net-BgRayX-P.mjs";
import { i as isGatewayCliClient, l as isWebchatClient, n as isBrowserOperatorUiClient, r as isEphemeralGatewayClient, s as isOperatorUiClient, t as isBrowserCopilotClient } from "./message-channel-DTYVLJT1.mjs";
import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs";
import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs";
import { i as hasMultipleResidentSessionSharingIdentities } from "./user-profile-list-D7DDbqt5.mjs";
import { h as resolveOperatorRolePolicyForAssignment, m as resolveOperatorRolePolicy, o as onOperatorRolePolicyChanged } from "./operator-role-policy-DhcqVpmG.mjs";
import { t as MAX_PAYLOAD_BYTES } from "./payload-limits-ChDi8AHf.mjs";
import { r as GATEWAY_SUSPEND_UNAVAILABLE_REASON, t as GATEWAY_RESTART_UNAVAILABLE_REASON } from "./restart-unavailable-CqvsgSBG.mjs";
import { t as GATEWAY_SERVER_CAPS } from "./server-capabilities-BDosLJeN.mjs";
import { i as PROTOCOL_VERSION, n as MIN_NODE_PROTOCOL_VERSION, r as MIN_PROBE_PROTOCOL_VERSION } from "./version-CwNT1gaY.mjs";
import { o as upsertPresence, t as commitPresence } from "./system-presence-Dj1W_mp4.mjs";
import { n as resolveGatewayAgentSelectionState } from "./agent-list-eAuBkvho.mjs";
import { c as AUTH_RATE_LIMIT_SCOPE_SHARED_SECRET, o as AUTH_RATE_LIMIT_SCOPE_NODE_PAIRING } from "./auth-rate-limit-DGfPTrXr.mjs";
import { a as getRemoteControlUiIngressContext, n as PROXY_ATTRIBUTION_REQUIRED_REASON, o as hasCurrentRemoteControlUiIngress, r as assertRemoteControlUiIngressCurrent } from "./ingress-attribution-DAAQgd6y.mjs";
import { t as resolveGatewayPublicOrigin } from "./gateway-public-origin-SLjx6A2a.mjs";
import { i as normalizeChromeExtensionOrigin, n as checkGatewayWsBrowserOrigin, r as isGatewayHostBrowserOrigin } from "./origin-check-C_9X1y_u.mjs";
import { n as withSerializedRateLimitAttempt, t as withSerializedCredentialFallbackAttempt } from "./rate-limit-attempt-serialization-B_N04LLR.mjs";
import { o as canReadDetailedUpdateMetadata } from "./events-BxTs-VBE.mjs";
import { h as resolveDeviceAuthConnectErrorDetailCode, i as buildPairingConnectErrorMessage, m as resolveAuthConnectErrorDetailCode, n as buildPairingConnectCloseReason, r as buildPairingConnectErrorDetails, t as ConnectErrorDetailCodes } from "./connect-error-details-BdhXf496.mjs";
import { t as authenticatedProfileUnavailableError } from "./gateway-client-identity-BkzV3v8p.mjs";
import { n as getSessionRowProjection } from "./session-row-projection-access-CjLImwLs.mjs";
import { t as allowedSessionVisibilities } from "./session-sharing-policy-3TAaxC-R.mjs";
import { a as prepareGatewayLocalUserIngress, t as attachGatewayLocalUserIngress } from "./local-user-ingress-CLpC74uh.mjs";
import { t as classifyTailscaleLogin } from "./user-profiles-tailscale-login-DtoF4wFU.mjs";
import { o as prepareUserProfileRoleAuthority } from "./user-channel-identity-operations-6wbdZymd.mjs";
import { d as prepareGatewayRecipientProfile, u as createExpectedProfileBinding } from "./session-sharing-read-BqjuH16A.mjs";
import "./session-sharing-BIP3raq1.mjs";
import { n as getHealthCache, r as getHealthVersion, t as buildGatewaySnapshot } from "./health-state-C4YLLrF7.mjs";
import { a as MAX_PREAUTH_PAYLOAD_BYTES, i as MAX_BUFFERED_BYTES, o as TICK_INTERVAL_MS } from "./server-constants-CYohpfLc.mjs";
import { a as registerGatewayPolicyResponse, i as onGatewayPolicyClientInvalidated, r as invalidateGatewayPolicyClient, t as hasCurrentGatewayPolicyClientSource } from "./ws-policy-close-Cspv0w92.mjs";
import { h as setClientPluginNodeCapability, o as indexPluginNodeCapabilitySurfaces, p as resolvePluginNodeCapabilityExpiresAtMs, r as buildPluginNodeCapabilityScopedHostUrl, s as mintPluginNodeCapabilityToken } from "./plugin-node-capability-DIz0zxpb.mjs";
import { r as createGatewayRpcDiagnostics, t as GatewayRpcDiagnostics } from "./request-diagnostics-cMTWTAK4.mjs";
import { r as captureGatewayDeviceRevocation } from "./device-revocation-Cbich35f.mjs";
import { t as shouldUseGatewayOwnerProfile } from "./gateway-owner-profile--usQDxAz.mjs";
import { a as resolveGatewayOperatorAccessAuthority, i as hasGatewayOperatorAccessPolicies, n as GatewayOperatorAccessDeniedError, r as hasCurrentGatewayOperatorAccess, t as GATEWAY_OPERATOR_ACCESS_DENIED_MESSAGE } from "./operator-access-policy-BWvd6twL.mjs";
import { t as resolveIdentityOperatorScopes } from "./operator-identity-scopes-CltjA6id.mjs";
import { a as listControlUiPluginWidgetKinds, i as listControlUiPluginTabs, t as listControlUiLinkReaders } from "./control-ui-plugin-tabs-C_6CJE64.mjs";
import { t as normalizeControlUiBasePath } from "./control-ui-shared-_tUmz6W8.mjs";
import { i as isGatewaySuspendControlAvailable } from "./gateway-suspend-coordinator-DwPh5h96.mjs";
import { r as loadPairedDevicePairingStoreRecordReadOnly } from "./device-pairing-store-readonly-CIEEZowO.mjs";
import { i as recordRemoteNodeInfo, o as refreshRemoteNodeBins } from "./remote-BFNOi3gh.mjs";
import { c as deviceBootstrapProfilesEqual, d as isVoiceNodePairingSetupBootstrapProfile, h as resolveBootstrapProfileScopesForRoles, l as isMobilePairingSetupBootstrapProfile, m as resolveBootstrapProfileScopesForRole, n as CLOUD_WORKER_PAIRING_SETUP_BOOTSTRAP_PROFILE, r as CONTROL_UI_OWNER_BOOTSTRAP_PROFILE, t as BOOTSTRAP_HANDOFF_OPERATOR_SCOPES, u as isNodePairingSetupBootstrapProfile } from "./device-bootstrap-profile-COYynVlw.mjs";
import { a as listEffectivePairedDeviceRoles, i as listApprovedPairedDeviceRoles, n as hasEffectivePairedDeviceRole, s as resolveAuthenticatedDeviceTokenIdentity } from "./device-pairing-identity-BqPJxbIo.mjs";
import { n as normalizeNodeApprovalSurfaceList } from "./node-pairing-surface-0CH0V-VR.mjs";
import { f as requestNodePairing, n as beginNodePairingConnect, o as recordPairedNodeConnection, r as finalizeNodePairingCleanupClaim, t as approveNodePairing, u as releaseNodePairingCleanupClaim } from "./device-pairing-node-CoZTLZY1.mjs";
import { i as scheduleNodeConnectionNotification, n as resolveGatewayWsBrowserOrigin, o as retireDeviceTokenClients, r as projectHealthSummary } from "./ws-origin-policy-CWX73XV0.mjs";
import { t as GatewayClientRequestError } from "./request-error-C4C6eD0S.mjs";
import { t as buildAuthenticatedPresenceUser } from "./authenticated-presence-user-cWd9lfpl.mjs";
import { d as requestDevicePairing, g as waitForDevicePairingResolution, i as listDevicePairing, o as pruneSupersededSilentPairedDevices, s as recordPairedDeviceAccess, t as getPairedDevice } from "./device-pairing-D--Fzrek.mjs";
import { n as logRejectedLargePayload } from "./diagnostic-payload-KWldAlR0.mjs";
import { i as summarizeSessionListForWsLog, n as logWs, t as formatForLog } from "./ws-log-CbOV6uhk.mjs";
import { n as isGatewayAuthGrantCurrent, r as isGatewayAuthPolicyCurrent, t as captureGatewayAuthPolicy } from "./auth-policy-CR6nKvhI.mjs";
import { t as SharedGatewaySessionGenerationState } from "./server-shared-auth-generation-BosbfyX3.mjs";
import { t as resolveSharedGatewaySessionGeneration } from "./ws-shared-generation-BWsSp-Zl.mjs";
import { t as getTailscalePublishedOrigin } from "./tailscale-published-origin-Bvc-skoM.mjs";
import { i as classifyGatewayStaleInstall } from "./stale-install-DESh14Fs.mjs";
import { o as resolveBrowserAuthOrigin } from "./provider-browser-auth-CczEsRoa.mjs";
import { t as resolveLocalNodeId } from "./local-id-DS74LcqM.mjs";
import { t as errorShapeFromError } from "./error-shape-BcwiXcnc.mjs";
import { r as normalizeDeviceMetadataForAuth } from "./device-auth-D9CpjNQV.mjs";
import { t as rawDataToString } from "./websocket-data-BMMkrJdl.mjs";
import { t as deriveDeviceIdFromPublicKey } from "./device-identity-JBn8J50B.mjs";
import { t as resolveGatewayClientPlatformIdentity } from "./gateway-client-platform-DW3cGQgF.mjs";
import { t as SYSTEM_RUN_EXECUTION_CONTEXT_CAPABILITY } from "./system-run-execution-context-UpbI778p.mjs";
import { i as verifyAgentRuntimeIdentityToken } from "./agent-runtime-identity-token-BK52eBqW.mjs";
import { n as isOperatorApprovalRuntimeToken } from "./operator-approval-runtime-token-C1wLoQal.mjs";
import { r as bindWebSocketRequestMutationAuthority } from "./session-mutation-guards-Bjnk_O0z.mjs";
import { t as rawDataByteLength } from "./ws-DFZcrj1T.mjs";
import { n as resolveControlUiLinkLocation } from "./control-ui-link-base-Drx2Z5zY.mjs";
import { r as resolveChatAttachmentPolicy } from "./chat-attachment-policy-7g-oMINW.mjs";
import { i as verifyDeviceToken, t as ensureDeviceToken } from "./device-pairing-tokens-Bivg3I0v.mjs";
import { t as resolveHostAccountName } from "./host-account-name-BgMaslGp.mjs";
import { i as ensureCanonicalUserProfileForTailscaleIdentity, n as ensureCanonicalGatewayOwnerProfile, r as ensureCanonicalUserProfileForEmail } from "./user-profile-writes-Coep_BY9.mjs";
import { r as resolveTrustedEnterpriseGitHubAccountId, t as createAuthenticatedGitHubIdentitySync } from "./github-user-identity-Da6Ux46-.mjs";
import { i as TALK_PTT_COMMANDS, n as IOS_WATCH_RELAY_COMMANDS, r as PLATFORM_DEFAULTS, t as DEFAULT_DANGEROUS_NODE_COMMANDS } from "./node-command-policy-DkH-pkTr.mjs";
import { n as approveDevicePairing, t as approveBootstrapDevicePairing } from "./device-pairing-approval-QMJvpfTq.mjs";
import { a as getBoundDeviceBootstrapContext, d as restoreGenericDeviceBootstrapToken, m as verifyDeviceBootstrapToken, o as getBoundDeviceBootstrapProfile, u as redeemDeviceBootstrapTokenProfile } from "./device-bootstrap-5DbASnAD.mjs";
import { t as resolveEffectiveComputerUseDescriptor } from "./node-computer-use-descriptor-D0U4PsFz.mjs";
import { r as serializeEventPayload } from "./node-registry-CE_3ElcX.mjs";
import { t as loadVoiceWakeRoutingConfig } from "./voicewake-routing-CWXNXBoJ.mjs";
import { n as parseGatewayRole, r as roleCanSkipDeviceIdentity } from "./role-policy-15uLJJ6i.mjs";
import { n as clearRemovedNodeRuntimeState, s as reconcileRevokedDeviceWorker } from "./node-runtime-state-DFpXFBB4.mjs";
import { n as broadcastRejectedNodePairing, t as broadcastRejectedDevicePairing } from "./pairing-events-DVOVq0n9.mjs";
import { t as shouldScheduleBackgroundHealthRefresh } from "./health-refresh-admission-GCeg0zv6.mjs";
import { t as captureAuthenticatedNodePairingState } from "./device-pairing-node-state-D6j3mDNN.mjs";
import { a as adoptTailscaleProfileAvatar } from "./user-profiles-DeFJDvhw.mjs";
import { n as loadVoiceWakeConfig } from "./voicewake-KuETablw.mjs";
import { t as truncateCloseReason } from "./close-reason-BqnE0JFy.mjs";
import { t as HandshakeAuthLogLimiter } from "./handshake-auth-log-limiter-2zox2ka1.mjs";
import { a as consumeSetupHandoff, c as resolvePairingLocality, d as shouldPreserveLocalCliSharedAuthScopes, f as shouldSkipLocalBackendSelfPairing, i as confirmSetupHandoffDelivery, l as resolveUnauthorizedHandshakeContext, m as resolveConnectAuthState, n as broadcastSetupHandoffCompletion, o as resolveDeviceSignaturePayloadVersion, p as resolveConnectAuthDecision, r as broadcastSetupHandoffDeliveryUncertain, s as resolveHandshakeBrowserSecurityContext, t as reconcileNodePairingOnConnect, u as shouldAllowSilentLocalPairing } from "./node-connect-reconcile-HxScENMn.mjs";
import os from "node:os";
import { performance as performance$1 } from "node:perf_hooks";
import { isDeepStrictEqual } from "node:util";
import net from "node:net";
import { setImmediate } from "node:timers/promises";
//#region src/gateway/node-pairing-auto-approve.ts
/** Remote auto-approval may grant only the fresh, capability-free node request it proved. */
function isScopelessNodePairingRequest(e) {
return e.isRepair !== true && (e.scopes ?? []).length === 0 && (e.role === void 0 || e.role === "node") && (e.roles ?? []).every((e) => e === "node");
}
function resolveNodePairingClientIpSource(e) {
if (!e.reportedClientIp) return "none";
if (!e.hasProxyHeaders || !e.remoteIsTrustedProxy) return "direct";
return e.remoteIsLoopback ? "loopback-trusted-proxy" : "trusted-proxy";
}
/**
* Shared floor for every non-interactive node pairing approval (trusted-CIDR,
* SSH-verified): only a fresh, scopeless, non-browser `role: node` request
* with a directly attributable client IP qualifies. Upgrades and spoofable
* loopback trusted-proxy header paths always stay on the manual prompt.
*/
function isEligibleFreshNodePairingRequest(e) {
return !e.existingPairedDevice && e.role === "node" && e.reason === "not-paired" && e.scopes.length === 0 && !e.hasBrowserOriginHeader && !e.isControlUi && !e.isWebchat && e.reportedClientIpSource !== "none" && e.reportedClientIpSource !== "loopback-trusted-proxy" && Boolean(e.reportedClientIp);
}
function shouldAutoApproveNodePairingFromTrustedCidrs(e) {
if (!isEligibleFreshNodePairingRequest(e) || !e.reportedClientIp) return false;
const t = e.autoApproveCidrs?.map((e) => e.trim()).filter((e) => e.length > 0);
if (!t || t.length === 0) return false;
return isTrustedProxyAddress(e.reportedClientIp, t);
}
//#endregion
//#region src/gateway/server/ws-connection/request-start.ts
const workBudget = {
count: 0,
bytes: 0,
maxCount: 1024,
maxBytes: 52428800,
maxConnectionCount: 256,
connections: /* @__PURE__ */ new Map()
};
const controlBudget = {
count: 0,
bytes: 0,
maxCount: 1024,
maxBytes: 1048576,
maxConnectionCount: 16,
connections: /* @__PURE__ */ new Map()
};
const pending = [];
const MAX_CONTROL_FRAME_BYTES = 4096;
const MAX_STARTS_PER_TURN = 64;
const START_WORK_BUDGET_MS = 12;
const MAX_CONCURRENT_PREPARATIONS = 4;
const MAX_QUEUE_WAIT_MS = 3e4;
let preparations = 0;
let notifyQueueChanged;
let active = false;
var GatewayRequestStartTimeoutError = class extends Error {
constructor() {
super("The server could not start the request within 30 seconds. Please try again.");
}
};
async function grantStarts() {
let e = 0;
let t = MAX_STARTS_PER_TURN;
while (pending.length > 0) {
const n = performance$1.now();
const r = /* @__PURE__ */ new Set();
const i = pending.findIndex((e) => {
if (e.signal?.aborted || n >= e.expiresAt) return true;
if (e.preparation && preparations >= MAX_CONCURRENT_PREPARATIONS || !e.independentRead && r.has(e.connection.id)) {
if (!e.independentRead) r.add(e.connection.id);
return false;
}
return true;
});
if (i === -1) {
const e = createDeferredCore();
notifyQueueChanged = e.resolve;
const t = setTimeout(e.resolve, Math.max(0, pending[0].expiresAt - performance$1.now()));
await racePromiseWithAbortSignal(e.promise, pending[0].signal).catch(() => {});
clearTimeout(t);
notifyQueueChanged = void 0;
continue;
}
const a = pending.splice(i, 1)[0];
a.budget.count--;
a.budget.bytes -= a.frameBytes;
a.connection.count--;
if (a.connection.count === 0) a.budget.connections.delete(a.connection.id);
if (a.preparation || t >= MAX_STARTS_PER_TURN || performance$1.now() - e >= START_WORK_BUDGET_MS) {
await setImmediate();
e = performance$1.now();
t = 0;
}
t++;
if (performance$1.now() >= a.expiresAt) {
a.reject(new GatewayRequestStartTimeoutError());
continue;
}
if (a.preparation && !a.signal?.aborted) {
preparations++;
a.settled.then(() => {
preparations--;
notifyQueueChanged?.();
});
}
a.grant();
await new Promise(queueMicrotask);
}
active = false;
}
/** Park saturated preparations; preserve connection order except for independent reads. */
function scheduleGatewayRequestStart(e, t, n, r, i) {
return runOutsideGatewayRootWorkAdmission(() => {
const a = asOptionalRecord(t.params);
const o = t.method === "sessions.subscribe" && Object.keys(a ?? {}).some((e) => e !== "includeMessageBodies") || t.method === "models.list" || t.method === "sessions.messages.subscribe" && (a?.includeApprovals === true || a?.initialHistory !== void 0);
const s = e <= MAX_CONTROL_FRAME_BYTES && (t.method === "gateway.suspend.prepare" || t.method === "gateway.suspend.status" || t.method === "gateway.suspend.resume" || t.method === "gateway.suspend.handoff" || t.method === "gateway.restart.request" || t.method === "update.status" || t.method === "update.run");
const c = t.method === "models.list" || t.method === "chat.history" || t.method === "board.get" || t.method === "sessions.resolve" || t.method === "sessions.describe" || t.method === "sessions.list" || t.method === "sessions.catalog.list" || t.method === "users.list" || t.method === "agents.list" || t.method === "agent.identity.get" || t.method === "plugins.controlUi.list" || t.method === "cron.list" || t.method === "push.web.vapidPublicKey" || t.method === "sessions.github.options" || t.method === "workboard.cards.list" || t.method === "workboard.boards.list" || t.method === "github.preview" || t.method === "gateway.suspend.status" || t.method === "update.status";
const l = s || e <= MAX_CONTROL_FRAME_BYTES && (t.method === "sessions.messages.unsubscribe" || t.method === "sessions.messages.subscribe" && a?.includeApprovals !== true && a?.initialHistory === void 0) ? controlBudget : workBudget;
const u = l.connections.get(n);
if (l.count >= l.maxCount || l.bytes + e > l.maxBytes || u && u.count >= l.maxConnectionCount) return null;
const { promise: d, resolve: f, reject: p } = createDeferredCore();
const m = u ?? {
id: n,
count: 0
};
l.count++;
l.bytes += e;
m.count++;
l.connections.set(n, m);
const h = s ? pending.findLastIndex((e) => e.lifecycle || !c && e.connection.id === n) + 1 : pending.length;
pending.splice(h, 0, {
grant: f,
reject: p,
expiresAt: performance$1.now() + MAX_QUEUE_WAIT_MS,
preparation: o,
independentRead: c,
lifecycle: s,
settled: r,
signal: i,
budget: l,
frameBytes: e,
connection: m
});
if (!active) {
active = true;
runWithMainThreadTask("gateway:rpc:queue", grantStarts);
} else notifyQueueChanged?.();
return d;
});
}
//#endregion
//#region src/gateway/server/ws-connection/authenticated-request-dispatch.ts
const MAX_UNAUTHORIZED_ROLE_FAILURES = 10;
const loadGatewayServerMethods = createLazyPromise(() => import("./authenticated-request-dispatch.server-methods.runtime.js"));
const DEVICE_CREDENTIAL_INVALIDATING_METHODS = /* @__PURE__ */ new Set([
"device.pair.remove",
"device.token.rotate",
"device.token.revoke",
"node.pair.remove"
]);
function createGatewayAuthenticatedRequestDispatcher(e) {
const { connId: t, clients: n, getRequiredSharedGatewaySessionGeneration: r, extraHandlers: i, getMethodRegistry: a, buildRequestContext: o, send: s, close: c, isClosed: l, setCloseCause: u, logGateway: d } = e.handler;
let f = 0;
let p;
const closeInvalidatedClient = (e, t, n) => {
const r = !isGatewayAuthPolicyCurrent(e.authPolicy);
if (!e.invalidated && !r) return false;
const i = e.invalidatedReason ?? (r ? "gateway-policy-changed" : "invalidated");
u("client-invalidated", {
reason: i,
method: t
});
invalidateGatewayPolicyClient(e, {
reason: i,
code: 4001,
message: `client invalidated: ${i}`,
close: () => c(4001, `client invalidated: ${i}`),
revokeSource: r && !n()
});
return true;
};
const dispatch = async (m, h, g, _, v = s) => {
if (!validateRequestFrame(m)) {
s({
type: "res",
id: m?.id ?? "invalid",
ok: false,
error: errorShape(ErrorCodes.INVALID_REQUEST, `invalid request frame: ${formatValidationErrors(validateRequestFrame.errors)}`)
});
return;
}
const y = m;
const b = o();
const x = b.resolveGatewayContext?.() ?? b;
let S = h.authPolicy;
const isCommittedGrantCurrent = () => {
const e = x.getCommittedRuntimeConfig?.() ?? x.getRuntimeConfig();
if (!isGatewayAuthGrantCurrent(S, e)) return false;
if (S && !S.browserOrigin?.remoteControlUiIngress) S = captureGatewayAuthPolicy(e, S);
return true;
};
if (closeInvalidatedClient(h, y.method, isCommittedGrantCurrent)) return;
const C = createGatewayRpcDiagnostics(y.method, a, i, {
clientKind: h.connect.client.id,
source: v === s ? "wire" : "internal",
params: y.params
});
logWs("in", "req", {
connId: t,
id: y.id,
method: y.method
});
const w = SharedGatewaySessionGenerationState.fromReader(r);
const T = h.remoteControlUiIngress;
const hasCurrentIngress = () => {
if (hasCurrentRemoteControlUiIngress(T)) return true;
invalidateGatewayPolicyClient(h, {
reason: "remote-control-ui-ingress-closed",
code: 4001,
message: "remote Control UI ingress closed",
close: () => c(4001, "remote Control UI ingress closed")
});
return false;
};
const E = h.internal?.authenticatedControlUi === true && h.isDeviceTokenAuth === true ? h.internal.operatorDeviceTokenIdentity : void 0;
const D = h.authenticatedUserProfile?.profileId;
const O = captureGatewayDeviceRevocation(b, {
deviceId: h.connect.device?.id,
role: h.connect.role
}, () => {
if (!hasCurrentIngress()) return false;
if (!hasCurrentGatewayOperatorAccess(h.internal?.operatorAccessAuthority)) invalidateGatewayPolicyClient(h, {
reason: "operator-access-closed",
code: 4001,
message: GATEWAY_OPERATOR_ACCESS_DENIED_MESSAGE,
close: () => c(4001, GATEWAY_OPERATOR_ACCESS_DENIED_MESSAGE)
});
if (closeInvalidatedClient(h, y.method, isCommittedGrantCurrent)) return false;
const e = h.usesSharedGatewayAuth ? r?.() : void 0;
if (e !== void 0 && h.sharedGatewaySessionGeneration !== e) {
u("gateway-auth-rotated", {
authGenerationStale: true,
method: y.method
});
invalidateGatewayPolicyClient(h, {
reason: "gateway-auth-changed",
code: 4001,
message: "gateway auth changed",
close: () => c(4001, "gateway auth changed"),
revokeSource: false
});
return false;
}
return true;
}, h.connectionSignal, h.connect.role === "operator" && (!h.usesSharedGatewayAuth || w) ? {
dependencies: {
client: h,
context: x,
authPolicyGeneration: h.authPolicy?.grantGeneration,
sharedGenerationOwner: h.usesSharedGatewayAuth ? w : void 0,
sharedGeneration: h.usesSharedGatewayAuth ? h.sharedGatewaySessionGeneration : void 0,
authorityOwner: T,
...E && D ? { reconnect: {
device: E,
profileId: D,
role: h.connect.role,
scopes: JSON.stringify([...new Set(h.connect.scopes ?? [])].toSorted()),
clientId: h.connect.client.id,
clientMode: h.connect.client.mode,
pairedClientId: h.pairedClientId,
transportPolicyGeneration: h.authPolicy?.generation,
verifiedIdentity: h.authPolicy?.verifiedIdentity,
origin: h.browserOrigin?.origin,
requestHost: h.browserOrigin?.requestHost,
isLocalClient: h.browserOrigin?.isLocalClient,
accessOwner: h.internal?.operatorAccessAuthority
} } : {}
},
isCurrent: () => hasCurrentIngress() && hasCurrentGatewayPolicyClientSource(h) && isCommittedGrantCurrent(),
subscribe: (e) => {
const t = n.retainRequest(h);
T?.signal.addEventListener("abort", e, { once: true });
if (T?.signal.aborted) e();
const r = onGatewayPolicyClientInvalidated(h, e);
const i = onOperatorRolePolicyChanged((t) => {
if (t.kind === "config" && t.context === x && !isCommittedGrantCurrent()) e();
});
const a = h.usesSharedGatewayAuth ? w?.onInvalidated(h.sharedGatewaySessionGeneration, e, h.authPolicy) : void 0;
return () => {
T?.signal.removeEventListener("abort", e);
r();
i();
a?.();
t();
};
}
} : void 0);
const k = O.isCurrent;
const A = n.retainRequest(h);
const j = p;
const M = DEVICE_CREDENTIAL_INVALIDATING_METHODS.has(y.method) ? createDeferredCore() : void 0;
if (M) {
const e = Promise.allSettled([j, M.promise]).then(() => {
if (p === e) p = void 0;
});
p = e;
}
try {
const n = y.expectedProfileId === void 0 ? void 0 : await createExpectedProfileBinding(y.expectedProfileId, h, () => {
if (!k()) throw new Error("Gateway requester authority changed");
});
const publishResponse = (e, n, r, i) => {
if (!p?.pending && !k()) {
C?.response("suppressed");
return;
}
try {
let a = e;
let o = r;
let s = v({
type: "res",
id: y.id,
ok: e,
payload: n,
error: r
});
if (s.kind === "serialization") {
const e = formatForLog(s.error);
d.error(`response serialization failed method=${y.method}: ${e}`);
a = false;
o = errorShape(ErrorCodes.UNAVAILABLE, "response serialization failed");
s = v({
type: "res",
id: y.id,
ok: a,
error: o
});
}
C?.response(s.kind === "sent" ? a ? "ok" : "error" : "unavailable", s.kind === "sent" ? s.bytes : void 0, {
payload: n,
params: y.params
});
let l = i;
if (o?.code === ErrorCodes.INVALID_REQUEST && typeof o.message === "string" && o.message.startsWith("unauthorized role:")) {
f += 1;
if (f === 11) l = {
...l,
suppressedUnauthorizedResponses: 9
};
if (f > 1 && f <= MAX_UNAUTHORIZED_ROLE_FAILURES) return;
if (f > MAX_UNAUTHORIZED_ROLE_FAILURES) {
u("repeated-unauthorized-requests", {
unauthorizedCount: f,
method: y.method
});
queueMicrotask(() => c(1008, "repeated unauthorized calls"));
}
l = {
...l,
unauthorizedCount: f
};
} else f = 0;
logWs("out", "res", () => ({
connId: t,
id: y.id,
ok: a,
method: y.method,
errorCode: o?.code,
errorMessage: o?.message,
...l,
...y.method === "sessions.list" ? summarizeSessionListForWsLog(y.params) : {},
bytes: s.kind === "sent" ? s.bytes : void 0
}));
} finally {
p?.finish();
if (h.connect.role === "node" && asOptionalRecord(r?.details)?.code === "PAIRING_CHANGED" && b.nodeRegistry.get(h.connect.device?.id ?? h.connect.client.id)?.connId !== h.connId) {
u("node-pairing-changed", { method: y.method });
c(4001, "node pairing changed; reconnect");
}
}
};
const o = n?.guardResponse(publishResponse) ?? publishResponse;
const s = h.internal?.agentRuntimeIdentity;
const hasCurrentRuntimeAuthority = () => {
if (s && b.validateAgentRuntimeApprovalAuthority?.(s) !== true) {
o(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "agent runtime authority is no longer active"));
u("agent-runtime-authority-closed", { method: y.method });
c(4001, "agent runtime authority closed");
return false;
}
return true;
};
const respondWithAuthority = (e, t, n, r) => {
if (hasCurrentRuntimeAuthority()) o(e, t, n, r);
};
const p = registerGatewayPolicyResponse(y.method, h, respondWithAuthority);
const executeRequest = async () => {
C?.bindTrace();
const o = createDeferredCore();
let s;
const c = y.method === "sessions.companion.ask" || y.method === "sessions.usage" || y.method === "plugins.reload" && asOptionalRecord(y.params)?.waitForDrain === true || y.method === "node.invoke" && h.connect.client.id === GATEWAY_CLIENT_IDS.CLI && h.connect.client.mode === GATEWAY_CLIENT_MODES.CLI ? new AbortController() : void 0;
const u = h.internal?.operatorAccessAuthority?.signal;
const f = T ? u ? AbortSignal.any([T.signal, u]) : T.signal : u;
const m = c ? f ? AbortSignal.any([c.signal, f]) : c.signal : f;
const cancelRequest = () => c?.abort();
if (c) h.socket.once("close", cancelRequest);
let v = "returned";
try {
s = b.requestEntryLifetime?.enter({
req: y,
client: h,
context: b
});
if (j) {
await racePromiseWithAbortSignal(j, b.requestEntryLifetime?.signal).catch(() => void 0);
s?.assertOpen();
if (l()) return;
}
if (!k() || !hasCurrentRuntimeAuthority()) return;
const { handleGatewayRequest: c } = await loadGatewayServerMethods();
s?.assertOpen();
if (h.connect.role === "operator") {
C?.startQueue();
const e = scheduleGatewayRequestStart(g, y, t, o.promise, b.requestEntryLifetime?.signal);
if (!e) {
respondWithAuthority(false, void 0, errorShape(ErrorCodes.UNAVAILABLE, "The server is busy. Please try again in a moment.", { retryable: true }));
return;
}
try {
await e;
} finally {
C?.finishQueue();
}
}
s?.assertOpen();
if (m?.aborted || !k() || !hasCurrentRuntimeAuthority()) return;
await runOutsideGatewayRootWorkAdmission(() => c(bindWebSocketRequestMutationAuthority({
req: y,
respond: respondWithAuthority,
acceptsSerializedJson: true,
acceptsDeflatedSegments: e.handler.socket.acceptsDeflatedSegments,
client: h,
isWebchatConnect: e.isWebchatConnect,
hasCurrentClientAuthority: k,
expectedProfileBinding: n,
extraHandlers: i,
methodRegistry: a?.(),
context: b,
..._ ? { admission: _ } : {},
requestEntry: s,
...m ? { signal: m } : {}
}, h, r), C));
} catch (e) {
const t = e instanceof GatewayRequestStartTimeoutError;
v = t ? "returned" : "threw";
if (!t) d.error(`request handler failed: ${formatForLog(e)}`);
const n = classifyGatewayStaleInstall(e);
respondWithAuthority(false, void 0, n?.error ?? errorShapeFromError(ErrorCodes.UNAVAILABLE, e, {
message: formatForLog(e),
...e instanceof GatewayClientRequestError ? {
retryable: e.retryable,
retryAfterMs: e.retryAfterMs,
details: e.details
} : t ? {
retryable: true,
details: { reason: "request-start-timeout" }
} : void 0
}));
} finally {
o.resolve();
p?.finish();
C?.finish(m?.aborted ? "cancelled" : v);
s?.release();
if (c) h.socket.off("close", cancelRequest);
}
};
const m = parseDiagnosticTraceparent(y.traceparent);
const dispatchRequest = () => m ? runWithDiagnosticTraceContext(createChildDiagnosticTraceContext(m), executeRequest) : executeRequest();
await (h.connect.role === "node" ? e.handler.nodeLifecycleDispatch.dispatch(y.method, dispatchRequest) : dispatchRequest());
} finally {
try {
A();
} finally {
try {
O.release();
} finally {
M?.resolve();
}
}
}
};
return { dispatch };
}
//#endregion
//#region src/gateway/server/ws-connection/connect-admission.ts
function isStartupNodeConnect(e) {
return e.role === "node" && e.client.mode === GATEWAY_CLIENT_MODES.NODE;
}
/** Exact first-connect shape emitted by `openclaw connect` for a setup-code node. */
function isStartupNodeBootstrapConnect(e) {
const t = e.auth;
const n = e.device;
return isStartupNodeConnect(e) && e.client.id === GATEWAY_CLIENT_IDS.NODE_HOST && Array.isArray(e.scopes) && e.scopes.length === 0 && Boolean(n?.id.trim() && n.publicKey.trim()) && hasNonEmptyString(t?.bootstrapToken) && !hasNonEmptyString(t?.token) && !hasNonEmptyString(t?.deviceToken) && !hasNonEmptyString(t?.password) && !hasNonEmptyString(t?.approvalRuntimeToken) && !hasNonEmptyString(t?.agentRuntimeIdentityToken);
}
async function rejectGatewayStartupConnect(e) {
const { close: t } = e.handler;
const { frame: n, markHandshakeFailure: r, sendFrame: i } = e;
r(GATEWAY_STARTUP_PENDING_CLOSE_CAUSE);
await i({
type: "res",
id: n.id,
ok: false,
error: errorShape(ErrorCodes.UNAVAILABLE, "gateway starting; retry shortly", {
retryable: true,
retryAfterMs: 500,
details: gatewayStartupUnavailableDetails()
})
}).catch(() => {});
queueMicrotask(() => t(GATEWAY_STARTUP_CLOSE_CODE, GATEWAY_STARTUP_CLOSE_REASON));
}
async function rejectUnavailableProfileConnect(e, t) {
const n = authenticatedProfileUnavailableError(t);
e.markHandshakeFailure("authenticated-profile-unavailable");
e.sendHandshakeErrorResponse(ErrorCodes.UNAVAILABLE, n.message, n);
await e.releasePendingNodePairingCleanup();
e.handler.close(1013, truncateCloseReason(n.message));
}
function applyConnectionScopeCap(e) {
const t = e.upgradeReq.headers["x-openclaw-scopes"];
const n = Array.isArray(t) ? t[0] : t;
if (n === void 0) return e.scopes;
const r = n.split(",").map((e) => e.trim()).filter((e) => e.length > 0);
return e.role === "operator" ? intersectOperatorScopes(e.scopes, r) : e.scopes.filter((e) => r.includes(e));
}
function resolveEffectiveConnectionScopes(e) {
const t = e.verifiedIdentity;
let n = [];
if (e.role === "operator" && t) n = resolveIdentityOperatorScopes(t, e.identityScopes);
return applyConnectionScopeCap({
role: e.role,
scopes: [.../* @__PURE__ */ new Set([...e.deviceScopes, ...n])],
upgradeReq: e.upgradeReq
});
}
function rejectGatewayConnectOrigin(e, t) {
const n = "origin not allowed (use gateway.publicOrigin with allowedOrigins omitted, or allow this origin in gateway.controlUi.allowedOrigins)";
e.markHandshakeFailure("origin-mismatch", {
origin: e.handler.requestOrigin ?? "n/a",
host: e.handler.requestHost ?? "n/a",
reason: t
});
e.sendHandshakeErrorResponse(ErrorCodes.INVALID_REQUEST, n, { details: {
code: ConnectErrorDetailCodes.CONTROL_UI_ORIGIN_NOT_ALLOWED,
reason: t
} });
e.handler.close(1008, truncateCloseReason(n));
}
/** Recheck live authority after awaited work, before granting credentials or registering a client. */
function resolveGatewayConnectPolicyFailure(e, t) {
if (e.browserOrigin) {
const t = checkGatewayWsBrowserOrigin(e.browserOrigin, readRuntimeConfig());
if (!t.ok) return {
kind: "origin",
reason: t.reason
};
}
if (!isDeepStrictEqual(e.configSnapshot.gateway?.roles, readRuntimeConfig().gateway?.roles) || !isGatewayAuthPolicyCurrent(t.authPolicy)) return { kind: "auth" };
if (t.sessionUsesSharedGatewayAuth && e.handler.getRequiredSharedGatewaySessionGeneration && t.sessionSharedGatewaySessionGeneration !== e.handler.getRequiredSharedGatewaySessionGeneration()) return { kind: "auth" };
}
async function admitGatewayConnect(e) {
const { connId: t, remoteAddr: n, remotePort: r, requestHost: i, requestOrigin: a, close: o, isStartupPending: s, logGateway: c, logWsControl: l, originCheckMetrics: u } = e.handler;
const { connectParams: d, configSnapshot: f, peerLabel: p, browserOrigin: m, clientLabel: h, markHandshakeFailure: g, sendHandshakeErrorResponse: _, isWebchatConnect: v } = e;
const y = isStartupNodeConnect(d);
const b = y && s?.() === true;
if (e.handler.isConnectPending?.() && !y) {
await rejectGatewayStartupConnect(e);
return;
}
const { minProtocol: x, maxProtocol: S } = d;
const C = S >= 4 && x <= 4;
const w = d.client.mode === GATEWAY_CLIENT_MODES.PROBE && S >= 3 && x <= 4;
const T = y && S >= 3 && x <= 3;
const E = !C && T;
if (!C && !w && !T) {
g("protocol-mismatch", {
minProtocol: x,
maxProtocol: S,
expectedProtocol: 4,
minimumProbeProtocol: 3
});
l.warn(`protocol mismatch conn=${t} peer=${formatForLog(p)} remote=${n ?? "?"} remotePort=${r ?? "?"} client=${formatForLog(h)} ${d.client.mode} v${formatForLog(d.client.version)} min=${x} max=${S} expected=${4} probeMin=${3} instance=${formatForLog(d.client.instanceId ?? "n/a")}`);
_(ErrorCodes.INVALID_REQUEST, "protocol mismatch", {
retryable: false,
details: {
code: ConnectErrorDetailCodes.PROTOCOL_MISMATCH,
clientMinProtocol: x,
clientMaxProtocol: S,
expectedProtocol: 4,
minimumProbeProtocol: 3,
minProtocol: y ? 3 : d.client.mode === GATEWAY_CLIENT_MODES.PROBE ? 3 : 4,
maxProtocol: 4,
gatewayBuildId: resolveRuntimeServiceBuildId(),
...d.client.id === GATEWAY_CLIENT_IDS.CONTROL_UI ? { reloadRequired: true } : {}
}
});
o(1002, "protocol mismatch");
return;
}
const D = d.role ?? "operator";
const O = parseGatewayRole(D);
if (!O) {
g("invalid-role", { role: D });
_(ErrorCodes.INVALID_REQUEST, "invalid role");
o(1008, "invalid role");
return;
}
const k = Array.isArray(d.scopes) ? d.scopes : [];
const A = getRemoteControlUiIngressContext(e.handler.upgradeReq);
if (A) {
const e = !hasCurrentRemoteControlUiIngress(A) ? "Remote Control UI ingress is no longer active; reconnect through the current grant." : O !== "operator" ? "Remote Control UI ingress only admits the operator role." : !d.device ? "Remote Control UI ingress requires a signed device identity." : Object.values(d.auth ?? {}).some((e) => e !== void 0) ? "Remote Control UI ingress requires a credential-free signed device; reconnect without stored credentials." : !roleScopesAllow({
role: O,
requestedScopes: k,
allowedScopes: A.operatorScopeCeiling
}) ? "Remote Control UI scopes must stay within this grant's operator scope ceiling." : void 0;
if (e) {
g("remote-control-ui-admission-denied");
_(ErrorCodes.FORBIDDEN, e);
o(1008, truncateCloseReason(e));
return;
}
}
d.role = O;
d.scopes = k;
const j = isBrowserCopilotClient(d.client);
const M = j ? normalizeChromeExtensionOrigin(a ?? void 0) : void 0;
if (j && (d.client.mode !== GATEWAY_CLIENT_MODES.UI || !hasGatewayClientCap(d.caps, GATEWAY_CLIENT_CAPS.RUN_TOOL_BINDINGS) || !hasGatewayClientCap(d.caps, GATEWAY_CLIENT_CAPS.SESSION_SCOPED_EVENTS))) {
const e = "browser copilot requires ui mode with run-tool-bindings and session-scoped-events capabilities";
g("invalid-client", {
client: d.client.id,
mode: d.client.mode
});
_(ErrorCodes.INVALID_REQUEST, e);
o(1008, truncateCloseReason(e));
return;
}
if (j && !M) {
const e = "browser copilot requires a canonical Chrome extension origin";
g("origin-mismatch", {
origin: a ?? "n/a",
client: d.client.id
});
_(ErrorCodes.INVALID_REQUEST, e, { details: {
code: ConnectErrorDetailCodes.CONTROL_UI_ORIGIN_NOT_ALLOWED,
reason: "invalid browser copilot origin"
} });
o(1008, truncateCloseReason(e));
return;
}
const N = isOperatorUiClient(d.client) && !j;
const P = isBrowserOperatorUiClient(d.client);
const F = v(d);
const I = isNativeAppUiClient(d.client);
if (m) {
const n = checkGatewayWsBrowserOrigin(m, f);
if (!n.ok) {
rejectGatewayConnectOrigin(e, n.reason);
return;
}
if (n.matchedBy === "host-header-fallback") {
u.hostHeaderFallbackAccepted += 1;
l.warn(`security warning: websocket origin accepted via Host-header fallback conn=${t} count=${u.hostHeaderFallbackAccepted} host=${i ?? "n/a"} origin=${a ?? "n/a"}`);
c.warn("security metric: gateway.controlUi.dangerouslyAllowHostHeaderOriginFallback accepted a websocket connect request");
}
}
return {
minProtocol: x,
maxProtocol: S,
usesLegacyNodeProtocol: E,
role: O,
scopes: k,
isControlUi: N,
isBrowserOperatorUi: P,
isWebchat: F,
isNativeAppUi: I,
startupPending: b
};
}
//#endregion
//#region src/gateway/server/ws-connection/auth-messages.ts
const SETUP_CODE_REJECTED_MESSAGE = "unauthorized: setup code invalid, expired, revoked, or already used (create a new code; review `openclaw devices list`)";
/** Formats a client-specific auth failure message without exposing secret values. */
function formatGatewayAuthFailureMessage(e) {
const { authMode: t, authProvided: n, reason: r, client: i, isLocalClient: a } = e;
const o = isGatewayCliClient(i);
const s = isOperatorUiClient(i);
const c = isWebchatClient(i);
if (i?.mode === "node" && r?.startsWith("trusted_proxy_missing_header_")) return "gateway rejected this node: trusted-proxy identity-header authentication is required and no usable machine credential was accepted; run `openclaw doctor` on the Gateway";
const l = "open the dashboard URL and paste the token in Control UI settings";
const u = "paste in Control UI settings or openclaw doctor --generate-gateway-token; restart";
const d = o ? a ? "use this gateway's gateway.auth.token or pair the device" : "set gateway.remote.token to match gateway.auth.token" : s || c ? l : "provide gateway auth token";
const f = o ? a ? "use this gateway's gateway.auth.password" : "set gateway.remote.password to match gateway.auth.password" : s || c ? "enter the password in Control UI settings" : "provide gateway auth password";
switch (r) {
case "token_missing": return `unauthorized: gateway token missing (${s || c ? u : d})`;
case "token_mismatch": return `unauthorized: gateway token mismatch (${d})`;
case "token_missing_config": return "unauthorized: gateway token not configured on gateway (set gateway.auth.token)";
case "token_redacted_config":
case "password_redacted_config": return "gateway credential is a redaction sentinel (run openclaw doctor --fix on the Gateway, then restart and re-pair)";
case "password_missing": return `unauthorized: gateway password missing (${f})`;
case "password_mismatch": return `unauthorized: gateway password mismatch (${f})`;
case "password_missing_config": return "unauthorized: gateway password not configured on gateway (set gateway.auth.password)";
case "bootstrap_token_invalid": return SETUP_CODE_REJECTED_MESSAGE;
case "tailscale_user_missing": return "unauthorized: tailscale identity missing (use Tailscale Serve auth or gateway token/password)";
case "tailscale_proxy_missing": return "unauthorized: tailscale proxy headers missing (use Tailscale Serve or gateway token/password)";
case "tailscale_whois_failed": return "unauthorized: tailscale identity check failed (use Tailscale Serve auth or gateway token/password)";
case "tailscale_user_mismatch": return "unauthorized: tailscale identity mismatch (use Tailscale Serve auth or gateway token/password)";
case "rate_limited": return "unauthorized: too many failed authentication attempts (retry later)";
case PROXY_ATTRIBUTION_REQUIRED_REASON: return "unauthorized: proxy client attribution is required (configure gateway.trustedProxies narrowly and make the proxy overwrite or safely rebuild forwarded client headers)";
case "device_token_mismatch": return "unauthorized: device token mismatch (rotate/reissue device token)";
case "scope_mismatch": return "unauthorized: device token scope mismatch (re-pair or approve scope upgrade)";
}
if (t === "token" && n === "none") return `unauthorized: gateway token missing (${d})`;
if (t === "token" && n === "device-token") return "unauthorized: device token rejected (pair/repair this device, or provide gateway token)";
if (n === "bootstrap-token") return SETUP_CODE_REJECTED_MESSAGE;
if (t === "password" && n === "none") return `unauthorized: gateway password missing (${f})`;
return "unauthorized";
}
//#endregion
//#region src/gateway/server/ws-connection/connect-auth-security.ts
function hashGatewaySecurityId(e) {
const t = e?.trim();
if (!t) return;
return `sha256:${sha256HexPrefixCore(t, 12)}`;
}
function emitGatewayAuthSecurityEvent(e) {
emitTrustedSecurityEvent({
category: "auth",
action: e.action,
outcome: e.outcome,
severity: e.severity,
actor: {
kind: e.role === "node" ? "node" : "operator",
...e.deviceId ? { deviceIdHash: hashGatewaySecurityId(e.deviceId) } : {},
role: e.role
},
target: {
kind: "gateway",
name: "websocket"
},
policy: {
id: "gateway.websocket-auth",
decision: e.outcome === "success" ? "allow" : "deny",
...e.reason ? { reason: e.reason } : {}
},
control: {
id: "gateway.ws.connect",
family: "auth"
},
...e.reason ? { reason: e.reason } : {},
attributes: {
auth_mode: e.authMode,
auth_method: e.authMethod ?? "unknown",
auth_provided: e.authProvided ?? "unknown",
client_mode: e.clientMode ?? "unknown",
has_device_identity: Boolean(e.deviceId),
scope_count: e.scopes.length,
...e.rateLimited !== void 0 ? { rate_limited: e.rateLimited } : {}
}
});
}
//#endregion
//#region src/gateway/server/ws-connection/connect-device-metadata.ts
function resolvePairedAccessScopes(e) {
const t = Array.isArray(e?.approvedScopes) ? e.approvedScopes : Array.isArray(e?.scopes) ? e.scopes : [];
return normalizeSortedUniqueTrimmedStringList(t);
}
function isSetupCodeMobileBootstrapClient(e) {
const t = normalizeDeviceMetadataForAuth(e.platform);
const n = normalizeDeviceMetadataForAuth(e.deviceFamily);
if (e.id === GATEWAY_CLIENT_IDS.ANDROID_APP) return /^android(?:\s|$)/u.test(t) && n === "android";
if (e.id === GATEWAY_CLIENT_IDS.IOS_APP) return /^(?:ios|ipados)(?:\s|$)/u.test(t) && /^(?:iphone|ipad|ios)$/u.test(n);
return false;
}
function isSetupCodeVoiceNodeBootstrapClient(e) {
const t = normalizeDeviceMetadataForAuth(e.platform);
const n = normalizeDeviceMetadataForAuth(e.deviceFamily);
return e.id === GATEWAY_CLIENT_IDS.NODE_HOST && /^esp32(?:\s|$)/u.test(t) && n === "esp32";
}
function isSetupCodeHandoffBootstrapClient(e) {
return isMobilePairingSetupBootstrapProfile(e.profile) && isSetupCodeMobileBootstrapClient(e.client) || isNodePairingSetupBootstrapProfile(e.profile) && e.client.id === GATEWAY_CLIENT_IDS.NODE_HOST || isVoiceNodePairingSetupBootstrapProfile(e.profile) && isSetupCodeVoiceNodeBootstrapClient(e.client);
}
/** Match the exact host-issued browser-owner profile and its closed requested scope set. */
function isControlUiOwnerBootstrapProfile(e) {
const { profile: t, requestedScopes: n } = e;
return Boolean(t && deviceBootstrapProfilesEqual(t, CONTROL_UI_OWNER_BOOTSTRAP_PROFILE) && deviceBootstrapProfilesEqual({
roles: ["operator"],
scopes: n,
purpose: CONTROL_UI_OWNER_BOOTSTRAP_PROFILE.purpose
}, CONTROL_UI_OWNER_BOOTSTRAP_PROFILE));
}
function isControlUiOperatorBootstrapProfile(e) {
const { profile: t, requestedScopes: n } = e;
if (isControlUiOwnerBootstrapProfile(e)) return true;
if (!t || t.purpose !== "control-ui") return false;
if (t.roles.length !== 1 || t.roles[0] !== "operator") return false;
if (!t.scopes.every((e) => BOOTSTRAP_HANDOFF_OPERATOR_SCOPES.includes(e))) return false;
return roleScopesAllow({
role: "operator",
requestedScopes: n,
allowedScopes: t.scopes
});
}
function isMobileNodeBootstrapConnect(e) {
return e.role === "node" && e.scopes.length === 0 && !e.isControlUi && !e.isBrowserOperatorUi && !e.isWebchat && e.clientMode === GATEWAY_CLIENT_MODES.NODE;
}
function pairedDeviceAllowsBootstrapProfile(e, t = e.profile.roles) {
const n = e.device;
return Boolean(n && n.publicKey === e.devicePublicKey && t.every((t) => hasEffectivePairedDeviceRole(n, t) && roleScopesAllow({
role: t,
requestedScopes: resolveBootstrapProfileScopesForRole(t, e.profile.scopes, e.profile.purpose),
allowedScopes: resolvePairedAccessScopes(n)
})));
}
function resolvePinnedClientMetadata(e) {
function resolveNativeAppPlatformFamily(e, t) {
if (e === GATEWAY_CLIENT_IDS.IOS_APP && /^(?:ios|ipados)(?:\s|$)/.test(t)) return "ios-family";
if (e === GATEWAY_CLIENT_IDS.ANDROID_APP && /^android(?:\s|$)/.test(t)) return "android";
if (e === GATEWAY_CLIENT_IDS.WATCHOS_APP && /^watchos \d+(?:\.\d+){0,2}$/.test(t)) return "watchos";
if (e === GATEWAY_CLIENT_IDS.MACOS_APP && /^macos \d+(?:\.\d+){0,2}$/.test(t)) return "macos";
}
const t = normalizeDeviceMetadataForAuth(e.claimedPlatform);
const n = normalizeDeviceMetadataForAuth(e.claimedDeviceFamily);
const r = normalizeDeviceMetadataForAuth(e.pairedPlatform);
const i = normalizeDeviceMetadataForAuth(e.pairedDeviceFamily);
const a = r !== "";
const o = i !== "";
const s = resolveGatewayClientPlatformIdentity(r);
const c = e.clientId === GATEWAY_CLIENT_IDS.NODE_HOST && e.clientMode === GATEWAY_CLIENT_MODES.NODE && a && t !== "" && resolveGatewayClientPlatformIdentity(t).platform === s.platform || !o && s.platform !== r && t === s.platform && n === normalizeDeviceMetadataForAuth(s.deviceFamily);
const l = (e.clientId === GATEWAY_CLIENT_IDS.NODE_HOST && e.clientMode === GATEWAY_CLIENT_MODES.NODE || e.clientId === GATEWAY_CLIENT_IDS.CLI && (e.clientMode === GATEWAY_CLIENT_MODES.CLI || e.clientMode === GATEWAY_CLIENT_MODES.PROBE)) && (t === "darwin" || t === "macos") && /^macos \d+(?:\.\d+){0,2}$/.test(r);
const u = resolveNativeAppPlatformFamily(e.clientId, t);
const d = resolveNativeAppPlatformFamily(e.clientId, r);
const f = a && t !== "" && t !== r && (u !== void 0 && u === d || e.clientId === GATEWAY_CLIENT_IDS.MACOS_APP && u === "macos" && (r === "darwin" || r === "macos"));
const p = a && t !== r && !c && !l && !f;
const m = o && n !== i;
const h = c ? s.platform : t === r || l ? e.pairedPlatform : f ? e.claimedPlatform : void 0;
return {
platformMismatch: p,
deviceFamilyMismatch: m,
pinnedPlatform: a ? h : void 0,
pinnedDeviceFamily: o ? e.pairedDeviceFamily : void 0,
...f ? { refreshPairedPlatform: e.claimedPlatform } : {}
};
}
//#endregion
//#region src/gateway/server/ws-connection/connect-policy.ts
function shouldSkipControlUiPairing(e) {
if (e.isControlUi && e.role === "operator" && e.authMethod === "tailscale" && e.device) return "tailscale-device";
if (e.isControlUi && e.role === "operator" && e.authMode === "none") return "auth-none";
return null;
}
function isTrustedProxyControlUiOperatorAuth(e) {
return e.isControlUi && e.role === "operator" && e.authMode === "trusted-proxy" && e.authOk && e.authMethod === "trusted-proxy";
}
function shouldClearUnboundScopesForMissingDeviceIdentity(e) {
return e.decision.kind !== "allow" || e.authMethod === "token" || e.authMethod === "password" || e.authMethod === "trusted-proxy";
}
function evaluateMissingDeviceIdentity(e) {
if (e.hasDeviceIdentity) return { kind: "allow" };
if (e.isControlUi && e.trustedProxyAuthOk) return { kind: "allow" };
if (e.localBackendSelfPairingOk && e.role === "operator") return { kind: "allow" };
if (e.isControlUi) return { kind: "reject-control-ui-insecure-auth" };
if (roleCanSkipDeviceIdentity(e.role, e.sharedAuthOk)) return { kind: "allow" };
if (!e.authOk && e.hasSharedAuth) return { kind: "reject-unauthorized" };
return { kind: "reject-device-required" };
}
//#endregion
//#region src/gateway/server/ws-connection/control-ui-build-admission.ts
/**
* The Gateway owns bundled same-origin UI admission. Browser code still owns
* reload, but an older document must never become an RPC-capable session.
*
* The exemptions are deliberate, not gaps (ui/AGENTS.md "Gateway Coupling"):
* configured roots serve an independently built artifact the Gateway owns no
* matching build identity for, "dev" is the ui:dev sentinel, and cross-origin
* stays exempt because build ids embed the build timestamp — version-identical
* source-built installs carry different ids, so equality would reject matched
* pairings, and "reload" cannot remediate a client the Gateway did not serve.
* Exempted skew fails visibly at the first missing method instead.
*/
function resolveControlUiBuildMismatch(e) {
const t = e.gatewayBuildId?.trim();
const n = e.clientBuildId?.trim();
if (e.clientId !== GATEWAY_CLIENT_IDS.CONTROL_UI || e.configuredControlUiRoot || !t || n === "dev" || !isGatewayHostBrowserOrigin({
requestHost: e.requestHost,
origin: e.requestOrigin
}) || n === t) return null;
return {
gatewayBuildId: t,
clientBuildId: n || null
};
}
//#endregion
//#region src/gateway/server/ws-connection/connect-auth.ts
const unauthorizedHandshakeLogLimiter = new HandshakeAuthLogLimiter();
const DEVICE_SIGNATURE_SKEW_MS = 12e4;
async function authenticateGatewayConnect(e) {
const t = Boolean(e.connectParams.auth?.deviceToken || e.connectParams.device && e.connectParams.auth?.token);
if (!e.authRateLimiter || !t) return await authenticateGatewayConnectCore(e);
return await withSerializedCredentialFallbackAttempt({
limiter: e.authRateLimiter,
ip: e.browserRateLimitClientIp,
run: async () => await authenticateGatewayConnectCore(e)
});
}
async function authenticateGatewayConnectCore(e) {
const t = getRemoteControlUiIngressContext(e.handler.upgradeReq);
const { upgradeReq: n, connId: r, remoteAddr: i, remotePort: a, localAddr: o, localPort: s, requestHost: c, requestOrigin: l, requestUserAgent: u, getResolvedAuth: d, getRequiredSharedGatewaySessionGeneration: f, advanceHandshakePhase: p, setCloseCause: m, close: h, logWsControl: g } = e.handler;
const { connectParams: _, trustedProxies: v, allowRealIpFallback: y, peerLabel: b, hasProxyHeaders: x, isLocalClient: S, hasBrowserOriginHeader: C, browserRateLimitClientIp: w, authRateLimiter: T, clientLabel: E, markHandshakeFailure: D, sendHandshakeErrorResponse: O } = e;
const k = d();
const A = Array.isArray(_.scopes);
const j = await admitGatewayConnect(e);
if (!j) return;
let { scopes: M } = j;
const { role: N, isControlUi: P, startupPending: F } = j;
const I = F && isStartupNodeBootstrapConnect(_);
const L = _.device;
const ee = Boolean(_.auth?.token);
const R = Boolean(_.auth?.password);
const z = ee || R;
const te = Boolean(_.auth?.bootstrapToken);
const ne = Boolean(_.auth?.deviceToken);
if (z || te || ne || Boolean(L)) p("auth_credentials_received");
const B = await resolveConnectAuthState({
resolvedAuth: k,
connectAuth: _.auth,
hasDeviceIdentity: Boolean(L),
req: n,
trustedProxies: v,
allowRealIpFallback: y,
rateLimiter: T,
clientIp: w
});
const { sharedAuthOk: V, pendingSharedAuthFailure: re, bootstrapTokenCandidate: H } = B;
let { authResult: U, authOk: W, authMethod: G } = B;
let K = re;
const settleRejectedSharedAuthFailure = async () => {
if (!K) return;
K = false;
await T?.recordFailureAndDelay(w, AUTH_RATE_LIMIT_SCOPE_SHARED_SECRET);
};
const rejectUnauthorized = (e) => {
const { authProvided: t, canRetryWithDeviceToken: n, recommendedNextStep: d } = resolveUnauthorizedHandshakeContext({
connectAuth: _.auth,
failedAuth: e,
hasDeviceIdentity: Boolean(L)
});
emitGatewayAuthSecurityEvent({
action: "gateway.auth.failed",
outcome: "denied",
severity: e.rateLimited ? "high" : "medium",
authMode: k.mode,
authMethod: e.method ?? G,
authProvided: t,
role: N,
scopes: M,
clientMode: _.client.mode,
deviceId: L?.id,
reason: e.reason ?? "unknown",
rateLimited: e.rateLimited === true
});
D("unauthorized", {
authMode: k.mode,
authProvided: t,
authReason: e.reason,
allowTailscale: k.allowTailscale,
peer: b,
remoteAddr: i,
remotePort: a,
localAddr: o,
localPort: s,
role: N,
scopeCount: M.length,
hasDeviceIdentity: Boolean(L)
});
const f = formatGatewayAuthFailureMessage({
authMode: k.mode,
authProvided: t,
reason: e.reason,
client: _.client,
isLocalClient: S
});
const p = unauthorizedHandshakeLogLimiter.missingCredentialLogSuffix({
reason: e.reason,
remoteAddr: i,
client: E,
mode: _.client.mode,
authProvided: t
});
if (p !== void 0) g.warn(`unauthorized conn=${r} peer=${formatForLog(b)} remote=${i ?? "?"} client=${formatForLog(E)} ${_.client.mode} v${formatForLog(_.client.version)} role=${N} scopes=${M.length} auth=${t} device=${L ? "yes" : "no"} platform=${formatForLog(_.client.platform)} instance=${formatForLog(_.client.instanceId ?? "n/a")} host=${formatForLog(c ?? "n/a")} origin=${formatForLog(l ?? "n/a")} ua=${formatForLog(u ?? "n/a")} reason=${e.reason ?? "unknown"} guidance=${formatForLog(f)}${p}`);
O(ErrorCodes.INVALID_REQUEST, f, {
...e.rateLimited === true ? {
retryable: true,
...e.retryAfterMs !== void 0 ? { retryAfterMs: e.retryAfterMs } : {}
} : {},
details: {
code: resolveAuthConnectErrorDetailCode(e.reason),
authReason: e.reason,
canRetryWithDeviceToken: n,
recommendedNextStep: d
}
});
h(1008, truncateCloseReason(f));
};
const clearUnboundScopes = () => {
if (M.length > 0) {
M = [];
_.scopes = M;
}
};
const resolvePairingContext = () => {
const e = resolvePairingLocality({
connectParams: _,
isLocalClient: S,
requestHost: c,
requestOrigin: l,
remoteAddress: i,
hasProxyHeaders: x,
hasBrowserOriginHeader: C,
sharedAuthOk: V,
authMethod: G
});
return {
pairingLocality: e,
skipLocalBackendSelfPairing: shouldSkipLocalBackendSelfPairing({
connectParams: _,
locality: e,
hasBrowserOriginHeader: C,
sharedAuthOk: V,
authMethod: G
})
};
};
let { pairingLocality: ie, skipLocalBackendSelfPairing: q } = resolvePairingContext();
const ae = shouldPreserveLocalCliSharedAuthScopes({
connectParams: _,
locality: ie,
hasBrowserOriginHeader: C,
sharedAuthOk: V,
authMethod: G
});
const handleMissingDeviceIdentity = () => {
const e = isTrustedProxyControlUiOperatorAuth({
isControlUi: P,
role: N,
authMode: k.mode,
authOk: W,
authMethod: G
});
const t = evaluateMissingDeviceIdentity({
hasDeviceIdentity: Boolean(L),
role: N,
isControlUi: P,
trustedProxyAuthOk: e,
localBackendSelfPairingOk: q,
sharedAuthOk: V,
authOk: W,
hasSharedAuth: z
});
if (!L && !q && !ae && shouldClearUnboundScopesForMissingDeviceIdentity({
decision: t,
authMethod: G
})) clearUnboundScopes();
if (t.kind === "allow") return true;
if (t.kind === "reject-control-ui-insecure-auth") {
const e = "control ui requires device identity (use HTTPS or localhost secure context)";
D("control-ui-insecure-auth", { insecureAuthConfigured: false });
O(ErrorCodes.INVALID_REQUEST, e, { details: { code: ConnectErrorDetailCodes.CONTROL_UI_DEVICE_IDENTITY_REQUIRED } });
h(1008, e);
return false;
}
if (t.kind === "reject-unauthorized") {
rejectUnauthorized(U);
return false;
}
D("device-required");
O(ErrorCodes.NOT_PAIRED, "device identity required", { details: { code: ConnectErrorDetailCodes.DEVICE_IDENTITY_REQUIRED } });
h(1008, "device identity required");
return false;
};
if (F && !L) {
await settleRejectedSharedAuthFailure();
await rejectGatewayStartupConnect(e);
return;
}
if (!handleMissingDeviceIdentity()) {
await settleRejectedSharedAuthFailure();
return;
}
let oe = null;
let se = null;
if (L) {
const rejectDeviceAuthInvalid = async (t, n) => {
emitGatewayAuthSecurityEvent({
action: "gateway.auth.failed",
outcome: "denied",
severity: "medium",
authMode: k.mode,
authMethod: G,
authProvided: "device-signature",
role: N,
scopes: M,
clientMode: _.client.mode,
deviceId: L.id,
reason: t
});
e.handler.setHandshakeState("failed");
m("device-auth-invalid", {
reason: t,
client: _.client.id,
deviceId: L.id
});
O(ErrorCodes.INVALID_REQUEST, n, { details: {
code: resolveDeviceAuthConnectErrorDetailCode(t),
reason: t
} });
h(1008, n);
await settleRejectedSharedAuthFailure();
};
const t = deriveDeviceIdFromPublicKey(L.publicKey);
if (!t || t !== L.id) return await rejectDeviceAuthInvalid("device-id-mismatch", "device identity mismatch");
const n = L.signedAt;
if (typeof n !== "number" || Math.abs(Date.now() - n) > DEVICE_SIGNATURE_SKEW_MS) return await rejectDeviceAuthInvalid("device-signature-stale", "device signature expired");
const r = typeof L.nonce === "string" ? L.nonce.trim() : "";
if (!r) return await rejectDeviceAuthInvalid("device-nonce-missing", "device nonce required");
if (r !== e.handler.connectNonce) return await rejectDeviceAuthInvalid("device-nonce-mismatch", "device nonce mismatch");
se = resolveDeviceSignaturePayloadVersion({
device: L,
connectParams: _,
role: N,
scopes: M,
signedAtMs: n,
nonce: r
});
if (!se) return await rejectDeviceAuthInvalid("device-signature", "device signature invalid");
oe = normalizeEd25519PublicKeyBase64Url(L.publicKey);
if (!oe) return await rejectDeviceAuthInvalid("device-public-key", "device public key invalid");
}
const J = t ? {
authResult: {
ok: true,
method: "remote-ingress"
},
authOk: true,
authMethod: "remote-ingress",
deviceTokenSharedGatewaySessionGeneration: void 0
} : await resolveConnectAuthDecision({
state: B,
hasDeviceIdentity: Boolean(L),
deviceId: L?.id,
publicKey: L?.publicKey,
role: N,
scopes: M,
requireBootstrapToken: I,
rateLimiter: T,
clientIp: w,
verifyBootstrapToken: verifyDeviceBootstrapToken,
async verifyDeviceToken(e) {
return await verifyDeviceToken({
...e,
requiredSharedGatewaySessionGeneration: f?.()
});
}
});
({authResult: U, authOk: W, authMethod: G} = J);
const Y = J.deviceTokenSharedGatewaySessionGeneration;
({pairingLocality: ie, skipLocalBackendSelfPairing: q} = resolvePairingContext());
if (!W) {
if (F && H) {
await rejectGatewayStartupConnect(e);
return;
}
rejectUnauthorized(U);
return;
}
const ce = t?.resolvePrincipal();
if (ce) {
M = M.length === 0 ? [...ce.scopes] : intersectOperatorScopes(M, ce.scopes);
_.scopes = M;
}
const X = G === "bootstrap-token" && H && L ? await getBoundDeviceBootstrapContext({
token: H,
deviceId: L.id,
publicKey: L.publicKey
}) : null;
if (F && G === "bootstrap-token" && !I) {
await rejectGatewayStartupConnect(e);
return;
}
if (I) {
const t = X?.setupId?.trim();
const n = Boolean(X && deviceBootstrapProfilesEqual(X.profile, CLOUD_WORKER_PAIRING_SETUP_BOOTSTRAP_PROFILE));
let r = false;
if (n && t && L) try {
r = e.handler.isPendingWorkerNodeSetup?.(t, L.id) === true;
} catch {
r = false;
}
if (!n || !r) {
await rejectGatewayStartupConnect(e);
return;
}
}
p("auth_validated");
const le = X?.profile ?? null;
const Z = G === "token" || G === "password" || G === "trusted-proxy" || G === "remote-ingress";
const ue = Z ? resolveSharedGatewaySessionGeneration(k, v) : void 0;
const de = G === "bootstrap-token" && P && N === "operator" && isControlUiOperatorBootstrapProfile({
profile: le,
requestedScopes: M
}) ? f?.() : void 0;
const fe = Z || Y !== void 0 || de !== void 0;
const pe = ue ?? Y ?? de;
if (fe) {
const e = f?.();
if (e !== void 0 && pe !== e) {
m("gateway-auth-rotated", { authGenerationStale: true });
h(4001, "gateway auth changed");
return;
}
}
const me = resolveControlUiBuildMismatch({
clientId: _.client.id,
clientBuildId: _.client.buildId,
gatewayBuildId: resolveRuntimeServiceBuildId(),
configuredControlUiRoot: e.configSnapshot.gateway?.controlUi?.root,
requestHost: e.handler.requestHost,
requestOrigin: e.handler.requestOrigin
});
if (me) {
const e = "protocol mismatch: Control UI updated; reload this page to continue";
D("control-ui-build-mismatch", {
clientBuildId: me.clientBuildId ?? "legacy",
gatewayBuildId: me.gatewayBuildId
});
O(ErrorCodes.UNAVAILABLE, e, {
retryable: false,
details: {
code: ConnectErrorDetailCodes.PROTOCOL_MISMATCH,
gatewayBuildId: me.gatewayBuildId,
reloadRequired: true
}
});
g.warn(`control ui build rejected conn=${r} clientBuild=${formatForLog(me.clientBuildId ?? "legacy")} gatewayBuild=${formatForLog(me.gatewayBuildId)}; reload required`);
h(1008, truncateCloseReason(e));
return;
}
const he = isTrustedProxyControlUiOperatorAuth({
isControlUi: P,
role: N,
authMode: k.mode,
authOk: W,
authMethod: G
});
if (he) {
M = applyConnectionScopeCap({
role: N,
scopes: M,
upgradeReq: n
});
_.scopes = M;
}
const ge = shouldSkipControlUiPairing({
isControlUi: P,
device: L,
role: N,
authMode: k.mode,
authMethod: G
});
return {
...j,
remoteIngressPrincipal: ce,
authPolicy: captureGatewayAuthPolicy(e.configSnapshot, {
role: N,
authMethod: G,
authModeOverride: k.modeSource === "override" ? k.mode : void 0,
verifiedIdentity: U.user,
browserOrigin: e.browserOrigin
}),
resolvedAuth: k,
scopes: M,
hasRequestedScopes: A,
device: L,
devicePublicKey: oe,
deviceAuthPayloadVersion: se,
hasTokenAuth: ee,
hasPasswordAuth: R,
bootstrapTokenCandidate: H,
deviceTokenSharedGatewaySessionGeneration: Y,
authResult: U,
authMethod: G,
pairingLocality: ie,
sessionUsesSharedGatewayAuth: fe,
sessionSharedGatewaySessionGeneration: pe,
issuedBootstrapProfile: le,
handoffBootstrapProfile: null,
trustedProxyAuthOk: he,
controlUiPairingKind: ge,
skipLocalBackendSelfPairing: q,
rejectUnauthorized
};
}
//#endregion
//#region src/gateway/device-pairing-prune.ts
/**
* After a silent auto-approval, retire older silent pairings of the same client
* cluster. Ephemeral state dirs mint a fresh deviceId per run and every run
* re-pairs silently, so without this the paired-device list grows without bound
* (dozens of stale operator/node records per host).
*/
async function pruneSupersededSilentPairingsAfterApproval(e) {
const { context: t } = e;
const n = await pruneSupersededSilentPairedDevices({
deviceId: e.deviceId,
protectedDeviceIds: e.connectedDeviceIds,
isDeviceConnected: (e) => t.hasConnectedClientsForDevice?.(e) ?? false
});
for (const e of n) t.invalidateClientsForDevice?.(e.deviceId, { reason: "device-pair-removed" });
for (const e of n) {
t.logGateway.info(`device pairing pruned superseded silent pairing device=${e.deviceId} roles=${e.roles.join(",") || "none"}`);
if (e.roles.includes("node")) clearRemovedNodeRuntimeState({
nodeId: e.deviceId,
context: t
});
await reconcileRevokedDeviceWorker(t, e.deviceId);
if (e.roles.includes("node")) t.broadcast("node.pair.resolved", {
requestId: "",
nodeId: e.deviceId,
decision: "removed",
ts: Date.now()
}, { dropIfSlow: true });
t.disconnectClientsForDevice?.(e.deviceId);
}
return n;
}
//#endregion
//#region src/gateway/node-legacy-protocol-filter.ts
const BUILT_IN_NODE_COMMANDS = /* @__PURE__ */ new Set([
...Object.values(PLATFORM_DEFAULTS).flat(),
...DEFAULT_DANGEROUS_NODE_COMMANDS,
...TALK_PTT_COMMANDS,
...IOS_WATCH_RELAY_COMMANDS
]);
const LEGACY_NODE_HOST_DESKTOP_METADATA = {
darwin: {
platform: "macos",
deviceFamily: "Mac"
},
linux: {
platform: "linux",
deviceFamily: "Linux"
},
macos: {
platform: "macos",
deviceFamily: "Mac"
},
win32: {
platform: "windows",
deviceFamily: "Windows"
},
windows: {
platform: "windows",
deviceFamily: "Windows"
}
};
/** Normalizes desktop aliases used by protocol-v3-compatible node hosts. */
function normalizeNodeHostCompatibilityMetadata(e) {
if (e.id !== GATEWAY_CLIENT_IDS.NODE_HOST || e.mode !== GATEWAY_CLIENT_MODES.NODE) return e;
if (!Object.hasOwn(LEGACY_NODE_HOST_DESKTOP_METADATA, e.platform)) return e;
const t = LEGACY_NODE_HOST_DESKTOP_METADATA[e.platform];
const n = e.deviceFamily?.trim();
if (n && n.toLowerCase() !== t.deviceFamily.toLowerCase()) return e;
if (e.platform === t.platform && n) return e;
return {
...e,
platform: t.platform,
deviceFamily: n || t.deviceFamily
};
}
function filterLegacyNodeProtocolFeatures(e) {
const t = getActivePluginGatewayNodePolicyRegistry();
if (!t) return {
caps: [...e.caps],
commands: [...e.commands]
};
const n = /* @__PURE__ */ new Set([...t.nodeHostCommands.map((e) => e.pluginId), ...t.nodeInvokePolicies.map((e) => e.pluginId)]);
const r = /* @__PURE__ */ new Set([...e.pluginSurfaces, ...n]);
const isPluginOnly = (e) => !BUILT_IN_NODE_COMMANDS.has(e);
const i = /* @__PURE__ */ new Set([...t.nodeHostCommands.map((e) => e.command.command).filter(isPluginOnly), ...t.nodeInvokePolicies.flatMap((e) => e.policy.commands).filter(isPluginOnly)]);
return {
caps: e.caps.filter((e) => !r.has(e)),
commands: e.commands.filter((e) => !i.has(e))
};
}
//#endregion
//#region src/gateway/server/ws-connection/connect-device-tokens.ts
async function issueGatewayConnectDeviceTokens(e) {
const { state: t, scopes: n, hasApprovedDeviceBaseline: r } = e;
const { role: i, device: a, isBrowserOperatorUi: o, isWebchat: s, trustedProxyAuthOk: c, sessionUsesSharedGatewayAuth: l, sessionSharedGatewaySessionGeneration: u, deviceTokenSharedGatewaySessionGeneration: d, handoffBootstrapProfile: f } = t;
const p = u && (d !== void 0 || l && (o || s)) ? {
kind: "shared-gateway-auth",
generation: u
} : void 0;
const m = !c && a && r ? await ensureDeviceToken({
deviceId: a.id,
role: i,
scopes: n,
issuer: p,
isIssuanceCurrent: e.isIssuanceCurrent
}) : null;
const h = [];
if (m) h.push({
deviceToken: m.token,
role: m.role,
scopes: m.scopes,
issuedAtMs: m.rotatedAtMs ?? m.createdAtMs
});
if (a && f) for (const t of f.roles) {
if (h.some((e) => e.role === t)) continue;
const n = t === "operator" ? resolveBootstrapProfileScopesForRole(t, f.scopes, f.purpose) : [];
const r = await ensureDeviceToken({
deviceId: a.id,
role: t,
scopes: n,
isIssuanceCurrent: e.isIssuanceCurrent
});
if (!r) continue;
h.push({
deviceToken: r.token,
role: r.role,
scopes: r.scopes,
issuedAtMs: r.rotatedAtMs ?? r.createdAtMs
});
}
return {
deviceToken: m,
bootstrapDeviceTokens: h
};
}
//#endregion
//#region src/gateway/server/ws-connection/connect-existing-device.ts
async function authorizeExistingGatewayDevice(e) {
const { context: t, state: n, paired: r, devicePublicKey: i, clientAccessMetadata: a, requirePairing: o } = e;
const { connectParams: s, hasBrowserOriginHeader: c, reportedClientIp: l } = t;
const { connId: u, logGateway: d } = t.handler;
const { role: f, scopes: p, device: m, deviceAuthPayloadVersion: h, authMethod: g, bootstrapTokenCandidate: _, pairingLocality: v, isControlUi: y, isBrowserOperatorUi: b, isWebchat: x, isNativeAppUi: S } = n;
let { handoffBootstrapProfile: C } = n;
const w = s.client.platform;
const T = r.platform;
const E = s.client.deviceFamily;
const D = r.deviceFamily;
const O = resolvePinnedClientMetadata({
clientId: s.client.id,
clientMode: s.client.mode,
claimedPlatform: w,
claimedDeviceFamily: E,
pairedPlatform: T,
pairedDeviceFamily: D
});
const { platformMismatch: k, deviceFamilyMismatch: A } = O;
if (k || A) {
if (!shouldAllowSilentLocalPairing({
locality: v,
hasBrowserOriginHeader: c,
isControlUi: y,
isWebchat: x,
isNativeAppUi: S,
authMethod: g,
reason: "metadata-upgrade"
})) d.warn(`security audit: device metadata upgrade requested reason=metadata-upgrade device=${m?.id} ip=${l ?? "unknown-ip"} auth=${g} payload=${h ?? "unknown"} claimedPlatform=${w ?? "<none>"} pinnedPlatform=${T ?? "<none>"} claimedDeviceFamily=${E ?? "<none>"} pinnedDeviceFamily=${D ?? "<none>"} client=${s.client.id} conn=${u}`);
if (!await o("metadata-upgrade", r)) return {
ok: false,
handoffBootstrapProfile: C
};
} else {
if (O.pinnedPlatform) s.client.platform = O.pinnedPlatform;
if (O.pinnedDeviceFamily) s.client.deviceFamily = O.pinnedDeviceFamily;
}
const j = listEffectivePairedDeviceRoles(r);
const M = resolvePairedAccessScopes(r);
if (!j.includes(f) && !await o("role-upgrade", r)) return {
ok: false,
handoffBootstrapProfile: C
};
if (p.length > 0 && !n.remoteIngressPrincipal) {
if (!(M.length > 0 && roleScopesAllow({
role: f,
requestedScopes: p,
allowedScopes: M
})) && !await o("scope-upgrade", r)) return {
ok: false,
handoffBootstrapProfile: C
};
}
const N = g === "bootstrap-token" && _ && isMobileNodeBootstrapConnect({
role: f,
scopes: p,
isControlUi: y,
isBrowserOperatorUi: b,
isWebchat: x,
clientMode: s.client.mode
}) && m ? await getBoundDeviceBootstrapProfile({
token: _,
deviceId: m.id,
publicKey: i
}) : null;
if (N && N.roles.includes("operator") && isSetupCodeHandoffBootstrapClient({
profile: N,
client: s.client
})) {
const e = resolveBootstrapProfileScopesForRole("operator", N.scopes, N.purpose);
if (!(j.includes("operator") && roleScopesAllow({
role: "operator",
requestedScopes: e,
allowedScopes: M
})) && !await o("scope-upgrade", r)) return {
ok: false,
handoffBootstrapProfile: C
};
if (pairedDeviceAllowsBootstrapProfile({
device: m ? await getPairedDevice(m.id) : null,
devicePublicKey: i,
profile: N
}, ["operator"])) C = N;
}
if (m) t.pendingDeviceMetadata = {
deviceId: m.id,
identity: r,
patch: {
...a,
...O.refreshPairedPlatform ? { platform: O.refreshPairedPlatform } : {}
}
};
return {
ok: true,
handoffBootstrapProfile: C
};
}
//#endregion
//#region src/gateway/node-pairing-ssh-verify.runtime.ts
const MAX_PROBE_OUTPUT_BYTES = 65536;
const REMOTE_IDENTITY_COMMAND = "sh -lc 'openclaw node identity --json'";
/** Read the node device identity back from the pairing host over SSH. */
async function runNodeIdentityProbe(e) {
const t = [
"-o",
"BatchMode=yes",
"-o",
"ConnectTimeout=5",
"-o",
"NumberOfPasswordPrompts=0",
"-o",
"PreferredAuthentications=publickey",
"-o",
"StrictHostKeyChecking=yes",
"-o",
"UpdateHostKeys=no",
"-a",
"-x",
"-o",
"ForwardAgent=no",
"-o",
"ForwardX11=no",
"-o",
"ForwardX11Trusted=no",
"-o",
"ClearAllForwardings=yes",
"-o",
"ExitOnForwardFailure=yes",
"-p",
"22"
];
if (e.identity?.trim()) t.push("-i", e.identity.trim(), "-o", "IdentitiesOnly=yes");
t.push("--", `${e.user}@${e.host}`, REMOTE_IDENTITY_COMMAND);
try {
const n = await runUtf8CommandWithTimeout(["ssh", ...t], {
maxOutputBytes: MAX_PROBE_OUTPUT_BYTES,
outputCapture: "head",
timeoutMs: Math.max(250, e.timeoutMs)
});
if (n.termination === "timeout") return { status: "timeout" };
if (n.code === 0) return {
status: "ok",
stdout: n.stdout
};
return {
status: "failed",
code: n.code,
stderr: n.stderr
};
} catch (e) {
return {
status: "spawn-error",
message: e instanceof Error ? e.message : String(e)
};
}
}
//#endregion
//#region src/gateway/node-pairing-ssh-verify.ts
const DEFAULT_TIMEOUT_MS = 7e3;
const FAILURE_COOLDOWN_MS = 6e4;
const MISMATCH_COOLDOWN_MS = 3e5;
const MAX_CONCURRENT_PROBES = 4;
const MAX_COOLDOWN_ENTRIES = 512;
function resolveProcessUser() {
try {
const e = os.userInfo().username.trim();
if (e) return e;
} catch {}
return (process.env.USER ?? process.env.USERNAME)?.trim() || void 0;
}
/** Normalize the enabled-by-default config union into a probe policy, or null when off. */
function resolveNodePairingSshVerifyPolicy(e) {
if (e === false) return null;
const t = typeof e === "object" && e !== null ? e : {};
const n = t.user?.trim() || resolveProcessUser();
if (!n) return null;
const r = t.cidrs?.map((e) => e.trim()).filter((e) => e.length > 0).toSorted();
return {
user: n,
identity: t.identity?.trim() || void 0,
timeoutMs: typeof t.timeoutMs === "number" && Number.isFinite(t.timeoutMs) && t.timeoutMs > 0 ? t.timeoutMs : DEFAULT_TIMEOUT_MS,
cidrs: r && r.length > 0 ? r : void 0
};
}
function normalizeProbeHost(e) {
const t = e.trim();
const n = t.toLowerCase().startsWith("::ffff:") ? t.slice(7) : t;
if (n.includes("%") || net.isIP(n) === 0) return null;
return n;
}
/**
* Resolve whether this pairing request qualifies for an SSH verification probe.
* Shares the fresh-node eligibility floor with trusted-CIDR auto-approval and
* additionally bounds the probe target: default private/CGNAT ranges only, so
* a token holder cannot use the gateway as an SSH probe primitive against
* arbitrary public addresses.
*/
function planNodePairingSshVerify(e) {
const t = resolveNodePairingSshVerifyPolicy(e.config);
if (!t) return null;
if (!isEligibleFreshNodePairingRequest(e.eligibility) || !e.eligibility.reportedClientIp) return null;
if (!(t.cidrs ? isTrustedProxyAddress(e.eligibility.reportedClientIp, t.cidrs) : isPrivateOrLoopbackAddress(e.eligibility.reportedClientIp) && !isLoopbackAddress(e.eligibility.reportedClientIp))) return null;
const n = normalizeProbeHost(e.eligibility.reportedClientIp);
return n ? {
policy: t,
host: n
} : null;
}
function parseRemoteIdentity(e) {
for (const t of e.split("\n")) {
const e = t.trim();
if (!e.startsWith("{")) continue;
try {
const t = JSON.parse(e);
if (typeof t.deviceId === "string" && typeof t.publicKey === "string") return {
deviceId: t.deviceId.trim(),
publicKey: t.publicKey.trim()
};
} catch {}
}
return null;
}
const inFlightByKey = /* @__PURE__ */ new Map();
const cooldownExpiryByKey = /* @__PURE__ */ new Map();
function probeKey(e, t, n) {
return JSON.stringify([
e.host,
t,
n,
e.policy.user,
e.policy.identity,
e.policy.timeoutMs,
e.policy.cidrs
]);
}
function pruneCooldowns(e) {
for (const [t, n] of cooldownExpiryByKey) if (n <= e) cooldownExpiryByKey.delete(t);
pruneMapToMaxSize(cooldownExpiryByKey, MAX_COOLDOWN_ENTRIES);
}
/**
* Start an SSH verification for one pending pairing request. Returns null when
* the probe should not run right now (cooldown or concurrency cap) so callers
* keep the default manual-approval reconnect behavior. A reconnect that lands
* while the probe is still running gets `alreadyInFlight: true`: the client
* must keep its retry hint, but only the connection that started the probe
* owns the approval work.
*/
function startNodePairingSshVerify(e) {
const t = Date.now();
pruneCooldowns(t);
const n = probeKey(e.plan, e.expectedDeviceId, e.expectedPublicKey);
const r = inFlightByKey.get(n);
if (r) return {
done: r,
alreadyInFlight: true
};
if ((cooldownExpiryByKey.get(n) ?? 0) > t) return null;
if (inFlightByKey.size >= MAX_CONCURRENT_PROBES) return null;
const i = (async () => {
const t = await runNodeIdentityProbe({
user: e.plan.policy.user,
host: e.plan.host,
identity: e.plan.policy.identity,
timeoutMs: e.plan.policy.timeoutMs
});
if (t.status !== "ok") {
cooldownExpiryByKey.set(n, Date.now() + FAILURE_COOLDOWN_MS);
return {
ok: false,
reason: "probe-failed"
};
}
const r = parseRemoteIdentity(t.stdout);
if (!r) {
cooldownExpiryByKey.set(n, Date.now() + FAILURE_COOLDOWN_MS);
return {
ok: false,
reason: "identity-unreadable"
};
}
const i = normalizeEd25519PublicKeyBase64Url(e.expectedPublicKey);
const a = normalizeEd25519PublicKeyBase64Url(r.publicKey);
if (!(Boolean(i) && i === a && r.deviceId === e.expectedDeviceId)) {
cooldownExpiryByKey.set(n, Date.now() + MISMATCH_COOLDOWN_MS);
return {
ok: false,
reason: "identity-mismatch"
};
}
return {
ok: true,
user: e.plan.policy.user,
host: e.plan.host
};
})();
return {
done: getOrCreatePromise(inFlightByKey, n, () => i, { evictOnSettled: true }),
alreadyInFlight: false
};
}
//#endregion
//#region src/gateway/server/ws-connection/connect-node-pairing-ssh.ts
function startGatewayNodePairingSshApproval(e) {
const { context: t, state: n, pairing: r, existingPairedDevice: i, devicePublicKey: a, clientAccessMetadata: o } = e;
const { connectParams: s, configSnapshot: c, reportedClientIp: l, reportedClientIpSource: u, hasBrowserOriginHeader: d, runDetachedConnectWork: f } = t;
const { connId: p, buildRequestContext: m, logGateway: h } = t.handler;
const { device: g, role: _, scopes: v, isControlUi: y, isWebchat: b } = n;
if (!g || r.request.silent === true) return false;
if (!isScopelessNodePairingRequest(r.request)) return false;
const x = {
existingPairedDevice: Boolean(i),
role: _,
reason: e.reason,
scopes: v,
hasBrowserOriginHeader: d,
isControlUi: y,
isWebchat: b,
reportedClientIpSource: u,
reportedClientIp: l
};
const S = planNodePairingSshVerify({
config: c.gateway?.nodes?.pairing?.sshVerify,
eligibility: x
});
const C = S ? startNodePairingSshVerify({
plan: S,
expectedDeviceId: g.id,
expectedPublicKey: a
}) : null;
if (S && C && !C.alreadyInFlight) {
const e = r.request.requestId;
f(async () => {
const t = await C.done;
if (!t.ok) {
h.info(`node pairing ssh-verify did not approve device=${g.id} host=${S.host} reason=${t.reason}`);
return;
}
const n = await approveDevicePairing(e, {
callerScopes: v,
accessMetadata: o,
approvedVia: "ssh-verified",
isApprovalCurrent: ({ pending: e, existing: t }) => {
const n = getRuntimeConfigSnapshot();
if (!n || e.deviceId !== g.id || e.publicKey !== a || !isScopelessNodePairingRequest(e)) return false;
return isDeepStrictEqual(S, planNodePairingSshVerify({
config: n.gateway?.nodes?.pairing?.sshVerify,
eligibility: {
...x,
existingPairedDevice: Boolean(t),
scopes: e.scopes ?? []
}
}));
}
});
if (n?.status !== "approved") {
const e = n?.status === "forbidden" ? n.reason : "request superseded or already resolved";
h.info(`node pairing ssh-verify approval skipped device=${g.id} (${e})`);
return;
}
h.info(`security audit: device pairing ssh-verified auto-approve device=${g.id} ip=${l ?? "unknown-ip"} sshUser=${t.user} client=${s.client.id} conn=${p}`);
m().broadcast("device.pair.resolved", {
requestId: e,
deviceId: g.id,
decision: "approved",
ts: Date.now()
}, { dropIfSlow: true });
}, (e) => {
h.warn(`node pairing ssh-verify failed device=${g.id}: ${String(e)}`);
});
}
return Boolean(S && C);
}
//#endregion
//#region src/gateway/server/ws-connection/connect-pairing-approval-plan.ts
const DEFAULT_TRUSTED_PROXY_DEVICE_AUTO_APPROVE_SCOPES = [
"operator.read",
"operator.write",
"operator.approvals",
"operator.questions"
];
function resolveTrustedProxyDeviceAutoApproveScopes(e) {
const t = normalizeSortedUniqueTrimmedStringList(e.configuredScopes ?? [...DEFAULT_TRUSTED_PROXY_DEVICE_AUTO_APPROVE_SCOPES]);
if (!e.hasRequestedScopes) return t;
const n = new Set(t);
return normalizeSortedUniqueTrimmedStringList([...e.requestedScopes, ...e.configuredScopes === void 0 ? ["operator.questions"] : []]).filter((e) => n.has(e));
}
/** Reused at planning and synchronous approval commit so config changes revoke the same policy. */
function resolveLocalPairingApproval(e) {
const { reason: t, existingPairedDevice: n, state: r, configSnapshot: i, scopes: a } = e;
const { role: o, isControlUi: s, isWebchat: c, isNativeAppUi: l, authMethod: u, pairingLocality: d } = r;
const f = o === "node" && t === "role-upgrade" && n?.publicKey === r.devicePublicKey && !n?.tokens?.node && a.length === 0 && !e.hasBrowserOriginHeader && !s && !c;
if ((!n || o === "operator" || f) && shouldAllowSilentLocalPairing({
autoApproveLocal: i.gateway?.nodes?.pairing?.autoApproveLocal,
locality: d,
hasBrowserOriginHeader: e.hasBrowserOriginHeader,
isControlUi: s,
isWebchat: c,
isNativeAppUi: l,
authMethod: u,
reason: t
})) return "silent";
return shouldAutoApproveNodePairingFromTrustedCidrs({
existingPairedDevice: Boolean(n),
role: o,
reason: t,
scopes: a,
hasBrowserOriginHeader: e.hasBrowserOriginHeader,
isControlUi: s,
isWebchat: c,
reportedClientIpSource: e.reportedClientIpSource,
reportedClientIp: e.reportedClientIp,
autoApproveCidrs: i.gateway?.nodes?.pairing?.autoApproveCidrs
}) ? "trusted-cidr" : null;
}
async function resolvePairingApprovalPlan(e) {
const { reason: t, existingPairedDevice: n, state: r, connectParams: i, configSnapshot: a, scopes: o } = e;
const { role: s, isControlUi: c, isBrowserOperatorUi: l, isWebchat: u, isNativeAppUi: d, authMethod: f, authResult: p, bootstrapTokenCandidate: m } = r;
const h = resolveLocalPairingApproval(e);
const g = a.gateway?.auth?.trustedProxy?.deviceAutoApprove;
const _ = p.user?.trim();
const v = t === "scope-upgrade" && n?.publicKey === e.devicePublicKey;
const y = f === "remote-ingress" && r.remoteIngressPrincipal ? "remote-ingress" : f === "trusted-proxy" && (l || u || d) && Boolean(_) && g?.enabled === true ? "trusted-proxy" : null;
const b = (t === "not-paired" && !n || v) && s === "operator" && y !== null ? e.connectionScopeCap(y === "remote-ingress" ? o : resolveTrustedProxyDeviceAutoApproveScopes({
requestedScopes: o,
hasRequestedScopes: e.hasRequestedScopes,
configuredScopes: g?.scopes
})) : null;
const x = isMobileNodeBootstrapConnect({
role: s,
scopes: o,
isControlUi: c,
isBrowserOperatorUi: l,
isWebchat: u,
clientMode: i.client.mode
});
const S = f === "bootstrap-token" && m && (t === "not-paired" && !n || t === "scope-upgrade" && Boolean(n)) && (x || c && s === "operator") ? await getBoundDeviceBootstrapProfile({
token: m,
deviceId: e.deviceId,
publicKey: e.devicePublicKey
}) : null;
const C = S !== null && x && isSetupCodeHandoffBootstrapClient({
profile: S,
client: i.client
});
const w = C ? S : null;
const T = t === "scope-upgrade" && isControlUiOwnerBootstrapProfile({
profile: S,
requestedScopes: o
});
const E = t === "not-paired" && isControlUiOperatorBootstrapProfile({
profile: S,
requestedScopes: o
}) || T;
const D = E ? S : null;
const O = w ? uniqueStrings([s, ...w.roles]) : D ? ["operator"] : void 0;
const k = w ? resolveBootstrapProfileScopesForRoles(O ?? [], w.scopes, w.purpose) : D ? resolveBootstrapProfileScopesForRole("operator", D.scopes, D.purpose) : void 0;
return {
silent: h !== null || C || E,
localApproval: h,
autoApproveOperatorScopes: b,
operatorApprovalKind: y,
trustedProxyUser: _,
isSameKeyScopeUpgrade: v,
allowSetupCodeHandoffBootstrapPairing: C,
bootstrapApprovalProfile: w ?? D,
bootstrapPairingRoles: O,
bootstrapPairingScopes: k
};
}
//#endregion
//#region src/gateway/server/ws-connection/connect-device-pairing.ts
async function authorizeGatewayConnectDevice(e, t) {
const { connId: n, buildRequestContext: r, close: i, setHandshakeState: a, setCloseCause: o, logGateway: s, requestOrigin: c } = e.handler;
const { sendHandshakeErrorResponse: l, connectParams: u, configSnapshot: d, reportedClientIp: f, reportedClientIpSource: p, hasBrowserOriginHeader: m } = e;
let { scopes: h } = t;
let { handoffBootstrapProfile: g } = t;
const { role: _, device: v, devicePublicKey: y, authMethod: b, authResult: x, hasRequestedScopes: S, skipLocalBackendSelfPairing: C, controlUiPairingKind: w } = t;
const isConnectAuthorizationCurrent = () => resolveGatewayConnectPolicyFailure(e, t) === void 0;
const failPairingHandshake = (e) => {
const { message: t, details: n, closeCause: r, closeReason: s } = e;
a("failed");
if (r) o(r.cause, r.meta);
l(ErrorCodes.NOT_PAIRED, t, n ? { details: n } : void 0);
i(1008, truncateCloseReason(s ?? t));
};
const T = _ === "operator" && Boolean(d.gateway?.roles);
if (T && !(b === "token" || b === "password") && !x.user?.trim() && t.remoteIngressPrincipal?.operatorRoleActor.kind !== "operator") {
failPairingHandshake({
message: "operator role policies require a verified user identity for this authentication method; reconnect through the trusted proxy or Tailscale, or use the shared gateway token/password",
details: { code: ConnectErrorDetailCodes.AUTH_VERIFIED_USER_REQUIRED }
});
return;
}
let E = false;
let D;
let O;
u.client = normalizeNodeHostCompatibilityMetadata(u.client);
const k = isBrowserCopilotClient(u.client) ? normalizeChromeExtensionOrigin(c) : void 0;
if (v && y) {
const formatAuditList = (e) => normalizeSortedUniqueTrimmedStringList(e).join(",") || "<none>";
const logUpgradeAudit = (e, t, r) => s.warn(`security audit: device access upgrade requested reason=${e} device=${v.id} ip=${f ?? "unknown-ip"} auth=${b} roleFrom=${formatAuditList(t)} roleTo=${_} scopesFrom=${formatAuditList(r)} scopesTo=${formatAuditList(h)} client=${u.client.id} conn=${n}`);
const a = {
displayName: u.client.displayName,
platform: u.client.platform,
deviceFamily: u.client.deviceFamily,
clientId: u.client.id,
clientMode: u.client.mode,
...k ? { browserOrigin: k } : {},
role: _,
scopes: h,
remoteIp: f
};
const o = {
displayName: u.client.displayName,
remoteIp: f,
lastSeenAtMs: Date.now(),
lastSeenReason: "connect"
};
const requirePairing = async (n, c = null) => {
const pairingStateAllowsRequestedAccess = (e, t = h) => e?.publicKey === y && hasEffectivePairedDeviceRole(e, _) && roleScopesAllow({
role: _,
requestedScopes: t,
allowedScopes: resolvePairedAccessScopes(e)
});
const x = {
reason: n,
existingPairedDevice: c,
state: t,
connectParams: u,
configSnapshot: d,
hasBrowserOriginHeader: m,
reportedClientIp: f,
reportedClientIpSource: p,
deviceId: v.id,
devicePublicKey: y,
scopes: h,
hasRequestedScopes: S,
connectionScopeCap: (t) => applyConnectionScopeCap({
role: _,
scopes: t,
upgradeReq: e.handler.upgradeReq
})
};
const C = await resolvePairingApprovalPlan(x);
if (n === "scope-upgrade" && C.isSameKeyScopeUpgrade && C.autoApproveOperatorScopes !== null) {
const e = await getPairedDevice(v.id);
if (e && pairingStateAllowsRequestedAccess(e, C.autoApproveOperatorScopes)) {
const t = resolvePairedAccessScopes(e);
h = normalizeSortedUniqueTrimmedStringList([...h, ...C.autoApproveOperatorScopes].filter((e) => roleScopesAllow({
role: _,
requestedScopes: [e],
allowedScopes: t
})));
u.scopes = h;
return true;
}
}
if (n === "role-upgrade" || n === "scope-upgrade") logUpgradeAudit(n, c ? listEffectivePairedDeviceRoles(c) : void 0, c ? resolvePairedAccessScopes(c) : void 0);
const w = t.isControlUi && _ === "operator";
const T = new AbortController();
const cancelPairingWait = () => T.abort();
let E;
const k = await requestDevicePairing({
deviceId: v.id,
publicKey: y,
...a,
scopes: h,
...C.bootstrapPairingRoles ? {
roles: C.bootstrapPairingRoles,
scopes: C.bootstrapPairingScopes ?? []
} : {},
silent: C.silent
}, void 0, w ? (t) => {
e.handler.socket.once("close", cancelPairingWait);
E = waitForDevicePairingResolution(t.request, {
expiresAtMs: t.expiresAtMs,
signal: T.signal
}).finally(() => e.handler.socket.off("close", cancelPairingWait));
if (e.handler.isClosed()) cancelPairingWait();
} : void 0);
const A = k.request.isRepair !== true || C.isSameKeyScopeUpgrade ? C.autoApproveOperatorScopes : null;
const j = r();
const M = Date.now();
for (const e of k.superseded ?? []) broadcastRejectedDevicePairing(j.broadcast, e, M);
let N;
const P = A !== null || k.request.silent === true || _ === "node" && n === "role-upgrade" && C.localApproval === "silent";
if (P) {
if (A !== null && C.operatorApprovalKind) N = await approveDevicePairing(k.request.requestId, {
callerScopes: A,
accessMetadata: o,
approvedVia: C.operatorApprovalKind,
autoApproveNewDeviceScopes: A,
isApprovalCurrent: isConnectAuthorizationCurrent
});
else if (C.bootstrapApprovalProfile) N = await approveBootstrapDevicePairing(k.request.requestId, C.bootstrapApprovalProfile, {
accessMetadata: o,
isApprovalCurrent: isConnectAuthorizationCurrent,
onTokensReplaced: (e, t) => retireDeviceTokenClients(j, e, t, "device-token-rotated")
});
else if (C.localApproval) N = await approveDevicePairing(k.request.requestId, {
callerScopes: uniqueStrings([...h, ...c ? resolvePairedAccessScopes(c) : []]),
accessMetadata: o,
approvedVia: C.localApproval,
isApprovalCurrent: ({ pending: e, existing: t }) => {
const n = getRuntimeConfigSnapshot();
if (!n || !isConnectAuthorizationCurrent() || e.deviceId !== v.id || e.publicKey !== y || _ === "node" && (e.role !== _ || e.roles?.some((e) => e !== _)) || C.localApproval === "trusted-cidr" && !isScopelessNodePairingRequest(e)) return false;
return resolveLocalPairingApproval({
...x,
configSnapshot: n,
existingPairedDevice: t ?? null,
scopes: e.scopes ?? []
}) === C.localApproval;
}
});
if (N?.status === "approved") {
if (A !== null) {
h = A;
u.scopes = h;
}
if (C.bootstrapApprovalProfile) g = C.bootstrapApprovalProfile;
if (A !== null && C.trustedProxyUser) s.warn(`security audit: trusted-proxy operator device auto-approved user=${formatForLog(C.trustedProxyUser)} device=${formatForLog(N.device.deviceId.slice(0, 12))} scopes=${formatAuditList(h)}`);
else s.info(`device pairing auto-approved device=${N.device.deviceId} role=${N.device.role ?? "unknown"}`);
j.broadcast("device.pair.resolved", {
requestId: k.request.requestId,
deviceId: N.device.deviceId,
decision: "approved",
ts: Date.now()
}, { dropIfSlow: true });
if (!C.allowSetupCodeHandoffBootstrapPairing) try {
await pruneSupersededSilentPairingsAfterApproval({
deviceId: N.device.deviceId,
connectedDeviceIds: [...e.handler.clients].flatMap((e) => e.connect.device && !e.invalidated ? [e.connect.device.id] : []),
context: j
});
} catch (e) {
s.warn(`device pairing prune failed device=${N.device.deviceId} error=${String(e)}`);
}
}
} else if (k.created) j.broadcast("device.pair.requested", k.request, { dropIfSlow: true });
const F = startGatewayNodePairingSshApproval({
context: e,
state: {
...t,
scopes: h,
handoffBootstrapProfile: g
},
pairing: k,
existingPairedDevice: c,
devicePublicKey: y,
clientAccessMetadata: o,
reason: n
});
const I = await getPairedDevice(v.id);
const L = resolvePinnedClientMetadata({
clientId: u.client.id,
clientMode: u.client.mode,
claimedPlatform: u.client.platform,
claimedDeviceFamily: u.client.deviceFamily,
pairedPlatform: I?.platform,
pairedDeviceFamily: I?.deviceFamily
});
if (!(!L.platformMismatch && !L.deviceFamilyMismatch && (C.bootstrapApprovalProfile ? pairedDeviceAllowsBootstrapProfile({
device: I,
devicePublicKey: y,
profile: C.bootstrapApprovalProfile
}) : pairingStateAllowsRequestedAccess(I)))) {
const { pending: r } = await listDevicePairing();
const a = (r.find((e) => e.requestId === k.request.requestId) ?? r.find((e) => e.deviceId === v.id && e.publicKey === y))?.requestId;
if (P && a === k.request.requestId) j.broadcast("device.pair.requested", k.request, { dropIfSlow: true });
const o = c?.publicKey === y;
const s = o ? listApprovedPairedDeviceRoles(c) : [];
const u = o ? resolvePairedAccessScopes(c) : [];
const d = b === "bootstrap-token" && n === "not-paired" && _ === "node" && h.length === 0 && !c;
const f = t.isControlUi && _ === "operator" && Boolean(a);
const p = d || F || _ === "node" && Boolean(a) || f;
const m = buildPairingConnectErrorDetails({
reason: n,
requestId: E ? k.request.requestId : a,
...E || p ? {
recommendedNextStep: "wait_then_retry",
retryable: true,
pauseReconnect: false
} : {},
...E ? { waitForResolution: true } : {},
deviceId: v.id,
requestedRole: _,
requestedScopes: h,
...s.length > 0 ? { approvedRoles: s } : {},
...u.length > 0 ? { approvedScopes: u } : {}
});
if (E) {
e.onPairingWait();
l(ErrorCodes.NOT_PAIRED, buildPairingConnectErrorMessage(n), { details: m });
E.then((t) => {
if (!t || e.handler.isClosed()) return;
if (t !== "superseded") e.handler.send({
type: "event",
event: "device.pair.resolved",
payload: {
requestId: k.request.requestId,
deviceId: v.id,
decision: t,
ts: Date.now()
}
});
i(1008, `pairing ${t}`);
});
return false;
}
failPairingHandshake({
message: buildPairingConnectErrorMessage(n),
details: m,
closeCause: {
cause: "pairing-required",
meta: {
deviceId: v.id,
...a ? { requestId: a } : {},
reason: n
}
},
closeReason: buildPairingConnectCloseReason({
reason: n,
requestId: a
})
});
return false;
}
cancelPairingWait();
D = I?.clientId;
O = I?.browserOrigin;
return true;
};
const c = performance.now();
const x = await getPairedDevice(v.id);
e.recordAttachTiming?.("deviceLookupMs", c);
const T = x?.publicKey === y;
if (x && !T && t.remoteIngressPrincipal) {
failPairingHandshake({ message: "Remote Control UI device key does not match the paired device; remove the stale device in Devices and reconnect with a fresh browser identity." });
return;
}
if (t.startupPending && !isStartupNodeBootstrapConnect(u) && (!x || !T || !hasEffectivePairedDeviceRole(x, "node") || !x.nodeSurface)) {
await rejectGatewayStartupConnect(e);
return;
}
if (C || w === "auth-none") {
if (T) {
D = x.clientId;
O = x.browserOrigin;
E = true;
e.pendingDeviceMetadata = {
deviceId: v.id,
identity: x,
patch: o
};
} else if (w === "auth-none" || C && b !== "device-token") E = true;
} else if (!T) {
if (w === null && !await requirePairing("not-paired", x)) return;
E = true;
} else {
D = x.clientId;
O = x.browserOrigin;
E = true;
const n = await authorizeExistingGatewayDevice({
context: e,
state: {
...t,
scopes: h,
handoffBootstrapProfile: g
},
paired: x,
devicePublicKey: y,
clientAccessMetadata: o,
requirePairing
});
if (!n.ok) return;
g = n.handoffBootstrapProfile;
}
}
const A = D !== u.client.id && (isBrowserCopilotClient(u.client) || isBrowserCopilotClient({ id: D }));
const j = isBrowserCopilotClient(u.client) && (!O || !k || O !== k);
if (A || j) {
failPairingHandshake({ message: "browser copilot requires a dedicated paired device identity" });
return;
}
const M = performance.now();
const { deviceToken: N, bootstrapDeviceTokens: P } = t.remoteIngressPrincipal || T && x.user?.trim() ? {
deviceToken: null,
bootstrapDeviceTokens: []
} : await issueGatewayConnectDeviceTokens({
state: {
...t,
scopes: h,
handoffBootstrapProfile: g
},
scopes: h,
hasApprovedDeviceBaseline: E,
isIssuanceCurrent: isConnectAuthorizationCurrent
});
e.recordAttachTiming?.("deviceTokensMs", M);
return {
...t,
scopes: h,
handoffBootstrapProfile: g,
deviceToken: N,
bootstrapDeviceTokens: P
};
}
//#endregion
//#region src/gateway/server/ws-connection/connect-model-catalog.ts
/** Bootstrap uses ordinary request admission and delivery authority, including deferred identity. */
async function publishConnectModelCatalog(e, t) {
const n = e.getClient();
const r = n?.connect.modelCatalog;
if (n?.connect.client.id !== GATEWAY_CLIENT_IDS.CONTROL_UI || !hasGatewayClientCap(n.connect.caps, GATEWAY_CLIENT_CAPS.MODEL_CATALOG_SNAPSHOT) || !r) return;
if (e.startupMethodsReady) await racePromiseWithAbortSignal(e.startupMethodsReady, n.connectionSignal);
let i;
if ("shortId" in r) {
const a = {
type: "req",
id: `catalog-session:${e.connId}`,
method: "sessions.resolve",
params: r
};
const o = {};
await t.dispatch(a, n, Buffer.byteLength(JSON.stringify(a)), void 0, (t) => {
if (!t.ok) return e.send(t);
o.value = t.payload;
return { kind: "sent" };
});
const s = o.value;
if (!s?.ok) return;
i = {
agentId: s.agentId,
sessionKey: s.key
};
} else if (r.sessionKey) i = r;
else {
const t = e.buildRequestContext().getRuntimeConfig();
const n = r.agentId ? normalizeAgentId(r.agentId) : void 0;
i = { agentId: n && listAgentIds(t).includes(n) ? n : resolveGatewayAgentSelectionState(t).defaultId };
}
const a = {
type: "req",
id: `catalog:${e.connId}`,
method: "models.list",
params: {
...i,
view: "configured"
}
};
return t.dispatch(a, n, Buffer.byteLength(JSON.stringify(a)), void 0, (t) => e.send(t.ok ? {
type: "event",
event: "models.snapshot",
payload: {
target: r,
scope: i,
catalog: t.payload
}
} : t));
}
//#endregion
//#region src/gateway/control-ui-identity.ts
/** Advertise browser identity at the ingress that actually authenticates people. */
function resolveControlUiIdentity(e, t) {
if (e.gateway?.controlUi?.enabled === false) return;
let n;
let r;
if (t.mode === "trusted-proxy") n = resolveGatewayPublicOrigin(e);
else if (t.mode !== "none" && t.allowTailscale) {
const e = getTailscalePublishedOrigin();
if (e?.mode === "serve") {
n = e.origin;
r = e.signal;
}
}
if (!n?.startsWith("https://")) return;
return {
url: `${n}${normalizeControlUiBasePath(e.gateway?.controlUi?.basePath)}/`,
signal: r
};
}
//#endregion
//#region src/gateway/server/ws-connection/connect-hello.ts
async function sendGatewayHello(e, t, n, r) {
const { connId: i, bootId: a, nodeReapprovalCoordinator: o, gatewayMethods: s, events: c, buildRequestContext: l, refreshHealthSnapshot: u, close: d, advanceHandshakePhase: f, setCloseCause: p, logGateway: m, logHealth: h } = e.handler;
const { frame: g, connectParams: _, sendFrame: v, onHelloDelivered: y, pendingNodePairingCleanup: b, releasePendingNodePairingCleanup: x } = e;
const { resolvedAuth: S, role: C, scopes: w, device: T, devicePublicKey: E, hasTokenAuth: D, hasPasswordAuth: O, bootstrapTokenCandidate: k, authResult: A, authMethod: j, sessionSharedGatewaySessionGeneration: M, issuedBootstrapProfile: N, handoffBootstrapProfile: P, deviceToken: F, bootstrapDeviceTokens: I } = t;
const L = A.user ? r ?? A.user : void 0;
const ee = L ? [
"principal",
L,
T?.id ?? ""
] : F?.token ? ["device-token", F.token] : M ? [
"shared-auth",
M,
T?.id ?? ""
] : T?.id ? ["device", T.id] : void 0;
const R = C === "operator" && ee ? sha256Base64Url(JSON.stringify(ee)) : void 0;
const z = C === "operator" && !L && Boolean(F);
const te = performance.now();
const ne = getSessionRowProjection(l());
const B = buildGatewaySnapshot({
client: e.handler.getClient(),
includeSensitive: w.includes(ADMIN_SCOPE),
includeUpdateDetails: canReadDetailedUpdateMetadata(C, w),
revisionProjector: l().configRevisionProjector,
sessionRowProjection: ne
});
const V = getHealthCache();
if (V && !_.caps?.includes(GATEWAY_CLIENT_CAPS.HELLO_HEALTH_ON_DEMAND)) {
B.health = _.caps?.includes(GATEWAY_CLIENT_CAPS.HEALTH_SUMMARY) ? projectHealthSummary(V) : V;
B.stateVersion.health = getHealthVersion();
}
e.recordAttachTiming?.("snapshotMs", te);
const re = performance.now();
const H = listControlUiPluginTabs(w, { requireGatewayAuthGrant: S.mode !== "none" });
const U = listControlUiPluginWidgetKinds(w);
const W = listControlUiLinkReaders(w, l().getGatewayMethodRegistry?.());
const G = getRemoteControlUiIngressContext(e.handler.upgradeReq);
const K = normalizeControlUiBasePath(e.configSnapshot.gateway?.controlUi?.basePath);
const ie = G ? {
origin: G.publicOrigin,
basePath: K
} : resolveControlUiLinkLocation(e.configSnapshot);
const q = e.configSnapshot.gateway?.controlUi?.root ? "configured" : "bundled";
const ae = resolveRuntimeServiceBuildId();
const oe = C === "operator" ? resolveOperatorRolePolicy(e.handler.getClient(), e.configSnapshot) : void 0;
const se = oe?.sessions.others;
const J = {
type: "hello-ok",
protocol: 4,
server: {
version: resolveRuntimeServiceVersion(process.env),
...ae ? { buildId: ae } : {},
bootId: a,
controlUiBuildSource: q,
connId: i
},
features: {
methods: resolveBrowserAuthOrigin(e.browserOrigin) ? s : s.filter((e) => e !== "mcp.authLogin"),
events: c,
capabilities: [
GATEWAY_SERVER_CAPS.AGENT_SESSION_ID_CREATE,
SYSTEM_RUN_EXECUTION_CONTEXT_CAPABILITY,
GATEWAY_SERVER_CAPS.BOARD_WIDGET_PUT_CANVAS_DOC,
GATEWAY_SERVER_CAPS.CHAT_SEND_ROUTING_CONTRACT,
...q === "bundled" && e.configSnapshot.gateway?.controlUi?.enabled !== false ? [GATEWAY_SERVER_CAPS.CONTROL_UI_BROWSER_FOCUS] : [],
GATEWAY_SERVER_CAPS.GATEWAY_RESTART_TARGET_SAFE,
GATEWAY_SERVER_CAPS.LOCAL_STATE_OWNER_ROUTING,
GATEWAY_SERVER_CAPS.MODELS_AUTH_SET_API_KEY_OWNER,
GATEWAY_SERVER_CAPS.MODELS_AUTH_LOGIN_OWNER,
GATEWAY_SERVER_CAPS.CHANNELS_PAIRING_LIST_OWNER,
GATEWAY_SERVER_CAPS.CHANNELS_PAIRING_APPROVE_OWNER,
GATEWAY_SERVER_CAPS.EXEC_APPROVALS_GET_OWNER,
GATEWAY_SERVER_CAPS.EXEC_APPROVALS_SET_OWNER,
GATEWAY_SERVER_CAPS.EXEC_APPROVALS_NATIVE_COMMIT,
GATEWAY_SERVER_CAPS.WORKTREES_REMOVE_OWNER,
GATEWAY_SERVER_CAPS.WORKTREES_RESTORE_OWNER,
GATEWAY_SERVER_CAPS.WORKTREES_GC_OWNER,
GATEWAY_SERVER_CAPS.WORKTREES_RECOVER_REMOVAL_OWNER,
GATEWAY_SERVER_CAPS.WORKTREES_RETIRE_SNAPSHOT_OWNER,
GATEWAY_SERVER_CAPS.MODEL_CATALOG_SNAPSHOT,
GATEWAY_SERVER_CAPS.NODE_WORKER_DEVICE_FOLDERS,
GATEWAY_SERVER_CAPS.NODE_PERMISSION_ERRORS,
GATEWAY_SERVER_CAPS.NODE_WORKER_BUNDLE_RETENTION,
GATEWAY_SERVER_CAPS.NODE_WORKER_BUNDLE_STATUS,
GATEWAY_SERVER_CAPS.NODE_WORKER_BUNDLE_PREFETCH,
GATEWAY_SERVER_CAPS.NODE_WORKER_CAPTURED_EXEC_POLICY,
GATEWAY_SERVER_CAPS.NODE_WORKER_WORKSPACE_QUIESCENCE,
GATEWAY_SERVER_CAPS.NODE_WORKER_WORKSPACE_RESULT,
GATEWAY_SERVER_CAPS.NODE_WORKER_ENVIRONMENT_SESSION,
GATEWAY_SERVER_CAPS.NODE_WORKER_HOST_DIAGNOSTICS,
GATEWAY_SERVER_CAPS.NODE_WORKER_IDLE_RETENTION,
GATEWAY_SERVER_CAPS.NODE_WORKER_LAUNCH_TOOL_NAMES,
GATEWAY_SERVER_CAPS.NODE_WORKER_NATIVE_INFERENCE,
GATEWAY_SERVER_CAPS.NODE_WORKER_PORTAL_STREAM,
GATEWAY_SERVER_CAPS.NODE_WORKER_PROMPT_CONTEXT,
GATEWAY_SERVER_CAPS.NODE_WORKER_STATUS_WAIT,
GATEWAY_SERVER_CAPS.PROFILE_BINDING,
GATEWAY_SERVER_CAPS.PUBLISHED_MODEL_CATALOG,
GATEWAY_SERVER_CAPS.PROGRESS_CARD_AGENT_SCOPE,
GATEWAY_SERVER_CAPS.SESSION_SCOPED_CHAT_METADATA,
GATEWAY_SERVER_CAPS.SESSION_SCOPED_MODEL_CATALOG,
GATEWAY_SERVER_CAPS.SESSION_UNREAD_ACK_CONTRACT,
GATEWAY_SERVER_CAPS.SESSION_GOAL_START,
GATEWAY_SERVER_CAPS.SESSION_SETTINGS_CONTRACT,
GATEWAY_SERVER_CAPS.SESSION_SETTINGS_CAS,
GATEWAY_SERVER_CAPS.SENDER_RESTRICTED_HIDDEN_HELPERS,
GATEWAY_SERVER_CAPS.SYSTEM_AGENT_WIZARD_CANCEL,
GATEWAY_SERVER_CAPS.SYSTEM_AGENT_SETUP_MODEL_REF,
GATEWAY_SERVER_CAPS.TASK_SUGGESTIONS_ACCEPT_MODES,
GATEWAY_SERVER_CAPS.TALK_SESSION_CLOSE_DISPOSITION
]
},
snapshot: B,
...ie ? { controlUiUrl: `${ie.origin}${ie.basePath}` } : {},
...K && e.configSnapshot.gateway?.controlUi?.enabled !== false ? { controlUiBasePath: K } : {},
...H.length > 0 ? { controlUiTabs: H } : {},
...U.length > 0 ? { controlUiWidgetKinds: U } : {},
...W.length > 0 ? { controlUiLinkReaders: W } : {},
...Object.keys(n).length > 0 ? { pluginSurfaceUrls: n } : {},
auth: {
method: j,
role: C,
scopes: w,
...C === "operator" ? { roleAllowsAdmin: !oe || oe.scopes.includes("operator.admin") } : {},
...se !== void 0 ? { sessionCap: se } : {},
...R ? { recoveryScope: R } : {},
...z ? { recoveryMigrationAllowed: true } : {},
...F ? {
deviceToken: F.token,
issuedAtMs: F.rotatedAtMs ?? F.createdAtMs,
...I.length > 1 ? { deviceTokens: I.slice(1) } : {}
} : {}
},
policy: {
maxPayload: MAX_PAYLOAD_BYTES,
maxBufferedBytes: MAX_BUFFERED_BYTES,
tickIntervalMs: TICK_INTERVAL_MS,
attachments: resolveChatAttachmentPolicy(e.configSnapshot),
allowedSessionVisibilities: allowedSessionVisibilities(e.configSnapshot),
hasMultipleSessionSharingIdentities: hasMultipleResidentSessionSharingIdentities()
}
};
e.recordAttachTiming?.("helloDescriptorsMs", re);
f("hello_payload_prepared");
let Y;
if (j === "bootstrap-token" && k && T) try {
if (P || N) {
const t = await redeemDeviceBootstrapTokenProfile({
token: k,
role: C,
scopes: w
});
if (P || t.fullyRedeemed) {
const t = await consumeSetupHandoff({
token: k,
deviceId: T.id,
admitsCloudWorkerSetup: e.handler.admitsNodeSetupCompletion,
pairedDeviceMatches: (e) => e?.publicKey === E
});
if (!t) {
await x();
p("bootstrap-token-consume-failed");
e.sendHandshakeErrorResponse(ErrorCodes.UNAVAILABLE, "bootstrap token unavailable");
d(1008, "bootstrap token unavailable");
return;
}
Y = t;
}
}
} catch (e) {
m.warn(`bootstrap token post-connect bookkeeping failed device=${T.id}: ${formatForLog(e)}`);
await x();
throw e;
}
let ce = false;
try {
if (C === "operator") {
const t = resolveControlUiIdentity(e.configSnapshot, S);
if (t) {
B.controlUiIdentityUrl = t.url;
if (t.signal && !e.handler.isClosed()) {
const n = t.signal;
const withdraw = () => {
p("browser-identity-route-withdrawn");
d(1012, "browser identity route changed");
};
n.addEventListener("abort", withdraw, { once: true });
e.handler.socket.once("close", () => n.removeEventListener("abort", withdraw));
}
}
}
B.suspension = { phase: getGatewaySuspendAdmissionPhase() };
ce = true;
await v({
type: "res",
id: g.id,
ok: true,
payload: J
});
} catch (e) {
if (Y) {
if (Y.completion) try {
broadcastSetupHandoffDeliveryUncertain({
handoff: Y,
broadcast: l().broadcast
});
} catch (e) {
m.warn(`setup delivery-uncertain broadcast failed device=${T?.id ?? "unknown"}: ${formatForLog(e)}`);
}
else try {
await restoreGenericDeviceBootstrapToken({ record: Y.record });
} catch (e) {
m.warn(`generic bootstrap token restore after hello-send failure failed device=${T?.id ?? "unknown"}: ${formatForLog(e)}`);
}
}
await x();
if (!ce) throw e;
p("hello-send-failed", { error: formatForLog(e) });
m.warn(`hello delivery failed conn=${i}: ${formatForLog(e)}`);
d(1011, "gateway hello delivery failed");
return;
}
y();
const X = e.pendingDeviceMetadata;
if (X) e.runDetachedConnectWork(() => recordPairedDeviceAccess(X.deviceId, X.patch, X.identity), (e) => m.warn(`device access metadata refresh failed conn=${i}: ${formatForLog(e)}`));
try {
const t = e.handler.getClient();
if (t?.presenceKey && !t.invalidated && t.socket.readyState === 1 && !e.handler.isClosed()) commitPresence(t.presenceKey, i);
} catch (e) {
m.warn(`presence commit failed conn=${i}: ${formatForLog(e)}`);
}
if (Y) try {
const e = await confirmSetupHandoffDelivery({ handoff: Y });
if (e) broadcastSetupHandoffCompletion({
handoff: e,
broadcast: l().broadcast
});
else broadcastSetupHandoffDeliveryUncertain({
handoff: Y,
broadcast: l().broadcast
});
} catch (e) {
m.warn(`setup completion confirmation failed device=${T?.id ?? "unknown"}: ${formatForLog(e)}`);
try {
broadcastSetupHandoffDeliveryUncertain({
handoff: Y,
broadcast: l().broadcast
});
} catch {}
}
let le = j;
if (j !== "device-token" && j !== "bootstrap-token") {
if (O) le = "password";
else if (D) le = "token";
}
emitGatewayAuthSecurityEvent({
action: "gateway.auth.succeeded",
outcome: "success",
severity: "low",
authMode: S.mode,
authMethod: j,
authProvided: le,
role: C,
scopes: w,
clientMode: _.client.mode,
deviceId: T?.id
});
f("ready");
if (C === "node") {
const e = l();
const t = _.device?.id ?? _.client.id;
const n = e.nodeRegistry.get(t);
const r = n?.pairingGeneration;
if (n?.connId === i && r) try {
const t = await recordPairedNodeConnection(n.nodeId, n.connectedAtMs, void 0, {
nodeId: n.nodeId,
key: r
});
if (!t.recorded) m.warn(`failed to record last connect for ${n.nodeId}: not paired`);
else {
const i = e.nodeRegistry.getForPairingGeneration(n.nodeId, r);
if (i) scheduleNodeConnectionNotification(e.nodeRegistry, i, { isFirstConnection: t.firstConnection });
}
} catch (e) {
m.warn(`failed to record last connect for ${n.nodeId}: ${formatForLog(e)}`);
}
}
if (b.value) {
const e = l();
const t = b.value;
b.value = void 0;
try {
const n = o ? await o.finalizeCleanup(t) : await finalizeNodePairingCleanupClaim(t);
const r = Date.now();
for (const t of n) broadcastRejectedNodePairing(e.broadcast, t, r);
} catch (e) {
m.warn(`failed to clear stale pending pairings for ${t.nodeId}: ${formatForLog(e)}`);
}
}
logWs("out", "hello-ok", {
connId: i,
methods: s.length,
events: c.length,
presence: B.presence.length,
stateVersion: B.stateVersion.presence
});
if (shouldScheduleBackgroundHealthRefresh(u, Date.now())) u({ probe: false }).catch((e) => h.error(`post-connect health refresh failed: ${formatErrorMessage(e)}`));
const Z = e.handler.getClient();
if (Z?.presenceKey && !Z.invalidated && Z.socket.readyState === 1 && !e.handler.isClosed()) l().publishPresence();
}
//#endregion
//#region src/gateway/server/ws-connection/connect-node-session.ts
var NodePairingRateLimitError = class extends Error {
constructor(e) {
super("node pairing rate limited");
this.retryAfterMs = e;
}
};
async function prepareGatewayNodeConnect(e, t) {
if (t.role !== "node") return true;
const { pluginNodeCapabilities: n = [], nodeReapprovalCoordinator: r, buildRequestContext: i, logGateway: a } = e.handler;
const { connectParams: o, reportedClientIp: s, authRateLimiter: c, browserRateLimitClientIp: l, pendingNodePairingCleanup: u, releasePendingNodePairingCleanup: d, broadcastNodePairingResult: f } = e;
const { device: p, devicePublicKey: m, usesLegacyNodeProtocol: h, rejectUnauthorized: g } = t;
const _ = o.device?.id ?? o.client.id;
const v = await beginNodePairingConnect(_);
const y = v.pairedNode;
u.value = v.cleanupClaim;
const b = p && m ? await getPairedDevice(p.id) : null;
const x = b?.publicKey === m ? b?.approvedVia : void 0;
const S = x === "silent" || x === "ssh-verified" || x === "bootstrap";
let C;
try {
C = await reconcileNodePairingOnConnect({
cfg: readRuntimeConfig(),
connectParams: o,
pairedNode: y,
reportedClientIp: s,
initialSurfaceSilent: S,
requestPairing: async (e) => {
if (y !== null) return r ? await r.request({
input: e,
cleanupClaim: u.value
}) : await requestNodePairing(e);
if (!c) return await requestNodePairing(e);
return await withSerializedRateLimitAttempt({
ip: l,
scope: AUTH_RATE_LIMIT_SCOPE_NODE_PAIRING,
run: async () => {
const t = c.check(l, AUTH_RATE_LIMIT_SCOPE_NODE_PAIRING);
if (!t.allowed) throw new NodePairingRateLimitError(t.retryAfterMs);
const n = await requestNodePairing(e);
c.recordFailure(l, AUTH_RATE_LIMIT_SCOPE_NODE_PAIRING);
return n;
}
});
}
});
} catch (e) {
await d();
if (e instanceof NodePairingRateLimitError) {
g({
ok: false,
reason: "rate_limited",
rateLimited: true,
retryAfterMs: e.retryAfterMs
});
return false;
}
throw e;
}
const isLocalApprovalCurrent = () => !e.handler.isClosed() && readRuntimeConfig().gateway?.nodes?.pairing?.autoApproveLocal !== false;
const w = x === "silent" && isLocalApprovalCurrent() && (t.pairingLocality === "direct_local" || t.pairingLocality === "shared_secret_loopback_local") && !e.hasProxyHeaders && !e.hasBrowserOriginHeader && !t.isControlUi && !t.isWebchat;
if ((w || x === "ssh-verified" || x === "bootstrap") && !y && C.pendingPairing) {
const e = C.pendingPairing.request.requestId;
const t = await approveNodePairing(e, {
callerScopes: [
ADMIN_SCOPE,
PAIRING_SCOPE,
WRITE_SCOPE
],
initialOnly: true,
isApprovalCurrent: w ? isLocalApprovalCurrent : void 0
});
if (t && "node" in t) {
a.info(`security audit: node capability surface ${x} auto-approve node=${C.nodeId} commands=${C.declaredCommands.join(",") || "<none>"}`);
i().broadcast("node.pair.resolved", {
requestId: e,
nodeId: C.nodeId,
decision: "approved",
ts: Date.now()
}, { dropIfSlow: true });
C = {
...C,
effectiveCaps: C.declaredCaps,
effectiveCommands: C.declaredCommands,
effectivePermissions: C.declaredPermissions,
pendingPairing: void 0,
shouldClearPendingPairings: true
};
}
}
if (!C.shouldClearPendingPairings) await d();
if (C.pendingPairing) f(C.pendingPairing);
const T = o;
T.declaredCaps = C.declaredCaps;
T.declaredCommands = C.declaredCommands;
T.withheldCommands = C.withheldCommands;
T.declaredComputerUse = C.declaredComputerUse;
T.declaredPermissions = C.declaredPermissions;
const E = n.map((e) => e.surface);
const D = {
caps: normalizeNodeApprovalSurfaceList(o.caps),
commands: normalizeNodeApprovalSurfaceList(o.commands)
};
const O = h ? filterLegacyNodeProtocolFeatures({
...D,
pluginSurfaces: E
}) : D;
T.sessionCapsCeiling = O.caps;
T.sessionCommandsCeiling = O.commands;
const k = h ? filterLegacyNodeProtocolFeatures({
caps: C.effectiveCaps,
commands: C.effectiveCommands,
pluginSurfaces: E
}) : {
caps: C.effectiveCaps,
commands: C.effectiveCommands
};
o.caps = k.caps;
o.commands = k.commands;
o.computerUse = resolveEffectiveComputerUseDescriptor({
commands: k.commands,
declared: C.declaredComputerUse
});
o.permissions = C.effectivePermissions;
return true;
}
//#endregion
//#region src/gateway/server/ws-connection/connect-operator-access.ts
function prepareGatewayConnectOperatorAccess(e) {
if (e.connect.role !== "operator" || e.internal?.operatorRoleActor?.kind === "system") return;
const t = e.authenticatedUserProfile;
const n = readRuntimeConfig();
if (hasGatewayOperatorAccessPolicies(n) && !t) throw new GatewayOperatorAccessDeniedError();
const r = t ? resolveGatewayOperatorAccessAuthority(t.profileId, n) : void 0;
if (r !== void 0) e.internal = {
...e.internal,
operatorAccessAuthority: r
};
}
async function rejectGatewayConnectOperatorAccess(e) {
e.markHandshakeFailure("operator-access-denied");
e.sendHandshakeErrorResponse(ErrorCodes.FORBIDDEN, GATEWAY_OPERATOR_ACCESS_DENIED_MESSAGE, { details: { code: ConnectErrorDetailCodes.OPERATOR_ACCESS_DENIED } });
await e.releasePendingNodePairingCleanup();
e.handler.close(1008, GATEWAY_OPERATOR_ACCESS_DENIED_MESSAGE);
}
/** Attach only this connection to the grant; disconnect never closes the retained authority. */
function bindGatewayConnectOperatorAccess(e, t) {
const n = t.internal?.operatorAccessAuthority;
if (!n) return true;
const revoke = () => {
e.handler.setCloseCause("operator-access-closed");
invalidateGatewayPolicyClient(t, {
reason: "operator-access-closed",
code: 4001,
message: GATEWAY_OPERATOR_ACCESS_DENIED_MESSAGE,
close: () => e.handler.close(4001, GATEWAY_OPERATOR_ACCESS_DENIED_MESSAGE)
});
};
const release = () => n.signal.removeEventListener("abort", revoke);
t.socket.once("close", release);
n.signal.addEventListener("abort", revoke, { once: true });
if (n.signal.aborted) {
revoke();
return false;
}
return true;
}
/** Capture the accepted credential before any run can retain this connection's authority. */
async function prepareGatewayConnectOperatorDeviceSource(e, t, n) {
const { device: r, devicePublicKey: i, deviceToken: a, authMethod: o } = t;
const s = o === "device-token" ? normalizeOptionalString(e.connectParams.auth?.deviceToken ?? e.connectParams.auth?.token) : a?.token;
const c = r && i && s ? resolveAuthenticatedDeviceTokenIdentity(await loadPairedDevicePairingStoreRecordReadOnly(r.id), {
role: "operator",
publicKey: i,
token: s,
scopes: n
}) : null;
if (s && !c) {
e.markHandshakeFailure("operator-pairing-generation-changed");
e.sendHandshakeErrorResponse(ErrorCodes.NOT_PAIRED, "device pairing changed during connect");
await e.releasePendingNodePairingCleanup();
e.handler.close(1008, "device pairing changed during connect");
return;
}
return c;
}
//#endregion
//#region src/gateway/server/ws-connection/connect-user-profile.ts
/** Provider identity enrichment remains owned by the admitted profile lifecycle. */
function scheduleGatewayConnectProfileSync(e) {
const { context: t, state: n, client: r, lifecycle: i, prepareIngress: a } = e;
const { connId: o, logGateway: s } = t.handler;
const { runDetachedConnectWork: c } = t;
const { authResult: l } = n;
const adoptProfileAvatar = async (e, t) => {
const n = await adoptTailscaleProfileAvatar(e, t);
if (n.avatarMime) await i.attach(n.id, n.updatedAt, a);
};
if (r.authenticatedGitHubIdentitySync) c(async () => {
const e = await r.authenticatedGitHubIdentitySync();
const t = r.authenticatedUserProfile;
const n = l.tailscaleIdentity?.profilePic;
if (!t?.hasAvatar && n) try {
await adoptProfileAvatar(e.profileId, n);
} catch (e) {
s.warn(`Tailscale avatar adoption failed conn=${o}: ${formatForLog(e)}`);
}
}, (e) => {
s.warn(`GitHub identity sync failed conn=${o}: ${formatForLog(e)}`);
});
const u = l.tailscaleIdentity?.profilePic;
const d = r.authenticatedUserProfile?.profileId;
if (!r.authenticatedGitHubIdentitySync && d && !r.authenticatedUserProfile?.hasAvatar && u) c(() => adoptProfileAvatar(d, u), (e) => s.warn(`Tailscale avatar adoption failed conn=${o}: ${formatForLog(e)}`));
}
/** One connection retains its profile authority through admission and later identity refreshes. */
function createGatewayConnectProfileLifecycle(e, t) {
const { handler: n } = e;
let r;
const clientCurrent = () => !n.isClosed() && n.socket.readyState === 1 && (!r || n.getClient() === r && !r.invalidated);
const assertCurrent = () => {
n.connectionWork.signal.throwIfAborted();
if (!clientCurrent() || resolveGatewayConnectPolicyFailure(e, t)) throw new Error("Gateway profile acquisition authority expired");
};
return {
assertCurrent,
isCurrent: (n) => (!n || n.authority.isCurrent()) && !resolveGatewayConnectPolicyFailure(e, t),
bind: (e) => {
r = e;
},
async attach(t, i, a) {
if (!r || !clientCurrent()) return;
const o = r;
assertCurrent();
const s = await resolveAuthenticatedProfile(t, i, assertCurrent);
assertCurrent();
if (r !== o || !s.authority.isCurrent()) throw new Error("Gateway profile changed before attachment");
const { profile: c } = s;
o.preparedRecipientProfileId = void 0;
if (o.authenticatedUserProfile) Object.assign(o.authenticatedUserProfile, c);
else o.authenticatedUserProfile = c;
if (o.internal?.operatorAccessAuthority === void 0) {
prepareGatewayConnectOperatorAccess(o);
if (!bindGatewayConnectOperatorAccess(e, o)) return;
}
prepareGatewayRecipientProfile(o, { identity: s.recipient });
attachGatewayLocalUserIngress(o, a(c));
const { profileId: l, ...u } = c;
n.buildRequestContext().refreshConnectedUserProfile?.({
id: l,
...u
});
}
};
}
async function resolveAuthenticatedProfile(e, t, n, r) {
n?.();
const i = performance.now();
const a = await prepareUserProfileRoleAuthority(e);
r?.("profileAuthorityMs", i);
n?.();
if (!a?.isCurrent()) throw new Error("Gateway profile changed during acquisition");
const o = performance.now();
const { id: s, displayName: c, avatarRevision: l, hasAvatar: u } = a.display;
const d = {
profile: {
profileId: s,
displayName: c,
avatarRevision: l,
hasAvatar: u,
updatedAt: t
},
authority: a,
recipient: {
profileId: a.profileId,
role: a.role,
githubLogin: a.githubLogin ?? null,
aliases: new Set(a.aliases)
}
};
r?.("profileProjectionMs", o);
return d;
}
/** Role and access policies need verified identity before admission; attribution alone may defer it. */
async function resolveGatewayConnectProfileAdmission(e) {
const { context: t, state: n, ownerProfileExpected: r, authenticatedUserId: i } = e;
const a = Boolean(t.configSnapshot.gateway?.roles) || hasGatewayOperatorAccessPolicies(t.configSnapshot);
if (!r && (!i || e.resolveAuthenticatedGitHubIdentity && !a)) return { ok: true };
try {
e.assertCurrent?.();
const a = { assertCurrent: e.assertCurrent };
const o = performance.now();
t.setConnectPhase?.("profile-ensure");
const s = r ? await ensureCanonicalGatewayOwnerProfile(resolveHostAccountName, a) : e.resolveAuthenticatedGitHubIdentity ? await e.resolveAuthenticatedGitHubIdentity() : n.authResult.tailscaleIdentity ? await ensureCanonicalUserProfileForTailscaleIdentity(n.authResult.tailscaleIdentity, a) : await ensureCanonicalUserProfileForEmail(i, a);
e.assertCurrent?.();
e.context.recordAttachTiming?.("profileEnsureMs", o);
t.setConnectPhase?.("profile-authority");
const c = await resolveAuthenticatedProfile("profileId" in s ? s.profileId : s.id, s.updatedAt, e.assertCurrent, t.recordAttachTiming);
e.assertCurrent?.();
if (!c.authority.isCurrent()) throw new Error("Gateway profile changed during acquisition");
return {
ok: true,
prepared: c
};
} catch (e) {
t.handler.logWsControl.warn(`user profile resolution failed conn=${t.handler.connId} user=${formatForLog(i)}: ${formatForLog(e)}`);
if (!r && a && n.role === "operator" && n.authMethod !== "token" && n.authMethod !== "password") {
await rejectUnavailableProfileConnect(t, e);
return { ok: false };
}
return { ok: true };
}
}
//#endregion
//#region src/gateway/server/ws-connection/connect-session.ts
async function attachAuthenticatedGatewayConnect(e, t) {
const { socket: n, connId: r, remoteAddr: i, pluginSurfaceBaseUrl: a, pluginNodeCapabilities: o = [], buildRequestContext: s, close: c, isClosed: l, clearHandshakeTimer: u, setClient: d, setHandshakeState: f, advanceHandshakePhase: p, setCloseCause: m, logGateway: h, logWsControl: g } = e.handler;
const { connectParams: _, isLocalClient: v, reportedClientIp: y, runDetachedConnectWork: b, clientLabel: x, clientMeta: S, markHandshakeFailure: C, sendHandshakeErrorResponse: w, releasePendingNodePairingCleanup: T } = e;
const { minProtocol: E, maxProtocol: D, usesLegacyNodeProtocol: O, role: k, scopes: A, device: j, devicePublicKey: M, deviceToken: N, authResult: P, authMethod: F, pairingLocality: I, sessionUsesSharedGatewayAuth: L, sessionSharedGatewaySessionGeneration: ee, remoteIngressPrincipal: R } = t;
const z = performance.now();
if (!await prepareGatewayNodeConnect(e, t)) return;
const rejectNodePairing = async (e, t = {}) => {
C("node-pairing-generation-changed", t);
w(ErrorCodes.NOT_PAIRED, e);
await T();
c(1008, truncateCloseReason(e));
};
let te;
if (k === "node") {
const e = j?.id ?? _.client.id;
const t = F === "device-token" ? normalizeOptionalString(_.auth?.deviceToken ?? _.auth?.token) : N?.token;
if (!j || !M || !t) {
await rejectNodePairing("authenticated node pairing identity unavailable");
return;
}
const n = {
nodeId: e,
publicKey: M,
token: t
};
const r = await captureAuthenticatedNodePairingState(n);
if (!r) {
await rejectNodePairing("node pairing changed during connect", j.id ? { deviceId: j.id } : {});
return;
}
te = {
...r,
authenticated: n
};
}
e.recordAttachTiming?.("nodePreparationMs", z);
const ne = !isEphemeralGatewayClient(_.client);
const B = _.client.id;
const V = _.client.instanceId;
const re = ne ? k === "node" ? j?.id ?? V ?? r : r : void 0;
const H = normalizeOptionalString(P.user);
const U = resolveTrustedEnterpriseGitHubAccountId({
authResult: P,
authConfig: e.configSnapshot.gateway?.auth,
config: e.configSnapshot
});
const W = (P.tailscaleIdentity ? classifyTailscaleLogin(P.tailscaleIdentity.login) : void 0)?.kind === "provider";
const G = createGatewayConnectProfileLifecycle(e, t);
const K = createAuthenticatedGitHubIdentitySync({
authResult: P,
authConfig: e.configSnapshot.gateway?.auth,
config: e.configSnapshot,
requestHeaders: e.handler.upgradeReq.headers,
assertCurrent: G.assertCurrent,
recordTiming: e.recordAttachTiming
});
const ie = Boolean(e.configSnapshot.gateway?.roles);
const q = k === "operator" && (F === "token" || F === "password" || R?.operatorRoleActor.kind === "system");
const ae = (ne || F !== void 0 && F !== "none") && shouldUseGatewayOwnerProfile({
role: k,
authenticatedUserId: H,
authMethod: F,
rolesConfigured: ie
});
const oe = performance.now();
const se = R ? {
ok: true,
prepared: void 0
} : await resolveGatewayConnectProfileAdmission({
context: e,
state: t,
ownerProfileExpected: ae,
authenticatedUserId: H,
resolveAuthenticatedGitHubIdentity: K,
assertCurrent: G.assertCurrent
});
e.recordAttachTiming?.("identityMs", oe);
if (!se.ok) return;
e.setConnectPhase?.("registration");
const J = se.prepared;
const Y = R?.authenticatedUserProfile ?? J?.profile;
const ce = performance.now();
const X = R ? A : resolveEffectiveConnectionScopes({
role: k,
deviceScopes: A,
verifiedIdentity: t.authPolicy.verifiedIdentity,
identityScopes: e.configSnapshot.gateway?.auth?.identityScopes,
upgradeReq: e.handler.upgradeReq
});
const le = R ? R.operatorRolePolicy : k === "operator" && !q ? resolveOperatorRolePolicyForAssignment(Y?.profileId, J?.authority.role ?? null, e.configSnapshot, J?.authority.githubLogin ?? null) : void 0;
const Z = le ? intersectOperatorScopes(X, le.scopes) : X;
t.scopes = Z;
_.scopes = Z;
if (k === "operator" && H) {
const e = Z.filter((e) => !roleScopesAllow({
role: k,
requestedScopes: [e],
allowedScopes: A
}));
if (e.length > 0) h.info(`security audit: identity scope grant elevated connection identity=${formatForLog(H)} addedScopes=${e.join(",")} auth=${F} conn=${r}`);
}
e.recordAttachTiming?.("scopeGrantMs", ce);
let ue = performance.now();
if (l()) {
await T();
m("connect-aborted-before-register", {
...S,
auth: F
});
return;
}
const de = {};
const fe = indexPluginNodeCapabilitySurfaces(o);
const pe = [];
const me = k === "node" ? new Set(_.caps ?? []) : void 0;
if (a && !O) for (const e of Object.values(fe)) {
if (me && !me.has(e.surface)) continue;
const t = mintPluginNodeCapabilityToken();
const n = resolvePluginNodeCapabilityExpiresAtMs(e);
if (n === void 0) continue;
const r = buildPluginNodeCapabilityScopedHostUrl(a, t) ?? a;
de[e.surface] = r;
pe.push({
surface: e,
capability: t,
expiresAtMs: n
});
}
const he = I !== "remote" && _.client.id === GATEWAY_CLIENT_IDS.GATEWAY_CLIENT && _.client.mode === GATEWAY_CLIENT_MODES.BACKEND;
const ge = _.auth?.agentRuntimeIdentityToken;
let _e;
if (typeof ge === "string") {
if (!he) {
const e = "agent runtime identity token is only accepted from local backend gateway clients";
C("agent-runtime-identity-untrusted-client", {
client: _.client.id,
mode: _.client.mode,
pairingLocality: I
});
w(ErrorCodes.INVALID_REQUEST, e);
c(1008, truncateCloseReason(e));
return;
}
_e = await verifyAgentRuntimeIdentityToken(ge);
if (!_e) {
const e = "invalid agent runtime identity token";
C("agent-runtime-identity-invalid", {
client: _.client.id,
mode: _.client.mode,
pairingLocality: I
});
w(ErrorCodes.INVALID_REQUEST, e);
c(1008, e);
return;
}
}
const ve = k === "operator" && F !== void 0 && F !== "none";
const ye = ve && _.client.id === GATEWAY_CLIENT_IDS.CONTROL_UI;
const be = ye && Z.includes("operator.admin");
const xe = {
...v ? { isLocalClient: true } : {},
...ve ? { authenticatedOperator: true } : {},
...ye ? { authenticatedControlUi: true } : {},
...be ? { controlUiAdmin: true } : {},
..._e ? { agentRuntimeIdentity: _e } : {},
...R ? {
remoteIngressPrincipal: R,
operatorRoleActor: R.operatorRoleActor,
operatorAccessAuthority: R.operatorAccessAuthority
} : q ? { operatorRoleActor: { kind: "system" } } : {}
};
if (ve) {
const n = performance.now();
const r = await prepareGatewayConnectOperatorDeviceSource(e, t, A);
e.recordAttachTiming?.("operatorDeviceMs", n);
if (r === void 0) return;
xe.operatorDeviceTokenIdentity = r;
ue += performance.now() - n;
}
const prepareLocalUserIngress = (e = Y) => prepareGatewayLocalUserIngress({
authMethod: F,
authenticatedUserExpected: Boolean(H) || ae,
...e ? { profile: {
profileId: e.profileId,
displayName: e.displayName
} } : {},
...j?.id ? { pairedDeviceId: j.id } : {},
isLocalClient: v
});
const Se = prepareLocalUserIngress();
if (O) g.warn(`legacy node protocol accepted conn=${r} client=${formatForLog(x)} v${formatForLog(_.client.version)} min=${E} max=${D} current=${4}; upgrade recommended`);
const Q = {
remoteControlUiIngress: getRemoteControlUiIngressContext(e.handler.upgradeReq),
socket: n,
connect: _,
connId: r,
connectionKind: "gateway",
...!O && a ? { pluginSurfaceBaseUrl: a } : {},
isDeviceTokenAuth: F === "device-token",
pairedClientId: isBrowserCopilotClient(_.client) ? _.client.id : void 0,
usesSharedGatewayAuth: L,
sharedGatewaySessionGeneration: ee,
authPolicy: t.authPolicy,
presenceKey: re,
...H ? { authenticatedUserId: H } : {},
...U ? { authenticatedFactoryGitHubAccountId: U } : {},
...W ? { authenticatedUserIsTailscaleProvider: true } : {},
...Y ? { authenticatedUserProfile: Y } : {},
clientIp: y,
...e.browserOrigin ? { browserOrigin: e.browserOrigin } : {},
...Object.keys(xe).length > 0 ? { internal: xe } : {},
...Object.keys(de).length > 0 ? { pluginSurfaceUrls: de } : {},
...Object.keys(fe).length > 0 ? { pluginNodeCapabilitySurfaces: fe } : {}
};
attachGatewayLocalUserIngress(Q, Se);
if (K) Q.authenticatedGitHubIdentitySync = async () => {
const e = await K();
await G.attach(e.profileId, e.updatedAt, prepareLocalUserIngress);
return e;
};
for (const e of pe) setClientPluginNodeCapability({
client: Q,
surface: e.surface,
capability: e.capability,
expiresAtMs: e.expiresAtMs
});
if (k === "node" && v) {
const e = await resolveLocalNodeId();
if (e && j?.id === e) {
const e = resolveRuntimeServiceVersion(process.env);
const t = _.client.version;
const n = compareOpenClawReleaseVersions(t, e);
if (n !== null && n < 0) {
g.info(`node version mismatch conn=${r} client=${formatForLog(x)} clientVersion=${formatForLog(t)} gatewayVersion=${e}; closing for supervisor restart`);
w(ErrorCodes.INVALID_REQUEST, "client version mismatch", { details: {
code: ConnectErrorDetailCodes.CLIENT_VERSION_MISMATCH,
clientVersion: t,
gatewayVersion: e
} });
await T();
c(1008, "client version mismatch");
return;
}
}
}
const $ = k === "node" ? te : void 0;
if ($) {
const e = await captureAuthenticatedNodePairingState($.authenticated);
if (!e || e.identity.key !== $.identity.key || e.generation?.key !== $.generation?.key) {
await rejectNodePairing("node pairing changed during connect", { deviceId: $.identity.nodeId });
return;
}
}
if (he && Z.includes("operator.approvals") && await isOperatorApprovalRuntimeToken(_.auth?.approvalRuntimeToken)) Q.internal = {
...Q.internal,
approvalRuntime: true
};
const Ce = resolveGatewayConnectPolicyFailure(e, t);
if (Ce) {
await T();
if (Ce.kind === "auth") {
m("gateway-auth-rotated", { authGenerationStale: true });
c(4001, "gateway auth changed");
} else rejectGatewayConnectOrigin(e, Ce.reason);
return;
}
const we = e.handler.prepareAuthenticatedReceive(k);
if (!we.ok) {
const { cause: e, message: t } = we.error;
C(e, {});
w(ErrorCodes.UNAVAILABLE, t);
await T();
c(1011, t);
return;
}
try {
if (!R) prepareGatewayConnectOperatorAccess(Q);
} catch {
await rejectGatewayConnectOperatorAccess(e);
return;
}
if (!G.isCurrent(J)) {
await rejectUnavailableProfileConnect(e, /* @__PURE__ */ new Error("Gateway profile changed before registration"));
return;
}
prepareGatewayRecipientProfile(Q, { identity: R?.preparedSessionProfile ?? J?.recipient });
if (!d(Q)) {
await T();
m("connect-aborted-before-register", {
...S,
auth: F
});
return;
}
G.bind(Q);
if (!bindGatewayConnectOperatorAccess(e, Q)) return;
u();
we.value();
f("connected");
p("session_attached");
e.recordAttachTiming?.("sessionRegistrationMs", ue);
if (k === "operator" && !isEphemeralGatewayClient(_.client)) b(async () => {
const { prewarmGatewaySessionHistory: t } = await import("./server-history-prewarm-DGBgwArl.mjs");
await t(readRuntimeConfig(), { isCancelled: () => e.handler.connectionWork.signal.aborted });
}, (e) => h.debug(`connection session history prewarm failed: ${formatForLog(e)}`));
g.info([
`client connected conn=${r}`,
`client=${B} name=${formatForLog(x)}`,
`mode=${_.client.mode} role=${k} auth=${F}`,
`version=${formatForLog(_.client.version)} platform=${formatForLog(_.client.platform)}`,
`build=${formatForLog(_.client.buildId?.trim() || "legacy")} remote=${i ?? "?"}`,
H ? `user=${formatForLog(H)}` : void 0
].filter(Boolean).join(" "));
const currentAuthenticatedPresenceUser = () => Q.authenticatedGitHubIdentitySync && !Q.authenticatedUserProfile ? void 0 : buildAuthenticatedPresenceUser({
authenticatedUserId: H,
authenticatedUserIsTailscaleProvider: W,
authenticatedUserProfile: Q.authenticatedUserProfile
});
if (re) {
const e = currentAuthenticatedPresenceUser();
upsertPresence(re, {
connectionId: r,
host: _.client.displayName ?? _.client.id ?? os.hostname(),
clientId: _.client.id,
ip: v ? void 0 : y,
version: _.client.version,
platform: _.client.platform,
deviceFamily: _.client.deviceFamily,
modelIdentifier: _.client.modelIdentifier,
timeZone: _.client.timeZone,
mode: _.client.mode,
deviceId: j?.id,
roles: [k],
scopes: Z,
instanceId: k === "node" ? j?.id ?? V : V,
...e ? { user: e } : {},
reason: "connect"
}, { pending: true });
}
if ($) {
const t = $.generation?.key;
const n = s();
const r = n.nodeRegistry.register(Q, {
remoteIp: y,
pairingIdentity: $.identity.key,
approvedSurface: $.approvedSurface,
...t ? { pairingGeneration: t } : {}
});
recordRemoteNodeInfo({
nodeId: r.nodeId,
connId: r.connId,
displayName: r.displayName,
platform: r.platform,
deviceFamily: r.deviceFamily,
commands: r.commands,
remoteIp: r.remoteIp,
pairingGeneration: r.pairingGeneration
});
b(async () => {
await refreshRemoteNodeBins({
nodeId: r.nodeId,
platform: r.platform,
deviceFamily: r.deviceFamily,
commands: r.commands,
cfg: readRuntimeConfig(),
readinessDelayMs: 5e3,
readinessSignal: e.handler.connectionWork.signal
});
}, (e) => h.warn(`remote bin check failed for ${r.nodeId}: ${formatForLog(e)}`));
const sendConnectSnapshot = async (e, i) => {
if (t) {
await n.nodeRegistry.sendEventRawForPairingGeneration(r.nodeId, t, e, serializeEventPayload(i));
return;
}
await n.nodeRegistry.sendEventForPairingIdentity({
nodeId: r.nodeId,
connId: r.connId,
pairingIdentity: $.identity.key,
event: e,
payload: i
});
};
b(async () => {
const e = await loadVoiceWakeConfig();
await sendConnectSnapshot("voicewake.changed", { triggers: e.triggers });
}, (e) => h.warn(`voicewake snapshot failed for ${r.nodeId}: ${formatForLog(e)}`));
b(async () => {
const e = await loadVoiceWakeRoutingConfig();
await sendConnectSnapshot("voicewake.routing.changed", { config: e });
}, (e) => h.warn(`voicewake routing snapshot failed for ${r.nodeId}: ${formatForLog(e)}`));
}
await sendGatewayHello(e, t, de, Y?.profileId);
scheduleGatewayConnectProfileSync({
context: e,
state: t,
client: Q,
lifecycle: G,
prepareIngress: prepareLocalUserIngress
});
}
//#endregion
//#region src/gateway/server/ws-connection/message-handler.ts
const GATEWAY_WORK_ADMISSION_RETRY_AFTER_MS = 1e3;
const GATEWAY_WORK_ADMISSION_CLOSE_CODE = 1013;
function claimsWorkerConnectionIdentity(e) {
const t = asOptionalObjectRecord(e);
if (t?.role === "worker") return true;
const n = asOptionalObjectRecord(t?.client);
return n?.id === GATEWAY_CLIENT_IDS.WORKER || n?.mode === GATEWAY_CLIENT_MODES.WORKER;
}
function attachGatewayWsMessageHandler(e) {
const t = getRemoteControlUiIngressContext(e.upgradeReq);
let n = false;
const { socket: r, ingressAttribution: i, connId: a, remoteAddr: o, endpoint: s, forwardedFor: c, requestHost: l, requestOrigin: u, requestUserAgent: d, rateLimiter: f, browserRateLimiter: p, buildRequestContext: m, send: h, close: g, isClosed: _, getClient: v, setHandshakeState: y, setCloseCause: b, setLastFrameMeta: x, logGateway: S, logWsControl: C } = e;
const sendFrame = async (e, n = false) => await new Promise((i, a) => {
const o = JSON.stringify(e);
assertRemoteControlUiIngressCurrent(t);
const sent = (e) => e ? a(e) : i(Buffer.byteLength(o));
if (n && r.sendUncompressed) r.sendUncompressed(o, sent);
else r.send(o, sent);
});
const w = readRuntimeConfig();
const T = w.gateway?.trustedProxies ?? [];
const E = w.gateway?.allowRealIpFallback === true;
const D = i.clientIp;
const O = s ?? o ?? "n/a";
const k = i.kind === "trusted-proxy" || i.kind === "tailscale-serve" || i.kind === "tailscale-funnel";
const A = isLocalishHost(l);
const j = i.kind === "direct-local";
const M = j ? void 0 : D && !isLoopbackAddress(D) ? D : void 0;
const N = resolveNodePairingClientIpSource({
reportedClientIp: M,
hasProxyHeaders: k,
remoteIsTrustedProxy: k,
remoteIsLoopback: isLoopbackAddress(o)
});
if (!A && isLoopbackAddress(o) && !k) C.warn("Loopback connection with non-local Host header. Treating it as remote. If you're behind a reverse proxy, set gateway.trustedProxies and forward X-Forwarded-For/X-Real-IP.");
const isWebchatConnect = (e) => isWebchatClient(e?.client);
const P = createGatewayAuthenticatedRequestDispatcher({
handler: e,
isWebchatConnect
});
const { hasBrowserOriginHeader: F, enforceOriginCheckForAnyClient: I, rateLimitClientIp: L, authRateLimiter: ee } = resolveHandshakeBrowserSecurityContext({
requestOrigin: u,
clientIp: i.rateLimit.subject.key,
rateLimiter: f,
browserRateLimiter: p
});
const runDetachedConnectWork = (t, n) => {
e.connectionWork.track(() => runWithGatewayIndependentRootWorkAdmission(t, "ws:preauth", e.connectionWork.signal)).catch(n);
};
const rejectOversizedPreauthFrame = (e) => {
const t = rawDataByteLength(e);
if (t <= 65536) return false;
logRejectedLargePayload({
surface: "gateway.ws.preauth",
bytes: t,
limitBytes: MAX_PREAUTH_PAYLOAD_BYTES,
reason: "preauth_frame_limit"
});
y("failed");
b("preauth-payload-too-large", {
payloadBytes: t,
limitBytes: MAX_PREAUTH_PAYLOAD_BYTES
});
g(1009, "preauth payload too large");
return true;
};
const handleMessage = async (r, i) => {
if (_()) return;
if (!v() && rejectOversizedPreauthFrame(r)) return;
let s;
try {
s = JSON.parse(rawDataToString(r));
} catch {
y("failed");
b("parse-error", { error: "invalid JSON" });
S.error("parse error: invalid JSON");
logWs("out", "parse-error", {
connId: a,
error: "invalid JSON"
});
g(1007, "invalid JSON");
return;
}
const f = s;
let p = false;
let D;
let A = "returned";
let writeHandshakeResponse;
let R;
let z;
let te;
const ne = {};
const broadcastNodePairingResult = (e) => {
const t = m();
const n = Date.now();
for (const r of e.created ? e.superseded ?? [] : []) broadcastRejectedNodePairing(t.broadcast, r, n);
if (e.created) t.broadcast("node.pair.requested", e.request, { dropIfSlow: true });
};
const releasePendingNodePairingCleanup = async () => {
const e = ne.value;
ne.value = void 0;
if (!e) return;
try {
await releaseNodePairingCleanupClaim(e);
} catch (t) {
S.warn(`failed to release pending pairing cleanup for ${e.nodeId}: ${formatForLog(t)}`);
}
};
const B = v();
try {
const s = asOptionalObjectRecord(f);
if (!B && claimsWorkerConnectionIdentity(s?.params)) {
y("failed");
b("invalid-handshake", { handshakeError: "invalid worker handshake" });
C.warn("worker admission rejected reason=invalid-handshake");
g(1008, "invalid-handshake");
return;
}
const m = readStringField(s, "type");
const _ = readStringField(s, "method");
const v = readStringField(s, "id");
if (m || _ || v) x({
type: m,
method: _,
id: v
});
if (!B) {
const r = validateRequestFrame(f);
if (!r || f.method !== "connect" || !validateConnectParams(f.params)) {
const e = r ? f.method === "connect" ? `invalid connect params: ${formatValidationErrors(validateConnectParams.errors)}` : "invalid handshake: first request must be connect" : "invalid request frame";
y("failed");
b("invalid-handshake", {
frameType: m,
frameMethod: _,
frameId: v,
handshakeError: e
});
if (r) h({
type: "res",
id: f.id,
ok: false,
error: errorShape(ErrorCodes.INVALID_REQUEST, e)
});
else C.warn(`invalid handshake conn=${a} peer=${formatForLog(O)} remote=${o ?? "?"} fwd=${formatForLog(c ?? "n/a")} origin=${formatForLog(u ?? "n/a")} host=${formatForLog(l ?? "n/a")} ua=${formatForLog(d ?? "n/a")}`);
const t = truncateCloseReason(e || "invalid handshake");
if (r) queueMicrotask(() => g(1008, t));
else g(1008, t);
return;
}
const i = f;
D = createGatewayRpcDiagnostics("connect", e.getMethodRegistry, e.extraHandlers);
const s = performance$1.now();
const x = {};
const A = {};
logWs("in", "req", {
connId: a,
id: i.id,
method: "connect"
});
const recordHandshakeResponse = (e, t, n) => {
D?.response(e ? "ok" : "error", t);
logWs("out", "res", {
connId: a,
id: i.id,
method: "connect",
ok: e,
bytes: t,
sendMs: n,
...!e ? {
failurePhase: z,
failureCause: te
} : {},
...A,
authMs: x.auth_validated,
attachMs: x.session_attached === void 0 ? void 0 : x.session_attached - (x.auth_validated ?? 0),
helloMs: x.hello_payload_prepared === void 0 ? void 0 : x.hello_payload_prepared - (x.session_attached ?? 0)
});
};
writeHandshakeResponse = async (e) => {
const t = performance$1.now();
let n;
try {
n = await sendFrame(e, true);
} catch (e) {
D?.response("unavailable");
throw e;
}
recordHandshakeResponse(e.ok, n, performance$1.now() - t);
};
const B = i.params;
const V = B.client.displayName ?? B.client.id;
const re = {
client: B.client.id,
clientDisplayName: B.client.displayName,
mode: B.client.mode,
version: B.client.version,
buildId: B.client.buildId,
platform: B.client.platform,
deviceFamily: B.client.deviceFamily,
modelIdentifier: B.client.modelIdentifier,
instanceId: B.client.instanceId
};
const markHandshakeFailure = (e, t) => {
te = e;
y("failed");
b(e, {
...t,
...re
});
};
const sendHandshakeErrorResponse = (e, t, n) => {
R = H.sendFrame({
type: "res",
id: i.id,
ok: false,
error: errorShape(e, t, n)
}).catch(() => {});
};
const H = {
handler: {
...e,
advanceHandshakePhase: (t) => {
if (t === "auth_validated" || t === "session_attached" || t === "hello_payload_prepared") x[t] = performance$1.now() - s;
e.advanceHandshakePhase(t);
if (t === "session_attached") z = "hello";
}
},
frame: i,
connectParams: B,
configSnapshot: w,
trustedProxies: T,
allowRealIpFallback: E,
peerLabel: O,
hasProxyHeaders: k,
isLocalClient: j,
reportedClientIp: M,
reportedClientIpSource: N,
hasBrowserOriginHeader: F,
browserOrigin: resolveGatewayWsBrowserOrigin({
client: B.client,
requestHost: l,
origin: u,
isLocalClient: j,
enforceOriginCheckForAnyClient: I,
remoteControlUiIngress: t
}),
browserRateLimitClientIp: L,
authRateLimiter: ee,
clientLabel: V,
clientMeta: re,
markHandshakeFailure,
sendHandshakeErrorResponse,
sendFrame: writeHandshakeResponse,
onHelloDelivered: () => {
p = true;
flushQueuedHandshakeFrames();
},
recordAttachTiming: (e, t) => {
A[e] = performance$1.now() - t;
},
setConnectPhase: (e) => {
z = e;
},
onPairingWait: () => {
n = true;
e.clearHandshakeTimer();
},
isWebchatConnect,
runDetachedConnectWork,
pendingNodePairingCleanup: ne,
broadcastNodePairingResult,
releasePendingNodePairingCleanup
};
await GatewayRpcDiagnostics.runHandler("connect", async () => {
try {
z = "auth";
const t = await authenticateGatewayConnect(H);
if (!t) return;
const n = performance$1.now();
z = "device";
const r = await authorizeGatewayConnectDevice(H, t);
H.recordAttachTiming("deviceAuthorizationMs", n);
if (!r) return;
z = "attach";
await attachAuthenticatedGatewayConnect(H, r);
runDetachedConnectWork(() => publishConnectModelCatalog(e, P), (e) => S.debug(`connection model catalog unavailable: ${formatForLog(e)}`));
} finally {
if (R) await R;
}
}, D);
return;
}
await P.dispatch(f, B, rawDataByteLength(r), i);
} catch (e) {
A = "threw";
te ??= "handler-error";
await releasePendingNodePairingCleanup();
S.error(`frame handler failed conn=${a}: ${formatForLog(e)}`);
logWs("out", "handler-error", {
connId: a,
failurePhase: z,
error: formatForLog(e)
});
if (!p && validateRequestFrame(f) && !_()) {
const t = {
type: "res",
id: f.id,
ok: false,
error: errorShape(ErrorCodes.UNAVAILABLE, formatForLog(e))
};
if (writeHandshakeResponse) await writeHandshakeResponse(t).catch(() => {});
else h(t);
}
} finally {
D?.finish(A);
}
};
const parsePreauthConnectFrame = (e) => {
if (_() || rawDataByteLength(e) > 65536) return null;
let t;
try {
t = JSON.parse(rawDataToString(e));
} catch {
return null;
}
if (!validateRequestFrame(t) || t.method !== "connect" || !validateConnectParams(t.params)) return null;
return {
id: t.id,
params: t.params
};
};
const rejectConnectForClosedAdmission = async (t) => {
const n = isGatewayRestartDraining();
const r = n ? GATEWAY_RESTART_UNAVAILABLE_REASON : GATEWAY_SUSPEND_UNAVAILABLE_REASON;
const i = n ? "restart" : "suspension";
const o = getGatewaySuspendAdmissionPhase();
x({
type: "req",
method: "connect",
id: t
});
y("failed");
b(r, {
method: "connect",
phase: o
});
const s = createGatewayRpcDiagnostics("connect", e.getMethodRegistry, e.extraHandlers);
logWs("in", "req", {
connId: a,
id: t,
method: "connect"
});
try {
const e = await sendFrame({
type: "res",
id: t,
ok: false,
error: errorShape(ErrorCodes.UNAVAILABLE, `connect unavailable during gateway ${i}`, {
retryable: true,
retryAfterMs: GATEWAY_WORK_ADMISSION_RETRY_AFTER_MS,
details: {
method: "connect",
reason: r,
phase: o
}
})
});
s?.response("error", e);
logWs("out", "res", {
connId: a,
id: t,
method: "connect",
ok: false,
bytes: e
});
} catch {
s?.response("unavailable");
} finally {
s?.finish("rejected");
}
queueMicrotask(() => g(GATEWAY_WORK_ADMISSION_CLOSE_CODE, `gateway ${i} in progress`));
};
const handleIncomingMessage = async (t, n) => {
if (v()) {
await handleMessage(t, n);
return;
}
const r = tryBeginGatewayRootWorkAdmission("ws:connect");
if (!r) {
const n = parsePreauthConnectFrame(t);
if (n && isGatewayRestartDraining() && getGatewaySuspendAdmissionPhase() === "accepting" && e.isStartupPending?.() === true && isStartupNodeConnect(n.params)) {
const e = tryBeginGatewayRestartStartupRootWorkAdmission();
if (e) {
try {
await e.run(() => handleMessage(t));
} finally {
e.release();
}
return;
}
}
if (n && isGatewaySuspendControlAvailable() && n.params.role !== "node" && !claimsWorkerConnectionIdentity(n.params)) {
await handleMessage(t);
return;
}
if (n) {
await rejectConnectForClosedAdmission(n.id);
return;
}
await handleMessage(t);
return;
}
try {
await r.run(() => handleMessage(t));
} finally {
r.release();
}
};
const dispatchIncomingMessage = (t, n) => {
const r = e.connectionWork.isClosing ? "continuation" : void 0;
if (r && v()?.connect.role !== "node") {
n?.();
return;
}
e.connectionWork.track(() => runWithDiagnosticTraceContext(createDiagnosticTraceContext(), () => runWithMainThreadTask("gateway:ws:frame", () => handleIncomingMessage(t, r)))).catch((e) => {
S.error(`request dispatch failed conn=${a}: ${formatForLog(e)}`);
}).finally(n);
};
let R;
function flushQueuedHandshakeFrames() {
const e = R?.splice(0) ?? [];
R = void 0;
if (_()) return;
for (const t of e) onMessage(t);
}
const onMessage = (e) => {
try {
assertRemoteControlUiIngressCurrent(t);
} catch {
g(1008, "remote Control UI ingress closed");
return;
}
if (_()) return;
if (n) {
g(1008, "pairing approval pending; reconnect to request again");
return;
}
if (R) {
if (rejectOversizedPreauthFrame(e)) {
R.length = 0;
return;
}
if (R.length >= 16 - 1) {
y("failed");
b("handshake-message-overflow", { queuedFrames: R.length });
R.length = 0;
g(1008, "too many pending handshake frames");
return;
}
R.push(e);
return;
}
if (v()) {
dispatchIncomingMessage(e);
return;
}
R = [];
dispatchIncomingMessage(e, flushQueuedHandshakeFrames);
};
r.on("message", onMessage);
return onMessage;
}
//#endregion
export { attachGatewayWsMessageHandler };