import { createRequire as __piCreateRequire } from "node:module"; const require = __piCreateRequire(import.meta.url);
var __require=(x=>typeof require<"u"?require:typeof Proxy<"u"?new Proxy(x,{get:(a,b)=>(typeof require<"u"?require:a)[b]}):x)(function(x){if(typeof require<"u")return require.apply(this,arguments);throw Error('Dynamic require of "'+x+'" is not supported')});var procEnvCache=null;function getBunSandboxEnvValue(name){if(!(typeof process>"u"||!process.versions?.bun||Object.keys(process.env).length>0)){if(procEnvCache===null){procEnvCache=new Map;try{let{readFileSync}=__require("node:fs"),data=readFileSync("/proc/self/environ","utf-8");for(let entry of data.split("\0")){let idx=entry.indexOf("=");idx>0&&procEnvCache.set(entry.slice(0,idx),entry.slice(idx+1))}}catch{}}return procEnvCache.get(name)}}function getProviderEnvValue(name,env){return env?.[name]||(typeof process<"u"?process.env[name]:void 0)||getBunSandboxEnvValue(name)||void 0}var CANCEL_MESSAGE="Login cancelled",TIMEOUT_MESSAGE="Device flow timed out",SLOW_DOWN_TIMEOUT_MESSAGE="Device flow timed out after one or more slow_down responses. This is often caused by clock drift in WSL or VM environments. Please sync or restart the VM clock and try again.";function abortableSleep(ms,signal,cancelMessage){return new Promise((resolve,reject)=>{if(signal.aborted){reject(new Error(cancelMessage));return}let onAbort=()=>{clearTimeout(timeout),reject(new Error(cancelMessage))},timeout=setTimeout(()=>{signal.removeEventListener("abort",onAbort),resolve()},ms);signal.addEventListener("abort",onAbort,{once:!0})})}async function pollOAuthDeviceCodeFlow(options){let deadline=typeof options.expiresInSeconds=="number"?Date.now()+options.expiresInSeconds*1e3:Number.POSITIVE_INFINITY,intervalMs=Math.max(1e3,Math.floor((options.intervalSeconds??5)*1e3)),slowDownResponses=0;if(options.waitBeforeFirstPoll){let remainingMs=deadline-Date.now();remainingMs>0&&await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}for(;Date.now()<deadline;){if(options.signal.aborted)throw new Error(CANCEL_MESSAGE);let result=await options.poll();if(result.status==="complete")return result.value;if(result.status==="failed")throw new Error(result.message);result.status==="slow_down"&&(slowDownResponses+=1,intervalMs=typeof result.intervalSeconds=="number"&&Number.isFinite(result.intervalSeconds)&&result.intervalSeconds>0?Math.max(1e3,Math.floor(result.intervalSeconds*1e3)):Math.max(1e3,intervalMs+5e3));let remainingMs=deadline-Date.now();if(remainingMs<=0)break;await abortableSleep(Math.min(intervalMs,remainingMs),options.signal,CANCEL_MESSAGE)}throw new Error(slowDownResponses>0?SLOW_DOWN_TIMEOUT_MESSAGE:TIMEOUT_MESSAGE)}var LOGO_SVG='<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 800 800" aria-hidden="true"><path fill="#fff" fill-rule="evenodd" d="M165.29 165.29 H517.36 V400 H400 V517.36 H282.65 V634.72 H165.29 Z M282.65 282.65 V400 H400 V282.65 Z"/><path fill="#fff" d="M517.36 400 H634.72 V634.72 H517.36 Z"/></svg>';function escapeHtml(value){return value.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&#39;")}function renderPage(options){let title=escapeHtml(options.title),heading=escapeHtml(options.heading),message=escapeHtml(options.message),details=options.details?escapeHtml(options.details):void 0;return`<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <title>${title}</title>
  <style>
    :root {
      --text: #fafafa;
      --text-dim: #a1a1aa;
      --page-bg: #09090b;
      --font-sans: ui-sans-serif, system-ui, -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Noto Sans", sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";
      --font-mono: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;
    }
    * { box-sizing: border-box; }
    html { color-scheme: dark; }
    body {
      margin: 0;
      min-height: 100vh;
      display: flex;
      align-items: center;
      justify-content: center;
      padding: 24px;
      background: var(--page-bg);
      color: var(--text);
      font-family: var(--font-sans);
      text-align: center;
    }
    main {
      width: 100%;
      max-width: 560px;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
    }
    .logo {
      width: 72px;
      height: 72px;
      display: block;
      margin-bottom: 24px;
    }
    h1 {
      margin: 0 0 10px;
      font-size: 28px;
      line-height: 1.15;
      font-weight: 650;
      color: var(--text);
    }
    p {
      margin: 0;
      line-height: 1.7;
      color: var(--text-dim);
      font-size: 15px;
    }
    .details {
      margin-top: 16px;
      font-family: var(--font-mono);
      font-size: 13px;
      color: var(--text-dim);
      white-space: pre-wrap;
      word-break: break-word;
    }
  </style>
</head>
<body>
  <main>
    <div class="logo">${LOGO_SVG}</div>
    <h1>${heading}</h1>
    <p>${message}</p>
    ${details?`<div class="details">${details}</div>`:""}
  </main>
</body>
</html>`}function oauthSuccessHtml(message){return renderPage({title:"Authentication successful",heading:"Authentication successful",message})}function oauthErrorHtml(message,details){return renderPage({title:"Authentication failed",heading:"Authentication failed",message,details})}function base64urlEncode(bytes){let binary="";for(let byte of bytes)binary+=String.fromCharCode(byte);return btoa(binary).replace(/\+/g,"-").replace(/\//g,"_").replace(/=/g,"")}async function generatePKCE(){let verifierBytes=new Uint8Array(32);crypto.getRandomValues(verifierBytes);let verifier=base64urlEncode(verifierBytes),data=new TextEncoder().encode(verifier),hashBuffer=await crypto.subtle.digest("SHA-256",data),challenge=base64urlEncode(new Uint8Array(hashBuffer));return{verifier,challenge}}var _randomBytes=null,_http=null;typeof process<"u"&&(process.versions?.node||process.versions?.bun)&&(import("node:crypto").then(m=>{_randomBytes=m.randomBytes}),import("node:http").then(m=>{_http=m}));var CLIENT_ID="app_EMoamEEZ73f0CkXaXp7hrann",AUTH_BASE_URL="https://auth.openai.com",AUTHORIZE_URL=`${AUTH_BASE_URL}/oauth/authorize`,TOKEN_URL=`${AUTH_BASE_URL}/oauth/token`,REDIRECT_URI="http://localhost:1455/auth/callback",DEVICE_USER_CODE_URL=`${AUTH_BASE_URL}/api/accounts/deviceauth/usercode`,DEVICE_TOKEN_URL=`${AUTH_BASE_URL}/api/accounts/deviceauth/token`,DEVICE_VERIFICATION_URI=`${AUTH_BASE_URL}/codex/device`,DEVICE_REDIRECT_URI=`${AUTH_BASE_URL}/deviceauth/callback`,DEVICE_CODE_TIMEOUT_SECONDS=900,OPENAI_CODEX_BROWSER_LOGIN_METHOD="browser",OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD="device_code",SCOPE="openid profile email offline_access",JWT_CLAIM_PATH="https://api.openai.com/auth";function getCallbackHost(){return getProviderEnvValue("PI_OAUTH_CALLBACK_HOST")||"127.0.0.1"}function createState(){if(!_randomBytes)throw new Error("OpenAI Codex OAuth is only available in Node.js environments");return _randomBytes(16).toString("hex")}function parseAuthorizationInput(input){let value=input.trim();if(!value)return{};try{let url=new URL(value);return{code:url.searchParams.get("code")??void 0,state:url.searchParams.get("state")??void 0}}catch{}if(value.includes("#")){let[code,state]=value.split("#",2);return{code,state}}if(value.includes("code=")){let params=new URLSearchParams(value);return{code:params.get("code")??void 0,state:params.get("state")??void 0}}return{code:value}}function decodeJwt(token){try{let parts=token.split(".");if(parts.length!==3)return null;let payload=parts[1]??"",decoded=atob(payload);return JSON.parse(decoded)}catch{return null}}async function fetchWithLoginCancellation(input,init){try{return await fetch(input,init)}catch(error){throw init.signal?.aborted?new Error("Login cancelled"):error}}async function readTokenResponse(response,operation){if(!response.ok){let text=await response.text().catch(()=>"");throw new Error(`OpenAI Codex token ${operation} failed (${response.status}): ${text||response.statusText}`)}let json=await response.json();if(!json?.access_token||!json.refresh_token||typeof json.expires_in!="number")throw new Error(`OpenAI Codex token ${operation} response missing fields: ${JSON.stringify(json)}`);return{access:json.access_token,refresh:json.refresh_token,expires:Date.now()+json.expires_in*1e3}}async function exchangeAuthorizationCode(code,verifier,redirectUri,signal){let response=await fetchWithLoginCancellation(TOKEN_URL,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"authorization_code",client_id:CLIENT_ID,code,code_verifier:verifier,redirect_uri:redirectUri}),signal});return readTokenResponse(response,"exchange")}async function refreshAccessToken(refreshToken,signal){let response;try{response=await fetch(TOKEN_URL,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded"},body:new URLSearchParams({grant_type:"refresh_token",refresh_token:refreshToken,client_id:CLIENT_ID}),signal})}catch(error){throw new Error(`OpenAI Codex token refresh error: ${error instanceof Error?error.message:String(error)}`)}return readTokenResponse(response,"refresh")}async function startOpenAICodexDeviceAuth(signal){let response=await fetchWithLoginCancellation(DEVICE_USER_CODE_URL,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({client_id:CLIENT_ID}),signal});if(!response.ok){if(response.status===404)throw new Error("OpenAI Codex device code login is not enabled for this server. Use browser login or verify the server URL.");let responseBody=await response.text().catch(()=>"");throw new Error(`OpenAI Codex device code request failed with status ${response.status}${responseBody?`: ${responseBody}`:""}`)}let json=await response.json(),intervalSeconds=typeof json?.interval=="string"?Number(json.interval.trim()):json?.interval;if(!json?.device_auth_id||!json.user_code||typeof intervalSeconds!="number"||!Number.isFinite(intervalSeconds)||intervalSeconds<0)throw new Error(`Invalid OpenAI Codex device code response: ${JSON.stringify(json)}`);return{deviceAuthId:json.device_auth_id,userCode:json.user_code,intervalSeconds}}async function pollOpenAICodexDeviceAuth(device,signal){return pollOAuthDeviceCodeFlow({intervalSeconds:device.intervalSeconds,expiresInSeconds:DEVICE_CODE_TIMEOUT_SECONDS,signal,poll:async()=>{let response=await fetchWithLoginCancellation(DEVICE_TOKEN_URL,{method:"POST",headers:{"Content-Type":"application/json"},body:JSON.stringify({device_auth_id:device.deviceAuthId,user_code:device.userCode}),signal});if(response.ok){let json=await response.json();return!json?.authorization_code||!json.code_verifier?{status:"failed",message:`Invalid OpenAI Codex device auth token response: ${JSON.stringify(json)}`}:{status:"complete",value:{authorizationCode:json.authorization_code,codeVerifier:json.code_verifier}}}if(response.status===403||response.status===404)return{status:"pending"};let responseBody=await response.text().catch(()=>""),errorCode;try{let error=JSON.parse(responseBody)?.error;errorCode=typeof error=="object"?error?.code:error}catch{}return errorCode==="deviceauth_authorization_pending"?{status:"pending"}:errorCode==="slow_down"?{status:"slow_down"}:{status:"failed",message:`OpenAI Codex device auth failed with status ${response.status}${responseBody?`: ${responseBody}`:""}`}}})}async function createAuthorizationFlow(originator="pi"){let{verifier,challenge}=await generatePKCE(),state=createState(),url=new URL(AUTHORIZE_URL);return url.searchParams.set("response_type","code"),url.searchParams.set("client_id",CLIENT_ID),url.searchParams.set("redirect_uri",REDIRECT_URI),url.searchParams.set("scope",SCOPE),url.searchParams.set("code_challenge",challenge),url.searchParams.set("code_challenge_method","S256"),url.searchParams.set("state",state),url.searchParams.set("id_token_add_organizations","true"),url.searchParams.set("codex_cli_simplified_flow","true"),url.searchParams.set("originator",originator),{verifier,state,url:url.toString()}}function startLocalOAuthServer(state){if(!_http)throw new Error("OpenAI Codex OAuth is only available in Node.js environments");let settleWait,waitForCodePromise=new Promise(resolve=>{let settled=!1;settleWait=value=>{settled||(settled=!0,resolve(value))}}),server=_http.createServer((req,res)=>{try{let url=new URL(req.url||"","http://localhost");if(url.pathname!=="/auth/callback"){res.statusCode=404,res.setHeader("Content-Type","text/html; charset=utf-8"),res.end(oauthErrorHtml("Callback route not found."));return}if(url.searchParams.get("state")!==state){res.statusCode=400,res.setHeader("Content-Type","text/html; charset=utf-8"),res.end(oauthErrorHtml("State mismatch."));return}let code=url.searchParams.get("code");if(!code){res.statusCode=400,res.setHeader("Content-Type","text/html; charset=utf-8"),res.end(oauthErrorHtml("Missing authorization code."));return}res.statusCode=200,res.setHeader("Content-Type","text/html; charset=utf-8"),res.end(oauthSuccessHtml("OpenAI authentication completed. You can close this window.")),settleWait?.({code})}catch{res.statusCode=500,res.setHeader("Content-Type","text/html; charset=utf-8"),res.end(oauthErrorHtml("Internal error while processing OAuth callback."))}});return new Promise(resolve=>{server.listen(1455,getCallbackHost(),()=>{resolve({close:()=>server.close(),cancelWait:()=>{settleWait?.(null)},waitForCode:()=>waitForCodePromise})}).on("error",_err=>{settleWait?.(null),resolve({close:()=>{try{server.close()}catch{}},cancelWait:()=>{},waitForCode:async()=>null})})})}function getAccountId(accessToken){let accountId=decodeJwt(accessToken)?.[JWT_CLAIM_PATH]?.chatgpt_account_id;return typeof accountId=="string"&&accountId.length>0?accountId:null}function credentialsFromToken(token){let accountId=getAccountId(token.access);if(!accountId)throw new Error("Failed to extract accountId from token");return{type:"oauth",access:token.access,refresh:token.refresh,expires:token.expires,accountId}}async function exchangeAuthorizationCodeForCredentials(code,verifier,redirectUri,signal){return credentialsFromToken(await exchangeAuthorizationCode(code,verifier,redirectUri,signal))}async function loginOpenAICodexDeviceCode(interaction){let device=await startOpenAICodexDeviceAuth(interaction.signal);interaction.notify({type:"device_code",userCode:device.userCode,verificationUri:DEVICE_VERIFICATION_URI,intervalSeconds:device.intervalSeconds,expiresInSeconds:DEVICE_CODE_TIMEOUT_SECONDS});let code=await pollOpenAICodexDeviceAuth(device,interaction.signal);return exchangeAuthorizationCodeForCredentials(code.authorizationCode,code.codeVerifier,DEVICE_REDIRECT_URI,interaction.signal)}async function loginOpenAICodex(interaction){let{verifier,state,url}=await createAuthorizationFlow(),server=await startLocalOAuthServer(state),manualAbort=new AbortController,onAbort=()=>server.cancelWait();interaction.signal.addEventListener("abort",onAbort,{once:!0}),interaction.signal.aborted&&onAbort();let code,manualCode,manualError;interaction.notify({type:"auth_url",url,instructions:"A browser window should open. Complete login to finish."});try{let manualPromise=interaction.prompt({type:"manual_code",message:"Complete login in your browser, or paste the authorization code / redirect URL here:",placeholder:REDIRECT_URI,signal:manualAbort.signal}).then(input=>{manualCode=input,server.cancelWait()}).catch(error=>{manualError=error instanceof Error?error:new Error(String(error)),server.cancelWait()}),result=await server.waitForCode();if(manualError)throw manualError;if(result?.code)code=result.code;else if(manualCode){let parsed=parseAuthorizationInput(manualCode);if(parsed.state&&parsed.state!==state)throw new Error("State mismatch");code=parsed.code}if(!code){if(await manualPromise,manualError)throw manualError;if(manualCode){let parsed=parseAuthorizationInput(manualCode);if(parsed.state&&parsed.state!==state)throw new Error("State mismatch");code=parsed.code}}if(!code)throw new Error("Missing authorization code");return exchangeAuthorizationCodeForCredentials(code,verifier,REDIRECT_URI,interaction.signal)}finally{interaction.signal.removeEventListener("abort",onAbort),manualAbort.abort(),server.close()}}async function refreshOpenAICodexToken(refreshToken,signal){return credentialsFromToken(await refreshAccessToken(refreshToken,signal))}var openaiCodexOAuth={name:"OpenAI (ChatGPT Plus/Pro)",isSubscription:!0,async login(interaction){let method=await interaction.prompt({type:"select",message:"Select OpenAI Codex login method:",options:[{id:OPENAI_CODEX_BROWSER_LOGIN_METHOD,label:"Browser login (default)"},{id:OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD,label:"Device code login (headless)"}]});if(method===OPENAI_CODEX_DEVICE_CODE_LOGIN_METHOD)return loginOpenAICodexDeviceCode(interaction);if(method!==OPENAI_CODEX_BROWSER_LOGIN_METHOD)throw new Error(`Unknown OpenAI Codex login method: ${method}`);return loginOpenAICodex(interaction)},refresh:(credential,signal)=>refreshOpenAICodexToken(credential.refresh,signal),async toAuth(credential){return{apiKey:credential.access}}};export{openaiCodexOAuth};
