@aventurevc/aventure-cli 0.7.296 → 0.7.297

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.
@@ -0,0 +1,2 @@
1
+ import{A as e,a as t,g as n,k as r,r as i}from"./auth-D_KyooBG.js";import{randomUUID as a}from"node:crypto";import{chmod as o,mkdir as s,readFile as c,rename as ee,rm as l,writeFile as u}from"node:fs/promises";import{dirname as d,join as te}from"node:path";function f(e,t=[]){let r=e instanceof Error?e.message:String(e);return n(r,t)}function p(e,t=[]){let r=n(e.title,t),i=n(e.detail?.trim()??``,t);return`${e.status} ${r}${i?` — ${i}`:``}`}function m(e){let t=e.trim();if(t.length===0)throw Error(`API host must not be blank`);let n=new URL(_(t)?t:`${v(t)}://${t}`),r=y(n.hostname);if(n.protocol!==`https:`&&n.protocol!==`http:`||n.username.length>0||n.password.length>0||n.pathname!==`/`&&n.pathname!==``||n.search.length>0||n.hash.length>0)throw Error(`API host must contain only an HTTP(S) host and optional port`);if(n.protocol===`http:`&&!r)throw Error(`personal credentials require HTTPS except for loopback API hosts`);return{host:n.host.toLowerCase(),origin:n.origin,isLoopback:r}}function h(e){return{...e,host:m(e.host).origin}}function g(e){let t=m(e);if(t.isLoopback)return`http://localhost:3000`;if(t.host===`api.aventure.vc`)return`https://aventure.vc`;throw Error(`no first-party browser origin is configured for API host ${t.host}`)}function _(e){return/^[a-z][a-z\d+.-]*:\/\//iu.test(e)}function v(e){let t=e.split(`/`,1)[0]?.toLowerCase()??``;try{return y(new URL(`http://${t}`).hostname)?`http`:`https`}catch{return`https`}}function y(e){let t=e.toLowerCase();return t===`localhost`||t===`127.0.0.1`||t===`0.0.0.0`||t===`[::1]`}function b(){return te(d(r()),`credentials.json`)}function x(e){return`OS keyring is unusable (${e}); the credential will be stored in ${b()} (mode 0600).\n`}async function S(e,t){let n;try{let n=await(await D(e,t)).getPassword()??void 0;if(n!==void 0)return{record:{provider:`keyring`,value:n}}}catch(e){n=E(e)}let r=(await O())[e]?.[t];return{...r===void 0?{}:{record:{provider:`file`,value:r}},...n===void 0?{}:{keyringFailure:n}}}async function C(e,t,n){let r;try{let i=await D(e,t);if(await i.setPassword(n),await i.getPassword()===n)return await k(e,t,void 0),`keyring`;r=`Error: keyring readback did not match`}catch(e){r=E(e,[n])}if(await k(e,t,n),(await O())[e]?.[t]!==n)throw Error(`credential storage did not confirm a durable write (keyring: ${r}; file: readback did not match)`);return`file`}async function w(e,t){let n=await D(e,t),r;try{await n.deleteCredential()}catch(e){r=e}let i;try{i=await n.getPassword()??void 0}catch(n){throw await k(e,t,void 0),Error(`OS keyring removal outcome is unknown (${E(r??n)})`,{cause:n})}if(await k(e,t,void 0),i!==void 0)throw Error(`OS keyring did not confirm removal (${E(r)})`,r===void 0?void 0:{cause:r})}async function T(e,t){let n=`${t}:probe:${a()}`,r=`aventure-cli-credential-probe:${a()}`,i;try{let t=await D(e,n);await t.setPassword(r);let a=await(await D(e,n)).getPassword(),o=await t.deleteCredential(),s=await(await D(e,n)).getPassword()??void 0;if(a!==r)i=`Error: probe readback did not match`;else if(!o||s!==void 0)i=`Error: probe cleanup was not confirmed`;else return{provider:`keyring`}}catch(e){i=E(e,[r])}try{await k(e,n,r);let t=(await O())[e]?.[n];if(await k(e,n,void 0),t!==r)throw Error(`probe readback did not match`)}catch(e){throw Error(`credential storage is unavailable (keyring: ${i}; file ${b()}: ${E(e,[r])})`,{cause:e})}return{provider:`file`,keyringFailure:i}}function E(e,t=[]){if(!(e instanceof Error))return`Error`;let n=e.name||`Error`,[r=``]=f(e,t).trim().split(`
2
+ `,1);return r&&r!==n?`${n}: ${r}`:n}async function D(e,t){let{AsyncEntry:n}=await import(`@napi-rs/keyring`);return new n(e,t)}async function O(){let t=b(),n;try{n=await c(t,`utf8`)}catch(t){if(e(t))return{};throw t}let r;try{r=JSON.parse(n)}catch(e){throw Error(`${t} is not a valid credential file`,{cause:e})}if(!ne(r))throw Error(`${t} is not a valid credential file`);return r}async function k(e,t,n){let r=b(),i=await O(),a={...i[e]};if(n===void 0?delete a[t]:a[t]=n,Object.keys(a).length===0?delete i[e]:i[e]=a,Object.keys(i).length===0){await l(r,{force:!0});return}await s(d(r),{recursive:!0,mode:448});let c=`${r}.tmp`;await u(c,`${JSON.stringify(i,null,2)}\n`,{mode:384}),await o(c,384),await ee(c,r)}function ne(e){return typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.values(e).every(e=>typeof e==`object`&&!!e&&!Array.isArray(e)&&Object.values(e).every(e=>typeof e==`string`))}var A=`vc.aventure.aventure-cli.oauth`,re=`oauth:`,ie=6e4;function ae(e,t){let n=X(t);return{client:e,expiresAt:se(Z(n)),tokens:n}}async function j(e,t){let n=H(e),r=K(n,t),i;try{i=await C(A,G(n),r)}catch(e){throw Error(`OAuth credential could not be stored — ${f(e,[r,...W(t.tokens)])}`,{cause:e})}return{host:n,provider:i,credential:q(n,r)}}async function M(e){let t=H(e),n;try{n=await S(A,G(t))}catch(e){return{state:`unavailable`,summary:f(e)}}let{record:r,keyringFailure:i}=n;return r===void 0?i===void 0?{state:`missing`}:{state:`missing`,keyringFailure:i}:{state:`found`,stored:{host:t,provider:r.provider,credential:q(t,r.value)}}}async function N(e){await w(A,G(H(e)))}async function P(e){try{return await M(e)}catch(e){return{state:`invalid`,summary:f(e)}}}async function F(e){let t=await P(e);if(t.state!==`missing`)return t;let n=await I(e);return n.state===`unavailable`?n:n.keyringFailure===void 0?{state:`missing`}:{state:`missing`,keyringFailure:n.keyringFailure}}async function I(e){let t=H(e);try{return{state:`available`,...await T(A,G(t))}}catch(e){return{state:`unavailable`,summary:f(e)}}}function L(e){return V(e.authorizationServer,`authorization server`)}function R(e){return V(e.resource,`resource`)}function z(e){if(e.clientId.trim()!==e.clientId||e.clientId.length===0)throw Error(`OAuth client ID must not be blank`);return e.clientId}function B(e){if(e.scope.length===0||e.scope.some(e=>e.trim()!==e||e.length===0)||new Set(e.scope).size!==e.scope.length)throw Error(`OAuth scope must contain unique non-blank values`);return e.scope}function V(e,t,n=!1){let r;try{r=new URL(e)}catch(e){throw Error(`OAuth ${t} is not a valid URL`,{cause:e})}if(r.protocol!==`https:`||r.username.length>0||r.password.length>0||!n&&r.search.length>0||r.hash.length>0)throw Error(`OAuth ${t} must be an HTTPS URL without credentials${n?``:`, query`} or fragment`);return r}function H(e){return m(e).host}function U(e){return new Date(e.expiresAt).getTime()-ie<=Date.now()}function W(e){return[e.access_token,e.refresh_token,e.id_token]}function G(e){return`${re}${e}`}function K(e,t){return JSON.stringify({client:J(e,t.client),expiresAt:Q(t.expiresAt),tokens:X(t.tokens)})}function q(e,t){let n;try{n=JSON.parse(t)}catch(e){throw Error(`OS OAuth credential entry failed schema validation`,{cause:e})}if(!ce(n))throw Error(`OS OAuth credential entry failed schema validation`);return{client:J(e,oe(n.client)),expiresAt:Q(n.expiresAt),tokens:X(Y(n.tokens))}}function J(e,t){if(H(t.resource)!==e)throw Error(`OAuth client resource must match the credential API host`);return t}function oe(e){let n=t.safeParse(e);if(!n.success)throw Error(`OS OAuth credential entry failed canonical client validation`,{cause:n.error});return n.data}function Y(e){let t=i.safeParse(e);if(!t.success)throw Error(`OS OAuth credential entry failed OAuth token validation`,{cause:t.error});return t.data}function X(e){if(!$(e.access_token)||e.token_type.trim().toLowerCase()!==`bearer`)throw Error(`OAuth token response must contain a bearer access token`);if(e.refresh_token!==void 0&&!$(e.refresh_token))throw Error(`OAuth token response has an invalid refresh token`);return Z(e),e}function Z(e){let t=e.expires_in;if(typeof t!=`number`||!Number.isSafeInteger(t)||t<=0)throw Error(`OAuth token response must contain a positive expires_in`);return t}function se(e){let t=new Date(Date.now()+e*1e3);if(!Number.isFinite(t.getTime()))throw Error(`OAuth token response has an expiry outside the supported date range`);return t.toISOString()}function Q(e){if(typeof e!=`string`)throw Error(`OS OAuth credential entry has an invalid absolute expiry`);let t=new Date(e);if(!Number.isFinite(t.getTime())||t.toISOString()!==e)throw Error(`OS OAuth credential entry has an invalid absolute expiry`);return e}function $(e){return e.trim()===e&&e.length>0}function ce(e){return typeof e==`object`&&!!e&&!Array.isArray(e)}export{y as C,p as E,m as S,f as T,x as _,F as a,C as b,L as c,B as d,W as f,w as g,j as h,P as i,z as l,V as m,ae as n,U as o,I as p,N as r,M as s,H as t,R as u,T as v,h as w,g as x,S as y};
@@ -0,0 +1 @@
1
+ import{i as e}from"./oauth-login-oAtCenVf.js";export{e as renewOAuthTokens};
@@ -0,0 +1,4 @@
1
+ import{_ as e,et as t,h as n,i as r,it as i,n as a,o,q as s,r as c,rt as l,t as u,u as d}from"./auth-D_KyooBG.js";import{C as f,E as p,T as m,_ as h,c as g,d as _,f as v,h as ee,i as te,l as y,m as b,n as ne,o as re,p as x,t as ie,u as S,w as ae}from"./oauth-credential-De9MML57.js";import{Y as oe,n as C,r as w,t as se,w as ce}from"./index.node-DsXU1568.js";import{execFile as le}from"node:child_process";import{randomBytes as ue,timingSafeEqual as de}from"node:crypto";import{platform as fe}from"node:os";import{stderr as T,stdin as pe}from"node:process";import{once as me}from"node:events";import{createServer as he}from"node:http";import{setTimeout as ge}from"node:timers/promises";function _e(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&&_e(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 t=e instanceof Response?e.status:void 0,n=e instanceof Response?await e.text():e;try{let{error:e,error_description:t,error_uri:r}=u.parse(JSON.parse(n));return new(C[e]||w)(t||``,r)}catch(e){let r=`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`;return new w(r)}}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=ce}={}){let i={"MCP-Protocol-Version":n,Accept:`application/json`},o=F(e);for(let{url:e,type:n}of o){let o=await P(e,i,t);if(o){if(!o.ok){if(await o.body?.cancel(),o.status>=400&&o.status<500)continue;throw Error(`HTTP ${o.status} trying to load ${n===`oauth`?`OAuth`:`OpenID provider`} metadata from ${e}`)}return n===`oauth`?a.parse(await o.json()):r.parse(await o.json())}}}async function ve(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 se(),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 ye(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function L(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),l=new Headers({"Content-Type":`application/x-www-form-urlencoded`,Accept:`application/json`});a&&n.set(`resource`,a.href),i?await i(l,n,s,t):r&&k(O(r,t?.token_endpoint_auth_methods_supported??[]),r,l,n);let u=await(o??fetch)(s,{method:`POST`,headers:l,body:n});if(!u.ok)throw await N(u);return c.parse(await u.json())}async function be(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){return L(e,{metadata:t,tokenRequestParams:ye(r,i,a),clientInformation:n,addClientAuthentication:s,resource:o,fetchFn:c})}async function xe(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await L(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}var Se=2;function Ce(e,t){return B(e,t).redactedUrl}async function R(e,t,n){let r=B(e,t);return await z(new URL(r.openerUrl),n)}async function z(e,t){let n=t.environment??process.env,r=t.operatingSystem??fe(),i=we(t.noBrowser,n,r);if(i!==null)return{state:`skipped`,reason:i};let a=Te(r,e.toString());if(a===null)return{state:`failed`,reason:`unsupported browser-opening platform: ${r}`};try{return await Ee(a.command,a.arguments),{state:`opened`,reason:null}}catch{return{state:`failed`,reason:`browser opener failed`}}}function B(e,t){let{id:n,verificationUrl:r,pollSecret:i}=e,a,o;try{a=new URL(r),o=new URL(t)}catch{throw Error(`broker returned an invalid browser verification URL`)}if(o.username.length>0||o.password.length>0||o.pathname!==`/`||o.search.length>0||o.hash.length>0)throw Error(`configured browser origin must contain only an origin`);let s=f(o.hostname);if(o.protocol!==`https:`&&!(o.protocol===`http:`&&s))throw Error(`configured browser origin must use HTTPS except for loopback development`);let c=new URLSearchParams(a.hash.slice(1)),l=[...c.keys()],u=c.getAll(`cliAuthorizationId`),d=c.getAll(`browserSecret`),p=d[0]??``;if(a.origin!==o.origin||a.protocol!==o.protocol||a.username.length>0||a.password.length>0||a.pathname!==`/settings/developer`||a.search.length>0||l.length!==Se||u.length!==1||u[0]!==n||d.length!==1||p.length===0||i.length===0||p===i)throw Error(`broker returned a browser verification URL outside the configured first-party approval flow`);let m;try{m=decodeURIComponent(r)}catch{throw Error(`broker returned a browser verification URL outside the configured first-party approval flow`)}if(r.includes(i)||m.includes(i))throw Error(`broker returned a browser verification URL outside the configured first-party approval flow`);let h=new URL(a);return h.hash=new URLSearchParams({cliAuthorizationId:n,browserSecret:`<redacted>`}).toString(),{openerUrl:r,redactedUrl:h.toString()}}function we(e,t,n){return e?`--no-browser was set`:n===`darwin`&&t.CODEX_SESSION_ID?`macOS Codex browser process boundary`:t.SSH_CONNECTION||t.SSH_CLIENT||t.SSH_TTY?`SSH/headless session detected`:(n===`linux`||n===`freebsd`)&&!t.DISPLAY&&!t.WAYLAND_DISPLAY?`no graphical display detected`:null}function Te(e,t){return e===`darwin`?{command:`open`,arguments:[t]}:e===`win32`?{command:`rundll32.exe`,arguments:[`url.dll,FileProtocolHandler`,t]}:e===`linux`||e===`freebsd`?{command:`xdg-open`,arguments:[t]}:null}function Ee(e,t){return new Promise((n,r)=>{le(e,[...t],{timeout:5e3,windowsHide:!0},e=>e?r(e):n())})}var De=5e3,Oe=`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 b(t,`device authorization endpoint`,!0)}async function ke(e,t){let n=await fetch(V(t),{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:y(e),scope:_(e).join(` `),resource:S(e).toString()})});if(!n.ok)throw Error(`device authorization endpoint answered ${n.status}`);return Ae(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 Ae(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:b(c,`verification URI`,!0),expiresAt:t+o*1e3,intervalMilliseconds:(typeof s==`number`&&s>=0?s:5)*1e3}}async function je(e,t,n){let r=b(t.token_endpoint,`token endpoint`,!0),i=n.intervalMilliseconds;for(;Date.now()<n.expiresAt;){await ge(i);let t=await fetch(r,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:y(e),grant_type:Oe,device_code:n.deviceCode})}),a=await H(t,`token`);if(t.ok){let e=c.safeParse(a);if(!e.success)throw Error(`token endpoint returned an invalid token response`);return e.data}let o=u.safeParse(a),s=o.success?o.data.error:`HTTP ${t.status}`;if(s!==`authorization_pending`){if(s===`slow_down`){i+=De;continue}throw Error(s===`access_denied`?`the sign-in was denied in the browser`:s===`expired_token`?`the device code expired before approval`:`token endpoint answered ${s}`)}}throw Error(`the device code expired before approval`)}var Me=3e5;function Ne(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 Pe(e,t){let n,r=new Promise(e=>{n=e}),i=he((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||!de(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=me(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`}),Me)})]).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))})}async function Fe(n,r){if(!pe.isTTY){let e=r??s().bin[0];return l(`${e} auth login requires an interactive TTY on stdin`,[`Use AUTH_TOKEN for non-interactive automation.`])}let a;try{a=ie(t().host)}catch(e){return l(`auth login: invalid API host — ${m(e)}`)}let o=await te(a);if(o.state===`missing`)return W(a,n);if(o.state===`unavailable`)return l(`auth login: ${o.summary}`);if(o.state===`invalid`)return W(a,n,`Saved OAuth credential cannot be read — ${o.summary}`);let{stored:c}=o;if(re(c.credential))return await Ie(c,n);let u;try{u=await d(c.credential.tokens.access_token,S(c.credential.client))!==null}catch(t){return t instanceof e?W(a,n,`Saved OAuth credential was rejected`):l(`auth login: saved OAuth credential could not be verified — ${m(t,v(c.credential.tokens))}`)}return u?i(`OAuth CLI access token is already stored and verified.`,$(c)):W(a,n,`Saved OAuth credential was rejected`)}async function Ie(e,t){let n=await x(e.host);if(n.state===`unavailable`)return l(`auth login: ${n.summary}`);let{client:r,tokens:i}=e.credential;if(i.refresh_token===void 0)return W(e.host,t,`Saved OAuth access token expired`,n);let a;try{a=await q(e)}catch(r){return W(e.host,t,`Saved OAuth credential could not be renewed — ${m(r,v(i))}`,n)}J(n);let o=await Z(r,a);return o.state===`failed`?l(`auth login: ${o.summary}`):o.state===`rejected`?W(e.host,t,`Renewed OAuth access token was rejected`,n):await Q(e.host,o.credential,`OAuth CLI access token renewed and verified.`)}async function W(e,t,n,r){let i=r??await x(e);if(i.state===`unavailable`)return l(`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 l(`auth login: OAuth configuration is unavailable — ${m(e)}`)}let o;try{o=await X(a)}catch(e){return l(`auth login: OAuth authorization-server discovery failed — ${m(e)}`)}if(t.noBrowser)return await G(e,a,o);let s=ue(32).toString(`base64url`),c;try{c=await Pe(Ne(a),s);let t=await ve(g(a),{metadata:o,clientInformation:{client_id:y(a)},redirectUrl:c.redirectUri,resource:S(a),scope:_(a).join(` `),state:s}),n=await z(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 G(e,a,o);T.write(`Browser sign-in opened: choose the account, then approve. Waiting for the loopback callback...
2
+ `);let r=await c.waitForAuthorizationCode();if(r.state===`timed-out`)return l(`auth login: browser authorization timed out before the loopback callback arrived`);if(r.state===`failed`)return l(`auth login: ${r.message}`);let i;try{i=await be(g(a),{metadata:o,clientInformation:{client_id:y(a)},authorizationCode:r.authorizationCode,codeVerifier:t.codeVerifier,redirectUri:c.redirectUri,resource:S(a)})}catch(e){return l(`auth login: OAuth token exchange failed — ${m(e,[r.authorizationCode,t.codeVerifier])}`)}return await K(e,a,i)}catch(e){return l(`auth login: OAuth browser authorization failed — ${m(e)}`)}finally{await c?.close()}}async function G(e,t,n){if(!T.isTTY)return l(`auth login: browser authorization requires an interactive terminal for manual handoff`);let r;try{r=await ke(t,n)}catch(e){return l(`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...
3
+ `].join(`
4
+ `));let i;try{i=await je(t,n,r)}catch(e){return l(`auth login: OAuth device authorization did not complete — ${m(e,[r.deviceCode])}`)}return await K(e,t,i)}async function K(e,t,n){let r=await Z(t,n);return r.state===`failed`?l(`auth login: ${r.summary}`):r.state===`rejected`?l(`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 q(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 xe(g(t),{metadata:r,clientInformation:{client_id:y(t)},refreshToken:n.refresh_token,resource:S(t)})}function J(e){e.state===`available`&&e.provider===`file`&&T.write(h(e.keyringFailure??`unknown failure`))}async function Y(){let e=await n(ae(t()),{method:`GET`,path:o(`getAuthProviderCatalog`,{}),headers:{}},oe);if(!e.ok)throw Error(`provider catalog request failed: ${p(e.problem)}`);return e.data}async function X(e){let t=await I(g(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 b(t.authorization_endpoint,`authorization endpoint`,!0),V(t),b(t.token_endpoint,`token endpoint`,!0),t}async function Z(t,n){let r;try{r=ne(t,n)}catch(e){return{state:`failed`,summary:`OAuth token response is invalid — ${m(e,v(n))}`}}let i;try{i=await d(r.tokens.access_token,S(r.client))!==null}catch(t){return t instanceof e?{state:`rejected`}:{state:`failed`,summary:`OAuth access token could not be verified — ${m(t,v(r.tokens))}`}}return i?{state:`accepted`,credential:r}:{state:`rejected`}}async function Q(e,t,n){try{let r=await ee(e,t);return i(n,$(r))}catch(e){return l(`auth login: OAuth credential could not be durably stored — ${m(e,v(t.tokens))}`)}}function $(e){return{host:e.host,provider:e.provider,expiresAt:e.credential.expiresAt,client:e.credential.client}}export{R as a,q as i,Y as n,Ce as o,Fe as r,X as t};