openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
320 lines (319 loc) • 18.1 kB
JavaScript
import { l as normalizeOptionalString } from "./string-coerce-CCIiB4H7.mjs";
import { f as asPositiveInteger } from "./number-coercion-D6u-4YD8.mjs";
import { l as isRecord } from "./record-coerce-CVPuDqcc.mjs";
import { c as normalizeOptionalTrimmedStringList } from "./string-normalization-DLmfYZXI.mjs";
//#region packages/gateway-protocol/src/connect-error-details.ts
/**
* Shared gateway connect-error detail helpers.
*
* These details cross client/server boundaries, so readers normalize untrusted
* payloads before using them in reconnect decisions or user-facing messages.
*/
/** Structured connect-error codes carried in gateway error `details.code`. */
const ConnectErrorDetailCodes = {
AUTH_REQUIRED: "AUTH_REQUIRED",
AUTH_UNAUTHORIZED: "AUTH_UNAUTHORIZED",
AUTH_TOKEN_MISSING: "AUTH_TOKEN_MISSING",
AUTH_TOKEN_MISMATCH: "AUTH_TOKEN_MISMATCH",
AUTH_TOKEN_NOT_CONFIGURED: "AUTH_TOKEN_NOT_CONFIGURED",
AUTH_PASSWORD_MISSING: "AUTH_PASSWORD_MISSING",
AUTH_PASSWORD_MISMATCH: "AUTH_PASSWORD_MISMATCH",
AUTH_PASSWORD_NOT_CONFIGURED: "AUTH_PASSWORD_NOT_CONFIGURED",
AUTH_BOOTSTRAP_TOKEN_INVALID: "AUTH_BOOTSTRAP_TOKEN_INVALID",
AUTH_DEVICE_TOKEN_MISMATCH: "AUTH_DEVICE_TOKEN_MISMATCH",
AUTH_SCOPE_MISMATCH: "AUTH_SCOPE_MISMATCH",
AUTH_RATE_LIMITED: "AUTH_RATE_LIMITED",
AUTH_TAILSCALE_IDENTITY_MISSING: "AUTH_TAILSCALE_IDENTITY_MISSING",
AUTH_TAILSCALE_PROXY_MISSING: "AUTH_TAILSCALE_PROXY_MISSING",
AUTH_TAILSCALE_WHOIS_FAILED: "AUTH_TAILSCALE_WHOIS_FAILED",
AUTH_TAILSCALE_IDENTITY_MISMATCH: "AUTH_TAILSCALE_IDENTITY_MISMATCH",
AUTH_IDENTITY_HEADER_REQUIRED: "AUTH_IDENTITY_HEADER_REQUIRED",
AUTH_VERIFIED_USER_REQUIRED: "AUTH_VERIFIED_USER_REQUIRED",
AUTHENTICATED_PROFILE_UNAVAILABLE: "AUTHENTICATED_PROFILE_UNAVAILABLE",
OPERATOR_ACCESS_DENIED: "OPERATOR_ACCESS_DENIED",
CONTROL_UI_BUILD_MISMATCH: "CONTROL_UI_BUILD_MISMATCH",
CONTROL_UI_ORIGIN_NOT_ALLOWED: "CONTROL_UI_ORIGIN_NOT_ALLOWED",
PROTOCOL_MISMATCH: "PROTOCOL_MISMATCH",
CONTROL_UI_DEVICE_IDENTITY_REQUIRED: "CONTROL_UI_DEVICE_IDENTITY_REQUIRED",
DEVICE_IDENTITY_REQUIRED: "DEVICE_IDENTITY_REQUIRED",
DEVICE_AUTH_INVALID: "DEVICE_AUTH_INVALID",
DEVICE_AUTH_DEVICE_ID_MISMATCH: "DEVICE_AUTH_DEVICE_ID_MISMATCH",
DEVICE_AUTH_SIGNATURE_EXPIRED: "DEVICE_AUTH_SIGNATURE_EXPIRED",
DEVICE_AUTH_NONCE_REQUIRED: "DEVICE_AUTH_NONCE_REQUIRED",
DEVICE_AUTH_NONCE_MISMATCH: "DEVICE_AUTH_NONCE_MISMATCH",
DEVICE_AUTH_SIGNATURE_INVALID: "DEVICE_AUTH_SIGNATURE_INVALID",
DEVICE_AUTH_PUBLIC_KEY_INVALID: "DEVICE_AUTH_PUBLIC_KEY_INVALID",
PAIRING_REQUIRED: "PAIRING_REQUIRED",
PAIRING_REJECTED: "PAIRING_REJECTED",
PAIRING_EXPIRED: "PAIRING_EXPIRED",
CLIENT_VERSION_MISMATCH: "CLIENT_VERSION_MISMATCH"
};
/** Suggested client-side recovery action for structured connect errors. */
const CONNECT_RECOVERY_NEXT_STEP_VALUES = [
"retry_with_device_token",
"update_auth_configuration",
"update_auth_credentials",
"wait_then_retry",
"review_auth_configuration"
];
const PAIRING_CONNECT_REQUEST_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const PAIRING_CONNECT_REASON_METADATA = {
"not-paired": {
message: "device pairing required",
requirement: "device is not approved yet",
remediationHint: "Approve this device from the pending pairing requests.",
recoveryTitle: "Gateway pairing approval required."
},
"role-upgrade": {
message: "role upgrade pending approval",
requirement: "device is asking for a higher role than currently approved",
remediationHint: "Review the requested role upgrade, then approve the pending request.",
recoveryTitle: "Gateway role upgrade approval required."
},
"scope-upgrade": {
message: "scope upgrade pending approval",
requirement: "device is asking for more scopes than currently approved",
remediationHint: "Review the requested scopes, then approve the pending upgrade.",
recoveryTitle: "Gateway scope upgrade approval required."
},
"metadata-upgrade": {
message: "device metadata change pending approval",
requirement: "device identity changed and must be re-approved",
remediationHint: "Review the refreshed device details, then approve the pending request.",
recoveryTitle: "Gateway device refresh approval required."
}
};
const AUTH_CONNECT_ERROR_CODES = /* @__PURE__ */ new Map([
["token_missing", ConnectErrorDetailCodes.AUTH_TOKEN_MISSING],
["token_mismatch", ConnectErrorDetailCodes.AUTH_TOKEN_MISMATCH],
["token_missing_config", ConnectErrorDetailCodes.AUTH_TOKEN_NOT_CONFIGURED],
["password_missing", ConnectErrorDetailCodes.AUTH_PASSWORD_MISSING],
["password_mismatch", ConnectErrorDetailCodes.AUTH_PASSWORD_MISMATCH],
["password_missing_config", ConnectErrorDetailCodes.AUTH_PASSWORD_NOT_CONFIGURED],
["bootstrap_token_invalid", ConnectErrorDetailCodes.AUTH_BOOTSTRAP_TOKEN_INVALID],
["tailscale_user_missing", ConnectErrorDetailCodes.AUTH_TAILSCALE_IDENTITY_MISSING],
["tailscale_proxy_missing", ConnectErrorDetailCodes.AUTH_TAILSCALE_PROXY_MISSING],
["tailscale_whois_failed", ConnectErrorDetailCodes.AUTH_TAILSCALE_WHOIS_FAILED],
["tailscale_user_mismatch", ConnectErrorDetailCodes.AUTH_TAILSCALE_IDENTITY_MISMATCH],
["rate_limited", ConnectErrorDetailCodes.AUTH_RATE_LIMITED],
["device_token_mismatch", ConnectErrorDetailCodes.AUTH_DEVICE_TOKEN_MISMATCH],
["scope_mismatch", ConnectErrorDetailCodes.AUTH_SCOPE_MISMATCH],
[void 0, ConnectErrorDetailCodes.AUTH_REQUIRED]
]);
const DEVICE_AUTH_CONNECT_ERROR_CODES = /* @__PURE__ */ new Map([
["device-id-mismatch", ConnectErrorDetailCodes.DEVICE_AUTH_DEVICE_ID_MISMATCH],
["device-signature-stale", ConnectErrorDetailCodes.DEVICE_AUTH_SIGNATURE_EXPIRED],
["device-nonce-missing", ConnectErrorDetailCodes.DEVICE_AUTH_NONCE_REQUIRED],
["device-nonce-mismatch", ConnectErrorDetailCodes.DEVICE_AUTH_NONCE_MISMATCH],
["device-signature", ConnectErrorDetailCodes.DEVICE_AUTH_SIGNATURE_INVALID],
["device-public-key", ConnectErrorDetailCodes.DEVICE_AUTH_PUBLIC_KEY_INVALID]
]);
/** Maps internal auth failure reasons to public connect-error detail codes. */
function resolveAuthConnectErrorDetailCode(e) {
if (e?.startsWith("trusted_proxy_missing_header_")) return ConnectErrorDetailCodes.AUTH_IDENTITY_HEADER_REQUIRED;
return AUTH_CONNECT_ERROR_CODES.get(e) ?? ConnectErrorDetailCodes.AUTH_UNAUTHORIZED;
}
/** Maps device-auth verifier reasons to public connect-error detail codes. */
function resolveDeviceAuthConnectErrorDetailCode(e) {
return DEVICE_AUTH_CONNECT_ERROR_CODES.get(e) ?? ConnectErrorDetailCodes.DEVICE_AUTH_INVALID;
}
/** Reads a non-empty detail code from an untrusted error details payload. */
function readConnectErrorDetailCode(e) {
if (!isRecord(e)) return null;
return normalizeOptionalString(e.code) ?? null;
}
/** Extracts normalized retry advice from untrusted connect-error details. */
function readConnectErrorRecoveryAdvice(e) {
if (!isRecord(e)) return {};
return {
canRetryWithDeviceToken: typeof e.canRetryWithDeviceToken === "boolean" ? e.canRetryWithDeviceToken : void 0,
recommendedNextStep: normalizeConnectRecoveryNextStep(e.recommendedNextStep)
};
}
function normalizeConnectRecoveryNextStep(e) {
const t = normalizeOptionalString(e) ?? "";
return CONNECT_RECOVERY_NEXT_STEP_VALUES.find((e) => e === t);
}
function normalizePairingConnectReason(e) {
const t = normalizeOptionalString(e) ?? "";
return Object.hasOwn(PAIRING_CONNECT_REASON_METADATA, t) ? t : void 0;
}
/** Normalizes pairing request ids before echoing them in close reasons or UI text. */
function normalizePairingConnectRequestId(e) {
const t = normalizeOptionalString(e);
return t && PAIRING_CONNECT_REQUEST_ID_PATTERN.test(t) ? t : void 0;
}
function createPairingConnectErrorDetails(e) {
return {
code: ConnectErrorDetailCodes.PAIRING_REQUIRED,
...e.reason ? { reason: e.reason } : {},
...e.requestId ? { requestId: e.requestId } : {},
...e.remediationHint ? { remediationHint: e.remediationHint } : {},
...e.recommendedNextStep ? { recommendedNextStep: e.recommendedNextStep } : {},
...e.retryable !== void 0 ? { retryable: e.retryable } : {},
...e.pauseReconnect !== void 0 ? { pauseReconnect: e.pauseReconnect } : {},
...e.waitForResolution !== void 0 ? { waitForResolution: e.waitForResolution } : {},
...e.deviceId ? { deviceId: e.deviceId } : {},
...e.requestedRole ? { requestedRole: e.requestedRole } : {},
...e.requestedScopes ? { requestedScopes: e.requestedScopes } : {},
...e.approvedRoles ? { approvedRoles: e.approvedRoles } : {},
...e.approvedScopes ? { approvedScopes: e.approvedScopes } : {}
};
}
/** Human-readable requirement summary for a pairing-required reason. */
function describePairingConnectRequirement(e) {
return e ? PAIRING_CONNECT_REASON_METADATA[e].requirement : "device approval is required";
}
/** Builds the gateway close/error message for a pairing-required connect failure. */
function buildPairingConnectErrorMessage(e) {
return e ? `pairing required: ${describePairingConnectRequirement(e)}` : "pairing required";
}
/** Short user-facing recovery title for pairing-required connect failures. */
function buildPairingConnectRecoveryTitle(e) {
return e ? PAIRING_CONNECT_REASON_METADATA[e].recoveryTitle : "Gateway pairing approval required.";
}
/** Builds sanitized structured details for a pairing-required connect failure. */
function buildPairingConnectErrorDetails(e) {
return createPairingConnectErrorDetails({
...normalizePairingConnectMetadata(e, e.reason),
reason: e.reason,
recommendedNextStep: e.recommendedNextStep,
retryable: e.retryable,
pauseReconnect: e.pauseReconnect,
waitForResolution: e.waitForResolution
});
}
function normalizePairingConnectMetadata(e, t) {
return {
requestId: normalizePairingConnectRequestId(e.requestId),
remediationHint: normalizeOptionalString(e.remediationHint) ?? (t ? PAIRING_CONNECT_REASON_METADATA[t].remediationHint : "Approve the pending device request before retrying."),
deviceId: normalizeOptionalString(e.deviceId),
requestedRole: normalizeOptionalString(e.requestedRole),
requestedScopes: normalizeOptionalTrimmedStringList(e.requestedScopes),
approvedRoles: normalizeOptionalTrimmedStringList(e.approvedRoles),
approvedScopes: normalizeOptionalTrimmedStringList(e.approvedScopes)
};
}
/** Builds a sanitized close reason string for WebSocket pairing rejections. */
function buildPairingConnectCloseReason(e) {
const t = normalizePairingConnectRequestId(e.requestId);
const n = buildPairingConnectErrorMessage(e.reason);
return t ? `${n} (requestId: ${t})` : n;
}
/** Reads and backfills pairing-required details from an untrusted details object. */
function readPairingConnectErrorDetails(e) {
if (readConnectErrorDetailCode(e) !== ConnectErrorDetailCodes.PAIRING_REQUIRED) return null;
if (!isRecord(e)) return null;
const t = normalizePairingConnectReason(e.reason);
return createPairingConnectErrorDetails({
...normalizePairingConnectMetadata(e, t),
reason: t,
recommendedNextStep: normalizeConnectRecoveryNextStep(e.recommendedNextStep),
retryable: typeof e.retryable === "boolean" ? e.retryable : void 0,
pauseReconnect: typeof e.pauseReconnect === "boolean" ? e.pauseReconnect : void 0,
waitForResolution: typeof e.waitForResolution === "boolean" ? e.waitForResolution : void 0
});
}
/** Parses legacy/string-only pairing-required messages into structured details. */
function readConnectPairingRequiredMessage(e) {
const t = normalizeOptionalString(e);
if (!t) return null;
const n = t.toLowerCase();
let r;
for (const [e, t] of Object.entries(PAIRING_CONNECT_REASON_METADATA)) if (n.includes(t.message)) {
r = e;
break;
}
if (!r && n.includes("pairing required")) r = "not-paired";
if (!r) return null;
const i = normalizePairingConnectRequestId(t.match(/\(requestId:\s*([^\s)]+)\)/i)?.[1]);
return {
...i ? { requestId: i } : {},
reason: r
};
}
const PAIRING_APPROVAL_REMEDIATION = "Approve this request from the Gateway host: run `openclaw devices approve --latest` there to preview the pending request, then run the printed `openclaw devices approve <requestId>` command (add --url and --token/--password if that CLI needs them to reach the Gateway), or approve it in the Gateway's Control UI (Settings -> Devices). Then reconnect.";
const DEVICE_TOKEN_REMEDIATION = "Rotate the paired-device token with `openclaw devices rotate --device <deviceId> --role operator`, then reconnect.";
const SHARED_TOKEN_REMEDIATION = "Verify `gateway.remote.token` matches `gateway.auth.token`. If a paired-device token is stale, rotate it with `openclaw devices rotate --device <deviceId> --role operator`, then reconnect.";
const SCOPE_MISMATCH_REMEDIATION = "Review approved scopes with `openclaw devices list`; if an upgrade is pending, preview it with `openclaw devices approve --latest`, approve the printed request, then reconnect.";
const RATE_LIMITED_REMEDIATION = "Wait for the temporary authentication lockout to expire, then retry.";
const IDENTITY_PROXY_REMEDIATION = "An identity-aware proxy rejected the WebSocket upgrade. Configure gateway.remote.edgeAuth for the configured Gateway origin, then reconnect. See https://docs.openclaw.ai/gateway/remote#gateway-behind-an-identity-aware-proxy.";
const CLOUDFLARE_ACCESS_REMEDIATION = "Cloudflare Access detected: configure its token header or service-token headers in gateway.remote.edgeAuth.";
const IDENTITY_PROXY_HTTP_STATUSES = /* @__PURE__ */ new Set([
301,
302,
303,
307,
308,
401,
403
]);
const GATEWAY_CLOSED_MESSAGE_PATTERN = /\bgateway closed \(\d+\):/i;
function readIdentityProxyRejection(e) {
if (!isRecord(e)) return null;
if (e.reason !== "websocket-upgrade-rejected" || typeof e.httpStatus !== "number" || !IDENTITY_PROXY_HTTP_STATUSES.has(e.httpStatus)) return null;
const t = normalizeOptionalString(e.location);
return { cloudflareAccess: (URL.parse(t ?? "")?.hostname.toLowerCase().replace(/\.+$/u, ""))?.endsWith(".cloudflareaccess.com") ?? false };
}
/** Classifies Gateway connect failures from structured details, with one legacy text fallback. */
function classifyGatewayConnectFailure(e) {
const t = readConnectErrorDetailCode(e.details);
const n = normalizeOptionalString(e.message);
const r = normalizeOptionalString(e.reason);
const i = n ?? r;
const a = [n, r].filter((e) => Boolean(e)).join("\n");
const o = a.toLowerCase();
const s = readPairingConnectErrorDetails(e.details) ?? readConnectPairingRequiredMessage(a);
if (t === ConnectErrorDetailCodes.PAIRING_REQUIRED || s) return {
kind: "pairing-required",
userMessage: t === ConnectErrorDetailCodes.PAIRING_REQUIRED ? formatConnectPairingRequiredMessage(e.details) : i ?? "device pairing required",
remediation: PAIRING_APPROVAL_REMEDIATION
};
const c = readIdentityProxyRejection(e.details);
if (c) return {
kind: "identity-proxy",
userMessage: i ?? "identity-aware proxy rejected websocket upgrade",
remediation: c.cloudflareAccess ? `${IDENTITY_PROXY_REMEDIATION}\n${CLOUDFLARE_ACCESS_REMEDIATION}` : IDENTITY_PROXY_REMEDIATION
};
const l = t === ConnectErrorDetailCodes.DEVICE_IDENTITY_REQUIRED || t === ConnectErrorDetailCodes.CONTROL_UI_DEVICE_IDENTITY_REQUIRED || o.includes("device identity required");
const u = t === ConnectErrorDetailCodes.AUTH_SCOPE_MISMATCH || o.includes("scope mismatch");
const d = t === ConnectErrorDetailCodes.AUTH_RATE_LIMITED || !t && o.includes("too many failed authentication attempts");
const f = t === ConnectErrorDetailCodes.AUTH_DEVICE_TOKEN_MISMATCH || o.includes("device token mismatch");
const p = t === ConnectErrorDetailCodes.AUTH_TOKEN_MISMATCH || o.includes("gateway token mismatch");
const m = f || p || t?.startsWith("AUTH_") || t?.startsWith("DEVICE_AUTH_");
const h = l ? "device-identity-required" : u ? "scope-mismatch" : d ? "rate-limited" : m ? "auth-rejected" : t || GATEWAY_CLOSED_MESSAGE_PATTERN.test(a) ? "gateway-rejected" : "unreachable";
const g = d ? RATE_LIMITED_REMEDIATION : u ? SCOPE_MISMATCH_REMEDIATION : f ? DEVICE_TOKEN_REMEDIATION : p ? SHARED_TOKEN_REMEDIATION : void 0;
return {
kind: h,
userMessage: i ?? (h === "unreachable" ? "gateway unreachable" : "gateway rejected connection"),
...g ? { remediation: g } : {}
};
}
/** Formats pairing-required details into the canonical user-facing message. */
function formatConnectPairingRequiredMessage(e) {
const t = readPairingConnectErrorDetails(e);
const n = PAIRING_CONNECT_REASON_METADATA[t?.reason ?? "not-paired"].message;
return t?.requestId ? `${n} (requestId: ${t.requestId})` : n;
}
/** Formats connect errors using structured details before falling back to raw messages. */
function formatConnectErrorMessage(e) {
const t = readConnectErrorDetailCode(e.details);
if (t === ConnectErrorDetailCodes.PAIRING_REQUIRED) return formatConnectPairingRequiredMessage(e.details);
if (t === ConnectErrorDetailCodes.PROTOCOL_MISMATCH) return formatProtocolMismatchMessage(e.message, e.details);
return normalizeOptionalString(e.message) ?? "gateway request failed";
}
function formatProtocolMismatchMessage(e, t) {
const n = t;
const r = asPositiveInteger(n.clientMinProtocol);
const i = asPositiveInteger(n.clientMaxProtocol);
const a = asPositiveInteger(n.expectedProtocol);
const o = asPositiveInteger(n.minimumProbeProtocol);
const s = [];
if (r !== void 0 && i !== void 0) s.push(r === i ? `Control UI v${r}` : `Control UI v${r}-v${i}`);
if (a !== void 0) s.push(`Gateway v${a}`);
if (o !== void 0) s.push(`connection check min v${o}`);
const c = normalizeOptionalString(e) ?? "protocol mismatch";
return s.length > 0 ? `${c}: ${s.join(", ")}` : c;
}
//#endregion
export { buildPairingConnectRecoveryTitle as a, formatConnectErrorMessage as c, readConnectErrorRecoveryAdvice as d, readConnectPairingRequiredMessage as f, resolveDeviceAuthConnectErrorDetailCode as h, buildPairingConnectErrorMessage as i, normalizePairingConnectRequestId as l, resolveAuthConnectErrorDetailCode as m, buildPairingConnectCloseReason as n, classifyGatewayConnectFailure as o, readPairingConnectErrorDetails as p, buildPairingConnectErrorDetails as r, describePairingConnectRequirement as s, ConnectErrorDetailCodes as t, readConnectErrorDetailCode as u };