openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
1,369 lines • 53.2 kB
JavaScript
import { l as normalizeOptionalString, o as normalizeLowercaseStringOrEmpty, s as normalizeNullableString } from "./string-coerce-CCIiB4H7.mjs";
import { i as asOptionalObjectRecord, r as asNullableRecord } from "./record-coerce-CVPuDqcc.mjs";
import { t as safeParseJson } from "./json-coercion-CaJLaav-.mjs";
import { v as normalizeUniqueTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs";
import { t as pruneMapToMaxSize } from "./map-size-BBr20tbc.mjs";
import { n as awaitWithinDeadline, t as ABSOLUTE_DEADLINE_EXPIRED } from "./absolute-deadline-kK4DcdPs.mjs";
import { i as GATEWAY_CLIENT_NAMES, r as GATEWAY_CLIENT_MODES } from "./client-info-Cm1BcrMm.mjs";
import { Ct as validateNodePairApproveParams, Dt as validateNodePendingAckParams, Et as validateNodePairRemoveParams, Mt as validateNodeRenameParams, St as validateNodeListParams, Tt as validateNodePairRejectParams, _t as validateNodeEventParams, bt as validateNodeInvokeProgressParams, wt as validateNodePairListParams, xt as validateNodeInvokeResultParams, yt as validateNodeInvokeParams } from "./src-BX8OAe1J.mjs";
import { d as hasGatewayAdminScope, r as PAIRING_SCOPE, t as ADMIN_SCOPE } from "./operator-scopes-CULmYfyY.mjs";
import { F as isPrivateNodeInvokeCommand, N as isAdminOnlyNodeInvokeCommand, P as isBrowserProxyNodeInvokeCommand } from "./node-commands-BfMJIlXP.mjs";
import { c as isForbiddenBrowserProxyMutation } from "./method-scopes-Dpyb0Ck-.mjs";
import "./session-event-handoff-CC7Ui3SA.mjs";
import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs";
import { m as missingScopeErrorShape, p as errorShape } from "./error-codes-BzF7aRQ0.mjs";
import { t as SessionMutationAuthorizationChangedError } from "./session-mutation-authorization-error-0K0ZVV7q.mjs";
import { o as getGatewayToolCallerIdentity } from "./gateway-caller-context-BNidAW8G.mjs";
import { r as captureSessionEventTargetForHost } from "./session-event-target-BPiQeS30.mjs";
import { a as resolveSessionStoreIdentity } from "./session-store-key-CEwU3noi.mjs";
import { i as listApprovedPairedDeviceRoles } from "./device-pairing-identity-BqPJxbIo.mjs";
import { a as listNodePairing, d as renamePairedNode, i as getPendingNodePairing, l as rejectNodePairing, t as approveNodePairing } from "./device-pairing-node-CoZTLZY1.mjs";
import { a as invalidateNodeWakeState, r as captureNodeWakeLifecycle, s as releaseNodeWakeLifecycle } from "./node-wake-state-i9g313wk.mjs";
import { t as getPairedDevice, u as removePairedDeviceRole } from "./device-pairing-D--Fzrek.mjs";
import { t as nodeInvokePolicy } from "./nodes-policy-BQpAVfw4.mjs";
import { r as respondUnavailableOnThrow, t as respondError } from "./response-C7fEiIN1.mjs";
import { n as defineValidatedGatewayHandler, t as assertValidParams } from "./validation-DwNk6A-B.mjs";
import { n as refreshConnectedNodeSurfaceCaches, t as nodeReadHandlers } from "./nodes.read-DYMngc6W.mjs";
import { n as validateSystemRunExecutionContext, t as SYSTEM_RUN_EXECUTION_CONTEXT_CAPABILITY } from "./system-run-execution-context-UpbI778p.mjs";
import { t as captureGatewayOperatorContinuation } from "./operator-run-recovery-DNcb8p2u.mjs";
import { n as resolveSystemRunCommandRequest } from "./system-run-command-Al2Xy1OR.mjs";
import { a as missingSystemRunApprovalBinding, f as toSystemRunApprovalMismatchError, i as matchSystemRunApprovalBinding, n as buildSystemRunApprovalBinding } from "./system-run-approval-binding-B3btPgad.mjs";
import { s as NodeWorkerProcessesChangedSchema } from "./worker-process-protocol-BD8BDPsH.mjs";
import { n as resolveEventSessionRoutingPolicy, t as resolveEventSessionKeyForPolicy } from "./event-session-routing-QCFK39bz.mjs";
import { a as isForegroundRestrictedPluginNodeCommand, l as resolveNodeCommandAllowlist, o as isNodeCommandAllowed, t as DEFAULT_DANGEROUS_NODE_COMMANDS } from "./node-command-policy-DkH-pkTr.mjs";
import { n as respondUnavailableOnNodeInvokeErrorWithProvenance, r as parseGatewayPayload } from "./nodes.helpers-CItZ-oW7.mjs";
import { r as resolveSystemRunApprovalRuntimeContext } from "./system-run-approval-context-DkkOMgNU.mjs";
import { _ as ApnsRegistrationPairingChangedError } from "./push-apns-store-dWsXv_d2.mjs";
import { a as captureGatewayClientUploadCommitGuard, n as GATEWAY_UPLOADS_DISABLED_MESSAGE, t as GATEWAY_UPLOADS_DISABLED_CODE } from "./upload-policy-Dp8z9OKP.mjs";
import { a as removePendingNodeAction, i as listPendingNodeActions, n as clearRemovedNodeRuntimeState, o as replacePendingNodeActionsForGeneration, r as enqueuePendingNodeAction, s as reconcileRevokedDeviceWorker, t as acknowledgePendingNodeActions } from "./node-runtime-state-DFpXFBB4.mjs";
import { n as broadcastRejectedNodePairing } from "./pairing-events-DVOVq0n9.mjs";
import { i as pairedDeviceHasNonOperatorRole, n as deniesCrossDeviceManagement, o as resolveDeviceManagementAuthz, s as resolveDeviceSessionAuthz, t as emitDeviceManagementSecurityEvent } from "./device-management-security-of_KK-C7.mjs";
import { n as captureNodePairingGeneration, r as isNodePairingGenerationCurrent } from "./device-pairing-node-state-D6j3mDNN.mjs";
import { a as isNodePairingWorkCurrent, i as waitForNodeReconnect, n as maybeSendNodeWakeNudge, o as resolveDispatchableNodeSession, r as maybeWakeNodeWithApns, s as respondPairingChanged, t as wakeNodeForReconnect } from "./nodes.wake-reconnect-BkR7WG4B.mjs";
import { n as invokeNodeWithReadinessRetry, t as applyPluginNodeInvokePolicy } from "./node-invoke-plugin-policy-DbONp8j_.mjs";
import { t as publishNodePermissionMissing } from "./nodes.permission-missing-D2B4c3Rq.mjs";
import { randomUUID } from "node:crypto";
//#region src/gateway/server-methods/nodes.event.ts
const nodeEventHandlers = { "node.event": async ({ params: e, respond: t, context: n, client: r }) => {
if (!assertValidParams(e, validateNodeEventParams, "node.event", t)) return;
const i = e;
const a = i.payloadJSON ?? (i.payload !== void 0 ? JSON.stringify(i.payload) : null);
await respondUnavailableOnThrow(t, async () => {
const e = r?.connect?.device?.id ?? r?.connect?.client?.id ?? "node";
const o = n.nodeRegistry.get(e);
const s = r?.connId;
const c = o?.pairingGeneration;
const sessionForGeneration = (t) => resolveDispatchableNodeSession(n.nodeRegistry.getForPairingGeneration(e, t));
const isEventConnectionCurrent = async () => {
if (!s || !c) return false;
const e = sessionForGeneration(c);
if (!e || e.connId !== s) return false;
if (!await n.nodeRegistry.isConnectionCurrentPairingState(s)) return false;
return sessionForGeneration(c)?.connId === s;
};
if (i.event === "worker.processes.changed") {
const r = NodeWorkerProcessesChangedSchema.safeParse(safeParseJson(a ?? ""));
let o = false;
if (r.success && await isEventConnectionCurrent()) {
const t = r.data;
const i = await n.workerSessionPlacementService?.prepareRuntimeRefresh?.(t.sessionId);
try {
if (i && await isEventConnectionCurrent()) {
i.assertCurrent();
const r = i.placement;
const a = n.workerEnvironmentService?.get(t.environmentId);
if (!i.move && !i.pendingResult && r?.state === "active" && r.executionMode === "worker-turn" && r.environmentId === t.environmentId && r.activeOwnerEpoch === t.ownerEpoch && r.generation === t.placementGeneration && a?.nodeDeviceId === e && a.ownerEpoch === t.ownerEpoch && a.destroyRequestedAtMs === null && [
"ready",
"idle",
"attached"
].includes(a.state)) {
const { sessionKey: e, agentId: t } = r;
n.broadcast("sessions.processes.changed", {
sessionKey: e,
agentId: t
}, {
sessionKeys: [e],
agentId: t,
dropIfSlow: true
});
o = true;
}
}
} finally {
i?.release();
}
}
t(true, {
ok: true,
event: i.event,
handled: o
}, void 0);
return;
}
const { handleNodeEvent: l } = await import("./server-node-events-CyhdrXE5.mjs");
const u = i.event === "push.apns.register" ? await captureNodePairingGeneration(e) : null;
const d = o !== void 0 && o.connId === r?.connId && o.permissions?.accessibility === true;
const bindSubscription = (t) => async (i, a, o) => {
if (i !== e || !o || o !== r?.connId || !await isEventConnectionCurrent()) return;
n[t](i, a, o);
};
const f = await l({
deps: n.deps,
broadcast: n.broadcast,
nodeSendToSession: n.nodeSendToSession,
nodeSubscribe: bindSubscription("nodeSubscribe"),
nodeUnsubscribe: bindSubscription("nodeUnsubscribe"),
broadcastVoiceWakeChanged: n.broadcastVoiceWakeChanged,
addChatRun: n.addChatRun,
removeChatRun: n.removeChatRun,
dedupe: n.dedupe,
agentRunSeq: n.agentRunSeq,
getHealthCache: n.getHealthCache,
refreshHealthSnapshot: n.refreshHealthSnapshot,
loadGatewayModelCatalog: n.loadGatewayModelCatalog,
loadGatewayModelCatalogSnapshot: n.loadGatewayModelCatalogSnapshot,
authorizeNodeSystemRunEvent: (e) => {
return n.nodeRegistry.authorizeSystemRunEventWithState({
nodeId: e.nodeId,
connId: e.connId,
runId: e.runId,
sessionKey: e.sessionKey,
terminal: e.event !== "exec.started"
}) ?? false;
},
updateNodePresenceActivity: (e) => {
const t = n.nodeRegistry.updatePresenceActivity(e);
return t?.lastActiveAtMs !== void 0 && t.presenceUpdatedAtMs !== void 0 ? {
lastActiveAtMs: t.lastActiveAtMs,
presenceUpdatedAtMs: t.presenceUpdatedAtMs
} : null;
},
clearNodePresenceActivity: (e) => n.nodeRegistry.clearPresenceActivity(e),
updateNodeDesktopAvailability: (e) => n.nodeRegistry.updateDesktopAvailability(e),
updateNodeHostStats: (e) => n.nodeRegistry.updateHostStats(e),
logGateway: { warn: n.logGateway.warn }
}, e, {
event: i.event,
payloadJSON: a
}, {
connId: r?.connId,
deviceId: r?.connect?.device?.id,
pairingGeneration: c ? {
nodeId: e,
key: c
} : void 0,
presenceAllowed: d,
isConnectionCurrent: isEventConnectionCurrent,
assertSessionEventCurrent: () => {
const e = c ? sessionForGeneration(c) : void 0;
if (!s || !e || e !== o || e.connId !== s || e.client.invalidated === true) throw new Error("Node event connection changed during preparation");
},
assertApnsRegistrationCurrent: () => {
const t = u ? n.nodeRegistry.getForPairingGeneration(e, u.key) : void 0;
if (!t || t !== o || t.connId !== s || t.client.invalidated === true) throw new ApnsRegistrationPairingChangedError();
},
resolveApnsRegistrationGeneration: async () => {
if (!u || !r?.connId) return null;
const e = sessionForGeneration(u.key);
if (!e || e.connId !== r.connId) return null;
if (!await isNodePairingGenerationCurrent(u)) return null;
return sessionForGeneration(u.key)?.connId === r.connId ? u.key : null;
}
});
if (f?.reason === "pairing_changed") {
respondPairingChanged(t);
return;
}
t(true, f ?? { ok: true }, void 0);
});
} };
//#endregion
//#region src/gateway/node-invoke-system-run-approval.ts
const BACKEND_BRIDGEABLE_NO_DEVICE_REQUEST_CLIENT_IDS = /* @__PURE__ */ new Set([
GATEWAY_CLIENT_NAMES.CONTROL_UI,
GATEWAY_CLIENT_NAMES.WEBCHAT_UI,
GATEWAY_CLIENT_NAMES.WEBCHAT,
GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT
]);
function systemRunApprovalGuardError(e, t, n) {
return {
ok: false,
message: t,
details: {
code: e,
...n ? { runId: n } : {}
}
};
}
function systemRunApprovalRequired(e) {
return systemRunApprovalGuardError("APPROVAL_REQUIRED", "approval required", e);
}
function normalizeApprovalDecision(e) {
const t = normalizeNullableString(e);
return t === "allow-once" || t === "allow-always" ? t : null;
}
function clientHasApprovals(e) {
const t = Array.isArray(e?.connect?.scopes) ? e?.connect?.scopes : [];
return t.includes("operator.admin") || t.includes("operator.approvals");
}
function isTrustedBackendApprovalClient(e) {
return clientHasApprovals(e) && e?.connect?.client?.id === GATEWAY_CLIENT_NAMES.GATEWAY_CLIENT && e.connect.client.mode === GATEWAY_CLIENT_MODES.BACKEND && e.isDeviceTokenAuth !== true;
}
function canBridgeNoDeviceApprovalFromBackend(e) {
const t = normalizeNullableString(e.snapshot.requestedByClientId);
const n = e.snapshot.request;
return e.snapshot.requestedByDeviceId == null && e.snapshot.requestedByDeviceTokenAuth !== true && !hasChatApprovalReplayBinding(n) && t !== null && BACKEND_BRIDGEABLE_NO_DEVICE_REQUEST_CLIENT_IDS.has(t) && isTrustedBackendApprovalClient(e.client);
}
function hasChatApprovalReplayBinding(e) {
return normalizeComparableString(e.turnSourceChannel, { lowercase: true }) !== null || normalizeComparableString(e.turnSourceTo) !== null || normalizeComparableString(e.turnSourceAccountId) !== null || normalizeComparableString(e.turnSourceThreadId) !== null;
}
function normalizeComparableString(e, t = {}) {
const n = typeof e === "number" && Number.isFinite(e) ? String(e) : normalizeNullableString(e);
if (!n) return null;
return t.lowercase ? n.toLowerCase() : n;
}
function matchesReplayBinding(e, t, n = {}) {
const r = normalizeComparableString(e, n);
return r ? r === normalizeComparableString(t, n) : n.optional === true;
}
function canBridgeNoDeviceChatApprovalFromBackend(e) {
if (e.snapshot.requestedByDeviceId != null || e.snapshot.requestedByDeviceTokenAuth === true || !isTrustedBackendApprovalClient(e.client)) return false;
const t = e.snapshot.request;
const n = t.systemRunPlan ?? null;
return matchesReplayBinding(t.turnSourceChannel, e.rawParams.turnSourceChannel, { lowercase: true }) && matchesReplayBinding(t.turnSourceTo, e.rawParams.turnSourceTo, { optional: true }) && matchesReplayBinding(n?.sessionKey ?? t.sessionKey, e.rawParams.sessionKey) && matchesReplayBinding(n?.agentId ?? t.agentId, e.rawParams.agentId, { optional: true }) && matchesReplayBinding(t.turnSourceAccountId, e.rawParams.turnSourceAccountId, { optional: true }) && matchesReplayBinding(t.turnSourceThreadId, e.rawParams.turnSourceThreadId, { optional: true });
}
function pickSystemRunParams(e) {
const t = {};
for (const n of [
"command",
"rawCommand",
"systemRunPlan",
"cwd",
"env",
"executionContext",
"timeoutMs",
"needsScreenRecording",
"agentId",
"sessionKey",
"runId",
"suppressNotifyOnExit"
]) if (n in e) t[n] = e[n];
return t;
}
function resolveForwardedRawCommand(e) {
const t = normalizeNullableString(e.commandPreview);
if (!t) return e.commandText;
const n = resolveSystemRunCommandRequest({
command: e.argv,
rawCommand: t
});
return n.ok && n.previewText === t ? t : e.commandText;
}
/**
* Gate `system.run` approval flags (`approved`, `approvalDecision`) behind a real
* `exec.approval.*` record. This prevents users with only `operator.write` from
* bypassing node-host approvals by injecting control fields into `node.invoke`.
*/
async function sanitizeSystemRunParamsForForwarding(e) {
const t = asNullableRecord(e.rawParams);
if (!t) return {
ok: true,
params: e.rawParams
};
const n = t.approved === true;
const r = normalizeApprovalDecision(t.approvalDecision);
if (t.approvalSource != null && t.approvalSource !== "ask-fallback") return systemRunApprovalGuardError("INVALID_APPROVAL_SOURCE", "approval source invalid");
const i = t.approvalSource === "ask-fallback" ? "ask-fallback" : null;
if (i !== null && (t.approved !== void 0 || t.approvalDecision !== void 0)) return systemRunApprovalGuardError("APPROVAL_SOURCE_MISMATCH", "approval source cannot be combined with explicit approval");
const a = n || r !== null || i !== null;
const o = pickSystemRunParams(t);
if (!a) {
const e = resolveSystemRunCommandRequest({
command: t.command,
rawCommand: t.rawCommand
});
if (!e.ok) return {
ok: false,
message: e.message,
details: e.details
};
return {
ok: true,
params: o
};
}
const s = normalizeNullableString(t.runId);
if (!s) return systemRunApprovalGuardError("MISSING_RUN_ID", "approval override requires params.runId");
const c = e.execApprovalManager;
if (!c) return systemRunApprovalGuardError("APPROVALS_UNAVAILABLE", "exec approvals unavailable");
const l = await c.getSnapshot(s);
if (!l) return systemRunApprovalGuardError("UNKNOWN_APPROVAL_ID", "unknown or expired approval id", s);
const u = l.resolutionSource ?? "operator";
if (u !== "operator" && u !== "auto-review") return systemRunApprovalGuardError("INVALID_APPROVAL_SOURCE", "approval record source invalid", s);
if (u === "auto-review" && l.decision !== "allow-once") {
if (l.consumedDecision === "allow-once") return systemRunApprovalRequired(s);
return systemRunApprovalGuardError("APPROVAL_SOURCE_MISMATCH", "auto-review source does not match approval decision", s);
}
const d = l.resolvedAtMs !== void 0 && l.decision === void 0 && l.consumedDecision === void 0 && l.askFallbackConsumed !== true;
const f = normalizeNullableString(e.nodeId);
if (!f) return systemRunApprovalGuardError("MISSING_NODE_ID", "node.invoke requires nodeId", s);
const p = normalizeNullableString(l.request.nodeId);
if (!p) return systemRunApprovalGuardError("APPROVAL_NODE_BINDING_MISSING", "approval id missing node binding", s);
if (p !== f) return systemRunApprovalGuardError("APPROVAL_NODE_MISMATCH", "approval id not valid for this node", s);
const m = l.requestedByDeviceId ?? null;
const h = e.client?.connect?.device?.id ?? null;
if (m) {
if (m !== h) return systemRunApprovalGuardError("APPROVAL_DEVICE_MISMATCH", "approval id not valid for this device", s);
} else if (l.requestedByConnId && l.requestedByConnId !== (e.client?.connId ?? null) && !canBridgeNoDeviceApprovalFromBackend({
snapshot: l,
client: e.client
}) && !canBridgeNoDeviceChatApprovalFromBackend({
snapshot: l,
rawParams: t,
client: e.client
})) return systemRunApprovalGuardError("APPROVAL_CLIENT_MISMATCH", "approval id not valid for this client", s);
const g = resolveSystemRunApprovalRuntimeContext({
plan: l.request.systemRunPlan ?? null,
command: t.command,
rawCommand: t.rawCommand,
cwd: t.cwd,
agentId: t.agentId,
sessionKey: t.sessionKey
});
if (!g.ok) return {
ok: false,
message: g.message,
details: g.details
};
if (g.plan) {
o.command = [...g.plan.argv];
o.systemRunPlan = g.plan;
o.rawCommand = resolveForwardedRawCommand(g.plan);
for (const e of [
"cwd",
"agentId",
"sessionKey"
]) if (g[e]) o[e] = g[e];
else delete o[e];
}
const _ = l.request;
if (_.host !== "node") return toSystemRunApprovalMismatchError({
runId: s,
match: {
ok: false,
code: "APPROVAL_REQUEST_MISMATCH",
message: "approval id does not match request"
}
});
const v = buildSystemRunApprovalBinding({
argv: g.argv,
cwd: g.cwd,
agentId: g.agentId,
sessionKey: g.sessionKey,
env: t.env
});
const y = _.systemRunBinding;
const b = y ? matchSystemRunApprovalBinding({
expected: y,
actual: v.binding,
actualEnvKeys: v.envKeys
}) : missingSystemRunApprovalBinding({ actualEnvKeys: v.envKeys });
if (!b.ok) return toSystemRunApprovalMismatchError({
runId: s,
match: b
});
const x = c.projectDecisionIfActive ? c.projectDecisionIfActive(s, l.decision ?? null) : l.decision ?? null;
if ((l.decision === "allow-once" || l.decision === "allow-always") && x !== l.decision) return systemRunApprovalRequired(s);
const S = l.decision;
if (S === "allow-once" || S === "allow-always") {
if (i !== null) return systemRunApprovalGuardError("APPROVAL_SOURCE_MISMATCH", "approval source does not match approval record", s);
if (S === "allow-once" && u === "auto-review" && !g.plan) return systemRunApprovalGuardError("APPROVAL_PLAN_REQUIRED", "auto-review approval requires an approved execution plan", s);
if (S === "allow-once" && (typeof c.consumeAllowOnce !== "function" || !await c.consumeAllowOnce(s))) return systemRunApprovalRequired(s);
if (S === "allow-once" && u === "auto-review") o.approvalSource = "auto-review";
else {
o.approved = true;
o.approvalDecision = S;
}
return {
ok: true,
params: o,
approvalAuthority: {
recordId: s,
decision: S
}
};
}
if (d && i === "ask-fallback" && !n && r === null && clientHasApprovals(e.client)) {
if (!g.plan) return systemRunApprovalGuardError("APPROVAL_PLAN_REQUIRED", "ask fallback requires an approved execution plan", s);
if (typeof c.consumeAskFallback !== "function" || !c.consumeAskFallback(s)) return systemRunApprovalRequired(s);
o.approvalSource = "ask-fallback";
return {
ok: true,
params: o,
approvalAuthority: {
recordId: s,
decision: "allow-once"
}
};
}
return systemRunApprovalRequired(s);
}
//#endregion
//#region src/gateway/node-invoke-sanitize.ts
async function sanitizeNodeInvokeParamsForForwarding(e) {
if (e.command === "system.run" || e.command === "system.run.prepare") {
const t = asNullableRecord(e.rawParams)?.executionContext;
if (t !== void 0 && (!e.caps?.includes("system.run.execution-context.v1") || !validateSystemRunExecutionContext(t))) return {
ok: false,
message: "executionContext invalid or unsupported by node; update the node and Gateway"
};
}
if (e.command === "system.run") return sanitizeSystemRunParamsForForwarding(e);
return {
ok: true,
params: e.rawParams
};
}
//#endregion
//#region src/gateway/server-methods/node-command-rejection-hint.ts
function buildNodeCommandRejectionHint(e, t, n, r) {
const i = n?.platform ?? "unknown";
if (e === "command not declared by node") return `node command not allowed: the node (platform: ${i}) does not support "${t}"`;
if (e === "command not allowlisted") {
if (t.startsWith("talk.")) return `node command not allowed: "${t}" requires a trusted Talk-capable node`;
if ((r.gateway?.nodes?.commands?.deny ?? []).some((e) => e.trim() === t)) return `node command not allowed: "${t}" is blocked by gateway.nodes.commands.deny`;
if (DEFAULT_DANGEROUS_NODE_COMMANDS.includes(t)) return `node command not allowed: "${t}" requires explicit gateway.nodes.commands.allow opt-in`;
return `node command not allowed: "${t}" is not in the allowlist for platform "${i}"`;
}
if (e === "node did not declare commands") {
if (n?.declaredCommands?.includes(t)) return "node command not allowed: the node's declared command surface is pending approval; run `openclaw nodes pending`, then `openclaw nodes approve <requestId>`";
return `node command not allowed: the node did not declare any supported commands`;
}
return `node command not allowed: ${e}`;
}
//#endregion
//#region src/gateway/server-methods/nodes.handlers.invoke-progress.ts
const MAX_PROGRESS_CHUNK_BYTES = 16384;
/** Accept one bounded stdout chunk for an active node invocation. */
const handleNodeInvokeProgress = defineValidatedGatewayHandler("node.invoke.progress", validateNodeInvokeProgressParams, async ({ params: e, respond: t, context: n, client: r }) => {
const i = r?.connect?.device?.id ?? r?.connect?.client?.id;
if (i && i !== e.nodeId) {
t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "nodeId mismatch"));
return;
}
if (Buffer.byteLength(e.chunk, "utf8") > MAX_PROGRESS_CHUNK_BYTES) {
t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "progress chunk too large"));
return;
}
t(true, {
ok: true,
ignored: !n.nodeRegistry.handleInvokeProgress({
...e,
connId: r?.connId
})
}, void 0);
});
//#endregion
//#region src/gateway/server-methods/nodes.handlers.invoke-result.ts
function normalizeNodeInvokeResultParams(e) {
if (!e || typeof e !== "object") return e;
const t = { ...e };
if (t.payloadJSON === null) delete t.payloadJSON;
else if (t.payloadJSON !== void 0 && typeof t.payloadJSON !== "string") {
if (t.payload === void 0) t.payload = t.payloadJSON;
delete t.payloadJSON;
}
if (t.error === null) delete t.error;
return t;
}
const handleNodeInvokeResult = async ({ params: e, respond: t, context: n, client: r }) => {
const i = normalizeNodeInvokeResultParams(e);
if (!assertValidParams(i, validateNodeInvokeResultParams, "node.invoke.result", t)) return;
const a = i;
const o = r?.connect?.device?.id ?? r?.connect?.client?.id;
if (o && o !== a.nodeId) {
t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "nodeId mismatch"));
return;
}
t(true, {
ok: true,
...!n.nodeRegistry.handleInvokeResult({
id: a.id,
nodeId: a.nodeId,
connId: r?.connId,
ok: a.ok,
payload: a.payload,
payloadJSON: a.payloadJSON ?? null,
error: a.error ?? null
}) ? { ignored: true } : {}
}, void 0);
};
//#endregion
//#region src/gateway/server-methods/nodes.invoke-authority.ts
function isForwardedNodeInvokeApprovalAuthorityActive(e) {
const t = e.authority;
return !t || e.manager?.projectDecisionIfActive(t.recordId, t.decision) === t.decision;
}
function resolveNodeInvokeRuntimeAuthorityError(e) {
const t = e.client?.internal?.agentRuntimeIdentity;
if (t && e.context.validateAgentRuntimeApprovalAuthority?.(t) !== true) return "agent runtime approval authority closed before node dispatch";
if (!isForwardedNodeInvokeApprovalAuthorityActive({
manager: e.context.execApprovalManager,
authority: e.approvalAuthority
})) return "approved runtime authority closed before node dispatch";
}
/** Capture the original caller before the node connection becomes the event producer. */
async function captureNodeSystemRunEventSource(e, t) {
const n = await captureGatewayOperatorContinuation(e);
if (!n && !getGatewayToolCallerIdentity()) return;
try {
const r = e.context.getRuntimeConfig();
const { canonicalKey: i, agentId: a } = resolveSessionStoreIdentity({
cfg: r,
sessionKey: t
});
const o = resolveEventSessionKeyForPolicy(i, resolveEventSessionRoutingPolicy({
cfg: r,
sessionKey: i
}));
return {
expectedTarget: await captureSessionEventTargetForHost(a, o, {
operatorAuthority: n?.authority,
assertCurrent: n?.authority.assertCurrent,
retainRequesterOwner: true
}),
release: n?.release ?? (() => {})
};
} catch (e) {
n?.release();
throw e;
}
}
//#endregion
//#region src/gateway/server-methods/nodes.invoke-foreground.ts
/** Queues only commands that iOS explicitly rejected as requiring the foreground. */
function shouldQueueAsPendingForegroundAction(e) {
const t = normalizeLowercaseStringOrEmpty(e.platform);
if (!t.startsWith("ios") && !t.startsWith("ipados")) return false;
if (!isForegroundRestrictedPluginNodeCommand(e.command) && !e.command.startsWith("camera.") && !e.command.startsWith("screen.") && !e.command.startsWith("talk.")) return false;
const n = asOptionalObjectRecord(e.error);
const r = normalizeOptionalString(n?.code)?.toUpperCase() ?? "";
const i = normalizeOptionalString(n?.message)?.toUpperCase() ?? "";
return r === "NODE_BACKGROUND_UNAVAILABLE" || i.includes("BACKGROUND_UNAVAILABLE");
}
//#endregion
//#region src/gateway/server-methods/nodes.invoke-talk-events.ts
const TALK_PTT_EVENT_TYPES = /* @__PURE__ */ new Map([
["talk.ptt.start", "capture.started"],
["talk.ptt.stop", "capture.stopped"],
["talk.ptt.cancel", "capture.cancelled"],
["talk.ptt.once", "capture.once"]
]);
const talkPttEventSeqBySessionId = /* @__PURE__ */ new Map();
function emitTalkPttNodeEvent(e) {
const t = TALK_PTT_EVENT_TYPES.get(e.command);
if (!t) return;
const n = typeof e.payload === "object" && e.payload !== null ? e.payload : {};
const r = normalizeOptionalString(n.captureId) ?? randomUUID();
const i = `node:${e.nodeId}:talk:${r}`;
const a = (talkPttEventSeqBySessionId.get(i) ?? 0) + 1;
talkPttEventSeqBySessionId.set(i, a);
pruneMapToMaxSize(talkPttEventSeqBySessionId, 2048);
const o = e.command !== "talk.ptt.start";
const s = {
id: `${i}:${a}`,
type: t,
sessionId: i,
captureId: r,
seq: a,
timestamp: (/* @__PURE__ */ new Date()).toISOString(),
mode: "stt-tts",
transport: "managed-room",
brain: "agent-consult",
final: o,
payload: {
nodeId: e.nodeId,
command: e.command,
status: normalizeOptionalString(n.status) ?? void 0,
transcript: normalizeOptionalString(n.transcript) ?? void 0
}
};
e.context.broadcast("talk.event", {
nodeId: e.nodeId,
command: e.command,
talkEvent: s
}, { dropIfSlow: true });
}
//#endregion
//#region src/gateway/server-methods/nodes.pending.ts
function resolveAllowedPendingNodeActions(e) {
const t = listPendingNodeActions({
nodeId: e.nodeId,
pairingGeneration: e.pairingGeneration,
ttlMs: nodeInvokePolicy.pendingActionTtlMs
});
if (t.length === 0) return t;
const n = e.client?.connect;
const r = n?.commands ?? [];
const i = resolveNodeCommandAllowlist(e.cfg, {
platform: n?.client?.platform,
deviceFamily: n?.client?.deviceFamily,
caps: n?.caps,
commands: r
});
const a = t.filter((e) => {
return isNodeCommandAllowed({
command: e.command,
declaredCommands: r,
allowlist: i
}).ok;
});
if (a.length !== t.length) replacePendingNodeActionsForGeneration({
nodeId: e.nodeId,
pairingGeneration: e.pairingGeneration,
replacement: a,
ttlMs: nodeInvokePolicy.pendingActionTtlMs
});
return a;
}
function toPendingParamsJSON(e) {
try {
return JSON.stringify(e);
} catch {
return;
}
}
async function withPendingNodeActions(e, t) {
const { respond: n, client: r, context: i } = e;
const a = r?.connect?.device?.id ?? r?.connect?.client?.id;
const o = normalizeOptionalString(a) ?? "";
if (!o) {
n(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "nodeId required"));
return;
}
await respondUnavailableOnThrow(n, async () => {
const e = await captureNodePairingGeneration(o);
if (!e) {
respondPairingChanged(n);
return;
}
const a = i.nodeRegistry.getForPairingGeneration(o, e.key);
if (!a || a.connId !== r?.connId) {
respondPairingChanged(n);
return;
}
const s = t(o, e.key);
if (!await isNodePairingGenerationCurrent(e)) {
respondPairingChanged(n);
return;
}
n(true, s(), void 0);
});
}
const nodePendingActionHandlers = {
"node.pending.pull": async (e) => {
const { params: t, respond: n, client: r, context: i } = e;
if (!assertValidParams(t, validateNodeListParams, "node.pending.pull", n)) return;
await withPendingNodeActions(e, (e, t) => {
const n = resolveAllowedPendingNodeActions({
nodeId: e,
pairingGeneration: t,
client: r,
cfg: i.getRuntimeConfig()
});
return () => ({
nodeId: e,
actions: n.map((e) => ({
id: e.id,
command: e.command,
paramsJSON: e.paramsJSON ?? null,
enqueuedAtMs: e.enqueuedAtMs
}))
});
});
},
"node.pending.ack": async (e) => {
const { params: t, respond: n } = e;
if (!assertValidParams(t, validateNodePendingAckParams, "node.pending.ack", n)) return;
await withPendingNodeActions(e, (e, n) => {
const r = normalizeUniqueTrimmedStringList(t.ids);
const i = acknowledgePendingNodeActions({
nodeId: e,
pairingGeneration: n,
ids: r,
ttlMs: nodeInvokePolicy.pendingActionTtlMs
});
return () => ({
nodeId: e,
ackedIds: r,
remainingCount: i.length
});
});
}
};
//#endregion
//#region src/gateway/server-methods/nodes.invoke.ts
const nodeInvokeHandlers = {
"node.invoke": async ({ params: e, respond: t, context: n, client: r, req: i, signal: a, hasCurrentClientAuthority: o }) => {
if (!assertValidParams(e, validateNodeInvokeParams, "node.invoke", t)) return;
const s = e;
const c = normalizeOptionalString(s.nodeId) ?? "";
const l = normalizeOptionalString(s.command) ?? "";
const u = normalizeOptionalString(s.sessionKey);
const d = r?.internal?.agentRuntimeIdentity ? {
channel: s.turnSourceChannel,
to: s.turnSourceTo,
accountId: s.turnSourceAccountId,
threadId: s.turnSourceThreadId
} : void 0;
const f = captureGatewayClientUploadCommitGuard({
method: "node.invoke",
requestParams: s,
client: r,
context: n
});
const isUploadAllowed = () => {
try {
f?.();
return true;
} catch (e) {
if (e instanceof SessionMutationAuthorizationChangedError) return false;
throw e;
}
};
const rejectDisabledUpload = () => {
if (isUploadAllowed()) return false;
respondError(t, ErrorCodes.FORBIDDEN, GATEWAY_UPLOADS_DISABLED_MESSAGE, { details: { code: GATEWAY_UPLOADS_DISABLED_CODE } });
return true;
};
if (rejectDisabledUpload()) return;
const p = r?.internal?.syntheticClient === true && r.internal.pluginRuntimeOwnerId ? r.internal.nodeInvokeStream : void 0;
if (!c || !l) {
respondError(t, ErrorCodes.INVALID_REQUEST, "nodeId and command required");
return;
}
if (isPrivateNodeInvokeCommand(l)) {
respondError(t, ErrorCodes.INVALID_REQUEST, "node.invoke does not allow private node controls", { details: { command: l } });
return;
}
if (l === "system.execApprovals.get" || l === "system.execApprovals.set") {
respondError(t, ErrorCodes.INVALID_REQUEST, "node.invoke does not allow system.execApprovals.*; use exec.approvals.node.*", { details: { command: l } });
return;
}
if (nodeInvokePolicy.rejectClaudeAgentRun(l, t)) return;
if (isBrowserProxyNodeInvokeCommand(l) && isForbiddenBrowserProxyMutation(s.params)) {
respondError(t, ErrorCodes.INVALID_REQUEST, `node.invoke cannot mutate persistent browser profiles via ${l}`, { details: { command: l } });
return;
}
if (isAdminOnlyNodeInvokeCommand(l) && !hasGatewayAdminScope(r)) {
t(false, void 0, missingScopeErrorShape({
missingScope: ADMIN_SCOPE,
requiredScopes: [ADMIN_SCOPE]
}));
return;
}
const m = typeof s.timeoutMs === "number" && s.timeoutMs > 0 ? performance.now() + s.timeoutMs : void 0;
const withinInvokeDeadline = (e) => awaitWithinDeadline(e, m, () => performance.now());
const respondWithInvocationResult = (e, r) => {
const i = e.payloadJSON ? parseGatewayPayload(e.payloadJSON) : e.payload;
emitTalkPttNodeEvent({
context: n,
nodeId: c,
command: l,
payload: i
});
t(true, {
ok: true,
nodeId: c,
command: l,
payload: r === "decoded" ? i : e.payload,
payloadJSON: e.payloadJSON ?? null
}, void 0);
};
let h = false;
const resolveRemainingInvokeTimeoutMs = () => m === void 0 ? s.timeoutMs : Math.max(0, m - performance.now());
const respondIfInvokeExpired = () => {
if (m === void 0 || resolveRemainingInvokeTimeoutMs() !== 0) return false;
respondUnavailableOnNodeInvokeErrorWithProvenance(t, {
ok: false,
error: {
code: "TIMEOUT",
message: "node invoke timed out"
}
}, { nodeCommandDispatched: h });
return true;
};
await respondUnavailableOnThrow(t, async () => {
const e = await withinInvokeDeadline(() => captureNodePairingGeneration(c));
if (e === ABSOLUTE_DEADLINE_EXPIRED) {
respondIfInvokeExpired();
return;
}
if (!e) {
respondPairingChanged(t);
return;
}
const f = captureNodeWakeLifecycle(c, e.key);
const g = a ? AbortSignal.any([f, a]) : f;
let _;
try {
const continuePairingWork = async () => {
const n = await withinInvokeDeadline(() => isNodePairingWorkCurrent({
nodeId: c,
generation: e,
lifecycle: f
}));
if (n === ABSOLUTE_DEADLINE_EXPIRED) {
respondIfInvokeExpired();
return false;
}
if (n) return true;
respondPairingChanged(t);
return false;
};
if (respondIfInvokeExpired()) return;
const a = n.getRuntimeConfig();
let v = resolveDispatchableNodeSession(n.nodeRegistry.getForPairingGeneration(c, e.key));
if (!v) {
const r = i.id;
const o = Date.now();
n.logGateway.info(`node wake start node=${c} req=${r} command=${l}`);
for (const t of [false, true]) {
const i = await wakeNodeForReconnect({
nodeId: c,
context: n,
cfg: a,
generation: e,
lifecycle: f,
requestId: r,
source: "invoke",
force: t,
deadlineAtMs: m
});
if (i === ABSOLUTE_DEADLINE_EXPIRED) {
respondIfInvokeExpired();
return;
}
if (!await continuePairingWork() || respondIfInvokeExpired()) return;
v = resolveDispatchableNodeSession(n.nodeRegistry.getForPairingGeneration(c, e.key));
if (v || !i.available) break;
}
if (!v) {
if (respondIfInvokeExpired()) return;
const i = Math.max(0, Date.now() - o);
const s = await withinInvokeDeadline(() => maybeSendNodeWakeNudge(c, {
cfg: a,
lifecycle: f,
generation: e
}));
if (s === ABSOLUTE_DEADLINE_EXPIRED) {
respondIfInvokeExpired();
return;
}
if (!await continuePairingWork()) return;
n.logGateway.info(`node wake nudge node=${c} req=${r} sent=${s.sent} throttled=${s.throttled} reason=${s.reason} durationMs=${s.durationMs} apnsStatus=${s.apnsStatus ?? -1} apnsReason=${s.apnsReason ?? "-"}`);
n.logGateway.warn(`node wake done node=${c} req=${r} connected=false reason=not_connected totalMs=${i}`);
respondError(t, ErrorCodes.UNAVAILABLE, "node not connected", { details: {
code: "NOT_CONNECTED",
nodeError: {
code: "NOT_CONNECTED",
message: "node not connected"
},
nodeCommandDispatched: false
} });
return;
}
const s = Math.max(0, Date.now() - o);
n.logGateway.info(`node wake done node=${c} req=${r} connected=true totalMs=${s}`);
}
const authorizeNodeCommand = (e, n) => {
const r = resolveNodeCommandAllowlist(n, {
...e,
approvedCommands: e.commands
});
const i = isNodeCommandAllowed({
command: l,
declaredCommands: e.commands,
allowlist: r
});
if (!i.ok) {
const r = buildNodeCommandRejectionHint(i.reason, l, e, n);
respondError(t, ErrorCodes.INVALID_REQUEST, r, { details: {
reason: i.reason,
command: l
} });
return false;
}
return true;
};
for (const e of [a, n.getRuntimeConfig()]) if (!authorizeNodeCommand(v, e)) return;
const y = await sanitizeNodeInvokeParamsForForwarding({
nodeId: c,
command: l,
caps: v.caps,
rawParams: s.params,
client: r,
execApprovalManager: n.execApprovalManager
});
if (!y.ok) {
respondError(t, ErrorCodes.INVALID_REQUEST, y.message, { details: y.details ?? null });
return;
}
if (respondIfInvokeExpired()) return;
if (y.approvalAuthority) {
const e = y.approvalAuthority;
_ = n.execApprovalManager?.retainForHandoff(e.recordId) ?? void 0;
if (!_) {
respondError(t, ErrorCodes.INVALID_REQUEST, "approved runtime authority closed before node dispatch", { details: { code: "APPROVAL_AUTHORITY_CLOSED" } });
return;
}
}
const runtimeAuthorityError = () => resolveNodeInvokeRuntimeAuthorityError({
context: n,
client: r,
approvalAuthority: y.approvalAuthority
});
const isForwardedApprovalAuthorityActive = () => isUploadAllowed() && isForwardedNodeInvokeApprovalAuthorityActive({
manager: n.execApprovalManager,
authority: y.approvalAuthority
});
if (rejectDisabledUpload()) return;
const b = await withinInvokeDeadline(() => applyPluginNodeInvokePolicy({
context: n,
client: r,
nodeSession: v,
command: l,
params: y.params,
...u ? { sessionKey: u } : {},
turnSource: {
channel: s.turnSourceChannel,
to: s.turnSourceTo,
accountId: s.turnSourceAccountId,
threadId: s.turnSourceThreadId
},
timeoutMs: s.timeoutMs,
deadlineAtMs: m,
signal: g,
resolveRemainingTimeoutMs: resolveRemainingInvokeTimeoutMs,
onNodeCommandDispatched: () => {
h = true;
},
idempotencyKey: s.idempotencyKey,
isInvocationCurrent: async () => await isNodePairingWorkCurrent({
nodeId: c,
generation: e,
lifecycle: f
}) && isUploadAllowed(),
isApprovalAuthorityActive: isForwardedApprovalAuthorityActive,
...p ? { nodeInvokeStream: p } : {}
}));
if (b === ABSOLUTE_DEADLINE_EXPIRED) {
respondIfInvokeExpired();
return;
}
if (!await continuePairingWork()) return;
if (b) {
if (!b.ok) {
const e = publishNodePermissionMissing({
error: asOptionalObjectRecord(b.details)?.nodeError,
nodeId: c,
nodeName: v.displayName,
command: l,
client: r,
context: n
});
const i = b.unavailable ? ErrorCodes.UNAVAILABLE : ErrorCodes.INVALID_REQUEST;
respondError(t, i, e?.message ?? b.message, { details: {
...b.details,
...b.code ? { code: b.code } : {},
...e ? { permissionMissing: e.permissionMissing } : {}
} });
return;
}
respondWithInvocationResult(b, "original");
return;
}
const x = resolveDispatchableNodeSession(n.nodeRegistry.getForPairingGeneration(c, e.key));
if (!x || x.connId !== v.connId) {
respondError(t, ErrorCodes.UNAVAILABLE, "node connection changed before dispatch", {
retryable: true,
details: { code: "ROUTE_CHANGED" }
});
return;
}
if (!authorizeNodeCommand(x, n.getRuntimeConfig())) return;
const S = resolveRemainingInvokeTimeoutMs();
if (m !== void 0 && S === 0) {
respondIfInvokeExpired();
return;
}
const C = runtimeAuthorityError();
if (C) {
respondError(t, ErrorCodes.INVALID_REQUEST, C, { details: { code: "APPROVAL_AUTHORITY_CLOSED" } });
return;
}
if (rejectDisabledUpload()) return;
const w = await invokeNodeWithReadinessRetry(n.nodeRegistry, {
nodeId: c,
expectedConnId: v.connId,
expectedPairingGeneration: e.key,
command: l,
params: y.params,
turnSource: d,
prepareSystemRunEventSource: (e) => captureNodeSystemRunEventSource({
client: r,
context: n,
hasCurrentClientAuthority: o
}, e),
timeoutMs: S,
deadlineAtMs: m,
signal: g,
idempotencyKey: s.idempotencyKey,
...u ? { sessionKey: u } : {},
...p && {
onProgress: p.onProgress,
idleTimeoutMs: p.idleTimeoutMs
},
isDispatchAuthorized: () => isUploadAllowed() && (p?.isRuntimeCurrent() ?? true) && runtimeAuthorityError() === void 0,
onDispatchReady: (e) => {
h = true;
p?.onDispatchReady(e);
}
});
if (!await continuePairingWork()) return;
if (!w.ok) {
if (shouldQueueAsPendingForegroundAction({
platform: v.platform,
command: l,
error: w.error
}) && !r?.internal?.agentRuntimeIdentity && !y.approvalAuthority) {
const r = toPendingParamsJSON(y.params);
const o = enqueuePendingNodeAction({
nodeId: c,
pairingGeneration: e.key,
command: l,
paramsJSON: r,
idempotencyKey: s.idempotencyKey,
ttlMs: nodeInvokePolicy.pendingActionTtlMs,
maxPerNode: nodeInvokePolicy.pendingActionMaxPerNode
});
const u = await withinInvokeDeadline(() => maybeWakeNodeWithApns(c, {
cfg: a,
lifecycle: f,
generation: e
}));
if (u === ABSOLUTE_DEADLINE_EXPIRED || !await continuePairingWork()) {
if (u === ABSOLUTE_DEADLINE_EXPIRED) respondIfInvokeExpired();
if (o.created) removePendingNodeAction({
nodeId: c,
pairingGeneration: e.key,
actionId: o.action.id,
ttlMs: nodeInvokePolicy.pendingActionTtlMs
});
return;
}
n.logGateway.info(`node pending queued node=${c} req=${i.id} command=${l} queuedId=${o.action.id} wakePath=${u.path} wakeAvailable=${u.available}`);
respondError(t, ErrorCodes.UNAVAILABLE, "node command queued until iOS returns to foreground", {
retryable: true,
details: {
code: "QUEUED_UNTIL_FOREGROUND",
queuedActionId: o.action.id,
nodeId: c,
command: l,
wake: {
path: u.path,
available: u.available,
throttled: u.throttled,
apnsStatus: u.apnsStatus,
apnsReason: u.apnsReason
},
nodeError: w.error ?? null
}
});
return;
}
respondUnavailableOnNodeInvokeErrorWithProvenance(t, w, {
nodeCommandDispatched: h,
...publishNodePermissionMissing({
error: w.error,
nodeId: c,
nodeName: v.displayName,
command: l,
client: r,
context: n
})
});
return;
}
respondWithInvocationResult(w, "decoded");
} finally {
_?.();
releaseNodeWakeLifecycle(c, f);
}
});
},
"node.invoke.progress": handleNodeInvokeProgress,
"node.invoke.result": handleNodeInvokeResult
};
//#endregion
//#region src/gateway/server-methods/nodes.pairing.ts
function emitNodePairingDeniedSecurityEvent(e) {
emitDeviceManagementSecurityEvent({
action: "device.pairing.denied",
outcome: "denied",
severity: "medium",
authz: e.authz,
targetDeviceId: e.nodeId,
policyId: "gateway.device-pairing",
decision: "deny",
controlId: e.controlId,
reason: "device-ownership-mismatch",
attributes: { role: "node" }
});
}
async function enforcePendingNodePairingOwnership(e) {
const t = e.mutation === "approve" ? "approval" : "rejection";
const n = e.mutation === "approve" ? "node.pair.approve" : "node.pair.reject";
const r = `node pairing ${t} denied`;
const i = await getPendingNodePairing(e.requestId);
const a = resolveDeviceSessionAuthz(e.client);
if (!i) {
if (a.callerDeviceId && !a.isAdminCaller) {
e.respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, r));
return false;
}
return true;
}
const o = resolveDeviceManagementAuthz(e.client, i.nodeId);
if (!deniesCrossDeviceManagement(o)) return true;
e.context.logGateway.warn(`${r} node=${i.nodeId} reason=device-ownership-mismatch`);
emitNodePairingDeniedSecurityEvent({
authz: o,
nodeId: i.nodeId,
controlId: n
});
e.respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, r));
return false;
}
function emitNodeRoleRemovalSecurityEvent(e) {
const t = e.reason !== void 0;
emitDeviceManagementSecurityEvent({
action: t ? "device.role.removal_denied" : "device.role.removed",
outcome: t ? "denied" : "success",
severity: "medium",
authz: e.authz,
targetDeviceId: e.deviceId,
policyId: "gateway.device-pairing",
decision: t ? "deny" : "allow",
controlId: "node.pair.remove",
...e.reason ? { reason: e.reason } : {},
attributes: {
role: "node",
...e.removedDevice !== void 0 ? { removed_device: e.removedDevice } : {}
}
});
}
const nodePairingHandlers = {
"node.pair.list": async ({ params: e, respond: t, client: n }) => {
if (!assertValidParams(e, validateNodePairListParams, "node.pair.list", t)) return;
await respondUnavailableOnThrow(t, async () => {
const e = await listNodePairing();
const r = resolveDeviceSessionAuthz(n);
t(true, r.callerDeviceId && !r.isAdminCaller ? {
pending: e.pending.filter((e) => e.nodeId.trim() === r.callerDeviceId),
paired: e.paired.filter((e) => e.nodeId.trim() === r.callerDeviceId)
} : e, void 0);
});
},
"node.pair.approve": async ({ params: e, respond: t, context: n, client: r }) => {
if (!assertValidParams(e, validateNodePairApproveParams, "node.pair.approve", t)) return;
const i = e.requestId.trim();
const a = r?.connect.scopes ?? [];
await respondUnavailableOnThrow(t, async () => {
if (!await enforcePendingNodePairingOwnership({
requestId: i,
mutation: "approve",
client: r,
context: n,
respond: t
})) return;
const e = { node: null };
const o = await approveNodePairing(i, {
callerScopes: a,
onApproved: (t) => {
const r = n.nodeRegistry.get(t.nodeId);
e.node = r ? n.nodeRegistry.updateSurface(t.nodeId, t.surface, {
expectedConnId: r.connId,
expectedPairingIdentity: t.pairingIdentity,
...t.previousPairingGeneration ? { expectedPairingGeneration: t.previousPairingGeneration } : {},
nextPairingGeneration: t.nextPairingGeneration
}) : null;
invalidateNodeWakeState(t.nodeId);
}
});
if (!o) {
t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "unknown requestId"));
return;
}
if ("status" in o && o.status === "forbidden") {
t(false, void 0, missingScopeErrorShape({
missingScope: o.missingScope,
requiredScopes: o.missingScope === "operator.pairing" ? [PAIRING_SCOPE] : [PAIRING_SCOPE, o.missingScope]
}));
return;
}
if (!("node" in o)) {
t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "unknown requestId"));
return;
}
const s = o.node;
const c = {
requestId: i,
nodeId: s.nodeId,
decision: "approved",
ts: Date.now()
};
const l = e.node;
if (l) {
refreshConnectedNodeSurfaceCaches({
context: n,
nodeSession: l
});
if (!await n.nodeRegistry.sendEventForPairingIdentity({
nodeId: l.nodeId,
connId: l.connId,
pairingIdentity: o.pairingIdentity,
event: "node.pair.resolved",
payload: c
})) n.logGateway.warn(`node approval refresh was not delivered for ${s.nodeId}; the current node must republish after reconnect`);
}
n.broadcast("node.pair.resolved", c, { dropIfSlow: true });
t(true, {
requestId: o.requestId,
node: s
}, void 0);
});
},
"node.pair.reject": async ({ params: e, respond: t, context: n, client: r }) => {
if (!assertValidParams(e, validateNodePairRejectParams, "node.pair.reject", t)) return;
const i = e.requestId.trim();
await respondUnavailableOnThrow(t, async () => {
if (!await enforcePendingNodePairingOwnership({
requestId: i,
mutation: "reject",
client: r,
context: n,
respond: t
})) return;
const e = await rejectNodePairing(i);
if (!e) {
t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "unknown requestId"));
return;
}
broadcastRejectedNodePairing(n.broadcast, {
requestId: i,
nodeId: e.nodeId
}, Date.now());
t(true, e, void 0);
});
},
"node.pair.remove": async ({ params: e, respond: t, context: n, client: r }) => {
if (!assertValidParams(e, validateNodePairRemoveParams, "node.pair.remove", t)) return;
const i = e.nodeId.trim();
await respondUnavailableOnThrow(t, async () => {
const e = i ? await getPairedDevice(i) : null;
if (!e || !listApprovedPairedDeviceRoles(e).includes("node")) {
t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "unknown nodeId"));
return;
}
const a = resolveDeviceManagementAuthz(r, i);
const o = deniesCrossDeviceManagement(a) ? "device-ownership-mismatch" : a.callerDeviceId && !a.isAdminCaller && pairedDeviceHasNonOperatorRole(e) ? "role-management-requires-admin" : void 0;
if (o) {
n.logGateway.warn(`node pairing removal denied node=${i} reason=${o}`);
emitNodeRoleRemovalSecurityEvent({
authz: a,
deviceId: i,
reason: o
});
t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "node pairing removal denied"));
return;
}
const s = await removePairedDeviceRole({ deviceId: i });
if (!s) {
t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "unknown nodeId"));
return;
}
n.logGateway.info(`node pairing removed device-backed node=${s.deviceId}`);
emitNodeRoleRemovalSecurityEvent({
authz: a,
deviceId: s.deviceId,
removedDevice: s.removedDevice
});
n.invalidateClientsForDevice?.(s.deviceId, {
role: "node",
reason: "device-pair-removed"
});
try {
clearRemovedNodeRuntimeState({
nodeId: s.deviceId,
context: n
});
await reconcileRevokedDeviceWorker(n, s.deviceId);
n.broadcast("node.pair.resolved", {
requestId: "",
nodeId: s.deviceId,
decision: "removed",
ts: Date.now()
}, { dropIfSlow: true });
t(true, { nodeId: s.deviceId }, void 0);
} finally {
queueMicrotask(() => {
n.disconnectClientsForDevice?.(s.deviceId, { role: "node" });
});
}
});
},
"node.rename": async ({ params: e, respond: t, context: n, client: r }) => {
if (!assertValidParams(e, validateNodeRenameParams, "node.rename", t)) return;
const { nodeId: i, displayName: a } = e;
await respondUnavailableOnThrow(t, async () => {
const e = resolveDeviceManagementAuthz(r, i);
if (deniesCrossDeviceManagement(e)) {
n.logGateway.warn(`node rename denied node=${e.normalizedTargetDeviceId} reason=device-ownership-mismatch`);
emitNodePairingDeniedSecurityEvent({
authz: e,
nodeId: e.normalizedTargetDeviceId,
controlId: "node.rename"
});
t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "node rename denied"));
return;
}
const o = a.trim();
if (!o) {
t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "displayName required"));
return;
}
const s = await renamePairedNode(i, o);
if (!s) {
t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "unknown nodeId"));
return;
}
t(true, {
nodeId: s.nodeId,
displayName: s.displayName
}, void 0);
});
}
};
//#endregion
//#region src/gateway/server-methods/nodes.ts
const nodeHandlers = {
...nodePairingHandlers,
...nodeReadHandlers,
...nodePendingActionHandlers,
...nodeInvokeHandlers,
...nodeEventHandlers
};
//#endregion
export { nodeHandlers };