UNPKG

openclaw

Version:

Multi-channel AI gateway with extensible messaging integrations

3 lines • 5.55 kB
import{A as resolveExpiresAtMsFromDurationMs,O as positiveSecondsToSafeMilliseconds,c as asFiniteNumberInRange,n as MAX_TIMER_TIMEOUT_MS}from"../../number-coercion-B3CfI447.mjs";import{t as sleep}from"../../sleep-B4CgCyZu.mjs";import{n as createOAuthRefreshResponseError,t as createOAuthRefreshError}from"../../oauth-refresh-outcome-CW1zSJnY.mjs";import{i as fetchWithSsrFGuard}from"../../fetch-guard-B_7-F5Lc.mjs";import{m as readProviderJsonObjectResponse}from"../../provider-http-errors-CWZQ78Qm.mjs";import{c as throwIfOAuthLoginAborted}from"../../provider-oauth-runtime-fFVFBIYg.mjs";import"../../string-coerce-runtime-BYDH9Quw.mjs";import"../../ssrf-runtime-Dx9DKr_m.mjs";import"../../text-utility-runtime-CDtGqkrl.mjs";import"../../number-runtime-G0nhUVZu.mjs";import"../../provider-http-D0sVd8r_.mjs"; //!extensions/opencode-go/console-oauth.ts const CONSOLE_ORIGIN=`https://opencode.ai`;const CONSOLE_URL=`${CONSOLE_ORIGIN}/console`;const CLIENT_ID=`openclaw`;const REQUEST_TIMEOUT_MS=3e4;var OpencodeConsoleOAuthError=class extends Error{constructor(e,t){super(`OpenCode Console sign-in request failed (HTTP ${t}). Retry sign-in.`);this.code=typeof e===`string`&&[`authorization_pending`,`slow_down`,`access_denied`,`expired_token`].includes(e)?e:void 0}};async function postConsoleJson(e,t,n,r){const{response:i,release:a}=await fetchWithSsrFGuard({url:`${CONSOLE_URL}/auth/device/${e}`,init:{method:`POST`,headers:{Accept:`application/json`,"Content-Type":`application/json`},body:JSON.stringify({client_id:CLIENT_ID,...t})},signal:n,beforeRequest:r,timeoutMs:REQUEST_TIMEOUT_MS,requireHttps:true,policy:{hostnameAllowlist:[`opencode.ai`]},auditContext:`opencode-go.console-oauth.${e}`});try{const e=await readProviderJsonObjectResponse(i,`OpenCode Console sign-in`,{maxBytes:65536,requestHeaders:{}});if(!i.ok||e.error!==void 0){if(t.grant_type===`refresh_token`)throw createOAuthRefreshResponseError(`OpenCode Console sign-in refresh`,i.status,e);throw new OpencodeConsoleOAuthError(e.error,i.status)}return e}finally{await a()}}function parseToken(e){const t=positiveSecondsToSafeMilliseconds(e.expires_in);const n=t===void 0?void 0:resolveExpiresAtMsFromDurationMs(t,{bufferMs:Math.min(3e5,Math.floor(t/2))});if(typeof e.access_token!==`string`||!e.access_token.trim()||typeof e.refresh_token!==`string`||!e.refresh_token.trim()||n===void 0)throw new Error(`OpenCode Console returned invalid credentials. Retry sign-in.`);return{access:e.access_token,refresh:e.refresh_token,expires:n}}async function loginOpencodeConsole(e){const assertCurrent=()=>{throwIfOAuthLoginAborted(e.signal);e.assertCurrent?.()};assertCurrent();const t=await postConsoleJson(`code`,{supports_org_scope:true},e.signal,assertCurrent);assertCurrent();const n=positiveSecondsToSafeMilliseconds(t.expires_in);const r=n===void 0?void 0:resolveExpiresAtMsFromDurationMs(n);const i=t.interval===void 0?5:asFiniteNumberInRange(t.interval,{min:Number.MIN_VALUE,max:MAX_TIMER_TIMEOUT_MS/1e3});const a=i===void 0?void 0:Math.ceil(i*1e3);const o=typeof t.verification_uri_complete===`string`?t.verification_uri_complete:t.verification_uri;if(typeof t.device_code!==`string`||!t.device_code.trim()||typeof t.user_code!==`string`||!t.user_code.trim()||typeof o!==`string`||r===void 0||a===void 0||a>2147e6)throw new Error(`OpenCode Console returned an invalid device authorization response.`);const s=URL.parse(o,`${CONSOLE_URL}/`);if(!s||s.origin!==CONSOLE_ORIGIN||s.username||s.password)throw new Error(`OpenCode Console returned an invalid verification URL.`);const{device_code:c,user_code:l}=t;if(e.prompter.deviceCode){await e.openUrl(s.href);await e.prompter.deviceCode({title:`OpenCode Console sign-in`,code:l,expiresInMinutes:Math.ceil((r-Date.now())/6e4),message:`Confirm this code, then pick the workspace OpenClaw should use.`})}else await e.prompter.note(`Open ${s.href}, confirm code ${l}, and pick a workspace.`,`OpenCode Console sign-in`);assertCurrent();if(!e.isRemote&&!e.prompter.deviceCode){try{await e.openUrl(s.href)}catch{}assertCurrent()}const u=e.prompter.progress(`Waiting for OpenCode Console approval…`);let d=false;try{let t=a;while(Date.now()<r){await sleep(Math.min(t,r-Date.now()),e.signal);assertCurrent();if(Date.now()>=r)break;try{const t=await postConsoleJson(`token`,{grant_type:`urn:ietf:params:oauth:grant-type:device_code`,device_code:c},e.signal,assertCurrent);assertCurrent();const n=parseToken(t);d=true;return n}catch(e){assertCurrent();if(!(e instanceof OpencodeConsoleOAuthError))throw e;switch(e.code){case`authorization_pending`:break;case`slow_down`:t=Math.min(t+5e3,MAX_TIMER_TIMEOUT_MS);break;case`access_denied`:throw new Error(`OpenCode Console sign-in was denied. Retry sign-in when ready.`,{cause:e});case`expired_token`:throw new Error(`OpenCode Console sign-in code expired. Start sign-in again.`,{cause:e});default:throw e}}}throw new Error(`OpenCode Console sign-in code expired. Start sign-in again.`)}finally{u.stop(d?`OpenCode Console sign-in complete`:`OpenCode Console sign-in stopped`)}}async function refreshOpencodeConsoleCredential(e){if(!e.refresh.trim())throw new Error(`OpenCode Console refresh token is missing. Sign in again.`);const t=await postConsoleJson(`token`,{grant_type:`refresh_token`,refresh_token:e.refresh});try{return{...e,...parseToken(t)}}catch(e){throw createOAuthRefreshError(`OpenCode Console refresh returned invalid credentials. Sign in again.`,{version:1,phase:`after-token-response`,outcome:`unknown`},{cause:e})}}export{loginOpencodeConsole,refreshOpencodeConsoleCredential};