openclaw
Version:
Multi-channel AI gateway with extensible messaging integrations
388 lines (387 loc) • 15.5 kB
JavaScript
import { g as readStringValue, l as normalizeOptionalString, m as readNonBlankString } from "../../string-coerce-CCIiB4H7.mjs";
import { M as resolveExpiresAtMsFromDurationSeconds, N as resolveExpiresAtMsFromEpochSeconds, O as positiveSecondsToSafeMilliseconds } from "../../number-coercion-D6u-4YD8.mjs";
import { a as asOptionalRecord } from "../../record-coerce-CVPuDqcc.mjs";
import { d as sleepWithAbort } from "../../src-BPmQBLJp.mjs";
import { t as formatErrorMessage } from "../../errors-BKzCeTYb.mjs";
import { i as readOAuthRefreshErrorReason, n as createOAuthRefreshResponseError, t as createOAuthRefreshError } from "../../oauth-refresh-outcome-DGKa-Dzy.mjs";
import { i as readResponseWithLimit } from "../../http-response-body-B-i_0116.mjs";
import { a as matchesNoProxy, o as resolveEnvHttpProxyAgentOptions } from "../../proxy-env-CZP0dXDG.mjs";
import { r as fetchWithSsrFGuard } from "../../fetch-guard-BLMw2n18.mjs";
import { c as toFormUrlEncoded } from "../../provider-openai-chatgpt-auth-Lx-WyDpB.mjs";
import "../../provider-oauth-runtime-C_hG37Q1.mjs";
import "../../string-coerce-runtime-BwAZZDf5.mjs";
import "../../ssrf-runtime-B6q6NM4E.mjs";
import "../../number-runtime-W4chuk8B.mjs";
import "../../error-runtime-BM740gJj.mjs";
import "../../fetch-runtime-Dz-KqFMb.mjs";
import "../../response-limit-runtime-DkiFHsEX.mjs";
import "../../runtime-env-D-Pa5lD6.mjs";
import "../../provider-auth-D_oAZ3fr.mjs";
import { t as buildOauthProviderAuthResult } from "../../provider-auth-result-Br3rDHr2.mjs";
import { r as applyXaiOAuthConfig, t as XAI_DEFAULT_MODEL_REF } from "../../onboard-B5OlMszM.mjs";
import { r as buildXaiProvider, t as buildLiveXaiOAuthProvider } from "../../provider-catalog-_Rqur04q.mjs";
import { t as xaiUserAgent } from "../../xai-user-agent-B_Nl--vP.mjs";
//#region extensions/xai/xai-oauth.ts
const PROVIDER_ID = "xai";
const XAI_OAUTH_CLIENT_ID = "b1a00492-073a-47ea-816f-4c329264a828";
const XAI_OAUTH_SCOPE = "openid profile email offline_access grok-cli:access api:access";
const XAI_OAUTH_ISSUER = "https://auth.x.ai";
const XAI_OAUTH_DISCOVERY_URL = `${XAI_OAUTH_ISSUER}/.well-known/openid-configuration`;
const XAI_LEGACY_OAUTH_TOKEN_ENDPOINT = `${XAI_OAUTH_ISSUER}/oauth/token`;
const XAI_OAUTH_TIMEOUT_MS = 3e5;
const XAI_OAUTH_FETCH_TIMEOUT_MS = 3e4;
const XAI_OAUTH_RESPONSE_MAX_BYTES = 16777216;
const XAI_DEVICE_CODE_DEFAULT_INTERVAL_MS = 5e3;
const XAI_DEVICE_CODE_MIN_INTERVAL_MS = 1e3;
const XAI_DEVICE_CODE_SLOW_DOWN_INCREMENT_MS = 5e3;
const XAI_DEVICE_CODE_GRANT_TYPE = "urn:ietf:params:oauth:grant-type:device_code";
function fetchXaiOAuth(e, t, n) {
return fetchWithSsrFGuard({
url: e,
beforeRequest: t.assertCurrent,
onResponse: t.onResponse,
mode: "trusted_explicit_proxy",
resolveDispatcherPolicy: (e) => {
const t = resolveEnvHttpProxyAgentOptions();
const n = e.protocol === "https:" ? t?.httpsProxy : t?.httpProxy;
return n && !matchesNoProxy(e.toString()) ? {
mode: "explicit-proxy",
proxyUrl: n,
allowPrivateProxy: true
} : void 0;
},
signal: t.signal,
timeoutMs: XAI_OAUTH_FETCH_TIMEOUT_MS,
requireHttps: true,
auditContext: "xai-oauth",
init: {
headers: {
Accept: "application/json",
"User-Agent": xaiUserAgent(),
...n ? { "Content-Type": "application/x-www-form-urlencoded" } : {}
},
...n ? {
method: "POST",
body: toFormUrlEncoded(n)
} : {}
}
});
}
function requireTrustedXaiOAuthEndpoint(e, t) {
const n = URL.parse(e);
if (n?.protocol === "https:" && (n.hostname === "x.ai" || n.hostname.endsWith(".x.ai"))) return e;
throw new Error(`xAI OAuth discovery returned untrusted ${t}`);
}
async function readResponseBody({ response: e, release: t }, n = {}) {
try {
const t = await readResponseWithLimit(e, XAI_OAUTH_RESPONSE_MAX_BYTES, { onOverflow: ({ maxBytes: e }) => /* @__PURE__ */ new Error(`xAI OAuth response exceeds ${e} bytes`) });
const r = new TextDecoder("utf-8", { fatal: n.fatalUtf8 }).decode(t);
let i;
try {
i = JSON.parse(r);
} catch {
i = null;
}
return {
json: i,
text: r
};
} finally {
await t();
}
}
async function readJsonResponse(e, t) {
const { response: n } = e;
const r = await readResponseBody(e);
if (!n.ok) {
const e = asOptionalRecord(r.json);
const i = e?.error_description ?? e?.error;
throw Object.assign(/* @__PURE__ */ new Error(`${t} failed (${n.status})${typeof i === "string" ? `: ${i}` : ""}`), {
status: n.status,
reason: readOAuthRefreshErrorReason(r.json)
});
}
return r.json;
}
async function fetchXaiOAuthDiscoveryDocument(e = {}) {
const t = await fetchXaiOAuth(XAI_OAUTH_DISCOVERY_URL, e);
return asOptionalRecord(await readJsonResponse(t, "xAI OAuth discovery")) ?? {};
}
function parseXaiOAuthTokenResponse(e, t = {}) {
const n = asOptionalRecord(e) ?? {};
const r = readNonBlankString(n.access_token);
if (!r) throw new Error("xAI OAuth token response is missing access_token");
const i = readNonBlankString(n.refresh_token);
if ((t.requireRefreshToken || n.refresh_token !== void 0) && !i) throw new Error("xAI OAuth token response is missing refresh_token. Re-run the login; if the issue persists, the OAuth client is not configured to issue refresh tokens (commonly because the offline_access scope was rejected).");
const a = readNonBlankString(n.id_token);
const o = resolveExpiresAtMsFromDurationSeconds(n.expires_in, { nowMs: Date.now() }) ?? resolveExpiresAtMsFromEpochSeconds(decodeJwtPayload(r).exp);
if (o === void 0) throw new Error("xAI OAuth token response is missing a usable access-token lifetime. Re-run xAI OAuth login.");
return {
accessToken: r,
...i ? { refreshToken: i } : {},
...a ? { idToken: a } : {},
expires: o
};
}
const XAI_FINAL_OAUTH_ERRORS = /* @__PURE__ */ new Set(["invalid_request", "access_denied"]);
async function requestXaiOAuthRefresh(e, t) {
const n = requireTrustedXaiOAuthEndpoint(e, "token endpoint");
const r = "xAI OAuth refresh";
const unknownRefreshError = (e, t, n, i) => createOAuthRefreshError(r + " " + e, {
version: 1,
phase: t,
outcome: "unknown",
...i === void 0 ? {} : { status: i }
}, { cause: n });
const i = 3;
for (let e = 1; e <= i; e++) {
let a;
try {
a = await fetchXaiOAuth(n, {}, {
grant_type: "refresh_token",
client_id: XAI_OAUTH_CLIENT_ID,
refresh_token: t
});
} catch (e) {
throw unknownRefreshError("transport failed", "token-response", e);
}
const { response: o } = a;
if (o.status === 403 && o.headers.get("cf-mitigated") === "challenge") {
try {
await o.body?.cancel();
} finally {
await a.release();
}
if (e < i) await sleepWithAbort(250);
continue;
}
let s;
try {
s = await readResponseBody(a, { fatalUtf8: true });
} catch (e) {
throw unknownRefreshError("response could not be read", "token-response", e, o.status);
}
if (!o.ok || asOptionalRecord(s.json)?.error !== void 0) {
const e = asOptionalRecord(s.json)?.error;
const t = readStringValue(e) ?? readStringValue(asOptionalRecord(e)?.code);
const n = createOAuthRefreshResponseError(r, o.status, s.json, t && XAI_FINAL_OAUTH_ERRORS.has(t) ? void 0 : "owner-accepted-provider-retry");
if (!asOptionalRecord(s.json)?.error && (o.headers.get("cf-mitigated") === "challenge" || /text\/html/i.test(o.headers.get("content-type") ?? "") || / {
const e = performance.now() + g;
let t = _;
while (performance.now() < e) {
const r = await fetchXaiOAuth(requireTrustedXaiOAuthEndpoint(s, "token endpoint"), n, {
grant_type: XAI_DEVICE_CODE_GRANT_TYPE,
client_id: XAI_OAUTH_CLIENT_ID,
device_code: u
});
const { response: i } = r;
let a;
try {
a = (await readResponseBody(r, { fatalUtf8: true })).json;
} catch {
a = null;
}
if (i.ok) return parseXaiOAuthTokenResponse(a, { requireRefreshToken: true });
const o = asOptionalRecord(a);
const c = readStringValue(o?.error);
if (c === "authorization_pending" || c === "slow_down") {
if (c === "slow_down") t += XAI_DEVICE_CODE_SLOW_DOWN_INCREMENT_MS;
await waitForXaiDeviceCodePoll(resolveNextXaiDeviceCodePollDelayMs(t, e), n.signal);
continue;
}
if (c === "access_denied" || c === "authorization_denied") throw new Error("xAI device authorization was denied");
if (c === "expired_token") throw new Error("xAI device code expired. Re-run the login.");
const l = readStringValue(o?.error_description);
const d = `xAI device token exchange failed (${i.status})`;
throw new Error(c ? `${d}: ${c}${l ? ` (${l})` : ""}` : d);
}
throw new Error("xAI device authorization timed out");
};
const S = await pollXaiDeviceCodeToken();
const C = resolveXaiOAuthIdentity(S);
const w = e.credentialOnly ? buildXaiProvider("openai-responses", "oauth") : await buildLiveXaiOAuthProvider({
discoveryApiKey: S.accessToken,
signal: e.signal,
fetchGuard: (t) => fetchWithSsrFGuard({
...t,
beforeRequest: e.assertCurrent
})
});
t.stop("xAI OAuth complete");
return buildOauthProviderAuthResult({
providerId: PROVIDER_ID,
defaultModel: XAI_DEFAULT_MODEL_REF,
access: S.accessToken,
refresh: S.refreshToken,
expires: S.expires,
email: C.email,
displayName: C.displayName,
profileName: C.email ?? C.accountId,
configPatch: applyXaiOAuthConfig(e.credentialOnly ? {} : e.config, w),
credentialExtra: {
tokenEndpoint: s,
deviceAuthorizationEndpoint: o,
issuer: XAI_OAUTH_ISSUER,
authFlow: "device-code",
...S.idToken ? { idToken: S.idToken } : {},
...C.accountId ? { accountId: C.accountId } : {}
},
notes: ["xAI OAuth uses device-code verification without requiring a localhost callback.", "xAI may label the consent app as Grok Build because OpenClaw uses xAI's shared OAuth client."]
});
} catch (e) {
t.stop("xAI OAuth failed");
throw new Error(`xAI OAuth failed: ${formatErrorMessage(e)}`, { cause: e });
}
}
async function refreshXaiOAuthCredential(e) {
const t = e.refresh;
if (!t) throw new Error("xAI OAuth credential is missing refresh token");
const n = await resolveXaiOAuthRefreshTokenEndpoint(e);
const r = await requestXaiOAuthRefresh(n, t);
return {
...e,
type: "oauth",
provider: PROVIDER_ID,
access: r.accessToken,
refresh: r.refreshToken ?? t,
expires: r.expires,
...r.idToken ? { idToken: r.idToken } : {},
...resolveXaiOAuthIdentity(r),
tokenEndpoint: n,
issuer: XAI_OAUTH_ISSUER
};
}
//#endregion
export { loginXaiDeviceCode, refreshXaiOAuthCredential };