@aventurevc/aventure-cli 0.7.332 → 0.8.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,6 +1,6 @@
1
- import{C as e,F as t,P as n,d as r,et as i,i as a,it as o,n as s,p as c,r as l,rt as u,s as ee,t as d}from"./auth-Dz_A-dL_.js";import{A as te,E as f,M as p,N as ne,T as re,_ as m,c as h,f as g,g as _,h as v,i as ie,l as y,m as b,n as x,o as S,p as C,r as ae,u as w}from"./oauth-bearer-credential-1WZWSwji.js";import{S as oe,q as se,t as ce}from"./index.node-BpjrGuen.js";import{once as le}from"node:events";import{stderr as T}from"node:process";import{createServer as ue}from"node:http";import{randomBytes as de,timingSafeEqual as fe}from"node:crypto";import{setTimeout as pe}from"node:timers/promises";function me(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}var E=`code`,D=`S256`;function O(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&me(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function k(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:A(i,a,n);return;case`client_secret_post`:j(i,a,r);return;case`none`:M(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function A(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function j(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function M(e,t){t.set(`client_id`,e)}async function N(e){let r=e instanceof Response?e.status:void 0,i=e instanceof Response?await e.text():e;try{let{error:e,error_description:r,error_uri:a}=d.parse(JSON.parse(i));return new(n[e]||t)(r||``,a)}catch(e){let n=`${r?`HTTP ${r}: `:``}Invalid OAuth error response: ${e}. Raw body: ${i}`;return new t(n)}}async function P(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?P(e,void 0,n):void 0;throw r}}function F(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function I(e,{fetchFn:t=fetch,protocolVersion:n=oe}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},i=F(e);for(let{url:e,type:n}of i){let i=await P(e,r,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?s.parse(await i.json()):a.parse(await i.json())}}}async function L(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(E))throw Error(`Incompatible auth server: does not support response type ${E}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(D))throw Error(`Incompatible auth server: does not support code challenge method ${D}`)}else s=new URL(`/authorize`,e);let c=await ce(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,E),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,D),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,o.href),{authorizationUrl:s,codeVerifier:l}}function R(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function z(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,a.href),i?await i(c,n,s,t):r&&k(O(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let u=await(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!u.ok)throw await N(u);return l.parse(await u.json())}async function he(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){return z(e,{metadata:t,tokenRequestParams:R(r,i,a),clientInformation:n,addClientAuthentication:s,resource:o,fetchFn:c})}async function ge(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await z(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}var _e=5e3,ve=500,B=`Approval poll was interrupted; retrying.
2
- `,ye=`urn:ietf:params:oauth:grant-type:device_code`;function V(e){let t=Reflect.get(e,`device_authorization_endpoint`);if(typeof t!=`string`)throw Error(`OAuth authorization-server metadata lacks device_authorization_endpoint`);return _(t,`device authorization endpoint`,!0)}async function be(e,t){let n=await fetch(V(t),{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:w(e),scope:C(e).join(` `),resource:g(e).toString()})});if(!n.ok)throw Error(`device authorization endpoint answered ${n.status}`);return xe(await H(n,`device authorization`),Date.now())}async function H(e,t){try{return await e.json()}catch(n){throw Error(`${t} endpoint answered ${e.status} without a JSON body`,{cause:n})}}function xe(e,t){if(typeof e!=`object`||!e)throw Error(`device authorization response is not an object`);let n=Reflect.get(e,`device_code`),r=Reflect.get(e,`user_code`),i=Reflect.get(e,`verification_uri_complete`),a=Reflect.get(e,`verification_uri`),o=Reflect.get(e,`expires_in`),s=Reflect.get(e,`interval`);if(typeof n!=`string`||typeof r!=`string`||n.length===0||r.length===0)throw Error(`device authorization response lacks device_code or user_code`);let c=typeof i==`string`&&i.length>0?i:a;if(typeof c!=`string`)throw Error(`device authorization response lacks a verification URI`);if(typeof o!=`number`||o<=0)throw Error(`device authorization response lacks a positive expires_in`);return{deviceCode:n,userCode:r,verificationUri:_(c,`verification URI`,!0),expiresAt:t+o*1e3,intervalMilliseconds:(typeof s==`number`&&s>=0?s:5)*1e3}}async function Se(e,t,n){let r=_(t.token_endpoint,`token endpoint`,!0),i=n.intervalMilliseconds,a=null;for(;Date.now()<n.expiresAt;){await pe(i);let t;try{t=await fetch(r,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:w(e),grant_type:ye,device_code:n.deviceCode})})}catch(e){a=`the token endpoint was unreachable — ${p(e)}`,T.write(B);continue}if(t.status>=ve){await t.body?.cancel(),a=`the token endpoint answered ${t.status}`,T.write(B);continue}a=null;let o=await H(t,`token`);if(t.ok){let e=l.safeParse(o);if(!e.success)throw Error(`token endpoint returned an invalid token response`);return e.data}let s=d.safeParse(o),c=s.success?s.data.error:`HTTP ${t.status}`;if(c!==`authorization_pending`){if(c===`slow_down`){i+=_e;continue}throw Error(c===`access_denied`?`the sign-in was denied in the browser`:c===`expired_token`?`the device code expired before approval`:`token endpoint answered ${c}`)}}throw Error(a===null?`the device code expired before approval`:`the device code expired before approval — last failure: ${a}`)}var Ce=3e5;function we(e){let t;try{t=new URL(e.redirectUri)}catch(e){throw Error(`OAuth callback configuration is not a valid URL`,{cause:e})}if(t.protocol!==`http:`||t.hostname!==`127.0.0.1`||t.port.length>0||t.pathname!==`/callback`||t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0)throw Error(`OAuth callback configuration must be http://127.0.0.1/callback without a port, query, or fragment`);return t}async function Te(e,t){let n,r=new Promise(e=>{n=e}),i=ue((r,i)=>{i.setHeader(`Cache-Control`,`no-store`),i.setHeader(`Content-Type`,`text/plain; charset=utf-8`);let a=new URL(r.url??`/`,e);if(r.method!==`GET`||a.pathname!==e.pathname){i.statusCode=404,i.end(`OAuth callback not found.`);return}let o=a.searchParams.getAll(`state`),s=Buffer.from(o[0]??``),c=Buffer.from(t);if(o.length!==1||s.length!==c.length||!fe(s,c)){i.statusCode=400,i.end(`OAuth callback state did not match. Return to the CLI and retry.`);return}if(a.searchParams.has(`error`)){i.statusCode=400,i.end(`OAuth authorization was not completed. Return to the CLI.`),n({state:`failed`,message:`OAuth authorization server returned an error`});return}let l=a.searchParams.getAll(`code`),u=l[0]?.trim();if(l.length!==1||u===void 0||u.length===0){i.statusCode=400,i.end(`OAuth callback did not include an authorization code.`);return}i.statusCode=200,i.end(`OAuth authorization completed. Return to the CLI.`),n({state:`code`,authorizationCode:u})});i.on(`error`,e=>n({state:`failed`,message:`OAuth callback listener failed: ${p(e)}`}));try{let t=le(i,`listening`);i.listen({host:`127.0.0.1`,port:0}),await t;let n=i.address();if(n===null||typeof n==`string`||n.port<=0)throw Error(`OAuth callback listener did not receive an ephemeral loopback port`);let a=new URL(e);return a.port=String(n.port),{redirectUri:a,waitForAuthorizationCode:async()=>{let e;return await Promise.race([r,new Promise(t=>{e=setTimeout(()=>t({state:`timed-out`}),Ce)})]).finally(()=>{e!==void 0&&clearTimeout(e)})},close:async()=>await U(i)}}catch(e){throw i.listening&&await U(i),e}}function U(e){return new Promise((t,n)=>{e.close(e=>e===void 0?t():n(e))})}var W=`the OAuth credential is valid, but the API refused this account (HTTP 403); signing in again will not change that`;async function Ee(t){let n;try{n=ae(i().host)}catch(e){return u(`auth login: invalid API host — ${p(e)}`)}let a=await S(n);if(a.state===`missing`)return G(n,t);if(a.state===`unavailable`)return u(`auth login: ${a.summary}`);if(a.state===`invalid`)return G(n,t,`Saved OAuth credential cannot be read — ${a.summary}`);let{stored:s}=a;if(h(s.credential))return await De(s,t);let c;try{c=await r(s.credential.tokens.access_token,g(s.credential.client))}catch(r){return r instanceof e?G(n,t,`Saved OAuth credential was rejected`):u(`auth login: saved OAuth credential could not be verified — ${p(r,b(s.credential.tokens))}`)}return c===`forbidden`?u(`auth login: ${W}`):c===null?G(n,t,`Saved OAuth credential was rejected`):o(`OAuth CLI access token is already stored and verified.`,$(s))}async function De(e,t){let n=await v(e.host);if(n.state===`unavailable`)return u(`auth login: ${n.summary}`);let{tokens:r}=e.credential;if(r.refresh_token===void 0)return G(e.host,t,`Saved OAuth access token expired`,n);let i;try{i=await x(e)}catch(i){return G(e.host,t,`Saved OAuth credential could not be renewed — ${p(i,b(r))}`,n)}J(n);let a=await Q(e.host,i,`OAuth CLI access token renewed and verified.`);if(!a.ok)return a;let o=await Z(i);return o.state===`failed`?u(`auth login: ${o.summary}`):o.state===`rejected`?G(e.host,t,`Renewed OAuth access token was rejected`,n):a}async function G(e,t,n,r){let i=r??await v(e);if(i.state===`unavailable`)return u(`auth login: ${i.summary}`);J(i),n!==void 0&&T.write(`${n}; continuing to browser sign-in.\n`);let a;try{let e=(await Y()).oauthClient;if(e==null)throw Error(`the API does not advertise an OAuth CLI client`);a=e}catch(e){return u(`auth login: OAuth configuration is unavailable — ${p(e)}`)}let o;try{o=await X(a)}catch(e){return u(`auth login: OAuth authorization-server discovery failed — ${p(e)}`)}if(t.noBrowser)return await K(e,a,o);let s=de(32).toString(`base64url`),c;try{c=await Te(we(a),s);let t=await L(y(a),{metadata:o,clientInformation:{client_id:w(a)},redirectUrl:c.redirectUri,resource:g(a),scope:C(a).join(` `),state:s}),n=await f(t.authorizationUrl,{noBrowser:!1});if(n.state!==`opened`)return await c.close(),c=void 0,T.write(`Browser not opened automatically (${n.reason}).\n`),await K(e,a,o);T.write(`Browser sign-in opened: choose the account, then approve. Waiting for the loopback callback...
3
- `);let r=await c.waitForAuthorizationCode();if(r.state===`timed-out`)return await c.close(),c=void 0,T.write(`Browser sign-in was not completed; continuing with a device code.
4
- `),await K(e,a,o);if(r.state===`failed`)return u(`auth login: ${r.message}`);let i;try{i=await he(y(a),{metadata:o,clientInformation:{client_id:w(a)},authorizationCode:r.authorizationCode,codeVerifier:t.codeVerifier,redirectUri:c.redirectUri,resource:g(a)})}catch(e){return u(`auth login: OAuth token exchange failed — ${p(e,[r.authorizationCode,t.codeVerifier])}`)}return await q(e,a,i)}catch(e){return u(`auth login: OAuth browser authorization failed — ${p(e)}`)}finally{await c?.close()}}async function K(e,t,n){let r;try{r=await be(t,n)}catch(e){return u(`auth login: OAuth device authorization request failed — ${p(e)}`)}T.write([`Sign-in URL (works on any device): ${r.verificationUri.toString()}`,`Confirm that the page shows code ${r.userCode} before approving.`,"That page approves with the account already signed in there; to pick an account, run `auth login` on a machine with a browser.",`Waiting for approval...
1
+ import{F as e,P as t,at as n,b as r,d as i,i as a,it as o,n as s,p as c,r as l,s as u,t as d,tt as f}from"./auth-B2TcUvpP.js";import{A as ee,E as p,M as m,N as te,T as ne,_ as re,c as h,f as g,g as _,h as v,i as ie,l as y,m as b,n as x,o as S,p as C,r as ae,u as w}from"./oauth-bearer-credential-BQj8L8v9.js";import{S as oe,q as se,t as ce}from"./index.node-CJ7HN-jk.js";import{once as le}from"node:events";import{stderr as T}from"node:process";import{createServer as ue}from"node:http";import{randomBytes as de,timingSafeEqual as fe}from"node:crypto";import{setTimeout as pe}from"node:timers/promises";function me(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}var E=`code`,D=`S256`;function O(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&me(e.token_endpoint_auth_method)&&(t.length===0||t.includes(e.token_endpoint_auth_method))?e.token_endpoint_auth_method:t.length===0?n?`client_secret_basic`:`none`:n&&t.includes(`client_secret_basic`)?`client_secret_basic`:n&&t.includes(`client_secret_post`)?`client_secret_post`:t.includes(`none`)?`none`:n?`client_secret_post`:`none`}function k(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:A(i,a,n);return;case`client_secret_post`:j(i,a,r);return;case`none`:M(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function A(e,t,n){if(!t)throw Error(`client_secret_basic authentication requires a client_secret`);let r=btoa(`${e}:${t}`);n.set(`Authorization`,`Basic ${r}`)}function j(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function M(e,t){t.set(`client_id`,e)}async function N(n){let r=n instanceof Response?n.status:void 0,i=n instanceof Response?await n.text():n;try{let{error:n,error_description:r,error_uri:a}=d.parse(JSON.parse(i));return new(t[n]||e)(r||``,a)}catch(t){let n=`${r?`HTTP ${r}: `:``}Invalid OAuth error response: ${t}. Raw body: ${i}`;return new e(n)}}async function P(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?P(e,void 0,n):void 0;throw r}}function F(e){let t=typeof e==`string`?new URL(e):e,n=t.pathname!==`/`,r=[];if(!n)return r.push({url:new URL(`/.well-known/oauth-authorization-server`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration`,t.origin),type:`oidc`}),r;let i=t.pathname;return i.endsWith(`/`)&&(i=i.slice(0,-1)),r.push({url:new URL(`/.well-known/oauth-authorization-server${i}`,t.origin),type:`oauth`}),r.push({url:new URL(`/.well-known/openid-configuration${i}`,t.origin),type:`oidc`}),r.push({url:new URL(`${i}/.well-known/openid-configuration`,t.origin),type:`oidc`}),r}async function I(e,{fetchFn:t=fetch,protocolVersion:n=oe}={}){let r={"MCP-Protocol-Version":n,Accept:`application/json`},i=F(e);for(let{url:e,type:n}of i){let i=await P(e,r,t);if(i){if(!i.ok){if(await i.body?.cancel(),i.status>=400&&i.status<500)continue;throw Error(`HTTP ${i.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?s.parse(await i.json()):a.parse(await i.json())}}}async function L(e,{metadata:t,clientInformation:n,redirectUrl:r,scope:i,state:a,resource:o}){let s;if(t){if(s=new URL(t.authorization_endpoint),!t.response_types_supported.includes(E))throw Error(`Incompatible auth server: does not support response type ${E}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(D))throw Error(`Incompatible auth server: does not support code challenge method ${D}`)}else s=new URL(`/authorize`,e);let c=await ce(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,E),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,D),s.searchParams.set(`redirect_uri`,String(r)),a&&s.searchParams.set(`state`,a),i&&s.searchParams.set(`scope`,i),i?.includes(`offline_access`)&&s.searchParams.append(`prompt`,`consent`),o&&s.searchParams.set(`resource`,o.href),{authorizationUrl:s,codeVerifier:l}}function R(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function z(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let s=t?.token_endpoint?new URL(t.token_endpoint):new URL(`/token`,e),c=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,a.href),i?await i(c,n,s,t):r&&k(O(r,t?.token_endpoint_auth_methods_supported??[]),r,c,n);let u=await(o??fetch)(s,{method:`POST`,headers:c,body:n});if(!u.ok)throw await N(u);return l.parse(await u.json())}async function he(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){return z(e,{metadata:t,tokenRequestParams:R(r,i,a),clientInformation:n,addClientAuthentication:s,resource:o,fetchFn:c})}async function ge(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await z(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}var _e=5e3,ve=500,B=`Approval poll was interrupted; retrying.
2
+ `,ye=`urn:ietf:params:oauth:grant-type:device_code`;function V(e){let t=Reflect.get(e,`device_authorization_endpoint`);if(typeof t!=`string`)throw Error(`OAuth authorization-server metadata lacks device_authorization_endpoint`);return _(t,`device authorization endpoint`,!0)}async function be(e,t){let n=await fetch(V(t),{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:w(e),scope:C(e).join(` `),resource:g(e).toString()})});if(!n.ok)throw Error(`device authorization endpoint answered ${n.status}`);return xe(await H(n,`device authorization`),Date.now())}async function H(e,t){try{return await e.json()}catch(n){throw Error(`${t} endpoint answered ${e.status} without a JSON body`,{cause:n})}}function xe(e,t){if(typeof e!=`object`||!e)throw Error(`device authorization response is not an object`);let n=Reflect.get(e,`device_code`),r=Reflect.get(e,`user_code`),i=Reflect.get(e,`verification_uri_complete`),a=Reflect.get(e,`verification_uri`),o=Reflect.get(e,`expires_in`),s=Reflect.get(e,`interval`);if(typeof n!=`string`||typeof r!=`string`||n.length===0||r.length===0)throw Error(`device authorization response lacks device_code or user_code`);let c=typeof i==`string`&&i.length>0?i:a;if(typeof c!=`string`)throw Error(`device authorization response lacks a verification URI`);if(typeof o!=`number`||o<=0)throw Error(`device authorization response lacks a positive expires_in`);return{deviceCode:n,userCode:r,verificationUri:_(c,`verification URI`,!0),expiresAt:t+o*1e3,intervalMilliseconds:(typeof s==`number`&&s>=0?s:5)*1e3}}async function Se(e,t,n){let r=_(t.token_endpoint,`token endpoint`,!0),i=n.intervalMilliseconds,a=null;for(;Date.now()<n.expiresAt;){await pe(i);let t;try{t=await fetch(r,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:w(e),grant_type:ye,device_code:n.deviceCode})})}catch(e){a=`the token endpoint was unreachable — ${m(e)}`,T.write(B);continue}if(t.status>=ve){await t.body?.cancel(),a=`the token endpoint answered ${t.status}`,T.write(B);continue}a=null;let o=await H(t,`token`);if(t.ok){let e=l.safeParse(o);if(!e.success)throw Error(`token endpoint returned an invalid token response`);return e.data}let s=d.safeParse(o),c=s.success?s.data.error:`HTTP ${t.status}`;if(c!==`authorization_pending`){if(c===`slow_down`){i+=_e;continue}throw Error(c===`access_denied`?`the sign-in was denied in the browser`:c===`expired_token`?`the device code expired before approval`:`token endpoint answered ${c}`)}}throw Error(a===null?`the device code expired before approval`:`the device code expired before approval — last failure: ${a}`)}var Ce=3e5;function we(e){let t;try{t=new URL(e.redirectUri)}catch(e){throw Error(`OAuth callback configuration is not a valid URL`,{cause:e})}if(t.protocol!==`http:`||t.hostname!==`127.0.0.1`||t.port.length>0||t.pathname!==`/callback`||t.username.length>0||t.password.length>0||t.search.length>0||t.hash.length>0)throw Error(`OAuth callback configuration must be http://127.0.0.1/callback without a port, query, or fragment`);return t}async function Te(e,t){let n,r=new Promise(e=>{n=e}),i=ue((r,i)=>{i.setHeader(`Cache-Control`,`no-store`),i.setHeader(`Content-Type`,`text/plain; charset=utf-8`);let a=new URL(r.url??`/`,e);if(r.method!==`GET`||a.pathname!==e.pathname){i.statusCode=404,i.end(`OAuth callback not found.`);return}let o=a.searchParams.getAll(`state`),s=Buffer.from(o[0]??``),c=Buffer.from(t);if(o.length!==1||s.length!==c.length||!fe(s,c)){i.statusCode=400,i.end(`OAuth callback state did not match. Return to the CLI and retry.`);return}if(a.searchParams.has(`error`)){i.statusCode=400,i.end(`OAuth authorization was not completed. Return to the CLI.`),n({state:`failed`,message:`OAuth authorization server returned an error`});return}let l=a.searchParams.getAll(`code`),u=l[0]?.trim();if(l.length!==1||u===void 0||u.length===0){i.statusCode=400,i.end(`OAuth callback did not include an authorization code.`);return}i.statusCode=200,i.end(`OAuth authorization completed. Return to the CLI.`),n({state:`code`,authorizationCode:u})});i.on(`error`,e=>n({state:`failed`,message:`OAuth callback listener failed: ${m(e)}`}));try{let t=le(i,`listening`);i.listen({host:`127.0.0.1`,port:0}),await t;let n=i.address();if(n===null||typeof n==`string`||n.port<=0)throw Error(`OAuth callback listener did not receive an ephemeral loopback port`);let a=new URL(e);return a.port=String(n.port),{redirectUri:a,waitForAuthorizationCode:async()=>{let e;return await Promise.race([r,new Promise(t=>{e=setTimeout(()=>t({state:`timed-out`}),Ce)})]).finally(()=>{e!==void 0&&clearTimeout(e)})},close:async()=>await U(i)}}catch(e){throw i.listening&&await U(i),e}}function U(e){return new Promise((t,n)=>{e.close(e=>e===void 0?t():n(e))})}var W=`the OAuth credential is valid, but the API refused this account (HTTP 403); signing in again will not change that`;async function Ee(e){let t;try{t=ae(f().host)}catch(e){return o(`auth login: invalid API host — ${m(e)}`)}let a=await S(t);if(a.state===`missing`)return G(t,e);if(a.state===`unavailable`)return o(`auth login: ${a.summary}`);if(a.state===`invalid`)return G(t,e,`Saved OAuth credential cannot be read — ${a.summary}`);let{stored:s}=a;if(h(s.credential))return await De(s,e);let c;try{c=await i(s.credential.tokens.access_token,g(s.credential.client))}catch(n){return n instanceof r?G(t,e,`Saved OAuth credential was rejected`):o(`auth login: saved OAuth credential could not be verified — ${m(n,b(s.credential.tokens))}`)}return c===`forbidden`?o(`auth login: ${W}`):c===null?G(t,e,`Saved OAuth credential was rejected`):n(`OAuth CLI access token is already stored and verified.`,$(s))}async function De(e,t){let n=await v(e.host);if(n.state===`unavailable`)return o(`auth login: ${n.summary}`);let{tokens:r}=e.credential;if(r.refresh_token===void 0)return G(e.host,t,`Saved OAuth access token expired`,n);let i;try{i=await x(e)}catch(i){return G(e.host,t,`Saved OAuth credential could not be renewed — ${m(i,b(r))}`,n)}J(n);let a=await Q(e.host,i,`OAuth CLI access token renewed and verified.`);if(!a.ok)return a;let s=await Z(i);return s.state===`failed`?o(`auth login: ${s.summary}`):s.state===`rejected`?G(e.host,t,`Renewed OAuth access token was rejected`,n):a}async function G(e,t,n,r){let i=r??await v(e);if(i.state===`unavailable`)return o(`auth login: ${i.summary}`);J(i),n!==void 0&&T.write(`${n}; continuing to browser sign-in.\n`);let a;try{let e=(await Y()).oauthClient;if(e==null)throw Error(`the API does not advertise an OAuth CLI client`);a=e}catch(e){return o(`auth login: OAuth configuration is unavailable — ${m(e)}`)}let s;try{s=await X(a)}catch(e){return o(`auth login: OAuth authorization-server discovery failed — ${m(e)}`)}if(t.noBrowser)return await K(e,a,s);let c=de(32).toString(`base64url`),l;try{l=await Te(we(a),c);let t=await L(y(a),{metadata:s,clientInformation:{client_id:w(a)},redirectUrl:l.redirectUri,resource:g(a),scope:C(a).join(` `),state:c}),n=await p(t.authorizationUrl,{noBrowser:!1});if(n.state!==`opened`)return await l.close(),l=void 0,T.write(`Browser not opened automatically (${n.reason}).\n`),await K(e,a,s);T.write(`Browser sign-in opened: choose the account, then approve. Waiting for the loopback callback...
3
+ `);let r=await l.waitForAuthorizationCode();if(r.state===`timed-out`)return await l.close(),l=void 0,T.write(`Browser sign-in was not completed; continuing with a device code.
4
+ `),await K(e,a,s);if(r.state===`failed`)return o(`auth login: ${r.message}`);let i;try{i=await he(y(a),{metadata:s,clientInformation:{client_id:w(a)},authorizationCode:r.authorizationCode,codeVerifier:t.codeVerifier,redirectUri:l.redirectUri,resource:g(a)})}catch(e){return o(`auth login: OAuth token exchange failed — ${m(e,[r.authorizationCode,t.codeVerifier])}`)}return await q(e,a,i)}catch(e){return o(`auth login: OAuth browser authorization failed — ${m(e)}`)}finally{await l?.close()}}async function K(e,t,n){let r;try{r=await be(t,n)}catch(e){return o(`auth login: OAuth device authorization request failed — ${m(e)}`)}T.write([`Sign-in URL (works on any device): ${r.verificationUri.toString()}`,`Confirm that the page shows code ${r.userCode} before approving.`,"That page approves with the account already signed in there; to pick an account, run `auth login` on a machine with a browser.",`Waiting for approval...
5
5
  `].join(`
6
- `));let i;try{i=await Se(t,n,r)}catch(e){return u(`auth login: OAuth device authorization did not complete — ${p(e,[r.deviceCode])}`)}return await q(e,t,i)}async function q(e,t,n){let r=await ke(t,n);return r.state===`failed`?u(`auth login: ${r.summary}`):r.state===`rejected`?u(`auth login: OAuth access token was rejected and was not stored`):await Q(e,r.credential,`OAuth CLI access token stored and verified.`)}async function Oe(e){let{client:t,tokens:n}=e.credential;if(n.refresh_token===void 0)throw Error(`saved OAuth credential has no refresh token`);let r=await X(t);return await ge(y(t),{metadata:r,clientInformation:{client_id:w(t)},refreshToken:n.refresh_token,resource:g(t)})}function J(e){e.state===`available`&&e.provider===`file`&&T.write(re(e.keyringFailure??`unknown failure`))}async function Y(){let e=await c(te(i()),{method:`GET`,path:ee(`getAuthProviderCatalog`,{}),headers:{}},se);if(!e.ok)throw Error(`provider catalog request failed: ${ne(e.problem)}`);return e.data}async function X(e){let t=await I(y(e));if(t===void 0||t.issuer!==e.authorizationServer)throw Error(`OAuth authorization-server metadata issuer must match its configured server`);if(!t.response_types_supported.includes(`code`)||t.code_challenge_methods_supported?.includes(`S256`)!==!0)throw Error(`OAuth authorization-server metadata must advertise authorization-code and PKCE S256 support`);if(t.grant_types_supported?.includes(`urn:ietf:params:oauth:grant-type:device_code`)!==!0)throw Error(`OAuth authorization-server metadata must advertise the device authorization grant`);return _(t.authorization_endpoint,`authorization endpoint`,!0),V(t),_(t.token_endpoint,`token endpoint`,!0),t}async function ke(e,t){let n;try{n=ie(e,t)}catch(e){return{state:`failed`,summary:`OAuth token response is invalid — ${p(e,b(t))}`}}return await Z(n)}async function Z(t){let n;try{n=await r(t.tokens.access_token,g(t.client))}catch(n){return n instanceof e?{state:`rejected`}:{state:`failed`,summary:`OAuth access token could not be verified — ${p(n,b(t.tokens))}`}}return n===`forbidden`?{state:`failed`,summary:W}:n===null?{state:`rejected`}:{state:`accepted`,credential:t}}async function Q(e,t,n){try{let r=await m(e,t);return o(n,$(r))}catch(e){return u(`auth login: OAuth credential could not be durably stored — ${p(e,b(t.tokens))}`)}}function $(e){return{host:e.host,provider:e.provider,expiresAt:e.credential.expiresAt,client:e.credential.client}}export{Oe as i,Y as n,Ee as r,X as t};
6
+ `));let i;try{i=await Se(t,n,r)}catch(e){return o(`auth login: OAuth device authorization did not complete — ${m(e,[r.deviceCode])}`)}return await q(e,t,i)}async function q(e,t,n){let r=await ke(t,n);return r.state===`failed`?o(`auth login: ${r.summary}`):r.state===`rejected`?o(`auth login: OAuth access token was rejected and was not stored`):await Q(e,r.credential,`OAuth CLI access token stored and verified.`)}async function Oe(e){let{client:t,tokens:n}=e.credential;if(n.refresh_token===void 0)throw Error(`saved OAuth credential has no refresh token`);let r=await X(t);return await ge(y(t),{metadata:r,clientInformation:{client_id:w(t)},refreshToken:n.refresh_token,resource:g(t)})}function J(e){e.state===`available`&&e.provider===`file`&&T.write(ne(e.keyringFailure??`unknown failure`))}async function Y(){let e=await c(ee(f()),{method:`GET`,path:u(`getAuthProviderCatalog`,{}),headers:{}},se);if(!e.ok)throw Error(`provider catalog request failed: ${te(e.problem)}`);return e.data}async function X(e){let t=await I(y(e));if(t===void 0||t.issuer!==e.authorizationServer)throw Error(`OAuth authorization-server metadata issuer must match its configured server`);if(!t.response_types_supported.includes(`code`)||t.code_challenge_methods_supported?.includes(`S256`)!==!0)throw Error(`OAuth authorization-server metadata must advertise authorization-code and PKCE S256 support`);if(t.grant_types_supported?.includes(`urn:ietf:params:oauth:grant-type:device_code`)!==!0)throw Error(`OAuth authorization-server metadata must advertise the device authorization grant`);return _(t.authorization_endpoint,`authorization endpoint`,!0),V(t),_(t.token_endpoint,`token endpoint`,!0),t}async function ke(e,t){let n;try{n=ie(e,t)}catch(e){return{state:`failed`,summary:`OAuth token response is invalid — ${m(e,b(t))}`}}return await Z(n)}async function Z(e){let t;try{t=await i(e.tokens.access_token,g(e.client))}catch(t){return t instanceof r?{state:`rejected`}:{state:`failed`,summary:`OAuth access token could not be verified — ${m(t,b(e.tokens))}`}}return t===`forbidden`?{state:`failed`,summary:W}:t===null?{state:`rejected`}:{state:`accepted`,credential:e}}async function Q(e,t,r){try{let i=await re(e,t);return n(r,$(i))}catch(e){return o(`auth login: OAuth credential could not be durably stored — ${m(e,b(t.tokens))}`)}}function $(e){return{host:e.host,provider:e.provider,expiresAt:e.credential.expiresAt,client:e.credential.client}}export{Oe as i,Y as n,Ee as r,X as t};
@@ -0,0 +1 @@
1
+ import{i as e}from"./oauth-login-CczMd-DZ.js";export{e as renewOAuthTokens};