@aventurevc/aventure-cli 0.7.297 → 0.7.301

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,2 +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};
1
+ import{A as e,a as t,g as n,j as r,r as i}from"./auth-DIikL8AE.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(e()),`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 e=b(),t;try{t=await c(e,`utf8`)}catch(e){if(r(e))return{};throw e}let n;try{n=JSON.parse(t)}catch(t){throw Error(`${e} is not a valid credential file`,{cause:t})}if(!ne(n))throw Error(`${e} is not a valid credential file`);return n}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-DlCQkNvx.js";export{e as renewOAuthTokens};
@@ -0,0 +1,5 @@
1
+ import{J as e,_ as t,h as n,i as r,it as i,n as a,o,r as s,rt as c,t as l,tt as u,u as d}from"./auth-DIikL8AE.js";import{C as ee,E as f,T as p,_ as m,c as h,d as g,f as _,h as te,i as ne,l as v,m as y,n as re,o as ie,p as b,t as x,u as S,w as ae}from"./oauth-credential-BwiTQED3.js";import{Y as oe,n as se,r as C,t as ce,w as le}from"./index.node-LwG3axmM.js";import{execFile as ue}from"node:child_process";import{randomBytes as de,timingSafeEqual as fe}from"node:crypto";import{platform as pe}from"node:os";import{stderr as w,stdin as me}from"node:process";import{once as he}from"node:events";import{createServer as ge}from"node:http";import{setTimeout as _e}from"node:timers/promises";function ve(e){return[`client_secret_basic`,`client_secret_post`,`none`].includes(e)}var T=`code`,E=`S256`;function D(e,t){let n=e.client_secret!==void 0;return`token_endpoint_auth_method`in e&&e.token_endpoint_auth_method&&ve(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 O(e,t,n,r){let{client_id:i,client_secret:a}=t;switch(e){case`client_secret_basic`:k(i,a,n);return;case`client_secret_post`:A(i,a,r);return;case`none`:j(i,r);return;default:throw Error(`Unsupported client authentication method: ${e}`)}}function k(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 A(e,t,n){n.set(`client_id`,e),t&&n.set(`client_secret`,t)}function j(e,t){t.set(`client_id`,e)}async function M(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}=l.parse(JSON.parse(n));return new(se[e]||C)(t||``,r)}catch(e){let r=`${t?`HTTP ${t}: `:``}Invalid OAuth error response: ${e}. Raw body: ${n}`;return new C(r)}}async function N(e,t,n=fetch){try{return await n(e,{headers:t})}catch(r){if(r instanceof TypeError)return t?N(e,void 0,n):void 0;throw r}}function P(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 F(e,{fetchFn:t=fetch,protocolVersion:n=le}={}){let i={"MCP-Protocol-Version":n,Accept:`application/json`},o=P(e);for(let{url:e,type:n}of o){let o=await N(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 ye(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(T))throw Error(`Incompatible auth server: does not support response type ${T}`);if(t.code_challenge_methods_supported&&!t.code_challenge_methods_supported.includes(E))throw Error(`Incompatible auth server: does not support code challenge method ${E}`)}else s=new URL(`/authorize`,e);let c=await ce(),l=c.code_verifier,u=c.code_challenge;return s.searchParams.set(`response_type`,T),s.searchParams.set(`client_id`,n.client_id),s.searchParams.set(`code_challenge`,u),s.searchParams.set(`code_challenge_method`,E),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 be(e,t,n){return new URLSearchParams({grant_type:`authorization_code`,code:e,code_verifier:t,redirect_uri:String(n)})}async function I(e,{metadata:t,tokenRequestParams:n,clientInformation:r,addClientAuthentication:i,resource:a,fetchFn:o}){let c=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,c,t):r&&O(D(r,t?.token_endpoint_auth_methods_supported??[]),r,l,n);let u=await(o??fetch)(c,{method:`POST`,headers:l,body:n});if(!u.ok)throw await M(u);return s.parse(await u.json())}async function xe(e,{metadata:t,clientInformation:n,authorizationCode:r,codeVerifier:i,redirectUri:a,resource:o,addClientAuthentication:s,fetchFn:c}){return I(e,{metadata:t,tokenRequestParams:be(r,i,a),clientInformation:n,addClientAuthentication:s,resource:o,fetchFn:c})}async function Se(e,{metadata:t,clientInformation:n,refreshToken:r,resource:i,addClientAuthentication:a,fetchFn:o}){return{refresh_token:r,...await I(e,{metadata:t,tokenRequestParams:new URLSearchParams({grant_type:`refresh_token`,refresh_token:r}),clientInformation:n,addClientAuthentication:a,resource:i,fetchFn:o})}}var Ce=2;function we(e,t){return R(e,t).redactedUrl}async function Te(e,t,n){let r=R(e,t);return await L(new URL(r.openerUrl),n)}async function L(e,t){let n=t.environment??process.env,r=t.operatingSystem??pe(),i=Ee(t.noBrowser,n,r);if(i!==null)return{state:`skipped`,reason:i};let a=De(r,e.toString());if(a===null)return{state:`failed`,reason:`unsupported browser-opening platform: ${r}`};try{return await Oe(a.command,a.arguments),{state:`opened`,reason:null}}catch{return{state:`failed`,reason:`browser opener failed`}}}function R(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=ee(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`),f=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!==Ce||u.length!==1||u[0]!==n||d.length!==1||f.length===0||i.length===0||f===i)throw Error(`broker returned a browser verification URL outside the configured first-party approval flow`);let p;try{p=decodeURIComponent(r)}catch{throw Error(`broker returned a browser verification URL outside the configured first-party approval flow`)}if(r.includes(i)||p.includes(i))throw Error(`broker returned a browser verification URL outside the configured first-party approval flow`);let m=new URL(a);return m.hash=new URLSearchParams({cliAuthorizationId:n,browserSecret:`<redacted>`}).toString(),{openerUrl:r,redactedUrl:m.toString()}}function Ee(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 De(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 Oe(e,t){return new Promise((n,r)=>{ue(e,[...t],{timeout:5e3,windowsHide:!0},e=>e?r(e):n())})}var ke=5e3,Ae=500,z=`Approval poll was interrupted; retrying.
2
+ `,je=`urn:ietf:params:oauth:grant-type:device_code`;function B(e){let t=Reflect.get(e,`device_authorization_endpoint`);if(typeof t!=`string`)throw Error(`OAuth authorization-server metadata lacks device_authorization_endpoint`);return y(t,`device authorization endpoint`,!0)}async function Me(e,t){let n=await fetch(B(t),{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:v(e),scope:g(e).join(` `),resource:S(e).toString()})});if(!n.ok)throw Error(`device authorization endpoint answered ${n.status}`);return Ne(await V(n,`device authorization`),Date.now())}async function V(e,t){try{return await e.json()}catch(n){throw Error(`${t} endpoint answered ${e.status} without a JSON body`,{cause:n})}}function Ne(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:y(c,`verification URI`,!0),expiresAt:t+o*1e3,intervalMilliseconds:(typeof s==`number`&&s>=0?s:5)*1e3}}async function Pe(e,t,n){let r=y(t.token_endpoint,`token endpoint`,!0),i=n.intervalMilliseconds,a=null;for(;Date.now()<n.expiresAt;){await _e(i);let t;try{t=await fetch(r,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`},body:new URLSearchParams({client_id:v(e),grant_type:je,device_code:n.deviceCode})})}catch(e){a=`the token endpoint was unreachable — ${p(e)}`,w.write(z);continue}if(t.status>=Ae){await t.body?.cancel(),a=`the token endpoint answered ${t.status}`,w.write(z);continue}a=null;let o=await V(t,`token`);if(t.ok){let e=s.safeParse(o);if(!e.success)throw Error(`token endpoint returned an invalid token response`);return e.data}let c=l.safeParse(o),u=c.success?c.data.error:`HTTP ${t.status}`;if(u!==`authorization_pending`){if(u===`slow_down`){i+=ke;continue}throw Error(u===`access_denied`?`the sign-in was denied in the browser`:u===`expired_token`?`the device code expired before approval`:`token endpoint answered ${u}`)}}throw Error(a===null?`the device code expired before approval`:`the device code expired before approval — last failure: ${a}`)}var Fe=3e5;function Ie(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 Le(e,t){let n,r=new Promise(e=>{n=e}),i=ge((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=he(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`}),Fe)})]).finally(()=>{e!==void 0&&clearTimeout(e)})},close:async()=>await H(i)}}catch(e){throw i.listening&&await H(i),e}}function H(e){return new Promise((t,n)=>{e.close(e=>e===void 0?t():n(e))})}async function U(n,r){if(!me.isTTY){let t=r??e().bin[0];return c(`${t} auth login requires an interactive TTY on stdin`,[`Use AUTH_TOKEN for non-interactive automation.`])}let a;try{a=x(u().host)}catch(e){return c(`auth login: invalid API host — ${p(e)}`)}let o=await ne(a);if(o.state===`missing`)return W(a,n);if(o.state===`unavailable`)return c(`auth login: ${o.summary}`);if(o.state===`invalid`)return W(a,n,`Saved OAuth credential cannot be read — ${o.summary}`);let{stored:s}=o;if(ie(s.credential))return await Re(s,n);let l;try{l=await d(s.credential.tokens.access_token,S(s.credential.client))!==null}catch(e){return e instanceof t?W(a,n,`Saved OAuth credential was rejected`):c(`auth login: saved OAuth credential could not be verified — ${p(e,_(s.credential.tokens))}`)}return l?i(`OAuth CLI access token is already stored and verified.`,$(s)):W(a,n,`Saved OAuth credential was rejected`)}async function Re(e,t){let n=await b(e.host);if(n.state===`unavailable`)return c(`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 — ${p(r,_(i))}`,n)}J(n);let o=await Z(r,a);return o.state===`failed`?c(`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 b(e);if(i.state===`unavailable`)return c(`auth login: ${i.summary}`);J(i),n!==void 0&&w.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 c(`auth login: OAuth configuration is unavailable — ${p(e)}`)}let o;try{o=await X(a)}catch(e){return c(`auth login: OAuth authorization-server discovery failed — ${p(e)}`)}if(t.noBrowser)return await G(e,a,o);let s=de(32).toString(`base64url`),l;try{l=await Le(Ie(a),s);let t=await ye(h(a),{metadata:o,clientInformation:{client_id:v(a)},redirectUrl:l.redirectUri,resource:S(a),scope:g(a).join(` `),state:s}),n=await L(t.authorizationUrl,{noBrowser:!1});if(n.state!==`opened`)return await l.close(),l=void 0,w.write(`Browser not opened automatically (${n.reason}).\n`),await G(e,a,o);w.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 c(`auth login: browser authorization timed out before the loopback callback arrived`);if(r.state===`failed`)return c(`auth login: ${r.message}`);let i;try{i=await xe(h(a),{metadata:o,clientInformation:{client_id:v(a)},authorizationCode:r.authorizationCode,codeVerifier:t.codeVerifier,redirectUri:l.redirectUri,resource:S(a)})}catch(e){return c(`auth login: OAuth token exchange failed — ${p(e,[r.authorizationCode,t.codeVerifier])}`)}return await K(e,a,i)}catch(e){return c(`auth login: OAuth browser authorization failed — ${p(e)}`)}finally{await l?.close()}}async function G(e,t,n){if(!w.isTTY)return c(`auth login: browser authorization requires an interactive terminal for manual handoff`);let r;try{r=await Me(t,n)}catch(e){return c(`auth login: OAuth device authorization request failed — ${p(e)}`)}w.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...
4
+ `].join(`
5
+ `));let i;try{i=await Pe(t,n,r)}catch(e){return c(`auth login: OAuth device authorization did not complete — ${p(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`?c(`auth login: ${r.summary}`):r.state===`rejected`?c(`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 Se(h(t),{metadata:r,clientInformation:{client_id:v(t)},refreshToken:n.refresh_token,resource:S(t)})}function J(e){e.state===`available`&&e.provider===`file`&&w.write(m(e.keyringFailure??`unknown failure`))}async function Y(){let e=await n(ae(u()),{method:`GET`,path:o(`getAuthProviderCatalog`,{}),headers:{}},oe);if(!e.ok)throw Error(`provider catalog request failed: ${f(e.problem)}`);return e.data}async function X(e){let t=await F(h(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 y(t.authorization_endpoint,`authorization endpoint`,!0),B(t),y(t.token_endpoint,`token endpoint`,!0),t}async function Z(e,n){let r;try{r=re(e,n)}catch(e){return{state:`failed`,summary:`OAuth token response is invalid — ${p(e,_(n))}`}}let i;try{i=await d(r.tokens.access_token,S(r.client))!==null}catch(e){return e instanceof t?{state:`rejected`}:{state:`failed`,summary:`OAuth access token could not be verified — ${p(e,_(r.tokens))}`}}return i?{state:`accepted`,credential:r}:{state:`rejected`}}async function Q(e,t,n){try{let r=await te(e,t);return i(n,$(r))}catch(e){return c(`auth login: OAuth credential could not be durably stored — ${p(e,_(t.tokens))}`)}}function $(e){return{host:e.host,provider:e.provider,expiresAt:e.credential.expiresAt,client:e.credential.client}}export{Te as a,q as i,Y as n,we as o,U as r,X as t};