openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
521 lines (520 loc) • 19 kB
JavaScript
import { $ as validateDevicePairListParams, $i as validateScopeUpgradeRequest, Q as validateDevicePairApproveParams, at as validateDeviceTokenRevokeParams, ea as validateScopeUpgradeWait, et as validateDevicePairRejectParams, nt as validateDevicePairRenameParams, ot as validateDeviceTokenRotateParams, tt as validateDevicePairRemoveParams } from "./src-BX8OAe1J.mjs";
import { f as isOperatorScope } from "./operator-scopes-CULmYfyY.mjs";
import { o as roleScopesAllow } from "./operator-scope-compat-CpFHu-FC.mjs";
import { t as ErrorCodes } from "./gateway-error-details-B69XiHdh.mjs";
import { p as errorShape } from "./error-codes-BzF7aRQ0.mjs";
import { m as resolveOperatorRolePolicy } from "./operator-role-policy-DhcqVpmG.mjs";
import { n as GATEWAY_EVENT_DEVICE_PAIR_CHANGED } from "./events-BxTs-VBE.mjs";
import { t as ConnectErrorDetailCodes } from "./connect-error-details-BdhXf496.mjs";
import { n as holdGatewayPolicyResponse } from "./ws-policy-close-Cspv0w92.mjs";
import { n as normalizeDeviceAuthScopes } from "./device-auth-Cu5vRDvP.mjs";
import { a as invalidateNodeWakeState } from "./node-wake-state-i9g313wk.mjs";
import { c as rejectDevicePairing, d as requestDevicePairing, f as updatePairedDeviceMetadata, i as listDevicePairing, l as removePairedDevice, n as getPendingDevicePairing, t as getPairedDevice } from "./device-pairing-D--Fzrek.mjs";
import { t as respondError } from "./response-C7fEiIN1.mjs";
import { n as defineValidatedGatewayHandler, t as assertValidParams } from "./validation-DwNk6A-B.mjs";
import { r as summarizeDeviceTokens } from "./device-pairing-token-utils-fd1VQ1i6.mjs";
import { n as revokeDeviceToken, r as rotateDeviceToken } from "./device-pairing-tokens-Bivg3I0v.mjs";
import { n as approveDevicePairing, r as formatDevicePairingForbiddenMessage } from "./device-pairing-approval-QMJvpfTq.mjs";
import { n as clearRemovedNodeRuntimeState, s as reconcileRevokedDeviceWorker } from "./node-runtime-state-DFpXFBB4.mjs";
import { t as broadcastRejectedDevicePairing } from "./pairing-events-DVOVq0n9.mjs";
import { a as requestsNonOperatorDeviceRole, i as pairedDeviceHasNonOperatorRole, n as deniesCrossDeviceManagement, o as resolveDeviceManagementAuthz, r as deniesDeviceTokenRoleManagement, s as resolveDeviceSessionAuthz, t as emitDeviceManagementSecurityEvent } from "./device-management-security-of_KK-C7.mjs";
//#region src/gateway/server-methods/device-scope-upgrade.ts
const DEVICE_REQUIRED_MESSAGE = "device scope upgrade requires a paired browser identity; reopen the Control UI over HTTPS or localhost, then retry";
function readUpgradeOwner(e) {
const t = e?.connect.device?.id.trim();
const n = e?.connect.device?.publicKey.trim();
return e?.connId && e.connect.role === "operator" && t && n ? {
deviceId: t,
publicKey: n
} : null;
}
function respondDeviceRequired(e) {
respondError(e, ErrorCodes.INVALID_REQUEST, DEVICE_REQUIRED_MESSAGE, { details: {
code: ConnectErrorDetailCodes.DEVICE_IDENTITY_REQUIRED,
recommendedNextStep: "reopen_control_ui_securely"
} });
}
/** Live operator scope-upgrade request and identity-bound wait handlers. */
const scopeUpgradeHandlers = {
"device.scopes.requestUpgrade": defineValidatedGatewayHandler("device.scopes.requestUpgrade", validateScopeUpgradeRequest, async ({ params: e, respond: t, context: n, client: r }) => {
const i = readUpgradeOwner(r);
if (!i) {
respondDeviceRequired(t);
return;
}
const a = await getPairedDevice(i.deviceId);
if (!a || a.publicKey !== i.publicKey) {
respondDeviceRequired(t);
return;
}
const o = normalizeDeviceAuthScopes(e.scopes);
if (!o.every(isOperatorScope)) {
respondError(t, ErrorCodes.INVALID_REQUEST, "requested scopes contain an unknown operator scope");
return;
}
const s = resolveOperatorRolePolicy(r, n.getRuntimeConfig());
if (s && !roleScopesAllow({
role: "operator",
requestedScopes: o,
allowedScopes: s.scopes
})) {
respondError(t, ErrorCodes.INVALID_REQUEST, "requested scopes exceed your assigned operator role; ask a gateway administrator to change your role");
return;
}
const c = r?.connect.scopes ?? [];
if (!roleScopesAllow({
role: "operator",
requestedScopes: c,
allowedScopes: o
})) {
respondError(t, ErrorCodes.INVALID_REQUEST, "requested scopes must include the connection's current scopes");
return;
}
const l = await requestDevicePairing({
deviceId: i.deviceId,
publicKey: i.publicKey,
displayName: r?.connect.client.displayName,
platform: r?.connect.client.platform,
deviceFamily: r?.connect.client.deviceFamily,
clientId: r?.connect.client.id,
clientMode: r?.connect.client.mode,
browserOrigin: a.browserOrigin,
role: "operator",
scopes: o,
remoteIp: r?.clientIp,
silent: false
});
const u = n.scopeUpgradeCoordinator;
if (!u?.register({
requestId: l.request.requestId,
expiresAtMs: l.expiresAtMs,
owner: i,
requestedScopes: o,
initialToken: a.tokens?.operator?.token,
initialApprovedAtMs: a.approvedAtMs
})) {
respondError(t, ErrorCodes.UNAVAILABLE, "device scope upgrade is temporarily unavailable", { retryable: true });
return;
}
const d = Date.now();
for (const e of l.superseded ?? []) {
u.notify(e.requestId, "rejected");
broadcastRejectedDevicePairing(n.broadcast, e, d);
}
if (l.created) n.broadcast("device.pair.requested", l.request, { dropIfSlow: true });
n.logGateway.warn(`security audit: live device scope upgrade requested device=${i.deviceId} scopesFrom=${c.join(",")} scopesTo=${o.join(",")}`);
t(true, { requestId: l.request.requestId }, void 0);
}),
"device.scopes.waitUpgrade": defineValidatedGatewayHandler("device.scopes.waitUpgrade", validateScopeUpgradeWait, async ({ params: e, respond: t, context: n, client: r }) => {
const i = readUpgradeOwner(r);
if (!i) {
respondDeviceRequired(t);
return;
}
const a = await n.scopeUpgradeCoordinator?.wait(e.requestId, i);
if (!a) {
respondError(t, ErrorCodes.INVALID_REQUEST, "scope upgrade expired or not found");
return;
}
if (a.status === "insufficient-scopes") {
respondError(t, ErrorCodes.INVALID_REQUEST, "Pairing was approved, but this browser's previously narrowed token still lacks the requested access. Run openclaw dashboard --json on the Gateway host for a fresh one-time owner pairing link. Open its browserUrl in this browser using the same Control UI address and Gateway URL to restore administrator access.");
return;
}
if (a.status === "approved") {
const e = resolveOperatorRolePolicy(r, n.getRuntimeConfig());
if (e && !roleScopesAllow({
role: "operator",
requestedScopes: a.scopes,
allowedScopes: e.scopes
})) {
respondError(t, ErrorCodes.INVALID_REQUEST, "approved scopes exceed your assigned operator role; ask a gateway administrator to change your role");
return;
}
}
t(true, a, void 0);
})
};
//#endregion
//#region src/gateway/server-methods/devices.ts
function redactPairedDevice(e, t) {
const { tokens: n, approvedScopes: r, ...i } = e;
return {
...i,
...t !== void 0 ? { connected: t } : {},
tokens: summarizeDeviceTokens(n)
};
}
function createDeviceTokenHandler(e) {
const t = `device.token.${e}`;
const n = e === "rotate" ? validateDeviceTokenRotateParams : validateDeviceTokenRevokeParams;
return async ({ params: r, client: i, context: a, respond: o }) => {
if (!assertValidParams(r, n, t, o)) return;
const { deviceId: s, role: c } = r;
const l = resolveDeviceManagementAuthz(i, s);
const deny = (t, n) => {
const r = e === "rotate" ? "rotation" : "revocation";
const i = `device token ${r} denied`;
const u = n ? ` scope=${n}` : "";
a.logGateway.warn(`${i} device=${s} role=${c} reason=${t}${u}`);
emitDeviceManagementSecurityEvent({
outcome: "denied",
severity: "medium",
policyId: "gateway.device-token",
decision: "deny",
action: `device.token.${r}_denied`,
authz: l,
targetDeviceId: s,
controlId: `device.token.${e}`,
reason: t,
attributes: { role: c.trim() }
});
o(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, i));
};
const u = deniesCrossDeviceManagement(l) ? "device-ownership-mismatch" : deniesDeviceTokenRoleManagement(l, c) ? "role-management-requires-admin" : void 0;
if (u) {
deny(u);
return;
}
const d = c.trim() === "operator" ? l.callerScopes : void 0;
const f = e === "rotate" ? await rotateDeviceToken({
deviceId: s,
role: c,
scopes: r.scopes,
callerScopes: d
}) : await revokeDeviceToken({
deviceId: s,
role: c,
callerScopes: d
});
if (!f.ok) {
deny(f.reason, f.scope);
return;
}
const p = f.entry;
const m = s.trim();
if (e === "rotate") {
a.logGateway.info(`device token rotated device=${s} role=${p.role} scopes=${p.scopes.join(",")}`);
emitDeviceTokenLifecycleSecurityEvent({
action: "device.token.rotated",
severity: "medium",
authz: l,
targetDeviceId: s,
controlId: "device.token.rotate",
role: p.role,
scopeCount: p.scopes.length
});
if (p.role === "node") invalidateNodeWakeState(m);
try {
holdGatewayPolicyResponse(o);
} finally {
a.invalidateClientsForDevice?.(m, {
role: p.role,
reason: "device-token-rotated"
});
queueMicrotask(() => {
a.disconnectClientsForDevice?.(m, { role: p.role });
});
}
const e = Boolean(l.callerDeviceId && l.callerDeviceId === l.normalizedTargetDeviceId);
o(true, {
deviceId: s,
role: p.role,
...e ? { token: p.token } : {},
scopes: p.scopes,
rotatedAtMs: p.rotatedAtMs ?? p.createdAtMs,
tokenDelivery: e ? "in-band" : "withheld-cross-device"
}, void 0);
return;
}
a.logGateway.info(`device token revoked device=${m} role=${p.role}`);
emitDeviceTokenLifecycleSecurityEvent({
action: "device.token.revoked",
severity: "high",
authz: l,
targetDeviceId: m,
controlId: "device.token.revoke",
role: p.role
});
try {
try {
holdGatewayPolicyResponse(o);
} finally {
a.invalidateClientsForDevice?.(m, {
role: p.role,
reason: "device-token-revoked"
});
if (p.role === "node") {
clearRemovedNodeRuntimeState({
nodeId: m,
context: a
});
await reconcileRevokedDeviceWorker(a, m);
}
}
} finally {
queueMicrotask(() => {
a.disconnectClientsForDevice?.(m, { role: p.role });
});
}
o(true, {
deviceId: m,
role: p.role,
revokedAtMs: p.revokedAtMs ?? Date.now()
}, void 0);
};
}
async function runDevicePairingMutation(e) {
const t = resolveDeviceManagementAuthz(e.client, e.deviceId);
let n;
if (deniesCrossDeviceManagement(t)) n = "device-ownership-mismatch";
else if (t.callerDeviceId && !t.isAdminCaller) {
const e = await getPairedDevice(t.normalizedTargetDeviceId);
if (e && pairedDeviceHasNonOperatorRole(e)) n = "role-management-requires-admin";
}
if (!n) return e.run(t);
const r = `device pairing ${e.operation === "remove" ? "removal" : "rename"} denied`;
e.context.logGateway.warn(`${r} device=${e.deviceId} reason=${n}`);
emitDevicePairingDeniedSecurityEvent({
authz: t,
targetDeviceId: e.deviceId,
controlId: `device.pair.${e.operation}`,
reason: n
});
e.respond(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, r));
}
function emitDevicePairingDeniedSecurityEvent(e) {
emitDeviceManagementSecurityEvent({
action: "device.pairing.denied",
outcome: "denied",
severity: e.severity ?? "medium",
authz: e.authz,
targetDeviceId: e.targetDeviceId,
policyId: "gateway.device-pairing",
decision: "deny",
controlId: e.controlId,
reason: e.reason
});
}
function authorizePairingDecision(e, t, n, r, { respond: i, context: a }) {
const o = n ? r.callerDeviceId && n.deviceId.trim() !== r.callerDeviceId ? "device-ownership-mismatch" : e === "approve" && requestsNonOperatorDeviceRole(n) ? "role-management-requires-admin" : void 0 : void 0;
if (n && !o) return true;
const s = `device pairing ${e === "approve" ? "approval" : "rejection"} denied`;
if (n && o) {
a.logGateway.warn(`${s} request=${t} reason=${o}`);
emitDevicePairingDeniedSecurityEvent({
authz: r,
targetDeviceId: n.deviceId,
controlId: `device.pair.${e}`,
reason: o
});
}
i(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, s));
return false;
}
function emitDevicePairingLifecycleSecurityEvent(e) {
emitDeviceManagementSecurityEvent({
...e,
outcome: "success",
policyId: "gateway.device-pairing",
decision: "allow"
});
}
function emitDeviceTokenLifecycleSecurityEvent(e) {
emitDeviceManagementSecurityEvent({
...e,
outcome: "success",
policyId: "gateway.device-token",
decision: "allow",
attributes: {
role: e.role,
...e.scopeCount !== void 0 ? { scope_count: e.scopeCount } : {}
}
});
}
const deviceHandlers = {
...scopeUpgradeHandlers,
"device.pair.list": async ({ params: e, respond: t, context: n, client: r }) => {
if (!assertValidParams(e, validateDevicePairListParams, "device.pair.list", t)) return;
const i = await listDevicePairing();
const a = resolveDeviceSessionAuthz(r);
let o = i;
if (a.callerDeviceId && !a.isAdminCaller) o = {
pending: i.pending.filter((e) => e.deviceId.trim() === a.callerDeviceId),
paired: i.paired.filter((e) => e.deviceId.trim() === a.callerDeviceId)
};
t(true, {
pending: o.pending,
paired: o.paired.map((e) => redactPairedDevice(e, n.hasConnectedClientsForDevice?.(e.deviceId.trim()) ?? false))
}, void 0);
},
"device.pair.approve": async ({ params: e, respond: t, context: n, client: r }) => {
if (!assertValidParams(e, validateDevicePairApproveParams, "device.pair.approve", t)) return;
const i = e.requestId.trim();
const a = resolveDeviceSessionAuthz(r);
if (!a.isAdminCaller) {
if (!authorizePairingDecision("approve", i, await getPendingDevicePairing(i), a, {
respond: t,
context: n
})) return;
}
const o = await approveDevicePairing(i, { callerScopes: a.callerScopes });
if (!o) {
t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "unknown requestId"));
return;
}
if (o.status === "forbidden") {
emitDevicePairingDeniedSecurityEvent({
authz: a,
controlId: "device.pair.approve",
reason: o.reason
});
t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, formatDevicePairingForbiddenMessage(o)));
return;
}
const s = o.device.deviceId.trim();
n.scopeUpgradeCoordinator?.notify(i, "approved");
if (o.nodePairingGenerationChanged) {
invalidateNodeWakeState(s);
n.invalidateClientsForDevice?.(s, {
role: "node",
reason: "device-pairing-reapproved"
});
}
n.logGateway.info(`device pairing approved device=${o.device.deviceId} role=${o.device.role ?? "unknown"}`);
emitDevicePairingLifecycleSecurityEvent({
action: "device.pairing.approved",
severity: "low",
authz: a,
targetDeviceId: o.device.deviceId,
controlId: "device.pair.approve",
attributes: {
role_count: o.device.roles?.length ?? (o.device.role ? 1 : 0),
scope_count: o.device.approvedScopes?.length ?? o.device.scopes?.length ?? 0
}
});
n.broadcast("device.pair.resolved", {
requestId: i,
deviceId: o.device.deviceId,
decision: "approved",
ts: Date.now()
}, { dropIfSlow: true });
t(true, {
requestId: i,
device: redactPairedDevice(o.device)
}, void 0);
if (o.nodePairingGenerationChanged) queueMicrotask(() => {
n.disconnectClientsForDevice?.(s, { role: "node" });
});
},
"device.pair.reject": async ({ params: e, respond: t, context: n, client: r }) => {
if (!assertValidParams(e, validateDevicePairRejectParams, "device.pair.reject", t)) return;
const i = e.requestId.trim();
const a = resolveDeviceSessionAuthz(r);
if (a.callerDeviceId && !a.isAdminCaller) {
if (!authorizePairingDecision("reject", i, await getPendingDevicePairing(i), a, {
respond: t,
context: n
})) return;
}
const o = await rejectDevicePairing(i);
if (!o) {
t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "unknown requestId"));
return;
}
n.scopeUpgradeCoordinator?.notify(i, "rejected");
emitDevicePairingLifecycleSecurityEvent({
action: "device.pairing.rejected",
authz: a,
targetDeviceId: o.deviceId,
controlId: "device.pair.reject",
severity: "low"
});
broadcastRejectedDevicePairing(n.broadcast, {
requestId: i,
deviceId: o.deviceId
}, Date.now());
t(true, o, void 0);
},
"device.pair.remove": async ({ params: e, respond: t, context: n, client: r }) => {
if (!assertValidParams(e, validateDevicePairRemoveParams, "device.pair.remove", t)) return;
const { deviceId: i } = e;
await runDevicePairingMutation({
operation: "remove",
client: r,
context: n,
respond: t,
deviceId: i,
run: async (e) => {
const r = await removePairedDevice(i);
if (!r) {
t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "unknown deviceId"));
return;
}
clearRemovedNodeRuntimeState({
nodeId: r.deviceId,
context: n
});
try {
try {
holdGatewayPolicyResponse(t);
} finally {
n.invalidateClientsForDevice?.(r.deviceId, { reason: "device-pair-removed" });
await reconcileRevokedDeviceWorker(n, r.deviceId);
}
n.logGateway.info(`device pairing removed device=${r.deviceId}`);
emitDevicePairingLifecycleSecurityEvent({
action: "device.pairing.removed",
severity: "medium",
authz: e,
targetDeviceId: r.deviceId,
controlId: "device.pair.remove"
});
t(true, r, void 0);
} finally {
queueMicrotask(() => {
n.disconnectClientsForDevice?.(r.deviceId);
});
}
}
});
},
"device.pair.rename": async ({ params: e, respond: t, context: n, client: r }) => {
if (!assertValidParams(e, validateDevicePairRenameParams, "device.pair.rename", t)) return;
const { deviceId: i, label: a } = e;
const o = a.trim();
if (!o) {
t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "label required"));
return;
}
await runDevicePairingMutation({
operation: "rename",
client: r,
context: n,
respond: t,
deviceId: i,
run: async (e) => {
if (!await updatePairedDeviceMetadata(i, { operatorLabel: o })) {
t(false, void 0, errorShape(ErrorCodes.INVALID_REQUEST, "unknown deviceId"));
return;
}
n.logGateway.info(`device pairing renamed device=${i} label=${o}`);
emitDevicePairingLifecycleSecurityEvent({
action: "device.pairing.renamed",
severity: "low",
authz: e,
targetDeviceId: i,
controlId: "device.pair.rename"
});
n.broadcast(GATEWAY_EVENT_DEVICE_PAIR_CHANGED, {}, { dropIfSlow: true });
t(true, {
deviceId: i,
label: o
}, void 0);
}
});
},
"device.token.rotate": createDeviceTokenHandler("rotate"),
"device.token.revoke": createDeviceTokenHandler("revoke")
};
//#endregion
export { deviceHandlers };