UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

9 lines • 11.1 kB
import{r as loadActivatedBundledPluginPublicSurfaceModuleSync}from"./facade-runtime-DOjwP1Dh.mjs";import{n as createOAuthRefreshResponseError,t as createOAuthRefreshError}from"./oauth-refresh-outcome-CW1zSJnY.mjs";import"./http-body-CsPV_uT5.mjs";import{i as readResponseWithLimit}from"./http-response-body-BJ35MG8h.mjs";import{t as startOAuthLoopbackCallbackServer}from"./oauth-loopback-callback-BPgd4XrV.mjs";import{a as parseOAuthAuthorizationInput,c as throwIfOAuthLoginAborted,i as generatePKCE,l as withOAuthLoginAbort,n as createOAuthLoginCancelledError,o as resolveOAuthTokenExpiresAt,r as generateBase64UrlOAuthState,t as buildOAuthRequestSignal}from"./provider-oauth-runtime-fFVFBIYg.mjs"; //!src/plugins/provider-runtime.errors.ts const OAUTH_PROVIDER_CONFIGURED_UNAVAILABLE=`OAUTH_PROVIDER_CONFIGURED_UNAVAILABLE`;var OAuthProviderConfiguredUnavailableError=class extends Error{constructor(e){super(`OAuth provider "${e}" is configured but unavailable. Install or enable its owning plugin, then retry; run openclaw doctor for diagnostics.`);this.code=OAUTH_PROVIDER_CONFIGURED_UNAVAILABLE;this.state=`configured-unavailable`;this.name=`OAuthProviderConfiguredUnavailableError`;this.providerId=e}}; //!src/llm/utils/oauth/anthropic.ts const CLIENT_ID=`9d1c250a-e61b-44d9-88ed-5944d1962f5e`;const AUTHORIZE_URL=`https://claude.ai/oauth/authorize`;const TOKEN_URL=`https://platform.claude.com/v1/oauth/token`;const DEFAULT_CALLBACK_HOST=`127.0.0.1`;const LOOPBACK_CALLBACK_HOSTS=/* @__PURE__ */ new Set([`localhost`,`127.0.0.1`,`::1`]);const REDIRECT_URI=`http://localhost:53692/callback`;const CALLBACK_TIMEOUT_MS=3e5;function resolveCallbackHost(e=process.env){const t=e.OPENCLAW_OAUTH_CALLBACK_HOST?.trim()||DEFAULT_CALLBACK_HOST;if(!LOOPBACK_CALLBACK_HOSTS.has(t))throw new Error(`Anthropic OAuth callback host must be localhost, 127.0.0.1, or ::1`);return t}const SCOPES=`org:create_api_key user:profile user:inference user:sessions:claude_code user:mcp_servers user:file_upload`;const OAUTH_RESPONSE_MAX_BYTES=16777216;function formatErrorDetails(e){if(e instanceof Error){const t=[`${e.name}: ${e.message}`];const n=e;if(n.code)t.push(`code=${n.code}`);if(n.errno!==void 0)t.push(`errno=${String(n.errno)}`);if(e.cause!==void 0)t.push(`cause=${formatErrorDetails(e.cause)}`);if(e.stack)t.push(`stack=${e.stack}`);return t.join(`; `)}return String(e)}var TokenResponseError=class extends Error{};function formatTokenResponseParseContext(e){return`bodyBytes=${Buffer.byteLength(e,`utf8`)}`}function parseTokenCredentials(e,t){let n;try{n=JSON.parse(e)}catch{throw new TokenResponseError(`${t.invalidJsonMessage} url=${TOKEN_URL}; ${formatTokenResponseParseContext(e)}`)}if(!n||typeof n!==`object`)throw new TokenResponseError(`${t.invalidFieldsMessage} url=${TOKEN_URL}; ${formatTokenResponseParseContext(e)}`);const r=n;const i=resolveOAuthTokenExpiresAt(r.expires_in,{refreshSkewMs:3e5});if(typeof r.access_token!==`string`||!r.access_token||typeof r.refresh_token!==`string`||!r.refresh_token||i===void 0)throw new TokenResponseError(`${t.invalidFieldsMessage} url=${TOKEN_URL}; ${formatTokenResponseParseContext(e)}`);return{refresh:r.refresh_token,access:r.access_token,expires:i}}async function startCallbackServer(e){if(typeof process===`undefined`||!process.versions?.node&&!process.versions?.bun)throw new Error(`Anthropic OAuth is only available in Node.js environments`);const t=await startOAuthLoopbackCallbackServer({redirectUrl:REDIRECT_URI,expectedState:e,timeoutMs:CALLBACK_TIMEOUT_MS,bindHostname:resolveCallbackHost()});return{cancelWait:()=>void t.close(),waitForCode:async()=>{try{const e=await t.waitForCallback();if(e.type===`oauth_error`)throw new Error(`Anthropic OAuth error: ${e.error}`);return{code:e.code,state:e.state}}catch(e){if(e instanceof Error&&(e.message===`OAuth callback timeout`||e.message===`OAuth callback cancelled`))return null;throw e}},close:t.close}}async function postJson(e,t){throwIfOAuthLoginAborted(t);const n=await fetch(TOKEN_URL,{method:`POST`,headers:{"Content-Type":`application/json`,Accept:`application/json`},body:JSON.stringify(e),signal:buildOAuthRequestSignal({signal:t,timeoutMs:3e4})});const r=await readResponseWithLimit(n,OAUTH_RESPONSE_MAX_BYTES,{onOverflow:({size:e})=>new TokenResponseError(`Anthropic OAuth response too large: ${e} bytes`)});const i=new TextDecoder(`utf-8`,{fatal:true}).decode(r);if(e.grant_type===`refresh_token`){let e;try{e=JSON.parse(i)}catch{}if(!n.ok||e&&typeof e===`object`&&`error`in e)throw createOAuthRefreshResponseError(`Anthropic token refresh`,n.status,e)}if(!n.ok)throw new Error(`HTTP request failed. status=${n.status}; url=${TOKEN_URL}; body=${i}`);return i}async function exchangeAuthorizationCode(e,t,n,r,i){let a;try{a=await postJson({grant_type:`authorization_code`,client_id:CLIENT_ID,code:e,state:t,redirect_uri:r,code_verifier:n},i)}catch(e){if(i?.aborted)throw createOAuthLoginCancelledError();throw new Error(`Token exchange request failed. url=${TOKEN_URL}; redirect_uri=${r}; response_type=authorization_code; details=${formatErrorDetails(e)}`,{cause:e})}return parseTokenCredentials(a,{invalidJsonMessage:`Token exchange returned invalid JSON.`,invalidFieldsMessage:`Token exchange returned invalid token fields.`})}async function loginAnthropic(e){throwIfOAuthLoginAborted(e.signal);const{verifier:t,challenge:n}=await generatePKCE();const r=generateBase64UrlOAuthState();const i=await startCallbackServer(r);const parseAuthorizationInput=e=>{const t=parseOAuthAuthorizationInput(e);if(t.state&&t.state!==r)throw new Error(`OAuth state mismatch`);return{code:t.code,state:t.state??r}};try{throwIfOAuthLoginAborted(e.signal);const a=new URLSearchParams({code:`true`,client_id:CLIENT_ID,response_type:`code`,redirect_uri:REDIRECT_URI,scope:SCOPES,code_challenge:n,code_challenge_method:`S256`,state:r});e.onAuth({url:`${AUTHORIZE_URL}?${a.toString()}`,instructions:`Complete login in your browser. If the browser is on another machine, paste the final redirect URL here.`});throwIfOAuthLoginAborted(e.signal);const o=e.onManualCodeInput?.().then(e=>{i.cancelWait();return parseAuthorizationInput(e)},e=>{i.cancelWait();throw e instanceof Error?e:new Error(String(e))});const s=i.waitForCode();let c=await withOAuthLoginAbort(o?Promise.race([o,s.then(e=>e??o)]):s,e.signal,i.cancelWait);if(!c?.code)c=parseAuthorizationInput(await withOAuthLoginAbort(e.onPrompt({message:`Paste the authorization code or full redirect URL:`,placeholder:REDIRECT_URI}),e.signal,i.cancelWait));if(!c.code)throw new Error(`Missing authorization code`);if(!c.state)throw new Error(`Missing OAuth state`);e.onProgress?.(`Exchanging authorization code for tokens...`);return exchangeAuthorizationCode(c.code,c.state,t,REDIRECT_URI,e.signal)}finally{await i.close()}}async function refreshAnthropicToken(e){let t;try{t=await postJson({grant_type:`refresh_token`,client_id:CLIENT_ID,refresh_token:e})}catch(e){throw createOAuthRefreshError(e instanceof TokenResponseError?`${e.message} Sign in again.`:`Anthropic token refresh request failed. Sign in again.`,{version:1,phase:`token-response`,outcome:`unknown`},{cause:e})}try{return parseTokenCredentials(t,{invalidJsonMessage:`Anthropic token refresh returned invalid JSON.`,invalidFieldsMessage:`Anthropic token refresh returned invalid token fields.`})}catch(e){throw createOAuthRefreshError(e instanceof TokenResponseError?`${e.message} Sign in again.`:`Anthropic token refresh returned invalid credentials. Sign in again.`,{version:1,phase:`after-token-response`,outcome:`unknown`},{cause:e})}}const anthropicOAuthProvider={id:`anthropic`,name:`Anthropic (Claude Pro/Max)`,usesCallbackServer:true,login:loginAnthropic,async refreshToken(e){return refreshAnthropicToken(e.refresh)},getApiKey(e){return e.access}}; //!src/llm/utils/oauth/openai-chatgpt.ts const OPENAI_CODEX_PROVIDER_ID=`openai`;function createLegacyRuntime(e){return{log:t=>e.onProgress?.(String(t)),error:t=>e.onProgress?.(String(t)),exit:e=>{throw new Error(`exit:${e}`)}}}function createLegacyPrompter(e){const t={update:t=>e.onProgress?.(t),stop:t=>{if(t)e.onProgress?.(t)}};return{intro:async()=>{},outro:async()=>{},note:async t=>e.onProgress?.(t),select:async e=>e.options[0]?.value,multiselect:async e=>e.initialValues??[],text:async t=>{const n=e.onPrompt({message:t.message,placeholder:t.placeholder});return await withOAuthLoginAbort(n,e.signal)},confirm:async()=>false,progress:()=>t}}async function refreshViaProviderRuntime(e){const{refreshProviderOAuthCredentialWithPlugin:t}=await import(`./plugins/provider-runtime.runtime.js`);const n=await t({provider:OPENAI_CODEX_PROVIDER_ID,context:{...e,type:`oauth`,provider:OPENAI_CODEX_PROVIDER_ID}});if(!n){if(e.authFlow)throw new Error(`OpenAI OAuth flow owner is unavailable. Enable the OpenAI plugin to reconnect.`);return await loadActivatedBundledPluginPublicSurfaceModuleSync({dirName:`openai`,artifactBasename:`api.js`}).refreshOpenAICodexToken(e.refresh)}const r={...n};delete r.type;delete r.provider;return r}async function loginOpenAICodex(e){throwIfOAuthLoginAborted(e.signal);const{loginOpenAICodexOAuth:t}=await import(`./provider-openai-chatgpt-oauth-CLIm_-cB.mjs`);const n=e.onManualCodeInput;const r=n?async()=>await withOAuthLoginAbort(n(),e.signal):void 0;const i=await withOAuthLoginAbort(t({prompter:createLegacyPrompter(e),runtime:createLegacyRuntime(e),isRemote:false,signal:e.signal,onManualCodeInput:r,openUrl:async t=>{throwIfOAuthLoginAborted(e.signal);await e.onAuth({url:t})}}),e.signal);throwIfOAuthLoginAborted(e.signal);if(!i)throw new Error(`OpenAI Codex OAuth login did not return credentials.`);return i}const openaiCodexOAuthProvider={id:OPENAI_CODEX_PROVIDER_ID,name:`ChatGPT Plus/Pro (Codex Subscription)`,usesCallbackServer:true,login:loginOpenAICodex,async refreshToken(e){return await refreshViaProviderRuntime(e)},getApiKey(e){return e.access}}; //!src/llm/utils/oauth/index.ts const BUILT_IN_OAUTH_PROVIDERS=[anthropicOAuthProvider,openaiCodexOAuthProvider];async function resolveOAuthApiKey(e,t){let n=t[e.id];if(!n)return null;if(Date.now()>=n.expires)try{n=await e.refreshToken(n)}catch(t){throw new Error(`Failed to refresh OAuth token for ${e.id}`,{cause:t})}return{newCredentials:n,apiKey:e.getApiKey(n)}}var OAuthProviderRegistry=class{constructor(){this.providers=/* @__PURE__ */ new Map;this.reset()}get(e){return this.providers.get(e)}register(e){this.providers.set(e.id,e)}reset(){this.providers.clear();for(const e of BUILT_IN_OAUTH_PROVIDERS)this.providers.set(e.id,e)}getAll(){return Array.from(this.providers.values())}async getApiKey(e,t){const n=this.get(e);if(!n)throw new Error(`Unknown OAuth provider: ${e}`);return resolveOAuthApiKey(n,t)}};function getOAuthProviders(){return[...BUILT_IN_OAUTH_PROVIDERS]}async function getOAuthApiKey(e,t){const n=BUILT_IN_OAUTH_PROVIDERS.find(t=>t.id===e);if(!n)throw new Error(`Unknown OAuth provider: ${e}`);return resolveOAuthApiKey(n,t)}export{OAuthProviderConfiguredUnavailableError as i,getOAuthApiKey as n,getOAuthProviders as r,OAuthProviderRegistry as t};