eve
Version:
Filesystem-first framework for durable backend AI agents that run anywhere.
2 lines • 9.49 kB
JavaScript
import{o as e}from"./rolldown-runtime-tZXQYakl.js";import{C as t,S as n,b as r,f as i,o as a,p as o,t as s,u as c,v as l}from"./schemas-g-rLPCNX.js";import{n as u,t as d}from"./xdg-app-paths-F-QHrdza.js";import{t as f}from"./version-BC6t2Txc.js";import*as p from"node:path";import m from"node:path";import{homedir as h}from"node:os";import g from"node:fs";import*as _ from"node:fs/promises";import v from"os";import{setTimeout as y}from"node:timers/promises";const b=l().transform((e,n)=>{try{return JSON.parse(e)}catch(e){return n.addIssue({code:u.custom,message:`Invalid JSON: ${e.message}`}),t}});var x=e(d(),1);const ee=i().transform(e=>new Date(e*1e3)),S=o({token:l().min(1).optional(),refreshToken:l().min(1).optional(),expiresAt:ee.optional()}),C=b.pipe(S),w=e=>{try{return g.lstatSync(e).isDirectory()}catch{return!1}},T=()=>{if(process.env.VERCEL_AUTH_CONFIG_DIR)return process.env.VERCEL_AUTH_CONFIG_DIR;let e=(0,x.default)(`com.vercel.cli`).dataDirs();return[...e,m.join(h(),`.now`),...(0,x.default)(`now`).dataDirs()].find(e=>w(e))||e[0]},E=()=>{try{let e=m.join(T(),`auth.json`);return C.parse(g.readFileSync(e,`utf8`))}catch{return null}};function D(e){let t=m.join(T(),`auth.json`);g.mkdirSync(m.dirname(t),{recursive:!0});let n={token:e.token,expiresAt:e.expiresAt&&Math.round(e.expiresAt.getTime()/1e3),refreshToken:e.refreshToken};g.writeFileSync(t,JSON.stringify(n)+`
`)}const O=`${v.hostname()} @ vercel/sandbox/${f} node-${process.version} ${v.platform()} (${v.arch()})`,k=new URL(`https://vercel.com`),A=`cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp`,j=o({issuer:l().url(),device_authorization_endpoint:l().url(),token_endpoint:l().url(),revocation_endpoint:l().url(),jwks_uri:l().url(),introspection_endpoint:l().url()});let M;const N=o({device_code:l(),user_code:l(),verification_uri:l().url(),verification_uri_complete:l().url(),expires_in:i(),interval:i()}),P=o({active:c(!0),client_id:l(),session_id:l()}).or(o({active:c(!1)}));async function F(){if(M)return M;let e=await fetch(new URL(`.well-known/openid-configuration`,k),{headers:{"Content-Type":`application/json`,"user-agent":O}});return M=j.parse(await e.json()),M}async function I(){let e=await F();return{async deviceAuthorizationRequest(){let t=await(await fetch(e.device_authorization_endpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":O},body:new URLSearchParams({client_id:A,scope:`openid offline_access`})})).json(),n=N.safeParse(t);if(!n.success)throw new B(`Failed to parse device authorization response from the Vercel authorization server.`,t);return{device_code:n.data.device_code,user_code:n.data.user_code,verification_uri:n.data.verification_uri,verification_uri_complete:n.data.verification_uri_complete,expiresAt:Date.now()+n.data.expires_in*1e3,interval:n.data.interval}},async deviceAccessTokenRequest(t){try{return[null,await fetch(e.token_endpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":O},body:new URLSearchParams({client_id:A,grant_type:`urn:ietf:params:oauth:grant-type:device_code`,device_code:t}),signal:AbortSignal.timeout(1e4)})]}catch(e){return e instanceof Error?[e]:[Error(`An unknown error occurred. See the logs for details.`,{cause:e})]}},async processTokenResponse(e){let t=await e.json(),n=L.safeParse(t);return n.success?[null,n.data]:[new B(`Failed to parse token response from the Vercel authorization server.`,t)]},async revokeToken(t){let n=await fetch(e.revocation_endpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":O},body:new URLSearchParams({token:t,client_id:A})});if(!n.ok)return new B(`Revocation request failed`,await n.json())},async refreshToken(t){let n=await fetch(e.token_endpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":O},body:new URLSearchParams({client_id:A,grant_type:`refresh_token`,refresh_token:t})}),[r,i]=await this.processTokenResponse(n);if(r)throw r;return i},async introspectToken(t){let n=await(await fetch(e.introspection_endpoint,{method:`POST`,headers:{"Content-Type":`application/x-www-form-urlencoded`,"user-agent":O},body:new URLSearchParams({token:t})})).json(),r=P.safeParse(n);if(!r.success)throw new B(`Failed to parse introspection response from the Vercel authorization server.`,n);return r.data}}}const L=o({access_token:l(),token_type:c(`Bearer`),expires_in:i(),refresh_token:l().optional(),scope:l().optional()}),R=o({error:s([`invalid_request`,`invalid_client`,`invalid_grant`,`unauthorized_client`,`unsupported_grant_type`,`invalid_scope`,`server_error`,`authorization_pending`,`slow_down`,`access_denied`,`expired_token`,`unsupported_token_type`]),error_description:l().optional(),error_uri:l().optional()});function z(e){try{return R.parse(e)}catch(e){return e instanceof n?TypeError(`Invalid OAuth error response: ${e.message}`):TypeError(`Failed to parse OAuth error response`)}}var B=class extends Error{constructor(e,t){super(e),this.name=`OAuthError`;let n=z(t);if(n instanceof TypeError){this.cause=Error(`Unexpected response from the Vercel authorization server.`),this.code=`server_error`;return}let r=n.error;n.error_description&&(r+=`: ${n.error_description}`),n.error_uri&&(r+=` (${n.error_uri})`),this.cause=Error(r),this.code=n.error}};function V(e){return e instanceof B}async function*H({request:e,oauth:t}){let n=new AbortController;try{let r=e.interval*1e3;for(;Date.now()<e.expiresAt;){let[i,a]=await t.deviceAccessTokenRequest(e.device_code);if(i){if(i.message.includes(`timeout`)){r*=2,yield{_tag:`Timeout`,newInterval:r},await y(r,{signal:n.signal});continue}yield{_tag:`Error`,error:i};return}yield{_tag:`Response`,response:a.clone()};let[o,s]=await t.processTokenResponse(a);if(V(o)){let{code:e}=o;switch(e){case`authorization_pending`:await y(r,{signal:n.signal});continue;case`slow_down`:r+=5e3,yield{_tag:`SlowDown`,newInterval:r},await y(r,{signal:n.signal});continue;default:yield{_tag:`Error`,error:o.cause};return}}if(o){yield{_tag:`Error`,error:o};return}D({token:s.access_token,expiresAt:new Date(Date.now()+s.expires_in*1e3),refreshToken:s.refresh_token});return}yield{_tag:`Error`,error:Error(`Timed out waiting for authentication. Please try again.`)};return}finally{n.abort()}}var U=class extends Error{constructor(e){super(`HTTP ${e.statusCode}: ${e.responseText}`),this.name=`NotOk`,this.response=e}};async function W(e){let t=await fetch(`https://vercel.com/api${e.endpoint}`,{method:e.method,body:e.body,headers:{Authorization:`Bearer ${e.token}`,"Content-Type":`application/json`}});if(!t.ok){let e=await t.text();try{let{error:t}=JSON.parse(e);e=`${t.code.toUpperCase()}: ${t.message}`}catch{}throw new U({responseText:e,statusCode:t.status})}return await t.json()}const G=b.pipe(o({projectId:l(),orgId:l()}));async function K(e){let t=p.join(e,`.vercel`,`project.json`),n;try{n=await _.readFile(t,`utf-8`)}catch{return null}let r=G.safeParse(n);return r.success?{projectId:r.data.projectId,teamId:r.data.orgId}:null}const q=o({user:o({defaultTeamId:l().nullable(),username:l()})}),J=o({id:l(),slug:l(),updatedAt:i().optional(),membership:o({role:l()}),billing:o({plan:l()})}),Y=o({teams:a(r()).transform(e=>e.flatMap(e=>{let t=J.safeParse(e);return t.success?[t.data]:[]})),pagination:o({count:i(),next:i().nullable()})}),X=`vercel-sandbox-default-project`;function Z(e){return e instanceof U&&(e.response.statusCode===402||e.response.statusCode===403)}async function Q(e){let t=await K(e.cwd??process.cwd());if(t){let n=await te(e.token,t.teamId,t.projectId);return{...t,created:!1,...n}}if(e.teamId)return $(e.token,e.teamId);let{defaultTeamId:n,username:r}=(await W({token:e.token,endpoint:`/v2/user`}).then(q.parse)).user;if(n)try{let t=await $(e.token,n);try{let r=await W({token:e.token,endpoint:`/v2/teams/${encodeURIComponent(n)}`}).then(o({slug:l()}).parse);return{...t,teamSlug:r.slug}}catch{return t}}catch(e){if(!Z(e))throw e}let i=null;do{let t=i===null?`/v2/teams?limit=20`:`/v2/teams?limit=20&until=${i}`,a=await W({token:e.token,endpoint:t}).then(Y.parse);i=a.pagination.next;let o=a.teams.filter(e=>e.membership.role===`OWNER`&&e.billing.plan===`hobby`);if(o.length===0)continue;let s=o.find(e=>e.slug===r)??o.sort((e,t)=>(t.updatedAt??0)-(e.updatedAt??0))[0];if(s&&s.id!==n)try{return{...await $(e.token,s.id),teamSlug:s.slug}}catch(e){if(!Z(e))throw e}}while(i!==null);try{return{...await $(e.token,r),teamSlug:r}}catch(e){if(!Z(e))throw e}throw new U({statusCode:403,responseText:`Authenticated as "${r}" but none of the available teams allow sandbox creation.`})}async function $(e,t){let n=t.startsWith(`team_`)?`teamId=${encodeURIComponent(t)}`:`slug=${encodeURIComponent(t)}`,r=!1;try{await W({token:e,endpoint:`/v2/projects/vercel-sandbox-default-project?${n}`})}catch(t){if(!(t instanceof U)||t.response.statusCode!==404)throw t;await W({token:e,endpoint:`/v11/projects?${n}`,method:`POST`,body:JSON.stringify({name:X})}),r=!0}return{projectId:X,teamId:t,created:r}}async function te(e,t,n){try{let r=t.startsWith(`team_`)?`teamId=${encodeURIComponent(t)}`:`slug=${encodeURIComponent(t)}`,[i,a]=await Promise.all([W({token:e,endpoint:`/v2/teams/${encodeURIComponent(t)}`}).then(o({slug:l()}).parse),W({token:e,endpoint:`/v2/projects/${encodeURIComponent(n)}?${r}`}).then(o({name:l()}).parse)]);return{teamSlug:i.slug,projectSlug:a.name}}catch{return{}}}export{U as NotOk,I as OAuth,E as getAuth,Q as inferScope,V as isOAuthError,H as pollForToken,D as updateAuthConfig};