UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

4 lines • 13.4 kB
import{g as readStringValue,l as normalizeOptionalString,m as readNonBlankString}from"../../string-coerce-CpTFcSwY.mjs";import{M as resolveExpiresAtMsFromDurationSeconds,N as resolveExpiresAtMsFromEpochSeconds,O as positiveSecondsToSafeMilliseconds}from"../../number-coercion-B3CfI447.mjs";import{a as asOptionalRecord}from"../../record-coerce-BTbqdJ3-.mjs";import{d as sleepWithAbort}from"../../src-De06gkOi.mjs";import{t as formatErrorMessage}from"../../errors-D37BJTfI.mjs";import{i as readOAuthRefreshErrorReason,n as createOAuthRefreshResponseError,t as createOAuthRefreshError}from"../../oauth-refresh-outcome-CW1zSJnY.mjs";import{i as readResponseWithLimit}from"../../http-response-body-BJ35MG8h.mjs";import{a as matchesNoProxy,o as resolveEnvHttpProxyAgentOptions}from"../../proxy-env-C0Jh7bHZ.mjs";import{i as fetchWithSsrFGuard}from"../../fetch-guard-B_7-F5Lc.mjs";import{r as toFormUrlEncoded}from"../../oauth-utils-CSVUYwgv.mjs";import"../../provider-oauth-runtime-fFVFBIYg.mjs";import"../../string-coerce-runtime-BYDH9Quw.mjs";import"../../ssrf-runtime-Dx9DKr_m.mjs";import"../../number-runtime-G0nhUVZu.mjs";import"../../error-runtime-DW-sj0iq.mjs";import"../../fetch-runtime-BnxPLWBI.mjs";import"../../response-limit-runtime-uUJhFwkj.mjs";import"../../runtime-env-Qb8DG6sI.mjs";import"../../provider-auth-Czspvb3-.mjs";import{t as buildOauthProviderAuthResult}from"../../provider-auth-result-BR7b9AE1.mjs";import{r as applyXaiOAuthConfig,t as XAI_DEFAULT_MODEL_REF}from"../../onboard-c0fuy15I.mjs";import{r as buildXaiProvider,t as buildLiveXaiOAuthProvider}from"../../provider-catalog-Dn0mlZgb.mjs";import{t as xaiUserAgent}from"../../xai-user-agent-CXUAj9Ku.mjs"; //!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`)??``)||/<!doctype html|<html\b/i.test(s.text)))n.message+=`: xAI returned an HTML/Cloudflare challenge instead of OAuth JSON. Re-run xAI OAuth login if it persists.`;throw n}try{return parseXaiOAuthTokenResponse(s.json)}catch(e){throw unknownRefreshError(`returned invalid credentials`,`after-token-response`,e,o.status)}}throw createOAuthRefreshError(r+` blocked by a Cloudflare challenge; retry later`,{version:1,phase:`token-response`,outcome:`unchanged`,status:403,recovery:{kind:`later`,evidence:`verified-intermediary-challenge`}})}function resolveNextXaiDeviceCodePollDelayMs(e,t){const n=Math.max(0,t-performance.now());return Math.min(Math.max(e,XAI_DEVICE_CODE_MIN_INTERVAL_MS),n)}async function waitForXaiDeviceCodePoll(e,t){try{await sleepWithAbort(e,t)}catch(e){if(t?.aborted)throw t.reason instanceof Error?t.reason:/* @__PURE__ */ new Error(`xAI login cancelled`);throw e}}function decodeJwtPayload(e){if(!e)return{};const t=e.split(`.`)[1];if(!t)return{};try{return asOptionalRecord(JSON.parse(Buffer.from(t,`base64url`).toString(`utf8`)))??{}}catch{return{}}}function resolveXaiOAuthIdentity(e){const t=decodeJwtPayload(e.idToken??e.accessToken);const n=typeof t.email===`string`?t.email:void 0;const r=typeof t.name===`string`?t.name:void 0;const i=typeof t.sub===`string`?t.sub:void 0;return{...n?{email:n}:{},...r?{displayName:r}:{},...i?{accountId:i}:{}}}function isLegacyXaiOAuthTokenEndpoint(e){const t=URL.parse(e);return t!==null&&`${t.origin}${t.pathname}`===XAI_LEGACY_OAUTH_TOKEN_ENDPOINT}async function resolveXaiOAuthRefreshTokenEndpoint(e){const t=normalizeOptionalString(e.tokenEndpoint);if(!t||isLegacyXaiOAuthTokenEndpoint(t)){let e;try{e=await fetchXaiOAuthDiscoveryDocument()}catch(e){throw createOAuthRefreshError(`xAI OAuth discovery failed before refresh dispatch`,{version:1,phase:`before-dispatch`,outcome:`not-attempted`,recovery:{kind:`later`,evidence:`dispatch-not-started`}},{cause:e})}if(typeof e.token_endpoint!==`string`)throw new Error(`xAI OAuth discovery response is missing the token endpoint`);return requireTrustedXaiOAuthEndpoint(e.token_endpoint,`token endpoint`)}return t}async function loginXaiDeviceCode(e){const t=e.prompter.progress(`Starting xAI OAuth...`);const n={signal:e.signal,assertCurrent:e.assertCurrent};try{const r=await fetchXaiOAuthDiscoveryDocument(n);const i=r.device_authorization_endpoint;const a=r.token_endpoint;if(typeof i!==`string`||typeof a!==`string`)throw new Error(`xAI OAuth discovery response is missing device code endpoints`);const o=requireTrustedXaiOAuthEndpoint(i,`device authorization endpoint`);const s=requireTrustedXaiOAuthEndpoint(a,`token endpoint`);t.update(`Requesting xAI OAuth device code...`);const c=await fetchXaiOAuth(requireTrustedXaiOAuthEndpoint(o,`device authorization endpoint`),n,{client_id:XAI_OAUTH_CLIENT_ID,scope:XAI_OAUTH_SCOPE});const l=asOptionalRecord(await readJsonResponse(c,`xAI device code request`))??{};const u=readNonBlankString(l.device_code);const d=readNonBlankString(l.user_code);const f=readNonBlankString(l.verification_uri);const p=readNonBlankString(l.verification_uri_complete);if(!u||!d||!f)throw new Error(`xAI device code response is missing device_code, user_code, or verification_uri`);const m=requireTrustedXaiOAuthEndpoint(f,`device verification URI`);const h=p?requireTrustedXaiOAuthEndpoint(p,`complete device verification URI`):void 0;const g=positiveSecondsToSafeMilliseconds(l.expires_in)??XAI_OAUTH_TIMEOUT_MS;const _=positiveSecondsToSafeMilliseconds(l.interval)??XAI_DEVICE_CODE_DEFAULT_INTERVAL_MS;const v=h??m;let y=false;try{await e.openUrl(v);y=true}catch{e.runtime.log(`Open manually: ${m}`)}const b=Math.max(1,Math.round(g/6e4));if(e.prompter.deviceCode)await e.prompter.deviceCode({title:`xAI OAuth`,code:d,expiresInMinutes:b,message:`Enter this one-time code on the sign-in page.`});else await e.prompter.note([e.isRemote?`Open this URL in your LOCAL browser and enter the code below.`:`Open this URL in your browser and enter the code below.`,`URL: <${h??m}>`,`Code: ${d}`,`Code expires in ${b} minutes. Never share it.`].join(` `),`xAI OAuth`);const x=m;if(e.isRemote)e.runtime.log(`\nOpen this URL in your LOCAL browser:\n\n${x}\n`);else if(y)e.runtime.log(`Open: ${x}`);t.update(`Waiting for xAI device authorization...`);const pollXaiDeviceCodeToken=async()=>{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}}export{loginXaiDeviceCode,refreshXaiOAuthCredential};