@cortexkit/opencode-openai-auth 0.1.0
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.
- package/LICENSE +21 -0
- package/README.md +47 -0
- package/dist/config.d.ts +26 -0
- package/dist/dump.d.ts +18 -0
- package/dist/hosted-web-search.d.ts +5 -0
- package/dist/index-6z8w05g9.js +2 -0
- package/dist/index-xqe8xm96.js +2 -0
- package/dist/index.d.ts +32 -0
- package/dist/index.js +156 -0
- package/dist/logger.d.ts +1 -0
- package/dist/raw-ws-bun.d.ts +33 -0
- package/dist/raw-ws-node.d.ts +30 -0
- package/dist/raw-ws.d.ts +3 -0
- package/dist/response-stream-error.d.ts +3 -0
- package/dist/token-util-fs3z8kkp.js +1 -0
- package/dist/token-yyjm093c.js +1 -0
- package/dist/util/error.d.ts +1 -0
- package/dist/util/proxy-env.d.ts +4 -0
- package/dist/util/record.d.ts +1 -0
- package/dist/util/stable-json.d.ts +1 -0
- package/dist/util/uuid-v7.d.ts +1 -0
- package/dist/version.d.ts +1 -0
- package/dist/ws-pool.d.ts +38 -0
- package/dist/ws.d.ts +34 -0
- package/package.json +44 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Ex Machina
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
ADDED
|
@@ -0,0 +1,47 @@
|
|
|
1
|
+
# @cortexkit/opencode-openai-auth
|
|
2
|
+
|
|
3
|
+
ChatGPT Plus/Pro OAuth support for [OpenCode](https://opencode.ai).
|
|
4
|
+
|
|
5
|
+
This OpenCode plugin lets OpenCode talk to the OpenAI Codex backend using a ChatGPT Plus/Pro subscription instead of a pay-as-you-go API key. It rewrites OpenCode's outbound OpenAI requests into Codex's request shape, filters the model list to OAuth-eligible models, zeroes provider costs for those models, and adds a prompt-cache stabilizer.
|
|
6
|
+
|
|
7
|
+
The plugin registers the built-in `openai` provider id. OpenCode loads external plugins after its built-ins, so this package supersedes OpenCode's internal OpenAI auth hook without any change to your model configuration.
|
|
8
|
+
|
|
9
|
+
## Install
|
|
10
|
+
|
|
11
|
+
```json
|
|
12
|
+
{
|
|
13
|
+
"plugin": ["@cortexkit/opencode-openai-auth@0.1.0"]
|
|
14
|
+
}
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
Restart OpenCode after changing plugin config, then authenticate:
|
|
18
|
+
|
|
19
|
+
```text
|
|
20
|
+
/login openai
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Features
|
|
24
|
+
|
|
25
|
+
- ChatGPT Plus/Pro OAuth login (browser and headless device flows), plus a manual API-key fallback.
|
|
26
|
+
- Codex request rewriting for OAuth requests, with Codex identity parity.
|
|
27
|
+
- OAuth model filtering and zero-cost display.
|
|
28
|
+
- Prompt-cache stabilizer (`web_search`) that keeps tool-continuation requests on the backend's cached path (on by default).
|
|
29
|
+
- Optional OpenAI Responses WebSocket transport (HTTP is the default).
|
|
30
|
+
|
|
31
|
+
## Configuration
|
|
32
|
+
|
|
33
|
+
Settings resolve as environment variable → config file (`~/.config/opencode/openai-auth.json`) → default.
|
|
34
|
+
|
|
35
|
+
| Config field | Environment variable | Default | Purpose |
|
|
36
|
+
| --- | --- | --- | --- |
|
|
37
|
+
| `webSearch` | `CORTEXKIT_OPENAI_AUTH_NO_WEB_SEARCH` (set to disable) | `true` | Inject the `web_search` prompt-cache stabilizer. |
|
|
38
|
+
| `webSockets` | `CORTEXKIT_OPENAI_AUTH_WEBSOCKETS` | `false` | Use the Codex Responses WebSocket transport instead of HTTP. |
|
|
39
|
+
| `rawWebSocket` | `CORTEXKIT_OPENAI_AUTH_RAW_WS` | `false` | Use the hand-rolled raw TCP/TLS client with Codex-style incremental streaming. Bun uses `Bun.connect`; Node/OpenCode Desktop uses `node:net`/`node:tls`. |
|
|
40
|
+
| `dump` | `CORTEXKIT_OPENAI_AUTH_DUMP` | `false` | Dump final Codex request bodies for cache debugging. |
|
|
41
|
+
| `dumpDir` | `OPENCODE_OPENAI_AUTH_DUMP_DIR` | OS temp dir: `opencode-openai-auth-dumps` | Directory for request dump files. |
|
|
42
|
+
|
|
43
|
+
See the [repository README](https://github.com/cortexkit/openai-auth#readme) for transport differences and why `web_search` is needed.
|
|
44
|
+
|
|
45
|
+
## License
|
|
46
|
+
|
|
47
|
+
MIT
|
package/dist/config.d.ts
ADDED
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/** Shape of ~/.config/opencode/openai-auth.json (all fields optional). */
|
|
2
|
+
export interface OpenAIAuthConfig {
|
|
3
|
+
/** Inject the native web_search tool to keep the Codex prompt cache stable. Default true. */
|
|
4
|
+
webSearch?: boolean;
|
|
5
|
+
/** Use the WebSocket transport for /responses instead of plain HTTP. Default false. */
|
|
6
|
+
webSockets?: boolean;
|
|
7
|
+
/** Use the hand-rolled raw TCP/TLS WebSocket client (incremental streaming). Default false. */
|
|
8
|
+
rawWebSocket?: boolean;
|
|
9
|
+
/** Dump final Codex request bodies for cache debugging. Default false. */
|
|
10
|
+
dump?: boolean;
|
|
11
|
+
/** Directory for request dumps. Defaults to the OS temp directory. */
|
|
12
|
+
dumpDir?: string;
|
|
13
|
+
}
|
|
14
|
+
export interface ResolvedSettings {
|
|
15
|
+
webSearch: boolean;
|
|
16
|
+
webSockets: boolean;
|
|
17
|
+
rawWebSocket: boolean;
|
|
18
|
+
dump: boolean;
|
|
19
|
+
dumpDir: string;
|
|
20
|
+
}
|
|
21
|
+
export declare function getConfigDir(): string;
|
|
22
|
+
export declare function getConfigPath(): string;
|
|
23
|
+
/** Resolved settings, computed once per process (env + config are process-static). */
|
|
24
|
+
export declare function getSettings(): ResolvedSettings;
|
|
25
|
+
/** Test-only: drop the memoized settings so a later getSettings() re-reads env + config. */
|
|
26
|
+
export declare function resetSettingsForTest(): void;
|
package/dist/dump.d.ts
ADDED
|
@@ -0,0 +1,18 @@
|
|
|
1
|
+
export declare const DUMP_SESSION_HEADER = "x-cortexkit-openai-auth-dump-session";
|
|
2
|
+
type DumpHeaders = ConstructorParameters<typeof Headers>[0];
|
|
3
|
+
type DumpTransport = 'http' | 'websocket';
|
|
4
|
+
type DumpPhase = 'http' | 'prewarm' | 'main';
|
|
5
|
+
export declare function dumpCodexRequest(input: {
|
|
6
|
+
sessionID?: string | null;
|
|
7
|
+
transport: DumpTransport;
|
|
8
|
+
phase: DumpPhase;
|
|
9
|
+
bodyText: string;
|
|
10
|
+
url?: string;
|
|
11
|
+
method?: string;
|
|
12
|
+
headers?: DumpHeaders;
|
|
13
|
+
status?: number;
|
|
14
|
+
error?: string;
|
|
15
|
+
}): Promise<void>;
|
|
16
|
+
export declare function dumpDiagnostic(event: Record<string, unknown>): Promise<void>;
|
|
17
|
+
export declare function resetDumpStateForTest(): void;
|
|
18
|
+
export {};
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { type ToolDefinition } from '@opencode-ai/plugin';
|
|
2
|
+
export declare const HostedWebSearchTool: ToolDefinition;
|
|
3
|
+
export declare function translateHostedWebSearchEvent(event: Record<string, unknown>): Record<string, unknown> | undefined;
|
|
4
|
+
export declare function translateHostedWebSearchResponse(response: Response): Response;
|
|
5
|
+
export declare function rewriteHostedWebSearchReplay(body: Record<string, unknown>): boolean;
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{createRequire as g}from"node:module";var d=Object.defineProperty;var h=(b,a)=>()=>(a||b((a={exports:{}}).exports,a),a.exports);var e=(b)=>b;function f(b,a){this[b]=e.bind(null,a)}var i=(b,a)=>{for(var c in a)d(b,c,{get:a[c],enumerable:!0,configurable:!0,set:f.bind(a,c)})};var k=g(import.meta.url);
|
|
2
|
+
export{h as c,i as d,k as e};
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
import{c as Y,e as K}from"./index-6z8w05g9.js";var V=Y((rz,O)=>{var{defineProperty:J,getOwnPropertyDescriptor:r,getOwnPropertyNames:t}=Object,e=Object.prototype.hasOwnProperty,o=(z,B)=>{for(var F in B)J(z,F,{get:B[F],enumerable:!0})},zz=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of t(B))if(!e.call(z,G)&&G!==F)J(z,G,{get:()=>B[G],enumerable:!(H=r(B,G))||H.enumerable})}return z},Bz=(z)=>zz(J({},"__esModule",{value:!0}),z),M={};o(M,{VercelOidcTokenError:()=>j});O.exports=Bz(M);class j extends Error{constructor(z,B){super(z);this.name="VercelOidcTokenError",this.cause=B}toString(){if(this.cause)return`${this.name}: ${this.message}: ${this.cause}`;return`${this.name}: ${this.message}`}}});var C=Y((tz,x)=>{var{create:Fz,defineProperty:v,getOwnPropertyDescriptor:Gz,getOwnPropertyNames:Hz,getPrototypeOf:Kz}=Object,Qz=Object.prototype.hasOwnProperty,Wz=(z,B)=>{for(var F in B)v(z,F,{get:B[F],enumerable:!0})},S=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Hz(B))if(!Qz.call(z,G)&&G!==F)v(z,G,{get:()=>B[G],enumerable:!(H=Gz(B,G))||H.enumerable})}return z},N=(z,B,F)=>(F=z!=null?Fz(Kz(z)):{},S(B||!z||!z.__esModule?v(F,"default",{value:z,enumerable:!0}):F,z)),Xz=(z)=>S(v({},"__esModule",{value:!0}),z),E={};Wz(E,{findRootDir:()=>$z,getUserDataDir:()=>qz});x.exports=Xz(E);var Z=N(K("path")),Yz=N(K("fs")),A=N(K("os")),Zz=V();function $z(){try{let z=process.cwd();while(z!==Z.default.dirname(z)){let B=Z.default.join(z,".vercel");if(Yz.default.existsSync(B))return z;z=Z.default.dirname(z)}}catch(z){throw new Zz.VercelOidcTokenError("Token refresh only supported in node server environments")}return null}function qz(){if(process.env.XDG_DATA_HOME)return process.env.XDG_DATA_HOME;switch(A.default.platform()){case"darwin":return Z.default.join(A.default.homedir(),"Library/Application Support");case"linux":return Z.default.join(A.default.homedir(),".local/share");case"win32":if(process.env.LOCALAPPDATA)return process.env.LOCALAPPDATA;return null;default:return null}}});var c=Y((ez,g)=>{var{create:vz,defineProperty:b,getOwnPropertyDescriptor:bz,getOwnPropertyNames:Uz,getPrototypeOf:Lz}=Object,Jz=Object.prototype.hasOwnProperty,Vz=(z,B)=>{for(var F in B)b(z,F,{get:B[F],enumerable:!0})},y=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Uz(B))if(!Jz.call(z,G)&&G!==F)b(z,G,{get:()=>B[G],enumerable:!(H=bz(B,G))||H.enumerable})}return z},u=(z,B,F)=>(F=z!=null?vz(Lz(z)):{},y(B||!z||!z.__esModule?b(F,"default",{value:z,enumerable:!0}):F,z)),Az=(z)=>y(b({},"__esModule",{value:!0}),z),P={};Vz(P,{isValidAccessToken:()=>wz,readAuthConfig:()=>Rz,writeAuthConfig:()=>Iz});g.exports=Az(P);var $=u(K("fs")),l=u(K("path")),Nz=k();function h(){let z=(0,Nz.getVercelDataDir)();if(!z)throw Error(`Unable to find Vercel CLI data directory. Your platform: ${process.platform}. Supported: darwin, linux, win32.`);return l.join(z,"auth.json")}function Rz(){try{let z=h();if(!$.existsSync(z))return null;let B=$.readFileSync(z,"utf8");if(!B)return null;return JSON.parse(B)}catch(z){return null}}function Iz(z){let B=h(),F=l.dirname(B);if(!$.existsSync(F))$.mkdirSync(F,{mode:504,recursive:!0});$.writeFileSync(B,JSON.stringify(z,null,2),{mode:384})}function wz(z){if(!z.token)return!1;if(typeof z.expiresAt!=="number")return!0;let B=Math.floor(Date.now()/1000);return z.expiresAt>=B}});var p=Y((oz,d)=>{var{defineProperty:w,getOwnPropertyDescriptor:Dz,getOwnPropertyNames:Tz}=Object,Mz=Object.prototype.hasOwnProperty,jz=(z,B)=>{for(var F in B)w(z,F,{get:B[F],enumerable:!0})},Oz=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of Tz(B))if(!Mz.call(z,G)&&G!==F)w(z,G,{get:()=>B[G],enumerable:!(H=Dz(B,G))||H.enumerable})}return z},Sz=(z)=>Oz(w({},"__esModule",{value:!0}),z),i={};jz(i,{processTokenResponse:()=>uz,refreshTokenRequest:()=>yz});d.exports=Sz(i);var R=K("os"),Ez="https://vercel.com",xz="cl_HYyOPBNtFMfHhaUn9L4QPfTZz6TP47bp",f=`@vercel/oidc node-${process.version} ${(0,R.platform)()} (${(0,R.arch)()}) ${(0,R.hostname)()}`,I=null;async function Cz(){if(I)return I;let z=`${Ez}/.well-known/openid-configuration`,B=await fetch(z,{headers:{"user-agent":f}});if(!B.ok)throw Error("Failed to discover OAuth endpoints");let F=await B.json();if(!F||typeof F.token_endpoint!=="string")throw Error("Invalid OAuth discovery response");let H=F.token_endpoint;return I=H,H}async function yz(z){let B=await Cz();return await fetch(B,{method:"POST",headers:{"Content-Type":"application/x-www-form-urlencoded","user-agent":f},body:new URLSearchParams({client_id:xz,grant_type:"refresh_token",...z})})}async function uz(z){let B=await z.json();if(!z.ok){let F=typeof B==="object"&&B&&"error"in B?String(B.error):"Token refresh failed";return[Error(F)]}if(typeof B!=="object"||B===null)return[Error("Invalid token response")];if(typeof B.access_token!=="string")return[Error("Missing access_token in response")];if(B.token_type!=="Bearer")return[Error("Invalid token_type in response")];if(typeof B.expires_in!=="number")return[Error("Missing expires_in in response")];return[null,B]}});var k=Y((zB,n)=>{var{create:Pz,defineProperty:U,getOwnPropertyDescriptor:lz,getOwnPropertyNames:hz,getPrototypeOf:gz}=Object,cz=Object.prototype.hasOwnProperty,kz=(z,B)=>{for(var F in B)U(z,F,{get:B[F],enumerable:!0})},a=(z,B,F,H)=>{if(B&&typeof B==="object"||typeof B==="function"){for(let G of hz(B))if(!cz.call(z,G)&&G!==F)U(z,G,{get:()=>B[G],enumerable:!(H=lz(B,G))||H.enumerable})}return z},_=(z,B,F)=>(F=z!=null?Pz(gz(z)):{},a(B||!z||!z.__esModule?U(F,"default",{value:z,enumerable:!0}):F,z)),iz=(z)=>a(U({},"__esModule",{value:!0}),z),m={};kz(m,{assertVercelOidcTokenResponse:()=>D,findProjectInfo:()=>sz,getTokenPayload:()=>mz,getVercelCliToken:()=>dz,getVercelDataDir:()=>fz,getVercelOidcToken:()=>pz,isExpired:()=>nz,loadToken:()=>_z,saveToken:()=>az});n.exports=iz(m);var q=_(K("path")),Q=_(K("fs")),X=V(),L=C(),W=c(),s=p();function fz(){let B=(0,L.getUserDataDir)();if(!B)return null;return q.join(B,"com.vercel.cli")}async function dz(){let z=(0,W.readAuthConfig)();if(!z)return null;if((0,W.isValidAccessToken)(z))return z.token||null;if(!z.refreshToken)return(0,W.writeAuthConfig)({}),null;try{let B=await(0,s.refreshTokenRequest)({refresh_token:z.refreshToken}),[F,H]=await(0,s.processTokenResponse)(B);if(F||!H)return(0,W.writeAuthConfig)({}),null;let G={token:H.access_token,expiresAt:Math.floor(Date.now()/1000)+H.expires_in};if(H.refresh_token)G.refreshToken=H.refresh_token;return(0,W.writeAuthConfig)(G),G.token??null}catch(B){return(0,W.writeAuthConfig)({}),null}}async function pz(z,B,F){let H=`https://api.vercel.com/v1/projects/${B}/token?source=vercel-oidc-refresh${F?`&teamId=${F}`:""}`,G=await fetch(H,{method:"POST",headers:{Authorization:`Bearer ${z}`}});if(!G.ok)throw new X.VercelOidcTokenError(`Failed to refresh OIDC token: ${G.statusText}`);let T=await G.json();return D(T),T}function D(z){if(!z||typeof z!=="object")throw TypeError("Vercel OIDC token is malformed. Expected an object. Please run `vc env pull` and try again");if(!("token"in z)||typeof z.token!=="string")throw TypeError("Vercel OIDC token is malformed. Expected a string-valued token property. Please run `vc env pull` and try again")}function sz(){let z=(0,L.findRootDir)();if(!z)throw new X.VercelOidcTokenError("Unable to find project root directory. Have you linked your project with `vc link?`");let B=q.join(z,".vercel","project.json");if(!Q.existsSync(B))throw new X.VercelOidcTokenError("project.json not found, have you linked your project with `vc link?`");let F=JSON.parse(Q.readFileSync(B,"utf8"));if(typeof F.projectId!=="string"&&typeof F.orgId!=="string")throw TypeError("Expected a string-valued projectId property. Try running `vc link` to re-link your project.");return{projectId:F.projectId,teamId:F.orgId}}function az(z,B){let F=(0,L.getUserDataDir)();if(!F)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let H=q.join(F,"com.vercel.token",`${B}.json`),G=JSON.stringify(z);Q.mkdirSync(q.dirname(H),{mode:504,recursive:!0}),Q.writeFileSync(H,G),Q.chmodSync(H,432);return}function _z(z){let B=(0,L.getUserDataDir)();if(!B)throw new X.VercelOidcTokenError("Unable to find user data directory. Please reach out to Vercel support.");let F=q.join(B,"com.vercel.token",`${z}.json`);if(!Q.existsSync(F))return null;let H=JSON.parse(Q.readFileSync(F,"utf8"));return D(H),H}function mz(z){let B=z.split(".");if(B.length!==3)throw new X.VercelOidcTokenError("Invalid token. Please run `vc env pull` and try again");let F=B[1].replace(/-/g,"+").replace(/_/g,"/"),H=F.padEnd(F.length+(4-F.length%4)%4,"=");return JSON.parse(Buffer.from(H,"base64").toString("utf8"))}function nz(z){return z.exp*1000<Date.now()}});
|
|
2
|
+
export{V as a,k as b};
|
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,32 @@
|
|
|
1
|
+
import type { Hooks, Plugin, PluginInput } from '@opencode-ai/plugin';
|
|
2
|
+
export interface IdTokenClaims {
|
|
3
|
+
chatgpt_account_id?: string;
|
|
4
|
+
organizations?: Array<{
|
|
5
|
+
id: string;
|
|
6
|
+
}>;
|
|
7
|
+
email?: string;
|
|
8
|
+
'https://api.openai.com/auth'?: {
|
|
9
|
+
chatgpt_account_id?: string;
|
|
10
|
+
};
|
|
11
|
+
}
|
|
12
|
+
export declare function parseJwtClaims(token: string): IdTokenClaims | undefined;
|
|
13
|
+
export declare function extractAccountIdFromClaims(claims: IdTokenClaims): string | undefined;
|
|
14
|
+
export declare function extractAccountId(tokens: TokenResponse): string | undefined;
|
|
15
|
+
interface TokenResponse {
|
|
16
|
+
id_token: string;
|
|
17
|
+
access_token: string;
|
|
18
|
+
refresh_token: string;
|
|
19
|
+
expires_in?: number;
|
|
20
|
+
}
|
|
21
|
+
interface CodexAuthPluginOptions {
|
|
22
|
+
issuer?: string;
|
|
23
|
+
codexApiEndpoint?: string;
|
|
24
|
+
experimentalWebSockets?: boolean;
|
|
25
|
+
}
|
|
26
|
+
export declare function CodexAuthPlugin(input: PluginInput, options?: CodexAuthPluginOptions): Promise<Hooks>;
|
|
27
|
+
export declare const OpenAIAuthPlugin: Plugin;
|
|
28
|
+
declare const _default: {
|
|
29
|
+
id: string;
|
|
30
|
+
server: Plugin;
|
|
31
|
+
};
|
|
32
|
+
export default _default;
|